From b732366815bc655ce3d86c1a14e0c8f79acd079f Mon Sep 17 00:00:00 2001 From: Project7 Date: Mon, 8 Jun 2026 02:30:19 +0000 Subject: [PATCH 1/2] Reclaim first-screen space in cut review --- app/web/components/CutListPanel.test.tsx | 22 +- app/web/components/CutListPanel.tsx | 302 ++++++++++-------- ...cut-BeffiHI_.js => export-cut-DvUnFkvP.js} | 2 +- ...{index-B1vSuADc.css => index-Bidn584T.css} | 2 +- .../{index-CuMJdtXy.js => index-uZfLBBm_.js} | 98 +++--- app/web/dist/index.html | 4 +- 6 files changed, 241 insertions(+), 189 deletions(-) rename app/web/dist/assets/{export-cut-BeffiHI_.js => export-cut-DvUnFkvP.js} (98%) rename app/web/dist/assets/{index-B1vSuADc.css => index-Bidn584T.css} (54%) rename app/web/dist/assets/{index-CuMJdtXy.js => index-uZfLBBm_.js} (65%) diff --git a/app/web/components/CutListPanel.test.tsx b/app/web/components/CutListPanel.test.tsx index 3e942b0..a423467 100644 --- a/app/web/components/CutListPanel.test.tsx +++ b/app/web/components/CutListPanel.test.tsx @@ -1861,7 +1861,7 @@ describe("CutListPanel stale bubble-renderer warning (#381)", () => { authFetch={mockAuthFetch({ ok: true, data: cutsData })} />, ); - await screen.findByTestId("cartoon-workflow-help"); + await screen.findByTestId("cut-workspace-tools"); expect( screen.queryByTestId("stale-bubble-export-warning"), ).not.toBeInTheDocument(); @@ -1881,7 +1881,7 @@ describe("CutListPanel stale bubble-renderer warning (#381)", () => { authFetch={mockAuthFetch({ ok: true, data: cutsData })} />, ); - await screen.findByTestId("cartoon-workflow-help"); + await screen.findByTestId("cut-workspace-tools"); expect( screen.queryByTestId("stale-bubble-export-warning"), ).not.toBeInTheDocument(); @@ -2221,15 +2221,15 @@ describe("CutListPanel asset diagnostics + Refresh assets (#427)", () => { "Between-scene lettering", ); - // Technical controls live under a collapsed-by-default Details disclosure. - const advanced = screen.getByTestId("cut-advanced"); - expect(advanced.tagName.toLowerCase()).toBe("details"); - expect(advanced).not.toHaveAttribute("open"); - expect(within(advanced).getByTestId("sync-clean-btn")).toBeInTheDocument(); - const help = screen.getByTestId("cartoon-workflow-help"); - expect(help.tagName.toLowerCase()).toBe("details"); - expect(help).not.toHaveAttribute("open"); - expect(within(help).getByText("Cut workflow help")).toBeInTheDocument(); + // Low-frequency workflow controls are collapsed into one workspace-tools disclosure. + const tools = screen.getByTestId("cut-workspace-tools"); + expect(tools.tagName.toLowerCase()).toBe("details"); + expect(tools).not.toHaveAttribute("open"); + expect(within(tools).getByTestId("sync-clean-btn")).toBeInTheDocument(); + expect(within(tools).getByText(/Workflow: Upload final images/i)).toBeInTheDocument(); + expect( + screen.queryByText(/^Technical details$/i), + ).not.toBeInTheDocument(); expect(screen.getByTestId("finish-episode-details")).not.toHaveAttribute( "open", ); diff --git a/app/web/components/CutListPanel.tsx b/app/web/components/CutListPanel.tsx index b7203cf..5b60456 100644 --- a/app/web/components/CutListPanel.tsx +++ b/app/web/components/CutListPanel.tsx @@ -284,6 +284,7 @@ function CutRow({ onConvert, converting, rowRef, + featured = false, }: { cut: Cut; storyName: string; @@ -307,6 +308,7 @@ function CutRow({ onConvert: (cutId: number, pngPath: string) => Promise; converting: boolean; rowRef?: (el: HTMLDivElement | null) => void; + featured?: boolean; }) { const fileInputRef = useRef(null); const [uploading, setUploading] = useState(false); @@ -444,6 +446,9 @@ function CutRow({ !!cut.narration || cut.dialogue.length > 0 || isTextPanel(cut); + const previewClassName = featured + ? "w-full rounded border border-border bg-white min-h-[14rem] md:min-h-[18rem] xl:min-h-[21rem]" + : "w-full rounded border border-border bg-white min-h-[11rem] md:min-h-[13rem]"; return (
) : (
{isTextPanel(cut) @@ -1548,6 +1553,11 @@ export function CutListPanel({ const canFinish = cutsFile.cuts.some((ct) => ct.finalImagePath && !ct.uploadedCid) || (uploadStepDone && !episodeState.markdownReady); + const workflowLabel = currentWorkflowLabel( + finishChecklist, + episodeState.markdownReady, + episodeState.published, + ); // PNG clean images awaiting conversion (#441): a friendly, batch-able step, not // a red unsupported-extension dump. Built from the disk-validated diagnostics. @@ -1596,6 +1606,7 @@ export function CutListPanel({ !cut.uploadedCid && !cut.uploadedUrl, ).length; + const assetSummary = workspaceAssetSummary(assetDiagnostics); return (
- {/* Lower-level / manual controls, collapsed by default so the board stays - focused on per-cut actions (#440). The guided Finish flow + per-cut - primary actions are the main path; these stay for power users. */}
- - Technical details + +
+
+
+ + Workflow: {workflowLabel} + + {assetSummary && ( + + Assets: {assetSummary} + + )} + {conversionJobs.length > 0 && ( + + Convert {conversionJobs.length} PNG + {conversionJobs.length === 1 ? "" : "s"} + + )} +
+

+ Per-cut actions stay on each card. Open workspace tools for + publish prep, asset recovery, narration cards, and workflow + guidance. +

+
+ + Workspace tools + +
-
+
+
{cutsFile.cuts.length} cuts @@ -1734,18 +1773,7 @@ export function CutListPanel({ > {uploadProgress || "Upload & Prepare for Publish"} -
-
- {/* Plain-language workflow + text-panel explainer (#360) so a non-technical - writer understands the order of operations and what a text panel is. */} -
- - Cut workflow help - -
+
1. Letter @@ -1768,6 +1796,103 @@ export function CutListPanel({ for a narration or title card. It becomes a solid card exported as a final image.
+ {conversionJobs.length > 0 && ( +
+
+ + {conversionJobs.length} PNG image + {conversionJobs.length === 1 ? "" : "s"} found + + +
+

+ PNG artwork is fine while drafting. Convert it before + lettering/export so PlotLink can publish it safely. +

+ {convertResult && ( +

+ {convertResult} +

+ )} + {conversionIssues.length > 0 && ( +
+ + Conversion notes + +
    + {conversionIssues.map((m, i) => ( +
  • {m}
  • + ))} +
+
+ )} +
+ )} + {assetDiagnostics && + assetDiagnostics.length > 0 && + (() => { + const s = summarizeAssetDiagnostics(assetDiagnostics); + const missing = assetDiagnostics.filter( + (d) => d.state === "missing", + ); + return ( +
+ + Assets: {s.uploaded} uploaded · {s.finalReady} final ·{" "} + {s.cleanReady} clean · {s.planned} planned + {s.needsConversion > 0 + ? ` · ${s.needsConversion} needs conversion` + : ""} + {s.missing > 0 ? ` · ${s.missing} missing` : ""} + + {missing.length > 0 && ( +
    + {missing.map((d) => ( +
  • {d.issue}
  • + ))} +
+ )} +
+ ); + })()} +
{/* Stale bubble-renderer warning (#381): a final image lettered before the @@ -1814,109 +1939,6 @@ export function CutListPanel({ {syncResult}
)} - {/* Convert artwork step (#441, spec §8): PNG clean images are a normal - drafting intermediate, surfaced as a friendly batch conversion rather - than red "Unsupported extension" errors. The raw reasons stay available - under a collapsed "Technical details" disclosure. */} - {conversionJobs.length > 0 && ( -
-
- - {conversionJobs.length} PNG image - {conversionJobs.length === 1 ? "" : "s"} found - - -
-

- PNG artwork is fine while drafting. Convert it before - lettering/export so PlotLink can publish it safely. -

- {convertResult && ( -

- {convertResult} -

- )} - {conversionIssues.length > 0 && ( -
- - Technical details - -
    - {conversionIssues.map((m, i) => ( -
  • {m}
  • - ))} -
-
- )} -
- )} - {/* Read-only per-cut asset state validated against disk (#427): a compact - state tally + a precise per-cut reason when a recorded path is broken, - so "files exist but aren't shown" / a typoed path is a clear diagnostic - rather than a generic publish warning. */} - {assetDiagnostics && - assetDiagnostics.length > 0 && - (() => { - const s = summarizeAssetDiagnostics(assetDiagnostics); - const missing = assetDiagnostics.filter((d) => d.state === "missing"); - return ( -
- - Assets: {s.uploaded} uploaded · {s.finalReady} final ·{" "} - {s.cleanReady} clean · {s.planned} planned - {s.needsConversion > 0 - ? ` · ${s.needsConversion} needs conversion` - : ""} - {s.missing > 0 ? ` · ${s.missing} missing` : ""} - - {missing.length > 0 && ( -
    - {missing.map((d) => ( -
  • {d.issue}
  • - ))} -
- )} -
- ); - })()} - {/* Guided Finish-episode flow (#414): writer-language step status, one primary - "Finish episode" action that uploads finals then prepares the publish - markdown in order, and any blockers grouped by the step that fixes them — - replacing the old flat amber warning list. The lower-level controls in the - header above stay available for manual recovery. */} - - {/* Full cut review (#488): all clean cuts are shown vertically first, with explicit between-scene slots for narration/title cards. */}
{ if (el) rowRefs.current.set(cut.id, el); else rowRefs.current.delete(cut.id); @@ -2022,3 +2045,32 @@ function BetweenSceneSlot({
); } + +function workspaceAssetSummary( + assetDiagnostics: CutAssetDiagnostic[] | null, +): string | null { + if (!assetDiagnostics || assetDiagnostics.length === 0) return null; + const s = summarizeAssetDiagnostics(assetDiagnostics); + const parts = [ + `${s.cleanReady} clean`, + `${s.finalReady} final`, + `${s.uploaded} uploaded`, + ]; + if (s.needsConversion > 0) parts.push(`${s.needsConversion} PNG`); + if (s.missing > 0) parts.push(`${s.missing} missing`); + return parts.join(" · "); +} + +function currentWorkflowLabel( + checklist: ReturnType, + markdownReady: boolean, + published: boolean, +): string { + if (published) return "Published to PlotLink"; + if (markdownReady) return "Ready to publish"; + const current = + checklist.steps.find((step) => step.status === "current") + ?? checklist.steps.find((step) => step.status === "todo") + ?? checklist.steps[checklist.steps.length - 1]; + return current?.label ?? "Review cuts"; +} diff --git a/app/web/dist/assets/export-cut-BeffiHI_.js b/app/web/dist/assets/export-cut-DvUnFkvP.js similarity index 98% rename from app/web/dist/assets/export-cut-BeffiHI_.js rename to app/web/dist/assets/export-cut-DvUnFkvP.js index 821f51b..fafea93 100644 --- a/app/web/dist/assets/export-cut-BeffiHI_.js +++ b/app/web/dist/assets/export-cut-DvUnFkvP.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-CuMJdtXy.js";const z=w;async function G(e){if(typeof document>"u"||!document.fonts||typeof document.fonts.load!="function")return{ready:!0,missing:[]};const n=[];for(const s of e)try{const t=await document.fonts.load(`16px "${s}"`);!t||t.length===0?n.push(s):document.fonts.check(`16px "${s}"`)||n.push(s)}catch{n.push(s)}return{ready:n.length===0,missing:n}}function C(e){return new Promise((n,s)=>{const t=new Image;t.crossOrigin="anonymous",t.onload=()=>n(t),t.onerror=()=>s(new Error("Failed to load image")),t.src=e})}const W="rgba(255, 255, 255, 0.95)",_="#1a1a1a",L="rgba(244, 239, 230, 0.94)",N="rgba(26, 26, 26, 0.55)";function Y(e){return Math.max(2,e*.004)}function K(e,n,s,t,c,d,f){e.beginPath();for(const o of F(n,s,t,c,d,f))o.k==="M"?e.moveTo(o.x,o.y):o.k==="L"?e.lineTo(o.x,o.y):e.arcTo(o.cornerX,o.cornerY,o.x,o.y,o.r);e.closePath()}function P(e,n,s,t,c,d){var f;for(const o of n){const l=o.x*s,i=o.y*t,r=o.width*s,a=o.height*t,y=Y(t);if(o.type==="speech"){const u=R(o,r,a),k=o.tailAnchor?H(l,i,r,a,o.tailAnchor,u):null;K(e,l,i,r,a,k,u),e.fillStyle=W,e.fill(),e.strokeStyle=_,e.lineWidth=y,e.lineJoin="round",e.stroke()}else if(o.type==="narration"){const u=Math.min(r,a)*.12;e.beginPath(),e.roundRect(l,i,r,a,u),e.fillStyle=L,e.fill(),e.strokeStyle=N,e.lineWidth=Math.max(1.5,y*.75),e.lineJoin="round",e.stroke()}const g=o.type==="sfx"?d:c,T=o.type!=="sfx"&&!!o.speaker,h=I((u,k,E=400)=>(e.font=`${E} ${k}px ${g}`,e.measureText(u).width),o.text,r,a,B(o,t,r,a));e.textAlign="center",e.textBaseline="middle";const p=l+r/2,S=T?h.speakerFontSize*1.2:0;T&&(e.fillStyle="#3a3a3a",e.font=`700 ${h.speakerFontSize}px ${g}`,e.fillText(o.speaker,p,i+S/2+a*.04,r-6));const v=i+S,b=a-S,$=h.lines.length*h.lineHeight;let m=v+b/2-$/2+h.lineHeight/2;e.font=`${((f=o.textStyle)==null?void 0:f.fontWeight)??400} ${h.fontSize}px ${g}`;for(const u of h.lines)o.type==="sfx"?(e.fillStyle="#000",e.strokeStyle="#fff",e.lineWidth=3,e.strokeText(u,p,m),e.fillText(u,p,m)):(e.fillStyle="#1a1a1a",e.fillText(u,p,m)),m+=h.lineHeight}}function X(e,n,s,t,c){const d=Math.max(14,Math.min(t*.05,28));e.font=`${d}px ${c}`,e.fillStyle="#1a1a1a",e.textAlign="center",e.textBaseline="middle";const f=[];if(n.dialogue)for(const i of n.dialogue)f.push(`${i.speaker}: ${i.text}`);n.narration&&f.push(n.narration);const o=d*1.6,l=t/2-(f.length-1)*o/2;for(let i=0;iz?{valid:!1,error:`Image is ${(e.size/1024).toFixed(0)}KB, exceeds 1MB limit`}:{valid:!0}}export{z as MAX_SIZE,G as ensureFontsReady,Z as exportCut,P as renderOverlays,A as textPanelDimensions,j as validateExportSize}; +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-uZfLBBm_.js";const z=w;async function G(e){if(typeof document>"u"||!document.fonts||typeof document.fonts.load!="function")return{ready:!0,missing:[]};const n=[];for(const s of e)try{const t=await document.fonts.load(`16px "${s}"`);!t||t.length===0?n.push(s):document.fonts.check(`16px "${s}"`)||n.push(s)}catch{n.push(s)}return{ready:n.length===0,missing:n}}function C(e){return new Promise((n,s)=>{const t=new Image;t.crossOrigin="anonymous",t.onload=()=>n(t),t.onerror=()=>s(new Error("Failed to load image")),t.src=e})}const W="rgba(255, 255, 255, 0.95)",_="#1a1a1a",L="rgba(244, 239, 230, 0.94)",N="rgba(26, 26, 26, 0.55)";function Y(e){return Math.max(2,e*.004)}function K(e,n,s,t,c,d,f){e.beginPath();for(const o of F(n,s,t,c,d,f))o.k==="M"?e.moveTo(o.x,o.y):o.k==="L"?e.lineTo(o.x,o.y):e.arcTo(o.cornerX,o.cornerY,o.x,o.y,o.r);e.closePath()}function P(e,n,s,t,c,d){var f;for(const o of n){const l=o.x*s,i=o.y*t,r=o.width*s,a=o.height*t,y=Y(t);if(o.type==="speech"){const u=R(o,r,a),k=o.tailAnchor?H(l,i,r,a,o.tailAnchor,u):null;K(e,l,i,r,a,k,u),e.fillStyle=W,e.fill(),e.strokeStyle=_,e.lineWidth=y,e.lineJoin="round",e.stroke()}else if(o.type==="narration"){const u=Math.min(r,a)*.12;e.beginPath(),e.roundRect(l,i,r,a,u),e.fillStyle=L,e.fill(),e.strokeStyle=N,e.lineWidth=Math.max(1.5,y*.75),e.lineJoin="round",e.stroke()}const g=o.type==="sfx"?d:c,T=o.type!=="sfx"&&!!o.speaker,h=I((u,k,E=400)=>(e.font=`${E} ${k}px ${g}`,e.measureText(u).width),o.text,r,a,B(o,t,r,a));e.textAlign="center",e.textBaseline="middle";const p=l+r/2,S=T?h.speakerFontSize*1.2:0;T&&(e.fillStyle="#3a3a3a",e.font=`700 ${h.speakerFontSize}px ${g}`,e.fillText(o.speaker,p,i+S/2+a*.04,r-6));const v=i+S,b=a-S,$=h.lines.length*h.lineHeight;let m=v+b/2-$/2+h.lineHeight/2;e.font=`${((f=o.textStyle)==null?void 0:f.fontWeight)??400} ${h.fontSize}px ${g}`;for(const u of h.lines)o.type==="sfx"?(e.fillStyle="#000",e.strokeStyle="#fff",e.lineWidth=3,e.strokeText(u,p,m),e.fillText(u,p,m)):(e.fillStyle="#1a1a1a",e.fillText(u,p,m)),m+=h.lineHeight}}function X(e,n,s,t,c){const d=Math.max(14,Math.min(t*.05,28));e.font=`${d}px ${c}`,e.fillStyle="#1a1a1a",e.textAlign="center",e.textBaseline="middle";const f=[];if(n.dialogue)for(const i of n.dialogue)f.push(`${i.speaker}: ${i.text}`);n.narration&&f.push(n.narration);const o=d*1.6,l=t/2-(f.length-1)*o/2;for(let i=0;iz?{valid:!1,error:`Image is ${(e.size/1024).toFixed(0)}KB, exceeds 1MB limit`}:{valid:!0}}export{z as MAX_SIZE,G as ensureFontsReady,Z as exportCut,P as renderOverlays,A as textPanelDimensions,j as validateExportSize}; diff --git a/app/web/dist/assets/index-B1vSuADc.css b/app/web/dist/assets/index-Bidn584T.css similarity index 54% rename from app/web/dist/assets/index-B1vSuADc.css rename to app/web/dist/assets/index-Bidn584T.css index 278fdde..6e606b8 100644 --- a/app/web/dist/assets/index-B1vSuADc.css +++ b/app/web/dist/assets/index-Bidn584T.css @@ -29,4 +29,4 @@ * The original design remains. The terminal itself * has been extended to include xterm CSI codes, among * other features. - */.xterm{cursor:text;position:relative;user-select:none;-ms-user-select:none;-webkit-user-select:none}.xterm.focus,.xterm:focus{outline:none}.xterm .xterm-helpers{position:absolute;top:0;z-index:5}.xterm .xterm-helper-textarea{padding:0;border:0;margin:0;position:absolute;opacity:0;left:-9999em;top:0;width:0;height:0;z-index:-5;white-space:nowrap;overflow:hidden;resize:none}.xterm .composition-view{background:#000;color:#fff;display:none;position:absolute;white-space:nowrap;z-index:1}.xterm .composition-view.active{display:block}.xterm .xterm-viewport{background-color:#000;overflow-y:scroll;cursor:default;position:absolute;right:0;left:0;top:0;bottom:0}.xterm .xterm-screen{position:relative}.xterm .xterm-screen canvas{position:absolute;left:0;top:0}.xterm-char-measure-element{display:inline-block;visibility:hidden;position:absolute;top:0;left:-9999em;line-height:normal}.xterm.enable-mouse-events{cursor:default}.xterm.xterm-cursor-pointer,.xterm .xterm-cursor-pointer{cursor:pointer}.xterm.column-select.focus{cursor:crosshair}.xterm .xterm-accessibility:not(.debug),.xterm .xterm-message{position:absolute;left:0;top:0;bottom:0;right:0;z-index:10;color:transparent;pointer-events:none}.xterm .xterm-accessibility-tree:not(.debug) *::selection{color:transparent}.xterm .xterm-accessibility-tree{font-family:monospace;-webkit-user-select:text;user-select:text;white-space:pre}.xterm .xterm-accessibility-tree>div{transform-origin:left;width:fit-content}.xterm .live-region{position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden}.xterm-dim{opacity:1!important}.xterm-underline-1{text-decoration:underline}.xterm-underline-2{text-decoration:double underline}.xterm-underline-3{text-decoration:wavy underline}.xterm-underline-4{text-decoration:dotted underline}.xterm-underline-5{text-decoration:dashed underline}.xterm-overline{text-decoration:overline}.xterm-overline.xterm-underline-1{text-decoration:overline underline}.xterm-overline.xterm-underline-2{text-decoration:overline double underline}.xterm-overline.xterm-underline-3{text-decoration:overline wavy underline}.xterm-overline.xterm-underline-4{text-decoration:overline dotted underline}.xterm-overline.xterm-underline-5{text-decoration:overline dashed underline}.xterm-strikethrough{text-decoration:line-through}.xterm-screen .xterm-decoration-container .xterm-decoration{z-index:6;position:absolute}.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer{z-index:7}.xterm-decoration-overview-ruler{z-index:8;position:absolute;top:0;right:0;pointer-events:none}.xterm-decoration-top{z-index:2;position:relative}.xterm .xterm-scrollable-element>.scrollbar{cursor:default}.xterm .xterm-scrollable-element>.scrollbar>.scra{cursor:pointer;font-size:11px!important}.xterm .xterm-scrollable-element>.visible{opacity:1;background:#0000;transition:opacity .1s linear;z-index:11}.xterm .xterm-scrollable-element>.invisible{opacity:0;pointer-events:none}.xterm .xterm-scrollable-element>.invisible.fade{transition:opacity .8s linear}.xterm .xterm-scrollable-element>.shadow{position:absolute;display:none}.xterm .xterm-scrollable-element>.shadow.top{display:block;top:0;left:3px;height:3px;width:100%;box-shadow:var(--vscode-scrollbar-shadow, #000) 0 6px 6px -6px inset}.xterm .xterm-scrollable-element>.shadow.left{display:block;top:3px;left:0;height:100%;width:3px;box-shadow:var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset}.xterm .xterm-scrollable-element>.shadow.top-left-corner{display:block;top:0;left:0;height:3px;width:3px}.xterm .xterm-scrollable-element>.shadow.top.left{box-shadow:var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset}/*! tailwindcss v4.2.2 | MIT License | https://tailwindcss.com */@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-space-y-reverse:0;--tw-border-style:solid;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial}}}@layer theme{:root,:host{--font-sans:ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--font-serif:ui-serif, Georgia, Cambria, "Times New Roman", Times, serif;--font-mono:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--color-red-700:oklch(50.5% .213 27.518);--color-amber-50:oklch(98.7% .022 95.277);--color-amber-100:oklch(96.2% .059 95.617);--color-amber-300:oklch(87.9% .169 91.605);--color-amber-500:oklch(76.9% .188 70.08);--color-amber-600:oklch(66.6% .179 58.318);--color-amber-700:oklch(55.5% .163 48.998);--color-amber-800:oklch(47.3% .137 46.201);--color-amber-950:oklch(27.9% .077 45.635);--color-green-50:oklch(98.2% .018 155.826);--color-green-100:oklch(96.2% .044 156.743);--color-green-300:oklch(87.1% .15 154.449);--color-green-600:oklch(62.7% .194 149.214);--color-green-700:oklch(52.7% .154 150.069);--color-green-800:oklch(44.8% .119 151.328);--color-green-950:oklch(26.6% .065 152.934);--color-white:#fff;--spacing:.25rem;--container-sm:24rem;--container-md:28rem;--container-lg:32rem;--container-xl:36rem;--container-2xl:42rem;--text-xs:.75rem;--text-xs--line-height:calc(1 / .75);--text-sm:.875rem;--text-sm--line-height:calc(1.25 / .875);--text-base:1rem;--text-base--line-height: 1.5 ;--text-lg:1.125rem;--text-lg--line-height:calc(1.75 / 1.125);--text-2xl:1.5rem;--text-2xl--line-height:calc(2 / 1.5);--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--font-weight-bold:700;--tracking-tight:-.025em;--tracking-wider:.05em;--leading-tight:1.25;--leading-relaxed:1.625;--radius-md:.375rem;--radius-lg:.5rem;--radius-xl:.75rem;--aspect-video:16 / 9;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;-moz-tab-size:4;tab-size:4;font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent;font-family:Inter,system-ui,-apple-system,sans-serif;line-height:1.5}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab,red,red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){-webkit-appearance:button;-moz-appearance:button;appearance:button}::file-selector-button{-webkit-appearance:button;-moz-appearance:button;appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer components;@layer utilities{.pointer-events-none{pointer-events:none}.collapse{visibility:collapse}.invisible{visibility:hidden}.visible{visibility:visible}.sr-only{clip-path:inset(50%);white-space:nowrap;border-width:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.inset-0{inset:calc(var(--spacing) * 0)}.start{inset-inline-start:var(--spacing)}.start\!{inset-inline-start:var(--spacing)!important}.end{inset-inline-end:var(--spacing)}.-top-1\.5{top:calc(var(--spacing) * -1.5)}.top-1{top:calc(var(--spacing) * 1)}.-right-1\.5{right:calc(var(--spacing) * -1.5)}.right-0{right:calc(var(--spacing) * 0)}.right-1{right:calc(var(--spacing) * 1)}.bottom-0{bottom:calc(var(--spacing) * 0)}.z-10{z-index:10}.z-50{z-index:50}.container{width:100%}@media(min-width:40rem){.container{max-width:40rem}}@media(min-width:48rem){.container{max-width:48rem}}@media(min-width:64rem){.container{max-width:64rem}}@media(min-width:80rem){.container{max-width:80rem}}@media(min-width:96rem){.container{max-width:96rem}}.m-3{margin:calc(var(--spacing) * 3)}.-mx-1{margin-inline:calc(var(--spacing) * -1)}.mx-auto{margin-inline:auto}.prose{color:var(--tw-prose-body);max-width:65ch}.prose :where(p):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em;margin-bottom:1.25em}.prose :where([class~=lead]):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-lead);margin-top:1.2em;margin-bottom:1.2em;font-size:1.25em;line-height:1.6}.prose :where(a):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-links);font-weight:500;text-decoration:underline}.prose :where(strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-bold);font-weight:600}.prose :where(a strong):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(blockquote strong):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(thead th strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit}.prose :where(ol):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em;margin-bottom:1.25em;padding-inline-start:1.625em;list-style-type:decimal}.prose :where(ol[type=A]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:upper-alpha}.prose :where(ol[type=a]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:lower-alpha}.prose :where(ol[type=A s]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:upper-alpha}.prose :where(ol[type=a s]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:lower-alpha}.prose :where(ol[type=I]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:upper-roman}.prose :where(ol[type=i]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:lower-roman}.prose :where(ol[type=I s]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:upper-roman}.prose :where(ol[type=i s]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:lower-roman}.prose :where(ol[type="1"]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:decimal}.prose :where(ul):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em;margin-bottom:1.25em;padding-inline-start:1.625em;list-style-type:disc}.prose :where(ol>li):not(:where([class~=not-prose],[class~=not-prose] *))::marker{color:var(--tw-prose-counters);font-weight:400}.prose :where(ul>li):not(:where([class~=not-prose],[class~=not-prose] *))::marker{color:var(--tw-prose-bullets)}.prose :where(dt):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);margin-top:1.25em;font-weight:600}.prose :where(hr):not(:where([class~=not-prose],[class~=not-prose] *)){border-color:var(--tw-prose-hr);border-top-width:1px;margin-top:3em;margin-bottom:3em}.prose :where(blockquote):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-quotes);border-inline-start-width:.25rem;border-inline-start-color:var(--tw-prose-quote-borders);quotes:"“""”""‘""’";margin-top:1.6em;margin-bottom:1.6em;padding-inline-start:1em;font-style:italic;font-weight:500}.prose :where(blockquote p:first-of-type):not(:where([class~=not-prose],[class~=not-prose] *)):before{content:open-quote}.prose :where(blockquote p:last-of-type):not(:where([class~=not-prose],[class~=not-prose] *)):after{content:close-quote}.prose :where(h1):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);margin-top:0;margin-bottom:.888889em;font-size:2.25em;font-weight:800;line-height:1.11111}.prose :where(h1 strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-weight:900}.prose :where(h2):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);margin-top:2em;margin-bottom:1em;font-size:1.5em;font-weight:700;line-height:1.33333}.prose :where(h2 strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-weight:800}.prose :where(h3):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);margin-top:1.6em;margin-bottom:.6em;font-size:1.25em;font-weight:600;line-height:1.6}.prose :where(h3 strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-weight:700}.prose :where(h4):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);margin-top:1.5em;margin-bottom:.5em;font-weight:600;line-height:1.5}.prose :where(h4 strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-weight:700}.prose :where(img):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:2em;margin-bottom:2em}.prose :where(picture):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:2em;margin-bottom:2em;display:block}.prose :where(video):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:2em;margin-bottom:2em}.prose :where(kbd):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-kbd);box-shadow:0 0 0 1px var(--tw-prose-kbd-shadows),0 3px 0 var(--tw-prose-kbd-shadows);padding-top:.1875em;padding-inline-end:.375em;padding-bottom:.1875em;border-radius:.3125rem;padding-inline-start:.375em;font-family:inherit;font-size:.875em;font-weight:500}.prose :where(code):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-code);font-size:.875em;font-weight:600}.prose :where(code):not(:where([class~=not-prose],[class~=not-prose] *)):before,.prose :where(code):not(:where([class~=not-prose],[class~=not-prose] *)):after{content:"`"}.prose :where(a code):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(h1 code):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit}.prose :where(h2 code):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-size:.875em}.prose :where(h3 code):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-size:.9em}.prose :where(h4 code):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(blockquote code):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(thead th code):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit}.prose :where(pre):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-pre-code);background-color:var(--tw-prose-pre-bg);padding-top:.857143em;padding-inline-end:1.14286em;padding-bottom:.857143em;border-radius:.375rem;margin-top:1.71429em;margin-bottom:1.71429em;padding-inline-start:1.14286em;font-size:.875em;font-weight:400;line-height:1.71429;overflow-x:auto}.prose :where(pre code):not(:where([class~=not-prose],[class~=not-prose] *)){font-weight:inherit;color:inherit;font-size:inherit;font-family:inherit;line-height:inherit;background-color:#0000;border-width:0;border-radius:0;padding:0}.prose :where(pre code):not(:where([class~=not-prose],[class~=not-prose] *)):before,.prose :where(pre code):not(:where([class~=not-prose],[class~=not-prose] *)):after{content:none}.prose :where(table):not(:where([class~=not-prose],[class~=not-prose] *)){table-layout:auto;width:100%;margin-top:2em;margin-bottom:2em;font-size:.875em;line-height:1.71429}.prose :where(thead):not(:where([class~=not-prose],[class~=not-prose] *)){border-bottom-width:1px;border-bottom-color:var(--tw-prose-th-borders)}.prose :where(thead th):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);vertical-align:bottom;padding-inline-end:.571429em;padding-bottom:.571429em;padding-inline-start:.571429em;font-weight:600}.prose :where(tbody tr):not(:where([class~=not-prose],[class~=not-prose] *)){border-bottom-width:1px;border-bottom-color:var(--tw-prose-td-borders)}.prose :where(tbody tr:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){border-bottom-width:0}.prose :where(tbody td):not(:where([class~=not-prose],[class~=not-prose] *)){vertical-align:baseline}.prose :where(tfoot):not(:where([class~=not-prose],[class~=not-prose] *)){border-top-width:1px;border-top-color:var(--tw-prose-th-borders)}.prose :where(tfoot td):not(:where([class~=not-prose],[class~=not-prose] *)){vertical-align:top}.prose :where(th,td):not(:where([class~=not-prose],[class~=not-prose] *)){text-align:start}.prose :where(figure>*):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:0;margin-bottom:0}.prose :where(figcaption):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-captions);margin-top:.857143em;font-size:.875em;line-height:1.42857}.prose{--tw-prose-body:oklch(37.3% .034 259.733);--tw-prose-headings:oklch(21% .034 264.665);--tw-prose-lead:oklch(44.6% .03 256.802);--tw-prose-links:oklch(21% .034 264.665);--tw-prose-bold:oklch(21% .034 264.665);--tw-prose-counters:oklch(55.1% .027 264.364);--tw-prose-bullets:oklch(87.2% .01 258.338);--tw-prose-hr:oklch(92.8% .006 264.531);--tw-prose-quotes:oklch(21% .034 264.665);--tw-prose-quote-borders:oklch(92.8% .006 264.531);--tw-prose-captions:oklch(55.1% .027 264.364);--tw-prose-kbd:oklch(21% .034 264.665);--tw-prose-kbd-shadows:oklab(21% -.00316127 -.0338527/.1);--tw-prose-code:oklch(21% .034 264.665);--tw-prose-pre-code:oklch(92.8% .006 264.531);--tw-prose-pre-bg:oklch(27.8% .033 256.848);--tw-prose-th-borders:oklch(87.2% .01 258.338);--tw-prose-td-borders:oklch(92.8% .006 264.531);--tw-prose-invert-body:oklch(87.2% .01 258.338);--tw-prose-invert-headings:#fff;--tw-prose-invert-lead:oklch(70.7% .022 261.325);--tw-prose-invert-links:#fff;--tw-prose-invert-bold:#fff;--tw-prose-invert-counters:oklch(70.7% .022 261.325);--tw-prose-invert-bullets:oklch(44.6% .03 256.802);--tw-prose-invert-hr:oklch(37.3% .034 259.733);--tw-prose-invert-quotes:oklch(96.7% .003 264.542);--tw-prose-invert-quote-borders:oklch(37.3% .034 259.733);--tw-prose-invert-captions:oklch(70.7% .022 261.325);--tw-prose-invert-kbd:#fff;--tw-prose-invert-kbd-shadows:#ffffff1a;--tw-prose-invert-code:#fff;--tw-prose-invert-pre-code:oklch(87.2% .01 258.338);--tw-prose-invert-pre-bg:#00000080;--tw-prose-invert-th-borders:oklch(44.6% .03 256.802);--tw-prose-invert-td-borders:oklch(37.3% .034 259.733);font-size:1rem;line-height:1.75}.prose :where(picture>img):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:0;margin-bottom:0}.prose :where(li):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:.5em;margin-bottom:.5em}.prose :where(ol>li):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(ul>li):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-start:.375em}.prose :where(.prose>ul>li p):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:.75em;margin-bottom:.75em}.prose :where(.prose>ul>li>p:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em}.prose :where(.prose>ul>li>p:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-bottom:1.25em}.prose :where(.prose>ol>li>p:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em}.prose :where(.prose>ol>li>p:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-bottom:1.25em}.prose :where(ul ul,ul ol,ol ul,ol ol):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:.75em;margin-bottom:.75em}.prose :where(dl):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em;margin-bottom:1.25em}.prose :where(dd):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:.5em;padding-inline-start:1.625em}.prose :where(hr+*):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(h2+*):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(h3+*):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(h4+*):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:0}.prose :where(thead th:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-start:0}.prose :where(thead th:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-end:0}.prose :where(tbody td,tfoot td):not(:where([class~=not-prose],[class~=not-prose] *)){padding-top:.571429em;padding-inline-end:.571429em;padding-bottom:.571429em;padding-inline-start:.571429em}.prose :where(tbody td:first-child,tfoot td:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-start:0}.prose :where(tbody td:last-child,tfoot td:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-end:0}.prose :where(figure):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:2em;margin-bottom:2em}.prose :where(.prose>:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:0}.prose :where(.prose>:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-bottom:0}.mt-0\.5{margin-top:calc(var(--spacing) * .5)}.mt-1{margin-top:calc(var(--spacing) * 1)}.mt-1\.5{margin-top:calc(var(--spacing) * 1.5)}.mt-2{margin-top:calc(var(--spacing) * 2)}.mt-3{margin-top:calc(var(--spacing) * 3)}.mt-4{margin-top:calc(var(--spacing) * 4)}.mb-1{margin-bottom:calc(var(--spacing) * 1)}.mb-1\.5{margin-bottom:calc(var(--spacing) * 1.5)}.mb-2{margin-bottom:calc(var(--spacing) * 2)}.mb-3{margin-bottom:calc(var(--spacing) * 3)}.mb-4{margin-bottom:calc(var(--spacing) * 4)}.mb-6{margin-bottom:calc(var(--spacing) * 6)}.ml-0\.5{margin-left:calc(var(--spacing) * .5)}.ml-1{margin-left:calc(var(--spacing) * 1)}.ml-2{margin-left:calc(var(--spacing) * 2)}.ml-3{margin-left:calc(var(--spacing) * 3)}.ml-auto{margin-left:auto}.block{display:block}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline{display:inline}.inline-flex{display:inline-flex}.table{display:table}.aspect-video{aspect-ratio:var(--aspect-video)}.h-0\.5{height:calc(var(--spacing) * .5)}.h-1\.5{height:calc(var(--spacing) * 1.5)}.h-2{height:calc(var(--spacing) * 2)}.h-4{height:calc(var(--spacing) * 4)}.h-5{height:calc(var(--spacing) * 5)}.h-14{height:calc(var(--spacing) * 14)}.h-16{height:calc(var(--spacing) * 16)}.h-24{height:calc(var(--spacing) * 24)}.h-\[calc\(100vh-3\.5rem\)\]{height:calc(100vh - 3.5rem)}.h-full{height:100%}.h-screen{height:100vh}.max-h-72{max-height:calc(var(--spacing) * 72)}.min-h-0{min-height:calc(var(--spacing) * 0)}.min-h-28{min-height:calc(var(--spacing) * 28)}.min-h-56{min-height:calc(var(--spacing) * 56)}.min-h-\[22rem\]{min-height:22rem}.w-0\.5{width:calc(var(--spacing) * .5)}.w-1\.5{width:calc(var(--spacing) * 1.5)}.w-2{width:calc(var(--spacing) * 2)}.w-4{width:calc(var(--spacing) * 4)}.w-5{width:calc(var(--spacing) * 5)}.w-14{width:calc(var(--spacing) * 14)}.w-16{width:calc(var(--spacing) * 16)}.w-56{width:calc(var(--spacing) * 56)}.w-64{width:calc(var(--spacing) * 64)}.w-full{width:100%}.max-w-2xl{max-width:var(--container-2xl)}.max-w-\[32rem\]{max-width:32rem}.max-w-\[120px\]{max-width:120px}.max-w-lg{max-width:var(--container-lg)}.max-w-md{max-width:var(--container-md)}.max-w-none{max-width:none}.max-w-sm{max-width:var(--container-sm)}.max-w-xl{max-width:var(--container-xl)}.min-w-0{min-width:calc(var(--spacing) * 0)}.min-w-\[140px\]{min-width:140px}.flex-1{flex:1}.flex-shrink-0{flex-shrink:0}.shrink{flex-shrink:1}.shrink-0{flex-shrink:0}.transform{transform:var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,)}.cursor-move{cursor:move}.cursor-pointer{cursor:pointer}.cursor-se-resize{cursor:se-resize}.resize{resize:both}.resize-none{resize:none}.resize-y{resize:vertical}.list-inside{list-style-position:inside}.list-decimal{list-style-type:decimal}.list-disc{list-style-type:disc}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-baseline{align-items:baseline}.items-center{align-items:center}.items-start{align-items:flex-start}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.justify-end{justify-content:flex-end}.gap-0\.5{gap:calc(var(--spacing) * .5)}.gap-1{gap:calc(var(--spacing) * 1)}.gap-1\.5{gap:calc(var(--spacing) * 1.5)}.gap-2{gap:calc(var(--spacing) * 2)}.gap-3{gap:calc(var(--spacing) * 3)}.gap-4{gap:calc(var(--spacing) * 4)}:where(.space-y-0\.5>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * .5) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * .5) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-1>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 1) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 1) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-1\.5>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 1.5) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 1.5) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-2>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 2) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 2) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-3>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 3) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 3) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-4>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 4) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 4) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-6>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 6) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 6) * calc(1 - var(--tw-space-y-reverse)))}.gap-x-3{column-gap:calc(var(--spacing) * 3)}.gap-y-0\.5{row-gap:calc(var(--spacing) * .5)}.gap-y-1{row-gap:calc(var(--spacing) * 1)}.self-start{align-self:flex-start}.truncate{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.rounded{border-radius:.25rem}.rounded-full{border-radius:3.40282e38px}.rounded-lg{border-radius:var(--radius-lg)}.rounded-md{border-radius:var(--radius-md)}.rounded-xl{border-radius:var(--radius-xl)}.border{border-style:var(--tw-border-style);border-width:1px}.border-2{border-style:var(--tw-border-style);border-width:2px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-r{border-right-style:var(--tw-border-style);border-right-width:1px}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-b-2{border-bottom-style:var(--tw-border-style);border-bottom-width:2px}.border-l{border-left-style:var(--tw-border-style);border-left-width:1px}.border-l-2{border-left-style:var(--tw-border-style);border-left-width:2px}.border-dashed{--tw-border-style:dashed;border-style:dashed}.border-accent{border-color:#8b4513}.border-accent-dim\/30{border-color:#6b34104d}.border-accent\/30{border-color:#8b45134d}.border-accent\/40{border-color:#8b451366}.border-amber-300{border-color:var(--color-amber-300)}.border-amber-500{border-color:var(--color-amber-500)}.border-amber-500\/40{border-color:#f99c0066}@supports (color:color-mix(in lab,red,red)){.border-amber-500\/40{border-color:color-mix(in oklab,var(--color-amber-500) 40%,transparent)}}.border-amber-500\/50{border-color:#f99c0080}@supports (color:color-mix(in lab,red,red)){.border-amber-500\/50{border-color:color-mix(in oklab,var(--color-amber-500) 50%,transparent)}}.border-amber-600\/30{border-color:#dd74004d}@supports (color:color-mix(in lab,red,red)){.border-amber-600\/30{border-color:color-mix(in oklab,var(--color-amber-600) 30%,transparent)}}.border-border{border-color:#d4c5b0}.border-border\/70{border-color:#d4c5b0b3}.border-border\/80{border-color:#d4c5b0cc}.border-error\/15{border-color:#cc333326}.border-error\/30{border-color:#cc33334d}.border-error\/40{border-color:#c336}.border-foreground\/40{border-color:#2c181066}.border-green-300{border-color:var(--color-green-300)}.border-green-700\/20{border-color:#00813833}@supports (color:color-mix(in lab,red,red)){.border-green-700\/20{border-color:color-mix(in oklab,var(--color-green-700) 20%,transparent)}}.border-green-700\/25{border-color:#00813840}@supports (color:color-mix(in lab,red,red)){.border-green-700\/25{border-color:color-mix(in oklab,var(--color-green-700) 25%,transparent)}}.border-green-700\/30{border-color:#0081384d}@supports (color:color-mix(in lab,red,red)){.border-green-700\/30{border-color:color-mix(in oklab,var(--color-green-700) 30%,transparent)}}.border-green-700\/40{border-color:#00813866}@supports (color:color-mix(in lab,red,red)){.border-green-700\/40{border-color:color-mix(in oklab,var(--color-green-700) 40%,transparent)}}.border-muted\/40{border-color:#8b735566}.border-red-700\/30{border-color:#bf000f4d}@supports (color:color-mix(in lab,red,red)){.border-red-700\/30{border-color:color-mix(in oklab,var(--color-red-700) 30%,transparent)}}.border-transparent{border-color:#0000}.bg-\[\#f4efe6\]\/85{background-color:#f4efe6d9}.bg-\[\#f8f5ef\]{background-color:#f8f5ef}.bg-accent{background-color:#8b4513}.bg-accent\/5{background-color:#8b45130d}.bg-accent\/10{background-color:#8b45131a}.bg-amber-50{background-color:var(--color-amber-50)}.bg-amber-100{background-color:var(--color-amber-100)}.bg-amber-500{background-color:var(--color-amber-500)}.bg-amber-500\/10{background-color:#f99c001a}@supports (color:color-mix(in lab,red,red)){.bg-amber-500\/10{background-color:color-mix(in oklab,var(--color-amber-500) 10%,transparent)}}.bg-amber-950\/10{background-color:#4619011a}@supports (color:color-mix(in lab,red,red)){.bg-amber-950\/10{background-color:color-mix(in oklab,var(--color-amber-950) 10%,transparent)}}.bg-background{background-color:#e8dfd0}.bg-background\/40{background-color:#e8dfd066}.bg-background\/50{background-color:#e8dfd080}.bg-background\/60{background-color:#e8dfd099}.bg-background\/70{background-color:#e8dfd0b3}.bg-background\/95{background-color:#e8dfd0f2}.bg-error{background-color:#c33}.bg-error\/5{background-color:#cc33330d}.bg-error\/10{background-color:#cc33331a}.bg-foreground{background-color:#2c1810}.bg-green-50{background-color:var(--color-green-50)}.bg-green-100{background-color:var(--color-green-100)}.bg-green-600{background-color:var(--color-green-600)}.bg-green-600\/10{background-color:#00a5441a}@supports (color:color-mix(in lab,red,red)){.bg-green-600\/10{background-color:color-mix(in oklab,var(--color-green-600) 10%,transparent)}}.bg-green-700\/10{background-color:#0081381a}@supports (color:color-mix(in lab,red,red)){.bg-green-700\/10{background-color:color-mix(in oklab,var(--color-green-700) 10%,transparent)}}.bg-green-950\/5{background-color:#032e150d}@supports (color:color-mix(in lab,red,red)){.bg-green-950\/5{background-color:color-mix(in oklab,var(--color-green-950) 5%,transparent)}}.bg-muted\/40{background-color:#8b735566}.bg-muted\/50{background-color:#8b735580}.bg-surface{background-color:#f0ebe1}.bg-surface\/35{background-color:#f0ebe159}.bg-surface\/40{background-color:#f0ebe166}.bg-surface\/50{background-color:#f0ebe180}.bg-surface\/60{background-color:#f0ebe199}.bg-surface\/70{background-color:#f0ebe1b3}.bg-surface\/80{background-color:#f0ebe1cc}.bg-surface\/95{background-color:#f0ebe1f2}.bg-transparent{background-color:#0000}.bg-white{background-color:var(--color-white)}.fill-white\/95{fill:#fffffff2}@supports (color:color-mix(in lab,red,red)){.fill-white\/95{fill:color-mix(in oklab,var(--color-white) 95%,transparent)}}.stroke-\[\#1a1a1a\]{stroke:#1a1a1a}.stroke-accent{stroke:#8b4513}.object-contain{object-fit:contain}.object-cover{object-fit:cover}.p-1\.5{padding:calc(var(--spacing) * 1.5)}.p-2{padding:calc(var(--spacing) * 2)}.p-3{padding:calc(var(--spacing) * 3)}.p-4{padding:calc(var(--spacing) * 4)}.p-6{padding:calc(var(--spacing) * 6)}.p-8{padding:calc(var(--spacing) * 8)}.px-1{padding-inline:calc(var(--spacing) * 1)}.px-1\.5{padding-inline:calc(var(--spacing) * 1.5)}.px-2{padding-inline:calc(var(--spacing) * 2)}.px-2\.5{padding-inline:calc(var(--spacing) * 2.5)}.px-3{padding-inline:calc(var(--spacing) * 3)}.px-4{padding-inline:calc(var(--spacing) * 4)}.px-6{padding-inline:calc(var(--spacing) * 6)}.py-0\.5{padding-block:calc(var(--spacing) * .5)}.py-1{padding-block:calc(var(--spacing) * 1)}.py-1\.5{padding-block:calc(var(--spacing) * 1.5)}.py-2{padding-block:calc(var(--spacing) * 2)}.py-2\.5{padding-block:calc(var(--spacing) * 2.5)}.py-3{padding-block:calc(var(--spacing) * 3)}.py-4{padding-block:calc(var(--spacing) * 4)}.py-6{padding-block:calc(var(--spacing) * 6)}.pt-1\.5{padding-top:calc(var(--spacing) * 1.5)}.pt-2{padding-top:calc(var(--spacing) * 2)}.pt-3{padding-top:calc(var(--spacing) * 3)}.pr-16{padding-right:calc(var(--spacing) * 16)}.pb-1{padding-bottom:calc(var(--spacing) * 1)}.pb-3{padding-bottom:calc(var(--spacing) * 3)}.pl-3{padding-left:calc(var(--spacing) * 3)}.pl-4{padding-left:calc(var(--spacing) * 4)}.text-center{text-align:center}.text-left{text-align:left}.font-mono{font-family:var(--font-mono)}.font-sans{font-family:var(--font-sans)}.font-serif{font-family:var(--font-serif)}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-base{font-size:var(--text-base);line-height:var(--tw-leading,var(--text-base--line-height))}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.text-\[9px\]{font-size:9px}.text-\[10px\]{font-size:10px}.text-\[11px\]{font-size:11px}.leading-none{--tw-leading:1;line-height:1}.leading-relaxed{--tw-leading:var(--leading-relaxed);line-height:var(--leading-relaxed)}.leading-tight{--tw-leading:var(--leading-tight);line-height:var(--leading-tight)}.font-bold{--tw-font-weight:var(--font-weight-bold);font-weight:var(--font-weight-bold)}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-normal{--tw-font-weight:var(--font-weight-normal);font-weight:var(--font-weight-normal)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-\[0\.14em\]{--tw-tracking:.14em;letter-spacing:.14em}.tracking-\[0\.16em\]{--tw-tracking:.16em;letter-spacing:.16em}.tracking-\[0\.18em\]{--tw-tracking:.18em;letter-spacing:.18em}.tracking-tight{--tw-tracking:var(--tracking-tight);letter-spacing:var(--tracking-tight)}.tracking-wider{--tw-tracking:var(--tracking-wider);letter-spacing:var(--tracking-wider)}.break-words{overflow-wrap:break-word}.break-all{word-break:break-all}.whitespace-nowrap{white-space:nowrap}.whitespace-pre-wrap{white-space:pre-wrap}.text-\[\#1a1a1a\]{color:#1a1a1a}.text-\[\#3a3a3a\]{color:#3a3a3a}.text-accent{color:#8b4513}.text-accent-dim{color:#6b3410}.text-amber-600{color:var(--color-amber-600)}.text-amber-700{color:var(--color-amber-700)}.text-amber-800{color:var(--color-amber-800)}.text-background{color:#e8dfd0}.text-error{color:#c33}.text-error\/70{color:#cc3333b3}.text-foreground{color:#2c1810}.text-green-700{color:var(--color-green-700)}.text-green-800{color:var(--color-green-800)}.text-muted{color:#8b7355}.text-muted\/70{color:#8b7355b3}.text-red-700{color:var(--color-red-700)}.text-white{color:var(--color-white)}.uppercase{text-transform:uppercase}.italic{font-style:italic}.overline{text-decoration-line:overline}.underline{text-decoration-line:underline}.opacity-90{opacity:.9}.shadow{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a), 0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a), 0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-sm{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a), 0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring-2{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring-accent{--tw-ring-color:#8b4513}.ring-amber-500{--tw-ring-color:var(--color-amber-500)}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.blur{--tw-blur:blur(8px);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.filter{filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.backdrop-blur{--tw-backdrop-blur:blur(8px);-webkit-backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.outline-none{--tw-outline-style:none;outline-style:none}.select-none{-webkit-user-select:none;user-select:none}.placeholder\:text-muted\/50::placeholder{color:#8b735580}@media(hover:hover){.hover\:border-accent:hover{border-color:#8b4513}.hover\:border-error:hover{border-color:#c33}.hover\:bg-accent-dim:hover{background-color:#6b3410}.hover\:bg-accent\/5:hover{background-color:#8b45130d}.hover\:bg-accent\/10:hover{background-color:#8b45131a}.hover\:bg-amber-500\/20:hover{background-color:#f99c0033}@supports (color:color-mix(in lab,red,red)){.hover\:bg-amber-500\/20:hover{background-color:color-mix(in oklab,var(--color-amber-500) 20%,transparent)}}.hover\:bg-border\/50:hover{background-color:#d4c5b080}.hover\:bg-error\/5:hover{background-color:#cc33330d}.hover\:bg-error\/10:hover{background-color:#cc33331a}.hover\:bg-green-700\/5:hover{background-color:#0081380d}@supports (color:color-mix(in lab,red,red)){.hover\:bg-green-700\/5:hover{background-color:color-mix(in oklab,var(--color-green-700) 5%,transparent)}}.hover\:bg-surface:hover{background-color:#f0ebe1}.hover\:text-accent:hover{color:#8b4513}.hover\:text-accent-dim:hover{color:#6b3410}.hover\:text-error:hover{color:#c33}.hover\:text-foreground:hover{color:#2c1810}.hover\:underline:hover{text-decoration-line:underline}.hover\:opacity-80:hover{opacity:.8}}.focus\:border-accent:focus{border-color:#8b4513}.focus\:outline-none:focus{--tw-outline-style:none;outline-style:none}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-40:disabled{opacity:.4}.disabled\:opacity-50:disabled{opacity:.5}@media(hover:hover){.disabled\:hover\:border-border:disabled:hover{border-color:#d4c5b0}.disabled\:hover\:bg-transparent:disabled:hover{background-color:#0000}}@media(min-width:40rem){.sm\:w-auto{width:auto}.sm\:flex-shrink-0{flex-shrink:0}.sm\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.sm\:flex-row{flex-direction:row}.sm\:items-center{align-items:center}.sm\:justify-between{justify-content:space-between}.sm\:px-4{padding-inline:calc(var(--spacing) * 4)}}}:root{--bg:#e8dfd0;--bg-surface:#f0ebe1;--bg-shelf:#ddd3c2;--text:#2c1810;--text-muted:#8b7355;--accent:#8b4513;--accent-dim:#6b3410;--border:#d4c5b0;--error:#c33;--paper-bg:#f5f0e8}body{background:var(--bg);color:var(--text);-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-family:Inter,system-ui,-apple-system,sans-serif}::selection{background:var(--accent);color:#fff}h1,h2,h3,h4{font-family:Lora,Georgia,Times New Roman,serif}.prose{--tw-prose-body:var(--text);--tw-prose-headings:var(--text);--tw-prose-links:var(--accent);--tw-prose-bold:var(--text);--tw-prose-quotes:var(--text-muted);--tw-prose-quote-borders:var(--border);--tw-prose-code:var(--text);--tw-prose-hr:var(--border)}.prose,.prose p,.prose li,.prose blockquote{font-family:Lora,Georgia,Times New Roman,serif}code,pre{font-family:Geist Mono,ui-monospace,monospace}.cartoon-awaiting-upload{border-color:var(--accent)}@supports (color:color-mix(in lab,red,red)){.cartoon-awaiting-upload{border-color:color-mix(in srgb,var(--accent) 30%,transparent)}}.cartoon-awaiting-upload{background:var(--accent)}@supports (color:color-mix(in lab,red,red)){.cartoon-awaiting-upload{background:color-mix(in srgb,var(--accent) 5%,transparent)}}.xterm .xterm-dim{opacity:1!important;color:#8b7355!important}.xterm,.xterm-viewport{border:none!important;outline:none!important}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-space-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-leading{syntax:"*";inherits:false}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-tracking{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false} + */.xterm{cursor:text;position:relative;user-select:none;-ms-user-select:none;-webkit-user-select:none}.xterm.focus,.xterm:focus{outline:none}.xterm .xterm-helpers{position:absolute;top:0;z-index:5}.xterm .xterm-helper-textarea{padding:0;border:0;margin:0;position:absolute;opacity:0;left:-9999em;top:0;width:0;height:0;z-index:-5;white-space:nowrap;overflow:hidden;resize:none}.xterm .composition-view{background:#000;color:#fff;display:none;position:absolute;white-space:nowrap;z-index:1}.xterm .composition-view.active{display:block}.xterm .xterm-viewport{background-color:#000;overflow-y:scroll;cursor:default;position:absolute;right:0;left:0;top:0;bottom:0}.xterm .xterm-screen{position:relative}.xterm .xterm-screen canvas{position:absolute;left:0;top:0}.xterm-char-measure-element{display:inline-block;visibility:hidden;position:absolute;top:0;left:-9999em;line-height:normal}.xterm.enable-mouse-events{cursor:default}.xterm.xterm-cursor-pointer,.xterm .xterm-cursor-pointer{cursor:pointer}.xterm.column-select.focus{cursor:crosshair}.xterm .xterm-accessibility:not(.debug),.xterm .xterm-message{position:absolute;left:0;top:0;bottom:0;right:0;z-index:10;color:transparent;pointer-events:none}.xterm .xterm-accessibility-tree:not(.debug) *::selection{color:transparent}.xterm .xterm-accessibility-tree{font-family:monospace;-webkit-user-select:text;user-select:text;white-space:pre}.xterm .xterm-accessibility-tree>div{transform-origin:left;width:fit-content}.xterm .live-region{position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden}.xterm-dim{opacity:1!important}.xterm-underline-1{text-decoration:underline}.xterm-underline-2{text-decoration:double underline}.xterm-underline-3{text-decoration:wavy underline}.xterm-underline-4{text-decoration:dotted underline}.xterm-underline-5{text-decoration:dashed underline}.xterm-overline{text-decoration:overline}.xterm-overline.xterm-underline-1{text-decoration:overline underline}.xterm-overline.xterm-underline-2{text-decoration:overline double underline}.xterm-overline.xterm-underline-3{text-decoration:overline wavy underline}.xterm-overline.xterm-underline-4{text-decoration:overline dotted underline}.xterm-overline.xterm-underline-5{text-decoration:overline dashed underline}.xterm-strikethrough{text-decoration:line-through}.xterm-screen .xterm-decoration-container .xterm-decoration{z-index:6;position:absolute}.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer{z-index:7}.xterm-decoration-overview-ruler{z-index:8;position:absolute;top:0;right:0;pointer-events:none}.xterm-decoration-top{z-index:2;position:relative}.xterm .xterm-scrollable-element>.scrollbar{cursor:default}.xterm .xterm-scrollable-element>.scrollbar>.scra{cursor:pointer;font-size:11px!important}.xterm .xterm-scrollable-element>.visible{opacity:1;background:#0000;transition:opacity .1s linear;z-index:11}.xterm .xterm-scrollable-element>.invisible{opacity:0;pointer-events:none}.xterm .xterm-scrollable-element>.invisible.fade{transition:opacity .8s linear}.xterm .xterm-scrollable-element>.shadow{position:absolute;display:none}.xterm .xterm-scrollable-element>.shadow.top{display:block;top:0;left:3px;height:3px;width:100%;box-shadow:var(--vscode-scrollbar-shadow, #000) 0 6px 6px -6px inset}.xterm .xterm-scrollable-element>.shadow.left{display:block;top:3px;left:0;height:100%;width:3px;box-shadow:var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset}.xterm .xterm-scrollable-element>.shadow.top-left-corner{display:block;top:0;left:0;height:3px;width:3px}.xterm .xterm-scrollable-element>.shadow.top.left{box-shadow:var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset}/*! tailwindcss v4.2.2 | MIT License | https://tailwindcss.com */@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-space-y-reverse:0;--tw-border-style:solid;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial}}}@layer theme{:root,:host{--font-sans:ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--font-serif:ui-serif, Georgia, Cambria, "Times New Roman", Times, serif;--font-mono:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--color-red-700:oklch(50.5% .213 27.518);--color-amber-50:oklch(98.7% .022 95.277);--color-amber-100:oklch(96.2% .059 95.617);--color-amber-300:oklch(87.9% .169 91.605);--color-amber-500:oklch(76.9% .188 70.08);--color-amber-600:oklch(66.6% .179 58.318);--color-amber-700:oklch(55.5% .163 48.998);--color-amber-800:oklch(47.3% .137 46.201);--color-amber-950:oklch(27.9% .077 45.635);--color-green-50:oklch(98.2% .018 155.826);--color-green-100:oklch(96.2% .044 156.743);--color-green-300:oklch(87.1% .15 154.449);--color-green-600:oklch(62.7% .194 149.214);--color-green-700:oklch(52.7% .154 150.069);--color-green-800:oklch(44.8% .119 151.328);--color-green-950:oklch(26.6% .065 152.934);--color-white:#fff;--spacing:.25rem;--container-sm:24rem;--container-md:28rem;--container-lg:32rem;--container-xl:36rem;--container-2xl:42rem;--text-xs:.75rem;--text-xs--line-height:calc(1 / .75);--text-sm:.875rem;--text-sm--line-height:calc(1.25 / .875);--text-base:1rem;--text-base--line-height: 1.5 ;--text-lg:1.125rem;--text-lg--line-height:calc(1.75 / 1.125);--text-2xl:1.5rem;--text-2xl--line-height:calc(2 / 1.5);--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--font-weight-bold:700;--tracking-tight:-.025em;--tracking-wider:.05em;--leading-tight:1.25;--leading-relaxed:1.625;--radius-md:.375rem;--radius-lg:.5rem;--radius-xl:.75rem;--aspect-video:16 / 9;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;-moz-tab-size:4;tab-size:4;font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent;font-family:Inter,system-ui,-apple-system,sans-serif;line-height:1.5}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab,red,red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){-webkit-appearance:button;-moz-appearance:button;appearance:button}::file-selector-button{-webkit-appearance:button;-moz-appearance:button;appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer components;@layer utilities{.pointer-events-none{pointer-events:none}.collapse{visibility:collapse}.invisible{visibility:hidden}.visible{visibility:visible}.sr-only{clip-path:inset(50%);white-space:nowrap;border-width:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.inset-0{inset:calc(var(--spacing) * 0)}.start{inset-inline-start:var(--spacing)}.start\!{inset-inline-start:var(--spacing)!important}.end{inset-inline-end:var(--spacing)}.-top-1\.5{top:calc(var(--spacing) * -1.5)}.top-1{top:calc(var(--spacing) * 1)}.-right-1\.5{right:calc(var(--spacing) * -1.5)}.right-0{right:calc(var(--spacing) * 0)}.right-1{right:calc(var(--spacing) * 1)}.bottom-0{bottom:calc(var(--spacing) * 0)}.z-10{z-index:10}.z-50{z-index:50}.container{width:100%}@media(min-width:40rem){.container{max-width:40rem}}@media(min-width:48rem){.container{max-width:48rem}}@media(min-width:64rem){.container{max-width:64rem}}@media(min-width:80rem){.container{max-width:80rem}}@media(min-width:96rem){.container{max-width:96rem}}.m-3{margin:calc(var(--spacing) * 3)}.-mx-1{margin-inline:calc(var(--spacing) * -1)}.mx-auto{margin-inline:auto}.prose{color:var(--tw-prose-body);max-width:65ch}.prose :where(p):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em;margin-bottom:1.25em}.prose :where([class~=lead]):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-lead);margin-top:1.2em;margin-bottom:1.2em;font-size:1.25em;line-height:1.6}.prose :where(a):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-links);font-weight:500;text-decoration:underline}.prose :where(strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-bold);font-weight:600}.prose :where(a strong):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(blockquote strong):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(thead th strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit}.prose :where(ol):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em;margin-bottom:1.25em;padding-inline-start:1.625em;list-style-type:decimal}.prose :where(ol[type=A]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:upper-alpha}.prose :where(ol[type=a]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:lower-alpha}.prose :where(ol[type=A s]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:upper-alpha}.prose :where(ol[type=a s]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:lower-alpha}.prose :where(ol[type=I]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:upper-roman}.prose :where(ol[type=i]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:lower-roman}.prose :where(ol[type=I s]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:upper-roman}.prose :where(ol[type=i s]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:lower-roman}.prose :where(ol[type="1"]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:decimal}.prose :where(ul):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em;margin-bottom:1.25em;padding-inline-start:1.625em;list-style-type:disc}.prose :where(ol>li):not(:where([class~=not-prose],[class~=not-prose] *))::marker{color:var(--tw-prose-counters);font-weight:400}.prose :where(ul>li):not(:where([class~=not-prose],[class~=not-prose] *))::marker{color:var(--tw-prose-bullets)}.prose :where(dt):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);margin-top:1.25em;font-weight:600}.prose :where(hr):not(:where([class~=not-prose],[class~=not-prose] *)){border-color:var(--tw-prose-hr);border-top-width:1px;margin-top:3em;margin-bottom:3em}.prose :where(blockquote):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-quotes);border-inline-start-width:.25rem;border-inline-start-color:var(--tw-prose-quote-borders);quotes:"“""”""‘""’";margin-top:1.6em;margin-bottom:1.6em;padding-inline-start:1em;font-style:italic;font-weight:500}.prose :where(blockquote p:first-of-type):not(:where([class~=not-prose],[class~=not-prose] *)):before{content:open-quote}.prose :where(blockquote p:last-of-type):not(:where([class~=not-prose],[class~=not-prose] *)):after{content:close-quote}.prose :where(h1):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);margin-top:0;margin-bottom:.888889em;font-size:2.25em;font-weight:800;line-height:1.11111}.prose :where(h1 strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-weight:900}.prose :where(h2):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);margin-top:2em;margin-bottom:1em;font-size:1.5em;font-weight:700;line-height:1.33333}.prose :where(h2 strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-weight:800}.prose :where(h3):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);margin-top:1.6em;margin-bottom:.6em;font-size:1.25em;font-weight:600;line-height:1.6}.prose :where(h3 strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-weight:700}.prose :where(h4):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);margin-top:1.5em;margin-bottom:.5em;font-weight:600;line-height:1.5}.prose :where(h4 strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-weight:700}.prose :where(img):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:2em;margin-bottom:2em}.prose :where(picture):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:2em;margin-bottom:2em;display:block}.prose :where(video):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:2em;margin-bottom:2em}.prose :where(kbd):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-kbd);box-shadow:0 0 0 1px var(--tw-prose-kbd-shadows),0 3px 0 var(--tw-prose-kbd-shadows);padding-top:.1875em;padding-inline-end:.375em;padding-bottom:.1875em;border-radius:.3125rem;padding-inline-start:.375em;font-family:inherit;font-size:.875em;font-weight:500}.prose :where(code):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-code);font-size:.875em;font-weight:600}.prose :where(code):not(:where([class~=not-prose],[class~=not-prose] *)):before,.prose :where(code):not(:where([class~=not-prose],[class~=not-prose] *)):after{content:"`"}.prose :where(a code):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(h1 code):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit}.prose :where(h2 code):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-size:.875em}.prose :where(h3 code):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-size:.9em}.prose :where(h4 code):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(blockquote code):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(thead th code):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit}.prose :where(pre):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-pre-code);background-color:var(--tw-prose-pre-bg);padding-top:.857143em;padding-inline-end:1.14286em;padding-bottom:.857143em;border-radius:.375rem;margin-top:1.71429em;margin-bottom:1.71429em;padding-inline-start:1.14286em;font-size:.875em;font-weight:400;line-height:1.71429;overflow-x:auto}.prose :where(pre code):not(:where([class~=not-prose],[class~=not-prose] *)){font-weight:inherit;color:inherit;font-size:inherit;font-family:inherit;line-height:inherit;background-color:#0000;border-width:0;border-radius:0;padding:0}.prose :where(pre code):not(:where([class~=not-prose],[class~=not-prose] *)):before,.prose :where(pre code):not(:where([class~=not-prose],[class~=not-prose] *)):after{content:none}.prose :where(table):not(:where([class~=not-prose],[class~=not-prose] *)){table-layout:auto;width:100%;margin-top:2em;margin-bottom:2em;font-size:.875em;line-height:1.71429}.prose :where(thead):not(:where([class~=not-prose],[class~=not-prose] *)){border-bottom-width:1px;border-bottom-color:var(--tw-prose-th-borders)}.prose :where(thead th):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);vertical-align:bottom;padding-inline-end:.571429em;padding-bottom:.571429em;padding-inline-start:.571429em;font-weight:600}.prose :where(tbody tr):not(:where([class~=not-prose],[class~=not-prose] *)){border-bottom-width:1px;border-bottom-color:var(--tw-prose-td-borders)}.prose :where(tbody tr:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){border-bottom-width:0}.prose :where(tbody td):not(:where([class~=not-prose],[class~=not-prose] *)){vertical-align:baseline}.prose :where(tfoot):not(:where([class~=not-prose],[class~=not-prose] *)){border-top-width:1px;border-top-color:var(--tw-prose-th-borders)}.prose :where(tfoot td):not(:where([class~=not-prose],[class~=not-prose] *)){vertical-align:top}.prose :where(th,td):not(:where([class~=not-prose],[class~=not-prose] *)){text-align:start}.prose :where(figure>*):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:0;margin-bottom:0}.prose :where(figcaption):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-captions);margin-top:.857143em;font-size:.875em;line-height:1.42857}.prose{--tw-prose-body:oklch(37.3% .034 259.733);--tw-prose-headings:oklch(21% .034 264.665);--tw-prose-lead:oklch(44.6% .03 256.802);--tw-prose-links:oklch(21% .034 264.665);--tw-prose-bold:oklch(21% .034 264.665);--tw-prose-counters:oklch(55.1% .027 264.364);--tw-prose-bullets:oklch(87.2% .01 258.338);--tw-prose-hr:oklch(92.8% .006 264.531);--tw-prose-quotes:oklch(21% .034 264.665);--tw-prose-quote-borders:oklch(92.8% .006 264.531);--tw-prose-captions:oklch(55.1% .027 264.364);--tw-prose-kbd:oklch(21% .034 264.665);--tw-prose-kbd-shadows:oklab(21% -.00316127 -.0338527/.1);--tw-prose-code:oklch(21% .034 264.665);--tw-prose-pre-code:oklch(92.8% .006 264.531);--tw-prose-pre-bg:oklch(27.8% .033 256.848);--tw-prose-th-borders:oklch(87.2% .01 258.338);--tw-prose-td-borders:oklch(92.8% .006 264.531);--tw-prose-invert-body:oklch(87.2% .01 258.338);--tw-prose-invert-headings:#fff;--tw-prose-invert-lead:oklch(70.7% .022 261.325);--tw-prose-invert-links:#fff;--tw-prose-invert-bold:#fff;--tw-prose-invert-counters:oklch(70.7% .022 261.325);--tw-prose-invert-bullets:oklch(44.6% .03 256.802);--tw-prose-invert-hr:oklch(37.3% .034 259.733);--tw-prose-invert-quotes:oklch(96.7% .003 264.542);--tw-prose-invert-quote-borders:oklch(37.3% .034 259.733);--tw-prose-invert-captions:oklch(70.7% .022 261.325);--tw-prose-invert-kbd:#fff;--tw-prose-invert-kbd-shadows:#ffffff1a;--tw-prose-invert-code:#fff;--tw-prose-invert-pre-code:oklch(87.2% .01 258.338);--tw-prose-invert-pre-bg:#00000080;--tw-prose-invert-th-borders:oklch(44.6% .03 256.802);--tw-prose-invert-td-borders:oklch(37.3% .034 259.733);font-size:1rem;line-height:1.75}.prose :where(picture>img):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:0;margin-bottom:0}.prose :where(li):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:.5em;margin-bottom:.5em}.prose :where(ol>li):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(ul>li):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-start:.375em}.prose :where(.prose>ul>li p):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:.75em;margin-bottom:.75em}.prose :where(.prose>ul>li>p:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em}.prose :where(.prose>ul>li>p:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-bottom:1.25em}.prose :where(.prose>ol>li>p:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em}.prose :where(.prose>ol>li>p:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-bottom:1.25em}.prose :where(ul ul,ul ol,ol ul,ol ol):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:.75em;margin-bottom:.75em}.prose :where(dl):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em;margin-bottom:1.25em}.prose :where(dd):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:.5em;padding-inline-start:1.625em}.prose :where(hr+*):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(h2+*):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(h3+*):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(h4+*):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:0}.prose :where(thead th:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-start:0}.prose :where(thead th:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-end:0}.prose :where(tbody td,tfoot td):not(:where([class~=not-prose],[class~=not-prose] *)){padding-top:.571429em;padding-inline-end:.571429em;padding-bottom:.571429em;padding-inline-start:.571429em}.prose :where(tbody td:first-child,tfoot td:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-start:0}.prose :where(tbody td:last-child,tfoot td:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-end:0}.prose :where(figure):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:2em;margin-bottom:2em}.prose :where(.prose>:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:0}.prose :where(.prose>:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-bottom:0}.mt-0\.5{margin-top:calc(var(--spacing) * .5)}.mt-1{margin-top:calc(var(--spacing) * 1)}.mt-1\.5{margin-top:calc(var(--spacing) * 1.5)}.mt-2{margin-top:calc(var(--spacing) * 2)}.mt-3{margin-top:calc(var(--spacing) * 3)}.mt-4{margin-top:calc(var(--spacing) * 4)}.mb-1{margin-bottom:calc(var(--spacing) * 1)}.mb-1\.5{margin-bottom:calc(var(--spacing) * 1.5)}.mb-2{margin-bottom:calc(var(--spacing) * 2)}.mb-3{margin-bottom:calc(var(--spacing) * 3)}.mb-4{margin-bottom:calc(var(--spacing) * 4)}.mb-6{margin-bottom:calc(var(--spacing) * 6)}.ml-0\.5{margin-left:calc(var(--spacing) * .5)}.ml-1{margin-left:calc(var(--spacing) * 1)}.ml-2{margin-left:calc(var(--spacing) * 2)}.ml-3{margin-left:calc(var(--spacing) * 3)}.ml-auto{margin-left:auto}.block{display:block}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline{display:inline}.inline-flex{display:inline-flex}.table{display:table}.aspect-video{aspect-ratio:var(--aspect-video)}.h-0\.5{height:calc(var(--spacing) * .5)}.h-1\.5{height:calc(var(--spacing) * 1.5)}.h-2{height:calc(var(--spacing) * 2)}.h-4{height:calc(var(--spacing) * 4)}.h-5{height:calc(var(--spacing) * 5)}.h-14{height:calc(var(--spacing) * 14)}.h-16{height:calc(var(--spacing) * 16)}.h-24{height:calc(var(--spacing) * 24)}.h-\[calc\(100vh-3\.5rem\)\]{height:calc(100vh - 3.5rem)}.h-full{height:100%}.h-screen{height:100vh}.max-h-72{max-height:calc(var(--spacing) * 72)}.min-h-0{min-height:calc(var(--spacing) * 0)}.min-h-28{min-height:calc(var(--spacing) * 28)}.min-h-56{min-height:calc(var(--spacing) * 56)}.min-h-\[11rem\]{min-height:11rem}.min-h-\[14rem\]{min-height:14rem}.min-h-\[22rem\]{min-height:22rem}.w-0\.5{width:calc(var(--spacing) * .5)}.w-1\.5{width:calc(var(--spacing) * 1.5)}.w-2{width:calc(var(--spacing) * 2)}.w-4{width:calc(var(--spacing) * 4)}.w-5{width:calc(var(--spacing) * 5)}.w-14{width:calc(var(--spacing) * 14)}.w-16{width:calc(var(--spacing) * 16)}.w-56{width:calc(var(--spacing) * 56)}.w-64{width:calc(var(--spacing) * 64)}.w-full{width:100%}.max-w-2xl{max-width:var(--container-2xl)}.max-w-\[32rem\]{max-width:32rem}.max-w-\[120px\]{max-width:120px}.max-w-lg{max-width:var(--container-lg)}.max-w-md{max-width:var(--container-md)}.max-w-none{max-width:none}.max-w-sm{max-width:var(--container-sm)}.max-w-xl{max-width:var(--container-xl)}.min-w-0{min-width:calc(var(--spacing) * 0)}.min-w-\[140px\]{min-width:140px}.flex-1{flex:1}.flex-shrink-0{flex-shrink:0}.shrink{flex-shrink:1}.shrink-0{flex-shrink:0}.transform{transform:var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,)}.cursor-move{cursor:move}.cursor-pointer{cursor:pointer}.cursor-se-resize{cursor:se-resize}.resize{resize:both}.resize-none{resize:none}.resize-y{resize:vertical}.list-inside{list-style-position:inside}.list-decimal{list-style-type:decimal}.list-disc{list-style-type:disc}.list-none{list-style-type:none}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-baseline{align-items:baseline}.items-center{align-items:center}.items-start{align-items:flex-start}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.justify-end{justify-content:flex-end}.gap-0\.5{gap:calc(var(--spacing) * .5)}.gap-1{gap:calc(var(--spacing) * 1)}.gap-1\.5{gap:calc(var(--spacing) * 1.5)}.gap-2{gap:calc(var(--spacing) * 2)}.gap-3{gap:calc(var(--spacing) * 3)}.gap-4{gap:calc(var(--spacing) * 4)}:where(.space-y-0\.5>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * .5) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * .5) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-1>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 1) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 1) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-1\.5>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 1.5) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 1.5) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-2>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 2) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 2) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-3>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 3) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 3) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-4>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 4) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 4) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-6>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 6) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 6) * calc(1 - var(--tw-space-y-reverse)))}.gap-x-3{column-gap:calc(var(--spacing) * 3)}.gap-y-0\.5{row-gap:calc(var(--spacing) * .5)}.gap-y-1{row-gap:calc(var(--spacing) * 1)}.self-start{align-self:flex-start}.truncate{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.rounded{border-radius:.25rem}.rounded-full{border-radius:3.40282e38px}.rounded-lg{border-radius:var(--radius-lg)}.rounded-md{border-radius:var(--radius-md)}.rounded-xl{border-radius:var(--radius-xl)}.border{border-style:var(--tw-border-style);border-width:1px}.border-2{border-style:var(--tw-border-style);border-width:2px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-r{border-right-style:var(--tw-border-style);border-right-width:1px}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-b-2{border-bottom-style:var(--tw-border-style);border-bottom-width:2px}.border-l{border-left-style:var(--tw-border-style);border-left-width:1px}.border-l-2{border-left-style:var(--tw-border-style);border-left-width:2px}.border-dashed{--tw-border-style:dashed;border-style:dashed}.border-accent{border-color:#8b4513}.border-accent-dim\/30{border-color:#6b34104d}.border-accent\/30{border-color:#8b45134d}.border-accent\/40{border-color:#8b451366}.border-amber-300{border-color:var(--color-amber-300)}.border-amber-500{border-color:var(--color-amber-500)}.border-amber-500\/40{border-color:#f99c0066}@supports (color:color-mix(in lab,red,red)){.border-amber-500\/40{border-color:color-mix(in oklab,var(--color-amber-500) 40%,transparent)}}.border-amber-500\/50{border-color:#f99c0080}@supports (color:color-mix(in lab,red,red)){.border-amber-500\/50{border-color:color-mix(in oklab,var(--color-amber-500) 50%,transparent)}}.border-amber-600\/30{border-color:#dd74004d}@supports (color:color-mix(in lab,red,red)){.border-amber-600\/30{border-color:color-mix(in oklab,var(--color-amber-600) 30%,transparent)}}.border-border{border-color:#d4c5b0}.border-border\/70{border-color:#d4c5b0b3}.border-border\/80{border-color:#d4c5b0cc}.border-error\/15{border-color:#cc333326}.border-error\/30{border-color:#cc33334d}.border-error\/40{border-color:#c336}.border-foreground\/40{border-color:#2c181066}.border-green-300{border-color:var(--color-green-300)}.border-green-700\/20{border-color:#00813833}@supports (color:color-mix(in lab,red,red)){.border-green-700\/20{border-color:color-mix(in oklab,var(--color-green-700) 20%,transparent)}}.border-green-700\/25{border-color:#00813840}@supports (color:color-mix(in lab,red,red)){.border-green-700\/25{border-color:color-mix(in oklab,var(--color-green-700) 25%,transparent)}}.border-green-700\/30{border-color:#0081384d}@supports (color:color-mix(in lab,red,red)){.border-green-700\/30{border-color:color-mix(in oklab,var(--color-green-700) 30%,transparent)}}.border-green-700\/40{border-color:#00813866}@supports (color:color-mix(in lab,red,red)){.border-green-700\/40{border-color:color-mix(in oklab,var(--color-green-700) 40%,transparent)}}.border-muted\/40{border-color:#8b735566}.border-red-700\/30{border-color:#bf000f4d}@supports (color:color-mix(in lab,red,red)){.border-red-700\/30{border-color:color-mix(in oklab,var(--color-red-700) 30%,transparent)}}.border-transparent{border-color:#0000}.bg-\[\#f4efe6\]\/85{background-color:#f4efe6d9}.bg-\[\#f8f5ef\]{background-color:#f8f5ef}.bg-accent{background-color:#8b4513}.bg-accent\/5{background-color:#8b45130d}.bg-accent\/10{background-color:#8b45131a}.bg-amber-50{background-color:var(--color-amber-50)}.bg-amber-100{background-color:var(--color-amber-100)}.bg-amber-500{background-color:var(--color-amber-500)}.bg-amber-500\/10{background-color:#f99c001a}@supports (color:color-mix(in lab,red,red)){.bg-amber-500\/10{background-color:color-mix(in oklab,var(--color-amber-500) 10%,transparent)}}.bg-amber-950\/10{background-color:#4619011a}@supports (color:color-mix(in lab,red,red)){.bg-amber-950\/10{background-color:color-mix(in oklab,var(--color-amber-950) 10%,transparent)}}.bg-background{background-color:#e8dfd0}.bg-background\/40{background-color:#e8dfd066}.bg-background\/50{background-color:#e8dfd080}.bg-background\/60{background-color:#e8dfd099}.bg-background\/70{background-color:#e8dfd0b3}.bg-background\/95{background-color:#e8dfd0f2}.bg-error{background-color:#c33}.bg-error\/5{background-color:#cc33330d}.bg-error\/10{background-color:#cc33331a}.bg-foreground{background-color:#2c1810}.bg-green-50{background-color:var(--color-green-50)}.bg-green-100{background-color:var(--color-green-100)}.bg-green-600{background-color:var(--color-green-600)}.bg-green-600\/10{background-color:#00a5441a}@supports (color:color-mix(in lab,red,red)){.bg-green-600\/10{background-color:color-mix(in oklab,var(--color-green-600) 10%,transparent)}}.bg-green-700\/10{background-color:#0081381a}@supports (color:color-mix(in lab,red,red)){.bg-green-700\/10{background-color:color-mix(in oklab,var(--color-green-700) 10%,transparent)}}.bg-green-950\/5{background-color:#032e150d}@supports (color:color-mix(in lab,red,red)){.bg-green-950\/5{background-color:color-mix(in oklab,var(--color-green-950) 5%,transparent)}}.bg-muted\/40{background-color:#8b735566}.bg-muted\/50{background-color:#8b735580}.bg-surface{background-color:#f0ebe1}.bg-surface\/35{background-color:#f0ebe159}.bg-surface\/40{background-color:#f0ebe166}.bg-surface\/50{background-color:#f0ebe180}.bg-surface\/60{background-color:#f0ebe199}.bg-surface\/70{background-color:#f0ebe1b3}.bg-surface\/80{background-color:#f0ebe1cc}.bg-surface\/95{background-color:#f0ebe1f2}.bg-transparent{background-color:#0000}.bg-white{background-color:var(--color-white)}.fill-white\/95{fill:#fffffff2}@supports (color:color-mix(in lab,red,red)){.fill-white\/95{fill:color-mix(in oklab,var(--color-white) 95%,transparent)}}.stroke-\[\#1a1a1a\]{stroke:#1a1a1a}.stroke-accent{stroke:#8b4513}.object-contain{object-fit:contain}.object-cover{object-fit:cover}.p-1\.5{padding:calc(var(--spacing) * 1.5)}.p-2{padding:calc(var(--spacing) * 2)}.p-3{padding:calc(var(--spacing) * 3)}.p-4{padding:calc(var(--spacing) * 4)}.p-6{padding:calc(var(--spacing) * 6)}.p-8{padding:calc(var(--spacing) * 8)}.px-1{padding-inline:calc(var(--spacing) * 1)}.px-1\.5{padding-inline:calc(var(--spacing) * 1.5)}.px-2{padding-inline:calc(var(--spacing) * 2)}.px-2\.5{padding-inline:calc(var(--spacing) * 2.5)}.px-3{padding-inline:calc(var(--spacing) * 3)}.px-4{padding-inline:calc(var(--spacing) * 4)}.px-6{padding-inline:calc(var(--spacing) * 6)}.py-0\.5{padding-block:calc(var(--spacing) * .5)}.py-1{padding-block:calc(var(--spacing) * 1)}.py-1\.5{padding-block:calc(var(--spacing) * 1.5)}.py-2{padding-block:calc(var(--spacing) * 2)}.py-2\.5{padding-block:calc(var(--spacing) * 2.5)}.py-3{padding-block:calc(var(--spacing) * 3)}.py-4{padding-block:calc(var(--spacing) * 4)}.py-6{padding-block:calc(var(--spacing) * 6)}.pt-1\.5{padding-top:calc(var(--spacing) * 1.5)}.pt-2{padding-top:calc(var(--spacing) * 2)}.pt-3{padding-top:calc(var(--spacing) * 3)}.pr-16{padding-right:calc(var(--spacing) * 16)}.pb-1{padding-bottom:calc(var(--spacing) * 1)}.pb-3{padding-bottom:calc(var(--spacing) * 3)}.pl-3{padding-left:calc(var(--spacing) * 3)}.pl-4{padding-left:calc(var(--spacing) * 4)}.text-center{text-align:center}.text-left{text-align:left}.font-mono{font-family:var(--font-mono)}.font-sans{font-family:var(--font-sans)}.font-serif{font-family:var(--font-serif)}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-base{font-size:var(--text-base);line-height:var(--tw-leading,var(--text-base--line-height))}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.text-\[9px\]{font-size:9px}.text-\[10px\]{font-size:10px}.text-\[11px\]{font-size:11px}.leading-none{--tw-leading:1;line-height:1}.leading-relaxed{--tw-leading:var(--leading-relaxed);line-height:var(--leading-relaxed)}.leading-tight{--tw-leading:var(--leading-tight);line-height:var(--leading-tight)}.font-bold{--tw-font-weight:var(--font-weight-bold);font-weight:var(--font-weight-bold)}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-normal{--tw-font-weight:var(--font-weight-normal);font-weight:var(--font-weight-normal)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-\[0\.14em\]{--tw-tracking:.14em;letter-spacing:.14em}.tracking-\[0\.16em\]{--tw-tracking:.16em;letter-spacing:.16em}.tracking-\[0\.18em\]{--tw-tracking:.18em;letter-spacing:.18em}.tracking-tight{--tw-tracking:var(--tracking-tight);letter-spacing:var(--tracking-tight)}.tracking-wider{--tw-tracking:var(--tracking-wider);letter-spacing:var(--tracking-wider)}.break-words{overflow-wrap:break-word}.break-all{word-break:break-all}.whitespace-nowrap{white-space:nowrap}.whitespace-pre-wrap{white-space:pre-wrap}.text-\[\#1a1a1a\]{color:#1a1a1a}.text-\[\#3a3a3a\]{color:#3a3a3a}.text-accent{color:#8b4513}.text-accent-dim{color:#6b3410}.text-amber-600{color:var(--color-amber-600)}.text-amber-700{color:var(--color-amber-700)}.text-amber-800{color:var(--color-amber-800)}.text-background{color:#e8dfd0}.text-error{color:#c33}.text-error\/70{color:#cc3333b3}.text-foreground{color:#2c1810}.text-green-700{color:var(--color-green-700)}.text-green-800{color:var(--color-green-800)}.text-muted{color:#8b7355}.text-muted\/70{color:#8b7355b3}.text-red-700{color:var(--color-red-700)}.text-white{color:var(--color-white)}.uppercase{text-transform:uppercase}.italic{font-style:italic}.overline{text-decoration-line:overline}.underline{text-decoration-line:underline}.opacity-90{opacity:.9}.shadow{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a), 0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a), 0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-sm{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a), 0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring-2{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring-accent{--tw-ring-color:#8b4513}.ring-amber-500{--tw-ring-color:var(--color-amber-500)}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.blur{--tw-blur:blur(8px);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.filter{filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.backdrop-blur{--tw-backdrop-blur:blur(8px);-webkit-backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.outline-none{--tw-outline-style:none;outline-style:none}.select-none{-webkit-user-select:none;user-select:none}.placeholder\:text-muted\/50::placeholder{color:#8b735580}@media(hover:hover){.hover\:border-accent:hover{border-color:#8b4513}.hover\:border-error:hover{border-color:#c33}.hover\:bg-accent-dim:hover{background-color:#6b3410}.hover\:bg-accent\/5:hover{background-color:#8b45130d}.hover\:bg-accent\/10:hover{background-color:#8b45131a}.hover\:bg-amber-500\/20:hover{background-color:#f99c0033}@supports (color:color-mix(in lab,red,red)){.hover\:bg-amber-500\/20:hover{background-color:color-mix(in oklab,var(--color-amber-500) 20%,transparent)}}.hover\:bg-border\/50:hover{background-color:#d4c5b080}.hover\:bg-error\/5:hover{background-color:#cc33330d}.hover\:bg-error\/10:hover{background-color:#cc33331a}.hover\:bg-green-700\/5:hover{background-color:#0081380d}@supports (color:color-mix(in lab,red,red)){.hover\:bg-green-700\/5:hover{background-color:color-mix(in oklab,var(--color-green-700) 5%,transparent)}}.hover\:bg-surface:hover{background-color:#f0ebe1}.hover\:bg-surface\/50:hover{background-color:#f0ebe180}.hover\:text-accent:hover{color:#8b4513}.hover\:text-accent-dim:hover{color:#6b3410}.hover\:text-error:hover{color:#c33}.hover\:text-foreground:hover{color:#2c1810}.hover\:underline:hover{text-decoration-line:underline}.hover\:opacity-80:hover{opacity:.8}}.focus\:border-accent:focus{border-color:#8b4513}.focus\:outline-none:focus{--tw-outline-style:none;outline-style:none}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-40:disabled{opacity:.4}.disabled\:opacity-50:disabled{opacity:.5}@media(hover:hover){.disabled\:hover\:border-border:disabled:hover{border-color:#d4c5b0}.disabled\:hover\:bg-transparent:disabled:hover{background-color:#0000}}@media(min-width:40rem){.sm\:w-auto{width:auto}.sm\:flex-shrink-0{flex-shrink:0}.sm\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.sm\:flex-row{flex-direction:row}.sm\:items-center{align-items:center}.sm\:justify-between{justify-content:space-between}.sm\:px-4{padding-inline:calc(var(--spacing) * 4)}}@media(min-width:48rem){.md\:min-h-40{min-height:calc(var(--spacing) * 40)}.md\:min-h-\[13rem\]{min-height:13rem}.md\:min-h-\[18rem\]{min-height:18rem}}@media(min-width:80rem){.xl\:min-h-\[21rem\]{min-height:21rem}}}:root{--bg:#e8dfd0;--bg-surface:#f0ebe1;--bg-shelf:#ddd3c2;--text:#2c1810;--text-muted:#8b7355;--accent:#8b4513;--accent-dim:#6b3410;--border:#d4c5b0;--error:#c33;--paper-bg:#f5f0e8}body{background:var(--bg);color:var(--text);-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-family:Inter,system-ui,-apple-system,sans-serif}::selection{background:var(--accent);color:#fff}h1,h2,h3,h4{font-family:Lora,Georgia,Times New Roman,serif}.prose{--tw-prose-body:var(--text);--tw-prose-headings:var(--text);--tw-prose-links:var(--accent);--tw-prose-bold:var(--text);--tw-prose-quotes:var(--text-muted);--tw-prose-quote-borders:var(--border);--tw-prose-code:var(--text);--tw-prose-hr:var(--border)}.prose,.prose p,.prose li,.prose blockquote{font-family:Lora,Georgia,Times New Roman,serif}code,pre{font-family:Geist Mono,ui-monospace,monospace}.cartoon-awaiting-upload{border-color:var(--accent)}@supports (color:color-mix(in lab,red,red)){.cartoon-awaiting-upload{border-color:color-mix(in srgb,var(--accent) 30%,transparent)}}.cartoon-awaiting-upload{background:var(--accent)}@supports (color:color-mix(in lab,red,red)){.cartoon-awaiting-upload{background:color-mix(in srgb,var(--accent) 5%,transparent)}}.xterm .xterm-dim{opacity:1!important;color:#8b7355!important}.xterm,.xterm-viewport{border:none!important;outline:none!important}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-space-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-leading{syntax:"*";inherits:false}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-tracking{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false} diff --git a/app/web/dist/assets/index-CuMJdtXy.js b/app/web/dist/assets/index-uZfLBBm_.js similarity index 65% rename from app/web/dist/assets/index-CuMJdtXy.js rename to app/web/dist/assets/index-uZfLBBm_.js index c4161d5..54dc7db 100644 --- a/app/web/dist/assets/index-CuMJdtXy.js +++ b/app/web/dist/assets/index-uZfLBBm_.js @@ -6,7 +6,7 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */var ib;function pC(){if(ib)return co;ib=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function i(s,a,o){var c=null;if(o!==void 0&&(c=""+o),a.key!==void 0&&(c=""+a.key),"key"in a){o={};for(var h in a)h!=="key"&&(o[h]=a[h])}else o=a;return a=o.ref,{$$typeof:e,type:s,key:c,ref:a!==void 0?a:null,props:o}}return co.Fragment=t,co.jsx=i,co.jsxs=i,co}var nb;function mC(){return nb||(nb=1,Vd.exports=pC()),Vd.exports}var d=mC(),Kd={exports:{}},tt={};/** + */var ib;function mC(){if(ib)return co;ib=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function i(s,a,o){var c=null;if(o!==void 0&&(c=""+o),a.key!==void 0&&(c=""+a.key),"key"in a){o={};for(var h in a)h!=="key"&&(o[h]=a[h])}else o=a;return a=o.ref,{$$typeof:e,type:s,key:c,ref:a!==void 0?a:null,props:o}}return co.Fragment=t,co.jsx=i,co.jsxs=i,co}var nb;function gC(){return nb||(nb=1,Vd.exports=mC()),Vd.exports}var d=gC(),Kd={exports:{}},it={};/** * @license React * react.production.js * @@ -14,7 +14,7 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */var rb;function gC(){if(rb)return tt;rb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),i=Symbol.for("react.fragment"),s=Symbol.for("react.strict_mode"),a=Symbol.for("react.profiler"),o=Symbol.for("react.consumer"),c=Symbol.for("react.context"),h=Symbol.for("react.forward_ref"),p=Symbol.for("react.suspense"),f=Symbol.for("react.memo"),_=Symbol.for("react.lazy"),x=Symbol.for("react.activity"),b=Symbol.iterator;function v(D){return D===null||typeof D!="object"?null:(D=b&&D[b]||D["@@iterator"],typeof D=="function"?D:null)}var S={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},N=Object.assign,M={};function E(D,X,C){this.props=D,this.context=X,this.refs=M,this.updater=C||S}E.prototype.isReactComponent={},E.prototype.setState=function(D,X){if(typeof D!="object"&&typeof D!="function"&&D!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,D,X,"setState")},E.prototype.forceUpdate=function(D){this.updater.enqueueForceUpdate(this,D,"forceUpdate")};function L(){}L.prototype=E.prototype;function I(D,X,C){this.props=D,this.context=X,this.refs=M,this.updater=C||S}var A=I.prototype=new L;A.constructor=I,N(A,E.prototype),A.isPureReactComponent=!0;var q=Array.isArray;function R(){}var ne={H:null,A:null,T:null,S:null},ue=Object.prototype.hasOwnProperty;function ye(D,X,C){var Z=C.ref;return{$$typeof:e,type:D,key:X,ref:Z!==void 0?Z:null,props:C}}function B(D,X){return ye(D.type,X,D.props)}function re(D){return typeof D=="object"&&D!==null&&D.$$typeof===e}function $(D){var X={"=":"=0",":":"=2"};return"$"+D.replace(/[=:]/g,function(C){return X[C]})}var G=/\/+/g;function V(D,X){return typeof D=="object"&&D!==null&&D.key!=null?$(""+D.key):X.toString(36)}function H(D){switch(D.status){case"fulfilled":return D.value;case"rejected":throw D.reason;default:switch(typeof D.status=="string"?D.then(R,R):(D.status="pending",D.then(function(X){D.status==="pending"&&(D.status="fulfilled",D.value=X)},function(X){D.status==="pending"&&(D.status="rejected",D.reason=X)})),D.status){case"fulfilled":return D.value;case"rejected":throw D.reason}}throw D}function T(D,X,C,Z,ae){var oe=typeof D;(oe==="undefined"||oe==="boolean")&&(D=null);var K=!1;if(D===null)K=!0;else switch(oe){case"bigint":case"string":case"number":K=!0;break;case"object":switch(D.$$typeof){case e:case t:K=!0;break;case _:return K=D._init,T(K(D._payload),X,C,Z,ae)}}if(K)return ae=ae(D),K=Z===""?"."+V(D,0):Z,q(ae)?(C="",K!=null&&(C=K.replace(G,"$&/")+"/"),T(ae,X,C,"",function(De){return De})):ae!=null&&(re(ae)&&(ae=B(ae,C+(ae.key==null||D&&D.key===ae.key?"":(""+ae.key).replace(G,"$&/")+"/")+K)),X.push(ae)),1;K=0;var he=Z===""?".":Z+":";if(q(D))for(var ge=0;ge>>1,j=T[xe];if(0>>1;xea(C,F))Za(ae,C)?(T[xe]=ae,T[Z]=F,xe=Z):(T[xe]=C,T[X]=F,xe=X);else if(Za(ae,F))T[xe]=ae,T[Z]=F,xe=Z;else break e}}return z}function a(T,z){var F=T.sortIndex-z.sortIndex;return F!==0?F:T.id-z.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var o=performance;e.unstable_now=function(){return o.now()}}else{var c=Date,h=c.now();e.unstable_now=function(){return c.now()-h}}var p=[],f=[],_=1,x=null,b=3,v=!1,S=!1,N=!1,M=!1,E=typeof setTimeout=="function"?setTimeout:null,L=typeof clearTimeout=="function"?clearTimeout:null,I=typeof setImmediate<"u"?setImmediate:null;function A(T){for(var z=i(f);z!==null;){if(z.callback===null)s(f);else if(z.startTime<=T)s(f),z.sortIndex=z.expirationTime,t(p,z);else break;z=i(f)}}function q(T){if(N=!1,A(T),!S)if(i(p)!==null)S=!0,R||(R=!0,$());else{var z=i(f);z!==null&&H(q,z.startTime-T)}}var R=!1,ne=-1,ue=5,ye=-1;function B(){return M?!0:!(e.unstable_now()-yeT&&B());){var xe=x.callback;if(typeof xe=="function"){x.callback=null,b=x.priorityLevel;var j=xe(x.expirationTime<=T);if(T=e.unstable_now(),typeof j=="function"){x.callback=j,A(T),z=!0;break t}x===i(p)&&s(p),A(T)}else s(p);x=i(p)}if(x!==null)z=!0;else{var D=i(f);D!==null&&H(q,D.startTime-T),z=!1}}break e}finally{x=null,b=F,v=!1}z=void 0}}finally{z?$():R=!1}}}var $;if(typeof I=="function")$=function(){I(re)};else if(typeof MessageChannel<"u"){var G=new MessageChannel,V=G.port2;G.port1.onmessage=re,$=function(){V.postMessage(null)}}else $=function(){E(re,0)};function H(T,z){ne=E(function(){T(e.unstable_now())},z)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(T){T.callback=null},e.unstable_forceFrameRate=function(T){0>T||125xe?(T.sortIndex=F,t(f,T),i(p)===null&&T===i(f)&&(N?(L(ne),ne=-1):N=!0,H(q,F-xe))):(T.sortIndex=j,t(p,T),S||v||(S=!0,R||(R=!0,$()))),T},e.unstable_shouldYield=B,e.unstable_wrapCallback=function(T){var z=b;return function(){var F=b;b=z;try{return T.apply(this,arguments)}finally{b=F}}}})(Qd)),Qd}var lb;function bC(){return lb||(lb=1,Zd.exports=_C()),Zd.exports}var Jd={exports:{}},ln={};/** + */var ab;function bC(){return ab||(ab=1,(function(e){function t(T,P){var q=T.length;T.push(P);e:for(;0>>1,j=T[xe];if(0>>1;xea(k,q))Ka(ae,k)?(T[xe]=ae,T[K]=q,xe=K):(T[xe]=k,T[Z]=q,xe=Z);else if(Ka(ae,q))T[xe]=ae,T[K]=q,xe=K;else break e}}return P}function a(T,P){var q=T.sortIndex-P.sortIndex;return q!==0?q:T.id-P.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var o=performance;e.unstable_now=function(){return o.now()}}else{var c=Date,h=c.now();e.unstable_now=function(){return c.now()-h}}var p=[],f=[],_=1,x=null,b=3,v=!1,S=!1,N=!1,B=!1,E=typeof setTimeout=="function"?setTimeout:null,O=typeof clearTimeout=="function"?clearTimeout:null,H=typeof setImmediate<"u"?setImmediate:null;function A(T){for(var P=i(f);P!==null;){if(P.callback===null)s(f);else if(P.startTime<=T)s(f),P.sortIndex=P.expirationTime,t(p,P);else break;P=i(f)}}function W(T){if(N=!1,A(T),!S)if(i(p)!==null)S=!0,D||(D=!0,F());else{var P=i(f);P!==null&&U(W,P.startTime-T)}}var D=!1,ne=-1,ue=5,be=-1;function L(){return B?!0:!(e.unstable_now()-beT&&L());){var xe=x.callback;if(typeof xe=="function"){x.callback=null,b=x.priorityLevel;var j=xe(x.expirationTime<=T);if(T=e.unstable_now(),typeof j=="function"){x.callback=j,A(T),P=!0;break t}x===i(p)&&s(p),A(T)}else s(p);x=i(p)}if(x!==null)P=!0;else{var R=i(f);R!==null&&U(W,R.startTime-T),P=!1}}break e}finally{x=null,b=q,v=!1}P=void 0}}finally{P?F():D=!1}}}var F;if(typeof H=="function")F=function(){H(re)};else if(typeof MessageChannel<"u"){var Y=new MessageChannel,V=Y.port2;Y.port1.onmessage=re,F=function(){V.postMessage(null)}}else F=function(){E(re,0)};function U(T,P){ne=E(function(){T(e.unstable_now())},P)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(T){T.callback=null},e.unstable_forceFrameRate=function(T){0>T||125xe?(T.sortIndex=q,t(f,T),i(p)===null&&T===i(f)&&(N?(O(ne),ne=-1):N=!0,U(W,q-xe))):(T.sortIndex=j,t(p,T),S||v||(S=!0,D||(D=!0,F()))),T},e.unstable_shouldYield=L,e.unstable_wrapCallback=function(T){var P=b;return function(){var q=b;b=P;try{return T.apply(this,arguments)}finally{b=q}}}})(Qd)),Qd}var lb;function vC(){return lb||(lb=1,Zd.exports=bC()),Zd.exports}var Jd={exports:{}},ln={};/** * @license React * react-dom.production.js * @@ -30,7 +30,7 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */var ob;function vC(){if(ob)return ln;ob=1;var e=$p();function t(p){var f="https://react.dev/errors/"+p;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Jd.exports=vC(),Jd.exports}/** + */var ob;function yC(){if(ob)return ln;ob=1;var e=$p();function t(p){var f="https://react.dev/errors/"+p;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Jd.exports=yC(),Jd.exports}/** * @license React * react-dom-client.production.js * @@ -38,15 +38,15 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */var ub;function SC(){if(ub)return uo;ub=1;var e=bC(),t=$p(),i=yC();function s(n){var r="https://react.dev/errors/"+n;if(1j||(n.current=xe[j],xe[j]=null,j--)}function C(n,r){j++,xe[j]=n.current,n.current=r}var Z=D(null),ae=D(null),oe=D(null),K=D(null);function he(n,r){switch(C(oe,r),C(ae,n),C(Z,null),r.nodeType){case 9:case 11:n=(n=r.documentElement)&&(n=n.namespaceURI)?k_(n):0;break;default:if(n=r.tagName,r=r.namespaceURI)r=k_(r),n=E_(r,n);else switch(n){case"svg":n=1;break;case"math":n=2;break;default:n=0}}X(Z),C(Z,n)}function ge(){X(Z),X(ae),X(oe)}function De(n){n.memoizedState!==null&&C(K,n);var r=Z.current,l=E_(r,n.type);r!==l&&(C(ae,n),C(Z,l))}function ze(n){ae.current===n&&(X(Z),X(ae)),K.current===n&&(X(K),so._currentValue=F)}var Fe,we;function He(n){if(Fe===void 0)try{throw Error()}catch(l){var r=l.stack.trim().match(/\n( *(at )?)/);Fe=r&&r[1]||"",we=-1j||(n.current=xe[j],xe[j]=null,j--)}function k(n,r){j++,xe[j]=n.current,n.current=r}var K=R(null),ae=R(null),oe=R(null),X=R(null);function he(n,r){switch(k(oe,r),k(ae,n),k(K,null),r.nodeType){case 9:case 11:n=(n=r.documentElement)&&(n=n.namespaceURI)?k_(n):0;break;default:if(n=r.tagName,r=r.namespaceURI)r=k_(r),n=E_(r,n);else switch(n){case"svg":n=1;break;case"math":n=2;break;default:n=0}}Z(K),k(K,n)}function ge(){Z(K),Z(ae),Z(oe)}function Re(n){n.memoizedState!==null&&k(X,n);var r=K.current,l=E_(r,n.type);r!==l&&(k(ae,n),k(K,l))}function Le(n){ae.current===n&&(Z(K),Z(ae)),X.current===n&&(Z(X),so._currentValue=q)}var Fe,ye;function st(n){if(Fe===void 0)try{throw Error()}catch(l){var r=l.stack.trim().match(/\n( *(at )?)/);Fe=r&&r[1]||"",ye=-1)":-1m||O[u]!==J[m]){var ce=` -`+O[u].replace(" at new "," at ");return n.displayName&&ce.includes("")&&(ce=ce.replace("",n.displayName)),ce}while(1<=u&&0<=m);break}}}finally{it=!1,Error.prepareStackTrace=l}return(l=n?n.displayName||n.name:"")?He(l):""}function nt(n,r){switch(n.tag){case 26:case 27:case 5:return He(n.type);case 16:return He("Lazy");case 13:return n.child!==r&&r!==null?He("Suspense Fallback"):He("Suspense");case 19:return He("SuspenseList");case 0:case 15:return st(n.type,!1);case 11:return st(n.type.render,!1);case 1:return st(n.type,!0);case 31:return He("Activity");default:return""}}function Nt(n){try{var r="",l=null;do r+=nt(n,l),l=n,n=n.return;while(n);return r}catch(u){return` +`+Fe+n+ye}var yt=!1;function Ue(n,r){if(!n||yt)return"";yt=!0;var l=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var u={DetermineComponentFrameRoot:function(){try{if(r){var fe=function(){throw Error()};if(Object.defineProperty(fe.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(fe,[])}catch(le){var te=le}Reflect.construct(n,[],fe)}else{try{fe.call()}catch(le){te=le}n.call(fe.prototype)}}else{try{throw Error()}catch(le){te=le}(fe=n())&&typeof fe.catch=="function"&&fe.catch(function(){})}}catch(le){if(le&&te&&typeof le.stack=="string")return[le.stack,te.stack]}return[null,null]}};u.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var m=Object.getOwnPropertyDescriptor(u.DetermineComponentFrameRoot,"name");m&&m.configurable&&Object.defineProperty(u.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var g=u.DetermineComponentFrameRoot(),y=g[0],C=g[1];if(y&&C){var z=y.split(` +`),J=C.split(` +`);for(m=u=0;um||z[u]!==J[m]){var ce=` +`+z[u].replace(" at new "," at ");return n.displayName&&ce.includes("")&&(ce=ce.replace("",n.displayName)),ce}while(1<=u&&0<=m);break}}}finally{yt=!1,Error.prepareStackTrace=l}return(l=n?n.displayName||n.name:"")?st(l):""}function qe(n,r){switch(n.tag){case 26:case 27:case 5:return st(n.type);case 16:return st("Lazy");case 13:return n.child!==r&&r!==null?st("Suspense Fallback"):st("Suspense");case 19:return st("SuspenseList");case 0:case 15:return Ue(n.type,!1);case 11:return Ue(n.type.render,!1);case 1:return Ue(n.type,!0);case 31:return st("Activity");default:return""}}function St(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 Be=Object.prototype.hasOwnProperty,ct=e.unstable_scheduleCallback,Te=e.unstable_cancelCallback,Wt=e.unstable_shouldYield,vi=e.unstable_requestPaint,Ct=e.unstable_now,et=e.unstable_getCurrentPriorityLevel,ee=e.unstable_ImmediatePriority,be=e.unstable_UserBlockingPriority,Me=e.unstable_NormalPriority,$e=e.unstable_LowPriority,Xe=e.unstable_IdlePriority,Gt=e.log,pi=e.unstable_setDisableYieldValue,Rt=null,St=null;function Yt(n){if(typeof Gt=="function"&&pi(n),St&&typeof St.setStrictMode=="function")try{St.setStrictMode(Rt,n)}catch{}}var ot=Math.clz32?Math.clz32:Ce,Ht=Math.log,U=Math.LN2;function Ce(n){return n>>>=0,n===0?32:31-(Ht(n)/U|0)|0}var Ae=256,Ne=262144,Ge=4194304;function Ue(n){var r=n&42;if(r!==0)return r;switch(n&-n){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return n&261888;case 262144:case 524288:case 1048576:case 2097152:return n&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return n&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return n}}function dt(n,r,l){var u=n.pendingLanes;if(u===0)return 0;var m=0,g=n.suspendedLanes,y=n.pingedLanes;n=n.warmLanes;var k=u&134217727;return k!==0?(u=k&~g,u!==0?m=Ue(u):(y&=k,y!==0?m=Ue(y):l||(l=k&~n,l!==0&&(m=Ue(l))))):(k=u&~g,k!==0?m=Ue(k):y!==0?m=Ue(y):l||(l=u&~n,l!==0&&(m=Ue(l)))),m===0?0:r!==0&&r!==m&&(r&g)===0&&(g=m&-m,l=r&-r,g>=l||g===32&&(l&4194048)!==0)?r:m}function _t(n,r){return(n.pendingLanes&~(n.suspendedLanes&~n.pingedLanes)&r)===0}function At(n,r){switch(n){case 1:case 2:case 4:case 8:case 64:return r+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return r+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Bt(){var n=Ge;return Ge<<=1,(Ge&62914560)===0&&(Ge=4194304),n}function Ut(n){for(var r=[],l=0;31>l;l++)r.push(n);return r}function Vt(n,r){n.pendingLanes|=r,r!==268435456&&(n.suspendedLanes=0,n.pingedLanes=0,n.warmLanes=0)}function an(n,r,l,u,m,g){var y=n.pendingLanes;n.pendingLanes=l,n.suspendedLanes=0,n.pingedLanes=0,n.warmLanes=0,n.expiredLanes&=l,n.entangledLanes&=l,n.errorRecoveryDisabledLanes&=l,n.shellSuspendCounter=0;var k=n.entanglements,O=n.expirationTimes,J=n.hiddenUpdates;for(l=y&~l;0"u")return null;try{return n.activeElement||n.body}catch{return n.body}}var Ws=/[\n"\\]/g;function Zi(n){return n.replace(Ws,function(r){return"\\"+r.charCodeAt(0).toString(16)+" "})}function Pr(n,r,l,u,m,g,y,k){n.name="",y!=null&&typeof y!="function"&&typeof y!="symbol"&&typeof y!="boolean"?n.type=y:n.removeAttribute("type"),r!=null?y==="number"?(r===0&&n.value===""||n.value!=r)&&(n.value=""+yi(r)):n.value!==""+yi(r)&&(n.value=""+yi(r)):y!=="submit"&&y!=="reset"||n.removeAttribute("value"),r!=null?ur(n,y,yi(r)):l!=null?ur(n,y,yi(l)):u!=null&&n.removeAttribute("value"),m==null&&g!=null&&(n.defaultChecked=!!g),m!=null&&(n.checked=m&&typeof m!="function"&&typeof m!="symbol"),k!=null&&typeof k!="function"&&typeof k!="symbol"&&typeof k!="boolean"?n.name=""+yi(k):n.removeAttribute("name")}function Si(n,r,l,u,m,g,y,k){if(g!=null&&typeof g!="function"&&typeof g!="symbol"&&typeof g!="boolean"&&(n.type=g),r!=null||l!=null){if(!(g!=="submit"&&g!=="reset"||r!=null)){Qt(n);return}l=l!=null?""+yi(l):"",r=r!=null?""+yi(r):l,k||r===n.value||(n.value=r),n.defaultValue=r}u=u??m,u=typeof u!="function"&&typeof u!="symbol"&&!!u,n.checked=k?n.checked:!!u,n.defaultChecked=!!u,y!=null&&typeof y!="function"&&typeof y!="symbol"&&typeof y!="boolean"&&(n.name=y),Qt(n)}function ur(n,r,l){r==="number"&&zr(n.ownerDocument)===n||n.defaultValue===""+l||(n.defaultValue=""+l)}function wi(n,r,l,u){if(n=n.options,r){r={};for(var m=0;m"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Cl=!1;if(Sn)try{var vr={};Object.defineProperty(vr,"passive",{get:function(){Cl=!0}}),window.addEventListener("test",vr,vr),window.removeEventListener("test",vr,vr)}catch{Cl=!1}var dr=null,se=null,Ee=null;function je(){if(Ee)return Ee;var n,r=se,l=r.length,u,m="value"in dr?dr.value:dr.textContent,g=m.length;for(n=0;n=El),Dm=" ",Mm=!1;function Bm(n,r){switch(n){case"keyup":return O1.indexOf(r.keyCode)!==-1;case"keydown":return r.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Lm(n){return n=n.detail,typeof n=="object"&&"data"in n?n.data:null}var Ea=!1;function P1(n,r){switch(n){case"compositionend":return Lm(r);case"keypress":return r.which!==32?null:(Mm=!0,Dm);case"textInput":return n=r.data,n===Dm&&Mm?null:n;default:return null}}function I1(n,r){if(Ea)return n==="compositionend"||!eh&&Bm(n,r)?(n=je(),Ee=se=dr=null,Ea=!1,n):null;switch(n){case"paste":return null;case"keypress":if(!(r.ctrlKey||r.altKey||r.metaKey)||r.ctrlKey&&r.altKey){if(r.char&&1=r)return{node:l,offset:r-n};n=u}e:{for(;l;){if(l.nextSibling){l=l.nextSibling;break e}l=l.parentNode}l=void 0}l=Fm(l)}}function Wm(n,r){return n&&r?n===r?!0:n&&n.nodeType===3?!1:r&&r.nodeType===3?Wm(n,r.parentNode):"contains"in n?n.contains(r):n.compareDocumentPosition?!!(n.compareDocumentPosition(r)&16):!1:!1}function Gm(n){n=n!=null&&n.ownerDocument!=null&&n.ownerDocument.defaultView!=null?n.ownerDocument.defaultView:window;for(var r=zr(n.document);r instanceof n.HTMLIFrameElement;){try{var l=typeof r.contentWindow.location.href=="string"}catch{l=!1}if(l)n=r.contentWindow;else break;r=zr(n.document)}return r}function nh(n){var r=n&&n.nodeName&&n.nodeName.toLowerCase();return r&&(r==="input"&&(n.type==="text"||n.type==="search"||n.type==="tel"||n.type==="url"||n.type==="password")||r==="textarea"||n.contentEditable==="true")}var Y1=Sn&&"documentMode"in document&&11>=document.documentMode,Na=null,rh=null,Al=null,sh=!1;function Ym(n,r,l){var u=l.window===l?l.document:l.nodeType===9?l:l.ownerDocument;sh||Na==null||Na!==zr(u)||(u=Na,"selectionStart"in u&&nh(u)?u={start:u.selectionStart,end:u.selectionEnd}:(u=(u.ownerDocument&&u.ownerDocument.defaultView||window).getSelection(),u={anchorNode:u.anchorNode,anchorOffset:u.anchorOffset,focusNode:u.focusNode,focusOffset:u.focusOffset}),Al&&Tl(Al,u)||(Al=u,u=Uc(rh,"onSelect"),0>=y,m-=y,yr=1<<32-ot(r)+m|l<at?(xt=Ie,Ie=null):xt=Ie.sibling;var Et=ie(W,Ie,Q[at],de);if(Et===null){Ie===null&&(Ie=xt);break}n&&Ie&&Et.alternate===null&&r(W,Ie),P=g(Et,P,at),kt===null?We=Et:kt.sibling=Et,kt=Et,Ie=xt}if(at===Q.length)return l(W,Ie),bt&&Ur(W,at),We;if(Ie===null){for(;atat?(xt=Ie,Ie=null):xt=Ie.sibling;var Ms=ie(W,Ie,Et.value,de);if(Ms===null){Ie===null&&(Ie=xt);break}n&&Ie&&Ms.alternate===null&&r(W,Ie),P=g(Ms,P,at),kt===null?We=Ms:kt.sibling=Ms,kt=Ms,Ie=xt}if(Et.done)return l(W,Ie),bt&&Ur(W,at),We;if(Ie===null){for(;!Et.done;at++,Et=Q.next())Et=fe(W,Et.value,de),Et!==null&&(P=g(Et,P,at),kt===null?We=Et:kt.sibling=Et,kt=Et);return bt&&Ur(W,at),We}for(Ie=u(Ie);!Et.done;at++,Et=Q.next())Et=le(Ie,W,at,Et.value,de),Et!==null&&(n&&Et.alternate!==null&&Ie.delete(Et.key===null?at:Et.key),P=g(Et,P,at),kt===null?We=Et:kt.sibling=Et,kt=Et);return n&&Ie.forEach(function(fC){return r(W,fC)}),bt&&Ur(W,at),We}function Pt(W,P,Q,de){if(typeof Q=="object"&&Q!==null&&Q.type===N&&Q.key===null&&(Q=Q.props.children),typeof Q=="object"&&Q!==null){switch(Q.$$typeof){case v:e:{for(var We=Q.key;P!==null;){if(P.key===We){if(We=Q.type,We===N){if(P.tag===7){l(W,P.sibling),de=m(P,Q.props.children),de.return=W,W=de;break e}}else if(P.elementType===We||typeof We=="object"&&We!==null&&We.$$typeof===ue&&ia(We)===P.type){l(W,P.sibling),de=m(P,Q.props),Ol(de,Q),de.return=W,W=de;break e}l(W,P);break}else r(W,P);P=P.sibling}Q.type===N?(de=Zs(Q.props.children,W.mode,de,Q.key),de.return=W,W=de):(de=rc(Q.type,Q.key,Q.props,null,W.mode,de),Ol(de,Q),de.return=W,W=de)}return y(W);case S:e:{for(We=Q.key;P!==null;){if(P.key===We)if(P.tag===4&&P.stateNode.containerInfo===Q.containerInfo&&P.stateNode.implementation===Q.implementation){l(W,P.sibling),de=m(P,Q.children||[]),de.return=W,W=de;break e}else{l(W,P);break}else r(W,P);P=P.sibling}de=dh(Q,W.mode,de),de.return=W,W=de}return y(W);case ue:return Q=ia(Q),Pt(W,P,Q,de)}if(H(Q))return Le(W,P,Q,de);if($(Q)){if(We=$(Q),typeof We!="function")throw Error(s(150));return Q=We.call(Q),Ve(W,P,Q,de)}if(typeof Q.then=="function")return Pt(W,P,hc(Q),de);if(Q.$$typeof===I)return Pt(W,P,lc(W,Q),de);dc(W,Q)}return typeof Q=="string"&&Q!==""||typeof Q=="number"||typeof Q=="bigint"?(Q=""+Q,P!==null&&P.tag===6?(l(W,P.sibling),de=m(P,Q),de.return=W,W=de):(l(W,P),de=hh(Q,W.mode,de),de.return=W,W=de),y(W)):l(W,P)}return function(W,P,Q,de){try{Ll=0;var We=Pt(W,P,Q,de);return Pa=null,We}catch(Ie){if(Ie===za||Ie===cc)throw Ie;var kt=Pn(29,Ie,null,W.mode);return kt.lanes=de,kt.return=W,kt}finally{}}}var ra=gg(!0),xg=gg(!1),gs=!1;function Ch(n){n.updateQueue={baseState:n.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function kh(n,r){n=n.updateQueue,r.updateQueue===n&&(r.updateQueue={baseState:n.baseState,firstBaseUpdate:n.firstBaseUpdate,lastBaseUpdate:n.lastBaseUpdate,shared:n.shared,callbacks:null})}function xs(n){return{lane:n,tag:0,payload:null,callback:null,next:null}}function _s(n,r,l){var u=n.updateQueue;if(u===null)return null;if(u=u.shared,(Tt&2)!==0){var m=u.pending;return m===null?r.next=r:(r.next=m.next,m.next=r),u.pending=r,r=nc(n),eg(n,null,l),r}return ic(n,u,r,l),nc(n)}function zl(n,r,l){if(r=r.updateQueue,r!==null&&(r=r.shared,(l&4194048)!==0)){var u=r.lanes;u&=n.pendingLanes,l|=u,r.lanes=l,Mn(n,l)}}function Eh(n,r){var l=n.updateQueue,u=n.alternate;if(u!==null&&(u=u.updateQueue,l===u)){var m=null,g=null;if(l=l.firstBaseUpdate,l!==null){do{var y={lane:l.lane,tag:l.tag,payload:l.payload,callback:null,next:null};g===null?m=g=y:g=g.next=y,l=l.next}while(l!==null);g===null?m=g=r:g=g.next=r}else m=g=r;l={baseState:u.baseState,firstBaseUpdate:m,lastBaseUpdate:g,shared:u.shared,callbacks:u.callbacks},n.updateQueue=l;return}n=l.lastBaseUpdate,n===null?l.firstBaseUpdate=r:n.next=r,l.lastBaseUpdate=r}var Nh=!1;function Pl(){if(Nh){var n=Oa;if(n!==null)throw n}}function Il(n,r,l,u){Nh=!1;var m=n.updateQueue;gs=!1;var g=m.firstBaseUpdate,y=m.lastBaseUpdate,k=m.shared.pending;if(k!==null){m.shared.pending=null;var O=k,J=O.next;O.next=null,y===null?g=J:y.next=J,y=O;var ce=n.alternate;ce!==null&&(ce=ce.updateQueue,k=ce.lastBaseUpdate,k!==y&&(k===null?ce.firstBaseUpdate=J:k.next=J,ce.lastBaseUpdate=O))}if(g!==null){var fe=m.baseState;y=0,ce=J=O=null,k=g;do{var ie=k.lane&-536870913,le=ie!==k.lane;if(le?(gt&ie)===ie:(u&ie)===ie){ie!==0&&ie===La&&(Nh=!0),ce!==null&&(ce=ce.next={lane:0,tag:k.tag,payload:k.payload,callback:null,next:null});e:{var Le=n,Ve=k;ie=r;var Pt=l;switch(Ve.tag){case 1:if(Le=Ve.payload,typeof Le=="function"){fe=Le.call(Pt,fe,ie);break e}fe=Le;break e;case 3:Le.flags=Le.flags&-65537|128;case 0:if(Le=Ve.payload,ie=typeof Le=="function"?Le.call(Pt,fe,ie):Le,ie==null)break e;fe=x({},fe,ie);break e;case 2:gs=!0}}ie=k.callback,ie!==null&&(n.flags|=64,le&&(n.flags|=8192),le=m.callbacks,le===null?m.callbacks=[ie]:le.push(ie))}else le={lane:ie,tag:k.tag,payload:k.payload,callback:k.callback,next:null},ce===null?(J=ce=le,O=fe):ce=ce.next=le,y|=ie;if(k=k.next,k===null){if(k=m.shared.pending,k===null)break;le=k,k=le.next,le.next=null,m.lastBaseUpdate=le,m.shared.pending=null}}while(!0);ce===null&&(O=fe),m.baseState=O,m.firstBaseUpdate=J,m.lastBaseUpdate=ce,g===null&&(m.shared.lanes=0),ws|=y,n.lanes=y,n.memoizedState=fe}}function _g(n,r){if(typeof n!="function")throw Error(s(191,n));n.call(r)}function bg(n,r){var l=n.callbacks;if(l!==null)for(n.callbacks=null,n=0;ng?g:8;var y=T.T,k={};T.T=k,Gh(n,!1,r,l);try{var O=m(),J=T.S;if(J!==null&&J(k,O),O!==null&&typeof O=="object"&&typeof O.then=="function"){var ce=iw(O,u);$l(n,r,ce,Fn(n))}else $l(n,r,u,Fn(n))}catch(fe){$l(n,r,{then:function(){},status:"rejected",reason:fe},Fn())}finally{z.p=g,y!==null&&k.types!==null&&(y.types=k.types),T.T=y}}function ow(){}function qh(n,r,l,u){if(n.tag!==5)throw Error(s(476));var m=Zg(n).queue;Xg(n,m,r,F,l===null?ow:function(){return Qg(n),l(u)})}function Zg(n){var r=n.memoizedState;if(r!==null)return r;r={memoizedState:F,baseState:F,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Wr,lastRenderedState:F},next:null};var l={};return r.next={memoizedState:l,baseState:l,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Wr,lastRenderedState:l},next:null},n.memoizedState=r,n=n.alternate,n!==null&&(n.memoizedState=r),r}function Qg(n){var r=Zg(n);r.next===null&&(r=n.alternate.memoizedState),$l(n,r.next.queue,{},Fn())}function Wh(){return Ji(so)}function Jg(){return _i().memoizedState}function ex(){return _i().memoizedState}function cw(n){for(var r=n.return;r!==null;){switch(r.tag){case 24:case 3:var l=Fn();n=xs(l);var u=_s(r,n,l);u!==null&&(jn(u,r,l),zl(u,r,l)),r={cache:vh()},n.payload=r;return}r=r.return}}function uw(n,r,l){var u=Fn();l={lane:u,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null},Sc(n)?ix(r,l):(l=ch(n,r,l,u),l!==null&&(jn(l,n,u),nx(l,r,u)))}function tx(n,r,l){var u=Fn();$l(n,r,l,u)}function $l(n,r,l,u){var m={lane:u,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null};if(Sc(n))ix(r,m);else{var g=n.alternate;if(n.lanes===0&&(g===null||g.lanes===0)&&(g=r.lastRenderedReducer,g!==null))try{var y=r.lastRenderedState,k=g(y,l);if(m.hasEagerState=!0,m.eagerState=k,zn(k,y))return ic(n,r,m,0),Ft===null&&tc(),!1}catch{}finally{}if(l=ch(n,r,m,u),l!==null)return jn(l,n,u),nx(l,r,u),!0}return!1}function Gh(n,r,l,u){if(u={lane:2,revertLane:Cd(),gesture:null,action:u,hasEagerState:!1,eagerState:null,next:null},Sc(n)){if(r)throw Error(s(479))}else r=ch(n,l,u,2),r!==null&&jn(r,n,2)}function Sc(n){var r=n.alternate;return n===rt||r!==null&&r===rt}function ix(n,r){Ha=mc=!0;var l=n.pending;l===null?r.next=r:(r.next=l.next,l.next=r),n.pending=r}function nx(n,r,l){if((l&4194048)!==0){var u=r.lanes;u&=n.pendingLanes,l|=u,r.lanes=l,Mn(n,l)}}var Fl={readContext:Ji,use:_c,useCallback:ci,useContext:ci,useEffect:ci,useImperativeHandle:ci,useLayoutEffect:ci,useInsertionEffect:ci,useMemo:ci,useReducer:ci,useRef:ci,useState:ci,useDebugValue:ci,useDeferredValue:ci,useTransition:ci,useSyncExternalStore:ci,useId:ci,useHostTransitionStatus:ci,useFormState:ci,useActionState:ci,useOptimistic:ci,useMemoCache:ci,useCacheRefresh:ci};Fl.useEffectEvent=ci;var rx={readContext:Ji,use:_c,useCallback:function(n,r){return fn().memoizedState=[n,r===void 0?null:r],n},useContext:Ji,useEffect:Ug,useImperativeHandle:function(n,r,l){l=l!=null?l.concat([n]):null,vc(4194308,4,Wg.bind(null,r,n),l)},useLayoutEffect:function(n,r){return vc(4194308,4,n,r)},useInsertionEffect:function(n,r){vc(4,2,n,r)},useMemo:function(n,r){var l=fn();r=r===void 0?null:r;var u=n();if(sa){Yt(!0);try{n()}finally{Yt(!1)}}return l.memoizedState=[u,r],u},useReducer:function(n,r,l){var u=fn();if(l!==void 0){var m=l(r);if(sa){Yt(!0);try{l(r)}finally{Yt(!1)}}}else m=r;return u.memoizedState=u.baseState=m,n={pending:null,lanes:0,dispatch:null,lastRenderedReducer:n,lastRenderedState:m},u.queue=n,n=n.dispatch=uw.bind(null,rt,n),[u.memoizedState,n]},useRef:function(n){var r=fn();return n={current:n},r.memoizedState=n},useState:function(n){n=Ih(n);var r=n.queue,l=tx.bind(null,rt,r);return r.dispatch=l,[n.memoizedState,l]},useDebugValue:$h,useDeferredValue:function(n,r){var l=fn();return Fh(l,n,r)},useTransition:function(){var n=Ih(!1);return n=Xg.bind(null,rt,n.queue,!0,!1),fn().memoizedState=n,[!1,n]},useSyncExternalStore:function(n,r,l){var u=rt,m=fn();if(bt){if(l===void 0)throw Error(s(407));l=l()}else{if(l=r(),Ft===null)throw Error(s(349));(gt&127)!==0||kg(u,r,l)}m.memoizedState=l;var g={value:l,getSnapshot:r};return m.queue=g,Ug(Ng.bind(null,u,g,n),[n]),u.flags|=2048,$a(9,{destroy:void 0},Eg.bind(null,u,g,l,r),null),l},useId:function(){var n=fn(),r=Ft.identifierPrefix;if(bt){var l=Sr,u=yr;l=(u&~(1<<32-ot(u)-1)).toString(32)+l,r="_"+r+"R_"+l,l=gc++,0<\/script>",g=g.removeChild(g.firstChild);break;case"select":g=typeof u.is=="string"?y.createElement("select",{is:u.is}):y.createElement("select"),u.multiple?g.multiple=!0:u.size&&(g.size=u.size);break;default:g=typeof u.is=="string"?y.createElement(m,{is:u.is}):y.createElement(m)}}g[Zt]=r,g[te]=u;e:for(y=r.child;y!==null;){if(y.tag===5||y.tag===6)g.appendChild(y.stateNode);else if(y.tag!==4&&y.tag!==27&&y.child!==null){y.child.return=y,y=y.child;continue}if(y===r)break e;for(;y.sibling===null;){if(y.return===null||y.return===r)break e;y=y.return}y.sibling.return=y.return,y=y.sibling}r.stateNode=g;e:switch(tn(g,m,u),m){case"button":case"input":case"select":case"textarea":u=!!u.autoFocus;break e;case"img":u=!0;break e;default:u=!1}u&&Yr(r)}}return ei(r),ad(r,r.type,n===null?null:n.memoizedProps,r.pendingProps,l),null;case 6:if(n&&r.stateNode!=null)n.memoizedProps!==u&&Yr(r);else{if(typeof u!="string"&&r.stateNode===null)throw Error(s(166));if(n=oe.current,Ma(r)){if(n=r.stateNode,l=r.memoizedProps,u=null,m=Qi,m!==null)switch(m.tag){case 27:case 5:u=m.memoizedProps}n[Zt]=r,n=!!(n.nodeValue===l||u!==null&&u.suppressHydrationWarning===!0||w_(n.nodeValue,l)),n||ps(r,!0)}else n=$c(n).createTextNode(u),n[Zt]=r,r.stateNode=n}return ei(r),null;case 31:if(l=r.memoizedState,n===null||n.memoizedState!==null){if(u=Ma(r),l!==null){if(n===null){if(!u)throw Error(s(318));if(n=r.memoizedState,n=n!==null?n.dehydrated:null,!n)throw Error(s(557));n[Zt]=r}else Qs(),(r.flags&128)===0&&(r.memoizedState=null),r.flags|=4;ei(r),n=!1}else l=gh(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=l),n=!0;if(!n)return r.flags&256?(Hn(r),r):(Hn(r),null);if((r.flags&128)!==0)throw Error(s(558))}return ei(r),null;case 13:if(u=r.memoizedState,n===null||n.memoizedState!==null&&n.memoizedState.dehydrated!==null){if(m=Ma(r),u!==null&&u.dehydrated!==null){if(n===null){if(!m)throw Error(s(318));if(m=r.memoizedState,m=m!==null?m.dehydrated:null,!m)throw Error(s(317));m[Zt]=r}else Qs(),(r.flags&128)===0&&(r.memoizedState=null),r.flags|=4;ei(r),m=!1}else m=gh(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=m),m=!0;if(!m)return r.flags&256?(Hn(r),r):(Hn(r),null)}return Hn(r),(r.flags&128)!==0?(r.lanes=l,r):(l=u!==null,n=n!==null&&n.memoizedState!==null,l&&(u=r.child,m=null,u.alternate!==null&&u.alternate.memoizedState!==null&&u.alternate.memoizedState.cachePool!==null&&(m=u.alternate.memoizedState.cachePool.pool),g=null,u.memoizedState!==null&&u.memoizedState.cachePool!==null&&(g=u.memoizedState.cachePool.pool),g!==m&&(u.flags|=2048)),l!==n&&l&&(r.child.flags|=8192),Nc(r,r.updateQueue),ei(r),null);case 4:return ge(),n===null&&jd(r.stateNode.containerInfo),ei(r),null;case 10:return Fr(r.type),ei(r),null;case 19:if(X(xi),u=r.memoizedState,u===null)return ei(r),null;if(m=(r.flags&128)!==0,g=u.rendering,g===null)if(m)Wl(u,!1);else{if(ui!==0||n!==null&&(n.flags&128)!==0)for(n=r.child;n!==null;){if(g=pc(n),g!==null){for(r.flags|=128,Wl(u,!1),n=g.updateQueue,r.updateQueue=n,Nc(r,n),r.subtreeFlags=0,n=l,l=r.child;l!==null;)tg(l,n),l=l.sibling;return C(xi,xi.current&1|2),bt&&Ur(r,u.treeForkCount),r.child}n=n.sibling}u.tail!==null&&Ct()>Dc&&(r.flags|=128,m=!0,Wl(u,!1),r.lanes=4194304)}else{if(!m)if(n=pc(g),n!==null){if(r.flags|=128,m=!0,n=n.updateQueue,r.updateQueue=n,Nc(r,n),Wl(u,!0),u.tail===null&&u.tailMode==="hidden"&&!g.alternate&&!bt)return ei(r),null}else 2*Ct()-u.renderingStartTime>Dc&&l!==536870912&&(r.flags|=128,m=!0,Wl(u,!1),r.lanes=4194304);u.isBackwards?(g.sibling=r.child,r.child=g):(n=u.last,n!==null?n.sibling=g:r.child=g,u.last=g)}return u.tail!==null?(n=u.tail,u.rendering=n,u.tail=n.sibling,u.renderingStartTime=Ct(),n.sibling=null,l=xi.current,C(xi,m?l&1|2:l&1),bt&&Ur(r,u.treeForkCount),n):(ei(r),null);case 22:case 23:return Hn(r),Th(),u=r.memoizedState!==null,n!==null?n.memoizedState!==null!==u&&(r.flags|=8192):u&&(r.flags|=8192),u?(l&536870912)!==0&&(r.flags&128)===0&&(ei(r),r.subtreeFlags&6&&(r.flags|=8192)):ei(r),l=r.updateQueue,l!==null&&Nc(r,l.retryQueue),l=null,n!==null&&n.memoizedState!==null&&n.memoizedState.cachePool!==null&&(l=n.memoizedState.cachePool.pool),u=null,r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(u=r.memoizedState.cachePool.pool),u!==l&&(r.flags|=2048),n!==null&&X(ta),null;case 24:return l=null,n!==null&&(l=n.memoizedState.cache),r.memoizedState.cache!==l&&(r.flags|=2048),Fr(Ci),ei(r),null;case 25:return null;case 30:return null}throw Error(s(156,r.tag))}function mw(n,r){switch(ph(r),r.tag){case 1:return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 3:return Fr(Ci),ge(),n=r.flags,(n&65536)!==0&&(n&128)===0?(r.flags=n&-65537|128,r):null;case 26:case 27:case 5:return ze(r),null;case 31:if(r.memoizedState!==null){if(Hn(r),r.alternate===null)throw Error(s(340));Qs()}return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 13:if(Hn(r),n=r.memoizedState,n!==null&&n.dehydrated!==null){if(r.alternate===null)throw Error(s(340));Qs()}return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 19:return X(xi),null;case 4:return ge(),null;case 10:return Fr(r.type),null;case 22:case 23:return Hn(r),Th(),n!==null&&X(ta),n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 24:return Fr(Ci),null;case 25:return null;default:return null}}function jx(n,r){switch(ph(r),r.tag){case 3:Fr(Ci),ge();break;case 26:case 27:case 5:ze(r);break;case 4:ge();break;case 31:r.memoizedState!==null&&Hn(r);break;case 13:Hn(r);break;case 19:X(xi);break;case 10:Fr(r.type);break;case 22:case 23:Hn(r),Th(),n!==null&&X(ta);break;case 24:Fr(Ci)}}function Gl(n,r){try{var l=r.updateQueue,u=l!==null?l.lastEffect:null;if(u!==null){var m=u.next;l=m;do{if((l.tag&n)===n){u=void 0;var g=l.create,y=l.inst;u=g(),y.destroy=u}l=l.next}while(l!==m)}}catch(k){Mt(r,r.return,k)}}function ys(n,r,l){try{var u=r.updateQueue,m=u!==null?u.lastEffect:null;if(m!==null){var g=m.next;u=g;do{if((u.tag&n)===n){var y=u.inst,k=y.destroy;if(k!==void 0){y.destroy=void 0,m=r;var O=l,J=k;try{J()}catch(ce){Mt(m,O,ce)}}}u=u.next}while(u!==g)}}catch(ce){Mt(r,r.return,ce)}}function Tx(n){var r=n.updateQueue;if(r!==null){var l=n.stateNode;try{bg(r,l)}catch(u){Mt(n,n.return,u)}}}function Ax(n,r,l){l.props=aa(n.type,n.memoizedProps),l.state=n.memoizedState;try{l.componentWillUnmount()}catch(u){Mt(n,r,u)}}function Yl(n,r){try{var l=n.ref;if(l!==null){switch(n.tag){case 26:case 27:case 5:var u=n.stateNode;break;case 30:u=n.stateNode;break;default:u=n.stateNode}typeof l=="function"?n.refCleanup=l(u):l.current=u}}catch(m){Mt(n,r,m)}}function wr(n,r){var l=n.ref,u=n.refCleanup;if(l!==null)if(typeof u=="function")try{u()}catch(m){Mt(n,r,m)}finally{n.refCleanup=null,n=n.alternate,n!=null&&(n.refCleanup=null)}else if(typeof l=="function")try{l(null)}catch(m){Mt(n,r,m)}else l.current=null}function Rx(n){var r=n.type,l=n.memoizedProps,u=n.stateNode;try{e:switch(r){case"button":case"input":case"select":case"textarea":l.autoFocus&&u.focus();break e;case"img":l.src?u.src=l.src:l.srcSet&&(u.srcset=l.srcSet)}}catch(m){Mt(n,n.return,m)}}function ld(n,r,l){try{var u=n.stateNode;zw(u,n.type,l,r),u[te]=r}catch(m){Mt(n,n.return,m)}}function Dx(n){return n.tag===5||n.tag===3||n.tag===26||n.tag===27&&js(n.type)||n.tag===4}function od(n){e:for(;;){for(;n.sibling===null;){if(n.return===null||Dx(n.return))return null;n=n.return}for(n.sibling.return=n.return,n=n.sibling;n.tag!==5&&n.tag!==6&&n.tag!==18;){if(n.tag===27&&js(n.type)||n.flags&2||n.child===null||n.tag===4)continue e;n.child.return=n,n=n.child}if(!(n.flags&2))return n.stateNode}}function cd(n,r,l){var u=n.tag;if(u===5||u===6)n=n.stateNode,r?(l.nodeType===9?l.body:l.nodeName==="HTML"?l.ownerDocument.body:l).insertBefore(n,r):(r=l.nodeType===9?l.body:l.nodeName==="HTML"?l.ownerDocument.body:l,r.appendChild(n),l=l._reactRootContainer,l!=null||r.onclick!==null||(r.onclick=dn));else if(u!==4&&(u===27&&js(n.type)&&(l=n.stateNode,r=null),n=n.child,n!==null))for(cd(n,r,l),n=n.sibling;n!==null;)cd(n,r,l),n=n.sibling}function jc(n,r,l){var u=n.tag;if(u===5||u===6)n=n.stateNode,r?l.insertBefore(n,r):l.appendChild(n);else if(u!==4&&(u===27&&js(n.type)&&(l=n.stateNode),n=n.child,n!==null))for(jc(n,r,l),n=n.sibling;n!==null;)jc(n,r,l),n=n.sibling}function Mx(n){var r=n.stateNode,l=n.memoizedProps;try{for(var u=n.type,m=r.attributes;m.length;)r.removeAttributeNode(m[0]);tn(r,u,l),r[Zt]=n,r[te]=l}catch(g){Mt(n,n.return,g)}}var Vr=!1,Ni=!1,ud=!1,Bx=typeof WeakSet=="function"?WeakSet:Set,Ui=null;function gw(n,r){if(n=n.containerInfo,Rd=Kc,n=Gm(n),nh(n)){if("selectionStart"in n)var l={start:n.selectionStart,end:n.selectionEnd};else e:{l=(l=n.ownerDocument)&&l.defaultView||window;var u=l.getSelection&&l.getSelection();if(u&&u.rangeCount!==0){l=u.anchorNode;var m=u.anchorOffset,g=u.focusNode;u=u.focusOffset;try{l.nodeType,g.nodeType}catch{l=null;break e}var y=0,k=-1,O=-1,J=0,ce=0,fe=n,ie=null;t:for(;;){for(var le;fe!==l||m!==0&&fe.nodeType!==3||(k=y+m),fe!==g||u!==0&&fe.nodeType!==3||(O=y+u),fe.nodeType===3&&(y+=fe.nodeValue.length),(le=fe.firstChild)!==null;)ie=fe,fe=le;for(;;){if(fe===n)break t;if(ie===l&&++J===m&&(k=y),ie===g&&++ce===u&&(O=y),(le=fe.nextSibling)!==null)break;fe=ie,ie=fe.parentNode}fe=le}l=k===-1||O===-1?null:{start:k,end:O}}else l=null}l=l||{start:0,end:0}}else l=null;for(Dd={focusedElem:n,selectionRange:l},Kc=!1,Ui=r;Ui!==null;)if(r=Ui,n=r.child,(r.subtreeFlags&1028)!==0&&n!==null)n.return=r,Ui=n;else for(;Ui!==null;){switch(r=Ui,g=r.alternate,n=r.flags,r.tag){case 0:if((n&4)!==0&&(n=r.updateQueue,n=n!==null?n.events:null,n!==null))for(l=0;l title"))),tn(g,u,l),g[Zt]=n,Qe(g),u=g;break e;case"link":var y=H_("link","href",m).get(u+(l.href||""));if(y){for(var k=0;kPt&&(y=Pt,Pt=Ve,Ve=y);var W=qm(k,Ve),P=qm(k,Pt);if(W&&P&&(le.rangeCount!==1||le.anchorNode!==W.node||le.anchorOffset!==W.offset||le.focusNode!==P.node||le.focusOffset!==P.offset)){var Q=fe.createRange();Q.setStart(W.node,W.offset),le.removeAllRanges(),Ve>Pt?(le.addRange(Q),le.extend(P.node,P.offset)):(Q.setEnd(P.node,P.offset),le.addRange(Q))}}}}for(fe=[],le=k;le=le.parentNode;)le.nodeType===1&&fe.push({element:le,left:le.scrollLeft,top:le.scrollTop});for(typeof k.focus=="function"&&k.focus(),k=0;kl?32:l,T.T=null,l=xd,xd=null;var g=ks,y=Jr;if(Bi=0,Ya=ks=null,Jr=0,(Tt&6)!==0)throw Error(s(331));var k=Tt;if(Tt|=4,Wx(g.current),$x(g,g.current,y,l),Tt=k,Jl(0,!1),St&&typeof St.onPostCommitFiberRoot=="function")try{St.onPostCommitFiberRoot(Rt,g)}catch{}return!0}finally{z.p=m,T.T=u,c_(n,r)}}function h_(n,r,l){r=Zn(l,r),r=Xh(n.stateNode,r,2),n=_s(n,r,2),n!==null&&(Vt(n,2),Cr(n))}function Mt(n,r,l){if(n.tag===3)h_(n,n,l);else for(;r!==null;){if(r.tag===3){h_(r,n,l);break}else if(r.tag===1){var u=r.stateNode;if(typeof r.type.getDerivedStateFromError=="function"||typeof u.componentDidCatch=="function"&&(Cs===null||!Cs.has(u))){n=Zn(l,n),l=dx(2),u=_s(r,l,2),u!==null&&(fx(l,u,r,n),Vt(u,2),Cr(u));break}}r=r.return}}function yd(n,r,l){var u=n.pingCache;if(u===null){u=n.pingCache=new bw;var m=new Set;u.set(r,m)}else m=u.get(r),m===void 0&&(m=new Set,u.set(r,m));m.has(l)||(fd=!0,m.add(l),n=Cw.bind(null,n,r,l),r.then(n,n))}function Cw(n,r,l){var u=n.pingCache;u!==null&&u.delete(r),n.pingedLanes|=n.suspendedLanes&l,n.warmLanes&=~l,Ft===n&&(gt&l)===l&&(ui===4||ui===3&&(gt&62914560)===gt&&300>Ct()-Rc?(Tt&2)===0&&Va(n,0):pd|=l,Ga===gt&&(Ga=0)),Cr(n)}function d_(n,r){r===0&&(r=Bt()),n=Xs(n,r),n!==null&&(Vt(n,r),Cr(n))}function kw(n){var r=n.memoizedState,l=0;r!==null&&(l=r.retryLane),d_(n,l)}function Ew(n,r){var l=0;switch(n.tag){case 31:case 13:var u=n.stateNode,m=n.memoizedState;m!==null&&(l=m.retryLane);break;case 19:u=n.stateNode;break;case 22:u=n.stateNode._retryCache;break;default:throw Error(s(314))}u!==null&&u.delete(r),d_(n,l)}function Nw(n,r){return ct(n,r)}var Pc=null,Xa=null,Sd=!1,Ic=!1,wd=!1,Ns=0;function Cr(n){n!==Xa&&n.next===null&&(Xa===null?Pc=Xa=n:Xa=Xa.next=n),Ic=!0,Sd||(Sd=!0,Tw())}function Jl(n,r){if(!wd&&Ic){wd=!0;do for(var l=!1,u=Pc;u!==null;){if(n!==0){var m=u.pendingLanes;if(m===0)var g=0;else{var y=u.suspendedLanes,k=u.pingedLanes;g=(1<<31-ot(42|n)+1)-1,g&=m&~(y&~k),g=g&201326741?g&201326741|1:g?g|2:0}g!==0&&(l=!0,g_(u,g))}else g=gt,g=dt(u,u===Ft?g:0,u.cancelPendingCommit!==null||u.timeoutHandle!==-1),(g&3)===0||_t(u,g)||(l=!0,g_(u,g));u=u.next}while(l);wd=!1}}function jw(){f_()}function f_(){Ic=Sd=!1;var n=0;Ns!==0&&Iw()&&(n=Ns);for(var r=Ct(),l=null,u=Pc;u!==null;){var m=u.next,g=p_(u,r);g===0?(u.next=null,l===null?Pc=m:l.next=m,m===null&&(Xa=l)):(l=u,(n!==0||(g&3)!==0)&&(Ic=!0)),u=m}Bi!==0&&Bi!==5||Jl(n),Ns!==0&&(Ns=0)}function p_(n,r){for(var l=n.suspendedLanes,u=n.pingedLanes,m=n.expirationTimes,g=n.pendingLanes&-62914561;0k)break;var ce=O.transferSize,fe=O.initiatorType;ce&&C_(fe)&&(O=O.responseEnd,y+=ce*(O"u"?null:document;function O_(n,r,l){var u=Za;if(u&&typeof r=="string"&&r){var m=Zi(r);m='link[rel="'+n+'"][href="'+m+'"]',typeof l=="string"&&(m+='[crossorigin="'+l+'"]'),L_.has(m)||(L_.add(m),n={rel:n,crossOrigin:l,href:r},u.querySelector(m)===null&&(r=u.createElement("link"),tn(r,"link",n),Qe(r),u.head.appendChild(r)))}}function Vw(n){es.D(n),O_("dns-prefetch",n,null)}function Kw(n,r){es.C(n,r),O_("preconnect",n,r)}function Xw(n,r,l){es.L(n,r,l);var u=Za;if(u&&n&&r){var m='link[rel="preload"][as="'+Zi(r)+'"]';r==="image"&&l&&l.imageSrcSet?(m+='[imagesrcset="'+Zi(l.imageSrcSet)+'"]',typeof l.imageSizes=="string"&&(m+='[imagesizes="'+Zi(l.imageSizes)+'"]')):m+='[href="'+Zi(n)+'"]';var g=m;switch(r){case"style":g=Qa(n);break;case"script":g=Ja(n)}nr.has(g)||(n=x({rel:"preload",href:r==="image"&&l&&l.imageSrcSet?void 0:n,as:r},l),nr.set(g,n),u.querySelector(m)!==null||r==="style"&&u.querySelector(no(g))||r==="script"&&u.querySelector(ro(g))||(r=u.createElement("link"),tn(r,"link",n),Qe(r),u.head.appendChild(r)))}}function Zw(n,r){es.m(n,r);var l=Za;if(l&&n){var u=r&&typeof r.as=="string"?r.as:"script",m='link[rel="modulepreload"][as="'+Zi(u)+'"][href="'+Zi(n)+'"]',g=m;switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":g=Ja(n)}if(!nr.has(g)&&(n=x({rel:"modulepreload",href:n},r),nr.set(g,n),l.querySelector(m)===null)){switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(l.querySelector(ro(g)))return}u=l.createElement("link"),tn(u,"link",n),Qe(u),l.head.appendChild(u)}}}function Qw(n,r,l){es.S(n,r,l);var u=Za;if(u&&n){var m=Ze(u).hoistableStyles,g=Qa(n);r=r||"default";var y=m.get(g);if(!y){var k={loading:0,preload:null};if(y=u.querySelector(no(g)))k.loading=5;else{n=x({rel:"stylesheet",href:n,"data-precedence":r},l),(l=nr.get(g))&&Id(n,l);var O=y=u.createElement("link");Qe(O),tn(O,"link",n),O._p=new Promise(function(J,ce){O.onload=J,O.onerror=ce}),O.addEventListener("load",function(){k.loading|=1}),O.addEventListener("error",function(){k.loading|=2}),k.loading|=4,qc(y,r,u)}y={type:"stylesheet",instance:y,count:1,state:k},m.set(g,y)}}}function Jw(n,r){es.X(n,r);var l=Za;if(l&&n){var u=Ze(l).hoistableScripts,m=Ja(n),g=u.get(m);g||(g=l.querySelector(ro(m)),g||(n=x({src:n,async:!0},r),(r=nr.get(m))&&Hd(n,r),g=l.createElement("script"),Qe(g),tn(g,"link",n),l.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(m,g))}}function eC(n,r){es.M(n,r);var l=Za;if(l&&n){var u=Ze(l).hoistableScripts,m=Ja(n),g=u.get(m);g||(g=l.querySelector(ro(m)),g||(n=x({src:n,async:!0,type:"module"},r),(r=nr.get(m))&&Hd(n,r),g=l.createElement("script"),Qe(g),tn(g,"link",n),l.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(m,g))}}function z_(n,r,l,u){var m=(m=oe.current)?Fc(m):null;if(!m)throw Error(s(446));switch(n){case"meta":case"title":return null;case"style":return typeof l.precedence=="string"&&typeof l.href=="string"?(r=Qa(l.href),l=Ze(m).hoistableStyles,u=l.get(r),u||(u={type:"style",instance:null,count:0,state:null},l.set(r,u)),u):{type:"void",instance:null,count:0,state:null};case"link":if(l.rel==="stylesheet"&&typeof l.href=="string"&&typeof l.precedence=="string"){n=Qa(l.href);var g=Ze(m).hoistableStyles,y=g.get(n);if(y||(m=m.ownerDocument||m,y={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},g.set(n,y),(g=m.querySelector(no(n)))&&!g._p&&(y.instance=g,y.state.loading=5),nr.has(n)||(l={rel:"preload",as:"style",href:l.href,crossOrigin:l.crossOrigin,integrity:l.integrity,media:l.media,hrefLang:l.hrefLang,referrerPolicy:l.referrerPolicy},nr.set(n,l),g||tC(m,n,l,y.state))),r&&u===null)throw Error(s(528,""));return y}if(r&&u!==null)throw Error(s(529,""));return null;case"script":return r=l.async,l=l.src,typeof l=="string"&&r&&typeof r!="function"&&typeof r!="symbol"?(r=Ja(l),l=Ze(m).hoistableScripts,u=l.get(r),u||(u={type:"script",instance:null,count:0,state:null},l.set(r,u)),u):{type:"void",instance:null,count:0,state:null};default:throw Error(s(444,n))}}function Qa(n){return'href="'+Zi(n)+'"'}function no(n){return'link[rel="stylesheet"]['+n+"]"}function P_(n){return x({},n,{"data-precedence":n.precedence,precedence:null})}function tC(n,r,l,u){n.querySelector('link[rel="preload"][as="style"]['+r+"]")?u.loading=1:(r=n.createElement("link"),u.preload=r,r.addEventListener("load",function(){return u.loading|=1}),r.addEventListener("error",function(){return u.loading|=2}),tn(r,"link",l),Qe(r),n.head.appendChild(r))}function Ja(n){return'[src="'+Zi(n)+'"]'}function ro(n){return"script[async]"+n}function I_(n,r,l){if(r.count++,r.instance===null)switch(r.type){case"style":var u=n.querySelector('style[data-href~="'+Zi(l.href)+'"]');if(u)return r.instance=u,Qe(u),u;var m=x({},l,{"data-href":l.href,"data-precedence":l.precedence,href:null,precedence:null});return u=(n.ownerDocument||n).createElement("style"),Qe(u),tn(u,"style",m),qc(u,l.precedence,n),r.instance=u;case"stylesheet":m=Qa(l.href);var g=n.querySelector(no(m));if(g)return r.state.loading|=4,r.instance=g,Qe(g),g;u=P_(l),(m=nr.get(m))&&Id(u,m),g=(n.ownerDocument||n).createElement("link"),Qe(g);var y=g;return y._p=new Promise(function(k,O){y.onload=k,y.onerror=O}),tn(g,"link",u),r.state.loading|=4,qc(g,l.precedence,n),r.instance=g;case"script":return g=Ja(l.src),(m=n.querySelector(ro(g)))?(r.instance=m,Qe(m),m):(u=l,(m=nr.get(g))&&(u=x({},l),Hd(u,m)),n=n.ownerDocument||n,m=n.createElement("script"),Qe(m),tn(m,"link",u),n.head.appendChild(m),r.instance=m);case"void":return null;default:throw Error(s(443,r.type))}else r.type==="stylesheet"&&(r.state.loading&4)===0&&(u=r.instance,r.state.loading|=4,qc(u,l.precedence,n));return r.instance}function qc(n,r,l){for(var u=l.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),m=u.length?u[u.length-1]:null,g=m,y=0;y title"):null)}function iC(n,r,l){if(l===1||r.itemProp!=null)return!1;switch(n){case"meta":case"title":return!0;case"style":if(typeof r.precedence!="string"||typeof r.href!="string"||r.href==="")break;return!0;case"link":if(typeof r.rel!="string"||typeof r.href!="string"||r.href===""||r.onLoad||r.onError)break;switch(r.rel){case"stylesheet":return n=r.disabled,typeof r.precedence=="string"&&n==null;default:return!0}case"script":if(r.async&&typeof r.async!="function"&&typeof r.async!="symbol"&&!r.onLoad&&!r.onError&&r.src&&typeof r.src=="string")return!0}return!1}function $_(n){return!(n.type==="stylesheet"&&(n.state.loading&3)===0)}function nC(n,r,l,u){if(l.type==="stylesheet"&&(typeof u.media!="string"||matchMedia(u.media).matches!==!1)&&(l.state.loading&4)===0){if(l.instance===null){var m=Qa(u.href),g=r.querySelector(no(m));if(g){r=g._p,r!==null&&typeof r=="object"&&typeof r.then=="function"&&(n.count++,n=Gc.bind(n),r.then(n,n)),l.state.loading|=4,l.instance=g,Qe(g);return}g=r.ownerDocument||r,u=P_(u),(m=nr.get(m))&&Id(u,m),g=g.createElement("link"),Qe(g);var y=g;y._p=new Promise(function(k,O){y.onload=k,y.onerror=O}),tn(g,"link",u),l.instance=g}n.stylesheets===null&&(n.stylesheets=new Map),n.stylesheets.set(l,r),(r=l.state.preload)&&(l.state.loading&3)===0&&(n.count++,l=Gc.bind(n),r.addEventListener("load",l),r.addEventListener("error",l))}}var Ud=0;function rC(n,r){return n.stylesheets&&n.count===0&&Vc(n,n.stylesheets),0Ud?50:800)+r);return n.unsuspend=l,function(){n.unsuspend=null,clearTimeout(u),clearTimeout(m)}}:null}function Gc(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Vc(this,this.stylesheets);else if(this.unsuspend){var n=this.unsuspend;this.unsuspend=null,n()}}}var Yc=null;function Vc(n,r){n.stylesheets=null,n.unsuspend!==null&&(n.count++,Yc=new Map,r.forEach(sC,n),Yc=null,Gc.call(n))}function sC(n,r){if(!(r.state.loading&4)){var l=Yc.get(n);if(l)var u=l.get(null);else{l=new Map,Yc.set(n,l);for(var m=n.querySelectorAll("link[data-precedence],style[data-precedence]"),g=0;g"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Xd.exports=SC(),Xd.exports}var CC=wC();const kC=Pu(CC);function EC({onLogin:e}){const[t,i]=w.useState(""),[s,a]=w.useState(null),[o,c]=w.useState(!1),h=async p=>{if(p.preventDefault(),!t.trim())return;c(!0),a(null);const f=await e(t);f&&a(f),c(!1)};return d.jsx("div",{className:"flex h-screen items-center justify-center p-4",children:d.jsxs("div",{className:"w-full max-w-sm",children:[d.jsxs("div",{className:"border-border rounded border p-6",children:[d.jsxs("div",{className:"mb-6 text-center",children:[d.jsx("h1",{className:"text-accent text-lg font-bold tracking-tight",children:"PlotLink OWS"}),d.jsx("p",{className:"text-muted mt-1 text-xs",children:"local writer agent"})]}),d.jsxs("form",{onSubmit:h,className:"space-y-4",children:[d.jsxs("div",{children:[d.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Passphrase"}),d.jsx("input",{type:"password",value:t,onChange:p=>i(p.target.value),placeholder:"enter your passphrase",autoFocus:!0,className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"})]}),s&&d.jsx("p",{className:"text-error text-xs",children:s}),d.jsx("button",{type:"submit",disabled:o||!t.trim(),className:"border-accent text-accent hover:bg-accent/10 disabled:opacity-40 w-full rounded border px-4 py-2 text-sm font-medium transition-colors",children:o?"authenticating...":"unlock"})]})]}),d.jsx("p",{className:"text-muted mt-4 text-center text-[10px]",children:"enter your passphrase to unlock"})]})})}function NC({onSetup:e}){const[t,i]=w.useState(""),[s,a]=w.useState(""),[o,c]=w.useState(null),[h,p]=w.useState(!1),f=async _=>{if(_.preventDefault(),!t.trim()||t.length<4){c("Passphrase must be at least 4 characters");return}if(t!==s){c("Passphrases do not match");return}p(!0),c(null);const x=await e(t);x&&c(x),p(!1)};return d.jsx("div",{className:"flex h-screen items-center justify-center p-4",children:d.jsx("div",{className:"w-full max-w-sm",children:d.jsxs("div",{className:"border-border rounded border p-6",children:[d.jsxs("div",{className:"mb-6 text-center",children:[d.jsx("h1",{className:"text-accent text-lg font-bold tracking-tight",children:"PlotLink OWS"}),d.jsx("p",{className:"text-muted mt-1 text-xs",children:"first-time setup"})]}),d.jsx("p",{className:"text-muted mb-4 text-xs leading-relaxed",children:"Choose a passphrase to protect your local writer agent. This will be used to unlock the app and secure your OWS wallet."}),d.jsxs("form",{onSubmit:f,className:"space-y-4",children:[d.jsxs("div",{children:[d.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Passphrase"}),d.jsx("input",{type:"password",value:t,onChange:_=>i(_.target.value),placeholder:"choose a passphrase",autoFocus:!0,className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Confirm"}),d.jsx("input",{type:"password",value:s,onChange:_=>a(_.target.value),placeholder:"repeat passphrase",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"})]}),o&&d.jsx("p",{className:"text-error text-xs",children:o}),d.jsx("button",{type:"submit",disabled:h||!t.trim()||!s.trim(),className:"border-accent text-accent hover:bg-accent/10 disabled:opacity-40 w-full rounded border px-4 py-2 text-sm font-medium transition-colors",children:h?"setting up...":"create passphrase"})]})]})})})}const ef="http://localhost:7777";function Dy({token:e}){const[t,i]=w.useState(null),[s,a]=w.useState(!1),[o,c]=w.useState(null),[h,p]=w.useState(!1),[f,_]=w.useState(null),x=w.useCallback((E,L)=>fetch(E,{...L,headers:{...L==null?void 0:L.headers,Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),[e]),b=w.useCallback(()=>{x(`${ef}/api/wallet`).then(E=>E.json()).then(E=>i(E)).catch(()=>i({exists:!1,error:"Failed to load wallet"}))},[x]);w.useEffect(()=>{b()},[b]);const v=async()=>{a(!0),_(null);try{const E=await x(`${ef}/api/wallet/create`,{method:"POST"}),L=await E.json();if(!E.ok)throw new Error(L.error||"Creation failed");b()}catch(E){_(E instanceof Error?E.message:"Failed to create wallet")}a(!1)},S=async E=>{c(E.walletId||E.name),_(null);try{const L=await x(`${ef}/api/wallet/active`,{method:"POST",body:JSON.stringify({walletId:E.walletId,name:E.name,address:E.normalizedAddress||E.address})}),I=await L.json();if(!L.ok)throw new Error(I.error||"Wallet switch failed");b()}catch(L){_(L instanceof Error?L.message:"Failed to switch wallet")}c(null)},N=()=>{t!=null&&t.address&&(navigator.clipboard.writeText(t.address),p(!0),setTimeout(()=>p(!1),2e3))},M=E=>`${E.slice(0,6)}...${E.slice(-4)}`;return d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"OWS Wallet"}),!t&&d.jsx("p",{className:"text-muted text-xs",children:"loading..."}),t&&!t.exists&&d.jsxs("div",{className:"space-y-3",children:[d.jsx("p",{className:"text-muted text-xs",children:t.error||"No wallet created yet. Create one to enable autonomous transactions."}),f&&d.jsx("p",{className:"text-error text-xs",children:f}),d.jsx("button",{onClick:v,disabled:s,className:"border-accent text-accent hover:bg-accent/10 disabled:opacity-40 rounded border px-4 py-2 text-xs font-medium transition-colors",children:s?"creating...":"create wallet"})]}),(t==null?void 0:t.selectionRequired)&&t.wallets&&t.wallets.length>0&&d.jsxs("div",{className:"mb-4 space-y-3 rounded border border-amber-600/30 bg-amber-950/10 p-3",children:[d.jsx("p",{className:"text-xs text-amber-700",children:"Multiple OWS wallets found. Select the wallet OWS should use for publishing and signing."}),t.wallets.map(E=>d.jsxs("div",{className:"border-border flex items-center justify-between gap-3 rounded border p-2",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsx("p",{className:"text-foreground truncate text-xs font-medium",children:E.name}),d.jsx("p",{className:"text-muted truncate text-[10px] font-mono",children:E.address||"No EVM address"})]}),d.jsx("button",{onClick:()=>S(E),disabled:!E.address||o===(E.walletId||E.name),className:"border-accent text-accent hover:bg-accent/10 disabled:opacity-40 rounded border px-2 py-1 text-[10px] font-medium transition-colors",children:o===(E.walletId||E.name)?"switching...":"use"})]},E.walletId||E.name)),f&&d.jsx("p",{className:"text-error text-xs",children:f})]}),t&&t.exists&&t.address&&d.jsxs("div",{className:"space-y-3",children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-muted text-[10px] uppercase tracking-wider",children:"Active Wallet (Base)"}),d.jsx("span",{className:`rounded border px-1.5 py-0.5 text-[9px] ${t.ethBalance&&parseFloat(t.ethBalance)>0?"border-accent/30 text-accent":"border-accent-dim/30 text-accent-dim"}`,children:t.ethBalance&&parseFloat(t.ethBalance)>0?"active":"no balance"})]}),t.name&&d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Name"}),d.jsx("span",{className:"text-foreground truncate pl-3 font-mono text-[10px]",children:t.name})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("code",{className:"text-foreground bg-surface rounded px-2 py-1 text-xs font-mono",children:M(t.address)}),d.jsx("button",{onClick:N,className:"text-muted hover:text-accent text-xs transition-colors",children:h?"copied":"copy"})]}),d.jsxs("div",{className:"border-border space-y-1 border-t pt-3",children:[d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"ETH"}),d.jsxs("span",{className:"text-foreground font-medium",children:[t.ethBalance||"0.000000"," ETH"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"USDC"}),d.jsxs("span",{className:"text-foreground font-medium",children:["$",t.usdcBalance||"0.00"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"PLOT"}),d.jsxs("span",{className:"text-foreground font-medium",children:[t.plotBalance||"0.0000"," PLOT"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Network"}),d.jsx("span",{className:"text-foreground",children:"Base"})]})]}),t.wallets&&t.wallets.length>1&&d.jsxs("div",{className:"border-border space-y-2 border-t pt-3",children:[d.jsx("p",{className:"text-muted text-[10px] font-medium uppercase tracking-wider",children:"Switch Wallet"}),t.wallets.map(E=>d.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsxs("p",{className:E.active?"text-accent truncate font-medium":"text-foreground truncate",children:[E.name,E.active?" (active)":""]}),d.jsx("p",{className:"text-muted truncate text-[10px] font-mono",children:E.address||"No EVM address"})]}),!E.active&&d.jsx("button",{onClick:()=>S(E),disabled:!E.address||o===(E.walletId||E.name),className:"border-border text-muted hover:border-accent hover:text-accent disabled:opacity-40 rounded border px-2 py-1 text-[10px] transition-colors",children:o===(E.walletId||E.name)?"...":"use"})]},E.walletId||E.name)),f&&d.jsx("p",{className:"text-error text-xs",children:f})]}),d.jsxs("div",{className:"border-border border-t pt-3",children:[d.jsx("p",{className:"text-muted mb-2 text-[10px] font-medium uppercase tracking-wider",children:"Fund Wallet"}),d.jsx("p",{className:"text-muted text-[10px]",children:"Send ETH on Base for gas (~$0.01 per publish):"}),d.jsx("code",{className:"text-foreground bg-surface mt-1 block break-all rounded px-2 py-1.5 text-[10px] font-mono",children:t.address})]})]}),(t==null?void 0:t.exists)&&d.jsx("button",{onClick:v,disabled:s,className:"border-border text-muted hover:border-accent hover:text-accent disabled:opacity-40 mt-4 rounded border px-3 py-1.5 text-[10px] font-medium transition-colors",children:s?"creating...":"create another wallet"})]})}function Eu(e){return!!e&&e.codex.installed&&e.codex.auth==="unknown"}const Fp="Codex is installed but its capabilities couldn't be read — you may need to log in to Codex (resolve outside OWS), then re-check.";function jC({token:e,onLogout:t}){const[i,s]=w.useState(""),[a,o]=w.useState(""),[c,h]=w.useState(null),[p,f]=w.useState(!1),[_,x]=w.useState(!1),[b,v]=w.useState(null),[S,N]=w.useState("AI Writer"),[M,E]=w.useState(""),[L,I]=w.useState(""),[A,q]=w.useState(!1),[R,ne]=w.useState(null),[ue,ye]=w.useState(""),[B,re]=w.useState(null),[$,G]=w.useState(!1),[V,H]=w.useState(null),[T,z]=w.useState(null),[F,xe]=w.useState(null),j=w.useCallback((ae,oe)=>fetch(ae,{...oe,headers:{...oe==null?void 0:oe.headers,Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),[e]);w.useEffect(()=>{j("/api/settings/link-status").then(ae=>ae.json()).then(ae=>v(ae)).catch(()=>v({linked:!1}))},[]),w.useEffect(()=>{j("/api/agent/readiness").then(ae=>ae.ok?ae.json():null).then(ae=>{ae&&xe(ae)}).catch(()=>{})},[]);const D=async()=>{if(!S.trim()){ne("Agent name is required");return}if(!M.trim()){ne("Description is required");return}q(!0),ne(null);try{const ae=await j("/api/settings/register-agent",{method:"POST",body:JSON.stringify({name:S,description:M,...L.trim()&&{genre:L}})}),oe=await ae.json();if(!ae.ok)throw new Error(oe.error||"Registration failed");v({linked:!0,agentId:oe.agentId,owsWallet:oe.owsWallet,txHash:oe.txHash})}catch(ae){ne(ae instanceof Error?ae.message:"Registration failed")}q(!1)},X=async()=>{if(!ue.trim()||!/^0x[a-fA-F0-9]{40}$/.test(ue)){H("Enter a valid wallet address (0x...)");return}G(!0),H(null),re(null);try{const ae=await j("/api/settings/generate-binding",{method:"POST",body:JSON.stringify({humanWallet:ue})}),oe=await ae.json();if(!ae.ok)throw new Error(oe.error||"Failed to generate binding code");re(oe)}catch(ae){H(ae instanceof Error?ae.message:"Failed to generate binding code")}G(!1)},C=async(ae,oe)=>{await navigator.clipboard.writeText(ae),z(oe),setTimeout(()=>z(null),2e3)},Z=async()=>{if(h(null),f(!1),!i||i.length<4){h("Passphrase must be at least 4 characters");return}if(i!==a){h("Passphrases do not match");return}x(!0);try{const ae=await j("/api/auth/reset-passphrase",{method:"POST",body:JSON.stringify({passphrase:i})});if(!ae.ok){const oe=await ae.json();throw new Error(oe.error||"Reset failed")}f(!0),s(""),o(""),setTimeout(()=>f(!1),3e3)}catch(ae){h(ae instanceof Error?ae.message:"Reset failed")}x(!1)};return d.jsxs("div",{className:"mx-auto max-w-lg space-y-6 p-6",children:[d.jsx("h2",{className:"text-accent text-lg font-bold",children:"Settings"}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Agent Identity"}),b!=null&&b.linked?d.jsxs("div",{className:"space-y-2",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"text-sm font-medium text-accent",children:"Registered"}),d.jsxs("span",{className:"text-muted text-xs",children:["Agent #",b.agentId]})]}),b.owsWallet&&d.jsxs("p",{className:"text-muted text-xs font-mono",children:["Wallet: ",b.owsWallet.slice(0,6),"...",b.owsWallet.slice(-4)]}),b.owner&&d.jsxs("p",{className:"text-muted text-xs font-mono",children:["Owner: ",b.owner.slice(0,6),"...",b.owner.slice(-4)]}),b.txHash&&d.jsx("p",{className:"text-muted text-xs",children:d.jsx("a",{href:`https://basescan.org/tx/${b.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View transaction on BaseScan"})}),d.jsx("p",{className:"text-muted text-xs",children:d.jsx("a",{href:`https://plotlink.xyz/profile/${b.owsWallet}`,target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View agent profile on plotlink.xyz"})})]}):d.jsxs("div",{className:"space-y-3",children:[d.jsx("p",{className:"text-muted text-xs",children:"Register this AI writer on-chain via ERC-8004. Uses your OWS wallet's existing ETH balance for gas."}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Name"}),d.jsx("input",{value:S,onChange:ae=>N(ae.target.value),placeholder:"AI Writer",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Description"}),d.jsx("input",{value:M,onChange:ae=>E(ae.target.value),placeholder:"An AI writing assistant for fiction stories",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Genre (optional)"}),d.jsx("input",{value:L,onChange:ae=>I(ae.target.value),placeholder:"e.g. Fiction, Sci-Fi, Fantasy",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"})]}),R&&d.jsx("p",{className:"text-error text-xs",children:R}),d.jsx("button",{onClick:D,disabled:A||!S.trim()||!M.trim(),className:"bg-accent text-white hover:bg-accent-dim disabled:opacity-50 w-full rounded px-4 py-2 text-sm font-medium transition-colors",children:A?"Registering...":"Register Agent Identity"})]})]}),d.jsxs("div",{className:"border-border rounded border p-4","data-testid":"provider-readiness",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Agent Providers"}),d.jsxs("div",{className:"space-y-2",children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Claude"}),d.jsx("span",{className:"text-muted text-xs",children:F!=null&&F.claude.installed?"Installed":"Not detected"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Codex"}),d.jsx("span",{className:"text-muted text-xs",children:F!=null&&F.codex.installed?"Installed":"Not detected"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Codex version"}),d.jsx("span",{className:"text-muted text-xs font-mono",children:(F==null?void 0:F.codex.version)??"—"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Image generation"}),d.jsx("span",{className:"text-muted text-xs",children:(F==null?void 0:F.codex.imageGeneration)??"unknown"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Codex auth"}),d.jsx("span",{className:"text-muted text-xs","data-testid":"codex-auth-status",children:F!=null&&F.codex.installed?F.codex.auth==="ok"?"ok":"unclear":"—"})]}),Eu(F)&&d.jsx("p",{className:"text-[11px] text-amber-700","data-testid":"codex-auth-unknown-settings",children:Fp}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Last checked"}),d.jsx("span",{className:"text-muted text-xs",children:F!=null&&F.checkedAt?new Date(F.checkedAt).toLocaleString():"—"})]})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Link to PlotLink"}),b!=null&&b.owner?d.jsxs("p",{className:"text-muted text-xs",children:["Linked to owner ",d.jsxs("span",{className:"font-mono",children:[b.owner.slice(0,6),"...",b.owner.slice(-4)]})]}):d.jsxs("div",{className:"space-y-3",children:[d.jsx("p",{className:"text-muted text-xs",children:"Link this OWS wallet to your PlotLink account so your stories appear under your profile on plotlink.xyz."}),d.jsxs("div",{className:"text-muted text-xs space-y-1 pl-3",children:[d.jsx("p",{children:"1. Enter your PlotLink wallet address below"}),d.jsx("p",{children:'2. Click "Generate Binding Code"'}),d.jsx("p",{children:"3. Copy the code and paste it on plotlink.xyz → Agents → Link AI Writer"})]}),d.jsx("input",{value:ue,onChange:ae=>ye(ae.target.value),placeholder:"Your PlotLink wallet address (0x...)",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent font-mono"}),V&&d.jsx("p",{className:"text-error text-xs",children:V}),d.jsx("button",{onClick:X,disabled:$||!ue.trim(),className:"bg-accent text-white hover:bg-accent-dim disabled:opacity-50 w-full rounded px-4 py-2 text-sm font-medium transition-colors",children:$?"Generating...":"Generate Binding Code"}),B&&d.jsxs("div",{className:"space-y-3 mt-3",children:[d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Binding Code (signature)"}),d.jsxs("div",{className:"relative",children:[d.jsx("div",{className:"bg-surface border-border rounded border p-2 text-xs font-mono break-all text-foreground pr-16",children:B.signature}),d.jsx("button",{onClick:()=>C(B.signature,"signature"),className:"absolute top-1 right-1 text-xs px-2 py-1 rounded border border-border text-muted hover:text-accent hover:border-accent transition-colors",children:T==="signature"?"Copied!":"Copy"})]})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"OWS Wallet Address"}),d.jsxs("div",{className:"relative",children:[d.jsx("div",{className:"bg-surface border-border rounded border p-2 text-xs font-mono break-all text-foreground pr-16",children:B.owsWallet}),d.jsx("button",{onClick:()=>C(B.owsWallet,"wallet"),className:"absolute top-1 right-1 text-xs px-2 py-1 rounded border border-border text-muted hover:text-accent hover:border-accent transition-colors",children:T==="wallet"?"Copied!":"Copy"})]})]}),B.agentId&&d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Agent ID"}),d.jsxs("div",{className:"relative",children:[d.jsx("div",{className:"bg-surface border-border rounded border p-2 text-xs font-mono text-foreground pr-16",children:B.agentId}),d.jsx("button",{onClick:()=>C(String(B.agentId),"agentId"),className:"absolute top-1 right-1 text-xs px-2 py-1 rounded border border-border text-muted hover:text-accent hover:border-accent transition-colors",children:T==="agentId"?"Copied!":"Copy"})]})]}),d.jsx("p",{className:"text-xs text-accent",children:'Now go to plotlink.xyz/agents and paste the values in the "Link AI Writer" section.'})]})]})]}),d.jsx(Dy,{token:e}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Reset Passphrase"}),d.jsxs("div",{className:"space-y-3",children:[d.jsx("input",{type:"password",value:i,onChange:ae=>s(ae.target.value),placeholder:"new passphrase",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"}),d.jsx("input",{type:"password",value:a,onChange:ae=>o(ae.target.value),placeholder:"confirm passphrase",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"}),c&&d.jsx("p",{className:"text-error text-xs",children:c}),p&&d.jsx("p",{className:"text-xs text-accent",children:"passphrase updated"}),d.jsx("button",{onClick:Z,disabled:_||!i.trim(),className:"border-border text-muted hover:border-accent hover:text-accent disabled:opacity-40 w-full rounded border px-4 py-2 text-xs font-medium transition-colors",children:_?"updating...":"update passphrase"})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Session"}),d.jsx("button",{onClick:t,className:"border-border text-muted hover:border-error hover:text-error rounded border px-4 py-2 text-xs font-medium transition-colors",children:"logout"})]})]})}const TC="http://localhost:7777";function AC({token:e}){const[t,i]=w.useState(null),s=w.useCallback((h,p)=>fetch(h,{...p,headers:{...p==null?void 0:p.headers,Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),[e]),a=w.useCallback(()=>{s(`${TC}/api/dashboard`).then(h=>h.json()).then(i)},[s]);w.useEffect(()=>{a()},[a]);const o=h=>`${h.slice(0,6)}...${h.slice(-4)}`,c=h=>{if(!h)return"Unknown date";const p=new Date(h);return isNaN(p.getTime())?"Unknown date":p.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})};return t?d.jsxs("div",{className:"mx-auto max-w-2xl space-y-6 p-6",children:[d.jsx("h2",{className:"text-accent text-lg font-bold",children:"Writer Dashboard"}),d.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[d.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[d.jsx("div",{className:"text-accent text-lg font-bold",children:t.stories.totalPublished}),d.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"published"})]}),d.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[d.jsx("div",{className:"text-foreground text-lg font-bold",children:t.stories.pendingFiles}),d.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"pending"})]}),d.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[d.jsx("div",{className:"text-foreground text-lg font-bold",children:t.stories.totalStories}),d.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"stories"})]}),d.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[d.jsx("div",{className:"text-foreground text-lg font-bold",children:t.stories.totalFiles}),d.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"files"})]})]}),t.wallet&&d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Wallet"}),d.jsxs("div",{className:"space-y-1.5",children:[t.wallet.name&&d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Active wallet"}),d.jsx("span",{className:"text-foreground truncate pl-3 font-mono text-[10px]",children:t.wallet.name})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Address"}),d.jsx("code",{className:"text-foreground font-mono text-[10px]",children:o(t.wallet.address)})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"ETH Balance"}),d.jsxs("span",{className:"text-foreground",children:[t.wallet.ethFormatted," ETH"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"USDC Balance"}),d.jsxs("span",{className:"text-foreground",children:["$",t.wallet.usdcBalance]})]})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Profit & Loss"}),d.jsxs("div",{className:"space-y-1.5",children:[d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Total costs (gas)"}),d.jsxs("span",{className:"text-error",children:["-",t.pnl.totalCostsEth," ETH (~$",t.pnl.totalCostsUsd,")"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Royalties earned"}),d.jsxs("span",{className:"text-accent",children:["+",t.pnl.totalRoyaltiesPlot," PLOT"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Unclaimed royalties"}),d.jsxs("span",{className:"text-foreground",children:[t.royalties.unclaimed," PLOT"]})]}),d.jsxs("div",{className:"border-border flex justify-between border-t pt-1.5 text-xs font-medium",children:[d.jsx("span",{className:"text-muted",children:"Net P&L (USD)"}),d.jsxs("span",{className:parseFloat(t.pnl.netPnlUsd)>=0?"text-accent":"text-error",children:[parseFloat(t.pnl.netPnlUsd)>=0?"+":"","$",t.pnl.netPnlUsd]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Stories published"}),d.jsx("span",{className:"text-foreground",children:t.costs.storiesPublished})]})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Published Stories"}),t.stories.published.length===0?d.jsx("p",{className:"text-muted text-xs",children:"no published stories yet"}):d.jsx("div",{className:"space-y-3",children:t.stories.published.map(h=>d.jsxs("div",{className:"bg-surface rounded border border-border p-4",children:[d.jsxs("div",{className:"flex items-start justify-between",children:[d.jsxs("div",{children:[h.genre&&d.jsx("span",{className:"bg-accent/10 text-accent rounded px-2 py-0.5 text-[10px] font-medium",children:h.genre}),d.jsx("h4",{className:"text-foreground mt-1 text-sm font-serif font-medium",children:h.title}),d.jsx("p",{className:"text-muted mt-0.5 text-[10px] font-mono",children:h.storyName})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[h.hasNotIndexed&&d.jsx("span",{className:"rounded border border-amber-600/30 px-1.5 py-0.5 text-[9px] text-amber-700",children:"not indexed"}),d.jsxs("span",{className:"rounded border border-green-700/30 px-1.5 py-0.5 text-[9px] text-green-700",children:[h.publishedFiles," published"]})]})]}),d.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-center",children:[d.jsxs("div",{className:"rounded bg-background p-1.5",children:[d.jsx("div",{className:"text-foreground text-sm font-medium",children:h.plotCount}),d.jsx("div",{className:"text-muted text-[9px]",children:"Plots"})]}),d.jsxs("div",{className:"rounded bg-background p-1.5",children:[d.jsx("div",{className:"text-foreground text-sm font-medium font-mono",children:h.storylineId?`#${h.storylineId}`:"—"}),d.jsx("div",{className:"text-muted text-[9px]",children:"Storyline"})]}),d.jsxs("div",{className:"rounded bg-background p-1.5",children:[d.jsx("div",{className:"text-foreground text-sm font-medium",children:h.totalGasCostEth??"—"}),d.jsx("div",{className:"text-muted text-[9px]",children:"Gas (ETH)"})]})]}),d.jsx("div",{className:"mt-2 space-y-1",children:h.files.map(p=>d.jsxs("div",{className:"flex items-center justify-between text-[10px]",children:[d.jsxs("div",{className:"flex items-center gap-1.5",children:[d.jsx("span",{className:p.status==="published-not-indexed"?"text-amber-700":"text-green-700",children:p.status==="published-not-indexed"?"⚠":"✓"}),d.jsx("span",{className:"text-muted font-mono",children:p.file})]}),p.txHash&&d.jsxs("a",{href:`https://basescan.org/tx/${p.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted hover:text-accent font-mono",children:["tx:",p.txHash.slice(0,8),"..."]})]},p.file))}),d.jsxs("div",{className:"mt-2 flex items-center justify-between text-[10px]",children:[d.jsx("span",{className:"text-muted",children:c(h.latestPublishedAt)}),h.storylineId&&d.jsx("a",{href:`https://plotlink.xyz/story/${h.storylineId}`,target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View on PlotLink"})]})]},h.id))})]}),t.stories.pendingFiles>0&&d.jsx("div",{className:"border-border rounded border p-4",children:d.jsxs("p",{className:"text-muted text-xs",children:[t.stories.pendingFiles," file(s) pending publish — go to Stories to publish them."]})})]}):d.jsx("div",{className:"flex h-full items-center justify-center",children:d.jsx("span",{className:"text-muted text-sm",children:"loading dashboard..."})})}const RC={published:"✓","published-not-indexed":"⚠",pending:"⏳",draft:"📝"},DC={published:"text-green-700","published-not-indexed":"text-amber-700",pending:"text-amber-700",draft:"text-muted"};function MC({authFetch:e,selectedStory:t,selectedFile:i,onSelectFile:s,onNewStory:a,untitledSessions:o=[]}){const[c,h]=w.useState([]),[p,f]=w.useState([]),[_,x]=w.useState(new Set),[b,v]=w.useState(!1),S=w.useCallback(async()=>{try{const q=await e("/api/stories");if(q.ok){const R=await q.json();h(R.stories)}}catch{}},[e]),N=w.useCallback(async()=>{try{const q=await e("/api/stories/archived");if(q.ok){const R=await q.json();f(R.stories)}}catch{}},[e]),M=w.useCallback(async q=>{try{(await e("/api/stories/restore",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:q})})).ok&&(N(),S())}catch{}},[e,N,S]);w.useEffect(()=>{S();const q=setInterval(S,5e3);return()=>clearInterval(q)},[S]),w.useEffect(()=>{b&&N()},[b,N]),w.useEffect(()=>{t&&x(q=>new Set(q).add(t))},[t]);const E=q=>{x(R=>{const ne=new Set(R);return ne.has(q)?ne.delete(q):ne.add(q),ne})},L=q=>{var ne;const R=q.map(ue=>{var ye;return{file:ue.file,num:(ye=ue.file.match(/^plot-(\d+)\.md$/))==null?void 0:ye[1]}}).filter(ue=>ue.num!=null).sort((ue,ye)=>parseInt(ye.num)-parseInt(ue.num));return R.length>0?R[0].file:q.some(ue=>ue.file==="genesis.md")?"genesis.md":q.some(ue=>ue.file==="structure.md")?"structure.md":((ne=q[0])==null?void 0:ne.file)??null},I=q=>{if(E(q.name),q.contentType==="cartoon")s(q.name,"");else{const R=L(q.files);R&&s(q.name,R)}},A=q=>{const R=ne=>{if(ne==="structure.md")return 0;if(ne==="genesis.md")return 1;const ue=ne.match(/^plot-(\d+)\.md$/);return ue?2+parseInt(ue[1]):100};return[...q].sort((ne,ue)=>R(ne.file)-R(ue.file))};return b?d.jsxs("div",{className:"h-full flex flex-col",children:[d.jsxs("div",{className:"px-3 py-1.5 border-b border-border flex items-center justify-between",children:[d.jsx("span",{className:"text-xs font-mono text-muted",children:"Archives"}),d.jsx("span",{className:"text-xs text-muted",children:p.length})]}),d.jsx("div",{className:"px-3 py-2 border-b border-border",children:d.jsxs("button",{onClick:()=>v(!1),className:"w-full px-3 py-1.5 text-sm text-muted hover:text-foreground hover:bg-surface rounded flex items-center gap-1.5",children:[d.jsx("span",{children:"←"}),d.jsx("span",{children:"Back"})]})}),d.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:p.length===0?d.jsx("div",{className:"p-3 text-sm text-muted",children:d.jsx("p",{children:"No archived stories."})}):p.map(q=>d.jsxs("div",{className:"px-3 py-2 flex items-center justify-between hover:bg-surface",children:[d.jsx("span",{className:"text-sm font-medium truncate",title:q.name,children:q.title||q.name}),d.jsx("button",{onClick:()=>M(q.name),className:"text-xs text-accent hover:text-accent-dim flex-shrink-0 ml-2",children:"Restore"})]},q.name))})]}):d.jsxs("div",{className:"h-full flex flex-col",children:[d.jsxs("div",{className:"px-3 py-1.5 border-b border-border flex items-center justify-between",children:[d.jsx("span",{className:"text-xs font-mono text-muted",children:"Stories"}),d.jsx("span",{className:"text-xs text-muted",children:c.length})]}),a&&d.jsx("div",{className:"px-3 py-2 border-b border-border",children:d.jsxs("button",{onClick:a,className:"w-full px-3 py-1.5 text-sm bg-accent text-white rounded hover:bg-accent-dim flex items-center justify-center gap-1.5",children:[d.jsx("span",{children:"+"}),d.jsx("span",{children:"New Story"})]})}),d.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto",children:[o.map(q=>d.jsx("div",{children:d.jsxs("button",{onClick:()=>s(q,""),className:`w-full px-3 py-2 text-left flex items-center gap-2 hover:bg-surface text-sm ${t===q?"bg-surface":""}`,children:[d.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-green-600 flex-shrink-0"}),d.jsx("span",{className:"font-medium italic text-muted",children:"Untitled"})]})},q)),c.length===0&&o.length===0?d.jsxs("div",{className:"p-3 text-sm text-muted",children:[d.jsx("p",{children:"No stories yet."}),d.jsx("p",{className:"mt-1 text-xs",children:'Click "+ New Story" above to start writing.'})]}):c.filter(q=>q.name!=="_example").map(q=>d.jsxs("div",{children:[d.jsxs("button",{onClick:()=>I(q),className:"w-full px-3 py-2 text-left flex items-center gap-2 hover:bg-surface text-sm",children:[d.jsx("span",{className:"text-xs text-muted",children:_.has(q.name)?"▼":"▶"}),d.jsx("span",{className:"font-medium truncate",title:q.name,children:q.title||q.name}),q.contentType==="cartoon"&&d.jsx("span",{className:"bg-accent/10 text-accent rounded px-1.5 py-0.5 text-[10px] font-medium flex-shrink-0",children:"Cartoon"}),d.jsxs("span",{className:"ml-auto flex-shrink-0 text-xs text-muted",children:[q.publishedCount,"/",q.files.length]})]}),_.has(q.name)&&d.jsx("div",{className:"pl-4",children:A(q.files).map(R=>{const ne=t===q.name&&i===R.file;return d.jsxs("button",{onClick:()=>s(q.name,R.file),className:`w-full px-3 py-1.5 text-left flex items-center gap-2 text-xs hover:bg-surface ${ne?"bg-surface font-medium":""}`,children:[d.jsx("span",{className:DC[R.status],children:RC[R.status]}),d.jsx("span",{className:"truncate font-mono",children:R.file})]},R.file)})})]},q.name))]}),d.jsx("div",{className:"px-3 py-2 border-t border-border",children:d.jsx("button",{onClick:()=>v(!0),className:"w-full px-3 py-1.5 text-xs text-muted hover:text-foreground hover:bg-surface rounded flex items-center justify-center gap-1.5",children:d.jsx("span",{children:"Archives"})})})]})}/** +`+u.stack}}var ze=Object.prototype.hasOwnProperty,nt=e.unstable_scheduleCallback,Ee=e.unstable_cancelCallback,Wt=e.unstable_shouldYield,vi=e.unstable_requestPaint,Ct=e.unstable_now,et=e.unstable_getCurrentPriorityLevel,ee=e.unstable_ImmediatePriority,_e=e.unstable_UserBlockingPriority,Me=e.unstable_NormalPriority,He=e.unstable_LowPriority,Ze=e.unstable_IdlePriority,Gt=e.log,mi=e.unstable_setDisableYieldValue,At=null,wt=null;function Yt(n){if(typeof Gt=="function"&&mi(n),wt&&typeof wt.setStrictMode=="function")try{wt.setStrictMode(At,n)}catch{}}var ot=Math.clz32?Math.clz32:we,Ht=Math.log,$=Math.LN2;function we(n){return n>>>=0,n===0?32:31-(Ht(n)/$|0)|0}var Ae=256,Ne=262144,We=4194304;function Ie(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 C=u&134217727;return C!==0?(u=C&~g,u!==0?m=Ie(u):(y&=C,y!==0?m=Ie(y):l||(l=C&~n,l!==0&&(m=Ie(l))))):(C=u&~g,C!==0?m=Ie(C):y!==0?m=Ie(y):l||(l=u&~n,l!==0&&(m=Ie(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 xt(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 Mt(){var n=We;return We<<=1,(We&62914560)===0&&(We=4194304),n}function Ut(n){for(var r=[],l=0;31>l;l++)r.push(n);return r}function li(n,r){n.pendingLanes|=r,r!==268435456&&(n.suspendedLanes=0,n.pingedLanes=0,n.warmLanes=0)}function oi(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,z=n.expirationTimes,J=n.hiddenUpdates;for(l=y&~l;0"u")return null;try{return n.activeElement||n.body}catch{return n.body}}var Ws=/[\n"\\]/g;function Zi(n){return n.replace(Ws,function(r){return"\\"+r.charCodeAt(0).toString(16)+" "})}function Ir(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=""+Si(r)):n.value!==""+Si(r)&&(n.value=""+Si(r)):y!=="submit"&&y!=="reset"||n.removeAttribute("value"),r!=null?hr(n,y,Si(r)):l!=null?hr(n,y,Si(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=""+Si(C):n.removeAttribute("name")}function wi(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)){Xt(n);return}l=l!=null?""+Si(l):"",r=r!=null?""+Si(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),Xt(n)}function hr(n,r,l){r==="number"&&Pr(n.ownerDocument)===n||n.defaultValue===""+l||(n.defaultValue=""+l)}function Ci(n,r,l,u){if(n=n.options,r){r={};for(var m=0;m"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Cl=!1;if(wn)try{var yr={};Object.defineProperty(yr,"passive",{get:function(){Cl=!0}}),window.addEventListener("test",yr,yr),window.removeEventListener("test",yr,yr)}catch{Cl=!1}var fr=null,se=null,ke=null;function je(){if(ke)return ke;var n,r=se,l=r.length,u,m="value"in fr?fr.value:fr.textContent,g=m.length;for(n=0;n=El),Dm=" ",Mm=!1;function Bm(n,r){switch(n){case"keyup":return z1.indexOf(r.keyCode)!==-1;case"keydown":return r.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Lm(n){return n=n.detail,typeof n=="object"&&"data"in n?n.data:null}var Ea=!1;function I1(n,r){switch(n){case"compositionend":return Lm(r);case"keypress":return r.which!==32?null:(Mm=!0,Dm);case"textInput":return n=r.data,n===Dm&&Mm?null:n;default:return null}}function H1(n,r){if(Ea)return n==="compositionend"||!eh&&Bm(n,r)?(n=je(),ke=se=fr=null,Ea=!1,n):null;switch(n){case"paste":return null;case"keypress":if(!(r.ctrlKey||r.altKey||r.metaKey)||r.ctrlKey&&r.altKey){if(r.char&&1=r)return{node:l,offset:r-n};n=u}e:{for(;l;){if(l.nextSibling){l=l.nextSibling;break e}l=l.parentNode}l=void 0}l=Fm(l)}}function Wm(n,r){return n&&r?n===r?!0:n&&n.nodeType===3?!1:r&&r.nodeType===3?Wm(n,r.parentNode):"contains"in n?n.contains(r):n.compareDocumentPosition?!!(n.compareDocumentPosition(r)&16):!1:!1}function Gm(n){n=n!=null&&n.ownerDocument!=null&&n.ownerDocument.defaultView!=null?n.ownerDocument.defaultView:window;for(var r=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 nh(n){var r=n&&n.nodeName&&n.nodeName.toLowerCase();return r&&(r==="input"&&(n.type==="text"||n.type==="search"||n.type==="tel"||n.type==="url"||n.type==="password")||r==="textarea"||n.contentEditable==="true")}var V1=wn&&"documentMode"in document&&11>=document.documentMode,Na=null,rh=null,Al=null,sh=!1;function Ym(n,r,l){var u=l.window===l?l.document:l.nodeType===9?l:l.ownerDocument;sh||Na==null||Na!==Pr(u)||(u=Na,"selectionStart"in u&&nh(u)?u={start:u.selectionStart,end:u.selectionEnd}:(u=(u.ownerDocument&&u.ownerDocument.defaultView||window).getSelection(),u={anchorNode:u.anchorNode,anchorOffset:u.anchorOffset,focusNode:u.focusNode,focusOffset:u.focusOffset}),Al&&Tl(Al,u)||(Al=u,u=Uc(rh,"onSelect"),0>=y,m-=y,Sr=1<<32-ot(r)+m|l<at?(gt=Pe,Pe=null):gt=Pe.sibling;var Et=te(G,Pe,Q[at],de);if(Et===null){Pe===null&&(Pe=gt);break}n&&Pe&&Et.alternate===null&&r(G,Pe),I=g(Et,I,at),kt===null?$e=Et:kt.sibling=Et,kt=Et,Pe=gt}if(at===Q.length)return l(G,Pe),bt&&$r(G,at),$e;if(Pe===null){for(;atat?(gt=Pe,Pe=null):gt=Pe.sibling;var Bs=te(G,Pe,Et.value,de);if(Bs===null){Pe===null&&(Pe=gt);break}n&&Pe&&Bs.alternate===null&&r(G,Pe),I=g(Bs,I,at),kt===null?$e=Bs:kt.sibling=Bs,kt=Bs,Pe=gt}if(Et.done)return l(G,Pe),bt&&$r(G,at),$e;if(Pe===null){for(;!Et.done;at++,Et=Q.next())Et=fe(G,Et.value,de),Et!==null&&(I=g(Et,I,at),kt===null?$e=Et:kt.sibling=Et,kt=Et);return bt&&$r(G,at),$e}for(Pe=u(Pe);!Et.done;at++,Et=Q.next())Et=le(Pe,G,at,Et.value,de),Et!==null&&(n&&Et.alternate!==null&&Pe.delete(Et.key===null?at:Et.key),I=g(Et,I,at),kt===null?$e=Et:kt.sibling=Et,kt=Et);return n&&Pe.forEach(function(pC){return r(G,pC)}),bt&&$r(G,at),$e}function Pt(G,I,Q,de){if(typeof Q=="object"&&Q!==null&&Q.type===N&&Q.key===null&&(Q=Q.props.children),typeof Q=="object"&&Q!==null){switch(Q.$$typeof){case v:e:{for(var $e=Q.key;I!==null;){if(I.key===$e){if($e=Q.type,$e===N){if(I.tag===7){l(G,I.sibling),de=m(I,Q.props.children),de.return=G,G=de;break e}}else if(I.elementType===$e||typeof $e=="object"&&$e!==null&&$e.$$typeof===ue&&ia($e)===I.type){l(G,I.sibling),de=m(I,Q.props),Ol(de,Q),de.return=G,G=de;break e}l(G,I);break}else r(G,I);I=I.sibling}Q.type===N?(de=Zs(Q.props.children,G.mode,de,Q.key),de.return=G,G=de):(de=rc(Q.type,Q.key,Q.props,null,G.mode,de),Ol(de,Q),de.return=G,G=de)}return y(G);case S:e:{for($e=Q.key;I!==null;){if(I.key===$e)if(I.tag===4&&I.stateNode.containerInfo===Q.containerInfo&&I.stateNode.implementation===Q.implementation){l(G,I.sibling),de=m(I,Q.children||[]),de.return=G,G=de;break e}else{l(G,I);break}else r(G,I);I=I.sibling}de=dh(Q,G.mode,de),de.return=G,G=de}return y(G);case ue:return Q=ia(Q),Pt(G,I,Q,de)}if(U(Q))return Oe(G,I,Q,de);if(F(Q)){if($e=F(Q),typeof $e!="function")throw Error(s(150));return Q=$e.call(Q),Ye(G,I,Q,de)}if(typeof Q.then=="function")return Pt(G,I,hc(Q),de);if(Q.$$typeof===H)return Pt(G,I,lc(G,Q),de);dc(G,Q)}return typeof Q=="string"&&Q!==""||typeof Q=="number"||typeof Q=="bigint"?(Q=""+Q,I!==null&&I.tag===6?(l(G,I.sibling),de=m(I,Q),de.return=G,G=de):(l(G,I),de=hh(Q,G.mode,de),de.return=G,G=de),y(G)):l(G,I)}return function(G,I,Q,de){try{Ll=0;var $e=Pt(G,I,Q,de);return Pa=null,$e}catch(Pe){if(Pe===za||Pe===cc)throw Pe;var kt=Pn(29,Pe,null,G.mode);return kt.lanes=de,kt.return=G,kt}finally{}}}var ra=gg(!0),xg=gg(!1),xs=!1;function Ch(n){n.updateQueue={baseState:n.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function kh(n,r){n=n.updateQueue,r.updateQueue===n&&(r.updateQueue={baseState:n.baseState,firstBaseUpdate:n.firstBaseUpdate,lastBaseUpdate:n.lastBaseUpdate,shared:n.shared,callbacks:null})}function _s(n){return{lane:n,tag:0,payload:null,callback:null,next:null}}function bs(n,r,l){var u=n.updateQueue;if(u===null)return null;if(u=u.shared,(Tt&2)!==0){var m=u.pending;return m===null?r.next=r:(r.next=m.next,m.next=r),u.pending=r,r=nc(n),eg(n,null,l),r}return ic(n,u,r,l),nc(n)}function zl(n,r,l){if(r=r.updateQueue,r!==null&&(r=r.shared,(l&4194048)!==0)){var u=r.lanes;u&=n.pendingLanes,l|=u,r.lanes=l,Sn(n,l)}}function Eh(n,r){var l=n.updateQueue,u=n.alternate;if(u!==null&&(u=u.updateQueue,l===u)){var m=null,g=null;if(l=l.firstBaseUpdate,l!==null){do{var y={lane:l.lane,tag:l.tag,payload:l.payload,callback:null,next:null};g===null?m=g=y:g=g.next=y,l=l.next}while(l!==null);g===null?m=g=r:g=g.next=r}else m=g=r;l={baseState:u.baseState,firstBaseUpdate:m,lastBaseUpdate:g,shared:u.shared,callbacks:u.callbacks},n.updateQueue=l;return}n=l.lastBaseUpdate,n===null?l.firstBaseUpdate=r:n.next=r,l.lastBaseUpdate=r}var Nh=!1;function Pl(){if(Nh){var n=Oa;if(n!==null)throw n}}function Il(n,r,l,u){Nh=!1;var m=n.updateQueue;xs=!1;var g=m.firstBaseUpdate,y=m.lastBaseUpdate,C=m.shared.pending;if(C!==null){m.shared.pending=null;var z=C,J=z.next;z.next=null,y===null?g=J:y.next=J,y=z;var ce=n.alternate;ce!==null&&(ce=ce.updateQueue,C=ce.lastBaseUpdate,C!==y&&(C===null?ce.firstBaseUpdate=J:C.next=J,ce.lastBaseUpdate=z))}if(g!==null){var fe=m.baseState;y=0,ce=J=z=null,C=g;do{var te=C.lane&-536870913,le=te!==C.lane;if(le?(mt&te)===te:(u&te)===te){te!==0&&te===La&&(Nh=!0),ce!==null&&(ce=ce.next={lane:0,tag:C.tag,payload:C.payload,callback:null,next:null});e:{var Oe=n,Ye=C;te=r;var Pt=l;switch(Ye.tag){case 1:if(Oe=Ye.payload,typeof Oe=="function"){fe=Oe.call(Pt,fe,te);break e}fe=Oe;break e;case 3:Oe.flags=Oe.flags&-65537|128;case 0:if(Oe=Ye.payload,te=typeof Oe=="function"?Oe.call(Pt,fe,te):Oe,te==null)break e;fe=x({},fe,te);break e;case 2:xs=!0}}te=C.callback,te!==null&&(n.flags|=64,le&&(n.flags|=8192),le=m.callbacks,le===null?m.callbacks=[te]:le.push(te))}else le={lane:te,tag:C.tag,payload:C.payload,callback:C.callback,next:null},ce===null?(J=ce=le,z=fe):ce=ce.next=le,y|=te;if(C=C.next,C===null){if(C=m.shared.pending,C===null)break;le=C,C=le.next,le.next=null,m.lastBaseUpdate=le,m.shared.pending=null}}while(!0);ce===null&&(z=fe),m.baseState=z,m.firstBaseUpdate=J,m.lastBaseUpdate=ce,g===null&&(m.shared.lanes=0),Cs|=y,n.lanes=y,n.memoizedState=fe}}function _g(n,r){if(typeof n!="function")throw Error(s(191,n));n.call(r)}function bg(n,r){var l=n.callbacks;if(l!==null)for(n.callbacks=null,n=0;ng?g:8;var y=T.T,C={};T.T=C,Gh(n,!1,r,l);try{var z=m(),J=T.S;if(J!==null&&J(C,z),z!==null&&typeof z=="object"&&typeof z.then=="function"){var ce=nw(z,u);$l(n,r,ce,Fn(n))}else $l(n,r,u,Fn(n))}catch(fe){$l(n,r,{then:function(){},status:"rejected",reason:fe},Fn())}finally{P.p=g,y!==null&&C.types!==null&&(y.types=C.types),T.T=y}}function cw(){}function qh(n,r,l,u){if(n.tag!==5)throw Error(s(476));var m=Zg(n).queue;Xg(n,m,r,q,l===null?cw:function(){return Qg(n),l(u)})}function Zg(n){var r=n.memoizedState;if(r!==null)return r;r={memoizedState:q,baseState:q,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Gr,lastRenderedState:q},next:null};var l={};return r.next={memoizedState:l,baseState:l,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Gr,lastRenderedState:l},next:null},n.memoizedState=r,n=n.alternate,n!==null&&(n.memoizedState=r),r}function Qg(n){var r=Zg(n);r.next===null&&(r=n.alternate.memoizedState),$l(n,r.next.queue,{},Fn())}function Wh(){return Ji(so)}function Jg(){return _i().memoizedState}function ex(){return _i().memoizedState}function uw(n){for(var r=n.return;r!==null;){switch(r.tag){case 24:case 3:var l=Fn();n=_s(l);var u=bs(r,n,l);u!==null&&(Tn(u,r,l),zl(u,r,l)),r={cache:vh()},n.payload=r;return}r=r.return}}function hw(n,r,l){var u=Fn();l={lane:u,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null},Sc(n)?ix(r,l):(l=ch(n,r,l,u),l!==null&&(Tn(l,n,u),nx(l,r,u)))}function tx(n,r,l){var u=Fn();$l(n,r,l,u)}function $l(n,r,l,u){var m={lane:u,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null};if(Sc(n))ix(r,m);else{var g=n.alternate;if(n.lanes===0&&(g===null||g.lanes===0)&&(g=r.lastRenderedReducer,g!==null))try{var y=r.lastRenderedState,C=g(y,l);if(m.hasEagerState=!0,m.eagerState=C,zn(C,y))return ic(n,r,m,0),Ft===null&&tc(),!1}catch{}finally{}if(l=ch(n,r,m,u),l!==null)return Tn(l,n,u),nx(l,r,u),!0}return!1}function Gh(n,r,l,u){if(u={lane:2,revertLane:Cd(),gesture:null,action:u,hasEagerState:!1,eagerState:null,next:null},Sc(n)){if(r)throw Error(s(479))}else r=ch(n,l,u,2),r!==null&&Tn(r,n,2)}function Sc(n){var r=n.alternate;return n===rt||r!==null&&r===rt}function ix(n,r){Ha=mc=!0;var l=n.pending;l===null?r.next=r:(r.next=l.next,l.next=r),n.pending=r}function nx(n,r,l){if((l&4194048)!==0){var u=r.lanes;u&=n.pendingLanes,l|=u,r.lanes=l,Sn(n,l)}}var Fl={readContext:Ji,use:_c,useCallback:ui,useContext:ui,useEffect:ui,useImperativeHandle:ui,useLayoutEffect:ui,useInsertionEffect:ui,useMemo:ui,useReducer:ui,useRef:ui,useState:ui,useDebugValue:ui,useDeferredValue:ui,useTransition:ui,useSyncExternalStore:ui,useId:ui,useHostTransitionStatus:ui,useFormState:ui,useActionState:ui,useOptimistic:ui,useMemoCache:ui,useCacheRefresh:ui};Fl.useEffectEvent=ui;var rx={readContext:Ji,use:_c,useCallback:function(n,r){return mn().memoizedState=[n,r===void 0?null:r],n},useContext:Ji,useEffect:Ug,useImperativeHandle:function(n,r,l){l=l!=null?l.concat([n]):null,vc(4194308,4,Wg.bind(null,r,n),l)},useLayoutEffect:function(n,r){return vc(4194308,4,n,r)},useInsertionEffect:function(n,r){vc(4,2,n,r)},useMemo:function(n,r){var l=mn();r=r===void 0?null:r;var u=n();if(sa){Yt(!0);try{n()}finally{Yt(!1)}}return l.memoizedState=[u,r],u},useReducer:function(n,r,l){var u=mn();if(l!==void 0){var m=l(r);if(sa){Yt(!0);try{l(r)}finally{Yt(!1)}}}else m=r;return u.memoizedState=u.baseState=m,n={pending:null,lanes:0,dispatch:null,lastRenderedReducer:n,lastRenderedState:m},u.queue=n,n=n.dispatch=hw.bind(null,rt,n),[u.memoizedState,n]},useRef:function(n){var r=mn();return n={current:n},r.memoizedState=n},useState:function(n){n=Ih(n);var r=n.queue,l=tx.bind(null,rt,r);return r.dispatch=l,[n.memoizedState,l]},useDebugValue:$h,useDeferredValue:function(n,r){var l=mn();return Fh(l,n,r)},useTransition:function(){var n=Ih(!1);return n=Xg.bind(null,rt,n.queue,!0,!1),mn().memoizedState=n,[!1,n]},useSyncExternalStore:function(n,r,l){var u=rt,m=mn();if(bt){if(l===void 0)throw Error(s(407));l=l()}else{if(l=r(),Ft===null)throw Error(s(349));(mt&127)!==0||kg(u,r,l)}m.memoizedState=l;var g={value:l,getSnapshot:r};return m.queue=g,Ug(Ng.bind(null,u,g,n),[n]),u.flags|=2048,$a(9,{destroy:void 0},Eg.bind(null,u,g,l,r),null),l},useId:function(){var n=mn(),r=Ft.identifierPrefix;if(bt){var l=wr,u=Sr;l=(u&~(1<<32-ot(u)-1)).toString(32)+l,r="_"+r+"R_"+l,l=gc++,0<\/script>",g=g.removeChild(g.firstChild);break;case"select":g=typeof u.is=="string"?y.createElement("select",{is:u.is}):y.createElement("select"),u.multiple?g.multiple=!0:u.size&&(g.size=u.size);break;default:g=typeof u.is=="string"?y.createElement(m,{is:u.is}):y.createElement(m)}}g[Kt]=r,g[jt]=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&&Vr(r)}}return Qt(r),ad(r,r.type,n===null?null:n.memoizedProps,r.pendingProps,l),null;case 6:if(n&&r.stateNode!=null)n.memoizedProps!==u&&Vr(r);else{if(typeof u!="string"&&r.stateNode===null)throw Error(s(166));if(n=oe.current,Ma(r)){if(n=r.stateNode,l=r.memoizedProps,u=null,m=Qi,m!==null)switch(m.tag){case 27:case 5:u=m.memoizedProps}n[Kt]=r,n=!!(n.nodeValue===l||u!==null&&u.suppressHydrationWarning===!0||w_(n.nodeValue,l)),n||ms(r,!0)}else n=$c(n).createTextNode(u),n[Kt]=r,r.stateNode=n}return Qt(r),null;case 31:if(l=r.memoizedState,n===null||n.memoizedState!==null){if(u=Ma(r),l!==null){if(n===null){if(!u)throw Error(s(318));if(n=r.memoizedState,n=n!==null?n.dehydrated:null,!n)throw Error(s(557));n[Kt]=r}else Qs(),(r.flags&128)===0&&(r.memoizedState=null),r.flags|=4;Qt(r),n=!1}else l=gh(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=l),n=!0;if(!n)return r.flags&256?(Hn(r),r):(Hn(r),null);if((r.flags&128)!==0)throw Error(s(558))}return Qt(r),null;case 13:if(u=r.memoizedState,n===null||n.memoizedState!==null&&n.memoizedState.dehydrated!==null){if(m=Ma(r),u!==null&&u.dehydrated!==null){if(n===null){if(!m)throw Error(s(318));if(m=r.memoizedState,m=m!==null?m.dehydrated:null,!m)throw Error(s(317));m[Kt]=r}else Qs(),(r.flags&128)===0&&(r.memoizedState=null),r.flags|=4;Qt(r),m=!1}else m=gh(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=m),m=!0;if(!m)return r.flags&256?(Hn(r),r):(Hn(r),null)}return Hn(r),(r.flags&128)!==0?(r.lanes=l,r):(l=u!==null,n=n!==null&&n.memoizedState!==null,l&&(u=r.child,m=null,u.alternate!==null&&u.alternate.memoizedState!==null&&u.alternate.memoizedState.cachePool!==null&&(m=u.alternate.memoizedState.cachePool.pool),g=null,u.memoizedState!==null&&u.memoizedState.cachePool!==null&&(g=u.memoizedState.cachePool.pool),g!==m&&(u.flags|=2048)),l!==n&&l&&(r.child.flags|=8192),Nc(r,r.updateQueue),Qt(r),null);case 4:return ge(),n===null&&jd(r.stateNode.containerInfo),Qt(r),null;case 10:return qr(r.type),Qt(r),null;case 19:if(Z(xi),u=r.memoizedState,u===null)return Qt(r),null;if(m=(r.flags&128)!==0,g=u.rendering,g===null)if(m)Wl(u,!1);else{if(hi!==0||n!==null&&(n.flags&128)!==0)for(n=r.child;n!==null;){if(g=pc(n),g!==null){for(r.flags|=128,Wl(u,!1),n=g.updateQueue,r.updateQueue=n,Nc(r,n),r.subtreeFlags=0,n=l,l=r.child;l!==null;)tg(l,n),l=l.sibling;return k(xi,xi.current&1|2),bt&&$r(r,u.treeForkCount),r.child}n=n.sibling}u.tail!==null&&Ct()>Dc&&(r.flags|=128,m=!0,Wl(u,!1),r.lanes=4194304)}else{if(!m)if(n=pc(g),n!==null){if(r.flags|=128,m=!0,n=n.updateQueue,r.updateQueue=n,Nc(r,n),Wl(u,!0),u.tail===null&&u.tailMode==="hidden"&&!g.alternate&&!bt)return Qt(r),null}else 2*Ct()-u.renderingStartTime>Dc&&l!==536870912&&(r.flags|=128,m=!0,Wl(u,!1),r.lanes=4194304);u.isBackwards?(g.sibling=r.child,r.child=g):(n=u.last,n!==null?n.sibling=g:r.child=g,u.last=g)}return u.tail!==null?(n=u.tail,u.rendering=n,u.tail=n.sibling,u.renderingStartTime=Ct(),n.sibling=null,l=xi.current,k(xi,m?l&1|2:l&1),bt&&$r(r,u.treeForkCount),n):(Qt(r),null);case 22:case 23:return Hn(r),Th(),u=r.memoizedState!==null,n!==null?n.memoizedState!==null!==u&&(r.flags|=8192):u&&(r.flags|=8192),u?(l&536870912)!==0&&(r.flags&128)===0&&(Qt(r),r.subtreeFlags&6&&(r.flags|=8192)):Qt(r),l=r.updateQueue,l!==null&&Nc(r,l.retryQueue),l=null,n!==null&&n.memoizedState!==null&&n.memoizedState.cachePool!==null&&(l=n.memoizedState.cachePool.pool),u=null,r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(u=r.memoizedState.cachePool.pool),u!==l&&(r.flags|=2048),n!==null&&Z(ta),null;case 24:return l=null,n!==null&&(l=n.memoizedState.cache),r.memoizedState.cache!==l&&(r.flags|=2048),qr(ki),Qt(r),null;case 25:return null;case 30:return null}throw Error(s(156,r.tag))}function gw(n,r){switch(ph(r),r.tag){case 1:return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 3:return qr(ki),ge(),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(Hn(r),r.alternate===null)throw Error(s(340));Qs()}return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 13:if(Hn(r),n=r.memoizedState,n!==null&&n.dehydrated!==null){if(r.alternate===null)throw Error(s(340));Qs()}return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 19:return Z(xi),null;case 4:return ge(),null;case 10:return qr(r.type),null;case 22:case 23:return Hn(r),Th(),n!==null&&Z(ta),n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 24:return qr(ki),null;case 25:return null;default:return null}}function jx(n,r){switch(ph(r),r.tag){case 3:qr(ki),ge();break;case 26:case 27:case 5:Le(r);break;case 4:ge();break;case 31:r.memoizedState!==null&&Hn(r);break;case 13:Hn(r);break;case 19:Z(xi);break;case 10:qr(r.type);break;case 22:case 23:Hn(r),Th(),n!==null&&Z(ta);break;case 24:qr(ki)}}function Gl(n,r){try{var l=r.updateQueue,u=l!==null?l.lastEffect:null;if(u!==null){var m=u.next;l=m;do{if((l.tag&n)===n){u=void 0;var g=l.create,y=l.inst;u=g(),y.destroy=u}l=l.next}while(l!==m)}}catch(C){Dt(r,r.return,C)}}function Ss(n,r,l){try{var u=r.updateQueue,m=u!==null?u.lastEffect:null;if(m!==null){var g=m.next;u=g;do{if((u.tag&n)===n){var y=u.inst,C=y.destroy;if(C!==void 0){y.destroy=void 0,m=r;var z=l,J=C;try{J()}catch(ce){Dt(m,z,ce)}}}u=u.next}while(u!==g)}}catch(ce){Dt(r,r.return,ce)}}function Tx(n){var r=n.updateQueue;if(r!==null){var l=n.stateNode;try{bg(r,l)}catch(u){Dt(n,n.return,u)}}}function Ax(n,r,l){l.props=aa(n.type,n.memoizedProps),l.state=n.memoizedState;try{l.componentWillUnmount()}catch(u){Dt(n,r,u)}}function Yl(n,r){try{var l=n.ref;if(l!==null){switch(n.tag){case 26:case 27:case 5:var u=n.stateNode;break;case 30:u=n.stateNode;break;default:u=n.stateNode}typeof l=="function"?n.refCleanup=l(u):l.current=u}}catch(m){Dt(n,r,m)}}function Cr(n,r){var l=n.ref,u=n.refCleanup;if(l!==null)if(typeof u=="function")try{u()}catch(m){Dt(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){Dt(n,r,m)}else l.current=null}function Rx(n){var r=n.type,l=n.memoizedProps,u=n.stateNode;try{e:switch(r){case"button":case"input":case"select":case"textarea":l.autoFocus&&u.focus();break e;case"img":l.src?u.src=l.src:l.srcSet&&(u.srcset=l.srcSet)}}catch(m){Dt(n,n.return,m)}}function ld(n,r,l){try{var u=n.stateNode;Pw(u,n.type,l,r),u[jt]=r}catch(m){Dt(n,n.return,m)}}function Dx(n){return n.tag===5||n.tag===3||n.tag===26||n.tag===27&&Ts(n.type)||n.tag===4}function od(n){e:for(;;){for(;n.sibling===null;){if(n.return===null||Dx(n.return))return null;n=n.return}for(n.sibling.return=n.return,n=n.sibling;n.tag!==5&&n.tag!==6&&n.tag!==18;){if(n.tag===27&&Ts(n.type)||n.flags&2||n.child===null||n.tag===4)continue e;n.child.return=n,n=n.child}if(!(n.flags&2))return n.stateNode}}function cd(n,r,l){var u=n.tag;if(u===5||u===6)n=n.stateNode,r?(l.nodeType===9?l.body:l.nodeName==="HTML"?l.ownerDocument.body:l).insertBefore(n,r):(r=l.nodeType===9?l.body:l.nodeName==="HTML"?l.ownerDocument.body:l,r.appendChild(n),l=l._reactRootContainer,l!=null||r.onclick!==null||(r.onclick=pn));else if(u!==4&&(u===27&&Ts(n.type)&&(l=n.stateNode,r=null),n=n.child,n!==null))for(cd(n,r,l),n=n.sibling;n!==null;)cd(n,r,l),n=n.sibling}function jc(n,r,l){var u=n.tag;if(u===5||u===6)n=n.stateNode,r?l.insertBefore(n,r):l.appendChild(n);else if(u!==4&&(u===27&&Ts(n.type)&&(l=n.stateNode),n=n.child,n!==null))for(jc(n,r,l),n=n.sibling;n!==null;)jc(n,r,l),n=n.sibling}function Mx(n){var r=n.stateNode,l=n.memoizedProps;try{for(var u=n.type,m=r.attributes;m.length;)r.removeAttributeNode(m[0]);tn(r,u,l),r[Kt]=n,r[jt]=l}catch(g){Dt(n,n.return,g)}}var Kr=!1,ji=!1,ud=!1,Bx=typeof WeakSet=="function"?WeakSet:Set,Hi=null;function xw(n,r){if(n=n.containerInfo,Rd=Kc,n=Gm(n),nh(n)){if("selectionStart"in n)var l={start:n.selectionStart,end:n.selectionEnd};else e:{l=(l=n.ownerDocument)&&l.defaultView||window;var u=l.getSelection&&l.getSelection();if(u&&u.rangeCount!==0){l=u.anchorNode;var m=u.anchorOffset,g=u.focusNode;u=u.focusOffset;try{l.nodeType,g.nodeType}catch{l=null;break e}var y=0,C=-1,z=-1,J=0,ce=0,fe=n,te=null;t:for(;;){for(var le;fe!==l||m!==0&&fe.nodeType!==3||(C=y+m),fe!==g||u!==0&&fe.nodeType!==3||(z=y+u),fe.nodeType===3&&(y+=fe.nodeValue.length),(le=fe.firstChild)!==null;)te=fe,fe=le;for(;;){if(fe===n)break t;if(te===l&&++J===m&&(C=y),te===g&&++ce===u&&(z=y),(le=fe.nextSibling)!==null)break;fe=te,te=fe.parentNode}fe=le}l=C===-1||z===-1?null:{start:C,end:z}}else l=null}l=l||{start:0,end:0}}else l=null;for(Dd={focusedElem:n,selectionRange:l},Kc=!1,Hi=r;Hi!==null;)if(r=Hi,n=r.child,(r.subtreeFlags&1028)!==0&&n!==null)n.return=r,Hi=n;else for(;Hi!==null;){switch(r=Hi,g=r.alternate,n=r.flags,r.tag){case 0:if((n&4)!==0&&(n=r.updateQueue,n=n!==null?n.events:null,n!==null))for(l=0;l title"))),tn(g,u,l),g[Kt]=n,Qe(g),u=g;break e;case"link":var y=H_("link","href",m).get(u+(l.href||""));if(y){for(var C=0;CPt&&(y=Pt,Pt=Ye,Ye=y);var G=qm(C,Ye),I=qm(C,Pt);if(G&&I&&(le.rangeCount!==1||le.anchorNode!==G.node||le.anchorOffset!==G.offset||le.focusNode!==I.node||le.focusOffset!==I.offset)){var Q=fe.createRange();Q.setStart(G.node,G.offset),le.removeAllRanges(),Ye>Pt?(le.addRange(Q),le.extend(I.node,I.offset)):(Q.setEnd(I.node,I.offset),le.addRange(Q))}}}}for(fe=[],le=C;le=le.parentNode;)le.nodeType===1&&fe.push({element:le,left:le.scrollLeft,top:le.scrollTop});for(typeof C.focus=="function"&&C.focus(),C=0;Cl?32:l,T.T=null,l=xd,xd=null;var g=Es,y=es;if(Bi=0,Ya=Es=null,es=0,(Tt&6)!==0)throw Error(s(331));var C=Tt;if(Tt|=4,Wx(g.current),$x(g,g.current,y,l),Tt=C,Jl(0,!1),wt&&typeof wt.onPostCommitFiberRoot=="function")try{wt.onPostCommitFiberRoot(At,g)}catch{}return!0}finally{P.p=m,T.T=u,c_(n,r)}}function h_(n,r,l){r=Qn(l,r),r=Xh(n.stateNode,r,2),n=bs(n,r,2),n!==null&&(li(n,2),kr(n))}function Dt(n,r,l){if(n.tag===3)h_(n,n,l);else for(;r!==null;){if(r.tag===3){h_(r,n,l);break}else if(r.tag===1){var u=r.stateNode;if(typeof r.type.getDerivedStateFromError=="function"||typeof u.componentDidCatch=="function"&&(ks===null||!ks.has(u))){n=Qn(l,n),l=dx(2),u=bs(r,l,2),u!==null&&(fx(l,u,r,n),li(u,2),kr(u));break}}r=r.return}}function yd(n,r,l){var u=n.pingCache;if(u===null){u=n.pingCache=new vw;var m=new Set;u.set(r,m)}else m=u.get(r),m===void 0&&(m=new Set,u.set(r,m));m.has(l)||(fd=!0,m.add(l),n=kw.bind(null,n,r,l),r.then(n,n))}function kw(n,r,l){var u=n.pingCache;u!==null&&u.delete(r),n.pingedLanes|=n.suspendedLanes&l,n.warmLanes&=~l,Ft===n&&(mt&l)===l&&(hi===4||hi===3&&(mt&62914560)===mt&&300>Ct()-Rc?(Tt&2)===0&&Va(n,0):pd|=l,Ga===mt&&(Ga=0)),kr(n)}function d_(n,r){r===0&&(r=Mt()),n=Xs(n,r),n!==null&&(li(n,r),kr(n))}function Ew(n){var r=n.memoizedState,l=0;r!==null&&(l=r.retryLane),d_(n,l)}function Nw(n,r){var l=0;switch(n.tag){case 31:case 13:var u=n.stateNode,m=n.memoizedState;m!==null&&(l=m.retryLane);break;case 19:u=n.stateNode;break;case 22:u=n.stateNode._retryCache;break;default:throw Error(s(314))}u!==null&&u.delete(r),d_(n,l)}function jw(n,r){return nt(n,r)}var Pc=null,Xa=null,Sd=!1,Ic=!1,wd=!1,js=0;function kr(n){n!==Xa&&n.next===null&&(Xa===null?Pc=Xa=n:Xa=Xa.next=n),Ic=!0,Sd||(Sd=!0,Aw())}function Jl(n,r){if(!wd&&Ic){wd=!0;do for(var l=!1,u=Pc;u!==null;){if(n!==0){var m=u.pendingLanes;if(m===0)var g=0;else{var y=u.suspendedLanes,C=u.pingedLanes;g=(1<<31-ot(42|n)+1)-1,g&=m&~(y&~C),g=g&201326741?g&201326741|1:g?g|2:0}g!==0&&(l=!0,g_(u,g))}else g=mt,g=ht(u,u===Ft?g:0,u.cancelPendingCommit!==null||u.timeoutHandle!==-1),(g&3)===0||xt(u,g)||(l=!0,g_(u,g));u=u.next}while(l);wd=!1}}function Tw(){f_()}function f_(){Ic=Sd=!1;var n=0;js!==0&&Hw()&&(n=js);for(var r=Ct(),l=null,u=Pc;u!==null;){var m=u.next,g=p_(u,r);g===0?(u.next=null,l===null?Pc=m:l.next=m,m===null&&(Xa=l)):(l=u,(n!==0||(g&3)!==0)&&(Ic=!0)),u=m}Bi!==0&&Bi!==5||Jl(n),js!==0&&(js=0)}function p_(n,r){for(var l=n.suspendedLanes,u=n.pingedLanes,m=n.expirationTimes,g=n.pendingLanes&-62914561;0C)break;var ce=z.transferSize,fe=z.initiatorType;ce&&C_(fe)&&(z=z.responseEnd,y+=ce*(z"u"?null:document;function O_(n,r,l){var u=Za;if(u&&typeof r=="string"&&r){var m=Zi(r);m='link[rel="'+n+'"][href="'+m+'"]',typeof l=="string"&&(m+='[crossorigin="'+l+'"]'),L_.has(m)||(L_.add(m),n={rel:n,crossOrigin:l,href:r},u.querySelector(m)===null&&(r=u.createElement("link"),tn(r,"link",n),Qe(r),u.head.appendChild(r)))}}function Kw(n){ts.D(n),O_("dns-prefetch",n,null)}function Xw(n,r){ts.C(n,r),O_("preconnect",n,r)}function Zw(n,r,l){ts.L(n,r,l);var u=Za;if(u&&n&&r){var m='link[rel="preload"][as="'+Zi(r)+'"]';r==="image"&&l&&l.imageSrcSet?(m+='[imagesrcset="'+Zi(l.imageSrcSet)+'"]',typeof l.imageSizes=="string"&&(m+='[imagesizes="'+Zi(l.imageSizes)+'"]')):m+='[href="'+Zi(n)+'"]';var g=m;switch(r){case"style":g=Qa(n);break;case"script":g=Ja(n)}rr.has(g)||(n=x({rel:"preload",href:r==="image"&&l&&l.imageSrcSet?void 0:n,as:r},l),rr.set(g,n),u.querySelector(m)!==null||r==="style"&&u.querySelector(no(g))||r==="script"&&u.querySelector(ro(g))||(r=u.createElement("link"),tn(r,"link",n),Qe(r),u.head.appendChild(r)))}}function Qw(n,r){ts.m(n,r);var l=Za;if(l&&n){var u=r&&typeof r.as=="string"?r.as:"script",m='link[rel="modulepreload"][as="'+Zi(u)+'"][href="'+Zi(n)+'"]',g=m;switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":g=Ja(n)}if(!rr.has(g)&&(n=x({rel:"modulepreload",href:n},r),rr.set(g,n),l.querySelector(m)===null)){switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(l.querySelector(ro(g)))return}u=l.createElement("link"),tn(u,"link",n),Qe(u),l.head.appendChild(u)}}}function Jw(n,r,l){ts.S(n,r,l);var u=Za;if(u&&n){var m=tt(u).hoistableStyles,g=Qa(n);r=r||"default";var y=m.get(g);if(!y){var C={loading:0,preload:null};if(y=u.querySelector(no(g)))C.loading=5;else{n=x({rel:"stylesheet",href:n,"data-precedence":r},l),(l=rr.get(g))&&Id(n,l);var z=y=u.createElement("link");Qe(z),tn(z,"link",n),z._p=new Promise(function(J,ce){z.onload=J,z.onerror=ce}),z.addEventListener("load",function(){C.loading|=1}),z.addEventListener("error",function(){C.loading|=2}),C.loading|=4,qc(y,r,u)}y={type:"stylesheet",instance:y,count:1,state:C},m.set(g,y)}}}function eC(n,r){ts.X(n,r);var l=Za;if(l&&n){var u=tt(l).hoistableScripts,m=Ja(n),g=u.get(m);g||(g=l.querySelector(ro(m)),g||(n=x({src:n,async:!0},r),(r=rr.get(m))&&Hd(n,r),g=l.createElement("script"),Qe(g),tn(g,"link",n),l.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(m,g))}}function tC(n,r){ts.M(n,r);var l=Za;if(l&&n){var u=tt(l).hoistableScripts,m=Ja(n),g=u.get(m);g||(g=l.querySelector(ro(m)),g||(n=x({src:n,async:!0,type:"module"},r),(r=rr.get(m))&&Hd(n,r),g=l.createElement("script"),Qe(g),tn(g,"link",n),l.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(m,g))}}function z_(n,r,l,u){var m=(m=oe.current)?Fc(m):null;if(!m)throw Error(s(446));switch(n){case"meta":case"title":return null;case"style":return typeof l.precedence=="string"&&typeof l.href=="string"?(r=Qa(l.href),l=tt(m).hoistableStyles,u=l.get(r),u||(u={type:"style",instance:null,count:0,state:null},l.set(r,u)),u):{type:"void",instance:null,count:0,state:null};case"link":if(l.rel==="stylesheet"&&typeof l.href=="string"&&typeof l.precedence=="string"){n=Qa(l.href);var g=tt(m).hoistableStyles,y=g.get(n);if(y||(m=m.ownerDocument||m,y={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},g.set(n,y),(g=m.querySelector(no(n)))&&!g._p&&(y.instance=g,y.state.loading=5),rr.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},rr.set(n,l),g||iC(m,n,l,y.state))),r&&u===null)throw Error(s(528,""));return y}if(r&&u!==null)throw Error(s(529,""));return null;case"script":return r=l.async,l=l.src,typeof l=="string"&&r&&typeof r!="function"&&typeof r!="symbol"?(r=Ja(l),l=tt(m).hoistableScripts,u=l.get(r),u||(u={type:"script",instance:null,count:0,state:null},l.set(r,u)),u):{type:"void",instance:null,count:0,state:null};default:throw Error(s(444,n))}}function Qa(n){return'href="'+Zi(n)+'"'}function no(n){return'link[rel="stylesheet"]['+n+"]"}function P_(n){return x({},n,{"data-precedence":n.precedence,precedence:null})}function iC(n,r,l,u){n.querySelector('link[rel="preload"][as="style"]['+r+"]")?u.loading=1:(r=n.createElement("link"),u.preload=r,r.addEventListener("load",function(){return u.loading|=1}),r.addEventListener("error",function(){return u.loading|=2}),tn(r,"link",l),Qe(r),n.head.appendChild(r))}function Ja(n){return'[src="'+Zi(n)+'"]'}function ro(n){return"script[async]"+n}function I_(n,r,l){if(r.count++,r.instance===null)switch(r.type){case"style":var u=n.querySelector('style[data-href~="'+Zi(l.href)+'"]');if(u)return r.instance=u,Qe(u),u;var m=x({},l,{"data-href":l.href,"data-precedence":l.precedence,href:null,precedence:null});return u=(n.ownerDocument||n).createElement("style"),Qe(u),tn(u,"style",m),qc(u,l.precedence,n),r.instance=u;case"stylesheet":m=Qa(l.href);var g=n.querySelector(no(m));if(g)return r.state.loading|=4,r.instance=g,Qe(g),g;u=P_(l),(m=rr.get(m))&&Id(u,m),g=(n.ownerDocument||n).createElement("link"),Qe(g);var y=g;return y._p=new Promise(function(C,z){y.onload=C,y.onerror=z}),tn(g,"link",u),r.state.loading|=4,qc(g,l.precedence,n),r.instance=g;case"script":return g=Ja(l.src),(m=n.querySelector(ro(g)))?(r.instance=m,Qe(m),m):(u=l,(m=rr.get(g))&&(u=x({},l),Hd(u,m)),n=n.ownerDocument||n,m=n.createElement("script"),Qe(m),tn(m,"link",u),n.head.appendChild(m),r.instance=m);case"void":return null;default:throw Error(s(443,r.type))}else r.type==="stylesheet"&&(r.state.loading&4)===0&&(u=r.instance,r.state.loading|=4,qc(u,l.precedence,n));return r.instance}function qc(n,r,l){for(var u=l.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),m=u.length?u[u.length-1]:null,g=m,y=0;y title"):null)}function nC(n,r,l){if(l===1||r.itemProp!=null)return!1;switch(n){case"meta":case"title":return!0;case"style":if(typeof r.precedence!="string"||typeof r.href!="string"||r.href==="")break;return!0;case"link":if(typeof r.rel!="string"||typeof r.href!="string"||r.href===""||r.onLoad||r.onError)break;switch(r.rel){case"stylesheet":return n=r.disabled,typeof r.precedence=="string"&&n==null;default:return!0}case"script":if(r.async&&typeof r.async!="function"&&typeof r.async!="symbol"&&!r.onLoad&&!r.onError&&r.src&&typeof r.src=="string")return!0}return!1}function $_(n){return!(n.type==="stylesheet"&&(n.state.loading&3)===0)}function rC(n,r,l,u){if(l.type==="stylesheet"&&(typeof u.media!="string"||matchMedia(u.media).matches!==!1)&&(l.state.loading&4)===0){if(l.instance===null){var m=Qa(u.href),g=r.querySelector(no(m));if(g){r=g._p,r!==null&&typeof r=="object"&&typeof r.then=="function"&&(n.count++,n=Gc.bind(n),r.then(n,n)),l.state.loading|=4,l.instance=g,Qe(g);return}g=r.ownerDocument||r,u=P_(u),(m=rr.get(m))&&Id(u,m),g=g.createElement("link"),Qe(g);var y=g;y._p=new Promise(function(C,z){y.onload=C,y.onerror=z}),tn(g,"link",u),l.instance=g}n.stylesheets===null&&(n.stylesheets=new Map),n.stylesheets.set(l,r),(r=l.state.preload)&&(l.state.loading&3)===0&&(n.count++,l=Gc.bind(n),r.addEventListener("load",l),r.addEventListener("error",l))}}var Ud=0;function sC(n,r){return n.stylesheets&&n.count===0&&Vc(n,n.stylesheets),0Ud?50:800)+r);return n.unsuspend=l,function(){n.unsuspend=null,clearTimeout(u),clearTimeout(m)}}:null}function Gc(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Vc(this,this.stylesheets);else if(this.unsuspend){var n=this.unsuspend;this.unsuspend=null,n()}}}var Yc=null;function Vc(n,r){n.stylesheets=null,n.unsuspend!==null&&(n.count++,Yc=new Map,r.forEach(aC,n),Yc=null,Gc.call(n))}function aC(n,r){if(!(r.state.loading&4)){var l=Yc.get(n);if(l)var u=l.get(null);else{l=new Map,Yc.set(n,l);for(var m=n.querySelectorAll("link[data-precedence],style[data-precedence]"),g=0;g"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Xd.exports=wC(),Xd.exports}var kC=CC();const EC=Pu(kC);function NC({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 jC({onSetup:e}){const[t,i]=w.useState(""),[s,a]=w.useState(""),[o,c]=w.useState(null),[h,p]=w.useState(!1),f=async _=>{if(_.preventDefault(),!t.trim()||t.length<4){c("Passphrase must be at least 4 characters");return}if(t!==s){c("Passphrases do not match");return}p(!0),c(null);const x=await e(t);x&&c(x),p(!1)};return d.jsx("div",{className:"flex h-screen items-center justify-center p-4",children:d.jsx("div",{className:"w-full max-w-sm",children:d.jsxs("div",{className:"border-border rounded border p-6",children:[d.jsxs("div",{className:"mb-6 text-center",children:[d.jsx("h1",{className:"text-accent text-lg font-bold tracking-tight",children:"PlotLink OWS"}),d.jsx("p",{className:"text-muted mt-1 text-xs",children:"first-time setup"})]}),d.jsx("p",{className:"text-muted mb-4 text-xs leading-relaxed",children:"Choose a passphrase to protect your local writer agent. This will be used to unlock the app and secure your OWS wallet."}),d.jsxs("form",{onSubmit:f,className:"space-y-4",children:[d.jsxs("div",{children:[d.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Passphrase"}),d.jsx("input",{type:"password",value:t,onChange:_=>i(_.target.value),placeholder:"choose a passphrase",autoFocus:!0,className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Confirm"}),d.jsx("input",{type:"password",value:s,onChange:_=>a(_.target.value),placeholder:"repeat passphrase",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"})]}),o&&d.jsx("p",{className:"text-error text-xs",children:o}),d.jsx("button",{type:"submit",disabled:h||!t.trim()||!s.trim(),className:"border-accent text-accent hover:bg-accent/10 disabled:opacity-40 w-full rounded border px-4 py-2 text-sm font-medium transition-colors",children:h?"setting up...":"create passphrase"})]})]})})})}const ef="http://localhost:7777";function Dy({token:e}){const[t,i]=w.useState(null),[s,a]=w.useState(!1),[o,c]=w.useState(null),[h,p]=w.useState(!1),[f,_]=w.useState(null),x=w.useCallback((E,O)=>fetch(E,{...O,headers:{...O==null?void 0:O.headers,Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),[e]),b=w.useCallback(()=>{x(`${ef}/api/wallet`).then(E=>E.json()).then(E=>i(E)).catch(()=>i({exists:!1,error:"Failed to load wallet"}))},[x]);w.useEffect(()=>{b()},[b]);const v=async()=>{a(!0),_(null);try{const E=await x(`${ef}/api/wallet/create`,{method:"POST"}),O=await E.json();if(!E.ok)throw new Error(O.error||"Creation failed");b()}catch(E){_(E instanceof Error?E.message:"Failed to create wallet")}a(!1)},S=async E=>{c(E.walletId||E.name),_(null);try{const O=await x(`${ef}/api/wallet/active`,{method:"POST",body:JSON.stringify({walletId:E.walletId,name:E.name,address:E.normalizedAddress||E.address})}),H=await O.json();if(!O.ok)throw new Error(H.error||"Wallet switch failed");b()}catch(O){_(O instanceof Error?O.message:"Failed to switch wallet")}c(null)},N=()=>{t!=null&&t.address&&(navigator.clipboard.writeText(t.address),p(!0),setTimeout(()=>p(!1),2e3))},B=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:B(t.address)}),d.jsx("button",{onClick:N,className:"text-muted hover:text-accent text-xs transition-colors",children:h?"copied":"copy"})]}),d.jsxs("div",{className:"border-border space-y-1 border-t pt-3",children:[d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"ETH"}),d.jsxs("span",{className:"text-foreground font-medium",children:[t.ethBalance||"0.000000"," ETH"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"USDC"}),d.jsxs("span",{className:"text-foreground font-medium",children:["$",t.usdcBalance||"0.00"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"PLOT"}),d.jsxs("span",{className:"text-foreground font-medium",children:[t.plotBalance||"0.0000"," PLOT"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Network"}),d.jsx("span",{className:"text-foreground",children:"Base"})]})]}),t.wallets&&t.wallets.length>1&&d.jsxs("div",{className:"border-border space-y-2 border-t pt-3",children:[d.jsx("p",{className:"text-muted text-[10px] font-medium uppercase tracking-wider",children:"Switch Wallet"}),t.wallets.map(E=>d.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsxs("p",{className:E.active?"text-accent truncate font-medium":"text-foreground truncate",children:[E.name,E.active?" (active)":""]}),d.jsx("p",{className:"text-muted truncate text-[10px] font-mono",children:E.address||"No EVM address"})]}),!E.active&&d.jsx("button",{onClick:()=>S(E),disabled:!E.address||o===(E.walletId||E.name),className:"border-border text-muted hover:border-accent hover:text-accent disabled:opacity-40 rounded border px-2 py-1 text-[10px] transition-colors",children:o===(E.walletId||E.name)?"...":"use"})]},E.walletId||E.name)),f&&d.jsx("p",{className:"text-error text-xs",children:f})]}),d.jsxs("div",{className:"border-border border-t pt-3",children:[d.jsx("p",{className:"text-muted mb-2 text-[10px] font-medium uppercase tracking-wider",children:"Fund Wallet"}),d.jsx("p",{className:"text-muted text-[10px]",children:"Send ETH on Base for gas (~$0.01 per publish):"}),d.jsx("code",{className:"text-foreground bg-surface mt-1 block break-all rounded px-2 py-1.5 text-[10px] font-mono",children:t.address})]})]}),(t==null?void 0:t.exists)&&d.jsx("button",{onClick:v,disabled:s,className:"border-border text-muted hover:border-accent hover:text-accent disabled:opacity-40 mt-4 rounded border px-3 py-1.5 text-[10px] font-medium transition-colors",children:s?"creating...":"create another wallet"})]})}function Eu(e){return!!e&&e.codex.installed&&e.codex.auth==="unknown"}const Fp="Codex is installed but its capabilities couldn't be read — you may need to log in to Codex (resolve outside OWS), then re-check.";function TC({token:e,onLogout:t}){const[i,s]=w.useState(""),[a,o]=w.useState(""),[c,h]=w.useState(null),[p,f]=w.useState(!1),[_,x]=w.useState(!1),[b,v]=w.useState(null),[S,N]=w.useState("AI Writer"),[B,E]=w.useState(""),[O,H]=w.useState(""),[A,W]=w.useState(!1),[D,ne]=w.useState(null),[ue,be]=w.useState(""),[L,re]=w.useState(null),[F,Y]=w.useState(!1),[V,U]=w.useState(null),[T,P]=w.useState(null),[q,xe]=w.useState(null),j=w.useCallback((ae,oe)=>fetch(ae,{...oe,headers:{...oe==null?void 0:oe.headers,Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),[e]);w.useEffect(()=>{j("/api/settings/link-status").then(ae=>ae.json()).then(ae=>v(ae)).catch(()=>v({linked:!1}))},[]),w.useEffect(()=>{j("/api/agent/readiness").then(ae=>ae.ok?ae.json():null).then(ae=>{ae&&xe(ae)}).catch(()=>{})},[]);const R=async()=>{if(!S.trim()){ne("Agent name is required");return}if(!B.trim()){ne("Description is required");return}W(!0),ne(null);try{const ae=await j("/api/settings/register-agent",{method:"POST",body:JSON.stringify({name:S,description:B,...O.trim()&&{genre:O}})}),oe=await ae.json();if(!ae.ok)throw new Error(oe.error||"Registration failed");v({linked:!0,agentId:oe.agentId,owsWallet:oe.owsWallet,txHash:oe.txHash})}catch(ae){ne(ae instanceof Error?ae.message:"Registration failed")}W(!1)},Z=async()=>{if(!ue.trim()||!/^0x[a-fA-F0-9]{40}$/.test(ue)){U("Enter a valid wallet address (0x...)");return}Y(!0),U(null),re(null);try{const ae=await j("/api/settings/generate-binding",{method:"POST",body:JSON.stringify({humanWallet:ue})}),oe=await ae.json();if(!ae.ok)throw new Error(oe.error||"Failed to generate binding code");re(oe)}catch(ae){U(ae instanceof Error?ae.message:"Failed to generate binding code")}Y(!1)},k=async(ae,oe)=>{await navigator.clipboard.writeText(ae),P(oe),setTimeout(()=>P(null),2e3)},K=async()=>{if(h(null),f(!1),!i||i.length<4){h("Passphrase must be at least 4 characters");return}if(i!==a){h("Passphrases do not match");return}x(!0);try{const ae=await j("/api/auth/reset-passphrase",{method:"POST",body:JSON.stringify({passphrase:i})});if(!ae.ok){const oe=await ae.json();throw new Error(oe.error||"Reset failed")}f(!0),s(""),o(""),setTimeout(()=>f(!1),3e3)}catch(ae){h(ae instanceof Error?ae.message:"Reset failed")}x(!1)};return d.jsxs("div",{className:"mx-auto max-w-lg space-y-6 p-6",children:[d.jsx("h2",{className:"text-accent text-lg font-bold",children:"Settings"}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Agent Identity"}),b!=null&&b.linked?d.jsxs("div",{className:"space-y-2",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"text-sm font-medium text-accent",children:"Registered"}),d.jsxs("span",{className:"text-muted text-xs",children:["Agent #",b.agentId]})]}),b.owsWallet&&d.jsxs("p",{className:"text-muted text-xs font-mono",children:["Wallet: ",b.owsWallet.slice(0,6),"...",b.owsWallet.slice(-4)]}),b.owner&&d.jsxs("p",{className:"text-muted text-xs font-mono",children:["Owner: ",b.owner.slice(0,6),"...",b.owner.slice(-4)]}),b.txHash&&d.jsx("p",{className:"text-muted text-xs",children:d.jsx("a",{href:`https://basescan.org/tx/${b.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View transaction on BaseScan"})}),d.jsx("p",{className:"text-muted text-xs",children:d.jsx("a",{href:`https://plotlink.xyz/profile/${b.owsWallet}`,target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View agent profile on plotlink.xyz"})})]}):d.jsxs("div",{className:"space-y-3",children:[d.jsx("p",{className:"text-muted text-xs",children:"Register this AI writer on-chain via ERC-8004. Uses your OWS wallet's existing ETH balance for gas."}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Name"}),d.jsx("input",{value:S,onChange:ae=>N(ae.target.value),placeholder:"AI Writer",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Description"}),d.jsx("input",{value:B,onChange:ae=>E(ae.target.value),placeholder:"An AI writing assistant for fiction stories",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Genre (optional)"}),d.jsx("input",{value:O,onChange:ae=>H(ae.target.value),placeholder:"e.g. Fiction, Sci-Fi, Fantasy",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"})]}),D&&d.jsx("p",{className:"text-error text-xs",children:D}),d.jsx("button",{onClick:R,disabled:A||!S.trim()||!B.trim(),className:"bg-accent text-white hover:bg-accent-dim disabled:opacity-50 w-full rounded px-4 py-2 text-sm font-medium transition-colors",children:A?"Registering...":"Register Agent Identity"})]})]}),d.jsxs("div",{className:"border-border rounded border p-4","data-testid":"provider-readiness",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Agent Providers"}),d.jsxs("div",{className:"space-y-2",children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Claude"}),d.jsx("span",{className:"text-muted text-xs",children:q!=null&&q.claude.installed?"Installed":"Not detected"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Codex"}),d.jsx("span",{className:"text-muted text-xs",children:q!=null&&q.codex.installed?"Installed":"Not detected"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Codex version"}),d.jsx("span",{className:"text-muted text-xs font-mono",children:(q==null?void 0:q.codex.version)??"—"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Image generation"}),d.jsx("span",{className:"text-muted text-xs",children:(q==null?void 0:q.codex.imageGeneration)??"unknown"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Codex auth"}),d.jsx("span",{className:"text-muted text-xs","data-testid":"codex-auth-status",children:q!=null&&q.codex.installed?q.codex.auth==="ok"?"ok":"unclear":"—"})]}),Eu(q)&&d.jsx("p",{className:"text-[11px] text-amber-700","data-testid":"codex-auth-unknown-settings",children:Fp}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Last checked"}),d.jsx("span",{className:"text-muted text-xs",children:q!=null&&q.checkedAt?new Date(q.checkedAt).toLocaleString():"—"})]})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Link to PlotLink"}),b!=null&&b.owner?d.jsxs("p",{className:"text-muted text-xs",children:["Linked to owner ",d.jsxs("span",{className:"font-mono",children:[b.owner.slice(0,6),"...",b.owner.slice(-4)]})]}):d.jsxs("div",{className:"space-y-3",children:[d.jsx("p",{className:"text-muted text-xs",children:"Link this OWS wallet to your PlotLink account so your stories appear under your profile on plotlink.xyz."}),d.jsxs("div",{className:"text-muted text-xs space-y-1 pl-3",children:[d.jsx("p",{children:"1. Enter your PlotLink wallet address below"}),d.jsx("p",{children:'2. Click "Generate Binding Code"'}),d.jsx("p",{children:"3. Copy the code and paste it on plotlink.xyz → Agents → Link AI Writer"})]}),d.jsx("input",{value:ue,onChange:ae=>be(ae.target.value),placeholder:"Your PlotLink wallet address (0x...)",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent font-mono"}),V&&d.jsx("p",{className:"text-error text-xs",children:V}),d.jsx("button",{onClick:Z,disabled:F||!ue.trim(),className:"bg-accent text-white hover:bg-accent-dim disabled:opacity-50 w-full rounded px-4 py-2 text-sm font-medium transition-colors",children:F?"Generating...":"Generate Binding Code"}),L&&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:L.signature}),d.jsx("button",{onClick:()=>k(L.signature,"signature"),className:"absolute top-1 right-1 text-xs px-2 py-1 rounded border border-border text-muted hover:text-accent hover:border-accent transition-colors",children:T==="signature"?"Copied!":"Copy"})]})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"OWS Wallet Address"}),d.jsxs("div",{className:"relative",children:[d.jsx("div",{className:"bg-surface border-border rounded border p-2 text-xs font-mono break-all text-foreground pr-16",children:L.owsWallet}),d.jsx("button",{onClick:()=>k(L.owsWallet,"wallet"),className:"absolute top-1 right-1 text-xs px-2 py-1 rounded border border-border text-muted hover:text-accent hover:border-accent transition-colors",children:T==="wallet"?"Copied!":"Copy"})]})]}),L.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:L.agentId}),d.jsx("button",{onClick:()=>k(String(L.agentId),"agentId"),className:"absolute top-1 right-1 text-xs px-2 py-1 rounded border border-border text-muted hover:text-accent hover:border-accent transition-colors",children:T==="agentId"?"Copied!":"Copy"})]})]}),d.jsx("p",{className:"text-xs text-accent",children:'Now go to plotlink.xyz/agents and paste the values in the "Link AI Writer" section.'})]})]})]}),d.jsx(Dy,{token:e}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Reset Passphrase"}),d.jsxs("div",{className:"space-y-3",children:[d.jsx("input",{type:"password",value:i,onChange:ae=>s(ae.target.value),placeholder:"new passphrase",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"}),d.jsx("input",{type:"password",value:a,onChange:ae=>o(ae.target.value),placeholder:"confirm passphrase",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"}),c&&d.jsx("p",{className:"text-error text-xs",children:c}),p&&d.jsx("p",{className:"text-xs text-accent",children:"passphrase updated"}),d.jsx("button",{onClick:K,disabled:_||!i.trim(),className:"border-border text-muted hover:border-accent hover:text-accent disabled:opacity-40 w-full rounded border px-4 py-2 text-xs font-medium transition-colors",children:_?"updating...":"update passphrase"})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Session"}),d.jsx("button",{onClick:t,className:"border-border text-muted hover:border-error hover:text-error rounded border px-4 py-2 text-xs font-medium transition-colors",children:"logout"})]})]})}const AC="http://localhost:7777";function RC({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(`${AC}/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 DC={published:"✓","published-not-indexed":"⚠",pending:"⏳",draft:"📝"},MC={published:"text-green-700","published-not-indexed":"text-amber-700",pending:"text-amber-700",draft:"text-muted"};function BC({authFetch:e,selectedStory:t,selectedFile:i,onSelectFile:s,onNewStory:a,untitledSessions:o=[]}){const[c,h]=w.useState([]),[p,f]=w.useState([]),[_,x]=w.useState(new Set),[b,v]=w.useState(!1),S=w.useCallback(async()=>{try{const W=await e("/api/stories");if(W.ok){const D=await W.json();h(D.stories)}}catch{}},[e]),N=w.useCallback(async()=>{try{const W=await e("/api/stories/archived");if(W.ok){const D=await W.json();f(D.stories)}}catch{}},[e]),B=w.useCallback(async W=>{try{(await e("/api/stories/restore",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:W})})).ok&&(N(),S())}catch{}},[e,N,S]);w.useEffect(()=>{S();const W=setInterval(S,5e3);return()=>clearInterval(W)},[S]),w.useEffect(()=>{b&&N()},[b,N]),w.useEffect(()=>{t&&x(W=>new Set(W).add(t))},[t]);const E=W=>{x(D=>{const ne=new Set(D);return ne.has(W)?ne.delete(W):ne.add(W),ne})},O=W=>{var ne;const D=W.map(ue=>{var be;return{file:ue.file,num:(be=ue.file.match(/^plot-(\d+)\.md$/))==null?void 0:be[1]}}).filter(ue=>ue.num!=null).sort((ue,be)=>parseInt(be.num)-parseInt(ue.num));return D.length>0?D[0].file:W.some(ue=>ue.file==="genesis.md")?"genesis.md":W.some(ue=>ue.file==="structure.md")?"structure.md":((ne=W[0])==null?void 0:ne.file)??null},H=W=>{if(E(W.name),W.contentType==="cartoon")s(W.name,"");else{const D=O(W.files);D&&s(W.name,D)}},A=W=>{const D=ne=>{if(ne==="structure.md")return 0;if(ne==="genesis.md")return 1;const ue=ne.match(/^plot-(\d+)\.md$/);return ue?2+parseInt(ue[1]):100};return[...W].sort((ne,ue)=>D(ne.file)-D(ue.file))};return b?d.jsxs("div",{className:"h-full flex flex-col",children:[d.jsxs("div",{className:"px-3 py-1.5 border-b border-border flex items-center justify-between",children:[d.jsx("span",{className:"text-xs font-mono text-muted",children:"Archives"}),d.jsx("span",{className:"text-xs text-muted",children:p.length})]}),d.jsx("div",{className:"px-3 py-2 border-b border-border",children:d.jsxs("button",{onClick:()=>v(!1),className:"w-full px-3 py-1.5 text-sm text-muted hover:text-foreground hover:bg-surface rounded flex items-center gap-1.5",children:[d.jsx("span",{children:"←"}),d.jsx("span",{children:"Back"})]})}),d.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:p.length===0?d.jsx("div",{className:"p-3 text-sm text-muted",children:d.jsx("p",{children:"No archived stories."})}):p.map(W=>d.jsxs("div",{className:"px-3 py-2 flex items-center justify-between hover:bg-surface",children:[d.jsx("span",{className:"text-sm font-medium truncate",title:W.name,children:W.title||W.name}),d.jsx("button",{onClick:()=>B(W.name),className:"text-xs text-accent hover:text-accent-dim flex-shrink-0 ml-2",children:"Restore"})]},W.name))})]}):d.jsxs("div",{className:"h-full flex flex-col",children:[d.jsxs("div",{className:"px-3 py-1.5 border-b border-border flex items-center justify-between",children:[d.jsx("span",{className:"text-xs font-mono text-muted",children:"Stories"}),d.jsx("span",{className:"text-xs text-muted",children:c.length})]}),a&&d.jsx("div",{className:"px-3 py-2 border-b border-border",children:d.jsxs("button",{onClick:a,className:"w-full px-3 py-1.5 text-sm bg-accent text-white rounded hover:bg-accent-dim flex items-center justify-center gap-1.5",children:[d.jsx("span",{children:"+"}),d.jsx("span",{children:"New Story"})]})}),d.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto",children:[o.map(W=>d.jsx("div",{children:d.jsxs("button",{onClick:()=>s(W,""),className:`w-full px-3 py-2 text-left flex items-center gap-2 hover:bg-surface text-sm ${t===W?"bg-surface":""}`,children:[d.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-green-600 flex-shrink-0"}),d.jsx("span",{className:"font-medium italic text-muted",children:"Untitled"})]})},W)),c.length===0&&o.length===0?d.jsxs("div",{className:"p-3 text-sm text-muted",children:[d.jsx("p",{children:"No stories yet."}),d.jsx("p",{className:"mt-1 text-xs",children:'Click "+ New Story" above to start writing.'})]}):c.filter(W=>W.name!=="_example").map(W=>d.jsxs("div",{children:[d.jsxs("button",{onClick:()=>H(W),className:"w-full px-3 py-2 text-left flex items-center gap-2 hover:bg-surface text-sm",children:[d.jsx("span",{className:"text-xs text-muted",children:_.has(W.name)?"▼":"▶"}),d.jsx("span",{className:"font-medium truncate",title:W.name,children:W.title||W.name}),W.contentType==="cartoon"&&d.jsx("span",{className:"bg-accent/10 text-accent rounded px-1.5 py-0.5 text-[10px] font-medium flex-shrink-0",children:"Cartoon"}),d.jsxs("span",{className:"ml-auto flex-shrink-0 text-xs text-muted",children:[W.publishedCount,"/",W.files.length]})]}),_.has(W.name)&&d.jsx("div",{className:"pl-4",children:A(W.files).map(D=>{const ne=t===W.name&&i===D.file;return d.jsxs("button",{onClick:()=>s(W.name,D.file),className:`w-full px-3 py-1.5 text-left flex items-center gap-2 text-xs hover:bg-surface ${ne?"bg-surface font-medium":""}`,children:[d.jsx("span",{className:MC[D.status],children:DC[D.status]}),d.jsx("span",{className:"truncate font-mono",children:D.file})]},D.file)})})]},W.name))]}),d.jsx("div",{className:"px-3 py-2 border-t border-border",children:d.jsx("button",{onClick:()=>v(!0),className:"w-full px-3 py-1.5 text-xs text-muted hover:text-foreground hover:bg-surface rounded flex items-center justify-center gap-1.5",children:d.jsx("span",{children:"Archives"})})})]})}/** * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved. * @license MIT * @@ -57,22 +57,22 @@ Error generating stack: `+u.message+` * Fabrice Bellard's javascript vt100 for jslinux: * http://bellard.org/jslinux/ * Copyright (c) 2011 Fabrice Bellard - */var My=Object.defineProperty,BC=Object.getOwnPropertyDescriptor,LC=(e,t)=>{for(var i in t)My(e,i,{get:t[i],enumerable:!0})},fi=(e,t,i,s)=>{for(var a=s>1?void 0:s?BC(t,i):t,o=e.length-1,c;o>=0;o--)(c=e[o])&&(a=(s?c(t,i,a):c(a))||a);return s&&a&&My(t,i,a),a},Re=(e,t)=>(i,s)=>t(i,s,e),db="Terminal input",Uf={get:()=>db,set:e=>db=e},fb="Too much output to announce, navigate to rows manually to read",$f={get:()=>fb,set:e=>fb=e};function OC(e){return e.replace(/\r?\n/g,"\r")}function zC(e,t){return t?"\x1B[200~"+e+"\x1B[201~":e}function PC(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()}function IC(e,t,i,s){if(e.stopPropagation(),e.clipboardData){let a=e.clipboardData.getData("text/plain");By(a,t,i,s)}}function By(e,t,i,s){e=OC(e),e=zC(e,i.decPrivateModes.bracketedPasteMode&&s.rawOptions.ignoreBracketedPasteMode!==!0),i.triggerDataEvent(e,!0),t.value=""}function Ly(e,t,i){let s=i.getBoundingClientRect(),a=e.clientX-s.left-10,o=e.clientY-s.top-10;t.style.width="20px",t.style.height="20px",t.style.left=`${a}px`,t.style.top=`${o}px`,t.style.zIndex="1000",t.focus()}function pb(e,t,i,s,a){Ly(e,t,i),a&&s.rightClickSelect(e),t.value=s.selectionText,t.select()}function Ps(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function Iu(e,t=0,i=e.length){let s="";for(let a=t;a65535?(o-=65536,s+=String.fromCharCode((o>>10)+55296)+String.fromCharCode(o%1024+56320)):s+=String.fromCharCode(o)}return s}var HC=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let i=e.length;if(!i)return 0;let s=0,a=0;if(this._interim){let o=e.charCodeAt(a++);56320<=o&&o<=57343?t[s++]=(this._interim-55296)*1024+o-56320+65536:(t[s++]=this._interim,t[s++]=o),this._interim=0}for(let o=a;o=i)return this._interim=c,s;let h=e.charCodeAt(o);56320<=h&&h<=57343?t[s++]=(c-55296)*1024+h-56320+65536:(t[s++]=c,t[s++]=h);continue}c!==65279&&(t[s++]=c)}return s}},UC=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let i=e.length;if(!i)return 0;let s=0,a,o,c,h,p=0,f=0;if(this.interim[0]){let b=!1,v=this.interim[0];v&=(v&224)===192?31:(v&240)===224?15:7;let S=0,N;for(;(N=this.interim[++S]&63)&&S<4;)v<<=6,v|=N;let M=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,E=M-S;for(;f=i)return 0;if(N=e[f++],(N&192)!==128){f--,b=!0;break}else this.interim[S++]=N,v<<=6,v|=N&63}b||(M===2?v<128?f--:t[s++]=v:M===3?v<2048||v>=55296&&v<=57343||v===65279||(t[s++]=v):v<65536||v>1114111||(t[s++]=v)),this.interim.fill(0)}let _=i-4,x=f;for(;x=i)return this.interim[0]=a,s;if(o=e[x++],(o&192)!==128){x--;continue}if(p=(a&31)<<6|o&63,p<128){x--;continue}t[s++]=p}else if((a&240)===224){if(x>=i)return this.interim[0]=a,s;if(o=e[x++],(o&192)!==128){x--;continue}if(x>=i)return this.interim[0]=a,this.interim[1]=o,s;if(c=e[x++],(c&192)!==128){x--;continue}if(p=(a&15)<<12|(o&63)<<6|c&63,p<2048||p>=55296&&p<=57343||p===65279)continue;t[s++]=p}else if((a&248)===240){if(x>=i)return this.interim[0]=a,s;if(o=e[x++],(o&192)!==128){x--;continue}if(x>=i)return this.interim[0]=a,this.interim[1]=o,s;if(c=e[x++],(c&192)!==128){x--;continue}if(x>=i)return this.interim[0]=a,this.interim[1]=o,this.interim[2]=c,s;if(h=e[x++],(h&192)!==128){x--;continue}if(p=(a&7)<<18|(o&63)<<12|(c&63)<<6|h&63,p<65536||p>1114111)continue;t[s++]=p}}return s}},Oy="",Hs=" ",$o=class zy{constructor(){this.fg=0,this.bg=0,this.extended=new Nu}static toColorRGB(t){return[t>>>16&255,t>>>8&255,t&255]}static fromColorRGB(t){return(t[0]&255)<<16|(t[1]&255)<<8|t[2]&255}clone(){let t=new zy;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)===50331648}isBgRGB(){return(this.bg&50331648)===50331648}isFgPalette(){return(this.fg&50331648)===16777216||(this.fg&50331648)===33554432}isBgPalette(){return(this.bg&50331648)===16777216||(this.bg&50331648)===33554432}isFgDefault(){return(this.fg&50331648)===0}isBgDefault(){return(this.bg&50331648)===0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===16777216||(this.extended.underlineColor&50331648)===33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===0:this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},Nu=class Py{constructor(t=0,i=0){this._ext=0,this._urlId=0,this._ext=t,this._urlId=i}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(t){this._ext=t}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(t){this._ext&=-469762049,this._ext|=t<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(t){this._ext&=-67108864,this._ext|=t&67108863}get urlId(){return this._urlId}set urlId(t){this._urlId=t}get underlineVariantOffset(){let t=(this._ext&3758096384)>>29;return t<0?t^4294967288:t}set underlineVariantOffset(t){this._ext&=536870911,this._ext|=t<<29&3758096384}clone(){return new Py(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},or=class Iy extends $o{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new Nu,this.combinedData=""}static fromCharData(t){let i=new Iy;return i.setFromCharData(t),i}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?Ps(this.content&2097151):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(t){this.fg=t[0],this.bg=0;let i=!1;if(t[1].length>2)i=!0;else if(t[1].length===2){let s=t[1].charCodeAt(0);if(55296<=s&&s<=56319){let a=t[1].charCodeAt(1);56320<=a&&a<=57343?this.content=(s-55296)*1024+a-56320+65536|t[2]<<22:i=!0}else i=!0}else this.content=t[1].charCodeAt(0)|t[2]<<22;i&&(this.combinedData=t[1],this.content=2097152|t[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},mb="di$target",Ff="di$dependencies",tf=new Map;function $C(e){return e[Ff]||[]}function Xi(e){if(tf.has(e))return tf.get(e);let t=function(i,s,a){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");FC(t,i,a)};return t._id=e,tf.set(e,t),t}function FC(e,t,i){t[mb]===t?t[Ff].push({id:e,index:i}):(t[Ff]=[{id:e,index:i}],t[mb]=t)}var _n=Xi("BufferService"),Hy=Xi("CoreMouseService"),va=Xi("CoreService"),qC=Xi("CharsetService"),qp=Xi("InstantiationService"),Uy=Xi("LogService"),bn=Xi("OptionsService"),$y=Xi("OscLinkService"),WC=Xi("UnicodeService"),Fo=Xi("DecorationService"),qf=class{constructor(e,t,i){this._bufferService=e,this._optionsService=t,this._oscLinkService=i}provideLinks(e,t){var _;let i=this._bufferService.buffer.lines.get(e-1);if(!i){t(void 0);return}let s=[],a=this._optionsService.rawOptions.linkHandler,o=new or,c=i.getTrimmedLength(),h=-1,p=-1,f=!1;for(let x=0;xa?a.activate(N,M,v):GC(N,M),hover:(N,M)=>{var E;return(E=a==null?void 0:a.hover)==null?void 0:E.call(a,N,M,v)},leave:(N,M)=>{var E;return(E=a==null?void 0:a.leave)==null?void 0:E.call(a,N,M,v)}})}f=!1,o.hasExtendedAttrs()&&o.extended.urlId?(p=x,h=o.extended.urlId):(p=-1,h=-1)}}t(s)}};qf=fi([Re(0,_n),Re(1,bn),Re(2,$y)],qf);function GC(e,t){if(confirm(`Do you want to navigate to ${t}? + */var My=Object.defineProperty,LC=Object.getOwnPropertyDescriptor,OC=(e,t)=>{for(var i in t)My(e,i,{get:t[i],enumerable:!0})},pi=(e,t,i,s)=>{for(var a=s>1?void 0:s?LC(t,i):t,o=e.length-1,c;o>=0;o--)(c=e[o])&&(a=(s?c(t,i,a):c(a))||a);return s&&a&&My(t,i,a),a},De=(e,t)=>(i,s)=>t(i,s,e),db="Terminal input",Uf={get:()=>db,set:e=>db=e},fb="Too much output to announce, navigate to rows manually to read",$f={get:()=>fb,set:e=>fb=e};function zC(e){return e.replace(/\r?\n/g,"\r")}function PC(e,t){return t?"\x1B[200~"+e+"\x1B[201~":e}function IC(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()}function HC(e,t,i,s){if(e.stopPropagation(),e.clipboardData){let a=e.clipboardData.getData("text/plain");By(a,t,i,s)}}function By(e,t,i,s){e=zC(e),e=PC(e,i.decPrivateModes.bracketedPasteMode&&s.rawOptions.ignoreBracketedPasteMode!==!0),i.triggerDataEvent(e,!0),t.value=""}function Ly(e,t,i){let s=i.getBoundingClientRect(),a=e.clientX-s.left-10,o=e.clientY-s.top-10;t.style.width="20px",t.style.height="20px",t.style.left=`${a}px`,t.style.top=`${o}px`,t.style.zIndex="1000",t.focus()}function pb(e,t,i,s,a){Ly(e,t,i),a&&s.rightClickSelect(e),t.value=s.selectionText,t.select()}function Is(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function Iu(e,t=0,i=e.length){let s="";for(let a=t;a65535?(o-=65536,s+=String.fromCharCode((o>>10)+55296)+String.fromCharCode(o%1024+56320)):s+=String.fromCharCode(o)}return s}var UC=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}},$C=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let i=e.length;if(!i)return 0;let s=0,a,o,c,h,p=0,f=0;if(this.interim[0]){let b=!1,v=this.interim[0];v&=(v&224)===192?31:(v&240)===224?15:7;let S=0,N;for(;(N=this.interim[++S]&63)&&S<4;)v<<=6,v|=N;let B=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,E=B-S;for(;f=i)return 0;if(N=e[f++],(N&192)!==128){f--,b=!0;break}else this.interim[S++]=N,v<<=6,v|=N&63}b||(B===2?v<128?f--:t[s++]=v:B===3?v<2048||v>=55296&&v<=57343||v===65279||(t[s++]=v):v<65536||v>1114111||(t[s++]=v)),this.interim.fill(0)}let _=i-4,x=f;for(;x=i)return this.interim[0]=a,s;if(o=e[x++],(o&192)!==128){x--;continue}if(p=(a&31)<<6|o&63,p<128){x--;continue}t[s++]=p}else if((a&240)===224){if(x>=i)return this.interim[0]=a,s;if(o=e[x++],(o&192)!==128){x--;continue}if(x>=i)return this.interim[0]=a,this.interim[1]=o,s;if(c=e[x++],(c&192)!==128){x--;continue}if(p=(a&15)<<12|(o&63)<<6|c&63,p<2048||p>=55296&&p<=57343||p===65279)continue;t[s++]=p}else if((a&248)===240){if(x>=i)return this.interim[0]=a,s;if(o=e[x++],(o&192)!==128){x--;continue}if(x>=i)return this.interim[0]=a,this.interim[1]=o,s;if(c=e[x++],(c&192)!==128){x--;continue}if(x>=i)return this.interim[0]=a,this.interim[1]=o,this.interim[2]=c,s;if(h=e[x++],(h&192)!==128){x--;continue}if(p=(a&7)<<18|(o&63)<<12|(c&63)<<6|h&63,p<65536||p>1114111)continue;t[s++]=p}}return s}},Oy="",Us=" ",$o=class zy{constructor(){this.fg=0,this.bg=0,this.extended=new Nu}static toColorRGB(t){return[t>>>16&255,t>>>8&255,t&255]}static fromColorRGB(t){return(t[0]&255)<<16|(t[1]&255)<<8|t[2]&255}clone(){let t=new zy;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)===50331648}isBgRGB(){return(this.bg&50331648)===50331648}isFgPalette(){return(this.fg&50331648)===16777216||(this.fg&50331648)===33554432}isBgPalette(){return(this.bg&50331648)===16777216||(this.bg&50331648)===33554432}isFgDefault(){return(this.fg&50331648)===0}isBgDefault(){return(this.bg&50331648)===0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===16777216||(this.extended.underlineColor&50331648)===33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===0:this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},Nu=class Py{constructor(t=0,i=0){this._ext=0,this._urlId=0,this._ext=t,this._urlId=i}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(t){this._ext=t}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(t){this._ext&=-469762049,this._ext|=t<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(t){this._ext&=-67108864,this._ext|=t&67108863}get urlId(){return this._urlId}set urlId(t){this._urlId=t}get underlineVariantOffset(){let t=(this._ext&3758096384)>>29;return t<0?t^4294967288:t}set underlineVariantOffset(t){this._ext&=536870911,this._ext|=t<<29&3758096384}clone(){return new Py(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},cr=class Iy extends $o{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new Nu,this.combinedData=""}static fromCharData(t){let i=new Iy;return i.setFromCharData(t),i}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?Is(this.content&2097151):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(t){this.fg=t[0],this.bg=0;let i=!1;if(t[1].length>2)i=!0;else if(t[1].length===2){let s=t[1].charCodeAt(0);if(55296<=s&&s<=56319){let a=t[1].charCodeAt(1);56320<=a&&a<=57343?this.content=(s-55296)*1024+a-56320+65536|t[2]<<22:i=!0}else i=!0}else this.content=t[1].charCodeAt(0)|t[2]<<22;i&&(this.combinedData=t[1],this.content=2097152|t[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},mb="di$target",Ff="di$dependencies",tf=new Map;function FC(e){return e[Ff]||[]}function Ki(e){if(tf.has(e))return tf.get(e);let t=function(i,s,a){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");qC(t,i,a)};return t._id=e,tf.set(e,t),t}function qC(e,t,i){t[mb]===t?t[Ff].push({id:e,index:i}):(t[Ff]=[{id:e,index:i}],t[mb]=t)}var vn=Ki("BufferService"),Hy=Ki("CoreMouseService"),va=Ki("CoreService"),WC=Ki("CharsetService"),qp=Ki("InstantiationService"),Uy=Ki("LogService"),yn=Ki("OptionsService"),$y=Ki("OscLinkService"),GC=Ki("UnicodeService"),Fo=Ki("DecorationService"),qf=class{constructor(e,t,i){this._bufferService=e,this._optionsService=t,this._oscLinkService=i}provideLinks(e,t){var _;let i=this._bufferService.buffer.lines.get(e-1);if(!i){t(void 0);return}let s=[],a=this._optionsService.rawOptions.linkHandler,o=new cr,c=i.getTrimmedLength(),h=-1,p=-1,f=!1;for(let x=0;xa?a.activate(N,B,v):YC(N,B),hover:(N,B)=>{var E;return(E=a==null?void 0:a.hover)==null?void 0:E.call(a,N,B,v)},leave:(N,B)=>{var E;return(E=a==null?void 0:a.leave)==null?void 0:E.call(a,N,B,v)}})}f=!1,o.hasExtendedAttrs()&&o.extended.urlId?(p=x,h=o.extended.urlId):(p=-1,h=-1)}}t(s)}};qf=pi([De(0,vn),De(1,yn),De(2,$y)],qf);function YC(e,t){if(confirm(`Do you want to navigate to ${t}? -WARNING: This link could potentially be dangerous`)){let i=window.open();if(i){try{i.opener=null}catch{}i.location.href=t}else console.warn("Opening link blocked as opener could not be cleared")}}var Hu=Xi("CharSizeService"),as=Xi("CoreBrowserService"),Wp=Xi("MouseService"),ls=Xi("RenderService"),YC=Xi("SelectionService"),Fy=Xi("CharacterJoinerService"),gl=Xi("ThemeService"),qy=Xi("LinkProviderService"),VC=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?gb.isErrorNoTelemetry(e)?new gb(e.message+` +WARNING: This link could potentially be dangerous`)){let i=window.open();if(i){try{i.opener=null}catch{}i.location.href=t}else console.warn("Opening link blocked as opener could not be cleared")}}var Hu=Ki("CharSizeService"),ls=Ki("CoreBrowserService"),Wp=Ki("MouseService"),os=Ki("RenderService"),VC=Ki("SelectionService"),Fy=Ki("CharacterJoinerService"),gl=Ki("ThemeService"),qy=Ki("LinkProviderService"),KC=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?gb.isErrorNoTelemetry(e)?new gb(e.message+` `+e.stack):new Error(e.message+` -`+e.stack):e},0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}},KC=new VC;function gu(e){XC(e)||KC.onUnexpectedError(e)}var Wf="Canceled";function XC(e){return e instanceof ZC?!0:e instanceof Error&&e.name===Wf&&e.message===Wf}var ZC=class extends Error{constructor(){super(Wf),this.name=this.message}};function QC(e){return new Error(`Illegal argument: ${e}`)}var gb=class Gf extends Error{constructor(t){super(t),this.name="CodeExpectedError"}static fromError(t){if(t instanceof Gf)return t;let i=new Gf;return i.message=t.message,i.stack=t.stack,i}static isErrorNoTelemetry(t){return t.name==="CodeExpectedError"}},Yf=class Wy extends Error{constructor(t){super(t||"An unexpected bug occurred."),Object.setPrototypeOf(this,Wy.prototype)}};function qn(e,t=0){return e[e.length-(1+t)]}var JC;(e=>{function t(o){return o<0}e.isLessThan=t;function i(o){return o<=0}e.isLessThanOrEqual=i;function s(o){return o>0}e.isGreaterThan=s;function a(o){return o===0}e.isNeitherLessOrGreaterThan=a,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(JC||(JC={}));function ek(e,t){let i=this,s=!1,a;return function(){return s||(s=!0,t||(a=e.apply(i,arguments))),a}}var Gy;(e=>{function t(A){return A&&typeof A=="object"&&typeof A[Symbol.iterator]=="function"}e.is=t;let i=Object.freeze([]);function s(){return i}e.empty=s;function*a(A){yield A}e.single=a;function o(A){return t(A)?A:a(A)}e.wrap=o;function c(A){return A||i}e.from=c;function*h(A){for(let q=A.length-1;q>=0;q--)yield A[q]}e.reverse=h;function p(A){return!A||A[Symbol.iterator]().next().done===!0}e.isEmpty=p;function f(A){return A[Symbol.iterator]().next().value}e.first=f;function _(A,q){let R=0;for(let ne of A)if(q(ne,R++))return!0;return!1}e.some=_;function x(A,q){for(let R of A)if(q(R))return R}e.find=x;function*b(A,q){for(let R of A)q(R)&&(yield R)}e.filter=b;function*v(A,q){let R=0;for(let ne of A)yield q(ne,R++)}e.map=v;function*S(A,q){let R=0;for(let ne of A)yield*q(ne,R++)}e.flatMap=S;function*N(...A){for(let q of A)yield*q}e.concat=N;function M(A,q,R){let ne=R;for(let ue of A)ne=q(ne,ue);return ne}e.reduce=M;function*E(A,q,R=A.length){for(q<0&&(q+=A.length),R<0?R+=A.length:R>A.length&&(R=A.length);q1)throw new AggregateError(t,"Encountered errors while disposing of store");return Array.isArray(e)?[]:e}else if(e)return e.dispose(),e}function tk(...e){return ni(()=>xa(e))}function ni(e){return{dispose:ek(()=>{e()})}}var Yy=class Vy{constructor(){this._toDispose=new Set,this._isDisposed=!1}dispose(){this._isDisposed||(this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{xa(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw new Error("Cannot register a disposable on itself!");return this._isDisposed?Vy.DISABLE_DISPOSED_WARNING||console.warn(new Error("Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!").stack):this._toDispose.add(t),t}delete(t){if(t){if(t===this)throw new Error("Cannot dispose a disposable on itself!");this._toDispose.delete(t),t.dispose()}}deleteAndLeak(t){t&&this._toDispose.has(t)&&(this._toDispose.delete(t),void 0)}};Yy.DISABLE_DISPOSED_WARNING=!1;var Us=Yy,ht=class{constructor(){this._store=new Us,this._store}dispose(){this._store.dispose()}_register(t){if(t===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(t)}};ht.None=Object.freeze({dispose(){}});var fl=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){var t;this._isDisposed||e===this._value||((t=this._value)==null||t.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){var e;this._isDisposed=!0,(e=this._value)==null||e.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e}},ss=typeof window=="object"?window:globalThis,Vf=class Kf{constructor(t){this.element=t,this.next=Kf.Undefined,this.prev=Kf.Undefined}};Vf.Undefined=new Vf(void 0);var si=Vf,xb=class{constructor(){this._first=si.Undefined,this._last=si.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===si.Undefined}clear(){let e=this._first;for(;e!==si.Undefined;){let t=e.next;e.prev=si.Undefined,e.next=si.Undefined,e=t}this._first=si.Undefined,this._last=si.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let i=new si(e);if(this._first===si.Undefined)this._first=i,this._last=i;else if(t){let a=this._last;this._last=i,i.prev=a,a.next=i}else{let a=this._first;this._first=i,i.next=a,a.prev=i}this._size+=1;let s=!1;return()=>{s||(s=!0,this._remove(i))}}shift(){if(this._first!==si.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==si.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==si.Undefined&&e.next!==si.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===si.Undefined&&e.next===si.Undefined?(this._first=si.Undefined,this._last=si.Undefined):e.next===si.Undefined?(this._last=this._last.prev,this._last.next=si.Undefined):e.prev===si.Undefined&&(this._first=this._first.next,this._first.prev=si.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==si.Undefined;)yield e.element,e=e.next}},ik=globalThis.performance&&typeof globalThis.performance.now=="function",nk=class Ky{static create(t){return new Ky(t)}constructor(t){this._now=ik&&t===!1?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime!==-1?this._stopTime-this._startTime:this._now()-this._startTime}},sn;(e=>{e.None=()=>ht.None;function t($,G){return x($,()=>{},0,void 0,!0,void 0,G)}e.defer=t;function i($){return(G,V=null,H)=>{let T=!1,z;return z=$(F=>{if(!T)return z?z.dispose():T=!0,G.call(V,F)},null,H),T&&z.dispose(),z}}e.once=i;function s($,G,V){return f((H,T=null,z)=>$(F=>H.call(T,G(F)),null,z),V)}e.map=s;function a($,G,V){return f((H,T=null,z)=>$(F=>{G(F),H.call(T,F)},null,z),V)}e.forEach=a;function o($,G,V){return f((H,T=null,z)=>$(F=>G(F)&&H.call(T,F),null,z),V)}e.filter=o;function c($){return $}e.signal=c;function h(...$){return(G,V=null,H)=>{let T=tk(...$.map(z=>z(F=>G.call(V,F))));return _(T,H)}}e.any=h;function p($,G,V,H){let T=V;return s($,z=>(T=G(T,z),T),H)}e.reduce=p;function f($,G){let V,H={onWillAddFirstListener(){V=$(T.fire,T)},onDidRemoveLastListener(){V==null||V.dispose()}},T=new ke(H);return G==null||G.add(T),T.event}function _($,G){return G instanceof Array?G.push($):G&&G.add($),$}function x($,G,V=100,H=!1,T=!1,z,F){let xe,j,D,X=0,C,Z={leakWarningThreshold:z,onWillAddFirstListener(){xe=$(oe=>{X++,j=G(j,oe),H&&!D&&(ae.fire(j),j=void 0),C=()=>{let K=j;j=void 0,D=void 0,(!H||X>1)&&ae.fire(K),X=0},typeof V=="number"?(clearTimeout(D),D=setTimeout(C,V)):D===void 0&&(D=0,queueMicrotask(C))})},onWillRemoveListener(){T&&X>0&&(C==null||C())},onDidRemoveLastListener(){C=void 0,xe.dispose()}},ae=new ke(Z);return F==null||F.add(ae),ae.event}e.debounce=x;function b($,G=0,V){return e.debounce($,(H,T)=>H?(H.push(T),H):[T],G,void 0,!0,void 0,V)}e.accumulate=b;function v($,G=(H,T)=>H===T,V){let H=!0,T;return o($,z=>{let F=H||!G(z,T);return H=!1,T=z,F},V)}e.latch=v;function S($,G,V){return[e.filter($,G,V),e.filter($,H=>!G(H),V)]}e.split=S;function N($,G=!1,V=[],H){let T=V.slice(),z=$(j=>{T?T.push(j):xe.fire(j)});H&&H.add(z);let F=()=>{T==null||T.forEach(j=>xe.fire(j)),T=null},xe=new ke({onWillAddFirstListener(){z||(z=$(j=>xe.fire(j)),H&&H.add(z))},onDidAddFirstListener(){T&&(G?setTimeout(F):F())},onDidRemoveLastListener(){z&&z.dispose(),z=null}});return H&&H.add(xe),xe.event}e.buffer=N;function M($,G){return(V,H,T)=>{let z=G(new L);return $(function(F){let xe=z.evaluate(F);xe!==E&&V.call(H,xe)},void 0,T)}}e.chain=M;let E=Symbol("HaltChainable");class L{constructor(){this.steps=[]}map(G){return this.steps.push(G),this}forEach(G){return this.steps.push(V=>(G(V),V)),this}filter(G){return this.steps.push(V=>G(V)?V:E),this}reduce(G,V){let H=V;return this.steps.push(T=>(H=G(H,T),H)),this}latch(G=(V,H)=>V===H){let V=!0,H;return this.steps.push(T=>{let z=V||!G(T,H);return V=!1,H=T,z?T:E}),this}evaluate(G){for(let V of this.steps)if(G=V(G),G===E)break;return G}}function I($,G,V=H=>H){let H=(...xe)=>F.fire(V(...xe)),T=()=>$.on(G,H),z=()=>$.removeListener(G,H),F=new ke({onWillAddFirstListener:T,onDidRemoveLastListener:z});return F.event}e.fromNodeEventEmitter=I;function A($,G,V=H=>H){let H=(...xe)=>F.fire(V(...xe)),T=()=>$.addEventListener(G,H),z=()=>$.removeEventListener(G,H),F=new ke({onWillAddFirstListener:T,onDidRemoveLastListener:z});return F.event}e.fromDOMEventEmitter=A;function q($){return new Promise(G=>i($)(G))}e.toPromise=q;function R($){let G=new ke;return $.then(V=>{G.fire(V)},()=>{G.fire(void 0)}).finally(()=>{G.dispose()}),G.event}e.fromPromise=R;function ne($,G){return $(V=>G.fire(V))}e.forward=ne;function ue($,G,V){return G(V),$(H=>G(H))}e.runAndSubscribe=ue;class ye{constructor(G,V){this._observable=G,this._counter=0,this._hasChanged=!1;let H={onWillAddFirstListener:()=>{G.addObserver(this)},onDidRemoveLastListener:()=>{G.removeObserver(this)}};this.emitter=new ke(H),V&&V.add(this.emitter)}beginUpdate(G){this._counter++}handlePossibleChange(G){}handleChange(G,V){this._hasChanged=!0}endUpdate(G){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function B($,G){return new ye($,G).emitter.event}e.fromObservable=B;function re($){return(G,V,H)=>{let T=0,z=!1,F={beginUpdate(){T++},endUpdate(){T--,T===0&&($.reportChanges(),z&&(z=!1,G.call(V)))},handlePossibleChange(){},handleChange(){z=!0}};$.addObserver(F),$.reportChanges();let xe={dispose(){$.removeObserver(F)}};return H instanceof Us?H.add(xe):Array.isArray(H)&&H.push(xe),xe}}e.fromObservableLight=re})(sn||(sn={}));var Xf=class Zf{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${Zf._idPool++}`,Zf.all.add(this)}start(t){this._stopWatch=new nk,this.listenerCount=t}stop(){if(this._stopWatch){let t=this._stopWatch.elapsed();this.durations.push(t),this.elapsedOverall+=t,this.invocationCount+=1,this._stopWatch=void 0}}};Xf.all=new Set,Xf._idPool=0;var rk=Xf,sk=-1,Xy=class Zy{constructor(t,i,s=(Zy._idPool++).toString(16).padStart(3,"0")){this._errorHandler=t,this.threshold=i,this.name=s,this._warnCountdown=0}dispose(){var t;(t=this._stacks)==null||t.clear()}check(t,i){let s=this.threshold;if(s<=0||i{let o=this._stacks.get(t.value)||0;this._stacks.set(t.value,o-1)}}getMostFrequentStack(){if(!this._stacks)return;let t,i=0;for(let[s,a]of this._stacks)(!t||i{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)}},XC=new KC;function gu(e){ZC(e)||XC.onUnexpectedError(e)}var Wf="Canceled";function ZC(e){return e instanceof QC?!0:e instanceof Error&&e.name===Wf&&e.message===Wf}var QC=class extends Error{constructor(){super(Wf),this.name=this.message}};function JC(e){return new Error(`Illegal argument: ${e}`)}var gb=class Gf extends Error{constructor(t){super(t),this.name="CodeExpectedError"}static fromError(t){if(t instanceof Gf)return t;let i=new Gf;return i.message=t.message,i.stack=t.stack,i}static isErrorNoTelemetry(t){return t.name==="CodeExpectedError"}},Yf=class Wy extends Error{constructor(t){super(t||"An unexpected bug occurred."),Object.setPrototypeOf(this,Wy.prototype)}};function qn(e,t=0){return e[e.length-(1+t)]}var ek;(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})(ek||(ek={}));function tk(e,t){let i=this,s=!1,a;return function(){return s||(s=!0,t||(a=e.apply(i,arguments))),a}}var Gy;(e=>{function t(A){return A&&typeof A=="object"&&typeof A[Symbol.iterator]=="function"}e.is=t;let i=Object.freeze([]);function s(){return i}e.empty=s;function*a(A){yield A}e.single=a;function o(A){return t(A)?A:a(A)}e.wrap=o;function c(A){return A||i}e.from=c;function*h(A){for(let W=A.length-1;W>=0;W--)yield A[W]}e.reverse=h;function p(A){return!A||A[Symbol.iterator]().next().done===!0}e.isEmpty=p;function f(A){return A[Symbol.iterator]().next().value}e.first=f;function _(A,W){let D=0;for(let ne of A)if(W(ne,D++))return!0;return!1}e.some=_;function x(A,W){for(let D of A)if(W(D))return D}e.find=x;function*b(A,W){for(let D of A)W(D)&&(yield D)}e.filter=b;function*v(A,W){let D=0;for(let ne of A)yield W(ne,D++)}e.map=v;function*S(A,W){let D=0;for(let ne of A)yield*W(ne,D++)}e.flatMap=S;function*N(...A){for(let W of A)yield*W}e.concat=N;function B(A,W,D){let ne=D;for(let ue of A)ne=W(ne,ue);return ne}e.reduce=B;function*E(A,W,D=A.length){for(W<0&&(W+=A.length),D<0?D+=A.length:D>A.length&&(D=A.length);W1)throw new AggregateError(t,"Encountered errors while disposing of store");return Array.isArray(e)?[]:e}else if(e)return e.dispose(),e}function ik(...e){return ti(()=>xa(e))}function ti(e){return{dispose:tk(()=>{e()})}}var Yy=class Vy{constructor(){this._toDispose=new Set,this._isDisposed=!1}dispose(){this._isDisposed||(this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{xa(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw new Error("Cannot register a disposable on itself!");return this._isDisposed?Vy.DISABLE_DISPOSED_WARNING||console.warn(new Error("Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!").stack):this._toDispose.add(t),t}delete(t){if(t){if(t===this)throw new Error("Cannot dispose a disposable on itself!");this._toDispose.delete(t),t.dispose()}}deleteAndLeak(t){t&&this._toDispose.has(t)&&(this._toDispose.delete(t),void 0)}};Yy.DISABLE_DISPOSED_WARNING=!1;var $s=Yy,ut=class{constructor(){this._store=new $s,this._store}dispose(){this._store.dispose()}_register(t){if(t===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(t)}};ut.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}},as=typeof window=="object"?window:globalThis,Vf=class Kf{constructor(t){this.element=t,this.next=Kf.Undefined,this.prev=Kf.Undefined}};Vf.Undefined=new Vf(void 0);var si=Vf,xb=class{constructor(){this._first=si.Undefined,this._last=si.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===si.Undefined}clear(){let e=this._first;for(;e!==si.Undefined;){let t=e.next;e.prev=si.Undefined,e.next=si.Undefined,e=t}this._first=si.Undefined,this._last=si.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let i=new si(e);if(this._first===si.Undefined)this._first=i,this._last=i;else if(t){let a=this._last;this._last=i,i.prev=a,a.next=i}else{let a=this._first;this._first=i,i.next=a,a.prev=i}this._size+=1;let s=!1;return()=>{s||(s=!0,this._remove(i))}}shift(){if(this._first!==si.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==si.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==si.Undefined&&e.next!==si.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===si.Undefined&&e.next===si.Undefined?(this._first=si.Undefined,this._last=si.Undefined):e.next===si.Undefined?(this._last=this._last.prev,this._last.next=si.Undefined):e.prev===si.Undefined&&(this._first=this._first.next,this._first.prev=si.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==si.Undefined;)yield e.element,e=e.next}},nk=globalThis.performance&&typeof globalThis.performance.now=="function",rk=class Ky{static create(t){return new Ky(t)}constructor(t){this._now=nk&&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=()=>ut.None;function t(F,Y){return x(F,()=>{},0,void 0,!0,void 0,Y)}e.defer=t;function i(F){return(Y,V=null,U)=>{let T=!1,P;return P=F(q=>{if(!T)return P?P.dispose():T=!0,Y.call(V,q)},null,U),T&&P.dispose(),P}}e.once=i;function s(F,Y,V){return f((U,T=null,P)=>F(q=>U.call(T,Y(q)),null,P),V)}e.map=s;function a(F,Y,V){return f((U,T=null,P)=>F(q=>{Y(q),U.call(T,q)},null,P),V)}e.forEach=a;function o(F,Y,V){return f((U,T=null,P)=>F(q=>Y(q)&&U.call(T,q),null,P),V)}e.filter=o;function c(F){return F}e.signal=c;function h(...F){return(Y,V=null,U)=>{let T=ik(...F.map(P=>P(q=>Y.call(V,q))));return _(T,U)}}e.any=h;function p(F,Y,V,U){let T=V;return s(F,P=>(T=Y(T,P),T),U)}e.reduce=p;function f(F,Y){let V,U={onWillAddFirstListener(){V=F(T.fire,T)},onDidRemoveLastListener(){V==null||V.dispose()}},T=new Ce(U);return Y==null||Y.add(T),T.event}function _(F,Y){return Y instanceof Array?Y.push(F):Y&&Y.add(F),F}function x(F,Y,V=100,U=!1,T=!1,P,q){let xe,j,R,Z=0,k,K={leakWarningThreshold:P,onWillAddFirstListener(){xe=F(oe=>{Z++,j=Y(j,oe),U&&!R&&(ae.fire(j),j=void 0),k=()=>{let X=j;j=void 0,R=void 0,(!U||Z>1)&&ae.fire(X),Z=0},typeof V=="number"?(clearTimeout(R),R=setTimeout(k,V)):R===void 0&&(R=0,queueMicrotask(k))})},onWillRemoveListener(){T&&Z>0&&(k==null||k())},onDidRemoveLastListener(){k=void 0,xe.dispose()}},ae=new Ce(K);return q==null||q.add(ae),ae.event}e.debounce=x;function b(F,Y=0,V){return e.debounce(F,(U,T)=>U?(U.push(T),U):[T],Y,void 0,!0,void 0,V)}e.accumulate=b;function v(F,Y=(U,T)=>U===T,V){let U=!0,T;return o(F,P=>{let q=U||!Y(P,T);return U=!1,T=P,q},V)}e.latch=v;function S(F,Y,V){return[e.filter(F,Y,V),e.filter(F,U=>!Y(U),V)]}e.split=S;function N(F,Y=!1,V=[],U){let T=V.slice(),P=F(j=>{T?T.push(j):xe.fire(j)});U&&U.add(P);let q=()=>{T==null||T.forEach(j=>xe.fire(j)),T=null},xe=new Ce({onWillAddFirstListener(){P||(P=F(j=>xe.fire(j)),U&&U.add(P))},onDidAddFirstListener(){T&&(Y?setTimeout(q):q())},onDidRemoveLastListener(){P&&P.dispose(),P=null}});return U&&U.add(xe),xe.event}e.buffer=N;function B(F,Y){return(V,U,T)=>{let P=Y(new O);return F(function(q){let xe=P.evaluate(q);xe!==E&&V.call(U,xe)},void 0,T)}}e.chain=B;let E=Symbol("HaltChainable");class O{constructor(){this.steps=[]}map(Y){return this.steps.push(Y),this}forEach(Y){return this.steps.push(V=>(Y(V),V)),this}filter(Y){return this.steps.push(V=>Y(V)?V:E),this}reduce(Y,V){let U=V;return this.steps.push(T=>(U=Y(U,T),U)),this}latch(Y=(V,U)=>V===U){let V=!0,U;return this.steps.push(T=>{let P=V||!Y(T,U);return V=!1,U=T,P?T:E}),this}evaluate(Y){for(let V of this.steps)if(Y=V(Y),Y===E)break;return Y}}function H(F,Y,V=U=>U){let U=(...xe)=>q.fire(V(...xe)),T=()=>F.on(Y,U),P=()=>F.removeListener(Y,U),q=new Ce({onWillAddFirstListener:T,onDidRemoveLastListener:P});return q.event}e.fromNodeEventEmitter=H;function A(F,Y,V=U=>U){let U=(...xe)=>q.fire(V(...xe)),T=()=>F.addEventListener(Y,U),P=()=>F.removeEventListener(Y,U),q=new Ce({onWillAddFirstListener:T,onDidRemoveLastListener:P});return q.event}e.fromDOMEventEmitter=A;function W(F){return new Promise(Y=>i(F)(Y))}e.toPromise=W;function D(F){let Y=new Ce;return F.then(V=>{Y.fire(V)},()=>{Y.fire(void 0)}).finally(()=>{Y.dispose()}),Y.event}e.fromPromise=D;function ne(F,Y){return F(V=>Y.fire(V))}e.forward=ne;function ue(F,Y,V){return Y(V),F(U=>Y(U))}e.runAndSubscribe=ue;class be{constructor(Y,V){this._observable=Y,this._counter=0,this._hasChanged=!1;let U={onWillAddFirstListener:()=>{Y.addObserver(this)},onDidRemoveLastListener:()=>{Y.removeObserver(this)}};this.emitter=new Ce(U),V&&V.add(this.emitter)}beginUpdate(Y){this._counter++}handlePossibleChange(Y){}handleChange(Y,V){this._hasChanged=!0}endUpdate(Y){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function L(F,Y){return new be(F,Y).emitter.event}e.fromObservable=L;function re(F){return(Y,V,U)=>{let T=0,P=!1,q={beginUpdate(){T++},endUpdate(){T--,T===0&&(F.reportChanges(),P&&(P=!1,Y.call(V)))},handlePossibleChange(){},handleChange(){P=!0}};F.addObserver(q),F.reportChanges();let xe={dispose(){F.removeObserver(q)}};return U instanceof $s?U.add(xe):Array.isArray(U)&&U.push(xe),xe}}e.fromObservableLight=re})(sn||(sn={}));var Xf=class Zf{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${Zf._idPool++}`,Zf.all.add(this)}start(t){this._stopWatch=new rk,this.listenerCount=t}stop(){if(this._stopWatch){let t=this._stopWatch.elapsed();this.durations.push(t),this.elapsedOverall+=t,this.invocationCount+=1,this._stopWatch=void 0}}};Xf.all=new Set,Xf._idPool=0;var sk=Xf,ak=-1,Xy=class Zy{constructor(t,i,s=(Zy._idPool++).toString(16).padStart(3,"0")){this._errorHandler=t,this.threshold=i,this.name=s,this._warnCountdown=0}dispose(){var t;(t=this._stacks)==null||t.clear()}check(t,i){let s=this.threshold;if(s<=0||i{let o=this._stacks.get(t.value)||0;this._stacks.set(t.value,o-1)}}getMostFrequentStack(){if(!this._stacks)return;let t,i=0;for(let[s,a]of this._stacks)(!t||i{var h,p,f,_,x;if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let b=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(b);let v=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],S=new ck(`${b}. HINT: Stack shows most frequent listener (${v[1]}-times)`,v[0]);return(((h=this._options)==null?void 0:h.onListenerError)||gu)(S),ht.None}if(this._disposed)return ht.None;i&&(t=t.bind(i));let a=new nf(t),o;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(a.stack=lk.create(),o=this._leakageMon.check(a.stack,this._size+1)),this._listeners?this._listeners instanceof nf?(this._deliveryQueue??(this._deliveryQueue=new fk),this._listeners=[this._listeners,a]):this._listeners.push(a):((f=(p=this._options)==null?void 0:p.onWillAddFirstListener)==null||f.call(p,this),this._listeners=a,(x=(_=this._options)==null?void 0:_.onDidAddFirstListener)==null||x.call(_,this)),this._size++;let c=ni(()=>{o==null||o(),this._removeListener(a)});return s instanceof Us?s.add(c):Array.isArray(s)&&s.push(c),c}),this._event}_removeListener(t){var o,c,h,p;if((c=(o=this._options)==null?void 0:o.onWillRemoveListener)==null||c.call(o,this),!this._listeners)return;if(this._size===1){this._listeners=void 0,(p=(h=this._options)==null?void 0:h.onDidRemoveLastListener)==null||p.call(h,this),this._size=0;return}let i=this._listeners,s=i.indexOf(t);if(s===-1)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),new Error("Attempted to dispose unknown listener");this._size--,i[s]=void 0;let a=this._deliveryQueue.current===this;if(this._size*hk<=i.length){let f=0;for(let _=0;_0}},fk=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,i){this.i=0,this.end=i,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},Qf=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new ke,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new ke,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(t){return this.mapWindowIdToZoomLevel.get(this.getWindowId(t))??0}setZoomLevel(t,i){if(this.getZoomLevel(i)===t)return;let s=this.getWindowId(i);this.mapWindowIdToZoomLevel.set(s,t),this._onDidChangeZoomLevel.fire(s)}getZoomFactor(t){return this.mapWindowIdToZoomFactor.get(this.getWindowId(t))??1}setZoomFactor(t,i){this.mapWindowIdToZoomFactor.set(this.getWindowId(i),t)}setFullscreen(t,i){if(this.isFullscreen(i)===t)return;let s=this.getWindowId(i);this.mapWindowIdToFullScreen.set(s,t),this._onDidChangeFullscreen.fire(s)}isFullscreen(t){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(t))}getWindowId(t){return t.vscodeWindowId}};Qf.INSTANCE=new Qf;var Gp=Qf;function pk(e,t,i){typeof t=="string"&&(t=e.matchMedia(t)),t.addEventListener("change",i)}Gp.INSTANCE.onDidChangeZoomLevel;function mk(e){return Gp.INSTANCE.getZoomFactor(e)}Gp.INSTANCE.onDidChangeFullscreen;var xl=typeof navigator=="object"?navigator.userAgent:"",Jf=xl.indexOf("Firefox")>=0,gk=xl.indexOf("AppleWebKit")>=0,Yp=xl.indexOf("Chrome")>=0,xk=!Yp&&xl.indexOf("Safari")>=0;xl.indexOf("Electron/")>=0;xl.indexOf("Android")>=0;var rf=!1;if(typeof ss.matchMedia=="function"){let e=ss.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)"),t=ss.matchMedia("(display-mode: fullscreen)");rf=e.matches,pk(ss,e,({matches:i})=>{rf&&t.matches||(rf=i)})}var ol="en",ep=!1,tp=!1,xu=!1,Jy=!1,iu,_u=ol,_b=ol,_k,gr,ga=globalThis,rn,Ty;typeof ga.vscode<"u"&&typeof ga.vscode.process<"u"?rn=ga.vscode.process:typeof process<"u"&&typeof((Ty=process==null?void 0:process.versions)==null?void 0:Ty.node)=="string"&&(rn=process);var Ay,bk=typeof((Ay=rn==null?void 0:rn.versions)==null?void 0:Ay.electron)=="string",vk=bk&&(rn==null?void 0:rn.type)==="renderer",Ry;if(typeof rn=="object"){ep=rn.platform==="win32",tp=rn.platform==="darwin",xu=rn.platform==="linux",xu&&rn.env.SNAP&&rn.env.SNAP_REVISION,rn.env.CI||rn.env.BUILD_ARTIFACTSTAGINGDIRECTORY,iu=ol,_u=ol;let e=rn.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);iu=t.userLocale,_b=t.osLocale,_u=t.resolvedLanguage||ol,_k=(Ry=t.languagePack)==null?void 0:Ry.translationsConfigFile}catch{}Jy=!0}else typeof navigator=="object"&&!vk?(gr=navigator.userAgent,ep=gr.indexOf("Windows")>=0,tp=gr.indexOf("Macintosh")>=0,(gr.indexOf("Macintosh")>=0||gr.indexOf("iPad")>=0||gr.indexOf("iPhone")>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0,xu=gr.indexOf("Linux")>=0,(gr==null?void 0:gr.indexOf("Mobi"))>=0,_u=globalThis._VSCODE_NLS_LANGUAGE||ol,iu=navigator.language.toLowerCase(),_b=iu):console.error("Unable to resolve platform.");var e0=ep,Rr=tp,yk=xu,bb=Jy,Dr=gr,Bs=_u,Sk;(e=>{function t(){return Bs}e.value=t;function i(){return Bs.length===2?Bs==="en":Bs.length>=3?Bs[0]==="e"&&Bs[1]==="n"&&Bs[2]==="-":!1}e.isDefaultVariant=i;function s(){return Bs==="en"}e.isDefault=s})(Sk||(Sk={}));var wk=typeof ga.postMessage=="function"&&!ga.importScripts;(()=>{if(wk){let e=[];ga.addEventListener("message",i=>{if(i.data&&i.data.vscodeScheduleAsyncWork)for(let s=0,a=e.length;s{let s=++t;e.push({id:s,callback:i}),ga.postMessage({vscodeScheduleAsyncWork:s},"*")}}return e=>setTimeout(e)})();var Ck=!!(Dr&&Dr.indexOf("Chrome")>=0);Dr&&Dr.indexOf("Firefox")>=0;!Ck&&Dr&&Dr.indexOf("Safari")>=0;Dr&&Dr.indexOf("Edg/")>=0;Dr&&Dr.indexOf("Android")>=0;var tl=typeof navigator=="object"?navigator:{};bb||document.queryCommandSupported&&document.queryCommandSupported("copy")||tl&&tl.clipboard&&tl.clipboard.writeText,bb||tl&&tl.clipboard&&tl.clipboard.readText;var Vp=class{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e}keyCodeToStr(e){return this._keyCodeToStr[e]}strToKeyCode(e){return this._strToKeyCode[e.toLowerCase()]||0}},sf=new Vp,vb=new Vp,yb=new Vp,kk=new Array(230),t0;(e=>{function t(h){return sf.keyCodeToStr(h)}e.toString=t;function i(h){return sf.strToKeyCode(h)}e.fromString=i;function s(h){return vb.keyCodeToStr(h)}e.toUserSettingsUS=s;function a(h){return yb.keyCodeToStr(h)}e.toUserSettingsGeneral=a;function o(h){return vb.strToKeyCode(h)||yb.strToKeyCode(h)}e.fromUserSettings=o;function c(h){if(h>=98&&h<=113)return null;switch(h){case 16:return"Up";case 18:return"Down";case 15:return"Left";case 17:return"Right"}return sf.keyCodeToStr(h)}e.toElectronAccelerator=c})(t0||(t0={}));var Ek=class i0{constructor(t,i,s,a,o){this.ctrlKey=t,this.shiftKey=i,this.altKey=s,this.metaKey=a,this.keyCode=o}equals(t){return t instanceof i0&&this.ctrlKey===t.ctrlKey&&this.shiftKey===t.shiftKey&&this.altKey===t.altKey&&this.metaKey===t.metaKey&&this.keyCode===t.keyCode}getHashCode(){let t=this.ctrlKey?"1":"0",i=this.shiftKey?"1":"0",s=this.altKey?"1":"0",a=this.metaKey?"1":"0";return`K${t}${i}${s}${a}${this.keyCode}`}isModifierKey(){return this.keyCode===0||this.keyCode===5||this.keyCode===57||this.keyCode===6||this.keyCode===4}toKeybinding(){return new Nk([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},Nk=class{constructor(e){if(e.length===0)throw QC("chords");this.chords=e}getHashCode(){let e="";for(let t=0,i=this.chords.length;t{function t(i){return i===e.None||i===e.Cancelled||i instanceof Ok?!0:!i||typeof i!="object"?!1:typeof i.isCancellationRequested=="boolean"&&typeof i.onCancellationRequested=="function"}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:sn.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:n0})})(Lk||(Lk={}));var Ok=class{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?n0:(this._emitter||(this._emitter=new ke),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}},Kp=class{constructor(e,t){this._isDisposed=!1,this._token=-1,typeof e=="function"&&typeof t=="number"&&this.setIfNotSet(e,t)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._token!==-1&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(e,t){if(this._isDisposed)throw new Yf("Calling 'cancelAndSet' on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new Yf("Calling 'setIfNotSet' on a disposed TimeoutTimer");this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},zk=class{constructor(){this.disposable=void 0,this.isDisposed=!1}cancel(){var e;(e=this.disposable)==null||e.dispose(),this.disposable=void 0}cancelAndSet(e,t,i=globalThis){if(this.isDisposed)throw new Yf("Calling 'cancelAndSet' on a disposed IntervalTimer");this.cancel();let s=i.setInterval(()=>{e()},t);this.disposable=ni(()=>{i.clearInterval(s),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}},Pk;(e=>{async function t(s){let a,o=await Promise.all(s.map(c=>c.then(h=>h,h=>{a||(a=h)})));if(typeof a<"u")throw a;return o}e.settled=t;function i(s){return new Promise(async(a,o)=>{try{await s(a,o)}catch(c){o(c)}})}e.withAsyncBody=i})(Pk||(Pk={}));var kb=class sr{static fromArray(t){return new sr(i=>{i.emitMany(t)})}static fromPromise(t){return new sr(async i=>{i.emitMany(await t)})}static fromPromises(t){return new sr(async i=>{await Promise.all(t.map(async s=>i.emitOne(await s)))})}static merge(t){return new sr(async i=>{await Promise.all(t.map(async s=>{for await(let a of s)i.emitOne(a)}))})}constructor(t,i){this._state=0,this._results=[],this._error=null,this._onReturn=i,this._onStateChanged=new ke,queueMicrotask(async()=>{let s={emitOne:a=>this.emitOne(a),emitMany:a=>this.emitMany(a),reject:a=>this.reject(a)};try{await Promise.resolve(t(s)),this.resolve()}catch(a){this.reject(a)}finally{s.emitOne=void 0,s.emitMany=void 0,s.reject=void 0}})}[Symbol.asyncIterator](){let t=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(t{var i;return(i=this._onReturn)==null||i.call(this),{done:!0,value:void 0}}}}static map(t,i){return new sr(async s=>{for await(let a of t)s.emitOne(i(a))})}map(t){return sr.map(this,t)}static filter(t,i){return new sr(async s=>{for await(let a of t)i(a)&&s.emitOne(a)})}filter(t){return sr.filter(this,t)}static coalesce(t){return sr.filter(t,i=>!!i)}coalesce(){return sr.coalesce(this)}static async toPromise(t){let i=[];for await(let s of t)i.push(s);return i}toPromise(){return sr.toPromise(this)}emitOne(t){this._state===0&&(this._results.push(t),this._onStateChanged.fire())}emitMany(t){this._state===0&&(this._results=this._results.concat(t),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(t){this._state===0&&(this._state=2,this._error=t,this._onStateChanged.fire())}};kb.EMPTY=kb.fromArray([]);var{getWindow:Tr,getWindowId:Ik,onDidRegisterWindow:Hk}=(function(){let e=new Map,t={window:ss,disposables:new Us};e.set(ss.vscodeWindowId,t);let i=new ke,s=new ke,a=new ke;function o(c,h){return(typeof c=="number"?e.get(c):void 0)??(h?t:void 0)}return{onDidRegisterWindow:i.event,onWillUnregisterWindow:a.event,onDidUnregisterWindow:s.event,registerWindow(c){if(e.has(c.vscodeWindowId))return ht.None;let h=new Us,p={window:c,disposables:h.add(new Us)};return e.set(c.vscodeWindowId,p),h.add(ni(()=>{e.delete(c.vscodeWindowId),s.fire(c)})),h.add(Ke(c,$i.BEFORE_UNLOAD,()=>{a.fire(c)})),i.fire(p),h},getWindows(){return e.values()},getWindowsCount(){return e.size},getWindowId(c){return c.vscodeWindowId},hasWindow(c){return e.has(c)},getWindowById:o,getWindow(c){var f;let h=c;if((f=h==null?void 0:h.ownerDocument)!=null&&f.defaultView)return h.ownerDocument.defaultView.window;let p=c;return p!=null&&p.view?p.view.window:ss},getDocument(c){return Tr(c).document}}})(),Uk=class{constructor(e,t,i,s){this._node=e,this._type=t,this._handler=i,this._options=s||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,this._handler=null)}};function Ke(e,t,i,s){return new Uk(e,t,i,s)}var Eb=function(e,t,i,s){return Ke(e,t,i,s)},Xp,$k=class extends zk{constructor(e){super(),this.defaultTarget=e&&Tr(e)}cancelAndSet(e,t,i){return super.cancelAndSet(e,t,i??this.defaultTarget)}},Nb=class{constructor(e,t=0){this._runner=e,this.priority=t,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(e){gu(e)}}static sort(e,t){return t.priority-e.priority}};(function(){let e=new Map,t=new Map,i=new Map,s=new Map,a=o=>{i.set(o,!1);let c=e.get(o)??[];for(t.set(o,c),e.set(o,[]),s.set(o,!0);c.length>0;)c.sort(Nb.sort),c.shift().execute();s.set(o,!1)};Xp=(o,c,h=0)=>{let p=Ik(o),f=new Nb(c,h),_=e.get(p);return _||(_=[],e.set(p,_)),_.push(f),i.get(p)||(i.set(p,!0),o.requestAnimationFrame(()=>a(p))),f}})();function Fk(e){let t=e.getBoundingClientRect(),i=Tr(e);return{left:t.left+i.scrollX,top:t.top+i.scrollY,width:t.width,height:t.height}}var $i={CLICK:"click",MOUSE_DOWN:"mousedown",MOUSE_OVER:"mouseover",MOUSE_LEAVE:"mouseleave",MOUSE_WHEEL:"wheel",POINTER_UP:"pointerup",POINTER_DOWN:"pointerdown",POINTER_MOVE:"pointermove",KEY_DOWN:"keydown",KEY_UP:"keyup",BEFORE_UNLOAD:"beforeunload",CHANGE:"change",FOCUS:"focus",BLUR:"blur",INPUT:"input"},qk=class{constructor(e){this.domNode=e,this._maxWidth="",this._width="",this._height="",this._top="",this._left="",this._bottom="",this._right="",this._paddingTop="",this._paddingLeft="",this._paddingBottom="",this._paddingRight="",this._fontFamily="",this._fontWeight="",this._fontSize="",this._fontStyle="",this._fontFeatureSettings="",this._fontVariationSettings="",this._textDecoration="",this._lineHeight="",this._letterSpacing="",this._className="",this._display="",this._position="",this._visibility="",this._color="",this._backgroundColor="",this._layerHint=!1,this._contain="none",this._boxShadow=""}setMaxWidth(e){let t=Tn(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=Tn(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=Tn(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=Tn(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=Tn(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=Tn(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=Tn(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=Tn(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=Tn(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=Tn(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=Tn(e);this._paddingRight!==t&&(this._paddingRight=t,this.domNode.style.paddingRight=this._paddingRight)}setFontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.domNode.style.fontFamily=this._fontFamily)}setFontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.domNode.style.fontWeight=this._fontWeight)}setFontSize(e){let t=Tn(e);this._fontSize!==t&&(this._fontSize=t,this.domNode.style.fontSize=this._fontSize)}setFontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.domNode.style.fontStyle=this._fontStyle)}setFontFeatureSettings(e){this._fontFeatureSettings!==e&&(this._fontFeatureSettings=e,this.domNode.style.fontFeatureSettings=this._fontFeatureSettings)}setFontVariationSettings(e){this._fontVariationSettings!==e&&(this._fontVariationSettings=e,this.domNode.style.fontVariationSettings=this._fontVariationSettings)}setTextDecoration(e){this._textDecoration!==e&&(this._textDecoration=e,this.domNode.style.textDecoration=this._textDecoration)}setLineHeight(e){let t=Tn(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=Tn(e);this._letterSpacing!==t&&(this._letterSpacing=t,this.domNode.style.letterSpacing=this._letterSpacing)}setClassName(e){this._className!==e&&(this._className=e,this.domNode.className=this._className)}toggleClassName(e,t){this.domNode.classList.toggle(e,t),this._className=this.domNode.className}setDisplay(e){this._display!==e&&(this._display=e,this.domNode.style.display=this._display)}setPosition(e){this._position!==e&&(this._position=e,this.domNode.style.position=this._position)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this.domNode.style.visibility=this._visibility)}setColor(e){this._color!==e&&(this._color=e,this.domNode.style.color=this._color)}setBackgroundColor(e){this._backgroundColor!==e&&(this._backgroundColor=e,this.domNode.style.backgroundColor=this._backgroundColor)}setLayerHinting(e){this._layerHint!==e&&(this._layerHint=e,this.domNode.style.transform=this._layerHint?"translate3d(0px, 0px, 0px)":"")}setBoxShadow(e){this._boxShadow!==e&&(this._boxShadow=e,this.domNode.style.boxShadow=e)}setContain(e){this._contain!==e&&(this._contain=e,this.domNode.style.contain=this._contain)}setAttribute(e,t){this.domNode.setAttribute(e,t)}removeAttribute(e){this.domNode.removeAttribute(e)}appendChild(e){this.domNode.appendChild(e.domNode)}removeChild(e){this.domNode.removeChild(e.domNode)}};function Tn(e){return typeof e=="number"?`${e}px`:e}function Ao(e){return new qk(e)}var r0=class{constructor(){this._hooks=new Us,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(e,t){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let i=this._onStopCallback;this._onStopCallback=null,e&&i&&i(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,i,s,a){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=s,this._onStopCallback=a;let o=e;try{e.setPointerCapture(t),this._hooks.add(ni(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{o=Tr(e)}this._hooks.add(Ke(o,$i.POINTER_MOVE,c=>{if(c.buttons!==i){this.stopMonitoring(!0);return}c.preventDefault(),this._pointerMoveCallback(c)})),this._hooks.add(Ke(o,$i.POINTER_UP,c=>this.stopMonitoring(!0)))}};function Wk(e,t,i){let s=null,a=null;if(typeof i.value=="function"?(s="value",a=i.value,a.length!==0&&console.warn("Memoize should only be used in functions with zero parameters")):typeof i.get=="function"&&(s="get",a=i.get),!a)throw new Error("not supported");let o=`$memoize$${t}`;i[s]=function(...c){return this.hasOwnProperty(o)||Object.defineProperty(this,o,{configurable:!1,enumerable:!1,writable:!1,value:a.apply(this,c)}),this[o]}}var Nr;(e=>(e.Tap="-xterm-gesturetap",e.Change="-xterm-gesturechange",e.Start="-xterm-gesturestart",e.End="-xterm-gesturesend",e.Contextmenu="-xterm-gesturecontextmenu"))(Nr||(Nr={}));var wo=class on extends ht{constructor(){super(),this.dispatched=!1,this.targets=new xb,this.ignoreTargets=new xb,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(sn.runAndSubscribe(Hk,({window:t,disposables:i})=>{i.add(Ke(t.document,"touchstart",s=>this.onTouchStart(s),{passive:!1})),i.add(Ke(t.document,"touchend",s=>this.onTouchEnd(t,s))),i.add(Ke(t.document,"touchmove",s=>this.onTouchMove(s),{passive:!1}))},{window:ss,disposables:this._store}))}static addTarget(t){if(!on.isTouchDevice())return ht.None;on.INSTANCE||(on.INSTANCE=new on);let i=on.INSTANCE.targets.push(t);return ni(i)}static ignoreTarget(t){if(!on.isTouchDevice())return ht.None;on.INSTANCE||(on.INSTANCE=new on);let i=on.INSTANCE.ignoreTargets.push(t);return ni(i)}static isTouchDevice(){return"ontouchstart"in ss||navigator.maxTouchPoints>0}dispose(){this.handle&&(this.handle.dispose(),this.handle=null),super.dispose()}onTouchStart(t){let i=Date.now();this.handle&&(this.handle.dispose(),this.handle=null);for(let s=0,a=t.targetTouches.length;s=on.HOLD_DELAY&&Math.abs(p.initialPageX-qn(p.rollingPageX))<30&&Math.abs(p.initialPageY-qn(p.rollingPageY))<30){let _=this.newGestureEvent(Nr.Contextmenu,p.initialTarget);_.pageX=qn(p.rollingPageX),_.pageY=qn(p.rollingPageY),this.dispatchEvent(_)}else if(a===1){let _=qn(p.rollingPageX),x=qn(p.rollingPageY),b=qn(p.rollingTimestamps)-p.rollingTimestamps[0],v=_-p.rollingPageX[0],S=x-p.rollingPageY[0],N=[...this.targets].filter(M=>p.initialTarget instanceof Node&&M.contains(p.initialTarget));this.inertia(t,N,s,Math.abs(v)/b,v>0?1:-1,_,Math.abs(S)/b,S>0?1:-1,x)}this.dispatchEvent(this.newGestureEvent(Nr.End,p.initialTarget)),delete this.activeTouches[h.identifier]}this.dispatched&&(i.preventDefault(),i.stopPropagation(),this.dispatched=!1)}newGestureEvent(t,i){let s=document.createEvent("CustomEvent");return s.initEvent(t,!1,!0),s.initialTarget=i,s.tapCount=0,s}dispatchEvent(t){if(t.type===Nr.Tap){let i=new Date().getTime(),s=0;i-this._lastSetTapCountTime>on.CLEAR_TAP_COUNT_TIME?s=1:s=2,this._lastSetTapCountTime=i,t.tapCount=s}else(t.type===Nr.Change||t.type===Nr.Contextmenu)&&(this._lastSetTapCountTime=0);if(t.initialTarget instanceof Node){for(let s of this.ignoreTargets)if(s.contains(t.initialTarget))return;let i=[];for(let s of this.targets)if(s.contains(t.initialTarget)){let a=0,o=t.initialTarget;for(;o&&o!==s;)a++,o=o.parentElement;i.push([a,s])}i.sort((s,a)=>s[0]-a[0]);for(let[s,a]of i)a.dispatchEvent(t),this.dispatched=!0}}inertia(t,i,s,a,o,c,h,p,f){this.handle=Xp(t,()=>{let _=Date.now(),x=_-s,b=0,v=0,S=!0;a+=on.SCROLL_FRICTION*x,h+=on.SCROLL_FRICTION*x,a>0&&(S=!1,b=o*a*x),h>0&&(S=!1,v=p*h*x);let N=this.newGestureEvent(Nr.Change);N.translationX=b,N.translationY=v,i.forEach(M=>M.dispatchEvent(N)),S||this.inertia(t,i,_,a,o,c+b,h,p,f+v)})}onTouchMove(t){let i=Date.now();for(let s=0,a=t.changedTouches.length;s3&&(c.rollingPageX.shift(),c.rollingPageY.shift(),c.rollingTimestamps.shift()),c.rollingPageX.push(o.pageX),c.rollingPageY.push(o.pageY),c.rollingTimestamps.push(i)}this.dispatched&&(t.preventDefault(),t.stopPropagation(),this.dispatched=!1)}};wo.SCROLL_FRICTION=-.005,wo.HOLD_DELAY=700,wo.CLEAR_TAP_COUNT_TIME=400,fi([Wk],wo,"isTouchDevice",1);var Gk=wo,Zp=class extends ht{onclick(e,t){this._register(Ke(e,$i.CLICK,i=>t(new nu(Tr(e),i))))}onmousedown(e,t){this._register(Ke(e,$i.MOUSE_DOWN,i=>t(new nu(Tr(e),i))))}onmouseover(e,t){this._register(Ke(e,$i.MOUSE_OVER,i=>t(new nu(Tr(e),i))))}onmouseleave(e,t){this._register(Ke(e,$i.MOUSE_LEAVE,i=>t(new nu(Tr(e),i))))}onkeydown(e,t){this._register(Ke(e,$i.KEY_DOWN,i=>t(new Sb(i))))}onkeyup(e,t){this._register(Ke(e,$i.KEY_UP,i=>t(new Sb(i))))}oninput(e,t){this._register(Ke(e,$i.INPUT,t))}onblur(e,t){this._register(Ke(e,$i.BLUR,t))}onfocus(e,t){this._register(Ke(e,$i.FOCUS,t))}onchange(e,t){this._register(Ke(e,$i.CHANGE,t))}ignoreGesture(e){return Gk.ignoreTarget(e)}},jb=11,Yk=class extends Zp{constructor(e){super(),this._onActivate=e.onActivate,this.bgDomNode=document.createElement("div"),this.bgDomNode.className="arrow-background",this.bgDomNode.style.position="absolute",this.bgDomNode.style.width=e.bgWidth+"px",this.bgDomNode.style.height=e.bgHeight+"px",typeof e.top<"u"&&(this.bgDomNode.style.top="0px"),typeof e.left<"u"&&(this.bgDomNode.style.left="0px"),typeof e.bottom<"u"&&(this.bgDomNode.style.bottom="0px"),typeof e.right<"u"&&(this.bgDomNode.style.right="0px"),this.domNode=document.createElement("div"),this.domNode.className=e.className,this.domNode.style.position="absolute",this.domNode.style.width=jb+"px",this.domNode.style.height=jb+"px",typeof e.top<"u"&&(this.domNode.style.top=e.top+"px"),typeof e.left<"u"&&(this.domNode.style.left=e.left+"px"),typeof e.bottom<"u"&&(this.domNode.style.bottom=e.bottom+"px"),typeof e.right<"u"&&(this.domNode.style.right=e.right+"px"),this._pointerMoveMonitor=this._register(new r0),this._register(Eb(this.bgDomNode,$i.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._register(Eb(this.domNode,$i.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._pointerdownRepeatTimer=this._register(new $k),this._pointerdownScheduleRepeatTimer=this._register(new Kp)}_arrowPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,Tr(e))};this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet(t,200),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,i=>{},()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()}),e.preventDefault()}},Vk=class ip{constructor(t,i,s,a,o,c,h){this._forceIntegerValues=t,this._scrollStateBrand=void 0,this._forceIntegerValues&&(i=i|0,s=s|0,a=a|0,o=o|0,c=c|0,h=h|0),this.rawScrollLeft=a,this.rawScrollTop=h,i<0&&(i=0),a+i>s&&(a=s-i),a<0&&(a=0),o<0&&(o=0),h+o>c&&(h=c-o),h<0&&(h=0),this.width=i,this.scrollWidth=s,this.scrollLeft=a,this.height=o,this.scrollHeight=c,this.scrollTop=h}equals(t){return this.rawScrollLeft===t.rawScrollLeft&&this.rawScrollTop===t.rawScrollTop&&this.width===t.width&&this.scrollWidth===t.scrollWidth&&this.scrollLeft===t.scrollLeft&&this.height===t.height&&this.scrollHeight===t.scrollHeight&&this.scrollTop===t.scrollTop}withScrollDimensions(t,i){return new ip(this._forceIntegerValues,typeof t.width<"u"?t.width:this.width,typeof t.scrollWidth<"u"?t.scrollWidth:this.scrollWidth,i?this.rawScrollLeft:this.scrollLeft,typeof t.height<"u"?t.height:this.height,typeof t.scrollHeight<"u"?t.scrollHeight:this.scrollHeight,i?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new ip(this._forceIntegerValues,this.width,this.scrollWidth,typeof t.scrollLeft<"u"?t.scrollLeft:this.rawScrollLeft,this.height,this.scrollHeight,typeof t.scrollTop<"u"?t.scrollTop:this.rawScrollTop)}createScrollEvent(t,i){let s=this.width!==t.width,a=this.scrollWidth!==t.scrollWidth,o=this.scrollLeft!==t.scrollLeft,c=this.height!==t.height,h=this.scrollHeight!==t.scrollHeight,p=this.scrollTop!==t.scrollTop;return{inSmoothScrolling:i,oldWidth:t.width,oldScrollWidth:t.scrollWidth,oldScrollLeft:t.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:t.height,oldScrollHeight:t.scrollHeight,oldScrollTop:t.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:s,scrollWidthChanged:a,scrollLeftChanged:o,heightChanged:c,scrollHeightChanged:h,scrollTopChanged:p}}},Kk=class extends ht{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new ke),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new Vk(e.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),super.dispose()}setSmoothScrollDuration(e){this._smoothScrollDuration=e}validateScrollPosition(e){return this._state.withScrollPosition(e)}getScrollDimensions(){return this._state}setScrollDimensions(e,t){var s;let i=this._state.withScrollDimensions(e,t);this._setState(i,!!this._smoothScrolling),(s=this._smoothScrolling)==null||s.acceptScrollDimensions(this._state)}getFutureScrollPosition(){return this._smoothScrolling?this._smoothScrolling.to:this._state}getCurrentScrollPosition(){return this._state}setScrollPositionNow(e){let t=this._state.withScrollPosition(e);this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),this._setState(t,!1)}setScrollPositionSmooth(e,t){if(this._smoothScrollDuration===0)return this.setScrollPositionNow(e);if(this._smoothScrolling){e={scrollLeft:typeof e.scrollLeft>"u"?this._smoothScrolling.to.scrollLeft:e.scrollLeft,scrollTop:typeof e.scrollTop>"u"?this._smoothScrolling.to.scrollTop:e.scrollTop};let i=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===i.scrollLeft&&this._smoothScrolling.to.scrollTop===i.scrollTop)return;let s;t?s=new Ab(this._smoothScrolling.from,i,this._smoothScrolling.startTime,this._smoothScrolling.duration):s=this._smoothScrolling.combine(this._state,i,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=s}else{let i=this._state.withScrollPosition(e);this._smoothScrolling=Ab.start(this._state,i,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}hasPendingScrollAnimation(){return!!this._smoothScrolling}_performSmoothScrolling(){if(!this._smoothScrolling)return;let e=this._smoothScrolling.tick(),t=this._state.withScrollPosition(e);if(this._setState(t,!0),!!this._smoothScrolling){if(e.isDone){this._smoothScrolling.dispose(),this._smoothScrolling=null;return}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}}_setState(e,t){let i=this._state;i.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(i,t)))}},Tb=class{constructor(e,t,i){this.scrollLeft=e,this.scrollTop=t,this.isDone=i}};function af(e,t){let i=t-e;return function(s){return e+i*Qk(s)}}function Xk(e,t,i){return function(s){return s2.5*s){let a,o;return t{var e;(e=this._domNode)==null||e.setClassName(this._visibleClassName)},0))}_hide(e){var t;this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,(t=this._domNode)==null||t.setClassName(this._invisibleClassName+(e?" fade":"")))}},e2=140,s0=class extends Zp{constructor(e){super(),this._lazyRender=e.lazyRender,this._host=e.host,this._scrollable=e.scrollable,this._scrollByPage=e.scrollByPage,this._scrollbarState=e.scrollbarState,this._visibilityController=this._register(new Jk(e.visibility,"visible scrollbar "+e.extraScrollbarClassName,"invisible scrollbar "+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new r0),this._shouldRender=!0,this.domNode=Ao(document.createElement("div")),this.domNode.setAttribute("role","presentation"),this.domNode.setAttribute("aria-hidden","true"),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition("absolute"),this._register(Ke(this.domNode.domNode,$i.POINTER_DOWN,t=>this._domNodePointerDown(t)))}_createArrow(e){let t=this._register(new Yk(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,i,s){this.slider=Ao(document.createElement("div")),this.slider.setClassName("slider"),this.slider.setPosition("absolute"),this.slider.setTop(e),this.slider.setLeft(t),typeof i=="number"&&this.slider.setWidth(i),typeof s=="number"&&this.slider.setHeight(s),this.slider.setLayerHinting(!0),this.slider.setContain("strict"),this.domNode.domNode.appendChild(this.slider.domNode),this._register(Ke(this.slider.domNode,$i.POINTER_DOWN,a=>{a.button===0&&(a.preventDefault(),this._sliderPointerDown(a))})),this.onclick(this.slider.domNode,a=>{a.leftButton&&a.stopPropagation()})}_onElementSize(e){return this._scrollbarState.setVisibleSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollSize(e){return this._scrollbarState.setScrollSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollPosition(e){return this._scrollbarState.setScrollPosition(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}beginReveal(){this._visibilityController.setShouldBeVisible(!0)}beginHide(){this._visibilityController.setShouldBeVisible(!1)}render(){this._shouldRender&&(this._shouldRender=!1,this._renderDomNode(this._scrollbarState.getRectangleLargeSize(),this._scrollbarState.getRectangleSmallSize()),this._updateSlider(this._scrollbarState.getSliderSize(),this._scrollbarState.getArrowSize()+this._scrollbarState.getSliderPosition()))}_domNodePointerDown(e){e.target===this.domNode.domNode&&this._onPointerDown(e)}delegatePointerDown(e){let t=this.domNode.domNode.getClientRects()[0].top,i=t+this._scrollbarState.getSliderPosition(),s=t+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),a=this._sliderPointerPosition(e);i<=a&&a<=s?e.button===0&&(e.preventDefault(),this._sliderPointerDown(e)):this._onPointerDown(e)}_onPointerDown(e){let t,i;if(e.target===this.domNode.domNode&&typeof e.offsetX=="number"&&typeof e.offsetY=="number")t=e.offsetX,i=e.offsetY;else{let a=Fk(this.domNode.domNode);t=e.pageX-a.left,i=e.pageY-a.top}let s=this._pointerDownRelativePosition(t,i);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(s):this._scrollbarState.getDesiredScrollPositionFromOffset(s)),e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))}_sliderPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=this._sliderPointerPosition(e),i=this._sliderOrthogonalPointerPosition(e),s=this._scrollbarState.clone();this.slider.toggleClassName("active",!0),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,a=>{let o=this._sliderOrthogonalPointerPosition(a),c=Math.abs(o-i);if(e0&&c>e2){this._setDesiredScrollPositionNow(s.getScrollPosition());return}let h=this._sliderPointerPosition(a)-t;this._setDesiredScrollPositionNow(s.getDesiredScrollPositionFromDelta(h))},()=>{this.slider.toggleClassName("active",!1),this._host.onDragEnd()}),this._host.onDragStart()}_setDesiredScrollPositionNow(e){let t={};this.writeScrollPosition(t,e),this._scrollable.setScrollPositionNow(t)}updateScrollbarSize(e){this._updateScrollbarSize(e),this._scrollbarState.setScrollbarSize(e),this._shouldRender=!0,this._lazyRender||this.render()}isNeeded(){return this._scrollbarState.isNeeded()}},a0=class rp{constructor(t,i,s,a,o,c){this._scrollbarSize=Math.round(i),this._oppositeScrollbarSize=Math.round(s),this._arrowSize=Math.round(t),this._visibleSize=a,this._scrollSize=o,this._scrollPosition=c,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new rp(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(t){let i=Math.round(t);return this._visibleSize!==i?(this._visibleSize=i,this._refreshComputedValues(),!0):!1}setScrollSize(t){let i=Math.round(t);return this._scrollSize!==i?(this._scrollSize=i,this._refreshComputedValues(),!0):!1}setScrollPosition(t){let i=Math.round(t);return this._scrollPosition!==i?(this._scrollPosition=i,this._refreshComputedValues(),!0):!1}setScrollbarSize(t){this._scrollbarSize=Math.round(t)}setOppositeScrollbarSize(t){this._oppositeScrollbarSize=Math.round(t)}static _computeValues(t,i,s,a,o){let c=Math.max(0,s-t),h=Math.max(0,c-2*i),p=a>0&&a>s;if(!p)return{computedAvailableSize:Math.round(c),computedIsNeeded:p,computedSliderSize:Math.round(h),computedSliderRatio:0,computedSliderPosition:0};let f=Math.round(Math.max(20,Math.floor(s*h/a))),_=(h-f)/(a-s),x=o*_;return{computedAvailableSize:Math.round(c),computedIsNeeded:p,computedSliderSize:Math.round(f),computedSliderRatio:_,computedSliderPosition:Math.round(x)}}_refreshComputedValues(){let t=rp._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=t.computedAvailableSize,this._computedIsNeeded=t.computedIsNeeded,this._computedSliderSize=t.computedSliderSize,this._computedSliderRatio=t.computedSliderRatio,this._computedSliderPosition=t.computedSliderPosition}getArrowSize(){return this._arrowSize}getScrollPosition(){return this._scrollPosition}getRectangleLargeSize(){return this._computedAvailableSize}getRectangleSmallSize(){return this._scrollbarSize}isNeeded(){return this._computedIsNeeded}getSliderSize(){return this._computedSliderSize}getSliderPosition(){return this._computedSliderPosition}getDesiredScrollPositionFromOffset(t){if(!this._computedIsNeeded)return 0;let i=t-this._arrowSize-this._computedSliderSize/2;return Math.round(i/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(t){if(!this._computedIsNeeded)return 0;let i=t-this._arrowSize,s=this._scrollPosition;return i0&&Math.abs(t.deltaY)>0)return 1;let s=.5;if((!this._isAlmostInt(t.deltaX)||!this._isAlmostInt(t.deltaY))&&(s+=.25),i){let a=Math.abs(t.deltaX),o=Math.abs(t.deltaY),c=Math.abs(i.deltaX),h=Math.abs(i.deltaY),p=Math.max(Math.min(a,c),1),f=Math.max(Math.min(o,h),1),_=Math.max(a,c),x=Math.max(o,h);_%p===0&&x%f===0&&(s-=.5)}return Math.min(Math.max(s,0),1)}_isAlmostInt(t){return Math.abs(Math.round(t)-t)<.01}};sp.INSTANCE=new sp;var s2=sp,a2=class extends Zp{constructor(e,t,i){super(),this._onScroll=this._register(new ke),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new ke),this.onWillScroll=this._onWillScroll.event,this._options=o2(t),this._scrollable=i,this._register(this._scrollable.onScroll(a=>{this._onWillScroll.fire(a),this._onDidScroll(a),this._onScroll.fire(a)}));let s={onMouseWheel:a=>this._onMouseWheel(a),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new i2(this._scrollable,this._options,s)),this._horizontalScrollbar=this._register(new t2(this._scrollable,this._options,s)),this._domNode=document.createElement("div"),this._domNode.className="xterm-scrollable-element "+this._options.className,this._domNode.setAttribute("role","presentation"),this._domNode.style.position="relative",this._domNode.appendChild(e),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=Ao(document.createElement("div")),this._leftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=Ao(document.createElement("div")),this._topShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=Ao(document.createElement("div")),this._topLeftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topLeftShadowDomNode.domNode)):(this._leftShadowDomNode=null,this._topShadowDomNode=null,this._topLeftShadowDomNode=null),this._listenOnDomNode=this._options.listenOnDomNode||this._domNode,this._mouseWheelToDispose=[],this._setListeningToMouseWheel(this._options.handleMouseWheel),this.onmouseover(this._listenOnDomNode,a=>this._onMouseOver(a)),this.onmouseleave(this._listenOnDomNode,a=>this._onMouseLeave(a)),this._hideTimeout=this._register(new Kp),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=xa(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(e){this._verticalScrollbar.delegatePointerDown(e)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(e){this._scrollable.setScrollDimensions(e,!1)}updateClassName(e){this._options.className=e,Rr&&(this._options.className+=" mac"),this._domNode.className="xterm-scrollable-element "+this._options.className}updateOptions(e){typeof e.handleMouseWheel<"u"&&(this._options.handleMouseWheel=e.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),typeof e.mouseWheelScrollSensitivity<"u"&&(this._options.mouseWheelScrollSensitivity=e.mouseWheelScrollSensitivity),typeof e.fastScrollSensitivity<"u"&&(this._options.fastScrollSensitivity=e.fastScrollSensitivity),typeof e.scrollPredominantAxis<"u"&&(this._options.scrollPredominantAxis=e.scrollPredominantAxis),typeof e.horizontal<"u"&&(this._options.horizontal=e.horizontal),typeof e.vertical<"u"&&(this._options.vertical=e.vertical),typeof e.horizontalScrollbarSize<"u"&&(this._options.horizontalScrollbarSize=e.horizontalScrollbarSize),typeof e.verticalScrollbarSize<"u"&&(this._options.verticalScrollbarSize=e.verticalScrollbarSize),typeof e.scrollByPage<"u"&&(this._options.scrollByPage=e.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}setRevealOnScroll(e){this._revealOnScroll=e}delegateScrollFromMouseWheelEvent(e){this._onMouseWheel(new Cb(e))}_setListeningToMouseWheel(e){if(this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=xa(this._mouseWheelToDispose),e)){let t=i=>{this._onMouseWheel(new Cb(i))};this._mouseWheelToDispose.push(Ke(this._listenOnDomNode,$i.MOUSE_WHEEL,t,{passive:!1}))}}_onMouseWheel(e){var a;if((a=e.browserEvent)!=null&&a.defaultPrevented)return;let t=s2.INSTANCE;t.acceptStandardWheelEvent(e);let i=!1;if(e.deltaY||e.deltaX){let o=e.deltaY*this._options.mouseWheelScrollSensitivity,c=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&c+o===0?c=o=0:Math.abs(o)>=Math.abs(c)?c=0:o=0),this._options.flipAxes&&([o,c]=[c,o]);let h=!Rr&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||h)&&!c&&(c=o,o=0),e.browserEvent&&e.browserEvent.altKey&&(c=c*this._options.fastScrollSensitivity,o=o*this._options.fastScrollSensitivity);let p=this._scrollable.getFutureScrollPosition(),f={};if(o){let _=Rb*o,x=p.scrollTop-(_<0?Math.floor(_):Math.ceil(_));this._verticalScrollbar.writeScrollPosition(f,x)}if(c){let _=Rb*c,x=p.scrollLeft-(_<0?Math.floor(_):Math.ceil(_));this._horizontalScrollbar.writeScrollPosition(f,x)}f=this._scrollable.validateScrollPosition(f),(p.scrollLeft!==f.scrollLeft||p.scrollTop!==f.scrollTop)&&(this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(f):this._scrollable.setScrollPositionNow(f),i=!0)}let s=i;!s&&this._options.alwaysConsumeMouseWheel&&(s=!0),!s&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(s=!0),s&&(e.preventDefault(),e.stopPropagation())}_onDidScroll(e){this._shouldRender=this._horizontalScrollbar.onDidScroll(e)||this._shouldRender,this._shouldRender=this._verticalScrollbar.onDidScroll(e)||this._shouldRender,this._options.useShadows&&(this._shouldRender=!0),this._revealOnScroll&&this._reveal(),this._options.lazyRender||this._render()}renderNow(){if(!this._options.lazyRender)throw new Error("Please use `lazyRender` together with `renderNow`!");this._render()}_render(){if(this._shouldRender&&(this._shouldRender=!1,this._horizontalScrollbar.render(),this._verticalScrollbar.render(),this._options.useShadows)){let e=this._scrollable.getCurrentScrollPosition(),t=e.scrollTop>0,i=e.scrollLeft>0,s=i?" left":"",a=t?" top":"",o=i||t?" top-left-corner":"";this._leftShadowDomNode.setClassName(`shadow${s}`),this._topShadowDomNode.setClassName(`shadow${a}`),this._topLeftShadowDomNode.setClassName(`shadow${o}${a}${s}`)}}_onDragStart(){this._isDragging=!0,this._reveal()}_onDragEnd(){this._isDragging=!1,this._hide()}_onMouseLeave(e){this._mouseIsOver=!1,this._hide()}_onMouseOver(e){this._mouseIsOver=!0,this._reveal()}_reveal(){this._verticalScrollbar.beginReveal(),this._horizontalScrollbar.beginReveal(),this._scheduleHide()}_hide(){!this._mouseIsOver&&!this._isDragging&&(this._verticalScrollbar.beginHide(),this._horizontalScrollbar.beginHide())}_scheduleHide(){!this._mouseIsOver&&!this._isDragging&&this._hideTimeout.cancelAndSet(()=>this._hide(),n2)}},l2=class extends a2{constructor(e,t,i){super(e,t,i)}setScrollPosition(e){e.reuseAnimation?this._scrollable.setScrollPositionSmooth(e,e.reuseAnimation):this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}};function o2(e){let t={lazyRender:typeof e.lazyRender<"u"?e.lazyRender:!1,className:typeof e.className<"u"?e.className:"",useShadows:typeof e.useShadows<"u"?e.useShadows:!0,handleMouseWheel:typeof e.handleMouseWheel<"u"?e.handleMouseWheel:!0,flipAxes:typeof e.flipAxes<"u"?e.flipAxes:!1,consumeMouseWheelIfScrollbarIsNeeded:typeof e.consumeMouseWheelIfScrollbarIsNeeded<"u"?e.consumeMouseWheelIfScrollbarIsNeeded:!1,alwaysConsumeMouseWheel:typeof e.alwaysConsumeMouseWheel<"u"?e.alwaysConsumeMouseWheel:!1,scrollYToX:typeof e.scrollYToX<"u"?e.scrollYToX:!1,mouseWheelScrollSensitivity:typeof e.mouseWheelScrollSensitivity<"u"?e.mouseWheelScrollSensitivity:1,fastScrollSensitivity:typeof e.fastScrollSensitivity<"u"?e.fastScrollSensitivity:5,scrollPredominantAxis:typeof e.scrollPredominantAxis<"u"?e.scrollPredominantAxis:!0,mouseWheelSmoothScroll:typeof e.mouseWheelSmoothScroll<"u"?e.mouseWheelSmoothScroll:!0,arrowSize:typeof e.arrowSize<"u"?e.arrowSize:11,listenOnDomNode:typeof e.listenOnDomNode<"u"?e.listenOnDomNode:null,horizontal:typeof e.horizontal<"u"?e.horizontal:1,horizontalScrollbarSize:typeof e.horizontalScrollbarSize<"u"?e.horizontalScrollbarSize:10,horizontalSliderSize:typeof e.horizontalSliderSize<"u"?e.horizontalSliderSize:0,horizontalHasArrows:typeof e.horizontalHasArrows<"u"?e.horizontalHasArrows:!1,vertical:typeof e.vertical<"u"?e.vertical:1,verticalScrollbarSize:typeof e.verticalScrollbarSize<"u"?e.verticalScrollbarSize:10,verticalHasArrows:typeof e.verticalHasArrows<"u"?e.verticalHasArrows:!1,verticalSliderSize:typeof e.verticalSliderSize<"u"?e.verticalSliderSize:0,scrollByPage:typeof e.scrollByPage<"u"?e.scrollByPage:!1};return t.horizontalSliderSize=typeof e.horizontalSliderSize<"u"?e.horizontalSliderSize:t.horizontalScrollbarSize,t.verticalSliderSize=typeof e.verticalSliderSize<"u"?e.verticalSliderSize:t.verticalScrollbarSize,Rr&&(t.className+=" mac"),t}var ap=class extends ht{constructor(e,t,i,s,a,o,c,h){super(),this._bufferService=i,this._optionsService=c,this._renderService=h,this._onRequestScrollLines=this._register(new ke),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let p=this._register(new Kk({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:f=>Xp(s.window,f)}));this._register(this._optionsService.onSpecificOptionChange("smoothScrollDuration",()=>{p.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new l2(t,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},p)),this._register(this._optionsService.onMultipleOptionChange(["scrollSensitivity","fastScrollSensitivity","overviewRuler"],()=>this._scrollableElement.updateOptions(this._getChangeOptions()))),this._register(a.onProtocolChange(f=>{this._scrollableElement.updateOptions({handleMouseWheel:!(f&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(sn.runAndSubscribe(o.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=o.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(ni(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=s.mainDocument.createElement("style"),t.appendChild(this._styleElement),this._register(ni(()=>this._styleElement.remove())),this._register(sn.runAndSubscribe(o.onChangeColors,()=>{this._styleElement.textContent=[".xterm .xterm-scrollable-element > .scrollbar > .slider {",` background: ${o.colors.scrollbarSliderBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider:hover {",` background: ${o.colors.scrollbarSliderHoverBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider.active {",` background: ${o.colors.scrollbarSliderActiveBackground.css};`,"}"].join(` -`)})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(f=>this._handleScroll(f)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){var e;return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:((e=this._optionsService.rawOptions.overviewRuler)==null?void 0:e.width)||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),i=t-this._bufferService.buffer.ydisp;i!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(i)),this._isHandlingScroll=!1}};ap=fi([Re(2,_n),Re(3,as),Re(4,Hy),Re(5,gl),Re(6,bn),Re(7,ls)],ap);var lp=class extends ht{constructor(e,t,i,s,a){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=i,this._decorationService=s,this._renderService=a,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement("div"),this._container.classList.add("xterm-decoration-container"),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(o=>this._removeDecoration(o))),this._register(ni(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){var s;let t=this._coreBrowserService.mainDocument.createElement("div");t.classList.add("xterm-decoration"),t.classList.toggle("xterm-decoration-top-layer",((s=e==null?void 0:e.options)==null?void 0:s.layer)==="top"),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,t.style.top=`${(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height}px`,t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let i=e.options.x??0;return i&&i>this._bufferService.cols&&(t.style.display="none"),this._refreshXPosition(e,t),t}_refreshStyle(e){let t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display="none",e.onRenderEmitter.fire(e.element));else{let i=this._decorationElements.get(e);i||(i=this._createElement(e),e.element=i,this._decorationElements.set(e,i),this._container.appendChild(i),e.onDispose(()=>{this._decorationElements.delete(e),i.remove()})),i.style.display=this._altBufferIsActive?"none":"block",this._altBufferIsActive||(i.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,i.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,i.style.top=`${t*this._renderService.dimensions.css.cell.height}px`,i.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(i)}}_refreshXPosition(e,t=e.element){if(!t)return;let i=e.options.x??0;(e.options.anchor||"left")==="right"?t.style.right=i?`${i*this._renderService.dimensions.css.cell.width}px`:"":t.style.left=i?`${i*this._renderService.dimensions.css.cell.width}px`:""}_removeDecoration(e){var t;(t=this._decorationElements.get(e))==null||t.remove(),this._decorationElements.delete(e),e.dispose()}};lp=fi([Re(1,_n),Re(2,as),Re(3,Fo),Re(4,ls)],lp);var c2=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(e){if(e.options.overviewRulerOptions){for(let t of this._zones)if(t.color===e.options.overviewRulerOptions.color&&t.position===e.options.overviewRulerOptions.position){if(this._lineIntersectsZone(t,e.marker.line))return;if(this._lineAdjacentToZone(t,e.marker.line,e.options.overviewRulerOptions.position)){this._addLineToZone(t,e.marker.line);return}}if(this._zonePoolIndex=e.startBufferLine&&t<=e.endBufferLine}_lineAdjacentToZone(e,t,i){return t>=e.startBufferLine-this._linePadding[i||"full"]&&t<=e.endBufferLine+this._linePadding[i||"full"]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}},kr={full:0,left:0,center:0,right:0},Ls={full:0,left:0,center:0,right:0},ho={full:0,left:0,center:0,right:0},ju=class extends ht{constructor(e,t,i,s,a,o,c,h){var f;super(),this._viewportElement=e,this._screenElement=t,this._bufferService=i,this._decorationService=s,this._renderService=a,this._optionsService=o,this._themeService=c,this._coreBrowserService=h,this._colorZoneStore=new c2,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement("canvas"),this._canvas.classList.add("xterm-decoration-overview-ruler"),this._refreshCanvasDimensions(),(f=this._viewportElement.parentElement)==null||f.insertBefore(this._canvas,this._viewportElement),this._register(ni(()=>{var _;return(_=this._canvas)==null?void 0:_.remove()}));let p=this._canvas.getContext("2d");if(p)this._ctx=p;else throw new Error("Ctx cannot be null");this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this._register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0))),this._register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?"none":"block"})),this._register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})),this._register(this._renderService.onRender(()=>{(!this._containerHeight||this._containerHeight!==this._screenElement.clientHeight)&&(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._register(this._optionsService.onSpecificOptionChange("overviewRuler",()=>this._queueRefresh(!0))),this._register(this._themeService.onChangeColors(()=>this._queueRefresh())),this._queueRefresh(!0)}get _width(){var e;return((e=this._optionsService.options.overviewRuler)==null?void 0:e.width)||0}_refreshDrawConstants(){let e=Math.floor((this._canvas.width-1)/3),t=Math.ceil((this._canvas.width-1)/3);Ls.full=this._canvas.width,Ls.left=e,Ls.center=t,Ls.right=e,this._refreshDrawHeightConstants(),ho.full=1,ho.left=1,ho.center=1+Ls.left,ho.right=1+Ls.left+Ls.center}_refreshDrawHeightConstants(){kr.full=Math.round(2*this._coreBrowserService.dpr);let e=this._canvas.height/this._bufferService.buffer.lines.length,t=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowserService.dpr);kr.left=t,kr.center=t,kr.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*kr.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*kr.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*kr.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*kr.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(let t of this._decorationService.decorations)this._colorZoneStore.addDecoration(t);this._ctx.lineWidth=1,this._renderRulerOutline();let e=this._colorZoneStore.zones;for(let t of e)t.position!=="full"&&this._renderColorZone(t);for(let t of e)t.position==="full"&&this._renderColorZone(t);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderRulerOutline(){this._ctx.fillStyle=this._themeService.colors.overviewRulerBorder.css,this._ctx.fillRect(0,0,1,this._canvas.height),this._optionsService.rawOptions.overviewRuler.showTopBorder&&this._ctx.fillRect(1,0,this._canvas.width-1,1),this._optionsService.rawOptions.overviewRuler.showBottomBorder&&this._ctx.fillRect(1,this._canvas.height-1,this._canvas.width-1,this._canvas.height)}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(ho[e.position||"full"],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-kr[e.position||"full"]/2),Ls[e.position||"full"],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+kr[e.position||"full"]))}_queueRefresh(e,t){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=t||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};ju=fi([Re(2,_n),Re(3,Fo),Re(4,ls),Re(5,bn),Re(6,gl),Re(7,as)],ju);var pe;(e=>(e.NUL="\0",e.SOH="",e.STX="",e.ETX="",e.EOT="",e.ENQ="",e.ACK="",e.BEL="\x07",e.BS="\b",e.HT=" ",e.LF=` -`,e.VT="\v",e.FF="\f",e.CR="\r",e.SO="",e.SI="",e.DLE="",e.DC1="",e.DC2="",e.DC3="",e.DC4="",e.NAK="",e.SYN="",e.ETB="",e.CAN="",e.EM="",e.SUB="",e.ESC="\x1B",e.FS="",e.GS="",e.RS="",e.US="",e.SP=" ",e.DEL=""))(pe||(pe={}));var bu;(e=>(e.PAD="€",e.HOP="",e.BPH="‚",e.NBH="ƒ",e.IND="„",e.NEL="…",e.SSA="†",e.ESA="‡",e.HTS="ˆ",e.HTJ="‰",e.VTS="Š",e.PLD="‹",e.PLU="Œ",e.RI="",e.SS2="Ž",e.SS3="",e.DCS="",e.PU1="‘",e.PU2="’",e.STS="“",e.CCH="”",e.MW="•",e.SPA="–",e.EPA="—",e.SOS="˜",e.SGCI="™",e.SCI="š",e.CSI="›",e.ST="œ",e.OSC="",e.PM="ž",e.APC="Ÿ"))(bu||(bu={}));var l0;(e=>e.ST=`${pe.ESC}\\`)(l0||(l0={}));var op=class{constructor(e,t,i,s,a,o){this._textarea=e,this._compositionView=t,this._bufferService=i,this._optionsService=s,this._coreService=a,this._renderService=o,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=""}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent="",this._dataAlreadySent="",this._compositionView.classList.add("active")}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return!1;this._finalizeComposition(!1)}return e.keyCode===229?(this._handleAnyTextareaChanges(),!1):!0}_finalizeComposition(e){if(this._compositionView.classList.remove("active"),this._isComposing=!1,e){let t={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let i;t.start+=this._dataAlreadySent.length,this._isComposing?i=this._textarea.value.substring(t.start,this._compositionPosition.start):i=this._textarea.value.substring(t.start),i.length>0&&this._coreService.triggerDataEvent(i,!0)}},0)}else{this._isSendingComposition=!1;let t=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(t,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,i=t.replace(e,"");this._dataAlreadySent=i,t.length>e.length?this._coreService.triggerDataEvent(i,!0):t.lengththis.updateCompositionElements(!0),0)}}};op=fi([Re(2,_n),Re(3,bn),Re(4,va),Re(5,ls)],op);var Fi=0,qi=0,Wi=0,hi=0,Db={css:"#00000000",rgba:0},Ai;(e=>{function t(a,o,c,h){return h!==void 0?`#${ca(a)}${ca(o)}${ca(c)}${ca(h)}`:`#${ca(a)}${ca(o)}${ca(c)}`}e.toCss=t;function i(a,o,c,h=255){return(a<<24|o<<16|c<<8|h)>>>0}e.toRgba=i;function s(a,o,c,h){return{css:e.toCss(a,o,c,h),rgba:e.toRgba(a,o,c,h)}}e.toColor=s})(Ai||(Ai={}));var ti;(e=>{function t(p,f){if(hi=(f.rgba&255)/255,hi===1)return{css:f.css,rgba:f.rgba};let _=f.rgba>>24&255,x=f.rgba>>16&255,b=f.rgba>>8&255,v=p.rgba>>24&255,S=p.rgba>>16&255,N=p.rgba>>8&255;Fi=v+Math.round((_-v)*hi),qi=S+Math.round((x-S)*hi),Wi=N+Math.round((b-N)*hi);let M=Ai.toCss(Fi,qi,Wi),E=Ai.toRgba(Fi,qi,Wi);return{css:M,rgba:E}}e.blend=t;function i(p){return(p.rgba&255)===255}e.isOpaque=i;function s(p,f,_){let x=vu.ensureContrastRatio(p.rgba,f.rgba,_);if(x)return Ai.toColor(x>>24&255,x>>16&255,x>>8&255)}e.ensureContrastRatio=s;function a(p){let f=(p.rgba|255)>>>0;return[Fi,qi,Wi]=vu.toChannels(f),{css:Ai.toCss(Fi,qi,Wi),rgba:f}}e.opaque=a;function o(p,f){return hi=Math.round(f*255),[Fi,qi,Wi]=vu.toChannels(p.rgba),{css:Ai.toCss(Fi,qi,Wi,hi),rgba:Ai.toRgba(Fi,qi,Wi,hi)}}e.opacity=o;function c(p,f){return hi=p.rgba&255,o(p,hi*f/255)}e.multiplyOpacity=c;function h(p){return[p.rgba>>24&255,p.rgba>>16&255,p.rgba>>8&255]}e.toColorRGB=h})(ti||(ti={}));var ai;(e=>{let t,i;try{let a=document.createElement("canvas");a.width=1,a.height=1;let o=a.getContext("2d",{willReadFrequently:!0});o&&(t=o,t.globalCompositeOperation="copy",i=t.createLinearGradient(0,0,1,1))}catch{}function s(a){if(a.match(/#[\da-f]{3,8}/i))switch(a.length){case 4:return Fi=parseInt(a.slice(1,2).repeat(2),16),qi=parseInt(a.slice(2,3).repeat(2),16),Wi=parseInt(a.slice(3,4).repeat(2),16),Ai.toColor(Fi,qi,Wi);case 5:return Fi=parseInt(a.slice(1,2).repeat(2),16),qi=parseInt(a.slice(2,3).repeat(2),16),Wi=parseInt(a.slice(3,4).repeat(2),16),hi=parseInt(a.slice(4,5).repeat(2),16),Ai.toColor(Fi,qi,Wi,hi);case 7:return{css:a,rgba:(parseInt(a.slice(1),16)<<8|255)>>>0};case 9:return{css:a,rgba:parseInt(a.slice(1),16)>>>0}}let o=a.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(o)return Fi=parseInt(o[1]),qi=parseInt(o[2]),Wi=parseInt(o[3]),hi=Math.round((o[5]===void 0?1:parseFloat(o[5]))*255),Ai.toColor(Fi,qi,Wi,hi);if(!t||!i)throw new Error("css.toColor: Unsupported css format");if(t.fillStyle=i,t.fillStyle=a,typeof t.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(t.fillRect(0,0,1,1),[Fi,qi,Wi,hi]=t.getImageData(0,0,1,1).data,hi!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:Ai.toRgba(Fi,qi,Wi,hi),css:a}}e.toColor=s})(ai||(ai={}));var pn;(e=>{function t(s){return i(s>>16&255,s>>8&255,s&255)}e.relativeLuminance=t;function i(s,a,o){let c=s/255,h=a/255,p=o/255,f=c<=.03928?c/12.92:Math.pow((c+.055)/1.055,2.4),_=h<=.03928?h/12.92:Math.pow((h+.055)/1.055,2.4),x=p<=.03928?p/12.92:Math.pow((p+.055)/1.055,2.4);return f*.2126+_*.7152+x*.0722}e.relativeLuminance2=i})(pn||(pn={}));var vu;(e=>{function t(c,h){if(hi=(h&255)/255,hi===1)return h;let p=h>>24&255,f=h>>16&255,_=h>>8&255,x=c>>24&255,b=c>>16&255,v=c>>8&255;return Fi=x+Math.round((p-x)*hi),qi=b+Math.round((f-b)*hi),Wi=v+Math.round((_-v)*hi),Ai.toRgba(Fi,qi,Wi)}e.blend=t;function i(c,h,p){let f=pn.relativeLuminance(c>>8),_=pn.relativeLuminance(h>>8);if(ts(f,_)>8));if(S>8));return S>M?v:N}return v}let x=a(c,h,p),b=ts(f,pn.relativeLuminance(x>>8));if(b>8));return b>S?x:v}return x}}e.ensureContrastRatio=i;function s(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,N=ts(pn.relativeLuminance2(b,v,S),pn.relativeLuminance2(f,_,x));for(;N0||v>0||S>0);)b-=Math.max(0,Math.ceil(b*.1)),v-=Math.max(0,Math.ceil(v*.1)),S-=Math.max(0,Math.ceil(S*.1)),N=ts(pn.relativeLuminance2(b,v,S),pn.relativeLuminance2(f,_,x));return(b<<24|v<<16|S<<8|255)>>>0}e.reduceLuminance=s;function a(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,N=ts(pn.relativeLuminance2(b,v,S),pn.relativeLuminance2(f,_,x));for(;N>>0}e.increaseLuminance=a;function o(c){return[c>>24&255,c>>16&255,c>>8&255,c&255]}e.toChannels=o})(vu||(vu={}));function ca(e){let t=e.toString(16);return t.length<2?"0"+t:t}function ts(e,t){return e1){let _=this._getJoinedRanges(s,c,o,t,a);for(let x=0;x<_.length;x++)i.push(_[x])}a=f,c=o,h=this._workCell.fg,p=this._workCell.bg}o+=this._workCell.getChars().length||Hs.length}if(this._bufferService.cols-a>1){let f=this._getJoinedRanges(s,c,o,t,a);for(let _=0;_=B,z=G,F=this._workCell;if(b.length>0&&G===b[0][0]&&T){let we=b.shift(),He=this._isCellInSelection(we[0],t);for(L=we[0]+1;L=we[1]),T?(H=!0,F=new u2(this._workCell,e.translateToString(!0,we[0],we[1]),we[1]-we[0]),z=we[1]-1,V=F.getWidth()):B=we[1]}let xe=this._isCellInSelection(G,t),j=i&&G===o,D=$&&G>=f&&G<=_,X=!1;this._decorationService.forEachDecorationAtCell(G,t,void 0,we=>{X=!0});let C=F.getChars()||Hs;if(C===" "&&(F.isUnderline()||F.isOverline())&&(C=" "),ye=V*h-p.get(C,F.isBold(),F.isItalic()),!N)N=this._document.createElement("span");else if(M&&(xe&&ue||!xe&&!ue&&F.bg===I)&&(xe&&ue&&v.selectionForeground||F.fg===A)&&F.extended.ext===q&&D===R&&ye===ne&&!j&&!H&&!X&&T){F.isInvisible()?E+=Hs:E+=C,M++;continue}else M&&(N.textContent=E),N=this._document.createElement("span"),M=0,E="";if(I=F.bg,A=F.fg,q=F.extended.ext,R=D,ne=ye,ue=xe,H&&o>=G&&o<=z&&(o=G),!this._coreService.isCursorHidden&&j&&this._coreService.isCursorInitialized){if(re.push("xterm-cursor"),this._coreBrowserService.isFocused)c&&re.push("xterm-cursor-blink"),re.push(s==="bar"?"xterm-cursor-bar":s==="underline"?"xterm-cursor-underline":"xterm-cursor-block");else if(a)switch(a){case"outline":re.push("xterm-cursor-outline");break;case"block":re.push("xterm-cursor-block");break;case"bar":re.push("xterm-cursor-bar");break;case"underline":re.push("xterm-cursor-underline");break}}if(F.isBold()&&re.push("xterm-bold"),F.isItalic()&&re.push("xterm-italic"),F.isDim()&&re.push("xterm-dim"),F.isInvisible()?E=Hs:E=F.getChars()||Hs,F.isUnderline()&&(re.push(`xterm-underline-${F.extended.underlineStyle}`),E===" "&&(E=" "),!F.isUnderlineColorDefault()))if(F.isUnderlineColorRGB())N.style.textDecorationColor=`rgb(${$o.toColorRGB(F.getUnderlineColor()).join(",")})`;else{let we=F.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&F.isBold()&&we<8&&(we+=8),N.style.textDecorationColor=v.ansi[we].css}F.isOverline()&&(re.push("xterm-overline"),E===" "&&(E=" ")),F.isStrikethrough()&&re.push("xterm-strikethrough"),D&&(N.style.textDecoration="underline");let Z=F.getFgColor(),ae=F.getFgColorMode(),oe=F.getBgColor(),K=F.getBgColorMode(),he=!!F.isInverse();if(he){let we=Z;Z=oe,oe=we;let He=ae;ae=K,K=He}let ge,De,ze=!1;this._decorationService.forEachDecorationAtCell(G,t,void 0,we=>{we.options.layer!=="top"&&ze||(we.backgroundColorRGB&&(K=50331648,oe=we.backgroundColorRGB.rgba>>8&16777215,ge=we.backgroundColorRGB),we.foregroundColorRGB&&(ae=50331648,Z=we.foregroundColorRGB.rgba>>8&16777215,De=we.foregroundColorRGB),ze=we.options.layer==="top")}),!ze&&xe&&(ge=this._coreBrowserService.isFocused?v.selectionBackgroundOpaque:v.selectionInactiveBackgroundOpaque,oe=ge.rgba>>8&16777215,K=50331648,ze=!0,v.selectionForeground&&(ae=50331648,Z=v.selectionForeground.rgba>>8&16777215,De=v.selectionForeground)),ze&&re.push("xterm-decoration-top");let Fe;switch(K){case 16777216:case 33554432:Fe=v.ansi[oe],re.push(`xterm-bg-${oe}`);break;case 50331648:Fe=Ai.toColor(oe>>16,oe>>8&255,oe&255),this._addStyle(N,`background-color:#${Mb((oe>>>0).toString(16),"0",6)}`);break;case 0:default:he?(Fe=v.foreground,re.push("xterm-bg-257")):Fe=v.background}switch(ge||F.isDim()&&(ge=ti.multiplyOpacity(Fe,.5)),ae){case 16777216:case 33554432:F.isBold()&&Z<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(Z+=8),this._applyMinimumContrast(N,Fe,v.ansi[Z],F,ge,void 0)||re.push(`xterm-fg-${Z}`);break;case 50331648:let we=Ai.toColor(Z>>16&255,Z>>8&255,Z&255);this._applyMinimumContrast(N,Fe,we,F,ge,De)||this._addStyle(N,`color:#${Mb(Z.toString(16),"0",6)}`);break;case 0:default:this._applyMinimumContrast(N,Fe,v.foreground,F,ge,De)||he&&re.push("xterm-fg-257")}re.length&&(N.className=re.join(" "),re.length=0),!j&&!H&&!X&&T?M++:N.textContent=E,ye!==this.defaultSpacing&&(N.style.letterSpacing=`${ye}px`),x.push(N),G=z}return N&&M&&(N.textContent=E),x}_applyMinimumContrast(e,t,i,s,a,o){if(this._optionsService.rawOptions.minimumContrastRatio===1||f2(s.getCode()))return!1;let c=this._getContrastCache(s),h;if(!a&&!o&&(h=c.getColor(t.rgba,i.rgba)),h===void 0){let p=this._optionsService.rawOptions.minimumContrastRatio/(s.isDim()?2:1);h=ti.ensureContrastRatio(a||t,o||i,p),c.setColor((a||t).rgba,(o||i).rgba,h??null)}return h?(this._addStyle(e,`color:${h.css}`),!0):!1}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute("style",`${e.getAttribute("style")||""}${t};`)}_isCellInSelection(e,t){let i=this._selectionStart,s=this._selectionEnd;return!i||!s?!1:this._columnSelectMode?i[0]<=s[0]?e>=i[0]&&t>=i[1]&&e=i[1]&&e>=s[0]&&t<=s[1]:t>i[1]&&t=i[0]&&e=i[0]}};cp=fi([Re(1,Fy),Re(2,bn),Re(3,as),Re(4,va),Re(5,Fo),Re(6,gl)],cp);function Mb(e,t,i){for(;e.length0&&(this._flat[s]=c),c}let a=e;t&&(a+="B"),i&&(a+="I");let o=this._holey.get(a);if(o===void 0){let c=0;t&&(c|=1),i&&(c|=2),o=this._measure(e,c),o>0&&this._holey.set(a,o)}return o}_measure(e,t){let i=this._measureElements[t];return i.textContent=e.repeat(32),i.offsetWidth/32}},g2=class{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(e,t,i,s=!1){if(this.selectionStart=t,this.selectionEnd=i,!t||!i||t[0]===i[0]&&t[1]===i[1]){this.clear();return}let a=e.buffers.active.ydisp,o=t[1]-a,c=i[1]-a,h=Math.max(o,0),p=Math.min(c,e.rows-1);if(h>=e.rows||p<0){this.clear();return}this.hasSelection=!0,this.columnSelectMode=s,this.viewportStartRow=o,this.viewportEndRow=c,this.viewportCappedStartRow=h,this.viewportCappedEndRow=p,this.startCol=t[0],this.endCol=i[0]}isCellSelected(e,t,i){return this.hasSelection?(i-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&i>=this.viewportCappedStartRow&&t=this.viewportCappedStartRow&&t>=this.endCol&&i<=this.viewportCappedEndRow:i>this.viewportStartRow&&i=this.startCol&&t=this.startCol):!1}};function x2(){return new g2}var lf="xterm-dom-renderer-owner-",rr="xterm-rows",su="xterm-fg-",Bb="xterm-bg-",fo="xterm-focus",au="xterm-selection",_2=1,up=class extends ht{constructor(e,t,i,s,a,o,c,h,p,f,_,x,b,v){super(),this._terminal=e,this._document=t,this._element=i,this._screenElement=s,this._viewportElement=a,this._helperContainer=o,this._linkifier2=c,this._charSizeService=p,this._optionsService=f,this._bufferService=_,this._coreService=x,this._coreBrowserService=b,this._themeService=v,this._terminalClass=_2++,this._rowElements=[],this._selectionRenderModel=x2(),this.onRequestRedraw=this._register(new ke).event,this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(rr),this._rowContainer.style.lineHeight="normal",this._rowContainer.setAttribute("aria-hidden","true"),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement("div"),this._selectionContainer.classList.add(au),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=p2(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(S=>this._injectCss(S))),this._injectCss(this._themeService.colors),this._rowFactory=h.createInstance(cp,document),this._element.classList.add(lf+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(S=>this._handleLinkHover(S))),this._register(this._linkifier2.onHideLinkUnderline(S=>this._handleLinkLeave(S))),this._register(ni(()=>{this._element.classList.remove(lf+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new m2(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){let e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(let i of this._rowElements)i.style.width=`${this.dimensions.css.canvas.width}px`,i.style.height=`${this.dimensions.css.cell.height}px`,i.style.lineHeight=`${this.dimensions.css.cell.height}px`,i.style.overflow="hidden";this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._dimensionsStyleElement));let t=`${this._terminalSelector} .${rr} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=t,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(e){this._themeStyleElement||(this._themeStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._themeStyleElement));let t=`${this._terminalSelector} .${rr} { pointer-events: none; color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;t+=`${this._terminalSelector} .${rr} .xterm-dim { color: ${ti.multiplyOpacity(e.foreground,.5).css};}`,t+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;let i=`blink_underline_${this._terminalClass}`,s=`blink_bar_${this._terminalClass}`,a=`blink_block_${this._terminalClass}`;t+=`@keyframes ${i} { 50% { border-bottom-style: hidden; }}`,t+=`@keyframes ${s} { 50% { box-shadow: none; }}`,t+=`@keyframes ${a} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${rr}.${fo} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${rr}.${fo} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${s} 1s step-end infinite;}${this._terminalSelector} .${rr}.${fo} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${a} 1s step-end infinite;}${this._terminalSelector} .${rr} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${rr} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${rr} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${rr} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${rr} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${au} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${au} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${au} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[o,c]of e.ansi.entries())t+=`${this._terminalSelector} .${su}${o} { color: ${c.css}; }${this._terminalSelector} .${su}${o}.xterm-dim { color: ${ti.multiplyOpacity(c,.5).css}; }${this._terminalSelector} .${Bb}${o} { background-color: ${c.css}; }`;t+=`${this._terminalSelector} .${su}257 { color: ${ti.opaque(e.background).css}; }${this._terminalSelector} .${su}257.xterm-dim { color: ${ti.multiplyOpacity(ti.opaque(e.background),.5).css}; }${this._terminalSelector} .${Bb}257 { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){let e=this.dimensions.css.cell.width-this._widthCache.get("W",!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let i=this._rowElements.length;i<=t;i++){let s=this._document.createElement("div");this._rowContainer.appendChild(s),this._rowElements.push(s)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(fo),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(fo),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,i){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,i),this.renderRows(0,this._bufferService.rows-1),!e||!t||(this._selectionRenderModel.update(this._terminal,e,t,i),!this._selectionRenderModel.hasSelection))return;let s=this._selectionRenderModel.viewportStartRow,a=this._selectionRenderModel.viewportEndRow,o=this._selectionRenderModel.viewportCappedStartRow,c=this._selectionRenderModel.viewportCappedEndRow,h=this._document.createDocumentFragment();if(i){let p=e[0]>t[0];h.appendChild(this._createSelectionElement(o,p?t[0]:e[0],p?e[0]:t[0],c-o+1))}else{let p=s===o?e[0]:0,f=o===a?t[0]:this._bufferService.cols;h.appendChild(this._createSelectionElement(o,p,f));let _=c-o-1;if(h.appendChild(this._createSelectionElement(o+1,0,this._bufferService.cols,_)),o!==c){let x=a===c?t[0]:this._bufferService.cols;h.appendChild(this._createSelectionElement(c,0,x))}}this._selectionContainer.appendChild(h)}_createSelectionElement(e,t,i,s=1){let a=this._document.createElement("div"),o=t*this.dimensions.css.cell.width,c=this.dimensions.css.cell.width*(i-t);return o+c>this.dimensions.css.canvas.width&&(c=this.dimensions.css.canvas.width-o),a.style.height=`${s*this.dimensions.css.cell.height}px`,a.style.top=`${e*this.dimensions.css.cell.height}px`,a.style.left=`${o}px`,a.style.width=`${c}px`,a}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(let e of this._rowElements)e.replaceChildren()}renderRows(e,t){let i=this._bufferService.buffer,s=i.ybase+i.y,a=Math.min(i.x,this._bufferService.cols-1),o=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,c=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,h=this._optionsService.rawOptions.cursorInactiveStyle;for(let p=e;p<=t;p++){let f=p+i.ydisp,_=this._rowElements[p],x=i.lines.get(f);if(!_||!x)break;_.replaceChildren(...this._rowFactory.createRow(x,f,f===s,c,h,a,o,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${lf}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,i,s,a,o){i<0&&(e=0),s<0&&(t=0);let c=this._bufferService.rows-1;i=Math.max(Math.min(i,c),0),s=Math.max(Math.min(s,c),0),a=Math.min(a,this._bufferService.cols);let h=this._bufferService.buffer,p=h.ybase+h.y,f=Math.min(h.x,a-1),_=this._optionsService.rawOptions.cursorBlink,x=this._optionsService.rawOptions.cursorStyle,b=this._optionsService.rawOptions.cursorInactiveStyle;for(let v=i;v<=s;++v){let S=v+h.ydisp,N=this._rowElements[v],M=h.lines.get(S);if(!N||!M)break;N.replaceChildren(...this._rowFactory.createRow(M,S,S===p,x,b,f,_,this.dimensions.css.cell.width,this._widthCache,o?v===i?e:0:-1,o?(v===s?t:a)-1:-1))}}};up=fi([Re(7,qp),Re(8,Hu),Re(9,bn),Re(10,_n),Re(11,va),Re(12,as),Re(13,gl)],up);var hp=class extends ht{constructor(e,t,i){super(),this._optionsService=i,this.width=0,this.height=0,this._onCharSizeChange=this._register(new ke),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new v2(this._optionsService))}catch{this._measureStrategy=this._register(new b2(e,t,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange(["fontFamily","fontSize"],()=>this.measure()))}get hasValidSize(){return this.width>0&&this.height>0}measure(){let e=this._measureStrategy.measure();(e.width!==this.width||e.height!==this.height)&&(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};hp=fi([Re(2,bn)],hp);var o0=class extends ht{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(e,t){e!==void 0&&e>0&&t!==void 0&&t>0&&(this._result.width=e,this._result.height=t)}},b2=class extends o0{constructor(e,t,i){super(),this._document=e,this._parentElement=t,this._optionsService=i,this._measureElement=this._document.createElement("span"),this._measureElement.classList.add("xterm-char-measure-element"),this._measureElement.textContent="W".repeat(32),this._measureElement.setAttribute("aria-hidden","true"),this._measureElement.style.whiteSpace="pre",this._measureElement.style.fontKerning="none",this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}},v2=class extends o0{constructor(e){super(),this._optionsService=e,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext("2d");let t=this._ctx.measureText("W");if(!("width"in t&&"fontBoundingBoxAscent"in t&&"fontBoundingBoxDescent"in t))throw new Error("Required font metrics not supported")}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;let e=this._ctx.measureText("W");return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}},y2=class extends ht{constructor(e,t,i){super(),this._textarea=e,this._window=t,this.mainDocument=i,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new S2(this._window)),this._onDprChange=this._register(new ke),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new ke),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(s=>this._screenDprMonitor.setWindow(s))),this._register(sn.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(Ke(this._textarea,"focus",()=>this._isFocused=!0)),this._register(Ke(this._textarea,"blur",()=>this._isFocused=!1))}get window(){return this._window}set window(e){this._window!==e&&(this._window=e,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask(()=>this._cachedIsFocused=void 0)),this._cachedIsFocused}},S2=class extends ht{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new fl),this._onDprChange=this._register(new ke),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(ni(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=Ke(this._parentWindow,"resize",()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){var e;this._outerListener&&((e=this._resolutionMediaMatchList)==null||e.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){!this._resolutionMediaMatchList||!this._outerListener||(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}},w2=class extends ht{constructor(){super(),this.linkProviders=[],this._register(ni(()=>this.linkProviders.length=0))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{let t=this.linkProviders.indexOf(e);t!==-1&&this.linkProviders.splice(t,1)}}}};function Qp(e,t,i){let s=i.getBoundingClientRect(),a=e.getComputedStyle(i),o=parseInt(a.getPropertyValue("padding-left")),c=parseInt(a.getPropertyValue("padding-top"));return[t.clientX-s.left-o,t.clientY-s.top-c]}function C2(e,t,i,s,a,o,c,h,p){if(!o)return;let f=Qp(e,t,i);if(f)return f[0]=Math.ceil((f[0]+(p?c/2:0))/c),f[1]=Math.ceil(f[1]/h),f[0]=Math.min(Math.max(f[0],1),s+(p?1:0)),f[1]=Math.min(Math.max(f[1],1),a),f}var dp=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,i,s,a){return C2(window,e,t,i,s,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,a)}getMouseReportCoords(e,t){let i=Qp(window,e,t);if(this._charSizeService.hasValidSize)return i[0]=Math.min(Math.max(i[0],0),this._renderService.dimensions.css.canvas.width-1),i[1]=Math.min(Math.max(i[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(i[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(i[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(i[0]),y:Math.floor(i[1])}}};dp=fi([Re(0,ls),Re(1,Hu)],dp);var k2=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this._refreshCallbacks=[]}dispose(){this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}addRefreshCallback(e){return this._refreshCallbacks.push(e),this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh())),this._animationFrame}refresh(e,t,i){this._rowCount=i,e=e!==void 0?e:0,t=t!==void 0?t:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,e):e,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,t):t,!this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0){this._runRefreshCallbacks();return}let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(let e of this._refreshCallbacks)e(0);this._refreshCallbacks=[]}},c0={};LC(c0,{getSafariVersion:()=>N2,isChromeOS:()=>f0,isFirefox:()=>u0,isIpad:()=>j2,isIphone:()=>T2,isLegacyEdge:()=>E2,isLinux:()=>Jp,isMac:()=>Au,isNode:()=>Uu,isSafari:()=>h0,isWindows:()=>d0});var Uu=typeof process<"u"&&"title"in process,qo=Uu?"node":navigator.userAgent,Wo=Uu?"node":navigator.platform,u0=qo.includes("Firefox"),E2=qo.includes("Edge"),h0=/^((?!chrome|android).)*safari/i.test(qo);function N2(){if(!h0)return 0;let e=qo.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var Au=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(Wo),j2=Wo==="iPad",T2=Wo==="iPhone",d0=["Windows","Win16","Win32","WinCE"].includes(Wo),Jp=Wo.indexOf("Linux")>=0,f0=/\bCrOS\b/.test(qo),p0=class{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._ia){s-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(s-t))}ms`),this._start();return}s=a}this.clear()}},A2=class extends p0{_requestCallback(e){return setTimeout(()=>e(this._createDeadline(16)))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=performance.now()+e;return{timeRemaining:()=>Math.max(0,t-performance.now())}}},R2=class extends p0{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},Ru=!Uu&&"requestIdleCallback"in window?R2:A2,D2=class{constructor(){this._queue=new Ru}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},fp=class extends ht{constructor(e,t,i,s,a,o,c,h,p){super(),this._rowCount=e,this._optionsService=i,this._charSizeService=s,this._coreService=a,this._coreBrowserService=h,this._renderer=this._register(new fl),this._pausedResizeTask=new D2,this._observerDisposable=this._register(new fl),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this._register(new ke),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new ke),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new ke),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new ke),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new k2((f,_)=>this._renderRows(f,_),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new M2(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(ni(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(c.onResize(()=>this._fullRefresh())),this._register(c.buffers.onBufferActivate(()=>{var f;return(f=this._renderer.value)==null?void 0:f.clear()})),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(o.onDecorationRegistered(()=>this._fullRefresh())),this._register(o.onDecorationRemoved(()=>this._fullRefresh())),this._register(this._optionsService.onMultipleOptionChange(["customGlyphs","drawBoldTextInBrightColors","letterSpacing","lineHeight","fontFamily","fontSize","fontWeight","fontWeightBold","minimumContrastRatio","rescaleOverlappingGlyphs"],()=>{this.clear(),this.handleResize(c.cols,c.rows),this._fullRefresh()})),this._register(this._optionsService.onMultipleOptionChange(["cursorBlink","cursorStyle"],()=>this.refreshRows(c.buffer.y,c.buffer.y,!0))),this._register(p.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,t),this._register(this._coreBrowserService.onWindowChange(f=>this._registerIntersectionObserver(f,t)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(e,t){if("IntersectionObserver"in e){let i=new e.IntersectionObserver(s=>this._handleIntersectionChange(s[s.length-1]),{threshold:0});i.observe(t),this._observerDisposable.value=ni(()=>i.disconnect())}}_handleIntersectionChange(e){this._isPaused=e.isIntersecting===void 0?e.intersectionRatio===0:!e.isIntersecting,!this._isPaused&&!this._charSizeService.hasValidSize&&this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,t,i=!1){if(this._isPaused){this._needsFullRefresh=!0;return}if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}let s=this._syncOutputHandler.flush();s&&(e=Math.min(e,s.start),t=Math.max(t,s.end)),i||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount)}_renderRows(e,t){if(this._renderer.value){if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),this._needsSelectionRefresh=!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0}}resize(e,t){this._rowCount=t,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw(t=>this.refreshRows(t.start,t.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){var e,t;this._renderer.value&&((t=(e=this._renderer.value).clearTextureAtlas)==null||t.call(e),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>{var i;return(i=this._renderer.value)==null?void 0:i.handleResize(e,t)}):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){var e;(e=this._renderer.value)==null||e.handleCharSizeChanged()}handleBlur(){var e;(e=this._renderer.value)==null||e.handleBlur()}handleFocus(){var e;(e=this._renderer.value)==null||e.handleFocus()}handleSelectionChanged(e,t,i){var s;this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=i,(s=this._renderer.value)==null||s.handleSelectionChanged(e,t,i)}handleCursorMove(){var e;(e=this._renderer.value)==null||e.handleCursorMove()}clear(){var e;(e=this._renderer.value)==null||e.clear()}};fp=fi([Re(2,bn),Re(3,Hu),Re(4,va),Re(5,Fo),Re(6,_n),Re(7,as),Re(8,gl)],fp);var M2=class{constructor(e,t,i){this._coreBrowserService=e,this._coreService=t,this._onTimeout=i,this._start=0,this._end=0,this._isBuffering=!1}bufferRows(e,t){this._isBuffering?(this._start=Math.min(this._start,e),this._end=Math.max(this._end,t)):(this._start=e,this._end=t,this._isBuffering=!0),this._timeout===void 0&&(this._timeout=this._coreBrowserService.window.setTimeout(()=>{this._timeout=void 0,this._coreService.decPrivateModes.synchronizedOutput=!1,this._onTimeout()},1e3))}flush(){if(this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0),!this._isBuffering)return;let e={start:this._start,end:this._end};return this._isBuffering=!1,e}dispose(){this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0)}};function B2(e,t,i,s){let a=i.buffer.x,o=i.buffer.y;if(!i.buffer.hasScrollback)return z2(a,o,e,t,i,s)+$u(o,t,i,s)+P2(a,o,e,t,i,s);let c;if(o===t)return c=a>e?"D":"C",Oo(Math.abs(a-e),Lo(c,s));c=o>t?"D":"C";let h=Math.abs(o-t),p=O2(o>t?e:a,i)+(h-1)*i.cols+1+L2(o>t?a:e);return Oo(p,Lo(c,s))}function L2(e,t){return e-1}function O2(e,t){return t.cols-e}function z2(e,t,i,s,a,o){return $u(t,s,a,o).length===0?"":Oo(g0(e,t,e,t-_a(t,a),!1,a).length,Lo("D",o))}function $u(e,t,i,s){let a=e-_a(e,i),o=t-_a(t,i),c=Math.abs(a-o)-I2(e,t,i);return Oo(c,Lo(m0(e,t),s))}function P2(e,t,i,s,a,o){let c;$u(t,s,a,o).length>0?c=s-_a(s,a):c=t;let h=s,p=H2(e,t,i,s,a,o);return Oo(g0(e,c,i,h,p==="C",a).length,Lo(p,o))}function I2(e,t,i){var c;let s=0,a=e-_a(e,i),o=t-_a(t,i);for(let h=0;h=0&&e0?c=s-_a(s,a):c=t,e=i&&ct?"A":"B"}function g0(e,t,i,s,a,o){let c=e,h=t,p="";for(;(c!==i||h!==s)&&h>=0&&ho.cols-1?(p+=o.buffer.translateBufferLineToString(h,!1,e,c),c=0,e=0,h++):!a&&c<0&&(p+=o.buffer.translateBufferLineToString(h,!1,0,e+1),c=o.cols-1,e=c,h--);return p+o.buffer.translateBufferLineToString(h,!1,e,c)}function Lo(e,t){let i=t?"O":"[";return pe.ESC+i+e}function Oo(e,t){e=Math.floor(e);let i="";for(let s=0;sthis._bufferService.cols?e%this._bufferService.cols===0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){let e=this.selectionStart,t=this.selectionEnd;return!e||!t?!1:e[1]>t[1]||e[1]===t[1]&&e[0]>t[0]}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}};function Lb(e,t){if(e.start.y>e.end.y)throw new Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}var of=50,$2=15,F2=50,q2=500,W2=" ",G2=new RegExp(W2,"g"),pp=class extends ht{constructor(e,t,i,s,a,o,c,h,p){super(),this._element=e,this._screenElement=t,this._linkifier=i,this._bufferService=s,this._coreService=a,this._mouseService=o,this._optionsService=c,this._renderService=h,this._coreBrowserService=p,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new or,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new ke),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new ke),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new ke),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new ke),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=f=>this._handleMouseMove(f),this._mouseUpListener=f=>this._handleMouseUp(f),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(f=>this._handleTrim(f)),this._register(this._bufferService.buffers.onBufferActivate(f=>this._handleBufferActivate(f))),this.enable(),this._model=new U2(this._bufferService),this._activeSelectionMode=0,this._register(ni(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(f=>{f.rowsChanged&&this.clearSelection()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!e||!t?!1:e[0]!==t[0]||e[1]!==t[1]}get selectionText(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return"";let i=this._bufferService.buffer,s=[];if(this._activeSelectionMode===3){if(e[0]===t[0])return"";let a=e[0]a.replace(G2," ")).join(d0?`\r +`))}},ck=class extends Error{constructor(e,t){super(e),this.name="ListenerLeakError",this.stack=t}},uk=class extends Error{constructor(e,t){super(e),this.name="ListenerRefusalError",this.stack=t}},hk=0,nf=class{constructor(e){this.value=e,this.id=hk++}},dk=2,fk,Ce=class{constructor(t){var i,s,a,o;this._size=0,this._options=t,this._leakageMon=(i=this._options)!=null&&i.leakWarningThreshold?new lk((t==null?void 0:t.onListenerError)??gu,((s=this._options)==null?void 0:s.leakWarningThreshold)??ak):void 0,this._perfMon=(a=this._options)!=null&&a._profName?new sk(this._options._profName):void 0,this._deliveryQueue=(o=this._options)==null?void 0:o.deliveryQueue}dispose(){var t,i,s,a;this._disposed||(this._disposed=!0,((t=this._deliveryQueue)==null?void 0:t.current)===this&&this._deliveryQueue.reset(),this._listeners&&(this._listeners=void 0,this._size=0),(s=(i=this._options)==null?void 0:i.onDidRemoveLastListener)==null||s.call(i),(a=this._leakageMon)==null||a.dispose())}get event(){return this._event??(this._event=(t,i,s)=>{var h,p,f,_,x;if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let b=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(b);let v=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],S=new uk(`${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 nf(t),o;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(a.stack=ok.create(),o=this._leakageMon.check(a.stack,this._size+1)),this._listeners?this._listeners instanceof nf?(this._deliveryQueue??(this._deliveryQueue=new pk),this._listeners=[this._listeners,a]):this._listeners.push(a):((f=(p=this._options)==null?void 0:p.onWillAddFirstListener)==null||f.call(p,this),this._listeners=a,(x=(_=this._options)==null?void 0:_.onDidAddFirstListener)==null||x.call(_,this)),this._size++;let c=ti(()=>{o==null||o(),this._removeListener(a)});return s instanceof $s?s.add(c):Array.isArray(s)&&s.push(c),c}),this._event}_removeListener(t){var o,c,h,p;if((c=(o=this._options)==null?void 0:o.onWillRemoveListener)==null||c.call(o,this),!this._listeners)return;if(this._size===1){this._listeners=void 0,(p=(h=this._options)==null?void 0:h.onDidRemoveLastListener)==null||p.call(h,this),this._size=0;return}let i=this._listeners,s=i.indexOf(t);if(s===-1)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),new Error("Attempted to dispose unknown listener");this._size--,i[s]=void 0;let a=this._deliveryQueue.current===this;if(this._size*dk<=i.length){let f=0;for(let _=0;_0}},pk=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,i){this.i=0,this.end=i,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},Qf=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new Ce,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new Ce,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(t){return this.mapWindowIdToZoomLevel.get(this.getWindowId(t))??0}setZoomLevel(t,i){if(this.getZoomLevel(i)===t)return;let s=this.getWindowId(i);this.mapWindowIdToZoomLevel.set(s,t),this._onDidChangeZoomLevel.fire(s)}getZoomFactor(t){return this.mapWindowIdToZoomFactor.get(this.getWindowId(t))??1}setZoomFactor(t,i){this.mapWindowIdToZoomFactor.set(this.getWindowId(i),t)}setFullscreen(t,i){if(this.isFullscreen(i)===t)return;let s=this.getWindowId(i);this.mapWindowIdToFullScreen.set(s,t),this._onDidChangeFullscreen.fire(s)}isFullscreen(t){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(t))}getWindowId(t){return t.vscodeWindowId}};Qf.INSTANCE=new Qf;var Gp=Qf;function mk(e,t,i){typeof t=="string"&&(t=e.matchMedia(t)),t.addEventListener("change",i)}Gp.INSTANCE.onDidChangeZoomLevel;function gk(e){return Gp.INSTANCE.getZoomFactor(e)}Gp.INSTANCE.onDidChangeFullscreen;var xl=typeof navigator=="object"?navigator.userAgent:"",Jf=xl.indexOf("Firefox")>=0,xk=xl.indexOf("AppleWebKit")>=0,Yp=xl.indexOf("Chrome")>=0,_k=!Yp&&xl.indexOf("Safari")>=0;xl.indexOf("Electron/")>=0;xl.indexOf("Android")>=0;var rf=!1;if(typeof as.matchMedia=="function"){let e=as.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)"),t=as.matchMedia("(display-mode: fullscreen)");rf=e.matches,mk(as,e,({matches:i})=>{rf&&t.matches||(rf=i)})}var ol="en",ep=!1,tp=!1,xu=!1,Jy=!1,iu,_u=ol,_b=ol,bk,xr,ga=globalThis,rn,Ty;typeof ga.vscode<"u"&&typeof ga.vscode.process<"u"?rn=ga.vscode.process:typeof process<"u"&&typeof((Ty=process==null?void 0:process.versions)==null?void 0:Ty.node)=="string"&&(rn=process);var Ay,vk=typeof((Ay=rn==null?void 0:rn.versions)==null?void 0:Ay.electron)=="string",yk=vk&&(rn==null?void 0:rn.type)==="renderer",Ry;if(typeof rn=="object"){ep=rn.platform==="win32",tp=rn.platform==="darwin",xu=rn.platform==="linux",xu&&rn.env.SNAP&&rn.env.SNAP_REVISION,rn.env.CI||rn.env.BUILD_ARTIFACTSTAGINGDIRECTORY,iu=ol,_u=ol;let e=rn.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);iu=t.userLocale,_b=t.osLocale,_u=t.resolvedLanguage||ol,bk=(Ry=t.languagePack)==null?void 0:Ry.translationsConfigFile}catch{}Jy=!0}else typeof navigator=="object"&&!yk?(xr=navigator.userAgent,ep=xr.indexOf("Windows")>=0,tp=xr.indexOf("Macintosh")>=0,(xr.indexOf("Macintosh")>=0||xr.indexOf("iPad")>=0||xr.indexOf("iPhone")>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0,xu=xr.indexOf("Linux")>=0,(xr==null?void 0:xr.indexOf("Mobi"))>=0,_u=globalThis._VSCODE_NLS_LANGUAGE||ol,iu=navigator.language.toLowerCase(),_b=iu):console.error("Unable to resolve platform.");var e0=ep,Dr=tp,Sk=xu,bb=Jy,Mr=xr,Ls=_u,wk;(e=>{function t(){return Ls}e.value=t;function i(){return Ls.length===2?Ls==="en":Ls.length>=3?Ls[0]==="e"&&Ls[1]==="n"&&Ls[2]==="-":!1}e.isDefaultVariant=i;function s(){return Ls==="en"}e.isDefault=s})(wk||(wk={}));var Ck=typeof ga.postMessage=="function"&&!ga.importScripts;(()=>{if(Ck){let e=[];ga.addEventListener("message",i=>{if(i.data&&i.data.vscodeScheduleAsyncWork)for(let s=0,a=e.length;s{let s=++t;e.push({id:s,callback:i}),ga.postMessage({vscodeScheduleAsyncWork:s},"*")}}return e=>setTimeout(e)})();var kk=!!(Mr&&Mr.indexOf("Chrome")>=0);Mr&&Mr.indexOf("Firefox")>=0;!kk&&Mr&&Mr.indexOf("Safari")>=0;Mr&&Mr.indexOf("Edg/")>=0;Mr&&Mr.indexOf("Android")>=0;var tl=typeof navigator=="object"?navigator:{};bb||document.queryCommandSupported&&document.queryCommandSupported("copy")||tl&&tl.clipboard&&tl.clipboard.writeText,bb||tl&&tl.clipboard&&tl.clipboard.readText;var Vp=class{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e}keyCodeToStr(e){return this._keyCodeToStr[e]}strToKeyCode(e){return this._strToKeyCode[e.toLowerCase()]||0}},sf=new Vp,vb=new Vp,yb=new Vp,Ek=new Array(230),t0;(e=>{function t(h){return sf.keyCodeToStr(h)}e.toString=t;function i(h){return sf.strToKeyCode(h)}e.fromString=i;function s(h){return vb.keyCodeToStr(h)}e.toUserSettingsUS=s;function a(h){return yb.keyCodeToStr(h)}e.toUserSettingsGeneral=a;function o(h){return vb.strToKeyCode(h)||yb.strToKeyCode(h)}e.fromUserSettings=o;function c(h){if(h>=98&&h<=113)return null;switch(h){case 16:return"Up";case 18:return"Down";case 15:return"Left";case 17:return"Right"}return sf.keyCodeToStr(h)}e.toElectronAccelerator=c})(t0||(t0={}));var Nk=class i0{constructor(t,i,s,a,o){this.ctrlKey=t,this.shiftKey=i,this.altKey=s,this.metaKey=a,this.keyCode=o}equals(t){return t instanceof i0&&this.ctrlKey===t.ctrlKey&&this.shiftKey===t.shiftKey&&this.altKey===t.altKey&&this.metaKey===t.metaKey&&this.keyCode===t.keyCode}getHashCode(){let t=this.ctrlKey?"1":"0",i=this.shiftKey?"1":"0",s=this.altKey?"1":"0",a=this.metaKey?"1":"0";return`K${t}${i}${s}${a}${this.keyCode}`}isModifierKey(){return this.keyCode===0||this.keyCode===5||this.keyCode===57||this.keyCode===6||this.keyCode===4}toKeybinding(){return new jk([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},jk=class{constructor(e){if(e.length===0)throw JC("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 zk?!0:!i||typeof i!="object"?!1:typeof i.isCancellationRequested=="boolean"&&typeof i.onCancellationRequested=="function"}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:sn.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:n0})})(Ok||(Ok={}));var zk=class{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?n0:(this._emitter||(this._emitter=new Ce),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}},Kp=class{constructor(e,t){this._isDisposed=!1,this._token=-1,typeof e=="function"&&typeof t=="number"&&this.setIfNotSet(e,t)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._token!==-1&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(e,t){if(this._isDisposed)throw new Yf("Calling 'cancelAndSet' on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new Yf("Calling 'setIfNotSet' on a disposed TimeoutTimer");this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},Pk=class{constructor(){this.disposable=void 0,this.isDisposed=!1}cancel(){var e;(e=this.disposable)==null||e.dispose(),this.disposable=void 0}cancelAndSet(e,t,i=globalThis){if(this.isDisposed)throw new Yf("Calling 'cancelAndSet' on a disposed IntervalTimer");this.cancel();let s=i.setInterval(()=>{e()},t);this.disposable=ti(()=>{i.clearInterval(s),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}},Ik;(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})(Ik||(Ik={}));var kb=class ar{static fromArray(t){return new ar(i=>{i.emitMany(t)})}static fromPromise(t){return new ar(async i=>{i.emitMany(await t)})}static fromPromises(t){return new ar(async i=>{await Promise.all(t.map(async s=>i.emitOne(await s)))})}static merge(t){return new ar(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 ar(async s=>{for await(let a of t)s.emitOne(i(a))})}map(t){return ar.map(this,t)}static filter(t,i){return new ar(async s=>{for await(let a of t)i(a)&&s.emitOne(a)})}filter(t){return ar.filter(this,t)}static coalesce(t){return ar.filter(t,i=>!!i)}coalesce(){return ar.coalesce(this)}static async toPromise(t){let i=[];for await(let s of t)i.push(s);return i}toPromise(){return ar.toPromise(this)}emitOne(t){this._state===0&&(this._results.push(t),this._onStateChanged.fire())}emitMany(t){this._state===0&&(this._results=this._results.concat(t),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(t){this._state===0&&(this._state=2,this._error=t,this._onStateChanged.fire())}};kb.EMPTY=kb.fromArray([]);var{getWindow:Ar,getWindowId:Hk,onDidRegisterWindow:Uk}=(function(){let e=new Map,t={window:as,disposables:new $s};e.set(as.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 $s,p={window:c,disposables:h.add(new $s)};return e.set(c.vscodeWindowId,p),h.add(ti(()=>{e.delete(c.vscodeWindowId),s.fire(c)})),h.add(Xe(c,Ui.BEFORE_UNLOAD,()=>{a.fire(c)})),i.fire(p),h},getWindows(){return e.values()},getWindowsCount(){return e.size},getWindowId(c){return c.vscodeWindowId},hasWindow(c){return e.has(c)},getWindowById:o,getWindow(c){var f;let h=c;if((f=h==null?void 0:h.ownerDocument)!=null&&f.defaultView)return h.ownerDocument.defaultView.window;let p=c;return p!=null&&p.view?p.view.window:as},getDocument(c){return Ar(c).document}}})(),$k=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 $k(e,t,i,s)}var Eb=function(e,t,i,s){return Xe(e,t,i,s)},Xp,Fk=class extends Pk{constructor(e){super(),this.defaultTarget=e&&Ar(e)}cancelAndSet(e,t,i){return super.cancelAndSet(e,t,i??this.defaultTarget)}},Nb=class{constructor(e,t=0){this._runner=e,this.priority=t,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(e){gu(e)}}static sort(e,t){return t.priority-e.priority}};(function(){let e=new Map,t=new Map,i=new Map,s=new Map,a=o=>{i.set(o,!1);let c=e.get(o)??[];for(t.set(o,c),e.set(o,[]),s.set(o,!0);c.length>0;)c.sort(Nb.sort),c.shift().execute();s.set(o,!1)};Xp=(o,c,h=0)=>{let p=Hk(o),f=new Nb(c,h),_=e.get(p);return _||(_=[],e.set(p,_)),_.push(f),i.get(p)||(i.set(p,!0),o.requestAnimationFrame(()=>a(p))),f}})();function qk(e){let t=e.getBoundingClientRect(),i=Ar(e);return{left:t.left+i.scrollX,top:t.top+i.scrollY,width:t.width,height:t.height}}var Ui={CLICK:"click",MOUSE_DOWN:"mousedown",MOUSE_OVER:"mouseover",MOUSE_LEAVE:"mouseleave",MOUSE_WHEEL:"wheel",POINTER_UP:"pointerup",POINTER_DOWN:"pointerdown",POINTER_MOVE:"pointermove",KEY_DOWN:"keydown",KEY_UP:"keyup",BEFORE_UNLOAD:"beforeunload",CHANGE:"change",FOCUS:"focus",BLUR:"blur",INPUT:"input"},Wk=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=An(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=An(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=An(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=An(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=An(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=An(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=An(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=An(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=An(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=An(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=An(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=An(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=An(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=An(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 An(e){return typeof e=="number"?`${e}px`:e}function Ao(e){return new Wk(e)}var r0=class{constructor(){this._hooks=new $s,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(e,t){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let i=this._onStopCallback;this._onStopCallback=null,e&&i&&i(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,i,s,a){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=s,this._onStopCallback=a;let o=e;try{e.setPointerCapture(t),this._hooks.add(ti(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{o=Ar(e)}this._hooks.add(Xe(o,Ui.POINTER_MOVE,c=>{if(c.buttons!==i){this.stopMonitoring(!0);return}c.preventDefault(),this._pointerMoveCallback(c)})),this._hooks.add(Xe(o,Ui.POINTER_UP,c=>this.stopMonitoring(!0)))}};function Gk(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 jr;(e=>(e.Tap="-xterm-gesturetap",e.Change="-xterm-gesturechange",e.Start="-xterm-gesturestart",e.End="-xterm-gesturesend",e.Contextmenu="-xterm-gesturecontextmenu"))(jr||(jr={}));var wo=class on extends ut{constructor(){super(),this.dispatched=!1,this.targets=new xb,this.ignoreTargets=new xb,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(sn.runAndSubscribe(Uk,({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:as,disposables:this._store}))}static addTarget(t){if(!on.isTouchDevice())return ut.None;on.INSTANCE||(on.INSTANCE=new on);let i=on.INSTANCE.targets.push(t);return ti(i)}static ignoreTarget(t){if(!on.isTouchDevice())return ut.None;on.INSTANCE||(on.INSTANCE=new on);let i=on.INSTANCE.ignoreTargets.push(t);return ti(i)}static isTouchDevice(){return"ontouchstart"in as||navigator.maxTouchPoints>0}dispose(){this.handle&&(this.handle.dispose(),this.handle=null),super.dispose()}onTouchStart(t){let i=Date.now();this.handle&&(this.handle.dispose(),this.handle=null);for(let s=0,a=t.targetTouches.length;s=on.HOLD_DELAY&&Math.abs(p.initialPageX-qn(p.rollingPageX))<30&&Math.abs(p.initialPageY-qn(p.rollingPageY))<30){let _=this.newGestureEvent(jr.Contextmenu,p.initialTarget);_.pageX=qn(p.rollingPageX),_.pageY=qn(p.rollingPageY),this.dispatchEvent(_)}else if(a===1){let _=qn(p.rollingPageX),x=qn(p.rollingPageY),b=qn(p.rollingTimestamps)-p.rollingTimestamps[0],v=_-p.rollingPageX[0],S=x-p.rollingPageY[0],N=[...this.targets].filter(B=>p.initialTarget instanceof Node&&B.contains(p.initialTarget));this.inertia(t,N,s,Math.abs(v)/b,v>0?1:-1,_,Math.abs(S)/b,S>0?1:-1,x)}this.dispatchEvent(this.newGestureEvent(jr.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===jr.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===jr.Change||t.type===jr.Contextmenu)&&(this._lastSetTapCountTime=0);if(t.initialTarget instanceof Node){for(let s of this.ignoreTargets)if(s.contains(t.initialTarget))return;let i=[];for(let s of this.targets)if(s.contains(t.initialTarget)){let a=0,o=t.initialTarget;for(;o&&o!==s;)a++,o=o.parentElement;i.push([a,s])}i.sort((s,a)=>s[0]-a[0]);for(let[s,a]of i)a.dispatchEvent(t),this.dispatched=!0}}inertia(t,i,s,a,o,c,h,p,f){this.handle=Xp(t,()=>{let _=Date.now(),x=_-s,b=0,v=0,S=!0;a+=on.SCROLL_FRICTION*x,h+=on.SCROLL_FRICTION*x,a>0&&(S=!1,b=o*a*x),h>0&&(S=!1,v=p*h*x);let N=this.newGestureEvent(jr.Change);N.translationX=b,N.translationY=v,i.forEach(B=>B.dispatchEvent(N)),S||this.inertia(t,i,_,a,o,c+b,h,p,f+v)})}onTouchMove(t){let i=Date.now();for(let s=0,a=t.changedTouches.length;s3&&(c.rollingPageX.shift(),c.rollingPageY.shift(),c.rollingTimestamps.shift()),c.rollingPageX.push(o.pageX),c.rollingPageY.push(o.pageY),c.rollingTimestamps.push(i)}this.dispatched&&(t.preventDefault(),t.stopPropagation(),this.dispatched=!1)}};wo.SCROLL_FRICTION=-.005,wo.HOLD_DELAY=700,wo.CLEAR_TAP_COUNT_TIME=400,pi([Gk],wo,"isTouchDevice",1);var Yk=wo,Zp=class extends ut{onclick(e,t){this._register(Xe(e,Ui.CLICK,i=>t(new nu(Ar(e),i))))}onmousedown(e,t){this._register(Xe(e,Ui.MOUSE_DOWN,i=>t(new nu(Ar(e),i))))}onmouseover(e,t){this._register(Xe(e,Ui.MOUSE_OVER,i=>t(new nu(Ar(e),i))))}onmouseleave(e,t){this._register(Xe(e,Ui.MOUSE_LEAVE,i=>t(new nu(Ar(e),i))))}onkeydown(e,t){this._register(Xe(e,Ui.KEY_DOWN,i=>t(new Sb(i))))}onkeyup(e,t){this._register(Xe(e,Ui.KEY_UP,i=>t(new Sb(i))))}oninput(e,t){this._register(Xe(e,Ui.INPUT,t))}onblur(e,t){this._register(Xe(e,Ui.BLUR,t))}onfocus(e,t){this._register(Xe(e,Ui.FOCUS,t))}onchange(e,t){this._register(Xe(e,Ui.CHANGE,t))}ignoreGesture(e){return Yk.ignoreTarget(e)}},jb=11,Vk=class extends Zp{constructor(e){super(),this._onActivate=e.onActivate,this.bgDomNode=document.createElement("div"),this.bgDomNode.className="arrow-background",this.bgDomNode.style.position="absolute",this.bgDomNode.style.width=e.bgWidth+"px",this.bgDomNode.style.height=e.bgHeight+"px",typeof e.top<"u"&&(this.bgDomNode.style.top="0px"),typeof e.left<"u"&&(this.bgDomNode.style.left="0px"),typeof e.bottom<"u"&&(this.bgDomNode.style.bottom="0px"),typeof e.right<"u"&&(this.bgDomNode.style.right="0px"),this.domNode=document.createElement("div"),this.domNode.className=e.className,this.domNode.style.position="absolute",this.domNode.style.width=jb+"px",this.domNode.style.height=jb+"px",typeof e.top<"u"&&(this.domNode.style.top=e.top+"px"),typeof e.left<"u"&&(this.domNode.style.left=e.left+"px"),typeof e.bottom<"u"&&(this.domNode.style.bottom=e.bottom+"px"),typeof e.right<"u"&&(this.domNode.style.right=e.right+"px"),this._pointerMoveMonitor=this._register(new r0),this._register(Eb(this.bgDomNode,Ui.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._register(Eb(this.domNode,Ui.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._pointerdownRepeatTimer=this._register(new Fk),this._pointerdownScheduleRepeatTimer=this._register(new Kp)}_arrowPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,Ar(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()}},Kk=class ip{constructor(t,i,s,a,o,c,h){this._forceIntegerValues=t,this._scrollStateBrand=void 0,this._forceIntegerValues&&(i=i|0,s=s|0,a=a|0,o=o|0,c=c|0,h=h|0),this.rawScrollLeft=a,this.rawScrollTop=h,i<0&&(i=0),a+i>s&&(a=s-i),a<0&&(a=0),o<0&&(o=0),h+o>c&&(h=c-o),h<0&&(h=0),this.width=i,this.scrollWidth=s,this.scrollLeft=a,this.height=o,this.scrollHeight=c,this.scrollTop=h}equals(t){return this.rawScrollLeft===t.rawScrollLeft&&this.rawScrollTop===t.rawScrollTop&&this.width===t.width&&this.scrollWidth===t.scrollWidth&&this.scrollLeft===t.scrollLeft&&this.height===t.height&&this.scrollHeight===t.scrollHeight&&this.scrollTop===t.scrollTop}withScrollDimensions(t,i){return new ip(this._forceIntegerValues,typeof t.width<"u"?t.width:this.width,typeof t.scrollWidth<"u"?t.scrollWidth:this.scrollWidth,i?this.rawScrollLeft:this.scrollLeft,typeof t.height<"u"?t.height:this.height,typeof t.scrollHeight<"u"?t.scrollHeight:this.scrollHeight,i?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new ip(this._forceIntegerValues,this.width,this.scrollWidth,typeof t.scrollLeft<"u"?t.scrollLeft:this.rawScrollLeft,this.height,this.scrollHeight,typeof t.scrollTop<"u"?t.scrollTop:this.rawScrollTop)}createScrollEvent(t,i){let s=this.width!==t.width,a=this.scrollWidth!==t.scrollWidth,o=this.scrollLeft!==t.scrollLeft,c=this.height!==t.height,h=this.scrollHeight!==t.scrollHeight,p=this.scrollTop!==t.scrollTop;return{inSmoothScrolling:i,oldWidth:t.width,oldScrollWidth:t.scrollWidth,oldScrollLeft:t.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:t.height,oldScrollHeight:t.scrollHeight,oldScrollTop:t.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:s,scrollWidthChanged:a,scrollLeftChanged:o,heightChanged:c,scrollHeightChanged:h,scrollTopChanged:p}}},Xk=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 Kk(e.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),super.dispose()}setSmoothScrollDuration(e){this._smoothScrollDuration=e}validateScrollPosition(e){return this._state.withScrollPosition(e)}getScrollDimensions(){return this._state}setScrollDimensions(e,t){var s;let i=this._state.withScrollDimensions(e,t);this._setState(i,!!this._smoothScrolling),(s=this._smoothScrolling)==null||s.acceptScrollDimensions(this._state)}getFutureScrollPosition(){return this._smoothScrolling?this._smoothScrolling.to:this._state}getCurrentScrollPosition(){return this._state}setScrollPositionNow(e){let t=this._state.withScrollPosition(e);this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),this._setState(t,!1)}setScrollPositionSmooth(e,t){if(this._smoothScrollDuration===0)return this.setScrollPositionNow(e);if(this._smoothScrolling){e={scrollLeft:typeof e.scrollLeft>"u"?this._smoothScrolling.to.scrollLeft:e.scrollLeft,scrollTop:typeof e.scrollTop>"u"?this._smoothScrolling.to.scrollTop:e.scrollTop};let i=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===i.scrollLeft&&this._smoothScrolling.to.scrollTop===i.scrollTop)return;let s;t?s=new Ab(this._smoothScrolling.from,i,this._smoothScrolling.startTime,this._smoothScrolling.duration):s=this._smoothScrolling.combine(this._state,i,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=s}else{let i=this._state.withScrollPosition(e);this._smoothScrolling=Ab.start(this._state,i,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}hasPendingScrollAnimation(){return!!this._smoothScrolling}_performSmoothScrolling(){if(!this._smoothScrolling)return;let e=this._smoothScrolling.tick(),t=this._state.withScrollPosition(e);if(this._setState(t,!0),!!this._smoothScrolling){if(e.isDone){this._smoothScrolling.dispose(),this._smoothScrolling=null;return}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}}_setState(e,t){let i=this._state;i.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(i,t)))}},Tb=class{constructor(e,t,i){this.scrollLeft=e,this.scrollTop=t,this.isDone=i}};function af(e,t){let i=t-e;return function(s){return e+i*Jk(s)}}function Zk(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":"")))}},t2=140,s0=class extends Zp{constructor(e){super(),this._lazyRender=e.lazyRender,this._host=e.host,this._scrollable=e.scrollable,this._scrollByPage=e.scrollByPage,this._scrollbarState=e.scrollbarState,this._visibilityController=this._register(new e2(e.visibility,"visible scrollbar "+e.extraScrollbarClassName,"invisible scrollbar "+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new r0),this._shouldRender=!0,this.domNode=Ao(document.createElement("div")),this.domNode.setAttribute("role","presentation"),this.domNode.setAttribute("aria-hidden","true"),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition("absolute"),this._register(Xe(this.domNode.domNode,Ui.POINTER_DOWN,t=>this._domNodePointerDown(t)))}_createArrow(e){let t=this._register(new Vk(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,i,s){this.slider=Ao(document.createElement("div")),this.slider.setClassName("slider"),this.slider.setPosition("absolute"),this.slider.setTop(e),this.slider.setLeft(t),typeof i=="number"&&this.slider.setWidth(i),typeof s=="number"&&this.slider.setHeight(s),this.slider.setLayerHinting(!0),this.slider.setContain("strict"),this.domNode.domNode.appendChild(this.slider.domNode),this._register(Xe(this.slider.domNode,Ui.POINTER_DOWN,a=>{a.button===0&&(a.preventDefault(),this._sliderPointerDown(a))})),this.onclick(this.slider.domNode,a=>{a.leftButton&&a.stopPropagation()})}_onElementSize(e){return this._scrollbarState.setVisibleSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollSize(e){return this._scrollbarState.setScrollSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollPosition(e){return this._scrollbarState.setScrollPosition(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}beginReveal(){this._visibilityController.setShouldBeVisible(!0)}beginHide(){this._visibilityController.setShouldBeVisible(!1)}render(){this._shouldRender&&(this._shouldRender=!1,this._renderDomNode(this._scrollbarState.getRectangleLargeSize(),this._scrollbarState.getRectangleSmallSize()),this._updateSlider(this._scrollbarState.getSliderSize(),this._scrollbarState.getArrowSize()+this._scrollbarState.getSliderPosition()))}_domNodePointerDown(e){e.target===this.domNode.domNode&&this._onPointerDown(e)}delegatePointerDown(e){let t=this.domNode.domNode.getClientRects()[0].top,i=t+this._scrollbarState.getSliderPosition(),s=t+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),a=this._sliderPointerPosition(e);i<=a&&a<=s?e.button===0&&(e.preventDefault(),this._sliderPointerDown(e)):this._onPointerDown(e)}_onPointerDown(e){let t,i;if(e.target===this.domNode.domNode&&typeof e.offsetX=="number"&&typeof e.offsetY=="number")t=e.offsetX,i=e.offsetY;else{let a=qk(this.domNode.domNode);t=e.pageX-a.left,i=e.pageY-a.top}let s=this._pointerDownRelativePosition(t,i);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(s):this._scrollbarState.getDesiredScrollPositionFromOffset(s)),e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))}_sliderPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=this._sliderPointerPosition(e),i=this._sliderOrthogonalPointerPosition(e),s=this._scrollbarState.clone();this.slider.toggleClassName("active",!0),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,a=>{let o=this._sliderOrthogonalPointerPosition(a),c=Math.abs(o-i);if(e0&&c>t2){this._setDesiredScrollPositionNow(s.getScrollPosition());return}let h=this._sliderPointerPosition(a)-t;this._setDesiredScrollPositionNow(s.getDesiredScrollPositionFromDelta(h))},()=>{this.slider.toggleClassName("active",!1),this._host.onDragEnd()}),this._host.onDragStart()}_setDesiredScrollPositionNow(e){let t={};this.writeScrollPosition(t,e),this._scrollable.setScrollPositionNow(t)}updateScrollbarSize(e){this._updateScrollbarSize(e),this._scrollbarState.setScrollbarSize(e),this._shouldRender=!0,this._lazyRender||this.render()}isNeeded(){return this._scrollbarState.isNeeded()}},a0=class rp{constructor(t,i,s,a,o,c){this._scrollbarSize=Math.round(i),this._oppositeScrollbarSize=Math.round(s),this._arrowSize=Math.round(t),this._visibleSize=a,this._scrollSize=o,this._scrollPosition=c,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new rp(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(t){let i=Math.round(t);return this._visibleSize!==i?(this._visibleSize=i,this._refreshComputedValues(),!0):!1}setScrollSize(t){let i=Math.round(t);return this._scrollSize!==i?(this._scrollSize=i,this._refreshComputedValues(),!0):!1}setScrollPosition(t){let i=Math.round(t);return this._scrollPosition!==i?(this._scrollPosition=i,this._refreshComputedValues(),!0):!1}setScrollbarSize(t){this._scrollbarSize=Math.round(t)}setOppositeScrollbarSize(t){this._oppositeScrollbarSize=Math.round(t)}static _computeValues(t,i,s,a,o){let c=Math.max(0,s-t),h=Math.max(0,c-2*i),p=a>0&&a>s;if(!p)return{computedAvailableSize:Math.round(c),computedIsNeeded:p,computedSliderSize:Math.round(h),computedSliderRatio:0,computedSliderPosition:0};let f=Math.round(Math.max(20,Math.floor(s*h/a))),_=(h-f)/(a-s),x=o*_;return{computedAvailableSize:Math.round(c),computedIsNeeded:p,computedSliderSize:Math.round(f),computedSliderRatio:_,computedSliderPosition:Math.round(x)}}_refreshComputedValues(){let t=rp._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=t.computedAvailableSize,this._computedIsNeeded=t.computedIsNeeded,this._computedSliderSize=t.computedSliderSize,this._computedSliderRatio=t.computedSliderRatio,this._computedSliderPosition=t.computedSliderPosition}getArrowSize(){return this._arrowSize}getScrollPosition(){return this._scrollPosition}getRectangleLargeSize(){return this._computedAvailableSize}getRectangleSmallSize(){return this._scrollbarSize}isNeeded(){return this._computedIsNeeded}getSliderSize(){return this._computedSliderSize}getSliderPosition(){return this._computedSliderPosition}getDesiredScrollPositionFromOffset(t){if(!this._computedIsNeeded)return 0;let i=t-this._arrowSize-this._computedSliderSize/2;return Math.round(i/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(t){if(!this._computedIsNeeded)return 0;let i=t-this._arrowSize,s=this._scrollPosition;return i0&&Math.abs(t.deltaY)>0)return 1;let s=.5;if((!this._isAlmostInt(t.deltaX)||!this._isAlmostInt(t.deltaY))&&(s+=.25),i){let a=Math.abs(t.deltaX),o=Math.abs(t.deltaY),c=Math.abs(i.deltaX),h=Math.abs(i.deltaY),p=Math.max(Math.min(a,c),1),f=Math.max(Math.min(o,h),1),_=Math.max(a,c),x=Math.max(o,h);_%p===0&&x%f===0&&(s-=.5)}return Math.min(Math.max(s,0),1)}_isAlmostInt(t){return Math.abs(Math.round(t)-t)<.01}};sp.INSTANCE=new sp;var a2=sp,l2=class extends Zp{constructor(e,t,i){super(),this._onScroll=this._register(new Ce),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new Ce),this.onWillScroll=this._onWillScroll.event,this._options=c2(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 n2(this._scrollable,this._options,s)),this._horizontalScrollbar=this._register(new i2(this._scrollable,this._options,s)),this._domNode=document.createElement("div"),this._domNode.className="xterm-scrollable-element "+this._options.className,this._domNode.setAttribute("role","presentation"),this._domNode.style.position="relative",this._domNode.appendChild(e),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=Ao(document.createElement("div")),this._leftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=Ao(document.createElement("div")),this._topShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=Ao(document.createElement("div")),this._topLeftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topLeftShadowDomNode.domNode)):(this._leftShadowDomNode=null,this._topShadowDomNode=null,this._topLeftShadowDomNode=null),this._listenOnDomNode=this._options.listenOnDomNode||this._domNode,this._mouseWheelToDispose=[],this._setListeningToMouseWheel(this._options.handleMouseWheel),this.onmouseover(this._listenOnDomNode,a=>this._onMouseOver(a)),this.onmouseleave(this._listenOnDomNode,a=>this._onMouseLeave(a)),this._hideTimeout=this._register(new Kp),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=xa(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(e){this._verticalScrollbar.delegatePointerDown(e)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(e){this._scrollable.setScrollDimensions(e,!1)}updateClassName(e){this._options.className=e,Dr&&(this._options.className+=" mac"),this._domNode.className="xterm-scrollable-element "+this._options.className}updateOptions(e){typeof e.handleMouseWheel<"u"&&(this._options.handleMouseWheel=e.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),typeof e.mouseWheelScrollSensitivity<"u"&&(this._options.mouseWheelScrollSensitivity=e.mouseWheelScrollSensitivity),typeof e.fastScrollSensitivity<"u"&&(this._options.fastScrollSensitivity=e.fastScrollSensitivity),typeof e.scrollPredominantAxis<"u"&&(this._options.scrollPredominantAxis=e.scrollPredominantAxis),typeof e.horizontal<"u"&&(this._options.horizontal=e.horizontal),typeof e.vertical<"u"&&(this._options.vertical=e.vertical),typeof e.horizontalScrollbarSize<"u"&&(this._options.horizontalScrollbarSize=e.horizontalScrollbarSize),typeof e.verticalScrollbarSize<"u"&&(this._options.verticalScrollbarSize=e.verticalScrollbarSize),typeof e.scrollByPage<"u"&&(this._options.scrollByPage=e.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}setRevealOnScroll(e){this._revealOnScroll=e}delegateScrollFromMouseWheelEvent(e){this._onMouseWheel(new Cb(e))}_setListeningToMouseWheel(e){if(this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=xa(this._mouseWheelToDispose),e)){let t=i=>{this._onMouseWheel(new Cb(i))};this._mouseWheelToDispose.push(Xe(this._listenOnDomNode,Ui.MOUSE_WHEEL,t,{passive:!1}))}}_onMouseWheel(e){var a;if((a=e.browserEvent)!=null&&a.defaultPrevented)return;let t=a2.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=!Dr&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||h)&&!c&&(c=o,o=0),e.browserEvent&&e.browserEvent.altKey&&(c=c*this._options.fastScrollSensitivity,o=o*this._options.fastScrollSensitivity);let p=this._scrollable.getFutureScrollPosition(),f={};if(o){let _=Rb*o,x=p.scrollTop-(_<0?Math.floor(_):Math.ceil(_));this._verticalScrollbar.writeScrollPosition(f,x)}if(c){let _=Rb*c,x=p.scrollLeft-(_<0?Math.floor(_):Math.ceil(_));this._horizontalScrollbar.writeScrollPosition(f,x)}f=this._scrollable.validateScrollPosition(f),(p.scrollLeft!==f.scrollLeft||p.scrollTop!==f.scrollTop)&&(this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(f):this._scrollable.setScrollPositionNow(f),i=!0)}let s=i;!s&&this._options.alwaysConsumeMouseWheel&&(s=!0),!s&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(s=!0),s&&(e.preventDefault(),e.stopPropagation())}_onDidScroll(e){this._shouldRender=this._horizontalScrollbar.onDidScroll(e)||this._shouldRender,this._shouldRender=this._verticalScrollbar.onDidScroll(e)||this._shouldRender,this._options.useShadows&&(this._shouldRender=!0),this._revealOnScroll&&this._reveal(),this._options.lazyRender||this._render()}renderNow(){if(!this._options.lazyRender)throw new Error("Please use `lazyRender` together with `renderNow`!");this._render()}_render(){if(this._shouldRender&&(this._shouldRender=!1,this._horizontalScrollbar.render(),this._verticalScrollbar.render(),this._options.useShadows)){let e=this._scrollable.getCurrentScrollPosition(),t=e.scrollTop>0,i=e.scrollLeft>0,s=i?" left":"",a=t?" top":"",o=i||t?" top-left-corner":"";this._leftShadowDomNode.setClassName(`shadow${s}`),this._topShadowDomNode.setClassName(`shadow${a}`),this._topLeftShadowDomNode.setClassName(`shadow${o}${a}${s}`)}}_onDragStart(){this._isDragging=!0,this._reveal()}_onDragEnd(){this._isDragging=!1,this._hide()}_onMouseLeave(e){this._mouseIsOver=!1,this._hide()}_onMouseOver(e){this._mouseIsOver=!0,this._reveal()}_reveal(){this._verticalScrollbar.beginReveal(),this._horizontalScrollbar.beginReveal(),this._scheduleHide()}_hide(){!this._mouseIsOver&&!this._isDragging&&(this._verticalScrollbar.beginHide(),this._horizontalScrollbar.beginHide())}_scheduleHide(){!this._mouseIsOver&&!this._isDragging&&this._hideTimeout.cancelAndSet(()=>this._hide(),r2)}},o2=class extends l2{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 c2(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,Dr&&(t.className+=" mac"),t}var ap=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 Xk({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:f=>Xp(s.window,f)}));this._register(this._optionsService.onSpecificOptionChange("smoothScrollDuration",()=>{p.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new o2(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(ti(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=s.mainDocument.createElement("style"),t.appendChild(this._styleElement),this._register(ti(()=>this._styleElement.remove())),this._register(sn.runAndSubscribe(o.onChangeColors,()=>{this._styleElement.textContent=[".xterm .xterm-scrollable-element > .scrollbar > .slider {",` background: ${o.colors.scrollbarSliderBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider:hover {",` background: ${o.colors.scrollbarSliderHoverBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider.active {",` background: ${o.colors.scrollbarSliderActiveBackground.css};`,"}"].join(` +`)})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(f=>this._handleScroll(f)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){var e;return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:((e=this._optionsService.rawOptions.overviewRuler)==null?void 0:e.width)||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),i=t-this._bufferService.buffer.ydisp;i!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(i)),this._isHandlingScroll=!1}};ap=pi([De(2,vn),De(3,ls),De(4,Hy),De(5,gl),De(6,yn),De(7,os)],ap);var lp=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(ti(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){var s;let t=this._coreBrowserService.mainDocument.createElement("div");t.classList.add("xterm-decoration"),t.classList.toggle("xterm-decoration-top-layer",((s=e==null?void 0:e.options)==null?void 0:s.layer)==="top"),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,t.style.top=`${(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height}px`,t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let i=e.options.x??0;return i&&i>this._bufferService.cols&&(t.style.display="none"),this._refreshXPosition(e,t),t}_refreshStyle(e){let t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display="none",e.onRenderEmitter.fire(e.element));else{let i=this._decorationElements.get(e);i||(i=this._createElement(e),e.element=i,this._decorationElements.set(e,i),this._container.appendChild(i),e.onDispose(()=>{this._decorationElements.delete(e),i.remove()})),i.style.display=this._altBufferIsActive?"none":"block",this._altBufferIsActive||(i.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,i.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,i.style.top=`${t*this._renderService.dimensions.css.cell.height}px`,i.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(i)}}_refreshXPosition(e,t=e.element){if(!t)return;let i=e.options.x??0;(e.options.anchor||"left")==="right"?t.style.right=i?`${i*this._renderService.dimensions.css.cell.width}px`:"":t.style.left=i?`${i*this._renderService.dimensions.css.cell.width}px`:""}_removeDecoration(e){var t;(t=this._decorationElements.get(e))==null||t.remove(),this._decorationElements.delete(e),e.dispose()}};lp=pi([De(1,vn),De(2,ls),De(3,Fo),De(4,os)],lp);var u2=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)}},Er={full:0,left:0,center:0,right:0},Os={full:0,left:0,center:0,right:0},ho={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 u2,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement("canvas"),this._canvas.classList.add("xterm-decoration-overview-ruler"),this._refreshCanvasDimensions(),(f=this._viewportElement.parentElement)==null||f.insertBefore(this._canvas,this._viewportElement),this._register(ti(()=>{var _;return(_=this._canvas)==null?void 0:_.remove()}));let p=this._canvas.getContext("2d");if(p)this._ctx=p;else throw new Error("Ctx cannot be null");this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this._register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0))),this._register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?"none":"block"})),this._register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})),this._register(this._renderService.onRender(()=>{(!this._containerHeight||this._containerHeight!==this._screenElement.clientHeight)&&(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._register(this._optionsService.onSpecificOptionChange("overviewRuler",()=>this._queueRefresh(!0))),this._register(this._themeService.onChangeColors(()=>this._queueRefresh())),this._queueRefresh(!0)}get _width(){var e;return((e=this._optionsService.options.overviewRuler)==null?void 0:e.width)||0}_refreshDrawConstants(){let e=Math.floor((this._canvas.width-1)/3),t=Math.ceil((this._canvas.width-1)/3);Os.full=this._canvas.width,Os.left=e,Os.center=t,Os.right=e,this._refreshDrawHeightConstants(),ho.full=1,ho.left=1,ho.center=1+Os.left,ho.right=1+Os.left+Os.center}_refreshDrawHeightConstants(){Er.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);Er.left=t,Er.center=t,Er.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*Er.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*Er.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*Er.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*Er.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(let t of this._decorationService.decorations)this._colorZoneStore.addDecoration(t);this._ctx.lineWidth=1,this._renderRulerOutline();let e=this._colorZoneStore.zones;for(let t of e)t.position!=="full"&&this._renderColorZone(t);for(let t of e)t.position==="full"&&this._renderColorZone(t);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderRulerOutline(){this._ctx.fillStyle=this._themeService.colors.overviewRulerBorder.css,this._ctx.fillRect(0,0,1,this._canvas.height),this._optionsService.rawOptions.overviewRuler.showTopBorder&&this._ctx.fillRect(1,0,this._canvas.width-1,1),this._optionsService.rawOptions.overviewRuler.showBottomBorder&&this._ctx.fillRect(1,this._canvas.height-1,this._canvas.width-1,this._canvas.height)}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(ho[e.position||"full"],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-Er[e.position||"full"]/2),Os[e.position||"full"],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+Er[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=pi([De(2,vn),De(3,Fo),De(4,os),De(5,yn),De(6,gl),De(7,ls)],ju);var pe;(e=>(e.NUL="\0",e.SOH="",e.STX="",e.ETX="",e.EOT="",e.ENQ="",e.ACK="",e.BEL="\x07",e.BS="\b",e.HT=" ",e.LF=` +`,e.VT="\v",e.FF="\f",e.CR="\r",e.SO="",e.SI="",e.DLE="",e.DC1="",e.DC2="",e.DC3="",e.DC4="",e.NAK="",e.SYN="",e.ETB="",e.CAN="",e.EM="",e.SUB="",e.ESC="\x1B",e.FS="",e.GS="",e.RS="",e.US="",e.SP=" ",e.DEL=""))(pe||(pe={}));var bu;(e=>(e.PAD="€",e.HOP="",e.BPH="‚",e.NBH="ƒ",e.IND="„",e.NEL="…",e.SSA="†",e.ESA="‡",e.HTS="ˆ",e.HTJ="‰",e.VTS="Š",e.PLD="‹",e.PLU="Œ",e.RI="",e.SS2="Ž",e.SS3="",e.DCS="",e.PU1="‘",e.PU2="’",e.STS="“",e.CCH="”",e.MW="•",e.SPA="–",e.EPA="—",e.SOS="˜",e.SGCI="™",e.SCI="š",e.CSI="›",e.ST="œ",e.OSC="",e.PM="ž",e.APC="Ÿ"))(bu||(bu={}));var l0;(e=>e.ST=`${pe.ESC}\\`)(l0||(l0={}));var op=class{constructor(e,t,i,s,a,o){this._textarea=e,this._compositionView=t,this._bufferService=i,this._optionsService=s,this._coreService=a,this._renderService=o,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=""}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent="",this._dataAlreadySent="",this._compositionView.classList.add("active")}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return!1;this._finalizeComposition(!1)}return e.keyCode===229?(this._handleAnyTextareaChanges(),!1):!0}_finalizeComposition(e){if(this._compositionView.classList.remove("active"),this._isComposing=!1,e){let t={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let i;t.start+=this._dataAlreadySent.length,this._isComposing?i=this._textarea.value.substring(t.start,this._compositionPosition.start):i=this._textarea.value.substring(t.start),i.length>0&&this._coreService.triggerDataEvent(i,!0)}},0)}else{this._isSendingComposition=!1;let t=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(t,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,i=t.replace(e,"");this._dataAlreadySent=i,t.length>e.length?this._coreService.triggerDataEvent(i,!0):t.lengththis.updateCompositionElements(!0),0)}}};op=pi([De(2,vn),De(3,yn),De(4,va),De(5,os)],op);var $i=0,Fi=0,qi=0,di=0,Db={css:"#00000000",rgba:0},Ri;(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})(Ri||(Ri={}));var Jt;(e=>{function t(p,f){if(di=(f.rgba&255)/255,di===1)return{css:f.css,rgba:f.rgba};let _=f.rgba>>24&255,x=f.rgba>>16&255,b=f.rgba>>8&255,v=p.rgba>>24&255,S=p.rgba>>16&255,N=p.rgba>>8&255;$i=v+Math.round((_-v)*di),Fi=S+Math.round((x-S)*di),qi=N+Math.round((b-N)*di);let B=Ri.toCss($i,Fi,qi),E=Ri.toRgba($i,Fi,qi);return{css:B,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 Ri.toColor(x>>24&255,x>>16&255,x>>8&255)}e.ensureContrastRatio=s;function a(p){let f=(p.rgba|255)>>>0;return[$i,Fi,qi]=vu.toChannels(f),{css:Ri.toCss($i,Fi,qi),rgba:f}}e.opaque=a;function o(p,f){return di=Math.round(f*255),[$i,Fi,qi]=vu.toChannels(p.rgba),{css:Ri.toCss($i,Fi,qi,di),rgba:Ri.toRgba($i,Fi,qi,di)}}e.opacity=o;function c(p,f){return di=p.rgba&255,o(p,di*f/255)}e.multiplyOpacity=c;function h(p){return[p.rgba>>24&255,p.rgba>>16&255,p.rgba>>8&255]}e.toColorRGB=h})(Jt||(Jt={}));var ai;(e=>{let t,i;try{let a=document.createElement("canvas");a.width=1,a.height=1;let o=a.getContext("2d",{willReadFrequently:!0});o&&(t=o,t.globalCompositeOperation="copy",i=t.createLinearGradient(0,0,1,1))}catch{}function s(a){if(a.match(/#[\da-f]{3,8}/i))switch(a.length){case 4:return $i=parseInt(a.slice(1,2).repeat(2),16),Fi=parseInt(a.slice(2,3).repeat(2),16),qi=parseInt(a.slice(3,4).repeat(2),16),Ri.toColor($i,Fi,qi);case 5:return $i=parseInt(a.slice(1,2).repeat(2),16),Fi=parseInt(a.slice(2,3).repeat(2),16),qi=parseInt(a.slice(3,4).repeat(2),16),di=parseInt(a.slice(4,5).repeat(2),16),Ri.toColor($i,Fi,qi,di);case 7:return{css:a,rgba:(parseInt(a.slice(1),16)<<8|255)>>>0};case 9:return{css:a,rgba:parseInt(a.slice(1),16)>>>0}}let o=a.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(o)return $i=parseInt(o[1]),Fi=parseInt(o[2]),qi=parseInt(o[3]),di=Math.round((o[5]===void 0?1:parseFloat(o[5]))*255),Ri.toColor($i,Fi,qi,di);if(!t||!i)throw new Error("css.toColor: Unsupported css format");if(t.fillStyle=i,t.fillStyle=a,typeof t.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(t.fillRect(0,0,1,1),[$i,Fi,qi,di]=t.getImageData(0,0,1,1).data,di!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:Ri.toRgba($i,Fi,qi,di),css:a}}e.toColor=s})(ai||(ai={}));var gn;(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})(gn||(gn={}));var vu;(e=>{function t(c,h){if(di=(h&255)/255,di===1)return h;let p=h>>24&255,f=h>>16&255,_=h>>8&255,x=c>>24&255,b=c>>16&255,v=c>>8&255;return $i=x+Math.round((p-x)*di),Fi=b+Math.round((f-b)*di),qi=v+Math.round((_-v)*di),Ri.toRgba($i,Fi,qi)}e.blend=t;function i(c,h,p){let f=gn.relativeLuminance(c>>8),_=gn.relativeLuminance(h>>8);if(is(f,_)>8));if(S>8));return S>B?v:N}return v}let x=a(c,h,p),b=is(f,gn.relativeLuminance(x>>8));if(b>8));return b>S?x:v}return x}}e.ensureContrastRatio=i;function s(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,N=is(gn.relativeLuminance2(b,v,S),gn.relativeLuminance2(f,_,x));for(;N0||v>0||S>0);)b-=Math.max(0,Math.ceil(b*.1)),v-=Math.max(0,Math.ceil(v*.1)),S-=Math.max(0,Math.ceil(S*.1)),N=is(gn.relativeLuminance2(b,v,S),gn.relativeLuminance2(f,_,x));return(b<<24|v<<16|S<<8|255)>>>0}e.reduceLuminance=s;function a(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,N=is(gn.relativeLuminance2(b,v,S),gn.relativeLuminance2(f,_,x));for(;N>>0}e.increaseLuminance=a;function o(c){return[c>>24&255,c>>16&255,c>>8&255,c&255]}e.toChannels=o})(vu||(vu={}));function ca(e){let t=e.toString(16);return t.length<2?"0"+t:t}function is(e,t){return e1){let _=this._getJoinedRanges(s,c,o,t,a);for(let x=0;x<_.length;x++)i.push(_[x])}a=f,c=o,h=this._workCell.fg,p=this._workCell.bg}o+=this._workCell.getChars().length||Us.length}if(this._bufferService.cols-a>1){let f=this._getJoinedRanges(s,c,o,t,a);for(let _=0;_=L,P=Y,q=this._workCell;if(b.length>0&&Y===b[0][0]&&T){let ye=b.shift(),st=this._isCellInSelection(ye[0],t);for(O=ye[0]+1;O=ye[1]),T?(U=!0,q=new h2(this._workCell,e.translateToString(!0,ye[0],ye[1]),ye[1]-ye[0]),P=ye[1]-1,V=q.getWidth()):L=ye[1]}let xe=this._isCellInSelection(Y,t),j=i&&Y===o,R=F&&Y>=f&&Y<=_,Z=!1;this._decorationService.forEachDecorationAtCell(Y,t,void 0,ye=>{Z=!0});let k=q.getChars()||Us;if(k===" "&&(q.isUnderline()||q.isOverline())&&(k=" "),be=V*h-p.get(k,q.isBold(),q.isItalic()),!N)N=this._document.createElement("span");else if(B&&(xe&&ue||!xe&&!ue&&q.bg===H)&&(xe&&ue&&v.selectionForeground||q.fg===A)&&q.extended.ext===W&&R===D&&be===ne&&!j&&!U&&!Z&&T){q.isInvisible()?E+=Us:E+=k,B++;continue}else B&&(N.textContent=E),N=this._document.createElement("span"),B=0,E="";if(H=q.bg,A=q.fg,W=q.extended.ext,D=R,ne=be,ue=xe,U&&o>=Y&&o<=P&&(o=Y),!this._coreService.isCursorHidden&&j&&this._coreService.isCursorInitialized){if(re.push("xterm-cursor"),this._coreBrowserService.isFocused)c&&re.push("xterm-cursor-blink"),re.push(s==="bar"?"xterm-cursor-bar":s==="underline"?"xterm-cursor-underline":"xterm-cursor-block");else if(a)switch(a){case"outline":re.push("xterm-cursor-outline");break;case"block":re.push("xterm-cursor-block");break;case"bar":re.push("xterm-cursor-bar");break;case"underline":re.push("xterm-cursor-underline");break}}if(q.isBold()&&re.push("xterm-bold"),q.isItalic()&&re.push("xterm-italic"),q.isDim()&&re.push("xterm-dim"),q.isInvisible()?E=Us:E=q.getChars()||Us,q.isUnderline()&&(re.push(`xterm-underline-${q.extended.underlineStyle}`),E===" "&&(E=" "),!q.isUnderlineColorDefault()))if(q.isUnderlineColorRGB())N.style.textDecorationColor=`rgb(${$o.toColorRGB(q.getUnderlineColor()).join(",")})`;else{let ye=q.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&q.isBold()&&ye<8&&(ye+=8),N.style.textDecorationColor=v.ansi[ye].css}q.isOverline()&&(re.push("xterm-overline"),E===" "&&(E=" ")),q.isStrikethrough()&&re.push("xterm-strikethrough"),R&&(N.style.textDecoration="underline");let K=q.getFgColor(),ae=q.getFgColorMode(),oe=q.getBgColor(),X=q.getBgColorMode(),he=!!q.isInverse();if(he){let ye=K;K=oe,oe=ye;let st=ae;ae=X,X=st}let ge,Re,Le=!1;this._decorationService.forEachDecorationAtCell(Y,t,void 0,ye=>{ye.options.layer!=="top"&&Le||(ye.backgroundColorRGB&&(X=50331648,oe=ye.backgroundColorRGB.rgba>>8&16777215,ge=ye.backgroundColorRGB),ye.foregroundColorRGB&&(ae=50331648,K=ye.foregroundColorRGB.rgba>>8&16777215,Re=ye.foregroundColorRGB),Le=ye.options.layer==="top")}),!Le&&xe&&(ge=this._coreBrowserService.isFocused?v.selectionBackgroundOpaque:v.selectionInactiveBackgroundOpaque,oe=ge.rgba>>8&16777215,X=50331648,Le=!0,v.selectionForeground&&(ae=50331648,K=v.selectionForeground.rgba>>8&16777215,Re=v.selectionForeground)),Le&&re.push("xterm-decoration-top");let Fe;switch(X){case 16777216:case 33554432:Fe=v.ansi[oe],re.push(`xterm-bg-${oe}`);break;case 50331648:Fe=Ri.toColor(oe>>16,oe>>8&255,oe&255),this._addStyle(N,`background-color:#${Mb((oe>>>0).toString(16),"0",6)}`);break;case 0:default:he?(Fe=v.foreground,re.push("xterm-bg-257")):Fe=v.background}switch(ge||q.isDim()&&(ge=Jt.multiplyOpacity(Fe,.5)),ae){case 16777216:case 33554432:q.isBold()&&K<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(K+=8),this._applyMinimumContrast(N,Fe,v.ansi[K],q,ge,void 0)||re.push(`xterm-fg-${K}`);break;case 50331648:let ye=Ri.toColor(K>>16&255,K>>8&255,K&255);this._applyMinimumContrast(N,Fe,ye,q,ge,Re)||this._addStyle(N,`color:#${Mb(K.toString(16),"0",6)}`);break;case 0:default:this._applyMinimumContrast(N,Fe,v.foreground,q,ge,Re)||he&&re.push("xterm-fg-257")}re.length&&(N.className=re.join(" "),re.length=0),!j&&!U&&!Z&&T?B++:N.textContent=E,be!==this.defaultSpacing&&(N.style.letterSpacing=`${be}px`),x.push(N),Y=P}return N&&B&&(N.textContent=E),x}_applyMinimumContrast(e,t,i,s,a,o){if(this._optionsService.rawOptions.minimumContrastRatio===1||p2(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=Jt.ensureContrastRatio(a||t,o||i,p),c.setColor((a||t).rgba,(o||i).rgba,h??null)}return h?(this._addStyle(e,`color:${h.css}`),!0):!1}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute("style",`${e.getAttribute("style")||""}${t};`)}_isCellInSelection(e,t){let i=this._selectionStart,s=this._selectionEnd;return!i||!s?!1:this._columnSelectMode?i[0]<=s[0]?e>=i[0]&&t>=i[1]&&e=i[1]&&e>=s[0]&&t<=s[1]:t>i[1]&&t=i[0]&&e=i[0]}};cp=pi([De(1,Fy),De(2,yn),De(3,ls),De(4,va),De(5,Fo),De(6,gl)],cp);function Mb(e,t,i){for(;e.length0&&(this._flat[s]=c),c}let a=e;t&&(a+="B"),i&&(a+="I");let o=this._holey.get(a);if(o===void 0){let c=0;t&&(c|=1),i&&(c|=2),o=this._measure(e,c),o>0&&this._holey.set(a,o)}return o}_measure(e,t){let i=this._measureElements[t];return i.textContent=e.repeat(32),i.offsetWidth/32}},x2=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 _2(){return new x2}var lf="xterm-dom-renderer-owner-",sr="xterm-rows",su="xterm-fg-",Bb="xterm-bg-",fo="xterm-focus",au="xterm-selection",b2=1,up=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=b2++,this._rowElements=[],this._selectionRenderModel=_2(),this.onRequestRedraw=this._register(new Ce).event,this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(sr),this._rowContainer.style.lineHeight="normal",this._rowContainer.setAttribute("aria-hidden","true"),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement("div"),this._selectionContainer.classList.add(au),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=m2(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(S=>this._injectCss(S))),this._injectCss(this._themeService.colors),this._rowFactory=h.createInstance(cp,document),this._element.classList.add(lf+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(S=>this._handleLinkHover(S))),this._register(this._linkifier2.onHideLinkUnderline(S=>this._handleLinkLeave(S))),this._register(ti(()=>{this._element.classList.remove(lf+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new g2(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} .${sr} 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} .${sr} { 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} .${sr} .xterm-dim { color: ${Jt.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} .${sr}.${fo} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${sr}.${fo} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${s} 1s step-end infinite;}${this._terminalSelector} .${sr}.${fo} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${a} 1s step-end infinite;}${this._terminalSelector} .${sr} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${sr} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${sr} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${sr} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${sr} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${au} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${au} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${au} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[o,c]of e.ansi.entries())t+=`${this._terminalSelector} .${su}${o} { color: ${c.css}; }${this._terminalSelector} .${su}${o}.xterm-dim { color: ${Jt.multiplyOpacity(c,.5).css}; }${this._terminalSelector} .${Bb}${o} { background-color: ${c.css}; }`;t+=`${this._terminalSelector} .${su}257 { color: ${Jt.opaque(e.background).css}; }${this._terminalSelector} .${su}257.xterm-dim { color: ${Jt.multiplyOpacity(Jt.opaque(e.background),.5).css}; }${this._terminalSelector} .${Bb}257 { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){let e=this.dimensions.css.cell.width-this._widthCache.get("W",!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let i=this._rowElements.length;i<=t;i++){let s=this._document.createElement("div");this._rowContainer.appendChild(s),this._rowElements.push(s)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(fo),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(fo),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,i){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,i),this.renderRows(0,this._bufferService.rows-1),!e||!t||(this._selectionRenderModel.update(this._terminal,e,t,i),!this._selectionRenderModel.hasSelection))return;let s=this._selectionRenderModel.viewportStartRow,a=this._selectionRenderModel.viewportEndRow,o=this._selectionRenderModel.viewportCappedStartRow,c=this._selectionRenderModel.viewportCappedEndRow,h=this._document.createDocumentFragment();if(i){let p=e[0]>t[0];h.appendChild(this._createSelectionElement(o,p?t[0]:e[0],p?e[0]:t[0],c-o+1))}else{let p=s===o?e[0]:0,f=o===a?t[0]:this._bufferService.cols;h.appendChild(this._createSelectionElement(o,p,f));let _=c-o-1;if(h.appendChild(this._createSelectionElement(o+1,0,this._bufferService.cols,_)),o!==c){let x=a===c?t[0]:this._bufferService.cols;h.appendChild(this._createSelectionElement(c,0,x))}}this._selectionContainer.appendChild(h)}_createSelectionElement(e,t,i,s=1){let a=this._document.createElement("div"),o=t*this.dimensions.css.cell.width,c=this.dimensions.css.cell.width*(i-t);return o+c>this.dimensions.css.canvas.width&&(c=this.dimensions.css.canvas.width-o),a.style.height=`${s*this.dimensions.css.cell.height}px`,a.style.top=`${e*this.dimensions.css.cell.height}px`,a.style.left=`${o}px`,a.style.width=`${c}px`,a}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(let e of this._rowElements)e.replaceChildren()}renderRows(e,t){let i=this._bufferService.buffer,s=i.ybase+i.y,a=Math.min(i.x,this._bufferService.cols-1),o=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,c=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,h=this._optionsService.rawOptions.cursorInactiveStyle;for(let p=e;p<=t;p++){let f=p+i.ydisp,_=this._rowElements[p],x=i.lines.get(f);if(!_||!x)break;_.replaceChildren(...this._rowFactory.createRow(x,f,f===s,c,h,a,o,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${lf}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,i,s,a,o){i<0&&(e=0),s<0&&(t=0);let c=this._bufferService.rows-1;i=Math.max(Math.min(i,c),0),s=Math.max(Math.min(s,c),0),a=Math.min(a,this._bufferService.cols);let h=this._bufferService.buffer,p=h.ybase+h.y,f=Math.min(h.x,a-1),_=this._optionsService.rawOptions.cursorBlink,x=this._optionsService.rawOptions.cursorStyle,b=this._optionsService.rawOptions.cursorInactiveStyle;for(let v=i;v<=s;++v){let S=v+h.ydisp,N=this._rowElements[v],B=h.lines.get(S);if(!N||!B)break;N.replaceChildren(...this._rowFactory.createRow(B,S,S===p,x,b,f,_,this.dimensions.css.cell.width,this._widthCache,o?v===i?e:0:-1,o?(v===s?t:a)-1:-1))}}};up=pi([De(7,qp),De(8,Hu),De(9,yn),De(10,vn),De(11,va),De(12,ls),De(13,gl)],up);var hp=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 y2(this._optionsService))}catch{this._measureStrategy=this._register(new v2(e,t,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange(["fontFamily","fontSize"],()=>this.measure()))}get hasValidSize(){return this.width>0&&this.height>0}measure(){let e=this._measureStrategy.measure();(e.width!==this.width||e.height!==this.height)&&(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};hp=pi([De(2,yn)],hp);var o0=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)}},v2=class extends o0{constructor(e,t,i){super(),this._document=e,this._parentElement=t,this._optionsService=i,this._measureElement=this._document.createElement("span"),this._measureElement.classList.add("xterm-char-measure-element"),this._measureElement.textContent="W".repeat(32),this._measureElement.setAttribute("aria-hidden","true"),this._measureElement.style.whiteSpace="pre",this._measureElement.style.fontKerning="none",this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}},y2=class extends o0{constructor(e){super(),this._optionsService=e,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext("2d");let t=this._ctx.measureText("W");if(!("width"in t&&"fontBoundingBoxAscent"in t&&"fontBoundingBoxDescent"in t))throw new Error("Required font metrics not supported")}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;let e=this._ctx.measureText("W");return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}},S2=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 w2(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(sn.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}},w2=class extends ut{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new fl),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(ti(()=>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)}},C2=class extends ut{constructor(){super(),this.linkProviders=[],this._register(ti(()=>this.linkProviders.length=0))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{let t=this.linkProviders.indexOf(e);t!==-1&&this.linkProviders.splice(t,1)}}}};function Qp(e,t,i){let s=i.getBoundingClientRect(),a=e.getComputedStyle(i),o=parseInt(a.getPropertyValue("padding-left")),c=parseInt(a.getPropertyValue("padding-top"));return[t.clientX-s.left-o,t.clientY-s.top-c]}function k2(e,t,i,s,a,o,c,h,p){if(!o)return;let f=Qp(e,t,i);if(f)return f[0]=Math.ceil((f[0]+(p?c/2:0))/c),f[1]=Math.ceil(f[1]/h),f[0]=Math.min(Math.max(f[0],1),s+(p?1:0)),f[1]=Math.min(Math.max(f[1],1),a),f}var dp=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,i,s,a){return k2(window,e,t,i,s,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,a)}getMouseReportCoords(e,t){let i=Qp(window,e,t);if(this._charSizeService.hasValidSize)return i[0]=Math.min(Math.max(i[0],0),this._renderService.dimensions.css.canvas.width-1),i[1]=Math.min(Math.max(i[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(i[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(i[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(i[0]),y:Math.floor(i[1])}}};dp=pi([De(0,os),De(1,Hu)],dp);var E2=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this._refreshCallbacks=[]}dispose(){this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}addRefreshCallback(e){return this._refreshCallbacks.push(e),this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh())),this._animationFrame}refresh(e,t,i){this._rowCount=i,e=e!==void 0?e:0,t=t!==void 0?t:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,e):e,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,t):t,!this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0){this._runRefreshCallbacks();return}let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(let e of this._refreshCallbacks)e(0);this._refreshCallbacks=[]}},c0={};OC(c0,{getSafariVersion:()=>j2,isChromeOS:()=>f0,isFirefox:()=>u0,isIpad:()=>T2,isIphone:()=>A2,isLegacyEdge:()=>N2,isLinux:()=>Jp,isMac:()=>Au,isNode:()=>Uu,isSafari:()=>h0,isWindows:()=>d0});var Uu=typeof process<"u"&&"title"in process,qo=Uu?"node":navigator.userAgent,Wo=Uu?"node":navigator.platform,u0=qo.includes("Firefox"),N2=qo.includes("Edge"),h0=/^((?!chrome|android).)*safari/i.test(qo);function j2(){if(!h0)return 0;let e=qo.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var Au=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(Wo),T2=Wo==="iPad",A2=Wo==="iPhone",d0=["Windows","Win16","Win32","WinCE"].includes(Wo),Jp=Wo.indexOf("Linux")>=0,f0=/\bCrOS\b/.test(qo),p0=class{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._ia){s-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(s-t))}ms`),this._start();return}s=a}this.clear()}},R2=class extends p0{_requestCallback(e){return setTimeout(()=>e(this._createDeadline(16)))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=performance.now()+e;return{timeRemaining:()=>Math.max(0,t-performance.now())}}},D2=class extends p0{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},Ru=!Uu&&"requestIdleCallback"in window?D2:R2,M2=class{constructor(){this._queue=new Ru}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},fp=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 fl),this._pausedResizeTask=new M2,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 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 E2((f,_)=>this._renderRows(f,_),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new B2(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(ti(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(c.onResize(()=>this._fullRefresh())),this._register(c.buffers.onBufferActivate(()=>{var f;return(f=this._renderer.value)==null?void 0:f.clear()})),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(o.onDecorationRegistered(()=>this._fullRefresh())),this._register(o.onDecorationRemoved(()=>this._fullRefresh())),this._register(this._optionsService.onMultipleOptionChange(["customGlyphs","drawBoldTextInBrightColors","letterSpacing","lineHeight","fontFamily","fontSize","fontWeight","fontWeightBold","minimumContrastRatio","rescaleOverlappingGlyphs"],()=>{this.clear(),this.handleResize(c.cols,c.rows),this._fullRefresh()})),this._register(this._optionsService.onMultipleOptionChange(["cursorBlink","cursorStyle"],()=>this.refreshRows(c.buffer.y,c.buffer.y,!0))),this._register(p.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,t),this._register(this._coreBrowserService.onWindowChange(f=>this._registerIntersectionObserver(f,t)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(e,t){if("IntersectionObserver"in e){let i=new e.IntersectionObserver(s=>this._handleIntersectionChange(s[s.length-1]),{threshold:0});i.observe(t),this._observerDisposable.value=ti(()=>i.disconnect())}}_handleIntersectionChange(e){this._isPaused=e.isIntersecting===void 0?e.intersectionRatio===0:!e.isIntersecting,!this._isPaused&&!this._charSizeService.hasValidSize&&this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,t,i=!1){if(this._isPaused){this._needsFullRefresh=!0;return}if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}let s=this._syncOutputHandler.flush();s&&(e=Math.min(e,s.start),t=Math.max(t,s.end)),i||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount)}_renderRows(e,t){if(this._renderer.value){if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),this._needsSelectionRefresh=!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0}}resize(e,t){this._rowCount=t,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw(t=>this.refreshRows(t.start,t.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){var e,t;this._renderer.value&&((t=(e=this._renderer.value).clearTextureAtlas)==null||t.call(e),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>{var i;return(i=this._renderer.value)==null?void 0:i.handleResize(e,t)}):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){var e;(e=this._renderer.value)==null||e.handleCharSizeChanged()}handleBlur(){var e;(e=this._renderer.value)==null||e.handleBlur()}handleFocus(){var e;(e=this._renderer.value)==null||e.handleFocus()}handleSelectionChanged(e,t,i){var s;this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=i,(s=this._renderer.value)==null||s.handleSelectionChanged(e,t,i)}handleCursorMove(){var e;(e=this._renderer.value)==null||e.handleCursorMove()}clear(){var e;(e=this._renderer.value)==null||e.clear()}};fp=pi([De(2,yn),De(3,Hu),De(4,va),De(5,Fo),De(6,vn),De(7,ls),De(8,gl)],fp);var B2=class{constructor(e,t,i){this._coreBrowserService=e,this._coreService=t,this._onTimeout=i,this._start=0,this._end=0,this._isBuffering=!1}bufferRows(e,t){this._isBuffering?(this._start=Math.min(this._start,e),this._end=Math.max(this._end,t)):(this._start=e,this._end=t,this._isBuffering=!0),this._timeout===void 0&&(this._timeout=this._coreBrowserService.window.setTimeout(()=>{this._timeout=void 0,this._coreService.decPrivateModes.synchronizedOutput=!1,this._onTimeout()},1e3))}flush(){if(this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0),!this._isBuffering)return;let e={start:this._start,end:this._end};return this._isBuffering=!1,e}dispose(){this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0)}};function L2(e,t,i,s){let a=i.buffer.x,o=i.buffer.y;if(!i.buffer.hasScrollback)return P2(a,o,e,t,i,s)+$u(o,t,i,s)+I2(a,o,e,t,i,s);let c;if(o===t)return c=a>e?"D":"C",Oo(Math.abs(a-e),Lo(c,s));c=o>t?"D":"C";let h=Math.abs(o-t),p=z2(o>t?e:a,i)+(h-1)*i.cols+1+O2(o>t?a:e);return Oo(p,Lo(c,s))}function O2(e,t){return e-1}function z2(e,t){return t.cols-e}function P2(e,t,i,s,a,o){return $u(t,s,a,o).length===0?"":Oo(g0(e,t,e,t-_a(t,a),!1,a).length,Lo("D",o))}function $u(e,t,i,s){let a=e-_a(e,i),o=t-_a(t,i),c=Math.abs(a-o)-H2(e,t,i);return Oo(c,Lo(m0(e,t),s))}function I2(e,t,i,s,a,o){let c;$u(t,s,a,o).length>0?c=s-_a(s,a):c=t;let h=s,p=U2(e,t,i,s,a,o);return Oo(g0(e,c,i,h,p==="C",a).length,Lo(p,o))}function H2(e,t,i){var c;let s=0,a=e-_a(e,i),o=t-_a(t,i);for(let h=0;h=0&&e0?c=s-_a(s,a):c=t,e=i&&ct?"A":"B"}function g0(e,t,i,s,a,o){let c=e,h=t,p="";for(;(c!==i||h!==s)&&h>=0&&ho.cols-1?(p+=o.buffer.translateBufferLineToString(h,!1,e,c),c=0,e=0,h++):!a&&c<0&&(p+=o.buffer.translateBufferLineToString(h,!1,0,e+1),c=o.cols-1,e=c,h--);return p+o.buffer.translateBufferLineToString(h,!1,e,c)}function Lo(e,t){let i=t?"O":"[";return pe.ESC+i+e}function Oo(e,t){e=Math.floor(e);let i="";for(let s=0;sthis._bufferService.cols?e%this._bufferService.cols===0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){let e=this.selectionStart,t=this.selectionEnd;return!e||!t?!1:e[1]>t[1]||e[1]===t[1]&&e[0]>t[0]}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}};function Lb(e,t){if(e.start.y>e.end.y)throw new Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}var of=50,F2=15,q2=50,W2=500,G2=" ",Y2=new RegExp(G2,"g"),pp=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 cr,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 $2(this._bufferService),this._activeSelectionMode=0,this._register(ti(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(f=>{f.rowsChanged&&this.clearSelection()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!e||!t?!1:e[0]!==t[0]||e[1]!==t[1]}get selectionText(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return"";let i=this._bufferService.buffer,s=[];if(this._activeSelectionMode===3){if(e[0]===t[0])return"";let a=e[0]a.replace(Y2," ")).join(d0?`\r `:` -`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),Jp&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),i=this._model.finalSelectionStart,s=this._model.finalSelectionEnd;return!i||!s||!t?!1:this._areCoordsInSelection(t,i,s)}isCellInSelection(e,t){let i=this._model.finalSelectionStart,s=this._model.finalSelectionEnd;return!i||!s?!1:this._areCoordsInSelection([e,t],i,s)}_areCoordsInSelection(e,t,i){return e[1]>t[1]&&e[1]=t[0]&&e[0]=t[0]}_selectWordAtCursor(e,t){var a,o;let i=(o=(a=this._linkifier.currentLink)==null?void 0:a.link)==null?void 0:o.range;if(i)return this._model.selectionStart=[i.start.x-1,i.start.y-1],this._model.selectionStartLength=Lb(i,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let s=this._getMouseBufferCoords(e);return s?(this._selectWordAt(s,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=Qp(this._coreBrowserService.window,e,this._screenElement)[1],i=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=i?0:(t>i&&(t-=i),t=Math.min(Math.max(t,-of),of),t/=of,t/Math.abs(t)+Math.round(t*($2-1)))}shouldForceSelection(e){return Au?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),F2)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(Au&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let i=this._bufferService.buffer;if(this._model.selectionEnd[1]0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&tthis._handleTrim(t))}_convertViewportColToCharacterIndex(e,t){let i=t;for(let s=0;t>=s;s++){let a=e.loadCell(s,this._workCell).getChars().length;this._workCell.getWidth()===0?i--:a>1&&t!==s&&(i+=a-1)}return i}setSelection(e,t,i){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=i,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,i=!0,s=!0){if(e[0]>=this._bufferService.cols)return;let a=this._bufferService.buffer,o=a.lines.get(e[1]);if(!o)return;let c=a.translateBufferLineToString(e[1],!1),h=this._convertViewportColToCharacterIndex(o,e[0]),p=h,f=e[0]-h,_=0,x=0,b=0,v=0;if(c.charAt(h)===" "){for(;h>0&&c.charAt(h-1)===" ";)h--;for(;p1&&(v+=L-1,p+=L-1);M>0&&h>0&&!this._isCharWordSeparator(o.loadCell(M-1,this._workCell));){o.loadCell(M-1,this._workCell);let I=this._workCell.getChars().length;this._workCell.getWidth()===0?(_++,M--):I>1&&(b+=I-1,h-=I-1),h--,M--}for(;E1&&(v+=I-1,p+=I-1),p++,E++}}p++;let S=h+f-_+b,N=Math.min(this._bufferService.cols,p-h+_+x-b-v);if(!(!t&&c.slice(h,p).trim()==="")){if(i&&S===0&&o.getCodePoint(0)!==32){let M=a.lines.get(e[1]-1);if(M&&o.isWrapped&&M.getCodePoint(this._bufferService.cols-1)!==32){let E=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(E){let L=this._bufferService.cols-E.start;S-=L,N+=L}}}if(s&&S+N===this._bufferService.cols&&o.getCodePoint(this._bufferService.cols-1)!==32){let M=a.lines.get(e[1]+1);if(M!=null&&M.isWrapped&&M.getCodePoint(0)!==32){let E=this._getWordAt([0,e[1]+1],!1,!1,!0);E&&(N+=E.length)}}return{start:S,length:N}}}_selectWordAt(e,t){let i=this._getWordAt(e,t);if(i){for(;i.start<0;)i.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[i.start,e[1]],this._model.selectionStartLength=i.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let i=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,i--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,i++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,i]}}_isCharWordSeparator(e){return e.getWidth()===0?!1:this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),i={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=Lb(i,this._bufferService.cols)}};pp=fi([Re(3,_n),Re(4,va),Re(5,Wp),Re(6,bn),Re(7,ls),Re(8,as)],pp);var Ob=class{constructor(){this._data={}}set(e,t,i){this._data[e]||(this._data[e]={}),this._data[e][t]=i}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},zb=class{constructor(){this._color=new Ob,this._css=new Ob}setCss(e,t,i){this._css.set(e,t,i)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,i){this._color.set(e,t,i)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},Li=Object.freeze((()=>{let e=[ai.toColor("#2e3436"),ai.toColor("#cc0000"),ai.toColor("#4e9a06"),ai.toColor("#c4a000"),ai.toColor("#3465a4"),ai.toColor("#75507b"),ai.toColor("#06989a"),ai.toColor("#d3d7cf"),ai.toColor("#555753"),ai.toColor("#ef2929"),ai.toColor("#8ae234"),ai.toColor("#fce94f"),ai.toColor("#729fcf"),ai.toColor("#ad7fa8"),ai.toColor("#34e2e2"),ai.toColor("#eeeeec")],t=[0,95,135,175,215,255];for(let i=0;i<216;i++){let s=t[i/36%6|0],a=t[i/6%6|0],o=t[i%6];e.push({css:Ai.toCss(s,a,o),rgba:Ai.toRgba(s,a,o)})}for(let i=0;i<24;i++){let s=8+i*10;e.push({css:Ai.toCss(s,s,s),rgba:Ai.toRgba(s,s,s)})}return e})()),fa=ai.toColor("#ffffff"),Co=ai.toColor("#000000"),Pb=ai.toColor("#ffffff"),Ib=Co,po={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117},Y2=fa,mp=class extends ht{constructor(e){super(),this._optionsService=e,this._contrastCache=new zb,this._halfContrastCache=new zb,this._onChangeColors=this._register(new ke),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:fa,background:Co,cursor:Pb,cursorAccent:Ib,selectionForeground:void 0,selectionBackgroundTransparent:po,selectionBackgroundOpaque:ti.blend(Co,po),selectionInactiveBackgroundTransparent:po,selectionInactiveBackgroundOpaque:ti.blend(Co,po),scrollbarSliderBackground:ti.opacity(fa,.2),scrollbarSliderHoverBackground:ti.opacity(fa,.4),scrollbarSliderActiveBackground:ti.opacity(fa,.5),overviewRulerBorder:fa,ansi:Li.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange("minimumContrastRatio",()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange("theme",()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(e={}){let t=this._colors;if(t.foreground=It(e.foreground,fa),t.background=It(e.background,Co),t.cursor=ti.blend(t.background,It(e.cursor,Pb)),t.cursorAccent=ti.blend(t.background,It(e.cursorAccent,Ib)),t.selectionBackgroundTransparent=It(e.selectionBackground,po),t.selectionBackgroundOpaque=ti.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=It(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=ti.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?It(e.selectionForeground,Db):void 0,t.selectionForeground===Db&&(t.selectionForeground=void 0),ti.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=ti.opacity(t.selectionBackgroundTransparent,.3)),ti.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=ti.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=It(e.scrollbarSliderBackground,ti.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=It(e.scrollbarSliderHoverBackground,ti.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=It(e.scrollbarSliderActiveBackground,ti.opacity(t.foreground,.5)),t.overviewRulerBorder=It(e.overviewRulerBorder,Y2),t.ansi=Li.slice(),t.ansi[0]=It(e.black,Li[0]),t.ansi[1]=It(e.red,Li[1]),t.ansi[2]=It(e.green,Li[2]),t.ansi[3]=It(e.yellow,Li[3]),t.ansi[4]=It(e.blue,Li[4]),t.ansi[5]=It(e.magenta,Li[5]),t.ansi[6]=It(e.cyan,Li[6]),t.ansi[7]=It(e.white,Li[7]),t.ansi[8]=It(e.brightBlack,Li[8]),t.ansi[9]=It(e.brightRed,Li[9]),t.ansi[10]=It(e.brightGreen,Li[10]),t.ansi[11]=It(e.brightYellow,Li[11]),t.ansi[12]=It(e.brightBlue,Li[12]),t.ansi[13]=It(e.brightMagenta,Li[13]),t.ansi[14]=It(e.brightCyan,Li[14]),t.ansi[15]=It(e.brightWhite,Li[15]),e.extendedAnsi){let i=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let s=0;so.index-c.index),s=[];for(let o of i){let c=this._services.get(o.id);if(!c)throw new Error(`[createInstance] ${e.name} depends on UNKNOWN service ${o.id._id}.`);s.push(c)}let a=i.length>0?i[0].index:t.length;if(t.length!==a)throw new Error(`[createInstance] First service dependency of ${e.name} at position ${a+1} conflicts with ${t.length} static arguments`);return new e(...t,...s)}},X2={trace:0,debug:1,info:2,warn:3,error:4,off:5},Z2="xterm.js: ",gp=class extends ht{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange("logLevel",()=>this._updateLogLevel()))}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=X2[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;tthis._length)for(let t=this._length;t=e;s--)this._array[this._getCyclicIndex(s+i.length)]=this._array[this._getCyclicIndex(s)];for(let s=0;sthis._maxLength){let s=this._length+i.length-this._maxLength;this._startIndex+=s,this._length=this._maxLength,this.onTrimEmitter.fire(s)}else this._length+=i.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,i){if(!(t<=0)){if(e<0||e>=this._length)throw new Error("start argument out of range");if(e+i<0)throw new Error("Cannot shift elements in list beyond index 0");if(i>0){for(let a=t-1;a>=0;a--)this.set(e+a+i,this.get(e+a));let s=e+t+i-this._length;if(s>0)for(this._length+=s;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let s=0;s>22,i&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):s]}set(t,i){this._data[t*ut+1]=i[0],i[1].length>1?(this._combined[t]=i[1],this._data[t*ut+0]=t|2097152|i[2]<<22):this._data[t*ut+0]=i[1].charCodeAt(0)|i[2]<<22}getWidth(t){return this._data[t*ut+0]>>22}hasWidth(t){return this._data[t*ut+0]&12582912}getFg(t){return this._data[t*ut+1]}getBg(t){return this._data[t*ut+2]}hasContent(t){return this._data[t*ut+0]&4194303}getCodePoint(t){let i=this._data[t*ut+0];return i&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):i&2097151}isCombined(t){return this._data[t*ut+0]&2097152}getString(t){let i=this._data[t*ut+0];return i&2097152?this._combined[t]:i&2097151?Ps(i&2097151):""}isProtected(t){return this._data[t*ut+2]&536870912}loadCell(t,i){return lu=t*ut,i.content=this._data[lu+0],i.fg=this._data[lu+1],i.bg=this._data[lu+2],i.content&2097152&&(i.combinedData=this._combined[t]),i.bg&268435456&&(i.extended=this._extendedAttrs[t]),i}setCell(t,i){i.content&2097152&&(this._combined[t]=i.combinedData),i.bg&268435456&&(this._extendedAttrs[t]=i.extended),this._data[t*ut+0]=i.content,this._data[t*ut+1]=i.fg,this._data[t*ut+2]=i.bg}setCellFromCodepoint(t,i,s,a){a.bg&268435456&&(this._extendedAttrs[t]=a.extended),this._data[t*ut+0]=i|s<<22,this._data[t*ut+1]=a.fg,this._data[t*ut+2]=a.bg}addCodepointToCell(t,i,s){let a=this._data[t*ut+0];a&2097152?this._combined[t]+=Ps(i):a&2097151?(this._combined[t]=Ps(a&2097151)+Ps(i),a&=-2097152,a|=2097152):a=i|1<<22,s&&(a&=-12582913,a|=s<<22),this._data[t*ut+0]=a}insertCells(t,i,s){if(t%=this.length,t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,s),i=0;--o)this.setCell(t+i+o,this.loadCell(t+o,a));for(let o=0;othis.length){if(this._data.buffer.byteLength>=s*4)this._data=new Uint32Array(this._data.buffer,0,s);else{let a=new Uint32Array(s);a.set(this._data),this._data=a}for(let a=this.length;a=t&&delete this._combined[h]}let o=Object.keys(this._extendedAttrs);for(let c=0;c=t&&delete this._extendedAttrs[h]}}return this.length=t,s*4*cf=0;--t)if(this._data[t*ut+0]&4194303)return t+(this._data[t*ut+0]>>22);return 0}getNoBgTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*ut+0]&4194303||this._data[t*ut+2]&50331648)return t+(this._data[t*ut+0]>>22);return 0}copyCellsFrom(t,i,s,a,o){let c=t._data;if(o)for(let p=a-1;p>=0;p--){for(let f=0;f=i&&(this._combined[f-i+s]=t._combined[f])}}translateToString(t,i,s,a){i=i??0,s=s??this.length,t&&(s=Math.min(s,this.getTrimmedLength())),a&&(a.length=0);let o="";for(;i>22||1}return a&&a.push(i),o}};function Q2(e,t,i,s,a,o){let c=[];for(let h=0;h=h&&s0&&(M>x||_[M].getTrimmedLength()===0);M--)N++;N>0&&(c.push(h+_.length-N),c.push(N)),h+=_.length-1}return c}function J2(e,t){let i=[],s=0,a=t[s],o=0;for(let c=0;czo(e,f,t)).reduce((p,f)=>p+f),o=0,c=0,h=0;for(;hp&&(o-=p,c++);let f=e[c].getWidth(o-1)===2;f&&o--;let _=f?i-1:i;s.push(_),h+=_}return s}function zo(e,t,i){if(t===e.length-1)return e[t].getTrimmedLength();let s=!e[t].hasContent(i-1)&&e[t].getWidth(i-1)===1,a=e[t+1].getWidth(0)===2;return s&&a?i-1:i}var _0=class b0{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=b0._nextId++,this._onDispose=this.register(new ke),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),xa(this._disposables),this._disposables.length=0)}register(t){return this._disposables.push(t),t}};_0._nextId=1;var iE=_0,Pi={},pa=Pi.B;Pi[0]={"`":"◆",a:"▒",b:"␉",c:"␌",d:"␍",e:"␊",f:"°",g:"±",h:"␤",i:"␋",j:"┘",k:"┐",l:"┌",m:"└",n:"┼",o:"⎺",p:"⎻",q:"─",r:"⎼",s:"⎽",t:"├",u:"┤",v:"┴",w:"┬",x:"│",y:"≤",z:"≥","{":"π","|":"≠","}":"£","~":"·"};Pi.A={"#":"£"};Pi.B=void 0;Pi[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"};Pi.C=Pi[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};Pi.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"};Pi.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"};Pi.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"};Pi.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"};Pi.E=Pi[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"};Pi.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"};Pi.H=Pi[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};Pi["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"};var Ub=4294967295,$b=class{constructor(e,t,i){this._hasScrollback=e,this._optionsService=t,this._bufferService=i,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=Ti.clone(),this.savedCharset=pa,this.markers=[],this._nullCell=or.fromCharData([0,Oy,1,0]),this._whitespaceCell=or.fromCharData([0,Hs,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new Ru,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new Hb(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new Nu),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new Nu),this._whitespaceCell}getBlankLine(e,t){return new ko(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&eUb?Ub:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=Ti);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new Hb(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let i=this.getNullCell(Ti),s=0,a=this._getCorrectBufferLength(t);if(a>this.lines.maxLength&&(this.lines.maxLength=a),this.lines.length>0){if(this._cols0&&this.lines.length<=this.ybase+this.y+o+1?(this.ybase--,o++,this.ydisp>0&&this.ydisp--):this.lines.push(new ko(e,i)));else for(let c=this._rows;c>t;c--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(a0&&(this.lines.trimStart(c),this.ybase=Math.max(this.ybase-c,0),this.ydisp=Math.max(this.ydisp-c,0),this.savedY=Math.max(this.savedY-c,0)),this.lines.maxLength=a}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),o&&(this.y+=o),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let o=0;o.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend==="conpty"&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let i=this._optionsService.rawOptions.reflowCursorLine,s=Q2(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(Ti),i);if(s.length>0){let a=J2(this.lines,s);eE(this.lines,a.layout),this._reflowLargerAdjustViewport(e,t,a.countRemoved)}}_reflowLargerAdjustViewport(e,t,i){let s=this.getNullCell(Ti),a=i;for(;a-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length=0;c--){let h=this.lines.get(c);if(!h||!h.isWrapped&&h.getTrimmedLength()<=e)continue;let p=[h];for(;h.isWrapped&&c>0;)h=this.lines.get(--c),p.unshift(h);if(!i){let I=this.ybase+this.y;if(I>=c&&I0&&(a.push({start:c+p.length+o,newLines:v}),o+=v.length),p.push(...v);let S=_.length-1,N=_[S];N===0&&(S--,N=_[S]);let M=p.length-x-1,E=f;for(;M>=0;){let I=Math.min(E,N);if(p[S]===void 0)break;if(p[S].copyCellsFrom(p[M],E-I,N-I,I,!0),N-=I,N===0&&(S--,N=_[S]),E-=I,E===0){M--;let A=Math.max(M,0);E=zo(p,A,this._cols)}}for(let I=0;I0;)this.ybase===0?this.y0){let c=[],h=[];for(let N=0;N=0;N--)if(x&&x.start>f+b){for(let M=x.newLines.length-1;M>=0;M--)this.lines.set(N--,x.newLines[M]);N++,c.push({index:f+1,amount:x.newLines.length}),b+=x.newLines.length,x=a[++_]}else this.lines.set(N,h[f--]);let v=0;for(let N=c.length-1;N>=0;N--)c[N].index+=v,this.lines.onInsertEmitter.fire(c[N]),v+=c[N].amount;let S=Math.max(0,p+o-this.lines.maxLength);S>0&&this.lines.onTrimEmitter.fire(S)}}translateBufferLineToString(e,t,i=0,s){let a=this.lines.get(e);return a?a.translateToString(t,i,s):""}getWrappedRangeForLine(e){let t=e,i=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;i+10;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e==null&&(e=this.x);!this.tabs[++e]&&e=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t{t.line-=i,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(i=>{t.line>=i.index&&(t.line+=i.amount)})),t.register(this.lines.onDelete(i=>{t.line>=i.index&&t.linei.index&&(t.line-=i.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},nE=class extends ht{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new ke),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this._register(this._optionsService.onSpecificOptionChange("scrollback",()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this._register(this._optionsService.onSpecificOptionChange("tabStopWidth",()=>this.setupTabStops()))}reset(){this._normal=new $b(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new $b(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}},v0=2,y0=1,xp=class extends ht{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new ke),this.onResize=this._onResize.event,this._onScroll=this._register(new ke),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,v0),this.rows=Math.max(e.rawOptions.rows||0,y0),this.buffers=this._register(new nE(e,this)),this._register(this.buffers.onBufferActivate(t=>{this._onScroll.fire(t.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let i=this.cols!==e,s=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:i,rowsChanged:s})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let i=this.buffer,s;s=this._cachedBlankLine,(!s||s.length!==this.cols||s.getFg(0)!==e.fg||s.getBg(0)!==e.bg)&&(s=i.getBlankLine(e,t),this._cachedBlankLine=s),s.isWrapped=t;let a=i.ybase+i.scrollTop,o=i.ybase+i.scrollBottom;if(i.scrollTop===0){let c=i.lines.isFull;o===i.lines.length-1?c?i.lines.recycle().copyFrom(s):i.lines.push(s.clone()):i.lines.splice(o+1,0,s.clone()),c?this.isUserScrolling&&(i.ydisp=Math.max(i.ydisp-1,0)):(i.ybase++,this.isUserScrolling||i.ydisp++)}else{let c=o-a+1;i.lines.shiftElements(a+1,c-1,-1),i.lines.set(o,s.clone())}this.isUserScrolling||(i.ydisp=i.ybase),this._onScroll.fire(i.ydisp)}scrollLines(e,t){let i=this.buffer;if(e<0){if(i.ydisp===0)return;this.isUserScrolling=!0}else e+i.ydisp>=i.ybase&&(this.isUserScrolling=!1);let s=i.ydisp;i.ydisp=Math.max(Math.min(i.ydisp+e,i.ybase),0),s!==i.ydisp&&(t||this._onScroll.fire(i.ydisp))}};xp=fi([Re(0,bn)],xp);var il={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:Au,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}},rE=["normal","bold","100","200","300","400","500","600","700","800","900"],sE=class extends ht{constructor(e){super(),this._onOptionChange=this._register(new ke),this.onOptionChange=this._onOptionChange.event;let t={...il};for(let i in e)if(i in t)try{let s=e[i];t[i]=this._sanitizeAndValidateOption(i,s)}catch(s){console.error(s)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register(ni(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(i=>{i===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(i=>{e.indexOf(i)!==-1&&t()})}_setupOptions(){let e=i=>{if(!(i in il))throw new Error(`No option with key "${i}"`);return this.rawOptions[i]},t=(i,s)=>{if(!(i in il))throw new Error(`No option with key "${i}"`);s=this._sanitizeAndValidateOption(i,s),this.rawOptions[i]!==s&&(this.rawOptions[i]=s,this._onOptionChange.fire(i))};for(let i in this.rawOptions){let s={get:e.bind(this,i),set:t.bind(this,i)};Object.defineProperty(this.options,i,s)}}_sanitizeAndValidateOption(e,t){switch(e){case"cursorStyle":if(t||(t=il[e]),!aE(t))throw new Error(`"${t}" is not a valid value for ${e}`);break;case"wordSeparator":t||(t=il[e]);break;case"fontWeight":case"fontWeightBold":if(typeof t=="number"&&1<=t&&t<=1e3)break;t=rE.includes(t)?t:il[e];break;case"cursorWidth":t=Math.floor(t);case"lineHeight":case"tabStopWidth":if(t<1)throw new Error(`${e} cannot be less than 1, value: ${t}`);break;case"minimumContrastRatio":t=Math.max(1,Math.min(21,Math.round(t*10)/10));break;case"scrollback":if(t=Math.min(t,4294967295),t<0)throw new Error(`${e} cannot be less than 0, value: ${t}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(t<=0)throw new Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case"rows":case"cols":if(!t&&t!==0)throw new Error(`${e} must be numeric, value: ${t}`);break;case"windowsPty":t=t??{};break}return t}};function aE(e){return e==="block"||e==="underline"||e==="bar"}function Eo(e,t=5){if(typeof e!="object")return e;let i=Array.isArray(e)?[]:{};for(let s in e)i[s]=t<=1?e[s]:e[s]&&Eo(e[s],t-1);return i}var Fb=Object.freeze({insertMode:!1}),qb=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),_p=class extends ht{constructor(e,t,i){super(),this._bufferService=e,this._logService=t,this._optionsService=i,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new ke),this.onData=this._onData.event,this._onUserInput=this._register(new ke),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new ke),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new ke),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=Eo(Fb),this.decPrivateModes=Eo(qb)}reset(){this.modes=Eo(Fb),this.decPrivateModes=Eo(qb)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let i=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&i.ybase!==i.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace("sending data (codes)",()=>e.split("").map(s=>s.charCodeAt(0))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace("sending binary (codes)",()=>e.split("").map(t=>t.charCodeAt(0))),this._onBinary.fire(e))}};_p=fi([Re(0,_n),Re(1,Uy),Re(2,bn)],_p);var Wb={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>e.button===4||e.action!==1?!1:(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>e.action!==32},DRAG:{events:23,restrict:e=>!(e.action===32&&e.button===3)},ANY:{events:31,restrict:e=>!0}};function uf(e,t){let i=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(i|=64,i|=e.action):(i|=e.button&3,e.button&4&&(i|=64),e.button&8&&(i|=128),e.action===32?i|=32:e.action===0&&!t&&(i|=3)),i}var hf=String.fromCharCode,Gb={DEFAULT:e=>{let t=[uf(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`\x1B[M${hf(t[0])}${hf(t[1])}${hf(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${uf(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${uf(e,!0)};${e.x};${e.y}${t}`}},bp=class extends ht{constructor(e,t,i){super(),this._bufferService=e,this._coreService=t,this._optionsService=i,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new ke),this.onProtocolChange=this._onProtocolChange.event;for(let s of Object.keys(Wb))this.addProtocol(s,Wb[s]);for(let s of Object.keys(Gb))this.addEncoding(s,Gb[s]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw new Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw new Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,i){if(e.deltaY===0||e.shiftKey||t===void 0||i===void 0)return 0;let s=t/i,a=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(a/=s+0,Math.abs(e.deltaY)<50&&(a*=.3),this._wheelPartialScroll+=a,a=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(a*=this._bufferService.rows),a}_applyScrollModifier(e,t){return t.altKey||t.ctrlKey||t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding==="SGR_PIXELS"))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(e&1),up:!!(e&2),drag:!!(e&4),move:!!(e&8),wheel:!!(e&16)}}_equalEvents(e,t,i){if(i){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return!(e.button!==t.button||e.action!==t.action||e.ctrl!==t.ctrl||e.alt!==t.alt||e.shift!==t.shift)}};bp=fi([Re(0,_n),Re(1,va),Re(2,bn)],bp);var df=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],lE=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],Oi;function oE(e,t){let i=0,s=t.length-1,a;if(et[s][1])return!1;for(;s>=i;)if(a=i+s>>1,e>t[a][1])i=a+1;else if(e=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let i=this.wcwidth(e),s=i===0&&t!==0;if(s){let a=ma.extractWidth(t);a===0?s=!1:a>i&&(i=a)}return ma.createPropertyValue(0,i,s)}},ma=class yu{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new ke,this.onChange=this._onChange.event;let t=new cE;this.register(t),this._active=t.version,this._activeProvider=t}static extractShouldJoin(t){return(t&1)!==0}static extractWidth(t){return t>>1&3}static extractCharKind(t){return t>>3}static createPropertyValue(t,i,s=!1){return(t&16777215)<<3|(i&3)<<1|(s?1:0)}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(t){if(!this._providers[t])throw new Error(`unknown Unicode version "${t}"`);this._active=t,this._activeProvider=this._providers[t],this._onChange.fire(t)}register(t){this._providers[t.version]=t}wcwidth(t){return this._activeProvider.wcwidth(t)}getStringCellWidth(t){let i=0,s=0,a=t.length;for(let o=0;o=a)return i+this.wcwidth(c);let f=t.charCodeAt(o);56320<=f&&f<=57343?c=(c-55296)*1024+f-56320+65536:i+=this.wcwidth(f)}let h=this.charProperties(c,s),p=yu.extractWidth(h);yu.extractShouldJoin(h)&&(p-=yu.extractWidth(s)),i+=p,s=h}return i}charProperties(t,i){return this._activeProvider.charProperties(t,i)}},uE=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}};function Yb(e){var s;let t=(s=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1))==null?void 0:s.get(e.cols-1),i=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);i&&t&&(i.isWrapped=t[3]!==0&&t[3]!==32)}var mo=2147483647,hE=256,S0=class vp{constructor(t=32,i=32){if(this.maxLength=t,this.maxSubParamsLength=i,i>hE)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(t),this.length=0,this._subParams=new Int32Array(i),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(t),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let i=new vp;if(!t.length)return i;for(let s=Array.isArray(t[0])?1:0;s>8,a=this._subParamsIdx[i]&255;a-s>0&&t.push(Array.prototype.slice.call(this._subParams,s,a))}return t}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(t){if(this._digitIsSub=!1,this.length>=this.maxLength){this._rejectDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=t>mo?mo:t}addSubParam(t){if(this._digitIsSub=!0,!!this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=t>mo?mo:t,this._subParamsIdx[this.length-1]++}}hasSubParams(t){return(this._subParamsIdx[t]&255)-(this._subParamsIdx[t]>>8)>0}getSubParams(t){let i=this._subParamsIdx[t]>>8,s=this._subParamsIdx[t]&255;return s-i>0?this._subParams.subarray(i,s):null}getSubParamsAll(){let t={};for(let i=0;i>8,a=this._subParamsIdx[i]&255;a-s>0&&(t[i]=this._subParams.slice(s,a))}return t}addDigit(t){let i;if(this._rejectDigits||!(i=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let s=this._digitIsSub?this._subParams:this.params,a=s[i-1];s[i-1]=~a?Math.min(a*10+t,mo):t}},go=[],dE=class{constructor(){this._state=0,this._active=go,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let i=this._handlers[e];return i.push(t),{dispose:()=>{let s=i.indexOf(t);s!==-1&&i.splice(s,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=go}reset(){if(this._state===2)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=go,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||go,!this._active.length)this._handlerFb(this._id,"START");else for(let e=this._active.length-1;e>=0;e--)this._active[e].start()}_put(e,t,i){if(!this._active.length)this._handlerFb(this._id,"PUT",Iu(e,t,i));else for(let s=this._active.length-1;s>=0;s--)this._active[s].put(e,t,i)}start(){this.reset(),this._state=1}put(e,t,i){if(this._state!==3){if(this._state===1)for(;t0&&this._put(e,t,i)}}end(e,t=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),!this._active.length)this._handlerFb(this._id,"END",e);else{let i=!1,s=this._active.length-1,a=!1;if(this._stack.paused&&(s=this._stack.loopPosition-1,i=t,a=this._stack.fallThrough,this._stack.paused=!1),!a&&i===!1){for(;s>=0&&(i=this._active[s].end(e),i!==!0);s--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!1,i;s--}for(;s>=0;s--)if(i=this._active[s].end(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!0,i}this._active=go,this._id=-1,this._state=0}}},Wn=class{constructor(e){this._handler=e,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=Iu(e,t,i),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then(i=>(this._data="",this._hitLimit=!1,i));return this._data="",this._hitLimit=!1,t}},xo=[],fE=class{constructor(){this._handlers=Object.create(null),this._active=xo,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=xo}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let i=this._handlers[e];return i.push(t),{dispose:()=>{let s=i.indexOf(t);s!==-1&&i.splice(s,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=xo,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||xo,!this._active.length)this._handlerFb(this._ident,"HOOK",t);else for(let i=this._active.length-1;i>=0;i--)this._active[i].hook(t)}put(e,t,i){if(!this._active.length)this._handlerFb(this._ident,"PUT",Iu(e,t,i));else for(let s=this._active.length-1;s>=0;s--)this._active[s].put(e,t,i)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,"UNHOOK",e);else{let i=!1,s=this._active.length-1,a=!1;if(this._stack.paused&&(s=this._stack.loopPosition-1,i=t,a=this._stack.fallThrough,this._stack.paused=!1),!a&&i===!1){for(;s>=0&&(i=this._active[s].unhook(e),i!==!0);s--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!1,i;s--}for(;s>=0;s--)if(i=this._active[s].unhook(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!0,i}this._active=xo,this._ident=0}},No=new S0;No.addParam(0);var Vb=class{constructor(e){this._handler=e,this._data="",this._params=No,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():No,this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=Iu(e,t,i),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then(i=>(this._params=No,this._data="",this._hitLimit=!1,i));return this._params=No,this._data="",this._hitLimit=!1,t}},pE=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,i,s){this.table[t<<8|e]=i<<4|s}addMany(e,t,i,s){for(let a=0;ap),i=(h,p)=>t.slice(h,p),s=i(32,127),a=i(0,24);a.push(25),a.push.apply(a,i(28,32));let o=i(0,14),c;e.setDefault(1,0),e.addMany(s,0,2,0);for(c in o)e.addMany([24,26,153,154],c,3,0),e.addMany(i(128,144),c,3,0),e.addMany(i(144,152),c,3,0),e.add(156,c,0,0),e.add(27,c,11,1),e.add(157,c,4,8),e.addMany([152,158,159],c,0,7),e.add(155,c,11,3),e.add(144,c,11,9);return e.addMany(a,0,3,0),e.addMany(a,1,3,1),e.add(127,1,0,1),e.addMany(a,8,0,8),e.addMany(a,3,3,3),e.add(127,3,0,3),e.addMany(a,4,3,4),e.add(127,4,0,4),e.addMany(a,6,3,6),e.addMany(a,5,3,5),e.add(127,5,0,5),e.addMany(a,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(s,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(i(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(s,7,0,7),e.addMany(a,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(i(64,127),3,7,0),e.addMany(i(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(i(48,60),4,8,4),e.addMany(i(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(i(32,64),6,0,6),e.add(127,6,0,6),e.addMany(i(64,127),6,0,0),e.addMany(i(32,48),3,9,5),e.addMany(i(32,48),5,9,5),e.addMany(i(48,64),5,0,6),e.addMany(i(64,127),5,7,0),e.addMany(i(32,48),4,9,5),e.addMany(i(32,48),1,9,2),e.addMany(i(32,48),2,9,2),e.addMany(i(48,127),2,10,0),e.addMany(i(48,80),1,10,0),e.addMany(i(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(i(96,127),1,10,0),e.add(80,1,11,9),e.addMany(a,9,0,9),e.add(127,9,0,9),e.addMany(i(28,32),9,0,9),e.addMany(i(32,48),9,9,12),e.addMany(i(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(a,11,0,11),e.addMany(i(32,128),11,0,11),e.addMany(i(28,32),11,0,11),e.addMany(a,10,0,10),e.add(127,10,0,10),e.addMany(i(28,32),10,0,10),e.addMany(i(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(i(32,48),10,9,12),e.addMany(a,12,0,12),e.add(127,12,0,12),e.addMany(i(28,32),12,0,12),e.addMany(i(32,48),12,9,12),e.addMany(i(48,64),12,0,11),e.addMany(i(64,127),12,12,13),e.addMany(i(64,127),10,12,13),e.addMany(i(64,127),9,12,13),e.addMany(a,13,13,13),e.addMany(s,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(ar,0,2,0),e.add(ar,8,5,8),e.add(ar,6,0,6),e.add(ar,11,0,11),e.add(ar,13,13,13),e})(),gE=class extends ht{constructor(e=mE){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new S0,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(t,i,s)=>{},this._executeHandlerFb=t=>{},this._csiHandlerFb=(t,i)=>{},this._escHandlerFb=t=>{},this._errorHandlerFb=t=>t,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register(ni(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new dE),this._dcsParser=this._register(new fE),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},()=>!0)}_identifier(e,t=[64,126]){let i=0;if(e.prefix){if(e.prefix.length>1)throw new Error("only one byte as prefix supported");if(i=e.prefix.charCodeAt(0),i&&60>i||i>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(e.intermediates){if(e.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let a=0;ao||o>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");i<<=8,i|=o}}if(e.final.length!==1)throw new Error("final must be a single byte");let s=e.final.charCodeAt(0);if(t[0]>s||s>t[1])throw new Error(`final must be in range ${t[0]} .. ${t[1]}`);return i<<=8,i|=s,i}identToString(e){let t=[];for(;e;)t.push(String.fromCharCode(e&255)),e>>=8;return t.reverse().join("")}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){let i=this._identifier(e,[48,126]);this._escHandlers[i]===void 0&&(this._escHandlers[i]=[]);let s=this._escHandlers[i];return s.push(t),{dispose:()=>{let a=s.indexOf(t);a!==-1&&s.splice(a,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){let i=this._identifier(e);this._csiHandlers[i]===void 0&&(this._csiHandlers[i]=[]);let s=this._csiHandlers[i];return s.push(t),{dispose:()=>{let a=s.indexOf(t);a!==-1&&s.splice(a,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,i,s,a){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=i,this._parseStack.transition=s,this._parseStack.chunkPos=a}parse(e,t,i){let s=0,a=0,o=0,c;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,o=this._parseStack.chunkPos+1;else{if(i===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");let h=this._parseStack.handlers,p=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(i===!1&&p>-1){for(;p>=0&&(c=h[p](this._params),c!==!0);p--)if(c instanceof Promise)return this._parseStack.handlerPos=p,c}this._parseStack.handlers=[];break;case 4:if(i===!1&&p>-1){for(;p>=0&&(c=h[p](),c!==!0);p--)if(c instanceof Promise)return this._parseStack.handlerPos=p,c}this._parseStack.handlers=[];break;case 6:if(s=e[this._parseStack.chunkPos],c=this._dcsParser.unhook(s!==24&&s!==26,i),c)return c;s===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(s=e[this._parseStack.chunkPos],c=this._oscParser.end(s!==24&&s!==26,i),c)return c;s===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break}this._parseStack.state=0,o=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}for(let h=o;h>4){case 2:for(let b=h+1;;++b){if(b>=t||(s=e[b])<32||s>126&&s=t||(s=e[b])<32||s>126&&s=t||(s=e[b])<32||s>126&&s=t||(s=e[b])<32||s>126&&s=0&&(c=p[f](this._params),c!==!0);f--)if(c instanceof Promise)return this._preserveStack(3,p,f,a,h),c;f<0&&this._csiHandlerFb(this._collect<<8|s,this._params),this.precedingJoinState=0;break;case 8:do switch(s){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(s-48)}while(++h47&&s<60);h--;break;case 9:this._collect<<=8,this._collect|=s;break;case 10:let _=this._escHandlers[this._collect<<8|s],x=_?_.length-1:-1;for(;x>=0&&(c=_[x](),c!==!0);x--)if(c instanceof Promise)return this._preserveStack(4,_,x,a,h),c;x<0&&this._escHandlerFb(this._collect<<8|s),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|s,this._params);break;case 13:for(let b=h+1;;++b)if(b>=t||(s=e[b])===24||s===26||s===27||s>127&&s=t||(s=e[b])<32||s>127&&s>4:o>>8}return s}}function ff(e,t){let i=e.toString(16),s=i.length<2?"0"+i:i;switch(t){case 4:return i[0];case 8:return s;case 12:return(s+s).slice(0,3);default:return s+s}}function bE(e,t=16){let[i,s,a]=e;return`rgb:${ff(i,t)}/${ff(s,t)}/${ff(a,t)}`}var vE={"(":0,")":1,"*":2,"+":3,"-":1,".":2},Os=131072,Xb=10;function Zb(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var Qb=5e3,Jb=0,yE=class extends ht{constructor(e,t,i,s,a,o,c,h,p=new gE){super(),this._bufferService=e,this._charsetService=t,this._coreService=i,this._logService=s,this._optionsService=a,this._oscLinkService=o,this._coreMouseService=c,this._unicodeService=h,this._parser=p,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new HC,this._utf8Decoder=new UC,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=Ti.clone(),this._eraseAttrDataInternal=Ti.clone(),this._onRequestBell=this._register(new ke),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new ke),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new ke),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new ke),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new ke),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new ke),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new ke),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new ke),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new ke),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new ke),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new ke),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new ke),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new ke),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this._register(this._parser),this._dirtyRowTracker=new yp(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(f=>this._activeBuffer=f.activeBuffer)),this._parser.setCsiHandlerFallback((f,_)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(f),params:_.toArray()})}),this._parser.setEscHandlerFallback(f=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(f)})}),this._parser.setExecuteHandlerFallback(f=>{this._logService.debug("Unknown EXECUTE code: ",{code:f})}),this._parser.setOscHandlerFallback((f,_,x)=>{this._logService.debug("Unknown OSC code: ",{identifier:f,action:_,data:x})}),this._parser.setDcsHandlerFallback((f,_,x)=>{_==="HOOK"&&(x=x.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(f),action:_,payload:x})}),this._parser.setPrintHandler((f,_,x)=>this.print(f,_,x)),this._parser.registerCsiHandler({final:"@"},f=>this.insertChars(f)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},f=>this.scrollLeft(f)),this._parser.registerCsiHandler({final:"A"},f=>this.cursorUp(f)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},f=>this.scrollRight(f)),this._parser.registerCsiHandler({final:"B"},f=>this.cursorDown(f)),this._parser.registerCsiHandler({final:"C"},f=>this.cursorForward(f)),this._parser.registerCsiHandler({final:"D"},f=>this.cursorBackward(f)),this._parser.registerCsiHandler({final:"E"},f=>this.cursorNextLine(f)),this._parser.registerCsiHandler({final:"F"},f=>this.cursorPrecedingLine(f)),this._parser.registerCsiHandler({final:"G"},f=>this.cursorCharAbsolute(f)),this._parser.registerCsiHandler({final:"H"},f=>this.cursorPosition(f)),this._parser.registerCsiHandler({final:"I"},f=>this.cursorForwardTab(f)),this._parser.registerCsiHandler({final:"J"},f=>this.eraseInDisplay(f,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},f=>this.eraseInDisplay(f,!0)),this._parser.registerCsiHandler({final:"K"},f=>this.eraseInLine(f,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},f=>this.eraseInLine(f,!0)),this._parser.registerCsiHandler({final:"L"},f=>this.insertLines(f)),this._parser.registerCsiHandler({final:"M"},f=>this.deleteLines(f)),this._parser.registerCsiHandler({final:"P"},f=>this.deleteChars(f)),this._parser.registerCsiHandler({final:"S"},f=>this.scrollUp(f)),this._parser.registerCsiHandler({final:"T"},f=>this.scrollDown(f)),this._parser.registerCsiHandler({final:"X"},f=>this.eraseChars(f)),this._parser.registerCsiHandler({final:"Z"},f=>this.cursorBackwardTab(f)),this._parser.registerCsiHandler({final:"`"},f=>this.charPosAbsolute(f)),this._parser.registerCsiHandler({final:"a"},f=>this.hPositionRelative(f)),this._parser.registerCsiHandler({final:"b"},f=>this.repeatPrecedingCharacter(f)),this._parser.registerCsiHandler({final:"c"},f=>this.sendDeviceAttributesPrimary(f)),this._parser.registerCsiHandler({prefix:">",final:"c"},f=>this.sendDeviceAttributesSecondary(f)),this._parser.registerCsiHandler({final:"d"},f=>this.linePosAbsolute(f)),this._parser.registerCsiHandler({final:"e"},f=>this.vPositionRelative(f)),this._parser.registerCsiHandler({final:"f"},f=>this.hVPosition(f)),this._parser.registerCsiHandler({final:"g"},f=>this.tabClear(f)),this._parser.registerCsiHandler({final:"h"},f=>this.setMode(f)),this._parser.registerCsiHandler({prefix:"?",final:"h"},f=>this.setModePrivate(f)),this._parser.registerCsiHandler({final:"l"},f=>this.resetMode(f)),this._parser.registerCsiHandler({prefix:"?",final:"l"},f=>this.resetModePrivate(f)),this._parser.registerCsiHandler({final:"m"},f=>this.charAttributes(f)),this._parser.registerCsiHandler({final:"n"},f=>this.deviceStatus(f)),this._parser.registerCsiHandler({prefix:"?",final:"n"},f=>this.deviceStatusPrivate(f)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},f=>this.softReset(f)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},f=>this.setCursorStyle(f)),this._parser.registerCsiHandler({final:"r"},f=>this.setScrollRegion(f)),this._parser.registerCsiHandler({final:"s"},f=>this.saveCursor(f)),this._parser.registerCsiHandler({final:"t"},f=>this.windowOptions(f)),this._parser.registerCsiHandler({final:"u"},f=>this.restoreCursor(f)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},f=>this.insertColumns(f)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},f=>this.deleteColumns(f)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},f=>this.selectProtected(f)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},f=>this.requestMode(f,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},f=>this.requestMode(f,!1)),this._parser.setExecuteHandler(pe.BEL,()=>this.bell()),this._parser.setExecuteHandler(pe.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(pe.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(pe.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(pe.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(pe.BS,()=>this.backspace()),this._parser.setExecuteHandler(pe.HT,()=>this.tab()),this._parser.setExecuteHandler(pe.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(pe.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(bu.IND,()=>this.index()),this._parser.setExecuteHandler(bu.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(bu.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new Wn(f=>(this.setTitle(f),this.setIconName(f),!0))),this._parser.registerOscHandler(1,new Wn(f=>this.setIconName(f))),this._parser.registerOscHandler(2,new Wn(f=>this.setTitle(f))),this._parser.registerOscHandler(4,new Wn(f=>this.setOrReportIndexedColor(f))),this._parser.registerOscHandler(8,new Wn(f=>this.setHyperlink(f))),this._parser.registerOscHandler(10,new Wn(f=>this.setOrReportFgColor(f))),this._parser.registerOscHandler(11,new Wn(f=>this.setOrReportBgColor(f))),this._parser.registerOscHandler(12,new Wn(f=>this.setOrReportCursorColor(f))),this._parser.registerOscHandler(104,new Wn(f=>this.restoreIndexedColor(f))),this._parser.registerOscHandler(110,new Wn(f=>this.restoreFgColor(f))),this._parser.registerOscHandler(111,new Wn(f=>this.restoreBgColor(f))),this._parser.registerOscHandler(112,new Wn(f=>this.restoreCursorColor(f))),this._parser.registerEscHandler({final:"7"},()=>this.saveCursor()),this._parser.registerEscHandler({final:"8"},()=>this.restoreCursor()),this._parser.registerEscHandler({final:"D"},()=>this.index()),this._parser.registerEscHandler({final:"E"},()=>this.nextLine()),this._parser.registerEscHandler({final:"H"},()=>this.tabSet()),this._parser.registerEscHandler({final:"M"},()=>this.reverseIndex()),this._parser.registerEscHandler({final:"="},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:">"},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:"c"},()=>this.fullReset()),this._parser.registerEscHandler({final:"n"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"o"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"|"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"}"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"~"},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:"%",final:"@"},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:"%",final:"G"},()=>this.selectDefaultCharset());for(let f in Pi)this._parser.registerEscHandler({intermediates:"(",final:f},()=>this.selectCharset("("+f)),this._parser.registerEscHandler({intermediates:")",final:f},()=>this.selectCharset(")"+f)),this._parser.registerEscHandler({intermediates:"*",final:f},()=>this.selectCharset("*"+f)),this._parser.registerEscHandler({intermediates:"+",final:f},()=>this.selectCharset("+"+f)),this._parser.registerEscHandler({intermediates:"-",final:f},()=>this.selectCharset("-"+f)),this._parser.registerEscHandler({intermediates:".",final:f},()=>this.selectCharset("."+f)),this._parser.registerEscHandler({intermediates:"/",final:f},()=>this.selectCharset("/"+f));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(f=>(this._logService.error("Parsing error: ",f),f)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new Vb((f,_)=>this.requestStatusString(f,_)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,i,s){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=i,this._parseStack.position=s}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((t,i)=>setTimeout(()=>i("#SLOW_TIMEOUT"),Qb))]).catch(t=>{if(t!=="#SLOW_TIMEOUT")throw t;console.warn(`async parser handler taking longer than ${Qb} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let i,s=this._activeBuffer.x,a=this._activeBuffer.y,o=0,c=this._parseStack.paused;if(c){if(i=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(i),i;s=this._parseStack.cursorStartX,a=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>Os&&(o=this._parseStack.position+Os)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e=="string"?` "${e}"`:` "${Array.prototype.map.call(e,f=>String.fromCharCode(f)).join("")}"`}`),this._logService.logLevel===0&&this._logService.trace("parsing data (codes)",typeof e=="string"?e.split("").map(f=>f.charCodeAt(0)):e),this._parseBuffer.lengthOs)for(let f=o;f0&&x.getWidth(this._activeBuffer.x-1)===2&&x.setCellFromCodepoint(this._activeBuffer.x-1,0,1,_);let b=this._parser.precedingJoinState;for(let v=t;vh){if(p){let E=x,L=this._activeBuffer.x-M;for(this._activeBuffer.x=M,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),x=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),M>0&&x instanceof ko&&x.copyCellsFrom(E,L,0,M,!1);L=0;)x.setCellFromCodepoint(this._activeBuffer.x++,0,0,_);continue}if(f&&(x.insertCells(this._activeBuffer.x,a-M,this._activeBuffer.getNullCell(_)),x.getWidth(h-1)===2&&x.setCellFromCodepoint(h-1,0,1,_)),x.setCellFromCodepoint(this._activeBuffer.x++,s,a,_),a>0)for(;--a;)x.setCellFromCodepoint(this._activeBuffer.x++,0,0,_)}this._parser.precedingJoinState=b,this._activeBuffer.x0&&x.getWidth(this._activeBuffer.x)===0&&!x.hasContent(this._activeBuffer.x)&&x.setCellFromCodepoint(this._activeBuffer.x,0,1,_),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final==="t"&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,i=>Zb(i.params[0],this._optionsService.rawOptions.windowOptions)?t(i):!0):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new Vb(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new Wn(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){var e;if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&((e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y))!=null&&e.isWrapped)){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);t.hasWidth(this._activeBuffer.x)&&!t.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),(t===2||t===0)&&(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,i,s=!1,a=!1){let o=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);o.replaceCells(t,i,this._activeBuffer.getNullCell(this._eraseAttrData()),a),s&&(o.isWrapped=!1)}_resetBufferLine(e,t=!1){let i=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);i&&(i.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),i.isWrapped=!1)}eraseInDisplay(e,t=!1){var s;this._restrictCursor(this._bufferService.cols);let i;switch(e.params[0]){case 0:for(i=this._activeBuffer.y,this._dirtyRowTracker.markDirty(i),this._eraseInBufferLine(i++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);i=this._bufferService.cols&&(this._activeBuffer.lines.get(i+1).isWrapped=!1);i--;)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(i=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,i-1);i--&&!((s=this._activeBuffer.lines.get(this._activeBuffer.ybase+i))!=null&&s.getTrimmedLength()););for(;i>=0;i--)this._bufferService.scroll(this._eraseAttrData())}else{for(i=this._bufferService.rows,this._dirtyRowTracker.markDirty(i-1);i--;)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let a=this._activeBuffer.lines.length-this._bufferService.rows;a>0&&(this._activeBuffer.lines.trimStart(a),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-a,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-a,0),this._onScroll.fire(0));break}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t);break}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.y65535?2:1}let p=h;for(let f=1;f0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(pe.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(pe.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(pe.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(pe.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(e.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(pe.ESC+"[>83;40003;0c")),!0}_is(e){return(this._optionsService.rawOptions.termName+"").indexOf(e)===0}setMode(e){for(let t=0;t(N[N.NOT_RECOGNIZED=0]="NOT_RECOGNIZED",N[N.SET=1]="SET",N[N.RESET=2]="RESET",N[N.PERMANENTLY_SET=3]="PERMANENTLY_SET",N[N.PERMANENTLY_RESET=4]="PERMANENTLY_RESET"))(void 0||(i={}));let s=this._coreService.decPrivateModes,{activeProtocol:a,activeEncoding:o}=this._coreMouseService,c=this._coreService,{buffers:h,cols:p}=this._bufferService,{active:f,alt:_}=h,x=this._optionsService.rawOptions,b=(N,M)=>(c.triggerDataEvent(`${pe.ESC}[${t?"":"?"}${N};${M}$y`),!0),v=N=>N?1:2,S=e.params[0];return t?S===2?b(S,4):S===4?b(S,v(c.modes.insertMode)):S===12?b(S,3):S===20?b(S,v(x.convertEol)):b(S,0):S===1?b(S,v(s.applicationCursorKeys)):S===3?b(S,x.windowOptions.setWinLines?p===80?2:p===132?1:0:0):S===6?b(S,v(s.origin)):S===7?b(S,v(s.wraparound)):S===8?b(S,3):S===9?b(S,v(a==="X10")):S===12?b(S,v(x.cursorBlink)):S===25?b(S,v(!c.isCursorHidden)):S===45?b(S,v(s.reverseWraparound)):S===66?b(S,v(s.applicationKeypad)):S===67?b(S,4):S===1e3?b(S,v(a==="VT200")):S===1002?b(S,v(a==="DRAG")):S===1003?b(S,v(a==="ANY")):S===1004?b(S,v(s.sendFocus)):S===1005?b(S,4):S===1006?b(S,v(o==="SGR")):S===1015?b(S,4):S===1016?b(S,v(o==="SGR_PIXELS")):S===1048?b(S,1):S===47||S===1047||S===1049?b(S,v(f===_)):S===2004?b(S,v(s.bracketedPasteMode)):S===2026?b(S,v(s.synchronizedOutput)):b(S,0)}_updateAttrColor(e,t,i,s,a){return t===2?(e|=50331648,e&=-16777216,e|=$o.fromColorRGB([i,s,a])):t===5&&(e&=-50331904,e|=33554432|i&255),e}_extractColor(e,t,i){let s=[0,0,-1,0,0,0],a=0,o=0;do{if(s[o+a]=e.params[t+o],e.hasSubParams(t+o)){let c=e.getSubParams(t+o),h=0;do s[1]===5&&(a=1),s[o+h+1+a]=c[h];while(++h=2||s[1]===2&&o+a>=5)break;s[1]&&(a=1)}while(++o+t5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=Ti.fg,e.bg=Ti.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,i,s=this._curAttrData;for(let a=0;a=30&&i<=37?(s.fg&=-50331904,s.fg|=16777216|i-30):i>=40&&i<=47?(s.bg&=-50331904,s.bg|=16777216|i-40):i>=90&&i<=97?(s.fg&=-50331904,s.fg|=16777216|i-90|8):i>=100&&i<=107?(s.bg&=-50331904,s.bg|=16777216|i-100|8):i===0?this._processSGR0(s):i===1?s.fg|=134217728:i===3?s.bg|=67108864:i===4?(s.fg|=268435456,this._processUnderline(e.hasSubParams(a)?e.getSubParams(a)[0]:1,s)):i===5?s.fg|=536870912:i===7?s.fg|=67108864:i===8?s.fg|=1073741824:i===9?s.fg|=2147483648:i===2?s.bg|=134217728:i===21?this._processUnderline(2,s):i===22?(s.fg&=-134217729,s.bg&=-134217729):i===23?s.bg&=-67108865:i===24?(s.fg&=-268435457,this._processUnderline(0,s)):i===25?s.fg&=-536870913:i===27?s.fg&=-67108865:i===28?s.fg&=-1073741825:i===29?s.fg&=2147483647:i===39?(s.fg&=-67108864,s.fg|=Ti.fg&16777215):i===49?(s.bg&=-67108864,s.bg|=Ti.bg&16777215):i===38||i===48||i===58?a+=this._extractColor(e,a,s):i===53?s.bg|=1073741824:i===55?s.bg&=-1073741825:i===59?(s.extended=s.extended.clone(),s.extended.underlineColor=-1,s.updateExtended()):i===100?(s.fg&=-67108864,s.fg|=Ti.fg&16777215,s.bg&=-67108864,s.bg|=Ti.bg&16777215):this._logService.debug("Unknown SGR attribute: %d.",i);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${pe.ESC}[0n`);break;case 6:let t=this._activeBuffer.y+1,i=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${pe.ESC}[${t};${i}R`);break}return!0}deviceStatusPrivate(e){switch(e.params[0]){case 6:let t=this._activeBuffer.y+1,i=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${pe.ESC}[?${t};${i}R`);break}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=Ti.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.length===0?1:e.params[0];if(t===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t){case 1:case 2:this._coreService.decPrivateModes.cursorStyle="block";break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle="underline";break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle="bar";break}let i=t%2===1;this._coreService.decPrivateModes.cursorBlink=i}return!0}setScrollRegion(e){let t=e.params[0]||1,i;return(e.length<2||(i=e.params[1])>this._bufferService.rows||i===0)&&(i=this._bufferService.rows),i>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=i-1,this._setCursor(0,0)),!0}windowOptions(e){if(!Zb(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${pe.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>Xb&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>Xb&&this._iconNameStack.shift());break;case 23:(t===0||t===2)&&this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),(t===0||t===1)&&this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop());break}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],i=e.split(";");for(;i.length>1;){let s=i.shift(),a=i.shift();if(/^\d+$/.exec(s)){let o=parseInt(s);if(ev(o))if(a==="?")t.push({type:0,index:o});else{let c=Kb(a);c&&t.push({type:1,index:o,color:c})}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(";");if(t===-1)return!0;let i=e.slice(0,t).trim(),s=e.slice(t+1);return s?this._createHyperlink(i,s):i.trim()?!1:this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let i=e.split(":"),s,a=i.findIndex(o=>o.startsWith("id="));return a!==-1&&(s=i[a].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:s,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let i=e.split(";");for(let s=0;s=this._specialColors.length);++s,++t)if(i[s]==="?")this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let a=Kb(i[s]);a&&this._onColor.fire([{type:1,index:this._specialColors[t],color:a}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],i=e.split(";");for(let s=0;s=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=Ti.clone(),this._eraseAttrDataInternal=Ti.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=this._curAttrData.bg&67108863,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new or;e.content=1<<22|69,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t(this._coreService.triggerDataEvent(`${pe.ESC}${c}${pe.ESC}\\`),!0),s=this._bufferService.buffer,a=this._optionsService.rawOptions;return i(e==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:e==='"p'?'P1$r61;1"p':e==="r"?`P1$r${s.scrollTop+1};${s.scrollBottom+1}r`:e==="m"?"P1$r0m":e===" q"?`P1$r${{block:2,underline:4,bar:6}[a.cursorStyle]-(a.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},yp=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){ethis.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(Jb=e,e=t,t=Jb),ethis.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};yp=fi([Re(0,_n)],yp);function ev(e){return 0<=e&&e<256}var SE=5e7,tv=12,wE=50,CE=class extends ht{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new ke),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(t!==void 0&&this._syncCalls>t){this._syncCalls=0;return}if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;this._isSyncWriting=!0;let i;for(;i=this._writeBuffer.shift();){this._action(i);let s=this._callbacks.shift();s&&s()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>SE)throw new Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput){this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),this._innerWrite();return}setTimeout(()=>this._innerWrite())}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){let i=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let s=this._writeBuffer[this._bufferOffset],a=this._action(s,t);if(a){let c=h=>performance.now()-i>=tv?setTimeout(()=>this._innerWrite(0,h)):this._innerWrite(i,h);a.catch(h=>(queueMicrotask(()=>{throw h}),Promise.resolve(!1))).then(c);return}let o=this._callbacks[this._bufferOffset];if(o&&o(),this._bufferOffset++,this._pendingData-=s.length,performance.now()-i>=tv)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>wE&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}},Sp=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let t=this._bufferService.buffer;if(e.id===void 0){let h=t.addMarker(t.ybase+t.y),p={data:e,id:this._nextId++,lines:[h]};return h.onDispose(()=>this._removeMarkerFromLink(p,h)),this._dataByLinkId.set(p.id,p),p.id}let i=e,s=this._getEntryIdKey(i),a=this._entriesWithId.get(s);if(a)return this.addLineToLink(a.id,t.ybase+t.y),a.id;let o=t.addMarker(t.ybase+t.y),c={id:this._nextId++,key:this._getEntryIdKey(i),data:i,lines:[o]};return o.onDispose(()=>this._removeMarkerFromLink(c,o)),this._entriesWithId.set(c.key,c),this._dataByLinkId.set(c.id,c),c.id}addLineToLink(e,t){let i=this._dataByLinkId.get(e);if(i&&i.lines.every(s=>s.line!==t)){let s=this._bufferService.buffer.addMarker(t);i.lines.push(s),s.onDispose(()=>this._removeMarkerFromLink(i,s))}}getLinkData(e){var t;return(t=this._dataByLinkId.get(e))==null?void 0:t.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let i=e.lines.indexOf(t);i!==-1&&(e.lines.splice(i,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};Sp=fi([Re(0,_n)],Sp);var iv=!1,kE=class extends ht{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new fl),this._onBinary=this._register(new ke),this.onBinary=this._onBinary.event,this._onData=this._register(new ke),this.onData=this._onData.event,this._onLineFeed=this._register(new ke),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new ke),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new ke),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new ke),this._instantiationService=new K2,this.optionsService=this._register(new sE(e)),this._instantiationService.setService(bn,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(xp)),this._instantiationService.setService(_n,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(gp)),this._instantiationService.setService(Uy,this._logService),this.coreService=this._register(this._instantiationService.createInstance(_p)),this._instantiationService.setService(va,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(bp)),this._instantiationService.setService(Hy,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(ma)),this._instantiationService.setService(WC,this.unicodeService),this._charsetService=this._instantiationService.createInstance(uE),this._instantiationService.setService(qC,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(Sp),this._instantiationService.setService($y,this._oscLinkService),this._inputHandler=this._register(new yE(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(sn.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(sn.forward(this._bufferService.onResize,this._onResize)),this._register(sn.forward(this.coreService.onData,this._onData)),this._register(sn.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom(!0))),this._register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this._register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],()=>this._handleWindowsPtyOptionChange())),this._register(this._bufferService.onScroll(()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this._register(new CE((t,i)=>this._inputHandler.parse(t,i))),this._register(sn.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new ke),this._onScroll.event(e=>{var t;(t=this._onScrollApi)==null||t.fire(e.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let t in e)this.optionsService.options[t]=e[t]}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=3&&!iv&&(this._logService.warn("writeSync is unreliable and will be removed soon."),iv=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,v0),t=Math.max(t,y0),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t){this._bufferService.scrollLines(e,t)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&t.buildNumber!==void 0&&t.buildNumber!==void 0?e=t.backend==="conpty"&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(Yb.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},()=>(Yb(this._bufferService),!1))),this._windowsWrappingHeuristics.value=ni(()=>{for(let t of e)t.dispose()})}}},EE={48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],186:[";",":"],187:["=","+"],188:[",","<"],189:["-","_"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"']};function NE(e,t,i,s){var c;let a={type:0,cancel:!1,key:void 0},o=(e.shiftKey?1:0)|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:e.key==="UIKeyInputUpArrow"?t?a.key=pe.ESC+"OA":a.key=pe.ESC+"[A":e.key==="UIKeyInputLeftArrow"?t?a.key=pe.ESC+"OD":a.key=pe.ESC+"[D":e.key==="UIKeyInputRightArrow"?t?a.key=pe.ESC+"OC":a.key=pe.ESC+"[C":e.key==="UIKeyInputDownArrow"&&(t?a.key=pe.ESC+"OB":a.key=pe.ESC+"[B");break;case 8:a.key=e.ctrlKey?"\b":pe.DEL,e.altKey&&(a.key=pe.ESC+a.key);break;case 9:if(e.shiftKey){a.key=pe.ESC+"[Z";break}a.key=pe.HT,a.cancel=!0;break;case 13:a.key=e.altKey?pe.ESC+pe.CR:pe.CR,a.cancel=!0;break;case 27:a.key=pe.ESC,e.altKey&&(a.key=pe.ESC+pe.ESC),a.cancel=!0;break;case 37:if(e.metaKey)break;o?a.key=pe.ESC+"[1;"+(o+1)+"D":t?a.key=pe.ESC+"OD":a.key=pe.ESC+"[D";break;case 39:if(e.metaKey)break;o?a.key=pe.ESC+"[1;"+(o+1)+"C":t?a.key=pe.ESC+"OC":a.key=pe.ESC+"[C";break;case 38:if(e.metaKey)break;o?a.key=pe.ESC+"[1;"+(o+1)+"A":t?a.key=pe.ESC+"OA":a.key=pe.ESC+"[A";break;case 40:if(e.metaKey)break;o?a.key=pe.ESC+"[1;"+(o+1)+"B":t?a.key=pe.ESC+"OB":a.key=pe.ESC+"[B";break;case 45:!e.shiftKey&&!e.ctrlKey&&(a.key=pe.ESC+"[2~");break;case 46:o?a.key=pe.ESC+"[3;"+(o+1)+"~":a.key=pe.ESC+"[3~";break;case 36:o?a.key=pe.ESC+"[1;"+(o+1)+"H":t?a.key=pe.ESC+"OH":a.key=pe.ESC+"[H";break;case 35:o?a.key=pe.ESC+"[1;"+(o+1)+"F":t?a.key=pe.ESC+"OF":a.key=pe.ESC+"[F";break;case 33:e.shiftKey?a.type=2:e.ctrlKey?a.key=pe.ESC+"[5;"+(o+1)+"~":a.key=pe.ESC+"[5~";break;case 34:e.shiftKey?a.type=3:e.ctrlKey?a.key=pe.ESC+"[6;"+(o+1)+"~":a.key=pe.ESC+"[6~";break;case 112:o?a.key=pe.ESC+"[1;"+(o+1)+"P":a.key=pe.ESC+"OP";break;case 113:o?a.key=pe.ESC+"[1;"+(o+1)+"Q":a.key=pe.ESC+"OQ";break;case 114:o?a.key=pe.ESC+"[1;"+(o+1)+"R":a.key=pe.ESC+"OR";break;case 115:o?a.key=pe.ESC+"[1;"+(o+1)+"S":a.key=pe.ESC+"OS";break;case 116:o?a.key=pe.ESC+"[15;"+(o+1)+"~":a.key=pe.ESC+"[15~";break;case 117:o?a.key=pe.ESC+"[17;"+(o+1)+"~":a.key=pe.ESC+"[17~";break;case 118:o?a.key=pe.ESC+"[18;"+(o+1)+"~":a.key=pe.ESC+"[18~";break;case 119:o?a.key=pe.ESC+"[19;"+(o+1)+"~":a.key=pe.ESC+"[19~";break;case 120:o?a.key=pe.ESC+"[20;"+(o+1)+"~":a.key=pe.ESC+"[20~";break;case 121:o?a.key=pe.ESC+"[21;"+(o+1)+"~":a.key=pe.ESC+"[21~";break;case 122:o?a.key=pe.ESC+"[23;"+(o+1)+"~":a.key=pe.ESC+"[23~";break;case 123:o?a.key=pe.ESC+"[24;"+(o+1)+"~":a.key=pe.ESC+"[24~";break;default:if(e.ctrlKey&&!e.shiftKey&&!e.altKey&&!e.metaKey)e.keyCode>=65&&e.keyCode<=90?a.key=String.fromCharCode(e.keyCode-64):e.keyCode===32?a.key=pe.NUL:e.keyCode>=51&&e.keyCode<=55?a.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?a.key=pe.DEL:e.keyCode===219?a.key=pe.ESC:e.keyCode===220?a.key=pe.FS:e.keyCode===221&&(a.key=pe.GS);else if((!i||s)&&e.altKey&&!e.metaKey){let h=(c=EE[e.keyCode])==null?void 0:c[e.shiftKey?1:0];if(h)a.key=pe.ESC+h;else if(e.keyCode>=65&&e.keyCode<=90){let p=e.ctrlKey?e.keyCode-64:e.keyCode+32,f=String.fromCharCode(p);e.shiftKey&&(f=f.toUpperCase()),a.key=pe.ESC+f}else if(e.keyCode===32)a.key=pe.ESC+(e.ctrlKey?pe.NUL:" ");else if(e.key==="Dead"&&e.code.startsWith("Key")){let p=e.code.slice(3,4);e.shiftKey||(p=p.toLowerCase()),a.key=pe.ESC+p,a.cancel=!0}}else i&&!e.altKey&&!e.ctrlKey&&!e.shiftKey&&e.metaKey?e.keyCode===65&&(a.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&e.key.length===1?a.key=e.key:e.key&&e.ctrlKey&&(e.key==="_"&&(a.key=pe.US),e.key==="@"&&(a.key=pe.NUL));break}return a}var bi=0,jE=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new Ru,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new Ru,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(e){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort((a,o)=>this._getKey(a)-this._getKey(o)),t=0,i=0,s=new Array(this._array.length+this._insertedValues.length);for(let a=0;a=this._array.length||this._getKey(e[t])<=this._getKey(this._array[i])?(s[a]=e[t],t++):s[a]=this._array[i++];this._array=s,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),this._array.length===0)return!1;let t=this._getKey(e);if(t===void 0||(bi=this._search(t),bi===-1)||this._getKey(this._array[bi])!==t)return!1;do if(this._array[bi]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(bi),!0;while(++bia-o),t=0,i=new Array(this._array.length-e.length),s=0;for(let a=0;a0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(bi=this._search(e),!(bi<0||bi>=this._array.length)&&this._getKey(this._array[bi])===e))do yield this._array[bi];while(++bi=this._array.length)&&this._getKey(this._array[bi])===e))do t(this._array[bi]);while(++bi=t;){let s=t+i>>1,a=this._getKey(this._array[s]);if(a>e)i=s-1;else if(a0&&this._getKey(this._array[s-1])===e;)s--;return s}}return t}},pf=0,nv=0,TE=class extends ht{constructor(){super(),this._decorations=new jE(e=>e==null?void 0:e.marker.line),this._onDecorationRegistered=this._register(new ke),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new ke),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(ni(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new AE(e);if(t){let i=t.marker.onDispose(()=>t.dispose()),s=t.onDispose(()=>{s.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),i.dispose())});this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,i){let s=0,a=0;for(let o of this._decorations.getKeyIterator(t))s=o.options.x??0,a=s+(o.options.width??1),e>=s&&e{pf=a.options.x??0,nv=pf+(a.options.width??1),e>=pf&&e=this._debounceThresholdMS)this._lastRefreshMs=s,this._innerRefresh();else if(!this._additionalRefreshRequested){let a=s-this._lastRefreshMs,o=this._debounceThresholdMS-a;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},o)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}},rv=20,Du=class extends ht{constructor(e,t,i,s){super(),this._terminal=e,this._coreBrowserService=i,this._renderService=s,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="";let a=this._coreBrowserService.mainDocument;this._accessibilityContainer=a.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=a.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let o=0;othis._handleBoundaryFocus(o,0),this._bottomBoundaryFocusListener=o=>this._handleBoundaryFocus(o,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=a.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new DE(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this._register(this._terminal.onResize(o=>this._handleResize(o.rows))),this._register(this._terminal.onRender(o=>this._refreshRows(o.start,o.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(o=>this._handleChar(o))),this._register(this._terminal.onLineFeed(()=>this._handleChar(` -`))),this._register(this._terminal.onA11yTab(o=>this._handleTab(o))),this._register(this._terminal.onKey(o=>this._handleKey(o.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(Ke(a,"selectionchange",()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(ni(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===` -`&&(this._liveRegionLineCount++,this._liveRegionLineCount===rv+1&&(this._liveRegion.textContent+=$f.get())))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let i=this._terminal.buffer,s=i.lines.length.toString();for(let a=e;a<=t;a++){let o=i.lines.get(i.ydisp+a),c=[],h=(o==null?void 0:o.translateToString(!0,void 0,void 0,c))||"",p=(i.ydisp+a+1).toString(),f=this._rowElements[a];f&&(h.length===0?(f.textContent=" ",this._rowColumns.set(f,[0,1])):(f.textContent=h,this._rowColumns.set(f,c)),f.setAttribute("aria-posinset",p),f.setAttribute("aria-setsize",s),this._alignRowWidth(f))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(e,t){let i=e.target,s=this._rowElements[t===0?1:this._rowElements.length-2],a=i.getAttribute("aria-posinset"),o=t===0?"1":`${this._terminal.buffer.lines.length}`;if(a===o||e.relatedTarget!==s)return;let c,h;if(t===0?(c=i,h=this._rowElements.pop(),this._rowContainer.removeChild(h)):(c=this._rowElements.shift(),h=i,this._rowContainer.removeChild(c)),c.removeEventListener("focus",this._topBoundaryFocusListener),h.removeEventListener("focus",this._bottomBoundaryFocusListener),t===0){let p=this._createAccessibilityTreeNode();this._rowElements.unshift(p),this._rowContainer.insertAdjacentElement("afterbegin",p)}else{let p=this._createAccessibilityTreeNode();this._rowElements.push(p),this._rowContainer.appendChild(p)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){var h;if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error("anchorNode and/or focusNode are null");return}let t={node:e.anchorNode,offset:e.anchorOffset},i={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(i.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===i.node&&t.offset>i.offset)&&([t,i]=[i,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let s=this._rowElements.slice(-1)[0];if(i.node.compareDocumentPosition(s)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(i={node:s,offset:((h=s.textContent)==null?void 0:h.length)??0}),!this._rowContainer.contains(i.node))return;let a=({node:p,offset:f})=>{let _=p instanceof Text?p.parentNode:p,x=parseInt(_==null?void 0:_.getAttribute("aria-posinset"),10)-1;if(isNaN(x))return console.warn("row is invalid. Race condition?"),null;let b=this._rowColumns.get(_);if(!b)return console.warn("columns is null. Race condition?"),null;let v=f=this._terminal.cols&&(++x,v=0),{row:x,column:v}},o=a(t),c=a(i);if(!(!o||!c)){if(o.row>c.row||o.row===c.row&&o.column>=c.column)throw new Error("invalid range");this._terminal.select(o.column,o.row,(c.row-o.row)*this._terminal.cols-o.column+c.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let t=this._rowContainer.children.length;te;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement("div");return e.setAttribute("role","listitem"),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e{var o;xa(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,(o=this._activeProviderReplies)==null||o.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(Ke(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(Ke(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register(Ke(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register(Ke(this._element,"mouseup",this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;let i=e.composedPath();for(let s=0;s{o==null||o.forEach(c=>{c.link.dispose&&c.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let i=!1;for(let[o,c]of this._linkProviderService.linkProviders.entries())t?(a=this._activeProviderReplies)!=null&&a.get(o)&&(i=this._checkLinkProviderResult(o,e,i)):c.provideLinks(e.y,h=>{var f,_;if(this._isMouseOut)return;let p=h==null?void 0:h.map(x=>({link:x}));(f=this._activeProviderReplies)==null||f.set(o,p),i=this._checkLinkProviderResult(o,e,i),((_=this._activeProviderReplies)==null?void 0:_.size)===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let i=new Set;for(let s=0;se?this._bufferService.cols:c.link.range.end.x;for(let f=h;f<=p;f++){if(i.has(f)){a.splice(o--,1);break}i.add(f)}}}}_checkLinkProviderResult(e,t,i){var o;if(!this._activeProviderReplies)return i;let s=this._activeProviderReplies.get(e),a=!1;for(let c=0;cthis._linkAtPosition(h.link,t));c&&(i=!0,this._handleNewLink(c))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!i)for(let c=0;cthis._linkAtPosition(p.link,t));if(h){i=!0,this._handleNewLink(h);break}}return i}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&ME(this._mouseDownLink.link,this._currentLink.link)&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){!this._currentLink||!this._lastMouseEvent||(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,xa(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:e.link.decorations===void 0?!0:e.link.decorations.underline,pointerCursor:e.link.decorations===void 0?!0:e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>{var i,s;return(s=(i=this._currentLink)==null?void 0:i.state)==null?void 0:s.decorations.pointerCursor},set:i=>{var s;(s=this._currentLink)!=null&&s.state&&this._currentLink.state.decorations.pointerCursor!==i&&(this._currentLink.state.decorations.pointerCursor=i,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",i))}},underline:{get:()=>{var i,s;return(s=(i=this._currentLink)==null?void 0:i.state)==null?void 0:s.decorations.underline},set:i=>{var s,a,o;(s=this._currentLink)!=null&&s.state&&((o=(a=this._currentLink)==null?void 0:a.state)==null?void 0:o.decorations.underline)!==i&&(this._currentLink.state.decorations.underline=i,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,i))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(i=>{if(!this._currentLink)return;let s=i.start===0?0:i.start+1+this._bufferService.buffer.ydisp,a=this._bufferService.buffer.ydisp+1+i.end;if(this._currentLink.link.range.start.y>=s&&this._currentLink.link.range.end.y<=a&&(this._clearCurrentLink(s,a),this._lastMouseEvent)){let o=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);o&&this._askForLink(o,!1)}})))}_linkHover(e,t,i){var s;(s=this._currentLink)!=null&&s.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add("xterm-cursor-pointer")),t.hover&&t.hover(i,t.text)}_fireUnderlineEvent(e,t){let i=e.range,s=this._bufferService.buffer.ydisp,a=this._createLinkUnderlineEvent(i.start.x-1,i.start.y-s-1,i.end.x,i.end.y-s-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(a)}_linkLeave(e,t,i){var s;(s=this._currentLink)!=null&&s.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove("xterm-cursor-pointer")),t.leave&&t.leave(i,t.text)}_linkAtPosition(e,t){let i=e.range.start.y*this._bufferService.cols+e.range.start.x,s=e.range.end.y*this._bufferService.cols+e.range.end.x,a=t.y*this._bufferService.cols+t.x;return i<=a&&a<=s}_positionFromMouseEvent(e,t,i){let s=i.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(s)return{x:s[0],y:s[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,i,s,a){return{x1:e,y1:t,x2:i,y2:s,cols:this._bufferService.cols,fg:a}}};wp=fi([Re(1,Wp),Re(2,ls),Re(3,_n),Re(4,qy)],wp);function ME(e,t){return e.text===t.text&&e.range.start.x===t.range.start.x&&e.range.start.y===t.range.start.y&&e.range.end.x===t.range.end.x&&e.range.end.y===t.range.end.y}var BE=class extends kE{constructor(e={}){super(e),this._linkifier=this._register(new fl),this.browser=c0,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new fl),this._onCursorMove=this._register(new ke),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new ke),this.onKey=this._onKey.event,this._onRender=this._register(new ke),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new ke),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new ke),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new ke),this.onBell=this._onBell.event,this._onFocus=this._register(new ke),this._onBlur=this._register(new ke),this._onA11yCharEmitter=this._register(new ke),this._onA11yTabEmitter=this._register(new ke),this._onWillOpen=this._register(new ke),this._setup(),this._decorationService=this._instantiationService.createInstance(TE),this._instantiationService.setService(Fo,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(w2),this._instantiationService.setService(qy,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(qf)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(t=>this.refresh((t==null?void 0:t.start)??0,(t==null?void 0:t.end)??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(t=>this._reportWindowsOptions(t))),this._register(this._inputHandler.onColor(t=>this._handleColorEvent(t))),this._register(sn.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(sn.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(sn.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(sn.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(t=>this._afterResize(t.cols,t.rows))),this._register(ni(()=>{var t,i;this._customKeyEventHandler=void 0,(i=(t=this.element)==null?void 0:t.parentNode)==null||i.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(e){if(this._themeService)for(let t of e){let i,s="";switch(t.index){case 256:i="foreground",s="10";break;case 257:i="background",s="11";break;case 258:i="cursor",s="12";break;default:i="ansi",s="4;"+t.index}switch(t.type){case 0:let a=ti.toColorRGB(i==="ansi"?this._themeService.colors.ansi[t.index]:this._themeService.colors[i]);this.coreService.triggerDataEvent(`${pe.ESC}]${s};${bE(a)}${l0.ST}`);break;case 1:if(i==="ansi")this._themeService.modifyColors(o=>o.ansi[t.index]=Ai.toColor(...t.color));else{let o=i;this._themeService.modifyColors(c=>c[o]=Ai.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index);break}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(Du,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(pe.ESC+"[I"),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()}blur(){var e;return(e=this.textarea)==null?void 0:e.blur()}_handleTextAreaBlur(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(pe.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;let i=Math.min(this.buffer.x,this.cols-1),s=this._renderService.dimensions.css.cell.height,a=t.getWidth(i),o=this._renderService.dimensions.css.cell.width*a,c=this.buffer.y*this._renderService.dimensions.css.cell.height,h=i*this._renderService.dimensions.css.cell.width;this.textarea.style.left=h+"px",this.textarea.style.top=c+"px",this.textarea.style.width=o+"px",this.textarea.style.height=s+"px",this.textarea.style.lineHeight=s+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this._register(Ke(this.element,"copy",t=>{this.hasSelection()&&PC(t,this._selectionService)}));let e=t=>IC(t,this.textarea,this.coreService,this.optionsService);this._register(Ke(this.textarea,"paste",e)),this._register(Ke(this.element,"paste",e)),u0?this._register(Ke(this.element,"mousedown",t=>{t.button===2&&pb(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(Ke(this.element,"contextmenu",t=>{pb(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),Jp&&this._register(Ke(this.element,"auxclick",t=>{t.button===1&&Ly(t,this.textarea,this.screenElement)}))}_bindKeys(){this._register(Ke(this.textarea,"keyup",e=>this._keyUp(e),!0)),this._register(Ke(this.textarea,"keydown",e=>this._keyDown(e),!0)),this._register(Ke(this.textarea,"keypress",e=>this._keyPress(e),!0)),this._register(Ke(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register(Ke(this.textarea,"compositionupdate",e=>this._compositionHelper.compositionupdate(e))),this._register(Ke(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register(Ke(this.textarea,"input",e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){var a;if(!e)throw new Error("Terminal requires a parent element.");if(e.isConnected||this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"),((a=this.element)==null?void 0:a.ownerDocument.defaultView)&&this._coreBrowserService){this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView);return}this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement("div"),this.element.dir="ltr",this.element.classList.add("terminal"),this.element.classList.add("xterm"),e.appendChild(this.element);let t=this._document.createDocumentFragment();this._viewportElement=this._document.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),t.appendChild(this._viewportElement),this.screenElement=this._document.createElement("div"),this.screenElement.classList.add("xterm-screen"),this._register(Ke(this.screenElement,"mousemove",o=>this.updateCursorStyle(o))),this._helperContainer=this._document.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let i=this.textarea=this._document.createElement("textarea");this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",Uf.get()),f0||this.textarea.setAttribute("aria-multiline","false"),this.textarea.setAttribute("autocorrect","off"),this.textarea.setAttribute("autocapitalize","off"),this.textarea.setAttribute("spellcheck","false"),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange("disableStdin",()=>i.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(y2,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(as,this._coreBrowserService),this._register(Ke(this.textarea,"focus",o=>this._handleTextAreaFocus(o))),this._register(Ke(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(hp,this._document,this._helperContainer),this._instantiationService.setService(Hu,this._charSizeService),this._themeService=this._instantiationService.createInstance(mp),this._instantiationService.setService(gl,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(Tu),this._instantiationService.setService(Fy,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(fp,this.rows,this.screenElement)),this._instantiationService.setService(ls,this._renderService),this._register(this._renderService.onRenderedViewportChange(o=>this._onRender.fire(o))),this.onResize(o=>this._renderService.resize(o.cols,o.rows)),this._compositionView=this._document.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(op,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(dp),this._instantiationService.setService(Wp,this._mouseService);let s=this._linkifier.value=this._register(this._instantiationService.createInstance(wp,this.screenElement));this.element.appendChild(t);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(ap,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(o=>{super.scrollLines(o,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(pp,this.element,this.screenElement,s)),this._instantiationService.setService(YC,this._selectionService),this._register(this._selectionService.onRequestScrollLines(o=>this.scrollLines(o.amount,o.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(o=>this._renderService.handleSelectionChanged(o.start,o.end,o.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(o=>{this.textarea.value=o,this.textarea.focus(),this.textarea.select()})),this._register(sn.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{var o;this._selectionService.refresh(),(o=this._viewport)==null||o.queueSync()})),this._register(this._instantiationService.createInstance(lp,this.screenElement)),this._register(Ke(this.element,"mousedown",o=>this._selectionService.handleMouseDown(o))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add("enable-mouse-events")):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(Du,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",o=>this._handleScreenReaderModeOptionChange(o))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(ju,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",o=>{!this._overviewRulerRenderer&&o&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(ju,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(up,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function i(o){var f,_,x,b,v;let c=e._mouseService.getMouseReportCoords(o,e.screenElement);if(!c)return!1;let h,p;switch(o.overrideType||o.type){case"mousemove":p=32,o.buttons===void 0?(h=3,o.button!==void 0&&(h=o.button<3?o.button:3)):h=o.buttons&1?0:o.buttons&4?1:o.buttons&2?2:3;break;case"mouseup":p=0,h=o.button<3?o.button:3;break;case"mousedown":p=1,h=o.button<3?o.button:3;break;case"wheel":if(e._customWheelEventHandler&&e._customWheelEventHandler(o)===!1)return!1;let S=o.deltaY;if(S===0||e.coreMouseService.consumeWheelEvent(o,(b=(x=(_=(f=e._renderService)==null?void 0:f.dimensions)==null?void 0:_.device)==null?void 0:x.cell)==null?void 0:b.height,(v=e._coreBrowserService)==null?void 0:v.dpr)===0)return!1;p=S<0?0:1,h=4;break;default:return!1}return p===void 0||h===void 0||h>4?!1:e.coreMouseService.triggerMouseEvent({col:c.col,row:c.row,x:c.x,y:c.y,button:h,action:p,ctrl:o.ctrlKey,alt:o.altKey,shift:o.shiftKey})}let s={mouseup:null,wheel:null,mousedrag:null,mousemove:null},a={mouseup:o=>(i(o),o.buttons||(this._document.removeEventListener("mouseup",s.mouseup),s.mousedrag&&this._document.removeEventListener("mousemove",s.mousedrag)),this.cancel(o)),wheel:o=>(i(o),this.cancel(o,!0)),mousedrag:o=>{o.buttons&&i(o)},mousemove:o=>{o.buttons||i(o)}};this._register(this.coreMouseService.onProtocolChange(o=>{o?(this.optionsService.rawOptions.logLevel==="debug"&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(o)),this.element.classList.add("enable-mouse-events"),this._selectionService.disable()):(this._logService.debug("Unbinding from mouse events."),this.element.classList.remove("enable-mouse-events"),this._selectionService.enable()),o&8?s.mousemove||(t.addEventListener("mousemove",a.mousemove),s.mousemove=a.mousemove):(t.removeEventListener("mousemove",s.mousemove),s.mousemove=null),o&16?s.wheel||(t.addEventListener("wheel",a.wheel,{passive:!1}),s.wheel=a.wheel):(t.removeEventListener("wheel",s.wheel),s.wheel=null),o&2?s.mouseup||(s.mouseup=a.mouseup):(this._document.removeEventListener("mouseup",s.mouseup),s.mouseup=null),o&4?s.mousedrag||(s.mousedrag=a.mousedrag):(this._document.removeEventListener("mousemove",s.mousedrag),s.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(Ke(t,"mousedown",o=>{if(o.preventDefault(),this.focus(),!(!this.coreMouseService.areMouseEventsActive||this._selectionService.shouldForceSelection(o)))return i(o),s.mouseup&&this._document.addEventListener("mouseup",s.mouseup),s.mousedrag&&this._document.addEventListener("mousemove",s.mousedrag),this.cancel(o)})),this._register(Ke(t,"wheel",o=>{var c,h,p,f,_;if(!s.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(o)===!1)return!1;if(!this.buffer.hasScrollback){if(o.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(o,(f=(p=(h=(c=e._renderService)==null?void 0:c.dimensions)==null?void 0:h.device)==null?void 0:p.cell)==null?void 0:f.height,(_=e._coreBrowserService)==null?void 0:_.dpr)===0)return this.cancel(o,!0);let x=pe.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(o.deltaY<0?"A":"B");return this.coreService.triggerDataEvent(x,!0),this.cancel(o,!0)}}},{passive:!1}))}refresh(e,t){var i;(i=this._renderService)==null||i.refreshRows(e,t)}updateCursorStyle(e){var t;(t=this._selectionService)!=null&&t.shouldColumnSelect(e)?this.element.classList.add("column-select"):this.element.classList.remove("column-select")}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,t){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,t),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}paste(e){By(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");let t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return this._selectionService?this._selectionService.hasSelection:!1}select(e,t,i){this._selectionService.setSelection(e,t,i)}getSelection(){return this._selectionService?this._selectionService.selectionText:""}getSelectionPosition(){if(!(!this._selectionService||!this._selectionService.hasSelection))return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){var e;(e=this._selectionService)==null||e.clearSelection()}selectAll(){var e;(e=this._selectionService)==null||e.selectAll()}selectLines(e,t){var i;(i=this._selectionService)==null||i.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;let t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;!t&&(e.key==="Dead"||e.key==="AltGraph")&&(this._unprocessedDeadKey=!0);let i=NE(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),i.type===3||i.type===2){let s=this.rows-1;return this.scrollLines(i.type===2?-s:s),this.cancel(e,!0)}if(i.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(i.cancel&&this.cancel(e,!0),!i.key)||e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.key.length===1&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)return!0;if(this._unprocessedDeadKey)return this._unprocessedDeadKey=!1,!0;if((i.key===pe.ETX||i.key===pe.CR)&&(this.textarea.value=""),this._onKey.fire({key:i.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(i.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,t){let i=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState("AltGraph");return t.type==="keypress"?i:i&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&(LE(e)||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let t;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(e.which===null||e.which===void 0)t=e.keyCode;else if(e.which!==0&&e.charCode!==0)t=e.which;else return!1;return!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e)?!1:(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(t,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(e){if(e.data&&e.inputType==="insertText"&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let t=e.data;return this.coreService.triggerDataEvent(t,!0),this.cancel(e),!0}return!1}resize(e,t){if(e===this.cols&&t===this.rows){this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure();return}super.resize(e,t)}_afterResize(e,t){var i;(i=this._charSizeService)==null||i.measure()}clear(){if(!(this.buffer.ybase===0&&this.buffer.y===0)){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let i={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(i),t.dispose=()=>this._wrappedAddonDispose(i),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let i=0;i=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new or)}translateToString(e,t,i){return this._line.translateToString(e,t,i)}},sv=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){let t=this._buffer.lines.get(e);if(t)return new zE(t)}getNullCell(){return new or}},PE=class extends ht{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new ke),this.onBufferChange=this._onBufferChange.event,this._normal=new sv(this._core.buffers.normal,"normal"),this._alternate=new sv(this._core.buffers.alt,"alternate"),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw new Error("Active buffer is neither normal nor alternate")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}},IE=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,i=>t(i.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(i,s)=>t(i,s.toArray()))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}},HE=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}},UE=["cols","rows"],Er=0,$E=class extends ht{constructor(e){super(),this._core=this._register(new BE(e)),this._addonManager=this._register(new OE),this._publicOptions={...this._core.options};let t=s=>this._core.options[s],i=(s,a)=>{this._checkReadonlyOptions(s),this._core.options[s]=a};for(let s in this._core.options){let a={get:t.bind(this,s),set:i.bind(this,s)};Object.defineProperty(this._publicOptions,s,a)}}_checkReadonlyOptions(e){if(UE.includes(e))throw new Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw new Error("You must set the allowProposedApi option to true to use proposed API")}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||(this._parser=new IE(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new HE(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||(this._buffer=this._register(new PE(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t="none";switch(this._core.coreMouseService.activeProtocol){case"X10":t="x10";break;case"VT200":t="vt200";break;case"DRAG":t="drag";break;case"ANY":t="any";break}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,i){this._verifyIntegers(e,t,i),this._core.select(e,t,i)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\r -`,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return Uf.get()},set promptLabel(e){Uf.set(e)},get tooMuchOutput(){return $f.get()},set tooMuchOutput(e){$f.set(e)}}}_verifyIntegers(...e){for(Er of e)if(Er===1/0||isNaN(Er)||Er%1!==0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(Er of e)if(Er&&(Er===1/0||isNaN(Er)||Er%1!==0||Er<0))throw new Error("This API only accepts positive integers")}};/** +`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),Jp&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),i=this._model.finalSelectionStart,s=this._model.finalSelectionEnd;return!i||!s||!t?!1:this._areCoordsInSelection(t,i,s)}isCellInSelection(e,t){let i=this._model.finalSelectionStart,s=this._model.finalSelectionEnd;return!i||!s?!1:this._areCoordsInSelection([e,t],i,s)}_areCoordsInSelection(e,t,i){return e[1]>t[1]&&e[1]=t[0]&&e[0]=t[0]}_selectWordAtCursor(e,t){var a,o;let i=(o=(a=this._linkifier.currentLink)==null?void 0:a.link)==null?void 0:o.range;if(i)return this._model.selectionStart=[i.start.x-1,i.start.y-1],this._model.selectionStartLength=Lb(i,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let s=this._getMouseBufferCoords(e);return s?(this._selectWordAt(s,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=Qp(this._coreBrowserService.window,e,this._screenElement)[1],i=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=i?0:(t>i&&(t-=i),t=Math.min(Math.max(t,-of),of),t/=of,t/Math.abs(t)+Math.round(t*(F2-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(),q2)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(Au&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let i=this._bufferService.buffer;if(this._model.selectionEnd[1]0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&tthis._handleTrim(t))}_convertViewportColToCharacterIndex(e,t){let i=t;for(let s=0;t>=s;s++){let a=e.loadCell(s,this._workCell).getChars().length;this._workCell.getWidth()===0?i--:a>1&&t!==s&&(i+=a-1)}return i}setSelection(e,t,i){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=i,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,i=!0,s=!0){if(e[0]>=this._bufferService.cols)return;let a=this._bufferService.buffer,o=a.lines.get(e[1]);if(!o)return;let c=a.translateBufferLineToString(e[1],!1),h=this._convertViewportColToCharacterIndex(o,e[0]),p=h,f=e[0]-h,_=0,x=0,b=0,v=0;if(c.charAt(h)===" "){for(;h>0&&c.charAt(h-1)===" ";)h--;for(;p1&&(v+=O-1,p+=O-1);B>0&&h>0&&!this._isCharWordSeparator(o.loadCell(B-1,this._workCell));){o.loadCell(B-1,this._workCell);let H=this._workCell.getChars().length;this._workCell.getWidth()===0?(_++,B--):H>1&&(b+=H-1,h-=H-1),h--,B--}for(;E1&&(v+=H-1,p+=H-1),p++,E++}}p++;let S=h+f-_+b,N=Math.min(this._bufferService.cols,p-h+_+x-b-v);if(!(!t&&c.slice(h,p).trim()==="")){if(i&&S===0&&o.getCodePoint(0)!==32){let B=a.lines.get(e[1]-1);if(B&&o.isWrapped&&B.getCodePoint(this._bufferService.cols-1)!==32){let E=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(E){let O=this._bufferService.cols-E.start;S-=O,N+=O}}}if(s&&S+N===this._bufferService.cols&&o.getCodePoint(this._bufferService.cols-1)!==32){let B=a.lines.get(e[1]+1);if(B!=null&&B.isWrapped&&B.getCodePoint(0)!==32){let E=this._getWordAt([0,e[1]+1],!1,!1,!0);E&&(N+=E.length)}}return{start:S,length:N}}}_selectWordAt(e,t){let i=this._getWordAt(e,t);if(i){for(;i.start<0;)i.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[i.start,e[1]],this._model.selectionStartLength=i.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let i=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,i--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,i++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,i]}}_isCharWordSeparator(e){return e.getWidth()===0?!1:this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),i={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=Lb(i,this._bufferService.cols)}};pp=pi([De(3,vn),De(4,va),De(5,Wp),De(6,yn),De(7,os),De(8,ls)],pp);var Ob=class{constructor(){this._data={}}set(e,t,i){this._data[e]||(this._data[e]={}),this._data[e][t]=i}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},zb=class{constructor(){this._color=new Ob,this._css=new Ob}setCss(e,t,i){this._css.set(e,t,i)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,i){this._color.set(e,t,i)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},Li=Object.freeze((()=>{let e=[ai.toColor("#2e3436"),ai.toColor("#cc0000"),ai.toColor("#4e9a06"),ai.toColor("#c4a000"),ai.toColor("#3465a4"),ai.toColor("#75507b"),ai.toColor("#06989a"),ai.toColor("#d3d7cf"),ai.toColor("#555753"),ai.toColor("#ef2929"),ai.toColor("#8ae234"),ai.toColor("#fce94f"),ai.toColor("#729fcf"),ai.toColor("#ad7fa8"),ai.toColor("#34e2e2"),ai.toColor("#eeeeec")],t=[0,95,135,175,215,255];for(let i=0;i<216;i++){let s=t[i/36%6|0],a=t[i/6%6|0],o=t[i%6];e.push({css:Ri.toCss(s,a,o),rgba:Ri.toRgba(s,a,o)})}for(let i=0;i<24;i++){let s=8+i*10;e.push({css:Ri.toCss(s,s,s),rgba:Ri.toRgba(s,s,s)})}return e})()),fa=ai.toColor("#ffffff"),Co=ai.toColor("#000000"),Pb=ai.toColor("#ffffff"),Ib=Co,po={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117},V2=fa,mp=class extends ut{constructor(e){super(),this._optionsService=e,this._contrastCache=new zb,this._halfContrastCache=new zb,this._onChangeColors=this._register(new Ce),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:fa,background:Co,cursor:Pb,cursorAccent:Ib,selectionForeground:void 0,selectionBackgroundTransparent:po,selectionBackgroundOpaque:Jt.blend(Co,po),selectionInactiveBackgroundTransparent:po,selectionInactiveBackgroundOpaque:Jt.blend(Co,po),scrollbarSliderBackground:Jt.opacity(fa,.2),scrollbarSliderHoverBackground:Jt.opacity(fa,.4),scrollbarSliderActiveBackground:Jt.opacity(fa,.5),overviewRulerBorder:fa,ansi:Li.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange("minimumContrastRatio",()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange("theme",()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(e={}){let t=this._colors;if(t.foreground=It(e.foreground,fa),t.background=It(e.background,Co),t.cursor=Jt.blend(t.background,It(e.cursor,Pb)),t.cursorAccent=Jt.blend(t.background,It(e.cursorAccent,Ib)),t.selectionBackgroundTransparent=It(e.selectionBackground,po),t.selectionBackgroundOpaque=Jt.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=It(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=Jt.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?It(e.selectionForeground,Db):void 0,t.selectionForeground===Db&&(t.selectionForeground=void 0),Jt.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=Jt.opacity(t.selectionBackgroundTransparent,.3)),Jt.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=Jt.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=It(e.scrollbarSliderBackground,Jt.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=It(e.scrollbarSliderHoverBackground,Jt.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=It(e.scrollbarSliderActiveBackground,Jt.opacity(t.foreground,.5)),t.overviewRulerBorder=It(e.overviewRulerBorder,V2),t.ansi=Li.slice(),t.ansi[0]=It(e.black,Li[0]),t.ansi[1]=It(e.red,Li[1]),t.ansi[2]=It(e.green,Li[2]),t.ansi[3]=It(e.yellow,Li[3]),t.ansi[4]=It(e.blue,Li[4]),t.ansi[5]=It(e.magenta,Li[5]),t.ansi[6]=It(e.cyan,Li[6]),t.ansi[7]=It(e.white,Li[7]),t.ansi[8]=It(e.brightBlack,Li[8]),t.ansi[9]=It(e.brightRed,Li[9]),t.ansi[10]=It(e.brightGreen,Li[10]),t.ansi[11]=It(e.brightYellow,Li[11]),t.ansi[12]=It(e.brightBlue,Li[12]),t.ansi[13]=It(e.brightMagenta,Li[13]),t.ansi[14]=It(e.brightCyan,Li[14]),t.ansi[15]=It(e.brightWhite,Li[15]),e.extendedAnsi){let i=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let s=0;so.index-c.index),s=[];for(let o of i){let c=this._services.get(o.id);if(!c)throw new Error(`[createInstance] ${e.name} depends on UNKNOWN service ${o.id._id}.`);s.push(c)}let a=i.length>0?i[0].index:t.length;if(t.length!==a)throw new Error(`[createInstance] First service dependency of ${e.name} at position ${a+1} conflicts with ${t.length} static arguments`);return new e(...t,...s)}},Z2={trace:0,debug:1,info:2,warn:3,error:4,off:5},Q2="xterm.js: ",gp=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=Z2[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?Is(i&2097151):""}isProtected(t){return this._data[t*ct+2]&536870912}loadCell(t,i){return lu=t*ct,i.content=this._data[lu+0],i.fg=this._data[lu+1],i.bg=this._data[lu+2],i.content&2097152&&(i.combinedData=this._combined[t]),i.bg&268435456&&(i.extended=this._extendedAttrs[t]),i}setCell(t,i){i.content&2097152&&(this._combined[t]=i.combinedData),i.bg&268435456&&(this._extendedAttrs[t]=i.extended),this._data[t*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]+=Is(i):a&2097151?(this._combined[t]=Is(a&2097151)+Is(i),a&=-2097152,a|=2097152):a=i|1<<22,s&&(a&=-12582913,a|=s<<22),this._data[t*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*cf=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 J2(e,t,i,s,a,o){let c=[];for(let h=0;h=h&&s0&&(B>x||_[B].getTrimmedLength()===0);B--)N++;N>0&&(c.push(h+_.length-N),c.push(N)),h+=_.length-1}return c}function eE(e,t){let i=[],s=0,a=t[s],o=0;for(let c=0;czo(e,f,t)).reduce((p,f)=>p+f),o=0,c=0,h=0;for(;hp&&(o-=p,c++);let f=e[c].getWidth(o-1)===2;f&&o--;let _=f?i-1:i;s.push(_),h+=_}return s}function zo(e,t,i){if(t===e.length-1)return e[t].getTrimmedLength();let s=!e[t].hasContent(i-1)&&e[t].getWidth(i-1)===1,a=e[t+1].getWidth(0)===2;return s&&a?i-1:i}var _0=class b0{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=b0._nextId++,this._onDispose=this.register(new Ce),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),xa(this._disposables),this._disposables.length=0)}register(t){return this._disposables.push(t),t}};_0._nextId=1;var nE=_0,Pi={},pa=Pi.B;Pi[0]={"`":"◆",a:"▒",b:"␉",c:"␌",d:"␍",e:"␊",f:"°",g:"±",h:"␤",i:"␋",j:"┘",k:"┐",l:"┌",m:"└",n:"┼",o:"⎺",p:"⎻",q:"─",r:"⎼",s:"⎽",t:"├",u:"┤",v:"┴",w:"┬",x:"│",y:"≤",z:"≥","{":"π","|":"≠","}":"£","~":"·"};Pi.A={"#":"£"};Pi.B=void 0;Pi[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"};Pi.C=Pi[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};Pi.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"};Pi.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"};Pi.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"};Pi.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"};Pi.E=Pi[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"};Pi.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"};Pi.H=Pi[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};Pi["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"};var Ub=4294967295,$b=class{constructor(e,t,i){this._hasScrollback=e,this._optionsService=t,this._bufferService=i,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=Ai.clone(),this.savedCharset=pa,this.markers=[],this._nullCell=cr.fromCharData([0,Oy,1,0]),this._whitespaceCell=cr.fromCharData([0,Us,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new Ru,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new Hb(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new Nu),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new Nu),this._whitespaceCell}getBlankLine(e,t){return new ko(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&eUb?Ub:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=Ai);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new Hb(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let i=this.getNullCell(Ai),s=0,a=this._getCorrectBufferLength(t);if(a>this.lines.maxLength&&(this.lines.maxLength=a),this.lines.length>0){if(this._cols0&&this.lines.length<=this.ybase+this.y+o+1?(this.ybase--,o++,this.ydisp>0&&this.ydisp--):this.lines.push(new ko(e,i)));else for(let c=this._rows;c>t;c--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(a0&&(this.lines.trimStart(c),this.ybase=Math.max(this.ybase-c,0),this.ydisp=Math.max(this.ydisp-c,0),this.savedY=Math.max(this.savedY-c,0)),this.lines.maxLength=a}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),o&&(this.y+=o),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let o=0;o.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend==="conpty"&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let i=this._optionsService.rawOptions.reflowCursorLine,s=J2(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(Ai),i);if(s.length>0){let a=eE(this.lines,s);tE(this.lines,a.layout),this._reflowLargerAdjustViewport(e,t,a.countRemoved)}}_reflowLargerAdjustViewport(e,t,i){let s=this.getNullCell(Ai),a=i;for(;a-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length=0;c--){let h=this.lines.get(c);if(!h||!h.isWrapped&&h.getTrimmedLength()<=e)continue;let p=[h];for(;h.isWrapped&&c>0;)h=this.lines.get(--c),p.unshift(h);if(!i){let H=this.ybase+this.y;if(H>=c&&H0&&(a.push({start:c+p.length+o,newLines:v}),o+=v.length),p.push(...v);let S=_.length-1,N=_[S];N===0&&(S--,N=_[S]);let B=p.length-x-1,E=f;for(;B>=0;){let H=Math.min(E,N);if(p[S]===void 0)break;if(p[S].copyCellsFrom(p[B],E-H,N-H,H,!0),N-=H,N===0&&(S--,N=_[S]),E-=H,E===0){B--;let A=Math.max(B,0);E=zo(p,A,this._cols)}}for(let H=0;H0;)this.ybase===0?this.y0){let c=[],h=[];for(let N=0;N=0;N--)if(x&&x.start>f+b){for(let B=x.newLines.length-1;B>=0;B--)this.lines.set(N--,x.newLines[B]);N++,c.push({index:f+1,amount:x.newLines.length}),b+=x.newLines.length,x=a[++_]}else this.lines.set(N,h[f--]);let v=0;for(let N=c.length-1;N>=0;N--)c[N].index+=v,this.lines.onInsertEmitter.fire(c[N]),v+=c[N].amount;let S=Math.max(0,p+o-this.lines.maxLength);S>0&&this.lines.onTrimEmitter.fire(S)}}translateBufferLineToString(e,t,i=0,s){let a=this.lines.get(e);return a?a.translateToString(t,i,s):""}getWrappedRangeForLine(e){let t=e,i=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;i+10;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e==null&&(e=this.x);!this.tabs[++e]&&e=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t{t.line-=i,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(i=>{t.line>=i.index&&(t.line+=i.amount)})),t.register(this.lines.onDelete(i=>{t.line>=i.index&&t.linei.index&&(t.line-=i.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},rE=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 $b(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new $b(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}},v0=2,y0=1,xp=class extends 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,v0),this.rows=Math.max(e.rawOptions.rows||0,y0),this.buffers=this._register(new rE(e,this)),this._register(this.buffers.onBufferActivate(t=>{this._onScroll.fire(t.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let i=this.cols!==e,s=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:i,rowsChanged:s})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let i=this.buffer,s;s=this._cachedBlankLine,(!s||s.length!==this.cols||s.getFg(0)!==e.fg||s.getBg(0)!==e.bg)&&(s=i.getBlankLine(e,t),this._cachedBlankLine=s),s.isWrapped=t;let a=i.ybase+i.scrollTop,o=i.ybase+i.scrollBottom;if(i.scrollTop===0){let c=i.lines.isFull;o===i.lines.length-1?c?i.lines.recycle().copyFrom(s):i.lines.push(s.clone()):i.lines.splice(o+1,0,s.clone()),c?this.isUserScrolling&&(i.ydisp=Math.max(i.ydisp-1,0)):(i.ybase++,this.isUserScrolling||i.ydisp++)}else{let c=o-a+1;i.lines.shiftElements(a+1,c-1,-1),i.lines.set(o,s.clone())}this.isUserScrolling||(i.ydisp=i.ybase),this._onScroll.fire(i.ydisp)}scrollLines(e,t){let i=this.buffer;if(e<0){if(i.ydisp===0)return;this.isUserScrolling=!0}else e+i.ydisp>=i.ybase&&(this.isUserScrolling=!1);let s=i.ydisp;i.ydisp=Math.max(Math.min(i.ydisp+e,i.ybase),0),s!==i.ydisp&&(t||this._onScroll.fire(i.ydisp))}};xp=pi([De(0,yn)],xp);var il={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:Au,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}},sE=["normal","bold","100","200","300","400","500","600","700","800","900"],aE=class extends ut{constructor(e){super(),this._onOptionChange=this._register(new Ce),this.onOptionChange=this._onOptionChange.event;let t={...il};for(let i in e)if(i in t)try{let s=e[i];t[i]=this._sanitizeAndValidateOption(i,s)}catch(s){console.error(s)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register(ti(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(i=>{i===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(i=>{e.indexOf(i)!==-1&&t()})}_setupOptions(){let e=i=>{if(!(i in il))throw new Error(`No option with key "${i}"`);return this.rawOptions[i]},t=(i,s)=>{if(!(i in il))throw new Error(`No option with key "${i}"`);s=this._sanitizeAndValidateOption(i,s),this.rawOptions[i]!==s&&(this.rawOptions[i]=s,this._onOptionChange.fire(i))};for(let i in this.rawOptions){let s={get:e.bind(this,i),set:t.bind(this,i)};Object.defineProperty(this.options,i,s)}}_sanitizeAndValidateOption(e,t){switch(e){case"cursorStyle":if(t||(t=il[e]),!lE(t))throw new Error(`"${t}" is not a valid value for ${e}`);break;case"wordSeparator":t||(t=il[e]);break;case"fontWeight":case"fontWeightBold":if(typeof t=="number"&&1<=t&&t<=1e3)break;t=sE.includes(t)?t:il[e];break;case"cursorWidth":t=Math.floor(t);case"lineHeight":case"tabStopWidth":if(t<1)throw new Error(`${e} cannot be less than 1, value: ${t}`);break;case"minimumContrastRatio":t=Math.max(1,Math.min(21,Math.round(t*10)/10));break;case"scrollback":if(t=Math.min(t,4294967295),t<0)throw new Error(`${e} cannot be less than 0, value: ${t}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(t<=0)throw new Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case"rows":case"cols":if(!t&&t!==0)throw new Error(`${e} must be numeric, value: ${t}`);break;case"windowsPty":t=t??{};break}return t}};function lE(e){return e==="block"||e==="underline"||e==="bar"}function Eo(e,t=5){if(typeof e!="object")return e;let i=Array.isArray(e)?[]:{};for(let s in e)i[s]=t<=1?e[s]:e[s]&&Eo(e[s],t-1);return i}var Fb=Object.freeze({insertMode:!1}),qb=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),_p=class extends 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=Eo(Fb),this.decPrivateModes=Eo(qb)}reset(){this.modes=Eo(Fb),this.decPrivateModes=Eo(qb)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let i=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&i.ybase!==i.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace("sending data (codes)",()=>e.split("").map(s=>s.charCodeAt(0))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace("sending binary (codes)",()=>e.split("").map(t=>t.charCodeAt(0))),this._onBinary.fire(e))}};_p=pi([De(0,vn),De(1,Uy),De(2,yn)],_p);var Wb={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>e.button===4||e.action!==1?!1:(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>e.action!==32},DRAG:{events:23,restrict:e=>!(e.action===32&&e.button===3)},ANY:{events:31,restrict:e=>!0}};function uf(e,t){let i=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(i|=64,i|=e.action):(i|=e.button&3,e.button&4&&(i|=64),e.button&8&&(i|=128),e.action===32?i|=32:e.action===0&&!t&&(i|=3)),i}var hf=String.fromCharCode,Gb={DEFAULT:e=>{let t=[uf(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`\x1B[M${hf(t[0])}${hf(t[1])}${hf(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${uf(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${uf(e,!0)};${e.x};${e.y}${t}`}},bp=class extends 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(Wb))this.addProtocol(s,Wb[s]);for(let s of Object.keys(Gb))this.addEncoding(s,Gb[s]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw new Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw new Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,i){if(e.deltaY===0||e.shiftKey||t===void 0||i===void 0)return 0;let s=t/i,a=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(a/=s+0,Math.abs(e.deltaY)<50&&(a*=.3),this._wheelPartialScroll+=a,a=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(a*=this._bufferService.rows),a}_applyScrollModifier(e,t){return t.altKey||t.ctrlKey||t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding==="SGR_PIXELS"))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(e&1),up:!!(e&2),drag:!!(e&4),move:!!(e&8),wheel:!!(e&16)}}_equalEvents(e,t,i){if(i){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return!(e.button!==t.button||e.action!==t.action||e.ctrl!==t.ctrl||e.alt!==t.alt||e.shift!==t.shift)}};bp=pi([De(0,vn),De(1,va),De(2,yn)],bp);var df=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],oE=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],Oi;function cE(e,t){let i=0,s=t.length-1,a;if(et[s][1])return!1;for(;s>=i;)if(a=i+s>>1,e>t[a][1])i=a+1;else if(e=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let i=this.wcwidth(e),s=i===0&&t!==0;if(s){let a=ma.extractWidth(t);a===0?s=!1:a>i&&(i=a)}return ma.createPropertyValue(0,i,s)}},ma=class yu{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new Ce,this.onChange=this._onChange.event;let t=new uE;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)}},hE=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}};function Yb(e){var s;let t=(s=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1))==null?void 0:s.get(e.cols-1),i=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);i&&t&&(i.isWrapped=t[3]!==0&&t[3]!==32)}var mo=2147483647,dE=256,S0=class vp{constructor(t=32,i=32){if(this.maxLength=t,this.maxSubParamsLength=i,i>dE)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(t),this.length=0,this._subParams=new Int32Array(i),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(t),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let i=new vp;if(!t.length)return i;for(let s=Array.isArray(t[0])?1:0;s>8,a=this._subParamsIdx[i]&255;a-s>0&&t.push(Array.prototype.slice.call(this._subParams,s,a))}return t}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(t){if(this._digitIsSub=!1,this.length>=this.maxLength){this._rejectDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=t>mo?mo:t}addSubParam(t){if(this._digitIsSub=!0,!!this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=t>mo?mo:t,this._subParamsIdx[this.length-1]++}}hasSubParams(t){return(this._subParamsIdx[t]&255)-(this._subParamsIdx[t]>>8)>0}getSubParams(t){let i=this._subParamsIdx[t]>>8,s=this._subParamsIdx[t]&255;return s-i>0?this._subParams.subarray(i,s):null}getSubParamsAll(){let t={};for(let i=0;i>8,a=this._subParamsIdx[i]&255;a-s>0&&(t[i]=this._subParams.slice(s,a))}return t}addDigit(t){let i;if(this._rejectDigits||!(i=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let s=this._digitIsSub?this._subParams:this.params,a=s[i-1];s[i-1]=~a?Math.min(a*10+t,mo):t}},go=[],fE=class{constructor(){this._state=0,this._active=go,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let i=this._handlers[e];return i.push(t),{dispose:()=>{let s=i.indexOf(t);s!==-1&&i.splice(s,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=go}reset(){if(this._state===2)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=go,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||go,!this._active.length)this._handlerFb(this._id,"START");else for(let e=this._active.length-1;e>=0;e--)this._active[e].start()}_put(e,t,i){if(!this._active.length)this._handlerFb(this._id,"PUT",Iu(e,t,i));else for(let s=this._active.length-1;s>=0;s--)this._active[s].put(e,t,i)}start(){this.reset(),this._state=1}put(e,t,i){if(this._state!==3){if(this._state===1)for(;t0&&this._put(e,t,i)}}end(e,t=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),!this._active.length)this._handlerFb(this._id,"END",e);else{let i=!1,s=this._active.length-1,a=!1;if(this._stack.paused&&(s=this._stack.loopPosition-1,i=t,a=this._stack.fallThrough,this._stack.paused=!1),!a&&i===!1){for(;s>=0&&(i=this._active[s].end(e),i!==!0);s--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!1,i;s--}for(;s>=0;s--)if(i=this._active[s].end(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!0,i}this._active=go,this._id=-1,this._state=0}}},Wn=class{constructor(e){this._handler=e,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=Iu(e,t,i),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then(i=>(this._data="",this._hitLimit=!1,i));return this._data="",this._hitLimit=!1,t}},xo=[],pE=class{constructor(){this._handlers=Object.create(null),this._active=xo,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=xo}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let i=this._handlers[e];return i.push(t),{dispose:()=>{let s=i.indexOf(t);s!==-1&&i.splice(s,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=xo,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||xo,!this._active.length)this._handlerFb(this._ident,"HOOK",t);else for(let i=this._active.length-1;i>=0;i--)this._active[i].hook(t)}put(e,t,i){if(!this._active.length)this._handlerFb(this._ident,"PUT",Iu(e,t,i));else for(let s=this._active.length-1;s>=0;s--)this._active[s].put(e,t,i)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,"UNHOOK",e);else{let i=!1,s=this._active.length-1,a=!1;if(this._stack.paused&&(s=this._stack.loopPosition-1,i=t,a=this._stack.fallThrough,this._stack.paused=!1),!a&&i===!1){for(;s>=0&&(i=this._active[s].unhook(e),i!==!0);s--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!1,i;s--}for(;s>=0;s--)if(i=this._active[s].unhook(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!0,i}this._active=xo,this._ident=0}},No=new S0;No.addParam(0);var Vb=class{constructor(e){this._handler=e,this._data="",this._params=No,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():No,this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=Iu(e,t,i),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then(i=>(this._params=No,this._data="",this._hitLimit=!1,i));return this._params=No,this._data="",this._hitLimit=!1,t}},mE=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(lr,0,2,0),e.add(lr,8,5,8),e.add(lr,6,0,6),e.add(lr,11,0,11),e.add(lr,13,13,13),e})(),xE=class extends ut{constructor(e=gE){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new S0,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(t,i,s)=>{},this._executeHandlerFb=t=>{},this._csiHandlerFb=(t,i)=>{},this._escHandlerFb=t=>{},this._errorHandlerFb=t=>t,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register(ti(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new fE),this._dcsParser=this._register(new pE),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},()=>!0)}_identifier(e,t=[64,126]){let i=0;if(e.prefix){if(e.prefix.length>1)throw new Error("only one byte as prefix supported");if(i=e.prefix.charCodeAt(0),i&&60>i||i>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(e.intermediates){if(e.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let a=0;ao||o>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");i<<=8,i|=o}}if(e.final.length!==1)throw new Error("final must be a single byte");let s=e.final.charCodeAt(0);if(t[0]>s||s>t[1])throw new Error(`final must be in range ${t[0]} .. ${t[1]}`);return i<<=8,i|=s,i}identToString(e){let t=[];for(;e;)t.push(String.fromCharCode(e&255)),e>>=8;return t.reverse().join("")}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){let i=this._identifier(e,[48,126]);this._escHandlers[i]===void 0&&(this._escHandlers[i]=[]);let s=this._escHandlers[i];return s.push(t),{dispose:()=>{let a=s.indexOf(t);a!==-1&&s.splice(a,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){let i=this._identifier(e);this._csiHandlers[i]===void 0&&(this._csiHandlers[i]=[]);let s=this._csiHandlers[i];return s.push(t),{dispose:()=>{let a=s.indexOf(t);a!==-1&&s.splice(a,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,i,s,a){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=i,this._parseStack.transition=s,this._parseStack.chunkPos=a}parse(e,t,i){let s=0,a=0,o=0,c;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,o=this._parseStack.chunkPos+1;else{if(i===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");let h=this._parseStack.handlers,p=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(i===!1&&p>-1){for(;p>=0&&(c=h[p](this._params),c!==!0);p--)if(c instanceof Promise)return this._parseStack.handlerPos=p,c}this._parseStack.handlers=[];break;case 4:if(i===!1&&p>-1){for(;p>=0&&(c=h[p](),c!==!0);p--)if(c instanceof Promise)return this._parseStack.handlerPos=p,c}this._parseStack.handlers=[];break;case 6:if(s=e[this._parseStack.chunkPos],c=this._dcsParser.unhook(s!==24&&s!==26,i),c)return c;s===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(s=e[this._parseStack.chunkPos],c=this._oscParser.end(s!==24&&s!==26,i),c)return c;s===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break}this._parseStack.state=0,o=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}for(let h=o;h>4){case 2:for(let b=h+1;;++b){if(b>=t||(s=e[b])<32||s>126&&s=t||(s=e[b])<32||s>126&&s=t||(s=e[b])<32||s>126&&s=t||(s=e[b])<32||s>126&&s=0&&(c=p[f](this._params),c!==!0);f--)if(c instanceof Promise)return this._preserveStack(3,p,f,a,h),c;f<0&&this._csiHandlerFb(this._collect<<8|s,this._params),this.precedingJoinState=0;break;case 8:do switch(s){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(s-48)}while(++h47&&s<60);h--;break;case 9:this._collect<<=8,this._collect|=s;break;case 10:let _=this._escHandlers[this._collect<<8|s],x=_?_.length-1:-1;for(;x>=0&&(c=_[x](),c!==!0);x--)if(c instanceof Promise)return this._preserveStack(4,_,x,a,h),c;x<0&&this._escHandlerFb(this._collect<<8|s),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|s,this._params);break;case 13:for(let b=h+1;;++b)if(b>=t||(s=e[b])===24||s===26||s===27||s>127&&s=t||(s=e[b])<32||s>127&&s>4:o>>8}return s}}function ff(e,t){let i=e.toString(16),s=i.length<2?"0"+i:i;switch(t){case 4:return i[0];case 8:return s;case 12:return(s+s).slice(0,3);default:return s+s}}function vE(e,t=16){let[i,s,a]=e;return`rgb:${ff(i,t)}/${ff(s,t)}/${ff(a,t)}`}var yE={"(":0,")":1,"*":2,"+":3,"-":1,".":2},zs=131072,Xb=10;function Zb(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var Qb=5e3,Jb=0,SE=class extends ut{constructor(e,t,i,s,a,o,c,h,p=new xE){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 UC,this._utf8Decoder=new $C,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=Ai.clone(),this._eraseAttrDataInternal=Ai.clone(),this._onRequestBell=this._register(new Ce),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new Ce),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new Ce),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new Ce),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new Ce),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new Ce),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new Ce),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new Ce),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new Ce),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new Ce),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new Ce),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new Ce),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new Ce),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this._register(this._parser),this._dirtyRowTracker=new yp(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(f=>this._activeBuffer=f.activeBuffer)),this._parser.setCsiHandlerFallback((f,_)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(f),params:_.toArray()})}),this._parser.setEscHandlerFallback(f=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(f)})}),this._parser.setExecuteHandlerFallback(f=>{this._logService.debug("Unknown EXECUTE code: ",{code:f})}),this._parser.setOscHandlerFallback((f,_,x)=>{this._logService.debug("Unknown OSC code: ",{identifier:f,action:_,data:x})}),this._parser.setDcsHandlerFallback((f,_,x)=>{_==="HOOK"&&(x=x.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(f),action:_,payload:x})}),this._parser.setPrintHandler((f,_,x)=>this.print(f,_,x)),this._parser.registerCsiHandler({final:"@"},f=>this.insertChars(f)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},f=>this.scrollLeft(f)),this._parser.registerCsiHandler({final:"A"},f=>this.cursorUp(f)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},f=>this.scrollRight(f)),this._parser.registerCsiHandler({final:"B"},f=>this.cursorDown(f)),this._parser.registerCsiHandler({final:"C"},f=>this.cursorForward(f)),this._parser.registerCsiHandler({final:"D"},f=>this.cursorBackward(f)),this._parser.registerCsiHandler({final:"E"},f=>this.cursorNextLine(f)),this._parser.registerCsiHandler({final:"F"},f=>this.cursorPrecedingLine(f)),this._parser.registerCsiHandler({final:"G"},f=>this.cursorCharAbsolute(f)),this._parser.registerCsiHandler({final:"H"},f=>this.cursorPosition(f)),this._parser.registerCsiHandler({final:"I"},f=>this.cursorForwardTab(f)),this._parser.registerCsiHandler({final:"J"},f=>this.eraseInDisplay(f,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},f=>this.eraseInDisplay(f,!0)),this._parser.registerCsiHandler({final:"K"},f=>this.eraseInLine(f,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},f=>this.eraseInLine(f,!0)),this._parser.registerCsiHandler({final:"L"},f=>this.insertLines(f)),this._parser.registerCsiHandler({final:"M"},f=>this.deleteLines(f)),this._parser.registerCsiHandler({final:"P"},f=>this.deleteChars(f)),this._parser.registerCsiHandler({final:"S"},f=>this.scrollUp(f)),this._parser.registerCsiHandler({final:"T"},f=>this.scrollDown(f)),this._parser.registerCsiHandler({final:"X"},f=>this.eraseChars(f)),this._parser.registerCsiHandler({final:"Z"},f=>this.cursorBackwardTab(f)),this._parser.registerCsiHandler({final:"`"},f=>this.charPosAbsolute(f)),this._parser.registerCsiHandler({final:"a"},f=>this.hPositionRelative(f)),this._parser.registerCsiHandler({final:"b"},f=>this.repeatPrecedingCharacter(f)),this._parser.registerCsiHandler({final:"c"},f=>this.sendDeviceAttributesPrimary(f)),this._parser.registerCsiHandler({prefix:">",final:"c"},f=>this.sendDeviceAttributesSecondary(f)),this._parser.registerCsiHandler({final:"d"},f=>this.linePosAbsolute(f)),this._parser.registerCsiHandler({final:"e"},f=>this.vPositionRelative(f)),this._parser.registerCsiHandler({final:"f"},f=>this.hVPosition(f)),this._parser.registerCsiHandler({final:"g"},f=>this.tabClear(f)),this._parser.registerCsiHandler({final:"h"},f=>this.setMode(f)),this._parser.registerCsiHandler({prefix:"?",final:"h"},f=>this.setModePrivate(f)),this._parser.registerCsiHandler({final:"l"},f=>this.resetMode(f)),this._parser.registerCsiHandler({prefix:"?",final:"l"},f=>this.resetModePrivate(f)),this._parser.registerCsiHandler({final:"m"},f=>this.charAttributes(f)),this._parser.registerCsiHandler({final:"n"},f=>this.deviceStatus(f)),this._parser.registerCsiHandler({prefix:"?",final:"n"},f=>this.deviceStatusPrivate(f)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},f=>this.softReset(f)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},f=>this.setCursorStyle(f)),this._parser.registerCsiHandler({final:"r"},f=>this.setScrollRegion(f)),this._parser.registerCsiHandler({final:"s"},f=>this.saveCursor(f)),this._parser.registerCsiHandler({final:"t"},f=>this.windowOptions(f)),this._parser.registerCsiHandler({final:"u"},f=>this.restoreCursor(f)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},f=>this.insertColumns(f)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},f=>this.deleteColumns(f)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},f=>this.selectProtected(f)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},f=>this.requestMode(f,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},f=>this.requestMode(f,!1)),this._parser.setExecuteHandler(pe.BEL,()=>this.bell()),this._parser.setExecuteHandler(pe.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(pe.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(pe.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(pe.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(pe.BS,()=>this.backspace()),this._parser.setExecuteHandler(pe.HT,()=>this.tab()),this._parser.setExecuteHandler(pe.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(pe.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(bu.IND,()=>this.index()),this._parser.setExecuteHandler(bu.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(bu.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new Wn(f=>(this.setTitle(f),this.setIconName(f),!0))),this._parser.registerOscHandler(1,new Wn(f=>this.setIconName(f))),this._parser.registerOscHandler(2,new Wn(f=>this.setTitle(f))),this._parser.registerOscHandler(4,new Wn(f=>this.setOrReportIndexedColor(f))),this._parser.registerOscHandler(8,new Wn(f=>this.setHyperlink(f))),this._parser.registerOscHandler(10,new Wn(f=>this.setOrReportFgColor(f))),this._parser.registerOscHandler(11,new Wn(f=>this.setOrReportBgColor(f))),this._parser.registerOscHandler(12,new Wn(f=>this.setOrReportCursorColor(f))),this._parser.registerOscHandler(104,new Wn(f=>this.restoreIndexedColor(f))),this._parser.registerOscHandler(110,new Wn(f=>this.restoreFgColor(f))),this._parser.registerOscHandler(111,new Wn(f=>this.restoreBgColor(f))),this._parser.registerOscHandler(112,new Wn(f=>this.restoreCursorColor(f))),this._parser.registerEscHandler({final:"7"},()=>this.saveCursor()),this._parser.registerEscHandler({final:"8"},()=>this.restoreCursor()),this._parser.registerEscHandler({final:"D"},()=>this.index()),this._parser.registerEscHandler({final:"E"},()=>this.nextLine()),this._parser.registerEscHandler({final:"H"},()=>this.tabSet()),this._parser.registerEscHandler({final:"M"},()=>this.reverseIndex()),this._parser.registerEscHandler({final:"="},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:">"},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:"c"},()=>this.fullReset()),this._parser.registerEscHandler({final:"n"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"o"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"|"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"}"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"~"},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:"%",final:"@"},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:"%",final:"G"},()=>this.selectDefaultCharset());for(let f in Pi)this._parser.registerEscHandler({intermediates:"(",final:f},()=>this.selectCharset("("+f)),this._parser.registerEscHandler({intermediates:")",final:f},()=>this.selectCharset(")"+f)),this._parser.registerEscHandler({intermediates:"*",final:f},()=>this.selectCharset("*"+f)),this._parser.registerEscHandler({intermediates:"+",final:f},()=>this.selectCharset("+"+f)),this._parser.registerEscHandler({intermediates:"-",final:f},()=>this.selectCharset("-"+f)),this._parser.registerEscHandler({intermediates:".",final:f},()=>this.selectCharset("."+f)),this._parser.registerEscHandler({intermediates:"/",final:f},()=>this.selectCharset("/"+f));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(f=>(this._logService.error("Parsing error: ",f),f)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new Vb((f,_)=>this.requestStatusString(f,_)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,i,s){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=i,this._parseStack.position=s}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((t,i)=>setTimeout(()=>i("#SLOW_TIMEOUT"),Qb))]).catch(t=>{if(t!=="#SLOW_TIMEOUT")throw t;console.warn(`async parser handler taking longer than ${Qb} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let i,s=this._activeBuffer.x,a=this._activeBuffer.y,o=0,c=this._parseStack.paused;if(c){if(i=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(i),i;s=this._parseStack.cursorStartX,a=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>zs&&(o=this._parseStack.position+zs)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e=="string"?` "${e}"`:` "${Array.prototype.map.call(e,f=>String.fromCharCode(f)).join("")}"`}`),this._logService.logLevel===0&&this._logService.trace("parsing data (codes)",typeof e=="string"?e.split("").map(f=>f.charCodeAt(0)):e),this._parseBuffer.lengthzs)for(let f=o;f0&&x.getWidth(this._activeBuffer.x-1)===2&&x.setCellFromCodepoint(this._activeBuffer.x-1,0,1,_);let b=this._parser.precedingJoinState;for(let v=t;vh){if(p){let E=x,O=this._activeBuffer.x-B;for(this._activeBuffer.x=B,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),B>0&&x instanceof ko&&x.copyCellsFrom(E,O,0,B,!1);O=0;)x.setCellFromCodepoint(this._activeBuffer.x++,0,0,_);continue}if(f&&(x.insertCells(this._activeBuffer.x,a-B,this._activeBuffer.getNullCell(_)),x.getWidth(h-1)===2&&x.setCellFromCodepoint(h-1,0,1,_)),x.setCellFromCodepoint(this._activeBuffer.x++,s,a,_),a>0)for(;--a;)x.setCellFromCodepoint(this._activeBuffer.x++,0,0,_)}this._parser.precedingJoinState=b,this._activeBuffer.x0&&x.getWidth(this._activeBuffer.x)===0&&!x.hasContent(this._activeBuffer.x)&&x.setCellFromCodepoint(this._activeBuffer.x,0,1,_),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final==="t"&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,i=>Zb(i.params[0],this._optionsService.rawOptions.windowOptions)?t(i):!0):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new Vb(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new Wn(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){var e;if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&((e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y))!=null&&e.isWrapped)){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);t.hasWidth(this._activeBuffer.x)&&!t.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),(t===2||t===0)&&(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,i,s=!1,a=!1){let o=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);o.replaceCells(t,i,this._activeBuffer.getNullCell(this._eraseAttrData()),a),s&&(o.isWrapped=!1)}_resetBufferLine(e,t=!1){let i=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);i&&(i.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),i.isWrapped=!1)}eraseInDisplay(e,t=!1){var s;this._restrictCursor(this._bufferService.cols);let i;switch(e.params[0]){case 0:for(i=this._activeBuffer.y,this._dirtyRowTracker.markDirty(i),this._eraseInBufferLine(i++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);i=this._bufferService.cols&&(this._activeBuffer.lines.get(i+1).isWrapped=!1);i--;)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(i=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,i-1);i--&&!((s=this._activeBuffer.lines.get(this._activeBuffer.ybase+i))!=null&&s.getTrimmedLength()););for(;i>=0;i--)this._bufferService.scroll(this._eraseAttrData())}else{for(i=this._bufferService.rows,this._dirtyRowTracker.markDirty(i-1);i--;)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let a=this._activeBuffer.lines.length-this._bufferService.rows;a>0&&(this._activeBuffer.lines.trimStart(a),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-a,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-a,0),this._onScroll.fire(0));break}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t);break}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.y65535?2:1}let p=h;for(let f=1;f0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(pe.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(pe.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(pe.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(pe.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(e.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(pe.ESC+"[>83;40003;0c")),!0}_is(e){return(this._optionsService.rawOptions.termName+"").indexOf(e)===0}setMode(e){for(let t=0;t(N[N.NOT_RECOGNIZED=0]="NOT_RECOGNIZED",N[N.SET=1]="SET",N[N.RESET=2]="RESET",N[N.PERMANENTLY_SET=3]="PERMANENTLY_SET",N[N.PERMANENTLY_RESET=4]="PERMANENTLY_RESET"))(void 0||(i={}));let s=this._coreService.decPrivateModes,{activeProtocol:a,activeEncoding:o}=this._coreMouseService,c=this._coreService,{buffers:h,cols:p}=this._bufferService,{active:f,alt:_}=h,x=this._optionsService.rawOptions,b=(N,B)=>(c.triggerDataEvent(`${pe.ESC}[${t?"":"?"}${N};${B}$y`),!0),v=N=>N?1:2,S=e.params[0];return t?S===2?b(S,4):S===4?b(S,v(c.modes.insertMode)):S===12?b(S,3):S===20?b(S,v(x.convertEol)):b(S,0):S===1?b(S,v(s.applicationCursorKeys)):S===3?b(S,x.windowOptions.setWinLines?p===80?2:p===132?1:0:0):S===6?b(S,v(s.origin)):S===7?b(S,v(s.wraparound)):S===8?b(S,3):S===9?b(S,v(a==="X10")):S===12?b(S,v(x.cursorBlink)):S===25?b(S,v(!c.isCursorHidden)):S===45?b(S,v(s.reverseWraparound)):S===66?b(S,v(s.applicationKeypad)):S===67?b(S,4):S===1e3?b(S,v(a==="VT200")):S===1002?b(S,v(a==="DRAG")):S===1003?b(S,v(a==="ANY")):S===1004?b(S,v(s.sendFocus)):S===1005?b(S,4):S===1006?b(S,v(o==="SGR")):S===1015?b(S,4):S===1016?b(S,v(o==="SGR_PIXELS")):S===1048?b(S,1):S===47||S===1047||S===1049?b(S,v(f===_)):S===2004?b(S,v(s.bracketedPasteMode)):S===2026?b(S,v(s.synchronizedOutput)):b(S,0)}_updateAttrColor(e,t,i,s,a){return t===2?(e|=50331648,e&=-16777216,e|=$o.fromColorRGB([i,s,a])):t===5&&(e&=-50331904,e|=33554432|i&255),e}_extractColor(e,t,i){let s=[0,0,-1,0,0,0],a=0,o=0;do{if(s[o+a]=e.params[t+o],e.hasSubParams(t+o)){let c=e.getSubParams(t+o),h=0;do s[1]===5&&(a=1),s[o+h+1+a]=c[h];while(++h=2||s[1]===2&&o+a>=5)break;s[1]&&(a=1)}while(++o+t5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=Ai.fg,e.bg=Ai.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|=Ai.fg&16777215):i===49?(s.bg&=-67108864,s.bg|=Ai.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|=Ai.fg&16777215,s.bg&=-67108864,s.bg|=Ai.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=Ai.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.length===0?1:e.params[0];if(t===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t){case 1:case 2:this._coreService.decPrivateModes.cursorStyle="block";break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle="underline";break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle="bar";break}let i=t%2===1;this._coreService.decPrivateModes.cursorBlink=i}return!0}setScrollRegion(e){let t=e.params[0]||1,i;return(e.length<2||(i=e.params[1])>this._bufferService.rows||i===0)&&(i=this._bufferService.rows),i>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=i-1,this._setCursor(0,0)),!0}windowOptions(e){if(!Zb(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${pe.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>Xb&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>Xb&&this._iconNameStack.shift());break;case 23:(t===0||t===2)&&this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),(t===0||t===1)&&this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop());break}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],i=e.split(";");for(;i.length>1;){let s=i.shift(),a=i.shift();if(/^\d+$/.exec(s)){let o=parseInt(s);if(ev(o))if(a==="?")t.push({type:0,index:o});else{let c=Kb(a);c&&t.push({type:1,index:o,color:c})}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(";");if(t===-1)return!0;let i=e.slice(0,t).trim(),s=e.slice(t+1);return s?this._createHyperlink(i,s):i.trim()?!1:this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let i=e.split(":"),s,a=i.findIndex(o=>o.startsWith("id="));return a!==-1&&(s=i[a].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:s,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let i=e.split(";");for(let s=0;s=this._specialColors.length);++s,++t)if(i[s]==="?")this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let a=Kb(i[s]);a&&this._onColor.fire([{type:1,index:this._specialColors[t],color:a}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],i=e.split(";");for(let s=0;s=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=Ai.clone(),this._eraseAttrDataInternal=Ai.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 cr;e.content=1<<22|69,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t(this._coreService.triggerDataEvent(`${pe.ESC}${c}${pe.ESC}\\`),!0),s=this._bufferService.buffer,a=this._optionsService.rawOptions;return i(e==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:e==='"p'?'P1$r61;1"p':e==="r"?`P1$r${s.scrollTop+1};${s.scrollBottom+1}r`:e==="m"?"P1$r0m":e===" q"?`P1$r${{block:2,underline:4,bar:6}[a.cursorStyle]-(a.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},yp=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){ethis.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(Jb=e,e=t,t=Jb),ethis.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};yp=pi([De(0,vn)],yp);function ev(e){return 0<=e&&e<256}var wE=5e7,tv=12,CE=50,kE=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>wE)throw new Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput){this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),this._innerWrite();return}setTimeout(()=>this._innerWrite())}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){let i=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let s=this._writeBuffer[this._bufferOffset],a=this._action(s,t);if(a){let c=h=>performance.now()-i>=tv?setTimeout(()=>this._innerWrite(0,h)):this._innerWrite(i,h);a.catch(h=>(queueMicrotask(()=>{throw h}),Promise.resolve(!1))).then(c);return}let o=this._callbacks[this._bufferOffset];if(o&&o(),this._bufferOffset++,this._pendingData-=s.length,performance.now()-i>=tv)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>CE&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}},Sp=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let t=this._bufferService.buffer;if(e.id===void 0){let h=t.addMarker(t.ybase+t.y),p={data:e,id:this._nextId++,lines:[h]};return h.onDispose(()=>this._removeMarkerFromLink(p,h)),this._dataByLinkId.set(p.id,p),p.id}let i=e,s=this._getEntryIdKey(i),a=this._entriesWithId.get(s);if(a)return this.addLineToLink(a.id,t.ybase+t.y),a.id;let o=t.addMarker(t.ybase+t.y),c={id:this._nextId++,key:this._getEntryIdKey(i),data:i,lines:[o]};return o.onDispose(()=>this._removeMarkerFromLink(c,o)),this._entriesWithId.set(c.key,c),this._dataByLinkId.set(c.id,c),c.id}addLineToLink(e,t){let i=this._dataByLinkId.get(e);if(i&&i.lines.every(s=>s.line!==t)){let s=this._bufferService.buffer.addMarker(t);i.lines.push(s),s.onDispose(()=>this._removeMarkerFromLink(i,s))}}getLinkData(e){var t;return(t=this._dataByLinkId.get(e))==null?void 0:t.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let i=e.lines.indexOf(t);i!==-1&&(e.lines.splice(i,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};Sp=pi([De(0,vn)],Sp);var iv=!1,EE=class extends ut{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new fl),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 X2,this.optionsService=this._register(new aE(e)),this._instantiationService.setService(yn,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(xp)),this._instantiationService.setService(vn,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(gp)),this._instantiationService.setService(Uy,this._logService),this.coreService=this._register(this._instantiationService.createInstance(_p)),this._instantiationService.setService(va,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(bp)),this._instantiationService.setService(Hy,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(ma)),this._instantiationService.setService(GC,this.unicodeService),this._charsetService=this._instantiationService.createInstance(hE),this._instantiationService.setService(WC,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(Sp),this._instantiationService.setService($y,this._oscLinkService),this._inputHandler=this._register(new SE(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(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 kE((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 Ce),this._onScroll.event(e=>{var t;(t=this._onScrollApi)==null||t.fire(e.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let t in e)this.optionsService.options[t]=e[t]}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=3&&!iv&&(this._logService.warn("writeSync is unreliable and will be removed soon."),iv=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,v0),t=Math.max(t,y0),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t){this._bufferService.scrollLines(e,t)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&t.buildNumber!==void 0&&t.buildNumber!==void 0?e=t.backend==="conpty"&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(Yb.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},()=>(Yb(this._bufferService),!1))),this._windowsWrappingHeuristics.value=ti(()=>{for(let t of e)t.dispose()})}}},NE={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 jE(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=NE[e.keyCode])==null?void 0:c[e.shiftKey?1:0];if(h)a.key=pe.ESC+h;else if(e.keyCode>=65&&e.keyCode<=90){let p=e.ctrlKey?e.keyCode-64:e.keyCode+32,f=String.fromCharCode(p);e.shiftKey&&(f=f.toUpperCase()),a.key=pe.ESC+f}else if(e.keyCode===32)a.key=pe.ESC+(e.ctrlKey?pe.NUL:" ");else if(e.key==="Dead"&&e.code.startsWith("Key")){let p=e.code.slice(3,4);e.shiftKey||(p=p.toLowerCase()),a.key=pe.ESC+p,a.cancel=!0}}else i&&!e.altKey&&!e.ctrlKey&&!e.shiftKey&&e.metaKey?e.keyCode===65&&(a.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&e.key.length===1?a.key=e.key:e.key&&e.ctrlKey&&(e.key==="_"&&(a.key=pe.US),e.key==="@"&&(a.key=pe.NUL));break}return a}var bi=0,TE=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new Ru,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new Ru,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(e){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort((a,o)=>this._getKey(a)-this._getKey(o)),t=0,i=0,s=new Array(this._array.length+this._insertedValues.length);for(let a=0;a=this._array.length||this._getKey(e[t])<=this._getKey(this._array[i])?(s[a]=e[t],t++):s[a]=this._array[i++];this._array=s,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),this._array.length===0)return!1;let t=this._getKey(e);if(t===void 0||(bi=this._search(t),bi===-1)||this._getKey(this._array[bi])!==t)return!1;do if(this._array[bi]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(bi),!0;while(++bia-o),t=0,i=new Array(this._array.length-e.length),s=0;for(let a=0;a0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(bi=this._search(e),!(bi<0||bi>=this._array.length)&&this._getKey(this._array[bi])===e))do yield this._array[bi];while(++bi=this._array.length)&&this._getKey(this._array[bi])===e))do t(this._array[bi]);while(++bi=t;){let s=t+i>>1,a=this._getKey(this._array[s]);if(a>e)i=s-1;else if(a0&&this._getKey(this._array[s-1])===e;)s--;return s}}return t}},pf=0,nv=0,AE=class extends ut{constructor(){super(),this._decorations=new TE(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(ti(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new RE(e);if(t){let i=t.marker.onDispose(()=>t.dispose()),s=t.onDispose(()=>{s.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),i.dispose())});this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,i){let s=0,a=0;for(let o of this._decorations.getKeyIterator(t))s=o.options.x??0,a=s+(o.options.width??1),e>=s&&e{pf=a.options.x??0,nv=pf+(a.options.width??1),e>=pf&&e=this._debounceThresholdMS)this._lastRefreshMs=s,this._innerRefresh();else if(!this._additionalRefreshRequested){let a=s-this._lastRefreshMs,o=this._debounceThresholdMS-a;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},o)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}},rv=20,Du=class extends 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 ME(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(ti(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===` +`&&(this._liveRegionLineCount++,this._liveRegionLineCount===rv+1&&(this._liveRegion.textContent+=$f.get())))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let i=this._terminal.buffer,s=i.lines.length.toString();for(let a=e;a<=t;a++){let o=i.lines.get(i.ydisp+a),c=[],h=(o==null?void 0:o.translateToString(!0,void 0,void 0,c))||"",p=(i.ydisp+a+1).toString(),f=this._rowElements[a];f&&(h.length===0?(f.textContent=" ",this._rowColumns.set(f,[0,1])):(f.textContent=h,this._rowColumns.set(f,c)),f.setAttribute("aria-posinset",p),f.setAttribute("aria-setsize",s),this._alignRowWidth(f))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(e,t){let i=e.target,s=this._rowElements[t===0?1:this._rowElements.length-2],a=i.getAttribute("aria-posinset"),o=t===0?"1":`${this._terminal.buffer.lines.length}`;if(a===o||e.relatedTarget!==s)return;let c,h;if(t===0?(c=i,h=this._rowElements.pop(),this._rowContainer.removeChild(h)):(c=this._rowElements.shift(),h=i,this._rowContainer.removeChild(c)),c.removeEventListener("focus",this._topBoundaryFocusListener),h.removeEventListener("focus",this._bottomBoundaryFocusListener),t===0){let p=this._createAccessibilityTreeNode();this._rowElements.unshift(p),this._rowContainer.insertAdjacentElement("afterbegin",p)}else{let p=this._createAccessibilityTreeNode();this._rowElements.push(p),this._rowContainer.appendChild(p)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){var h;if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error("anchorNode and/or focusNode are null");return}let t={node:e.anchorNode,offset:e.anchorOffset},i={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(i.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===i.node&&t.offset>i.offset)&&([t,i]=[i,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let s=this._rowElements.slice(-1)[0];if(i.node.compareDocumentPosition(s)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(i={node:s,offset:((h=s.textContent)==null?void 0:h.length)??0}),!this._rowContainer.contains(i.node))return;let a=({node:p,offset:f})=>{let _=p instanceof Text?p.parentNode:p,x=parseInt(_==null?void 0:_.getAttribute("aria-posinset"),10)-1;if(isNaN(x))return console.warn("row is invalid. Race condition?"),null;let b=this._rowColumns.get(_);if(!b)return console.warn("columns is null. Race condition?"),null;let v=f=this._terminal.cols&&(++x,v=0),{row:x,column:v}},o=a(t),c=a(i);if(!(!o||!c)){if(o.row>c.row||o.row===c.row&&o.column>=c.column)throw new Error("invalid range");this._terminal.select(o.column,o.row,(c.row-o.row)*this._terminal.cols-o.column+c.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let t=this._rowContainer.children.length;te;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement("div");return e.setAttribute("role","listitem"),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e{var o;xa(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,(o=this._activeProviderReplies)==null||o.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(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&&BE(this._mouseDownLink.link,this._currentLink.link)&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){!this._currentLink||!this._lastMouseEvent||(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,xa(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:e.link.decorations===void 0?!0:e.link.decorations.underline,pointerCursor:e.link.decorations===void 0?!0:e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>{var i,s;return(s=(i=this._currentLink)==null?void 0:i.state)==null?void 0:s.decorations.pointerCursor},set:i=>{var s;(s=this._currentLink)!=null&&s.state&&this._currentLink.state.decorations.pointerCursor!==i&&(this._currentLink.state.decorations.pointerCursor=i,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",i))}},underline:{get:()=>{var i,s;return(s=(i=this._currentLink)==null?void 0:i.state)==null?void 0:s.decorations.underline},set:i=>{var s,a,o;(s=this._currentLink)!=null&&s.state&&((o=(a=this._currentLink)==null?void 0:a.state)==null?void 0:o.decorations.underline)!==i&&(this._currentLink.state.decorations.underline=i,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,i))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(i=>{if(!this._currentLink)return;let s=i.start===0?0:i.start+1+this._bufferService.buffer.ydisp,a=this._bufferService.buffer.ydisp+1+i.end;if(this._currentLink.link.range.start.y>=s&&this._currentLink.link.range.end.y<=a&&(this._clearCurrentLink(s,a),this._lastMouseEvent)){let o=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);o&&this._askForLink(o,!1)}})))}_linkHover(e,t,i){var s;(s=this._currentLink)!=null&&s.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add("xterm-cursor-pointer")),t.hover&&t.hover(i,t.text)}_fireUnderlineEvent(e,t){let i=e.range,s=this._bufferService.buffer.ydisp,a=this._createLinkUnderlineEvent(i.start.x-1,i.start.y-s-1,i.end.x,i.end.y-s-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(a)}_linkLeave(e,t,i){var s;(s=this._currentLink)!=null&&s.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove("xterm-cursor-pointer")),t.leave&&t.leave(i,t.text)}_linkAtPosition(e,t){let i=e.range.start.y*this._bufferService.cols+e.range.start.x,s=e.range.end.y*this._bufferService.cols+e.range.end.x,a=t.y*this._bufferService.cols+t.x;return i<=a&&a<=s}_positionFromMouseEvent(e,t,i){let s=i.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(s)return{x:s[0],y:s[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,i,s,a){return{x1:e,y1:t,x2:i,y2:s,cols:this._bufferService.cols,fg:a}}};wp=pi([De(1,Wp),De(2,os),De(3,vn),De(4,qy)],wp);function BE(e,t){return e.text===t.text&&e.range.start.x===t.range.start.x&&e.range.start.y===t.range.start.y&&e.range.end.x===t.range.end.x&&e.range.end.y===t.range.end.y}var LE=class extends EE{constructor(e={}){super(e),this._linkifier=this._register(new fl),this.browser=c0,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new fl),this._onCursorMove=this._register(new 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(AE),this._instantiationService.setService(Fo,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(C2),this._instantiationService.setService(qy,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(qf)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(t=>this.refresh((t==null?void 0:t.start)??0,(t==null?void 0:t.end)??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(t=>this._reportWindowsOptions(t))),this._register(this._inputHandler.onColor(t=>this._handleColorEvent(t))),this._register(sn.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(sn.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(sn.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(sn.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(t=>this._afterResize(t.cols,t.rows))),this._register(ti(()=>{var t,i;this._customKeyEventHandler=void 0,(i=(t=this.element)==null?void 0:t.parentNode)==null||i.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(e){if(this._themeService)for(let t of e){let i,s="";switch(t.index){case 256:i="foreground",s="10";break;case 257:i="background",s="11";break;case 258:i="cursor",s="12";break;default:i="ansi",s="4;"+t.index}switch(t.type){case 0:let a=Jt.toColorRGB(i==="ansi"?this._themeService.colors.ansi[t.index]:this._themeService.colors[i]);this.coreService.triggerDataEvent(`${pe.ESC}]${s};${vE(a)}${l0.ST}`);break;case 1:if(i==="ansi")this._themeService.modifyColors(o=>o.ansi[t.index]=Ri.toColor(...t.color));else{let o=i;this._themeService.modifyColors(c=>c[o]=Ri.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index);break}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(Du,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(pe.ESC+"[I"),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()}blur(){var e;return(e=this.textarea)==null?void 0:e.blur()}_handleTextAreaBlur(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(pe.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;let i=Math.min(this.buffer.x,this.cols-1),s=this._renderService.dimensions.css.cell.height,a=t.getWidth(i),o=this._renderService.dimensions.css.cell.width*a,c=this.buffer.y*this._renderService.dimensions.css.cell.height,h=i*this._renderService.dimensions.css.cell.width;this.textarea.style.left=h+"px",this.textarea.style.top=c+"px",this.textarea.style.width=o+"px",this.textarea.style.height=s+"px",this.textarea.style.lineHeight=s+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this._register(Xe(this.element,"copy",t=>{this.hasSelection()&&IC(t,this._selectionService)}));let e=t=>HC(t,this.textarea,this.coreService,this.optionsService);this._register(Xe(this.textarea,"paste",e)),this._register(Xe(this.element,"paste",e)),u0?this._register(Xe(this.element,"mousedown",t=>{t.button===2&&pb(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(Xe(this.element,"contextmenu",t=>{pb(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),Jp&&this._register(Xe(this.element,"auxclick",t=>{t.button===1&&Ly(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",Uf.get()),f0||this.textarea.setAttribute("aria-multiline","false"),this.textarea.setAttribute("autocorrect","off"),this.textarea.setAttribute("autocapitalize","off"),this.textarea.setAttribute("spellcheck","false"),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange("disableStdin",()=>i.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(S2,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(ls,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(hp,this._document,this._helperContainer),this._instantiationService.setService(Hu,this._charSizeService),this._themeService=this._instantiationService.createInstance(mp),this._instantiationService.setService(gl,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(Tu),this._instantiationService.setService(Fy,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(fp,this.rows,this.screenElement)),this._instantiationService.setService(os,this._renderService),this._register(this._renderService.onRenderedViewportChange(o=>this._onRender.fire(o))),this.onResize(o=>this._renderService.resize(o.cols,o.rows)),this._compositionView=this._document.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(op,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(dp),this._instantiationService.setService(Wp,this._mouseService);let s=this._linkifier.value=this._register(this._instantiationService.createInstance(wp,this.screenElement));this.element.appendChild(t);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(ap,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(o=>{super.scrollLines(o,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(pp,this.element,this.screenElement,s)),this._instantiationService.setService(VC,this._selectionService),this._register(this._selectionService.onRequestScrollLines(o=>this.scrollLines(o.amount,o.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(o=>this._renderService.handleSelectionChanged(o.start,o.end,o.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(o=>{this.textarea.value=o,this.textarea.focus(),this.textarea.select()})),this._register(sn.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{var o;this._selectionService.refresh(),(o=this._viewport)==null||o.queueSync()})),this._register(this._instantiationService.createInstance(lp,this.screenElement)),this._register(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(up,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function i(o){var f,_,x,b,v;let c=e._mouseService.getMouseReportCoords(o,e.screenElement);if(!c)return!1;let h,p;switch(o.overrideType||o.type){case"mousemove":p=32,o.buttons===void 0?(h=3,o.button!==void 0&&(h=o.button<3?o.button:3)):h=o.buttons&1?0:o.buttons&4?1:o.buttons&2?2:3;break;case"mouseup":p=0,h=o.button<3?o.button:3;break;case"mousedown":p=1,h=o.button<3?o.button:3;break;case"wheel":if(e._customWheelEventHandler&&e._customWheelEventHandler(o)===!1)return!1;let S=o.deltaY;if(S===0||e.coreMouseService.consumeWheelEvent(o,(b=(x=(_=(f=e._renderService)==null?void 0:f.dimensions)==null?void 0:_.device)==null?void 0:x.cell)==null?void 0:b.height,(v=e._coreBrowserService)==null?void 0:v.dpr)===0)return!1;p=S<0?0:1,h=4;break;default:return!1}return p===void 0||h===void 0||h>4?!1:e.coreMouseService.triggerMouseEvent({col:c.col,row:c.row,x:c.x,y:c.y,button:h,action:p,ctrl:o.ctrlKey,alt:o.altKey,shift:o.shiftKey})}let s={mouseup:null,wheel:null,mousedrag:null,mousemove:null},a={mouseup:o=>(i(o),o.buttons||(this._document.removeEventListener("mouseup",s.mouseup),s.mousedrag&&this._document.removeEventListener("mousemove",s.mousedrag)),this.cancel(o)),wheel:o=>(i(o),this.cancel(o,!0)),mousedrag:o=>{o.buttons&&i(o)},mousemove:o=>{o.buttons||i(o)}};this._register(this.coreMouseService.onProtocolChange(o=>{o?(this.optionsService.rawOptions.logLevel==="debug"&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(o)),this.element.classList.add("enable-mouse-events"),this._selectionService.disable()):(this._logService.debug("Unbinding from mouse events."),this.element.classList.remove("enable-mouse-events"),this._selectionService.enable()),o&8?s.mousemove||(t.addEventListener("mousemove",a.mousemove),s.mousemove=a.mousemove):(t.removeEventListener("mousemove",s.mousemove),s.mousemove=null),o&16?s.wheel||(t.addEventListener("wheel",a.wheel,{passive:!1}),s.wheel=a.wheel):(t.removeEventListener("wheel",s.wheel),s.wheel=null),o&2?s.mouseup||(s.mouseup=a.mouseup):(this._document.removeEventListener("mouseup",s.mouseup),s.mouseup=null),o&4?s.mousedrag||(s.mousedrag=a.mousedrag):(this._document.removeEventListener("mousemove",s.mousedrag),s.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(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=pe.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(o.deltaY<0?"A":"B");return this.coreService.triggerDataEvent(x,!0),this.cancel(o,!0)}}},{passive:!1}))}refresh(e,t){var i;(i=this._renderService)==null||i.refreshRows(e,t)}updateCursorStyle(e){var t;(t=this._selectionService)!=null&&t.shouldColumnSelect(e)?this.element.classList.add("column-select"):this.element.classList.remove("column-select")}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,t){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,t),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}paste(e){By(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");let t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return this._selectionService?this._selectionService.hasSelection:!1}select(e,t,i){this._selectionService.setSelection(e,t,i)}getSelection(){return this._selectionService?this._selectionService.selectionText:""}getSelectionPosition(){if(!(!this._selectionService||!this._selectionService.hasSelection))return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){var e;(e=this._selectionService)==null||e.clearSelection()}selectAll(){var e;(e=this._selectionService)==null||e.selectAll()}selectLines(e,t){var i;(i=this._selectionService)==null||i.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;let t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;!t&&(e.key==="Dead"||e.key==="AltGraph")&&(this._unprocessedDeadKey=!0);let i=jE(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)&&(OE(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 cr)}translateToString(e,t,i){return this._line.translateToString(e,t,i)}},sv=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){let t=this._buffer.lines.get(e);if(t)return new PE(t)}getNullCell(){return new cr}},IE=class extends ut{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new Ce),this.onBufferChange=this._onBufferChange.event,this._normal=new sv(this._core.buffers.normal,"normal"),this._alternate=new sv(this._core.buffers.alt,"alternate"),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw new Error("Active buffer is neither normal nor alternate")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}},HE=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)}},UE=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}},$E=["cols","rows"],Nr=0,FE=class extends ut{constructor(e){super(),this._core=this._register(new LE(e)),this._addonManager=this._register(new zE),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($E.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 HE(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new UE(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 IE(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t="none";switch(this._core.coreMouseService.activeProtocol){case"X10":t="x10";break;case"VT200":t="vt200";break;case"DRAG":t="drag";break;case"ANY":t="any";break}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,i){this._verifyIntegers(e,t,i),this._core.select(e,t,i)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\r +`,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return Uf.get()},set promptLabel(e){Uf.set(e)},get tooMuchOutput(){return $f.get()},set tooMuchOutput(e){$f.set(e)}}}_verifyIntegers(...e){for(Nr of e)if(Nr===1/0||isNaN(Nr)||Nr%1!==0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(Nr of e)if(Nr&&(Nr===1/0||isNaN(Nr)||Nr%1!==0||Nr<0))throw new Error("This API only accepts positive integers")}};/** * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved. * @license MIT * @@ -83,7 +83,7 @@ WARNING: This link could potentially be dangerous`)){let i=window.open();if(i){t * Fabrice Bellard's javascript vt100 for jslinux: * http://bellard.org/jslinux/ * Copyright (c) 2011 Fabrice Bellard - */var FE=2,qE=1,WE=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){var x;if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:((x=this._terminal.options.overviewRuler)==null?void 0:x.width)||14,i=window.getComputedStyle(this._terminal.element.parentElement),s=parseInt(i.getPropertyValue("height")),a=Math.max(0,parseInt(i.getPropertyValue("width"))),o=window.getComputedStyle(this._terminal.element),c={top:parseInt(o.getPropertyValue("padding-top")),bottom:parseInt(o.getPropertyValue("padding-bottom")),right:parseInt(o.getPropertyValue("padding-right")),left:parseInt(o.getPropertyValue("padding-left"))},h=c.top+c.bottom,p=c.right+c.left,f=s-h,_=a-p-t;return{cols:Math.max(FE,Math.floor(_/e.css.cell.width)),rows:Math.max(qE,Math.floor(f/e.css.cell.height))}}};/** + */var qE=2,WE=1,GE=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(qE,Math.floor(_/e.css.cell.width)),rows:Math.max(WE,Math.floor(f/e.css.cell.height))}}};/** * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved. * @license MIT * @@ -94,48 +94,48 @@ WARNING: This link could potentially be dangerous`)){let i=window.open();if(i){t * Fabrice Bellard's javascript vt100 for jslinux: * http://bellard.org/jslinux/ * Copyright (c) 2011 Fabrice Bellard - */var Gi=0,Yi=0,Vi=0,di=0,cn;(e=>{function t(a,o,c,h){return h!==void 0?`#${ua(a)}${ua(o)}${ua(c)}${ua(h)}`:`#${ua(a)}${ua(o)}${ua(c)}`}e.toCss=t;function i(a,o,c,h=255){return(a<<24|o<<16|c<<8|h)>>>0}e.toRgba=i;function s(a,o,c,h){return{css:e.toCss(a,o,c,h),rgba:e.toRgba(a,o,c,h)}}e.toColor=s})(cn||(cn={}));var GE;(e=>{function t(p,f){if(di=(f.rgba&255)/255,di===1)return{css:f.css,rgba:f.rgba};let _=f.rgba>>24&255,x=f.rgba>>16&255,b=f.rgba>>8&255,v=p.rgba>>24&255,S=p.rgba>>16&255,N=p.rgba>>8&255;Gi=v+Math.round((_-v)*di),Yi=S+Math.round((x-S)*di),Vi=N+Math.round((b-N)*di);let M=cn.toCss(Gi,Yi,Vi),E=cn.toRgba(Gi,Yi,Vi);return{css:M,rgba:E}}e.blend=t;function i(p){return(p.rgba&255)===255}e.isOpaque=i;function s(p,f,_){let x=Su.ensureContrastRatio(p.rgba,f.rgba,_);if(x)return cn.toColor(x>>24&255,x>>16&255,x>>8&255)}e.ensureContrastRatio=s;function a(p){let f=(p.rgba|255)>>>0;return[Gi,Yi,Vi]=Su.toChannels(f),{css:cn.toCss(Gi,Yi,Vi),rgba:f}}e.opaque=a;function o(p,f){return di=Math.round(f*255),[Gi,Yi,Vi]=Su.toChannels(p.rgba),{css:cn.toCss(Gi,Yi,Vi,di),rgba:cn.toRgba(Gi,Yi,Vi,di)}}e.opacity=o;function c(p,f){return di=p.rgba&255,o(p,di*f/255)}e.multiplyOpacity=c;function h(p){return[p.rgba>>24&255,p.rgba>>16&255,p.rgba>>8&255]}e.toColorRGB=h})(GE||(GE={}));var nn;(e=>{let t,i;try{let a=document.createElement("canvas");a.width=1,a.height=1;let o=a.getContext("2d",{willReadFrequently:!0});o&&(t=o,t.globalCompositeOperation="copy",i=t.createLinearGradient(0,0,1,1))}catch{}function s(a){if(a.match(/#[\da-f]{3,8}/i))switch(a.length){case 4:return Gi=parseInt(a.slice(1,2).repeat(2),16),Yi=parseInt(a.slice(2,3).repeat(2),16),Vi=parseInt(a.slice(3,4).repeat(2),16),cn.toColor(Gi,Yi,Vi);case 5:return Gi=parseInt(a.slice(1,2).repeat(2),16),Yi=parseInt(a.slice(2,3).repeat(2),16),Vi=parseInt(a.slice(3,4).repeat(2),16),di=parseInt(a.slice(4,5).repeat(2),16),cn.toColor(Gi,Yi,Vi,di);case 7:return{css:a,rgba:(parseInt(a.slice(1),16)<<8|255)>>>0};case 9:return{css:a,rgba:parseInt(a.slice(1),16)>>>0}}let o=a.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(o)return Gi=parseInt(o[1]),Yi=parseInt(o[2]),Vi=parseInt(o[3]),di=Math.round((o[5]===void 0?1:parseFloat(o[5]))*255),cn.toColor(Gi,Yi,Vi,di);if(!t||!i)throw new Error("css.toColor: Unsupported css format");if(t.fillStyle=i,t.fillStyle=a,typeof t.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(t.fillRect(0,0,1,1),[Gi,Yi,Vi,di]=t.getImageData(0,0,1,1).data,di!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:cn.toRgba(Gi,Yi,Vi,di),css:a}}e.toColor=s})(nn||(nn={}));var mn;(e=>{function t(s){return i(s>>16&255,s>>8&255,s&255)}e.relativeLuminance=t;function i(s,a,o){let c=s/255,h=a/255,p=o/255,f=c<=.03928?c/12.92:Math.pow((c+.055)/1.055,2.4),_=h<=.03928?h/12.92:Math.pow((h+.055)/1.055,2.4),x=p<=.03928?p/12.92:Math.pow((p+.055)/1.055,2.4);return f*.2126+_*.7152+x*.0722}e.relativeLuminance2=i})(mn||(mn={}));var Su;(e=>{function t(c,h){if(di=(h&255)/255,di===1)return h;let p=h>>24&255,f=h>>16&255,_=h>>8&255,x=c>>24&255,b=c>>16&255,v=c>>8&255;return Gi=x+Math.round((p-x)*di),Yi=b+Math.round((f-b)*di),Vi=v+Math.round((_-v)*di),cn.toRgba(Gi,Yi,Vi)}e.blend=t;function i(c,h,p){let f=mn.relativeLuminance(c>>8),_=mn.relativeLuminance(h>>8);if(is(f,_)>8));if(S>8));return S>M?v:N}return v}let x=a(c,h,p),b=is(f,mn.relativeLuminance(x>>8));if(b>8));return b>S?x:v}return x}}e.ensureContrastRatio=i;function s(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,N=is(mn.relativeLuminance2(b,v,S),mn.relativeLuminance2(f,_,x));for(;N0||v>0||S>0);)b-=Math.max(0,Math.ceil(b*.1)),v-=Math.max(0,Math.ceil(v*.1)),S-=Math.max(0,Math.ceil(S*.1)),N=is(mn.relativeLuminance2(b,v,S),mn.relativeLuminance2(f,_,x));return(b<<24|v<<16|S<<8|255)>>>0}e.reduceLuminance=s;function a(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,N=is(mn.relativeLuminance2(b,v,S),mn.relativeLuminance2(f,_,x));for(;N>>0}e.increaseLuminance=a;function o(c){return[c>>24&255,c>>16&255,c>>8&255,c&255]}e.toChannels=o})(Su||(Su={}));function ua(e){let t=e.toString(16);return t.length<2?"0"+t:t}function is(e,t){return e{let e=[nn.toColor("#2e3436"),nn.toColor("#cc0000"),nn.toColor("#4e9a06"),nn.toColor("#c4a000"),nn.toColor("#3465a4"),nn.toColor("#75507b"),nn.toColor("#06989a"),nn.toColor("#d3d7cf"),nn.toColor("#555753"),nn.toColor("#ef2929"),nn.toColor("#8ae234"),nn.toColor("#fce94f"),nn.toColor("#729fcf"),nn.toColor("#ad7fa8"),nn.toColor("#34e2e2"),nn.toColor("#eeeeec")],t=[0,95,135,175,215,255];for(let i=0;i<216;i++){let s=t[i/36%6|0],a=t[i/6%6|0],o=t[i%6];e.push({css:cn.toCss(s,a,o),rgba:cn.toRgba(s,a,o)})}for(let i=0;i<24;i++){let s=8+i*10;e.push({css:cn.toCss(s,s,s),rgba:cn.toRgba(s,s,s)})}return e})());function av(e,t,i){return Math.max(t,Math.min(e,i))}function VE(e){switch(e){case"&":return"&";case"<":return"<"}return e}var w0=class{constructor(e){this._buffer=e}serialize(e,t){let i=this._buffer.getNullCell(),s=this._buffer.getNullCell(),a=i,o=e.start.y,c=e.end.y,h=e.start.x,p=e.end.x;this._beforeSerialize(c-o,o,c);for(let f=o;f<=c;f++){let _=this._buffer.getLine(f);if(_){let x=f===e.start.y?h:0,b=f===e.end.y?p:_.length;for(let v=x;v0&&!ns(this._cursorStyle,this._backgroundCell)&&(this._currentRow+=`\x1B[${this._nullCellCount}X`);let i="";if(!t){e-this._firstRow>=this._terminal.rows&&((s=this._buffer.getLine(this._cursorStyleRow))==null||s.getCell(this._cursorStyleCol,this._backgroundCell));let a=this._buffer.getLine(e),o=this._buffer.getLine(e+1);if(!o.isWrapped)i=`\r -`,this._lastCursorRow=e+1,this._lastCursorCol=0;else{i="";let c=a.getCell(a.length-1,this._thisRowLastChar),h=a.getCell(a.length-2,this._thisRowLastSecondChar),p=o.getCell(0,this._nextRowFirstChar),f=p.getWidth()>1,_=!1;(p.getChars()&&f?this._nullCellCount<=1:this._nullCellCount<=0)&&((c.getChars()||c.getWidth()===0)&&ns(c,p)&&(_=!0),f&&(h.getChars()||h.getWidth()===0)&&ns(c,p)&&ns(h,p)&&(_=!0)),_||(i="-".repeat(this._nullCellCount+1),i+="\x1B[1D\x1B[1X",this._nullCellCount>0&&(i+="\x1B[A",i+=`\x1B[${a.length-this._nullCellCount}C`,i+=`\x1B[${this._nullCellCount}X`,i+=`\x1B[${a.length-this._nullCellCount}D`,i+="\x1B[B"),this._lastContentCursorRow=e+1,this._lastContentCursorCol=0,this._lastCursorRow=e+1,this._lastCursorCol=0)}}this._allRows[this._rowIndex]=this._currentRow,this._allRowSeparators[this._rowIndex++]=i,this._currentRow="",this._nullCellCount=0}_diffStyle(e,t){let i=[],s=!C0(e,t),a=!ns(e,t),o=!k0(e,t);if(s||a||o)if(e.isAttributeDefault())t.isAttributeDefault()||i.push(0);else{if(s){let c=e.getFgColor();e.isFgRGB()?i.push(38,2,c>>>16&255,c>>>8&255,c&255):e.isFgPalette()?c>=16?i.push(38,5,c):i.push(c&8?90+(c&7):30+(c&7)):i.push(39)}if(a){let c=e.getBgColor();e.isBgRGB()?i.push(48,2,c>>>16&255,c>>>8&255,c&255):e.isBgPalette()?c>=16?i.push(48,5,c):i.push(c&8?100+(c&7):40+(c&7)):i.push(49)}o&&(e.isInverse()!==t.isInverse()&&i.push(e.isInverse()?7:27),e.isBold()!==t.isBold()&&i.push(e.isBold()?1:22),e.isUnderline()!==t.isUnderline()&&i.push(e.isUnderline()?4:24),e.isOverline()!==t.isOverline()&&i.push(e.isOverline()?53:55),e.isBlink()!==t.isBlink()&&i.push(e.isBlink()?5:25),e.isInvisible()!==t.isInvisible()&&i.push(e.isInvisible()?8:28),e.isItalic()!==t.isItalic()&&i.push(e.isItalic()?3:23),e.isDim()!==t.isDim()&&i.push(e.isDim()?2:22),e.isStrikethrough()!==t.isStrikethrough()&&i.push(e.isStrikethrough()?9:29))}return i}_nextCell(e,t,i,s){if(e.getWidth()===0)return;let a=e.getChars()==="",o=this._diffStyle(e,this._cursorStyle);if(a?!ns(this._cursorStyle,e):o.length>0){this._nullCellCount>0&&(ns(this._cursorStyle,this._backgroundCell)||(this._currentRow+=`\x1B[${this._nullCellCount}X`),this._currentRow+=`\x1B[${this._nullCellCount}C`,this._nullCellCount=0),this._lastContentCursorRow=this._lastCursorRow=i,this._lastContentCursorCol=this._lastCursorCol=s,this._currentRow+=`\x1B[${o.join(";")}m`;let c=this._buffer.getLine(i);c!==void 0&&(c.getCell(s,this._cursorStyle),this._cursorStyleRow=i,this._cursorStyleCol=s)}a?this._nullCellCount+=e.getWidth():(this._nullCellCount>0&&(ns(this._cursorStyle,this._backgroundCell)?this._currentRow+=`\x1B[${this._nullCellCount}C`:(this._currentRow+=`\x1B[${this._nullCellCount}X`,this._currentRow+=`\x1B[${this._nullCellCount}C`),this._nullCellCount=0),this._currentRow+=e.getChars(),this._lastContentCursorRow=this._lastCursorRow=i,this._lastContentCursorCol=this._lastCursorCol=s+e.getWidth())}_serializeString(e){let t=this._allRows.length;this._buffer.length-this._firstRow<=this._terminal.rows&&(t=this._lastContentCursorRow+1-this._firstRow,this._lastCursorCol=this._lastContentCursorCol,this._lastCursorRow=this._lastContentCursorRow);let i="";for(let o=0;o{f>0?i+=`\x1B[${f}C`:f<0&&(i+=`\x1B[${-f}D`)};h&&((f=>{f>0?i+=`\x1B[${f}B`:f<0&&(i+=`\x1B[${-f}A`)})(o-this._lastCursorRow),p(c-this._lastCursorCol))}let s=this._terminal._core._inputHandler._curAttrData,a=this._diffStyle(s,this._cursorStyle);return a.length>0&&(i+=`\x1B[${a.join(";")}m`),i}},XE=class{activate(e){this._terminal=e}_serializeBufferByScrollback(e,t,i){let s=t.length,a=i===void 0?s:av(i+e.rows,0,s);return this._serializeBufferByRange(e,t,{start:s-a,end:s-1},!1)}_serializeBufferByRange(e,t,i,s){return new KE(t,e).serialize({start:{x:0,y:typeof i.start=="number"?i.start:i.start.line},end:{x:e.cols,y:typeof i.end=="number"?i.end:i.end.line}},s)}_serializeBufferAsHTML(e,t){var h;let i=e.buffer.active,s=new ZE(i,e,t),a=t.onlySelection??!1,o=t.range;if(o)return s.serialize({start:{x:o.startCol,y:(o.startLine,o.startLine)},end:{x:e.cols,y:(o.endLine,o.endLine)}});if(!a){let p=i.length,f=t.scrollback,_=f===void 0?p:av(f+e.rows,0,p);return s.serialize({start:{x:0,y:p-_},end:{x:e.cols,y:p-1}})}let c=(h=this._terminal)==null?void 0:h.getSelectionPosition();return c!==void 0?s.serialize({start:{x:c.start.x,y:c.start.y},end:{x:c.end.x,y:c.end.y}}):""}_serializeModes(e){let t="",i=e.modes;if(i.applicationCursorKeysMode&&(t+="\x1B[?1h"),i.applicationKeypadMode&&(t+="\x1B[?66h"),i.bracketedPasteMode&&(t+="\x1B[?2004h"),i.insertMode&&(t+="\x1B[4h"),i.originMode&&(t+="\x1B[?6h"),i.reverseWraparoundMode&&(t+="\x1B[?45h"),i.sendFocusMode&&(t+="\x1B[?1004h"),i.wraparoundMode===!1&&(t+="\x1B[?7l"),i.mouseTrackingMode!=="none")switch(i.mouseTrackingMode){case"x10":t+="\x1B[?9h";break;case"vt200":t+="\x1B[?1000h";break;case"drag":t+="\x1B[?1002h";break;case"any":t+="\x1B[?1003h";break}return t}serialize(e){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");let t=e!=null&&e.range?this._serializeBufferByRange(this._terminal,this._terminal.buffer.normal,e.range,!0):this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.normal,e==null?void 0:e.scrollback);if(!(e!=null&&e.excludeAltBuffer)&&this._terminal.buffer.active.type==="alternate"){let i=this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.alternate,void 0);t+=`\x1B[?1049h\x1B[H${i}`}return e!=null&&e.excludeModes||(t+=this._serializeModes(this._terminal)),t}serializeAsHTML(e){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");return this._serializeBufferAsHTML(this._terminal,e||{})}dispose(){}},ZE=class extends w0{constructor(e,t,i){super(e),this._terminal=t,this._options=i,this._currentRow="",this._htmlContent="",t._core._themeService?this._ansiColors=t._core._themeService.colors.ansi:this._ansiColors=YE}_padStart(e,t,i){return t=t>>0,i=i??" ",e.length>t?e:(t-=e.length,t>i.length&&(i+=i.repeat(t/i.length)),i.slice(0,t)+e)}_beforeSerialize(e,t,i){var c,h;this._htmlContent+="
";let s="#000000",a="#ffffff";(this._options.includeGlobalBackground??!1)&&(s=((c=this._terminal.options.theme)==null?void 0:c.foreground)??"#ffffff",a=((h=this._terminal.options.theme)==null?void 0:h.background)??"#000000");let o=[];o.push("color: "+s+";"),o.push("background-color: "+a+";"),o.push("font-family: "+this._terminal.options.fontFamily+";"),o.push("font-size: "+this._terminal.options.fontSize+"px;"),this._htmlContent+="
"}_afterSerialize(){this._htmlContent+="
",this._htmlContent+="
"}_rowEnd(e,t){this._htmlContent+="
"+this._currentRow+"
",this._currentRow=""}_getHexColor(e,t){let i=t?e.getFgColor():e.getBgColor();if(t?e.isFgRGB():e.isBgRGB())return"#"+[i>>16&255,i>>8&255,i&255].map(s=>this._padStart(s.toString(16),2,"0")).join("");if(t?e.isFgPalette():e.isBgPalette())return this._ansiColors[i].css}_diffStyle(e,t){let i=[],s=!C0(e,t),a=!ns(e,t),o=!k0(e,t);if(s||a||o){let c=this._getHexColor(e,!0);c&&i.push("color: "+c+";");let h=this._getHexColor(e,!1);return h&&i.push("background-color: "+h+";"),e.isInverse()&&i.push("color: #000000; background-color: #BFBFBF;"),e.isBold()&&i.push("font-weight: bold;"),e.isUnderline()&&e.isOverline()?i.push("text-decoration: overline underline;"):e.isUnderline()?i.push("text-decoration: underline;"):e.isOverline()&&i.push("text-decoration: overline;"),e.isBlink()&&i.push("text-decoration: blink;"),e.isInvisible()&&i.push("visibility: hidden;"),e.isItalic()&&i.push("font-style: italic;"),e.isDim()&&i.push("opacity: 0.5;"),e.isStrikethrough()&&i.push("text-decoration: line-through;"),i}}_nextCell(e,t,i,s){if(e.getWidth()===0)return;let a=e.getChars()==="",o=this._diffStyle(e,t);o&&(this._currentRow+=o.length===0?"":""),a?this._currentRow+=" ":this._currentRow+=VE(e.getChars())}_serializeString(){return this._htmlContent}};const QE="__OWS_FRESH_SESSION__",nl="[REDACTED]",JE=[[/(authorization\s*:\s*bearer\s+)[^\s'"\x1b]+/gi,`$1${nl}`],[/(\bbearer\s+)[A-Za-z0-9._-]{12,}/gi,`$1${nl}`],[/(\btoken=)[^\s'"&\x1b]+/gi,`$1${nl}`],[/(OWS_PASSPHRASE\s*[=:]\s*)[^\s'"\x1b]+/gi,`$1${nl}`],[/(--passphrase[=\s]+)[^\s'"\x1b]+/gi,`$1${nl}`],[/(passphrase["']?\s*[:=]\s*["']?)[^\s'"\x1b]+/gi,`$1${nl}`]];function lv(e){let t=e;for(const[i,s]of JE)t=t.replace(i,s);return t}const ov="codex features enable image_generation";function eN(e,t){return e!=="cartoon"||!t?!1:!(t.codex.installed&&t.codex.imageGeneration==="enabled")}const tN={background:"#F0EBE1",foreground:"#2C1810",cursor:"#8B4513",cursorAccent:"#F0EBE1",selectionBackground:"#D4C5B0",selectionForeground:"#2C1810",black:"#2C1810",red:"#A63D40",green:"#4A7A4A",yellow:"#8B6914",blue:"#4A6FA5",magenta:"#7B4B8A",cyan:"#3D7A7A",white:"#E6DDD0",brightBlack:"#8B7355",brightRed:"#B85C5C",brightGreen:"#5A8A5A",brightYellow:"#A07D1C",brightBlue:"#5A82BA",brightMagenta:"#8E5D9F",brightCyan:"#5A8F8F",brightWhite:"#4A3728"},iN="plotlink-terminal",nN=1,$s="scrollback",cv=10*1024*1024;function em(){return new Promise((e,t)=>{const i=indexedDB.open(iN,nN);i.onupgradeneeded=()=>{const s=i.result;s.objectStoreNames.contains($s)||s.createObjectStore($s)},i.onsuccess=()=>e(i.result),i.onerror=()=>t(i.error)})}async function rl(e,t){const i=t.length>cv?t.slice(-cv):t,s=await em();return new Promise((a,o)=>{const c=s.transaction($s,"readwrite");c.objectStore($s).put(i,e),c.oncomplete=()=>{s.close(),a()},c.onerror=()=>{s.close(),o(c.error)}})}async function rN(e){const t=await em();return new Promise((i,s)=>{const o=t.transaction($s,"readonly").objectStore($s).get(e);o.onsuccess=()=>{t.close(),i(o.result??null)},o.onerror=()=>{t.close(),s(o.error)}})}async function mf(e){const t=await em();return new Promise((i,s)=>{const a=t.transaction($s,"readwrite");a.objectStore($s).delete(e),a.oncomplete=()=>{t.close(),i()},a.onerror=()=>{t.close(),s(a.error)}})}const zi=new Map;function sN({token:e,storyName:t,authFetch:i,onSelectStory:s,onDestroySession:a,onArchiveStory:o,confirmedStories:c,renameRef:h,bypassStories:p,agentProviders:f,readiness:_,contentType:x,needsProviderRepair:b,onRepairProvider:v}){const S=w.useRef(null),N=w.useRef(i),[M,E]=w.useState([]),[L,I]=w.useState(new Set),[A,q]=w.useState(null),[R,ne]=w.useState(null),[ue,ye]=w.useState(!1),[B,re]=w.useState(!1),$=eN(x,_),G=!!b,V=w.useRef(()=>{});w.useEffect(()=>{N.current=i},[i]);const H=w.useCallback(K=>{var ge;const{width:he}=K.container.getBoundingClientRect();if(!(he<50))try{K.fit.fit(),((ge=K.ws)==null?void 0:ge.readyState)===WebSocket.OPEN&&K.ws.send(JSON.stringify({type:"resize",cols:K.term.cols,rows:K.term.rows}))}catch{}},[]),T=w.useCallback(K=>{for(const[he,ge]of zi)ge.container.style.display=he===K?"block":"none";if(K){const he=zi.get(K);he&&setTimeout(()=>H(he),50)}},[H]),z=w.useRef({});w.useEffect(()=>{z.current=p||{}},[p]);const F=w.useRef({});w.useEffect(()=>{F.current=f||{}},[f]);const xe=w.useCallback((K,he,ge)=>{const De=window.location.protocol==="https:"?"wss:":"ws:",ze=z.current[K]?"&bypass=true":"",Fe=F.current[K],we=Fe?`&provider=${encodeURIComponent(Fe)}`:"",He=new WebSocket(`${De}//${window.location.host}/ws/terminal?story=${encodeURIComponent(K)}&token=${e}&resume=${ge}${ze}${we}`);He.onopen=()=>{he.connected=!0,he._retried=!1,I(st=>{const nt=new Set(st);return nt.delete(K),nt}),He.send(JSON.stringify({type:"resize",cols:he.term.cols,rows:he.term.rows}))};let it=!0;He.onmessage=st=>{if(it&&(it=!1,typeof st.data=="string"&&st.data===QE)){he.term.reset(),mf(K).catch(()=>{});return}he.term.write(typeof st.data=="string"?lv(st.data):st.data)},He.onclose=st=>{if(he.connected=!1,he.ws===He){he.ws=null;try{const nt=he.serialize.serialize();rl(K,nt).catch(()=>{})}catch{}if(st.code===4e3&&!he._retried){he._retried=!0,he.term.write(`\r + */var Wi=0,Gi=0,Yi=0,fi=0,cn;(e=>{function t(a,o,c,h){return h!==void 0?`#${ua(a)}${ua(o)}${ua(c)}${ua(h)}`:`#${ua(a)}${ua(o)}${ua(c)}`}e.toCss=t;function i(a,o,c,h=255){return(a<<24|o<<16|c<<8|h)>>>0}e.toRgba=i;function s(a,o,c,h){return{css:e.toCss(a,o,c,h),rgba:e.toRgba(a,o,c,h)}}e.toColor=s})(cn||(cn={}));var YE;(e=>{function t(p,f){if(fi=(f.rgba&255)/255,fi===1)return{css:f.css,rgba:f.rgba};let _=f.rgba>>24&255,x=f.rgba>>16&255,b=f.rgba>>8&255,v=p.rgba>>24&255,S=p.rgba>>16&255,N=p.rgba>>8&255;Wi=v+Math.round((_-v)*fi),Gi=S+Math.round((x-S)*fi),Yi=N+Math.round((b-N)*fi);let B=cn.toCss(Wi,Gi,Yi),E=cn.toRgba(Wi,Gi,Yi);return{css:B,rgba:E}}e.blend=t;function i(p){return(p.rgba&255)===255}e.isOpaque=i;function s(p,f,_){let x=Su.ensureContrastRatio(p.rgba,f.rgba,_);if(x)return cn.toColor(x>>24&255,x>>16&255,x>>8&255)}e.ensureContrastRatio=s;function a(p){let f=(p.rgba|255)>>>0;return[Wi,Gi,Yi]=Su.toChannels(f),{css:cn.toCss(Wi,Gi,Yi),rgba:f}}e.opaque=a;function o(p,f){return fi=Math.round(f*255),[Wi,Gi,Yi]=Su.toChannels(p.rgba),{css:cn.toCss(Wi,Gi,Yi,fi),rgba:cn.toRgba(Wi,Gi,Yi,fi)}}e.opacity=o;function c(p,f){return fi=p.rgba&255,o(p,fi*f/255)}e.multiplyOpacity=c;function h(p){return[p.rgba>>24&255,p.rgba>>16&255,p.rgba>>8&255]}e.toColorRGB=h})(YE||(YE={}));var nn;(e=>{let t,i;try{let a=document.createElement("canvas");a.width=1,a.height=1;let o=a.getContext("2d",{willReadFrequently:!0});o&&(t=o,t.globalCompositeOperation="copy",i=t.createLinearGradient(0,0,1,1))}catch{}function s(a){if(a.match(/#[\da-f]{3,8}/i))switch(a.length){case 4:return Wi=parseInt(a.slice(1,2).repeat(2),16),Gi=parseInt(a.slice(2,3).repeat(2),16),Yi=parseInt(a.slice(3,4).repeat(2),16),cn.toColor(Wi,Gi,Yi);case 5:return Wi=parseInt(a.slice(1,2).repeat(2),16),Gi=parseInt(a.slice(2,3).repeat(2),16),Yi=parseInt(a.slice(3,4).repeat(2),16),fi=parseInt(a.slice(4,5).repeat(2),16),cn.toColor(Wi,Gi,Yi,fi);case 7:return{css:a,rgba:(parseInt(a.slice(1),16)<<8|255)>>>0};case 9:return{css:a,rgba:parseInt(a.slice(1),16)>>>0}}let o=a.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(o)return Wi=parseInt(o[1]),Gi=parseInt(o[2]),Yi=parseInt(o[3]),fi=Math.round((o[5]===void 0?1:parseFloat(o[5]))*255),cn.toColor(Wi,Gi,Yi,fi);if(!t||!i)throw new Error("css.toColor: Unsupported css format");if(t.fillStyle=i,t.fillStyle=a,typeof t.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(t.fillRect(0,0,1,1),[Wi,Gi,Yi,fi]=t.getImageData(0,0,1,1).data,fi!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:cn.toRgba(Wi,Gi,Yi,fi),css:a}}e.toColor=s})(nn||(nn={}));var xn;(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})(xn||(xn={}));var Su;(e=>{function t(c,h){if(fi=(h&255)/255,fi===1)return h;let p=h>>24&255,f=h>>16&255,_=h>>8&255,x=c>>24&255,b=c>>16&255,v=c>>8&255;return Wi=x+Math.round((p-x)*fi),Gi=b+Math.round((f-b)*fi),Yi=v+Math.round((_-v)*fi),cn.toRgba(Wi,Gi,Yi)}e.blend=t;function i(c,h,p){let f=xn.relativeLuminance(c>>8),_=xn.relativeLuminance(h>>8);if(ns(f,_)>8));if(S>8));return S>B?v:N}return v}let x=a(c,h,p),b=ns(f,xn.relativeLuminance(x>>8));if(b>8));return b>S?x:v}return x}}e.ensureContrastRatio=i;function s(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,N=ns(xn.relativeLuminance2(b,v,S),xn.relativeLuminance2(f,_,x));for(;N0||v>0||S>0);)b-=Math.max(0,Math.ceil(b*.1)),v-=Math.max(0,Math.ceil(v*.1)),S-=Math.max(0,Math.ceil(S*.1)),N=ns(xn.relativeLuminance2(b,v,S),xn.relativeLuminance2(f,_,x));return(b<<24|v<<16|S<<8|255)>>>0}e.reduceLuminance=s;function a(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,N=ns(xn.relativeLuminance2(b,v,S),xn.relativeLuminance2(f,_,x));for(;N>>0}e.increaseLuminance=a;function o(c){return[c>>24&255,c>>16&255,c>>8&255,c&255]}e.toChannels=o})(Su||(Su={}));function ua(e){let t=e.toString(16);return t.length<2?"0"+t:t}function ns(e,t){return e{let e=[nn.toColor("#2e3436"),nn.toColor("#cc0000"),nn.toColor("#4e9a06"),nn.toColor("#c4a000"),nn.toColor("#3465a4"),nn.toColor("#75507b"),nn.toColor("#06989a"),nn.toColor("#d3d7cf"),nn.toColor("#555753"),nn.toColor("#ef2929"),nn.toColor("#8ae234"),nn.toColor("#fce94f"),nn.toColor("#729fcf"),nn.toColor("#ad7fa8"),nn.toColor("#34e2e2"),nn.toColor("#eeeeec")],t=[0,95,135,175,215,255];for(let i=0;i<216;i++){let s=t[i/36%6|0],a=t[i/6%6|0],o=t[i%6];e.push({css:cn.toCss(s,a,o),rgba:cn.toRgba(s,a,o)})}for(let i=0;i<24;i++){let s=8+i*10;e.push({css:cn.toCss(s,s,s),rgba:cn.toRgba(s,s,s)})}return e})());function av(e,t,i){return Math.max(t,Math.min(e,i))}function KE(e){switch(e){case"&":return"&";case"<":return"<"}return e}var w0=class{constructor(e){this._buffer=e}serialize(e,t){let i=this._buffer.getNullCell(),s=this._buffer.getNullCell(),a=i,o=e.start.y,c=e.end.y,h=e.start.x,p=e.end.x;this._beforeSerialize(c-o,o,c);for(let f=o;f<=c;f++){let _=this._buffer.getLine(f);if(_){let x=f===e.start.y?h:0,b=f===e.end.y?p:_.length;for(let v=x;v0&&!rs(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)&&rs(c,p)&&(_=!0),f&&(h.getChars()||h.getWidth()===0)&&rs(c,p)&&rs(h,p)&&(_=!0)),_||(i="-".repeat(this._nullCellCount+1),i+="\x1B[1D\x1B[1X",this._nullCellCount>0&&(i+="\x1B[A",i+=`\x1B[${a.length-this._nullCellCount}C`,i+=`\x1B[${this._nullCellCount}X`,i+=`\x1B[${a.length-this._nullCellCount}D`,i+="\x1B[B"),this._lastContentCursorRow=e+1,this._lastContentCursorCol=0,this._lastCursorRow=e+1,this._lastCursorCol=0)}}this._allRows[this._rowIndex]=this._currentRow,this._allRowSeparators[this._rowIndex++]=i,this._currentRow="",this._nullCellCount=0}_diffStyle(e,t){let i=[],s=!C0(e,t),a=!rs(e,t),o=!k0(e,t);if(s||a||o)if(e.isAttributeDefault())t.isAttributeDefault()||i.push(0);else{if(s){let c=e.getFgColor();e.isFgRGB()?i.push(38,2,c>>>16&255,c>>>8&255,c&255):e.isFgPalette()?c>=16?i.push(38,5,c):i.push(c&8?90+(c&7):30+(c&7)):i.push(39)}if(a){let c=e.getBgColor();e.isBgRGB()?i.push(48,2,c>>>16&255,c>>>8&255,c&255):e.isBgPalette()?c>=16?i.push(48,5,c):i.push(c&8?100+(c&7):40+(c&7)):i.push(49)}o&&(e.isInverse()!==t.isInverse()&&i.push(e.isInverse()?7:27),e.isBold()!==t.isBold()&&i.push(e.isBold()?1:22),e.isUnderline()!==t.isUnderline()&&i.push(e.isUnderline()?4:24),e.isOverline()!==t.isOverline()&&i.push(e.isOverline()?53:55),e.isBlink()!==t.isBlink()&&i.push(e.isBlink()?5:25),e.isInvisible()!==t.isInvisible()&&i.push(e.isInvisible()?8:28),e.isItalic()!==t.isItalic()&&i.push(e.isItalic()?3:23),e.isDim()!==t.isDim()&&i.push(e.isDim()?2:22),e.isStrikethrough()!==t.isStrikethrough()&&i.push(e.isStrikethrough()?9:29))}return i}_nextCell(e,t,i,s){if(e.getWidth()===0)return;let a=e.getChars()==="",o=this._diffStyle(e,this._cursorStyle);if(a?!rs(this._cursorStyle,e):o.length>0){this._nullCellCount>0&&(rs(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&&(rs(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}},ZE=class{activate(e){this._terminal=e}_serializeBufferByScrollback(e,t,i){let s=t.length,a=i===void 0?s:av(i+e.rows,0,s);return this._serializeBufferByRange(e,t,{start:s-a,end:s-1},!1)}_serializeBufferByRange(e,t,i,s){return new XE(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 QE(i,e,t),a=t.onlySelection??!1,o=t.range;if(o)return s.serialize({start:{x:o.startCol,y:(o.startLine,o.startLine)},end:{x:e.cols,y:(o.endLine,o.endLine)}});if(!a){let p=i.length,f=t.scrollback,_=f===void 0?p:av(f+e.rows,0,p);return s.serialize({start:{x:0,y:p-_},end:{x:e.cols,y:p-1}})}let c=(h=this._terminal)==null?void 0:h.getSelectionPosition();return c!==void 0?s.serialize({start:{x:c.start.x,y:c.start.y},end:{x:c.end.x,y:c.end.y}}):""}_serializeModes(e){let t="",i=e.modes;if(i.applicationCursorKeysMode&&(t+="\x1B[?1h"),i.applicationKeypadMode&&(t+="\x1B[?66h"),i.bracketedPasteMode&&(t+="\x1B[?2004h"),i.insertMode&&(t+="\x1B[4h"),i.originMode&&(t+="\x1B[?6h"),i.reverseWraparoundMode&&(t+="\x1B[?45h"),i.sendFocusMode&&(t+="\x1B[?1004h"),i.wraparoundMode===!1&&(t+="\x1B[?7l"),i.mouseTrackingMode!=="none")switch(i.mouseTrackingMode){case"x10":t+="\x1B[?9h";break;case"vt200":t+="\x1B[?1000h";break;case"drag":t+="\x1B[?1002h";break;case"any":t+="\x1B[?1003h";break}return t}serialize(e){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");let t=e!=null&&e.range?this._serializeBufferByRange(this._terminal,this._terminal.buffer.normal,e.range,!0):this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.normal,e==null?void 0:e.scrollback);if(!(e!=null&&e.excludeAltBuffer)&&this._terminal.buffer.active.type==="alternate"){let i=this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.alternate,void 0);t+=`\x1B[?1049h\x1B[H${i}`}return e!=null&&e.excludeModes||(t+=this._serializeModes(this._terminal)),t}serializeAsHTML(e){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");return this._serializeBufferAsHTML(this._terminal,e||{})}dispose(){}},QE=class extends w0{constructor(e,t,i){super(e),this._terminal=t,this._options=i,this._currentRow="",this._htmlContent="",t._core._themeService?this._ansiColors=t._core._themeService.colors.ansi:this._ansiColors=VE}_padStart(e,t,i){return t=t>>0,i=i??" ",e.length>t?e:(t-=e.length,t>i.length&&(i+=i.repeat(t/i.length)),i.slice(0,t)+e)}_beforeSerialize(e,t,i){var c,h;this._htmlContent+="
";let s="#000000",a="#ffffff";(this._options.includeGlobalBackground??!1)&&(s=((c=this._terminal.options.theme)==null?void 0:c.foreground)??"#ffffff",a=((h=this._terminal.options.theme)==null?void 0:h.background)??"#000000");let o=[];o.push("color: "+s+";"),o.push("background-color: "+a+";"),o.push("font-family: "+this._terminal.options.fontFamily+";"),o.push("font-size: "+this._terminal.options.fontSize+"px;"),this._htmlContent+="
"}_afterSerialize(){this._htmlContent+="
",this._htmlContent+="
"}_rowEnd(e,t){this._htmlContent+="
"+this._currentRow+"
",this._currentRow=""}_getHexColor(e,t){let i=t?e.getFgColor():e.getBgColor();if(t?e.isFgRGB():e.isBgRGB())return"#"+[i>>16&255,i>>8&255,i&255].map(s=>this._padStart(s.toString(16),2,"0")).join("");if(t?e.isFgPalette():e.isBgPalette())return this._ansiColors[i].css}_diffStyle(e,t){let i=[],s=!C0(e,t),a=!rs(e,t),o=!k0(e,t);if(s||a||o){let c=this._getHexColor(e,!0);c&&i.push("color: "+c+";");let h=this._getHexColor(e,!1);return h&&i.push("background-color: "+h+";"),e.isInverse()&&i.push("color: #000000; background-color: #BFBFBF;"),e.isBold()&&i.push("font-weight: bold;"),e.isUnderline()&&e.isOverline()?i.push("text-decoration: overline underline;"):e.isUnderline()?i.push("text-decoration: underline;"):e.isOverline()&&i.push("text-decoration: overline;"),e.isBlink()&&i.push("text-decoration: blink;"),e.isInvisible()&&i.push("visibility: hidden;"),e.isItalic()&&i.push("font-style: italic;"),e.isDim()&&i.push("opacity: 0.5;"),e.isStrikethrough()&&i.push("text-decoration: line-through;"),i}}_nextCell(e,t,i,s){if(e.getWidth()===0)return;let a=e.getChars()==="",o=this._diffStyle(e,t);o&&(this._currentRow+=o.length===0?"
":""),a?this._currentRow+=" ":this._currentRow+=KE(e.getChars())}_serializeString(){return this._htmlContent}};const JE="__OWS_FRESH_SESSION__",nl="[REDACTED]",eN=[[/(authorization\s*:\s*bearer\s+)[^\s'"\x1b]+/gi,`$1${nl}`],[/(\bbearer\s+)[A-Za-z0-9._-]{12,}/gi,`$1${nl}`],[/(\btoken=)[^\s'"&\x1b]+/gi,`$1${nl}`],[/(OWS_PASSPHRASE\s*[=:]\s*)[^\s'"\x1b]+/gi,`$1${nl}`],[/(--passphrase[=\s]+)[^\s'"\x1b]+/gi,`$1${nl}`],[/(passphrase["']?\s*[:=]\s*["']?)[^\s'"\x1b]+/gi,`$1${nl}`]];function lv(e){let t=e;for(const[i,s]of eN)t=t.replace(i,s);return t}const ov="codex features enable image_generation";function tN(e,t){return e!=="cartoon"||!t?!1:!(t.codex.installed&&t.codex.imageGeneration==="enabled")}const iN={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"},nN="plotlink-terminal",rN=1,Fs="scrollback",cv=10*1024*1024;function em(){return new Promise((e,t)=>{const i=indexedDB.open(nN,rN);i.onupgradeneeded=()=>{const s=i.result;s.objectStoreNames.contains(Fs)||s.createObjectStore(Fs)},i.onsuccess=()=>e(i.result),i.onerror=()=>t(i.error)})}async function rl(e,t){const i=t.length>cv?t.slice(-cv):t,s=await em();return new Promise((a,o)=>{const c=s.transaction(Fs,"readwrite");c.objectStore(Fs).put(i,e),c.oncomplete=()=>{s.close(),a()},c.onerror=()=>{s.close(),o(c.error)}})}async function sN(e){const t=await em();return new Promise((i,s)=>{const o=t.transaction(Fs,"readonly").objectStore(Fs).get(e);o.onsuccess=()=>{t.close(),i(o.result??null)},o.onerror=()=>{t.close(),s(o.error)}})}async function mf(e){const t=await em();return new Promise((i,s)=>{const a=t.transaction(Fs,"readwrite");a.objectStore(Fs).delete(e),a.oncomplete=()=>{t.close(),i()},a.onerror=()=>{t.close(),s(a.error)}})}const zi=new Map;function aN({token:e,storyName:t,authFetch:i,onSelectStory:s,onDestroySession:a,onArchiveStory:o,confirmedStories:c,renameRef:h,bypassStories:p,agentProviders:f,readiness:_,contentType:x,needsProviderRepair:b,onRepairProvider:v}){const S=w.useRef(null),N=w.useRef(i),[B,E]=w.useState([]),[O,H]=w.useState(new Set),[A,W]=w.useState(null),[D,ne]=w.useState(null),[ue,be]=w.useState(!1),[L,re]=w.useState(!1),F=tN(x,_),Y=!!b,V=w.useRef(()=>{});w.useEffect(()=>{N.current=i},[i]);const U=w.useCallback(X=>{var ge;const{width:he}=X.container.getBoundingClientRect();if(!(he<50))try{X.fit.fit(),((ge=X.ws)==null?void 0:ge.readyState)===WebSocket.OPEN&&X.ws.send(JSON.stringify({type:"resize",cols:X.term.cols,rows:X.term.rows}))}catch{}},[]),T=w.useCallback(X=>{for(const[he,ge]of zi)ge.container.style.display=he===X?"block":"none";if(X){const he=zi.get(X);he&&setTimeout(()=>U(he),50)}},[U]),P=w.useRef({});w.useEffect(()=>{P.current=p||{}},[p]);const q=w.useRef({});w.useEffect(()=>{q.current=f||{}},[f]);const xe=w.useCallback((X,he,ge)=>{const Re=window.location.protocol==="https:"?"wss:":"ws:",Le=P.current[X]?"&bypass=true":"",Fe=q.current[X],ye=Fe?`&provider=${encodeURIComponent(Fe)}`:"",st=new WebSocket(`${Re}//${window.location.host}/ws/terminal?story=${encodeURIComponent(X)}&token=${e}&resume=${ge}${Le}${ye}`);st.onopen=()=>{he.connected=!0,he._retried=!1,H(Ue=>{const qe=new Set(Ue);return qe.delete(X),qe}),st.send(JSON.stringify({type:"resize",cols:he.term.cols,rows:he.term.rows}))};let yt=!0;st.onmessage=Ue=>{if(yt&&(yt=!1,typeof Ue.data=="string"&&Ue.data===JE)){he.term.reset(),mf(X).catch(()=>{});return}he.term.write(typeof Ue.data=="string"?lv(Ue.data):Ue.data)},st.onclose=Ue=>{if(he.connected=!1,he.ws===st){he.ws=null;try{const qe=he.serialize.serialize();rl(X,qe).catch(()=>{})}catch{}if(Ue.code===4e3&&!he._retried){he._retried=!0,he.term.write(`\r \x1B[33m[Resume failed — starting fresh session...]\x1B[0m\r -`),V.current(K,he,!1);return}I(nt=>new Set(nt).add(K))}},he.term.onData(st=>{He.readyState===WebSocket.OPEN&&He.send(st)}),he.ws=He},[e]);w.useEffect(()=>{V.current=xe},[xe]);const j=w.useCallback(async(K,he)=>{if(!S.current||zi.has(K))return;const{resume:ge=!1,autoConnect:De=!0}=he??{},ze=document.createElement("div");ze.style.width="100%",ze.style.height="100%",ze.style.display="none",ze.style.paddingLeft="10px",ze.style.boxSizing="border-box",S.current.appendChild(ze);const Fe=new $E({cols:80,scrollback:5e3,fontSize:13,fontFamily:'"Geist Mono", ui-monospace, monospace',lineHeight:1.05,letterSpacing:0,cursorBlink:!0,cursorStyle:"block",theme:tN,allowTransparency:!1,drawBoldTextInBrightColors:!1,minimumContrastRatio:7}),we=new WE,He=new XE;Fe.loadAddon(we),Fe.loadAddon(He),Fe.open(ze);const it={term:Fe,fit:we,serialize:He,ws:null,container:ze,observer:null,connected:!1},st=new ResizeObserver(()=>{var Nt;const{width:nt}=ze.getBoundingClientRect();if(!(nt<50))try{we.fit(),((Nt=it.ws)==null?void 0:Nt.readyState)===WebSocket.OPEN&&it.ws.send(JSON.stringify({type:"resize",cols:Fe.cols,rows:Fe.rows}))}catch{}});st.observe(ze),it.observer=st,zi.set(K,it),E(nt=>[...nt,K]);try{const nt=await rN(K);if(nt){const Nt=lv(nt);Fe.write(Nt),Nt!==nt&&rl(K,Nt).catch(()=>{})}}catch{}De?xe(K,it,ge):I(nt=>new Set(nt).add(K)),setTimeout(()=>H(it),50)},[xe,H]),D=w.useCallback(async(K,he)=>{const ge=zi.get(K);ge&&(ge.ws&&(ge.ws.close(),ge.ws=null),he||(await N.current(`/api/terminal/${encodeURIComponent(K)}`,{method:"DELETE"}).catch(()=>{}),ge.term.clear()),xe(K,ge,he))},[xe]),X=w.useCallback(K=>{const he=zi.get(K);if(he){try{const ge=he.serialize.serialize();rl(K,ge).catch(()=>{})}catch{}he.observer.disconnect(),he.ws&&he.ws.close(),he.term.dispose(),he.container.remove(),zi.delete(K),E(ge=>ge.filter(De=>De!==K)),I(ge=>{const De=new Set(ge);return De.delete(K),De}),i(`/api/terminal/${encodeURIComponent(K)}`,{method:"DELETE"}).catch(()=>{}),a==null||a(K)}},[i,a]),C=w.useCallback(K=>{var ge;const he=zi.get(K);he&&(((ge=he.ws)==null?void 0:ge.readyState)===WebSocket.OPEN&&he.ws.send(`exit -`),mf(K).catch(()=>{}),he.observer.disconnect(),he.ws&&he.ws.close(),he.term.dispose(),he.container.remove(),zi.delete(K),E(De=>De.filter(ze=>ze!==K)),I(De=>{const ze=new Set(De);return ze.delete(K),ze}),i(`/api/terminal/${encodeURIComponent(K)}/discard`,{method:"DELETE"}).catch(()=>{}),a==null||a(K))},[i,a]),Z=w.useCallback(async(K,he,ge)=>{const De=zi.get(K);if(!De||zi.has(he)||!(await N.current("/api/terminal/rename",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldName:K,newName:he,...ge??{}})})).ok)return!1;zi.delete(K),zi.set(he,De);try{const Fe=De.serialize.serialize();await mf(K),await rl(he,Fe)}catch{}return E(Fe=>Fe.map(we=>we===K?he:we)),I(Fe=>{if(!Fe.has(K))return Fe;const we=new Set(Fe);return we.delete(K),we.add(he),we}),(De.connected||De.ws)&&(await N.current(`/api/terminal/${encodeURIComponent(he)}`,{method:"DELETE"}).catch(()=>{}),De.ws&&(De.ws.close(),De.ws=null),V.current(he,De,!0)),!0},[]);w.useEffect(()=>(h&&(h.current=Z),()=>{h&&(h.current=null)}),[h,Z]),w.useEffect(()=>{if(t){if($){T(null);return}if(G){T(null);return}zi.has(t)?T(t):N.current(`/api/terminal/session/${encodeURIComponent(t)}`).then(K=>K.ok?K.json():null).then(K=>{if(!zi.has(t)){const he=(K==null?void 0:K.sessionId)&&!(K!=null&&K.running);j(t,{autoConnect:!he}),T(t)}}).catch(()=>{zi.has(t)||(j(t),T(t))})}},[t,j,T,$,G]),w.useEffect(()=>{const K=setInterval(()=>{for(const[he,ge]of zi)if(ge.connected)try{const De=ge.serialize.serialize();rl(he,De).catch(()=>{})}catch{}},3e4);return()=>clearInterval(K)},[]),w.useEffect(()=>()=>{for(const[K,he]of zi){try{const ge=he.serialize.serialize();rl(K,ge).catch(()=>{})}catch{}he.observer.disconnect(),he.ws&&he.ws.close(),he.term.dispose(),he.container.remove(),N.current(`/api/terminal/${encodeURIComponent(K)}`,{method:"DELETE"}).catch(()=>{})}zi.clear()},[]);const ae=t?L.has(t):!1,oe=M.length===0;return d.jsxs("div",{className:"h-full flex flex-col",children:[!oe&&d.jsxs("div",{className:"px-2 py-1 border-b border-border flex items-center gap-1 overflow-x-auto",children:[M.map(K=>d.jsxs("div",{onClick:()=>s==null?void 0:s(K),className:`flex items-center gap-1 px-2 py-0.5 rounded text-xs font-mono cursor-pointer ${K===t?"bg-accent/10 text-accent":"text-muted hover:text-foreground"}`,children:[d.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${L.has(K)?"bg-amber-500":K===t?"bg-green-600":"bg-muted/50"}`}),d.jsx("span",{className:`truncate max-w-[120px] ${K.startsWith("_new_")?"italic":""}`,children:K.startsWith("_new_")?"Untitled":K}),d.jsx("button",{onClick:he=>{he.stopPropagation(),K.startsWith("_new_")?q(K):X(K)},className:"ml-0.5 text-muted hover:text-error text-[10px] leading-none",title:"Close terminal",children:"×"})]},K)),t!=null&&t.startsWith("_new_")?d.jsx("button",{onClick:()=>q(t),className:"ml-auto px-2 py-0.5 text-xs text-error hover:bg-surface rounded flex items-center gap-1 flex-shrink-0",children:"Cancel ×"}):t&&o&&(c!=null&&c.has(t))?d.jsx("button",{onClick:()=>ne(t),className:"ml-auto px-2 py-0.5 text-xs text-muted hover:text-foreground hover:bg-surface rounded flex items-center gap-1 flex-shrink-0",children:"Archive"}):null]}),d.jsxs("div",{className:"relative flex-1 min-h-0",children:[d.jsx("div",{ref:S,className:"h-full"}),oe&&!$&&!G&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center text-muted",children:d.jsxs("div",{className:"text-center",children:[d.jsx("p",{className:"text-lg font-serif",children:"Select a story on the left menu"}),d.jsx("p",{className:"text-sm mt-1",children:"to start an AI Writer session"})]})}),$&&d.jsx("div",{"data-testid":"cartoon-launch-blocked",className:"absolute inset-0 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-md",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Cartoon agent can't launch yet"}),d.jsx("p",{className:"text-xs text-muted",children:"This is a cartoon story. The writing agent needs Codex with image generation enabled before it can start, because the clean-image step relies on image generation support."}),_&&!_.codex.installed?d.jsxs("p",{className:"text-xs text-amber-700",children:["Codex was not detected. Install the Codex CLI and sign in (e.g. ",d.jsx("span",{className:"font-mono",children:"npm i -g @openai/codex"})," then"," ",d.jsx("span",{className:"font-mono",children:"codex login"}),"), then reopen this story."]}):Eu(_)?d.jsxs("p",{className:"text-xs text-amber-700","data-testid":"codex-auth-unknown-launch",children:[Fp," Then reopen this story."]}):d.jsxs("div",{className:"space-y-1",children:[d.jsx("p",{className:"text-xs text-amber-700",children:"Codex is installed but image generation isn't enabled. Enable it, then reopen this story:"}),d.jsxs("div",{className:"flex items-center gap-1",children:[d.jsx("code",{className:"flex-1 truncate rounded border border-border bg-surface px-1.5 py-1 text-left text-[10px] font-mono text-foreground",children:ov}),d.jsx("button",{type:"button","data-testid":"copy-codex-enable-launch",onClick:async()=>{try{await navigator.clipboard.writeText(ov),ye(!0),setTimeout(()=>ye(!1),2e3)}catch{}},className:"rounded border border-border px-2 py-1 text-[10px] text-muted hover:border-accent hover:text-accent transition-colors",children:ue?"Copied!":"Copy"})]})]})]})}),G&&!$&&d.jsx("div",{"data-testid":"legacy-cartoon-provider-repair",className:"absolute inset-0 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-md",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Set this cartoon story's provider"}),d.jsx("p",{className:"text-xs text-muted",children:"This cartoon story was created before provider tracking, so it has no provider recorded and would launch with Claude — which can't generate the clean images cartoons need. Set this story's provider to Codex to continue."}),d.jsx("p",{className:"text-[11px] text-muted",children:"Only this story is changed. Other stories and fiction are not affected."}),d.jsx("button",{type:"button","data-testid":"repair-provider-codex",disabled:B,onClick:async()=>{if(!B){re(!0);try{await(v==null?void 0:v())}finally{re(!1)}}},className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim disabled:opacity-50 disabled:cursor-not-allowed",children:B?"Setting…":"Set this story's provider to Codex"})]})}),A&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-10",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"text-center space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-sm",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Discard this session?"}),d.jsx("p",{className:"text-xs text-muted",children:"This session will be lost — your AI hasn't created a story structure yet."}),d.jsxs("div",{className:"flex items-center justify-center gap-2",children:[d.jsx("button",{onClick:()=>q(null),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Cancel"}),d.jsx("button",{onClick:()=>{const K=A;q(null),C(K)},className:"px-4 py-1.5 bg-error text-white text-sm rounded hover:opacity-80",children:"Discard"})]})]})}),R&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-10",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"text-center space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-sm",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Archive this story?"}),d.jsx("p",{className:"text-xs text-muted",children:"You can restore it later from the Archives view."}),d.jsxs("div",{className:"flex items-center justify-center gap-2",children:[d.jsx("button",{onClick:()=>ne(null),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Cancel"}),d.jsx("button",{onClick:async()=>{const K=R;ne(null);try{(await N.current("/api/stories/archive",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:K})})).ok&&(X(K),o==null||o(K))}catch{}},className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim",children:"Archive"})]})]})}),ae&&t&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"text-center space-y-3",children:[d.jsx("p",{className:"text-sm font-serif text-foreground",children:"Terminal disconnected"}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{onClick:()=>D(t,!0),className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim",children:"Resume Session"}),d.jsx("button",{onClick:()=>D(t,!1),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Start Fresh"})]}),d.jsx("p",{className:"text-xs text-muted",children:"Resume continues your previous Claude conversation"})]})})]})]})}function aN(e,t){const i={};return(e[e.length-1]===""?[...e,""]:e).join((i.padRight?" ":"")+","+(i.padLeft===!1?"":" ")).trim()}const lN=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,oN=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,cN={};function uv(e,t){return(cN.jsx?oN:lN).test(e)}const uN=/[ \t\n\f\r]/g;function hN(e){return typeof e=="object"?e.type==="text"?hv(e.value):!1:hv(e)}function hv(e){return e.replace(uN,"")===""}class Go{constructor(t,i,s){this.normal=i,this.property=t,s&&(this.space=s)}}Go.prototype.normal={};Go.prototype.property={};Go.prototype.space=void 0;function E0(e,t){const i={},s={};for(const a of e)Object.assign(i,a.property),Object.assign(s,a.normal);return new Go(i,s,t)}function Cp(e){return e.toLowerCase()}class Dn{constructor(t,i){this.attribute=i,this.property=t}}Dn.prototype.attribute="";Dn.prototype.booleanish=!1;Dn.prototype.boolean=!1;Dn.prototype.commaOrSpaceSeparated=!1;Dn.prototype.commaSeparated=!1;Dn.prototype.defined=!1;Dn.prototype.mustUseProperty=!1;Dn.prototype.number=!1;Dn.prototype.overloadedBoolean=!1;Dn.prototype.property="";Dn.prototype.spaceSeparated=!1;Dn.prototype.space=void 0;let dN=0;const lt=ya(),ji=ya(),kp=ya(),Se=ya(),Xt=ya(),ul=ya(),Gn=ya();function ya(){return 2**++dN}const Ep=Object.freeze(Object.defineProperty({__proto__:null,boolean:lt,booleanish:ji,commaOrSpaceSeparated:Gn,commaSeparated:ul,number:Se,overloadedBoolean:kp,spaceSeparated:Xt},Symbol.toStringTag,{value:"Module"})),gf=Object.keys(Ep);class tm extends Dn{constructor(t,i,s,a){let o=-1;if(super(t,i),dv(this,"space",a),typeof s=="number")for(;++o4&&i.slice(0,4)==="data"&&xN.test(t)){if(t.charAt(4)==="-"){const o=t.slice(5).replace(fv,vN);s="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=t.slice(4);if(!fv.test(o)){let c=o.replace(gN,bN);c.charAt(0)!=="-"&&(c="-"+c),t="data"+c}}a=tm}return new a(s,t)}function bN(e){return"-"+e.toLowerCase()}function vN(e){return e.charAt(1).toUpperCase()}const yN=E0([N0,fN,A0,R0,D0],"html"),im=E0([N0,pN,A0,R0,D0],"svg");function SN(e){return e.join(" ").trim()}var sl={},xf,pv;function wN(){if(pv)return xf;pv=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,i=/^\s*/,s=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,a=/^:\s*/,o=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,c=/^[;\s]*/,h=/^\s+|\s+$/g,p=` -`,f="/",_="*",x="",b="comment",v="declaration";function S(M,E){if(typeof M!="string")throw new TypeError("First argument must be a string");if(!M)return[];E=E||{};var L=1,I=1;function A(V){var H=V.match(t);H&&(L+=H.length);var T=V.lastIndexOf(p);I=~T?V.length-T:I+V.length}function q(){var V={line:L,column:I};return function(H){return H.position=new R(V),ye(),H}}function R(V){this.start=V,this.end={line:L,column:I},this.source=E.source}R.prototype.content=M;function ne(V){var H=new Error(E.source+":"+L+":"+I+": "+V);if(H.reason=V,H.filename=E.source,H.line=L,H.column=I,H.source=M,!E.silent)throw H}function ue(V){var H=V.exec(M);if(H){var T=H[0];return A(T),M=M.slice(T.length),H}}function ye(){ue(i)}function B(V){var H;for(V=V||[];H=re();)H!==!1&&V.push(H);return V}function re(){var V=q();if(!(f!=M.charAt(0)||_!=M.charAt(1))){for(var H=2;x!=M.charAt(H)&&(_!=M.charAt(H)||f!=M.charAt(H+1));)++H;if(H+=2,x===M.charAt(H-1))return ne("End of comment missing");var T=M.slice(2,H-2);return I+=2,A(T),M=M.slice(H),I+=2,V({type:b,comment:T})}}function $(){var V=q(),H=ue(s);if(H){if(re(),!ue(a))return ne("property missing ':'");var T=ue(o),z=V({type:v,property:N(H[0].replace(e,x)),value:T?N(T[0].replace(e,x)):x});return ue(c),z}}function G(){var V=[];B(V);for(var H;H=$();)H!==!1&&(V.push(H),B(V));return V}return ye(),G()}function N(M){return M?M.replace(h,x):x}return xf=S,xf}var mv;function CN(){if(mv)return sl;mv=1;var e=sl&&sl.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(sl,"__esModule",{value:!0}),sl.default=i;const t=e(wN());function i(s,a){let o=null;if(!s||typeof s!="string")return o;const c=(0,t.default)(s),h=typeof a=="function";return c.forEach(p=>{if(p.type!=="declaration")return;const{property:f,value:_}=p;h?a(f,_,p):_&&(o=o||{},o[f]=_)}),o}return sl}var _o={},gv;function kN(){if(gv)return _o;gv=1,Object.defineProperty(_o,"__esModule",{value:!0}),_o.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,i=/^[^-]+$/,s=/^-(webkit|moz|ms|o|khtml)-/,a=/^-(ms)-/,o=function(f){return!f||i.test(f)||e.test(f)},c=function(f,_){return _.toUpperCase()},h=function(f,_){return"".concat(_,"-")},p=function(f,_){return _===void 0&&(_={}),o(f)?f:(f=f.toLowerCase(),_.reactCompat?f=f.replace(a,h):f=f.replace(s,h),f.replace(t,c))};return _o.camelCase=p,_o}var bo,xv;function EN(){if(xv)return bo;xv=1;var e=bo&&bo.__importDefault||function(a){return a&&a.__esModule?a:{default:a}},t=e(CN()),i=kN();function s(a,o){var c={};return!a||typeof a!="string"||(0,t.default)(a,function(h,p){h&&p&&(c[(0,i.camelCase)(h,o)]=p)}),c}return s.default=s,bo=s,bo}var NN=EN();const jN=Pu(NN),M0=B0("end"),nm=B0("start");function B0(e){return t;function t(i){const s=i&&i.position&&i.position[e]||{};if(typeof s.line=="number"&&s.line>0&&typeof s.column=="number"&&s.column>0)return{line:s.line,column:s.column,offset:typeof s.offset=="number"&&s.offset>-1?s.offset:void 0}}}function L0(e){const t=nm(e),i=M0(e);if(t&&i)return{start:t,end:i}}function Ro(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?_v(e.position):"start"in e||"end"in e?_v(e):"line"in e||"column"in e?Np(e):""}function Np(e){return bv(e&&e.line)+":"+bv(e&&e.column)}function _v(e){return Np(e&&e.start)+"-"+Np(e&&e.end)}function bv(e){return e&&typeof e=="number"?e:1}class hn extends Error{constructor(t,i,s){super(),typeof i=="string"&&(s=i,i=void 0);let a="",o={},c=!1;if(i&&("line"in i&&"column"in i?o={place:i}:"start"in i&&"end"in i?o={place:i}:"type"in i?o={ancestors:[i],place:i.position}:o={...i}),typeof t=="string"?a=t:!o.cause&&t&&(c=!0,a=t.message,o.cause=t),!o.ruleId&&!o.source&&typeof s=="string"){const p=s.indexOf(":");p===-1?o.ruleId=s:(o.source=s.slice(0,p),o.ruleId=s.slice(p+1))}if(!o.place&&o.ancestors&&o.ancestors){const p=o.ancestors[o.ancestors.length-1];p&&(o.place=p.position)}const h=o.place&&"start"in o.place?o.place.start:o.place;this.ancestors=o.ancestors||void 0,this.cause=o.cause||void 0,this.column=h?h.column:void 0,this.fatal=void 0,this.file="",this.message=a,this.line=h?h.line:void 0,this.name=Ro(o.place)||"1:1",this.place=o.place||void 0,this.reason=this.message,this.ruleId=o.ruleId||void 0,this.source=o.source||void 0,this.stack=c&&o.cause&&typeof o.cause.stack=="string"?o.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}hn.prototype.file="";hn.prototype.name="";hn.prototype.reason="";hn.prototype.message="";hn.prototype.stack="";hn.prototype.column=void 0;hn.prototype.line=void 0;hn.prototype.ancestors=void 0;hn.prototype.cause=void 0;hn.prototype.fatal=void 0;hn.prototype.place=void 0;hn.prototype.ruleId=void 0;hn.prototype.source=void 0;const rm={}.hasOwnProperty,TN=new Map,AN=/[A-Z]/g,RN=new Set(["table","tbody","thead","tfoot","tr"]),DN=new Set(["td","th"]),O0="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function MN(e,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const i=t.filePath||void 0;let s;if(t.development){if(typeof t.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");s=UN(i,t.jsxDEV)}else{if(typeof t.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof t.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");s=HN(i,t.jsx,t.jsxs)}const a={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:s,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:i,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?im:yN,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},o=z0(a,e,void 0);return o&&typeof o!="string"?o:a.create(e,a.Fragment,{children:o||void 0},void 0)}function z0(e,t,i){if(t.type==="element")return BN(e,t,i);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return LN(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return zN(e,t,i);if(t.type==="mdxjsEsm")return ON(e,t);if(t.type==="root")return PN(e,t,i);if(t.type==="text")return IN(e,t)}function BN(e,t,i){const s=e.schema;let a=s;t.tagName.toLowerCase()==="svg"&&s.space==="html"&&(a=im,e.schema=a),e.ancestors.push(t);const o=I0(e,t.tagName,!1),c=$N(e,t);let h=am(e,t);return RN.has(t.tagName)&&(h=h.filter(function(p){return typeof p=="string"?!hN(p):!0})),P0(e,c,o,t),sm(c,h),e.ancestors.pop(),e.schema=s,e.create(t,o,c,i)}function LN(e,t){if(t.data&&t.data.estree&&e.evaluater){const s=t.data.estree.body[0];return s.type,e.evaluater.evaluateExpression(s.expression)}Po(e,t.position)}function ON(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);Po(e,t.position)}function zN(e,t,i){const s=e.schema;let a=s;t.name==="svg"&&s.space==="html"&&(a=im,e.schema=a),e.ancestors.push(t);const o=t.name===null?e.Fragment:I0(e,t.name,!0),c=FN(e,t),h=am(e,t);return P0(e,c,o,t),sm(c,h),e.ancestors.pop(),e.schema=s,e.create(t,o,c,i)}function PN(e,t,i){const s={};return sm(s,am(e,t)),e.create(t,e.Fragment,s,i)}function IN(e,t){return t.value}function P0(e,t,i,s){typeof i!="string"&&i!==e.Fragment&&e.passNode&&(t.node=s)}function sm(e,t){if(t.length>0){const i=t.length>1?t:t[0];i&&(e.children=i)}}function HN(e,t,i){return s;function s(a,o,c,h){const f=Array.isArray(c.children)?i:t;return h?f(o,c,h):f(o,c)}}function UN(e,t){return i;function i(s,a,o,c){const h=Array.isArray(o.children),p=nm(s);return t(a,o,c,h,{columnNumber:p?p.column-1:void 0,fileName:e,lineNumber:p?p.line:void 0},void 0)}}function $N(e,t){const i={};let s,a;for(a in t.properties)if(a!=="children"&&rm.call(t.properties,a)){const o=qN(e,a,t.properties[a]);if(o){const[c,h]=o;e.tableCellAlignToStyle&&c==="align"&&typeof h=="string"&&DN.has(t.tagName)?s=h:i[c]=h}}if(s){const o=i.style||(i.style={});o[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=s}return i}function FN(e,t){const i={};for(const s of t.attributes)if(s.type==="mdxJsxExpressionAttribute")if(s.data&&s.data.estree&&e.evaluater){const o=s.data.estree.body[0];o.type;const c=o.expression;c.type;const h=c.properties[0];h.type,Object.assign(i,e.evaluater.evaluateExpression(h.argument))}else Po(e,t.position);else{const a=s.name;let o;if(s.value&&typeof s.value=="object")if(s.value.data&&s.value.data.estree&&e.evaluater){const h=s.value.data.estree.body[0];h.type,o=e.evaluater.evaluateExpression(h.expression)}else Po(e,t.position);else o=s.value===null?!0:s.value;i[a]=o}return i}function am(e,t){const i=[];let s=-1;const a=e.passKeys?new Map:TN;for(;++sa?0:a+t:t=t>a?a:t,i=i>0?i:0,s.length<1e4)c=Array.from(s),c.unshift(t,i),e.splice(...c);else for(i&&e.splice(t,i);o0?(Yn(e,e.length,0,t),e):t}const Sv={}.hasOwnProperty;function U0(e){const t={};let i=-1;for(;++i13&&i<32||i>126&&i<160||i>55295&&i<57344||i>64975&&i<65008||(i&65535)===65535||(i&65535)===65534||i>1114111?"�":String.fromCodePoint(i)}function xr(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const xn=Fs(/[A-Za-z]/),un=Fs(/[\dA-Za-z]/),JN=Fs(/[#-'*+\--9=?A-Z^-~]/);function Mu(e){return e!==null&&(e<32||e===127)}const jp=Fs(/\d/),e5=Fs(/[\dA-Fa-f]/),t5=Fs(/[!-/:-@[-`{-~]/);function Ye(e){return e!==null&&e<-2}function qt(e){return e!==null&&(e<0||e===32)}function mt(e){return e===-2||e===-1||e===32}const Fu=Fs(new RegExp("\\p{P}|\\p{S}","u")),ba=Fs(/\s/);function Fs(e){return t;function t(i){return i!==null&&i>-1&&e.test(String.fromCharCode(i))}}function bl(e){const t=[];let i=-1,s=0,a=0;for(;++i55295&&o<57344){const h=e.charCodeAt(i+1);o<56320&&h>56319&&h<57344?(c=String.fromCharCode(o,h),a=1):c="�"}else c=String.fromCharCode(o);c&&(t.push(e.slice(s,i),encodeURIComponent(c)),s=i+a+1,c=""),a&&(i+=a,a=0)}return t.join("")+e.slice(s)}function yt(e,t,i,s){const a=s?s-1:Number.POSITIVE_INFINITY;let o=0;return c;function c(p){return mt(p)?(e.enter(i),h(p)):t(p)}function h(p){return mt(p)&&o++c))return;const ne=t.events.length;let ue=ne,ye,B;for(;ue--;)if(t.events[ue][0]==="exit"&&t.events[ue][1].type==="chunkFlow"){if(ye){B=t.events[ue][1].end;break}ye=!0}for(E(s),R=ne;RI;){const q=i[A];t.containerState=q[1],q[0].exit.call(t,e)}i.length=I}function L(){a.write([null]),o=void 0,a=void 0,t.containerState._closeFlow=void 0}}function a5(e,t,i){return yt(e,e.attempt(this.parser.constructs.document,t,i),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function pl(e){if(e===null||qt(e)||ba(e))return 1;if(Fu(e))return 2}function qu(e,t,i){const s=[];let a=-1;for(;++a1&&e[i][1].end.offset-e[i][1].start.offset>1?2:1;const x={...e[s][1].end},b={...e[i][1].start};Cv(x,-p),Cv(b,p),c={type:p>1?"strongSequence":"emphasisSequence",start:x,end:{...e[s][1].end}},h={type:p>1?"strongSequence":"emphasisSequence",start:{...e[i][1].start},end:b},o={type:p>1?"strongText":"emphasisText",start:{...e[s][1].end},end:{...e[i][1].start}},a={type:p>1?"strong":"emphasis",start:{...c.start},end:{...h.end}},e[s][1].end={...c.start},e[i][1].start={...h.end},f=[],e[s][1].end.offset-e[s][1].start.offset&&(f=lr(f,[["enter",e[s][1],t],["exit",e[s][1],t]])),f=lr(f,[["enter",a,t],["enter",c,t],["exit",c,t],["enter",o,t]]),f=lr(f,qu(t.parser.constructs.insideSpan.null,e.slice(s+1,i),t)),f=lr(f,[["exit",o,t],["enter",h,t],["exit",h,t],["exit",a,t]]),e[i][1].end.offset-e[i][1].start.offset?(_=2,f=lr(f,[["enter",e[i][1],t],["exit",e[i][1],t]])):_=0,Yn(e,s-1,i-s+3,f),i=s+f.length-_-2;break}}for(i=-1;++i0&&mt(R)?yt(e,L,"linePrefix",o+1)(R):L(R)}function L(R){return R===null||Ye(R)?e.check(kv,N,A)(R):(e.enter("codeFlowValue"),I(R))}function I(R){return R===null||Ye(R)?(e.exit("codeFlowValue"),L(R)):(e.consume(R),I)}function A(R){return e.exit("codeFenced"),t(R)}function q(R,ne,ue){let ye=0;return B;function B(H){return R.enter("lineEnding"),R.consume(H),R.exit("lineEnding"),re}function re(H){return R.enter("codeFencedFence"),mt(H)?yt(R,$,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(H):$(H)}function $(H){return H===h?(R.enter("codeFencedFenceSequence"),G(H)):ue(H)}function G(H){return H===h?(ye++,R.consume(H),G):ye>=c?(R.exit("codeFencedFenceSequence"),mt(H)?yt(R,V,"whitespace")(H):V(H)):ue(H)}function V(H){return H===null||Ye(H)?(R.exit("codeFencedFence"),ne(H)):ue(H)}}}function _5(e,t,i){const s=this;return a;function a(c){return c===null?i(c):(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),o)}function o(c){return s.parser.lazy[s.now().line]?i(c):t(c)}}const bf={name:"codeIndented",tokenize:v5},b5={partial:!0,tokenize:y5};function v5(e,t,i){const s=this;return a;function a(f){return e.enter("codeIndented"),yt(e,o,"linePrefix",5)(f)}function o(f){const _=s.events[s.events.length-1];return _&&_[1].type==="linePrefix"&&_[2].sliceSerialize(_[1],!0).length>=4?c(f):i(f)}function c(f){return f===null?p(f):Ye(f)?e.attempt(b5,c,p)(f):(e.enter("codeFlowValue"),h(f))}function h(f){return f===null||Ye(f)?(e.exit("codeFlowValue"),c(f)):(e.consume(f),h)}function p(f){return e.exit("codeIndented"),t(f)}}function y5(e,t,i){const s=this;return a;function a(c){return s.parser.lazy[s.now().line]?i(c):Ye(c)?(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),a):yt(e,o,"linePrefix",5)(c)}function o(c){const h=s.events[s.events.length-1];return h&&h[1].type==="linePrefix"&&h[2].sliceSerialize(h[1],!0).length>=4?t(c):Ye(c)?a(c):i(c)}}const S5={name:"codeText",previous:C5,resolve:w5,tokenize:k5};function w5(e){let t=e.length-4,i=3,s,a;if((e[i][1].type==="lineEnding"||e[i][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(s=i;++s=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return tthis.left.length?this.right.slice(this.right.length-s+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-s+this.left.length).reverse())}splice(t,i,s){const a=i||0;this.setCursor(Math.trunc(t));const o=this.right.splice(this.right.length-a,Number.POSITIVE_INFINITY);return s&&vo(this.left,s),o.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),vo(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),vo(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t=4?t(c):e.interrupt(s.parser.constructs.flow,i,t)(c)}}function Y0(e,t,i,s,a,o,c,h,p){const f=p||Number.POSITIVE_INFINITY;let _=0;return x;function x(E){return E===60?(e.enter(s),e.enter(a),e.enter(o),e.consume(E),e.exit(o),b):E===null||E===32||E===41||Mu(E)?i(E):(e.enter(s),e.enter(c),e.enter(h),e.enter("chunkString",{contentType:"string"}),N(E))}function b(E){return E===62?(e.enter(o),e.consume(E),e.exit(o),e.exit(a),e.exit(s),t):(e.enter(h),e.enter("chunkString",{contentType:"string"}),v(E))}function v(E){return E===62?(e.exit("chunkString"),e.exit(h),b(E)):E===null||E===60||Ye(E)?i(E):(e.consume(E),E===92?S:v)}function S(E){return E===60||E===62||E===92?(e.consume(E),v):v(E)}function N(E){return!_&&(E===null||E===41||qt(E))?(e.exit("chunkString"),e.exit(h),e.exit(c),e.exit(s),t(E)):_999||v===null||v===91||v===93&&!p||v===94&&!h&&"_hiddenFootnoteSupport"in c.parser.constructs?i(v):v===93?(e.exit(o),e.enter(a),e.consume(v),e.exit(a),e.exit(s),t):Ye(v)?(e.enter("lineEnding"),e.consume(v),e.exit("lineEnding"),_):(e.enter("chunkString",{contentType:"string"}),x(v))}function x(v){return v===null||v===91||v===93||Ye(v)||h++>999?(e.exit("chunkString"),_(v)):(e.consume(v),p||(p=!mt(v)),v===92?b:x)}function b(v){return v===91||v===92||v===93?(e.consume(v),h++,x):x(v)}}function K0(e,t,i,s,a,o){let c;return h;function h(b){return b===34||b===39||b===40?(e.enter(s),e.enter(a),e.consume(b),e.exit(a),c=b===40?41:b,p):i(b)}function p(b){return b===c?(e.enter(a),e.consume(b),e.exit(a),e.exit(s),t):(e.enter(o),f(b))}function f(b){return b===c?(e.exit(o),p(c)):b===null?i(b):Ye(b)?(e.enter("lineEnding"),e.consume(b),e.exit("lineEnding"),yt(e,f,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),_(b))}function _(b){return b===c||b===null||Ye(b)?(e.exit("chunkString"),f(b)):(e.consume(b),b===92?x:_)}function x(b){return b===c||b===92?(e.consume(b),_):_(b)}}function Do(e,t){let i;return s;function s(a){return Ye(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),i=!0,s):mt(a)?yt(e,s,i?"linePrefix":"lineSuffix")(a):t(a)}}const M5={name:"definition",tokenize:L5},B5={partial:!0,tokenize:O5};function L5(e,t,i){const s=this;let a;return o;function o(v){return e.enter("definition"),c(v)}function c(v){return V0.call(s,e,h,i,"definitionLabel","definitionLabelMarker","definitionLabelString")(v)}function h(v){return a=xr(s.sliceSerialize(s.events[s.events.length-1][1]).slice(1,-1)),v===58?(e.enter("definitionMarker"),e.consume(v),e.exit("definitionMarker"),p):i(v)}function p(v){return qt(v)?Do(e,f)(v):f(v)}function f(v){return Y0(e,_,i,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(v)}function _(v){return e.attempt(B5,x,x)(v)}function x(v){return mt(v)?yt(e,b,"whitespace")(v):b(v)}function b(v){return v===null||Ye(v)?(e.exit("definition"),s.parser.defined.push(a),t(v)):i(v)}}function O5(e,t,i){return s;function s(h){return qt(h)?Do(e,a)(h):i(h)}function a(h){return K0(e,o,i,"definitionTitle","definitionTitleMarker","definitionTitleString")(h)}function o(h){return mt(h)?yt(e,c,"whitespace")(h):c(h)}function c(h){return h===null||Ye(h)?t(h):i(h)}}const z5={name:"hardBreakEscape",tokenize:P5};function P5(e,t,i){return s;function s(o){return e.enter("hardBreakEscape"),e.consume(o),a}function a(o){return Ye(o)?(e.exit("hardBreakEscape"),t(o)):i(o)}}const I5={name:"headingAtx",resolve:H5,tokenize:U5};function H5(e,t){let i=e.length-2,s=3,a,o;return e[s][1].type==="whitespace"&&(s+=2),i-2>s&&e[i][1].type==="whitespace"&&(i-=2),e[i][1].type==="atxHeadingSequence"&&(s===i-1||i-4>s&&e[i-2][1].type==="whitespace")&&(i-=s+1===i?2:4),i>s&&(a={type:"atxHeadingText",start:e[s][1].start,end:e[i][1].end},o={type:"chunkText",start:e[s][1].start,end:e[i][1].end,contentType:"text"},Yn(e,s,i-s+1,[["enter",a,t],["enter",o,t],["exit",o,t],["exit",a,t]])),e}function U5(e,t,i){let s=0;return a;function a(_){return e.enter("atxHeading"),o(_)}function o(_){return e.enter("atxHeadingSequence"),c(_)}function c(_){return _===35&&s++<6?(e.consume(_),c):_===null||qt(_)?(e.exit("atxHeadingSequence"),h(_)):i(_)}function h(_){return _===35?(e.enter("atxHeadingSequence"),p(_)):_===null||Ye(_)?(e.exit("atxHeading"),t(_)):mt(_)?yt(e,h,"whitespace")(_):(e.enter("atxHeadingText"),f(_))}function p(_){return _===35?(e.consume(_),p):(e.exit("atxHeadingSequence"),h(_))}function f(_){return _===null||_===35||qt(_)?(e.exit("atxHeadingText"),h(_)):(e.consume(_),f)}}const $5=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],Nv=["pre","script","style","textarea"],F5={concrete:!0,name:"htmlFlow",resolveTo:G5,tokenize:Y5},q5={partial:!0,tokenize:K5},W5={partial:!0,tokenize:V5};function G5(e){let t=e.length;for(;t--&&!(e[t][0]==="enter"&&e[t][1].type==="htmlFlow"););return t>1&&e[t-2][1].type==="linePrefix"&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function Y5(e,t,i){const s=this;let a,o,c,h,p;return f;function f(C){return _(C)}function _(C){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(C),x}function x(C){return C===33?(e.consume(C),b):C===47?(e.consume(C),o=!0,N):C===63?(e.consume(C),a=3,s.interrupt?t:j):xn(C)?(e.consume(C),c=String.fromCharCode(C),M):i(C)}function b(C){return C===45?(e.consume(C),a=2,v):C===91?(e.consume(C),a=5,h=0,S):xn(C)?(e.consume(C),a=4,s.interrupt?t:j):i(C)}function v(C){return C===45?(e.consume(C),s.interrupt?t:j):i(C)}function S(C){const Z="CDATA[";return C===Z.charCodeAt(h++)?(e.consume(C),h===Z.length?s.interrupt?t:$:S):i(C)}function N(C){return xn(C)?(e.consume(C),c=String.fromCharCode(C),M):i(C)}function M(C){if(C===null||C===47||C===62||qt(C)){const Z=C===47,ae=c.toLowerCase();return!Z&&!o&&Nv.includes(ae)?(a=1,s.interrupt?t(C):$(C)):$5.includes(c.toLowerCase())?(a=6,Z?(e.consume(C),E):s.interrupt?t(C):$(C)):(a=7,s.interrupt&&!s.parser.lazy[s.now().line]?i(C):o?L(C):I(C))}return C===45||un(C)?(e.consume(C),c+=String.fromCharCode(C),M):i(C)}function E(C){return C===62?(e.consume(C),s.interrupt?t:$):i(C)}function L(C){return mt(C)?(e.consume(C),L):B(C)}function I(C){return C===47?(e.consume(C),B):C===58||C===95||xn(C)?(e.consume(C),A):mt(C)?(e.consume(C),I):B(C)}function A(C){return C===45||C===46||C===58||C===95||un(C)?(e.consume(C),A):q(C)}function q(C){return C===61?(e.consume(C),R):mt(C)?(e.consume(C),q):I(C)}function R(C){return C===null||C===60||C===61||C===62||C===96?i(C):C===34||C===39?(e.consume(C),p=C,ne):mt(C)?(e.consume(C),R):ue(C)}function ne(C){return C===p?(e.consume(C),p=null,ye):C===null||Ye(C)?i(C):(e.consume(C),ne)}function ue(C){return C===null||C===34||C===39||C===47||C===60||C===61||C===62||C===96||qt(C)?q(C):(e.consume(C),ue)}function ye(C){return C===47||C===62||mt(C)?I(C):i(C)}function B(C){return C===62?(e.consume(C),re):i(C)}function re(C){return C===null||Ye(C)?$(C):mt(C)?(e.consume(C),re):i(C)}function $(C){return C===45&&a===2?(e.consume(C),T):C===60&&a===1?(e.consume(C),z):C===62&&a===4?(e.consume(C),D):C===63&&a===3?(e.consume(C),j):C===93&&a===5?(e.consume(C),xe):Ye(C)&&(a===6||a===7)?(e.exit("htmlFlowData"),e.check(q5,X,G)(C)):C===null||Ye(C)?(e.exit("htmlFlowData"),G(C)):(e.consume(C),$)}function G(C){return e.check(W5,V,X)(C)}function V(C){return e.enter("lineEnding"),e.consume(C),e.exit("lineEnding"),H}function H(C){return C===null||Ye(C)?G(C):(e.enter("htmlFlowData"),$(C))}function T(C){return C===45?(e.consume(C),j):$(C)}function z(C){return C===47?(e.consume(C),c="",F):$(C)}function F(C){if(C===62){const Z=c.toLowerCase();return Nv.includes(Z)?(e.consume(C),D):$(C)}return xn(C)&&c.length<8?(e.consume(C),c+=String.fromCharCode(C),F):$(C)}function xe(C){return C===93?(e.consume(C),j):$(C)}function j(C){return C===62?(e.consume(C),D):C===45&&a===2?(e.consume(C),j):$(C)}function D(C){return C===null||Ye(C)?(e.exit("htmlFlowData"),X(C)):(e.consume(C),D)}function X(C){return e.exit("htmlFlow"),t(C)}}function V5(e,t,i){const s=this;return a;function a(c){return Ye(c)?(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),o):i(c)}function o(c){return s.parser.lazy[s.now().line]?i(c):t(c)}}function K5(e,t,i){return s;function s(a){return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),e.attempt(Yo,t,i)}}const X5={name:"htmlText",tokenize:Z5};function Z5(e,t,i){const s=this;let a,o,c;return h;function h(j){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(j),p}function p(j){return j===33?(e.consume(j),f):j===47?(e.consume(j),q):j===63?(e.consume(j),I):xn(j)?(e.consume(j),ue):i(j)}function f(j){return j===45?(e.consume(j),_):j===91?(e.consume(j),o=0,S):xn(j)?(e.consume(j),L):i(j)}function _(j){return j===45?(e.consume(j),v):i(j)}function x(j){return j===null?i(j):j===45?(e.consume(j),b):Ye(j)?(c=x,z(j)):(e.consume(j),x)}function b(j){return j===45?(e.consume(j),v):x(j)}function v(j){return j===62?T(j):j===45?b(j):x(j)}function S(j){const D="CDATA[";return j===D.charCodeAt(o++)?(e.consume(j),o===D.length?N:S):i(j)}function N(j){return j===null?i(j):j===93?(e.consume(j),M):Ye(j)?(c=N,z(j)):(e.consume(j),N)}function M(j){return j===93?(e.consume(j),E):N(j)}function E(j){return j===62?T(j):j===93?(e.consume(j),E):N(j)}function L(j){return j===null||j===62?T(j):Ye(j)?(c=L,z(j)):(e.consume(j),L)}function I(j){return j===null?i(j):j===63?(e.consume(j),A):Ye(j)?(c=I,z(j)):(e.consume(j),I)}function A(j){return j===62?T(j):I(j)}function q(j){return xn(j)?(e.consume(j),R):i(j)}function R(j){return j===45||un(j)?(e.consume(j),R):ne(j)}function ne(j){return Ye(j)?(c=ne,z(j)):mt(j)?(e.consume(j),ne):T(j)}function ue(j){return j===45||un(j)?(e.consume(j),ue):j===47||j===62||qt(j)?ye(j):i(j)}function ye(j){return j===47?(e.consume(j),T):j===58||j===95||xn(j)?(e.consume(j),B):Ye(j)?(c=ye,z(j)):mt(j)?(e.consume(j),ye):T(j)}function B(j){return j===45||j===46||j===58||j===95||un(j)?(e.consume(j),B):re(j)}function re(j){return j===61?(e.consume(j),$):Ye(j)?(c=re,z(j)):mt(j)?(e.consume(j),re):ye(j)}function $(j){return j===null||j===60||j===61||j===62||j===96?i(j):j===34||j===39?(e.consume(j),a=j,G):Ye(j)?(c=$,z(j)):mt(j)?(e.consume(j),$):(e.consume(j),V)}function G(j){return j===a?(e.consume(j),a=void 0,H):j===null?i(j):Ye(j)?(c=G,z(j)):(e.consume(j),G)}function V(j){return j===null||j===34||j===39||j===60||j===61||j===96?i(j):j===47||j===62||qt(j)?ye(j):(e.consume(j),V)}function H(j){return j===47||j===62||qt(j)?ye(j):i(j)}function T(j){return j===62?(e.consume(j),e.exit("htmlTextData"),e.exit("htmlText"),t):i(j)}function z(j){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(j),e.exit("lineEnding"),F}function F(j){return mt(j)?yt(e,xe,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(j):xe(j)}function xe(j){return e.enter("htmlTextData"),c(j)}}const cm={name:"labelEnd",resolveAll:tj,resolveTo:ij,tokenize:nj},Q5={tokenize:rj},J5={tokenize:sj},ej={tokenize:aj};function tj(e){let t=-1;const i=[];for(;++t=3&&(f===null||Ye(f))?(e.exit("thematicBreak"),t(f)):i(f)}function p(f){return f===a?(e.consume(f),s++,p):(e.exit("thematicBreakSequence"),mt(f)?yt(e,h,"whitespace")(f):h(f))}}const Rn={continuation:{tokenize:gj},exit:_j,name:"list",tokenize:mj},fj={partial:!0,tokenize:bj},pj={partial:!0,tokenize:xj};function mj(e,t,i){const s=this,a=s.events[s.events.length-1];let o=a&&a[1].type==="linePrefix"?a[2].sliceSerialize(a[1],!0).length:0,c=0;return h;function h(v){const S=s.containerState.type||(v===42||v===43||v===45?"listUnordered":"listOrdered");if(S==="listUnordered"?!s.containerState.marker||v===s.containerState.marker:jp(v)){if(s.containerState.type||(s.containerState.type=S,e.enter(S,{_container:!0})),S==="listUnordered")return e.enter("listItemPrefix"),v===42||v===45?e.check(wu,i,f)(v):f(v);if(!s.interrupt||v===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),p(v)}return i(v)}function p(v){return jp(v)&&++c<10?(e.consume(v),p):(!s.interrupt||c<2)&&(s.containerState.marker?v===s.containerState.marker:v===41||v===46)?(e.exit("listItemValue"),f(v)):i(v)}function f(v){return e.enter("listItemMarker"),e.consume(v),e.exit("listItemMarker"),s.containerState.marker=s.containerState.marker||v,e.check(Yo,s.interrupt?i:_,e.attempt(fj,b,x))}function _(v){return s.containerState.initialBlankLine=!0,o++,b(v)}function x(v){return mt(v)?(e.enter("listItemPrefixWhitespace"),e.consume(v),e.exit("listItemPrefixWhitespace"),b):i(v)}function b(v){return s.containerState.size=o+s.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(v)}}function gj(e,t,i){const s=this;return s.containerState._closeFlow=void 0,e.check(Yo,a,o);function a(h){return s.containerState.furtherBlankLines=s.containerState.furtherBlankLines||s.containerState.initialBlankLine,yt(e,t,"listItemIndent",s.containerState.size+1)(h)}function o(h){return s.containerState.furtherBlankLines||!mt(h)?(s.containerState.furtherBlankLines=void 0,s.containerState.initialBlankLine=void 0,c(h)):(s.containerState.furtherBlankLines=void 0,s.containerState.initialBlankLine=void 0,e.attempt(pj,t,c)(h))}function c(h){return s.containerState._closeFlow=!0,s.interrupt=void 0,yt(e,e.attempt(Rn,t,i),"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(h)}}function xj(e,t,i){const s=this;return yt(e,a,"listItemIndent",s.containerState.size+1);function a(o){const c=s.events[s.events.length-1];return c&&c[1].type==="listItemIndent"&&c[2].sliceSerialize(c[1],!0).length===s.containerState.size?t(o):i(o)}}function _j(e){e.exit(this.containerState.type)}function bj(e,t,i){const s=this;return yt(e,a,"listItemPrefixWhitespace",s.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function a(o){const c=s.events[s.events.length-1];return!mt(o)&&c&&c[1].type==="listItemPrefixWhitespace"?t(o):i(o)}}const jv={name:"setextUnderline",resolveTo:vj,tokenize:yj};function vj(e,t){let i=e.length,s,a,o;for(;i--;)if(e[i][0]==="enter"){if(e[i][1].type==="content"){s=i;break}e[i][1].type==="paragraph"&&(a=i)}else e[i][1].type==="content"&&e.splice(i,1),!o&&e[i][1].type==="definition"&&(o=i);const c={type:"setextHeading",start:{...e[s][1].start},end:{...e[e.length-1][1].end}};return e[a][1].type="setextHeadingText",o?(e.splice(a,0,["enter",c,t]),e.splice(o+1,0,["exit",e[s][1],t]),e[s][1].end={...e[o][1].end}):e[s][1]=c,e.push(["exit",c,t]),e}function yj(e,t,i){const s=this;let a;return o;function o(f){let _=s.events.length,x;for(;_--;)if(s.events[_][1].type!=="lineEnding"&&s.events[_][1].type!=="linePrefix"&&s.events[_][1].type!=="content"){x=s.events[_][1].type==="paragraph";break}return!s.parser.lazy[s.now().line]&&(s.interrupt||x)?(e.enter("setextHeadingLine"),a=f,c(f)):i(f)}function c(f){return e.enter("setextHeadingLineSequence"),h(f)}function h(f){return f===a?(e.consume(f),h):(e.exit("setextHeadingLineSequence"),mt(f)?yt(e,p,"lineSuffix")(f):p(f))}function p(f){return f===null||Ye(f)?(e.exit("setextHeadingLine"),t(f)):i(f)}}const Sj={tokenize:wj};function wj(e){const t=this,i=e.attempt(Yo,s,e.attempt(this.parser.constructs.flowInitial,a,yt(e,e.attempt(this.parser.constructs.flow,a,e.attempt(j5,a)),"linePrefix")));return i;function s(o){if(o===null){e.consume(o);return}return e.enter("lineEndingBlank"),e.consume(o),e.exit("lineEndingBlank"),t.currentConstruct=void 0,i}function a(o){if(o===null){e.consume(o);return}return e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),t.currentConstruct=void 0,i}}const Cj={resolveAll:Z0()},kj=X0("string"),Ej=X0("text");function X0(e){return{resolveAll:Z0(e==="text"?Nj:void 0),tokenize:t};function t(i){const s=this,a=this.parser.constructs[e],o=i.attempt(a,c,h);return c;function c(_){return f(_)?o(_):h(_)}function h(_){if(_===null){i.consume(_);return}return i.enter("data"),i.consume(_),p}function p(_){return f(_)?(i.exit("data"),o(_)):(i.consume(_),p)}function f(_){if(_===null)return!0;const x=a[_];let b=-1;if(x)for(;++b-1){const h=c[0];typeof h=="string"?c[0]=h.slice(s):c.shift()}o>0&&c.push(e[a].slice(0,o))}return c}function Hj(e,t){let i=-1;const s=[];let a;for(;++inew Set(qe).add(X))}},he.term.onData(Ue=>{st.readyState===WebSocket.OPEN&&st.send(Ue)}),he.ws=st},[e]);w.useEffect(()=>{V.current=xe},[xe]);const j=w.useCallback(async(X,he)=>{if(!S.current||zi.has(X))return;const{resume:ge=!1,autoConnect:Re=!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 Fe=new FE({cols:80,scrollback:5e3,fontSize:13,fontFamily:'"Geist Mono", ui-monospace, monospace',lineHeight:1.05,letterSpacing:0,cursorBlink:!0,cursorStyle:"block",theme:iN,allowTransparency:!1,drawBoldTextInBrightColors:!1,minimumContrastRatio:7}),ye=new GE,st=new ZE;Fe.loadAddon(ye),Fe.loadAddon(st),Fe.open(Le);const yt={term:Fe,fit:ye,serialize:st,ws:null,container:Le,observer:null,connected:!1},Ue=new ResizeObserver(()=>{var St;const{width:qe}=Le.getBoundingClientRect();if(!(qe<50))try{ye.fit(),((St=yt.ws)==null?void 0:St.readyState)===WebSocket.OPEN&&yt.ws.send(JSON.stringify({type:"resize",cols:Fe.cols,rows:Fe.rows}))}catch{}});Ue.observe(Le),yt.observer=Ue,zi.set(X,yt),E(qe=>[...qe,X]);try{const qe=await sN(X);if(qe){const St=lv(qe);Fe.write(St),St!==qe&&rl(X,St).catch(()=>{})}}catch{}Re?xe(X,yt,ge):H(qe=>new Set(qe).add(X)),setTimeout(()=>U(yt),50)},[xe,U]),R=w.useCallback(async(X,he)=>{const ge=zi.get(X);ge&&(ge.ws&&(ge.ws.close(),ge.ws=null),he||(await N.current(`/api/terminal/${encodeURIComponent(X)}`,{method:"DELETE"}).catch(()=>{}),ge.term.clear()),xe(X,ge,he))},[xe]),Z=w.useCallback(X=>{const he=zi.get(X);if(he){try{const ge=he.serialize.serialize();rl(X,ge).catch(()=>{})}catch{}he.observer.disconnect(),he.ws&&he.ws.close(),he.term.dispose(),he.container.remove(),zi.delete(X),E(ge=>ge.filter(Re=>Re!==X)),H(ge=>{const Re=new Set(ge);return Re.delete(X),Re}),i(`/api/terminal/${encodeURIComponent(X)}`,{method:"DELETE"}).catch(()=>{}),a==null||a(X)}},[i,a]),k=w.useCallback(X=>{var ge;const he=zi.get(X);he&&(((ge=he.ws)==null?void 0:ge.readyState)===WebSocket.OPEN&&he.ws.send(`exit +`),mf(X).catch(()=>{}),he.observer.disconnect(),he.ws&&he.ws.close(),he.term.dispose(),he.container.remove(),zi.delete(X),E(Re=>Re.filter(Le=>Le!==X)),H(Re=>{const Le=new Set(Re);return Le.delete(X),Le}),i(`/api/terminal/${encodeURIComponent(X)}/discard`,{method:"DELETE"}).catch(()=>{}),a==null||a(X))},[i,a]),K=w.useCallback(async(X,he,ge)=>{const Re=zi.get(X);if(!Re||zi.has(he)||!(await N.current("/api/terminal/rename",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldName:X,newName:he,...ge??{}})})).ok)return!1;zi.delete(X),zi.set(he,Re);try{const Fe=Re.serialize.serialize();await mf(X),await rl(he,Fe)}catch{}return E(Fe=>Fe.map(ye=>ye===X?he:ye)),H(Fe=>{if(!Fe.has(X))return Fe;const ye=new Set(Fe);return ye.delete(X),ye.add(he),ye}),(Re.connected||Re.ws)&&(await N.current(`/api/terminal/${encodeURIComponent(he)}`,{method:"DELETE"}).catch(()=>{}),Re.ws&&(Re.ws.close(),Re.ws=null),V.current(he,Re,!0)),!0},[]);w.useEffect(()=>(h&&(h.current=K),()=>{h&&(h.current=null)}),[h,K]),w.useEffect(()=>{if(t){if(F){T(null);return}if(Y){T(null);return}zi.has(t)?T(t):N.current(`/api/terminal/session/${encodeURIComponent(t)}`).then(X=>X.ok?X.json():null).then(X=>{if(!zi.has(t)){const he=(X==null?void 0:X.sessionId)&&!(X!=null&&X.running);j(t,{autoConnect:!he}),T(t)}}).catch(()=>{zi.has(t)||(j(t),T(t))})}},[t,j,T,F,Y]),w.useEffect(()=>{const X=setInterval(()=>{for(const[he,ge]of zi)if(ge.connected)try{const Re=ge.serialize.serialize();rl(he,Re).catch(()=>{})}catch{}},3e4);return()=>clearInterval(X)},[]),w.useEffect(()=>()=>{for(const[X,he]of zi){try{const ge=he.serialize.serialize();rl(X,ge).catch(()=>{})}catch{}he.observer.disconnect(),he.ws&&he.ws.close(),he.term.dispose(),he.container.remove(),N.current(`/api/terminal/${encodeURIComponent(X)}`,{method:"DELETE"}).catch(()=>{})}zi.clear()},[]);const ae=t?O.has(t):!1,oe=B.length===0;return d.jsxs("div",{className:"h-full flex flex-col",children:[!oe&&d.jsxs("div",{className:"px-2 py-1 border-b border-border flex items-center gap-1 overflow-x-auto",children:[B.map(X=>d.jsxs("div",{onClick:()=>s==null?void 0:s(X),className:`flex items-center gap-1 px-2 py-0.5 rounded text-xs font-mono cursor-pointer ${X===t?"bg-accent/10 text-accent":"text-muted hover:text-foreground"}`,children:[d.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${O.has(X)?"bg-amber-500":X===t?"bg-green-600":"bg-muted/50"}`}),d.jsx("span",{className:`truncate max-w-[120px] ${X.startsWith("_new_")?"italic":""}`,children:X.startsWith("_new_")?"Untitled":X}),d.jsx("button",{onClick:he=>{he.stopPropagation(),X.startsWith("_new_")?W(X):Z(X)},className:"ml-0.5 text-muted hover:text-error text-[10px] leading-none",title:"Close terminal",children:"×"})]},X)),t!=null&&t.startsWith("_new_")?d.jsx("button",{onClick:()=>W(t),className:"ml-auto px-2 py-0.5 text-xs text-error hover:bg-surface rounded flex items-center gap-1 flex-shrink-0",children:"Cancel ×"}):t&&o&&(c!=null&&c.has(t))?d.jsx("button",{onClick:()=>ne(t),className:"ml-auto px-2 py-0.5 text-xs text-muted hover:text-foreground hover:bg-surface rounded flex items-center gap-1 flex-shrink-0",children:"Archive"}):null]}),d.jsxs("div",{className:"relative flex-1 min-h-0",children:[d.jsx("div",{ref:S,className:"h-full"}),oe&&!F&&!Y&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center text-muted",children:d.jsxs("div",{className:"text-center",children:[d.jsx("p",{className:"text-lg font-serif",children:"Select a story on the left menu"}),d.jsx("p",{className:"text-sm mt-1",children:"to start an AI Writer session"})]})}),F&&d.jsx("div",{"data-testid":"cartoon-launch-blocked",className:"absolute inset-0 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-md",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Cartoon agent can't launch yet"}),d.jsx("p",{className:"text-xs text-muted",children:"This is a cartoon story. The writing agent needs Codex with image generation enabled before it can start, because the clean-image step relies on image generation support."}),_&&!_.codex.installed?d.jsxs("p",{className:"text-xs text-amber-700",children:["Codex was not detected. Install the Codex CLI and sign in (e.g. ",d.jsx("span",{className:"font-mono",children:"npm i -g @openai/codex"})," then"," ",d.jsx("span",{className:"font-mono",children:"codex login"}),"), then reopen this story."]}):Eu(_)?d.jsxs("p",{className:"text-xs text-amber-700","data-testid":"codex-auth-unknown-launch",children:[Fp," Then reopen this story."]}):d.jsxs("div",{className:"space-y-1",children:[d.jsx("p",{className:"text-xs text-amber-700",children:"Codex is installed but image generation isn't enabled. Enable it, then reopen this story:"}),d.jsxs("div",{className:"flex items-center gap-1",children:[d.jsx("code",{className:"flex-1 truncate rounded border border-border bg-surface px-1.5 py-1 text-left text-[10px] font-mono text-foreground",children:ov}),d.jsx("button",{type:"button","data-testid":"copy-codex-enable-launch",onClick:async()=>{try{await navigator.clipboard.writeText(ov),be(!0),setTimeout(()=>be(!1),2e3)}catch{}},className:"rounded border border-border px-2 py-1 text-[10px] text-muted hover:border-accent hover:text-accent transition-colors",children:ue?"Copied!":"Copy"})]})]})]})}),Y&&!F&&d.jsx("div",{"data-testid":"legacy-cartoon-provider-repair",className:"absolute inset-0 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-md",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Set this cartoon story's provider"}),d.jsx("p",{className:"text-xs text-muted",children:"This cartoon story was created before provider tracking, so it has no provider recorded and would launch with Claude — which can't generate the clean images cartoons need. Set this story's provider to Codex to continue."}),d.jsx("p",{className:"text-[11px] text-muted",children:"Only this story is changed. Other stories and fiction are not affected."}),d.jsx("button",{type:"button","data-testid":"repair-provider-codex",disabled:L,onClick:async()=>{if(!L){re(!0);try{await(v==null?void 0:v())}finally{re(!1)}}},className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim disabled:opacity-50 disabled:cursor-not-allowed",children:L?"Setting…":"Set this story's provider to Codex"})]})}),A&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-10",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"text-center space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-sm",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Discard this session?"}),d.jsx("p",{className:"text-xs text-muted",children:"This session will be lost — your AI hasn't created a story structure yet."}),d.jsxs("div",{className:"flex items-center justify-center gap-2",children:[d.jsx("button",{onClick:()=>W(null),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Cancel"}),d.jsx("button",{onClick:()=>{const X=A;W(null),k(X)},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:()=>ne(null),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Cancel"}),d.jsx("button",{onClick:async()=>{const X=D;ne(null);try{(await N.current("/api/stories/archive",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:X})})).ok&&(Z(X),o==null||o(X))}catch{}},className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim",children:"Archive"})]})]})}),ae&&t&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"text-center space-y-3",children:[d.jsx("p",{className:"text-sm font-serif text-foreground",children:"Terminal disconnected"}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{onClick:()=>R(t,!0),className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim",children:"Resume Session"}),d.jsx("button",{onClick:()=>R(t,!1),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Start Fresh"})]}),d.jsx("p",{className:"text-xs text-muted",children:"Resume continues your previous Claude conversation"})]})})]})]})}function lN(e,t){const i={};return(e[e.length-1]===""?[...e,""]:e).join((i.padRight?" ":"")+","+(i.padLeft===!1?"":" ")).trim()}const oN=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,cN=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,uN={};function uv(e,t){return(uN.jsx?cN:oN).test(e)}const hN=/[ \t\n\f\r]/g;function dN(e){return typeof e=="object"?e.type==="text"?hv(e.value):!1:hv(e)}function hv(e){return e.replace(hN,"")===""}class Go{constructor(t,i,s){this.normal=i,this.property=t,s&&(this.space=s)}}Go.prototype.normal={};Go.prototype.property={};Go.prototype.space=void 0;function E0(e,t){const i={},s={};for(const a of e)Object.assign(i,a.property),Object.assign(s,a.normal);return new Go(i,s,t)}function Cp(e){return e.toLowerCase()}class Mn{constructor(t,i){this.attribute=i,this.property=t}}Mn.prototype.attribute="";Mn.prototype.booleanish=!1;Mn.prototype.boolean=!1;Mn.prototype.commaOrSpaceSeparated=!1;Mn.prototype.commaSeparated=!1;Mn.prototype.defined=!1;Mn.prototype.mustUseProperty=!1;Mn.prototype.number=!1;Mn.prototype.overloadedBoolean=!1;Mn.prototype.property="";Mn.prototype.spaceSeparated=!1;Mn.prototype.space=void 0;let fN=0;const lt=ya(),Ti=ya(),kp=ya(),ve=ya(),Vt=ya(),ul=ya(),Gn=ya();function ya(){return 2**++fN}const Ep=Object.freeze(Object.defineProperty({__proto__:null,boolean:lt,booleanish:Ti,commaOrSpaceSeparated:Gn,commaSeparated:ul,number:ve,overloadedBoolean:kp,spaceSeparated:Vt},Symbol.toStringTag,{value:"Module"})),gf=Object.keys(Ep);class tm extends Mn{constructor(t,i,s,a){let o=-1;if(super(t,i),dv(this,"space",a),typeof s=="number")for(;++o4&&i.slice(0,4)==="data"&&_N.test(t)){if(t.charAt(4)==="-"){const o=t.slice(5).replace(fv,yN);s="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=t.slice(4);if(!fv.test(o)){let c=o.replace(xN,vN);c.charAt(0)!=="-"&&(c="-"+c),t="data"+c}}a=tm}return new a(s,t)}function vN(e){return"-"+e.toLowerCase()}function yN(e){return e.charAt(1).toUpperCase()}const SN=E0([N0,pN,A0,R0,D0],"html"),im=E0([N0,mN,A0,R0,D0],"svg");function wN(e){return e.join(" ").trim()}var sl={},xf,pv;function CN(){if(pv)return xf;pv=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,i=/^\s*/,s=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,a=/^:\s*/,o=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,c=/^[;\s]*/,h=/^\s+|\s+$/g,p=` +`,f="/",_="*",x="",b="comment",v="declaration";function S(B,E){if(typeof B!="string")throw new TypeError("First argument must be a string");if(!B)return[];E=E||{};var O=1,H=1;function A(V){var U=V.match(t);U&&(O+=U.length);var T=V.lastIndexOf(p);H=~T?V.length-T:H+V.length}function W(){var V={line:O,column:H};return function(U){return U.position=new D(V),be(),U}}function D(V){this.start=V,this.end={line:O,column:H},this.source=E.source}D.prototype.content=B;function ne(V){var U=new Error(E.source+":"+O+":"+H+": "+V);if(U.reason=V,U.filename=E.source,U.line=O,U.column=H,U.source=B,!E.silent)throw U}function ue(V){var U=V.exec(B);if(U){var T=U[0];return A(T),B=B.slice(T.length),U}}function be(){ue(i)}function L(V){var U;for(V=V||[];U=re();)U!==!1&&V.push(U);return V}function re(){var V=W();if(!(f!=B.charAt(0)||_!=B.charAt(1))){for(var U=2;x!=B.charAt(U)&&(_!=B.charAt(U)||f!=B.charAt(U+1));)++U;if(U+=2,x===B.charAt(U-1))return ne("End of comment missing");var T=B.slice(2,U-2);return H+=2,A(T),B=B.slice(U),H+=2,V({type:b,comment:T})}}function F(){var V=W(),U=ue(s);if(U){if(re(),!ue(a))return ne("property missing ':'");var T=ue(o),P=V({type:v,property:N(U[0].replace(e,x)),value:T?N(T[0].replace(e,x)):x});return ue(c),P}}function Y(){var V=[];L(V);for(var U;U=F();)U!==!1&&(V.push(U),L(V));return V}return be(),Y()}function N(B){return B?B.replace(h,x):x}return xf=S,xf}var mv;function kN(){if(mv)return sl;mv=1;var e=sl&&sl.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(sl,"__esModule",{value:!0}),sl.default=i;const t=e(CN());function i(s,a){let o=null;if(!s||typeof s!="string")return o;const c=(0,t.default)(s),h=typeof a=="function";return c.forEach(p=>{if(p.type!=="declaration")return;const{property:f,value:_}=p;h?a(f,_,p):_&&(o=o||{},o[f]=_)}),o}return sl}var _o={},gv;function EN(){if(gv)return _o;gv=1,Object.defineProperty(_o,"__esModule",{value:!0}),_o.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,i=/^[^-]+$/,s=/^-(webkit|moz|ms|o|khtml)-/,a=/^-(ms)-/,o=function(f){return!f||i.test(f)||e.test(f)},c=function(f,_){return _.toUpperCase()},h=function(f,_){return"".concat(_,"-")},p=function(f,_){return _===void 0&&(_={}),o(f)?f:(f=f.toLowerCase(),_.reactCompat?f=f.replace(a,h):f=f.replace(s,h),f.replace(t,c))};return _o.camelCase=p,_o}var bo,xv;function NN(){if(xv)return bo;xv=1;var e=bo&&bo.__importDefault||function(a){return a&&a.__esModule?a:{default:a}},t=e(kN()),i=EN();function s(a,o){var c={};return!a||typeof a!="string"||(0,t.default)(a,function(h,p){h&&p&&(c[(0,i.camelCase)(h,o)]=p)}),c}return s.default=s,bo=s,bo}var jN=NN();const TN=Pu(jN),M0=B0("end"),nm=B0("start");function B0(e){return t;function t(i){const s=i&&i.position&&i.position[e]||{};if(typeof s.line=="number"&&s.line>0&&typeof s.column=="number"&&s.column>0)return{line:s.line,column:s.column,offset:typeof s.offset=="number"&&s.offset>-1?s.offset:void 0}}}function L0(e){const t=nm(e),i=M0(e);if(t&&i)return{start:t,end:i}}function Ro(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?_v(e.position):"start"in e||"end"in e?_v(e):"line"in e||"column"in e?Np(e):""}function Np(e){return bv(e&&e.line)+":"+bv(e&&e.column)}function _v(e){return Np(e&&e.start)+"-"+Np(e&&e.end)}function bv(e){return e&&typeof e=="number"?e:1}class hn extends Error{constructor(t,i,s){super(),typeof i=="string"&&(s=i,i=void 0);let a="",o={},c=!1;if(i&&("line"in i&&"column"in i?o={place:i}:"start"in i&&"end"in i?o={place:i}:"type"in i?o={ancestors:[i],place:i.position}:o={...i}),typeof t=="string"?a=t:!o.cause&&t&&(c=!0,a=t.message,o.cause=t),!o.ruleId&&!o.source&&typeof s=="string"){const p=s.indexOf(":");p===-1?o.ruleId=s:(o.source=s.slice(0,p),o.ruleId=s.slice(p+1))}if(!o.place&&o.ancestors&&o.ancestors){const p=o.ancestors[o.ancestors.length-1];p&&(o.place=p.position)}const h=o.place&&"start"in o.place?o.place.start:o.place;this.ancestors=o.ancestors||void 0,this.cause=o.cause||void 0,this.column=h?h.column:void 0,this.fatal=void 0,this.file="",this.message=a,this.line=h?h.line:void 0,this.name=Ro(o.place)||"1:1",this.place=o.place||void 0,this.reason=this.message,this.ruleId=o.ruleId||void 0,this.source=o.source||void 0,this.stack=c&&o.cause&&typeof o.cause.stack=="string"?o.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}hn.prototype.file="";hn.prototype.name="";hn.prototype.reason="";hn.prototype.message="";hn.prototype.stack="";hn.prototype.column=void 0;hn.prototype.line=void 0;hn.prototype.ancestors=void 0;hn.prototype.cause=void 0;hn.prototype.fatal=void 0;hn.prototype.place=void 0;hn.prototype.ruleId=void 0;hn.prototype.source=void 0;const rm={}.hasOwnProperty,AN=new Map,RN=/[A-Z]/g,DN=new Set(["table","tbody","thead","tfoot","tr"]),MN=new Set(["td","th"]),O0="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function BN(e,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const i=t.filePath||void 0;let s;if(t.development){if(typeof t.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");s=$N(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=UN(i,t.jsx,t.jsxs)}const a={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:s,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:i,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?im:SN,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},o=z0(a,e,void 0);return o&&typeof o!="string"?o:a.create(e,a.Fragment,{children:o||void 0},void 0)}function z0(e,t,i){if(t.type==="element")return LN(e,t,i);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return ON(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return PN(e,t,i);if(t.type==="mdxjsEsm")return zN(e,t);if(t.type==="root")return IN(e,t,i);if(t.type==="text")return HN(e,t)}function LN(e,t,i){const s=e.schema;let a=s;t.tagName.toLowerCase()==="svg"&&s.space==="html"&&(a=im,e.schema=a),e.ancestors.push(t);const o=I0(e,t.tagName,!1),c=FN(e,t);let h=am(e,t);return DN.has(t.tagName)&&(h=h.filter(function(p){return typeof p=="string"?!dN(p):!0})),P0(e,c,o,t),sm(c,h),e.ancestors.pop(),e.schema=s,e.create(t,o,c,i)}function ON(e,t){if(t.data&&t.data.estree&&e.evaluater){const s=t.data.estree.body[0];return s.type,e.evaluater.evaluateExpression(s.expression)}Po(e,t.position)}function zN(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);Po(e,t.position)}function PN(e,t,i){const s=e.schema;let a=s;t.name==="svg"&&s.space==="html"&&(a=im,e.schema=a),e.ancestors.push(t);const o=t.name===null?e.Fragment:I0(e,t.name,!0),c=qN(e,t),h=am(e,t);return P0(e,c,o,t),sm(c,h),e.ancestors.pop(),e.schema=s,e.create(t,o,c,i)}function IN(e,t,i){const s={};return sm(s,am(e,t)),e.create(t,e.Fragment,s,i)}function HN(e,t){return t.value}function P0(e,t,i,s){typeof i!="string"&&i!==e.Fragment&&e.passNode&&(t.node=s)}function sm(e,t){if(t.length>0){const i=t.length>1?t:t[0];i&&(e.children=i)}}function UN(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 $N(e,t){return i;function i(s,a,o,c){const h=Array.isArray(o.children),p=nm(s);return t(a,o,c,h,{columnNumber:p?p.column-1:void 0,fileName:e,lineNumber:p?p.line:void 0},void 0)}}function FN(e,t){const i={};let s,a;for(a in t.properties)if(a!=="children"&&rm.call(t.properties,a)){const o=WN(e,a,t.properties[a]);if(o){const[c,h]=o;e.tableCellAlignToStyle&&c==="align"&&typeof h=="string"&&MN.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 qN(e,t){const i={};for(const s of t.attributes)if(s.type==="mdxJsxExpressionAttribute")if(s.data&&s.data.estree&&e.evaluater){const o=s.data.estree.body[0];o.type;const c=o.expression;c.type;const h=c.properties[0];h.type,Object.assign(i,e.evaluater.evaluateExpression(h.argument))}else Po(e,t.position);else{const a=s.name;let o;if(s.value&&typeof s.value=="object")if(s.value.data&&s.value.data.estree&&e.evaluater){const h=s.value.data.estree.body[0];h.type,o=e.evaluater.evaluateExpression(h.expression)}else Po(e,t.position);else o=s.value===null?!0:s.value;i[a]=o}return i}function am(e,t){const i=[];let s=-1;const a=e.passKeys?new Map:AN;for(;++sa?0:a+t:t=t>a?a:t,i=i>0?i:0,s.length<1e4)c=Array.from(s),c.unshift(t,i),e.splice(...c);else for(i&&e.splice(t,i);o0?(Yn(e,e.length,0,t),e):t}const Sv={}.hasOwnProperty;function U0(e){const t={};let i=-1;for(;++i13&&i<32||i>126&&i<160||i>55295&&i<57344||i>64975&&i<65008||(i&65535)===65535||(i&65535)===65534||i>1114111?"�":String.fromCodePoint(i)}function _r(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const bn=qs(/[A-Za-z]/),un=qs(/[\dA-Za-z]/),e5=qs(/[#-'*+\--9=?A-Z^-~]/);function Mu(e){return e!==null&&(e<32||e===127)}const jp=qs(/\d/),t5=qs(/[\dA-Fa-f]/),i5=qs(/[!-/:-@[-`{-~]/);function Ge(e){return e!==null&&e<-2}function qt(e){return e!==null&&(e<0||e===32)}function pt(e){return e===-2||e===-1||e===32}const Fu=qs(new RegExp("\\p{P}|\\p{S}","u")),ba=qs(/\s/);function qs(e){return t;function t(i){return i!==null&&i>-1&&e.test(String.fromCharCode(i))}}function 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 vt(e,t,i,s){const a=s?s-1:Number.POSITIVE_INFINITY;let o=0;return c;function c(p){return pt(p)?(e.enter(i),h(p)):t(p)}function h(p){return pt(p)&&o++c))return;const ne=t.events.length;let ue=ne,be,L;for(;ue--;)if(t.events[ue][0]==="exit"&&t.events[ue][1].type==="chunkFlow"){if(be){L=t.events[ue][1].end;break}be=!0}for(E(s),D=ne;DH;){const W=i[A];t.containerState=W[1],W[0].exit.call(t,e)}i.length=H}function O(){a.write([null]),o=void 0,a=void 0,t.containerState._closeFlow=void 0}}function l5(e,t,i){return vt(e,e.attempt(this.parser.constructs.document,t,i),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function pl(e){if(e===null||qt(e)||ba(e))return 1;if(Fu(e))return 2}function qu(e,t,i){const s=[];let a=-1;for(;++a1&&e[i][1].end.offset-e[i][1].start.offset>1?2:1;const x={...e[s][1].end},b={...e[i][1].start};Cv(x,-p),Cv(b,p),c={type:p>1?"strongSequence":"emphasisSequence",start:x,end:{...e[s][1].end}},h={type:p>1?"strongSequence":"emphasisSequence",start:{...e[i][1].start},end:b},o={type:p>1?"strongText":"emphasisText",start:{...e[s][1].end},end:{...e[i][1].start}},a={type:p>1?"strong":"emphasis",start:{...c.start},end:{...h.end}},e[s][1].end={...c.start},e[i][1].start={...h.end},f=[],e[s][1].end.offset-e[s][1].start.offset&&(f=or(f,[["enter",e[s][1],t],["exit",e[s][1],t]])),f=or(f,[["enter",a,t],["enter",c,t],["exit",c,t],["enter",o,t]]),f=or(f,qu(t.parser.constructs.insideSpan.null,e.slice(s+1,i),t)),f=or(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=or(f,[["enter",e[i][1],t],["exit",e[i][1],t]])):_=0,Yn(e,s-1,i-s+3,f),i=s+f.length-_-2;break}}for(i=-1;++i0&&pt(D)?vt(e,O,"linePrefix",o+1)(D):O(D)}function O(D){return D===null||Ge(D)?e.check(kv,N,A)(D):(e.enter("codeFlowValue"),H(D))}function H(D){return D===null||Ge(D)?(e.exit("codeFlowValue"),O(D)):(e.consume(D),H)}function A(D){return e.exit("codeFenced"),t(D)}function W(D,ne,ue){let be=0;return L;function L(U){return D.enter("lineEnding"),D.consume(U),D.exit("lineEnding"),re}function re(U){return D.enter("codeFencedFence"),pt(U)?vt(D,F,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(U):F(U)}function F(U){return U===h?(D.enter("codeFencedFenceSequence"),Y(U)):ue(U)}function Y(U){return U===h?(be++,D.consume(U),Y):be>=c?(D.exit("codeFencedFenceSequence"),pt(U)?vt(D,V,"whitespace")(U):V(U)):ue(U)}function V(U){return U===null||Ge(U)?(D.exit("codeFencedFence"),ne(U)):ue(U)}}}function b5(e,t,i){const s=this;return a;function a(c){return c===null?i(c):(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),o)}function o(c){return s.parser.lazy[s.now().line]?i(c):t(c)}}const bf={name:"codeIndented",tokenize:y5},v5={partial:!0,tokenize:S5};function y5(e,t,i){const s=this;return a;function a(f){return e.enter("codeIndented"),vt(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):Ge(f)?e.attempt(v5,c,p)(f):(e.enter("codeFlowValue"),h(f))}function h(f){return f===null||Ge(f)?(e.exit("codeFlowValue"),c(f)):(e.consume(f),h)}function p(f){return e.exit("codeIndented"),t(f)}}function S5(e,t,i){const s=this;return a;function a(c){return s.parser.lazy[s.now().line]?i(c):Ge(c)?(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),a):vt(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):Ge(c)?a(c):i(c)}}const w5={name:"codeText",previous:k5,resolve:C5,tokenize:E5};function C5(e){let t=e.length-4,i=3,s,a;if((e[i][1].type==="lineEnding"||e[i][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(s=i;++s=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return tthis.left.length?this.right.slice(this.right.length-s+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-s+this.left.length).reverse())}splice(t,i,s){const a=i||0;this.setCursor(Math.trunc(t));const o=this.right.splice(this.right.length-a,Number.POSITIVE_INFINITY);return s&&vo(this.left,s),o.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),vo(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),vo(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t=4?t(c):e.interrupt(s.parser.constructs.flow,i,t)(c)}}function Y0(e,t,i,s,a,o,c,h,p){const f=p||Number.POSITIVE_INFINITY;let _=0;return x;function x(E){return E===60?(e.enter(s),e.enter(a),e.enter(o),e.consume(E),e.exit(o),b):E===null||E===32||E===41||Mu(E)?i(E):(e.enter(s),e.enter(c),e.enter(h),e.enter("chunkString",{contentType:"string"}),N(E))}function b(E){return E===62?(e.enter(o),e.consume(E),e.exit(o),e.exit(a),e.exit(s),t):(e.enter(h),e.enter("chunkString",{contentType:"string"}),v(E))}function v(E){return E===62?(e.exit("chunkString"),e.exit(h),b(E)):E===null||E===60||Ge(E)?i(E):(e.consume(E),E===92?S:v)}function S(E){return E===60||E===62||E===92?(e.consume(E),v):v(E)}function N(E){return!_&&(E===null||E===41||qt(E))?(e.exit("chunkString"),e.exit(h),e.exit(c),e.exit(s),t(E)):_999||v===null||v===91||v===93&&!p||v===94&&!h&&"_hiddenFootnoteSupport"in c.parser.constructs?i(v):v===93?(e.exit(o),e.enter(a),e.consume(v),e.exit(a),e.exit(s),t):Ge(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||Ge(v)||h++>999?(e.exit("chunkString"),_(v)):(e.consume(v),p||(p=!pt(v)),v===92?b:x)}function b(v){return v===91||v===92||v===93?(e.consume(v),h++,x):x(v)}}function K0(e,t,i,s,a,o){let c;return h;function h(b){return b===34||b===39||b===40?(e.enter(s),e.enter(a),e.consume(b),e.exit(a),c=b===40?41:b,p):i(b)}function p(b){return b===c?(e.enter(a),e.consume(b),e.exit(a),e.exit(s),t):(e.enter(o),f(b))}function f(b){return b===c?(e.exit(o),p(c)):b===null?i(b):Ge(b)?(e.enter("lineEnding"),e.consume(b),e.exit("lineEnding"),vt(e,f,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),_(b))}function _(b){return b===c||b===null||Ge(b)?(e.exit("chunkString"),f(b)):(e.consume(b),b===92?x:_)}function x(b){return b===c||b===92?(e.consume(b),_):_(b)}}function Do(e,t){let i;return s;function s(a){return Ge(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),i=!0,s):pt(a)?vt(e,s,i?"linePrefix":"lineSuffix")(a):t(a)}}const B5={name:"definition",tokenize:O5},L5={partial:!0,tokenize:z5};function O5(e,t,i){const s=this;let a;return o;function o(v){return e.enter("definition"),c(v)}function c(v){return V0.call(s,e,h,i,"definitionLabel","definitionLabelMarker","definitionLabelString")(v)}function h(v){return a=_r(s.sliceSerialize(s.events[s.events.length-1][1]).slice(1,-1)),v===58?(e.enter("definitionMarker"),e.consume(v),e.exit("definitionMarker"),p):i(v)}function p(v){return qt(v)?Do(e,f)(v):f(v)}function f(v){return Y0(e,_,i,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(v)}function _(v){return e.attempt(L5,x,x)(v)}function x(v){return pt(v)?vt(e,b,"whitespace")(v):b(v)}function b(v){return v===null||Ge(v)?(e.exit("definition"),s.parser.defined.push(a),t(v)):i(v)}}function z5(e,t,i){return s;function s(h){return qt(h)?Do(e,a)(h):i(h)}function a(h){return K0(e,o,i,"definitionTitle","definitionTitleMarker","definitionTitleString")(h)}function o(h){return pt(h)?vt(e,c,"whitespace")(h):c(h)}function c(h){return h===null||Ge(h)?t(h):i(h)}}const P5={name:"hardBreakEscape",tokenize:I5};function I5(e,t,i){return s;function s(o){return e.enter("hardBreakEscape"),e.consume(o),a}function a(o){return Ge(o)?(e.exit("hardBreakEscape"),t(o)):i(o)}}const H5={name:"headingAtx",resolve:U5,tokenize:$5};function U5(e,t){let i=e.length-2,s=3,a,o;return e[s][1].type==="whitespace"&&(s+=2),i-2>s&&e[i][1].type==="whitespace"&&(i-=2),e[i][1].type==="atxHeadingSequence"&&(s===i-1||i-4>s&&e[i-2][1].type==="whitespace")&&(i-=s+1===i?2:4),i>s&&(a={type:"atxHeadingText",start:e[s][1].start,end:e[i][1].end},o={type:"chunkText",start:e[s][1].start,end:e[i][1].end,contentType:"text"},Yn(e,s,i-s+1,[["enter",a,t],["enter",o,t],["exit",o,t],["exit",a,t]])),e}function $5(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||Ge(_)?(e.exit("atxHeading"),t(_)):pt(_)?vt(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 F5=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],Nv=["pre","script","style","textarea"],q5={concrete:!0,name:"htmlFlow",resolveTo:Y5,tokenize:V5},W5={partial:!0,tokenize:X5},G5={partial:!0,tokenize:K5};function Y5(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 V5(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,N):k===63?(e.consume(k),a=3,s.interrupt?t:j):bn(k)?(e.consume(k),c=String.fromCharCode(k),B):i(k)}function b(k){return k===45?(e.consume(k),a=2,v):k===91?(e.consume(k),a=5,h=0,S):bn(k)?(e.consume(k),a=4,s.interrupt?t:j):i(k)}function v(k){return k===45?(e.consume(k),s.interrupt?t:j):i(k)}function S(k){const K="CDATA[";return k===K.charCodeAt(h++)?(e.consume(k),h===K.length?s.interrupt?t:F:S):i(k)}function N(k){return bn(k)?(e.consume(k),c=String.fromCharCode(k),B):i(k)}function B(k){if(k===null||k===47||k===62||qt(k)){const K=k===47,ae=c.toLowerCase();return!K&&!o&&Nv.includes(ae)?(a=1,s.interrupt?t(k):F(k)):F5.includes(c.toLowerCase())?(a=6,K?(e.consume(k),E):s.interrupt?t(k):F(k)):(a=7,s.interrupt&&!s.parser.lazy[s.now().line]?i(k):o?O(k):H(k))}return k===45||un(k)?(e.consume(k),c+=String.fromCharCode(k),B):i(k)}function E(k){return k===62?(e.consume(k),s.interrupt?t:F):i(k)}function O(k){return pt(k)?(e.consume(k),O):L(k)}function H(k){return k===47?(e.consume(k),L):k===58||k===95||bn(k)?(e.consume(k),A):pt(k)?(e.consume(k),H):L(k)}function A(k){return k===45||k===46||k===58||k===95||un(k)?(e.consume(k),A):W(k)}function W(k){return k===61?(e.consume(k),D):pt(k)?(e.consume(k),W):H(k)}function D(k){return k===null||k===60||k===61||k===62||k===96?i(k):k===34||k===39?(e.consume(k),p=k,ne):pt(k)?(e.consume(k),D):ue(k)}function ne(k){return k===p?(e.consume(k),p=null,be):k===null||Ge(k)?i(k):(e.consume(k),ne)}function ue(k){return k===null||k===34||k===39||k===47||k===60||k===61||k===62||k===96||qt(k)?W(k):(e.consume(k),ue)}function be(k){return k===47||k===62||pt(k)?H(k):i(k)}function L(k){return k===62?(e.consume(k),re):i(k)}function re(k){return k===null||Ge(k)?F(k):pt(k)?(e.consume(k),re):i(k)}function F(k){return k===45&&a===2?(e.consume(k),T):k===60&&a===1?(e.consume(k),P):k===62&&a===4?(e.consume(k),R):k===63&&a===3?(e.consume(k),j):k===93&&a===5?(e.consume(k),xe):Ge(k)&&(a===6||a===7)?(e.exit("htmlFlowData"),e.check(W5,Z,Y)(k)):k===null||Ge(k)?(e.exit("htmlFlowData"),Y(k)):(e.consume(k),F)}function Y(k){return e.check(G5,V,Z)(k)}function V(k){return e.enter("lineEnding"),e.consume(k),e.exit("lineEnding"),U}function U(k){return k===null||Ge(k)?Y(k):(e.enter("htmlFlowData"),F(k))}function T(k){return k===45?(e.consume(k),j):F(k)}function P(k){return k===47?(e.consume(k),c="",q):F(k)}function q(k){if(k===62){const K=c.toLowerCase();return Nv.includes(K)?(e.consume(k),R):F(k)}return bn(k)&&c.length<8?(e.consume(k),c+=String.fromCharCode(k),q):F(k)}function xe(k){return k===93?(e.consume(k),j):F(k)}function j(k){return k===62?(e.consume(k),R):k===45&&a===2?(e.consume(k),j):F(k)}function R(k){return k===null||Ge(k)?(e.exit("htmlFlowData"),Z(k)):(e.consume(k),R)}function Z(k){return e.exit("htmlFlow"),t(k)}}function K5(e,t,i){const s=this;return a;function a(c){return Ge(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 X5(e,t,i){return s;function s(a){return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),e.attempt(Yo,t,i)}}const Z5={name:"htmlText",tokenize:Q5};function Q5(e,t,i){const s=this;let a,o,c;return h;function h(j){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(j),p}function p(j){return j===33?(e.consume(j),f):j===47?(e.consume(j),W):j===63?(e.consume(j),H):bn(j)?(e.consume(j),ue):i(j)}function f(j){return j===45?(e.consume(j),_):j===91?(e.consume(j),o=0,S):bn(j)?(e.consume(j),O):i(j)}function _(j){return j===45?(e.consume(j),v):i(j)}function x(j){return j===null?i(j):j===45?(e.consume(j),b):Ge(j)?(c=x,P(j)):(e.consume(j),x)}function b(j){return j===45?(e.consume(j),v):x(j)}function v(j){return j===62?T(j):j===45?b(j):x(j)}function S(j){const R="CDATA[";return j===R.charCodeAt(o++)?(e.consume(j),o===R.length?N:S):i(j)}function N(j){return j===null?i(j):j===93?(e.consume(j),B):Ge(j)?(c=N,P(j)):(e.consume(j),N)}function B(j){return j===93?(e.consume(j),E):N(j)}function E(j){return j===62?T(j):j===93?(e.consume(j),E):N(j)}function O(j){return j===null||j===62?T(j):Ge(j)?(c=O,P(j)):(e.consume(j),O)}function H(j){return j===null?i(j):j===63?(e.consume(j),A):Ge(j)?(c=H,P(j)):(e.consume(j),H)}function A(j){return j===62?T(j):H(j)}function W(j){return bn(j)?(e.consume(j),D):i(j)}function D(j){return j===45||un(j)?(e.consume(j),D):ne(j)}function ne(j){return Ge(j)?(c=ne,P(j)):pt(j)?(e.consume(j),ne):T(j)}function ue(j){return j===45||un(j)?(e.consume(j),ue):j===47||j===62||qt(j)?be(j):i(j)}function be(j){return j===47?(e.consume(j),T):j===58||j===95||bn(j)?(e.consume(j),L):Ge(j)?(c=be,P(j)):pt(j)?(e.consume(j),be):T(j)}function L(j){return j===45||j===46||j===58||j===95||un(j)?(e.consume(j),L):re(j)}function re(j){return j===61?(e.consume(j),F):Ge(j)?(c=re,P(j)):pt(j)?(e.consume(j),re):be(j)}function F(j){return j===null||j===60||j===61||j===62||j===96?i(j):j===34||j===39?(e.consume(j),a=j,Y):Ge(j)?(c=F,P(j)):pt(j)?(e.consume(j),F):(e.consume(j),V)}function Y(j){return j===a?(e.consume(j),a=void 0,U):j===null?i(j):Ge(j)?(c=Y,P(j)):(e.consume(j),Y)}function V(j){return j===null||j===34||j===39||j===60||j===61||j===96?i(j):j===47||j===62||qt(j)?be(j):(e.consume(j),V)}function U(j){return j===47||j===62||qt(j)?be(j):i(j)}function T(j){return j===62?(e.consume(j),e.exit("htmlTextData"),e.exit("htmlText"),t):i(j)}function P(j){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(j),e.exit("lineEnding"),q}function q(j){return pt(j)?vt(e,xe,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(j):xe(j)}function xe(j){return e.enter("htmlTextData"),c(j)}}const cm={name:"labelEnd",resolveAll:ij,resolveTo:nj,tokenize:rj},J5={tokenize:sj},ej={tokenize:aj},tj={tokenize:lj};function ij(e){let t=-1;const i=[];for(;++t=3&&(f===null||Ge(f))?(e.exit("thematicBreak"),t(f)):i(f)}function p(f){return f===a?(e.consume(f),s++,p):(e.exit("thematicBreakSequence"),pt(f)?vt(e,h,"whitespace")(f):h(f))}}const Dn={continuation:{tokenize:xj},exit:bj,name:"list",tokenize:gj},pj={partial:!0,tokenize:vj},mj={partial:!0,tokenize:_j};function gj(e,t,i){const s=this,a=s.events[s.events.length-1];let o=a&&a[1].type==="linePrefix"?a[2].sliceSerialize(a[1],!0).length:0,c=0;return h;function h(v){const S=s.containerState.type||(v===42||v===43||v===45?"listUnordered":"listOrdered");if(S==="listUnordered"?!s.containerState.marker||v===s.containerState.marker:jp(v)){if(s.containerState.type||(s.containerState.type=S,e.enter(S,{_container:!0})),S==="listUnordered")return e.enter("listItemPrefix"),v===42||v===45?e.check(wu,i,f)(v):f(v);if(!s.interrupt||v===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),p(v)}return i(v)}function p(v){return jp(v)&&++c<10?(e.consume(v),p):(!s.interrupt||c<2)&&(s.containerState.marker?v===s.containerState.marker:v===41||v===46)?(e.exit("listItemValue"),f(v)):i(v)}function f(v){return e.enter("listItemMarker"),e.consume(v),e.exit("listItemMarker"),s.containerState.marker=s.containerState.marker||v,e.check(Yo,s.interrupt?i:_,e.attempt(pj,b,x))}function _(v){return s.containerState.initialBlankLine=!0,o++,b(v)}function x(v){return pt(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 xj(e,t,i){const s=this;return s.containerState._closeFlow=void 0,e.check(Yo,a,o);function a(h){return s.containerState.furtherBlankLines=s.containerState.furtherBlankLines||s.containerState.initialBlankLine,vt(e,t,"listItemIndent",s.containerState.size+1)(h)}function o(h){return s.containerState.furtherBlankLines||!pt(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(mj,t,c)(h))}function c(h){return s.containerState._closeFlow=!0,s.interrupt=void 0,vt(e,e.attempt(Dn,t,i),"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(h)}}function _j(e,t,i){const s=this;return vt(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 bj(e){e.exit(this.containerState.type)}function vj(e,t,i){const s=this;return vt(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!pt(o)&&c&&c[1].type==="listItemPrefixWhitespace"?t(o):i(o)}}const jv={name:"setextUnderline",resolveTo:yj,tokenize:Sj};function yj(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 Sj(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"),pt(f)?vt(e,p,"lineSuffix")(f):p(f))}function p(f){return f===null||Ge(f)?(e.exit("setextHeadingLine"),t(f)):i(f)}}const wj={tokenize:Cj};function Cj(e){const t=this,i=e.attempt(Yo,s,e.attempt(this.parser.constructs.flowInitial,a,vt(e,e.attempt(this.parser.constructs.flow,a,e.attempt(T5,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 kj={resolveAll:Z0()},Ej=X0("string"),Nj=X0("text");function X0(e){return{resolveAll:Z0(e==="text"?jj: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 Uj(e,t){let i=-1;const s=[];let a;for(;++i0){const Gt=Me.tokenStack[Me.tokenStack.length-1];(Gt[1]||Av).call(Me,void 0,Gt[0])}for(be.position={start:zs(ee.length>0?ee[0][1].start:{line:1,column:1,offset:0}),end:zs(ee.length>0?ee[ee.length-2][1].end:{line:1,column:1,offset:0})},Xe=-1;++Xe0&&(s.className=["language-"+a[0]]);let o={type:"element",tagName:"code",properties:s,children:[{type:"text",value:i}]};return t.meta&&(o.data={meta:t.meta}),e.patch(t,o),o=e.applyData(t,o),o={type:"element",tagName:"pre",properties:{},children:[o]},e.patch(t,o),o}function eT(e,t){const i={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function tT(e,t){const i={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function iT(e,t){const i=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=String(t.identifier).toUpperCase(),a=bl(s.toLowerCase()),o=e.footnoteOrder.indexOf(s);let c,h=e.footnoteCounts.get(s);h===void 0?(h=0,e.footnoteOrder.push(s),c=e.footnoteOrder.length):c=o+1,h+=1,e.footnoteCounts.set(s,h);const p={type:"element",tagName:"a",properties:{href:"#"+i+"fn-"+a,id:i+"fnref-"+a+(h>1?"-"+h:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(c)}]};e.patch(t,p);const f={type:"element",tagName:"sup",properties:{},children:[p]};return e.patch(t,f),e.applyData(t,f)}function nT(e,t){const i={type:"element",tagName:"h"+t.depth,properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function rT(e,t){if(e.options.allowDangerousHtml){const i={type:"raw",value:t.value};return e.patch(t,i),e.applyData(t,i)}}function eS(e,t){const i=t.referenceType;let s="]";if(i==="collapsed"?s+="[]":i==="full"&&(s+="["+(t.label||t.identifier)+"]"),t.type==="imageReference")return[{type:"text",value:"!["+t.alt+s}];const a=e.all(t),o=a[0];o&&o.type==="text"?o.value="["+o.value:a.unshift({type:"text",value:"["});const c=a[a.length-1];return c&&c.type==="text"?c.value+=s:a.push({type:"text",value:s}),a}function sT(e,t){const i=String(t.identifier).toUpperCase(),s=e.definitionById.get(i);if(!s)return eS(e,t);const a={src:bl(s.url||""),alt:t.alt};s.title!==null&&s.title!==void 0&&(a.title=s.title);const o={type:"element",tagName:"img",properties:a,children:[]};return e.patch(t,o),e.applyData(t,o)}function aT(e,t){const i={src:bl(t.url)};t.alt!==null&&t.alt!==void 0&&(i.alt=t.alt),t.title!==null&&t.title!==void 0&&(i.title=t.title);const s={type:"element",tagName:"img",properties:i,children:[]};return e.patch(t,s),e.applyData(t,s)}function lT(e,t){const i={type:"text",value:t.value.replace(/\r?\n|\r/g," ")};e.patch(t,i);const s={type:"element",tagName:"code",properties:{},children:[i]};return e.patch(t,s),e.applyData(t,s)}function oT(e,t){const i=String(t.identifier).toUpperCase(),s=e.definitionById.get(i);if(!s)return eS(e,t);const a={href:bl(s.url||"")};s.title!==null&&s.title!==void 0&&(a.title=s.title);const o={type:"element",tagName:"a",properties:a,children:e.all(t)};return e.patch(t,o),e.applyData(t,o)}function cT(e,t){const i={href:bl(t.url)};t.title!==null&&t.title!==void 0&&(i.title=t.title);const s={type:"element",tagName:"a",properties:i,children:e.all(t)};return e.patch(t,s),e.applyData(t,s)}function uT(e,t,i){const s=e.all(t),a=i?hT(i):tS(t),o={},c=[];if(typeof t.checked=="boolean"){const _=s[0];let x;_&&_.type==="element"&&_.tagName==="p"?x=_:(x={type:"element",tagName:"p",properties:{},children:[]},s.unshift(x)),x.children.length>0&&x.children.unshift({type:"text",value:" "}),x.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:t.checked,disabled:!0},children:[]}),o.className=["task-list-item"]}let h=-1;for(;++h0){const Gt=Me.tokenStack[Me.tokenStack.length-1];(Gt[1]||Av).call(Me,void 0,Gt[0])}for(_e.position={start:Ps(ee.length>0?ee[0][1].start:{line:1,column:1,offset:0}),end:Ps(ee.length>0?ee[ee.length-2][1].end:{line:1,column:1,offset:0})},Ze=-1;++Ze0&&(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 tT(e,t){const i={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function iT(e,t){const i={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function nT(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 rT(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 sT(e,t){if(e.options.allowDangerousHtml){const i={type:"raw",value:t.value};return e.patch(t,i),e.applyData(t,i)}}function eS(e,t){const i=t.referenceType;let s="]";if(i==="collapsed"?s+="[]":i==="full"&&(s+="["+(t.label||t.identifier)+"]"),t.type==="imageReference")return[{type:"text",value:"!["+t.alt+s}];const a=e.all(t),o=a[0];o&&o.type==="text"?o.value="["+o.value:a.unshift({type:"text",value:"["});const c=a[a.length-1];return c&&c.type==="text"?c.value+=s:a.push({type:"text",value:s}),a}function aT(e,t){const i=String(t.identifier).toUpperCase(),s=e.definitionById.get(i);if(!s)return eS(e,t);const a={src:bl(s.url||""),alt:t.alt};s.title!==null&&s.title!==void 0&&(a.title=s.title);const o={type:"element",tagName:"img",properties:a,children:[]};return e.patch(t,o),e.applyData(t,o)}function lT(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 oT(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 cT(e,t){const i=String(t.identifier).toUpperCase(),s=e.definitionById.get(i);if(!s)return eS(e,t);const a={href:bl(s.url||"")};s.title!==null&&s.title!==void 0&&(a.title=s.title);const o={type:"element",tagName:"a",properties:a,children:e.all(t)};return e.patch(t,o),e.applyData(t,o)}function uT(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 hT(e,t,i){const s=e.all(t),a=i?dT(i):tS(t),o={},c=[];if(typeof t.checked=="boolean"){const _=s[0];let x;_&&_.type==="element"&&_.tagName==="p"?x=_:(x={type:"element",tagName:"p",properties:{},children:[]},s.unshift(x)),x.children.length>0&&x.children.unshift({type:"text",value:" "}),x.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:t.checked,disabled:!0},children:[]}),o.className=["task-list-item"]}let h=-1;for(;++h1}function dT(e,t){const i={},s=e.all(t);let a=-1;for(typeof t.start=="number"&&t.start!==1&&(i.start=t.start);++a0){const c={type:"element",tagName:"tbody",properties:{},children:e.wrap(i,!0)},h=nm(t.children[1]),p=M0(t.children[t.children.length-1]);h&&p&&(c.position={start:h,end:p}),a.push(c)}const o={type:"element",tagName:"table",properties:{},children:e.wrap(a,!0)};return e.patch(t,o),e.applyData(t,o)}function xT(e,t,i){const s=i?i.children:void 0,o=(s?s.indexOf(t):1)===0?"th":"td",c=i&&i.type==="table"?i.align:void 0,h=c?c.length:t.children.length;let p=-1;const f=[];for(;++p0,!0),s[0]),a=s.index+s[0].length,s=i.exec(t);return o.push(Mv(t.slice(a),a>0,!1)),o.join("")}function Mv(e,t,i){let s=0,a=e.length;if(t){let o=e.codePointAt(s);for(;o===Rv||o===Dv;)s++,o=e.codePointAt(s)}if(i){let o=e.codePointAt(a-1);for(;o===Rv||o===Dv;)a--,o=e.codePointAt(a-1)}return a>s?e.slice(s,a):""}function vT(e,t){const i={type:"text",value:bT(String(t.value))};return e.patch(t,i),e.applyData(t,i)}function yT(e,t){const i={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,i),e.applyData(t,i)}const ST={blockquote:Zj,break:Qj,code:Jj,delete:eT,emphasis:tT,footnoteReference:iT,heading:nT,html:rT,imageReference:sT,image:aT,inlineCode:lT,linkReference:oT,link:cT,listItem:uT,list:dT,paragraph:fT,root:pT,strong:mT,table:gT,tableCell:_T,tableRow:xT,text:vT,thematicBreak:yT,toml:ou,yaml:ou,definition:ou,footnoteDefinition:ou};function ou(){}const iS=-1,Wu=0,Mo=1,Bu=2,um=3,hm=4,dm=5,fm=6,nS=7,rS=8,Bv=typeof self=="object"?self:globalThis,wT=(e,t)=>{const i=(a,o)=>(e.set(o,a),a),s=a=>{if(e.has(a))return e.get(a);const[o,c]=t[a];switch(o){case Wu:case iS:return i(c,a);case Mo:{const h=i([],a);for(const p of c)h.push(s(p));return h}case Bu:{const h=i({},a);for(const[p,f]of c)h[s(p)]=s(f);return h}case um:return i(new Date(c),a);case hm:{const{source:h,flags:p}=c;return i(new RegExp(h,p),a)}case dm:{const h=i(new Map,a);for(const[p,f]of c)h.set(s(p),s(f));return h}case fm:{const h=i(new Set,a);for(const p of c)h.add(s(p));return h}case nS:{const{name:h,message:p}=c;return i(new Bv[h](p),a)}case rS:return i(BigInt(c),a);case"BigInt":return i(Object(BigInt(c)),a);case"ArrayBuffer":return i(new Uint8Array(c).buffer,c);case"DataView":{const{buffer:h}=new Uint8Array(c);return i(new DataView(h),c)}}return i(new Bv[o](c),a)};return s},Lv=e=>wT(new Map,e)(0),al="",{toString:CT}={},{keys:kT}=Object,yo=e=>{const t=typeof e;if(t!=="object"||!e)return[Wu,t];const i=CT.call(e).slice(8,-1);switch(i){case"Array":return[Mo,al];case"Object":return[Bu,al];case"Date":return[um,al];case"RegExp":return[hm,al];case"Map":return[dm,al];case"Set":return[fm,al];case"DataView":return[Mo,i]}return i.includes("Array")?[Mo,i]:i.includes("Error")?[nS,i]:[Bu,i]},cu=([e,t])=>e===Wu&&(t==="function"||t==="symbol"),ET=(e,t,i,s)=>{const a=(c,h)=>{const p=s.push(c)-1;return i.set(h,p),p},o=c=>{if(i.has(c))return i.get(c);let[h,p]=yo(c);switch(h){case Wu:{let _=c;switch(p){case"bigint":h=rS,_=c.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+p);_=null;break;case"undefined":return a([iS],c)}return a([h,_],c)}case Mo:{if(p){let b=c;return p==="DataView"?b=new Uint8Array(c.buffer):p==="ArrayBuffer"&&(b=new Uint8Array(c)),a([p,[...b]],c)}const _=[],x=a([h,_],c);for(const b of c)_.push(o(b));return x}case Bu:{if(p)switch(p){case"BigInt":return a([p,c.toString()],c);case"Boolean":case"Number":case"String":return a([p,c.valueOf()],c)}if(t&&"toJSON"in c)return o(c.toJSON());const _=[],x=a([h,_],c);for(const b of kT(c))(e||!cu(yo(c[b])))&&_.push([o(b),o(c[b])]);return x}case um:return a([h,c.toISOString()],c);case hm:{const{source:_,flags:x}=c;return a([h,{source:_,flags:x}],c)}case dm:{const _=[],x=a([h,_],c);for(const[b,v]of c)(e||!(cu(yo(b))||cu(yo(v))))&&_.push([o(b),o(v)]);return x}case fm:{const _=[],x=a([h,_],c);for(const b of c)(e||!cu(yo(b)))&&_.push(o(b));return x}}const{message:f}=c;return a([h,{name:p,message:f}],c)};return o},Ov=(e,{json:t,lossy:i}={})=>{const s=[];return ET(!(t||i),!!t,new Map,s)(e),s},Io=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?Lv(Ov(e,t)):structuredClone(e):(e,t)=>Lv(Ov(e,t));function NT(e,t){const i=[{type:"text",value:"↩"}];return t>1&&i.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(t)}]}),i}function jT(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function TT(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",i=e.options.footnoteBackContent||NT,s=e.options.footnoteBackLabel||jT,a=e.options.footnoteLabel||"Footnotes",o=e.options.footnoteLabelTagName||"h2",c=e.options.footnoteLabelProperties||{className:["sr-only"]},h=[];let p=-1;for(;++p0&&S.push({type:"text",value:" "});let L=typeof i=="string"?i:i(p,v);typeof L=="string"&&(L={type:"text",value:L}),S.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+b+(v>1?"-"+v:""),dataFootnoteBackref:"",ariaLabel:typeof s=="string"?s:s(p,v),className:["data-footnote-backref"]},children:Array.isArray(L)?L:[L]})}const M=_[_.length-1];if(M&&M.type==="element"&&M.tagName==="p"){const L=M.children[M.children.length-1];L&&L.type==="text"?L.value+=" ":M.children.push({type:"text",value:" "}),M.children.push(...S)}else _.push(...S);const E={type:"element",tagName:"li",properties:{id:t+"fn-"+b},children:e.wrap(_,!0)};e.patch(f,E),h.push(E)}if(h.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...Io(c),id:"footnote-label"},children:[{type:"text",value:a}]},{type:"text",value:` +`});const f={type:"element",tagName:"li",properties:o,children:c};return e.patch(t,f),e.applyData(t,f)}function dT(e){let t=!1;if(e.type==="list"){t=e.spread||!1;const i=e.children;let s=-1;for(;!t&&++s1}function fT(e,t){const i={},s=e.all(t);let a=-1;for(typeof t.start=="number"&&t.start!==1&&(i.start=t.start);++a0){const c={type:"element",tagName:"tbody",properties:{},children:e.wrap(i,!0)},h=nm(t.children[1]),p=M0(t.children[t.children.length-1]);h&&p&&(c.position={start:h,end:p}),a.push(c)}const o={type:"element",tagName:"table",properties:{},children:e.wrap(a,!0)};return e.patch(t,o),e.applyData(t,o)}function _T(e,t,i){const s=i?i.children:void 0,o=(s?s.indexOf(t):1)===0?"th":"td",c=i&&i.type==="table"?i.align:void 0,h=c?c.length:t.children.length;let p=-1;const f=[];for(;++p0,!0),s[0]),a=s.index+s[0].length,s=i.exec(t);return o.push(Mv(t.slice(a),a>0,!1)),o.join("")}function Mv(e,t,i){let s=0,a=e.length;if(t){let o=e.codePointAt(s);for(;o===Rv||o===Dv;)s++,o=e.codePointAt(s)}if(i){let o=e.codePointAt(a-1);for(;o===Rv||o===Dv;)a--,o=e.codePointAt(a-1)}return a>s?e.slice(s,a):""}function yT(e,t){const i={type:"text",value:vT(String(t.value))};return e.patch(t,i),e.applyData(t,i)}function ST(e,t){const i={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,i),e.applyData(t,i)}const wT={blockquote:Qj,break:Jj,code:eT,delete:tT,emphasis:iT,footnoteReference:nT,heading:rT,html:sT,imageReference:aT,image:lT,inlineCode:oT,linkReference:cT,link:uT,listItem:hT,list:fT,paragraph:pT,root:mT,strong:gT,table:xT,tableCell:bT,tableRow:_T,text:yT,thematicBreak:ST,toml:ou,yaml:ou,definition:ou,footnoteDefinition:ou};function ou(){}const iS=-1,Wu=0,Mo=1,Bu=2,um=3,hm=4,dm=5,fm=6,nS=7,rS=8,Bv=typeof self=="object"?self:globalThis,CT=(e,t)=>{const i=(a,o)=>(e.set(o,a),a),s=a=>{if(e.has(a))return e.get(a);const[o,c]=t[a];switch(o){case Wu:case iS:return i(c,a);case Mo:{const h=i([],a);for(const p of c)h.push(s(p));return h}case Bu:{const h=i({},a);for(const[p,f]of c)h[s(p)]=s(f);return h}case um:return i(new Date(c),a);case hm:{const{source:h,flags:p}=c;return i(new RegExp(h,p),a)}case dm:{const h=i(new Map,a);for(const[p,f]of c)h.set(s(p),s(f));return h}case fm:{const h=i(new Set,a);for(const p of c)h.add(s(p));return h}case nS:{const{name:h,message:p}=c;return i(new Bv[h](p),a)}case rS:return i(BigInt(c),a);case"BigInt":return i(Object(BigInt(c)),a);case"ArrayBuffer":return i(new Uint8Array(c).buffer,c);case"DataView":{const{buffer:h}=new Uint8Array(c);return i(new DataView(h),c)}}return i(new Bv[o](c),a)};return s},Lv=e=>CT(new Map,e)(0),al="",{toString:kT}={},{keys:ET}=Object,yo=e=>{const t=typeof e;if(t!=="object"||!e)return[Wu,t];const i=kT.call(e).slice(8,-1);switch(i){case"Array":return[Mo,al];case"Object":return[Bu,al];case"Date":return[um,al];case"RegExp":return[hm,al];case"Map":return[dm,al];case"Set":return[fm,al];case"DataView":return[Mo,i]}return i.includes("Array")?[Mo,i]:i.includes("Error")?[nS,i]:[Bu,i]},cu=([e,t])=>e===Wu&&(t==="function"||t==="symbol"),NT=(e,t,i,s)=>{const a=(c,h)=>{const p=s.push(c)-1;return i.set(h,p),p},o=c=>{if(i.has(c))return i.get(c);let[h,p]=yo(c);switch(h){case Wu:{let _=c;switch(p){case"bigint":h=rS,_=c.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+p);_=null;break;case"undefined":return a([iS],c)}return a([h,_],c)}case Mo:{if(p){let b=c;return p==="DataView"?b=new Uint8Array(c.buffer):p==="ArrayBuffer"&&(b=new Uint8Array(c)),a([p,[...b]],c)}const _=[],x=a([h,_],c);for(const b of c)_.push(o(b));return x}case Bu:{if(p)switch(p){case"BigInt":return a([p,c.toString()],c);case"Boolean":case"Number":case"String":return a([p,c.valueOf()],c)}if(t&&"toJSON"in c)return o(c.toJSON());const _=[],x=a([h,_],c);for(const b of ET(c))(e||!cu(yo(c[b])))&&_.push([o(b),o(c[b])]);return x}case um:return a([h,c.toISOString()],c);case hm:{const{source:_,flags:x}=c;return a([h,{source:_,flags:x}],c)}case dm:{const _=[],x=a([h,_],c);for(const[b,v]of c)(e||!(cu(yo(b))||cu(yo(v))))&&_.push([o(b),o(v)]);return x}case fm:{const _=[],x=a([h,_],c);for(const b of c)(e||!cu(yo(b)))&&_.push(o(b));return x}}const{message:f}=c;return a([h,{name:p,message:f}],c)};return o},Ov=(e,{json:t,lossy:i}={})=>{const s=[];return NT(!(t||i),!!t,new Map,s)(e),s},Io=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?Lv(Ov(e,t)):structuredClone(e):(e,t)=>Lv(Ov(e,t));function jT(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 TT(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function AT(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",i=e.options.footnoteBackContent||jT,s=e.options.footnoteBackLabel||TT,a=e.options.footnoteLabel||"Footnotes",o=e.options.footnoteLabelTagName||"h2",c=e.options.footnoteLabelProperties||{className:["sr-only"]},h=[];let p=-1;for(;++p0&&S.push({type:"text",value:" "});let O=typeof i=="string"?i:i(p,v);typeof O=="string"&&(O={type:"text",value:O}),S.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+b+(v>1?"-"+v:""),dataFootnoteBackref:"",ariaLabel:typeof s=="string"?s:s(p,v),className:["data-footnote-backref"]},children:Array.isArray(O)?O:[O]})}const B=_[_.length-1];if(B&&B.type==="element"&&B.tagName==="p"){const O=B.children[B.children.length-1];O&&O.type==="text"?O.value+=" ":B.children.push({type:"text",value:" "}),B.children.push(...S)}else _.push(...S);const E={type:"element",tagName:"li",properties:{id:t+"fn-"+b},children:e.wrap(_,!0)};e.patch(f,E),h.push(E)}if(h.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...Io(c),id:"footnote-label"},children:[{type:"text",value:a}]},{type:"text",value:` `},{type:"element",tagName:"ol",properties:{},children:e.wrap(h,!0)},{type:"text",value:` -`}]}}const Gu=(function(e){if(e==null)return MT;if(typeof e=="function")return Yu(e);if(typeof e=="object")return Array.isArray(e)?AT(e):RT(e);if(typeof e=="string")return DT(e);throw new Error("Expected function, string, or object as test")});function AT(e){const t=[];let i=-1;for(;++i":""))+")"})}return b;function b(){let v=sS,S,N,M;if((!t||o(p,f,_[_.length-1]||void 0))&&(v=zT(i(p,_)),v[0]===Ap))return v;if("children"in p&&p.children){const E=p;if(E.children&&v[0]!==OT)for(N=(s?E.children.length:-1)+c,M=_.concat(E);N>-1&&N":""))+")"})}return b;function b(){let v=sS,S,N,B;if((!t||o(p,f,_[_.length-1]||void 0))&&(v=PT(i(p,_)),v[0]===Ap))return v;if("children"in p&&p.children){const E=p;if(E.children&&v[0]!==zT)for(N=(s?E.children.length:-1)+c,B=_.concat(E);N>-1&&N0&&i.push({type:"text",value:` -`}),i}function zv(e){let t=0,i=e.charCodeAt(t);for(;i===9||i===32;)t++,i=e.charCodeAt(t);return e.slice(t)}function Pv(e,t){const i=IT(e,t),s=i.one(e,void 0),a=TT(i),o=Array.isArray(s)?{type:"root",children:s}:s||{type:"root",children:[]};return a&&o.children.push({type:"text",value:` -`},a),o}function qT(e,t){return e&&"run"in e?async function(i,s){const a=Pv(i,{file:s,...t});await e.run(a,s)}:function(i,s){return Pv(i,{file:s,...e||t})}}function Iv(e){if(e)throw e}var yf,Hv;function WT(){if(Hv)return yf;Hv=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,i=Object.defineProperty,s=Object.getOwnPropertyDescriptor,a=function(f){return typeof Array.isArray=="function"?Array.isArray(f):t.call(f)==="[object Array]"},o=function(f){if(!f||t.call(f)!=="[object Object]")return!1;var _=e.call(f,"constructor"),x=f.constructor&&f.constructor.prototype&&e.call(f.constructor.prototype,"isPrototypeOf");if(f.constructor&&!_&&!x)return!1;var b;for(b in f);return typeof b>"u"||e.call(f,b)},c=function(f,_){i&&_.name==="__proto__"?i(f,_.name,{enumerable:!0,configurable:!0,value:_.newValue,writable:!0}):f[_.name]=_.newValue},h=function(f,_){if(_==="__proto__")if(e.call(f,_)){if(s)return s(f,_).value}else return;return f[_]};return yf=function p(){var f,_,x,b,v,S,N=arguments[0],M=1,E=arguments.length,L=!1;for(typeof N=="boolean"&&(L=N,N=arguments[1]||{},M=2),(N==null||typeof N!="object"&&typeof N!="function")&&(N={});Mc.length;let p;h&&c.push(a);try{p=e.apply(this,c)}catch(f){const _=f;if(h&&i)throw _;return a(_)}h||(p&&p.then&&typeof p.then=="function"?p.then(o,a):p instanceof Error?a(p):o(p))}function a(c,...h){i||(i=!0,t(c,...h))}function o(c){a(null,c)}}const jr={basename:KT,dirname:XT,extname:ZT,join:QT,sep:"/"};function KT(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');Vo(e);let i=0,s=-1,a=e.length,o;if(t===void 0||t.length===0||t.length>e.length){for(;a--;)if(e.codePointAt(a)===47){if(o){i=a+1;break}}else s<0&&(o=!0,s=a+1);return s<0?"":e.slice(i,s)}if(t===e)return"";let c=-1,h=t.length-1;for(;a--;)if(e.codePointAt(a)===47){if(o){i=a+1;break}}else c<0&&(o=!0,c=a+1),h>-1&&(e.codePointAt(a)===t.codePointAt(h--)?h<0&&(s=a):(h=-1,s=c));return i===s?s=c:s<0&&(s=e.length),e.slice(i,s)}function XT(e){if(Vo(e),e.length===0)return".";let t=-1,i=e.length,s;for(;--i;)if(e.codePointAt(i)===47){if(s){t=i;break}}else s||(s=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function ZT(e){Vo(e);let t=e.length,i=-1,s=0,a=-1,o=0,c;for(;t--;){const h=e.codePointAt(t);if(h===47){if(c){s=t+1;break}continue}i<0&&(c=!0,i=t+1),h===46?a<0?a=t:o!==1&&(o=1):a>-1&&(o=-1)}return a<0||i<0||o===0||o===1&&a===i-1&&a===s+1?"":e.slice(a,i)}function QT(...e){let t=-1,i;for(;++t0&&e.codePointAt(e.length-1)===47&&(i+="/"),t?"/"+i:i}function eA(e,t){let i="",s=0,a=-1,o=0,c=-1,h,p;for(;++c<=e.length;){if(c2){if(p=i.lastIndexOf("/"),p!==i.length-1){p<0?(i="",s=0):(i=i.slice(0,p),s=i.length-1-i.lastIndexOf("/")),a=c,o=0;continue}}else if(i.length>0){i="",s=0,a=c,o=0;continue}}t&&(i=i.length>0?i+"/..":"..",s=2)}else i.length>0?i+="/"+e.slice(a+1,c):i=e.slice(a+1,c),s=c-a-1;a=c,o=0}else h===46&&o>-1?o++:o=-1}return i}function Vo(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const tA={cwd:iA};function iA(){return"/"}function Mp(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function nA(e){if(typeof e=="string")e=new URL(e);else if(!Mp(e)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(e.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return rA(e)}function rA(e){if(e.hostname!==""){const s=new TypeError('File URL host must be "localhost" or empty on darwin');throw s.code="ERR_INVALID_FILE_URL_HOST",s}const t=e.pathname;let i=-1;for(;++i0){let[v,...S]=_;const N=s[b][1];Dp(N)&&Dp(v)&&(v=Sf(!0,N,v)),s[b]=[f,v,...S]}}}}const oA=new mm().freeze();function Ef(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Nf(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function jf(e,t){if(t)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function $v(e){if(!Dp(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Fv(e,t,i){if(!i)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function uu(e){return cA(e)?e:new lS(e)}function cA(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function uA(e){return typeof e=="string"||hA(e)}function hA(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const dA="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",qv=[],Wv={allowDangerousHtml:!0},fA=/^(https?|ircs?|mailto|xmpp)$/i,pA=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function oS(e){const t=mA(e),i=gA(e);return xA(t.runSync(t.parse(i),i),e)}function mA(e){const t=e.rehypePlugins||qv,i=e.remarkPlugins||qv,s=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...Wv}:Wv;return oA().use(Xj).use(i).use(qT,s).use(t)}function gA(e){const t=e.children||"",i=new lS;return typeof t=="string"&&(i.value=t),i}function xA(e,t){const i=t.allowedElements,s=t.allowElement,a=t.components,o=t.disallowedElements,c=t.skipHtml,h=t.unwrapDisallowed,p=t.urlTransform||_A;for(const _ of pA)Object.hasOwn(t,_.from)&&(""+_.from+(_.to?"use `"+_.to+"` instead":"remove it")+dA+_.id,void 0);return pm(e,f),MN(e,{Fragment:d.Fragment,components:a,ignoreInvalidStyle:!0,jsx:d.jsx,jsxs:d.jsxs,passKeys:!0,passNode:!0});function f(_,x,b){if(_.type==="raw"&&b&&typeof x=="number")return c?b.children.splice(x,1):b.children[x]={type:"text",value:_.value},x;if(_.type==="element"){let v;for(v in _f)if(Object.hasOwn(_f,v)&&Object.hasOwn(_.properties,v)){const S=_.properties[v],N=_f[v];(N===null||N.includes(_.tagName))&&(_.properties[v]=p(String(S||""),v,_))}}if(_.type==="element"){let v=i?!i.includes(_.tagName):o?o.includes(_.tagName):!1;if(!v&&s&&typeof x=="number"&&(v=!s(_,x,b)),v&&b&&typeof x=="number")return h&&_.children?b.children.splice(x,1,..._.children):b.children.splice(x,1),x}}}function _A(e){const t=e.indexOf(":"),i=e.indexOf("?"),s=e.indexOf("#"),a=e.indexOf("/");return t===-1||a!==-1&&t>a||i!==-1&&t>i||s!==-1&&t>s||fA.test(e.slice(0,t))?e:""}function bA(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function cS(e,t,i){const a=Gu((i||{}).ignore||[]),o=vA(t);let c=-1;for(;++c0?{type:"text",value:R}:void 0),R===!1?b.lastIndex=A+1:(S!==A&&L.push({type:"text",value:f.value.slice(S,A)}),Array.isArray(R)?L.push(...R):R&&L.push(R),S=A+I[0].length,E=!0),!b.global)break;I=b.exec(f.value)}return E?(S?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let i=t[0],s=i.indexOf(")");const a=Gv(e,"(");let o=Gv(e,")");for(;s!==-1&&a>o;)e+=i.slice(0,s+1),i=i.slice(s+1),s=i.indexOf(")"),o++;return[e,i]}function hS(e,t){const i=e.input.charCodeAt(e.index-1);return(e.index===0||ba(i)||Fu(i))&&(!t||i!==47)}dS.peek=WA;function zA(){this.buffer()}function PA(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function IA(){this.buffer()}function HA(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function UA(e){const t=this.resume(),i=this.stack[this.stack.length-1];i.type,i.identifier=xr(this.sliceSerialize(e)).toLowerCase(),i.label=t}function $A(e){this.exit(e)}function FA(e){const t=this.resume(),i=this.stack[this.stack.length-1];i.type,i.identifier=xr(this.sliceSerialize(e)).toLowerCase(),i.label=t}function qA(e){this.exit(e)}function WA(){return"["}function dS(e,t,i,s){const a=i.createTracker(s);let o=a.move("[^");const c=i.enter("footnoteReference"),h=i.enter("reference");return o+=a.move(i.safe(i.associationId(e),{after:"]",before:o})),h(),c(),o+=a.move("]"),o}function GA(){return{enter:{gfmFootnoteCallString:zA,gfmFootnoteCall:PA,gfmFootnoteDefinitionLabelString:IA,gfmFootnoteDefinition:HA},exit:{gfmFootnoteCallString:UA,gfmFootnoteCall:$A,gfmFootnoteDefinitionLabelString:FA,gfmFootnoteDefinition:qA}}}function YA(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:i,footnoteReference:dS},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function i(s,a,o,c){const h=o.createTracker(c);let p=h.move("[^");const f=o.enter("footnoteDefinition"),_=o.enter("label");return p+=h.move(o.safe(o.associationId(s),{before:p,after:"]"})),_(),p+=h.move("]:"),s.children&&s.children.length>0&&(h.shift(4),p+=h.move((t?` -`:" ")+o.indentLines(o.containerFlow(s,h.current()),t?fS:VA))),f(),p}}function VA(e,t,i){return t===0?e:fS(e,t,i)}function fS(e,t,i){return(i?"":" ")+e}const KA=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];pS.peek=eR;function XA(){return{canContainEols:["delete"],enter:{strikethrough:QA},exit:{strikethrough:JA}}}function ZA(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:KA}],handlers:{delete:pS}}}function QA(e){this.enter({type:"delete",children:[]},e)}function JA(e){this.exit(e)}function pS(e,t,i,s){const a=i.createTracker(s),o=i.enter("strikethrough");let c=a.move("~~");return c+=i.containerPhrasing(e,{...a.current(),before:c,after:"~"}),c+=a.move("~~"),o(),c}function eR(){return"~"}function tR(e){return e.length}function iR(e,t){const i=t||{},s=(i.align||[]).concat(),a=i.stringLength||tR,o=[],c=[],h=[],p=[];let f=0,_=-1;for(;++_f&&(f=e[_].length);++Ep[E])&&(p[E]=I)}N.push(L)}c[_]=N,h[_]=M}let x=-1;if(typeof s=="object"&&"length"in s)for(;++xp[x]&&(p[x]=L),v[x]=L),b[x]=I}c.splice(1,0,b),h.splice(1,0,v),_=-1;const S=[];for(;++_ "),o.shift(2);const c=i.indentLines(i.containerFlow(e,o.current()),sR);return a(),c}function sR(e,t,i){return">"+(i?"":" ")+e}function aR(e,t){return Vv(e,t.inConstruct,!0)&&!Vv(e,t.notInConstruct,!1)}function Vv(e,t,i){if(typeof t=="string"&&(t=[t]),!t||t.length===0)return i;let s=-1;for(;++sc&&(c=o):o=1,a=s+t.length,s=i.indexOf(t,a);return c}function oR(e,t){return!!(t.options.fences===!1&&e.value&&!e.lang&&/[^ \r\n]/.test(e.value)&&!/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(e.value))}function cR(e){const t=e.options.fence||"`";if(t!=="`"&&t!=="~")throw new Error("Cannot serialize code with `"+t+"` for `options.fence`, expected `` ` `` or `~`");return t}function uR(e,t,i,s){const a=cR(i),o=e.value||"",c=a==="`"?"GraveAccent":"Tilde";if(oR(e,i)){const x=i.enter("codeIndented"),b=i.indentLines(o,hR);return x(),b}const h=i.createTracker(s),p=a.repeat(Math.max(lR(o,a)+1,3)),f=i.enter("codeFenced");let _=h.move(p);if(e.lang){const x=i.enter(`codeFencedLang${c}`);_+=h.move(i.safe(e.lang,{before:_,after:" ",encode:["`"],...h.current()})),x()}if(e.lang&&e.meta){const x=i.enter(`codeFencedMeta${c}`);_+=h.move(" "),_+=h.move(i.safe(e.meta,{before:_,after:` +`}),i}function zv(e){let t=0,i=e.charCodeAt(t);for(;i===9||i===32;)t++,i=e.charCodeAt(t);return e.slice(t)}function Pv(e,t){const i=HT(e,t),s=i.one(e,void 0),a=AT(i),o=Array.isArray(s)?{type:"root",children:s}:s||{type:"root",children:[]};return a&&o.children.push({type:"text",value:` +`},a),o}function WT(e,t){return e&&"run"in e?async function(i,s){const a=Pv(i,{file:s,...t});await e.run(a,s)}:function(i,s){return Pv(i,{file:s,...e||t})}}function Iv(e){if(e)throw e}var yf,Hv;function GT(){if(Hv)return yf;Hv=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,i=Object.defineProperty,s=Object.getOwnPropertyDescriptor,a=function(f){return typeof Array.isArray=="function"?Array.isArray(f):t.call(f)==="[object Array]"},o=function(f){if(!f||t.call(f)!=="[object Object]")return!1;var _=e.call(f,"constructor"),x=f.constructor&&f.constructor.prototype&&e.call(f.constructor.prototype,"isPrototypeOf");if(f.constructor&&!_&&!x)return!1;var b;for(b in f);return typeof b>"u"||e.call(f,b)},c=function(f,_){i&&_.name==="__proto__"?i(f,_.name,{enumerable:!0,configurable:!0,value:_.newValue,writable:!0}):f[_.name]=_.newValue},h=function(f,_){if(_==="__proto__")if(e.call(f,_)){if(s)return s(f,_).value}else return;return f[_]};return yf=function p(){var f,_,x,b,v,S,N=arguments[0],B=1,E=arguments.length,O=!1;for(typeof N=="boolean"&&(O=N,N=arguments[1]||{},B=2),(N==null||typeof N!="object"&&typeof N!="function")&&(N={});Bc.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 Tr={basename:XT,dirname:ZT,extname:QT,join:JT,sep:"/"};function XT(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');Vo(e);let i=0,s=-1,a=e.length,o;if(t===void 0||t.length===0||t.length>e.length){for(;a--;)if(e.codePointAt(a)===47){if(o){i=a+1;break}}else s<0&&(o=!0,s=a+1);return s<0?"":e.slice(i,s)}if(t===e)return"";let c=-1,h=t.length-1;for(;a--;)if(e.codePointAt(a)===47){if(o){i=a+1;break}}else c<0&&(o=!0,c=a+1),h>-1&&(e.codePointAt(a)===t.codePointAt(h--)?h<0&&(s=a):(h=-1,s=c));return i===s?s=c:s<0&&(s=e.length),e.slice(i,s)}function ZT(e){if(Vo(e),e.length===0)return".";let t=-1,i=e.length,s;for(;--i;)if(e.codePointAt(i)===47){if(s){t=i;break}}else s||(s=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function QT(e){Vo(e);let t=e.length,i=-1,s=0,a=-1,o=0,c;for(;t--;){const h=e.codePointAt(t);if(h===47){if(c){s=t+1;break}continue}i<0&&(c=!0,i=t+1),h===46?a<0?a=t:o!==1&&(o=1):a>-1&&(o=-1)}return a<0||i<0||o===0||o===1&&a===i-1&&a===s+1?"":e.slice(a,i)}function JT(...e){let t=-1,i;for(;++t0&&e.codePointAt(e.length-1)===47&&(i+="/"),t?"/"+i:i}function tA(e,t){let i="",s=0,a=-1,o=0,c=-1,h,p;for(;++c<=e.length;){if(c2){if(p=i.lastIndexOf("/"),p!==i.length-1){p<0?(i="",s=0):(i=i.slice(0,p),s=i.length-1-i.lastIndexOf("/")),a=c,o=0;continue}}else if(i.length>0){i="",s=0,a=c,o=0;continue}}t&&(i=i.length>0?i+"/..":"..",s=2)}else i.length>0?i+="/"+e.slice(a+1,c):i=e.slice(a+1,c),s=c-a-1;a=c,o=0}else h===46&&o>-1?o++:o=-1}return i}function Vo(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const iA={cwd:nA};function nA(){return"/"}function Mp(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function rA(e){if(typeof e=="string")e=new URL(e);else if(!Mp(e)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(e.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return sA(e)}function sA(e){if(e.hostname!==""){const s=new TypeError('File URL host must be "localhost" or empty on darwin');throw s.code="ERR_INVALID_FILE_URL_HOST",s}const t=e.pathname;let i=-1;for(;++i0){let[v,...S]=_;const N=s[b][1];Dp(N)&&Dp(v)&&(v=Sf(!0,N,v)),s[b]=[f,v,...S]}}}}const cA=new mm().freeze();function Ef(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Nf(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function jf(e,t){if(t)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function $v(e){if(!Dp(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Fv(e,t,i){if(!i)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function uu(e){return uA(e)?e:new lS(e)}function uA(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function hA(e){return typeof e=="string"||dA(e)}function dA(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const fA="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",qv=[],Wv={allowDangerousHtml:!0},pA=/^(https?|ircs?|mailto|xmpp)$/i,mA=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function oS(e){const t=gA(e),i=xA(e);return _A(t.runSync(t.parse(i),i),e)}function gA(e){const t=e.rehypePlugins||qv,i=e.remarkPlugins||qv,s=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...Wv}:Wv;return cA().use(Zj).use(i).use(WT,s).use(t)}function xA(e){const t=e.children||"",i=new lS;return typeof t=="string"&&(i.value=t),i}function _A(e,t){const i=t.allowedElements,s=t.allowElement,a=t.components,o=t.disallowedElements,c=t.skipHtml,h=t.unwrapDisallowed,p=t.urlTransform||bA;for(const _ of mA)Object.hasOwn(t,_.from)&&(""+_.from+(_.to?"use `"+_.to+"` instead":"remove it")+fA+_.id,void 0);return pm(e,f),BN(e,{Fragment:d.Fragment,components:a,ignoreInvalidStyle:!0,jsx:d.jsx,jsxs:d.jsxs,passKeys:!0,passNode:!0});function f(_,x,b){if(_.type==="raw"&&b&&typeof x=="number")return c?b.children.splice(x,1):b.children[x]={type:"text",value:_.value},x;if(_.type==="element"){let v;for(v in _f)if(Object.hasOwn(_f,v)&&Object.hasOwn(_.properties,v)){const S=_.properties[v],N=_f[v];(N===null||N.includes(_.tagName))&&(_.properties[v]=p(String(S||""),v,_))}}if(_.type==="element"){let v=i?!i.includes(_.tagName):o?o.includes(_.tagName):!1;if(!v&&s&&typeof x=="number"&&(v=!s(_,x,b)),v&&b&&typeof x=="number")return h&&_.children?b.children.splice(x,1,..._.children):b.children.splice(x,1),x}}}function bA(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||pA.test(e.slice(0,t))?e:""}function vA(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function cS(e,t,i){const a=Gu((i||{}).ignore||[]),o=yA(t);let c=-1;for(;++c0?{type:"text",value:D}:void 0),D===!1?b.lastIndex=A+1:(S!==A&&O.push({type:"text",value:f.value.slice(S,A)}),Array.isArray(D)?O.push(...D):D&&O.push(D),S=A+H[0].length,E=!0),!b.global)break;H=b.exec(f.value)}return E?(S?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let i=t[0],s=i.indexOf(")");const a=Gv(e,"(");let o=Gv(e,")");for(;s!==-1&&a>o;)e+=i.slice(0,s+1),i=i.slice(s+1),s=i.indexOf(")"),o++;return[e,i]}function hS(e,t){const i=e.input.charCodeAt(e.index-1);return(e.index===0||ba(i)||Fu(i))&&(!t||i!==47)}dS.peek=GA;function PA(){this.buffer()}function IA(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function HA(){this.buffer()}function UA(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function $A(e){const t=this.resume(),i=this.stack[this.stack.length-1];i.type,i.identifier=_r(this.sliceSerialize(e)).toLowerCase(),i.label=t}function FA(e){this.exit(e)}function qA(e){const t=this.resume(),i=this.stack[this.stack.length-1];i.type,i.identifier=_r(this.sliceSerialize(e)).toLowerCase(),i.label=t}function WA(e){this.exit(e)}function GA(){return"["}function dS(e,t,i,s){const a=i.createTracker(s);let o=a.move("[^");const c=i.enter("footnoteReference"),h=i.enter("reference");return o+=a.move(i.safe(i.associationId(e),{after:"]",before:o})),h(),c(),o+=a.move("]"),o}function YA(){return{enter:{gfmFootnoteCallString:PA,gfmFootnoteCall:IA,gfmFootnoteDefinitionLabelString:HA,gfmFootnoteDefinition:UA},exit:{gfmFootnoteCallString:$A,gfmFootnoteCall:FA,gfmFootnoteDefinitionLabelString:qA,gfmFootnoteDefinition:WA}}}function VA(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:i,footnoteReference:dS},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function i(s,a,o,c){const h=o.createTracker(c);let p=h.move("[^");const f=o.enter("footnoteDefinition"),_=o.enter("label");return p+=h.move(o.safe(o.associationId(s),{before:p,after:"]"})),_(),p+=h.move("]:"),s.children&&s.children.length>0&&(h.shift(4),p+=h.move((t?` +`:" ")+o.indentLines(o.containerFlow(s,h.current()),t?fS:KA))),f(),p}}function KA(e,t,i){return t===0?e:fS(e,t,i)}function fS(e,t,i){return(i?"":" ")+e}const XA=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];pS.peek=tR;function ZA(){return{canContainEols:["delete"],enter:{strikethrough:JA},exit:{strikethrough:eR}}}function QA(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:XA}],handlers:{delete:pS}}}function JA(e){this.enter({type:"delete",children:[]},e)}function eR(e){this.exit(e)}function pS(e,t,i,s){const a=i.createTracker(s),o=i.enter("strikethrough");let c=a.move("~~");return c+=i.containerPhrasing(e,{...a.current(),before:c,after:"~"}),c+=a.move("~~"),o(),c}function tR(){return"~"}function iR(e){return e.length}function nR(e,t){const i=t||{},s=(i.align||[]).concat(),a=i.stringLength||iR,o=[],c=[],h=[],p=[];let f=0,_=-1;for(;++_f&&(f=e[_].length);++Ep[E])&&(p[E]=H)}N.push(O)}c[_]=N,h[_]=B}let x=-1;if(typeof s=="object"&&"length"in s)for(;++xp[x]&&(p[x]=O),v[x]=O),b[x]=H}c.splice(1,0,b),h.splice(1,0,v),_=-1;const S=[];for(;++_ "),o.shift(2);const c=i.indentLines(i.containerFlow(e,o.current()),aR);return a(),c}function aR(e,t,i){return">"+(i?"":" ")+e}function lR(e,t){return Vv(e,t.inConstruct,!0)&&!Vv(e,t.notInConstruct,!1)}function Vv(e,t,i){if(typeof t=="string"&&(t=[t]),!t||t.length===0)return i;let s=-1;for(;++sc&&(c=o):o=1,a=s+t.length,s=i.indexOf(t,a);return c}function cR(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 uR(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 hR(e,t,i,s){const a=uR(i),o=e.value||"",c=a==="`"?"GraveAccent":"Tilde";if(cR(e,i)){const x=i.enter("codeIndented"),b=i.indentLines(o,dR);return x(),b}const h=i.createTracker(s),p=a.repeat(Math.max(oR(o,a)+1,3)),f=i.enter("codeFenced");let _=h.move(p);if(e.lang){const x=i.enter(`codeFencedLang${c}`);_+=h.move(i.safe(e.lang,{before:_,after:" ",encode:["`"],...h.current()})),x()}if(e.lang&&e.meta){const x=i.enter(`codeFencedMeta${c}`);_+=h.move(" "),_+=h.move(i.safe(e.meta,{before:_,after:` `,encode:["`"],...h.current()})),x()}return _+=h.move(` `),o&&(_+=h.move(o+` -`)),_+=h.move(p),f(),_}function hR(e,t,i){return(i?"":" ")+e}function gm(e){const t=e.options.quote||'"';if(t!=='"'&&t!=="'")throw new Error("Cannot serialize title with `"+t+"` for `options.quote`, expected `\"`, or `'`");return t}function dR(e,t,i,s){const a=gm(i),o=a==='"'?"Quote":"Apostrophe",c=i.enter("definition");let h=i.enter("label");const p=i.createTracker(s);let f=p.move("[");return f+=p.move(i.safe(i.associationId(e),{before:f,after:"]",...p.current()})),f+=p.move("]: "),h(),!e.url||/[\0- \u007F]/.test(e.url)?(h=i.enter("destinationLiteral"),f+=p.move("<"),f+=p.move(i.safe(e.url,{before:f,after:">",...p.current()})),f+=p.move(">")):(h=i.enter("destinationRaw"),f+=p.move(i.safe(e.url,{before:f,after:e.title?" ":` -`,...p.current()}))),h(),e.title&&(h=i.enter(`title${o}`),f+=p.move(" "+a),f+=p.move(i.safe(e.title,{before:f,after:a,...p.current()})),f+=p.move(a),h()),c(),f}function fR(e){const t=e.options.emphasis||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize emphasis with `"+t+"` for `options.emphasis`, expected `*`, or `_`");return t}function Ho(e){return"&#x"+e.toString(16).toUpperCase()+";"}function Lu(e,t,i){const s=pl(e),a=pl(t);return s===void 0?a===void 0?i==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:a===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:s===1?a===void 0?{inside:!1,outside:!1}:a===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:a===void 0?{inside:!1,outside:!1}:a===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}mS.peek=pR;function mS(e,t,i,s){const a=fR(i),o=i.enter("emphasis"),c=i.createTracker(s),h=c.move(a);let p=c.move(i.containerPhrasing(e,{after:a,before:h,...c.current()}));const f=p.charCodeAt(0),_=Lu(s.before.charCodeAt(s.before.length-1),f,a);_.inside&&(p=Ho(f)+p.slice(1));const x=p.charCodeAt(p.length-1),b=Lu(s.after.charCodeAt(0),x,a);b.inside&&(p=p.slice(0,-1)+Ho(x));const v=c.move(a);return o(),i.attentionEncodeSurroundingInfo={after:b.outside,before:_.outside},h+p+v}function pR(e,t,i){return i.options.emphasis||"*"}function mR(e,t){let i=!1;return pm(e,function(s){if("value"in s&&/\r?\n|\r/.test(s.value)||s.type==="break")return i=!0,Ap}),!!((!e.depth||e.depth<3)&&lm(e)&&(t.options.setext||i))}function gR(e,t,i,s){const a=Math.max(Math.min(6,e.depth||1),1),o=i.createTracker(s);if(mR(e,i)){const _=i.enter("headingSetext"),x=i.enter("phrasing"),b=i.containerPhrasing(e,{...o.current(),before:` +`)),_+=h.move(p),f(),_}function dR(e,t,i){return(i?"":" ")+e}function gm(e){const t=e.options.quote||'"';if(t!=='"'&&t!=="'")throw new Error("Cannot serialize title with `"+t+"` for `options.quote`, expected `\"`, or `'`");return t}function fR(e,t,i,s){const a=gm(i),o=a==='"'?"Quote":"Apostrophe",c=i.enter("definition");let h=i.enter("label");const p=i.createTracker(s);let f=p.move("[");return f+=p.move(i.safe(i.associationId(e),{before:f,after:"]",...p.current()})),f+=p.move("]: "),h(),!e.url||/[\0- \u007F]/.test(e.url)?(h=i.enter("destinationLiteral"),f+=p.move("<"),f+=p.move(i.safe(e.url,{before:f,after:">",...p.current()})),f+=p.move(">")):(h=i.enter("destinationRaw"),f+=p.move(i.safe(e.url,{before:f,after:e.title?" ":` +`,...p.current()}))),h(),e.title&&(h=i.enter(`title${o}`),f+=p.move(" "+a),f+=p.move(i.safe(e.title,{before:f,after:a,...p.current()})),f+=p.move(a),h()),c(),f}function pR(e){const t=e.options.emphasis||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize emphasis with `"+t+"` for `options.emphasis`, expected `*`, or `_`");return t}function Ho(e){return"&#x"+e.toString(16).toUpperCase()+";"}function Lu(e,t,i){const s=pl(e),a=pl(t);return s===void 0?a===void 0?i==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:a===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:s===1?a===void 0?{inside:!1,outside:!1}:a===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:a===void 0?{inside:!1,outside:!1}:a===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}mS.peek=mR;function mS(e,t,i,s){const a=pR(i),o=i.enter("emphasis"),c=i.createTracker(s),h=c.move(a);let p=c.move(i.containerPhrasing(e,{after:a,before:h,...c.current()}));const f=p.charCodeAt(0),_=Lu(s.before.charCodeAt(s.before.length-1),f,a);_.inside&&(p=Ho(f)+p.slice(1));const x=p.charCodeAt(p.length-1),b=Lu(s.after.charCodeAt(0),x,a);b.inside&&(p=p.slice(0,-1)+Ho(x));const v=c.move(a);return o(),i.attentionEncodeSurroundingInfo={after:b.outside,before:_.outside},h+p+v}function mR(e,t,i){return i.options.emphasis||"*"}function gR(e,t){let i=!1;return pm(e,function(s){if("value"in s&&/\r?\n|\r/.test(s.value)||s.type==="break")return i=!0,Ap}),!!((!e.depth||e.depth<3)&&lm(e)&&(t.options.setext||i))}function xR(e,t,i,s){const a=Math.max(Math.min(6,e.depth||1),1),o=i.createTracker(s);if(gR(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=Ho(f.charCodeAt(0))+f.slice(1)),f=f?c+" "+f:c,i.options.closeAtx&&(f+=" "+c),p(),h(),f}gS.peek=xR;function gS(e){return e.value||""}function xR(){return"<"}xS.peek=_R;function xS(e,t,i,s){const a=gm(i),o=a==='"'?"Quote":"Apostrophe",c=i.enter("image");let h=i.enter("label");const p=i.createTracker(s);let f=p.move("![");return f+=p.move(i.safe(e.alt,{before:f,after:"]",...p.current()})),f+=p.move("]("),h(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(h=i.enter("destinationLiteral"),f+=p.move("<"),f+=p.move(i.safe(e.url,{before:f,after:">",...p.current()})),f+=p.move(">")):(h=i.enter("destinationRaw"),f+=p.move(i.safe(e.url,{before:f,after:e.title?" ":")",...p.current()}))),h(),e.title&&(h=i.enter(`title${o}`),f+=p.move(" "+a),f+=p.move(i.safe(e.title,{before:f,after:a,...p.current()})),f+=p.move(a),h()),f+=p.move(")"),c(),f}function _R(){return"!"}_S.peek=bR;function _S(e,t,i,s){const a=e.referenceType,o=i.enter("imageReference");let c=i.enter("label");const h=i.createTracker(s);let p=h.move("![");const f=i.safe(e.alt,{before:p,after:"]",...h.current()});p+=h.move(f+"]["),c();const _=i.stack;i.stack=[],c=i.enter("reference");const x=i.safe(i.associationId(e),{before:p,after:"]",...h.current()});return c(),i.stack=_,o(),a==="full"||!f||f!==x?p+=h.move(x+"]"):a==="shortcut"?p=p.slice(0,-1):p+=h.move("]"),p}function bR(){return"!"}bS.peek=vR;function bS(e,t,i){let s=e.value||"",a="`",o=-1;for(;new RegExp("(^|[^`])"+a+"([^`]|$)").test(s);)a+="`";for(/[^ \r\n]/.test(s)&&(/^[ \r\n]/.test(s)&&/[ \r\n]$/.test(s)||/^`|`$/.test(s))&&(s=" "+s+" ");++o\u007F]/.test(e.url))}yS.peek=yR;function yS(e,t,i,s){const a=gm(i),o=a==='"'?"Quote":"Apostrophe",c=i.createTracker(s);let h,p;if(vS(e,i)){const _=i.stack;i.stack=[],h=i.enter("autolink");let x=c.move("<");return x+=c.move(i.containerPhrasing(e,{before:x,after:">",...c.current()})),x+=c.move(">"),h(),i.stack=_,x}h=i.enter("link"),p=i.enter("label");let f=c.move("[");return f+=c.move(i.containerPhrasing(e,{before:f,after:"](",...c.current()})),f+=c.move("]("),p(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(p=i.enter("destinationLiteral"),f+=c.move("<"),f+=c.move(i.safe(e.url,{before:f,after:">",...c.current()})),f+=c.move(">")):(p=i.enter("destinationRaw"),f+=c.move(i.safe(e.url,{before:f,after:e.title?" ":")",...c.current()}))),p(),e.title&&(p=i.enter(`title${o}`),f+=c.move(" "+a),f+=c.move(i.safe(e.title,{before:f,after:a,...c.current()})),f+=c.move(a),p()),f+=c.move(")"),h(),f}function yR(e,t,i){return vS(e,i)?"<":"["}SS.peek=SR;function SS(e,t,i,s){const a=e.referenceType,o=i.enter("linkReference");let c=i.enter("label");const h=i.createTracker(s);let p=h.move("[");const f=i.containerPhrasing(e,{before:p,after:"]",...h.current()});p+=h.move(f+"]["),c();const _=i.stack;i.stack=[],c=i.enter("reference");const x=i.safe(i.associationId(e),{before:p,after:"]",...h.current()});return c(),i.stack=_,o(),a==="full"||!f||f!==x?p+=h.move(x+"]"):a==="shortcut"?p=p.slice(0,-1):p+=h.move("]"),p}function SR(){return"["}function xm(e){const t=e.options.bullet||"*";if(t!=="*"&&t!=="+"&&t!=="-")throw new Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function wR(e){const t=xm(e),i=e.options.bulletOther;if(!i)return t==="*"?"-":"*";if(i!=="*"&&i!=="+"&&i!=="-")throw new Error("Cannot serialize items with `"+i+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(i===t)throw new Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+i+"`) to be different");return i}function CR(e){const t=e.options.bulletOrdered||".";if(t!=="."&&t!==")")throw new Error("Cannot serialize items with `"+t+"` for `options.bulletOrdered`, expected `.` or `)`");return t}function wS(e){const t=e.options.rule||"*";if(t!=="*"&&t!=="-"&&t!=="_")throw new Error("Cannot serialize rules with `"+t+"` for `options.rule`, expected `*`, `-`, or `_`");return t}function kR(e,t,i,s){const a=i.enter("list"),o=i.bulletCurrent;let c=e.ordered?CR(i):xm(i);const h=e.ordered?c==="."?")":".":wR(i);let p=t&&i.bulletLastUsed?c===i.bulletLastUsed:!1;if(!e.ordered){const _=e.children?e.children[0]:void 0;if((c==="*"||c==="-")&&_&&(!_.children||!_.children[0])&&i.stack[i.stack.length-1]==="list"&&i.stack[i.stack.length-2]==="listItem"&&i.stack[i.stack.length-3]==="list"&&i.stack[i.stack.length-4]==="listItem"&&i.indexStack[i.indexStack.length-1]===0&&i.indexStack[i.indexStack.length-2]===0&&i.indexStack[i.indexStack.length-3]===0&&(p=!0),wS(i)===c&&_){let x=-1;for(;++x-1?t.start:1)+(i.options.incrementListMarker===!1?0:t.children.indexOf(e))+o);let c=o.length+1;(a==="tab"||a==="mixed"&&(t&&t.type==="list"&&t.spread||e.spread))&&(c=Math.ceil(c/4)*4);const h=i.createTracker(s);h.move(o+" ".repeat(c-o.length)),h.shift(c);const p=i.enter("listItem"),f=i.indentLines(i.containerFlow(e,h.current()),_);return p(),f;function _(x,b,v){return b?(v?"":" ".repeat(c))+x:(v?o:o+" ".repeat(c-o.length))+x}}function jR(e,t,i,s){const a=i.enter("paragraph"),o=i.enter("phrasing"),c=i.containerPhrasing(e,s);return o(),a(),c}const TR=Gu(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function AR(e,t,i,s){return(e.children.some(function(c){return TR(c)})?i.containerPhrasing:i.containerFlow).call(i,e,s)}function RR(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}CS.peek=DR;function CS(e,t,i,s){const a=RR(i),o=i.enter("strong"),c=i.createTracker(s),h=c.move(a+a);let p=c.move(i.containerPhrasing(e,{after:a,before:h,...c.current()}));const f=p.charCodeAt(0),_=Lu(s.before.charCodeAt(s.before.length-1),f,a);_.inside&&(p=Ho(f)+p.slice(1));const x=p.charCodeAt(p.length-1),b=Lu(s.after.charCodeAt(0),x,a);b.inside&&(p=p.slice(0,-1)+Ho(x));const v=c.move(a+a);return o(),i.attentionEncodeSurroundingInfo={after:b.outside,before:_.outside},h+p+v}function DR(e,t,i){return i.options.strong||"*"}function MR(e,t,i,s){return i.safe(e.value,s)}function BR(e){const t=e.options.ruleRepetition||3;if(t<3)throw new Error("Cannot serialize rules with repetition `"+t+"` for `options.ruleRepetition`, expected `3` or more");return t}function LR(e,t,i){const s=(wS(i)+(i.options.ruleSpaces?" ":"")).repeat(BR(i));return i.options.ruleSpaces?s.slice(0,-1):s}const kS={blockquote:rR,break:Kv,code:uR,definition:dR,emphasis:mS,hardBreak:Kv,heading:gR,html:gS,image:xS,imageReference:_S,inlineCode:bS,link:yS,linkReference:SS,list:kR,listItem:NR,paragraph:jR,root:AR,strong:CS,text:MR,thematicBreak:LR};function OR(){return{enter:{table:zR,tableData:Xv,tableHeader:Xv,tableRow:IR},exit:{codeText:HR,table:PR,tableData:Df,tableHeader:Df,tableRow:Df}}}function zR(e){const t=e._align;this.enter({type:"table",align:t.map(function(i){return i==="none"?null:i}),children:[]},e),this.data.inTable=!0}function PR(e){this.exit(e),this.data.inTable=void 0}function IR(e){this.enter({type:"tableRow",children:[]},e)}function Df(e){this.exit(e)}function Xv(e){this.enter({type:"tableCell",children:[]},e)}function HR(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,UR));const i=this.stack[this.stack.length-1];i.type,i.value=t,this.exit(e)}function UR(e,t){return t==="|"?t:e}function $R(e){const t=e||{},i=t.tableCellPadding,s=t.tablePipeAlign,a=t.stringLength,o=i?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:` -`,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:b,table:c,tableCell:p,tableRow:h}};function c(v,S,N,M){return f(_(v,N,M),v.align)}function h(v,S,N,M){const E=x(v,N,M),L=f([E]);return L.slice(0,L.indexOf(` -`))}function p(v,S,N,M){const E=N.enter("tableCell"),L=N.enter("phrasing"),I=N.containerPhrasing(v,{...M,before:o,after:o});return L(),E(),I}function f(v,S){return iR(v,{align:S,alignDelimiters:s,padding:i,stringLength:a})}function _(v,S,N){const M=v.children;let E=-1;const L=[],I=S.enter("table");for(;++E0&&!i&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),i}const a3={tokenize:p3,partial:!0};function l3(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:h3,continuation:{tokenize:d3},exit:f3}},text:{91:{name:"gfmFootnoteCall",tokenize:u3},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:o3,resolveTo:c3}}}}function o3(e,t,i){const s=this;let a=s.events.length;const o=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let c;for(;a--;){const p=s.events[a][1];if(p.type==="labelImage"){c=p;break}if(p.type==="gfmFootnoteCall"||p.type==="labelLink"||p.type==="label"||p.type==="image"||p.type==="link")break}return h;function h(p){if(!c||!c._balanced)return i(p);const f=xr(s.sliceSerialize({start:c.end,end:s.now()}));return f.codePointAt(0)!==94||!o.includes(f.slice(1))?i(p):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(p),e.exit("gfmFootnoteCallLabelMarker"),t(p))}}function c3(e,t){let i=e.length;for(;i--;)if(e[i][1].type==="labelImage"&&e[i][0]==="enter"){e[i][1];break}e[i+1][1].type="data",e[i+3][1].type="gfmFootnoteCallLabelMarker";const s={type:"gfmFootnoteCall",start:Object.assign({},e[i+3][1].start),end:Object.assign({},e[e.length-1][1].end)},a={type:"gfmFootnoteCallMarker",start:Object.assign({},e[i+3][1].end),end:Object.assign({},e[i+3][1].end)};a.end.column++,a.end.offset++,a.end._bufferIndex++;const o={type:"gfmFootnoteCallString",start:Object.assign({},a.end),end:Object.assign({},e[e.length-1][1].start)},c={type:"chunkString",contentType:"string",start:Object.assign({},o.start),end:Object.assign({},o.end)},h=[e[i+1],e[i+2],["enter",s,t],e[i+3],e[i+4],["enter",a,t],["exit",a,t],["enter",o,t],["enter",c,t],["exit",c,t],["exit",o,t],e[e.length-2],e[e.length-1],["exit",s,t]];return e.splice(i,e.length-i+1,...h),e}function u3(e,t,i){const s=this,a=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let o=0,c;return h;function h(x){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(x),e.exit("gfmFootnoteCallLabelMarker"),p}function p(x){return x!==94?i(x):(e.enter("gfmFootnoteCallMarker"),e.consume(x),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",f)}function f(x){if(o>999||x===93&&!c||x===null||x===91||qt(x))return i(x);if(x===93){e.exit("chunkString");const b=e.exit("gfmFootnoteCallString");return a.includes(xr(s.sliceSerialize(b)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(x),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):i(x)}return qt(x)||(c=!0),o++,e.consume(x),x===92?_:f}function _(x){return x===91||x===92||x===93?(e.consume(x),o++,f):f(x)}}function h3(e,t,i){const s=this,a=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let o,c=0,h;return p;function p(S){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionLabelMarker"),f}function f(S){return S===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",_):i(S)}function _(S){if(c>999||S===93&&!h||S===null||S===91||qt(S))return i(S);if(S===93){e.exit("chunkString");const N=e.exit("gfmFootnoteDefinitionLabelString");return o=xr(s.sliceSerialize(N)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),b}return qt(S)||(h=!0),c++,e.consume(S),S===92?x:_}function x(S){return S===91||S===92||S===93?(e.consume(S),c++,_):_(S)}function b(S){return S===58?(e.enter("definitionMarker"),e.consume(S),e.exit("definitionMarker"),a.includes(o)||a.push(o),yt(e,v,"gfmFootnoteDefinitionWhitespace")):i(S)}function v(S){return t(S)}}function d3(e,t,i){return e.check(Yo,t,e.attempt(a3,t,i))}function f3(e){e.exit("gfmFootnoteDefinition")}function p3(e,t,i){const s=this;return yt(e,a,"gfmFootnoteDefinitionIndent",5);function a(o){const c=s.events[s.events.length-1];return c&&c[1].type==="gfmFootnoteDefinitionIndent"&&c[2].sliceSerialize(c[1],!0).length===4?t(o):i(o)}}function m3(e){let i=(e||{}).singleTilde;const s={name:"strikethrough",tokenize:o,resolveAll:a};return i==null&&(i=!0),{text:{126:s},insideSpan:{null:[s]},attentionMarkers:{null:[126]}};function a(c,h){let p=-1;for(;++p1?p(S):(c.consume(S),x++,v);if(x<2&&!i)return p(S);const M=c.exit("strikethroughSequenceTemporary"),E=pl(S);return M._open=!E||E===2&&!!N,M._close=!N||N===2&&!!E,h(S)}}}class g3{constructor(){this.map=[]}add(t,i,s){x3(this,t,i,s)}consume(t){if(this.map.sort(function(o,c){return o[0]-c[0]}),this.map.length===0)return;let i=this.map.length;const s=[];for(;i>0;)i-=1,s.push(t.slice(this.map[i][0]+this.map[i][1]),this.map[i][2]),t.length=this.map[i][0];s.push(t.slice()),t.length=0;let a=s.pop();for(;a;){for(const o of a)t.push(o);a=s.pop()}this.map.length=0}}function x3(e,t,i,s){let a=0;if(!(i===0&&s.length===0)){for(;a-1;){const V=s.events[re][1].type;if(V==="lineEnding"||V==="linePrefix")re--;else break}const $=re>-1?s.events[re][1].type:null,G=$==="tableHead"||$==="tableRow"?R:p;return G===R&&s.parser.lazy[s.now().line]?i(B):G(B)}function p(B){return e.enter("tableHead"),e.enter("tableRow"),f(B)}function f(B){return B===124||(c=!0,o+=1),_(B)}function _(B){return B===null?i(B):Ye(B)?o>1?(o=0,s.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(B),e.exit("lineEnding"),v):i(B):mt(B)?yt(e,_,"whitespace")(B):(o+=1,c&&(c=!1,a+=1),B===124?(e.enter("tableCellDivider"),e.consume(B),e.exit("tableCellDivider"),c=!0,_):(e.enter("data"),x(B)))}function x(B){return B===null||B===124||qt(B)?(e.exit("data"),_(B)):(e.consume(B),B===92?b:x)}function b(B){return B===92||B===124?(e.consume(B),x):x(B)}function v(B){return s.interrupt=!1,s.parser.lazy[s.now().line]?i(B):(e.enter("tableDelimiterRow"),c=!1,mt(B)?yt(e,S,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(B):S(B))}function S(B){return B===45||B===58?M(B):B===124?(c=!0,e.enter("tableCellDivider"),e.consume(B),e.exit("tableCellDivider"),N):q(B)}function N(B){return mt(B)?yt(e,M,"whitespace")(B):M(B)}function M(B){return B===58?(o+=1,c=!0,e.enter("tableDelimiterMarker"),e.consume(B),e.exit("tableDelimiterMarker"),E):B===45?(o+=1,E(B)):B===null||Ye(B)?A(B):q(B)}function E(B){return B===45?(e.enter("tableDelimiterFiller"),L(B)):q(B)}function L(B){return B===45?(e.consume(B),L):B===58?(c=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(B),e.exit("tableDelimiterMarker"),I):(e.exit("tableDelimiterFiller"),I(B))}function I(B){return mt(B)?yt(e,A,"whitespace")(B):A(B)}function A(B){return B===124?S(B):B===null||Ye(B)?!c||a!==o?q(B):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(B)):q(B)}function q(B){return i(B)}function R(B){return e.enter("tableRow"),ne(B)}function ne(B){return B===124?(e.enter("tableCellDivider"),e.consume(B),e.exit("tableCellDivider"),ne):B===null||Ye(B)?(e.exit("tableRow"),t(B)):mt(B)?yt(e,ne,"whitespace")(B):(e.enter("data"),ue(B))}function ue(B){return B===null||B===124||qt(B)?(e.exit("data"),ne(B)):(e.consume(B),B===92?ye:ue)}function ye(B){return B===92||B===124?(e.consume(B),ue):ue(B)}}function y3(e,t){let i=-1,s=!0,a=0,o=[0,0,0,0],c=[0,0,0,0],h=!1,p=0,f,_,x;const b=new g3;for(;++ii[2]+1){const S=i[2]+1,N=i[3]-i[2]-1;e.add(S,N,[])}}e.add(i[3]+1,0,[["exit",x,t]])}return a!==void 0&&(o.end=Object.assign({},ll(t.events,a)),e.add(a,0,[["exit",o,t]]),o=void 0),o}function Qv(e,t,i,s,a){const o=[],c=ll(t.events,i);a&&(a.end=Object.assign({},c),o.push(["exit",a,t])),s.end=Object.assign({},c),o.push(["exit",s,t]),e.add(i+1,0,o)}function ll(e,t){const i=e[t],s=i[0]==="enter"?"start":"end";return i[1][s]}const S3={name:"tasklistCheck",tokenize:C3};function w3(){return{text:{91:S3}}}function C3(e,t,i){const s=this;return a;function a(p){return s.previous!==null||!s._gfmTasklistFirstContentOfListItem?i(p):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(p),e.exit("taskListCheckMarker"),o)}function o(p){return qt(p)?(e.enter("taskListCheckValueUnchecked"),e.consume(p),e.exit("taskListCheckValueUnchecked"),c):p===88||p===120?(e.enter("taskListCheckValueChecked"),e.consume(p),e.exit("taskListCheckValueChecked"),c):i(p)}function c(p){return p===93?(e.enter("taskListCheckMarker"),e.consume(p),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),h):i(p)}function h(p){return Ye(p)?t(p):mt(p)?e.check({tokenize:k3},t,i)(p):i(p)}}function k3(e,t,i){return yt(e,s,"whitespace");function s(a){return a===null?i(a):t(a)}}function E3(e){return U0([ZR(),l3(),m3(e),b3(),w3()])}const N3={};function BS(e){const t=this,i=e||N3,s=t.data(),a=s.micromarkExtensions||(s.micromarkExtensions=[]),o=s.fromMarkdownExtensions||(s.fromMarkdownExtensions=[]),c=s.toMarkdownExtensions||(s.toMarkdownExtensions=[]);a.push(E3(i)),o.push(YR()),c.push(VR(i))}const da=["ariaDescribedBy","ariaLabel","ariaLabelledBy"],ml={ancestors:{tbody:["table"],td:["table"],th:["table"],thead:["table"],tfoot:["table"],tr:["table"]},attributes:{a:[...da,"dataFootnoteBackref","dataFootnoteRef",["className","data-footnote-backref"],"href"],blockquote:["cite"],code:[["className",/^language-./]],del:["cite"],div:["itemScope","itemType"],dl:[...da],h2:[["className","sr-only"]],img:[...da,"longDesc","src"],input:[["disabled",!0],["type","checkbox"]],ins:["cite"],li:[["className","task-list-item"]],ol:[...da,["className","contains-task-list"]],q:["cite"],section:["dataFootnotes",["className","footnotes"]],source:["srcSet"],summary:[...da],table:[...da],ul:[...da,["className","contains-task-list"]],"*":["abbr","accept","acceptCharset","accessKey","action","align","alt","axis","border","cellPadding","cellSpacing","char","charOff","charSet","checked","clear","colSpan","color","cols","compact","coords","dateTime","dir","encType","frame","hSpace","headers","height","hrefLang","htmlFor","id","isMap","itemProp","label","lang","maxLength","media","method","multiple","name","noHref","noShade","noWrap","open","prompt","readOnly","rev","rowSpan","rows","rules","scope","selected","shape","size","span","start","summary","tabIndex","title","useMap","vAlign","value","width"]},clobber:["ariaDescribedBy","ariaLabelledBy","id","name"],clobberPrefix:"user-content-",protocols:{cite:["http","https"],href:["http","https","irc","ircs","mailto","xmpp"],longDesc:["http","https"],src:["http","https"]},required:{input:{disabled:!0,type:"checkbox"}},strip:["script"],tagNames:["a","b","blockquote","br","code","dd","del","details","div","dl","dt","em","h1","h2","h3","h4","h5","h6","hr","i","img","input","ins","kbd","li","ol","p","picture","pre","q","rp","rt","ruby","s","samp","section","source","span","strike","strong","sub","summary","sup","table","tbody","td","tfoot","th","thead","tr","tt","ul","var"]},Is={}.hasOwnProperty;function j3(e,t){let i={type:"root",children:[]};const s={schema:t?{...ml,...t}:ml,stack:[]},a=LS(s,e);return a&&(Array.isArray(a)?a.length===1?i=a[0]:i.children=a:i=a),i}function LS(e,t){if(t&&typeof t=="object"){const i=t;switch(typeof i.type=="string"?i.type:""){case"comment":return T3(e,i);case"doctype":return A3(e,i);case"element":return R3(e,i);case"root":return D3(e,i);case"text":return M3(e,i)}}}function T3(e,t){if(e.schema.allowComments){const i=typeof t.value=="string"?t.value:"",s=i.indexOf("-->"),o={type:"comment",value:s<0?i:i.slice(0,s)};return Ko(o,t),o}}function A3(e,t){if(e.schema.allowDoctypes){const i={type:"doctype"};return Ko(i,t),i}}function R3(e,t){const i=typeof t.tagName=="string"?t.tagName:"";e.stack.push(i);const s=OS(e,t.children),a=B3(e,t.properties);e.stack.pop();let o=!1;if(i&&i!=="*"&&(!e.schema.tagNames||e.schema.tagNames.includes(i))&&(o=!0,e.schema.ancestors&&Is.call(e.schema.ancestors,i))){const h=e.schema.ancestors[i];let p=-1;for(o=!1;++p1){let a=!1,o=0;for(;++o-1&&o>p||c>-1&&o>c||h>-1&&o>h)return!0;let f=-1;for(;++f4&&t.slice(0,4).toLowerCase()==="data")return i}function PS(e){return function(t){return j3(t,e)}}const hl=["Romance","Fantasy","Science Fiction","Mystery","Thriller","Horror","Adventure","Historical Fiction","Contemporary Lit","Humor","Poetry","Non-Fiction","Fanfiction","Short Story","Paranormal","Werewolf","LGBTQ+","New Adult","Teen Fiction","Diverse Lit","Others"],rs=["English","Chinese","Korean","Japanese","Spanish","French","Hindi","Arabic","Portuguese","Russian","Others"];function IS(e){return e.toLowerCase().replace(/[^a-z0-9+]/g,"")}const z3=Object.fromEntries(hl.map(e=>[IS(e),e])),P3={scifi:"Science Fiction",sf:"Science Fiction",comedy:"Humor",humour:"Humor",ya:"Teen Fiction",youngadult:"Teen Fiction",lgbt:"LGBTQ+",lgbtq:"LGBTQ+","lgbtqia+":"LGBTQ+",historical:"Historical Fiction",scary:"Horror"};function Cu(e){if(!e)return null;const t=IS(e.trim());return t?z3[t]??P3[t]??null:null}function HS(e,t){const i=t.startsWith("assets/")?t.slice(7):t;return`/api/stories/${e}/asset/${i}`}function bm(e,t,i){const[s,a]=w.useState({url:null,loading:!!t,error:!1});return w.useEffect(()=>{if(!t){a({url:null,loading:!1,error:!1});return}let o=null,c=!1;return a({url:null,loading:!0,error:!1}),(async()=>{try{const h=await i(HS(e,t));if(!h.ok)throw new Error(`asset request failed (${h.status})`);const p=await h.blob();if(c)return;o=URL.createObjectURL(p),a({url:o,loading:!1,error:!1})}catch{c||a({url:null,loading:!1,error:!0})}})(),()=>{c=!0,o&&URL.revokeObjectURL(o)}},[e,t,i]),s}function ty({storyName:e,assetPath:t,authFetch:i,alt:s,className:a}){const{url:o,loading:c,error:h}=bm(e,t,i);return h||!c&&!o?d.jsx("div",{className:"w-full aspect-video bg-surface border border-border rounded flex items-center justify-center",children:d.jsx("span",{className:"text-xs text-muted",children:"Image not available"})}):o?d.jsx("img",{src:o,alt:s,className:a??"w-full rounded border border-border"}):d.jsx("div",{className:"w-full aspect-video bg-surface border border-border rounded flex items-center justify-center","data-testid":"asset-loading",children:d.jsx("span",{className:"text-xs text-muted",children:"Loading image…"})})}function iy(e,t,i,s){const a=t.split(/\s+/).filter(Boolean);if(a.length===0)return[""];const o=[];let c="";for(const h of a){const p=c?`${c} ${h}`:h;!c||e(p,s)<=i?c=p:(o.push(c),c=h)}return c&&o.push(c),o}function jo(e,t,i,s,a){const o=a.lineHeightFactor??1.2,c=a.speakerScale??.8,h=a.paddingX??Math.max(2,i*.06),p=a.paddingY??Math.max(2,s*.08),f=Math.max(1,i-2*h),_=Math.max(1,s-2*p),x=Math.max(a.minFontSize,a.maxFontSize),b=Math.max(1,Math.min(a.minFontSize,x)),v=N=>{const M=a.hasSpeaker?N*c:0,E=a.hasSpeaker?M*o:0,L=Math.max(1,_-E),I=a.fontWeight??400,A=iy((ne,ue)=>e(ne,ue,I),t,f,N),q=A.length*N*o,R=A.every(ne=>e(ne,N,I)<=f+.5);return{lines:A,ok:q<=L&&R}};if(typeof a.fontSize=="number"&&Number.isFinite(a.fontSize)&&a.fontSize>0){const N=Math.max(1,a.fontSize),{lines:M,ok:E}=v(N);return{lines:M,fontSize:N,lineHeight:N*o,speakerFontSize:a.hasSpeaker?N*c:0,overflow:!E}}for(let N=x;N>=b;N-=.5){const{lines:M,ok:E}=v(N);if(E)return{lines:M,fontSize:N,lineHeight:N*o,speakerFontSize:a.hasSpeaker?N*c:0,overflow:!1}}return{lines:iy(e,t,f,b),fontSize:b,lineHeight:b*o,speakerFontSize:a.hasSpeaker?b*c:0,overflow:!0}}function I3(e){return{minFontSize:Math.max(1,e*.022),maxFontSize:Math.max(1,e*.05)}}const US=["speech","narration","sfx"],H3=2;function Ar(e,t,i){return Math.min(i,Math.max(t,e))}function dl(e,t,i){return typeof e=="number"&&Number.isFinite(e)?Ar(e,t,i):void 0}function vm(e){if(!e||typeof e!="object")return;const t=e,i=t.mode==="manual"?"manual":t.mode==="auto"?"auto":void 0,s=dl(t.fontScale,.015,.12),a=t.fontWeight===700?700:t.fontWeight===400?400:void 0,o=dl(t.lineHeightFactor,.9,2),c=dl(t.speakerScale,.5,1.5);if(!(!i&&s===void 0&&a===void 0&&o===void 0&&c===void 0))return{...i?{mode:i}:{},...s!==void 0?{fontScale:s}:{},...a!==void 0?{fontWeight:a}:{},...o!==void 0?{lineHeightFactor:o}:{},...c!==void 0?{speakerScale:c}:{}}}function Vu(e){if(!e||typeof e!="object")return;const t=e,i=dl(t.paddingX,0,.25),s=dl(t.paddingY,0,.25),a=dl(t.cornerRadius,0,.49);if(!(i===void 0&&s===void 0&&a===void 0))return{...i!==void 0?{paddingX:i}:{},...s!==void 0?{paddingY:s}:{},...a!==void 0?{cornerRadius:a}:{}}}function To(e,t,i,s){const{minFontSize:a,maxFontSize:o}=I3(t),c=vm(e.textStyle),h=Vu(e.bubbleStyle);return{minFontSize:a,maxFontSize:o,hasSpeaker:e.type!=="sfx"&&!!e.speaker,...(c==null?void 0:c.lineHeightFactor)!==void 0?{lineHeightFactor:c.lineHeightFactor}:{},...(c==null?void 0:c.speakerScale)!==void 0?{speakerScale:c.speakerScale}:{},...(c==null?void 0:c.fontWeight)!==void 0?{fontWeight:c.fontWeight}:{},...(c==null?void 0:c.mode)==="manual"&&c.fontScale!==void 0?{fontSize:Math.max(1,t*c.fontScale)}:{},...(h==null?void 0:h.paddingX)!==void 0?{paddingX:i*h.paddingX}:{},...(h==null?void 0:h.paddingY)!==void 0?{paddingY:s*h.paddingY}:{}}}function $S(e,t,i){const s=Vu(e.bubbleStyle);return(s==null?void 0:s.cornerRadius)!==void 0?Math.min(t,i)*s.cornerRadius:void 0}function FS(e,t){const i=Math.min(e,t);return Math.max(0,Math.min(i*.4,i/2))}function ny(e,t,i,s,a){const o=Math.max(0,i-2*s),c=Math.max(1,Math.min(a,o)/2),h=t+s+c,p=t+i-s-c;return{center:p>=h?Ar(e,h,p):t+i/2,half:c}}function ym(e,t,i,s,a,o){const c=e+i/2,h=t+s/2,p=e+a.x*i,f=t+a.y*s;if(p>=e&&p<=e+i&&f>=t&&f<=t+s)return null;const _=p-c,x=f-h,b=Math.max(6,Math.min(i,s)*.3),v=o??FS(i,s);if(Math.abs(x)>=Math.abs(_)){const E=x>=0?t+s:t,{center:L,half:I}=ny(p,e,i,v,b);return{tip:{x:p,y:f},base1:{x:L-I,y:E},base2:{x:L+I,y:E}}}const S=_>=0?e+i:e,{center:N,half:M}=ny(f,t,s,v,b);return{tip:{x:p,y:f},base1:{x:S,y:N-M},base2:{x:S,y:N+M}}}function U3(e){return e.type!=="speech"||!e.tailAnchor?!1:ym(0,0,1,1,e.tailAnchor)!==null}function $3(e,t,i,s,a,o){const c=o??FS(i,s),h=e+i,p=t+s,f=!!a&&a.base1.y===t&&a.base2.y===t,_=!!a&&a.base1.x===h&&a.base2.x===h,x=!!a&&a.base1.y===p&&a.base2.y===p,b=!!a&&a.base1.x===e&&a.base2.x===e,v=[{k:"M",x:e+c,y:t}];return f&&a&&v.push({k:"L",x:a.base1.x,y:t},{k:"L",x:a.tip.x,y:a.tip.y},{k:"L",x:a.base2.x,y:t}),v.push({k:"L",x:h-c,y:t},{k:"A",cornerX:h,cornerY:t,x:h,y:t+c,r:c}),_&&a&&v.push({k:"L",x:h,y:a.base1.y},{k:"L",x:a.tip.x,y:a.tip.y},{k:"L",x:h,y:a.base2.y}),v.push({k:"L",x:h,y:p-c},{k:"A",cornerX:h,cornerY:p,x:h-c,y:p,r:c}),x&&a&&v.push({k:"L",x:a.base2.x,y:p},{k:"L",x:a.tip.x,y:a.tip.y},{k:"L",x:a.base1.x,y:p}),v.push({k:"L",x:e+c,y:p},{k:"A",cornerX:e,cornerY:p,x:e,y:p-c,r:c}),b&&a&&v.push({k:"L",x:e,y:a.base2.y},{k:"L",x:a.tip.x,y:a.tip.y},{k:"L",x:e,y:a.base1.y}),v.push({k:"L",x:e,y:t+c},{k:"A",cornerX:e,cornerY:t,x:e+c,y:t,r:c}),v}function qS(e,t,i,s,a,o){const c=$3(e,t,i,s,a,o).map(h=>h.k==="A"?`A ${h.r} ${h.r} 0 0 1 ${h.x} ${h.y}`:`${h.k} ${h.x} ${h.y}`);return c.push("Z"),c.join(" ")}function F3(e){return e.x<-1e-6||e.y<-1e-6||e.x+e.width>1+1e-6||e.y+e.height>1+1e-6}let ry=0;function Lp(e,t=.1,i=.1){return ry++,{id:`overlay-${Date.now()}-${ry}`,type:e,x:t,y:i,width:e==="sfx"?.15:.25,height:e==="sfx"?.08:.12,text:"",...e==="speech"?{speaker:"",tailAnchor:{x:.5,y:1.2}}:{}}}function WS(e,t,i){return{width:Math.min(e==="sfx"?.3:.5,Math.max(.15,1-t)),height:Math.min(e==="sfx"?.1:.2,Math.max(.06,1-i))}}const du=.05;function Ki(e){return typeof e=="number"&&Number.isFinite(e)}function q3(e,t,i){const s=e.toLowerCase(),a=/\bleft\b/.test(s),o=/\bright\b/.test(s),c=/\b(?:top|upper)\b/.test(s),h=/\b(?:bottom|lower)\b/.test(s),p=/\b(?:center|centre|middle)\b/.test(s);if(!a&&!o&&!c&&!h&&!p)return null;const f=a?du:Ar(o?1-t-du:(1-t)/2,0,1),_=c?du:Ar(h?1-i-du:(1-i)/2,0,1);return{x:f,y:_}}let W3=0;function G3(e){if(!e||typeof e!="object")return null;const t=e,i=US.includes(t.type)?t.type:"speech",s=typeof t.text=="string"?t.text:"";let a=Ki(t.width)&&t.width>0?t.width:i==="sfx"?.15:.4,o=Ki(t.height)&&t.height>0?t.height:i==="sfx"?.08:.16,c,h;if(Ki(t.x)&&Ki(t.y))c=t.x,h=t.y;else{const b=typeof t.position=="string"?q3(t.position,a,o):null;if(!b)return null;c=b.x,h=b.y}c=Ar(c,0,1),h=Ar(h,0,1),a=Ar(a,.02,1),o=Ar(o,.02,1);const f={id:typeof t.id=="string"&&t.id?t.id:`overlay-norm-${++W3}`,type:i,x:c,y:h,width:a,height:o,text:s};if(i==="speech"){f.speaker=typeof t.speaker=="string"?t.speaker:"";const b=t.tailAnchor;f.tailAnchor=b&&Ki(b.x)&&Ki(b.y)?{x:b.x,y:b.y}:{x:.5,y:1.2}}else typeof t.speaker=="string"&&t.speaker&&(f.speaker=t.speaker);const _=vm(t.textStyle),x=Vu(t.bubbleStyle);return _&&(f.textStyle=_),x&&(f.bubbleStyle=x),f}function Y3(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.id=="string"&&!!t.id&&US.includes(t.type)&&Ki(t.x)&&Ki(t.y)&&Ki(t.width)&&Ki(t.height)&&typeof t.text=="string"}function V3(e){const t=Array.isArray(e)?e:[],i=[],s=[];let a=!Array.isArray(e);return t.forEach((o,c)=>{const h=G3(o);if(!h){s.push({index:c,reason:"overlay has no numeric x/y/width/height and no recognizable position"}),a=!0;return}i.push(h),Y3(o)||(a=!0)}),{overlays:i,changed:a,invalid:s}}function r4(e){for(let t=0;t0&&i.height>0))return{valid:!1,error:`Overlay ${t+1}${i!=null&&i.type?` (${i.type})`:""} has invalid geometry — repair or re-place it in the lettering editor before export`};const a=vm(i==null?void 0:i.textStyle);if(i!=null&&i.textStyle&&!a)return{valid:!1,error:`Overlay ${t+1}${i!=null&&i.type?` (${i.type})`:""} has invalid typography controls — reset them in the lettering editor before export`};const o=Vu(i==null?void 0:i.bubbleStyle);if(i!=null&&i.bubbleStyle&&!o)return{valid:!1,error:`Overlay ${t+1}${i!=null&&i.type?` (${i.type})`:""} has invalid bubble controls — reset them in the lettering editor before export`}}return{valid:!0}}const sy=new Set(["speech","narration"]),K3=.12;function ay(e){return Ki(e==null?void 0:e.x)&&Ki(e==null?void 0:e.y)&&Ki(e==null?void 0:e.width)&&Ki(e==null?void 0:e.height)&&e.width>0&&e.height>0}function X3(e,t=K3){const i=[];for(let s=0;s0?f/_:0;x>=t&&i.push({indexA:s,indexB:o,idA:a.id,idB:c.id,ratio:x})}}return i}function gn(e){return e.kind==="text"}function Z3(e){return!!e.finalImagePath||!!e.exportedAt?{key:"review",label:"Review final panel",opensEditor:!0}:e.cleanImagePath||gn(e)?{key:"letter",label:"Letter this cut",opensEditor:!0}:{key:"add-art",label:"Add clean art for this cut",opensEditor:!1}}function GS(e,t=H3){return!e.finalImagePath||!(e.overlays??[]).some(U3)?!1:(e.finalRendererVersion??0)0)||!(s>0)?null:{width:ly,height:Math.round(ly*s/i)}}function fu({cut:e}){return e.dialogue.length>0||e.narration||e.sfx?d.jsxs("div",{className:"space-y-1.5","data-testid":`cut-${e.id}-overlay`,children:[e.dialogue.map((i,s)=>d.jsxs("div",{className:"flex gap-2 text-xs",children:[d.jsxs("span",{className:"font-medium text-foreground flex-shrink-0",children:[i.speaker,":"]}),d.jsx("span",{className:"text-foreground",children:i.text})]},s)),e.narration&&d.jsx("div",{className:"border-l-2 border-border pl-3",children:d.jsx("p",{className:"text-xs text-muted italic",children:e.narration})}),e.sfx&&d.jsxs("p",{className:"text-xs font-mono text-muted",children:["SFX: ",e.sfx]})]}):null}function Q3({cut:e,storyName:t,authFetch:i,onEditCut:s}){const a=!!e.finalImagePath,o=!!e.cleanImagePath,c=a||o,h=e.dialogue.length>0||!!e.narration||!!e.sfx,p=e.kind==="text";return d.jsxs("div",{className:"space-y-2",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs("span",{className:"text-[10px] font-mono text-muted bg-surface border border-border rounded px-1.5 py-0.5",children:["#",e.id]}),d.jsx("span",{className:"text-[10px] font-mono text-muted",children:e.shotType}),e.characters.length>0&&d.jsx("span",{className:"text-[10px] text-muted truncate",children:e.characters.join(", ")})]}),a&&d.jsx(ty,{storyName:t,assetPath:e.finalImagePath,authFetch:i,alt:e.description||`Cut ${e.id}`}),!a&&o&&d.jsxs("div",{className:"border border-border rounded overflow-hidden",children:[d.jsx(ty,{storyName:t,assetPath:e.cleanImagePath,authFetch:i,alt:e.description||`Cut ${e.id}`}),d.jsx("div",{className:"px-3 py-2 bg-surface/80 border-t border-border",children:d.jsx(fu,{cut:e})})]}),!c&&p&&d.jsxs("div",{className:"w-full border border-border rounded p-4 space-y-2",style:{background:e.background||void 0},"data-testid":`cut-${e.id}-textpanel`,children:[d.jsx("span",{className:"text-[10px] font-mono text-muted",children:"Text panel"}),h?d.jsx(fu,{cut:e}):d.jsx("p",{className:"text-xs text-muted italic",children:"Empty text panel — open the editor to add text."})]}),!c&&!p&&d.jsxs("div",{className:"w-full bg-surface border border-dashed border-border rounded p-4 space-y-2","data-testid":`cut-${e.id}-pending`,children:[d.jsxs("div",{className:"aspect-video flex flex-col items-center justify-center gap-1 text-center",children:[d.jsx("span",{className:"text-xs text-muted font-medium",children:"Image pending"}),d.jsx("span",{className:"text-[10px] text-muted",children:"Planned image cut — generate & upload the art"})]}),h&&d.jsxs("div",{className:"border-t border-dashed border-border pt-2 space-y-1",children:[d.jsx("span",{className:"text-[10px] font-mono text-muted",children:"Planned text (will be lettered onto the image)"}),d.jsx(fu,{cut:e})]})]}),e.description&&d.jsx("p",{className:"text-xs text-muted italic",children:e.description}),a&&d.jsx(fu,{cut:e}),s&&(()=>{const f=Z3(e);return d.jsx("button",{type:"button","data-testid":`cut-${e.id}-cta`,"data-cut-action":f.key,onClick:()=>s(e.id,f.opensEditor),className:"w-full px-3 py-1.5 text-xs font-medium rounded bg-accent text-white hover:bg-accent-dim",children:f.label})})()]})}function J3({storyName:e,fileName:t,authFetch:i,onEditCut:s}){const[a,o]=w.useState(null),[c,h]=w.useState(!0),[p,f]=w.useState(null),_=t.replace(/\.md$/,""),x=w.useCallback(async()=>{h(!0),f(null);try{const b=await i(`/api/stories/${e}/cuts/${_}`);if(b.status===404){o(null),h(!1);return}if(!b.ok){const S=await b.json();f(S.error||"Failed to load cuts"),h(!1);return}const v=await b.json();o(v)}catch{f("Failed to load cuts")}finally{h(!1)}},[i,e,_]);return w.useEffect(()=>{x();const b=setInterval(x,5e3);return()=>clearInterval(b)},[x]),c&&!a?d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Loading cuts..."}):p?d.jsxs("div",{className:"h-full flex flex-col items-center justify-center gap-2 px-4 text-center","data-testid":"cuts-error",children:[d.jsx("p",{className:"text-sm text-error font-medium",children:"Invalid cuts file"}),d.jsx("p",{className:"text-xs text-error",children:p}),d.jsxs("p",{className:"text-xs text-muted max-w-sm",children:[_,".cuts.json must follow the OWS v1 schema. Ask Claude to regenerate it using the v1 cuts schema shown in the cartoon writing instructions."]}),d.jsx("button",{onClick:x,className:"text-xs text-accent hover:text-accent-dim",children:"Retry"})]}):!a||a.cuts.length===0?d.jsxs("div",{className:"h-full flex flex-col items-center justify-center gap-2 px-4 text-center",children:[d.jsx("p",{className:"text-sm text-muted",children:"No cuts yet"}),d.jsx("p",{className:"text-xs text-muted",children:"Ask Claude to create a cut plan for this episode."})]}):d.jsx("div",{className:"h-full overflow-y-auto",children:d.jsx("div",{className:"max-w-lg mx-auto px-4 py-6 space-y-6",children:a.cuts.map(b=>d.jsx(Q3,{cut:b,storyName:e,authFetch:i,onEditCut:s},b.id))})})}const oy=/!\[[^\]]*\]\([^)]*\)/g,eD=//g,VS=200;function tD(e){const t=(e.match(oy)||[]).length,i=e.length,s=e.replace(eD," ").replace(oy," ").replace(/\s+/g," ").trim();return{imageCount:t,charCount:i,nonImageProse:s,nonImageProsePreview:s.slice(0,VS)}}function iD(e){return`${e}: re-export required before publish — this final image uses an older speech-bubble tail style that can show a visible seam`}const nD=[/placeholder only/i,/\bOWS (?:should )?generates? the publish markdown/i,/generate(?:s|d)? the publish markdown from/i,/after clean images are approved/i,/lettered final images are created/i,/do not hand-?write/i,/\b(?:TODO|FIXME)\b/];function rD(e){for(const t of nD){const i=e.match(t);if(i)return i[0]}return null}function Sm(e,t){const i=``,s=``,a=e.indexOf(i),o=e.indexOf(s);return a===-1||o===-1||ob[1].trim());x.length===0?i.push(`${p}: block has no image reference`):x.length>1?i.push(`${p}: block must contain exactly one image reference`):h.uploadedUrl&&x[0]!==h.uploadedUrl&&i.push(`${p}: image URL does not match the recorded uploaded URL`)}/awaiting upload|image pending|final image pending|pending upload/i.test(e)&&i.push("Markdown contains awaiting-upload placeholders");const s=rD(e);s&&i.push(`This episode still has placeholder/instructional text ("${s.slice(0,60)}") — remove it or re-run “Prepare episode for publish” so the published episode is images only`);const a=new Set(t.map(c=>c.uploadedUrl).filter(c=>!!c&&/^https?:\/\//i.test(c))),o=[...e.matchAll(/!\[[^\]]*\]\(([^)]*)\)/g)];for(const c of o){const h=c[1].trim();/^https?:\/\//i.test(h)?a.has(h)||i.push(`Image reference is not a recorded uploaded cut URL: ${h.slice(0,60)}`):i.push(`Invalid image reference (not an http(s) URL): ${h.slice(0,60)}`)}return e.length>1e4&&i.push(`Markdown is ${e.length} chars (limit 10,000)`),{ready:i.length===0,issues:i}}function XS(e,t){const i=t.length;if(i===0)return{stage:"not-started",issues:[],awaitingCount:0,totalCuts:0};if(sD(e,t))return{stage:"planning",issues:[],awaitingCount:0,totalCuts:i};const{ready:s,issues:a}=KS(e,t);if(s)return{stage:"ready",issues:[],awaitingCount:0,totalCuts:i};const o=new Set;for(let p=0;p!c.has(p));return h.length>0?{stage:"error",issues:h,awaitingCount:o.size,totalCuts:i}:{stage:"awaiting-upload",issues:[],awaitingCount:o.size,totalCuts:i}}const Mf=[{key:"assemble",title:"Prepare the episode for publish",test:/markdown block|missing or incomplete/i},{key:"export",title:"Export final images",test:/re-export|older speech-bubble|visible seam/i},{key:"upload",title:"Upload final images",test:/not uploaded|no recorded uploaded url/i},{key:"images",title:"Fix image references",test:/image reference|not an http|does not match|exactly one image/i},{key:"cleanup",title:"Remove leftover text",test:/placeholder|instructional|awaiting-upload|awaiting upload/i},{key:"size",title:"Shorten the episode",test:/\blimit\b|\bchars\b/i}];function aD(e){const t=new Map,i=[],s=[];for(const o of e){const c=o.match(/^Cut (\d+): (.+)$/);if(c){const h=c[2];t.has(h)||(t.set(h,[]),i.push(h)),t.get(h).push(Number(c[1]))}else s.push(o)}return[...i.map(o=>{const c=t.get(o).slice().sort((p,f)=>p-f);return`${c.length===1?`Cut ${c[0]}`:`Cuts ${c.join(", ")}`}: ${o}`}),...s]}function ZS(e){const t=c=>{var h;return((h=Mf.find(p=>p.test.test(c)))==null?void 0:h.key)??"other"},i=new Map;for(const c of e){const h=t(c);i.has(h)||i.set(h,[]),i.get(h).push(c)}const s=[...Mf.map(c=>c.key),"other"],a=c=>{var h;return((h=Mf.find(p=>p.key===c))==null?void 0:h.title)??"Other issues"},o=[];for(const c of s){const h=i.get(c);!h||h.length===0||o.push({key:c,title:a(c),lines:aD(h)})}return o}const lD=220,Bf=/^(genre|logline|synopsis|premise|setting|tone|theme|themes|summary|hook|characters?|cast|arc|status|word\s*count|length|title)\b\s*[:\-–]/i;function wm(e){const t=[],i=[],s=e??"",a=s.match(/^#[ \t]+(.+)$/m),o=!!(a&&a[1].trim());o||t.push("Add a “# Title” heading — the Story opening needs a real title readers see first.");const c=s.replace(/^#\s+.+$/m,"").trim();if(c.lengthx.trim()).filter(Boolean),p=h.filter(x=>/^([-*+]|\d+[.)])\s/.test(x)||Bf.test(x)).length,f=c.split(/\n\s*\n/).map(x=>x.trim()).filter(Boolean),_=f.some(x=>x.length>=120&&!/^([-*+]|\d+[.)])\s/.test(x)&&!Bf.test(x));h.length>0&&p/h.length>=.5||!_?t.push("This reads like a synopsis or outline. Write the Genesis as a reader-facing opening scene that sets up the first beat and stakes, then bridges into Episode 01 — not a logline, genre pitch, or character list."):f.filter(b=>b.length>=40&&!/^([-*+]|\d+[.)])\s/.test(b)&&!Bf.test(b)).length<2&&t.push("Give the opening room to build: open across a few short paragraphs — the premise, what the lead wants, and the hook — that lead into Episode 01, instead of a single dense block that drops readers into a cold scene.")}return{hasTitle:o,blockers:t,warnings:i}}function oD(e){return/\.(webp|jpe?g)$/i.test(e)}function Op(e){var c,h;let t=0,i=0,s=0,a=0,o=0;for(const p of e)gn(p)?(((h=p.overlays)==null?void 0:h.length)??0)>0&&s++:(t++,p.cleanImagePath&&oD(p.cleanImagePath)&&(i++,(((c=p.overlays)==null?void 0:c.length)??0)>0&&s++)),p.finalImagePath&&p.exportedAt&&a++,p.uploadedUrl&&o++;return{total:e.length,needClean:t,withClean:i,withText:s,exported:a,uploaded:o}}const cD={plan:"Plan cuts",clean:"Create clean images",letter:"Add speech bubbles & captions",export:"Export final images",upload:"Upload final images",publish:"Publish to PlotLink"};function So(e,t){return`${e} / ${t} cut${t===1?"":"s"}`}function uD(e){const{cuts:t,published:i=!1}=e,s=Op(t);if(s.total===0)return{steps:[],nextStep:null};const a=s.total>0,o=a&&s.withClean===s.needClean,c=o&&s.withText===s.total,h=c&&s.exported===s.total,p=h&&s.uploaded===s.total,_={plan:a,clean:o,letter:c,export:h,upload:p,publish:p&&i},x=["plan","clean","letter","export","upload","publish"],b=x.findIndex(L=>!_[L]),v=L=>s.needClean>0?So(L,s.needClean):"no image cuts",S={plan:So(s.total,s.total),clean:v(s.withClean),letter:So(s.withText,s.total),export:So(s.exported,s.total),upload:So(s.uploaded,s.total),publish:null},N=x.map((L,I)=>({key:L,label:cD[L],status:b===-1||IVS,a=fD({stage:t,imageCount:i.imageCount,hasNonImageProse:i.nonImageProse.length>0});return d.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"cartoon-publish-preview",children:[d.jsxs("div",{className:"px-4 py-2 border-b border-border text-[10px] text-muted flex flex-wrap items-center gap-x-3 gap-y-1","data-testid":"cartoon-publish-summary",children:[d.jsxs("span",{children:[i.imageCount," image",i.imageCount===1?"":"s"]}),d.jsxs("span",{children:[i.charCount.toLocaleString()," / 10,000 chars"]}),d.jsx("span",{className:`rounded-full px-2 py-0.5 font-medium ${a.possible?"bg-green-100 text-green-800":"bg-background text-muted"}`,"data-testid":"publish-possible",children:a.possible?"Publish possible":"Publish not possible yet"}),d.jsx("span",{className:`rounded-full px-2 py-0.5 font-medium ${a.recommended?"bg-green-100 text-green-800":a.tone==="warning"?"bg-amber-100 text-amber-800":"bg-background text-muted"}`,"data-testid":"publish-recommended",children:a.recommended?"Recommended":"Not recommended yet"})]}),d.jsxs("div",{className:`px-4 py-2 border-b text-[11px] ${mD[a.tone]}`,"data-testid":"cartoon-publish-verdict",children:[d.jsx("p",{className:"font-medium",children:a.headline}),a.detail&&d.jsx("p",{className:"mt-0.5 opacity-90",children:a.detail}),a.action&&d.jsxs("p",{className:"mt-0.5 opacity-90",children:["→ ",a.action]})]}),i.nonImageProse&&d.jsxs("div",{className:"px-4 py-2 border-b border-amber-300 bg-amber-50 text-[11px] text-amber-800","data-testid":"cartoon-nonimage-prose",children:[d.jsx("p",{className:"font-medium",children:"⚠ Non-image text in the published markdown:"}),d.jsxs("p",{className:"font-mono mt-1 whitespace-pre-wrap break-words",children:[i.nonImageProsePreview,s?"…":""]}),d.jsx("p",{className:"mt-1",children:"This text publishes verbatim around the comic images. Remove it (or re-run “Prepare episode for publish”) if it is planning or placeholder prose."})]}),d.jsx("div",{className:"max-w-lg mx-auto px-4 py-6",children:e.trim()?d.jsx("div",{className:"prose max-w-none",children:d.jsx(oS,{remarkPlugins:[uS,BS],rehypePlugins:[[PS,pD]],children:e})}):d.jsx("p",{className:"text-muted italic text-sm","data-testid":"cartoon-publish-empty",children:"No publish markdown yet — build it from the cut plan (Edit → Upload & Prepare for Publish)."})})]})}const xD="modulepreload",_D=function(e){return"/"+e},cy={},uy=function(t,i,s){let a=Promise.resolve();if(i&&i.length>0){let c=function(f){return Promise.all(f.map(_=>Promise.resolve(_).then(x=>({status:"fulfilled",value:x}),x=>({status:"rejected",reason:x}))))};document.getElementsByTagName("link");const h=document.querySelector("meta[property=csp-nonce]"),p=(h==null?void 0:h.nonce)||(h==null?void 0:h.getAttribute("nonce"));a=c(i.map(f=>{if(f=_D(f),f in cy)return;cy[f]=!0;const _=f.endsWith(".css"),x=_?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${f}"]${x}`))return;const b=document.createElement("link");if(b.rel=_?"stylesheet":xD,_||(b.as="script"),b.crossOrigin="",b.href=f,p&&b.setAttribute("nonce",p),document.head.appendChild(b),_)return new Promise((v,S)=>{b.addEventListener("load",v),b.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${f}`)))})}))}function o(c){const h=new Event("vite:preloadError",{cancelable:!0});if(h.payload=c,window.dispatchEvent(h),!h.defaultPrevented)throw c}return a.then(c=>{for(const h of c||[])h.status==="rejected"&&o(h.reason);return t().catch(o)})},Cm=[{family:"Noto Sans",googleFontsId:"Noto+Sans",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Sans/about",category:"body",weights:[400,500,700],languages:["English","Spanish","French","Portuguese","Russian","Others"]},{family:"Noto Sans KR",googleFontsId:"Noto+Sans+KR",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Sans+KR/about",category:"body",weights:[400,500,700],languages:["Korean"]},{family:"Noto Sans JP",googleFontsId:"Noto+Sans+JP",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Sans+JP/about",category:"body",weights:[400,500,700],languages:["Japanese"]},{family:"Noto Sans SC",googleFontsId:"Noto+Sans+SC",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Sans+SC/about",category:"body",weights:[400,500,700],languages:["Chinese"]},{family:"Noto Sans Devanagari",googleFontsId:"Noto+Sans+Devanagari",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Sans+Devanagari/about",category:"body",weights:[400,500,700],languages:["Hindi"]},{family:"Noto Naskh Arabic",googleFontsId:"Noto+Naskh+Arabic",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Naskh+Arabic/about",category:"body",weights:[400,500,700],languages:["Arabic"]},{family:"Bangers",googleFontsId:"Bangers",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/specimen/Bangers/about",category:"display",weights:[400],languages:[]}],bD="system-ui, sans-serif",vD=Cm.find(e=>e.family==="Noto Sans"),yD=Cm.find(e=>e.category==="display");function QS(e){return Cm.find(i=>i.category==="body"&&i.languages.includes(e))||vD}function JS(){return yD}function e1(e){const t=e.weights.join(";");return`https://fonts.googleapis.com/css2?family=${e.googleFontsId}:wght@${t}&display=swap`}function Ou(e){return`"${e.family}", ${bD}`}function SD(e,t={}){var a,o,c,h;const i=!t.staleExport&&(!!e.finalImagePath||!!e.exportedAt),s=!t.staleExport&&(!!e.uploadedUrl||!!e.uploadedCid);return{hasCleanImage:!!e.cleanImagePath,hasScriptText:(((a=e.dialogue)==null?void 0:a.length)??0)>0||!!((o=e.narration)!=null&&o.trim())||!!((c=e.sfx)!=null&&c.trim()),bubblesPlaced:((h=e.overlays)==null?void 0:h.length)??0,exported:i,uploaded:s}}function cl(e){return JSON.stringify((e??[]).map(t=>[t.type,t.x,t.y,t.width,t.height,t.text,t.speaker??"",t.tailAnchor??null,t.textStyle??null,t.bubbleStyle??null]))}function wD(e){return!e.exported&&!e.uploaded?!1:e.baselineSig!==cl(e.current)}function km(e){var i,s;const t=[];return(e.dialogue??[]).forEach((a,o)=>{var c;(c=a==null?void 0:a.text)!=null&&c.trim()&&t.push({type:"speech",speaker:a.speaker,text:a.text.trim(),key:`speech-${o}`})}),(i=e.narration)!=null&&i.trim()&&t.push({type:"narration",text:e.narration.trim(),key:"narration"}),(s=e.sfx)!=null&&s.trim()&&t.push({type:"sfx",text:e.sfx.trim(),key:"sfx"}),t}function CD(e,t,i){if(e==="narration")return{x:.08,y:.05+Math.min(t,2)*.18};if(e==="sfx"){const c=t%2,h=Math.floor(t/2);return{x:c===0?.1:.62,y:.68+h*.12}}const s=Math.floor(t/2),a=t%2===0,o=.08+s*Math.max(.15,Math.min(.22,i>4?.16:.2));return{x:a?.05:.45,y:o}}function hy(e){const t=km(e);return t.map((i,s)=>{const{x:a,y:o}=CD(i.type,s,t.length),c=Lp(i.type,a,o),h=WS(i.type,a,o);return{...c,...h,text:i.text,...i.type==="speech"?{speaker:i.speaker??""}:{}}})}function An(e,t){return e*t}function dy(e,t){return t===0?0:e/t}function fy(e){const t=`gfont-${e.googleFontsId}`;if(document.getElementById(t))return;const i=document.createElement("link");i.id=t,i.rel="stylesheet",i.href=e1(e),document.head.appendChild(i)}const ku={speech:"Speech",narration:"Narration",sfx:"SFX"},kD={speech:"border-foreground/40",narration:"border-muted/40",sfx:"border-accent/40"};function Lf(e){const t=(e.speaker||e.text||"").trim().replace(/\s+/g," ");return t?`“${t.length>18?`${t.slice(0,18)}…`:t}”`:ku[e.type]}const py=.05,ED=[{key:"down",label:"Down",anchor:{x:.5,y:1.2}},{key:"up",label:"Up",anchor:{x:.5,y:-.2}},{key:"left",label:"Left",anchor:{x:-.2,y:.5}},{key:"right",label:"Right",anchor:{x:1.2,y:.5}}];function pu(e,t,i){return Math.min(i,Math.max(t,e))}function ND({storyName:e,cut:t,plotFile:i,onSave:s,onClose:a,onExported:o,language:c="English",authFetch:h,targetLabel:p,returnOnSave:f=!1,workspaceVisible:_=!1,onToggleWorkspaceVisible:x}){var Gt,pi,Rt,St,Yt,ot,Ht;const b=QS(c),v=JS(),S=Ou(b),N=Ou(v);w.useEffect(()=>{fy(b),fy(v)},[b,v]),w.useEffect(()=>{let U=!1;return G(!1),(async()=>{try{const{ensureFontsReady:Ce}=await uy(async()=>{const{ensureFontsReady:Ae}=await import("./export-cut-BeffiHI_.js");return{ensureFontsReady:Ae}},[]);await Ce([b.family,v.family])}catch{}U||G(!0)})(),()=>{U=!0}},[b.family,v.family]);const M=bm(e,t.cleanImagePath,h),E=w.useMemo(()=>V3(t.overlays),[t.overlays]),L=E.invalid.length,[I,A]=w.useState(!1),q=L===0&&E.changed&&E.overlays.length>0,[R,ne]=w.useState(()=>E.overlays),[ue,ye]=w.useState(()=>cl(E.overlays)),B=w.useRef(null),re=w.useCallback(U=>(Ce,Ae,Ne=400)=>{var Ue;!B.current&&typeof document<"u"&&(B.current=document.createElement("canvas"));const Ge=(Ue=B.current)==null?void 0:Ue.getContext("2d");return Ge?(Ge.font=`${Ne} ${Ae}px ${U}`,Ge.measureText(Ce).width):Ce.length*Ae*.5},[]),[$,G]=w.useState(!1),[V,H]=w.useState(null),[T,z]=w.useState(!1),[F,xe]=w.useState(!1),[j,D]=w.useState(null),[X,C]=w.useState(null),[Z,ae]=w.useState({x:0,y:0,width:0,height:0}),oe=w.useRef(null),K=w.useRef(null),he=w.useRef(null),ge=w.useCallback(()=>{const U=oe.current;if(!U)return;const Ce=U.clientWidth,Ae=U.clientHeight;let Ne,Ge;if(t.kind==="text"){const At=YS(t.aspectRatio)??{width:800,height:600};Ne=At.width,Ge=At.height}else{const At=K.current;if(!At||!At.naturalWidth)return;Ne=At.naturalWidth,Ge=At.naturalHeight}if(!Ce||!Ae)return;const Ue=Math.min(Ce/Ne,Ae/Ge),dt=Ne*Ue,_t=Ge*Ue;ae({x:(Ce-dt)/2,y:(Ae-_t)/2,width:dt,height:_t})},[t.kind,t.aspectRatio]);w.useEffect(()=>{const U=oe.current;if(!U)return;const Ce=new ResizeObserver(()=>ge());return Ce.observe(U),()=>Ce.disconnect()},[ge]);const De=w.useCallback(U=>{const Ce=WS(U.type,U.x,U.y),Ae=Ce.width,Ne=Math.max(.08,1-U.y);if(!U.text||!$||Z.width<=0)return Ce;const Ge=U.type==="sfx"?N:S,Ue=An(Ae,Z.width);let dt=U.type==="sfx"?.08:.12;for(let _t=0;_t<24;_t++){const At=Math.min(dt,Ne),Bt=An(At,Z.height);if(!jo(re(Ge),U.text,Ue,Bt,To({...U},Z.height||300,Ue,Bt)).overflow||At>=Ne)return{width:Ae,height:At};dt+=.03}return{width:Ae,height:Math.min(dt,Ne)}},[$,Z,re,S,N]),ze=w.useCallback(U=>{const Ce=Lp(U,.1+Math.random()*.3,.1+Math.random()*.3),Ae={...Ce,...De(Ce)};ne(Ne=>[...Ne,Ae]),H(Ae.id)},[De]),Fe=w.useCallback(U=>{const Ae={...Lp(U.type,.1+Math.random()*.3,.1+Math.random()*.3),text:U.text,...U.type==="speech"&&U.speaker?{speaker:U.speaker}:{}},Ne={...Ae,...De(Ae)};ne(Ge=>[...Ge,Ne]),H(Ne.id)},[De]),we=w.useCallback((U,Ce)=>{ne(Ae=>Ae.map(Ne=>Ne.id===U?{...Ne,...Ce}:Ne))},[]),He=w.useCallback(U=>{var dt;const Ce=Z.height||300,Ae=Z.width>0?An(U.width,Z.width):200,Ne=Z.height>0?An(U.height,Z.height):100,Ge=U.type==="sfx"?N:S,Ue=jo(re(Ge),U.text,Ae,Ne,To({...U,textStyle:void 0},Ce,Ae,Ne));we(U.id,{textStyle:{mode:"manual",fontScale:Ue.fontSize/Math.max(1,Ce),fontWeight:((dt=U.textStyle)==null?void 0:dt.fontWeight)??400,lineHeightFactor:Ue.fontSize>0?Ue.lineHeight/Ue.fontSize:1.2,speakerScale:Ue.fontSize>0&&Ue.speakerFontSize>0?Ue.speakerFontSize/Ue.fontSize:.8}})},[Z,N,S,re,we]),it=w.useCallback(U=>{ne(Ce=>Ce.filter(Ae=>Ae.id!==U)),H(null),z(!1)},[]),st=w.useCallback(()=>{H(null),z(!1)},[]),nt=w.useCallback((U,Ce)=>{U.stopPropagation(),H(Ce),z(!1)},[]),Nt=w.useCallback((U,Ce,Ae)=>{U.stopPropagation(),U.preventDefault();const Ne=R.find(Ge=>Ge.id===Ce);Ne&&(H(Ce),he.current={id:Ce,mode:Ae,startX:U.clientX,startY:U.clientY,origX:Ne.x,origY:Ne.y,origW:Ne.width,origH:Ne.height})},[R]);w.useEffect(()=>{const U=Ae=>{const Ne=he.current;if(!Ne||Z.width===0)return;const Ge=dy(Ae.clientX-Ne.startX,Z.width),Ue=dy(Ae.clientY-Ne.startY,Z.height);if(Ne.mode==="move"){const dt=pu(Ne.origX+Ge,0,1-Ne.origW),_t=pu(Ne.origY+Ue,0,1-Ne.origH);we(Ne.id,{x:dt,y:_t})}else{const dt=pu(Ne.origW+Ge,py,1-Ne.origX),_t=pu(Ne.origH+Ue,py,1-Ne.origY);we(Ne.id,{width:dt,height:_t})}},Ce=()=>{he.current=null};return window.addEventListener("mousemove",U),window.addEventListener("mouseup",Ce),()=>{window.removeEventListener("mousemove",U),window.removeEventListener("mouseup",Ce)}},[Z,we]);const Be=w.useCallback(async()=>{var U;C(null);try{const Ce=cl(R),Ae=((U=t.aiDraft)==null?void 0:U.status)==="generated"&&Ce!==(t.aiDraft.baseSig??"")?{...t.aiDraft,status:"edited",updatedAt:new Date().toISOString()}:t.aiDraft??void 0;await s(R,Ae??null),f&&a()}catch(Ce){C(Ce instanceof Error?Ce.message:"Failed to save overlays")}},[R,s,a,f,t.aiDraft]),ct=w.useCallback(async()=>{if(L>0&&!I){const U=L;D(`${U} overlay${U===1?"":"s"} from the cut plan ${U===1?"has":"have"} no usable position and cannot be exported — re-place ${U===1?"it":"them"} or discard ${U===1?"it":"them"} first.`);return}xe(!0),D(null);try{await s(R);const{exportCut:U,ensureFontsReady:Ce}=await uy(async()=>{const{exportCut:Vt,ensureFontsReady:an}=await import("./export-cut-BeffiHI_.js");return{exportCut:Vt,ensureFontsReady:an}},[]),Ae=R.some(Vt=>Vt.type==="sfx"),Ne=[b.family,...Ae?[v.family]:[]],{ready:Ge,missing:Ue}=await Ce(Ne);if(!Ge){D(`Fonts not loaded: ${Ue.join(", ")}. Check your connection and retry.`),xe(!1);return}if(t.cleanImagePath&&!M.url){D(M.error?"Clean image failed to load — cannot export. Retry once it renders.":"Clean image still loading — wait for it to render, then export."),xe(!1);return}const dt=M.url,_t=await U(dt,R,S,N,{narration:t.narration,dialogue:t.dialogue},t.kind==="text"?{background:t.background,aspectRatio:t.aspectRatio}:void 0),At=new FormData,Bt=_t.type==="image/webp"?"webp":"jpg";At.append("file",_t,`cut-${t.id}.${Bt}`);const Ut=await h(`/api/stories/${e}/cuts/${i}/export-final/${t.id}`,{method:"POST",body:At});if(Ut.ok)ye(cl(R)),o==null||o();else{const Vt=await Ut.json();D(Vt.error||"Export failed")}}catch(U){D(U instanceof Error?U.message:"Export failed")}finally{xe(!1)}},[t,M,R,e,i,b,v,S,N,h,s,o,L,I]),Te=R.find(U=>U.id===V),Wt=w.useMemo(()=>X3(R),[R]),vi=w.useRef(t.id);w.useEffect(()=>{vi.current!==t.id&&(vi.current=t.id,ye(cl(E.overlays)))},[t.id,E.overlays]);const Ct=wD({exported:!!t.finalImagePath||!!t.exportedAt,uploaded:!!t.uploadedUrl||!!t.uploadedCid,baselineSig:ue,current:R}),et=w.useMemo(()=>SD({...t,overlays:R},{staleExport:Ct}),[t,R,Ct]),ee=w.useMemo(()=>km(t),[t]),be=w.useMemo(()=>{const U={};for(const Ce of R){const Ae=F3(Ce);let Ne=!1;if($&&Z.width>0&&Ce.text){const Ge=Ce.type==="sfx"?N:S,Ue=An(Ce.width,Z.width),dt=An(Ce.height,Z.height);Ne=jo(re(Ge),Ce.text,Ue,dt,To(Ce,Z.height||300,Ue,dt)).overflow}(Ae||Ne)&&(U[Ce.id]={outOfBounds:Ae,overflow:Ne})}return U},[R,$,Z,re,S,N]),Me=Object.keys(be).length,$e=t.kind==="text",Xe=!t.cleanImagePath;return!$e&&Xe&&R.length===0&&!t.narration&&!((Gt=t.dialogue)!=null&&Gt.length)?d.jsx("div",{className:"h-full flex items-center justify-center text-sm text-muted",children:"No clean image — upload one first, or add overlays for a narration cut."}):d.jsxs("div",{className:"h-full flex flex-col","data-testid":"focused-lettering-editor",children:[d.jsxs("div",{className:"px-4 py-3 border-b border-border bg-surface/40 flex items-center justify-between gap-3",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"text-[10px] font-bold uppercase tracking-[0.16em] text-accent",children:"Focused lettering editor"}),d.jsx("span",{className:"text-xs font-mono text-muted",children:p??`Cut #${t.id}`})]}),d.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"Place bubbles, captions, SFX, or between-scene card text, then save back to the full cut review."}),d.jsxs("span",{className:"text-[10px] text-muted","data-testid":"overlay-count",children:[R.length," overlays"]})]}),d.jsxs("div",{className:"flex items-center gap-2 flex-wrap justify-end",children:[d.jsx("button",{onClick:a,className:"px-3 py-1 text-xs border border-border rounded text-muted hover:text-foreground","data-testid":"return-to-cut-review-btn",children:"Back to cut review"}),x&&d.jsx("button",{onClick:x,className:"px-3 py-1 text-xs border border-border rounded text-muted hover:border-accent hover:text-accent","data-testid":"toggle-work-area-btn",children:_?"Hide work area":"Show work area"}),d.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[d.jsx("button",{onClick:()=>ze("speech"),className:"px-2 py-0.5 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5","data-testid":"add-speech",children:"Speech"}),d.jsx("button",{onClick:()=>ze("narration"),className:"px-2 py-0.5 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5","data-testid":"add-narration",children:"Narration"}),d.jsx("button",{onClick:()=>ze("sfx"),className:"px-2 py-0.5 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5","data-testid":"add-sfx",children:"SFX"})]}),j&&d.jsx("span",{className:"text-[10px] text-error",children:j}),X&&d.jsx("span",{className:"text-[10px] text-error",children:X}),d.jsx("button",{onClick:ct,disabled:F,className:"px-3 py-1 text-xs border border-accent text-accent rounded hover:bg-accent/5 disabled:opacity-50","data-testid":"export-btn",children:F?"Exporting...":"Export"}),d.jsx("button",{onClick:()=>{Be()},className:"px-3 py-1 text-xs bg-accent text-white rounded hover:bg-accent-dim","data-testid":"save-lettering-btn",children:"Save"}),d.jsx("button",{onClick:a,className:"px-3 py-1 text-xs text-muted hover:text-foreground border border-border rounded","data-testid":"cancel-lettering-btn",children:"Cancel"})]})]}),L>0&&!I?d.jsxs("div",{className:"px-3 py-1 border-b border-border bg-error/10 text-[10px] text-error flex items-center gap-2 flex-wrap","data-testid":"overlay-repair-note",children:[d.jsxs("span",{children:[L," overlay",L===1?"":"s"," ","from the cut plan ",L===1?"has":"have"," no usable position and cannot be exported. Re-place"," ",L===1?"it":"them",", or"]}),d.jsxs("button",{onClick:()=>A(!0),"data-testid":"discard-invalid-overlays",className:"px-1.5 py-0.5 border border-error/40 rounded hover:bg-error/10",children:["discard ",L," unplaceable overlay",L===1?"":"s"]})]}):L>0?d.jsxs("div",{className:"px-3 py-1 border-b border-border bg-amber-500/10 text-[10px] text-amber-700","data-testid":"overlay-repair-note",children:["Discarded ",L," unplaceable overlay",L===1?"":"s"," — the export will not include"," ",L===1?"it":"them","."]}):q?d.jsx("div",{className:"px-3 py-1 border-b border-border bg-amber-500/10 text-[10px] text-amber-700","data-testid":"overlay-repair-note",children:"Auto-placed overlays from the cut plan — review their positions before exporting."}):null,Wt.length>0&&d.jsxs("div",{className:"px-3 py-1 border-b border-border bg-amber-500/10 text-[10px] text-amber-700","data-testid":"overlay-overlap-warning",children:["Cut #",t.id,": ",Wt.length," bubble"," ",Wt.length===1?"pair overlaps":"pairs overlap"," and may be hard to read —"," ",Wt.map(U=>`#${U.indexA+1} ${Lf(R[U.indexA])} ↔ #${U.indexB+1} ${Lf(R[U.indexB])}`).join("; "),". Move them apart, or export as-is if the overlap is intended."]}),d.jsx("div",{className:"px-3 py-1 border-b border-border flex items-center gap-3 flex-wrap text-[10px] text-muted","data-testid":"lettering-checklist",children:[["clean-image","Clean image",et.hasCleanImage],["script-text","Script text",et.hasScriptText],["bubbles",`Bubbles placed${et.bubblesPlaced?` (${et.bubblesPlaced})`:""}`,et.bubblesPlaced>0],["exported","Final exported",et.exported],["uploaded","Uploaded",et.uploaded]].map(([U,Ce,Ae])=>d.jsxs("span",{"data-testid":`lettering-check-${U}`,"data-done":Ae?"true":"false",className:`flex items-center gap-1 ${Ae?"text-green-700":"text-muted/70"}`,children:[d.jsx("span",{"aria-hidden":!0,children:Ae?"✓":"○"}),Ce]},U))}),Ct&&d.jsx("div",{className:"px-3 py-1 border-b border-border bg-amber-500/10 text-[10px] text-amber-700","data-testid":"lettering-stale-export-warning",children:"Bubbles changed since the last export — re-export this cut and upload the new final image before publishing."}),Me>0&&d.jsxs("div",{className:"px-3 py-1 border-b border-border bg-amber-500/10 text-[10px] text-amber-700","data-testid":"lettering-export-warning",children:[Me," bubble",Me===1?"":"s"," may not export cleanly:"," ",Object.entries(be).map(([U,Ce])=>{const Ae=R.findIndex(Ge=>Ge.id===U),Ne=[Ce.outOfBounds?"outside image":null,Ce.overflow?"text overflow":null].filter(Boolean).join(", ");return`#${Ae+1} ${Lf(R[Ae])} (${Ne})`}).join("; "),". Resize or reposition before exporting."]}),d.jsxs("div",{className:"flex-1 min-h-0 flex",children:[d.jsxs("div",{ref:oe,className:"flex-1 min-w-0 relative overflow-hidden bg-[#f8f5ef]",onClick:st,"data-testid":"editor-surface",children:[t.cleanImagePath&&M.error?d.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted text-xs","data-testid":"clean-image-error",children:"Clean image not available"}):t.cleanImagePath&&!M.url?d.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted text-xs","data-testid":"clean-image-loading",children:"Loading clean image…"}):t.cleanImagePath?d.jsx("img",{ref:K,src:M.url,alt:`Cut ${t.id} clean`,className:"w-full h-full object-contain",draggable:!1,onLoad:ge}):$e?Z.width>0&&d.jsx("div",{className:"absolute flex items-center justify-center text-muted text-xs",style:{left:Z.x,top:Z.y,width:Z.width,height:Z.height,background:t.background||"#ffffff"},"data-testid":"text-panel-canvas",children:"Text panel"}):d.jsx("div",{className:"w-full h-full bg-white flex items-center justify-center text-muted text-xs",ref:U=>{if(U&&Z.width===0){const Ce=U.getBoundingClientRect();Ce.width>0&&ae({x:0,y:0,width:Ce.width,height:Ce.height})}},children:"Narration cut"}),Z.width>0&&d.jsx("svg",{className:"absolute inset-0 w-full h-full pointer-events-none","data-testid":"balloon-layer",children:R.map(U=>{if(U.type!=="speech")return null;const Ce=Z.x+An(U.x,Z.width),Ae=Z.y+An(U.y,Z.height),Ne=An(U.width,Z.width),Ge=An(U.height,Z.height),Ue=$S(U,Ne,Ge),dt=U.tailAnchor?ym(Ce,Ae,Ne,Ge,U.tailAnchor,Ue):null,_t=Math.max(1.5,Z.height*.004),At=U.id===V;return d.jsx("path",{"data-testid":`balloon-${U.id}`,d:qS(Ce,Ae,Ne,Ge,dt,Ue),className:`fill-white/95 ${At?"stroke-accent":"stroke-[#1a1a1a]"}`,strokeWidth:At?_t+.5:_t,strokeLinejoin:"round"},U.id)})}),Z.width>0&&R.map(U=>{const Ce=Z.x+An(U.x,Z.width),Ae=Z.y+An(U.y,Z.height),Ne=An(U.width,Z.width),Ge=An(U.height,Z.height),Ue=U.id===V,dt=U.type==="speech",_t=U.type==="narration",At=!!be[U.id];return d.jsxs("div",{"data-testid":`overlay-${U.id}`,"data-warning":At?"true":"false",onClick:Bt=>nt(Bt,U.id),onMouseDown:Bt=>Nt(Bt,U.id,"move"),className:`absolute rounded cursor-move select-none ${dt?"":`border-2 ${kD[U.type]}`} ${_t?"bg-[#f4efe6]/85 rounded-md":""} ${Ue&&!dt?"ring-2 ring-accent":""} ${At?"ring-2 ring-amber-500":""}`,style:{left:Ce,top:Ae,width:Ne,height:Ge},children:[(()=>{var an,ri;const Bt=U.type==="sfx"?N:S;if(!U.text)return d.jsx("span",{className:"text-[9px] px-1 text-muted truncate block pointer-events-none",style:{fontFamily:Bt},children:ku[U.type]});const Ut=U.type!=="sfx"&&!!U.speaker;if(!$)return d.jsx("div",{className:"absolute inset-0 flex items-center justify-center px-1 overflow-hidden pointer-events-none text-center break-words",style:{fontFamily:Bt,fontSize:Math.max(9,Math.min(Ge*.05,16)),fontWeight:((an=U.textStyle)==null?void 0:an.fontWeight)??400},"data-testid":`overlay-text-${U.id}`,"data-fonts-ready":"false",children:Ut?`${U.speaker}: ${U.text}`:U.text});const Vt=jo(re(Bt),U.text,Ne,Ge,To(U,Z.height,Ne,Ge));return d.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center px-1 overflow-hidden pointer-events-none text-center",style:{fontFamily:Bt},"data-testid":`overlay-text-${U.id}`,"data-fonts-ready":"true",children:[Ut&&d.jsx("span",{className:"font-bold text-[#3a3a3a] block",style:{fontSize:Vt.speakerFontSize,lineHeight:1.2},children:U.speaker}),d.jsx("span",{className:"text-[#1a1a1a]",style:{fontSize:Vt.fontSize,lineHeight:`${Vt.lineHeight}px`,fontWeight:((ri=U.textStyle)==null?void 0:ri.fontWeight)??400},children:Vt.lines.map((Mn,Bn)=>d.jsx("span",{className:"block",children:Mn},Bn))})]})})(),Ue&&d.jsx("div",{onMouseDown:Bt=>{Bt.stopPropagation(),Nt(Bt,U.id,"resize")},className:"absolute bottom-0 right-0 w-2 h-2 bg-accent cursor-se-resize","data-testid":`resize-${U.id}`})]},U.id)})]}),d.jsxs("div",{className:"w-64 border-l border-border p-3 overflow-y-auto flex-shrink-0",children:[((pi=t.aiDraft)==null?void 0:pi.status)==="generated"&&d.jsxs("div",{className:"mb-3 rounded border border-accent/30 bg-accent/5 p-2 space-y-1","data-testid":"ai-draft-current-target",children:[d.jsx("p",{className:"text-[10px] font-bold uppercase tracking-[0.14em] text-accent",children:"AI draft ready"}),d.jsx("p",{className:"text-[11px] text-muted",children:"These first-pass overlays came from the cut script. Review and tune them here before exporting the final panel."})]}),ee.length>0&&d.jsxs("div",{className:"mb-3 space-y-1.5","data-testid":"script-insert-panel",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"From script"}),d.jsx("div",{className:"flex flex-col gap-1",children:ee.map(U=>d.jsxs("button",{onClick:()=>Fe(U),"data-testid":`script-insert-${U.key}`,title:`Add ${U.type} overlay with this text`,className:"text-left px-2 py-1 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5",children:[d.jsxs("span",{className:"font-medium text-accent",children:["+ ",ku[U.type]]})," ",d.jsxs("span",{className:"text-muted",children:[U.speaker?`${U.speaker}: `:"",U.text.length>32?`${U.text.slice(0,32)}…`:U.text]})]},U.key))})]}),Te?d.jsxs("div",{className:"space-y-3",children:[d.jsx("p",{className:"text-xs font-medium text-foreground",children:ku[Te.type]}),Te.speaker!==void 0&&d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Speaker"}),d.jsx("input",{value:Te.speaker||"",onChange:U=>we(Te.id,{speaker:U.target.value}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none",placeholder:"Character name","data-testid":"inspector-speaker"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Text"}),d.jsx("textarea",{value:Te.text,onChange:U=>we(Te.id,{text:U.target.value}),rows:3,className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent resize-none focus:border-accent focus:outline-none",placeholder:"Overlay text","data-testid":"inspector-text"})]}),d.jsx("button",{onClick:()=>we(Te.id,De(Te)),"data-testid":"inspector-fit-text",className:"w-full px-2 py-1 text-[11px] border border-border rounded hover:border-accent hover:text-accent",title:"Resize this overlay so its text fits without overflowing",children:"Fit box to text"}),d.jsxs("div",{className:"space-y-1.5 rounded border border-border/70 p-2","data-testid":"inspector-typography",children:[d.jsxs("div",{className:"flex items-center justify-between gap-2",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Typography"}),((Rt=Te.textStyle)==null?void 0:Rt.mode)==="manual"?d.jsx("button",{type:"button",onClick:()=>we(Te.id,{textStyle:void 0}),className:"px-1.5 py-0.5 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5","data-testid":"inspector-text-auto",children:"Auto-fit"}):d.jsx("button",{type:"button",onClick:()=>He(Te),className:"px-1.5 py-0.5 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5","data-testid":"inspector-text-manual",children:"Manual"})]}),((St=Te.textStyle)==null?void 0:St.mode)==="manual"?d.jsxs("div",{className:"space-y-1.5",children:[d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Font size (% panel height)"}),d.jsx("input",{type:"number",step:"0.1",min:"1.5",max:"12",value:((Te.textStyle.fontScale??.032)*100).toFixed(1),onChange:U=>we(Te.id,{textStyle:{...Te.textStyle,mode:"manual",fontScale:Math.max(.015,Math.min(.12,(parseFloat(U.target.value)||3.2)/100))}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-font-scale"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Weight"}),d.jsxs("select",{value:String(Te.textStyle.fontWeight??400),onChange:U=>we(Te.id,{textStyle:{...Te.textStyle,mode:"manual",fontWeight:U.target.value==="700"?700:400}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-font-weight",children:[d.jsx("option",{value:"400",children:"Regular"}),d.jsx("option",{value:"700",children:"Bold"})]})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Line height"}),d.jsx("input",{type:"number",step:"0.05",min:"0.9",max:"2",value:(Te.textStyle.lineHeightFactor??1.2).toFixed(2),onChange:U=>we(Te.id,{textStyle:{...Te.textStyle,mode:"manual",lineHeightFactor:Math.max(.9,Math.min(2,parseFloat(U.target.value)||1.2))}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-line-height"})]}),Te.type!=="sfx"&&d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Speaker scale"}),d.jsx("input",{type:"number",step:"0.05",min:"0.5",max:"1.5",value:(Te.textStyle.speakerScale??.8).toFixed(2),onChange:U=>we(Te.id,{textStyle:{...Te.textStyle,mode:"manual",speakerScale:Math.max(.5,Math.min(1.5,parseFloat(U.target.value)||.8))}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-speaker-scale"})]})]}):d.jsx("p",{className:"text-[10px] text-muted",children:"Auto-fit stays on by default and resizes text to the box."})]}),Te.type==="speech"&&(()=>{const U=Te.tailAnchor||{x:.5,y:1.2};return d.jsxs("div",{className:"space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Tail anchor"}),d.jsx("div",{className:"flex flex-wrap gap-1","data-testid":"inspector-tail-presets",children:ED.map(Ce=>d.jsx("button",{type:"button",onClick:()=>we(Te.id,{tailAnchor:Ce.anchor}),className:"px-1.5 py-0.5 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5","data-testid":`inspector-tail-${Ce.key}`,children:Ce.label},Ce.key))}),d.jsxs("div",{className:"flex gap-2",children:[d.jsxs("label",{className:"flex items-center gap-1 text-[10px] font-mono text-muted",children:["x",d.jsx("input",{type:"number",step:"0.1",value:U.x,onChange:Ce=>we(Te.id,{tailAnchor:{...U,x:parseFloat(Ce.target.value)||0}}),className:"w-14 px-1 py-0.5 text-[10px] border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-tail-x"})]}),d.jsxs("label",{className:"flex items-center gap-1 text-[10px] font-mono text-muted",children:["y",d.jsx("input",{type:"number",step:"0.1",value:U.y,onChange:Ce=>we(Te.id,{tailAnchor:{...U,y:parseFloat(Ce.target.value)||0}}),className:"w-14 px-1 py-0.5 text-[10px] border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-tail-y"})]})]})]})})(),Te.type!=="sfx"&&d.jsxs("div",{className:"space-y-1.5 rounded border border-border/70 p-2","data-testid":"inspector-bubble-style",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Bubble controls"}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Padding X (% width)"}),d.jsx("input",{type:"number",step:"1",min:"0",max:"25",value:((((Yt=Te.bubbleStyle)==null?void 0:Yt.paddingX)??.06)*100).toFixed(0),onChange:U=>we(Te.id,{bubbleStyle:{...Te.bubbleStyle,paddingX:Math.max(0,Math.min(.25,(parseFloat(U.target.value)||6)/100))}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-padding-x"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Padding Y (% height)"}),d.jsx("input",{type:"number",step:"1",min:"0",max:"25",value:((((ot=Te.bubbleStyle)==null?void 0:ot.paddingY)??.08)*100).toFixed(0),onChange:U=>we(Te.id,{bubbleStyle:{...Te.bubbleStyle,paddingY:Math.max(0,Math.min(.25,(parseFloat(U.target.value)||8)/100))}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-padding-y"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Corner roundness (% short side)"}),d.jsx("input",{type:"number",step:"1",min:"0",max:"49",value:((((Ht=Te.bubbleStyle)==null?void 0:Ht.cornerRadius)??.4)*100).toFixed(0),onChange:U=>we(Te.id,{bubbleStyle:{...Te.bubbleStyle,cornerRadius:Math.max(0,Math.min(.49,(parseFloat(U.target.value)||40)/100))}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-corner-radius"})]})]}),d.jsxs("div",{className:"text-[10px] text-muted","data-testid":"inspector-font",children:["Font:"," ",Te.type==="sfx"?v.family:b.family]}),d.jsxs("div",{className:"text-[10px] font-mono text-muted space-y-0.5",children:[d.jsxs("p",{children:["x: ",Te.x.toFixed(3),", y:"," ",Te.y.toFixed(3)]}),d.jsxs("p",{children:["w: ",Te.width.toFixed(3),", h:"," ",Te.height.toFixed(3)]})]}),d.jsx("button",{onClick:()=>{T?it(Te.id):z(!0)},className:"w-full px-2 py-1 text-xs text-error border border-error/30 rounded hover:bg-error/5","data-testid":"delete-overlay",children:T?"Click again to delete":"Delete"})]}):d.jsx("p",{className:"text-xs text-muted","data-testid":"inspector-empty",children:"Select an overlay to inspect."})]})]})]})}function my(e){const t=`gfont-${e.googleFontsId}`;if(document.getElementById(t))return;const i=document.createElement("link");i.id=t,i.rel="stylesheet",i.href=e1(e),document.head.appendChild(i)}function jD({storyName:e,assetPath:t,authFetch:i,alt:s,overlays:a,language:o="English",background:c,aspectRatio:h,className:p,onClick:f,testId:_}){const x=QS(o),b=JS(),v=Ou(x),S=Ou(b),N=bm(e,t,i),M=w.useRef(null),E=w.useMemo(()=>typeof document<"u"?document.createElement("canvas").getContext("2d"):null,[]),[L,I]=w.useState(!1),[A,q]=w.useState(()=>YS(h)??{width:800,height:600}),[R,ne]=w.useState({width:0,height:0});w.useEffect(()=>{my(x),my(b)},[x,b]),w.useEffect(()=>{let B=!1;return(async()=>{var re;try{(re=document.fonts)!=null&&re.load&&await Promise.all([document.fonts.load(`16px "${x.family}"`),document.fonts.load(`16px "${b.family}"`)])}catch{}B||I(!0)})(),()=>{B=!0}},[x.family,b.family]),w.useEffect(()=>{const B=M.current;if(!B)return;const re=new ResizeObserver(()=>{ne({width:B.clientWidth,height:B.clientHeight})});return re.observe(B),()=>re.disconnect()},[]);const ue=w.useCallback(B=>(re,$,G=400)=>E?(E.font=`${G} ${$}px ${B}`,E.measureText(re).width):re.length*$*.5,[E]),ye=d.jsx("div",{className:p??"w-full rounded border border-border bg-white","data-testid":_,ref:M,style:{aspectRatio:`${A.width} / ${A.height}`,maxHeight:"32rem"},children:d.jsxs("div",{className:"relative w-full h-full overflow-hidden rounded border border-border bg-white",children:[t?N.error||!N.loading&&!N.url?d.jsx("div",{className:"w-full h-full flex items-center justify-center text-[10px] text-muted bg-surface/40",children:"Image not available"}):N.url?d.jsx("img",{src:N.url,alt:s,className:"absolute inset-0 w-full h-full object-contain",draggable:!1,onLoad:B=>{const re=B.currentTarget.naturalWidth||A.width,$=B.currentTarget.naturalHeight||A.height;re>0&&$>0&&q({width:re,height:$})}}):d.jsx("div",{className:"w-full h-full flex items-center justify-center text-[10px] text-muted bg-surface/40",children:"Loading image…"}):d.jsx("div",{className:"absolute inset-0",style:{background:c||"#101820"}}),R.width>0&&R.height>0&&a.length>0&&d.jsxs(d.Fragment,{children:[d.jsx("svg",{className:"absolute inset-0 w-full h-full pointer-events-none","data-testid":_?`${_}-overlay-layer`:void 0,children:a.map(B=>{if(B.type!=="speech")return null;const re=B.x*R.width,$=B.y*R.height,G=B.width*R.width,V=B.height*R.height,H=$S(B,G,V),T=B.tailAnchor?ym(re,$,G,V,B.tailAnchor,H):null,z=Math.max(1.25,R.height*.004);return d.jsx("path",{"data-testid":_?`${_}-overlay-${B.id}`:void 0,d:qS(re,$,G,V,T,H),className:"fill-white/95 stroke-[#1a1a1a]",strokeWidth:z,strokeLinejoin:"round"},B.id)})}),a.map(B=>{var F;const re=B.x*R.width,$=B.y*R.height,G=B.width*R.width,V=B.height*R.height,H=B.type==="sfx"?S:v,T=B.type==="speech";B.type;const z=B.type!=="sfx"&&!!B.speaker;return d.jsx("div",{className:`absolute rounded overflow-hidden ${T?"":"border-2"} ${B.type==="narration"?"border-muted/40 bg-[#f4efe6]/85 rounded-md":B.type==="sfx"?"border-accent/40":""}`,style:{left:re,top:$,width:G,height:V},children:B.text?L?(()=>{var j;const xe=jo(ue(H),B.text,G,V,To(B,R.height,G,V));return d.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center px-1 text-center",style:{fontFamily:H},children:[z&&d.jsx("span",{className:"block font-bold text-[#3a3a3a]",style:{fontSize:xe.speakerFontSize,lineHeight:1.2},children:B.speaker}),d.jsx("span",{className:"text-[#1a1a1a]",style:{fontSize:xe.fontSize,lineHeight:`${xe.lineHeight}px`,fontWeight:((j=B.textStyle)==null?void 0:j.fontWeight)??400},children:xe.lines.map((D,X)=>d.jsx("span",{className:"block",children:D},X))})]})})():d.jsx("div",{className:"absolute inset-0 flex items-center justify-center px-1 text-center break-words",style:{fontFamily:H,fontSize:Math.max(8,Math.min(V*.05,14)),fontWeight:((F=B.textStyle)==null?void 0:F.fontWeight)??400},children:z?`${B.speaker}: ${B.text}`:B.text}):d.jsx("span",{className:"block truncate px-1 text-[9px] text-muted",style:{fontFamily:H},children:B.type})},B.id)})]})]})});return f?d.jsx("button",{type:"button",onClick:f,className:"block w-full text-left","data-testid":_?`${_}-open`:void 0,children:ye}):ye}const TD={wide:"Wide",medium:"Medium","close-up":"Close-up","extreme-close-up":"Extreme close-up"},AD="No speech bubbles, captions, sound effects, narration, or any text or lettering in the image.",RD="Style lock — illustrated comic/webtoon panel art: clean black contour/ink lines, flat or cel shading, simplified but realistic (semi-realistic) anatomy and faces, backgrounds drawn as illustrated comic panels. Hold this same style on every cut for character and panel consistency. Hard negatives — NOT photorealistic, NOT a photograph, NOT a glossy or painterly digital painting, NOT concept art, NOT a 3D/CGI render, NOT airbrushed, no photoreal textures.";function DD(e){var a;const t=TD[e.shotType]??e.shotType,i=((a=e.description)==null?void 0:a.trim())||`Cut ${e.id}`,s=[`${t} shot. ${i}`];return e.characters.length>0&&s.push(`Characters: ${e.characters.join(", ")}.`),s.push(RD),s.push(AD),s.join(` -`).trim()}function MD(e,t){return`assets/${e}/cut-${String(t).padStart(2,"0")}-clean.webp`}function gy(e,t){const i=MD(t,e.id);return[`Generate the clean image for cut ${e.id}.`,"","Image description:",DD(e),"","How to hand it off:","- Produce the actual image — do not just describe it or return a prompt.",`- If your image tool can write a WebP or JPEG under 1MB, save it at ${i} and run "Sync clean images".`,'- If it only produces a PNG (e.g. built-in image generation saves to ~/.codex/generated_images), that is fine — do NOT convert or rename it yourself. Leave it there and import it into this cut with the OWS "Import from Codex" button, which converts the PNG automatically.',"- Clean image only: no text, speech bubbles, captions, sound effects, signage, watermark, or signature.","- Hold the style lock above — an illustrated comic/webtoon panel, NOT a photoreal photo, painterly concept art, or 3D render. If a result reads photorealistic, regenerate it as illustrated panel art.","- Do not letter or upload anything — final lettering and upload happen later in OWS."].join(` -`)}const t1=12e3,BD=5,LD=6e4,OD=6e4,zD=5;function PD(e,t){return e===429?!0:!!t&&/rate[\s-]?limit/i.test(t)}function ID(e,t=t1){return Math.min(t*2**e,LD)}const i1=e=>new Promise(t=>setTimeout(t,e));async function HD(e,t={}){var c;const i=t.sleep??i1,s=t.maxRetries??BD,a=t.baseDelayMs??t1;let o=0;for(;;){const h=await e();if(h.ok||!PD(h.status,h.errorMessage)||o>=s)return h;const p=ID(o,a);o+=1,(c=t.onWaiting)==null||c.call(t,{attempt:o,maxRetries:s,waitMs:p}),await i(p)}}function UD(e={}){const t=e.limit??zD,i=e.windowMs??OD,s=e.sleep??i1,a=e.now??(()=>Date.now()),o=[],c=()=>{const h=a()-i;for(;o.length&&o[0]<=h;)o.shift()};return async function(){var p;if(c(),o.length>=t){const f=o[0]+i-a();f>0&&((p=e.onWaiting)==null||p.call(e,{waitMs:f}),await s(f)),c()}o.push(a())}}const zp=1024*1024;function xy(e,t,i){return new Promise((s,a)=>{e.toBlob(o=>o?s(o):a(new Error(`Failed to export as ${t}`)),t,i)})}async function $D(e){const t=[.9,.8,.7,.6];for(const s of t)try{const a=await xy(e,"image/webp",s);if(a.type!=="image/webp")break;if(a.size<=zp)return a}catch{break}const i=[.85,.7,.5];for(const s of i){const a=await xy(e,"image/jpeg",s);if(a.size<=zp)return a}throw new Error("Cannot compress image under 1MB — reduce overlay count or image size")}const FD=["image/webp","image/jpeg"];function n1(e){return FD.includes(e.type)&&e.size<=zp}async function qD(e){var i;if(typeof createImageBitmap!="function")throw new Error("This browser cannot decode the image for import");let t;try{t=await createImageBitmap(e)}catch{throw new Error("Could not read the selected image — pick a PNG, WebP, or JPEG file")}try{const s=document.createElement("canvas");s.width=t.width,s.height=t.height;const a=s.getContext("2d");if(!a)throw new Error("Could not process the image for import");return a.drawImage(t,0,0),s}finally{(i=t.close)==null||i.call(t)}}async function Ku(e){if(n1(e))return e;const t=await qD(e);return $D(t)}function WD(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.token=="string"&&t.token.length>0&&typeof t.name=="string"&&typeof t.size=="number"&&typeof t.mtimeMs=="number"}async function GD(e){let t;try{t=await e("/api/codex/images")}catch{return[]}if(!t.ok)return[];let i;try{i=await t.json()}catch{return[]}const s=i==null?void 0:i.images;return Array.isArray(s)?s.filter(WD):[]}async function YD(e,t){let i;try{i=await e(`/api/codex/images/${encodeURIComponent(t.token)}`)}catch{throw new Error("Could not read the generated image from the Codex cache")}if(!i.ok)throw new Error("Could not read the generated image from the Codex cache");const s=await i.blob(),a=s.type||i.headers.get("Content-Type")||"image/png";return new File([s],t.name||"codex-image.png",{type:a})}function VD(e,t){const[i,s]=w.useState(null);return w.useEffect(()=>{let a=null,o=!1;return(async()=>{try{const c=await t(e);if(!c.ok)return;const h=await c.blob();if(o)return;a=URL.createObjectURL(h),s(a)}catch{}})(),()=>{o=!0,a&&URL.revokeObjectURL(a)}},[e,t]),i}function KD(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:e>=1024?`${Math.round(e/1024)} KB`:`${e} B`}function XD(e,t){const i=t-e;if(!Number.isFinite(i)||i<45e3)return"just now";const s=Math.round(i/6e4);if(s<60)return`${s}m ago`;const a=Math.round(i/36e5);if(a<24)return`${a}h ago`;const o=Math.round(i/864e5);return o<7?`${o}d ago`:`${Math.round(i/(7*864e5))}w ago`}function ZD({image:e,authFetch:t}){const i=VD(`/api/codex/images/${encodeURIComponent(e.token)}`,t);return i?d.jsx("img",{src:i,alt:e.name,className:"w-16 h-16 flex-shrink-0 rounded border border-border object-cover bg-white"}):d.jsx("div",{className:"w-16 h-16 flex-shrink-0 rounded border border-border bg-surface"})}function QD({authFetch:e,cutId:t,onImport:i,onClose:s}){const[a,o]=w.useState(null),[c,h]=w.useState(null),[p,f]=w.useState(null),[_,x]=w.useState("");w.useEffect(()=>{let E=!1;return(async()=>{const L=await GD(e);E||o(L)})(),()=>{E=!0}},[e]);const b=_.trim().toLowerCase(),v=w.useMemo(()=>a?b?a.filter(E=>E.name.toLowerCase().includes(b)):a:[],[a,b]),S=Date.now(),N=async E=>{h(null),f(E.token);try{const L=await YD(e,E);await i(L)}catch(L){h(L instanceof Error?L.message:"Could not import the generated image")}finally{f(null)}},M=a!==null&&a.length>0;return d.jsxs("div",{className:"rounded border border-border bg-surface/60 p-2 space-y-2","data-testid":`codex-picker-${t}`,children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("p",{className:"text-[11px] font-medium text-foreground",children:"Import a Codex-generated image"}),d.jsx("button",{onClick:s,"data-testid":`codex-picker-close-${t}`,className:"text-[11px] text-muted hover:text-foreground",children:"Close"})]}),M&&d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("input",{type:"search",value:_,onChange:E=>x(E.target.value),placeholder:"Filter by file name…","data-testid":`codex-picker-search-${t}`,className:"min-w-0 flex-1 px-2 py-1 text-[11px] border border-border rounded bg-transparent focus:border-accent focus:outline-none"}),d.jsx("span",{className:"text-[10px] text-muted whitespace-nowrap","data-testid":`codex-picker-count-${t}`,children:b?`${v.length} of ${a.length}`:`${a.length} image${a.length===1?"":"s"}`})]}),a===null&&d.jsx("p",{className:"text-[11px] text-muted","data-testid":`codex-picker-loading-${t}`,children:"Looking for generated images…"}),a!==null&&a.length===0&&d.jsx("p",{className:"text-[11px] text-muted","data-testid":`codex-picker-empty-${t}`,children:"No generated images found in the Codex cache yet. Generate art in Codex, then reopen this list — or use “Upload clean image” to pick a file."}),M&&v.length===0&&d.jsxs("p",{className:"text-[11px] text-muted","data-testid":`codex-picker-no-match-${t}`,children:["No generated images match “",_.trim(),"”."]}),M&&v.length>0&&d.jsx("ul",{className:"space-y-1 max-h-72 overflow-y-auto",children:v.map(E=>d.jsxs("li",{"data-testid":`codex-image-${E.token}`,className:"flex items-center gap-2 rounded border border-border bg-background/40 p-1.5",children:[d.jsx(ZD,{image:E,authFetch:e}),d.jsxs("div",{className:"min-w-0 flex-1",children:[d.jsxs("p",{className:"text-[11px] text-foreground",children:[XD(E.mtimeMs,S)," · ",KD(E.size)]}),d.jsx("p",{className:"truncate text-[10px] font-mono text-muted",title:E.name,children:E.name})]}),d.jsx("button",{onClick:()=>N(E),disabled:p!==null,"data-testid":`codex-import-${E.token}`,className:"px-2 py-1 text-[11px] border border-accent/30 text-accent rounded hover:bg-accent/5 disabled:opacity-50",children:p===E.token?"Importing…":"Import to this cut"})]},E.token))}),c&&d.jsx("p",{className:"text-[11px] text-error",children:c})]})}const JD={done:"✓",current:"▸",todo:"○"};function eM({checklist:e,issues:t,onFinish:i,finishing:s,progressText:a,canFinish:o,markdownReady:c=!1,published:h=!1}){var E;if(!e||e.steps.length===0)return null;const p=ZS(t),f=((E=e.steps.find(L=>L.key==="upload"))==null?void 0:E.status)==="done",_=f&&c&&!h,x=h||c?"done":f?"current":"todo",b=h?"done":_?"current":"todo",v=[...e.steps.filter(L=>L.key!=="publish"),{key:"assemble",label:"Episode sequence prepared",status:x,detail:null},{key:"ready",label:h?"Published to PlotLink":"Ready to publish",status:b,detail:null}],S=s?a||"Finishing…":h?"Published ✓":_?"Episode ready to publish":"Finish episode",N=v.filter(L=>L.status!=="done").length,M=p.reduce((L,I)=>L+I.lines.length,0);return d.jsxs("div",{className:"px-3 py-1.5 border-b border-border bg-surface/50 flex-shrink-0","data-testid":"finish-episode-panel",children:[d.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Finish episode"}),e.nextStep&&d.jsxs("span",{className:"min-w-0 flex-1 text-[10px] text-muted truncate","data-testid":"finish-next-step",children:["Next: ",e.nextStep]}),d.jsx("button",{onClick:i,disabled:s||!o,"data-testid":"finish-episode-btn",title:"Upload the exported final panels, then prepare the episode for publishing — picks up where it left off",className:"px-2.5 py-0.5 text-[11px] border border-accent/40 text-accent rounded hover:bg-accent/5 disabled:opacity-50",children:S})]}),d.jsxs("details",{className:"mt-1","data-testid":"finish-episode-details",children:[d.jsxs("summary",{className:"cursor-pointer select-none text-[10px] text-muted hover:text-foreground",children:[N===0?"Progress details":`${N} step${N===1?"":"s"} left`,M>0?` · ${M} blocker${M===1?"":"s"}`:""]}),d.jsxs("div",{className:"mt-1.5 space-y-1.5",children:[d.jsx("ol",{className:"flex flex-wrap gap-1.5",children:v.map(L=>d.jsxs("li",{"data-testid":`finish-step-${L.key}`,"data-status":L.status,className:`flex items-center gap-1 rounded border px-1.5 py-0.5 text-[10px] ${L.status==="current"?"border-accent/40 bg-accent/10 text-accent":L.status==="done"?"border-border bg-background/70 text-foreground":"border-border/70 bg-background/40 text-muted"}`,children:[d.jsx("span",{"aria-hidden":!0,children:JD[L.status]}),d.jsx("span",{children:L.label}),L.detail&&d.jsxs("span",{className:"text-muted",children:["· ",L.detail]})]},L.key))}),p.length>0&&d.jsx("div",{className:"space-y-1.5","data-testid":"finish-issues",children:p.map(L=>d.jsxs("div",{"data-testid":`finish-issue-group-${L.key}`,className:"text-[10px]",children:[d.jsx("p",{className:"font-medium text-amber-700",children:L.title}),d.jsx("ul",{className:"ml-3 list-disc text-muted",children:L.lines.map((I,A)=>d.jsx("li",{children:I},A))})]},L.key))})]})]})]})}function tM(e){return{planned:e.filter(t=>t.state==="planned").length,needsConversion:e.filter(t=>t.state==="needs-conversion").length,missing:e.filter(t=>t.state==="missing").length,cleanReady:e.filter(t=>t.state==="clean-ready").length,finalReady:e.filter(t=>t.state==="final-ready").length,uploaded:e.filter(t=>t.state==="uploaded").length}}function Bo(e){return(!!e.cleanImagePath||gn(e))&&km(e).length>0}function _y(e){const t=new Date().toISOString();return{status:"generated",baseSig:cl(e),generatedAt:t,updatedAt:t}}function r1(e){return e.uploadedCid?"uploaded":e.finalImagePath||e.exportedAt?"lettered":e.cleanImagePath?"clean":gn(e)?"text":"missing"}const by={muted:"text-muted",amber:"text-amber-700",green:"text-green-700",accent:"text-accent"},iM={muted:"bg-muted/40",amber:"bg-amber-500",green:"bg-green-600",accent:"bg-accent"};function nM(e,t,i){var s;return e.uploadedCid||e.uploadedUrl?{key:"uploaded",label:"Uploaded",tone:"green"}:t?{key:"convert",label:"Needs conversion",tone:"amber"}:i?e.finalImagePath?{key:"review",label:"Needs review",tone:"amber"}:{key:"needs-image",label:"Needs image",tone:"muted"}:e.finalImagePath?{key:"exported",label:"Exported",tone:"green"}:gn(e)?{key:"text",label:"Ready for captions",tone:"accent"}:e.cleanImagePath?(((s=e.overlays)==null?void 0:s.length)??0)>0?{key:"review",label:"Needs review",tone:"amber"}:{key:"letter",label:"Ready for lettering",tone:"green"}:{key:"needs-image",label:"Needs image",tone:"muted"}}function rM(e){var t,i;return e.uploadedCid||e.uploadedUrl?{label:"Complete",detail:"Final image uploaded",tone:"green"}:e.finalImagePath||e.exportedAt?{label:"Exported",detail:"Ready to upload",tone:"green"}:(((t=e.overlays)==null?void 0:t.length)??0)>0?((i=e.aiDraft)==null?void 0:i.status)==="generated"?{label:"Draft ready",detail:`${e.overlays.length} AI-drafted overlay${e.overlays.length===1?"":"s"} ready to review`,tone:"amber"}:{label:"User-edited",detail:`${e.overlays.length} overlay${e.overlays.length===1?"":"s"} adjusted and ready to review`,tone:"amber"}:Bo(e)?{label:"No draft",detail:"Draft with AI or place bubbles manually",tone:"muted"}:gn(e)?{label:"Between-scene card",detail:"Open to add narration or title text",tone:"accent"}:e.cleanImagePath?{label:"Unlettered",detail:"Clean art ready for bubble placement",tone:"muted"}:{label:"Needs artwork",detail:"Add or sync clean art first",tone:"muted"}}function sM({cut:e,storyName:t,plotFile:i,language:s,expanded:a,onToggle:o,authFetch:c,onUpdated:h,onOpenEditor:p,detectedLocalClean:f,onSyncClean:_,syncing:x,onAiDraft:b,aiDrafting:v,staleMessages:S,onRepairStale:N,repairing:M,conversionPng:E,onConvert:L,converting:I,rowRef:A}){var Fe,we;const q=w.useRef(null),[R,ne]=w.useState(!1),[ue,ye]=w.useState(null),[B,re]=w.useState(!1),[$,G]=w.useState(!1),[V,H]=w.useState(!1),[T,z]=w.useState(!1),F=r1(e),xe=S.length>0,j=!!E,D=w.useCallback(async()=>{E&&(z(!0),await L(e.id,E),z(!1),h())},[E,L,e.id,h]),X=w.useCallback(async He=>{ne(!0),ye(null);try{let it=He;if(!n1(He))try{it=await Ku(He)}catch(Be){return ye(Be instanceof Error?Be.message:"Could not import image"),!1}const st=it.type==="image/jpeg"?"jpg":"webp",nt=new FormData;nt.append("file",new File([it],`clean.${st}`,{type:it.type}));const Nt=await c(`/api/stories/${t}/cuts/${i}/upload-clean/${e.id}`,{method:"POST",body:nt});if(!Nt.ok){const Be=await Nt.json();return ye(Be.error||"Upload failed"),!1}return h(),!0}catch{return ye("Upload failed"),!1}finally{ne(!1)}},[c,t,i,e.id,h]),C=nM(e,j,xe),Z=e.cleanImagePath??E??null,ae=((Fe=e.overlays)==null?void 0:Fe.length)??0,oe=!gn(e)&&!!e.cleanImagePath&&!e.finalImagePath&&!e.uploadedCid&&!e.uploadedUrl&&!xe&&!j,K=!xe&&!j&&!e.finalImagePath&&!e.uploadedCid&&!e.uploadedUrl&&Bo(e),he=(((we=e.overlays)==null?void 0:we.length)??0)>0?"Re-draft with AI":"AI draft lettering",ge=C.key==="convert"?{label:T?"Converting…":"Convert image",onClick:D,testid:`card-convert-${e.id}`}:C.key==="review"?{label:"Review cut",onClick:p,testid:`card-review-${e.id}`}:C.key==="text"?{label:"Add captions",onClick:p,testid:`card-letter-${e.id}`}:C.key==="needs-image"?{label:"Add artwork",onClick:o,testid:`card-addart-${e.id}`}:null,De=rM(e),ze=!!e.cleanImagePath||!!e.narration||e.dialogue.length>0||gn(e);return d.jsxs("div",{ref:A,"data-cut-row":e.id,className:`border rounded ${a?"border-accent/30":"border-border"}`,children:[d.jsxs("div",{className:"px-3 py-2 space-y-2","data-testid":`cut-card-${e.id}`,children:[d.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[d.jsx("span",{className:`w-2 h-2 rounded-full flex-shrink-0 ${iM[C.tone]}`}),d.jsxs("span",{className:"font-medium text-xs text-foreground",children:["Cut ",String(e.id).padStart(2,"0")]}),d.jsxs("span",{className:"font-mono text-[10px] text-muted",children:["· ",e.shotType]}),d.jsx("span",{className:`ml-auto text-[10px] font-medium flex-shrink-0 ${by[C.tone]}`,"data-testid":`cut-card-status-${e.id}`,children:C.label})]}),Z||gn(e)?d.jsx(jD,{storyName:t,assetPath:Z,authFetch:c,alt:`Cut ${e.id} artwork`,overlays:e.overlays,language:s,background:e.background,aspectRatio:e.aspectRatio,onClick:ze?p:void 0,className:"w-full",testId:`cut-preview-${e.id}`}):d.jsx("div",{className:"w-full min-h-28 rounded border border-dashed border-border bg-surface/40 flex items-center justify-center text-[10px] text-muted","data-testid":`cut-card-noart-${e.id}`,children:gn(e)?"Text panel — no artwork needed":"No artwork yet"}),d.jsxs("div",{className:`rounded border border-border/70 bg-surface/50 px-2 py-1.5 text-[11px] ${by[De.tone]}`,"data-testid":`lettering-review-state-${e.id}`,children:[d.jsx("span",{className:"font-semibold",children:De.label}),d.jsxs("span",{className:"text-muted",children:[" · ",De.detail]})]}),d.jsx("button",{onClick:o,"data-testid":`cut-desc-${e.id}`,className:"block w-full text-left text-[11px] text-muted hover:text-foreground",children:e.description||"No description"}),d.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[oe?d.jsxs(d.Fragment,{children:[d.jsx("button",{onClick:p,"data-testid":`add-bubbles-${e.id}`,className:"px-2.5 py-1 text-[11px] font-medium rounded bg-accent text-white hover:bg-accent-dim",children:ae>0?"Review lettering":"Open focused editor"}),K&&d.jsx("button",{onClick:b,disabled:v,"data-testid":`ai-draft-${e.id}`,className:"px-2.5 py-1 text-[11px] rounded border border-accent/40 text-accent hover:bg-accent/5 disabled:opacity-50",children:v?"Drafting…":he})]}):ge?d.jsx("button",{onClick:ge.onClick,disabled:C.key==="convert"&&(T||I),"data-testid":ge.testid,className:"px-2.5 py-1 text-[11px] font-medium rounded bg-accent text-white hover:bg-accent-dim disabled:opacity-50",children:ge.label}):null,!oe&&!ge&&K&&d.jsx("button",{onClick:b,disabled:v,"data-testid":`ai-draft-${e.id}`,className:"px-2.5 py-1 text-[11px] rounded border border-accent/40 text-accent hover:bg-accent/5 disabled:opacity-50",children:v?"Drafting…":he}),d.jsx("button",{onClick:o,"data-testid":`cut-details-${e.id}`,className:"px-2.5 py-1 text-[11px] rounded border border-border text-muted hover:border-accent hover:text-accent",children:a?"Hide details":"Open details"})]})]}),a&&d.jsxs("div",{className:"px-3 pb-3 space-y-3 border-t border-border",children:[j&&d.jsxs("div",{className:"mt-2 rounded border border-amber-500/40 bg-amber-500/10 p-2 space-y-1","data-testid":`needs-conversion-${e.id}`,children:[d.jsx("p",{className:"text-[11px] text-amber-800",children:"This cut’s artwork is a PNG. Convert it to WebP so it can be lettered and published."}),d.jsx("button",{onClick:D,disabled:T||I,"data-testid":`convert-cut-${e.id}`,className:"px-2 py-1 text-[11px] border border-amber-500/50 text-amber-800 rounded hover:bg-amber-500/20 disabled:opacity-50",children:T?"Converting…":"Convert image"})]}),xe&&!j&&d.jsxs("div",{className:"mt-2 rounded border border-error/40 bg-error/5 p-2 space-y-1","data-testid":`stale-asset-${e.id}`,children:[S.map((He,it)=>d.jsx("p",{className:"text-[11px] text-error",children:He},it)),d.jsx("button",{onClick:N,disabled:M,"data-testid":`repair-stale-${e.id}`,className:"px-2 py-1 text-[11px] border border-error/40 text-error rounded hover:bg-error/10 disabled:opacity-50",children:M?"Repairing…":"Clear stale path"})]}),!gn(e)&&d.jsxs("div",{className:"mt-2 space-y-2",children:[d.jsx("button",{onClick:()=>{navigator.clipboard.writeText(gy(e,i)),re(!0),setTimeout(()=>re(!1),2e3)},"data-testid":`copy-prompt-${e.id}`,className:"px-3 py-1.5 text-xs border border-border rounded hover:border-accent hover:bg-accent/5",children:B?"Copied!":"Copy Codex task"}),d.jsx("input",{ref:q,type:"file",accept:"image/webp,image/jpeg,image/png",className:"hidden",onChange:He=>{var st;const it=(st=He.target.files)==null?void 0:st[0];it&&X(it),He.target.value=""}}),d.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[d.jsx("button",{onClick:()=>{var He;return(He=q.current)==null?void 0:He.click()},disabled:R,className:"px-3 py-1.5 text-xs border border-border rounded hover:border-accent hover:bg-accent/5 disabled:opacity-50",children:R?"Uploading...":e.cleanImagePath?"Replace clean image":"Upload clean image"}),d.jsx("button",{onClick:()=>H(He=>!He),disabled:R,"data-testid":`import-codex-${e.id}`,className:"px-3 py-1.5 text-xs border border-border rounded hover:border-accent hover:bg-accent/5 disabled:opacity-50",children:V?"Hide Codex images":"Import from Codex"})]}),V&&d.jsx(QD,{authFetch:c,cutId:e.id,onImport:async He=>{await X(He)&&H(!1)},onClose:()=>H(!1)}),!e.cleanImagePath&&d.jsx("p",{className:"text-xs text-muted","data-testid":`clean-image-handoff-${e.id}`,children:"Generate this cut in Codex, then import the cached PNG with “Import from Codex” — or upload an image manually. Letter it next."}),F==="missing"&&d.jsxs("div",{className:"rounded border border-border bg-surface/60 p-2 space-y-1","data-testid":`ask-codex-${e.id}`,children:[d.jsx("p",{className:"text-[11px] font-medium text-foreground",children:"Generate this cut in Codex"}),d.jsxs("p",{className:"text-[10px] text-muted",children:["Copy the task below and paste it into Codex. Codex usually saves a PNG to its image cache — bring it into this cut with “Import from Codex” above (the PNG becomes a WebP automatically). If Codex instead writes a WebP/JPEG at"," ",d.jsxs("span",{className:"font-mono",children:["assets/",i,"/cut-",String(e.id).padStart(2,"0"),"-clean.webp"]}),", it’s picked up by “Sync clean images”."]}),d.jsx("button",{onClick:()=>{navigator.clipboard.writeText(gy(e,i)),G(!0),setTimeout(()=>G(!1),2e3)},"data-testid":`ask-codex-copy-${e.id}`,className:"px-2 py-1 text-[11px] border border-border rounded hover:border-accent hover:bg-accent/5",children:$?"Copied!":"Copy Codex task"})]}),F==="missing"&&f&&d.jsx("button",{onClick:_,disabled:x,"data-testid":`found-local-clean-${e.id}`,className:"px-3 py-1.5 text-xs border border-green-700/40 text-green-700 rounded hover:bg-green-700/5 disabled:opacity-50",children:x?"Syncing...":"Found local clean image — sync to cut plan"}),ue&&d.jsx("p",{className:"text-xs text-error mt-1",children:ue})]}),(e.cleanImagePath||e.narration||e.dialogue.length>0||gn(e))&&d.jsx("button",{onClick:p,"data-testid":`open-editor-${e.id}`,className:"px-3 py-1.5 text-xs border border-accent/30 text-accent rounded hover:bg-accent/5",children:"Open editor"}),e.characters.length>0&&d.jsxs("p",{className:"text-xs text-muted",children:["Characters: ",e.characters.join(", ")]}),e.dialogue.length>0&&d.jsx("div",{className:"text-xs text-muted",children:e.dialogue.map((He,it)=>d.jsxs("p",{children:[d.jsxs("span",{className:"font-medium",children:[He.speaker,":"]})," ",He.text]},it))}),e.narration&&d.jsx("p",{className:"text-xs text-muted italic",children:e.narration})]})]})}function vy({storyName:e,fileName:t,authFetch:i,language:s,uploadRetry:a,onCutsChanged:o,focusRequest:c,onFocusHandled:h,onFocusedLetteringModeChange:p,workspaceVisible:f=!1,onWorkspaceVisibleChange:_}){var _r,mi,Zt;const[x,b]=w.useState(null),v=w.useRef(o);v.current=o;const S=w.useRef(h);S.current=h;const[N,M]=w.useState(!0),[E,L]=w.useState(null),[I,A]=w.useState(null),[q,R]=w.useState(null),[ne,ue]=w.useState(!1),[ye,B]=w.useState([]),[re,$]=w.useState(!1),[G,V]=w.useState(""),[H,T]=w.useState({markdownReady:!1,published:!1}),[z,F]=w.useState(!1),[xe,j]=w.useState(!1),[D,X]=w.useState(!1),[C,Z]=w.useState(null),[ae,oe]=w.useState(null),[K,he]=w.useState(null),[ge,De]=w.useState(!1),[ze,Fe]=w.useState(new Set),[we,He]=w.useState(new Map),[it,st]=w.useState(!1),[nt,Nt]=w.useState(null),[Be,ct]=w.useState(!1),[Te,Wt]=w.useState(null),vi=w.useRef(new Map),Ct=w.useRef(null),et=t.replace(/\.md$/,"");w.useEffect(()=>{var te;c&&Ct.current!==c.seq&&(Ct.current=c.seq,c.openEditor?R(c.cutId):(A(c.cutId),Wt(c.cutId)),(te=S.current)==null||te.call(S))},[c]),w.useEffect(()=>(p==null||p(q!==null),()=>p==null?void 0:p(!1)),[q,p]),w.useEffect(()=>{var ve;if(Te==null)return;const te=vi.current.get(Te);te&&((ve=te.scrollIntoView)==null||ve.call(te,{behavior:"smooth",block:"center"}),Wt(null))},[Te,x]);const ee=w.useCallback(async()=>{var te;try{const ve=await i(`/api/stories/${e}/cuts/${et}`);if(ve.status===404){b(null);return}if(!ve.ok){const me=await ve.json();L(me.error||"Failed to load cuts");return}const Y=await ve.json();b(Y),L(null);try{const me=await i(`/api/stories/${e}/${t}`);if(me.ok){const _e=await me.json(),Oe=typeof(_e==null?void 0:_e.content)=="string"?_e.content:"",Pe=Array.isArray(Y==null?void 0:Y.cuts)?Y.cuts:[],qe=Oe.length>0&&KS(Oe,Pe).ready,wt=(_e==null?void 0:_e.status)==="published"||(_e==null?void 0:_e.status)==="published-not-indexed";T({markdownReady:qe,published:wt})}else T({markdownReady:!1,published:!1})}catch{T({markdownReady:!1,published:!1})}(te=v.current)==null||te.call(v)}catch{L("Failed to load cuts")}finally{M(!1)}},[i,e,et,t]),be=w.useCallback(async te=>!!(await i(`/api/stories/${e}/cuts/${et}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(te)})).ok,[i,e,et]),Me=w.useCallback(async()=>{st(!1);try{const te=await i(`/api/stories/${e}/cuts/${et}/detect-clean-images`);if(!te.ok)return;const ve=await te.json();Fe(new Set(Array.isArray(ve.detected)?ve.detected:[]));const Y=new Map,me=ve.stale;if(Array.isArray(me))for(const _e of me){if(typeof(_e==null?void 0:_e.cutId)!="number"||typeof(_e==null?void 0:_e.message)!="string")continue;const Oe=Y.get(_e.cutId)??[];Oe.push(_e.message),Y.set(_e.cutId,Oe)}He(Y),st(!0)}catch{}},[i,e,et]),$e=w.useCallback(async()=>{Nt(null);try{const te=await i(`/api/stories/${e}/cuts/${et}/asset-diagnostics`);if(!te.ok)return;const ve=await te.json();Nt(Array.isArray(ve.diagnostics)?ve.diagnostics:null)}catch{}},[i,e,et]),Xe=w.useCallback(async()=>{ct(!0);try{await Promise.all([ee(),Me(),$e()])}finally{ct(!1)}},[ee,Me,$e]),Gt=w.useCallback(async(te,ve={})=>{var _e;if(!x)return!1;const Y=x.cuts.find(Oe=>Oe.id===te);if(!Y||!Bo(Y)||(((_e=Y.overlays)==null?void 0:_e.length)??0)>0&&!window.confirm("This cut already has overlays. Re-drafting with AI will replace the current draft overlays for this cut. Continue?"))return!1;const me=hy(Y);if(me.length===0)return oe(`Cut ${Y.id}: no script lines available to draft.`),!1;he(te),oe(null);try{const Oe={...x,cuts:x.cuts.map(qe=>qe.id===te?{...qe,overlays:me,aiDraft:_y(me)}:qe)};return await be(Oe)?(oe(`Cut ${Y.id}: AI draft ready`),await ee(),ve.openEditor&&R(te),!0):(oe(`Cut ${Y.id}: AI draft failed`),!1)}finally{he(null)}},[x,be,ee]),pi=w.useCallback(async()=>{if(!x)return;const te=x.cuts.filter(ve=>{var Y;return Bo(ve)&&(((Y=ve.overlays)==null?void 0:Y.length)??0)===0&&!ve.finalImagePath&&!ve.uploadedCid&&!ve.uploadedUrl});if(te.length===0){oe("No unlettered cuts need an AI draft");return}De(!0),oe(null);try{const ve={...x,cuts:x.cuts.map(me=>{if(!te.some(Oe=>Oe.id===me.id))return me;const _e=hy(me);return _e.length>0?{...me,overlays:_e,aiDraft:_y(_e)}:me})};if(!await be(ve)){oe("AI draft failed");return}oe(`AI draft ready for ${te.length} cut${te.length===1?"":"s"}`),await ee()}finally{De(!1)}},[x,be,ee]),Rt=w.useCallback(async()=>{F(!0),oe(null),B([]);try{const te=await i(`/api/stories/${e}/cuts/${et}/sync-clean-images`,{method:"POST"}),ve=await te.json().catch(()=>({}));if(!te.ok)oe(ve.error||"Sync failed");else{const Y=Array.isArray(ve.synced)?ve.synced.length:0,me=Array.isArray(ve.cleared)?ve.cleared.length:0,_e=Array.isArray(ve.rejected)?ve.rejected:[];_e.length>0&&B(_e.map(Pe=>`Cut ${Pe.cutId}: ${Pe.reason}`));const Oe=[];Y>0&&Oe.push(`Synced ${Y}`),me>0&&Oe.push(`Cleared ${me} stale path${me===1?"":"s"}`),oe(Oe.length>0?Oe.join(", "):"No new clean images"),await ee(),await Me(),await $e()}}catch{oe("Sync failed")}F(!1)},[i,e,et,ee,Me,$e]),St=w.useCallback(async(te,ve)=>{try{const Y=await i(HS(e,ve));if(!Y.ok)return!1;const me=await Y.blob(),_e=await Ku(new File([me],"clean.png",{type:me.type||"image/png"})),Oe=_e.type==="image/jpeg"?"jpg":"webp",Pe=new FormData;return Pe.append("file",new File([_e],`clean.${Oe}`,{type:_e.type})),(await i(`/api/stories/${e}/cuts/${et}/upload-clean/${te}`,{method:"POST",body:Pe})).ok}catch{return!1}},[i,e,et]),Yt=w.useCallback(async te=>{X(!0),Z(null);let ve=0;const Y=[];for(const me of te)await St(me.cutId,me.pngPath)?ve++:Y.push(me.cutId);await Xe(),X(!1),Z(Y.length===0?`Converted ${ve} image${ve===1?"":"s"} to WebP`:`Converted ${ve}; ${Y.length} failed (Cut ${Y.join(", ")}) — try Convert image on each`)},[St,Xe]),ot=w.useCallback(async()=>{var _e;if(!x)return;$(!0),V(""),B([]);const te=x.cuts.filter(Oe=>Oe.finalImagePath&&!Oe.uploadedCid),ve=[],Y=UD({sleep:a==null?void 0:a.sleep,onWaiting:({waitMs:Oe})=>V(`Upload limit reached — waiting ${Math.round(Oe/1e3)}s before continuing…`)});for(let Oe=0;Oe{const gi=await i("/api/publish/upload-plot-image",{method:"POST",body:jt});if(gi.ok){const{cid:Di,url:yn}=await gi.json();return{ok:!0,status:gi.status,cid:Di,url:yn}}const li=await gi.json().catch(()=>({}));return{ok:!1,status:gi.status,errorMessage:li.error}},{...a,onWaiting:({attempt:gi,maxRetries:li,waitMs:Di})=>V(`Cut ${Pe.id} rate-limited — waiting ${Math.round(Di/1e3)}s before retry ${gi}/${li}...`)});if(!Ze.ok){ve.push(`Cut ${Pe.id}: upload failed — ${Ze.errorMessage||"unknown"}`);continue}const{cid:Qe,url:Kt}=Ze;(await i(`/api/stories/${e}/cuts/${et}/set-uploaded/${Pe.id}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cid:Qe,url:Kt})})).ok||ve.push(`Cut ${Pe.id}: failed to record upload`)}catch(qe){ve.push(`Cut ${Pe.id}: ${qe instanceof Error?qe.message:"failed"}`)}}if(ve.length>0){B(ve),$(!1),V(""),ee();return}V("Preparing episode for publishing…");const me=await i(`/api/stories/${e}/cuts/${et}/generate-markdown`,{method:"POST"});if(me.ok){const Oe=await me.json();((_e=Oe.warnings)==null?void 0:_e.length)>0&&B(Oe.warnings)}$(!1),V(""),ee()},[x,i,e,et,a,ee]),Ht=w.useCallback(async()=>{j(!0),oe(null);try{const te=await i(`/api/stories/${e}/cuts/${et}/repair-asset-paths`,{method:"POST"}),ve=await te.json().catch(()=>({}));if(!te.ok)oe(ve.error||"Repair failed");else{const Y=Array.isArray(ve.cleared)?ve.cleared.length:0;oe(Y>0?`Cleared ${Y} stale path${Y===1?"":"s"}`:"No stale paths to clear"),await ee(),await Me()}}catch{oe("Repair failed")}j(!1)},[i,e,et,ee,Me]),[U,Ce]=w.useState(!1),Ae=w.useCallback(async(te,ve=!0)=>{if(x){Ce(!0);try{const Y=x.cuts.reduce((qe,wt)=>Math.max(qe,wt.id),0)+1,me={id:Y,shotType:"wide",description:"Text panel",characters:[],dialogue:[],narration:"",sfx:"",cleanImagePath:null,finalImagePath:null,exportedAt:null,uploadedCid:null,uploadedUrl:null,overlays:[],kind:"text",background:"#101820",aspectRatio:"4:5"},_e=[...x.cuts];_e.splice(Math.max(0,Math.min(te,_e.length)),0,me);const Oe={...x,cuts:_e},Pe=await i(`/api/stories/${e}/cuts/${et}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(Oe)});if(Pe.ok)ve?R(Y):A(Y),await ee();else{const qe=await Pe.json().catch(()=>({}));oe(qe.error||"Could not add text panel")}}catch{oe("Could not add text panel")}Ce(!1)}},[x,i,e,et,ee]),Ne=w.useCallback(()=>Ae((x==null?void 0:x.cuts.length)??0,!0),[Ae,x]);if(w.useEffect(()=>{ee(),Me(),$e()},[ee,Me,$e]),N)return d.jsx("div",{className:"p-4 text-sm text-muted",children:"Loading cuts..."});if(E)return d.jsxs("div",{className:"p-4 space-y-2","data-testid":"cuts-error",children:[d.jsx("p",{className:"text-sm text-error font-medium",children:"Invalid cuts file"}),d.jsx("p",{className:"text-xs text-error",children:E}),d.jsxs("p",{className:"text-xs text-muted",children:[et,".cuts.json must follow the OWS v1 schema. Ask Claude to regenerate it using the v1 cuts schema from the cartoon writing instructions."]}),d.jsx("button",{onClick:ee,className:"text-xs text-accent hover:text-accent-dim",children:"Retry"})]});if(!x||x.cuts.length===0)return d.jsxs("div",{className:"p-4 text-center space-y-1",children:[d.jsx("p",{className:"text-sm text-muted",children:"No cuts yet"}),d.jsx("p",{className:"text-xs text-muted",children:"Ask Claude to create a cut plan for this episode."})]});const Ge=q!==null?x.cuts.find(te=>te.id===q):null;if(Ge)return d.jsx(ND,{storyName:e,cut:Ge,plotFile:et,language:s,authFetch:i,targetLabel:gn(Ge)?`Between-scene card ${Ge.id}`:`Cut ${String(Ge.id).padStart(2,"0")}`,returnOnSave:!0,workspaceVisible:f,onToggleWorkspaceVisible:_?()=>_(!f):void 0,onSave:async(te,ve)=>{const Y={...x,cuts:x.cuts.map(_e=>_e.id===q?{..._e,overlays:te,aiDraft:ve??_e.aiDraft??null}:_e)};if(!await be(Y))throw new Error("Failed to save overlays")},onExported:()=>ee(),onClose:()=>{R(null),ee()}});const Ue=x.cuts.reduce((te,ve)=>{const Y=r1(ve);return te[Y]++,te},{missing:0,clean:0,lettered:0,uploaded:0,text:0}),dt=x.cuts.filter(te=>!gn(te)).length,_t=x.cuts.filter(te=>GS(te)).map(te=>te.id),At=uD({cuts:x.cuts,published:H.published}),Bt=((_r=At.steps.find(te=>te.key==="upload"))==null?void 0:_r.status)==="done",Ut=x.cuts.some(te=>te.finalImagePath&&!te.uploadedCid)||Bt&&!H.markdownReady,Vt=(nt??[]).filter(te=>te.state==="needs-conversion"&&te.convertiblePng).map(te=>({cutId:te.cutId,pngPath:te.convertiblePng})),an=new Map(Vt.map(te=>[te.cutId,te.pngPath])),ri=(nt??[]).filter(te=>te.state==="needs-conversion"&&te.issue).map(te=>te.issue),Mn=t==="genesis.md"?"Genesis / Episode 1":`Episode ${parseInt(((mi=et.match(/\d+/))==null?void 0:mi[0])??"0",10)+1}`,Bn=typeof x.title=="string"?x.title:null,cr=x.cuts.filter(te=>!gn(te)),Ii={cuts:x.cuts.length,artwork:cr.filter(te=>te.cleanImagePath||an.has(te.id)).length,converted:cr.filter(te=>te.cleanImagePath&&/\.(webp|jpe?g)$/i.test(te.cleanImagePath)).length,lettered:x.cuts.filter(te=>{var ve;return(((ve=te.overlays)==null?void 0:ve.length)??0)>0||!!te.finalImagePath}).length,uploaded:x.cuts.filter(te=>te.uploadedCid||te.uploadedUrl).length},vn=x.cuts.filter(te=>{var ve;return Bo(te)&&(((ve=te.overlays)==null?void 0:ve.length)??0)===0&&!te.finalImagePath&&!te.uploadedCid&&!te.uploadedUrl}).length;return d.jsxs("div",{className:"h-full min-h-[22rem] flex flex-col overflow-hidden","data-testid":"cut-list-panel",children:[d.jsx("div",{className:"px-3 py-2 border-b border-border flex-shrink-0","data-testid":"cut-board-header",children:d.jsxs("div",{className:"flex items-start gap-3 justify-between",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:"font-serif text-foreground truncate",children:Mn}),Bn&&d.jsxs("span",{className:"text-muted truncate",children:["· ",Bn]})]}),d.jsxs("div",{className:"mt-0.5 text-[10px] text-muted","data-testid":"cut-board-summary",children:[Ii.cuts," cuts · ",Ii.artwork," artwork found ·"," ",Ii.converted," converted · ",Ii.lettered," ","lettered · ",Ii.uploaded," uploaded"]})]}),vn>0&&d.jsx("button",{onClick:pi,disabled:ge,"data-testid":"ai-draft-all-btn",className:"px-2.5 py-1 text-[11px] rounded border border-accent/40 text-accent hover:bg-accent/5 disabled:opacity-50",children:ge?"Drafting…":`AI draft all unlettered (${vn})`})]})}),d.jsxs("details",{className:"border-b border-border flex-shrink-0","data-testid":"cut-advanced",children:[d.jsx("summary",{className:"px-3 py-1.5 text-[10px] text-muted cursor-pointer hover:text-foreground",children:"Technical details"}),d.jsxs("div",{className:"px-3 py-2 flex flex-wrap items-center gap-2 text-[10px]",children:[d.jsxs("span",{className:"font-mono text-muted",children:[x.cuts.length," cuts"]}),Ue.missing>0&&d.jsxs("span",{className:"text-muted",children:[Ue.missing," missing"]}),Ue.clean>0&&d.jsxs("span",{className:"text-green-700",children:[Ue.clean," clean"]}),Ue.lettered>0&&d.jsxs("span",{className:"text-amber-700",children:[Ue.lettered," lettered"]}),Ue.uploaded>0&&d.jsxs("span",{className:"text-green-700",children:[Ue.uploaded," uploaded"]}),Ue.text>0&&d.jsxs("span",{className:"text-accent",children:[Ue.text," text ",Ue.text===1?"panel":"panels"]}),d.jsx("button",{onClick:async()=>{ue(!0),B([]);try{const te=await i(`/api/stories/${e}/cuts/${et}/generate-markdown`,{method:"POST"});if(te.ok){const ve=await te.json();B(ve.warnings||[])}}catch{}ue(!1)},disabled:ne,className:"ml-auto px-2 py-0.5 border border-accent/30 text-accent rounded hover:bg-accent/5 disabled:opacity-50","data-testid":"generate-markdown-btn",title:"Build the publish-ready episode from the uploaded cut images",children:ne?"Preparing…":"Prepare episode for publish"}),d.jsx("button",{onClick:Ne,disabled:U,className:"px-2 py-0.5 border border-accent/30 text-accent rounded hover:bg-accent/5 disabled:opacity-50","data-testid":"add-text-panel-btn",title:"Insert a narration/title card between art panels — a solid card exported as a final image panel, no drawing needed",children:U?"Adding…":"Add narration/text panel"}),d.jsx("button",{onClick:Xe,disabled:Be,className:"px-2 py-0.5 border border-border text-muted rounded hover:border-accent hover:text-accent disabled:opacity-50","data-testid":"refresh-assets-btn",title:"Re-check the story folder for agent-generated images and report each cut's asset state — read only, nothing is uploaded or published",children:Be?"Checking…":"Refresh assets"}),d.jsx("button",{onClick:Rt,disabled:z,className:"px-2 py-0.5 border border-accent/30 text-accent rounded hover:bg-accent/5 disabled:opacity-50","data-testid":"sync-clean-btn",children:z?"Syncing...":"Sync clean images"}),d.jsx("button",{onClick:ot,disabled:re||!(x!=null&&x.cuts.some(te=>te.finalImagePath&&!te.uploadedCid)),className:"px-2 py-0.5 border border-accent/30 text-accent rounded hover:bg-accent/5 disabled:opacity-50","data-testid":"upload-generate-btn",title:"Upload each cut's final lettered image, then prepare the episode for publishing",children:G||"Upload & Prepare for Publish"})]})]}),d.jsxs("details",{className:"px-3 py-1.5 border-b border-border bg-surface/40 flex-shrink-0","data-testid":"cartoon-workflow-help",children:[d.jsx("summary",{className:"cursor-pointer select-none text-[10px] text-muted hover:text-foreground",children:"Cut workflow help"}),d.jsxs("div",{className:"mt-1.5",children:[d.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 text-[10px] text-muted",children:[d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"1. Letter"}),d.jsx("span",{"aria-hidden":!0,children:"→"}),d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"2. Export"}),d.jsx("span",{"aria-hidden":!0,children:"→"}),d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"3. Upload"}),d.jsx("span",{"aria-hidden":!0,children:"→"}),d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"4. Prepare episode for publish"})]}),d.jsxs("div",{className:"mt-1 text-[10px] text-muted",children:["Use ",d.jsx("span",{className:"text-accent",children:"Add narration/text panel"})," ","for a narration or title card. It becomes a solid card exported as a final image."]})]})]}),_t.length>0&&d.jsxs("div",{className:"px-3 py-1.5 border-b border-amber-500/40 bg-amber-500/10 text-[10px] text-amber-700 flex-shrink-0","data-testid":"stale-bubble-export-warning",children:[_t.length===1?"Cut":"Cuts"," ",_t.join(", ")," ",_t.length===1?"was":"were"," lettered with an older speech-bubble style whose tail can show a visible seam. Re-export"," ",_t.length===1?"it":"them"," (open lettering → Export) and re-upload before publishing so the bubble tails are seamless."]}),it&&dt>0&&Ue.missing===0&&we.size===0&&d.jsxs("div",{className:"px-3 py-1 border-b border-border bg-green-600/10 text-[10px] text-green-700 flex items-center gap-1 flex-shrink-0","data-testid":"clean-assets-ready",children:[d.jsx("span",{"aria-hidden":!0,children:"✓"}),d.jsxs("span",{children:["All ",dt," clean image",dt===1?"":"s"," ","present — clean-asset generation is complete. Ready for lettering in OWS."]})]}),ae&&d.jsx("div",{className:"px-3 py-1 border-b border-border text-[10px] text-muted flex-shrink-0","data-testid":"sync-result",children:ae}),Vt.length>0&&d.jsxs("div",{className:"px-3 py-2 border-b border-amber-500/40 bg-amber-500/10 text-[11px] flex-shrink-0","data-testid":"convert-artwork",children:[d.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[d.jsxs("span",{className:"font-medium text-amber-700","data-testid":"convert-artwork-count",children:[Vt.length," PNG image",Vt.length===1?"":"s"," found"]}),d.jsx("button",{onClick:()=>Yt(Vt),disabled:D,"data-testid":"convert-all-btn",className:"ml-auto px-2 py-0.5 border border-amber-500/50 text-amber-800 rounded hover:bg-amber-500/20 disabled:opacity-50",children:D?"Converting…":"Convert all to WebP"})]}),d.jsx("p",{className:"mt-1 text-[10px] text-muted",children:"PNG artwork is fine while drafting. Convert it before lettering/export so PlotLink can publish it safely."}),C&&d.jsx("p",{className:"mt-1 text-[10px] text-muted","data-testid":"convert-result",children:C}),ri.length>0&&d.jsxs("details",{className:"mt-1","data-testid":"convert-technical-details",children:[d.jsx("summary",{className:"text-[10px] text-muted cursor-pointer",children:"Technical details"}),d.jsx("ul",{className:"mt-1 ml-3 list-disc text-[10px] text-muted",children:ri.map((te,ve)=>d.jsx("li",{children:te},ve))})]})]}),nt&&nt.length>0&&(()=>{const te=tM(nt),ve=nt.filter(Y=>Y.state==="missing");return d.jsxs("div",{className:"px-3 py-1.5 border-b border-border bg-surface/40 text-[10px] flex-shrink-0","data-testid":"asset-diagnostics",children:[d.jsxs("span",{className:"text-muted","data-testid":"asset-diag-summary",children:["Assets: ",te.uploaded," uploaded · ",te.finalReady," final ·"," ",te.cleanReady," clean · ",te.planned," planned",te.needsConversion>0?` · ${te.needsConversion} needs conversion`:"",te.missing>0?` · ${te.missing} missing`:""]}),ve.length>0&&d.jsx("ul",{className:"mt-1 ml-3 list-disc text-error","data-testid":"asset-diag-issues",children:ve.map(Y=>d.jsx("li",{children:Y.issue},Y.cutId))})]})})(),d.jsx(eM,{checklist:At,issues:ye,onFinish:ot,finishing:re,progressText:G,canFinish:Ut,markdownReady:H.markdownReady,published:H.published}),d.jsxs("div",{className:"flex-1 min-h-56 overflow-y-auto p-3 space-y-3","data-testid":"lettering-review-board",children:[x.cuts.map((te,ve)=>{var Y;return d.jsxs(w.Fragment,{children:[d.jsx(yy,{index:ve,beforeLabel:ve===0?"Episode opening":`After cut ${(Y=x.cuts[ve-1])==null?void 0:Y.id}`,afterLabel:`Before cut ${te.id}`,disabled:U,onAdd:()=>Ae(ve)}),d.jsx(sM,{cut:te,storyName:e,plotFile:et,language:s,expanded:I===te.id,onToggle:()=>A(I===te.id?null:te.id),authFetch:i,onUpdated:()=>{ee(),Me(),$e()},onOpenEditor:()=>R(te.id),detectedLocalClean:ze.has(te.id),onSyncClean:Rt,syncing:z,onAiDraft:()=>{Gt(te.id,{openEditor:!0})},aiDrafting:K===te.id,staleMessages:we.get(te.id)??[],onRepairStale:Ht,repairing:xe,conversionPng:an.get(te.id)??null,onConvert:St,converting:D,rowRef:me=>{me?vi.current.set(te.id,me):vi.current.delete(te.id)}})]},te.id)}),d.jsx(yy,{index:x.cuts.length,beforeLabel:`After cut ${(Zt=x.cuts[x.cuts.length-1])==null?void 0:Zt.id}`,afterLabel:"Episode ending",disabled:U,onAdd:()=>Ae(x.cuts.length)})]})]})}function yy({index:e,beforeLabel:t,afterLabel:i,disabled:s,onAdd:a}){return d.jsxs("div",{className:"rounded border border-dashed border-border bg-surface/35 px-3 py-2 text-[11px] text-muted flex items-center gap-3","data-testid":`between-scene-slot-${e}`,children:[d.jsxs("span",{className:"min-w-0 flex-1",children:[d.jsx("span",{className:"font-medium text-foreground",children:"Between-scene lettering"}),d.jsxs("span",{className:"block truncate",children:[t," · ",i]})]}),d.jsx("button",{type:"button",onClick:a,disabled:s,className:"flex-shrink-0 rounded border border-accent/40 px-2.5 py-1 text-[11px] font-medium text-accent hover:bg-accent/5 disabled:opacity-50","data-testid":`add-between-scene-${e}`,children:"Add card"})]})}const aM=1024*1024,lM=["image/webp","image/jpeg"],oM="Cover: WebP or JPEG, max 1MB, 600×900 portrait recommended. Use clean cover art — avoid unreadable AI text or broken lettering.";function cM(e){return e.attached?{state:"attached",label:"Cover attached to your story.",tone:"success"}:e.invalid?{state:"invalid",label:"Cover file can't be used — must be WebP or JPEG, max 1MB.",tone:"error"}:e.hasSelectedCover?{state:"selected",label:"Cover selected — it will be uploaded when you publish.",tone:"accent"}:{state:"none",label:"No cover yet — add one before publishing (recommended).",tone:"muted"}}function Sy(e){return e.size>aM?"Image exceeds 1MB limit":lM.includes(e.type)?null:"Only WebP and JPEG images are accepted"}async function uM(e,t,i){const s=new FormData;s.append("file",i);const a=await e("/api/publish/upload-cover",{method:"POST",body:s});if(!a.ok)return null;const{cid:o}=await a.json();return!o||!(await e("/api/publish/update-storyline",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storylineId:t,coverCid:o})})).ok?null:o}function Pp(e){const t=e.match(/^#\s+(.+)$/m),i=t?t[1].trim():"";return i||null}function hM(e){return e.replace(/[-_]+/g," ").replace(/\s+/g," ").trim().split(" ").map(t=>t&&t[0].toUpperCase()+t.slice(1)).join(" ")}function Uo(e,t){const i=(e??"").trim().toLowerCase();if(!i)return!0;if(t==="genesis.md")return i==="genesis";const s=t.match(/^(plot-\d+)\.md$/);return s?i===s[1].toLowerCase()||/^plot-\d+$/.test(i):!1}function dM(e){const t=e.match(/^plot-(\d+)\.md$/);if(!t)return null;const i=t[1];return`Episode ${i.length<2?i.padStart(2,"0"):i}`}function Ip(e){const t=(e??"").trim();return!!(!t||/^(?:episode|ep|chapter|ch|part|pt|plot)\.?\s*[-–—:#]?\s*\d+$/i.test(t)||/^\d+$/.test(t)||/^plot[-_\s]?\d+$/i.test(t))}function Em(e){var s;const t=Pp(e.fileContent);if(t)return!Ip(t);const i=((s=e.episodeTitle)==null?void 0:s.trim())||null;return!!i&&!Ip(i)}function Nm(e){const{fileName:t,fileContent:i,storySlug:s,structureContent:a,contentType:o,episodeTitle:c}=e,h=Pp(i);if(t==="genesis.md"){const p=a?Pp(a):null;return(h??p??hM(s)).slice(0,60)}if(h)return h.slice(0,60);if(o==="cartoon"){const p=c==null?void 0:c.trim(),f=dM(t);return((p||f)??t.replace(/\.md$/,"")).slice(0,60)}return t.replace(/\.md$/,"").slice(0,60)}function fM(e){return!!(e!=null&&e.txHash)&&(e==null?void 0:e.plotIndex)!=null&&e.plotIndex>0}function pM(e){return fM(e)&&(e==null?void 0:e.status)!=="published-not-indexed"}function wy(e,t,i){if(e[t]==="cartoon"&&!i)return"cartoon"}function mM(e,t,i){return!(e!=="cartoon"||t||!i||i.startsWith("_new_"))}function Of(e,t,i){if(e)return t[e]||i.get(e)||"fiction"}function zf(e){if(!e)return null;const t=Number(e);return Number.isFinite(t)?(t/1e18).toFixed(6):null}function gM(e){return!!e&&e.ready===!1}function xM(e){const t=zf(e.requiredBalance)??zf(e.creationFee),i=zf(e.ethBalance);return e.hasEnoughEth===!1&&t&&i?`Insufficient ETH: need at least ${t} ETH to publish; current balance is ${i} ETH.`+(e.address?` Top up the OWS wallet (${e.address}) and try again.`:" Top up the OWS wallet and try again."):e.error||"Publish preflight failed — the OWS wallet isn't ready to publish."}const _M={...ml,attributes:{...ml.attributes,img:["src","alt","title"]}},bM="https://ipfs.filebase.io/ipfs/";function vM(e){const t=[],i=/!\[([^\]]*)\]\(([^)]+)\)/g;let s;for(;(s=i.exec(e))!==null;)t.push({full:s[0],alt:s[1],url:s[2]});return t}function yM(e){const t=vM(e),i=[];for(const a of t)a.url.startsWith(bM)||i.push(`Non-IPFS image URL: ${a.url.length>60?a.url.slice(0,60)+"...":a.url}`);return e.match(/!\[[^\]]*\]\([^)]*$|!\[[^\]]*$(?!\])/gm)&&i.push("Malformed image markdown detected — check brackets and parentheses"),{count:t.length,warnings:i}}function SM(e){return e==="open-cuts"||e==="open-lettering"||e==="upload"||e==="refresh-assets"}function wM({storyName:e,fileName:t,authFetch:i,onPublish:s,publishingFile:a,walletAddress:o,contentType:c="fiction",language:h,genre:p,isNsfw:f,hasGenesis:_=!1,onViewProgress:x,onOpenFile:b,onViewPublish:v,focusedLetteringMode:S=!1,focusedLetteringWorkspaceVisible:N=!1,onFocusedLetteringModeChange:M,onFocusedLetteringWorkspaceVisibleChange:E,workflowActionRequest:L=null,onWorkflowActionHandled:I}){const[A,q]=w.useState(null),[R,ne]=w.useState(!1),[ue,ye]=w.useState("preview"),[B,re]=w.useState("publish"),[$,G]=w.useState("text"),[V,H]=w.useState(null),T=w.useCallback((se,Ee)=>{ye("edit"),H(je=>({cutId:se,openEditor:Ee,seq:((je==null?void 0:je.seq)??0)+1}))},[]),[z,F]=w.useState(""),[xe,j]=w.useState(!1),[D,X]=w.useState(!1),[C,Z]=w.useState(!1),[ae,oe]=w.useState(null),[K,he]=w.useState(""),[ge,De]=w.useState(""),[ze,Fe]=w.useState(!1),[we,He]=w.useState(null),[it,st]=w.useState(0),[nt,Nt]=w.useState(0),[Be,ct]=w.useState(null),[Te,Wt]=w.useState(null),[vi,Ct]=w.useState(null),[et,ee]=w.useState(0),be=w.useRef(null),Me=w.useRef(!1),[$e,Xe]=w.useState(!1),[Gt,pi]=w.useState(hl[0]),[Rt,St]=w.useState(rs[0]),[Yt,ot]=w.useState(!1),[Ht,U]=w.useState(null),[Ce,Ae]=w.useState(null),[Ne,Ge]=w.useState(!1),[Ue,dt]=w.useState(!1),[_t,At]=w.useState(!1),[Bt,Ut]=w.useState(null),[Vt,an]=w.useState(!1),ri=w.useRef(null),Mn=w.useRef(null),[Bn,cr]=w.useState(!1),[Ii,vn]=w.useState(null),[_r,mi]=w.useState(null),[Zt,te]=w.useState("unknown"),ve=w.useRef(!1),[Y,me]=w.useState(!1),[_e,Oe]=w.useState(!1),[Pe,qe]=w.useState(null),[wt,vt]=w.useState([]),[jt,Ze]=w.useState(null),Qe=w.useRef(null),Kt=w.useRef(null),Ri=w.useRef(0),gi=w.useRef(!1);gi.current=SM(L==null?void 0:L.action);const li=w.useCallback(async()=>{if(!e||!t){q(null);return}const se=`${e}/${t}`,Ee=Kt.current!==se;Ee&&(Kt.current=se);try{const je=await i(`/api/stories/${e}/${t}`);if(je.ok){const Je=await je.json();q(Je),(Ee||!Me.current)&&(F(Je.content??""),Ee&&(X(!1),Me.current=!1))}}catch{}},[e,t,i]);w.useEffect(()=>{ne(!0),li().finally(()=>ne(!1))},[li]),w.useEffect(()=>{if(!e||!t||ue==="edit"&&D)return;const se=setInterval(li,3e3);return()=>clearInterval(se)},[e,t,li,ue,D]);const[Di,yn]=w.useState(null),Br=c==="cartoon"&&t==="genesis.md";w.useEffect(()=>{if(!Br||!e){yn(null);return}let se=!1;return i(`/api/stories/${e}/cuts/genesis`).then(Ee=>Ee.ok?Ee.json():null).then(Ee=>{se||yn(Ee?Op(Ee.cuts||[]):null)}).catch(()=>{se||yn(null)}),()=>{se=!0}},[Br,e,i]);const qs=c==="cartoon"&&!!t&&/^plot-\d+\.md$/.test(t);w.useEffect(()=>{if(!qs||!e||!t){He(null),st(0),Nt(0),ct(null);return}let se=!1;const Ee=t.replace(/\.md$/,"");return ct(null),(async()=>{try{const[je,Je]=await Promise.all([i(`/api/stories/${e}/${t}`),i(`/api/stories/${e}/cuts/${Ee}`)]);if(se)return;if(!Je.ok){He("error"),st(0),Nt(0),ct(null);return}const Lt=await Je.json(),Mi=Lt.cuts||[],oi=je.ok?(await je.json()).content??"":"",wn=XS(oi,Mi);se||(He(wn.stage),st(wn.awaitingCount),Nt(wn.totalCuts),ct(Op(Mi)),Ct(typeof Lt.title=="string"?Lt.title:null))}catch{se||(He("error"),st(0),Nt(0),ct(null))}})(),()=>{se=!0}},[qs,e,t,i,A==null?void 0:A.content,A==null?void 0:A.status,et]),w.useEffect(()=>{if(!e){Wt(null);return}let se=!1;return i(`/api/stories/${e}/structure.md`).then(Ee=>Ee.ok?Ee.json():null).then(Ee=>{se||Wt((Ee==null?void 0:Ee.content)??null)}).catch(()=>{}),()=>{se=!0}},[e,i]),w.useEffect(()=>{if(!e)return;const se=Cu(p);let Ee=se??"";if(!se&&Te){const Je=Te.match(/\*{0,2}genre\*{0,2}[:\s]+(.+)/i);Je&&(Ee=Cu(Je[1].replace(/\*+/g,"").trim())??"")}he(Ee);let je=h&&rs.find(Je=>Je.toLowerCase()===h.toLowerCase())||"";if(!je&&Te){const Je=Te.match(/\*{0,2}language\*{0,2}[:\s]+(.+)/i);Je&&(je=rs.find(Lt=>Lt.toLowerCase()===Je[1].replace(/\*+/g,"").trim().toLowerCase())||"")}De(je),Fe(f??!1)},[e,p,h,f,Te]);const br=w.useCallback(se=>{e&&i(`/api/stories/${e}/publish-metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(se)}).catch(()=>{})},[e,i]),$t=w.useCallback(async()=>{if(!(!e||!t)){j(!0);try{(await i(`/api/stories/${e}/${t}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:z})})).ok&&(X(!1),Me.current=!1,q(Ee=>Ee&&{...Ee,content:z}))}catch{}j(!1)}},[e,t,i,z]),Hi=w.useCallback(async()=>{if(!e||!t)return;const se=t.replace(/\.md$/,"");try{(await i(`/api/stories/${e}/cuts/${se}/generate-markdown`,{method:"POST"})).ok&&(await li(),ee(je=>je+1))}catch{}},[e,t,i,li]);w.useEffect(()=>{if(L&&L.seq!==Ri.current){switch(Ri.current=L.seq,L.action){case"view-progress":x==null||x();break;case"open-cuts":case"open-lettering":case"upload":case"refresh-assets":ye("edit"),G("cuts");break;case"generate-markdown":Hi();break;case"publish":ye("preview");break}I==null||I(L.seq)}},[L,x,Hi,I]);const yi=w.useCallback(se=>{var Je;const Ee=(Je=se.target.files)==null?void 0:Je[0];if(!Ee)return;ve.current=!0,vn(null),mi(null);const je=Sy(Ee);if(je){U(null),Ae(Lt=>(Lt&&URL.revokeObjectURL(Lt),null)),ri.current&&(ri.current.value=""),Ut(je),te("invalid");return}U(Ee),Ae(Lt=>(Lt&&URL.revokeObjectURL(Lt),URL.createObjectURL(Ee))),Ut(null),te("selected")},[]),Lr=w.useCallback(async se=>{var je;const Ee=(je=se.target.files)==null?void 0:je[0];if(Mn.current&&(Mn.current.value=""),!(!Ee||!e)){ve.current=!0,vn(null),cr(!0),Ut(null);try{let Je;try{Je=await Ku(Ee)}catch(Kn){U(null),Ae(hs=>(hs&&URL.revokeObjectURL(hs),null)),Ut(Kn instanceof Error?Kn.message:"Could not import image");return}const Lt=Je.type==="image/jpeg"?"jpg":"webp",Mi=new File([Je],`cover.${Lt}`,{type:Je.type}),oi=new FormData;oi.append("file",Mi);const wn=await i(`/api/stories/${e}/import-cover`,{method:"POST",body:oi});if(!wn.ok){const Kn=await wn.json().catch(()=>({}));Ut(Kn.error||"Cover import failed");return}U(Mi),Ae(Kn=>(Kn&&URL.revokeObjectURL(Kn),URL.createObjectURL(Mi))),mi(null),te("selected"),Ut(null)}catch{Ut("Cover import failed")}finally{cr(!1)}}},[e,i]),Or=w.useCallback(async se=>{if(se.size>1024*1024){qe("Image exceeds 1MB limit");return}if(!["image/webp","image/jpeg"].includes(se.type)){qe("Only WebP and JPEG images are accepted");return}Oe(!0),qe(null);try{const je=new FormData;je.append("file",se);const Je=await i("/api/publish/upload-plot-image",{method:"POST",body:je});if(!Je.ok){const Mi=await Je.json();throw new Error(Mi.error||"Upload failed")}const Lt=await Je.json();vt(Mi=>[...Mi,{cid:Lt.cid,url:Lt.url}])}catch(je){qe(je instanceof Error?je.message:"Upload failed")}finally{Oe(!1),Qe.current&&(Qe.current.value="")}},[i]),Qt=w.useCallback(se=>{var je;const Ee=(je=se.target.files)==null?void 0:je[0];Ee&&Or(Ee)},[Or]),Vn=w.useCallback(async()=>{if(A!=null&&A.storylineId){Ge(!0),Ut(null),an(!1);try{let se;if(Ht){const je=new FormData;je.append("file",Ht);const Je=await i("/api/publish/upload-cover",{method:"POST",body:je});if(!Je.ok){const Mi=await Je.json();throw new Error(Mi.error||"Cover upload failed")}se=(await Je.json()).cid}const Ee=await i("/api/publish/update-storyline",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storylineId:A.storylineId,...se!==void 0&&{coverCid:se},genre:Gt,language:Rt,isNsfw:Yt})});if(!Ee.ok){const je=await Ee.json();throw new Error(je.error||"Update failed")}an(!0),U(null),se!==void 0&&(At(!0),Ae(je=>(je&&URL.revokeObjectURL(je),null)),te("unknown"),ri.current&&(ri.current.value="")),setTimeout(()=>an(!1),3e3)}catch(se){Ut(se instanceof Error?se.message:"Update failed")}finally{Ge(!1)}}},[A==null?void 0:A.storylineId,Ht,Gt,Rt,Yt,i]);w.useEffect(()=>{Xe(!1),U(null),Ae(null),Ut(null),an(!1),dt(!1),me(!1),vt([]),qe(null),vn(null),mi(null),te("unknown"),ve.current=!1,G(gi.current?"cuts":"text")},[e,t]),w.useEffect(()=>{if(t!=="genesis.md"||!e||!A||A.storylineId||A.status==="published"||A.status==="published-not-indexed"||ve.current)return;let se=!1;return(async()=>{try{const Ee=await i(`/api/stories/${e}/cover-asset`);if(se||!Ee.ok)return;const je=await Ee.json();if(se)return;if(!(je!=null&&je.found)){te("none");return}if(!je.valid){mi(je.error||"Detected cover asset is invalid and was not used"),te("invalid");return}const Je=await i(`/api/stories/${e}/asset/${je.path.replace(/^assets\//,"")}`);if(se||!Je.ok)return;const Lt=await Je.blob(),Mi=new File([Lt],je.path.split("/").pop()||"cover.webp",{type:je.type});if(Sy(Mi)||se||ve.current)return;U(Mi),Ae(oi=>(oi&&URL.revokeObjectURL(oi),URL.createObjectURL(Mi))),vn(je.path),te("detected")}catch{}})(),()=>{se=!0}},[e,t,A,A==null?void 0:A.status,A==null?void 0:A.storylineId,i]),w.useEffect(()=>{if(!$e||!(A!=null&&A.storylineId))return;dt(!1);const se="https://plotlink.xyz";let Ee=!1;return fetch(`${se}/api/storyline/${A.storylineId}`).then(je=>je.ok?je.json():null).then(je=>{if(!Ee){if(!je){Ut("Could not load current story metadata");return}if(je.genre){const Je=Cu(je.genre);Je&&pi(Je)}if(je.language){const Je=rs.find(Lt=>Lt.toLowerCase()===je.language.toLowerCase());Je&&St(Je)}je.isNsfw!==void 0&&ot(!!je.isNsfw),At(!!(je.coverCid||je.coverUrl||je.cover)),dt(!0)}}).catch(()=>{Ee||Ut("Could not load current story metadata")}),()=>{Ee=!0}},[$e,A==null?void 0:A.storylineId]),w.useEffect(()=>{if(ue!=="edit")return;const se=Ee=>{(Ee.metaKey||Ee.ctrlKey)&&Ee.key==="s"&&(Ee.preventDefault(),$t())};return window.addEventListener("keydown",se),()=>window.removeEventListener("keydown",se)},[ue,$t]),w.useEffect(()=>{if((A==null?void 0:A.status)!=="published-not-indexed"||!A.publishedAt)return;const se=new Date(A.publishedAt).getTime(),Ee=300*1e3,je=()=>{const Lt=Math.max(0,Ee-(Date.now()-se));oe(Lt)};je();const Je=setInterval(je,1e3);return()=>clearInterval(Je)},[A==null?void 0:A.status,A==null?void 0:A.publishedAt]);const zr=ae!==null&&ae<=0,Ws=ae!==null&&ae>0?`${Math.floor(ae/6e4)}:${String(Math.floor(ae%6e4/1e3)).padStart(2,"0")}`:null;if(!e||!t)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted",children:d.jsxs("div",{className:"text-center",children:[d.jsx("p",{className:"text-lg font-serif",children:"Select a file to preview"}),d.jsx("p",{className:"text-sm mt-1",children:"Click a story file in the sidebar"})]})});if(R&&!A)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted",children:"Loading..."});const Pr=(ue==="edit"?z:(A==null?void 0:A.content)??"").length,Si=t==="genesis.md",ur=t?/^plot-\d+\.md$/.test(t):!1,wi=c==="cartoon"&&ur,Ln=c==="cartoon"&&Si,cs=Ln||wi,On=(A==null?void 0:A.status)==="published"||(A==null?void 0:A.status)==="published-not-indexed",Xo=S&&cs,vl=Ln?Di?Di.total:null:wi?we===null?null:nt:null,Sa=dD({fileName:t??"",contentType:c,hasGenesis:_,isPublished:On,cutCount:vl,cutProgress:Ln?Di:null}),wa=(Ln||wi)&&!On,Gs=wa?Nm({fileName:t,fileContent:(A==null?void 0:A.content)??"",storySlug:e??"",structureContent:Te,contentType:"cartoon",episodeTitle:vi}):null,yl=!!Gs&&Uo(Gs,t),Ys=wi&&!On&&!Em({fileContent:(A==null?void 0:A.content)??"",episodeTitle:vi}),dn=Ln&&!On?wm((A==null?void 0:A.content)??""):null,Ca=!!dn&&dn.blockers.length>0,Sl="w-full max-w-[32rem] rounded-xl border px-3 py-3",us={muted:"text-muted",accent:"text-accent",error:"text-error",success:"text-green-700"},Ir=se=>{if(!Ln)return null;const Ee=cM({hasSelectedCover:!!Ht,invalid:Zt==="invalid",attached:se});return d.jsxs("div",{className:"flex flex-col gap-0.5","data-testid":"cartoon-cover-status","data-state":Ee.state,children:[d.jsx("span",{className:`text-[11px] font-medium ${us[Ee.tone]}`,children:Ee.label}),d.jsxs("details",{className:"text-[10px] text-muted","data-testid":"cover-details",children:[d.jsx("summary",{className:"cursor-pointer select-none",children:"Cover tips"}),d.jsx("span",{className:"block mt-0.5","data-testid":"cartoon-cover-guidance",children:oM})]})]})},ka=yl||Ys,wl=()=>{if(!wa||!Gs)return null;const se=Si?"Story title":"Episode title";return d.jsxs("div",{className:"flex flex-col gap-0.5","data-testid":"publish-title-preview","data-raw":yl?"true":"false","data-blocked":ka?"true":"false",children:[d.jsxs("span",{className:"text-[11px] text-foreground",children:[d.jsxs("span",{className:"font-medium",children:[se,":"]})," ",d.jsx("span",{className:ka?"text-error font-medium":"text-foreground",children:Gs})]}),yl?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-raw-error",children:["This would publish as a raw filename."," ",Si?"Add a real “# Title” heading to genesis.md":"Set a title in the cut plan (or add a “# Title” to the episode)"," ","before publishing."]}):Ys?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-episode-required",children:["“",Gs,"” is a generic placeholder, not a reader-facing title, so it can’t be published. Set a real episode title in the cut plan (or add a “# Title” to the episode) — e.g. “Episode 01 — The Couple Coupon” — before publishing."]}):null]})},Zo=()=>dn?d.jsxs("div",{className:"flex flex-col gap-1 rounded border border-border bg-surface/50 p-2","data-testid":"cartoon-genesis-readiness","data-blocked":Ca?"true":"false",children:[d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Story opening (Prologue)"}),d.jsx("span",{className:"text-[10px] text-muted","data-testid":"genesis-readiness-hint",children:"Genesis is the first thing readers see. Write it as the story opening/prologue, not a synopsis — set up the premise and stakes, then bridge into Episode 01."}),dn.blockers.map((se,Ee)=>d.jsx("span",{className:"text-[10px] text-error","data-testid":"genesis-readiness-blocker",children:se},`b-${Ee}`)),dn.warnings.map((se,Ee)=>d.jsx("span",{className:"text-[10px] text-amber-600","data-testid":"genesis-readiness-warning",children:se},`w-${Ee}`))]}):null,hr=Si||ur?1e4:null,Sn=!On&&hr!==null&&Pr>hr,Cl=(A==null?void 0:A.content)??"",vr=On?{count:0,warnings:[]}:yM(Cl),dr=d.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden","data-testid":"prose-editor-shell",style:{background:"var(--paper-bg)"},children:[d.jsx("textarea",{ref:be,value:z,onChange:se=>{F(se.target.value),X(!0),Me.current=!0},className:"flex-1 min-h-0 w-full resize-none px-4 py-3 text-sm leading-relaxed focus:outline-none",style:{fontFamily:'"Geist Mono", ui-monospace, monospace',background:"var(--paper-bg)",color:"var(--text)"},spellCheck:!1,"data-testid":"prose-editor-textarea"}),d.jsxs("div",{className:"shrink-0 px-3 py-1.5 border-t border-border flex items-center justify-between bg-surface/95","data-testid":"prose-editor-savebar",children:[d.jsx("span",{className:"text-xs text-muted",children:D?"Unsaved changes":"No changes"}),d.jsx("button",{onClick:$t,disabled:!D||xe,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50 disabled:cursor-not-allowed",children:xe?"Saving...":"Save"})]})]});return d.jsxs("div",{className:"h-full min-h-0 flex flex-col",children:[!Xo&&d.jsxs("div",{className:"border-b border-border",children:[d.jsxs("div",{className:"px-3 py-1.5 flex items-center justify-between",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs font-mono text-muted",children:[x&&d.jsx("button",{onClick:x,"data-testid":"view-progress-btn",className:"text-accent hover:underline font-sans",title:"Story progress overview",children:"← Progress"}),d.jsxs("span",{children:[e,"/",t]}),(A==null?void 0:A.status)==="published"&&d.jsx("span",{className:"text-green-700 font-medium",children:"Published"}),(A==null?void 0:A.status)==="published-not-indexed"&&d.jsx("span",{className:"text-amber-700 font-medium",title:A.indexError,children:"Published (not indexed)"}),(A==null?void 0:A.status)==="pending"&&d.jsx("span",{className:"text-amber-700 font-medium",children:"Pending"})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs("span",{className:`text-xs font-mono ${Sn?"text-error font-medium":"text-muted"}`,children:[Pr.toLocaleString(),hr!==null?`/${hr.toLocaleString()}`:" chars"]}),Sn&&d.jsxs("span",{className:"text-error text-xs font-medium",children:[(Pr-hr).toLocaleString()," over limit"]})]})]}),d.jsxs("div",{className:"flex px-3 gap-1",children:[d.jsx("button",{onClick:()=>ye("preview"),className:`px-3 py-1 text-xs font-medium border-b-2 transition-colors ${ue==="preview"?"border-accent text-accent":"border-transparent text-muted hover:text-foreground"}`,children:"Preview"}),d.jsxs("button",{onClick:()=>ye("edit"),className:`px-3 py-1 text-xs font-medium border-b-2 transition-colors ${ue==="edit"?"border-accent text-accent":"border-transparent text-muted hover:text-foreground"}`,children:["Edit",D&&d.jsx("span",{className:"ml-1 text-amber-600",children:"*"})]})]})]}),ue==="preview"?wi?d.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",style:{background:"var(--paper-bg)"},children:[d.jsxs("div",{className:"flex gap-1 px-3 py-1 border-b border-border",children:[d.jsx("button",{"data-testid":"cartoon-mode-publish",onClick:()=>re("publish"),className:`px-2 py-0.5 text-[11px] rounded ${B==="publish"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Publish Preview"}),d.jsx("button",{"data-testid":"cartoon-mode-inspect",onClick:()=>re("inspect"),className:`px-2 py-0.5 text-[11px] rounded ${B==="inspect"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Cut Inspector"})]}),d.jsx("div",{className:"flex-1 min-h-0",children:B==="publish"?d.jsx(gD,{content:(A==null?void 0:A.content)??"",stage:we}):d.jsx(J3,{storyName:e,fileName:t,authFetch:i,onEditCut:T})})]}):d.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-6 py-4",style:{background:"var(--paper-bg)"},children:A!=null&&A.content?d.jsx("div",{className:"prose max-w-none",children:d.jsx(oS,{remarkPlugins:[uS,BS],rehypePlugins:[[PS,_M]],children:A.content})}):d.jsx("p",{className:"text-muted italic",children:"No content"})}):wi?d.jsx("div",{className:"flex-1 min-h-[22rem] overflow-hidden",style:{background:"var(--paper-bg)"},children:d.jsx(vy,{storyName:e,fileName:t,authFetch:i,language:h,onCutsChanged:()=>ee(se=>se+1),focusRequest:V,onFocusHandled:()=>H(null),onFocusedLetteringModeChange:M,workspaceVisible:N,onWorkspaceVisibleChange:E})}):Ln?d.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",style:{background:"var(--paper-bg)"},children:[d.jsxs("div",{className:"flex gap-1 px-3 py-1 border-b border-border",children:[d.jsx("button",{"data-testid":"genesis-edit-mode-text",onClick:()=>G("text"),className:`px-2 py-0.5 text-[11px] rounded ${$==="text"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Opening text"}),d.jsx("button",{"data-testid":"genesis-edit-mode-cuts",onClick:()=>G("cuts"),className:`px-2 py-0.5 text-[11px] rounded ${$==="cuts"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Cuts"})]}),d.jsx("div",{className:"flex-1 min-h-0",children:$==="cuts"?d.jsx(vy,{storyName:e,fileName:t,authFetch:i,language:h,onCutsChanged:()=>ee(se=>se+1),focusRequest:V,onFocusHandled:()=>H(null),onFocusedLetteringModeChange:M,workspaceVisible:N,onWorkspaceVisibleChange:E}):dr})]}):dr,!Xo&&d.jsx("div",{className:"shrink-0 px-3 py-2 border-t border-border flex items-center justify-between bg-surface/95","data-testid":"preview-panel-footer",children:t==="structure.md"?d.jsx("p",{className:"text-muted text-xs italic","data-testid":"footer-guidance",children:Sa}):(A==null?void 0:A.status)==="published-not-indexed"?d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:"text-amber-700",children:"Published on-chain but not indexed on PlotLink"}),!zr&&d.jsx("button",{onClick:async()=>{if(!(!e||!t||!A.txHash)){Z(!0);try{(await(await i("/api/publish/retry-index",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storyName:e,fileName:t,txHash:A.txHash,content:A.content,storylineId:A.storylineId})})).json()).ok&&(await i(`/api/stories/${e}/${t}/publish-status`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({txHash:A.txHash,storylineId:A.storylineId,contentCid:"",gasCost:""})}),li())}catch{}Z(!1)}},disabled:C,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50",children:C?"Retrying...":`Retry Index${Ws?` (${Ws})`:""}`}),ur&&d.jsx("button",{onClick:()=>{!e||!t||!window.confirm(`This episode is already on-chain — try “Retry Index” first. +`,...o.current()});return/^[\t ]/.test(f)&&(f=Ho(f.charCodeAt(0))+f.slice(1)),f=f?c+" "+f:c,i.options.closeAtx&&(f+=" "+c),p(),h(),f}gS.peek=_R;function gS(e){return e.value||""}function _R(){return"<"}xS.peek=bR;function xS(e,t,i,s){const a=gm(i),o=a==='"'?"Quote":"Apostrophe",c=i.enter("image");let h=i.enter("label");const p=i.createTracker(s);let f=p.move("![");return f+=p.move(i.safe(e.alt,{before:f,after:"]",...p.current()})),f+=p.move("]("),h(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(h=i.enter("destinationLiteral"),f+=p.move("<"),f+=p.move(i.safe(e.url,{before:f,after:">",...p.current()})),f+=p.move(">")):(h=i.enter("destinationRaw"),f+=p.move(i.safe(e.url,{before:f,after:e.title?" ":")",...p.current()}))),h(),e.title&&(h=i.enter(`title${o}`),f+=p.move(" "+a),f+=p.move(i.safe(e.title,{before:f,after:a,...p.current()})),f+=p.move(a),h()),f+=p.move(")"),c(),f}function bR(){return"!"}_S.peek=vR;function _S(e,t,i,s){const a=e.referenceType,o=i.enter("imageReference");let c=i.enter("label");const h=i.createTracker(s);let p=h.move("![");const f=i.safe(e.alt,{before:p,after:"]",...h.current()});p+=h.move(f+"]["),c();const _=i.stack;i.stack=[],c=i.enter("reference");const x=i.safe(i.associationId(e),{before:p,after:"]",...h.current()});return c(),i.stack=_,o(),a==="full"||!f||f!==x?p+=h.move(x+"]"):a==="shortcut"?p=p.slice(0,-1):p+=h.move("]"),p}function vR(){return"!"}bS.peek=yR;function bS(e,t,i){let s=e.value||"",a="`",o=-1;for(;new RegExp("(^|[^`])"+a+"([^`]|$)").test(s);)a+="`";for(/[^ \r\n]/.test(s)&&(/^[ \r\n]/.test(s)&&/[ \r\n]$/.test(s)||/^`|`$/.test(s))&&(s=" "+s+" ");++o\u007F]/.test(e.url))}yS.peek=SR;function yS(e,t,i,s){const a=gm(i),o=a==='"'?"Quote":"Apostrophe",c=i.createTracker(s);let h,p;if(vS(e,i)){const _=i.stack;i.stack=[],h=i.enter("autolink");let x=c.move("<");return x+=c.move(i.containerPhrasing(e,{before:x,after:">",...c.current()})),x+=c.move(">"),h(),i.stack=_,x}h=i.enter("link"),p=i.enter("label");let f=c.move("[");return f+=c.move(i.containerPhrasing(e,{before:f,after:"](",...c.current()})),f+=c.move("]("),p(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(p=i.enter("destinationLiteral"),f+=c.move("<"),f+=c.move(i.safe(e.url,{before:f,after:">",...c.current()})),f+=c.move(">")):(p=i.enter("destinationRaw"),f+=c.move(i.safe(e.url,{before:f,after:e.title?" ":")",...c.current()}))),p(),e.title&&(p=i.enter(`title${o}`),f+=c.move(" "+a),f+=c.move(i.safe(e.title,{before:f,after:a,...c.current()})),f+=c.move(a),p()),f+=c.move(")"),h(),f}function SR(e,t,i){return vS(e,i)?"<":"["}SS.peek=wR;function SS(e,t,i,s){const a=e.referenceType,o=i.enter("linkReference");let c=i.enter("label");const h=i.createTracker(s);let p=h.move("[");const f=i.containerPhrasing(e,{before:p,after:"]",...h.current()});p+=h.move(f+"]["),c();const _=i.stack;i.stack=[],c=i.enter("reference");const x=i.safe(i.associationId(e),{before:p,after:"]",...h.current()});return c(),i.stack=_,o(),a==="full"||!f||f!==x?p+=h.move(x+"]"):a==="shortcut"?p=p.slice(0,-1):p+=h.move("]"),p}function wR(){return"["}function xm(e){const t=e.options.bullet||"*";if(t!=="*"&&t!=="+"&&t!=="-")throw new Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function CR(e){const t=xm(e),i=e.options.bulletOther;if(!i)return t==="*"?"-":"*";if(i!=="*"&&i!=="+"&&i!=="-")throw new Error("Cannot serialize items with `"+i+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(i===t)throw new Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+i+"`) to be different");return i}function kR(e){const t=e.options.bulletOrdered||".";if(t!=="."&&t!==")")throw new Error("Cannot serialize items with `"+t+"` for `options.bulletOrdered`, expected `.` or `)`");return t}function wS(e){const t=e.options.rule||"*";if(t!=="*"&&t!=="-"&&t!=="_")throw new Error("Cannot serialize rules with `"+t+"` for `options.rule`, expected `*`, `-`, or `_`");return t}function ER(e,t,i,s){const a=i.enter("list"),o=i.bulletCurrent;let c=e.ordered?kR(i):xm(i);const h=e.ordered?c==="."?")":".":CR(i);let p=t&&i.bulletLastUsed?c===i.bulletLastUsed:!1;if(!e.ordered){const _=e.children?e.children[0]:void 0;if((c==="*"||c==="-")&&_&&(!_.children||!_.children[0])&&i.stack[i.stack.length-1]==="list"&&i.stack[i.stack.length-2]==="listItem"&&i.stack[i.stack.length-3]==="list"&&i.stack[i.stack.length-4]==="listItem"&&i.indexStack[i.indexStack.length-1]===0&&i.indexStack[i.indexStack.length-2]===0&&i.indexStack[i.indexStack.length-3]===0&&(p=!0),wS(i)===c&&_){let x=-1;for(;++x-1?t.start:1)+(i.options.incrementListMarker===!1?0:t.children.indexOf(e))+o);let c=o.length+1;(a==="tab"||a==="mixed"&&(t&&t.type==="list"&&t.spread||e.spread))&&(c=Math.ceil(c/4)*4);const h=i.createTracker(s);h.move(o+" ".repeat(c-o.length)),h.shift(c);const p=i.enter("listItem"),f=i.indentLines(i.containerFlow(e,h.current()),_);return p(),f;function _(x,b,v){return b?(v?"":" ".repeat(c))+x:(v?o:o+" ".repeat(c-o.length))+x}}function TR(e,t,i,s){const a=i.enter("paragraph"),o=i.enter("phrasing"),c=i.containerPhrasing(e,s);return o(),a(),c}const AR=Gu(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function RR(e,t,i,s){return(e.children.some(function(c){return AR(c)})?i.containerPhrasing:i.containerFlow).call(i,e,s)}function DR(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}CS.peek=MR;function CS(e,t,i,s){const a=DR(i),o=i.enter("strong"),c=i.createTracker(s),h=c.move(a+a);let p=c.move(i.containerPhrasing(e,{after:a,before:h,...c.current()}));const f=p.charCodeAt(0),_=Lu(s.before.charCodeAt(s.before.length-1),f,a);_.inside&&(p=Ho(f)+p.slice(1));const x=p.charCodeAt(p.length-1),b=Lu(s.after.charCodeAt(0),x,a);b.inside&&(p=p.slice(0,-1)+Ho(x));const v=c.move(a+a);return o(),i.attentionEncodeSurroundingInfo={after:b.outside,before:_.outside},h+p+v}function MR(e,t,i){return i.options.strong||"*"}function BR(e,t,i,s){return i.safe(e.value,s)}function LR(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 OR(e,t,i){const s=(wS(i)+(i.options.ruleSpaces?" ":"")).repeat(LR(i));return i.options.ruleSpaces?s.slice(0,-1):s}const kS={blockquote:sR,break:Kv,code:hR,definition:fR,emphasis:mS,hardBreak:Kv,heading:xR,html:gS,image:xS,imageReference:_S,inlineCode:bS,link:yS,linkReference:SS,list:ER,listItem:jR,paragraph:TR,root:RR,strong:CS,text:BR,thematicBreak:OR};function zR(){return{enter:{table:PR,tableData:Xv,tableHeader:Xv,tableRow:HR},exit:{codeText:UR,table:IR,tableData:Df,tableHeader:Df,tableRow:Df}}}function PR(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 IR(e){this.exit(e),this.data.inTable=void 0}function HR(e){this.enter({type:"tableRow",children:[]},e)}function Df(e){this.exit(e)}function Xv(e){this.enter({type:"tableCell",children:[]},e)}function UR(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,$R));const i=this.stack[this.stack.length-1];i.type,i.value=t,this.exit(e)}function $R(e,t){return t==="|"?t:e}function FR(e){const t=e||{},i=t.tableCellPadding,s=t.tablePipeAlign,a=t.stringLength,o=i?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:` +`,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:b,table:c,tableCell:p,tableRow:h}};function c(v,S,N,B){return f(_(v,N,B),v.align)}function h(v,S,N,B){const E=x(v,N,B),O=f([E]);return O.slice(0,O.indexOf(` +`))}function p(v,S,N,B){const E=N.enter("tableCell"),O=N.enter("phrasing"),H=N.containerPhrasing(v,{...B,before:o,after:o});return O(),E(),H}function f(v,S){return nR(v,{align:S,alignDelimiters:s,padding:i,stringLength:a})}function _(v,S,N){const B=v.children;let E=-1;const O=[],H=S.enter("table");for(;++E0&&!i&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),i}const l3={tokenize:m3,partial:!0};function o3(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:d3,continuation:{tokenize:f3},exit:p3}},text:{91:{name:"gfmFootnoteCall",tokenize:h3},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:c3,resolveTo:u3}}}}function c3(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=_r(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 u3(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 h3(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(_r(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 d3(e,t,i){const s=this,a=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let o,c=0,h;return p;function p(S){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionLabelMarker"),f}function f(S){return S===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",_):i(S)}function _(S){if(c>999||S===93&&!h||S===null||S===91||qt(S))return i(S);if(S===93){e.exit("chunkString");const N=e.exit("gfmFootnoteDefinitionLabelString");return o=_r(s.sliceSerialize(N)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),b}return qt(S)||(h=!0),c++,e.consume(S),S===92?x:_}function x(S){return S===91||S===92||S===93?(e.consume(S),c++,_):_(S)}function b(S){return S===58?(e.enter("definitionMarker"),e.consume(S),e.exit("definitionMarker"),a.includes(o)||a.push(o),vt(e,v,"gfmFootnoteDefinitionWhitespace")):i(S)}function v(S){return t(S)}}function f3(e,t,i){return e.check(Yo,t,e.attempt(l3,t,i))}function p3(e){e.exit("gfmFootnoteDefinition")}function m3(e,t,i){const s=this;return vt(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 g3(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 B=c.exit("strikethroughSequenceTemporary"),E=pl(S);return B._open=!E||E===2&&!!N,B._close=!N||N===2&&!!E,h(S)}}}class x3{constructor(){this.map=[]}add(t,i,s){_3(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 _3(e,t,i,s){let a=0;if(!(i===0&&s.length===0)){for(;a-1;){const V=s.events[re][1].type;if(V==="lineEnding"||V==="linePrefix")re--;else break}const F=re>-1?s.events[re][1].type:null,Y=F==="tableHead"||F==="tableRow"?D:p;return Y===D&&s.parser.lazy[s.now().line]?i(L):Y(L)}function p(L){return e.enter("tableHead"),e.enter("tableRow"),f(L)}function f(L){return L===124||(c=!0,o+=1),_(L)}function _(L){return L===null?i(L):Ge(L)?o>1?(o=0,s.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(L),e.exit("lineEnding"),v):i(L):pt(L)?vt(e,_,"whitespace")(L):(o+=1,c&&(c=!1,a+=1),L===124?(e.enter("tableCellDivider"),e.consume(L),e.exit("tableCellDivider"),c=!0,_):(e.enter("data"),x(L)))}function x(L){return L===null||L===124||qt(L)?(e.exit("data"),_(L)):(e.consume(L),L===92?b:x)}function b(L){return L===92||L===124?(e.consume(L),x):x(L)}function v(L){return s.interrupt=!1,s.parser.lazy[s.now().line]?i(L):(e.enter("tableDelimiterRow"),c=!1,pt(L)?vt(e,S,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(L):S(L))}function S(L){return L===45||L===58?B(L):L===124?(c=!0,e.enter("tableCellDivider"),e.consume(L),e.exit("tableCellDivider"),N):W(L)}function N(L){return pt(L)?vt(e,B,"whitespace")(L):B(L)}function B(L){return L===58?(o+=1,c=!0,e.enter("tableDelimiterMarker"),e.consume(L),e.exit("tableDelimiterMarker"),E):L===45?(o+=1,E(L)):L===null||Ge(L)?A(L):W(L)}function E(L){return L===45?(e.enter("tableDelimiterFiller"),O(L)):W(L)}function O(L){return L===45?(e.consume(L),O):L===58?(c=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(L),e.exit("tableDelimiterMarker"),H):(e.exit("tableDelimiterFiller"),H(L))}function H(L){return pt(L)?vt(e,A,"whitespace")(L):A(L)}function A(L){return L===124?S(L):L===null||Ge(L)?!c||a!==o?W(L):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(L)):W(L)}function W(L){return i(L)}function D(L){return e.enter("tableRow"),ne(L)}function ne(L){return L===124?(e.enter("tableCellDivider"),e.consume(L),e.exit("tableCellDivider"),ne):L===null||Ge(L)?(e.exit("tableRow"),t(L)):pt(L)?vt(e,ne,"whitespace")(L):(e.enter("data"),ue(L))}function ue(L){return L===null||L===124||qt(L)?(e.exit("data"),ne(L)):(e.consume(L),L===92?be:ue)}function be(L){return L===92||L===124?(e.consume(L),ue):ue(L)}}function S3(e,t){let i=-1,s=!0,a=0,o=[0,0,0,0],c=[0,0,0,0],h=!1,p=0,f,_,x;const b=new x3;for(;++ii[2]+1){const S=i[2]+1,N=i[3]-i[2]-1;e.add(S,N,[])}}e.add(i[3]+1,0,[["exit",x,t]])}return a!==void 0&&(o.end=Object.assign({},ll(t.events,a)),e.add(a,0,[["exit",o,t]]),o=void 0),o}function Qv(e,t,i,s,a){const o=[],c=ll(t.events,i);a&&(a.end=Object.assign({},c),o.push(["exit",a,t])),s.end=Object.assign({},c),o.push(["exit",s,t]),e.add(i+1,0,o)}function ll(e,t){const i=e[t],s=i[0]==="enter"?"start":"end";return i[1][s]}const w3={name:"tasklistCheck",tokenize:k3};function C3(){return{text:{91:w3}}}function k3(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 Ge(p)?t(p):pt(p)?e.check({tokenize:E3},t,i)(p):i(p)}}function E3(e,t,i){return vt(e,s,"whitespace");function s(a){return a===null?i(a):t(a)}}function N3(e){return U0([QR(),o3(),g3(e),v3(),C3()])}const j3={};function BS(e){const t=this,i=e||j3,s=t.data(),a=s.micromarkExtensions||(s.micromarkExtensions=[]),o=s.fromMarkdownExtensions||(s.fromMarkdownExtensions=[]),c=s.toMarkdownExtensions||(s.toMarkdownExtensions=[]);a.push(N3(i)),o.push(VR()),c.push(KR(i))}const da=["ariaDescribedBy","ariaLabel","ariaLabelledBy"],ml={ancestors:{tbody:["table"],td:["table"],th:["table"],thead:["table"],tfoot:["table"],tr:["table"]},attributes:{a:[...da,"dataFootnoteBackref","dataFootnoteRef",["className","data-footnote-backref"],"href"],blockquote:["cite"],code:[["className",/^language-./]],del:["cite"],div:["itemScope","itemType"],dl:[...da],h2:[["className","sr-only"]],img:[...da,"longDesc","src"],input:[["disabled",!0],["type","checkbox"]],ins:["cite"],li:[["className","task-list-item"]],ol:[...da,["className","contains-task-list"]],q:["cite"],section:["dataFootnotes",["className","footnotes"]],source:["srcSet"],summary:[...da],table:[...da],ul:[...da,["className","contains-task-list"]],"*":["abbr","accept","acceptCharset","accessKey","action","align","alt","axis","border","cellPadding","cellSpacing","char","charOff","charSet","checked","clear","colSpan","color","cols","compact","coords","dateTime","dir","encType","frame","hSpace","headers","height","hrefLang","htmlFor","id","isMap","itemProp","label","lang","maxLength","media","method","multiple","name","noHref","noShade","noWrap","open","prompt","readOnly","rev","rowSpan","rows","rules","scope","selected","shape","size","span","start","summary","tabIndex","title","useMap","vAlign","value","width"]},clobber:["ariaDescribedBy","ariaLabelledBy","id","name"],clobberPrefix:"user-content-",protocols:{cite:["http","https"],href:["http","https","irc","ircs","mailto","xmpp"],longDesc:["http","https"],src:["http","https"]},required:{input:{disabled:!0,type:"checkbox"}},strip:["script"],tagNames:["a","b","blockquote","br","code","dd","del","details","div","dl","dt","em","h1","h2","h3","h4","h5","h6","hr","i","img","input","ins","kbd","li","ol","p","picture","pre","q","rp","rt","ruby","s","samp","section","source","span","strike","strong","sub","summary","sup","table","tbody","td","tfoot","th","thead","tr","tt","ul","var"]},Hs={}.hasOwnProperty;function T3(e,t){let i={type:"root",children:[]};const s={schema:t?{...ml,...t}:ml,stack:[]},a=LS(s,e);return a&&(Array.isArray(a)?a.length===1?i=a[0]:i.children=a:i=a),i}function LS(e,t){if(t&&typeof t=="object"){const i=t;switch(typeof i.type=="string"?i.type:""){case"comment":return A3(e,i);case"doctype":return R3(e,i);case"element":return D3(e,i);case"root":return M3(e,i);case"text":return B3(e,i)}}}function A3(e,t){if(e.schema.allowComments){const i=typeof t.value=="string"?t.value:"",s=i.indexOf("-->"),o={type:"comment",value:s<0?i:i.slice(0,s)};return Ko(o,t),o}}function R3(e,t){if(e.schema.allowDoctypes){const i={type:"doctype"};return Ko(i,t),i}}function D3(e,t){const i=typeof t.tagName=="string"?t.tagName:"";e.stack.push(i);const s=OS(e,t.children),a=L3(e,t.properties);e.stack.pop();let o=!1;if(i&&i!=="*"&&(!e.schema.tagNames||e.schema.tagNames.includes(i))&&(o=!0,e.schema.ancestors&&Hs.call(e.schema.ancestors,i))){const h=e.schema.ancestors[i];let p=-1;for(o=!1;++p1){let a=!1,o=0;for(;++o-1&&o>p||c>-1&&o>c||h>-1&&o>h)return!0;let f=-1;for(;++f4&&t.slice(0,4).toLowerCase()==="data")return i}function PS(e){return function(t){return T3(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"],ss=["English","Chinese","Korean","Japanese","Spanish","French","Hindi","Arabic","Portuguese","Russian","Others"];function IS(e){return e.toLowerCase().replace(/[^a-z0-9+]/g,"")}const P3=Object.fromEntries(hl.map(e=>[IS(e),e])),I3={scifi:"Science Fiction",sf:"Science Fiction",comedy:"Humor",humour:"Humor",ya:"Teen Fiction",youngadult:"Teen Fiction",lgbt:"LGBTQ+",lgbtq:"LGBTQ+","lgbtqia+":"LGBTQ+",historical:"Historical Fiction",scary:"Horror"};function Cu(e){if(!e)return null;const t=IS(e.trim());return t?P3[t]??I3[t]??null:null}function HS(e,t){const i=t.startsWith("assets/")?t.slice(7):t;return`/api/stories/${e}/asset/${i}`}function bm(e,t,i){const[s,a]=w.useState({url:null,loading:!!t,error:!1});return w.useEffect(()=>{if(!t){a({url:null,loading:!1,error:!1});return}let o=null,c=!1;return a({url:null,loading:!0,error:!1}),(async()=>{try{const h=await i(HS(e,t));if(!h.ok)throw new Error(`asset request failed (${h.status})`);const p=await h.blob();if(c)return;o=URL.createObjectURL(p),a({url:o,loading:!1,error:!1})}catch{c||a({url:null,loading:!1,error:!0})}})(),()=>{c=!0,o&&URL.revokeObjectURL(o)}},[e,t,i]),s}function ty({storyName:e,assetPath:t,authFetch:i,alt:s,className:a}){const{url:o,loading:c,error:h}=bm(e,t,i);return h||!c&&!o?d.jsx("div",{className:"w-full aspect-video bg-surface border border-border rounded flex items-center justify-center",children:d.jsx("span",{className:"text-xs text-muted",children:"Image not available"})}):o?d.jsx("img",{src:o,alt:s,className:a??"w-full rounded border border-border"}):d.jsx("div",{className:"w-full aspect-video bg-surface border border-border rounded flex items-center justify-center","data-testid":"asset-loading",children:d.jsx("span",{className:"text-xs text-muted",children:"Loading image…"})})}function iy(e,t,i,s){const a=t.split(/\s+/).filter(Boolean);if(a.length===0)return[""];const o=[];let c="";for(const h of a){const p=c?`${c} ${h}`:h;!c||e(p,s)<=i?c=p:(o.push(c),c=h)}return c&&o.push(c),o}function jo(e,t,i,s,a){const o=a.lineHeightFactor??1.2,c=a.speakerScale??.8,h=a.paddingX??Math.max(2,i*.06),p=a.paddingY??Math.max(2,s*.08),f=Math.max(1,i-2*h),_=Math.max(1,s-2*p),x=Math.max(a.minFontSize,a.maxFontSize),b=Math.max(1,Math.min(a.minFontSize,x)),v=N=>{const B=a.hasSpeaker?N*c:0,E=a.hasSpeaker?B*o:0,O=Math.max(1,_-E),H=a.fontWeight??400,A=iy((ne,ue)=>e(ne,ue,H),t,f,N),W=A.length*N*o,D=A.every(ne=>e(ne,N,H)<=f+.5);return{lines:A,ok:W<=O&&D}};if(typeof a.fontSize=="number"&&Number.isFinite(a.fontSize)&&a.fontSize>0){const N=Math.max(1,a.fontSize),{lines:B,ok:E}=v(N);return{lines:B,fontSize:N,lineHeight:N*o,speakerFontSize:a.hasSpeaker?N*c:0,overflow:!E}}for(let N=x;N>=b;N-=.5){const{lines:B,ok:E}=v(N);if(E)return{lines:B,fontSize:N,lineHeight:N*o,speakerFontSize:a.hasSpeaker?N*c:0,overflow:!1}}return{lines:iy(e,t,f,b),fontSize:b,lineHeight:b*o,speakerFontSize:a.hasSpeaker?b*c:0,overflow:!0}}function H3(e){return{minFontSize:Math.max(1,e*.022),maxFontSize:Math.max(1,e*.05)}}const US=["speech","narration","sfx"],U3=2;function Rr(e,t,i){return Math.min(i,Math.max(t,e))}function dl(e,t,i){return typeof e=="number"&&Number.isFinite(e)?Rr(e,t,i):void 0}function vm(e){if(!e||typeof e!="object")return;const t=e,i=t.mode==="manual"?"manual":t.mode==="auto"?"auto":void 0,s=dl(t.fontScale,.015,.12),a=t.fontWeight===700?700:t.fontWeight===400?400:void 0,o=dl(t.lineHeightFactor,.9,2),c=dl(t.speakerScale,.5,1.5);if(!(!i&&s===void 0&&a===void 0&&o===void 0&&c===void 0))return{...i?{mode:i}:{},...s!==void 0?{fontScale:s}:{},...a!==void 0?{fontWeight:a}:{},...o!==void 0?{lineHeightFactor:o}:{},...c!==void 0?{speakerScale:c}:{}}}function Vu(e){if(!e||typeof e!="object")return;const t=e,i=dl(t.paddingX,0,.25),s=dl(t.paddingY,0,.25),a=dl(t.cornerRadius,0,.49);if(!(i===void 0&&s===void 0&&a===void 0))return{...i!==void 0?{paddingX:i}:{},...s!==void 0?{paddingY:s}:{},...a!==void 0?{cornerRadius:a}:{}}}function To(e,t,i,s){const{minFontSize:a,maxFontSize:o}=H3(t),c=vm(e.textStyle),h=Vu(e.bubbleStyle);return{minFontSize:a,maxFontSize:o,hasSpeaker:e.type!=="sfx"&&!!e.speaker,...(c==null?void 0:c.lineHeightFactor)!==void 0?{lineHeightFactor:c.lineHeightFactor}:{},...(c==null?void 0:c.speakerScale)!==void 0?{speakerScale:c.speakerScale}:{},...(c==null?void 0:c.fontWeight)!==void 0?{fontWeight:c.fontWeight}:{},...(c==null?void 0:c.mode)==="manual"&&c.fontScale!==void 0?{fontSize:Math.max(1,t*c.fontScale)}:{},...(h==null?void 0:h.paddingX)!==void 0?{paddingX:i*h.paddingX}:{},...(h==null?void 0:h.paddingY)!==void 0?{paddingY:s*h.paddingY}:{}}}function $S(e,t,i){const s=Vu(e.bubbleStyle);return(s==null?void 0:s.cornerRadius)!==void 0?Math.min(t,i)*s.cornerRadius:void 0}function FS(e,t){const i=Math.min(e,t);return Math.max(0,Math.min(i*.4,i/2))}function ny(e,t,i,s,a){const o=Math.max(0,i-2*s),c=Math.max(1,Math.min(a,o)/2),h=t+s+c,p=t+i-s-c;return{center:p>=h?Rr(e,h,p):t+i/2,half:c}}function ym(e,t,i,s,a,o){const c=e+i/2,h=t+s/2,p=e+a.x*i,f=t+a.y*s;if(p>=e&&p<=e+i&&f>=t&&f<=t+s)return null;const _=p-c,x=f-h,b=Math.max(6,Math.min(i,s)*.3),v=o??FS(i,s);if(Math.abs(x)>=Math.abs(_)){const E=x>=0?t+s:t,{center:O,half:H}=ny(p,e,i,v,b);return{tip:{x:p,y:f},base1:{x:O-H,y:E},base2:{x:O+H,y:E}}}const S=_>=0?e+i:e,{center:N,half:B}=ny(f,t,s,v,b);return{tip:{x:p,y:f},base1:{x:S,y:N-B},base2:{x:S,y:N+B}}}function $3(e){return e.type!=="speech"||!e.tailAnchor?!1:ym(0,0,1,1,e.tailAnchor)!==null}function F3(e,t,i,s,a,o){const c=o??FS(i,s),h=e+i,p=t+s,f=!!a&&a.base1.y===t&&a.base2.y===t,_=!!a&&a.base1.x===h&&a.base2.x===h,x=!!a&&a.base1.y===p&&a.base2.y===p,b=!!a&&a.base1.x===e&&a.base2.x===e,v=[{k:"M",x:e+c,y:t}];return f&&a&&v.push({k:"L",x:a.base1.x,y:t},{k:"L",x:a.tip.x,y:a.tip.y},{k:"L",x:a.base2.x,y:t}),v.push({k:"L",x:h-c,y:t},{k:"A",cornerX:h,cornerY:t,x:h,y:t+c,r:c}),_&&a&&v.push({k:"L",x:h,y:a.base1.y},{k:"L",x:a.tip.x,y:a.tip.y},{k:"L",x:h,y:a.base2.y}),v.push({k:"L",x:h,y:p-c},{k:"A",cornerX:h,cornerY:p,x:h-c,y:p,r:c}),x&&a&&v.push({k:"L",x:a.base2.x,y:p},{k:"L",x:a.tip.x,y:a.tip.y},{k:"L",x:a.base1.x,y:p}),v.push({k:"L",x:e+c,y:p},{k:"A",cornerX:e,cornerY:p,x:e,y:p-c,r:c}),b&&a&&v.push({k:"L",x:e,y:a.base2.y},{k:"L",x:a.tip.x,y:a.tip.y},{k:"L",x:e,y:a.base1.y}),v.push({k:"L",x:e,y:t+c},{k:"A",cornerX:e,cornerY:t,x:e+c,y:t,r:c}),v}function qS(e,t,i,s,a,o){const c=F3(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 q3(e){return e.x<-1e-6||e.y<-1e-6||e.x+e.width>1+1e-6||e.y+e.height>1+1e-6}let ry=0;function Lp(e,t=.1,i=.1){return ry++,{id:`overlay-${Date.now()}-${ry}`,type:e,x:t,y:i,width:e==="sfx"?.15:.25,height:e==="sfx"?.08:.12,text:"",...e==="speech"?{speaker:"",tailAnchor:{x:.5,y:1.2}}:{}}}function WS(e,t,i){return{width:Math.min(e==="sfx"?.3:.5,Math.max(.15,1-t)),height:Math.min(e==="sfx"?.1:.2,Math.max(.06,1-i))}}const du=.05;function Vi(e){return typeof e=="number"&&Number.isFinite(e)}function W3(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:Rr(o?1-t-du:(1-t)/2,0,1),_=c?du:Rr(h?1-i-du:(1-i)/2,0,1);return{x:f,y:_}}let G3=0;function Y3(e){if(!e||typeof e!="object")return null;const t=e,i=US.includes(t.type)?t.type:"speech",s=typeof t.text=="string"?t.text:"";let a=Vi(t.width)&&t.width>0?t.width:i==="sfx"?.15:.4,o=Vi(t.height)&&t.height>0?t.height:i==="sfx"?.08:.16,c,h;if(Vi(t.x)&&Vi(t.y))c=t.x,h=t.y;else{const b=typeof t.position=="string"?W3(t.position,a,o):null;if(!b)return null;c=b.x,h=b.y}c=Rr(c,0,1),h=Rr(h,0,1),a=Rr(a,.02,1),o=Rr(o,.02,1);const f={id:typeof t.id=="string"&&t.id?t.id:`overlay-norm-${++G3}`,type:i,x:c,y:h,width:a,height:o,text:s};if(i==="speech"){f.speaker=typeof t.speaker=="string"?t.speaker:"";const b=t.tailAnchor;f.tailAnchor=b&&Vi(b.x)&&Vi(b.y)?{x:b.x,y:b.y}:{x:.5,y:1.2}}else typeof t.speaker=="string"&&t.speaker&&(f.speaker=t.speaker);const _=vm(t.textStyle),x=Vu(t.bubbleStyle);return _&&(f.textStyle=_),x&&(f.bubbleStyle=x),f}function V3(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.id=="string"&&!!t.id&&US.includes(t.type)&&Vi(t.x)&&Vi(t.y)&&Vi(t.width)&&Vi(t.height)&&typeof t.text=="string"}function K3(e){const t=Array.isArray(e)?e:[],i=[],s=[];let a=!Array.isArray(e);return t.forEach((o,c)=>{const h=Y3(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),V3(o)||(a=!0)}),{overlays:i,changed:a,invalid:s}}function a4(e){for(let t=0;t0&&i.height>0))return{valid:!1,error:`Overlay ${t+1}${i!=null&&i.type?` (${i.type})`:""} has invalid geometry — repair or re-place it in the lettering editor before export`};const a=vm(i==null?void 0:i.textStyle);if(i!=null&&i.textStyle&&!a)return{valid:!1,error:`Overlay ${t+1}${i!=null&&i.type?` (${i.type})`:""} has invalid typography controls — reset them in the lettering editor before export`};const o=Vu(i==null?void 0:i.bubbleStyle);if(i!=null&&i.bubbleStyle&&!o)return{valid:!1,error:`Overlay ${t+1}${i!=null&&i.type?` (${i.type})`:""} has invalid bubble controls — reset them in the lettering editor before export`}}return{valid:!0}}const sy=new Set(["speech","narration"]),X3=.12;function ay(e){return Vi(e==null?void 0:e.x)&&Vi(e==null?void 0:e.y)&&Vi(e==null?void 0:e.width)&&Vi(e==null?void 0:e.height)&&e.width>0&&e.height>0}function Z3(e,t=X3){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 _n(e){return e.kind==="text"}function Q3(e){return!!e.finalImagePath||!!e.exportedAt?{key:"review",label:"Review final panel",opensEditor:!0}:e.cleanImagePath||_n(e)?{key:"letter",label:"Letter this cut",opensEditor:!0}:{key:"add-art",label:"Add clean art for this cut",opensEditor:!1}}function GS(e,t=U3){return!e.finalImagePath||!(e.overlays??[]).some($3)?!1:(e.finalRendererVersion??0)0)||!(s>0)?null:{width:ly,height:Math.round(ly*s/i)}}function fu({cut:e}){return e.dialogue.length>0||e.narration||e.sfx?d.jsxs("div",{className:"space-y-1.5","data-testid":`cut-${e.id}-overlay`,children:[e.dialogue.map((i,s)=>d.jsxs("div",{className:"flex gap-2 text-xs",children:[d.jsxs("span",{className:"font-medium text-foreground flex-shrink-0",children:[i.speaker,":"]}),d.jsx("span",{className:"text-foreground",children:i.text})]},s)),e.narration&&d.jsx("div",{className:"border-l-2 border-border pl-3",children:d.jsx("p",{className:"text-xs text-muted italic",children:e.narration})}),e.sfx&&d.jsxs("p",{className:"text-xs font-mono text-muted",children:["SFX: ",e.sfx]})]}):null}function J3({cut:e,storyName:t,authFetch:i,onEditCut:s}){const a=!!e.finalImagePath,o=!!e.cleanImagePath,c=a||o,h=e.dialogue.length>0||!!e.narration||!!e.sfx,p=e.kind==="text";return d.jsxs("div",{className:"space-y-2",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs("span",{className:"text-[10px] font-mono text-muted bg-surface border border-border rounded px-1.5 py-0.5",children:["#",e.id]}),d.jsx("span",{className:"text-[10px] font-mono text-muted",children:e.shotType}),e.characters.length>0&&d.jsx("span",{className:"text-[10px] text-muted truncate",children:e.characters.join(", ")})]}),a&&d.jsx(ty,{storyName:t,assetPath:e.finalImagePath,authFetch:i,alt:e.description||`Cut ${e.id}`}),!a&&o&&d.jsxs("div",{className:"border border-border rounded overflow-hidden",children:[d.jsx(ty,{storyName:t,assetPath:e.cleanImagePath,authFetch:i,alt:e.description||`Cut ${e.id}`}),d.jsx("div",{className:"px-3 py-2 bg-surface/80 border-t border-border",children:d.jsx(fu,{cut:e})})]}),!c&&p&&d.jsxs("div",{className:"w-full border border-border rounded p-4 space-y-2",style:{background:e.background||void 0},"data-testid":`cut-${e.id}-textpanel`,children:[d.jsx("span",{className:"text-[10px] font-mono text-muted",children:"Text panel"}),h?d.jsx(fu,{cut:e}):d.jsx("p",{className:"text-xs text-muted italic",children:"Empty text panel — open the editor to add text."})]}),!c&&!p&&d.jsxs("div",{className:"w-full bg-surface border border-dashed border-border rounded p-4 space-y-2","data-testid":`cut-${e.id}-pending`,children:[d.jsxs("div",{className:"aspect-video flex flex-col items-center justify-center gap-1 text-center",children:[d.jsx("span",{className:"text-xs text-muted font-medium",children:"Image pending"}),d.jsx("span",{className:"text-[10px] text-muted",children:"Planned image cut — generate & upload the art"})]}),h&&d.jsxs("div",{className:"border-t border-dashed border-border pt-2 space-y-1",children:[d.jsx("span",{className:"text-[10px] font-mono text-muted",children:"Planned text (will be lettered onto the image)"}),d.jsx(fu,{cut:e})]})]}),e.description&&d.jsx("p",{className:"text-xs text-muted italic",children:e.description}),a&&d.jsx(fu,{cut:e}),s&&(()=>{const f=Q3(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 eD({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(J3,{cut:b,storyName:e,authFetch:i,onEditCut:s},b.id))})})}const oy=/!\[[^\]]*\]\([^)]*\)/g,tD=//g,VS=200;function iD(e){const t=(e.match(oy)||[]).length,i=e.length,s=e.replace(tD," ").replace(oy," ").replace(/\s+/g," ").trim();return{imageCount:t,charCount:i,nonImageProse:s,nonImageProsePreview:s.slice(0,VS)}}function nD(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 rD=[/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 sD(e){for(const t of rD){const i=e.match(t);if(i)return i[0]}return null}function Sm(e,t){const i=``,s=``,a=e.indexOf(i),o=e.indexOf(s);return a===-1||o===-1||ob[1].trim());x.length===0?i.push(`${p}: block has no image reference`):x.length>1?i.push(`${p}: block must contain exactly one image reference`):h.uploadedUrl&&x[0]!==h.uploadedUrl&&i.push(`${p}: image URL does not match the recorded uploaded URL`)}/awaiting upload|image pending|final image pending|pending upload/i.test(e)&&i.push("Markdown contains awaiting-upload placeholders");const s=sD(e);s&&i.push(`This episode still has placeholder/instructional text ("${s.slice(0,60)}") — remove it or re-run “Prepare episode for publish” so the published episode is images only`);const a=new Set(t.map(c=>c.uploadedUrl).filter(c=>!!c&&/^https?:\/\//i.test(c))),o=[...e.matchAll(/!\[[^\]]*\]\(([^)]*)\)/g)];for(const c of o){const h=c[1].trim();/^https?:\/\//i.test(h)?a.has(h)||i.push(`Image reference is not a recorded uploaded cut URL: ${h.slice(0,60)}`):i.push(`Invalid image reference (not an http(s) URL): ${h.slice(0,60)}`)}return e.length>1e4&&i.push(`Markdown is ${e.length} chars (limit 10,000)`),{ready:i.length===0,issues:i}}function XS(e,t){const i=t.length;if(i===0)return{stage:"not-started",issues:[],awaitingCount:0,totalCuts:0};if(aD(e,t))return{stage:"planning",issues:[],awaitingCount:0,totalCuts:i};const{ready:s,issues:a}=KS(e,t);if(s)return{stage:"ready",issues:[],awaitingCount:0,totalCuts:i};const o=new Set;for(let p=0;p!c.has(p));return h.length>0?{stage:"error",issues:h,awaitingCount:o.size,totalCuts:i}:{stage:"awaiting-upload",issues:[],awaitingCount:o.size,totalCuts:i}}const Mf=[{key:"assemble",title:"Prepare the episode for publish",test:/markdown block|missing or incomplete/i},{key:"export",title:"Export final images",test:/re-export|older speech-bubble|visible seam/i},{key:"upload",title:"Upload final images",test:/not uploaded|no recorded uploaded url/i},{key:"images",title:"Fix image references",test:/image reference|not an http|does not match|exactly one image/i},{key:"cleanup",title:"Remove leftover text",test:/placeholder|instructional|awaiting-upload|awaiting upload/i},{key:"size",title:"Shorten the episode",test:/\blimit\b|\bchars\b/i}];function lD(e){const t=new Map,i=[],s=[];for(const o of e){const c=o.match(/^Cut (\d+): (.+)$/);if(c){const h=c[2];t.has(h)||(t.set(h,[]),i.push(h)),t.get(h).push(Number(c[1]))}else s.push(o)}return[...i.map(o=>{const c=t.get(o).slice().sort((p,f)=>p-f);return`${c.length===1?`Cut ${c[0]}`:`Cuts ${c.join(", ")}`}: ${o}`}),...s]}function ZS(e){const t=c=>{var h;return((h=Mf.find(p=>p.test.test(c)))==null?void 0:h.key)??"other"},i=new Map;for(const c of e){const h=t(c);i.has(h)||i.set(h,[]),i.get(h).push(c)}const s=[...Mf.map(c=>c.key),"other"],a=c=>{var h;return((h=Mf.find(p=>p.key===c))==null?void 0:h.title)??"Other issues"},o=[];for(const c of s){const h=i.get(c);!h||h.length===0||o.push({key:c,title:a(c),lines:lD(h)})}return o}const oD=220,Bf=/^(genre|logline|synopsis|premise|setting|tone|theme|themes|summary|hook|characters?|cast|arc|status|word\s*count|length|title)\b\s*[:\-–]/i;function wm(e){const t=[],i=[],s=e??"",a=s.match(/^#[ \t]+(.+)$/m),o=!!(a&&a[1].trim());o||t.push("Add a “# Title” heading — the Story opening needs a real title readers see first.");const c=s.replace(/^#\s+.+$/m,"").trim();if(c.lengthx.trim()).filter(Boolean),p=h.filter(x=>/^([-*+]|\d+[.)])\s/.test(x)||Bf.test(x)).length,f=c.split(/\n\s*\n/).map(x=>x.trim()).filter(Boolean),_=f.some(x=>x.length>=120&&!/^([-*+]|\d+[.)])\s/.test(x)&&!Bf.test(x));h.length>0&&p/h.length>=.5||!_?t.push("This reads like a synopsis or outline. Write the Genesis as a reader-facing opening scene that sets up the first beat and stakes, then bridges into Episode 01 — not a logline, genre pitch, or character list."):f.filter(b=>b.length>=40&&!/^([-*+]|\d+[.)])\s/.test(b)&&!Bf.test(b)).length<2&&t.push("Give the opening room to build: open across a few short paragraphs — the premise, what the lead wants, and the hook — that lead into Episode 01, instead of a single dense block that drops readers into a cold scene.")}return{hasTitle:o,blockers:t,warnings:i}}function cD(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)_n(p)?(((h=p.overlays)==null?void 0:h.length)??0)>0&&s++:(t++,p.cleanImagePath&&cD(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 uD={plan:"Plan cuts",clean:"Create clean images",letter:"Add speech bubbles & captions",export:"Export final images",upload:"Upload final images",publish:"Publish to PlotLink"};function So(e,t){return`${e} / ${t} cut${t===1?"":"s"}`}function hD(e){const{cuts:t,published:i=!1}=e,s=Op(t);if(s.total===0)return{steps:[],nextStep:null};const a=s.total>0,o=a&&s.withClean===s.needClean,c=o&&s.withText===s.total,h=c&&s.exported===s.total,p=h&&s.uploaded===s.total,_={plan:a,clean:o,letter:c,export:h,upload:p,publish:p&&i},x=["plan","clean","letter","export","upload","publish"],b=x.findIndex(O=>!_[O]),v=O=>s.needClean>0?So(O,s.needClean):"no image cuts",S={plan:So(s.total,s.total),clean:v(s.withClean),letter:So(s.withText,s.total),export:So(s.exported,s.total),upload:So(s.uploaded,s.total),publish:null},N=x.map((O,H)=>({key:O,label:uD[O],status:b===-1||HVS,a=pD({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] ${gD[a.tone]}`,"data-testid":"cartoon-publish-verdict",children:[d.jsx("p",{className:"font-medium",children:a.headline}),a.detail&&d.jsx("p",{className:"mt-0.5 opacity-90",children:a.detail}),a.action&&d.jsxs("p",{className:"mt-0.5 opacity-90",children:["→ ",a.action]})]}),i.nonImageProse&&d.jsxs("div",{className:"px-4 py-2 border-b border-amber-300 bg-amber-50 text-[11px] text-amber-800","data-testid":"cartoon-nonimage-prose",children:[d.jsx("p",{className:"font-medium",children:"⚠ Non-image text in the published markdown:"}),d.jsxs("p",{className:"font-mono mt-1 whitespace-pre-wrap break-words",children:[i.nonImageProsePreview,s?"…":""]}),d.jsx("p",{className:"mt-1",children:"This text publishes verbatim around the comic images. Remove it (or re-run “Prepare episode for publish”) if it is planning or placeholder prose."})]}),d.jsx("div",{className:"max-w-lg mx-auto px-4 py-6",children:e.trim()?d.jsx("div",{className:"prose max-w-none",children:d.jsx(oS,{remarkPlugins:[uS,BS],rehypePlugins:[[PS,mD]],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 _D="modulepreload",bD=function(e){return"/"+e},cy={},uy=function(t,i,s){let a=Promise.resolve();if(i&&i.length>0){let c=function(f){return Promise.all(f.map(_=>Promise.resolve(_).then(x=>({status:"fulfilled",value:x}),x=>({status:"rejected",reason:x}))))};document.getElementsByTagName("link");const h=document.querySelector("meta[property=csp-nonce]"),p=(h==null?void 0:h.nonce)||(h==null?void 0:h.getAttribute("nonce"));a=c(i.map(f=>{if(f=bD(f),f in cy)return;cy[f]=!0;const _=f.endsWith(".css"),x=_?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${f}"]${x}`))return;const b=document.createElement("link");if(b.rel=_?"stylesheet":_D,_||(b.as="script"),b.crossOrigin="",b.href=f,p&&b.setAttribute("nonce",p),document.head.appendChild(b),_)return new Promise((v,S)=>{b.addEventListener("load",v),b.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${f}`)))})}))}function o(c){const h=new Event("vite:preloadError",{cancelable:!0});if(h.payload=c,window.dispatchEvent(h),!h.defaultPrevented)throw c}return a.then(c=>{for(const h of c||[])h.status==="rejected"&&o(h.reason);return t().catch(o)})},Cm=[{family:"Noto Sans",googleFontsId:"Noto+Sans",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Sans/about",category:"body",weights:[400,500,700],languages:["English","Spanish","French","Portuguese","Russian","Others"]},{family:"Noto Sans KR",googleFontsId:"Noto+Sans+KR",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Sans+KR/about",category:"body",weights:[400,500,700],languages:["Korean"]},{family:"Noto Sans JP",googleFontsId:"Noto+Sans+JP",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Sans+JP/about",category:"body",weights:[400,500,700],languages:["Japanese"]},{family:"Noto Sans SC",googleFontsId:"Noto+Sans+SC",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Sans+SC/about",category:"body",weights:[400,500,700],languages:["Chinese"]},{family:"Noto Sans Devanagari",googleFontsId:"Noto+Sans+Devanagari",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Sans+Devanagari/about",category:"body",weights:[400,500,700],languages:["Hindi"]},{family:"Noto Naskh Arabic",googleFontsId:"Noto+Naskh+Arabic",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Naskh+Arabic/about",category:"body",weights:[400,500,700],languages:["Arabic"]},{family:"Bangers",googleFontsId:"Bangers",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/specimen/Bangers/about",category:"display",weights:[400],languages:[]}],vD="system-ui, sans-serif",yD=Cm.find(e=>e.family==="Noto Sans"),SD=Cm.find(e=>e.category==="display");function QS(e){return Cm.find(i=>i.category==="body"&&i.languages.includes(e))||yD}function JS(){return SD}function e1(e){const t=e.weights.join(";");return`https://fonts.googleapis.com/css2?family=${e.googleFontsId}:wght@${t}&display=swap`}function Ou(e){return`"${e.family}", ${vD}`}function wD(e,t={}){var a,o,c,h;const i=!t.staleExport&&(!!e.finalImagePath||!!e.exportedAt),s=!t.staleExport&&(!!e.uploadedUrl||!!e.uploadedCid);return{hasCleanImage:!!e.cleanImagePath,hasScriptText:(((a=e.dialogue)==null?void 0:a.length)??0)>0||!!((o=e.narration)!=null&&o.trim())||!!((c=e.sfx)!=null&&c.trim()),bubblesPlaced:((h=e.overlays)==null?void 0:h.length)??0,exported:i,uploaded:s}}function cl(e){return JSON.stringify((e??[]).map(t=>[t.type,t.x,t.y,t.width,t.height,t.text,t.speaker??"",t.tailAnchor??null,t.textStyle??null,t.bubbleStyle??null]))}function CD(e){return!e.exported&&!e.uploaded?!1:e.baselineSig!==cl(e.current)}function km(e){var i,s;const t=[];return(e.dialogue??[]).forEach((a,o)=>{var c;(c=a==null?void 0:a.text)!=null&&c.trim()&&t.push({type:"speech",speaker:a.speaker,text:a.text.trim(),key:`speech-${o}`})}),(i=e.narration)!=null&&i.trim()&&t.push({type:"narration",text:e.narration.trim(),key:"narration"}),(s=e.sfx)!=null&&s.trim()&&t.push({type:"sfx",text:e.sfx.trim(),key:"sfx"}),t}function kD(e,t,i){if(e==="narration")return{x:.08,y:.05+Math.min(t,2)*.18};if(e==="sfx"){const c=t%2,h=Math.floor(t/2);return{x:c===0?.1:.62,y:.68+h*.12}}const s=Math.floor(t/2),a=t%2===0,o=.08+s*Math.max(.15,Math.min(.22,i>4?.16:.2));return{x:a?.05:.45,y:o}}function hy(e){const t=km(e);return t.map((i,s)=>{const{x:a,y:o}=kD(i.type,s,t.length),c=Lp(i.type,a,o),h=WS(i.type,a,o);return{...c,...h,text:i.text,...i.type==="speech"?{speaker:i.speaker??""}:{}}})}function Rn(e,t){return e*t}function dy(e,t){return t===0?0:e/t}function fy(e){const t=`gfont-${e.googleFontsId}`;if(document.getElementById(t))return;const i=document.createElement("link");i.id=t,i.rel="stylesheet",i.href=e1(e),document.head.appendChild(i)}const ku={speech:"Speech",narration:"Narration",sfx:"SFX"},ED={speech:"border-foreground/40",narration:"border-muted/40",sfx:"border-accent/40"};function Lf(e){const t=(e.speaker||e.text||"").trim().replace(/\s+/g," ");return t?`“${t.length>18?`${t.slice(0,18)}…`:t}”`:ku[e.type]}const py=.05,ND=[{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 jD({storyName:e,cut:t,plotFile:i,onSave:s,onClose:a,onExported:o,language:c="English",authFetch:h,targetLabel:p,returnOnSave:f=!1,workspaceVisible:_=!1,onToggleWorkspaceVisible:x}){var Gt,mi,At,wt,Yt,ot,Ht;const b=QS(c),v=JS(),S=Ou(b),N=Ou(v);w.useEffect(()=>{fy(b),fy(v)},[b,v]),w.useEffect(()=>{let $=!1;return Y(!1),(async()=>{try{const{ensureFontsReady:we}=await uy(async()=>{const{ensureFontsReady:Ae}=await import("./export-cut-DvUnFkvP.js");return{ensureFontsReady:Ae}},[]);await we([b.family,v.family])}catch{}$||Y(!0)})(),()=>{$=!0}},[b.family,v.family]);const B=bm(e,t.cleanImagePath,h),E=w.useMemo(()=>K3(t.overlays),[t.overlays]),O=E.invalid.length,[H,A]=w.useState(!1),W=O===0&&E.changed&&E.overlays.length>0,[D,ne]=w.useState(()=>E.overlays),[ue,be]=w.useState(()=>cl(E.overlays)),L=w.useRef(null),re=w.useCallback($=>(we,Ae,Ne=400)=>{var Ie;!L.current&&typeof document<"u"&&(L.current=document.createElement("canvas"));const We=(Ie=L.current)==null?void 0:Ie.getContext("2d");return We?(We.font=`${Ne} ${Ae}px ${$}`,We.measureText(we).width):we.length*Ae*.5},[]),[F,Y]=w.useState(!1),[V,U]=w.useState(null),[T,P]=w.useState(!1),[q,xe]=w.useState(!1),[j,R]=w.useState(null),[Z,k]=w.useState(null),[K,ae]=w.useState({x:0,y:0,width:0,height:0}),oe=w.useRef(null),X=w.useRef(null),he=w.useRef(null),ge=w.useCallback(()=>{const $=oe.current;if(!$)return;const we=$.clientWidth,Ae=$.clientHeight;let Ne,We;if(t.kind==="text"){const Nt=YS(t.aspectRatio)??{width:800,height:600};Ne=Nt.width,We=Nt.height}else{const Nt=X.current;if(!Nt||!Nt.naturalWidth)return;Ne=Nt.naturalWidth,We=Nt.naturalHeight}if(!we||!Ae)return;const Ie=Math.min(we/Ne,Ae/We),ht=Ne*Ie,xt=We*Ie;ae({x:(we-ht)/2,y:(Ae-xt)/2,width:ht,height:xt})},[t.kind,t.aspectRatio]);w.useEffect(()=>{const $=oe.current;if(!$)return;const we=new ResizeObserver(()=>ge());return we.observe($),()=>we.disconnect()},[ge]);const Re=w.useCallback($=>{const we=WS($.type,$.x,$.y),Ae=we.width,Ne=Math.max(.08,1-$.y);if(!$.text||!F||K.width<=0)return we;const We=$.type==="sfx"?N:S,Ie=Rn(Ae,K.width);let ht=$.type==="sfx"?.08:.12;for(let xt=0;xt<24;xt++){const Nt=Math.min(ht,Ne),Mt=Rn(Nt,K.height);if(!jo(re(We),$.text,Ie,Mt,To({...$},K.height||300,Ie,Mt)).overflow||Nt>=Ne)return{width:Ae,height:Nt};ht+=.03}return{width:Ae,height:Math.min(ht,Ne)}},[F,K,re,S,N]),Le=w.useCallback($=>{const we=Lp($,.1+Math.random()*.3,.1+Math.random()*.3),Ae={...we,...Re(we)};ne(Ne=>[...Ne,Ae]),U(Ae.id)},[Re]),Fe=w.useCallback($=>{const Ae={...Lp($.type,.1+Math.random()*.3,.1+Math.random()*.3),text:$.text,...$.type==="speech"&&$.speaker?{speaker:$.speaker}:{}},Ne={...Ae,...Re(Ae)};ne(We=>[...We,Ne]),U(Ne.id)},[Re]),ye=w.useCallback(($,we)=>{ne(Ae=>Ae.map(Ne=>Ne.id===$?{...Ne,...we}:Ne))},[]),st=w.useCallback($=>{var ht;const we=K.height||300,Ae=K.width>0?Rn($.width,K.width):200,Ne=K.height>0?Rn($.height,K.height):100,We=$.type==="sfx"?N:S,Ie=jo(re(We),$.text,Ae,Ne,To({...$,textStyle:void 0},we,Ae,Ne));ye($.id,{textStyle:{mode:"manual",fontScale:Ie.fontSize/Math.max(1,we),fontWeight:((ht=$.textStyle)==null?void 0:ht.fontWeight)??400,lineHeightFactor:Ie.fontSize>0?Ie.lineHeight/Ie.fontSize:1.2,speakerScale:Ie.fontSize>0&&Ie.speakerFontSize>0?Ie.speakerFontSize/Ie.fontSize:.8}})},[K,N,S,re,ye]),yt=w.useCallback($=>{ne(we=>we.filter(Ae=>Ae.id!==$)),U(null),P(!1)},[]),Ue=w.useCallback(()=>{U(null),P(!1)},[]),qe=w.useCallback(($,we)=>{$.stopPropagation(),U(we),P(!1)},[]),St=w.useCallback(($,we,Ae)=>{$.stopPropagation(),$.preventDefault();const Ne=D.find(We=>We.id===we);Ne&&(U(we),he.current={id:we,mode:Ae,startX:$.clientX,startY:$.clientY,origX:Ne.x,origY:Ne.y,origW:Ne.width,origH:Ne.height})},[D]);w.useEffect(()=>{const $=Ae=>{const Ne=he.current;if(!Ne||K.width===0)return;const We=dy(Ae.clientX-Ne.startX,K.width),Ie=dy(Ae.clientY-Ne.startY,K.height);if(Ne.mode==="move"){const ht=pu(Ne.origX+We,0,1-Ne.origW),xt=pu(Ne.origY+Ie,0,1-Ne.origH);ye(Ne.id,{x:ht,y:xt})}else{const ht=pu(Ne.origW+We,py,1-Ne.origX),xt=pu(Ne.origH+Ie,py,1-Ne.origY);ye(Ne.id,{width:ht,height:xt})}},we=()=>{he.current=null};return window.addEventListener("mousemove",$),window.addEventListener("mouseup",we),()=>{window.removeEventListener("mousemove",$),window.removeEventListener("mouseup",we)}},[K,ye]);const ze=w.useCallback(async()=>{var $;k(null);try{const we=cl(D),Ae=(($=t.aiDraft)==null?void 0:$.status)==="generated"&&we!==(t.aiDraft.baseSig??"")?{...t.aiDraft,status:"edited",updatedAt:new Date().toISOString()}:t.aiDraft??void 0;await s(D,Ae??null),f&&a()}catch(we){k(we instanceof Error?we.message:"Failed to save overlays")}},[D,s,a,f,t.aiDraft]),nt=w.useCallback(async()=>{if(O>0&&!H){const $=O;R(`${$} overlay${$===1?"":"s"} from the cut plan ${$===1?"has":"have"} no usable position and cannot be exported — re-place ${$===1?"it":"them"} or discard ${$===1?"it":"them"} first.`);return}xe(!0),R(null);try{await s(D);const{exportCut:$,ensureFontsReady:we}=await uy(async()=>{const{exportCut:li,ensureFontsReady:oi}=await import("./export-cut-DvUnFkvP.js");return{exportCut:li,ensureFontsReady:oi}},[]),Ae=D.some(li=>li.type==="sfx"),Ne=[b.family,...Ae?[v.family]:[]],{ready:We,missing:Ie}=await we(Ne);if(!We){R(`Fonts not loaded: ${Ie.join(", ")}. Check your connection and retry.`),xe(!1);return}if(t.cleanImagePath&&!B.url){R(B.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=B.url,xt=await $(ht,D,S,N,{narration:t.narration,dialogue:t.dialogue},t.kind==="text"?{background:t.background,aspectRatio:t.aspectRatio}:void 0),Nt=new FormData,Mt=xt.type==="image/webp"?"webp":"jpg";Nt.append("file",xt,`cut-${t.id}.${Mt}`);const Ut=await h(`/api/stories/${e}/cuts/${i}/export-final/${t.id}`,{method:"POST",body:Nt});if(Ut.ok)be(cl(D)),o==null||o();else{const li=await Ut.json();R(li.error||"Export failed")}}catch($){R($ instanceof Error?$.message:"Export failed")}finally{xe(!1)}},[t,B,D,e,i,b,v,S,N,h,s,o,O,H]),Ee=D.find($=>$.id===V),Wt=w.useMemo(()=>Z3(D),[D]),vi=w.useRef(t.id);w.useEffect(()=>{vi.current!==t.id&&(vi.current=t.id,be(cl(E.overlays)))},[t.id,E.overlays]);const Ct=CD({exported:!!t.finalImagePath||!!t.exportedAt,uploaded:!!t.uploadedUrl||!!t.uploadedCid,baselineSig:ue,current:D}),et=w.useMemo(()=>wD({...t,overlays:D},{staleExport:Ct}),[t,D,Ct]),ee=w.useMemo(()=>km(t),[t]),_e=w.useMemo(()=>{const $={};for(const we of D){const Ae=q3(we);let Ne=!1;if(F&&K.width>0&&we.text){const We=we.type==="sfx"?N:S,Ie=Rn(we.width,K.width),ht=Rn(we.height,K.height);Ne=jo(re(We),we.text,Ie,ht,To(we,K.height||300,Ie,ht)).overflow}(Ae||Ne)&&($[we.id]={outOfBounds:Ae,overflow:Ne})}return $},[D,F,K,re,S,N]),Me=Object.keys(_e).length,He=t.kind==="text",Ze=!t.cleanImagePath;return!He&&Ze&&D.length===0&&!t.narration&&!((Gt=t.dialogue)!=null&&Gt.length)?d.jsx("div",{className:"h-full flex items-center justify-center text-sm text-muted",children:"No clean image — upload one first, or add overlays for a narration cut."}):d.jsxs("div",{className:"h-full flex flex-col","data-testid":"focused-lettering-editor",children:[d.jsxs("div",{className:"px-4 py-3 border-b border-border bg-surface/40 flex items-center justify-between gap-3",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"text-[10px] font-bold uppercase tracking-[0.16em] text-accent",children:"Focused lettering editor"}),d.jsx("span",{className:"text-xs font-mono text-muted",children:p??`Cut #${t.id}`})]}),d.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"Place bubbles, captions, SFX, or between-scene card text, then save back to the full cut review."}),d.jsxs("span",{className:"text-[10px] text-muted","data-testid":"overlay-count",children:[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"})]}),j&&d.jsx("span",{className:"text-[10px] text-error",children:j}),Z&&d.jsx("span",{className:"text-[10px] text-error",children:Z}),d.jsx("button",{onClick:nt,disabled:q,className:"px-3 py-1 text-xs border border-accent text-accent rounded hover:bg-accent/5 disabled:opacity-50","data-testid":"export-btn",children:q?"Exporting...":"Export"}),d.jsx("button",{onClick:()=>{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"})]})]}),O>0&&!H?d.jsxs("div",{className:"px-3 py-1 border-b border-border bg-error/10 text-[10px] text-error flex items-center gap-2 flex-wrap","data-testid":"overlay-repair-note",children:[d.jsxs("span",{children:[O," overlay",O===1?"":"s"," ","from the cut plan ",O===1?"has":"have"," no usable position and cannot be exported. Re-place"," ",O===1?"it":"them",", or"]}),d.jsxs("button",{onClick:()=>A(!0),"data-testid":"discard-invalid-overlays",className:"px-1.5 py-0.5 border border-error/40 rounded hover:bg-error/10",children:["discard ",O," unplaceable overlay",O===1?"":"s"]})]}):O>0?d.jsxs("div",{className:"px-3 py-1 border-b border-border bg-amber-500/10 text-[10px] text-amber-700","data-testid":"overlay-repair-note",children:["Discarded ",O," unplaceable overlay",O===1?"":"s"," — the export will not include"," ",O===1?"it":"them","."]}):W?d.jsx("div",{className:"px-3 py-1 border-b border-border bg-amber-500/10 text-[10px] text-amber-700","data-testid":"overlay-repair-note",children:"Auto-placed overlays from the cut plan — review their positions before exporting."}):null,Wt.length>0&&d.jsxs("div",{className:"px-3 py-1 border-b border-border bg-amber-500/10 text-[10px] text-amber-700","data-testid":"overlay-overlap-warning",children:["Cut #",t.id,": ",Wt.length," bubble"," ",Wt.length===1?"pair overlaps":"pairs overlap"," and may be hard to read —"," ",Wt.map($=>`#${$.indexA+1} ${Lf(D[$.indexA])} ↔ #${$.indexB+1} ${Lf(D[$.indexB])}`).join("; "),". Move them apart, or export as-is if the overlap is intended."]}),d.jsx("div",{className:"px-3 py-1 border-b border-border flex items-center gap-3 flex-wrap text-[10px] text-muted","data-testid":"lettering-checklist",children:[["clean-image","Clean image",et.hasCleanImage],["script-text","Script text",et.hasScriptText],["bubbles",`Bubbles placed${et.bubblesPlaced?` (${et.bubblesPlaced})`:""}`,et.bubblesPlaced>0],["exported","Final exported",et.exported],["uploaded","Uploaded",et.uploaded]].map(([$,we,Ae])=>d.jsxs("span",{"data-testid":`lettering-check-${$}`,"data-done":Ae?"true":"false",className:`flex items-center gap-1 ${Ae?"text-green-700":"text-muted/70"}`,children:[d.jsx("span",{"aria-hidden":!0,children:Ae?"✓":"○"}),we]},$))}),Ct&&d.jsx("div",{className:"px-3 py-1 border-b border-border bg-amber-500/10 text-[10px] text-amber-700","data-testid":"lettering-stale-export-warning",children:"Bubbles changed since the last export — re-export this cut and upload the new final image before publishing."}),Me>0&&d.jsxs("div",{className:"px-3 py-1 border-b border-border bg-amber-500/10 text-[10px] text-amber-700","data-testid":"lettering-export-warning",children:[Me," bubble",Me===1?"":"s"," may not export cleanly:"," ",Object.entries(_e).map(([$,we])=>{const Ae=D.findIndex(We=>We.id===$),Ne=[we.outOfBounds?"outside image":null,we.overflow?"text overflow":null].filter(Boolean).join(", ");return`#${Ae+1} ${Lf(D[Ae])} (${Ne})`}).join("; "),". Resize or reposition before exporting."]}),d.jsxs("div",{className:"flex-1 min-h-0 flex",children:[d.jsxs("div",{ref:oe,className:"flex-1 min-w-0 relative overflow-hidden bg-[#f8f5ef]",onClick:Ue,"data-testid":"editor-surface",children:[t.cleanImagePath&&B.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&&!B.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:X,src:B.url,alt:`Cut ${t.id} clean`,className:"w-full h-full object-contain",draggable:!1,onLoad:ge}):He?K.width>0&&d.jsx("div",{className:"absolute flex items-center justify-center text-muted text-xs",style:{left:K.x,top:K.y,width:K.width,height:K.height,background:t.background||"#ffffff"},"data-testid":"text-panel-canvas",children:"Text panel"}):d.jsx("div",{className:"w-full h-full bg-white flex items-center justify-center text-muted text-xs",ref:$=>{if($&&K.width===0){const we=$.getBoundingClientRect();we.width>0&&ae({x:0,y:0,width:we.width,height:we.height})}},children:"Narration cut"}),K.width>0&&d.jsx("svg",{className:"absolute inset-0 w-full h-full pointer-events-none","data-testid":"balloon-layer",children:D.map($=>{if($.type!=="speech")return null;const we=K.x+Rn($.x,K.width),Ae=K.y+Rn($.y,K.height),Ne=Rn($.width,K.width),We=Rn($.height,K.height),Ie=$S($,Ne,We),ht=$.tailAnchor?ym(we,Ae,Ne,We,$.tailAnchor,Ie):null,xt=Math.max(1.5,K.height*.004),Nt=$.id===V;return d.jsx("path",{"data-testid":`balloon-${$.id}`,d:qS(we,Ae,Ne,We,ht,Ie),className:`fill-white/95 ${Nt?"stroke-accent":"stroke-[#1a1a1a]"}`,strokeWidth:Nt?xt+.5:xt,strokeLinejoin:"round"},$.id)})}),K.width>0&&D.map($=>{const we=K.x+Rn($.x,K.width),Ae=K.y+Rn($.y,K.height),Ne=Rn($.width,K.width),We=Rn($.height,K.height),Ie=$.id===V,ht=$.type==="speech",xt=$.type==="narration",Nt=!!_e[$.id];return d.jsxs("div",{"data-testid":`overlay-${$.id}`,"data-warning":Nt?"true":"false",onClick:Mt=>qe(Mt,$.id),onMouseDown:Mt=>St(Mt,$.id,"move"),className:`absolute rounded cursor-move select-none ${ht?"":`border-2 ${ED[$.type]}`} ${xt?"bg-[#f4efe6]/85 rounded-md":""} ${Ie&&!ht?"ring-2 ring-accent":""} ${Nt?"ring-2 ring-amber-500":""}`,style:{left:we,top:Ae,width:Ne,height:We},children:[(()=>{var oi,ii;const Mt=$.type==="sfx"?N:S;if(!$.text)return d.jsx("span",{className:"text-[9px] px-1 text-muted truncate block pointer-events-none",style:{fontFamily:Mt},children:ku[$.type]});const Ut=$.type!=="sfx"&&!!$.speaker;if(!F)return d.jsx("div",{className:"absolute inset-0 flex items-center justify-center px-1 overflow-hidden pointer-events-none text-center break-words",style:{fontFamily:Mt,fontSize:Math.max(9,Math.min(We*.05,16)),fontWeight:((oi=$.textStyle)==null?void 0:oi.fontWeight)??400},"data-testid":`overlay-text-${$.id}`,"data-fonts-ready":"false",children:Ut?`${$.speaker}: ${$.text}`:$.text});const li=jo(re(Mt),$.text,Ne,We,To($,K.height,Ne,We));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:Mt},"data-testid":`overlay-text-${$.id}`,"data-fonts-ready":"true",children:[Ut&&d.jsx("span",{className:"font-bold text-[#3a3a3a] block",style:{fontSize:li.speakerFontSize,lineHeight:1.2},children:$.speaker}),d.jsx("span",{className:"text-[#1a1a1a]",style:{fontSize:li.fontSize,lineHeight:`${li.lineHeight}px`,fontWeight:((ii=$.textStyle)==null?void 0:ii.fontWeight)??400},children:li.lines.map((Sn,Vn)=>d.jsx("span",{className:"block",children:Sn},Vn))})]})})(),Ie&&d.jsx("div",{onMouseDown:Mt=>{Mt.stopPropagation(),St(Mt,$.id,"resize")},className:"absolute bottom-0 right-0 w-2 h-2 bg-accent cursor-se-resize","data-testid":`resize-${$.id}`})]},$.id)})]}),d.jsxs("div",{className:"w-64 border-l border-border p-3 overflow-y-auto flex-shrink-0",children:[((mi=t.aiDraft)==null?void 0:mi.status)==="generated"&&d.jsxs("div",{className:"mb-3 rounded border border-accent/30 bg-accent/5 p-2 space-y-1","data-testid":"ai-draft-current-target",children:[d.jsx("p",{className:"text-[10px] font-bold uppercase tracking-[0.14em] text-accent",children:"AI draft ready"}),d.jsx("p",{className:"text-[11px] text-muted",children:"These first-pass overlays came from the cut script. Review and tune them here before exporting the final panel."})]}),ee.length>0&&d.jsxs("div",{className:"mb-3 space-y-1.5","data-testid":"script-insert-panel",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"From script"}),d.jsx("div",{className:"flex flex-col gap-1",children:ee.map($=>d.jsxs("button",{onClick:()=>Fe($),"data-testid":`script-insert-${$.key}`,title:`Add ${$.type} overlay with this text`,className:"text-left px-2 py-1 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5",children:[d.jsxs("span",{className:"font-medium text-accent",children:["+ ",ku[$.type]]})," ",d.jsxs("span",{className:"text-muted",children:[$.speaker?`${$.speaker}: `:"",$.text.length>32?`${$.text.slice(0,32)}…`:$.text]})]},$.key))})]}),Ee?d.jsxs("div",{className:"space-y-3",children:[d.jsx("p",{className:"text-xs font-medium text-foreground",children:ku[Ee.type]}),Ee.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:Ee.speaker||"",onChange:$=>ye(Ee.id,{speaker:$.target.value}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none",placeholder:"Character name","data-testid":"inspector-speaker"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Text"}),d.jsx("textarea",{value:Ee.text,onChange:$=>ye(Ee.id,{text:$.target.value}),rows:3,className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent resize-none focus:border-accent focus:outline-none",placeholder:"Overlay text","data-testid":"inspector-text"})]}),d.jsx("button",{onClick:()=>ye(Ee.id,Re(Ee)),"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"}),((At=Ee.textStyle)==null?void 0:At.mode)==="manual"?d.jsx("button",{type:"button",onClick:()=>ye(Ee.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:()=>st(Ee),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"})]}),((wt=Ee.textStyle)==null?void 0:wt.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:((Ee.textStyle.fontScale??.032)*100).toFixed(1),onChange:$=>ye(Ee.id,{textStyle:{...Ee.textStyle,mode:"manual",fontScale:Math.max(.015,Math.min(.12,(parseFloat($.target.value)||3.2)/100))}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-font-scale"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Weight"}),d.jsxs("select",{value:String(Ee.textStyle.fontWeight??400),onChange:$=>ye(Ee.id,{textStyle:{...Ee.textStyle,mode:"manual",fontWeight:$.target.value==="700"?700:400}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-font-weight",children:[d.jsx("option",{value:"400",children:"Regular"}),d.jsx("option",{value:"700",children:"Bold"})]})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Line height"}),d.jsx("input",{type:"number",step:"0.05",min:"0.9",max:"2",value:(Ee.textStyle.lineHeightFactor??1.2).toFixed(2),onChange:$=>ye(Ee.id,{textStyle:{...Ee.textStyle,mode:"manual",lineHeightFactor:Math.max(.9,Math.min(2,parseFloat($.target.value)||1.2))}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-line-height"})]}),Ee.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:(Ee.textStyle.speakerScale??.8).toFixed(2),onChange:$=>ye(Ee.id,{textStyle:{...Ee.textStyle,mode:"manual",speakerScale:Math.max(.5,Math.min(1.5,parseFloat($.target.value)||.8))}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-speaker-scale"})]})]}):d.jsx("p",{className:"text-[10px] text-muted",children:"Auto-fit stays on by default and resizes text to the box."})]}),Ee.type==="speech"&&(()=>{const $=Ee.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:ND.map(we=>d.jsx("button",{type:"button",onClick:()=>ye(Ee.id,{tailAnchor:we.anchor}),className:"px-1.5 py-0.5 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5","data-testid":`inspector-tail-${we.key}`,children:we.label},we.key))}),d.jsxs("div",{className:"flex gap-2",children:[d.jsxs("label",{className:"flex items-center gap-1 text-[10px] font-mono text-muted",children:["x",d.jsx("input",{type:"number",step:"0.1",value:$.x,onChange:we=>ye(Ee.id,{tailAnchor:{...$,x:parseFloat(we.target.value)||0}}),className:"w-14 px-1 py-0.5 text-[10px] border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-tail-x"})]}),d.jsxs("label",{className:"flex items-center gap-1 text-[10px] font-mono text-muted",children:["y",d.jsx("input",{type:"number",step:"0.1",value:$.y,onChange:we=>ye(Ee.id,{tailAnchor:{...$,y:parseFloat(we.target.value)||0}}),className:"w-14 px-1 py-0.5 text-[10px] border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-tail-y"})]})]})]})})(),Ee.type!=="sfx"&&d.jsxs("div",{className:"space-y-1.5 rounded border border-border/70 p-2","data-testid":"inspector-bubble-style",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Bubble controls"}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Padding X (% width)"}),d.jsx("input",{type:"number",step:"1",min:"0",max:"25",value:((((Yt=Ee.bubbleStyle)==null?void 0:Yt.paddingX)??.06)*100).toFixed(0),onChange:$=>ye(Ee.id,{bubbleStyle:{...Ee.bubbleStyle,paddingX:Math.max(0,Math.min(.25,(parseFloat($.target.value)||6)/100))}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-padding-x"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Padding Y (% height)"}),d.jsx("input",{type:"number",step:"1",min:"0",max:"25",value:((((ot=Ee.bubbleStyle)==null?void 0:ot.paddingY)??.08)*100).toFixed(0),onChange:$=>ye(Ee.id,{bubbleStyle:{...Ee.bubbleStyle,paddingY:Math.max(0,Math.min(.25,(parseFloat($.target.value)||8)/100))}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-padding-y"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Corner roundness (% short side)"}),d.jsx("input",{type:"number",step:"1",min:"0",max:"49",value:((((Ht=Ee.bubbleStyle)==null?void 0:Ht.cornerRadius)??.4)*100).toFixed(0),onChange:$=>ye(Ee.id,{bubbleStyle:{...Ee.bubbleStyle,cornerRadius:Math.max(0,Math.min(.49,(parseFloat($.target.value)||40)/100))}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-corner-radius"})]})]}),d.jsxs("div",{className:"text-[10px] text-muted","data-testid":"inspector-font",children:["Font:"," ",Ee.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: ",Ee.x.toFixed(3),", y:"," ",Ee.y.toFixed(3)]}),d.jsxs("p",{children:["w: ",Ee.width.toFixed(3),", h:"," ",Ee.height.toFixed(3)]})]}),d.jsx("button",{onClick:()=>{T?yt(Ee.id):P(!0)},className:"w-full px-2 py-1 text-xs text-error border border-error/30 rounded hover:bg-error/5","data-testid":"delete-overlay",children:T?"Click again to delete":"Delete"})]}):d.jsx("p",{className:"text-xs text-muted","data-testid":"inspector-empty",children:"Select an overlay to inspect."})]})]})]})}function my(e){const t=`gfont-${e.googleFontsId}`;if(document.getElementById(t))return;const i=document.createElement("link");i.id=t,i.rel="stylesheet",i.href=e1(e),document.head.appendChild(i)}function TD({storyName:e,assetPath:t,authFetch:i,alt:s,overlays:a,language:o="English",background:c,aspectRatio:h,className:p,onClick:f,testId:_}){const x=QS(o),b=JS(),v=Ou(x),S=Ou(b),N=bm(e,t,i),B=w.useRef(null),E=w.useMemo(()=>typeof document<"u"?document.createElement("canvas").getContext("2d"):null,[]),[O,H]=w.useState(!1),[A,W]=w.useState(()=>YS(h)??{width:800,height:600}),[D,ne]=w.useState({width:0,height:0});w.useEffect(()=>{my(x),my(b)},[x,b]),w.useEffect(()=>{let L=!1;return(async()=>{var re;try{(re=document.fonts)!=null&&re.load&&await Promise.all([document.fonts.load(`16px "${x.family}"`),document.fonts.load(`16px "${b.family}"`)])}catch{}L||H(!0)})(),()=>{L=!0}},[x.family,b.family]),w.useEffect(()=>{const L=B.current;if(!L)return;const re=new ResizeObserver(()=>{ne({width:L.clientWidth,height:L.clientHeight})});return re.observe(L),()=>re.disconnect()},[]);const ue=w.useCallback(L=>(re,F,Y=400)=>E?(E.font=`${Y} ${F}px ${L}`,E.measureText(re).width):re.length*F*.5,[E]),be=d.jsx("div",{className:p??"w-full rounded border border-border bg-white","data-testid":_,ref:B,style:{aspectRatio:`${A.width} / ${A.height}`,maxHeight:"32rem"},children:d.jsxs("div",{className:"relative w-full h-full overflow-hidden rounded border border-border bg-white",children:[t?N.error||!N.loading&&!N.url?d.jsx("div",{className:"w-full h-full flex items-center justify-center text-[10px] text-muted bg-surface/40",children:"Image not available"}):N.url?d.jsx("img",{src:N.url,alt:s,className:"absolute inset-0 w-full h-full object-contain",draggable:!1,onLoad:L=>{const re=L.currentTarget.naturalWidth||A.width,F=L.currentTarget.naturalHeight||A.height;re>0&&F>0&&W({width:re,height:F})}}):d.jsx("div",{className:"w-full h-full flex items-center justify-center text-[10px] text-muted bg-surface/40",children:"Loading image…"}):d.jsx("div",{className:"absolute inset-0",style:{background:c||"#101820"}}),D.width>0&&D.height>0&&a.length>0&&d.jsxs(d.Fragment,{children:[d.jsx("svg",{className:"absolute inset-0 w-full h-full pointer-events-none","data-testid":_?`${_}-overlay-layer`:void 0,children:a.map(L=>{if(L.type!=="speech")return null;const re=L.x*D.width,F=L.y*D.height,Y=L.width*D.width,V=L.height*D.height,U=$S(L,Y,V),T=L.tailAnchor?ym(re,F,Y,V,L.tailAnchor,U):null,P=Math.max(1.25,D.height*.004);return d.jsx("path",{"data-testid":_?`${_}-overlay-${L.id}`:void 0,d:qS(re,F,Y,V,T,U),className:"fill-white/95 stroke-[#1a1a1a]",strokeWidth:P,strokeLinejoin:"round"},L.id)})}),a.map(L=>{var q;const re=L.x*D.width,F=L.y*D.height,Y=L.width*D.width,V=L.height*D.height,U=L.type==="sfx"?S:v,T=L.type==="speech";L.type;const P=L.type!=="sfx"&&!!L.speaker;return d.jsx("div",{className:`absolute rounded overflow-hidden ${T?"":"border-2"} ${L.type==="narration"?"border-muted/40 bg-[#f4efe6]/85 rounded-md":L.type==="sfx"?"border-accent/40":""}`,style:{left:re,top:F,width:Y,height:V},children:L.text?O?(()=>{var j;const xe=jo(ue(U),L.text,Y,V,To(L,D.height,Y,V));return d.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center px-1 text-center",style:{fontFamily:U},children:[P&&d.jsx("span",{className:"block font-bold text-[#3a3a3a]",style:{fontSize:xe.speakerFontSize,lineHeight:1.2},children:L.speaker}),d.jsx("span",{className:"text-[#1a1a1a]",style:{fontSize:xe.fontSize,lineHeight:`${xe.lineHeight}px`,fontWeight:((j=L.textStyle)==null?void 0:j.fontWeight)??400},children:xe.lines.map((R,Z)=>d.jsx("span",{className:"block",children:R},Z))})]})})():d.jsx("div",{className:"absolute inset-0 flex items-center justify-center px-1 text-center break-words",style:{fontFamily:U,fontSize:Math.max(8,Math.min(V*.05,14)),fontWeight:((q=L.textStyle)==null?void 0:q.fontWeight)??400},children:P?`${L.speaker}: ${L.text}`:L.text}):d.jsx("span",{className:"block truncate px-1 text-[9px] text-muted",style:{fontFamily:U},children:L.type})},L.id)})]})]})});return f?d.jsx("button",{type:"button",onClick:f,className:"block w-full text-left","data-testid":_?`${_}-open`:void 0,children:be}):be}const AD={wide:"Wide",medium:"Medium","close-up":"Close-up","extreme-close-up":"Extreme close-up"},RD="No speech bubbles, captions, sound effects, narration, or any text or lettering in the image.",DD="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 MD(e){var a;const t=AD[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(DD),s.push(RD),s.join(` +`).trim()}function BD(e,t){return`assets/${e}/cut-${String(t).padStart(2,"0")}-clean.webp`}function gy(e,t){const i=BD(t,e.id);return[`Generate the clean image for cut ${e.id}.`,"","Image description:",MD(e),"","How to hand it off:","- Produce the actual image — do not just describe it or return a prompt.",`- If your image tool can write a WebP or JPEG under 1MB, save it at ${i} and run "Sync clean images".`,'- If it only produces a PNG (e.g. built-in image generation saves to ~/.codex/generated_images), that is fine — do NOT convert or rename it yourself. Leave it there and import it into this cut with the OWS "Import from Codex" button, which converts the PNG automatically.',"- Clean image only: no text, speech bubbles, captions, sound effects, signage, watermark, or signature.","- Hold the style lock above — an illustrated comic/webtoon panel, NOT a photoreal photo, painterly concept art, or 3D render. If a result reads photorealistic, regenerate it as illustrated panel art.","- Do not letter or upload anything — final lettering and upload happen later in OWS."].join(` +`)}const t1=12e3,LD=5,OD=6e4,zD=6e4,PD=5;function ID(e,t){return e===429?!0:!!t&&/rate[\s-]?limit/i.test(t)}function HD(e,t=t1){return Math.min(t*2**e,OD)}const i1=e=>new Promise(t=>setTimeout(t,e));async function UD(e,t={}){var c;const i=t.sleep??i1,s=t.maxRetries??LD,a=t.baseDelayMs??t1;let o=0;for(;;){const h=await e();if(h.ok||!ID(h.status,h.errorMessage)||o>=s)return h;const p=HD(o,a);o+=1,(c=t.onWaiting)==null||c.call(t,{attempt:o,maxRetries:s,waitMs:p}),await i(p)}}function $D(e={}){const t=e.limit??PD,i=e.windowMs??zD,s=e.sleep??i1,a=e.now??(()=>Date.now()),o=[],c=()=>{const h=a()-i;for(;o.length&&o[0]<=h;)o.shift()};return async function(){var p;if(c(),o.length>=t){const f=o[0]+i-a();f>0&&((p=e.onWaiting)==null||p.call(e,{waitMs:f}),await s(f)),c()}o.push(a())}}const zp=1024*1024;function xy(e,t,i){return new Promise((s,a)=>{e.toBlob(o=>o?s(o):a(new Error(`Failed to export as ${t}`)),t,i)})}async function FD(e){const t=[.9,.8,.7,.6];for(const s of t)try{const a=await xy(e,"image/webp",s);if(a.type!=="image/webp")break;if(a.size<=zp)return a}catch{break}const i=[.85,.7,.5];for(const s of i){const a=await xy(e,"image/jpeg",s);if(a.size<=zp)return a}throw new Error("Cannot compress image under 1MB — reduce overlay count or image size")}const qD=["image/webp","image/jpeg"];function n1(e){return qD.includes(e.type)&&e.size<=zp}async function WD(e){var i;if(typeof createImageBitmap!="function")throw new Error("This browser cannot decode the image for import");let t;try{t=await createImageBitmap(e)}catch{throw new Error("Could not read the selected image — pick a PNG, WebP, or JPEG file")}try{const s=document.createElement("canvas");s.width=t.width,s.height=t.height;const a=s.getContext("2d");if(!a)throw new Error("Could not process the image for import");return a.drawImage(t,0,0),s}finally{(i=t.close)==null||i.call(t)}}async function Ku(e){if(n1(e))return e;const t=await WD(e);return FD(t)}function GD(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 YD(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(GD):[]}async function VD(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 KD(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 XD(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:e>=1024?`${Math.round(e/1024)} KB`:`${e} B`}function ZD(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 QD({image:e,authFetch:t}){const i=KD(`/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 JD({authFetch:e,cutId:t,onImport:i,onClose:s}){const[a,o]=w.useState(null),[c,h]=w.useState(null),[p,f]=w.useState(null),[_,x]=w.useState("");w.useEffect(()=>{let E=!1;return(async()=>{const O=await YD(e);E||o(O)})(),()=>{E=!0}},[e]);const b=_.trim().toLowerCase(),v=w.useMemo(()=>a?b?a.filter(E=>E.name.toLowerCase().includes(b)):a:[],[a,b]),S=Date.now(),N=async E=>{h(null),f(E.token);try{const O=await VD(e,E);await i(O)}catch(O){h(O instanceof Error?O.message:"Could not import the generated image")}finally{f(null)}},B=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"})]}),B&&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."}),B&&v.length===0&&d.jsxs("p",{className:"text-[11px] text-muted","data-testid":`codex-picker-no-match-${t}`,children:["No generated images match “",_.trim(),"”."]}),B&&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(QD,{image:E,authFetch:e}),d.jsxs("div",{className:"min-w-0 flex-1",children:[d.jsxs("p",{className:"text-[11px] text-foreground",children:[ZD(E.mtimeMs,S)," · ",XD(E.size)]}),d.jsx("p",{className:"truncate text-[10px] font-mono text-muted",title:E.name,children:E.name})]}),d.jsx("button",{onClick:()=>N(E),disabled:p!==null,"data-testid":`codex-import-${E.token}`,className:"px-2 py-1 text-[11px] border border-accent/30 text-accent rounded hover:bg-accent/5 disabled:opacity-50",children:p===E.token?"Importing…":"Import to this cut"})]},E.token))}),c&&d.jsx("p",{className:"text-[11px] text-error",children:c})]})}const eM={done:"✓",current:"▸",todo:"○"};function tM({checklist:e,issues:t,onFinish:i,finishing:s,progressText:a,canFinish:o,markdownReady:c=!1,published:h=!1}){var E;if(!e||e.steps.length===0)return null;const p=ZS(t),f=((E=e.steps.find(O=>O.key==="upload"))==null?void 0:E.status)==="done",_=f&&c&&!h,x=h||c?"done":f?"current":"todo",b=h?"done":_?"current":"todo",v=[...e.steps.filter(O=>O.key!=="publish"),{key:"assemble",label:"Episode sequence prepared",status:x,detail:null},{key:"ready",label:h?"Published to PlotLink":"Ready to publish",status:b,detail:null}],S=s?a||"Finishing…":h?"Published ✓":_?"Episode ready to publish":"Finish episode",N=v.filter(O=>O.status!=="done").length,B=p.reduce((O,H)=>O+H.lines.length,0);return d.jsxs("div",{className:"px-3 py-1.5 border-b border-border bg-surface/50 flex-shrink-0","data-testid":"finish-episode-panel",children:[d.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Finish episode"}),e.nextStep&&d.jsxs("span",{className:"min-w-0 flex-1 text-[10px] text-muted truncate","data-testid":"finish-next-step",children:["Next: ",e.nextStep]}),d.jsx("button",{onClick:i,disabled:s||!o,"data-testid":"finish-episode-btn",title:"Upload the exported final panels, then prepare the episode for publishing — picks up where it left off",className:"px-2.5 py-0.5 text-[11px] border border-accent/40 text-accent rounded hover:bg-accent/5 disabled:opacity-50",children:S})]}),d.jsxs("details",{className:"mt-1","data-testid":"finish-episode-details",children:[d.jsxs("summary",{className:"cursor-pointer select-none text-[10px] text-muted hover:text-foreground",children:[N===0?"Progress details":`${N} step${N===1?"":"s"} left`,B>0?` · ${B} blocker${B===1?"":"s"}`:""]}),d.jsxs("div",{className:"mt-1.5 space-y-1.5",children:[d.jsx("ol",{className:"flex flex-wrap gap-1.5",children:v.map(O=>d.jsxs("li",{"data-testid":`finish-step-${O.key}`,"data-status":O.status,className:`flex items-center gap-1 rounded border px-1.5 py-0.5 text-[10px] ${O.status==="current"?"border-accent/40 bg-accent/10 text-accent":O.status==="done"?"border-border bg-background/70 text-foreground":"border-border/70 bg-background/40 text-muted"}`,children:[d.jsx("span",{"aria-hidden":!0,children:eM[O.status]}),d.jsx("span",{children:O.label}),O.detail&&d.jsxs("span",{className:"text-muted",children:["· ",O.detail]})]},O.key))}),p.length>0&&d.jsx("div",{className:"space-y-1.5","data-testid":"finish-issues",children:p.map(O=>d.jsxs("div",{"data-testid":`finish-issue-group-${O.key}`,className:"text-[10px]",children:[d.jsx("p",{className:"font-medium text-amber-700",children:O.title}),d.jsx("ul",{className:"ml-3 list-disc text-muted",children:O.lines.map((H,A)=>d.jsx("li",{children:H},A))})]},O.key))})]})]})]})}function r1(e){return{planned:e.filter(t=>t.state==="planned").length,needsConversion:e.filter(t=>t.state==="needs-conversion").length,missing:e.filter(t=>t.state==="missing").length,cleanReady:e.filter(t=>t.state==="clean-ready").length,finalReady:e.filter(t=>t.state==="final-ready").length,uploaded:e.filter(t=>t.state==="uploaded").length}}function Bo(e){return(!!e.cleanImagePath||_n(e))&&km(e).length>0}function _y(e){const t=new Date().toISOString();return{status:"generated",baseSig:cl(e),generatedAt:t,updatedAt:t}}function s1(e){return e.uploadedCid?"uploaded":e.finalImagePath||e.exportedAt?"lettered":e.cleanImagePath?"clean":_n(e)?"text":"missing"}const by={muted:"text-muted",amber:"text-amber-700",green:"text-green-700",accent:"text-accent"},iM={muted:"bg-muted/40",amber:"bg-amber-500",green:"bg-green-600",accent:"bg-accent"};function nM(e,t,i){var s;return e.uploadedCid||e.uploadedUrl?{key:"uploaded",label:"Uploaded",tone:"green"}:t?{key:"convert",label:"Needs conversion",tone:"amber"}:i?e.finalImagePath?{key:"review",label:"Needs review",tone:"amber"}:{key:"needs-image",label:"Needs image",tone:"muted"}:e.finalImagePath?{key:"exported",label:"Exported",tone:"green"}:_n(e)?{key:"text",label:"Ready for captions",tone:"accent"}:e.cleanImagePath?(((s=e.overlays)==null?void 0:s.length)??0)>0?{key:"review",label:"Needs review",tone:"amber"}:{key:"letter",label:"Ready for lettering",tone:"green"}:{key:"needs-image",label:"Needs image",tone:"muted"}}function rM(e){var t,i;return e.uploadedCid||e.uploadedUrl?{label:"Complete",detail:"Final image uploaded",tone:"green"}:e.finalImagePath||e.exportedAt?{label:"Exported",detail:"Ready to upload",tone:"green"}:(((t=e.overlays)==null?void 0:t.length)??0)>0?((i=e.aiDraft)==null?void 0:i.status)==="generated"?{label:"Draft ready",detail:`${e.overlays.length} AI-drafted overlay${e.overlays.length===1?"":"s"} ready to review`,tone:"amber"}:{label:"User-edited",detail:`${e.overlays.length} overlay${e.overlays.length===1?"":"s"} adjusted and ready to review`,tone:"amber"}:Bo(e)?{label:"No draft",detail:"Draft with AI or place bubbles manually",tone:"muted"}:_n(e)?{label:"Between-scene card",detail:"Open to add narration or title text",tone:"accent"}:e.cleanImagePath?{label:"Unlettered",detail:"Clean art ready for bubble placement",tone:"muted"}:{label:"Needs artwork",detail:"Add or sync clean art first",tone:"muted"}}function sM({cut:e,storyName:t,plotFile:i,language:s,expanded:a,onToggle:o,authFetch:c,onUpdated:h,onOpenEditor:p,detectedLocalClean:f,onSyncClean:_,syncing:x,onAiDraft:b,aiDrafting:v,staleMessages:S,onRepairStale:N,repairing:B,conversionPng:E,onConvert:O,converting:H,rowRef:A,featured:W=!1}){var st,yt;const D=w.useRef(null),[ne,ue]=w.useState(!1),[be,L]=w.useState(null),[re,F]=w.useState(!1),[Y,V]=w.useState(!1),[U,T]=w.useState(!1),[P,q]=w.useState(!1),xe=s1(e),j=S.length>0,R=!!E,Z=w.useCallback(async()=>{E&&(q(!0),await O(e.id,E),q(!1),h())},[E,O,e.id,h]),k=w.useCallback(async Ue=>{ue(!0),L(null);try{let qe=Ue;if(!n1(Ue))try{qe=await Ku(Ue)}catch(Ee){return L(Ee instanceof Error?Ee.message:"Could not import image"),!1}const St=qe.type==="image/jpeg"?"jpg":"webp",ze=new FormData;ze.append("file",new File([qe],`clean.${St}`,{type:qe.type}));const nt=await c(`/api/stories/${t}/cuts/${i}/upload-clean/${e.id}`,{method:"POST",body:ze});if(!nt.ok){const Ee=await nt.json();return L(Ee.error||"Upload failed"),!1}return h(),!0}catch{return L("Upload failed"),!1}finally{ue(!1)}},[c,t,i,e.id,h]),K=nM(e,R,j),ae=e.cleanImagePath??E??null,oe=((st=e.overlays)==null?void 0:st.length)??0,X=!_n(e)&&!!e.cleanImagePath&&!e.finalImagePath&&!e.uploadedCid&&!e.uploadedUrl&&!j&&!R,he=!j&&!R&&!e.finalImagePath&&!e.uploadedCid&&!e.uploadedUrl&&Bo(e),ge=(((yt=e.overlays)==null?void 0:yt.length)??0)>0?"Re-draft with AI":"AI draft lettering",Re=K.key==="convert"?{label:P?"Converting…":"Convert image",onClick:Z,testid:`card-convert-${e.id}`}:K.key==="review"?{label:"Review cut",onClick:p,testid:`card-review-${e.id}`}:K.key==="text"?{label:"Add captions",onClick:p,testid:`card-letter-${e.id}`}:K.key==="needs-image"?{label:"Add artwork",onClick:o,testid:`card-addart-${e.id}`}:null,Le=rM(e),Fe=!!e.cleanImagePath||!!e.narration||e.dialogue.length>0||_n(e),ye=W?"w-full rounded border border-border bg-white min-h-[14rem] md:min-h-[18rem] xl:min-h-[21rem]":"w-full rounded border border-border bg-white min-h-[11rem] md:min-h-[13rem]";return d.jsxs("div",{ref:A,"data-cut-row":e.id,className:`border rounded ${a?"border-accent/30":"border-border"}`,children:[d.jsxs("div",{className:"px-3 py-2 space-y-2","data-testid":`cut-card-${e.id}`,children:[d.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[d.jsx("span",{className:`w-2 h-2 rounded-full flex-shrink-0 ${iM[K.tone]}`}),d.jsxs("span",{className:"font-medium text-xs text-foreground",children:["Cut ",String(e.id).padStart(2,"0")]}),d.jsxs("span",{className:"font-mono text-[10px] text-muted",children:["· ",e.shotType]}),d.jsx("span",{className:`ml-auto text-[10px] font-medium flex-shrink-0 ${by[K.tone]}`,"data-testid":`cut-card-status-${e.id}`,children:K.label})]}),ae||_n(e)?d.jsx(TD,{storyName:t,assetPath:ae,authFetch:c,alt:`Cut ${e.id} artwork`,overlays:e.overlays,language:s,background:e.background,aspectRatio:e.aspectRatio,onClick:Fe?p:void 0,className:ye,testId:`cut-preview-${e.id}`}):d.jsx("div",{className:`${W?"min-h-[14rem] md:min-h-[18rem] xl:min-h-[21rem]":"min-h-28 md:min-h-40"} w-full 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:_n(e)?"Text panel — no artwork needed":"No artwork yet"}),d.jsxs("div",{className:`rounded border border-border/70 bg-surface/50 px-2 py-1.5 text-[11px] ${by[Le.tone]}`,"data-testid":`lettering-review-state-${e.id}`,children:[d.jsx("span",{className:"font-semibold",children:Le.label}),d.jsxs("span",{className:"text-muted",children:[" · ",Le.detail]})]}),d.jsx("button",{onClick:o,"data-testid":`cut-desc-${e.id}`,className:"block w-full text-left text-[11px] text-muted hover:text-foreground",children:e.description||"No description"}),d.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[X?d.jsxs(d.Fragment,{children:[d.jsx("button",{onClick:p,"data-testid":`add-bubbles-${e.id}`,className:"px-2.5 py-1 text-[11px] font-medium rounded bg-accent text-white hover:bg-accent-dim",children:oe>0?"Review lettering":"Open focused editor"}),he&&d.jsx("button",{onClick:b,disabled:v,"data-testid":`ai-draft-${e.id}`,className:"px-2.5 py-1 text-[11px] rounded border border-accent/40 text-accent hover:bg-accent/5 disabled:opacity-50",children:v?"Drafting…":ge})]}):Re?d.jsx("button",{onClick:Re.onClick,disabled:K.key==="convert"&&(P||H),"data-testid":Re.testid,className:"px-2.5 py-1 text-[11px] font-medium rounded bg-accent text-white hover:bg-accent-dim disabled:opacity-50",children:Re.label}):null,!X&&!Re&&he&&d.jsx("button",{onClick:b,disabled:v,"data-testid":`ai-draft-${e.id}`,className:"px-2.5 py-1 text-[11px] rounded border border-accent/40 text-accent hover:bg-accent/5 disabled:opacity-50",children:v?"Drafting…":ge}),d.jsx("button",{onClick:o,"data-testid":`cut-details-${e.id}`,className:"px-2.5 py-1 text-[11px] rounded border border-border text-muted hover:border-accent hover:text-accent",children:a?"Hide details":"Open details"})]})]}),a&&d.jsxs("div",{className:"px-3 pb-3 space-y-3 border-t border-border",children:[R&&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:Z,disabled:P||H,"data-testid":`convert-cut-${e.id}`,className:"px-2 py-1 text-[11px] border border-amber-500/50 text-amber-800 rounded hover:bg-amber-500/20 disabled:opacity-50",children:P?"Converting…":"Convert image"})]}),j&&!R&&d.jsxs("div",{className:"mt-2 rounded border border-error/40 bg-error/5 p-2 space-y-1","data-testid":`stale-asset-${e.id}`,children:[S.map((Ue,qe)=>d.jsx("p",{className:"text-[11px] text-error",children:Ue},qe)),d.jsx("button",{onClick:N,disabled:B,"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:B?"Repairing…":"Clear stale path"})]}),!_n(e)&&d.jsxs("div",{className:"mt-2 space-y-2",children:[d.jsx("button",{onClick:()=>{navigator.clipboard.writeText(gy(e,i)),F(!0),setTimeout(()=>F(!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:re?"Copied!":"Copy Codex task"}),d.jsx("input",{ref:D,type:"file",accept:"image/webp,image/jpeg,image/png",className:"hidden",onChange:Ue=>{var St;const qe=(St=Ue.target.files)==null?void 0:St[0];qe&&k(qe),Ue.target.value=""}}),d.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[d.jsx("button",{onClick:()=>{var Ue;return(Ue=D.current)==null?void 0:Ue.click()},disabled:ne,className:"px-3 py-1.5 text-xs border border-border rounded hover:border-accent hover:bg-accent/5 disabled:opacity-50",children:ne?"Uploading...":e.cleanImagePath?"Replace clean image":"Upload clean image"}),d.jsx("button",{onClick:()=>T(Ue=>!Ue),disabled:ne,"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:U?"Hide Codex images":"Import from Codex"})]}),U&&d.jsx(JD,{authFetch:c,cutId:e.id,onImport:async Ue=>{await k(Ue)&&T(!1)},onClose:()=>T(!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."}),xe==="missing"&&d.jsxs("div",{className:"rounded border border-border bg-surface/60 p-2 space-y-1","data-testid":`ask-codex-${e.id}`,children:[d.jsx("p",{className:"text-[11px] font-medium text-foreground",children:"Generate this cut in Codex"}),d.jsxs("p",{className:"text-[10px] text-muted",children:["Copy the task below and paste it into Codex. Codex usually saves a PNG to its image cache — bring it into this cut with “Import from Codex” above (the PNG becomes a WebP automatically). If Codex instead writes a WebP/JPEG at"," ",d.jsxs("span",{className:"font-mono",children:["assets/",i,"/cut-",String(e.id).padStart(2,"0"),"-clean.webp"]}),", it’s picked up by “Sync clean images”."]}),d.jsx("button",{onClick:()=>{navigator.clipboard.writeText(gy(e,i)),V(!0),setTimeout(()=>V(!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:Y?"Copied!":"Copy Codex task"})]}),xe==="missing"&&f&&d.jsx("button",{onClick:_,disabled:x,"data-testid":`found-local-clean-${e.id}`,className:"px-3 py-1.5 text-xs border border-green-700/40 text-green-700 rounded hover:bg-green-700/5 disabled:opacity-50",children:x?"Syncing...":"Found local clean image — sync to cut plan"}),be&&d.jsx("p",{className:"text-xs text-error mt-1",children:be})]}),(e.cleanImagePath||e.narration||e.dialogue.length>0||_n(e))&&d.jsx("button",{onClick:p,"data-testid":`open-editor-${e.id}`,className:"px-3 py-1.5 text-xs border border-accent/30 text-accent rounded hover:bg-accent/5",children:"Open editor"}),e.characters.length>0&&d.jsxs("p",{className:"text-xs text-muted",children:["Characters: ",e.characters.join(", ")]}),e.dialogue.length>0&&d.jsx("div",{className:"text-xs text-muted",children:e.dialogue.map((Ue,qe)=>d.jsxs("p",{children:[d.jsxs("span",{className:"font-medium",children:[Ue.speaker,":"]})," ",Ue.text]},qe))}),e.narration&&d.jsx("p",{className:"text-xs text-muted italic",children:e.narration})]})]})}function vy({storyName:e,fileName:t,authFetch:i,language:s,uploadRetry:a,onCutsChanged:o,focusRequest:c,onFocusHandled:h,onFocusedLetteringModeChange:p,workspaceVisible:f=!1,onWorkspaceVisibleChange:_}){var Kt,jt,ni;const[x,b]=w.useState(null),v=w.useRef(o);v.current=o;const S=w.useRef(h);S.current=h;const[N,B]=w.useState(!0),[E,O]=w.useState(null),[H,A]=w.useState(null),[W,D]=w.useState(null),[ne,ue]=w.useState(!1),[be,L]=w.useState([]),[re,F]=w.useState(!1),[Y,V]=w.useState(""),[U,T]=w.useState({markdownReady:!1,published:!1}),[P,q]=w.useState(!1),[xe,j]=w.useState(!1),[R,Z]=w.useState(!1),[k,K]=w.useState(null),[ae,oe]=w.useState(null),[X,he]=w.useState(null),[ge,Re]=w.useState(!1),[Le,Fe]=w.useState(new Set),[ye,st]=w.useState(new Map),[yt,Ue]=w.useState(!1),[qe,St]=w.useState(null),[ze,nt]=w.useState(!1),[Ee,Wt]=w.useState(null),vi=w.useRef(new Map),Ct=w.useRef(null),et=t.replace(/\.md$/,"");w.useEffect(()=>{var M;c&&Ct.current!==c.seq&&(Ct.current=c.seq,c.openEditor?D(c.cutId):(A(c.cutId),Wt(c.cutId)),(M=S.current)==null||M.call(S))},[c]),w.useEffect(()=>(p==null||p(W!==null),()=>p==null?void 0:p(!1)),[W,p]),w.useEffect(()=>{var ie;if(Ee==null)return;const M=vi.current.get(Ee);M&&((ie=M.scrollIntoView)==null||ie.call(M,{behavior:"smooth",block:"center"}),Wt(null))},[Ee,x]);const ee=w.useCallback(async()=>{var M;try{const ie=await i(`/api/stories/${e}/cuts/${et}`);if(ie.status===404){b(null);return}if(!ie.ok){const Be=await ie.json();O(Be.error||"Failed to load cuts");return}const me=await ie.json();b(me),O(null);try{const Be=await i(`/api/stories/${e}/${t}`);if(Be.ok){const Se=await Be.json(),Te=typeof(Se==null?void 0:Se.content)=="string"?Se.content:"",Ve=Array.isArray(me==null?void 0:me.cuts)?me.cuts:[],Ke=Te.length>0&&KS(Te,Ve).ready,_t=(Se==null?void 0:Se.status)==="published"||(Se==null?void 0:Se.status)==="published-not-indexed";T({markdownReady:Ke,published:_t})}else T({markdownReady:!1,published:!1})}catch{T({markdownReady:!1,published:!1})}(M=v.current)==null||M.call(v)}catch{O("Failed to load cuts")}finally{B(!1)}},[i,e,et,t]),_e=w.useCallback(async M=>!!(await i(`/api/stories/${e}/cuts/${et}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(M)})).ok,[i,e,et]),Me=w.useCallback(async()=>{Ue(!1);try{const M=await i(`/api/stories/${e}/cuts/${et}/detect-clean-images`);if(!M.ok)return;const ie=await M.json();Fe(new Set(Array.isArray(ie.detected)?ie.detected:[]));const me=new Map,Be=ie.stale;if(Array.isArray(Be))for(const Se of Be){if(typeof(Se==null?void 0:Se.cutId)!="number"||typeof(Se==null?void 0:Se.message)!="string")continue;const Te=me.get(Se.cutId)??[];Te.push(Se.message),me.set(Se.cutId,Te)}st(me),Ue(!0)}catch{}},[i,e,et]),He=w.useCallback(async()=>{St(null);try{const M=await i(`/api/stories/${e}/cuts/${et}/asset-diagnostics`);if(!M.ok)return;const ie=await M.json();St(Array.isArray(ie.diagnostics)?ie.diagnostics:null)}catch{}},[i,e,et]),Ze=w.useCallback(async()=>{nt(!0);try{await Promise.all([ee(),Me(),He()])}finally{nt(!1)}},[ee,Me,He]),Gt=w.useCallback(async(M,ie={})=>{var Se;if(!x)return!1;const me=x.cuts.find(Te=>Te.id===M);if(!me||!Bo(me)||(((Se=me.overlays)==null?void 0:Se.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 Be=hy(me);if(Be.length===0)return oe(`Cut ${me.id}: no script lines available to draft.`),!1;he(M),oe(null);try{const Te={...x,cuts:x.cuts.map(Ke=>Ke.id===M?{...Ke,overlays:Be,aiDraft:_y(Be)}:Ke)};return await _e(Te)?(oe(`Cut ${me.id}: AI draft ready`),await ee(),ie.openEditor&&D(M),!0):(oe(`Cut ${me.id}: AI draft failed`),!1)}finally{he(null)}},[x,_e,ee]),mi=w.useCallback(async()=>{if(!x)return;const M=x.cuts.filter(ie=>{var me;return Bo(ie)&&(((me=ie.overlays)==null?void 0:me.length)??0)===0&&!ie.finalImagePath&&!ie.uploadedCid&&!ie.uploadedUrl});if(M.length===0){oe("No unlettered cuts need an AI draft");return}Re(!0),oe(null);try{const ie={...x,cuts:x.cuts.map(Be=>{if(!M.some(Te=>Te.id===Be.id))return Be;const Se=hy(Be);return Se.length>0?{...Be,overlays:Se,aiDraft:_y(Se)}:Be})};if(!await _e(ie)){oe("AI draft failed");return}oe(`AI draft ready for ${M.length} cut${M.length===1?"":"s"}`),await ee()}finally{Re(!1)}},[x,_e,ee]),At=w.useCallback(async()=>{q(!0),oe(null),L([]);try{const M=await i(`/api/stories/${e}/cuts/${et}/sync-clean-images`,{method:"POST"}),ie=await M.json().catch(()=>({}));if(!M.ok)oe(ie.error||"Sync failed");else{const me=Array.isArray(ie.synced)?ie.synced.length:0,Be=Array.isArray(ie.cleared)?ie.cleared.length:0,Se=Array.isArray(ie.rejected)?ie.rejected:[];Se.length>0&&L(Se.map(Ve=>`Cut ${Ve.cutId}: ${Ve.reason}`));const Te=[];me>0&&Te.push(`Synced ${me}`),Be>0&&Te.push(`Cleared ${Be} stale path${Be===1?"":"s"}`),oe(Te.length>0?Te.join(", "):"No new clean images"),await ee(),await Me(),await He()}}catch{oe("Sync failed")}q(!1)},[i,e,et,ee,Me,He]),wt=w.useCallback(async(M,ie)=>{try{const me=await i(HS(e,ie));if(!me.ok)return!1;const Be=await me.blob(),Se=await Ku(new File([Be],"clean.png",{type:Be.type||"image/png"})),Te=Se.type==="image/jpeg"?"jpg":"webp",Ve=new FormData;return Ve.append("file",new File([Se],`clean.${Te}`,{type:Se.type})),(await i(`/api/stories/${e}/cuts/${et}/upload-clean/${M}`,{method:"POST",body:Ve})).ok}catch{return!1}},[i,e,et]),Yt=w.useCallback(async M=>{Z(!0),K(null);let ie=0;const me=[];for(const Be of M)await wt(Be.cutId,Be.pngPath)?ie++:me.push(Be.cutId);await Ze(),Z(!1),K(me.length===0?`Converted ${ie} image${ie===1?"":"s"} to WebP`:`Converted ${ie}; ${me.length} failed (Cut ${me.join(", ")}) — try Convert image on each`)},[wt,Ze]),ot=w.useCallback(async()=>{var Se;if(!x)return;F(!0),V(""),L([]);const M=x.cuts.filter(Te=>Te.finalImagePath&&!Te.uploadedCid),ie=[],me=$D({sleep:a==null?void 0:a.sleep,onWaiting:({waitMs:Te})=>V(`Upload limit reached — waiting ${Math.round(Te/1e3)}s before continuing…`)});for(let Te=0;Te{const ri=await i("/api/publish/upload-plot-image",{method:"POST",body:Qe});if(ri.ok){const{cid:Bn,url:Lr}=await ri.json();return{ok:!0,status:ri.status,cid:Bn,url:Lr}}const an=await ri.json().catch(()=>({}));return{ok:!1,status:ri.status,errorMessage:an.error}},{...a,onWaiting:({attempt:ri,maxRetries:an,waitMs:Bn})=>V(`Cut ${Ve.id} rate-limited — waiting ${Math.round(Bn/1e3)}s before retry ${ri}/${an}...`)});if(!Bt.ok){ie.push(`Cut ${Ve.id}: upload failed — ${Bt.errorMessage||"unknown"}`);continue}const{cid:yi,url:fn}=Bt;(await i(`/api/stories/${e}/cuts/${et}/set-uploaded/${Ve.id}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cid:yi,url:fn})})).ok||ie.push(`Cut ${Ve.id}: failed to record upload`)}catch(Ke){ie.push(`Cut ${Ve.id}: ${Ke instanceof Error?Ke.message:"failed"}`)}}if(ie.length>0){L(ie),F(!1),V(""),ee();return}V("Preparing episode for publishing…");const Be=await i(`/api/stories/${e}/cuts/${et}/generate-markdown`,{method:"POST"});if(Be.ok){const Te=await Be.json();((Se=Te.warnings)==null?void 0:Se.length)>0&&L(Te.warnings)}F(!1),V(""),ee()},[x,i,e,et,a,ee]),Ht=w.useCallback(async()=>{j(!0),oe(null);try{const M=await i(`/api/stories/${e}/cuts/${et}/repair-asset-paths`,{method:"POST"}),ie=await M.json().catch(()=>({}));if(!M.ok)oe(ie.error||"Repair failed");else{const me=Array.isArray(ie.cleared)?ie.cleared.length:0;oe(me>0?`Cleared ${me} stale path${me===1?"":"s"}`:"No stale paths to clear"),await ee(),await Me()}}catch{oe("Repair failed")}j(!1)},[i,e,et,ee,Me]),[$,we]=w.useState(!1),Ae=w.useCallback(async(M,ie=!0)=>{if(x){we(!0);try{const me=x.cuts.reduce((Ke,_t)=>Math.max(Ke,_t.id),0)+1,Be={id:me,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"},Se=[...x.cuts];Se.splice(Math.max(0,Math.min(M,Se.length)),0,Be);const Te={...x,cuts:Se},Ve=await i(`/api/stories/${e}/cuts/${et}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(Te)});if(Ve.ok)ie?D(me):A(me),await ee();else{const Ke=await Ve.json().catch(()=>({}));oe(Ke.error||"Could not add text panel")}}catch{oe("Could not add text panel")}we(!1)}},[x,i,e,et,ee]),Ne=w.useCallback(()=>Ae((x==null?void 0:x.cuts.length)??0,!0),[Ae,x]);if(w.useEffect(()=>{ee(),Me(),He()},[ee,Me,He]),N)return d.jsx("div",{className:"p-4 text-sm text-muted",children:"Loading cuts..."});if(E)return d.jsxs("div",{className:"p-4 space-y-2","data-testid":"cuts-error",children:[d.jsx("p",{className:"text-sm text-error font-medium",children:"Invalid cuts file"}),d.jsx("p",{className:"text-xs text-error",children:E}),d.jsxs("p",{className:"text-xs text-muted",children:[et,".cuts.json must follow the OWS v1 schema. Ask Claude to regenerate it using the v1 cuts schema from the cartoon writing instructions."]}),d.jsx("button",{onClick:ee,className:"text-xs text-accent hover:text-accent-dim",children:"Retry"})]});if(!x||x.cuts.length===0)return d.jsxs("div",{className:"p-4 text-center space-y-1",children:[d.jsx("p",{className:"text-sm text-muted",children:"No cuts yet"}),d.jsx("p",{className:"text-xs text-muted",children:"Ask Claude to create a cut plan for this episode."})]});const We=W!==null?x.cuts.find(M=>M.id===W):null;if(We)return d.jsx(jD,{storyName:e,cut:We,plotFile:et,language:s,authFetch:i,targetLabel:_n(We)?`Between-scene card ${We.id}`:`Cut ${String(We.id).padStart(2,"0")}`,returnOnSave:!0,workspaceVisible:f,onToggleWorkspaceVisible:_?()=>_(!f):void 0,onSave:async(M,ie)=>{const me={...x,cuts:x.cuts.map(Se=>Se.id===W?{...Se,overlays:M,aiDraft:ie??Se.aiDraft??null}:Se)};if(!await _e(me))throw new Error("Failed to save overlays")},onExported:()=>ee(),onClose:()=>{D(null),ee()}});const Ie=x.cuts.reduce((M,ie)=>{const me=s1(ie);return M[me]++,M},{missing:0,clean:0,lettered:0,uploaded:0,text:0}),ht=x.cuts.filter(M=>!_n(M)).length,xt=x.cuts.filter(M=>GS(M)).map(M=>M.id),Nt=hD({cuts:x.cuts,published:U.published}),Mt=((Kt=Nt.steps.find(M=>M.key==="upload"))==null?void 0:Kt.status)==="done",Ut=x.cuts.some(M=>M.finalImagePath&&!M.uploadedCid)||Mt&&!U.markdownReady,li=lM(Nt,U.markdownReady,U.published),oi=(qe??[]).filter(M=>M.state==="needs-conversion"&&M.convertiblePng).map(M=>({cutId:M.cutId,pngPath:M.convertiblePng})),ii=new Map(oi.map(M=>[M.cutId,M.pngPath])),Sn=(qe??[]).filter(M=>M.state==="needs-conversion"&&M.issue).map(M=>M.issue),Vn=t==="genesis.md"?"Genesis / Episode 1":`Episode ${parseInt(((jt=et.match(/\d+/))==null?void 0:jt[0])??"0",10)+1}`,ur=typeof x.title=="string"?x.title:null,dn=x.cuts.filter(M=>!_n(M)),Xi={cuts:x.cuts.length,artwork:dn.filter(M=>M.cleanImagePath||ii.has(M.id)).length,converted:dn.filter(M=>M.cleanImagePath&&/\.(webp|jpe?g)$/i.test(M.cleanImagePath)).length,lettered:x.cuts.filter(M=>{var ie;return(((ie=M.overlays)==null?void 0:ie.length)??0)>0||!!M.finalImagePath}).length,uploaded:x.cuts.filter(M=>M.uploadedCid||M.uploadedUrl).length},br=x.cuts.filter(M=>{var ie;return Bo(M)&&(((ie=M.overlays)==null?void 0:ie.length)??0)===0&&!M.finalImagePath&&!M.uploadedCid&&!M.uploadedUrl}).length,gi=aM(qe);return d.jsxs("div",{className:"h-full min-h-[22rem] flex flex-col overflow-hidden","data-testid":"cut-list-panel",children:[d.jsx("div",{className:"px-3 py-2 border-b border-border flex-shrink-0","data-testid":"cut-board-header",children:d.jsxs("div",{className:"flex items-start gap-3 justify-between",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:"font-serif text-foreground truncate",children:Vn}),ur&&d.jsxs("span",{className:"text-muted truncate",children:["· ",ur]})]}),d.jsxs("div",{className:"mt-0.5 text-[10px] text-muted","data-testid":"cut-board-summary",children:[Xi.cuts," cuts · ",Xi.artwork," artwork found ·"," ",Xi.converted," converted · ",Xi.lettered," ","lettered · ",Xi.uploaded," uploaded"]})]}),br>0&&d.jsx("button",{onClick:mi,disabled:ge,"data-testid":"ai-draft-all-btn",className:"px-2.5 py-1 text-[11px] rounded border border-accent/40 text-accent hover:bg-accent/5 disabled:opacity-50",children:ge?"Drafting…":`AI draft all unlettered (${br})`})]})}),d.jsxs("details",{className:"border-b border-border bg-surface/35 flex-shrink-0","data-testid":"cut-workspace-tools",children:[d.jsx("summary",{className:"list-none cursor-pointer px-3 py-2 hover:bg-surface/50",children:d.jsxs("div",{className:"flex items-start gap-3 justify-between",children:[d.jsxs("div",{className:"min-w-0 space-y-1",children:[d.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 text-[10px]",children:[d.jsxs("span",{className:"rounded-full border border-accent/30 bg-background px-2 py-0.5 font-medium text-accent",children:["Workflow: ",li]}),gi&&d.jsxs("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-muted","data-testid":"workspace-asset-summary",children:["Assets: ",gi]}),oi.length>0&&d.jsxs("span",{className:"rounded-full border border-amber-500/40 bg-amber-500/10 px-2 py-0.5 text-amber-700",children:["Convert ",oi.length," PNG",oi.length===1?"":"s"]})]}),d.jsx("p",{className:"text-[10px] text-muted",children:"Per-cut actions stay on each card. Open workspace tools for publish prep, asset recovery, narration cards, and workflow guidance."})]}),d.jsx("span",{className:"flex-shrink-0 rounded border border-border bg-background px-2 py-1 text-[10px] text-muted",children:"Workspace tools"})]})}),d.jsxs("div",{className:"border-t border-border px-3 py-2 space-y-3",children:[d.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[10px]",children:[d.jsxs("span",{className:"font-mono text-muted",children:[x.cuts.length," cuts"]}),Ie.missing>0&&d.jsxs("span",{className:"text-muted",children:[Ie.missing," missing"]}),Ie.clean>0&&d.jsxs("span",{className:"text-green-700",children:[Ie.clean," clean"]}),Ie.lettered>0&&d.jsxs("span",{className:"text-amber-700",children:[Ie.lettered," lettered"]}),Ie.uploaded>0&&d.jsxs("span",{className:"text-green-700",children:[Ie.uploaded," uploaded"]}),Ie.text>0&&d.jsxs("span",{className:"text-accent",children:[Ie.text," text ",Ie.text===1?"panel":"panels"]}),d.jsx("button",{onClick:async()=>{ue(!0),L([]);try{const M=await i(`/api/stories/${e}/cuts/${et}/generate-markdown`,{method:"POST"});if(M.ok){const ie=await M.json();L(ie.warnings||[])}}catch{}ue(!1)},disabled:ne,className:"ml-auto px-2 py-0.5 border border-accent/30 text-accent rounded hover:bg-accent/5 disabled:opacity-50","data-testid":"generate-markdown-btn",title:"Build the publish-ready episode from the uploaded cut images",children:ne?"Preparing…":"Prepare episode for publish"}),d.jsx("button",{onClick:Ne,disabled:$,className:"px-2 py-0.5 border border-accent/30 text-accent rounded hover:bg-accent/5 disabled:opacity-50","data-testid":"add-text-panel-btn",title:"Insert a narration/title card between art panels — a solid card exported as a final image panel, no drawing needed",children:$?"Adding…":"Add narration/text panel"}),d.jsx("button",{onClick:Ze,disabled:ze,className:"px-2 py-0.5 border border-border text-muted rounded hover:border-accent hover:text-accent disabled:opacity-50","data-testid":"refresh-assets-btn",title:"Re-check the story folder for agent-generated images and report each cut's asset state — read only, nothing is uploaded or published",children:ze?"Checking…":"Refresh assets"}),d.jsx("button",{onClick:At,disabled:P,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:P?"Syncing...":"Sync clean images"}),d.jsx("button",{onClick:ot,disabled:re||!(x!=null&&x.cuts.some(M=>M.finalImagePath&&!M.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("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."]}),oi.length>0&&d.jsxs("div",{className:"rounded border border-amber-500/40 bg-amber-500/10 p-2 text-[11px]","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:[oi.length," PNG image",oi.length===1?"":"s"," found"]}),d.jsx("button",{onClick:()=>Yt(oi),disabled:R,"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:R?"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}),Sn.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:"Conversion notes"}),d.jsx("ul",{className:"mt-1 ml-3 list-disc text-[10px] text-muted",children:Sn.map((M,ie)=>d.jsx("li",{children:M},ie))})]})]}),qe&&qe.length>0&&(()=>{const M=r1(qe),ie=qe.filter(me=>me.state==="missing");return d.jsxs("div",{className:"rounded border border-border bg-background p-2 text-[10px]","data-testid":"asset-diagnostics",children:[d.jsxs("span",{className:"text-muted","data-testid":"asset-diag-summary",children:["Assets: ",M.uploaded," uploaded · ",M.finalReady," final ·"," ",M.cleanReady," clean · ",M.planned," planned",M.needsConversion>0?` · ${M.needsConversion} needs conversion`:"",M.missing>0?` · ${M.missing} missing`:""]}),ie.length>0&&d.jsx("ul",{className:"mt-1 ml-3 list-disc text-error","data-testid":"asset-diag-issues",children:ie.map(me=>d.jsx("li",{children:me.issue},me.cutId))})]})})(),d.jsx(tM,{checklist:Nt,issues:be,onFinish:ot,finishing:re,progressText:Y,canFinish:Ut,markdownReady:U.markdownReady,published:U.published})]})]}),xt.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:[xt.length===1?"Cut":"Cuts"," ",xt.join(", ")," ",xt.length===1?"was":"were"," lettered with an older speech-bubble style whose tail can show a visible seam. Re-export"," ",xt.length===1?"it":"them"," (open lettering → Export) and re-upload before publishing so the bubble tails are seamless."]}),yt&&ht>0&&Ie.missing===0&&ye.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."]})]}),ae&&d.jsx("div",{className:"px-3 py-1 border-b border-border text-[10px] text-muted flex-shrink-0","data-testid":"sync-result",children:ae}),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((M,ie)=>{var me;return d.jsxs(w.Fragment,{children:[d.jsx(yy,{index:ie,beforeLabel:ie===0?"Episode opening":`After cut ${(me=x.cuts[ie-1])==null?void 0:me.id}`,afterLabel:`Before cut ${M.id}`,disabled:$,onAdd:()=>Ae(ie)}),d.jsx(sM,{cut:M,storyName:e,plotFile:et,language:s,expanded:H===M.id,onToggle:()=>A(H===M.id?null:M.id),authFetch:i,onUpdated:()=>{ee(),Me(),He()},onOpenEditor:()=>D(M.id),detectedLocalClean:Le.has(M.id),onSyncClean:At,syncing:P,onAiDraft:()=>{Gt(M.id,{openEditor:!0})},aiDrafting:X===M.id,staleMessages:ye.get(M.id)??[],onRepairStale:Ht,repairing:xe,conversionPng:ii.get(M.id)??null,onConvert:wt,converting:R,featured:ie===0,rowRef:Be=>{Be?vi.current.set(M.id,Be):vi.current.delete(M.id)}})]},M.id)}),d.jsx(yy,{index:x.cuts.length,beforeLabel:`After cut ${(ni=x.cuts[x.cuts.length-1])==null?void 0:ni.id}`,afterLabel:"Episode ending",disabled:$,onAdd:()=>Ae(x.cuts.length)})]})]})}function yy({index:e,beforeLabel:t,afterLabel:i,disabled:s,onAdd:a}){return d.jsxs("div",{className:"rounded border border-dashed border-border bg-surface/35 px-3 py-2 text-[11px] text-muted flex items-center gap-3","data-testid":`between-scene-slot-${e}`,children:[d.jsxs("span",{className:"min-w-0 flex-1",children:[d.jsx("span",{className:"font-medium text-foreground",children:"Between-scene lettering"}),d.jsxs("span",{className:"block truncate",children:[t," · ",i]})]}),d.jsx("button",{type:"button",onClick:a,disabled:s,className:"flex-shrink-0 rounded border border-accent/40 px-2.5 py-1 text-[11px] font-medium text-accent hover:bg-accent/5 disabled:opacity-50","data-testid":`add-between-scene-${e}`,children:"Add card"})]})}function aM(e){if(!e||e.length===0)return null;const t=r1(e),i=[`${t.cleanReady} clean`,`${t.finalReady} final`,`${t.uploaded} uploaded`];return t.needsConversion>0&&i.push(`${t.needsConversion} PNG`),t.missing>0&&i.push(`${t.missing} missing`),i.join(" · ")}function lM(e,t,i){if(i)return"Published to PlotLink";if(t)return"Ready to publish";const s=e.steps.find(a=>a.status==="current")??e.steps.find(a=>a.status==="todo")??e.steps[e.steps.length-1];return(s==null?void 0:s.label)??"Review cuts"}const oM=1024*1024,cM=["image/webp","image/jpeg"],uM="Cover: WebP or JPEG, max 1MB, 600×900 portrait recommended. Use clean cover art — avoid unreadable AI text or broken lettering.";function hM(e){return e.attached?{state:"attached",label:"Cover attached to your story.",tone:"success"}:e.invalid?{state:"invalid",label:"Cover file can't be used — must be WebP or JPEG, max 1MB.",tone:"error"}:e.hasSelectedCover?{state:"selected",label:"Cover selected — it will be uploaded when you publish.",tone:"accent"}:{state:"none",label:"No cover yet — add one before publishing (recommended).",tone:"muted"}}function Sy(e){return e.size>oM?"Image exceeds 1MB limit":cM.includes(e.type)?null:"Only WebP and JPEG images are accepted"}async function dM(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 fM(e){return e.replace(/[-_]+/g," ").replace(/\s+/g," ").trim().split(" ").map(t=>t&&t[0].toUpperCase()+t.slice(1)).join(" ")}function Uo(e,t){const i=(e??"").trim().toLowerCase();if(!i)return!0;if(t==="genesis.md")return i==="genesis";const s=t.match(/^(plot-\d+)\.md$/);return s?i===s[1].toLowerCase()||/^plot-\d+$/.test(i):!1}function pM(e){const t=e.match(/^plot-(\d+)\.md$/);if(!t)return null;const i=t[1];return`Episode ${i.length<2?i.padStart(2,"0"):i}`}function Ip(e){const t=(e??"").trim();return!!(!t||/^(?:episode|ep|chapter|ch|part|pt|plot)\.?\s*[-–—:#]?\s*\d+$/i.test(t)||/^\d+$/.test(t)||/^plot[-_\s]?\d+$/i.test(t))}function Em(e){var s;const t=Pp(e.fileContent);if(t)return!Ip(t);const i=((s=e.episodeTitle)==null?void 0:s.trim())||null;return!!i&&!Ip(i)}function Nm(e){const{fileName:t,fileContent:i,storySlug:s,structureContent:a,contentType:o,episodeTitle:c}=e,h=Pp(i);if(t==="genesis.md"){const p=a?Pp(a):null;return(h??p??fM(s)).slice(0,60)}if(h)return h.slice(0,60);if(o==="cartoon"){const p=c==null?void 0:c.trim(),f=pM(t);return((p||f)??t.replace(/\.md$/,"")).slice(0,60)}return t.replace(/\.md$/,"").slice(0,60)}function mM(e){return!!(e!=null&&e.txHash)&&(e==null?void 0:e.plotIndex)!=null&&e.plotIndex>0}function gM(e){return mM(e)&&(e==null?void 0:e.status)!=="published-not-indexed"}function wy(e,t,i){if(e[t]==="cartoon"&&!i)return"cartoon"}function xM(e,t,i){return!(e!=="cartoon"||t||!i||i.startsWith("_new_"))}function Of(e,t,i){if(e)return t[e]||i.get(e)||"fiction"}function zf(e){if(!e)return null;const t=Number(e);return Number.isFinite(t)?(t/1e18).toFixed(6):null}function _M(e){return!!e&&e.ready===!1}function bM(e){const t=zf(e.requiredBalance)??zf(e.creationFee),i=zf(e.ethBalance);return e.hasEnoughEth===!1&&t&&i?`Insufficient ETH: need at least ${t} ETH to publish; current balance is ${i} ETH.`+(e.address?` Top up the OWS wallet (${e.address}) and try again.`:" Top up the OWS wallet and try again."):e.error||"Publish preflight failed — the OWS wallet isn't ready to publish."}const vM={...ml,attributes:{...ml.attributes,img:["src","alt","title"]}},yM="https://ipfs.filebase.io/ipfs/";function SM(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 wM(e){const t=SM(e),i=[];for(const a of t)a.url.startsWith(yM)||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 CM(e){return e==="open-cuts"||e==="open-lettering"||e==="upload"||e==="refresh-assets"}function kM({storyName:e,fileName:t,authFetch:i,onPublish:s,publishingFile:a,walletAddress:o,contentType:c="fiction",language:h,genre:p,isNsfw:f,hasGenesis:_=!1,onViewProgress:x,onOpenFile:b,onViewPublish:v,focusedLetteringMode:S=!1,focusedLetteringWorkspaceVisible:N=!1,onFocusedLetteringModeChange:B,onFocusedLetteringWorkspaceVisibleChange:E,workflowActionRequest:O=null,onWorkflowActionHandled:H}){const[A,W]=w.useState(null),[D,ne]=w.useState(!1),[ue,be]=w.useState("preview"),[L,re]=w.useState("publish"),[F,Y]=w.useState("text"),[V,U]=w.useState(null),T=w.useCallback((se,ke)=>{be("edit"),U(je=>({cutId:se,openEditor:ke,seq:((je==null?void 0:je.seq)??0)+1}))},[]),[P,q]=w.useState(""),[xe,j]=w.useState(!1),[R,Z]=w.useState(!1),[k,K]=w.useState(!1),[ae,oe]=w.useState(null),[X,he]=w.useState(""),[ge,Re]=w.useState(""),[Le,Fe]=w.useState(!1),[ye,st]=w.useState(null),[yt,Ue]=w.useState(0),[qe,St]=w.useState(0),[ze,nt]=w.useState(null),[Ee,Wt]=w.useState(null),[vi,Ct]=w.useState(null),[et,ee]=w.useState(0),_e=w.useRef(null),Me=w.useRef(!1),[He,Ze]=w.useState(!1),[Gt,mi]=w.useState(hl[0]),[At,wt]=w.useState(ss[0]),[Yt,ot]=w.useState(!1),[Ht,$]=w.useState(null),[we,Ae]=w.useState(null),[Ne,We]=w.useState(!1),[Ie,ht]=w.useState(!1),[xt,Nt]=w.useState(!1),[Mt,Ut]=w.useState(null),[li,oi]=w.useState(!1),ii=w.useRef(null),Sn=w.useRef(null),[Vn,ur]=w.useState(!1),[dn,Xi]=w.useState(null),[br,gi]=w.useState(null),[Kt,jt]=w.useState("unknown"),ni=w.useRef(!1),[M,ie]=w.useState(!1),[me,Be]=w.useState(!1),[Se,Te]=w.useState(null),[Ve,Ke]=w.useState([]),[_t,tt]=w.useState(null),Qe=w.useRef(null),Bt=w.useRef(null),yi=w.useRef(0),fn=w.useRef(!1);fn.current=CM(O==null?void 0:O.action);const Di=w.useCallback(async()=>{if(!e||!t){W(null);return}const se=`${e}/${t}`,ke=Bt.current!==se;ke&&(Bt.current=se);try{const je=await i(`/api/stories/${e}/${t}`);if(je.ok){const Je=await je.json();W(Je),(ke||!Me.current)&&(q(Je.content??""),ke&&(Z(!1),Me.current=!1))}}catch{}},[e,t,i]);w.useEffect(()=>{ne(!0),Di().finally(()=>ne(!1))},[Di]),w.useEffect(()=>{if(!e||!t||ue==="edit"&&R)return;const se=setInterval(Di,3e3);return()=>clearInterval(se)},[e,t,Di,ue,R]);const[ri,an]=w.useState(null),Bn=c==="cartoon"&&t==="genesis.md";w.useEffect(()=>{if(!Bn||!e){an(null);return}let se=!1;return i(`/api/stories/${e}/cuts/genesis`).then(ke=>ke.ok?ke.json():null).then(ke=>{se||an(ke?Op(ke.cuts||[]):null)}).catch(()=>{se||an(null)}),()=>{se=!0}},[Bn,e,i]);const Lr=c==="cartoon"&&!!t&&/^plot-\d+\.md$/.test(t);w.useEffect(()=>{if(!Lr||!e||!t){st(null),Ue(0),St(0),nt(null);return}let se=!1;const ke=t.replace(/\.md$/,"");return nt(null),(async()=>{try{const[je,Je]=await Promise.all([i(`/api/stories/${e}/${t}`),i(`/api/stories/${e}/cuts/${ke}`)]);if(se)return;if(!Je.ok){st("error"),Ue(0),St(0),nt(null);return}const Lt=await Je.json(),Mi=Lt.cuts||[],ci=je.ok?(await je.json()).content??"":"",Cn=XS(ci,Mi);se||(st(Cn.stage),Ue(Cn.awaitingCount),St(Cn.totalCuts),nt(Op(Mi)),Ct(typeof Lt.title=="string"?Lt.title:null))}catch{se||(st("error"),Ue(0),St(0),nt(null))}})(),()=>{se=!0}},[Lr,e,t,i,A==null?void 0:A.content,A==null?void 0:A.status,et]),w.useEffect(()=>{if(!e){Wt(null);return}let se=!1;return i(`/api/stories/${e}/structure.md`).then(ke=>ke.ok?ke.json():null).then(ke=>{se||Wt((ke==null?void 0:ke.content)??null)}).catch(()=>{}),()=>{se=!0}},[e,i]),w.useEffect(()=>{if(!e)return;const se=Cu(p);let ke=se??"";if(!se&&Ee){const Je=Ee.match(/\*{0,2}genre\*{0,2}[:\s]+(.+)/i);Je&&(ke=Cu(Je[1].replace(/\*+/g,"").trim())??"")}he(ke);let je=h&&ss.find(Je=>Je.toLowerCase()===h.toLowerCase())||"";if(!je&&Ee){const Je=Ee.match(/\*{0,2}language\*{0,2}[:\s]+(.+)/i);Je&&(je=ss.find(Lt=>Lt.toLowerCase()===Je[1].replace(/\*+/g,"").trim().toLowerCase())||"")}Re(je),Fe(f??!1)},[e,p,h,f,Ee]);const vr=w.useCallback(se=>{e&&i(`/api/stories/${e}/publish-metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(se)}).catch(()=>{})},[e,i]),$t=w.useCallback(async()=>{if(!(!e||!t)){j(!0);try{(await i(`/api/stories/${e}/${t}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:P})})).ok&&(Z(!1),Me.current=!1,W(ke=>ke&&{...ke,content:P}))}catch{}j(!1)}},[e,t,i,P]),Ii=w.useCallback(async()=>{if(!e||!t)return;const se=t.replace(/\.md$/,"");try{(await i(`/api/stories/${e}/cuts/${se}/generate-markdown`,{method:"POST"})).ok&&(await Di(),ee(je=>je+1))}catch{}},[e,t,i,Di]);w.useEffect(()=>{if(O&&O.seq!==yi.current){switch(yi.current=O.seq,O.action){case"view-progress":x==null||x();break;case"open-cuts":case"open-lettering":case"upload":case"refresh-assets":be("edit"),Y("cuts");break;case"generate-markdown":Ii();break;case"publish":be("preview");break}H==null||H(O.seq)}},[O,x,Ii,H]);const Si=w.useCallback(se=>{var Je;const ke=(Je=se.target.files)==null?void 0:Je[0];if(!ke)return;ni.current=!0,Xi(null),gi(null);const je=Sy(ke);if(je){$(null),Ae(Lt=>(Lt&&URL.revokeObjectURL(Lt),null)),ii.current&&(ii.current.value=""),Ut(je),jt("invalid");return}$(ke),Ae(Lt=>(Lt&&URL.revokeObjectURL(Lt),URL.createObjectURL(ke))),Ut(null),jt("selected")},[]),Or=w.useCallback(async se=>{var je;const ke=(je=se.target.files)==null?void 0:je[0];if(Sn.current&&(Sn.current.value=""),!(!ke||!e)){ni.current=!0,Xi(null),ur(!0),Ut(null);try{let Je;try{Je=await Ku(ke)}catch(Xn){$(null),Ae(ds=>(ds&&URL.revokeObjectURL(ds),null)),Ut(Xn instanceof Error?Xn.message:"Could not import image");return}const Lt=Je.type==="image/jpeg"?"jpg":"webp",Mi=new File([Je],`cover.${Lt}`,{type:Je.type}),ci=new FormData;ci.append("file",Mi);const Cn=await i(`/api/stories/${e}/import-cover`,{method:"POST",body:ci});if(!Cn.ok){const Xn=await Cn.json().catch(()=>({}));Ut(Xn.error||"Cover import failed");return}$(Mi),Ae(Xn=>(Xn&&URL.revokeObjectURL(Xn),URL.createObjectURL(Mi))),gi(null),jt("selected"),Ut(null)}catch{Ut("Cover import failed")}finally{ur(!1)}}},[e,i]),zr=w.useCallback(async se=>{if(se.size>1024*1024){Te("Image exceeds 1MB limit");return}if(!["image/webp","image/jpeg"].includes(se.type)){Te("Only WebP and JPEG images are accepted");return}Be(!0),Te(null);try{const je=new FormData;je.append("file",se);const Je=await i("/api/publish/upload-plot-image",{method:"POST",body:je});if(!Je.ok){const Mi=await Je.json();throw new Error(Mi.error||"Upload failed")}const Lt=await Je.json();Ke(Mi=>[...Mi,{cid:Lt.cid,url:Lt.url}])}catch(je){Te(je instanceof Error?je.message:"Upload failed")}finally{Be(!1),Qe.current&&(Qe.current.value="")}},[i]),Xt=w.useCallback(se=>{var je;const ke=(je=se.target.files)==null?void 0:je[0];ke&&zr(ke)},[zr]),Kn=w.useCallback(async()=>{if(A!=null&&A.storylineId){We(!0),Ut(null),oi(!1);try{let se;if(Ht){const je=new FormData;je.append("file",Ht);const Je=await i("/api/publish/upload-cover",{method:"POST",body:je});if(!Je.ok){const Mi=await Je.json();throw new Error(Mi.error||"Cover upload failed")}se=(await Je.json()).cid}const ke=await i("/api/publish/update-storyline",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storylineId:A.storylineId,...se!==void 0&&{coverCid:se},genre:Gt,language:At,isNsfw:Yt})});if(!ke.ok){const je=await ke.json();throw new Error(je.error||"Update failed")}oi(!0),$(null),se!==void 0&&(Nt(!0),Ae(je=>(je&&URL.revokeObjectURL(je),null)),jt("unknown"),ii.current&&(ii.current.value="")),setTimeout(()=>oi(!1),3e3)}catch(se){Ut(se instanceof Error?se.message:"Update failed")}finally{We(!1)}}},[A==null?void 0:A.storylineId,Ht,Gt,At,Yt,i]);w.useEffect(()=>{Ze(!1),$(null),Ae(null),Ut(null),oi(!1),ht(!1),ie(!1),Ke([]),Te(null),Xi(null),gi(null),jt("unknown"),ni.current=!1,Y(fn.current?"cuts":"text")},[e,t]),w.useEffect(()=>{if(t!=="genesis.md"||!e||!A||A.storylineId||A.status==="published"||A.status==="published-not-indexed"||ni.current)return;let se=!1;return(async()=>{try{const ke=await i(`/api/stories/${e}/cover-asset`);if(se||!ke.ok)return;const je=await ke.json();if(se)return;if(!(je!=null&&je.found)){jt("none");return}if(!je.valid){gi(je.error||"Detected cover asset is invalid and was not used"),jt("invalid");return}const Je=await i(`/api/stories/${e}/asset/${je.path.replace(/^assets\//,"")}`);if(se||!Je.ok)return;const Lt=await Je.blob(),Mi=new File([Lt],je.path.split("/").pop()||"cover.webp",{type:je.type});if(Sy(Mi)||se||ni.current)return;$(Mi),Ae(ci=>(ci&&URL.revokeObjectURL(ci),URL.createObjectURL(Mi))),Xi(je.path),jt("detected")}catch{}})(),()=>{se=!0}},[e,t,A,A==null?void 0:A.status,A==null?void 0:A.storylineId,i]),w.useEffect(()=>{if(!He||!(A!=null&&A.storylineId))return;ht(!1);const se="https://plotlink.xyz";let ke=!1;return fetch(`${se}/api/storyline/${A.storylineId}`).then(je=>je.ok?je.json():null).then(je=>{if(!ke){if(!je){Ut("Could not load current story metadata");return}if(je.genre){const Je=Cu(je.genre);Je&&mi(Je)}if(je.language){const Je=ss.find(Lt=>Lt.toLowerCase()===je.language.toLowerCase());Je&&wt(Je)}je.isNsfw!==void 0&&ot(!!je.isNsfw),Nt(!!(je.coverCid||je.coverUrl||je.cover)),ht(!0)}}).catch(()=>{ke||Ut("Could not load current story metadata")}),()=>{ke=!0}},[He,A==null?void 0:A.storylineId]),w.useEffect(()=>{if(ue!=="edit")return;const se=ke=>{(ke.metaKey||ke.ctrlKey)&&ke.key==="s"&&(ke.preventDefault(),$t())};return window.addEventListener("keydown",se),()=>window.removeEventListener("keydown",se)},[ue,$t]),w.useEffect(()=>{if((A==null?void 0:A.status)!=="published-not-indexed"||!A.publishedAt)return;const se=new Date(A.publishedAt).getTime(),ke=300*1e3,je=()=>{const Lt=Math.max(0,ke-(Date.now()-se));oe(Lt)};je();const Je=setInterval(je,1e3);return()=>clearInterval(Je)},[A==null?void 0:A.status,A==null?void 0:A.publishedAt]);const Pr=ae!==null&&ae<=0,Ws=ae!==null&&ae>0?`${Math.floor(ae/6e4)}:${String(Math.floor(ae%6e4/1e3)).padStart(2,"0")}`:null;if(!e||!t)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted",children:d.jsxs("div",{className:"text-center",children:[d.jsx("p",{className:"text-lg font-serif",children:"Select a file to preview"}),d.jsx("p",{className:"text-sm mt-1",children:"Click a story file in the sidebar"})]})});if(D&&!A)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted",children:"Loading..."});const Ir=(ue==="edit"?P:(A==null?void 0:A.content)??"").length,wi=t==="genesis.md",hr=t?/^plot-\d+\.md$/.test(t):!1,Ci=c==="cartoon"&&hr,Ln=c==="cartoon"&&wi,us=Ln||Ci,On=(A==null?void 0:A.status)==="published"||(A==null?void 0:A.status)==="published-not-indexed",Xo=S&&us,vl=Ln?ri?ri.total:null:Ci?ye===null?null:qe:null,Sa=fD({fileName:t??"",contentType:c,hasGenesis:_,isPublished:On,cutCount:vl,cutProgress:Ln?ri:null}),wa=(Ln||Ci)&&!On,Gs=wa?Nm({fileName:t,fileContent:(A==null?void 0:A.content)??"",storySlug:e??"",structureContent:Ee,contentType:"cartoon",episodeTitle:vi}):null,yl=!!Gs&&Uo(Gs,t),Ys=Ci&&!On&&!Em({fileContent:(A==null?void 0:A.content)??"",episodeTitle:vi}),pn=Ln&&!On?wm((A==null?void 0:A.content)??""):null,Ca=!!pn&&pn.blockers.length>0,Sl="w-full max-w-[32rem] rounded-xl border px-3 py-3",hs={muted:"text-muted",accent:"text-accent",error:"text-error",success:"text-green-700"},Hr=se=>{if(!Ln)return null;const ke=hM({hasSelectedCover:!!Ht,invalid:Kt==="invalid",attached:se});return d.jsxs("div",{className:"flex flex-col gap-0.5","data-testid":"cartoon-cover-status","data-state":ke.state,children:[d.jsx("span",{className:`text-[11px] font-medium ${hs[ke.tone]}`,children:ke.label}),d.jsxs("details",{className:"text-[10px] text-muted","data-testid":"cover-details",children:[d.jsx("summary",{className:"cursor-pointer select-none",children:"Cover tips"}),d.jsx("span",{className:"block mt-0.5","data-testid":"cartoon-cover-guidance",children:uM})]})]})},ka=yl||Ys,wl=()=>{if(!wa||!Gs)return null;const se=wi?"Story title":"Episode title";return d.jsxs("div",{className:"flex flex-col gap-0.5","data-testid":"publish-title-preview","data-raw":yl?"true":"false","data-blocked":ka?"true":"false",children:[d.jsxs("span",{className:"text-[11px] text-foreground",children:[d.jsxs("span",{className:"font-medium",children:[se,":"]})," ",d.jsx("span",{className:ka?"text-error font-medium":"text-foreground",children:Gs})]}),yl?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-raw-error",children:["This would publish as a raw filename."," ",wi?"Add a real “# Title” heading to genesis.md":"Set a title in the cut plan (or add a “# Title” to the episode)"," ","before publishing."]}):Ys?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-episode-required",children:["“",Gs,"” is a generic placeholder, not a reader-facing title, so it can’t be published. Set a real episode title in the cut plan (or add a “# Title” to the episode) — e.g. “Episode 01 — The Couple Coupon” — before publishing."]}):null]})},Zo=()=>pn?d.jsxs("div",{className:"flex flex-col gap-1 rounded border border-border bg-surface/50 p-2","data-testid":"cartoon-genesis-readiness","data-blocked":Ca?"true":"false",children:[d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Story opening (Prologue)"}),d.jsx("span",{className:"text-[10px] text-muted","data-testid":"genesis-readiness-hint",children:"Genesis is the first thing readers see. Write it as the story opening/prologue, not a synopsis — set up the premise and stakes, then bridge into Episode 01."}),pn.blockers.map((se,ke)=>d.jsx("span",{className:"text-[10px] text-error","data-testid":"genesis-readiness-blocker",children:se},`b-${ke}`)),pn.warnings.map((se,ke)=>d.jsx("span",{className:"text-[10px] text-amber-600","data-testid":"genesis-readiness-warning",children:se},`w-${ke}`))]}):null,dr=wi||hr?1e4:null,wn=!On&&dr!==null&&Ir>dr,Cl=(A==null?void 0:A.content)??"",yr=On?{count:0,warnings:[]}:wM(Cl),fr=d.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden","data-testid":"prose-editor-shell",style:{background:"var(--paper-bg)"},children:[d.jsx("textarea",{ref:_e,value:P,onChange:se=>{q(se.target.value),Z(!0),Me.current=!0},className:"flex-1 min-h-0 w-full resize-none px-4 py-3 text-sm leading-relaxed focus:outline-none",style:{fontFamily:'"Geist Mono", ui-monospace, monospace',background:"var(--paper-bg)",color:"var(--text)"},spellCheck:!1,"data-testid":"prose-editor-textarea"}),d.jsxs("div",{className:"shrink-0 px-3 py-1.5 border-t border-border flex items-center justify-between bg-surface/95","data-testid":"prose-editor-savebar",children:[d.jsx("span",{className:"text-xs text-muted",children:R?"Unsaved changes":"No changes"}),d.jsx("button",{onClick:$t,disabled:!R||xe,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50 disabled:cursor-not-allowed",children:xe?"Saving...":"Save"})]})]});return d.jsxs("div",{className:"h-full min-h-0 flex flex-col",children:[!Xo&&d.jsxs("div",{className:"border-b border-border",children:[d.jsxs("div",{className:"px-3 py-1.5 flex items-center justify-between",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs font-mono text-muted",children:[x&&d.jsx("button",{onClick:x,"data-testid":"view-progress-btn",className:"text-accent hover:underline font-sans",title:"Story progress overview",children:"← Progress"}),d.jsxs("span",{children:[e,"/",t]}),(A==null?void 0:A.status)==="published"&&d.jsx("span",{className:"text-green-700 font-medium",children:"Published"}),(A==null?void 0:A.status)==="published-not-indexed"&&d.jsx("span",{className:"text-amber-700 font-medium",title:A.indexError,children:"Published (not indexed)"}),(A==null?void 0:A.status)==="pending"&&d.jsx("span",{className:"text-amber-700 font-medium",children:"Pending"})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs("span",{className:`text-xs font-mono ${wn?"text-error font-medium":"text-muted"}`,children:[Ir.toLocaleString(),dr!==null?`/${dr.toLocaleString()}`:" chars"]}),wn&&d.jsxs("span",{className:"text-error text-xs font-medium",children:[(Ir-dr).toLocaleString()," over limit"]})]})]}),d.jsxs("div",{className:"flex px-3 gap-1",children:[d.jsx("button",{onClick:()=>be("preview"),className:`px-3 py-1 text-xs font-medium border-b-2 transition-colors ${ue==="preview"?"border-accent text-accent":"border-transparent text-muted hover:text-foreground"}`,children:"Preview"}),d.jsxs("button",{onClick:()=>be("edit"),className:`px-3 py-1 text-xs font-medium border-b-2 transition-colors ${ue==="edit"?"border-accent text-accent":"border-transparent text-muted hover:text-foreground"}`,children:["Edit",R&&d.jsx("span",{className:"ml-1 text-amber-600",children:"*"})]})]})]}),ue==="preview"?Ci?d.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",style:{background:"var(--paper-bg)"},children:[d.jsxs("div",{className:"flex gap-1 px-3 py-1 border-b border-border",children:[d.jsx("button",{"data-testid":"cartoon-mode-publish",onClick:()=>re("publish"),className:`px-2 py-0.5 text-[11px] rounded ${L==="publish"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Publish Preview"}),d.jsx("button",{"data-testid":"cartoon-mode-inspect",onClick:()=>re("inspect"),className:`px-2 py-0.5 text-[11px] rounded ${L==="inspect"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Cut Inspector"})]}),d.jsx("div",{className:"flex-1 min-h-0",children:L==="publish"?d.jsx(xD,{content:(A==null?void 0:A.content)??"",stage:ye}):d.jsx(eD,{storyName:e,fileName:t,authFetch:i,onEditCut:T})})]}):d.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-6 py-4",style:{background:"var(--paper-bg)"},children:A!=null&&A.content?d.jsx("div",{className:"prose max-w-none",children:d.jsx(oS,{remarkPlugins:[uS,BS],rehypePlugins:[[PS,vM]],children:A.content})}):d.jsx("p",{className:"text-muted italic",children:"No content"})}):Ci?d.jsx("div",{className:"flex-1 min-h-[22rem] overflow-hidden",style:{background:"var(--paper-bg)"},children:d.jsx(vy,{storyName:e,fileName:t,authFetch:i,language:h,onCutsChanged:()=>ee(se=>se+1),focusRequest:V,onFocusHandled:()=>U(null),onFocusedLetteringModeChange:B,workspaceVisible:N,onWorkspaceVisibleChange:E})}):Ln?d.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",style:{background:"var(--paper-bg)"},children:[d.jsxs("div",{className:"flex gap-1 px-3 py-1 border-b border-border",children:[d.jsx("button",{"data-testid":"genesis-edit-mode-text",onClick:()=>Y("text"),className:`px-2 py-0.5 text-[11px] rounded ${F==="text"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Opening text"}),d.jsx("button",{"data-testid":"genesis-edit-mode-cuts",onClick:()=>Y("cuts"),className:`px-2 py-0.5 text-[11px] rounded ${F==="cuts"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Cuts"})]}),d.jsx("div",{className:"flex-1 min-h-0",children:F==="cuts"?d.jsx(vy,{storyName:e,fileName:t,authFetch:i,language:h,onCutsChanged:()=>ee(se=>se+1),focusRequest:V,onFocusHandled:()=>U(null),onFocusedLetteringModeChange:B,workspaceVisible:N,onWorkspaceVisibleChange:E}):fr})]}):fr,!Xo&&d.jsx("div",{className:"shrink-0 px-3 py-2 border-t border-border flex items-center justify-between bg-surface/95","data-testid":"preview-panel-footer",children:t==="structure.md"?d.jsx("p",{className:"text-muted text-xs italic","data-testid":"footer-guidance",children:Sa}):(A==null?void 0:A.status)==="published-not-indexed"?d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:"text-amber-700",children:"Published on-chain but not indexed on PlotLink"}),!Pr&&d.jsx("button",{onClick:async()=>{if(!(!e||!t||!A.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:A.txHash,content:A.content,storylineId:A.storylineId})})).json()).ok&&(await i(`/api/stories/${e}/${t}/publish-status`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({txHash:A.txHash,storylineId:A.storylineId,contentCid:"",gasCost:""})}),Di())}catch{}K(!1)}},disabled:k,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50",children:k?"Retrying...":`Retry Index${Ws?` (${Ws})`:""}`}),hr&&d.jsx("button",{onClick:()=>{!e||!t||!window.confirm(`This episode is already on-chain — try “Retry Index” first. Retry Publish creates a NEW on-chain transaction and a SECOND, permanent chapter on PlotLink (PlotLink content is immutable). Only do this if the chapter never appeared after indexing. -Create a new on-chain chapter anyway?`)||s==null||s(e,t,K,ge,ze)},disabled:!!a,"data-testid":"retry-publish-btn",className:"px-3 py-1 border border-border text-xs rounded hover:bg-surface disabled:opacity-50",children:a===t?"Publishing...":"Retry Publish"}),A.txHash&&d.jsx("a",{href:`https://basescan.org/tx/${A.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted underline",children:"BaseScan"})]}),d.jsx("p",{className:"text-muted text-xs",children:zr?ur?"Index window expired. Use Retry Publish to create a new on-chain tx.":"Index window expired. Contact support or re-publish manually.":ur?"Try Retry Index first (available for 5 min after publish). If that fails, Retry Publish creates a new on-chain tx.":"Retry Index is available for 5 min after publish."}),A.indexError&&d.jsx("p",{className:"text-error text-xs",children:A.indexError})]}):(A==null?void 0:A.status)==="published"?d.jsxs("div",{className:"flex flex-col gap-2",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:"text-green-700",children:"Published"}),A.storylineId&&d.jsx("a",{href:(()=>{var je;const se=`https://plotlink.xyz/story/${A.storylineId}`;if(!ur)return se;const Ee=A.plotIndex!=null&&A.plotIndex>0?A.plotIndex:parseInt(((je=t==null?void 0:t.match(/^plot-(\d+)\.md$/))==null?void 0:je[1])??"1");return`${se}/${Ee}`})(),target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View on PlotLink"}),A.txHash&&d.jsx("a",{href:`https://basescan.org/tx/${A.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted underline",children:"BaseScan"}),Si&&o&&A.storylineId&&(!A.authorAddress||A.authorAddress.toLowerCase()===o.toLowerCase())&&d.jsx("button",{onClick:()=>Xe(se=>!se),className:"px-2 py-0.5 border border-border text-xs rounded hover:bg-surface",children:$e?"Close Edit":"Edit Story"})]}),$e&&Si&&A.storylineId&&d.jsxs("div",{className:"border border-border rounded p-3 flex flex-col gap-3 bg-surface",children:[d.jsxs("div",{className:"flex flex-col gap-1.5",children:[d.jsx("span",{className:"text-xs font-medium text-foreground",children:"Cover Image"}),Ir(_t),d.jsxs("div",{className:"flex items-start gap-3",children:[Ce&&d.jsxs("div",{className:"relative",children:[d.jsx("img",{src:Ce,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),d.jsx("button",{onClick:()=>{U(null),Ae(null),mi(null),te("unknown"),ri.current&&(ri.current.value="")},className:"absolute -top-1.5 -right-1.5 w-4 h-4 bg-error text-white rounded-full text-xs flex items-center justify-center",children:"x"})]}),d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsx("input",{ref:ri,type:"file",accept:"image/webp,image/jpeg",onChange:yi,className:"text-xs","data-testid":"cover-input"}),d.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB, 600x900px recommended"})]})]})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("select",{value:Gt,onChange:se=>pi(se.target.value),className:"px-2 py-1.5 text-xs border border-border rounded bg-surface text-foreground",children:hl.map(se=>d.jsx("option",{value:se,children:se},se))}),d.jsx("select",{value:Rt,onChange:se=>St(se.target.value),className:"px-2 py-1.5 text-xs border border-border rounded bg-surface text-foreground",children:rs.map(se=>d.jsx("option",{value:se,children:se},se))})]}),d.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[d.jsx("input",{type:"checkbox",checked:Yt,onChange:se=>ot(se.target.checked),className:"rounded border-border"}),"This story contains adult content (18+)"]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{onClick:Vn,disabled:Ne||!Ue,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50",children:Ne?"Saving...":Ue?"Save Changes":"Loading..."}),Vt&&d.jsx("span",{className:"text-green-700 text-xs",children:"Updated!"}),Bt&&d.jsx("span",{className:"text-error text-xs",children:Bt})]})]})]}):d.jsxs("div",{className:"flex flex-col gap-2",children:[wi&&Be&&Be.total>0&&d.jsxs("div",{className:"flex items-center flex-wrap gap-x-3 gap-y-0.5 text-[10px] text-muted","data-testid":"cartoon-status-summary",children:[d.jsxs("span",{children:["Cuts:"," ",d.jsx("span",{className:"text-foreground font-medium",children:Be.total})]}),d.jsxs("span",{children:["Clean:"," ",d.jsxs("span",{className:"text-foreground font-medium",children:[Be.withClean,"/",Be.needClean]})]}),d.jsxs("span",{children:["Lettered:"," ",d.jsxs("span",{className:"text-foreground font-medium",children:[Be.withText,"/",Be.total]})]}),d.jsxs("span",{children:["Uploaded:"," ",d.jsxs("span",{className:"text-foreground font-medium",children:[Be.uploaded,"/",Be.total]})]}),x&&d.jsx("button",{onClick:x,className:"ml-auto text-accent hover:underline","data-testid":"status-view-progress",children:"View progress →"})]}),Ln&&Di&&d.jsxs("div",{className:"text-xs text-muted","data-testid":"genesis-cuts-summary",children:["Episode 1 (Genesis) cuts: ",Di.total," planned",Di.total>0&&d.jsxs(d.Fragment,{children:[" ","· ",Di.withClean," clean ·"," ",Di.withText," lettered ·"," ",Di.exported," exported ·"," ",Di.uploaded," uploaded"]})]}),(Ln||wi)&&Sa&&d.jsxs("div",{className:`${Sl} flex flex-col gap-1 border-border bg-surface/50`,"data-testid":"cartoon-not-started",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"rounded-full bg-background px-2 py-0.5 text-[10px] font-medium uppercase tracking-[0.14em] text-muted",children:vl===0?"Not started":"Next step"}),d.jsx("span",{className:"text-xs font-medium text-foreground",children:Ln?"Genesis (Episode 1)":"Future episode"})]}),d.jsx("span",{className:"text-xs text-muted",children:Sa})]}),ur&&!wi&&ue==="preview"&&d.jsxs("div",{children:[d.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[d.jsx("input",{type:"checkbox",checked:Y,onChange:se=>me(se.target.checked),className:"rounded border-border"}),"Add illustrations in the plot"]}),Y&&d.jsxs("div",{className:"mt-2 flex flex-col gap-2",children:[d.jsxs("div",{className:"border-2 border-dashed border-border rounded p-3 flex flex-col items-center gap-1.5 cursor-pointer hover:border-accent transition-colors",onClick:()=>{var se;return(se=Qe.current)==null?void 0:se.click()},onDragOver:se=>{se.preventDefault(),se.stopPropagation()},onDrop:se=>{var je;se.preventDefault(),se.stopPropagation();const Ee=(je=se.dataTransfer.files)==null?void 0:je[0];Ee&&Or(Ee)},children:[d.jsx("input",{ref:Qe,type:"file",accept:"image/webp,image/jpeg",onChange:Qt,className:"hidden"}),d.jsx("span",{className:"text-xs text-muted",children:_e?"Uploading...":"Drop image here or click to browse"}),d.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB"})]}),Pe&&d.jsx("span",{className:"text-error text-xs",children:Pe}),wt.map((se,Ee)=>d.jsxs("div",{className:"border border-border rounded p-2 flex flex-col gap-1 bg-surface",children:[d.jsx("span",{className:"text-xs text-green-700",children:"Image uploaded! Copy the markdown below and paste it where you want the illustration to appear in your plot:"}),d.jsxs("div",{className:"flex items-center gap-1.5",children:[d.jsxs("code",{className:"flex-1 text-xs bg-background px-2 py-1 rounded font-mono break-all",children:["![Scene description](",se.url,")"]}),d.jsx("button",{onClick:()=>{navigator.clipboard.writeText(`![Scene description](${se.url})`),Ze(Ee),setTimeout(()=>Ze(null),2e3)},className:"px-2 py-1 text-xs border border-border rounded hover:bg-surface shrink-0",children:jt===Ee?"Copied!":"Copy"})]})]},se.cid))]})]}),Si&&c!=="cartoon"&&!(ue==="edit"&&$==="cuts")&&d.jsxs("div",{className:"flex flex-col gap-1.5","data-testid":"prepublish-cover",children:[d.jsxs("span",{className:"text-xs font-medium text-foreground",children:["Cover Image"," ",d.jsx("span",{className:"text-muted font-normal",children:"(optional)"})]}),Ir(!1),d.jsxs("div",{className:"flex items-start gap-3",children:[Ce&&d.jsxs("div",{className:"relative",children:[d.jsx("img",{src:Ce,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),d.jsx("button",{onClick:()=>{ve.current=!0,vn(null),mi(null),te("unknown"),U(null),Ae(se=>(se&&URL.revokeObjectURL(se),null)),ri.current&&(ri.current.value="")},className:"absolute -top-1.5 -right-1.5 w-4 h-4 bg-error text-white rounded-full text-xs flex items-center justify-center",children:"x"})]}),d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsx("input",{ref:ri,type:"file",accept:"image/webp,image/jpeg",onChange:yi,className:"text-xs","data-testid":"prepublish-cover-input"}),d.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB, 600x900px recommended"}),d.jsx("input",{ref:Mn,type:"file",accept:"image/png,image/webp,image/jpeg",onChange:Lr,className:"hidden","data-testid":"prepublish-cover-import-input"}),d.jsx("button",{type:"button",onClick:()=>{var se;return(se=Mn.current)==null?void 0:se.click()},disabled:Bn,className:"self-start px-2 py-1 text-xs border border-border rounded hover:border-accent hover:bg-accent/5 disabled:opacity-50","data-testid":"prepublish-cover-import",children:Bn?"Importing…":"Import generated image (PNG ok)"}),Ht&&d.jsx("span",{className:"text-green-700 text-xs","data-testid":"prepublish-cover-will-upload",children:"This cover will be uploaded as the PlotLink storyline cover when you publish."}),Ii&&d.jsxs("span",{className:"text-accent text-xs","data-testid":"prepublish-cover-detected",children:["Auto-detected generated cover ",Ii," — pick a file to override."]}),_r&&d.jsxs("span",{className:"text-amber-700 text-xs","data-testid":"prepublish-cover-detected-warning",children:[_r," Use “Import generated image” below to convert/compress it, or pick a file."]}),c==="cartoon"&&Zt==="none"&&!Ht&&d.jsxs("span",{className:"text-muted text-xs","data-testid":"prepublish-cover-none",children:["No generated cover detected. Create"," ",d.jsx("span",{className:"font-mono",children:"assets/cover.webp"})," ","or use “Import generated image” — it will be uploaded as the PlotLink storyline cover when you publish."]}),Bt&&d.jsx("span",{className:"text-error text-xs","data-testid":"prepublish-cover-error",children:Bt})]})]})]}),!cs&&wl(),!cs&&Zo(),!cs&&d.jsxs("div",{className:"flex items-center gap-2",children:[Si&&c!=="cartoon"&&d.jsxs(d.Fragment,{children:[d.jsxs("select",{value:K,"data-testid":"publish-genre-select",onChange:se=>{he(se.target.value),se.target.value&&br({genre:se.target.value})},className:`px-2 py-1.5 text-xs border rounded bg-surface text-foreground ${K?"border-border":"border-amber-500"}`,children:[!K&&d.jsx("option",{value:"",disabled:!0,children:"Needs metadata — select genre"}),hl.map(se=>d.jsx("option",{value:se,children:se},se))]}),d.jsxs("select",{value:ge,"data-testid":"publish-language-select",onChange:se=>{De(se.target.value),se.target.value&&br({language:se.target.value})},className:`px-2 py-1.5 text-xs border rounded bg-surface text-foreground ${ge?"border-border":"border-amber-500"}`,children:[!ge&&d.jsx("option",{value:"",disabled:!0,children:"Needs metadata — select language"}),rs.map(se=>d.jsx("option",{value:se,children:se},se))]})]}),d.jsx("button",{onClick:async()=>{if(!e||!t)return;if(vr.count>0){const Ee=`This plot contains ${vr.count} illustration(s). Content is immutable after publishing — image references cannot be changed or removed. +Create a new on-chain chapter anyway?`)||s==null||s(e,t,X,ge,Le)},disabled:!!a,"data-testid":"retry-publish-btn",className:"px-3 py-1 border border-border text-xs rounded hover:bg-surface disabled:opacity-50",children:a===t?"Publishing...":"Retry Publish"}),A.txHash&&d.jsx("a",{href:`https://basescan.org/tx/${A.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted underline",children:"BaseScan"})]}),d.jsx("p",{className:"text-muted text-xs",children:Pr?hr?"Index window expired. Use Retry Publish to create a new on-chain tx.":"Index window expired. Contact support or re-publish manually.":hr?"Try Retry Index first (available for 5 min after publish). If that fails, Retry Publish creates a new on-chain tx.":"Retry Index is available for 5 min after publish."}),A.indexError&&d.jsx("p",{className:"text-error text-xs",children:A.indexError})]}):(A==null?void 0:A.status)==="published"?d.jsxs("div",{className:"flex flex-col gap-2",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:"text-green-700",children:"Published"}),A.storylineId&&d.jsx("a",{href:(()=>{var je;const se=`https://plotlink.xyz/story/${A.storylineId}`;if(!hr)return se;const ke=A.plotIndex!=null&&A.plotIndex>0?A.plotIndex:parseInt(((je=t==null?void 0:t.match(/^plot-(\d+)\.md$/))==null?void 0:je[1])??"1");return`${se}/${ke}`})(),target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View on PlotLink"}),A.txHash&&d.jsx("a",{href:`https://basescan.org/tx/${A.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted underline",children:"BaseScan"}),wi&&o&&A.storylineId&&(!A.authorAddress||A.authorAddress.toLowerCase()===o.toLowerCase())&&d.jsx("button",{onClick:()=>Ze(se=>!se),className:"px-2 py-0.5 border border-border text-xs rounded hover:bg-surface",children:He?"Close Edit":"Edit Story"})]}),He&&wi&&A.storylineId&&d.jsxs("div",{className:"border border-border rounded p-3 flex flex-col gap-3 bg-surface",children:[d.jsxs("div",{className:"flex flex-col gap-1.5",children:[d.jsx("span",{className:"text-xs font-medium text-foreground",children:"Cover Image"}),Hr(xt),d.jsxs("div",{className:"flex items-start gap-3",children:[we&&d.jsxs("div",{className:"relative",children:[d.jsx("img",{src:we,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),d.jsx("button",{onClick:()=>{$(null),Ae(null),gi(null),jt("unknown"),ii.current&&(ii.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:ii,type:"file",accept:"image/webp,image/jpeg",onChange:Si,className:"text-xs","data-testid":"cover-input"}),d.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB, 600x900px recommended"})]})]})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("select",{value:Gt,onChange:se=>mi(se.target.value),className:"px-2 py-1.5 text-xs border border-border rounded bg-surface text-foreground",children:hl.map(se=>d.jsx("option",{value:se,children:se},se))}),d.jsx("select",{value:At,onChange:se=>wt(se.target.value),className:"px-2 py-1.5 text-xs border border-border rounded bg-surface text-foreground",children:ss.map(se=>d.jsx("option",{value:se,children:se},se))})]}),d.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[d.jsx("input",{type:"checkbox",checked:Yt,onChange:se=>ot(se.target.checked),className:"rounded border-border"}),"This story contains adult content (18+)"]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{onClick:Kn,disabled:Ne||!Ie,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50",children:Ne?"Saving...":Ie?"Save Changes":"Loading..."}),li&&d.jsx("span",{className:"text-green-700 text-xs",children:"Updated!"}),Mt&&d.jsx("span",{className:"text-error text-xs",children:Mt})]})]})]}):d.jsxs("div",{className:"flex flex-col gap-2",children:[Ci&&ze&&ze.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:ze.total})]}),d.jsxs("span",{children:["Clean:"," ",d.jsxs("span",{className:"text-foreground font-medium",children:[ze.withClean,"/",ze.needClean]})]}),d.jsxs("span",{children:["Lettered:"," ",d.jsxs("span",{className:"text-foreground font-medium",children:[ze.withText,"/",ze.total]})]}),d.jsxs("span",{children:["Uploaded:"," ",d.jsxs("span",{className:"text-foreground font-medium",children:[ze.uploaded,"/",ze.total]})]}),x&&d.jsx("button",{onClick:x,className:"ml-auto text-accent hover:underline","data-testid":"status-view-progress",children:"View progress →"})]}),Ln&&ri&&d.jsxs("div",{className:"text-xs text-muted","data-testid":"genesis-cuts-summary",children:["Episode 1 (Genesis) cuts: ",ri.total," planned",ri.total>0&&d.jsxs(d.Fragment,{children:[" ","· ",ri.withClean," clean ·"," ",ri.withText," lettered ·"," ",ri.exported," exported ·"," ",ri.uploaded," uploaded"]})]}),(Ln||Ci)&&Sa&&d.jsxs("div",{className:`${Sl} flex flex-col gap-1 border-border bg-surface/50`,"data-testid":"cartoon-not-started",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"rounded-full bg-background px-2 py-0.5 text-[10px] font-medium uppercase tracking-[0.14em] text-muted",children:vl===0?"Not started":"Next step"}),d.jsx("span",{className:"text-xs font-medium text-foreground",children:Ln?"Genesis (Episode 1)":"Future episode"})]}),d.jsx("span",{className:"text-xs text-muted",children:Sa})]}),hr&&!Ci&&ue==="preview"&&d.jsxs("div",{children:[d.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[d.jsx("input",{type:"checkbox",checked:M,onChange:se=>ie(se.target.checked),className:"rounded border-border"}),"Add illustrations in the plot"]}),M&&d.jsxs("div",{className:"mt-2 flex flex-col gap-2",children:[d.jsxs("div",{className:"border-2 border-dashed border-border rounded p-3 flex flex-col items-center gap-1.5 cursor-pointer hover:border-accent transition-colors",onClick:()=>{var se;return(se=Qe.current)==null?void 0:se.click()},onDragOver:se=>{se.preventDefault(),se.stopPropagation()},onDrop:se=>{var je;se.preventDefault(),se.stopPropagation();const ke=(je=se.dataTransfer.files)==null?void 0:je[0];ke&&zr(ke)},children:[d.jsx("input",{ref:Qe,type:"file",accept:"image/webp,image/jpeg",onChange:Xt,className:"hidden"}),d.jsx("span",{className:"text-xs text-muted",children:me?"Uploading...":"Drop image here or click to browse"}),d.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB"})]}),Se&&d.jsx("span",{className:"text-error text-xs",children:Se}),Ve.map((se,ke)=>d.jsxs("div",{className:"border border-border rounded p-2 flex flex-col gap-1 bg-surface",children:[d.jsx("span",{className:"text-xs text-green-700",children:"Image uploaded! Copy the markdown below and paste it where you want the illustration to appear in your plot:"}),d.jsxs("div",{className:"flex items-center gap-1.5",children:[d.jsxs("code",{className:"flex-1 text-xs bg-background px-2 py-1 rounded font-mono break-all",children:["![Scene description](",se.url,")"]}),d.jsx("button",{onClick:()=>{navigator.clipboard.writeText(`![Scene description](${se.url})`),tt(ke),setTimeout(()=>tt(null),2e3)},className:"px-2 py-1 text-xs border border-border rounded hover:bg-surface shrink-0",children:_t===ke?"Copied!":"Copy"})]})]},se.cid))]})]}),wi&&c!=="cartoon"&&!(ue==="edit"&&F==="cuts")&&d.jsxs("div",{className:"flex flex-col gap-1.5","data-testid":"prepublish-cover",children:[d.jsxs("span",{className:"text-xs font-medium text-foreground",children:["Cover Image"," ",d.jsx("span",{className:"text-muted font-normal",children:"(optional)"})]}),Hr(!1),d.jsxs("div",{className:"flex items-start gap-3",children:[we&&d.jsxs("div",{className:"relative",children:[d.jsx("img",{src:we,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),d.jsx("button",{onClick:()=>{ni.current=!0,Xi(null),gi(null),jt("unknown"),$(null),Ae(se=>(se&&URL.revokeObjectURL(se),null)),ii.current&&(ii.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:ii,type:"file",accept:"image/webp,image/jpeg",onChange:Si,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:Sn,type:"file",accept:"image/png,image/webp,image/jpeg",onChange:Or,className:"hidden","data-testid":"prepublish-cover-import-input"}),d.jsx("button",{type:"button",onClick:()=>{var se;return(se=Sn.current)==null?void 0:se.click()},disabled:Vn,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:Vn?"Importing…":"Import generated image (PNG ok)"}),Ht&&d.jsx("span",{className:"text-green-700 text-xs","data-testid":"prepublish-cover-will-upload",children:"This cover will be uploaded as the PlotLink storyline cover when you publish."}),dn&&d.jsxs("span",{className:"text-accent text-xs","data-testid":"prepublish-cover-detected",children:["Auto-detected generated cover ",dn," — pick a file to override."]}),br&&d.jsxs("span",{className:"text-amber-700 text-xs","data-testid":"prepublish-cover-detected-warning",children:[br," Use “Import generated image” below to convert/compress it, or pick a file."]}),c==="cartoon"&&Kt==="none"&&!Ht&&d.jsxs("span",{className:"text-muted text-xs","data-testid":"prepublish-cover-none",children:["No generated cover detected. Create"," ",d.jsx("span",{className:"font-mono",children:"assets/cover.webp"})," ","or use “Import generated image” — it will be uploaded as the PlotLink storyline cover when you publish."]}),Mt&&d.jsx("span",{className:"text-error text-xs","data-testid":"prepublish-cover-error",children:Mt})]})]})]}),!us&&wl(),!us&&Zo(),!us&&d.jsxs("div",{className:"flex items-center gap-2",children:[wi&&c!=="cartoon"&&d.jsxs(d.Fragment,{children:[d.jsxs("select",{value:X,"data-testid":"publish-genre-select",onChange:se=>{he(se.target.value),se.target.value&&vr({genre:se.target.value})},className:`px-2 py-1.5 text-xs border rounded bg-surface text-foreground ${X?"border-border":"border-amber-500"}`,children:[!X&&d.jsx("option",{value:"",disabled:!0,children:"Needs metadata — select genre"}),hl.map(se=>d.jsx("option",{value:se,children:se},se))]}),d.jsxs("select",{value:ge,"data-testid":"publish-language-select",onChange:se=>{Re(se.target.value),se.target.value&&vr({language:se.target.value})},className:`px-2 py-1.5 text-xs border rounded bg-surface text-foreground ${ge?"border-border":"border-amber-500"}`,children:[!ge&&d.jsx("option",{value:"",disabled:!0,children:"Needs metadata — select language"}),ss.map(se=>d.jsx("option",{value:se,children:se},se))]})]}),d.jsx("button",{onClick:async()=>{if(!e||!t)return;if(yr.count>0){const ke=`This plot contains ${yr.count} illustration(s). Content is immutable after publishing — image references cannot be changed or removed. Please verify illustrations appear correctly in Preview before continuing. -Publish now?`;if(!window.confirm(Ee))return}const se=Si?Ht:null;se?await(s==null?void 0:s(e,t,K,ge,ze,se))&&(ve.current=!0,vn(null),mi(null),te("unknown"),U(null),Ae(je=>(je&&URL.revokeObjectURL(je),null)),ri.current&&(ri.current.value="")):s==null||s(e,t,K,ge,ze)},disabled:!!a||Sn||ka||Ca||Si&&(!K||!ge)||wi&&we!=="ready",className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim disabled:opacity-50 disabled:cursor-not-allowed",children:a===t?"Publishing...":"Publish to PlotLink"}),Si&&c==="cartoon"&&(!K||!ge)&&d.jsx("span",{className:"text-amber-600 text-xs","data-testid":"cartoon-metadata-needs-story-info",children:"Set the genre and language in Story Info before publishing"}),Si&&c!=="cartoon"&&!K&&d.jsx("span",{className:"text-amber-600 text-xs","data-testid":"genre-needs-metadata",children:"Needs metadata — choose a genre before publishing"}),Si&&c!=="cartoon"&&K&&!ge&&d.jsx("span",{className:"text-amber-600 text-xs","data-testid":"language-needs-metadata",children:"Needs metadata — choose a language before publishing"}),Sn&&d.jsx("span",{className:"text-error text-xs",children:"Reduce content to publish"}),wi&&we==="error"&&d.jsx("span",{className:"text-error text-xs","data-testid":"publish-disabled-reason",children:"Fix the issues below before publishing"}),wi&&we==="planning"&&d.jsx("span",{className:"text-muted text-xs","data-testid":"publish-disabled-reason",children:"Prepare the episode for publish to continue"}),wi&&we==="awaiting-upload"&&d.jsxs("span",{className:"text-muted text-xs","data-testid":"publish-disabled-reason",children:["Upload all final images, then “Prepare episode for publish” — ",it," of ",nt," ","still need an uploaded image"]})]}),cs&&d.jsx("button",{onClick:()=>v==null?void 0:v(),"data-testid":"cartoon-review-publish",className:"self-start rounded border border-accent/40 px-3 py-1 text-xs text-accent hover:bg-accent/5 transition-colors",children:"Review publish checklist →"}),vr.warnings.length>0&&d.jsx("div",{className:"flex flex-col gap-0.5",children:vr.warnings.map((se,Ee)=>d.jsx("span",{className:"text-amber-600 text-xs",children:se},Ee))}),Si&&c!=="cartoon"&&d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[d.jsx("input",{type:"checkbox",checked:ze,onChange:se=>{Fe(se.target.checked),br({isNsfw:se.target.checked})},className:"rounded border-border"}),"This story contains adult content (18+)"]}),ze&&d.jsx("span",{className:"text-xs text-amber-600",children:"Adult content will be hidden from the default browse view."})]})]})})]})}function CM(e){if(e.cover!=="present")return e.cover==="invalid"?"Replace the cover image - it must be a valid WebP or JPEG.":"Add a cover image before publishing.";const t=[];return e.metadata.language||t.push("language"),e.metadata.genre||t.push("genre"),e.metadata.title||t.push("title"),`Add the story ${t.join(" and ")||"details"} before publishing.`}function s1(e){const t=e.coach??null,i=e.metadata,s=e.setup.hasStructure,a=e.setup.hasGenesis,o=e.cover==="present",c=!i.title||!i.language||!i.genre,h=e.episodes.find(f=>!f.published)??null,p=!!h&&h.state!=="ready";return s?a?c?"story-info":p&&(t!=null&&t.episodeFile)?t.episodeFile:o?(t==null?void 0:t.episodeFile)??null:"story-info":"genesis.md":"whitepaper"}function Hp({badge:e,tone:t="accent",summary:i,children:s,note:a,testId:o}){const c=t==="complete"?"border-green-700/20 bg-green-950/5":"border-accent/30 bg-background/95",h=t==="complete"?"bg-green-700/10 text-green-700":"bg-accent/10 text-accent";return d.jsx("div",{className:`border px-3 py-3 sm:px-4 ${c}`,"data-testid":o,"data-state":t==="complete"?"complete":"active",children:d.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[d.jsxs("div",{className:"min-w-0 flex-1",children:[d.jsx("span",{className:`inline-flex rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.14em] ${h}`,children:e}),d.jsx("p",{className:"mt-1 text-sm text-foreground",children:i}),a?d.jsx("p",{className:"mt-1 text-[11px] font-medium text-accent",children:a}):null]}),s?d.jsx("div",{className:"flex w-full justify-end sm:w-auto sm:flex-shrink-0",children:s}):null]})})}function Up({onClick:e,disabled:t,testId:i}){return d.jsx("button",{type:"button",onClick:e,disabled:t,className:"w-full rounded bg-accent px-4 py-2.5 text-sm font-bold text-white shadow-sm transition-colors hover:bg-accent-dim disabled:cursor-not-allowed disabled:opacity-50 sm:w-auto","data-testid":i,children:"Next Action"})}function a1({coach:e,onAction:t}){const[i,s]=w.useState(null),a=i!==null&&i===(e==null?void 0:e.prompt);if(e===void 0)return null;if(!e)return d.jsx(Hp,{badge:"Complete",tone:"complete",summary:"No next action available.",note:"This workflow has no queued next step right now.",testId:"cartoon-next-action"});const o=e.actionKind==="agent"&&e.prompt?d.jsx(Up,{testId:"workflow-coach-copy",onClick:()=>{var h;if(!e.prompt)return;const c=e.prompt;(h=navigator.clipboard)==null||h.writeText(c).then(()=>s(c)).catch(()=>{})}}):e.actionKind==="ui"&&e.uiAction?d.jsx(Up,{testId:"workflow-coach-do",onClick:()=>t(e.uiAction,e.episodeFile)}):null;return d.jsx(Hp,{badge:e.stageLabel,summary:d.jsxs("span",{"data-testid":"workflow-coach-action",children:[d.jsx("span",{className:"font-semibold",children:"Next: "}),d.jsx("span",{children:e.action})]}),note:a?"Prompt copied.":void 0,testId:"cartoon-next-action",children:o})}function kM({progress:e,onOpenStoryInfo:t}){return d.jsx(Hp,{badge:"Story info",summary:d.jsxs("span",{"data-testid":"story-info-next-action",children:[d.jsx("span",{className:"font-semibold",children:"Next: "}),d.jsx("span",{children:CM(e)})]}),testId:"story-info-cta",children:d.jsx(Up,{testId:"story-info-next-action-btn",onClick:()=>t==null?void 0:t(),disabled:!t})})}function EM({progress:e,onCoachAction:t,onOpenStoryInfo:i}){return s1(e)==="story-info"?d.jsx(kM,{progress:e,onOpenStoryInfo:i}):d.jsx(a1,{coach:e.coach??null,onAction:t})}function NM({storyName:e,authFetch:t,fileName:i,refreshKey:s=0,onCoachAction:a,onOpenStoryInfo:o}){const[c,h]=w.useState(void 0),p=JSON.stringify([e,i??"",s]),[f,_]=w.useState(null);return f!==p&&(h(void 0),_(p)),w.useEffect(()=>{let x=!1;const b=i?`?focus=${encodeURIComponent(i)}`:"";return t(`/api/stories/${e}/progress${b}`).then(v=>v.ok?v.json():null).then(v=>{x||h(jM(v)?v:null)}).catch(()=>{x||h(null)}),()=>{x=!0}},[e,i,t,s]),c===void 0?null:c?d.jsx(EM,{progress:c,onCoachAction:a,onOpenStoryInfo:o}):d.jsx(a1,{coach:null,onAction:a})}function jM(e){return!!e&&!!e.metadata&&!!e.setup&&Array.isArray(e.episodes)}function TM({storyName:e,authFetch:t,onOpenFile:i,refreshKey:s=0}){const[a,o]=w.useState(null),[c,h]=w.useState(!0);return w.useEffect(()=>{let p=!1;return(async()=>{h(!0);try{const _=await t(`/api/stories/${e}/progress`),x=_.ok?await _.json():null;p||(o(x),h(!1))}catch{p||(o(null),h(!1))}})(),()=>{p=!0}},[e,t,s]),c?d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"progress-loading",children:"Loading progress…"}):!a||!a.metadata||!Array.isArray(a.episodes)?d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load story progress."}):a.contentType==="cartoon"?d.jsx(OM,{progress:a,storyName:e,onOpenFile:i}):d.jsx(IM,{progress:a,storyName:e,onOpenFile:i})}function mu({label:e,value:t,tone:i="muted"}){const s=i==="ok"?"text-green-700":i==="warn"?"text-amber-700":"text-muted";return d.jsxs("span",{className:"text-[11px]",children:[d.jsxs("span",{className:"text-muted",children:[e,": "]}),d.jsx("span",{className:`font-medium ${s}`,children:t})]})}function l1({progress:e}){const t=e.contentType==="cartoon",i=e.cover==="present"?"ok":e.cover==="invalid"?"warn":"muted";return d.jsxs("div",{className:"px-4 py-3 border-b border-border",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("h2",{className:"text-base font-serif text-foreground truncate",children:e.metadata.title||e.name}),d.jsx("span",{className:`rounded px-1.5 py-0.5 text-[10px] font-medium ${t?"bg-accent/10 text-accent":"bg-surface text-muted"}`,children:t?"Cartoon":"Fiction"})]}),d.jsxs("div",{className:"mt-1.5 flex flex-wrap gap-x-3 gap-y-1",children:[d.jsx(mu,{label:"Language",value:e.metadata.language||"Needs metadata",tone:e.metadata.language?"muted":"warn"}),d.jsx(mu,{label:"Genre",value:e.metadata.genre||"Needs metadata",tone:e.metadata.genre?"muted":"warn"}),e.metadata.isNsfw!=null&&d.jsx(mu,{label:"Adult",value:e.metadata.isNsfw?"Yes (18+)":"No"}),t&&d.jsx(mu,{label:"Cover",value:e.cover==="present"?"Ready":e.cover==="invalid"?"Invalid":"Missing",tone:i})]})]})}const o1={published:"✓",done:"●",current:"◉","needs-action":"●","not-started":"○"},zu={published:"text-green-700",done:"text-green-700",current:"text-accent","needs-action":"text-amber-700","not-started":"text-muted"},c1={published:"Published",done:"Complete",current:"Current","needs-action":"Needs action","not-started":"Not started"},AM={done:"✓",current:"◓",todo:"○"},RM={done:"text-green-700",current:"text-accent",todo:"text-muted"};function u1({item:e}){return d.jsxs("div",{className:"flex items-baseline gap-2 text-[11px]","data-testid":"checklist-item","data-status":e.status,children:[d.jsx("span",{className:`${RM[e.status]} flex-shrink-0`,"aria-hidden":!0,children:AM[e.status]}),d.jsx("span",{className:e.status==="todo"?"text-muted":"text-foreground",children:e.label}),e.detail&&d.jsxs("span",{className:"text-muted",children:["· ",e.detail]})]})}function Cy({index:e,title:t,status:i,items:s,fileName:a,openFile:o}){const c=d.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[d.jsx("span",{className:`flex-shrink-0 ${zu[i]}`,"aria-hidden":!0,children:o1[i]}),d.jsxs("span",{className:"text-xs font-medium text-foreground truncate",children:[e,". ",t]}),a&&d.jsx("span",{className:"text-[10px] text-muted truncate",children:a}),d.jsx("span",{className:`ml-auto text-[10px] font-medium ${zu[i]} flex-shrink-0`,children:c1[i]})]});return d.jsxs("div",{className:"px-4 py-2.5 border-b border-border","data-testid":`workflow-section-${e}`,"data-status":i,children:[o?d.jsx("button",{onClick:o,className:"w-full text-left rounded hover:bg-surface -mx-1 px-1 py-0.5","data-testid":`section-open-${e}`,children:c}):c,d.jsx("div",{className:"mt-1.5 ml-1 flex flex-col gap-1 border-l border-border pl-3",children:s.map((h,p)=>d.jsx(u1,{item:h},p))})]})}function DM(e,t){return e.published?"published":t?"current":e.state==="placeholder"?"not-started":(e.state==="blocked","needs-action")}function MM(e,t=!0){const i=e.checklist??[],s=[];if(e.kind==="genesis"&&s.push({label:"Opening text",status:t?"done":"todo"}),i.length===0)return s.push({label:"Cut plan",status:"todo"}),s.push({label:"Clean artwork",status:"todo"}),s;for(const a of i)s.push(BM(a));return s}function BM(e){return{label:e.label,status:e.status,detail:e.detail}}const LM={file:"genesis.md",label:"Episode 1 / Genesis",kind:"genesis",title:null,state:"placeholder",summary:"",published:!1,checklist:[],cuts:null};function OM({progress:e,storyName:t,onOpenFile:i}){const s=e.metadata,a=e.setup.hasStructure,o=e.cover==="present",h=!s.title||!s.language||!s.genre||!o,p=s1(e),f=[{label:"Public title",status:s.title?"done":"todo",detail:s.title??null},{label:"Language",status:s.language?"done":"todo",detail:s.language??null},{label:"Genre",status:s.genre?"done":"todo",detail:s.genre??null},{label:"Cover image",status:o?"done":"todo",detail:e.cover==="invalid"?"Invalid — re-import":o?null:"Missing"}],_=p==="story-info"?"current":h?"needs-action":"done",x=a?"done":p==="whitepaper"?"current":"not-started",b=e.episodes.find(N=>N.kind==="genesis")??null,v=e.episodes.filter(N=>N.kind==="plot");let S=0;return d.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"story-progress-panel",children:[d.jsx(l1,{progress:e}),d.jsx("p",{className:"px-4 pt-3 pb-1 text-[11px] font-medium text-muted uppercase tracking-wider",children:"Production Progress"}),d.jsx(Cy,{index:++S,title:"Define Story Info",status:_,items:f}),d.jsx(Cy,{index:++S,title:"Story Whitepaper",status:x,fileName:"structure.md",openFile:a?()=>i(t,"structure.md"):void 0,items:[{label:"Planning document",status:a?"done":"todo",detail:a?null:"Not written yet"}]}),b?d.jsx(Pf,{index:++S,ep:b,isActive:p===b.file,storyName:t,onOpenFile:i}):d.jsx(Pf,{index:++S,ep:LM,isActive:p==="genesis.md",openingDone:!1,canOpen:!1,storyName:t,onOpenFile:i}),v.map(N=>d.jsx(Pf,{index:++S,ep:N,isActive:p===N.file,storyName:t,onOpenFile:i},N.file)),d.jsxs("div",{className:"px-4 py-2 text-[11px] text-muted flex flex-wrap gap-x-3","data-testid":"progress-summary",children:[d.jsxs("span",{children:[e.summary.published," published"]}),d.jsxs("span",{children:[e.summary.readyToPublish," ready"]}),e.summary.placeholders>0&&d.jsxs("span",{children:[e.summary.placeholders," not started"]}),e.summary.blocked>0&&d.jsxs("span",{className:"text-error",children:[e.summary.blocked," need fixes"]})]})]})}function Pf({index:e,ep:t,isActive:i,storyName:s,onOpenFile:a,openingDone:o=!0,canOpen:c=!0}){const h=DM(t,i),p=MM(t,o),f=t.title?`${t.label} · ${t.title}`:t.label,_=d.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[d.jsx("span",{className:`flex-shrink-0 ${zu[h]}`,"aria-hidden":!0,children:o1[h]}),d.jsxs("span",{className:"text-xs font-medium text-foreground truncate",children:[e,". ",f]}),d.jsx("span",{className:"text-[10px] text-muted truncate",children:t.file}),d.jsx("span",{className:`ml-auto text-[10px] font-medium ${zu[h]} flex-shrink-0`,children:c1[h]})]});return d.jsxs("div",{className:"px-4 py-2.5 border-b border-border","data-testid":`workflow-section-${e}`,"data-status":h,children:[c?d.jsx("button",{onClick:()=>a(s,t.file),"data-testid":`progress-episode-${t.file}`,"data-state":t.state,className:"w-full text-left rounded hover:bg-surface -mx-1 px-1 py-0.5",children:_}):d.jsx("div",{"data-state":t.state,children:_}),d.jsx("div",{className:"mt-1.5 ml-1 flex flex-col gap-1 border-l border-border pl-3",children:p.map((x,b)=>d.jsx(u1,{item:x},b))})]})}const zM={published:"✓",ready:"●","in-progress":"◐",planning:"○",placeholder:"○",blocked:"✕",draft:"○"},ky={published:"text-green-700",ready:"text-green-700","in-progress":"text-accent",planning:"text-accent",placeholder:"text-muted",blocked:"text-error",draft:"text-muted"},PM={published:"Published",ready:"Ready","in-progress":"In progress",planning:"Planning",placeholder:"Not started",blocked:"Needs fixes",draft:"Draft"};function IM({progress:e,storyName:t,onOpenFile:i}){const[s,a]=w.useState(!1);return d.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"story-progress-panel",children:[d.jsx(l1,{progress:e}),e.nextAction&&d.jsxs("div",{className:"px-4 py-2 border-b border-accent/30 bg-accent/5 text-xs space-y-1.5","data-testid":"progress-next-action",children:[d.jsxs("div",{children:[d.jsx("span",{className:"font-medium text-foreground",children:"Next: "}),d.jsx("span",{className:"text-muted",children:e.nextAction})]}),e.nextPrompt&&d.jsxs("div",{className:"flex items-start gap-1.5","data-testid":"progress-next-prompt",children:[d.jsx("code",{className:"flex-1 rounded border border-border bg-surface px-1.5 py-1 text-[10px] text-foreground break-words",children:e.nextPrompt}),d.jsx("button",{onClick:()=>{var o;e.nextPrompt&&((o=navigator.clipboard)==null||o.writeText(e.nextPrompt).then(()=>{a(!0)}).catch(()=>{}))},"data-testid":"copy-next-prompt",className:"rounded border border-border px-2 py-1 text-[10px] text-muted hover:border-accent hover:text-accent transition-colors flex-shrink-0",children:s?"Copied!":"Copy"})]})]}),d.jsxs("div",{className:"px-4 py-2 border-b border-border flex flex-col gap-1",children:[d.jsx(Ey,{done:e.setup.hasStructure,label:"Story bible (structure.md)",onClick:e.setup.hasStructure?()=>i(t,"structure.md"):void 0}),d.jsx(Ey,{done:e.setup.hasGenesis,label:"Genesis written",onClick:e.setup.hasGenesis?()=>i(t,"genesis.md"):void 0})]}),d.jsxs("div",{className:"px-4 py-2",children:[d.jsx("p",{className:"text-[11px] font-medium text-muted uppercase tracking-wider mb-1.5",children:"Chapters"}),e.episodes.length===0?d.jsx("p",{className:"text-xs text-muted italic","data-testid":"progress-no-episodes",children:"No chapters yet — write the Genesis to start."}):d.jsx("ol",{className:"flex flex-col gap-1",children:e.episodes.map(o=>d.jsx("li",{children:d.jsxs("button",{onClick:()=>i(t,o.file),"data-testid":`progress-episode-${o.file}`,"data-state":o.state,className:"w-full text-left flex items-start gap-2 rounded px-2 py-1.5 hover:bg-surface",children:[d.jsx("span",{className:`mt-0.5 ${ky[o.state]}`,"aria-hidden":!0,children:zM[o.state]}),d.jsxs("span",{className:"min-w-0 flex-1",children:[d.jsxs("span",{className:"flex items-center gap-1.5",children:[d.jsx("span",{className:"text-xs font-medium text-foreground",children:o.label}),o.title&&d.jsxs("span",{className:"text-[11px] text-muted truncate",children:["· ",o.title]}),d.jsx("span",{className:`ml-auto text-[10px] font-medium ${ky[o.state]}`,children:PM[o.state]})]}),d.jsx("span",{className:"block text-[11px] text-muted",children:o.summary})]})]})},o.file))})]}),d.jsxs("div",{className:"px-4 py-2 border-t border-border text-[11px] text-muted flex flex-wrap gap-x-3","data-testid":"progress-summary",children:[d.jsxs("span",{children:[e.summary.published," published"]}),e.summary.blocked>0&&d.jsxs("span",{className:"text-error",children:[e.summary.blocked," need fixes"]})]})]})}function Ey({done:e,label:t,onClick:i}){const s=d.jsxs("span",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:e?"text-green-700":"text-muted","aria-hidden":!0,children:e?"✓":"○"}),d.jsx("span",{className:e?"text-foreground":"text-muted",children:t})]});return i?d.jsx("button",{onClick:i,className:"text-left hover:underline",children:s}):d.jsx("div",{children:s})}const HM=[{key:"progress",label:"Progress"},{key:"story-info",label:"Story Info"},{key:"whitepaper",label:"Whitepaper"},{key:"genesis",label:"Genesis / Ep 1"},{key:"episodes",label:"Episodes"},{key:"publish",label:"Publish"}];function UM({storyTitle:e,active:t,onSelect:i}){return d.jsxs("div",{className:"flex-shrink-0 border-b border-border bg-surface/40","data-testid":"cartoon-workflow-nav",children:[d.jsxs("div",{className:"flex items-center gap-2 px-3 pt-2",children:[d.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.14em] text-accent",children:"Cartoon"}),d.jsx("span",{className:"text-xs font-serif text-foreground truncate",children:e})]}),d.jsx("div",{className:"flex items-center gap-1 px-2 py-1.5 overflow-x-auto",role:"tablist",children:HM.map(s=>{const a=s.key===t;return d.jsx("button",{role:"tab","aria-selected":a,"data-testid":`nav-tab-${s.key}`,"data-active":a,onClick:()=>i(s.key),className:`flex-shrink-0 rounded-full px-2.5 py-1 text-[11px] font-medium transition-colors ${a?"bg-accent text-white":"text-muted hover:text-foreground hover:bg-surface"}`,children:s.label},s.key)})})]})}function $M({storyName:e,authFetch:t,onSaved:i}){const[s,a]=w.useState(!0),[o,c]=w.useState(!1),[h,p]=w.useState(""),[f,_]=w.useState(""),[x,b]=w.useState(""),[v,S]=w.useState(""),[N,M]=w.useState(!1),[E,L]=w.useState("cartoon"),[I,A]=w.useState("unknown"),[q,R]=w.useState(!1),[ne,ue]=w.useState(!1),[ye,B]=w.useState(null),[re,$]=w.useState(!1),[G,V]=w.useState(null),[H,T]=w.useState(!1),z=w.useRef(null);w.useEffect(()=>{let C=!1;return a(!0),c(!1),ue(!1),B(null),(async()=>{try{const[Z,ae]=await Promise.all([t(`/api/stories/${e}`),t(`/api/stories/${e}/progress`)]);if(!Z.ok){C||(c(!0),a(!1));return}const oe=await Z.json(),K=ae.ok?await ae.json().catch(()=>null):null;if(C)return;p(oe.title??""),_(oe.description??""),b(Cu(oe.genre)??""),S(oe.language&&rs.find(he=>he.toLowerCase()===oe.language.toLowerCase())||""),M(!!oe.isNsfw),L(oe.contentType==="fiction"?"fiction":"cartoon"),A((K==null?void 0:K.cover)??"unknown"),a(!1)}catch{C||(c(!0),a(!1))}})(),()=>{C=!0}},[e,t]);const F=w.useCallback(async()=>{R(!0),ue(!1),B(null);const C={title:h.trim(),description:f.trim(),genre:x,language:v,isNsfw:N};try{const Z=await t(`/api/stories/${e}/publish-metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(C)});if(Z.ok)ue(!0),i==null||i({genre:x,language:v,isNsfw:N});else{const ae=await Z.json().catch(()=>({}));B(ae.error||"Could not save story info.")}}catch{B("Could not save story info.")}R(!1)},[e,t,h,f,x,v,N,i]),xe=w.useCallback(async C=>{var ae;const Z=(ae=C.target.files)==null?void 0:ae[0];if(z.current&&(z.current.value=""),!!Z){$(!0),B(null);try{let oe;try{oe=await Ku(Z)}catch(ze){B(ze instanceof Error?ze.message:"Could not import image");return}const K=oe.type==="image/jpeg"?"jpg":"webp",he=new File([oe],`cover.${K}`,{type:oe.type}),ge=new FormData;ge.append("file",he);const De=await t(`/api/stories/${e}/import-cover`,{method:"POST",body:ge});if(!De.ok){const ze=await De.json().catch(()=>({}));B(ze.error||"Cover import failed.");return}A("present"),V(ze=>(ze&&URL.revokeObjectURL(ze),URL.createObjectURL(he)))}catch{B("Cover import failed.")}finally{$(!1)}}},[e,t]),j=w.useCallback(()=>{var Z;const C=`Generate a cover image for this story (${h||e}) and save it as assets/cover.webp — portrait 600x900, WebP, under 1MB. Don't publish.`;(Z=navigator.clipboard)==null||Z.writeText(C).then(()=>{T(!0)}).catch(()=>{})},[h,e]);if(s)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"story-info-loading",children:"Loading story info…"});if(o)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load story info."});const D=I==="present"?"Cover set":I==="invalid"?"Invalid cover — re-import a WebP/JPEG under 1MB":"Missing cover",X=I==="present"?"text-green-700":I==="invalid"?"text-amber-700":"text-muted";return d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"story-info-page",children:[d.jsx("h2",{className:"text-base font-serif text-foreground",children:"Story Info"}),d.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"These details appear on PlotLink when the story is published."}),d.jsxs("div",{className:"mt-4 flex flex-col gap-4 max-w-xl",children:[d.jsxs("label",{className:"flex flex-col gap-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Public title"}),d.jsx("input",{type:"text",value:h,onChange:C=>{p(C.target.value),ue(!1)},"data-testid":"story-info-title",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none"})]}),d.jsxs("label",{className:"flex flex-col gap-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Short description"}),d.jsx("textarea",{value:f,onChange:C=>{_(C.target.value),ue(!1)},rows:3,"data-testid":"story-info-description",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none resize-y"})]}),d.jsxs("div",{className:"flex flex-wrap gap-4",children:[d.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Genre"}),d.jsxs("select",{value:x,onChange:C=>{b(C.target.value),ue(!1)},"data-testid":"story-info-genre",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none",children:[d.jsx("option",{value:"",children:"Needs metadata"}),hl.map(C=>d.jsx("option",{value:C,children:C},C))]})]}),d.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Language"}),d.jsxs("select",{value:v,onChange:C=>{S(C.target.value),ue(!1)},"data-testid":"story-info-language",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none",children:[d.jsx("option",{value:"",children:"Needs metadata"}),rs.map(C=>d.jsx("option",{value:C,children:C},C))]})]}),d.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Content type"}),d.jsx("span",{className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-surface text-muted","data-testid":"story-info-content-type",title:"Content type is locked after creation.",children:E==="cartoon"?"Cartoon · locked":"Fiction · locked"})]})]}),d.jsxs("div",{className:"flex flex-col gap-1.5",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Cover image"}),d.jsxs("div",{className:"flex items-start gap-3",children:[G&&d.jsx("img",{src:G,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),d.jsxs("div",{className:"flex flex-col gap-1.5",children:[d.jsx("span",{className:`text-[11px] font-medium ${X}`,"data-testid":"story-info-cover-status",children:D}),d.jsx("span",{className:"text-[10px] text-muted",children:"WebP or JPEG, max 1MB, 600×900 recommended."}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{type:"button",onClick:()=>{var C;return(C=z.current)==null?void 0:C.click()},disabled:re,"data-testid":"story-info-import-cover",className:"rounded border border-border px-2.5 py-1 text-[11px] text-foreground hover:border-accent hover:text-accent transition-colors disabled:opacity-50",children:re?"Importing…":"Import cover"}),d.jsx("button",{type:"button",onClick:j,"data-testid":"story-info-cover-prompt",className:"rounded border border-border px-2.5 py-1 text-[11px] text-muted hover:border-accent hover:text-accent transition-colors",children:H?"Copied!":"Ask agent for cover prompt"})]}),d.jsx("input",{ref:z,type:"file",accept:"image/*",onChange:xe,className:"hidden"})]})]})]}),d.jsxs("label",{className:"flex items-center gap-2",children:[d.jsx("input",{type:"checkbox",checked:N,onChange:C=>{M(C.target.checked),ue(!1)},"data-testid":"story-info-nsfw"}),d.jsx("span",{className:"text-xs text-foreground",children:"This story contains adult content (18+)"})]}),d.jsxs("div",{className:"flex items-center gap-3",children:[d.jsx("button",{type:"button",onClick:F,disabled:q,"data-testid":"story-info-save",className:"rounded bg-accent px-3 py-1.5 text-xs font-medium text-white hover:bg-accent-dim transition-colors disabled:opacity-50",children:q?"Saving…":"Save Story Info"}),ne&&d.jsx("span",{className:"text-[11px] text-green-700","data-testid":"story-info-saved",children:"Saved"}),ye&&d.jsx("span",{className:"text-[11px] text-error","data-testid":"story-info-error",children:ye})]})]})]})}function FM({storyName:e,authFetch:t,onOpenFile:i}){const[s,a]=w.useState(null),[o,c]=w.useState(!0);return w.useEffect(()=>{let h=!1;return(async()=>{c(!0);try{const f=await t(`/api/stories/${e}/progress`),_=f.ok?await f.json():null;h||(a(Array.isArray(_==null?void 0:_.episodes)?_.episodes:null),c(!1))}catch{h||(a(null),c(!1))}})(),()=>{h=!0}},[e,t]),o?d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"episodes-loading",children:"Loading episodes…"}):s?d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"episodes-page",children:[d.jsx("h2",{className:"text-base font-serif text-foreground",children:"Episodes"}),d.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"Genesis is Episode 1; each plot file is the next episode."}),s.length===0?d.jsx("p",{className:"mt-4 text-xs text-muted italic","data-testid":"episodes-empty",children:"No episodes yet — write the Genesis to start Episode 1."}):d.jsx("ol",{className:"mt-3 flex flex-col gap-1",children:s.map(h=>d.jsx("li",{children:d.jsx("button",{onClick:()=>i(e,h.file),"data-testid":`episodes-row-${h.file}`,"data-state":h.state,className:"w-full text-left flex items-start gap-2 rounded px-2 py-1.5 hover:bg-surface",children:d.jsxs("span",{className:"min-w-0 flex-1",children:[d.jsxs("span",{className:"flex items-center gap-1.5",children:[d.jsx("span",{className:"text-xs font-medium text-foreground",children:h.label}),h.title&&d.jsxs("span",{className:"text-[11px] text-muted truncate",children:["· ",h.title]}),d.jsx("span",{className:"ml-auto text-[10px] text-muted",children:h.file})]}),d.jsx("span",{className:"block text-[11px] text-muted",children:h.summary})]})})},h.file))})]}):d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load episodes."})}function qM({storyName:e,authFetch:t,onOpenFile:i,onOpenStoryInfo:s,onPublish:a,publishingFile:o,genre:c,language:h,isNsfw:p,refreshKey:f=0}){var nt,Nt;const[_,x]=w.useState(null),[b,v]=w.useState(!0),[S,N]=w.useState(!1),[M,E]=w.useState(null),[L,I]=w.useState(null),[A,q]=w.useState(null),[R,ne]=w.useState(null),[ue,ye]=w.useState(null),B=async()=>{try{const Be=await t(`/api/stories/${e}/cover-asset`),ct=Be.ok?await Be.json():null;if(!(ct!=null&&ct.found)||!ct.valid||!ct.path)return null;const Te=await t(`/api/stories/${e}/asset/${String(ct.path).replace(/^assets\//,"")}`);if(!Te.ok)return null;const Wt=await Te.blob();return new File([Wt],String(ct.path).split("/").pop()||"cover.webp",{type:ct.type||Wt.type})}catch{return null}};w.useEffect(()=>{let Be=!1;return(async()=>{v(!0),N(!1);try{const Te=await t(`/api/stories/${e}/progress`),Wt=Te.ok?await Te.json():null;if(Be)return;!Wt||!Array.isArray(Wt.episodes)?(N(!0),x(null)):x(Wt),v(!1)}catch{Be||(N(!0),x(null),v(!1))}})(),()=>{Be=!0}},[e,t,f]);const re=((Nt=(nt=_==null?void 0:_.episodes)==null?void 0:nt.find(Be=>!Be.published))==null?void 0:Nt.file)??null,$=re==="genesis.md",G=JSON.stringify([re??"",f]),[V,H]=w.useState(null);if(V!==G&&(H(G),I(null),q(null),ne(null),ye(null)),w.useEffect(()=>{if(!re)return;let Be=!1;const ct=re.replace(/\.md$/,"");return(async()=>{var Te;try{const Wt=[t(`/api/stories/${e}/${re}`),t(`/api/stories/${e}/cuts/${ct}`)];$&&Wt.push(t(`/api/stories/${e}/structure.md`));const[vi,Ct,et]=await Promise.all(Wt);if(Be)return;if(I(vi.ok?(await vi.json()).content??"":""),Ct.ok){const ee=await Ct.json();if(Be)return;q(Array.isArray(ee.cuts)?ee.cuts:[]),ne(typeof ee.title=="string"?ee.title:null)}else q(null),ne(null);ye($&&et&&et.ok?((Te=await et.json())==null?void 0:Te.content)??null:null)}catch{Be||(I(""),q(null),ne(null),ye(null))}})(),()=>{Be=!0}},[re,$,e,t,f]),b)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"publish-page-loading",children:"Loading publish readiness…"});if(S||!_)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load publish readiness."});const T=_.episodes.find(Be=>!Be.published);if(!T)return d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"cartoon-publish-page",children:[d.jsx("h2",{className:"text-base font-serif text-foreground",children:"Publish"}),d.jsx("p",{className:"mt-2 text-xs text-green-700","data-testid":"publish-all-done",children:_.episodes.length>0?"All episodes are published to PlotLink. Plan the next episode to continue.":"No episodes yet — write the Genesis (Episode 1) to begin."})]});const z=T.cuts,F=_.cover==="present",xe=[{label:"Opening text ready",status:"done"},{label:"Cut plan",status:z&&z.total>0?"done":"todo",detail:z?`${z.total} cut${z.total===1?"":"s"} planned`:"not started"},{label:"Clean images converted",status:z&&z.needClean>0&&z.withClean===z.needClean?"done":"todo",detail:z?`${z.withClean} / ${z.needClean}`:null},{label:"Cuts lettered",status:z&&z.total>0&&z.withText===z.total?"done":"todo",detail:z?`${z.withText} / ${z.total}`:null},{label:"Final images exported",status:z&&z.total>0&&z.exported===z.total?"done":"todo",detail:z?`${z.exported} / ${z.total}`:null},{label:"Final images uploaded",status:z&&z.total>0&&z.uploaded===z.total?"done":"todo",detail:z?`${z.uploaded} / ${z.total}`:null},{label:"Cover image",status:F?"done":"todo",detail:F?null:"recommended before publishing"},{label:"Publish to PlotLink",status:T.published?"done":"todo"}],j=T.state==="ready",D=T.state==="blocked",X=T.file==="genesis.md",C=!X||!!c&&!!h,Z=!!o&&o===T.file,ae=L!==null,oe=ae?Nm({fileName:T.file,fileContent:L??"",storySlug:e,structureContent:ue,contentType:"cartoon",episodeTitle:R}):null,K=!!oe&&Uo(oe,T.file),he=!X&&ae&&!Em({fileContent:L??"",episodeTitle:R}),ge=K||he,De=X&&ae?wm(L??""):null,ze=!!De&&De.blockers.length>0,Fe=!X&&ae&&A!==null?XS(L??"",A):null,we=Fe&&Fe.stage==="error"?Fe.issues:[],it=j&&C&&(ae&&(X||A!==null))&&!ge&&!ze&&!Z&&!!a,st=async()=>{if(!(!it||!a)){E(null);try{const Be=X?await B():null;await a(e,T.file,c??"",h??"",!!p,Be)}catch{E("Publish could not be started. Please try again.")}}};return d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"cartoon-publish-page",children:[d.jsxs("h2",{className:"text-base font-serif text-foreground",children:["Publish ",T.label]}),d.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"Finalize this episode: convert, letter, export, upload, then publish to PlotLink."}),d.jsx("ul",{className:"mt-3 flex flex-col gap-1.5 max-w-xl","data-testid":"publish-checklist",children:xe.map((Be,ct)=>d.jsxs("li",{className:"flex items-baseline gap-2 text-xs","data-testid":"publish-check","data-status":Be.status,children:[d.jsx("span",{className:`flex-shrink-0 ${Be.status==="done"?"text-green-700":"text-muted"}`,"aria-hidden":!0,children:Be.status==="done"?"✓":"○"}),d.jsx("span",{className:Be.status==="done"?"text-foreground":"text-muted",children:Be.label}),Be.detail&&d.jsxs("span",{className:"text-muted",children:["· ",Be.detail]})]},ct))}),oe&&d.jsxs("div",{className:"mt-4 flex flex-col gap-0.5 max-w-xl","data-testid":"publish-title-preview","data-raw":K?"true":"false","data-blocked":ge?"true":"false",children:[d.jsxs("span",{className:"text-[11px] text-foreground",children:[d.jsxs("span",{className:"font-medium",children:[X?"Story title":"Episode title",":"]})," ",d.jsx("span",{className:ge?"text-error font-medium":"text-foreground",children:oe})]}),K?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-raw-error",children:["This would publish as a raw filename. ",X?"Add a real “# Title” heading to genesis.md":"Set a title in the cut plan (or add a “# Title” to the episode)"," before publishing."]}):he?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-episode-required",children:["“",oe,"” is a generic placeholder, not a reader-facing title, so it can’t be published. Set a real episode title in the cut plan (or add a “# Title” to the episode) — e.g. “Episode 01 — The Couple Coupon” — before publishing."]}):null]}),De&&d.jsxs("div",{className:"mt-4 flex flex-col gap-1 rounded border border-border bg-surface/50 p-2 max-w-xl","data-testid":"cartoon-genesis-readiness","data-blocked":ze?"true":"false",children:[d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Story opening (Prologue)"}),d.jsx("span",{className:"text-[10px] text-muted","data-testid":"genesis-readiness-hint",children:"Genesis is the first thing readers see. Write it as the story opening/prologue, not a synopsis — set up the premise and stakes, then bridge into Episode 01."}),De.blockers.map((Be,ct)=>d.jsx("span",{className:"text-[10px] text-error","data-testid":"genesis-readiness-blocker",children:Be},`b-${ct}`)),De.warnings.map((Be,ct)=>d.jsx("span",{className:"text-[10px] text-amber-600","data-testid":"genesis-readiness-warning",children:Be},`w-${ct}`))]}),we.length>0&&d.jsxs("div",{className:"mt-4 flex flex-col gap-2 rounded-xl border border-error/30 bg-error/5 px-3 py-3 max-w-xl","data-testid":"cartoon-publish-issues",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"rounded-full bg-error px-2 py-0.5 text-[10px] font-medium uppercase tracking-[0.14em] text-white",children:"Before publish"}),d.jsx("span",{className:"text-xs font-medium text-foreground",children:"Finish these workflow steps"})]}),ZS(we).map(Be=>d.jsx("div",{className:"rounded-lg border border-error/15 bg-background/70 px-2.5 py-2","data-testid":`cartoon-issue-group-${Be.key}`,children:d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:Be.title})},Be.key)),d.jsxs("details",{className:"text-[10px] text-muted","data-testid":"cartoon-technical-details",children:[d.jsx("summary",{className:"cursor-pointer select-none",children:"Technical details"}),d.jsx("ul",{className:"mt-1 ml-3 list-disc",children:we.map((Be,ct)=>d.jsx("li",{className:"font-mono break-words",children:Be},ct))})]})]}),d.jsxs("div",{className:"mt-4 flex flex-col gap-2 max-w-xl",children:[!F&&d.jsx("button",{onClick:s,"data-testid":"publish-add-cover",className:"self-start rounded border border-border px-3 py-1.5 text-xs text-foreground hover:border-accent hover:text-accent transition-colors",children:"Add a cover image (Story Info)"}),X&&!C&&d.jsx("button",{onClick:s,"data-testid":"publish-set-metadata",className:"self-start rounded border border-border px-3 py-1.5 text-xs text-foreground hover:border-accent hover:text-accent transition-colors",children:"Set genre & language (Story Info)"}),!j&&d.jsxs("button",{onClick:()=>i(e,T.file),"data-testid":"publish-open-episode",className:"self-start rounded border border-accent/40 px-3 py-1.5 text-xs text-accent hover:bg-accent/5 transition-colors",children:["Open ",T.label," to finish ",D?"and fix issues":"(letter / export / upload)"]}),d.jsx("button",{onClick:st,disabled:!it,"data-testid":"publish-cta",className:"self-start rounded bg-accent px-3 py-1.5 text-xs font-medium text-white hover:bg-accent-dim disabled:opacity-50 transition-colors",title:it?void 0:"Finish the remaining steps above first",children:Z?"Publishing…":`Publish ${T.label} to PlotLink`}),j?C?ge||ze?d.jsx("p",{className:"text-[11px] text-error","data-testid":"publish-title-blocked-reason",children:ze?"Fix the Story opening issues above before publishing.":"Set a real reader-facing title above before publishing."}):null:d.jsx("p",{className:"text-[11px] text-amber-700","data-testid":"publish-needs-metadata",children:"Set the genre and language in Story Info before publishing."}):d.jsx("p",{className:"text-[11px] text-muted","data-testid":"publish-blocked-reason",children:D?`Not publishable yet — ${T.summary.toLowerCase()}. Open the episode to fix the flagged cuts.`:`Not ready yet — ${T.summary.toLowerCase()}.`}),M&&d.jsx("p",{className:"text-[11px] text-error","data-testid":"publish-error",children:M})]}),d.jsxs("details",{className:"mt-4 max-w-xl","data-testid":"publish-technical-details",children:[d.jsx("summary",{className:"text-[11px] text-muted cursor-pointer hover:text-foreground",children:"Technical validation details"}),d.jsxs("div",{className:"mt-1 text-[10px] text-muted space-y-0.5",children:[d.jsxs("p",{children:["Episode file: ",d.jsx("span",{className:"font-mono",children:T.file})]}),d.jsxs("p",{children:["State: ",T.state," — ",T.summary]}),d.jsx("p",{children:"Per-cut production (cut plan, clean images, lettering, export, upload) happens in the episode’s cut workspace; open it above to finish any remaining step."})]})]})]})}function WM(e,t){var s;const i=[e.plots,e.chapters].filter(Boolean);for(const a of i){let c=t!=null?a.find(p=>p.plotIndex===t||p.index===t):void 0;if(!c&&a.length===1){const p=a[0];(!(p.plotIndex!=null||p.index!=null)||t==null)&&(c=p)}const h=(s=(c==null?void 0:c.title)??(c==null?void 0:c.name))==null?void 0:s.trim();if(h)return h}}function GM(e){var o;const{fileName:t,detail:i,plotIndex:s}=e;if(!i)return{ok:!0,checked:!1};if(t==="genesis.md"){const c=(o=i.title??i.name)==null?void 0:o.trim();return c?Uo(c,"genesis.md")?{ok:!1,checked:!0,publicTitle:c,reason:`PlotLink indexed the storyline title as “${c}”, a raw filename rather than the reader-facing title.`}:{ok:!0,checked:!0,publicTitle:c}:{ok:!0,checked:!1}}const a=WM(i,s);return a?Uo(a,t)||Ip(a)?{ok:!1,checked:!0,publicTitle:a,reason:`PlotLink indexed the episode title as “${a}”, a generic placeholder rather than a reader-facing episode title.`}:{ok:!0,checked:!0,publicTitle:a}:{ok:!0,checked:!1}}function YM(e){return`${e.reason??"PlotLink indexed a raw/generic public title for this publish."} Published metadata is immutable on-chain and cannot be edited — the next publish must use corrected, reader-facing metadata. (The webtoon pilot stays blocked until a publish indexes a real public title.)`}const h1="plotlink-panel-ratio",VM=.6,Ny=300,If=224,Hf=6;function KM(){try{const e=localStorage.getItem(h1);if(e){const t=parseFloat(e);if(t>0&&t<1)return t}}catch{}return VM}function jy(e,t){if(t<=0)return e;const i=Ny/t,s=1-Ny/t;return i>=s?.5:Math.min(s,Math.max(i,e))}function XM({token:e,authFetch:t}){const[i,s]=w.useState(null),[a,o]=w.useState(null),[c,h]=w.useState(null),[p,f]=w.useState(null),[_,x]=w.useState(0),[b,v]=w.useState(""),[S,N]=w.useState(null),[M,E]=w.useState(null),[L,I]=w.useState(KM),[A,q]=w.useState([]),[R,ne]=w.useState(!1),[ue,ye]=w.useState(""),[B,re]=w.useState(""),[$,G]=w.useState(""),[V,H]=w.useState("English"),[T,z]=w.useState("normal"),[F,xe]=w.useState("claude"),[j,D]=w.useState(null),[X,C]=w.useState(!1),[Z,ae]=w.useState({}),[oe,K]=w.useState({}),[he,ge]=w.useState(new Set),[De,ze]=w.useState(new Set),[Fe,we]=w.useState({}),[He,it]=w.useState({}),[st,nt]=w.useState({}),[Nt,Be]=w.useState({}),[ct,Te]=w.useState({}),[Wt,vi]=w.useState({}),[Ct,et]=w.useState(!1),[ee,be]=w.useState(!0),[Me,$e]=w.useState(null),Xe=w.useRef(new Map),Gt=w.useRef(new Map),pi=w.useRef(new Map),Rt=w.useRef(new Map),St=w.useRef(new Set),Yt=w.useRef(0),ot=w.useRef(null),Ht=w.useRef(null),U=w.useRef(!1);w.useEffect(()=>{t("/api/wallet").then(Y=>Y.ok?Y.json():null).then(Y=>{Y!=null&&Y.address&&E(Y.address)}).catch(()=>{})},[t]),w.useEffect(()=>{t("/api/agent/readiness").then(Y=>Y.ok?Y.json():null).then(Y=>{Y&&D(Y)}).catch(()=>{})},[t]),w.useEffect(()=>{try{localStorage.setItem(h1,String(L))}catch{}},[L]),w.useEffect(()=>{const Y=()=>{if(!Ht.current)return;const me=Ht.current.getBoundingClientRect().width-If-Hf;I(_e=>jy(_e,me))};return window.addEventListener("resize",Y),Y(),()=>window.removeEventListener("resize",Y)},[]);const Ce=w.useCallback(()=>{ye(""),re(""),G(""),z("normal"),xe("claude"),ne(!0)},[]),Ae=w.useCallback(async(Y,me,_e,Oe)=>{const Pe=ue.trim();if(!Pe)return;const qe=Y==="cartoon"?"codex":Oe;try{const wt=await t("/api/stories/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:Pe,description:B.trim()||void 0,language:me,genre:$||void 0,contentType:Y,agentMode:_e,agentProvider:qe})});if(!wt.ok)return;const vt=await wt.json();ne(!1),we(jt=>({...jt,[vt.name]:Y})),it(jt=>({...jt,[vt.name]:me})),$&&nt(jt=>({...jt,[vt.name]:$})),K(jt=>({...jt,[vt.name]:qe})),_e==="bypass"&&ae(jt=>({...jt,[vt.name]:!0})),s(vt.name),o(null)}catch{}},[t,ue,B,$]);w.useEffect(()=>{if(A.length===0)return;const Y=setInterval(async()=>{try{const me=await t("/api/stories");if(!me.ok)return;const _e=await me.json(),Oe=new Set(_e.stories.filter(Pe=>Pe.name!=="_example").map(Pe=>Pe.name));for(const Pe of Oe)if(!St.current.has(Pe)&&A.length>0){const qe=A[0],wt=Xe.current.get(qe)||"fiction",vt=Gt.current.get(qe)||"English",jt=pi.current.get(qe)||"normal",Ze=Rt.current.get(qe)||"claude";let Qe=!1;ot.current&&(Qe=await ot.current(qe,Pe,{contentType:wt,language:vt,agentMode:jt,agentProvider:Ze}).catch(()=>!1)),Qe&&(q(Kt=>Kt.slice(1)),Xe.current.delete(qe),Gt.current.delete(qe),pi.current.delete(qe),Rt.current.delete(qe),jt==="bypass"&&ae(Kt=>{const Ri={...Kt,[Pe]:!0};return delete Ri[qe],Ri}),K(Kt=>{const Ri={...Kt,[Pe]:Ze};return delete Ri[qe],Ri}),t(`/api/stories/${Pe}/metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentType:wt,language:vt,agentMode:jt,agentProvider:Ze})}).catch(()=>{})),s(Pe),o(null)}St.current=Oe}catch{}},3e3);return()=>clearInterval(Y)},[t,A]),w.useEffect(()=>{t("/api/stories").then(Y=>{if(Y.ok)return Y.json()}).then(Y=>{Y!=null&&Y.stories&&(St.current=new Set(Y.stories.filter(me=>me.name!=="_example").map(me=>me.name)))}).catch(()=>{})},[t]);const Ne=w.useCallback((Y,me)=>{s(Y),o(me),h(null)},[]),Ge=w.useRef(null),Ue=w.useCallback(async Y=>{var me,_e,Oe,Pe;Ge.current=Y,s(Y),o(null),h(null);try{const qe=await t(`/api/stories/${Y}`);if(qe.ok&&Ge.current===Y){const wt=await qe.json();if(wt.contentType==="cartoon")return;const vt=wt.files||[],Ze=((me=vt.map(Qe=>{var Kt;return{file:Qe.file,num:(Kt=Qe.file.match(/^plot-(\d+)\.md$/))==null?void 0:Kt[1]}}).filter(Qe=>Qe.num!=null).sort((Qe,Kt)=>parseInt(Kt.num)-parseInt(Qe.num))[0])==null?void 0:me.file)??((_e=vt.find(Qe=>Qe.file==="genesis.md"))==null?void 0:_e.file)??((Oe=vt.find(Qe=>Qe.file==="structure.md"))==null?void 0:Oe.file)??((Pe=vt[0])==null?void 0:Pe.file);Ze&&Ge.current===Y&&o(Ze)}}catch{}},[t]),dt=w.useCallback(Y=>{Y.preventDefault(),U.current=!0,document.body.style.cursor="col-resize",document.body.style.userSelect="none";const me=Oe=>{if(!U.current||!Ht.current)return;const Pe=Ht.current.getBoundingClientRect(),qe=Pe.width-If-Hf,wt=Oe.clientX-Pe.left-If;I(jy(wt/qe,qe))},_e=()=>{U.current=!1,document.body.style.cursor="",document.body.style.userSelect="",window.removeEventListener("mousemove",me),window.removeEventListener("mouseup",_e)};window.addEventListener("mousemove",me),window.addEventListener("mouseup",_e)},[]),_t=w.useCallback(async(Y,me,_e,Oe,Pe,qe)=>{var Ze;f(me),v("Reading file..."),N(null);let wt=!1,vt=null,jt=!1;try{const Qe=await t(`/api/stories/${Y}/${me}`);if(!Qe.ok)throw new Error("Failed to read file");const Kt=await Qe.json(),Ri=Fe[Y];let gi=null,li=null;if(me==="genesis.md")try{const $t=await t(`/api/stories/${Y}/structure.md`);$t.ok&&(gi=(await $t.json()).content??null)}catch{}else if(Ri==="cartoon"&&me.match(/^plot-\d+\.md$/))try{const $t=await t(`/api/stories/${Y}/cuts/${me.replace(/\.md$/,"")}`);$t.ok&&(li=(await $t.json()).title??null)}catch{}const Di=Nm({fileName:me,fileContent:Kt.content,storySlug:Y,structureContent:gi,contentType:Ri,episodeTitle:li});if(Ri==="cartoon"&&Uo(Di,me))return v(me==="genesis.md"?"Add a real “# Title” heading to genesis.md before publishing — it would otherwise publish as a raw filename.":"Set an episode title in the cut plan before publishing — it would otherwise publish as a raw filename."),setTimeout(()=>{f(null),v("")},6e3),!1;if(Ri==="cartoon"&&me.match(/^plot-\d+\.md$/)&&!Em({fileContent:Kt.content,episodeTitle:li}))return v("Set a real episode title in the cut plan (or add a “# Title” to the episode) before publishing — a generic “Episode NN” placeholder can’t be published."),setTimeout(()=>{f(null),v("")},6e3),!1;if(Ri==="cartoon"&&me==="genesis.md"){const $t=wm(Kt.content).blockers;if($t.length>0)return v(`Genesis is the reader-facing Story opening — fix it before publishing: ${$t[0]}`),setTimeout(()=>{f(null),v("")},6e3),!1}let yn;if(me.match(/^plot-\d+\.md$/)){if(pM(Kt)){v("Already published on PlotLink — republishing would create a duplicate chapter. Open it on PlotLink instead (or use Retry Index if it isn't showing yet)."),setTimeout(()=>{f(null),v("")},6e3);return}try{const $t=await t(`/api/stories/${Y}`);if($t.ok){const yi=(await $t.json()).files.find(Lr=>Lr.file==="genesis.md"&&Lr.storylineId);yn=yi==null?void 0:yi.storylineId}}catch{}if(!yn)return v("Error: Publish genesis first to create the storyline"),setTimeout(()=>{f(null),v("")},3e3),!1}v("Checking wallet balance...");try{const $t=await t("/api/publish/preflight");if($t.ok){const Hi=await $t.json();if(gM(Hi))return N(xM(Hi)),f(null),v(""),!1}}catch{}v("Publishing...");const Br=await t("/api/publish/file",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storyName:Y,fileName:me,title:Di,content:Kt.content,genre:_e,language:Oe,isNsfw:Pe,storylineId:yn,...wy(Fe,Y,yn)?{contentType:wy(Fe,Y,yn)}:{}})});if(!Br.ok){const $t=await Br.json();throw new Error($t.error||"Publish failed")}const qs=(Ze=Br.body)==null?void 0:Ze.getReader(),br=new TextDecoder;if(qs)for(;;){const{done:$t,value:Hi}=await qs.read();if($t)break;const Lr=br.decode(Hi).split(` -`).filter(Or=>Or.startsWith("data: "));for(const Or of Lr)try{const Qt=JSON.parse(Or.slice(6));if(Qt.step&&v(Qt.message||Qt.step),Qt.step==="done"&&Qt.txHash){if(jt=!0,await t(`/api/stories/${Y}/${me}/publish-status`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({txHash:Qt.txHash,storylineId:Qt.storylineId,plotIndex:Qt.plotIndex,contentCid:Qt.contentCid,gasCost:Qt.gasCost,indexError:Qt.indexError,authorAddress:M})}),x(Vn=>Vn+1),qe&&me==="genesis.md"&&Qt.storylineId){v("Uploading cover...");let Vn=null;try{Vn=await uM(t,Qt.storylineId,qe)}catch{}Vn||(wt=!0)}if(Ri==="cartoon"&&Qt.storylineId)try{const Vn=me!=="genesis.md",zr=`storylineId=${Qt.storylineId}`+(Vn&&Qt.plotIndex!=null?`&plotIndex=${Qt.plotIndex}`:""),Ws=await t(`/api/publish/public-title?${zr}`);if(Ws.ok){const Zi=await Ws.json(),Pr=Vn?{plots:Zi.plotTitle!=null?[{plotIndex:Qt.plotIndex,title:Zi.plotTitle}]:[]}:{title:Zi.storylineTitle},Si=GM({fileName:me,detail:Pr,plotIndex:Qt.plotIndex});Si.ok||(vt=YM(Si))}}catch{}}}catch{}}vt&&N(vt),v(wt?"Published, but cover upload failed — set it later from Edit Story.":"Published!")}catch(Qe){const Kt=Qe instanceof Error?Qe.message:"Publish failed";v(`Error: ${Kt}`)}finally{setTimeout(()=>{f(null),v("")},3e3)}return jt&&!wt},[t,Fe,M]),At=w.useCallback(Y=>{Y.startsWith("_new_")&&(q(me=>me.filter(_e=>_e!==Y)),Xe.current.delete(Y),Gt.current.delete(Y),pi.current.delete(Y),Rt.current.delete(Y),ae(me=>{if(!(Y in me))return me;const _e={...me};return delete _e[Y],_e}),K(me=>{if(!(Y in me))return me;const _e={...me};return delete _e[Y],_e}))},[]);w.useEffect(()=>{const Y=_e=>{ge(new Set(_e.filter(Ze=>Ze.hasStructure).map(Ze=>Ze.name))),ze(new Set(_e.filter(Ze=>Ze.hasGenesis).map(Ze=>Ze.name)));const Oe={},Pe={},qe={},wt={},vt={},jt={};for(const Ze of _e)Oe[Ze.name]=Ze.contentType||"fiction",Pe[Ze.name]=Ze.language,qe[Ze.name]=Ze.genre,wt[Ze.name]=Ze.isNsfw,vt[Ze.name]=Ze.agentProvider,Ze.title&&(jt[Ze.name]=Ze.title);we(Oe),it(Pe),nt(qe),Be(wt),vi(vt),Te(jt)};t("/api/stories").then(_e=>_e.ok?_e.json():null).then(_e=>{_e!=null&&_e.stories&&Y(_e.stories)}).catch(()=>{});const me=setInterval(async()=>{try{const _e=await t("/api/stories");if(_e.ok){const Oe=await _e.json();Y(Oe.stories)}}catch{}},5e3);return()=>clearInterval(me)},[t]);const Bt=!!j&&j.codex.installed&&j.codex.imageGeneration==="enabled",Ut=!!j&&!Bt,Vt=w.useCallback(async()=>{try{await navigator.clipboard.writeText("codex features enable image_generation"),C(!0),setTimeout(()=>C(!1),2e3)}catch{}},[]),an=w.useCallback(async()=>{if(!i||i.startsWith("_new_"))return;const Y=i;if((await t(`/api/stories/${Y}/metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentType:"cartoon",agentProvider:"codex"})})).ok){vi(_e=>({..._e,[Y]:"codex"})),K(_e=>({..._e,[Y]:"codex"}));try{const _e=await t("/api/stories");if(_e.ok){const Oe=await _e.json();if(Oe!=null&&Oe.stories){const Pe={};for(const qe of Oe.stories)Pe[qe.name]=qe.agentProvider;vi(Pe)}}}catch{}}},[t,i]),ri=w.useCallback(Y=>{i===Y&&(s(null),o(null))},[i]),Mn=i?oe[i]??Wt[i]:void 0,Bn=Of(i,Fe,Xe.current),cr=mM(Bn,Mn,i),Ii=!!i&&Bn==="cartoon",vn=c==="story-info"?"story-info":c==="episodes"?"episodes":c==="publish"?"publish":a==="structure.md"?"whitepaper":a==="genesis.md"?"genesis":a&&/^plot-\d+\.md$/.test(a)?"episodes":"progress",_r=w.useCallback(Y=>{const me=i;if(me)switch(Y){case"progress":h(null),o(null);break;case"story-info":h("story-info");break;case"episodes":h("episodes");break;case"whitepaper":Ne(me,"structure.md");break;case"genesis":Ne(me,"genesis.md");break;case"publish":h("publish");break}},[i,Ne]),mi=w.useCallback((Y,me)=>{const _e=i;if(!_e)return;const Oe=Pe=>{Yt.current+=1,$e({action:Pe,seq:Yt.current})};switch(Y){case"view-progress":h(null),o(null);break;case"publish":h("publish");break;case"open-cuts":case"open-lettering":case"upload":case"refresh-assets":case"generate-markdown":if(!me)return;Ne(_e,me),Oe(Y);break}},[i,Ne]),Zt=w.useCallback(Y=>{i&&(Y.genre!==void 0&&nt(me=>({...me,[i]:Y.genre||void 0})),Y.language!==void 0&&it(me=>({...me,[i]:Y.language||void 0})),Y.isNsfw!==void 0&&Be(me=>({...me,[i]:Y.isNsfw})))},[i]),te=w.useCallback(Y=>{et(Y),be(!Y)},[]),ve=Ct&&!ee;return d.jsxs("div",{ref:Ht,className:"h-[calc(100vh-3.5rem)] flex","data-testid":ve?"stories-focused-lettering-mode":"stories-default-layout",children:[!ve&&d.jsx("div",{className:"w-56 border-r border-border flex-shrink-0",children:d.jsx(MC,{authFetch:t,selectedStory:i,selectedFile:a,onSelectFile:Ne,onNewStory:Ce,untitledSessions:A})}),!ve&&d.jsx("div",{className:"min-w-0 border-r border-border",style:{flex:`${L} 0 0`},children:d.jsx(sN,{token:e,storyName:i,authFetch:t,onSelectStory:Ue,onDestroySession:At,onArchiveStory:ri,confirmedStories:he,renameRef:ot,bypassStories:Z,agentProviders:oe,readiness:j,contentType:Of(i,Fe,Xe.current),needsProviderRepair:cr,onRepairProvider:an})}),!ve&&d.jsx("div",{onMouseDown:dt,className:"flex-shrink-0 flex items-center justify-center hover:bg-border/50 transition-colors",style:{width:Hf,cursor:"col-resize",background:"var(--border)"},children:d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}}),d.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}}),d.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}})]})}),d.jsxs("div",{className:"min-w-0 min-h-0 flex flex-col",style:ve?{flex:"1 0 0"}:{flex:`${1-L} 0 0`},children:[!Ct&&Ii&&i&&d.jsx(UM,{storyTitle:ct[i]||i,active:vn,onSelect:_r}),d.jsx("div",{className:"flex-1 min-h-0 flex flex-col",children:Ii&&c==="story-info"&&i?d.jsx($M,{storyName:i,authFetch:t,onSaved:Zt}):Ii&&c==="episodes"&&i?d.jsx(FM,{storyName:i,authFetch:t,onOpenFile:Ne}):Ii&&c==="publish"&&i?d.jsx(qM,{storyName:i,authFetch:t,onOpenFile:Ne,onOpenStoryInfo:()=>h("story-info"),onPublish:_t,publishingFile:p,genre:st[i],language:He[i],isNsfw:Nt[i],refreshKey:_}):i&&!a?d.jsx(TM,{storyName:i,authFetch:t,onOpenFile:Ne}):d.jsx(wM,{storyName:i,fileName:a,authFetch:t,onPublish:_t,publishingFile:p,walletAddress:M,contentType:Of(i,Fe,Xe.current)||"fiction",language:i?He[i]:void 0,genre:i?st[i]:void 0,isNsfw:i?Nt[i]:void 0,hasGenesis:i?De.has(i):!1,onViewProgress:()=>o(null),onOpenFile:Y=>i&&Ne(i,Y),onViewPublish:()=>h("publish"),focusedLetteringMode:Ct,focusedLetteringWorkspaceVisible:ee,onFocusedLetteringModeChange:te,onFocusedLetteringWorkspaceVisibleChange:be,workflowActionRequest:Me,onWorkflowActionHandled:Y=>$e(me=>(me==null?void 0:me.seq)===Y?null:me)})}),!Ct&&Ii&&i&&d.jsx("div",{className:"flex-shrink-0 border-t border-border bg-background/95 backdrop-blur","data-testid":"workflow-persistent-next-action",children:d.jsx(NM,{storyName:i,fileName:c===null?a:null,authFetch:t,refreshKey:_,onCoachAction:mi,onOpenStoryInfo:()=>h("story-info")})}),b&&d.jsx("div",{className:"shrink-0 px-3 py-1.5 bg-surface border-t border-border text-xs text-muted",children:b}),S&&d.jsxs("div",{className:"shrink-0 px-3 py-2 bg-error/10 border-t border-error/40 text-xs text-error flex items-start justify-between gap-3","data-testid":"publish-block-error",role:"alert",children:[d.jsx("span",{children:S}),d.jsx("button",{type:"button",onClick:()=>N(null),className:"shrink-0 text-error/70 hover:text-error underline","data-testid":"publish-block-error-dismiss",children:"Dismiss"})]})]}),R&&d.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"bg-surface border border-border rounded-lg shadow-lg p-6 max-w-sm w-full space-y-4",children:[d.jsx("h3",{className:"text-sm font-serif font-medium text-foreground text-center",children:"New Story"}),d.jsxs("label",{className:"block space-y-1",children:[d.jsxs("span",{className:"text-[10px] font-medium text-muted",children:["Title ",d.jsx("span",{className:"text-accent",children:"*"})]}),d.jsx("input",{type:"text",value:ue,onChange:Y=>ye(Y.target.value),placeholder:"e.g. 신의 세포","data-testid":"new-story-title",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Short description (optional)"}),d.jsx("input",{type:"text",value:B,onChange:Y=>re(Y.target.value),placeholder:"One line about the story","data-testid":"new-story-description",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Genre (optional)"}),d.jsxs("select",{value:$,onChange:Y=>G(Y.target.value),"data-testid":"new-story-genre",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none",children:[d.jsx("option",{value:"",children:"— Select later —"}),hl.map(Y=>d.jsx("option",{value:Y,children:Y},Y))]})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Language"}),d.jsx("select",{value:V,onChange:Y=>H(Y.target.value),className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none",children:rs.map(Y=>d.jsx("option",{value:Y,children:Y},Y))})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Agent mode"}),d.jsxs("select",{value:T,onChange:Y=>z(Y.target.value),className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"agent-mode-select",children:[d.jsx("option",{value:"normal",children:"Normal (approve each action)"}),d.jsx("option",{value:"bypass",children:"Permissions Bypass (advanced)"})]}),T==="bypass"&&d.jsx("p",{className:"text-[10px] text-amber-700","data-testid":"agent-mode-warning",children:"Less safe: Claude can run actions without per-command approval."})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Provider"}),d.jsxs("select",{value:F,onChange:Y=>xe(Y.target.value),className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"agent-provider-select",children:[d.jsx("option",{value:"claude",children:"🤖 Claude (default)"}),d.jsx("option",{value:"codex",children:"🎨 Codex"})]}),d.jsx("p",{className:"text-[10px] text-muted","data-testid":"agent-provider-helper",children:F==="codex"?"Codex can generate clean cartoon images directly in the terminal.":"Claude prepares image prompts; you generate and upload clean images externally."})]}),d.jsx("p",{className:"text-xs text-muted text-center",children:"Choose a content type to create"}),!ue.trim()&&d.jsx("p",{className:"text-[10px] text-amber-700 text-center","data-testid":"new-story-title-required",children:"Enter a title to create your story."}),d.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[d.jsxs("button",{onClick:()=>Ae("fiction",V,T,F),disabled:!ue.trim(),"data-testid":"create-fiction",className:"border border-border rounded-lg p-4 hover:border-accent hover:bg-accent/5 transition-colors text-center space-y-1 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:border-border disabled:hover:bg-transparent",children:[d.jsx("p",{className:"text-sm font-serif font-medium text-foreground",children:"Fiction"}),d.jsx("p",{className:"text-[11px] text-muted",children:"Novels, short stories, poetry"})]}),d.jsxs("div",{className:"space-y-1",children:[d.jsxs("button",{onClick:()=>Ae("cartoon",V,T,"codex"),disabled:Ut||!ue.trim(),"data-testid":"create-cartoon",className:"w-full border border-border rounded-lg p-4 hover:border-accent hover:bg-accent/5 transition-colors text-center space-y-1 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:border-border disabled:hover:bg-transparent",children:[d.jsx("p",{className:"text-sm font-serif font-medium text-foreground",children:"Cartoon"}),d.jsx("p",{className:"text-[11px] text-muted",children:"Comics, manga, webtoons"}),d.jsx("p",{className:"text-[11px] text-muted","data-testid":"cartoon-codex-note",children:"Cartoon mode requires Codex because the clean-image step needs image generation support."})]}),j&&!j.codex.installed&&d.jsxs("p",{className:"text-[11px] text-amber-700 text-left","data-testid":"cartoon-codex-warning",children:["Codex was not detected. Install the Codex CLI and sign in (e.g."," ",d.jsx("span",{className:"font-mono",children:"npm i -g @openai/codex"})," ","then ",d.jsx("span",{className:"font-mono",children:"codex login"}),") to create cartoons."]}),Eu(j)&&d.jsx("p",{className:"text-[11px] text-amber-700 text-left","data-testid":"cartoon-codex-auth-unknown",children:Fp}),j&&j.codex.installed&&!Eu(j)&&j.codex.imageGeneration!=="enabled"&&d.jsxs("div",{"data-testid":"cartoon-codex-warning",children:[d.jsx("p",{className:"text-[11px] text-amber-700 text-left",children:"Codex is installed but image generation isn't enabled. Enable it, then reopen this dialog:"}),d.jsxs("div",{className:"mt-1 flex items-center gap-1",children:[d.jsx("code",{className:"flex-1 truncate rounded border border-border bg-surface px-1.5 py-1 text-left text-[10px] font-mono text-foreground",children:"codex features enable image_generation"}),d.jsx("button",{type:"button","data-testid":"copy-codex-enable",onClick:Vt,className:"rounded border border-border px-2 py-1 text-[10px] text-muted hover:border-accent hover:text-accent transition-colors",children:X?"Copied!":"Copy"})]})]})]})]}),d.jsx("button",{onClick:()=>ne(!1),className:"w-full px-3 py-1.5 text-xs text-muted hover:text-foreground hover:bg-surface rounded text-center",children:"Cancel"})]})})]})}function ZM({token:e,onComplete:t}){const[i,s]=w.useState(!1),[a,o]=w.useState(null),[c,h]=w.useState(!1),p=async()=>{s(!0),o(null);try{const f=await fetch("/api/wallet/create",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),_=await f.json();if(!f.ok)throw new Error(_.error||"Wallet creation failed");h(!0)}catch(f){o(f instanceof Error?f.message:"Wallet creation failed")}s(!1)};return w.useEffect(()=>{p()},[]),d.jsxs("div",{className:"mx-auto max-w-sm p-6 text-center",children:[d.jsx("h2",{className:"text-accent mb-1 text-lg font-bold",children:"Wallet Setup"}),d.jsx("p",{className:"text-muted mb-6 text-xs",children:"creating your OWS wallet for on-chain publishing"}),i&&d.jsx("p",{className:"text-accent text-sm",children:"creating wallet..."}),a&&d.jsxs("div",{className:"space-y-4",children:[d.jsx("div",{className:"rounded border border-red-700/30 p-3 text-xs text-red-700",children:a}),d.jsx("button",{onClick:p,className:"border-accent text-accent hover:bg-accent/10 w-full rounded border px-4 py-2 text-sm font-medium transition-colors",children:"retry"})]}),c&&d.jsxs("div",{className:"space-y-4",children:[d.jsx("div",{className:"text-accent text-2xl",children:"✓"}),d.jsx("p",{className:"text-foreground text-sm font-medium",children:"wallet created"}),d.jsx("button",{onClick:t,className:"border-accent text-accent hover:bg-accent/10 w-full rounded border px-4 py-2 text-sm font-medium transition-colors",children:"continue"})]})]})}function QM({token:e,onLogout:t}){const[i,s]=w.useState("home"),[a,o]=w.useState(0),[c,h]=w.useState(null),p=w.useCallback(async(f,_)=>fetch(f,{..._,headers:{...(_==null?void 0:_.headers)||{},Authorization:`Bearer ${e}`}}),[e]);return w.useEffect(()=>{fetch("/api/health").then(f=>f.json()).then(f=>{f.version&&h(f.version)}).catch(()=>{})},[]),w.useEffect(()=>{async function f(){try{if(!(await(await p("/api/wallet")).json()).exists){s("wallet-setup");return}const b=await p("/api/stories");if(b.ok){const v=await b.json();o(v.stories.filter(S=>S.name!=="_example").length)}}catch{}}f()},[e]),d.jsxs("div",{className:"flex h-screen flex-col",children:[d.jsxs("header",{className:"border-border flex h-14 items-center justify-between border-b px-4 flex-shrink-0",children:[d.jsxs("div",{className:"flex items-center gap-3",children:[d.jsx("button",{onClick:()=>{i!=="wallet-setup"&&s("home")},className:"flex items-center gap-2 hover:opacity-80",children:d.jsx("span",{className:"text-accent text-sm font-bold tracking-tight",children:"PlotLink OWS"})}),d.jsxs("span",{className:"text-muted text-[10px] uppercase tracking-wider",children:["writer",c?` v${c}`:""]})]}),i!=="wallet-setup"&&d.jsxs("nav",{className:"flex items-center gap-4",children:[d.jsx("button",{onClick:()=>s("stories"),className:`text-xs transition-colors ${i==="stories"?"text-accent":"text-muted hover:text-foreground"}`,children:"stories"}),d.jsx("button",{onClick:()=>s("dashboard"),className:`text-xs transition-colors ${i==="dashboard"?"text-accent":"text-muted hover:text-foreground"}`,children:"dashboard"}),d.jsx("button",{onClick:()=>s("settings"),className:`text-xs transition-colors ${i==="settings"?"text-accent":"text-muted hover:text-foreground"}`,children:"settings"}),d.jsx("button",{onClick:t,className:"text-muted hover:text-foreground text-xs transition-colors",children:"logout"})]})]}),d.jsxs("main",{className:"flex-1 min-h-0",children:[i==="home"&&d.jsxs("div",{className:"mx-auto max-w-lg space-y-6 p-8",children:[d.jsxs("div",{className:"text-center space-y-2",children:[d.jsx("h1",{className:"text-2xl font-serif text-foreground",children:"Write. Publish. Earn."}),d.jsx("p",{className:"text-muted text-sm",children:"Claude or Codex helps create your story. You publish it on-chain."})]}),d.jsxs("div",{className:"text-center space-y-3",children:[d.jsx("button",{onClick:()=>s("stories"),className:"bg-accent text-white hover:bg-accent-dim px-6 py-2.5 rounded text-sm font-medium transition-colors",children:"Start Writing"}),a>0&&d.jsxs("p",{className:"text-muted text-xs",children:[a," ",a===1?"story":"stories"," in progress"]})]}),d.jsxs("div",{className:"rounded border border-border p-4 space-y-2 text-xs text-muted",children:[d.jsx("p",{className:"font-medium text-foreground text-sm",children:"How it works"}),d.jsxs("ol",{className:"space-y-1.5 list-decimal list-inside",children:[d.jsxs("li",{children:["Open the ",d.jsx("strong",{children:"Stories"})," tab — your writing agent launches in the terminal"]}),d.jsx("li",{children:"Tell the agent your story idea — it brainstorms, outlines, and writes"}),d.jsx("li",{children:"Review the live preview as the agent creates files"}),d.jsxs("li",{children:["Click ",d.jsx("strong",{children:"Publish"})," to put your story on-chain"]}),d.jsxs("li",{children:["Earn 5% royalties on every trade at ",d.jsx("a",{href:"https://plotlink.xyz",target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"plotlink.xyz"})]})]}),d.jsx("p",{className:"text-[11px] text-muted",children:"Fiction defaults to Claude; cartoon mode uses Codex for clean-image generation."})]}),d.jsx("div",{className:"text-center",children:d.jsx("a",{href:"https://github.com/realproject7/plotlink-ows#-wallet-setup",target:"_blank",rel:"noopener noreferrer",className:"text-xs text-muted hover:text-accent underline transition-colors",children:"Wallet Setup Guide"})}),d.jsx(Dy,{token:e})]}),i==="stories"&&d.jsx(XM,{token:e,authFetch:p}),i==="dashboard"&&d.jsx(AC,{token:e}),i==="wallet-setup"&&d.jsx(ZM,{token:e,onComplete:()=>s("home")}),i==="settings"&&d.jsx(jC,{token:e,onLogout:t})]})]})}function JM(){const[e,t]=w.useState(()=>localStorage.getItem("ows-token")),[i,s]=w.useState(null),[a,o]=w.useState(!0);w.useEffect(()=>{fetch("/api/auth/status").then(f=>f.json()).then(f=>s(f.configured)).catch(()=>s(null))},[]),w.useEffect(()=>{if(!e){o(!1);return}fetch("/api/auth/verify",{headers:{Authorization:`Bearer ${e}`}}).then(f=>{f.ok||(localStorage.removeItem("ows-token"),t(null))}).catch(()=>{localStorage.removeItem("ows-token"),t(null)}).finally(()=>o(!1))},[e]);const c=async f=>{try{const _=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({passphrase:f})}),x=await _.json();return _.ok?(localStorage.setItem("ows-token",x.token),t(x.token),null):x.error||"Login failed"}catch{return"Cannot connect to server"}},h=async f=>{try{const _=await fetch("/api/auth/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({passphrase:f})}),x=await _.json();return _.ok?(localStorage.setItem("ows-token",x.token),t(x.token),s(!0),null):x.error||"Setup failed"}catch{return"Cannot connect to server"}},p=()=>{localStorage.removeItem("ows-token"),t(null)};return a||i===null?d.jsx("div",{className:"flex h-screen items-center justify-center",children:d.jsx("span",{className:"text-muted text-sm",children:"connecting..."})}):i?e?d.jsx(QM,{token:e,onLogout:p}):d.jsx(EC,{onLogin:c}):d.jsx(NC,{onSetup:h})}kC.createRoot(document.getElementById("root")).render(d.jsx(xC.StrictMode,{children:d.jsx(JM,{})}));export{zp as M,To as a,$S as b,$D as c,$3 as d,jo as l,ym as s,YS as t,r4 as v}; +Publish now?`;if(!window.confirm(ke))return}const se=wi?Ht:null;se?await(s==null?void 0:s(e,t,X,ge,Le,se))&&(ni.current=!0,Xi(null),gi(null),jt("unknown"),$(null),Ae(je=>(je&&URL.revokeObjectURL(je),null)),ii.current&&(ii.current.value="")):s==null||s(e,t,X,ge,Le)},disabled:!!a||wn||ka||Ca||wi&&(!X||!ge)||Ci&&ye!=="ready",className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim disabled:opacity-50 disabled:cursor-not-allowed",children:a===t?"Publishing...":"Publish to PlotLink"}),wi&&c==="cartoon"&&(!X||!ge)&&d.jsx("span",{className:"text-amber-600 text-xs","data-testid":"cartoon-metadata-needs-story-info",children:"Set the genre and language in Story Info before publishing"}),wi&&c!=="cartoon"&&!X&&d.jsx("span",{className:"text-amber-600 text-xs","data-testid":"genre-needs-metadata",children:"Needs metadata — choose a genre before publishing"}),wi&&c!=="cartoon"&&X&&!ge&&d.jsx("span",{className:"text-amber-600 text-xs","data-testid":"language-needs-metadata",children:"Needs metadata — choose a language before publishing"}),wn&&d.jsx("span",{className:"text-error text-xs",children:"Reduce content to publish"}),Ci&&ye==="error"&&d.jsx("span",{className:"text-error text-xs","data-testid":"publish-disabled-reason",children:"Fix the issues below before publishing"}),Ci&&ye==="planning"&&d.jsx("span",{className:"text-muted text-xs","data-testid":"publish-disabled-reason",children:"Prepare the episode for publish to continue"}),Ci&&ye==="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” — ",yt," of ",qe," ","still need an uploaded image"]})]}),us&&d.jsx("button",{onClick:()=>v==null?void 0:v(),"data-testid":"cartoon-review-publish",className:"self-start rounded border border-accent/40 px-3 py-1 text-xs text-accent hover:bg-accent/5 transition-colors",children:"Review publish checklist →"}),yr.warnings.length>0&&d.jsx("div",{className:"flex flex-col gap-0.5",children:yr.warnings.map((se,ke)=>d.jsx("span",{className:"text-amber-600 text-xs",children:se},ke))}),wi&&c!=="cartoon"&&d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[d.jsx("input",{type:"checkbox",checked:Le,onChange:se=>{Fe(se.target.checked),vr({isNsfw:se.target.checked})},className:"rounded border-border"}),"This story contains adult content (18+)"]}),Le&&d.jsx("span",{className:"text-xs text-amber-600",children:"Adult content will be hidden from the default browse view."})]})]})})]})}function EM(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 a1(e){const t=e.coach??null,i=e.metadata,s=e.setup.hasStructure,a=e.setup.hasGenesis,o=e.cover==="present",c=!i.title||!i.language||!i.genre,h=e.episodes.find(f=>!f.published)??null,p=!!h&&h.state!=="ready";return s?a?c?"story-info":p&&(t!=null&&t.episodeFile)?t.episodeFile:o?(t==null?void 0:t.episodeFile)??null:"story-info":"genesis.md":"whitepaper"}function Hp({badge:e,tone:t="accent",summary:i,children:s,note:a,testId:o}){const c=t==="complete"?"border-green-700/20 bg-green-950/5":"border-accent/30 bg-background/95",h=t==="complete"?"bg-green-700/10 text-green-700":"bg-accent/10 text-accent";return d.jsx("div",{className:`border px-3 py-3 sm:px-4 ${c}`,"data-testid":o,"data-state":t==="complete"?"complete":"active",children:d.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[d.jsxs("div",{className:"min-w-0 flex-1",children:[d.jsx("span",{className:`inline-flex rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.14em] ${h}`,children:e}),d.jsx("p",{className:"mt-1 text-sm text-foreground",children:i}),a?d.jsx("p",{className:"mt-1 text-[11px] font-medium text-accent",children:a}):null]}),s?d.jsx("div",{className:"flex w-full justify-end sm:w-auto sm:flex-shrink-0",children:s}):null]})})}function Up({onClick:e,disabled:t,testId:i}){return d.jsx("button",{type:"button",onClick:e,disabled:t,className:"w-full rounded bg-accent px-4 py-2.5 text-sm font-bold text-white shadow-sm transition-colors hover:bg-accent-dim disabled:cursor-not-allowed disabled:opacity-50 sm:w-auto","data-testid":i,children:"Next Action"})}function l1({coach:e,onAction:t}){const[i,s]=w.useState(null),a=i!==null&&i===(e==null?void 0:e.prompt);if(e===void 0)return null;if(!e)return d.jsx(Hp,{badge:"Complete",tone:"complete",summary:"No next action available.",note:"This workflow has no queued next step right now.",testId:"cartoon-next-action"});const o=e.actionKind==="agent"&&e.prompt?d.jsx(Up,{testId:"workflow-coach-copy",onClick:()=>{var h;if(!e.prompt)return;const c=e.prompt;(h=navigator.clipboard)==null||h.writeText(c).then(()=>s(c)).catch(()=>{})}}):e.actionKind==="ui"&&e.uiAction?d.jsx(Up,{testId:"workflow-coach-do",onClick:()=>t(e.uiAction,e.episodeFile)}):null;return d.jsx(Hp,{badge:e.stageLabel,summary:d.jsxs("span",{"data-testid":"workflow-coach-action",children:[d.jsx("span",{className:"font-semibold",children:"Next: "}),d.jsx("span",{children:e.action})]}),note:a?"Prompt copied.":void 0,testId:"cartoon-next-action",children:o})}function NM({progress:e,onOpenStoryInfo:t}){return d.jsx(Hp,{badge:"Story info",summary:d.jsxs("span",{"data-testid":"story-info-next-action",children:[d.jsx("span",{className:"font-semibold",children:"Next: "}),d.jsx("span",{children:EM(e)})]}),testId:"story-info-cta",children:d.jsx(Up,{testId:"story-info-next-action-btn",onClick:()=>t==null?void 0:t(),disabled:!t})})}function jM({progress:e,onCoachAction:t,onOpenStoryInfo:i}){return a1(e)==="story-info"?d.jsx(NM,{progress:e,onOpenStoryInfo:i}):d.jsx(l1,{coach:e.coach??null,onAction:t})}function TM({storyName:e,authFetch:t,fileName:i,refreshKey:s=0,onCoachAction:a,onOpenStoryInfo:o}){const[c,h]=w.useState(void 0),p=JSON.stringify([e,i??"",s]),[f,_]=w.useState(null);return f!==p&&(h(void 0),_(p)),w.useEffect(()=>{let x=!1;const b=i?`?focus=${encodeURIComponent(i)}`:"";return t(`/api/stories/${e}/progress${b}`).then(v=>v.ok?v.json():null).then(v=>{x||h(AM(v)?v:null)}).catch(()=>{x||h(null)}),()=>{x=!0}},[e,i,t,s]),c===void 0?null:c?d.jsx(jM,{progress:c,onCoachAction:a,onOpenStoryInfo:o}):d.jsx(l1,{coach:null,onAction:a})}function AM(e){return!!e&&!!e.metadata&&!!e.setup&&Array.isArray(e.episodes)}function RM({storyName:e,authFetch:t,onOpenFile:i,refreshKey:s=0}){const[a,o]=w.useState(null),[c,h]=w.useState(!0);return w.useEffect(()=>{let p=!1;return(async()=>{h(!0);try{const _=await t(`/api/stories/${e}/progress`),x=_.ok?await _.json():null;p||(o(x),h(!1))}catch{p||(o(null),h(!1))}})(),()=>{p=!0}},[e,t,s]),c?d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"progress-loading",children:"Loading progress…"}):!a||!a.metadata||!Array.isArray(a.episodes)?d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load story progress."}):a.contentType==="cartoon"?d.jsx(PM,{progress:a,storyName:e,onOpenFile:i}):d.jsx(UM,{progress:a,storyName:e,onOpenFile:i})}function mu({label:e,value:t,tone:i="muted"}){const s=i==="ok"?"text-green-700":i==="warn"?"text-amber-700":"text-muted";return d.jsxs("span",{className:"text-[11px]",children:[d.jsxs("span",{className:"text-muted",children:[e,": "]}),d.jsx("span",{className:`font-medium ${s}`,children:t})]})}function o1({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 c1={published:"✓",done:"●",current:"◉","needs-action":"●","not-started":"○"},zu={published:"text-green-700",done:"text-green-700",current:"text-accent","needs-action":"text-amber-700","not-started":"text-muted"},u1={published:"Published",done:"Complete",current:"Current","needs-action":"Needs action","not-started":"Not started"},DM={done:"✓",current:"◓",todo:"○"},MM={done:"text-green-700",current:"text-accent",todo:"text-muted"};function h1({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:`${MM[e.status]} flex-shrink-0`,"aria-hidden":!0,children:DM[e.status]}),d.jsx("span",{className:e.status==="todo"?"text-muted":"text-foreground",children:e.label}),e.detail&&d.jsxs("span",{className:"text-muted",children:["· ",e.detail]})]})}function Cy({index:e,title:t,status:i,items:s,fileName:a,openFile:o}){const c=d.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[d.jsx("span",{className:`flex-shrink-0 ${zu[i]}`,"aria-hidden":!0,children:c1[i]}),d.jsxs("span",{className:"text-xs font-medium text-foreground truncate",children:[e,". ",t]}),a&&d.jsx("span",{className:"text-[10px] text-muted truncate",children:a}),d.jsx("span",{className:`ml-auto text-[10px] font-medium ${zu[i]} flex-shrink-0`,children:u1[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(h1,{item:h},p))})]})}function BM(e,t){return e.published?"published":t?"current":e.state==="placeholder"?"not-started":(e.state==="blocked","needs-action")}function LM(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(OM(a));return s}function OM(e){return{label:e.label,status:e.status,detail:e.detail}}const zM={file:"genesis.md",label:"Episode 1 / Genesis",kind:"genesis",title:null,state:"placeholder",summary:"",published:!1,checklist:[],cuts:null};function PM({progress:e,storyName:t,onOpenFile:i}){const s=e.metadata,a=e.setup.hasStructure,o=e.cover==="present",h=!s.title||!s.language||!s.genre||!o,p=a1(e),f=[{label:"Public title",status:s.title?"done":"todo",detail:s.title??null},{label:"Language",status:s.language?"done":"todo",detail:s.language??null},{label:"Genre",status:s.genre?"done":"todo",detail:s.genre??null},{label:"Cover image",status:o?"done":"todo",detail:e.cover==="invalid"?"Invalid — re-import":o?null:"Missing"}],_=p==="story-info"?"current":h?"needs-action":"done",x=a?"done":p==="whitepaper"?"current":"not-started",b=e.episodes.find(N=>N.kind==="genesis")??null,v=e.episodes.filter(N=>N.kind==="plot");let S=0;return d.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"story-progress-panel",children:[d.jsx(o1,{progress:e}),d.jsx("p",{className:"px-4 pt-3 pb-1 text-[11px] font-medium text-muted uppercase tracking-wider",children:"Production Progress"}),d.jsx(Cy,{index:++S,title:"Define Story Info",status:_,items:f}),d.jsx(Cy,{index:++S,title:"Story Whitepaper",status:x,fileName:"structure.md",openFile:a?()=>i(t,"structure.md"):void 0,items:[{label:"Planning document",status:a?"done":"todo",detail:a?null:"Not written yet"}]}),b?d.jsx(Pf,{index:++S,ep:b,isActive:p===b.file,storyName:t,onOpenFile:i}):d.jsx(Pf,{index:++S,ep:zM,isActive:p==="genesis.md",openingDone:!1,canOpen:!1,storyName:t,onOpenFile:i}),v.map(N=>d.jsx(Pf,{index:++S,ep:N,isActive:p===N.file,storyName:t,onOpenFile:i},N.file)),d.jsxs("div",{className:"px-4 py-2 text-[11px] text-muted flex flex-wrap gap-x-3","data-testid":"progress-summary",children:[d.jsxs("span",{children:[e.summary.published," published"]}),d.jsxs("span",{children:[e.summary.readyToPublish," ready"]}),e.summary.placeholders>0&&d.jsxs("span",{children:[e.summary.placeholders," not started"]}),e.summary.blocked>0&&d.jsxs("span",{className:"text-error",children:[e.summary.blocked," need fixes"]})]})]})}function Pf({index:e,ep:t,isActive:i,storyName:s,onOpenFile:a,openingDone:o=!0,canOpen:c=!0}){const h=BM(t,i),p=LM(t,o),f=t.title?`${t.label} · ${t.title}`:t.label,_=d.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[d.jsx("span",{className:`flex-shrink-0 ${zu[h]}`,"aria-hidden":!0,children:c1[h]}),d.jsxs("span",{className:"text-xs font-medium text-foreground truncate",children:[e,". ",f]}),d.jsx("span",{className:"text-[10px] text-muted truncate",children:t.file}),d.jsx("span",{className:`ml-auto text-[10px] font-medium ${zu[h]} flex-shrink-0`,children:u1[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(h1,{item:x},b))})]})}const IM={published:"✓",ready:"●","in-progress":"◐",planning:"○",placeholder:"○",blocked:"✕",draft:"○"},ky={published:"text-green-700",ready:"text-green-700","in-progress":"text-accent",planning:"text-accent",placeholder:"text-muted",blocked:"text-error",draft:"text-muted"},HM={published:"Published",ready:"Ready","in-progress":"In progress",planning:"Planning",placeholder:"Not started",blocked:"Needs fixes",draft:"Draft"};function UM({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(o1,{progress:e}),e.nextAction&&d.jsxs("div",{className:"px-4 py-2 border-b border-accent/30 bg-accent/5 text-xs space-y-1.5","data-testid":"progress-next-action",children:[d.jsxs("div",{children:[d.jsx("span",{className:"font-medium text-foreground",children:"Next: "}),d.jsx("span",{className:"text-muted",children:e.nextAction})]}),e.nextPrompt&&d.jsxs("div",{className:"flex items-start gap-1.5","data-testid":"progress-next-prompt",children:[d.jsx("code",{className:"flex-1 rounded border border-border bg-surface px-1.5 py-1 text-[10px] text-foreground break-words",children:e.nextPrompt}),d.jsx("button",{onClick:()=>{var o;e.nextPrompt&&((o=navigator.clipboard)==null||o.writeText(e.nextPrompt).then(()=>{a(!0)}).catch(()=>{}))},"data-testid":"copy-next-prompt",className:"rounded border border-border px-2 py-1 text-[10px] text-muted hover:border-accent hover:text-accent transition-colors flex-shrink-0",children:s?"Copied!":"Copy"})]})]}),d.jsxs("div",{className:"px-4 py-2 border-b border-border flex flex-col gap-1",children:[d.jsx(Ey,{done:e.setup.hasStructure,label:"Story bible (structure.md)",onClick:e.setup.hasStructure?()=>i(t,"structure.md"):void 0}),d.jsx(Ey,{done:e.setup.hasGenesis,label:"Genesis written",onClick:e.setup.hasGenesis?()=>i(t,"genesis.md"):void 0})]}),d.jsxs("div",{className:"px-4 py-2",children:[d.jsx("p",{className:"text-[11px] font-medium text-muted uppercase tracking-wider mb-1.5",children:"Chapters"}),e.episodes.length===0?d.jsx("p",{className:"text-xs text-muted italic","data-testid":"progress-no-episodes",children:"No chapters yet — write the Genesis to start."}):d.jsx("ol",{className:"flex flex-col gap-1",children:e.episodes.map(o=>d.jsx("li",{children:d.jsxs("button",{onClick:()=>i(t,o.file),"data-testid":`progress-episode-${o.file}`,"data-state":o.state,className:"w-full text-left flex items-start gap-2 rounded px-2 py-1.5 hover:bg-surface",children:[d.jsx("span",{className:`mt-0.5 ${ky[o.state]}`,"aria-hidden":!0,children:IM[o.state]}),d.jsxs("span",{className:"min-w-0 flex-1",children:[d.jsxs("span",{className:"flex items-center gap-1.5",children:[d.jsx("span",{className:"text-xs font-medium text-foreground",children:o.label}),o.title&&d.jsxs("span",{className:"text-[11px] text-muted truncate",children:["· ",o.title]}),d.jsx("span",{className:`ml-auto text-[10px] font-medium ${ky[o.state]}`,children:HM[o.state]})]}),d.jsx("span",{className:"block text-[11px] text-muted",children:o.summary})]})]})},o.file))})]}),d.jsxs("div",{className:"px-4 py-2 border-t border-border text-[11px] text-muted flex flex-wrap gap-x-3","data-testid":"progress-summary",children:[d.jsxs("span",{children:[e.summary.published," published"]}),e.summary.blocked>0&&d.jsxs("span",{className:"text-error",children:[e.summary.blocked," need fixes"]})]})]})}function Ey({done:e,label:t,onClick:i}){const s=d.jsxs("span",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:e?"text-green-700":"text-muted","aria-hidden":!0,children:e?"✓":"○"}),d.jsx("span",{className:e?"text-foreground":"text-muted",children:t})]});return i?d.jsx("button",{onClick:i,className:"text-left hover:underline",children:s}):d.jsx("div",{children:s})}const $M=[{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 FM({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:$M.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 qM({storyName:e,authFetch:t,onSaved:i}){const[s,a]=w.useState(!0),[o,c]=w.useState(!1),[h,p]=w.useState(""),[f,_]=w.useState(""),[x,b]=w.useState(""),[v,S]=w.useState(""),[N,B]=w.useState(!1),[E,O]=w.useState("cartoon"),[H,A]=w.useState("unknown"),[W,D]=w.useState(!1),[ne,ue]=w.useState(!1),[be,L]=w.useState(null),[re,F]=w.useState(!1),[Y,V]=w.useState(null),[U,T]=w.useState(!1),P=w.useRef(null);w.useEffect(()=>{let k=!1;return a(!0),c(!1),ue(!1),L(null),(async()=>{try{const[K,ae]=await Promise.all([t(`/api/stories/${e}`),t(`/api/stories/${e}/progress`)]);if(!K.ok){k||(c(!0),a(!1));return}const oe=await K.json(),X=ae.ok?await ae.json().catch(()=>null):null;if(k)return;p(oe.title??""),_(oe.description??""),b(Cu(oe.genre)??""),S(oe.language&&ss.find(he=>he.toLowerCase()===oe.language.toLowerCase())||""),B(!!oe.isNsfw),O(oe.contentType==="fiction"?"fiction":"cartoon"),A((X==null?void 0:X.cover)??"unknown"),a(!1)}catch{k||(c(!0),a(!1))}})(),()=>{k=!0}},[e,t]);const q=w.useCallback(async()=>{D(!0),ue(!1),L(null);const k={title:h.trim(),description:f.trim(),genre:x,language:v,isNsfw:N};try{const K=await t(`/api/stories/${e}/publish-metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(k)});if(K.ok)ue(!0),i==null||i({genre:x,language:v,isNsfw:N});else{const ae=await K.json().catch(()=>({}));L(ae.error||"Could not save story info.")}}catch{L("Could not save story info.")}D(!1)},[e,t,h,f,x,v,N,i]),xe=w.useCallback(async k=>{var ae;const K=(ae=k.target.files)==null?void 0:ae[0];if(P.current&&(P.current.value=""),!!K){F(!0),L(null);try{let oe;try{oe=await Ku(K)}catch(Le){L(Le instanceof Error?Le.message:"Could not import image");return}const X=oe.type==="image/jpeg"?"jpg":"webp",he=new File([oe],`cover.${X}`,{type:oe.type}),ge=new FormData;ge.append("file",he);const Re=await t(`/api/stories/${e}/import-cover`,{method:"POST",body:ge});if(!Re.ok){const Le=await Re.json().catch(()=>({}));L(Le.error||"Cover import failed.");return}A("present"),V(Le=>(Le&&URL.revokeObjectURL(Le),URL.createObjectURL(he)))}catch{L("Cover import failed.")}finally{F(!1)}}},[e,t]),j=w.useCallback(()=>{var K;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.`;(K=navigator.clipboard)==null||K.writeText(k).then(()=>{T(!0)}).catch(()=>{})},[h,e]);if(s)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"story-info-loading",children:"Loading story info…"});if(o)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load story info."});const R=H==="present"?"Cover set":H==="invalid"?"Invalid cover — re-import a WebP/JPEG under 1MB":"Missing cover",Z=H==="present"?"text-green-700":H==="invalid"?"text-amber-700":"text-muted";return d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"story-info-page",children:[d.jsx("h2",{className:"text-base font-serif text-foreground",children:"Story Info"}),d.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"These details appear on PlotLink when the story is published."}),d.jsxs("div",{className:"mt-4 flex flex-col gap-4 max-w-xl",children:[d.jsxs("label",{className:"flex flex-col gap-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Public title"}),d.jsx("input",{type:"text",value:h,onChange:k=>{p(k.target.value),ue(!1)},"data-testid":"story-info-title",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none"})]}),d.jsxs("label",{className:"flex flex-col gap-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Short description"}),d.jsx("textarea",{value:f,onChange:k=>{_(k.target.value),ue(!1)},rows:3,"data-testid":"story-info-description",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none resize-y"})]}),d.jsxs("div",{className:"flex flex-wrap gap-4",children:[d.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Genre"}),d.jsxs("select",{value:x,onChange:k=>{b(k.target.value),ue(!1)},"data-testid":"story-info-genre",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none",children:[d.jsx("option",{value:"",children:"Needs metadata"}),hl.map(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),ue(!1)},"data-testid":"story-info-language",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none",children:[d.jsx("option",{value:"",children:"Needs metadata"}),ss.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 ${Z}`,"data-testid":"story-info-cover-status",children:R}),d.jsx("span",{className:"text-[10px] text-muted",children:"WebP or JPEG, max 1MB, 600×900 recommended."}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{type:"button",onClick:()=>{var k;return(k=P.current)==null?void 0:k.click()},disabled:re,"data-testid":"story-info-import-cover",className:"rounded border border-border px-2.5 py-1 text-[11px] text-foreground hover:border-accent hover:text-accent transition-colors disabled:opacity-50",children:re?"Importing…":"Import cover"}),d.jsx("button",{type:"button",onClick:j,"data-testid":"story-info-cover-prompt",className:"rounded border border-border px-2.5 py-1 text-[11px] text-muted hover:border-accent hover:text-accent transition-colors",children:U?"Copied!":"Ask agent for cover prompt"})]}),d.jsx("input",{ref:P,type:"file",accept:"image/*",onChange:xe,className:"hidden"})]})]})]}),d.jsxs("label",{className:"flex items-center gap-2",children:[d.jsx("input",{type:"checkbox",checked:N,onChange:k=>{B(k.target.checked),ue(!1)},"data-testid":"story-info-nsfw"}),d.jsx("span",{className:"text-xs text-foreground",children:"This story contains adult content (18+)"})]}),d.jsxs("div",{className:"flex items-center gap-3",children:[d.jsx("button",{type:"button",onClick:q,disabled:W,"data-testid":"story-info-save",className:"rounded bg-accent px-3 py-1.5 text-xs font-medium text-white hover:bg-accent-dim transition-colors disabled:opacity-50",children:W?"Saving…":"Save Story Info"}),ne&&d.jsx("span",{className:"text-[11px] text-green-700","data-testid":"story-info-saved",children:"Saved"}),be&&d.jsx("span",{className:"text-[11px] text-error","data-testid":"story-info-error",children:be})]})]})]})}function WM({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 GM({storyName:e,authFetch:t,onOpenFile:i,onOpenStoryInfo:s,onPublish:a,publishingFile:o,genre:c,language:h,isNsfw:p,refreshKey:f=0}){var qe,St;const[_,x]=w.useState(null),[b,v]=w.useState(!0),[S,N]=w.useState(!1),[B,E]=w.useState(null),[O,H]=w.useState(null),[A,W]=w.useState(null),[D,ne]=w.useState(null),[ue,be]=w.useState(null),L=async()=>{try{const ze=await t(`/api/stories/${e}/cover-asset`),nt=ze.ok?await ze.json():null;if(!(nt!=null&&nt.found)||!nt.valid||!nt.path)return null;const Ee=await t(`/api/stories/${e}/asset/${String(nt.path).replace(/^assets\//,"")}`);if(!Ee.ok)return null;const Wt=await Ee.blob();return new File([Wt],String(nt.path).split("/").pop()||"cover.webp",{type:nt.type||Wt.type})}catch{return null}};w.useEffect(()=>{let ze=!1;return(async()=>{v(!0),N(!1);try{const Ee=await t(`/api/stories/${e}/progress`),Wt=Ee.ok?await Ee.json():null;if(ze)return;!Wt||!Array.isArray(Wt.episodes)?(N(!0),x(null)):x(Wt),v(!1)}catch{ze||(N(!0),x(null),v(!1))}})(),()=>{ze=!0}},[e,t,f]);const re=((St=(qe=_==null?void 0:_.episodes)==null?void 0:qe.find(ze=>!ze.published))==null?void 0:St.file)??null,F=re==="genesis.md",Y=JSON.stringify([re??"",f]),[V,U]=w.useState(null);if(V!==Y&&(U(Y),H(null),W(null),ne(null),be(null)),w.useEffect(()=>{if(!re)return;let ze=!1;const nt=re.replace(/\.md$/,"");return(async()=>{var Ee;try{const Wt=[t(`/api/stories/${e}/${re}`),t(`/api/stories/${e}/cuts/${nt}`)];F&&Wt.push(t(`/api/stories/${e}/structure.md`));const[vi,Ct,et]=await Promise.all(Wt);if(ze)return;if(H(vi.ok?(await vi.json()).content??"":""),Ct.ok){const ee=await Ct.json();if(ze)return;W(Array.isArray(ee.cuts)?ee.cuts:[]),ne(typeof ee.title=="string"?ee.title:null)}else W(null),ne(null);be(F&&et&&et.ok?((Ee=await et.json())==null?void 0:Ee.content)??null:null)}catch{ze||(H(""),W(null),ne(null),be(null))}})(),()=>{ze=!0}},[re,F,e,t,f]),b)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"publish-page-loading",children:"Loading publish readiness…"});if(S||!_)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load publish readiness."});const T=_.episodes.find(ze=>!ze.published);if(!T)return d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"cartoon-publish-page",children:[d.jsx("h2",{className:"text-base font-serif text-foreground",children:"Publish"}),d.jsx("p",{className:"mt-2 text-xs text-green-700","data-testid":"publish-all-done",children:_.episodes.length>0?"All episodes are published to PlotLink. Plan the next episode to continue.":"No episodes yet — write the Genesis (Episode 1) to begin."})]});const P=T.cuts,q=_.cover==="present",xe=[{label:"Opening text ready",status:"done"},{label:"Cut plan",status:P&&P.total>0?"done":"todo",detail:P?`${P.total} cut${P.total===1?"":"s"} planned`:"not started"},{label:"Clean images converted",status:P&&P.needClean>0&&P.withClean===P.needClean?"done":"todo",detail:P?`${P.withClean} / ${P.needClean}`:null},{label:"Cuts lettered",status:P&&P.total>0&&P.withText===P.total?"done":"todo",detail:P?`${P.withText} / ${P.total}`:null},{label:"Final images exported",status:P&&P.total>0&&P.exported===P.total?"done":"todo",detail:P?`${P.exported} / ${P.total}`:null},{label:"Final images uploaded",status:P&&P.total>0&&P.uploaded===P.total?"done":"todo",detail:P?`${P.uploaded} / ${P.total}`:null},{label:"Cover image",status:q?"done":"todo",detail:q?null:"recommended before publishing"},{label:"Publish to PlotLink",status:T.published?"done":"todo"}],j=T.state==="ready",R=T.state==="blocked",Z=T.file==="genesis.md",k=!Z||!!c&&!!h,K=!!o&&o===T.file,ae=O!==null,oe=ae?Nm({fileName:T.file,fileContent:O??"",storySlug:e,structureContent:ue,contentType:"cartoon",episodeTitle:D}):null,X=!!oe&&Uo(oe,T.file),he=!Z&&ae&&!Em({fileContent:O??"",episodeTitle:D}),ge=X||he,Re=Z&&ae?wm(O??""):null,Le=!!Re&&Re.blockers.length>0,Fe=!Z&&ae&&A!==null?XS(O??"",A):null,ye=Fe&&Fe.stage==="error"?Fe.issues:[],yt=j&&k&&(ae&&(Z||A!==null))&&!ge&&!Le&&!K&&!!a,Ue=async()=>{if(!(!yt||!a)){E(null);try{const ze=Z?await L():null;await a(e,T.file,c??"",h??"",!!p,ze)}catch{E("Publish could not be started. Please try again.")}}};return d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"cartoon-publish-page",children:[d.jsxs("h2",{className:"text-base font-serif text-foreground",children:["Publish ",T.label]}),d.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"Finalize this episode: convert, letter, export, upload, then publish to PlotLink."}),d.jsx("ul",{className:"mt-3 flex flex-col gap-1.5 max-w-xl","data-testid":"publish-checklist",children:xe.map((ze,nt)=>d.jsxs("li",{className:"flex items-baseline gap-2 text-xs","data-testid":"publish-check","data-status":ze.status,children:[d.jsx("span",{className:`flex-shrink-0 ${ze.status==="done"?"text-green-700":"text-muted"}`,"aria-hidden":!0,children:ze.status==="done"?"✓":"○"}),d.jsx("span",{className:ze.status==="done"?"text-foreground":"text-muted",children:ze.label}),ze.detail&&d.jsxs("span",{className:"text-muted",children:["· ",ze.detail]})]},nt))}),oe&&d.jsxs("div",{className:"mt-4 flex flex-col gap-0.5 max-w-xl","data-testid":"publish-title-preview","data-raw":X?"true":"false","data-blocked":ge?"true":"false",children:[d.jsxs("span",{className:"text-[11px] text-foreground",children:[d.jsxs("span",{className:"font-medium",children:[Z?"Story title":"Episode title",":"]})," ",d.jsx("span",{className:ge?"text-error font-medium":"text-foreground",children:oe})]}),X?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-raw-error",children:["This would publish as a raw filename. ",Z?"Add a real “# Title” heading to genesis.md":"Set a title in the cut plan (or add a “# Title” to the episode)"," before publishing."]}):he?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-episode-required",children:["“",oe,"” is a generic placeholder, not a reader-facing title, so it can’t be published. Set a real episode title in the cut plan (or add a “# Title” to the episode) — e.g. “Episode 01 — The Couple Coupon” — before publishing."]}):null]}),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":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."}),Re.blockers.map((ze,nt)=>d.jsx("span",{className:"text-[10px] text-error","data-testid":"genesis-readiness-blocker",children:ze},`b-${nt}`)),Re.warnings.map((ze,nt)=>d.jsx("span",{className:"text-[10px] text-amber-600","data-testid":"genesis-readiness-warning",children:ze},`w-${nt}`))]}),ye.length>0&&d.jsxs("div",{className:"mt-4 flex flex-col gap-2 rounded-xl border border-error/30 bg-error/5 px-3 py-3 max-w-xl","data-testid":"cartoon-publish-issues",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"rounded-full bg-error px-2 py-0.5 text-[10px] font-medium uppercase tracking-[0.14em] text-white",children:"Before publish"}),d.jsx("span",{className:"text-xs font-medium text-foreground",children:"Finish these workflow steps"})]}),ZS(ye).map(ze=>d.jsx("div",{className:"rounded-lg border border-error/15 bg-background/70 px-2.5 py-2","data-testid":`cartoon-issue-group-${ze.key}`,children:d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:ze.title})},ze.key)),d.jsxs("details",{className:"text-[10px] text-muted","data-testid":"cartoon-technical-details",children:[d.jsx("summary",{className:"cursor-pointer select-none",children:"Technical details"}),d.jsx("ul",{className:"mt-1 ml-3 list-disc",children:ye.map((ze,nt)=>d.jsx("li",{className:"font-mono break-words",children:ze},nt))})]})]}),d.jsxs("div",{className:"mt-4 flex flex-col gap-2 max-w-xl",children:[!q&&d.jsx("button",{onClick:s,"data-testid":"publish-add-cover",className:"self-start rounded border border-border px-3 py-1.5 text-xs text-foreground hover:border-accent hover:text-accent transition-colors",children:"Add a cover image (Story Info)"}),Z&&!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)"}),!j&&d.jsxs("button",{onClick:()=>i(e,T.file),"data-testid":"publish-open-episode",className:"self-start rounded border border-accent/40 px-3 py-1.5 text-xs text-accent hover:bg-accent/5 transition-colors",children:["Open ",T.label," to finish ",R?"and fix issues":"(letter / export / upload)"]}),d.jsx("button",{onClick:Ue,disabled:!yt,"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:yt?void 0:"Finish the remaining steps above first",children:K?"Publishing…":`Publish ${T.label} to PlotLink`}),j?k?ge||Le?d.jsx("p",{className:"text-[11px] text-error","data-testid":"publish-title-blocked-reason",children:Le?"Fix the Story opening issues above before publishing.":"Set a real reader-facing title above before publishing."}):null:d.jsx("p",{className:"text-[11px] text-amber-700","data-testid":"publish-needs-metadata",children:"Set the genre and language in Story Info before publishing."}):d.jsx("p",{className:"text-[11px] text-muted","data-testid":"publish-blocked-reason",children:R?`Not publishable yet — ${T.summary.toLowerCase()}. Open the episode to fix the flagged cuts.`:`Not ready yet — ${T.summary.toLowerCase()}.`}),B&&d.jsx("p",{className:"text-[11px] text-error","data-testid":"publish-error",children:B})]}),d.jsxs("details",{className:"mt-4 max-w-xl","data-testid":"publish-technical-details",children:[d.jsx("summary",{className:"text-[11px] text-muted cursor-pointer hover:text-foreground",children:"Technical validation details"}),d.jsxs("div",{className:"mt-1 text-[10px] text-muted space-y-0.5",children:[d.jsxs("p",{children:["Episode file: ",d.jsx("span",{className:"font-mono",children:T.file})]}),d.jsxs("p",{children:["State: ",T.state," — ",T.summary]}),d.jsx("p",{children:"Per-cut production (cut plan, clean images, lettering, export, upload) happens in the episode’s cut workspace; open it above to finish any remaining step."})]})]})]})}function YM(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 VM(e){var o;const{fileName:t,detail:i,plotIndex:s}=e;if(!i)return{ok:!0,checked:!1};if(t==="genesis.md"){const c=(o=i.title??i.name)==null?void 0:o.trim();return c?Uo(c,"genesis.md")?{ok:!1,checked:!0,publicTitle:c,reason:`PlotLink indexed the storyline title as “${c}”, a raw filename rather than the reader-facing title.`}:{ok:!0,checked:!0,publicTitle:c}:{ok:!0,checked:!1}}const a=YM(i,s);return a?Uo(a,t)||Ip(a)?{ok:!1,checked:!0,publicTitle:a,reason:`PlotLink indexed the episode title as “${a}”, a generic placeholder rather than a reader-facing episode title.`}:{ok:!0,checked:!0,publicTitle:a}:{ok:!0,checked:!1}}function KM(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 d1="plotlink-panel-ratio",XM=.6,Ny=300,If=224,Hf=6;function ZM(){try{const e=localStorage.getItem(d1);if(e){const t=parseFloat(e);if(t>0&&t<1)return t}}catch{}return XM}function jy(e,t){if(t<=0)return e;const i=Ny/t,s=1-Ny/t;return i>=s?.5:Math.min(s,Math.max(i,e))}function QM({token:e,authFetch:t}){const[i,s]=w.useState(null),[a,o]=w.useState(null),[c,h]=w.useState(null),[p,f]=w.useState(null),[_,x]=w.useState(0),[b,v]=w.useState(""),[S,N]=w.useState(null),[B,E]=w.useState(null),[O,H]=w.useState(ZM),[A,W]=w.useState([]),[D,ne]=w.useState(!1),[ue,be]=w.useState(""),[L,re]=w.useState(""),[F,Y]=w.useState(""),[V,U]=w.useState("English"),[T,P]=w.useState("normal"),[q,xe]=w.useState("claude"),[j,R]=w.useState(null),[Z,k]=w.useState(!1),[K,ae]=w.useState({}),[oe,X]=w.useState({}),[he,ge]=w.useState(new Set),[Re,Le]=w.useState(new Set),[Fe,ye]=w.useState({}),[st,yt]=w.useState({}),[Ue,qe]=w.useState({}),[St,ze]=w.useState({}),[nt,Ee]=w.useState({}),[Wt,vi]=w.useState({}),[Ct,et]=w.useState(!1),[ee,_e]=w.useState(!0),[Me,He]=w.useState(null),Ze=w.useRef(new Map),Gt=w.useRef(new Map),mi=w.useRef(new Map),At=w.useRef(new Map),wt=w.useRef(new Set),Yt=w.useRef(0),ot=w.useRef(null),Ht=w.useRef(null),$=w.useRef(!1);w.useEffect(()=>{t("/api/wallet").then(M=>M.ok?M.json():null).then(M=>{M!=null&&M.address&&E(M.address)}).catch(()=>{})},[t]),w.useEffect(()=>{t("/api/agent/readiness").then(M=>M.ok?M.json():null).then(M=>{M&&R(M)}).catch(()=>{})},[t]),w.useEffect(()=>{try{localStorage.setItem(d1,String(O))}catch{}},[O]),w.useEffect(()=>{const M=()=>{if(!Ht.current)return;const ie=Ht.current.getBoundingClientRect().width-If-Hf;H(me=>jy(me,ie))};return window.addEventListener("resize",M),M(),()=>window.removeEventListener("resize",M)},[]);const we=w.useCallback(()=>{be(""),re(""),Y(""),P("normal"),xe("claude"),ne(!0)},[]),Ae=w.useCallback(async(M,ie,me,Be)=>{const Se=ue.trim();if(!Se)return;const Te=M==="cartoon"?"codex":Be;try{const Ve=await t("/api/stories/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:Se,description:L.trim()||void 0,language:ie,genre:F||void 0,contentType:M,agentMode:me,agentProvider:Te})});if(!Ve.ok)return;const Ke=await Ve.json();ne(!1),ye(_t=>({..._t,[Ke.name]:M})),yt(_t=>({..._t,[Ke.name]:ie})),F&&qe(_t=>({..._t,[Ke.name]:F})),X(_t=>({..._t,[Ke.name]:Te})),me==="bypass"&&ae(_t=>({..._t,[Ke.name]:!0})),s(Ke.name),o(null)}catch{}},[t,ue,L,F]);w.useEffect(()=>{if(A.length===0)return;const M=setInterval(async()=>{try{const ie=await t("/api/stories");if(!ie.ok)return;const me=await ie.json(),Be=new Set(me.stories.filter(Se=>Se.name!=="_example").map(Se=>Se.name));for(const Se of Be)if(!wt.current.has(Se)&&A.length>0){const Te=A[0],Ve=Ze.current.get(Te)||"fiction",Ke=Gt.current.get(Te)||"English",_t=mi.current.get(Te)||"normal",tt=At.current.get(Te)||"claude";let Qe=!1;ot.current&&(Qe=await ot.current(Te,Se,{contentType:Ve,language:Ke,agentMode:_t,agentProvider:tt}).catch(()=>!1)),Qe&&(W(Bt=>Bt.slice(1)),Ze.current.delete(Te),Gt.current.delete(Te),mi.current.delete(Te),At.current.delete(Te),_t==="bypass"&&ae(Bt=>{const yi={...Bt,[Se]:!0};return delete yi[Te],yi}),X(Bt=>{const yi={...Bt,[Se]:tt};return delete yi[Te],yi}),t(`/api/stories/${Se}/metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentType:Ve,language:Ke,agentMode:_t,agentProvider:tt})}).catch(()=>{})),s(Se),o(null)}wt.current=Be}catch{}},3e3);return()=>clearInterval(M)},[t,A]),w.useEffect(()=>{t("/api/stories").then(M=>{if(M.ok)return M.json()}).then(M=>{M!=null&&M.stories&&(wt.current=new Set(M.stories.filter(ie=>ie.name!=="_example").map(ie=>ie.name)))}).catch(()=>{})},[t]);const Ne=w.useCallback((M,ie)=>{s(M),o(ie),h(null)},[]),We=w.useRef(null),Ie=w.useCallback(async M=>{var ie,me,Be,Se;We.current=M,s(M),o(null),h(null);try{const Te=await t(`/api/stories/${M}`);if(Te.ok&&We.current===M){const Ve=await Te.json();if(Ve.contentType==="cartoon")return;const Ke=Ve.files||[],tt=((ie=Ke.map(Qe=>{var Bt;return{file:Qe.file,num:(Bt=Qe.file.match(/^plot-(\d+)\.md$/))==null?void 0:Bt[1]}}).filter(Qe=>Qe.num!=null).sort((Qe,Bt)=>parseInt(Bt.num)-parseInt(Qe.num))[0])==null?void 0:ie.file)??((me=Ke.find(Qe=>Qe.file==="genesis.md"))==null?void 0:me.file)??((Be=Ke.find(Qe=>Qe.file==="structure.md"))==null?void 0:Be.file)??((Se=Ke[0])==null?void 0:Se.file);tt&&We.current===M&&o(tt)}}catch{}},[t]),ht=w.useCallback(M=>{M.preventDefault(),$.current=!0,document.body.style.cursor="col-resize",document.body.style.userSelect="none";const ie=Be=>{if(!$.current||!Ht.current)return;const Se=Ht.current.getBoundingClientRect(),Te=Se.width-If-Hf,Ve=Be.clientX-Se.left-If;H(jy(Ve/Te,Te))},me=()=>{$.current=!1,document.body.style.cursor="",document.body.style.userSelect="",window.removeEventListener("mousemove",ie),window.removeEventListener("mouseup",me)};window.addEventListener("mousemove",ie),window.addEventListener("mouseup",me)},[]),xt=w.useCallback(async(M,ie,me,Be,Se,Te)=>{var tt;f(ie),v("Reading file..."),N(null);let Ve=!1,Ke=null,_t=!1;try{const Qe=await t(`/api/stories/${M}/${ie}`);if(!Qe.ok)throw new Error("Failed to read file");const Bt=await Qe.json(),yi=Fe[M];let fn=null,Di=null;if(ie==="genesis.md")try{const $t=await t(`/api/stories/${M}/structure.md`);$t.ok&&(fn=(await $t.json()).content??null)}catch{}else if(yi==="cartoon"&&ie.match(/^plot-\d+\.md$/))try{const $t=await t(`/api/stories/${M}/cuts/${ie.replace(/\.md$/,"")}`);$t.ok&&(Di=(await $t.json()).title??null)}catch{}const ri=Nm({fileName:ie,fileContent:Bt.content,storySlug:M,structureContent:fn,contentType:yi,episodeTitle:Di});if(yi==="cartoon"&&Uo(ri,ie))return v(ie==="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(yi==="cartoon"&&ie.match(/^plot-\d+\.md$/)&&!Em({fileContent:Bt.content,episodeTitle:Di}))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(yi==="cartoon"&&ie==="genesis.md"){const $t=wm(Bt.content).blockers;if($t.length>0)return v(`Genesis is the reader-facing Story opening — fix it before publishing: ${$t[0]}`),setTimeout(()=>{f(null),v("")},6e3),!1}let an;if(ie.match(/^plot-\d+\.md$/)){if(gM(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 $t=await t(`/api/stories/${M}`);if($t.ok){const Si=(await $t.json()).files.find(Or=>Or.file==="genesis.md"&&Or.storylineId);an=Si==null?void 0:Si.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 $t=await t("/api/publish/preflight");if($t.ok){const Ii=await $t.json();if(_M(Ii))return N(bM(Ii)),f(null),v(""),!1}}catch{}v("Publishing...");const Bn=await t("/api/publish/file",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storyName:M,fileName:ie,title:ri,content:Bt.content,genre:me,language:Be,isNsfw:Se,storylineId:an,...wy(Fe,M,an)?{contentType:wy(Fe,M,an)}:{}})});if(!Bn.ok){const $t=await Bn.json();throw new Error($t.error||"Publish failed")}const Lr=(tt=Bn.body)==null?void 0:tt.getReader(),vr=new TextDecoder;if(Lr)for(;;){const{done:$t,value:Ii}=await Lr.read();if($t)break;const Or=vr.decode(Ii).split(` +`).filter(zr=>zr.startsWith("data: "));for(const zr of Or)try{const Xt=JSON.parse(zr.slice(6));if(Xt.step&&v(Xt.message||Xt.step),Xt.step==="done"&&Xt.txHash){if(_t=!0,await t(`/api/stories/${M}/${ie}/publish-status`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({txHash:Xt.txHash,storylineId:Xt.storylineId,plotIndex:Xt.plotIndex,contentCid:Xt.contentCid,gasCost:Xt.gasCost,indexError:Xt.indexError,authorAddress:B})}),x(Kn=>Kn+1),Te&&ie==="genesis.md"&&Xt.storylineId){v("Uploading cover...");let Kn=null;try{Kn=await dM(t,Xt.storylineId,Te)}catch{}Kn||(Ve=!0)}if(yi==="cartoon"&&Xt.storylineId)try{const Kn=ie!=="genesis.md",Pr=`storylineId=${Xt.storylineId}`+(Kn&&Xt.plotIndex!=null?`&plotIndex=${Xt.plotIndex}`:""),Ws=await t(`/api/publish/public-title?${Pr}`);if(Ws.ok){const Zi=await Ws.json(),Ir=Kn?{plots:Zi.plotTitle!=null?[{plotIndex:Xt.plotIndex,title:Zi.plotTitle}]:[]}:{title:Zi.storylineTitle},wi=VM({fileName:ie,detail:Ir,plotIndex:Xt.plotIndex});wi.ok||(Ke=KM(wi))}}catch{}}}catch{}}Ke&&N(Ke),v(Ve?"Published, but cover upload failed — set it later from Edit Story.":"Published!")}catch(Qe){const Bt=Qe instanceof Error?Qe.message:"Publish failed";v(`Error: ${Bt}`)}finally{setTimeout(()=>{f(null),v("")},3e3)}return _t&&!Ve},[t,Fe,B]),Nt=w.useCallback(M=>{M.startsWith("_new_")&&(W(ie=>ie.filter(me=>me!==M)),Ze.current.delete(M),Gt.current.delete(M),mi.current.delete(M),At.current.delete(M),ae(ie=>{if(!(M in ie))return ie;const me={...ie};return delete me[M],me}),X(ie=>{if(!(M in ie))return ie;const me={...ie};return delete me[M],me}))},[]);w.useEffect(()=>{const M=me=>{ge(new Set(me.filter(tt=>tt.hasStructure).map(tt=>tt.name))),Le(new Set(me.filter(tt=>tt.hasGenesis).map(tt=>tt.name)));const Be={},Se={},Te={},Ve={},Ke={},_t={};for(const tt of me)Be[tt.name]=tt.contentType||"fiction",Se[tt.name]=tt.language,Te[tt.name]=tt.genre,Ve[tt.name]=tt.isNsfw,Ke[tt.name]=tt.agentProvider,tt.title&&(_t[tt.name]=tt.title);ye(Be),yt(Se),qe(Te),ze(Ve),vi(Ke),Ee(_t)};t("/api/stories").then(me=>me.ok?me.json():null).then(me=>{me!=null&&me.stories&&M(me.stories)}).catch(()=>{});const ie=setInterval(async()=>{try{const me=await t("/api/stories");if(me.ok){const Be=await me.json();M(Be.stories)}}catch{}},5e3);return()=>clearInterval(ie)},[t]);const Mt=!!j&&j.codex.installed&&j.codex.imageGeneration==="enabled",Ut=!!j&&!Mt,li=w.useCallback(async()=>{try{await navigator.clipboard.writeText("codex features enable image_generation"),k(!0),setTimeout(()=>k(!1),2e3)}catch{}},[]),oi=w.useCallback(async()=>{if(!i||i.startsWith("_new_"))return;const M=i;if((await t(`/api/stories/${M}/metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentType:"cartoon",agentProvider:"codex"})})).ok){vi(me=>({...me,[M]:"codex"})),X(me=>({...me,[M]:"codex"}));try{const me=await t("/api/stories");if(me.ok){const Be=await me.json();if(Be!=null&&Be.stories){const Se={};for(const Te of Be.stories)Se[Te.name]=Te.agentProvider;vi(Se)}}}catch{}}},[t,i]),ii=w.useCallback(M=>{i===M&&(s(null),o(null))},[i]),Sn=i?oe[i]??Wt[i]:void 0,Vn=Of(i,Fe,Ze.current),ur=xM(Vn,Sn,i),dn=!!i&&Vn==="cartoon",Xi=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",br=w.useCallback(M=>{const ie=i;if(ie)switch(M){case"progress":h(null),o(null);break;case"story-info":h("story-info");break;case"episodes":h("episodes");break;case"whitepaper":Ne(ie,"structure.md");break;case"genesis":Ne(ie,"genesis.md");break;case"publish":h("publish");break}},[i,Ne]),gi=w.useCallback((M,ie)=>{const me=i;if(!me)return;const Be=Se=>{Yt.current+=1,He({action:Se,seq:Yt.current})};switch(M){case"view-progress":h(null),o(null);break;case"publish":h("publish");break;case"open-cuts":case"open-lettering":case"upload":case"refresh-assets":case"generate-markdown":if(!ie)return;Ne(me,ie),Be(M);break}},[i,Ne]),Kt=w.useCallback(M=>{i&&(M.genre!==void 0&&qe(ie=>({...ie,[i]:M.genre||void 0})),M.language!==void 0&&yt(ie=>({...ie,[i]:M.language||void 0})),M.isNsfw!==void 0&&ze(ie=>({...ie,[i]:M.isNsfw})))},[i]),jt=w.useCallback(M=>{et(M),_e(!M)},[]),ni=Ct&&!ee;return d.jsxs("div",{ref:Ht,className:"h-[calc(100vh-3.5rem)] flex","data-testid":ni?"stories-focused-lettering-mode":"stories-default-layout",children:[!ni&&d.jsx("div",{className:"w-56 border-r border-border flex-shrink-0",children:d.jsx(BC,{authFetch:t,selectedStory:i,selectedFile:a,onSelectFile:Ne,onNewStory:we,untitledSessions:A})}),!ni&&d.jsx("div",{className:"min-w-0 border-r border-border",style:{flex:`${O} 0 0`},children:d.jsx(aN,{token:e,storyName:i,authFetch:t,onSelectStory:Ie,onDestroySession:Nt,onArchiveStory:ii,confirmedStories:he,renameRef:ot,bypassStories:K,agentProviders:oe,readiness:j,contentType:Of(i,Fe,Ze.current),needsProviderRepair:ur,onRepairProvider:oi})}),!ni&&d.jsx("div",{onMouseDown:ht,className:"flex-shrink-0 flex items-center justify-center hover:bg-border/50 transition-colors",style:{width:Hf,cursor:"col-resize",background:"var(--border)"},children:d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}}),d.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}}),d.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}})]})}),d.jsxs("div",{className:"min-w-0 min-h-0 flex flex-col",style:ni?{flex:"1 0 0"}:{flex:`${1-O} 0 0`},children:[!Ct&&dn&&i&&d.jsx(FM,{storyTitle:nt[i]||i,active:Xi,onSelect:br}),d.jsx("div",{className:"flex-1 min-h-0 flex flex-col",children:dn&&c==="story-info"&&i?d.jsx(qM,{storyName:i,authFetch:t,onSaved:Kt}):dn&&c==="episodes"&&i?d.jsx(WM,{storyName:i,authFetch:t,onOpenFile:Ne}):dn&&c==="publish"&&i?d.jsx(GM,{storyName:i,authFetch:t,onOpenFile:Ne,onOpenStoryInfo:()=>h("story-info"),onPublish:xt,publishingFile:p,genre:Ue[i],language:st[i],isNsfw:St[i],refreshKey:_}):i&&!a?d.jsx(RM,{storyName:i,authFetch:t,onOpenFile:Ne}):d.jsx(kM,{storyName:i,fileName:a,authFetch:t,onPublish:xt,publishingFile:p,walletAddress:B,contentType:Of(i,Fe,Ze.current)||"fiction",language:i?st[i]:void 0,genre:i?Ue[i]:void 0,isNsfw:i?St[i]:void 0,hasGenesis:i?Re.has(i):!1,onViewProgress:()=>o(null),onOpenFile:M=>i&&Ne(i,M),onViewPublish:()=>h("publish"),focusedLetteringMode:Ct,focusedLetteringWorkspaceVisible:ee,onFocusedLetteringModeChange:jt,onFocusedLetteringWorkspaceVisibleChange:_e,workflowActionRequest:Me,onWorkflowActionHandled:M=>He(ie=>(ie==null?void 0:ie.seq)===M?null:ie)})}),!Ct&&dn&&i&&d.jsx("div",{className:"flex-shrink-0 border-t border-border bg-background/95 backdrop-blur","data-testid":"workflow-persistent-next-action",children:d.jsx(TM,{storyName:i,fileName:c===null?a:null,authFetch:t,refreshKey:_,onCoachAction:gi,onOpenStoryInfo:()=>h("story-info")})}),b&&d.jsx("div",{className:"shrink-0 px-3 py-1.5 bg-surface border-t border-border text-xs text-muted",children:b}),S&&d.jsxs("div",{className:"shrink-0 px-3 py-2 bg-error/10 border-t border-error/40 text-xs text-error flex items-start justify-between gap-3","data-testid":"publish-block-error",role:"alert",children:[d.jsx("span",{children:S}),d.jsx("button",{type:"button",onClick:()=>N(null),className:"shrink-0 text-error/70 hover:text-error underline","data-testid":"publish-block-error-dismiss",children:"Dismiss"})]})]}),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:ue,onChange:M=>be(M.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:L,onChange:M=>re(M.target.value),placeholder:"One line about the story","data-testid":"new-story-description",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Genre (optional)"}),d.jsxs("select",{value:F,onChange:M=>Y(M.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(M=>d.jsx("option",{value:M,children:M},M))]})]}),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:M=>U(M.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:ss.map(M=>d.jsx("option",{value:M,children:M},M))})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Agent mode"}),d.jsxs("select",{value:T,onChange:M=>P(M.target.value),className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"agent-mode-select",children:[d.jsx("option",{value:"normal",children:"Normal (approve each action)"}),d.jsx("option",{value:"bypass",children:"Permissions Bypass (advanced)"})]}),T==="bypass"&&d.jsx("p",{className:"text-[10px] text-amber-700","data-testid":"agent-mode-warning",children:"Less safe: Claude can run actions without per-command approval."})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Provider"}),d.jsxs("select",{value:q,onChange:M=>xe(M.target.value),className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"agent-provider-select",children:[d.jsx("option",{value:"claude",children:"🤖 Claude (default)"}),d.jsx("option",{value:"codex",children:"🎨 Codex"})]}),d.jsx("p",{className:"text-[10px] text-muted","data-testid":"agent-provider-helper",children:q==="codex"?"Codex can generate clean cartoon images directly in the terminal.":"Claude prepares image prompts; you generate and upload clean images externally."})]}),d.jsx("p",{className:"text-xs text-muted text-center",children:"Choose a content type to create"}),!ue.trim()&&d.jsx("p",{className:"text-[10px] text-amber-700 text-center","data-testid":"new-story-title-required",children:"Enter a title to create your story."}),d.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[d.jsxs("button",{onClick:()=>Ae("fiction",V,T,q),disabled:!ue.trim(),"data-testid":"create-fiction",className:"border border-border rounded-lg p-4 hover:border-accent hover:bg-accent/5 transition-colors text-center space-y-1 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:border-border disabled:hover:bg-transparent",children:[d.jsx("p",{className:"text-sm font-serif font-medium text-foreground",children:"Fiction"}),d.jsx("p",{className:"text-[11px] text-muted",children:"Novels, short stories, poetry"})]}),d.jsxs("div",{className:"space-y-1",children:[d.jsxs("button",{onClick:()=>Ae("cartoon",V,T,"codex"),disabled:Ut||!ue.trim(),"data-testid":"create-cartoon",className:"w-full border border-border rounded-lg p-4 hover:border-accent hover:bg-accent/5 transition-colors text-center space-y-1 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:border-border disabled:hover:bg-transparent",children:[d.jsx("p",{className:"text-sm font-serif font-medium text-foreground",children:"Cartoon"}),d.jsx("p",{className:"text-[11px] text-muted",children:"Comics, manga, webtoons"}),d.jsx("p",{className:"text-[11px] text-muted","data-testid":"cartoon-codex-note",children:"Cartoon mode requires Codex because the clean-image step needs image generation support."})]}),j&&!j.codex.installed&&d.jsxs("p",{className:"text-[11px] text-amber-700 text-left","data-testid":"cartoon-codex-warning",children:["Codex was not detected. Install the Codex CLI and sign in (e.g."," ",d.jsx("span",{className:"font-mono",children:"npm i -g @openai/codex"})," ","then ",d.jsx("span",{className:"font-mono",children:"codex login"}),") to create cartoons."]}),Eu(j)&&d.jsx("p",{className:"text-[11px] text-amber-700 text-left","data-testid":"cartoon-codex-auth-unknown",children:Fp}),j&&j.codex.installed&&!Eu(j)&&j.codex.imageGeneration!=="enabled"&&d.jsxs("div",{"data-testid":"cartoon-codex-warning",children:[d.jsx("p",{className:"text-[11px] text-amber-700 text-left",children:"Codex is installed but image generation isn't enabled. Enable it, then reopen this dialog:"}),d.jsxs("div",{className:"mt-1 flex items-center gap-1",children:[d.jsx("code",{className:"flex-1 truncate rounded border border-border bg-surface px-1.5 py-1 text-left text-[10px] font-mono text-foreground",children:"codex features enable image_generation"}),d.jsx("button",{type:"button","data-testid":"copy-codex-enable",onClick:li,className:"rounded border border-border px-2 py-1 text-[10px] text-muted hover:border-accent hover:text-accent transition-colors",children:Z?"Copied!":"Copy"})]})]})]})]}),d.jsx("button",{onClick:()=>ne(!1),className:"w-full px-3 py-1.5 text-xs text-muted hover:text-foreground hover:bg-surface rounded text-center",children:"Cancel"})]})})]})}function JM({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 e4({token:e,onLogout:t}){const[i,s]=w.useState("home"),[a,o]=w.useState(0),[c,h]=w.useState(null),p=w.useCallback(async(f,_)=>fetch(f,{..._,headers:{...(_==null?void 0:_.headers)||{},Authorization:`Bearer ${e}`}}),[e]);return w.useEffect(()=>{fetch("/api/health").then(f=>f.json()).then(f=>{f.version&&h(f.version)}).catch(()=>{})},[]),w.useEffect(()=>{async function f(){try{if(!(await(await p("/api/wallet")).json()).exists){s("wallet-setup");return}const b=await p("/api/stories");if(b.ok){const v=await b.json();o(v.stories.filter(S=>S.name!=="_example").length)}}catch{}}f()},[e]),d.jsxs("div",{className:"flex h-screen flex-col",children:[d.jsxs("header",{className:"border-border flex h-14 items-center justify-between border-b px-4 flex-shrink-0",children:[d.jsxs("div",{className:"flex items-center gap-3",children:[d.jsx("button",{onClick:()=>{i!=="wallet-setup"&&s("home")},className:"flex items-center gap-2 hover:opacity-80",children:d.jsx("span",{className:"text-accent text-sm font-bold tracking-tight",children:"PlotLink OWS"})}),d.jsxs("span",{className:"text-muted text-[10px] uppercase tracking-wider",children:["writer",c?` v${c}`:""]})]}),i!=="wallet-setup"&&d.jsxs("nav",{className:"flex items-center gap-4",children:[d.jsx("button",{onClick:()=>s("stories"),className:`text-xs transition-colors ${i==="stories"?"text-accent":"text-muted hover:text-foreground"}`,children:"stories"}),d.jsx("button",{onClick:()=>s("dashboard"),className:`text-xs transition-colors ${i==="dashboard"?"text-accent":"text-muted hover:text-foreground"}`,children:"dashboard"}),d.jsx("button",{onClick:()=>s("settings"),className:`text-xs transition-colors ${i==="settings"?"text-accent":"text-muted hover:text-foreground"}`,children:"settings"}),d.jsx("button",{onClick:t,className:"text-muted hover:text-foreground text-xs transition-colors",children:"logout"})]})]}),d.jsxs("main",{className:"flex-1 min-h-0",children:[i==="home"&&d.jsxs("div",{className:"mx-auto max-w-lg space-y-6 p-8",children:[d.jsxs("div",{className:"text-center space-y-2",children:[d.jsx("h1",{className:"text-2xl font-serif text-foreground",children:"Write. Publish. Earn."}),d.jsx("p",{className:"text-muted text-sm",children:"Claude or Codex helps create your story. You publish it on-chain."})]}),d.jsxs("div",{className:"text-center space-y-3",children:[d.jsx("button",{onClick:()=>s("stories"),className:"bg-accent text-white hover:bg-accent-dim px-6 py-2.5 rounded text-sm font-medium transition-colors",children:"Start Writing"}),a>0&&d.jsxs("p",{className:"text-muted text-xs",children:[a," ",a===1?"story":"stories"," in progress"]})]}),d.jsxs("div",{className:"rounded border border-border p-4 space-y-2 text-xs text-muted",children:[d.jsx("p",{className:"font-medium text-foreground text-sm",children:"How it works"}),d.jsxs("ol",{className:"space-y-1.5 list-decimal list-inside",children:[d.jsxs("li",{children:["Open the ",d.jsx("strong",{children:"Stories"})," tab — your writing agent launches in the terminal"]}),d.jsx("li",{children:"Tell the agent your story idea — it brainstorms, outlines, and writes"}),d.jsx("li",{children:"Review the live preview as the agent creates files"}),d.jsxs("li",{children:["Click ",d.jsx("strong",{children:"Publish"})," to put your story on-chain"]}),d.jsxs("li",{children:["Earn 5% royalties on every trade at ",d.jsx("a",{href:"https://plotlink.xyz",target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"plotlink.xyz"})]})]}),d.jsx("p",{className:"text-[11px] text-muted",children:"Fiction defaults to Claude; cartoon mode uses Codex for clean-image generation."})]}),d.jsx("div",{className:"text-center",children:d.jsx("a",{href:"https://github.com/realproject7/plotlink-ows#-wallet-setup",target:"_blank",rel:"noopener noreferrer",className:"text-xs text-muted hover:text-accent underline transition-colors",children:"Wallet Setup Guide"})}),d.jsx(Dy,{token:e})]}),i==="stories"&&d.jsx(QM,{token:e,authFetch:p}),i==="dashboard"&&d.jsx(RC,{token:e}),i==="wallet-setup"&&d.jsx(JM,{token:e,onComplete:()=>s("home")}),i==="settings"&&d.jsx(TC,{token:e,onLogout:t})]})]})}function t4(){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(e4,{token:e,onLogout:p}):d.jsx(NC,{onLogin:c}):d.jsx(jC,{onSetup:h})}EC.createRoot(document.getElementById("root")).render(d.jsx(_C.StrictMode,{children:d.jsx(t4,{})}));export{zp as M,To as a,$S as b,FD as c,F3 as d,jo as l,ym as s,YS as t,a4 as v}; diff --git a/app/web/dist/index.html b/app/web/dist/index.html index ada5ffa..b243adb 100644 --- a/app/web/dist/index.html +++ b/app/web/dist/index.html @@ -7,8 +7,8 @@ - - + +
From 223ba4f06cf2dff39577a8de1e4fe07c85199a1f Mon Sep 17 00:00:00 2001 From: Project7 Date: Mon, 8 Jun 2026 02:35:22 +0000 Subject: [PATCH 2/2] Fix cut review test expectations --- app/web/components/CutListPanel.test.tsx | 4 +++- app/web/components/cartoon-text-panel-cutlist.test.tsx | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/app/web/components/CutListPanel.test.tsx b/app/web/components/CutListPanel.test.tsx index a423467..e33338a 100644 --- a/app/web/components/CutListPanel.test.tsx +++ b/app/web/components/CutListPanel.test.tsx @@ -2226,7 +2226,9 @@ describe("CutListPanel asset diagnostics + Refresh assets (#427)", () => { expect(tools.tagName.toLowerCase()).toBe("details"); expect(tools).not.toHaveAttribute("open"); expect(within(tools).getByTestId("sync-clean-btn")).toBeInTheDocument(); - expect(within(tools).getByText(/Workflow: Upload final images/i)).toBeInTheDocument(); + expect( + within(tools).getByText(/Workflow: Create clean images/i), + ).toBeInTheDocument(); expect( screen.queryByText(/^Technical details$/i), ).not.toBeInTheDocument(); diff --git a/app/web/components/cartoon-text-panel-cutlist.test.tsx b/app/web/components/cartoon-text-panel-cutlist.test.tsx index f2858e8..7e3767c 100644 --- a/app/web/components/cartoon-text-panel-cutlist.test.tsx +++ b/app/web/components/cartoon-text-panel-cutlist.test.tsx @@ -90,7 +90,7 @@ describe("CutListPanel self-guiding workflow copy (#360)", () => { const authFetch = makeFetch([makeCut({ id: 1, cleanImagePath: "assets/plot-01/cut-01-clean.webp" })]); render(); - const help = await screen.findByTestId("cartoon-workflow-help"); + const help = await screen.findByTestId("cut-workspace-tools"); // Explains the order of operations and what a text panel is, in plain terms. expect(help.textContent).toMatch(/Add narration\/text panel/); expect(help.textContent).toMatch(/solid card exported as a final image/i);