From 50e48eb202be45ac5f59b0b3eb31a969fa672d53 Mon Sep 17 00:00:00 2001 From: Project7 Date: Sun, 7 Jun 2026 21:59:27 +0000 Subject: [PATCH 1/3] [#494] Replace prompt copy with AI draft overlays --- app/lib/cuts.ts | 153 +++- app/lib/lettering-status.test.ts | 178 ++++- app/lib/lettering-status.ts | 70 +- app/web/components/CutListPanel.test.tsx | 174 +++-- app/web/components/CutListPanel.tsx | 278 +++++-- app/web/components/LetteringEditor.test.tsx | 696 ++++++++++++++---- app/web/components/LetteringEditor.tsx | 65 +- ...cut-DmVsiKji.js => export-cut-BqZI0-Rv.js} | 2 +- app/web/dist/assets/index-C43toXVm.js | 141 ++++ app/web/dist/assets/index-D3eZu5VE.js | 143 ---- app/web/dist/index.html | 2 +- 11 files changed, 1456 insertions(+), 446 deletions(-) rename app/web/dist/assets/{export-cut-DmVsiKji.js => export-cut-BqZI0-Rv.js} (98%) create mode 100644 app/web/dist/assets/index-C43toXVm.js delete mode 100644 app/web/dist/assets/index-D3eZu5VE.js diff --git a/app/lib/cuts.ts b/app/lib/cuts.ts index 2354c0b..0f824b5 100644 --- a/app/lib/cuts.ts +++ b/app/lib/cuts.ts @@ -1,8 +1,17 @@ import fs from "fs"; import path from "path"; -import { hasVisibleSpeechTail, CARTOON_BUBBLE_RENDERER_VERSION, type Overlay } from "./overlays"; +import { + hasVisibleSpeechTail, + CARTOON_BUBBLE_RENDERER_VERSION, + type Overlay, +} from "./overlays"; -export const SHOT_TYPES = ["wide", "medium", "close-up", "extreme-close-up"] as const; +export const SHOT_TYPES = [ + "wide", + "medium", + "close-up", + "extreme-close-up", +] as const; export type ShotType = (typeof SHOT_TYPES)[number]; export interface CutDialogue { @@ -19,6 +28,19 @@ export interface CutDialogue { */ export type CutKind = "image" | "text"; +/** + * AI draft lettering state (#494). `generated` means OWS created a first-pass + * overlay set from the cut script and it has not been user-tuned yet. `edited` + * means the writer has since adjusted or replaced that draft in the editor. + */ +export interface CutAiDraft { + status: "generated" | "edited"; + /** Signature of the generated overlay set, for edit-detection on save. */ + baseSig?: string; + generatedAt?: string; + updatedAt?: string; +} + export interface Cut { id: number; shotType: ShotType; @@ -41,6 +63,8 @@ export interface Cut { finalRendererVersion?: number; /** Panel kind (#350). Absent ⇒ "image" (backward-compatible). */ kind?: CutKind; + /** AI draft lettering state (#494). Optional and backward-compatible. */ + aiDraft?: CutAiDraft | null; /** Text-panel background color (CSS color), e.g. "#101820". Optional (#350). */ background?: string; /** Text-panel aspect ratio hint, e.g. "4:5". Optional (#350). */ @@ -89,7 +113,11 @@ export function cutNextAction( if (cut.cleanImagePath || isTextPanel(cut)) { return { key: "letter", label: "Letter this cut", opensEditor: true }; } - return { key: "add-art", label: "Add clean art for this cut", opensEditor: false }; + return { + key: "add-art", + label: "Add clean art for this cut", + opensEditor: false, + }; } /** @@ -115,7 +143,9 @@ export function staleTailedCutIds( cutsFile: Pick, currentVersion: number = CARTOON_BUBBLE_RENDERER_VERSION, ): number[] { - return cutsFile.cuts.filter((c) => isStaleTailedExport(c, currentVersion)).map((c) => c.id); + return cutsFile.cuts + .filter((c) => isStaleTailedExport(c, currentVersion)) + .map((c) => c.id); } /** Base canvas width for a text panel sized from its aspect ratio (#351). */ @@ -127,14 +157,19 @@ export const TEXT_PANEL_BASE_WIDTH = 800; * panel letters and exports at the SAME shape. Returns null for a missing or * malformed ratio; callers fall back to 800×600. */ -export function textPanelDimensions(aspectRatio: string | undefined): { width: number; height: number } | null { +export function textPanelDimensions( + aspectRatio: string | undefined, +): { width: number; height: number } | null { if (!aspectRatio) return null; const m = aspectRatio.match(/^\s*(\d+(?:\.\d+)?)\s*:\s*(\d+(?:\.\d+)?)\s*$/); if (!m) return null; const w = parseFloat(m[1]); const h = parseFloat(m[2]); if (!(w > 0) || !(h > 0)) return null; - return { width: TEXT_PANEL_BASE_WIDTH, height: Math.round((TEXT_PANEL_BASE_WIDTH * h) / w) }; + return { + width: TEXT_PANEL_BASE_WIDTH, + height: Math.round((TEXT_PANEL_BASE_WIDTH * h) / w), + }; } export interface CutsFile { @@ -170,7 +205,9 @@ export function createDefaultCut(id: number, _plotFile: string): Cut { } export function createCutsFile(plotFile: string, cutCount = 1): CutsFile { - const cuts = Array.from({ length: cutCount }, (_, i) => createDefaultCut(i + 1, plotFile)); + const cuts = Array.from({ length: cutCount }, (_, i) => + createDefaultCut(i + 1, plotFile), + ); return { version: 1, plotFile, cuts }; } @@ -178,7 +215,10 @@ function cutsFilePath(storyDir: string, plotFile: string): string { return path.join(storyDir, `${plotFile}.cuts.json`); } -export function readCutsFile(storyDir: string, plotFile: string): CutsFile | null { +export function readCutsFile( + storyDir: string, + plotFile: string, +): CutsFile | null { const filePath = cutsFilePath(storyDir, plotFile); if (!fs.existsSync(filePath)) return null; @@ -186,7 +226,9 @@ export function readCutsFile(storyDir: string, plotFile: string): CutsFile | nul try { raw = fs.readFileSync(filePath, "utf-8"); } catch (err) { - throw new Error(`Cannot read ${plotFile}.cuts.json: ${(err as Error).message}`); + throw new Error( + `Cannot read ${plotFile}.cuts.json: ${(err as Error).message}`, + ); } let data: unknown; @@ -204,12 +246,19 @@ export function readCutsFile(storyDir: string, plotFile: string): CutsFile | nul return data as CutsFile; } -export function writeCutsFile(storyDir: string, plotFile: string, cutsFile: CutsFile): void { +export function writeCutsFile( + storyDir: string, + plotFile: string, + cutsFile: CutsFile, +): void { const filePath = cutsFilePath(storyDir, plotFile); fs.writeFileSync(filePath, JSON.stringify(cutsFile, null, 2) + "\n"); } -export function validateCutsFile(data: unknown): { valid: boolean; error?: string } { +export function validateCutsFile(data: unknown): { + valid: boolean; + error?: string; +} { if (typeof data !== "object" || data === null || Array.isArray(data)) { return { valid: false, error: "Must be a JSON object" }; } @@ -254,7 +303,10 @@ export function validateCutsFile(data: unknown): { valid: boolean; error?: strin } for (let j = 0; j < (cut.characters as unknown[]).length; j++) { if (typeof (cut.characters as unknown[])[j] !== "string") { - return { valid: false, error: `Cut ${i} characters[${j}] must be a string` }; + return { + valid: false, + error: `Cut ${i} characters[${j}] must be a string`, + }; } } if (!Array.isArray(cut.dialogue)) { @@ -262,8 +314,16 @@ export function validateCutsFile(data: unknown): { valid: boolean; error?: strin } for (let j = 0; j < (cut.dialogue as unknown[]).length; j++) { const d = (cut.dialogue as Record[])[j]; - if (typeof d !== "object" || d === null || typeof d.speaker !== "string" || typeof d.text !== "string") { - return { valid: false, error: `Cut ${i} dialogue[${j}] must have speaker and text strings` }; + if ( + typeof d !== "object" || + d === null || + typeof d.speaker !== "string" || + typeof d.text !== "string" + ) { + return { + valid: false, + error: `Cut ${i} dialogue[${j}] must have speaker and text strings`, + }; } } if (typeof cut.narration !== "string") { @@ -272,10 +332,19 @@ export function validateCutsFile(data: unknown): { valid: boolean; error?: strin if (typeof cut.sfx !== "string") { return { valid: false, error: `Cut ${i} missing sfx` }; } - const nullableStrings = ["cleanImagePath", "finalImagePath", "exportedAt", "uploadedCid", "uploadedUrl"] as const; + const nullableStrings = [ + "cleanImagePath", + "finalImagePath", + "exportedAt", + "uploadedCid", + "uploadedUrl", + ] as const; for (const field of nullableStrings) { if (cut[field] !== null && typeof cut[field] !== "string") { - return { valid: false, error: `Cut ${i} ${field} must be a string or null` }; + return { + valid: false, + error: `Cut ${i} ${field} must be a string or null`, + }; } } if (cut.overlays !== undefined && !Array.isArray(cut.overlays)) { @@ -285,6 +354,48 @@ export function validateCutsFile(data: unknown): { valid: boolean; error?: strin if (cut.kind !== undefined && cut.kind !== "image" && cut.kind !== "text") { return { valid: false, error: `Cut ${i} kind must be "image" or "text"` }; } + if (cut.aiDraft !== undefined && cut.aiDraft !== null) { + if (typeof cut.aiDraft !== "object") { + return { + valid: false, + error: `Cut ${i} aiDraft must be an object or null`, + }; + } + const aiDraft = cut.aiDraft as Record; + if (aiDraft.status !== "generated" && aiDraft.status !== "edited") { + return { + valid: false, + error: `Cut ${i} aiDraft.status must be "generated" or "edited"`, + }; + } + if ( + aiDraft.baseSig !== undefined && + typeof aiDraft.baseSig !== "string" + ) { + return { + valid: false, + error: `Cut ${i} aiDraft.baseSig must be a string`, + }; + } + if ( + aiDraft.generatedAt !== undefined && + typeof aiDraft.generatedAt !== "string" + ) { + return { + valid: false, + error: `Cut ${i} aiDraft.generatedAt must be a string`, + }; + } + if ( + aiDraft.updatedAt !== undefined && + typeof aiDraft.updatedAt !== "string" + ) { + return { + valid: false, + error: `Cut ${i} aiDraft.updatedAt must be a string`, + }; + } + } if (cut.background !== undefined && typeof cut.background !== "string") { return { valid: false, error: `Cut ${i} background must be a string` }; } @@ -293,8 +404,14 @@ export function validateCutsFile(data: unknown): { valid: boolean; error?: strin } // Bubble-renderer version stamp (#381) — optional, backward-compatible // (absent ⇒ pre-versioning final image). - if (cut.finalRendererVersion !== undefined && typeof cut.finalRendererVersion !== "number") { - return { valid: false, error: `Cut ${i} finalRendererVersion must be a number` }; + if ( + cut.finalRendererVersion !== undefined && + typeof cut.finalRendererVersion !== "number" + ) { + return { + valid: false, + error: `Cut ${i} finalRendererVersion must be a number`, + }; } } diff --git a/app/lib/lettering-status.test.ts b/app/lib/lettering-status.test.ts index 69b9374..70d6cfb 100644 --- a/app/lib/lettering-status.test.ts +++ b/app/lib/lettering-status.test.ts @@ -1,9 +1,22 @@ import { describe, it, expect } from "vitest"; -import { cutLetteringChecklist, cutScriptLines, overlaysSignature, isExportStale } from "./lettering-status"; +import { + buildDraftOverlays, + cutLetteringChecklist, + cutScriptLines, + overlaysSignature, + isExportStale, +} from "./lettering-status"; import type { Overlay } from "./overlays"; const ov = (over: Partial = {}): Overlay => ({ - id: "o1", type: "speech", x: 0.1, y: 0.1, width: 0.2, height: 0.1, text: "Hi", ...over, + id: "o1", + type: "speech", + x: 0.1, + y: 0.1, + width: 0.2, + height: 0.1, + text: "Hi", + ...over, }); describe("cutLetteringChecklist (#336)", () => { @@ -22,7 +35,17 @@ describe("cutLetteringChecklist (#336)", () => { const c = cutLetteringChecklist({ cleanImagePath: "c.webp", dialogue: [{ speaker: "Mira", text: "Hi" }], - overlays: [{ id: "o1", type: "speech", x: 0, y: 0, width: 0.2, height: 0.1, text: "Hi" }], + overlays: [ + { + id: "o1", + type: "speech", + x: 0, + y: 0, + width: 0.2, + height: 0.1, + text: "Hi", + }, + ], finalImagePath: "f.webp", exportedAt: "2026-01-01", uploadedUrl: "https://ipfs/Qm", @@ -37,34 +60,62 @@ describe("cutLetteringChecklist (#336)", () => { }); it("treats narration or SFX as script text, and exportedAt or finalImagePath as exported", () => { - expect(cutLetteringChecklist({ narration: "Later..." }).hasScriptText).toBe(true); + expect(cutLetteringChecklist({ narration: "Later..." }).hasScriptText).toBe( + true, + ); expect(cutLetteringChecklist({ sfx: "BOOM" }).hasScriptText).toBe(true); - expect(cutLetteringChecklist({ exportedAt: "2026-01-01" }).exported).toBe(true); - expect(cutLetteringChecklist({ finalImagePath: "f.webp" }).exported).toBe(true); + expect(cutLetteringChecklist({ exportedAt: "2026-01-01" }).exported).toBe( + true, + ); + expect(cutLetteringChecklist({ finalImagePath: "f.webp" }).exported).toBe( + true, + ); expect(cutLetteringChecklist({ uploadedCid: "Qm" }).uploaded).toBe(true); }); it("ignores whitespace-only narration/SFX", () => { - expect(cutLetteringChecklist({ narration: " ", sfx: " " }).hasScriptText).toBe(false); + expect( + cutLetteringChecklist({ narration: " ", sfx: " " }).hasScriptText, + ).toBe(false); }); }); describe("cutScriptLines (#336)", () => { it("flattens dialogue, narration and SFX into insertable lines in order", () => { const lines = cutScriptLines({ - dialogue: [{ speaker: "Mira", text: "We're here." }, { speaker: "Jin", text: "Finally." }], + dialogue: [ + { speaker: "Mira", text: "We're here." }, + { speaker: "Jin", text: "Finally." }, + ], narration: "Dawn broke.", sfx: "BANG", }); - expect(lines.map((l) => l.type)).toEqual(["speech", "speech", "narration", "sfx"]); - expect(lines[0]).toEqual({ type: "speech", speaker: "Mira", text: "We're here.", key: "speech-0" }); - expect(lines[2]).toEqual({ type: "narration", text: "Dawn broke.", key: "narration" }); + expect(lines.map((l) => l.type)).toEqual([ + "speech", + "speech", + "narration", + "sfx", + ]); + expect(lines[0]).toEqual({ + type: "speech", + speaker: "Mira", + text: "We're here.", + key: "speech-0", + }); + expect(lines[2]).toEqual({ + type: "narration", + text: "Dawn broke.", + key: "narration", + }); expect(lines[3]).toEqual({ type: "sfx", text: "BANG", key: "sfx" }); }); it("skips empty pieces (no blank script lines)", () => { const lines = cutScriptLines({ - dialogue: [{ speaker: "A", text: "" }, { speaker: "B", text: "hi" }], + dialogue: [ + { speaker: "A", text: "" }, + { speaker: "B", text: "hi" }, + ], narration: " ", }); expect(lines).toHaveLength(1); @@ -76,10 +127,43 @@ describe("cutScriptLines (#336)", () => { }); }); +describe("buildDraftOverlays (#494)", () => { + it("creates editable overlays from the cut script in order", () => { + const overlays = buildDraftOverlays({ + dialogue: [{ speaker: "Mira", text: "We're here." }], + narration: "Dawn broke.", + sfx: "BANG", + }); + expect(overlays).toHaveLength(3); + expect(overlays[0]).toMatchObject({ + type: "speech", + speaker: "Mira", + text: "We're here.", + }); + expect(overlays[1]).toMatchObject({ + type: "narration", + text: "Dawn broke.", + }); + expect(overlays[2]).toMatchObject({ + type: "sfx", + text: "BANG", + }); + expect(overlays[0].width).toBeGreaterThan(0.2); + expect(overlays[0].height).toBeGreaterThan(0.1); + }); + + it("returns an empty list when the cut has no script text", () => { + expect(buildDraftOverlays({})).toEqual([]); + }); +}); + describe("cutLetteringChecklist staleExport (#336, re1)", () => { const exportedCut = { - cleanImagePath: "c.webp", finalImagePath: "f.webp", exportedAt: "2026-01-01", - uploadedUrl: "https://ipfs/Qm", overlays: [ov()], + cleanImagePath: "c.webp", + finalImagePath: "f.webp", + exportedAt: "2026-01-01", + uploadedUrl: "https://ipfs/Qm", + overlays: [ov()], }; it("reports exported/uploaded done when not stale", () => { const c = cutLetteringChecklist(exportedCut); @@ -96,30 +180,78 @@ describe("cutLetteringChecklist staleExport (#336, re1)", () => { describe("overlaysSignature (#336)", () => { it("is equal for identical overlays and changes on any rendered-field edit", () => { expect(overlaysSignature([ov()])).toBe(overlaysSignature([ov()])); - expect(overlaysSignature([ov({ text: "Hi" })])).not.toBe(overlaysSignature([ov({ text: "Bye" })])); - expect(overlaysSignature([ov({ x: 0.1 })])).not.toBe(overlaysSignature([ov({ x: 0.5 })])); + expect(overlaysSignature([ov({ text: "Hi" })])).not.toBe( + overlaysSignature([ov({ text: "Bye" })]), + ); + expect(overlaysSignature([ov({ x: 0.1 })])).not.toBe( + overlaysSignature([ov({ x: 0.5 })]), + ); // A different id alone (same geometry/text) does not count as an edit. - expect(overlaysSignature([ov({ id: "a" })])).toBe(overlaysSignature([ov({ id: "b" })])); + expect(overlaysSignature([ov({ id: "a" })])).toBe( + overlaysSignature([ov({ id: "b" })]), + ); }); }); describe("isExportStale (#336, re1)", () => { const sig = (overlays: Overlay[]) => overlaysSignature(overlays); it("is false when the cut was never exported/uploaded", () => { - expect(isExportStale({ exported: false, uploaded: false, baselineSig: sig([ov()]), current: [ov({ x: 0.9 })] })).toBe(false); + expect( + isExportStale({ + exported: false, + uploaded: false, + baselineSig: sig([ov()]), + current: [ov({ x: 0.9 })], + }), + ).toBe(false); }); it("is false when overlays are unchanged since export", () => { - expect(isExportStale({ exported: true, uploaded: true, baselineSig: sig([ov()]), current: [ov()] })).toBe(false); + expect( + isExportStale({ + exported: true, + uploaded: true, + baselineSig: sig([ov()]), + current: [ov()], + }), + ).toBe(false); }); it("is true when overlays changed after export/upload", () => { - expect(isExportStale({ exported: true, uploaded: false, baselineSig: sig([ov()]), current: [ov({ text: "edited" })] })).toBe(true); - expect(isExportStale({ exported: false, uploaded: true, baselineSig: sig([ov()]), current: [ov({ x: 0.4 })] })).toBe(true); + expect( + isExportStale({ + exported: true, + uploaded: false, + baselineSig: sig([ov()]), + current: [ov({ text: "edited" })], + }), + ).toBe(true); + expect( + isExportStale({ + exported: false, + uploaded: true, + baselineSig: sig([ov()]), + current: [ov({ x: 0.4 })], + }), + ).toBe(true); }); it("clears once the baseline is advanced to the current overlays (re-export)", () => { const edited = [ov({ text: "edited" })]; // Stale against the old baseline... - expect(isExportStale({ exported: true, uploaded: true, baselineSig: sig([ov()]), current: edited })).toBe(true); + expect( + isExportStale({ + exported: true, + uploaded: true, + baselineSig: sig([ov()]), + current: edited, + }), + ).toBe(true); // ...not stale once the baseline matches what was re-exported. - expect(isExportStale({ exported: true, uploaded: true, baselineSig: sig(edited), current: edited })).toBe(false); + expect( + isExportStale({ + exported: true, + uploaded: true, + baselineSig: sig(edited), + current: edited, + }), + ).toBe(false); }); }); diff --git a/app/lib/lettering-status.ts b/app/lib/lettering-status.ts index 0caae26..6502723 100644 --- a/app/lib/lettering-status.ts +++ b/app/lib/lettering-status.ts @@ -3,7 +3,12 @@ // tested and shared between the editor checklist and the insert-from-script // panel. None of this changes the export model or publish readiness rules. -import type { Overlay } from "./overlays"; +import { + comfortableOverlaySize, + createOverlay, + type Overlay, + type OverlayType, +} from "./overlays"; /** The cut fields the lettering guidance reads (a structural subset of Cut). */ export interface LetteringCut { @@ -16,6 +21,7 @@ export interface LetteringCut { sfx?: string; dialogue?: { speaker: string; text: string }[]; overlays?: Overlay[]; + kind?: "image" | "text"; } export interface LetteringChecklist { @@ -45,12 +51,16 @@ export function cutLetteringChecklist( cut: LetteringCut, opts: { staleExport?: boolean } = {}, ): LetteringChecklist { - const exported = !opts.staleExport && (!!cut.finalImagePath || !!cut.exportedAt); - const uploaded = !opts.staleExport && (!!cut.uploadedUrl || !!cut.uploadedCid); + const exported = + !opts.staleExport && (!!cut.finalImagePath || !!cut.exportedAt); + const uploaded = + !opts.staleExport && (!!cut.uploadedUrl || !!cut.uploadedCid); return { hasCleanImage: !!cut.cleanImagePath, hasScriptText: - (cut.dialogue?.length ?? 0) > 0 || !!cut.narration?.trim() || !!cut.sfx?.trim(), + (cut.dialogue?.length ?? 0) > 0 || + !!cut.narration?.trim() || + !!cut.sfx?.trim(), bubblesPlaced: cut.overlays?.length ?? 0, exported, uploaded, @@ -120,14 +130,62 @@ export function cutScriptLines(cut: LetteringCut): ScriptLine[] { const lines: ScriptLine[] = []; (cut.dialogue ?? []).forEach((d, i) => { if (d?.text?.trim()) { - lines.push({ type: "speech", speaker: d.speaker, text: d.text.trim(), key: `speech-${i}` }); + lines.push({ + type: "speech", + speaker: d.speaker, + text: d.text.trim(), + key: `speech-${i}`, + }); } }); if (cut.narration?.trim()) { - lines.push({ type: "narration", text: cut.narration.trim(), key: "narration" }); + lines.push({ + type: "narration", + text: cut.narration.trim(), + key: "narration", + }); } if (cut.sfx?.trim()) { lines.push({ type: "sfx", text: cut.sfx.trim(), key: "sfx" }); } return lines; } + +function draftAnchorFor( + type: OverlayType, + index: number, + total: number, +): { x: number; y: number } { + if (type === "narration") + return { x: 0.08, y: 0.05 + Math.min(index, 2) * 0.18 }; + if (type === "sfx") { + const col = index % 2; + const row = Math.floor(index / 2); + return { x: col === 0 ? 0.1 : 0.62, y: 0.68 + row * 0.12 }; + } + const row = Math.floor(index / 2); + const left = index % 2 === 0; + const y = 0.08 + row * Math.max(0.15, Math.min(0.22, total > 4 ? 0.16 : 0.2)); + return { x: left ? 0.05 : 0.45, y }; +} + +/** + * Create a first-pass editable overlay set from the cut script (#494). Pure, + * deterministic, and intentionally approximate: these are draft bubble/caption + * positions for the writer to review in the focused editor, not export-ready + * layout. Empty script pieces produce no overlays. + */ +export function buildDraftOverlays(cut: LetteringCut): Overlay[] { + const lines = cutScriptLines(cut); + return lines.map((line, index) => { + const { x, y } = draftAnchorFor(line.type, index, lines.length); + const overlay = createOverlay(line.type, x, y); + const comfortable = comfortableOverlaySize(line.type, x, y); + return { + ...overlay, + ...comfortable, + text: line.text, + ...(line.type === "speech" ? { speaker: line.speaker ?? "" } : {}), + }; + }); +} diff --git a/app/web/components/CutListPanel.test.tsx b/app/web/components/CutListPanel.test.tsx index e241bad..3e5d9b4 100644 --- a/app/web/components/CutListPanel.test.tsx +++ b/app/web/components/CutListPanel.test.tsx @@ -1989,7 +1989,7 @@ describe("CutListPanel asset diagnostics + Refresh assets (#427)", () => { // #441: a PNG clean image is a friendly conversion step, not a red error. it("shows a Convert artwork step for PNG clean images instead of red unsupported-extension errors", async () => { - const fn = vi.fn((url: string) => { + const fn = vi.fn((url: string, opts?: RequestInit) => { if (url.includes("/asset-diagnostics")) { return Promise.resolve({ ok: true, @@ -2235,9 +2235,7 @@ describe("CutListPanel asset diagnostics + Refresh assets (#427)", () => { ); }); - // #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 () => { + it("drafts overlays from full review and opens the focused editor for tuning (#494)", async () => { const overlay = { id: "o1", type: "speech", @@ -2248,6 +2246,22 @@ describe("CutListPanel asset diagnostics + Refresh assets (#427)", () => { text: "Hi", speaker: "Sera", }; + let cuts = [ + makeCut({ + id: 1, + shotType: "close-up", + cleanImagePath: "assets/genesis/cut-01-clean.webp", + dialogue: [{ speaker: "Sera", text: "그거 따라한 거야" }], + description: "Close shot", + }), + makeCut({ + id: 2, + shotType: "wide", + cleanImagePath: "assets/genesis/cut-02-clean.webp", + overlays: [overlay], + description: "Wide shot", + }), + ]; const fn = vi.fn((url: string) => { if (url.includes("/asset-diagnostics")) { return Promise.resolve({ @@ -2288,31 +2302,20 @@ describe("CutListPanel asset diagnostics + Refresh assets (#427)", () => { status: 200, json: () => Promise.resolve({ detected: [], stale: [] }), }); + if (url.endsWith("/cuts/genesis") && opts?.method === "PUT") { + cuts = JSON.parse(String(opts.body)).cuts; + return Promise.resolve({ + ok: true, + status: 200, + json: () => Promise.resolve({ ok: true }), + }); + } if (url.includes("/cuts/")) return Promise.resolve({ ok: true, status: 200, json: () => - Promise.resolve({ - version: 1, - plotFile: "genesis", - cuts: [ - makeCut({ - id: 1, - shotType: "close-up", - cleanImagePath: "assets/genesis/cut-01-clean.webp", - dialogue: [{ speaker: "Sera", text: "그거 따라한 거야" }], - description: "Close shot", - }), - makeCut({ - id: 2, - shotType: "wide", - cleanImagePath: "assets/genesis/cut-02-clean.webp", - overlays: [overlay], - description: "Wide shot", - }), - ], - }), + Promise.resolve({ version: 1, plotFile: "genesis", cuts }), }); return Promise.resolve({ ok: true, @@ -2329,42 +2332,131 @@ describe("CutListPanel asset diagnostics + Refresh assets (#427)", () => { ); await screen.findByTestId("cut-list-panel"); - // 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")); + ).toHaveTextContent("No draft"); + expect(screen.getByTestId("ai-draft-1")).toBeInTheDocument(); + + fireEvent.click(screen.getByTestId("ai-draft-1")); expect( await screen.findByTestId("focused-lettering-editor"), ).toBeInTheDocument(); expect(screen.getByTestId("ai-draft-current-target")).toHaveTextContent( - "Cut 01", + "AI draft ready", ); - - // 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); + expect(cuts[0].overlays.length).toBeGreaterThan(0); + expect(cuts[0].aiDraft?.status).toBe("generated"); fireEvent.click(screen.getByTestId("cancel-lettering-btn")); - // Cut 2 (bubbles already placed): status "Needs review" + a draft-saved state. + expect( + await screen.findByTestId("lettering-review-state-1"), + ).toHaveTextContent("Draft ready"); expect(screen.getByTestId("cut-card-status-2")).toHaveTextContent( "Needs review", ); expect(screen.getByTestId("lettering-review-state-2")).toHaveTextContent( - "Draft saved", + "User-edited", ); expect(screen.getByTestId("add-bubbles-2")).toHaveTextContent( "Review lettering", ); }); + it("does not overwrite existing overlays with AI draft without explicit confirmation (#494)", async () => { + const confirmSpy = vi.spyOn(window, "confirm").mockReturnValue(false); + let cuts = [ + makeCut({ + id: 1, + cleanImagePath: "assets/plot-01/cut-01-clean.webp", + dialogue: [{ speaker: "Mira", text: "We move now." }], + overlays: [ + { + id: "existing", + type: "speech", + x: 0.1, + y: 0.1, + width: 0.2, + height: 0.1, + text: "Existing", + }, + ], + }), + ]; + const fn = vi.fn((url: string, opts?: RequestInit) => { + if (url.includes("/asset-diagnostics")) { + return Promise.resolve({ + ok: true, + status: 200, + json: () => + Promise.resolve({ + diagnostics: [ + { + cutId: 1, + kind: "image", + state: "clean-ready", + issue: null, + convertiblePng: null, + }, + ], + summary: { + planned: 0, + needsConversion: 0, + missing: 0, + cleanReady: 1, + 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/plot-01") && opts?.method === "PUT") { + cuts = JSON.parse(String(opts.body)).cuts; + return Promise.resolve({ + ok: true, + status: 200, + json: () => Promise.resolve({ ok: true }), + }); + } + if (url.includes("/cuts/plot-01")) + return Promise.resolve({ + ok: true, + status: 200, + json: () => + Promise.resolve({ version: 1, plotFile: "plot-01", cuts }), + }); + return Promise.resolve({ + ok: true, + status: 200, + json: () => Promise.resolve({}), + }); + }); + + render( + , + ); + + await screen.findByTestId("cut-list-panel"); + fireEvent.click(screen.getByTestId("ai-draft-1")); + + expect(confirmSpy).toHaveBeenCalledTimes(1); + expect( + fn.mock.calls.some( + (call) => + String(call[0]).endsWith("/cuts/plot-01") && + (call[1] as RequestInit | undefined)?.method === "PUT", + ), + ).toBe(false); + expect(cuts[0].overlays[0].text).toBe("Existing"); + confirmSpy.mockRestore(); + }); + it("enters focused lettering mode, exposes the work-area toggle, and restores review state on close (#493)", async () => { const onFocusedLetteringModeChange = vi.fn(); const onWorkspaceVisibleChange = vi.fn(); @@ -2536,7 +2628,7 @@ describe("CutListPanel asset diagnostics + Refresh assets (#427)", () => { expect(screen.getByTestId("lettering-review-board")).toBeInTheDocument(), ); expect(screen.getByTestId("lettering-review-state-3")).toHaveTextContent( - "Draft saved", + "User-edited", ); }); diff --git a/app/web/components/CutListPanel.tsx b/app/web/components/CutListPanel.tsx index 5a80fdc..9408ac6 100644 --- a/app/web/components/CutListPanel.tsx +++ b/app/web/components/CutListPanel.tsx @@ -23,6 +23,12 @@ import { summarizeAssetDiagnostics, type CutAssetDiagnostic, } from "@app-lib/cut-asset-diagnostics"; +import { + buildDraftOverlays, + overlaysSignature, + cutScriptLines, +} from "@app-lib/lettering-status"; +import type { CutAiDraft } from "@app-lib/cuts"; interface Overlay { id: string; @@ -67,6 +73,7 @@ interface Cut { uploadedUrl: string | null; overlays: Overlay[]; kind?: "image" | "text"; + aiDraft?: CutAiDraft | null; background?: string; aspectRatio?: string; finalRendererVersion?: number; @@ -106,6 +113,22 @@ interface CutListPanelProps { type CutStatus = "missing" | "clean" | "lettered" | "uploaded" | "text"; +function canDraftLettering(cut: Cut): boolean { + return ( + (!!cut.cleanImagePath || isTextPanel(cut)) && cutScriptLines(cut).length > 0 + ); +} + +function buildAiDraftState(overlays: Overlay[]): CutAiDraft { + const now = new Date().toISOString(); + return { + status: "generated", + baseSig: overlaysSignature(overlays), + generatedAt: now, + updatedAt: now, + }; +} + function getCutStatus(cut: Cut): CutStatus { if (cut.uploadedCid) return "uploaded"; if (cut.finalImagePath || cut.exportedAt) return "lettered"; @@ -197,12 +220,26 @@ function letteringReviewState(cut: Cut): { return { label: "Exported", detail: "Ready to upload", tone: "green" }; } if ((cut.overlays?.length ?? 0) > 0) { + if (cut.aiDraft?.status === "generated") { + return { + label: "Draft ready", + detail: `${cut.overlays.length} AI-drafted overlay${cut.overlays.length === 1 ? "" : "s"} ready to review`, + tone: "amber", + }; + } return { - label: "Draft saved", - detail: `${cut.overlays.length} overlay${cut.overlays.length === 1 ? "" : "s"} placed`, + label: "User-edited", + detail: `${cut.overlays.length} overlay${cut.overlays.length === 1 ? "" : "s"} adjusted and ready to review`, tone: "amber", }; } + if (canDraftLettering(cut)) { + return { + label: "No draft", + detail: "Draft with AI or place bubbles manually", + tone: "muted", + }; + } if (isTextPanel(cut)) { return { label: "Between-scene card", @@ -236,6 +273,8 @@ function CutRow({ detectedLocalClean, onSyncClean, syncing, + onAiDraft, + aiDrafting, staleMessages, onRepairStale, repairing, @@ -255,6 +294,8 @@ function CutRow({ detectedLocalClean: boolean; onSyncClean: () => void; syncing: boolean; + onAiDraft: () => void; + aiDrafting: boolean; staleMessages: string[]; onRepairStale: () => void; repairing: boolean; @@ -358,6 +399,15 @@ function CutRow({ !cut.uploadedUrl && !hasStale && !needsConversion; + const canAiDraft = + !hasStale && + !needsConversion && + !cut.finalImagePath && + !cut.uploadedCid && + !cut.uploadedUrl && + canDraftLettering(cut); + const aiDraftLabel = + (cut.overlays?.length ?? 0) > 0 ? "Re-draft with AI" : "AI draft lettering"; const primary: { label: string; onClick: () => void; testid: string } | null = board.key === "convert" @@ -447,13 +497,25 @@ function CutRow({
{atLetteringStage ? ( - + <> + + {canAiDraft && ( + + )} + ) : primary ? ( + )} )}
-
- {boardSummary.cuts} cuts · {boardSummary.artwork} artwork found ·{" "} - {boardSummary.converted} converted · {boardSummary.lettered} lettered - · {boardSummary.uploaded} uploaded -
{/* Lower-level / manual controls, collapsed by default so the board stays focused on per-cut actions (#440). The guided Finish flow + per-cut @@ -1748,6 +1940,10 @@ export function CutListPanel({ detectedLocalClean={detected.has(cut.id)} onSyncClean={syncCleanImages} syncing={syncing} + onAiDraft={() => { + void draftCutWithAi(cut.id, { openEditor: true }); + }} + aiDrafting={aiDraftingCutId === cut.id} staleMessages={staleByCut.get(cut.id) ?? []} onRepairStale={repairStalePaths} repairing={repairing} diff --git a/app/web/components/LetteringEditor.test.tsx b/app/web/components/LetteringEditor.test.tsx index a355616..a8e6903 100644 --- a/app/web/components/LetteringEditor.test.tsx +++ b/app/web/components/LetteringEditor.test.tsx @@ -1,18 +1,45 @@ import { describe, it, expect, vi, afterEach, beforeAll } from "vitest"; -import { render, screen, cleanup, fireEvent, act, waitFor } from "@testing-library/react"; +import { + render, + screen, + cleanup, + fireEvent, + act, + waitFor, +} from "@testing-library/react"; import { LetteringEditor } from "./LetteringEditor"; -import { installObjectUrlStub, makeAssetAuthFetch, MOCK_BLOB_URL } from "./asset-test-utils"; +import { + installObjectUrlStub, + makeAssetAuthFetch, + MOCK_BLOB_URL, +} from "./asset-test-utils"; import { textPanelDimensions } from "@app-lib/cuts"; beforeAll(() => { installObjectUrlStub(); global.ResizeObserver = class { callback: ResizeObserverCallback; - constructor(callback: ResizeObserverCallback) { this.callback = callback; } + constructor(callback: ResizeObserverCallback) { + this.callback = callback; + } observe(target: Element) { - Object.defineProperty(target, "clientWidth", { value: 400, configurable: true }); - Object.defineProperty(target, "clientHeight", { value: 300, configurable: true }); - this.callback([{ contentRect: { width: 400, height: 300 }, target } as unknown as ResizeObserverEntry], this); + Object.defineProperty(target, "clientWidth", { + value: 400, + configurable: true, + }); + Object.defineProperty(target, "clientHeight", { + value: 300, + configurable: true, + }); + this.callback( + [ + { + contentRect: { width: 400, height: 300 }, + target, + } as unknown as ResizeObserverEntry, + ], + this, + ); } unobserve() {} disconnect() {} @@ -50,9 +77,17 @@ afterEach(cleanup); // load event that drives overlay positioning. async function simulateImageLoad() { const img = await screen.findByRole("img"); - Object.defineProperty(img, "naturalWidth", { value: 800, configurable: true }); - Object.defineProperty(img, "naturalHeight", { value: 600, configurable: true }); - act(() => { fireEvent.load(img); }); + Object.defineProperty(img, "naturalWidth", { + value: 800, + configurable: true, + }); + Object.defineProperty(img, "naturalHeight", { + value: 600, + configurable: true, + }); + act(() => { + fireEvent.load(img); + }); return img; } @@ -83,8 +118,13 @@ describe("LetteringEditor", () => { ); const img = await screen.findByAltText("Cut 1 clean"); expect(img).toHaveAttribute("src", MOCK_BLOB_URL); - expect(img).not.toHaveAttribute("src", "/api/stories/story/asset/plot-01/cut-01-clean.webp"); - expect(authFetch).toHaveBeenCalledWith("/api/stories/story/asset/plot-01/cut-01-clean.webp"); + expect(img).not.toHaveAttribute( + "src", + "/api/stories/story/asset/plot-01/cut-01-clean.webp", + ); + expect(authFetch).toHaveBeenCalledWith( + "/api/stories/story/asset/plot-01/cut-01-clean.webp", + ); }); // #452: a clean-image cut opens a clear lettering workspace, and a narration @@ -94,7 +134,10 @@ describe("LetteringEditor", () => { render( { fireEvent.click(screen.getByTestId("script-insert-narration")); expect(screen.getByTestId("overlay-count")).toHaveTextContent("1 overlays"); // The inspector opens with the text and a one-click Fit control. - expect(screen.getByTestId("inspector-text")).toHaveValue("A long narration line that would overflow a tiny default box on an ordinary panel."); + expect(screen.getByTestId("inspector-text")).toHaveValue( + "A long narration line that would overflow a tiny default box on an ordinary panel.", + ); const fit = screen.getByTestId("inspector-fit-text"); expect(fit).toBeInTheDocument(); @@ -137,7 +182,10 @@ describe("LetteringEditor", () => { const overlay: Overlay = { id: "narr-1", type: "narration", - x: 0.1, y: 0.1, width: 0.8, height: 0.2, + x: 0.1, + y: 0.1, + width: 0.8, + height: 0.2, text: "The story begins...", }; render( @@ -158,7 +206,11 @@ describe("LetteringEditor", () => { render( { // ready, the body wraps into its own line span. Wait for that re-render so // the body-text assertion is deterministic (was a flaky getByText race). await waitFor(() => - expect(screen.getByTestId("overlay-text-test-overlay-1")).toHaveAttribute("data-fonts-ready", "true"), + expect(screen.getByTestId("overlay-text-test-overlay-1")).toHaveAttribute( + "data-fonts-ready", + "true", + ), ); expect(screen.getByText("Hello!")).toBeInTheDocument(); }); @@ -213,8 +268,12 @@ describe("LetteringEditor", () => { const overlay: Overlay = { id: "tail-speech", type: "speech", - x: 0.1, y: 0.2, width: 0.25, height: 0.12, - text: "Hi", speaker: "Mira", + x: 0.1, + y: 0.2, + width: 0.25, + height: 0.12, + text: "Hi", + speaker: "Mira", tailAnchor: { x: 0.5, y: 1.2 }, }; render( @@ -243,7 +302,9 @@ describe("LetteringEditor", () => { // The default {0.5, 1.2} tail points straight down: its tip Y sits below the // bubble's bottom edge, so the integrated path must reach past the bottom. const bubbleBottom = 0.2 * 300 + 0.12 * 300; // oy + oh in display px (image 800x600 → 400x300) - const ys = Array.from(d.matchAll(/[ML] [\d.-]+ ([\d.-]+)/g)).map((m) => parseFloat(m[1])); + const ys = Array.from(d.matchAll(/[ML] [\d.-]+ ([\d.-]+)/g)).map((m) => + parseFloat(m[1]), + ); expect(Math.max(...ys)).toBeGreaterThan(bubbleBottom); // tail tip extends below the body // No separate stroked tail polygon — that was the old seamed rendering. expect(document.querySelector("polygon")).toBeNull(); @@ -255,8 +316,12 @@ describe("LetteringEditor", () => { const overlay: Overlay = { id: "no-tail-speech", type: "speech", - x: 0.1, y: 0.2, width: 0.25, height: 0.12, - text: "Hi", speaker: "Mira", + x: 0.1, + y: 0.2, + width: 0.25, + height: 0.12, + text: "Hi", + speaker: "Mira", tailAnchor: { x: 0.5, y: 0.5 }, // tip inside the bubble → no tail }; render( @@ -277,7 +342,9 @@ describe("LetteringEditor", () => { const d = balloon.getAttribute("d") ?? ""; // Bounded by the body rect — no point extends past the bottom edge. const bubbleBottom = 0.2 * 300 + 0.12 * 300; - const ys = Array.from(d.matchAll(/[ML] [\d.-]+ ([\d.-]+)/g)).map((m) => parseFloat(m[1])); + const ys = Array.from(d.matchAll(/[ML] [\d.-]+ ([\d.-]+)/g)).map((m) => + parseFloat(m[1]), + ); expect(Math.max(...ys)).toBeLessThanOrEqual(bubbleBottom + 0.01); }); @@ -285,7 +352,10 @@ describe("LetteringEditor", () => { const overlay: Overlay = { id: "narr-tail", type: "narration", - x: 0.1, y: 0.2, width: 0.25, height: 0.12, + x: 0.1, + y: 0.2, + width: 0.25, + height: 0.12, text: "Later...", }; render( @@ -393,14 +463,28 @@ describe("LetteringEditor", () => { // Simulate a wide image in a tall container (will letterbox top/bottom) const img = await screen.findByRole("img"); - Object.defineProperty(img, "naturalWidth", { value: 800, configurable: true }); - Object.defineProperty(img, "naturalHeight", { value: 200, configurable: true }); + Object.defineProperty(img, "naturalWidth", { + value: 800, + configurable: true, + }); + Object.defineProperty(img, "naturalHeight", { + value: 200, + configurable: true, + }); const container = screen.getByTestId("editor-surface"); - Object.defineProperty(container, "clientWidth", { value: 400, configurable: true }); - Object.defineProperty(container, "clientHeight", { value: 400, configurable: true }); - - act(() => { fireEvent.load(img); }); + Object.defineProperty(container, "clientWidth", { + value: 400, + configurable: true, + }); + Object.defineProperty(container, "clientHeight", { + value: 400, + configurable: true, + }); + + act(() => { + fireEvent.load(img); + }); // With 800x200 image in 400x400 container: // scale = min(400/800, 400/200) = min(0.5, 2) = 0.5 @@ -414,7 +498,14 @@ describe("LetteringEditor", () => { it("adds overlay via toolbar button", async () => { render( - , + , ); await simulateImageLoad(); @@ -425,12 +516,21 @@ describe("LetteringEditor", () => { it("edits overlay text via inspector", async () => { render( - , + , ); await simulateImageLoad(); fireEvent.click(screen.getByTestId("add-narration")); - const overlayEl = document.querySelector("[data-testid^='overlay-overlay-']")!; + const overlayEl = document.querySelector( + "[data-testid^='overlay-overlay-']", + )!; fireEvent.click(overlayEl); const textInput = screen.getByTestId("inspector-text"); @@ -441,14 +541,23 @@ describe("LetteringEditor", () => { it("deletes overlay with double-click confirmation", async () => { render( - , + , ); await simulateImageLoad(); fireEvent.click(screen.getByTestId("add-sfx")); expect(screen.getByTestId("overlay-count")).toHaveTextContent("1 overlays"); - const overlayEl = document.querySelector("[data-testid^='overlay-overlay-']")!; + const overlayEl = document.querySelector( + "[data-testid^='overlay-overlay-']", + )!; fireEvent.click(overlayEl); const deleteBtn = screen.getByTestId("delete-overlay"); @@ -463,7 +572,14 @@ describe("LetteringEditor", () => { it("saves overlays via onSave callback", async () => { const onSave = vi.fn(); render( - , + , ); await simulateImageLoad(); @@ -480,7 +596,20 @@ describe("LetteringEditor", () => { render( { fireEvent.click(screen.getByTestId("overlay-manual")); fireEvent.click(screen.getByTestId("inspector-text-manual")); - fireEvent.change(screen.getByTestId("inspector-font-scale"), { target: { value: "4.5" } }); - fireEvent.change(screen.getByTestId("inspector-line-height"), { target: { value: "1.35" } }); - fireEvent.change(screen.getByTestId("inspector-speaker-scale"), { target: { value: "0.9" } }); - fireEvent.change(screen.getByTestId("inspector-padding-x"), { target: { value: "12" } }); - fireEvent.change(screen.getByTestId("inspector-padding-y"), { target: { value: "10" } }); - fireEvent.change(screen.getByTestId("inspector-corner-radius"), { target: { value: "25" } }); + fireEvent.change(screen.getByTestId("inspector-font-scale"), { + target: { value: "4.5" }, + }); + fireEvent.change(screen.getByTestId("inspector-line-height"), { + target: { value: "1.35" }, + }); + fireEvent.change(screen.getByTestId("inspector-speaker-scale"), { + target: { value: "0.9" }, + }); + fireEvent.change(screen.getByTestId("inspector-padding-x"), { + target: { value: "12" }, + }); + fireEvent.change(screen.getByTestId("inspector-padding-y"), { + target: { value: "10" }, + }); + fireEvent.change(screen.getByTestId("inspector-corner-radius"), { + target: { value: "25" }, + }); fireEvent.click(screen.getByText("Save")); - expect(onSave).toHaveBeenCalledWith(expect.arrayContaining([ - expect.objectContaining({ - id: "manual", - textStyle: expect.objectContaining({ - mode: "manual", - fontScale: 0.045, - fontWeight: 400, - lineHeightFactor: 1.35, - speakerScale: 0.9, - }), - bubbleStyle: expect.objectContaining({ - paddingX: 0.12, - paddingY: 0.1, - cornerRadius: 0.25, + expect(onSave).toHaveBeenCalledWith( + expect.arrayContaining([ + expect.objectContaining({ + id: "manual", + textStyle: expect.objectContaining({ + mode: "manual", + fontScale: 0.045, + fontWeight: 400, + lineHeightFactor: 1.35, + speakerScale: 0.9, + }), + bubbleStyle: expect.objectContaining({ + paddingX: 0.12, + paddingY: 0.1, + cornerRadius: 0.25, + }), }), - }), - ])); + ]), + ); }); it("applies the manual bold text style in the preview", async () => { @@ -523,17 +666,19 @@ describe("LetteringEditor", () => { { ); await simulateImageLoad(); await waitFor(() => - expect(screen.getByTestId("overlay-text-bold")).toHaveAttribute("data-fonts-ready", "true"), + expect(screen.getByTestId("overlay-text-bold")).toHaveAttribute( + "data-fonts-ready", + "true", + ), ); - const body = screen.getByTestId("overlay-text-bold").querySelector(".text-\\[\\#1a1a1a\\]") as HTMLElement | null; + const body = screen + .getByTestId("overlay-text-bold") + .querySelector(".text-\\[\\#1a1a1a\\]") as HTMLElement | null; expect(body?.style.fontWeight).toBe("700"); }); @@ -610,8 +760,12 @@ describe("LetteringEditor", () => { fireEvent.click(screen.getByTestId("overlay-tail-preset")); fireEvent.click(screen.getByTestId("inspector-tail-left")); - expect((screen.getByTestId("inspector-tail-x") as HTMLInputElement).value).toBe("-0.2"); - expect((screen.getByTestId("inspector-tail-y") as HTMLInputElement).value).toBe("0.5"); + expect( + (screen.getByTestId("inspector-tail-x") as HTMLInputElement).value, + ).toBe("-0.2"); + expect( + (screen.getByTestId("inspector-tail-y") as HTMLInputElement).value, + ).toBe("0.5"); }); it("uses Korean font when language is Korean", async () => { @@ -641,7 +795,9 @@ describe("LetteringEditor", () => { await simulateImageLoad(); fireEvent.click(screen.getByTestId("overlay-test-kr-font")); - expect(screen.getByTestId("inspector-font")).toHaveTextContent("Noto Sans KR"); + expect(screen.getByTestId("inspector-font")).toHaveTextContent( + "Noto Sans KR", + ); }); it("calls onClose when Cancel button is clicked", () => { @@ -659,14 +815,20 @@ describe("LetteringEditor", () => { expect(onClose).toHaveBeenCalled(); }); - it("offers scoped AI draft assistance and can return to review after Save (#488)", async () => { + it("shows generated AI draft guidance and can return to review after Save (#494)", 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")); + expect(screen.getByTestId("focused-lettering-editor")).toHaveTextContent( + "Focused lettering editor", + ); + expect(screen.getByTestId("ai-draft-current-target")).toHaveTextContent( + "AI draft ready", + ); fireEvent.click(screen.getByTestId("add-speech")); fireEvent.click(screen.getByTestId("save-lettering-btn")); @@ -690,11 +855,25 @@ describe("LetteringEditor", () => { // (shared layout with the export), not a single truncated label. it("renders wrapped multi-line bubble text in the preview (WYSIWYG)", async () => { const authFetch = makeAssetAuthFetch(); - const longText = "the quick brown fox jumps over the lazy dog and keeps on running through"; + const longText = + "the quick brown fox jumps over the lazy dog and keeps on running through"; render( { await simulateImageLoad(); // The exact (canvas-measured) layout only renders once fonts are ready. await waitFor(() => - expect(screen.getByTestId("overlay-text-ov1")).toHaveAttribute("data-fonts-ready", "true"), + expect(screen.getByTestId("overlay-text-ov1")).toHaveAttribute( + "data-fonts-ready", + "true", + ), ); const textBox = screen.getByTestId("overlay-text-ov1"); - const lines = Array.from(textBox.querySelectorAll("span.block")).map((s) => s.textContent); + const lines = Array.from(textBox.querySelectorAll("span.block")).map( + (s) => s.textContent, + ); expect(lines.length).toBeGreaterThan(1); // wrapped, not one line expect(lines.join(" ")).toBe(longText); // no words lost across the wrapped lines }); @@ -718,20 +902,37 @@ describe("LetteringEditor", () => { it("defers the exact preview layout until fonts are ready, then recomputes", async () => { // Control font readiness: ensureFontsReady awaits document.fonts.load. let resolveLoad: (v: unknown) => void = () => {}; - const loadPromise = new Promise((r) => { resolveLoad = r; }); + const loadPromise = new Promise((r) => { + resolveLoad = r; + }); const fontsStub = { load: vi.fn(() => loadPromise), check: vi.fn(() => false), ready: Promise.resolve(), }; const original = Object.getOwnPropertyDescriptor(document, "fonts"); - Object.defineProperty(document, "fonts", { value: fontsStub, configurable: true }); + Object.defineProperty(document, "fonts", { + value: fontsStub, + configurable: true, + }); try { const authFetch = makeAssetAuthFetch(); render( { expect(fontsStub.load).toHaveBeenCalled(); // export's readiness signal used // Fonts become ready → preview recomputes the exact layout. - await act(async () => { resolveLoad([{}]); await Promise.resolve(); }); + await act(async () => { + resolveLoad([{}]); + await Promise.resolve(); + }); await waitFor(() => - expect(screen.getByTestId("overlay-text-ovf")).toHaveAttribute("data-fonts-ready", "true"), + expect(screen.getByTestId("overlay-text-ovf")).toHaveAttribute( + "data-fonts-ready", + "true", + ), ); - expect(screen.getByTestId("overlay-text-ovf").querySelectorAll("span.block").length).toBeGreaterThan(1); + expect( + screen.getByTestId("overlay-text-ovf").querySelectorAll("span.block") + .length, + ).toBeGreaterThan(1); } finally { if (original) Object.defineProperty(document, "fonts", original); else Reflect.deleteProperty(document, "fonts"); @@ -764,14 +974,25 @@ describe("LetteringEditor", () => { render( , ); - expect(await screen.findByTestId("overlay-repair-note")).toBeInTheDocument(); + expect( + await screen.findByTestId("overlay-repair-note"), + ).toBeInTheDocument(); // Repaired (not dropped) → still counted as one overlay. expect(screen.getByTestId("overlay-count")).toHaveTextContent("1 overlays"); }); @@ -781,7 +1002,11 @@ describe("LetteringEditor", () => { render( { render( { await screen.findByTestId("overlay-repair-note"); fireEvent.click(screen.getByTestId("export-btn")); // Clear, blocking error; the reduced overlay set is neither saved nor exported. - await screen.findByText(/cannot be exported — re-place it or discard it first/); + await screen.findByText( + /cannot be exported — re-place it or discard it first/, + ); expect(onSave).not.toHaveBeenCalled(); }); @@ -822,7 +1053,11 @@ describe("LetteringEditor", () => { render( { await screen.findByTestId("discard-invalid-overlays"); fireEvent.click(screen.getByTestId("discard-invalid-overlays")); // Note flips to the discarded state; the export guard no longer blocks. - await waitFor(() => expect(screen.getByTestId("overlay-repair-note")).toHaveTextContent(/Discarded/)); + await waitFor(() => + expect(screen.getByTestId("overlay-repair-note")).toHaveTextContent( + /Discarded/, + ), + ); fireEvent.click(screen.getByTestId("export-btn")); await waitFor(() => expect(onSave).toHaveBeenCalled()); }); @@ -842,8 +1081,26 @@ describe("LetteringEditor", () => { // without blocking export (overlap can be intentional). it("warns when two bubbles overlap, naming the cut and overlay indexes", async () => { const overlays: Overlay[] = [ - { id: "ov-a", type: "speech", x: 0.1, y: 0.1, width: 0.3, height: 0.2, text: "Good news! We are short one", speaker: "Boss" }, - { id: "ov-b", type: "speech", x: 0.2, y: 0.15, width: 0.3, height: 0.2, text: "I am not applying for a boyfriend.", speaker: "Mei" }, + { + id: "ov-a", + type: "speech", + x: 0.1, + y: 0.1, + width: 0.3, + height: 0.2, + text: "Good news! We are short one", + speaker: "Boss", + }, + { + id: "ov-b", + type: "speech", + x: 0.2, + y: 0.15, + width: 0.3, + height: 0.2, + text: "I am not applying for a boyfriend.", + speaker: "Mei", + }, ]; render( { it("does not warn when bubbles do not overlap", async () => { const overlays: Overlay[] = [ - { id: "ov-a", type: "speech", x: 0.0, y: 0.0, width: 0.25, height: 0.15, text: "Hi", speaker: "A" }, - { id: "ov-b", type: "speech", x: 0.6, y: 0.6, width: 0.25, height: 0.15, text: "Bye", speaker: "B" }, + { + id: "ov-a", + type: "speech", + x: 0.0, + y: 0.0, + width: 0.25, + height: 0.15, + text: "Hi", + speaker: "A", + }, + { + id: "ov-b", + type: "speech", + x: 0.6, + y: 0.6, + width: 0.25, + height: 0.15, + text: "Bye", + speaker: "B", + }, ]; render( { />, ); await simulateImageLoad(); - expect(screen.queryByTestId("overlay-overlap-warning")).not.toBeInTheDocument(); + expect( + screen.queryByTestId("overlay-overlap-warning"), + ).not.toBeInTheDocument(); }); it("the overlap warning is non-blocking — export still proceeds", async () => { const onSave = vi.fn().mockResolvedValue(undefined); const overlays: Overlay[] = [ - { id: "ov-a", type: "speech", x: 0.1, y: 0.1, width: 0.3, height: 0.2, text: "front", speaker: "A" }, - { id: "ov-b", type: "speech", x: 0.2, y: 0.15, width: 0.3, height: 0.2, text: "back", speaker: "B" }, + { + id: "ov-a", + type: "speech", + x: 0.1, + y: 0.1, + width: 0.3, + height: 0.2, + text: "front", + speaker: "A", + }, + { + id: "ov-b", + type: "speech", + x: 0.2, + y: 0.15, + width: 0.3, + height: 0.2, + text: "back", + speaker: "B", + }, ]; render( { it("clears the overlap warning once the bubbles are separated (live)", async () => { const overlays: Overlay[] = [ - { id: "ov-a", type: "speech", x: 0.1, y: 0.1, width: 0.3, height: 0.2, text: "front", speaker: "A" }, - { id: "ov-b", type: "speech", x: 0.2, y: 0.15, width: 0.3, height: 0.2, text: "back", speaker: "B" }, + { + id: "ov-a", + type: "speech", + x: 0.1, + y: 0.1, + width: 0.3, + height: 0.2, + text: "front", + speaker: "A", + }, + { + id: "ov-b", + type: "speech", + x: 0.2, + y: 0.15, + width: 0.3, + height: 0.2, + text: "back", + speaker: "B", + }, ]; render( { const del = screen.getByTestId("delete-overlay"); fireEvent.click(del); // arms confirmation fireEvent.click(del); // confirms delete - await waitFor(() => expect(screen.queryByTestId("overlay-overlap-warning")).not.toBeInTheDocument()); + await waitFor(() => + expect( + screen.queryByTestId("overlay-overlap-warning"), + ).not.toBeInTheDocument(), + ); }); // #336: insert dialogue/narration/SFX from cuts.json straight into a prefilled @@ -935,7 +1252,11 @@ describe("LetteringEditor", () => { render( { // Clicking a dialogue line adds a speech overlay carrying that text/speaker. fireEvent.click(screen.getByTestId("script-insert-speech-0")); expect(screen.getByTestId("overlay-count")).toHaveTextContent("1 overlays"); - const speakerInput = screen.getByTestId("inspector-speaker") as HTMLInputElement; + const speakerInput = screen.getByTestId( + "inspector-speaker", + ) as HTMLInputElement; expect(speakerInput.value).toBe("Mira"); - expect((screen.getByTestId("inspector-text") as HTMLTextAreaElement).value).toBe("We're here at last."); + expect( + (screen.getByTestId("inspector-text") as HTMLTextAreaElement).value, + ).toBe("We're here at last."); // Narration is insertable too. fireEvent.click(screen.getByTestId("script-insert-narration")); @@ -966,8 +1291,12 @@ describe("LetteringEditor", () => { const overlay: Overlay = { id: "oob", type: "speech", - x: 0.9, y: 0.2, width: 0.25, height: 0.12, // x + width = 1.15 > 1 → clipped - text: "Edge", speaker: "Mira", + x: 0.9, + y: 0.2, + width: 0.25, + height: 0.12, // x + width = 1.15 > 1 → clipped + text: "Edge", + speaker: "Mira", tailAnchor: { x: 0.5, y: 1.2 }, }; render( @@ -984,17 +1313,30 @@ describe("LetteringEditor", () => { const warning = screen.getByTestId("lettering-export-warning"); expect(warning).toHaveTextContent(/outside image/i); - expect(screen.getByTestId("overlay-oob")).toHaveAttribute("data-warning", "true"); + expect(screen.getByTestId("overlay-oob")).toHaveAttribute( + "data-warning", + "true", + ); }); it("shows the per-cut lettering checklist reflecting cut progress", async () => { const overlay: Overlay = { - id: "ck", type: "speech", x: 0.1, y: 0.2, width: 0.25, height: 0.12, text: "Hi", speaker: "Mira", + id: "ck", + type: "speech", + x: 0.1, + y: 0.2, + width: 0.25, + height: 0.12, + text: "Hi", + speaker: "Mira", }; render( { await simulateImageLoad(); // makeCut sets a cleanImagePath; dialogue + a placed overlay are present, but // nothing is exported/uploaded yet. - expect(screen.getByTestId("lettering-check-clean-image")).toHaveAttribute("data-done", "true"); - expect(screen.getByTestId("lettering-check-script-text")).toHaveAttribute("data-done", "true"); - expect(screen.getByTestId("lettering-check-bubbles")).toHaveAttribute("data-done", "true"); - expect(screen.getByTestId("lettering-check-exported")).toHaveAttribute("data-done", "false"); - expect(screen.getByTestId("lettering-check-uploaded")).toHaveAttribute("data-done", "false"); + expect(screen.getByTestId("lettering-check-clean-image")).toHaveAttribute( + "data-done", + "true", + ); + expect(screen.getByTestId("lettering-check-script-text")).toHaveAttribute( + "data-done", + "true", + ); + expect(screen.getByTestId("lettering-check-bubbles")).toHaveAttribute( + "data-done", + "true", + ); + expect(screen.getByTestId("lettering-check-exported")).toHaveAttribute( + "data-done", + "false", + ); + expect(screen.getByTestId("lettering-check-uploaded")).toHaveAttribute( + "data-done", + "false", + ); }); // #336 (re1): editing bubbles after an export/upload must invalidate them — the // checklist can't keep reporting "Final exported"/"Uploaded" for a stale image. it("marks export/upload stale after overlays are edited post-export", async () => { const overlay: Overlay = { - id: "stale", type: "speech", x: 0.1, y: 0.2, width: 0.25, height: 0.12, text: "Hi", speaker: "Mira", + id: "stale", + type: "speech", + x: 0.1, + y: 0.2, + width: 0.25, + height: 0.12, + text: "Hi", + speaker: "Mira", tailAnchor: { x: 0.5, y: 1.2 }, }; render( @@ -1036,19 +1400,37 @@ describe("LetteringEditor", () => { await simulateImageLoad(); // On open (no edits) the recorded export/upload count as done, no warning. - expect(screen.getByTestId("lettering-check-exported")).toHaveAttribute("data-done", "true"); - expect(screen.getByTestId("lettering-check-uploaded")).toHaveAttribute("data-done", "true"); - expect(screen.queryByTestId("lettering-stale-export-warning")).not.toBeInTheDocument(); + expect(screen.getByTestId("lettering-check-exported")).toHaveAttribute( + "data-done", + "true", + ); + expect(screen.getByTestId("lettering-check-uploaded")).toHaveAttribute( + "data-done", + "true", + ); + expect( + screen.queryByTestId("lettering-stale-export-warning"), + ).not.toBeInTheDocument(); // Edit the bubble text → the prior export/upload no longer match the screen. fireEvent.click(screen.getByTestId("overlay-stale")); - fireEvent.change(screen.getByTestId("inspector-text"), { target: { value: "Changed line" } }); + fireEvent.change(screen.getByTestId("inspector-text"), { + target: { value: "Changed line" }, + }); await waitFor(() => - expect(screen.getByTestId("lettering-stale-export-warning")).toBeInTheDocument(), + expect( + screen.getByTestId("lettering-stale-export-warning"), + ).toBeInTheDocument(), + ); + expect(screen.getByTestId("lettering-check-exported")).toHaveAttribute( + "data-done", + "false", + ); + expect(screen.getByTestId("lettering-check-uploaded")).toHaveAttribute( + "data-done", + "false", ); - expect(screen.getByTestId("lettering-check-exported")).toHaveAttribute("data-done", "false"); - expect(screen.getByTestId("lettering-check-uploaded")).toHaveAttribute("data-done", "false"); }); // #336 (re1): the lifecycle that regressed lives in handleExport/React state — @@ -1056,12 +1438,23 @@ describe("LetteringEditor", () => { // SAME open editor, with export-cut mocked so the export succeeds in jsdom. it("clears the stale-export warning after a successful re-export in the same editor session", async () => { vi.doMock("./export-cut", () => ({ - exportCut: vi.fn().mockResolvedValue(new Blob([new Uint8Array(10)], { type: "image/webp" })), + exportCut: vi + .fn() + .mockResolvedValue( + new Blob([new Uint8Array(10)], { type: "image/webp" }), + ), ensureFontsReady: vi.fn().mockResolvedValue({ ready: true, missing: [] }), })); try { const overlay: Overlay = { - id: "re", type: "speech", x: 0.1, y: 0.2, width: 0.25, height: 0.12, text: "Hi", speaker: "Mira", + id: "re", + type: "speech", + x: 0.1, + y: 0.2, + width: 0.25, + height: 0.12, + text: "Hi", + speaker: "Mira", tailAnchor: { x: 0.5, y: 1.2 }, }; render( @@ -1084,16 +1477,37 @@ describe("LetteringEditor", () => { // Edit a bubble → export goes stale. fireEvent.click(screen.getByTestId("overlay-re")); - fireEvent.change(screen.getByTestId("inspector-text"), { target: { value: "Changed line" } }); - await waitFor(() => expect(screen.getByTestId("lettering-stale-export-warning")).toBeInTheDocument()); - expect(screen.getByTestId("lettering-check-exported")).toHaveAttribute("data-done", "false"); + fireEvent.change(screen.getByTestId("inspector-text"), { + target: { value: "Changed line" }, + }); + await waitFor(() => + expect( + screen.getByTestId("lettering-stale-export-warning"), + ).toBeInTheDocument(), + ); + expect(screen.getByTestId("lettering-check-exported")).toHaveAttribute( + "data-done", + "false", + ); // Re-export in the same session → handleExport advances the baseline, so // the warning clears and the checklist steps return to done. - await act(async () => { fireEvent.click(screen.getByTestId("export-btn")); }); - await waitFor(() => expect(screen.queryByTestId("lettering-stale-export-warning")).not.toBeInTheDocument()); - expect(screen.getByTestId("lettering-check-exported")).toHaveAttribute("data-done", "true"); - expect(screen.getByTestId("lettering-check-uploaded")).toHaveAttribute("data-done", "true"); + await act(async () => { + fireEvent.click(screen.getByTestId("export-btn")); + }); + await waitFor(() => + expect( + screen.queryByTestId("lettering-stale-export-warning"), + ).not.toBeInTheDocument(), + ); + expect(screen.getByTestId("lettering-check-exported")).toHaveAttribute( + "data-done", + "true", + ); + expect(screen.getByTestId("lettering-check-uploaded")).toHaveAttribute( + "data-done", + "true", + ); } finally { vi.doUnmock("./export-cut"); } @@ -1107,7 +1521,13 @@ describe("LetteringEditor", () => { render( void | Promise; + onSave: ( + overlays: Overlay[], + aiDraft?: CutAiDraft | null, + ) => void | Promise; onClose: () => void; onExported?: () => void; language?: string; @@ -222,7 +224,6 @@ export function LetteringEditor({ 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, @@ -486,22 +487,24 @@ export function LetteringEditor({ const handleSave = useCallback(async () => { setSaveError(null); try { - await onSave(overlays); + const currentSig = overlaysSignature(overlays); + const nextAiDraft = + cut.aiDraft?.status === "generated" && + currentSig !== (cut.aiDraft.baseSig ?? "") + ? { + ...cut.aiDraft, + status: "edited" as const, + updatedAt: new Date().toISOString(), + } + : (cut.aiDraft ?? undefined); + await onSave(overlays, nextAiDraft ?? null); 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]); + }, [overlays, onSave, onClose, returnOnSave, cut.aiDraft]); const handleExport = useCallback(async () => { // Block export when the cut plan contained overlays that could not be placed @@ -1172,26 +1175,20 @@ export function LetteringEditor({ {/* Inspector panel */}
-
-

- AI draft assist -

-

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

- -
+

+ AI draft ready +

+

+ These first-pass overlays came from the cut script. Review and + tune them here before exporting the final panel. +

+
+ )} {/* 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-DmVsiKji.js b/app/web/dist/assets/export-cut-BqZI0-Rv.js similarity index 98% rename from app/web/dist/assets/export-cut-DmVsiKji.js rename to app/web/dist/assets/export-cut-BqZI0-Rv.js index 2a7f724..0062c83 100644 --- a/app/web/dist/assets/export-cut-DmVsiKji.js +++ b/app/web/dist/assets/export-cut-BqZI0-Rv.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-D3eZu5VE.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-C43toXVm.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-C43toXVm.js b/app/web/dist/assets/index-C43toXVm.js new file mode 100644 index 0000000..3859e56 --- /dev/null +++ b/app/web/dist/assets/index-C43toXVm.js @@ -0,0 +1,141 @@ +(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))s(a);new MutationObserver(a=>{for(const o of a)if(o.type==="childList")for(const c of o.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&s(c)}).observe(document,{childList:!0,subtree:!0});function i(a){const o={};return a.integrity&&(o.integrity=a.integrity),a.referrerPolicy&&(o.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?o.credentials="include":a.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function s(a){if(a.ep)return;a.ep=!0;const o=i(a);fetch(a.href,o)}})();function zu(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Yd={exports:{}},lo={};/** + * @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 J_;function aC(){if(J_)return lo;J_=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function i(s,a,o){var c=null;if(o!==void 0&&(c=""+o),a.key!==void 0&&(c=""+a.key),"key"in a){o={};for(var h in a)h!=="key"&&(o[h]=a[h])}else o=a;return a=o.ref,{$$typeof:e,type:s,key:c,ref:a!==void 0?a:null,props:o}}return lo.Fragment=t,lo.jsx=i,lo.jsxs=i,lo}var eb;function lC(){return eb||(eb=1,Yd.exports=aC()),Yd.exports}var d=lC(),Kd={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 tb;function oC(){if(tb)return et;tb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),i=Symbol.for("react.fragment"),s=Symbol.for("react.strict_mode"),a=Symbol.for("react.profiler"),o=Symbol.for("react.consumer"),c=Symbol.for("react.context"),h=Symbol.for("react.forward_ref"),p=Symbol.for("react.suspense"),f=Symbol.for("react.memo"),_=Symbol.for("react.lazy"),x=Symbol.for("react.activity"),b=Symbol.iterator;function v(M){return M===null||typeof M!="object"?null:(M=b&&M[b]||M["@@iterator"],typeof M=="function"?M:null)}var S={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},j=Object.assign,R={};function E(M,G,C){this.props=M,this.context=G,this.refs=R,this.updater=C||S}E.prototype.isReactComponent={},E.prototype.setState=function(M,G){if(typeof M!="object"&&typeof M!="function"&&M!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,M,G,"setState")},E.prototype.forceUpdate=function(M){this.updater.enqueueForceUpdate(this,M,"forceUpdate")};function N(){}N.prototype=E.prototype;function I(M,G,C){this.props=M,this.context=G,this.refs=R,this.updater=C||S}var te=I.prototype=new N;te.constructor=I,j(te,E.prototype),te.isPureReactComponent=!0;var F=Array.isArray;function D(){}var ie={H:null,A:null,T:null,S:null},fe=Object.prototype.hasOwnProperty;function Se(M,G,C){var V=C.ref;return{$$typeof:e,type:M,key:G,ref:V!==void 0?V:null,props:C}}function H(M,G){return Se(M.type,G,M.props)}function ce(M){return typeof M=="object"&&M!==null&&M.$$typeof===e}function W(M){var G={"=":"=0",":":"=2"};return"$"+M.replace(/[=:]/g,function(C){return G[C]})}var K=/\/+/g;function X(M,G){return typeof M=="object"&&M!==null&&M.key!=null?W(""+M.key):G.toString(36)}function U(M){switch(M.status){case"fulfilled":return M.value;case"rejected":throw M.reason;default:switch(typeof M.status=="string"?M.then(D,D):(M.status="pending",M.then(function(G){M.status==="pending"&&(M.status="fulfilled",M.value=G)},function(G){M.status==="pending"&&(M.status="rejected",M.reason=G)})),M.status){case"fulfilled":return M.value;case"rejected":throw M.reason}}throw M}function A(M,G,C,V,ne){var ae=typeof M;(ae==="undefined"||ae==="boolean")&&(M=null);var Y=!1;if(M===null)Y=!0;else switch(ae){case"bigint":case"string":case"number":Y=!0;break;case"object":switch(M.$$typeof){case e:case t:Y=!0;break;case _:return Y=M._init,A(Y(M._payload),G,C,V,ne)}}if(Y)return ne=ne(M),Y=V===""?"."+X(M,0):V,F(ne)?(C="",Y!=null&&(C=Y.replace(K,"$&/")+"/"),A(ne,G,C,"",function(Be){return Be})):ne!=null&&(ce(ne)&&(ne=H(ne,C+(ne.key==null||M&&M.key===ne.key?"":(""+ne.key).replace(K,"$&/")+"/")+Y)),G.push(ne)),1;Y=0;var he=V===""?".":V+":";if(F(M))for(var _e=0;_e>>1,T=A[xe];if(0>>1;xea(C,$))Va(ne,C)?(A[xe]=ne,A[V]=$,xe=V):(A[xe]=C,A[G]=$,xe=G);else if(Va(ne,$))A[xe]=ne,A[V]=$,xe=V;else break e}}return O}function a(A,O){var $=A.sortIndex-O.sortIndex;return $!==0?$:A.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=[],f=[],_=1,x=null,b=3,v=!1,S=!1,j=!1,R=!1,E=typeof setTimeout=="function"?setTimeout:null,N=typeof clearTimeout=="function"?clearTimeout:null,I=typeof setImmediate<"u"?setImmediate:null;function te(A){for(var O=i(f);O!==null;){if(O.callback===null)s(f);else if(O.startTime<=A)s(f),O.sortIndex=O.expirationTime,t(p,O);else break;O=i(f)}}function F(A){if(j=!1,te(A),!S)if(i(p)!==null)S=!0,D||(D=!0,W());else{var O=i(f);O!==null&&U(F,O.startTime-A)}}var D=!1,ie=-1,fe=5,Se=-1;function H(){return R?!0:!(e.unstable_now()-SeA&&H());){var xe=x.callback;if(typeof xe=="function"){x.callback=null,b=x.priorityLevel;var T=xe(x.expirationTime<=A);if(A=e.unstable_now(),typeof T=="function"){x.callback=T,te(A),O=!0;break t}x===i(p)&&s(p),te(A)}else s(p);x=i(p)}if(x!==null)O=!0;else{var M=i(f);M!==null&&U(F,M.startTime-A),O=!1}}break e}finally{x=null,b=$,v=!1}O=void 0}}finally{O?W():D=!1}}}var W;if(typeof I=="function")W=function(){I(ce)};else if(typeof MessageChannel<"u"){var K=new MessageChannel,X=K.port2;K.port1.onmessage=ce,W=function(){X.postMessage(null)}}else W=function(){E(ce,0)};function U(A,O){ie=E(function(){A(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(A){A.callback=null},e.unstable_forceFrameRate=function(A){0>A||125xe?(A.sortIndex=$,t(f,A),i(p)===null&&A===i(f)&&(j?(N(ie),ie=-1):j=!0,U(F,$-xe))):(A.sortIndex=T,t(p,A),S||v||(S=!0,D||(D=!0,W()))),A},e.unstable_shouldYield=H,e.unstable_wrapCallback=function(A){var O=b;return function(){var $=b;b=O;try{return A.apply(this,arguments)}finally{b=$}}}})(Zd)),Zd}var rb;function hC(){return rb||(rb=1,Xd.exports=uC()),Xd.exports}var Qd={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 sb;function dC(){if(sb)return tn;sb=1;var e=Hp();function t(p){var f="https://react.dev/errors/"+p;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Qd.exports=dC(),Qd.exports}/** + * @license React + * react-dom-client.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var lb;function pC(){if(lb)return oo;lb=1;var e=hC(),t=Hp(),i=fC();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 V=M(null),ne=M(null),ae=M(null),Y=M(null);function he(n,r){switch(C(ae,r),C(ne,n),C(V,null),r.nodeType){case 9:case 11:n=(n=r.documentElement)&&(n=n.namespaceURI)?S_(n):0;break;default:if(n=r.tagName,r=r.namespaceURI)r=S_(r),n=w_(r,n);else switch(n){case"svg":n=1;break;case"math":n=2;break;default:n=0}}G(V),C(V,n)}function _e(){G(V),G(ne),G(ae)}function Be(n){n.memoizedState!==null&&C(Y,n);var r=V.current,l=w_(r,n.type);r!==l&&(C(ne,n),C(V,l))}function Le(n){ne.current===n&&(G(V),G(ne)),Y.current===n&&(G(Y),no._currentValue=$)}var je,be;function tt(n){if(je===void 0)try{throw Error()}catch(l){var r=l.stack.trim().match(/\n( *(at )?)/);je=r&&r[1]||"",be=-1)":-1m||B[u]!==J[m]){var ue=` +`+B[u].replace(" at new "," at ");return n.displayName&&ue.includes("")&&(ue=ue.replace("",n.displayName)),ue}while(1<=u&&0<=m);break}}}finally{St=!1,Error.prepareStackTrace=l}return(l=n?n.displayName||n.name:"")?tt(l):""}function We(n,r){switch(n.tag){case 26:case 27:case 5:return tt(n.type);case 16:return tt("Lazy");case 13:return n.child!==r&&r!==null?tt("Suspense Fallback"):tt("Suspense");case 19:return tt("SuspenseList");case 0:case 15:return ot(n.type,!1);case 11:return ot(n.type.render,!1);case 1:return ot(n.type,!0);case 31:return tt("Activity");default:return""}}function Mt(n){try{var r="",l=null;do r+=We(n,l),l=n,n=n.return;while(n);return r}catch(u){return` +Error generating stack: `+u.message+` +`+u.stack}}var He=Object.prototype.hasOwnProperty,xt=e.unstable_scheduleCallback,Ae=e.unstable_cancelCallback,Kt=e.unstable_shouldYield,mi=e.unstable_requestPaint,wt=e.unstable_now,Qe=e.unstable_getCurrentPriorityLevel,Q=e.unstable_ImmediatePriority,ge=e.unstable_UserBlockingPriority,Te=e.unstable_NormalPriority,Ue=e.unstable_LowPriority,it=e.unstable_IdlePriority,Wt=e.log,ui=e.unstable_setDisableYieldValue,Bt=null,vt=null;function At(n){if(typeof Wt=="function"&&ui(n),vt&&typeof vt.setStrictMode=="function")try{vt.setStrictMode(Bt,n)}catch{}}var Ze=Math.clz32?Math.clz32:we,hi=Math.log,P=Math.LN2;function we(n){return n>>>=0,n===0?32:31-(hi(n)/P|0)|0}var ze=256,Re=262144,Ge=4194304;function $e(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 ht(n,r,l){var u=n.pendingLanes;if(u===0)return 0;var m=0,g=n.suspendedLanes,y=n.pingedLanes;n=n.warmLanes;var k=u&134217727;return k!==0?(u=k&~g,u!==0?m=$e(u):(y&=k,y!==0?m=$e(y):l||(l=k&~n,l!==0&&(m=$e(l))))):(k=u&~g,k!==0?m=$e(k):y!==0?m=$e(y):l||(l=u&~n,l!==0&&(m=$e(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 dt(n,r){return(n.pendingLanes&~(n.suspendedLanes&~n.pingedLanes)&r)===0}function lt(n,r){switch(n){case 1:case 2:case 4:case 8:case 64:return r+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return r+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Vt(){var n=Ge;return Ge<<=1,(Ge&62914560)===0&&(Ge=4194304),n}function Ci(n){for(var r=[],l=0;31>l;l++)r.push(n);return r}function ft(n,r){n.pendingLanes|=r,r!==268435456&&(n.suspendedLanes=0,n.pingedLanes=0,n.warmLanes=0)}function Fi(n,r,l,u,m,g){var y=n.pendingLanes;n.pendingLanes=l,n.suspendedLanes=0,n.pingedLanes=0,n.warmLanes=0,n.expiredLanes&=l,n.entangledLanes&=l,n.errorRecoveryDisabledLanes&=l,n.shellSuspendCounter=0;var k=n.entanglements,B=n.expirationTimes,J=n.hiddenUpdates;for(l=y&~l;0"u")return null;try{return n.activeElement||n.body}catch{return n.body}}var Ei=/[\n"\\]/g;function gi(n){return n.replace(Ei,function(r){return"\\"+r.charCodeAt(0).toString(16)+" "})}function Gi(n,r,l,u,m,g,y,k){n.name="",y!=null&&typeof y!="function"&&typeof y!="symbol"&&typeof y!="boolean"?n.type=y:n.removeAttribute("type"),r!=null?y==="number"?(r===0&&n.value===""||n.value!=r)&&(n.value=""+Ct(r)):n.value!==""+Ct(r)&&(n.value=""+Ct(r)):y!=="submit"&&y!=="reset"||n.removeAttribute("value"),r!=null?Or(n,y,Ct(r)):l!=null?Or(n,y,Ct(l)):u!=null&&n.removeAttribute("value"),m==null&&g!=null&&(n.defaultChecked=!!g),m!=null&&(n.checked=m&&typeof m!="function"&&typeof m!="symbol"),k!=null&&typeof k!="function"&&typeof k!="symbol"&&typeof k!="boolean"?n.name=""+Ct(k):n.removeAttribute("name")}function Nn(n,r,l,u,m,g,y,k){if(g!=null&&typeof g!="function"&&typeof g!="symbol"&&typeof g!="boolean"&&(n.type=g),r!=null||l!=null){if(!(g!=="submit"&&g!=="reset"||r!=null)){Lr(n);return}l=l!=null?""+Ct(l):"",r=r!=null?""+Ct(r):l,k||r===n.value||(n.value=r),n.defaultValue=r}u=u??m,u=typeof u!="function"&&typeof u!="symbol"&&!!u,n.checked=k?n.checked:!!u,n.defaultChecked=!!u,y!=null&&typeof y!="function"&&typeof y!="symbol"&&typeof y!="boolean"&&(n.name=y),Lr(n)}function Or(n,r,l){r==="number"&&xr(n.ownerDocument)===n||n.defaultValue===""+l||(n.defaultValue=""+l)}function jn(n,r,l,u){if(n=n.options,r){r={};for(var m=0;m"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),re=!1;if(Wn)try{var ye={};Object.defineProperty(ye,"passive",{get:function(){re=!0}}),window.addEventListener("test",ye,ye),window.removeEventListener("test",ye,ye)}catch{re=!1}var ke=null,Je=null,Pt=null;function Ni(){if(Pt)return Pt;var n,r=Je,l=r.length,u,m="value"in ke?ke.value:ke.textContent,g=m.length;for(n=0;n=Cl),Tm=" ",Am=!1;function Rm(n,r){switch(n){case"keyup":return j1.indexOf(r.keyCode)!==-1;case"keydown":return r.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Dm(n){return n=n.detail,typeof n=="object"&&"data"in n?n.data:null}var Na=!1;function A1(n,r){switch(n){case"compositionend":return Dm(r);case"keypress":return r.which!==32?null:(Am=!0,Tm);case"textInput":return n=r.data,n===Tm&&Am?null:n;default:return null}}function R1(n,r){if(Na)return n==="compositionend"||!Ju&&Rm(n,r)?(n=Ni(),Pt=Je=ke=null,Na=!1,n):null;switch(n){case"paste":return null;case"keypress":if(!(r.ctrlKey||r.altKey||r.metaKey)||r.ctrlKey&&r.altKey){if(r.char&&1=r)return{node:l,offset:r-n};n=u}e:{for(;l;){if(l.nextSibling){l=l.nextSibling;break e}l=l.parentNode}l=void 0}l=Hm(l)}}function $m(n,r){return n&&r?n===r?!0:n&&n.nodeType===3?!1:r&&r.nodeType===3?$m(n,r.parentNode):"contains"in n?n.contains(r):n.compareDocumentPosition?!!(n.compareDocumentPosition(r)&16):!1:!1}function Fm(n){n=n!=null&&n.ownerDocument!=null&&n.ownerDocument.defaultView!=null?n.ownerDocument.defaultView:window;for(var r=xr(n.document);r instanceof n.HTMLIFrameElement;){try{var l=typeof r.contentWindow.location.href=="string"}catch{l=!1}if(l)n=r.contentWindow;else break;r=xr(n.document)}return r}function ih(n){var r=n&&n.nodeName&&n.nodeName.toLowerCase();return r&&(r==="input"&&(n.type==="text"||n.type==="search"||n.type==="tel"||n.type==="url"||n.type==="password")||r==="textarea"||n.contentEditable==="true")}var I1=Wn&&"documentMode"in document&&11>=document.documentMode,ja=null,nh=null,jl=null,rh=!1;function qm(n,r,l){var u=l.window===l?l.document:l.nodeType===9?l:l.ownerDocument;rh||ja==null||ja!==xr(u)||(u=ja,"selectionStart"in u&&ih(u)?u={start:u.selectionStart,end:u.selectionEnd}:(u=(u.ownerDocument&&u.ownerDocument.defaultView||window).getSelection(),u={anchorNode:u.anchorNode,anchorOffset:u.anchorOffset,focusNode:u.focusNode,focusOffset:u.focusOffset}),jl&&Nl(jl,u)||(jl=u,u=Ic(nh,"onSelect"),0>=y,m-=y,yr=1<<32-Ze(r)+m|l<st?(bt=Ie,Ie=null):bt=Ie.sibling;var Tt=ee(q,Ie,Z[st],de);if(Tt===null){Ie===null&&(Ie=bt);break}n&&Ie&&Tt.alternate===null&&r(q,Ie),z=g(Tt,z,st),jt===null?Fe=Tt:jt.sibling=Tt,jt=Tt,Ie=bt}if(st===Z.length)return l(q,Ie),yt&&Pr(q,st),Fe;if(Ie===null){for(;stst?(bt=Ie,Ie=null):bt=Ie.sibling;var Ds=ee(q,Ie,Tt.value,de);if(Ds===null){Ie===null&&(Ie=bt);break}n&&Ie&&Ds.alternate===null&&r(q,Ie),z=g(Ds,z,st),jt===null?Fe=Ds:jt.sibling=Ds,jt=Ds,Ie=bt}if(Tt.done)return l(q,Ie),yt&&Pr(q,st),Fe;if(Ie===null){for(;!Tt.done;st++,Tt=Z.next())Tt=pe(q,Tt.value,de),Tt!==null&&(z=g(Tt,z,st),jt===null?Fe=Tt:jt.sibling=Tt,jt=Tt);return yt&&Pr(q,st),Fe}for(Ie=u(Ie);!Tt.done;st++,Tt=Z.next())Tt=se(Ie,q,st,Tt.value,de),Tt!==null&&(n&&Tt.alternate!==null&&Ie.delete(Tt.key===null?st:Tt.key),z=g(Tt,z,st),jt===null?Fe=Tt:jt.sibling=Tt,jt=Tt);return n&&Ie.forEach(function(sC){return r(q,sC)}),yt&&Pr(q,st),Fe}function Ut(q,z,Z,de){if(typeof Z=="object"&&Z!==null&&Z.type===j&&Z.key===null&&(Z=Z.props.children),typeof Z=="object"&&Z!==null){switch(Z.$$typeof){case v:e:{for(var Fe=Z.key;z!==null;){if(z.key===Fe){if(Fe=Z.type,Fe===j){if(z.tag===7){l(q,z.sibling),de=m(z,Z.props.children),de.return=q,q=de;break e}}else if(z.elementType===Fe||typeof Fe=="object"&&Fe!==null&&Fe.$$typeof===fe&&ta(Fe)===z.type){l(q,z.sibling),de=m(z,Z.props),Bl(de,Z),de.return=q,q=de;break e}l(q,z);break}else r(q,z);z=z.sibling}Z.type===j?(de=Xs(Z.props.children,q.mode,de,Z.key),de.return=q,q=de):(de=ic(Z.type,Z.key,Z.props,null,q.mode,de),Bl(de,Z),de.return=q,q=de)}return y(q);case S:e:{for(Fe=Z.key;z!==null;){if(z.key===Fe)if(z.tag===4&&z.stateNode.containerInfo===Z.containerInfo&&z.stateNode.implementation===Z.implementation){l(q,z.sibling),de=m(z,Z.children||[]),de.return=q,q=de;break e}else{l(q,z);break}else r(q,z);z=z.sibling}de=hh(Z,q.mode,de),de.return=q,q=de}return y(q);case fe:return Z=ta(Z),Ut(q,z,Z,de)}if(U(Z))return Oe(q,z,Z,de);if(W(Z)){if(Fe=W(Z),typeof Fe!="function")throw Error(s(150));return Z=Fe.call(Z),Ke(q,z,Z,de)}if(typeof Z.then=="function")return Ut(q,z,cc(Z),de);if(Z.$$typeof===I)return Ut(q,z,sc(q,Z),de);uc(q,Z)}return typeof Z=="string"&&Z!==""||typeof Z=="number"||typeof Z=="bigint"?(Z=""+Z,z!==null&&z.tag===6?(l(q,z.sibling),de=m(z,Z),de.return=q,q=de):(l(q,z),de=uh(Z,q.mode,de),de.return=q,q=de),y(q)):l(q,z)}return function(q,z,Z,de){try{Ml=0;var Fe=Ut(q,z,Z,de);return Ia=null,Fe}catch(Ie){if(Ie===Pa||Ie===lc)throw Ie;var jt=An(29,Ie,null,q.mode);return jt.lanes=de,jt.return=q,jt}finally{}}}var na=fg(!0),pg=fg(!1),ms=!1;function wh(n){n.updateQueue={baseState:n.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Ch(n,r){n=n.updateQueue,r.updateQueue===n&&(r.updateQueue={baseState:n.baseState,firstBaseUpdate:n.firstBaseUpdate,lastBaseUpdate:n.lastBaseUpdate,shared:n.shared,callbacks:null})}function gs(n){return{lane:n,tag:0,payload:null,callback:null,next:null}}function xs(n,r,l){var u=n.updateQueue;if(u===null)return null;if(u=u.shared,(Dt&2)!==0){var m=u.pending;return m===null?r.next=r:(r.next=m.next,m.next=r),u.pending=r,r=tc(n),Zm(n,null,l),r}return ec(n,u,r,l),tc(n)}function Ll(n,r,l){if(r=r.updateQueue,r!==null&&(r=r.shared,(l&4194048)!==0)){var u=r.lanes;u&=n.pendingLanes,l|=u,r.lanes=l,ln(n,l)}}function kh(n,r){var l=n.updateQueue,u=n.alternate;if(u!==null&&(u=u.updateQueue,l===u)){var m=null,g=null;if(l=l.firstBaseUpdate,l!==null){do{var y={lane:l.lane,tag:l.tag,payload:l.payload,callback:null,next:null};g===null?m=g=y:g=g.next=y,l=l.next}while(l!==null);g===null?m=g=r:g=g.next=r}else m=g=r;l={baseState:u.baseState,firstBaseUpdate:m,lastBaseUpdate:g,shared:u.shared,callbacks:u.callbacks},n.updateQueue=l;return}n=l.lastBaseUpdate,n===null?l.firstBaseUpdate=r:n.next=r,l.lastBaseUpdate=r}var Eh=!1;function Ol(){if(Eh){var n=za;if(n!==null)throw n}}function zl(n,r,l,u){Eh=!1;var m=n.updateQueue;ms=!1;var g=m.firstBaseUpdate,y=m.lastBaseUpdate,k=m.shared.pending;if(k!==null){m.shared.pending=null;var B=k,J=B.next;B.next=null,y===null?g=J:y.next=J,y=B;var ue=n.alternate;ue!==null&&(ue=ue.updateQueue,k=ue.lastBaseUpdate,k!==y&&(k===null?ue.firstBaseUpdate=J:k.next=J,ue.lastBaseUpdate=B))}if(g!==null){var pe=m.baseState;y=0,ue=J=B=null,k=g;do{var ee=k.lane&-536870913,se=ee!==k.lane;if(se?(_t&ee)===ee:(u&ee)===ee){ee!==0&&ee===Oa&&(Eh=!0),ue!==null&&(ue=ue.next={lane:0,tag:k.tag,payload:k.payload,callback:null,next:null});e:{var Oe=n,Ke=k;ee=r;var Ut=l;switch(Ke.tag){case 1:if(Oe=Ke.payload,typeof Oe=="function"){pe=Oe.call(Ut,pe,ee);break e}pe=Oe;break e;case 3:Oe.flags=Oe.flags&-65537|128;case 0:if(Oe=Ke.payload,ee=typeof Oe=="function"?Oe.call(Ut,pe,ee):Oe,ee==null)break e;pe=x({},pe,ee);break e;case 2:ms=!0}}ee=k.callback,ee!==null&&(n.flags|=64,se&&(n.flags|=8192),se=m.callbacks,se===null?m.callbacks=[ee]:se.push(ee))}else se={lane:ee,tag:k.tag,payload:k.payload,callback:k.callback,next:null},ue===null?(J=ue=se,B=pe):ue=ue.next=se,y|=ee;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);ue===null&&(B=pe),m.baseState=B,m.firstBaseUpdate=J,m.lastBaseUpdate=ue,g===null&&(m.shared.lanes=0),Ss|=y,n.lanes=y,n.memoizedState=pe}}function mg(n,r){if(typeof n!="function")throw Error(s(191,n));n.call(r)}function gg(n,r){var l=n.callbacks;if(l!==null)for(n.callbacks=null,n=0;ng?g:8;var y=A.T,k={};A.T=k,Wh(n,!1,r,l);try{var B=m(),J=A.S;if(J!==null&&J(k,B),B!==null&&typeof B=="object"&&typeof B.then=="function"){var ue=K1(B,u);Hl(n,r,ue,Ln(n))}else Hl(n,r,u,Ln(n))}catch(pe){Hl(n,r,{then:function(){},status:"rejected",reason:pe},Ln())}finally{O.p=g,y!==null&&k.types!==null&&(y.types=k.types),A.T=y}}function ew(){}function Fh(n,r,l,u){if(n.tag!==5)throw Error(s(476));var m=Kg(n).queue;Yg(n,m,r,$,l===null?ew:function(){return Vg(n),l(u)})}function Kg(n){var r=n.memoizedState;if(r!==null)return r;r={memoizedState:$,baseState:$,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:$r,lastRenderedState:$},next:null};var l={};return r.next={memoizedState:l,baseState:l,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:$r,lastRenderedState:l},next:null},n.memoizedState=r,n=n.alternate,n!==null&&(n.memoizedState=r),r}function Vg(n){var r=Kg(n);r.next===null&&(r=n.alternate.memoizedState),Hl(n,r.next.queue,{},Ln())}function qh(){return Vi(no)}function Xg(){return fi().memoizedState}function Zg(){return fi().memoizedState}function tw(n){for(var r=n.return;r!==null;){switch(r.tag){case 24:case 3:var l=Ln();n=gs(l);var u=xs(r,n,l);u!==null&&(yn(u,r,l),Ll(u,r,l)),r={cache:bh()},n.payload=r;return}r=r.return}}function iw(n,r,l){var u=Ln();l={lane:u,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null},vc(n)?Jg(r,l):(l=oh(n,r,l,u),l!==null&&(yn(l,n,u),ex(l,r,u)))}function Qg(n,r,l){var u=Ln();Hl(n,r,l,u)}function Hl(n,r,l,u){var m={lane:u,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null};if(vc(n))Jg(r,m);else{var g=n.alternate;if(n.lanes===0&&(g===null||g.lanes===0)&&(g=r.lastRenderedReducer,g!==null))try{var y=r.lastRenderedState,k=g(y,l);if(m.hasEagerState=!0,m.eagerState=k,Tn(k,y))return ec(n,r,m,0),Ft===null&&Jo(),!1}catch{}finally{}if(l=oh(n,r,m,u),l!==null)return yn(l,n,u),ex(l,r,u),!0}return!1}function Wh(n,r,l,u){if(u={lane:2,revertLane:wd(),gesture:null,action:u,hasEagerState:!1,eagerState:null,next:null},vc(n)){if(r)throw Error(s(479))}else r=oh(n,l,u,2),r!==null&&yn(r,n,2)}function vc(n){var r=n.alternate;return n===rt||r!==null&&r===rt}function Jg(n,r){Ua=fc=!0;var l=n.pending;l===null?r.next=r:(r.next=l.next,l.next=r),n.pending=r}function ex(n,r,l){if((l&4194048)!==0){var u=r.lanes;u&=n.pendingLanes,l|=u,r.lanes=l,ln(n,l)}}var Ul={readContext:Vi,use:gc,useCallback:si,useContext:si,useEffect:si,useImperativeHandle:si,useLayoutEffect:si,useInsertionEffect:si,useMemo:si,useReducer:si,useRef:si,useState:si,useDebugValue:si,useDeferredValue:si,useTransition:si,useSyncExternalStore:si,useId:si,useHostTransitionStatus:si,useFormState:si,useActionState:si,useOptimistic:si,useMemoCache:si,useCacheRefresh:si};Ul.useEffectEvent=si;var tx={readContext:Vi,use:gc,useCallback:function(n,r){return un().memoizedState=[n,r===void 0?null:r],n},useContext:Vi,useEffect:Pg,useImperativeHandle:function(n,r,l){l=l!=null?l.concat([n]):null,_c(4194308,4,$g.bind(null,r,n),l)},useLayoutEffect:function(n,r){return _c(4194308,4,n,r)},useInsertionEffect:function(n,r){_c(4,2,n,r)},useMemo:function(n,r){var l=un();r=r===void 0?null:r;var u=n();if(ra){At(!0);try{n()}finally{At(!1)}}return l.memoizedState=[u,r],u},useReducer:function(n,r,l){var u=un();if(l!==void 0){var m=l(r);if(ra){At(!0);try{l(r)}finally{At(!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=iw.bind(null,rt,n),[u.memoizedState,n]},useRef:function(n){var r=un();return n={current:n},r.memoizedState=n},useState:function(n){n=Ph(n);var r=n.queue,l=Qg.bind(null,rt,r);return r.dispatch=l,[n.memoizedState,l]},useDebugValue:Uh,useDeferredValue:function(n,r){var l=un();return $h(l,n,r)},useTransition:function(){var n=Ph(!1);return n=Yg.bind(null,rt,n.queue,!0,!1),un().memoizedState=n,[!1,n]},useSyncExternalStore:function(n,r,l){var u=rt,m=un();if(yt){if(l===void 0)throw Error(s(407));l=l()}else{if(l=r(),Ft===null)throw Error(s(349));(_t&127)!==0||Sg(u,r,l)}m.memoizedState=l;var g={value:l,getSnapshot:r};return m.queue=g,Pg(Cg.bind(null,u,g,n),[n]),u.flags|=2048,Fa(9,{destroy:void 0},wg.bind(null,u,g,l,r),null),l},useId:function(){var n=un(),r=Ft.identifierPrefix;if(yt){var l=Sr,u=yr;l=(u&~(1<<32-Ze(u)-1)).toString(32)+l,r="_"+r+"R_"+l,l=pc++,0<\/script>",g=g.removeChild(g.firstChild);break;case"select":g=typeof u.is=="string"?y.createElement("select",{is:u.is}):y.createElement("select"),u.multiple?g.multiple=!0:u.size&&(g.size=u.size);break;default:g=typeof u.is=="string"?y.createElement(m,{is:u.is}):y.createElement(m)}}g[le]=r,g[L]=u;e:for(y=r.child;y!==null;){if(y.tag===5||y.tag===6)g.appendChild(y.stateNode);else if(y.tag!==4&&y.tag!==27&&y.child!==null){y.child.return=y,y=y.child;continue}if(y===r)break e;for(;y.sibling===null;){if(y.return===null||y.return===r)break e;y=y.return}y.sibling.return=y.return,y=y.sibling}r.stateNode=g;e:switch(Zi(g,m,u),m){case"button":case"input":case"select":case"textarea":u=!!u.autoFocus;break e;case"img":u=!0;break e;default:u=!1}u&&qr(r)}}return Zt(r),sd(r,r.type,n===null?null:n.memoizedProps,r.pendingProps,l),null;case 6:if(n&&r.stateNode!=null)n.memoizedProps!==u&&qr(r);else{if(typeof u!="string"&&r.stateNode===null)throw Error(s(166));if(n=ae.current,Ba(r)){if(n=r.stateNode,l=r.memoizedProps,u=null,m=Ki,m!==null)switch(m.tag){case 27:case 5:u=m.memoizedProps}n[le]=r,n=!!(n.nodeValue===l||u!==null&&u.suppressHydrationWarning===!0||v_(n.nodeValue,l)),n||fs(r,!0)}else n=Hc(n).createTextNode(u),n[le]=r,r.stateNode=n}return Zt(r),null;case 31:if(l=r.memoizedState,n===null||n.memoizedState!==null){if(u=Ba(r),l!==null){if(n===null){if(!u)throw Error(s(318));if(n=r.memoizedState,n=n!==null?n.dehydrated:null,!n)throw Error(s(557));n[le]=r}else Zs(),(r.flags&128)===0&&(r.memoizedState=null),r.flags|=4;Zt(r),n=!1}else l=mh(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=l),n=!0;if(!n)return r.flags&256?(Dn(r),r):(Dn(r),null);if((r.flags&128)!==0)throw Error(s(558))}return Zt(r),null;case 13:if(u=r.memoizedState,n===null||n.memoizedState!==null&&n.memoizedState.dehydrated!==null){if(m=Ba(r),u!==null&&u.dehydrated!==null){if(n===null){if(!m)throw Error(s(318));if(m=r.memoizedState,m=m!==null?m.dehydrated:null,!m)throw Error(s(317));m[le]=r}else Zs(),(r.flags&128)===0&&(r.memoizedState=null),r.flags|=4;Zt(r),m=!1}else m=mh(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=m),m=!0;if(!m)return r.flags&256?(Dn(r),r):(Dn(r),null)}return Dn(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),kc(r,r.updateQueue),Zt(r),null);case 4:return _e(),n===null&&Nd(r.stateNode.containerInfo),Zt(r),null;case 10:return Hr(r.type),Zt(r),null;case 19:if(G(di),u=r.memoizedState,u===null)return Zt(r),null;if(m=(r.flags&128)!==0,g=u.rendering,g===null)if(m)Fl(u,!1);else{if(ai!==0||n!==null&&(n.flags&128)!==0)for(n=r.child;n!==null;){if(g=dc(n),g!==null){for(r.flags|=128,Fl(u,!1),n=g.updateQueue,r.updateQueue=n,kc(r,n),r.subtreeFlags=0,n=l,l=r.child;l!==null;)Qm(l,n),l=l.sibling;return C(di,di.current&1|2),yt&&Pr(r,u.treeForkCount),r.child}n=n.sibling}u.tail!==null&&wt()>Ac&&(r.flags|=128,m=!0,Fl(u,!1),r.lanes=4194304)}else{if(!m)if(n=dc(g),n!==null){if(r.flags|=128,m=!0,n=n.updateQueue,r.updateQueue=n,kc(r,n),Fl(u,!0),u.tail===null&&u.tailMode==="hidden"&&!g.alternate&&!yt)return Zt(r),null}else 2*wt()-u.renderingStartTime>Ac&&l!==536870912&&(r.flags|=128,m=!0,Fl(u,!1),r.lanes=4194304);u.isBackwards?(g.sibling=r.child,r.child=g):(n=u.last,n!==null?n.sibling=g:r.child=g,u.last=g)}return u.tail!==null?(n=u.tail,u.rendering=n,u.tail=n.sibling,u.renderingStartTime=wt(),n.sibling=null,l=di.current,C(di,m?l&1|2:l&1),yt&&Pr(r,u.treeForkCount),n):(Zt(r),null);case 22:case 23:return Dn(r),jh(),u=r.memoizedState!==null,n!==null?n.memoizedState!==null!==u&&(r.flags|=8192):u&&(r.flags|=8192),u?(l&536870912)!==0&&(r.flags&128)===0&&(Zt(r),r.subtreeFlags&6&&(r.flags|=8192)):Zt(r),l=r.updateQueue,l!==null&&kc(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&&G(ea),null;case 24:return l=null,n!==null&&(l=n.memoizedState.cache),r.memoizedState.cache!==l&&(r.flags|=2048),Hr(xi),Zt(r),null;case 25:return null;case 30:return null}throw Error(s(156,r.tag))}function lw(n,r){switch(fh(r),r.tag){case 1:return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 3:return Hr(xi),_e(),n=r.flags,(n&65536)!==0&&(n&128)===0?(r.flags=n&-65537|128,r):null;case 26:case 27:case 5:return Le(r),null;case 31:if(r.memoizedState!==null){if(Dn(r),r.alternate===null)throw Error(s(340));Zs()}return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 13:if(Dn(r),n=r.memoizedState,n!==null&&n.dehydrated!==null){if(r.alternate===null)throw Error(s(340));Zs()}return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 19:return G(di),null;case 4:return _e(),null;case 10:return Hr(r.type),null;case 22:case 23:return Dn(r),jh(),n!==null&&G(ea),n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 24:return Hr(xi),null;case 25:return null;default:return null}}function kx(n,r){switch(fh(r),r.tag){case 3:Hr(xi),_e();break;case 26:case 27:case 5:Le(r);break;case 4:_e();break;case 31:r.memoizedState!==null&&Dn(r);break;case 13:Dn(r);break;case 19:G(di);break;case 10:Hr(r.type);break;case 22:case 23:Dn(r),jh(),n!==null&&G(ea);break;case 24:Hr(xi)}}function ql(n,r){try{var l=r.updateQueue,u=l!==null?l.lastEffect:null;if(u!==null){var m=u.next;l=m;do{if((l.tag&n)===n){u=void 0;var g=l.create,y=l.inst;u=g(),y.destroy=u}l=l.next}while(l!==m)}}catch(k){zt(r,r.return,k)}}function vs(n,r,l){try{var u=r.updateQueue,m=u!==null?u.lastEffect:null;if(m!==null){var g=m.next;u=g;do{if((u.tag&n)===n){var y=u.inst,k=y.destroy;if(k!==void 0){y.destroy=void 0,m=r;var B=l,J=k;try{J()}catch(ue){zt(m,B,ue)}}}u=u.next}while(u!==g)}}catch(ue){zt(r,r.return,ue)}}function Ex(n){var r=n.updateQueue;if(r!==null){var l=n.stateNode;try{gg(r,l)}catch(u){zt(n,n.return,u)}}}function Nx(n,r,l){l.props=sa(n.type,n.memoizedProps),l.state=n.memoizedState;try{l.componentWillUnmount()}catch(u){zt(n,r,u)}}function Wl(n,r){try{var l=n.ref;if(l!==null){switch(n.tag){case 26:case 27:case 5:var u=n.stateNode;break;case 30:u=n.stateNode;break;default:u=n.stateNode}typeof l=="function"?n.refCleanup=l(u):l.current=u}}catch(m){zt(n,r,m)}}function wr(n,r){var l=n.ref,u=n.refCleanup;if(l!==null)if(typeof u=="function")try{u()}catch(m){zt(n,r,m)}finally{n.refCleanup=null,n=n.alternate,n!=null&&(n.refCleanup=null)}else if(typeof l=="function")try{l(null)}catch(m){zt(n,r,m)}else l.current=null}function jx(n){var r=n.type,l=n.memoizedProps,u=n.stateNode;try{e:switch(r){case"button":case"input":case"select":case"textarea":l.autoFocus&&u.focus();break e;case"img":l.src?u.src=l.src:l.srcSet&&(u.srcset=l.srcSet)}}catch(m){zt(n,n.return,m)}}function ad(n,r,l){try{var u=n.stateNode;Tw(u,n.type,l,r),u[L]=r}catch(m){zt(n,n.return,m)}}function Tx(n){return n.tag===5||n.tag===3||n.tag===26||n.tag===27&&Ns(n.type)||n.tag===4}function ld(n){e:for(;;){for(;n.sibling===null;){if(n.return===null||Tx(n.return))return null;n=n.return}for(n.sibling.return=n.return,n=n.sibling;n.tag!==5&&n.tag!==6&&n.tag!==18;){if(n.tag===27&&Ns(n.type)||n.flags&2||n.child===null||n.tag===4)continue e;n.child.return=n,n=n.child}if(!(n.flags&2))return n.stateNode}}function od(n,r,l){var u=n.tag;if(u===5||u===6)n=n.stateNode,r?(l.nodeType===9?l.body:l.nodeName==="HTML"?l.ownerDocument.body:l).insertBefore(n,r):(r=l.nodeType===9?l.body:l.nodeName==="HTML"?l.ownerDocument.body:l,r.appendChild(n),l=l._reactRootContainer,l!=null||r.onclick!==null||(r.onclick=lr));else if(u!==4&&(u===27&&Ns(n.type)&&(l=n.stateNode,r=null),n=n.child,n!==null))for(od(n,r,l),n=n.sibling;n!==null;)od(n,r,l),n=n.sibling}function Ec(n,r,l){var u=n.tag;if(u===5||u===6)n=n.stateNode,r?l.insertBefore(n,r):l.appendChild(n);else if(u!==4&&(u===27&&Ns(n.type)&&(l=n.stateNode),n=n.child,n!==null))for(Ec(n,r,l),n=n.sibling;n!==null;)Ec(n,r,l),n=n.sibling}function Ax(n){var r=n.stateNode,l=n.memoizedProps;try{for(var u=n.type,m=r.attributes;m.length;)r.removeAttributeNode(m[0]);Zi(r,u,l),r[le]=n,r[L]=l}catch(g){zt(n,n.return,g)}}var Wr=!1,vi=!1,cd=!1,Rx=typeof WeakSet=="function"?WeakSet:Set,Mi=null;function ow(n,r){if(n=n.containerInfo,Ad=Yc,n=Fm(n),ih(n)){if("selectionStart"in n)var l={start:n.selectionStart,end:n.selectionEnd};else e:{l=(l=n.ownerDocument)&&l.defaultView||window;var u=l.getSelection&&l.getSelection();if(u&&u.rangeCount!==0){l=u.anchorNode;var m=u.anchorOffset,g=u.focusNode;u=u.focusOffset;try{l.nodeType,g.nodeType}catch{l=null;break e}var y=0,k=-1,B=-1,J=0,ue=0,pe=n,ee=null;t:for(;;){for(var se;pe!==l||m!==0&&pe.nodeType!==3||(k=y+m),pe!==g||u!==0&&pe.nodeType!==3||(B=y+u),pe.nodeType===3&&(y+=pe.nodeValue.length),(se=pe.firstChild)!==null;)ee=pe,pe=se;for(;;){if(pe===n)break t;if(ee===l&&++J===m&&(k=y),ee===g&&++ue===u&&(B=y),(se=pe.nextSibling)!==null)break;pe=ee,ee=pe.parentNode}pe=se}l=k===-1||B===-1?null:{start:k,end:B}}else l=null}l=l||{start:0,end:0}}else l=null;for(Rd={focusedElem:n,selectionRange:l},Yc=!1,Mi=r;Mi!==null;)if(r=Mi,n=r.child,(r.subtreeFlags&1028)!==0&&n!==null)n.return=r,Mi=n;else for(;Mi!==null;){switch(r=Mi,g=r.alternate,n=r.flags,r.tag){case 0:if((n&4)!==0&&(n=r.updateQueue,n=n!==null?n.events:null,n!==null))for(l=0;l title"))),Zi(g,u,l),g[le]=n,Rt(g),u=g;break e;case"link":var y=z_("link","href",m).get(u+(l.href||""));if(y){for(var k=0;kUt&&(y=Ut,Ut=Ke,Ke=y);var q=Um(k,Ke),z=Um(k,Ut);if(q&&z&&(se.rangeCount!==1||se.anchorNode!==q.node||se.anchorOffset!==q.offset||se.focusNode!==z.node||se.focusOffset!==z.offset)){var Z=pe.createRange();Z.setStart(q.node,q.offset),se.removeAllRanges(),Ke>Ut?(se.addRange(Z),se.extend(z.node,z.offset)):(Z.setEnd(z.node,z.offset),se.addRange(Z))}}}}for(pe=[],se=k;se=se.parentNode;)se.nodeType===1&&pe.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=gd,gd=null;var g=Cs,y=Xr;if(ji=0,Ka=Cs=null,Xr=0,(Dt&6)!==0)throw Error(s(331));var k=Dt;if(Dt|=4,$x(g.current),Ix(g,g.current,y,l),Dt=k,Zl(0,!1),vt&&typeof vt.onPostCommitFiberRoot=="function")try{vt.onPostCommitFiberRoot(Bt,g)}catch{}return!0}finally{O.p=m,A.T=u,a_(n,r)}}function o_(n,r,l){r=Kn(l,r),r=Vh(n.stateNode,r,2),n=xs(n,r,2),n!==null&&(ft(n,2),Cr(n))}function zt(n,r,l){if(n.tag===3)o_(n,n,l);else for(;r!==null;){if(r.tag===3){o_(r,n,l);break}else if(r.tag===1){var u=r.stateNode;if(typeof r.type.getDerivedStateFromError=="function"||typeof u.componentDidCatch=="function"&&(ws===null||!ws.has(u))){n=Kn(l,n),l=cx(2),u=xs(r,l,2),u!==null&&(ux(l,u,r,n),ft(u,2),Cr(u));break}}r=r.return}}function vd(n,r,l){var u=n.pingCache;if(u===null){u=n.pingCache=new hw;var m=new Set;u.set(r,m)}else m=u.get(r),m===void 0&&(m=new Set,u.set(r,m));m.has(l)||(dd=!0,m.add(l),n=gw.bind(null,n,r,l),r.then(n,n))}function gw(n,r,l){var u=n.pingCache;u!==null&&u.delete(r),n.pingedLanes|=n.suspendedLanes&l,n.warmLanes&=~l,Ft===n&&(_t&l)===l&&(ai===4||ai===3&&(_t&62914560)===_t&&300>wt()-Tc?(Dt&2)===0&&Va(n,0):fd|=l,Ya===_t&&(Ya=0)),Cr(n)}function c_(n,r){r===0&&(r=Vt()),n=Vs(n,r),n!==null&&(ft(n,r),Cr(n))}function xw(n){var r=n.memoizedState,l=0;r!==null&&(l=r.retryLane),c_(n,l)}function _w(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),c_(n,l)}function bw(n,r){return xt(n,r)}var Oc=null,Za=null,yd=!1,zc=!1,Sd=!1,Es=0;function Cr(n){n!==Za&&n.next===null&&(Za===null?Oc=Za=n:Za=Za.next=n),zc=!0,yd||(yd=!0,yw())}function Zl(n,r){if(!Sd&&zc){Sd=!0;do for(var l=!1,u=Oc;u!==null;){if(n!==0){var m=u.pendingLanes;if(m===0)var g=0;else{var y=u.suspendedLanes,k=u.pingedLanes;g=(1<<31-Ze(42|n)+1)-1,g&=m&~(y&~k),g=g&201326741?g&201326741|1:g?g|2:0}g!==0&&(l=!0,f_(u,g))}else g=_t,g=ht(u,u===Ft?g:0,u.cancelPendingCommit!==null||u.timeoutHandle!==-1),(g&3)===0||dt(u,g)||(l=!0,f_(u,g));u=u.next}while(l);Sd=!1}}function vw(){u_()}function u_(){zc=yd=!1;var n=0;Es!==0&&Rw()&&(n=Es);for(var r=wt(),l=null,u=Oc;u!==null;){var m=u.next,g=h_(u,r);g===0?(u.next=null,l===null?Oc=m:l.next=m,m===null&&(Za=l)):(l=u,(n!==0||(g&3)!==0)&&(zc=!0)),u=m}ji!==0&&ji!==5||Zl(n),Es!==0&&(Es=0)}function h_(n,r){for(var l=n.suspendedLanes,u=n.pingedLanes,m=n.expirationTimes,g=n.pendingLanes&-62914561;0k)break;var ue=B.transferSize,pe=B.initiatorType;ue&&y_(pe)&&(B=B.responseEnd,y+=ue*(B"u"?null:document;function M_(n,r,l){var u=Qa;if(u&&typeof r=="string"&&r){var m=gi(r);m='link[rel="'+n+'"][href="'+m+'"]',typeof l=="string"&&(m+='[crossorigin="'+l+'"]'),D_.has(m)||(D_.add(m),n={rel:n,crossOrigin:l,href:r},u.querySelector(m)===null&&(r=u.createElement("link"),Zi(r,"link",n),Rt(r),u.head.appendChild(r)))}}function Hw(n){Zr.D(n),M_("dns-prefetch",n,null)}function Uw(n,r){Zr.C(n,r),M_("preconnect",n,r)}function $w(n,r,l){Zr.L(n,r,l);var u=Qa;if(u&&n&&r){var m='link[rel="preload"][as="'+gi(r)+'"]';r==="image"&&l&&l.imageSrcSet?(m+='[imagesrcset="'+gi(l.imageSrcSet)+'"]',typeof l.imageSizes=="string"&&(m+='[imagesizes="'+gi(l.imageSizes)+'"]')):m+='[href="'+gi(n)+'"]';var g=m;switch(r){case"style":g=Ja(n);break;case"script":g=el(n)}er.has(g)||(n=x({rel:"preload",href:r==="image"&&l&&l.imageSrcSet?void 0:n,as:r},l),er.set(g,n),u.querySelector(m)!==null||r==="style"&&u.querySelector(to(g))||r==="script"&&u.querySelector(io(g))||(r=u.createElement("link"),Zi(r,"link",n),Rt(r),u.head.appendChild(r)))}}function Fw(n,r){Zr.m(n,r);var l=Qa;if(l&&n){var u=r&&typeof r.as=="string"?r.as:"script",m='link[rel="modulepreload"][as="'+gi(u)+'"][href="'+gi(n)+'"]',g=m;switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":g=el(n)}if(!er.has(g)&&(n=x({rel:"modulepreload",href:n},r),er.set(g,n),l.querySelector(m)===null)){switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(l.querySelector(io(g)))return}u=l.createElement("link"),Zi(u,"link",n),Rt(u),l.head.appendChild(u)}}}function qw(n,r,l){Zr.S(n,r,l);var u=Qa;if(u&&n){var m=Gt(u).hoistableStyles,g=Ja(n);r=r||"default";var y=m.get(g);if(!y){var k={loading:0,preload:null};if(y=u.querySelector(to(g)))k.loading=5;else{n=x({rel:"stylesheet",href:n,"data-precedence":r},l),(l=er.get(g))&&Pd(n,l);var B=y=u.createElement("link");Rt(B),Zi(B,"link",n),B._p=new Promise(function(J,ue){B.onload=J,B.onerror=ue}),B.addEventListener("load",function(){k.loading|=1}),B.addEventListener("error",function(){k.loading|=2}),k.loading|=4,$c(y,r,u)}y={type:"stylesheet",instance:y,count:1,state:k},m.set(g,y)}}}function Ww(n,r){Zr.X(n,r);var l=Qa;if(l&&n){var u=Gt(l).hoistableScripts,m=el(n),g=u.get(m);g||(g=l.querySelector(io(m)),g||(n=x({src:n,async:!0},r),(r=er.get(m))&&Id(n,r),g=l.createElement("script"),Rt(g),Zi(g,"link",n),l.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(m,g))}}function Gw(n,r){Zr.M(n,r);var l=Qa;if(l&&n){var u=Gt(l).hoistableScripts,m=el(n),g=u.get(m);g||(g=l.querySelector(io(m)),g||(n=x({src:n,async:!0,type:"module"},r),(r=er.get(m))&&Id(n,r),g=l.createElement("script"),Rt(g),Zi(g,"link",n),l.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(m,g))}}function B_(n,r,l,u){var m=(m=ae.current)?Uc(m):null;if(!m)throw Error(s(446));switch(n){case"meta":case"title":return null;case"style":return typeof l.precedence=="string"&&typeof l.href=="string"?(r=Ja(l.href),l=Gt(m).hoistableStyles,u=l.get(r),u||(u={type:"style",instance:null,count:0,state:null},l.set(r,u)),u):{type:"void",instance:null,count:0,state:null};case"link":if(l.rel==="stylesheet"&&typeof l.href=="string"&&typeof l.precedence=="string"){n=Ja(l.href);var g=Gt(m).hoistableStyles,y=g.get(n);if(y||(m=m.ownerDocument||m,y={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},g.set(n,y),(g=m.querySelector(to(n)))&&!g._p&&(y.instance=g,y.state.loading=5),er.has(n)||(l={rel:"preload",as:"style",href:l.href,crossOrigin:l.crossOrigin,integrity:l.integrity,media:l.media,hrefLang:l.hrefLang,referrerPolicy:l.referrerPolicy},er.set(n,l),g||Yw(m,n,l,y.state))),r&&u===null)throw Error(s(528,""));return y}if(r&&u!==null)throw Error(s(529,""));return null;case"script":return r=l.async,l=l.src,typeof l=="string"&&r&&typeof r!="function"&&typeof r!="symbol"?(r=el(l),l=Gt(m).hoistableScripts,u=l.get(r),u||(u={type:"script",instance:null,count:0,state:null},l.set(r,u)),u):{type:"void",instance:null,count:0,state:null};default:throw Error(s(444,n))}}function Ja(n){return'href="'+gi(n)+'"'}function to(n){return'link[rel="stylesheet"]['+n+"]"}function L_(n){return x({},n,{"data-precedence":n.precedence,precedence:null})}function Yw(n,r,l,u){n.querySelector('link[rel="preload"][as="style"]['+r+"]")?u.loading=1:(r=n.createElement("link"),u.preload=r,r.addEventListener("load",function(){return u.loading|=1}),r.addEventListener("error",function(){return u.loading|=2}),Zi(r,"link",l),Rt(r),n.head.appendChild(r))}function el(n){return'[src="'+gi(n)+'"]'}function io(n){return"script[async]"+n}function O_(n,r,l){if(r.count++,r.instance===null)switch(r.type){case"style":var u=n.querySelector('style[data-href~="'+gi(l.href)+'"]');if(u)return r.instance=u,Rt(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"),Rt(u),Zi(u,"style",m),$c(u,l.precedence,n),r.instance=u;case"stylesheet":m=Ja(l.href);var g=n.querySelector(to(m));if(g)return r.state.loading|=4,r.instance=g,Rt(g),g;u=L_(l),(m=er.get(m))&&Pd(u,m),g=(n.ownerDocument||n).createElement("link"),Rt(g);var y=g;return y._p=new Promise(function(k,B){y.onload=k,y.onerror=B}),Zi(g,"link",u),r.state.loading|=4,$c(g,l.precedence,n),r.instance=g;case"script":return g=el(l.src),(m=n.querySelector(io(g)))?(r.instance=m,Rt(m),m):(u=l,(m=er.get(g))&&(u=x({},l),Id(u,m)),n=n.ownerDocument||n,m=n.createElement("script"),Rt(m),Zi(m,"link",u),n.head.appendChild(m),r.instance=m);case"void":return null;default:throw Error(s(443,r.type))}else r.type==="stylesheet"&&(r.state.loading&4)===0&&(u=r.instance,r.state.loading|=4,$c(u,l.precedence,n));return r.instance}function $c(n,r,l){for(var u=l.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),m=u.length?u[u.length-1]:null,g=m,y=0;y title"):null)}function Kw(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 I_(n){return!(n.type==="stylesheet"&&(n.state.loading&3)===0)}function Vw(n,r,l,u){if(l.type==="stylesheet"&&(typeof u.media!="string"||matchMedia(u.media).matches!==!1)&&(l.state.loading&4)===0){if(l.instance===null){var m=Ja(u.href),g=r.querySelector(to(m));if(g){r=g._p,r!==null&&typeof r=="object"&&typeof r.then=="function"&&(n.count++,n=qc.bind(n),r.then(n,n)),l.state.loading|=4,l.instance=g,Rt(g);return}g=r.ownerDocument||r,u=L_(u),(m=er.get(m))&&Pd(u,m),g=g.createElement("link"),Rt(g);var y=g;y._p=new Promise(function(k,B){y.onload=k,y.onerror=B}),Zi(g,"link",u),l.instance=g}n.stylesheets===null&&(n.stylesheets=new Map),n.stylesheets.set(l,r),(r=l.state.preload)&&(l.state.loading&3)===0&&(n.count++,l=qc.bind(n),r.addEventListener("load",l),r.addEventListener("error",l))}}var Hd=0;function Xw(n,r){return n.stylesheets&&n.count===0&&Gc(n,n.stylesheets),0Hd?50:800)+r);return n.unsuspend=l,function(){n.unsuspend=null,clearTimeout(u),clearTimeout(m)}}:null}function qc(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Gc(this,this.stylesheets);else if(this.unsuspend){var n=this.unsuspend;this.unsuspend=null,n()}}}var Wc=null;function Gc(n,r){n.stylesheets=null,n.unsuspend!==null&&(n.count++,Wc=new Map,r.forEach(Zw,n),Wc=null,qc.call(n))}function Zw(n,r){if(!(r.state.loading&4)){var l=Wc.get(n);if(l)var u=l.get(null);else{l=new Map,Wc.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(),Vd.exports=pC(),Vd.exports}var gC=mC();const xC=zu(gC);function _C({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 bC({onSetup:e}){const[t,i]=w.useState(""),[s,a]=w.useState(""),[o,c]=w.useState(null),[h,p]=w.useState(!1),f=async _=>{if(_.preventDefault(),!t.trim()||t.length<4){c("Passphrase must be at least 4 characters");return}if(t!==s){c("Passphrases do not match");return}p(!0),c(null);const x=await e(t);x&&c(x),p(!1)};return d.jsx("div",{className:"flex h-screen items-center justify-center p-4",children:d.jsx("div",{className:"w-full max-w-sm",children:d.jsxs("div",{className:"border-border rounded border p-6",children:[d.jsxs("div",{className:"mb-6 text-center",children:[d.jsx("h1",{className:"text-accent text-lg font-bold tracking-tight",children:"PlotLink OWS"}),d.jsx("p",{className:"text-muted mt-1 text-xs",children:"first-time setup"})]}),d.jsx("p",{className:"text-muted mb-4 text-xs leading-relaxed",children:"Choose a passphrase to protect your local writer agent. This will be used to unlock the app and secure your OWS wallet."}),d.jsxs("form",{onSubmit:f,className:"space-y-4",children:[d.jsxs("div",{children:[d.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Passphrase"}),d.jsx("input",{type:"password",value:t,onChange:_=>i(_.target.value),placeholder:"choose a passphrase",autoFocus:!0,className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Confirm"}),d.jsx("input",{type:"password",value:s,onChange:_=>a(_.target.value),placeholder:"repeat passphrase",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"})]}),o&&d.jsx("p",{className:"text-error text-xs",children:o}),d.jsx("button",{type:"submit",disabled:h||!t.trim()||!s.trim(),className:"border-accent text-accent hover:bg-accent/10 disabled:opacity-40 w-full rounded border px-4 py-2 text-sm font-medium transition-colors",children:h?"setting up...":"create passphrase"})]})]})})})}const Jd="http://localhost:7777";function jy({token:e}){const[t,i]=w.useState(null),[s,a]=w.useState(!1),[o,c]=w.useState(null),[h,p]=w.useState(!1),[f,_]=w.useState(null),x=w.useCallback((E,N)=>fetch(E,{...N,headers:{...N==null?void 0:N.headers,Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),[e]),b=w.useCallback(()=>{x(`${Jd}/api/wallet`).then(E=>E.json()).then(E=>i(E)).catch(()=>i({exists:!1,error:"Failed to load wallet"}))},[x]);w.useEffect(()=>{b()},[b]);const v=async()=>{a(!0),_(null);try{const E=await x(`${Jd}/api/wallet/create`,{method:"POST"}),N=await E.json();if(!E.ok)throw new Error(N.error||"Creation failed");b()}catch(E){_(E instanceof Error?E.message:"Failed to create wallet")}a(!1)},S=async E=>{c(E.walletId||E.name),_(null);try{const N=await x(`${Jd}/api/wallet/active`,{method:"POST",body:JSON.stringify({walletId:E.walletId,name:E.name,address:E.normalizedAddress||E.address})}),I=await N.json();if(!N.ok)throw new Error(I.error||"Wallet switch failed");b()}catch(N){_(N instanceof Error?N.message:"Failed to switch wallet")}c(null)},j=()=>{t!=null&&t.address&&(navigator.clipboard.writeText(t.address),p(!0),setTimeout(()=>p(!1),2e3))},R=E=>`${E.slice(0,6)}...${E.slice(-4)}`;return d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"OWS Wallet"}),!t&&d.jsx("p",{className:"text-muted text-xs",children:"loading..."}),t&&!t.exists&&d.jsxs("div",{className:"space-y-3",children:[d.jsx("p",{className:"text-muted text-xs",children:t.error||"No wallet created yet. Create one to enable autonomous transactions."}),f&&d.jsx("p",{className:"text-error text-xs",children:f}),d.jsx("button",{onClick:v,disabled:s,className:"border-accent text-accent hover:bg-accent/10 disabled:opacity-40 rounded border px-4 py-2 text-xs font-medium transition-colors",children:s?"creating...":"create wallet"})]}),(t==null?void 0:t.selectionRequired)&&t.wallets&&t.wallets.length>0&&d.jsxs("div",{className:"mb-4 space-y-3 rounded border border-amber-600/30 bg-amber-950/10 p-3",children:[d.jsx("p",{className:"text-xs text-amber-700",children:"Multiple OWS wallets found. Select the wallet OWS should use for publishing and signing."}),t.wallets.map(E=>d.jsxs("div",{className:"border-border flex items-center justify-between gap-3 rounded border p-2",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsx("p",{className:"text-foreground truncate text-xs font-medium",children:E.name}),d.jsx("p",{className:"text-muted truncate text-[10px] font-mono",children:E.address||"No EVM address"})]}),d.jsx("button",{onClick:()=>S(E),disabled:!E.address||o===(E.walletId||E.name),className:"border-accent text-accent hover:bg-accent/10 disabled:opacity-40 rounded border px-2 py-1 text-[10px] font-medium transition-colors",children:o===(E.walletId||E.name)?"switching...":"use"})]},E.walletId||E.name)),f&&d.jsx("p",{className:"text-error text-xs",children:f})]}),t&&t.exists&&t.address&&d.jsxs("div",{className:"space-y-3",children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-muted text-[10px] uppercase tracking-wider",children:"Active Wallet (Base)"}),d.jsx("span",{className:`rounded border px-1.5 py-0.5 text-[9px] ${t.ethBalance&&parseFloat(t.ethBalance)>0?"border-accent/30 text-accent":"border-accent-dim/30 text-accent-dim"}`,children:t.ethBalance&&parseFloat(t.ethBalance)>0?"active":"no balance"})]}),t.name&&d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Name"}),d.jsx("span",{className:"text-foreground truncate pl-3 font-mono text-[10px]",children:t.name})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("code",{className:"text-foreground bg-surface rounded px-2 py-1 text-xs font-mono",children:R(t.address)}),d.jsx("button",{onClick:j,className:"text-muted hover:text-accent text-xs transition-colors",children:h?"copied":"copy"})]}),d.jsxs("div",{className:"border-border space-y-1 border-t pt-3",children:[d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"ETH"}),d.jsxs("span",{className:"text-foreground font-medium",children:[t.ethBalance||"0.000000"," ETH"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"USDC"}),d.jsxs("span",{className:"text-foreground font-medium",children:["$",t.usdcBalance||"0.00"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"PLOT"}),d.jsxs("span",{className:"text-foreground font-medium",children:[t.plotBalance||"0.0000"," PLOT"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Network"}),d.jsx("span",{className:"text-foreground",children:"Base"})]})]}),t.wallets&&t.wallets.length>1&&d.jsxs("div",{className:"border-border space-y-2 border-t pt-3",children:[d.jsx("p",{className:"text-muted text-[10px] font-medium uppercase tracking-wider",children:"Switch Wallet"}),t.wallets.map(E=>d.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsxs("p",{className:E.active?"text-accent truncate font-medium":"text-foreground truncate",children:[E.name,E.active?" (active)":""]}),d.jsx("p",{className:"text-muted truncate text-[10px] font-mono",children:E.address||"No EVM address"})]}),!E.active&&d.jsx("button",{onClick:()=>S(E),disabled:!E.address||o===(E.walletId||E.name),className:"border-border text-muted hover:border-accent hover:text-accent disabled:opacity-40 rounded border px-2 py-1 text-[10px] transition-colors",children:o===(E.walletId||E.name)?"...":"use"})]},E.walletId||E.name)),f&&d.jsx("p",{className:"text-error text-xs",children:f})]}),d.jsxs("div",{className:"border-border border-t pt-3",children:[d.jsx("p",{className:"text-muted mb-2 text-[10px] font-medium uppercase tracking-wider",children:"Fund Wallet"}),d.jsx("p",{className:"text-muted text-[10px]",children:"Send ETH on Base for gas (~$0.01 per publish):"}),d.jsx("code",{className:"text-foreground bg-surface mt-1 block break-all rounded px-2 py-1.5 text-[10px] font-mono",children:t.address})]})]}),(t==null?void 0:t.exists)&&d.jsx("button",{onClick:v,disabled:s,className:"border-border text-muted hover:border-accent hover:text-accent disabled:opacity-40 mt-4 rounded border px-3 py-1.5 text-[10px] font-medium transition-colors",children:s?"creating...":"create another wallet"})]})}function Eu(e){return!!e&&e.codex.installed&&e.codex.auth==="unknown"}const Up="Codex is installed but its capabilities couldn't be read — you may need to log in to Codex (resolve outside OWS), then re-check.";function vC({token:e,onLogout:t}){const[i,s]=w.useState(""),[a,o]=w.useState(""),[c,h]=w.useState(null),[p,f]=w.useState(!1),[_,x]=w.useState(!1),[b,v]=w.useState(null),[S,j]=w.useState("AI Writer"),[R,E]=w.useState(""),[N,I]=w.useState(""),[te,F]=w.useState(!1),[D,ie]=w.useState(null),[fe,Se]=w.useState(""),[H,ce]=w.useState(null),[W,K]=w.useState(!1),[X,U]=w.useState(null),[A,O]=w.useState(null),[$,xe]=w.useState(null),T=w.useCallback((ne,ae)=>fetch(ne,{...ae,headers:{...ae==null?void 0:ae.headers,Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),[e]);w.useEffect(()=>{T("/api/settings/link-status").then(ne=>ne.json()).then(ne=>v(ne)).catch(()=>v({linked:!1}))},[]),w.useEffect(()=>{T("/api/agent/readiness").then(ne=>ne.ok?ne.json():null).then(ne=>{ne&&xe(ne)}).catch(()=>{})},[]);const M=async()=>{if(!S.trim()){ie("Agent name is required");return}if(!R.trim()){ie("Description is required");return}F(!0),ie(null);try{const ne=await T("/api/settings/register-agent",{method:"POST",body:JSON.stringify({name:S,description:R,...N.trim()&&{genre:N}})}),ae=await ne.json();if(!ne.ok)throw new Error(ae.error||"Registration failed");v({linked:!0,agentId:ae.agentId,owsWallet:ae.owsWallet,txHash:ae.txHash})}catch(ne){ie(ne instanceof Error?ne.message:"Registration failed")}F(!1)},G=async()=>{if(!fe.trim()||!/^0x[a-fA-F0-9]{40}$/.test(fe)){U("Enter a valid wallet address (0x...)");return}K(!0),U(null),ce(null);try{const ne=await T("/api/settings/generate-binding",{method:"POST",body:JSON.stringify({humanWallet:fe})}),ae=await ne.json();if(!ne.ok)throw new Error(ae.error||"Failed to generate binding code");ce(ae)}catch(ne){U(ne instanceof Error?ne.message:"Failed to generate binding code")}K(!1)},C=async(ne,ae)=>{await navigator.clipboard.writeText(ne),O(ae),setTimeout(()=>O(null),2e3)},V=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 ne=await T("/api/auth/reset-passphrase",{method:"POST",body:JSON.stringify({passphrase:i})});if(!ne.ok){const ae=await ne.json();throw new Error(ae.error||"Reset failed")}f(!0),s(""),o(""),setTimeout(()=>f(!1),3e3)}catch(ne){h(ne instanceof Error?ne.message:"Reset failed")}x(!1)};return d.jsxs("div",{className:"mx-auto max-w-lg space-y-6 p-6",children:[d.jsx("h2",{className:"text-accent text-lg font-bold",children:"Settings"}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Agent Identity"}),b!=null&&b.linked?d.jsxs("div",{className:"space-y-2",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"text-sm font-medium text-accent",children:"Registered"}),d.jsxs("span",{className:"text-muted text-xs",children:["Agent #",b.agentId]})]}),b.owsWallet&&d.jsxs("p",{className:"text-muted text-xs font-mono",children:["Wallet: ",b.owsWallet.slice(0,6),"...",b.owsWallet.slice(-4)]}),b.owner&&d.jsxs("p",{className:"text-muted text-xs font-mono",children:["Owner: ",b.owner.slice(0,6),"...",b.owner.slice(-4)]}),b.txHash&&d.jsx("p",{className:"text-muted text-xs",children:d.jsx("a",{href:`https://basescan.org/tx/${b.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View transaction on BaseScan"})}),d.jsx("p",{className:"text-muted text-xs",children:d.jsx("a",{href:`https://plotlink.xyz/profile/${b.owsWallet}`,target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View agent profile on plotlink.xyz"})})]}):d.jsxs("div",{className:"space-y-3",children:[d.jsx("p",{className:"text-muted text-xs",children:"Register this AI writer on-chain via ERC-8004. Uses your OWS wallet's existing ETH balance for gas."}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Name"}),d.jsx("input",{value:S,onChange:ne=>j(ne.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:R,onChange:ne=>E(ne.target.value),placeholder:"An AI writing assistant for fiction stories",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Genre (optional)"}),d.jsx("input",{value:N,onChange:ne=>I(ne.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:M,disabled:te||!S.trim()||!R.trim(),className:"bg-accent text-white hover:bg-accent-dim disabled:opacity-50 w-full rounded px-4 py-2 text-sm font-medium transition-colors",children:te?"Registering...":"Register Agent Identity"})]})]}),d.jsxs("div",{className:"border-border rounded border p-4","data-testid":"provider-readiness",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Agent Providers"}),d.jsxs("div",{className:"space-y-2",children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Claude"}),d.jsx("span",{className:"text-muted text-xs",children:$!=null&&$.claude.installed?"Installed":"Not detected"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Codex"}),d.jsx("span",{className:"text-muted text-xs",children:$!=null&&$.codex.installed?"Installed":"Not detected"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Codex version"}),d.jsx("span",{className:"text-muted text-xs font-mono",children:($==null?void 0:$.codex.version)??"—"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Image generation"}),d.jsx("span",{className:"text-muted text-xs",children:($==null?void 0:$.codex.imageGeneration)??"unknown"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Codex auth"}),d.jsx("span",{className:"text-muted text-xs","data-testid":"codex-auth-status",children:$!=null&&$.codex.installed?$.codex.auth==="ok"?"ok":"unclear":"—"})]}),Eu($)&&d.jsx("p",{className:"text-[11px] text-amber-700","data-testid":"codex-auth-unknown-settings",children:Up}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Last checked"}),d.jsx("span",{className:"text-muted text-xs",children:$!=null&&$.checkedAt?new Date($.checkedAt).toLocaleString():"—"})]})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Link to PlotLink"}),b!=null&&b.owner?d.jsxs("p",{className:"text-muted text-xs",children:["Linked to owner ",d.jsxs("span",{className:"font-mono",children:[b.owner.slice(0,6),"...",b.owner.slice(-4)]})]}):d.jsxs("div",{className:"space-y-3",children:[d.jsx("p",{className:"text-muted text-xs",children:"Link this OWS wallet to your PlotLink account so your stories appear under your profile on plotlink.xyz."}),d.jsxs("div",{className:"text-muted text-xs space-y-1 pl-3",children:[d.jsx("p",{children:"1. Enter your PlotLink wallet address below"}),d.jsx("p",{children:'2. Click "Generate Binding Code"'}),d.jsx("p",{children:"3. Copy the code and paste it on plotlink.xyz → Agents → Link AI Writer"})]}),d.jsx("input",{value:fe,onChange:ne=>Se(ne.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&&d.jsx("p",{className:"text-error text-xs",children:X}),d.jsx("button",{onClick:G,disabled:W||!fe.trim(),className:"bg-accent text-white hover:bg-accent-dim disabled:opacity-50 w-full rounded px-4 py-2 text-sm font-medium transition-colors",children:W?"Generating...":"Generate Binding Code"}),H&&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:H.signature}),d.jsx("button",{onClick:()=>C(H.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:H.owsWallet}),d.jsx("button",{onClick:()=>C(H.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"})]})]}),H.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:H.agentId}),d.jsx("button",{onClick:()=>C(String(H.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(jy,{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:ne=>s(ne.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:ne=>o(ne.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:V,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 yC="http://localhost:7777";function SC({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(`${yC}/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 wC={published:"✓","published-not-indexed":"⚠",pending:"⏳",draft:"📝"},CC={published:"text-green-700","published-not-indexed":"text-amber-700",pending:"text-amber-700",draft:"text-muted"};function kC({authFetch:e,selectedStory:t,selectedFile:i,onSelectFile:s,onNewStory:a,untitledSessions:o=[]}){const[c,h]=w.useState([]),[p,f]=w.useState([]),[_,x]=w.useState(new Set),[b,v]=w.useState(!1),S=w.useCallback(async()=>{try{const F=await e("/api/stories");if(F.ok){const D=await F.json();h(D.stories)}}catch{}},[e]),j=w.useCallback(async()=>{try{const F=await e("/api/stories/archived");if(F.ok){const D=await F.json();f(D.stories)}}catch{}},[e]),R=w.useCallback(async F=>{try{(await e("/api/stories/restore",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:F})})).ok&&(j(),S())}catch{}},[e,j,S]);w.useEffect(()=>{S();const F=setInterval(S,5e3);return()=>clearInterval(F)},[S]),w.useEffect(()=>{b&&j()},[b,j]),w.useEffect(()=>{t&&x(F=>new Set(F).add(t))},[t]);const E=F=>{x(D=>{const ie=new Set(D);return ie.has(F)?ie.delete(F):ie.add(F),ie})},N=F=>{var ie;const D=F.map(fe=>{var Se;return{file:fe.file,num:(Se=fe.file.match(/^plot-(\d+)\.md$/))==null?void 0:Se[1]}}).filter(fe=>fe.num!=null).sort((fe,Se)=>parseInt(Se.num)-parseInt(fe.num));return D.length>0?D[0].file:F.some(fe=>fe.file==="genesis.md")?"genesis.md":F.some(fe=>fe.file==="structure.md")?"structure.md":((ie=F[0])==null?void 0:ie.file)??null},I=F=>{if(E(F.name),F.contentType==="cartoon")s(F.name,"");else{const D=N(F.files);D&&s(F.name,D)}},te=F=>{const D=ie=>{if(ie==="structure.md")return 0;if(ie==="genesis.md")return 1;const fe=ie.match(/^plot-(\d+)\.md$/);return fe?2+parseInt(fe[1]):100};return[...F].sort((ie,fe)=>D(ie.file)-D(fe.file))};return b?d.jsxs("div",{className:"h-full flex flex-col",children:[d.jsxs("div",{className:"px-3 py-1.5 border-b border-border flex items-center justify-between",children:[d.jsx("span",{className:"text-xs font-mono text-muted",children:"Archives"}),d.jsx("span",{className:"text-xs text-muted",children:p.length})]}),d.jsx("div",{className:"px-3 py-2 border-b border-border",children:d.jsxs("button",{onClick:()=>v(!1),className:"w-full px-3 py-1.5 text-sm text-muted hover:text-foreground hover:bg-surface rounded flex items-center gap-1.5",children:[d.jsx("span",{children:"←"}),d.jsx("span",{children:"Back"})]})}),d.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:p.length===0?d.jsx("div",{className:"p-3 text-sm text-muted",children:d.jsx("p",{children:"No archived stories."})}):p.map(F=>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:F.name,children:F.title||F.name}),d.jsx("button",{onClick:()=>R(F.name),className:"text-xs text-accent hover:text-accent-dim flex-shrink-0 ml-2",children:"Restore"})]},F.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(F=>d.jsx("div",{children:d.jsxs("button",{onClick:()=>s(F,""),className:`w-full px-3 py-2 text-left flex items-center gap-2 hover:bg-surface text-sm ${t===F?"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"})]})},F)),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(F=>F.name!=="_example").map(F=>d.jsxs("div",{children:[d.jsxs("button",{onClick:()=>I(F),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(F.name)?"▼":"▶"}),d.jsx("span",{className:"font-medium truncate",title:F.name,children:F.title||F.name}),F.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:[F.publishedCount,"/",F.files.length]})]}),_.has(F.name)&&d.jsx("div",{className:"pl-4",children:te(F.files).map(D=>{const ie=t===F.name&&i===D.file;return d.jsxs("button",{onClick:()=>s(F.name,D.file),className:`w-full px-3 py-1.5 text-left flex items-center gap-2 text-xs hover:bg-surface ${ie?"bg-surface font-medium":""}`,children:[d.jsx("span",{className:CC[D.status],children:wC[D.status]}),d.jsx("span",{className:"truncate font-mono",children:D.file})]},D.file)})})]},F.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 Ty=Object.defineProperty,EC=Object.getOwnPropertyDescriptor,NC=(e,t)=>{for(var i in t)Ty(e,i,{get:t[i],enumerable:!0})},ci=(e,t,i,s)=>{for(var a=s>1?void 0:s?EC(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&&Ty(t,i,a),a},De=(e,t)=>(i,s)=>t(i,s,e),cb="Terminal input",Hf={get:()=>cb,set:e=>cb=e},ub="Too much output to announce, navigate to rows manually to read",Uf={get:()=>ub,set:e=>ub=e};function jC(e){return e.replace(/\r?\n/g,"\r")}function TC(e,t){return t?"\x1B[200~"+e+"\x1B[201~":e}function AC(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()}function RC(e,t,i,s){if(e.stopPropagation(),e.clipboardData){let a=e.clipboardData.getData("text/plain");Ay(a,t,i,s)}}function Ay(e,t,i,s){e=jC(e),e=TC(e,i.decPrivateModes.bracketedPasteMode&&s.rawOptions.ignoreBracketedPasteMode!==!0),i.triggerDataEvent(e,!0),t.value=""}function Ry(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 hb(e,t,i,s,a){Ry(e,t,i),a&&s.rightClickSelect(e),t.value=s.selectionText,t.select()}function zs(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function Pu(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 DC=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}},MC=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let i=e.length;if(!i)return 0;let s=0,a,o,c,h,p=0,f=0;if(this.interim[0]){let b=!1,v=this.interim[0];v&=(v&224)===192?31:(v&240)===224?15:7;let S=0,j;for(;(j=this.interim[++S]&63)&&S<4;)v<<=6,v|=j;let R=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,E=R-S;for(;f=i)return 0;if(j=e[f++],(j&192)!==128){f--,b=!0;break}else this.interim[S++]=j,v<<=6,v|=j&63}b||(R===2?v<128?f--:t[s++]=v:R===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}},Dy="",Is=" ",Po=class My{constructor(){this.fg=0,this.bg=0,this.extended=new Nu}static toColorRGB(t){return[t>>>16&255,t>>>8&255,t&255]}static fromColorRGB(t){return(t[0]&255)<<16|(t[1]&255)<<8|t[2]&255}clone(){let t=new My;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)===50331648}isBgRGB(){return(this.bg&50331648)===50331648}isFgPalette(){return(this.fg&50331648)===16777216||(this.fg&50331648)===33554432}isBgPalette(){return(this.bg&50331648)===16777216||(this.bg&50331648)===33554432}isFgDefault(){return(this.fg&50331648)===0}isBgDefault(){return(this.bg&50331648)===0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===16777216||(this.extended.underlineColor&50331648)===33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===0:this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},Nu=class By{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 By(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},sr=class Ly extends Po{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new Nu,this.combinedData=""}static fromCharData(t){let i=new Ly;return i.setFromCharData(t),i}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?zs(this.content&2097151):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(t){this.fg=t[0],this.bg=0;let i=!1;if(t[1].length>2)i=!0;else if(t[1].length===2){let s=t[1].charCodeAt(0);if(55296<=s&&s<=56319){let a=t[1].charCodeAt(1);56320<=a&&a<=57343?this.content=(s-55296)*1024+a-56320+65536|t[2]<<22:i=!0}else i=!0}else this.content=t[1].charCodeAt(0)|t[2]<<22;i&&(this.combinedData=t[1],this.content=2097152|t[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},db="di$target",$f="di$dependencies",ef=new Map;function BC(e){return e[$f]||[]}function $i(e){if(ef.has(e))return ef.get(e);let t=function(i,s,a){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");LC(t,i,a)};return t._id=e,ef.set(e,t),t}function LC(e,t,i){t[db]===t?t[$f].push({id:e,index:i}):(t[$f]=[{id:e,index:i}],t[db]=t)}var pn=$i("BufferService"),Oy=$i("CoreMouseService"),ba=$i("CoreService"),OC=$i("CharsetService"),$p=$i("InstantiationService"),zy=$i("LogService"),mn=$i("OptionsService"),Py=$i("OscLinkService"),zC=$i("UnicodeService"),Io=$i("DecorationService"),Ff=class{constructor(e,t,i){this._bufferService=e,this._optionsService=t,this._oscLinkService=i}provideLinks(e,t){var _;let i=this._bufferService.buffer.lines.get(e-1);if(!i){t(void 0);return}let s=[],a=this._optionsService.rawOptions.linkHandler,o=new sr,c=i.getTrimmedLength(),h=-1,p=-1,f=!1;for(let x=0;xa?a.activate(j,R,v):PC(j,R),hover:(j,R)=>{var E;return(E=a==null?void 0:a.hover)==null?void 0:E.call(a,j,R,v)},leave:(j,R)=>{var E;return(E=a==null?void 0:a.leave)==null?void 0:E.call(a,j,R,v)}})}f=!1,o.hasExtendedAttrs()&&o.extended.urlId?(p=x,h=o.extended.urlId):(p=-1,h=-1)}}t(s)}};Ff=ci([De(0,pn),De(1,mn),De(2,Py)],Ff);function PC(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 Iu=$i("CharSizeService"),ns=$i("CoreBrowserService"),Fp=$i("MouseService"),rs=$i("RenderService"),IC=$i("SelectionService"),Iy=$i("CharacterJoinerService"),xl=$i("ThemeService"),Hy=$i("LinkProviderService"),HC=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?fb.isErrorNoTelemetry(e)?new fb(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)}},UC=new HC;function gu(e){$C(e)||UC.onUnexpectedError(e)}var qf="Canceled";function $C(e){return e instanceof FC?!0:e instanceof Error&&e.name===qf&&e.message===qf}var FC=class extends Error{constructor(){super(qf),this.name=this.message}};function qC(e){return new Error(`Illegal argument: ${e}`)}var fb=class Wf extends Error{constructor(t){super(t),this.name="CodeExpectedError"}static fromError(t){if(t instanceof Wf)return t;let i=new Wf;return i.message=t.message,i.stack=t.stack,i}static isErrorNoTelemetry(t){return t.name==="CodeExpectedError"}},Gf=class Uy extends Error{constructor(t){super(t||"An unexpected bug occurred."),Object.setPrototypeOf(this,Uy.prototype)}};function On(e,t=0){return e[e.length-(1+t)]}var WC;(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})(WC||(WC={}));function GC(e,t){let i=this,s=!1,a;return function(){return s||(s=!0,t||(a=e.apply(i,arguments))),a}}var $y;(e=>{function t(te){return te&&typeof te=="object"&&typeof te[Symbol.iterator]=="function"}e.is=t;let i=Object.freeze([]);function s(){return i}e.empty=s;function*a(te){yield te}e.single=a;function o(te){return t(te)?te:a(te)}e.wrap=o;function c(te){return te||i}e.from=c;function*h(te){for(let F=te.length-1;F>=0;F--)yield te[F]}e.reverse=h;function p(te){return!te||te[Symbol.iterator]().next().done===!0}e.isEmpty=p;function f(te){return te[Symbol.iterator]().next().value}e.first=f;function _(te,F){let D=0;for(let ie of te)if(F(ie,D++))return!0;return!1}e.some=_;function x(te,F){for(let D of te)if(F(D))return D}e.find=x;function*b(te,F){for(let D of te)F(D)&&(yield D)}e.filter=b;function*v(te,F){let D=0;for(let ie of te)yield F(ie,D++)}e.map=v;function*S(te,F){let D=0;for(let ie of te)yield*F(ie,D++)}e.flatMap=S;function*j(...te){for(let F of te)yield*F}e.concat=j;function R(te,F,D){let ie=D;for(let fe of te)ie=F(ie,fe);return ie}e.reduce=R;function*E(te,F,D=te.length){for(F<0&&(F+=te.length),D<0?D+=te.length:D>te.length&&(D=te.length);F1)throw new AggregateError(t,"Encountered errors while disposing of store");return Array.isArray(e)?[]:e}else if(e)return e.dispose(),e}function YC(...e){return ii(()=>ga(e))}function ii(e){return{dispose:GC(()=>{e()})}}var Fy=class qy{constructor(){this._toDispose=new Set,this._isDisposed=!1}dispose(){this._isDisposed||(this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{ga(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw new Error("Cannot register a disposable on itself!");return this._isDisposed?qy.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)}};Fy.DISABLE_DISPOSED_WARNING=!1;var Hs=Fy,ut=class{constructor(){this._store=new Hs,this._store}dispose(){this._store.dispose()}_register(t){if(t===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(t)}};ut.None=Object.freeze({dispose(){}});var pl=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){var t;this._isDisposed||e===this._value||((t=this._value)==null||t.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){var e;this._isDisposed=!0,(e=this._value)==null||e.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e}},is=typeof window=="object"?window:globalThis,Yf=class Kf{constructor(t){this.element=t,this.next=Kf.Undefined,this.prev=Kf.Undefined}};Yf.Undefined=new Yf(void 0);var ni=Yf,pb=class{constructor(){this._first=ni.Undefined,this._last=ni.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===ni.Undefined}clear(){let e=this._first;for(;e!==ni.Undefined;){let t=e.next;e.prev=ni.Undefined,e.next=ni.Undefined,e=t}this._first=ni.Undefined,this._last=ni.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let i=new ni(e);if(this._first===ni.Undefined)this._first=i,this._last=i;else if(t){let a=this._last;this._last=i,i.prev=a,a.next=i}else{let a=this._first;this._first=i,i.next=a,a.prev=i}this._size+=1;let s=!1;return()=>{s||(s=!0,this._remove(i))}}shift(){if(this._first!==ni.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==ni.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==ni.Undefined&&e.next!==ni.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===ni.Undefined&&e.next===ni.Undefined?(this._first=ni.Undefined,this._last=ni.Undefined):e.next===ni.Undefined?(this._last=this._last.prev,this._last.next=ni.Undefined):e.prev===ni.Undefined&&(this._first=this._first.next,this._first.prev=ni.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==ni.Undefined;)yield e.element,e=e.next}},KC=globalThis.performance&&typeof globalThis.performance.now=="function",VC=class Wy{static create(t){return new Wy(t)}constructor(t){this._now=KC&&t===!1?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime!==-1?this._stopTime-this._startTime:this._now()-this._startTime}},en;(e=>{e.None=()=>ut.None;function t(W,K){return x(W,()=>{},0,void 0,!0,void 0,K)}e.defer=t;function i(W){return(K,X=null,U)=>{let A=!1,O;return O=W($=>{if(!A)return O?O.dispose():A=!0,K.call(X,$)},null,U),A&&O.dispose(),O}}e.once=i;function s(W,K,X){return f((U,A=null,O)=>W($=>U.call(A,K($)),null,O),X)}e.map=s;function a(W,K,X){return f((U,A=null,O)=>W($=>{K($),U.call(A,$)},null,O),X)}e.forEach=a;function o(W,K,X){return f((U,A=null,O)=>W($=>K($)&&U.call(A,$),null,O),X)}e.filter=o;function c(W){return W}e.signal=c;function h(...W){return(K,X=null,U)=>{let A=YC(...W.map(O=>O($=>K.call(X,$))));return _(A,U)}}e.any=h;function p(W,K,X,U){let A=X;return s(W,O=>(A=K(A,O),A),U)}e.reduce=p;function f(W,K){let X,U={onWillAddFirstListener(){X=W(A.fire,A)},onDidRemoveLastListener(){X==null||X.dispose()}},A=new Ce(U);return K==null||K.add(A),A.event}function _(W,K){return K instanceof Array?K.push(W):K&&K.add(W),W}function x(W,K,X=100,U=!1,A=!1,O,$){let xe,T,M,G=0,C,V={leakWarningThreshold:O,onWillAddFirstListener(){xe=W(ae=>{G++,T=K(T,ae),U&&!M&&(ne.fire(T),T=void 0),C=()=>{let Y=T;T=void 0,M=void 0,(!U||G>1)&&ne.fire(Y),G=0},typeof X=="number"?(clearTimeout(M),M=setTimeout(C,X)):M===void 0&&(M=0,queueMicrotask(C))})},onWillRemoveListener(){A&&G>0&&(C==null||C())},onDidRemoveLastListener(){C=void 0,xe.dispose()}},ne=new Ce(V);return $==null||$.add(ne),ne.event}e.debounce=x;function b(W,K=0,X){return e.debounce(W,(U,A)=>U?(U.push(A),U):[A],K,void 0,!0,void 0,X)}e.accumulate=b;function v(W,K=(U,A)=>U===A,X){let U=!0,A;return o(W,O=>{let $=U||!K(O,A);return U=!1,A=O,$},X)}e.latch=v;function S(W,K,X){return[e.filter(W,K,X),e.filter(W,U=>!K(U),X)]}e.split=S;function j(W,K=!1,X=[],U){let A=X.slice(),O=W(T=>{A?A.push(T):xe.fire(T)});U&&U.add(O);let $=()=>{A==null||A.forEach(T=>xe.fire(T)),A=null},xe=new Ce({onWillAddFirstListener(){O||(O=W(T=>xe.fire(T)),U&&U.add(O))},onDidAddFirstListener(){A&&(K?setTimeout($):$())},onDidRemoveLastListener(){O&&O.dispose(),O=null}});return U&&U.add(xe),xe.event}e.buffer=j;function R(W,K){return(X,U,A)=>{let O=K(new N);return W(function($){let xe=O.evaluate($);xe!==E&&X.call(U,xe)},void 0,A)}}e.chain=R;let E=Symbol("HaltChainable");class N{constructor(){this.steps=[]}map(K){return this.steps.push(K),this}forEach(K){return this.steps.push(X=>(K(X),X)),this}filter(K){return this.steps.push(X=>K(X)?X:E),this}reduce(K,X){let U=X;return this.steps.push(A=>(U=K(U,A),U)),this}latch(K=(X,U)=>X===U){let X=!0,U;return this.steps.push(A=>{let O=X||!K(A,U);return X=!1,U=A,O?A:E}),this}evaluate(K){for(let X of this.steps)if(K=X(K),K===E)break;return K}}function I(W,K,X=U=>U){let U=(...xe)=>$.fire(X(...xe)),A=()=>W.on(K,U),O=()=>W.removeListener(K,U),$=new Ce({onWillAddFirstListener:A,onDidRemoveLastListener:O});return $.event}e.fromNodeEventEmitter=I;function te(W,K,X=U=>U){let U=(...xe)=>$.fire(X(...xe)),A=()=>W.addEventListener(K,U),O=()=>W.removeEventListener(K,U),$=new Ce({onWillAddFirstListener:A,onDidRemoveLastListener:O});return $.event}e.fromDOMEventEmitter=te;function F(W){return new Promise(K=>i(W)(K))}e.toPromise=F;function D(W){let K=new Ce;return W.then(X=>{K.fire(X)},()=>{K.fire(void 0)}).finally(()=>{K.dispose()}),K.event}e.fromPromise=D;function ie(W,K){return W(X=>K.fire(X))}e.forward=ie;function fe(W,K,X){return K(X),W(U=>K(U))}e.runAndSubscribe=fe;class Se{constructor(K,X){this._observable=K,this._counter=0,this._hasChanged=!1;let U={onWillAddFirstListener:()=>{K.addObserver(this)},onDidRemoveLastListener:()=>{K.removeObserver(this)}};this.emitter=new Ce(U),X&&X.add(this.emitter)}beginUpdate(K){this._counter++}handlePossibleChange(K){}handleChange(K,X){this._hasChanged=!0}endUpdate(K){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function H(W,K){return new Se(W,K).emitter.event}e.fromObservable=H;function ce(W){return(K,X,U)=>{let A=0,O=!1,$={beginUpdate(){A++},endUpdate(){A--,A===0&&(W.reportChanges(),O&&(O=!1,K.call(X)))},handlePossibleChange(){},handleChange(){O=!0}};W.addObserver($),W.reportChanges();let xe={dispose(){W.removeObserver($)}};return U instanceof Hs?U.add(xe):Array.isArray(U)&&U.push(xe),xe}}e.fromObservableLight=ce})(en||(en={}));var Vf=class Xf{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${Xf._idPool++}`,Xf.all.add(this)}start(t){this._stopWatch=new VC,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}}};Vf.all=new Set,Vf._idPool=0;var XC=Vf,ZC=-1,Gy=class Yy{constructor(t,i,s=(Yy._idPool++).toString(16).padStart(3,"0")){this._errorHandler=t,this.threshold=i,this.name=s,this._warnCountdown=0}dispose(){var t;(t=this._stacks)==null||t.clear()}check(t,i){let s=this.threshold;if(s<=0||i{let o=this._stacks.get(t.value)||0;this._stacks.set(t.value,o-1)}}getMostFrequentStack(){if(!this._stacks)return;let t,i=0;for(let[s,a]of this._stacks)(!t||i{var h,p,f,_,x;if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let b=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(b);let v=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],S=new tk(`${b}. HINT: Stack shows most frequent listener (${v[1]}-times)`,v[0]);return(((h=this._options)==null?void 0:h.onListenerError)||gu)(S),ut.None}if(this._disposed)return ut.None;i&&(t=t.bind(i));let a=new tf(t),o;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(a.stack=JC.create(),o=this._leakageMon.check(a.stack,this._size+1)),this._listeners?this._listeners instanceof tf?(this._deliveryQueue??(this._deliveryQueue=new sk),this._listeners=[this._listeners,a]):this._listeners.push(a):((f=(p=this._options)==null?void 0:p.onWillAddFirstListener)==null||f.call(p,this),this._listeners=a,(x=(_=this._options)==null?void 0:_.onDidAddFirstListener)==null||x.call(_,this)),this._size++;let c=ii(()=>{o==null||o(),this._removeListener(a)});return s instanceof Hs?s.add(c):Array.isArray(s)&&s.push(c),c}),this._event}_removeListener(t){var o,c,h,p;if((c=(o=this._options)==null?void 0:o.onWillRemoveListener)==null||c.call(o,this),!this._listeners)return;if(this._size===1){this._listeners=void 0,(p=(h=this._options)==null?void 0:h.onDidRemoveLastListener)==null||p.call(h,this),this._size=0;return}let i=this._listeners,s=i.indexOf(t);if(s===-1)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),new Error("Attempted to dispose unknown listener");this._size--,i[s]=void 0;let a=this._deliveryQueue.current===this;if(this._size*nk<=i.length){let f=0;for(let _=0;_0}},sk=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,i){this.i=0,this.end=i,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},Zf=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new Ce,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new Ce,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(t){return this.mapWindowIdToZoomLevel.get(this.getWindowId(t))??0}setZoomLevel(t,i){if(this.getZoomLevel(i)===t)return;let s=this.getWindowId(i);this.mapWindowIdToZoomLevel.set(s,t),this._onDidChangeZoomLevel.fire(s)}getZoomFactor(t){return this.mapWindowIdToZoomFactor.get(this.getWindowId(t))??1}setZoomFactor(t,i){this.mapWindowIdToZoomFactor.set(this.getWindowId(i),t)}setFullscreen(t,i){if(this.isFullscreen(i)===t)return;let s=this.getWindowId(i);this.mapWindowIdToFullScreen.set(s,t),this._onDidChangeFullscreen.fire(s)}isFullscreen(t){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(t))}getWindowId(t){return t.vscodeWindowId}};Zf.INSTANCE=new Zf;var qp=Zf;function ak(e,t,i){typeof t=="string"&&(t=e.matchMedia(t)),t.addEventListener("change",i)}qp.INSTANCE.onDidChangeZoomLevel;function lk(e){return qp.INSTANCE.getZoomFactor(e)}qp.INSTANCE.onDidChangeFullscreen;var _l=typeof navigator=="object"?navigator.userAgent:"",Qf=_l.indexOf("Firefox")>=0,ok=_l.indexOf("AppleWebKit")>=0,Wp=_l.indexOf("Chrome")>=0,ck=!Wp&&_l.indexOf("Safari")>=0;_l.indexOf("Electron/")>=0;_l.indexOf("Android")>=0;var nf=!1;if(typeof is.matchMedia=="function"){let e=is.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)"),t=is.matchMedia("(display-mode: fullscreen)");nf=e.matches,ak(is,e,({matches:i})=>{nf&&t.matches||(nf=i)})}var cl="en",Jf=!1,ep=!1,xu=!1,Vy=!1,eu,_u=cl,mb=cl,uk,dr,ma=globalThis,Ji,ky;typeof ma.vscode<"u"&&typeof ma.vscode.process<"u"?Ji=ma.vscode.process:typeof process<"u"&&typeof((ky=process==null?void 0:process.versions)==null?void 0:ky.node)=="string"&&(Ji=process);var Ey,hk=typeof((Ey=Ji==null?void 0:Ji.versions)==null?void 0:Ey.electron)=="string",dk=hk&&(Ji==null?void 0:Ji.type)==="renderer",Ny;if(typeof Ji=="object"){Jf=Ji.platform==="win32",ep=Ji.platform==="darwin",xu=Ji.platform==="linux",xu&&Ji.env.SNAP&&Ji.env.SNAP_REVISION,Ji.env.CI||Ji.env.BUILD_ARTIFACTSTAGINGDIRECTORY,eu=cl,_u=cl;let e=Ji.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);eu=t.userLocale,mb=t.osLocale,_u=t.resolvedLanguage||cl,uk=(Ny=t.languagePack)==null?void 0:Ny.translationsConfigFile}catch{}Vy=!0}else typeof navigator=="object"&&!dk?(dr=navigator.userAgent,Jf=dr.indexOf("Windows")>=0,ep=dr.indexOf("Macintosh")>=0,(dr.indexOf("Macintosh")>=0||dr.indexOf("iPad")>=0||dr.indexOf("iPhone")>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0,xu=dr.indexOf("Linux")>=0,(dr==null?void 0:dr.indexOf("Mobi"))>=0,_u=globalThis._VSCODE_NLS_LANGUAGE||cl,eu=navigator.language.toLowerCase(),mb=eu):console.error("Unable to resolve platform.");var Xy=Jf,Rr=ep,fk=xu,gb=Vy,Dr=dr,Ms=_u,pk;(e=>{function t(){return Ms}e.value=t;function i(){return Ms.length===2?Ms==="en":Ms.length>=3?Ms[0]==="e"&&Ms[1]==="n"&&Ms[2]==="-":!1}e.isDefaultVariant=i;function s(){return Ms==="en"}e.isDefault=s})(pk||(pk={}));var mk=typeof ma.postMessage=="function"&&!ma.importScripts;(()=>{if(mk){let e=[];ma.addEventListener("message",i=>{if(i.data&&i.data.vscodeScheduleAsyncWork)for(let s=0,a=e.length;s{let s=++t;e.push({id:s,callback:i}),ma.postMessage({vscodeScheduleAsyncWork:s},"*")}}return e=>setTimeout(e)})();var gk=!!(Dr&&Dr.indexOf("Chrome")>=0);Dr&&Dr.indexOf("Firefox")>=0;!gk&&Dr&&Dr.indexOf("Safari")>=0;Dr&&Dr.indexOf("Edg/")>=0;Dr&&Dr.indexOf("Android")>=0;var il=typeof navigator=="object"?navigator:{};gb||document.queryCommandSupported&&document.queryCommandSupported("copy")||il&&il.clipboard&&il.clipboard.writeText,gb||il&&il.clipboard&&il.clipboard.readText;var Gp=class{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e}keyCodeToStr(e){return this._keyCodeToStr[e]}strToKeyCode(e){return this._strToKeyCode[e.toLowerCase()]||0}},rf=new Gp,xb=new Gp,_b=new Gp,xk=new Array(230),Zy;(e=>{function t(h){return rf.keyCodeToStr(h)}e.toString=t;function i(h){return rf.strToKeyCode(h)}e.fromString=i;function s(h){return xb.keyCodeToStr(h)}e.toUserSettingsUS=s;function a(h){return _b.keyCodeToStr(h)}e.toUserSettingsGeneral=a;function o(h){return xb.strToKeyCode(h)||_b.strToKeyCode(h)}e.fromUserSettings=o;function c(h){if(h>=98&&h<=113)return null;switch(h){case 16:return"Up";case 18:return"Down";case 15:return"Left";case 17:return"Right"}return rf.keyCodeToStr(h)}e.toElectronAccelerator=c})(Zy||(Zy={}));var _k=class Qy{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 Qy&&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 bk([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},bk=class{constructor(e){if(e.length===0)throw qC("chords");this.chords=e}getHashCode(){let e="";for(let t=0,i=this.chords.length;t{function t(i){return i===e.None||i===e.Cancelled||i instanceof jk?!0:!i||typeof i!="object"?!1:typeof i.isCancellationRequested=="boolean"&&typeof i.onCancellationRequested=="function"}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:en.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:Jy})})(Nk||(Nk={}));var jk=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?Jy:(this._emitter||(this._emitter=new Ce),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}},Yp=class{constructor(e,t){this._isDisposed=!1,this._token=-1,typeof e=="function"&&typeof t=="number"&&this.setIfNotSet(e,t)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._token!==-1&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(e,t){if(this._isDisposed)throw new Gf("Calling 'cancelAndSet' on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new Gf("Calling 'setIfNotSet' on a disposed TimeoutTimer");this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},Tk=class{constructor(){this.disposable=void 0,this.isDisposed=!1}cancel(){var e;(e=this.disposable)==null||e.dispose(),this.disposable=void 0}cancelAndSet(e,t,i=globalThis){if(this.isDisposed)throw new Gf("Calling 'cancelAndSet' on a disposed IntervalTimer");this.cancel();let s=i.setInterval(()=>{e()},t);this.disposable=ii(()=>{i.clearInterval(s),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}},Ak;(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})(Ak||(Ak={}));var Sb=class ir{static fromArray(t){return new ir(i=>{i.emitMany(t)})}static fromPromise(t){return new ir(async i=>{i.emitMany(await t)})}static fromPromises(t){return new ir(async i=>{await Promise.all(t.map(async s=>i.emitOne(await s)))})}static merge(t){return new ir(async i=>{await Promise.all(t.map(async s=>{for await(let a of s)i.emitOne(a)}))})}constructor(t,i){this._state=0,this._results=[],this._error=null,this._onReturn=i,this._onStateChanged=new Ce,queueMicrotask(async()=>{let s={emitOne:a=>this.emitOne(a),emitMany:a=>this.emitMany(a),reject:a=>this.reject(a)};try{await Promise.resolve(t(s)),this.resolve()}catch(a){this.reject(a)}finally{s.emitOne=void 0,s.emitMany=void 0,s.reject=void 0}})}[Symbol.asyncIterator](){let t=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(t{var i;return(i=this._onReturn)==null||i.call(this),{done:!0,value:void 0}}}}static map(t,i){return new ir(async s=>{for await(let a of t)s.emitOne(i(a))})}map(t){return ir.map(this,t)}static filter(t,i){return new ir(async s=>{for await(let a of t)i(a)&&s.emitOne(a)})}filter(t){return ir.filter(this,t)}static coalesce(t){return ir.filter(t,i=>!!i)}coalesce(){return ir.coalesce(this)}static async toPromise(t){let i=[];for await(let s of t)i.push(s);return i}toPromise(){return ir.toPromise(this)}emitOne(t){this._state===0&&(this._results.push(t),this._onStateChanged.fire())}emitMany(t){this._state===0&&(this._results=this._results.concat(t),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(t){this._state===0&&(this._state=2,this._error=t,this._onStateChanged.fire())}};Sb.EMPTY=Sb.fromArray([]);var{getWindow:Tr,getWindowId:Rk,onDidRegisterWindow:Dk}=(function(){let e=new Map,t={window:is,disposables:new Hs};e.set(is.vscodeWindowId,t);let i=new Ce,s=new Ce,a=new Ce;function o(c,h){return(typeof c=="number"?e.get(c):void 0)??(h?t:void 0)}return{onDidRegisterWindow:i.event,onWillUnregisterWindow:a.event,onDidUnregisterWindow:s.event,registerWindow(c){if(e.has(c.vscodeWindowId))return ut.None;let h=new Hs,p={window:c,disposables:h.add(new Hs)};return e.set(c.vscodeWindowId,p),h.add(ii(()=>{e.delete(c.vscodeWindowId),s.fire(c)})),h.add(Xe(c,Bi.BEFORE_UNLOAD,()=>{a.fire(c)})),i.fire(p),h},getWindows(){return e.values()},getWindowsCount(){return e.size},getWindowId(c){return c.vscodeWindowId},hasWindow(c){return e.has(c)},getWindowById:o,getWindow(c){var f;let h=c;if((f=h==null?void 0:h.ownerDocument)!=null&&f.defaultView)return h.ownerDocument.defaultView.window;let p=c;return p!=null&&p.view?p.view.window:is},getDocument(c){return Tr(c).document}}})(),Mk=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 Xe(e,t,i,s){return new Mk(e,t,i,s)}var wb=function(e,t,i,s){return Xe(e,t,i,s)},Kp,Bk=class extends Tk{constructor(e){super(),this.defaultTarget=e&&Tr(e)}cancelAndSet(e,t,i){return super.cancelAndSet(e,t,i??this.defaultTarget)}},Cb=class{constructor(e,t=0){this._runner=e,this.priority=t,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(e){gu(e)}}static sort(e,t){return t.priority-e.priority}};(function(){let e=new Map,t=new Map,i=new Map,s=new Map,a=o=>{i.set(o,!1);let c=e.get(o)??[];for(t.set(o,c),e.set(o,[]),s.set(o,!0);c.length>0;)c.sort(Cb.sort),c.shift().execute();s.set(o,!1)};Kp=(o,c,h=0)=>{let p=Rk(o),f=new Cb(c,h),_=e.get(p);return _||(_=[],e.set(p,_)),_.push(f),i.get(p)||(i.set(p,!0),o.requestAnimationFrame(()=>a(p))),f}})();function Lk(e){let t=e.getBoundingClientRect(),i=Tr(e);return{left:t.left+i.scrollX,top:t.top+i.scrollY,width:t.width,height:t.height}}var Bi={CLICK:"click",MOUSE_DOWN:"mousedown",MOUSE_OVER:"mouseover",MOUSE_LEAVE:"mouseleave",MOUSE_WHEEL:"wheel",POINTER_UP:"pointerup",POINTER_DOWN:"pointerdown",POINTER_MOVE:"pointermove",KEY_DOWN:"keydown",KEY_UP:"keyup",BEFORE_UNLOAD:"beforeunload",CHANGE:"change",FOCUS:"focus",BLUR:"blur",INPUT:"input"},Ok=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=Sn(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=Sn(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=Sn(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=Sn(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=Sn(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=Sn(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=Sn(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=Sn(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=Sn(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=Sn(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=Sn(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=Sn(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=Sn(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=Sn(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 Sn(e){return typeof e=="number"?`${e}px`:e}function Eo(e){return new Ok(e)}var e0=class{constructor(){this._hooks=new Hs,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(e,t){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let i=this._onStopCallback;this._onStopCallback=null,e&&i&&i(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,i,s,a){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=s,this._onStopCallback=a;let o=e;try{e.setPointerCapture(t),this._hooks.add(ii(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{o=Tr(e)}this._hooks.add(Xe(o,Bi.POINTER_MOVE,c=>{if(c.buttons!==i){this.stopMonitoring(!0);return}c.preventDefault(),this._pointerMoveCallback(c)})),this._hooks.add(Xe(o,Bi.POINTER_UP,c=>this.stopMonitoring(!0)))}};function zk(e,t,i){let s=null,a=null;if(typeof i.value=="function"?(s="value",a=i.value,a.length!==0&&console.warn("Memoize should only be used in functions with zero parameters")):typeof i.get=="function"&&(s="get",a=i.get),!a)throw new Error("not supported");let o=`$memoize$${t}`;i[s]=function(...c){return this.hasOwnProperty(o)||Object.defineProperty(this,o,{configurable:!1,enumerable:!1,writable:!1,value:a.apply(this,c)}),this[o]}}var Nr;(e=>(e.Tap="-xterm-gesturetap",e.Change="-xterm-gesturechange",e.Start="-xterm-gesturestart",e.End="-xterm-gesturesend",e.Contextmenu="-xterm-gesturecontextmenu"))(Nr||(Nr={}));var yo=class nn extends ut{constructor(){super(),this.dispatched=!1,this.targets=new pb,this.ignoreTargets=new pb,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(en.runAndSubscribe(Dk,({window:t,disposables:i})=>{i.add(Xe(t.document,"touchstart",s=>this.onTouchStart(s),{passive:!1})),i.add(Xe(t.document,"touchend",s=>this.onTouchEnd(t,s))),i.add(Xe(t.document,"touchmove",s=>this.onTouchMove(s),{passive:!1}))},{window:is,disposables:this._store}))}static addTarget(t){if(!nn.isTouchDevice())return ut.None;nn.INSTANCE||(nn.INSTANCE=new nn);let i=nn.INSTANCE.targets.push(t);return ii(i)}static ignoreTarget(t){if(!nn.isTouchDevice())return ut.None;nn.INSTANCE||(nn.INSTANCE=new nn);let i=nn.INSTANCE.ignoreTargets.push(t);return ii(i)}static isTouchDevice(){return"ontouchstart"in is||navigator.maxTouchPoints>0}dispose(){this.handle&&(this.handle.dispose(),this.handle=null),super.dispose()}onTouchStart(t){let i=Date.now();this.handle&&(this.handle.dispose(),this.handle=null);for(let s=0,a=t.targetTouches.length;s=nn.HOLD_DELAY&&Math.abs(p.initialPageX-On(p.rollingPageX))<30&&Math.abs(p.initialPageY-On(p.rollingPageY))<30){let _=this.newGestureEvent(Nr.Contextmenu,p.initialTarget);_.pageX=On(p.rollingPageX),_.pageY=On(p.rollingPageY),this.dispatchEvent(_)}else if(a===1){let _=On(p.rollingPageX),x=On(p.rollingPageY),b=On(p.rollingTimestamps)-p.rollingTimestamps[0],v=_-p.rollingPageX[0],S=x-p.rollingPageY[0],j=[...this.targets].filter(R=>p.initialTarget instanceof Node&&R.contains(p.initialTarget));this.inertia(t,j,s,Math.abs(v)/b,v>0?1:-1,_,Math.abs(S)/b,S>0?1:-1,x)}this.dispatchEvent(this.newGestureEvent(Nr.End,p.initialTarget)),delete this.activeTouches[h.identifier]}this.dispatched&&(i.preventDefault(),i.stopPropagation(),this.dispatched=!1)}newGestureEvent(t,i){let s=document.createEvent("CustomEvent");return s.initEvent(t,!1,!0),s.initialTarget=i,s.tapCount=0,s}dispatchEvent(t){if(t.type===Nr.Tap){let i=new Date().getTime(),s=0;i-this._lastSetTapCountTime>nn.CLEAR_TAP_COUNT_TIME?s=1:s=2,this._lastSetTapCountTime=i,t.tapCount=s}else(t.type===Nr.Change||t.type===Nr.Contextmenu)&&(this._lastSetTapCountTime=0);if(t.initialTarget instanceof Node){for(let s of this.ignoreTargets)if(s.contains(t.initialTarget))return;let i=[];for(let s of this.targets)if(s.contains(t.initialTarget)){let a=0,o=t.initialTarget;for(;o&&o!==s;)a++,o=o.parentElement;i.push([a,s])}i.sort((s,a)=>s[0]-a[0]);for(let[s,a]of i)a.dispatchEvent(t),this.dispatched=!0}}inertia(t,i,s,a,o,c,h,p,f){this.handle=Kp(t,()=>{let _=Date.now(),x=_-s,b=0,v=0,S=!0;a+=nn.SCROLL_FRICTION*x,h+=nn.SCROLL_FRICTION*x,a>0&&(S=!1,b=o*a*x),h>0&&(S=!1,v=p*h*x);let j=this.newGestureEvent(Nr.Change);j.translationX=b,j.translationY=v,i.forEach(R=>R.dispatchEvent(j)),S||this.inertia(t,i,_,a,o,c+b,h,p,f+v)})}onTouchMove(t){let i=Date.now();for(let s=0,a=t.changedTouches.length;s3&&(c.rollingPageX.shift(),c.rollingPageY.shift(),c.rollingTimestamps.shift()),c.rollingPageX.push(o.pageX),c.rollingPageY.push(o.pageY),c.rollingTimestamps.push(i)}this.dispatched&&(t.preventDefault(),t.stopPropagation(),this.dispatched=!1)}};yo.SCROLL_FRICTION=-.005,yo.HOLD_DELAY=700,yo.CLEAR_TAP_COUNT_TIME=400,ci([zk],yo,"isTouchDevice",1);var Pk=yo,Vp=class extends ut{onclick(e,t){this._register(Xe(e,Bi.CLICK,i=>t(new tu(Tr(e),i))))}onmousedown(e,t){this._register(Xe(e,Bi.MOUSE_DOWN,i=>t(new tu(Tr(e),i))))}onmouseover(e,t){this._register(Xe(e,Bi.MOUSE_OVER,i=>t(new tu(Tr(e),i))))}onmouseleave(e,t){this._register(Xe(e,Bi.MOUSE_LEAVE,i=>t(new tu(Tr(e),i))))}onkeydown(e,t){this._register(Xe(e,Bi.KEY_DOWN,i=>t(new bb(i))))}onkeyup(e,t){this._register(Xe(e,Bi.KEY_UP,i=>t(new bb(i))))}oninput(e,t){this._register(Xe(e,Bi.INPUT,t))}onblur(e,t){this._register(Xe(e,Bi.BLUR,t))}onfocus(e,t){this._register(Xe(e,Bi.FOCUS,t))}onchange(e,t){this._register(Xe(e,Bi.CHANGE,t))}ignoreGesture(e){return Pk.ignoreTarget(e)}},kb=11,Ik=class extends Vp{constructor(e){super(),this._onActivate=e.onActivate,this.bgDomNode=document.createElement("div"),this.bgDomNode.className="arrow-background",this.bgDomNode.style.position="absolute",this.bgDomNode.style.width=e.bgWidth+"px",this.bgDomNode.style.height=e.bgHeight+"px",typeof e.top<"u"&&(this.bgDomNode.style.top="0px"),typeof e.left<"u"&&(this.bgDomNode.style.left="0px"),typeof e.bottom<"u"&&(this.bgDomNode.style.bottom="0px"),typeof e.right<"u"&&(this.bgDomNode.style.right="0px"),this.domNode=document.createElement("div"),this.domNode.className=e.className,this.domNode.style.position="absolute",this.domNode.style.width=kb+"px",this.domNode.style.height=kb+"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 e0),this._register(wb(this.bgDomNode,Bi.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._register(wb(this.domNode,Bi.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._pointerdownRepeatTimer=this._register(new Bk),this._pointerdownScheduleRepeatTimer=this._register(new Yp)}_arrowPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,Tr(e))};this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet(t,200),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,i=>{},()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()}),e.preventDefault()}},Hk=class tp{constructor(t,i,s,a,o,c,h){this._forceIntegerValues=t,this._scrollStateBrand=void 0,this._forceIntegerValues&&(i=i|0,s=s|0,a=a|0,o=o|0,c=c|0,h=h|0),this.rawScrollLeft=a,this.rawScrollTop=h,i<0&&(i=0),a+i>s&&(a=s-i),a<0&&(a=0),o<0&&(o=0),h+o>c&&(h=c-o),h<0&&(h=0),this.width=i,this.scrollWidth=s,this.scrollLeft=a,this.height=o,this.scrollHeight=c,this.scrollTop=h}equals(t){return this.rawScrollLeft===t.rawScrollLeft&&this.rawScrollTop===t.rawScrollTop&&this.width===t.width&&this.scrollWidth===t.scrollWidth&&this.scrollLeft===t.scrollLeft&&this.height===t.height&&this.scrollHeight===t.scrollHeight&&this.scrollTop===t.scrollTop}withScrollDimensions(t,i){return new tp(this._forceIntegerValues,typeof t.width<"u"?t.width:this.width,typeof t.scrollWidth<"u"?t.scrollWidth:this.scrollWidth,i?this.rawScrollLeft:this.scrollLeft,typeof t.height<"u"?t.height:this.height,typeof t.scrollHeight<"u"?t.scrollHeight:this.scrollHeight,i?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new tp(this._forceIntegerValues,this.width,this.scrollWidth,typeof t.scrollLeft<"u"?t.scrollLeft:this.rawScrollLeft,this.height,this.scrollHeight,typeof t.scrollTop<"u"?t.scrollTop:this.rawScrollTop)}createScrollEvent(t,i){let s=this.width!==t.width,a=this.scrollWidth!==t.scrollWidth,o=this.scrollLeft!==t.scrollLeft,c=this.height!==t.height,h=this.scrollHeight!==t.scrollHeight,p=this.scrollTop!==t.scrollTop;return{inSmoothScrolling:i,oldWidth:t.width,oldScrollWidth:t.scrollWidth,oldScrollLeft:t.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:t.height,oldScrollHeight:t.scrollHeight,oldScrollTop:t.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:s,scrollWidthChanged:a,scrollLeftChanged:o,heightChanged:c,scrollHeightChanged:h,scrollTopChanged:p}}},Uk=class extends ut{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new Ce),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new Hk(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 Nb(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=Nb.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)))}},Eb=class{constructor(e,t,i){this.scrollLeft=e,this.scrollTop=t,this.isDone=i}};function sf(e,t){let i=t-e;return function(s){return e+i*qk(s)}}function $k(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":"")))}},Gk=140,t0=class extends Vp{constructor(e){super(),this._lazyRender=e.lazyRender,this._host=e.host,this._scrollable=e.scrollable,this._scrollByPage=e.scrollByPage,this._scrollbarState=e.scrollbarState,this._visibilityController=this._register(new Wk(e.visibility,"visible scrollbar "+e.extraScrollbarClassName,"invisible scrollbar "+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new e0),this._shouldRender=!0,this.domNode=Eo(document.createElement("div")),this.domNode.setAttribute("role","presentation"),this.domNode.setAttribute("aria-hidden","true"),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition("absolute"),this._register(Xe(this.domNode.domNode,Bi.POINTER_DOWN,t=>this._domNodePointerDown(t)))}_createArrow(e){let t=this._register(new Ik(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,i,s){this.slider=Eo(document.createElement("div")),this.slider.setClassName("slider"),this.slider.setPosition("absolute"),this.slider.setTop(e),this.slider.setLeft(t),typeof i=="number"&&this.slider.setWidth(i),typeof s=="number"&&this.slider.setHeight(s),this.slider.setLayerHinting(!0),this.slider.setContain("strict"),this.domNode.domNode.appendChild(this.slider.domNode),this._register(Xe(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=Lk(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(Xy&&c>Gk){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()}},i0=class np{constructor(t,i,s,a,o,c){this._scrollbarSize=Math.round(i),this._oppositeScrollbarSize=Math.round(s),this._arrowSize=Math.round(t),this._visibleSize=a,this._scrollSize=o,this._scrollPosition=c,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new np(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(t){let i=Math.round(t);return this._visibleSize!==i?(this._visibleSize=i,this._refreshComputedValues(),!0):!1}setScrollSize(t){let i=Math.round(t);return this._scrollSize!==i?(this._scrollSize=i,this._refreshComputedValues(),!0):!1}setScrollPosition(t){let i=Math.round(t);return this._scrollPosition!==i?(this._scrollPosition=i,this._refreshComputedValues(),!0):!1}setScrollbarSize(t){this._scrollbarSize=Math.round(t)}setOppositeScrollbarSize(t){this._oppositeScrollbarSize=Math.round(t)}static _computeValues(t,i,s,a,o){let c=Math.max(0,s-t),h=Math.max(0,c-2*i),p=a>0&&a>s;if(!p)return{computedAvailableSize:Math.round(c),computedIsNeeded:p,computedSliderSize:Math.round(h),computedSliderRatio:0,computedSliderPosition:0};let f=Math.round(Math.max(20,Math.floor(s*h/a))),_=(h-f)/(a-s),x=o*_;return{computedAvailableSize:Math.round(c),computedIsNeeded:p,computedSliderSize:Math.round(f),computedSliderRatio:_,computedSliderPosition:Math.round(x)}}_refreshComputedValues(){let t=np._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=t.computedAvailableSize,this._computedIsNeeded=t.computedIsNeeded,this._computedSliderSize=t.computedSliderSize,this._computedSliderRatio=t.computedSliderRatio,this._computedSliderPosition=t.computedSliderPosition}getArrowSize(){return this._arrowSize}getScrollPosition(){return this._scrollPosition}getRectangleLargeSize(){return this._computedAvailableSize}getRectangleSmallSize(){return this._scrollbarSize}isNeeded(){return this._computedIsNeeded}getSliderSize(){return this._computedSliderSize}getSliderPosition(){return this._computedSliderPosition}getDesiredScrollPositionFromOffset(t){if(!this._computedIsNeeded)return 0;let i=t-this._arrowSize-this._computedSliderSize/2;return Math.round(i/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(t){if(!this._computedIsNeeded)return 0;let i=t-this._arrowSize,s=this._scrollPosition;return i0&&Math.abs(t.deltaY)>0)return 1;let s=.5;if((!this._isAlmostInt(t.deltaX)||!this._isAlmostInt(t.deltaY))&&(s+=.25),i){let a=Math.abs(t.deltaX),o=Math.abs(t.deltaY),c=Math.abs(i.deltaX),h=Math.abs(i.deltaY),p=Math.max(Math.min(a,c),1),f=Math.max(Math.min(o,h),1),_=Math.max(a,c),x=Math.max(o,h);_%p===0&&x%f===0&&(s-=.5)}return Math.min(Math.max(s,0),1)}_isAlmostInt(t){return Math.abs(Math.round(t)-t)<.01}};rp.INSTANCE=new rp;var Zk=rp,Qk=class extends Vp{constructor(e,t,i){super(),this._onScroll=this._register(new Ce),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new Ce),this.onWillScroll=this._onWillScroll.event,this._options=e2(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 Kk(this._scrollable,this._options,s)),this._horizontalScrollbar=this._register(new Yk(this._scrollable,this._options,s)),this._domNode=document.createElement("div"),this._domNode.className="xterm-scrollable-element "+this._options.className,this._domNode.setAttribute("role","presentation"),this._domNode.style.position="relative",this._domNode.appendChild(e),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=Eo(document.createElement("div")),this._leftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=Eo(document.createElement("div")),this._topShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=Eo(document.createElement("div")),this._topLeftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topLeftShadowDomNode.domNode)):(this._leftShadowDomNode=null,this._topShadowDomNode=null,this._topLeftShadowDomNode=null),this._listenOnDomNode=this._options.listenOnDomNode||this._domNode,this._mouseWheelToDispose=[],this._setListeningToMouseWheel(this._options.handleMouseWheel),this.onmouseover(this._listenOnDomNode,a=>this._onMouseOver(a)),this.onmouseleave(this._listenOnDomNode,a=>this._onMouseLeave(a)),this._hideTimeout=this._register(new Yp),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=ga(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(e){this._verticalScrollbar.delegatePointerDown(e)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(e){this._scrollable.setScrollDimensions(e,!1)}updateClassName(e){this._options.className=e,Rr&&(this._options.className+=" mac"),this._domNode.className="xterm-scrollable-element "+this._options.className}updateOptions(e){typeof e.handleMouseWheel<"u"&&(this._options.handleMouseWheel=e.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),typeof e.mouseWheelScrollSensitivity<"u"&&(this._options.mouseWheelScrollSensitivity=e.mouseWheelScrollSensitivity),typeof e.fastScrollSensitivity<"u"&&(this._options.fastScrollSensitivity=e.fastScrollSensitivity),typeof e.scrollPredominantAxis<"u"&&(this._options.scrollPredominantAxis=e.scrollPredominantAxis),typeof e.horizontal<"u"&&(this._options.horizontal=e.horizontal),typeof e.vertical<"u"&&(this._options.vertical=e.vertical),typeof e.horizontalScrollbarSize<"u"&&(this._options.horizontalScrollbarSize=e.horizontalScrollbarSize),typeof e.verticalScrollbarSize<"u"&&(this._options.verticalScrollbarSize=e.verticalScrollbarSize),typeof e.scrollByPage<"u"&&(this._options.scrollByPage=e.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}setRevealOnScroll(e){this._revealOnScroll=e}delegateScrollFromMouseWheelEvent(e){this._onMouseWheel(new yb(e))}_setListeningToMouseWheel(e){if(this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=ga(this._mouseWheelToDispose),e)){let t=i=>{this._onMouseWheel(new yb(i))};this._mouseWheelToDispose.push(Xe(this._listenOnDomNode,Bi.MOUSE_WHEEL,t,{passive:!1}))}}_onMouseWheel(e){var a;if((a=e.browserEvent)!=null&&a.defaultPrevented)return;let t=Zk.INSTANCE;t.acceptStandardWheelEvent(e);let i=!1;if(e.deltaY||e.deltaX){let o=e.deltaY*this._options.mouseWheelScrollSensitivity,c=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&c+o===0?c=o=0:Math.abs(o)>=Math.abs(c)?c=0:o=0),this._options.flipAxes&&([o,c]=[c,o]);let h=!Rr&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||h)&&!c&&(c=o,o=0),e.browserEvent&&e.browserEvent.altKey&&(c=c*this._options.fastScrollSensitivity,o=o*this._options.fastScrollSensitivity);let p=this._scrollable.getFutureScrollPosition(),f={};if(o){let _=jb*o,x=p.scrollTop-(_<0?Math.floor(_):Math.ceil(_));this._verticalScrollbar.writeScrollPosition(f,x)}if(c){let _=jb*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(),Vk)}},Jk=class extends Qk{constructor(e,t,i){super(e,t,i)}setScrollPosition(e){e.reuseAnimation?this._scrollable.setScrollPositionSmooth(e,e.reuseAnimation):this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}};function e2(e){let t={lazyRender:typeof e.lazyRender<"u"?e.lazyRender:!1,className:typeof e.className<"u"?e.className:"",useShadows:typeof e.useShadows<"u"?e.useShadows:!0,handleMouseWheel:typeof e.handleMouseWheel<"u"?e.handleMouseWheel:!0,flipAxes:typeof e.flipAxes<"u"?e.flipAxes:!1,consumeMouseWheelIfScrollbarIsNeeded:typeof e.consumeMouseWheelIfScrollbarIsNeeded<"u"?e.consumeMouseWheelIfScrollbarIsNeeded:!1,alwaysConsumeMouseWheel:typeof e.alwaysConsumeMouseWheel<"u"?e.alwaysConsumeMouseWheel:!1,scrollYToX:typeof e.scrollYToX<"u"?e.scrollYToX:!1,mouseWheelScrollSensitivity:typeof e.mouseWheelScrollSensitivity<"u"?e.mouseWheelScrollSensitivity:1,fastScrollSensitivity:typeof e.fastScrollSensitivity<"u"?e.fastScrollSensitivity:5,scrollPredominantAxis:typeof e.scrollPredominantAxis<"u"?e.scrollPredominantAxis:!0,mouseWheelSmoothScroll:typeof e.mouseWheelSmoothScroll<"u"?e.mouseWheelSmoothScroll:!0,arrowSize:typeof e.arrowSize<"u"?e.arrowSize:11,listenOnDomNode:typeof e.listenOnDomNode<"u"?e.listenOnDomNode:null,horizontal:typeof e.horizontal<"u"?e.horizontal:1,horizontalScrollbarSize:typeof e.horizontalScrollbarSize<"u"?e.horizontalScrollbarSize:10,horizontalSliderSize:typeof e.horizontalSliderSize<"u"?e.horizontalSliderSize:0,horizontalHasArrows:typeof e.horizontalHasArrows<"u"?e.horizontalHasArrows:!1,vertical:typeof e.vertical<"u"?e.vertical:1,verticalScrollbarSize:typeof e.verticalScrollbarSize<"u"?e.verticalScrollbarSize:10,verticalHasArrows:typeof e.verticalHasArrows<"u"?e.verticalHasArrows:!1,verticalSliderSize:typeof e.verticalSliderSize<"u"?e.verticalSliderSize:0,scrollByPage:typeof e.scrollByPage<"u"?e.scrollByPage:!1};return t.horizontalSliderSize=typeof e.horizontalSliderSize<"u"?e.horizontalSliderSize:t.horizontalScrollbarSize,t.verticalSliderSize=typeof e.verticalSliderSize<"u"?e.verticalSliderSize:t.verticalScrollbarSize,Rr&&(t.className+=" mac"),t}var sp=class extends ut{constructor(e,t,i,s,a,o,c,h){super(),this._bufferService=i,this._optionsService=c,this._renderService=h,this._onRequestScrollLines=this._register(new Ce),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let p=this._register(new Uk({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:f=>Kp(s.window,f)}));this._register(this._optionsService.onSpecificOptionChange("smoothScrollDuration",()=>{p.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new Jk(t,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},p)),this._register(this._optionsService.onMultipleOptionChange(["scrollSensitivity","fastScrollSensitivity","overviewRuler"],()=>this._scrollableElement.updateOptions(this._getChangeOptions()))),this._register(a.onProtocolChange(f=>{this._scrollableElement.updateOptions({handleMouseWheel:!(f&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(en.runAndSubscribe(o.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=o.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(ii(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=s.mainDocument.createElement("style"),t.appendChild(this._styleElement),this._register(ii(()=>this._styleElement.remove())),this._register(en.runAndSubscribe(o.onChangeColors,()=>{this._styleElement.textContent=[".xterm .xterm-scrollable-element > .scrollbar > .slider {",` background: ${o.colors.scrollbarSliderBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider:hover {",` background: ${o.colors.scrollbarSliderHoverBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider.active {",` background: ${o.colors.scrollbarSliderActiveBackground.css};`,"}"].join(` +`)})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(f=>this._handleScroll(f)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){var e;return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:((e=this._optionsService.rawOptions.overviewRuler)==null?void 0:e.width)||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),i=t-this._bufferService.buffer.ydisp;i!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(i)),this._isHandlingScroll=!1}};sp=ci([De(2,pn),De(3,ns),De(4,Oy),De(5,xl),De(6,mn),De(7,rs)],sp);var ap=class extends ut{constructor(e,t,i,s,a){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=i,this._decorationService=s,this._renderService=a,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement("div"),this._container.classList.add("xterm-decoration-container"),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(o=>this._removeDecoration(o))),this._register(ii(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){var s;let t=this._coreBrowserService.mainDocument.createElement("div");t.classList.add("xterm-decoration"),t.classList.toggle("xterm-decoration-top-layer",((s=e==null?void 0:e.options)==null?void 0:s.layer)==="top"),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,t.style.top=`${(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height}px`,t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let i=e.options.x??0;return i&&i>this._bufferService.cols&&(t.style.display="none"),this._refreshXPosition(e,t),t}_refreshStyle(e){let t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display="none",e.onRenderEmitter.fire(e.element));else{let i=this._decorationElements.get(e);i||(i=this._createElement(e),e.element=i,this._decorationElements.set(e,i),this._container.appendChild(i),e.onDispose(()=>{this._decorationElements.delete(e),i.remove()})),i.style.display=this._altBufferIsActive?"none":"block",this._altBufferIsActive||(i.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,i.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,i.style.top=`${t*this._renderService.dimensions.css.cell.height}px`,i.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(i)}}_refreshXPosition(e,t=e.element){if(!t)return;let i=e.options.x??0;(e.options.anchor||"left")==="right"?t.style.right=i?`${i*this._renderService.dimensions.css.cell.width}px`:"":t.style.left=i?`${i*this._renderService.dimensions.css.cell.width}px`:""}_removeDecoration(e){var t;(t=this._decorationElements.get(e))==null||t.remove(),this._decorationElements.delete(e),e.dispose()}};ap=ci([De(1,pn),De(2,ns),De(3,Io),De(4,rs)],ap);var t2=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(e){if(e.options.overviewRulerOptions){for(let t of this._zones)if(t.color===e.options.overviewRulerOptions.color&&t.position===e.options.overviewRulerOptions.position){if(this._lineIntersectsZone(t,e.marker.line))return;if(this._lineAdjacentToZone(t,e.marker.line,e.options.overviewRulerOptions.position)){this._addLineToZone(t,e.marker.line);return}}if(this._zonePoolIndex=e.startBufferLine&&t<=e.endBufferLine}_lineAdjacentToZone(e,t,i){return t>=e.startBufferLine-this._linePadding[i||"full"]&&t<=e.endBufferLine+this._linePadding[i||"full"]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}},kr={full:0,left:0,center:0,right:0},Bs={full:0,left:0,center:0,right:0},co={full:0,left:0,center:0,right:0},ju=class extends ut{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 t2,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement("canvas"),this._canvas.classList.add("xterm-decoration-overview-ruler"),this._refreshCanvasDimensions(),(f=this._viewportElement.parentElement)==null||f.insertBefore(this._canvas,this._viewportElement),this._register(ii(()=>{var _;return(_=this._canvas)==null?void 0:_.remove()}));let p=this._canvas.getContext("2d");if(p)this._ctx=p;else throw new Error("Ctx cannot be null");this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this._register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0))),this._register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?"none":"block"})),this._register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})),this._register(this._renderService.onRender(()=>{(!this._containerHeight||this._containerHeight!==this._screenElement.clientHeight)&&(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._register(this._optionsService.onSpecificOptionChange("overviewRuler",()=>this._queueRefresh(!0))),this._register(this._themeService.onChangeColors(()=>this._queueRefresh())),this._queueRefresh(!0)}get _width(){var e;return((e=this._optionsService.options.overviewRuler)==null?void 0:e.width)||0}_refreshDrawConstants(){let e=Math.floor((this._canvas.width-1)/3),t=Math.ceil((this._canvas.width-1)/3);Bs.full=this._canvas.width,Bs.left=e,Bs.center=t,Bs.right=e,this._refreshDrawHeightConstants(),co.full=1,co.left=1,co.center=1+Bs.left,co.right=1+Bs.left+Bs.center}_refreshDrawHeightConstants(){kr.full=Math.round(2*this._coreBrowserService.dpr);let e=this._canvas.height/this._bufferService.buffer.lines.length,t=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowserService.dpr);kr.left=t,kr.center=t,kr.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*kr.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*kr.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*kr.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*kr.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(let t of this._decorationService.decorations)this._colorZoneStore.addDecoration(t);this._ctx.lineWidth=1,this._renderRulerOutline();let e=this._colorZoneStore.zones;for(let t of e)t.position!=="full"&&this._renderColorZone(t);for(let t of e)t.position==="full"&&this._renderColorZone(t);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderRulerOutline(){this._ctx.fillStyle=this._themeService.colors.overviewRulerBorder.css,this._ctx.fillRect(0,0,1,this._canvas.height),this._optionsService.rawOptions.overviewRuler.showTopBorder&&this._ctx.fillRect(1,0,this._canvas.width-1,1),this._optionsService.rawOptions.overviewRuler.showBottomBorder&&this._ctx.fillRect(1,this._canvas.height-1,this._canvas.width-1,this._canvas.height)}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(co[e.position||"full"],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-kr[e.position||"full"]/2),Bs[e.position||"full"],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+kr[e.position||"full"]))}_queueRefresh(e,t){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=t||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};ju=ci([De(2,pn),De(3,Io),De(4,rs),De(5,mn),De(6,xl),De(7,ns)],ju);var me;(e=>(e.NUL="\0",e.SOH="",e.STX="",e.ETX="",e.EOT="",e.ENQ="",e.ACK="",e.BEL="\x07",e.BS="\b",e.HT=" ",e.LF=` +`,e.VT="\v",e.FF="\f",e.CR="\r",e.SO="",e.SI="",e.DLE="",e.DC1="",e.DC2="",e.DC3="",e.DC4="",e.NAK="",e.SYN="",e.ETB="",e.CAN="",e.EM="",e.SUB="",e.ESC="\x1B",e.FS="",e.GS="",e.RS="",e.US="",e.SP=" ",e.DEL=""))(me||(me={}));var bu;(e=>(e.PAD="€",e.HOP="",e.BPH="‚",e.NBH="ƒ",e.IND="„",e.NEL="…",e.SSA="†",e.ESA="‡",e.HTS="ˆ",e.HTJ="‰",e.VTS="Š",e.PLD="‹",e.PLU="Œ",e.RI="",e.SS2="Ž",e.SS3="",e.DCS="",e.PU1="‘",e.PU2="’",e.STS="“",e.CCH="”",e.MW="•",e.SPA="–",e.EPA="—",e.SOS="˜",e.SGCI="™",e.SCI="š",e.CSI="›",e.ST="œ",e.OSC="",e.PM="ž",e.APC="Ÿ"))(bu||(bu={}));var n0;(e=>e.ST=`${me.ESC}\\`)(n0||(n0={}));var lp=class{constructor(e,t,i,s,a,o){this._textarea=e,this._compositionView=t,this._bufferService=i,this._optionsService=s,this._coreService=a,this._renderService=o,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=""}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent="",this._dataAlreadySent="",this._compositionView.classList.add("active")}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return!1;this._finalizeComposition(!1)}return e.keyCode===229?(this._handleAnyTextareaChanges(),!1):!0}_finalizeComposition(e){if(this._compositionView.classList.remove("active"),this._isComposing=!1,e){let t={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let i;t.start+=this._dataAlreadySent.length,this._isComposing?i=this._textarea.value.substring(t.start,this._compositionPosition.start):i=this._textarea.value.substring(t.start),i.length>0&&this._coreService.triggerDataEvent(i,!0)}},0)}else{this._isSendingComposition=!1;let t=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(t,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,i=t.replace(e,"");this._dataAlreadySent=i,t.length>e.length?this._coreService.triggerDataEvent(i,!0):t.lengththis.updateCompositionElements(!0),0)}}};lp=ci([De(2,pn),De(3,mn),De(4,ba),De(5,rs)],lp);var Li=0,Oi=0,zi=0,li=0,Tb={css:"#00000000",rgba:0},wi;(e=>{function t(a,o,c,h){return h!==void 0?`#${oa(a)}${oa(o)}${oa(c)}${oa(h)}`:`#${oa(a)}${oa(o)}${oa(c)}`}e.toCss=t;function i(a,o,c,h=255){return(a<<24|o<<16|c<<8|h)>>>0}e.toRgba=i;function s(a,o,c,h){return{css:e.toCss(a,o,c,h),rgba:e.toRgba(a,o,c,h)}}e.toColor=s})(wi||(wi={}));var Qt;(e=>{function t(p,f){if(li=(f.rgba&255)/255,li===1)return{css:f.css,rgba:f.rgba};let _=f.rgba>>24&255,x=f.rgba>>16&255,b=f.rgba>>8&255,v=p.rgba>>24&255,S=p.rgba>>16&255,j=p.rgba>>8&255;Li=v+Math.round((_-v)*li),Oi=S+Math.round((x-S)*li),zi=j+Math.round((b-j)*li);let R=wi.toCss(Li,Oi,zi),E=wi.toRgba(Li,Oi,zi);return{css:R,rgba:E}}e.blend=t;function i(p){return(p.rgba&255)===255}e.isOpaque=i;function s(p,f,_){let x=vu.ensureContrastRatio(p.rgba,f.rgba,_);if(x)return wi.toColor(x>>24&255,x>>16&255,x>>8&255)}e.ensureContrastRatio=s;function a(p){let f=(p.rgba|255)>>>0;return[Li,Oi,zi]=vu.toChannels(f),{css:wi.toCss(Li,Oi,zi),rgba:f}}e.opaque=a;function o(p,f){return li=Math.round(f*255),[Li,Oi,zi]=vu.toChannels(p.rgba),{css:wi.toCss(Li,Oi,zi,li),rgba:wi.toRgba(Li,Oi,zi,li)}}e.opacity=o;function c(p,f){return li=p.rgba&255,o(p,li*f/255)}e.multiplyOpacity=c;function h(p){return[p.rgba>>24&255,p.rgba>>16&255,p.rgba>>8&255]}e.toColorRGB=h})(Qt||(Qt={}));var ri;(e=>{let t,i;try{let a=document.createElement("canvas");a.width=1,a.height=1;let o=a.getContext("2d",{willReadFrequently:!0});o&&(t=o,t.globalCompositeOperation="copy",i=t.createLinearGradient(0,0,1,1))}catch{}function s(a){if(a.match(/#[\da-f]{3,8}/i))switch(a.length){case 4:return Li=parseInt(a.slice(1,2).repeat(2),16),Oi=parseInt(a.slice(2,3).repeat(2),16),zi=parseInt(a.slice(3,4).repeat(2),16),wi.toColor(Li,Oi,zi);case 5:return Li=parseInt(a.slice(1,2).repeat(2),16),Oi=parseInt(a.slice(2,3).repeat(2),16),zi=parseInt(a.slice(3,4).repeat(2),16),li=parseInt(a.slice(4,5).repeat(2),16),wi.toColor(Li,Oi,zi,li);case 7:return{css:a,rgba:(parseInt(a.slice(1),16)<<8|255)>>>0};case 9:return{css:a,rgba:parseInt(a.slice(1),16)>>>0}}let o=a.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(o)return Li=parseInt(o[1]),Oi=parseInt(o[2]),zi=parseInt(o[3]),li=Math.round((o[5]===void 0?1:parseFloat(o[5]))*255),wi.toColor(Li,Oi,zi,li);if(!t||!i)throw new Error("css.toColor: Unsupported css format");if(t.fillStyle=i,t.fillStyle=a,typeof t.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(t.fillRect(0,0,1,1),[Li,Oi,zi,li]=t.getImageData(0,0,1,1).data,li!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:wi.toRgba(Li,Oi,zi,li),css:a}}e.toColor=s})(ri||(ri={}));var hn;(e=>{function t(s){return i(s>>16&255,s>>8&255,s&255)}e.relativeLuminance=t;function i(s,a,o){let c=s/255,h=a/255,p=o/255,f=c<=.03928?c/12.92:Math.pow((c+.055)/1.055,2.4),_=h<=.03928?h/12.92:Math.pow((h+.055)/1.055,2.4),x=p<=.03928?p/12.92:Math.pow((p+.055)/1.055,2.4);return f*.2126+_*.7152+x*.0722}e.relativeLuminance2=i})(hn||(hn={}));var vu;(e=>{function t(c,h){if(li=(h&255)/255,li===1)return h;let p=h>>24&255,f=h>>16&255,_=h>>8&255,x=c>>24&255,b=c>>16&255,v=c>>8&255;return Li=x+Math.round((p-x)*li),Oi=b+Math.round((f-b)*li),zi=v+Math.round((_-v)*li),wi.toRgba(Li,Oi,zi)}e.blend=t;function i(c,h,p){let f=hn.relativeLuminance(c>>8),_=hn.relativeLuminance(h>>8);if(Qr(f,_)>8));if(S>8));return S>R?v:j}return v}let x=a(c,h,p),b=Qr(f,hn.relativeLuminance(x>>8));if(b>8));return b>S?x:v}return x}}e.ensureContrastRatio=i;function s(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,j=Qr(hn.relativeLuminance2(b,v,S),hn.relativeLuminance2(f,_,x));for(;j0||v>0||S>0);)b-=Math.max(0,Math.ceil(b*.1)),v-=Math.max(0,Math.ceil(v*.1)),S-=Math.max(0,Math.ceil(S*.1)),j=Qr(hn.relativeLuminance2(b,v,S),hn.relativeLuminance2(f,_,x));return(b<<24|v<<16|S<<8|255)>>>0}e.reduceLuminance=s;function a(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,j=Qr(hn.relativeLuminance2(b,v,S),hn.relativeLuminance2(f,_,x));for(;j>>0}e.increaseLuminance=a;function o(c){return[c>>24&255,c>>16&255,c>>8&255,c&255]}e.toChannels=o})(vu||(vu={}));function oa(e){let t=e.toString(16);return t.length<2?"0"+t:t}function Qr(e,t){return e1){let _=this._getJoinedRanges(s,c,o,t,a);for(let x=0;x<_.length;x++)i.push(_[x])}a=f,c=o,h=this._workCell.fg,p=this._workCell.bg}o+=this._workCell.getChars().length||Is.length}if(this._bufferService.cols-a>1){let f=this._getJoinedRanges(s,c,o,t,a);for(let _=0;_=H,O=K,$=this._workCell;if(b.length>0&&K===b[0][0]&&A){let be=b.shift(),tt=this._isCellInSelection(be[0],t);for(N=be[0]+1;N=be[1]),A?(U=!0,$=new i2(this._workCell,e.translateToString(!0,be[0],be[1]),be[1]-be[0]),O=be[1]-1,X=$.getWidth()):H=be[1]}let xe=this._isCellInSelection(K,t),T=i&&K===o,M=W&&K>=f&&K<=_,G=!1;this._decorationService.forEachDecorationAtCell(K,t,void 0,be=>{G=!0});let C=$.getChars()||Is;if(C===" "&&($.isUnderline()||$.isOverline())&&(C=" "),Se=X*h-p.get(C,$.isBold(),$.isItalic()),!j)j=this._document.createElement("span");else if(R&&(xe&&fe||!xe&&!fe&&$.bg===I)&&(xe&&fe&&v.selectionForeground||$.fg===te)&&$.extended.ext===F&&M===D&&Se===ie&&!T&&!U&&!G&&A){$.isInvisible()?E+=Is:E+=C,R++;continue}else R&&(j.textContent=E),j=this._document.createElement("span"),R=0,E="";if(I=$.bg,te=$.fg,F=$.extended.ext,D=M,ie=Se,fe=xe,U&&o>=K&&o<=O&&(o=K),!this._coreService.isCursorHidden&&T&&this._coreService.isCursorInitialized){if(ce.push("xterm-cursor"),this._coreBrowserService.isFocused)c&&ce.push("xterm-cursor-blink"),ce.push(s==="bar"?"xterm-cursor-bar":s==="underline"?"xterm-cursor-underline":"xterm-cursor-block");else if(a)switch(a){case"outline":ce.push("xterm-cursor-outline");break;case"block":ce.push("xterm-cursor-block");break;case"bar":ce.push("xterm-cursor-bar");break;case"underline":ce.push("xterm-cursor-underline");break}}if($.isBold()&&ce.push("xterm-bold"),$.isItalic()&&ce.push("xterm-italic"),$.isDim()&&ce.push("xterm-dim"),$.isInvisible()?E=Is:E=$.getChars()||Is,$.isUnderline()&&(ce.push(`xterm-underline-${$.extended.underlineStyle}`),E===" "&&(E=" "),!$.isUnderlineColorDefault()))if($.isUnderlineColorRGB())j.style.textDecorationColor=`rgb(${Po.toColorRGB($.getUnderlineColor()).join(",")})`;else{let be=$.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&$.isBold()&&be<8&&(be+=8),j.style.textDecorationColor=v.ansi[be].css}$.isOverline()&&(ce.push("xterm-overline"),E===" "&&(E=" ")),$.isStrikethrough()&&ce.push("xterm-strikethrough"),M&&(j.style.textDecoration="underline");let V=$.getFgColor(),ne=$.getFgColorMode(),ae=$.getBgColor(),Y=$.getBgColorMode(),he=!!$.isInverse();if(he){let be=V;V=ae,ae=be;let tt=ne;ne=Y,Y=tt}let _e,Be,Le=!1;this._decorationService.forEachDecorationAtCell(K,t,void 0,be=>{be.options.layer!=="top"&&Le||(be.backgroundColorRGB&&(Y=50331648,ae=be.backgroundColorRGB.rgba>>8&16777215,_e=be.backgroundColorRGB),be.foregroundColorRGB&&(ne=50331648,V=be.foregroundColorRGB.rgba>>8&16777215,Be=be.foregroundColorRGB),Le=be.options.layer==="top")}),!Le&&xe&&(_e=this._coreBrowserService.isFocused?v.selectionBackgroundOpaque:v.selectionInactiveBackgroundOpaque,ae=_e.rgba>>8&16777215,Y=50331648,Le=!0,v.selectionForeground&&(ne=50331648,V=v.selectionForeground.rgba>>8&16777215,Be=v.selectionForeground)),Le&&ce.push("xterm-decoration-top");let je;switch(Y){case 16777216:case 33554432:je=v.ansi[ae],ce.push(`xterm-bg-${ae}`);break;case 50331648:je=wi.toColor(ae>>16,ae>>8&255,ae&255),this._addStyle(j,`background-color:#${Ab((ae>>>0).toString(16),"0",6)}`);break;case 0:default:he?(je=v.foreground,ce.push("xterm-bg-257")):je=v.background}switch(_e||$.isDim()&&(_e=Qt.multiplyOpacity(je,.5)),ne){case 16777216:case 33554432:$.isBold()&&V<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(V+=8),this._applyMinimumContrast(j,je,v.ansi[V],$,_e,void 0)||ce.push(`xterm-fg-${V}`);break;case 50331648:let be=wi.toColor(V>>16&255,V>>8&255,V&255);this._applyMinimumContrast(j,je,be,$,_e,Be)||this._addStyle(j,`color:#${Ab(V.toString(16),"0",6)}`);break;case 0:default:this._applyMinimumContrast(j,je,v.foreground,$,_e,Be)||he&&ce.push("xterm-fg-257")}ce.length&&(j.className=ce.join(" "),ce.length=0),!T&&!U&&!G&&A?R++:j.textContent=E,Se!==this.defaultSpacing&&(j.style.letterSpacing=`${Se}px`),x.push(j),K=O}return j&&R&&(j.textContent=E),x}_applyMinimumContrast(e,t,i,s,a,o){if(this._optionsService.rawOptions.minimumContrastRatio===1||s2(s.getCode()))return!1;let c=this._getContrastCache(s),h;if(!a&&!o&&(h=c.getColor(t.rgba,i.rgba)),h===void 0){let p=this._optionsService.rawOptions.minimumContrastRatio/(s.isDim()?2:1);h=Qt.ensureContrastRatio(a||t,o||i,p),c.setColor((a||t).rgba,(o||i).rgba,h??null)}return h?(this._addStyle(e,`color:${h.css}`),!0):!1}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute("style",`${e.getAttribute("style")||""}${t};`)}_isCellInSelection(e,t){let i=this._selectionStart,s=this._selectionEnd;return!i||!s?!1:this._columnSelectMode?i[0]<=s[0]?e>=i[0]&&t>=i[1]&&e=i[1]&&e>=s[0]&&t<=s[1]:t>i[1]&&t=i[0]&&e=i[0]}};op=ci([De(1,Iy),De(2,mn),De(3,ns),De(4,ba),De(5,Io),De(6,xl)],op);function Ab(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}},o2=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 c2(){return new o2}var af="xterm-dom-renderer-owner-",tr="xterm-rows",nu="xterm-fg-",Rb="xterm-bg-",uo="xterm-focus",ru="xterm-selection",u2=1,cp=class extends ut{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=u2++,this._rowElements=[],this._selectionRenderModel=c2(),this.onRequestRedraw=this._register(new Ce).event,this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(tr),this._rowContainer.style.lineHeight="normal",this._rowContainer.setAttribute("aria-hidden","true"),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement("div"),this._selectionContainer.classList.add(ru),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=a2(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(S=>this._injectCss(S))),this._injectCss(this._themeService.colors),this._rowFactory=h.createInstance(op,document),this._element.classList.add(af+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(S=>this._handleLinkHover(S))),this._register(this._linkifier2.onHideLinkUnderline(S=>this._handleLinkLeave(S))),this._register(ii(()=>{this._element.classList.remove(af+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new l2(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){let e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(let i of this._rowElements)i.style.width=`${this.dimensions.css.canvas.width}px`,i.style.height=`${this.dimensions.css.cell.height}px`,i.style.lineHeight=`${this.dimensions.css.cell.height}px`,i.style.overflow="hidden";this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._dimensionsStyleElement));let t=`${this._terminalSelector} .${tr} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=t,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(e){this._themeStyleElement||(this._themeStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._themeStyleElement));let t=`${this._terminalSelector} .${tr} { pointer-events: none; color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;t+=`${this._terminalSelector} .${tr} .xterm-dim { color: ${Qt.multiplyOpacity(e.foreground,.5).css};}`,t+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;let i=`blink_underline_${this._terminalClass}`,s=`blink_bar_${this._terminalClass}`,a=`blink_block_${this._terminalClass}`;t+=`@keyframes ${i} { 50% { border-bottom-style: hidden; }}`,t+=`@keyframes ${s} { 50% { box-shadow: none; }}`,t+=`@keyframes ${a} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${tr}.${uo} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${tr}.${uo} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${s} 1s step-end infinite;}${this._terminalSelector} .${tr}.${uo} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${a} 1s step-end infinite;}${this._terminalSelector} .${tr} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${tr} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${tr} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${tr} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${tr} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${ru} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${ru} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${ru} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[o,c]of e.ansi.entries())t+=`${this._terminalSelector} .${nu}${o} { color: ${c.css}; }${this._terminalSelector} .${nu}${o}.xterm-dim { color: ${Qt.multiplyOpacity(c,.5).css}; }${this._terminalSelector} .${Rb}${o} { background-color: ${c.css}; }`;t+=`${this._terminalSelector} .${nu}257 { color: ${Qt.opaque(e.background).css}; }${this._terminalSelector} .${nu}257.xterm-dim { color: ${Qt.multiplyOpacity(Qt.opaque(e.background),.5).css}; }${this._terminalSelector} .${Rb}257 { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){let e=this.dimensions.css.cell.width-this._widthCache.get("W",!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let i=this._rowElements.length;i<=t;i++){let s=this._document.createElement("div");this._rowContainer.appendChild(s),this._rowElements.push(s)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(uo),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(uo),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,i){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,i),this.renderRows(0,this._bufferService.rows-1),!e||!t||(this._selectionRenderModel.update(this._terminal,e,t,i),!this._selectionRenderModel.hasSelection))return;let s=this._selectionRenderModel.viewportStartRow,a=this._selectionRenderModel.viewportEndRow,o=this._selectionRenderModel.viewportCappedStartRow,c=this._selectionRenderModel.viewportCappedEndRow,h=this._document.createDocumentFragment();if(i){let p=e[0]>t[0];h.appendChild(this._createSelectionElement(o,p?t[0]:e[0],p?e[0]:t[0],c-o+1))}else{let p=s===o?e[0]:0,f=o===a?t[0]:this._bufferService.cols;h.appendChild(this._createSelectionElement(o,p,f));let _=c-o-1;if(h.appendChild(this._createSelectionElement(o+1,0,this._bufferService.cols,_)),o!==c){let x=a===c?t[0]:this._bufferService.cols;h.appendChild(this._createSelectionElement(c,0,x))}}this._selectionContainer.appendChild(h)}_createSelectionElement(e,t,i,s=1){let a=this._document.createElement("div"),o=t*this.dimensions.css.cell.width,c=this.dimensions.css.cell.width*(i-t);return o+c>this.dimensions.css.canvas.width&&(c=this.dimensions.css.canvas.width-o),a.style.height=`${s*this.dimensions.css.cell.height}px`,a.style.top=`${e*this.dimensions.css.cell.height}px`,a.style.left=`${o}px`,a.style.width=`${c}px`,a}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(let e of this._rowElements)e.replaceChildren()}renderRows(e,t){let i=this._bufferService.buffer,s=i.ybase+i.y,a=Math.min(i.x,this._bufferService.cols-1),o=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,c=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,h=this._optionsService.rawOptions.cursorInactiveStyle;for(let p=e;p<=t;p++){let f=p+i.ydisp,_=this._rowElements[p],x=i.lines.get(f);if(!_||!x)break;_.replaceChildren(...this._rowFactory.createRow(x,f,f===s,c,h,a,o,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${af}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,i,s,a,o){i<0&&(e=0),s<0&&(t=0);let c=this._bufferService.rows-1;i=Math.max(Math.min(i,c),0),s=Math.max(Math.min(s,c),0),a=Math.min(a,this._bufferService.cols);let h=this._bufferService.buffer,p=h.ybase+h.y,f=Math.min(h.x,a-1),_=this._optionsService.rawOptions.cursorBlink,x=this._optionsService.rawOptions.cursorStyle,b=this._optionsService.rawOptions.cursorInactiveStyle;for(let v=i;v<=s;++v){let S=v+h.ydisp,j=this._rowElements[v],R=h.lines.get(S);if(!j||!R)break;j.replaceChildren(...this._rowFactory.createRow(R,S,S===p,x,b,f,_,this.dimensions.css.cell.width,this._widthCache,o?v===i?e:0:-1,o?(v===s?t:a)-1:-1))}}};cp=ci([De(7,$p),De(8,Iu),De(9,mn),De(10,pn),De(11,ba),De(12,ns),De(13,xl)],cp);var up=class extends ut{constructor(e,t,i){super(),this._optionsService=i,this.width=0,this.height=0,this._onCharSizeChange=this._register(new Ce),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new d2(this._optionsService))}catch{this._measureStrategy=this._register(new h2(e,t,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange(["fontFamily","fontSize"],()=>this.measure()))}get hasValidSize(){return this.width>0&&this.height>0}measure(){let e=this._measureStrategy.measure();(e.width!==this.width||e.height!==this.height)&&(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};up=ci([De(2,mn)],up);var r0=class extends ut{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)}},h2=class extends r0{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}},d2=class extends r0{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}},f2=class extends ut{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 p2(this._window)),this._onDprChange=this._register(new Ce),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new Ce),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(s=>this._screenDprMonitor.setWindow(s))),this._register(en.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(Xe(this._textarea,"focus",()=>this._isFocused=!0)),this._register(Xe(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}},p2=class extends ut{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new pl),this._onDprChange=this._register(new Ce),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(ii(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=Xe(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)}},m2=class extends ut{constructor(){super(),this.linkProviders=[],this._register(ii(()=>this.linkProviders.length=0))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{let t=this.linkProviders.indexOf(e);t!==-1&&this.linkProviders.splice(t,1)}}}};function Xp(e,t,i){let s=i.getBoundingClientRect(),a=e.getComputedStyle(i),o=parseInt(a.getPropertyValue("padding-left")),c=parseInt(a.getPropertyValue("padding-top"));return[t.clientX-s.left-o,t.clientY-s.top-c]}function g2(e,t,i,s,a,o,c,h,p){if(!o)return;let f=Xp(e,t,i);if(f)return f[0]=Math.ceil((f[0]+(p?c/2:0))/c),f[1]=Math.ceil(f[1]/h),f[0]=Math.min(Math.max(f[0],1),s+(p?1:0)),f[1]=Math.min(Math.max(f[1],1),a),f}var hp=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,i,s,a){return g2(window,e,t,i,s,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,a)}getMouseReportCoords(e,t){let i=Xp(window,e,t);if(this._charSizeService.hasValidSize)return i[0]=Math.min(Math.max(i[0],0),this._renderService.dimensions.css.canvas.width-1),i[1]=Math.min(Math.max(i[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(i[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(i[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(i[0]),y:Math.floor(i[1])}}};hp=ci([De(0,rs),De(1,Iu)],hp);var x2=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=[]}},s0={};NC(s0,{getSafariVersion:()=>b2,isChromeOS:()=>c0,isFirefox:()=>a0,isIpad:()=>v2,isIphone:()=>y2,isLegacyEdge:()=>_2,isLinux:()=>Zp,isMac:()=>Au,isNode:()=>Hu,isSafari:()=>l0,isWindows:()=>o0});var Hu=typeof process<"u"&&"title"in process,Ho=Hu?"node":navigator.userAgent,Uo=Hu?"node":navigator.platform,a0=Ho.includes("Firefox"),_2=Ho.includes("Edge"),l0=/^((?!chrome|android).)*safari/i.test(Ho);function b2(){if(!l0)return 0;let e=Ho.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var Au=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(Uo),v2=Uo==="iPad",y2=Uo==="iPhone",o0=["Windows","Win16","Win32","WinCE"].includes(Uo),Zp=Uo.indexOf("Linux")>=0,c0=/\bCrOS\b/.test(Ho),u0=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()}},S2=class extends u0{_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())}}},w2=class extends u0{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},Ru=!Hu&&"requestIdleCallback"in window?w2:S2,C2=class{constructor(){this._queue=new Ru}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},dp=class extends ut{constructor(e,t,i,s,a,o,c,h,p){super(),this._rowCount=e,this._optionsService=i,this._charSizeService=s,this._coreService=a,this._coreBrowserService=h,this._renderer=this._register(new pl),this._pausedResizeTask=new C2,this._observerDisposable=this._register(new pl),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this._register(new Ce),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new Ce),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new Ce),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new Ce),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new x2((f,_)=>this._renderRows(f,_),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new k2(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(ii(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(c.onResize(()=>this._fullRefresh())),this._register(c.buffers.onBufferActivate(()=>{var f;return(f=this._renderer.value)==null?void 0:f.clear()})),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(o.onDecorationRegistered(()=>this._fullRefresh())),this._register(o.onDecorationRemoved(()=>this._fullRefresh())),this._register(this._optionsService.onMultipleOptionChange(["customGlyphs","drawBoldTextInBrightColors","letterSpacing","lineHeight","fontFamily","fontSize","fontWeight","fontWeightBold","minimumContrastRatio","rescaleOverlappingGlyphs"],()=>{this.clear(),this.handleResize(c.cols,c.rows),this._fullRefresh()})),this._register(this._optionsService.onMultipleOptionChange(["cursorBlink","cursorStyle"],()=>this.refreshRows(c.buffer.y,c.buffer.y,!0))),this._register(p.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,t),this._register(this._coreBrowserService.onWindowChange(f=>this._registerIntersectionObserver(f,t)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(e,t){if("IntersectionObserver"in e){let i=new e.IntersectionObserver(s=>this._handleIntersectionChange(s[s.length-1]),{threshold:0});i.observe(t),this._observerDisposable.value=ii(()=>i.disconnect())}}_handleIntersectionChange(e){this._isPaused=e.isIntersecting===void 0?e.intersectionRatio===0:!e.isIntersecting,!this._isPaused&&!this._charSizeService.hasValidSize&&this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,t,i=!1){if(this._isPaused){this._needsFullRefresh=!0;return}if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}let s=this._syncOutputHandler.flush();s&&(e=Math.min(e,s.start),t=Math.max(t,s.end)),i||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount)}_renderRows(e,t){if(this._renderer.value){if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),this._needsSelectionRefresh=!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0}}resize(e,t){this._rowCount=t,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw(t=>this.refreshRows(t.start,t.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){var e,t;this._renderer.value&&((t=(e=this._renderer.value).clearTextureAtlas)==null||t.call(e),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>{var i;return(i=this._renderer.value)==null?void 0:i.handleResize(e,t)}):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){var e;(e=this._renderer.value)==null||e.handleCharSizeChanged()}handleBlur(){var e;(e=this._renderer.value)==null||e.handleBlur()}handleFocus(){var e;(e=this._renderer.value)==null||e.handleFocus()}handleSelectionChanged(e,t,i){var s;this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=i,(s=this._renderer.value)==null||s.handleSelectionChanged(e,t,i)}handleCursorMove(){var e;(e=this._renderer.value)==null||e.handleCursorMove()}clear(){var e;(e=this._renderer.value)==null||e.clear()}};dp=ci([De(2,mn),De(3,Iu),De(4,ba),De(5,Io),De(6,pn),De(7,ns),De(8,xl)],dp);var k2=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 E2(e,t,i,s){let a=i.buffer.x,o=i.buffer.y;if(!i.buffer.hasScrollback)return T2(a,o,e,t,i,s)+Uu(o,t,i,s)+A2(a,o,e,t,i,s);let c;if(o===t)return c=a>e?"D":"C",Do(Math.abs(a-e),Ro(c,s));c=o>t?"D":"C";let h=Math.abs(o-t),p=j2(o>t?e:a,i)+(h-1)*i.cols+1+N2(o>t?a:e);return Do(p,Ro(c,s))}function N2(e,t){return e-1}function j2(e,t){return t.cols-e}function T2(e,t,i,s,a,o){return Uu(t,s,a,o).length===0?"":Do(d0(e,t,e,t-xa(t,a),!1,a).length,Ro("D",o))}function Uu(e,t,i,s){let a=e-xa(e,i),o=t-xa(t,i),c=Math.abs(a-o)-R2(e,t,i);return Do(c,Ro(h0(e,t),s))}function A2(e,t,i,s,a,o){let c;Uu(t,s,a,o).length>0?c=s-xa(s,a):c=t;let h=s,p=D2(e,t,i,s,a,o);return Do(d0(e,c,i,h,p==="C",a).length,Ro(p,o))}function R2(e,t,i){var c;let s=0,a=e-xa(e,i),o=t-xa(t,i);for(let h=0;h=0&&e0?c=s-xa(s,a):c=t,e=i&&ct?"A":"B"}function d0(e,t,i,s,a,o){let c=e,h=t,p="";for(;(c!==i||h!==s)&&h>=0&&ho.cols-1?(p+=o.buffer.translateBufferLineToString(h,!1,e,c),c=0,e=0,h++):!a&&c<0&&(p+=o.buffer.translateBufferLineToString(h,!1,0,e+1),c=o.cols-1,e=c,h--);return p+o.buffer.translateBufferLineToString(h,!1,e,c)}function Ro(e,t){let i=t?"O":"[";return me.ESC+i+e}function Do(e,t){e=Math.floor(e);let i="";for(let s=0;sthis._bufferService.cols?e%this._bufferService.cols===0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){let e=this.selectionStart,t=this.selectionEnd;return!e||!t?!1:e[1]>t[1]||e[1]===t[1]&&e[0]>t[0]}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}};function Db(e,t){if(e.start.y>e.end.y)throw new Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}var lf=50,B2=15,L2=50,O2=500,z2=" ",P2=new RegExp(z2,"g"),fp=class extends ut{constructor(e,t,i,s,a,o,c,h,p){super(),this._element=e,this._screenElement=t,this._linkifier=i,this._bufferService=s,this._coreService=a,this._mouseService=o,this._optionsService=c,this._renderService=h,this._coreBrowserService=p,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new sr,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new Ce),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new Ce),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new Ce),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new Ce),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=f=>this._handleMouseMove(f),this._mouseUpListener=f=>this._handleMouseUp(f),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(f=>this._handleTrim(f)),this._register(this._bufferService.buffers.onBufferActivate(f=>this._handleBufferActivate(f))),this.enable(),this._model=new M2(this._bufferService),this._activeSelectionMode=0,this._register(ii(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(f=>{f.rowsChanged&&this.clearSelection()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!e||!t?!1:e[0]!==t[0]||e[1]!==t[1]}get selectionText(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return"";let i=this._bufferService.buffer,s=[];if(this._activeSelectionMode===3){if(e[0]===t[0])return"";let a=e[0]a.replace(P2," ")).join(o0?`\r +`:` +`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),Zp&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),i=this._model.finalSelectionStart,s=this._model.finalSelectionEnd;return!i||!s||!t?!1:this._areCoordsInSelection(t,i,s)}isCellInSelection(e,t){let i=this._model.finalSelectionStart,s=this._model.finalSelectionEnd;return!i||!s?!1:this._areCoordsInSelection([e,t],i,s)}_areCoordsInSelection(e,t,i){return e[1]>t[1]&&e[1]=t[0]&&e[0]=t[0]}_selectWordAtCursor(e,t){var a,o;let i=(o=(a=this._linkifier.currentLink)==null?void 0:a.link)==null?void 0:o.range;if(i)return this._model.selectionStart=[i.start.x-1,i.start.y-1],this._model.selectionStartLength=Db(i,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let s=this._getMouseBufferCoords(e);return s?(this._selectWordAt(s,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=Xp(this._coreBrowserService.window,e,this._screenElement)[1],i=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=i?0:(t>i&&(t-=i),t=Math.min(Math.max(t,-lf),lf),t/=lf,t/Math.abs(t)+Math.round(t*(B2-1)))}shouldForceSelection(e){return Au?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),L2)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(Au&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let i=this._bufferService.buffer;if(this._model.selectionEnd[1]0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&tthis._handleTrim(t))}_convertViewportColToCharacterIndex(e,t){let i=t;for(let s=0;t>=s;s++){let a=e.loadCell(s,this._workCell).getChars().length;this._workCell.getWidth()===0?i--:a>1&&t!==s&&(i+=a-1)}return i}setSelection(e,t,i){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=i,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,i=!0,s=!0){if(e[0]>=this._bufferService.cols)return;let a=this._bufferService.buffer,o=a.lines.get(e[1]);if(!o)return;let c=a.translateBufferLineToString(e[1],!1),h=this._convertViewportColToCharacterIndex(o,e[0]),p=h,f=e[0]-h,_=0,x=0,b=0,v=0;if(c.charAt(h)===" "){for(;h>0&&c.charAt(h-1)===" ";)h--;for(;p1&&(v+=N-1,p+=N-1);R>0&&h>0&&!this._isCharWordSeparator(o.loadCell(R-1,this._workCell));){o.loadCell(R-1,this._workCell);let I=this._workCell.getChars().length;this._workCell.getWidth()===0?(_++,R--):I>1&&(b+=I-1,h-=I-1),h--,R--}for(;E1&&(v+=I-1,p+=I-1),p++,E++}}p++;let S=h+f-_+b,j=Math.min(this._bufferService.cols,p-h+_+x-b-v);if(!(!t&&c.slice(h,p).trim()==="")){if(i&&S===0&&o.getCodePoint(0)!==32){let R=a.lines.get(e[1]-1);if(R&&o.isWrapped&&R.getCodePoint(this._bufferService.cols-1)!==32){let E=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(E){let N=this._bufferService.cols-E.start;S-=N,j+=N}}}if(s&&S+j===this._bufferService.cols&&o.getCodePoint(this._bufferService.cols-1)!==32){let R=a.lines.get(e[1]+1);if(R!=null&&R.isWrapped&&R.getCodePoint(0)!==32){let E=this._getWordAt([0,e[1]+1],!1,!1,!0);E&&(j+=E.length)}}return{start:S,length:j}}}_selectWordAt(e,t){let i=this._getWordAt(e,t);if(i){for(;i.start<0;)i.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[i.start,e[1]],this._model.selectionStartLength=i.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let i=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,i--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,i++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,i]}}_isCharWordSeparator(e){return e.getWidth()===0?!1:this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),i={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=Db(i,this._bufferService.cols)}};fp=ci([De(3,pn),De(4,ba),De(5,Fp),De(6,mn),De(7,rs),De(8,ns)],fp);var Mb=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={}}},Bb=class{constructor(){this._color=new Mb,this._css=new Mb}setCss(e,t,i){this._css.set(e,t,i)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,i){this._color.set(e,t,i)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},Ti=Object.freeze((()=>{let e=[ri.toColor("#2e3436"),ri.toColor("#cc0000"),ri.toColor("#4e9a06"),ri.toColor("#c4a000"),ri.toColor("#3465a4"),ri.toColor("#75507b"),ri.toColor("#06989a"),ri.toColor("#d3d7cf"),ri.toColor("#555753"),ri.toColor("#ef2929"),ri.toColor("#8ae234"),ri.toColor("#fce94f"),ri.toColor("#729fcf"),ri.toColor("#ad7fa8"),ri.toColor("#34e2e2"),ri.toColor("#eeeeec")],t=[0,95,135,175,215,255];for(let i=0;i<216;i++){let s=t[i/36%6|0],a=t[i/6%6|0],o=t[i%6];e.push({css:wi.toCss(s,a,o),rgba:wi.toRgba(s,a,o)})}for(let i=0;i<24;i++){let s=8+i*10;e.push({css:wi.toCss(s,s,s),rgba:wi.toRgba(s,s,s)})}return e})()),da=ri.toColor("#ffffff"),So=ri.toColor("#000000"),Lb=ri.toColor("#ffffff"),Ob=So,ho={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117},I2=da,pp=class extends ut{constructor(e){super(),this._optionsService=e,this._contrastCache=new Bb,this._halfContrastCache=new Bb,this._onChangeColors=this._register(new Ce),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:da,background:So,cursor:Lb,cursorAccent:Ob,selectionForeground:void 0,selectionBackgroundTransparent:ho,selectionBackgroundOpaque:Qt.blend(So,ho),selectionInactiveBackgroundTransparent:ho,selectionInactiveBackgroundOpaque:Qt.blend(So,ho),scrollbarSliderBackground:Qt.opacity(da,.2),scrollbarSliderHoverBackground:Qt.opacity(da,.4),scrollbarSliderActiveBackground:Qt.opacity(da,.5),overviewRulerBorder:da,ansi:Ti.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange("minimumContrastRatio",()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange("theme",()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(e={}){let t=this._colors;if(t.foreground=$t(e.foreground,da),t.background=$t(e.background,So),t.cursor=Qt.blend(t.background,$t(e.cursor,Lb)),t.cursorAccent=Qt.blend(t.background,$t(e.cursorAccent,Ob)),t.selectionBackgroundTransparent=$t(e.selectionBackground,ho),t.selectionBackgroundOpaque=Qt.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=$t(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=Qt.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?$t(e.selectionForeground,Tb):void 0,t.selectionForeground===Tb&&(t.selectionForeground=void 0),Qt.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=Qt.opacity(t.selectionBackgroundTransparent,.3)),Qt.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=Qt.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=$t(e.scrollbarSliderBackground,Qt.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=$t(e.scrollbarSliderHoverBackground,Qt.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=$t(e.scrollbarSliderActiveBackground,Qt.opacity(t.foreground,.5)),t.overviewRulerBorder=$t(e.overviewRulerBorder,I2),t.ansi=Ti.slice(),t.ansi[0]=$t(e.black,Ti[0]),t.ansi[1]=$t(e.red,Ti[1]),t.ansi[2]=$t(e.green,Ti[2]),t.ansi[3]=$t(e.yellow,Ti[3]),t.ansi[4]=$t(e.blue,Ti[4]),t.ansi[5]=$t(e.magenta,Ti[5]),t.ansi[6]=$t(e.cyan,Ti[6]),t.ansi[7]=$t(e.white,Ti[7]),t.ansi[8]=$t(e.brightBlack,Ti[8]),t.ansi[9]=$t(e.brightRed,Ti[9]),t.ansi[10]=$t(e.brightGreen,Ti[10]),t.ansi[11]=$t(e.brightYellow,Ti[11]),t.ansi[12]=$t(e.brightBlue,Ti[12]),t.ansi[13]=$t(e.brightMagenta,Ti[13]),t.ansi[14]=$t(e.brightCyan,Ti[14]),t.ansi[15]=$t(e.brightWhite,Ti[15]),e.extendedAnsi){let i=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let s=0;so.index-c.index),s=[];for(let o of i){let c=this._services.get(o.id);if(!c)throw new Error(`[createInstance] ${e.name} depends on UNKNOWN service ${o.id._id}.`);s.push(c)}let a=i.length>0?i[0].index:t.length;if(t.length!==a)throw new Error(`[createInstance] First service dependency of ${e.name} at position ${a+1} conflicts with ${t.length} static arguments`);return new e(...t,...s)}},$2={trace:0,debug:1,info:2,warn:3,error:4,off:5},F2="xterm.js: ",mp=class extends ut{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=$2[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*ct+1]=i[0],i[1].length>1?(this._combined[t]=i[1],this._data[t*ct+0]=t|2097152|i[2]<<22):this._data[t*ct+0]=i[1].charCodeAt(0)|i[2]<<22}getWidth(t){return this._data[t*ct+0]>>22}hasWidth(t){return this._data[t*ct+0]&12582912}getFg(t){return this._data[t*ct+1]}getBg(t){return this._data[t*ct+2]}hasContent(t){return this._data[t*ct+0]&4194303}getCodePoint(t){let i=this._data[t*ct+0];return i&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):i&2097151}isCombined(t){return this._data[t*ct+0]&2097152}getString(t){let i=this._data[t*ct+0];return i&2097152?this._combined[t]:i&2097151?zs(i&2097151):""}isProtected(t){return this._data[t*ct+2]&536870912}loadCell(t,i){return su=t*ct,i.content=this._data[su+0],i.fg=this._data[su+1],i.bg=this._data[su+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*ct+0]=i.content,this._data[t*ct+1]=i.fg,this._data[t*ct+2]=i.bg}setCellFromCodepoint(t,i,s,a){a.bg&268435456&&(this._extendedAttrs[t]=a.extended),this._data[t*ct+0]=i|s<<22,this._data[t*ct+1]=a.fg,this._data[t*ct+2]=a.bg}addCodepointToCell(t,i,s){let a=this._data[t*ct+0];a&2097152?this._combined[t]+=zs(i):a&2097151?(this._combined[t]=zs(a&2097151)+zs(i),a&=-2097152,a|=2097152):a=i|1<<22,s&&(a&=-12582913,a|=s<<22),this._data[t*ct+0]=a}insertCells(t,i,s){if(t%=this.length,t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,s),i=0;--o)this.setCell(t+i+o,this.loadCell(t+o,a));for(let o=0;othis.length){if(this._data.buffer.byteLength>=s*4)this._data=new Uint32Array(this._data.buffer,0,s);else{let a=new Uint32Array(s);a.set(this._data),this._data=a}for(let a=this.length;a=t&&delete this._combined[h]}let o=Object.keys(this._extendedAttrs);for(let c=0;c=t&&delete this._extendedAttrs[h]}}return this.length=t,s*4*of=0;--t)if(this._data[t*ct+0]&4194303)return t+(this._data[t*ct+0]>>22);return 0}getNoBgTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*ct+0]&4194303||this._data[t*ct+2]&50331648)return t+(this._data[t*ct+0]>>22);return 0}copyCellsFrom(t,i,s,a,o){let c=t._data;if(o)for(let p=a-1;p>=0;p--){for(let f=0;f=i&&(this._combined[f-i+s]=t._combined[f])}}translateToString(t,i,s,a){i=i??0,s=s??this.length,t&&(s=Math.min(s,this.getTrimmedLength())),a&&(a.length=0);let o="";for(;i>22||1}return a&&a.push(i),o}};function q2(e,t,i,s,a,o){let c=[];for(let h=0;h=h&&s0&&(R>x||_[R].getTrimmedLength()===0);R--)j++;j>0&&(c.push(h+_.length-j),c.push(j)),h+=_.length-1}return c}function W2(e,t){let i=[],s=0,a=t[s],o=0;for(let c=0;cMo(e,f,t)).reduce((p,f)=>p+f),o=0,c=0,h=0;for(;hp&&(o-=p,c++);let f=e[c].getWidth(o-1)===2;f&&o--;let _=f?i-1:i;s.push(_),h+=_}return s}function Mo(e,t,i){if(t===e.length-1)return e[t].getTrimmedLength();let s=!e[t].hasContent(i-1)&&e[t].getWidth(i-1)===1,a=e[t+1].getWidth(0)===2;return s&&a?i-1:i}var p0=class m0{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=m0._nextId++,this._onDispose=this.register(new Ce),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),ga(this._disposables),this._disposables.length=0)}register(t){return this._disposables.push(t),t}};p0._nextId=1;var K2=p0,Di={},fa=Di.B;Di[0]={"`":"◆",a:"▒",b:"␉",c:"␌",d:"␍",e:"␊",f:"°",g:"±",h:"␤",i:"␋",j:"┘",k:"┐",l:"┌",m:"└",n:"┼",o:"⎺",p:"⎻",q:"─",r:"⎼",s:"⎽",t:"├",u:"┤",v:"┴",w:"┬",x:"│",y:"≤",z:"≥","{":"π","|":"≠","}":"£","~":"·"};Di.A={"#":"£"};Di.B=void 0;Di[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"};Di.C=Di[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};Di.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"};Di.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"};Di.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"};Di.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"};Di.E=Di[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"};Di.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"};Di.H=Di[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};Di["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"};var Pb=4294967295,Ib=class{constructor(e,t,i){this._hasScrollback=e,this._optionsService=t,this._bufferService=i,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=Si.clone(),this.savedCharset=fa,this.markers=[],this._nullCell=sr.fromCharData([0,Dy,1,0]),this._whitespaceCell=sr.fromCharData([0,Is,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new Ru,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new zb(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new Nu),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new Nu),this._whitespaceCell}getBlankLine(e,t){return new wo(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&ePb?Pb:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=Si);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new zb(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let i=this.getNullCell(Si),s=0,a=this._getCorrectBufferLength(t);if(a>this.lines.maxLength&&(this.lines.maxLength=a),this.lines.length>0){if(this._cols0&&this.lines.length<=this.ybase+this.y+o+1?(this.ybase--,o++,this.ydisp>0&&this.ydisp--):this.lines.push(new wo(e,i)));else for(let c=this._rows;c>t;c--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(a0&&(this.lines.trimStart(c),this.ybase=Math.max(this.ybase-c,0),this.ydisp=Math.max(this.ydisp-c,0),this.savedY=Math.max(this.savedY-c,0)),this.lines.maxLength=a}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),o&&(this.y+=o),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let o=0;o.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend==="conpty"&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let i=this._optionsService.rawOptions.reflowCursorLine,s=q2(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(Si),i);if(s.length>0){let a=W2(this.lines,s);G2(this.lines,a.layout),this._reflowLargerAdjustViewport(e,t,a.countRemoved)}}_reflowLargerAdjustViewport(e,t,i){let s=this.getNullCell(Si),a=i;for(;a-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length=0;c--){let h=this.lines.get(c);if(!h||!h.isWrapped&&h.getTrimmedLength()<=e)continue;let p=[h];for(;h.isWrapped&&c>0;)h=this.lines.get(--c),p.unshift(h);if(!i){let I=this.ybase+this.y;if(I>=c&&I0&&(a.push({start:c+p.length+o,newLines:v}),o+=v.length),p.push(...v);let S=_.length-1,j=_[S];j===0&&(S--,j=_[S]);let R=p.length-x-1,E=f;for(;R>=0;){let I=Math.min(E,j);if(p[S]===void 0)break;if(p[S].copyCellsFrom(p[R],E-I,j-I,I,!0),j-=I,j===0&&(S--,j=_[S]),E-=I,E===0){R--;let te=Math.max(R,0);E=Mo(p,te,this._cols)}}for(let I=0;I0;)this.ybase===0?this.y0){let c=[],h=[];for(let j=0;j=0;j--)if(x&&x.start>f+b){for(let R=x.newLines.length-1;R>=0;R--)this.lines.set(j--,x.newLines[R]);j++,c.push({index:f+1,amount:x.newLines.length}),b+=x.newLines.length,x=a[++_]}else this.lines.set(j,h[f--]);let v=0;for(let j=c.length-1;j>=0;j--)c[j].index+=v,this.lines.onInsertEmitter.fire(c[j]),v+=c[j].amount;let S=Math.max(0,p+o-this.lines.maxLength);S>0&&this.lines.onTrimEmitter.fire(S)}}translateBufferLineToString(e,t,i=0,s){let a=this.lines.get(e);return a?a.translateToString(t,i,s):""}getWrappedRangeForLine(e){let t=e,i=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;i+10;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e==null&&(e=this.x);!this.tabs[++e]&&e=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t{t.line-=i,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(i=>{t.line>=i.index&&(t.line+=i.amount)})),t.register(this.lines.onDelete(i=>{t.line>=i.index&&t.linei.index&&(t.line-=i.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},V2=class extends ut{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new Ce),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this._register(this._optionsService.onSpecificOptionChange("scrollback",()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this._register(this._optionsService.onSpecificOptionChange("tabStopWidth",()=>this.setupTabStops()))}reset(){this._normal=new Ib(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new Ib(!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)}},g0=2,x0=1,gp=class extends ut{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new Ce),this.onResize=this._onResize.event,this._onScroll=this._register(new Ce),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,g0),this.rows=Math.max(e.rawOptions.rows||0,x0),this.buffers=this._register(new V2(e,this)),this._register(this.buffers.onBufferActivate(t=>{this._onScroll.fire(t.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let i=this.cols!==e,s=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:i,rowsChanged:s})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let i=this.buffer,s;s=this._cachedBlankLine,(!s||s.length!==this.cols||s.getFg(0)!==e.fg||s.getBg(0)!==e.bg)&&(s=i.getBlankLine(e,t),this._cachedBlankLine=s),s.isWrapped=t;let a=i.ybase+i.scrollTop,o=i.ybase+i.scrollBottom;if(i.scrollTop===0){let c=i.lines.isFull;o===i.lines.length-1?c?i.lines.recycle().copyFrom(s):i.lines.push(s.clone()):i.lines.splice(o+1,0,s.clone()),c?this.isUserScrolling&&(i.ydisp=Math.max(i.ydisp-1,0)):(i.ybase++,this.isUserScrolling||i.ydisp++)}else{let c=o-a+1;i.lines.shiftElements(a+1,c-1,-1),i.lines.set(o,s.clone())}this.isUserScrolling||(i.ydisp=i.ybase),this._onScroll.fire(i.ydisp)}scrollLines(e,t){let i=this.buffer;if(e<0){if(i.ydisp===0)return;this.isUserScrolling=!0}else e+i.ydisp>=i.ybase&&(this.isUserScrolling=!1);let s=i.ydisp;i.ydisp=Math.max(Math.min(i.ydisp+e,i.ybase),0),s!==i.ydisp&&(t||this._onScroll.fire(i.ydisp))}};gp=ci([De(0,mn)],gp);var nl={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:Au,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}},X2=["normal","bold","100","200","300","400","500","600","700","800","900"],Z2=class extends ut{constructor(e){super(),this._onOptionChange=this._register(new Ce),this.onOptionChange=this._onOptionChange.event;let t={...nl};for(let i in e)if(i in t)try{let s=e[i];t[i]=this._sanitizeAndValidateOption(i,s)}catch(s){console.error(s)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register(ii(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(i=>{i===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(i=>{e.indexOf(i)!==-1&&t()})}_setupOptions(){let e=i=>{if(!(i in nl))throw new Error(`No option with key "${i}"`);return this.rawOptions[i]},t=(i,s)=>{if(!(i in nl))throw new Error(`No option with key "${i}"`);s=this._sanitizeAndValidateOption(i,s),this.rawOptions[i]!==s&&(this.rawOptions[i]=s,this._onOptionChange.fire(i))};for(let i in this.rawOptions){let s={get:e.bind(this,i),set:t.bind(this,i)};Object.defineProperty(this.options,i,s)}}_sanitizeAndValidateOption(e,t){switch(e){case"cursorStyle":if(t||(t=nl[e]),!Q2(t))throw new Error(`"${t}" is not a valid value for ${e}`);break;case"wordSeparator":t||(t=nl[e]);break;case"fontWeight":case"fontWeightBold":if(typeof t=="number"&&1<=t&&t<=1e3)break;t=X2.includes(t)?t:nl[e];break;case"cursorWidth":t=Math.floor(t);case"lineHeight":case"tabStopWidth":if(t<1)throw new Error(`${e} cannot be less than 1, value: ${t}`);break;case"minimumContrastRatio":t=Math.max(1,Math.min(21,Math.round(t*10)/10));break;case"scrollback":if(t=Math.min(t,4294967295),t<0)throw new Error(`${e} cannot be less than 0, value: ${t}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(t<=0)throw new Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case"rows":case"cols":if(!t&&t!==0)throw new Error(`${e} must be numeric, value: ${t}`);break;case"windowsPty":t=t??{};break}return t}};function Q2(e){return e==="block"||e==="underline"||e==="bar"}function Co(e,t=5){if(typeof e!="object")return e;let i=Array.isArray(e)?[]:{};for(let s in e)i[s]=t<=1?e[s]:e[s]&&Co(e[s],t-1);return i}var Hb=Object.freeze({insertMode:!1}),Ub=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),xp=class extends ut{constructor(e,t,i){super(),this._bufferService=e,this._logService=t,this._optionsService=i,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new Ce),this.onData=this._onData.event,this._onUserInput=this._register(new Ce),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new Ce),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new Ce),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=Co(Hb),this.decPrivateModes=Co(Ub)}reset(){this.modes=Co(Hb),this.decPrivateModes=Co(Ub)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let i=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&i.ybase!==i.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace("sending data (codes)",()=>e.split("").map(s=>s.charCodeAt(0))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace("sending binary (codes)",()=>e.split("").map(t=>t.charCodeAt(0))),this._onBinary.fire(e))}};xp=ci([De(0,pn),De(1,zy),De(2,mn)],xp);var $b={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>e.button===4||e.action!==1?!1:(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>e.action!==32},DRAG:{events:23,restrict:e=>!(e.action===32&&e.button===3)},ANY:{events:31,restrict:e=>!0}};function cf(e,t){let i=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(i|=64,i|=e.action):(i|=e.button&3,e.button&4&&(i|=64),e.button&8&&(i|=128),e.action===32?i|=32:e.action===0&&!t&&(i|=3)),i}var uf=String.fromCharCode,Fb={DEFAULT:e=>{let t=[cf(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`\x1B[M${uf(t[0])}${uf(t[1])}${uf(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${cf(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${cf(e,!0)};${e.x};${e.y}${t}`}},_p=class extends ut{constructor(e,t,i){super(),this._bufferService=e,this._coreService=t,this._optionsService=i,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new Ce),this.onProtocolChange=this._onProtocolChange.event;for(let s of Object.keys($b))this.addProtocol(s,$b[s]);for(let s of Object.keys(Fb))this.addEncoding(s,Fb[s]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw new Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw new Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,i){if(e.deltaY===0||e.shiftKey||t===void 0||i===void 0)return 0;let s=t/i,a=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(a/=s+0,Math.abs(e.deltaY)<50&&(a*=.3),this._wheelPartialScroll+=a,a=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(a*=this._bufferService.rows),a}_applyScrollModifier(e,t){return t.altKey||t.ctrlKey||t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding==="SGR_PIXELS"))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(e&1),up:!!(e&2),drag:!!(e&4),move:!!(e&8),wheel:!!(e&16)}}_equalEvents(e,t,i){if(i){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return!(e.button!==t.button||e.action!==t.action||e.ctrl!==t.ctrl||e.alt!==t.alt||e.shift!==t.shift)}};_p=ci([De(0,pn),De(1,ba),De(2,mn)],_p);var hf=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],J2=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],Ai;function eE(e,t){let i=0,s=t.length-1,a;if(et[s][1])return!1;for(;s>=i;)if(a=i+s>>1,e>t[a][1])i=a+1;else if(e=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let i=this.wcwidth(e),s=i===0&&t!==0;if(s){let a=pa.extractWidth(t);a===0?s=!1:a>i&&(i=a)}return pa.createPropertyValue(0,i,s)}},pa=class yu{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new Ce,this.onChange=this._onChange.event;let t=new tE;this.register(t),this._active=t.version,this._activeProvider=t}static extractShouldJoin(t){return(t&1)!==0}static extractWidth(t){return t>>1&3}static extractCharKind(t){return t>>3}static createPropertyValue(t,i,s=!1){return(t&16777215)<<3|(i&3)<<1|(s?1:0)}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(t){if(!this._providers[t])throw new Error(`unknown Unicode version "${t}"`);this._active=t,this._activeProvider=this._providers[t],this._onChange.fire(t)}register(t){this._providers[t.version]=t}wcwidth(t){return this._activeProvider.wcwidth(t)}getStringCellWidth(t){let i=0,s=0,a=t.length;for(let o=0;o=a)return i+this.wcwidth(c);let f=t.charCodeAt(o);56320<=f&&f<=57343?c=(c-55296)*1024+f-56320+65536:i+=this.wcwidth(f)}let h=this.charProperties(c,s),p=yu.extractWidth(h);yu.extractShouldJoin(h)&&(p-=yu.extractWidth(s)),i+=p,s=h}return i}charProperties(t,i){return this._activeProvider.charProperties(t,i)}},iE=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 qb(e){var s;let t=(s=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1))==null?void 0:s.get(e.cols-1),i=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);i&&t&&(i.isWrapped=t[3]!==0&&t[3]!==32)}var fo=2147483647,nE=256,_0=class bp{constructor(t=32,i=32){if(this.maxLength=t,this.maxSubParamsLength=i,i>nE)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(t),this.length=0,this._subParams=new Int32Array(i),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(t),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let i=new bp;if(!t.length)return i;for(let s=Array.isArray(t[0])?1:0;s>8,a=this._subParamsIdx[i]&255;a-s>0&&t.push(Array.prototype.slice.call(this._subParams,s,a))}return t}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(t){if(this._digitIsSub=!1,this.length>=this.maxLength){this._rejectDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=t>fo?fo:t}addSubParam(t){if(this._digitIsSub=!0,!!this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=t>fo?fo:t,this._subParamsIdx[this.length-1]++}}hasSubParams(t){return(this._subParamsIdx[t]&255)-(this._subParamsIdx[t]>>8)>0}getSubParams(t){let i=this._subParamsIdx[t]>>8,s=this._subParamsIdx[t]&255;return s-i>0?this._subParams.subarray(i,s):null}getSubParamsAll(){let t={};for(let i=0;i>8,a=this._subParamsIdx[i]&255;a-s>0&&(t[i]=this._subParams.slice(s,a))}return t}addDigit(t){let i;if(this._rejectDigits||!(i=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let s=this._digitIsSub?this._subParams:this.params,a=s[i-1];s[i-1]=~a?Math.min(a*10+t,fo):t}},po=[],rE=class{constructor(){this._state=0,this._active=po,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let i=this._handlers[e];return i.push(t),{dispose:()=>{let s=i.indexOf(t);s!==-1&&i.splice(s,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=po}reset(){if(this._state===2)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=po,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||po,!this._active.length)this._handlerFb(this._id,"START");else for(let e=this._active.length-1;e>=0;e--)this._active[e].start()}_put(e,t,i){if(!this._active.length)this._handlerFb(this._id,"PUT",Pu(e,t,i));else for(let s=this._active.length-1;s>=0;s--)this._active[s].put(e,t,i)}start(){this.reset(),this._state=1}put(e,t,i){if(this._state!==3){if(this._state===1)for(;t0&&this._put(e,t,i)}}end(e,t=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),!this._active.length)this._handlerFb(this._id,"END",e);else{let i=!1,s=this._active.length-1,a=!1;if(this._stack.paused&&(s=this._stack.loopPosition-1,i=t,a=this._stack.fallThrough,this._stack.paused=!1),!a&&i===!1){for(;s>=0&&(i=this._active[s].end(e),i!==!0);s--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!1,i;s--}for(;s>=0;s--)if(i=this._active[s].end(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!0,i}this._active=po,this._id=-1,this._state=0}}},zn=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+=Pu(e,t,i),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then(i=>(this._data="",this._hitLimit=!1,i));return this._data="",this._hitLimit=!1,t}},mo=[],sE=class{constructor(){this._handlers=Object.create(null),this._active=mo,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=mo}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let i=this._handlers[e];return i.push(t),{dispose:()=>{let s=i.indexOf(t);s!==-1&&i.splice(s,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=mo,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||mo,!this._active.length)this._handlerFb(this._ident,"HOOK",t);else for(let i=this._active.length-1;i>=0;i--)this._active[i].hook(t)}put(e,t,i){if(!this._active.length)this._handlerFb(this._ident,"PUT",Pu(e,t,i));else for(let s=this._active.length-1;s>=0;s--)this._active[s].put(e,t,i)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,"UNHOOK",e);else{let i=!1,s=this._active.length-1,a=!1;if(this._stack.paused&&(s=this._stack.loopPosition-1,i=t,a=this._stack.fallThrough,this._stack.paused=!1),!a&&i===!1){for(;s>=0&&(i=this._active[s].unhook(e),i!==!0);s--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!1,i;s--}for(;s>=0;s--)if(i=this._active[s].unhook(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!0,i}this._active=mo,this._ident=0}},ko=new _0;ko.addParam(0);var Wb=class{constructor(e){this._handler=e,this._data="",this._params=ko,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():ko,this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=Pu(e,t,i),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then(i=>(this._params=ko,this._data="",this._hitLimit=!1,i));return this._params=ko,this._data="",this._hitLimit=!1,t}},aE=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})(),oE=class extends ut{constructor(e=lE){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 _0,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(t,i,s)=>{},this._executeHandlerFb=t=>{},this._csiHandlerFb=(t,i)=>{},this._escHandlerFb=t=>{},this._errorHandlerFb=t=>t,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register(ii(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new rE),this._dcsParser=this._register(new sE),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},()=>!0)}_identifier(e,t=[64,126]){let i=0;if(e.prefix){if(e.prefix.length>1)throw new Error("only one byte as prefix supported");if(i=e.prefix.charCodeAt(0),i&&60>i||i>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(e.intermediates){if(e.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let a=0;ao||o>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");i<<=8,i|=o}}if(e.final.length!==1)throw new Error("final must be a single byte");let s=e.final.charCodeAt(0);if(t[0]>s||s>t[1])throw new Error(`final must be in range ${t[0]} .. ${t[1]}`);return i<<=8,i|=s,i}identToString(e){let t=[];for(;e;)t.push(String.fromCharCode(e&255)),e>>=8;return t.reverse().join("")}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){let i=this._identifier(e,[48,126]);this._escHandlers[i]===void 0&&(this._escHandlers[i]=[]);let s=this._escHandlers[i];return s.push(t),{dispose:()=>{let a=s.indexOf(t);a!==-1&&s.splice(a,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){let i=this._identifier(e);this._csiHandlers[i]===void 0&&(this._csiHandlers[i]=[]);let s=this._csiHandlers[i];return s.push(t),{dispose:()=>{let a=s.indexOf(t);a!==-1&&s.splice(a,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,i,s,a){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=i,this._parseStack.transition=s,this._parseStack.chunkPos=a}parse(e,t,i){let s=0,a=0,o=0,c;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,o=this._parseStack.chunkPos+1;else{if(i===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");let h=this._parseStack.handlers,p=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(i===!1&&p>-1){for(;p>=0&&(c=h[p](this._params),c!==!0);p--)if(c instanceof Promise)return this._parseStack.handlerPos=p,c}this._parseStack.handlers=[];break;case 4:if(i===!1&&p>-1){for(;p>=0&&(c=h[p](),c!==!0);p--)if(c instanceof Promise)return this._parseStack.handlerPos=p,c}this._parseStack.handlers=[];break;case 6:if(s=e[this._parseStack.chunkPos],c=this._dcsParser.unhook(s!==24&&s!==26,i),c)return c;s===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(s=e[this._parseStack.chunkPos],c=this._oscParser.end(s!==24&&s!==26,i),c)return c;s===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break}this._parseStack.state=0,o=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}for(let h=o;h>4){case 2:for(let b=h+1;;++b){if(b>=t||(s=e[b])<32||s>126&&s=t||(s=e[b])<32||s>126&&s=t||(s=e[b])<32||s>126&&s=t||(s=e[b])<32||s>126&&s=0&&(c=p[f](this._params),c!==!0);f--)if(c instanceof Promise)return this._preserveStack(3,p,f,a,h),c;f<0&&this._csiHandlerFb(this._collect<<8|s,this._params),this.precedingJoinState=0;break;case 8:do switch(s){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(s-48)}while(++h47&&s<60);h--;break;case 9:this._collect<<=8,this._collect|=s;break;case 10:let _=this._escHandlers[this._collect<<8|s],x=_?_.length-1:-1;for(;x>=0&&(c=_[x](),c!==!0);x--)if(c instanceof Promise)return this._preserveStack(4,_,x,a,h),c;x<0&&this._escHandlerFb(this._collect<<8|s),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|s,this._params);break;case 13:for(let b=h+1;;++b)if(b>=t||(s=e[b])===24||s===26||s===27||s>127&&s=t||(s=e[b])<32||s>127&&s>4:o>>8}return s}}function df(e,t){let i=e.toString(16),s=i.length<2?"0"+i:i;switch(t){case 4:return i[0];case 8:return s;case 12:return(s+s).slice(0,3);default:return s+s}}function hE(e,t=16){let[i,s,a]=e;return`rgb:${df(i,t)}/${df(s,t)}/${df(a,t)}`}var dE={"(":0,")":1,"*":2,"+":3,"-":1,".":2},Ls=131072,Yb=10;function Kb(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 Vb=5e3,Xb=0,fE=class extends ut{constructor(e,t,i,s,a,o,c,h,p=new oE){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 DC,this._utf8Decoder=new MC,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=Si.clone(),this._eraseAttrDataInternal=Si.clone(),this._onRequestBell=this._register(new Ce),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new Ce),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new Ce),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new Ce),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new Ce),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new Ce),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new Ce),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new Ce),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new Ce),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new Ce),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new Ce),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new Ce),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new Ce),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this._register(this._parser),this._dirtyRowTracker=new vp(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(f=>this._activeBuffer=f.activeBuffer)),this._parser.setCsiHandlerFallback((f,_)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(f),params:_.toArray()})}),this._parser.setEscHandlerFallback(f=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(f)})}),this._parser.setExecuteHandlerFallback(f=>{this._logService.debug("Unknown EXECUTE code: ",{code:f})}),this._parser.setOscHandlerFallback((f,_,x)=>{this._logService.debug("Unknown OSC code: ",{identifier:f,action:_,data:x})}),this._parser.setDcsHandlerFallback((f,_,x)=>{_==="HOOK"&&(x=x.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(f),action:_,payload:x})}),this._parser.setPrintHandler((f,_,x)=>this.print(f,_,x)),this._parser.registerCsiHandler({final:"@"},f=>this.insertChars(f)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},f=>this.scrollLeft(f)),this._parser.registerCsiHandler({final:"A"},f=>this.cursorUp(f)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},f=>this.scrollRight(f)),this._parser.registerCsiHandler({final:"B"},f=>this.cursorDown(f)),this._parser.registerCsiHandler({final:"C"},f=>this.cursorForward(f)),this._parser.registerCsiHandler({final:"D"},f=>this.cursorBackward(f)),this._parser.registerCsiHandler({final:"E"},f=>this.cursorNextLine(f)),this._parser.registerCsiHandler({final:"F"},f=>this.cursorPrecedingLine(f)),this._parser.registerCsiHandler({final:"G"},f=>this.cursorCharAbsolute(f)),this._parser.registerCsiHandler({final:"H"},f=>this.cursorPosition(f)),this._parser.registerCsiHandler({final:"I"},f=>this.cursorForwardTab(f)),this._parser.registerCsiHandler({final:"J"},f=>this.eraseInDisplay(f,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},f=>this.eraseInDisplay(f,!0)),this._parser.registerCsiHandler({final:"K"},f=>this.eraseInLine(f,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},f=>this.eraseInLine(f,!0)),this._parser.registerCsiHandler({final:"L"},f=>this.insertLines(f)),this._parser.registerCsiHandler({final:"M"},f=>this.deleteLines(f)),this._parser.registerCsiHandler({final:"P"},f=>this.deleteChars(f)),this._parser.registerCsiHandler({final:"S"},f=>this.scrollUp(f)),this._parser.registerCsiHandler({final:"T"},f=>this.scrollDown(f)),this._parser.registerCsiHandler({final:"X"},f=>this.eraseChars(f)),this._parser.registerCsiHandler({final:"Z"},f=>this.cursorBackwardTab(f)),this._parser.registerCsiHandler({final:"`"},f=>this.charPosAbsolute(f)),this._parser.registerCsiHandler({final:"a"},f=>this.hPositionRelative(f)),this._parser.registerCsiHandler({final:"b"},f=>this.repeatPrecedingCharacter(f)),this._parser.registerCsiHandler({final:"c"},f=>this.sendDeviceAttributesPrimary(f)),this._parser.registerCsiHandler({prefix:">",final:"c"},f=>this.sendDeviceAttributesSecondary(f)),this._parser.registerCsiHandler({final:"d"},f=>this.linePosAbsolute(f)),this._parser.registerCsiHandler({final:"e"},f=>this.vPositionRelative(f)),this._parser.registerCsiHandler({final:"f"},f=>this.hVPosition(f)),this._parser.registerCsiHandler({final:"g"},f=>this.tabClear(f)),this._parser.registerCsiHandler({final:"h"},f=>this.setMode(f)),this._parser.registerCsiHandler({prefix:"?",final:"h"},f=>this.setModePrivate(f)),this._parser.registerCsiHandler({final:"l"},f=>this.resetMode(f)),this._parser.registerCsiHandler({prefix:"?",final:"l"},f=>this.resetModePrivate(f)),this._parser.registerCsiHandler({final:"m"},f=>this.charAttributes(f)),this._parser.registerCsiHandler({final:"n"},f=>this.deviceStatus(f)),this._parser.registerCsiHandler({prefix:"?",final:"n"},f=>this.deviceStatusPrivate(f)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},f=>this.softReset(f)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},f=>this.setCursorStyle(f)),this._parser.registerCsiHandler({final:"r"},f=>this.setScrollRegion(f)),this._parser.registerCsiHandler({final:"s"},f=>this.saveCursor(f)),this._parser.registerCsiHandler({final:"t"},f=>this.windowOptions(f)),this._parser.registerCsiHandler({final:"u"},f=>this.restoreCursor(f)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},f=>this.insertColumns(f)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},f=>this.deleteColumns(f)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},f=>this.selectProtected(f)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},f=>this.requestMode(f,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},f=>this.requestMode(f,!1)),this._parser.setExecuteHandler(me.BEL,()=>this.bell()),this._parser.setExecuteHandler(me.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(me.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(me.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(me.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(me.BS,()=>this.backspace()),this._parser.setExecuteHandler(me.HT,()=>this.tab()),this._parser.setExecuteHandler(me.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(me.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(bu.IND,()=>this.index()),this._parser.setExecuteHandler(bu.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(bu.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new zn(f=>(this.setTitle(f),this.setIconName(f),!0))),this._parser.registerOscHandler(1,new zn(f=>this.setIconName(f))),this._parser.registerOscHandler(2,new zn(f=>this.setTitle(f))),this._parser.registerOscHandler(4,new zn(f=>this.setOrReportIndexedColor(f))),this._parser.registerOscHandler(8,new zn(f=>this.setHyperlink(f))),this._parser.registerOscHandler(10,new zn(f=>this.setOrReportFgColor(f))),this._parser.registerOscHandler(11,new zn(f=>this.setOrReportBgColor(f))),this._parser.registerOscHandler(12,new zn(f=>this.setOrReportCursorColor(f))),this._parser.registerOscHandler(104,new zn(f=>this.restoreIndexedColor(f))),this._parser.registerOscHandler(110,new zn(f=>this.restoreFgColor(f))),this._parser.registerOscHandler(111,new zn(f=>this.restoreBgColor(f))),this._parser.registerOscHandler(112,new zn(f=>this.restoreCursorColor(f))),this._parser.registerEscHandler({final:"7"},()=>this.saveCursor()),this._parser.registerEscHandler({final:"8"},()=>this.restoreCursor()),this._parser.registerEscHandler({final:"D"},()=>this.index()),this._parser.registerEscHandler({final:"E"},()=>this.nextLine()),this._parser.registerEscHandler({final:"H"},()=>this.tabSet()),this._parser.registerEscHandler({final:"M"},()=>this.reverseIndex()),this._parser.registerEscHandler({final:"="},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:">"},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:"c"},()=>this.fullReset()),this._parser.registerEscHandler({final:"n"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"o"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"|"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"}"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"~"},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:"%",final:"@"},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:"%",final:"G"},()=>this.selectDefaultCharset());for(let f in Di)this._parser.registerEscHandler({intermediates:"(",final:f},()=>this.selectCharset("("+f)),this._parser.registerEscHandler({intermediates:")",final:f},()=>this.selectCharset(")"+f)),this._parser.registerEscHandler({intermediates:"*",final:f},()=>this.selectCharset("*"+f)),this._parser.registerEscHandler({intermediates:"+",final:f},()=>this.selectCharset("+"+f)),this._parser.registerEscHandler({intermediates:"-",final:f},()=>this.selectCharset("-"+f)),this._parser.registerEscHandler({intermediates:".",final:f},()=>this.selectCharset("."+f)),this._parser.registerEscHandler({intermediates:"/",final:f},()=>this.selectCharset("/"+f));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(f=>(this._logService.error("Parsing error: ",f),f)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new Wb((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"),Vb))]).catch(t=>{if(t!=="#SLOW_TIMEOUT")throw t;console.warn(`async parser handler taking longer than ${Vb} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let i,s=this._activeBuffer.x,a=this._activeBuffer.y,o=0,c=this._parseStack.paused;if(c){if(i=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(i),i;s=this._parseStack.cursorStartX,a=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>Ls&&(o=this._parseStack.position+Ls)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e=="string"?` "${e}"`:` "${Array.prototype.map.call(e,f=>String.fromCharCode(f)).join("")}"`}`),this._logService.logLevel===0&&this._logService.trace("parsing data (codes)",typeof e=="string"?e.split("").map(f=>f.charCodeAt(0)):e),this._parseBuffer.lengthLs)for(let f=o;f0&&x.getWidth(this._activeBuffer.x-1)===2&&x.setCellFromCodepoint(this._activeBuffer.x-1,0,1,_);let b=this._parser.precedingJoinState;for(let v=t;vh){if(p){let E=x,N=this._activeBuffer.x-R;for(this._activeBuffer.x=R,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),R>0&&x instanceof wo&&x.copyCellsFrom(E,N,0,R,!1);N=0;)x.setCellFromCodepoint(this._activeBuffer.x++,0,0,_);continue}if(f&&(x.insertCells(this._activeBuffer.x,a-R,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=>Kb(i.params[0],this._optionsService.rawOptions.windowOptions)?t(i):!0):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new Wb(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new zn(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){var e;if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&((e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y))!=null&&e.isWrapped)){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);t.hasWidth(this._activeBuffer.x)&&!t.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),(t===2||t===0)&&(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,i,s=!1,a=!1){let o=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);o.replaceCells(t,i,this._activeBuffer.getNullCell(this._eraseAttrData()),a),s&&(o.isWrapped=!1)}_resetBufferLine(e,t=!1){let i=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);i&&(i.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),i.isWrapped=!1)}eraseInDisplay(e,t=!1){var s;this._restrictCursor(this._bufferService.cols);let i;switch(e.params[0]){case 0:for(i=this._activeBuffer.y,this._dirtyRowTracker.markDirty(i),this._eraseInBufferLine(i++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);i=this._bufferService.cols&&(this._activeBuffer.lines.get(i+1).isWrapped=!1);i--;)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(i=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,i-1);i--&&!((s=this._activeBuffer.lines.get(this._activeBuffer.ybase+i))!=null&&s.getTrimmedLength()););for(;i>=0;i--)this._bufferService.scroll(this._eraseAttrData())}else{for(i=this._bufferService.rows,this._dirtyRowTracker.markDirty(i-1);i--;)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let a=this._activeBuffer.lines.length-this._bufferService.rows;a>0&&(this._activeBuffer.lines.trimStart(a),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-a,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-a,0),this._onScroll.fire(0));break}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t);break}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.y65535?2:1}let p=h;for(let f=1;f0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(me.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(me.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(me.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(me.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(e.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(me.ESC+"[>83;40003;0c")),!0}_is(e){return(this._optionsService.rawOptions.termName+"").indexOf(e)===0}setMode(e){for(let t=0;t(j[j.NOT_RECOGNIZED=0]="NOT_RECOGNIZED",j[j.SET=1]="SET",j[j.RESET=2]="RESET",j[j.PERMANENTLY_SET=3]="PERMANENTLY_SET",j[j.PERMANENTLY_RESET=4]="PERMANENTLY_RESET"))(void 0||(i={}));let s=this._coreService.decPrivateModes,{activeProtocol:a,activeEncoding:o}=this._coreMouseService,c=this._coreService,{buffers:h,cols:p}=this._bufferService,{active:f,alt:_}=h,x=this._optionsService.rawOptions,b=(j,R)=>(c.triggerDataEvent(`${me.ESC}[${t?"":"?"}${j};${R}$y`),!0),v=j=>j?1:2,S=e.params[0];return t?S===2?b(S,4):S===4?b(S,v(c.modes.insertMode)):S===12?b(S,3):S===20?b(S,v(x.convertEol)):b(S,0):S===1?b(S,v(s.applicationCursorKeys)):S===3?b(S,x.windowOptions.setWinLines?p===80?2:p===132?1:0:0):S===6?b(S,v(s.origin)):S===7?b(S,v(s.wraparound)):S===8?b(S,3):S===9?b(S,v(a==="X10")):S===12?b(S,v(x.cursorBlink)):S===25?b(S,v(!c.isCursorHidden)):S===45?b(S,v(s.reverseWraparound)):S===66?b(S,v(s.applicationKeypad)):S===67?b(S,4):S===1e3?b(S,v(a==="VT200")):S===1002?b(S,v(a==="DRAG")):S===1003?b(S,v(a==="ANY")):S===1004?b(S,v(s.sendFocus)):S===1005?b(S,4):S===1006?b(S,v(o==="SGR")):S===1015?b(S,4):S===1016?b(S,v(o==="SGR_PIXELS")):S===1048?b(S,1):S===47||S===1047||S===1049?b(S,v(f===_)):S===2004?b(S,v(s.bracketedPasteMode)):S===2026?b(S,v(s.synchronizedOutput)):b(S,0)}_updateAttrColor(e,t,i,s,a){return t===2?(e|=50331648,e&=-16777216,e|=Po.fromColorRGB([i,s,a])):t===5&&(e&=-50331904,e|=33554432|i&255),e}_extractColor(e,t,i){let s=[0,0,-1,0,0,0],a=0,o=0;do{if(s[o+a]=e.params[t+o],e.hasSubParams(t+o)){let c=e.getSubParams(t+o),h=0;do s[1]===5&&(a=1),s[o+h+1+a]=c[h];while(++h=2||s[1]===2&&o+a>=5)break;s[1]&&(a=1)}while(++o+t5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=Si.fg,e.bg=Si.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,i,s=this._curAttrData;for(let a=0;a=30&&i<=37?(s.fg&=-50331904,s.fg|=16777216|i-30):i>=40&&i<=47?(s.bg&=-50331904,s.bg|=16777216|i-40):i>=90&&i<=97?(s.fg&=-50331904,s.fg|=16777216|i-90|8):i>=100&&i<=107?(s.bg&=-50331904,s.bg|=16777216|i-100|8):i===0?this._processSGR0(s):i===1?s.fg|=134217728:i===3?s.bg|=67108864:i===4?(s.fg|=268435456,this._processUnderline(e.hasSubParams(a)?e.getSubParams(a)[0]:1,s)):i===5?s.fg|=536870912:i===7?s.fg|=67108864:i===8?s.fg|=1073741824:i===9?s.fg|=2147483648:i===2?s.bg|=134217728:i===21?this._processUnderline(2,s):i===22?(s.fg&=-134217729,s.bg&=-134217729):i===23?s.bg&=-67108865:i===24?(s.fg&=-268435457,this._processUnderline(0,s)):i===25?s.fg&=-536870913:i===27?s.fg&=-67108865:i===28?s.fg&=-1073741825:i===29?s.fg&=2147483647:i===39?(s.fg&=-67108864,s.fg|=Si.fg&16777215):i===49?(s.bg&=-67108864,s.bg|=Si.bg&16777215):i===38||i===48||i===58?a+=this._extractColor(e,a,s):i===53?s.bg|=1073741824:i===55?s.bg&=-1073741825:i===59?(s.extended=s.extended.clone(),s.extended.underlineColor=-1,s.updateExtended()):i===100?(s.fg&=-67108864,s.fg|=Si.fg&16777215,s.bg&=-67108864,s.bg|=Si.bg&16777215):this._logService.debug("Unknown SGR attribute: %d.",i);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${me.ESC}[0n`);break;case 6:let t=this._activeBuffer.y+1,i=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${me.ESC}[${t};${i}R`);break}return!0}deviceStatusPrivate(e){switch(e.params[0]){case 6:let t=this._activeBuffer.y+1,i=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${me.ESC}[?${t};${i}R`);break}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=Si.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.length===0?1:e.params[0];if(t===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t){case 1:case 2:this._coreService.decPrivateModes.cursorStyle="block";break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle="underline";break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle="bar";break}let i=t%2===1;this._coreService.decPrivateModes.cursorBlink=i}return!0}setScrollRegion(e){let t=e.params[0]||1,i;return(e.length<2||(i=e.params[1])>this._bufferService.rows||i===0)&&(i=this._bufferService.rows),i>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=i-1,this._setCursor(0,0)),!0}windowOptions(e){if(!Kb(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${me.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>Yb&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>Yb&&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(Zb(o))if(a==="?")t.push({type:0,index:o});else{let c=Gb(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=Gb(i[s]);a&&this._onColor.fire([{type:1,index:this._specialColors[t],color:a}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],i=e.split(";");for(let s=0;s=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=Si.clone(),this._eraseAttrDataInternal=Si.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=this._curAttrData.bg&67108863,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new sr;e.content=1<<22|69,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t(this._coreService.triggerDataEvent(`${me.ESC}${c}${me.ESC}\\`),!0),s=this._bufferService.buffer,a=this._optionsService.rawOptions;return i(e==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:e==='"p'?'P1$r61;1"p':e==="r"?`P1$r${s.scrollTop+1};${s.scrollBottom+1}r`:e==="m"?"P1$r0m":e===" q"?`P1$r${{block:2,underline:4,bar:6}[a.cursorStyle]-(a.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},vp=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){ethis.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(Xb=e,e=t,t=Xb),ethis.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};vp=ci([De(0,pn)],vp);function Zb(e){return 0<=e&&e<256}var pE=5e7,Qb=12,mE=50,gE=class extends ut{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new Ce),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(t!==void 0&&this._syncCalls>t){this._syncCalls=0;return}if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;this._isSyncWriting=!0;let i;for(;i=this._writeBuffer.shift();){this._action(i);let s=this._callbacks.shift();s&&s()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>pE)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>=Qb?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>=Qb)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>mE&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}},yp=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let t=this._bufferService.buffer;if(e.id===void 0){let h=t.addMarker(t.ybase+t.y),p={data:e,id:this._nextId++,lines:[h]};return h.onDispose(()=>this._removeMarkerFromLink(p,h)),this._dataByLinkId.set(p.id,p),p.id}let i=e,s=this._getEntryIdKey(i),a=this._entriesWithId.get(s);if(a)return this.addLineToLink(a.id,t.ybase+t.y),a.id;let o=t.addMarker(t.ybase+t.y),c={id:this._nextId++,key:this._getEntryIdKey(i),data:i,lines:[o]};return o.onDispose(()=>this._removeMarkerFromLink(c,o)),this._entriesWithId.set(c.key,c),this._dataByLinkId.set(c.id,c),c.id}addLineToLink(e,t){let i=this._dataByLinkId.get(e);if(i&&i.lines.every(s=>s.line!==t)){let s=this._bufferService.buffer.addMarker(t);i.lines.push(s),s.onDispose(()=>this._removeMarkerFromLink(i,s))}}getLinkData(e){var t;return(t=this._dataByLinkId.get(e))==null?void 0:t.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let i=e.lines.indexOf(t);i!==-1&&(e.lines.splice(i,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};yp=ci([De(0,pn)],yp);var Jb=!1,xE=class extends ut{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new pl),this._onBinary=this._register(new Ce),this.onBinary=this._onBinary.event,this._onData=this._register(new Ce),this.onData=this._onData.event,this._onLineFeed=this._register(new Ce),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new Ce),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new Ce),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new Ce),this._instantiationService=new U2,this.optionsService=this._register(new Z2(e)),this._instantiationService.setService(mn,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(gp)),this._instantiationService.setService(pn,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(mp)),this._instantiationService.setService(zy,this._logService),this.coreService=this._register(this._instantiationService.createInstance(xp)),this._instantiationService.setService(ba,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(_p)),this._instantiationService.setService(Oy,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(pa)),this._instantiationService.setService(zC,this.unicodeService),this._charsetService=this._instantiationService.createInstance(iE),this._instantiationService.setService(OC,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(yp),this._instantiationService.setService(Py,this._oscLinkService),this._inputHandler=this._register(new fE(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(en.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(en.forward(this._bufferService.onResize,this._onResize)),this._register(en.forward(this.coreService.onData,this._onData)),this._register(en.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom(!0))),this._register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this._register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],()=>this._handleWindowsPtyOptionChange())),this._register(this._bufferService.onScroll(()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this._register(new gE((t,i)=>this._inputHandler.parse(t,i))),this._register(en.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new Ce),this._onScroll.event(e=>{var t;(t=this._onScrollApi)==null||t.fire(e.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let t in e)this.optionsService.options[t]=e[t]}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=3&&!Jb&&(this._logService.warn("writeSync is unreliable and will be removed soon."),Jb=!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,g0),t=Math.max(t,x0),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(qb.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},()=>(qb(this._bufferService),!1))),this._windowsWrappingHeuristics.value=ii(()=>{for(let t of e)t.dispose()})}}},_E={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 bE(e,t,i,s){var c;let a={type:0,cancel:!1,key:void 0},o=(e.shiftKey?1:0)|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:e.key==="UIKeyInputUpArrow"?t?a.key=me.ESC+"OA":a.key=me.ESC+"[A":e.key==="UIKeyInputLeftArrow"?t?a.key=me.ESC+"OD":a.key=me.ESC+"[D":e.key==="UIKeyInputRightArrow"?t?a.key=me.ESC+"OC":a.key=me.ESC+"[C":e.key==="UIKeyInputDownArrow"&&(t?a.key=me.ESC+"OB":a.key=me.ESC+"[B");break;case 8:a.key=e.ctrlKey?"\b":me.DEL,e.altKey&&(a.key=me.ESC+a.key);break;case 9:if(e.shiftKey){a.key=me.ESC+"[Z";break}a.key=me.HT,a.cancel=!0;break;case 13:a.key=e.altKey?me.ESC+me.CR:me.CR,a.cancel=!0;break;case 27:a.key=me.ESC,e.altKey&&(a.key=me.ESC+me.ESC),a.cancel=!0;break;case 37:if(e.metaKey)break;o?a.key=me.ESC+"[1;"+(o+1)+"D":t?a.key=me.ESC+"OD":a.key=me.ESC+"[D";break;case 39:if(e.metaKey)break;o?a.key=me.ESC+"[1;"+(o+1)+"C":t?a.key=me.ESC+"OC":a.key=me.ESC+"[C";break;case 38:if(e.metaKey)break;o?a.key=me.ESC+"[1;"+(o+1)+"A":t?a.key=me.ESC+"OA":a.key=me.ESC+"[A";break;case 40:if(e.metaKey)break;o?a.key=me.ESC+"[1;"+(o+1)+"B":t?a.key=me.ESC+"OB":a.key=me.ESC+"[B";break;case 45:!e.shiftKey&&!e.ctrlKey&&(a.key=me.ESC+"[2~");break;case 46:o?a.key=me.ESC+"[3;"+(o+1)+"~":a.key=me.ESC+"[3~";break;case 36:o?a.key=me.ESC+"[1;"+(o+1)+"H":t?a.key=me.ESC+"OH":a.key=me.ESC+"[H";break;case 35:o?a.key=me.ESC+"[1;"+(o+1)+"F":t?a.key=me.ESC+"OF":a.key=me.ESC+"[F";break;case 33:e.shiftKey?a.type=2:e.ctrlKey?a.key=me.ESC+"[5;"+(o+1)+"~":a.key=me.ESC+"[5~";break;case 34:e.shiftKey?a.type=3:e.ctrlKey?a.key=me.ESC+"[6;"+(o+1)+"~":a.key=me.ESC+"[6~";break;case 112:o?a.key=me.ESC+"[1;"+(o+1)+"P":a.key=me.ESC+"OP";break;case 113:o?a.key=me.ESC+"[1;"+(o+1)+"Q":a.key=me.ESC+"OQ";break;case 114:o?a.key=me.ESC+"[1;"+(o+1)+"R":a.key=me.ESC+"OR";break;case 115:o?a.key=me.ESC+"[1;"+(o+1)+"S":a.key=me.ESC+"OS";break;case 116:o?a.key=me.ESC+"[15;"+(o+1)+"~":a.key=me.ESC+"[15~";break;case 117:o?a.key=me.ESC+"[17;"+(o+1)+"~":a.key=me.ESC+"[17~";break;case 118:o?a.key=me.ESC+"[18;"+(o+1)+"~":a.key=me.ESC+"[18~";break;case 119:o?a.key=me.ESC+"[19;"+(o+1)+"~":a.key=me.ESC+"[19~";break;case 120:o?a.key=me.ESC+"[20;"+(o+1)+"~":a.key=me.ESC+"[20~";break;case 121:o?a.key=me.ESC+"[21;"+(o+1)+"~":a.key=me.ESC+"[21~";break;case 122:o?a.key=me.ESC+"[23;"+(o+1)+"~":a.key=me.ESC+"[23~";break;case 123:o?a.key=me.ESC+"[24;"+(o+1)+"~":a.key=me.ESC+"[24~";break;default:if(e.ctrlKey&&!e.shiftKey&&!e.altKey&&!e.metaKey)e.keyCode>=65&&e.keyCode<=90?a.key=String.fromCharCode(e.keyCode-64):e.keyCode===32?a.key=me.NUL:e.keyCode>=51&&e.keyCode<=55?a.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?a.key=me.DEL:e.keyCode===219?a.key=me.ESC:e.keyCode===220?a.key=me.FS:e.keyCode===221&&(a.key=me.GS);else if((!i||s)&&e.altKey&&!e.metaKey){let h=(c=_E[e.keyCode])==null?void 0:c[e.shiftKey?1:0];if(h)a.key=me.ESC+h;else if(e.keyCode>=65&&e.keyCode<=90){let p=e.ctrlKey?e.keyCode-64:e.keyCode+32,f=String.fromCharCode(p);e.shiftKey&&(f=f.toUpperCase()),a.key=me.ESC+f}else if(e.keyCode===32)a.key=me.ESC+(e.ctrlKey?me.NUL:" ");else if(e.key==="Dead"&&e.code.startsWith("Key")){let p=e.code.slice(3,4);e.shiftKey||(p=p.toLowerCase()),a.key=me.ESC+p,a.cancel=!0}}else i&&!e.altKey&&!e.ctrlKey&&!e.shiftKey&&e.metaKey?e.keyCode===65&&(a.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&e.key.length===1?a.key=e.key:e.key&&e.ctrlKey&&(e.key==="_"&&(a.key=me.US),e.key==="@"&&(a.key=me.NUL));break}return a}var pi=0,vE=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new Ru,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new Ru,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(e){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort((a,o)=>this._getKey(a)-this._getKey(o)),t=0,i=0,s=new Array(this._array.length+this._insertedValues.length);for(let a=0;a=this._array.length||this._getKey(e[t])<=this._getKey(this._array[i])?(s[a]=e[t],t++):s[a]=this._array[i++];this._array=s,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),this._array.length===0)return!1;let t=this._getKey(e);if(t===void 0||(pi=this._search(t),pi===-1)||this._getKey(this._array[pi])!==t)return!1;do if(this._array[pi]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(pi),!0;while(++pia-o),t=0,i=new Array(this._array.length-e.length),s=0;for(let a=0;a0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(pi=this._search(e),!(pi<0||pi>=this._array.length)&&this._getKey(this._array[pi])===e))do yield this._array[pi];while(++pi=this._array.length)&&this._getKey(this._array[pi])===e))do t(this._array[pi]);while(++pi=t;){let s=t+i>>1,a=this._getKey(this._array[s]);if(a>e)i=s-1;else if(a0&&this._getKey(this._array[s-1])===e;)s--;return s}}return t}},ff=0,ev=0,yE=class extends ut{constructor(){super(),this._decorations=new vE(e=>e==null?void 0:e.marker.line),this._onDecorationRegistered=this._register(new Ce),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new Ce),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(ii(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new SE(e);if(t){let i=t.marker.onDispose(()=>t.dispose()),s=t.onDispose(()=>{s.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),i.dispose())});this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,i){let s=0,a=0;for(let o of this._decorations.getKeyIterator(t))s=o.options.x??0,a=s+(o.options.width??1),e>=s&&e{ff=a.options.x??0,ev=ff+(a.options.width??1),e>=ff&&e=this._debounceThresholdMS)this._lastRefreshMs=s,this._innerRefresh();else if(!this._additionalRefreshRequested){let a=s-this._lastRefreshMs,o=this._debounceThresholdMS-a;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},o)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}},tv=20,Du=class extends ut{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 CE(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(Xe(a,"selectionchange",()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(ii(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===` +`&&(this._liveRegionLineCount++,this._liveRegionLineCount===tv+1&&(this._liveRegion.textContent+=Uf.get())))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let i=this._terminal.buffer,s=i.lines.length.toString();for(let a=e;a<=t;a++){let o=i.lines.get(i.ydisp+a),c=[],h=(o==null?void 0:o.translateToString(!0,void 0,void 0,c))||"",p=(i.ydisp+a+1).toString(),f=this._rowElements[a];f&&(h.length===0?(f.textContent=" ",this._rowColumns.set(f,[0,1])):(f.textContent=h,this._rowColumns.set(f,c)),f.setAttribute("aria-posinset",p),f.setAttribute("aria-setsize",s),this._alignRowWidth(f))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(e,t){let i=e.target,s=this._rowElements[t===0?1:this._rowElements.length-2],a=i.getAttribute("aria-posinset"),o=t===0?"1":`${this._terminal.buffer.lines.length}`;if(a===o||e.relatedTarget!==s)return;let c,h;if(t===0?(c=i,h=this._rowElements.pop(),this._rowContainer.removeChild(h)):(c=this._rowElements.shift(),h=i,this._rowContainer.removeChild(c)),c.removeEventListener("focus",this._topBoundaryFocusListener),h.removeEventListener("focus",this._bottomBoundaryFocusListener),t===0){let p=this._createAccessibilityTreeNode();this._rowElements.unshift(p),this._rowContainer.insertAdjacentElement("afterbegin",p)}else{let p=this._createAccessibilityTreeNode();this._rowElements.push(p),this._rowContainer.appendChild(p)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){var h;if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error("anchorNode and/or focusNode are null");return}let t={node:e.anchorNode,offset:e.anchorOffset},i={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(i.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===i.node&&t.offset>i.offset)&&([t,i]=[i,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let s=this._rowElements.slice(-1)[0];if(i.node.compareDocumentPosition(s)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(i={node:s,offset:((h=s.textContent)==null?void 0:h.length)??0}),!this._rowContainer.contains(i.node))return;let a=({node:p,offset:f})=>{let _=p instanceof Text?p.parentNode:p,x=parseInt(_==null?void 0:_.getAttribute("aria-posinset"),10)-1;if(isNaN(x))return console.warn("row is invalid. Race condition?"),null;let b=this._rowColumns.get(_);if(!b)return console.warn("columns is null. Race condition?"),null;let v=f=this._terminal.cols&&(++x,v=0),{row:x,column:v}},o=a(t),c=a(i);if(!(!o||!c)){if(o.row>c.row||o.row===c.row&&o.column>=c.column)throw new Error("invalid range");this._terminal.select(o.column,o.row,(c.row-o.row)*this._terminal.cols-o.column+c.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let t=this._rowContainer.children.length;te;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement("div");return e.setAttribute("role","listitem"),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e{var o;ga(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,(o=this._activeProviderReplies)==null||o.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(Xe(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(Xe(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register(Xe(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register(Xe(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&&kE(this._mouseDownLink.link,this._currentLink.link)&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){!this._currentLink||!this._lastMouseEvent||(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,ga(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:e.link.decorations===void 0?!0:e.link.decorations.underline,pointerCursor:e.link.decorations===void 0?!0:e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>{var i,s;return(s=(i=this._currentLink)==null?void 0:i.state)==null?void 0:s.decorations.pointerCursor},set:i=>{var s;(s=this._currentLink)!=null&&s.state&&this._currentLink.state.decorations.pointerCursor!==i&&(this._currentLink.state.decorations.pointerCursor=i,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",i))}},underline:{get:()=>{var i,s;return(s=(i=this._currentLink)==null?void 0:i.state)==null?void 0:s.decorations.underline},set:i=>{var s,a,o;(s=this._currentLink)!=null&&s.state&&((o=(a=this._currentLink)==null?void 0:a.state)==null?void 0:o.decorations.underline)!==i&&(this._currentLink.state.decorations.underline=i,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,i))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(i=>{if(!this._currentLink)return;let s=i.start===0?0:i.start+1+this._bufferService.buffer.ydisp,a=this._bufferService.buffer.ydisp+1+i.end;if(this._currentLink.link.range.start.y>=s&&this._currentLink.link.range.end.y<=a&&(this._clearCurrentLink(s,a),this._lastMouseEvent)){let o=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);o&&this._askForLink(o,!1)}})))}_linkHover(e,t,i){var s;(s=this._currentLink)!=null&&s.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add("xterm-cursor-pointer")),t.hover&&t.hover(i,t.text)}_fireUnderlineEvent(e,t){let i=e.range,s=this._bufferService.buffer.ydisp,a=this._createLinkUnderlineEvent(i.start.x-1,i.start.y-s-1,i.end.x,i.end.y-s-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(a)}_linkLeave(e,t,i){var s;(s=this._currentLink)!=null&&s.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove("xterm-cursor-pointer")),t.leave&&t.leave(i,t.text)}_linkAtPosition(e,t){let i=e.range.start.y*this._bufferService.cols+e.range.start.x,s=e.range.end.y*this._bufferService.cols+e.range.end.x,a=t.y*this._bufferService.cols+t.x;return i<=a&&a<=s}_positionFromMouseEvent(e,t,i){let s=i.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(s)return{x:s[0],y:s[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,i,s,a){return{x1:e,y1:t,x2:i,y2:s,cols:this._bufferService.cols,fg:a}}};Sp=ci([De(1,Fp),De(2,rs),De(3,pn),De(4,Hy)],Sp);function kE(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 EE=class extends xE{constructor(e={}){super(e),this._linkifier=this._register(new pl),this.browser=s0,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new pl),this._onCursorMove=this._register(new Ce),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new Ce),this.onKey=this._onKey.event,this._onRender=this._register(new Ce),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new Ce),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new Ce),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new Ce),this.onBell=this._onBell.event,this._onFocus=this._register(new Ce),this._onBlur=this._register(new Ce),this._onA11yCharEmitter=this._register(new Ce),this._onA11yTabEmitter=this._register(new Ce),this._onWillOpen=this._register(new Ce),this._setup(),this._decorationService=this._instantiationService.createInstance(yE),this._instantiationService.setService(Io,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(m2),this._instantiationService.setService(Hy,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(Ff)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(t=>this.refresh((t==null?void 0:t.start)??0,(t==null?void 0:t.end)??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(t=>this._reportWindowsOptions(t))),this._register(this._inputHandler.onColor(t=>this._handleColorEvent(t))),this._register(en.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(en.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(en.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(en.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(t=>this._afterResize(t.cols,t.rows))),this._register(ii(()=>{var t,i;this._customKeyEventHandler=void 0,(i=(t=this.element)==null?void 0:t.parentNode)==null||i.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(e){if(this._themeService)for(let t of e){let i,s="";switch(t.index){case 256:i="foreground",s="10";break;case 257:i="background",s="11";break;case 258:i="cursor",s="12";break;default:i="ansi",s="4;"+t.index}switch(t.type){case 0:let a=Qt.toColorRGB(i==="ansi"?this._themeService.colors.ansi[t.index]:this._themeService.colors[i]);this.coreService.triggerDataEvent(`${me.ESC}]${s};${hE(a)}${n0.ST}`);break;case 1:if(i==="ansi")this._themeService.modifyColors(o=>o.ansi[t.index]=wi.toColor(...t.color));else{let o=i;this._themeService.modifyColors(c=>c[o]=wi.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index);break}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(Du,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(me.ESC+"[I"),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()}blur(){var e;return(e=this.textarea)==null?void 0:e.blur()}_handleTextAreaBlur(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(me.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;let i=Math.min(this.buffer.x,this.cols-1),s=this._renderService.dimensions.css.cell.height,a=t.getWidth(i),o=this._renderService.dimensions.css.cell.width*a,c=this.buffer.y*this._renderService.dimensions.css.cell.height,h=i*this._renderService.dimensions.css.cell.width;this.textarea.style.left=h+"px",this.textarea.style.top=c+"px",this.textarea.style.width=o+"px",this.textarea.style.height=s+"px",this.textarea.style.lineHeight=s+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this._register(Xe(this.element,"copy",t=>{this.hasSelection()&&AC(t,this._selectionService)}));let e=t=>RC(t,this.textarea,this.coreService,this.optionsService);this._register(Xe(this.textarea,"paste",e)),this._register(Xe(this.element,"paste",e)),a0?this._register(Xe(this.element,"mousedown",t=>{t.button===2&&hb(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(Xe(this.element,"contextmenu",t=>{hb(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),Zp&&this._register(Xe(this.element,"auxclick",t=>{t.button===1&&Ry(t,this.textarea,this.screenElement)}))}_bindKeys(){this._register(Xe(this.textarea,"keyup",e=>this._keyUp(e),!0)),this._register(Xe(this.textarea,"keydown",e=>this._keyDown(e),!0)),this._register(Xe(this.textarea,"keypress",e=>this._keyPress(e),!0)),this._register(Xe(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register(Xe(this.textarea,"compositionupdate",e=>this._compositionHelper.compositionupdate(e))),this._register(Xe(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register(Xe(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(Xe(this.screenElement,"mousemove",o=>this.updateCursorStyle(o))),this._helperContainer=this._document.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let i=this.textarea=this._document.createElement("textarea");this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",Hf.get()),c0||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(f2,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(ns,this._coreBrowserService),this._register(Xe(this.textarea,"focus",o=>this._handleTextAreaFocus(o))),this._register(Xe(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(up,this._document,this._helperContainer),this._instantiationService.setService(Iu,this._charSizeService),this._themeService=this._instantiationService.createInstance(pp),this._instantiationService.setService(xl,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(Tu),this._instantiationService.setService(Iy,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(dp,this.rows,this.screenElement)),this._instantiationService.setService(rs,this._renderService),this._register(this._renderService.onRenderedViewportChange(o=>this._onRender.fire(o))),this.onResize(o=>this._renderService.resize(o.cols,o.rows)),this._compositionView=this._document.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(lp,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(hp),this._instantiationService.setService(Fp,this._mouseService);let s=this._linkifier.value=this._register(this._instantiationService.createInstance(Sp,this.screenElement));this.element.appendChild(t);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(sp,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(o=>{super.scrollLines(o,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(fp,this.element,this.screenElement,s)),this._instantiationService.setService(IC,this._selectionService),this._register(this._selectionService.onRequestScrollLines(o=>this.scrollLines(o.amount,o.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(o=>this._renderService.handleSelectionChanged(o.start,o.end,o.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(o=>{this.textarea.value=o,this.textarea.focus(),this.textarea.select()})),this._register(en.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{var o;this._selectionService.refresh(),(o=this._viewport)==null||o.queueSync()})),this._register(this._instantiationService.createInstance(ap,this.screenElement)),this._register(Xe(this.element,"mousedown",o=>this._selectionService.handleMouseDown(o))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add("enable-mouse-events")):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(Du,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",o=>this._handleScreenReaderModeOptionChange(o))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(ju,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",o=>{!this._overviewRulerRenderer&&o&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(ju,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(cp,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function i(o){var f,_,x,b,v;let c=e._mouseService.getMouseReportCoords(o,e.screenElement);if(!c)return!1;let h,p;switch(o.overrideType||o.type){case"mousemove":p=32,o.buttons===void 0?(h=3,o.button!==void 0&&(h=o.button<3?o.button:3)):h=o.buttons&1?0:o.buttons&4?1:o.buttons&2?2:3;break;case"mouseup":p=0,h=o.button<3?o.button:3;break;case"mousedown":p=1,h=o.button<3?o.button:3;break;case"wheel":if(e._customWheelEventHandler&&e._customWheelEventHandler(o)===!1)return!1;let S=o.deltaY;if(S===0||e.coreMouseService.consumeWheelEvent(o,(b=(x=(_=(f=e._renderService)==null?void 0:f.dimensions)==null?void 0:_.device)==null?void 0:x.cell)==null?void 0:b.height,(v=e._coreBrowserService)==null?void 0:v.dpr)===0)return!1;p=S<0?0:1,h=4;break;default:return!1}return p===void 0||h===void 0||h>4?!1:e.coreMouseService.triggerMouseEvent({col:c.col,row:c.row,x:c.x,y:c.y,button:h,action:p,ctrl:o.ctrlKey,alt:o.altKey,shift:o.shiftKey})}let s={mouseup:null,wheel:null,mousedrag:null,mousemove:null},a={mouseup:o=>(i(o),o.buttons||(this._document.removeEventListener("mouseup",s.mouseup),s.mousedrag&&this._document.removeEventListener("mousemove",s.mousedrag)),this.cancel(o)),wheel:o=>(i(o),this.cancel(o,!0)),mousedrag:o=>{o.buttons&&i(o)},mousemove:o=>{o.buttons||i(o)}};this._register(this.coreMouseService.onProtocolChange(o=>{o?(this.optionsService.rawOptions.logLevel==="debug"&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(o)),this.element.classList.add("enable-mouse-events"),this._selectionService.disable()):(this._logService.debug("Unbinding from mouse events."),this.element.classList.remove("enable-mouse-events"),this._selectionService.enable()),o&8?s.mousemove||(t.addEventListener("mousemove",a.mousemove),s.mousemove=a.mousemove):(t.removeEventListener("mousemove",s.mousemove),s.mousemove=null),o&16?s.wheel||(t.addEventListener("wheel",a.wheel,{passive:!1}),s.wheel=a.wheel):(t.removeEventListener("wheel",s.wheel),s.wheel=null),o&2?s.mouseup||(s.mouseup=a.mouseup):(this._document.removeEventListener("mouseup",s.mouseup),s.mouseup=null),o&4?s.mousedrag||(s.mousedrag=a.mousedrag):(this._document.removeEventListener("mousemove",s.mousedrag),s.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(Xe(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(Xe(t,"wheel",o=>{var c,h,p,f,_;if(!s.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(o)===!1)return!1;if(!this.buffer.hasScrollback){if(o.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(o,(f=(p=(h=(c=e._renderService)==null?void 0:c.dimensions)==null?void 0:h.device)==null?void 0:p.cell)==null?void 0:f.height,(_=e._coreBrowserService)==null?void 0:_.dpr)===0)return this.cancel(o,!0);let x=me.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(o.deltaY<0?"A":"B");return this.coreService.triggerDataEvent(x,!0),this.cancel(o,!0)}}},{passive:!1}))}refresh(e,t){var i;(i=this._renderService)==null||i.refreshRows(e,t)}updateCursorStyle(e){var t;(t=this._selectionService)!=null&&t.shouldColumnSelect(e)?this.element.classList.add("column-select"):this.element.classList.remove("column-select")}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,t){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,t),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}paste(e){Ay(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=bE(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),i.type===3||i.type===2){let s=this.rows-1;return this.scrollLines(i.type===2?-s:s),this.cancel(e,!0)}if(i.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(i.cancel&&this.cancel(e,!0),!i.key)||e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.key.length===1&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)return!0;if(this._unprocessedDeadKey)return this._unprocessedDeadKey=!1,!0;if((i.key===me.ETX||i.key===me.CR)&&(this.textarea.value=""),this._onKey.fire({key:i.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(i.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,t){let i=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState("AltGraph");return t.type==="keypress"?i:i&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&(NE(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)}},iv=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 TE(t)}getNullCell(){return new sr}},AE=class extends ut{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new Ce),this.onBufferChange=this._onBufferChange.event,this._normal=new iv(this._core.buffers.normal,"normal"),this._alternate=new iv(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)}},RE=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)}},DE=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}},ME=["cols","rows"],Er=0,BE=class extends ut{constructor(e){super(),this._core=this._register(new EE(e)),this._addonManager=this._register(new jE),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(ME.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 RE(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new DE(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 AE(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t="none";switch(this._core.coreMouseService.activeProtocol){case"X10":t="x10";break;case"VT200":t="vt200";break;case"DRAG":t="drag";break;case"ANY":t="any";break}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,i){this._verifyIntegers(e,t,i),this._core.select(e,t,i)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\r +`,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return Hf.get()},set promptLabel(e){Hf.set(e)},get tooMuchOutput(){return Uf.get()},set tooMuchOutput(e){Uf.set(e)}}}_verifyIntegers(...e){for(Er of e)if(Er===1/0||isNaN(Er)||Er%1!==0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(Er of e)if(Er&&(Er===1/0||isNaN(Er)||Er%1!==0||Er<0))throw new Error("This API only accepts positive integers")}};/** + * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved. + * @license MIT + * + * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) + * @license MIT + * + * Originally forked from (with the author's permission): + * Fabrice Bellard's javascript vt100 for jslinux: + * http://bellard.org/jslinux/ + * Copyright (c) 2011 Fabrice Bellard + */var LE=2,OE=1,zE=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(LE,Math.floor(_/e.css.cell.width)),rows:Math.max(OE,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,oi=0,rn;(e=>{function t(a,o,c,h){return h!==void 0?`#${ca(a)}${ca(o)}${ca(c)}${ca(h)}`:`#${ca(a)}${ca(o)}${ca(c)}`}e.toCss=t;function i(a,o,c,h=255){return(a<<24|o<<16|c<<8|h)>>>0}e.toRgba=i;function s(a,o,c,h){return{css:e.toCss(a,o,c,h),rgba:e.toRgba(a,o,c,h)}}e.toColor=s})(rn||(rn={}));var PE;(e=>{function t(p,f){if(oi=(f.rgba&255)/255,oi===1)return{css:f.css,rgba:f.rgba};let _=f.rgba>>24&255,x=f.rgba>>16&255,b=f.rgba>>8&255,v=p.rgba>>24&255,S=p.rgba>>16&255,j=p.rgba>>8&255;Pi=v+Math.round((_-v)*oi),Ii=S+Math.round((x-S)*oi),Hi=j+Math.round((b-j)*oi);let R=rn.toCss(Pi,Ii,Hi),E=rn.toRgba(Pi,Ii,Hi);return{css:R,rgba:E}}e.blend=t;function i(p){return(p.rgba&255)===255}e.isOpaque=i;function s(p,f,_){let x=Su.ensureContrastRatio(p.rgba,f.rgba,_);if(x)return rn.toColor(x>>24&255,x>>16&255,x>>8&255)}e.ensureContrastRatio=s;function a(p){let f=(p.rgba|255)>>>0;return[Pi,Ii,Hi]=Su.toChannels(f),{css:rn.toCss(Pi,Ii,Hi),rgba:f}}e.opaque=a;function o(p,f){return oi=Math.round(f*255),[Pi,Ii,Hi]=Su.toChannels(p.rgba),{css:rn.toCss(Pi,Ii,Hi,oi),rgba:rn.toRgba(Pi,Ii,Hi,oi)}}e.opacity=o;function c(p,f){return oi=p.rgba&255,o(p,oi*f/255)}e.multiplyOpacity=c;function h(p){return[p.rgba>>24&255,p.rgba>>16&255,p.rgba>>8&255]}e.toColorRGB=h})(PE||(PE={}));var Qi;(e=>{let t,i;try{let a=document.createElement("canvas");a.width=1,a.height=1;let o=a.getContext("2d",{willReadFrequently:!0});o&&(t=o,t.globalCompositeOperation="copy",i=t.createLinearGradient(0,0,1,1))}catch{}function s(a){if(a.match(/#[\da-f]{3,8}/i))switch(a.length){case 4:return Pi=parseInt(a.slice(1,2).repeat(2),16),Ii=parseInt(a.slice(2,3).repeat(2),16),Hi=parseInt(a.slice(3,4).repeat(2),16),rn.toColor(Pi,Ii,Hi);case 5:return Pi=parseInt(a.slice(1,2).repeat(2),16),Ii=parseInt(a.slice(2,3).repeat(2),16),Hi=parseInt(a.slice(3,4).repeat(2),16),oi=parseInt(a.slice(4,5).repeat(2),16),rn.toColor(Pi,Ii,Hi,oi);case 7:return{css:a,rgba:(parseInt(a.slice(1),16)<<8|255)>>>0};case 9:return{css:a,rgba:parseInt(a.slice(1),16)>>>0}}let o=a.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(o)return Pi=parseInt(o[1]),Ii=parseInt(o[2]),Hi=parseInt(o[3]),oi=Math.round((o[5]===void 0?1:parseFloat(o[5]))*255),rn.toColor(Pi,Ii,Hi,oi);if(!t||!i)throw new Error("css.toColor: Unsupported css format");if(t.fillStyle=i,t.fillStyle=a,typeof t.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(t.fillRect(0,0,1,1),[Pi,Ii,Hi,oi]=t.getImageData(0,0,1,1).data,oi!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:rn.toRgba(Pi,Ii,Hi,oi),css:a}}e.toColor=s})(Qi||(Qi={}));var dn;(e=>{function t(s){return i(s>>16&255,s>>8&255,s&255)}e.relativeLuminance=t;function i(s,a,o){let c=s/255,h=a/255,p=o/255,f=c<=.03928?c/12.92:Math.pow((c+.055)/1.055,2.4),_=h<=.03928?h/12.92:Math.pow((h+.055)/1.055,2.4),x=p<=.03928?p/12.92:Math.pow((p+.055)/1.055,2.4);return f*.2126+_*.7152+x*.0722}e.relativeLuminance2=i})(dn||(dn={}));var Su;(e=>{function t(c,h){if(oi=(h&255)/255,oi===1)return h;let p=h>>24&255,f=h>>16&255,_=h>>8&255,x=c>>24&255,b=c>>16&255,v=c>>8&255;return Pi=x+Math.round((p-x)*oi),Ii=b+Math.round((f-b)*oi),Hi=v+Math.round((_-v)*oi),rn.toRgba(Pi,Ii,Hi)}e.blend=t;function i(c,h,p){let f=dn.relativeLuminance(c>>8),_=dn.relativeLuminance(h>>8);if(Jr(f,_)>8));if(S>8));return S>R?v:j}return v}let x=a(c,h,p),b=Jr(f,dn.relativeLuminance(x>>8));if(b>8));return b>S?x:v}return x}}e.ensureContrastRatio=i;function s(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,j=Jr(dn.relativeLuminance2(b,v,S),dn.relativeLuminance2(f,_,x));for(;j0||v>0||S>0);)b-=Math.max(0,Math.ceil(b*.1)),v-=Math.max(0,Math.ceil(v*.1)),S-=Math.max(0,Math.ceil(S*.1)),j=Jr(dn.relativeLuminance2(b,v,S),dn.relativeLuminance2(f,_,x));return(b<<24|v<<16|S<<8|255)>>>0}e.reduceLuminance=s;function a(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,j=Jr(dn.relativeLuminance2(b,v,S),dn.relativeLuminance2(f,_,x));for(;j>>0}e.increaseLuminance=a;function o(c){return[c>>24&255,c>>16&255,c>>8&255,c&255]}e.toChannels=o})(Su||(Su={}));function ca(e){let t=e.toString(16);return t.length<2?"0"+t:t}function Jr(e,t){return e{let e=[Qi.toColor("#2e3436"),Qi.toColor("#cc0000"),Qi.toColor("#4e9a06"),Qi.toColor("#c4a000"),Qi.toColor("#3465a4"),Qi.toColor("#75507b"),Qi.toColor("#06989a"),Qi.toColor("#d3d7cf"),Qi.toColor("#555753"),Qi.toColor("#ef2929"),Qi.toColor("#8ae234"),Qi.toColor("#fce94f"),Qi.toColor("#729fcf"),Qi.toColor("#ad7fa8"),Qi.toColor("#34e2e2"),Qi.toColor("#eeeeec")],t=[0,95,135,175,215,255];for(let i=0;i<216;i++){let s=t[i/36%6|0],a=t[i/6%6|0],o=t[i%6];e.push({css:rn.toCss(s,a,o),rgba:rn.toRgba(s,a,o)})}for(let i=0;i<24;i++){let s=8+i*10;e.push({css:rn.toCss(s,s,s),rgba:rn.toRgba(s,s,s)})}return e})());function nv(e,t,i){return Math.max(t,Math.min(e,i))}function HE(e){switch(e){case"&":return"&";case"<":return"<"}return e}var b0=class{constructor(e){this._buffer=e}serialize(e,t){let i=this._buffer.getNullCell(),s=this._buffer.getNullCell(),a=i,o=e.start.y,c=e.end.y,h=e.start.x,p=e.end.x;this._beforeSerialize(c-o,o,c);for(let f=o;f<=c;f++){let _=this._buffer.getLine(f);if(_){let x=f===e.start.y?h:0,b=f===e.end.y?p:_.length;for(let v=x;v0&&!es(this._cursorStyle,this._backgroundCell)&&(this._currentRow+=`\x1B[${this._nullCellCount}X`);let i="";if(!t){e-this._firstRow>=this._terminal.rows&&((s=this._buffer.getLine(this._cursorStyleRow))==null||s.getCell(this._cursorStyleCol,this._backgroundCell));let a=this._buffer.getLine(e),o=this._buffer.getLine(e+1);if(!o.isWrapped)i=`\r +`,this._lastCursorRow=e+1,this._lastCursorCol=0;else{i="";let c=a.getCell(a.length-1,this._thisRowLastChar),h=a.getCell(a.length-2,this._thisRowLastSecondChar),p=o.getCell(0,this._nextRowFirstChar),f=p.getWidth()>1,_=!1;(p.getChars()&&f?this._nullCellCount<=1:this._nullCellCount<=0)&&((c.getChars()||c.getWidth()===0)&&es(c,p)&&(_=!0),f&&(h.getChars()||h.getWidth()===0)&&es(c,p)&&es(h,p)&&(_=!0)),_||(i="-".repeat(this._nullCellCount+1),i+="\x1B[1D\x1B[1X",this._nullCellCount>0&&(i+="\x1B[A",i+=`\x1B[${a.length-this._nullCellCount}C`,i+=`\x1B[${this._nullCellCount}X`,i+=`\x1B[${a.length-this._nullCellCount}D`,i+="\x1B[B"),this._lastContentCursorRow=e+1,this._lastContentCursorCol=0,this._lastCursorRow=e+1,this._lastCursorCol=0)}}this._allRows[this._rowIndex]=this._currentRow,this._allRowSeparators[this._rowIndex++]=i,this._currentRow="",this._nullCellCount=0}_diffStyle(e,t){let i=[],s=!v0(e,t),a=!es(e,t),o=!y0(e,t);if(s||a||o)if(e.isAttributeDefault())t.isAttributeDefault()||i.push(0);else{if(s){let c=e.getFgColor();e.isFgRGB()?i.push(38,2,c>>>16&255,c>>>8&255,c&255):e.isFgPalette()?c>=16?i.push(38,5,c):i.push(c&8?90+(c&7):30+(c&7)):i.push(39)}if(a){let c=e.getBgColor();e.isBgRGB()?i.push(48,2,c>>>16&255,c>>>8&255,c&255):e.isBgPalette()?c>=16?i.push(48,5,c):i.push(c&8?100+(c&7):40+(c&7)):i.push(49)}o&&(e.isInverse()!==t.isInverse()&&i.push(e.isInverse()?7:27),e.isBold()!==t.isBold()&&i.push(e.isBold()?1:22),e.isUnderline()!==t.isUnderline()&&i.push(e.isUnderline()?4:24),e.isOverline()!==t.isOverline()&&i.push(e.isOverline()?53:55),e.isBlink()!==t.isBlink()&&i.push(e.isBlink()?5:25),e.isInvisible()!==t.isInvisible()&&i.push(e.isInvisible()?8:28),e.isItalic()!==t.isItalic()&&i.push(e.isItalic()?3:23),e.isDim()!==t.isDim()&&i.push(e.isDim()?2:22),e.isStrikethrough()!==t.isStrikethrough()&&i.push(e.isStrikethrough()?9:29))}return i}_nextCell(e,t,i,s){if(e.getWidth()===0)return;let a=e.getChars()==="",o=this._diffStyle(e,this._cursorStyle);if(a?!es(this._cursorStyle,e):o.length>0){this._nullCellCount>0&&(es(this._cursorStyle,this._backgroundCell)||(this._currentRow+=`\x1B[${this._nullCellCount}X`),this._currentRow+=`\x1B[${this._nullCellCount}C`,this._nullCellCount=0),this._lastContentCursorRow=this._lastCursorRow=i,this._lastContentCursorCol=this._lastCursorCol=s,this._currentRow+=`\x1B[${o.join(";")}m`;let c=this._buffer.getLine(i);c!==void 0&&(c.getCell(s,this._cursorStyle),this._cursorStyleRow=i,this._cursorStyleCol=s)}a?this._nullCellCount+=e.getWidth():(this._nullCellCount>0&&(es(this._cursorStyle,this._backgroundCell)?this._currentRow+=`\x1B[${this._nullCellCount}C`:(this._currentRow+=`\x1B[${this._nullCellCount}X`,this._currentRow+=`\x1B[${this._nullCellCount}C`),this._nullCellCount=0),this._currentRow+=e.getChars(),this._lastContentCursorRow=this._lastCursorRow=i,this._lastContentCursorCol=this._lastCursorCol=s+e.getWidth())}_serializeString(e){let t=this._allRows.length;this._buffer.length-this._firstRow<=this._terminal.rows&&(t=this._lastContentCursorRow+1-this._firstRow,this._lastCursorCol=this._lastContentCursorCol,this._lastCursorRow=this._lastContentCursorRow);let i="";for(let o=0;o{f>0?i+=`\x1B[${f}C`:f<0&&(i+=`\x1B[${-f}D`)};h&&((f=>{f>0?i+=`\x1B[${f}B`:f<0&&(i+=`\x1B[${-f}A`)})(o-this._lastCursorRow),p(c-this._lastCursorCol))}let s=this._terminal._core._inputHandler._curAttrData,a=this._diffStyle(s,this._cursorStyle);return a.length>0&&(i+=`\x1B[${a.join(";")}m`),i}},$E=class{activate(e){this._terminal=e}_serializeBufferByScrollback(e,t,i){let s=t.length,a=i===void 0?s:nv(i+e.rows,0,s);return this._serializeBufferByRange(e,t,{start:s-a,end:s-1},!1)}_serializeBufferByRange(e,t,i,s){return new UE(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 FE(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:nv(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(){}},FE=class extends b0{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=IE}_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=!v0(e,t),a=!es(e,t),o=!y0(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+=HE(e.getChars())}_serializeString(){return this._htmlContent}};const qE="__OWS_FRESH_SESSION__",rl="[REDACTED]",WE=[[/(authorization\s*:\s*bearer\s+)[^\s'"\x1b]+/gi,`$1${rl}`],[/(\bbearer\s+)[A-Za-z0-9._-]{12,}/gi,`$1${rl}`],[/(\btoken=)[^\s'"&\x1b]+/gi,`$1${rl}`],[/(OWS_PASSPHRASE\s*[=:]\s*)[^\s'"\x1b]+/gi,`$1${rl}`],[/(--passphrase[=\s]+)[^\s'"\x1b]+/gi,`$1${rl}`],[/(passphrase["']?\s*[:=]\s*["']?)[^\s'"\x1b]+/gi,`$1${rl}`]];function rv(e){let t=e;for(const[i,s]of WE)t=t.replace(i,s);return t}const sv="codex features enable image_generation";function GE(e,t){return e!=="cartoon"||!t?!1:!(t.codex.installed&&t.codex.imageGeneration==="enabled")}const YE={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"},KE="plotlink-terminal",VE=1,Us="scrollback",av=10*1024*1024;function Qp(){return new Promise((e,t)=>{const i=indexedDB.open(KE,VE);i.onupgradeneeded=()=>{const s=i.result;s.objectStoreNames.contains(Us)||s.createObjectStore(Us)},i.onsuccess=()=>e(i.result),i.onerror=()=>t(i.error)})}async function sl(e,t){const i=t.length>av?t.slice(-av):t,s=await Qp();return new Promise((a,o)=>{const c=s.transaction(Us,"readwrite");c.objectStore(Us).put(i,e),c.oncomplete=()=>{s.close(),a()},c.onerror=()=>{s.close(),o(c.error)}})}async function XE(e){const t=await Qp();return new Promise((i,s)=>{const o=t.transaction(Us,"readonly").objectStore(Us).get(e);o.onsuccess=()=>{t.close(),i(o.result??null)},o.onerror=()=>{t.close(),s(o.error)}})}async function pf(e){const t=await Qp();return new Promise((i,s)=>{const a=t.transaction(Us,"readwrite");a.objectStore(Us).delete(e),a.oncomplete=()=>{t.close(),i()},a.onerror=()=>{t.close(),s(a.error)}})}const Ri=new Map;function ZE({token:e,storyName:t,authFetch:i,onSelectStory:s,onDestroySession:a,onArchiveStory:o,confirmedStories:c,renameRef:h,bypassStories:p,agentProviders:f,readiness:_,contentType:x,needsProviderRepair:b,onRepairProvider:v}){const S=w.useRef(null),j=w.useRef(i),[R,E]=w.useState([]),[N,I]=w.useState(new Set),[te,F]=w.useState(null),[D,ie]=w.useState(null),[fe,Se]=w.useState(!1),[H,ce]=w.useState(!1),W=GE(x,_),K=!!b,X=w.useRef(()=>{});w.useEffect(()=>{j.current=i},[i]);const U=w.useCallback(Y=>{var _e;const{width:he}=Y.container.getBoundingClientRect();if(!(he<50))try{Y.fit.fit(),((_e=Y.ws)==null?void 0:_e.readyState)===WebSocket.OPEN&&Y.ws.send(JSON.stringify({type:"resize",cols:Y.term.cols,rows:Y.term.rows}))}catch{}},[]),A=w.useCallback(Y=>{for(const[he,_e]of Ri)_e.container.style.display=he===Y?"block":"none";if(Y){const he=Ri.get(Y);he&&setTimeout(()=>U(he),50)}},[U]),O=w.useRef({});w.useEffect(()=>{O.current=p||{}},[p]);const $=w.useRef({});w.useEffect(()=>{$.current=f||{}},[f]);const xe=w.useCallback((Y,he,_e)=>{const Be=window.location.protocol==="https:"?"wss:":"ws:",Le=O.current[Y]?"&bypass=true":"",je=$.current[Y],be=je?`&provider=${encodeURIComponent(je)}`:"",tt=new WebSocket(`${Be}//${window.location.host}/ws/terminal?story=${encodeURIComponent(Y)}&token=${e}&resume=${_e}${Le}${be}`);tt.onopen=()=>{he.connected=!0,he._retried=!1,I(ot=>{const We=new Set(ot);return We.delete(Y),We}),tt.send(JSON.stringify({type:"resize",cols:he.term.cols,rows:he.term.rows}))};let St=!0;tt.onmessage=ot=>{if(St&&(St=!1,typeof ot.data=="string"&&ot.data===qE)){he.term.reset(),pf(Y).catch(()=>{});return}he.term.write(typeof ot.data=="string"?rv(ot.data):ot.data)},tt.onclose=ot=>{if(he.connected=!1,he.ws===tt){he.ws=null;try{const We=he.serialize.serialize();sl(Y,We).catch(()=>{})}catch{}if(ot.code===4e3&&!he._retried){he._retried=!0,he.term.write(`\r +\x1B[33m[Resume failed — starting fresh session...]\x1B[0m\r +`),X.current(Y,he,!1);return}I(We=>new Set(We).add(Y))}},he.term.onData(ot=>{tt.readyState===WebSocket.OPEN&&tt.send(ot)}),he.ws=tt},[e]);w.useEffect(()=>{X.current=xe},[xe]);const T=w.useCallback(async(Y,he)=>{if(!S.current||Ri.has(Y))return;const{resume:_e=!1,autoConnect:Be=!0}=he??{},Le=document.createElement("div");Le.style.width="100%",Le.style.height="100%",Le.style.display="none",Le.style.paddingLeft="10px",Le.style.boxSizing="border-box",S.current.appendChild(Le);const je=new BE({cols:80,scrollback:5e3,fontSize:13,fontFamily:'"Geist Mono", ui-monospace, monospace',lineHeight:1.05,letterSpacing:0,cursorBlink:!0,cursorStyle:"block",theme:YE,allowTransparency:!1,drawBoldTextInBrightColors:!1,minimumContrastRatio:7}),be=new zE,tt=new $E;je.loadAddon(be),je.loadAddon(tt),je.open(Le);const St={term:je,fit:be,serialize:tt,ws:null,container:Le,observer:null,connected:!1},ot=new ResizeObserver(()=>{var Mt;const{width:We}=Le.getBoundingClientRect();if(!(We<50))try{be.fit(),((Mt=St.ws)==null?void 0:Mt.readyState)===WebSocket.OPEN&&St.ws.send(JSON.stringify({type:"resize",cols:je.cols,rows:je.rows}))}catch{}});ot.observe(Le),St.observer=ot,Ri.set(Y,St),E(We=>[...We,Y]);try{const We=await XE(Y);if(We){const Mt=rv(We);je.write(Mt),Mt!==We&&sl(Y,Mt).catch(()=>{})}}catch{}Be?xe(Y,St,_e):I(We=>new Set(We).add(Y)),setTimeout(()=>U(St),50)},[xe,U]),M=w.useCallback(async(Y,he)=>{const _e=Ri.get(Y);_e&&(_e.ws&&(_e.ws.close(),_e.ws=null),he||(await j.current(`/api/terminal/${encodeURIComponent(Y)}`,{method:"DELETE"}).catch(()=>{}),_e.term.clear()),xe(Y,_e,he))},[xe]),G=w.useCallback(Y=>{const he=Ri.get(Y);if(he){try{const _e=he.serialize.serialize();sl(Y,_e).catch(()=>{})}catch{}he.observer.disconnect(),he.ws&&he.ws.close(),he.term.dispose(),he.container.remove(),Ri.delete(Y),E(_e=>_e.filter(Be=>Be!==Y)),I(_e=>{const Be=new Set(_e);return Be.delete(Y),Be}),i(`/api/terminal/${encodeURIComponent(Y)}`,{method:"DELETE"}).catch(()=>{}),a==null||a(Y)}},[i,a]),C=w.useCallback(Y=>{var _e;const he=Ri.get(Y);he&&(((_e=he.ws)==null?void 0:_e.readyState)===WebSocket.OPEN&&he.ws.send(`exit +`),pf(Y).catch(()=>{}),he.observer.disconnect(),he.ws&&he.ws.close(),he.term.dispose(),he.container.remove(),Ri.delete(Y),E(Be=>Be.filter(Le=>Le!==Y)),I(Be=>{const Le=new Set(Be);return Le.delete(Y),Le}),i(`/api/terminal/${encodeURIComponent(Y)}/discard`,{method:"DELETE"}).catch(()=>{}),a==null||a(Y))},[i,a]),V=w.useCallback(async(Y,he,_e)=>{const Be=Ri.get(Y);if(!Be||Ri.has(he)||!(await j.current("/api/terminal/rename",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldName:Y,newName:he,..._e??{}})})).ok)return!1;Ri.delete(Y),Ri.set(he,Be);try{const je=Be.serialize.serialize();await pf(Y),await sl(he,je)}catch{}return E(je=>je.map(be=>be===Y?he:be)),I(je=>{if(!je.has(Y))return je;const be=new Set(je);return be.delete(Y),be.add(he),be}),(Be.connected||Be.ws)&&(await j.current(`/api/terminal/${encodeURIComponent(he)}`,{method:"DELETE"}).catch(()=>{}),Be.ws&&(Be.ws.close(),Be.ws=null),X.current(he,Be,!0)),!0},[]);w.useEffect(()=>(h&&(h.current=V),()=>{h&&(h.current=null)}),[h,V]),w.useEffect(()=>{if(t){if(W){A(null);return}if(K){A(null);return}Ri.has(t)?A(t):j.current(`/api/terminal/session/${encodeURIComponent(t)}`).then(Y=>Y.ok?Y.json():null).then(Y=>{if(!Ri.has(t)){const he=(Y==null?void 0:Y.sessionId)&&!(Y!=null&&Y.running);T(t,{autoConnect:!he}),A(t)}}).catch(()=>{Ri.has(t)||(T(t),A(t))})}},[t,T,A,W,K]),w.useEffect(()=>{const Y=setInterval(()=>{for(const[he,_e]of Ri)if(_e.connected)try{const Be=_e.serialize.serialize();sl(he,Be).catch(()=>{})}catch{}},3e4);return()=>clearInterval(Y)},[]),w.useEffect(()=>()=>{for(const[Y,he]of Ri){try{const _e=he.serialize.serialize();sl(Y,_e).catch(()=>{})}catch{}he.observer.disconnect(),he.ws&&he.ws.close(),he.term.dispose(),he.container.remove(),j.current(`/api/terminal/${encodeURIComponent(Y)}`,{method:"DELETE"}).catch(()=>{})}Ri.clear()},[]);const ne=t?N.has(t):!1,ae=R.length===0;return d.jsxs("div",{className:"h-full flex flex-col",children:[!ae&&d.jsxs("div",{className:"px-2 py-1 border-b border-border flex items-center gap-1 overflow-x-auto",children:[R.map(Y=>d.jsxs("div",{onClick:()=>s==null?void 0:s(Y),className:`flex items-center gap-1 px-2 py-0.5 rounded text-xs font-mono cursor-pointer ${Y===t?"bg-accent/10 text-accent":"text-muted hover:text-foreground"}`,children:[d.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${N.has(Y)?"bg-amber-500":Y===t?"bg-green-600":"bg-muted/50"}`}),d.jsx("span",{className:`truncate max-w-[120px] ${Y.startsWith("_new_")?"italic":""}`,children:Y.startsWith("_new_")?"Untitled":Y}),d.jsx("button",{onClick:he=>{he.stopPropagation(),Y.startsWith("_new_")?F(Y):G(Y)},className:"ml-0.5 text-muted hover:text-error text-[10px] leading-none",title:"Close terminal",children:"×"})]},Y)),t!=null&&t.startsWith("_new_")?d.jsx("button",{onClick:()=>F(t),className:"ml-auto px-2 py-0.5 text-xs text-error hover:bg-surface rounded flex items-center gap-1 flex-shrink-0",children:"Cancel ×"}):t&&o&&(c!=null&&c.has(t))?d.jsx("button",{onClick:()=>ie(t),className:"ml-auto px-2 py-0.5 text-xs text-muted hover:text-foreground hover:bg-surface rounded flex items-center gap-1 flex-shrink-0",children:"Archive"}):null]}),d.jsxs("div",{className:"relative flex-1 min-h-0",children:[d.jsx("div",{ref:S,className:"h-full"}),ae&&!W&&!K&&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"})]})}),W&&d.jsx("div",{"data-testid":"cartoon-launch-blocked",className:"absolute inset-0 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-md",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Cartoon agent can't launch yet"}),d.jsx("p",{className:"text-xs text-muted",children:"This is a cartoon story. The writing agent needs Codex with image generation enabled before it can start, because the clean-image step relies on image generation support."}),_&&!_.codex.installed?d.jsxs("p",{className:"text-xs text-amber-700",children:["Codex was not detected. Install the Codex CLI and sign in (e.g. ",d.jsx("span",{className:"font-mono",children:"npm i -g @openai/codex"})," then"," ",d.jsx("span",{className:"font-mono",children:"codex login"}),"), then reopen this story."]}):Eu(_)?d.jsxs("p",{className:"text-xs text-amber-700","data-testid":"codex-auth-unknown-launch",children:[Up," Then reopen this story."]}):d.jsxs("div",{className:"space-y-1",children:[d.jsx("p",{className:"text-xs text-amber-700",children:"Codex is installed but image generation isn't enabled. Enable it, then reopen this story:"}),d.jsxs("div",{className:"flex items-center gap-1",children:[d.jsx("code",{className:"flex-1 truncate rounded border border-border bg-surface px-1.5 py-1 text-left text-[10px] font-mono text-foreground",children:sv}),d.jsx("button",{type:"button","data-testid":"copy-codex-enable-launch",onClick:async()=>{try{await navigator.clipboard.writeText(sv),Se(!0),setTimeout(()=>Se(!1),2e3)}catch{}},className:"rounded border border-border px-2 py-1 text-[10px] text-muted hover:border-accent hover:text-accent transition-colors",children:fe?"Copied!":"Copy"})]})]})]})}),K&&!W&&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:H,onClick:async()=>{if(!H){ce(!0);try{await(v==null?void 0:v())}finally{ce(!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:H?"Setting…":"Set this story's provider to Codex"})]})}),te&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-10",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"text-center space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-sm",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Discard this session?"}),d.jsx("p",{className:"text-xs text-muted",children:"This session will be lost — your AI hasn't created a story structure yet."}),d.jsxs("div",{className:"flex items-center justify-center gap-2",children:[d.jsx("button",{onClick:()=>F(null),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Cancel"}),d.jsx("button",{onClick:()=>{const Y=te;F(null),C(Y)},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:()=>ie(null),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Cancel"}),d.jsx("button",{onClick:async()=>{const Y=D;ie(null);try{(await j.current("/api/stories/archive",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:Y})})).ok&&(G(Y),o==null||o(Y))}catch{}},className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim",children:"Archive"})]})]})}),ne&&t&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"text-center space-y-3",children:[d.jsx("p",{className:"text-sm font-serif text-foreground",children:"Terminal disconnected"}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{onClick:()=>M(t,!0),className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim",children:"Resume Session"}),d.jsx("button",{onClick:()=>M(t,!1),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Start Fresh"})]}),d.jsx("p",{className:"text-xs text-muted",children:"Resume continues your previous Claude conversation"})]})})]})]})}function QE(e,t){const i={};return(e[e.length-1]===""?[...e,""]:e).join((i.padRight?" ":"")+","+(i.padLeft===!1?"":" ")).trim()}const JE=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,eN=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,tN={};function lv(e,t){return(tN.jsx?eN:JE).test(e)}const iN=/[ \t\n\f\r]/g;function nN(e){return typeof e=="object"?e.type==="text"?ov(e.value):!1:ov(e)}function ov(e){return e.replace(iN,"")===""}class $o{constructor(t,i,s){this.normal=i,this.property=t,s&&(this.space=s)}}$o.prototype.normal={};$o.prototype.property={};$o.prototype.space=void 0;function S0(e,t){const i={},s={};for(const a of e)Object.assign(i,a.property),Object.assign(s,a.normal);return new $o(i,s,t)}function wp(e){return e.toLowerCase()}class kn{constructor(t,i){this.attribute=i,this.property=t}}kn.prototype.attribute="";kn.prototype.booleanish=!1;kn.prototype.boolean=!1;kn.prototype.commaOrSpaceSeparated=!1;kn.prototype.commaSeparated=!1;kn.prototype.defined=!1;kn.prototype.mustUseProperty=!1;kn.prototype.number=!1;kn.prototype.overloadedBoolean=!1;kn.prototype.property="";kn.prototype.spaceSeparated=!1;kn.prototype.space=void 0;let rN=0;const at=va(),yi=va(),Cp=va(),ve=va(),Yt=va(),hl=va(),Pn=va();function va(){return 2**++rN}const kp=Object.freeze(Object.defineProperty({__proto__:null,boolean:at,booleanish:yi,commaOrSpaceSeparated:Pn,commaSeparated:hl,number:ve,overloadedBoolean:Cp,spaceSeparated:Yt},Symbol.toStringTag,{value:"Module"})),mf=Object.keys(kp);class Jp extends kn{constructor(t,i,s,a){let o=-1;if(super(t,i),cv(this,"space",a),typeof s=="number")for(;++o4&&i.slice(0,4)==="data"&&cN.test(t)){if(t.charAt(4)==="-"){const o=t.slice(5).replace(uv,dN);s="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=t.slice(4);if(!uv.test(o)){let c=o.replace(oN,hN);c.charAt(0)!=="-"&&(c="-"+c),t="data"+c}}a=Jp}return new a(s,t)}function hN(e){return"-"+e.toLowerCase()}function dN(e){return e.charAt(1).toUpperCase()}const fN=S0([w0,sN,E0,N0,j0],"html"),em=S0([w0,aN,E0,N0,j0],"svg");function pN(e){return e.join(" ").trim()}var al={},gf,hv;function mN(){if(hv)return gf;hv=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,i=/^\s*/,s=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,a=/^:\s*/,o=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,c=/^[;\s]*/,h=/^\s+|\s+$/g,p=` +`,f="/",_="*",x="",b="comment",v="declaration";function S(R,E){if(typeof R!="string")throw new TypeError("First argument must be a string");if(!R)return[];E=E||{};var N=1,I=1;function te(X){var U=X.match(t);U&&(N+=U.length);var A=X.lastIndexOf(p);I=~A?X.length-A:I+X.length}function F(){var X={line:N,column:I};return function(U){return U.position=new D(X),Se(),U}}function D(X){this.start=X,this.end={line:N,column:I},this.source=E.source}D.prototype.content=R;function ie(X){var U=new Error(E.source+":"+N+":"+I+": "+X);if(U.reason=X,U.filename=E.source,U.line=N,U.column=I,U.source=R,!E.silent)throw U}function fe(X){var U=X.exec(R);if(U){var A=U[0];return te(A),R=R.slice(A.length),U}}function Se(){fe(i)}function H(X){var U;for(X=X||[];U=ce();)U!==!1&&X.push(U);return X}function ce(){var X=F();if(!(f!=R.charAt(0)||_!=R.charAt(1))){for(var U=2;x!=R.charAt(U)&&(_!=R.charAt(U)||f!=R.charAt(U+1));)++U;if(U+=2,x===R.charAt(U-1))return ie("End of comment missing");var A=R.slice(2,U-2);return I+=2,te(A),R=R.slice(U),I+=2,X({type:b,comment:A})}}function W(){var X=F(),U=fe(s);if(U){if(ce(),!fe(a))return ie("property missing ':'");var A=fe(o),O=X({type:v,property:j(U[0].replace(e,x)),value:A?j(A[0].replace(e,x)):x});return fe(c),O}}function K(){var X=[];H(X);for(var U;U=W();)U!==!1&&(X.push(U),H(X));return X}return Se(),K()}function j(R){return R?R.replace(h,x):x}return gf=S,gf}var dv;function gN(){if(dv)return al;dv=1;var e=al&&al.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(al,"__esModule",{value:!0}),al.default=i;const t=e(mN());function i(s,a){let o=null;if(!s||typeof s!="string")return o;const c=(0,t.default)(s),h=typeof a=="function";return c.forEach(p=>{if(p.type!=="declaration")return;const{property:f,value:_}=p;h?a(f,_,p):_&&(o=o||{},o[f]=_)}),o}return al}var go={},fv;function xN(){if(fv)return go;fv=1,Object.defineProperty(go,"__esModule",{value:!0}),go.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,i=/^[^-]+$/,s=/^-(webkit|moz|ms|o|khtml)-/,a=/^-(ms)-/,o=function(f){return!f||i.test(f)||e.test(f)},c=function(f,_){return _.toUpperCase()},h=function(f,_){return"".concat(_,"-")},p=function(f,_){return _===void 0&&(_={}),o(f)?f:(f=f.toLowerCase(),_.reactCompat?f=f.replace(a,h):f=f.replace(s,h),f.replace(t,c))};return go.camelCase=p,go}var xo,pv;function _N(){if(pv)return xo;pv=1;var e=xo&&xo.__importDefault||function(a){return a&&a.__esModule?a:{default:a}},t=e(gN()),i=xN();function s(a,o){var c={};return!a||typeof a!="string"||(0,t.default)(a,function(h,p){h&&p&&(c[(0,i.camelCase)(h,o)]=p)}),c}return s.default=s,xo=s,xo}var bN=_N();const vN=zu(bN),T0=A0("end"),tm=A0("start");function A0(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 R0(e){const t=tm(e),i=T0(e);if(t&&i)return{start:t,end:i}}function No(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?mv(e.position):"start"in e||"end"in e?mv(e):"line"in e||"column"in e?Ep(e):""}function Ep(e){return gv(e&&e.line)+":"+gv(e&&e.column)}function mv(e){return Ep(e&&e.start)+"-"+Ep(e&&e.end)}function gv(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=No(o.place)||"1:1",this.place=o.place||void 0,this.reason=this.message,this.ruleId=o.ruleId||void 0,this.source=o.source||void 0,this.stack=c&&o.cause&&typeof o.cause.stack=="string"?o.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}an.prototype.file="";an.prototype.name="";an.prototype.reason="";an.prototype.message="";an.prototype.stack="";an.prototype.column=void 0;an.prototype.line=void 0;an.prototype.ancestors=void 0;an.prototype.cause=void 0;an.prototype.fatal=void 0;an.prototype.place=void 0;an.prototype.ruleId=void 0;an.prototype.source=void 0;const im={}.hasOwnProperty,yN=new Map,SN=/[A-Z]/g,wN=new Set(["table","tbody","thead","tfoot","tr"]),CN=new Set(["td","th"]),D0="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function kN(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=MN(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=DN(i,t.jsx,t.jsxs)}const a={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:s,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:i,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?em:fN,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},o=M0(a,e,void 0);return o&&typeof o!="string"?o:a.create(e,a.Fragment,{children:o||void 0},void 0)}function M0(e,t,i){if(t.type==="element")return EN(e,t,i);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return NN(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return TN(e,t,i);if(t.type==="mdxjsEsm")return jN(e,t);if(t.type==="root")return AN(e,t,i);if(t.type==="text")return RN(e,t)}function EN(e,t,i){const s=e.schema;let a=s;t.tagName.toLowerCase()==="svg"&&s.space==="html"&&(a=em,e.schema=a),e.ancestors.push(t);const o=L0(e,t.tagName,!1),c=BN(e,t);let h=rm(e,t);return wN.has(t.tagName)&&(h=h.filter(function(p){return typeof p=="string"?!nN(p):!0})),B0(e,c,o,t),nm(c,h),e.ancestors.pop(),e.schema=s,e.create(t,o,c,i)}function NN(e,t){if(t.data&&t.data.estree&&e.evaluater){const s=t.data.estree.body[0];return s.type,e.evaluater.evaluateExpression(s.expression)}Bo(e,t.position)}function jN(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);Bo(e,t.position)}function TN(e,t,i){const s=e.schema;let a=s;t.name==="svg"&&s.space==="html"&&(a=em,e.schema=a),e.ancestors.push(t);const o=t.name===null?e.Fragment:L0(e,t.name,!0),c=LN(e,t),h=rm(e,t);return B0(e,c,o,t),nm(c,h),e.ancestors.pop(),e.schema=s,e.create(t,o,c,i)}function AN(e,t,i){const s={};return nm(s,rm(e,t)),e.create(t,e.Fragment,s,i)}function RN(e,t){return t.value}function B0(e,t,i,s){typeof i!="string"&&i!==e.Fragment&&e.passNode&&(t.node=s)}function nm(e,t){if(t.length>0){const i=t.length>1?t:t[0];i&&(e.children=i)}}function DN(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 MN(e,t){return i;function i(s,a,o,c){const h=Array.isArray(o.children),p=tm(s);return t(a,o,c,h,{columnNumber:p?p.column-1:void 0,fileName:e,lineNumber:p?p.line:void 0},void 0)}}function BN(e,t){const i={};let s,a;for(a in t.properties)if(a!=="children"&&im.call(t.properties,a)){const o=ON(e,a,t.properties[a]);if(o){const[c,h]=o;e.tableCellAlignToStyle&&c==="align"&&typeof h=="string"&&CN.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 LN(e,t){const i={};for(const s of t.attributes)if(s.type==="mdxJsxExpressionAttribute")if(s.data&&s.data.estree&&e.evaluater){const o=s.data.estree.body[0];o.type;const c=o.expression;c.type;const h=c.properties[0];h.type,Object.assign(i,e.evaluater.evaluateExpression(h.argument))}else Bo(e,t.position);else{const a=s.name;let o;if(s.value&&typeof s.value=="object")if(s.value.data&&s.value.data.estree&&e.evaluater){const h=s.value.data.estree.body[0];h.type,o=e.evaluater.evaluateExpression(h.expression)}else Bo(e,t.position);else o=s.value===null?!0:s.value;i[a]=o}return i}function rm(e,t){const i=[];let s=-1;const a=e.passKeys?new Map:yN;for(;++sa?0:a+t:t=t>a?a:t,i=i>0?i:0,s.length<1e4)c=Array.from(s),c.unshift(t,i),e.splice(...c);else for(i&&e.splice(t,i);o0?(Hn(e,e.length,0,t),e):t}const bv={}.hasOwnProperty;function z0(e){const t={};let i=-1;for(;++i13&&i<32||i>126&&i<160||i>55295&&i<57344||i>64975&&i<65008||(i&65535)===65535||(i&65535)===65534||i>1114111?"�":String.fromCodePoint(i)}function fr(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const fn=$s(/[A-Za-z]/),sn=$s(/[\dA-Za-z]/),WN=$s(/[#-'*+\--9=?A-Z^-~]/);function Mu(e){return e!==null&&(e<32||e===127)}const Np=$s(/\d/),GN=$s(/[\dA-Fa-f]/),YN=$s(/[!-/:-@[-`{-~]/);function Ye(e){return e!==null&&e<-2}function qt(e){return e!==null&&(e<0||e===32)}function gt(e){return e===-2||e===-1||e===32}const $u=$s(new RegExp("\\p{P}|\\p{S}","u")),_a=$s(/\s/);function $s(e){return t;function t(i){return i!==null&&i>-1&&e.test(String.fromCharCode(i))}}function vl(e){const t=[];let i=-1,s=0,a=0;for(;++i55295&&o<57344){const h=e.charCodeAt(i+1);o<56320&&h>56319&&h<57344?(c=String.fromCharCode(o,h),a=1):c="�"}else c=String.fromCharCode(o);c&&(t.push(e.slice(s,i),encodeURIComponent(c)),s=i+a+1,c=""),a&&(i+=a,a=0)}return t.join("")+e.slice(s)}function kt(e,t,i,s){const a=s?s-1:Number.POSITIVE_INFINITY;let o=0;return c;function c(p){return gt(p)?(e.enter(i),h(p)):t(p)}function h(p){return gt(p)&&o++c))return;const ie=t.events.length;let fe=ie,Se,H;for(;fe--;)if(t.events[fe][0]==="exit"&&t.events[fe][1].type==="chunkFlow"){if(Se){H=t.events[fe][1].end;break}Se=!0}for(E(s),D=ie;DI;){const F=i[te];t.containerState=F[1],F[0].exit.call(t,e)}i.length=I}function N(){a.write([null]),o=void 0,a=void 0,t.containerState._closeFlow=void 0}}function QN(e,t,i){return kt(e,e.attempt(this.parser.constructs.document,t,i),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function ml(e){if(e===null||qt(e)||_a(e))return 1;if($u(e))return 2}function Fu(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};yv(x,-p),yv(b,p),c={type:p>1?"strongSequence":"emphasisSequence",start:x,end:{...e[s][1].end}},h={type:p>1?"strongSequence":"emphasisSequence",start:{...e[i][1].start},end:b},o={type:p>1?"strongText":"emphasisText",start:{...e[s][1].end},end:{...e[i][1].start}},a={type:p>1?"strong":"emphasis",start:{...c.start},end:{...h.end}},e[s][1].end={...c.start},e[i][1].start={...h.end},f=[],e[s][1].end.offset-e[s][1].start.offset&&(f=rr(f,[["enter",e[s][1],t],["exit",e[s][1],t]])),f=rr(f,[["enter",a,t],["enter",c,t],["exit",c,t],["enter",o,t]]),f=rr(f,Fu(t.parser.constructs.insideSpan.null,e.slice(s+1,i),t)),f=rr(f,[["exit",o,t],["enter",h,t],["exit",h,t],["exit",a,t]]),e[i][1].end.offset-e[i][1].start.offset?(_=2,f=rr(f,[["enter",e[i][1],t],["exit",e[i][1],t]])):_=0,Hn(e,s-1,i-s+3,f),i=s+f.length-_-2;break}}for(i=-1;++i0&>(D)?kt(e,N,"linePrefix",o+1)(D):N(D)}function N(D){return D===null||Ye(D)?e.check(Sv,j,te)(D):(e.enter("codeFlowValue"),I(D))}function I(D){return D===null||Ye(D)?(e.exit("codeFlowValue"),N(D)):(e.consume(D),I)}function te(D){return e.exit("codeFenced"),t(D)}function F(D,ie,fe){let Se=0;return H;function H(U){return D.enter("lineEnding"),D.consume(U),D.exit("lineEnding"),ce}function ce(U){return D.enter("codeFencedFence"),gt(U)?kt(D,W,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(U):W(U)}function W(U){return U===h?(D.enter("codeFencedFenceSequence"),K(U)):fe(U)}function K(U){return U===h?(Se++,D.consume(U),K):Se>=c?(D.exit("codeFencedFenceSequence"),gt(U)?kt(D,X,"whitespace")(U):X(U)):fe(U)}function X(U){return U===null||Ye(U)?(D.exit("codeFencedFence"),ie(U)):fe(U)}}}function u5(e,t,i){const s=this;return a;function a(c){return c===null?i(c):(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),o)}function o(c){return s.parser.lazy[s.now().line]?i(c):t(c)}}const _f={name:"codeIndented",tokenize:d5},h5={partial:!0,tokenize:f5};function d5(e,t,i){const s=this;return a;function a(f){return e.enter("codeIndented"),kt(e,o,"linePrefix",5)(f)}function o(f){const _=s.events[s.events.length-1];return _&&_[1].type==="linePrefix"&&_[2].sliceSerialize(_[1],!0).length>=4?c(f):i(f)}function c(f){return f===null?p(f):Ye(f)?e.attempt(h5,c,p)(f):(e.enter("codeFlowValue"),h(f))}function h(f){return f===null||Ye(f)?(e.exit("codeFlowValue"),c(f)):(e.consume(f),h)}function p(f){return e.exit("codeIndented"),t(f)}}function f5(e,t,i){const s=this;return a;function a(c){return s.parser.lazy[s.now().line]?i(c):Ye(c)?(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),a):kt(e,o,"linePrefix",5)(c)}function o(c){const h=s.events[s.events.length-1];return h&&h[1].type==="linePrefix"&&h[2].sliceSerialize(h[1],!0).length>=4?t(c):Ye(c)?a(c):i(c)}}const p5={name:"codeText",previous:g5,resolve:m5,tokenize:x5};function m5(e){let t=e.length-4,i=3,s,a;if((e[i][1].type==="lineEnding"||e[i][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(s=i;++s=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return tthis.left.length?this.right.slice(this.right.length-s+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-s+this.left.length).reverse())}splice(t,i,s){const a=i||0;this.setCursor(Math.trunc(t));const o=this.right.splice(this.right.length-a,Number.POSITIVE_INFINITY);return s&&_o(this.left,s),o.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),_o(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),_o(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t=4?t(c):e.interrupt(s.parser.constructs.flow,i,t)(c)}}function F0(e,t,i,s,a,o,c,h,p){const f=p||Number.POSITIVE_INFINITY;let _=0;return x;function x(E){return E===60?(e.enter(s),e.enter(a),e.enter(o),e.consume(E),e.exit(o),b):E===null||E===32||E===41||Mu(E)?i(E):(e.enter(s),e.enter(c),e.enter(h),e.enter("chunkString",{contentType:"string"}),j(E))}function b(E){return E===62?(e.enter(o),e.consume(E),e.exit(o),e.exit(a),e.exit(s),t):(e.enter(h),e.enter("chunkString",{contentType:"string"}),v(E))}function v(E){return E===62?(e.exit("chunkString"),e.exit(h),b(E)):E===null||E===60||Ye(E)?i(E):(e.consume(E),E===92?S:v)}function S(E){return E===60||E===62||E===92?(e.consume(E),v):v(E)}function j(E){return!_&&(E===null||E===41||qt(E))?(e.exit("chunkString"),e.exit(h),e.exit(c),e.exit(s),t(E)):_999||v===null||v===91||v===93&&!p||v===94&&!h&&"_hiddenFootnoteSupport"in c.parser.constructs?i(v):v===93?(e.exit(o),e.enter(a),e.consume(v),e.exit(a),e.exit(s),t):Ye(v)?(e.enter("lineEnding"),e.consume(v),e.exit("lineEnding"),_):(e.enter("chunkString",{contentType:"string"}),x(v))}function x(v){return v===null||v===91||v===93||Ye(v)||h++>999?(e.exit("chunkString"),_(v)):(e.consume(v),p||(p=!gt(v)),v===92?b:x)}function b(v){return v===91||v===92||v===93?(e.consume(v),h++,x):x(v)}}function W0(e,t,i,s,a,o){let c;return h;function h(b){return b===34||b===39||b===40?(e.enter(s),e.enter(a),e.consume(b),e.exit(a),c=b===40?41:b,p):i(b)}function p(b){return b===c?(e.enter(a),e.consume(b),e.exit(a),e.exit(s),t):(e.enter(o),f(b))}function f(b){return b===c?(e.exit(o),p(c)):b===null?i(b):Ye(b)?(e.enter("lineEnding"),e.consume(b),e.exit("lineEnding"),kt(e,f,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),_(b))}function _(b){return b===c||b===null||Ye(b)?(e.exit("chunkString"),f(b)):(e.consume(b),b===92?x:_)}function x(b){return b===c||b===92?(e.consume(b),_):_(b)}}function jo(e,t){let i;return s;function s(a){return Ye(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),i=!0,s):gt(a)?kt(e,s,i?"linePrefix":"lineSuffix")(a):t(a)}}const k5={name:"definition",tokenize:N5},E5={partial:!0,tokenize:j5};function N5(e,t,i){const s=this;let a;return o;function o(v){return e.enter("definition"),c(v)}function c(v){return q0.call(s,e,h,i,"definitionLabel","definitionLabelMarker","definitionLabelString")(v)}function h(v){return a=fr(s.sliceSerialize(s.events[s.events.length-1][1]).slice(1,-1)),v===58?(e.enter("definitionMarker"),e.consume(v),e.exit("definitionMarker"),p):i(v)}function p(v){return qt(v)?jo(e,f)(v):f(v)}function f(v){return F0(e,_,i,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(v)}function _(v){return e.attempt(E5,x,x)(v)}function x(v){return gt(v)?kt(e,b,"whitespace")(v):b(v)}function b(v){return v===null||Ye(v)?(e.exit("definition"),s.parser.defined.push(a),t(v)):i(v)}}function j5(e,t,i){return s;function s(h){return qt(h)?jo(e,a)(h):i(h)}function a(h){return W0(e,o,i,"definitionTitle","definitionTitleMarker","definitionTitleString")(h)}function o(h){return gt(h)?kt(e,c,"whitespace")(h):c(h)}function c(h){return h===null||Ye(h)?t(h):i(h)}}const T5={name:"hardBreakEscape",tokenize:A5};function A5(e,t,i){return s;function s(o){return e.enter("hardBreakEscape"),e.consume(o),a}function a(o){return Ye(o)?(e.exit("hardBreakEscape"),t(o)):i(o)}}const R5={name:"headingAtx",resolve:D5,tokenize:M5};function D5(e,t){let i=e.length-2,s=3,a,o;return e[s][1].type==="whitespace"&&(s+=2),i-2>s&&e[i][1].type==="whitespace"&&(i-=2),e[i][1].type==="atxHeadingSequence"&&(s===i-1||i-4>s&&e[i-2][1].type==="whitespace")&&(i-=s+1===i?2:4),i>s&&(a={type:"atxHeadingText",start:e[s][1].start,end:e[i][1].end},o={type:"chunkText",start:e[s][1].start,end:e[i][1].end,contentType:"text"},Hn(e,s,i-s+1,[["enter",a,t],["enter",o,t],["exit",o,t],["exit",a,t]])),e}function M5(e,t,i){let s=0;return a;function a(_){return e.enter("atxHeading"),o(_)}function o(_){return e.enter("atxHeadingSequence"),c(_)}function c(_){return _===35&&s++<6?(e.consume(_),c):_===null||qt(_)?(e.exit("atxHeadingSequence"),h(_)):i(_)}function h(_){return _===35?(e.enter("atxHeadingSequence"),p(_)):_===null||Ye(_)?(e.exit("atxHeading"),t(_)):gt(_)?kt(e,h,"whitespace")(_):(e.enter("atxHeadingText"),f(_))}function p(_){return _===35?(e.consume(_),p):(e.exit("atxHeadingSequence"),h(_))}function f(_){return _===null||_===35||qt(_)?(e.exit("atxHeadingText"),h(_)):(e.consume(_),f)}}const B5=["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"],Cv=["pre","script","style","textarea"],L5={concrete:!0,name:"htmlFlow",resolveTo:P5,tokenize:I5},O5={partial:!0,tokenize:U5},z5={partial:!0,tokenize:H5};function P5(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 I5(e,t,i){const s=this;let a,o,c,h,p;return f;function f(C){return _(C)}function _(C){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(C),x}function x(C){return C===33?(e.consume(C),b):C===47?(e.consume(C),o=!0,j):C===63?(e.consume(C),a=3,s.interrupt?t:T):fn(C)?(e.consume(C),c=String.fromCharCode(C),R):i(C)}function b(C){return C===45?(e.consume(C),a=2,v):C===91?(e.consume(C),a=5,h=0,S):fn(C)?(e.consume(C),a=4,s.interrupt?t:T):i(C)}function v(C){return C===45?(e.consume(C),s.interrupt?t:T):i(C)}function S(C){const V="CDATA[";return C===V.charCodeAt(h++)?(e.consume(C),h===V.length?s.interrupt?t:W:S):i(C)}function j(C){return fn(C)?(e.consume(C),c=String.fromCharCode(C),R):i(C)}function R(C){if(C===null||C===47||C===62||qt(C)){const V=C===47,ne=c.toLowerCase();return!V&&!o&&Cv.includes(ne)?(a=1,s.interrupt?t(C):W(C)):B5.includes(c.toLowerCase())?(a=6,V?(e.consume(C),E):s.interrupt?t(C):W(C)):(a=7,s.interrupt&&!s.parser.lazy[s.now().line]?i(C):o?N(C):I(C))}return C===45||sn(C)?(e.consume(C),c+=String.fromCharCode(C),R):i(C)}function E(C){return C===62?(e.consume(C),s.interrupt?t:W):i(C)}function N(C){return gt(C)?(e.consume(C),N):H(C)}function I(C){return C===47?(e.consume(C),H):C===58||C===95||fn(C)?(e.consume(C),te):gt(C)?(e.consume(C),I):H(C)}function te(C){return C===45||C===46||C===58||C===95||sn(C)?(e.consume(C),te):F(C)}function F(C){return C===61?(e.consume(C),D):gt(C)?(e.consume(C),F):I(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,ie):gt(C)?(e.consume(C),D):fe(C)}function ie(C){return C===p?(e.consume(C),p=null,Se):C===null||Ye(C)?i(C):(e.consume(C),ie)}function fe(C){return C===null||C===34||C===39||C===47||C===60||C===61||C===62||C===96||qt(C)?F(C):(e.consume(C),fe)}function Se(C){return C===47||C===62||gt(C)?I(C):i(C)}function H(C){return C===62?(e.consume(C),ce):i(C)}function ce(C){return C===null||Ye(C)?W(C):gt(C)?(e.consume(C),ce):i(C)}function W(C){return C===45&&a===2?(e.consume(C),A):C===60&&a===1?(e.consume(C),O):C===62&&a===4?(e.consume(C),M):C===63&&a===3?(e.consume(C),T):C===93&&a===5?(e.consume(C),xe):Ye(C)&&(a===6||a===7)?(e.exit("htmlFlowData"),e.check(O5,G,K)(C)):C===null||Ye(C)?(e.exit("htmlFlowData"),K(C)):(e.consume(C),W)}function K(C){return e.check(z5,X,G)(C)}function X(C){return e.enter("lineEnding"),e.consume(C),e.exit("lineEnding"),U}function U(C){return C===null||Ye(C)?K(C):(e.enter("htmlFlowData"),W(C))}function A(C){return C===45?(e.consume(C),T):W(C)}function O(C){return C===47?(e.consume(C),c="",$):W(C)}function $(C){if(C===62){const V=c.toLowerCase();return Cv.includes(V)?(e.consume(C),M):W(C)}return fn(C)&&c.length<8?(e.consume(C),c+=String.fromCharCode(C),$):W(C)}function xe(C){return C===93?(e.consume(C),T):W(C)}function T(C){return C===62?(e.consume(C),M):C===45&&a===2?(e.consume(C),T):W(C)}function M(C){return C===null||Ye(C)?(e.exit("htmlFlowData"),G(C)):(e.consume(C),M)}function G(C){return e.exit("htmlFlow"),t(C)}}function H5(e,t,i){const s=this;return a;function a(c){return Ye(c)?(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),o):i(c)}function o(c){return s.parser.lazy[s.now().line]?i(c):t(c)}}function U5(e,t,i){return s;function s(a){return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),e.attempt(Fo,t,i)}}const $5={name:"htmlText",tokenize:F5};function F5(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),F):T===63?(e.consume(T),I):fn(T)?(e.consume(T),fe):i(T)}function f(T){return T===45?(e.consume(T),_):T===91?(e.consume(T),o=0,S):fn(T)?(e.consume(T),N):i(T)}function _(T){return T===45?(e.consume(T),v):i(T)}function x(T){return T===null?i(T):T===45?(e.consume(T),b):Ye(T)?(c=x,O(T)):(e.consume(T),x)}function b(T){return T===45?(e.consume(T),v):x(T)}function v(T){return T===62?A(T):T===45?b(T):x(T)}function S(T){const M="CDATA[";return T===M.charCodeAt(o++)?(e.consume(T),o===M.length?j:S):i(T)}function j(T){return T===null?i(T):T===93?(e.consume(T),R):Ye(T)?(c=j,O(T)):(e.consume(T),j)}function R(T){return T===93?(e.consume(T),E):j(T)}function E(T){return T===62?A(T):T===93?(e.consume(T),E):j(T)}function N(T){return T===null||T===62?A(T):Ye(T)?(c=N,O(T)):(e.consume(T),N)}function I(T){return T===null?i(T):T===63?(e.consume(T),te):Ye(T)?(c=I,O(T)):(e.consume(T),I)}function te(T){return T===62?A(T):I(T)}function F(T){return fn(T)?(e.consume(T),D):i(T)}function D(T){return T===45||sn(T)?(e.consume(T),D):ie(T)}function ie(T){return Ye(T)?(c=ie,O(T)):gt(T)?(e.consume(T),ie):A(T)}function fe(T){return T===45||sn(T)?(e.consume(T),fe):T===47||T===62||qt(T)?Se(T):i(T)}function Se(T){return T===47?(e.consume(T),A):T===58||T===95||fn(T)?(e.consume(T),H):Ye(T)?(c=Se,O(T)):gt(T)?(e.consume(T),Se):A(T)}function H(T){return T===45||T===46||T===58||T===95||sn(T)?(e.consume(T),H):ce(T)}function ce(T){return T===61?(e.consume(T),W):Ye(T)?(c=ce,O(T)):gt(T)?(e.consume(T),ce):Se(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,K):Ye(T)?(c=W,O(T)):gt(T)?(e.consume(T),W):(e.consume(T),X)}function K(T){return T===a?(e.consume(T),a=void 0,U):T===null?i(T):Ye(T)?(c=K,O(T)):(e.consume(T),K)}function X(T){return T===null||T===34||T===39||T===60||T===61||T===96?i(T):T===47||T===62||qt(T)?Se(T):(e.consume(T),X)}function U(T){return T===47||T===62||qt(T)?Se(T):i(T)}function A(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"),$}function $(T){return gt(T)?kt(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 lm={name:"labelEnd",resolveAll:Y5,resolveTo:K5,tokenize:V5},q5={tokenize:X5},W5={tokenize:Z5},G5={tokenize:Q5};function Y5(e){let t=-1;const i=[];for(;++t=3&&(f===null||Ye(f))?(e.exit("thematicBreak"),t(f)):i(f)}function p(f){return f===a?(e.consume(f),s++,p):(e.exit("thematicBreakSequence"),gt(f)?kt(e,h,"whitespace")(f):h(f))}}const Cn={continuation:{tokenize:oj},exit:uj,name:"list",tokenize:lj},sj={partial:!0,tokenize:hj},aj={partial:!0,tokenize:cj};function lj(e,t,i){const s=this,a=s.events[s.events.length-1];let o=a&&a[1].type==="linePrefix"?a[2].sliceSerialize(a[1],!0).length:0,c=0;return h;function h(v){const S=s.containerState.type||(v===42||v===43||v===45?"listUnordered":"listOrdered");if(S==="listUnordered"?!s.containerState.marker||v===s.containerState.marker:Np(v)){if(s.containerState.type||(s.containerState.type=S,e.enter(S,{_container:!0})),S==="listUnordered")return e.enter("listItemPrefix"),v===42||v===45?e.check(wu,i,f)(v):f(v);if(!s.interrupt||v===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),p(v)}return i(v)}function p(v){return Np(v)&&++c<10?(e.consume(v),p):(!s.interrupt||c<2)&&(s.containerState.marker?v===s.containerState.marker:v===41||v===46)?(e.exit("listItemValue"),f(v)):i(v)}function f(v){return e.enter("listItemMarker"),e.consume(v),e.exit("listItemMarker"),s.containerState.marker=s.containerState.marker||v,e.check(Fo,s.interrupt?i:_,e.attempt(sj,b,x))}function _(v){return s.containerState.initialBlankLine=!0,o++,b(v)}function x(v){return gt(v)?(e.enter("listItemPrefixWhitespace"),e.consume(v),e.exit("listItemPrefixWhitespace"),b):i(v)}function b(v){return s.containerState.size=o+s.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(v)}}function oj(e,t,i){const s=this;return s.containerState._closeFlow=void 0,e.check(Fo,a,o);function a(h){return s.containerState.furtherBlankLines=s.containerState.furtherBlankLines||s.containerState.initialBlankLine,kt(e,t,"listItemIndent",s.containerState.size+1)(h)}function o(h){return s.containerState.furtherBlankLines||!gt(h)?(s.containerState.furtherBlankLines=void 0,s.containerState.initialBlankLine=void 0,c(h)):(s.containerState.furtherBlankLines=void 0,s.containerState.initialBlankLine=void 0,e.attempt(aj,t,c)(h))}function c(h){return s.containerState._closeFlow=!0,s.interrupt=void 0,kt(e,e.attempt(Cn,t,i),"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(h)}}function cj(e,t,i){const s=this;return kt(e,a,"listItemIndent",s.containerState.size+1);function a(o){const c=s.events[s.events.length-1];return c&&c[1].type==="listItemIndent"&&c[2].sliceSerialize(c[1],!0).length===s.containerState.size?t(o):i(o)}}function uj(e){e.exit(this.containerState.type)}function hj(e,t,i){const s=this;return kt(e,a,"listItemPrefixWhitespace",s.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function a(o){const c=s.events[s.events.length-1];return!gt(o)&&c&&c[1].type==="listItemPrefixWhitespace"?t(o):i(o)}}const kv={name:"setextUnderline",resolveTo:dj,tokenize:fj};function dj(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 fj(e,t,i){const s=this;let a;return o;function o(f){let _=s.events.length,x;for(;_--;)if(s.events[_][1].type!=="lineEnding"&&s.events[_][1].type!=="linePrefix"&&s.events[_][1].type!=="content"){x=s.events[_][1].type==="paragraph";break}return!s.parser.lazy[s.now().line]&&(s.interrupt||x)?(e.enter("setextHeadingLine"),a=f,c(f)):i(f)}function c(f){return e.enter("setextHeadingLineSequence"),h(f)}function h(f){return f===a?(e.consume(f),h):(e.exit("setextHeadingLineSequence"),gt(f)?kt(e,p,"lineSuffix")(f):p(f))}function p(f){return f===null||Ye(f)?(e.exit("setextHeadingLine"),t(f)):i(f)}}const pj={tokenize:mj};function mj(e){const t=this,i=e.attempt(Fo,s,e.attempt(this.parser.constructs.flowInitial,a,kt(e,e.attempt(this.parser.constructs.flow,a,e.attempt(v5,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 gj={resolveAll:Y0()},xj=G0("string"),_j=G0("text");function G0(e){return{resolveAll:Y0(e==="text"?bj: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 Dj(e,t){let i=-1;const s=[];let a;for(;++i0){const Wt=Te.tokenStack[Te.tokenStack.length-1];(Wt[1]||Nv).call(Te,void 0,Wt[0])}for(ge.position={start:Os(Q.length>0?Q[0][1].start:{line:1,column:1,offset:0}),end:Os(Q.length>0?Q[Q.length-2][1].end:{line:1,column:1,offset:0})},it=-1;++it0&&(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 Gj(e,t){const i={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function Yj(e,t){const i={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function Kj(e,t){const i=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=String(t.identifier).toUpperCase(),a=vl(s.toLowerCase()),o=e.footnoteOrder.indexOf(s);let c,h=e.footnoteCounts.get(s);h===void 0?(h=0,e.footnoteOrder.push(s),c=e.footnoteOrder.length):c=o+1,h+=1,e.footnoteCounts.set(s,h);const p={type:"element",tagName:"a",properties:{href:"#"+i+"fn-"+a,id:i+"fnref-"+a+(h>1?"-"+h:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(c)}]};e.patch(t,p);const f={type:"element",tagName:"sup",properties:{},children:[p]};return e.patch(t,f),e.applyData(t,f)}function Vj(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 Xj(e,t){if(e.options.allowDangerousHtml){const i={type:"raw",value:t.value};return e.patch(t,i),e.applyData(t,i)}}function X0(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 Zj(e,t){const i=String(t.identifier).toUpperCase(),s=e.definitionById.get(i);if(!s)return X0(e,t);const a={src:vl(s.url||""),alt:t.alt};s.title!==null&&s.title!==void 0&&(a.title=s.title);const o={type:"element",tagName:"img",properties:a,children:[]};return e.patch(t,o),e.applyData(t,o)}function Qj(e,t){const i={src:vl(t.url)};t.alt!==null&&t.alt!==void 0&&(i.alt=t.alt),t.title!==null&&t.title!==void 0&&(i.title=t.title);const s={type:"element",tagName:"img",properties:i,children:[]};return e.patch(t,s),e.applyData(t,s)}function Jj(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 eT(e,t){const i=String(t.identifier).toUpperCase(),s=e.definitionById.get(i);if(!s)return X0(e,t);const a={href:vl(s.url||"")};s.title!==null&&s.title!==void 0&&(a.title=s.title);const o={type:"element",tagName:"a",properties:a,children:e.all(t)};return e.patch(t,o),e.applyData(t,o)}function tT(e,t){const i={href:vl(t.url)};t.title!==null&&t.title!==void 0&&(i.title=t.title);const s={type:"element",tagName:"a",properties:i,children:e.all(t)};return e.patch(t,s),e.applyData(t,s)}function iT(e,t,i){const s=e.all(t),a=i?nT(i):Z0(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 rT(e,t){const i={},s=e.all(t);let a=-1;for(typeof t.start=="number"&&t.start!==1&&(i.start=t.start);++a0){const c={type:"element",tagName:"tbody",properties:{},children:e.wrap(i,!0)},h=tm(t.children[1]),p=T0(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 cT(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(Av(t.slice(a),a>0,!1)),o.join("")}function Av(e,t,i){let s=0,a=e.length;if(t){let o=e.codePointAt(s);for(;o===jv||o===Tv;)s++,o=e.codePointAt(s)}if(i){let o=e.codePointAt(a-1);for(;o===jv||o===Tv;)a--,o=e.codePointAt(a-1)}return a>s?e.slice(s,a):""}function dT(e,t){const i={type:"text",value:hT(String(t.value))};return e.patch(t,i),e.applyData(t,i)}function fT(e,t){const i={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,i),e.applyData(t,i)}const pT={blockquote:Fj,break:qj,code:Wj,delete:Gj,emphasis:Yj,footnoteReference:Kj,heading:Vj,html:Xj,imageReference:Zj,image:Qj,inlineCode:Jj,linkReference:eT,link:tT,listItem:iT,list:rT,paragraph:sT,root:aT,strong:lT,table:oT,tableCell:uT,tableRow:cT,text:dT,thematicBreak:fT,toml:au,yaml:au,definition:au,footnoteDefinition:au};function au(){}const Q0=-1,qu=0,To=1,Bu=2,om=3,cm=4,um=5,hm=6,J0=7,eS=8,Rv=typeof self=="object"?self:globalThis,mT=(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 qu:case Q0:return i(c,a);case To:{const h=i([],a);for(const p of c)h.push(s(p));return h}case Bu:{const h=i({},a);for(const[p,f]of c)h[s(p)]=s(f);return h}case om:return i(new Date(c),a);case cm:{const{source:h,flags:p}=c;return i(new RegExp(h,p),a)}case um:{const h=i(new Map,a);for(const[p,f]of c)h.set(s(p),s(f));return h}case hm:{const h=i(new Set,a);for(const p of c)h.add(s(p));return h}case J0:{const{name:h,message:p}=c;return i(new Rv[h](p),a)}case eS: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 Rv[o](c),a)};return s},Dv=e=>mT(new Map,e)(0),ll="",{toString:gT}={},{keys:xT}=Object,bo=e=>{const t=typeof e;if(t!=="object"||!e)return[qu,t];const i=gT.call(e).slice(8,-1);switch(i){case"Array":return[To,ll];case"Object":return[Bu,ll];case"Date":return[om,ll];case"RegExp":return[cm,ll];case"Map":return[um,ll];case"Set":return[hm,ll];case"DataView":return[To,i]}return i.includes("Array")?[To,i]:i.includes("Error")?[J0,i]:[Bu,i]},lu=([e,t])=>e===qu&&(t==="function"||t==="symbol"),_T=(e,t,i,s)=>{const a=(c,h)=>{const p=s.push(c)-1;return i.set(h,p),p},o=c=>{if(i.has(c))return i.get(c);let[h,p]=bo(c);switch(h){case qu:{let _=c;switch(p){case"bigint":h=eS,_=c.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+p);_=null;break;case"undefined":return a([Q0],c)}return a([h,_],c)}case To:{if(p){let b=c;return p==="DataView"?b=new Uint8Array(c.buffer):p==="ArrayBuffer"&&(b=new Uint8Array(c)),a([p,[...b]],c)}const _=[],x=a([h,_],c);for(const b of c)_.push(o(b));return x}case Bu:{if(p)switch(p){case"BigInt":return a([p,c.toString()],c);case"Boolean":case"Number":case"String":return a([p,c.valueOf()],c)}if(t&&"toJSON"in c)return o(c.toJSON());const _=[],x=a([h,_],c);for(const b of xT(c))(e||!lu(bo(c[b])))&&_.push([o(b),o(c[b])]);return x}case om:return a([h,c.toISOString()],c);case cm:{const{source:_,flags:x}=c;return a([h,{source:_,flags:x}],c)}case um:{const _=[],x=a([h,_],c);for(const[b,v]of c)(e||!(lu(bo(b))||lu(bo(v))))&&_.push([o(b),o(v)]);return x}case hm:{const _=[],x=a([h,_],c);for(const b of c)(e||!lu(bo(b)))&&_.push(o(b));return x}}const{message:f}=c;return a([h,{name:p,message:f}],c)};return o},Mv=(e,{json:t,lossy:i}={})=>{const s=[];return _T(!(t||i),!!t,new Map,s)(e),s},Lo=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?Dv(Mv(e,t)):structuredClone(e):(e,t)=>Dv(Mv(e,t));function bT(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 vT(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function yT(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",i=e.options.footnoteBackContent||bT,s=e.options.footnoteBackLabel||vT,a=e.options.footnoteLabel||"Footnotes",o=e.options.footnoteLabelTagName||"h2",c=e.options.footnoteLabelProperties||{className:["sr-only"]},h=[];let p=-1;for(;++p0&&S.push({type:"text",value:" "});let N=typeof i=="string"?i:i(p,v);typeof N=="string"&&(N={type:"text",value:N}),S.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+b+(v>1?"-"+v:""),dataFootnoteBackref:"",ariaLabel:typeof s=="string"?s:s(p,v),className:["data-footnote-backref"]},children:Array.isArray(N)?N:[N]})}const R=_[_.length-1];if(R&&R.type==="element"&&R.tagName==="p"){const N=R.children[R.children.length-1];N&&N.type==="text"?N.value+=" ":R.children.push({type:"text",value:" "}),R.children.push(...S)}else _.push(...S);const E={type:"element",tagName:"li",properties:{id:t+"fn-"+b},children:e.wrap(_,!0)};e.patch(f,E),h.push(E)}if(h.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...Lo(c),id:"footnote-label"},children:[{type:"text",value:a}]},{type:"text",value:` +`},{type:"element",tagName:"ol",properties:{},children:e.wrap(h,!0)},{type:"text",value:` +`}]}}const Wu=(function(e){if(e==null)return kT;if(typeof e=="function")return Gu(e);if(typeof e=="object")return Array.isArray(e)?ST(e):wT(e);if(typeof e=="string")return CT(e);throw new Error("Expected function, string, or object as test")});function ST(e){const t=[];let i=-1;for(;++i":""))+")"})}return b;function b(){let v=tS,S,j,R;if((!t||o(p,f,_[_.length-1]||void 0))&&(v=TT(i(p,_)),v[0]===Tp))return v;if("children"in p&&p.children){const E=p;if(E.children&&v[0]!==jT)for(j=(s?E.children.length:-1)+c,R=_.concat(E);j>-1&&j0&&i.push({type:"text",value:` +`}),i}function Bv(e){let t=0,i=e.charCodeAt(t);for(;i===9||i===32;)t++,i=e.charCodeAt(t);return e.slice(t)}function Lv(e,t){const i=RT(e,t),s=i.one(e,void 0),a=yT(i),o=Array.isArray(s)?{type:"root",children:s}:s||{type:"root",children:[]};return a&&o.children.push({type:"text",value:` +`},a),o}function OT(e,t){return e&&"run"in e?async function(i,s){const a=Lv(i,{file:s,...t});await e.run(a,s)}:function(i,s){return Lv(i,{file:s,...e||t})}}function Ov(e){if(e)throw e}var vf,zv;function zT(){if(zv)return vf;zv=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,i=Object.defineProperty,s=Object.getOwnPropertyDescriptor,a=function(f){return typeof Array.isArray=="function"?Array.isArray(f):t.call(f)==="[object Array]"},o=function(f){if(!f||t.call(f)!=="[object Object]")return!1;var _=e.call(f,"constructor"),x=f.constructor&&f.constructor.prototype&&e.call(f.constructor.prototype,"isPrototypeOf");if(f.constructor&&!_&&!x)return!1;var b;for(b in f);return typeof b>"u"||e.call(f,b)},c=function(f,_){i&&_.name==="__proto__"?i(f,_.name,{enumerable:!0,configurable:!0,value:_.newValue,writable:!0}):f[_.name]=_.newValue},h=function(f,_){if(_==="__proto__")if(e.call(f,_)){if(s)return s(f,_).value}else return;return f[_]};return vf=function p(){var f,_,x,b,v,S,j=arguments[0],R=1,E=arguments.length,N=!1;for(typeof j=="boolean"&&(N=j,j=arguments[1]||{},R=2),(j==null||typeof j!="object"&&typeof j!="function")&&(j={});Rc.length;let p;h&&c.push(a);try{p=e.apply(this,c)}catch(f){const _=f;if(h&&i)throw _;return a(_)}h||(p&&p.then&&typeof p.then=="function"?p.then(o,a):p instanceof Error?a(p):o(p))}function a(c,...h){i||(i=!0,t(c,...h))}function o(c){a(null,c)}}const jr={basename:UT,dirname:$T,extname:FT,join:qT,sep:"/"};function UT(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');qo(e);let i=0,s=-1,a=e.length,o;if(t===void 0||t.length===0||t.length>e.length){for(;a--;)if(e.codePointAt(a)===47){if(o){i=a+1;break}}else s<0&&(o=!0,s=a+1);return s<0?"":e.slice(i,s)}if(t===e)return"";let c=-1,h=t.length-1;for(;a--;)if(e.codePointAt(a)===47){if(o){i=a+1;break}}else c<0&&(o=!0,c=a+1),h>-1&&(e.codePointAt(a)===t.codePointAt(h--)?h<0&&(s=a):(h=-1,s=c));return i===s?s=c:s<0&&(s=e.length),e.slice(i,s)}function $T(e){if(qo(e),e.length===0)return".";let t=-1,i=e.length,s;for(;--i;)if(e.codePointAt(i)===47){if(s){t=i;break}}else s||(s=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function FT(e){qo(e);let t=e.length,i=-1,s=0,a=-1,o=0,c;for(;t--;){const h=e.codePointAt(t);if(h===47){if(c){s=t+1;break}continue}i<0&&(c=!0,i=t+1),h===46?a<0?a=t:o!==1&&(o=1):a>-1&&(o=-1)}return a<0||i<0||o===0||o===1&&a===i-1&&a===s+1?"":e.slice(a,i)}function qT(...e){let t=-1,i;for(;++t0&&e.codePointAt(e.length-1)===47&&(i+="/"),t?"/"+i:i}function GT(e,t){let i="",s=0,a=-1,o=0,c=-1,h,p;for(;++c<=e.length;){if(c2){if(p=i.lastIndexOf("/"),p!==i.length-1){p<0?(i="",s=0):(i=i.slice(0,p),s=i.length-1-i.lastIndexOf("/")),a=c,o=0;continue}}else if(i.length>0){i="",s=0,a=c,o=0;continue}}t&&(i=i.length>0?i+"/..":"..",s=2)}else i.length>0?i+="/"+e.slice(a+1,c):i=e.slice(a+1,c),s=c-a-1;a=c,o=0}else h===46&&o>-1?o++:o=-1}return i}function qo(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const YT={cwd:KT};function KT(){return"/"}function Dp(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function VT(e){if(typeof e=="string")e=new URL(e);else if(!Dp(e)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(e.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return XT(e)}function XT(e){if(e.hostname!==""){const s=new TypeError('File URL host must be "localhost" or empty on darwin');throw s.code="ERR_INVALID_FILE_URL_HOST",s}const t=e.pathname;let i=-1;for(;++i0){let[v,...S]=_;const j=s[b][1];Rp(j)&&Rp(v)&&(v=yf(!0,j,v)),s[b]=[f,v,...S]}}}}const eA=new fm().freeze();function kf(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Ef(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Nf(e,t){if(t)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function Iv(e){if(!Rp(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Hv(e,t,i){if(!i)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function ou(e){return tA(e)?e:new nS(e)}function tA(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function iA(e){return typeof e=="string"||nA(e)}function nA(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const rA="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Uv=[],$v={allowDangerousHtml:!0},sA=/^(https?|ircs?|mailto|xmpp)$/i,aA=[{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 rS(e){const t=lA(e),i=oA(e);return cA(t.runSync(t.parse(i),i),e)}function lA(e){const t=e.rehypePlugins||Uv,i=e.remarkPlugins||Uv,s=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...$v}:$v;return eA().use($j).use(i).use(OT,s).use(t)}function oA(e){const t=e.children||"",i=new nS;return typeof t=="string"&&(i.value=t),i}function cA(e,t){const i=t.allowedElements,s=t.allowElement,a=t.components,o=t.disallowedElements,c=t.skipHtml,h=t.unwrapDisallowed,p=t.urlTransform||uA;for(const _ of aA)Object.hasOwn(t,_.from)&&(""+_.from+(_.to?"use `"+_.to+"` instead":"remove it")+rA+_.id,void 0);return dm(e,f),kN(e,{Fragment:d.Fragment,components:a,ignoreInvalidStyle:!0,jsx:d.jsx,jsxs:d.jsxs,passKeys:!0,passNode:!0});function f(_,x,b){if(_.type==="raw"&&b&&typeof x=="number")return c?b.children.splice(x,1):b.children[x]={type:"text",value:_.value},x;if(_.type==="element"){let v;for(v in xf)if(Object.hasOwn(xf,v)&&Object.hasOwn(_.properties,v)){const S=_.properties[v],j=xf[v];(j===null||j.includes(_.tagName))&&(_.properties[v]=p(String(S||""),v,_))}}if(_.type==="element"){let v=i?!i.includes(_.tagName):o?o.includes(_.tagName):!1;if(!v&&s&&typeof x=="number"&&(v=!s(_,x,b)),v&&b&&typeof x=="number")return h&&_.children?b.children.splice(x,1,..._.children):b.children.splice(x,1),x}}}function uA(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||sA.test(e.slice(0,t))?e:""}function hA(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function sS(e,t,i){const a=Wu((i||{}).ignore||[]),o=dA(t);let c=-1;for(;++c0?{type:"text",value:D}:void 0),D===!1?b.lastIndex=te+1:(S!==te&&N.push({type:"text",value:f.value.slice(S,te)}),Array.isArray(D)?N.push(...D):D&&N.push(D),S=te+I[0].length,E=!0),!b.global)break;I=b.exec(f.value)}return E?(S?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let i=t[0],s=i.indexOf(")");const a=Fv(e,"(");let o=Fv(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 lS(e,t){const i=e.input.charCodeAt(e.index-1);return(e.index===0||_a(i)||$u(i))&&(!t||i!==47)}oS.peek=zA;function TA(){this.buffer()}function AA(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function RA(){this.buffer()}function DA(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function MA(e){const t=this.resume(),i=this.stack[this.stack.length-1];i.type,i.identifier=fr(this.sliceSerialize(e)).toLowerCase(),i.label=t}function BA(e){this.exit(e)}function LA(e){const t=this.resume(),i=this.stack[this.stack.length-1];i.type,i.identifier=fr(this.sliceSerialize(e)).toLowerCase(),i.label=t}function OA(e){this.exit(e)}function zA(){return"["}function oS(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 PA(){return{enter:{gfmFootnoteCallString:TA,gfmFootnoteCall:AA,gfmFootnoteDefinitionLabelString:RA,gfmFootnoteDefinition:DA},exit:{gfmFootnoteCallString:MA,gfmFootnoteCall:BA,gfmFootnoteDefinitionLabelString:LA,gfmFootnoteDefinition:OA}}}function IA(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:i,footnoteReference:oS},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?cS:HA))),f(),p}}function HA(e,t,i){return t===0?e:cS(e,t,i)}function cS(e,t,i){return(i?"":" ")+e}const UA=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];uS.peek=GA;function $A(){return{canContainEols:["delete"],enter:{strikethrough:qA},exit:{strikethrough:WA}}}function FA(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:UA}],handlers:{delete:uS}}}function qA(e){this.enter({type:"delete",children:[]},e)}function WA(e){this.exit(e)}function uS(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 GA(){return"~"}function YA(e){return e.length}function KA(e,t){const i=t||{},s=(i.align||[]).concat(),a=i.stringLength||YA,o=[],c=[],h=[],p=[];let f=0,_=-1;for(;++_f&&(f=e[_].length);++Ep[E])&&(p[E]=I)}j.push(N)}c[_]=j,h[_]=R}let x=-1;if(typeof s=="object"&&"length"in s)for(;++xp[x]&&(p[x]=N),v[x]=N),b[x]=I}c.splice(1,0,b),h.splice(1,0,v),_=-1;const S=[];for(;++_ "),o.shift(2);const c=i.indentLines(i.containerFlow(e,o.current()),ZA);return a(),c}function ZA(e,t,i){return">"+(i?"":" ")+e}function QA(e,t){return Wv(e,t.inConstruct,!0)&&!Wv(e,t.notInConstruct,!1)}function Wv(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 eR(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 tR(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 iR(e,t,i,s){const a=tR(i),o=e.value||"",c=a==="`"?"GraveAccent":"Tilde";if(eR(e,i)){const x=i.enter("codeIndented"),b=i.indentLines(o,nR);return x(),b}const h=i.createTracker(s),p=a.repeat(Math.max(JA(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 nR(e,t,i){return(i?"":" ")+e}function pm(e){const t=e.options.quote||'"';if(t!=='"'&&t!=="'")throw new Error("Cannot serialize title with `"+t+"` for `options.quote`, expected `\"`, or `'`");return t}function rR(e,t,i,s){const a=pm(i),o=a==='"'?"Quote":"Apostrophe",c=i.enter("definition");let h=i.enter("label");const p=i.createTracker(s);let f=p.move("[");return f+=p.move(i.safe(i.associationId(e),{before:f,after:"]",...p.current()})),f+=p.move("]: "),h(),!e.url||/[\0- \u007F]/.test(e.url)?(h=i.enter("destinationLiteral"),f+=p.move("<"),f+=p.move(i.safe(e.url,{before:f,after:">",...p.current()})),f+=p.move(">")):(h=i.enter("destinationRaw"),f+=p.move(i.safe(e.url,{before:f,after:e.title?" ":` +`,...p.current()}))),h(),e.title&&(h=i.enter(`title${o}`),f+=p.move(" "+a),f+=p.move(i.safe(e.title,{before:f,after:a,...p.current()})),f+=p.move(a),h()),c(),f}function sR(e){const t=e.options.emphasis||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize emphasis with `"+t+"` for `options.emphasis`, expected `*`, or `_`");return t}function Oo(e){return"&#x"+e.toString(16).toUpperCase()+";"}function Lu(e,t,i){const s=ml(e),a=ml(t);return s===void 0?a===void 0?i==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:a===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:s===1?a===void 0?{inside:!1,outside:!1}:a===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:a===void 0?{inside:!1,outside:!1}:a===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}hS.peek=aR;function hS(e,t,i,s){const a=sR(i),o=i.enter("emphasis"),c=i.createTracker(s),h=c.move(a);let p=c.move(i.containerPhrasing(e,{after:a,before:h,...c.current()}));const f=p.charCodeAt(0),_=Lu(s.before.charCodeAt(s.before.length-1),f,a);_.inside&&(p=Oo(f)+p.slice(1));const x=p.charCodeAt(p.length-1),b=Lu(s.after.charCodeAt(0),x,a);b.inside&&(p=p.slice(0,-1)+Oo(x));const v=c.move(a);return o(),i.attentionEncodeSurroundingInfo={after:b.outside,before:_.outside},h+p+v}function aR(e,t,i){return i.options.emphasis||"*"}function lR(e,t){let i=!1;return dm(e,function(s){if("value"in s&&/\r?\n|\r/.test(s.value)||s.type==="break")return i=!0,Tp}),!!((!e.depth||e.depth<3)&&sm(e)&&(t.options.setext||i))}function oR(e,t,i,s){const a=Math.max(Math.min(6,e.depth||1),1),o=i.createTracker(s);if(lR(e,i)){const _=i.enter("headingSetext"),x=i.enter("phrasing"),b=i.containerPhrasing(e,{...o.current(),before:` +`,after:` +`});return x(),_(),b+` +`+(a===1?"=":"-").repeat(b.length-(Math.max(b.lastIndexOf("\r"),b.lastIndexOf(` +`))+1))}const c="#".repeat(a),h=i.enter("headingAtx"),p=i.enter("phrasing");o.move(c+" ");let f=i.containerPhrasing(e,{before:"# ",after:` +`,...o.current()});return/^[\t ]/.test(f)&&(f=Oo(f.charCodeAt(0))+f.slice(1)),f=f?c+" "+f:c,i.options.closeAtx&&(f+=" "+c),p(),h(),f}dS.peek=cR;function dS(e){return e.value||""}function cR(){return"<"}fS.peek=uR;function fS(e,t,i,s){const a=pm(i),o=a==='"'?"Quote":"Apostrophe",c=i.enter("image");let h=i.enter("label");const p=i.createTracker(s);let f=p.move("![");return f+=p.move(i.safe(e.alt,{before:f,after:"]",...p.current()})),f+=p.move("]("),h(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(h=i.enter("destinationLiteral"),f+=p.move("<"),f+=p.move(i.safe(e.url,{before:f,after:">",...p.current()})),f+=p.move(">")):(h=i.enter("destinationRaw"),f+=p.move(i.safe(e.url,{before:f,after:e.title?" ":")",...p.current()}))),h(),e.title&&(h=i.enter(`title${o}`),f+=p.move(" "+a),f+=p.move(i.safe(e.title,{before:f,after:a,...p.current()})),f+=p.move(a),h()),f+=p.move(")"),c(),f}function uR(){return"!"}pS.peek=hR;function pS(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 hR(){return"!"}mS.peek=dR;function mS(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))}xS.peek=fR;function xS(e,t,i,s){const a=pm(i),o=a==='"'?"Quote":"Apostrophe",c=i.createTracker(s);let h,p;if(gS(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 fR(e,t,i){return gS(e,i)?"<":"["}_S.peek=pR;function _S(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 pR(){return"["}function mm(e){const t=e.options.bullet||"*";if(t!=="*"&&t!=="+"&&t!=="-")throw new Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function mR(e){const t=mm(e),i=e.options.bulletOther;if(!i)return t==="*"?"-":"*";if(i!=="*"&&i!=="+"&&i!=="-")throw new Error("Cannot serialize items with `"+i+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(i===t)throw new Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+i+"`) to be different");return i}function gR(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 bS(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 xR(e,t,i,s){const a=i.enter("list"),o=i.bulletCurrent;let c=e.ordered?gR(i):mm(i);const h=e.ordered?c==="."?")":".":mR(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),bS(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 vR(e,t,i,s){const a=i.enter("paragraph"),o=i.enter("phrasing"),c=i.containerPhrasing(e,s);return o(),a(),c}const yR=Wu(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function SR(e,t,i,s){return(e.children.some(function(c){return yR(c)})?i.containerPhrasing:i.containerFlow).call(i,e,s)}function wR(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}vS.peek=CR;function vS(e,t,i,s){const a=wR(i),o=i.enter("strong"),c=i.createTracker(s),h=c.move(a+a);let p=c.move(i.containerPhrasing(e,{after:a,before:h,...c.current()}));const f=p.charCodeAt(0),_=Lu(s.before.charCodeAt(s.before.length-1),f,a);_.inside&&(p=Oo(f)+p.slice(1));const x=p.charCodeAt(p.length-1),b=Lu(s.after.charCodeAt(0),x,a);b.inside&&(p=p.slice(0,-1)+Oo(x));const v=c.move(a+a);return o(),i.attentionEncodeSurroundingInfo={after:b.outside,before:_.outside},h+p+v}function CR(e,t,i){return i.options.strong||"*"}function kR(e,t,i,s){return i.safe(e.value,s)}function ER(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 NR(e,t,i){const s=(bS(i)+(i.options.ruleSpaces?" ":"")).repeat(ER(i));return i.options.ruleSpaces?s.slice(0,-1):s}const yS={blockquote:XA,break:Gv,code:iR,definition:rR,emphasis:hS,hardBreak:Gv,heading:oR,html:dS,image:fS,imageReference:pS,inlineCode:mS,link:xS,linkReference:_S,list:xR,listItem:bR,paragraph:vR,root:SR,strong:vS,text:kR,thematicBreak:NR};function jR(){return{enter:{table:TR,tableData:Yv,tableHeader:Yv,tableRow:RR},exit:{codeText:DR,table:AR,tableData:Rf,tableHeader:Rf,tableRow:Rf}}}function TR(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 AR(e){this.exit(e),this.data.inTable=void 0}function RR(e){this.enter({type:"tableRow",children:[]},e)}function Rf(e){this.exit(e)}function Yv(e){this.enter({type:"tableCell",children:[]},e)}function DR(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,MR));const i=this.stack[this.stack.length-1];i.type,i.value=t,this.exit(e)}function MR(e,t){return t==="|"?t:e}function BR(e){const t=e||{},i=t.tableCellPadding,s=t.tablePipeAlign,a=t.stringLength,o=i?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:` +`,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:b,table:c,tableCell:p,tableRow:h}};function c(v,S,j,R){return f(_(v,j,R),v.align)}function h(v,S,j,R){const E=x(v,j,R),N=f([E]);return N.slice(0,N.indexOf(` +`))}function p(v,S,j,R){const E=j.enter("tableCell"),N=j.enter("phrasing"),I=j.containerPhrasing(v,{...R,before:o,after:o});return N(),E(),I}function f(v,S){return KA(v,{align:S,alignDelimiters:s,padding:i,stringLength:a})}function _(v,S,j){const R=v.children;let E=-1;const N=[],I=S.enter("table");for(;++E0&&!i&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),i}const QR={tokenize:a3,partial:!0};function JR(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:n3,continuation:{tokenize:r3},exit:s3}},text:{91:{name:"gfmFootnoteCall",tokenize:i3},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:e3,resolveTo:t3}}}}function e3(e,t,i){const s=this;let a=s.events.length;const o=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let c;for(;a--;){const p=s.events[a][1];if(p.type==="labelImage"){c=p;break}if(p.type==="gfmFootnoteCall"||p.type==="labelLink"||p.type==="label"||p.type==="image"||p.type==="link")break}return h;function h(p){if(!c||!c._balanced)return i(p);const f=fr(s.sliceSerialize({start:c.end,end:s.now()}));return f.codePointAt(0)!==94||!o.includes(f.slice(1))?i(p):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(p),e.exit("gfmFootnoteCallLabelMarker"),t(p))}}function t3(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 i3(e,t,i){const s=this,a=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let o=0,c;return h;function h(x){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(x),e.exit("gfmFootnoteCallLabelMarker"),p}function p(x){return x!==94?i(x):(e.enter("gfmFootnoteCallMarker"),e.consume(x),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",f)}function f(x){if(o>999||x===93&&!c||x===null||x===91||qt(x))return i(x);if(x===93){e.exit("chunkString");const b=e.exit("gfmFootnoteCallString");return a.includes(fr(s.sliceSerialize(b)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(x),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):i(x)}return qt(x)||(c=!0),o++,e.consume(x),x===92?_:f}function _(x){return x===91||x===92||x===93?(e.consume(x),o++,f):f(x)}}function n3(e,t,i){const s=this,a=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let o,c=0,h;return p;function p(S){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionLabelMarker"),f}function f(S){return S===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",_):i(S)}function _(S){if(c>999||S===93&&!h||S===null||S===91||qt(S))return i(S);if(S===93){e.exit("chunkString");const j=e.exit("gfmFootnoteDefinitionLabelString");return o=fr(s.sliceSerialize(j)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),b}return qt(S)||(h=!0),c++,e.consume(S),S===92?x:_}function x(S){return S===91||S===92||S===93?(e.consume(S),c++,_):_(S)}function b(S){return S===58?(e.enter("definitionMarker"),e.consume(S),e.exit("definitionMarker"),a.includes(o)||a.push(o),kt(e,v,"gfmFootnoteDefinitionWhitespace")):i(S)}function v(S){return t(S)}}function r3(e,t,i){return e.check(Fo,t,e.attempt(QR,t,i))}function s3(e){e.exit("gfmFootnoteDefinition")}function a3(e,t,i){const s=this;return kt(e,a,"gfmFootnoteDefinitionIndent",5);function a(o){const c=s.events[s.events.length-1];return c&&c[1].type==="gfmFootnoteDefinitionIndent"&&c[2].sliceSerialize(c[1],!0).length===4?t(o):i(o)}}function l3(e){let i=(e||{}).singleTilde;const s={name:"strikethrough",tokenize:o,resolveAll:a};return i==null&&(i=!0),{text:{126:s},insideSpan:{null:[s]},attentionMarkers:{null:[126]}};function a(c,h){let p=-1;for(;++p1?p(S):(c.consume(S),x++,v);if(x<2&&!i)return p(S);const R=c.exit("strikethroughSequenceTemporary"),E=ml(S);return R._open=!E||E===2&&!!j,R._close=!j||j===2&&!!E,h(S)}}}class o3{constructor(){this.map=[]}add(t,i,s){c3(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 c3(e,t,i,s){let a=0;if(!(i===0&&s.length===0)){for(;a-1;){const X=s.events[ce][1].type;if(X==="lineEnding"||X==="linePrefix")ce--;else break}const W=ce>-1?s.events[ce][1].type:null,K=W==="tableHead"||W==="tableRow"?D:p;return K===D&&s.parser.lazy[s.now().line]?i(H):K(H)}function p(H){return e.enter("tableHead"),e.enter("tableRow"),f(H)}function f(H){return H===124||(c=!0,o+=1),_(H)}function _(H){return H===null?i(H):Ye(H)?o>1?(o=0,s.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(H),e.exit("lineEnding"),v):i(H):gt(H)?kt(e,_,"whitespace")(H):(o+=1,c&&(c=!1,a+=1),H===124?(e.enter("tableCellDivider"),e.consume(H),e.exit("tableCellDivider"),c=!0,_):(e.enter("data"),x(H)))}function x(H){return H===null||H===124||qt(H)?(e.exit("data"),_(H)):(e.consume(H),H===92?b:x)}function b(H){return H===92||H===124?(e.consume(H),x):x(H)}function v(H){return s.interrupt=!1,s.parser.lazy[s.now().line]?i(H):(e.enter("tableDelimiterRow"),c=!1,gt(H)?kt(e,S,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(H):S(H))}function S(H){return H===45||H===58?R(H):H===124?(c=!0,e.enter("tableCellDivider"),e.consume(H),e.exit("tableCellDivider"),j):F(H)}function j(H){return gt(H)?kt(e,R,"whitespace")(H):R(H)}function R(H){return H===58?(o+=1,c=!0,e.enter("tableDelimiterMarker"),e.consume(H),e.exit("tableDelimiterMarker"),E):H===45?(o+=1,E(H)):H===null||Ye(H)?te(H):F(H)}function E(H){return H===45?(e.enter("tableDelimiterFiller"),N(H)):F(H)}function N(H){return H===45?(e.consume(H),N):H===58?(c=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(H),e.exit("tableDelimiterMarker"),I):(e.exit("tableDelimiterFiller"),I(H))}function I(H){return gt(H)?kt(e,te,"whitespace")(H):te(H)}function te(H){return H===124?S(H):H===null||Ye(H)?!c||a!==o?F(H):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(H)):F(H)}function F(H){return i(H)}function D(H){return e.enter("tableRow"),ie(H)}function ie(H){return H===124?(e.enter("tableCellDivider"),e.consume(H),e.exit("tableCellDivider"),ie):H===null||Ye(H)?(e.exit("tableRow"),t(H)):gt(H)?kt(e,ie,"whitespace")(H):(e.enter("data"),fe(H))}function fe(H){return H===null||H===124||qt(H)?(e.exit("data"),ie(H)):(e.consume(H),H===92?Se:fe)}function Se(H){return H===92||H===124?(e.consume(H),fe):fe(H)}}function f3(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 o3;for(;++ii[2]+1){const S=i[2]+1,j=i[3]-i[2]-1;e.add(S,j,[])}}e.add(i[3]+1,0,[["exit",x,t]])}return a!==void 0&&(o.end=Object.assign({},ol(t.events,a)),e.add(a,0,[["exit",o,t]]),o=void 0),o}function Vv(e,t,i,s,a){const o=[],c=ol(t.events,i);a&&(a.end=Object.assign({},c),o.push(["exit",a,t])),s.end=Object.assign({},c),o.push(["exit",s,t]),e.add(i+1,0,o)}function ol(e,t){const i=e[t],s=i[0]==="enter"?"start":"end";return i[1][s]}const p3={name:"tasklistCheck",tokenize:g3};function m3(){return{text:{91:p3}}}function g3(e,t,i){const s=this;return a;function a(p){return s.previous!==null||!s._gfmTasklistFirstContentOfListItem?i(p):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(p),e.exit("taskListCheckMarker"),o)}function o(p){return qt(p)?(e.enter("taskListCheckValueUnchecked"),e.consume(p),e.exit("taskListCheckValueUnchecked"),c):p===88||p===120?(e.enter("taskListCheckValueChecked"),e.consume(p),e.exit("taskListCheckValueChecked"),c):i(p)}function c(p){return p===93?(e.enter("taskListCheckMarker"),e.consume(p),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),h):i(p)}function h(p){return Ye(p)?t(p):gt(p)?e.check({tokenize:x3},t,i)(p):i(p)}}function x3(e,t,i){return kt(e,s,"whitespace");function s(a){return a===null?i(a):t(a)}}function _3(e){return z0([FR(),JR(),l3(e),h3(),m3()])}const b3={};function AS(e){const t=this,i=e||b3,s=t.data(),a=s.micromarkExtensions||(s.micromarkExtensions=[]),o=s.fromMarkdownExtensions||(s.fromMarkdownExtensions=[]),c=s.toMarkdownExtensions||(s.toMarkdownExtensions=[]);a.push(_3(i)),o.push(IR()),c.push(HR(i))}const ha=["ariaDescribedBy","ariaLabel","ariaLabelledBy"],gl={ancestors:{tbody:["table"],td:["table"],th:["table"],thead:["table"],tfoot:["table"],tr:["table"]},attributes:{a:[...ha,"dataFootnoteBackref","dataFootnoteRef",["className","data-footnote-backref"],"href"],blockquote:["cite"],code:[["className",/^language-./]],del:["cite"],div:["itemScope","itemType"],dl:[...ha],h2:[["className","sr-only"]],img:[...ha,"longDesc","src"],input:[["disabled",!0],["type","checkbox"]],ins:["cite"],li:[["className","task-list-item"]],ol:[...ha,["className","contains-task-list"]],q:["cite"],section:["dataFootnotes",["className","footnotes"]],source:["srcSet"],summary:[...ha],table:[...ha],ul:[...ha,["className","contains-task-list"]],"*":["abbr","accept","acceptCharset","accessKey","action","align","alt","axis","border","cellPadding","cellSpacing","char","charOff","charSet","checked","clear","colSpan","color","cols","compact","coords","dateTime","dir","encType","frame","hSpace","headers","height","hrefLang","htmlFor","id","isMap","itemProp","label","lang","maxLength","media","method","multiple","name","noHref","noShade","noWrap","open","prompt","readOnly","rev","rowSpan","rows","rules","scope","selected","shape","size","span","start","summary","tabIndex","title","useMap","vAlign","value","width"]},clobber:["ariaDescribedBy","ariaLabelledBy","id","name"],clobberPrefix:"user-content-",protocols:{cite:["http","https"],href:["http","https","irc","ircs","mailto","xmpp"],longDesc:["http","https"],src:["http","https"]},required:{input:{disabled:!0,type:"checkbox"}},strip:["script"],tagNames:["a","b","blockquote","br","code","dd","del","details","div","dl","dt","em","h1","h2","h3","h4","h5","h6","hr","i","img","input","ins","kbd","li","ol","p","picture","pre","q","rp","rt","ruby","s","samp","section","source","span","strike","strong","sub","summary","sup","table","tbody","td","tfoot","th","thead","tr","tt","ul","var"]},Ps={}.hasOwnProperty;function v3(e,t){let i={type:"root",children:[]};const s={schema:t?{...gl,...t}:gl,stack:[]},a=RS(s,e);return a&&(Array.isArray(a)?a.length===1?i=a[0]:i.children=a:i=a),i}function RS(e,t){if(t&&typeof t=="object"){const i=t;switch(typeof i.type=="string"?i.type:""){case"comment":return y3(e,i);case"doctype":return S3(e,i);case"element":return w3(e,i);case"root":return C3(e,i);case"text":return k3(e,i)}}}function y3(e,t){if(e.schema.allowComments){const i=typeof t.value=="string"?t.value:"",s=i.indexOf("-->"),o={type:"comment",value:s<0?i:i.slice(0,s)};return Wo(o,t),o}}function S3(e,t){if(e.schema.allowDoctypes){const i={type:"doctype"};return Wo(i,t),i}}function w3(e,t){const i=typeof t.tagName=="string"?t.tagName:"";e.stack.push(i);const s=DS(e,t.children),a=E3(e,t.properties);e.stack.pop();let o=!1;if(i&&i!=="*"&&(!e.schema.tagNames||e.schema.tagNames.includes(i))&&(o=!0,e.schema.ancestors&&Ps.call(e.schema.ancestors,i))){const h=e.schema.ancestors[i];let p=-1;for(o=!1;++p1){let a=!1,o=0;for(;++o-1&&o>p||c>-1&&o>c||h>-1&&o>h)return!0;let f=-1;for(;++f4&&t.slice(0,4).toLowerCase()==="data")return i}function BS(e){return function(t){return v3(t,e)}}const dl=["Romance","Fantasy","Science Fiction","Mystery","Thriller","Horror","Adventure","Historical Fiction","Contemporary Lit","Humor","Poetry","Non-Fiction","Fanfiction","Short Story","Paranormal","Werewolf","LGBTQ+","New Adult","Teen Fiction","Diverse Lit","Others"],ts=["English","Chinese","Korean","Japanese","Spanish","French","Hindi","Arabic","Portuguese","Russian","Others"];function LS(e){return e.toLowerCase().replace(/[^a-z0-9+]/g,"")}const T3=Object.fromEntries(dl.map(e=>[LS(e),e])),A3={scifi:"Science Fiction",sf:"Science Fiction",comedy:"Humor",humour:"Humor",ya:"Teen Fiction",youngadult:"Teen Fiction",lgbt:"LGBTQ+",lgbtq:"LGBTQ+","lgbtqia+":"LGBTQ+",historical:"Historical Fiction",scary:"Horror"};function Cu(e){if(!e)return null;const t=LS(e.trim());return t?T3[t]??A3[t]??null:null}function OS(e,t){const i=t.startsWith("assets/")?t.slice(7):t;return`/api/stories/${e}/asset/${i}`}function zS(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(OS(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 Bp({storyName:e,assetPath:t,authFetch:i,alt:s,className:a}){const{url:o,loading:c,error:h}=zS(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 Qv(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 uu(e,t,i,s,a){const o=a.lineHeightFactor??1.2,c=a.speakerScale??.8,h=a.paddingX??Math.max(2,i*.06),p=a.paddingY??Math.max(2,s*.08),f=Math.max(1,i-2*h),_=Math.max(1,s-2*p),x=Math.max(a.minFontSize,a.maxFontSize),b=Math.max(1,Math.min(a.minFontSize,x)),v=j=>{const R=a.hasSpeaker?j*c:0,E=a.hasSpeaker?R*o:0,N=Math.max(1,_-E),I=a.fontWeight??400,te=Qv((ie,fe)=>e(ie,fe,I),t,f,j),F=te.length*j*o,D=te.every(ie=>e(ie,j,I)<=f+.5);return{lines:te,ok:F<=N&&D}};if(typeof a.fontSize=="number"&&Number.isFinite(a.fontSize)&&a.fontSize>0){const j=Math.max(1,a.fontSize),{lines:R,ok:E}=v(j);return{lines:R,fontSize:j,lineHeight:j*o,speakerFontSize:a.hasSpeaker?j*c:0,overflow:!E}}for(let j=x;j>=b;j-=.5){const{lines:R,ok:E}=v(j);if(E)return{lines:R,fontSize:j,lineHeight:j*o,speakerFontSize:a.hasSpeaker?j*c:0,overflow:!1}}return{lines:Qv(e,t,f,b),fontSize:b,lineHeight:b*o,speakerFontSize:a.hasSpeaker?b*c:0,overflow:!0}}function R3(e){return{minFontSize:Math.max(1,e*.022),maxFontSize:Math.max(1,e*.05)}}const PS=["speech","narration","sfx"],D3=2;function Ar(e,t,i){return Math.min(i,Math.max(t,e))}function fl(e,t,i){return typeof e=="number"&&Number.isFinite(e)?Ar(e,t,i):void 0}function xm(e){if(!e||typeof e!="object")return;const t=e,i=t.mode==="manual"?"manual":t.mode==="auto"?"auto":void 0,s=fl(t.fontScale,.015,.12),a=t.fontWeight===700?700:t.fontWeight===400?400:void 0,o=fl(t.lineHeightFactor,.9,2),c=fl(t.speakerScale,.5,1.5);if(!(!i&&s===void 0&&a===void 0&&o===void 0&&c===void 0))return{...i?{mode:i}:{},...s!==void 0?{fontScale:s}:{},...a!==void 0?{fontWeight:a}:{},...o!==void 0?{lineHeightFactor:o}:{},...c!==void 0?{speakerScale:c}:{}}}function Yu(e){if(!e||typeof e!="object")return;const t=e,i=fl(t.paddingX,0,.25),s=fl(t.paddingY,0,.25),a=fl(t.cornerRadius,0,.49);if(!(i===void 0&&s===void 0&&a===void 0))return{...i!==void 0?{paddingX:i}:{},...s!==void 0?{paddingY:s}:{},...a!==void 0?{cornerRadius:a}:{}}}function hu(e,t,i,s){const{minFontSize:a,maxFontSize:o}=R3(t),c=xm(e.textStyle),h=Yu(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 M3(e,t,i){const s=Yu(e.bubbleStyle);return(s==null?void 0:s.cornerRadius)!==void 0?Math.min(t,i)*s.cornerRadius:void 0}function IS(e,t){const i=Math.min(e,t);return Math.max(0,Math.min(i*.4,i/2))}function Jv(e,t,i,s,a){const o=Math.max(0,i-2*s),c=Math.max(1,Math.min(a,o)/2),h=t+s+c,p=t+i-s-c;return{center:p>=h?Ar(e,h,p):t+i/2,half:c}}function HS(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??IS(i,s);if(Math.abs(x)>=Math.abs(_)){const E=x>=0?t+s:t,{center:N,half:I}=Jv(p,e,i,v,b);return{tip:{x:p,y:f},base1:{x:N-I,y:E},base2:{x:N+I,y:E}}}const S=_>=0?e+i:e,{center:j,half:R}=Jv(f,t,s,v,b);return{tip:{x:p,y:f},base1:{x:S,y:j-R},base2:{x:S,y:j+R}}}function B3(e){return e.type!=="speech"||!e.tailAnchor?!1:HS(0,0,1,1,e.tailAnchor)!==null}function L3(e,t,i,s,a,o){const c=o??IS(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 O3(e,t,i,s,a,o){const c=L3(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 z3(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 ey=0;function Lp(e,t=.1,i=.1){return ey++,{id:`overlay-${Date.now()}-${ey}`,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 US(e,t,i){return{width:Math.min(e==="sfx"?.3:.5,Math.max(.15,1-t)),height:Math.min(e==="sfx"?.1:.2,Math.max(.06,1-i))}}const du=.05;function Ui(e){return typeof e=="number"&&Number.isFinite(e)}function P3(e,t,i){const s=e.toLowerCase(),a=/\bleft\b/.test(s),o=/\bright\b/.test(s),c=/\b(?:top|upper)\b/.test(s),h=/\b(?:bottom|lower)\b/.test(s),p=/\b(?:center|centre|middle)\b/.test(s);if(!a&&!o&&!c&&!h&&!p)return null;const f=a?du:Ar(o?1-t-du:(1-t)/2,0,1),_=c?du:Ar(h?1-i-du:(1-i)/2,0,1);return{x:f,y:_}}let I3=0;function H3(e){if(!e||typeof e!="object")return null;const t=e,i=PS.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"?P3(t.position,a,o):null;if(!b)return null;c=b.x,h=b.y}c=Ar(c,0,1),h=Ar(h,0,1),a=Ar(a,.02,1),o=Ar(o,.02,1);const f={id:typeof t.id=="string"&&t.id?t.id:`overlay-norm-${++I3}`,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 _=xm(t.textStyle),x=Yu(t.bubbleStyle);return _&&(f.textStyle=_),x&&(f.bubbleStyle=x),f}function U3(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.id=="string"&&!!t.id&&PS.includes(t.type)&&Ui(t.x)&&Ui(t.y)&&Ui(t.width)&&Ui(t.height)&&typeof t.text=="string"}function $3(e){const t=Array.isArray(e)?e:[],i=[],s=[];let a=!Array.isArray(e);return t.forEach((o,c)=>{const h=H3(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),U3(o)||(a=!0)}),{overlays:i,changed:a,invalid:s}}function e4(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=xm(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=Yu(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 ty=new Set(["speech","narration"]),F3=.12;function iy(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 q3(e,t=F3){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 In(e){return e.kind==="text"}function W3(e){return!!e.finalImagePath||!!e.exportedAt?{key:"review",label:"Review final panel",opensEditor:!0}:e.cleanImagePath||In(e)?{key:"letter",label:"Letter this cut",opensEditor:!0}:{key:"add-art",label:"Add clean art for this cut",opensEditor:!1}}function $S(e,t=D3){return!e.finalImagePath||!(e.overlays??[]).some(B3)?!1:(e.finalRendererVersion??0)0)||!(s>0)?null:{width:ny,height:Math.round(ny*s/i)}}function fu({cut:e}){return e.dialogue.length>0||e.narration||e.sfx?d.jsxs("div",{className:"space-y-1.5","data-testid":`cut-${e.id}-overlay`,children:[e.dialogue.map((i,s)=>d.jsxs("div",{className:"flex gap-2 text-xs",children:[d.jsxs("span",{className:"font-medium text-foreground flex-shrink-0",children:[i.speaker,":"]}),d.jsx("span",{className:"text-foreground",children:i.text})]},s)),e.narration&&d.jsx("div",{className:"border-l-2 border-border pl-3",children:d.jsx("p",{className:"text-xs text-muted italic",children:e.narration})}),e.sfx&&d.jsxs("p",{className:"text-xs font-mono text-muted",children:["SFX: ",e.sfx]})]}):null}function Y3({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(Bp,{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(Bp,{storyName:t,assetPath:e.cleanImagePath,authFetch:i,alt:e.description||`Cut ${e.id}`}),d.jsx("div",{className:"px-3 py-2 bg-surface/80 border-t border-border",children:d.jsx(fu,{cut:e})})]}),!c&&p&&d.jsxs("div",{className:"w-full border border-border rounded p-4 space-y-2",style:{background:e.background||void 0},"data-testid":`cut-${e.id}-textpanel`,children:[d.jsx("span",{className:"text-[10px] font-mono text-muted",children:"Text panel"}),h?d.jsx(fu,{cut:e}):d.jsx("p",{className:"text-xs text-muted italic",children:"Empty text panel — open the editor to add text."})]}),!c&&!p&&d.jsxs("div",{className:"w-full bg-surface border border-dashed border-border rounded p-4 space-y-2","data-testid":`cut-${e.id}-pending`,children:[d.jsxs("div",{className:"aspect-video flex flex-col items-center justify-center gap-1 text-center",children:[d.jsx("span",{className:"text-xs text-muted font-medium",children:"Image pending"}),d.jsx("span",{className:"text-[10px] text-muted",children:"Planned image cut — generate & upload the art"})]}),h&&d.jsxs("div",{className:"border-t border-dashed border-border pt-2 space-y-1",children:[d.jsx("span",{className:"text-[10px] font-mono text-muted",children:"Planned text (will be lettered onto the image)"}),d.jsx(fu,{cut:e})]})]}),e.description&&d.jsx("p",{className:"text-xs text-muted italic",children:e.description}),a&&d.jsx(fu,{cut:e}),s&&(()=>{const f=W3(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 K3({storyName:e,fileName:t,authFetch:i,onEditCut:s}){const[a,o]=w.useState(null),[c,h]=w.useState(!0),[p,f]=w.useState(null),_=t.replace(/\.md$/,""),x=w.useCallback(async()=>{h(!0),f(null);try{const b=await i(`/api/stories/${e}/cuts/${_}`);if(b.status===404){o(null),h(!1);return}if(!b.ok){const S=await b.json();f(S.error||"Failed to load cuts"),h(!1);return}const v=await b.json();o(v)}catch{f("Failed to load cuts")}finally{h(!1)}},[i,e,_]);return w.useEffect(()=>{x();const b=setInterval(x,5e3);return()=>clearInterval(b)},[x]),c&&!a?d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Loading cuts..."}):p?d.jsxs("div",{className:"h-full flex flex-col items-center justify-center gap-2 px-4 text-center","data-testid":"cuts-error",children:[d.jsx("p",{className:"text-sm text-error font-medium",children:"Invalid cuts file"}),d.jsx("p",{className:"text-xs text-error",children:p}),d.jsxs("p",{className:"text-xs text-muted max-w-sm",children:[_,".cuts.json must follow the OWS v1 schema. Ask Claude to regenerate it using the v1 cuts schema shown in the cartoon writing instructions."]}),d.jsx("button",{onClick:x,className:"text-xs text-accent hover:text-accent-dim",children:"Retry"})]}):!a||a.cuts.length===0?d.jsxs("div",{className:"h-full flex flex-col items-center justify-center gap-2 px-4 text-center",children:[d.jsx("p",{className:"text-sm text-muted",children:"No cuts yet"}),d.jsx("p",{className:"text-xs text-muted",children:"Ask Claude to create a cut plan for this episode."})]}):d.jsx("div",{className:"h-full overflow-y-auto",children:d.jsx("div",{className:"max-w-lg mx-auto px-4 py-6 space-y-6",children:a.cuts.map(b=>d.jsx(Y3,{cut:b,storyName:e,authFetch:i,onEditCut:s},b.id))})})}const ry=/!\[[^\]]*\]\([^)]*\)/g,V3=//g,FS=200;function X3(e){const t=(e.match(ry)||[]).length,i=e.length,s=e.replace(V3," ").replace(ry," ").replace(/\s+/g," ").trim();return{imageCount:t,charCount:i,nonImageProse:s,nonImageProsePreview:s.slice(0,FS)}}function Z3(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 Q3=[/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 J3(e){for(const t of Q3){const i=e.match(t);if(i)return i[0]}return null}function _m(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=J3(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 WS(e,t){const i=t.length;if(i===0)return{stage:"not-started",issues:[],awaitingCount:0,totalCuts:0};if(eD(e,t))return{stage:"planning",issues:[],awaitingCount:0,totalCuts:i};const{ready:s,issues:a}=qS(e,t);if(s)return{stage:"ready",issues:[],awaitingCount:0,totalCuts:i};const o=new Set;for(let p=0;p!c.has(p));return h.length>0?{stage:"error",issues:h,awaitingCount:o.size,totalCuts:i}:{stage:"awaiting-upload",issues:[],awaitingCount:o.size,totalCuts:i}}const Df=[{key:"assemble",title:"Prepare the episode for publish",test:/markdown block|missing or incomplete/i},{key:"export",title:"Export final images",test:/re-export|older speech-bubble|visible seam/i},{key:"upload",title:"Upload final images",test:/not uploaded|no recorded uploaded url/i},{key:"images",title:"Fix image references",test:/image reference|not an http|does not match|exactly one image/i},{key:"cleanup",title:"Remove leftover text",test:/placeholder|instructional|awaiting-upload|awaiting upload/i},{key:"size",title:"Shorten the episode",test:/\blimit\b|\bchars\b/i}];function tD(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 GS(e){const t=c=>{var h;return((h=Df.find(p=>p.test.test(c)))==null?void 0:h.key)??"other"},i=new Map;for(const c of e){const h=t(c);i.has(h)||i.set(h,[]),i.get(h).push(c)}const s=[...Df.map(c=>c.key),"other"],a=c=>{var h;return((h=Df.find(p=>p.key===c))==null?void 0:h.title)??"Other issues"},o=[];for(const c of s){const h=i.get(c);!h||h.length===0||o.push({key:c,title:a(c),lines:tD(h)})}return o}const iD=220,Mf=/^(genre|logline|synopsis|premise|setting|tone|theme|themes|summary|hook|characters?|cast|arc|status|word\s*count|length|title)\b\s*[:\-–]/i;function bm(e){const t=[],i=[],s=e??"",a=s.match(/^#[ \t]+(.+)$/m),o=!!(a&&a[1].trim());o||t.push("Add a “# Title” heading — the Story opening needs a real title readers see first.");const c=s.replace(/^#\s+.+$/m,"").trim();if(c.lengthx.trim()).filter(Boolean),p=h.filter(x=>/^([-*+]|\d+[.)])\s/.test(x)||Mf.test(x)).length,f=c.split(/\n\s*\n/).map(x=>x.trim()).filter(Boolean),_=f.some(x=>x.length>=120&&!/^([-*+]|\d+[.)])\s/.test(x)&&!Mf.test(x));h.length>0&&p/h.length>=.5||!_?t.push("This reads like a synopsis or outline. Write the Genesis as a reader-facing opening scene that sets up the first beat and stakes, then bridges into Episode 01 — not a logline, genre pitch, or character list."):f.filter(b=>b.length>=40&&!/^([-*+]|\d+[.)])\s/.test(b)&&!Mf.test(b)).length<2&&t.push("Give the opening room to build: open across a few short paragraphs — the premise, what the lead wants, and the hook — that lead into Episode 01, instead of a single dense block that drops readers into a cold scene.")}return{hasTitle:o,blockers:t,warnings:i}}function nD(e){return/\.(webp|jpe?g)$/i.test(e)}function Op(e){var c,h;let t=0,i=0,s=0,a=0,o=0;for(const p of e)In(p)?(((h=p.overlays)==null?void 0:h.length)??0)>0&&s++:(t++,p.cleanImagePath&&nD(p.cleanImagePath)&&(i++,(((c=p.overlays)==null?void 0:c.length)??0)>0&&s++)),p.finalImagePath&&p.exportedAt&&a++,p.uploadedUrl&&o++;return{total:e.length,needClean:t,withClean:i,withText:s,exported:a,uploaded:o}}const rD={plan:"Plan cuts",clean:"Create clean images",letter:"Add speech bubbles & captions",export:"Export final images",upload:"Upload final images",publish:"Publish to PlotLink"};function vo(e,t){return`${e} / ${t} cut${t===1?"":"s"}`}function sD(e){const{cuts:t,published:i=!1}=e,s=Op(t);if(s.total===0)return{steps:[],nextStep:null};const a=s.total>0,o=a&&s.withClean===s.needClean,c=o&&s.withText===s.total,h=c&&s.exported===s.total,p=h&&s.uploaded===s.total,_={plan:a,clean:o,letter:c,export:h,upload:p,publish:p&&i},x=["plan","clean","letter","export","upload","publish"],b=x.findIndex(N=>!_[N]),v=N=>s.needClean>0?vo(N,s.needClean):"no image cuts",S={plan:vo(s.total,s.total),clean:v(s.withClean),letter:vo(s.withText,s.total),export:vo(s.exported,s.total),upload:vo(s.uploaded,s.total),publish:null},j=x.map((N,I)=>({key:N,label:rD[N],status:b===-1||IFS,a=oD({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] ${uD[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(rS,{remarkPlugins:[aS,AS],rehypePlugins:[[BS,cD]],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 dD="modulepreload",fD=function(e){return"/"+e},sy={},ay=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=fD(f),f in sy)return;sy[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":dD,_||(b.as="script"),b.crossOrigin="",b.href=f,p&&b.setAttribute("nonce",p),document.head.appendChild(b),_)return new Promise((v,S)=>{b.addEventListener("load",v),b.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${f}`)))})}))}function o(c){const h=new Event("vite:preloadError",{cancelable:!0});if(h.payload=c,window.dispatchEvent(h),!h.defaultPrevented)throw c}return a.then(c=>{for(const h of c||[])h.status==="rejected"&&o(h.reason);return t().catch(o)})},vm=[{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:[]}],pD="system-ui, sans-serif",mD=vm.find(e=>e.family==="Noto Sans"),gD=vm.find(e=>e.category==="display");function xD(e){return vm.find(i=>i.category==="body"&&i.languages.includes(e))||mD}function _D(){return gD}function bD(e){const t=e.weights.join(";");return`https://fonts.googleapis.com/css2?family=${e.googleFontsId}:wght@${t}&display=swap`}function ly(e){return`"${e.family}", ${pD}`}function vD(e,t={}){var a,o,c,h;const i=!t.staleExport&&(!!e.finalImagePath||!!e.exportedAt),s=!t.staleExport&&(!!e.uploadedUrl||!!e.uploadedCid);return{hasCleanImage:!!e.cleanImagePath,hasScriptText:(((a=e.dialogue)==null?void 0:a.length)??0)>0||!!((o=e.narration)!=null&&o.trim())||!!((c=e.sfx)!=null&&c.trim()),bubblesPlaced:((h=e.overlays)==null?void 0:h.length)??0,exported:i,uploaded:s}}function ul(e){return JSON.stringify((e??[]).map(t=>[t.type,t.x,t.y,t.width,t.height,t.text,t.speaker??"",t.tailAnchor??null,t.textStyle??null,t.bubbleStyle??null]))}function yD(e){return!e.exported&&!e.uploaded?!1:e.baselineSig!==ul(e.current)}function ym(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 SD(e,t,i){if(e==="narration")return{x:.08,y:.05+Math.min(t,2)*.18};if(e==="sfx"){const c=t%2,h=Math.floor(t/2);return{x:c===0?.1:.62,y:.68+h*.12}}const s=Math.floor(t/2),a=t%2===0,o=.08+s*Math.max(.15,Math.min(.22,i>4?.16:.2));return{x:a?.05:.45,y:o}}function oy(e){const t=ym(e);return t.map((i,s)=>{const{x:a,y:o}=SD(i.type,s,t.length),c=Lp(i.type,a,o),h=US(i.type,a,o);return{...c,...h,text:i.text,...i.type==="speech"?{speaker:i.speaker??""}:{}}})}function wn(e,t){return e*t}function cy(e,t){return t===0?0:e/t}function uy(e){const t=`gfont-${e.googleFontsId}`;if(document.getElementById(t))return;const i=document.createElement("link");i.id=t,i.rel="stylesheet",i.href=bD(e),document.head.appendChild(i)}const ku={speech:"Speech",narration:"Narration",sfx:"SFX"},wD={speech:"border-foreground/40",narration:"border-muted/40",sfx:"border-accent/40"};function Bf(e){const t=(e.speaker||e.text||"").trim().replace(/\s+/g," ");return t?`“${t.length>18?`${t.slice(0,18)}…`:t}”`:ku[e.type]}const hy=.05,CD=[{key:"down",label:"Down",anchor:{x:.5,y:1.2}},{key:"up",label:"Up",anchor:{x:.5,y:-.2}},{key:"left",label:"Left",anchor:{x:-.2,y:.5}},{key:"right",label:"Right",anchor:{x:1.2,y:.5}}];function pu(e,t,i){return Math.min(i,Math.max(t,e))}function kD({storyName:e,cut:t,plotFile:i,onSave:s,onClose:a,onExported:o,language:c="English",authFetch:h,targetLabel:p,returnOnSave:f=!1,workspaceVisible:_=!1,onToggleWorkspaceVisible:x}){var Wt,ui,Bt,vt,At,Ze,hi;const b=xD(c),v=_D(),S=ly(b),j=ly(v);w.useEffect(()=>{uy(b),uy(v)},[b,v]),w.useEffect(()=>{let P=!1;return K(!1),(async()=>{try{const{ensureFontsReady:we}=await ay(async()=>{const{ensureFontsReady:ze}=await import("./export-cut-BqZI0-Rv.js");return{ensureFontsReady:ze}},[]);await we([b.family,v.family])}catch{}P||K(!0)})(),()=>{P=!0}},[b.family,v.family]);const R=zS(e,t.cleanImagePath,h),E=w.useMemo(()=>$3(t.overlays),[t.overlays]),N=E.invalid.length,[I,te]=w.useState(!1),F=N===0&&E.changed&&E.overlays.length>0,[D,ie]=w.useState(()=>E.overlays),[fe,Se]=w.useState(()=>ul(E.overlays)),H=w.useRef(null),ce=w.useCallback(P=>(we,ze,Re=400)=>{var $e;!H.current&&typeof document<"u"&&(H.current=document.createElement("canvas"));const Ge=($e=H.current)==null?void 0:$e.getContext("2d");return Ge?(Ge.font=`${Re} ${ze}px ${P}`,Ge.measureText(we).width):we.length*ze*.5},[]),[W,K]=w.useState(!1),[X,U]=w.useState(null),[A,O]=w.useState(!1),[$,xe]=w.useState(!1),[T,M]=w.useState(null),[G,C]=w.useState(null),[V,ne]=w.useState({x:0,y:0,width:0,height:0}),ae=w.useRef(null),Y=w.useRef(null),he=w.useRef(null),_e=w.useCallback(()=>{const P=ae.current;if(!P)return;const we=P.clientWidth,ze=P.clientHeight;let Re,Ge;if(t.kind==="text"){const lt=G3(t.aspectRatio)??{width:800,height:600};Re=lt.width,Ge=lt.height}else{const lt=Y.current;if(!lt||!lt.naturalWidth)return;Re=lt.naturalWidth,Ge=lt.naturalHeight}if(!we||!ze)return;const $e=Math.min(we/Re,ze/Ge),ht=Re*$e,dt=Ge*$e;ne({x:(we-ht)/2,y:(ze-dt)/2,width:ht,height:dt})},[t.kind,t.aspectRatio]);w.useEffect(()=>{const P=ae.current;if(!P)return;const we=new ResizeObserver(()=>_e());return we.observe(P),()=>we.disconnect()},[_e]);const Be=w.useCallback(P=>{const we=US(P.type,P.x,P.y),ze=we.width,Re=Math.max(.08,1-P.y);if(!P.text||!W||V.width<=0)return we;const Ge=P.type==="sfx"?j:S,$e=wn(ze,V.width);let ht=P.type==="sfx"?.08:.12;for(let dt=0;dt<24;dt++){const lt=Math.min(ht,Re),Vt=wn(lt,V.height);if(!uu(ce(Ge),P.text,$e,Vt,hu({...P},V.height||300,$e,Vt)).overflow||lt>=Re)return{width:ze,height:lt};ht+=.03}return{width:ze,height:Math.min(ht,Re)}},[W,V,ce,S,j]),Le=w.useCallback(P=>{const we=Lp(P,.1+Math.random()*.3,.1+Math.random()*.3),ze={...we,...Be(we)};ie(Re=>[...Re,ze]),U(ze.id)},[Be]),je=w.useCallback(P=>{const ze={...Lp(P.type,.1+Math.random()*.3,.1+Math.random()*.3),text:P.text,...P.type==="speech"&&P.speaker?{speaker:P.speaker}:{}},Re={...ze,...Be(ze)};ie(Ge=>[...Ge,Re]),U(Re.id)},[Be]),be=w.useCallback((P,we)=>{ie(ze=>ze.map(Re=>Re.id===P?{...Re,...we}:Re))},[]),tt=w.useCallback(P=>{var ht;const we=V.height||300,ze=V.width>0?wn(P.width,V.width):200,Re=V.height>0?wn(P.height,V.height):100,Ge=P.type==="sfx"?j:S,$e=uu(ce(Ge),P.text,ze,Re,hu({...P,textStyle:void 0},we,ze,Re));be(P.id,{textStyle:{mode:"manual",fontScale:$e.fontSize/Math.max(1,we),fontWeight:((ht=P.textStyle)==null?void 0:ht.fontWeight)??400,lineHeightFactor:$e.fontSize>0?$e.lineHeight/$e.fontSize:1.2,speakerScale:$e.fontSize>0&&$e.speakerFontSize>0?$e.speakerFontSize/$e.fontSize:.8}})},[V,j,S,ce,be]),St=w.useCallback(P=>{ie(we=>we.filter(ze=>ze.id!==P)),U(null),O(!1)},[]),ot=w.useCallback(()=>{U(null),O(!1)},[]),We=w.useCallback((P,we)=>{P.stopPropagation(),U(we),O(!1)},[]),Mt=w.useCallback((P,we,ze)=>{P.stopPropagation(),P.preventDefault();const Re=D.find(Ge=>Ge.id===we);Re&&(U(we),he.current={id:we,mode:ze,startX:P.clientX,startY:P.clientY,origX:Re.x,origY:Re.y,origW:Re.width,origH:Re.height})},[D]);w.useEffect(()=>{const P=ze=>{const Re=he.current;if(!Re||V.width===0)return;const Ge=cy(ze.clientX-Re.startX,V.width),$e=cy(ze.clientY-Re.startY,V.height);if(Re.mode==="move"){const ht=pu(Re.origX+Ge,0,1-Re.origW),dt=pu(Re.origY+$e,0,1-Re.origH);be(Re.id,{x:ht,y:dt})}else{const ht=pu(Re.origW+Ge,hy,1-Re.origX),dt=pu(Re.origH+$e,hy,1-Re.origY);be(Re.id,{width:ht,height:dt})}},we=()=>{he.current=null};return window.addEventListener("mousemove",P),window.addEventListener("mouseup",we),()=>{window.removeEventListener("mousemove",P),window.removeEventListener("mouseup",we)}},[V,be]);const He=w.useCallback(async()=>{var P;C(null);try{const we=ul(D),ze=((P=t.aiDraft)==null?void 0:P.status)==="generated"&&we!==(t.aiDraft.baseSig??"")?{...t.aiDraft,status:"edited",updatedAt:new Date().toISOString()}:t.aiDraft??void 0;await s(D,ze??null),f&&a()}catch(we){C(we instanceof Error?we.message:"Failed to save overlays")}},[D,s,a,f,t.aiDraft]),xt=w.useCallback(async()=>{if(N>0&&!I){const P=N;M(`${P} overlay${P===1?"":"s"} from the cut plan ${P===1?"has":"have"} no usable position and cannot be exported — re-place ${P===1?"it":"them"} or discard ${P===1?"it":"them"} first.`);return}xe(!0),M(null);try{await s(D);const{exportCut:P,ensureFontsReady:we}=await ay(async()=>{const{exportCut:ft,ensureFontsReady:Fi}=await import("./export-cut-BqZI0-Rv.js");return{exportCut:ft,ensureFontsReady:Fi}},[]),ze=D.some(ft=>ft.type==="sfx"),Re=[b.family,...ze?[v.family]:[]],{ready:Ge,missing:$e}=await we(Re);if(!Ge){M(`Fonts not loaded: ${$e.join(", ")}. Check your connection and retry.`),xe(!1);return}if(t.cleanImagePath&&!R.url){M(R.error?"Clean image failed to load — cannot export. Retry once it renders.":"Clean image still loading — wait for it to render, then export."),xe(!1);return}const ht=R.url,dt=await P(ht,D,S,j,{narration:t.narration,dialogue:t.dialogue},t.kind==="text"?{background:t.background,aspectRatio:t.aspectRatio}:void 0),lt=new FormData,Vt=dt.type==="image/webp"?"webp":"jpg";lt.append("file",dt,`cut-${t.id}.${Vt}`);const Ci=await h(`/api/stories/${e}/cuts/${i}/export-final/${t.id}`,{method:"POST",body:lt});if(Ci.ok)Se(ul(D)),o==null||o();else{const ft=await Ci.json();M(ft.error||"Export failed")}}catch(P){M(P instanceof Error?P.message:"Export failed")}finally{xe(!1)}},[t,R,D,e,i,b,v,S,j,h,s,o,N,I]),Ae=D.find(P=>P.id===X),Kt=w.useMemo(()=>q3(D),[D]),mi=w.useRef(t.id);w.useEffect(()=>{mi.current!==t.id&&(mi.current=t.id,Se(ul(E.overlays)))},[t.id,E.overlays]);const wt=yD({exported:!!t.finalImagePath||!!t.exportedAt,uploaded:!!t.uploadedUrl||!!t.uploadedCid,baselineSig:fe,current:D}),Qe=w.useMemo(()=>vD({...t,overlays:D},{staleExport:wt}),[t,D,wt]),Q=w.useMemo(()=>ym(t),[t]),ge=w.useMemo(()=>{const P={};for(const we of D){const ze=z3(we);let Re=!1;if(W&&V.width>0&&we.text){const Ge=we.type==="sfx"?j:S,$e=wn(we.width,V.width),ht=wn(we.height,V.height);Re=uu(ce(Ge),we.text,$e,ht,hu(we,V.height||300,$e,ht)).overflow}(ze||Re)&&(P[we.id]={outOfBounds:ze,overflow:Re})}return P},[D,W,V,ce,S,j]),Te=Object.keys(ge).length,Ue=t.kind==="text",it=!t.cleanImagePath;return!Ue&&it&&D.length===0&&!t.narration&&!((Wt=t.dialogue)!=null&&Wt.length)?d.jsx("div",{className:"h-full flex items-center justify-center text-sm text-muted",children:"No clean image — upload one first, or add overlays for a narration cut."}):d.jsxs("div",{className:"h-full flex flex-col","data-testid":"focused-lettering-editor",children:[d.jsxs("div",{className:"px-4 py-3 border-b border-border bg-surface/40 flex items-center justify-between gap-3",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"text-[10px] font-bold uppercase tracking-[0.16em] text-accent",children:"Focused lettering editor"}),d.jsx("span",{className:"text-xs font-mono text-muted",children:p??`Cut #${t.id}`})]}),d.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"Place bubbles, captions, SFX, or between-scene card text, then save back to the full cut review."}),d.jsxs("span",{className:"text-[10px] text-muted","data-testid":"overlay-count",children:[D.length," overlays"]})]}),d.jsxs("div",{className:"flex items-center gap-2 flex-wrap justify-end",children:[d.jsx("button",{onClick:a,className:"px-3 py-1 text-xs border border-border rounded text-muted hover:text-foreground","data-testid":"return-to-cut-review-btn",children:"Back to cut review"}),x&&d.jsx("button",{onClick:x,className:"px-3 py-1 text-xs border border-border rounded text-muted hover:border-accent hover:text-accent","data-testid":"toggle-work-area-btn",children:_?"Hide work area":"Show work area"}),d.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[d.jsx("button",{onClick:()=>Le("speech"),className:"px-2 py-0.5 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5","data-testid":"add-speech",children:"Speech"}),d.jsx("button",{onClick:()=>Le("narration"),className:"px-2 py-0.5 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5","data-testid":"add-narration",children:"Narration"}),d.jsx("button",{onClick:()=>Le("sfx"),className:"px-2 py-0.5 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5","data-testid":"add-sfx",children:"SFX"})]}),T&&d.jsx("span",{className:"text-[10px] text-error",children:T}),G&&d.jsx("span",{className:"text-[10px] text-error",children:G}),d.jsx("button",{onClick:xt,disabled:$,className:"px-3 py-1 text-xs border border-accent text-accent rounded hover:bg-accent/5 disabled:opacity-50","data-testid":"export-btn",children:$?"Exporting...":"Export"}),d.jsx("button",{onClick:()=>{He()},className:"px-3 py-1 text-xs bg-accent text-white rounded hover:bg-accent-dim","data-testid":"save-lettering-btn",children:"Save"}),d.jsx("button",{onClick:a,className:"px-3 py-1 text-xs text-muted hover:text-foreground border border-border rounded","data-testid":"cancel-lettering-btn",children:"Cancel"})]})]}),N>0&&!I?d.jsxs("div",{className:"px-3 py-1 border-b border-border bg-error/10 text-[10px] text-error flex items-center gap-2 flex-wrap","data-testid":"overlay-repair-note",children:[d.jsxs("span",{children:[N," overlay",N===1?"":"s"," ","from the cut plan ",N===1?"has":"have"," no usable position and cannot be exported. Re-place"," ",N===1?"it":"them",", or"]}),d.jsxs("button",{onClick:()=>te(!0),"data-testid":"discard-invalid-overlays",className:"px-1.5 py-0.5 border border-error/40 rounded hover:bg-error/10",children:["discard ",N," unplaceable overlay",N===1?"":"s"]})]}):N>0?d.jsxs("div",{className:"px-3 py-1 border-b border-border bg-amber-500/10 text-[10px] text-amber-700","data-testid":"overlay-repair-note",children:["Discarded ",N," unplaceable overlay",N===1?"":"s"," — the export will not include"," ",N===1?"it":"them","."]}):F?d.jsx("div",{className:"px-3 py-1 border-b border-border bg-amber-500/10 text-[10px] text-amber-700","data-testid":"overlay-repair-note",children:"Auto-placed overlays from the cut plan — review their positions before exporting."}):null,Kt.length>0&&d.jsxs("div",{className:"px-3 py-1 border-b border-border bg-amber-500/10 text-[10px] text-amber-700","data-testid":"overlay-overlap-warning",children:["Cut #",t.id,": ",Kt.length," bubble"," ",Kt.length===1?"pair overlaps":"pairs overlap"," and may be hard to read —"," ",Kt.map(P=>`#${P.indexA+1} ${Bf(D[P.indexA])} ↔ #${P.indexB+1} ${Bf(D[P.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",Qe.hasCleanImage],["script-text","Script text",Qe.hasScriptText],["bubbles",`Bubbles placed${Qe.bubblesPlaced?` (${Qe.bubblesPlaced})`:""}`,Qe.bubblesPlaced>0],["exported","Final exported",Qe.exported],["uploaded","Uploaded",Qe.uploaded]].map(([P,we,ze])=>d.jsxs("span",{"data-testid":`lettering-check-${P}`,"data-done":ze?"true":"false",className:`flex items-center gap-1 ${ze?"text-green-700":"text-muted/70"}`,children:[d.jsx("span",{"aria-hidden":!0,children:ze?"✓":"○"}),we]},P))}),wt&&d.jsx("div",{className:"px-3 py-1 border-b border-border bg-amber-500/10 text-[10px] text-amber-700","data-testid":"lettering-stale-export-warning",children:"Bubbles changed since the last export — re-export this cut and upload the new final image before publishing."}),Te>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:[Te," bubble",Te===1?"":"s"," may not export cleanly:"," ",Object.entries(ge).map(([P,we])=>{const ze=D.findIndex(Ge=>Ge.id===P),Re=[we.outOfBounds?"outside image":null,we.overflow?"text overflow":null].filter(Boolean).join(", ");return`#${ze+1} ${Bf(D[ze])} (${Re})`}).join("; "),". Resize or reposition before exporting."]}),d.jsxs("div",{className:"flex-1 min-h-0 flex",children:[d.jsxs("div",{ref:ae,className:"flex-1 min-w-0 relative overflow-hidden bg-[#f8f5ef]",onClick:ot,"data-testid":"editor-surface",children:[t.cleanImagePath&&R.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&&!R.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:Y,src:R.url,alt:`Cut ${t.id} clean`,className:"w-full h-full object-contain",draggable:!1,onLoad:_e}):Ue?V.width>0&&d.jsx("div",{className:"absolute flex items-center justify-center text-muted text-xs",style:{left:V.x,top:V.y,width:V.width,height:V.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:P=>{if(P&&V.width===0){const we=P.getBoundingClientRect();we.width>0&&ne({x:0,y:0,width:we.width,height:we.height})}},children:"Narration cut"}),V.width>0&&d.jsx("svg",{className:"absolute inset-0 w-full h-full pointer-events-none","data-testid":"balloon-layer",children:D.map(P=>{if(P.type!=="speech")return null;const we=V.x+wn(P.x,V.width),ze=V.y+wn(P.y,V.height),Re=wn(P.width,V.width),Ge=wn(P.height,V.height),$e=M3(P,Re,Ge),ht=P.tailAnchor?HS(we,ze,Re,Ge,P.tailAnchor,$e):null,dt=Math.max(1.5,V.height*.004),lt=P.id===X;return d.jsx("path",{"data-testid":`balloon-${P.id}`,d:O3(we,ze,Re,Ge,ht,$e),className:`fill-white/95 ${lt?"stroke-accent":"stroke-[#1a1a1a]"}`,strokeWidth:lt?dt+.5:dt,strokeLinejoin:"round"},P.id)})}),V.width>0&&D.map(P=>{const we=V.x+wn(P.x,V.width),ze=V.y+wn(P.y,V.height),Re=wn(P.width,V.width),Ge=wn(P.height,V.height),$e=P.id===X,ht=P.type==="speech",dt=P.type==="narration",lt=!!ge[P.id];return d.jsxs("div",{"data-testid":`overlay-${P.id}`,"data-warning":lt?"true":"false",onClick:Vt=>We(Vt,P.id),onMouseDown:Vt=>Mt(Vt,P.id,"move"),className:`absolute rounded cursor-move select-none ${ht?"":`border-2 ${wD[P.type]}`} ${dt?"bg-[#f4efe6]/85 rounded-md":""} ${$e&&!ht?"ring-2 ring-accent":""} ${lt?"ring-2 ring-amber-500":""}`,style:{left:we,top:ze,width:Re,height:Ge},children:[(()=>{var Fi,En;const Vt=P.type==="sfx"?j:S;if(!P.text)return d.jsx("span",{className:"text-[9px] px-1 text-muted truncate block pointer-events-none",style:{fontFamily:Vt},children:ku[P.type]});const Ci=P.type!=="sfx"&&!!P.speaker;if(!W)return d.jsx("div",{className:"absolute inset-0 flex items-center justify-center px-1 overflow-hidden pointer-events-none text-center break-words",style:{fontFamily:Vt,fontSize:Math.max(9,Math.min(Ge*.05,16)),fontWeight:((Fi=P.textStyle)==null?void 0:Fi.fontWeight)??400},"data-testid":`overlay-text-${P.id}`,"data-fonts-ready":"false",children:Ci?`${P.speaker}: ${P.text}`:P.text});const ft=uu(ce(Vt),P.text,Re,Ge,hu(P,V.height,Re,Ge));return d.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center px-1 overflow-hidden pointer-events-none text-center",style:{fontFamily:Vt},"data-testid":`overlay-text-${P.id}`,"data-fonts-ready":"true",children:[Ci&&d.jsx("span",{className:"font-bold text-[#3a3a3a] block",style:{fontSize:ft.speakerFontSize,lineHeight:1.2},children:P.speaker}),d.jsx("span",{className:"text-[#1a1a1a]",style:{fontSize:ft.fontSize,lineHeight:`${ft.lineHeight}px`,fontWeight:((En=P.textStyle)==null?void 0:En.fontWeight)??400},children:ft.lines.map((ln,Un)=>d.jsx("span",{className:"block",children:ln},Un))})]})})(),$e&&d.jsx("div",{onMouseDown:Vt=>{Vt.stopPropagation(),Mt(Vt,P.id,"resize")},className:"absolute bottom-0 right-0 w-2 h-2 bg-accent cursor-se-resize","data-testid":`resize-${P.id}`})]},P.id)})]}),d.jsxs("div",{className:"w-64 border-l border-border p-3 overflow-y-auto flex-shrink-0",children:[((ui=t.aiDraft)==null?void 0:ui.status)==="generated"&&d.jsxs("div",{className:"mb-3 rounded border border-accent/30 bg-accent/5 p-2 space-y-1","data-testid":"ai-draft-current-target",children:[d.jsx("p",{className:"text-[10px] font-bold uppercase tracking-[0.14em] text-accent",children:"AI draft ready"}),d.jsx("p",{className:"text-[11px] text-muted",children:"These first-pass overlays came from the cut script. Review and tune them here before exporting the final panel."})]}),Q.length>0&&d.jsxs("div",{className:"mb-3 space-y-1.5","data-testid":"script-insert-panel",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"From script"}),d.jsx("div",{className:"flex flex-col gap-1",children:Q.map(P=>d.jsxs("button",{onClick:()=>je(P),"data-testid":`script-insert-${P.key}`,title:`Add ${P.type} overlay with this text`,className:"text-left px-2 py-1 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5",children:[d.jsxs("span",{className:"font-medium text-accent",children:["+ ",ku[P.type]]})," ",d.jsxs("span",{className:"text-muted",children:[P.speaker?`${P.speaker}: `:"",P.text.length>32?`${P.text.slice(0,32)}…`:P.text]})]},P.key))})]}),Ae?d.jsxs("div",{className:"space-y-3",children:[d.jsx("p",{className:"text-xs font-medium text-foreground",children:ku[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:P=>be(Ae.id,{speaker:P.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:P=>be(Ae.id,{text:P.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:()=>be(Ae.id,Be(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"}),((Bt=Ae.textStyle)==null?void 0:Bt.mode)==="manual"?d.jsx("button",{type:"button",onClick:()=>be(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:()=>tt(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"})]}),((vt=Ae.textStyle)==null?void 0:vt.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:P=>be(Ae.id,{textStyle:{...Ae.textStyle,mode:"manual",fontScale:Math.max(.015,Math.min(.12,(parseFloat(P.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:P=>be(Ae.id,{textStyle:{...Ae.textStyle,mode:"manual",fontWeight:P.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:P=>be(Ae.id,{textStyle:{...Ae.textStyle,mode:"manual",lineHeightFactor:Math.max(.9,Math.min(2,parseFloat(P.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:P=>be(Ae.id,{textStyle:{...Ae.textStyle,mode:"manual",speakerScale:Math.max(.5,Math.min(1.5,parseFloat(P.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 P=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:CD.map(we=>d.jsx("button",{type:"button",onClick:()=>be(Ae.id,{tailAnchor:we.anchor}),className:"px-1.5 py-0.5 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5","data-testid":`inspector-tail-${we.key}`,children:we.label},we.key))}),d.jsxs("div",{className:"flex gap-2",children:[d.jsxs("label",{className:"flex items-center gap-1 text-[10px] font-mono text-muted",children:["x",d.jsx("input",{type:"number",step:"0.1",value:P.x,onChange:we=>be(Ae.id,{tailAnchor:{...P,x:parseFloat(we.target.value)||0}}),className:"w-14 px-1 py-0.5 text-[10px] border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-tail-x"})]}),d.jsxs("label",{className:"flex items-center gap-1 text-[10px] font-mono text-muted",children:["y",d.jsx("input",{type:"number",step:"0.1",value:P.y,onChange:we=>be(Ae.id,{tailAnchor:{...P,y:parseFloat(we.target.value)||0}}),className:"w-14 px-1 py-0.5 text-[10px] border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-tail-y"})]})]})]})})(),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:((((At=Ae.bubbleStyle)==null?void 0:At.paddingX)??.06)*100).toFixed(0),onChange:P=>be(Ae.id,{bubbleStyle:{...Ae.bubbleStyle,paddingX:Math.max(0,Math.min(.25,(parseFloat(P.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:((((Ze=Ae.bubbleStyle)==null?void 0:Ze.paddingY)??.08)*100).toFixed(0),onChange:P=>be(Ae.id,{bubbleStyle:{...Ae.bubbleStyle,paddingY:Math.max(0,Math.min(.25,(parseFloat(P.target.value)||8)/100))}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-padding-y"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Corner roundness (% short side)"}),d.jsx("input",{type:"number",step:"1",min:"0",max:"49",value:((((hi=Ae.bubbleStyle)==null?void 0:hi.cornerRadius)??.4)*100).toFixed(0),onChange:P=>be(Ae.id,{bubbleStyle:{...Ae.bubbleStyle,cornerRadius:Math.max(0,Math.min(.49,(parseFloat(P.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"?v.family:b.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:()=>{A?St(Ae.id):O(!0)},className:"w-full px-2 py-1 text-xs text-error border border-error/30 rounded hover:bg-error/5","data-testid":"delete-overlay",children:A?"Click again to delete":"Delete"})]}):d.jsx("p",{className:"text-xs text-muted","data-testid":"inspector-empty",children:"Select an overlay to inspect."})]})]})]})}const ED={wide:"Wide",medium:"Medium","close-up":"Close-up","extreme-close-up":"Extreme close-up"},ND="No speech bubbles, captions, sound effects, narration, or any text or lettering in the image.",jD="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 TD(e){var a;const t=ED[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(jD),s.push(ND),s.join(` +`).trim()}function AD(e,t){return`assets/${e}/cut-${String(t).padStart(2,"0")}-clean.webp`}function dy(e,t){const i=AD(t,e.id);return[`Generate the clean image for cut ${e.id}.`,"","Image description:",TD(e),"","How to hand it off:","- Produce the actual image — do not just describe it or return a prompt.",`- If your image tool can write a WebP or JPEG under 1MB, save it at ${i} and run "Sync clean images".`,'- If it only produces a PNG (e.g. built-in image generation saves to ~/.codex/generated_images), that is fine — do NOT convert or rename it yourself. Leave it there and import it into this cut with the OWS "Import from Codex" button, which converts the PNG automatically.',"- Clean image only: no text, speech bubbles, captions, sound effects, signage, watermark, or signature.","- Hold the style lock above — an illustrated comic/webtoon panel, NOT a photoreal photo, painterly concept art, or 3D render. If a result reads photorealistic, regenerate it as illustrated panel art.","- Do not letter or upload anything — final lettering and upload happen later in OWS."].join(` +`)}const YS=12e3,RD=5,DD=6e4,MD=6e4,BD=5;function LD(e,t){return e===429?!0:!!t&&/rate[\s-]?limit/i.test(t)}function OD(e,t=YS){return Math.min(t*2**e,DD)}const KS=e=>new Promise(t=>setTimeout(t,e));async function zD(e,t={}){var c;const i=t.sleep??KS,s=t.maxRetries??RD,a=t.baseDelayMs??YS;let o=0;for(;;){const h=await e();if(h.ok||!LD(h.status,h.errorMessage)||o>=s)return h;const p=OD(o,a);o+=1,(c=t.onWaiting)==null||c.call(t,{attempt:o,maxRetries:s,waitMs:p}),await i(p)}}function PD(e={}){const t=e.limit??BD,i=e.windowMs??MD,s=e.sleep??KS,a=e.now??(()=>Date.now()),o=[],c=()=>{const h=a()-i;for(;o.length&&o[0]<=h;)o.shift()};return async function(){var p;if(c(),o.length>=t){const f=o[0]+i-a();f>0&&((p=e.onWaiting)==null||p.call(e,{waitMs:f}),await s(f)),c()}o.push(a())}}const zp=1024*1024;function fy(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 ID(e){const t=[.9,.8,.7,.6];for(const s of t)try{const a=await fy(e,"image/webp",s);if(a.type!=="image/webp")break;if(a.size<=zp)return a}catch{break}const i=[.85,.7,.5];for(const s of i){const a=await fy(e,"image/jpeg",s);if(a.size<=zp)return a}throw new Error("Cannot compress image under 1MB — reduce overlay count or image size")}const HD=["image/webp","image/jpeg"];function VS(e){return HD.includes(e.type)&&e.size<=zp}async function UD(e){var i;if(typeof createImageBitmap!="function")throw new Error("This browser cannot decode the image for import");let t;try{t=await createImageBitmap(e)}catch{throw new Error("Could not read the selected image — pick a PNG, WebP, or JPEG file")}try{const s=document.createElement("canvas");s.width=t.width,s.height=t.height;const a=s.getContext("2d");if(!a)throw new Error("Could not process the image for import");return a.drawImage(t,0,0),s}finally{(i=t.close)==null||i.call(t)}}async function Ku(e){if(VS(e))return e;const t=await UD(e);return ID(t)}function $D(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 FD(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($D):[]}async function qD(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 WD(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 GD(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:e>=1024?`${Math.round(e/1024)} KB`:`${e} B`}function YD(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 KD({image:e,authFetch:t}){const i=WD(`/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 VD({authFetch:e,cutId:t,onImport:i,onClose:s}){const[a,o]=w.useState(null),[c,h]=w.useState(null),[p,f]=w.useState(null),[_,x]=w.useState("");w.useEffect(()=>{let E=!1;return(async()=>{const N=await FD(e);E||o(N)})(),()=>{E=!0}},[e]);const b=_.trim().toLowerCase(),v=w.useMemo(()=>a?b?a.filter(E=>E.name.toLowerCase().includes(b)):a:[],[a,b]),S=Date.now(),j=async E=>{h(null),f(E.token);try{const N=await qD(e,E);await i(N)}catch(N){h(N instanceof Error?N.message:"Could not import the generated image")}finally{f(null)}},R=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"})]}),R&&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."}),R&&v.length===0&&d.jsxs("p",{className:"text-[11px] text-muted","data-testid":`codex-picker-no-match-${t}`,children:["No generated images match “",_.trim(),"”."]}),R&&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(KD,{image:E,authFetch:e}),d.jsxs("div",{className:"min-w-0 flex-1",children:[d.jsxs("p",{className:"text-[11px] text-foreground",children:[YD(E.mtimeMs,S)," · ",GD(E.size)]}),d.jsx("p",{className:"truncate text-[10px] font-mono text-muted",title:E.name,children:E.name})]}),d.jsx("button",{onClick:()=>j(E),disabled:p!==null,"data-testid":`codex-import-${E.token}`,className:"px-2 py-1 text-[11px] border border-accent/30 text-accent rounded hover:bg-accent/5 disabled:opacity-50",children:p===E.token?"Importing…":"Import to this cut"})]},E.token))}),c&&d.jsx("p",{className:"text-[11px] text-error",children:c})]})}const XD={done:"✓",current:"▸",todo:"○"};function ZD({checklist:e,issues:t,onFinish:i,finishing:s,progressText:a,canFinish:o,markdownReady:c=!1,published:h=!1}){var E;if(!e||e.steps.length===0)return null;const p=GS(t),f=((E=e.steps.find(N=>N.key==="upload"))==null?void 0:E.status)==="done",_=f&&c&&!h,x=h||c?"done":f?"current":"todo",b=h?"done":_?"current":"todo",v=[...e.steps.filter(N=>N.key!=="publish"),{key:"assemble",label:"Episode sequence prepared",status:x,detail:null},{key:"ready",label:h?"Published to PlotLink":"Ready to publish",status:b,detail:null}],S=s?a||"Finishing…":h?"Published ✓":_?"Episode ready to publish":"Finish episode",j=v.filter(N=>N.status!=="done").length,R=p.reduce((N,I)=>N+I.lines.length,0);return d.jsxs("div",{className:"px-3 py-1.5 border-b border-border bg-surface/50 flex-shrink-0","data-testid":"finish-episode-panel",children:[d.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Finish episode"}),e.nextStep&&d.jsxs("span",{className:"min-w-0 flex-1 text-[10px] text-muted truncate","data-testid":"finish-next-step",children:["Next: ",e.nextStep]}),d.jsx("button",{onClick:i,disabled:s||!o,"data-testid":"finish-episode-btn",title:"Upload the exported final panels, then prepare the episode for publishing — picks up where it left off",className:"px-2.5 py-0.5 text-[11px] border border-accent/40 text-accent rounded hover:bg-accent/5 disabled:opacity-50",children:S})]}),d.jsxs("details",{className:"mt-1","data-testid":"finish-episode-details",children:[d.jsxs("summary",{className:"cursor-pointer select-none text-[10px] text-muted hover:text-foreground",children:[j===0?"Progress details":`${j} step${j===1?"":"s"} left`,R>0?` · ${R} blocker${R===1?"":"s"}`:""]}),d.jsxs("div",{className:"mt-1.5 space-y-1.5",children:[d.jsx("ol",{className:"flex flex-wrap gap-1.5",children:v.map(N=>d.jsxs("li",{"data-testid":`finish-step-${N.key}`,"data-status":N.status,className:`flex items-center gap-1 rounded border px-1.5 py-0.5 text-[10px] ${N.status==="current"?"border-accent/40 bg-accent/10 text-accent":N.status==="done"?"border-border bg-background/70 text-foreground":"border-border/70 bg-background/40 text-muted"}`,children:[d.jsx("span",{"aria-hidden":!0,children:XD[N.status]}),d.jsx("span",{children:N.label}),N.detail&&d.jsxs("span",{className:"text-muted",children:["· ",N.detail]})]},N.key))}),p.length>0&&d.jsx("div",{className:"space-y-1.5","data-testid":"finish-issues",children:p.map(N=>d.jsxs("div",{"data-testid":`finish-issue-group-${N.key}`,className:"text-[10px]",children:[d.jsx("p",{className:"font-medium text-amber-700",children:N.title}),d.jsx("ul",{className:"ml-3 list-disc text-muted",children:N.lines.map((I,te)=>d.jsx("li",{children:I},te))})]},N.key))})]})]})]})}function QD(e){return{planned:e.filter(t=>t.state==="planned").length,needsConversion:e.filter(t=>t.state==="needs-conversion").length,missing:e.filter(t=>t.state==="missing").length,cleanReady:e.filter(t=>t.state==="clean-ready").length,finalReady:e.filter(t=>t.state==="final-ready").length,uploaded:e.filter(t=>t.state==="uploaded").length}}function Ao(e){return(!!e.cleanImagePath||In(e))&&ym(e).length>0}function py(e){const t=new Date().toISOString();return{status:"generated",baseSig:ul(e),generatedAt:t,updatedAt:t}}function XS(e){return e.uploadedCid?"uploaded":e.finalImagePath||e.exportedAt?"lettered":e.cleanImagePath?"clean":In(e)?"text":"missing"}const my={muted:"text-muted",amber:"text-amber-700",green:"text-green-700",accent:"text-accent"},JD={muted:"bg-muted/40",amber:"bg-amber-500",green:"bg-green-600",accent:"bg-accent"};function eM(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"}:In(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 tM(e){var t,i;return e.uploadedCid||e.uploadedUrl?{label:"Complete",detail:"Final image uploaded",tone:"green"}:e.finalImagePath||e.exportedAt?{label:"Exported",detail:"Ready to upload",tone:"green"}:(((t=e.overlays)==null?void 0:t.length)??0)>0?((i=e.aiDraft)==null?void 0:i.status)==="generated"?{label:"Draft ready",detail:`${e.overlays.length} AI-drafted overlay${e.overlays.length===1?"":"s"} ready to review`,tone:"amber"}:{label:"User-edited",detail:`${e.overlays.length} overlay${e.overlays.length===1?"":"s"} adjusted and ready to review`,tone:"amber"}:Ao(e)?{label:"No draft",detail:"Draft with AI or place bubbles manually",tone:"muted"}:In(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 iM({cut:e,storyName:t,plotFile:i,expanded:s,onToggle:a,authFetch:o,onUpdated:c,onOpenEditor:h,detectedLocalClean:p,onSyncClean:f,syncing:_,onAiDraft:x,aiDrafting:b,staleMessages:v,onRepairStale:S,repairing:j,conversionPng:R,onConvert:E,converting:N,rowRef:I}){var Be,Le;const te=w.useRef(null),[F,D]=w.useState(!1),[ie,fe]=w.useState(null),[Se,H]=w.useState(!1),[ce,W]=w.useState(!1),[K,X]=w.useState(!1),[U,A]=w.useState(!1),O=XS(e),$=v.length>0,xe=!!R,T=w.useCallback(async()=>{R&&(A(!0),await E(e.id,R),A(!1),c())},[R,E,e.id,c]),M=w.useCallback(async je=>{D(!0),fe(null);try{let be=je;if(!VS(je))try{be=await Ku(je)}catch(We){return fe(We instanceof Error?We.message:"Could not import image"),!1}const tt=be.type==="image/jpeg"?"jpg":"webp",St=new FormData;St.append("file",new File([be],`clean.${tt}`,{type:be.type}));const ot=await o(`/api/stories/${t}/cuts/${i}/upload-clean/${e.id}`,{method:"POST",body:St});if(!ot.ok){const We=await ot.json();return fe(We.error||"Upload failed"),!1}return c(),!0}catch{return fe("Upload failed"),!1}finally{D(!1)}},[o,t,i,e.id,c]),G=eM(e,xe,$),C=e.cleanImagePath??R??null,V=((Be=e.overlays)==null?void 0:Be.length)??0,ne=!In(e)&&!!e.cleanImagePath&&!e.finalImagePath&&!e.uploadedCid&&!e.uploadedUrl&&!$&&!xe,ae=!$&&!xe&&!e.finalImagePath&&!e.uploadedCid&&!e.uploadedUrl&&Ao(e),Y=(((Le=e.overlays)==null?void 0:Le.length)??0)>0?"Re-draft with AI":"AI draft lettering",he=G.key==="convert"?{label:U?"Converting…":"Convert image",onClick:T,testid:`card-convert-${e.id}`}:G.key==="review"?{label:"Review cut",onClick:h,testid:`card-review-${e.id}`}:G.key==="text"?{label:"Add captions",onClick:h,testid:`card-letter-${e.id}`}:G.key==="needs-image"?{label:"Add artwork",onClick:a,testid:`card-addart-${e.id}`}:null,_e=tM(e);return d.jsxs("div",{ref:I,"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 ${JD[G.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 ${my[G.tone]}`,"data-testid":`cut-card-status-${e.id}`,children:G.label})]}),C?d.jsx(Bp,{storyName:t,assetPath:C,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:In(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] ${my[_e.tone]}`,"data-testid":`lettering-review-state-${e.id}`,children:[d.jsx("span",{className:"font-semibold",children:_e.label}),d.jsxs("span",{className:"text-muted",children:[" · ",_e.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:[ne?d.jsxs(d.Fragment,{children:[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"}),ae&&d.jsx("button",{onClick:x,disabled:b,"data-testid":`ai-draft-${e.id}`,className:"px-2.5 py-1 text-[11px] rounded border border-accent/40 text-accent hover:bg-accent/5 disabled:opacity-50",children:b?"Drafting…":Y})]}):he?d.jsx("button",{onClick:he.onClick,disabled:G.key==="convert"&&(U||N),"data-testid":he.testid,className:"px-2.5 py-1 text-[11px] font-medium rounded bg-accent text-white hover:bg-accent-dim disabled:opacity-50",children:he.label}):null,!ne&&!he&&ae&&d.jsx("button",{onClick:x,disabled:b,"data-testid":`ai-draft-${e.id}`,className:"px-2.5 py-1 text-[11px] rounded border border-accent/40 text-accent hover:bg-accent/5 disabled:opacity-50",children:b?"Drafting…":Y}),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:[xe&&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:T,disabled:U||N,"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:U?"Converting…":"Convert image"})]}),$&&!xe&&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:[v.map((je,be)=>d.jsx("p",{className:"text-[11px] text-error",children:je},be)),d.jsx("button",{onClick:S,disabled:j,"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:j?"Repairing…":"Clear stale path"})]}),!In(e)&&d.jsxs("div",{className:"mt-2 space-y-2",children:[d.jsx("button",{onClick:()=>{navigator.clipboard.writeText(dy(e,i)),H(!0),setTimeout(()=>H(!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:Se?"Copied!":"Copy Codex task"}),d.jsx("input",{ref:te,type:"file",accept:"image/webp,image/jpeg,image/png",className:"hidden",onChange:je=>{var tt;const be=(tt=je.target.files)==null?void 0:tt[0];be&&M(be),je.target.value=""}}),d.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[d.jsx("button",{onClick:()=>{var je;return(je=te.current)==null?void 0:je.click()},disabled:F,className:"px-3 py-1.5 text-xs border border-border rounded hover:border-accent hover:bg-accent/5 disabled:opacity-50",children:F?"Uploading...":e.cleanImagePath?"Replace clean image":"Upload clean image"}),d.jsx("button",{onClick:()=>X(je=>!je),disabled:F,"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:K?"Hide Codex images":"Import from Codex"})]}),K&&d.jsx(VD,{authFetch:o,cutId:e.id,onImport:async je=>{await M(je)&&X(!1)},onClose:()=>X(!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."}),O==="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(dy(e,i)),W(!0),setTimeout(()=>W(!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:ce?"Copied!":"Copy Codex task"})]}),O==="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"}),ie&&d.jsx("p",{className:"text-xs text-error mt-1",children:ie})]}),(e.cleanImagePath||e.narration||e.dialogue.length>0||In(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((je,be)=>d.jsxs("p",{children:[d.jsxs("span",{className:"font-medium",children:[je.speaker,":"]})," ",je.text]},be))}),e.narration&&d.jsx("p",{className:"text-xs text-muted italic",children:e.narration})]})]})}function gy({storyName:e,fileName:t,authFetch:i,language:s,uploadRetry:a,onCutsChanged:o,focusRequest:c,onFocusHandled:h,onFocusedLetteringModeChange:p,workspaceVisible:f=!1,onWorkspaceVisibleChange:_}){var pr,Lt,le;const[x,b]=w.useState(null),v=w.useRef(o);v.current=o;const S=w.useRef(h);S.current=h;const[j,R]=w.useState(!0),[E,N]=w.useState(null),[I,te]=w.useState(null),[F,D]=w.useState(null),[ie,fe]=w.useState(!1),[Se,H]=w.useState([]),[ce,W]=w.useState(!1),[K,X]=w.useState(""),[U,A]=w.useState({markdownReady:!1,published:!1}),[O,$]=w.useState(!1),[xe,T]=w.useState(!1),[M,G]=w.useState(!1),[C,V]=w.useState(null),[ne,ae]=w.useState(null),[Y,he]=w.useState(null),[_e,Be]=w.useState(!1),[Le,je]=w.useState(new Set),[be,tt]=w.useState(new Map),[St,ot]=w.useState(!1),[We,Mt]=w.useState(null),[He,xt]=w.useState(!1),[Ae,Kt]=w.useState(null),mi=w.useRef(new Map),wt=w.useRef(null),Qe=t.replace(/\.md$/,"");w.useEffect(()=>{var L;c&&wt.current!==c.seq&&(wt.current=c.seq,c.openEditor?D(c.cutId):(te(c.cutId),Kt(c.cutId)),(L=S.current)==null||L.call(S))},[c]),w.useEffect(()=>(p==null||p(F!==null),()=>p==null?void 0:p(!1)),[F,p]),w.useEffect(()=>{var oe;if(Ae==null)return;const L=mi.current.get(Ae);L&&((oe=L.scrollIntoView)==null||oe.call(L,{behavior:"smooth",block:"center"}),Kt(null))},[Ae,x]);const Q=w.useCallback(async()=>{var L;try{const oe=await i(`/api/stories/${e}/cuts/${Qe}`);if(oe.status===404){b(null);return}if(!oe.ok){const Me=await oe.json();N(Me.error||"Failed to load cuts");return}const Ee=await oe.json();b(Ee),N(null);try{const Me=await i(`/api/stories/${e}/${t}`);if(Me.ok){const Ne=await Me.json(),Pe=typeof(Ne==null?void 0:Ne.content)=="string"?Ne.content:"",qe=Array.isArray(Ee==null?void 0:Ee.cuts)?Ee.cuts:[],nt=Pe.length>0&&qS(Pe,qe).ready,Ve=(Ne==null?void 0:Ne.status)==="published"||(Ne==null?void 0:Ne.status)==="published-not-indexed";A({markdownReady:nt,published:Ve})}else A({markdownReady:!1,published:!1})}catch{A({markdownReady:!1,published:!1})}(L=v.current)==null||L.call(v)}catch{N("Failed to load cuts")}finally{R(!1)}},[i,e,Qe,t]),ge=w.useCallback(async L=>!!(await i(`/api/stories/${e}/cuts/${Qe}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(L)})).ok,[i,e,Qe]),Te=w.useCallback(async()=>{ot(!1);try{const L=await i(`/api/stories/${e}/cuts/${Qe}/detect-clean-images`);if(!L.ok)return;const oe=await L.json();je(new Set(Array.isArray(oe.detected)?oe.detected:[]));const Ee=new Map,Me=oe.stale;if(Array.isArray(Me))for(const Ne of Me){if(typeof(Ne==null?void 0:Ne.cutId)!="number"||typeof(Ne==null?void 0:Ne.message)!="string")continue;const Pe=Ee.get(Ne.cutId)??[];Pe.push(Ne.message),Ee.set(Ne.cutId,Pe)}tt(Ee),ot(!0)}catch{}},[i,e,Qe]),Ue=w.useCallback(async()=>{Mt(null);try{const L=await i(`/api/stories/${e}/cuts/${Qe}/asset-diagnostics`);if(!L.ok)return;const oe=await L.json();Mt(Array.isArray(oe.diagnostics)?oe.diagnostics:null)}catch{}},[i,e,Qe]),it=w.useCallback(async()=>{xt(!0);try{await Promise.all([Q(),Te(),Ue()])}finally{xt(!1)}},[Q,Te,Ue]),Wt=w.useCallback(async(L,oe={})=>{var Ne;if(!x)return!1;const Ee=x.cuts.find(Pe=>Pe.id===L);if(!Ee||!Ao(Ee)||(((Ne=Ee.overlays)==null?void 0:Ne.length)??0)>0&&!window.confirm("This cut already has overlays. Re-drafting with AI will replace the current draft overlays for this cut. Continue?"))return!1;const Me=oy(Ee);if(Me.length===0)return ae(`Cut ${Ee.id}: no script lines available to draft.`),!1;he(L),ae(null);try{const Pe={...x,cuts:x.cuts.map(nt=>nt.id===L?{...nt,overlays:Me,aiDraft:py(Me)}:nt)};return await ge(Pe)?(ae(`Cut ${Ee.id}: AI draft ready`),await Q(),oe.openEditor&&D(L),!0):(ae(`Cut ${Ee.id}: AI draft failed`),!1)}finally{he(null)}},[x,ge,Q]),ui=w.useCallback(async()=>{if(!x)return;const L=x.cuts.filter(oe=>{var Ee;return Ao(oe)&&(((Ee=oe.overlays)==null?void 0:Ee.length)??0)===0&&!oe.finalImagePath&&!oe.uploadedCid&&!oe.uploadedUrl});if(L.length===0){ae("No unlettered cuts need an AI draft");return}Be(!0),ae(null);try{const oe={...x,cuts:x.cuts.map(Me=>{if(!L.some(Pe=>Pe.id===Me.id))return Me;const Ne=oy(Me);return Ne.length>0?{...Me,overlays:Ne,aiDraft:py(Ne)}:Me})};if(!await ge(oe)){ae("AI draft failed");return}ae(`AI draft ready for ${L.length} cut${L.length===1?"":"s"}`),await Q()}finally{Be(!1)}},[x,ge,Q]),Bt=w.useCallback(async()=>{$(!0),ae(null),H([]);try{const L=await i(`/api/stories/${e}/cuts/${Qe}/sync-clean-images`,{method:"POST"}),oe=await L.json().catch(()=>({}));if(!L.ok)ae(oe.error||"Sync failed");else{const Ee=Array.isArray(oe.synced)?oe.synced.length:0,Me=Array.isArray(oe.cleared)?oe.cleared.length:0,Ne=Array.isArray(oe.rejected)?oe.rejected:[];Ne.length>0&&H(Ne.map(qe=>`Cut ${qe.cutId}: ${qe.reason}`));const Pe=[];Ee>0&&Pe.push(`Synced ${Ee}`),Me>0&&Pe.push(`Cleared ${Me} stale path${Me===1?"":"s"}`),ae(Pe.length>0?Pe.join(", "):"No new clean images"),await Q(),await Te(),await Ue()}}catch{ae("Sync failed")}$(!1)},[i,e,Qe,Q,Te,Ue]),vt=w.useCallback(async(L,oe)=>{try{const Ee=await i(OS(e,oe));if(!Ee.ok)return!1;const Me=await Ee.blob(),Ne=await Ku(new File([Me],"clean.png",{type:Me.type||"image/png"})),Pe=Ne.type==="image/jpeg"?"jpg":"webp",qe=new FormData;return qe.append("file",new File([Ne],`clean.${Pe}`,{type:Ne.type})),(await i(`/api/stories/${e}/cuts/${Qe}/upload-clean/${L}`,{method:"POST",body:qe})).ok}catch{return!1}},[i,e,Qe]),At=w.useCallback(async L=>{G(!0),V(null);let oe=0;const Ee=[];for(const Me of L)await vt(Me.cutId,Me.pngPath)?oe++:Ee.push(Me.cutId);await it(),G(!1),V(Ee.length===0?`Converted ${oe} image${oe===1?"":"s"} to WebP`:`Converted ${oe}; ${Ee.length} failed (Cut ${Ee.join(", ")}) — try Convert image on each`)},[vt,it]),Ze=w.useCallback(async()=>{var Ne;if(!x)return;W(!0),X(""),H([]);const L=x.cuts.filter(Pe=>Pe.finalImagePath&&!Pe.uploadedCid),oe=[],Ee=PD({sleep:a==null?void 0:a.sleep,onWaiting:({waitMs:Pe})=>X(`Upload limit reached — waiting ${Math.round(Pe/1e3)}s before continuing…`)});for(let Pe=0;Pe{const Jt=await i("/api/publish/upload-plot-image",{method:"POST",body:Nt});if(Jt.ok){const{cid:$n,url:gr}=await Jt.json();return{ok:!0,status:Jt.status,cid:$n,url:gr}}const qi=await Jt.json().catch(()=>({}));return{ok:!1,status:Jt.status,errorMessage:qi.error}},{...a,onWaiting:({attempt:Jt,maxRetries:qi,waitMs:$n})=>X(`Cut ${qe.id} rate-limited — waiting ${Math.round($n/1e3)}s before retry ${Jt}/${qi}...`)});if(!Gt.ok){oe.push(`Cut ${qe.id}: upload failed — ${Gt.errorMessage||"unknown"}`);continue}const{cid:Rt,url:ki}=Gt;(await i(`/api/stories/${e}/cuts/${Qe}/set-uploaded/${qe.id}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cid:Rt,url:ki})})).ok||oe.push(`Cut ${qe.id}: failed to record upload`)}catch(nt){oe.push(`Cut ${qe.id}: ${nt instanceof Error?nt.message:"failed"}`)}}if(oe.length>0){H(oe),W(!1),X(""),Q();return}X("Preparing episode for publishing…");const Me=await i(`/api/stories/${e}/cuts/${Qe}/generate-markdown`,{method:"POST"});if(Me.ok){const Pe=await Me.json();((Ne=Pe.warnings)==null?void 0:Ne.length)>0&&H(Pe.warnings)}W(!1),X(""),Q()},[x,i,e,Qe,a,Q]),hi=w.useCallback(async()=>{T(!0),ae(null);try{const L=await i(`/api/stories/${e}/cuts/${Qe}/repair-asset-paths`,{method:"POST"}),oe=await L.json().catch(()=>({}));if(!L.ok)ae(oe.error||"Repair failed");else{const Ee=Array.isArray(oe.cleared)?oe.cleared.length:0;ae(Ee>0?`Cleared ${Ee} stale path${Ee===1?"":"s"}`:"No stale paths to clear"),await Q(),await Te()}}catch{ae("Repair failed")}T(!1)},[i,e,Qe,Q,Te]),[P,we]=w.useState(!1),ze=w.useCallback(async(L,oe=!0)=>{if(x){we(!0);try{const Ee=x.cuts.reduce((nt,Ve)=>Math.max(nt,Ve.id),0)+1,Me={id:Ee,shotType:"wide",description:"Text panel",characters:[],dialogue:[],narration:"",sfx:"",cleanImagePath:null,finalImagePath:null,exportedAt:null,uploadedCid:null,uploadedUrl:null,overlays:[],kind:"text",background:"#101820",aspectRatio:"4:5"},Ne=[...x.cuts];Ne.splice(Math.max(0,Math.min(L,Ne.length)),0,Me);const Pe={...x,cuts:Ne},qe=await i(`/api/stories/${e}/cuts/${Qe}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(Pe)});if(qe.ok)oe?D(Ee):te(Ee),await Q();else{const nt=await qe.json().catch(()=>({}));ae(nt.error||"Could not add text panel")}}catch{ae("Could not add text panel")}we(!1)}},[x,i,e,Qe,Q]),Re=w.useCallback(()=>ze((x==null?void 0:x.cuts.length)??0,!0),[ze,x]);if(w.useEffect(()=>{Q(),Te(),Ue()},[Q,Te,Ue]),j)return d.jsx("div",{className:"p-4 text-sm text-muted",children:"Loading cuts..."});if(E)return d.jsxs("div",{className:"p-4 space-y-2","data-testid":"cuts-error",children:[d.jsx("p",{className:"text-sm text-error font-medium",children:"Invalid cuts file"}),d.jsx("p",{className:"text-xs text-error",children:E}),d.jsxs("p",{className:"text-xs text-muted",children:[Qe,".cuts.json must follow the OWS v1 schema. Ask Claude to regenerate it using the v1 cuts schema from the cartoon writing instructions."]}),d.jsx("button",{onClick:Q,className:"text-xs text-accent hover:text-accent-dim",children:"Retry"})]});if(!x||x.cuts.length===0)return d.jsxs("div",{className:"p-4 text-center space-y-1",children:[d.jsx("p",{className:"text-sm text-muted",children:"No cuts yet"}),d.jsx("p",{className:"text-xs text-muted",children:"Ask Claude to create a cut plan for this episode."})]});const Ge=F!==null?x.cuts.find(L=>L.id===F):null;if(Ge)return d.jsx(kD,{storyName:e,cut:Ge,plotFile:Qe,language:s,authFetch:i,targetLabel:In(Ge)?`Between-scene card ${Ge.id}`:`Cut ${String(Ge.id).padStart(2,"0")}`,returnOnSave:!0,workspaceVisible:f,onToggleWorkspaceVisible:_?()=>_(!f):void 0,onSave:async(L,oe)=>{const Ee={...x,cuts:x.cuts.map(Ne=>Ne.id===F?{...Ne,overlays:L,aiDraft:oe??Ne.aiDraft??null}:Ne)};if(!await ge(Ee))throw new Error("Failed to save overlays")},onExported:()=>Q(),onClose:()=>{D(null),Q()}});const $e=x.cuts.reduce((L,oe)=>{const Ee=XS(oe);return L[Ee]++,L},{missing:0,clean:0,lettered:0,uploaded:0,text:0}),ht=x.cuts.filter(L=>!In(L)).length,dt=x.cuts.filter(L=>$S(L)).map(L=>L.id),lt=sD({cuts:x.cuts,published:U.published}),Vt=((pr=lt.steps.find(L=>L.key==="upload"))==null?void 0:pr.status)==="done",Ci=x.cuts.some(L=>L.finalImagePath&&!L.uploadedCid)||Vt&&!U.markdownReady,ft=(We??[]).filter(L=>L.state==="needs-conversion"&&L.convertiblePng).map(L=>({cutId:L.cutId,pngPath:L.convertiblePng})),Fi=new Map(ft.map(L=>[L.cutId,L.pngPath])),En=(We??[]).filter(L=>L.state==="needs-conversion"&&L.issue).map(L=>L.issue),ln=t==="genesis.md"?"Genesis / Episode 1":`Episode ${parseInt(((Lt=Qe.match(/\d+/))==null?void 0:Lt[0])??"0",10)+1}`,Un=typeof x.title=="string"?x.title:null,on=x.cuts.filter(L=>!In(L)),gn={cuts:x.cuts.length,artwork:on.filter(L=>L.cleanImagePath||Fi.has(L.id)).length,converted:on.filter(L=>L.cleanImagePath&&/\.(webp|jpe?g)$/i.test(L.cleanImagePath)).length,lettered:x.cuts.filter(L=>{var oe;return(((oe=L.overlays)==null?void 0:oe.length)??0)>0||!!L.finalImagePath}).length,uploaded:x.cuts.filter(L=>L.uploadedCid||L.uploadedUrl).length},cn=x.cuts.filter(L=>{var oe;return Ao(L)&&(((oe=L.overlays)==null?void 0:oe.length)??0)===0&&!L.finalImagePath&&!L.uploadedCid&&!L.uploadedUrl}).length;return d.jsxs("div",{className:"h-full min-h-[22rem] flex flex-col overflow-hidden","data-testid":"cut-list-panel",children:[d.jsx("div",{className:"px-3 py-2 border-b border-border flex-shrink-0","data-testid":"cut-board-header",children:d.jsxs("div",{className:"flex items-start gap-3 justify-between",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:"font-serif text-foreground truncate",children:ln}),Un&&d.jsxs("span",{className:"text-muted truncate",children:["· ",Un]})]}),d.jsxs("div",{className:"mt-0.5 text-[10px] text-muted","data-testid":"cut-board-summary",children:[gn.cuts," cuts · ",gn.artwork," artwork found ·"," ",gn.converted," converted · ",gn.lettered," ","lettered · ",gn.uploaded," uploaded"]})]}),cn>0&&d.jsx("button",{onClick:ui,disabled:_e,"data-testid":"ai-draft-all-btn",className:"px-2.5 py-1 text-[11px] rounded border border-accent/40 text-accent hover:bg-accent/5 disabled:opacity-50",children:_e?"Drafting…":`AI draft all unlettered (${cn})`})]})}),d.jsxs("details",{className:"border-b border-border flex-shrink-0","data-testid":"cut-advanced",children:[d.jsx("summary",{className:"px-3 py-1.5 text-[10px] text-muted cursor-pointer hover:text-foreground",children:"Technical details"}),d.jsxs("div",{className:"px-3 py-2 flex flex-wrap items-center gap-2 text-[10px]",children:[d.jsxs("span",{className:"font-mono text-muted",children:[x.cuts.length," cuts"]}),$e.missing>0&&d.jsxs("span",{className:"text-muted",children:[$e.missing," missing"]}),$e.clean>0&&d.jsxs("span",{className:"text-green-700",children:[$e.clean," clean"]}),$e.lettered>0&&d.jsxs("span",{className:"text-amber-700",children:[$e.lettered," lettered"]}),$e.uploaded>0&&d.jsxs("span",{className:"text-green-700",children:[$e.uploaded," uploaded"]}),$e.text>0&&d.jsxs("span",{className:"text-accent",children:[$e.text," text ",$e.text===1?"panel":"panels"]}),d.jsx("button",{onClick:async()=>{fe(!0),H([]);try{const L=await i(`/api/stories/${e}/cuts/${Qe}/generate-markdown`,{method:"POST"});if(L.ok){const oe=await L.json();H(oe.warnings||[])}}catch{}fe(!1)},disabled:ie,className:"ml-auto px-2 py-0.5 border border-accent/30 text-accent rounded hover:bg-accent/5 disabled:opacity-50","data-testid":"generate-markdown-btn",title:"Build the publish-ready episode from the uploaded cut images",children:ie?"Preparing…":"Prepare episode for publish"}),d.jsx("button",{onClick:Re,disabled:P,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:P?"Adding…":"Add narration/text panel"}),d.jsx("button",{onClick:it,disabled:He,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:He?"Checking…":"Refresh assets"}),d.jsx("button",{onClick:Bt,disabled:O,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:O?"Syncing...":"Sync clean images"}),d.jsx("button",{onClick:Ze,disabled:ce||!(x!=null&&x.cuts.some(L=>L.finalImagePath&&!L.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:K||"Upload & Prepare for Publish"})]})]}),d.jsxs("details",{className:"px-3 py-1.5 border-b border-border bg-surface/40 flex-shrink-0","data-testid":"cartoon-workflow-help",children:[d.jsx("summary",{className:"cursor-pointer select-none text-[10px] text-muted hover:text-foreground",children:"Cut workflow help"}),d.jsxs("div",{className:"mt-1.5",children:[d.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 text-[10px] text-muted",children:[d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"1. Letter"}),d.jsx("span",{"aria-hidden":!0,children:"→"}),d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"2. Export"}),d.jsx("span",{"aria-hidden":!0,children:"→"}),d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"3. Upload"}),d.jsx("span",{"aria-hidden":!0,children:"→"}),d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"4. Prepare episode for publish"})]}),d.jsxs("div",{className:"mt-1 text-[10px] text-muted",children:["Use ",d.jsx("span",{className:"text-accent",children:"Add narration/text panel"})," ","for a narration or title card. It becomes a solid card exported as a final image."]})]})]}),dt.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:[dt.length===1?"Cut":"Cuts"," ",dt.join(", ")," ",dt.length===1?"was":"were"," lettered with an older speech-bubble style whose tail can show a visible seam. Re-export"," ",dt.length===1?"it":"them"," (open lettering → Export) and re-upload before publishing so the bubble tails are seamless."]}),St&&ht>0&&$e.missing===0&&be.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 ",ht," clean image",ht===1?"":"s"," ","present — clean-asset generation is complete. Ready for lettering in OWS."]})]}),ne&&d.jsx("div",{className:"px-3 py-1 border-b border-border text-[10px] text-muted flex-shrink-0","data-testid":"sync-result",children:ne}),ft.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:[ft.length," PNG image",ft.length===1?"":"s"," found"]}),d.jsx("button",{onClick:()=>At(ft),disabled:M,"data-testid":"convert-all-btn",className:"ml-auto px-2 py-0.5 border border-amber-500/50 text-amber-800 rounded hover:bg-amber-500/20 disabled:opacity-50",children:M?"Converting…":"Convert all to WebP"})]}),d.jsx("p",{className:"mt-1 text-[10px] text-muted",children:"PNG artwork is fine while drafting. Convert it before lettering/export so PlotLink can publish it safely."}),C&&d.jsx("p",{className:"mt-1 text-[10px] text-muted","data-testid":"convert-result",children:C}),En.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:En.map((L,oe)=>d.jsx("li",{children:L},oe))})]})]}),We&&We.length>0&&(()=>{const L=QD(We),oe=We.filter(Ee=>Ee.state==="missing");return d.jsxs("div",{className:"px-3 py-1.5 border-b border-border bg-surface/40 text-[10px] flex-shrink-0","data-testid":"asset-diagnostics",children:[d.jsxs("span",{className:"text-muted","data-testid":"asset-diag-summary",children:["Assets: ",L.uploaded," uploaded · ",L.finalReady," final ·"," ",L.cleanReady," clean · ",L.planned," planned",L.needsConversion>0?` · ${L.needsConversion} needs conversion`:"",L.missing>0?` · ${L.missing} missing`:""]}),oe.length>0&&d.jsx("ul",{className:"mt-1 ml-3 list-disc text-error","data-testid":"asset-diag-issues",children:oe.map(Ee=>d.jsx("li",{children:Ee.issue},Ee.cutId))})]})})(),d.jsx(ZD,{checklist:lt,issues:Se,onFinish:Ze,finishing:ce,progressText:K,canFinish:Ci,markdownReady:U.markdownReady,published:U.published}),d.jsxs("div",{className:"flex-1 min-h-56 overflow-y-auto p-3 space-y-3","data-testid":"lettering-review-board",children:[x.cuts.map((L,oe)=>{var Ee;return d.jsxs(w.Fragment,{children:[d.jsx(xy,{index:oe,beforeLabel:oe===0?"Episode opening":`After cut ${(Ee=x.cuts[oe-1])==null?void 0:Ee.id}`,afterLabel:`Before cut ${L.id}`,disabled:P,onAdd:()=>ze(oe)}),d.jsx(iM,{cut:L,storyName:e,plotFile:Qe,expanded:I===L.id,onToggle:()=>te(I===L.id?null:L.id),authFetch:i,onUpdated:()=>{Q(),Te(),Ue()},onOpenEditor:()=>D(L.id),detectedLocalClean:Le.has(L.id),onSyncClean:Bt,syncing:O,onAiDraft:()=>{Wt(L.id,{openEditor:!0})},aiDrafting:Y===L.id,staleMessages:be.get(L.id)??[],onRepairStale:hi,repairing:xe,conversionPng:Fi.get(L.id)??null,onConvert:vt,converting:M,rowRef:Me=>{Me?mi.current.set(L.id,Me):mi.current.delete(L.id)}})]},L.id)}),d.jsx(xy,{index:x.cuts.length,beforeLabel:`After cut ${(le=x.cuts[x.cuts.length-1])==null?void 0:le.id}`,afterLabel:"Episode ending",disabled:P,onAdd:()=>ze(x.cuts.length)})]})]})}function xy({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 Sm({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 nM({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(Sm,{coach:c,onAction:a,showEmptyState:o})}const rM=1024*1024,sM=["image/webp","image/jpeg"],aM="Cover: WebP or JPEG, max 1MB, 600×900 portrait recommended. Use clean cover art — avoid unreadable AI text or broken lettering.";function lM(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 _y(e){return e.size>rM?"Image exceeds 1MB limit":sM.includes(e.type)?null:"Only WebP and JPEG images are accepted"}async function oM(e,t,i){const s=new FormData;s.append("file",i);const a=await e("/api/publish/upload-cover",{method:"POST",body:s});if(!a.ok)return null;const{cid:o}=await a.json();return!o||!(await e("/api/publish/update-storyline",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storylineId:t,coverCid:o})})).ok?null:o}function Pp(e){const t=e.match(/^#\s+(.+)$/m),i=t?t[1].trim():"";return i||null}function cM(e){return e.replace(/[-_]+/g," ").replace(/\s+/g," ").trim().split(" ").map(t=>t&&t[0].toUpperCase()+t.slice(1)).join(" ")}function zo(e,t){const i=(e??"").trim().toLowerCase();if(!i)return!0;if(t==="genesis.md")return i==="genesis";const s=t.match(/^(plot-\d+)\.md$/);return s?i===s[1].toLowerCase()||/^plot-\d+$/.test(i):!1}function uM(e){const t=e.match(/^plot-(\d+)\.md$/);if(!t)return null;const i=t[1];return`Episode ${i.length<2?i.padStart(2,"0"):i}`}function Ip(e){const t=(e??"").trim();return!!(!t||/^(?:episode|ep|chapter|ch|part|pt|plot)\.?\s*[-–—:#]?\s*\d+$/i.test(t)||/^\d+$/.test(t)||/^plot[-_\s]?\d+$/i.test(t))}function wm(e){var s;const t=Pp(e.fileContent);if(t)return!Ip(t);const i=((s=e.episodeTitle)==null?void 0:s.trim())||null;return!!i&&!Ip(i)}function Cm(e){const{fileName:t,fileContent:i,storySlug:s,structureContent:a,contentType:o,episodeTitle:c}=e,h=Pp(i);if(t==="genesis.md"){const p=a?Pp(a):null;return(h??p??cM(s)).slice(0,60)}if(h)return h.slice(0,60);if(o==="cartoon"){const p=c==null?void 0:c.trim(),f=uM(t);return((p||f)??t.replace(/\.md$/,"")).slice(0,60)}return t.replace(/\.md$/,"").slice(0,60)}function hM(e){return!!(e!=null&&e.txHash)&&(e==null?void 0:e.plotIndex)!=null&&e.plotIndex>0}function dM(e){return hM(e)&&(e==null?void 0:e.status)!=="published-not-indexed"}function by(e,t,i){if(e[t]==="cartoon"&&!i)return"cartoon"}function fM(e,t,i){return!(e!=="cartoon"||t||!i||i.startsWith("_new_"))}function Lf(e,t,i){if(e)return t[e]||i.get(e)||"fiction"}function Of(e){if(!e)return null;const t=Number(e);return Number.isFinite(t)?(t/1e18).toFixed(6):null}function pM(e){return!!e&&e.ready===!1}function mM(e){const t=Of(e.requiredBalance)??Of(e.creationFee),i=Of(e.ethBalance);return e.hasEnoughEth===!1&&t&&i?`Insufficient ETH: need at least ${t} ETH to publish; current balance is ${i} ETH.`+(e.address?` Top up the OWS wallet (${e.address}) and try again.`:" Top up the OWS wallet and try again."):e.error||"Publish preflight failed — the OWS wallet isn't ready to publish."}const gM={...gl,attributes:{...gl.attributes,img:["src","alt","title"]}},xM="https://ipfs.filebase.io/ipfs/";function _M(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 bM(e){const t=_M(e),i=[];for(const a of t)a.url.startsWith(xM)||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 vM({storyName:e,fileName:t,authFetch:i,onPublish:s,publishingFile:a,walletAddress:o,contentType:c="fiction",language:h,genre:p,isNsfw:f,hasGenesis:_=!1,onViewProgress:x,onOpenFile:b,onViewPublish:v,focusedLetteringMode:S=!1,focusedLetteringWorkspaceVisible:j=!1,onFocusedLetteringModeChange:R,onFocusedLetteringWorkspaceVisibleChange:E}){const[N,I]=w.useState(null),[te,F]=w.useState(!1),[D,ie]=w.useState("preview"),[fe,Se]=w.useState("publish"),[H,ce]=w.useState("text"),[W,K]=w.useState(null),X=w.useCallback((re,ye)=>{ie("edit"),K(ke=>({cutId:re,openEditor:ye,seq:((ke==null?void 0:ke.seq)??0)+1}))},[]),[U,A]=w.useState(""),[O,$]=w.useState(!1),[xe,T]=w.useState(!1),[M,G]=w.useState(!1),[C,V]=w.useState(null),[ne,ae]=w.useState(""),[Y,he]=w.useState(""),[_e,Be]=w.useState(!1),[Le,je]=w.useState(null),[be,tt]=w.useState(0),[St,ot]=w.useState(0),[We,Mt]=w.useState(null),[He,xt]=w.useState(null),[Ae,Kt]=w.useState(null),[mi,wt]=w.useState(0),Qe=w.useRef(null),Q=w.useRef(!1),[ge,Te]=w.useState(!1),[Ue,it]=w.useState(dl[0]),[Wt,ui]=w.useState(ts[0]),[Bt,vt]=w.useState(!1),[At,Ze]=w.useState(null),[hi,P]=w.useState(null),[we,ze]=w.useState(!1),[Re,Ge]=w.useState(!1),[$e,ht]=w.useState(!1),[dt,lt]=w.useState(null),[Vt,Ci]=w.useState(!1),ft=w.useRef(null),Fi=w.useRef(null),[En,ln]=w.useState(!1),[Un,on]=w.useState(null),[gn,cn]=w.useState(null),[pr,Lt]=w.useState("unknown"),le=w.useRef(!1),[L,oe]=w.useState(!1),[Ee,Me]=w.useState(!1),[Ne,Pe]=w.useState(null),[qe,nt]=w.useState([]),[Ve,Et]=w.useState(null),Nt=w.useRef(null),Gt=w.useRef(null),Rt=w.useCallback(async()=>{if(!e||!t){I(null);return}const re=`${e}/${t}`,ye=Gt.current!==re;ye&&(Gt.current=re);try{const ke=await i(`/api/stories/${e}/${t}`);if(ke.ok){const Je=await ke.json();I(Je),(ye||!Q.current)&&(A(Je.content??""),ye&&(T(!1),Q.current=!1))}}catch{}},[e,t,i]);w.useEffect(()=>{F(!0),Rt().finally(()=>F(!1))},[Rt]),w.useEffect(()=>{if(!e||!t||D==="edit"&&xe)return;const re=setInterval(Rt,3e3);return()=>clearInterval(re)},[e,t,Rt,D,xe]);const[ki,mr]=w.useState(null),Jt=c==="cartoon"&&t==="genesis.md";w.useEffect(()=>{if(!Jt||!e){mr(null);return}let re=!1;return i(`/api/stories/${e}/cuts/genesis`).then(ye=>ye.ok?ye.json():null).then(ye=>{re||mr(ye?Op(ye.cuts||[]):null)}).catch(()=>{re||mr(null)}),()=>{re=!0}},[Jt,e,i]);const qi=c==="cartoon"&&!!t&&/^plot-\d+\.md$/.test(t);w.useEffect(()=>{if(!qi||!e||!t){je(null),tt(0),ot(0),Mt(null);return}let re=!1;const ye=t.replace(/\.md$/,"");return Mt(null),(async()=>{try{const[ke,Je]=await Promise.all([i(`/api/stories/${e}/${t}`),i(`/api/stories/${e}/cuts/${ye}`)]);if(re)return;if(!Je.ok){je("error"),tt(0),ot(0),Mt(null);return}const Pt=await Je.json(),Ni=Pt.cuts||[],Gn=ke.ok?(await ke.json()).content??"":"",or=WS(Gn,Ni);re||(je(or.stage),tt(or.awaitingCount),ot(or.totalCuts),Mt(Op(Ni)),Kt(typeof Pt.title=="string"?Pt.title:null))}catch{re||(je("error"),tt(0),ot(0),Mt(null))}})(),()=>{re=!0}},[qi,e,t,i,N==null?void 0:N.content,N==null?void 0:N.status,mi]),w.useEffect(()=>{if(!e){xt(null);return}let re=!1;return i(`/api/stories/${e}/structure.md`).then(ye=>ye.ok?ye.json():null).then(ye=>{re||xt((ye==null?void 0:ye.content)??null)}).catch(()=>{}),()=>{re=!0}},[e,i]),w.useEffect(()=>{if(!e)return;const re=Cu(p);let ye=re??"";if(!re&&He){const Je=He.match(/\*{0,2}genre\*{0,2}[:\s]+(.+)/i);Je&&(ye=Cu(Je[1].replace(/\*+/g,"").trim())??"")}ae(ye);let ke=h&&ts.find(Je=>Je.toLowerCase()===h.toLowerCase())||"";if(!ke&&He){const Je=He.match(/\*{0,2}language\*{0,2}[:\s]+(.+)/i);Je&&(ke=ts.find(Pt=>Pt.toLowerCase()===Je[1].replace(/\*+/g,"").trim().toLowerCase())||"")}he(ke),Be(f??!1)},[e,p,h,f,He]);const $n=w.useCallback(re=>{e&&i(`/api/stories/${e}/publish-metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(re)}).catch(()=>{})},[e,i]),gr=w.useCallback(async()=>{if(!(!e||!t)){$(!0);try{(await i(`/api/stories/${e}/${t}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:U})})).ok&&(T(!1),Q.current=!1,I(ye=>ye&&{...ye,content:U}))}catch{}$(!1)}},[e,t,i,U]),ei=w.useCallback(async()=>{if(!e||!t)return;const re=t.replace(/\.md$/,"");try{(await i(`/api/stories/${e}/cuts/${re}/generate-markdown`,{method:"POST"})).ok&&(await Rt(),wt(ke=>ke+1))}catch{}},[e,t,i,Rt]),Br=w.useCallback((re,ye)=>{if(re==="view-progress"){x==null||x();return}if(ye&&ye!==t){b==null||b(ye);return}switch(re){case"open-cuts":case"open-lettering":case"upload":case"refresh-assets":ie("edit"),ce("cuts");break;case"generate-markdown":ei();break;case"publish":ie("preview");break}},[t,x,b,ei]),Fn=w.useCallback(re=>{var Je;const ye=(Je=re.target.files)==null?void 0:Je[0];if(!ye)return;le.current=!0,on(null),cn(null);const ke=_y(ye);if(ke){Ze(null),P(Pt=>(Pt&&URL.revokeObjectURL(Pt),null)),ft.current&&(ft.current.value=""),lt(ke),Lt("invalid");return}Ze(ye),P(Pt=>(Pt&&URL.revokeObjectURL(Pt),URL.createObjectURL(ye))),lt(null),Lt("selected")},[]),ar=w.useCallback(async re=>{var ke;const ye=(ke=re.target.files)==null?void 0:ke[0];if(Fi.current&&(Fi.current.value=""),!(!ye||!e)){le.current=!0,on(null),ln(!0),lt(null);try{let Je;try{Je=await Ku(ye)}catch(vr){Ze(null),P(Yi=>(Yi&&URL.revokeObjectURL(Yi),null)),lt(vr instanceof Error?vr.message:"Could not import image");return}const Pt=Je.type==="image/jpeg"?"jpg":"webp",Ni=new File([Je],`cover.${Pt}`,{type:Je.type}),Gn=new FormData;Gn.append("file",Ni);const or=await i(`/api/stories/${e}/import-cover`,{method:"POST",body:Gn});if(!or.ok){const vr=await or.json().catch(()=>({}));lt(vr.error||"Cover import failed");return}Ze(Ni),P(vr=>(vr&&URL.revokeObjectURL(vr),URL.createObjectURL(Ni))),cn(null),Lt("selected"),lt(null)}catch{lt("Cover import failed")}finally{ln(!1)}}},[e,i]),Wi=w.useCallback(async re=>{if(re.size>1024*1024){Pe("Image exceeds 1MB limit");return}if(!["image/webp","image/jpeg"].includes(re.type)){Pe("Only WebP and JPEG images are accepted");return}Me(!0),Pe(null);try{const ke=new FormData;ke.append("file",re);const Je=await i("/api/publish/upload-plot-image",{method:"POST",body:ke});if(!Je.ok){const Ni=await Je.json();throw new Error(Ni.error||"Upload failed")}const Pt=await Je.json();nt(Ni=>[...Ni,{cid:Pt.cid,url:Pt.url}])}catch(ke){Pe(ke instanceof Error?ke.message:"Upload failed")}finally{Me(!1),Nt.current&&(Nt.current.value="")}},[i]),Ct=w.useCallback(re=>{var ke;const ye=(ke=re.target.files)==null?void 0:ke[0];ye&&Wi(ye)},[Wi]),qn=w.useCallback(async()=>{if(N!=null&&N.storylineId){ze(!0),lt(null),Ci(!1);try{let re;if(At){const ke=new FormData;ke.append("file",At);const Je=await i("/api/publish/upload-cover",{method:"POST",body:ke});if(!Je.ok){const Ni=await Je.json();throw new Error(Ni.error||"Cover upload failed")}re=(await Je.json()).cid}const ye=await i("/api/publish/update-storyline",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storylineId:N.storylineId,...re!==void 0&&{coverCid:re},genre:Ue,language:Wt,isNsfw:Bt})});if(!ye.ok){const ke=await ye.json();throw new Error(ke.error||"Update failed")}Ci(!0),Ze(null),re!==void 0&&(ht(!0),P(ke=>(ke&&URL.revokeObjectURL(ke),null)),Lt("unknown"),ft.current&&(ft.current.value="")),setTimeout(()=>Ci(!1),3e3)}catch(re){lt(re instanceof Error?re.message:"Update failed")}finally{ze(!1)}}},[N==null?void 0:N.storylineId,At,Ue,Wt,Bt,i]);w.useEffect(()=>{Te(!1),Ze(null),P(null),lt(null),Ci(!1),Ge(!1),oe(!1),nt([]),Pe(null),on(null),cn(null),Lt("unknown"),le.current=!1,ce("text")},[e,t]),w.useEffect(()=>{if(t!=="genesis.md"||!e||!N||N.storylineId||N.status==="published"||N.status==="published-not-indexed"||le.current)return;let re=!1;return(async()=>{try{const ye=await i(`/api/stories/${e}/cover-asset`);if(re||!ye.ok)return;const ke=await ye.json();if(re)return;if(!(ke!=null&&ke.found)){Lt("none");return}if(!ke.valid){cn(ke.error||"Detected cover asset is invalid and was not used"),Lt("invalid");return}const Je=await i(`/api/stories/${e}/asset/${ke.path.replace(/^assets\//,"")}`);if(re||!Je.ok)return;const Pt=await Je.blob(),Ni=new File([Pt],ke.path.split("/").pop()||"cover.webp",{type:ke.type});if(_y(Ni)||re||le.current)return;Ze(Ni),P(Gn=>(Gn&&URL.revokeObjectURL(Gn),URL.createObjectURL(Ni))),on(ke.path),Lt("detected")}catch{}})(),()=>{re=!0}},[e,t,N,N==null?void 0:N.status,N==null?void 0:N.storylineId,i]),w.useEffect(()=>{if(!ge||!(N!=null&&N.storylineId))return;Ge(!1);const re="https://plotlink.xyz";let ye=!1;return fetch(`${re}/api/storyline/${N.storylineId}`).then(ke=>ke.ok?ke.json():null).then(ke=>{if(!ye){if(!ke){lt("Could not load current story metadata");return}if(ke.genre){const Je=Cu(ke.genre);Je&&it(Je)}if(ke.language){const Je=ts.find(Pt=>Pt.toLowerCase()===ke.language.toLowerCase());Je&&ui(Je)}ke.isNsfw!==void 0&&vt(!!ke.isNsfw),ht(!!(ke.coverCid||ke.coverUrl||ke.cover)),Ge(!0)}}).catch(()=>{ye||lt("Could not load current story metadata")}),()=>{ye=!0}},[ge,N==null?void 0:N.storylineId]),w.useEffect(()=>{if(D!=="edit")return;const re=ye=>{(ye.metaKey||ye.ctrlKey)&&ye.key==="s"&&(ye.preventDefault(),gr())};return window.addEventListener("keydown",re),()=>window.removeEventListener("keydown",re)},[D,gr]),w.useEffect(()=>{if((N==null?void 0:N.status)!=="published-not-indexed"||!N.publishedAt)return;const re=new Date(N.publishedAt).getTime(),ye=300*1e3,ke=()=>{const Pt=Math.max(0,ye-(Date.now()-re));V(Pt)};ke();const Je=setInterval(ke,1e3);return()=>clearInterval(Je)},[N==null?void 0:N.status,N==null?void 0:N.publishedAt]);const ya=C!==null&&C<=0,Lr=C!==null&&C>0?`${Math.floor(C/6e4)}:${String(Math.floor(C%6e4/1e3)).padStart(2,"0")}`:null;if(!e||!t)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted",children:d.jsxs("div",{className:"text-center",children:[d.jsx("p",{className:"text-lg font-serif",children:"Select a file to preview"}),d.jsx("p",{className:"text-sm mt-1",children:"Click a story file in the sidebar"})]})});if(te&&!N)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted",children:"Loading..."});const xr=(D==="edit"?U:(N==null?void 0:N.content)??"").length,Ei=t==="genesis.md",gi=t?/^plot-\d+\.md$/.test(t):!1,Gi=c==="cartoon"&&gi,Nn=c==="cartoon"&&Ei,Or=Nn||Gi,jn=(N==null?void 0:N.status)==="published"||(N==null?void 0:N.status)==="published-not-indexed",Sa=S&&Or,yl=Nn?ki?ki.total:null:Gi?Le===null?null:St:null,_r=lD({fileName:t??"",contentType:c,hasGenesis:_,isPublished:jn,cutCount:yl,cutProgress:Nn?ki:null}),Go=(Nn||Gi)&&!jn,as=Go?Cm({fileName:t,fileContent:(N==null?void 0:N.content)??"",storySlug:e??"",structureContent:He,contentType:"cartoon",episodeTitle:Ae}):null,wa=!!as&&zo(as,t),Ca=Gi&&!jn&&!wm({fileContent:(N==null?void 0:N.content)??"",episodeTitle:Ae}),qs=Nn&&!jn?bm((N==null?void 0:N.content)??""):null,Yo=!!qs&&qs.blockers.length>0,ka="w-full max-w-[32rem] rounded-xl border px-3 py-3",lr={muted:"text-muted",accent:"text-accent",error:"text-error",success:"text-green-700"},Ea=re=>{if(!Nn)return null;const ye=lM({hasSelectedCover:!!At,invalid:pr==="invalid",attached:re});return d.jsxs("div",{className:"flex flex-col gap-0.5","data-testid":"cartoon-cover-status","data-state":ye.state,children:[d.jsx("span",{className:`text-[11px] font-medium ${lr[ye.tone]}`,children:ye.label}),d.jsxs("details",{className:"text-[10px] text-muted","data-testid":"cover-details",children:[d.jsx("summary",{className:"cursor-pointer select-none",children:"Cover tips"}),d.jsx("span",{className:"block mt-0.5","data-testid":"cartoon-cover-guidance",children:aM})]})]})},Ws=wa||Ca,ls=()=>{if(!Go||!as)return null;const re=Ei?"Story title":"Episode title";return d.jsxs("div",{className:"flex flex-col gap-0.5","data-testid":"publish-title-preview","data-raw":wa?"true":"false","data-blocked":Ws?"true":"false",children:[d.jsxs("span",{className:"text-[11px] text-foreground",children:[d.jsxs("span",{className:"font-medium",children:[re,":"]})," ",d.jsx("span",{className:Ws?"text-error font-medium":"text-foreground",children:as})]}),wa?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-raw-error",children:["This would publish as a raw filename."," ",Ei?"Add a real “# Title” heading to genesis.md":"Set a title in the cut plan (or add a “# Title” to the episode)"," ","before publishing."]}):Ca?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-episode-required",children:["“",as,"” is a generic placeholder, not a reader-facing title, so it can’t be published. Set a real episode title in the cut plan (or add a “# Title” to the episode) — e.g. “Episode 01 — The Couple Coupon” — before publishing."]}):null]})},os=()=>qs?d.jsxs("div",{className:"flex flex-col gap-1 rounded border border-border bg-surface/50 p-2","data-testid":"cartoon-genesis-readiness","data-blocked":Yo?"true":"false",children:[d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Story opening (Prologue)"}),d.jsx("span",{className:"text-[10px] text-muted","data-testid":"genesis-readiness-hint",children:"Genesis is the first thing readers see. Write it as the story opening/prologue, not a synopsis — set up the premise and stakes, then bridge into Episode 01."}),qs.blockers.map((re,ye)=>d.jsx("span",{className:"text-[10px] text-error","data-testid":"genesis-readiness-blocker",children:re},`b-${ye}`)),qs.warnings.map((re,ye)=>d.jsx("span",{className:"text-[10px] text-amber-600","data-testid":"genesis-readiness-warning",children:re},`w-${ye}`))]}):null,cs=Ei||gi?1e4:null,us=!jn&&cs!==null&&xr>cs,Ko=(N==null?void 0:N.content)??"",br=jn?{count:0,warnings:[]}:bM(Ko),Wn=d.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",style:{background:"var(--paper-bg)"},children:[d.jsx("textarea",{ref:Qe,value:U,onChange:re=>{A(re.target.value),T(!0),Q.current=!0},className:"flex-1 min-h-0 w-full resize-none px-4 py-3 text-sm leading-relaxed focus:outline-none",style:{fontFamily:'"Geist Mono", ui-monospace, monospace',background:"var(--paper-bg)",color:"var(--text)"},spellCheck:!1}),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:xe?"Unsaved changes":"No changes"}),d.jsx("button",{onClick:gr,disabled:!xe||O,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50 disabled:cursor-not-allowed",children:O?"Saving...":"Save"})]})]});return d.jsxs("div",{className:"h-full flex flex-col",children:[!Sa&&d.jsxs("div",{className:"border-b border-border",children:[d.jsxs("div",{className:"px-3 py-1.5 flex items-center justify-between",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs font-mono text-muted",children:[x&&d.jsx("button",{onClick:x,"data-testid":"view-progress-btn",className:"text-accent hover:underline font-sans",title:"Story progress overview",children:"← Progress"}),d.jsxs("span",{children:[e,"/",t]}),(N==null?void 0:N.status)==="published"&&d.jsx("span",{className:"text-green-700 font-medium",children:"Published"}),(N==null?void 0:N.status)==="published-not-indexed"&&d.jsx("span",{className:"text-amber-700 font-medium",title:N.indexError,children:"Published (not indexed)"}),(N==null?void 0:N.status)==="pending"&&d.jsx("span",{className:"text-amber-700 font-medium",children:"Pending"})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs("span",{className:`text-xs font-mono ${us?"text-error font-medium":"text-muted"}`,children:[xr.toLocaleString(),cs!==null?`/${cs.toLocaleString()}`:" chars"]}),us&&d.jsxs("span",{className:"text-error text-xs font-medium",children:[(xr-cs).toLocaleString()," over limit"]})]})]}),d.jsxs("div",{className:"flex px-3 gap-1",children:[d.jsx("button",{onClick:()=>ie("preview"),className:`px-3 py-1 text-xs font-medium border-b-2 transition-colors ${D==="preview"?"border-accent text-accent":"border-transparent text-muted hover:text-foreground"}`,children:"Preview"}),d.jsxs("button",{onClick:()=>ie("edit"),className:`px-3 py-1 text-xs font-medium border-b-2 transition-colors ${D==="edit"?"border-accent text-accent":"border-transparent text-muted hover:text-foreground"}`,children:["Edit",xe&&d.jsx("span",{className:"ml-1 text-amber-600",children:"*"})]})]})]}),!Sa&&c==="cartoon"&&e&&t&&d.jsx(nM,{storyName:e,fileName:t,authFetch:i,refreshKey:mi,onAction:Br,showEmptyState:!0}),D==="preview"?Gi?d.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",style:{background:"var(--paper-bg)"},children:[d.jsxs("div",{className:"flex gap-1 px-3 py-1 border-b border-border",children:[d.jsx("button",{"data-testid":"cartoon-mode-publish",onClick:()=>Se("publish"),className:`px-2 py-0.5 text-[11px] rounded ${fe==="publish"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Publish Preview"}),d.jsx("button",{"data-testid":"cartoon-mode-inspect",onClick:()=>Se("inspect"),className:`px-2 py-0.5 text-[11px] rounded ${fe==="inspect"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Cut Inspector"})]}),d.jsx("div",{className:"flex-1 min-h-0",children:fe==="publish"?d.jsx(hD,{content:(N==null?void 0:N.content)??"",stage:Le}):d.jsx(K3,{storyName:e,fileName:t,authFetch:i,onEditCut:X})})]}):d.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-6 py-4",style:{background:"var(--paper-bg)"},children:N!=null&&N.content?d.jsx("div",{className:"prose max-w-none",children:d.jsx(rS,{remarkPlugins:[aS,AS],rehypePlugins:[[BS,gM]],children:N.content})}):d.jsx("p",{className:"text-muted italic",children:"No content"})}):Gi?d.jsx("div",{className:"flex-1 min-h-[22rem] overflow-hidden",style:{background:"var(--paper-bg)"},children:d.jsx(gy,{storyName:e,fileName:t,authFetch:i,language:h,onCutsChanged:()=>wt(re=>re+1),focusRequest:W,onFocusHandled:()=>K(null),onFocusedLetteringModeChange:R,workspaceVisible:j,onWorkspaceVisibleChange:E})}):Nn?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:()=>ce("text"),className:`px-2 py-0.5 text-[11px] rounded ${H==="text"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Opening text"}),d.jsx("button",{"data-testid":"genesis-edit-mode-cuts",onClick:()=>ce("cuts"),className:`px-2 py-0.5 text-[11px] rounded ${H==="cuts"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Cuts"})]}),d.jsx("div",{className:"flex-1 min-h-0",children:H==="cuts"?d.jsx(gy,{storyName:e,fileName:t,authFetch:i,language:h,onCutsChanged:()=>wt(re=>re+1),focusRequest:W,onFocusHandled:()=>K(null),onFocusedLetteringModeChange:R,workspaceVisible:j,onWorkspaceVisibleChange:E}):Wn})]}):Wn,!Sa&&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:_r}):(N==null?void 0:N.status)==="published-not-indexed"?d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:"text-amber-700",children:"Published on-chain but not indexed on PlotLink"}),!ya&&d.jsx("button",{onClick:async()=>{if(!(!e||!t||!N.txHash)){G(!0);try{(await(await i("/api/publish/retry-index",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storyName:e,fileName:t,txHash:N.txHash,content:N.content,storylineId:N.storylineId})})).json()).ok&&(await i(`/api/stories/${e}/${t}/publish-status`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({txHash:N.txHash,storylineId:N.storylineId,contentCid:"",gasCost:""})}),Rt())}catch{}G(!1)}},disabled:M,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50",children:M?"Retrying...":`Retry Index${Lr?` (${Lr})`:""}`}),gi&&d.jsx("button",{onClick:()=>{!e||!t||!window.confirm(`This episode is already on-chain — try “Retry Index” first. + +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,ne,Y,_e)},disabled:!!a,"data-testid":"retry-publish-btn",className:"px-3 py-1 border border-border text-xs rounded hover:bg-surface disabled:opacity-50",children:a===t?"Publishing...":"Retry Publish"}),N.txHash&&d.jsx("a",{href:`https://basescan.org/tx/${N.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted underline",children:"BaseScan"})]}),d.jsx("p",{className:"text-muted text-xs",children:ya?gi?"Index window expired. Use Retry Publish to create a new on-chain tx.":"Index window expired. Contact support or re-publish manually.":gi?"Try Retry Index first (available for 5 min after publish). If that fails, Retry Publish creates a new on-chain tx.":"Retry Index is available for 5 min after publish."}),N.indexError&&d.jsx("p",{className:"text-error text-xs",children:N.indexError})]}):(N==null?void 0:N.status)==="published"?d.jsxs("div",{className:"flex flex-col gap-2",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:"text-green-700",children:"Published"}),N.storylineId&&d.jsx("a",{href:(()=>{var ke;const re=`https://plotlink.xyz/story/${N.storylineId}`;if(!gi)return re;const ye=N.plotIndex!=null&&N.plotIndex>0?N.plotIndex:parseInt(((ke=t==null?void 0:t.match(/^plot-(\d+)\.md$/))==null?void 0:ke[1])??"1");return`${re}/${ye}`})(),target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View on PlotLink"}),N.txHash&&d.jsx("a",{href:`https://basescan.org/tx/${N.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted underline",children:"BaseScan"}),Ei&&o&&N.storylineId&&(!N.authorAddress||N.authorAddress.toLowerCase()===o.toLowerCase())&&d.jsx("button",{onClick:()=>Te(re=>!re),className:"px-2 py-0.5 border border-border text-xs rounded hover:bg-surface",children:ge?"Close Edit":"Edit Story"})]}),ge&&Ei&&N.storylineId&&d.jsxs("div",{className:"border border-border rounded p-3 flex flex-col gap-3 bg-surface",children:[d.jsxs("div",{className:"flex flex-col gap-1.5",children:[d.jsx("span",{className:"text-xs font-medium text-foreground",children:"Cover Image"}),Ea($e),d.jsxs("div",{className:"flex items-start gap-3",children:[hi&&d.jsxs("div",{className:"relative",children:[d.jsx("img",{src:hi,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),d.jsx("button",{onClick:()=>{Ze(null),P(null),cn(null),Lt("unknown"),ft.current&&(ft.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:ft,type:"file",accept:"image/webp,image/jpeg",onChange:Fn,className:"text-xs","data-testid":"cover-input"}),d.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB, 600x900px recommended"})]})]})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("select",{value:Ue,onChange:re=>it(re.target.value),className:"px-2 py-1.5 text-xs border border-border rounded bg-surface text-foreground",children:dl.map(re=>d.jsx("option",{value:re,children:re},re))}),d.jsx("select",{value:Wt,onChange:re=>ui(re.target.value),className:"px-2 py-1.5 text-xs border border-border rounded bg-surface text-foreground",children:ts.map(re=>d.jsx("option",{value:re,children:re},re))})]}),d.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[d.jsx("input",{type:"checkbox",checked:Bt,onChange:re=>vt(re.target.checked),className:"rounded border-border"}),"This story contains adult content (18+)"]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{onClick:qn,disabled:we||!Re,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50",children:we?"Saving...":Re?"Save Changes":"Loading..."}),Vt&&d.jsx("span",{className:"text-green-700 text-xs",children:"Updated!"}),dt&&d.jsx("span",{className:"text-error text-xs",children:dt})]})]})]}):d.jsxs("div",{className:"flex flex-col gap-2",children:[Gi&&We&&We.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:We.total})]}),d.jsxs("span",{children:["Clean:"," ",d.jsxs("span",{className:"text-foreground font-medium",children:[We.withClean,"/",We.needClean]})]}),d.jsxs("span",{children:["Lettered:"," ",d.jsxs("span",{className:"text-foreground font-medium",children:[We.withText,"/",We.total]})]}),d.jsxs("span",{children:["Uploaded:"," ",d.jsxs("span",{className:"text-foreground font-medium",children:[We.uploaded,"/",We.total]})]}),x&&d.jsx("button",{onClick:x,className:"ml-auto text-accent hover:underline","data-testid":"status-view-progress",children:"View progress →"})]}),Nn&&ki&&d.jsxs("div",{className:"text-xs text-muted","data-testid":"genesis-cuts-summary",children:["Episode 1 (Genesis) cuts: ",ki.total," planned",ki.total>0&&d.jsxs(d.Fragment,{children:[" ","· ",ki.withClean," clean ·"," ",ki.withText," lettered ·"," ",ki.exported," exported ·"," ",ki.uploaded," uploaded"]})]}),(Nn||Gi)&&_r&&d.jsxs("div",{className:`${ka} flex flex-col gap-1 border-border bg-surface/50`,"data-testid":"cartoon-not-started",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"rounded-full bg-background px-2 py-0.5 text-[10px] font-medium uppercase tracking-[0.14em] text-muted",children:yl===0?"Not started":"Next step"}),d.jsx("span",{className:"text-xs font-medium text-foreground",children:Nn?"Genesis (Episode 1)":"Future episode"})]}),d.jsx("span",{className:"text-xs text-muted",children:_r})]}),gi&&!Gi&&D==="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:L,onChange:re=>oe(re.target.checked),className:"rounded border-border"}),"Add illustrations in the plot"]}),L&&d.jsxs("div",{className:"mt-2 flex flex-col gap-2",children:[d.jsxs("div",{className:"border-2 border-dashed border-border rounded p-3 flex flex-col items-center gap-1.5 cursor-pointer hover:border-accent transition-colors",onClick:()=>{var re;return(re=Nt.current)==null?void 0:re.click()},onDragOver:re=>{re.preventDefault(),re.stopPropagation()},onDrop:re=>{var ke;re.preventDefault(),re.stopPropagation();const ye=(ke=re.dataTransfer.files)==null?void 0:ke[0];ye&&Wi(ye)},children:[d.jsx("input",{ref:Nt,type:"file",accept:"image/webp,image/jpeg",onChange:Ct,className:"hidden"}),d.jsx("span",{className:"text-xs text-muted",children:Ee?"Uploading...":"Drop image here or click to browse"}),d.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB"})]}),Ne&&d.jsx("span",{className:"text-error text-xs",children:Ne}),qe.map((re,ye)=>d.jsxs("div",{className:"border border-border rounded p-2 flex flex-col gap-1 bg-surface",children:[d.jsx("span",{className:"text-xs text-green-700",children:"Image uploaded! Copy the markdown below and paste it where you want the illustration to appear in your plot:"}),d.jsxs("div",{className:"flex items-center gap-1.5",children:[d.jsxs("code",{className:"flex-1 text-xs bg-background px-2 py-1 rounded font-mono break-all",children:["![Scene description](",re.url,")"]}),d.jsx("button",{onClick:()=>{navigator.clipboard.writeText(`![Scene description](${re.url})`),Et(ye),setTimeout(()=>Et(null),2e3)},className:"px-2 py-1 text-xs border border-border rounded hover:bg-surface shrink-0",children:Ve===ye?"Copied!":"Copy"})]})]},re.cid))]})]}),Ei&&c!=="cartoon"&&!(D==="edit"&&H==="cuts")&&d.jsxs("div",{className:"flex flex-col gap-1.5","data-testid":"prepublish-cover",children:[d.jsxs("span",{className:"text-xs font-medium text-foreground",children:["Cover Image"," ",d.jsx("span",{className:"text-muted font-normal",children:"(optional)"})]}),Ea(!1),d.jsxs("div",{className:"flex items-start gap-3",children:[hi&&d.jsxs("div",{className:"relative",children:[d.jsx("img",{src:hi,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),d.jsx("button",{onClick:()=>{le.current=!0,on(null),cn(null),Lt("unknown"),Ze(null),P(re=>(re&&URL.revokeObjectURL(re),null)),ft.current&&(ft.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:ft,type:"file",accept:"image/webp,image/jpeg",onChange:Fn,className:"text-xs","data-testid":"prepublish-cover-input"}),d.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB, 600x900px recommended"}),d.jsx("input",{ref:Fi,type:"file",accept:"image/png,image/webp,image/jpeg",onChange:ar,className:"hidden","data-testid":"prepublish-cover-import-input"}),d.jsx("button",{type:"button",onClick:()=>{var re;return(re=Fi.current)==null?void 0:re.click()},disabled:En,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:En?"Importing…":"Import generated image (PNG ok)"}),At&&d.jsx("span",{className:"text-green-700 text-xs","data-testid":"prepublish-cover-will-upload",children:"This cover will be uploaded as the PlotLink storyline cover when you publish."}),Un&&d.jsxs("span",{className:"text-accent text-xs","data-testid":"prepublish-cover-detected",children:["Auto-detected generated cover ",Un," — pick a file to override."]}),gn&&d.jsxs("span",{className:"text-amber-700 text-xs","data-testid":"prepublish-cover-detected-warning",children:[gn," Use “Import generated image” below to convert/compress it, or pick a file."]}),c==="cartoon"&&pr==="none"&&!At&&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."]}),dt&&d.jsx("span",{className:"text-error text-xs","data-testid":"prepublish-cover-error",children:dt})]})]})]}),!Or&&ls(),!Or&&os(),!Or&&d.jsxs("div",{className:"flex items-center gap-2",children:[Ei&&c!=="cartoon"&&d.jsxs(d.Fragment,{children:[d.jsxs("select",{value:ne,"data-testid":"publish-genre-select",onChange:re=>{ae(re.target.value),re.target.value&&$n({genre:re.target.value})},className:`px-2 py-1.5 text-xs border rounded bg-surface text-foreground ${ne?"border-border":"border-amber-500"}`,children:[!ne&&d.jsx("option",{value:"",disabled:!0,children:"Needs metadata — select genre"}),dl.map(re=>d.jsx("option",{value:re,children:re},re))]}),d.jsxs("select",{value:Y,"data-testid":"publish-language-select",onChange:re=>{he(re.target.value),re.target.value&&$n({language:re.target.value})},className:`px-2 py-1.5 text-xs border rounded bg-surface text-foreground ${Y?"border-border":"border-amber-500"}`,children:[!Y&&d.jsx("option",{value:"",disabled:!0,children:"Needs metadata — select language"}),ts.map(re=>d.jsx("option",{value:re,children:re},re))]})]}),d.jsx("button",{onClick:async()=>{if(!e||!t)return;if(br.count>0){const ye=`This plot contains ${br.count} illustration(s). Content is immutable after publishing — image references cannot be changed or removed. + +Please verify illustrations appear correctly in Preview before continuing. + +Publish now?`;if(!window.confirm(ye))return}const re=Ei?At:null;re?await(s==null?void 0:s(e,t,ne,Y,_e,re))&&(le.current=!0,on(null),cn(null),Lt("unknown"),Ze(null),P(ke=>(ke&&URL.revokeObjectURL(ke),null)),ft.current&&(ft.current.value="")):s==null||s(e,t,ne,Y,_e)},disabled:!!a||us||Ws||Yo||Ei&&(!ne||!Y)||Gi&&Le!=="ready",className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim disabled:opacity-50 disabled:cursor-not-allowed",children:a===t?"Publishing...":"Publish to PlotLink"}),Ei&&c==="cartoon"&&(!ne||!Y)&&d.jsx("span",{className:"text-amber-600 text-xs","data-testid":"cartoon-metadata-needs-story-info",children:"Set the genre and language in Story Info before publishing"}),Ei&&c!=="cartoon"&&!ne&&d.jsx("span",{className:"text-amber-600 text-xs","data-testid":"genre-needs-metadata",children:"Needs metadata — choose a genre before publishing"}),Ei&&c!=="cartoon"&&ne&&!Y&&d.jsx("span",{className:"text-amber-600 text-xs","data-testid":"language-needs-metadata",children:"Needs metadata — choose a language before publishing"}),us&&d.jsx("span",{className:"text-error text-xs",children:"Reduce content to publish"}),Gi&&Le==="error"&&d.jsx("span",{className:"text-error text-xs","data-testid":"publish-disabled-reason",children:"Fix the issues below before publishing"}),Gi&&Le==="planning"&&d.jsx("span",{className:"text-muted text-xs","data-testid":"publish-disabled-reason",children:"Prepare the episode for publish to continue"}),Gi&&Le==="awaiting-upload"&&d.jsxs("span",{className:"text-muted text-xs","data-testid":"publish-disabled-reason",children:["Upload all final images, then “Prepare episode for publish” — ",be," of ",St," ","still need an uploaded image"]})]}),Or&&d.jsx("button",{onClick:()=>v==null?void 0:v(),"data-testid":"cartoon-review-publish",className:"self-start rounded border border-accent/40 px-3 py-1 text-xs text-accent hover:bg-accent/5 transition-colors",children:"Review publish checklist →"}),br.warnings.length>0&&d.jsx("div",{className:"flex flex-col gap-0.5",children:br.warnings.map((re,ye)=>d.jsx("span",{className:"text-amber-600 text-xs",children:re},ye))}),Ei&&c!=="cartoon"&&d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[d.jsx("input",{type:"checkbox",checked:_e,onChange:re=>{Be(re.target.checked),$n({isNsfw:re.target.checked})},className:"rounded border-border"}),"This story contains adult content (18+)"]}),_e&&d.jsx("span",{className:"text-xs text-amber-600",children:"Adult content will be hidden from the default browse view."})]})]})})]})}function yM(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 ZS(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 SM({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:yM(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 QS({progress:e,onCoachAction:t,onOpenStoryInfo:i}){return ZS(e)==="story-info"?d.jsx(SM,{progress:e,onOpenStoryInfo:i}):d.jsx(Sm,{coach:e.coach??null,showEmptyState:!0,onAction:t})}function wM({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(CM(x)?x:null)}).catch(()=>{_||c(null)}),()=>{_=!0}},[e,t,i]),o===void 0?null:o?d.jsx(QS,{progress:o,onCoachAction:s,onOpenStoryInfo:a}):d.jsx(Sm,{coach:null,showEmptyState:!0,onAction:s})}function CM(e){return!!e&&!!e.metadata&&!!e.setup&&Array.isArray(e.episodes)}function kM({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(DM,{progress:o,storyName:e,onOpenFile:i,onOpenStoryInfo:s}):d.jsx(LM,{progress:o,storyName:e,onOpenFile:i})}function mu({label:e,value:t,tone:i="muted"}){const s=i==="ok"?"text-green-700":i==="warn"?"text-amber-700":"text-muted";return d.jsxs("span",{className:"text-[11px]",children:[d.jsxs("span",{className:"text-muted",children:[e,": "]}),d.jsx("span",{className:`font-medium ${s}`,children:t})]})}function JS({progress:e}){const t=e.contentType==="cartoon",i=e.cover==="present"?"ok":e.cover==="invalid"?"warn":"muted";return d.jsxs("div",{className:"px-4 py-3 border-b border-border",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("h2",{className:"text-base font-serif text-foreground truncate",children:e.metadata.title||e.name}),d.jsx("span",{className:`rounded px-1.5 py-0.5 text-[10px] font-medium ${t?"bg-accent/10 text-accent":"bg-surface text-muted"}`,children:t?"Cartoon":"Fiction"})]}),d.jsxs("div",{className:"mt-1.5 flex flex-wrap gap-x-3 gap-y-1",children:[d.jsx(mu,{label:"Language",value:e.metadata.language||"Needs metadata",tone:e.metadata.language?"muted":"warn"}),d.jsx(mu,{label:"Genre",value:e.metadata.genre||"Needs metadata",tone:e.metadata.genre?"muted":"warn"}),e.metadata.isNsfw!=null&&d.jsx(mu,{label:"Adult",value:e.metadata.isNsfw?"Yes (18+)":"No"}),t&&d.jsx(mu,{label:"Cover",value:e.cover==="present"?"Ready":e.cover==="invalid"?"Invalid":"Missing",tone:i})]})]})}const e1={published:"✓",done:"●",current:"◉","needs-action":"●","not-started":"○"},Ou={published:"text-green-700",done:"text-green-700",current:"text-accent","needs-action":"text-amber-700","not-started":"text-muted"},t1={published:"Published",done:"Complete",current:"Current","needs-action":"Needs action","not-started":"Not started"},EM={done:"✓",current:"◓",todo:"○"},NM={done:"text-green-700",current:"text-accent",todo:"text-muted"};function i1({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:`${NM[e.status]} flex-shrink-0`,"aria-hidden":!0,children:EM[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 vy({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 ${Ou[i]}`,"aria-hidden":!0,children:e1[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 ${Ou[i]} flex-shrink-0`,children:t1[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(i1,{item:h},p))})]})}function jM(e,t){return e.published?"published":t?"current":e.state==="placeholder"?"not-started":(e.state==="blocked","needs-action")}function TM(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(AM(a));return s}function AM(e){return{label:e.label,status:e.status,detail:e.detail}}const RM={file:"genesis.md",label:"Episode 1 / Genesis",kind:"genesis",title:null,state:"placeholder",summary:"",published:!1,checklist:[],cuts:null};function DM({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=ZS(e),_=d.jsx(QS,{progress:e,onOpenStoryInfo:s,onCoachAction:(E,N)=>{E!=="view-progress"&&N&&i(t,N)}}),x=[{label:"Public title",status:a.title?"done":"todo",detail:a.title??null},{label:"Language",status:a.language?"done":"todo",detail:a.language??null},{label:"Genre",status:a.genre?"done":"todo",detail:a.genre??null},{label:"Cover image",status:c?"done":"todo",detail:e.cover==="invalid"?"Invalid — re-import":c?null:"Missing"}],b=f==="story-info"?"current":p?"needs-action":"done",v=o?"done":f==="whitepaper"?"current":"not-started",S=e.episodes.find(E=>E.kind==="genesis")??null,j=e.episodes.filter(E=>E.kind==="plot");let R=0;return d.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"story-progress-panel",children:[d.jsx(JS,{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(vy,{index:++R,title:"Define Story Info",status:b,items:x}),d.jsx(vy,{index:++R,title:"Story Whitepaper",status:v,fileName:"structure.md",openFile:o?()=>i(t,"structure.md"):void 0,items:[{label:"Planning document",status:o?"done":"todo",detail:o?null:"Not written yet"}]}),S?d.jsx(zf,{index:++R,ep:S,isActive:f===S.file,storyName:t,onOpenFile:i}):d.jsx(zf,{index:++R,ep:RM,isActive:f==="genesis.md",openingDone:!1,canOpen:!1,storyName:t,onOpenFile:i}),j.map(E=>d.jsx(zf,{index:++R,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 zf({index:e,ep:t,isActive:i,storyName:s,onOpenFile:a,openingDone:o=!0,canOpen:c=!0}){const h=jM(t,i),p=TM(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 ${Ou[h]}`,"aria-hidden":!0,children:e1[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 ${Ou[h]} flex-shrink-0`,children:t1[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(i1,{item:x},b))})]})}const MM={published:"✓",ready:"●","in-progress":"◐",planning:"○",placeholder:"○",blocked:"✕",draft:"○"},yy={published:"text-green-700",ready:"text-green-700","in-progress":"text-accent",planning:"text-accent",placeholder:"text-muted",blocked:"text-error",draft:"text-muted"},BM={published:"Published",ready:"Ready","in-progress":"In progress",planning:"Planning",placeholder:"Not started",blocked:"Needs fixes",draft:"Draft"};function LM({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(JS,{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(Sy,{done:e.setup.hasStructure,label:"Story bible (structure.md)",onClick:e.setup.hasStructure?()=>i(t,"structure.md"):void 0}),d.jsx(Sy,{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 ${yy[o.state]}`,"aria-hidden":!0,children:MM[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 ${yy[o.state]}`,children:BM[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 Sy({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 OM=[{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 zM({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:OM.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 PM({storyName:e,authFetch:t,onSaved:i}){const[s,a]=w.useState(!0),[o,c]=w.useState(!1),[h,p]=w.useState(""),[f,_]=w.useState(""),[x,b]=w.useState(""),[v,S]=w.useState(""),[j,R]=w.useState(!1),[E,N]=w.useState("cartoon"),[I,te]=w.useState("unknown"),[F,D]=w.useState(!1),[ie,fe]=w.useState(!1),[Se,H]=w.useState(null),[ce,W]=w.useState(!1),[K,X]=w.useState(null),[U,A]=w.useState(!1),O=w.useRef(null);w.useEffect(()=>{let C=!1;return a(!0),c(!1),fe(!1),H(null),(async()=>{try{const[V,ne]=await Promise.all([t(`/api/stories/${e}`),t(`/api/stories/${e}/progress`)]);if(!V.ok){C||(c(!0),a(!1));return}const ae=await V.json(),Y=ne.ok?await ne.json().catch(()=>null):null;if(C)return;p(ae.title??""),_(ae.description??""),b(Cu(ae.genre)??""),S(ae.language&&ts.find(he=>he.toLowerCase()===ae.language.toLowerCase())||""),R(!!ae.isNsfw),N(ae.contentType==="fiction"?"fiction":"cartoon"),te((Y==null?void 0:Y.cover)??"unknown"),a(!1)}catch{C||(c(!0),a(!1))}})(),()=>{C=!0}},[e,t]);const $=w.useCallback(async()=>{D(!0),fe(!1),H(null);const C={title:h.trim(),description:f.trim(),genre:x,language:v,isNsfw:j};try{const V=await t(`/api/stories/${e}/publish-metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(C)});if(V.ok)fe(!0),i==null||i({genre:x,language:v,isNsfw:j});else{const ne=await V.json().catch(()=>({}));H(ne.error||"Could not save story info.")}}catch{H("Could not save story info.")}D(!1)},[e,t,h,f,x,v,j,i]),xe=w.useCallback(async C=>{var ne;const V=(ne=C.target.files)==null?void 0:ne[0];if(O.current&&(O.current.value=""),!!V){W(!0),H(null);try{let ae;try{ae=await Ku(V)}catch(Le){H(Le instanceof Error?Le.message:"Could not import image");return}const Y=ae.type==="image/jpeg"?"jpg":"webp",he=new File([ae],`cover.${Y}`,{type:ae.type}),_e=new FormData;_e.append("file",he);const Be=await t(`/api/stories/${e}/import-cover`,{method:"POST",body:_e});if(!Be.ok){const Le=await Be.json().catch(()=>({}));H(Le.error||"Cover import failed.");return}te("present"),X(Le=>(Le&&URL.revokeObjectURL(Le),URL.createObjectURL(he)))}catch{H("Cover import failed.")}finally{W(!1)}}},[e,t]),T=w.useCallback(()=>{var V;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.`;(V=navigator.clipboard)==null||V.writeText(C).then(()=>{A(!0)}).catch(()=>{})},[h,e]);if(s)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"story-info-loading",children:"Loading story info…"});if(o)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load story info."});const M=I==="present"?"Cover set":I==="invalid"?"Invalid cover — re-import a WebP/JPEG under 1MB":"Missing cover",G=I==="present"?"text-green-700":I==="invalid"?"text-amber-700":"text-muted";return d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"story-info-page",children:[d.jsx("h2",{className:"text-base font-serif text-foreground",children:"Story Info"}),d.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"These details appear on PlotLink when the story is published."}),d.jsxs("div",{className:"mt-4 flex flex-col gap-4 max-w-xl",children:[d.jsxs("label",{className:"flex flex-col gap-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Public title"}),d.jsx("input",{type:"text",value:h,onChange:C=>{p(C.target.value),fe(!1)},"data-testid":"story-info-title",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none"})]}),d.jsxs("label",{className:"flex flex-col gap-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Short description"}),d.jsx("textarea",{value:f,onChange:C=>{_(C.target.value),fe(!1)},rows:3,"data-testid":"story-info-description",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none resize-y"})]}),d.jsxs("div",{className:"flex flex-wrap gap-4",children:[d.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Genre"}),d.jsxs("select",{value:x,onChange:C=>{b(C.target.value),fe(!1)},"data-testid":"story-info-genre",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none",children:[d.jsx("option",{value:"",children:"Needs metadata"}),dl.map(C=>d.jsx("option",{value:C,children:C},C))]})]}),d.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Language"}),d.jsxs("select",{value:v,onChange:C=>{S(C.target.value),fe(!1)},"data-testid":"story-info-language",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none",children:[d.jsx("option",{value:"",children:"Needs metadata"}),ts.map(C=>d.jsx("option",{value:C,children:C},C))]})]}),d.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Content type"}),d.jsx("span",{className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-surface text-muted","data-testid":"story-info-content-type",title:"Content type is locked after creation.",children:E==="cartoon"?"Cartoon · locked":"Fiction · locked"})]})]}),d.jsxs("div",{className:"flex flex-col gap-1.5",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Cover image"}),d.jsxs("div",{className:"flex items-start gap-3",children:[K&&d.jsx("img",{src:K,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 ${G}`,"data-testid":"story-info-cover-status",children:M}),d.jsx("span",{className:"text-[10px] text-muted",children:"WebP or JPEG, max 1MB, 600×900 recommended."}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{type:"button",onClick:()=>{var C;return(C=O.current)==null?void 0:C.click()},disabled:ce,"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:ce?"Importing…":"Import cover"}),d.jsx("button",{type:"button",onClick:T,"data-testid":"story-info-cover-prompt",className:"rounded border border-border px-2.5 py-1 text-[11px] text-muted hover:border-accent hover:text-accent transition-colors",children:U?"Copied!":"Ask agent for cover prompt"})]}),d.jsx("input",{ref:O,type:"file",accept:"image/*",onChange:xe,className:"hidden"})]})]})]}),d.jsxs("label",{className:"flex items-center gap-2",children:[d.jsx("input",{type:"checkbox",checked:j,onChange:C=>{R(C.target.checked),fe(!1)},"data-testid":"story-info-nsfw"}),d.jsx("span",{className:"text-xs text-foreground",children:"This story contains adult content (18+)"})]}),d.jsxs("div",{className:"flex items-center gap-3",children:[d.jsx("button",{type:"button",onClick:$,disabled:F,"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:F?"Saving…":"Save Story Info"}),ie&&d.jsx("span",{className:"text-[11px] text-green-700","data-testid":"story-info-saved",children:"Saved"}),Se&&d.jsx("span",{className:"text-[11px] text-error","data-testid":"story-info-error",children:Se})]})]})]})}function IM({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 HM({storyName:e,authFetch:t,onOpenFile:i,onOpenStoryInfo:s,onPublish:a,publishingFile:o,genre:c,language:h,isNsfw:p,refreshKey:f=0}){var We,Mt;const[_,x]=w.useState(null),[b,v]=w.useState(!0),[S,j]=w.useState(!1),[R,E]=w.useState(null),[N,I]=w.useState(null),[te,F]=w.useState(null),[D,ie]=w.useState(null),[fe,Se]=w.useState(null),H=async()=>{try{const He=await t(`/api/stories/${e}/cover-asset`),xt=He.ok?await He.json():null;if(!(xt!=null&&xt.found)||!xt.valid||!xt.path)return null;const Ae=await t(`/api/stories/${e}/asset/${String(xt.path).replace(/^assets\//,"")}`);if(!Ae.ok)return null;const Kt=await Ae.blob();return new File([Kt],String(xt.path).split("/").pop()||"cover.webp",{type:xt.type||Kt.type})}catch{return null}};w.useEffect(()=>{let He=!1;return(async()=>{v(!0),j(!1);try{const Ae=await t(`/api/stories/${e}/progress`),Kt=Ae.ok?await Ae.json():null;if(He)return;!Kt||!Array.isArray(Kt.episodes)?(j(!0),x(null)):x(Kt),v(!1)}catch{He||(j(!0),x(null),v(!1))}})(),()=>{He=!0}},[e,t,f]);const ce=((Mt=(We=_==null?void 0:_.episodes)==null?void 0:We.find(He=>!He.published))==null?void 0:Mt.file)??null,W=ce==="genesis.md",K=JSON.stringify([ce??"",f]),[X,U]=w.useState(null);if(X!==K&&(U(K),I(null),F(null),ie(null),Se(null)),w.useEffect(()=>{if(!ce)return;let He=!1;const xt=ce.replace(/\.md$/,"");return(async()=>{var Ae;try{const Kt=[t(`/api/stories/${e}/${ce}`),t(`/api/stories/${e}/cuts/${xt}`)];W&&Kt.push(t(`/api/stories/${e}/structure.md`));const[mi,wt,Qe]=await Promise.all(Kt);if(He)return;if(I(mi.ok?(await mi.json()).content??"":""),wt.ok){const Q=await wt.json();if(He)return;F(Array.isArray(Q.cuts)?Q.cuts:[]),ie(typeof Q.title=="string"?Q.title:null)}else F(null),ie(null);Se(W&&Qe&&Qe.ok?((Ae=await Qe.json())==null?void 0:Ae.content)??null:null)}catch{He||(I(""),F(null),ie(null),Se(null))}})(),()=>{He=!0}},[ce,W,e,t,f]),b)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"publish-page-loading",children:"Loading publish readiness…"});if(S||!_)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load publish readiness."});const A=_.episodes.find(He=>!He.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 O=A.cuts,$=_.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.total>0&&O.withText===O.total?"done":"todo",detail:O?`${O.withText} / ${O.total}`: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:$?"done":"todo",detail:$?null:"recommended before publishing"},{label:"Publish to PlotLink",status:A.published?"done":"todo"}],T=A.state==="ready",M=A.state==="blocked",G=A.file==="genesis.md",C=!G||!!c&&!!h,V=!!o&&o===A.file,ne=N!==null,ae=ne?Cm({fileName:A.file,fileContent:N??"",storySlug:e,structureContent:fe,contentType:"cartoon",episodeTitle:D}):null,Y=!!ae&&zo(ae,A.file),he=!G&&ne&&!wm({fileContent:N??"",episodeTitle:D}),_e=Y||he,Be=G&&ne?bm(N??""):null,Le=!!Be&&Be.blockers.length>0,je=!G&&ne&&te!==null?WS(N??"",te):null,be=je&&je.stage==="error"?je.issues:[],St=T&&C&&(ne&&(G||te!==null))&&!_e&&!Le&&!V&&!!a,ot=async()=>{if(!(!St||!a)){E(null);try{const He=G?await H():null;await a(e,A.file,c??"",h??"",!!p,He)}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:xe.map((He,xt)=>d.jsxs("li",{className:"flex items-baseline gap-2 text-xs","data-testid":"publish-check","data-status":He.status,children:[d.jsx("span",{className:`flex-shrink-0 ${He.status==="done"?"text-green-700":"text-muted"}`,"aria-hidden":!0,children:He.status==="done"?"✓":"○"}),d.jsx("span",{className:He.status==="done"?"text-foreground":"text-muted",children:He.label}),He.detail&&d.jsxs("span",{className:"text-muted",children:["· ",He.detail]})]},xt))}),ae&&d.jsxs("div",{className:"mt-4 flex flex-col gap-0.5 max-w-xl","data-testid":"publish-title-preview","data-raw":Y?"true":"false","data-blocked":_e?"true":"false",children:[d.jsxs("span",{className:"text-[11px] text-foreground",children:[d.jsxs("span",{className:"font-medium",children:[G?"Story title":"Episode title",":"]})," ",d.jsx("span",{className:_e?"text-error font-medium":"text-foreground",children:ae})]}),Y?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-raw-error",children:["This would publish as a raw filename. ",G?"Add a real “# Title” heading to genesis.md":"Set a title in the cut plan (or add a “# Title” to the episode)"," before publishing."]}):he?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-episode-required",children:["“",ae,"” 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]}),Be&&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."}),Be.blockers.map((He,xt)=>d.jsx("span",{className:"text-[10px] text-error","data-testid":"genesis-readiness-blocker",children:He},`b-${xt}`)),Be.warnings.map((He,xt)=>d.jsx("span",{className:"text-[10px] text-amber-600","data-testid":"genesis-readiness-warning",children:He},`w-${xt}`))]}),be.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"})]}),GS(be).map(He=>d.jsx("div",{className:"rounded-lg border border-error/15 bg-background/70 px-2.5 py-2","data-testid":`cartoon-issue-group-${He.key}`,children:d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:He.title})},He.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:be.map((He,xt)=>d.jsx("li",{className:"font-mono break-words",children:He},xt))})]})]}),d.jsxs("div",{className:"mt-4 flex flex-col gap-2 max-w-xl",children:[!$&&d.jsx("button",{onClick:s,"data-testid":"publish-add-cover",className:"self-start rounded border border-border px-3 py-1.5 text-xs text-foreground hover:border-accent hover:text-accent transition-colors",children:"Add a cover image (Story Info)"}),G&&!C&&d.jsx("button",{onClick:s,"data-testid":"publish-set-metadata",className:"self-start rounded border border-border px-3 py-1.5 text-xs text-foreground hover:border-accent hover:text-accent transition-colors",children:"Set genre & language (Story Info)"}),!T&&d.jsxs("button",{onClick:()=>i(e,A.file),"data-testid":"publish-open-episode",className:"self-start rounded border border-accent/40 px-3 py-1.5 text-xs text-accent hover:bg-accent/5 transition-colors",children:["Open ",A.label," to finish ",M?"and fix issues":"(letter / export / upload)"]}),d.jsx("button",{onClick:ot,disabled:!St,"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:St?void 0:"Finish the remaining steps above first",children:V?"Publishing…":`Publish ${A.label} to PlotLink`}),T?C?_e||Le?d.jsx("p",{className:"text-[11px] text-error","data-testid":"publish-title-blocked-reason",children:Le?"Fix the Story opening issues above before publishing.":"Set a real reader-facing title above before publishing."}):null:d.jsx("p",{className:"text-[11px] text-amber-700","data-testid":"publish-needs-metadata",children:"Set the genre and language in Story Info before publishing."}):d.jsx("p",{className:"text-[11px] text-muted","data-testid":"publish-blocked-reason",children:M?`Not publishable yet — ${A.summary.toLowerCase()}. Open the episode to fix the flagged cuts.`:`Not ready yet — ${A.summary.toLowerCase()}.`}),R&&d.jsx("p",{className:"text-[11px] text-error","data-testid":"publish-error",children:R})]}),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 UM(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 $M(e){var o;const{fileName:t,detail:i,plotIndex:s}=e;if(!i)return{ok:!0,checked:!1};if(t==="genesis.md"){const c=(o=i.title??i.name)==null?void 0:o.trim();return c?zo(c,"genesis.md")?{ok:!1,checked:!0,publicTitle:c,reason:`PlotLink indexed the storyline title as “${c}”, a raw filename rather than the reader-facing title.`}:{ok:!0,checked:!0,publicTitle:c}:{ok:!0,checked:!1}}const a=UM(i,s);return a?zo(a,t)||Ip(a)?{ok:!1,checked:!0,publicTitle:a,reason:`PlotLink indexed the episode title as “${a}”, a generic placeholder rather than a reader-facing episode title.`}:{ok:!0,checked:!0,publicTitle:a}:{ok:!0,checked:!1}}function FM(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 n1="plotlink-panel-ratio",qM=.6,wy=300,Pf=224,If=6;function WM(){try{const e=localStorage.getItem(n1);if(e){const t=parseFloat(e);if(t>0&&t<1)return t}}catch{}return qM}function Cy(e,t){if(t<=0)return e;const i=wy/t,s=1-wy/t;return i>=s?.5:Math.min(s,Math.max(i,e))}function GM({token:e,authFetch:t}){const[i,s]=w.useState(null),[a,o]=w.useState(null),[c,h]=w.useState(null),[p,f]=w.useState(null),[_,x]=w.useState(0),[b,v]=w.useState(""),[S,j]=w.useState(null),[R,E]=w.useState(null),[N,I]=w.useState(WM),[te,F]=w.useState([]),[D,ie]=w.useState(!1),[fe,Se]=w.useState(""),[H,ce]=w.useState(""),[W,K]=w.useState(""),[X,U]=w.useState("English"),[A,O]=w.useState("normal"),[$,xe]=w.useState("claude"),[T,M]=w.useState(null),[G,C]=w.useState(!1),[V,ne]=w.useState({}),[ae,Y]=w.useState({}),[he,_e]=w.useState(new Set),[Be,Le]=w.useState(new Set),[je,be]=w.useState({}),[tt,St]=w.useState({}),[ot,We]=w.useState({}),[Mt,He]=w.useState({}),[xt,Ae]=w.useState({}),[Kt,mi]=w.useState({}),[wt,Qe]=w.useState(!1),[Q,ge]=w.useState(!0),Te=w.useRef(new Map),Ue=w.useRef(new Map),it=w.useRef(new Map),Wt=w.useRef(new Map),ui=w.useRef(new Set),Bt=w.useRef(null),vt=w.useRef(null),At=w.useRef(!1);w.useEffect(()=>{t("/api/wallet").then(le=>le.ok?le.json():null).then(le=>{le!=null&&le.address&&E(le.address)}).catch(()=>{})},[t]),w.useEffect(()=>{t("/api/agent/readiness").then(le=>le.ok?le.json():null).then(le=>{le&&M(le)}).catch(()=>{})},[t]),w.useEffect(()=>{try{localStorage.setItem(n1,String(N))}catch{}},[N]),w.useEffect(()=>{const le=()=>{if(!vt.current)return;const L=vt.current.getBoundingClientRect().width-Pf-If;I(oe=>Cy(oe,L))};return window.addEventListener("resize",le),le(),()=>window.removeEventListener("resize",le)},[]);const Ze=w.useCallback(()=>{Se(""),ce(""),K(""),O("normal"),xe("claude"),ie(!0)},[]),hi=w.useCallback(async(le,L,oe,Ee)=>{const Me=fe.trim();if(!Me)return;const Ne=le==="cartoon"?"codex":Ee;try{const Pe=await t("/api/stories/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:Me,description:H.trim()||void 0,language:L,genre:W||void 0,contentType:le,agentMode:oe,agentProvider:Ne})});if(!Pe.ok)return;const qe=await Pe.json();ie(!1),be(nt=>({...nt,[qe.name]:le})),St(nt=>({...nt,[qe.name]:L})),W&&We(nt=>({...nt,[qe.name]:W})),Y(nt=>({...nt,[qe.name]:Ne})),oe==="bypass"&&ne(nt=>({...nt,[qe.name]:!0})),s(qe.name),o(null)}catch{}},[t,fe,H,W]);w.useEffect(()=>{if(te.length===0)return;const le=setInterval(async()=>{try{const L=await t("/api/stories");if(!L.ok)return;const oe=await L.json(),Ee=new Set(oe.stories.filter(Me=>Me.name!=="_example").map(Me=>Me.name));for(const Me of Ee)if(!ui.current.has(Me)&&te.length>0){const Ne=te[0],Pe=Te.current.get(Ne)||"fiction",qe=Ue.current.get(Ne)||"English",nt=it.current.get(Ne)||"normal",Ve=Wt.current.get(Ne)||"claude";let Et=!1;Bt.current&&(Et=await Bt.current(Ne,Me,{contentType:Pe,language:qe,agentMode:nt,agentProvider:Ve}).catch(()=>!1)),Et&&(F(Nt=>Nt.slice(1)),Te.current.delete(Ne),Ue.current.delete(Ne),it.current.delete(Ne),Wt.current.delete(Ne),nt==="bypass"&&ne(Nt=>{const Gt={...Nt,[Me]:!0};return delete Gt[Ne],Gt}),Y(Nt=>{const Gt={...Nt,[Me]:Ve};return delete Gt[Ne],Gt}),t(`/api/stories/${Me}/metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentType:Pe,language:qe,agentMode:nt,agentProvider:Ve})}).catch(()=>{})),s(Me),o(null)}ui.current=Ee}catch{}},3e3);return()=>clearInterval(le)},[t,te]),w.useEffect(()=>{t("/api/stories").then(le=>{if(le.ok)return le.json()}).then(le=>{le!=null&&le.stories&&(ui.current=new Set(le.stories.filter(L=>L.name!=="_example").map(L=>L.name)))}).catch(()=>{})},[t]);const P=w.useCallback((le,L)=>{s(le),o(L),h(null)},[]),we=w.useRef(null),ze=w.useCallback(async le=>{var L,oe,Ee,Me;we.current=le,s(le),o(null),h(null);try{const Ne=await t(`/api/stories/${le}`);if(Ne.ok&&we.current===le){const Pe=await Ne.json();if(Pe.contentType==="cartoon")return;const qe=Pe.files||[],Ve=((L=qe.map(Et=>{var Nt;return{file:Et.file,num:(Nt=Et.file.match(/^plot-(\d+)\.md$/))==null?void 0:Nt[1]}}).filter(Et=>Et.num!=null).sort((Et,Nt)=>parseInt(Nt.num)-parseInt(Et.num))[0])==null?void 0:L.file)??((oe=qe.find(Et=>Et.file==="genesis.md"))==null?void 0:oe.file)??((Ee=qe.find(Et=>Et.file==="structure.md"))==null?void 0:Ee.file)??((Me=qe[0])==null?void 0:Me.file);Ve&&we.current===le&&o(Ve)}}catch{}},[t]),Re=w.useCallback(le=>{le.preventDefault(),At.current=!0,document.body.style.cursor="col-resize",document.body.style.userSelect="none";const L=Ee=>{if(!At.current||!vt.current)return;const Me=vt.current.getBoundingClientRect(),Ne=Me.width-Pf-If,Pe=Ee.clientX-Me.left-Pf;I(Cy(Pe/Ne,Ne))},oe=()=>{At.current=!1,document.body.style.cursor="",document.body.style.userSelect="",window.removeEventListener("mousemove",L),window.removeEventListener("mouseup",oe)};window.addEventListener("mousemove",L),window.addEventListener("mouseup",oe)},[]),Ge=w.useCallback(async(le,L,oe,Ee,Me,Ne)=>{var Ve;f(L),v("Reading file..."),j(null);let Pe=!1,qe=null,nt=!1;try{const Et=await t(`/api/stories/${le}/${L}`);if(!Et.ok)throw new Error("Failed to read file");const Nt=await Et.json(),Gt=je[le];let Rt=null,ki=null;if(L==="genesis.md")try{const ei=await t(`/api/stories/${le}/structure.md`);ei.ok&&(Rt=(await ei.json()).content??null)}catch{}else if(Gt==="cartoon"&&L.match(/^plot-\d+\.md$/))try{const ei=await t(`/api/stories/${le}/cuts/${L.replace(/\.md$/,"")}`);ei.ok&&(ki=(await ei.json()).title??null)}catch{}const mr=Cm({fileName:L,fileContent:Nt.content,storySlug:le,structureContent:Rt,contentType:Gt,episodeTitle:ki});if(Gt==="cartoon"&&zo(mr,L))return v(L==="genesis.md"?"Add a real “# Title” heading to genesis.md before publishing — it would otherwise publish as a raw filename.":"Set an episode title in the cut plan before publishing — it would otherwise publish as a raw filename."),setTimeout(()=>{f(null),v("")},6e3),!1;if(Gt==="cartoon"&&L.match(/^plot-\d+\.md$/)&&!wm({fileContent:Nt.content,episodeTitle:ki}))return v("Set a real episode title in the cut plan (or add a “# Title” to the episode) before publishing — a generic “Episode NN” placeholder can’t be published."),setTimeout(()=>{f(null),v("")},6e3),!1;if(Gt==="cartoon"&&L==="genesis.md"){const ei=bm(Nt.content).blockers;if(ei.length>0)return v(`Genesis is the reader-facing Story opening — fix it before publishing: ${ei[0]}`),setTimeout(()=>{f(null),v("")},6e3),!1}let Jt;if(L.match(/^plot-\d+\.md$/)){if(dM(Nt)){v("Already published on PlotLink — republishing would create a duplicate chapter. Open it on PlotLink instead (or use Retry Index if it isn't showing yet)."),setTimeout(()=>{f(null),v("")},6e3);return}try{const ei=await t(`/api/stories/${le}`);if(ei.ok){const Fn=(await ei.json()).files.find(ar=>ar.file==="genesis.md"&&ar.storylineId);Jt=Fn==null?void 0:Fn.storylineId}}catch{}if(!Jt)return v("Error: Publish genesis first to create the storyline"),setTimeout(()=>{f(null),v("")},3e3),!1}v("Checking wallet balance...");try{const ei=await t("/api/publish/preflight");if(ei.ok){const Br=await ei.json();if(pM(Br))return j(mM(Br)),f(null),v(""),!1}}catch{}v("Publishing...");const qi=await t("/api/publish/file",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storyName:le,fileName:L,title:mr,content:Nt.content,genre:oe,language:Ee,isNsfw:Me,storylineId:Jt,...by(je,le,Jt)?{contentType:by(je,le,Jt)}:{}})});if(!qi.ok){const ei=await qi.json();throw new Error(ei.error||"Publish failed")}const $n=(Ve=qi.body)==null?void 0:Ve.getReader(),gr=new TextDecoder;if($n)for(;;){const{done:ei,value:Br}=await $n.read();if(ei)break;const ar=gr.decode(Br).split(` +`).filter(Wi=>Wi.startsWith("data: "));for(const Wi of ar)try{const Ct=JSON.parse(Wi.slice(6));if(Ct.step&&v(Ct.message||Ct.step),Ct.step==="done"&&Ct.txHash){if(nt=!0,await t(`/api/stories/${le}/${L}/publish-status`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({txHash:Ct.txHash,storylineId:Ct.storylineId,plotIndex:Ct.plotIndex,contentCid:Ct.contentCid,gasCost:Ct.gasCost,indexError:Ct.indexError,authorAddress:R})}),x(qn=>qn+1),Ne&&L==="genesis.md"&&Ct.storylineId){v("Uploading cover...");let qn=null;try{qn=await oM(t,Ct.storylineId,Ne)}catch{}qn||(Pe=!0)}if(Gt==="cartoon"&&Ct.storylineId)try{const qn=L!=="genesis.md",ya=`storylineId=${Ct.storylineId}`+(qn&&Ct.plotIndex!=null?`&plotIndex=${Ct.plotIndex}`:""),Lr=await t(`/api/publish/public-title?${ya}`);if(Lr.ok){const Fs=await Lr.json(),xr=qn?{plots:Fs.plotTitle!=null?[{plotIndex:Ct.plotIndex,title:Fs.plotTitle}]:[]}:{title:Fs.storylineTitle},Ei=$M({fileName:L,detail:xr,plotIndex:Ct.plotIndex});Ei.ok||(qe=FM(Ei))}}catch{}}}catch{}}qe&&j(qe),v(Pe?"Published, but cover upload failed — set it later from Edit Story.":"Published!")}catch(Et){const Nt=Et instanceof Error?Et.message:"Publish failed";v(`Error: ${Nt}`)}finally{setTimeout(()=>{f(null),v("")},3e3)}return nt&&!Pe},[t,je,R]),$e=w.useCallback(le=>{le.startsWith("_new_")&&(F(L=>L.filter(oe=>oe!==le)),Te.current.delete(le),Ue.current.delete(le),it.current.delete(le),Wt.current.delete(le),ne(L=>{if(!(le in L))return L;const oe={...L};return delete oe[le],oe}),Y(L=>{if(!(le in L))return L;const oe={...L};return delete oe[le],oe}))},[]);w.useEffect(()=>{const le=oe=>{_e(new Set(oe.filter(Ve=>Ve.hasStructure).map(Ve=>Ve.name))),Le(new Set(oe.filter(Ve=>Ve.hasGenesis).map(Ve=>Ve.name)));const Ee={},Me={},Ne={},Pe={},qe={},nt={};for(const Ve of oe)Ee[Ve.name]=Ve.contentType||"fiction",Me[Ve.name]=Ve.language,Ne[Ve.name]=Ve.genre,Pe[Ve.name]=Ve.isNsfw,qe[Ve.name]=Ve.agentProvider,Ve.title&&(nt[Ve.name]=Ve.title);be(Ee),St(Me),We(Ne),He(Pe),mi(qe),Ae(nt)};t("/api/stories").then(oe=>oe.ok?oe.json():null).then(oe=>{oe!=null&&oe.stories&&le(oe.stories)}).catch(()=>{});const L=setInterval(async()=>{try{const oe=await t("/api/stories");if(oe.ok){const Ee=await oe.json();le(Ee.stories)}}catch{}},5e3);return()=>clearInterval(L)},[t]);const ht=!!T&&T.codex.installed&&T.codex.imageGeneration==="enabled",dt=!!T&&!ht,lt=w.useCallback(async()=>{try{await navigator.clipboard.writeText("codex features enable image_generation"),C(!0),setTimeout(()=>C(!1),2e3)}catch{}},[]),Vt=w.useCallback(async()=>{if(!i||i.startsWith("_new_"))return;const le=i;if((await t(`/api/stories/${le}/metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentType:"cartoon",agentProvider:"codex"})})).ok){mi(oe=>({...oe,[le]:"codex"})),Y(oe=>({...oe,[le]:"codex"}));try{const oe=await t("/api/stories");if(oe.ok){const Ee=await oe.json();if(Ee!=null&&Ee.stories){const Me={};for(const Ne of Ee.stories)Me[Ne.name]=Ne.agentProvider;mi(Me)}}}catch{}}},[t,i]),Ci=w.useCallback(le=>{i===le&&(s(null),o(null))},[i]),ft=i?ae[i]??Kt[i]:void 0,Fi=Lf(i,je,Te.current),En=fM(Fi,ft,i),ln=!!i&&Fi==="cartoon",Un=c==="story-info"?"story-info":c==="episodes"?"episodes":c==="publish"?"publish":a==="structure.md"?"whitepaper":a==="genesis.md"?"genesis":a&&/^plot-\d+\.md$/.test(a)?"episodes":"progress",on=w.useCallback(le=>{const L=i;if(L)switch(le){case"progress":h(null),o(null);break;case"story-info":h("story-info");break;case"episodes":h("episodes");break;case"whitepaper":P(L,"structure.md");break;case"genesis":P(L,"genesis.md");break;case"publish":h("publish");break}},[i,P]),gn=w.useCallback((le,L)=>{const oe=i;if(oe)switch(le){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":L&&P(oe,L);break}},[i,P]),cn=w.useCallback(le=>{i&&(le.genre!==void 0&&We(L=>({...L,[i]:le.genre||void 0})),le.language!==void 0&&St(L=>({...L,[i]:le.language||void 0})),le.isNsfw!==void 0&&He(L=>({...L,[i]:le.isNsfw})))},[i]),pr=w.useCallback(le=>{Qe(le),ge(!le)},[]),Lt=wt&&!Q;return d.jsxs("div",{ref:vt,className:"h-[calc(100vh-3.5rem)] flex","data-testid":Lt?"stories-focused-lettering-mode":"stories-default-layout",children:[!Lt&&d.jsx("div",{className:"w-56 border-r border-border flex-shrink-0",children:d.jsx(kC,{authFetch:t,selectedStory:i,selectedFile:a,onSelectFile:P,onNewStory:Ze,untitledSessions:te})}),!Lt&&d.jsx("div",{className:"min-w-0 border-r border-border",style:{flex:`${N} 0 0`},children:d.jsx(ZE,{token:e,storyName:i,authFetch:t,onSelectStory:ze,onDestroySession:$e,onArchiveStory:Ci,confirmedStories:he,renameRef:Bt,bypassStories:V,agentProviders:ae,readiness:T,contentType:Lf(i,je,Te.current),needsProviderRepair:En,onRepairProvider:Vt})}),!Lt&&d.jsx("div",{onMouseDown:Re,className:"flex-shrink-0 flex items-center justify-center hover:bg-border/50 transition-colors",style:{width:If,cursor:"col-resize",background:"var(--border)"},children:d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}}),d.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}}),d.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}})]})}),d.jsxs("div",{className:"min-w-0 flex flex-col",style:Lt?{flex:"1 0 0"}:{flex:`${1-N} 0 0`},children:[!wt&&ln&&i&&d.jsx(zM,{storyTitle:xt[i]||i,active:Un,onSelect:on}),!wt&&ln&&i&&c!==null&&d.jsx("div",{className:"flex-shrink-0 border-b border-border","data-testid":"workflow-context-next-action",children:d.jsx(wM,{storyName:i,authFetch:t,refreshKey:_,onCoachAction:gn,onOpenStoryInfo:()=>h("story-info")})}),ln&&c==="story-info"&&i?d.jsx(PM,{storyName:i,authFetch:t,onSaved:cn}):ln&&c==="episodes"&&i?d.jsx(IM,{storyName:i,authFetch:t,onOpenFile:P}):ln&&c==="publish"&&i?d.jsx(HM,{storyName:i,authFetch:t,onOpenFile:P,onOpenStoryInfo:()=>h("story-info"),onPublish:Ge,publishingFile:p,genre:ot[i],language:tt[i],isNsfw:Mt[i],refreshKey:_}):i&&!a?d.jsx(kM,{storyName:i,authFetch:t,onOpenFile:P,onOpenStoryInfo:()=>h("story-info")}):d.jsx(vM,{storyName:i,fileName:a,authFetch:t,onPublish:Ge,publishingFile:p,walletAddress:R,contentType:Lf(i,je,Te.current)||"fiction",language:i?tt[i]:void 0,genre:i?ot[i]:void 0,isNsfw:i?Mt[i]:void 0,hasGenesis:i?Be.has(i):!1,onViewProgress:()=>o(null),onOpenFile:le=>i&&P(i,le),onViewPublish:()=>h("publish"),focusedLetteringMode:wt,focusedLetteringWorkspaceVisible:Q,onFocusedLetteringModeChange:pr,onFocusedLetteringWorkspaceVisibleChange:ge}),b&&d.jsx("div",{className:"px-3 py-1.5 bg-surface border-t border-border text-xs text-muted",children:b}),S&&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:S}),d.jsx("button",{type:"button",onClick:()=>j(null),className:"shrink-0 text-error/70 hover:text-error underline","data-testid":"publish-block-error-dismiss",children:"Dismiss"})]})]}),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:fe,onChange:le=>Se(le.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:H,onChange:le=>ce(le.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:W,onChange:le=>K(le.target.value),"data-testid":"new-story-genre",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none",children:[d.jsx("option",{value:"",children:"— Select later —"}),dl.map(le=>d.jsx("option",{value:le,children:le},le))]})]}),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:X,onChange:le=>U(le.target.value),className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none",children:ts.map(le=>d.jsx("option",{value:le,children:le},le))})]}),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:le=>O(le.target.value),className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"agent-mode-select",children:[d.jsx("option",{value:"normal",children:"Normal (approve each action)"}),d.jsx("option",{value:"bypass",children:"Permissions Bypass (advanced)"})]}),A==="bypass"&&d.jsx("p",{className:"text-[10px] text-amber-700","data-testid":"agent-mode-warning",children:"Less safe: Claude can run actions without per-command approval."})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Provider"}),d.jsxs("select",{value:$,onChange:le=>xe(le.target.value),className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"agent-provider-select",children:[d.jsx("option",{value:"claude",children:"🤖 Claude (default)"}),d.jsx("option",{value:"codex",children:"🎨 Codex"})]}),d.jsx("p",{className:"text-[10px] text-muted","data-testid":"agent-provider-helper",children:$==="codex"?"Codex can generate clean cartoon images directly in the terminal.":"Claude prepares image prompts; you generate and upload clean images externally."})]}),d.jsx("p",{className:"text-xs text-muted text-center",children:"Choose a content type to create"}),!fe.trim()&&d.jsx("p",{className:"text-[10px] text-amber-700 text-center","data-testid":"new-story-title-required",children:"Enter a title to create your story."}),d.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[d.jsxs("button",{onClick:()=>hi("fiction",X,A,$),disabled:!fe.trim(),"data-testid":"create-fiction",className:"border border-border rounded-lg p-4 hover:border-accent hover:bg-accent/5 transition-colors text-center space-y-1 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:border-border disabled:hover:bg-transparent",children:[d.jsx("p",{className:"text-sm font-serif font-medium text-foreground",children:"Fiction"}),d.jsx("p",{className:"text-[11px] text-muted",children:"Novels, short stories, poetry"})]}),d.jsxs("div",{className:"space-y-1",children:[d.jsxs("button",{onClick:()=>hi("cartoon",X,A,"codex"),disabled:dt||!fe.trim(),"data-testid":"create-cartoon",className:"w-full border border-border rounded-lg p-4 hover:border-accent hover:bg-accent/5 transition-colors text-center space-y-1 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:border-border disabled:hover:bg-transparent",children:[d.jsx("p",{className:"text-sm font-serif font-medium text-foreground",children:"Cartoon"}),d.jsx("p",{className:"text-[11px] text-muted",children:"Comics, manga, webtoons"}),d.jsx("p",{className:"text-[11px] text-muted","data-testid":"cartoon-codex-note",children:"Cartoon mode requires Codex because the clean-image step needs image generation support."})]}),T&&!T.codex.installed&&d.jsxs("p",{className:"text-[11px] text-amber-700 text-left","data-testid":"cartoon-codex-warning",children:["Codex was not detected. Install the Codex CLI and sign in (e.g."," ",d.jsx("span",{className:"font-mono",children:"npm i -g @openai/codex"})," ","then ",d.jsx("span",{className:"font-mono",children:"codex login"}),") to create cartoons."]}),Eu(T)&&d.jsx("p",{className:"text-[11px] text-amber-700 text-left","data-testid":"cartoon-codex-auth-unknown",children:Up}),T&&T.codex.installed&&!Eu(T)&&T.codex.imageGeneration!=="enabled"&&d.jsxs("div",{"data-testid":"cartoon-codex-warning",children:[d.jsx("p",{className:"text-[11px] text-amber-700 text-left",children:"Codex is installed but image generation isn't enabled. Enable it, then reopen this dialog:"}),d.jsxs("div",{className:"mt-1 flex items-center gap-1",children:[d.jsx("code",{className:"flex-1 truncate rounded border border-border bg-surface px-1.5 py-1 text-left text-[10px] font-mono text-foreground",children:"codex features enable image_generation"}),d.jsx("button",{type:"button","data-testid":"copy-codex-enable",onClick:lt,className:"rounded border border-border px-2 py-1 text-[10px] text-muted hover:border-accent hover:text-accent transition-colors",children:G?"Copied!":"Copy"})]})]})]})]}),d.jsx("button",{onClick:()=>ie(!1),className:"w-full px-3 py-1.5 text-xs text-muted hover:text-foreground hover:bg-surface rounded text-center",children:"Cancel"})]})})]})}function YM({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 KM({token:e,onLogout:t}){const[i,s]=w.useState("home"),[a,o]=w.useState(0),[c,h]=w.useState(null),p=w.useCallback(async(f,_)=>fetch(f,{..._,headers:{...(_==null?void 0:_.headers)||{},Authorization:`Bearer ${e}`}}),[e]);return w.useEffect(()=>{fetch("/api/health").then(f=>f.json()).then(f=>{f.version&&h(f.version)}).catch(()=>{})},[]),w.useEffect(()=>{async function f(){try{if(!(await(await p("/api/wallet")).json()).exists){s("wallet-setup");return}const b=await p("/api/stories");if(b.ok){const v=await b.json();o(v.stories.filter(S=>S.name!=="_example").length)}}catch{}}f()},[e]),d.jsxs("div",{className:"flex h-screen flex-col",children:[d.jsxs("header",{className:"border-border flex h-14 items-center justify-between border-b px-4 flex-shrink-0",children:[d.jsxs("div",{className:"flex items-center gap-3",children:[d.jsx("button",{onClick:()=>{i!=="wallet-setup"&&s("home")},className:"flex items-center gap-2 hover:opacity-80",children:d.jsx("span",{className:"text-accent text-sm font-bold tracking-tight",children:"PlotLink OWS"})}),d.jsxs("span",{className:"text-muted text-[10px] uppercase tracking-wider",children:["writer",c?` v${c}`:""]})]}),i!=="wallet-setup"&&d.jsxs("nav",{className:"flex items-center gap-4",children:[d.jsx("button",{onClick:()=>s("stories"),className:`text-xs transition-colors ${i==="stories"?"text-accent":"text-muted hover:text-foreground"}`,children:"stories"}),d.jsx("button",{onClick:()=>s("dashboard"),className:`text-xs transition-colors ${i==="dashboard"?"text-accent":"text-muted hover:text-foreground"}`,children:"dashboard"}),d.jsx("button",{onClick:()=>s("settings"),className:`text-xs transition-colors ${i==="settings"?"text-accent":"text-muted hover:text-foreground"}`,children:"settings"}),d.jsx("button",{onClick:t,className:"text-muted hover:text-foreground text-xs transition-colors",children:"logout"})]})]}),d.jsxs("main",{className:"flex-1 min-h-0",children:[i==="home"&&d.jsxs("div",{className:"mx-auto max-w-lg space-y-6 p-8",children:[d.jsxs("div",{className:"text-center space-y-2",children:[d.jsx("h1",{className:"text-2xl font-serif text-foreground",children:"Write. Publish. Earn."}),d.jsx("p",{className:"text-muted text-sm",children:"Claude or Codex helps create your story. You publish it on-chain."})]}),d.jsxs("div",{className:"text-center space-y-3",children:[d.jsx("button",{onClick:()=>s("stories"),className:"bg-accent text-white hover:bg-accent-dim px-6 py-2.5 rounded text-sm font-medium transition-colors",children:"Start Writing"}),a>0&&d.jsxs("p",{className:"text-muted text-xs",children:[a," ",a===1?"story":"stories"," in progress"]})]}),d.jsxs("div",{className:"rounded border border-border p-4 space-y-2 text-xs text-muted",children:[d.jsx("p",{className:"font-medium text-foreground text-sm",children:"How it works"}),d.jsxs("ol",{className:"space-y-1.5 list-decimal list-inside",children:[d.jsxs("li",{children:["Open the ",d.jsx("strong",{children:"Stories"})," tab — your writing agent launches in the terminal"]}),d.jsx("li",{children:"Tell the agent your story idea — it brainstorms, outlines, and writes"}),d.jsx("li",{children:"Review the live preview as the agent creates files"}),d.jsxs("li",{children:["Click ",d.jsx("strong",{children:"Publish"})," to put your story on-chain"]}),d.jsxs("li",{children:["Earn 5% royalties on every trade at ",d.jsx("a",{href:"https://plotlink.xyz",target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"plotlink.xyz"})]})]}),d.jsx("p",{className:"text-[11px] text-muted",children:"Fiction defaults to Claude; cartoon mode uses Codex for clean-image generation."})]}),d.jsx("div",{className:"text-center",children:d.jsx("a",{href:"https://github.com/realproject7/plotlink-ows#-wallet-setup",target:"_blank",rel:"noopener noreferrer",className:"text-xs text-muted hover:text-accent underline transition-colors",children:"Wallet Setup Guide"})}),d.jsx(jy,{token:e})]}),i==="stories"&&d.jsx(GM,{token:e,authFetch:p}),i==="dashboard"&&d.jsx(SC,{token:e}),i==="wallet-setup"&&d.jsx(YM,{token:e,onComplete:()=>s("home")}),i==="settings"&&d.jsx(vC,{token:e,onLogout:t})]})]})}function VM(){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(KM,{token:e,onLogout:p}):d.jsx(_C,{onLogin:c}):d.jsx(bC,{onSetup:h})}xC.createRoot(document.getElementById("root")).render(d.jsx(cC.StrictMode,{children:d.jsx(VM,{})}));export{zp as M,hu as a,M3 as b,ID as c,L3 as d,uu as l,HS as s,G3 as t,e4 as v}; diff --git a/app/web/dist/assets/index-D3eZu5VE.js b/app/web/dist/assets/index-D3eZu5VE.js deleted file mode 100644 index b562ffd..0000000 --- a/app/web/dist/assets/index-D3eZu5VE.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 Ou(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Gd={exports:{}},ao={};/** - * @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 ao;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 ao.Fragment=t,ao.jsx=i,ao.jsxs=i,ao}var Z_;function nC(){return Z_||(Z_=1,Gd.exports=iC()),Gd.exports}var d=nC(),Yd={exports:{}},tt={};/** - * @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 tt;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(D){return D===null||typeof D!="object"?null:(D=b&&D[b]||D["@@iterator"],typeof D=="function"?D:null)}var S={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},j=Object.assign,R={};function E(D,K,k){this.props=D,this.context=K,this.refs=R,this.updater=k||S}E.prototype.isReactComponent={},E.prototype.setState=function(D,K){if(typeof D!="object"&&typeof D!="function"&&D!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,D,K,"setState")},E.prototype.forceUpdate=function(D){this.updater.enqueueForceUpdate(this,D,"forceUpdate")};function N(){}N.prototype=E.prototype;function z(D,K,k){this.props=D,this.context=K,this.refs=R,this.updater=k||S}var J=z.prototype=new N;J.constructor=z,j(J,E.prototype),J.isPureReactComponent=!0;var F=Array.isArray;function M(){}var ee={H:null,A:null,T:null,S:null},fe=Object.prototype.hasOwnProperty;function ye(D,K,k){var ue=k.ref;return{$$typeof:e,type:D,key:K,ref:ue!==void 0?ue:null,props:k}}function P(D,K){return ye(D.type,K,D.props)}function ae(D){return typeof D=="object"&&D!==null&&D.$$typeof===e}function W(D){var K={"=":"=0",":":"=2"};return"$"+D.replace(/[=:]/g,function(k){return K[k]})}var Y=/\/+/g;function V(D,K){return typeof D=="object"&&D!==null&&D.key!=null?W(""+D.key):K.toString(36)}function I(D){switch(D.status){case"fulfilled":return D.value;case"rejected":throw D.reason;default:switch(typeof D.status=="string"?D.then(M,M):(D.status="pending",D.then(function(K){D.status==="pending"&&(D.status="fulfilled",D.value=K)},function(K){D.status==="pending"&&(D.status="rejected",D.reason=K)})),D.status){case"fulfilled":return D.value;case"rejected":throw D.reason}}throw D}function A(D,K,k,ue,te){var G=typeof D;(G==="undefined"||G==="boolean")&&(D=null);var H=!1;if(D===null)H=!0;else switch(G){case"bigint":case"string":case"number":H=!0;break;case"object":switch(D.$$typeof){case e:case t:H=!0;break;case _:return H=D._init,A(H(D._payload),K,k,ue,te)}}if(H)return te=te(D),H=ue===""?"."+V(D,0):ue,F(te)?(k="",H!=null&&(k=H.replace(Y,"$&/")+"/"),A(te,K,k,"",function(Re){return Re})):te!=null&&(ae(te)&&(te=P(te,k+(te.key==null||D&&D.key===te.key?"":(""+te.key).replace(Y,"$&/")+"/")+H)),K.push(te)),1;H=0;var le=ue===""?".":ue+":";if(F(D))for(var xe=0;xe>>1,T=A[ge];if(0>>1;gea(k,U))uea(te,k)?(A[ge]=te,A[ue]=U,ge=ue):(A[ge]=k,A[K]=U,ge=K);else if(uea(te,U))A[ge]=te,A[ue]=U,ge=ue;else break e}}return L}function a(A,L){var U=A.sortIndex-L.sortIndex;return U!==0?U:A.id-L.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var o=performance;e.unstable_now=function(){return o.now()}}else{var c=Date,h=c.now();e.unstable_now=function(){return c.now()-h}}var p=[],f=[],_=1,x=null,b=3,v=!1,S=!1,j=!1,R=!1,E=typeof setTimeout=="function"?setTimeout:null,N=typeof clearTimeout=="function"?clearTimeout:null,z=typeof setImmediate<"u"?setImmediate:null;function J(A){for(var L=i(f);L!==null;){if(L.callback===null)s(f);else if(L.startTime<=A)s(f),L.sortIndex=L.expirationTime,t(p,L);else break;L=i(f)}}function F(A){if(j=!1,J(A),!S)if(i(p)!==null)S=!0,M||(M=!0,W());else{var L=i(f);L!==null&&I(F,L.startTime-A)}}var M=!1,ee=-1,fe=5,ye=-1;function P(){return R?!0:!(e.unstable_now()-yeA&&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,J(A),L=!0;break t}x===i(p)&&s(p),J(A)}else s(p);x=i(p)}if(x!==null)L=!0;else{var D=i(f);D!==null&&I(F,D.startTime-A),L=!1}}break e}finally{x=null,b=U,v=!1}L=void 0}}finally{L?W():M=!1}}}var W;if(typeof z=="function")W=function(){z(ae)};else if(typeof MessageChannel<"u"){var Y=new MessageChannel,V=Y.port2;Y.port1.onmessage=ae,W=function(){V.postMessage(null)}}else W=function(){E(ae,0)};function I(A,L){ee=E(function(){A(e.unstable_now())},L)}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)&&(j?(N(ee),ee=-1):j=!0,I(F,U-ge))):(A.sortIndex=T,t(p,A),S||v||(S=!0,M||(M=!0,W()))),A},e.unstable_shouldYield=P,e.unstable_wrapCallback=function(A){var L=b;return function(){var U=b;b=L;try{return A.apply(this,arguments)}finally{b=U}}}})(Xd)),Xd}var tb;function lC(){return tb||(tb=1,Vd.exports=aC()),Vd.exports}var Zd={exports:{}},ln={};/** - * @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 ln;ib=1;var e=Pp();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(),Zd.exports=oC(),Zd.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 lo;rb=1;var e=lC(),t=Pp(),i=cC();function s(n){var r="https://react.dev/errors/"+n;if(1T||(n.current=ge[T],ge[T]=null,T--)}function k(n,r){T++,ge[T]=n.current,n.current=r}var ue=D(null),te=D(null),G=D(null),H=D(null);function le(n,r){switch(k(G,r),k(te,n),k(ue,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}}K(ue),k(ue,n)}function xe(){K(ue),K(te),K(G)}function Re(n){n.memoizedState!==null&&k(H,n);var r=ue.current,l=v_(r,n.type);r!==l&&(k(te,n),k(ue,l))}function Me(n){te.current===n&&(K(ue),K(te)),H.current===n&&(K(H),io._currentValue=U)}var Le,Ae;function ut(n){if(Le===void 0)try{throw Error()}catch(l){var r=l.stack.trim().match(/\n( *(at )?)/);Le=r&&r[1]||"",Ae=-1)":-1m||B[u]!==Z[m]){var oe=` -`+B[u].replace(" at new "," at ");return n.displayName&&oe.includes("")&&(oe=oe.replace("",n.displayName)),oe}while(1<=u&&0<=m);break}}}finally{We=!1,Error.prepareStackTrace=l}return(l=n?n.displayName||n.name:"")?ut(l):""}function Qe(n,r){switch(n.tag){case 26:case 27:case 5:return ut(n.type);case 16:return ut("Lazy");case 13:return n.child!==r&&r!==null?ut("Suspense Fallback"):ut("Suspense");case 19:return ut("SuspenseList");case 0:case 15:return bt(n.type,!1);case 11:return bt(n.type.render,!1);case 1:return bt(n.type,!0);case 31:return ut("Activity");default:return""}}function Ft(n){try{var r="",l=null;do r+=Qe(n,l),l=n,n=n.return;while(n);return r}catch(u){return` -Error generating stack: `+u.message+` -`+u.stack}}var Pe=Object.prototype.hasOwnProperty,ft=e.unstable_scheduleCallback,Ze=e.unstable_cancelCallback,pt=e.unstable_shouldYield,ei=e.unstable_requestPaint,we=e.unstable_now,yi=e.unstable_getCurrentPriorityLevel,se=e.unstable_ImmediatePriority,me=e.unstable_UserBlockingPriority,Te=e.unstable_NormalPriority,Fe=e.unstable_LowPriority,it=e.unstable_IdlePriority,Ot=e.log,ui=e.unstable_setDisableYieldValue,zt=null,At=null;function Ct(n){if(typeof Ot=="function"&&ui(n),At&&typeof At.setStrictMode=="function")try{At.setStrictMode(zt,n)}catch{}}var He=Math.clz32?Math.clz32:_n,li=Math.log,st=Math.LN2;function _n(n){return n>>>=0,n===0?32:31-(li(n)/st|0)|0}var q=256,ke=262144,De=4194304;function Ee(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 Ke(n,r,l){var u=n.pendingLanes;if(u===0)return 0;var m=0,g=n.suspendedLanes,y=n.pingedLanes;n=n.warmLanes;var C=u&134217727;return C!==0?(u=C&~g,u!==0?m=Ee(u):(y&=C,y!==0?m=Ee(y):l||(l=C&~n,l!==0&&(m=Ee(l))))):(C=u&~g,C!==0?m=Ee(C):y!==0?m=Ee(y):l||(l=u&~n,l!==0&&(m=Ee(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 Xe(n,r){return(n.pendingLanes&~(n.suspendedLanes&~n.pingedLanes)&r)===0}function nt(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=De;return De<<=1,(De&62914560)===0&&(De=4194304),n}function mt(n){for(var r=[],l=0;31>l;l++)r.push(n);return r}function ct(n,r){n.pendingLanes|=r,r!==268435456&&(n.suspendedLanes=0,n.pingedLanes=0,n.warmLanes=0)}function Ai(n,r,l,u,m,g){var y=n.pendingLanes;n.pendingLanes=l,n.suspendedLanes=0,n.pingedLanes=0,n.warmLanes=0,n.expiredLanes&=l,n.entangledLanes&=l,n.errorRecoveryDisabledLanes&=l,n.shellSuspendCounter=0;var C=n.entanglements,B=n.expirationTimes,Z=n.hiddenUpdates;for(l=y&~l;0"u")return null;try{return n.activeElement||n.body}catch{return n.body}}var Ri=/[\n"\\]/g;function Si(n){return n.replace(Ri,function(r){return"\\"+r.charCodeAt(0).toString(16)+" "})}function Xi(n,r,l,u,m,g,y,C){n.name="",y!=null&&typeof y!="function"&&typeof y!="symbol"&&typeof y!="boolean"?n.type=y:n.removeAttribute("type"),r!=null?y==="number"?(r===0&&n.value===""||n.value!=r)&&(n.value=""+jt(r)):n.value!==""+jt(r)&&(n.value=""+jt(r)):y!=="submit"&&y!=="reset"||n.removeAttribute("value"),r!=null?Br(n,y,jt(r)):l!=null?Br(n,y,jt(l)):u!=null&&n.removeAttribute("value"),m==null&&g!=null&&(n.defaultChecked=!!g),m!=null&&(n.checked=m&&typeof m!="function"&&typeof m!="symbol"),C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"?n.name=""+jt(C):n.removeAttribute("name")}function Tn(n,r,l,u,m,g,y,C){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)){Dr(n);return}l=l!=null?""+jt(l):"",r=r!=null?""+jt(r):l,C||r===n.value||(n.value=r),n.defaultValue=r}u=u??m,u=typeof u!="function"&&typeof u!="symbol"&&!!u,n.checked=C?n.checked:!!u,n.defaultChecked=!!u,y!=null&&typeof y!="function"&&typeof y!="symbol"&&typeof y!="boolean"&&(n.name=y),Dr(n)}function Br(n,r,l){r==="number"&&pr(n.ownerDocument)===n||n.defaultValue===""+l||(n.defaultValue=""+l)}function An(n,r,l,u){if(n=n.options,r){r={};for(var m=0;m"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),ne=!1;if(qn)try{var be={};Object.defineProperty(be,"passive",{get:function(){ne=!0}}),window.addEventListener("test",be,be),window.removeEventListener("test",be,be)}catch{ne=!1}var Ce=null,et=null,Gt=null;function Mi(){if(Gt)return Gt;var n,r=et,l=r.length,u,m="value"in Ce?Ce.value:Ce.textContent,g=m.length;for(n=0;n=wl),Em=" ",Nm=!1;function jm(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 Tm(n){return n=n.detail,typeof n=="object"&&"data"in n?n.data:null}var Na=!1;function E1(n,r){switch(n){case"compositionend":return Tm(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(Na)return n==="compositionend"||!Qu&&jm(n,r)?(n=Mi(),Gt=et=Ce=null,Na=!1,n):null;switch(n){case"paste":return null;case"keypress":if(!(r.ctrlKey||r.altKey||r.metaKey)||r.ctrlKey&&r.altKey){if(r.char&&1=r)return{node:l,offset:r-n};n=u}e:{for(;l;){if(l.nextSibling){l=l.nextSibling;break e}l=l.parentNode}l=void 0}l=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=pr(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=pr(n.document)}return r}function th(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=qn&&"documentMode"in document&&11>=document.documentMode,ja=null,ih=null,Nl=null,nh=!1;function Um(n,r,l){var u=l.window===l?l.document:l.nodeType===9?l:l.ownerDocument;nh||ja==null||ja!==pr(u)||(u=ja,"selectionStart"in u&&th(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}),Nl&&El(Nl,u)||(Nl=u,u=zc(ih,"onSelect"),0>=y,m-=y,_r=1<<32-He(r)+m|l<lt?(wt=Oe,Oe=null):wt=Oe.sibling;var Dt=Q($,Oe,X[lt],he);if(Dt===null){Oe===null&&(Oe=wt);break}n&&Oe&&Dt.alternate===null&&r($,Oe),O=g(Dt,O,lt),Mt===null?Ue=Dt:Mt.sibling=Dt,Mt=Dt,Oe=wt}if(lt===X.length)return l($,Oe),Nt&&Or($,lt),Ue;if(Oe===null){for(;ltlt?(wt=Oe,Oe=null):wt=Oe.sibling;var Ms=Q($,Oe,Dt.value,he);if(Ms===null){Oe===null&&(Oe=wt);break}n&&Oe&&Ms.alternate===null&&r($,Oe),O=g(Ms,O,lt),Mt===null?Ue=Ms:Mt.sibling=Ms,Mt=Ms,Oe=wt}if(Dt.done)return l($,Oe),Nt&&Or($,lt),Ue;if(Oe===null){for(;!Dt.done;lt++,Dt=X.next())Dt=de($,Dt.value,he),Dt!==null&&(O=g(Dt,O,lt),Mt===null?Ue=Dt:Mt.sibling=Dt,Mt=Dt);return Nt&&Or($,lt),Ue}for(Oe=u(Oe);!Dt.done;lt++,Dt=X.next())Dt=re(Oe,$,lt,Dt.value,he),Dt!==null&&(n&&Dt.alternate!==null&&Oe.delete(Dt.key===null?lt:Dt.key),O=g(Dt,O,lt),Mt===null?Ue=Dt:Mt.sibling=Dt,Mt=Dt);return n&&Oe.forEach(function(tC){return r($,tC)}),Nt&&Or($,lt),Ue}function Vt($,O,X,he){if(typeof X=="object"&&X!==null&&X.type===j&&X.key===null&&(X=X.props.children),typeof X=="object"&&X!==null){switch(X.$$typeof){case v:e:{for(var Ue=X.key;O!==null;){if(O.key===Ue){if(Ue=X.type,Ue===j){if(O.tag===7){l($,O.sibling),he=m(O,X.props.children),he.return=$,$=he;break e}}else if(O.elementType===Ue||typeof Ue=="object"&&Ue!==null&&Ue.$$typeof===fe&&ta(Ue)===O.type){l($,O.sibling),he=m(O,X.props),Dl(he,X),he.return=$,$=he;break e}l($,O);break}else r($,O);O=O.sibling}X.type===j?(he=Xs(X.props.children,$.mode,he,X.key),he.return=$,$=he):(he=ec(X.type,X.key,X.props,null,$.mode,he),Dl(he,X),he.return=$,$=he)}return y($);case S:e:{for(Ue=X.key;O!==null;){if(O.key===Ue)if(O.tag===4&&O.stateNode.containerInfo===X.containerInfo&&O.stateNode.implementation===X.implementation){l($,O.sibling),he=m(O,X.children||[]),he.return=$,$=he;break e}else{l($,O);break}else r($,O);O=O.sibling}he=uh(X,$.mode,he),he.return=$,$=he}return y($);case fe:return X=ta(X),Vt($,O,X,he)}if(I(X))return Be($,O,X,he);if(W(X)){if(Ue=W(X),typeof Ue!="function")throw Error(s(150));return X=Ue.call(X),qe($,O,X,he)}if(typeof X.then=="function")return Vt($,O,lc(X),he);if(X.$$typeof===z)return Vt($,O,nc($,X),he);oc($,X)}return typeof X=="string"&&X!==""||typeof X=="number"||typeof X=="bigint"?(X=""+X,O!==null&&O.tag===6?(l($,O.sibling),he=m(O,X),he.return=$,$=he):(l($,O),he=ch(X,$.mode,he),he.return=$,$=he),y($)):l($,O)}return function($,O,X,he){try{Ml=0;var Ue=Vt($,O,X,he);return Ia=null,Ue}catch(Oe){if(Oe===Pa||Oe===sc)throw Oe;var Mt=Mn(29,Oe,null,$.mode);return Mt.lanes=he,Mt.return=$,Mt}finally{}}}var na=ug(!0),hg=ug(!1),ms=!1;function Sh(n){n.updateQueue={baseState:n.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function wh(n,r){n=n.updateQueue,r.updateQueue===n&&(r.updateQueue={baseState:n.baseState,firstBaseUpdate:n.firstBaseUpdate,lastBaseUpdate:n.lastBaseUpdate,shared:n.shared,callbacks:null})}function gs(n){return{lane:n,tag:0,payload:null,callback:null,next:null}}function xs(n,r,l){var u=n.updateQueue;if(u===null)return null;if(u=u.shared,(Lt&2)!==0){var m=u.pending;return m===null?r.next=r:(r.next=m.next,m.next=r),u.pending=r,r=Jo(n),Km(n,null,l),r}return Qo(n,u,r,l),Jo(n)}function Bl(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,ce(n,l)}}function Ch(n,r){var l=n.updateQueue,u=n.alternate;if(u!==null&&(u=u.updateQueue,l===u)){var m=null,g=null;if(l=l.firstBaseUpdate,l!==null){do{var y={lane:l.lane,tag:l.tag,payload:l.payload,callback:null,next:null};g===null?m=g=y:g=g.next=y,l=l.next}while(l!==null);g===null?m=g=r:g=g.next=r}else m=g=r;l={baseState:u.baseState,firstBaseUpdate:m,lastBaseUpdate:g,shared:u.shared,callbacks:u.callbacks},n.updateQueue=l;return}n=l.lastBaseUpdate,n===null?l.firstBaseUpdate=r:n.next=r,l.lastBaseUpdate=r}var kh=!1;function Ll(){if(kh){var n=za;if(n!==null)throw n}}function Ol(n,r,l,u){kh=!1;var m=n.updateQueue;ms=!1;var g=m.firstBaseUpdate,y=m.lastBaseUpdate,C=m.shared.pending;if(C!==null){m.shared.pending=null;var B=C,Z=B.next;B.next=null,y===null?g=Z:y.next=Z,y=B;var oe=n.alternate;oe!==null&&(oe=oe.updateQueue,C=oe.lastBaseUpdate,C!==y&&(C===null?oe.firstBaseUpdate=Z:C.next=Z,oe.lastBaseUpdate=B))}if(g!==null){var de=m.baseState;y=0,oe=Z=B=null,C=g;do{var Q=C.lane&-536870913,re=Q!==C.lane;if(re?(St&Q)===Q:(u&Q)===Q){Q!==0&&Q===Oa&&(kh=!0),oe!==null&&(oe=oe.next={lane:0,tag:C.tag,payload:C.payload,callback:null,next:null});e:{var Be=n,qe=C;Q=r;var Vt=l;switch(qe.tag){case 1:if(Be=qe.payload,typeof Be=="function"){de=Be.call(Vt,de,Q);break e}de=Be;break e;case 3:Be.flags=Be.flags&-65537|128;case 0:if(Be=qe.payload,Q=typeof Be=="function"?Be.call(Vt,de,Q):Be,Q==null)break e;de=x({},de,Q);break e;case 2:ms=!0}}Q=C.callback,Q!==null&&(n.flags|=64,re&&(n.flags|=8192),re=m.callbacks,re===null?m.callbacks=[Q]:re.push(Q))}else re={lane:Q,tag:C.tag,payload:C.payload,callback:C.callback,next:null},oe===null?(Z=oe=re,B=de):oe=oe.next=re,y|=Q;if(C=C.next,C===null){if(C=m.shared.pending,C===null)break;re=C,C=re.next,re.next=null,m.lastBaseUpdate=re,m.shared.pending=null}}while(!0);oe===null&&(B=de),m.baseState=B,m.firstBaseUpdate=Z,m.lastBaseUpdate=oe,g===null&&(m.shared.lanes=0),Ss|=y,n.lanes=y,n.memoizedState=de}}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 y=A.T,C={};A.T=C,qh(n,!1,r,l);try{var B=m(),Z=A.S;if(Z!==null&&Z(C,B),B!==null&&typeof B=="object"&&typeof B.then=="function"){var oe=q1(B,u);Il(n,r,oe,zn(n))}else Il(n,r,u,zn(n))}catch(de){Il(n,r,{then:function(){},status:"rejected",reason:de},zn())}finally{L.p=g,y!==null&&C.types!==null&&(y.types=C.types),A.T=y}}function X1(){}function $h(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:Hr,lastRenderedState:U},next:null};var l={};return r.next={memoizedState:l,baseState:l,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Hr,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),Il(n,r.next.queue,{},zn())}function Fh(){return Ji(io)}function Yg(){return bi().memoizedState}function Kg(){return bi().memoizedState}function Z1(n){for(var r=n.return;r!==null;){switch(r.tag){case 24:case 3:var l=zn();n=gs(l);var u=xs(r,n,l);u!==null&&(wn(u,r,l),Bl(u,r,l)),r={cache:_h()},n.payload=r;return}r=r.return}}function Q1(n,r,l){var u=zn();l={lane:u,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null},_c(n)?Xg(r,l):(l=lh(n,r,l,u),l!==null&&(wn(l,n,u),Zg(l,r,u)))}function Vg(n,r,l){var u=zn();Il(n,r,l,u)}function Il(n,r,l,u){var m={lane:u,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null};if(_c(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 y=r.lastRenderedState,C=g(y,l);if(m.hasEagerState=!0,m.eagerState=C,Rn(C,y))return Qo(n,r,m,0),Zt===null&&Zo(),!1}catch{}finally{}if(l=lh(n,r,m,u),l!==null)return wn(l,n,u),Zg(l,r,u),!0}return!1}function qh(n,r,l,u){if(u={lane:2,revertLane:Sd(),gesture:null,action:u,hasEagerState:!1,eagerState:null,next:null},_c(n)){if(r)throw Error(s(479))}else r=lh(n,l,u,2),r!==null&&wn(r,n,2)}function _c(n){var r=n.alternate;return n===at||r!==null&&r===at}function Xg(n,r){Ua=hc=!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,ce(n,l)}}var Hl={readContext:Ji,use:pc,useCallback:di,useContext:di,useEffect:di,useImperativeHandle:di,useLayoutEffect:di,useInsertionEffect:di,useMemo:di,useReducer:di,useRef:di,useState:di,useDebugValue:di,useDeferredValue:di,useTransition:di,useSyncExternalStore:di,useId:di,useHostTransitionStatus:di,useFormState:di,useActionState:di,useOptimistic:di,useMemoCache:di,useCacheRefresh:di};Hl.useEffectEvent=di;var Qg={readContext:Ji,use:pc,useCallback:function(n,r){return dn().memoizedState=[n,r===void 0?null:r],n},useContext:Ji,useEffect:Lg,useImperativeHandle:function(n,r,l){l=l!=null?l.concat([n]):null,gc(4194308,4,Ig.bind(null,r,n),l)},useLayoutEffect:function(n,r){return gc(4194308,4,n,r)},useInsertionEffect:function(n,r){gc(4,2,n,r)},useMemo:function(n,r){var l=dn();r=r===void 0?null:r;var u=n();if(ra){Ct(!0);try{n()}finally{Ct(!1)}}return l.memoizedState=[u,r],u},useReducer:function(n,r,l){var u=dn();if(l!==void 0){var m=l(r);if(ra){Ct(!0);try{l(r)}finally{Ct(!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,at,n),[u.memoizedState,n]},useRef:function(n){var r=dn();return n={current:n},r.memoizedState=n},useState:function(n){n=zh(n);var r=n.queue,l=Vg.bind(null,at,r);return r.dispatch=l,[n.memoizedState,l]},useDebugValue:Hh,useDeferredValue:function(n,r){var l=dn();return Uh(l,n,r)},useTransition:function(){var n=zh(!1);return n=qg.bind(null,at,n.queue,!0,!1),dn().memoizedState=n,[!1,n]},useSyncExternalStore:function(n,r,l){var u=at,m=dn();if(Nt){if(l===void 0)throw Error(s(407));l=l()}else{if(l=r(),Zt===null)throw Error(s(349));(St&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,Fa(9,{destroy:void 0},vg.bind(null,u,g,l,r),null),l},useId:function(){var n=dn(),r=Zt.identifierPrefix;if(Nt){var l=br,u=_r;l=(u&~(1<<32-He(u)-1)).toString(32)+l,r="_"+r+"R_"+l,l=dc++,0<\/script>",g=g.removeChild(g.firstChild);break;case"select":g=typeof u.is=="string"?y.createElement("select",{is:u.is}):y.createElement("select"),u.multiple?g.multiple=!0:u.size&&(g.size=u.size);break;default:g=typeof u.is=="string"?y.createElement(m,{is:u.is}):y.createElement(m)}}g[ie]=r,g[ve]=u;e:for(y=r.child;y!==null;){if(y.tag===5||y.tag===6)g.appendChild(y.stateNode);else if(y.tag!==4&&y.tag!==27&&y.child!==null){y.child.return=y,y=y.child;continue}if(y===r)break e;for(;y.sibling===null;){if(y.return===null||y.return===r)break e;y=y.return}y.sibling.return=y.return,y=y.sibling}r.stateNode=g;e:switch(tn(g,m,u),m){case"button":case"input":case"select":case"textarea":u=!!u.autoFocus;break e;case"img":u=!0;break e;default:u=!1}u&&$r(r)}}return ii(r),rd(r,r.type,n===null?null:n.memoizedProps,r.pendingProps,l),null;case 6:if(n&&r.stateNode!=null)n.memoizedProps!==u&&$r(r);else{if(typeof u!="string"&&r.stateNode===null)throw Error(s(166));if(n=G.current,Ba(r)){if(n=r.stateNode,l=r.memoizedProps,u=null,m=Qi,m!==null)switch(m.tag){case 27:case 5:u=m.memoizedProps}n[ie]=r,n=!!(n.nodeValue===l||u!==null&&u.suppressHydrationWarning===!0||x_(n.nodeValue,l)),n||fs(r,!0)}else n=Pc(n).createTextNode(u),n[ie]=r,r.stateNode=n}return ii(r),null;case 31:if(l=r.memoizedState,n===null||n.memoizedState!==null){if(u=Ba(r),l!==null){if(n===null){if(!u)throw Error(s(318));if(n=r.memoizedState,n=n!==null?n.dehydrated:null,!n)throw Error(s(557));n[ie]=r}else Zs(),(r.flags&128)===0&&(r.memoizedState=null),r.flags|=4;ii(r),n=!1}else l=ph(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=l),n=!0;if(!n)return r.flags&256?(Bn(r),r):(Bn(r),null);if((r.flags&128)!==0)throw Error(s(558))}return ii(r),null;case 13:if(u=r.memoizedState,n===null||n.memoizedState!==null&&n.memoizedState.dehydrated!==null){if(m=Ba(r),u!==null&&u.dehydrated!==null){if(n===null){if(!m)throw Error(s(318));if(m=r.memoizedState,m=m!==null?m.dehydrated:null,!m)throw Error(s(317));m[ie]=r}else Zs(),(r.flags&128)===0&&(r.memoizedState=null),r.flags|=4;ii(r),m=!1}else m=ph(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=m),m=!0;if(!m)return r.flags&256?(Bn(r),r):(Bn(r),null)}return Bn(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),wc(r,r.updateQueue),ii(r),null);case 4:return xe(),n===null&&Ed(r.stateNode.containerInfo),ii(r),null;case 10:return Pr(r.type),ii(r),null;case 19:if(K(_i),u=r.memoizedState,u===null)return ii(r),null;if(m=(r.flags&128)!==0,g=u.rendering,g===null)if(m)$l(u,!1);else{if(fi!==0||n!==null&&(n.flags&128)!==0)for(n=r.child;n!==null;){if(g=uc(n),g!==null){for(r.flags|=128,$l(u,!1),n=g.updateQueue,r.updateQueue=n,wc(r,n),r.subtreeFlags=0,n=l,l=r.child;l!==null;)Vm(l,n),l=l.sibling;return k(_i,_i.current&1|2),Nt&&Or(r,u.treeForkCount),r.child}n=n.sibling}u.tail!==null&&we()>jc&&(r.flags|=128,m=!0,$l(u,!1),r.lanes=4194304)}else{if(!m)if(n=uc(g),n!==null){if(r.flags|=128,m=!0,n=n.updateQueue,r.updateQueue=n,wc(r,n),$l(u,!0),u.tail===null&&u.tailMode==="hidden"&&!g.alternate&&!Nt)return ii(r),null}else 2*we()-u.renderingStartTime>jc&&l!==536870912&&(r.flags|=128,m=!0,$l(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=we(),n.sibling=null,l=_i.current,k(_i,m?l&1|2:l&1),Nt&&Or(r,u.treeForkCount),n):(ii(r),null);case 22:case 23:return Bn(r),Nh(),u=r.memoizedState!==null,n!==null?n.memoizedState!==null!==u&&(r.flags|=8192):u&&(r.flags|=8192),u?(l&536870912)!==0&&(r.flags&128)===0&&(ii(r),r.subtreeFlags&6&&(r.flags|=8192)):ii(r),l=r.updateQueue,l!==null&&wc(r,l.retryQueue),l=null,n!==null&&n.memoizedState!==null&&n.memoizedState.cachePool!==null&&(l=n.memoizedState.cachePool.pool),u=null,r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(u=r.memoizedState.cachePool.pool),u!==l&&(r.flags|=2048),n!==null&&K(ea),null;case 24:return l=null,n!==null&&(l=n.memoizedState.cache),r.memoizedState.cache!==l&&(r.flags|=2048),Pr(wi),ii(r),null;case 25:return null;case 30:return null}throw Error(s(156,r.tag))}function nw(n,r){switch(dh(r),r.tag){case 1:return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 3:return Pr(wi),xe(),n=r.flags,(n&65536)!==0&&(n&128)===0?(r.flags=n&-65537|128,r):null;case 26:case 27:case 5:return Me(r),null;case 31:if(r.memoizedState!==null){if(Bn(r),r.alternate===null)throw Error(s(340));Zs()}return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 13:if(Bn(r),n=r.memoizedState,n!==null&&n.dehydrated!==null){if(r.alternate===null)throw Error(s(340));Zs()}return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 19:return K(_i),null;case 4:return xe(),null;case 10:return Pr(r.type),null;case 22:case 23:return Bn(r),Nh(),n!==null&&K(ea),n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 24:return Pr(wi),null;case 25:return null;default:return null}}function Sx(n,r){switch(dh(r),r.tag){case 3:Pr(wi),xe();break;case 26:case 27:case 5:Me(r);break;case 4:xe();break;case 31:r.memoizedState!==null&&Bn(r);break;case 13:Bn(r);break;case 19:K(_i);break;case 10:Pr(r.type);break;case 22:case 23:Bn(r),Nh(),n!==null&&K(ea);break;case 24:Pr(wi)}}function Fl(n,r){try{var l=r.updateQueue,u=l!==null?l.lastEffect:null;if(u!==null){var m=u.next;l=m;do{if((l.tag&n)===n){u=void 0;var g=l.create,y=l.inst;u=g(),y.destroy=u}l=l.next}while(l!==m)}}catch(C){$t(r,r.return,C)}}function vs(n,r,l){try{var u=r.updateQueue,m=u!==null?u.lastEffect:null;if(m!==null){var g=m.next;u=g;do{if((u.tag&n)===n){var y=u.inst,C=y.destroy;if(C!==void 0){y.destroy=void 0,m=r;var B=l,Z=C;try{Z()}catch(oe){$t(m,B,oe)}}}u=u.next}while(u!==g)}}catch(oe){$t(r,r.return,oe)}}function wx(n){var r=n.updateQueue;if(r!==null){var l=n.stateNode;try{fg(r,l)}catch(u){$t(n,n.return,u)}}}function Cx(n,r,l){l.props=sa(n.type,n.memoizedProps),l.state=n.memoizedState;try{l.componentWillUnmount()}catch(u){$t(n,r,u)}}function ql(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){$t(n,r,m)}}function vr(n,r){var l=n.ref,u=n.refCleanup;if(l!==null)if(typeof u=="function")try{u()}catch(m){$t(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){$t(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){$t(n,n.return,m)}}function sd(n,r,l){try{var u=n.stateNode;kw(u,n.type,l,r),u[ve]=r}catch(m){$t(n,n.return,m)}}function Ex(n){return n.tag===5||n.tag===3||n.tag===26||n.tag===27&&Ns(n.type)||n.tag===4}function ad(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&&Ns(n.type)||n.flags&2||n.child===null||n.tag===4)continue e;n.child.return=n,n=n.child}if(!(n.flags&2))return n.stateNode}}function ld(n,r,l){var u=n.tag;if(u===5||u===6)n=n.stateNode,r?(l.nodeType===9?l.body:l.nodeName==="HTML"?l.ownerDocument.body:l).insertBefore(n,r):(r=l.nodeType===9?l.body:l.nodeName==="HTML"?l.ownerDocument.body:l,r.appendChild(n),l=l._reactRootContainer,l!=null||r.onclick!==null||(r.onclick=lr));else if(u!==4&&(u===27&&Ns(n.type)&&(l=n.stateNode,r=null),n=n.child,n!==null))for(ld(n,r,l),n=n.sibling;n!==null;)ld(n,r,l),n=n.sibling}function Cc(n,r,l){var u=n.tag;if(u===5||u===6)n=n.stateNode,r?l.insertBefore(n,r):l.appendChild(n);else if(u!==4&&(u===27&&Ns(n.type)&&(l=n.stateNode),n=n.child,n!==null))for(Cc(n,r,l),n=n.sibling;n!==null;)Cc(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]);tn(r,u,l),r[ie]=n,r[ve]=l}catch(g){$t(n,n.return,g)}}var Fr=!1,Ei=!1,od=!1,jx=typeof WeakSet=="function"?WeakSet:Set,Pi=null;function rw(n,r){if(n=n.containerInfo,Td=Wc,n=Hm(n),th(n)){if("selectionStart"in n)var l={start:n.selectionStart,end:n.selectionEnd};else e:{l=(l=n.ownerDocument)&&l.defaultView||window;var u=l.getSelection&&l.getSelection();if(u&&u.rangeCount!==0){l=u.anchorNode;var m=u.anchorOffset,g=u.focusNode;u=u.focusOffset;try{l.nodeType,g.nodeType}catch{l=null;break e}var y=0,C=-1,B=-1,Z=0,oe=0,de=n,Q=null;t:for(;;){for(var re;de!==l||m!==0&&de.nodeType!==3||(C=y+m),de!==g||u!==0&&de.nodeType!==3||(B=y+u),de.nodeType===3&&(y+=de.nodeValue.length),(re=de.firstChild)!==null;)Q=de,de=re;for(;;){if(de===n)break t;if(Q===l&&++Z===m&&(C=y),Q===g&&++oe===u&&(B=y),(re=de.nextSibling)!==null)break;de=Q,Q=de.parentNode}de=re}l=C===-1||B===-1?null:{start:C,end:B}}else l=null}l=l||{start:0,end:0}}else l=null;for(Ad={focusedElem:n,selectionRange:l},Wc=!1,Pi=r;Pi!==null;)if(r=Pi,n=r.child,(r.subtreeFlags&1028)!==0&&n!==null)n.return=r,Pi=n;else for(;Pi!==null;){switch(r=Pi,g=r.alternate,n=r.flags,r.tag){case 0:if((n&4)!==0&&(n=r.updateQueue,n=n!==null?n.events:null,n!==null))for(l=0;l title"))),tn(g,u,l),g[ie]=n,Ht(g),u=g;break e;case"link":var y=B_("link","href",m).get(u+(l.href||""));if(y){for(var C=0;CVt&&(y=Vt,Vt=qe,qe=y);var $=Pm(C,qe),O=Pm(C,Vt);if($&&O&&(re.rangeCount!==1||re.anchorNode!==$.node||re.anchorOffset!==$.offset||re.focusNode!==O.node||re.focusOffset!==O.offset)){var X=de.createRange();X.setStart($.node,$.offset),re.removeAllRanges(),qe>Vt?(re.addRange(X),re.extend(O.node,O.offset)):(X.setEnd(O.node,O.offset),re.addRange(X))}}}}for(de=[],re=C;re=re.parentNode;)re.nodeType===1&&de.push({element:re,left:re.scrollLeft,top:re.scrollTop});for(typeof C.focus=="function"&&C.focus(),C=0;Cl?32:l,A.T=null,l=md,md=null;var g=Cs,y=Kr;if(Di=0,Ka=Cs=null,Kr=0,(Lt&6)!==0)throw Error(s(331));var C=Lt;if(Lt|=4,Ix(g.current),Ox(g,g.current,y,l),Lt=C,Xl(0,!1),At&&typeof At.onPostCommitFiberRoot=="function")try{At.onPostCommitFiberRoot(zt,g)}catch{}return!0}finally{L.p=m,A.T=u,n_(n,r)}}function s_(n,r,l){r=Yn(l,r),r=Kh(n.stateNode,r,2),n=xs(n,r,2),n!==null&&(ct(n,2),yr(n))}function $t(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"&&(ws===null||!ws.has(u))){n=Yn(l,n),l=ax(2),u=xs(r,l,2),u!==null&&(lx(l,u,r,n),ct(u,2),yr(u));break}}r=r.return}}function bd(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)||(hd=!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,Zt===n&&(St&l)===l&&(fi===4||fi===3&&(St&62914560)===St&&300>we()-Nc?(Lt&2)===0&&Va(n,0):dd|=l,Ya===St&&(Ya=0)),yr(n)}function a_(n,r){r===0&&(r=qt()),n=Vs(n,r),n!==null&&(ct(n,r),yr(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 ft(n,r)}var Bc=null,Za=null,vd=!1,Lc=!1,yd=!1,Es=0;function yr(n){n!==Za&&n.next===null&&(Za===null?Bc=Za=n:Za=Za.next=n),Lc=!0,vd||(vd=!0,xw())}function Xl(n,r){if(!yd&&Lc){yd=!0;do for(var l=!1,u=Bc;u!==null;){if(n!==0){var m=u.pendingLanes;if(m===0)var g=0;else{var y=u.suspendedLanes,C=u.pingedLanes;g=(1<<31-He(42|n)+1)-1,g&=m&~(y&~C),g=g&201326741?g&201326741|1:g?g|2:0}g!==0&&(l=!0,u_(u,g))}else g=St,g=Ke(u,u===Zt?g:0,u.cancelPendingCommit!==null||u.timeoutHandle!==-1),(g&3)===0||Xe(u,g)||(l=!0,u_(u,g));u=u.next}while(l);yd=!1}}function gw(){l_()}function l_(){Lc=vd=!1;var n=0;Es!==0&&Nw()&&(n=Es);for(var r=we(),l=null,u=Bc;u!==null;){var m=u.next,g=o_(u,r);g===0?(u.next=null,l===null?Bc=m:l.next=m,m===null&&(Za=l)):(l=u,(n!==0||(g&3)!==0)&&(Lc=!0)),u=m}Di!==0&&Di!==5||Xl(n),Es!==0&&(Es=0)}function o_(n,r){for(var l=n.suspendedLanes,u=n.pingedLanes,m=n.expirationTimes,g=n.pendingLanes&-62914561;0C)break;var oe=B.transferSize,de=B.initiatorType;oe&&__(de)&&(B=B.responseEnd,y+=oe*(B"u"?null:document;function A_(n,r,l){var u=Qa;if(u&&typeof r=="string"&&r){var m=Si(r);m='link[rel="'+n+'"][href="'+m+'"]',typeof l=="string"&&(m+='[crossorigin="'+l+'"]'),T_.has(m)||(T_.add(m),n={rel:n,crossOrigin:l,href:r},u.querySelector(m)===null&&(r=u.createElement("link"),tn(r,"link",n),Ht(r),u.head.appendChild(r)))}}function Ow(n){Vr.D(n),A_("dns-prefetch",n,null)}function zw(n,r){Vr.C(n,r),A_("preconnect",n,r)}function Pw(n,r,l){Vr.L(n,r,l);var u=Qa;if(u&&n&&r){var m='link[rel="preload"][as="'+Si(r)+'"]';r==="image"&&l&&l.imageSrcSet?(m+='[imagesrcset="'+Si(l.imageSrcSet)+'"]',typeof l.imageSizes=="string"&&(m+='[imagesizes="'+Si(l.imageSizes)+'"]')):m+='[href="'+Si(n)+'"]';var g=m;switch(r){case"style":g=Ja(n);break;case"script":g=el(n)}Jn.has(g)||(n=x({rel:"preload",href:r==="image"&&l&&l.imageSrcSet?void 0:n,as:r},l),Jn.set(g,n),u.querySelector(m)!==null||r==="style"&&u.querySelector(eo(g))||r==="script"&&u.querySelector(to(g))||(r=u.createElement("link"),tn(r,"link",n),Ht(r),u.head.appendChild(r)))}}function Iw(n,r){Vr.m(n,r);var l=Qa;if(l&&n){var u=r&&typeof r.as=="string"?r.as:"script",m='link[rel="modulepreload"][as="'+Si(u)+'"][href="'+Si(n)+'"]',g=m;switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":g=el(n)}if(!Jn.has(g)&&(n=x({rel:"modulepreload",href:n},r),Jn.set(g,n),l.querySelector(m)===null)){switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(l.querySelector(to(g)))return}u=l.createElement("link"),tn(u,"link",n),Ht(u),l.head.appendChild(u)}}}function Hw(n,r,l){Vr.S(n,r,l);var u=Qa;if(u&&n){var m=hi(u).hoistableStyles,g=Ja(n);r=r||"default";var y=m.get(g);if(!y){var C={loading:0,preload:null};if(y=u.querySelector(eo(g)))C.loading=5;else{n=x({rel:"stylesheet",href:n,"data-precedence":r},l),(l=Jn.get(g))&&zd(n,l);var B=y=u.createElement("link");Ht(B),tn(B,"link",n),B._p=new Promise(function(Z,oe){B.onload=Z,B.onerror=oe}),B.addEventListener("load",function(){C.loading|=1}),B.addEventListener("error",function(){C.loading|=2}),C.loading|=4,Hc(y,r,u)}y={type:"stylesheet",instance:y,count:1,state:C},m.set(g,y)}}}function Uw(n,r){Vr.X(n,r);var l=Qa;if(l&&n){var u=hi(l).hoistableScripts,m=el(n),g=u.get(m);g||(g=l.querySelector(to(m)),g||(n=x({src:n,async:!0},r),(r=Jn.get(m))&&Pd(n,r),g=l.createElement("script"),Ht(g),tn(g,"link",n),l.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(m,g))}}function $w(n,r){Vr.M(n,r);var l=Qa;if(l&&n){var u=hi(l).hoistableScripts,m=el(n),g=u.get(m);g||(g=l.querySelector(to(m)),g||(n=x({src:n,async:!0,type:"module"},r),(r=Jn.get(m))&&Pd(n,r),g=l.createElement("script"),Ht(g),tn(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=G.current)?Ic(m):null;if(!m)throw Error(s(446));switch(n){case"meta":case"title":return null;case"style":return typeof l.precedence=="string"&&typeof l.href=="string"?(r=Ja(l.href),l=hi(m).hoistableStyles,u=l.get(r),u||(u={type:"style",instance:null,count:0,state:null},l.set(r,u)),u):{type:"void",instance:null,count:0,state:null};case"link":if(l.rel==="stylesheet"&&typeof l.href=="string"&&typeof l.precedence=="string"){n=Ja(l.href);var g=hi(m).hoistableStyles,y=g.get(n);if(y||(m=m.ownerDocument||m,y={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},g.set(n,y),(g=m.querySelector(eo(n)))&&!g._p&&(y.instance=g,y.state.loading=5),Jn.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},Jn.set(n,l),g||Fw(m,n,l,y.state))),r&&u===null)throw Error(s(528,""));return y}if(r&&u!==null)throw Error(s(529,""));return null;case"script":return r=l.async,l=l.src,typeof l=="string"&&r&&typeof r!="function"&&typeof r!="symbol"?(r=el(l),l=hi(m).hoistableScripts,u=l.get(r),u||(u={type:"script",instance:null,count:0,state:null},l.set(r,u)),u):{type:"void",instance:null,count:0,state:null};default:throw Error(s(444,n))}}function Ja(n){return'href="'+Si(n)+'"'}function eo(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}),tn(r,"link",l),Ht(r),n.head.appendChild(r))}function el(n){return'[src="'+Si(n)+'"]'}function to(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~="'+Si(l.href)+'"]');if(u)return r.instance=u,Ht(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"),Ht(u),tn(u,"style",m),Hc(u,l.precedence,n),r.instance=u;case"stylesheet":m=Ja(l.href);var g=n.querySelector(eo(m));if(g)return r.state.loading|=4,r.instance=g,Ht(g),g;u=M_(l),(m=Jn.get(m))&&zd(u,m),g=(n.ownerDocument||n).createElement("link"),Ht(g);var y=g;return y._p=new Promise(function(C,B){y.onload=C,y.onerror=B}),tn(g,"link",u),r.state.loading|=4,Hc(g,l.precedence,n),r.instance=g;case"script":return g=el(l.src),(m=n.querySelector(to(g)))?(r.instance=m,Ht(m),m):(u=l,(m=Jn.get(g))&&(u=x({},l),Pd(u,m)),n=n.ownerDocument||n,m=n.createElement("script"),Ht(m),tn(m,"link",u),n.head.appendChild(m),r.instance=m);case"void":return null;default:throw Error(s(443,r.type))}else r.type==="stylesheet"&&(r.state.loading&4)===0&&(u=r.instance,r.state.loading|=4,Hc(u,l.precedence,n));return r.instance}function Hc(n,r,l){for(var u=l.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),m=u.length?u[u.length-1]:null,g=m,y=0;y title"):null)}function 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=Ja(u.href),g=r.querySelector(eo(m));if(g){r=g._p,r!==null&&typeof r=="object"&&typeof r.then=="function"&&(n.count++,n=$c.bind(n),r.then(n,n)),l.state.loading|=4,l.instance=g,Ht(g);return}g=r.ownerDocument||r,u=M_(u),(m=Jn.get(m))&&zd(u,m),g=g.createElement("link"),Ht(g);var y=g;y._p=new Promise(function(C,B){y.onload=C,y.onerror=B}),tn(g,"link",u),l.instance=g}n.stylesheets===null&&(n.stylesheets=new Map),n.stylesheets.set(l,r),(r=l.state.preload)&&(l.state.loading&3)===0&&(n.count++,l=$c.bind(n),r.addEventListener("load",l),r.addEventListener("error",l))}}var Id=0;function Gw(n,r){return n.stylesheets&&n.count===0&&qc(n,n.stylesheets),0Id?50:800)+r);return n.unsuspend=l,function(){n.unsuspend=null,clearTimeout(u),clearTimeout(m)}}:null}function $c(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)qc(this,this.stylesheets);else if(this.unsuspend){var n=this.unsuspend;this.unsuspend=null,n()}}}var Fc=null;function qc(n,r){n.stylesheets=null,n.unsuspend!==null&&(n.count++,Fc=new Map,r.forEach(Yw,n),Fc=null,$c.call(n))}function Yw(n,r){if(!(r.state.loading&4)){var l=Fc.get(n);if(l)var u=l.get(null);else{l=new Map,Fc.set(n,l);for(var m=n.querySelectorAll("link[data-precedence],style[data-precedence]"),g=0;g"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Kd.exports=uC(),Kd.exports}var dC=hC();const fC=Ou(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 Qd="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,N)=>fetch(E,{...N,headers:{...N==null?void 0:N.headers,Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),[e]),b=w.useCallback(()=>{x(`${Qd}/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(`${Qd}/api/wallet/create`,{method:"POST"}),N=await E.json();if(!E.ok)throw new Error(N.error||"Creation failed");b()}catch(E){_(E instanceof Error?E.message:"Failed to create wallet")}a(!1)},S=async E=>{c(E.walletId||E.name),_(null);try{const N=await x(`${Qd}/api/wallet/active`,{method:"POST",body:JSON.stringify({walletId:E.walletId,name:E.name,address:E.normalizedAddress||E.address})}),z=await N.json();if(!N.ok)throw new Error(z.error||"Wallet switch failed");b()}catch(N){_(N instanceof Error?N.message:"Failed to switch wallet")}c(null)},j=()=>{t!=null&&t.address&&(navigator.clipboard.writeText(t.address),p(!0),setTimeout(()=>p(!1),2e3))},R=E=>`${E.slice(0,6)}...${E.slice(-4)}`;return d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"OWS Wallet"}),!t&&d.jsx("p",{className:"text-muted text-xs",children:"loading..."}),t&&!t.exists&&d.jsxs("div",{className:"space-y-3",children:[d.jsx("p",{className:"text-muted text-xs",children:t.error||"No wallet created yet. Create one to enable autonomous transactions."}),f&&d.jsx("p",{className:"text-error text-xs",children:f}),d.jsx("button",{onClick:v,disabled:s,className:"border-accent text-accent hover:bg-accent/10 disabled:opacity-40 rounded border px-4 py-2 text-xs font-medium transition-colors",children:s?"creating...":"create wallet"})]}),(t==null?void 0:t.selectionRequired)&&t.wallets&&t.wallets.length>0&&d.jsxs("div",{className:"mb-4 space-y-3 rounded border border-amber-600/30 bg-amber-950/10 p-3",children:[d.jsx("p",{className:"text-xs text-amber-700",children:"Multiple OWS wallets found. Select the wallet OWS should use for publishing and signing."}),t.wallets.map(E=>d.jsxs("div",{className:"border-border flex items-center justify-between gap-3 rounded border p-2",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsx("p",{className:"text-foreground truncate text-xs font-medium",children:E.name}),d.jsx("p",{className:"text-muted truncate text-[10px] font-mono",children:E.address||"No EVM address"})]}),d.jsx("button",{onClick:()=>S(E),disabled:!E.address||o===(E.walletId||E.name),className:"border-accent text-accent hover:bg-accent/10 disabled:opacity-40 rounded border px-2 py-1 text-[10px] font-medium transition-colors",children:o===(E.walletId||E.name)?"switching...":"use"})]},E.walletId||E.name)),f&&d.jsx("p",{className:"text-error text-xs",children:f})]}),t&&t.exists&&t.address&&d.jsxs("div",{className:"space-y-3",children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-muted text-[10px] uppercase tracking-wider",children:"Active Wallet (Base)"}),d.jsx("span",{className:`rounded border px-1.5 py-0.5 text-[9px] ${t.ethBalance&&parseFloat(t.ethBalance)>0?"border-accent/30 text-accent":"border-accent-dim/30 text-accent-dim"}`,children:t.ethBalance&&parseFloat(t.ethBalance)>0?"active":"no balance"})]}),t.name&&d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Name"}),d.jsx("span",{className:"text-foreground truncate pl-3 font-mono text-[10px]",children:t.name})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("code",{className:"text-foreground bg-surface rounded px-2 py-1 text-xs font-mono",children:R(t.address)}),d.jsx("button",{onClick:j,className:"text-muted hover:text-accent text-xs transition-colors",children:h?"copied":"copy"})]}),d.jsxs("div",{className:"border-border space-y-1 border-t pt-3",children:[d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"ETH"}),d.jsxs("span",{className:"text-foreground font-medium",children:[t.ethBalance||"0.000000"," ETH"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"USDC"}),d.jsxs("span",{className:"text-foreground font-medium",children:["$",t.usdcBalance||"0.00"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"PLOT"}),d.jsxs("span",{className:"text-foreground font-medium",children:[t.plotBalance||"0.0000"," PLOT"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Network"}),d.jsx("span",{className:"text-foreground",children:"Base"})]})]}),t.wallets&&t.wallets.length>1&&d.jsxs("div",{className:"border-border space-y-2 border-t pt-3",children:[d.jsx("p",{className:"text-muted text-[10px] font-medium uppercase tracking-wider",children:"Switch Wallet"}),t.wallets.map(E=>d.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsxs("p",{className:E.active?"text-accent truncate font-medium":"text-foreground truncate",children:[E.name,E.active?" (active)":""]}),d.jsx("p",{className:"text-muted truncate text-[10px] font-mono",children:E.address||"No EVM address"})]}),!E.active&&d.jsx("button",{onClick:()=>S(E),disabled:!E.address||o===(E.walletId||E.name),className:"border-border text-muted hover:border-accent hover:text-accent disabled:opacity-40 rounded border px-2 py-1 text-[10px] transition-colors",children:o===(E.walletId||E.name)?"...":"use"})]},E.walletId||E.name)),f&&d.jsx("p",{className:"text-error text-xs",children:f})]}),d.jsxs("div",{className:"border-border border-t pt-3",children:[d.jsx("p",{className:"text-muted mb-2 text-[10px] font-medium uppercase tracking-wider",children:"Fund Wallet"}),d.jsx("p",{className:"text-muted text-[10px]",children:"Send ETH on Base for gas (~$0.01 per publish):"}),d.jsx("code",{className:"text-foreground bg-surface mt-1 block break-all rounded px-2 py-1.5 text-[10px] font-mono",children:t.address})]})]}),(t==null?void 0:t.exists)&&d.jsx("button",{onClick:v,disabled:s,className:"border-border text-muted hover:border-accent hover:text-accent disabled:opacity-40 mt-4 rounded border px-3 py-1.5 text-[10px] font-medium transition-colors",children:s?"creating...":"create another wallet"})]})}function ku(e){return!!e&&e.codex.installed&&e.codex.auth==="unknown"}const Ip="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),[S,j]=w.useState("AI Writer"),[R,E]=w.useState(""),[N,z]=w.useState(""),[J,F]=w.useState(!1),[M,ee]=w.useState(null),[fe,ye]=w.useState(""),[P,ae]=w.useState(null),[W,Y]=w.useState(!1),[V,I]=w.useState(null),[A,L]=w.useState(null),[U,ge]=w.useState(null),T=w.useCallback((te,G)=>fetch(te,{...G,headers:{...G==null?void 0:G.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&&ge(te)}).catch(()=>{})},[]);const D=async()=>{if(!S.trim()){ee("Agent name is required");return}if(!R.trim()){ee("Description is required");return}F(!0),ee(null);try{const te=await T("/api/settings/register-agent",{method:"POST",body:JSON.stringify({name:S,description:R,...N.trim()&&{genre:N}})}),G=await te.json();if(!te.ok)throw new Error(G.error||"Registration failed");v({linked:!0,agentId:G.agentId,owsWallet:G.owsWallet,txHash:G.txHash})}catch(te){ee(te instanceof Error?te.message:"Registration failed")}F(!1)},K=async()=>{if(!fe.trim()||!/^0x[a-fA-F0-9]{40}$/.test(fe)){I("Enter a valid wallet address (0x...)");return}Y(!0),I(null),ae(null);try{const te=await T("/api/settings/generate-binding",{method:"POST",body:JSON.stringify({humanWallet:fe})}),G=await te.json();if(!te.ok)throw new Error(G.error||"Failed to generate binding code");ae(G)}catch(te){I(te instanceof Error?te.message:"Failed to generate binding code")}Y(!1)},k=async(te,G)=>{await navigator.clipboard.writeText(te),L(G),setTimeout(()=>L(null),2e3)},ue=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 te=await T("/api/auth/reset-passphrase",{method:"POST",body:JSON.stringify({passphrase:i})});if(!te.ok){const G=await te.json();throw new Error(G.error||"Reset failed")}f(!0),s(""),o(""),setTimeout(()=>f(!1),3e3)}catch(te){h(te instanceof Error?te.message:"Reset failed")}x(!1)};return d.jsxs("div",{className:"mx-auto max-w-lg space-y-6 p-6",children:[d.jsx("h2",{className:"text-accent text-lg font-bold",children:"Settings"}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Agent Identity"}),b!=null&&b.linked?d.jsxs("div",{className:"space-y-2",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"text-sm font-medium text-accent",children:"Registered"}),d.jsxs("span",{className:"text-muted text-xs",children:["Agent #",b.agentId]})]}),b.owsWallet&&d.jsxs("p",{className:"text-muted text-xs font-mono",children:["Wallet: ",b.owsWallet.slice(0,6),"...",b.owsWallet.slice(-4)]}),b.owner&&d.jsxs("p",{className:"text-muted text-xs font-mono",children:["Owner: ",b.owner.slice(0,6),"...",b.owner.slice(-4)]}),b.txHash&&d.jsx("p",{className:"text-muted text-xs",children:d.jsx("a",{href:`https://basescan.org/tx/${b.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View transaction on BaseScan"})}),d.jsx("p",{className:"text-muted text-xs",children:d.jsx("a",{href:`https://plotlink.xyz/profile/${b.owsWallet}`,target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View agent profile on plotlink.xyz"})})]}):d.jsxs("div",{className:"space-y-3",children:[d.jsx("p",{className:"text-muted text-xs",children:"Register this AI writer on-chain via ERC-8004. Uses your OWS wallet's existing ETH balance for gas."}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Name"}),d.jsx("input",{value:S,onChange:te=>j(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"})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Description"}),d.jsx("input",{value:R,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"})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Genre (optional)"}),d.jsx("input",{value:N,onChange:te=>z(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"})]}),M&&d.jsx("p",{className:"text-error text-xs",children:M}),d.jsx("button",{onClick:D,disabled:J||!S.trim()||!R.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"})]})]}),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":"—"})]}),ku(U)&&d.jsx("p",{className:"text-[11px] text-amber-700","data-testid":"codex-auth-unknown-settings",children:Ip}),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:fe,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"}),V&&d.jsx("p",{className:"text-error text-xs",children:V}),d.jsx("button",{onClick:K,disabled:W||!fe.trim(),className:"bg-accent text-white hover:bg-accent-dim disabled:opacity-50 w-full rounded px-4 py-2 text-sm font-medium transition-colors",children:W?"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:()=>k(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:()=>k(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:()=>k(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: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"}),d.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&&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:ue,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),S=w.useCallback(async()=>{try{const F=await e("/api/stories");if(F.ok){const M=await F.json();h(M.stories)}}catch{}},[e]),j=w.useCallback(async()=>{try{const F=await e("/api/stories/archived");if(F.ok){const M=await F.json();f(M.stories)}}catch{}},[e]),R=w.useCallback(async F=>{try{(await e("/api/stories/restore",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:F})})).ok&&(j(),S())}catch{}},[e,j,S]);w.useEffect(()=>{S();const F=setInterval(S,5e3);return()=>clearInterval(F)},[S]),w.useEffect(()=>{b&&j()},[b,j]),w.useEffect(()=>{t&&x(F=>new Set(F).add(t))},[t]);const E=F=>{x(M=>{const ee=new Set(M);return ee.has(F)?ee.delete(F):ee.add(F),ee})},N=F=>{var ee;const M=F.map(fe=>{var ye;return{file:fe.file,num:(ye=fe.file.match(/^plot-(\d+)\.md$/))==null?void 0:ye[1]}}).filter(fe=>fe.num!=null).sort((fe,ye)=>parseInt(ye.num)-parseInt(fe.num));return M.length>0?M[0].file:F.some(fe=>fe.file==="genesis.md")?"genesis.md":F.some(fe=>fe.file==="structure.md")?"structure.md":((ee=F[0])==null?void 0:ee.file)??null},z=F=>{if(E(F.name),F.contentType==="cartoon")s(F.name,"");else{const M=N(F.files);M&&s(F.name,M)}},J=F=>{const M=ee=>{if(ee==="structure.md")return 0;if(ee==="genesis.md")return 1;const fe=ee.match(/^plot-(\d+)\.md$/);return fe?2+parseInt(fe[1]):100};return[...F].sort((ee,fe)=>M(ee.file)-M(fe.file))};return b?d.jsxs("div",{className:"h-full flex flex-col",children:[d.jsxs("div",{className:"px-3 py-1.5 border-b border-border flex items-center justify-between",children:[d.jsx("span",{className:"text-xs font-mono text-muted",children:"Archives"}),d.jsx("span",{className:"text-xs text-muted",children:p.length})]}),d.jsx("div",{className:"px-3 py-2 border-b border-border",children:d.jsxs("button",{onClick:()=>v(!1),className:"w-full px-3 py-1.5 text-sm text-muted hover:text-foreground hover:bg-surface rounded flex items-center gap-1.5",children:[d.jsx("span",{children:"←"}),d.jsx("span",{children:"Back"})]})}),d.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:p.length===0?d.jsx("div",{className:"p-3 text-sm text-muted",children:d.jsx("p",{children:"No archived stories."})}):p.map(F=>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:F.name,children:F.title||F.name}),d.jsx("button",{onClick:()=>R(F.name),className:"text-xs text-accent hover:text-accent-dim flex-shrink-0 ml-2",children:"Restore"})]},F.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(F=>d.jsx("div",{children:d.jsxs("button",{onClick:()=>s(F,""),className:`w-full px-3 py-2 text-left flex items-center gap-2 hover:bg-surface text-sm ${t===F?"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"})]})},F)),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(F=>F.name!=="_example").map(F=>d.jsxs("div",{children:[d.jsxs("button",{onClick:()=>z(F),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(F.name)?"▼":"▶"}),d.jsx("span",{className:"font-medium truncate",title:F.name,children:F.title||F.name}),F.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:[F.publishedCount,"/",F.files.length]})]}),_.has(F.name)&&d.jsx("div",{className:"pl-4",children:J(F.files).map(M=>{const ee=t===F.name&&i===M.file;return d.jsxs("button",{onClick:()=>s(F.name,M.file),className:`w-full px-3 py-1.5 text-left flex items-center gap-2 text-xs hover:bg-surface ${ee?"bg-surface font-medium":""}`,children:[d.jsx("span",{className:vC[M.status],children:bC[M.status]}),d.jsx("span",{className:"truncate font-mono",children:M.file})]},M.file)})})]},F.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})},gi=(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},je=(e,t)=>(i,s)=>t(i,s,e),ab="Terminal input",If={get:()=>ab,set:e=>ab=e},lb="Too much output to announce, navigate to rows manually to read",Hf={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 zs(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function zu(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 jC=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}},TC=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let i=e.length;if(!i)return 0;let s=0,a,o,c,h,p=0,f=0;if(this.interim[0]){let b=!1,v=this.interim[0];v&=(v&224)===192?31:(v&240)===224?15:7;let S=0,j;for(;(j=this.interim[++S]&63)&&S<4;)v<<=6,v|=j;let R=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,E=R-S;for(;f=i)return 0;if(j=e[f++],(j&192)!==128){f--,b=!0;break}else this.interim[S++]=j,v<<=6,v|=j&63}b||(R===2?v<128?f--:t[s++]=v:R===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}},jy="",Is=" ",Oo=class Ty{constructor(){this.fg=0,this.bg=0,this.extended=new Eu}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 Ty;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}},Eu=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}},sr=class Ry extends Oo{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new Eu,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?zs(this.content&2097151):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(t){this.fg=t[0],this.bg=0;let i=!1;if(t[1].length>2)i=!0;else if(t[1].length===2){let s=t[1].charCodeAt(0);if(55296<=s&&s<=56319){let a=t[1].charCodeAt(1);56320<=a&&a<=57343?this.content=(s-55296)*1024+a-56320+65536|t[2]<<22:i=!0}else i=!0}else this.content=t[1].charCodeAt(0)|t[2]<<22;i&&(this.combinedData=t[1],this.content=2097152|t[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},cb="di$target",Uf="di$dependencies",Jd=new Map;function AC(e){return e[Uf]||[]}function Yi(e){if(Jd.has(e))return Jd.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,Jd.set(e,t),t}function RC(e,t,i){t[cb]===t?t[Uf].push({id:e,index:i}):(t[Uf]=[{id:e,index:i}],t[cb]=t)}var gn=Yi("BufferService"),My=Yi("CoreMouseService"),ba=Yi("CoreService"),MC=Yi("CharsetService"),Hp=Yi("InstantiationService"),Dy=Yi("LogService"),xn=Yi("OptionsService"),By=Yi("OscLinkService"),DC=Yi("UnicodeService"),zo=Yi("DecorationService"),$f=class{constructor(e,t,i){this._bufferService=e,this._optionsService=t,this._oscLinkService=i}provideLinks(e,t){var _;let i=this._bufferService.buffer.lines.get(e-1);if(!i){t(void 0);return}let s=[],a=this._optionsService.rawOptions.linkHandler,o=new sr,c=i.getTrimmedLength(),h=-1,p=-1,f=!1;for(let x=0;xa?a.activate(j,R,v):BC(j,R),hover:(j,R)=>{var E;return(E=a==null?void 0:a.hover)==null?void 0:E.call(a,j,R,v)},leave:(j,R)=>{var E;return(E=a==null?void 0:a.leave)==null?void 0:E.call(a,j,R,v)}})}f=!1,o.hasExtendedAttrs()&&o.extended.urlId?(p=x,h=o.extended.urlId):(p=-1,h=-1)}}t(s)}};$f=gi([je(0,gn),je(1,xn),je(2,By)],$f);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 Pu=Yi("CharSizeService"),ts=Yi("CoreBrowserService"),Up=Yi("MouseService"),is=Yi("RenderService"),LC=Yi("SelectionService"),Ly=Yi("CharacterJoinerService"),gl=Yi("ThemeService"),Oy=Yi("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 pu(e){PC(e)||zC.onUnexpectedError(e)}var Ff="Canceled";function PC(e){return e instanceof IC?!0:e instanceof Error&&e.name===Ff&&e.message===Ff}var IC=class extends Error{constructor(){super(Ff),this.name=this.message}};function HC(e){return new Error(`Illegal argument: ${e}`)}var ub=class qf extends Error{constructor(t){super(t),this.name="CodeExpectedError"}static fromError(t){if(t instanceof qf)return t;let i=new qf;return i.message=t.message,i.stack=t.stack,i}static isErrorNoTelemetry(t){return t.name==="CodeExpectedError"}},Wf=class zy extends Error{constructor(t){super(t||"An unexpected bug occurred."),Object.setPrototypeOf(this,zy.prototype)}};function Pn(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(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 F=J.length-1;F>=0;F--)yield J[F]}e.reverse=h;function p(J){return!J||J[Symbol.iterator]().next().done===!0}e.isEmpty=p;function f(J){return J[Symbol.iterator]().next().value}e.first=f;function _(J,F){let M=0;for(let ee of J)if(F(ee,M++))return!0;return!1}e.some=_;function x(J,F){for(let M of J)if(F(M))return M}e.find=x;function*b(J,F){for(let M of J)F(M)&&(yield M)}e.filter=b;function*v(J,F){let M=0;for(let ee of J)yield F(ee,M++)}e.map=v;function*S(J,F){let M=0;for(let ee of J)yield*F(ee,M++)}e.flatMap=S;function*j(...J){for(let F of J)yield*F}e.concat=j;function R(J,F,M){let ee=M;for(let fe of J)ee=F(ee,fe);return ee}e.reduce=R;function*E(J,F,M=J.length){for(F<0&&(F+=J.length),M<0?M+=J.length:M>J.length&&(M=J.length);F1)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 ai(()=>ga(e))}function ai(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{ga(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw new Error("Cannot register a disposable on itself!");return this._isDisposed?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 Hs=Iy,dt=class{constructor(){this._store=new Hs,this._store}dispose(){this._store.dispose()}_register(t){if(t===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(t)}};dt.None=Object.freeze({dispose(){}});var fl=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){var t;this._isDisposed||e===this._value||((t=this._value)==null||t.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){var e;this._isDisposed=!0,(e=this._value)==null||e.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e}},es=typeof window=="object"?window:globalThis,Gf=class Yf{constructor(t){this.element=t,this.next=Yf.Undefined,this.prev=Yf.Undefined}};Gf.Undefined=new Gf(void 0);var oi=Gf,hb=class{constructor(){this._first=oi.Undefined,this._last=oi.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===oi.Undefined}clear(){let e=this._first;for(;e!==oi.Undefined;){let t=e.next;e.prev=oi.Undefined,e.next=oi.Undefined,e=t}this._first=oi.Undefined,this._last=oi.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let i=new oi(e);if(this._first===oi.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!==oi.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==oi.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==oi.Undefined&&e.next!==oi.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===oi.Undefined&&e.next===oi.Undefined?(this._first=oi.Undefined,this._last=oi.Undefined):e.next===oi.Undefined?(this._last=this._last.prev,this._last.next=oi.Undefined):e.prev===oi.Undefined&&(this._first=this._first.next,this._first.prev=oi.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==oi.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}},sn;(e=>{e.None=()=>dt.None;function t(W,Y){return x(W,()=>{},0,void 0,!0,void 0,Y)}e.defer=t;function i(W){return(Y,V=null,I)=>{let A=!1,L;return L=W(U=>{if(!A)return L?L.dispose():A=!0,Y.call(V,U)},null,I),A&&L.dispose(),L}}e.once=i;function s(W,Y,V){return f((I,A=null,L)=>W(U=>I.call(A,Y(U)),null,L),V)}e.map=s;function a(W,Y,V){return f((I,A=null,L)=>W(U=>{Y(U),I.call(A,U)},null,L),V)}e.forEach=a;function o(W,Y,V){return f((I,A=null,L)=>W(U=>Y(U)&&I.call(A,U),null,L),V)}e.filter=o;function c(W){return W}e.signal=c;function h(...W){return(Y,V=null,I)=>{let A=FC(...W.map(L=>L(U=>Y.call(V,U))));return _(A,I)}}e.any=h;function p(W,Y,V,I){let A=V;return s(W,L=>(A=Y(A,L),A),I)}e.reduce=p;function f(W,Y){let V,I={onWillAddFirstListener(){V=W(A.fire,A)},onDidRemoveLastListener(){V==null||V.dispose()}},A=new Se(I);return Y==null||Y.add(A),A.event}function _(W,Y){return Y instanceof Array?Y.push(W):Y&&Y.add(W),W}function x(W,Y,V=100,I=!1,A=!1,L,U){let ge,T,D,K=0,k,ue={leakWarningThreshold:L,onWillAddFirstListener(){ge=W(G=>{K++,T=Y(T,G),I&&!D&&(te.fire(T),T=void 0),k=()=>{let H=T;T=void 0,D=void 0,(!I||K>1)&&te.fire(H),K=0},typeof V=="number"?(clearTimeout(D),D=setTimeout(k,V)):D===void 0&&(D=0,queueMicrotask(k))})},onWillRemoveListener(){A&&K>0&&(k==null||k())},onDidRemoveLastListener(){k=void 0,ge.dispose()}},te=new Se(ue);return U==null||U.add(te),te.event}e.debounce=x;function b(W,Y=0,V){return e.debounce(W,(I,A)=>I?(I.push(A),I):[A],Y,void 0,!0,void 0,V)}e.accumulate=b;function v(W,Y=(I,A)=>I===A,V){let I=!0,A;return o(W,L=>{let U=I||!Y(L,A);return I=!1,A=L,U},V)}e.latch=v;function S(W,Y,V){return[e.filter(W,Y,V),e.filter(W,I=>!Y(I),V)]}e.split=S;function j(W,Y=!1,V=[],I){let A=V.slice(),L=W(T=>{A?A.push(T):ge.fire(T)});I&&I.add(L);let U=()=>{A==null||A.forEach(T=>ge.fire(T)),A=null},ge=new Se({onWillAddFirstListener(){L||(L=W(T=>ge.fire(T)),I&&I.add(L))},onDidAddFirstListener(){A&&(Y?setTimeout(U):U())},onDidRemoveLastListener(){L&&L.dispose(),L=null}});return I&&I.add(ge),ge.event}e.buffer=j;function R(W,Y){return(V,I,A)=>{let L=Y(new N);return W(function(U){let ge=L.evaluate(U);ge!==E&&V.call(I,ge)},void 0,A)}}e.chain=R;let E=Symbol("HaltChainable");class N{constructor(){this.steps=[]}map(Y){return this.steps.push(Y),this}forEach(Y){return this.steps.push(V=>(Y(V),V)),this}filter(Y){return this.steps.push(V=>Y(V)?V:E),this}reduce(Y,V){let I=V;return this.steps.push(A=>(I=Y(I,A),I)),this}latch(Y=(V,I)=>V===I){let V=!0,I;return this.steps.push(A=>{let L=V||!Y(A,I);return V=!1,I=A,L?A:E}),this}evaluate(Y){for(let V of this.steps)if(Y=V(Y),Y===E)break;return Y}}function z(W,Y,V=I=>I){let I=(...ge)=>U.fire(V(...ge)),A=()=>W.on(Y,I),L=()=>W.removeListener(Y,I),U=new Se({onWillAddFirstListener:A,onDidRemoveLastListener:L});return U.event}e.fromNodeEventEmitter=z;function J(W,Y,V=I=>I){let I=(...ge)=>U.fire(V(...ge)),A=()=>W.addEventListener(Y,I),L=()=>W.removeEventListener(Y,I),U=new Se({onWillAddFirstListener:A,onDidRemoveLastListener:L});return U.event}e.fromDOMEventEmitter=J;function F(W){return new Promise(Y=>i(W)(Y))}e.toPromise=F;function M(W){let Y=new Se;return W.then(V=>{Y.fire(V)},()=>{Y.fire(void 0)}).finally(()=>{Y.dispose()}),Y.event}e.fromPromise=M;function ee(W,Y){return W(V=>Y.fire(V))}e.forward=ee;function fe(W,Y,V){return Y(V),W(I=>Y(I))}e.runAndSubscribe=fe;class ye{constructor(Y,V){this._observable=Y,this._counter=0,this._hasChanged=!1;let I={onWillAddFirstListener:()=>{Y.addObserver(this)},onDidRemoveLastListener:()=>{Y.removeObserver(this)}};this.emitter=new Se(I),V&&V.add(this.emitter)}beginUpdate(Y){this._counter++}handlePossibleChange(Y){}handleChange(Y,V){this._hasChanged=!0}endUpdate(Y){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function P(W,Y){return new ye(W,Y).emitter.event}e.fromObservable=P;function ae(W){return(Y,V,I)=>{let A=0,L=!1,U={beginUpdate(){A++},endUpdate(){A--,A===0&&(W.reportChanges(),L&&(L=!1,Y.call(V)))},handlePossibleChange(){},handleChange(){L=!0}};W.addObserver(U),W.reportChanges();let ge={dispose(){W.removeObserver(U)}};return I instanceof Hs?I.add(ge):Array.isArray(I)&&I.push(ge),ge}}e.fromObservableLight=ae})(sn||(sn={}));var Kf=class Vf{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${Vf._idPool++}`,Vf.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}}};Kf.all=new Set,Kf._idPool=0;var GC=Kf,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],S=new ZC(`${b}. HINT: Stack shows most frequent listener (${v[1]}-times)`,v[0]);return(((h=this._options)==null?void 0:h.onListenerError)||pu)(S),dt.None}if(this._disposed)return dt.None;i&&(t=t.bind(i));let a=new ef(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 ef?(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=ai(()=>{o==null||o(),this._removeListener(a)});return s instanceof Hs?s.add(c):Array.isArray(s)&&s.push(c),c}),this._event}_removeListener(t){var o,c,h,p;if((c=(o=this._options)==null?void 0:o.onWillRemoveListener)==null||c.call(o,this),!this._listeners)return;if(this._size===1){this._listeners=void 0,(p=(h=this._options)==null?void 0:h.onDidRemoveLastListener)==null||p.call(h,this),this._size=0;return}let i=this._listeners,s=i.indexOf(t);if(s===-1)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),new Error("Attempted to dispose unknown listener");this._size--,i[s]=void 0;let a=this._deliveryQueue.current===this;if(this._size*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}},Xf=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new Se,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new Se,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}};Xf.INSTANCE=new Xf;var $p=Xf;function ik(e,t,i){typeof t=="string"&&(t=e.matchMedia(t)),t.addEventListener("change",i)}$p.INSTANCE.onDidChangeZoomLevel;function nk(e){return $p.INSTANCE.getZoomFactor(e)}$p.INSTANCE.onDidChangeFullscreen;var xl=typeof navigator=="object"?navigator.userAgent:"",Zf=xl.indexOf("Firefox")>=0,rk=xl.indexOf("AppleWebKit")>=0,Fp=xl.indexOf("Chrome")>=0,sk=!Fp&&xl.indexOf("Safari")>=0;xl.indexOf("Electron/")>=0;xl.indexOf("Android")>=0;var tf=!1;if(typeof es.matchMedia=="function"){let e=es.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)"),t=es.matchMedia("(display-mode: fullscreen)");tf=e.matches,ik(es,e,({matches:i})=>{tf&&t.matches||(tf=i)})}var cl="en",Qf=!1,Jf=!1,mu=!1,Wy=!1,Qc,gu=cl,db=cl,ak,dr,ma=globalThis,rn,yy;typeof ma.vscode<"u"&&typeof ma.vscode.process<"u"?rn=ma.vscode.process:typeof process<"u"&&typeof((yy=process==null?void 0:process.versions)==null?void 0:yy.node)=="string"&&(rn=process);var Sy,lk=typeof((Sy=rn==null?void 0:rn.versions)==null?void 0:Sy.electron)=="string",ok=lk&&(rn==null?void 0:rn.type)==="renderer",wy;if(typeof rn=="object"){Qf=rn.platform==="win32",Jf=rn.platform==="darwin",mu=rn.platform==="linux",mu&&rn.env.SNAP&&rn.env.SNAP_REVISION,rn.env.CI||rn.env.BUILD_ARTIFACTSTAGINGDIRECTORY,Qc=cl,gu=cl;let e=rn.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);Qc=t.userLocale,db=t.osLocale,gu=t.resolvedLanguage||cl,ak=(wy=t.languagePack)==null?void 0:wy.translationsConfigFile}catch{}Wy=!0}else typeof navigator=="object"&&!ok?(dr=navigator.userAgent,Qf=dr.indexOf("Windows")>=0,Jf=dr.indexOf("Macintosh")>=0,(dr.indexOf("Macintosh")>=0||dr.indexOf("iPad")>=0||dr.indexOf("iPhone")>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0,mu=dr.indexOf("Linux")>=0,(dr==null?void 0:dr.indexOf("Mobi"))>=0,gu=globalThis._VSCODE_NLS_LANGUAGE||cl,Qc=navigator.language.toLowerCase(),db=Qc):console.error("Unable to resolve platform.");var Gy=Qf,jr=Jf,ck=mu,fb=Wy,Tr=dr,Ds=gu,uk;(e=>{function t(){return Ds}e.value=t;function i(){return Ds.length===2?Ds==="en":Ds.length>=3?Ds[0]==="e"&&Ds[1]==="n"&&Ds[2]==="-":!1}e.isDefaultVariant=i;function s(){return Ds==="en"}e.isDefault=s})(uk||(uk={}));var hk=typeof ma.postMessage=="function"&&!ma.importScripts;(()=>{if(hk){let e=[];ma.addEventListener("message",i=>{if(i.data&&i.data.vscodeScheduleAsyncWork)for(let s=0,a=e.length;s{let s=++t;e.push({id:s,callback:i}),ma.postMessage({vscodeScheduleAsyncWork:s},"*")}}return e=>setTimeout(e)})();var 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 il=typeof navigator=="object"?navigator:{};fb||document.queryCommandSupported&&document.queryCommandSupported("copy")||il&&il.clipboard&&il.clipboard.writeText,fb||il&&il.clipboard&&il.clipboard.readText;var qp=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}},nf=new qp,pb=new qp,mb=new qp,fk=new Array(230),Yy;(e=>{function t(h){return nf.keyCodeToStr(h)}e.toString=t;function i(h){return nf.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 nf.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:sn.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 Se),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}},Wp=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 Wf("Calling 'cancelAndSet' on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new Wf("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 Wf("Calling 'cancelAndSet' on a disposed IntervalTimer");this.cancel();let s=i.setInterval(()=>{e()},t);this.disposable=ai(()=>{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 tr{static fromArray(t){return new tr(i=>{i.emitMany(t)})}static fromPromise(t){return new tr(async i=>{i.emitMany(await t)})}static fromPromises(t){return new tr(async i=>{await Promise.all(t.map(async s=>i.emitOne(await s)))})}static merge(t){return new tr(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 Se,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 tr(async s=>{for await(let a of t)s.emitOne(i(a))})}map(t){return tr.map(this,t)}static filter(t,i){return new tr(async s=>{for await(let a of t)i(a)&&s.emitOne(a)})}filter(t){return tr.filter(this,t)}static coalesce(t){return tr.filter(t,i=>!!i)}coalesce(){return tr.coalesce(this)}static async toPromise(t){let i=[];for await(let s of t)i.push(s);return i}toPromise(){return tr.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:Er,getWindowId:Nk,onDidRegisterWindow:jk}=(function(){let e=new Map,t={window:es,disposables:new Hs};e.set(es.vscodeWindowId,t);let i=new Se,s=new Se,a=new Se;function o(c,h){return(typeof c=="number"?e.get(c):void 0)??(h?t:void 0)}return{onDidRegisterWindow:i.event,onWillUnregisterWindow:a.event,onDidUnregisterWindow:s.event,registerWindow(c){if(e.has(c.vscodeWindowId))return dt.None;let h=new Hs,p={window:c,disposables:h.add(new Hs)};return e.set(c.vscodeWindowId,p),h.add(ai(()=>{e.delete(c.vscodeWindowId),s.fire(c)})),h.add(Ve(c,Ii.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:es},getDocument(c){return Er(c).document}}})(),Tk=class{constructor(e,t,i,s){this._node=e,this._type=t,this._handler=i,this._options=s||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,this._handler=null)}};function Ve(e,t,i,s){return new Tk(e,t,i,s)}var vb=function(e,t,i,s){return Ve(e,t,i,s)},Gp,Ak=class extends kk{constructor(e){super(),this.defaultTarget=e&&Er(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){pu(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)};Gp=(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=Er(e);return{left:t.left+i.scrollX,top:t.top+i.scrollY,width:t.width,height:t.height}}var Ii={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=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 ko(e){return new Mk(e)}var Xy=class{constructor(){this._hooks=new Hs,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(e,t){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let i=this._onStopCallback;this._onStopCallback=null,e&&i&&i(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,i,s,a){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=s,this._onStopCallback=a;let o=e;try{e.setPointerCapture(t),this._hooks.add(ai(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{o=Er(e)}this._hooks.add(Ve(o,Ii.POINTER_MOVE,c=>{if(c.buttons!==i){this.stopMonitoring(!0);return}c.preventDefault(),this._pointerMoveCallback(c)})),this._hooks.add(Ve(o,Ii.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 Cr;(e=>(e.Tap="-xterm-gesturetap",e.Change="-xterm-gesturechange",e.Start="-xterm-gesturestart",e.End="-xterm-gesturesend",e.Contextmenu="-xterm-gesturecontextmenu"))(Cr||(Cr={}));var vo=class on extends dt{constructor(){super(),this.dispatched=!1,this.targets=new hb,this.ignoreTargets=new hb,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(sn.runAndSubscribe(jk,({window:t,disposables:i})=>{i.add(Ve(t.document,"touchstart",s=>this.onTouchStart(s),{passive:!1})),i.add(Ve(t.document,"touchend",s=>this.onTouchEnd(t,s))),i.add(Ve(t.document,"touchmove",s=>this.onTouchMove(s),{passive:!1}))},{window:es,disposables:this._store}))}static addTarget(t){if(!on.isTouchDevice())return dt.None;on.INSTANCE||(on.INSTANCE=new on);let i=on.INSTANCE.targets.push(t);return ai(i)}static ignoreTarget(t){if(!on.isTouchDevice())return dt.None;on.INSTANCE||(on.INSTANCE=new on);let i=on.INSTANCE.ignoreTargets.push(t);return ai(i)}static isTouchDevice(){return"ontouchstart"in es||navigator.maxTouchPoints>0}dispose(){this.handle&&(this.handle.dispose(),this.handle=null),super.dispose()}onTouchStart(t){let i=Date.now();this.handle&&(this.handle.dispose(),this.handle=null);for(let s=0,a=t.targetTouches.length;s=on.HOLD_DELAY&&Math.abs(p.initialPageX-Pn(p.rollingPageX))<30&&Math.abs(p.initialPageY-Pn(p.rollingPageY))<30){let _=this.newGestureEvent(Cr.Contextmenu,p.initialTarget);_.pageX=Pn(p.rollingPageX),_.pageY=Pn(p.rollingPageY),this.dispatchEvent(_)}else if(a===1){let _=Pn(p.rollingPageX),x=Pn(p.rollingPageY),b=Pn(p.rollingTimestamps)-p.rollingTimestamps[0],v=_-p.rollingPageX[0],S=x-p.rollingPageY[0],j=[...this.targets].filter(R=>p.initialTarget instanceof Node&&R.contains(p.initialTarget));this.inertia(t,j,s,Math.abs(v)/b,v>0?1:-1,_,Math.abs(S)/b,S>0?1:-1,x)}this.dispatchEvent(this.newGestureEvent(Cr.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===Cr.Tap){let i=new Date().getTime(),s=0;i-this._lastSetTapCountTime>on.CLEAR_TAP_COUNT_TIME?s=1:s=2,this._lastSetTapCountTime=i,t.tapCount=s}else(t.type===Cr.Change||t.type===Cr.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=Gp(t,()=>{let _=Date.now(),x=_-s,b=0,v=0,S=!0;a+=on.SCROLL_FRICTION*x,h+=on.SCROLL_FRICTION*x,a>0&&(S=!1,b=o*a*x),h>0&&(S=!1,v=p*h*x);let j=this.newGestureEvent(Cr.Change);j.translationX=b,j.translationY=v,i.forEach(R=>R.dispatchEvent(j)),S||this.inertia(t,i,_,a,o,c+b,h,p,f+v)})}onTouchMove(t){let i=Date.now();for(let s=0,a=t.changedTouches.length;s3&&(c.rollingPageX.shift(),c.rollingPageY.shift(),c.rollingTimestamps.shift()),c.rollingPageX.push(o.pageX),c.rollingPageY.push(o.pageY),c.rollingTimestamps.push(i)}this.dispatched&&(t.preventDefault(),t.stopPropagation(),this.dispatched=!1)}};vo.SCROLL_FRICTION=-.005,vo.HOLD_DELAY=700,vo.CLEAR_TAP_COUNT_TIME=400,gi([Dk],vo,"isTouchDevice",1);var Bk=vo,Yp=class extends dt{onclick(e,t){this._register(Ve(e,Ii.CLICK,i=>t(new Jc(Er(e),i))))}onmousedown(e,t){this._register(Ve(e,Ii.MOUSE_DOWN,i=>t(new Jc(Er(e),i))))}onmouseover(e,t){this._register(Ve(e,Ii.MOUSE_OVER,i=>t(new Jc(Er(e),i))))}onmouseleave(e,t){this._register(Ve(e,Ii.MOUSE_LEAVE,i=>t(new Jc(Er(e),i))))}onkeydown(e,t){this._register(Ve(e,Ii.KEY_DOWN,i=>t(new gb(i))))}onkeyup(e,t){this._register(Ve(e,Ii.KEY_UP,i=>t(new gb(i))))}oninput(e,t){this._register(Ve(e,Ii.INPUT,t))}onblur(e,t){this._register(Ve(e,Ii.BLUR,t))}onfocus(e,t){this._register(Ve(e,Ii.FOCUS,t))}onchange(e,t){this._register(Ve(e,Ii.CHANGE,t))}ignoreGesture(e){return Bk.ignoreTarget(e)}},Sb=11,Lk=class extends Yp{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,Ii.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._register(vb(this.domNode,Ii.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._pointerdownRepeatTimer=this._register(new Ak),this._pointerdownScheduleRepeatTimer=this._register(new Wp)}_arrowPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,Er(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 ep{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 ep(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 ep(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 dt{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new Se),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 rf(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 Yp{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=ko(document.createElement("div")),this.domNode.setAttribute("role","presentation"),this.domNode.setAttribute("aria-hidden","true"),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition("absolute"),this._register(Ve(this.domNode.domNode,Ii.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=ko(document.createElement("div")),this.slider.setClassName("slider"),this.slider.setPosition("absolute"),this.slider.setTop(e),this.slider.setLeft(t),typeof i=="number"&&this.slider.setWidth(i),typeof s=="number"&&this.slider.setHeight(s),this.slider.setLayerHinting(!0),this.slider.setContain("strict"),this.domNode.domNode.appendChild(this.slider.domNode),this._register(Ve(this.slider.domNode,Ii.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 ip{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 ip(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=ip._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}};np.INSTANCE=new np;var Yk=np,Kk=class extends Yp{constructor(e,t,i){super(),this._onScroll=this._register(new Se),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new Se),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=ko(document.createElement("div")),this._leftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=ko(document.createElement("div")),this._topShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=ko(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 Wp),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=ga(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(e){this._verticalScrollbar.delegatePointerDown(e)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(e){this._scrollable.setScrollDimensions(e,!1)}updateClassName(e){this._options.className=e,jr&&(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=ga(this._mouseWheelToDispose),e)){let t=i=>{this._onMouseWheel(new _b(i))};this._mouseWheelToDispose.push(Ve(this._listenOnDomNode,Ii.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=!jr&&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,jr&&(t.className+=" mac"),t}var rp=class extends dt{constructor(e,t,i,s,a,o,c,h){super(),this._bufferService=i,this._optionsService=c,this._renderService=h,this._onRequestScrollLines=this._register(new Se),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=>Gp(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(sn.runAndSubscribe(o.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=o.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(ai(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=s.mainDocument.createElement("style"),t.appendChild(this._styleElement),this._register(ai(()=>this._styleElement.remove())),this._register(sn.runAndSubscribe(o.onChangeColors,()=>{this._styleElement.textContent=[".xterm .xterm-scrollable-element > .scrollbar > .slider {",` background: ${o.colors.scrollbarSliderBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider:hover {",` background: ${o.colors.scrollbarSliderHoverBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider.active {",` background: ${o.colors.scrollbarSliderActiveBackground.css};`,"}"].join(` -`)})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(f=>this._handleScroll(f)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){var e;return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:((e=this._optionsService.rawOptions.overviewRuler)==null?void 0:e.width)||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),i=t-this._bufferService.buffer.ydisp;i!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(i)),this._isHandlingScroll=!1}};rp=gi([je(2,gn),je(3,ts),je(4,My),je(5,gl),je(6,xn),je(7,is)],rp);var sp=class extends dt{constructor(e,t,i,s,a){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=i,this._decorationService=s,this._renderService=a,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement("div"),this._container.classList.add("xterm-decoration-container"),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(o=>this._removeDecoration(o))),this._register(ai(()=>{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()}};sp=gi([je(1,gn),je(2,ts),je(3,zo),je(4,is)],sp);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)}},Sr={full:0,left:0,center:0,right:0},Bs={full:0,left:0,center:0,right:0},oo={full:0,left:0,center:0,right:0},Nu=class extends dt{constructor(e,t,i,s,a,o,c,h){var f;super(),this._viewportElement=e,this._screenElement=t,this._bufferService=i,this._decorationService=s,this._renderService=a,this._optionsService=o,this._themeService=c,this._coreBrowserService=h,this._colorZoneStore=new 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(ai(()=>{var _;return(_=this._canvas)==null?void 0:_.remove()}));let p=this._canvas.getContext("2d");if(p)this._ctx=p;else throw new Error("Ctx cannot be null");this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this._register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0))),this._register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?"none":"block"})),this._register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})),this._register(this._renderService.onRender(()=>{(!this._containerHeight||this._containerHeight!==this._screenElement.clientHeight)&&(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._register(this._optionsService.onSpecificOptionChange("overviewRuler",()=>this._queueRefresh(!0))),this._register(this._themeService.onChangeColors(()=>this._queueRefresh())),this._queueRefresh(!0)}get _width(){var e;return((e=this._optionsService.options.overviewRuler)==null?void 0:e.width)||0}_refreshDrawConstants(){let e=Math.floor((this._canvas.width-1)/3),t=Math.ceil((this._canvas.width-1)/3);Bs.full=this._canvas.width,Bs.left=e,Bs.center=t,Bs.right=e,this._refreshDrawHeightConstants(),oo.full=1,oo.left=1,oo.center=1+Bs.left,oo.right=1+Bs.left+Bs.center}_refreshDrawHeightConstants(){Sr.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);Sr.left=t,Sr.center=t,Sr.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*Sr.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*Sr.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*Sr.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*Sr.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(oo[e.position||"full"],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-Sr[e.position||"full"]/2),Bs[e.position||"full"],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+Sr[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}))}};Nu=gi([je(2,gn),je(3,zo),je(4,is),je(5,xn),je(6,gl),je(7,ts)],Nu);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 xu;(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="Ÿ"))(xu||(xu={}));var Jy;(e=>e.ST=`${pe.ESC}\\`)(Jy||(Jy={}));var ap=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)}}};ap=gi([je(2,gn),je(3,xn),je(4,ba),je(5,is)],ap);var Hi=0,Ui=0,$i=0,pi=0,Eb={css:"#00000000",rgba:0},Ti;(e=>{function t(a,o,c,h){return h!==void 0?`#${oa(a)}${oa(o)}${oa(c)}${oa(h)}`:`#${oa(a)}${oa(o)}${oa(c)}`}e.toCss=t;function i(a,o,c,h=255){return(a<<24|o<<16|c<<8|h)>>>0}e.toRgba=i;function s(a,o,c,h){return{css:e.toCss(a,o,c,h),rgba:e.toRgba(a,o,c,h)}}e.toColor=s})(Ti||(Ti={}));var ni;(e=>{function t(p,f){if(pi=(f.rgba&255)/255,pi===1)return{css:f.css,rgba:f.rgba};let _=f.rgba>>24&255,x=f.rgba>>16&255,b=f.rgba>>8&255,v=p.rgba>>24&255,S=p.rgba>>16&255,j=p.rgba>>8&255;Hi=v+Math.round((_-v)*pi),Ui=S+Math.round((x-S)*pi),$i=j+Math.round((b-j)*pi);let R=Ti.toCss(Hi,Ui,$i),E=Ti.toRgba(Hi,Ui,$i);return{css:R,rgba:E}}e.blend=t;function i(p){return(p.rgba&255)===255}e.isOpaque=i;function s(p,f,_){let x=_u.ensureContrastRatio(p.rgba,f.rgba,_);if(x)return Ti.toColor(x>>24&255,x>>16&255,x>>8&255)}e.ensureContrastRatio=s;function a(p){let f=(p.rgba|255)>>>0;return[Hi,Ui,$i]=_u.toChannels(f),{css:Ti.toCss(Hi,Ui,$i),rgba:f}}e.opaque=a;function o(p,f){return pi=Math.round(f*255),[Hi,Ui,$i]=_u.toChannels(p.rgba),{css:Ti.toCss(Hi,Ui,$i,pi),rgba:Ti.toRgba(Hi,Ui,$i,pi)}}e.opacity=o;function c(p,f){return pi=p.rgba&255,o(p,pi*f/255)}e.multiplyOpacity=c;function h(p){return[p.rgba>>24&255,p.rgba>>16&255,p.rgba>>8&255]}e.toColorRGB=h})(ni||(ni={}));var ci;(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 Hi=parseInt(a.slice(1,2).repeat(2),16),Ui=parseInt(a.slice(2,3).repeat(2),16),$i=parseInt(a.slice(3,4).repeat(2),16),Ti.toColor(Hi,Ui,$i);case 5:return Hi=parseInt(a.slice(1,2).repeat(2),16),Ui=parseInt(a.slice(2,3).repeat(2),16),$i=parseInt(a.slice(3,4).repeat(2),16),pi=parseInt(a.slice(4,5).repeat(2),16),Ti.toColor(Hi,Ui,$i,pi);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 Hi=parseInt(o[1]),Ui=parseInt(o[2]),$i=parseInt(o[3]),pi=Math.round((o[5]===void 0?1:parseFloat(o[5]))*255),Ti.toColor(Hi,Ui,$i,pi);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),[Hi,Ui,$i,pi]=t.getImageData(0,0,1,1).data,pi!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:Ti.toRgba(Hi,Ui,$i,pi),css:a}}e.toColor=s})(ci||(ci={}));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 _u;(e=>{function t(c,h){if(pi=(h&255)/255,pi===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 Hi=x+Math.round((p-x)*pi),Ui=b+Math.round((f-b)*pi),$i=v+Math.round((_-v)*pi),Ti.toRgba(Hi,Ui,$i)}e.blend=t;function i(c,h,p){let f=fn.relativeLuminance(c>>8),_=fn.relativeLuminance(h>>8);if(Xr(f,_)>8));if(S>8));return S>R?v:j}return v}let x=a(c,h,p),b=Xr(f,fn.relativeLuminance(x>>8));if(b>8));return b>S?x:v}return x}}e.ensureContrastRatio=i;function s(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,j=Xr(fn.relativeLuminance2(b,v,S),fn.relativeLuminance2(f,_,x));for(;j0||v>0||S>0);)b-=Math.max(0,Math.ceil(b*.1)),v-=Math.max(0,Math.ceil(v*.1)),S-=Math.max(0,Math.ceil(S*.1)),j=Xr(fn.relativeLuminance2(b,v,S),fn.relativeLuminance2(f,_,x));return(b<<24|v<<16|S<<8|255)>>>0}e.reduceLuminance=s;function a(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,j=Xr(fn.relativeLuminance2(b,v,S),fn.relativeLuminance2(f,_,x));for(;j>>0}e.increaseLuminance=a;function o(c){return[c>>24&255,c>>16&255,c>>8&255,c&255]}e.toChannels=o})(_u||(_u={}));function oa(e){let t=e.toString(16);return t.length<2?"0"+t:t}function Xr(e,t){return e1){let _=this._getJoinedRanges(s,c,o,t,a);for(let x=0;x<_.length;x++)i.push(_[x])}a=f,c=o,h=this._workCell.fg,p=this._workCell.bg}o+=this._workCell.getChars().length||Is.length}if(this._bufferService.cols-a>1){let f=this._getJoinedRanges(s,c,o,t,a);for(let _=0;_=P,L=Y,U=this._workCell;if(b.length>0&&Y===b[0][0]&&A){let Ae=b.shift(),ut=this._isCellInSelection(Ae[0],t);for(N=Ae[0]+1;N=Ae[1]),A?(I=!0,U=new Qk(this._workCell,e.translateToString(!0,Ae[0],Ae[1]),Ae[1]-Ae[0]),L=Ae[1]-1,V=U.getWidth()):P=Ae[1]}let ge=this._isCellInSelection(Y,t),T=i&&Y===o,D=W&&Y>=f&&Y<=_,K=!1;this._decorationService.forEachDecorationAtCell(Y,t,void 0,Ae=>{K=!0});let k=U.getChars()||Is;if(k===" "&&(U.isUnderline()||U.isOverline())&&(k=" "),ye=V*h-p.get(k,U.isBold(),U.isItalic()),!j)j=this._document.createElement("span");else if(R&&(ge&&fe||!ge&&!fe&&U.bg===z)&&(ge&&fe&&v.selectionForeground||U.fg===J)&&U.extended.ext===F&&D===M&&ye===ee&&!T&&!I&&!K&&A){U.isInvisible()?E+=Is:E+=k,R++;continue}else R&&(j.textContent=E),j=this._document.createElement("span"),R=0,E="";if(z=U.bg,J=U.fg,F=U.extended.ext,M=D,ee=ye,fe=ge,I&&o>=Y&&o<=L&&(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=Is:E=U.getChars()||Is,U.isUnderline()&&(ae.push(`xterm-underline-${U.extended.underlineStyle}`),E===" "&&(E=" "),!U.isUnderlineColorDefault()))if(U.isUnderlineColorRGB())j.style.textDecorationColor=`rgb(${Oo.toColorRGB(U.getUnderlineColor()).join(",")})`;else{let Ae=U.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&U.isBold()&&Ae<8&&(Ae+=8),j.style.textDecorationColor=v.ansi[Ae].css}U.isOverline()&&(ae.push("xterm-overline"),E===" "&&(E=" ")),U.isStrikethrough()&&ae.push("xterm-strikethrough"),D&&(j.style.textDecoration="underline");let ue=U.getFgColor(),te=U.getFgColorMode(),G=U.getBgColor(),H=U.getBgColorMode(),le=!!U.isInverse();if(le){let Ae=ue;ue=G,G=Ae;let ut=te;te=H,H=ut}let xe,Re,Me=!1;this._decorationService.forEachDecorationAtCell(Y,t,void 0,Ae=>{Ae.options.layer!=="top"&&Me||(Ae.backgroundColorRGB&&(H=50331648,G=Ae.backgroundColorRGB.rgba>>8&16777215,xe=Ae.backgroundColorRGB),Ae.foregroundColorRGB&&(te=50331648,ue=Ae.foregroundColorRGB.rgba>>8&16777215,Re=Ae.foregroundColorRGB),Me=Ae.options.layer==="top")}),!Me&&ge&&(xe=this._coreBrowserService.isFocused?v.selectionBackgroundOpaque:v.selectionInactiveBackgroundOpaque,G=xe.rgba>>8&16777215,H=50331648,Me=!0,v.selectionForeground&&(te=50331648,ue=v.selectionForeground.rgba>>8&16777215,Re=v.selectionForeground)),Me&&ae.push("xterm-decoration-top");let Le;switch(H){case 16777216:case 33554432:Le=v.ansi[G],ae.push(`xterm-bg-${G}`);break;case 50331648:Le=Ti.toColor(G>>16,G>>8&255,G&255),this._addStyle(j,`background-color:#${Nb((G>>>0).toString(16),"0",6)}`);break;case 0:default:le?(Le=v.foreground,ae.push("xterm-bg-257")):Le=v.background}switch(xe||U.isDim()&&(xe=ni.multiplyOpacity(Le,.5)),te){case 16777216:case 33554432:U.isBold()&&ue<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(ue+=8),this._applyMinimumContrast(j,Le,v.ansi[ue],U,xe,void 0)||ae.push(`xterm-fg-${ue}`);break;case 50331648:let Ae=Ti.toColor(ue>>16&255,ue>>8&255,ue&255);this._applyMinimumContrast(j,Le,Ae,U,xe,Re)||this._addStyle(j,`color:#${Nb(ue.toString(16),"0",6)}`);break;case 0:default:this._applyMinimumContrast(j,Le,v.foreground,U,xe,Re)||le&&ae.push("xterm-fg-257")}ae.length&&(j.className=ae.join(" "),ae.length=0),!T&&!I&&!K&&A?R++:j.textContent=E,ye!==this.defaultSpacing&&(j.style.letterSpacing=`${ye}px`),x.push(j),Y=L}return j&&R&&(j.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=ni.ensureContrastRatio(a||t,o||i,p),c.setColor((a||t).rgba,(o||i).rgba,h??null)}return h?(this._addStyle(e,`color:${h.css}`),!0):!1}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute("style",`${e.getAttribute("style")||""}${t};`)}_isCellInSelection(e,t){let i=this._selectionStart,s=this._selectionEnd;return!i||!s?!1:this._columnSelectMode?i[0]<=s[0]?e>=i[0]&&t>=i[1]&&e=i[1]&&e>=s[0]&&t<=s[1]:t>i[1]&&t=i[0]&&e=i[0]}};lp=gi([je(1,Ly),je(2,xn),je(3,ts),je(4,ba),je(5,zo),je(6,gl)],lp);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 sf="xterm-dom-renderer-owner-",er="xterm-rows",tu="xterm-fg-",jb="xterm-bg-",co="xterm-focus",iu="xterm-selection",a2=1,op=class extends dt{constructor(e,t,i,s,a,o,c,h,p,f,_,x,b,v){super(),this._terminal=e,this._document=t,this._element=i,this._screenElement=s,this._viewportElement=a,this._helperContainer=o,this._linkifier2=c,this._charSizeService=p,this._optionsService=f,this._bufferService=_,this._coreService=x,this._coreBrowserService=b,this._themeService=v,this._terminalClass=a2++,this._rowElements=[],this._selectionRenderModel=s2(),this.onRequestRedraw=this._register(new Se).event,this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(er),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(iu),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=i2(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(S=>this._injectCss(S))),this._injectCss(this._themeService.colors),this._rowFactory=h.createInstance(lp,document),this._element.classList.add(sf+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(S=>this._handleLinkHover(S))),this._register(this._linkifier2.onHideLinkUnderline(S=>this._handleLinkLeave(S))),this._register(ai(()=>{this._element.classList.remove(sf+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} .${er} 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} .${er} { 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} .${er} .xterm-dim { color: ${ni.multiplyOpacity(e.foreground,.5).css};}`,t+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;let i=`blink_underline_${this._terminalClass}`,s=`blink_bar_${this._terminalClass}`,a=`blink_block_${this._terminalClass}`;t+=`@keyframes ${i} { 50% { border-bottom-style: hidden; }}`,t+=`@keyframes ${s} { 50% { box-shadow: none; }}`,t+=`@keyframes ${a} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${er}.${co} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${er}.${co} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${s} 1s step-end infinite;}${this._terminalSelector} .${er}.${co} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${a} 1s step-end infinite;}${this._terminalSelector} .${er} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${er} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${er} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${er} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${er} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${iu} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${iu} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${iu} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[o,c]of e.ansi.entries())t+=`${this._terminalSelector} .${tu}${o} { color: ${c.css}; }${this._terminalSelector} .${tu}${o}.xterm-dim { color: ${ni.multiplyOpacity(c,.5).css}; }${this._terminalSelector} .${jb}${o} { background-color: ${c.css}; }`;t+=`${this._terminalSelector} .${tu}257 { color: ${ni.opaque(e.background).css}; }${this._terminalSelector} .${tu}257.xterm-dim { color: ${ni.multiplyOpacity(ni.opaque(e.background),.5).css}; }${this._terminalSelector} .${jb}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(co),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(co),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`.${sf}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,i,s,a,o){i<0&&(e=0),s<0&&(t=0);let c=this._bufferService.rows-1;i=Math.max(Math.min(i,c),0),s=Math.max(Math.min(s,c),0),a=Math.min(a,this._bufferService.cols);let h=this._bufferService.buffer,p=h.ybase+h.y,f=Math.min(h.x,a-1),_=this._optionsService.rawOptions.cursorBlink,x=this._optionsService.rawOptions.cursorStyle,b=this._optionsService.rawOptions.cursorInactiveStyle;for(let v=i;v<=s;++v){let S=v+h.ydisp,j=this._rowElements[v],R=h.lines.get(S);if(!j||!R)break;j.replaceChildren(...this._rowFactory.createRow(R,S,S===p,x,b,f,_,this.dimensions.css.cell.width,this._widthCache,o?v===i?e:0:-1,o?(v===s?t:a)-1:-1))}}};op=gi([je(7,Hp),je(8,Pu),je(9,xn),je(10,gn),je(11,ba),je(12,ts),je(13,gl)],op);var cp=class extends dt{constructor(e,t,i){super(),this._optionsService=i,this.width=0,this.height=0,this._onCharSizeChange=this._register(new Se),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())}};cp=gi([je(2,xn)],cp);var e0=class extends dt{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(e,t){e!==void 0&&e>0&&t!==void 0&&t>0&&(this._result.width=e,this._result.height=t)}},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 dt{constructor(e,t,i){super(),this._textarea=e,this._window=t,this.mainDocument=i,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new u2(this._window)),this._onDprChange=this._register(new Se),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new Se),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(s=>this._screenDprMonitor.setWindow(s))),this._register(sn.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(Ve(this._textarea,"focus",()=>this._isFocused=!0)),this._register(Ve(this._textarea,"blur",()=>this._isFocused=!1))}get window(){return this._window}set window(e){this._window!==e&&(this._window=e,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask(()=>this._cachedIsFocused=void 0)),this._cachedIsFocused}},u2=class extends dt{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new fl),this._onDprChange=this._register(new Se),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(ai(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=Ve(this._parentWindow,"resize",()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){var e;this._outerListener&&((e=this._resolutionMediaMatchList)==null||e.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){!this._resolutionMediaMatchList||!this._outerListener||(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}},h2=class extends dt{constructor(){super(),this.linkProviders=[],this._register(ai(()=>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 Kp(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=Kp(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 up=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=Kp(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])}}};up=gi([je(0,is),je(1,Pu)],up);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:()=>Vp,isMac:()=>Tu,isNode:()=>Iu,isSafari:()=>n0,isWindows:()=>r0});var Iu=typeof process<"u"&&"title"in process,Po=Iu?"node":navigator.userAgent,Io=Iu?"node":navigator.platform,i0=Po.includes("Firefox"),p2=Po.includes("Edge"),n0=/^((?!chrome|android).)*safari/i.test(Po);function m2(){if(!n0)return 0;let e=Po.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var Tu=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(Io),g2=Io==="iPad",x2=Io==="iPhone",r0=["Windows","Win16","Win32","WinCE"].includes(Io),Vp=Io.indexOf("Linux")>=0,s0=/\bCrOS\b/.test(Po),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)}},Au=!Iu&&"requestIdleCallback"in window?b2:_2,v2=class{constructor(){this._queue=new Au}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},hp=class extends dt{constructor(e,t,i,s,a,o,c,h,p){super(),this._rowCount=e,this._optionsService=i,this._charSizeService=s,this._coreService=a,this._coreBrowserService=h,this._renderer=this._register(new fl),this._pausedResizeTask=new v2,this._observerDisposable=this._register(new fl),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this._register(new Se),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new Se),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new Se),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new Se),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(ai(()=>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=ai(()=>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()}};hp=gi([je(2,xn),je(3,Pu),je(4,ba),je(5,zo),je(6,gn),je(7,ts),je(8,gl)],hp);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)+Hu(o,t,i,s)+E2(a,o,e,t,i,s);let c;if(o===t)return c=a>e?"D":"C",Ao(Math.abs(a-e),To(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 Ao(p,To(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 Hu(t,s,a,o).length===0?"":Ao(o0(e,t,e,t-xa(t,a),!1,a).length,To("D",o))}function Hu(e,t,i,s){let a=e-xa(e,i),o=t-xa(t,i),c=Math.abs(a-o)-N2(e,t,i);return Ao(c,To(l0(e,t),s))}function E2(e,t,i,s,a,o){let c;Hu(t,s,a,o).length>0?c=s-xa(s,a):c=t;let h=s,p=j2(e,t,i,s,a,o);return Ao(o0(e,c,i,h,p==="C",a).length,To(p,o))}function N2(e,t,i){var c;let s=0,a=e-xa(e,i),o=t-xa(t,i);for(let h=0;h=0&&e0?c=s-xa(s,a):c=t,e=i&&ct?"A":"B"}function 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 To(e,t){let i=t?"O":"[";return pe.ESC+i+e}function Ao(e,t){e=Math.floor(e);let i="";for(let s=0;sthis._bufferService.cols?e%this._bufferService.cols===0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){let e=this.selectionStart,t=this.selectionEnd;return!e||!t?!1:e[1]>t[1]||e[1]===t[1]&&e[0]>t[0]}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}};function Tb(e,t){if(e.start.y>e.end.y)throw new Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}var af=50,A2=15,R2=50,M2=500,D2=" ",B2=new RegExp(D2,"g"),dp=class extends dt{constructor(e,t,i,s,a,o,c,h,p){super(),this._element=e,this._screenElement=t,this._linkifier=i,this._bufferService=s,this._coreService=a,this._mouseService=o,this._optionsService=c,this._renderService=h,this._coreBrowserService=p,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new sr,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new Se),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new Se),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new Se),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new Se),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 T2(this._bufferService),this._activeSelectionMode=0,this._register(ai(()=>{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())),Vp&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),i=this._model.finalSelectionStart,s=this._model.finalSelectionEnd;return!i||!s||!t?!1:this._areCoordsInSelection(t,i,s)}isCellInSelection(e,t){let i=this._model.finalSelectionStart,s=this._model.finalSelectionEnd;return!i||!s?!1:this._areCoordsInSelection([e,t],i,s)}_areCoordsInSelection(e,t,i){return e[1]>t[1]&&e[1]=t[0]&&e[0]=t[0]}_selectWordAtCursor(e,t){var a,o;let i=(o=(a=this._linkifier.currentLink)==null?void 0:a.link)==null?void 0:o.range;if(i)return this._model.selectionStart=[i.start.x-1,i.start.y-1],this._model.selectionStartLength=Tb(i,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let s=this._getMouseBufferCoords(e);return s?(this._selectWordAt(s,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=Kp(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,-af),af),t/=af,t/Math.abs(t)+Math.round(t*(A2-1)))}shouldForceSelection(e){return Tu?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&&!(Tu&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let i=this._bufferService.buffer;if(this._model.selectionEnd[1]0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&tthis._handleTrim(t))}_convertViewportColToCharacterIndex(e,t){let i=t;for(let s=0;t>=s;s++){let a=e.loadCell(s,this._workCell).getChars().length;this._workCell.getWidth()===0?i--:a>1&&t!==s&&(i+=a-1)}return i}setSelection(e,t,i){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=i,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,i=!0,s=!0){if(e[0]>=this._bufferService.cols)return;let a=this._bufferService.buffer,o=a.lines.get(e[1]);if(!o)return;let c=a.translateBufferLineToString(e[1],!1),h=this._convertViewportColToCharacterIndex(o,e[0]),p=h,f=e[0]-h,_=0,x=0,b=0,v=0;if(c.charAt(h)===" "){for(;h>0&&c.charAt(h-1)===" ";)h--;for(;p1&&(v+=N-1,p+=N-1);R>0&&h>0&&!this._isCharWordSeparator(o.loadCell(R-1,this._workCell));){o.loadCell(R-1,this._workCell);let z=this._workCell.getChars().length;this._workCell.getWidth()===0?(_++,R--):z>1&&(b+=z-1,h-=z-1),h--,R--}for(;E1&&(v+=z-1,p+=z-1),p++,E++}}p++;let S=h+f-_+b,j=Math.min(this._bufferService.cols,p-h+_+x-b-v);if(!(!t&&c.slice(h,p).trim()==="")){if(i&&S===0&&o.getCodePoint(0)!==32){let R=a.lines.get(e[1]-1);if(R&&o.isWrapped&&R.getCodePoint(this._bufferService.cols-1)!==32){let E=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(E){let N=this._bufferService.cols-E.start;S-=N,j+=N}}}if(s&&S+j===this._bufferService.cols&&o.getCodePoint(this._bufferService.cols-1)!==32){let R=a.lines.get(e[1]+1);if(R!=null&&R.isWrapped&&R.getCodePoint(0)!==32){let E=this._getWordAt([0,e[1]+1],!1,!1,!0);E&&(j+=E.length)}}return{start:S,length:j}}}_selectWordAt(e,t){let i=this._getWordAt(e,t);if(i){for(;i.start<0;)i.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[i.start,e[1]],this._model.selectionStartLength=i.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let i=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,i--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,i++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,i]}}_isCharWordSeparator(e){return e.getWidth()===0?!1:this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),i={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=Tb(i,this._bufferService.cols)}};dp=gi([je(3,gn),je(4,ba),je(5,Up),je(6,xn),je(7,is),je(8,ts)],dp);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()}},Bi=Object.freeze((()=>{let e=[ci.toColor("#2e3436"),ci.toColor("#cc0000"),ci.toColor("#4e9a06"),ci.toColor("#c4a000"),ci.toColor("#3465a4"),ci.toColor("#75507b"),ci.toColor("#06989a"),ci.toColor("#d3d7cf"),ci.toColor("#555753"),ci.toColor("#ef2929"),ci.toColor("#8ae234"),ci.toColor("#fce94f"),ci.toColor("#729fcf"),ci.toColor("#ad7fa8"),ci.toColor("#34e2e2"),ci.toColor("#eeeeec")],t=[0,95,135,175,215,255];for(let i=0;i<216;i++){let s=t[i/36%6|0],a=t[i/6%6|0],o=t[i%6];e.push({css:Ti.toCss(s,a,o),rgba:Ti.toRgba(s,a,o)})}for(let i=0;i<24;i++){let s=8+i*10;e.push({css:Ti.toCss(s,s,s),rgba:Ti.toRgba(s,s,s)})}return e})()),da=ci.toColor("#ffffff"),yo=ci.toColor("#000000"),Mb=ci.toColor("#ffffff"),Db=yo,uo={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117},L2=da,fp=class extends dt{constructor(e){super(),this._optionsService=e,this._contrastCache=new Rb,this._halfContrastCache=new Rb,this._onChangeColors=this._register(new Se),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:da,background:yo,cursor:Mb,cursorAccent:Db,selectionForeground:void 0,selectionBackgroundTransparent:uo,selectionBackgroundOpaque:ni.blend(yo,uo),selectionInactiveBackgroundTransparent:uo,selectionInactiveBackgroundOpaque:ni.blend(yo,uo),scrollbarSliderBackground:ni.opacity(da,.2),scrollbarSliderHoverBackground:ni.opacity(da,.4),scrollbarSliderActiveBackground:ni.opacity(da,.5),overviewRulerBorder:da,ansi:Bi.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange("minimumContrastRatio",()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange("theme",()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(e={}){let t=this._colors;if(t.foreground=Xt(e.foreground,da),t.background=Xt(e.background,yo),t.cursor=ni.blend(t.background,Xt(e.cursor,Mb)),t.cursorAccent=ni.blend(t.background,Xt(e.cursorAccent,Db)),t.selectionBackgroundTransparent=Xt(e.selectionBackground,uo),t.selectionBackgroundOpaque=ni.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=Xt(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=ni.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?Xt(e.selectionForeground,Eb):void 0,t.selectionForeground===Eb&&(t.selectionForeground=void 0),ni.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=ni.opacity(t.selectionBackgroundTransparent,.3)),ni.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=ni.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=Xt(e.scrollbarSliderBackground,ni.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=Xt(e.scrollbarSliderHoverBackground,ni.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=Xt(e.scrollbarSliderActiveBackground,ni.opacity(t.foreground,.5)),t.overviewRulerBorder=Xt(e.overviewRulerBorder,L2),t.ansi=Bi.slice(),t.ansi[0]=Xt(e.black,Bi[0]),t.ansi[1]=Xt(e.red,Bi[1]),t.ansi[2]=Xt(e.green,Bi[2]),t.ansi[3]=Xt(e.yellow,Bi[3]),t.ansi[4]=Xt(e.blue,Bi[4]),t.ansi[5]=Xt(e.magenta,Bi[5]),t.ansi[6]=Xt(e.cyan,Bi[6]),t.ansi[7]=Xt(e.white,Bi[7]),t.ansi[8]=Xt(e.brightBlack,Bi[8]),t.ansi[9]=Xt(e.brightRed,Bi[9]),t.ansi[10]=Xt(e.brightGreen,Bi[10]),t.ansi[11]=Xt(e.brightYellow,Bi[11]),t.ansi[12]=Xt(e.brightBlue,Bi[12]),t.ansi[13]=Xt(e.brightMagenta,Bi[13]),t.ansi[14]=Xt(e.brightCyan,Bi[14]),t.ansi[15]=Xt(e.brightWhite,Bi[15]),e.extendedAnsi){let i=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let s=0;so.index-c.index),s=[];for(let o of i){let c=this._services.get(o.id);if(!c)throw new Error(`[createInstance] ${e.name} depends on UNKNOWN service ${o.id._id}.`);s.push(c)}let a=i.length>0?i[0].index:t.length;if(t.length!==a)throw new Error(`[createInstance] First service dependency of ${e.name} at position ${a+1} conflicts with ${t.length} static arguments`);return new e(...t,...s)}},P2={trace:0,debug:1,info:2,warn:3,error:4,off:5},I2="xterm.js: ",pp=class extends dt{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange("logLevel",()=>this._updateLogLevel()))}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=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*ht+1]=i[0],i[1].length>1?(this._combined[t]=i[1],this._data[t*ht+0]=t|2097152|i[2]<<22):this._data[t*ht+0]=i[1].charCodeAt(0)|i[2]<<22}getWidth(t){return this._data[t*ht+0]>>22}hasWidth(t){return this._data[t*ht+0]&12582912}getFg(t){return this._data[t*ht+1]}getBg(t){return this._data[t*ht+2]}hasContent(t){return this._data[t*ht+0]&4194303}getCodePoint(t){let i=this._data[t*ht+0];return i&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):i&2097151}isCombined(t){return this._data[t*ht+0]&2097152}getString(t){let i=this._data[t*ht+0];return i&2097152?this._combined[t]:i&2097151?zs(i&2097151):""}isProtected(t){return this._data[t*ht+2]&536870912}loadCell(t,i){return nu=t*ht,i.content=this._data[nu+0],i.fg=this._data[nu+1],i.bg=this._data[nu+2],i.content&2097152&&(i.combinedData=this._combined[t]),i.bg&268435456&&(i.extended=this._extendedAttrs[t]),i}setCell(t,i){i.content&2097152&&(this._combined[t]=i.combinedData),i.bg&268435456&&(this._extendedAttrs[t]=i.extended),this._data[t*ht+0]=i.content,this._data[t*ht+1]=i.fg,this._data[t*ht+2]=i.bg}setCellFromCodepoint(t,i,s,a){a.bg&268435456&&(this._extendedAttrs[t]=a.extended),this._data[t*ht+0]=i|s<<22,this._data[t*ht+1]=a.fg,this._data[t*ht+2]=a.bg}addCodepointToCell(t,i,s){let a=this._data[t*ht+0];a&2097152?this._combined[t]+=zs(i):a&2097151?(this._combined[t]=zs(a&2097151)+zs(i),a&=-2097152,a|=2097152):a=i|1<<22,s&&(a&=-12582913,a|=s<<22),this._data[t*ht+0]=a}insertCells(t,i,s){if(t%=this.length,t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,s),i=0;--o)this.setCell(t+i+o,this.loadCell(t+o,a));for(let o=0;othis.length){if(this._data.buffer.byteLength>=s*4)this._data=new Uint32Array(this._data.buffer,0,s);else{let a=new Uint32Array(s);a.set(this._data),this._data=a}for(let a=this.length;a=t&&delete this._combined[h]}let o=Object.keys(this._extendedAttrs);for(let c=0;c=t&&delete this._extendedAttrs[h]}}return this.length=t,s*4*lf=0;--t)if(this._data[t*ht+0]&4194303)return t+(this._data[t*ht+0]>>22);return 0}getNoBgTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*ht+0]&4194303||this._data[t*ht+2]&50331648)return t+(this._data[t*ht+0]>>22);return 0}copyCellsFrom(t,i,s,a,o){let c=t._data;if(o)for(let p=a-1;p>=0;p--){for(let f=0;f=i&&(this._combined[f-i+s]=t._combined[f])}}translateToString(t,i,s,a){i=i??0,s=s??this.length,t&&(s=Math.min(s,this.getTrimmedLength())),a&&(a.length=0);let o="";for(;i>22||1}return a&&a.push(i),o}};function H2(e,t,i,s,a,o){let c=[];for(let h=0;h=h&&s0&&(R>x||_[R].getTrimmedLength()===0);R--)j++;j>0&&(c.push(h+_.length-j),c.push(j)),h+=_.length-1}return c}function U2(e,t){let i=[],s=0,a=t[s],o=0;for(let c=0;cRo(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 Ro(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 Se),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),ga(this._disposables),this._disposables.length=0)}register(t){return this._disposables.push(t),t}};u0._nextId=1;var q2=u0,zi={},fa=zi.B;zi[0]={"`":"◆",a:"▒",b:"␉",c:"␌",d:"␍",e:"␊",f:"°",g:"±",h:"␤",i:"␋",j:"┘",k:"┐",l:"┌",m:"└",n:"┼",o:"⎺",p:"⎻",q:"─",r:"⎼",s:"⎽",t:"├",u:"┤",v:"┴",w:"┬",x:"│",y:"≤",z:"≥","{":"π","|":"≠","}":"£","~":"·"};zi.A={"#":"£"};zi.B=void 0;zi[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"};zi.C=zi[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};zi.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"};zi.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"};zi.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"};zi.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"};zi.E=zi[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"};zi.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"};zi.H=zi[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};zi["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"};var 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=ji.clone(),this.savedCharset=fa,this.markers=[],this._nullCell=sr.fromCharData([0,jy,1,0]),this._whitespaceCell=sr.fromCharData([0,Is,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new Au,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 Eu),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 Eu),this._whitespaceCell}getBlankLine(e,t){return new So(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=ji);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new Bb(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let i=this.getNullCell(ji),s=0,a=this._getCorrectBufferLength(t);if(a>this.lines.maxLength&&(this.lines.maxLength=a),this.lines.length>0){if(this._cols0&&this.lines.length<=this.ybase+this.y+o+1?(this.ybase--,o++,this.ydisp>0&&this.ydisp--):this.lines.push(new So(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(ji),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(ji),a=i;for(;a-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length=0;c--){let h=this.lines.get(c);if(!h||!h.isWrapped&&h.getTrimmedLength()<=e)continue;let p=[h];for(;h.isWrapped&&c>0;)h=this.lines.get(--c),p.unshift(h);if(!i){let z=this.ybase+this.y;if(z>=c&&z0&&(a.push({start:c+p.length+o,newLines:v}),o+=v.length),p.push(...v);let S=_.length-1,j=_[S];j===0&&(S--,j=_[S]);let R=p.length-x-1,E=f;for(;R>=0;){let z=Math.min(E,j);if(p[S]===void 0)break;if(p[S].copyCellsFrom(p[R],E-z,j-z,z,!0),j-=z,j===0&&(S--,j=_[S]),E-=z,E===0){R--;let J=Math.max(R,0);E=Ro(p,J,this._cols)}}for(let z=0;z0;)this.ybase===0?this.y0){let c=[],h=[];for(let j=0;j=0;j--)if(x&&x.start>f+b){for(let R=x.newLines.length-1;R>=0;R--)this.lines.set(j--,x.newLines[R]);j++,c.push({index:f+1,amount:x.newLines.length}),b+=x.newLines.length,x=a[++_]}else this.lines.set(j,h[f--]);let v=0;for(let j=c.length-1;j>=0;j--)c[j].index+=v,this.lines.onInsertEmitter.fire(c[j]),v+=c[j].amount;let S=Math.max(0,p+o-this.lines.maxLength);S>0&&this.lines.onTrimEmitter.fire(S)}}translateBufferLineToString(e,t,i=0,s){let a=this.lines.get(e);return a?a.translateToString(t,i,s):""}getWrappedRangeForLine(e){let t=e,i=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;i+10;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e==null&&(e=this.x);!this.tabs[++e]&&e=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t{t.line-=i,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(i=>{t.line>=i.index&&(t.line+=i.amount)})),t.register(this.lines.onDelete(i=>{t.line>=i.index&&t.linei.index&&(t.line-=i.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},W2=class extends dt{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new Se),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,mp=class extends dt{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new Se),this.onResize=this._onResize.event,this._onScroll=this._register(new Se),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))}};mp=gi([je(0,xn)],mp);var nl={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:Tu,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 dt{constructor(e){super(),this._onOptionChange=this._register(new Se),this.onOptionChange=this._onOptionChange.event;let t={...nl};for(let i in e)if(i in t)try{let s=e[i];t[i]=this._sanitizeAndValidateOption(i,s)}catch(s){console.error(s)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register(ai(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(i=>{i===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(i=>{e.indexOf(i)!==-1&&t()})}_setupOptions(){let e=i=>{if(!(i in nl))throw new Error(`No option with key "${i}"`);return this.rawOptions[i]},t=(i,s)=>{if(!(i in nl))throw new Error(`No option with key "${i}"`);s=this._sanitizeAndValidateOption(i,s),this.rawOptions[i]!==s&&(this.rawOptions[i]=s,this._onOptionChange.fire(i))};for(let i in this.rawOptions){let s={get:e.bind(this,i),set:t.bind(this,i)};Object.defineProperty(this.options,i,s)}}_sanitizeAndValidateOption(e,t){switch(e){case"cursorStyle":if(t||(t=nl[e]),!K2(t))throw new Error(`"${t}" is not a valid value for ${e}`);break;case"wordSeparator":t||(t=nl[e]);break;case"fontWeight":case"fontWeightBold":if(typeof t=="number"&&1<=t&&t<=1e3)break;t=G2.includes(t)?t:nl[e];break;case"cursorWidth":t=Math.floor(t);case"lineHeight":case"tabStopWidth":if(t<1)throw new Error(`${e} cannot be less than 1, value: ${t}`);break;case"minimumContrastRatio":t=Math.max(1,Math.min(21,Math.round(t*10)/10));break;case"scrollback":if(t=Math.min(t,4294967295),t<0)throw new Error(`${e} cannot be less than 0, value: ${t}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(t<=0)throw new Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case"rows":case"cols":if(!t&&t!==0)throw new Error(`${e} must be numeric, value: ${t}`);break;case"windowsPty":t=t??{};break}return t}};function K2(e){return e==="block"||e==="underline"||e==="bar"}function wo(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]&&wo(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}),gp=class extends dt{constructor(e,t,i){super(),this._bufferService=e,this._logService=t,this._optionsService=i,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new Se),this.onData=this._onData.event,this._onUserInput=this._register(new Se),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new Se),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new Se),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=wo(zb),this.decPrivateModes=wo(Pb)}reset(){this.modes=wo(zb),this.decPrivateModes=wo(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))}};gp=gi([je(0,gn),je(1,Dy),je(2,xn)],gp);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 of(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 cf=String.fromCharCode,Hb={DEFAULT:e=>{let t=[of(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`\x1B[M${cf(t[0])}${cf(t[1])}${cf(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${of(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${of(e,!0)};${e.x};${e.y}${t}`}},xp=class extends dt{constructor(e,t,i){super(),this._bufferService=e,this._coreService=t,this._optionsService=i,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new Se),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)}};xp=gi([je(0,gn),je(1,ba),je(2,xn)],xp);var uf=[[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]],Li;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=pa.extractWidth(t);a===0?s=!1:a>i&&(i=a)}return pa.createPropertyValue(0,i,s)}},pa=class bu{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new Se,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=bu.extractWidth(h);bu.extractShouldJoin(h)&&(p-=bu.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 ho=2147483647,J2=256,p0=class _p{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 _p;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>ho?ho: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>ho?ho: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,ho):t}},fo=[],eE=class{constructor(){this._state=0,this._active=fo,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=fo}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=fo,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||fo,!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",zu(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=fo,this._id=-1,this._state=0}}},In=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+=zu(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}},po=[],tE=class{constructor(){this._handlers=Object.create(null),this._active=po,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=po}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=po,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||po,!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",zu(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=po,this._ident=0}},Co=new p0;Co.addParam(0);var $b=class{constructor(e){this._handler=e,this._data="",this._params=Co,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():Co,this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=zu(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=Co,this._data="",this._hitLimit=!1,i));return this._params=Co,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(ir,0,2,0),e.add(ir,8,5,8),e.add(ir,6,0,6),e.add(ir,11,0,11),e.add(ir,13,13,13),e})(),rE=class extends dt{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(ai(()=>{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 hf(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:${hf(i,t)}/${hf(s,t)}/${hf(a,t)}`}var oE={"(":0,")":1,"*":2,"+":3,"-":1,".":2},Ls=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 dt{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 jC,this._utf8Decoder=new TC,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=ji.clone(),this._eraseAttrDataInternal=ji.clone(),this._onRequestBell=this._register(new Se),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new Se),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new Se),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new Se),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new Se),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new Se),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new Se),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new Se),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new Se),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new Se),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new Se),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new Se),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new Se),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 bp(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(xu.IND,()=>this.index()),this._parser.setExecuteHandler(xu.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(xu.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new In(f=>(this.setTitle(f),this.setIconName(f),!0))),this._parser.registerOscHandler(1,new In(f=>this.setIconName(f))),this._parser.registerOscHandler(2,new In(f=>this.setTitle(f))),this._parser.registerOscHandler(4,new In(f=>this.setOrReportIndexedColor(f))),this._parser.registerOscHandler(8,new In(f=>this.setHyperlink(f))),this._parser.registerOscHandler(10,new In(f=>this.setOrReportFgColor(f))),this._parser.registerOscHandler(11,new In(f=>this.setOrReportBgColor(f))),this._parser.registerOscHandler(12,new In(f=>this.setOrReportCursorColor(f))),this._parser.registerOscHandler(104,new In(f=>this.restoreIndexedColor(f))),this._parser.registerOscHandler(110,new In(f=>this.restoreFgColor(f))),this._parser.registerOscHandler(111,new In(f=>this.restoreBgColor(f))),this._parser.registerOscHandler(112,new In(f=>this.restoreCursorColor(f))),this._parser.registerEscHandler({final:"7"},()=>this.saveCursor()),this._parser.registerEscHandler({final:"8"},()=>this.restoreCursor()),this._parser.registerEscHandler({final:"D"},()=>this.index()),this._parser.registerEscHandler({final:"E"},()=>this.nextLine()),this._parser.registerEscHandler({final:"H"},()=>this.tabSet()),this._parser.registerEscHandler({final:"M"},()=>this.reverseIndex()),this._parser.registerEscHandler({final:"="},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:">"},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:"c"},()=>this.fullReset()),this._parser.registerEscHandler({final:"n"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"o"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"|"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"}"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"~"},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:"%",final:"@"},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:"%",final:"G"},()=>this.selectDefaultCharset());for(let f in zi)this._parser.registerEscHandler({intermediates:"(",final:f},()=>this.selectCharset("("+f)),this._parser.registerEscHandler({intermediates:")",final:f},()=>this.selectCharset(")"+f)),this._parser.registerEscHandler({intermediates:"*",final:f},()=>this.selectCharset("*"+f)),this._parser.registerEscHandler({intermediates:"+",final:f},()=>this.selectCharset("+"+f)),this._parser.registerEscHandler({intermediates:"-",final:f},()=>this.selectCharset("-"+f)),this._parser.registerEscHandler({intermediates:".",final:f},()=>this.selectCharset("."+f)),this._parser.registerEscHandler({intermediates:"/",final:f},()=>this.selectCharset("/"+f));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(f=>(this._logService.error("Parsing error: ",f),f)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new $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>Ls&&(o=this._parseStack.position+Ls)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e=="string"?` "${e}"`:` "${Array.prototype.map.call(e,f=>String.fromCharCode(f)).join("")}"`}`),this._logService.logLevel===0&&this._logService.trace("parsing data (codes)",typeof e=="string"?e.split("").map(f=>f.charCodeAt(0)):e),this._parseBuffer.lengthLs)for(let f=o;f0&&x.getWidth(this._activeBuffer.x-1)===2&&x.setCellFromCodepoint(this._activeBuffer.x-1,0,1,_);let b=this._parser.precedingJoinState;for(let v=t;vh){if(p){let E=x,N=this._activeBuffer.x-R;for(this._activeBuffer.x=R,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),R>0&&x instanceof So&&x.copyCellsFrom(E,N,0,R,!1);N=0;)x.setCellFromCodepoint(this._activeBuffer.x++,0,0,_);continue}if(f&&(x.insertCells(this._activeBuffer.x,a-R,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 In(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(j[j.NOT_RECOGNIZED=0]="NOT_RECOGNIZED",j[j.SET=1]="SET",j[j.RESET=2]="RESET",j[j.PERMANENTLY_SET=3]="PERMANENTLY_SET",j[j.PERMANENTLY_RESET=4]="PERMANENTLY_RESET"))(void 0||(i={}));let s=this._coreService.decPrivateModes,{activeProtocol:a,activeEncoding:o}=this._coreMouseService,c=this._coreService,{buffers:h,cols:p}=this._bufferService,{active:f,alt:_}=h,x=this._optionsService.rawOptions,b=(j,R)=>(c.triggerDataEvent(`${pe.ESC}[${t?"":"?"}${j};${R}$y`),!0),v=j=>j?1:2,S=e.params[0];return t?S===2?b(S,4):S===4?b(S,v(c.modes.insertMode)):S===12?b(S,3):S===20?b(S,v(x.convertEol)):b(S,0):S===1?b(S,v(s.applicationCursorKeys)):S===3?b(S,x.windowOptions.setWinLines?p===80?2:p===132?1:0:0):S===6?b(S,v(s.origin)):S===7?b(S,v(s.wraparound)):S===8?b(S,3):S===9?b(S,v(a==="X10")):S===12?b(S,v(x.cursorBlink)):S===25?b(S,v(!c.isCursorHidden)):S===45?b(S,v(s.reverseWraparound)):S===66?b(S,v(s.applicationKeypad)):S===67?b(S,4):S===1e3?b(S,v(a==="VT200")):S===1002?b(S,v(a==="DRAG")):S===1003?b(S,v(a==="ANY")):S===1004?b(S,v(s.sendFocus)):S===1005?b(S,4):S===1006?b(S,v(o==="SGR")):S===1015?b(S,4):S===1016?b(S,v(o==="SGR_PIXELS")):S===1048?b(S,1):S===47||S===1047||S===1049?b(S,v(f===_)):S===2004?b(S,v(s.bracketedPasteMode)):S===2026?b(S,v(s.synchronizedOutput)):b(S,0)}_updateAttrColor(e,t,i,s,a){return t===2?(e|=50331648,e&=-16777216,e|=Oo.fromColorRGB([i,s,a])):t===5&&(e&=-50331904,e|=33554432|i&255),e}_extractColor(e,t,i){let s=[0,0,-1,0,0,0],a=0,o=0;do{if(s[o+a]=e.params[t+o],e.hasSubParams(t+o)){let c=e.getSubParams(t+o),h=0;do s[1]===5&&(a=1),s[o+h+1+a]=c[h];while(++h=2||s[1]===2&&o+a>=5)break;s[1]&&(a=1)}while(++o+t5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=ji.fg,e.bg=ji.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,i,s=this._curAttrData;for(let a=0;a=30&&i<=37?(s.fg&=-50331904,s.fg|=16777216|i-30):i>=40&&i<=47?(s.bg&=-50331904,s.bg|=16777216|i-40):i>=90&&i<=97?(s.fg&=-50331904,s.fg|=16777216|i-90|8):i>=100&&i<=107?(s.bg&=-50331904,s.bg|=16777216|i-100|8):i===0?this._processSGR0(s):i===1?s.fg|=134217728:i===3?s.bg|=67108864:i===4?(s.fg|=268435456,this._processUnderline(e.hasSubParams(a)?e.getSubParams(a)[0]:1,s)):i===5?s.fg|=536870912:i===7?s.fg|=67108864:i===8?s.fg|=1073741824:i===9?s.fg|=2147483648:i===2?s.bg|=134217728:i===21?this._processUnderline(2,s):i===22?(s.fg&=-134217729,s.bg&=-134217729):i===23?s.bg&=-67108865:i===24?(s.fg&=-268435457,this._processUnderline(0,s)):i===25?s.fg&=-536870913:i===27?s.fg&=-67108865:i===28?s.fg&=-1073741825:i===29?s.fg&=2147483647:i===39?(s.fg&=-67108864,s.fg|=ji.fg&16777215):i===49?(s.bg&=-67108864,s.bg|=ji.bg&16777215):i===38||i===48||i===58?a+=this._extractColor(e,a,s):i===53?s.bg|=1073741824:i===55?s.bg&=-1073741825:i===59?(s.extended=s.extended.clone(),s.extended.underlineColor=-1,s.updateExtended()):i===100?(s.fg&=-67108864,s.fg|=ji.fg&16777215,s.bg&=-67108864,s.bg|=ji.bg&16777215):this._logService.debug("Unknown SGR attribute: %d.",i);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${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=ji.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.length===0?1:e.params[0];if(t===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t){case 1:case 2:this._coreService.decPrivateModes.cursorStyle="block";break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle="underline";break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle="bar";break}let i=t%2===1;this._coreService.decPrivateModes.cursorBlink=i}return!0}setScrollRegion(e){let t=e.params[0]||1,i;return(e.length<2||(i=e.params[1])>this._bufferService.rows||i===0)&&(i=this._bufferService.rows),i>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=i-1,this._setCursor(0,0)),!0}windowOptions(e){if(!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=ji.clone(),this._eraseAttrDataInternal=ji.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=this._curAttrData.bg&67108863,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new sr;e.content=1<<22|69,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t(this._coreService.triggerDataEvent(`${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)}},bp=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)}};bp=gi([je(0,gn)],bp);function Kb(e){return 0<=e&&e<256}var uE=5e7,Vb=12,hE=50,dE=class extends dt{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new Se),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()}},vp=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)))}};vp=gi([je(0,gn)],vp);var Xb=!1,fE=class extends dt{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new fl),this._onBinary=this._register(new Se),this.onBinary=this._onBinary.event,this._onData=this._register(new Se),this.onData=this._onData.event,this._onLineFeed=this._register(new Se),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new Se),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new Se),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new Se),this._instantiationService=new z2,this.optionsService=this._register(new Y2(e)),this._instantiationService.setService(xn,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(mp)),this._instantiationService.setService(gn,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(pp)),this._instantiationService.setService(Dy,this._logService),this.coreService=this._register(this._instantiationService.createInstance(gp)),this._instantiationService.setService(ba,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(xp)),this._instantiationService.setService(My,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(pa)),this._instantiationService.setService(DC,this.unicodeService),this._charsetService=this._instantiationService.createInstance(Q2),this._instantiationService.setService(MC,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(vp),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(sn.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(sn.forward(this._bufferService.onResize,this._onResize)),this._register(sn.forward(this.coreService.onData,this._onData)),this._register(sn.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom(!0))),this._register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this._register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],()=>this._handleWindowsPtyOptionChange())),this._register(this._bufferService.onScroll(()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this._register(new dE((t,i)=>this._inputHandler.parse(t,i))),this._register(sn.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new Se),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=ai(()=>{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 vi=0,gE=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new Au,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new Au,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(e){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort((a,o)=>this._getKey(a)-this._getKey(o)),t=0,i=0,s=new Array(this._array.length+this._insertedValues.length);for(let a=0;a=this._array.length||this._getKey(e[t])<=this._getKey(this._array[i])?(s[a]=e[t],t++):s[a]=this._array[i++];this._array=s,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),this._array.length===0)return!1;let t=this._getKey(e);if(t===void 0||(vi=this._search(t),vi===-1)||this._getKey(this._array[vi])!==t)return!1;do if(this._array[vi]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(vi),!0;while(++via-o),t=0,i=new Array(this._array.length-e.length),s=0;for(let a=0;a0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(vi=this._search(e),!(vi<0||vi>=this._array.length)&&this._getKey(this._array[vi])===e))do yield this._array[vi];while(++vi=this._array.length)&&this._getKey(this._array[vi])===e))do t(this._array[vi]);while(++vi=t;){let s=t+i>>1,a=this._getKey(this._array[s]);if(a>e)i=s-1;else if(a0&&this._getKey(this._array[s-1])===e;)s--;return s}}return t}},df=0,Zb=0,xE=class extends dt{constructor(){super(),this._decorations=new gE(e=>e==null?void 0:e.marker.line),this._onDecorationRegistered=this._register(new Se),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new Se),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(ai(()=>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{df=a.options.x??0,Zb=df+(a.options.width??1),e>=df&&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,Ru=class extends dt{constructor(e,t,i,s){super(),this._terminal=e,this._coreBrowserService=i,this._renderService=s,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="";let a=this._coreBrowserService.mainDocument;this._accessibilityContainer=a.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=a.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let o=0;othis._handleBoundaryFocus(o,0),this._bottomBoundaryFocusListener=o=>this._handleBoundaryFocus(o,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=a.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new 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(Ve(a,"selectionchange",()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(ai(()=>{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+=Hf.get())))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let i=this._terminal.buffer,s=i.lines.length.toString();for(let a=e;a<=t;a++){let o=i.lines.get(i.ydisp+a),c=[],h=(o==null?void 0:o.translateToString(!0,void 0,void 0,c))||"",p=(i.ydisp+a+1).toString(),f=this._rowElements[a];f&&(h.length===0?(f.textContent=" ",this._rowColumns.set(f,[0,1])):(f.textContent=h,this._rowColumns.set(f,c)),f.setAttribute("aria-posinset",p),f.setAttribute("aria-setsize",s),this._alignRowWidth(f))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(e,t){let i=e.target,s=this._rowElements[t===0?1:this._rowElements.length-2],a=i.getAttribute("aria-posinset"),o=t===0?"1":`${this._terminal.buffer.lines.length}`;if(a===o||e.relatedTarget!==s)return;let c,h;if(t===0?(c=i,h=this._rowElements.pop(),this._rowContainer.removeChild(h)):(c=this._rowElements.shift(),h=i,this._rowContainer.removeChild(c)),c.removeEventListener("focus",this._topBoundaryFocusListener),h.removeEventListener("focus",this._bottomBoundaryFocusListener),t===0){let p=this._createAccessibilityTreeNode();this._rowElements.unshift(p),this._rowContainer.insertAdjacentElement("afterbegin",p)}else{let p=this._createAccessibilityTreeNode();this._rowElements.push(p),this._rowContainer.appendChild(p)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){var h;if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error("anchorNode and/or focusNode are null");return}let t={node:e.anchorNode,offset:e.anchorOffset},i={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(i.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===i.node&&t.offset>i.offset)&&([t,i]=[i,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let s=this._rowElements.slice(-1)[0];if(i.node.compareDocumentPosition(s)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(i={node:s,offset:((h=s.textContent)==null?void 0:h.length)??0}),!this._rowContainer.contains(i.node))return;let a=({node:p,offset:f})=>{let _=p instanceof Text?p.parentNode:p,x=parseInt(_==null?void 0:_.getAttribute("aria-posinset"),10)-1;if(isNaN(x))return console.warn("row is invalid. Race condition?"),null;let b=this._rowColumns.get(_);if(!b)return console.warn("columns is null. Race condition?"),null;let v=f=this._terminal.cols&&(++x,v=0),{row:x,column:v}},o=a(t),c=a(i);if(!(!o||!c)){if(o.row>c.row||o.row===c.row&&o.column>=c.column)throw new Error("invalid range");this._terminal.select(o.column,o.row,(c.row-o.row)*this._terminal.cols-o.column+c.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let t=this._rowContainer.children.length;te;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement("div");return e.setAttribute("role","listitem"),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e{var o;ga(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,(o=this._activeProviderReplies)==null||o.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(Ve(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(Ve(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register(Ve(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register(Ve(this._element,"mouseup",this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;let i=e.composedPath();for(let s=0;s{o==null||o.forEach(c=>{c.link.dispose&&c.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let i=!1;for(let[o,c]of this._linkProviderService.linkProviders.entries())t?(a=this._activeProviderReplies)!=null&&a.get(o)&&(i=this._checkLinkProviderResult(o,e,i)):c.provideLinks(e.y,h=>{var f,_;if(this._isMouseOut)return;let p=h==null?void 0:h.map(x=>({link:x}));(f=this._activeProviderReplies)==null||f.set(o,p),i=this._checkLinkProviderResult(o,e,i),((_=this._activeProviderReplies)==null?void 0:_.size)===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let i=new Set;for(let s=0;se?this._bufferService.cols:c.link.range.end.x;for(let f=h;f<=p;f++){if(i.has(f)){a.splice(o--,1);break}i.add(f)}}}}_checkLinkProviderResult(e,t,i){var o;if(!this._activeProviderReplies)return i;let s=this._activeProviderReplies.get(e),a=!1;for(let c=0;cthis._linkAtPosition(h.link,t));c&&(i=!0,this._handleNewLink(c))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!i)for(let c=0;cthis._linkAtPosition(p.link,t));if(h){i=!0,this._handleNewLink(h);break}}return i}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&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,ga(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:e.link.decorations===void 0?!0:e.link.decorations.underline,pointerCursor:e.link.decorations===void 0?!0:e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>{var i,s;return(s=(i=this._currentLink)==null?void 0:i.state)==null?void 0:s.decorations.pointerCursor},set:i=>{var s;(s=this._currentLink)!=null&&s.state&&this._currentLink.state.decorations.pointerCursor!==i&&(this._currentLink.state.decorations.pointerCursor=i,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",i))}},underline:{get:()=>{var i,s;return(s=(i=this._currentLink)==null?void 0:i.state)==null?void 0:s.decorations.underline},set:i=>{var s,a,o;(s=this._currentLink)!=null&&s.state&&((o=(a=this._currentLink)==null?void 0:a.state)==null?void 0:o.decorations.underline)!==i&&(this._currentLink.state.decorations.underline=i,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,i))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(i=>{if(!this._currentLink)return;let s=i.start===0?0:i.start+1+this._bufferService.buffer.ydisp,a=this._bufferService.buffer.ydisp+1+i.end;if(this._currentLink.link.range.start.y>=s&&this._currentLink.link.range.end.y<=a&&(this._clearCurrentLink(s,a),this._lastMouseEvent)){let o=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);o&&this._askForLink(o,!1)}})))}_linkHover(e,t,i){var s;(s=this._currentLink)!=null&&s.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add("xterm-cursor-pointer")),t.hover&&t.hover(i,t.text)}_fireUnderlineEvent(e,t){let i=e.range,s=this._bufferService.buffer.ydisp,a=this._createLinkUnderlineEvent(i.start.x-1,i.start.y-s-1,i.end.x,i.end.y-s-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(a)}_linkLeave(e,t,i){var s;(s=this._currentLink)!=null&&s.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove("xterm-cursor-pointer")),t.leave&&t.leave(i,t.text)}_linkAtPosition(e,t){let i=e.range.start.y*this._bufferService.cols+e.range.start.x,s=e.range.end.y*this._bufferService.cols+e.range.end.x,a=t.y*this._bufferService.cols+t.x;return i<=a&&a<=s}_positionFromMouseEvent(e,t,i){let s=i.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(s)return{x:s[0],y:s[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,i,s,a){return{x1:e,y1:t,x2:i,y2:s,cols:this._bufferService.cols,fg:a}}};yp=gi([je(1,Up),je(2,is),je(3,gn),je(4,Oy)],yp);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 fl),this.browser=t0,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new fl),this._onCursorMove=this._register(new Se),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new Se),this.onKey=this._onKey.event,this._onRender=this._register(new Se),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new Se),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new Se),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new Se),this.onBell=this._onBell.event,this._onFocus=this._register(new Se),this._onBlur=this._register(new Se),this._onA11yCharEmitter=this._register(new Se),this._onA11yTabEmitter=this._register(new Se),this._onWillOpen=this._register(new Se),this._setup(),this._decorationService=this._instantiationService.createInstance(xE),this._instantiationService.setService(zo,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(h2),this._instantiationService.setService(Oy,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance($f)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(t=>this.refresh((t==null?void 0:t.start)??0,(t==null?void 0:t.end)??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(t=>this._reportWindowsOptions(t))),this._register(this._inputHandler.onColor(t=>this._handleColorEvent(t))),this._register(sn.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(sn.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(sn.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(sn.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(t=>this._afterResize(t.cols,t.rows))),this._register(ai(()=>{var t,i;this._customKeyEventHandler=void 0,(i=(t=this.element)==null?void 0:t.parentNode)==null||i.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(e){if(this._themeService)for(let t of e){let i,s="";switch(t.index){case 256:i="foreground",s="10";break;case 257:i="background",s="11";break;case 258:i="cursor",s="12";break;default:i="ansi",s="4;"+t.index}switch(t.type){case 0:let a=ni.toColorRGB(i==="ansi"?this._themeService.colors.ansi[t.index]:this._themeService.colors[i]);this.coreService.triggerDataEvent(`${pe.ESC}]${s};${lE(a)}${Jy.ST}`);break;case 1:if(i==="ansi")this._themeService.modifyColors(o=>o.ansi[t.index]=Ti.toColor(...t.color));else{let o=i;this._themeService.modifyColors(c=>c[o]=Ti.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index);break}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(Ru,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(Ve(this.element,"copy",t=>{this.hasSelection()&&EC(t,this._selectionService)}));let e=t=>NC(t,this.textarea,this.coreService,this.optionsService);this._register(Ve(this.textarea,"paste",e)),this._register(Ve(this.element,"paste",e)),i0?this._register(Ve(this.element,"mousedown",t=>{t.button===2&&ob(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(Ve(this.element,"contextmenu",t=>{ob(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),Vp&&this._register(Ve(this.element,"auxclick",t=>{t.button===1&&Ny(t,this.textarea,this.screenElement)}))}_bindKeys(){this._register(Ve(this.textarea,"keyup",e=>this._keyUp(e),!0)),this._register(Ve(this.textarea,"keydown",e=>this._keyDown(e),!0)),this._register(Ve(this.textarea,"keypress",e=>this._keyPress(e),!0)),this._register(Ve(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register(Ve(this.textarea,"compositionupdate",e=>this._compositionHelper.compositionupdate(e))),this._register(Ve(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register(Ve(this.textarea,"input",e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){var a;if(!e)throw new Error("Terminal requires a parent element.");if(e.isConnected||this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"),((a=this.element)==null?void 0:a.ownerDocument.defaultView)&&this._coreBrowserService){this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView);return}this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement("div"),this.element.dir="ltr",this.element.classList.add("terminal"),this.element.classList.add("xterm"),e.appendChild(this.element);let t=this._document.createDocumentFragment();this._viewportElement=this._document.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),t.appendChild(this._viewportElement),this.screenElement=this._document.createElement("div"),this.screenElement.classList.add("xterm-screen"),this._register(Ve(this.screenElement,"mousemove",o=>this.updateCursorStyle(o))),this._helperContainer=this._document.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let i=this.textarea=this._document.createElement("textarea");this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",If.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(ts,this._coreBrowserService),this._register(Ve(this.textarea,"focus",o=>this._handleTextAreaFocus(o))),this._register(Ve(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(cp,this._document,this._helperContainer),this._instantiationService.setService(Pu,this._charSizeService),this._themeService=this._instantiationService.createInstance(fp),this._instantiationService.setService(gl,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(ju),this._instantiationService.setService(Ly,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(hp,this.rows,this.screenElement)),this._instantiationService.setService(is,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(ap,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(up),this._instantiationService.setService(Up,this._mouseService);let s=this._linkifier.value=this._register(this._instantiationService.createInstance(yp,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(rp,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(dp,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(sn.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{var o;this._selectionService.refresh(),(o=this._viewport)==null||o.queueSync()})),this._register(this._instantiationService.createInstance(sp,this.screenElement)),this._register(Ve(this.element,"mousedown",o=>this._selectionService.handleMouseDown(o))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add("enable-mouse-events")):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(Ru,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",o=>this._handleScreenReaderModeOptionChange(o))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(Nu,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",o=>{!this._overviewRulerRenderer&&o&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(Nu,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(op,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function i(o){var f,_,x,b,v;let c=e._mouseService.getMouseReportCoords(o,e.screenElement);if(!c)return!1;let h,p;switch(o.overrideType||o.type){case"mousemove":p=32,o.buttons===void 0?(h=3,o.button!==void 0&&(h=o.button<3?o.button:3)):h=o.buttons&1?0:o.buttons&4?1:o.buttons&2?2:3;break;case"mouseup":p=0,h=o.button<3?o.button:3;break;case"mousedown":p=1,h=o.button<3?o.button:3;break;case"wheel":if(e._customWheelEventHandler&&e._customWheelEventHandler(o)===!1)return!1;let S=o.deltaY;if(S===0||e.coreMouseService.consumeWheelEvent(o,(b=(x=(_=(f=e._renderService)==null?void 0:f.dimensions)==null?void 0:_.device)==null?void 0:x.cell)==null?void 0:b.height,(v=e._coreBrowserService)==null?void 0:v.dpr)===0)return!1;p=S<0?0:1,h=4;break;default:return!1}return p===void 0||h===void 0||h>4?!1:e.coreMouseService.triggerMouseEvent({col:c.col,row:c.row,x:c.x,y:c.y,button:h,action:p,ctrl:o.ctrlKey,alt:o.altKey,shift:o.shiftKey})}let s={mouseup:null,wheel:null,mousedrag:null,mousemove:null},a={mouseup:o=>(i(o),o.buttons||(this._document.removeEventListener("mouseup",s.mouseup),s.mousedrag&&this._document.removeEventListener("mousemove",s.mousedrag)),this.cancel(o)),wheel:o=>(i(o),this.cancel(o,!0)),mousedrag:o=>{o.buttons&&i(o)},mousemove:o=>{o.buttons||i(o)}};this._register(this.coreMouseService.onProtocolChange(o=>{o?(this.optionsService.rawOptions.logLevel==="debug"&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(o)),this.element.classList.add("enable-mouse-events"),this._selectionService.disable()):(this._logService.debug("Unbinding from mouse events."),this.element.classList.remove("enable-mouse-events"),this._selectionService.enable()),o&8?s.mousemove||(t.addEventListener("mousemove",a.mousemove),s.mousemove=a.mousemove):(t.removeEventListener("mousemove",s.mousemove),s.mousemove=null),o&16?s.wheel||(t.addEventListener("wheel",a.wheel,{passive:!1}),s.wheel=a.wheel):(t.removeEventListener("wheel",s.wheel),s.wheel=null),o&2?s.mouseup||(s.mouseup=a.mouseup):(this._document.removeEventListener("mouseup",s.mouseup),s.mouseup=null),o&4?s.mousedrag||(s.mousedrag=a.mousedrag):(this._document.removeEventListener("mousemove",s.mousedrag),s.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(Ve(t,"mousedown",o=>{if(o.preventDefault(),this.focus(),!(!this.coreMouseService.areMouseEventsActive||this._selectionService.shouldForceSelection(o)))return i(o),s.mouseup&&this._document.addEventListener("mouseup",s.mouseup),s.mousedrag&&this._document.addEventListener("mousemove",s.mousedrag),this.cancel(o)})),this._register(Ve(t,"wheel",o=>{var c,h,p,f,_;if(!s.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(o)===!1)return!1;if(!this.buffer.hasScrollback){if(o.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(o,(f=(p=(h=(c=e._renderService)==null?void 0:c.dimensions)==null?void 0:h.device)==null?void 0:p.cell)==null?void 0:f.height,(_=e._coreBrowserService)==null?void 0:_.dpr)===0)return this.cancel(o,!0);let x=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 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 kE(t)}getNullCell(){return new sr}},EE=class extends dt{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new Se),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)}},jE=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}},TE=["cols","rows"],wr=0,AE=class extends dt{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(TE.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 jE(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 If.get()},set promptLabel(e){If.set(e)},get tooMuchOutput(){return Hf.get()},set tooMuchOutput(e){Hf.set(e)}}}_verifyIntegers(...e){for(wr of e)if(wr===1/0||isNaN(wr)||wr%1!==0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(wr of e)if(wr&&(wr===1/0||isNaN(wr)||wr%1!==0||wr<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 Fi=0,qi=0,Wi=0,mi=0,cn;(e=>{function t(a,o,c,h){return h!==void 0?`#${ca(a)}${ca(o)}${ca(c)}${ca(h)}`:`#${ca(a)}${ca(o)}${ca(c)}`}e.toCss=t;function i(a,o,c,h=255){return(a<<24|o<<16|c<<8|h)>>>0}e.toRgba=i;function s(a,o,c,h){return{css:e.toCss(a,o,c,h),rgba:e.toRgba(a,o,c,h)}}e.toColor=s})(cn||(cn={}));var BE;(e=>{function t(p,f){if(mi=(f.rgba&255)/255,mi===1)return{css:f.css,rgba:f.rgba};let _=f.rgba>>24&255,x=f.rgba>>16&255,b=f.rgba>>8&255,v=p.rgba>>24&255,S=p.rgba>>16&255,j=p.rgba>>8&255;Fi=v+Math.round((_-v)*mi),qi=S+Math.round((x-S)*mi),Wi=j+Math.round((b-j)*mi);let R=cn.toCss(Fi,qi,Wi),E=cn.toRgba(Fi,qi,Wi);return{css:R,rgba:E}}e.blend=t;function i(p){return(p.rgba&255)===255}e.isOpaque=i;function s(p,f,_){let x=vu.ensureContrastRatio(p.rgba,f.rgba,_);if(x)return cn.toColor(x>>24&255,x>>16&255,x>>8&255)}e.ensureContrastRatio=s;function a(p){let f=(p.rgba|255)>>>0;return[Fi,qi,Wi]=vu.toChannels(f),{css:cn.toCss(Fi,qi,Wi),rgba:f}}e.opaque=a;function o(p,f){return mi=Math.round(f*255),[Fi,qi,Wi]=vu.toChannels(p.rgba),{css:cn.toCss(Fi,qi,Wi,mi),rgba:cn.toRgba(Fi,qi,Wi,mi)}}e.opacity=o;function c(p,f){return mi=p.rgba&255,o(p,mi*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 nn;(e=>{let t,i;try{let a=document.createElement("canvas");a.width=1,a.height=1;let o=a.getContext("2d",{willReadFrequently:!0});o&&(t=o,t.globalCompositeOperation="copy",i=t.createLinearGradient(0,0,1,1))}catch{}function s(a){if(a.match(/#[\da-f]{3,8}/i))switch(a.length){case 4:return Fi=parseInt(a.slice(1,2).repeat(2),16),qi=parseInt(a.slice(2,3).repeat(2),16),Wi=parseInt(a.slice(3,4).repeat(2),16),cn.toColor(Fi,qi,Wi);case 5:return Fi=parseInt(a.slice(1,2).repeat(2),16),qi=parseInt(a.slice(2,3).repeat(2),16),Wi=parseInt(a.slice(3,4).repeat(2),16),mi=parseInt(a.slice(4,5).repeat(2),16),cn.toColor(Fi,qi,Wi,mi);case 7:return{css:a,rgba:(parseInt(a.slice(1),16)<<8|255)>>>0};case 9:return{css:a,rgba:parseInt(a.slice(1),16)>>>0}}let o=a.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(o)return Fi=parseInt(o[1]),qi=parseInt(o[2]),Wi=parseInt(o[3]),mi=Math.round((o[5]===void 0?1:parseFloat(o[5]))*255),cn.toColor(Fi,qi,Wi,mi);if(!t||!i)throw new Error("css.toColor: Unsupported css format");if(t.fillStyle=i,t.fillStyle=a,typeof t.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(t.fillRect(0,0,1,1),[Fi,qi,Wi,mi]=t.getImageData(0,0,1,1).data,mi!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:cn.toRgba(Fi,qi,Wi,mi),css:a}}e.toColor=s})(nn||(nn={}));var pn;(e=>{function t(s){return i(s>>16&255,s>>8&255,s&255)}e.relativeLuminance=t;function i(s,a,o){let c=s/255,h=a/255,p=o/255,f=c<=.03928?c/12.92:Math.pow((c+.055)/1.055,2.4),_=h<=.03928?h/12.92:Math.pow((h+.055)/1.055,2.4),x=p<=.03928?p/12.92:Math.pow((p+.055)/1.055,2.4);return f*.2126+_*.7152+x*.0722}e.relativeLuminance2=i})(pn||(pn={}));var vu;(e=>{function t(c,h){if(mi=(h&255)/255,mi===1)return h;let p=h>>24&255,f=h>>16&255,_=h>>8&255,x=c>>24&255,b=c>>16&255,v=c>>8&255;return Fi=x+Math.round((p-x)*mi),qi=b+Math.round((f-b)*mi),Wi=v+Math.round((_-v)*mi),cn.toRgba(Fi,qi,Wi)}e.blend=t;function i(c,h,p){let f=pn.relativeLuminance(c>>8),_=pn.relativeLuminance(h>>8);if(Zr(f,_)>8));if(S>8));return S>R?v:j}return v}let x=a(c,h,p),b=Zr(f,pn.relativeLuminance(x>>8));if(b>8));return b>S?x:v}return x}}e.ensureContrastRatio=i;function s(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,j=Zr(pn.relativeLuminance2(b,v,S),pn.relativeLuminance2(f,_,x));for(;j0||v>0||S>0);)b-=Math.max(0,Math.ceil(b*.1)),v-=Math.max(0,Math.ceil(v*.1)),S-=Math.max(0,Math.ceil(S*.1)),j=Zr(pn.relativeLuminance2(b,v,S),pn.relativeLuminance2(f,_,x));return(b<<24|v<<16|S<<8|255)>>>0}e.reduceLuminance=s;function a(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,j=Zr(pn.relativeLuminance2(b,v,S),pn.relativeLuminance2(f,_,x));for(;j>>0}e.increaseLuminance=a;function o(c){return[c>>24&255,c>>16&255,c>>8&255,c&255]}e.toChannels=o})(vu||(vu={}));function ca(e){let t=e.toString(16);return t.length<2?"0"+t:t}function Zr(e,t){return e{let e=[nn.toColor("#2e3436"),nn.toColor("#cc0000"),nn.toColor("#4e9a06"),nn.toColor("#c4a000"),nn.toColor("#3465a4"),nn.toColor("#75507b"),nn.toColor("#06989a"),nn.toColor("#d3d7cf"),nn.toColor("#555753"),nn.toColor("#ef2929"),nn.toColor("#8ae234"),nn.toColor("#fce94f"),nn.toColor("#729fcf"),nn.toColor("#ad7fa8"),nn.toColor("#34e2e2"),nn.toColor("#eeeeec")],t=[0,95,135,175,215,255];for(let i=0;i<216;i++){let s=t[i/36%6|0],a=t[i/6%6|0],o=t[i%6];e.push({css:cn.toCss(s,a,o),rgba:cn.toRgba(s,a,o)})}for(let i=0;i<24;i++){let s=8+i*10;e.push({css:cn.toCss(s,s,s),rgba:cn.toRgba(s,s,s)})}return e})());function 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&&!Qr(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)&&Qr(c,p)&&(_=!0),f&&(h.getChars()||h.getWidth()===0)&&Qr(c,p)&&Qr(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=!Qr(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?!Qr(this._cursorStyle,e):o.length>0){this._nullCellCount>0&&(Qr(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&&(Qr(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=!Qr(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__",rl="[REDACTED]",UE=[[/(authorization\s*:\s*bearer\s+)[^\s'"\x1b]+/gi,`$1${rl}`],[/(\bbearer\s+)[A-Za-z0-9._-]{12,}/gi,`$1${rl}`],[/(\btoken=)[^\s'"&\x1b]+/gi,`$1${rl}`],[/(OWS_PASSPHRASE\s*[=:]\s*)[^\s'"\x1b]+/gi,`$1${rl}`],[/(--passphrase[=\s]+)[^\s'"\x1b]+/gi,`$1${rl}`],[/(passphrase["']?\s*[:=]\s*["']?)[^\s'"\x1b]+/gi,`$1${rl}`]];function 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,Us="scrollback",nv=10*1024*1024;function Xp(){return new Promise((e,t)=>{const i=indexedDB.open(qE,WE);i.onupgradeneeded=()=>{const s=i.result;s.objectStoreNames.contains(Us)||s.createObjectStore(Us)},i.onsuccess=()=>e(i.result),i.onerror=()=>t(i.error)})}async function sl(e,t){const i=t.length>nv?t.slice(-nv):t,s=await Xp();return new Promise((a,o)=>{const c=s.transaction(Us,"readwrite");c.objectStore(Us).put(i,e),c.oncomplete=()=>{s.close(),a()},c.onerror=()=>{s.close(),o(c.error)}})}async function GE(e){const t=await Xp();return new Promise((i,s)=>{const o=t.transaction(Us,"readonly").objectStore(Us).get(e);o.onsuccess=()=>{t.close(),i(o.result??null)},o.onerror=()=>{t.close(),s(o.error)}})}async function ff(e){const t=await Xp();return new Promise((i,s)=>{const a=t.transaction(Us,"readwrite");a.objectStore(Us).delete(e),a.oncomplete=()=>{t.close(),i()},a.onerror=()=>{t.close(),s(a.error)}})}const Oi=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 S=w.useRef(null),j=w.useRef(i),[R,E]=w.useState([]),[N,z]=w.useState(new Set),[J,F]=w.useState(null),[M,ee]=w.useState(null),[fe,ye]=w.useState(!1),[P,ae]=w.useState(!1),W=$E(x,_),Y=!!b,V=w.useRef(()=>{});w.useEffect(()=>{j.current=i},[i]);const I=w.useCallback(H=>{var xe;const{width:le}=H.container.getBoundingClientRect();if(!(le<50))try{H.fit.fit(),((xe=H.ws)==null?void 0:xe.readyState)===WebSocket.OPEN&&H.ws.send(JSON.stringify({type:"resize",cols:H.term.cols,rows:H.term.rows}))}catch{}},[]),A=w.useCallback(H=>{for(const[le,xe]of Oi)xe.container.style.display=le===H?"block":"none";if(H){const le=Oi.get(H);le&&setTimeout(()=>I(le),50)}},[I]),L=w.useRef({});w.useEffect(()=>{L.current=p||{}},[p]);const U=w.useRef({});w.useEffect(()=>{U.current=f||{}},[f]);const ge=w.useCallback((H,le,xe)=>{const Re=window.location.protocol==="https:"?"wss:":"ws:",Me=L.current[H]?"&bypass=true":"",Le=U.current[H],Ae=Le?`&provider=${encodeURIComponent(Le)}`:"",ut=new WebSocket(`${Re}//${window.location.host}/ws/terminal?story=${encodeURIComponent(H)}&token=${e}&resume=${xe}${Me}${Ae}`);ut.onopen=()=>{le.connected=!0,le._retried=!1,z(bt=>{const Qe=new Set(bt);return Qe.delete(H),Qe}),ut.send(JSON.stringify({type:"resize",cols:le.term.cols,rows:le.term.rows}))};let We=!0;ut.onmessage=bt=>{if(We&&(We=!1,typeof bt.data=="string"&&bt.data===HE)){le.term.reset(),ff(H).catch(()=>{});return}le.term.write(typeof bt.data=="string"?tv(bt.data):bt.data)},ut.onclose=bt=>{if(le.connected=!1,le.ws===ut){le.ws=null;try{const Qe=le.serialize.serialize();sl(H,Qe).catch(()=>{})}catch{}if(bt.code===4e3&&!le._retried){le._retried=!0,le.term.write(`\r -\x1B[33m[Resume failed — starting fresh session...]\x1B[0m\r -`),V.current(H,le,!1);return}z(Qe=>new Set(Qe).add(H))}},le.term.onData(bt=>{ut.readyState===WebSocket.OPEN&&ut.send(bt)}),le.ws=ut},[e]);w.useEffect(()=>{V.current=ge},[ge]);const T=w.useCallback(async(H,le)=>{if(!S.current||Oi.has(H))return;const{resume:xe=!1,autoConnect:Re=!0}=le??{},Me=document.createElement("div");Me.style.width="100%",Me.style.height="100%",Me.style.display="none",Me.style.paddingLeft="10px",Me.style.boxSizing="border-box",S.current.appendChild(Me);const Le=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}),Ae=new DE,ut=new PE;Le.loadAddon(Ae),Le.loadAddon(ut),Le.open(Me);const We={term:Le,fit:Ae,serialize:ut,ws:null,container:Me,observer:null,connected:!1},bt=new ResizeObserver(()=>{var Ft;const{width:Qe}=Me.getBoundingClientRect();if(!(Qe<50))try{Ae.fit(),((Ft=We.ws)==null?void 0:Ft.readyState)===WebSocket.OPEN&&We.ws.send(JSON.stringify({type:"resize",cols:Le.cols,rows:Le.rows}))}catch{}});bt.observe(Me),We.observer=bt,Oi.set(H,We),E(Qe=>[...Qe,H]);try{const Qe=await GE(H);if(Qe){const Ft=tv(Qe);Le.write(Ft),Ft!==Qe&&sl(H,Ft).catch(()=>{})}}catch{}Re?ge(H,We,xe):z(Qe=>new Set(Qe).add(H)),setTimeout(()=>I(We),50)},[ge,I]),D=w.useCallback(async(H,le)=>{const xe=Oi.get(H);xe&&(xe.ws&&(xe.ws.close(),xe.ws=null),le||(await j.current(`/api/terminal/${encodeURIComponent(H)}`,{method:"DELETE"}).catch(()=>{}),xe.term.clear()),ge(H,xe,le))},[ge]),K=w.useCallback(H=>{const le=Oi.get(H);if(le){try{const xe=le.serialize.serialize();sl(H,xe).catch(()=>{})}catch{}le.observer.disconnect(),le.ws&&le.ws.close(),le.term.dispose(),le.container.remove(),Oi.delete(H),E(xe=>xe.filter(Re=>Re!==H)),z(xe=>{const Re=new Set(xe);return Re.delete(H),Re}),i(`/api/terminal/${encodeURIComponent(H)}`,{method:"DELETE"}).catch(()=>{}),a==null||a(H)}},[i,a]),k=w.useCallback(H=>{var xe;const le=Oi.get(H);le&&(((xe=le.ws)==null?void 0:xe.readyState)===WebSocket.OPEN&&le.ws.send(`exit -`),ff(H).catch(()=>{}),le.observer.disconnect(),le.ws&&le.ws.close(),le.term.dispose(),le.container.remove(),Oi.delete(H),E(Re=>Re.filter(Me=>Me!==H)),z(Re=>{const Me=new Set(Re);return Me.delete(H),Me}),i(`/api/terminal/${encodeURIComponent(H)}/discard`,{method:"DELETE"}).catch(()=>{}),a==null||a(H))},[i,a]),ue=w.useCallback(async(H,le,xe)=>{const Re=Oi.get(H);if(!Re||Oi.has(le)||!(await j.current("/api/terminal/rename",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldName:H,newName:le,...xe??{}})})).ok)return!1;Oi.delete(H),Oi.set(le,Re);try{const Le=Re.serialize.serialize();await ff(H),await sl(le,Le)}catch{}return E(Le=>Le.map(Ae=>Ae===H?le:Ae)),z(Le=>{if(!Le.has(H))return Le;const Ae=new Set(Le);return Ae.delete(H),Ae.add(le),Ae}),(Re.connected||Re.ws)&&(await j.current(`/api/terminal/${encodeURIComponent(le)}`,{method:"DELETE"}).catch(()=>{}),Re.ws&&(Re.ws.close(),Re.ws=null),V.current(le,Re,!0)),!0},[]);w.useEffect(()=>(h&&(h.current=ue),()=>{h&&(h.current=null)}),[h,ue]),w.useEffect(()=>{if(t){if(W){A(null);return}if(Y){A(null);return}Oi.has(t)?A(t):j.current(`/api/terminal/session/${encodeURIComponent(t)}`).then(H=>H.ok?H.json():null).then(H=>{if(!Oi.has(t)){const le=(H==null?void 0:H.sessionId)&&!(H!=null&&H.running);T(t,{autoConnect:!le}),A(t)}}).catch(()=>{Oi.has(t)||(T(t),A(t))})}},[t,T,A,W,Y]),w.useEffect(()=>{const H=setInterval(()=>{for(const[le,xe]of Oi)if(xe.connected)try{const Re=xe.serialize.serialize();sl(le,Re).catch(()=>{})}catch{}},3e4);return()=>clearInterval(H)},[]),w.useEffect(()=>()=>{for(const[H,le]of Oi){try{const xe=le.serialize.serialize();sl(H,xe).catch(()=>{})}catch{}le.observer.disconnect(),le.ws&&le.ws.close(),le.term.dispose(),le.container.remove(),j.current(`/api/terminal/${encodeURIComponent(H)}`,{method:"DELETE"}).catch(()=>{})}Oi.clear()},[]);const te=t?N.has(t):!1,G=R.length===0;return d.jsxs("div",{className:"h-full flex flex-col",children:[!G&&d.jsxs("div",{className:"px-2 py-1 border-b border-border flex items-center gap-1 overflow-x-auto",children:[R.map(H=>d.jsxs("div",{onClick:()=>s==null?void 0:s(H),className:`flex items-center gap-1 px-2 py-0.5 rounded text-xs font-mono cursor-pointer ${H===t?"bg-accent/10 text-accent":"text-muted hover:text-foreground"}`,children:[d.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${N.has(H)?"bg-amber-500":H===t?"bg-green-600":"bg-muted/50"}`}),d.jsx("span",{className:`truncate max-w-[120px] ${H.startsWith("_new_")?"italic":""}`,children:H.startsWith("_new_")?"Untitled":H}),d.jsx("button",{onClick:le=>{le.stopPropagation(),H.startsWith("_new_")?F(H):K(H)},className:"ml-0.5 text-muted hover:text-error text-[10px] leading-none",title:"Close terminal",children:"×"})]},H)),t!=null&&t.startsWith("_new_")?d.jsx("button",{onClick:()=>F(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:()=>ee(t),className:"ml-auto px-2 py-0.5 text-xs text-muted hover:text-foreground hover:bg-surface rounded flex items-center gap-1 flex-shrink-0",children:"Archive"}):null]}),d.jsxs("div",{className:"relative flex-1 min-h-0",children:[d.jsx("div",{ref:S,className:"h-full"}),G&&!W&&!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"})]})}),W&&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."]}):ku(_)?d.jsxs("p",{className:"text-xs text-amber-700","data-testid":"codex-auth-unknown-launch",children:[Ip," 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),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:fe?"Copied!":"Copy"})]})]})]})}),Y&&!W&&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"})]})}),J&&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:()=>F(null),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Cancel"}),d.jsx("button",{onClick:()=>{const H=J;F(null),k(H)},className:"px-4 py-1.5 bg-error text-white text-sm rounded hover:opacity-80",children:"Discard"})]})]})}),M&&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:()=>ee(null),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Cancel"}),d.jsx("button",{onClick:async()=>{const H=M;ee(null);try{(await j.current("/api/stories/archive",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:H})})).ok&&(K(H),o==null||o(H))}catch{}},className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim",children:"Archive"})]})]})}),te&&t&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"text-center space-y-3",children:[d.jsx("p",{className:"text-sm font-serif text-foreground",children:"Terminal disconnected"}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{onClick:()=>D(t,!0),className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim",children:"Resume Session"}),d.jsx("button",{onClick:()=>D(t,!1),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Start Fresh"})]}),d.jsx("p",{className:"text-xs text-muted",children:"Resume continues your previous Claude conversation"})]})})]})]})}function 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 Ho{constructor(t,i,s){this.normal=i,this.property=t,s&&(this.space=s)}}Ho.prototype.normal={};Ho.prototype.property={};Ho.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 Ho(i,s,t)}function Sp(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 eN=0;const ot=va(),Ni=va(),wp=va(),_e=va(),Jt=va(),ul=va(),Hn=va();function va(){return 2**++eN}const Cp=Object.freeze(Object.defineProperty({__proto__:null,boolean:ot,booleanish:Ni,commaOrSpaceSeparated:Hn,commaSeparated:ul,number:_e,overloadedBoolean:wp,spaceSeparated:Jt},Symbol.toStringTag,{value:"Module"})),pf=Object.keys(Cp);class Zp 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"&&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=Zp}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"),Qp=_0([b0,iN,S0,w0,C0],"svg");function uN(e){return e.join(" ").trim()}var al={},mf,ov;function hN(){if(ov)return mf;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 S(R,E){if(typeof R!="string")throw new TypeError("First argument must be a string");if(!R)return[];E=E||{};var N=1,z=1;function J(V){var I=V.match(t);I&&(N+=I.length);var A=V.lastIndexOf(p);z=~A?V.length-A:z+V.length}function F(){var V={line:N,column:z};return function(I){return I.position=new M(V),ye(),I}}function M(V){this.start=V,this.end={line:N,column:z},this.source=E.source}M.prototype.content=R;function ee(V){var I=new Error(E.source+":"+N+":"+z+": "+V);if(I.reason=V,I.filename=E.source,I.line=N,I.column=z,I.source=R,!E.silent)throw I}function fe(V){var I=V.exec(R);if(I){var A=I[0];return J(A),R=R.slice(A.length),I}}function ye(){fe(i)}function P(V){var I;for(V=V||[];I=ae();)I!==!1&&V.push(I);return V}function ae(){var V=F();if(!(f!=R.charAt(0)||_!=R.charAt(1))){for(var I=2;x!=R.charAt(I)&&(_!=R.charAt(I)||f!=R.charAt(I+1));)++I;if(I+=2,x===R.charAt(I-1))return ee("End of comment missing");var A=R.slice(2,I-2);return z+=2,J(A),R=R.slice(I),z+=2,V({type:b,comment:A})}}function W(){var V=F(),I=fe(s);if(I){if(ae(),!fe(a))return ee("property missing ':'");var A=fe(o),L=V({type:v,property:j(I[0].replace(e,x)),value:A?j(A[0].replace(e,x)):x});return fe(c),L}}function Y(){var V=[];P(V);for(var I;I=W();)I!==!1&&(V.push(I),P(V));return V}return ye(),Y()}function j(R){return R?R.replace(h,x):x}return mf=S,mf}var cv;function dN(){if(cv)return al;cv=1;var e=al&&al.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(al,"__esModule",{value:!0}),al.default=i;const t=e(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 al}var mo={},uv;function fN(){if(uv)return mo;uv=1,Object.defineProperty(mo,"__esModule",{value:!0}),mo.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 mo.camelCase=p,mo}var go,hv;function pN(){if(hv)return go;hv=1;var e=go&&go.__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,go=s,go}var mN=pN();const gN=Ou(mN),k0=E0("end"),Jp=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=Jp(e),i=k0(e);if(t&&i)return{start:t,end:i}}function Eo(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?kp(e):""}function kp(e){return fv(e&&e.line)+":"+fv(e&&e.column)}function dv(e){return kp(e&&e.start)+"-"+kp(e&&e.end)}function fv(e){return e&&typeof e=="number"?e:1}class hn extends Error{constructor(t,i,s){super(),typeof i=="string"&&(s=i,i=void 0);let a="",o={},c=!1;if(i&&("line"in i&&"column"in i?o={place:i}:"start"in i&&"end"in i?o={place:i}:"type"in i?o={ancestors:[i],place:i.position}:o={...i}),typeof t=="string"?a=t:!o.cause&&t&&(c=!0,a=t.message,o.cause=t),!o.ruleId&&!o.source&&typeof s=="string"){const p=s.indexOf(":");p===-1?o.ruleId=s:(o.source=s.slice(0,p),o.ruleId=s.slice(p+1))}if(!o.place&&o.ancestors&&o.ancestors){const p=o.ancestors[o.ancestors.length-1];p&&(o.place=p.position)}const h=o.place&&"start"in o.place?o.place.start:o.place;this.ancestors=o.ancestors||void 0,this.cause=o.cause||void 0,this.column=h?h.column:void 0,this.fatal=void 0,this.file="",this.message=a,this.line=h?h.line:void 0,this.name=Eo(o.place)||"1:1",this.place=o.place||void 0,this.reason=this.message,this.ruleId=o.ruleId||void 0,this.source=o.source||void 0,this.stack=c&&o.cause&&typeof o.cause.stack=="string"?o.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}hn.prototype.file="";hn.prototype.name="";hn.prototype.reason="";hn.prototype.message="";hn.prototype.stack="";hn.prototype.column=void 0;hn.prototype.line=void 0;hn.prototype.ancestors=void 0;hn.prototype.cause=void 0;hn.prototype.fatal=void 0;hn.prototype.place=void 0;hn.prototype.ruleId=void 0;hn.prototype.source=void 0;const em={}.hasOwnProperty,xN=new Map,_N=/[A-Z]/g,bN=new Set(["table","tbody","thead","tfoot","tr"]),vN=new Set(["td","th"]),j0="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=TN(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=jN(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"?Qp:cN,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},o=T0(a,e,void 0);return o&&typeof o!="string"?o:a.create(e,a.Fragment,{children:o||void 0},void 0)}function T0(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=Qp,e.schema=a),e.ancestors.push(t);const o=R0(e,t.tagName,!1),c=AN(e,t);let h=im(e,t);return bN.has(t.tagName)&&(h=h.filter(function(p){return typeof p=="string"?!JE(p):!0})),A0(e,c,o,t),tm(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)}Mo(e,t.position)}function CN(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);Mo(e,t.position)}function kN(e,t,i){const s=e.schema;let a=s;t.name==="svg"&&s.space==="html"&&(a=Qp,e.schema=a),e.ancestors.push(t);const o=t.name===null?e.Fragment:R0(e,t.name,!0),c=RN(e,t),h=im(e,t);return A0(e,c,o,t),tm(c,h),e.ancestors.pop(),e.schema=s,e.create(t,o,c,i)}function EN(e,t,i){const s={};return tm(s,im(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 tm(e,t){if(t.length>0){const i=t.length>1?t:t[0];i&&(e.children=i)}}function jN(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 TN(e,t){return i;function i(s,a,o,c){const h=Array.isArray(o.children),p=Jp(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"&&em.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 Mo(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 Mo(e,t.position);else o=s.value===null?!0:s.value;i[a]=o}return i}function im(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?(Un(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 fr(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const mn=$s(/[A-Za-z]/),un=$s(/[\dA-Za-z]/),UN=$s(/[#-'*+\--9=?A-Z^-~]/);function Mu(e){return e!==null&&(e<32||e===127)}const Ep=$s(/\d/),$N=$s(/[\dA-Fa-f]/),FN=$s(/[!-/:-@[-`{-~]/);function $e(e){return e!==null&&e<-2}function Qt(e){return e!==null&&(e<0||e===32)}function _t(e){return e===-2||e===-1||e===32}const Uu=$s(new RegExp("\\p{P}|\\p{S}","u")),_a=$s(/\s/);function $s(e){return t;function t(i){return i!==null&&i>-1&&e.test(String.fromCharCode(i))}}function bl(e){const t=[];let i=-1,s=0,a=0;for(;++i55295&&o<57344){const h=e.charCodeAt(i+1);o<56320&&h>56319&&h<57344?(c=String.fromCharCode(o,h),a=1):c="�"}else c=String.fromCharCode(o);c&&(t.push(e.slice(s,i),encodeURIComponent(c)),s=i+a+1,c=""),a&&(i+=a,a=0)}return t.join("")+e.slice(s)}function Tt(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 ee=t.events.length;let fe=ee,ye,P;for(;fe--;)if(t.events[fe][0]==="exit"&&t.events[fe][1].type==="chunkFlow"){if(ye){P=t.events[fe][1].end;break}ye=!0}for(E(s),M=ee;Mz;){const F=i[J];t.containerState=F[1],F[0].exit.call(t,e)}i.length=z}function N(){a.write([null]),o=void 0,a=void 0,t.containerState._closeFlow=void 0}}function KN(e,t,i){return Tt(e,e.attempt(this.parser.constructs.document,t,i),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function pl(e){if(e===null||Qt(e)||_a(e))return 1;if(Uu(e))return 2}function $u(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=nr(f,[["enter",e[s][1],t],["exit",e[s][1],t]])),f=nr(f,[["enter",a,t],["enter",c,t],["exit",c,t],["enter",o,t]]),f=nr(f,$u(t.parser.constructs.insideSpan.null,e.slice(s+1,i),t)),f=nr(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=nr(f,[["enter",e[i][1],t],["exit",e[i][1],t]])):_=0,Un(e,s-1,i-s+3,f),i=s+f.length-_-2;break}}for(i=-1;++i0&&_t(M)?Tt(e,N,"linePrefix",o+1)(M):N(M)}function N(M){return M===null||$e(M)?e.check(bv,j,J)(M):(e.enter("codeFlowValue"),z(M))}function z(M){return M===null||$e(M)?(e.exit("codeFlowValue"),N(M)):(e.consume(M),z)}function J(M){return e.exit("codeFenced"),t(M)}function F(M,ee,fe){let ye=0;return P;function P(I){return M.enter("lineEnding"),M.consume(I),M.exit("lineEnding"),ae}function ae(I){return M.enter("codeFencedFence"),_t(I)?Tt(M,W,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(I):W(I)}function W(I){return I===h?(M.enter("codeFencedFenceSequence"),Y(I)):fe(I)}function Y(I){return I===h?(ye++,M.consume(I),Y):ye>=c?(M.exit("codeFencedFenceSequence"),_t(I)?Tt(M,V,"whitespace")(I):V(I)):fe(I)}function V(I){return I===null||$e(I)?(M.exit("codeFencedFence"),ee(I)):fe(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 xf={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"),Tt(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):$e(f)?e.attempt(l5,c,p)(f):(e.enter("codeFlowValue"),h(f))}function h(f){return f===null||$e(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):$e(c)?(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),a):Tt(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 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&&xo(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),xo(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),xo(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||Mu(E)?i(E):(e.enter(s),e.enter(c),e.enter(h),e.enter("chunkString",{contentType:"string"}),j(E))}function b(E){return E===62?(e.enter(o),e.consume(E),e.exit(o),e.exit(a),e.exit(s),t):(e.enter(h),e.enter("chunkString",{contentType:"string"}),v(E))}function v(E){return E===62?(e.exit("chunkString"),e.exit(h),b(E)):E===null||E===60||$e(E)?i(E):(e.consume(E),E===92?S:v)}function S(E){return E===60||E===62||E===92?(e.consume(E),v):v(E)}function j(E){return!_&&(E===null||E===41||Qt(E))?(e.exit("chunkString"),e.exit(h),e.exit(c),e.exit(s),t(E)):_999||v===null||v===91||v===93&&!p||v===94&&!h&&"_hiddenFootnoteSupport"in c.parser.constructs?i(v):v===93?(e.exit(o),e.enter(a),e.consume(v),e.exit(a),e.exit(s),t):$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=!_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):$e(b)?(e.enter("lineEnding"),e.consume(b),e.exit("lineEnding"),Tt(e,f,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),_(b))}function _(b){return b===c||b===null||$e(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 No(e,t){let i;return s;function s(a){return $e(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),i=!0,s):_t(a)?Tt(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=fr(s.sliceSerialize(s.events[s.events.length-1][1]).slice(1,-1)),v===58?(e.enter("definitionMarker"),e.consume(v),e.exit("definitionMarker"),p):i(v)}function p(v){return Qt(v)?No(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)?Tt(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 C5(e,t,i){return s;function s(h){return Qt(h)?No(e,a)(h):i(h)}function a(h){return U0(e,o,i,"definitionTitle","definitionTitleMarker","definitionTitleString")(h)}function o(h){return _t(h)?Tt(e,c,"whitespace")(h):c(h)}function c(h){return h===null||$e(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 $e(o)?(e.exit("hardBreakEscape"),t(o)):i(o)}}const N5={name:"headingAtx",resolve:j5,tokenize:T5};function j5(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"},Un(e,s,i-s+1,[["enter",a,t],["enter",o,t],["exit",o,t],["exit",a,t]])),e}function T5(e,t,i){let s=0;return a;function a(_){return e.enter("atxHeading"),o(_)}function o(_){return e.enter("atxHeadingSequence"),c(_)}function c(_){return _===35&&s++<6?(e.consume(_),c):_===null||Qt(_)?(e.exit("atxHeadingSequence"),h(_)):i(_)}function h(_){return _===35?(e.enter("atxHeadingSequence"),p(_)):_===null||$e(_)?(e.exit("atxHeading"),t(_)):_t(_)?Tt(e,h,"whitespace")(_):(e.enter("atxHeadingText"),f(_))}function p(_){return _===35?(e.consume(_),p):(e.exit("atxHeadingSequence"),h(_))}function f(_){return _===null||_===35||Qt(_)?(e.exit("atxHeadingText"),h(_)):(e.consume(_),f)}}const 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(k){return _(k)}function _(k){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(k),x}function x(k){return k===33?(e.consume(k),b):k===47?(e.consume(k),o=!0,j):k===63?(e.consume(k),a=3,s.interrupt?t:T):mn(k)?(e.consume(k),c=String.fromCharCode(k),R):i(k)}function b(k){return k===45?(e.consume(k),a=2,v):k===91?(e.consume(k),a=5,h=0,S):mn(k)?(e.consume(k),a=4,s.interrupt?t:T):i(k)}function v(k){return k===45?(e.consume(k),s.interrupt?t:T):i(k)}function S(k){const ue="CDATA[";return k===ue.charCodeAt(h++)?(e.consume(k),h===ue.length?s.interrupt?t:W:S):i(k)}function j(k){return mn(k)?(e.consume(k),c=String.fromCharCode(k),R):i(k)}function R(k){if(k===null||k===47||k===62||Qt(k)){const ue=k===47,te=c.toLowerCase();return!ue&&!o&&yv.includes(te)?(a=1,s.interrupt?t(k):W(k)):A5.includes(c.toLowerCase())?(a=6,ue?(e.consume(k),E):s.interrupt?t(k):W(k)):(a=7,s.interrupt&&!s.parser.lazy[s.now().line]?i(k):o?N(k):z(k))}return k===45||un(k)?(e.consume(k),c+=String.fromCharCode(k),R):i(k)}function E(k){return k===62?(e.consume(k),s.interrupt?t:W):i(k)}function N(k){return _t(k)?(e.consume(k),N):P(k)}function z(k){return k===47?(e.consume(k),P):k===58||k===95||mn(k)?(e.consume(k),J):_t(k)?(e.consume(k),z):P(k)}function J(k){return k===45||k===46||k===58||k===95||un(k)?(e.consume(k),J):F(k)}function F(k){return k===61?(e.consume(k),M):_t(k)?(e.consume(k),F):z(k)}function M(k){return k===null||k===60||k===61||k===62||k===96?i(k):k===34||k===39?(e.consume(k),p=k,ee):_t(k)?(e.consume(k),M):fe(k)}function ee(k){return k===p?(e.consume(k),p=null,ye):k===null||$e(k)?i(k):(e.consume(k),ee)}function fe(k){return k===null||k===34||k===39||k===47||k===60||k===61||k===62||k===96||Qt(k)?F(k):(e.consume(k),fe)}function ye(k){return k===47||k===62||_t(k)?z(k):i(k)}function P(k){return k===62?(e.consume(k),ae):i(k)}function ae(k){return k===null||$e(k)?W(k):_t(k)?(e.consume(k),ae):i(k)}function W(k){return k===45&&a===2?(e.consume(k),A):k===60&&a===1?(e.consume(k),L):k===62&&a===4?(e.consume(k),D):k===63&&a===3?(e.consume(k),T):k===93&&a===5?(e.consume(k),ge):$e(k)&&(a===6||a===7)?(e.exit("htmlFlowData"),e.check(M5,K,Y)(k)):k===null||$e(k)?(e.exit("htmlFlowData"),Y(k)):(e.consume(k),W)}function Y(k){return e.check(D5,V,K)(k)}function V(k){return e.enter("lineEnding"),e.consume(k),e.exit("lineEnding"),I}function I(k){return k===null||$e(k)?Y(k):(e.enter("htmlFlowData"),W(k))}function A(k){return k===45?(e.consume(k),T):W(k)}function L(k){return k===47?(e.consume(k),c="",U):W(k)}function U(k){if(k===62){const ue=c.toLowerCase();return yv.includes(ue)?(e.consume(k),D):W(k)}return mn(k)&&c.length<8?(e.consume(k),c+=String.fromCharCode(k),U):W(k)}function ge(k){return k===93?(e.consume(k),T):W(k)}function T(k){return k===62?(e.consume(k),D):k===45&&a===2?(e.consume(k),T):W(k)}function D(k){return k===null||$e(k)?(e.exit("htmlFlowData"),K(k)):(e.consume(k),D)}function K(k){return e.exit("htmlFlow"),t(k)}}function O5(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 z5(e,t,i){return s;function s(a){return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),e.attempt(Uo,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),F):T===63?(e.consume(T),z):mn(T)?(e.consume(T),fe):i(T)}function f(T){return T===45?(e.consume(T),_):T===91?(e.consume(T),o=0,S):mn(T)?(e.consume(T),N):i(T)}function _(T){return T===45?(e.consume(T),v):i(T)}function x(T){return T===null?i(T):T===45?(e.consume(T),b):$e(T)?(c=x,L(T)):(e.consume(T),x)}function b(T){return T===45?(e.consume(T),v):x(T)}function v(T){return T===62?A(T):T===45?b(T):x(T)}function S(T){const D="CDATA[";return T===D.charCodeAt(o++)?(e.consume(T),o===D.length?j:S):i(T)}function j(T){return T===null?i(T):T===93?(e.consume(T),R):$e(T)?(c=j,L(T)):(e.consume(T),j)}function R(T){return T===93?(e.consume(T),E):j(T)}function E(T){return T===62?A(T):T===93?(e.consume(T),E):j(T)}function N(T){return T===null||T===62?A(T):$e(T)?(c=N,L(T)):(e.consume(T),N)}function z(T){return T===null?i(T):T===63?(e.consume(T),J):$e(T)?(c=z,L(T)):(e.consume(T),z)}function J(T){return T===62?A(T):z(T)}function F(T){return mn(T)?(e.consume(T),M):i(T)}function M(T){return T===45||un(T)?(e.consume(T),M):ee(T)}function ee(T){return $e(T)?(c=ee,L(T)):_t(T)?(e.consume(T),ee):A(T)}function fe(T){return T===45||un(T)?(e.consume(T),fe):T===47||T===62||Qt(T)?ye(T):i(T)}function ye(T){return T===47?(e.consume(T),A):T===58||T===95||mn(T)?(e.consume(T),P):$e(T)?(c=ye,L(T)):_t(T)?(e.consume(T),ye):A(T)}function P(T){return T===45||T===46||T===58||T===95||un(T)?(e.consume(T),P):ae(T)}function ae(T){return T===61?(e.consume(T),W):$e(T)?(c=ae,L(T)):_t(T)?(e.consume(T),ae):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,Y):$e(T)?(c=W,L(T)):_t(T)?(e.consume(T),W):(e.consume(T),V)}function Y(T){return T===a?(e.consume(T),a=void 0,I):T===null?i(T):$e(T)?(c=Y,L(T)):(e.consume(T),Y)}function V(T){return T===null||T===34||T===39||T===60||T===61||T===96?i(T):T===47||T===62||Qt(T)?ye(T):(e.consume(T),V)}function I(T){return T===47||T===62||Qt(T)?ye(T):i(T)}function A(T){return T===62?(e.consume(T),e.exit("htmlTextData"),e.exit("htmlText"),t):i(T)}function L(T){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(T),e.exit("lineEnding"),U}function U(T){return _t(T)?Tt(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 sm={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||$e(f))?(e.exit("thematicBreak"),t(f)):i(f)}function p(f){return f===a?(e.consume(f),s++,p):(e.exit("thematicBreakSequence"),_t(f)?Tt(e,h,"whitespace")(f):h(f))}}const En={continuation:{tokenize:rj},exit:aj,name:"list",tokenize:nj},tj={partial:!0,tokenize:lj},ij={partial:!0,tokenize:sj};function nj(e,t,i){const s=this,a=s.events[s.events.length-1];let o=a&&a[1].type==="linePrefix"?a[2].sliceSerialize(a[1],!0).length:0,c=0;return h;function h(v){const S=s.containerState.type||(v===42||v===43||v===45?"listUnordered":"listOrdered");if(S==="listUnordered"?!s.containerState.marker||v===s.containerState.marker:Ep(v)){if(s.containerState.type||(s.containerState.type=S,e.enter(S,{_container:!0})),S==="listUnordered")return e.enter("listItemPrefix"),v===42||v===45?e.check(yu,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 Ep(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(Uo,s.interrupt?i:_,e.attempt(tj,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 rj(e,t,i){const s=this;return s.containerState._closeFlow=void 0,e.check(Uo,a,o);function a(h){return s.containerState.furtherBlankLines=s.containerState.furtherBlankLines||s.containerState.initialBlankLine,Tt(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(ij,t,c)(h))}function c(h){return s.containerState._closeFlow=!0,s.interrupt=void 0,Tt(e,e.attempt(En,t,i),"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(h)}}function sj(e,t,i){const s=this;return Tt(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 aj(e){e.exit(this.containerState.type)}function lj(e,t,i){const s=this;return Tt(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:oj,tokenize:cj};function oj(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 cj(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)?Tt(e,p,"lineSuffix")(f):p(f))}function p(f){return f===null||$e(f)?(e.exit("setextHeadingLine"),t(f)):i(f)}}const uj={tokenize:hj};function hj(e){const t=this,i=e.attempt(Uo,s,e.attempt(this.parser.constructs.flowInitial,a,Tt(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 dj={resolveAll:F0()},fj=$0("string"),pj=$0("text");function $0(e){return{resolveAll:F0(e==="text"?mj: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 jj(e,t){let i=-1;const s=[];let a;for(;++i0){const Ot=Te.tokenStack[Te.tokenStack.length-1];(Ot[1]||Cv).call(Te,void 0,Ot[0])}for(me.position={start:Os(se.length>0?se[0][1].start:{line:1,column:1,offset:0}),end:Os(se.length>0?se[se.length-2][1].end:{line:1,column:1,offset:0})},it=-1;++it0&&(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 $j(e,t){const i={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function Fj(e,t){const i={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function qj(e,t){const i=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=String(t.identifier).toUpperCase(),a=bl(s.toLowerCase()),o=e.footnoteOrder.indexOf(s);let c,h=e.footnoteCounts.get(s);h===void 0?(h=0,e.footnoteOrder.push(s),c=e.footnoteOrder.length):c=o+1,h+=1,e.footnoteCounts.set(s,h);const p={type:"element",tagName:"a",properties:{href:"#"+i+"fn-"+a,id:i+"fnref-"+a+(h>1?"-"+h:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(c)}]};e.patch(t,p);const f={type:"element",tagName:"sup",properties:{},children:[p]};return e.patch(t,f),e.applyData(t,f)}function Wj(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 Gj(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 Yj(e,t){const i=String(t.identifier).toUpperCase(),s=e.definitionById.get(i);if(!s)return G0(e,t);const a={src:bl(s.url||""),alt:t.alt};s.title!==null&&s.title!==void 0&&(a.title=s.title);const o={type:"element",tagName:"img",properties:a,children:[]};return e.patch(t,o),e.applyData(t,o)}function Kj(e,t){const i={src:bl(t.url)};t.alt!==null&&t.alt!==void 0&&(i.alt=t.alt),t.title!==null&&t.title!==void 0&&(i.title=t.title);const s={type:"element",tagName:"img",properties:i,children:[]};return e.patch(t,s),e.applyData(t,s)}function Vj(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 Xj(e,t){const i=String(t.identifier).toUpperCase(),s=e.definitionById.get(i);if(!s)return G0(e,t);const a={href:bl(s.url||"")};s.title!==null&&s.title!==void 0&&(a.title=s.title);const o={type:"element",tagName:"a",properties:a,children:e.all(t)};return e.patch(t,o),e.applyData(t,o)}function Zj(e,t){const i={href:bl(t.url)};t.title!==null&&t.title!==void 0&&(i.title=t.title);const s={type:"element",tagName:"a",properties:i,children:e.all(t)};return e.patch(t,s),e.applyData(t,s)}function Qj(e,t,i){const s=e.all(t),a=i?Jj(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 eT(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=Jp(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 sT(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 oT(e,t){const i={type:"text",value:lT(String(t.value))};return e.patch(t,i),e.applyData(t,i)}function cT(e,t){const i={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,i),e.applyData(t,i)}const uT={blockquote:Ij,break:Hj,code:Uj,delete:$j,emphasis:Fj,footnoteReference:qj,heading:Wj,html:Gj,imageReference:Yj,image:Kj,inlineCode:Vj,linkReference:Xj,link:Zj,listItem:Qj,list:eT,paragraph:tT,root:iT,strong:nT,table:rT,tableCell:aT,tableRow:sT,text:oT,thematicBreak:cT,toml:ru,yaml:ru,definition:ru,footnoteDefinition:ru};function ru(){}const K0=-1,Fu=0,jo=1,Du=2,am=3,lm=4,om=5,cm=6,V0=7,X0=8,jv=typeof self=="object"?self:globalThis,hT=(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 Fu:case K0:return i(c,a);case jo:{const h=i([],a);for(const p of c)h.push(s(p));return h}case Du:{const h=i({},a);for(const[p,f]of c)h[s(p)]=s(f);return h}case am:return i(new Date(c),a);case lm:{const{source:h,flags:p}=c;return i(new RegExp(h,p),a)}case om:{const h=i(new Map,a);for(const[p,f]of c)h.set(s(p),s(f));return h}case cm:{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 jv[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 jv[o](c),a)};return s},Tv=e=>hT(new Map,e)(0),ll="",{toString:dT}={},{keys:fT}=Object,_o=e=>{const t=typeof e;if(t!=="object"||!e)return[Fu,t];const i=dT.call(e).slice(8,-1);switch(i){case"Array":return[jo,ll];case"Object":return[Du,ll];case"Date":return[am,ll];case"RegExp":return[lm,ll];case"Map":return[om,ll];case"Set":return[cm,ll];case"DataView":return[jo,i]}return i.includes("Array")?[jo,i]:i.includes("Error")?[V0,i]:[Du,i]},su=([e,t])=>e===Fu&&(t==="function"||t==="symbol"),pT=(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]=_o(c);switch(h){case Fu:{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 jo:{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 Du:{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 fT(c))(e||!su(_o(c[b])))&&_.push([o(b),o(c[b])]);return x}case am:return a([h,c.toISOString()],c);case lm:{const{source:_,flags:x}=c;return a([h,{source:_,flags:x}],c)}case om:{const _=[],x=a([h,_],c);for(const[b,v]of c)(e||!(su(_o(b))||su(_o(v))))&&_.push([o(b),o(v)]);return x}case cm:{const _=[],x=a([h,_],c);for(const b of c)(e||!su(_o(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 pT(!(t||i),!!t,new Map,s)(e),s},Do=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?Tv(Av(e,t)):structuredClone(e):(e,t)=>Tv(Av(e,t));function mT(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 gT(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function xT(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",i=e.options.footnoteBackContent||mT,s=e.options.footnoteBackLabel||gT,a=e.options.footnoteLabel||"Footnotes",o=e.options.footnoteLabelTagName||"h2",c=e.options.footnoteLabelProperties||{className:["sr-only"]},h=[];let p=-1;for(;++p0&&S.push({type:"text",value:" "});let N=typeof i=="string"?i:i(p,v);typeof N=="string"&&(N={type:"text",value:N}),S.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+b+(v>1?"-"+v:""),dataFootnoteBackref:"",ariaLabel:typeof s=="string"?s:s(p,v),className:["data-footnote-backref"]},children:Array.isArray(N)?N:[N]})}const R=_[_.length-1];if(R&&R.type==="element"&&R.tagName==="p"){const N=R.children[R.children.length-1];N&&N.type==="text"?N.value+=" ":R.children.push({type:"text",value:" "}),R.children.push(...S)}else _.push(...S);const E={type:"element",tagName:"li",properties:{id:t+"fn-"+b},children:e.wrap(_,!0)};e.patch(f,E),h.push(E)}if(h.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...Do(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 qu=(function(e){if(e==null)return yT;if(typeof e=="function")return Wu(e);if(typeof e=="object")return Array.isArray(e)?_T(e):bT(e);if(typeof e=="string")return vT(e);throw new Error("Expected function, string, or object as test")});function _T(e){const t=[];let i=-1;for(;++i":""))+")"})}return b;function b(){let v=Z0,S,j,R;if((!t||o(p,f,_[_.length-1]||void 0))&&(v=kT(i(p,_)),v[0]===jp))return v;if("children"in p&&p.children){const E=p;if(E.children&&v[0]!==CT)for(j=(s?E.children.length:-1)+c,R=_.concat(E);j>-1&&j0&&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=NT(e,t),s=i.one(e,void 0),a=xT(i),o=Array.isArray(s)?{type:"root",children:s}:s||{type:"root",children:[]};return a&&o.children.push({type:"text",value:` -`},a),o}function MT(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 bf,Bv;function DT(){if(Bv)return bf;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 bf=function p(){var f,_,x,b,v,S,j=arguments[0],R=1,E=arguments.length,N=!1;for(typeof j=="boolean"&&(N=j,j=arguments[1]||{},R=2),(j==null||typeof j!="object"&&typeof j!="function")&&(j={});Rc.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 kr={basename:zT,dirname:PT,extname:IT,join:HT,sep:"/"};function zT(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');$o(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 PT(e){if($o(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 IT(e){$o(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 HT(...e){let t=-1,i;for(;++t0&&e.codePointAt(e.length-1)===47&&(i+="/"),t?"/"+i:i}function $T(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 $o(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const FT={cwd:qT};function qT(){return"/"}function Rp(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function WT(e){if(typeof e=="string")e=new URL(e);else if(!Rp(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 GT(e)}function GT(e){if(e.hostname!==""){const s=new TypeError('File URL host must be "localhost" or empty on darwin');throw s.code="ERR_INVALID_FILE_URL_HOST",s}const t=e.pathname;let i=-1;for(;++i0){let[v,...S]=_;const j=s[b][1];Ap(j)&&Ap(v)&&(v=vf(!0,j,v)),s[b]=[f,v,...S]}}}}const XT=new hm().freeze();function Cf(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function kf(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Ef(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(!Ap(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 au(e){return ZT(e)?e:new J0(e)}function ZT(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function QT(e){return typeof e=="string"||JT(e)}function JT(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 XT().use(Pj).use(i).use(MT,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 um(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 gf)if(Object.hasOwn(gf,v)&&Object.hasOwn(_.properties,v)){const S=_.properties[v],j=gf[v];(j===null||j.includes(_.tagName))&&(_.properties[v]=p(String(S||""),v,_))}}if(_.type==="element"){let v=i?!i.includes(_.tagName):o?o.includes(_.tagName):!1;if(!v&&s&&typeof x=="number"&&(v=!s(_,x,b)),v&&b&&typeof x=="number")return h&&_.children?b.children.splice(x,1,..._.children):b.children.splice(x,1),x}}}function 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=qu((i||{}).ignore||[]),o=oA(t);let c=-1;for(;++c0?{type:"text",value:M}:void 0),M===!1?b.lastIndex=J+1:(S!==J&&N.push({type:"text",value:f.value.slice(S,J)}),Array.isArray(M)?N.push(...M):M&&N.push(M),S=J+z[0].length,E=!0),!b.global)break;z=b.exec(f.value)}return E?(S?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let i=t[0],s=i.indexOf(")");const a=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||_a(i)||Uu(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 jA(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function TA(e){const t=this.resume(),i=this.stack[this.stack.length-1];i.type,i.identifier=fr(this.sliceSerialize(e)).toLowerCase(),i.label=t}function AA(e){this.exit(e)}function RA(e){const t=this.resume(),i=this.stack[this.stack.length-1];i.type,i.identifier=fr(this.sliceSerialize(e)).toLowerCase(),i.label=t}function 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:jA},exit:{gfmFootnoteCallString:TA,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]=z)}j.push(N)}c[_]=j,h[_]=R}let x=-1;if(typeof s=="object"&&"length"in s)for(;++xp[x]&&(p[x]=N),v[x]=N),b[x]=z}c.splice(1,0,b),h.splice(1,0,v),_=-1;const S=[];for(;++_ "),o.shift(2);const c=i.indentLines(i.containerFlow(e,o.current()),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 dm(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=dm(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 Bo(e){return"&#x"+e.toString(16).toUpperCase()+";"}function Bu(e,t,i){const s=pl(e),a=pl(t);return s===void 0?a===void 0?i==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:a===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:s===1?a===void 0?{inside:!1,outside:!1}:a===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:a===void 0?{inside:!1,outside:!1}:a===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}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),_=Bu(s.before.charCodeAt(s.before.length-1),f,a);_.inside&&(p=Bo(f)+p.slice(1));const x=p.charCodeAt(p.length-1),b=Bu(s.after.charCodeAt(0),x,a);b.inside&&(p=p.slice(0,-1)+Bo(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 um(e,function(s){if("value"in s&&/\r?\n|\r/.test(s.value)||s.type==="break")return i=!0,jp}),!!((!e.depth||e.depth<3)&&nm(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=Bo(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=dm(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=dm(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 fm(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=fm(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):fm(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=qu(["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),_=Bu(s.before.charCodeAt(s.before.length-1),f,a);_.inside&&(p=Bo(f)+p.slice(1));const x=p.charCodeAt(p.length-1),b=Bu(s.after.charCodeAt(0),x,a);b.inside&&(p=p.slice(0,-1)+Bo(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:jR,table:ER,tableData:Af,tableHeader:Af,tableRow:Af}}}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 Af(e){this.exit(e)}function qv(e){this.enter({type:"tableCell",children:[]},e)}function jR(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,TR));const i=this.stack[this.stack.length-1];i.type,i.value=t,this.exit(e)}function TR(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,S,j,R){return f(_(v,j,R),v.align)}function h(v,S,j,R){const E=x(v,j,R),N=f([E]);return N.slice(0,N.indexOf(` -`))}function p(v,S,j,R){const E=j.enter("tableCell"),N=j.enter("phrasing"),z=j.containerPhrasing(v,{...R,before:o,after:o});return N(),E(),z}function f(v,S){return qA(v,{align:S,alignDelimiters:s,padding:i,stringLength:a})}function _(v,S,j){const R=v.children;let E=-1;const N=[],z=S.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=fr(s.sliceSerialize({start:c.end,end:s.now()}));return f.codePointAt(0)!==94||!o.includes(f.slice(1))?i(p):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(p),e.exit("gfmFootnoteCallLabelMarker"),t(p))}}function 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||Qt(x))return i(x);if(x===93){e.exit("chunkString");const b=e.exit("gfmFootnoteCallString");return a.includes(fr(s.sliceSerialize(b)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(x),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):i(x)}return Qt(x)||(c=!0),o++,e.consume(x),x===92?_:f}function _(x){return x===91||x===92||x===93?(e.consume(x),o++,f):f(x)}}function JR(e,t,i){const s=this,a=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let o,c=0,h;return p;function p(S){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionLabelMarker"),f}function f(S){return S===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",_):i(S)}function _(S){if(c>999||S===93&&!h||S===null||S===91||Qt(S))return i(S);if(S===93){e.exit("chunkString");const j=e.exit("gfmFootnoteDefinitionLabelString");return o=fr(s.sliceSerialize(j)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),b}return Qt(S)||(h=!0),c++,e.consume(S),S===92?x:_}function x(S){return S===91||S===92||S===93?(e.consume(S),c++,_):_(S)}function b(S){return S===58?(e.enter("definitionMarker"),e.consume(S),e.exit("definitionMarker"),a.includes(o)||a.push(o),Tt(e,v,"gfmFootnoteDefinitionWhitespace")):i(S)}function v(S){return t(S)}}function e3(e,t,i){return e.check(Uo,t,e.attempt(KR,t,i))}function t3(e){e.exit("gfmFootnoteDefinition")}function i3(e,t,i){const s=this;return Tt(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(S):(c.consume(S),x++,v);if(x<2&&!i)return p(S);const R=c.exit("strikethroughSequenceTemporary"),E=pl(S);return R._open=!E||E===2&&!!j,R._close=!j||j===2&&!!E,h(S)}}}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 V=s.events[ae][1].type;if(V==="lineEnding"||V==="linePrefix")ae--;else break}const W=ae>-1?s.events[ae][1].type:null,Y=W==="tableHead"||W==="tableRow"?M:p;return Y===M&&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):$e(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)?Tt(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||Qt(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)?Tt(e,S,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(P):S(P))}function S(P){return P===45||P===58?R(P):P===124?(c=!0,e.enter("tableCellDivider"),e.consume(P),e.exit("tableCellDivider"),j):F(P)}function j(P){return _t(P)?Tt(e,R,"whitespace")(P):R(P)}function R(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||$e(P)?J(P):F(P)}function E(P){return P===45?(e.enter("tableDelimiterFiller"),N(P)):F(P)}function N(P){return P===45?(e.consume(P),N):P===58?(c=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(P),e.exit("tableDelimiterMarker"),z):(e.exit("tableDelimiterFiller"),z(P))}function z(P){return _t(P)?Tt(e,J,"whitespace")(P):J(P)}function J(P){return P===124?S(P):P===null||$e(P)?!c||a!==o?F(P):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(P)):F(P)}function F(P){return i(P)}function M(P){return e.enter("tableRow"),ee(P)}function ee(P){return P===124?(e.enter("tableCellDivider"),e.consume(P),e.exit("tableCellDivider"),ee):P===null||$e(P)?(e.exit("tableRow"),t(P)):_t(P)?Tt(e,ee,"whitespace")(P):(e.enter("data"),fe(P))}function fe(P){return P===null||P===124||Qt(P)?(e.exit("data"),ee(P)):(e.consume(P),P===92?ye:fe)}function ye(P){return P===92||P===124?(e.consume(P),fe):fe(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 S=i[2]+1,j=i[3]-i[2]-1;e.add(S,j,[])}}e.add(i[3]+1,0,[["exit",x,t]])}return a!==void 0&&(o.end=Object.assign({},ol(t.events,a)),e.add(a,0,[["exit",o,t]]),o=void 0),o}function Gv(e,t,i,s,a){const o=[],c=ol(t.events,i);a&&(a.end=Object.assign({},c),o.push(["exit",a,t])),s.end=Object.assign({},c),o.push(["exit",s,t]),e.add(i+1,0,o)}function ol(e,t){const i=e[t],s=i[0]==="enter"?"start":"end";return i[1][s]}const 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 Qt(p)?(e.enter("taskListCheckValueUnchecked"),e.consume(p),e.exit("taskListCheckValueUnchecked"),c):p===88||p===120?(e.enter("taskListCheckValueChecked"),e.consume(p),e.exit("taskListCheckValueChecked"),c):i(p)}function c(p){return p===93?(e.enter("taskListCheckMarker"),e.consume(p),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),h):i(p)}function h(p){return $e(p)?t(p):_t(p)?e.check({tokenize:f3},t,i)(p):i(p)}}function f3(e,t,i){return Tt(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 ha=["ariaDescribedBy","ariaLabel","ariaLabelledBy"],ml={ancestors:{tbody:["table"],td:["table"],th:["table"],thead:["table"],tfoot:["table"],tr:["table"]},attributes:{a:[...ha,"dataFootnoteBackref","dataFootnoteRef",["className","data-footnote-backref"],"href"],blockquote:["cite"],code:[["className",/^language-./]],del:["cite"],div:["itemScope","itemType"],dl:[...ha],h2:[["className","sr-only"]],img:[...ha,"longDesc","src"],input:[["disabled",!0],["type","checkbox"]],ins:["cite"],li:[["className","task-list-item"]],ol:[...ha,["className","contains-task-list"]],q:["cite"],section:["dataFootnotes",["className","footnotes"]],source:["srcSet"],summary:[...ha],table:[...ha],ul:[...ha,["className","contains-task-list"]],"*":["abbr","accept","acceptCharset","accessKey","action","align","alt","axis","border","cellPadding","cellSpacing","char","charOff","charSet","checked","clear","colSpan","color","cols","compact","coords","dateTime","dir","encType","frame","hSpace","headers","height","hrefLang","htmlFor","id","isMap","itemProp","label","lang","maxLength","media","method","multiple","name","noHref","noShade","noWrap","open","prompt","readOnly","rev","rowSpan","rows","rules","scope","selected","shape","size","span","start","summary","tabIndex","title","useMap","vAlign","value","width"]},clobber:["ariaDescribedBy","ariaLabelledBy","id","name"],clobberPrefix:"user-content-",protocols:{cite:["http","https"],href:["http","https","irc","ircs","mailto","xmpp"],longDesc:["http","https"],src:["http","https"]},required:{input:{disabled:!0,type:"checkbox"}},strip:["script"],tagNames:["a","b","blockquote","br","code","dd","del","details","div","dl","dt","em","h1","h2","h3","h4","h5","h6","hr","i","img","input","ins","kbd","li","ol","p","picture","pre","q","rp","rt","ruby","s","samp","section","source","span","strike","strong","sub","summary","sup","table","tbody","td","tfoot","th","thead","tr","tt","ul","var"]},Ps={}.hasOwnProperty;function g3(e,t){let i={type:"root",children:[]};const s={schema:t?{...ml,...t}:ml,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 Fo(o,t),o}}function _3(e,t){if(e.schema.allowDoctypes){const i={type:"doctype"};return Fo(i,t),i}}function b3(e,t){const i=typeof t.tagName=="string"?t.tagName:"";e.stack.push(i);const s=jS(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&&Ps.call(e.schema.ancestors,i))){const h=e.schema.ancestors[i];let p=-1;for(o=!1;++p1){let a=!1,o=0;for(;++o-1&&o>p||c>-1&&o>c||h>-1&&o>h)return!0;let f=-1;for(;++f4&&t.slice(0,4).toLowerCase()==="data")return i}function AS(e){return function(t){return g3(t,e)}}const hl=["Romance","Fantasy","Science Fiction","Mystery","Thriller","Horror","Adventure","Historical Fiction","Contemporary Lit","Humor","Poetry","Non-Fiction","Fanfiction","Short Story","Paranormal","Werewolf","LGBTQ+","New Adult","Teen Fiction","Diverse Lit","Others"],Jr=["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(hl.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 Su(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 Dp({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 ou(e,t,i,s,a){const o=a.lineHeightFactor??1.2,c=a.speakerScale??.8,h=a.paddingX??Math.max(2,i*.06),p=a.paddingY??Math.max(2,s*.08),f=Math.max(1,i-2*h),_=Math.max(1,s-2*p),x=Math.max(a.minFontSize,a.maxFontSize),b=Math.max(1,Math.min(a.minFontSize,x)),v=j=>{const R=a.hasSpeaker?j*c:0,E=a.hasSpeaker?R*o:0,N=Math.max(1,_-E),z=a.fontWeight??400,J=Vv((ee,fe)=>e(ee,fe,z),t,f,j),F=J.length*j*o,M=J.every(ee=>e(ee,j,z)<=f+.5);return{lines:J,ok:F<=N&&M}};if(typeof a.fontSize=="number"&&Number.isFinite(a.fontSize)&&a.fontSize>0){const j=Math.max(1,a.fontSize),{lines:R,ok:E}=v(j);return{lines:R,fontSize:j,lineHeight:j*o,speakerFontSize:a.hasSpeaker?j*c:0,overflow:!E}}for(let j=x;j>=b;j-=.5){const{lines:R,ok:E}=v(j);if(E)return{lines:R,fontSize:j,lineHeight:j*o,speakerFontSize:a.hasSpeaker?j*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"],j3=2;function Nr(e,t,i){return Math.min(i,Math.max(t,e))}function dl(e,t,i){return typeof e=="number"&&Number.isFinite(e)?Nr(e,t,i):void 0}function mm(e){if(!e||typeof e!="object")return;const t=e,i=t.mode==="manual"?"manual":t.mode==="auto"?"auto":void 0,s=dl(t.fontScale,.015,.12),a=t.fontWeight===700?700:t.fontWeight===400?400:void 0,o=dl(t.lineHeightFactor,.9,2),c=dl(t.speakerScale,.5,1.5);if(!(!i&&s===void 0&&a===void 0&&o===void 0&&c===void 0))return{...i?{mode:i}:{},...s!==void 0?{fontScale:s}:{},...a!==void 0?{fontWeight:a}:{},...o!==void 0?{lineHeightFactor:o}:{},...c!==void 0?{speakerScale:c}:{}}}function Gu(e){if(!e||typeof e!="object")return;const t=e,i=dl(t.paddingX,0,.25),s=dl(t.paddingY,0,.25),a=dl(t.cornerRadius,0,.49);if(!(i===void 0&&s===void 0&&a===void 0))return{...i!==void 0?{paddingX:i}:{},...s!==void 0?{paddingY:s}:{},...a!==void 0?{cornerRadius:a}:{}}}function cu(e,t,i,s){const{minFontSize:a,maxFontSize:o}=N3(t),c=mm(e.textStyle),h=Gu(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 T3(e,t,i){const s=Gu(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?Nr(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:N,half:z}=Xv(p,e,i,v,b);return{tip:{x:p,y:f},base1:{x:N-z,y:E},base2:{x:N+z,y:E}}}const S=_>=0?e+i:e,{center:j,half:R}=Xv(f,t,s,v,b);return{tip:{x:p,y:f},base1:{x:S,y:j-R},base2:{x:S,y:j+R}}}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 uu=.05;function Gi(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?uu:Nr(o?1-t-uu:(1-t)/2,0,1),_=c?uu:Nr(h?1-i-uu:(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=Gi(t.width)&&t.width>0?t.width:i==="sfx"?.15:.4,o=Gi(t.height)&&t.height>0?t.height:i==="sfx"?.08:.16,c,h;if(Gi(t.x)&&Gi(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=Nr(c,0,1),h=Nr(h,0,1),a=Nr(a,.02,1),o=Nr(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&&Gi(b.x)&&Gi(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 _=mm(t.textStyle),x=Gu(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)&&Gi(t.x)&&Gi(t.y)&&Gi(t.width)&&Gi(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=mm(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=Gu(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 Gi(e==null?void 0:e.x)&&Gi(e==null?void 0:e.y)&&Gi(e==null?void 0:e.width)&&Gi(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 rr(e){return e.kind==="text"}function $3(e){return!!e.finalImagePath||!!e.exportedAt?{key:"review",label:"Review final panel",opensEditor:!0}:e.cleanImagePath||rr(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=j3){return!e.finalImagePath||!(e.overlays??[]).some(A3)?!1:(e.finalRendererVersion??0)0)||!(s>0)?null:{width:ty,height:Math.round(ty*s/i)}}function hu({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(Dp,{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(Dp,{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(hu,{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(hu,{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(hu,{cut:e})]})]}),e.description&&d.jsx("p",{className:"text-xs text-muted italic",children:e.description}),a&&d.jsx(hu,{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 S=await b.json();f(S.error||"Failed to load cuts"),h(!1);return}const v=await b.json();o(v)}catch{f("Failed to load cuts")}finally{h(!1)}},[i,e,_]);return w.useEffect(()=>{x();const b=setInterval(x,5e3);return()=>clearInterval(b)},[x]),c&&!a?d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Loading cuts..."}):p?d.jsxs("div",{className:"h-full flex flex-col items-center justify-center gap-2 px-4 text-center","data-testid":"cuts-error",children:[d.jsx("p",{className:"text-sm text-error font-medium",children:"Invalid cuts file"}),d.jsx("p",{className:"text-xs text-error",children:p}),d.jsxs("p",{className:"text-xs text-muted max-w-sm",children:[_,".cuts.json must follow the OWS v1 schema. Ask Claude to regenerate it using the v1 cuts schema shown in the cartoon writing instructions."]}),d.jsx("button",{onClick:x,className:"text-xs text-accent hover:text-accent-dim",children:"Retry"})]}):!a||a.cuts.length===0?d.jsxs("div",{className:"h-full flex flex-col items-center justify-center gap-2 px-4 text-center",children:[d.jsx("p",{className:"text-sm text-muted",children:"No cuts yet"}),d.jsx("p",{className:"text-xs text-muted",children:"Ask Claude to create a cut plan for this episode."})]}):d.jsx("div",{className:"h-full overflow-y-auto",children:d.jsx("div",{className:"max-w-lg mx-auto px-4 py-6 space-y-6",children:a.cuts.map(b=>d.jsx(q3,{cut:b,storyName:e,authFetch:i,onEditCut:s},b.id))})})}const 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 gm(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 Rf=[{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=Rf.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=[...Rf.map(c=>c.key),"other"],a=c=>{var h;return((h=Rf.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,Mf=/^(genre|logline|synopsis|premise|setting|tone|theme|themes|summary|hook|characters?|cast|arc|status|word\s*count|length|title)\b\s*[:\-–]/i;function xm(e){const t=[],i=[],s=e??"",a=s.match(/^#[ \t]+(.+)$/m),o=!!(a&&a[1].trim());o||t.push("Add a “# Title” heading — the Story opening needs a real title readers see first.");const c=s.replace(/^#\s+.+$/m,"").trim();if(c.lengthx.trim()).filter(Boolean),p=h.filter(x=>/^([-*+]|\d+[.)])\s/.test(x)||Mf.test(x)).length,f=c.split(/\n\s*\n/).map(x=>x.trim()).filter(Boolean),_=f.some(x=>x.length>=120&&!/^([-*+]|\d+[.)])\s/.test(x)&&!Mf.test(x));h.length>0&&p/h.length>=.5||!_?t.push("This reads like a synopsis or outline. Write the Genesis as a reader-facing opening scene that sets up the first beat and stakes, then bridges into Episode 01 — not a logline, genre pitch, or character list."):f.filter(b=>b.length>=40&&!/^([-*+]|\d+[.)])\s/.test(b)&&!Mf.test(b)).length<2&&t.push("Give the opening room to build: open across a few short paragraphs — the premise, what the lead wants, and the hook — that lead into Episode 01, instead of a single dense block that drops readers into a cold scene.")}return{hasTitle:o,blockers:t,warnings:i}}function eM(e){return/\.(webp|jpe?g)$/i.test(e)}function Bp(e){var c,h;let t=0,i=0,s=0,a=0,o=0;for(const p of e)rr(p)?(((h=p.overlays)==null?void 0:h.length)??0)>0&&s++:(t++,p.cleanImagePath&&eM(p.cleanImagePath)&&(i++,(((c=p.overlays)==null?void 0:c.length)??0)>0&&s++)),p.finalImagePath&&p.exportedAt&&a++,p.uploadedUrl&&o++;return{total:e.length,needClean:t,withClean:i,withText:s,exported:a,uploaded:o}}const 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 bo(e,t){return`${e} / ${t} cut${t===1?"":"s"}`}function iM(e){const{cuts:t,published:i=!1}=e,s=Bp(t);if(s.total===0)return{steps:[],nextStep:null};const a=s.total>0,o=a&&s.withClean===s.needClean,c=o&&s.withText===s.total,h=c&&s.exported===s.total,p=h&&s.uploaded===s.total,_={plan:a,clean:o,letter:c,export:h,upload:p,publish:p&&i},x=["plan","clean","letter","export","upload","publish"],b=x.findIndex(N=>!_[N]),v=N=>s.needClean>0?bo(N,s.needClean):"no image cuts",S={plan:bo(s.total,s.total),clean:v(s.withClean),letter:bo(s.withText,s.total),export:bo(s.exported,s.total),upload:bo(s.uploaded,s.total),publish:null},j=x.map((N,z)=>({key:N,label:tM[N],status:b===-1||zPS,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,S)=>{b.addEventListener("load",v),b.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${f}`)))})}))}function o(c){const h=new Event("vite:preloadError",{cancelable:!0});if(h.payload=c,window.dispatchEvent(h),!h.defaultPrevented)throw c}return a.then(c=>{for(const h of c||[])h.status==="rejected"&&o(h.reason);return t().catch(o)})},_m=[{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=_m.find(e=>e.family==="Noto Sans"),fM=_m.find(e=>e.category==="display");function pM(e){return _m.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 wu(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!==wu(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 kn(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 Cu={speech:"Speech",narration:"Narration",sfx:"SFX"},kM={speech:"border-foreground/40",narration:"border-muted/40",sfx:"border-accent/40"};function Df(e){const t=(e.speaker||e.text||"").trim().replace(/\s+/g," ");return t?`“${t.length>18?`${t.slice(0,18)}…`:t}”`:Cu[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 du(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,workspaceVisible:_=!1,onToggleWorkspaceVisible:x}){var At,Ct,He,li,st,_n;const b=pM(c),v=mM(),S=sy(b),j=sy(v);w.useEffect(()=>{oy(b),oy(v)},[b,v]),w.useEffect(()=>{let q=!1;return Y(!1),(async()=>{try{const{ensureFontsReady:ke}=await ry(async()=>{const{ensureFontsReady:De}=await import("./export-cut-DmVsiKji.js");return{ensureFontsReady:De}},[]);await ke([b.family,v.family])}catch{}q||Y(!0)})(),()=>{q=!0}},[b.family,v.family]);const R=DS(e,t.cleanImagePath,h),E=w.useMemo(()=>I3(t.overlays),[t.overlays]),N=E.invalid.length,[z,J]=w.useState(!1),F=N===0&&E.changed&&E.overlays.length>0,[M,ee]=w.useState(()=>E.overlays),[fe,ye]=w.useState(()=>wu(E.overlays)),P=w.useRef(null),ae=w.useCallback(q=>(ke,De,Ee=400)=>{var Xe;!P.current&&typeof document<"u"&&(P.current=document.createElement("canvas"));const Ke=(Xe=P.current)==null?void 0:Xe.getContext("2d");return Ke?(Ke.font=`${Ee} ${De}px ${q}`,Ke.measureText(ke).width):ke.length*De*.5},[]),[W,Y]=w.useState(!1),[V,I]=w.useState(null),[A,L]=w.useState(!1),[U,ge]=w.useState(!1),[T,D]=w.useState(null),[K,k]=w.useState(null),[ue,te]=w.useState(!1),[G,H]=w.useState({x:0,y:0,width:0,height:0}),le=w.useRef(null),xe=w.useRef(null),Re=w.useRef(null),Me=w.useCallback(()=>{const q=le.current;if(!q)return;const ke=q.clientWidth,De=q.clientHeight;let Ee,Ke;if(t.kind==="text"){const mt=F3(t.aspectRatio)??{width:800,height:600};Ee=mt.width,Ke=mt.height}else{const mt=xe.current;if(!mt||!mt.naturalWidth)return;Ee=mt.naturalWidth,Ke=mt.naturalHeight}if(!ke||!De)return;const Xe=Math.min(ke/Ee,De/Ke),nt=Ee*Xe,qt=Ke*Xe;H({x:(ke-nt)/2,y:(De-qt)/2,width:nt,height:qt})},[t.kind,t.aspectRatio]);w.useEffect(()=>{const q=le.current;if(!q)return;const ke=new ResizeObserver(()=>Me());return ke.observe(q),()=>ke.disconnect()},[Me]);const Le=w.useCallback(q=>{const ke=B3(q.type,q.x,q.y),De=ke.width,Ee=Math.max(.08,1-q.y);if(!q.text||!W||G.width<=0)return ke;const Ke=q.type==="sfx"?j:S,Xe=kn(De,G.width);let nt=q.type==="sfx"?.08:.12;for(let qt=0;qt<24;qt++){const mt=Math.min(nt,Ee),ct=kn(mt,G.height);if(!ou(ae(Ke),q.text,Xe,ct,cu({...q},G.height||300,Xe,ct)).overflow||mt>=Ee)return{width:De,height:mt};nt+=.03}return{width:De,height:Math.min(nt,Ee)}},[W,G,ae,S,j]),Ae=w.useCallback(q=>{const ke=Qv(q,.1+Math.random()*.3,.1+Math.random()*.3),De={...ke,...Le(ke)};ee(Ee=>[...Ee,De]),I(De.id)},[Le]),ut=w.useCallback(q=>{const De={...Qv(q.type,.1+Math.random()*.3,.1+Math.random()*.3),text:q.text,...q.type==="speech"&&q.speaker?{speaker:q.speaker}:{}},Ee={...De,...Le(De)};ee(Ke=>[...Ke,Ee]),I(Ee.id)},[Le]),We=w.useCallback((q,ke)=>{ee(De=>De.map(Ee=>Ee.id===q?{...Ee,...ke}:Ee))},[]),bt=w.useCallback(q=>{var nt;const ke=G.height||300,De=G.width>0?kn(q.width,G.width):200,Ee=G.height>0?kn(q.height,G.height):100,Ke=q.type==="sfx"?j:S,Xe=ou(ae(Ke),q.text,De,Ee,cu({...q,textStyle:void 0},ke,De,Ee));We(q.id,{textStyle:{mode:"manual",fontScale:Xe.fontSize/Math.max(1,ke),fontWeight:((nt=q.textStyle)==null?void 0:nt.fontWeight)??400,lineHeightFactor:Xe.fontSize>0?Xe.lineHeight/Xe.fontSize:1.2,speakerScale:Xe.fontSize>0&&Xe.speakerFontSize>0?Xe.speakerFontSize/Xe.fontSize:.8}})},[G,j,S,ae,We]),Qe=w.useCallback(q=>{ee(ke=>ke.filter(De=>De.id!==q)),I(null),L(!1)},[]),Ft=w.useCallback(()=>{I(null),L(!1)},[]),Pe=w.useCallback((q,ke)=>{q.stopPropagation(),I(ke),L(!1)},[]),ft=w.useCallback((q,ke,De)=>{q.stopPropagation(),q.preventDefault();const Ee=M.find(Ke=>Ke.id===ke);Ee&&(I(ke),Re.current={id:ke,mode:De,startX:q.clientX,startY:q.clientY,origX:Ee.x,origY:Ee.y,origW:Ee.width,origH:Ee.height})},[M]);w.useEffect(()=>{const q=De=>{const Ee=Re.current;if(!Ee||G.width===0)return;const Ke=ly(De.clientX-Ee.startX,G.width),Xe=ly(De.clientY-Ee.startY,G.height);if(Ee.mode==="move"){const nt=du(Ee.origX+Ke,0,1-Ee.origW),qt=du(Ee.origY+Xe,0,1-Ee.origH);We(Ee.id,{x:nt,y:qt})}else{const nt=du(Ee.origW+Ke,cy,1-Ee.origX),qt=du(Ee.origH+Xe,cy,1-Ee.origY);We(Ee.id,{width:nt,height:qt})}},ke=()=>{Re.current=null};return window.addEventListener("mousemove",q),window.addEventListener("mouseup",ke),()=>{window.removeEventListener("mousemove",q),window.removeEventListener("mouseup",ke)}},[G,We]);const Ze=w.useCallback(async()=>{k(null);try{await s(M),f&&a()}catch(q){k(q instanceof Error?q.message:"Failed to save overlays")}},[M,s,a,f]),pt=w.useCallback(()=>{var q;(q=navigator.clipboard)==null||q.writeText(CM(t,i)),te(!0),setTimeout(()=>te(!1),2e3)},[t,i]),ei=w.useCallback(async()=>{if(N>0&&!z){const q=N;D(`${q} overlay${q===1?"":"s"} from the cut plan ${q===1?"has":"have"} no usable position and cannot be exported — re-place ${q===1?"it":"them"} or discard ${q===1?"it":"them"} first.`);return}ge(!0),D(null);try{await s(M);const{exportCut:q,ensureFontsReady:ke}=await ry(async()=>{const{exportCut:xi,ensureFontsReady:ce}=await import("./export-cut-DmVsiKji.js");return{exportCut:xi,ensureFontsReady:ce}},[]),De=M.some(xi=>xi.type==="sfx"),Ee=[b.family,...De?[v.family]:[]],{ready:Ke,missing:Xe}=await ke(Ee);if(!Ke){D(`Fonts not loaded: ${Xe.join(", ")}. Check your connection and retry.`),ge(!1);return}if(t.cleanImagePath&&!R.url){D(R.error?"Clean image failed to load — cannot export. Retry once it renders.":"Clean image still loading — wait for it to render, then export."),ge(!1);return}const nt=R.url,qt=await q(nt,M,S,j,{narration:t.narration,dialogue:t.dialogue},t.kind==="text"?{background:t.background,aspectRatio:t.aspectRatio}:void 0),mt=new FormData,ct=qt.type==="image/webp"?"webp":"jpg";mt.append("file",qt,`cut-${t.id}.${ct}`);const Ai=await h(`/api/stories/${e}/cuts/${i}/export-final/${t.id}`,{method:"POST",body:mt});if(Ai.ok)ye(wu(M)),o==null||o();else{const xi=await Ai.json();D(xi.error||"Export failed")}}catch(q){D(q instanceof Error?q.message:"Export failed")}finally{ge(!1)}},[t,R,M,e,i,b,v,S,j,h,s,o,N,z]),we=M.find(q=>q.id===V),yi=w.useMemo(()=>U3(M),[M]),se=w.useRef(t.id);w.useEffect(()=>{se.current!==t.id&&(se.current=t.id,ye(wu(E.overlays)))},[t.id,E.overlays]);const me=_M({exported:!!t.finalImagePath||!!t.exportedAt,uploaded:!!t.uploadedUrl||!!t.uploadedCid,baselineSig:fe,current:M}),Te=w.useMemo(()=>xM({...t,overlays:M},{staleExport:me}),[t,M,me]),Fe=w.useMemo(()=>$S(t),[t]),it=w.useMemo(()=>{const q={};for(const ke of M){const De=D3(ke);let Ee=!1;if(W&&G.width>0&&ke.text){const Ke=ke.type==="sfx"?j:S,Xe=kn(ke.width,G.width),nt=kn(ke.height,G.height);Ee=ou(ae(Ke),ke.text,Xe,nt,cu(ke,G.height||300,Xe,nt)).overflow}(De||Ee)&&(q[ke.id]={outOfBounds:De,overflow:Ee})}return q},[M,W,G,ae,S,j]),Ot=Object.keys(it).length,ui=t.kind==="text",zt=!t.cleanImagePath;return!ui&&zt&&M.length===0&&!t.narration&&!((At=t.dialogue)!=null&&At.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:[M.length," overlays"]})]}),d.jsxs("div",{className:"flex items-center gap-2 flex-wrap justify-end",children:[d.jsx("button",{onClick:a,className:"px-3 py-1 text-xs border border-border rounded text-muted hover:text-foreground","data-testid":"return-to-cut-review-btn",children:"Back to cut review"}),x&&d.jsx("button",{onClick:x,className:"px-3 py-1 text-xs border border-border rounded text-muted hover:border-accent hover:text-accent","data-testid":"toggle-work-area-btn",children:_?"Hide work area":"Show work area"}),d.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[d.jsx("button",{onClick:()=>Ae("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:()=>Ae("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:()=>Ae("sfx"),className:"px-2 py-0.5 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5","data-testid":"add-sfx",children:"SFX"})]}),T&&d.jsx("span",{className:"text-[10px] text-error",children:T}),K&&d.jsx("span",{className:"text-[10px] text-error",children:K}),d.jsx("button",{onClick:ei,disabled:U,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:U?"Exporting...":"Export"}),d.jsx("button",{onClick:()=>{Ze()},className:"px-3 py-1 text-xs bg-accent text-white rounded hover:bg-accent-dim","data-testid":"save-lettering-btn",children:"Save"}),d.jsx("button",{onClick:a,className:"px-3 py-1 text-xs text-muted hover:text-foreground border border-border rounded","data-testid":"cancel-lettering-btn",children:"Cancel"})]})]}),N>0&&!z?d.jsxs("div",{className:"px-3 py-1 border-b border-border bg-error/10 text-[10px] text-error flex items-center gap-2 flex-wrap","data-testid":"overlay-repair-note",children:[d.jsxs("span",{children:[N," overlay",N===1?"":"s"," ","from the cut plan ",N===1?"has":"have"," no usable position and cannot be exported. Re-place"," ",N===1?"it":"them",", or"]}),d.jsxs("button",{onClick:()=>J(!0),"data-testid":"discard-invalid-overlays",className:"px-1.5 py-0.5 border border-error/40 rounded hover:bg-error/10",children:["discard ",N," unplaceable overlay",N===1?"":"s"]})]}):N>0?d.jsxs("div",{className:"px-3 py-1 border-b border-border bg-amber-500/10 text-[10px] text-amber-700","data-testid":"overlay-repair-note",children:["Discarded ",N," unplaceable overlay",N===1?"":"s"," — the export will not include"," ",N===1?"it":"them","."]}):F?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,yi.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,": ",yi.length," bubble"," ",yi.length===1?"pair overlaps":"pairs overlap"," and may be hard to read —"," ",yi.map(q=>`#${q.indexA+1} ${Df(M[q.indexA])} ↔ #${q.indexB+1} ${Df(M[q.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",Te.hasCleanImage],["script-text","Script text",Te.hasScriptText],["bubbles",`Bubbles placed${Te.bubblesPlaced?` (${Te.bubblesPlaced})`:""}`,Te.bubblesPlaced>0],["exported","Final exported",Te.exported],["uploaded","Uploaded",Te.uploaded]].map(([q,ke,De])=>d.jsxs("span",{"data-testid":`lettering-check-${q}`,"data-done":De?"true":"false",className:`flex items-center gap-1 ${De?"text-green-700":"text-muted/70"}`,children:[d.jsx("span",{"aria-hidden":!0,children:De?"✓":"○"}),ke]},q))}),me&&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."}),Ot>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:[Ot," bubble",Ot===1?"":"s"," may not export cleanly:"," ",Object.entries(it).map(([q,ke])=>{const De=M.findIndex(Ke=>Ke.id===q),Ee=[ke.outOfBounds?"outside image":null,ke.overflow?"text overflow":null].filter(Boolean).join(", ");return`#${De+1} ${Df(M[De])} (${Ee})`}).join("; "),". Resize or reposition before exporting."]}),d.jsxs("div",{className:"flex-1 min-h-0 flex",children:[d.jsxs("div",{ref:le,className:"flex-1 min-w-0 relative overflow-hidden bg-[#f8f5ef]",onClick:Ft,"data-testid":"editor-surface",children:[t.cleanImagePath&&R.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&&!R.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:xe,src:R.url,alt:`Cut ${t.id} clean`,className:"w-full h-full object-contain",draggable:!1,onLoad:Me}):ui?G.width>0&&d.jsx("div",{className:"absolute flex items-center justify-center text-muted text-xs",style:{left:G.x,top:G.y,width:G.width,height:G.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:q=>{if(q&&G.width===0){const ke=q.getBoundingClientRect();ke.width>0&&H({x:0,y:0,width:ke.width,height:ke.height})}},children:"Narration cut"}),G.width>0&&d.jsx("svg",{className:"absolute inset-0 w-full h-full pointer-events-none","data-testid":"balloon-layer",children:M.map(q=>{if(q.type!=="speech")return null;const ke=G.x+kn(q.x,G.width),De=G.y+kn(q.y,G.height),Ee=kn(q.width,G.width),Ke=kn(q.height,G.height),Xe=T3(q,Ee,Ke),nt=q.tailAnchor?OS(ke,De,Ee,Ke,q.tailAnchor,Xe):null,qt=Math.max(1.5,G.height*.004),mt=q.id===V;return d.jsx("path",{"data-testid":`balloon-${q.id}`,d:M3(ke,De,Ee,Ke,nt,Xe),className:`fill-white/95 ${mt?"stroke-accent":"stroke-[#1a1a1a]"}`,strokeWidth:mt?qt+.5:qt,strokeLinejoin:"round"},q.id)})}),G.width>0&&M.map(q=>{const ke=G.x+kn(q.x,G.width),De=G.y+kn(q.y,G.height),Ee=kn(q.width,G.width),Ke=kn(q.height,G.height),Xe=q.id===V,nt=q.type==="speech",qt=q.type==="narration",mt=!!it[q.id];return d.jsxs("div",{"data-testid":`overlay-${q.id}`,"data-warning":mt?"true":"false",onClick:ct=>Pe(ct,q.id),onMouseDown:ct=>ft(ct,q.id,"move"),className:`absolute rounded cursor-move select-none ${nt?"":`border-2 ${kM[q.type]}`} ${qt?"bg-[#f4efe6]/85 rounded-md":""} ${Xe&&!nt?"ring-2 ring-accent":""} ${mt?"ring-2 ring-amber-500":""}`,style:{left:ke,top:De,width:Ee,height:Ke},children:[(()=>{var ce,Ne;const ct=q.type==="sfx"?j:S;if(!q.text)return d.jsx("span",{className:"text-[9px] px-1 text-muted truncate block pointer-events-none",style:{fontFamily:ct},children:Cu[q.type]});const Ai=q.type!=="sfx"&&!!q.speaker;if(!W)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:ct,fontSize:Math.max(9,Math.min(Ke*.05,16)),fontWeight:((ce=q.textStyle)==null?void 0:ce.fontWeight)??400},"data-testid":`overlay-text-${q.id}`,"data-fonts-ready":"false",children:Ai?`${q.speaker}: ${q.text}`:q.text});const xi=ou(ae(ct),q.text,Ee,Ke,cu(q,G.height,Ee,Ke));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:ct},"data-testid":`overlay-text-${q.id}`,"data-fonts-ready":"true",children:[Ai&&d.jsx("span",{className:"font-bold text-[#3a3a3a] block",style:{fontSize:xi.speakerFontSize,lineHeight:1.2},children:q.speaker}),d.jsx("span",{className:"text-[#1a1a1a]",style:{fontSize:xi.fontSize,lineHeight:`${xi.lineHeight}px`,fontWeight:((Ne=q.textStyle)==null?void 0:Ne.fontWeight)??400},children:xi.lines.map((Ie,rt)=>d.jsx("span",{className:"block",children:Ie},rt))})]})})(),Xe&&d.jsx("div",{onMouseDown:ct=>{ct.stopPropagation(),ft(ct,q.id,"resize")},className:"absolute bottom-0 right-0 w-2 h-2 bg-accent cursor-se-resize","data-testid":`resize-${q.id}`})]},q.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:pt,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:ue?"Copied!":"Copy AI draft prompt"})]}),Fe.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:Fe.map(q=>d.jsxs("button",{onClick:()=>ut(q),"data-testid":`script-insert-${q.key}`,title:`Add ${q.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:["+ ",Cu[q.type]]})," ",d.jsxs("span",{className:"text-muted",children:[q.speaker?`${q.speaker}: `:"",q.text.length>32?`${q.text.slice(0,32)}…`:q.text]})]},q.key))})]}),we?d.jsxs("div",{className:"space-y-3",children:[d.jsx("p",{className:"text-xs font-medium text-foreground",children:Cu[we.type]}),we.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:we.speaker||"",onChange:q=>We(we.id,{speaker:q.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:we.text,onChange:q=>We(we.id,{text:q.target.value}),rows:3,className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent resize-none focus:border-accent focus:outline-none",placeholder:"Overlay text","data-testid":"inspector-text"})]}),d.jsx("button",{onClick:()=>We(we.id,Le(we)),"data-testid":"inspector-fit-text",className:"w-full px-2 py-1 text-[11px] border border-border rounded hover:border-accent hover:text-accent",title:"Resize this overlay so its text fits without overflowing",children:"Fit box to text"}),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=we.textStyle)==null?void 0:Ct.mode)==="manual"?d.jsx("button",{type:"button",onClick:()=>We(we.id,{textStyle:void 0}),className:"px-1.5 py-0.5 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5","data-testid":"inspector-text-auto",children:"Auto-fit"}):d.jsx("button",{type:"button",onClick:()=>bt(we),className:"px-1.5 py-0.5 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5","data-testid":"inspector-text-manual",children:"Manual"})]}),((He=we.textStyle)==null?void 0:He.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:((we.textStyle.fontScale??.032)*100).toFixed(1),onChange:q=>We(we.id,{textStyle:{...we.textStyle,mode:"manual",fontScale:Math.max(.015,Math.min(.12,(parseFloat(q.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(we.textStyle.fontWeight??400),onChange:q=>We(we.id,{textStyle:{...we.textStyle,mode:"manual",fontWeight:q.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:(we.textStyle.lineHeightFactor??1.2).toFixed(2),onChange:q=>We(we.id,{textStyle:{...we.textStyle,mode:"manual",lineHeightFactor:Math.max(.9,Math.min(2,parseFloat(q.target.value)||1.2))}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-line-height"})]}),we.type!=="sfx"&&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:(we.textStyle.speakerScale??.8).toFixed(2),onChange:q=>We(we.id,{textStyle:{...we.textStyle,mode:"manual",speakerScale:Math.max(.5,Math.min(1.5,parseFloat(q.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."})]}),we.type==="speech"&&(()=>{const q=we.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:()=>We(we.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:q.x,onChange:ke=>We(we.id,{tailAnchor:{...q,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:q.y,onChange:ke=>We(we.id,{tailAnchor:{...q,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"})]})]})]})})(),we.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:((((li=we.bubbleStyle)==null?void 0:li.paddingX)??.06)*100).toFixed(0),onChange:q=>We(we.id,{bubbleStyle:{...we.bubbleStyle,paddingX:Math.max(0,Math.min(.25,(parseFloat(q.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:((((st=we.bubbleStyle)==null?void 0:st.paddingY)??.08)*100).toFixed(0),onChange:q=>We(we.id,{bubbleStyle:{...we.bubbleStyle,paddingY:Math.max(0,Math.min(.25,(parseFloat(q.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:((((_n=we.bubbleStyle)==null?void 0:_n.cornerRadius)??.4)*100).toFixed(0),onChange:q=>We(we.id,{bubbleStyle:{...we.bubbleStyle,cornerRadius:Math.max(0,Math.min(.49,(parseFloat(q.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:"," ",we.type==="sfx"?v.family:b.family]}),d.jsxs("div",{className:"text-[10px] font-mono text-muted space-y-0.5",children:[d.jsxs("p",{children:["x: ",we.x.toFixed(3),", y:"," ",we.y.toFixed(3)]}),d.jsxs("p",{children:["w: ",we.width.toFixed(3),", h:"," ",we.height.toFixed(3)]})]}),d.jsx("button",{onClick:()=>{A?Qe(we.id):L(!0)},className:"w-full px-2 py-1 text-xs text-error border border-error/30 rounded hover:bg-error/5","data-testid":"delete-overlay",children:A?"Click again to delete":"Delete"})]}):d.jsx("p",{className:"text-xs text-muted","data-testid":"inspector-empty",children:"Select an overlay to inspect."})]})]})]})}const FS=12e3,jM=5,TM=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,TM)}const qS=e=>new Promise(t=>setTimeout(t,e));async function BM(e,t={}){var c;const i=t.sleep??qS,s=t.maxRetries??jM,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 Lp=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<=Lp)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<=Lp)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<=Lp}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 Yu(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 N=await HM(e);E||o(N)})(),()=>{E=!0}},[e]);const b=_.trim().toLowerCase(),v=w.useMemo(()=>a?b?a.filter(E=>E.name.toLowerCase().includes(b)):a:[],[a,b]),S=Date.now(),j=async E=>{h(null),f(E.token);try{const N=await UM(e,E);await i(N)}catch(N){h(N instanceof Error?N.message:"Could not import the generated image")}finally{f(null)}},R=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"})]}),R&&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."}),R&&v.length===0&&d.jsxs("p",{className:"text-[11px] text-muted","data-testid":`codex-picker-no-match-${t}`,children:["No generated images match “",_.trim(),"”."]}),R&&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,S)," · ",FM(E.size)]}),d.jsx("p",{className:"truncate text-[10px] font-mono text-muted",title:E.name,children:E.name})]}),d.jsx("button",{onClick:()=>j(E),disabled:p!==null,"data-testid":`codex-import-${E.token}`,className:"px-2 py-1 text-[11px] border border-accent/30 text-accent rounded hover:bg-accent/5 disabled:opacity-50",children:p===E.token?"Importing…":"Import to this cut"})]},E.token))}),c&&d.jsx("p",{className:"text-[11px] text-error",children:c})]})}const 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 E;if(!e||e.steps.length===0)return null;const p=US(t),f=((E=e.steps.find(N=>N.key==="upload"))==null?void 0:E.status)==="done",_=f&&c&&!h,x=h||c?"done":f?"current":"todo",b=h?"done":_?"current":"todo",v=[...e.steps.filter(N=>N.key!=="publish"),{key:"assemble",label:"Episode sequence prepared",status:x,detail:null},{key:"ready",label:h?"Published to PlotLink":"Ready to publish",status:b,detail:null}],S=s?a||"Finishing…":h?"Published ✓":_?"Episode ready to publish":"Finish episode",j=v.filter(N=>N.status!=="done").length,R=p.reduce((N,z)=>N+z.lines.length,0);return d.jsxs("div",{className:"px-3 py-1.5 border-b border-border bg-surface/50 flex-shrink-0","data-testid":"finish-episode-panel",children:[d.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Finish episode"}),e.nextStep&&d.jsxs("span",{className:"min-w-0 flex-1 text-[10px] text-muted truncate","data-testid":"finish-next-step",children:["Next: ",e.nextStep]}),d.jsx("button",{onClick:i,disabled:s||!o,"data-testid":"finish-episode-btn",title:"Upload the exported final panels, then prepare the episode for publishing — picks up where it left off",className:"px-2.5 py-0.5 text-[11px] border border-accent/40 text-accent rounded hover:bg-accent/5 disabled:opacity-50",children:S})]}),d.jsxs("details",{className:"mt-1","data-testid":"finish-episode-details",children:[d.jsxs("summary",{className:"cursor-pointer select-none text-[10px] text-muted hover:text-foreground",children:[j===0?"Progress details":`${j} step${j===1?"":"s"} left`,R>0?` · ${R} blocker${R===1?"":"s"}`:""]}),d.jsxs("div",{className:"mt-1.5 space-y-1.5",children:[d.jsx("ol",{className:"flex flex-wrap gap-1.5",children:v.map(N=>d.jsxs("li",{"data-testid":`finish-step-${N.key}`,"data-status":N.status,className:`flex items-center gap-1 rounded border px-1.5 py-0.5 text-[10px] ${N.status==="current"?"border-accent/40 bg-accent/10 text-accent":N.status==="done"?"border-border bg-background/70 text-foreground":"border-border/70 bg-background/40 text-muted"}`,children:[d.jsx("span",{"aria-hidden":!0,children:YM[N.status]}),d.jsx("span",{children:N.label}),N.detail&&d.jsxs("span",{className:"text-muted",children:["· ",N.detail]})]},N.key))}),p.length>0&&d.jsx("div",{className:"space-y-1.5","data-testid":"finish-issues",children:p.map(N=>d.jsxs("div",{"data-testid":`finish-issue-group-${N.key}`,className:"text-[10px]",children:[d.jsx("p",{className:"font-medium text-amber-700",children:N.title}),d.jsx("ul",{className:"ml-3 list-disc text-muted",children:N.lines.map((z,J)=>d.jsx("li",{children:z},J))})]},N.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":rr(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"}:rr(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"}:rr(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:S,onConvert:j,converting:R,rowRef:E}){var G;const N=w.useRef(null),[z,J]=w.useState(!1),[F,M]=w.useState(null),[ee,fe]=w.useState(!1),[ye,P]=w.useState(!1),[ae,W]=w.useState(!1),[Y,V]=w.useState(!1),I=GS(e),A=x.length>0,L=!!S,U=w.useCallback(async()=>{S&&(V(!0),await j(e.id,S),V(!1),c())},[S,j,e.id,c]),ge=w.useCallback(async H=>{J(!0),M(null);try{let le=H;if(!WS(H))try{le=await Yu(H)}catch(Le){return M(Le instanceof Error?Le.message:"Could not import image"),!1}const xe=le.type==="image/jpeg"?"jpg":"webp",Re=new FormData;Re.append("file",new File([le],`clean.${xe}`,{type:le.type}));const Me=await o(`/api/stories/${t}/cuts/${i}/upload-clean/${e.id}`,{method:"POST",body:Re});if(!Me.ok){const Le=await Me.json();return M(Le.error||"Upload failed"),!1}return c(),!0}catch{return M("Upload failed"),!1}finally{J(!1)}},[o,t,i,e.id,c]),T=ZM(e,L,A),D=e.cleanImagePath??S??null,K=((G=e.overlays)==null?void 0:G.length)??0,k=!rr(e)&&!!e.cleanImagePath&&!e.finalImagePath&&!e.uploadedCid&&!e.uploadedUrl&&!A&&!L,ue=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,te=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})]}),D?d.jsx(Dp,{storyName:t,assetPath:D,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:rr(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[te.tone]}`,"data-testid":`lettering-review-state-${e.id}`,children:[d.jsx("span",{className:"font-semibold",children:te.label}),d.jsxs("span",{className:"text-muted",children:[" · ",te.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:[k?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:K>0?"Review lettering":"Open focused editor"}):ue?d.jsx("button",{onClick:ue.onClick,disabled:T.key==="convert"&&(Y||R),"data-testid":ue.testid,className:"px-2.5 py-1 text-[11px] font-medium rounded bg-accent text-white hover:bg-accent-dim disabled:opacity-50",children:ue.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:[L&&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||R,"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&&!L&&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((H,le)=>d.jsx("p",{className:"text-[11px] text-error",children:H},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"})]}),!rr(e)&&d.jsxs("div",{className:"mt-2 space-y-2",children:[d.jsx("button",{onClick:()=>{navigator.clipboard.writeText(ay(e,i)),fe(!0),setTimeout(()=>fe(!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:ee?"Copied!":"Copy Codex task"}),d.jsx("input",{ref:N,type:"file",accept:"image/webp,image/jpeg,image/png",className:"hidden",onChange:H=>{var xe;const le=(xe=H.target.files)==null?void 0:xe[0];le&&ge(le),H.target.value=""}}),d.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[d.jsx("button",{onClick:()=>{var H;return(H=N.current)==null?void 0:H.click()},disabled:z,className:"px-3 py-1.5 text-xs border border-border rounded hover:border-accent hover:bg-accent/5 disabled:opacity-50",children:z?"Uploading...":e.cleanImagePath?"Replace clean image":"Upload clean image"}),d.jsx("button",{onClick:()=>W(H=>!H),disabled:z,"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 H=>{await ge(H)&&W(!1)},onClose:()=>W(!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:ye?"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"}),F&&d.jsx("p",{className:"text-xs text-error mt-1",children:F})]}),(e.cleanImagePath||e.narration||e.dialogue.length>0||rr(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((H,le)=>d.jsxs("p",{children:[d.jsxs("span",{className:"font-medium",children:[H.speaker,":"]})," ",H.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,onFocusedLetteringModeChange:p,workspaceVisible:f=!1,onWorkspaceVisibleChange:_}){var ct,Ai,xi;const[x,b]=w.useState(null),v=w.useRef(o);v.current=o;const S=w.useRef(h);S.current=h;const[j,R]=w.useState(!0),[E,N]=w.useState(null),[z,J]=w.useState(null),[F,M]=w.useState(null),[ee,fe]=w.useState(!1),[ye,P]=w.useState([]),[ae,W]=w.useState(!1),[Y,V]=w.useState(""),[I,A]=w.useState({markdownReady:!1,published:!1}),[L,U]=w.useState(!1),[ge,T]=w.useState(!1),[D,K]=w.useState(!1),[k,ue]=w.useState(null),[te,G]=w.useState(null),[H,le]=w.useState(new Set),[xe,Re]=w.useState(new Map),[Me,Le]=w.useState(!1),[Ae,ut]=w.useState(null),[We,bt]=w.useState(!1),[Qe,Ft]=w.useState(null),Pe=w.useRef(new Map),ft=w.useRef(null),Ze=t.replace(/\.md$/,"");w.useEffect(()=>{var ce;c&&ft.current!==c.seq&&(ft.current=c.seq,c.openEditor?M(c.cutId):(J(c.cutId),Ft(c.cutId)),(ce=S.current)==null||ce.call(S))},[c]),w.useEffect(()=>{var Ne;if(Qe==null)return;const ce=Pe.current.get(Qe);ce&&((Ne=ce.scrollIntoView)==null||Ne.call(ce,{behavior:"smooth",block:"center"}),Ft(null))},[Qe,x]),w.useEffect(()=>(p==null||p(F!==null),()=>p==null?void 0:p(!1)),[F,p]);const pt=w.useCallback(async()=>{var ce;try{const Ne=await i(`/api/stories/${e}/cuts/${Ze}`);if(Ne.status===404){b(null);return}if(!Ne.ok){const rt=await Ne.json();N(rt.error||"Failed to load cuts");return}const Ie=await Ne.json();b(Ie),N(null);try{const rt=await i(`/api/stories/${e}/${t}`);if(rt.ok){const Ye=await rt.json(),kt=typeof(Ye==null?void 0:Ye.content)=="string"?Ye.content:"",Ge=Array.isArray(Ie==null?void 0:Ie.cuts)?Ie.cuts:[],ie=kt.length>0&&IS(kt,Ge).ready,ve=(Ye==null?void 0:Ye.status)==="published"||(Ye==null?void 0:Ye.status)==="published-not-indexed";A({markdownReady:ie,published:ve})}else A({markdownReady:!1,published:!1})}catch{A({markdownReady:!1,published:!1})}(ce=v.current)==null||ce.call(v)}catch{N("Failed to load cuts")}finally{R(!1)}},[i,e,Ze,t]),ei=w.useCallback(async()=>{Le(!1);try{const ce=await i(`/api/stories/${e}/cuts/${Ze}/detect-clean-images`);if(!ce.ok)return;const Ne=await ce.json();le(new Set(Array.isArray(Ne.detected)?Ne.detected:[]));const Ie=new Map,rt=Ne.stale;if(Array.isArray(rt))for(const Ye of rt){if(typeof(Ye==null?void 0:Ye.cutId)!="number"||typeof(Ye==null?void 0:Ye.message)!="string")continue;const kt=Ie.get(Ye.cutId)??[];kt.push(Ye.message),Ie.set(Ye.cutId,kt)}Re(Ie),Le(!0)}catch{}},[i,e,Ze]),we=w.useCallback(async()=>{ut(null);try{const ce=await i(`/api/stories/${e}/cuts/${Ze}/asset-diagnostics`);if(!ce.ok)return;const Ne=await ce.json();ut(Array.isArray(Ne.diagnostics)?Ne.diagnostics:null)}catch{}},[i,e,Ze]),yi=w.useCallback(async()=>{bt(!0);try{await Promise.all([pt(),ei(),we()])}finally{bt(!1)}},[pt,ei,we]),se=w.useCallback(async()=>{U(!0),G(null),P([]);try{const ce=await i(`/api/stories/${e}/cuts/${Ze}/sync-clean-images`,{method:"POST"}),Ne=await ce.json().catch(()=>({}));if(!ce.ok)G(Ne.error||"Sync failed");else{const Ie=Array.isArray(Ne.synced)?Ne.synced.length:0,rt=Array.isArray(Ne.cleared)?Ne.cleared.length:0,Ye=Array.isArray(Ne.rejected)?Ne.rejected:[];Ye.length>0&&P(Ye.map(Ge=>`Cut ${Ge.cutId}: ${Ge.reason}`));const kt=[];Ie>0&&kt.push(`Synced ${Ie}`),rt>0&&kt.push(`Cleared ${rt} stale path${rt===1?"":"s"}`),G(kt.length>0?kt.join(", "):"No new clean images"),await pt(),await ei(),await we()}}catch{G("Sync failed")}U(!1)},[i,e,Ze,pt,ei,we]),me=w.useCallback(async(ce,Ne)=>{try{const Ie=await i(MS(e,Ne));if(!Ie.ok)return!1;const rt=await Ie.blob(),Ye=await Yu(new File([rt],"clean.png",{type:rt.type||"image/png"})),kt=Ye.type==="image/jpeg"?"jpg":"webp",Ge=new FormData;return Ge.append("file",new File([Ye],`clean.${kt}`,{type:Ye.type})),(await i(`/api/stories/${e}/cuts/${Ze}/upload-clean/${ce}`,{method:"POST",body:Ge})).ok}catch{return!1}},[i,e,Ze]),Te=w.useCallback(async ce=>{K(!0),ue(null);let Ne=0;const Ie=[];for(const rt of ce)await me(rt.cutId,rt.pngPath)?Ne++:Ie.push(rt.cutId);await yi(),K(!1),ue(Ie.length===0?`Converted ${Ne} image${Ne===1?"":"s"} to WebP`:`Converted ${Ne}; ${Ie.length} failed (Cut ${Ie.join(", ")}) — try Convert image on each`)},[me,yi]),Fe=w.useCallback(async()=>{var Ye;if(!x)return;W(!0),V(""),P([]);const ce=x.cuts.filter(kt=>kt.finalImagePath&&!kt.uploadedCid),Ne=[],Ie=LM({sleep:a==null?void 0:a.sleep,onWaiting:({waitMs:kt})=>V(`Upload limit reached — waiting ${Math.round(kt/1e3)}s before continuing…`)});for(let kt=0;kt{const Et=await i("/api/publish/upload-plot-image",{method:"POST",body:Pt});if(Et.ok){const{cid:Rt,url:Bt}=await Et.json();return{ok:!0,status:Et.status,cid:Rt,url:Bt}}const Je=await Et.json().catch(()=>({}));return{ok:!1,status:Et.status,errorMessage:Je.error}},{...a,onWaiting:({attempt:Et,maxRetries:Je,waitMs:Rt})=>V(`Cut ${Ge.id} rate-limited — waiting ${Math.round(Rt/1e3)}s before retry ${Et}/${Je}...`)});if(!vt.ok){Ne.push(`Cut ${Ge.id}: upload failed — ${vt.errorMessage||"unknown"}`);continue}const{cid:yt,url:Wt}=vt;(await i(`/api/stories/${e}/cuts/${Ze}/set-uploaded/${Ge.id}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cid:yt,url:Wt})})).ok||Ne.push(`Cut ${Ge.id}: failed to record upload`)}catch(ie){Ne.push(`Cut ${Ge.id}: ${ie instanceof Error?ie.message:"failed"}`)}}if(Ne.length>0){P(Ne),W(!1),V(""),pt();return}V("Preparing episode for publishing…");const rt=await i(`/api/stories/${e}/cuts/${Ze}/generate-markdown`,{method:"POST"});if(rt.ok){const kt=await rt.json();((Ye=kt.warnings)==null?void 0:Ye.length)>0&&P(kt.warnings)}W(!1),V(""),pt()},[x,i,e,Ze,a,pt]),it=w.useCallback(async()=>{T(!0),G(null);try{const ce=await i(`/api/stories/${e}/cuts/${Ze}/repair-asset-paths`,{method:"POST"}),Ne=await ce.json().catch(()=>({}));if(!ce.ok)G(Ne.error||"Repair failed");else{const Ie=Array.isArray(Ne.cleared)?Ne.cleared.length:0;G(Ie>0?`Cleared ${Ie} stale path${Ie===1?"":"s"}`:"No stale paths to clear"),await pt(),await ei()}}catch{G("Repair failed")}T(!1)},[i,e,Ze,pt,ei]),[Ot,ui]=w.useState(!1),zt=w.useCallback(async(ce,Ne=!0)=>{if(x){ui(!0);try{const Ie=x.cuts.reduce((ie,ve)=>Math.max(ie,ve.id),0)+1,rt={id:Ie,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"},Ye=[...x.cuts];Ye.splice(Math.max(0,Math.min(ce,Ye.length)),0,rt);const kt={...x,cuts:Ye},Ge=await i(`/api/stories/${e}/cuts/${Ze}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(kt)});if(Ge.ok)Ne?M(Ie):J(Ie),await pt();else{const ie=await Ge.json().catch(()=>({}));G(ie.error||"Could not add text panel")}}catch{G("Could not add text panel")}ui(!1)}},[x,i,e,Ze,pt]),At=w.useCallback(()=>zt((x==null?void 0:x.cuts.length)??0,!0),[zt,x]);if(w.useEffect(()=>{pt(),ei(),we()},[pt,ei,we]),j)return d.jsx("div",{className:"p-4 text-sm text-muted",children:"Loading cuts..."});if(E)return d.jsxs("div",{className:"p-4 space-y-2","data-testid":"cuts-error",children:[d.jsx("p",{className:"text-sm text-error font-medium",children:"Invalid cuts file"}),d.jsx("p",{className:"text-xs text-error",children:E}),d.jsxs("p",{className:"text-xs text-muted",children:[Ze,".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:pt,className:"text-xs text-accent hover:text-accent-dim",children:"Retry"})]});if(!x||x.cuts.length===0)return d.jsxs("div",{className:"p-4 text-center space-y-1",children:[d.jsx("p",{className:"text-sm text-muted",children:"No cuts yet"}),d.jsx("p",{className:"text-xs text-muted",children:"Ask Claude to create a cut plan for this episode."})]});const Ct=F!==null?x.cuts.find(ce=>ce.id===F):null;if(Ct)return d.jsx(NM,{storyName:e,cut:Ct,plotFile:Ze,language:s,authFetch:i,targetLabel:rr(Ct)?`Between-scene card ${Ct.id}`:`Cut ${String(Ct.id).padStart(2,"0")}`,returnOnSave:!0,workspaceVisible:f,onToggleWorkspaceVisible:_?()=>_(!f):void 0,onSave:async ce=>{const Ne={...x,cuts:x.cuts.map(rt=>rt.id===F?{...rt,overlays:ce}:rt)},Ie=await i(`/api/stories/${e}/cuts/${Ze}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(Ne)});if(!Ie.ok){const rt=await Ie.json().catch(()=>({}));throw new Error(rt.error||"Failed to save overlays")}},onExported:()=>pt(),onClose:()=>{M(null),pt()}});const He=x.cuts.reduce((ce,Ne)=>{const Ie=GS(Ne);return ce[Ie]++,ce},{missing:0,clean:0,lettered:0,uploaded:0,text:0}),li=x.cuts.filter(ce=>!rr(ce)).length,st=x.cuts.filter(ce=>zS(ce)).map(ce=>ce.id),_n=iM({cuts:x.cuts,published:I.published}),q=((ct=_n.steps.find(ce=>ce.key==="upload"))==null?void 0:ct.status)==="done",ke=x.cuts.some(ce=>ce.finalImagePath&&!ce.uploadedCid)||q&&!I.markdownReady,De=(Ae??[]).filter(ce=>ce.state==="needs-conversion"&&ce.convertiblePng).map(ce=>({cutId:ce.cutId,pngPath:ce.convertiblePng})),Ee=new Map(De.map(ce=>[ce.cutId,ce.pngPath])),Ke=(Ae??[]).filter(ce=>ce.state==="needs-conversion"&&ce.issue).map(ce=>ce.issue),Xe=t==="genesis.md"?"Genesis / Episode 1":`Episode ${parseInt(((Ai=Ze.match(/\d+/))==null?void 0:Ai[0])??"0",10)+1}`,nt=typeof x.title=="string"?x.title:null,qt=x.cuts.filter(ce=>!rr(ce)),mt={cuts:x.cuts.length,artwork:qt.filter(ce=>ce.cleanImagePath||Ee.has(ce.id)).length,converted:qt.filter(ce=>ce.cleanImagePath&&/\.(webp|jpe?g)$/i.test(ce.cleanImagePath)).length,lettered:x.cuts.filter(ce=>{var Ne;return(((Ne=ce.overlays)==null?void 0:Ne.length)??0)>0||!!ce.finalImagePath}).length,uploaded:x.cuts.filter(ce=>ce.uploadedCid||ce.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:Xe}),nt&&d.jsxs("span",{className:"text-muted truncate",children:["· ",nt]})]}),d.jsxs("div",{className:"mt-0.5 text-[10px] text-muted","data-testid":"cut-board-summary",children:[mt.cuts," cuts · ",mt.artwork," artwork found ·"," ",mt.converted," converted · ",mt.lettered," lettered · ",mt.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:[x.cuts.length," cuts"]}),He.missing>0&&d.jsxs("span",{className:"text-muted",children:[He.missing," missing"]}),He.clean>0&&d.jsxs("span",{className:"text-green-700",children:[He.clean," clean"]}),He.lettered>0&&d.jsxs("span",{className:"text-amber-700",children:[He.lettered," lettered"]}),He.uploaded>0&&d.jsxs("span",{className:"text-green-700",children:[He.uploaded," uploaded"]}),He.text>0&&d.jsxs("span",{className:"text-accent",children:[He.text," text ",He.text===1?"panel":"panels"]}),d.jsx("button",{onClick:async()=>{fe(!0),P([]);try{const ce=await i(`/api/stories/${e}/cuts/${Ze}/generate-markdown`,{method:"POST"});if(ce.ok){const Ne=await ce.json();P(Ne.warnings||[])}}catch{}fe(!1)},disabled:ee,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:ee?"Preparing…":"Prepare episode for publish"}),d.jsx("button",{onClick:At,disabled:Ot,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:Ot?"Adding…":"Add narration/text panel"}),d.jsx("button",{onClick:yi,disabled:We,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:We?"Checking…":"Refresh assets"}),d.jsx("button",{onClick:se,disabled:L,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:L?"Syncing...":"Sync clean images"}),d.jsx("button",{onClick:Fe,disabled:ae||!(x!=null&&x.cuts.some(ce=>ce.finalImagePath&&!ce.uploadedCid)),className:"px-2 py-0.5 border border-accent/30 text-accent rounded hover:bg-accent/5 disabled:opacity-50","data-testid":"upload-generate-btn",title:"Upload each cut's final lettered image, then prepare the episode for publishing",children:Y||"Upload & Prepare for Publish"})]})]}),d.jsxs("details",{className:"px-3 py-1.5 border-b border-border bg-surface/40 flex-shrink-0","data-testid":"cartoon-workflow-help",children:[d.jsx("summary",{className:"cursor-pointer select-none text-[10px] text-muted hover:text-foreground",children:"Cut workflow help"}),d.jsxs("div",{className:"mt-1.5",children:[d.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 text-[10px] text-muted",children:[d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"1. Letter"}),d.jsx("span",{"aria-hidden":!0,children:"→"}),d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"2. Export"}),d.jsx("span",{"aria-hidden":!0,children:"→"}),d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"3. Upload"}),d.jsx("span",{"aria-hidden":!0,children:"→"}),d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"4. Prepare episode for publish"})]}),d.jsxs("div",{className:"mt-1 text-[10px] text-muted",children:["Use ",d.jsx("span",{className:"text-accent",children:"Add narration/text panel"})," ","for a narration or title card. It becomes a solid card exported as a final image."]})]})]}),st.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:[st.length===1?"Cut":"Cuts"," ",st.join(", ")," ",st.length===1?"was":"were"," lettered with an older speech-bubble style whose tail can show a visible seam. Re-export"," ",st.length===1?"it":"them"," (open lettering → Export) and re-upload before publishing so the bubble tails are seamless."]}),Me&&li>0&&He.missing===0&&xe.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 ",li," clean image",li===1?"":"s"," ","present — clean-asset generation is complete. Ready for lettering in OWS."]})]}),te&&d.jsx("div",{className:"px-3 py-1 border-b border-border text-[10px] text-muted flex-shrink-0","data-testid":"sync-result",children:te}),De.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:[De.length," PNG image",De.length===1?"":"s"," found"]}),d.jsx("button",{onClick:()=>Te(De),disabled:D,"data-testid":"convert-all-btn",className:"ml-auto px-2 py-0.5 border border-amber-500/50 text-amber-800 rounded hover:bg-amber-500/20 disabled:opacity-50",children:D?"Converting…":"Convert all to WebP"})]}),d.jsx("p",{className:"mt-1 text-[10px] text-muted",children:"PNG artwork is fine while drafting. Convert it before lettering/export so PlotLink can publish it safely."}),k&&d.jsx("p",{className:"mt-1 text-[10px] text-muted","data-testid":"convert-result",children:k}),Ke.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:Ke.map((ce,Ne)=>d.jsx("li",{children:ce},Ne))})]})]}),Ae&&Ae.length>0&&(()=>{const ce=VM(Ae),Ne=Ae.filter(Ie=>Ie.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: ",ce.uploaded," uploaded · ",ce.finalReady," final ·"," ",ce.cleanReady," clean · ",ce.planned," planned",ce.needsConversion>0?` · ${ce.needsConversion} needs conversion`:"",ce.missing>0?` · ${ce.missing} missing`:""]}),Ne.length>0&&d.jsx("ul",{className:"mt-1 ml-3 list-disc text-error","data-testid":"asset-diag-issues",children:Ne.map(Ie=>d.jsx("li",{children:Ie.issue},Ie.cutId))})]})})(),d.jsx(KM,{checklist:_n,issues:ye,onFinish:Fe,finishing:ae,progressText:Y,canFinish:ke,markdownReady:I.markdownReady,published:I.published}),d.jsxs("div",{className:"flex-1 min-h-56 overflow-y-auto p-3 space-y-3","data-testid":"lettering-review-board",children:[x.cuts.map((ce,Ne)=>{var Ie;return d.jsxs(w.Fragment,{children:[d.jsx(fy,{index:Ne,beforeLabel:Ne===0?"Episode opening":`After cut ${(Ie=x.cuts[Ne-1])==null?void 0:Ie.id}`,afterLabel:`Before cut ${ce.id}`,disabled:Ot,onAdd:()=>zt(Ne)}),d.jsx(JM,{cut:ce,storyName:e,plotFile:Ze,expanded:z===ce.id,onToggle:()=>J(z===ce.id?null:ce.id),authFetch:i,onUpdated:()=>{pt(),ei(),we()},onOpenEditor:()=>M(ce.id),detectedLocalClean:H.has(ce.id),onSyncClean:se,syncing:L,staleMessages:xe.get(ce.id)??[],onRepairStale:it,repairing:ge,conversionPng:Ee.get(ce.id)??null,onConvert:me,converting:D,rowRef:rt=>{rt?Pe.current.set(ce.id,rt):Pe.current.delete(ce.id)}})]},ce.id)}),d.jsx(fy,{index:x.cuts.length,beforeLabel:`After cut ${(xi=x.cuts[x.cuts.length-1])==null?void 0:xi.id}`,afterLabel:"Episode ending",disabled:Ot,onAdd:()=>zt(x.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 bm({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(bm,{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 Op(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 Lo(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 zp(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 vm(e){var s;const t=Op(e.fileContent);if(t)return!zp(t);const i=((s=e.episodeTitle)==null?void 0:s.trim())||null;return!!i&&!zp(i)}function ym(e){const{fileName:t,fileContent:i,storySlug:s,structureContent:a,contentType:o,episodeTitle:c}=e,h=Op(i);if(t==="genesis.md"){const p=a?Op(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 Bf(e,t,i){if(e)return t[e]||i.get(e)||"fiction"}function Lf(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=Lf(e.requiredBalance)??Lf(e.creationFee),i=Lf(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={...ml,attributes:{...ml.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,focusedLetteringMode:S=!1,focusedLetteringWorkspaceVisible:j=!1,onFocusedLetteringModeChange:R,onFocusedLetteringWorkspaceVisibleChange:E}){const[N,z]=w.useState(null),[J,F]=w.useState(!1),[M,ee]=w.useState("preview"),[fe,ye]=w.useState("publish"),[P,ae]=w.useState("text"),[W,Y]=w.useState(null),V=w.useCallback((ne,be)=>{ee("edit"),Y(Ce=>({cutId:ne,openEditor:be,seq:((Ce==null?void 0:Ce.seq)??0)+1}))},[]),[I,A]=w.useState(""),[L,U]=w.useState(!1),[ge,T]=w.useState(!1),[D,K]=w.useState(!1),[k,ue]=w.useState(null),[te,G]=w.useState(""),[H,le]=w.useState(""),[xe,Re]=w.useState(!1),[Me,Le]=w.useState(null),[Ae,ut]=w.useState(0),[We,bt]=w.useState(0),[Qe,Ft]=w.useState(null),[Pe,ft]=w.useState(null),[Ze,pt]=w.useState(null),[ei,we]=w.useState(0),yi=w.useRef(null),se=w.useRef(!1),[me,Te]=w.useState(!1),[Fe,it]=w.useState(hl[0]),[Ot,ui]=w.useState(Jr[0]),[zt,At]=w.useState(!1),[Ct,He]=w.useState(null),[li,st]=w.useState(null),[_n,q]=w.useState(!1),[ke,De]=w.useState(!1),[Ee,Ke]=w.useState(!1),[Xe,nt]=w.useState(null),[qt,mt]=w.useState(!1),ct=w.useRef(null),Ai=w.useRef(null),[xi,ce]=w.useState(!1),[Ne,Ie]=w.useState(null),[rt,Ye]=w.useState(null),[kt,Ge]=w.useState("unknown"),ie=w.useRef(!1),[ve,ze]=w.useState(!1),[Pt,vt]=w.useState(!1),[yt,Wt]=w.useState(null),[It,Et]=w.useState([]),[Je,Rt]=w.useState(null),Bt=w.useRef(null),hi=w.useRef(null),Ht=w.useCallback(async()=>{if(!e||!t){z(null);return}const ne=`${e}/${t}`,be=hi.current!==ne;be&&(hi.current=ne);try{const Ce=await i(`/api/stories/${e}/${t}`);if(Ce.ok){const et=await Ce.json();z(et),(be||!se.current)&&(A(et.content??""),be&&(T(!1),se.current=!1))}}catch{}},[e,t,i]);w.useEffect(()=>{F(!0),Ht().finally(()=>F(!1))},[Ht]),w.useEffect(()=>{if(!e||!t||M==="edit"&&ge)return;const ne=setInterval(Ht,3e3);return()=>clearInterval(ne)},[e,t,Ht,M,ge]);const[Ki,Rr]=w.useState(null),an=c==="cartoon"&&t==="genesis.md";w.useEffect(()=>{if(!an||!e){Rr(null);return}let ne=!1;return i(`/api/stories/${e}/cuts/genesis`).then(be=>be.ok?be.json():null).then(be=>{ne||Rr(be?Bp(be.cuts||[]):null)}).catch(()=>{ne||Rr(null)}),()=>{ne=!0}},[an,e,i]);const jn=c==="cartoon"&&!!t&&/^plot-\d+\.md$/.test(t);w.useEffect(()=>{if(!jn||!e||!t){Le(null),ut(0),bt(0),Ft(null);return}let ne=!1;const be=t.replace(/\.md$/,"");return Ft(null),(async()=>{try{const[Ce,et]=await Promise.all([i(`/api/stories/${e}/${t}`),i(`/api/stories/${e}/cuts/${be}`)]);if(ne)return;if(!et.ok){Le("error"),ut(0),bt(0),Ft(null);return}const Gt=await et.json(),Mi=Gt.cuts||[],Wn=Ce.ok?(await Ce.json()).content??"":"",or=HS(Wn,Mi);ne||(Le(or.stage),ut(or.awaitingCount),bt(or.totalCuts),Ft(Bp(Mi)),pt(typeof Gt.title=="string"?Gt.title:null))}catch{ne||(Le("error"),ut(0),bt(0),Ft(null))}})(),()=>{ne=!0}},[jn,e,t,i,N==null?void 0:N.content,N==null?void 0:N.status,ei]),w.useEffect(()=>{if(!e){ft(null);return}let ne=!1;return i(`/api/stories/${e}/structure.md`).then(be=>be.ok?be.json():null).then(be=>{ne||ft((be==null?void 0:be.content)??null)}).catch(()=>{}),()=>{ne=!0}},[e,i]),w.useEffect(()=>{if(!e)return;const ne=Su(p);let be=ne??"";if(!ne&&Pe){const et=Pe.match(/\*{0,2}genre\*{0,2}[:\s]+(.+)/i);et&&(be=Su(et[1].replace(/\*+/g,"").trim())??"")}G(be);let Ce=h&&Jr.find(et=>et.toLowerCase()===h.toLowerCase())||"";if(!Ce&&Pe){const et=Pe.match(/\*{0,2}language\*{0,2}[:\s]+(.+)/i);et&&(Ce=Jr.find(Gt=>Gt.toLowerCase()===et[1].replace(/\*+/g,"").trim().toLowerCase())||"")}le(Ce),Re(f??!1)},[e,p,h,f,Pe]);const rs=w.useCallback(ne=>{e&&i(`/api/stories/${e}/publish-metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(ne)}).catch(()=>{})},[e,i]),ss=w.useCallback(async()=>{if(!(!e||!t)){U(!0);try{(await i(`/api/stories/${e}/${t}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:I})})).ok&&(T(!1),se.current=!1,z(be=>be&&{...be,content:I}))}catch{}U(!1)}},[e,t,i,I]),ri=w.useCallback(async()=>{if(!e||!t)return;const ne=t.replace(/\.md$/,"");try{(await i(`/api/stories/${e}/cuts/${ne}/generate-markdown`,{method:"POST"})).ok&&(await Ht(),we(Ce=>Ce+1))}catch{}},[e,t,i,Ht]),Mr=w.useCallback((ne,be)=>{if(ne==="view-progress"){x==null||x();return}if(be&&be!==t){b==null||b(be);return}switch(ne){case"open-cuts":case"open-lettering":case"upload":case"refresh-assets":ee("edit"),ae("cuts");break;case"generate-markdown":ri();break;case"publish":ee("preview");break}},[t,x,b,ri]),$n=w.useCallback(ne=>{var et;const be=(et=ne.target.files)==null?void 0:et[0];if(!be)return;ie.current=!0,Ie(null),Ye(null);const Ce=py(be);if(Ce){He(null),st(Gt=>(Gt&&URL.revokeObjectURL(Gt),null)),ct.current&&(ct.current.value=""),nt(Ce),Ge("invalid");return}He(be),st(Gt=>(Gt&&URL.revokeObjectURL(Gt),URL.createObjectURL(be))),nt(null),Ge("selected")},[]),ar=w.useCallback(async ne=>{var Ce;const be=(Ce=ne.target.files)==null?void 0:Ce[0];if(Ai.current&&(Ai.current.value=""),!(!be||!e)){ie.current=!0,Ie(null),ce(!0),nt(null);try{let et;try{et=await Yu(be)}catch(xr){He(null),st(Zi=>(Zi&&URL.revokeObjectURL(Zi),null)),nt(xr instanceof Error?xr.message:"Could not import image");return}const Gt=et.type==="image/jpeg"?"jpg":"webp",Mi=new File([et],`cover.${Gt}`,{type:et.type}),Wn=new FormData;Wn.append("file",Mi);const or=await i(`/api/stories/${e}/import-cover`,{method:"POST",body:Wn});if(!or.ok){const xr=await or.json().catch(()=>({}));nt(xr.error||"Cover import failed");return}He(Mi),st(xr=>(xr&&URL.revokeObjectURL(xr),URL.createObjectURL(Mi))),Ye(null),Ge("selected"),nt(null)}catch{nt("Cover import failed")}finally{ce(!1)}}},[e,i]),Vi=w.useCallback(async ne=>{if(ne.size>1024*1024){Wt("Image exceeds 1MB limit");return}if(!["image/webp","image/jpeg"].includes(ne.type)){Wt("Only WebP and JPEG images are accepted");return}vt(!0),Wt(null);try{const Ce=new FormData;Ce.append("file",ne);const et=await i("/api/publish/upload-plot-image",{method:"POST",body:Ce});if(!et.ok){const Mi=await et.json();throw new Error(Mi.error||"Upload failed")}const Gt=await et.json();Et(Mi=>[...Mi,{cid:Gt.cid,url:Gt.url}])}catch(Ce){Wt(Ce instanceof Error?Ce.message:"Upload failed")}finally{vt(!1),Bt.current&&(Bt.current.value="")}},[i]),jt=w.useCallback(ne=>{var Ce;const be=(Ce=ne.target.files)==null?void 0:Ce[0];be&&Vi(be)},[Vi]),Fn=w.useCallback(async()=>{if(N!=null&&N.storylineId){q(!0),nt(null),mt(!1);try{let ne;if(Ct){const Ce=new FormData;Ce.append("file",Ct);const et=await i("/api/publish/upload-cover",{method:"POST",body:Ce});if(!et.ok){const Mi=await et.json();throw new Error(Mi.error||"Cover upload failed")}ne=(await et.json()).cid}const be=await i("/api/publish/update-storyline",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storylineId:N.storylineId,...ne!==void 0&&{coverCid:ne},genre:Fe,language:Ot,isNsfw:zt})});if(!be.ok){const Ce=await be.json();throw new Error(Ce.error||"Update failed")}mt(!0),He(null),ne!==void 0&&(Ke(!0),st(Ce=>(Ce&&URL.revokeObjectURL(Ce),null)),Ge("unknown"),ct.current&&(ct.current.value="")),setTimeout(()=>mt(!1),3e3)}catch(ne){nt(ne instanceof Error?ne.message:"Update failed")}finally{q(!1)}}},[N==null?void 0:N.storylineId,Ct,Fe,Ot,zt,i]);w.useEffect(()=>{Te(!1),He(null),st(null),nt(null),mt(!1),De(!1),ze(!1),Et([]),Wt(null),Ie(null),Ye(null),Ge("unknown"),ie.current=!1,ae("text")},[e,t]),w.useEffect(()=>{if(t!=="genesis.md"||!e||!N||N.storylineId||N.status==="published"||N.status==="published-not-indexed"||ie.current)return;let ne=!1;return(async()=>{try{const be=await i(`/api/stories/${e}/cover-asset`);if(ne||!be.ok)return;const Ce=await be.json();if(ne)return;if(!(Ce!=null&&Ce.found)){Ge("none");return}if(!Ce.valid){Ye(Ce.error||"Detected cover asset is invalid and was not used"),Ge("invalid");return}const et=await i(`/api/stories/${e}/asset/${Ce.path.replace(/^assets\//,"")}`);if(ne||!et.ok)return;const Gt=await et.blob(),Mi=new File([Gt],Ce.path.split("/").pop()||"cover.webp",{type:Ce.type});if(py(Mi)||ne||ie.current)return;He(Mi),st(Wn=>(Wn&&URL.revokeObjectURL(Wn),URL.createObjectURL(Mi))),Ie(Ce.path),Ge("detected")}catch{}})(),()=>{ne=!0}},[e,t,N,N==null?void 0:N.status,N==null?void 0:N.storylineId,i]),w.useEffect(()=>{if(!me||!(N!=null&&N.storylineId))return;De(!1);const ne="https://plotlink.xyz";let be=!1;return fetch(`${ne}/api/storyline/${N.storylineId}`).then(Ce=>Ce.ok?Ce.json():null).then(Ce=>{if(!be){if(!Ce){nt("Could not load current story metadata");return}if(Ce.genre){const et=Su(Ce.genre);et&&it(et)}if(Ce.language){const et=Jr.find(Gt=>Gt.toLowerCase()===Ce.language.toLowerCase());et&&ui(et)}Ce.isNsfw!==void 0&&At(!!Ce.isNsfw),Ke(!!(Ce.coverCid||Ce.coverUrl||Ce.cover)),De(!0)}}).catch(()=>{be||nt("Could not load current story metadata")}),()=>{be=!0}},[me,N==null?void 0:N.storylineId]),w.useEffect(()=>{if(M!=="edit")return;const ne=be=>{(be.metaKey||be.ctrlKey)&&be.key==="s"&&(be.preventDefault(),ss())};return window.addEventListener("keydown",ne),()=>window.removeEventListener("keydown",ne)},[M,ss]),w.useEffect(()=>{if((N==null?void 0:N.status)!=="published-not-indexed"||!N.publishedAt)return;const ne=new Date(N.publishedAt).getTime(),be=300*1e3,Ce=()=>{const Gt=Math.max(0,be-(Date.now()-ne));ue(Gt)};Ce();const et=setInterval(Ce,1e3);return()=>clearInterval(et)},[N==null?void 0:N.status,N==null?void 0:N.publishedAt]);const ya=k!==null&&k<=0,Dr=k!==null&&k>0?`${Math.floor(k/6e4)}:${String(Math.floor(k%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&&!N)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted",children:"Loading..."});const pr=(M==="edit"?I:(N==null?void 0:N.content)??"").length,Ri=t==="genesis.md",Si=t?/^plot-\d+\.md$/.test(t):!1,Xi=c==="cartoon"&&Si,Tn=c==="cartoon"&&Ri,Br=Tn||Xi,An=(N==null?void 0:N.status)==="published"||(N==null?void 0:N.status)==="published-not-indexed",Sa=S&&Br,vl=Tn?Ki?Ki.total:null:Xi?Me===null?null:We:null,mr=rM({fileName:t??"",contentType:c,hasGenesis:_,isPublished:An,cutCount:vl,cutProgress:Tn?Ki:null}),qo=(Tn||Xi)&&!An,as=qo?ym({fileName:t,fileContent:(N==null?void 0:N.content)??"",storySlug:e??"",structureContent:Pe,contentType:"cartoon",episodeTitle:Ze}):null,wa=!!as&&Lo(as,t),Ca=Xi&&!An&&!vm({fileContent:(N==null?void 0:N.content)??"",episodeTitle:Ze}),qs=Tn&&!An?xm((N==null?void 0:N.content)??""):null,Wo=!!qs&&qs.blockers.length>0,ka="w-full max-w-[32rem] rounded-xl border px-3 py-3",lr={muted:"text-muted",accent:"text-accent",error:"text-error",success:"text-green-700"},Ea=ne=>{if(!Tn)return null;const be=rD({hasSelectedCover:!!Ct,invalid:kt==="invalid",attached:ne});return d.jsxs("div",{className:"flex flex-col gap-0.5","data-testid":"cartoon-cover-status","data-state":be.state,children:[d.jsx("span",{className:`text-[11px] font-medium ${lr[be.tone]}`,children:be.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})]})]})},Ws=wa||Ca,ls=()=>{if(!qo||!as)return null;const ne=Ri?"Story title":"Episode title";return d.jsxs("div",{className:"flex flex-col gap-0.5","data-testid":"publish-title-preview","data-raw":wa?"true":"false","data-blocked":Ws?"true":"false",children:[d.jsxs("span",{className:"text-[11px] text-foreground",children:[d.jsxs("span",{className:"font-medium",children:[ne,":"]})," ",d.jsx("span",{className:Ws?"text-error font-medium":"text-foreground",children:as})]}),wa?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-raw-error",children:["This would publish as a raw filename."," ",Ri?"Add a real “# Title” heading to genesis.md":"Set a title in the cut plan (or add a “# Title” to the episode)"," ","before publishing."]}):Ca?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-episode-required",children:["“",as,"” is a generic placeholder, not a reader-facing title, so it can’t be published. Set a real episode title in the cut plan (or add a “# Title” to the episode) — e.g. “Episode 01 — The Couple Coupon” — before publishing."]}):null]})},os=()=>qs?d.jsxs("div",{className:"flex flex-col gap-1 rounded border border-border bg-surface/50 p-2","data-testid":"cartoon-genesis-readiness","data-blocked":Wo?"true":"false",children:[d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Story opening (Prologue)"}),d.jsx("span",{className:"text-[10px] text-muted","data-testid":"genesis-readiness-hint",children:"Genesis is the first thing readers see. Write it as the story opening/prologue, not a synopsis — set up the premise and stakes, then bridge into Episode 01."}),qs.blockers.map((ne,be)=>d.jsx("span",{className:"text-[10px] text-error","data-testid":"genesis-readiness-blocker",children:ne},`b-${be}`)),qs.warnings.map((ne,be)=>d.jsx("span",{className:"text-[10px] text-amber-600","data-testid":"genesis-readiness-warning",children:ne},`w-${be}`))]}):null,cs=Ri||Si?1e4:null,us=!An&&cs!==null&&pr>cs,Go=(N==null?void 0:N.content)??"",gr=An?{count:0,warnings:[]}:gD(Go),qn=d.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",style:{background:"var(--paper-bg)"},children:[d.jsx("textarea",{ref:yi,value:I,onChange:ne=>{A(ne.target.value),T(!0),se.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:ge?"Unsaved changes":"No changes"}),d.jsx("button",{onClick:ss,disabled:!ge||L,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50 disabled:cursor-not-allowed",children:L?"Saving...":"Save"})]})]});return d.jsxs("div",{className:"h-full flex flex-col",children:[!Sa&&d.jsxs("div",{className:"border-b border-border",children:[d.jsxs("div",{className:"px-3 py-1.5 flex items-center justify-between",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs font-mono text-muted",children:[x&&d.jsx("button",{onClick:x,"data-testid":"view-progress-btn",className:"text-accent hover:underline font-sans",title:"Story progress overview",children:"← Progress"}),d.jsxs("span",{children:[e,"/",t]}),(N==null?void 0:N.status)==="published"&&d.jsx("span",{className:"text-green-700 font-medium",children:"Published"}),(N==null?void 0:N.status)==="published-not-indexed"&&d.jsx("span",{className:"text-amber-700 font-medium",title:N.indexError,children:"Published (not indexed)"}),(N==null?void 0:N.status)==="pending"&&d.jsx("span",{className:"text-amber-700 font-medium",children:"Pending"})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs("span",{className:`text-xs font-mono ${us?"text-error font-medium":"text-muted"}`,children:[pr.toLocaleString(),cs!==null?`/${cs.toLocaleString()}`:" chars"]}),us&&d.jsxs("span",{className:"text-error text-xs font-medium",children:[(pr-cs).toLocaleString()," over limit"]})]})]}),d.jsxs("div",{className:"flex px-3 gap-1",children:[d.jsx("button",{onClick:()=>ee("preview"),className:`px-3 py-1 text-xs font-medium border-b-2 transition-colors ${M==="preview"?"border-accent text-accent":"border-transparent text-muted hover:text-foreground"}`,children:"Preview"}),d.jsxs("button",{onClick:()=>ee("edit"),className:`px-3 py-1 text-xs font-medium border-b-2 transition-colors ${M==="edit"?"border-accent text-accent":"border-transparent text-muted hover:text-foreground"}`,children:["Edit",ge&&d.jsx("span",{className:"ml-1 text-amber-600",children:"*"})]})]})]}),!Sa&&c==="cartoon"&&e&&t&&d.jsx(eD,{storyName:e,fileName:t,authFetch:i,refreshKey:ei,onAction:Mr,showEmptyState:!0}),M==="preview"?Xi?d.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",style:{background:"var(--paper-bg)"},children:[d.jsxs("div",{className:"flex gap-1 px-3 py-1 border-b border-border",children:[d.jsx("button",{"data-testid":"cartoon-mode-publish",onClick:()=>ye("publish"),className:`px-2 py-0.5 text-[11px] rounded ${fe==="publish"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Publish Preview"}),d.jsx("button",{"data-testid":"cartoon-mode-inspect",onClick:()=>ye("inspect"),className:`px-2 py-0.5 text-[11px] rounded ${fe==="inspect"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Cut Inspector"})]}),d.jsx("div",{className:"flex-1 min-h-0",children:fe==="publish"?d.jsx(oM,{content:(N==null?void 0:N.content)??"",stage:Me}):d.jsx(W3,{storyName:e,fileName:t,authFetch:i,onEditCut:V})})]}):d.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-6 py-4",style:{background:"var(--paper-bg)"},children:N!=null&&N.content?d.jsx("div",{className:"prose max-w-none",children:d.jsx(eS,{remarkPlugins:[iS,ES],rehypePlugins:[[AS,fD]],children:N.content})}):d.jsx("p",{className:"text-muted italic",children:"No content"})}):Xi?d.jsx("div",{className:"flex-1 min-h-[22rem] overflow-hidden",style:{background:"var(--paper-bg)"},children:d.jsx(dy,{storyName:e,fileName:t,authFetch:i,language:h,onCutsChanged:()=>we(ne=>ne+1),focusRequest:W,onFocusHandled:()=>Y(null),onFocusedLetteringModeChange:R,workspaceVisible:j,onWorkspaceVisibleChange:E})}):Tn?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:()=>ae("text"),className:`px-2 py-0.5 text-[11px] rounded ${P==="text"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Opening text"}),d.jsx("button",{"data-testid":"genesis-edit-mode-cuts",onClick:()=>ae("cuts"),className:`px-2 py-0.5 text-[11px] rounded ${P==="cuts"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Cuts"})]}),d.jsx("div",{className:"flex-1 min-h-0",children:P==="cuts"?d.jsx(dy,{storyName:e,fileName:t,authFetch:i,language:h,onCutsChanged:()=>we(ne=>ne+1),focusRequest:W,onFocusHandled:()=>Y(null),onFocusedLetteringModeChange:R,workspaceVisible:j,onWorkspaceVisibleChange:E}):qn})]}):qn,!Sa&&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:mr}):(N==null?void 0:N.status)==="published-not-indexed"?d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:"text-amber-700",children:"Published on-chain but not indexed on PlotLink"}),!ya&&d.jsx("button",{onClick:async()=>{if(!(!e||!t||!N.txHash)){K(!0);try{(await(await i("/api/publish/retry-index",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storyName:e,fileName:t,txHash:N.txHash,content:N.content,storylineId:N.storylineId})})).json()).ok&&(await i(`/api/stories/${e}/${t}/publish-status`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({txHash:N.txHash,storylineId:N.storylineId,contentCid:"",gasCost:""})}),Ht())}catch{}K(!1)}},disabled:D,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50",children:D?"Retrying...":`Retry Index${Dr?` (${Dr})`:""}`}),Si&&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,te,H,xe)},disabled:!!a,"data-testid":"retry-publish-btn",className:"px-3 py-1 border border-border text-xs rounded hover:bg-surface disabled:opacity-50",children:a===t?"Publishing...":"Retry Publish"}),N.txHash&&d.jsx("a",{href:`https://basescan.org/tx/${N.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted underline",children:"BaseScan"})]}),d.jsx("p",{className:"text-muted text-xs",children:ya?Si?"Index window expired. Use Retry Publish to create a new on-chain tx.":"Index window expired. Contact support or re-publish manually.":Si?"Try Retry Index first (available for 5 min after publish). If that fails, Retry Publish creates a new on-chain tx.":"Retry Index is available for 5 min after publish."}),N.indexError&&d.jsx("p",{className:"text-error text-xs",children:N.indexError})]}):(N==null?void 0:N.status)==="published"?d.jsxs("div",{className:"flex flex-col gap-2",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:"text-green-700",children:"Published"}),N.storylineId&&d.jsx("a",{href:(()=>{var Ce;const ne=`https://plotlink.xyz/story/${N.storylineId}`;if(!Si)return ne;const be=N.plotIndex!=null&&N.plotIndex>0?N.plotIndex:parseInt(((Ce=t==null?void 0:t.match(/^plot-(\d+)\.md$/))==null?void 0:Ce[1])??"1");return`${ne}/${be}`})(),target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View on PlotLink"}),N.txHash&&d.jsx("a",{href:`https://basescan.org/tx/${N.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted underline",children:"BaseScan"}),Ri&&o&&N.storylineId&&(!N.authorAddress||N.authorAddress.toLowerCase()===o.toLowerCase())&&d.jsx("button",{onClick:()=>Te(ne=>!ne),className:"px-2 py-0.5 border border-border text-xs rounded hover:bg-surface",children:me?"Close Edit":"Edit Story"})]}),me&&Ri&&N.storylineId&&d.jsxs("div",{className:"border border-border rounded p-3 flex flex-col gap-3 bg-surface",children:[d.jsxs("div",{className:"flex flex-col gap-1.5",children:[d.jsx("span",{className:"text-xs font-medium text-foreground",children:"Cover Image"}),Ea(Ee),d.jsxs("div",{className:"flex items-start gap-3",children:[li&&d.jsxs("div",{className:"relative",children:[d.jsx("img",{src:li,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),d.jsx("button",{onClick:()=>{He(null),st(null),Ye(null),Ge("unknown"),ct.current&&(ct.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:ct,type:"file",accept:"image/webp,image/jpeg",onChange:$n,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:Fe,onChange:ne=>it(ne.target.value),className:"px-2 py-1.5 text-xs border border-border rounded bg-surface text-foreground",children:hl.map(ne=>d.jsx("option",{value:ne,children:ne},ne))}),d.jsx("select",{value:Ot,onChange:ne=>ui(ne.target.value),className:"px-2 py-1.5 text-xs border border-border rounded bg-surface text-foreground",children:Jr.map(ne=>d.jsx("option",{value:ne,children:ne},ne))})]}),d.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[d.jsx("input",{type:"checkbox",checked:zt,onChange:ne=>At(ne.target.checked),className:"rounded border-border"}),"This story contains adult content (18+)"]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{onClick:Fn,disabled:_n||!ke,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50",children:_n?"Saving...":ke?"Save Changes":"Loading..."}),qt&&d.jsx("span",{className:"text-green-700 text-xs",children:"Updated!"}),Xe&&d.jsx("span",{className:"text-error text-xs",children:Xe})]})]})]}):d.jsxs("div",{className:"flex flex-col gap-2",children:[Xi&&Qe&&Qe.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:Qe.total})]}),d.jsxs("span",{children:["Clean:"," ",d.jsxs("span",{className:"text-foreground font-medium",children:[Qe.withClean,"/",Qe.needClean]})]}),d.jsxs("span",{children:["Lettered:"," ",d.jsxs("span",{className:"text-foreground font-medium",children:[Qe.withText,"/",Qe.total]})]}),d.jsxs("span",{children:["Uploaded:"," ",d.jsxs("span",{className:"text-foreground font-medium",children:[Qe.uploaded,"/",Qe.total]})]}),x&&d.jsx("button",{onClick:x,className:"ml-auto text-accent hover:underline","data-testid":"status-view-progress",children:"View progress →"})]}),Tn&&Ki&&d.jsxs("div",{className:"text-xs text-muted","data-testid":"genesis-cuts-summary",children:["Episode 1 (Genesis) cuts: ",Ki.total," planned",Ki.total>0&&d.jsxs(d.Fragment,{children:[" ","· ",Ki.withClean," clean ·"," ",Ki.withText," lettered ·"," ",Ki.exported," exported ·"," ",Ki.uploaded," uploaded"]})]}),(Tn||Xi)&&mr&&d.jsxs("div",{className:`${ka} flex flex-col gap-1 border-border bg-surface/50`,"data-testid":"cartoon-not-started",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"rounded-full bg-background px-2 py-0.5 text-[10px] font-medium uppercase tracking-[0.14em] text-muted",children:vl===0?"Not started":"Next step"}),d.jsx("span",{className:"text-xs font-medium text-foreground",children:Tn?"Genesis (Episode 1)":"Future episode"})]}),d.jsx("span",{className:"text-xs text-muted",children:mr})]}),Si&&!Xi&&M==="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:ve,onChange:ne=>ze(ne.target.checked),className:"rounded border-border"}),"Add illustrations in the plot"]}),ve&&d.jsxs("div",{className:"mt-2 flex flex-col gap-2",children:[d.jsxs("div",{className:"border-2 border-dashed border-border rounded p-3 flex flex-col items-center gap-1.5 cursor-pointer hover:border-accent transition-colors",onClick:()=>{var ne;return(ne=Bt.current)==null?void 0:ne.click()},onDragOver:ne=>{ne.preventDefault(),ne.stopPropagation()},onDrop:ne=>{var Ce;ne.preventDefault(),ne.stopPropagation();const be=(Ce=ne.dataTransfer.files)==null?void 0:Ce[0];be&&Vi(be)},children:[d.jsx("input",{ref:Bt,type:"file",accept:"image/webp,image/jpeg",onChange:jt,className:"hidden"}),d.jsx("span",{className:"text-xs text-muted",children:Pt?"Uploading...":"Drop image here or click to browse"}),d.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB"})]}),yt&&d.jsx("span",{className:"text-error text-xs",children:yt}),It.map((ne,be)=>d.jsxs("div",{className:"border border-border rounded p-2 flex flex-col gap-1 bg-surface",children:[d.jsx("span",{className:"text-xs text-green-700",children:"Image uploaded! Copy the markdown below and paste it where you want the illustration to appear in your plot:"}),d.jsxs("div",{className:"flex items-center gap-1.5",children:[d.jsxs("code",{className:"flex-1 text-xs bg-background px-2 py-1 rounded font-mono break-all",children:["![Scene description](",ne.url,")"]}),d.jsx("button",{onClick:()=>{navigator.clipboard.writeText(`![Scene description](${ne.url})`),Rt(be),setTimeout(()=>Rt(null),2e3)},className:"px-2 py-1 text-xs border border-border rounded hover:bg-surface shrink-0",children:Je===be?"Copied!":"Copy"})]})]},ne.cid))]})]}),Ri&&c!=="cartoon"&&!(M==="edit"&&P==="cuts")&&d.jsxs("div",{className:"flex flex-col gap-1.5","data-testid":"prepublish-cover",children:[d.jsxs("span",{className:"text-xs font-medium text-foreground",children:["Cover Image"," ",d.jsx("span",{className:"text-muted font-normal",children:"(optional)"})]}),Ea(!1),d.jsxs("div",{className:"flex items-start gap-3",children:[li&&d.jsxs("div",{className:"relative",children:[d.jsx("img",{src:li,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),d.jsx("button",{onClick:()=>{ie.current=!0,Ie(null),Ye(null),Ge("unknown"),He(null),st(ne=>(ne&&URL.revokeObjectURL(ne),null)),ct.current&&(ct.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:ct,type:"file",accept:"image/webp,image/jpeg",onChange:$n,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:Ai,type:"file",accept:"image/png,image/webp,image/jpeg",onChange:ar,className:"hidden","data-testid":"prepublish-cover-import-input"}),d.jsx("button",{type:"button",onClick:()=>{var ne;return(ne=Ai.current)==null?void 0:ne.click()},disabled:xi,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:xi?"Importing…":"Import generated image (PNG ok)"}),Ct&&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."}),Ne&&d.jsxs("span",{className:"text-accent text-xs","data-testid":"prepublish-cover-detected",children:["Auto-detected generated cover ",Ne," — pick a file to override."]}),rt&&d.jsxs("span",{className:"text-amber-700 text-xs","data-testid":"prepublish-cover-detected-warning",children:[rt," Use “Import generated image” below to convert/compress it, or pick a file."]}),c==="cartoon"&&kt==="none"&&!Ct&&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."]}),Xe&&d.jsx("span",{className:"text-error text-xs","data-testid":"prepublish-cover-error",children:Xe})]})]})]}),!Br&&ls(),!Br&&os(),!Br&&d.jsxs("div",{className:"flex items-center gap-2",children:[Ri&&c!=="cartoon"&&d.jsxs(d.Fragment,{children:[d.jsxs("select",{value:te,"data-testid":"publish-genre-select",onChange:ne=>{G(ne.target.value),ne.target.value&&rs({genre:ne.target.value})},className:`px-2 py-1.5 text-xs border rounded bg-surface text-foreground ${te?"border-border":"border-amber-500"}`,children:[!te&&d.jsx("option",{value:"",disabled:!0,children:"Needs metadata — select genre"}),hl.map(ne=>d.jsx("option",{value:ne,children:ne},ne))]}),d.jsxs("select",{value:H,"data-testid":"publish-language-select",onChange:ne=>{le(ne.target.value),ne.target.value&&rs({language:ne.target.value})},className:`px-2 py-1.5 text-xs border rounded bg-surface text-foreground ${H?"border-border":"border-amber-500"}`,children:[!H&&d.jsx("option",{value:"",disabled:!0,children:"Needs metadata — select language"}),Jr.map(ne=>d.jsx("option",{value:ne,children:ne},ne))]})]}),d.jsx("button",{onClick:async()=>{if(!e||!t)return;if(gr.count>0){const be=`This plot contains ${gr.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(be))return}const ne=Ri?Ct:null;ne?await(s==null?void 0:s(e,t,te,H,xe,ne))&&(ie.current=!0,Ie(null),Ye(null),Ge("unknown"),He(null),st(Ce=>(Ce&&URL.revokeObjectURL(Ce),null)),ct.current&&(ct.current.value="")):s==null||s(e,t,te,H,xe)},disabled:!!a||us||Ws||Wo||Ri&&(!te||!H)||Xi&&Me!=="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"}),Ri&&c==="cartoon"&&(!te||!H)&&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"}),Ri&&c!=="cartoon"&&!te&&d.jsx("span",{className:"text-amber-600 text-xs","data-testid":"genre-needs-metadata",children:"Needs metadata — choose a genre before publishing"}),Ri&&c!=="cartoon"&&te&&!H&&d.jsx("span",{className:"text-amber-600 text-xs","data-testid":"language-needs-metadata",children:"Needs metadata — choose a language before publishing"}),us&&d.jsx("span",{className:"text-error text-xs",children:"Reduce content to publish"}),Xi&&Me==="error"&&d.jsx("span",{className:"text-error text-xs","data-testid":"publish-disabled-reason",children:"Fix the issues below before publishing"}),Xi&&Me==="planning"&&d.jsx("span",{className:"text-muted text-xs","data-testid":"publish-disabled-reason",children:"Prepare the episode for publish to continue"}),Xi&&Me==="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” — ",Ae," of ",We," ","still need an uploaded image"]})]}),Br&&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 →"}),gr.warnings.length>0&&d.jsx("div",{className:"flex flex-col gap-0.5",children:gr.warnings.map((ne,be)=>d.jsx("span",{className:"text-amber-600 text-xs",children:ne},be))}),Ri&&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:xe,onChange:ne=>{Re(ne.target.checked),rs({isNsfw:ne.target.checked})},className:"rounded border-border"}),"This story contains adult content (18+)"]}),xe&&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(bm,{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(bm,{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(TD,{progress:o,storyName:e,onOpenFile:i,onOpenStoryInfo:s}):d.jsx(MD,{progress:o,storyName:e,onOpenFile:i})}function fu({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(fu,{label:"Language",value:e.metadata.language||"Needs metadata",tone:e.metadata.language?"muted":"warn"}),d.jsx(fu,{label:"Genre",value:e.metadata.genre||"Needs metadata",tone:e.metadata.genre?"muted":"warn"}),e.metadata.isNsfw!=null&&d.jsx(fu,{label:"Adult",value:e.metadata.isNsfw?"Yes (18+)":"No"}),t&&d.jsx(fu,{label:"Cover",value:e.cover==="present"?"Ready":e.cover==="invalid"?"Invalid":"Missing",tone:i})]})]})}const XS={published:"✓",done:"●",current:"◉","needs-action":"●","not-started":"○"},Lu={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 ${Lu[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 ${Lu[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 jD={file:"genesis.md",label:"Episode 1 / Genesis",kind:"genesis",title:null,state:"placeholder",summary:"",published:!1,checklist:[],cuts:null};function TD({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,N)=>{E!=="view-progress"&&N&&i(t,N)}}),x=[{label:"Public title",status:a.title?"done":"todo",detail:a.title??null},{label:"Language",status:a.language?"done":"todo",detail:a.language??null},{label:"Genre",status:a.genre?"done":"todo",detail:a.genre??null},{label:"Cover image",status:c?"done":"todo",detail:e.cover==="invalid"?"Invalid — re-import":c?null:"Missing"}],b=f==="story-info"?"current":p?"needs-action":"done",v=o?"done":f==="whitepaper"?"current":"not-started",S=e.episodes.find(E=>E.kind==="genesis")??null,j=e.episodes.filter(E=>E.kind==="plot");let R=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:++R,title:"Define Story Info",status:b,items:x}),d.jsx(gy,{index:++R,title:"Story Whitepaper",status:v,fileName:"structure.md",openFile:o?()=>i(t,"structure.md"):void 0,items:[{label:"Planning document",status:o?"done":"todo",detail:o?null:"Not written yet"}]}),S?d.jsx(Of,{index:++R,ep:S,isActive:f===S.file,storyName:t,onOpenFile:i}):d.jsx(Of,{index:++R,ep:jD,isActive:f==="genesis.md",openingDone:!1,canOpen:!1,storyName:t,onOpenFile:i}),j.map(E=>d.jsx(Of,{index:++R,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 Of({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 ${Lu[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 ${Lu[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,S]=w.useState(""),[j,R]=w.useState(!1),[E,N]=w.useState("cartoon"),[z,J]=w.useState("unknown"),[F,M]=w.useState(!1),[ee,fe]=w.useState(!1),[ye,P]=w.useState(null),[ae,W]=w.useState(!1),[Y,V]=w.useState(null),[I,A]=w.useState(!1),L=w.useRef(null);w.useEffect(()=>{let k=!1;return a(!0),c(!1),fe(!1),P(null),(async()=>{try{const[ue,te]=await Promise.all([t(`/api/stories/${e}`),t(`/api/stories/${e}/progress`)]);if(!ue.ok){k||(c(!0),a(!1));return}const G=await ue.json(),H=te.ok?await te.json().catch(()=>null):null;if(k)return;p(G.title??""),_(G.description??""),b(Su(G.genre)??""),S(G.language&&Jr.find(le=>le.toLowerCase()===G.language.toLowerCase())||""),R(!!G.isNsfw),N(G.contentType==="fiction"?"fiction":"cartoon"),J((H==null?void 0:H.cover)??"unknown"),a(!1)}catch{k||(c(!0),a(!1))}})(),()=>{k=!0}},[e,t]);const U=w.useCallback(async()=>{M(!0),fe(!1),P(null);const k={title:h.trim(),description:f.trim(),genre:x,language:v,isNsfw:j};try{const ue=await t(`/api/stories/${e}/publish-metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(k)});if(ue.ok)fe(!0),i==null||i({genre:x,language:v,isNsfw:j});else{const te=await ue.json().catch(()=>({}));P(te.error||"Could not save story info.")}}catch{P("Could not save story info.")}M(!1)},[e,t,h,f,x,v,j,i]),ge=w.useCallback(async k=>{var te;const ue=(te=k.target.files)==null?void 0:te[0];if(L.current&&(L.current.value=""),!!ue){W(!0),P(null);try{let G;try{G=await Yu(ue)}catch(Me){P(Me instanceof Error?Me.message:"Could not import image");return}const H=G.type==="image/jpeg"?"jpg":"webp",le=new File([G],`cover.${H}`,{type:G.type}),xe=new FormData;xe.append("file",le);const Re=await t(`/api/stories/${e}/import-cover`,{method:"POST",body:xe});if(!Re.ok){const Me=await Re.json().catch(()=>({}));P(Me.error||"Cover import failed.");return}J("present"),V(Me=>(Me&&URL.revokeObjectURL(Me),URL.createObjectURL(le)))}catch{P("Cover import failed.")}finally{W(!1)}}},[e,t]),T=w.useCallback(()=>{var ue;const k=`Generate a cover image for this story (${h||e}) and save it as assets/cover.webp — portrait 600x900, WebP, under 1MB. Don't publish.`;(ue=navigator.clipboard)==null||ue.writeText(k).then(()=>{A(!0)}).catch(()=>{})},[h,e]);if(s)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"story-info-loading",children:"Loading story info…"});if(o)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load story info."});const D=z==="present"?"Cover set":z==="invalid"?"Invalid cover — re-import a WebP/JPEG under 1MB":"Missing cover",K=z==="present"?"text-green-700":z==="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:k=>{p(k.target.value),fe(!1)},"data-testid":"story-info-title",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none"})]}),d.jsxs("label",{className:"flex flex-col gap-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Short description"}),d.jsx("textarea",{value:f,onChange:k=>{_(k.target.value),fe(!1)},rows:3,"data-testid":"story-info-description",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none resize-y"})]}),d.jsxs("div",{className:"flex flex-wrap gap-4",children:[d.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Genre"}),d.jsxs("select",{value:x,onChange:k=>{b(k.target.value),fe(!1)},"data-testid":"story-info-genre",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none",children:[d.jsx("option",{value:"",children:"Needs metadata"}),hl.map(k=>d.jsx("option",{value:k,children:k},k))]})]}),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:k=>{S(k.target.value),fe(!1)},"data-testid":"story-info-language",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none",children:[d.jsx("option",{value:"",children:"Needs metadata"}),Jr.map(k=>d.jsx("option",{value:k,children:k},k))]})]}),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 ${K}`,"data-testid":"story-info-cover-status",children:D}),d.jsx("span",{className:"text-[10px] text-muted",children:"WebP or JPEG, max 1MB, 600×900 recommended."}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{type:"button",onClick:()=>{var k;return(k=L.current)==null?void 0:k.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:L,type:"file",accept:"image/*",onChange:ge,className:"hidden"})]})]})]}),d.jsxs("label",{className:"flex items-center gap-2",children:[d.jsx("input",{type:"checkbox",checked:j,onChange:k=>{R(k.target.checked),fe(!1)},"data-testid":"story-info-nsfw"}),d.jsx("span",{className:"text-xs text-foreground",children:"This story contains adult content (18+)"})]}),d.jsxs("div",{className:"flex items-center gap-3",children:[d.jsx("button",{type:"button",onClick:U,disabled:F,"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:F?"Saving…":"Save Story Info"}),ee&&d.jsx("span",{className:"text-[11px] text-green-700","data-testid":"story-info-saved",children:"Saved"}),ye&&d.jsx("span",{className:"text-[11px] text-error","data-testid":"story-info-error",children:ye})]})]})]})}function 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 Qe,Ft;const[_,x]=w.useState(null),[b,v]=w.useState(!0),[S,j]=w.useState(!1),[R,E]=w.useState(null),[N,z]=w.useState(null),[J,F]=w.useState(null),[M,ee]=w.useState(null),[fe,ye]=w.useState(null),P=async()=>{try{const Pe=await t(`/api/stories/${e}/cover-asset`),ft=Pe.ok?await Pe.json():null;if(!(ft!=null&&ft.found)||!ft.valid||!ft.path)return null;const Ze=await t(`/api/stories/${e}/asset/${String(ft.path).replace(/^assets\//,"")}`);if(!Ze.ok)return null;const pt=await Ze.blob();return new File([pt],String(ft.path).split("/").pop()||"cover.webp",{type:ft.type||pt.type})}catch{return null}};w.useEffect(()=>{let Pe=!1;return(async()=>{v(!0),j(!1);try{const Ze=await t(`/api/stories/${e}/progress`),pt=Ze.ok?await Ze.json():null;if(Pe)return;!pt||!Array.isArray(pt.episodes)?(j(!0),x(null)):x(pt),v(!1)}catch{Pe||(j(!0),x(null),v(!1))}})(),()=>{Pe=!0}},[e,t,f]);const ae=((Ft=(Qe=_==null?void 0:_.episodes)==null?void 0:Qe.find(Pe=>!Pe.published))==null?void 0:Ft.file)??null,W=ae==="genesis.md",Y=JSON.stringify([ae??"",f]),[V,I]=w.useState(null);if(V!==Y&&(I(Y),z(null),F(null),ee(null),ye(null)),w.useEffect(()=>{if(!ae)return;let Pe=!1;const ft=ae.replace(/\.md$/,"");return(async()=>{var Ze;try{const pt=[t(`/api/stories/${e}/${ae}`),t(`/api/stories/${e}/cuts/${ft}`)];W&&pt.push(t(`/api/stories/${e}/structure.md`));const[ei,we,yi]=await Promise.all(pt);if(Pe)return;if(z(ei.ok?(await ei.json()).content??"":""),we.ok){const se=await we.json();if(Pe)return;F(Array.isArray(se.cuts)?se.cuts:[]),ee(typeof se.title=="string"?se.title:null)}else F(null),ee(null);ye(W&&yi&&yi.ok?((Ze=await yi.json())==null?void 0:Ze.content)??null:null)}catch{Pe||(z(""),F(null),ee(null),ye(null))}})(),()=>{Pe=!0}},[ae,W,e,t,f]),b)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"publish-page-loading",children:"Loading publish readiness…"});if(S||!_)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load publish readiness."});const A=_.episodes.find(Pe=>!Pe.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 L=A.cuts,U=_.cover==="present",ge=[{label:"Opening text ready",status:"done"},{label:"Cut plan",status:L&&L.total>0?"done":"todo",detail:L?`${L.total} cut${L.total===1?"":"s"} planned`:"not started"},{label:"Clean images converted",status:L&&L.needClean>0&&L.withClean===L.needClean?"done":"todo",detail:L?`${L.withClean} / ${L.needClean}`:null},{label:"Cuts lettered",status:L&&L.total>0&&L.withText===L.total?"done":"todo",detail:L?`${L.withText} / ${L.total}`:null},{label:"Final images exported",status:L&&L.total>0&&L.exported===L.total?"done":"todo",detail:L?`${L.exported} / ${L.total}`:null},{label:"Final images uploaded",status:L&&L.total>0&&L.uploaded===L.total?"done":"todo",detail:L?`${L.uploaded} / ${L.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",D=A.state==="blocked",K=A.file==="genesis.md",k=!K||!!c&&!!h,ue=!!o&&o===A.file,te=N!==null,G=te?ym({fileName:A.file,fileContent:N??"",storySlug:e,structureContent:fe,contentType:"cartoon",episodeTitle:M}):null,H=!!G&&Lo(G,A.file),le=!K&&te&&!vm({fileContent:N??"",episodeTitle:M}),xe=H||le,Re=K&&te?xm(N??""):null,Me=!!Re&&Re.blockers.length>0,Le=!K&&te&&J!==null?HS(N??"",J):null,Ae=Le&&Le.stage==="error"?Le.issues:[],We=T&&k&&(te&&(K||J!==null))&&!xe&&!Me&&!ue&&!!a,bt=async()=>{if(!(!We||!a)){E(null);try{const Pe=K?await P():null;await a(e,A.file,c??"",h??"",!!p,Pe)}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((Pe,ft)=>d.jsxs("li",{className:"flex items-baseline gap-2 text-xs","data-testid":"publish-check","data-status":Pe.status,children:[d.jsx("span",{className:`flex-shrink-0 ${Pe.status==="done"?"text-green-700":"text-muted"}`,"aria-hidden":!0,children:Pe.status==="done"?"✓":"○"}),d.jsx("span",{className:Pe.status==="done"?"text-foreground":"text-muted",children:Pe.label}),Pe.detail&&d.jsxs("span",{className:"text-muted",children:["· ",Pe.detail]})]},ft))}),G&&d.jsxs("div",{className:"mt-4 flex flex-col gap-0.5 max-w-xl","data-testid":"publish-title-preview","data-raw":H?"true":"false","data-blocked":xe?"true":"false",children:[d.jsxs("span",{className:"text-[11px] text-foreground",children:[d.jsxs("span",{className:"font-medium",children:[K?"Story title":"Episode title",":"]})," ",d.jsx("span",{className:xe?"text-error font-medium":"text-foreground",children:G})]}),H?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-raw-error",children:["This would publish as a raw filename. ",K?"Add a real “# Title” heading to genesis.md":"Set a title in the cut plan (or add a “# Title” to the episode)"," before publishing."]}):le?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-episode-required",children:["“",G,"” 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]}),Re&&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":Me?"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."}),Re.blockers.map((Pe,ft)=>d.jsx("span",{className:"text-[10px] text-error","data-testid":"genesis-readiness-blocker",children:Pe},`b-${ft}`)),Re.warnings.map((Pe,ft)=>d.jsx("span",{className:"text-[10px] text-amber-600","data-testid":"genesis-readiness-warning",children:Pe},`w-${ft}`))]}),Ae.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(Ae).map(Pe=>d.jsx("div",{className:"rounded-lg border border-error/15 bg-background/70 px-2.5 py-2","data-testid":`cartoon-issue-group-${Pe.key}`,children:d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:Pe.title})},Pe.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:Ae.map((Pe,ft)=>d.jsx("li",{className:"font-mono break-words",children:Pe},ft))})]})]}),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)"}),K&&!k&&d.jsx("button",{onClick:s,"data-testid":"publish-set-metadata",className:"self-start rounded border border-border px-3 py-1.5 text-xs text-foreground hover:border-accent hover:text-accent transition-colors",children:"Set genre & language (Story Info)"}),!T&&d.jsxs("button",{onClick:()=>i(e,A.file),"data-testid":"publish-open-episode",className:"self-start rounded border border-accent/40 px-3 py-1.5 text-xs text-accent hover:bg-accent/5 transition-colors",children:["Open ",A.label," to finish ",D?"and fix issues":"(letter / export / upload)"]}),d.jsx("button",{onClick:bt,disabled:!We,"data-testid":"publish-cta",className:"self-start rounded bg-accent px-3 py-1.5 text-xs font-medium text-white hover:bg-accent-dim disabled:opacity-50 transition-colors",title:We?void 0:"Finish the remaining steps above first",children:ue?"Publishing…":`Publish ${A.label} to PlotLink`}),T?k?xe||Me?d.jsx("p",{className:"text-[11px] text-error","data-testid":"publish-title-blocked-reason",children:Me?"Fix the Story opening issues above before publishing.":"Set a real reader-facing title above before publishing."}):null:d.jsx("p",{className:"text-[11px] text-amber-700","data-testid":"publish-needs-metadata",children:"Set the genre and language in Story Info before publishing."}):d.jsx("p",{className:"text-[11px] text-muted","data-testid":"publish-blocked-reason",children:D?`Not publishable yet — ${A.summary.toLowerCase()}. Open the episode to fix the flagged cuts.`:`Not ready yet — ${A.summary.toLowerCase()}.`}),R&&d.jsx("p",{className:"text-[11px] text-error","data-testid":"publish-error",children:R})]}),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?Lo(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?Lo(a,t)||zp(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,zf=224,Pf=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(""),[S,j]=w.useState(null),[R,E]=w.useState(null),[N,z]=w.useState($D),[J,F]=w.useState([]),[M,ee]=w.useState(!1),[fe,ye]=w.useState(""),[P,ae]=w.useState(""),[W,Y]=w.useState(""),[V,I]=w.useState("English"),[A,L]=w.useState("normal"),[U,ge]=w.useState("claude"),[T,D]=w.useState(null),[K,k]=w.useState(!1),[ue,te]=w.useState({}),[G,H]=w.useState({}),[le,xe]=w.useState(new Set),[Re,Me]=w.useState(new Set),[Le,Ae]=w.useState({}),[ut,We]=w.useState({}),[bt,Qe]=w.useState({}),[Ft,Pe]=w.useState({}),[ft,Ze]=w.useState({}),[pt,ei]=w.useState({}),[we,yi]=w.useState(!1),[se,me]=w.useState(!0),Te=w.useRef(new Map),Fe=w.useRef(new Map),it=w.useRef(new Map),Ot=w.useRef(new Map),ui=w.useRef(new Set),zt=w.useRef(null),At=w.useRef(null),Ct=w.useRef(!1);w.useEffect(()=>{t("/api/wallet").then(ie=>ie.ok?ie.json():null).then(ie=>{ie!=null&&ie.address&&E(ie.address)}).catch(()=>{})},[t]),w.useEffect(()=>{t("/api/agent/readiness").then(ie=>ie.ok?ie.json():null).then(ie=>{ie&&D(ie)}).catch(()=>{})},[t]),w.useEffect(()=>{try{localStorage.setItem(JS,String(N))}catch{}},[N]),w.useEffect(()=>{const ie=()=>{if(!At.current)return;const ve=At.current.getBoundingClientRect().width-zf-Pf;z(ze=>vy(ze,ve))};return window.addEventListener("resize",ie),ie(),()=>window.removeEventListener("resize",ie)},[]);const He=w.useCallback(()=>{ye(""),ae(""),Y(""),L("normal"),ge("claude"),ee(!0)},[]),li=w.useCallback(async(ie,ve,ze,Pt)=>{const vt=fe.trim();if(!vt)return;const yt=ie==="cartoon"?"codex":Pt;try{const Wt=await t("/api/stories/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:vt,description:P.trim()||void 0,language:ve,genre:W||void 0,contentType:ie,agentMode:ze,agentProvider:yt})});if(!Wt.ok)return;const It=await Wt.json();ee(!1),Ae(Et=>({...Et,[It.name]:ie})),We(Et=>({...Et,[It.name]:ve})),W&&Qe(Et=>({...Et,[It.name]:W})),H(Et=>({...Et,[It.name]:yt})),ze==="bypass"&&te(Et=>({...Et,[It.name]:!0})),s(It.name),o(null)}catch{}},[t,fe,P,W]);w.useEffect(()=>{if(J.length===0)return;const ie=setInterval(async()=>{try{const ve=await t("/api/stories");if(!ve.ok)return;const ze=await ve.json(),Pt=new Set(ze.stories.filter(vt=>vt.name!=="_example").map(vt=>vt.name));for(const vt of Pt)if(!ui.current.has(vt)&&J.length>0){const yt=J[0],Wt=Te.current.get(yt)||"fiction",It=Fe.current.get(yt)||"English",Et=it.current.get(yt)||"normal",Je=Ot.current.get(yt)||"claude";let Rt=!1;zt.current&&(Rt=await zt.current(yt,vt,{contentType:Wt,language:It,agentMode:Et,agentProvider:Je}).catch(()=>!1)),Rt&&(F(Bt=>Bt.slice(1)),Te.current.delete(yt),Fe.current.delete(yt),it.current.delete(yt),Ot.current.delete(yt),Et==="bypass"&&te(Bt=>{const hi={...Bt,[vt]:!0};return delete hi[yt],hi}),H(Bt=>{const hi={...Bt,[vt]:Je};return delete hi[yt],hi}),t(`/api/stories/${vt}/metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentType:Wt,language:It,agentMode:Et,agentProvider:Je})}).catch(()=>{})),s(vt),o(null)}ui.current=Pt}catch{}},3e3);return()=>clearInterval(ie)},[t,J]),w.useEffect(()=>{t("/api/stories").then(ie=>{if(ie.ok)return ie.json()}).then(ie=>{ie!=null&&ie.stories&&(ui.current=new Set(ie.stories.filter(ve=>ve.name!=="_example").map(ve=>ve.name)))}).catch(()=>{})},[t]);const st=w.useCallback((ie,ve)=>{s(ie),o(ve),h(null)},[]),_n=w.useRef(null),q=w.useCallback(async ie=>{var ve,ze,Pt,vt;_n.current=ie,s(ie),o(null),h(null);try{const yt=await t(`/api/stories/${ie}`);if(yt.ok&&_n.current===ie){const Wt=await yt.json();if(Wt.contentType==="cartoon")return;const It=Wt.files||[],Je=((ve=It.map(Rt=>{var Bt;return{file:Rt.file,num:(Bt=Rt.file.match(/^plot-(\d+)\.md$/))==null?void 0:Bt[1]}}).filter(Rt=>Rt.num!=null).sort((Rt,Bt)=>parseInt(Bt.num)-parseInt(Rt.num))[0])==null?void 0:ve.file)??((ze=It.find(Rt=>Rt.file==="genesis.md"))==null?void 0:ze.file)??((Pt=It.find(Rt=>Rt.file==="structure.md"))==null?void 0:Pt.file)??((vt=It[0])==null?void 0:vt.file);Je&&_n.current===ie&&o(Je)}}catch{}},[t]),ke=w.useCallback(ie=>{ie.preventDefault(),Ct.current=!0,document.body.style.cursor="col-resize",document.body.style.userSelect="none";const ve=Pt=>{if(!Ct.current||!At.current)return;const vt=At.current.getBoundingClientRect(),yt=vt.width-zf-Pf,Wt=Pt.clientX-vt.left-zf;z(vy(Wt/yt,yt))},ze=()=>{Ct.current=!1,document.body.style.cursor="",document.body.style.userSelect="",window.removeEventListener("mousemove",ve),window.removeEventListener("mouseup",ze)};window.addEventListener("mousemove",ve),window.addEventListener("mouseup",ze)},[]),De=w.useCallback(async(ie,ve,ze,Pt,vt,yt)=>{var Je;f(ve),v("Reading file..."),j(null);let Wt=!1,It=null,Et=!1;try{const Rt=await t(`/api/stories/${ie}/${ve}`);if(!Rt.ok)throw new Error("Failed to read file");const Bt=await Rt.json(),hi=Le[ie];let Ht=null,Ki=null;if(ve==="genesis.md")try{const ri=await t(`/api/stories/${ie}/structure.md`);ri.ok&&(Ht=(await ri.json()).content??null)}catch{}else if(hi==="cartoon"&&ve.match(/^plot-\d+\.md$/))try{const ri=await t(`/api/stories/${ie}/cuts/${ve.replace(/\.md$/,"")}`);ri.ok&&(Ki=(await ri.json()).title??null)}catch{}const Rr=ym({fileName:ve,fileContent:Bt.content,storySlug:ie,structureContent:Ht,contentType:hi,episodeTitle:Ki});if(hi==="cartoon"&&Lo(Rr,ve))return v(ve==="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(hi==="cartoon"&&ve.match(/^plot-\d+\.md$/)&&!vm({fileContent:Bt.content,episodeTitle:Ki}))return v("Set a real episode title in the cut plan (or add a “# Title” to the episode) before publishing — a generic “Episode NN” placeholder can’t be published."),setTimeout(()=>{f(null),v("")},6e3),!1;if(hi==="cartoon"&&ve==="genesis.md"){const ri=xm(Bt.content).blockers;if(ri.length>0)return v(`Genesis is the reader-facing Story opening — fix it before publishing: ${ri[0]}`),setTimeout(()=>{f(null),v("")},6e3),!1}let an;if(ve.match(/^plot-\d+\.md$/)){if(cD(Bt)){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 ri=await t(`/api/stories/${ie}`);if(ri.ok){const $n=(await ri.json()).files.find(ar=>ar.file==="genesis.md"&&ar.storylineId);an=$n==null?void 0:$n.storylineId}}catch{}if(!an)return v("Error: Publish genesis first to create the storyline"),setTimeout(()=>{f(null),v("")},3e3),!1}v("Checking wallet balance...");try{const ri=await t("/api/publish/preflight");if(ri.ok){const Mr=await ri.json();if(hD(Mr))return j(dD(Mr)),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:ie,fileName:ve,title:Rr,content:Bt.content,genre:ze,language:Pt,isNsfw:vt,storylineId:an,...my(Le,ie,an)?{contentType:my(Le,ie,an)}:{}})});if(!jn.ok){const ri=await jn.json();throw new Error(ri.error||"Publish failed")}const rs=(Je=jn.body)==null?void 0:Je.getReader(),ss=new TextDecoder;if(rs)for(;;){const{done:ri,value:Mr}=await rs.read();if(ri)break;const ar=ss.decode(Mr).split(` -`).filter(Vi=>Vi.startsWith("data: "));for(const Vi of ar)try{const jt=JSON.parse(Vi.slice(6));if(jt.step&&v(jt.message||jt.step),jt.step==="done"&&jt.txHash){if(Et=!0,await t(`/api/stories/${ie}/${ve}/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:R})}),x(Fn=>Fn+1),yt&&ve==="genesis.md"&&jt.storylineId){v("Uploading cover...");let Fn=null;try{Fn=await sD(t,jt.storylineId,yt)}catch{}Fn||(Wt=!0)}if(hi==="cartoon"&&jt.storylineId)try{const Fn=ve!=="genesis.md",ya=`storylineId=${jt.storylineId}`+(Fn&&jt.plotIndex!=null?`&plotIndex=${jt.plotIndex}`:""),Dr=await t(`/api/publish/public-title?${ya}`);if(Dr.ok){const Fs=await Dr.json(),pr=Fn?{plots:Fs.plotTitle!=null?[{plotIndex:jt.plotIndex,title:Fs.plotTitle}]:[]}:{title:Fs.storylineTitle},Ri=ID({fileName:ve,detail:pr,plotIndex:jt.plotIndex});Ri.ok||(It=HD(Ri))}}catch{}}}catch{}}It&&j(It),v(Wt?"Published, but cover upload failed — set it later from Edit Story.":"Published!")}catch(Rt){const Bt=Rt instanceof Error?Rt.message:"Publish failed";v(`Error: ${Bt}`)}finally{setTimeout(()=>{f(null),v("")},3e3)}return Et&&!Wt},[t,Le,R]),Ee=w.useCallback(ie=>{ie.startsWith("_new_")&&(F(ve=>ve.filter(ze=>ze!==ie)),Te.current.delete(ie),Fe.current.delete(ie),it.current.delete(ie),Ot.current.delete(ie),te(ve=>{if(!(ie in ve))return ve;const ze={...ve};return delete ze[ie],ze}),H(ve=>{if(!(ie in ve))return ve;const ze={...ve};return delete ze[ie],ze}))},[]);w.useEffect(()=>{const ie=ze=>{xe(new Set(ze.filter(Je=>Je.hasStructure).map(Je=>Je.name))),Me(new Set(ze.filter(Je=>Je.hasGenesis).map(Je=>Je.name)));const Pt={},vt={},yt={},Wt={},It={},Et={};for(const Je of ze)Pt[Je.name]=Je.contentType||"fiction",vt[Je.name]=Je.language,yt[Je.name]=Je.genre,Wt[Je.name]=Je.isNsfw,It[Je.name]=Je.agentProvider,Je.title&&(Et[Je.name]=Je.title);Ae(Pt),We(vt),Qe(yt),Pe(Wt),ei(It),Ze(Et)};t("/api/stories").then(ze=>ze.ok?ze.json():null).then(ze=>{ze!=null&&ze.stories&&ie(ze.stories)}).catch(()=>{});const ve=setInterval(async()=>{try{const ze=await t("/api/stories");if(ze.ok){const Pt=await ze.json();ie(Pt.stories)}}catch{}},5e3);return()=>clearInterval(ve)},[t]);const Ke=!!T&&T.codex.installed&&T.codex.imageGeneration==="enabled",Xe=!!T&&!Ke,nt=w.useCallback(async()=>{try{await navigator.clipboard.writeText("codex features enable image_generation"),k(!0),setTimeout(()=>k(!1),2e3)}catch{}},[]),qt=w.useCallback(async()=>{if(!i||i.startsWith("_new_"))return;const ie=i;if((await t(`/api/stories/${ie}/metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentType:"cartoon",agentProvider:"codex"})})).ok){ei(ze=>({...ze,[ie]:"codex"})),H(ze=>({...ze,[ie]:"codex"}));try{const ze=await t("/api/stories");if(ze.ok){const Pt=await ze.json();if(Pt!=null&&Pt.stories){const vt={};for(const yt of Pt.stories)vt[yt.name]=yt.agentProvider;ei(vt)}}}catch{}}},[t,i]),mt=w.useCallback(ie=>{i===ie&&(s(null),o(null))},[i]),ct=i?G[i]??pt[i]:void 0,Ai=Bf(i,Le,Te.current),xi=uD(Ai,ct,i),ce=!!i&&Ai==="cartoon",Ne=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",Ie=w.useCallback(ie=>{const ve=i;if(ve)switch(ie){case"progress":h(null),o(null);break;case"story-info":h("story-info");break;case"episodes":h("episodes");break;case"whitepaper":st(ve,"structure.md");break;case"genesis":st(ve,"genesis.md");break;case"publish":h("publish");break}},[i,st]),rt=w.useCallback((ie,ve)=>{const ze=i;if(ze)switch(ie){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":ve&&st(ze,ve);break}},[i,st]),Ye=w.useCallback(ie=>{i&&(ie.genre!==void 0&&Qe(ve=>({...ve,[i]:ie.genre||void 0})),ie.language!==void 0&&We(ve=>({...ve,[i]:ie.language||void 0})),ie.isNsfw!==void 0&&Pe(ve=>({...ve,[i]:ie.isNsfw})))},[i]),kt=w.useCallback(ie=>{yi(ie),me(!ie)},[]),Ge=we&&!se;return d.jsxs("div",{ref:At,className:"h-[calc(100vh-3.5rem)] flex","data-testid":Ge?"stories-focused-lettering-mode":"stories-default-layout",children:[!Ge&&d.jsx("div",{className:"w-56 border-r border-border flex-shrink-0",children:d.jsx(yC,{authFetch:t,selectedStory:i,selectedFile:a,onSelectFile:st,onNewStory:He,untitledSessions:J})}),!Ge&&d.jsx("div",{className:"min-w-0 border-r border-border",style:{flex:`${N} 0 0`},children:d.jsx(YE,{token:e,storyName:i,authFetch:t,onSelectStory:q,onDestroySession:Ee,onArchiveStory:mt,confirmedStories:le,renameRef:zt,bypassStories:ue,agentProviders:G,readiness:T,contentType:Bf(i,Le,Te.current),needsProviderRepair:xi,onRepairProvider:qt})}),!Ge&&d.jsx("div",{onMouseDown:ke,className:"flex-shrink-0 flex items-center justify-center hover:bg-border/50 transition-colors",style:{width:Pf,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:Ge?{flex:"1 0 0"}:{flex:`${1-N} 0 0`},children:[!we&&ce&&i&&d.jsx(BD,{storyTitle:ft[i]||i,active:Ne,onSelect:Ie}),!we&&ce&&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:rt,onOpenStoryInfo:()=>h("story-info")})}),ce&&c==="story-info"&&i?d.jsx(LD,{storyName:i,authFetch:t,onSaved:Ye}):ce&&c==="episodes"&&i?d.jsx(OD,{storyName:i,authFetch:t,onOpenFile:st}):ce&&c==="publish"&&i?d.jsx(zD,{storyName:i,authFetch:t,onOpenFile:st,onOpenStoryInfo:()=>h("story-info"),onPublish:De,publishingFile:p,genre:bt[i],language:ut[i],isNsfw:Ft[i],refreshKey:_}):i&&!a?d.jsx(SD,{storyName:i,authFetch:t,onOpenFile:st,onOpenStoryInfo:()=>h("story-info")}):d.jsx(xD,{storyName:i,fileName:a,authFetch:t,onPublish:De,publishingFile:p,walletAddress:R,contentType:Bf(i,Le,Te.current)||"fiction",language:i?ut[i]:void 0,genre:i?bt[i]:void 0,isNsfw:i?Ft[i]:void 0,hasGenesis:i?Re.has(i):!1,onViewProgress:()=>o(null),onOpenFile:ie=>i&&st(i,ie),onViewPublish:()=>h("publish"),focusedLetteringMode:we,focusedLetteringWorkspaceVisible:se,onFocusedLetteringModeChange:kt,onFocusedLetteringWorkspaceVisibleChange:me}),b&&d.jsx("div",{className:"px-3 py-1.5 bg-surface border-t border-border text-xs text-muted",children:b}),S&&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:S}),d.jsx("button",{type:"button",onClick:()=>j(null),className:"shrink-0 text-error/70 hover:text-error underline","data-testid":"publish-block-error-dismiss",children:"Dismiss"})]})]}),M&&d.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"bg-surface border border-border rounded-lg shadow-lg p-6 max-w-sm w-full space-y-4",children:[d.jsx("h3",{className:"text-sm font-serif font-medium text-foreground text-center",children:"New Story"}),d.jsxs("label",{className:"block space-y-1",children:[d.jsxs("span",{className:"text-[10px] font-medium text-muted",children:["Title ",d.jsx("span",{className:"text-accent",children:"*"})]}),d.jsx("input",{type:"text",value:fe,onChange:ie=>ye(ie.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:ie=>ae(ie.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:W,onChange:ie=>Y(ie.target.value),"data-testid":"new-story-genre",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none",children:[d.jsx("option",{value:"",children:"— Select later —"}),hl.map(ie=>d.jsx("option",{value:ie,children:ie},ie))]})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Language"}),d.jsx("select",{value:V,onChange:ie=>I(ie.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:Jr.map(ie=>d.jsx("option",{value:ie,children:ie},ie))})]}),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:ie=>L(ie.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:ie=>ge(ie.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"}),!fe.trim()&&d.jsx("p",{className:"text-[10px] text-amber-700 text-center","data-testid":"new-story-title-required",children:"Enter a title to create your story."}),d.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[d.jsxs("button",{onClick:()=>li("fiction",V,A,U),disabled:!fe.trim(),"data-testid":"create-fiction",className:"border border-border rounded-lg p-4 hover:border-accent hover:bg-accent/5 transition-colors text-center space-y-1 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:border-border disabled:hover:bg-transparent",children:[d.jsx("p",{className:"text-sm font-serif font-medium text-foreground",children:"Fiction"}),d.jsx("p",{className:"text-[11px] text-muted",children:"Novels, short stories, poetry"})]}),d.jsxs("div",{className:"space-y-1",children:[d.jsxs("button",{onClick:()=>li("cartoon",V,A,"codex"),disabled:Xe||!fe.trim(),"data-testid":"create-cartoon",className:"w-full border border-border rounded-lg p-4 hover:border-accent hover:bg-accent/5 transition-colors text-center space-y-1 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:border-border disabled:hover:bg-transparent",children:[d.jsx("p",{className:"text-sm font-serif font-medium text-foreground",children:"Cartoon"}),d.jsx("p",{className:"text-[11px] text-muted",children:"Comics, manga, webtoons"}),d.jsx("p",{className:"text-[11px] text-muted","data-testid":"cartoon-codex-note",children:"Cartoon mode requires Codex because the clean-image step needs image generation support."})]}),T&&!T.codex.installed&&d.jsxs("p",{className:"text-[11px] text-amber-700 text-left","data-testid":"cartoon-codex-warning",children:["Codex was not detected. Install the Codex CLI and sign in (e.g."," ",d.jsx("span",{className:"font-mono",children:"npm i -g @openai/codex"})," ","then ",d.jsx("span",{className:"font-mono",children:"codex login"}),") to create cartoons."]}),ku(T)&&d.jsx("p",{className:"text-[11px] text-amber-700 text-left","data-testid":"cartoon-codex-auth-unknown",children:Ip}),T&&T.codex.installed&&!ku(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:nt,className:"rounded border border-border px-2 py-1 text-[10px] text-muted hover:border-accent hover:text-accent transition-colors",children:K?"Copied!":"Copy"})]})]})]})]}),d.jsx("button",{onClick:()=>ee(!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(S=>S.name!=="_example").length)}}catch{}}f()},[e]),d.jsxs("div",{className:"flex h-screen flex-col",children:[d.jsxs("header",{className:"border-border flex h-14 items-center justify-between border-b px-4 flex-shrink-0",children:[d.jsxs("div",{className:"flex items-center gap-3",children:[d.jsx("button",{onClick:()=>{i!=="wallet-setup"&&s("home")},className:"flex items-center gap-2 hover:opacity-80",children:d.jsx("span",{className:"text-accent text-sm font-bold tracking-tight",children:"PlotLink OWS"})}),d.jsxs("span",{className:"text-muted text-[10px] uppercase tracking-wider",children:["writer",c?` v${c}`:""]})]}),i!=="wallet-setup"&&d.jsxs("nav",{className:"flex items-center gap-4",children:[d.jsx("button",{onClick:()=>s("stories"),className:`text-xs transition-colors ${i==="stories"?"text-accent":"text-muted hover:text-foreground"}`,children:"stories"}),d.jsx("button",{onClick:()=>s("dashboard"),className:`text-xs transition-colors ${i==="dashboard"?"text-accent":"text-muted hover:text-foreground"}`,children:"dashboard"}),d.jsx("button",{onClick:()=>s("settings"),className:`text-xs transition-colors ${i==="settings"?"text-accent":"text-muted hover:text-foreground"}`,children:"settings"}),d.jsx("button",{onClick:t,className:"text-muted hover:text-foreground text-xs transition-colors",children:"logout"})]})]}),d.jsxs("main",{className:"flex-1 min-h-0",children:[i==="home"&&d.jsxs("div",{className:"mx-auto max-w-lg space-y-6 p-8",children:[d.jsxs("div",{className:"text-center space-y-2",children:[d.jsx("h1",{className:"text-2xl font-serif text-foreground",children:"Write. Publish. Earn."}),d.jsx("p",{className:"text-muted text-sm",children:"Claude or Codex helps create your story. You publish it on-chain."})]}),d.jsxs("div",{className:"text-center space-y-3",children:[d.jsx("button",{onClick:()=>s("stories"),className:"bg-accent text-white hover:bg-accent-dim px-6 py-2.5 rounded text-sm font-medium transition-colors",children:"Start Writing"}),a>0&&d.jsxs("p",{className:"text-muted text-xs",children:[a," ",a===1?"story":"stories"," in progress"]})]}),d.jsxs("div",{className:"rounded border border-border p-4 space-y-2 text-xs text-muted",children:[d.jsx("p",{className:"font-medium text-foreground text-sm",children:"How it works"}),d.jsxs("ol",{className:"space-y-1.5 list-decimal list-inside",children:[d.jsxs("li",{children:["Open the ",d.jsx("strong",{children:"Stories"})," tab — your writing agent launches in the terminal"]}),d.jsx("li",{children:"Tell the agent your story idea — it brainstorms, outlines, and writes"}),d.jsx("li",{children:"Review the live preview as the agent creates files"}),d.jsxs("li",{children:["Click ",d.jsx("strong",{children:"Publish"})," to put your story on-chain"]}),d.jsxs("li",{children:["Earn 5% royalties on every trade at ",d.jsx("a",{href:"https://plotlink.xyz",target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"plotlink.xyz"})]})]}),d.jsx("p",{className:"text-[11px] text-muted",children:"Fiction defaults to Claude; cartoon mode uses Codex for clean-image generation."})]}),d.jsx("div",{className:"text-center",children:d.jsx("a",{href:"https://github.com/realproject7/plotlink-ows#-wallet-setup",target:"_blank",rel:"noopener noreferrer",className:"text-xs text-muted hover:text-accent underline transition-colors",children:"Wallet Setup Guide"})}),d.jsx(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{Lp as M,cu as a,T3 as b,OM as c,R3 as d,ou as l,OS as s,F3 as t,ZD as v}; diff --git a/app/web/dist/index.html b/app/web/dist/index.html index 5bf2dd6..c8a0649 100644 --- a/app/web/dist/index.html +++ b/app/web/dist/index.html @@ -7,7 +7,7 @@ - + From 0cbd41dcaff8daddd373706af58e815481d3f4d0 Mon Sep 17 00:00:00 2001 From: Project7 Date: Sun, 7 Jun 2026 22:12:12 +0000 Subject: [PATCH 2/3] test: fix rebased lettering test expectations --- app/web/components/CutListPanel.test.tsx | 2 +- app/web/components/LetteringEditor.test.tsx | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/app/web/components/CutListPanel.test.tsx b/app/web/components/CutListPanel.test.tsx index 3e5d9b4..08e1ec1 100644 --- a/app/web/components/CutListPanel.test.tsx +++ b/app/web/components/CutListPanel.test.tsx @@ -2098,7 +2098,7 @@ describe("CutListPanel asset diagnostics + Refresh assets (#427)", () => { // card per cut with a creator-facing status + primary action, technical // controls collapsed by default. it("renders an episode header, progress summary, per-cut card statuses, and collapses technical controls", async () => { - const fn = vi.fn((url: string) => { + const fn = vi.fn((url: string, opts?: RequestInit) => { if (url.includes("/asset-diagnostics")) { return Promise.resolve({ ok: true, diff --git a/app/web/components/LetteringEditor.test.tsx b/app/web/components/LetteringEditor.test.tsx index a8e6903..12c367a 100644 --- a/app/web/components/LetteringEditor.test.tsx +++ b/app/web/components/LetteringEditor.test.tsx @@ -588,6 +588,7 @@ describe("LetteringEditor", () => { expect(onSave).toHaveBeenCalledWith( expect.arrayContaining([expect.objectContaining({ type: "speech" })]), + null, ); }); @@ -658,6 +659,7 @@ describe("LetteringEditor", () => { }), }), ]), + null, ); }); From eb1bfbfaea535bf589afb8a1c423f5d2da432670 Mon Sep 17 00:00:00 2001 From: Project7 Date: Sun, 7 Jun 2026 22:15:08 +0000 Subject: [PATCH 3/3] test: fix ai draft cut list mock signature --- app/web/components/CutListPanel.test.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/web/components/CutListPanel.test.tsx b/app/web/components/CutListPanel.test.tsx index 08e1ec1..1ceadbc 100644 --- a/app/web/components/CutListPanel.test.tsx +++ b/app/web/components/CutListPanel.test.tsx @@ -2262,7 +2262,7 @@ describe("CutListPanel asset diagnostics + Refresh assets (#427)", () => { description: "Wide shot", }), ]; - const fn = vi.fn((url: string) => { + const fn = vi.fn((url: string, opts?: RequestInit) => { if (url.includes("/asset-diagnostics")) { return Promise.resolve({ ok: true,