@inkeep/open-knowledge 0.5.0-beta.14 → 0.5.0-beta.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,7 +3,7 @@ name: open-knowledge
3
3
  description: "MUST invoke when the project contains a .ok/ directory — before any read or edit of .md / .mdx files, any mcp__open-knowledge__ tool call, and any write_document / edit_document. Skip if no .ok/ — not an Open Knowledge project. Carries preview-attach (open preview browser at session start; one-shot on `action: attach-preview-once`), STOP rules for native Read/Grep/Edit on in-scope markdown, grounding rules (every factual claim needs a source), standard markdown linking with get_dead_links verification, image sourcing + alt-text + source-citation rules, folder-first organization with opt-in nested .ok/ frontmatter + templates, and the anti-pattern table. Authoritative — MCP server instructions and AGENTS.md overlap but do not substitute for the full attach rule, grounding rule, media rules, dead-link verification, and failure-mode guidance carried only here."
4
4
  compatibility: "Claude Code, Claude Desktop, Claude Cowork, Claude.ai web. Requires Open Knowledge MCP server + code execution."
5
5
  metadata:
6
- version: "0.5.0-beta.14"
6
+ version: "0.5.0-beta.15"
7
7
  author: "Inkeep"
8
8
  repository: "https://github.com/inkeep/open-knowledge"
9
9
  ---
@@ -1,3 +1,3 @@
1
1
  import{a as e,i as t,n,t as r}from"./colors-BNufdynn.mjs";const i={single:{topLeft:`┌`,top:`─`,topRight:`┐`,right:`│`,bottomRight:`┘`,bottom:`─`,bottomLeft:`└`,left:`│`},double:{topLeft:`╔`,top:`═`,topRight:`╗`,right:`║`,bottomRight:`╝`,bottom:`═`,bottomLeft:`╚`,left:`║`},round:{topLeft:`╭`,top:`─`,topRight:`╮`,right:`│`,bottomRight:`╯`,bottom:`─`,bottomLeft:`╰`,left:`│`},bold:{topLeft:`┏`,top:`━`,topRight:`┓`,right:`┃`,bottomRight:`┛`,bottom:`━`,bottomLeft:`┗`,left:`┃`},singleDouble:{topLeft:`╓`,top:`─`,topRight:`╖`,right:`║`,bottomRight:`╜`,bottom:`─`,bottomLeft:`╙`,left:`║`},doubleSingle:{topLeft:`╒`,top:`═`,topRight:`╕`,right:`│`,bottomRight:`╛`,bottom:`═`,bottomLeft:`╘`,left:`│`},classic:{topLeft:`+`,top:`-`,topRight:`+`,right:`|`,bottomRight:`+`,bottom:`-`,bottomLeft:`+`,left:`|`},arrow:{topLeft:`↘`,top:`↓`,topRight:`↙`,right:`←`,bottomRight:`↖`,bottom:`↑`,bottomLeft:`↗`,left:`→`}}.round;function a(a){let o=[],s=`${a.name} v${a.version}`;o.push({plain:s,colored:r(s)}),o.push({plain:``,colored:``});let c=a.apiUrl?`Editor: `:`Local: `;if(o.push({plain:`${c}${a.localUrl}`,colored:`${c}${e(t(a.localUrl),a.localUrl)}`}),a.apiUrl){let t=`API: `;o.push({plain:`${t}${a.apiUrl}`,colored:`${t}${n(e(a.apiUrl,a.apiUrl))}`})}if(a.networkUrl){let n=`Network: `;o.push({plain:`${n}${a.networkUrl}`,colored:`${n}${e(t(a.networkUrl),a.networkUrl)}`})}o.push({plain:``,colored:``});let l=`Press Ctrl+C to stop`;o.push({plain:l,colored:n(l)});let u=Math.max(...o.map(e=>e.plain.length)),d=u+4,f=` ${i.topLeft}${i.top.repeat(d)}${i.topRight}`,p=` ${i.bottomLeft}${i.bottom.repeat(d)}${i.bottomRight}`;return[``,f,...o.map(e=>{let t=u-e.plain.length;return` ${i.left}${` `.repeat(2)}${e.colored}${` `.repeat(t+2)}${i.right}`}),p,``].join(`
2
2
  `)}export{a as renderBanner};
3
- //# sourceMappingURL=banner-4PRLiK-I.mjs.map
3
+ //# sourceMappingURL=banner-DdbR6AZr.mjs.map
package/dist/cli.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{o as e}from"./chunk-FK9Q3tQk.mjs";import{t}from"./esm-CEs3LWY3.mjs";import{$ as n,Ai as r,Bn as i,Ci as a,D as o,Di as s,E as c,Ei as l,G as u,Gr as d,H as f,Hr as p,Jr as m,Kn as h,Kr as g,Kt as ee,Lr as _,Oi as te,On as v,Si as y,Ti as b,Ur as ne,V as x,Vr as S,Wr as re,Yn as ie,Yr as ae,_i as oe,bi as se,cr as ce,fi as le,it as ue,ji as de,ki as fe,m as pe,ot as me,pn as he,wi as ge,xi as C,yi as _e}from"./dist-BFaejI07.mjs";import{n as ve,r as ye,t as w}from"./dist-bundle-BSdjl7Rj.mjs";import{C as be,E as xe,S as Se,T as Ce,_ as we,b as Te,g as Ee,r as De,u as Oe,v as ke,w as Ae,x as je,y as Me}from"./init-DoDYKuWt.mjs";import{c as Ne,f as Pe,l as Fe,n as Ie,s as T}from"./server-lock-D7DXNVql-BRVVzA6T.mjs";import{i as Le}from"./git-handle-DwfYp_z--CfyPz4Dz.mjs";import{n as Re}from"./constants-BMZzAuZK.mjs";import{n as ze,t as Be}from"./loader-DwY1uRWB.mjs";import{d as Ve,f as He,l as Ue,m as We,p as Ge,s as Ke}from"./start-Bi19bmNy.mjs";import{c as qe,i as E,n as D,o as O,r as k,s as A,t as j}from"./colors-BNufdynn.mjs";import"./src-T_WN5ziD.mjs";import{execFileSync as Je,spawn as Ye,spawnSync as M}from"node:child_process";import Xe,{basename as Ze,dirname as Qe,isAbsolute as $e,join as N,relative as et,resolve as P}from"node:path";import{closeSync as tt,existsSync as F,mkdirSync as nt,mkdtempSync as rt,openSync as it,readFileSync as I,readdirSync as at,rmSync as ot,unlinkSync as st,writeFileSync as ct}from"node:fs";import lt from"node:process";import{homedir as ut,hostname as dt,tmpdir as ft}from"node:os";import{fileURLToPath as pt}from"node:url";import{AsyncLocalStorage as mt,AsyncResource as ht}from"node:async_hooks";import{stripVTControlCharacters as gt,styleText as L}from"node:util";import*as _t from"node:readline";import{randomUUID as vt}from"node:crypto";import{realpath as yt}from"node:fs/promises";import{setTimeout as bt}from"node:timers/promises";import{createInterface as xt}from"node:readline/promises";var St=de();const Ct=`open-knowledge`;var wt=class{backend=`keyring`;async get(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{let n=new t(Ct,e).getPassword();return n==null?null:JSON.parse(n)}catch{return null}}async set(e,t,n,r){let{Entry:i}=await import(`@napi-rs/keyring`),a=new i(Ct,e),o={login:t,token:n,...r};a.setPassword(JSON.stringify(o))}async clear(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{new t(Ct,e).deletePassword()}catch{}}},Tt=class{backend=`file`;authFile;constructor(e){this.authFile=e??N(ut(),`.ok`,`auth.yml`)}read(){if(!F(this.authFile))return{};try{return(0,St.parse)(I(this.authFile,`utf-8`))??{}}catch(e){let t=e instanceof Error?e.message:`unknown error`;return process.stderr.write(`[auth] Failed to parse ${this.authFile}: ${t}. Starting with empty credentials.\n`),{}}}write(e){let t=Qe(this.authFile);F(t)||nt(t,{recursive:!0,mode:448}),ct(this.authFile,(0,St.stringify)(e),{mode:384})}async get(e){return this.read()[e]??null}async set(e,t,n,r){let i=this.read();i[e]={login:t,token:n,...r},this.write(i)}async clear(e){let t=this.read();delete t[e],this.write(t)}};async function Et(e){try{let{Entry:e}=await import(`@napi-rs/keyring`);return new e(Ct,`__probe__`),process.stderr.write(`[auth] token storage: OS keychain
2
+ import{o as e}from"./chunk-FK9Q3tQk.mjs";import{t}from"./esm-CEs3LWY3.mjs";import{$ as n,Ai as r,Bn as i,Ci as a,D as o,Di as s,E as c,Ei as l,G as u,Gr as d,H as f,Hr as p,Jr as m,Kn as h,Kr as g,Kt as ee,Lr as _,Oi as te,On as v,Si as y,Ti as b,Ur as ne,V as x,Vr as S,Wr as re,Yn as ie,Yr as ae,_i as oe,bi as se,cr as ce,fi as le,it as ue,ji as de,ki as fe,m as pe,ot as me,pn as he,wi as ge,xi as C,yi as _e}from"./dist-BFaejI07.mjs";import{n as ve,r as ye,t as w}from"./dist-bundle-BSdjl7Rj.mjs";import{C as be,E as xe,S as Se,T as Ce,_ as we,b as Te,g as Ee,r as De,u as Oe,v as ke,w as Ae,x as je,y as Me}from"./init-JeGcMd-V.mjs";import{c as Ne,f as Pe,l as Fe,n as Ie,s as T}from"./server-lock-D7DXNVql-BRVVzA6T.mjs";import{i as Le}from"./git-handle-DwfYp_z--CfyPz4Dz.mjs";import{n as Re}from"./constants-BKcZ-SZr.mjs";import{n as ze,t as Be}from"./loader-ZLKIXjJM.mjs";import{d as Ve,f as He,l as Ue,m as We,p as Ge,s as Ke}from"./start-Ci3v8Z67.mjs";import{c as qe,i as E,n as D,o as O,r as k,s as A,t as j}from"./colors-BNufdynn.mjs";import"./src-DK12uoo0.mjs";import{execFileSync as Je,spawn as Ye,spawnSync as M}from"node:child_process";import Xe,{basename as Ze,dirname as Qe,isAbsolute as $e,join as N,relative as et,resolve as P}from"node:path";import{closeSync as tt,existsSync as F,mkdirSync as nt,mkdtempSync as rt,openSync as it,readFileSync as I,readdirSync as at,rmSync as ot,unlinkSync as st,writeFileSync as ct}from"node:fs";import lt from"node:process";import{homedir as ut,hostname as dt,tmpdir as ft}from"node:os";import{fileURLToPath as pt}from"node:url";import{AsyncLocalStorage as mt,AsyncResource as ht}from"node:async_hooks";import{stripVTControlCharacters as gt,styleText as L}from"node:util";import*as _t from"node:readline";import{randomUUID as vt}from"node:crypto";import{realpath as yt}from"node:fs/promises";import{setTimeout as bt}from"node:timers/promises";import{createInterface as xt}from"node:readline/promises";var St=de();const Ct=`open-knowledge`;var wt=class{backend=`keyring`;async get(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{let n=new t(Ct,e).getPassword();return n==null?null:JSON.parse(n)}catch{return null}}async set(e,t,n,r){let{Entry:i}=await import(`@napi-rs/keyring`),a=new i(Ct,e),o={login:t,token:n,...r};a.setPassword(JSON.stringify(o))}async clear(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{new t(Ct,e).deletePassword()}catch{}}},Tt=class{backend=`file`;authFile;constructor(e){this.authFile=e??N(ut(),`.ok`,`auth.yml`)}read(){if(!F(this.authFile))return{};try{return(0,St.parse)(I(this.authFile,`utf-8`))??{}}catch(e){let t=e instanceof Error?e.message:`unknown error`;return process.stderr.write(`[auth] Failed to parse ${this.authFile}: ${t}. Starting with empty credentials.\n`),{}}}write(e){let t=Qe(this.authFile);F(t)||nt(t,{recursive:!0,mode:448}),ct(this.authFile,(0,St.stringify)(e),{mode:384})}async get(e){return this.read()[e]??null}async set(e,t,n,r){let i=this.read();i[e]={login:t,token:n,...r},this.write(i)}async clear(e){let t=this.read();delete t[e],this.write(t)}};async function Et(e){try{let{Entry:e}=await import(`@napi-rs/keyring`);return new e(Ct,`__probe__`),process.stderr.write(`[auth] token storage: OS keychain
3
3
  `),new wt}catch{return process.stderr.write(`[auth] token storage: file (~/.ok/auth.yml)
4
4
  `),new Tt(e)}}async function Dt(e,t,n){let r=Ot(await kt(e)).host??``;if(!r)return 1;let i=await n.get(r);if(i==null)return 1;let a=e=>e.replace(/[\r\n]/g,``);return t.write(`username=${a(i.login)}\npassword=${a(i.token)}\n`),0}function Ot(e){let t={};for(let n of e.split(`
5
5
  `)){let e=n.trim();if(e===``)continue;let r=e.indexOf(`=`);r!==-1&&(t[e.slice(0,r)]=e.slice(r+1))}return t}function kt(e){return new Promise((t,n)=>{let r=[];e.on(`data`,e=>r.push(e)),e.on(`end`,()=>t(Buffer.concat(r).toString(`utf-8`))),e.on(`error`,n)})}function At(e){let n=new t(`git-credential`);return n.description(`Git credential helper (git credential-helper protocol)`),n.command(`get`).description(`Lookup credentials from TokenStore (called by git)`).action(async()=>{let t=await e(),n=await Dt(process.stdin,process.stdout,t);process.exit(n)}),n}function jt(e){let t=e.endpoint.DEFAULTS;return/^https:\/\/(api\.)?github\.com$/.test(t.baseUrl)?`https://github.com`:t.baseUrl.replace(`/api/v3`,``)}async function Mt(e,t,n){let r={baseUrl:jt(e),headers:{accept:`application/json`},...n},i=await e(t,r);if(`error`in i.data){let n=new ve(`${i.data.error_description} (${i.data.error}, ${i.data.error_uri})`,400,{request:e.endpoint.merge(t,r)});throw n.response=i,n}return i}async function Nt(e){let t=e.request||w,n={client_id:e.clientId};return`scopes`in e&&Array.isArray(e.scopes)&&(n.scope=e.scopes.join(` `)),Mt(t,`POST /login/device/code`,n)}async function Pt(e){let t=await Mt(e.request||w,`POST /login/oauth/access_token`,{client_id:e.clientId,device_code:e.code,grant_type:`urn:ietf:params:oauth:grant-type:device_code`}),n={clientType:e.clientType,clientId:e.clientId,token:t.data.access_token,scopes:t.data.scope.split(/\s+/).filter(Boolean)};if(`clientSecret`in e&&(n.clientSecret=e.clientSecret),e.clientType===`github-app`){if(`refresh_token`in t.data){let e=new Date(t.headers.date).getTime();n.refreshToken=t.data.refresh_token,n.expiresAt=Ft(e,t.data.expires_in),n.refreshTokenExpiresAt=Ft(e,t.data.refresh_token_expires_in)}delete n.scopes}return{...t,authentication:n}}function Ft(e,t){return new Date(e+t*1e3).toISOString()}async function It(e,t){let n=Lt(e,t.auth);if(n)return n;let{data:r}=await Nt({clientType:e.clientType,clientId:e.clientId,request:t.request||e.request,scopes:t.auth.scopes||e.scopes});await e.onVerification(r);let i=await zt(t.request||e.request,e.clientId,e.clientType,r);return e.authentication=i,i}function Lt(e,t){if(t.refresh===!0||!e.authentication)return!1;if(e.clientType===`github-app`)return e.authentication;let n=e.authentication;return(`scopes`in t&&t.scopes||e.scopes).join(` `)===n.scopes.join(` `)?n:!1}async function Rt(e){await new Promise(t=>setTimeout(t,e*1e3))}async function zt(e,t,n,r){try{let i={clientId:t,request:e,code:r.device_code},{authentication:a}=n===`oauth-app`?await Pt({...i,clientType:`oauth-app`}):await Pt({...i,clientType:`github-app`});return{type:`token`,tokenType:`oauth`,...a}}catch(i){if(!i.response)throw i;let a=i.response.data.error;if(a===`authorization_pending`)return await Rt(r.interval),zt(e,t,n,r);if(a===`slow_down`)return await Rt(r.interval+7),zt(e,t,n,r);throw i}}async function Bt(e,t){return It(e,{auth:t})}async function Vt(e,t,n,r){let i=t.endpoint.merge(n,r);if(/\/login\/(oauth\/access_token|device\/code)$/.test(i.url))return t(i);let{token:a}=await It(e,{request:t,auth:{type:`oauth`}});return i.headers.authorization=`token ${a}`,t(i)}var Ht=`0.0.0-development`;function Ut(e){let t=e.request||w.defaults({headers:{"user-agent":`octokit-auth-oauth-device.js/${Ht} ${ye()}`}}),{request:n=t,...r}=e,i=e.clientType===`github-app`?{...r,clientType:`github-app`,request:n}:{...r,clientType:`oauth-app`,request:n,scopes:e.scopes||[]};if(!e.clientId)throw Error(`[@octokit/auth-oauth-device] "clientId" option must be set (https://github.com/octokit/auth-oauth-device.js#usage)`);if(!e.onVerification)throw Error(`[@octokit/auth-oauth-device] "onVerification" option must be a function (https://github.com/octokit/auth-oauth-device.js#usage)`);return Object.assign(Bt.bind(null,i),{hook:Vt.bind(null,i)})}async function Wt(e){let{clientId:t,scopes:n=[`repo`,`read:user`,`user:email`],onVerification:r,host:i}=e,a=i&&i!==`github.com`?`https://${i}/api/v3`:`https://api.github.com`,o=Ut({clientType:`oauth-app`,clientId:t,scopes:n,onVerification:async e=>{await r({verificationUri:e.verification_uri,userCode:e.user_code,expiresIn:e.expires_in,interval:e.interval})},request:a===`https://api.github.com`?void 0:(await import(`./dist-bundle-BmF5_Mcp.mjs`)).request.defaults({baseUrl:a})}),s;try{s=await o({type:`oauth`})}catch(e){if(e instanceof Error){let t=e.message.toLowerCase();throw t.includes(`access_denied`)?Error(`Device-flow authorization was denied.`):t.includes(`expired_token`)||t.includes(`timeout`)||t.includes(`timed out`)?Error(`Device-flow code expired before authorization — please try again.`):Error(`GitHub sign-in failed: ${e.message}`)}throw e}return{token:s.token,tokenType:s.tokenType,scopes:s.scopes??[]}}const Gt={invalid_type:`invalid_type`,too_big:`too_big`,too_small:`too_small`,invalid_format:`invalid_format`,not_multiple_of:`not_multiple_of`,unrecognized_keys:`unrecognized_keys`,invalid_union:`invalid_union`,invalid_key:`invalid_key`,invalid_element:`invalid_element`,invalid_value:`invalid_value`,custom:`custom`};var Kt;(function(e){})(Kt||={});function qt(e){return fe(_e,e)}function Jt(){return process.env.OPEN_KNOWLEDGE_GITHUB_CLIENT_ID??`Ov23liqlSd0V1MwR6rhI`}const Yt=new Set([`gitlab.com`,`bitbucket.org`,`codeberg.org`,`gitea.com`,`sr.ht`,`sourcehut.org`]);function Xt(e){let t=e.toLowerCase().replace(/:\d+$/,``);Yt.has(t)&&(process.stderr.write(`Error: ${e} is not a GitHub host. Only GitHub and GitHub Enterprise Server are supported.\n`),process.exit(1))}function Zt(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function Qt(e,t,n=Wt){let r=Jt(),{host:i,json:a}=e;Xt(i),a||process.stderr.write(`Logging in to ${i}\n`);let o=await n({clientId:r,host:i===`github.com`?void 0:i,onVerification:e=>{e.userCode,e.verificationUri,a?Zt(!0,{type:`verification`,user_code:e.userCode,verification_uri:e.verificationUri,expires_in:e.expiresIn}):process.stderr.write(`Open: ${e.verificationUri}\nEnter code: ${e.userCode}\n`)}}),s=`unknown`,c,l;try{let e=i===`github.com`?`https://api.github.com`:`https://${i}/api/v3`,t=await fetch(`${e}/user`,{headers:{Authorization:`Bearer ${o.token}`,"User-Agent":`open-knowledge-cli`,Accept:`application/vnd.github+json`}});if(t.ok){let e=await t.json();s=e.login??s,c=e.name??void 0,l=e.email??void 0}}catch{}await t.set(i,s,o.token,{gitProtocol:`https`,name:c,email:l}),a?Zt(!0,{type:`complete`,host:i,login:s}):process.stderr.write(`✓ Logged in as ${s} on ${i}\n`)}function $t(e){return new t(`login`).description(`Authenticate with GitHub via Device Flow`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{await Qt(t,await e())})}const en=e=>e.name===`enter`||e.name===`return`;var tn=class extends Error{name=`AbortPromptError`;message=`Prompt was aborted`;constructor(e){super(),this.cause=e?.cause}},nn=class extends Error{name=`CancelPromptError`;message=`Prompt was canceled`},rn=class extends Error{name=`ExitPromptError`},an=class extends Error{name=`HookError`},on=class extends Error{name=`ValidationError`};const sn=new mt;function cn(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function ln(e,t){let n=cn(e);return sn.run(n,()=>{function e(e){n.handleChange=()=>{n.index=0,e()},n.handleChange()}return t(e)})}function R(){let e=sn.getStore();if(!e)throw new an(`[Inquirer] Hook functions can only be called from within a prompt`);return e}function un(){return R().rl}function dn(e){return ht.bind((...t)=>{let n=R(),r=!1,i=n.handleChange;n.handleChange=()=>{r=!0};let a=e(...t);return r&&i(),n.handleChange=i,a})}function fn(e){let t=R(),{index:n}=t,r=e({get(){return t.hooks[n]},set(e){t.hooks[n]=e},initialized:n in t.hooks});return t.index++,r}function pn(){R().handleChange()}const mn={queue(e){let t=R(),{index:n}=t;t.hooksEffect.push(()=>{t.hooksCleanup[n]?.();let r=e(un());if(r!=null&&typeof r!=`function`)throw new on(`useEffect return value must be a cleanup function or nothing.`);t.hooksCleanup[n]=r})},run(){let e=R();dn(()=>{e.hooksEffect.forEach(e=>{e()}),e.hooksEffect.length=0})()},clearAll(){let e=R();e.hooksCleanup.forEach(e=>{e?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function hn(e){return typeof e==`function`}function z(e){return fn(t=>{let n=ht.bind(function(e){t.get()!==e&&(t.set(e),pn())});if(t.initialized)return[t.get(),n];let r=hn(e)?e():e;return t.set(r),[r,n]})}function gn(e,t){fn(n=>{let r=n.get();(!Array.isArray(r)||t.some((e,t)=>!Object.is(e,r[t])))&&mn.queue(e),n.set(t)})}const _n={prefix:{idle:L(`blue`,`?`),done:L(`green`,xe.tick)},spinner:{interval:80,frames:[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`].map(e=>L(`yellow`,e))},style:{answer:e=>L(`cyan`,e),message:e=>L(`bold`,e),error:e=>L(`red`,`> ${e}`),defaultAnswer:e=>L(`dim`,`(${e})`),help:e=>L(`dim`,e),highlight:e=>L(`cyan`,e),key:e=>L(`cyan`,L(`bold`,`<${e}>`))}};function vn(e){if(typeof e!=`object`||!e)return!1;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function yn(...e){let t={};for(let n of e)for(let[e,r]of Object.entries(n)){let n=t[e];t[e]=vn(n)&&vn(r)?yn(n,r):r}return t}function bn(...e){return yn(_n,...e.filter(e=>e!=null))}function xn({status:e=`idle`,theme:t}){let[n,r]=z(!1),[i,a]=z(0),{prefix:o,spinner:s}=bn(t);return gn(()=>{if(e===`loading`){let e,t=-1,n=setTimeout(()=>{r(!0),e=setInterval(()=>{t+=1,a(t%s.frames.length)},s.interval)},300);return()=>{clearTimeout(n),clearInterval(e)}}else r(!1)},[e]),n?s.frames[i]:typeof o==`string`?o:o[e===`loading`?`idle`:e]??o.idle}function Sn(e){return z({current:e})[0]}function Cn(e){let t=Sn(e);t.current=e,gn(e=>{let n=!1,r=dn((r,i)=>{n||t.current(i,e)});return e.input.on(`keypress`,r),()=>{n=!0,e.input.removeListener(`keypress`,r)}},[])}var wn=e(Ce(),1);function Tn(e,t){return e.split(`
@@ -17,10 +17,10 @@ import{o as e}from"./chunk-FK9Q3tQk.mjs";import{t}from"./esm-CEs3LWY3.mjs";impor
17
17
  `),process.exit(1)}await t.set(r,c,a,{gitProtocol:`https`,name:l,email:u}),i?process.stdout.write(`${JSON.stringify({type:`complete`,host:r,login:c})}\n`):process.stderr.write(`✓ PAT stored for ${c} on ${r}\n`)}function Mr(e){return new t(`pat`).description(`Store a Personal Access Token`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{await jr(t,await e())})}async function Nr(e,t){let{host:n,json:r}=e;Xt(n);let i=await t.get(n);i??(process.stderr.write(`Not logged in to ${n}\n`),process.exit(1));let a=n===`github.com`?void 0:`https://${n}/api/v3`,o=new Ar({auth:i.token,...a?{baseUrl:a}:{}}),s=[];for await(let e of o.paginate.iterator(o.repos.listForAuthenticatedUser,{per_page:100,sort:`updated`}))for(let t of e.data)s.push({full_name:t.full_name,clone_url:t.clone_url,private:t.private});if(r)process.stdout.write(`${JSON.stringify({type:`repos`,host:n,repos:s})}\n`);else for(let e of s)process.stdout.write(`${e.full_name} ${e.clone_url}\n`)}function Pr(e){return new t(`repos`).description(`List accessible repositories`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{await Nr(t,await e())})}async function Fr(e,t){let{host:n}=e;await t.clear(n),process.stderr.write(`✓ Signed out from ${n}\n`)}function Ir(e){return new t(`signout`).description(`Remove stored credentials`).option(`--host <host>`,`GitHub hostname`,`github.com`).action(async t=>{await Fr(t,await e())})}async function Lr(e,t){let{host:n,json:r}=e;Xt(n);let i=await t.get(n);i??(r?process.stdout.write(`${JSON.stringify({type:`status`,host:n,authenticated:!1})}\n`):process.stderr.write(`Not logged in to ${n}\n`),process.exit(1));let a=n===`github.com`?void 0:`https://${n}/api/v3`,o=new Ar({auth:i.token,...a?{baseUrl:a}:{}});try{let{data:e}=await o.users.getAuthenticated();r?process.stdout.write(`${JSON.stringify({type:`status`,host:n,authenticated:!0,login:e.login,name:e.name,email:e.email})}\n`):process.stderr.write(`✓ Logged in as ${e.login} on ${n}\n`)}catch{r?process.stdout.write(JSON.stringify({type:`status`,host:n,authenticated:!1,error:`token invalid`})+`
18
18
  `):process.stderr.write(`✗ Token invalid for ${n}\n`),process.exit(1)}}function Rr(e){return new t(`status`).description(`Show authentication status`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{await Lr(t,await e())})}function zr(){let e=new t(`auth`);e.description(`GitHub authentication management`);let n=()=>Et();return e.addCommand($t(n)),e.addCommand(Rr(n)),e.addCommand(Pr(n)),e.addCommand(Ir(n)),e.addCommand(Mr(n)),e.addCommand(At(n)),e}function V(e,t,n={}){let r=Fe(e,t);if(!F(r))return{status:`missing`,lockPath:r};let i;try{i=JSON.parse(I(r,`utf-8`))}catch{return{status:`corrupt`,lockPath:r}}if(!i||typeof i!=`object`||!Ne(i.pid))return{status:`corrupt`,lockPath:r};let a=i;if(!(n.isAlive??T)(a.pid))return{status:`dead-pid`,lockPath:r,lock:a};let o=n.host??dt();return a.hostname===o?{status:`alive`,lockPath:r,lock:a}:{status:`foreign-host`,lockPath:r,lock:a}}function Br(e,t){let n=[];for(let[r,i]of[[`server`,e],[`ui`,t]])(i.status===`dead-pid`||i.status===`corrupt`)&&n.push({name:r,lockPath:i.lockPath,reason:i.status});return{prune:n}}function Vr(e){let t=e.inspect??(t=>V(e.lockDir,t)),n=e.unlink??(e=>st(e)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=Br(t(`server`),t(`ui`));if(a.prune.length===0)return r(`No stale locks.`),{pruned:[],failed:[]};let o=[],s=[];for(let e of a.prune)try{n(e.lockPath),o.push(e)}catch(t){s.push({target:e,error:t instanceof Error?t.message:String(t)})}if(o.length>0){let e=o.map(e=>`${e.name} (${e.reason})`).join(`, `);r(`Pruned ${o.length} stale lock${o.length===1?``:`s`}: ${e}`)}return s.length>0&&i(`Failed to prune: ${s.map(({target:e,error:t})=>`${e.name} (${e.lockPath}): ${t}`).join(`; `)}`),{pruned:o,failed:s}}function Hr(e){return new t(`clean`).description(`Prune stale / corrupt open-knowledge lock files (never touches live locks)`).action(()=>{e(),Vr({lockDir:ie(process.cwd())}).failed.length>0&&(process.exitCode=1)})}function Ur(){try{let e=Je(`gh`,[`auth`,`token`],{encoding:`utf-8`,stdio:[`ignore`,`pipe`,`pipe`],timeout:5e3}).trim();return e.length===0?{available:!1}:{available:!0,token:e}}catch{return{available:!1}}}async function Wr(e,t,n={},r=Ur){if(!n.skipGhDetect&&r().available)return{tier:`A`,credentialArgs:[`-c`,`credential.helper=!gh auth git-credential`]};let i=await t.get(e);return i==null?{tier:`none`,credentialArgs:[]}:{tier:i.gitProtocol===`ssh`?`C`:`B`,credentialArgs:[`-c`,`credential.helper=!open-knowledge auth git-credential`]}}function Gr(e){return e.replace(/:\d+$/,``)}function Kr(e){let t=e.trim();if(!t)return null;{let e=/^https?:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`https`,hostname:Gr(e[1]),owner:e[2],name:e[3]}}{let e=/^ssh:\/\/(?:[\w.-]+@)?([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`ssh`,hostname:Gr(e[1]),owner:e[2],name:e[3]}}{let e=/^git:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:Gr(e[1]),owner:e[2],name:e[3]}}{let e=/^(?:[\w.-]+@)?([\w.-]+):([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t);if(e?.[1].includes(`.`)||e&&t.startsWith(`git@`))return{protocol:`ssh`,hostname:e[1],owner:e[2],name:e[3]}}{let e=/^git:([\w.-]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:e[1],owner:e[2],name:e[3]}}if(!t.includes(`://`)&&!t.includes(`@`)&&!t.startsWith(`/`)){let e=/^([\w.-]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t);if(e)return{protocol:`https`,hostname:`github.com`,owner:e[1],name:e[2]}}return null}const qr=[[`count`,0,10],[`compress`,10,20],[`receiv`,20,60],[`resolv`,60,100]];function Jr(e){let t=/^([\w ]+):\s+(\d+)%/.exec(e.trim());if(!t)return null;let n=t[1].toLowerCase(),r=Number(t[2]);for(let[e,i,a]of qr)if(n.includes(e))return{stage:t[1],pct:Math.round(i+r/100*(a-i))};return null}function H(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function Yr(e,t,n,r=process.cwd()){let i=Kr(e);if(!i)throw Error(`Invalid git URL: ${e}`);let a=t.dir?P(r,t.dir):P(r,i.name);if(F(a)&&at(a).length>0)throw Error(`Target directory is not empty: ${a}`);let o=await Et(),s=await Wr(i.hostname,o,{}),c=Le({baseDir:r,config:s.credentialArgs.length>=2?[s.credentialArgs[1]]:[],unsafe:{allowUnsafeCredentialHelper:!0}}).env({GIT_TERMINAL_PROMPT:`0`}),l=-1;c.outputHandler((e,n,r)=>{r.on(`data`,e=>{let n=e.toString(`utf-8`);for(let e of n.split(`
19
19
  `)){let n=Jr(e);n&&n.pct!==l&&(l=n.pct,H(t.json,{type:`progress`,pct:n.pct,stage:n.stage}),t.json||process.stderr.write(`\r Cloning ${n.pct}%`))}})}),await c.clone(e,a,[`--progress`]),t.json||process.stderr.write(`
20
- `);try{let{runInit:e}=await import(`./init-DeafrQoL.mjs`),n=await e({cwd:a,mcp:!1});if(n.contentUpdated.length>0){let e=`auto-init: updated ${n.contentUpdated.join(`, `)}`;t.json?H(!0,{type:`warning`,message:e}):process.stderr.write(` ${e}\n`)}}catch(e){let n=e instanceof Error?e.message:String(e);t.json?H(!0,{type:`warning`,message:`auto-init: ${n}`}):process.stderr.write(` auto-init: ${n}\n`)}try{Xr(a)}catch(e){let n=e instanceof Error?e.message:String(e);t.json?H(!0,{type:`warning`,message:`git-exclude: ${n}`}):process.stderr.write(` git-exclude: ${n}\n`)}return a}function Xr(e){let t=N(e,`.git`,`info`,`exclude`);if(!F(t))return`no-exclude`;let n=I(t,`utf-8`),r=new Set([`.ok`,`.ok/`,`/.ok`,`/.ok/`]);return n.split(`
20
+ `);try{let{runInit:e}=await import(`./init-BROwb5FR.mjs`),n=await e({cwd:a,mcp:!1});if(n.contentUpdated.length>0){let e=`auto-init: updated ${n.contentUpdated.join(`, `)}`;t.json?H(!0,{type:`warning`,message:e}):process.stderr.write(` ${e}\n`)}}catch(e){let n=e instanceof Error?e.message:String(e);t.json?H(!0,{type:`warning`,message:`auto-init: ${n}`}):process.stderr.write(` auto-init: ${n}\n`)}try{Xr(a)}catch(e){let n=e instanceof Error?e.message:String(e);t.json?H(!0,{type:`warning`,message:`git-exclude: ${n}`}):process.stderr.write(` git-exclude: ${n}\n`)}return a}function Xr(e){let t=N(e,`.git`,`info`,`exclude`);if(!F(t))return`no-exclude`;let n=I(t,`utf-8`),r=new Set([`.ok`,`.ok/`,`/.ok`,`/.ok/`]);return n.split(`
21
21
  `).map(e=>e.trim()).some(e=>r.has(e))?`already-present`:(ct(t,`${n}${n.length===0||n.endsWith(`
22
22
  `)?``:`
23
- `}.ok/\n`,`utf-8`),`appended`)}function Zr(e){return new t(`clone`).description(`Clone a git repository and open it`).argument(`<url>`,`Repository URL or owner/repo shorthand`).argument(`[dir]`,`Target directory (default: ./<repo-name>)`).option(`--json`,`Output JSONL progress events`,!1).action(async(t,n,r)=>{let i=e();try{let a=await Yr(t,{json:r.json,dir:n},i);if(r.json)H(!0,{type:`complete`,dir:a});else{process.stderr.write(`✓ Cloned to ${a}\n`),process.chdir(a);let{startCommand:t}=await import(`./start-CxJ_Uuo2.mjs`);await t(e).parseAsync([],{from:`user`})}}catch(e){let t=e instanceof Error?e.message:String(e);r.json?H(!0,{type:`error`,message:t}):process.stderr.write(`✗ ${t}\n`),process.exitCode=1}})}const Qr=[[`sync`],[`persistence`,`debounceMs`],[`persistence`,`maxDebounceMs`],[`server`,`port`],[`content`,`include`],[`content`,`exclude`]];function $r(e={}){let t=e.log??(e=>console.error(e)),n=e.error??(e=>console.error(e)),r=e.loadConfigFn??ze;try{let{sources:n}=r(e.cwd);return t(`✓ Configuration valid (sources: ${n.length===0?`defaults only`:n.join(`, `)})`),{ok:!0}}catch(e){return n(e instanceof Error?e.message:String(e)),{ok:!1}}}function ei(e){let t=(0,St.parseDocument)(I(e,`utf-8`));if(t.errors.length>0)throw Error(`Could not parse ${e}: ${t.errors.map(e=>e.message).join(`; `)}`);let n=[];for(let e of Qr)t.hasIn(e)&&n.push(e.join(`.`));return n}function ti(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ni(e){let t={};for(let n of e){let e=t;for(let t=0;t<n.length-1;t++){let r=n[t],i=e[r],a=ti(i)?i:{};e[r]=a,e=a}e[n[n.length-1]]=null}return t}async function ri(e={}){let t=e.log??(e=>console.log(e)),n=e.error??(e=>console.error(e)),r=e.scope??`both`,i=e.dryRun??!1,a=e.cwd??process.cwd(),o=e.writeConfigPatchFn??ae,s=[];(r===`project`||r===`both`)&&s.push({scope:`project`,absPath:m(`project`,a,e.homedirOverride)}),(r===`user`||r===`both`)&&s.push({scope:`user`,absPath:m(`user`,a,e.homedirOverride)});let c=[],l=!0;for(let{scope:t,absPath:n}of s){if(!F(n)){c.push({path:n,scope:t,found:[],removed:[]});continue}let r;try{r=ei(n)}catch(e){let r=e instanceof Error?e.message:String(e);c.push({path:n,scope:t,found:[],removed:[],error:r}),l=!1;continue}if(r.length===0||i){c.push({path:n,scope:t,found:r,removed:[]});continue}let s=await o({cwd:a,scope:t,patch:ni(Qr.filter(e=>r.includes(e.join(`.`)))),homedirOverride:e.homedirOverride});if(!s.ok){c.push({path:n,scope:t,found:r,removed:[],error:le(s.error)}),l=!1;continue}c.push({path:n,scope:t,found:r,removed:r})}for(let e of c)e.error&&n(`✗ ${e.path}: ${e.error}`);let u=c.some(e=>e.error!==void 0),d=c.reduce((e,t)=>e+t.found.length,0);if(d===0&&!u)t(`No deprecated fields found.`);else if(d>0)for(let e of c)e.error||(e.found.length===0?t(` ${e.path}: no deprecated fields`):t(i?`[dry-run] ${e.path}: would remove ${e.found.length} field(s): ${e.found.join(`, `)}`:`✓ ${e.path}: removed ${e.removed.length} field(s): ${e.removed.join(`, `)}`));return{outcomes:c,ok:l}}function ii(){let e=new t(`config`).description(`Inspect and maintain Open Knowledge configuration files`);return e.command(`validate`).description(`Validate the merged config (defaults → user → project)`).action(()=>{$r({}).ok||(process.exitCode=1)}),e.command(`migrate`).description(`Remove deprecated config fields (sync.*, persistence.{debounceMs,maxDebounceMs}, server.port, content.{include,exclude}) idempotently`).option(`--scope <scope>`,`Which scope to migrate: project | user | both`,`both`).option(`--dry-run`,`Preview without writing`,!1).action(async e=>{let t=e.scope;if(t!==`project`&&t!==`user`&&t!==`both`){console.error(`Invalid --scope: ${t}. Expected: project | user | both`),process.exitCode=2;return}(await ri({scope:t,dryRun:e.dryRun})).ok||(process.exitCode=1)}),e}var U=e(qe(),1);const W=2e3,ai=[/cli\.mjs/,/(^|[\s/])(open-knowledge|ok)\s+(start|mcp|ui)(\s|$)/,/(^|[\s/])bun([\s/]).*?(run dev|packages\/app|vite|hocuspocus)/,/(^|[\s/])node([\s/]).*?(packages\/(cli|app)|vite|hocuspocus)/,/(^|\s)--ok-lock-dir-b64=/];function oi(e){return ai.some(t=>t.test(e))}function si(e){let t=e.trim().split(/\s+/).find(e=>e.startsWith(`--ok-lock-dir-b64=`));if(t==null)return null;let n=t.slice(18);if(!n)return null;try{let e=Buffer.from(n,`base64url`).toString(`utf8`);return $e(e)?e:null}catch{return null}}function ci(e){let t=[];for(let n of e.split(`
23
+ `}.ok/\n`,`utf-8`),`appended`)}function Zr(e){return new t(`clone`).description(`Clone a git repository and open it`).argument(`<url>`,`Repository URL or owner/repo shorthand`).argument(`[dir]`,`Target directory (default: ./<repo-name>)`).option(`--json`,`Output JSONL progress events`,!1).action(async(t,n,r)=>{let i=e();try{let a=await Yr(t,{json:r.json,dir:n},i);if(r.json)H(!0,{type:`complete`,dir:a});else{process.stderr.write(`✓ Cloned to ${a}\n`),process.chdir(a);let{startCommand:t}=await import(`./start-BQOVij1z.mjs`);await t(e).parseAsync([],{from:`user`})}}catch(e){let t=e instanceof Error?e.message:String(e);r.json?H(!0,{type:`error`,message:t}):process.stderr.write(`✗ ${t}\n`),process.exitCode=1}})}const Qr=[[`sync`],[`persistence`,`debounceMs`],[`persistence`,`maxDebounceMs`],[`server`,`port`],[`content`,`include`],[`content`,`exclude`]];function $r(e={}){let t=e.log??(e=>console.error(e)),n=e.error??(e=>console.error(e)),r=e.loadConfigFn??ze;try{let{sources:n}=r(e.cwd);return t(`✓ Configuration valid (sources: ${n.length===0?`defaults only`:n.join(`, `)})`),{ok:!0}}catch(e){return n(e instanceof Error?e.message:String(e)),{ok:!1}}}function ei(e){let t=(0,St.parseDocument)(I(e,`utf-8`));if(t.errors.length>0)throw Error(`Could not parse ${e}: ${t.errors.map(e=>e.message).join(`; `)}`);let n=[];for(let e of Qr)t.hasIn(e)&&n.push(e.join(`.`));return n}function ti(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ni(e){let t={};for(let n of e){let e=t;for(let t=0;t<n.length-1;t++){let r=n[t],i=e[r],a=ti(i)?i:{};e[r]=a,e=a}e[n[n.length-1]]=null}return t}async function ri(e={}){let t=e.log??(e=>console.log(e)),n=e.error??(e=>console.error(e)),r=e.scope??`both`,i=e.dryRun??!1,a=e.cwd??process.cwd(),o=e.writeConfigPatchFn??ae,s=[];(r===`project`||r===`both`)&&s.push({scope:`project`,absPath:m(`project`,a,e.homedirOverride)}),(r===`user`||r===`both`)&&s.push({scope:`user`,absPath:m(`user`,a,e.homedirOverride)});let c=[],l=!0;for(let{scope:t,absPath:n}of s){if(!F(n)){c.push({path:n,scope:t,found:[],removed:[]});continue}let r;try{r=ei(n)}catch(e){let r=e instanceof Error?e.message:String(e);c.push({path:n,scope:t,found:[],removed:[],error:r}),l=!1;continue}if(r.length===0||i){c.push({path:n,scope:t,found:r,removed:[]});continue}let s=await o({cwd:a,scope:t,patch:ni(Qr.filter(e=>r.includes(e.join(`.`)))),homedirOverride:e.homedirOverride});if(!s.ok){c.push({path:n,scope:t,found:r,removed:[],error:le(s.error)}),l=!1;continue}c.push({path:n,scope:t,found:r,removed:r})}for(let e of c)e.error&&n(`✗ ${e.path}: ${e.error}`);let u=c.some(e=>e.error!==void 0),d=c.reduce((e,t)=>e+t.found.length,0);if(d===0&&!u)t(`No deprecated fields found.`);else if(d>0)for(let e of c)e.error||(e.found.length===0?t(` ${e.path}: no deprecated fields`):t(i?`[dry-run] ${e.path}: would remove ${e.found.length} field(s): ${e.found.join(`, `)}`:`✓ ${e.path}: removed ${e.removed.length} field(s): ${e.removed.join(`, `)}`));return{outcomes:c,ok:l}}function ii(){let e=new t(`config`).description(`Inspect and maintain Open Knowledge configuration files`);return e.command(`validate`).description(`Validate the merged config (defaults → user → project)`).action(()=>{$r({}).ok||(process.exitCode=1)}),e.command(`migrate`).description(`Remove deprecated config fields (sync.*, persistence.{debounceMs,maxDebounceMs}, server.port, content.{include,exclude}) idempotently`).option(`--scope <scope>`,`Which scope to migrate: project | user | both`,`both`).option(`--dry-run`,`Preview without writing`,!1).action(async e=>{let t=e.scope;if(t!==`project`&&t!==`user`&&t!==`both`){console.error(`Invalid --scope: ${t}. Expected: project | user | both`),process.exitCode=2;return}(await ri({scope:t,dryRun:e.dryRun})).ok||(process.exitCode=1)}),e}var U=e(qe(),1);const W=2e3,ai=[/cli\.mjs/,/(^|[\s/])(open-knowledge|ok)\s+(start|mcp|ui)(\s|$)/,/(^|[\s/])bun([\s/]).*?(run dev|packages\/app|vite|hocuspocus)/,/(^|[\s/])node([\s/]).*?(packages\/(cli|app)|vite|hocuspocus)/,/(^|\s)--ok-lock-dir-b64=/];function oi(e){return ai.some(t=>t.test(e))}function si(e){let t=e.trim().split(/\s+/).find(e=>e.startsWith(`--ok-lock-dir-b64=`));if(t==null)return null;let n=t.slice(18);if(!n)return null;try{let e=Buffer.from(n,`base64url`).toString(`utf8`);return $e(e)?e:null}catch{return null}}function ci(e){let t=[];for(let n of e.split(`
24
24
  `)){let e=n.trim();if(!e)continue;let r=e.indexOf(` `);if(r===-1)continue;let i=e.slice(0,r),a=e.slice(r+1),o=Number.parseInt(i,10);!Number.isNaN(o)&&oi(a)&&t.push({pid:o,command:a})}return t}function li(e){let t=[],n=e.split(`
25
25
  `);for(let e=1;e<n.length;e++){let r=n[e]?.trim();if(!r)continue;let i=r.indexOf(` `);if(i===-1)continue;let a=r.slice(0,i),o=r.slice(i+1).trim(),s=Number.parseInt(a,10);!Number.isNaN(s)&&oi(o)&&t.push({pid:s,command:o})}return t}async function ui(){let e=M(`pgrep`,[`-a`,`-f`,`cli\\.mjs|open-knowledge|--ok-lock-dir-b64=|(^|[ /])ok[ ]+(start|mcp|ui)([ ]|$)|packages/(cli|app)|hocuspocus|vite`],{encoding:`utf-8`,timeout:W});if(!(e.error!=null&&e.error.code===`ENOENT`)){let t=e.stdout??``,n=ci(t);if(n.length>0||t.trim()===``)return n}let t=M(`ps`,[`-axo`,`pid,command`],{encoding:`utf-8`,timeout:W});return t.error!=null||!t.stdout?[]:li(t.stdout)}function di(e){let t=e.trim().split(/\s+/).filter(Boolean);for(let e of t){if(e.startsWith(`@`))continue;let t=Ze(e);if(t===`open-knowledge`||t===`ok`||e.endsWith(`/packages/cli/src/cli.ts`)||e.endsWith(`/packages/cli/dist/cli.mjs`)||t===`cli.mjs`||t===`cli.ts`)return e}return null}function fi(e){let t=M(`ps`,[`-p`,String(e),`-o`,`command=`],{encoding:`utf-8`,timeout:W});return t.error!=null||!t.stdout?null:t.stdout.trim()||null}function pi(e){let t=M(`ps`,[`-p`,String(e),`-o`,`%cpu=,%mem=`],{encoding:`utf-8`,timeout:W});if(t.error!=null||!t.stdout)return null;let[n,r]=t.stdout.trim().split(/\s+/),i=Number.parseFloat(n??``),a=Number.parseFloat(r??``);return Number.isNaN(i)||Number.isNaN(a)?null:{cpuPercent:i,memPercent:a}}async function mi(e){let t=M(`lsof`,[`-p`,String(e),`-a`,`-d`,`cwd`,`-Fn`],{encoding:`utf-8`,timeout:W});if(t.error!=null)return null;let n=t.stdout??``;for(let e of n.split(`
26
26
  `))if(e.startsWith(`n`)&&e.length>1)return e.slice(1);return null}function hi(e){let t=[],n=e.split(`
@@ -56,7 +56,7 @@ setTimeout(() => process.exit(2), ${t+1e4});
56
56
  `)?c.slice(0,-1):c}),s=void 0,c=``,l=``}function m(e={}){a&&e.consume&&d(a),o=!0,s=void 0,c=``,l=``,a=``}return{feed:u,reset:m}}function eo(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e.indexOf(`\r`,r),a=e.indexOf(`
57
57
  `,r),o=-1;if(i!==-1&&a!==-1?o=Math.min(i,a):i===-1?a!==-1&&(o=a):o=i===e.length-1?-1:i,o===-1){n=e.slice(r);break}else{let n=e.slice(r,o);t.push(n),r=o+1,e[r-1]===`\r`&&e[r]===`
58
58
  `&&r++}}return[t,n]}var to=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let r;super({start(i){r=$a({onEvent:e=>{i.enqueue(e)},onError(t){e===`terminate`?i.error(t):typeof e==`function`&&e(t)},onRetry:t,onComment:n})},transform(e){r.feed(e)}})}};const no={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};var Y=class extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}},ro=class{constructor(e,t){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=Bi(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??no}async _authThenStart(){if(!this._authProvider)throw new J(`No auth provider`);let e;try{e=await Aa(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(e){throw this.onerror?.(e),e}if(e!==`AUTHORIZED`)throw new J;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}this._sessionId&&(e[`mcp-session-id`]=this._sessionId),this._protocolVersion&&(e[`mcp-protocol-version`]=this._protocolVersion);let t=zi(this._requestInit?.headers);return new Headers({...e,...t})}async _startOrAuthSse(e){let{resumptionToken:t}=e;try{let n=await this._commonHeaders();n.set(`Accept`,`text/event-stream`),t&&n.set(`last-event-id`,t);let r=await(this._fetch??fetch)(this._url,{method:`GET`,headers:n,signal:this._abortController?.signal});if(!r.ok){if(await r.body?.cancel(),r.status===401&&this._authProvider)return await this._authThenStart();if(r.status===405)return;throw new Y(r.status,`Failed to open SSE stream: ${r.statusText}`)}this._handleSseStream(r.body,e,!0)}catch(e){throw this.onerror?.(e),e}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let t=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,r=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*n**+e,r)}_scheduleReconnection(e,t=0){let n=this._reconnectionOptions.maxRetries;if(t>=n){this.onerror?.(Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let r=this._getNextReconnectionDelay(t);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(n=>{this.onerror?.(Error(`Failed to reconnect SSE stream: ${n instanceof Error?n.message:String(n)}`)),this._scheduleReconnection(e,t+1)})},r)}_handleSseStream(e,t,n){if(!e)return;let{onresumptiontoken:r,replayMessageId:i}=t,a,o=!1,s=!1;(async()=>{try{let t=e.pipeThrough(new TextDecoderStream).pipeThrough(new to({onRetry:e=>{this._serverRetryMs=e}})).getReader();for(;;){let{value:e,done:n}=await t.read();if(n)break;if(e.id&&(a=e.id,o=!0,r?.(e.id)),e.data&&(!e.event||e.event===`message`))try{let t=p.parse(JSON.parse(e.data));g(t)&&(s=!0,i!==void 0&&(t.id=i)),this.onmessage?.(t)}catch(e){this.onerror?.(e)}}(n||o)&&!s&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:a,onresumptiontoken:r,replayMessageId:i},0)}catch(e){if(this.onerror?.(Error(`SSE stream disconnected: ${e}`)),(n||o)&&!s&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:r,replayMessageId:i},0)}catch(e){this.onerror?.(Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`))}}})()}async start(){if(this._abortController)throw Error(`StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.`);this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new J(`No auth provider`);if(await Aa(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new J(`Failed to authorize`)}async close(){this._reconnectionTimeout&&=(clearTimeout(this._reconnectionTimeout),void 0),this._abortController?.abort(),this.onclose?.()}async send(e,t){try{let{resumptionToken:n,onresumptiontoken:r}=t||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:d(e)?e.id:void 0}).catch(e=>this.onerror?.(e));return}let i=await this._commonHeaders();i.set(`content-type`,`application/json`),i.set(`accept`,`application/json, text/event-stream`);let a={...this._requestInit,method:`POST`,headers:i,body:JSON.stringify(e),signal:this._abortController?.signal},o=await(this._fetch??fetch)(this._url,a),s=o.headers.get(`mcp-session-id`);if(s&&(this._sessionId=s),!o.ok){let t=await o.text().catch(()=>null);if(o.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Y(401,`Server returned 401 after successful authentication`);let{resourceMetadataUrl:t,scope:n}=Pa(o);if(this._resourceMetadataUrl=t,this._scope=n,await Aa(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new J;return this._hasCompletedAuthFlow=!0,this.send(e)}if(o.status===403&&this._authProvider){let{resourceMetadataUrl:t,scope:n,error:r}=Pa(o);if(r===`insufficient_scope`){let r=o.headers.get(`WWW-Authenticate`);if(this._lastUpscopingHeader===r)throw new Y(403,`Server returned 403 after trying upscoping`);if(n&&(this._scope=n),t&&(this._resourceMetadataUrl=t),this._lastUpscopingHeader=r??void 0,await Aa(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!==`AUTHORIZED`)throw new J;return this.send(e)}}throw new Y(o.status,`Error POSTing to endpoint: ${t}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,o.status===202){await o.body?.cancel(),re(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>this.onerror?.(e));return}let c=(Array.isArray(e)?e:[e]).filter(e=>`method`in e&&`id`in e&&e.id!==void 0).length>0,l=o.headers.get(`content-type`);if(c)if(l?.includes(`text/event-stream`))this._handleSseStream(o.body,{onresumptiontoken:r},!1);else if(l?.includes(`application/json`)){let e=await o.json(),t=Array.isArray(e)?e.map(e=>p.parse(e)):[p.parse(e)];for(let e of t)this.onmessage?.(e)}else throw await o.body?.cancel(),new Y(-1,`Unexpected content type: ${l}`);else await o.body?.cancel()}catch(e){throw this.onerror?.(e),e}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),t={...this._requestInit,method:`DELETE`,headers:e,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,t);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new Y(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}};function io(e){return(t,n)=>{if((n?.method??`GET`).toUpperCase()===`GET`)return globalThis.fetch(t,n);let r=new AbortController,i=setTimeout(()=>r.abort(Error(`MCP request timed out after ${e}ms`)),e),a=n?.signal instanceof AbortSignal?AbortSignal.any([n.signal,r.signal]):r.signal;return globalThis.fetch(t,{...n,signal:a}).finally(()=>clearTimeout(i))}}function ao(e){if(e===void 0||e===``)return;let t=Number.parseInt(e,10);if(!(Number.isNaN(t)||t<=0))return t}function oo(e){return e===`0.0.0.0`||e===`::`?`localhost`:e.includes(`:`)&&!e.startsWith(`[`)?`[${e}]`:e}function so(e,t){return`http://${oo(e)}:${t}/mcp`}function co(e,t){return`ws://${oo(e)}:${t}`}function lo(e){let t=new URL(e);return t.protocol=t.protocol===`https:`?`wss:`:`ws:`,t.pathname=``,t.search=``,t.hash=``,t.toString().replace(/\/$/,``)}function uo(e,t){if(!(!e||e.port<=0)&&t(e.pid))return e.port}function fo(e){return F(e)?I(e,`utf-8`).trim():``}function po(e,t){return`server did not start within ${e}ms${t?` stderr:\n${t}`:``}`}function mo(e){if(e&&typeof e==`object`&&`method`in e&&`id`in e)return e.id}function ho(e){if(!e||typeof e!=`object`||!(`result`in e))return;let t=e.result;if(!t||typeof t!=`object`||!(`protocolVersion`in t))return;let n=t.protocolVersion;return typeof n==`string`?n:void 0}function go(e,t){return{jsonrpc:`2.0`,id:e,error:{code:-32e3,message:t instanceof Error?t.message:String(t)}}}async function _o(e){let t=e.readLock??(()=>Pe(e.lockDir)),n=e.isAlive??T,r=e.sleep??(e=>bt(e)),i=e.spawn??Ye,a=e.readErrorLog??fo,o=e.openErrorLog??(e=>it(e,`w`)),s=e.closeFd??tt,c=e.timeoutMs??5e3,l=e.pollIntervalMs??100;if(e.portOverride!==void 0){let t=Number.parseInt(e.portOverride,10);if(Number.isNaN(t)||t<=0)throw Error(`invalid --port value '${e.portOverride}' — HTTP MCP shim requires a positive port`);return so(`localhost`,t)}let u=uo(t(),n);if(u!==void 0)return so(`localhost`,u);if(e.envAutoStart===`0`)throw Error(`Open Knowledge server is not running and OK_MCP_AUTOSTART=0 disables auto-start.`);F(e.lockDir)||nt(e.lockDir,{recursive:!0});let d=N(e.lockDir,`last-spawn-error.log`),f=o(d),p,m,h=Ve();try{try{p=i(h.command,[...h.prefixArgs,`start`],{detached:!0,stdio:[`ignore`,`ignore`,f],cwd:e.contentDir,env:{...process.env,OK_LOCK_KIND:`mcp-spawned`}}),p.on(`error`,e=>{m=e instanceof Error?e.message:String(e)}),p.unref()}catch(e){m=e instanceof Error?e.message:String(e)}}finally{try{s(f)}catch{}}let g=Date.now()+c;for(;Date.now()<g;){if(m){let e=a(d),t=e?` stderr:\n${e}`:``;throw Error(`spawn failed: ${m}${t}`)}await r(l);let e=uo(t(),n);if(e!==void 0)return so(`localhost`,e)}if(m){let e=a(d),t=e?` stderr:\n${e}`:``;throw Error(`spawn failed: ${m}${t}`)}throw Error(po(c,a(d)))}function vo(e,t){if(e.portOverride!==void 0)return lo(t);let n=e.readLock??(()=>Pe(e.lockDir)),r=e.isAlive??T,i=uo(n(),r);if(i!==void 0)return co(`localhost`,i)}async function yo(e,t={}){let n=t.stderr??process.stderr,r=t.requestTimeoutMs??12e4,i=t.createStdioTransport?t.createStdioTransport(t.stdin,t.stdout):new Li(t.stdin,t.stdout),a=t.createHttpTransport?t.createHttpTransport(new URL(e)):new ro(new URL(e),{fetch:io(r),...t.connectionId===void 0?{}:{requestInit:{headers:{[c]:t.connectionId}}}}),o=!1,s=async()=>{o||(o=!0,t.onclose?.(),await Promise.allSettled([i.close(),a.close()]))};i.onerror=e=>{n.write(`[mcp-shim] stdio error: ${e.message}\n`)},a.onerror=e=>{n.write(`[mcp-shim] HTTP transport error: ${e.message}\n`)},i.onclose=()=>{s()},a.onclose=()=>{s()};let l=Promise.resolve();i.onmessage=e=>{l=l.then(async()=>{try{await a.send(e)}catch(t){let r=mo(e);if(r===void 0){n.write(`[mcp-shim] failed to forward stdio notification: ${t instanceof Error?t.message:String(t)}\n`);return}await i.send(go(r,t)).catch(e=>{n.write(`[mcp-shim] failed to write stdio error response: ${e instanceof Error?e.message:String(e)}\n`)})}}).catch(e=>{n.write(`[mcp-shim] unexpected stdio forwarding failure: ${e instanceof Error?e.message:String(e)}\n`)})},a.onmessage=e=>{let t=ho(e);t&&a.setProtocolVersion?.(t),i.send(e).catch(e=>{n.write(`[mcp-shim] failed to write stdio response: ${e instanceof Error?e.message:String(e)}\n`)})};try{await a.start(),await i.start()}catch(e){throw await s(),e}return{close:s}}async function bo(e){let t=e.stderr??process.stderr,n=e.bridgeFn??yo,r=await _o(e),i=e.createConnectionId?.()??vt(),a=!1,o=(e.startKeepalive??Ri)({connectionId:i,resolveWsUrl:async()=>vo(e,r),log:e=>t.write(`[mcp-shim] keepalive: ${e}\n`)});t.write(`[mcp-shim] proxying stdio to ${r}\n`);let s;try{s=await n(r,{stderr:t,connectionId:i,onclose:()=>{a||(o.close(),process.exit(0))}})}catch(e){throw o.close(),e}let c=()=>{a=!0,o.close(),s.close().finally(()=>{process.exit(0)})};process.once(`SIGINT`,c),process.once(`SIGTERM`,c)}function xo(e){let t=P(e);for(;;){if(he(t))return t;let n=Qe(t);if(n===t)throw Error(`No Open Knowledge project found at or above ${e}. Pass an explicit \`cwd\` argument that points inside an OK project (a directory with a \`${oe}\`).`);t=n}}function So(e){try{let t=new URL(e);return t.protocol===`file:`?pt(t):void 0}catch{return}}async function Co(e){if(!e.getClientCapabilities()?.roots)return;let t;try{t=await e.listRoots()}catch(t){e.log?.(`listRoots fallback failed: ${t instanceof Error?t.message:String(t)}`);return}let n=t.roots??[];if(n.length!==1)return;let r=So(n[0].uri);return r===void 0&&e.log?.(`single root URI not usable as fs path: ${n[0].uri}`),r}async function wo(e,t){if(e!==void 0)return xo(e);let n=await t();if(n!==void 0)return xo(n);throw Error("`cwd` is required for tool calls against the global MCP server. Pass an absolute path inside an Open Knowledge project, or have the MCP client advertise a single root.")}async function To(e){let t=process.stderr,n=e.spawnTimeoutMs??ao(process.env.OK_MCP_SPAWN_TIMEOUT_MS),r=e.envAutoStart??process.env.OK_MCP_AUTOSTART,a=Be({startupCwd:e.startupCwd,startupConfig:e.startupConfig}),s=new S({name:o,version:Ie},{instructions:me({dir:`.`})}),c=vt(),l={current:{connectionId:c,displayName:c,colorSeed:c}},u=new Map,d=e=>{if(u.has(e))return;let n=ee(e),r=l.current,i=Ri({connectionId:c,displayName:r.displayName,clientName:r.clientInfo?.name??r.displayName,colorSeed:r.colorSeed,resolveWsUrl:async()=>vo({lockDir:n,contentDir:e},``),log:n=>t.write(`[mcp] keepalive[${e}]: ${n}\n`)});u.set(e,i)},f=()=>Co({getClientCapabilities:()=>s.server.getClientCapabilities(),listRoots:()=>s.server.listRoots(),log:e=>t.write(`[mcp] ${e}\n`)}),p=e=>wo(e,f),m=async e=>{let t;if(e===void 0){let e=await f();if(e===void 0)return;t=xo(e)}else t=xo(e);let i=await a(t),o=await _o({lockDir:ee(t),contentDir:h(i,t),envAutoStart:r,...n===void 0?{}:{timeoutMs:n}});return d(t),o.replace(/\/mcp$/,``)};s.server.oninitialized=()=>{let e=s.server.getClientVersion(),t=ce(e?.name,c);l.current={connectionId:c,clientInfo:e?{name:t,version:e.version}:void 0,displayName:t,colorSeed:t}},i(s,{serverUrl:m,resolveCwd:p,config:a,identityRef:l});let g=new Li,_=!1,te=async()=>{if(_)return;_=!0;for(let e of u.values())try{e.close()}catch(e){t.write(`[mcp] keepalive close error: ${e instanceof Error?e.message:String(e)}\n`)}u.clear();let e=await Promise.allSettled([s.close(),g.close()]);for(let n of e)if(n.status===`rejected`){let e=n.reason;t.write(`[mcp] shutdown close error: ${e instanceof Error?e.message:String(e)}\n`)}};await s.connect(g),t.write(`[mcp] global stdio server ready (per-call project routing)
59
- `);let v=()=>{te().finally(()=>{process.exit(0)})};return process.once(`SIGINT`,v),process.once(`SIGTERM`,v),{close:te}}function Eo(e){return new t(`mcp`).description(`Start MCP stdio server for project knowledge base`).option(`-p, --port <port>`,`Override per-call routing and proxy stdio to this HTTP MCP port`,void 0).action(async t=>{try{let n=e(),r=process.cwd();if(t.port!==void 0){let e=ao(process.env.OK_MCP_SPAWN_TIMEOUT_MS);await bo({lockDir:``,contentDir:``,portOverride:t.port,envAutoStart:process.env.OK_MCP_AUTOSTART,timeoutMs:e});return}await To({startupCwd:r,startupConfig:n})}catch(e){process.stderr.write(`MCP server failed to start: ${e instanceof Error?e.message:String(e)}\n`),process.exitCode=1}})}function Do(e){return new t(`preview`).description(`Show what content the watcher will track (read-only)`).action(async()=>{let{previewContent:t,formatPreviewBlock:n}=await import(`./preview-DCoA7FqK.mjs`),r=e(),i=process.cwd(),a=h(r,i),o;try{o=t({projectDir:i,contentDir:a})}catch(e){console.error(`Content preview failed: ${e instanceof Error?e.message:String(e)}`),process.exitCode=1;return}process.stdout.write(`${n(o,i)}\n`),o.totalCount===0&&o.warnings.length>0&&(process.exitCode=1)})}function Oo(e){return e==null?!1:e.includes(`--type=utility`)&&e.includes(`--utility-sub-type=node.mojom.NodeService`)}function ko(e,t=Date.now()){let n=new Date(e).getTime();if(Number.isNaN(n))return`—`;let r=t-n,i=Math.floor(r/1e3);if(i<60)return`${i}s`;let a=Math.floor(i/60);if(a<60)return`${a}m ago`;let o=Math.floor(a/60);return o<24?`${o}h ago`:`${Math.floor(o/24)}d ago`}function Ao(e,t,n,r,i,a){if(t.status===`missing`||t.status===`corrupt`)return null;let o=t.lock,s=null;if(n.status!==`missing`&&n.status!==`corrupt`){let e=n.lock;s={port:e.port,status:n.status,pid:e.pid,startedAt:e.startedAt,usage:a}}return{directory:o.worktreeRoot,server:{port:o.port,status:t.status,pid:o.pid,startedAt:o.startedAt,usage:i},ui:s,hostname:o.hostname,lockPath:t.lockPath,binary:r==null?null:di(r),command:r,isDesktop:Oo(r)}}function jo(e){return e.ui==null?!1:e.ui.status===`alive`||e.ui.status===`foreign-host`}function Mo(e){let t=e.server.status;return t===`alive`||t===`foreign-host`?e.isDesktop?`desktop`:t===`alive`?`running`:`foreign`:t===`dead-pid`&&jo(e)?`ui-orphan`:`stale`}const No=new Set([`running`,`desktop`,`foreign`,`ui-orphan`]);function Po(e){switch(e){case`running`:return U.default.green(e);case`desktop`:return U.default.blue(e);case`foreign`:return U.default.cyan(e);case`ui-orphan`:return U.default.magenta(e);case`stale`:return U.default.yellow(e)}}function Fo(e){return e==null?`—`:`${e.cpuPercent.toFixed(1)}% / ${e.memPercent.toFixed(1)}%`}function Io(e){return`${Fo(e.server.usage)} | ${Fo(e.ui?.usage??null)}`}function Lo(e){return`${e.server.port===0?`(starting)`:String(e.server.port)} / ${e.ui==null||e.ui.status===`dead-pid`?`—`:String(e.ui.port)}`}function Ro(e){if(e.length===0)return`No open-knowledge servers found.`;let t=[`DIRECTORY`,`PORTS (API/UI)`,`CPU/MEM (API | UI)`,`STATUS`,`PID`,`STARTED`,`BINARY`],n=e.map(e=>{let t=Mo(e),n=t===`ui-orphan`&&e.ui!=null?e.ui.pid:e.server.pid;return[e.directory,Lo(e),Io(e),t,String(n),ko(e.server.startedAt),e.binary??`—`]}),r=t.length,i=t.map(e=>e.length);for(let e of n)for(let t=0;t<r;t++)i[t]=Math.max(i[t]??0,(e[t]??``).length);let a=t.map((e,t)=>e.padEnd(i[t]??0)).join(` `).trimEnd(),o=e.map((e,t)=>{let a=n[t]??[],o=[];for(let t=0;t<r;t++){let n=(a[t]??``).padEnd(i[t]??0);if(t===3){let r=a[t]??``;n=Po(Mo(e))+` `.repeat(Math.max(0,(i[t]??0)-r.length))}o.push(n)}return o.join(` `).trimEnd()}),s=U.default.dim(`To stop a server: ok stop <port|pid|directory|all>`);return[a,...o,``,s].join(`
59
+ `);let v=()=>{te().finally(()=>{process.exit(0)})};return process.once(`SIGINT`,v),process.once(`SIGTERM`,v),{close:te}}function Eo(e){return new t(`mcp`).description(`Start MCP stdio server for project knowledge base`).option(`-p, --port <port>`,`Override per-call routing and proxy stdio to this HTTP MCP port`,void 0).action(async t=>{try{let n=e(),r=process.cwd();if(t.port!==void 0){let e=ao(process.env.OK_MCP_SPAWN_TIMEOUT_MS);await bo({lockDir:``,contentDir:``,portOverride:t.port,envAutoStart:process.env.OK_MCP_AUTOSTART,timeoutMs:e});return}await To({startupCwd:r,startupConfig:n})}catch(e){process.stderr.write(`MCP server failed to start: ${e instanceof Error?e.message:String(e)}\n`),process.exitCode=1}})}function Do(e){return new t(`preview`).description(`Show what content the watcher will track (read-only)`).action(async()=>{let{previewContent:t,formatPreviewBlock:n}=await import(`./preview-f1ZGdsVb.mjs`),r=e(),i=process.cwd(),a=h(r,i),o;try{o=t({projectDir:i,contentDir:a})}catch(e){console.error(`Content preview failed: ${e instanceof Error?e.message:String(e)}`),process.exitCode=1;return}process.stdout.write(`${n(o,i)}\n`),o.totalCount===0&&o.warnings.length>0&&(process.exitCode=1)})}function Oo(e){return e==null?!1:e.includes(`--type=utility`)&&e.includes(`--utility-sub-type=node.mojom.NodeService`)}function ko(e,t=Date.now()){let n=new Date(e).getTime();if(Number.isNaN(n))return`—`;let r=t-n,i=Math.floor(r/1e3);if(i<60)return`${i}s`;let a=Math.floor(i/60);if(a<60)return`${a}m ago`;let o=Math.floor(a/60);return o<24?`${o}h ago`:`${Math.floor(o/24)}d ago`}function Ao(e,t,n,r,i,a){if(t.status===`missing`||t.status===`corrupt`)return null;let o=t.lock,s=null;if(n.status!==`missing`&&n.status!==`corrupt`){let e=n.lock;s={port:e.port,status:n.status,pid:e.pid,startedAt:e.startedAt,usage:a}}return{directory:o.worktreeRoot,server:{port:o.port,status:t.status,pid:o.pid,startedAt:o.startedAt,usage:i},ui:s,hostname:o.hostname,lockPath:t.lockPath,binary:r==null?null:di(r),command:r,isDesktop:Oo(r)}}function jo(e){return e.ui==null?!1:e.ui.status===`alive`||e.ui.status===`foreign-host`}function Mo(e){let t=e.server.status;return t===`alive`||t===`foreign-host`?e.isDesktop?`desktop`:t===`alive`?`running`:`foreign`:t===`dead-pid`&&jo(e)?`ui-orphan`:`stale`}const No=new Set([`running`,`desktop`,`foreign`,`ui-orphan`]);function Po(e){switch(e){case`running`:return U.default.green(e);case`desktop`:return U.default.blue(e);case`foreign`:return U.default.cyan(e);case`ui-orphan`:return U.default.magenta(e);case`stale`:return U.default.yellow(e)}}function Fo(e){return e==null?`—`:`${e.cpuPercent.toFixed(1)}% / ${e.memPercent.toFixed(1)}%`}function Io(e){return`${Fo(e.server.usage)} | ${Fo(e.ui?.usage??null)}`}function Lo(e){return`${e.server.port===0?`(starting)`:String(e.server.port)} / ${e.ui==null||e.ui.status===`dead-pid`?`—`:String(e.ui.port)}`}function Ro(e){if(e.length===0)return`No open-knowledge servers found.`;let t=[`DIRECTORY`,`PORTS (API/UI)`,`CPU/MEM (API | UI)`,`STATUS`,`PID`,`STARTED`,`BINARY`],n=e.map(e=>{let t=Mo(e),n=t===`ui-orphan`&&e.ui!=null?e.ui.pid:e.server.pid;return[e.directory,Lo(e),Io(e),t,String(n),ko(e.server.startedAt),e.binary??`—`]}),r=t.length,i=t.map(e=>e.length);for(let e of n)for(let t=0;t<r;t++)i[t]=Math.max(i[t]??0,(e[t]??``).length);let a=t.map((e,t)=>e.padEnd(i[t]??0)).join(` `).trimEnd(),o=e.map((e,t)=>{let a=n[t]??[],o=[];for(let t=0;t<r;t++){let n=(a[t]??``).padEnd(i[t]??0);if(t===3){let r=a[t]??``;n=Po(Mo(e))+` `.repeat(Math.max(0,(i[t]??0)-r.length))}o.push(n)}return o.join(` `).trimEnd()}),s=U.default.dim(`To stop a server: ok stop <port|pid|directory|all>`);return[a,...o,``,s].join(`
60
60
  `)}async function zo(e={}){let t=e.discover??gi,n=e.inspect??V,r=e.log??(e=>console.log(e)),i=e.resolveCommand??fi,a=e.resolveUsage??pi,o=await t(),s=[];for(let e of o){let t=n(e,`server`),r=n(e,`ui`),o=Ao(e,t,r,t.status===`missing`||t.status===`corrupt`?null:i(t.lock.pid),t.status===`missing`||t.status===`corrupt`?null:a(t.lock.pid),r.status===`missing`||r.status===`corrupt`?null:a(r.lock.pid));o!=null&&s.push(o)}if(e.json){let e=s.map(e=>({...e,displayStatus:Mo(e)}));r(JSON.stringify(e,null,2));return}r(Ro(e.all?s:s.filter(e=>No.has(Mo(e)))))}function Bo(){return new t(`ps`).description(`List all running open-knowledge servers`).argument(`[modifier]`,`"all" to include stale (dead-pid) entries`).option(`--all`,`Include stale (dead-pid) entries (foreign-host shows by default)`).option(`--json`,`Emit structured JSON (always includes all statuses)`).action(async(e,t)=>{await zo({all:t.all===!0||e===`all`,json:t.json===!0})})}function X(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function Vo(e,t,n=process.cwd()){let r=e.op??`sync`,i=Pe(ie(n));if(i&&i.port>0){let t=`http://127.0.0.1:${i.port}/api/sync/trigger`;e.json||process.stderr.write(`Triggering ${r} via running server (port ${i.port})\n`);try{let n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({op:r})});if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(e.title??e.error??e.message??`Server responded with ${n.status}`)}X(e.json,{type:`triggered`,op:r,port:i.port}),e.json||process.stderr.write(`✓ ${r} triggered\n`);return}catch(t){let n=t instanceof Error?t.message:String(t);e.json||process.stderr.write(`Server trigger failed (${n}), running directly\n`)}}e.json||process.stderr.write(`Running ${r} directly (no live server)\n`);let a=Le({baseDir:n});if(r===`sync`||r===`pull`){X(e.json,{type:`step`,step:`pull`});let t=await a.pull();X(e.json,{type:`pull`,summary:t.summary}),e.json||process.stderr.write(` pull: ${t.summary.changes} changes\n`)}(r===`sync`||r===`push`)&&(X(e.json,{type:`step`,step:`push`}),await a.push(),X(e.json,{type:`push`,ok:!0}),e.json||process.stderr.write(` push: ok
61
61
  `)),X(e.json,{type:`complete`,op:r}),e.json||process.stderr.write(`✓ ${r} complete\n`)}function Ho(e){return new t(`sync`).description(`Commit, pull, and push to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Vo({json:t.json,op:`sync`},e())}catch(e){let n=e instanceof Error?e.message:String(e);t.json?process.stdout.write(`${JSON.stringify({type:`error`,message:n})}\n`):process.stderr.write(`✗ sync failed: ${n}\n`),process.exit(1)}})}function Uo(e){return new t(`pull`).description(`Pull changes from the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Vo({json:t.json,op:`pull`},e())}catch(e){let n=e instanceof Error?e.message:String(e);t.json?process.stdout.write(`${JSON.stringify({type:`error`,message:n})}\n`):process.stderr.write(`✗ pull failed: ${n}\n`),process.exit(1)}})}function Wo(e){return new t(`push`).description(`Push commits to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Vo({json:t.json,op:`push`},e())}catch(e){let n=e instanceof Error?e.message:String(e);t.json?process.stdout.write(`${JSON.stringify({type:`error`,message:n})}\n`):process.stderr.write(`✗ push failed: ${n}\n`),process.exit(1)}})}function Go(e){return typeof e==`string`&&f.includes(e)}async function Ko(e={}){let t=P(e.cwd??process.cwd()),r=e.pack??`knowledge-base`;if(!x[r])return{status:`failed`,message:`${k(`Error:`)} Unknown pack "${r}". Available: ${f.join(`, `)}`,exitCode:1};let i;try{i=await v({projectDir:t,rootDir:e.root,packId:r})}catch(e){return e instanceof u?{status:`prerequisite-missing`,message:`${k(`Error:`)} ${e.message}`,exitCode:1}:{status:`failed`,message:`${k(`Error:`)} ${e instanceof Error?e.message:String(e)}`,exitCode:1}}if(i.created.length===0){let t=x[r].name;if(e.personalTemplates&&!e.dryRun){let e=_();if(e.errors.length>0){let n=e.errors.map(e=>` ${A(`!`)} ${e.path}: ${e.error}`);return{status:`failed`,message:[`${O(`Your ${t} pack is already seeded.`)}`,`${A(`Personal templates: some writes failed:`)}`,...n].join(`
62
62
  `),plan:i,exitCode:1}}let n=e.written.length;if(n>0)return{status:`applied`,message:`${O(`Your ${t} pack is already seeded.`)}\n${O(`✓ Wrote ${n} personal template${n===1?``:`s`}`)} ${D(`to ~/.ok/templates/`)}`,plan:i,exitCode:0}}return{status:`no-op`,message:`${O(`Your ${t} pack is already seeded.`)}\n${D(`Nothing to do.`)}`,plan:i,exitCode:0}}if(e.dryRun)return{status:`dry-run`,message:`${j(`Plan (dry-run — no changes made):`)}\n\n${Jo(i,t)}`,plan:i,exitCode:0};if(!e.yes&&!await Yo(`${j(`Plan:`)}\n\n${Jo(i,t)}\n\n${j(`Apply?`)} ${D(`[Y/n] `)}`,e.confirmStream))return{status:`cancelled`,message:D(`Cancelled.`),plan:i,exitCode:0};let a=await n(i,{projectDir:t,packId:r});if(a.errors.length>0){let e=a.errors.map(e=>` ${k(`✗`)} ${e.path}: ${e.error}`);return{status:`failed`,message:[`${A(`Applied`)} ${a.applied} entries, ${A(String(a.errors.length))} error(s):`,...e].join(`
@@ -0,0 +1,2 @@
1
+ import"./dist-BFaejI07.mjs";var e=`0.5.0-beta.15`;const t=`config.yml`,n=e;export{n,t};
2
+ //# sourceMappingURL=constants-BKcZ-SZr.mjs.map
package/dist/index.d.mts CHANGED
@@ -62,7 +62,7 @@ interface UserMcpConfigsOptions {
62
62
  home?: string;
63
63
  }
64
64
  declare function writeUserMcpConfigs(opts: UserMcpConfigsOptions): Promise<EditorMcpResult[]>;
65
- declare function readExistingMcpEntry(target: EditorMcpTarget, cwd: string, home?: string): Record<string, unknown> | null;
65
+ declare function readExistingMcpEntry(target: EditorMcpTarget, cwd: string, home?: string, configPathOverride?: string): Record<string, unknown> | null;
66
66
  declare function detectInstalledEditors(cwd: string, home?: string): EditorId[];
67
67
  //#endregion
68
68
  //#region src/config/loader.d.ts
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{c as e,d as t,f as n,h as r,i,l as a,m as o,p as s,t as c}from"./init-DoDYKuWt.mjs";import{n as l}from"./loader-DwY1uRWB.mjs";import{n as u}from"./preview-D0Cwj9ak.mjs";import{t as d}from"./src-T_WN5ziD.mjs";export{t as ALL_EDITOR_IDS,n as EDITOR_LABELS,s as EDITOR_TARGETS,c as detectInstalledEditors,r as initContent,l as loadConfig,u as previewContent,i as readExistingMcpEntry,o as resolveProjectRoot,e as writeEditorMcpConfig,d as writeProjectAiIntegrations,a as writeUserMcpConfigs};
1
+ import{c as e,d as t,f as n,h as r,i,l as a,m as o,p as s,t as c}from"./init-JeGcMd-V.mjs";import{n as l}from"./loader-ZLKIXjJM.mjs";import{n as u}from"./preview-BIVzSnXG.mjs";import{t as d}from"./src-DK12uoo0.mjs";export{t as ALL_EDITOR_IDS,n as EDITOR_LABELS,s as EDITOR_TARGETS,c as detectInstalledEditors,r as initContent,l as loadConfig,u as previewContent,i as readExistingMcpEntry,o as resolveProjectRoot,e as writeEditorMcpConfig,d as writeProjectAiIntegrations,a as writeUserMcpConfigs};
@@ -0,0 +1 @@
1
+ import{o as e}from"./init-JeGcMd-V.mjs";export{e as runInit};
@@ -1,4 +1,4 @@
1
- import{i as e,o as t,t as n}from"./chunk-FK9Q3tQk.mjs";import{r,t as i}from"./esm-CEs3LWY3.mjs";import{$r as a,D as o,F as s,Gn as c,It as l,Pt as u,Qr as d,ai as f,an as p,di as m,gi as h,hi as g,ii as _,in as v,on as y,pn as b,ri as x,si as S,un as C}from"./dist-BFaejI07.mjs";import{n as w,t as ee}from"./constants-BMZzAuZK.mjs";import{t as T}from"./is-object-DF0ZeuvD.mjs";import{i as E,o as D,r as te,s as ne,t as O}from"./colors-BNufdynn.mjs";import{t as re}from"./preview-D0Cwj9ak.mjs";import{execFileSync as ie}from"node:child_process";import k,{basename as A,dirname as j,isAbsolute as ae,join as M,posix as oe,relative as N,resolve as P,sep as se,win32 as ce}from"node:path";import{cpSync as le,existsSync as F,lstatSync as ue,mkdirSync as I,readFileSync as de,realpathSync as fe,rmSync as pe,writeFileSync as L}from"node:fs";import R from"node:process";import{homedir as z}from"node:os";import{AsyncLocalStorage as me,AsyncResource as he}from"node:async_hooks";import{stripVTControlCharacters as ge,styleText as B}from"node:util";import*as _e from"node:readline";import{randomUUID as ve}from"node:crypto";import{createServer as ye,request as be}from"node:http";function xe(){return R.platform.startsWith(`win`)?!!R.env.CI||!!R.env.WT_SESSION||!!R.env.TERMINUS_SUBLIME||R.env.ConEmuTask===`{cmd::Cmder}`||R.env.TERM_PROGRAM===`Terminus-Sublime`||R.env.TERM_PROGRAM===`vscode`||R.env.TERM===`xterm-256color`||R.env.TERM===`alacritty`||R.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:R.env.TERM!==`linux`}const Se={circleQuestionMark:`(?)`,questionMarkPrefix:`(?)`,square:`█`,squareDarkShade:`▓`,squareMediumShade:`▒`,squareLightShade:`░`,squareTop:`▀`,squareBottom:`▄`,squareLeft:`▌`,squareRight:`▐`,squareCenter:`■`,bullet:`●`,dot:`․`,ellipsis:`…`,pointerSmall:`›`,triangleUp:`▲`,triangleUpSmall:`▴`,triangleDown:`▼`,triangleDownSmall:`▾`,triangleLeftSmall:`◂`,triangleRightSmall:`▸`,home:`⌂`,heart:`♥`,musicNote:`♪`,musicNoteBeamed:`♫`,arrowUp:`↑`,arrowDown:`↓`,arrowLeft:`←`,arrowRight:`→`,arrowLeftRight:`↔`,arrowUpDown:`↕`,almostEqual:`≈`,notEqual:`≠`,lessOrEqual:`≤`,greaterOrEqual:`≥`,identical:`≡`,infinity:`∞`,subscriptZero:`₀`,subscriptOne:`₁`,subscriptTwo:`₂`,subscriptThree:`₃`,subscriptFour:`₄`,subscriptFive:`₅`,subscriptSix:`₆`,subscriptSeven:`₇`,subscriptEight:`₈`,subscriptNine:`₉`,oneHalf:`½`,oneThird:`⅓`,oneQuarter:`¼`,oneFifth:`⅕`,oneSixth:`⅙`,oneEighth:`⅛`,twoThirds:`⅔`,twoFifths:`⅖`,threeQuarters:`¾`,threeFifths:`⅗`,threeEighths:`⅜`,fourFifths:`⅘`,fiveSixths:`⅚`,fiveEighths:`⅝`,sevenEighths:`⅞`,line:`─`,lineBold:`━`,lineDouble:`═`,lineDashed0:`┄`,lineDashed1:`┅`,lineDashed2:`┈`,lineDashed3:`┉`,lineDashed4:`╌`,lineDashed5:`╍`,lineDashed6:`╴`,lineDashed7:`╶`,lineDashed8:`╸`,lineDashed9:`╺`,lineDashed10:`╼`,lineDashed11:`╾`,lineDashed12:`−`,lineDashed13:`–`,lineDashed14:`‐`,lineDashed15:`⁃`,lineVertical:`│`,lineVerticalBold:`┃`,lineVerticalDouble:`║`,lineVerticalDashed0:`┆`,lineVerticalDashed1:`┇`,lineVerticalDashed2:`┊`,lineVerticalDashed3:`┋`,lineVerticalDashed4:`╎`,lineVerticalDashed5:`╏`,lineVerticalDashed6:`╵`,lineVerticalDashed7:`╷`,lineVerticalDashed8:`╹`,lineVerticalDashed9:`╻`,lineVerticalDashed10:`╽`,lineVerticalDashed11:`╿`,lineDownLeft:`┐`,lineDownLeftArc:`╮`,lineDownBoldLeftBold:`┓`,lineDownBoldLeft:`┒`,lineDownLeftBold:`┑`,lineDownDoubleLeftDouble:`╗`,lineDownDoubleLeft:`╖`,lineDownLeftDouble:`╕`,lineDownRight:`┌`,lineDownRightArc:`╭`,lineDownBoldRightBold:`┏`,lineDownBoldRight:`┎`,lineDownRightBold:`┍`,lineDownDoubleRightDouble:`╔`,lineDownDoubleRight:`╓`,lineDownRightDouble:`╒`,lineUpLeft:`┘`,lineUpLeftArc:`╯`,lineUpBoldLeftBold:`┛`,lineUpBoldLeft:`┚`,lineUpLeftBold:`┙`,lineUpDoubleLeftDouble:`╝`,lineUpDoubleLeft:`╜`,lineUpLeftDouble:`╛`,lineUpRight:`└`,lineUpRightArc:`╰`,lineUpBoldRightBold:`┗`,lineUpBoldRight:`┖`,lineUpRightBold:`┕`,lineUpDoubleRightDouble:`╚`,lineUpDoubleRight:`╙`,lineUpRightDouble:`╘`,lineUpDownLeft:`┤`,lineUpBoldDownBoldLeftBold:`┫`,lineUpBoldDownBoldLeft:`┨`,lineUpDownLeftBold:`┥`,lineUpBoldDownLeftBold:`┩`,lineUpDownBoldLeftBold:`┪`,lineUpDownBoldLeft:`┧`,lineUpBoldDownLeft:`┦`,lineUpDoubleDownDoubleLeftDouble:`╣`,lineUpDoubleDownDoubleLeft:`╢`,lineUpDownLeftDouble:`╡`,lineUpDownRight:`├`,lineUpBoldDownBoldRightBold:`┣`,lineUpBoldDownBoldRight:`┠`,lineUpDownRightBold:`┝`,lineUpBoldDownRightBold:`┡`,lineUpDownBoldRightBold:`┢`,lineUpDownBoldRight:`┟`,lineUpBoldDownRight:`┞`,lineUpDoubleDownDoubleRightDouble:`╠`,lineUpDoubleDownDoubleRight:`╟`,lineUpDownRightDouble:`╞`,lineDownLeftRight:`┬`,lineDownBoldLeftBoldRightBold:`┳`,lineDownLeftBoldRightBold:`┯`,lineDownBoldLeftRight:`┰`,lineDownBoldLeftBoldRight:`┱`,lineDownBoldLeftRightBold:`┲`,lineDownLeftRightBold:`┮`,lineDownLeftBoldRight:`┭`,lineDownDoubleLeftDoubleRightDouble:`╦`,lineDownDoubleLeftRight:`╥`,lineDownLeftDoubleRightDouble:`╤`,lineUpLeftRight:`┴`,lineUpBoldLeftBoldRightBold:`┻`,lineUpLeftBoldRightBold:`┷`,lineUpBoldLeftRight:`┸`,lineUpBoldLeftBoldRight:`┹`,lineUpBoldLeftRightBold:`┺`,lineUpLeftRightBold:`┶`,lineUpLeftBoldRight:`┵`,lineUpDoubleLeftDoubleRightDouble:`╩`,lineUpDoubleLeftRight:`╨`,lineUpLeftDoubleRightDouble:`╧`,lineUpDownLeftRight:`┼`,lineUpBoldDownBoldLeftBoldRightBold:`╋`,lineUpDownBoldLeftBoldRightBold:`╈`,lineUpBoldDownLeftBoldRightBold:`╇`,lineUpBoldDownBoldLeftRightBold:`╊`,lineUpBoldDownBoldLeftBoldRight:`╉`,lineUpBoldDownLeftRight:`╀`,lineUpDownBoldLeftRight:`╁`,lineUpDownLeftBoldRight:`┽`,lineUpDownLeftRightBold:`┾`,lineUpBoldDownBoldLeftRight:`╂`,lineUpDownLeftBoldRightBold:`┿`,lineUpBoldDownLeftBoldRight:`╃`,lineUpBoldDownLeftRightBold:`╄`,lineUpDownBoldLeftBoldRight:`╅`,lineUpDownBoldLeftRightBold:`╆`,lineUpDoubleDownDoubleLeftDoubleRightDouble:`╬`,lineUpDoubleDownDoubleLeftRight:`╫`,lineUpDownLeftDoubleRightDouble:`╪`,lineCross:`╳`,lineBackslash:`╲`,lineSlash:`╱`},Ce={tick:`✔`,info:`ℹ`,warning:`⚠`,cross:`✘`,squareSmall:`◻`,squareSmallFilled:`◼`,circle:`◯`,circleFilled:`◉`,circleDotted:`◌`,circleDouble:`◎`,circleCircle:`ⓞ`,circleCross:`ⓧ`,circlePipe:`Ⓘ`,radioOn:`◉`,radioOff:`◯`,checkboxOn:`☒`,checkboxOff:`☐`,checkboxCircleOn:`ⓧ`,checkboxCircleOff:`Ⓘ`,pointer:`❯`,triangleUpOutline:`△`,triangleLeft:`◀`,triangleRight:`▶`,lozenge:`◆`,lozengeOutline:`◇`,hamburger:`☰`,smiley:`㋡`,mustache:`෴`,star:`★`,play:`▶`,nodejs:`⬢`,oneSeventh:`⅐`,oneNinth:`⅑`,oneTenth:`⅒`},we={tick:`√`,info:`i`,warning:`‼`,cross:`×`,squareSmall:`□`,squareSmallFilled:`■`,circle:`( )`,circleFilled:`(*)`,circleDotted:`( )`,circleDouble:`( )`,circleCircle:`(○)`,circleCross:`(×)`,circlePipe:`(│)`,radioOn:`(*)`,radioOff:`( )`,checkboxOn:`[×]`,checkboxOff:`[ ]`,checkboxCircleOn:`(×)`,checkboxCircleOff:`( )`,pointer:`>`,triangleUpOutline:`∆`,triangleLeft:`◄`,triangleRight:`►`,lozenge:`♦`,lozengeOutline:`◊`,hamburger:`≡`,smiley:`☺`,mustache:`┌─┐`,star:`✶`,play:`►`,nodejs:`♦`,oneSeventh:`1/7`,oneNinth:`1/9`,oneTenth:`1/10`},Te={...Se,...Ce},Ee={...Se,...we},V=xe()?Te:Ee;Object.entries(Ce);var De=n(((t,n)=>{n.exports=i;function r(t){let n={defaultWidth:0,output:process.stdout,tty:e(`tty`)};return t?(Object.keys(n).forEach(function(e){t[e]||(t[e]=n[e])}),t):n}function i(e){let t=r(e);if(t.output.getWindowSize)return t.output.getWindowSize()[0]||t.defaultWidth;if(t.tty.getWindowSize)return t.tty.getWindowSize()[1]||t.defaultWidth;if(t.output.columns)return t.output.columns;if(process.env.CLI_WIDTH){let e=parseInt(process.env.CLI_WIDTH,10);if(!isNaN(e)&&e!==0)return e}return t.defaultWidth}}));const Oe=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return t=>{let n=0;for(e.lastIndex=0;e.test(t);)n+=1;return t.length-n}})(),ke=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,Ae=e=>e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141,je=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,Me=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Ne=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/uy,Pe=/\t{1,1000}/y,Fe=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/uy,Ie=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Le=/\p{M}+/gu,Re={limit:1/0,ellipsis:``},ze=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??``,a=t?.ellipsisWidth??(i?ze(i,Re,n).width:0),o=n.controlWidth??0,s=n.tabWidth??8,c=n.emojiWidth??2,l=n.regularWidth??1,u=n.wideWidth??2,d=[[Ie,l],[je,0],[Me,o],[Pe,s],[Fe,c],[Ne,u]],f=0,p=0,m=e.length,h=0,g=!1,_=m,v=Math.max(0,r-a),y=0,b=0,x=0,S=0;outer:for(;;){if(b>y||p>=m&&p>f){let t=e.slice(y,b)||e.slice(f,p);h=0;for(let e of t.replaceAll(Le,``)){let t=e.codePointAt(0)||0;if(S=ke(t)?2:Ae(t)?u:l,x+S>v&&(_=Math.min(_,Math.max(y,f)+h)),x+S>r){g=!0;break outer}h+=e.length,x+=S}y=b=0}if(p>=m)break outer;for(let t=0,n=d.length;t<n;t++){let[n,i]=d[t];if(n.lastIndex=p,n.test(e)){if(h=n===Ne?Oe(e.slice(p,n.lastIndex)):n===Fe?1:n.lastIndex-p,S=h*i,x+S>v&&(_=Math.min(_,p+Math.floor((v-x)/i))),x+S>r){g=!0;break outer}x+=S,y=f,b=p,p=f=n.lastIndex;continue outer}}p+=1}return{width:g?v:x,index:g?_:m,truncated:g,ellipsed:g&&r>=a}},Be={limit:1/0,ellipsis:``,ellipsisWidth:0},H=(e,t={})=>ze(e,Be,t).width,Ve=`]8;;`,He=RegExp(`(?:\\[(?<code>\\d+)m|\\${Ve}(?<uri>.*))`,`y`),Ue=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},We=e=>`[${e}m`,Ge=e=>`${Ve}${e}`,Ke=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,a=!1,o=e.at(-1),s=o===void 0?0:H(o),c=r.next(),l=r.next(),u=0;for(;!c.done;){let o=c.value,d=H(o);s+d<=n?e[e.length-1]+=o:(e.push(o),s=0),(o===`\x1B`||o===`›`)&&(i=!0,a=t.startsWith(Ve,u+1)),i?a?o===`\x07`&&(i=!1,a=!1):o===`m`&&(i=!1):(s+=d,s===n&&!l.done&&(e.push(``),s=0)),c=l,l=r.next(),u+=o.length}o=e.at(-1),!s&&o!==void 0&&o.length&&e.length>1&&(e[e.length-2]+=e.pop())},qe=e=>{let t=e.split(` `),n=t.length;for(;n&&!H(t[n-1]);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},Je=(e,t,n={})=>{if(n.trim!==!1&&e.trim()===``)return``;let r=``,i,a,o=e.split(` `),s=[``],c=0;for(let e=0;e<o.length;e++){let r=o[e];if(n.trim!==!1){let e=s.at(-1)??``,t=e.trimStart();e.length!==t.length&&(s[s.length-1]=t,c=H(t))}e!==0&&(c>=t&&(n.wordWrap===!1||n.trim===!1)&&(s.push(``),c=0),(c||n.trim===!1)&&(s[s.length-1]+=` `,c++));let i=H(r);if(n.hard&&i>t){let e=t-c,n=1+Math.floor((i-e-1)/t);Math.floor((i-1)/t)<n&&s.push(``),Ke(s,r,t),c=H(s.at(-1)??``);continue}if(c+i>t&&c&&i){if(n.wordWrap===!1&&c<t){Ke(s,r,t),c=H(s.at(-1)??``);continue}s.push(``),c=0}if(c+i>t&&n.wordWrap===!1){Ke(s,r,t),c=H(s.at(-1)??``);continue}s[s.length-1]+=r,c+=i}n.trim!==!1&&(s=s.map(e=>qe(e)));let l=s.join(`
1
+ import{i as e,o as t,t as n}from"./chunk-FK9Q3tQk.mjs";import{r,t as i}from"./esm-CEs3LWY3.mjs";import{$r as a,D as o,F as s,Gn as c,It as l,Pt as u,Qr as d,ai as f,an as p,di as m,gi as h,hi as g,ii as _,in as v,on as y,pn as b,ri as x,si as S,un as C}from"./dist-BFaejI07.mjs";import{n as w,t as ee}from"./constants-BKcZ-SZr.mjs";import{t as T}from"./is-object-DF0ZeuvD.mjs";import{i as E,o as D,r as te,s as ne,t as O}from"./colors-BNufdynn.mjs";import{t as re}from"./preview-BIVzSnXG.mjs";import{execFileSync as ie}from"node:child_process";import k,{basename as A,dirname as j,isAbsolute as ae,join as M,posix as oe,relative as N,resolve as P,sep as se,win32 as ce}from"node:path";import{cpSync as le,existsSync as F,lstatSync as ue,mkdirSync as I,readFileSync as de,realpathSync as fe,rmSync as pe,writeFileSync as L}from"node:fs";import R from"node:process";import{homedir as z}from"node:os";import{AsyncLocalStorage as me,AsyncResource as he}from"node:async_hooks";import{stripVTControlCharacters as ge,styleText as B}from"node:util";import*as _e from"node:readline";import{randomUUID as ve}from"node:crypto";import{createServer as ye,request as be}from"node:http";function xe(){return R.platform.startsWith(`win`)?!!R.env.CI||!!R.env.WT_SESSION||!!R.env.TERMINUS_SUBLIME||R.env.ConEmuTask===`{cmd::Cmder}`||R.env.TERM_PROGRAM===`Terminus-Sublime`||R.env.TERM_PROGRAM===`vscode`||R.env.TERM===`xterm-256color`||R.env.TERM===`alacritty`||R.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:R.env.TERM!==`linux`}const Se={circleQuestionMark:`(?)`,questionMarkPrefix:`(?)`,square:`█`,squareDarkShade:`▓`,squareMediumShade:`▒`,squareLightShade:`░`,squareTop:`▀`,squareBottom:`▄`,squareLeft:`▌`,squareRight:`▐`,squareCenter:`■`,bullet:`●`,dot:`․`,ellipsis:`…`,pointerSmall:`›`,triangleUp:`▲`,triangleUpSmall:`▴`,triangleDown:`▼`,triangleDownSmall:`▾`,triangleLeftSmall:`◂`,triangleRightSmall:`▸`,home:`⌂`,heart:`♥`,musicNote:`♪`,musicNoteBeamed:`♫`,arrowUp:`↑`,arrowDown:`↓`,arrowLeft:`←`,arrowRight:`→`,arrowLeftRight:`↔`,arrowUpDown:`↕`,almostEqual:`≈`,notEqual:`≠`,lessOrEqual:`≤`,greaterOrEqual:`≥`,identical:`≡`,infinity:`∞`,subscriptZero:`₀`,subscriptOne:`₁`,subscriptTwo:`₂`,subscriptThree:`₃`,subscriptFour:`₄`,subscriptFive:`₅`,subscriptSix:`₆`,subscriptSeven:`₇`,subscriptEight:`₈`,subscriptNine:`₉`,oneHalf:`½`,oneThird:`⅓`,oneQuarter:`¼`,oneFifth:`⅕`,oneSixth:`⅙`,oneEighth:`⅛`,twoThirds:`⅔`,twoFifths:`⅖`,threeQuarters:`¾`,threeFifths:`⅗`,threeEighths:`⅜`,fourFifths:`⅘`,fiveSixths:`⅚`,fiveEighths:`⅝`,sevenEighths:`⅞`,line:`─`,lineBold:`━`,lineDouble:`═`,lineDashed0:`┄`,lineDashed1:`┅`,lineDashed2:`┈`,lineDashed3:`┉`,lineDashed4:`╌`,lineDashed5:`╍`,lineDashed6:`╴`,lineDashed7:`╶`,lineDashed8:`╸`,lineDashed9:`╺`,lineDashed10:`╼`,lineDashed11:`╾`,lineDashed12:`−`,lineDashed13:`–`,lineDashed14:`‐`,lineDashed15:`⁃`,lineVertical:`│`,lineVerticalBold:`┃`,lineVerticalDouble:`║`,lineVerticalDashed0:`┆`,lineVerticalDashed1:`┇`,lineVerticalDashed2:`┊`,lineVerticalDashed3:`┋`,lineVerticalDashed4:`╎`,lineVerticalDashed5:`╏`,lineVerticalDashed6:`╵`,lineVerticalDashed7:`╷`,lineVerticalDashed8:`╹`,lineVerticalDashed9:`╻`,lineVerticalDashed10:`╽`,lineVerticalDashed11:`╿`,lineDownLeft:`┐`,lineDownLeftArc:`╮`,lineDownBoldLeftBold:`┓`,lineDownBoldLeft:`┒`,lineDownLeftBold:`┑`,lineDownDoubleLeftDouble:`╗`,lineDownDoubleLeft:`╖`,lineDownLeftDouble:`╕`,lineDownRight:`┌`,lineDownRightArc:`╭`,lineDownBoldRightBold:`┏`,lineDownBoldRight:`┎`,lineDownRightBold:`┍`,lineDownDoubleRightDouble:`╔`,lineDownDoubleRight:`╓`,lineDownRightDouble:`╒`,lineUpLeft:`┘`,lineUpLeftArc:`╯`,lineUpBoldLeftBold:`┛`,lineUpBoldLeft:`┚`,lineUpLeftBold:`┙`,lineUpDoubleLeftDouble:`╝`,lineUpDoubleLeft:`╜`,lineUpLeftDouble:`╛`,lineUpRight:`└`,lineUpRightArc:`╰`,lineUpBoldRightBold:`┗`,lineUpBoldRight:`┖`,lineUpRightBold:`┕`,lineUpDoubleRightDouble:`╚`,lineUpDoubleRight:`╙`,lineUpRightDouble:`╘`,lineUpDownLeft:`┤`,lineUpBoldDownBoldLeftBold:`┫`,lineUpBoldDownBoldLeft:`┨`,lineUpDownLeftBold:`┥`,lineUpBoldDownLeftBold:`┩`,lineUpDownBoldLeftBold:`┪`,lineUpDownBoldLeft:`┧`,lineUpBoldDownLeft:`┦`,lineUpDoubleDownDoubleLeftDouble:`╣`,lineUpDoubleDownDoubleLeft:`╢`,lineUpDownLeftDouble:`╡`,lineUpDownRight:`├`,lineUpBoldDownBoldRightBold:`┣`,lineUpBoldDownBoldRight:`┠`,lineUpDownRightBold:`┝`,lineUpBoldDownRightBold:`┡`,lineUpDownBoldRightBold:`┢`,lineUpDownBoldRight:`┟`,lineUpBoldDownRight:`┞`,lineUpDoubleDownDoubleRightDouble:`╠`,lineUpDoubleDownDoubleRight:`╟`,lineUpDownRightDouble:`╞`,lineDownLeftRight:`┬`,lineDownBoldLeftBoldRightBold:`┳`,lineDownLeftBoldRightBold:`┯`,lineDownBoldLeftRight:`┰`,lineDownBoldLeftBoldRight:`┱`,lineDownBoldLeftRightBold:`┲`,lineDownLeftRightBold:`┮`,lineDownLeftBoldRight:`┭`,lineDownDoubleLeftDoubleRightDouble:`╦`,lineDownDoubleLeftRight:`╥`,lineDownLeftDoubleRightDouble:`╤`,lineUpLeftRight:`┴`,lineUpBoldLeftBoldRightBold:`┻`,lineUpLeftBoldRightBold:`┷`,lineUpBoldLeftRight:`┸`,lineUpBoldLeftBoldRight:`┹`,lineUpBoldLeftRightBold:`┺`,lineUpLeftRightBold:`┶`,lineUpLeftBoldRight:`┵`,lineUpDoubleLeftDoubleRightDouble:`╩`,lineUpDoubleLeftRight:`╨`,lineUpLeftDoubleRightDouble:`╧`,lineUpDownLeftRight:`┼`,lineUpBoldDownBoldLeftBoldRightBold:`╋`,lineUpDownBoldLeftBoldRightBold:`╈`,lineUpBoldDownLeftBoldRightBold:`╇`,lineUpBoldDownBoldLeftRightBold:`╊`,lineUpBoldDownBoldLeftBoldRight:`╉`,lineUpBoldDownLeftRight:`╀`,lineUpDownBoldLeftRight:`╁`,lineUpDownLeftBoldRight:`┽`,lineUpDownLeftRightBold:`┾`,lineUpBoldDownBoldLeftRight:`╂`,lineUpDownLeftBoldRightBold:`┿`,lineUpBoldDownLeftBoldRight:`╃`,lineUpBoldDownLeftRightBold:`╄`,lineUpDownBoldLeftBoldRight:`╅`,lineUpDownBoldLeftRightBold:`╆`,lineUpDoubleDownDoubleLeftDoubleRightDouble:`╬`,lineUpDoubleDownDoubleLeftRight:`╫`,lineUpDownLeftDoubleRightDouble:`╪`,lineCross:`╳`,lineBackslash:`╲`,lineSlash:`╱`},Ce={tick:`✔`,info:`ℹ`,warning:`⚠`,cross:`✘`,squareSmall:`◻`,squareSmallFilled:`◼`,circle:`◯`,circleFilled:`◉`,circleDotted:`◌`,circleDouble:`◎`,circleCircle:`ⓞ`,circleCross:`ⓧ`,circlePipe:`Ⓘ`,radioOn:`◉`,radioOff:`◯`,checkboxOn:`☒`,checkboxOff:`☐`,checkboxCircleOn:`ⓧ`,checkboxCircleOff:`Ⓘ`,pointer:`❯`,triangleUpOutline:`△`,triangleLeft:`◀`,triangleRight:`▶`,lozenge:`◆`,lozengeOutline:`◇`,hamburger:`☰`,smiley:`㋡`,mustache:`෴`,star:`★`,play:`▶`,nodejs:`⬢`,oneSeventh:`⅐`,oneNinth:`⅑`,oneTenth:`⅒`},we={tick:`√`,info:`i`,warning:`‼`,cross:`×`,squareSmall:`□`,squareSmallFilled:`■`,circle:`( )`,circleFilled:`(*)`,circleDotted:`( )`,circleDouble:`( )`,circleCircle:`(○)`,circleCross:`(×)`,circlePipe:`(│)`,radioOn:`(*)`,radioOff:`( )`,checkboxOn:`[×]`,checkboxOff:`[ ]`,checkboxCircleOn:`(×)`,checkboxCircleOff:`( )`,pointer:`>`,triangleUpOutline:`∆`,triangleLeft:`◄`,triangleRight:`►`,lozenge:`♦`,lozengeOutline:`◊`,hamburger:`≡`,smiley:`☺`,mustache:`┌─┐`,star:`✶`,play:`►`,nodejs:`♦`,oneSeventh:`1/7`,oneNinth:`1/9`,oneTenth:`1/10`},Te={...Se,...Ce},Ee={...Se,...we},V=xe()?Te:Ee;Object.entries(Ce);var De=n(((t,n)=>{n.exports=i;function r(t){let n={defaultWidth:0,output:process.stdout,tty:e(`tty`)};return t?(Object.keys(n).forEach(function(e){t[e]||(t[e]=n[e])}),t):n}function i(e){let t=r(e);if(t.output.getWindowSize)return t.output.getWindowSize()[0]||t.defaultWidth;if(t.tty.getWindowSize)return t.tty.getWindowSize()[1]||t.defaultWidth;if(t.output.columns)return t.output.columns;if(process.env.CLI_WIDTH){let e=parseInt(process.env.CLI_WIDTH,10);if(!isNaN(e)&&e!==0)return e}return t.defaultWidth}}));const Oe=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return t=>{let n=0;for(e.lastIndex=0;e.test(t);)n+=1;return t.length-n}})(),ke=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,Ae=e=>e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141,je=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,Me=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Ne=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/uy,Pe=/\t{1,1000}/y,Fe=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/uy,Ie=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Le=/\p{M}+/gu,Re={limit:1/0,ellipsis:``},ze=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??``,a=t?.ellipsisWidth??(i?ze(i,Re,n).width:0),o=n.controlWidth??0,s=n.tabWidth??8,c=n.emojiWidth??2,l=n.regularWidth??1,u=n.wideWidth??2,d=[[Ie,l],[je,0],[Me,o],[Pe,s],[Fe,c],[Ne,u]],f=0,p=0,m=e.length,h=0,g=!1,_=m,v=Math.max(0,r-a),y=0,b=0,x=0,S=0;outer:for(;;){if(b>y||p>=m&&p>f){let t=e.slice(y,b)||e.slice(f,p);h=0;for(let e of t.replaceAll(Le,``)){let t=e.codePointAt(0)||0;if(S=ke(t)?2:Ae(t)?u:l,x+S>v&&(_=Math.min(_,Math.max(y,f)+h)),x+S>r){g=!0;break outer}h+=e.length,x+=S}y=b=0}if(p>=m)break outer;for(let t=0,n=d.length;t<n;t++){let[n,i]=d[t];if(n.lastIndex=p,n.test(e)){if(h=n===Ne?Oe(e.slice(p,n.lastIndex)):n===Fe?1:n.lastIndex-p,S=h*i,x+S>v&&(_=Math.min(_,p+Math.floor((v-x)/i))),x+S>r){g=!0;break outer}x+=S,y=f,b=p,p=f=n.lastIndex;continue outer}}p+=1}return{width:g?v:x,index:g?_:m,truncated:g,ellipsed:g&&r>=a}},Be={limit:1/0,ellipsis:``,ellipsisWidth:0},H=(e,t={})=>ze(e,Be,t).width,Ve=`]8;;`,He=RegExp(`(?:\\[(?<code>\\d+)m|\\${Ve}(?<uri>.*))`,`y`),Ue=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},We=e=>`[${e}m`,Ge=e=>`${Ve}${e}`,Ke=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,a=!1,o=e.at(-1),s=o===void 0?0:H(o),c=r.next(),l=r.next(),u=0;for(;!c.done;){let o=c.value,d=H(o);s+d<=n?e[e.length-1]+=o:(e.push(o),s=0),(o===`\x1B`||o===`›`)&&(i=!0,a=t.startsWith(Ve,u+1)),i?a?o===`\x07`&&(i=!1,a=!1):o===`m`&&(i=!1):(s+=d,s===n&&!l.done&&(e.push(``),s=0)),c=l,l=r.next(),u+=o.length}o=e.at(-1),!s&&o!==void 0&&o.length&&e.length>1&&(e[e.length-2]+=e.pop())},qe=e=>{let t=e.split(` `),n=t.length;for(;n&&!H(t[n-1]);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},Je=(e,t,n={})=>{if(n.trim!==!1&&e.trim()===``)return``;let r=``,i,a,o=e.split(` `),s=[``],c=0;for(let e=0;e<o.length;e++){let r=o[e];if(n.trim!==!1){let e=s.at(-1)??``,t=e.trimStart();e.length!==t.length&&(s[s.length-1]=t,c=H(t))}e!==0&&(c>=t&&(n.wordWrap===!1||n.trim===!1)&&(s.push(``),c=0),(c||n.trim===!1)&&(s[s.length-1]+=` `,c++));let i=H(r);if(n.hard&&i>t){let e=t-c,n=1+Math.floor((i-e-1)/t);Math.floor((i-1)/t)<n&&s.push(``),Ke(s,r,t),c=H(s.at(-1)??``);continue}if(c+i>t&&c&&i){if(n.wordWrap===!1&&c<t){Ke(s,r,t),c=H(s.at(-1)??``);continue}s.push(``),c=0}if(c+i>t&&n.wordWrap===!1){Ke(s,r,t),c=H(s.at(-1)??``);continue}s[s.length-1]+=r,c+=i}n.trim!==!1&&(s=s.map(e=>qe(e)));let l=s.join(`
2
2
  `),u=!1;for(let e=0;e<l.length;e++){let t=l[e];if(r+=t,u)u=!1;else if(u=t>=`\ud800`&&t<=`\udbff`,u)continue;if(t===`\x1B`||t===`›`){He.lastIndex=e+1;let t=He.exec(l)?.groups;if(t?.code!==void 0){let e=Number.parseFloat(t.code);i=e===39?void 0:e}else t?.uri!==void 0&&(a=t.uri.length===0?void 0:t.uri)}if(l[e+1]===`
3
3
  `){a&&(r+=Ge(``));let e=i?Ue(i):void 0;i&&e&&(r+=We(e))}else t===`
4
4
  `&&(i&&Ue(i)&&(r+=We(i)),a&&(r+=Ge(a)))}return r},Ye=/\r?\n/;function Xe(e,t,n){return String(e).normalize().split(Ye).map(e=>Je(e,t,n)).join(`
@@ -400,9 +400,9 @@ last-spawn-error.log
400
400
  # drafts/ # exclude a directory
401
401
  # *.draft.md # exclude files matching a pattern
402
402
  # !keep.md # re-include a file .gitignore excluded
403
- `,`.okignore`)?r.push(`.okignore`):a.push(`.okignore`),{created:r,updated:i,skipped:a}}function $n(e,t){let n=N(t,e);return n.length>0&&!n.startsWith(`..`)&&!ae(n)}const er=e=>{try{let t=ie(`git`,[`rev-parse`,`--show-toplevel`],{cwd:e,encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]}).trim();return t.length>0?t:null}catch{return null}};function tr(e,t={}){let n=t.homeDir??z(),r=t.gitTopLevel??er,i=P(e),a;try{a=fe(i)}catch{a=i}let o=a,s=0;for(;s<30&&!(o===n||o===`/`||o===``);){if(b(o))return{projectRoot:o,defaultContentDir:`.`,ancestorPromoted:o!==a,gitRootPromoted:!1};let e=j(o);if(e===o)break;o=e,s+=1}let c=r(a);return c!==null&&$n(c,n)?c===a?{projectRoot:i,defaultContentDir:`.`,ancestorPromoted:!1,gitRootPromoted:!1}:{projectRoot:c,defaultContentDir:`.`,ancestorPromoted:!1,gitRootPromoted:!0}:{projectRoot:i,defaultContentDir:`.`,ancestorPromoted:!1,gitRootPromoted:!1}}const nr=d,Z=x,rr=[`@inkeep/open-knowledge`,`mcp`],ir={MCP_DEBUG:`1`,OK_LOG_FILE:`/tmp/ok-mcp.log`};function ar(e=process.argv[1]){if(!e)throw Error(`Cannot infer the local CLI entry for --dev-mcp because process.argv[1] is empty.`);let t=P(e);if(A(t)===`cli.mjs`&&A(j(t))===`dist`)return t;let n=t.split(se),r=n.lastIndexOf(`packages`);if(r===-1||n[r+1]!==`cli`)throw Error(`Cannot infer the repo root for --dev-mcp from ${t}. Run the local CLI from this repo so the built dist path can be derived.`);let i=n.slice(0,r);return M(i.length===0?se:i.join(se),`packages`,`cli`,`dist`,`cli.mjs`)}function or(e={}){return e.cliPath?{command:e.cliPath,args:[`mcp`]}:e.mode===`dev`?{command:`node`,args:[ar(),`mcp`],env:{...ir}}:{command:`npx`,args:[...rr]}}function sr(e){return e===`win32`?ce:oe}function cr(e={}){let t=e.platformName??process.platform,n=e.home??z();return sr(t).join(n,`.claude.json`)}function lr(e={}){let t=e.platformName??process.platform,n=e.home??z(),r=e.env??process.env;if(t===`darwin`)return oe.join(n,`Library`,`Application Support`,`Claude`,`claude_desktop_config.json`);if(t===`win32`){let e=r.APPDATA??ce.join(n,`AppData`,`Roaming`);return ce.join(e,`Claude`,`claude_desktop_config.json`)}throw Error(`Claude Desktop is not available on ${t}. Supported: macOS, Windows.`)}function ur(e={}){let t=e.platformName??process.platform,n=e.home??z();return sr(t).join(n,`.cursor`,`mcp.json`)}function dr(e={}){let t=e.platformName??process.platform,n=e.home??z();return(e.env??process.env).CODEX_HOME??sr(t).join(n,`.codex`)}function fr(e={}){return sr(e.platformName??process.platform).join(dr(e),`config.toml`)}function pr(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((e,n)=>pr(e,t[n]));if(T(e)&&T(t)){let n=Object.keys(e).sort(),r=Object.keys(t).sort();return n.length===r.length&&n.every((e,t)=>e===r[t])&&n.every(n=>pr(e[n],t[n]))}return!1}function mr(e,t){return Object.entries(t).every(([t,n])=>pr(e[t],n))}function hr(e,t){return{...e,...t}}function gr(e){return{...e,isCompatible(t,n,r){return mr(t,e.buildEntry(n,r))},mergeManagedFields(t,n,r){return hr(t,e.buildEntry(n,r))}}}const Q={claude:gr({id:`claude`,label:Z.claude,configPath:(e,t)=>cr({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>o,buildEntry:(e,t)=>or(t),scope:`global`,detectPath:(e,t)=>M(t??z(),`.claude`),projectConfigPath:e=>M(e,`.mcp.json`),projectSkillPath:e=>M(e,`.claude`,`skills`,`open-knowledge`,`SKILL.md`)}),"claude-desktop":gr({id:`claude-desktop`,label:Z[`claude-desktop`],configPath:(e,t)=>lr({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>o,buildEntry:(e,t)=>or(t),scope:`global`,detectPath:(e,t)=>j(lr({home:t}))}),cursor:gr({id:`cursor`,label:Z.cursor,configPath:(e,t)=>ur({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>o,buildEntry:(e,t)=>or(t),scope:`global`,detectPath:(e,t)=>j(ur({home:t})),projectConfigPath:e=>M(e,`.cursor`,`mcp.json`),projectSkillPath:e=>M(e,`.cursor`,`skills`,`open-knowledge`,`SKILL.md`)}),codex:gr({id:`codex`,label:Z.codex,configPath:(e,t)=>fr({home:t}),format:`toml`,topLevelKey:`mcp_servers`,serverName:()=>o,buildEntry:(e,t)=>or(t),scope:`global`,detectPath:(e,t)=>j(fr({home:t})),projectConfigPath:e=>M(e,`.codex`,`config.toml`)})};function _r(e){let t=e.filter(e=>!Object.hasOwn(Q,e));if(t.length>0)throw Error(`Unknown editor(s): ${t.join(`, `)}. Valid options: ${nr.join(`, `)}`);return e.map(e=>Q[e])}function $(e,t,n,r,i){let a=`urn:uuid:${ve()}`;if(e.headersSent||e.writableEnded||e.destroyed){console.error(`[ok ui] emitProblem called after headers sent — suppressed`,{type:n,status:t,instance:a});return}let o={type:n,title:r,status:t,instance:a,...i===void 0?{}:{detail:i}},s=S.safeParse(o);if(!s.success){console.error(`[ok ui] emitProblem produced an invalid ProblemDetails body:`,{issues:s.error.issues,originalStatus:t,body:o}),e.writeHead(500,{"Content-Type":`application/problem+json`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-store`}),e.end(JSON.stringify({type:`urn:ok:error:internal-server-error`,title:`Internal server error.`,status:500,instance:a}));return}e.writeHead(t,{"Content-Type":`application/problem+json`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-store`}),e.end(JSON.stringify(o))}const vr=1e4;function yr(e,t){let n=e.socket?.remoteAddress;if(n!==void 0&&!C(n))return $(t,403,`urn:ok:error:loopback-required`,`Request must originate from a loopback address.`),!0;if(!y(e.headers.host))return $(t,403,`urn:ok:error:host-not-allowed`,`Host header is not in the loopback allowlist.`),!0;let r=e.headers.origin;return r!==void 0&&!p(r)?($(t,403,`urn:ok:error:invalid-origin`,`Origin header is not in the loopback allowlist.`),!0):!1}const br=3e4,xr=[`connection`,`keep-alive`,`proxy-authenticate`,`proxy-authorization`,`te`,`trailer`,`transfer-encoding`,`upgrade`,`cookie`,`set-cookie`];async function Sr(e){let t=e.upstreamTimeoutMs??vr,n=ye((n,r)=>{yr(n,r)||wr(n,r,e.upstreamHost,e.upstreamPort,t)});await new Promise((t,r)=>{let i=e=>r(e);n.once(`error`,i),n.listen(e.listenPort,e.host,()=>{n.off(`error`,i),t()})});let r=n.address();return{httpServer:n,port:typeof r==`object`&&r?r.port:e.listenPort,close:()=>new Promise(e=>{n.close(()=>e()),n.closeIdleConnections()})}}function Cr(e,t,n){wr(e,t,n.upstreamHost,n.upstreamPort,n.upstreamTimeoutMs??vr)}function wr(e,t,n,r,i){let a={...e.headers};delete a.host;for(let e of xr)delete a[e];e.setTimeout(br,()=>{if(t.headersSent)try{t.end()}catch{}else try{$(t,408,`urn:ok:error:request-timeout`,`Proxy request exceeded the per-request deadline.`,`Slow-loris-class: client did not finish within ${br/1e3}s.`)}catch{}try{e.socket?.destroy()}catch{}});let o=be({host:n,port:r,method:e.method,path:e.url,headers:{...a,host:`${n}:${r}`}},e=>{let n={...e.headers};for(let e of xr)delete n[e];t.writeHead(e.statusCode??502,n),e.pipe(t),e.once(`error`,()=>{try{t.end()}catch{}})});i>0&&o.setTimeout(i,()=>{if(!t.headersSent)$(t,504,`urn:ok:error:gateway-timeout`,`Upstream did not respond before the gateway deadline.`,`Upstream timeout: ${i/1e3}s elapsed without a response.`);else try{t.end()}catch{}o.destroy()}),o.on(`error`,()=>{if(!t.headersSent)$(t,502,`urn:ok:error:collab-server-not-running`,`Collab server is unreachable.`,`Upstream connection failed or dropped before a response was received.`);else try{t.end()}catch{}}),e.on(`error`,()=>{o.destroy()}),e.pipe(o)}const Tr=39847,Er=39848;async function Dr(e){await Promise.all(e.map(e=>new Promise(t=>{e.close(()=>t())})))}async function Or(e){let{existsSync:t}=await import(`node:fs`),{createServer:n}=await import(`node:http`),{resolve:r}=await import(`node:path`),{acquireUiLock:i,createAssetServeMiddleware:o,createContentFilter:s,readServerLock:c,releaseUiLock:l,updateUiLockPort:u}=await import(`./dist-JvyJrwkx.mjs`),{default:d}=await import(`./build-B4ZT2GMK.mjs`),{resolveContentDir:p,resolveLockDir:h}=await import(`./dist-JvyJrwkx.mjs`),g=p(e.config,e.cwd),v=h(e.cwd);i(v,{port:0,worktreeRoot:e.cwd});let y=import.meta.dirname??new URL(`.`,import.meta.url).pathname,b=[r(y,`public`),r(y,`../../app/dist`),r(y,`../../../app/dist`)].find(e=>t(e)),x=b?d(b,{single:!0,gzip:!0,immutable:!0,extensions:[]}):null,S=t(g)?o({contentFilter:s({projectDir:e.cwd,contentDir:g}),contentSirv:d(g,{dotfiles:!1,dev:!0,extensions:[]}),inlineExtensions:f,assetExtensions:a,blocklistExtensions:_}):null,C=e.port,w=null,ee=(e,t)=>{let n=e.url?.split(`?`)[0];if((n===`/`||n===``)&&(e.url=`/index.html`),!(n?.startsWith(`/api/`)&&yr(e,t))){if(n===`/api/config`&&(e.method===`GET`||e.method===`HEAD`)){w?.();let n=c(v),r=n&&n.port>0?`ws://localhost:${n.port}/collab`:null,i=JSON.stringify({collabUrl:r,previewUrl:null,port:C});t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,e.method===`HEAD`?t.end():t.end(i);return}if(n?.startsWith(`/api/`)){w?.();let r=c(v);if(!r||r.port<=0){$(t,503,`urn:ok:error:collab-server-not-running`,"Collab server not running. Start `ok start` or run `ok status`.",`Path: ${n}`);return}Cr(e,t,{upstreamHost:`localhost`,upstreamPort:r.port});return}if(S){S(e,t,()=>{x?x(e,t):kr(t,n)});return}if(x){x(e,t);return}kr(t,n)}},T=e.host===void 0?[`::1`,`127.0.0.1`]:[e.host],E=[],D=e.port,te=e=>e instanceof Error&&e.code===`EADDRINUSE`,ne=async()=>{await Promise.all(E.splice(0).map(e=>new Promise(t=>{try{e.close(()=>t())}catch{t()}})))},O=async e=>{D=e;for(let e of T){let t=n(ee);E.push(t),await new Promise((n,r)=>{let i=e=>r(e);t.once(`error`,i),t.listen(D,e,()=>{t.off(`error`,i);let e=t.address();typeof e==`object`&&e&&(D=e.port),n()})})}};try{try{await O(e.port)}catch(t){if(e.fallbackToKernel===!0&&te(t))await ne(),await O(0);else throw t}}catch(e){await ne();try{l(v)}catch{}throw e}let re=D;C=re,u(v,re);let ie=e.scheduler??m,k=e.safetyNetMs??432e5,A=null,j=!1,ae=!1,M=()=>{j||(j=!0,A!==null&&(ie.clearTimeout(A),A=null))},oe=()=>{if(M(),!ae){ae=!0;try{l(v)}catch{}}},N=()=>{j||k<=0||(A!==null&&(ie.clearTimeout(A),A=null),A=ie.setTimeout(()=>{A=null,console.warn(`[ui] safety-net (${k}ms) reached — shutting down (D-025 backstop)`);try{e.onSafetyNet?.()}catch{}for(let e of E)try{e.close()}catch{}oe()},k))},P=()=>{j||k<=0||N()};return w=P,N(),{httpServers:E,port:re,release:oe,detachSafetyNet:M,nudgeSafetyNet:P}}function kr(e,t){$(e,404,`urn:ok:error:not-found`,`Resource not found.`,t===void 0?void 0:`Path: ${t}`)}function Ar(e,t){if(e!==void 0){let t=Number.parseInt(e,10);if(Number.isNaN(t)||t<0||t>65535)throw Error(`Invalid --port value '${e}'`);return{port:t,fallbackToKernel:!1}}if(t!==void 0&&t!==``){let e=Number.parseInt(t,10);if(Number.isNaN(e)||e<0||e>65535)throw Error(`Invalid PORT env value '${t}'`);return{port:e,fallbackToKernel:!1}}return{port:Tr,fallbackToKernel:!0}}async function jr(e){let t=e.readLock??(async()=>{let{readUiLock:t}=await import(`./dist-JvyJrwkx.mjs`);return t(e.lockDir)}),n=await t();if(!n)throw Error(`UI lock collision reported but the lock disappeared before handling — retry acquiring.`);if(n.port===e.requestedPort&&n.port>0)return{mode:`already-running`,port:n.port};let r=n.port;if(r===0){let n=Date.now()+(e.pollDeadlineMs??2e3),i=e.pollIntervalMs??100;for(;Date.now()<n;){await new Promise(e=>{setTimeout(e,i)});let e=await t();if(e&&e.port>0){r=e.port;break}}if(r===0)throw Error("UI did not bind within 2s; run `ok clean`");if(r===e.requestedPort)return{mode:`already-running`,port:r}}return{mode:`proxy`,handle:await Sr({listenPort:e.requestedPort,host:e.host,upstreamHost:`localhost`,upstreamPort:r}),upstreamPort:r}}function Mr(e){return new i(`ui`).description(`Serve the Open Knowledge React editor UI`).option(`-p, --port <port>`,`UI port (default: $PORT env or ${Tr}, kernel-allocated fallback if busy)`).option(`-H, --host <host>`,"UI host. Default: two-socket loopback bind (`[::1]` + `127.0.0.1`) so cross-family collisions fail loud (D-033). Pass an explicit host (e.g. `127.0.0.1`, `0.0.0.0`) to bind a single socket on that host.").action(async t=>{let{dim:n}=await import(`./colors-T3xmlXQT.mjs`),{UiLockCollisionError:r}=await import(`./dist-JvyJrwkx.mjs`),{resolveLockDir:i}=await import(`./dist-JvyJrwkx.mjs`),a=e(),o=t.host,s;try{s=Ar(t.port,process.env.PORT)}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exitCode=1;return}let c=s.port;try{let e=await Or({config:a,cwd:process.cwd(),port:c,fallbackToKernel:s.fallbackToKernel,host:o}),t=o===void 0||o===`::`||o===`0.0.0.0`?`localhost`:o;console.log(`${n(`[ui]`)} listening on http://${t}:${e.port}`);let r=!1,i=t=>{if(r)return;r=!0,console.log(n(`\n[ui] Shutting down (${t})`)),e.detachSafetyNet();let i=()=>{try{e.release()}finally{process.exit(process.exitCode??0)}};Dr(e.httpServers).then(i,i),setTimeout(i,2e3).unref()};process.once(`SIGINT`,()=>i(`SIGINT`)),process.once(`SIGTERM`,()=>i(`SIGTERM`));return}catch(e){if(!(e instanceof r))throw e;let t=i(process.cwd()),a=o??`localhost`,s;try{s=await jr({requestedPort:c,host:a,lockDir:t})}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exit(1)}s.mode===`already-running`&&(console.log(`UI already running at http://${a}:${s.port}`),process.exit(0)),console.log(`UI running at http://${a}:${s.upstreamPort}; acting as HTTP proxy on port ${s.handle.port}`);let l=!1,u=e=>{l||(l=!0,console.log(n(`\n[ui-proxy] Shutting down (${e})`)),s.handle.close().finally(()=>process.exit(process.exitCode??0)),setTimeout(()=>process.exit(process.exitCode??0),2e3).unref())};process.once(`SIGINT`,()=>u(`SIGINT`)),process.once(`SIGTERM`,()=>u(`SIGTERM`))}})}function Nr(e){if(!F(e))return{};let t=de(e,`utf-8`).trim();if(t===``)return{};try{let n=JSON.parse(t);if(T(n))return n;throw Error(`${e} root must be a JSON object`)}catch(t){throw t instanceof SyntaxError?Error(`${e} contains invalid JSON: ${t.message}`):t}}function Pr(e){if(!F(e))return{};let t=de(e,`utf-8`).trim();if(t===``)return{};try{let n=In(t);if(T(n))return n;throw Error(`${e} root must be a TOML table`)}catch(t){throw Error(`${e} contains invalid TOML: ${t instanceof Error?t.message:String(t)}`)}}function Fr(e,t){I(j(e),{recursive:!0}),L(e,`${JSON.stringify(t,null,2)}\n`,`utf-8`)}function Ir(e,t){I(j(e),{recursive:!0});let n=Gn(t);L(e,n.endsWith(`
403
+ `,`.okignore`)?r.push(`.okignore`):a.push(`.okignore`),{created:r,updated:i,skipped:a}}function $n(e,t){let n=N(t,e);return n.length>0&&!n.startsWith(`..`)&&!ae(n)}const er=e=>{try{let t=ie(`git`,[`rev-parse`,`--show-toplevel`],{cwd:e,encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]}).trim();return t.length>0?t:null}catch{return null}};function tr(e,t={}){let n=t.homeDir??z(),r=t.gitTopLevel??er,i=P(e),a;try{a=fe(i)}catch{a=i}let o=a,s=0;for(;s<30&&!(o===n||o===`/`||o===``);){if(b(o))return{projectRoot:o,defaultContentDir:`.`,ancestorPromoted:o!==a,gitRootPromoted:!1};let e=j(o);if(e===o)break;o=e,s+=1}let c=r(a);return c!==null&&$n(c,n)?c===a?{projectRoot:i,defaultContentDir:`.`,ancestorPromoted:!1,gitRootPromoted:!1}:{projectRoot:c,defaultContentDir:`.`,ancestorPromoted:!1,gitRootPromoted:!0}:{projectRoot:i,defaultContentDir:`.`,ancestorPromoted:!1,gitRootPromoted:!1}}const nr=d,Z=x,rr=[`-y`,`@inkeep/open-knowledge@latest`,`mcp`],ir={MCP_DEBUG:`1`,OK_LOG_FILE:`/tmp/ok-mcp.log`};function ar(e=process.argv[1]){if(!e)throw Error(`Cannot infer the local CLI entry for --dev-mcp because process.argv[1] is empty.`);let t=P(e);if(A(t)===`cli.mjs`&&A(j(t))===`dist`)return t;let n=t.split(se),r=n.lastIndexOf(`packages`);if(r===-1||n[r+1]!==`cli`)throw Error(`Cannot infer the repo root for --dev-mcp from ${t}. Run the local CLI from this repo so the built dist path can be derived.`);let i=n.slice(0,r);return M(i.length===0?se:i.join(se),`packages`,`cli`,`dist`,`cli.mjs`)}function or(e={}){return e.cliPath?{command:e.cliPath,args:[`mcp`]}:e.mode===`dev`?{command:`node`,args:[ar(),`mcp`],env:{...ir}}:{command:`npx`,args:[...rr]}}function sr(e){return e===`win32`?ce:oe}function cr(e={}){let t=e.platformName??process.platform,n=e.home??z();return sr(t).join(n,`.claude.json`)}function lr(e={}){let t=e.platformName??process.platform,n=e.home??z(),r=e.env??process.env;if(t===`darwin`)return oe.join(n,`Library`,`Application Support`,`Claude`,`claude_desktop_config.json`);if(t===`win32`){let e=r.APPDATA??ce.join(n,`AppData`,`Roaming`);return ce.join(e,`Claude`,`claude_desktop_config.json`)}throw Error(`Claude Desktop is not available on ${t}. Supported: macOS, Windows.`)}function ur(e={}){let t=e.platformName??process.platform,n=e.home??z();return sr(t).join(n,`.cursor`,`mcp.json`)}function dr(e={}){let t=e.platformName??process.platform,n=e.home??z();return(e.env??process.env).CODEX_HOME??sr(t).join(n,`.codex`)}function fr(e={}){return sr(e.platformName??process.platform).join(dr(e),`config.toml`)}function pr(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((e,n)=>pr(e,t[n]));if(T(e)&&T(t)){let n=Object.keys(e).sort(),r=Object.keys(t).sort();return n.length===r.length&&n.every((e,t)=>e===r[t])&&n.every(n=>pr(e[n],t[n]))}return!1}function mr(e,t){return Object.entries(t).every(([t,n])=>pr(e[t],n))}function hr(e,t){return{...e,...t}}function gr(e){return{...e,isCompatible(t,n,r){return mr(t,e.buildEntry(n,r))},mergeManagedFields(t,n,r){return hr(t,e.buildEntry(n,r))}}}const Q={claude:gr({id:`claude`,label:Z.claude,configPath:(e,t)=>cr({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>o,buildEntry:(e,t)=>or(t),scope:`global`,detectPath:(e,t)=>M(t??z(),`.claude`),projectConfigPath:e=>M(e,`.mcp.json`),projectSkillPath:e=>M(e,`.claude`,`skills`,`open-knowledge`,`SKILL.md`)}),"claude-desktop":gr({id:`claude-desktop`,label:Z[`claude-desktop`],configPath:(e,t)=>lr({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>o,buildEntry:(e,t)=>or(t),scope:`global`,detectPath:(e,t)=>j(lr({home:t}))}),cursor:gr({id:`cursor`,label:Z.cursor,configPath:(e,t)=>ur({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>o,buildEntry:(e,t)=>or(t),scope:`global`,detectPath:(e,t)=>j(ur({home:t})),projectConfigPath:e=>M(e,`.cursor`,`mcp.json`),projectSkillPath:e=>M(e,`.cursor`,`skills`,`open-knowledge`,`SKILL.md`)}),codex:gr({id:`codex`,label:Z.codex,configPath:(e,t)=>fr({home:t}),format:`toml`,topLevelKey:`mcp_servers`,serverName:()=>o,buildEntry:(e,t)=>or(t),scope:`global`,detectPath:(e,t)=>j(fr({home:t})),projectConfigPath:e=>M(e,`.codex`,`config.toml`)})};function _r(e){let t=e.filter(e=>!Object.hasOwn(Q,e));if(t.length>0)throw Error(`Unknown editor(s): ${t.join(`, `)}. Valid options: ${nr.join(`, `)}`);return e.map(e=>Q[e])}function $(e,t,n,r,i){let a=`urn:uuid:${ve()}`;if(e.headersSent||e.writableEnded||e.destroyed){console.error(`[ok ui] emitProblem called after headers sent — suppressed`,{type:n,status:t,instance:a});return}let o={type:n,title:r,status:t,instance:a,...i===void 0?{}:{detail:i}},s=S.safeParse(o);if(!s.success){console.error(`[ok ui] emitProblem produced an invalid ProblemDetails body:`,{issues:s.error.issues,originalStatus:t,body:o}),e.writeHead(500,{"Content-Type":`application/problem+json`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-store`}),e.end(JSON.stringify({type:`urn:ok:error:internal-server-error`,title:`Internal server error.`,status:500,instance:a}));return}e.writeHead(t,{"Content-Type":`application/problem+json`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-store`}),e.end(JSON.stringify(o))}const vr=1e4;function yr(e,t){let n=e.socket?.remoteAddress;if(n!==void 0&&!C(n))return $(t,403,`urn:ok:error:loopback-required`,`Request must originate from a loopback address.`),!0;if(!y(e.headers.host))return $(t,403,`urn:ok:error:host-not-allowed`,`Host header is not in the loopback allowlist.`),!0;let r=e.headers.origin;return r!==void 0&&!p(r)?($(t,403,`urn:ok:error:invalid-origin`,`Origin header is not in the loopback allowlist.`),!0):!1}const br=3e4,xr=[`connection`,`keep-alive`,`proxy-authenticate`,`proxy-authorization`,`te`,`trailer`,`transfer-encoding`,`upgrade`,`cookie`,`set-cookie`];async function Sr(e){let t=e.upstreamTimeoutMs??vr,n=ye((n,r)=>{yr(n,r)||wr(n,r,e.upstreamHost,e.upstreamPort,t)});await new Promise((t,r)=>{let i=e=>r(e);n.once(`error`,i),n.listen(e.listenPort,e.host,()=>{n.off(`error`,i),t()})});let r=n.address();return{httpServer:n,port:typeof r==`object`&&r?r.port:e.listenPort,close:()=>new Promise(e=>{n.close(()=>e()),n.closeIdleConnections()})}}function Cr(e,t,n){wr(e,t,n.upstreamHost,n.upstreamPort,n.upstreamTimeoutMs??vr)}function wr(e,t,n,r,i){let a={...e.headers};delete a.host;for(let e of xr)delete a[e];e.setTimeout(br,()=>{if(t.headersSent)try{t.end()}catch{}else try{$(t,408,`urn:ok:error:request-timeout`,`Proxy request exceeded the per-request deadline.`,`Slow-loris-class: client did not finish within ${br/1e3}s.`)}catch{}try{e.socket?.destroy()}catch{}});let o=be({host:n,port:r,method:e.method,path:e.url,headers:{...a,host:`${n}:${r}`}},e=>{let n={...e.headers};for(let e of xr)delete n[e];t.writeHead(e.statusCode??502,n),e.pipe(t),e.once(`error`,()=>{try{t.end()}catch{}})});i>0&&o.setTimeout(i,()=>{if(!t.headersSent)$(t,504,`urn:ok:error:gateway-timeout`,`Upstream did not respond before the gateway deadline.`,`Upstream timeout: ${i/1e3}s elapsed without a response.`);else try{t.end()}catch{}o.destroy()}),o.on(`error`,()=>{if(!t.headersSent)$(t,502,`urn:ok:error:collab-server-not-running`,`Collab server is unreachable.`,`Upstream connection failed or dropped before a response was received.`);else try{t.end()}catch{}}),e.on(`error`,()=>{o.destroy()}),e.pipe(o)}const Tr=39847,Er=39848;async function Dr(e){await Promise.all(e.map(e=>new Promise(t=>{e.close(()=>t())})))}async function Or(e){let{existsSync:t}=await import(`node:fs`),{createServer:n}=await import(`node:http`),{resolve:r}=await import(`node:path`),{acquireUiLock:i,createAssetServeMiddleware:o,createContentFilter:s,readServerLock:c,releaseUiLock:l,updateUiLockPort:u}=await import(`./dist-JvyJrwkx.mjs`),{default:d}=await import(`./build-B4ZT2GMK.mjs`),{resolveContentDir:p,resolveLockDir:h}=await import(`./dist-JvyJrwkx.mjs`),g=p(e.config,e.cwd),v=h(e.cwd);i(v,{port:0,worktreeRoot:e.cwd});let y=import.meta.dirname??new URL(`.`,import.meta.url).pathname,b=[r(y,`public`),r(y,`../../app/dist`),r(y,`../../../app/dist`)].find(e=>t(e)),x=b?d(b,{single:!0,gzip:!0,immutable:!0,extensions:[]}):null,S=t(g)?o({contentFilter:s({projectDir:e.cwd,contentDir:g}),contentSirv:d(g,{dotfiles:!1,dev:!0,extensions:[]}),inlineExtensions:f,assetExtensions:a,blocklistExtensions:_}):null,C=e.port,w=null,ee=(e,t)=>{let n=e.url?.split(`?`)[0];if((n===`/`||n===``)&&(e.url=`/index.html`),!(n?.startsWith(`/api/`)&&yr(e,t))){if(n===`/api/config`&&(e.method===`GET`||e.method===`HEAD`)){w?.();let n=c(v),r=n&&n.port>0?`ws://localhost:${n.port}/collab`:null,i=JSON.stringify({collabUrl:r,previewUrl:null,port:C});t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,e.method===`HEAD`?t.end():t.end(i);return}if(n?.startsWith(`/api/`)){w?.();let r=c(v);if(!r||r.port<=0){$(t,503,`urn:ok:error:collab-server-not-running`,"Collab server not running. Start `ok start` or run `ok status`.",`Path: ${n}`);return}Cr(e,t,{upstreamHost:`localhost`,upstreamPort:r.port});return}if(S){S(e,t,()=>{x?x(e,t):kr(t,n)});return}if(x){x(e,t);return}kr(t,n)}},T=e.host===void 0?[`::1`,`127.0.0.1`]:[e.host],E=[],D=e.port,te=e=>e instanceof Error&&e.code===`EADDRINUSE`,ne=async()=>{await Promise.all(E.splice(0).map(e=>new Promise(t=>{try{e.close(()=>t())}catch{t()}})))},O=async e=>{D=e;for(let e of T){let t=n(ee);E.push(t),await new Promise((n,r)=>{let i=e=>r(e);t.once(`error`,i),t.listen(D,e,()=>{t.off(`error`,i);let e=t.address();typeof e==`object`&&e&&(D=e.port),n()})})}};try{try{await O(e.port)}catch(t){if(e.fallbackToKernel===!0&&te(t))await ne(),await O(0);else throw t}}catch(e){await ne();try{l(v)}catch{}throw e}let re=D;C=re,u(v,re);let ie=e.scheduler??m,k=e.safetyNetMs??432e5,A=null,j=!1,ae=!1,M=()=>{j||(j=!0,A!==null&&(ie.clearTimeout(A),A=null))},oe=()=>{if(M(),!ae){ae=!0;try{l(v)}catch{}}},N=()=>{j||k<=0||(A!==null&&(ie.clearTimeout(A),A=null),A=ie.setTimeout(()=>{A=null,console.warn(`[ui] safety-net (${k}ms) reached — shutting down (D-025 backstop)`);try{e.onSafetyNet?.()}catch{}for(let e of E)try{e.close()}catch{}oe()},k))},P=()=>{j||k<=0||N()};return w=P,N(),{httpServers:E,port:re,release:oe,detachSafetyNet:M,nudgeSafetyNet:P}}function kr(e,t){$(e,404,`urn:ok:error:not-found`,`Resource not found.`,t===void 0?void 0:`Path: ${t}`)}function Ar(e,t){if(e!==void 0){let t=Number.parseInt(e,10);if(Number.isNaN(t)||t<0||t>65535)throw Error(`Invalid --port value '${e}'`);return{port:t,fallbackToKernel:!1}}if(t!==void 0&&t!==``){let e=Number.parseInt(t,10);if(Number.isNaN(e)||e<0||e>65535)throw Error(`Invalid PORT env value '${t}'`);return{port:e,fallbackToKernel:!1}}return{port:Tr,fallbackToKernel:!0}}async function jr(e){let t=e.readLock??(async()=>{let{readUiLock:t}=await import(`./dist-JvyJrwkx.mjs`);return t(e.lockDir)}),n=await t();if(!n)throw Error(`UI lock collision reported but the lock disappeared before handling — retry acquiring.`);if(n.port===e.requestedPort&&n.port>0)return{mode:`already-running`,port:n.port};let r=n.port;if(r===0){let n=Date.now()+(e.pollDeadlineMs??2e3),i=e.pollIntervalMs??100;for(;Date.now()<n;){await new Promise(e=>{setTimeout(e,i)});let e=await t();if(e&&e.port>0){r=e.port;break}}if(r===0)throw Error("UI did not bind within 2s; run `ok clean`");if(r===e.requestedPort)return{mode:`already-running`,port:r}}return{mode:`proxy`,handle:await Sr({listenPort:e.requestedPort,host:e.host,upstreamHost:`localhost`,upstreamPort:r}),upstreamPort:r}}function Mr(e){return new i(`ui`).description(`Serve the Open Knowledge React editor UI`).option(`-p, --port <port>`,`UI port (default: $PORT env or ${Tr}, kernel-allocated fallback if busy)`).option(`-H, --host <host>`,"UI host. Default: two-socket loopback bind (`[::1]` + `127.0.0.1`) so cross-family collisions fail loud (D-033). Pass an explicit host (e.g. `127.0.0.1`, `0.0.0.0`) to bind a single socket on that host.").action(async t=>{let{dim:n}=await import(`./colors-T3xmlXQT.mjs`),{UiLockCollisionError:r}=await import(`./dist-JvyJrwkx.mjs`),{resolveLockDir:i}=await import(`./dist-JvyJrwkx.mjs`),a=e(),o=t.host,s;try{s=Ar(t.port,process.env.PORT)}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exitCode=1;return}let c=s.port;try{let e=await Or({config:a,cwd:process.cwd(),port:c,fallbackToKernel:s.fallbackToKernel,host:o}),t=o===void 0||o===`::`||o===`0.0.0.0`?`localhost`:o;console.log(`${n(`[ui]`)} listening on http://${t}:${e.port}`);let r=!1,i=t=>{if(r)return;r=!0,console.log(n(`\n[ui] Shutting down (${t})`)),e.detachSafetyNet();let i=()=>{try{e.release()}finally{process.exit(process.exitCode??0)}};Dr(e.httpServers).then(i,i),setTimeout(i,2e3).unref()};process.once(`SIGINT`,()=>i(`SIGINT`)),process.once(`SIGTERM`,()=>i(`SIGTERM`));return}catch(e){if(!(e instanceof r))throw e;let t=i(process.cwd()),a=o??`localhost`,s;try{s=await jr({requestedPort:c,host:a,lockDir:t})}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exit(1)}s.mode===`already-running`&&(console.log(`UI already running at http://${a}:${s.port}`),process.exit(0)),console.log(`UI running at http://${a}:${s.upstreamPort}; acting as HTTP proxy on port ${s.handle.port}`);let l=!1,u=e=>{l||(l=!0,console.log(n(`\n[ui-proxy] Shutting down (${e})`)),s.handle.close().finally(()=>process.exit(process.exitCode??0)),setTimeout(()=>process.exit(process.exitCode??0),2e3).unref())};process.once(`SIGINT`,()=>u(`SIGINT`)),process.once(`SIGTERM`,()=>u(`SIGTERM`))}})}function Nr(e){if(!F(e))return{};let t=de(e,`utf-8`).trim();if(t===``)return{};try{let n=JSON.parse(t);if(T(n))return n;throw Error(`${e} root must be a JSON object`)}catch(t){throw t instanceof SyntaxError?Error(`${e} contains invalid JSON: ${t.message}`):t}}function Pr(e){if(!F(e))return{};let t=de(e,`utf-8`).trim();if(t===``)return{};try{let n=In(t);if(T(n))return n;throw Error(`${e} root must be a TOML table`)}catch(t){throw Error(`${e} contains invalid TOML: ${t instanceof Error?t.message:String(t)}`)}}function Fr(e,t){I(j(e),{recursive:!0}),L(e,`${JSON.stringify(t,null,2)}\n`,`utf-8`)}function Ir(e,t){I(j(e),{recursive:!0});let n=Gn(t);L(e,n.endsWith(`
404
404
  `)?n:`${n}\n`,`utf-8`)}function Lr(e,t){let n;try{n=fe(t)}catch{n=P(t)}let r;try{r=ue(e)}catch(e){if(e.code!==`ENOENT`)throw e}if(r?.isSymbolicLink())throw Error(`Refusing to write through a symbolic link at ${e}. Remove the symlink and re-run \`ok init\`, or pass \`--no-mcp\` to skip MCP config writes.`);let i=j(e);for(;i.length>1&&i!==se;){let t;try{t=fe(i)}catch(e){if(e.code===`ENOENT`){i=j(i);continue}throw e}let r=N(n,t);if(r===``||!r.startsWith(`..`)&&!ae(r))return;throw Error(`Refusing to write at ${e}: ancestor ${i} resolves to ${t}, which is outside the project directory ${n}. A symbolic link in the path likely escapes the project. Remove the symlink and re-run, or pass \`--no-mcp\`.`)}}const Rr=e=>e!==`project`,zr=e=>e!==`user`;async function Br(){let e=await fn({message:`Where should the MCP server be configured?
405
- `,required:!1,theme:{icon:{checked:`[x]`,unchecked:`[ ]`}},choices:[{name:`User-level (~/.claude.json, ~/.cursor/mcp.json, …)`,value:`user`,checked:!0},{name:`Project-level (.mcp.json, .cursor/mcp.json, …)`,value:`project`,checked:!0}]});return e.includes(`user`)&&e.includes(`project`)?`both`:e.includes(`user`)?`user`:e.includes(`project`)?`project`:null}async function Vr(e){return e.mcp===!1?null:e.scope?e.scope:e.isTTY??process.stdout.isTTY?(e.promptFn??Br)():`both`}const Hr=`0.0.1`,Ur=`open-knowledge-ui`;function Wr(e,t={}){let n=M(e,`.claude`,`launch.json`),r=t.mode===`dev`?{name:Ur,runtimeExecutable:`node`,runtimeArgs:[ar(),`ui`],port:Er,autoPort:!0}:{name:Ur,runtimeExecutable:`npx`,runtimeArgs:[`@inkeep/open-knowledge`,`ui`],port:Er,autoPort:!0};try{if(Lr(n,e),!F(n))return I(j(n),{recursive:!0}),L(n,`${JSON.stringify({version:Hr,configurations:[r]},null,2)}\n`,`utf-8`),{action:`created`,configPath:n};let t=de(n,`utf-8`).trim(),i=t?JSON.parse(t):{};if(!T(i))return{action:`failed`,configPath:n,error:`launch.json root is not an object`};let a=Array.isArray(i.configurations)?i.configurations:[],o=a.findIndex(e=>T(e)&&e.name===Ur);o>=0?a[o]=r:a.push(r);let s={...i,version:i.version??Hr,configurations:a};return L(n,`${JSON.stringify(s,null,2)}\n`,`utf-8`),{action:o>=0?`merged`:`created`,configPath:n}}catch(e){return{action:`failed`,configPath:n,error:e instanceof Error?e.message:String(e)}}}function Gr(e,t,n){try{return F(e.detectPath?.(t,n)??j(e.configPath(t,n)))}catch{return!1}}function Kr(e,t,n,r,i){let a=e.serverName(t),o;try{o=i??e.configPath(t,r)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:``,serverName:a,error:t instanceof Error?t.message:String(t)}}if(!i&&!n.skipAvailabilityCheck&&!Gr(e,t,r))return{editorId:e.id,label:e.label,action:`skipped-missing`,configPath:o,serverName:a};if(i!==void 0)try{Lr(o,t)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),configScope:`project`}}let s;try{s=e.format===`toml`?Pr(o):Nr(o)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t)}}let c=s[e.topLevelKey]??{},l=c[a],u;try{u=e.buildEntry(t,n)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t)}}let d={...s,[e.topLevelKey]:{...c,[a]:u}};try{e.format===`toml`?Ir(o,d):Fr(o,d)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t)}}return{editorId:e.id,label:e.label,action:l===void 0?`written`:`overwritten`,configPath:o,serverName:a,...i===void 0?{}:{configScope:`project`}}}function qr(e,t){let n=e.projectSkillPath?.(t);if(!n)return{editorId:e.id,label:e.label,action:`skipped-unsupported`,path:``};try{let r=c(),i=j(n);Lr(i,t);let a=F(n)?`overwritten`:`written`;return pe(i,{recursive:!0,force:!0}),I(j(i),{recursive:!0}),le(r,i,{recursive:!0}),{editorId:e.id,label:e.label,action:a,path:n}}catch(t){return{editorId:e.id,label:e.label,action:`failed`,path:n,error:t instanceof Error?t.message:String(t)}}}function Jr(e,t){let n=e.projectConfigPath?.(t);if(!(!n||!F(n)))return{editorId:e.id,label:e.label,path:n}}async function Yr(e){let t=_r(e.editors),n={mode:`published`,cliPath:e.cliPath,skipAvailabilityCheck:!0};return t.map(t=>Kr(t,``,n,e.home))}function Xr(e,t,n){let r;try{r=e.configPath(t,n)}catch{return null}let i;try{i=e.format===`toml`?Pr(r):Nr(r)}catch{return null}let a=i[e.topLevelKey];if(!T(a))return null;let o=a[e.serverName(t)];return T(o)?o:null}async function Zr(e={}){let t=P(e.cwd??process.cwd()),n=tr(t,{homeDir:e.home}),r=n.projectRoot,i=!F(M(r,`.ok`));n.ancestorPromoted?console.log(`[ok] Opened existing project at ${r}`):n.gitRootPromoted&&i&&console.log(`[ok] Initialized OK at ${r} — opened parent of ${N(r,t)} because it contains a .git folder`);let a={mode:e.devMcp?`dev`:`published`},o=await l(r),s;try{s=Qn(r,{contentDir:n.defaultContentDir})}catch(t){let n=Q.claude.configPath(r,e.home);return{projectRoot:r,contentCreated:[],contentUpdated:[],contentSkipped:[],editors:[],projectSkills:[],legacyProjectConfigs:[],didGitInit:o.didInit,claudeDesktopDetected:!1,mcpAction:`failed`,mcpPath:n,mcpError:`Content scaffolding failed: ${t instanceof Error?t.message:String(t)}`}}let c=await Vr({scope:e.scope,mcp:e.mcp,isTTY:e.isTTY,promptFn:e.promptFn}),d=e.editors??$r(r,e.home),f=e.editors??nr.filter(e=>Q[e].projectConfigPath!==void 0),p=_r(d),m=_r(f),h=e.mcp===!1||c===null,g=Array.from(new Map([...p,...h?[]:m].map(e=>[e.id,e])).values()),_=p.filter(t=>Gr(t,r,e.home)),y=[],b=[],x=new Set;for(let t of g){if(h){let n=``;try{n=t.configPath(r,e.home)}catch{}y.push({editorId:t.id,label:t.label,action:`skipped-flag`,configPath:n,serverName:t.serverName(r)});continue}if(Rr(c)&&p.includes(t)&&y.push(Kr(t,r,a,e.home)),zr(c)&&m.includes(t)&&t.projectConfigPath){let n=t.projectConfigPath(r),i=Kr(t,r,a,e.home,n);y.push(i),(i.action===`written`||i.action===`overwritten`)&&(x.add(n),b.push(qr(t,r)))}}let S=!h&&c!==null&&zr(c)?m.filter(e=>!e.projectConfigPath).map(e=>e.label):void 0,C=h?[]:_.map(e=>Jr(e,r)).filter(e=>e!==void 0).filter(e=>!x.has(e.path)),w=_.some(e=>e.id===`claude`)&&!h?Wr(r,a):void 0,ee=await(e.installUserSkill??v)({home:e.home}),T=u({home:e.home}),E=h?`skipped-flag`:`skipped-missing`,D=y.find(e=>e.editorId===`claude`)??y[0]??{action:E,configPath:Q.claude.configPath(r,e.home)};return{projectRoot:r,contentCreated:s.created,contentUpdated:s.updated,contentSkipped:s.skipped,editors:y,projectSkills:b,legacyProjectConfigs:C,launchJson:w,skillInstall:ee,didGitInit:o.didInit,claudeDesktopDetected:T,mcpAction:D.action,mcpPath:D.configPath,mcpError:`error`in D?D.error:void 0,projectScopeUnsupportedLabels:S}}function Qr(e,t){let n=[],r=e.editors.some(e=>e.action===`written`||e.action===`overwritten`),i=e.editors.some(e=>e.action===`failed`)||e.projectSkills.some(e=>e.action===`failed`),a=e.editors.length>0&&e.editors.every(e=>e.action===`skipped-flag`),o=e.editors.length>0&&e.editors.every(e=>e.action===`skipped-missing`),s=e=>{let n=e.configPath.startsWith(t)?N(t,e.configPath):e.configPath;switch(e.action){case`created`:return` app preview server ${n} configured for Claude Code Desktop embedded browser`;case`merged`:return` app preview server ${n} updated for Claude Code Desktop embedded browser`;case`failed`:return` app preview server ${n} FAILED: ${e.error}`}};e.didGitInit&&n.push(`Initialized git repo at ${t}/.git/ (default branch: main)`);let c=M(t,`.ok`);if(e.contentCreated.length>0||e.contentUpdated.length>0?(n.push(O(`Content scaffolded at ${c}/`)),e.contentCreated.length>0&&n.push(` Created: ${e.contentCreated.join(`, `)}`),e.contentUpdated.length>0&&n.push(` Updated: ${e.contentUpdated.join(`, `)}`)):n.push(O(`Content already present at ${c}/`)),e.contentSkipped.length>0&&n.push(` Skipped (already exist): ${e.contentSkipped.join(`, `)}`),n.push(``),e.mcpError&&e.editors.length===0)n.push(`Warning: ${e.mcpError}`);else if(e.editors.length===0)if(n.push(O(`MCP server configuration:`)),e.mcpAction===`skipped-flag`)n.push(` MCP config not written — use without --no-mcp to configure editors`);else if(e.projectScopeUnsupportedLabels&&e.projectScopeUnsupportedLabels.length>0){let t=e.projectScopeUnsupportedLabels.join(`, `),r=e.projectScopeUnsupportedLabels.length===1?`does`:`do`;n.push(` ${t} ${r} not support project-level config; skipped`)}else n.push(` No supported editor config directories detected; skipped MCP registration`);else if(a)n.push(`MCP config not written — use without --no-mcp to configure editors`);else if(o)n.push(O(`MCP server configuration:`)),n.push(` No supported editor config directories detected; skipped MCP registration`);else{n.push(O(`MCP server configuration:`));for(let r of e.editors){let i=r.configPath.startsWith(t)?N(t,r.configPath):r.configPath.replace(/^\/Users\/[^/]+/,`~`),a=r.serverName===`open-knowledge`?``:` (${r.serverName})`,o=r.configScope===`project`?` (project)`:``,c=`${r.label}${o}`,l=` `.repeat(Math.max(1,20-c.length)),u=r.editorId===`claude-desktop`&&(r.action===`written`||r.action===`overwritten`)?` — quit and relaunch Claude Desktop to activate`:``;switch(r.action){case`written`:n.push(` ${c}${l}${i} ${D(`registered`)}${a}${u}`);break;case`overwritten`:n.push(` ${c}${l}${i} ${D(`updated`)}${a}${u}`);break;case`skipped-missing`:n.push(` ${c}${l}${i} config root missing; skipped`);break;case`failed`:n.push(` ${c}${l}${i} ${te(`FAILED`)}: ${r.error}`);break;case`skipped-flag`:break}r.editorId===`claude`&&e.launchJson&&n.push(s(e.launchJson))}if(e.projectScopeUnsupportedLabels&&e.projectScopeUnsupportedLabels.length>0){let t=e.projectScopeUnsupportedLabels.join(`, `),r=e.projectScopeUnsupportedLabels.length===1?`does`:`do`;n.push(` ${t} ${r} not support project-level config; skipped`)}}if(e.projectSkills.length>0){n.push(``),n.push(O(`Project-local skills:`));for(let r of e.projectSkills){let e=`${r.label} (project)`,i=` `.repeat(Math.max(1,20-e.length)),a=r.path?N(t,r.path):``;switch(r.action){case`written`:n.push(` ${e}${i}${a} ${D(`installed`)}`);break;case`overwritten`:n.push(` ${e}${i}${a} ${D(`updated`)}`);break;case`skipped-unsupported`:n.push(` ${e}${i}no known project skill surface; skipped`);break;case`failed`:n.push(` ${e}${i}${a} ${te(`FAILED`)}: ${r.error}`);break}}}if(i&&(n.push(``),n.push(`For failed editors, add the MCP server entry or project skill manually. See:`),n.push(` https://github.com/inkeep/open-knowledge#mcp-setup`)),e.legacyProjectConfigs.length>0){n.push(``),n.push(`Project MCP configs found:`);for(let r of e.legacyProjectConfigs)n.push(` ${r.label} ${N(t,r.path)}`);n.push(` These project-local files may override the global config. Remove them if you want fully user-scoped MCP setup in this project.`)}if(e.skillInstall)switch(n.push(``),n.push(O(`User-global skill:`)),e.skillInstall){case`installed`:n.push(` open-knowledge ${D(`installed to detected agent hosts`)} via \`npx skills\``);break;case`skip-current`:n.push(` open-knowledge ${D(`already installed at current version`)}`);break;case`failed`:n.push(` ${ne(`open-knowledge install failed — MCP still configured; run manually:`)}`),n.push(` ${ne(` npx skills@~1.5.0 add <bundled-path> --agent '*' -g -y --copy`)}`);break}if(e.claudeDesktopDetected&&(n.push(``),n.push(`Claude Desktop App detected. To enable in Claude Chat & Cowork, run: ${O(`ok install-skill`)}`)),e.preview?(n.push(``),n.push(re(e.preview,t))):e.previewWarning&&(n.push(``),n.push(`Content preview unavailable: ${e.previewWarning}`)),r){let t=new Set,r=e.editors.filter(e=>e.action===`written`||e.action===`overwritten`).filter(e=>!t.has(e.editorId)&&t.add(e.editorId)).map(e=>e.label);n.push(``),n.push(`${D(`✓`)} ${O(`Next steps:`)}`),n.push(` 1. Open your editor (${E(r.join(` / `))})`),n.push(` 2. Approve the MCP server when prompted`),n.push(` 3. (Optional) scaffold the starter knowledge-base structure:`),n.push(` - ${E(`ok seed`)}`),n.push(` 4. Use the three MCP workflow tools as you build the wiki:`),n.push(` - ${E(`mcp__open-knowledge__ingest`)} — capture an external source`),n.push(` - ${E(`mcp__open-knowledge__research`)} — gather sources and write findings`),n.push(` - ${E(`mcp__open-knowledge__consolidate`)} — promote research to canonical articles`)}return n.join(`
405
+ `,required:!1,theme:{icon:{checked:`[x]`,unchecked:`[ ]`}},choices:[{name:`User-level (~/.claude.json, ~/.cursor/mcp.json, …)`,value:`user`,checked:!0},{name:`Project-level (.mcp.json, .cursor/mcp.json, …)`,value:`project`,checked:!0}]});return e.includes(`user`)&&e.includes(`project`)?`both`:e.includes(`user`)?`user`:e.includes(`project`)?`project`:null}async function Vr(e){return e.mcp===!1?null:e.scope?e.scope:e.isTTY??process.stdout.isTTY?(e.promptFn??Br)():`both`}const Hr=`0.0.1`,Ur=`open-knowledge-ui`;function Wr(e,t={}){let n=M(e,`.claude`,`launch.json`),r=t.mode===`dev`?{name:Ur,runtimeExecutable:`node`,runtimeArgs:[ar(),`ui`],port:Er,autoPort:!0}:{name:Ur,runtimeExecutable:`npx`,runtimeArgs:[`@inkeep/open-knowledge`,`ui`],port:Er,autoPort:!0};try{if(Lr(n,e),!F(n))return I(j(n),{recursive:!0}),L(n,`${JSON.stringify({version:Hr,configurations:[r]},null,2)}\n`,`utf-8`),{action:`created`,configPath:n};let t=de(n,`utf-8`).trim(),i=t?JSON.parse(t):{};if(!T(i))return{action:`failed`,configPath:n,error:`launch.json root is not an object`};let a=Array.isArray(i.configurations)?i.configurations:[],o=a.findIndex(e=>T(e)&&e.name===Ur);o>=0?a[o]=r:a.push(r);let s={...i,version:i.version??Hr,configurations:a};return L(n,`${JSON.stringify(s,null,2)}\n`,`utf-8`),{action:o>=0?`merged`:`created`,configPath:n}}catch(e){return{action:`failed`,configPath:n,error:e instanceof Error?e.message:String(e)}}}function Gr(e,t,n){try{return F(e.detectPath?.(t,n)??j(e.configPath(t,n)))}catch{return!1}}function Kr(e,t,n,r,i){let a=e.serverName(t),o;try{o=i??e.configPath(t,r)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:``,serverName:a,error:t instanceof Error?t.message:String(t)}}if(!i&&!n.skipAvailabilityCheck&&!Gr(e,t,r))return{editorId:e.id,label:e.label,action:`skipped-missing`,configPath:o,serverName:a};if(i!==void 0)try{Lr(o,t)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),configScope:`project`}}let s;try{s=e.format===`toml`?Pr(o):Nr(o)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t)}}let c=s[e.topLevelKey]??{},l=c[a],u;try{u=e.buildEntry(t,n)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t)}}let d={...s,[e.topLevelKey]:{...c,[a]:u}};try{e.format===`toml`?Ir(o,d):Fr(o,d)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t)}}return{editorId:e.id,label:e.label,action:l===void 0?`written`:`overwritten`,configPath:o,serverName:a,...i===void 0?{}:{configScope:`project`}}}function qr(e,t){let n=e.projectSkillPath?.(t);if(!n)return{editorId:e.id,label:e.label,action:`skipped-unsupported`,path:``};try{let r=c(),i=j(n);Lr(i,t);let a=F(n)?`overwritten`:`written`;return pe(i,{recursive:!0,force:!0}),I(j(i),{recursive:!0}),le(r,i,{recursive:!0}),{editorId:e.id,label:e.label,action:a,path:n}}catch(t){return{editorId:e.id,label:e.label,action:`failed`,path:n,error:t instanceof Error?t.message:String(t)}}}function Jr(e,t){let n=e.projectConfigPath?.(t);if(!(!n||!F(n)))return{editorId:e.id,label:e.label,path:n}}async function Yr(e){let t=_r(e.editors),n={mode:`published`,cliPath:e.cliPath,skipAvailabilityCheck:!0};return t.map(t=>Kr(t,``,n,e.home))}function Xr(e,t,n,r){let i;try{i=r??e.configPath(t,n)}catch{return null}let a;try{a=e.format===`toml`?Pr(i):Nr(i)}catch{return null}let o=a[e.topLevelKey];if(!T(o))return null;let s=o[e.serverName(t)];return T(s)?s:null}async function Zr(e={}){let t=P(e.cwd??process.cwd()),n=tr(t,{homeDir:e.home}),r=n.projectRoot,i=!F(M(r,`.ok`));n.ancestorPromoted?console.log(`[ok] Opened existing project at ${r}`):n.gitRootPromoted&&i&&console.log(`[ok] Initialized OK at ${r} — opened parent of ${N(r,t)} because it contains a .git folder`);let a={mode:e.devMcp?`dev`:`published`},o=await l(r),s;try{s=Qn(r,{contentDir:n.defaultContentDir})}catch(t){let n=Q.claude.configPath(r,e.home);return{projectRoot:r,contentCreated:[],contentUpdated:[],contentSkipped:[],editors:[],projectSkills:[],legacyProjectConfigs:[],didGitInit:o.didInit,claudeDesktopDetected:!1,mcpAction:`failed`,mcpPath:n,mcpError:`Content scaffolding failed: ${t instanceof Error?t.message:String(t)}`}}let c=await Vr({scope:e.scope,mcp:e.mcp,isTTY:e.isTTY,promptFn:e.promptFn}),d=e.editors??$r(r,e.home),f=e.editors??nr.filter(e=>Q[e].projectConfigPath!==void 0),p=_r(d),m=_r(f),h=e.mcp===!1||c===null,g=Array.from(new Map([...p,...h?[]:m].map(e=>[e.id,e])).values()),_=p.filter(t=>Gr(t,r,e.home)),y=[],b=[],x=new Set;for(let t of g){if(h){let n=``;try{n=t.configPath(r,e.home)}catch{}y.push({editorId:t.id,label:t.label,action:`skipped-flag`,configPath:n,serverName:t.serverName(r)});continue}if(Rr(c)&&p.includes(t)&&y.push(Kr(t,r,a,e.home)),zr(c)&&m.includes(t)&&t.projectConfigPath){let n=t.projectConfigPath(r),i=Kr(t,r,a,e.home,n);y.push(i),(i.action===`written`||i.action===`overwritten`)&&(x.add(n),b.push(qr(t,r)))}}let S=!h&&c!==null&&zr(c)?m.filter(e=>!e.projectConfigPath).map(e=>e.label):void 0,C=h?[]:_.map(e=>Jr(e,r)).filter(e=>e!==void 0).filter(e=>!x.has(e.path)),w=_.some(e=>e.id===`claude`)&&!h?Wr(r,a):void 0,ee=await(e.installUserSkill??v)({home:e.home}),T=u({home:e.home}),E=h?`skipped-flag`:`skipped-missing`,D=y.find(e=>e.editorId===`claude`)??y[0]??{action:E,configPath:Q.claude.configPath(r,e.home)};return{projectRoot:r,contentCreated:s.created,contentUpdated:s.updated,contentSkipped:s.skipped,editors:y,projectSkills:b,legacyProjectConfigs:C,launchJson:w,skillInstall:ee,didGitInit:o.didInit,claudeDesktopDetected:T,mcpAction:D.action,mcpPath:D.configPath,mcpError:`error`in D?D.error:void 0,projectScopeUnsupportedLabels:S}}function Qr(e,t){let n=[],r=e.editors.some(e=>e.action===`written`||e.action===`overwritten`),i=e.editors.some(e=>e.action===`failed`)||e.projectSkills.some(e=>e.action===`failed`),a=e.editors.length>0&&e.editors.every(e=>e.action===`skipped-flag`),o=e.editors.length>0&&e.editors.every(e=>e.action===`skipped-missing`),s=e=>{let n=e.configPath.startsWith(t)?N(t,e.configPath):e.configPath;switch(e.action){case`created`:return` app preview server ${n} configured for Claude Code Desktop embedded browser`;case`merged`:return` app preview server ${n} updated for Claude Code Desktop embedded browser`;case`failed`:return` app preview server ${n} FAILED: ${e.error}`}};e.didGitInit&&n.push(`Initialized git repo at ${t}/.git/ (default branch: main)`);let c=M(t,`.ok`);if(e.contentCreated.length>0||e.contentUpdated.length>0?(n.push(O(`Content scaffolded at ${c}/`)),e.contentCreated.length>0&&n.push(` Created: ${e.contentCreated.join(`, `)}`),e.contentUpdated.length>0&&n.push(` Updated: ${e.contentUpdated.join(`, `)}`)):n.push(O(`Content already present at ${c}/`)),e.contentSkipped.length>0&&n.push(` Skipped (already exist): ${e.contentSkipped.join(`, `)}`),n.push(``),e.mcpError&&e.editors.length===0)n.push(`Warning: ${e.mcpError}`);else if(e.editors.length===0)if(n.push(O(`MCP server configuration:`)),e.mcpAction===`skipped-flag`)n.push(` MCP config not written — use without --no-mcp to configure editors`);else if(e.projectScopeUnsupportedLabels&&e.projectScopeUnsupportedLabels.length>0){let t=e.projectScopeUnsupportedLabels.join(`, `),r=e.projectScopeUnsupportedLabels.length===1?`does`:`do`;n.push(` ${t} ${r} not support project-level config; skipped`)}else n.push(` No supported editor config directories detected; skipped MCP registration`);else if(a)n.push(`MCP config not written — use without --no-mcp to configure editors`);else if(o)n.push(O(`MCP server configuration:`)),n.push(` No supported editor config directories detected; skipped MCP registration`);else{n.push(O(`MCP server configuration:`));for(let r of e.editors){let i=r.configPath.startsWith(t)?N(t,r.configPath):r.configPath.replace(/^\/Users\/[^/]+/,`~`),a=r.serverName===`open-knowledge`?``:` (${r.serverName})`,o=r.configScope===`project`?` (project)`:``,c=`${r.label}${o}`,l=` `.repeat(Math.max(1,20-c.length)),u=r.editorId===`claude-desktop`&&(r.action===`written`||r.action===`overwritten`)?` — quit and relaunch Claude Desktop to activate`:``;switch(r.action){case`written`:n.push(` ${c}${l}${i} ${D(`registered`)}${a}${u}`);break;case`overwritten`:n.push(` ${c}${l}${i} ${D(`updated`)}${a}${u}`);break;case`skipped-missing`:n.push(` ${c}${l}${i} config root missing; skipped`);break;case`failed`:n.push(` ${c}${l}${i} ${te(`FAILED`)}: ${r.error}`);break;case`skipped-flag`:break}r.editorId===`claude`&&e.launchJson&&n.push(s(e.launchJson))}if(e.projectScopeUnsupportedLabels&&e.projectScopeUnsupportedLabels.length>0){let t=e.projectScopeUnsupportedLabels.join(`, `),r=e.projectScopeUnsupportedLabels.length===1?`does`:`do`;n.push(` ${t} ${r} not support project-level config; skipped`)}}if(e.projectSkills.length>0){n.push(``),n.push(O(`Project-local skills:`));for(let r of e.projectSkills){let e=`${r.label} (project)`,i=` `.repeat(Math.max(1,20-e.length)),a=r.path?N(t,r.path):``;switch(r.action){case`written`:n.push(` ${e}${i}${a} ${D(`installed`)}`);break;case`overwritten`:n.push(` ${e}${i}${a} ${D(`updated`)}`);break;case`skipped-unsupported`:n.push(` ${e}${i}no known project skill surface; skipped`);break;case`failed`:n.push(` ${e}${i}${a} ${te(`FAILED`)}: ${r.error}`);break}}}if(i&&(n.push(``),n.push(`For failed editors, add the MCP server entry or project skill manually. See:`),n.push(` https://github.com/inkeep/open-knowledge#mcp-setup`)),e.legacyProjectConfigs.length>0){n.push(``),n.push(`Project MCP configs found:`);for(let r of e.legacyProjectConfigs)n.push(` ${r.label} ${N(t,r.path)}`);n.push(` These project-local files may override the global config. Remove them if you want fully user-scoped MCP setup in this project.`)}if(e.skillInstall)switch(n.push(``),n.push(O(`User-global skill:`)),e.skillInstall){case`installed`:n.push(` open-knowledge ${D(`installed to detected agent hosts`)} via \`npx skills\``);break;case`skip-current`:n.push(` open-knowledge ${D(`already installed at current version`)}`);break;case`failed`:n.push(` ${ne(`open-knowledge install failed — MCP still configured; run manually:`)}`),n.push(` ${ne(` npx skills@~1.5.0 add <bundled-path> --agent '*' -g -y --copy`)}`);break}if(e.claudeDesktopDetected&&(n.push(``),n.push(`Claude Desktop App detected. To enable in Claude Chat & Cowork, run: ${O(`ok install-skill`)}`)),e.preview?(n.push(``),n.push(re(e.preview,t))):e.previewWarning&&(n.push(``),n.push(`Content preview unavailable: ${e.previewWarning}`)),r){let t=new Set,r=e.editors.filter(e=>e.action===`written`||e.action===`overwritten`).filter(e=>!t.has(e.editorId)&&t.add(e.editorId)).map(e=>e.label);n.push(``),n.push(`${D(`✓`)} ${O(`Next steps:`)}`),n.push(` 1. Open your editor (${E(r.join(` / `))})`),n.push(` 2. Approve the MCP server when prompted`),n.push(` 3. (Optional) scaffold the starter knowledge-base structure:`),n.push(` - ${E(`ok seed`)}`),n.push(` 4. Use the three MCP workflow tools as you build the wiki:`),n.push(` - ${E(`mcp__open-knowledge__ingest`)} — capture an external source`),n.push(` - ${E(`mcp__open-knowledge__research`)} — gather sources and write findings`),n.push(` - ${E(`mcp__open-knowledge__consolidate`)} — promote research to canonical articles`)}return n.join(`
406
406
  `)}function $r(e,t){let n=[];for(let r of nr)Gr(Q[r],e,t)&&n.push(r);return n}function ei(){return new i(`init`).description(`Scaffold .ok/ in the current directory and register the MCP server for your editor(s)`).option(`--mcp`,`Register the MCP server for selected editors (default: true)`,!0).option(`--no-mcp`,`Scaffold the .ok/ directory but do not touch MCP config`).option(`--dev-mcp`,`Register a local dev MCP entry using node + packages/cli/dist/cli.mjs with debug logging`).addOption(new r(`--scope <scope>`,`Write MCP config at user level, project level, or both`).choices([`user`,`project`,`both`])).action(async e=>{let t=process.cwd(),n;try{n=await Zr({cwd:t,mcp:e.mcp,devMcp:e.devMcp,scope:e.scope})}catch(e){if(e instanceof s){process.stderr.write(`open-knowledge requires git to initialize a parent repo. Install git or run 'git init' yourself, then re-run.
407
- `),e.stderr&&process.stderr.write(`${e.stderr.trim()}\n`),process.exitCode=1;return}throw e}try{let{previewContent:e}=await import(`./preview-DCoA7FqK.mjs`),{loadConfig:t}=await import(`./loader-DyZnLFXV.mjs`),{resolveContentDir:r}=await import(`./dist-JvyJrwkx.mjs`),{config:i}=t(n.projectRoot),a=r(i,n.projectRoot);n.preview=e({projectDir:n.projectRoot,contentDir:a})}catch(e){n.previewWarning=e instanceof Error?e.message:String(e)}process.stdout.write(`${Qr(n,n.projectRoot)}\n`),(n.editors.some(e=>e.action===`failed`)||n.mcpAction===`failed`)&&(process.exitCode=1)})}export{Ze as C,V as E,ct as S,De as T,dt as _,Vr as a,pt as b,Kr as c,nr as d,Z as f,mt as g,Qn as h,Xr as i,Yr as l,tr as m,Qr as n,Zr as o,Q as p,ei as r,Wr as s,$r as t,Mr as u,ft as v,Xe as w,_t as x,ht as y};
408
- //# sourceMappingURL=init-DoDYKuWt.mjs.map
407
+ `),e.stderr&&process.stderr.write(`${e.stderr.trim()}\n`),process.exitCode=1;return}throw e}try{let{previewContent:e}=await import(`./preview-f1ZGdsVb.mjs`),{loadConfig:t}=await import(`./loader-B01x_zMV.mjs`),{resolveContentDir:r}=await import(`./dist-JvyJrwkx.mjs`),{config:i}=t(n.projectRoot),a=r(i,n.projectRoot);n.preview=e({projectDir:n.projectRoot,contentDir:a})}catch(e){n.previewWarning=e instanceof Error?e.message:String(e)}process.stdout.write(`${Qr(n,n.projectRoot)}\n`),(n.editors.some(e=>e.action===`failed`)||n.mcpAction===`failed`)&&(process.exitCode=1)})}export{Ze as C,V as E,ct as S,De as T,dt as _,Vr as a,pt as b,Kr as c,nr as d,Z as f,mt as g,Qn as h,Xr as i,Yr as l,tr as m,Qr as n,Zr as o,Q as p,ei as r,Wr as s,$r as t,Mr as u,ft as v,Xe as w,_t as x,ht as y};
408
+ //# sourceMappingURL=init-JeGcMd-V.mjs.map
@@ -0,0 +1 @@
1
+ import{n as e}from"./loader-ZLKIXjJM.mjs";export{e as loadConfig};
@@ -1,4 +1,4 @@
1
- import{Jr as e,f as t,fi as n,ji as r,qr as i,vi as a}from"./dist-BFaejI07.mjs";import{t as o}from"./constants-BMZzAuZK.mjs";import{t as s}from"./is-object-DF0ZeuvD.mjs";import{resolve as c}from"node:path";import{existsSync as l,readFileSync as u}from"node:fs";import{realpath as d}from"node:fs/promises";async function f(e){let t=c(e);try{return await d(t)}catch(e){if(e.code!==`ENOENT`){let n=e instanceof Error?e.message:String(e);console.warn(`[normalize-cwd] realpath failed for ${t}: ${n}`)}return t}}var p=r();function m(e,t){let n={...e};for(let r of Object.keys(t)){let i=e[r],a=t[r];s(a)&&s(i)?n[r]=m(i,a):a!==void 0&&(n[r]=a)}return n}function h(e){if(!l(e))return{value:null,path:e,source:null,doc:null};let t;try{t=u(e,`utf-8`)}catch(t){return console.warn(`[config] Failed to read ${e}: ${t instanceof Error?t.message:t}`),{value:null,path:e,source:null,doc:null}}let n=(0,p.parseDocument)(t);if(n.errors.length>0)return console.warn(`[config] Failed to parse ${e}: ${n.errors.map(e=>e.message).join(`; `)}`),{value:null,path:e,source:t,doc:null};let r=n.toJSON();return s(r)?{value:r,path:e,source:t,doc:n}:{value:null,path:e,source:t,doc:n}}const g=[`include`,`exclude`];function _(e){let t="Run `ok config migrate` to strip the obsolete key from config.yml automatically, or remove it by hand.";return e===`exclude`?[`Move these patterns to .okignore at the project root (gitignore syntax, 1:1 migration).`,t].join(` `):[`content.include has been removed.`,`For subdirectory scoping, set content.dir in .ok/config.yml instead.`,`For pattern-based filtering, use .okignore (gitignore syntax — exclude-only; do not copy include patterns directly).`,t].join(` `)}function v(e){let t=e.value;if(!s(t))return[];let n=t.content;if(!s(n))return[];let r=[];for(let t of g)if(t in n){let n=[`content`,t],i;e.doc!==null&&e.source!==null&&(i=a({file:e.path,source:e.source,doc:e.doc,path:n})),r.push({code:`REMOVED_KEY`,path:n,redirect:_(t),...i===void 0?{}:{source:i}})}return r}function y(e,t){return e.map(e=>{let n=e.path.map(e=>typeof e==`symbol`?String(e):e),r={path:n,message:e.message,issueCode:e.code};if(t.doc!==null&&t.source!==null){let e=a({file:t.path,source:t.source,doc:t.doc,path:n});if(e!==void 0)return{...r,source:e}}return r})}function b(r){let a=r??process.cwd(),s=[],l=e(`user`,a),u=i({absPath:l}),d={};u.valid&&u.source!==void 0?(d=m(d,u.value),s.push(l)):u.valid;let f=c(a,`.ok`,o),p=h(f);if(p.value!==null){let e=v(p);if(e.length>0)throw Error(e.map(n).join(`
1
+ import{Jr as e,f as t,fi as n,ji as r,qr as i,vi as a}from"./dist-BFaejI07.mjs";import{t as o}from"./constants-BKcZ-SZr.mjs";import{t as s}from"./is-object-DF0ZeuvD.mjs";import{resolve as c}from"node:path";import{existsSync as l,readFileSync as u}from"node:fs";import{realpath as d}from"node:fs/promises";async function f(e){let t=c(e);try{return await d(t)}catch(e){if(e.code!==`ENOENT`){let n=e instanceof Error?e.message:String(e);console.warn(`[normalize-cwd] realpath failed for ${t}: ${n}`)}return t}}var p=r();function m(e,t){let n={...e};for(let r of Object.keys(t)){let i=e[r],a=t[r];s(a)&&s(i)?n[r]=m(i,a):a!==void 0&&(n[r]=a)}return n}function h(e){if(!l(e))return{value:null,path:e,source:null,doc:null};let t;try{t=u(e,`utf-8`)}catch(t){return console.warn(`[config] Failed to read ${e}: ${t instanceof Error?t.message:t}`),{value:null,path:e,source:null,doc:null}}let n=(0,p.parseDocument)(t);if(n.errors.length>0)return console.warn(`[config] Failed to parse ${e}: ${n.errors.map(e=>e.message).join(`; `)}`),{value:null,path:e,source:t,doc:null};let r=n.toJSON();return s(r)?{value:r,path:e,source:t,doc:n}:{value:null,path:e,source:t,doc:n}}const g=[`include`,`exclude`];function _(e){let t="Run `ok config migrate` to strip the obsolete key from config.yml automatically, or remove it by hand.";return e===`exclude`?[`Move these patterns to .okignore at the project root (gitignore syntax, 1:1 migration).`,t].join(` `):[`content.include has been removed.`,`For subdirectory scoping, set content.dir in .ok/config.yml instead.`,`For pattern-based filtering, use .okignore (gitignore syntax — exclude-only; do not copy include patterns directly).`,t].join(` `)}function v(e){let t=e.value;if(!s(t))return[];let n=t.content;if(!s(n))return[];let r=[];for(let t of g)if(t in n){let n=[`content`,t],i;e.doc!==null&&e.source!==null&&(i=a({file:e.path,source:e.source,doc:e.doc,path:n})),r.push({code:`REMOVED_KEY`,path:n,redirect:_(t),...i===void 0?{}:{source:i}})}return r}function y(e,t){return e.map(e=>{let n=e.path.map(e=>typeof e==`symbol`?String(e):e),r={path:n,message:e.message,issueCode:e.code};if(t.doc!==null&&t.source!==null){let e=a({file:t.path,source:t.source,doc:t.doc,path:n});if(e!==void 0)return{...r,source:e}}return r})}function b(r){let a=r??process.cwd(),s=[],l=e(`user`,a),u=i({absPath:l}),d={};u.valid&&u.source!==void 0?(d=m(d,u.value),s.push(l)):u.valid;let f=c(a,`.ok`,o),p=h(f);if(p.value!==null){let e=v(p);if(e.length>0)throw Error(e.map(n).join(`
2
2
 
3
3
  `));d=m(d,p.value),s.push(f)}x(d,[`upload`,`maxBytes`],`streaming uploads have no user-facing cap`),x(d,[`github`,`oauthAppClientId`],`use the OPEN_KNOWLEDGE_GITHUB_CLIENT_ID env var instead`),x(d,[`server`,`host`],`use the --host flag or HOST env var instead`),x(d,[`server`,`openOnAgentEdit`]),x(d,[`mcp`,`autoStart`],`to disable auto-start, set OK_MCP_AUTOSTART=0`),x(d,[`mcp`,`tools`,`read_document`,`historyDepth`]),x(d,[`mcp`,`tools`,`grep`,`maxResults`]),x(d,[`mcp`,`tools`,`search`,`maxResults`]),x(d,[`preview`,`baseUrl`],"preview URLs now resolve only to the running UI process — start one with `ok ui`");let g=t.safeParse(d);if(!g.success){let e={code:`SCHEMA_INVALID`,issues:y(g.error.issues,p)};throw Error(n(e))}return{config:g.data,sources:s}}function x(e,t,n){let r=e;for(let e=0;e<t.length-1;e++){if(!s(r))return;r=r[t[e]]}if(!s(r))return;let i=t[t.length-1];if(r[i]===void 0)return;let a=t.join(`.`);console.warn(`[config] ${a} is no longer user-configurable; ${n??`the value is hardcoded in @inkeep/open-knowledge-core`}. Remove the key to silence this warning.`)}function S(e){let t=e.cacheMs??1e3,n=e.loadConfigFn??b,r=new Map,i=new Map,a=f(e.startupCwd);return async o=>{let s=await f(o??e.startupCwd),c=Date.now(),l=r.get(s);if(l&&l.expiresAt>c)return l.config;let u=i.get(s);if(u)return await u;let d=(async()=>{if(s===await a)return r.set(s,{config:e.startupConfig,expiresAt:Date.now()+t}),e.startupConfig;let i=n(s).config;return r.set(s,{config:i,expiresAt:Date.now()+t}),i})();i.set(s,d);try{return await d}finally{i.delete(s)}}}export{b as n,S as t};
4
- //# sourceMappingURL=loader-DwY1uRWB.mjs.map
4
+ //# sourceMappingURL=loader-ZLKIXjJM.mjs.map
@@ -1,2 +1,2 @@
1
1
  import{execFile as e}from"node:child_process";const t=new Set([`http:`,`https:`]),n=/[\u0000-\u0020\u007F-\u009F"'`\\&|<>^()$;{}[\]*?!~]/;function r(e,t){console.warn(`Could not auto-open browser (${t}); visit ${e} manually`)}function i(i){let a;try{a=new URL(i)}catch{r(i,`invalid URL`);return}if(!t.has(a.protocol)){r(i,`unsupported scheme '${a.protocol}'`);return}if(n.test(i)){r(i,`URL contains unsafe characters`);return}e(process.platform===`darwin`?`open`:process.platform===`win32`?`cmd`:`xdg-open`,process.platform===`win32`?[`/c`,`start`,``,i]:[i],e=>{e&&console.warn(`Could not auto-open browser (${e.message}); visit ${i} manually`)})}export{i as openBrowser};
2
- //# sourceMappingURL=open-browser-CoKDMbx5.mjs.map
2
+ //# sourceMappingURL=open-browser-BOeCxs2W.mjs.map
@@ -1,3 +1,3 @@
1
- import{Ct as e}from"./dist-BFaejI07.mjs";import"./constants-BMZzAuZK.mjs";import{join as t,relative as n}from"node:path";import{existsSync as r,lstatSync as i,readdirSync as a,realpathSync as o,statSync as s}from"node:fs";function c(r){let{projectDir:c,contentDir:l,sampleCap:u=5}=r,d=[],f=[];try{i(l)}catch(e){return{totalCount:0,sample:[],contentDir:l,warnings:[`cannot access content directory ${l}: ${e instanceof Error?e.message:String(e)}`]}}let p;try{p=e({projectDir:c,contentDir:l})}catch(e){return{totalCount:0,sample:[],contentDir:l,warnings:[e instanceof Error?e.message:String(e)]}}function m(e){let r;try{r=a(e,{withFileTypes:!0})}catch(t){let r=t instanceof Error?t.message:String(t);d.push(`could not read directory ${n(l,e)||`.`}: ${r}`);return}for(let i of r){let r=t(e,i.name);if(i.isSymbolicLink()){let e;try{e=o(r)}catch(e){let t=e.code;t===`ENOENT`||t===`ELOOP`?d.push(`broken or cyclic symlink: ${n(l,r)}`):d.push(`cannot resolve symlink ${n(l,r)}: ${t??`unknown error`}`);continue}let t;try{t=s(e)}catch{continue}if(t.isDirectory()){let e=n(l,r);if(p.isDirExcluded(e))continue;m(r)}else if(t.isFile()){let e=n(l,r);if(p.isExcluded(e))continue;f.push(e)}}else if(i.isDirectory()){let e=n(l,r);if(p.isDirExcluded(e))continue;m(r)}else if(i.isFile()){let e=n(l,r);if(p.isExcluded(e))continue;f.push(e)}}}return m(l),{totalCount:f.length,sample:f.slice(0,u),contentDir:l,warnings:d}}function l(e,i){let a=[],o=n(i,e.contentDir),s=o===``?`./`:`./${o}`;if(a.push(`Content:`),a.push(` Found ${e.totalCount} markdown files in ${s}`),e.sample.length>0){let t=e.sample.join(`, `),n=e.totalCount>e.sample.length?`, …`:``;a.push(` Sample: ${t}${n}`)}if(e.warnings.length>0)for(let t of e.warnings)a.push(` Warning: ${t}`);return a.push(``),r(t(i,`.ok`,`config.yml`))?(a.push(` To adjust scope, add patterns to .okignore at the project root.`),a.push(` To change the content root, edit .ok/config.yml → content.dir.`)):a.push(" Run `open-knowledge init` to scaffold config + .okignore."),a.push(``),a.push(` Re-check anytime: open-knowledge preview`),a.join(`
1
+ import{Ct as e}from"./dist-BFaejI07.mjs";import"./constants-BKcZ-SZr.mjs";import{join as t,relative as n}from"node:path";import{existsSync as r,lstatSync as i,readdirSync as a,realpathSync as o,statSync as s}from"node:fs";function c(r){let{projectDir:c,contentDir:l,sampleCap:u=5}=r,d=[],f=[];try{i(l)}catch(e){return{totalCount:0,sample:[],contentDir:l,warnings:[`cannot access content directory ${l}: ${e instanceof Error?e.message:String(e)}`]}}let p;try{p=e({projectDir:c,contentDir:l})}catch(e){return{totalCount:0,sample:[],contentDir:l,warnings:[e instanceof Error?e.message:String(e)]}}function m(e){let r;try{r=a(e,{withFileTypes:!0})}catch(t){let r=t instanceof Error?t.message:String(t);d.push(`could not read directory ${n(l,e)||`.`}: ${r}`);return}for(let i of r){let r=t(e,i.name);if(i.isSymbolicLink()){let e;try{e=o(r)}catch(e){let t=e.code;t===`ENOENT`||t===`ELOOP`?d.push(`broken or cyclic symlink: ${n(l,r)}`):d.push(`cannot resolve symlink ${n(l,r)}: ${t??`unknown error`}`);continue}let t;try{t=s(e)}catch{continue}if(t.isDirectory()){let e=n(l,r);if(p.isDirExcluded(e))continue;m(r)}else if(t.isFile()){let e=n(l,r);if(p.isExcluded(e))continue;f.push(e)}}else if(i.isDirectory()){let e=n(l,r);if(p.isDirExcluded(e))continue;m(r)}else if(i.isFile()){let e=n(l,r);if(p.isExcluded(e))continue;f.push(e)}}}return m(l),{totalCount:f.length,sample:f.slice(0,u),contentDir:l,warnings:d}}function l(e,i){let a=[],o=n(i,e.contentDir),s=o===``?`./`:`./${o}`;if(a.push(`Content:`),a.push(` Found ${e.totalCount} markdown files in ${s}`),e.sample.length>0){let t=e.sample.join(`, `),n=e.totalCount>e.sample.length?`, …`:``;a.push(` Sample: ${t}${n}`)}if(e.warnings.length>0)for(let t of e.warnings)a.push(` Warning: ${t}`);return a.push(``),r(t(i,`.ok`,`config.yml`))?(a.push(` To adjust scope, add patterns to .okignore at the project root.`),a.push(` To change the content root, edit .ok/config.yml → content.dir.`)):a.push(" Run `open-knowledge init` to scaffold config + .okignore."),a.push(``),a.push(` Re-check anytime: open-knowledge preview`),a.join(`
2
2
  `)}export{c as n,l as t};
3
- //# sourceMappingURL=preview-D0Cwj9ak.mjs.map
3
+ //# sourceMappingURL=preview-BIVzSnXG.mjs.map
@@ -0,0 +1 @@
1
+ import{n as e,t}from"./preview-BIVzSnXG.mjs";export{t as formatPreviewBlock,e as previewContent};
@@ -12,7 +12,7 @@ Error generating stack: `+e.message+`
12
12
  `);i=o.pop()??``;for(let e of o)if(e.trim()&&t(e)===`terminal`)return!0}}function jc(e){let t=[],n=[],r=new AbortController,i=!1,a=()=>{for(let e of n.splice(0))e(null)};return e(e=>{i||(n.length>0?n.shift()?.(e):t.push(e),(e.type===`complete`||e.type===`error`)&&(i=!0,r.abort(),a()))},r.signal),{events:{[Symbol.asyncIterator](){return{async next(){if(t.length>0){let e=t.shift();return e===void 0?{value:void 0,done:!0}:{value:e,done:!1}}return i?{value:void 0,done:!0}:new Promise(e=>{n.push(t=>{e(t===null?{value:void 0,done:!0}:{value:t,done:!1})})})}}}},cancel:()=>{i||(i=!0,r.abort(),a())}}}function Mc(){return{start(){return jc((e,t)=>{(async()=>{try{let n=await fetch(`/api/local-op/auth/login`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({json:!0}),signal:t});if(!n.ok){let t=`Failed to start sign-in — try again`;try{let e=await n.json(),r=ir.safeParse(e);r.success&&(t=r.data.title)}catch{}e({type:`error`,message:t});return}if(!n.body){e({type:`error`,message:`Failed to start sign-in — try again`});return}!await Ac(n.body,t=>{let n;try{n=JSON.parse(t)}catch{return console.warn(`[auth-transport] Dropped unparseable NDJSON line:`,t.slice(0,100)),`continue`}if(n&&typeof n==`object`&&n.type===`error`&&`problem`in n){let t=n.problem;return e({type:`error`,message:t?.detail||t?.title||`Unknown error`}),`terminal`}let r=n;return e(r),r.type===`complete`||r.type===`error`?`terminal`:`continue`})&&!t.aborted&&e({type:`error`,message:`Sign-in stream ended without confirmation — please try again`})}catch(t){if(t instanceof Error&&t.name===`AbortError`)return;e({type:`error`,message:`Connection error — try again`})}})()})}}}function Nc(e){return{start(){return e.localOp.auth.start()}}}function Pc(){return{start(e){return jc((t,n)=>{(async()=>{try{let r=await fetch(`/api/local-op/clone`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({url:e.url,dir:e.dir||void 0}),signal:n});if(!r.ok){let e=`Clone failed — check the URL and try again (${r.status})`;try{let t=await r.json(),n=ir.safeParse(t);n.success&&(e=`Clone failed: ${n.data.title}`)}catch{}t({type:`error`,message:e});return}if(!r.body){t({type:`error`,message:`Clone failed — empty response body`});return}let i=r.body.getReader(),a=new TextDecoder,o=``;for(;;){let{done:e,value:r}=await i.read();if(e)break;o+=a.decode(r,{stream:!0});let s=o.split(`
13
13
  `);o=s.pop()??``;for(let e of s){if(!e.trim())continue;let n;try{n=JSON.parse(e)}catch{console.warn(`[clone-transport] Dropped unparseable NDJSON line:`,e.slice(0,100));continue}if(n&&typeof n==`object`&&n.type===`error`&&`problem`in n){let e=n.problem;t({type:`error`,message:e?.detail||e?.title||`Unknown error`});break}t(n)}if(n.aborted)break}n.aborted||t({type:`error`,message:`Clone stream ended unexpectedly — check if the clone completed`})}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;t({type:`error`,message:`Clone failed — connection error`})}})()})}}}function Fc(e){return{start(t){return e.localOp.clone.start(t)}}}var Ic=`ContextMenu`,[Lc,Rc]=Ur(Ic,[Ni]),zc=Ni(),[Bc,Vc]=Lc(Ic),Hc=e=>{let{__scopeContextMenu:t,children:n,onOpenChange:r,dir:i,modal:a=!0}=e,[o,s]=Q.useState(!1),c=zc(t),l=Gr(r),u=Q.useCallback(e=>{s(e),l(e)},[l]);return(0,Z.jsx)(Bc,{scope:t,open:o,onOpenChange:u,modal:a,children:(0,Z.jsx)(Ui,{...c,dir:i,open:o,onOpenChange:u,modal:a,children:n})})};Hc.displayName=Ic;var Uc=`ContextMenuTrigger`,Wc=Q.forwardRef((e,t)=>{let{__scopeContextMenu:n,disabled:r=!1,...i}=e,a=Vc(Uc,n),o=zc(n),s=Q.useRef({x:0,y:0}),c=Q.useRef({getBoundingClientRect:()=>DOMRect.fromRect({width:0,height:0,...s.current})}),l=Q.useRef(0),u=Q.useCallback(()=>window.clearTimeout(l.current),[]),d=e=>{s.current={x:e.clientX,y:e.clientY},a.onOpenChange(!0)};return Q.useEffect(()=>u,[u]),Q.useEffect(()=>void(r&&u()),[r,u]),(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(fa,{...o,virtualRef:c}),(0,Z.jsx)(Br.span,{"data-state":a.open?`open`:`closed`,"data-disabled":r?``:void 0,...i,ref:t,style:{WebkitTouchCallout:`none`,...e.style},onContextMenu:r?e.onContextMenu:zr(e.onContextMenu,e=>{u(),d(e),e.preventDefault()}),onPointerDown:r?e.onPointerDown:zr(e.onPointerDown,yl(e=>{u(),l.current=window.setTimeout(()=>d(e),700)})),onPointerMove:r?e.onPointerMove:zr(e.onPointerMove,yl(u)),onPointerCancel:r?e.onPointerCancel:zr(e.onPointerCancel,yl(u)),onPointerUp:r?e.onPointerUp:zr(e.onPointerUp,yl(u))})]})});Wc.displayName=Uc;var Gc=`ContextMenuPortal`,Kc=e=>{let{__scopeContextMenu:t,...n}=e,r=zc(t);return(0,Z.jsx)(ua,{...r,...n})};Kc.displayName=Gc;var qc=`ContextMenuContent`,Jc=Q.forwardRef((e,t)=>{let{__scopeContextMenu:n,...r}=e,i=Vc(qc,n),a=zc(n),o=Q.useRef(!1);return(0,Z.jsx)(ca,{...a,...r,ref:t,side:`right`,sideOffset:2,align:`start`,onCloseAutoFocus:t=>{e.onCloseAutoFocus?.(t),!t.defaultPrevented&&o.current&&t.preventDefault(),o.current=!1},onInteractOutside:t=>{e.onInteractOutside?.(t),!t.defaultPrevented&&!i.modal&&(o.current=!0)},style:{...e.style,"--radix-context-menu-content-transform-origin":`var(--radix-popper-transform-origin)`,"--radix-context-menu-content-available-width":`var(--radix-popper-available-width)`,"--radix-context-menu-content-available-height":`var(--radix-popper-available-height)`,"--radix-context-menu-trigger-width":`var(--radix-popper-anchor-width)`,"--radix-context-menu-trigger-height":`var(--radix-popper-anchor-height)`}})});Jc.displayName=qc;var Yc=`ContextMenuGroup`,Xc=Q.forwardRef((e,t)=>{let{__scopeContextMenu:n,...r}=e,i=zc(n);return(0,Z.jsx)(xa,{...i,...r,ref:t})});Xc.displayName=Yc;var Zc=`ContextMenuLabel`,Qc=Q.forwardRef((e,t)=>{let{__scopeContextMenu:n,...r}=e,i=zc(n);return(0,Z.jsx)(ma,{...i,...r,ref:t})});Qc.displayName=Zc;var $c=`ContextMenuItem`,el=Q.forwardRef((e,t)=>{let{__scopeContextMenu:n,...r}=e,i=zc(n);return(0,Z.jsx)(Yi,{...i,...r,ref:t})});el.displayName=$c;var tl=`ContextMenuCheckboxItem`,nl=Q.forwardRef((e,t)=>{let{__scopeContextMenu:n,...r}=e,i=zc(n);return(0,Z.jsx)(Ji,{...i,...r,ref:t})});nl.displayName=tl;var rl=`ContextMenuRadioGroup`,il=Q.forwardRef((e,t)=>{let{__scopeContextMenu:n,...r}=e,i=zc(n);return(0,Z.jsx)(na,{...i,...r,ref:t})});il.displayName=rl;var al=`ContextMenuRadioItem`,ol=Q.forwardRef((e,t)=>{let{__scopeContextMenu:n,...r}=e,i=zc(n);return(0,Z.jsx)(ea,{...i,...r,ref:t})});ol.displayName=al;var sl=`ContextMenuItemIndicator`,cl=Q.forwardRef((e,t)=>{let{__scopeContextMenu:n,...r}=e,i=zc(n);return(0,Z.jsx)(Qi,{...i,...r,ref:t})});cl.displayName=sl;var ll=`ContextMenuSeparator`,ul=Q.forwardRef((e,t)=>{let{__scopeContextMenu:n,...r}=e,i=zc(n);return(0,Z.jsx)(Ca,{...i,...r,ref:t})});ul.displayName=ll;var dl=`ContextMenuArrow`,fl=Q.forwardRef((e,t)=>{let{__scopeContextMenu:n,...r}=e,i=zc(n);return(0,Z.jsx)(va,{...i,...r,ref:t})});fl.displayName=dl;var pl=`ContextMenuSub`,ml=e=>{let{__scopeContextMenu:t,children:n,onOpenChange:r,open:i,defaultOpen:a}=e,o=zc(t),[s,c]=Kr({prop:i,defaultProp:a??!1,onChange:r,caller:pl});return(0,Z.jsx)(ka,{...o,open:s,onOpenChange:c,children:n})};ml.displayName=pl;var hl=`ContextMenuSubTrigger`,gl=Q.forwardRef((e,t)=>{let{__scopeContextMenu:n,...r}=e,i=zc(n);return(0,Z.jsx)(Da,{...i,...r,ref:t})});gl.displayName=hl;var _l=`ContextMenuSubContent`,vl=Q.forwardRef((e,t)=>{let{__scopeContextMenu:n,...r}=e,i=zc(n);return(0,Z.jsx)(qi,{...i,...r,ref:t,style:{...e.style,"--radix-context-menu-content-transform-origin":`var(--radix-popper-transform-origin)`,"--radix-context-menu-content-available-width":`var(--radix-popper-available-width)`,"--radix-context-menu-content-available-height":`var(--radix-popper-available-height)`,"--radix-context-menu-trigger-width":`var(--radix-popper-anchor-width)`,"--radix-context-menu-trigger-height":`var(--radix-popper-anchor-height)`}})});vl.displayName=_l;function yl(e){return t=>t.pointerType===`mouse`?void 0:e(t)}var bl=Hc,xl=Wc,Sl=Kc,Cl=Jc,wl=el,Tl=ul,El=`Radio`,[Dl,Ol]=Ur(El),[kl,Al]=Dl(El),jl=Q.forwardRef((e,t)=>{let{__scopeRadio:n,name:r,checked:i=!1,required:a,disabled:o,value:s=`on`,onCheck:c,form:l,...u}=e,[d,f]=Q.useState(null),p=Jr(t,e=>f(e)),m=Q.useRef(!1),h=d?l||!!d.closest(`form`):!0;return(0,Z.jsxs)(kl,{scope:n,checked:i,disabled:o,children:[(0,Z.jsx)(Br.button,{type:`button`,role:`radio`,"aria-checked":i,"data-state":Il(i),"data-disabled":o?``:void 0,disabled:o,value:s,...u,ref:p,onClick:zr(e.onClick,e=>{i||c?.(),h&&(m.current=e.isPropagationStopped(),m.current||e.stopPropagation())})}),h&&(0,Z.jsx)(Fl,{control:d,bubbles:!m.current,name:r,value:s,checked:i,required:a,disabled:o,form:l,style:{transform:`translateX(-100%)`}})]})});jl.displayName=El;var Ml=`RadioIndicator`,Nl=Q.forwardRef((e,t)=>{let{__scopeRadio:n,forceMount:r,...i}=e,a=Al(Ml,n);return(0,Z.jsx)(Hr,{present:r||a.checked,children:(0,Z.jsx)(Br.span,{"data-state":Il(a.checked),"data-disabled":a.disabled?``:void 0,...i,ref:t})})});Nl.displayName=Ml;var Pl=`RadioBubbleInput`,Fl=Q.forwardRef(({__scopeRadio:e,control:t,checked:n,bubbles:r=!0,...i},a)=>{let o=Q.useRef(null),s=Jr(o,a),c=Pa(n),l=Za(t);return Q.useEffect(()=>{let e=o.current;if(!e)return;let t=window.HTMLInputElement.prototype,i=Object.getOwnPropertyDescriptor(t,`checked`).set;if(c!==n&&i){let t=new Event(`click`,{bubbles:r});i.call(e,n),e.dispatchEvent(t)}},[c,n,r]),(0,Z.jsx)(Br.input,{type:`radio`,"aria-hidden":!0,defaultChecked:n,...i,tabIndex:-1,ref:s,style:{...i.style,...l,position:`absolute`,pointerEvents:`none`,opacity:0,margin:0}})});Fl.displayName=Pl;function Il(e){return e?`checked`:`unchecked`}var Ll=[`ArrowUp`,`ArrowDown`,`ArrowLeft`,`ArrowRight`],Rl=`RadioGroup`,[zl,Bl]=Ur(Rl,[to,Ol]),Vl=to(),Hl=Ol(),[Ul,Wl]=zl(Rl),Gl=Q.forwardRef((e,t)=>{let{__scopeRadioGroup:n,name:r,defaultValue:i,value:a,required:o=!1,disabled:s=!1,orientation:c,dir:l,loop:u=!0,onValueChange:d,...f}=e,p=Vl(n),m=un(l),[h,g]=Kr({prop:a,defaultProp:i??null,onChange:d,caller:Rl});return(0,Z.jsx)(Ul,{scope:n,name:r,required:o,disabled:s,value:h,onValueChange:g,children:(0,Z.jsx)(no,{asChild:!0,...p,orientation:c,dir:m,loop:u,children:(0,Z.jsx)(Br.div,{role:`radiogroup`,"aria-required":o,"aria-orientation":c,"data-disabled":s?``:void 0,dir:m,...f,ref:t})})})});Gl.displayName=Rl;var Kl=`RadioGroupItem`,ql=Q.forwardRef((e,t)=>{let{__scopeRadioGroup:n,disabled:r,...i}=e,a=Wl(Kl,n),o=a.disabled||r,s=Vl(n),c=Hl(n),l=Q.useRef(null),u=Jr(t,l),d=a.value===i.value,f=Q.useRef(!1);return Q.useEffect(()=>{let e=e=>{Ll.includes(e.key)&&(f.current=!0)},t=()=>f.current=!1;return document.addEventListener(`keydown`,e),document.addEventListener(`keyup`,t),()=>{document.removeEventListener(`keydown`,e),document.removeEventListener(`keyup`,t)}},[]),(0,Z.jsx)(io,{asChild:!0,...s,focusable:!o,active:d,children:(0,Z.jsx)(jl,{disabled:o,required:a.required,checked:d,...c,...i,name:a.name,ref:u,onCheck:()=>a.onValueChange(i.value),onKeyDown:zr(e=>{e.key===`Enter`&&e.preventDefault()}),onFocus:zr(i.onFocus,()=>{f.current&&l.current?.click()})})})});ql.displayName=Kl;var Jl=`RadioGroupIndicator`,Yl=Q.forwardRef((e,t)=>{let{__scopeRadioGroup:n,...r}=e;return(0,Z.jsx)(Nl,{...Hl(n),...r,ref:t})});Yl.displayName=Jl;var Xl=Gl,Zl=ql,Ql=Yl;async function $l(e){try{await navigator.clipboard.writeText(e)}catch{}}var eu=120*1e3;function tu(e){let t=(0,$.c)(26),{onSuccess:n,onCancel:r,transport:i}=e,[a,o]=(0,Q.useState)(null),[s,c]=(0,Q.useState)(`https://github.com/login/device`),[l,u]=(0,Q.useState)(!1),[d,f]=(0,Q.useState)(null),[p,m]=(0,Q.useState)(!1),[h,g]=(0,Q.useState)(eu),_=(0,Q.useRef)(null),v=(0,Q.useRef)(null),y;t[0]!==n||t[1]!==i?(y=async function(){f(null),m(!0);try{let e=i.start();_.current=e.cancel;let t=e.events[Symbol.asyncIterator](),r=!1,a=await t.next();for(;!a.done;){let e=a.value;if(e.type===`verification`)o(e.user_code),c(e.verification_uri),g(e.expires_in*1e3),$l(e.user_code).then(()=>{u(!0),setTimeout(()=>u(!1),2e3)});else if(e.type===`complete`){r=!0,m(!1),n({login:e.login,name:e.name,email:e.email,avatarUrl:e.avatarUrl});break}else if(e.type===`error`){r=!0,f(e.message),m(!1);break}a=await t.next()}r||(f(`Sign-in stream ended without confirmation — please try again`),m(!1))}catch(e){let t=e;t instanceof Error&&t.name!==`AbortError`&&f(`Connection error — try again`),m(!1)}},t[0]=n,t[1]=i,t[2]=y):y=t[2];let b=y,x;t[3]===b?x=t[4]:(x=()=>{let e=!1;return queueMicrotask(()=>{e||b()}),()=>{e=!0,_.current?.(),_.current=null,v.current&&clearInterval(v.current)}},t[3]=b,t[4]=x);let S;t[5]===Symbol.for(`react.memo_cache_sentinel`)?(S=[],t[5]=S):S=t[5],(0,Q.useEffect)(x,S);let C,w;t[6]===a?(C=t[7],w=t[8]):(C=()=>{if(!a)return;let e=Date.now();return v.current=setInterval(()=>{let t=eu-(Date.now()-e);t<=0?(g(0),v.current&&clearInterval(v.current),f(`Code expired — please try again`)):g(t)},1e3),()=>{v.current&&clearInterval(v.current)}},w=[a],t[6]=a,t[7]=C,t[8]=w),(0,Q.useEffect)(C,w);let T=Math.floor(h/6e4),E=Math.floor(h%6e4/1e3),D;t[9]===E?D=t[10]:(D=E.toString().padStart(2,`0`),t[9]=E,t[10]=D);let O=`${T}:${D}`,k;t[11]!==l||t[12]!==d||t[13]!==O||t[14]!==a||t[15]!==s?(k=a?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Open`,` `,(0,Z.jsx)(`a`,{href:s,target:`_blank`,rel:`noopener noreferrer`,onClick:e=>pi(e,s),onAuxClick:e=>pi(e,s),className:`underline underline-offset-2`,children:s}),` `,`and enter this code:`]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`code`,{className:`flex-1 text-center text-2xl font-mono font-bold tracking-widest border rounded-md py-3 bg-muted`,children:a}),(0,Z.jsx)(X,{variant:`outline`,size:`sm`,onClick:()=>void $l(a).then(()=>{u(!0),setTimeout(()=>u(!1),2e3)}),children:l?`Copied!`:`Copy`})]}),(0,Z.jsxs)(`div`,{className:`flex items-center justify-between text-xs text-muted-foreground`,children:[(0,Z.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[(0,Z.jsx)(`span`,{className:`size-1.5 rounded-full bg-amber-500 animate-pulse`}),`Waiting for authorization`]}),(0,Z.jsxs)(`span`,{children:[`Expires in `,O]})]})]}):(0,Z.jsx)(`div`,{className:`flex items-center justify-center py-6 text-sm text-muted-foreground`,children:d?null:`Starting sign-in flow`}),t[11]=l,t[12]=d,t[13]=O,t[14]=a,t[15]=s,t[16]=k):k=t[16];let A;t[17]===d?A=t[18]:(A=d&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:d}),t[17]=d,t[18]=A);let j;t[19]!==r||t[20]!==p?(j=p&&(0,Z.jsx)(X,{variant:`ghost`,size:`sm`,onClick:r,children:`Cancel`}),t[19]=r,t[20]=p,t[21]=j):j=t[21];let M;return t[22]!==k||t[23]!==A||t[24]!==j?(M=(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[k,A,j]}),t[22]=k,t[23]=A,t[24]=j,t[25]=M):M=t[25],M}function nu(e){let t=(0,$.c)(32),{onSuccess:n,onCancel:r}=e,[i,a]=(0,Q.useState)(``),[o,s]=(0,Q.useState)(!1),[c,l]=(0,Q.useState)(null),u=(0,Q.useRef)(null),d,f;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(d=()=>()=>{u.current?.abort()},f=[],t[0]=d,t[1]=f):(d=t[0],f=t[1]),(0,Q.useEffect)(d,f);let p;t[2]!==n||t[3]!==i?(p=async function(){if(!i.trim()){l(`Paste a personal access token`);return}u.current?.abort();let e=new AbortController;u.current=e,s(!0),l(null);try{let t=await fetch(`/api/local-op/auth/pat`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({pat:i.trim()}),signal:e.signal});if(!t.ok){let e=`Invalid token — check that it has repo scope`;try{let n=await t.json(),r=ir.safeParse(n);r.success&&(e=r.data.title)}catch{}l(e),s(!1);return}if(!t.body){l(`Invalid token — check that it has repo scope`),s(!1);return}await Ac(t.body,e=>{let t;try{t=JSON.parse(e)}catch{return`continue`}return t.type===`complete`?(n({login:t.login,name:t.name,email:t.email}),s(!1),`terminal`):`continue`})||l(`No response — try again`)}catch(e){let t=e;t instanceof Error&&t.name!==`AbortError`&&l(`Connection error — try again`)}s(!1)},t[2]=n,t[3]=i,t[4]=p):p=t[4];let m=p,h;t[5]===Symbol.for(`react.memo_cache_sentinel`)?(h=(0,Z.jsx)(`a`,{href:`https://github.com/settings/tokens`,target:`_blank`,rel:`noopener noreferrer`,onClick:iu,onAuxClick:ru,className:`underline underline-offset-2`,children:`github.com/settings/tokens`}),t[5]=h):h=t[5];let g;t[6]===Symbol.for(`react.memo_cache_sentinel`)?(g=(0,Z.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Create a token at`,` `,h,` `,`with `,(0,Z.jsx)(`code`,{className:`text-xs bg-muted px-1 rounded`,children:`repo`}),` scope.`]}),t[6]=g):g=t[6];let _;t[7]===Symbol.for(`react.memo_cache_sentinel`)?(_=e=>a(e.target.value),t[7]=_):_=t[7];let v;t[8]===m?v=t[9]:(v=e=>{e.key===`Enter`&&m()},t[8]=m,t[9]=v);let y;t[10]!==o||t[11]!==i||t[12]!==v?(y=(0,Z.jsx)(fo,{type:`password`,"aria-label":`Personal access token`,placeholder:`ghp_…`,value:i,onChange:_,disabled:o,onKeyDown:v}),t[10]=o,t[11]=i,t[12]=v,t[13]=y):y=t[13];let b;t[14]===c?b=t[15]:(b=c&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:c}),t[14]=c,t[15]=b);let x;t[16]===m?x=t[17]:(x=()=>void m(),t[16]=m,t[17]=x);let S=o?`Validating`:`Add token`,C;t[18]!==o||t[19]!==x||t[20]!==S?(C=(0,Z.jsx)(X,{className:`flex-1`,onClick:x,disabled:o,children:S}),t[18]=o,t[19]=x,t[20]=S,t[21]=C):C=t[21];let w;t[22]!==o||t[23]!==r?(w=(0,Z.jsx)(X,{variant:`ghost`,onClick:r,disabled:o,children:`Cancel`}),t[22]=o,t[23]=r,t[24]=w):w=t[24];let T;t[25]!==C||t[26]!==w?(T=(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[C,w]}),t[25]=C,t[26]=w,t[27]=T):T=t[27];let E;return t[28]!==T||t[29]!==y||t[30]!==b?(E=(0,Z.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[g,y,b,T]}),t[28]=T,t[29]=y,t[30]=b,t[31]=E):E=t[31],E}function ru(e){return pi(e,`https://github.com/settings/tokens`)}function iu(e){return pi(e,`https://github.com/settings/tokens`)}function au(e){let t=(0,$.c)(27),{login:n,onSave:r,onSkip:i}=e,[a,o]=(0,Q.useState)(``),[s,c]=(0,Q.useState)(``),l;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(l=(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Before syncing, set your identity for git commits:`}),t[0]=l):l=t[0];let u=`Name (e.g. ${n})`,d;t[1]===Symbol.for(`react.memo_cache_sentinel`)?(d=e=>o(e.target.value),t[1]=d):d=t[1];let f;t[2]!==a||t[3]!==u?(f=(0,Z.jsx)(fo,{"aria-label":`Name`,placeholder:u,value:a,onChange:d}),t[2]=a,t[3]=u,t[4]=f):f=t[4];let p;t[5]===Symbol.for(`react.memo_cache_sentinel`)?(p=e=>c(e.target.value),t[5]=p):p=t[5];let m;t[6]===s?m=t[7]:(m=(0,Z.jsx)(fo,{type:`email`,"aria-label":`Email`,placeholder:`Email`,value:s,onChange:p}),t[6]=s,t[7]=m);let h;t[8]!==s||t[9]!==a||t[10]!==r?(h=()=>r(a.trim(),s.trim()),t[8]=s,t[9]=a,t[10]=r,t[11]=h):h=t[11];let g;t[12]!==s||t[13]!==a?(g=!a.trim()||!s.trim(),t[12]=s,t[13]=a,t[14]=g):g=t[14];let _;t[15]!==h||t[16]!==g?(_=(0,Z.jsx)(X,{className:`flex-1`,onClick:h,disabled:g,children:`Save`}),t[15]=h,t[16]=g,t[17]=_):_=t[17];let v;t[18]===i?v=t[19]:(v=(0,Z.jsx)(X,{variant:`ghost`,onClick:i,children:`Skip`}),t[18]=i,t[19]=v);let y;t[20]!==v||t[21]!==_?(y=(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[_,v]}),t[20]=v,t[21]=_,t[22]=y):y=t[22];let b;return t[23]!==y||t[24]!==f||t[25]!==m?(b=(0,Z.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[l,f,m,y]}),t[23]=y,t[24]=f,t[25]=m,t[26]=b):b=t[26],b}function ou(e){let t=(0,$.c)(42),{open:n,onOpenChange:r,onSuccess:i,identityPrompt:a,reauth:o,transport:s}=e,c;t[0]===s?c=t[1]:(c=s??Mc(),t[0]=s,t[1]=c);let l=c,[u,d]=(0,Q.useState)(`device`),[f,p]=(0,Q.useState)(`auth`),[m,h]=(0,Q.useState)(null),g,_;t[2]===n?(g=t[3],_=t[4]):(g=()=>{n&&(d(`device`),p(`auth`),h(null))},_=[n],t[2]=n,t[3]=g,t[4]=_),(0,Q.useEffect)(g,_);let v;t[5]!==a||t[6]!==r||t[7]!==i?(v=function(e){h(e),a&&(!e.name||!e.email)?p(`identity`):(p(`done`),i?.(e),r(!1),Xa.success(`Signed in as @${e.login}`))},t[5]=a,t[6]=r,t[7]=i,t[8]=v):v=t[8];let y=v,b;t[9]!==m||t[10]!==r||t[11]!==i?(b=function(e,t){fetch(`/api/local-op/auth/set-identity`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:e,email:t})}).catch(su);let n={...m??{login:``},name:e,email:t};p(`done`),i?.(n),r(!1),Xa.success(`Signed in as @${n.login}`)},t[9]=m,t[10]=r,t[11]=i,t[12]=b):b=t[12];let x=b,S;t[13]!==m||t[14]!==r||t[15]!==i?(S=function(){m&&(p(`done`),i?.(m),r(!1),Xa.success(`Signed in as @${m.login}`))},t[13]=m,t[14]=r,t[15]=i,t[16]=S):S=t[16];let C=S,w;t[17]===r?w=t[18]:(w=function(){r(!1)},t[17]=r,t[18]=w);let T=w,E=o?`Re-authenticate with GitHub`:`Sign in to GitHub`,D;t[19]===E?D=t[20]:(D=(0,Z.jsx)(qa,{children:(0,Z.jsx)(Ra,{children:E})}),t[19]=E,t[20]=D);let O;t[21]!==y||t[22]!==T||t[23]!==l||t[24]!==f||t[25]!==u?(O=f===`auth`&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`flex gap-1 border-b pb-2 mb-1`,children:[(0,Z.jsx)(X,{variant:u===`device`?`secondary`:`ghost`,size:`sm`,onClick:()=>d(`device`),children:`GitHub App`}),(0,Z.jsx)(X,{variant:u===`pat`?`secondary`:`ghost`,size:`sm`,onClick:()=>d(`pat`),children:`Token`})]}),u===`device`?(0,Z.jsx)(tu,{onSuccess:y,onCancel:T,transport:l}):(0,Z.jsx)(nu,{onSuccess:y,onCancel:T})]}),t[21]=y,t[22]=T,t[23]=l,t[24]=f,t[25]=u,t[26]=O):O=t[26];let k;t[27]!==m||t[28]!==x||t[29]!==C||t[30]!==f?(k=f===`identity`&&m&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`p`,{className:`text-sm font-medium`,children:[`Signed in as @`,m.login]}),(0,Z.jsx)(au,{login:m.login,onSave:x,onSkip:C})]}),t[27]=m,t[28]=x,t[29]=C,t[30]=f,t[31]=k):k=t[31];let A;t[32]!==k||t[33]!==O?(A=(0,Z.jsxs)(Wa,{children:[O,k]}),t[32]=k,t[33]=O,t[34]=A):A=t[34];let j;t[35]!==A||t[36]!==D?(j=(0,Z.jsxs)(Va,{className:`sm:max-w-md`,children:[D,A]}),t[35]=A,t[36]=D,t[37]=j):j=t[37];let M;return t[38]!==r||t[39]!==n||t[40]!==j?(M=(0,Z.jsx)(Ja,{open:n,onOpenChange:r,children:j}),t[38]=r,t[39]=n,t[40]=j,t[41]=M):M=t[41],M}function su(){}function cu(e){let t=(0,$.c)(2),{className:n}=e,{channel:r}=bc();if(r!==`beta`)return null;let i;return t[0]===n?i=t[1]:(i=(0,Z.jsx)(Ne,{variant:`secondary`,"aria-label":`Beta channel`,"data-testid":`beta-badge`,className:n,children:`BETA`}),t[0]=n,t[1]=i),i}function lu(e){switch(e){case`receiving`:return`Receiving objects`;case`resolving`:return`Resolving deltas`;case`checking`:return`Checking out files`;case`init`:return`Initializing project`;case`done`:return`Complete`;default:return`Cloning`}}function uu(e){let t=e.trim();if(/^[\w.-]+\/[\w.-]+$/.test(t))return t.split(`/`)[1];try{return new URL(t.replace(/^git@([^:]+):/,`https://$1/`)).pathname.replace(/\.git$/,``).split(`/`).pop()??`repo`}catch{return t.split(`/`).pop()?.replace(/\.git$/,``)??`repo`}}function du(e){let t=(0,$.c)(94),{open:n,onOpenChange:r,onSignIn:i,onCloneComplete:a,transport:o,authQueryTransport:s,pickParentFolder:c}=e,l;t[0]===o?l=t[1]:(l=o??Pc(),t[0]=o,t[1]=l);let u=l,d;t[2]===s?d=t[3]:(d=s??Oc(),t[2]=s,t[3]=d);let f=d,p=c!==void 0,[m,h]=(0,Q.useState)(``),[g,_]=(0,Q.useState)(``),[v,y]=(0,Q.useState)(null),[b,x]=(0,Q.useState)(!1),[S,C]=(0,Q.useState)(``),[w,T]=(0,Q.useState)(!1),[E,D]=(0,Q.useState)(!1),O=(0,Q.useRef)(null),k=(0,Q.useRef)(null),A;t[4]!==n||t[5]!==f?(A=()=>{if(!n)return;let e=!1;return f.status().then(t=>{e||T(t.authenticated)}).catch(()=>{e||T(!1)}),()=>{e=!0}},t[4]=n,t[5]=f,t[6]=A):A=t[6];let j;t[7]===n?j=t[8]:(j=[n],t[7]=n,t[8]=j),(0,Q.useEffect)(A,j);let M;t[9]!==w||t[10]!==n||t[11]!==f?(M=()=>{if(!w||!n)return;let e=!1;return x(!0),f.repos().then(t=>{e||(y(t.ok?t.repos:[]),x(!1))}).catch(()=>{e||(y([]),x(!1))}),()=>{e=!0}},t[9]=w,t[10]=n,t[11]=f,t[12]=M):M=t[12];let N;t[13]!==w||t[14]!==n?(N=[w,n],t[13]=w,t[14]=n,t[15]=N):N=t[15],(0,Q.useEffect)(M,N);let P;t[16]===p?P=t[17]:(P=function(e){if(h(e),p)return;let t=uu(e);t&&_(`~/Documents/${t}`)},t[16]=p,t[17]=P);let F=P,I;t[18]===p?I=t[19]:(I=function(e){if(h(e.clone_url),p)return;let t=e.full_name.split(`/`)[1];_(`~/Documents/${t}`)},t[18]=p,t[19]=I);let L=I,R;t[20]!==g||t[21]!==a||t[22]!==r||t[23]!==c||t[24]!==u||t[25]!==m?(R=async function(){let e=m.trim();if(!e){Xa.error(`Enter a repository URL or owner/repo`);return}let t=g||``;if(c){D(!0);let n=await c();if(!n){D(!1);return}let r=uu(e);t=`${n.replace(/\/$/,``)}/${r}`}else D(!0);let n=Xa.loading(`Starting clone`,{duration:1/0});k.current=n;let i=u.start({url:e,dir:t});O.current=i.cancel;try{let e=i.events[Symbol.asyncIterator](),t=await e.next();for(;!t.done;){let i=t.value;if(i.type===`progress`)Xa.loading(`${lu(i.phase)} — ${i.pct}%`,{id:n});else if(i.type===`complete`){Xa.success(`Clone complete — opening project`,{id:n}),r(!1),D(!1),O.current=null;let e=`port`in i?i.port:void 0;a?a({port:e,dir:i.dir}):e!==void 0&&(window.location.href=`http://localhost:${e}`);return}else if(i.type===`error`){Xa.error(`Clone failed: ${i.message}`,{id:n}),D(!1),O.current=null;return}t=await e.next()}Xa.error(`Clone stream ended unexpectedly — check if the clone completed`,{id:n}),D(!1),O.current=null}catch(e){console.error(`[CloneDialog] clone iteration failed:`,e),Xa.error(`Clone failed — connection error`,{id:n}),D(!1),O.current=null}},t[20]=g,t[21]=a,t[22]=r,t[23]=c,t[24]=u,t[25]=m,t[26]=R):R=t[26];let z=R,B;t[27]===Symbol.for(`react.memo_cache_sentinel`)?(B=function(){O.current?.(),O.current=null,D(!1),Xa.dismiss(k.current??void 0)},t[27]=B):B=t[27];let V=B,H;t[28]!==E||t[29]!==r||t[30]!==p?(H=function(e){E||(r(e),e||(h(``),p||_(``),C(``)))},t[28]=E,t[29]=r,t[30]=p,t[31]=H):H=t[31];let U=H,W,G,K,q,ee,te,ne,re,ie,ae;if(t[32]!==E||t[33]!==U||t[34]!==L||t[35]!==F||t[36]!==w||t[37]!==b||t[38]!==n||t[39]!==S||t[40]!==v||t[41]!==m){let e=v?.filter(e=>e.full_name.toLowerCase().includes(S.toLowerCase()));K=Ja,ie=n,ae=U,G=Va,ne=`sm:max-w-lg`,t[52]===Symbol.for(`react.memo_cache_sentinel`)?(re=(0,Z.jsx)(qa,{children:(0,Z.jsx)(Ra,{children:`Clone from GitHub`})}),t[52]=re):re=t[52],W=Wa,q=`flex flex-col gap-4`;let r;t[53]===Symbol.for(`react.memo_cache_sentinel`)?(r=(0,Z.jsx)(`label`,{htmlFor:`clone-url`,className:`text-sm font-medium`,children:`Repository URL or owner/repo`}),t[53]=r):r=t[53];let i;t[54]===F?i=t[55]:(i=e=>F(e.target.value),t[54]=F,t[55]=i),t[56]!==E||t[57]!==i||t[58]!==m?(ee=(0,Z.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[r,(0,Z.jsx)(fo,{id:`clone-url`,placeholder:`https://github.com/owner/repo or owner/repo`,value:m,onChange:i,disabled:E})]}),t[56]=E,t[57]=i,t[58]=m,t[59]=ee):ee=t[59],te=w&&(0,Z.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,Z.jsx)(`label`,{htmlFor:`repo-filter`,className:`text-sm font-medium`,children:`Your repositories`}),(0,Z.jsx)(fo,{id:`repo-filter`,"aria-label":`Filter repositories`,placeholder:`Filter repositories`,value:S,onChange:e=>C(e.target.value),disabled:E||b&&v===null}),(0,Z.jsx)(`div`,{className:`border rounded-md max-h-40 overflow-y-auto subtle-scrollbar`,"aria-busy":b&&v===null,children:b&&v===null?(0,Z.jsxs)(`output`,{className:`flex flex-col gap-1.5 px-3 py-2`,"aria-label":`Loading repositories`,children:[(0,Z.jsx)(Gi,{className:`h-4 w-2/3`}),(0,Z.jsx)(Gi,{className:`h-4 w-1/2`}),(0,Z.jsx)(Gi,{className:`h-4 w-3/4`}),(0,Z.jsx)(Gi,{className:`h-4 w-2/5`}),(0,Z.jsx)(Gi,{className:`h-4 w-3/5`})]}):e?.length===0?(0,Z.jsx)(`p`,{className:`px-3 py-2 text-xs text-muted-foreground`,children:v?.length===0?`No repositories found.`:`No matches.`}):e?.map(e=>(0,Z.jsxs)(`button`,{type:`button`,className:`w-full text-left px-3 py-1.5 text-sm hover:bg-muted flex items-center gap-2 truncate disabled:opacity-50`,onClick:()=>L(e),disabled:E,children:[e.private&&(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground shrink-0`,children:`🔒`}),e.full_name]},e.full_name))})]}),t[32]=E,t[33]=U,t[34]=L,t[35]=F,t[36]=w,t[37]=b,t[38]=n,t[39]=S,t[40]=v,t[41]=m,t[42]=W,t[43]=G,t[44]=K,t[45]=q,t[46]=ee,t[47]=te,t[48]=ne,t[49]=re,t[50]=ie,t[51]=ae}else W=t[42],G=t[43],K=t[44],q=t[45],ee=t[46],te=t[47],ne=t[48],re=t[49],ie=t[50],ae=t[51];let oe;t[60]!==E||t[61]!==w||t[62]!==i?(oe=!w&&(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,Z.jsx)(`span`,{children:`Browse your repos:`}),(0,Z.jsx)(X,{variant:`link`,size:`sm`,className:`h-auto p-0`,onClick:()=>i?.(),disabled:E,children:`Sign in to GitHub`})]}),t[60]=E,t[61]=w,t[62]=i,t[63]=oe):oe=t[63];let se;t[64]!==E||t[65]!==g||t[66]!==p?(se=!p&&(0,Z.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,Z.jsx)(`label`,{htmlFor:`clone-path`,className:`text-sm font-medium`,children:`Local path`}),(0,Z.jsx)(fo,{id:`clone-path`,placeholder:`~/Documents/repo-name`,value:g,onChange:e=>_(e.target.value),disabled:E})]}),t[64]=E,t[65]=g,t[66]=p,t[67]=se):se=t[67];let ce;t[68]!==q||t[69]!==ee||t[70]!==te||t[71]!==oe||t[72]!==se?(ce=(0,Z.jsxs)(`div`,{className:q,children:[ee,te,oe,se]}),t[68]=q,t[69]=ee,t[70]=te,t[71]=oe,t[72]=se,t[73]=ce):ce=t[73];let le;t[74]!==W||t[75]!==ce?(le=(0,Z.jsx)(W,{children:ce}),t[74]=W,t[75]=ce,t[76]=le):le=t[76];let ue;t[77]!==E||t[78]!==z||t[79]!==U||t[80]!==m||t[81]!==p?(ue=(0,Z.jsx)(Ga,{children:E?(0,Z.jsx)(X,{variant:`outline`,className:`font-mono uppercase`,onClick:V,children:`Cancel`}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(X,{variant:`outline`,className:`font-mono uppercase`,onClick:()=>U(!1),children:`Cancel`}),(0,Z.jsx)(X,{onClick:()=>void z(),disabled:!m.trim(),"aria-describedby":p?`clone-picker-hint`:void 0,children:`Clone`}),p&&(0,Z.jsx)(`span`,{id:`clone-picker-hint`,className:`sr-only`,children:`Opens a folder picker to choose where to clone the repository.`})]})}),t[77]=E,t[78]=z,t[79]=U,t[80]=m,t[81]=p,t[82]=ue):ue=t[82];let de;t[83]!==G||t[84]!==ne||t[85]!==re||t[86]!==le||t[87]!==ue?(de=(0,Z.jsxs)(G,{className:ne,children:[re,le,ue]}),t[83]=G,t[84]=ne,t[85]=re,t[86]=le,t[87]=ue,t[88]=de):de=t[88];let fe;return t[89]!==K||t[90]!==ie||t[91]!==ae||t[92]!==de?(fe=(0,Z.jsx)(K,{open:ie,onOpenChange:ae,children:de}),t[89]=K,t[90]=ie,t[91]=ae,t[92]=de,t[93]=fe):fe=t[93],fe}var fu=(0,Q.lazy)(()=>r(()=>import(`./ConsentDialogBody-BYenkRKt.js`),__vite__mapDeps([5,1,6,7,8,9,10,11]),import.meta.url));function pu(){let e=(0,$.c)(1);if(!(0,Q.useSyncExternalStore)(ho.subscribe,hu,mu))return null;let t;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=(0,Z.jsx)(Q.Suspense,{fallback:null,children:(0,Z.jsx)(fu,{})}),e[0]=t):t=e[0],t}function mu(){return!1}function hu(){return ho.getSnapshot()!==null}var gu=180;function _u(e,t){if(e===``||t===``)return``;let n=e.includes(`\\`)&&!e.includes(`/`)?`\\`:`/`;return`${e.replace(/[/\\]+$/,``)}${n}${t}`}function vu(e){if(e===``)return``;let t=e.split(/[/\\]/).filter(Boolean);return t.length>0?t[t.length-1]??e:e}function yu(e){let{parent:t,sanitizedName:n,enclosingProject:r,enclosingGit:i,targetState:a}=e;return t===``||n===``?{kind:`idle`}:r===null?i===null?a===`exists-nonempty`?{kind:`block-nonempty`}:{kind:`free`}:{kind:`confirm-git`,gitRoot:i.gitRoot}:{kind:`block-nested`,rootPath:r.rootPath}}function bu(e){let t=e instanceof Error?e.message:String(e);for(let e of Cr)if(t.startsWith(`${e}:`)||t.includes(`${e}: `))return e===`nested-project`||e===`target-not-empty`?{reason:e}:{reason:e,message:t};return{reason:`unknown`,message:t}}function xu(e){switch(e.reason){case`nested-project`:return`A project already exists at this location. Pick a different parent folder.`;case`target-not-empty`:return`A non-empty folder with this name already exists. Use a different name.`;case`invalid-args`:return`Invalid input — please check the name and try again.`;case`mkdir-failed`:return`Could not create the project folder. Try a different name or location.`;case`git-init-failed`:return`Project folder created, but git init failed. Try again.`;case`init-failed`:return`Could not write project files. Try a different location.`;case`discovery-failed`:return`Could not finalize project setup. Try again.`;case`unknown`:return`Could not create project. Try again or pick a different location.`}}function Su(e){let t=(0,$.c)(94),{open:n,onOpenChange:r,bridge:i}=e,[a,o]=(0,Q.useState)(``),[s,c]=(0,Q.useState)(``),[l,u]=(0,Q.useState)(!1),[d,f]=(0,Q.useState)(Tu),p;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(p={kind:`idle`},t[0]=p):p=t[0];let[m,h]=(0,Q.useState)(p),[g,_]=(0,Q.useState)(!1),[v,y]=(0,Q.useState)(null),b;t[1]===Symbol.for(`react.memo_cache_sentinel`)?(b=new Map,t[1]=b):b=t[1];let x=(0,Q.useRef)(b),S;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(S=new Set,t[2]=S):S=t[2];let C=(0,Q.useRef)(S),w=(0,Q.useRef)(null),T=(0,Q.useRef)(null),E=(0,Q.useRef)(null),D,O;t[3]!==i||t[4]!==n?(D=()=>{if(!n)return;x.current.clear(),C.current.clear(),y(null),h({kind:`idle`}),_(!1),o(``),f(new Set(cn));let e=!1;u(!0),i.fs.defaultProjectsRoot().then(t=>{e||c(t)}).catch(wu).finally(()=>{e||u(!1)});let t=requestAnimationFrame(()=>{E.current?.focus()});return()=>{e=!0,cancelAnimationFrame(t)}},O=[n,i],t[3]=i,t[4]=n,t[5]=D,t[6]=O):(D=t[5],O=t[6]),(0,Q.useEffect)(D,O);let k,A;t[7]!==i||t[8]!==a||t[9]!==n||t[10]!==s?(k=()=>{if(!n)return;T.current!==null&&clearTimeout(T.current),w.current!==null&&w.current.abort();let e=jn(a);if(s===``||e===``){h({kind:`idle`});return}let t=_u(s,e),r=x.current.get(t);if(r!==void 0){h(yu({parent:s,sanitizedName:e,enclosingProject:r.enclosingProject,enclosingGit:r.enclosingGit,targetState:r.targetState}));return}h({kind:`pending`});let o=new AbortController;return w.current=o,T.current=setTimeout(()=>{Promise.all([i.fs.findEnclosingProjectRoot(s),i.fs.findEnclosingGitRoot(s),i.fs.folderState(t)]).then(n=>{let[r,i,a]=n;o.signal.aborted||(x.current.set(t,{enclosingProject:r,enclosingGit:i,targetState:a}),h(yu({parent:s,sanitizedName:e,enclosingProject:r,enclosingGit:i,targetState:a})))}).catch(e=>{o.signal.aborted||(console.warn(`[CreateProjectDialog] cascade probe failed:`,e),h({kind:`free`}))})},gu),()=>{T.current!==null&&clearTimeout(T.current),o.abort()}},A=[n,a,s,i],t[7]=i,t[8]=a,t[9]=n,t[10]=s,t[11]=k,t[12]=A):(k=t[11],A=t[12]),(0,Q.useEffect)(k,A);let j,M;t[13]!==i||t[14]!==m||t[15]!==n?(j=()=>{if(!n)return;let e=null;m.kind===`block-nested`?e=`nested`:m.kind===`block-nonempty`?e=`nonempty`:m.kind===`confirm-git`&&(e=`git-confirm`),e!==null&&(C.current.has(e)||(C.current.add(e),i.project.recordCreateNewBannerShown(e).catch(Cu)))},M=[n,m,i],t[13]=i,t[14]=m,t[15]=n,t[16]=j,t[17]=M):(j=t[16],M=t[17]),(0,Q.useEffect)(j,M);let N,P;t[18]!==a||t[19]!==s?(N=jn(a),P=N===``||s===``?``:_u(s,N),t[18]=a,t[19]=s,t[20]=N,t[21]=P):(N=t[20],P=t[21]);let F=P,I=F===``?s:F,L=!g&&N!==``&&s!==``&&(m.kind===`free`||m.kind===`confirm-git`),R;t[22]===Symbol.for(`react.memo_cache_sentinel`)?(R=function(e){f(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},t[22]=R):R=t[22];let z=R,B;t[23]===i?B=t[24]:(B=async function(){try{let e=await i.dialog.openFolder();if(e===null)return;c(e)}catch(e){console.warn(`[CreateProjectDialog] dialog.openFolder failed:`,e)}},t[23]=i,t[24]=B);let V=B,H;t[25]!==i||t[26]!==L||t[27]!==d||t[28]!==r||t[29]!==s||t[30]!==N?(H=async function(e){if(e.preventDefault(),L){_(!0),y(null);try{await i.project.createNew({parent:s,name:N,editors:Array.from(d)}),r(!1)}catch(e){y(bu(e)),_(!1)}}},t[25]=i,t[26]=L,t[27]=d,t[28]=r,t[29]=s,t[30]=N,t[31]=H):H=t[31];let U=H,W;t[32]!==g||t[33]!==r?(W=function(e){g||r(e)},t[32]=g,t[33]=r,t[34]=W):W=t[34];let G=W,K;t[35]!==i||t[36]!==r?(K=async function(e){r(!1);try{await i.project.open({path:e,target:`new-window`,entryPoint:`create-new-nested-redirect`})}catch(e){console.warn(`[CreateProjectDialog] project.open failed:`,e)}},t[35]=i,t[36]=r,t[37]=K):K=t[37];let q=K,ee;t[38]===Symbol.for(`react.memo_cache_sentinel`)?(ee=(0,Z.jsxs)(qa,{children:[(0,Z.jsx)(Ra,{children:`Create new project`}),(0,Z.jsx)(Ia,{children:`Make a new folder for a brand-new Open Knowledge project.`})]}),t[38]=ee):ee=t[38];let te;t[39]===Symbol.for(`react.memo_cache_sentinel`)?(te=(0,Z.jsx)(oo,{htmlFor:`create-name`,className:`block`,children:`Name`}),t[39]=te):te=t[39];let ne;t[40]===Symbol.for(`react.memo_cache_sentinel`)?(ne=e=>{o(e.target.value),y(null)},t[40]=ne):ne=t[40];let re;t[41]!==g||t[42]!==a?(re=(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[te,(0,Z.jsx)(fo,{id:`create-name`,ref:E,value:a,onChange:ne,disabled:g,placeholder:`My Notes`,autoComplete:`off`,spellCheck:!1,"aria-describedby":`create-target-caption`,"data-testid":`create-name`})]}),t[41]=g,t[42]=a,t[43]=re):re=t[43];let ie;t[44]===Symbol.for(`react.memo_cache_sentinel`)?(ie=(0,Z.jsx)(oo,{htmlFor:`create-location`,className:`block`,children:`Location`}),t[44]=ie):ie=t[44];let ae=g||l,oe;t[45]===V?oe=t[46]:(oe=()=>void V(),t[45]=V,t[46]=oe);let se;t[47]!==ae||t[48]!==oe?(se=(0,Z.jsx)(`div`,{className:`flex items-stretch gap-2`,children:(0,Z.jsx)(X,{id:`create-location`,type:`button`,variant:`outline`,disabled:ae,onClick:oe,"data-testid":`create-browse`,children:`Browse`})}),t[47]=ae,t[48]=oe,t[49]=se):se=t[49];let ce;t[50]===I?ce=t[51]:(ce=I===``?(0,Z.jsx)(`span`,{className:`sr-only`,children:`No target path yet`}):I,t[50]=I,t[51]=ce);let le;t[52]===ce?le=t[53]:(le=(0,Z.jsx)(`p`,{id:`create-target-caption`,className:`text-xs text-muted-foreground`,"aria-live":`polite`,"data-testid":`create-target-caption`,children:ce}),t[52]=ce,t[53]=le);let ue;t[54]!==se||t[55]!==le?(ue=(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[ie,se,le]}),t[54]=se,t[55]=le,t[56]=ue):ue=t[56];let de;t[57]!==m||t[58]!==q?(de=(0,Z.jsx)(Eu,{cascade:m,onOpenNested:q}),t[57]=m,t[58]=q,t[59]=de):de=t[59];let fe,pe;t[60]===Symbol.for(`react.memo_cache_sentinel`)?(fe=(0,Z.jsx)(`legend`,{className:`text-sm font-medium`,children:`Connect AI editors`}),pe=(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`All editors are checked by default — uncheck the ones you don't use.`}),t[60]=fe,t[61]=pe):(fe=t[60],pe=t[61]);let me;t[62]!==g||t[63]!==d?(me=cn.map(e=>{let t=`create-editor-${e}`;return(0,Z.jsxs)(oo,{htmlFor:t,className:`text-sm font-normal`,children:[(0,Z.jsx)($a,{id:t,checked:d.has(e),onCheckedChange:()=>z(e),disabled:g,"data-testid":`create-editor-${e}`}),(0,Z.jsx)(`span`,{children:qn[e]})]},e)}),t[62]=g,t[63]=d,t[64]=me):me=t[64];let he;t[65]===me?he=t[66]:(he=(0,Z.jsxs)(`fieldset`,{className:`space-y-2 pb-2`,children:[fe,pe,me]}),t[65]=me,t[66]=he);let ge;t[67]===v?ge=t[68]:(ge=v===null?null:(0,Z.jsx)(`div`,{role:`alert`,className:`rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive`,"data-testid":`create-submit-error`,children:xu(v)}),t[67]=v,t[68]=ge);let _e;t[69]!==re||t[70]!==ue||t[71]!==de||t[72]!==he||t[73]!==ge?(_e=(0,Z.jsxs)(Wa,{className:`space-y-4`,children:[re,ue,de,he,ge]}),t[69]=re,t[70]=ue,t[71]=de,t[72]=he,t[73]=ge,t[74]=_e):_e=t[74];let ve;t[75]===r?ve=t[76]:(ve=()=>r(!1),t[75]=r,t[76]=ve);let ye;t[77]!==g||t[78]!==ve?(ye=(0,Z.jsx)(X,{type:`button`,variant:`outline`,className:`font-mono uppercase`,onClick:ve,disabled:g,"data-testid":`create-cancel`,children:`Cancel`}),t[77]=g,t[78]=ve,t[79]=ye):ye=t[79];let be=!L,xe=g?`Creating`:`Create`,Se;t[80]!==be||t[81]!==xe?(Se=(0,Z.jsx)(X,{type:`submit`,disabled:be,"data-testid":`create-submit`,children:xe}),t[80]=be,t[81]=xe,t[82]=Se):Se=t[82];let Ce;t[83]!==ye||t[84]!==Se?(Ce=(0,Z.jsxs)(Ga,{children:[ye,Se]}),t[83]=ye,t[84]=Se,t[85]=Ce):Ce=t[85];let we;t[86]!==U||t[87]!==_e||t[88]!==Ce?(we=(0,Z.jsxs)(Va,{className:`sm:max-w-lg motion-reduce:duration-0 motion-reduce:data-open:animate-none motion-reduce:data-closed:animate-none`,"data-testid":`create-project-dialog`,children:[ee,(0,Z.jsxs)(`form`,{onSubmit:U,"data-testid":`create-project-form`,className:`flex min-h-0 flex-1 flex-col`,children:[_e,Ce]})]}),t[86]=U,t[87]=_e,t[88]=Ce,t[89]=we):we=t[89];let J;return t[90]!==G||t[91]!==n||t[92]!==we?(J=(0,Z.jsx)(Ja,{open:n,onOpenChange:G,children:we}),t[90]=G,t[91]=n,t[92]=we,t[93]=J):J=t[93],J}function Cu(){}function wu(e){console.warn(`[CreateProjectDialog] defaultProjectsRoot probe failed:`,e)}function Tu(){return new Set(cn)}function Eu(e){let t=(0,$.c)(19),{cascade:n,onOpenNested:r}=e;if(n.kind===`idle`||n.kind===`pending`||n.kind===`free`)return null;if(n.kind===`block-nested`){let e;t[0]===n.rootPath?e=t[1]:(e=vu(n.rootPath),t[0]=n.rootPath,t[1]=e);let i=e,a;t[2]===n.rootPath?a=t[3]:(a=(0,Z.jsxs)(`p`,{className:`mb-2`,children:[`Can't nest projects. An Open Knowledge project already exists at`,` `,(0,Z.jsx)(`code`,{className:`font-mono break-all`,children:n.rootPath}),`. Choose a location outside it, or open that project instead.`]}),t[2]=n.rootPath,t[3]=a);let o;t[4]!==n.rootPath||t[5]!==r?(o=()=>r(n.rootPath),t[4]=n.rootPath,t[5]=r,t[6]=o):o=t[6];let s;t[7]!==i||t[8]!==o?(s=(0,Z.jsxs)(X,{type:`button`,variant:`outline`,size:`sm`,onClick:o,"data-testid":`create-banner-nested-open`,children:[`Open `,i]}),t[7]=i,t[8]=o,t[9]=s):s=t[9];let c;return t[10]!==a||t[11]!==s?(c=(0,Z.jsxs)(`div`,{role:`alert`,className:`rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive`,"data-testid":`create-banner-nested`,children:[a,s]}),t[10]=a,t[11]=s,t[12]=c):c=t[12],c}if(n.kind===`confirm-git`){let e;t[13]===n.gitRoot?e=t[14]:(e=(0,Z.jsx)(`code`,{children:n.gitRoot}),t[13]=n.gitRoot,t[14]=e);let r;t[15]===Symbol.for(`react.memo_cache_sentinel`)?(r=(0,Z.jsx)(`code`,{children:`.git`}),t[15]=r):r=t[15];let i;return t[16]===e?i=t[17]:(i=(0,Z.jsx)(`div`,{role:`status`,"aria-live":`polite`,className:`rounded-md border border-blue-300 bg-blue-50 px-3 py-2 text-sm text-blue-900 dark:border-blue-700 dark:bg-blue-950 dark:text-blue-200`,"data-testid":`create-banner-git-confirm`,children:(0,Z.jsxs)(`p`,{children:[`Open Knowledge will be initialized at `,e,` — the parent of your new folder, because it contains a `,r,` folder (one project per git repo).`]})}),t[16]=e,t[17]=i),i}let i;return t[18]===Symbol.for(`react.memo_cache_sentinel`)?(i=(0,Z.jsx)(`div`,{role:`alert`,className:`rounded-md border border-amber-300 bg-amber-50 px-3 py-2 text-sm text-amber-900 dark:border-amber-700 dark:bg-amber-950 dark:text-amber-200`,"data-testid":`create-banner-nonempty`,children:(0,Z.jsx)(`p`,{children:`A non-empty folder with this name already exists. Use "Open folder on disk" instead.`})}),t[18]=i):i=t[18],i}function Du(e){let t=(0,$.c)(4),n,r;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(n=(0,Z.jsx)(`title`,{children:`GitHub`}),r=(0,Z.jsx)(`path`,{d:`M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12`}),t[0]=n,t[1]=r):(n=t[0],r=t[1]);let i;return t[2]===e?i=t[3]:(i=(0,Z.jsxs)(`svg`,{role:`img`,fill:`currentColor`,height:24,width:24,viewBox:`0 0 24 24`,xmlns:`http://www.w3.org/2000/svg`,...e,children:[n,r]}),t[2]=e,t[3]=i),i}function Ou(e){let t=(0,$.c)(5),n;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(n=(0,Z.jsx)(`title`,{children:`Open Knowledge icon`}),t[0]=n):n=t[0];let r;t[1]===Symbol.for(`react.memo_cache_sentinel`)?(r=(0,Z.jsxs)(`g`,{filter:`url(#filter0_d_ok)`,children:[(0,Z.jsx)(`path`,{d:`M66.8902 16.1017C58.2694 3.86669 46.1739 -0.690239 29.9182 2.17749C21.3995 3.67813 13.4602 9.555 8.67934 17.9009C3.93974 26.1701 2.98514 35.6533 6.05714 43.9166C9.31574 52.6868 16.7168 58.4752 24.2299 63.4231C25.7973 64.4562 26.1351 65.7172 26.3551 68.9896C26.5221 71.4625 26.799 75.6011 30.6842 77.7204C31.8176 78.3372 33.0648 78.6515 34.3946 78.6515C37.0796 78.6515 39.4033 77.3649 40.5189 76.7482C47.1049 73.1046 68.8878 59.7147 72.6453 40.4027C74.3444 31.6679 70.9797 21.9019 66.8922 16.1017H66.8902Z`,fill:`white`}),(0,Z.jsx)(`path`,{d:`M37.4214 71.154C28.7888 75.929 36.787 64.0397 27.7458 58.0843C21.6372 54.0616 14.788 49.0568 12.0499 41.6911C6.74463 27.4192 17.5438 10.8473 31.028 8.47262C45.1977 5.97613 54.6946 9.8947 61.6635 19.7844C65.2089 24.8167 67.6013 32.8365 66.3658 39.1828C63.6906 52.9341 49.073 64.7075 37.4214 71.154Z`,fill:`#69A3FF`}),(0,Z.jsx)(`path`,{d:`M52.7244 29.2638C53.4665 28.5217 54.6697 28.5217 55.4119 29.2638V29.2638C56.154 30.0059 56.154 31.2091 55.4119 31.9513L49.2589 38.1042L46.5715 35.4167L52.7244 29.2638Z`,fill:`#D5E5FF`}),(0,Z.jsx)(`path`,{d:`M55.4119 38.8821C56.154 39.6242 56.154 40.8274 55.4119 41.5696V41.5696C54.6698 42.3117 53.4665 42.3117 52.7244 41.5696L46.5715 35.4166L49.259 32.7292L55.4119 38.8821Z`,fill:`#D5E5FF`})]}),t[1]=r):r=t[1];let i;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(i=(0,Z.jsx)(`defs`,{children:(0,Z.jsxs)(`filter`,{id:`filter0_d_ok`,x:`-9.53674e-07`,y:`-0.0799994`,width:`77.3817`,height:`85.8743`,filterUnits:`userSpaceOnUse`,colorInterpolationFilters:`sRGB`,children:[(0,Z.jsx)(`feFlood`,{floodOpacity:`0`,result:`BackgroundImageFix`}),(0,Z.jsx)(`feColorMatrix`,{in:`SourceAlpha`,type:`matrix`,values:`0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0`,result:`hardAlpha`}),(0,Z.jsx)(`feOffset`,{dy:`2.85714`}),(0,Z.jsx)(`feGaussianBlur`,{stdDeviation:`2.14286`}),(0,Z.jsx)(`feComposite`,{in2:`hardAlpha`,operator:`out`}),(0,Z.jsx)(`feColorMatrix`,{type:`matrix`,values:`0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0`}),(0,Z.jsx)(`feBlend`,{mode:`normal`,in2:`BackgroundImageFix`,result:`effect1_dropShadow_ok`}),(0,Z.jsx)(`feBlend`,{mode:`normal`,in:`SourceGraphic`,in2:`effect1_dropShadow_ok`,result:`shape`})]})}),t[2]=i):i=t[2];let a;return t[3]===e?a=t[4]:(a=(0,Z.jsxs)(`svg`,{role:`img`,"aria-label":`Open Knowledge icon`,fill:`none`,height:24,width:24,viewBox:`0 0 78 80`,xmlns:`http://www.w3.org/2000/svg`,...e,children:[n,r,i]}),t[3]=e,t[4]=a),a}var ku=(0,Q.lazy)(()=>r(()=>import(`./McpConsentDialogBody-CEvkljQ2.js`),__vite__mapDeps([12,1,6,7,13,14,15,8,16]),import.meta.url));function Au(){let e=(0,$.c)(1);if(!(0,Q.useSyncExternalStore)(Qa.subscribe,Mu,ju))return null;let t;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=(0,Z.jsx)(Q.Suspense,{fallback:null,children:(0,Z.jsx)(ku,{})}),e[0]=t):t=e[0],t}function ju(){return!1}function Mu(){return Qa.getSnapshot()!==null}var Nu=(e,t,n)=>Cc(e,t,n,`NavigatorApp`);function Pu(e){let t=(0,$.c)(74),{bridge:n}=e,r;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(r=[],t[0]=r):r=t[0];let[i,a]=(0,Q.useState)(r),[o,s]=(0,Q.useState)(!0),[c,l]=(0,Q.useState)(null),[u,d]=(0,Q.useState)(!1),[f,p]=(0,Q.useState)(!1),[m,h]=(0,Q.useState)(!1),[g,_]=(0,Q.useState)(!1),v=typeof window<`u`&&window.okDesktop!=null,[y,b]=(0,Q.useState)(`auth`),{channel:x}=bc(),{theme:S}=yr();Ta(n,S??`system`);let C;t[1]===n.project?C=t[2]:(C=()=>{let e=!1;return n.project.listRecent().then(t=>{e||a(t)}).catch(t=>{console.error(`[NavigatorApp] listRecent failed:`,t),e||l(t instanceof Error?t.message:`Failed to load recent projects.`)}).finally(()=>{e||s(!1)}),()=>{e=!0}},t[1]=n.project,t[2]=C);let w;t[3]===n?w=t[4]:(w=[n],t[3]=n,t[4]=w),(0,Q.useEffect)(C,w);let T;t[5]===Symbol.for(`react.memo_cache_sentinel`)?(T=(e,t)=>Nu(e,t,l),t[5]=T):T=t[5];let E=T,D;t[6]===Symbol.for(`react.memo_cache_sentinel`)?(D=()=>d(!0),t[6]=D):D=t[6];let O=D,k;t[7]===n?k=t[8]:(k=()=>E(async()=>{let e=await n.dialog.openFolder();e&&await Lu(n,e,`pick-existing`)},`Failed to open folder.`),t[7]=n,t[8]=k);let A=k,j;t[9]===Symbol.for(`react.memo_cache_sentinel`)?(j=()=>p(!0),t[9]=j):j=t[9];let M=j,N;t[10]===n?N=t[11]:(N=e=>E(async()=>{await Lu(n,e,`recents`)},`Failed to open project.`),t[10]=n,t[11]=N);let P=N,F;t[12]===Symbol.for(`react.memo_cache_sentinel`)?(F=(0,Z.jsx)(Ou,{className:`size-12 shrink-0`}),t[12]=F):F=t[12];let I;t[13]===Symbol.for(`react.memo_cache_sentinel`)?(I=(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`h1`,{className:`font-medium text-xl tracking-tight`,children:`Open Knowledge`}),(0,Z.jsx)(cu,{})]}),t[13]=I):I=t[13];let L;t[14]===n.appVersion?L=t[15]:(L=(0,Z.jsxs)(`p`,{className:`text-muted-foreground text-xs font-mono`,children:[`v`,n.appVersion]}),t[14]=n.appVersion,t[15]=L);let R;t[16]===x?R=t[17]:(R=x!==null&&(0,Z.jsx)(Ne,{variant:`gray`,className:`text-2xs font-mono`,children:x===`beta`?`Beta`:`Stable`}),t[16]=x,t[17]=R);let z;t[18]!==L||t[19]!==R?(z=(0,Z.jsx)(`div`,{className:`shrink-0 ${v?`[-webkit-app-region:drag]`:``}`,"data-testid":`nav-chrome-row`,children:(0,Z.jsx)(`div`,{className:`mx-auto w-full max-w-5xl px-12 pt-12 pb-10`,children:(0,Z.jsxs)(`header`,{className:`shrink-0 flex-wrap flex items-center gap-2.5`,children:[F,(0,Z.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[I,(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[L,R]})]})]})})}),t[18]=L,t[19]=R,t[20]=z):z=t[20];let B=`mx-auto flex w-full max-w-5xl flex-1 flex-col overflow-hidden px-12 pb-12 space-y-10 ${!o&&i.length===0?`justify-center`:``}`,V;t[21]===Symbol.for(`react.memo_cache_sentinel`)?(V=(0,Z.jsx)(Fu,{title:`Clone from GitHub`,description:`Bring a remote repository onto this machine.`,onClick:O,dataTestId:`nav-clone`,Icon:Du}),t[21]=V):V=t[21];let H;t[22]===A?H=t[23]:(H=(0,Z.jsx)(Fu,{title:`Open folder on disk`,description:`Use a folder you already have.`,onClick:A,dataTestId:`nav-open`,Icon:G}),t[22]=A,t[23]=H);let U;t[24]===Symbol.for(`react.memo_cache_sentinel`)?(U=(0,Z.jsx)(Fu,{title:`Create new project`,description:`Make a new folder for a brand-new project.`,onClick:M,dataTestId:`nav-create-new`,Icon:Fi}),t[24]=U):U=t[24];let W;t[25]===H?W=t[26]:(W=(0,Z.jsxs)(`section`,{className:`grid shrink-0 sm:grid-cols-3 gap-3`,children:[V,H,U]}),t[25]=H,t[26]=W);let K;t[27]===c?K=t[28]:(K=c===null?null:(0,Z.jsxs)(`div`,{className:`mb-3 flex shrink-0 items-start justify-between gap-3 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2`,"data-testid":`nav-error-banner`,role:`alert`,children:[(0,Z.jsx)(`span`,{className:`text-red-700 text-xs dark:text-red-300`,children:c}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>l(null),className:`text-red-700 text-xs underline hover:no-underline dark:text-red-300`,"data-testid":`nav-error-dismiss`,children:`Dismiss`})]}),t[27]=c,t[28]=K);let q;t[29]!==o||t[30]!==P||t[31]!==i?(q=o?(0,Z.jsx)(`section`,{className:`flex min-h-0 flex-1 flex-col`,children:(0,Z.jsx)(`div`,{className:`flex items-center justify-center h-full`,children:(0,Z.jsx)(Ze,{className:`size-4 animate-spin text-muted-foreground/60`})})}):i.length>0?(0,Z.jsxs)(`section`,{className:`flex min-h-0 flex-1 flex-col`,children:[(0,Z.jsx)(`h2`,{className:`mb-2 shrink-0 font-medium text-muted-foreground font-mono text-xs uppercase tracking-wide`,children:`Recent`}),(0,Z.jsx)(`ul`,{className:`min-h-0 flex-1 subtle-scrollbar overflow-y-auto space-y-0.5 -mx-4`,"data-testid":`nav-recent-list`,children:i.map(e=>(0,Z.jsx)(Iu,{project:e,onOpen:()=>P(e.path)},e.path))})]}):null,t[29]=o,t[30]=P,t[31]=i,t[32]=q):q=t[32];let ee;t[33]!==B||t[34]!==W||t[35]!==K||t[36]!==q?(ee=(0,Z.jsxs)(`div`,{className:B,children:[W,K,q]}),t[33]=B,t[34]=W,t[35]=K,t[36]=q,t[37]=ee):ee=t[37];let te,ne;t[38]===Symbol.for(`react.memo_cache_sentinel`)?(te=(0,Z.jsx)(Au,{}),ne=(0,Z.jsx)(pu,{}),t[38]=te,t[39]=ne):(te=t[38],ne=t[39]);let re;t[40]!==n||t[41]!==f?(re=(0,Z.jsx)(Su,{open:f,onOpenChange:p,bridge:n}),t[40]=n,t[41]=f,t[42]=re):re=t[42];let ie;t[43]===Symbol.for(`react.memo_cache_sentinel`)?(ie=e=>{h(e),e||_(!1)},t[43]=ie):ie=t[43];let ae;t[44]===n?ae=t[45]:(ae=Nc(n),t[44]=n,t[45]=ae);let oe=y===`identity`,se;t[46]===g?se=t[47]:(se=()=>{h(!1),g&&(_(!1),d(!0))},t[46]=g,t[47]=se);let ce;t[48]!==m||t[49]!==ae||t[50]!==oe||t[51]!==se?(ce=(0,Z.jsx)(ou,{open:m,onOpenChange:ie,transport:ae,identityPrompt:oe,onSuccess:se}),t[48]=m,t[49]=ae,t[50]=oe,t[51]=se,t[52]=ce):ce=t[52];let le;t[53]===n?le=t[54]:(le=Fc(n),t[53]=n,t[54]=le);let ue;t[55]===n?ue=t[56]:(ue=kc(n),t[55]=n,t[56]=ue);let de;t[57]===n.dialog?de=t[58]:(de=()=>n.dialog.openFolder(),t[57]=n.dialog,t[58]=de);let fe;t[59]===Symbol.for(`react.memo_cache_sentinel`)?(fe=()=>{d(!1),b(`auth`),_(!0),h(!0)},t[59]=fe):fe=t[59];let pe;t[60]===n?pe=t[61]:(pe=e=>{let{dir:t}=e;E(()=>Lu(n,t,`pick-existing`),`Failed to open cloned project.`)},t[60]=n,t[61]=pe);let me;t[62]!==u||t[63]!==le||t[64]!==ue||t[65]!==de||t[66]!==pe?(me=(0,Z.jsx)(du,{open:u,onOpenChange:d,transport:le,authQueryTransport:ue,pickParentFolder:de,onSignIn:fe,onCloneComplete:pe}),t[62]=u,t[63]=le,t[64]=ue,t[65]=de,t[66]=pe,t[67]=me):me=t[67];let he;return t[68]!==z||t[69]!==ee||t[70]!==re||t[71]!==ce||t[72]!==me?(he=(0,Z.jsxs)(`div`,{className:`flex h-screen w-screen flex-col overflow-hidden bg-primary-foreground dark:bg-background text-foreground`,children:[z,ee,te,ne,re,ce,me]}),t[68]=z,t[69]=ee,t[70]=re,t[71]=ce,t[72]=me,t[73]=he):he=t[73],he}function Fu(e){let t=(0,$.c)(14),{title:n,description:r,onClick:i,dataTestId:a,Icon:o}=e,s;t[0]===o?s=t[1]:(s=o?(0,Z.jsx)(o,{className:`size-4 shrink-0 text-muted-foreground`}):null,t[0]=o,t[1]=s);let c;t[2]===n?c=t[3]:(c=(0,Z.jsx)(`span`,{className:`font-medium text-gray-700 dark:text-foreground text-sm`,children:n}),t[2]=n,t[3]=c);let l;t[4]!==s||t[5]!==c?(l=(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[s,c]}),t[4]=s,t[5]=c,t[6]=l):l=t[6];let u;t[7]===r?u=t[8]:(u=(0,Z.jsx)(`span`,{className:`text-muted-foreground text-xs leading-snug`,children:r}),t[7]=r,t[8]=u);let d;return t[9]!==a||t[10]!==i||t[11]!==l||t[12]!==u?(d=(0,Z.jsxs)(`button`,{type:`button`,onClick:i,"data-testid":a,className:`flex flex-col items-start gap-1.5 rounded-lg border border-border bg-card py-3.5 px-4 text-left transition-colors hover:bg-accent`,children:[l,u]}),t[9]=a,t[10]=i,t[11]=l,t[12]=u,t[13]=d):d=t[13],d}function Iu(e){let t=(0,$.c)(17),{project:n,onOpen:r}=e,i=`flex items-center justify-between ${n.missing?`opacity-50`:``}`,a;t[0]===n.name?a=t[1]:(a=(0,Z.jsx)(`span`,{className:`font-medium text-sm text-gray-700 dark:text-foreground`,children:n.name}),t[0]=n.name,t[1]=a);let o;t[2]===n.path?o=t[3]:(o=(0,Z.jsx)(`span`,{className:`truncate w-full text-muted-foreground text-xs`,children:n.path}),t[2]=n.path,t[3]=o);let s;t[4]!==a||t[5]!==o?(s=(0,Z.jsxs)(`div`,{className:`flex flex-col gap-1 truncate`,children:[a,o]}),t[4]=a,t[5]=o,t[6]=s):s=t[6];let c;t[7]===n.missing?c=t[8]:(c=n.missing?(0,Z.jsx)(Ne,{className:`text-2xs rounded-sm`,variant:`warning`,children:`Missing`}):null,t[7]=n.missing,t[8]=c);let l;t[9]!==r||t[10]!==n.missing||t[11]!==s||t[12]!==c?(l=(0,Z.jsxs)(`button`,{type:`button`,onClick:r,disabled:n.missing,className:`flex min-w-0 flex-1 items-center text-left disabled:cursor-not-allowed py-3.5 px-4 hover:bg-accent rounded-lg gap-2 justify-between`,children:[s,c]}),t[9]=r,t[10]=n.missing,t[11]=s,t[12]=c,t[13]=l):l=t[13];let u;return t[14]!==i||t[15]!==l?(u=(0,Z.jsx)(`li`,{className:i,children:l}),t[14]=i,t[15]=l,t[16]=u):u=t[16],u}async function Lu(e,t,n){await e.project.open({path:t,target:`new-window`,entryPoint:n})}var Ru=e=>{let t=(0,$.c)(8),n;t[0]===e?n=t[1]:({...n}=e,t[0]=e,t[1]=n);let{theme:r}=yr(),i=r===void 0?`system`:r,a,o;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(a={success:(0,Z.jsx)(sn,{className:`size-4`}),info:(0,Z.jsx)(le,{className:`size-4`}),warning:(0,Z.jsx)(Dn,{className:`size-4`}),error:(0,Z.jsx)(Ks,{className:`size-4`}),loading:(0,Z.jsx)(Ze,{className:`size-4 animate-spin`})},o={"--normal-bg":`var(--popover)`,"--normal-text":`var(--popover-foreground)`,"--normal-border":`var(--border)`,"--border-radius":`var(--radius)`},t[2]=a,t[3]=o):(a=t[2],o=t[3]);let s;t[4]===Symbol.for(`react.memo_cache_sentinel`)?(s={classNames:{toast:`cn-toast`}},t[4]=s):s=t[4];let c;return t[5]!==n||t[6]!==i?(c=(0,Z.jsx)(La,{theme:i,className:`toaster group`,icons:a,style:o,toastOptions:s,...n}),t[5]=n,t[6]=i,t[7]=c):c=t[7],c};function zu(e){let{apiOrigin:t}=e;if(!t)return;let n=Symbol.for(`ok.desktop.fetchRewrite`);if(window.fetch[n])return;let r=window.fetch.bind(window),i=((e,n)=>{if(typeof e==`string`)return r(Bu(e,t),n);if(e instanceof URL)return e.pathname.startsWith(`/api/`)&&(e.origin===window.location.origin||e.protocol===`file:`)?r(t+(e.pathname+e.search+e.hash),n):r(e,n);try{let i=new URL(e.url,window.location.origin);if(i.pathname.startsWith(`/api/`)){let a=i.pathname+i.search+i.hash;return r(new Request(t+a,e),n)}}catch{}return r(e,n)});i[n]=!0,window.fetch=i}function Bu(e,t){return e.startsWith(`/api/`)?t+e:e}function Vu(e){return`#/${encodeURIComponent(e)}`}function Hu(e){let t=e.bridge;if(!t)return;let n=e.setHash??(e=>{window.location.hash=e});return t.onDeepLink(e=>{n(Vu(e.doc))})}var Uu=4e3,Wu=1440*60*1e3;function Gu(e){let t=e.bridge;if(t&&t.onboarding)return t.onboarding.onToast(e=>{if(e.kind===`ancestor-promote`){Xa.success(`Opened existing OK project at ${e.ancestorPath}`,{duration:Uu});return}if(e.kind===`mcp-repaired`){let t=e.editors.map(e=>qn[e]??e).join(`, `);Xa.success(`Repaired ${t} MCP integration. Restart ${t} if already open.`,{duration:Wu});return}if(e.kind===`mcp-repair-failed`){Xa.error(`MCP auto-repair failed — open Settings → AI Tool Integration to fix.`,{duration:Wu});return}let t=mo(e.gitRoot,e.pickedPath)??e.pickedPath;Xa.success(`Initialized OK at ${e.gitRoot} — opened parent of ${t} because it contains a .git folder`,{duration:Uu})})}var Ku=!1;function qu(e,t,n,r){let i=e[t];if(typeof i!=`function`){console.warn(`[cold-mount-instrumentation] target missing method "${t}"`);return}e[t]=function(...e){let t=performance.now(),a,o=!1;try{return a=i.apply(this,e),o=!0,a}finally{let e=performance.now()-t,i;if(o&&r)try{i=r(this,a,t,e)}catch(e){i={"instrumentation-error":e instanceof Error?e.message:String(e)}}try{Ge(n,{durationMs:Math.round(e*1e3)/1e3,threw:!o,...i},{startTime:t,duration:e})}catch{}}}}function Ju(e){return e?.doc?typeof e.doc.nodeSize==`number`?e.doc.nodeSize:e.doc.content&&typeof e.doc.content.size==`number`?e.doc.content.size:null:null}var Yu=0,Xu=0,Zu=0,Qu=0,$u=null,ed=[`linkResolutionDecoration$`],td=new WeakSet,nd=new WeakSet;function rd(e){return e.replace(/([a-z0-9])([A-Z])/g,`$1-$2`).toLowerCase()}function id(){return!1}function ad(){return!id()}function od(e,t){if(ad())return t;let n=`ok/cold/nodeview-factory-${rd(e)}`;return function(...r){let i=performance.now();try{return t(...r)}finally{let t=performance.now()-i;Ge(n,{nodeType:e,durationMs:Math.round(t*1e3)/1e3},{startTime:i,duration:t})}}}function sd(e){if(ad())return;let t=e.state.plugins;for(let e of t){if(nd.has(e))continue;let t=e.spec?.key?.key;if(!t||!ed.some(e=>t.startsWith(e)))continue;let n=e.props,r=n.decorations;if(typeof r!=`function`){nd.add(e);continue}let i=`ok/cold/decoration-${rd(t.replace(/\$\d*$/,``))}`;n.decorations=function(...e){let n=performance.now();try{return r.apply(this,e)}finally{let e=performance.now()-n;Ge(i,{pluginKey:t,durationMs:Math.round(e*1e3)/1e3},{startTime:n,duration:e})}},nd.add(e)}}function cd(e){if(ad())return;let t=e._props?.nodeViews;if(!(!t||typeof t!=`object`))for(let[e,n]of Object.entries(t)){if(typeof n!=`function`||n.__okWrapped===!0)continue;let r=od(e,n);r.__okWrapped=!0,t[e]=r}}function ld(e){return ad()?e:e.map(e=>{let t=e.name??`unknown`,n=rd(t);return e.extend({onBeforeCreate(){let e=performance.now();try{this.parent?.()}finally{let r=performance.now()-e;Ge(`ok/cold/ext-${n}-on-before-create`,{ext:t,hook:`onBeforeCreate`,durationMs:Math.round(r*1e3)/1e3},{startTime:e,duration:r})}},onCreate(){let e=performance.now();try{this.parent?.()}finally{let r=performance.now()-e;Ge(`ok/cold/ext-${n}-on-create`,{ext:t,hook:`onCreate`,durationMs:Math.round(r*1e3)/1e3},{startTime:e,duration:r})}},onUpdate(){let e=performance.now();try{this.parent?.()}finally{let r=performance.now()-e;Ge(`ok/cold/ext-${n}-on-update`,{ext:t,hook:`onUpdate`,durationMs:Math.round(r*1e3)/1e3},{startTime:e,duration:r})}},onDestroy(){let e=performance.now();try{this.parent?.()}finally{let r=performance.now()-e;Ge(`ok/cold/ext-${n}-on-destroy`,{ext:t,hook:`onDestroy`,durationMs:Math.round(r*1e3)/1e3},{startTime:e,duration:r})}}})})}function ud(){if(!Ku){Ku=!0,qu(hr.prototype,`mount`,`ok/cold/editor-mount`,(e,t,n,r)=>{let i=e;return ad()||($u=performance.now()),{elementDefault:i.options?.element?.nodeName??null,docSize:Ju(i.editorState),durationMs:r}}),qu(hr.prototype,`createView`,`ok/cold/editor-create-view`,e=>{let t=e;return!ad()&&!td.has(e)&&t.view&&(sd(t.view),cd(t.view),td.add(e)),{docSize:Ju(t.editorState)}}),qu(hr.prototype,`createNodeViews`,`ok/cold/create-node-views`,(e,t,n,r)=>{Qu+=1;let i=e;return!ad()&&i.view&&cd(i.view),{docSize:Ju(i.view),seq:Qu,durationMs:r}}),qu(Tn.prototype,`updateState`,`ok/cold/pm-update-state`,(e,t,n,r)=>(Xu+=1,{seq:Xu,docSize:Ju(e.state),durationMs:r})),qu(Tn.prototype,`setProps`,`ok/cold/pm-set-props`,(e,t,n,r)=>(Zu+=1,{seq:Zu,docSize:Ju(e.state),durationMs:r})),qu(x.prototype,`_forceRerender`,`ok/cold/force-rerender`,(e,t,n,r)=>{Yu+=1;let i=e,a=(()=>{try{return i.type?.toArray?i.type.toArray().length:null}catch{return null}})();return{seq:Yu,topLevelYElements:a,durationMs:r}}),qu(H.prototype,`init`,`ok/cold/ec-init`,e=>({editorPresent:!!e.props?.editor}));try{typeof PerformanceObserver<`u`&&new PerformanceObserver(e=>{for(let t of e.getEntries()){let e=t.name;if((e===`first-paint`||e===`first-contentful-paint`)&&(Ge(e===`first-paint`?`ok/cold/paint-fp`:`ok/cold/paint-fcp`,{entryType:t.entryType,startTime:Math.round(t.startTime*1e3)/1e3},{startTime:t.startTime,duration:0}),!ad()&&e===`first-paint`&&$u!==null)){let e=$u,n=Math.max(0,t.startTime-e);Ge(`ok/cold/append-to-paint`,{paintEntryType:t.entryType,durationMs:Math.round(n*1e3)/1e3,paintAt:Math.round(t.startTime*1e3)/1e3},{startTime:e,duration:n}),$u=null}}}).observe({type:`paint`,buffered:!0})}catch{}globalThis.__okColdMountInstrumented=!0}}var dd=`Relaunch`,fd=`Release notes`,pd=`Updates paused`,md=`Download`,hd=`Reset to defaults`,gd=`Relaunch failed — please restart manually`,_d=`Recovery action failed — please try again`;function vd(e,t){let n=t instanceof Error&&t.message?t.message:``;return n?`${e}: ${n}`:e}function yd(e){return`Version ${e} ready to install`}function bd(e){return`Updated to Version ${e}`}function xd(e){return`Your settings and recent projects were saved by a newer build than this one (v${e}). Reset to defaults to continue.`}var Sd=0,Cd=0,wd=1,Td=2,Ed=3;function Dd(e,t,n=()=>{}){let r=[];return r.push(e.onUpdateDownloaded(({version:r})=>{let i=`update-downloaded-${r}`;t({id:i,body:yd(r),priority:Td,action:{label:dd,onClick:()=>{e.update.relaunchNow().then(()=>{n(i)},e=>{t({id:`relaunch-error-${r}`,body:vd(gd,e),variant:`error`,priority:wd})})}}})})),r.push(e.onWhatsNew(({version:n,releaseUrl:r})=>{t({id:`whats-new-${n}`,body:bd(n),priority:Ed,action:{label:fd,onClick:()=>{e.shell.openExternal(r)}}})})),r.push(e.onUpdateStuckHint(({downloadUrl:n})=>{t({id:`update-stuck-hint`,body:pd,priority:Cd,action:{label:md,onClick:()=>{e.shell.openExternal(n)}}})})),()=>{for(let e of r)e()}}function Od(e,t,n,r=()=>{}){let i=`schema-incompatibility-${t.persistedSchemaVersion}`,a=`schema-incompatibility-error-${t.persistedSchemaVersion}`,o=e=>{r(i),n({id:a,body:vd(_d,e),variant:`error`,priority:Sd})};n({id:i,body:xd(t.currentBuild),priority:Sd,action:{label:hd,onClick:()=>{e.state.resetIncompatible().then(()=>{r(i)},o)}}})}var kd=[],Ad=new Set,jd=!1;function Md(){for(let e of Ad)e()}function Nd(e){let t=kd.findIndex(t=>t.id===e.id);if(t===-1)kd=[...kd,e];else{let n=kd.slice();n[t]=e,kd=n}Md()}function Pd(e){let t=kd.filter(t=>t.id!==e);t.length!==kd.length&&(kd=t,Md())}function Fd(){return kd}function Id(e){return Ad.add(e),()=>{Ad.delete(e)}}function Ld(){if(jd||typeof window>`u`)return;let e=window.okDesktop;e&&(jd=!0,Dd(e,Nd,Pd),e.state.query().then(t=>{t.schemaIncompatibility&&Od(e,t.schemaIncompatibility,Nd,Pd)},e=>{console.warn(`[update-notices-store] bridge.state.query() failed`,e)}))}var Rd=`ok-omnibar-recents-v1`,zd=10;function Bd(e){return typeof e==`object`&&!!e&&(e.kind===`file`||e.kind===`folder`)&&typeof e.path==`string`&&typeof e.lastOpenedAt==`string`}function Vd(e){if(e)return e;if(typeof window>`u`)return null;try{return window.localStorage}catch{return null}}function Hd(e,t){return`${e}:${t}`}function Ud(e){let t=Vd(e);if(!t)return[];try{let e=t.getItem(Rd);if(!e)return[];let n=JSON.parse(e);return Array.isArray(n)?n.filter(Bd).slice(0,zd):[]}catch{return[]}}function Wd(e,t){let n=Vd(t);if(n)try{n.setItem(Rd,JSON.stringify(e.slice(0,zd)))}catch(e){console.warn(`[omnibar] Failed to save recent entries:`,e)}}function Gd(e,t){return[t,...e.filter(e=>e.kind!==t.kind||e.path!==t.path)].slice(0,zd)}function Kd(e,t){return e.filter(e=>t.has(Hd(e.kind,e.path)))}var qd=50,Jd=30,Yd=``,Xd=null;function Zd(e){return e.trim().toLowerCase()}function Qd(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function $d(e){let t=e.trim();return t?[...new Set(t.split(/\s+/).filter(Boolean))].sort((e,t)=>t.length-e.length):[]}function ef(e,t,n=new Map,r=new Map){let i=[];for(let t of e){let e=r.get(t)?.modified,a=n.get(t);i.push({kind:`file`,path:t,name:pr(t),...a?{title:a}:{},...e?{modifiedTs:Date.parse(e)}:{}})}for(let e of t)i.push({kind:`folder`,path:e,name:pr(e)});return i.sort((e,t)=>{let n=e.path.localeCompare(t.path);return n===0?e.kind===t.kind?0:e.kind===`folder`?-1:1:n}),i}function tf(e){return cr({kind:e.kind===`file`?`page`:`folder`,path:e.path,title:e.title??e.name,modifiedTs:e.modifiedTs??0})}function nf(e){return{entries:e,byId:new Map(e.map(e=>[`${e.kind===`file`?`page`:`folder`}:${e.path}`,e])),corpus:Un(e.map(tf))}}function rf(e){return e.map(e=>`${e.kind}\u0000${e.path}\u0000${e.title??``}\u0000${e.modifiedTs??0}`).join(``)}function af(e){let t=rf(e);return Xd&&Yd===t?Xd:(Yd=t,Xd=nf(e),Xd)}function of(e,t,n=qd){return sf(af(e),t,n)}function sf(e,t,n=qd){let r=Zd(t);return r?kn(e.corpus,r,{intent:`omnibar`,limit:n,scopes:[`page`,`folder`]}).map(t=>e.byId.get(t.document.id)).filter(e=>e!==void 0):e.entries.slice(0,20)}function cf(e,t){let n=$d(t);if(n.length===0||e.length===0)return[{text:e,match:!1,start:0}];let r=RegExp(`(${n.map(Qd).join(`|`)})`,`gi`),i=[],a=0;for(let t of e.matchAll(r)){let n=t.index??0;n>a&&i.push({text:e.slice(a,n),match:!1,start:a}),i.push({text:t[0],match:!0,start:n}),a=n+t[0].length}return a<e.length&&i.push({text:e.slice(a),match:!1,start:a}),i.length>0?i:[{text:e,match:!1,start:0}]}function lf(e){if(e.kind!==`page`&&e.kind!==`folder`||typeof e.path!=`string`)return null;let t=pr(e.path);return{kind:e.kind===`page`?`file`:`folder`,path:e.path,name:t,...e.title&&{title:e.title},...e.snippet&&{snippet:e.snippet},...typeof e.score==`number`&&{score:e.score}}}async function uf(e,t={}){let n=e.trim();if(!n)return[];let r=await fetch(`/api/search`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({query:n,intent:`full_text`,scopes:[`page`,`folder`,`content`],limit:t.limit??Jd}),signal:t.signal});if(!r.ok){let e=await r.json().catch(()=>null);throw Error(Bn(e)??`Search failed with status ${r.status}`)}return((await r.json()).results??[]).map(lf).filter(e=>!!e)}function df(e,t,n=[]){let r=Zd(t);return r?Zd([e,...n].join(` `)).includes(r):!0}var ff=`tag:`;function pf(e,t){if(!e.toLowerCase().startsWith(`tag:`))return{kind:`normal`,query:e};let n=e.slice(4).replace(/^\s+/,``).trim();return n&&t.has(n)?{kind:`tag-docs`,tagName:n}:{kind:`tag-list`,query:n}}function mf(e,t){return B(e,t)}var hf=F;async function gf(e){let t=await fetch(`/api/tags/${encodeURIComponent(e)}`);if(!t.ok)throw Error(`/api/tags/${e} responded with ${t.status}`);let n=await t.json();return Array.isArray(n.docs)?n.docs:[]}var _f=`open-knowledge:doc-panel-tab`,vf=null;function yf(){let e=vf;return vf=null,e}function bf(e,t=typeof window>`u`?new EventTarget:window){vf=e,t.dispatchEvent(new CustomEvent(_f,{detail:{tab:e}}))}function xf(e,t=typeof window>`u`?new EventTarget:window){let n=t=>{let n=t instanceof CustomEvent?t.detail?.tab:void 0;n&&e(n)};return t.addEventListener(_f,n),()=>t.removeEventListener(_f,n)}function Sf(e){let t=(0,$.c)(8),n,r;t[0]===e?(n=t[1],r=t[2]):({className:n,...r}=e,t[0]=e,t[1]=n,t[2]=r);let i;t[3]===n?i=t[4]:(i=Y(`grid w-full gap-2`,n),t[3]=n,t[4]=i);let a;return t[5]!==r||t[6]!==i?(a=(0,Z.jsx)(Xl,{"data-slot":`radio-group`,className:i,...r}),t[5]=r,t[6]=i,t[7]=a):a=t[7],a}function Cf(e){let t=(0,$.c)(9),n,r;t[0]===e?(n=t[1],r=t[2]):({className:n,...r}=e,t[0]=e,t[1]=n,t[2]=r);let i;t[3]===n?i=t[4]:(i=Y(`group/radio-group-item peer relative flex aspect-square size-4 shrink-0 rounded-full border border-input outline-none after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 aria-invalid:aria-checked:border-primary dark:bg-input/30 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:border-primary data-checked:bg-primary data-checked:text-primary-foreground dark:data-checked:bg-primary`,n),t[3]=n,t[4]=i);let a;t[5]===Symbol.for(`react.memo_cache_sentinel`)?(a=(0,Z.jsx)(Ql,{"data-slot":`radio-group-indicator`,className:`flex size-4 items-center justify-center`,children:(0,Z.jsx)(`span`,{className:`absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2 rounded-full bg-primary-foreground`})}),t[5]=a):a=t[5];let o;return t[6]!==r||t[7]!==i?(o=(0,Z.jsx)(Zl,{"data-slot":`radio-group-item`,className:i,...r,children:a}),t[6]=r,t[7]=i,t[8]=o):o=t[8],o}var wf=[`.md`,`.mdx`];function Tf(e){let t=e.toLowerCase();for(let e of wf)if(t.endsWith(e))return e;return null}function Ef(e){let t=Tf(e);return t?e.slice(0,-t.length):e}var Df=`__blank__`,Of={local:0,inherited:1,user:2};function kf(e){return[...e].sort((e,t)=>{let n=Of[e.scope]-Of[t.scope];if(n!==0)return n;let r=(e.title??e.name).toLowerCase(),i=(t.title??t.name).toLowerCase();return r.localeCompare(i)})}function Af(e){return e.trim()?e.includes(`..`)?`Path cannot contain ".."`:e.startsWith(`/`)?`Path cannot start with "/"`:e.includes(`\\`)?`Path cannot contain backslashes`:e.includes(`\0`)?`Path cannot contain null bytes`:null:`Name cannot be empty`}function jf(e){let t=e.fileName.trim(),n=Tf(t)?t:`${t}${e.fileExtension??`.md`}`;if(e.kind===`folder`){let t=(e.folderName??``).trim();return`${e.initialDir?`${e.initialDir}/${t}`:t}/${n}`}return e.initialDir?`${e.initialDir}/${n}`:n}function Mf(e){let t=e.target;return t?.tagName===`INPUT`||t?.tagName===`TEXTAREA`||t?.isContentEditable?!1:!!((e.metaKey||e.ctrlKey)&&e.altKey&&e.key.toLowerCase()===`n`)}function Nf(e){let t=e.value.lastIndexOf(`.`);t>0?e.setSelectionRange(0,t):e.select()}function Pf(e){let t=(0,$.c)(115),{open:n,onOpenChange:r,kind:i,initialDir:a,suggestedName:o,initialTemplate:s,description:c,onCreated:l,folderConfig:u}=e,{addPage:d}=wr(),f=ra(u?null:a),p=u??f,[m,h]=(0,Q.useState)(``),[g,_]=(0,Q.useState)(``),[v,y]=(0,Q.useState)(`.md`),[b,x]=(0,Q.useState)(Df),[S,C]=(0,Q.useState)(null),[w,T]=(0,Q.useState)(!1),[E,D]=(0,Q.useState)(null),O=(0,Q.useId)(),k=(0,Q.useId)(),A=(0,Q.useId)(),j=(0,Q.useId)(),M=(0,Q.useRef)(null),N=(0,Q.useRef)(null),P,F;t[0]!==s||t[1]!==i||t[2]!==n||t[3]!==o?(P=()=>{if(n){C(null),D(null),T(!1),_(``),x(i===`file`&&s?s:Df);let e=i===`file`?o??`untitled`:`index`,t=Tf(e);y(t??`.md`),h(t?Ef(e):e)}},F=[n,i,o,s],t[0]=s,t[1]=i,t[2]=n,t[3]=o,t[4]=P,t[5]=F):(P=t[4],F=t[5]),(0,Q.useEffect)(P,F);let I=p.state.status===`ready`?kf(p.state.data.folder.templates_available??[]):[],L;t[6]!==p.state.data||t[7]!==p.state.status||t[8]!==n||t[9]!==b?(L=()=>{n&&b!==Df&&p.state.status===`ready`&&((p.state.data.folder.templates_available??[]).some(e=>e.name===b)||x(Df))},t[6]=p.state.data,t[7]=p.state.status,t[8]=n,t[9]=b,t[10]=L):L=t[10];let R;t[11]!==p.state||t[12]!==n||t[13]!==b?(R=[n,b,p.state],t[11]=p.state,t[12]=n,t[13]=b,t[14]=R):R=t[14],(0,Q.useEffect)(L,R);let z=i===`file`,B=p.state.status===`loading`||p.state.status===`idle`,V=p.state.status===`error`?p.state.message:null,H;t[15]===Symbol.for(`react.memo_cache_sentinel`)?(H=function(e){let t=Tf(e);t?(y(t),h(Ef(e))):h(e),C(null)},t[15]=H):H=t[15];let U=H,W;t[16]!==v||t[17]!==m||t[18]!==g||t[19]!==a||t[20]!==i?(W=function(){return jf({kind:i,initialDir:a,fileName:m,fileExtension:v,folderName:g})},t[16]=v,t[17]=m,t[18]=g,t[19]=a,t[20]=i,t[21]=W):W=t[21];let G=W,K;t[22]!==m||t[23]!==g||t[24]!==i?(K=function(){if(i===`folder`){let e=Af(g.trim());if(e)return{message:`Folder name: ${e}`,field:`folder`}}let e=Af(m.trim());return e?{message:e,field:`file`}:null},t[22]=m,t[23]=g,t[24]=i,t[25]=K):K=t[25];let q=K,ee;t[26]!==w||t[27]!==m||t[28]!==g||t[29]!==i?(ee=w||!m.trim()||i===`folder`&&!g.trim(),t[26]=w,t[27]=m,t[28]=g,t[29]=i,t[30]=ee):ee=t[30];let te=ee,ne;t[31]!==d||t[32]!==G||t[33]!==q||t[34]!==i||t[35]!==l||t[36]!==r||t[37]!==b?(ne=async function(){let e=q();if(e){C(e.message),D(e.field);return}T(!0),C(null),D(null);let t=G(),n=i===`file`&&b!==Df?b:void 0,a={path:t};n!==void 0&&(a.template=n);try{let e=await fetch(`/api/create-page`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(a)}),t=await Le(e,`Server error (HTTP ${e.status})`);if(!t.ok){T(!1),C(t.title),D(`form`);return}let n=Er.safeParse(t.body);if(T(!1),!n.success){C(`Failed to create ${i}`),D(`form`);return}let o=n.data.docName;r(!1),window.location.hash=`#/${o}`,d(o),Kn([`files`,`backlinks`,`graph`]),l?.(o)}catch(e){console.warn(`[NewItemDialog] create failed:`,e),T(!1),C(`Network error — please try again`),D(`form`)}},t[31]=d,t[32]=G,t[33]=q,t[34]=i,t[35]=l,t[36]=r,t[37]=b,t[38]=ne):ne=t[38];let re=ne,ie=a||`(root)`,ae=i===`file`?`New file`:`New folder`,oe=Ja,se=Va,ce;t[39]===ae?ce=t[40]:(ce=(0,Z.jsx)(Ra,{children:ae}),t[39]=ae,t[40]=ce);let le;t[41]!==c||t[42]!==ie?(le=c??(0,Z.jsxs)(Z.Fragment,{children:[`Create in `,(0,Z.jsx)(`span`,{className:`font-medium text-foreground`,children:ie})]}),t[41]=c,t[42]=ie,t[43]=le):le=t[43];let ue;t[44]===le?ue=t[45]:(ue=(0,Z.jsx)(Ia,{children:le}),t[44]=le,t[45]=ue);let de;t[46]!==ce||t[47]!==ue?(de=(0,Z.jsxs)(qa,{children:[ce,ue]}),t[46]=ce,t[47]=ue,t[48]=de):de=t[48];let fe=Wa,pe=z&&(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{id:j,className:`mb-1.5 text-sm font-medium`,children:`Start from`}),B?(0,Z.jsx)(`div`,{className:`rounded-md border border-border bg-muted/30 px-3 py-2 text-xs text-muted-foreground`,children:`Loading templates`}):(0,Z.jsxs)(Z.Fragment,{children:[V?(0,Z.jsxs)(`p`,{role:`alert`,className:`mb-1.5 text-xs text-destructive`,children:[`Could not load templates: `,V,`. You can still create a blank note.`]}):null,(0,Z.jsxs)(Sf,{value:b,onValueChange:x,"aria-labelledby":j,className:`max-h-56 overflow-y-auto rounded-md border border-border bg-card subtle-scrollbar`,children:[(0,Z.jsx)(Rf,{value:Df,title:`Blank note`,description:`Empty starting content`}),I.length===0&&!V?(0,Z.jsx)(`p`,{className:`px-3 pb-2 text-xs text-muted-foreground`,children:`No templates resolve here. Add one in this folder's Templates section, or in Settings → User templates.`}):I.map(Lf)]})]})]}),me;t[49]!==S||t[50]!==E||t[51]!==O||t[52]!==k||t[53]!==g||t[54]!==i?(me=i===`folder`&&(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{className:`mb-1.5 block text-sm font-medium`,htmlFor:k,children:`Folder name`}),(0,Z.jsx)(fo,{ref:N,id:k,value:g,onChange:e=>{_(e.target.value),C(null)},placeholder:`folder-name`,autoFocus:!0,"aria-describedby":S&&(E===`folder`||E===`form`)?O:void 0,"aria-invalid":S&&(E===`folder`||E===`form`)?!0:void 0,onKeyDown:e=>{if(e.key===`Enter`){e.preventDefault();let t=Af(g.trim());if(t){C(`Folder name: ${t}`),D(`folder`);return}M.current?.focus()}}})]}),t[49]=S,t[50]=E,t[51]=O,t[52]=k,t[53]=g,t[54]=i,t[55]=me):me=t[55];let he=i===`folder`?`First file name`:`File name`,ge;t[56]!==A||t[57]!==he?(ge=(0,Z.jsx)(`label`,{className:`mb-1.5 block text-sm font-medium`,htmlFor:A,children:he}),t[56]=A,t[57]=he,t[58]=ge):ge=t[58];let _e;t[59]===U?_e=t[60]:(_e=e=>U(e.target.value),t[59]=U,t[60]=_e);let ve=i===`file`,ye=S&&(E===`file`||E===`form`)?O:void 0,be=S&&(E===`file`||E===`form`)?!0:void 0,xe;t[61]!==re||t[62]!==te?(xe=e=>{e.key===`Enter`&&!te&&re()},t[61]=re,t[62]=te,t[63]=xe):xe=t[63];let Se;t[64]!==A||t[65]!==m||t[66]!==_e||t[67]!==ve||t[68]!==ye||t[69]!==be||t[70]!==xe?(Se=(0,Z.jsx)(fo,{ref:M,id:A,value:m,onChange:_e,placeholder:`my-note`,autoFocus:ve,"aria-describedby":ye,"aria-invalid":be,onFocus:If,onKeyDown:xe,className:`flex-1`}),t[64]=A,t[65]=m,t[66]=_e,t[67]=ve,t[68]=ye,t[69]=be,t[70]=xe,t[71]=Se):Se=t[71];let Ce;t[72]===Symbol.for(`react.memo_cache_sentinel`)?(Ce=e=>{(e===`.md`||e===`.mdx`)&&y(e)},t[72]=Ce):Ce=t[72];let we;t[73]===Symbol.for(`react.memo_cache_sentinel`)?(we=wf.map(Ff),t[73]=we):we=t[73];let J;t[74]===v?J=t[75]:(J=(0,Z.jsx)(ao,{type:`single`,value:v,onValueChange:Ce,variant:`outline`,size:`sm`,"aria-label":`File extension`,className:`shrink-0`,children:we}),t[74]=v,t[75]=J);let Te;t[76]!==Se||t[77]!==J?(Te=(0,Z.jsxs)(`div`,{className:`flex items-stretch gap-2`,children:[Se,J]}),t[76]=Se,t[77]=J,t[78]=Te):Te=t[78];let Ee;t[79]!==S||t[80]!==O?(Ee=S&&(0,Z.jsx)(`p`,{id:O,role:`alert`,className:`text-xs text-red-600 dark:text-red-400`,children:S}),t[79]=S,t[80]=O,t[81]=Ee):Ee=t[81];let De;t[82]!==ge||t[83]!==Te||t[84]!==Ee?(De=(0,Z.jsxs)(`div`,{children:[ge,Te,Ee]}),t[82]=ge,t[83]=Te,t[84]=Ee,t[85]=De):De=t[85];let Oe;t[86]!==pe||t[87]!==me||t[88]!==De?(Oe=(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[pe,me,De]}),t[86]=pe,t[87]=me,t[88]=De,t[89]=Oe):Oe=t[89];let ke;t[90]!==fe||t[91]!==Oe?(ke=(0,Z.jsx)(fe,{children:Oe}),t[90]=fe,t[91]=Oe,t[92]=ke):ke=t[92];let Ae;t[93]===r?Ae=t[94]:(Ae=()=>r(!1),t[93]=r,t[94]=Ae);let je;t[95]!==w||t[96]!==Ae?(je=(0,Z.jsx)(X,{variant:`outline`,className:`font-mono uppercase`,onClick:Ae,disabled:w,children:`Cancel`}),t[95]=w,t[96]=Ae,t[97]=je):je=t[97];let Me=w?`Creating`:`Create`,Ne;t[98]!==re||t[99]!==te||t[100]!==Me?(Ne=(0,Z.jsx)(X,{onClick:re,disabled:te,children:Me}),t[98]=re,t[99]=te,t[100]=Me,t[101]=Ne):Ne=t[101];let Pe;t[102]!==je||t[103]!==Ne?(Pe=(0,Z.jsxs)(Ga,{children:[je,Ne]}),t[102]=je,t[103]=Ne,t[104]=Pe):Pe=t[104];let Fe;t[105]!==se||t[106]!==de||t[107]!==ke||t[108]!==Pe?(Fe=(0,Z.jsxs)(se,{className:`sm:max-w-md`,"data-ok-layer-spawned":``,children:[de,ke,Pe]}),t[105]=se,t[106]=de,t[107]=ke,t[108]=Pe,t[109]=Fe):Fe=t[109];let Ie;return t[110]!==oe||t[111]!==r||t[112]!==n||t[113]!==Fe?(Ie=(0,Z.jsx)(oe,{open:n,onOpenChange:r,children:Fe}),t[110]=oe,t[111]=r,t[112]=n,t[113]=Fe,t[114]=Ie):Ie=t[114],Ie}function Ff(e){return(0,Z.jsx)(ro,{value:e,"aria-label":`Use ${e} extension`,children:e},e)}function If(e){return Nf(e.currentTarget)}function Lf(e){return(0,Z.jsx)(Rf,{value:e.name,title:e.title??e.name,subName:e.title&&e.title!==e.name?e.name:void 0,description:e.description,scope:e.scope,sourceFolder:e.source_folder},`${e.scope}:${e.source_folder}:${e.name}`)}function Rf(e){let t=(0,$.c)(26),{value:n,title:r,subName:i,description:a,scope:o,sourceFolder:s}=e,c=(0,Q.useId)(),l;t[0]!==c||t[1]!==n?(l=(0,Z.jsx)(Cf,{id:c,value:n,className:`mt-1`}),t[0]=c,t[1]=n,t[2]=l):l=t[2];let u;t[3]===r?u=t[4]:(u=(0,Z.jsx)(`span`,{className:`truncate text-sm font-medium`,children:r}),t[3]=r,t[4]=u);let d;t[5]===i?d=t[6]:(d=i?(0,Z.jsx)(`code`,{className:`font-mono text-2xs text-muted-foreground shrink-0`,children:i}):null,t[5]=i,t[6]=d);let f;t[7]!==o||t[8]!==s?(f=o===`inherited`&&s?(0,Z.jsx)(Ne,{variant:`gray`,className:`ml-auto shrink-0 text-2xs`,children:s||`root`}):null,t[7]=o,t[8]=s,t[9]=f):f=t[9];let p;t[10]===o?p=t[11]:(p=o===`user`?(0,Z.jsx)(Ne,{variant:`primary`,className:`ml-auto shrink-0 text-2xs`,children:`user`}):null,t[10]=o,t[11]=p);let m;t[12]!==u||t[13]!==d||t[14]!==f||t[15]!==p?(m=(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[u,d,f,p]}),t[12]=u,t[13]=d,t[14]=f,t[15]=p,t[16]=m):m=t[16];let h;t[17]===a?h=t[18]:(h=a?(0,Z.jsx)(`p`,{className:`mt-0.5 line-clamp-2 text-xs text-muted-foreground`,children:a}):null,t[17]=a,t[18]=h);let g;t[19]!==m||t[20]!==h?(g=(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[m,h]}),t[19]=m,t[20]=h,t[21]=g):g=t[21];let _;return t[22]!==c||t[23]!==l||t[24]!==g?(_=(0,Z.jsxs)(`label`,{htmlFor:c,className:`flex cursor-pointer items-start gap-3 px-3 py-2 transition-colors hover:bg-muted/50 has-data-[state=checked]:bg-muted/70`,children:[l,g]}),t[22]=c,t[23]=l,t[24]=g,t[25]=_):_=t[25],_}var zf=[{id:`claude-cowork`,displayName:`Claude Cowork`,appBrandName:`Claude Desktop`,schemes:[`claude:`],installUrl:`https://claude.com/download`,hasWebFallback:!0,tagline:`Conversational pairing in Claude Desktop's Cowork tab.`},{id:`claude-code`,displayName:`Claude Code`,appBrandName:`Claude Desktop`,schemes:[`claude:`],installUrl:`https://claude.com/download`,hasWebFallback:!0,tagline:`Agentic coding in Claude Desktop's Code tab.`},{id:`codex`,displayName:`Codex`,appBrandName:`Codex Desktop`,schemes:[`codex:`],installUrl:`https://openai.com/codex`,tagline:`OpenAI's coding agent, terminal-native.`},{id:`cursor`,displayName:`Cursor`,schemes:[`cursor:`],installUrl:`https://cursor.com/`,tagline:`AI-first VS Code fork with multi-file edits.`}],Bf=`#settings`;function Vf(e){let t=e.target;return t?.tagName===`INPUT`||t?.tagName===`TEXTAREA`||t?.isContentEditable?!1:!!((e.metaKey||e.ctrlKey)&&!e.altKey&&e.key===`,`)}function Hf(e){return e.replace(/^#/,``)===`settings`}function Uf(){return typeof window>`u`?``:window.location.hash}function Wf(){let e=(0,$.c)(4),[t,n]=(0,Q.useState)(Kf),r,i;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(r=()=>{let e=()=>{n(Hf(Uf()))};return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},i=[],e[0]=r,e[1]=i):(r=e[0],i=e[1]),(0,Q.useEffect)(r,i);let a=Gf,o;return e[2]===t?o=e[3]:(o={open:t,close:a},e[2]=t,e[3]=o),o}function Gf(){typeof window>`u`||Hf(Uf())&&window.history.back()}function Kf(){return Hf(Uf())}function qf(){let e=(0,$.c)(3),[t,n]=(0,Q.useState)(Xf),r,i;return e[0]===t?(r=e[1],i=e[2]):(r=()=>{if(t!==null||typeof window>`u`||window.okDesktop)return;let e=!0;return fetch(`/api/workspace`).then(async t=>{let r=await t.json().catch(Yf);if(!e||!t.ok)return;let i=On.safeParse(r);i.success&&n({contentDir:i.data.contentDir,pathSeparator:i.data.pathSeparator})}).catch(Jf),()=>{e=!1}},i=[t],e[0]=t,e[1]=r,e[2]=i),(0,Q.useEffect)(r,i),t}function Jf(e){console.warn(`[useWorkspace] /api/workspace fetch failed:`,e)}function Yf(){return null}function Xf(){return Zf()}function Zf(e=typeof window>`u`?void 0:window){if(!e)return null;let t=e.okDesktop;return t?{contentDir:t.config.projectPath,pathSeparator:t.platform===`win32`?`\\`:`/`}:null}function Qf(e){return{async install(t){let n;try{n=await e.buildAndOpen(t?.force?{force:!0}:void 0)}catch(e){return{ok:!1,reason:`bridge-error`,message:e instanceof Error?e.message:String(e)}}return n.ok?{ok:!0,path:n.path}:{ok:!1,reason:n.reason,message:n.message}}}}function $f(e={}){let t=e.fetch??globalThis.fetch,n=`${e.apiOrigin??``}/api/install-skill`;return{async install(e){let r;try{r=await t(n,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e?.force?{force:!0}:{})})}catch(e){return{ok:!1,reason:`network-error`,message:e instanceof Error?e.message:String(e)}}if(!r.ok){let e=`HTTP ${r.status}`;try{let t=Bn(await r.json());t&&(e=t)}catch{}return{ok:!1,reason:`http-error`,message:e}}let i;try{i=await r.json()}catch(e){return{ok:!1,reason:`parse-error`,message:e instanceof Error?e.message:`Invalid server response`}}return!i||typeof i.status!=`string`?{ok:!1,reason:`parse-error`,message:`Invalid server response shape`}:i.status===`failed`?{ok:!1,reason:`build-failed`,message:i.buildError??`unknown build failure`}:{ok:!0,path:i.outputPath,handoffWarning:i.handoffError?.message}}}}function ep(){if(typeof window>`u`)return null;let e=window.okDesktop?.skill;return e?Qf(e):$f()}var tp=`ok:skill:cowork:installed`,np=`1`,rp=250,ip=`/api/skill/install-state`;function ap(e){return`${tp}:v${e}`}var op=new Map;async function sp(e={},t={}){let n=t.force?`__force__`:`__default__`,r=op.get(n);if(r)return r;let i=cp(e,t);return op.set(n,i),i.finally(()=>{op.get(n)===i&&op.delete(n)}),i}async function cp(e,t){let n=e.installer===void 0?ep():e.installer,r=lp(e.storage),i=e.fetchSnapshot??dp,a=e.serverTimeoutMs??rp,o=null;if(!t.force){try{o=await fp(i(),a)}catch(e){console.warn(`[cowork-skill] server install-state check failed; falling through:`,e)}if(o){let e=o.targets[`claude-cowork`]??null;if(e&&e.version===o.currentVersion)return{kind:`already-installed`,source:`server`}}}let s=ap(o?.currentVersion??e.fallbackSkillVersion??up());if(!t.force&&r?.getItem(s)===np)return{kind:`already-installed`,source:`local`};if(!n)return{kind:`host-unsupported`};let c=await n.install({force:t.force??!1});if(!c.ok)return{kind:`install-failed`,reason:c.reason,message:c.message};try{r?.setItem(s,np)}catch(e){console.warn(`[cowork-skill] storage.setItem failed (guard will not persist):`,e)}return{kind:`installed-now`,path:c.path,handoffWarning:c.handoffWarning}}function lp(e){if(e!==void 0)return e;if(typeof window>`u`)return null;try{return window.localStorage}catch{return null}}function up(){return typeof window>`u`?`unknown`:window.okDesktop?.appVersion??`unknown`}async function dp(){let e;try{e=await fetch(ip,{method:`GET`,cache:`no-store`})}catch{return null}if(!e.ok)return null;try{let t=await e.json();return typeof t?.currentVersion==`string`?t:null}catch{return null}}async function fp(e,t){return Promise.race([e,new Promise(e=>{setTimeout(()=>e(null),t)})])}function pp(e){return sp({},e)}function mp(){return sp({},{force:!0})}async function hp(e,t){let n;try{n=await t(`/api/handoff`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)})}catch(e){return{ok:!1,reason:`dispatch-error`,detail:e instanceof Error?e.message:String(e)}}return n.status===200?{ok:!0}:n.status===404?{ok:!1,reason:`not-installed`,detail:`POST /api/handoff returned 404`}:n.status===422?{ok:!1,reason:`not-installed`,detail:`POST /api/handoff returned ${n.status}`}:{ok:!1,reason:`dispatch-error`,detail:`POST /api/handoff returned ${n.status}`}}async function gp(e,t={}){let n=t.fetch??globalThis.fetch.bind(globalThis);switch(e.target){case`claude-cowork`:return hp({target:`claude-cowork`,url:An({mode:`cowork`},e)},n);case`claude-code`:return hp({target:`claude-code`,url:An({mode:`code`},e)},n);case`codex`:return hp({target:`codex`,url:Pn(e)},n);case`cursor`:return hp({target:`cursor`,url:Cn(e),workspacePath:e.projectDir},n);default:{let t=e.target;return{ok:!1,reason:`invalid-payload`,detail:`unknown target: ${String(t)}`}}}}async function _p(e,t={}){let n=t.okDesktop??(typeof window<`u`?window.okDesktop:void 0);if(n?.shell?.openExternal)try{return await n.shell.openExternal(e),{ok:!0}}catch(e){return{ok:!1,reason:`dispatch-error`,detail:vp(e)}}let r=t.doc??(typeof document<`u`?document:void 0);if(!r)return{ok:!1,reason:`dispatch-error`,detail:`no DOM available`};try{let t=r.createElement(`a`);return t.href=e,t.rel=`noopener noreferrer`,/^https?:/i.test(e)&&(t.target=`_blank`),r.body.appendChild(t),t.click(),t.remove(),{ok:!0}}catch(e){return{ok:!1,reason:`dispatch-error`,detail:vp(e)}}}function vp(e){if(e instanceof Error)return e.message;if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return String(e)}}async function yp(e,t={}){let n=t.okDesktop??(typeof window<`u`?window.okDesktop:void 0);if(n?.shell?.recordHandoff)try{await n.shell.recordHandoff(e)}catch(e){(t.warn??(e=>console.warn(e)))(`[handoff] recordHandoff IPC rejected (telemetry skipped): ${e instanceof Error?e.message:String(e)}`)}}function bp(e,t,n){let r=n===`\\`?t.replaceAll(`/`,`\\`):t;return`${e.endsWith(n)?e.slice(0,-1):e}${n}${r}`}function xp(e){return`${e}.md`}function Sp(e){if(!e.docName||!e.workspace)return null;let t=xp(e.docName),{contentDir:n,pathSeparator:r}=e.workspace;return{docContext:{relativePath:t},projectDir:n,docPath:bp(n,t,r)}}function Cp(e){return e.workspace?.contentDir?{docContext:null,projectDir:e.workspace.contentDir,docPath:``}:null}function wp(e){return _p(e.installUrl).then(()=>void 0)}function Tp(e){return`Opened in ${e}.`}function Ep(e,t=1){return t>=3?`Couldn't reach ${e} — please try again later.`:t===2?`Still couldn't reach ${e} — try one more time?`:`Couldn't reach ${e} — try again?`}function Dp(e){return e>=3?null:e===2?`Try one more time`:`Retry`}function Op(e,t,n,r){return t.ok?{target:e,host:n,outcome:`ok`,ts:r}:{target:e,host:n,outcome:`error`,ts:r,reason:t.reason}}async function kp(e,t,n,r=1){if(e===`claude-cowork`&&r===1){let e;try{e=await n.ensureCoworkSkillInstalled()}catch(e){let t=e instanceof Error?e.message:String(e);return n.toast.error(`Couldn't install Open Knowledge skill — ${t}`),{ok:!1,reason:`dispatch-error`,detail:`install-error: ${t}`}}if(e.kind===`installed-now`)return n.toast.success(`Open Knowledge skill saved. Upload it in Claude Desktop, then click Cowork again.`),{ok:!0};if(e.kind===`install-failed`){let t=e.message??e.reason;return n.toast.error(`Couldn't install Open Knowledge skill — ${t}`),{ok:!1,reason:`dispatch-error`,detail:`install-failed: ${t}`}}}let i={target:e,projectDir:t.projectDir,docPath:t.docPath,prompt:t.docContext===null?``:tr(t.docContext)},a=await n.dispatchHandoff(i),o=Op(e,a,n.isElectronHost()?`electron`:`web`,n.now().toISOString());await n.recordHandoff(o);let s=n.getDisplayName(e);if(a.ok)n.toast.success(Tp(s));else{let i=Dp(r),a=Ep(s,r);i===null?n.toast.error(a):n.toast.error(a,{action:{label:i,onClick:()=>{kp(e,t,n,r+1)}}})}return a}function Ap(e){return zf.find(t=>t.id===e)?.displayName??e}function jp(e=typeof window<`u`?window:void 0){return e?.okDesktop!=null}function Mp(){return{dispatchHandoff:gp,recordHandoff:yp,toast:{success:e=>{Xa.success(e)},error:(e,t)=>{Xa.error(e,t?{action:t.action}:void 0)}},now:()=>new Date,isElectronHost:()=>jp(),getDisplayName:Ap,ensureCoworkSkillInstalled:pp}}function Np(){return{dispatch:(e,t)=>kp(e,t,Mp()),reinstallCoworkSkill:mp}}var Pp=[...new Set(zf.flatMap(e=>e.schemes))];function Fp(e,t){let n=t.now?.()??Date.now(),r={};for(let t of zf){let i=t.schemes[0],a=i===void 0?void 0:e[i];if(!a){r[t.id]={installed:null};continue}r[t.id]={installed:a.installed,...a.displayName===void 0?{}:{displayName:a.displayName},lastChecked:n}}return r}function Ip(e){return Fp({},e)}async function Lp(e){let t=e.schemes??Pp,n=await Promise.all(t.map(async t=>{let n=t.replace(/:$/,``);try{return[t,await e.detectProtocol(n)]}catch{return[t,{installed:!1}]}}));return Object.fromEntries(n)}var Rp=Object.fromEntries(Pp.map(e=>[e,{installed:!1}]));async function zp(e){let t;try{t=await e.fetch(`/api/installed-agents`,{signal:e.signal,headers:{Accept:`application/json`}})}catch(e){if(e.name===`AbortError`)throw e;return Rp}if(!t.ok)return Rp;let n;try{n=await t.json()}catch{return Rp}if(typeof n!=`object`||!n||Array.isArray(n))return Rp;let r=n,i={};for(let e of Pp)i[e]={installed:r[e.replace(/:$/,``)]===!0};return i}function Bp(e,t){let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n){let n=e[r],i=t[r];if(!n||!i||n.installed!==i.installed||n.displayName!==i.displayName)return!1}return!0}function Vp(e){let t=e.throttleMs??1e4,n=!1,r=null,i=null,a={},o=Ip({isElectronHost:e.isElectronHost(),now:e.now}),s=new Set,c=()=>{if(!n)for(let e of s)e(o)},l=()=>{o=Fp(a,{isElectronHost:e.isElectronHost(),now:e.now})};return{probe:async()=>{if(n)return;if(i)return i;if(r!==null&&e.now()-r<t)return;let o=(async()=>{try{let t=await e.probe();if(n)return;let i=!Bp(a,t);a=t,i&&(l(),c()),r=e.now()}catch{}finally{i=null}})();return i=o,o},getTargetStates:()=>o,subscribe:e=>(s.add(e),()=>{s.delete(e)}),cancel:()=>{n=!0,s.clear()}}}function Hp(e=typeof window<`u`?window:void 0){return e?.okDesktop!=null}function Up(){let e=typeof window<`u`?window.okDesktop:void 0;if(e){let t=t=>e.shell.detectProtocol(t);return{probe:()=>Lp({detectProtocol:t}),isElectronHost:()=>!0,now:Date.now}}let t=globalThis.fetch.bind(globalThis);return{probe:()=>zp({fetch:t}),isElectronHost:()=>!1,now:Date.now}}function Wp(){let e=(0,$.c)(5),[t,n]=(0,Q.useState)(Gp),r=(0,Q.useRef)(null),i,a;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(i=()=>{let e=Vp(Up());r.current=e;let t=e.subscribe(n);e.probe();let i=()=>{e.probe()};return typeof window<`u`&&window.addEventListener(`focus`,i),()=>{typeof window<`u`&&window.removeEventListener(`focus`,i),t(),e.cancel(),r.current=null}},a=[],e[0]=i,e[1]=a):(i=e[0],a=e[1]),(0,Q.useEffect)(i,a);let o;e[2]===Symbol.for(`react.memo_cache_sentinel`)?(o=()=>r.current?.probe()??Promise.resolve(),e[2]=o):o=e[2];let s;return e[3]===t?s=e[4]:(s={states:t,refresh:o},e[3]=t,e[4]=s),s}function Gp(){return Ip({isElectronHost:Hp(),now:Date.now})}var Kp=3e3,qp=(e,t,n)=>wc(e,t,n,`CommandPalette`);function Jp(e){window.location.assign(er(e))}function Yp(e,t){return e?.kind===`folder`||e?.kind===`folder-index`?e.folderPath:Jn(t)}function Xp(e){let t=(0,$.c)(23),{entry:n,query:r,onSelect:i}=e,a=r===void 0?``:r,o=n.kind===`folder`?G:ws,s;t[0]===n?s=t[1]:(s=`title`in n&&n.title?n.title:n.path.split(`/`).pop()??n.path,t[0]=n,t[1]=s);let c=s,l=`snippet`in n?n.snippet:void 0,u=`${n.kind} ${n.path}`,d=`command-palette-nav-${n.kind}-${n.path}`,f;t[2]===o?f=t[3]:(f=(0,Z.jsx)(o,{className:`mt-0.5`}),t[2]=o,t[3]=f);let p;t[4]!==a||t[5]!==c?(p=(0,Z.jsx)(`span`,{className:`truncate font-medium`,children:(0,Z.jsx)(Zp,{query:a,text:c})}),t[4]=a,t[5]=c,t[6]=p):p=t[6];let m;t[7]!==n.path||t[8]!==a?(m=(0,Z.jsx)(`span`,{className:`truncate text-muted-foreground text-xs`,children:(0,Z.jsx)(Zp,{query:a,text:n.path})}),t[7]=n.path,t[8]=a,t[9]=m):m=t[9];let h;t[10]!==a||t[11]!==l?(h=l?(0,Z.jsx)(`span`,{className:`max-h-10 overflow-hidden text-muted-foreground text-xs leading-relaxed`,children:(0,Z.jsx)(Zp,{query:a,text:l})}):null,t[10]=a,t[11]=l,t[12]=h):h=t[12];let g;t[13]!==p||t[14]!==m||t[15]!==h?(g=(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col gap-1`,children:[p,m,h]}),t[13]=p,t[14]=m,t[15]=h,t[16]=g):g=t[16];let _;return t[17]!==i||t[18]!==u||t[19]!==d||t[20]!==f||t[21]!==g?(_=(0,Z.jsxs)(L,{value:u,onSelect:i,"data-testid":d,className:`items-start`,children:[f,g]}),t[17]=i,t[18]=u,t[19]=d,t[20]=f,t[21]=g,t[22]=_):_=t[22],_}function Zp(e){let t=(0,$.c)(5),{text:n,query:r}=e,i;t[0]!==r||t[1]!==n?(i=cf(n,r).map(Qp),t[0]=r,t[1]=n,t[2]=i):i=t[2];let a;return t[3]===i?a=t[4]:(a=(0,Z.jsx)(Z.Fragment,{children:i}),t[3]=i,t[4]=a),a}function Qp(e){let t=`${e.start}:${e.match?`match`:`plain`}`;return e.match?(0,Z.jsx)(`mark`,{className:`rounded-sm bg-primary/10 px-0.5 font-semibold text-primary`,children:e.text},t):(0,Z.jsx)(`span`,{children:e.text},t)}function $p({searchResults:e,fallbackSearchResults:t,searchStatus:n}){return e.length>0?e:n===`success`?[]:t}function em(e){let t=(0,$.c)(104),{bridge:n,open:r,onOpenChange:i}=e,a=n===void 0?null:n,[o,s]=(0,Q.useState)(``),c=(0,Q.useDeferredValue)(o),l=c.trim(),d;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(d=[],t[0]=d):d=t[0];let[f,p]=(0,Q.useState)(d),[m,h]=(0,Q.useState)(`idle`),_;t[1]===Symbol.for(`react.memo_cache_sentinel`)?(_=[],t[1]=_):_=t[1];let[v,b]=(0,Q.useState)(_),x;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(x=[],t[2]=x):x=t[2];let[S,C]=(0,Q.useState)(x),[w,T]=(0,Q.useState)(null),E;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(E=[],t[3]=E):E=t[3];let[D,O]=(0,Q.useState)(E),[k,A]=(0,Q.useState)(`idle`),j;t[4]===Symbol.for(`react.memo_cache_sentinel`)?(j=[],t[4]=j):j=t[4];let[M,N]=(0,Q.useState)(j),[P,F]=(0,Q.useState)(`idle`),I=(0,Q.useRef)(!1),R=(0,Q.useRef)(null),z=(0,Q.useRef)(null),{activeDocName:B,activeTarget:V}=We(),{pages:H,pageTitles:U,pageMeta:W,folderPaths:K}=wr(),q=qf(),{states:ee,refresh:ne}=Wp(),{dispatch:re}=Np(),ie=Sp({docName:B,workspace:q}),ae=ef(H,K,U,W),oe=Kd(S,new Set(ae.map(rm))),se=a?.config.projectPath??null,ce=a?v.filter(e=>e.path!==se):[],le;t[5]!==B||t[6]!==V?(le=Yp(V,B),t[5]=B,t[6]=V,t[7]=le):le=t[7];let ue=le,de=l===``?[]:of(ae,l,8),fe,pe;t[8]!==i||t[9]!==r?(fe=()=>{let e=function(e){e.key===`k`&&(Vr()?e.metaKey:e.ctrlKey)&&(e.preventDefault(),i(!r))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},pe=[i,r],t[8]=i,t[9]=r,t[10]=fe,t[11]=pe):(fe=t[10],pe=t[11]),(0,Q.useEffect)(fe,pe);let me,he;t[12]!==a||t[13]!==r||t[14]!==ne?(me=()=>{if(r){if(C(Ud()),ne(),a){let e=!1;return qp(async()=>{let t=await a.project.listRecent();e||b(t)},`Failed to load recent projects.`),()=>{e=!0}}return}s(``),O([]),A(`idle`),I.current=!1,N([]),F(`idle`)},he=[r,a,ne],t[12]=a,t[13]=r,t[14]=ne,t[15]=me,t[16]=he):(me=t[15],he=t[16]),(0,Q.useEffect)(me,he);let ge;t[17]===Symbol.for(`react.memo_cache_sentinel`)?(ge=()=>{R.current&&(R.current.scrollTop=0)},t[17]=ge):ge=t[17];let _e;t[18]===o?_e=t[19]:(_e=[o],t[18]=o,t[19]=_e),(0,Q.useEffect)(ge,_e);let ve=pf(c,new Set(D.map(nm))),ye=ve.kind!==`normal`,be,xe;t[20]!==ye||t[21]!==r?(be=()=>{if(!r||!ye||I.current)return;I.current=!0,A(`loading`);let e=!1;return hf().then(t=>{e||(O(t),A(`success`))}).catch(t=>{e||(console.error(`[command-palette-tag] fetch tags failed`,t),O([]),A(`error`))}),()=>{e=!0}},xe=[r,ye],t[20]=ye,t[21]=r,t[22]=be,t[23]=xe):(be=t[22],xe=t[23]),(0,Q.useEffect)(be,xe);let Se=ve.kind===`tag-docs`?ve.tagName:null;(0,Q.useEffect)(()=>{if(!r||Se===null){N([]),F(`idle`);return}F(`loading`),N([]);let e=!1;return gf(Se).then(t=>{e||(N(t),F(`success`))}).catch(t=>{e||(console.error(`[command-palette-tag] fetch tag docs failed`,t),N([]),F(`error`))}),()=>{e=!0}},[r,Se]),(0,Q.useEffect)(()=>{if(!r||!l||ye){p([]),h(`idle`);return}let e=new AbortController;h(`loading`);let t=!1,n=window.setTimeout(()=>{t=!0,e.abort(),p([]),h(`error`)},Kp);return uf(l,{signal:e.signal}).then(e=>{window.clearTimeout(n),p(e),h(`success`)}).catch(e=>{window.clearTimeout(n),!(e instanceof Error&&e.name===`AbortError`&&!t)&&(p([]),h(`error`))}),()=>{window.clearTimeout(n),e.abort()}},[r,l,ye]);let Ce;t[24]===i?Ce=t[25]:(Ce=(e,t)=>{let n=t===void 0?`Command failed.`:t;i(!1),qp(async()=>{await e()},n)},t[24]=i,t[25]=Ce);let we=Ce,J;t[26]===Symbol.for(`react.memo_cache_sentinel`)?(J=function(e){let t={kind:e.kind,path:e.path,lastOpenedAt:new Date().toISOString()},n=Gd(Ud(),t);Wd(n),C(n)},t[26]=J):J=t[26];let Te=J,Ee;t[27]===i?Ee=t[28]:(Ee=function(e){i(!1),Te(e),Jp(e.path)},t[27]=i,t[28]=Ee);let De=Ee,Oe=!ye&&l===``&&oe.length>0,ke=$p({searchResults:f,fallbackSearchResults:de,searchStatus:m}),Ae=!ye&&ke.length>0,je=!ye&&l!==``&&m===`loading`&&!Ae,Me;t[29]!==c||t[30]!==ye?(Me=!ye&&df(`New file`,c,[`create file`]),t[29]=c,t[30]=ye,t[31]=Me):Me=t[31];let Ne=Me,Pe;t[32]!==c||t[33]!==ye?(Pe=!ye&&df(`New folder`,c,[`create folder`]),t[32]=c,t[33]=ye,t[34]=Pe):Pe=t[34];let Fe=Pe,Ie;t[35]!==B||t[36]!==c||t[37]!==ye?(Ie=!ye&&B!==null&&df(`Open graph`,c,[`graph panel network`]),t[35]=B,t[36]=c,t[37]=ye,t[38]=Ie):Ie=t[38];let Le=Ie,ze=!ye&&a!==null&&df(`Open folder on disk`,c,[`project`]),Be=!ye&&a!==null&&df(`Switch Project`,c,[`switch project navigator projects`]),Ve=!ye&&df(`Settings`,c,[`preferences config`]),He=!ye&&df(`Install for Claude Chat & Cowork (Desktop App)`,c,[`claude desktop install cowork`]),Ue=!ye&&a!==null&&ce.length>0&&(l===``||ce.some(e=>df(`${e.name} ${e.path}`,c,[`recent project`]))),Ge=!ye&&ie!==null&&(l===``||zf.some(e=>df(`Open in ${e.displayName}`,c,[e.id,`agent handoff`]))),Ke=ve.kind===`tag-list`?mf(D,ve.query):[],qe=ve.kind===`tag-list`&&k!==`loading`&&Ke.length===0,Je=ve.kind===`tag-docs`&&P===`success`&&M.length===0,Ye=ye||Oe||Ae||je||Ne||Fe||Le||ze||Be||Ve||He||Ue||Ge,Xe;t[39]===Symbol.for(`react.memo_cache_sentinel`)?(Xe=function(e){s(`${ff}${e}`)},t[39]=Xe):Xe=t[39];let Ze=Xe,Qe=ht,$e;t[40]===Symbol.for(`react.memo_cache_sentinel`)?($e={shouldFilter:!1,className:`[&_[cmdk-input-wrapper]_svg]:h-4 [&_[cmdk-input-wrapper]_svg]:w-4 [&_[cmdk-item]_svg]:h-4 [&_[cmdk-item]_svg]:w-4`},t[40]=$e):$e=t[40];let et;t[41]===o?et=t[42]:(et=(0,Z.jsx)(g,{ref:z,value:o,onValueChange:s,placeholder:`Search files, folders, or commands`}),t[41]=o,t[42]=et);let tt;t[43]===ye?tt=t[44]:(tt=()=>{s(ye?``:ff),z.current?.focus()},t[43]=ye,t[44]=tt);let nt=ye?`border-primary/30 bg-primary/10 text-primary`:`border-border bg-transparent text-muted-foreground hover:bg-accent hover:text-accent-foreground`,rt;t[45]===nt?rt=t[46]:(rt=Y(`inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-xs font-medium transition-colors`,nt),t[45]=nt,t[46]=rt);let it,at;t[47]===Symbol.for(`react.memo_cache_sentinel`)?(it=(0,Z.jsx)(_t,{className:`size-3.5`}),at=(0,Z.jsx)(`span`,{children:`By tag`}),t[47]=it,t[48]=at):(it=t[47],at=t[48]);let ot;t[49]!==ye||t[50]!==tt||t[51]!==rt?(ot=(0,Z.jsx)(`div`,{className:`flex flex-wrap gap-1.5 border-b px-3 py-2`,children:(0,Z.jsxs)(`button`,{type:`button`,onClick:tt,"data-testid":`command-palette-filter-tag`,"data-active":ye,"aria-pressed":ye,className:rt,children:[it,at]})}),t[49]=ye,t[50]=tt,t[51]=rt,t[52]=ot):ot=t[52];let st=Re,ct;t[53]!==Ae||t[54]!==je?(ct=je&&!Ae?(0,Z.jsx)(te,{children:`Searching`}):null,t[53]=Ae,t[54]=je,t[55]=ct):ct=t[55];let lt=Ye?null:(0,Z.jsx)(te,{children:m===`error`?`Search failed.`:`No matching commands.`}),ut=ve.kind===`tag-list`?(0,Z.jsxs)(y,{heading:ve.query?`Tags matching "${ve.query}"`:`All tags`,children:[k===`loading`?(0,Z.jsx)(te,{children:`Loading tags`}):null,k===`error`?(0,Z.jsx)(te,{children:`Failed to load tags. Press Escape and re-open to retry.`}):null,qe?(0,Z.jsx)(te,{children:ve.query?`No tags match "${ve.query}".`:"No tags yet — author `#tagname` in any doc to populate the index."}):null,Ke.map(e=>(0,Z.jsxs)(L,{value:`tag ${e.name}`,onSelect:()=>Ze(e.name),"data-testid":`command-palette-tag-${e.name}`,children:[(0,Z.jsx)(_t,{}),(0,Z.jsx)(`span`,{className:`min-w-0 flex-1 truncate font-medium`,children:e.name}),(0,Z.jsxs)(`span`,{className:`ml-auto shrink-0 text-[11px] text-muted-foreground tabular-nums`,children:[e.count,` `,e.count===1?`doc`:`docs`]})]},`tag:${e.name}`))]}):null,dt;t[56]!==i||t[57]!==ve||t[58]!==Je||t[59]!==M||t[60]!==P?(dt=ve.kind===`tag-docs`?(0,Z.jsxs)(y,{heading:`Docs tagged #${ve.tagName}`,children:[P===`loading`?(0,Z.jsx)(te,{children:`Loading docs`}):null,P===`error`?(0,Z.jsx)(te,{children:`Failed to load docs. Press Escape and re-open to retry.`}):null,Je?(0,Z.jsx)(te,{children:`No docs registered under #${ve.tagName}.`}):null,M.map(e=>{let t=e.title||e.docName.split(`/`).pop()||e.docName;return(0,Z.jsxs)(L,{value:`tag-doc ${e.docName}`,onSelect:()=>{i(!1),Jp(e.docName)},"data-testid":`command-palette-tag-doc-${e.docName}`,className:`items-start`,children:[(0,Z.jsx)(ws,{className:`mt-0.5`}),(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col gap-1`,children:[(0,Z.jsx)(`span`,{className:`truncate font-medium`,children:t}),(0,Z.jsx)(`span`,{className:`truncate text-muted-foreground text-xs`,children:e.docName}),e.matchingTags.length>0&&e.matchingTags.some(e=>e!==ve.tagName)?(0,Z.jsxs)(`span`,{className:`truncate text-muted-foreground text-[11px]`,children:[`via`,` `,e.matchingTags.filter(e=>e!==ve.tagName).map(tm).join(`, `)]}):null]})]},`tag-doc:${e.docName}`)})]}):null,t[56]=i,t[57]=ve,t[58]=Je,t[59]=M,t[60]=P,t[61]=dt):dt=t[61];let ft=Oe?(0,Z.jsx)(y,{heading:`Recently opened`,children:oe.map(e=>(0,Z.jsx)(Xp,{entry:e,onSelect:()=>De(e)},Hd(e.kind,e.path)))}):null,pt;t[62]!==B||t[63]!==i||t[64]!==T||t[65]!==Ne||t[66]!==Fe||t[67]!==Le?(pt=Ne||Fe||Le?(0,Z.jsxs)(y,{heading:`Commands`,children:[Ne?(0,Z.jsxs)(L,{value:`new file create file`,onSelect:()=>{i(!1),T(`file`)},"data-testid":`command-palette-new-file`,children:[(0,Z.jsx)(mt,{}),(0,Z.jsx)(`span`,{children:`New file`})]}):null,Fe?(0,Z.jsxs)(L,{value:`new folder create folder`,onSelect:()=>{i(!1),T(`folder`)},"data-testid":`command-palette-new-folder`,children:[(0,Z.jsx)(Os,{}),(0,Z.jsx)(`span`,{children:`New folder`})]}):null,Le?(0,Z.jsxs)(L,{value:`open graph graph panel network`,onSelect:()=>{B&&(i(!1),bf(`graph`))},"data-testid":`command-palette-open-graph`,children:[(0,Z.jsx)(Gs,{}),(0,Z.jsx)(`span`,{children:`Open graph`})]}):null]}):null,t[62]=B,t[63]=i,t[64]=T,t[65]=Ne,t[66]=Fe,t[67]=Le,t[68]=pt):pt=t[68];let gt=Ge?(0,Z.jsx)(y,{heading:`Open in agent`,children:zf.filter(e=>df(`Open in ${e.displayName}`,c,[e.id,`agent handoff`])).map(e=>{let t=ee[e.id],n=t.installed===!0&&ie!==null,r=t.installed===null?`Detecting`:t.installed===!1?`Not installed`:null,a=r?`Open in ${e.displayName}, ${r}`:`Open in ${e.displayName}`;return(0,Z.jsxs)(L,{value:`open in ${e.displayName} ${e.id} agent`,disabled:!n,onSelect:()=>{!n||!ie||(i(!1),re(e.id,ie))},"data-testid":`command-palette-open-in-${e.id}`,"aria-label":a,children:[(0,Z.jsxs)(`span`,{className:`flex-1`,children:[`Open in `,e.displayName]}),r?(0,Z.jsx)(`span`,{"aria-hidden":`true`,className:`ml-auto text-muted-foreground text-xs`,children:r}):null]},e.id)})}):null,vt=ze||Be||Ve||He||Ue?(0,Z.jsxs)(y,{heading:`Project`,children:[ze&&a?(0,Z.jsxs)(L,{value:`open folder on disk project`,onSelect:()=>we(async()=>{let e=await a.dialog.openFolder();e&&await a.project.open({path:e,target:`new-window`,entryPoint:`pick-existing`})}),"data-testid":`command-palette-open-folder`,children:[(0,Z.jsx)(G,{}),(0,Z.jsx)(`span`,{children:`Open folder on disk`}),(0,Z.jsx)(u,{children:`⌘O`})]}):null,Be&&a?(0,Z.jsxs)(L,{value:`switch-project navigator projects`,onSelect:()=>we(()=>a.navigator.open(),`Failed to open Project Navigator.`),"data-testid":`command-palette-switch-project`,children:[(0,Z.jsx)(Fs,{}),(0,Z.jsx)(`span`,{children:`Switch Project`}),(0,Z.jsx)(u,{children:`⌘⇧N`})]}):null,Ve?(0,Z.jsxs)(L,{value:`settings preferences config`,onSelect:()=>{i(!1),window.location.hash!==`#settings`&&(window.location.hash=Bf)},"data-testid":`command-palette-settings`,children:[(0,Z.jsx)(rc,{}),(0,Z.jsx)(`span`,{children:`Settings`}),(0,Z.jsx)(u,{children:`⌘,`})]}):null,He?(0,Z.jsxs)(L,{value:`install claude desktop cowork app`,onSelect:()=>{i(!1),window.location.hash=`#install-claude-desktop`},"data-testid":`command-palette-install-claude-desktop`,children:[(0,Z.jsx)(Oi,{}),(0,Z.jsx)(`span`,{children:`Install for Claude Chat & Cowork (Desktop App)`})]}):null,Ue&&a?ce.filter(e=>df(`${e.name} ${e.path}`,c,[`recent project`])).slice(0,10).map(e=>(0,Z.jsxs)(L,{value:`${e.name} ${e.path} recent project`,disabled:e.missing,onSelect:()=>we(()=>a.project.open({path:e.path,target:`new-window`,entryPoint:`recents`}),`Failed to open project.`),"data-testid":`command-palette-recent-${e.path}`,children:[(0,Z.jsx)(ii,{}),(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-col`,children:[(0,Z.jsx)(`span`,{className:`truncate font-medium`,children:e.name}),(0,Z.jsxs)(`span`,{className:`truncate text-muted-foreground text-xs`,children:[e.path,e.missing?` (missing)`:``]})]})]},e.path)):null]}):null,yt=Ae?(0,Z.jsx)(y,{heading:`Search`,children:ke.map(e=>(0,Z.jsx)(Xp,{entry:e,query:l,onSelect:()=>De(e)},Hd(e.kind,e.path)))}):null,bt;t[69]!==st||t[70]!==ct||t[71]!==lt||t[72]!==ut||t[73]!==dt||t[74]!==ft||t[75]!==pt||t[76]!==gt||t[77]!==vt||t[78]!==yt?(bt=(0,Z.jsxs)(st,{ref:R,className:`subtle-scrollbar`,children:[ct,lt,ut,dt,ft,pt,gt,vt,yt]}),t[69]=st,t[70]=ct,t[71]=lt,t[72]=ut,t[73]=dt,t[74]=ft,t[75]=pt,t[76]=gt,t[77]=vt,t[78]=yt,t[79]=bt):bt=t[79];let xt;t[80]!==Qe||t[81]!==i||t[82]!==r||t[83]!==$e||t[84]!==et||t[85]!==ot||t[86]!==bt?(xt=(0,Z.jsxs)(Qe,{open:r,onOpenChange:i,title:`Workspace Command Palette`,description:`Search files, folders, and commands for the current workspace.`,className:`sm:max-w-2xl`,commandProps:$e,children:[et,ot,bt]}),t[80]=Qe,t[81]=i,t[82]=r,t[83]=$e,t[84]=et,t[85]=ot,t[86]=bt,t[87]=xt):xt=t[87];let St=w===`file`,Ct;t[88]===T?Ct=t[89]:(Ct=e=>{e||T(null)},t[88]=T,t[89]=Ct);let wt;t[90]!==ue||t[91]!==St||t[92]!==Ct?(wt=(0,Z.jsx)(Pf,{open:St,onOpenChange:Ct,kind:`file`,initialDir:ue}),t[90]=ue,t[91]=St,t[92]=Ct,t[93]=wt):wt=t[93];let Tt=w===`folder`,Et;t[94]===T?Et=t[95]:(Et=e=>{e||T(null)},t[94]=T,t[95]=Et);let Dt;t[96]!==ue||t[97]!==Tt||t[98]!==Et?(Dt=(0,Z.jsx)(Pf,{open:Tt,onOpenChange:Et,kind:`folder`,initialDir:ue}),t[96]=ue,t[97]=Tt,t[98]=Et,t[99]=Dt):Dt=t[99];let Ot;return t[100]!==xt||t[101]!==wt||t[102]!==Dt?(Ot=(0,Z.jsxs)(Z.Fragment,{children:[xt,wt,Dt]}),t[100]=xt,t[101]=wt,t[102]=Dt,t[103]=Ot):Ot=t[103],Ot}function tm(e){return`#${e}`}function nm(e){return e.name}function rm(e){return Hd(e.kind,e.path)}var im=500;function am(e,t,n){return t?`terminal`:e===null&&n?`retrying`:`hidden`}function om(e){return e===null?`no response`:e.kind===`null-collab`?`ok ui responded but server.lock has no port yet`:e.code===`network`?"network error (is `ok ui` running?)":e.code===`invalid-body`?`/api/config returned a malformed body`:`/api/config returned HTTP ${e.code}`}function sm(){let e=(0,$.c)(16),{collabUrl:t,collabTerminal:n,collabLastError:r,retryCollab:i}=We(),[a,o]=(0,Q.useState)(!1),s,c;e[0]!==n||e[1]!==t?(s=()=>{if(t!==null||n){o(!1);return}let e=setTimeout(()=>o(!0),im);return()=>clearTimeout(e)},c=[t,n],e[0]=n,e[1]=t,e[2]=s,e[3]=c):(s=e[2],c=e[3]),(0,Q.useEffect)(s,c);let l=am(t,n,a);if(l===`hidden`)return null;if(l===`terminal`){let t;e[4]===r?t=e[5]:(t=om(r),e[4]=r,e[5]=t);let n;e[6]===Symbol.for(`react.memo_cache_sentinel`)?(n=(0,Z.jsx)(`code`,{className:`bg-red-100/60 px-1 rounded`,children:`ok status`}),e[6]=n):n=e[6];let a;e[7]===Symbol.for(`react.memo_cache_sentinel`)?(a=(0,Z.jsx)(`code`,{className:`bg-red-100/60 px-1 rounded`,children:`.ok/local/last-spawn-error.log`}),e[7]=a):a=e[7];let o;e[8]===t?o=e[9]:(o=(0,Z.jsxs)(`span`,{children:[`Couldn't reach collab server — `,t,`. Try`,` `,n,` or check`,` `,a,`.`]}),e[8]=t,e[9]=o);let s;e[10]===i?s=e[11]:(s=(0,Z.jsx)(`button`,{type:`button`,onClick:i,className:`bg-red-950 text-red-50 px-2 py-0.5 rounded text-xs font-medium hover:bg-red-900`,children:`Retry`}),e[10]=i,e[11]=s);let c;return e[12]!==o||e[13]!==s?(c=(0,Z.jsxs)(`div`,{role:`alert`,"aria-live":`assertive`,className:`fixed top-0 inset-x-0 z-50 bg-red-500/95 text-red-950 text-sm text-center py-2 px-4 shadow-md flex items-center justify-center gap-3 flex-wrap`,children:[o,s]}),e[12]=o,e[13]=s,e[14]=c):c=e[14],c}let u;return e[15]===Symbol.for(`react.memo_cache_sentinel`)?(u=(0,Z.jsx)(`div`,{role:`status`,"aria-live":`polite`,className:`fixed top-0 inset-x-0 z-50 bg-amber-500/95 text-amber-950 text-sm text-center py-2 px-4 shadow-md`,children:`Connecting — waiting for collab server`}),e[15]=u):u=e[15],u}async function cm(e){let t=await fetch(`/api/tags/${encodeURIComponent(e)}`);if(!t.ok){let e=await t.json().catch(()=>null);throw Error(Bn(e)??`Server error: ${t.status} ${t.statusText}`)}return(await t.json()).docs??[]}function lm(){let e=(0,$.c)(15),[t,n]=(0,Q.useState)(!1),[r,i]=(0,Q.useState)(null),a;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(a={kind:`idle`},e[0]=a):a=e[0];let[o,s]=(0,Q.useState)(a),c=(0,Q.useRef)(0),l,u;e[1]===Symbol.for(`react.memo_cache_sentinel`)?(l=()=>{let e=function(e){let t=e.detail;if(!t||typeof t.value!=`string`)return;let r=c.current+=1;i(t.value),n(!0),s({kind:`loading`}),cm(t.value).then(e=>{c.current===r&&s({kind:`ready`,docs:e})}).catch(e=>{c.current===r&&s({kind:`error`,message:e instanceof Error?e.message:String(e)})})};return document.addEventListener(Ve,e),()=>document.removeEventListener(Ve,e)},u=[],e[1]=l,e[2]=u):(l=e[1],u=e[2]),(0,Q.useEffect)(l,u);let d;e[3]===Symbol.for(`react.memo_cache_sentinel`)?(d=function(e){n(!1),window.location.assign(er(e))},e[3]=d):d=e[3];let f=d,p=r??``,m;e[4]===p?m=e[5]:(m=(0,Z.jsx)(qa,{children:(0,Z.jsxs)(Ra,{children:[`Documents tagged `,(0,Z.jsxs)(`span`,{className:`font-mono`,children:[`#`,p]})]})}),e[4]=p,e[5]=m);let h=r??``,g;e[6]!==o||e[7]!==h?(g=(0,Z.jsx)(Wa,{children:(0,Z.jsx)(um,{fetchState:o,tag:h,onSelectDoc:f})}),e[6]=o,e[7]=h,e[8]=g):g=e[8];let _;e[9]!==m||e[10]!==g?(_=(0,Z.jsxs)(Va,{children:[m,g]}),e[9]=m,e[10]=g,e[11]=_):_=e[11];let v;return e[12]!==t||e[13]!==_?(v=(0,Z.jsx)(Ja,{open:t,onOpenChange:n,children:_}),e[12]=t,e[13]=_,e[14]=v):v=e[14],v}function um(e){let t=(0,$.c)(12),{fetchState:n,tag:r,onSelectDoc:i}=e;if(n.kind===`idle`||n.kind===`loading`){let e;return t[0]===Symbol.for(`react.memo_cache_sentinel`)?(e=(0,Z.jsx)(`p`,{className:`text-muted-foreground text-sm`,"data-testid":`tag-dialog-loading`,children:`Loading`}),t[0]=e):e=t[0],e}if(n.kind===`error`){let e;return t[1]===n.message?e=t[2]:(e=(0,Z.jsx)(`p`,{className:`text-destructive text-sm`,"data-testid":`tag-dialog-error`,children:n.message}),t[1]=n.message,t[2]=e),e}if(n.docs.length===0){let e;return t[3]===r?e=t[4]:(e=(0,Z.jsxs)(`p`,{className:`text-muted-foreground text-sm`,"data-testid":`tag-dialog-empty`,children:[`Only the current document uses `,(0,Z.jsxs)(`span`,{className:`font-mono`,children:[`#`,r]}),`.`]}),t[3]=r,t[4]=e),e}let a;if(t[5]!==n.docs||t[6]!==i){let e;t[8]===i?e=t[9]:(e=e=>{let t=e.matchingTags??[];return(0,Z.jsx)(`li`,{children:(0,Z.jsxs)(`button`,{type:`button`,className:`w-full rounded-md px-2 py-1.5 text-left text-sm hover:bg-muted focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring`,onClick:()=>i(e.docName),"data-testid":`tag-dialog-row`,children:[(0,Z.jsx)(`span`,{className:`block truncate font-medium`,children:e.title}),e.docName===e.title?null:(0,Z.jsx)(`span`,{className:`block truncate text-xs text-muted-foreground`,children:e.docName}),t.length>0?(0,Z.jsx)(`span`,{className:`mt-1 flex flex-wrap items-center gap-1`,"data-testid":`tag-dialog-row-matches`,children:t.map(dm)}):null]})},e.docName)},t[8]=i,t[9]=e),a=n.docs.map(e),t[5]=n.docs,t[6]=i,t[7]=a}else a=t[7];let o;return t[10]===a?o=t[11]:(o=(0,Z.jsx)(`ul`,{className:`flex flex-col gap-1`,"data-testid":`tag-dialog-list`,children:a}),t[10]=a,t[11]=o),o}function dm(e){return(0,Z.jsxs)(`span`,{"data-testid":`tag-dialog-row-match`,"data-tag":e,className:`tag pointer-events-none text-xs`,children:[`#`,e]},e)}var fm=`raw-mdx-nav`,pm=`ok-editor-mode-v1`,mm=[`wysiwyg`,`source`],hm=`wysiwyg`;function gm(e){return mm.includes(e)}function _m(e=localStorage){try{let t=e.getItem(pm);if(t===null)return hm;if(gm(t))return t;console.warn(`[editor-mode] invalid persisted value, falling back to default`,{raw:t})}catch{}return hm}function vm(e=window,t=localStorage){let n=e.__OK_EDITOR_MODE__;return gm(n)?n:_m(t)}function ym(e,t=localStorage){try{return t.setItem(pm,e),!0}catch(e){return console.warn(`[editor-mode] persist failed`,e),!1}}function bm(){let e=(0,$.c)(3),[t,n]=(0,Q.useState)(vm),r;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(r=function(e){n(e),ym(e)},e[0]=r):r=e[0];let i=r,a;return e[1]===t?a=e[2]:(a=[t,i],e[1]=t,e[2]=a),a}function xm(e){let t=(0,$.c)(21),{open:n,onResolved:r}=e,i=Vi(),a;t[0]!==r||t[1]!==i?(a=function(e){if(i===null){Xa.error(`Sync settings not yet loaded — try again in a moment`);return}let t=i(e);if(!t.ok){Xa.error(`Could not ${e?`enable sync`:`save sync preference`}: ${t.error}`);return}r()},t[0]=r,t[1]=i,t[2]=a):a=t[2];let o=a,s;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(s=(0,Z.jsx)(qa,{children:(0,Z.jsx)(Ai,{})}),t[3]=s):s=t[3];let c;t[4]===Symbol.for(`react.memo_cache_sentinel`)?(c=(0,Z.jsx)(Wa,{children:(0,Z.jsx)(li,{})}),t[4]=c):c=t[4];let l;t[5]===o?l=t[6]:(l=()=>o(!1),t[5]=o,t[6]=l);let u=i===null,d;t[7]!==l||t[8]!==u?(d=(0,Z.jsx)(X,{variant:`ghost`,className:`uppercase font-mono`,onClick:l,disabled:u,children:`Keep disabled`}),t[7]=l,t[8]=u,t[9]=d):d=t[9];let f;t[10]===o?f=t[11]:(f=()=>o(!0),t[10]=o,t[11]=f);let p=i===null,m;t[12]!==f||t[13]!==p?(m=(0,Z.jsx)(X,{onClick:f,disabled:p,children:`Enable auto-sync`}),t[12]=f,t[13]=p,t[14]=m):m=t[14];let h;t[15]!==d||t[16]!==m?(h=(0,Z.jsxs)(Va,{className:`sm:max-w-lg`,showCloseButton:!1,children:[s,c,(0,Z.jsxs)(Ga,{children:[d,m]})]}),t[15]=d,t[16]=m,t[17]=h):h=t[17];let g;return t[18]!==n||t[19]!==h?(g=(0,Z.jsx)(Ja,{open:n,onOpenChange:Sm,children:h}),t[18]=n,t[19]=h,t[20]=g):g=t[20],g}function Sm(){}function Cm(e){let t=(0,$.c)(9),{onOpenResolver:n}=e,r=da();if(!r||r.state!==`conflict`)return null;let i=r.conflictCount,a=i>0?`${i} page${i===1?``:`s`}`:`Some pages`,o;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(o=(0,Z.jsx)(Dn,{className:`size-4 shrink-0`}),t[0]=o):o=t[0];let s=i===1?`has`:`have`,c;t[1]!==a||t[2]!==s?(c=(0,Z.jsxs)(`span`,{className:`flex-1`,children:[a,` `,s,` conflicting changes.`]}),t[1]=a,t[2]=s,t[3]=c):c=t[3];let l;t[4]===n?l=t[5]:(l=(0,Z.jsx)(X,{variant:`outline`,size:`xs`,className:`shrink-0 border-amber-400 dark:border-amber-700 text-amber-800 dark:text-amber-300 hover:bg-amber-100 dark:hover:bg-amber-900/50`,onClick:n,children:`Review and resolve`}),t[4]=n,t[5]=l);let u;return t[6]!==c||t[7]!==l?(u=(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-2 text-sm border-b bg-amber-50 dark:bg-amber-950/30 text-amber-800 dark:text-amber-300 shrink-0`,children:[o,c,l]}),t[6]=c,t[7]=l,t[8]=u):u=t[8],u}var wm=class e{constructor(e,t,n,r){this.fromA=e,this.toA=t,this.fromB=n,this.toB=r}offset(t,n=t){return new e(this.fromA+t,this.toA+t,this.fromB+n,this.toB+n)}};function Tm(e,t,n,r,i,a){if(e==r)return[];let o=Fm(e,t,n,r,i,a),s=Im(e,t+o,n,r,i+o,a);t+=o,n-=s,i+=o,a-=s;let c=n-t,l=a-i;if(!c||!l)return[new wm(t,n,i,a)];if(c>l){let o=e.slice(t,n).indexOf(r.slice(i,a));if(o>-1)return[new wm(t,t+o,i,i),new wm(t+o+l,n,a,a)]}else if(l>c){let o=r.slice(i,a).indexOf(e.slice(t,n));if(o>-1)return[new wm(t,t,i,i+o),new wm(n,n,i+o+c,a)]}if(c==1||l==1)return[new wm(t,n,i,a)];let u=Rm(e,t,n,r,i,a);if(u){let[o,s,c]=u;return Tm(e,t,o,r,i,s).concat(Tm(e,o+c,n,r,s+c,a))}return km(e,t,n,r,i,a)}var Em=1e9,Dm=0,Om=!1;function km(e,t,n,r,i,a){let o=n-t,s=a-i;if(Em<1e9&&Math.min(o,s)>Em*16||Dm>0&&Date.now()>Dm)return Math.min(o,s)>Em*64?[new wm(t,n,i,a)]:zm(e,t,n,r,i,a);let c=Math.ceil((o+s)/2);jm.reset(c),Mm.reset(c);let l=(n,a)=>e.charCodeAt(t+n)==r.charCodeAt(i+a),u=(t,i)=>e.charCodeAt(n-t-1)==r.charCodeAt(a-i-1),d=(o-s)%2==0?null:Mm,f=d?null:jm;for(let p=0;p<c;p++){if(p>Em||Dm>0&&!(p&63)&&Date.now()>Dm)return zm(e,t,n,r,i,a);let m=jm.advance(p,o,s,c,d,!1,l)||Mm.advance(p,o,s,c,f,!0,u);if(m)return Nm(e,t,n,t+m[0],r,i,a,i+m[1])}return[new wm(t,n,i,a)]}var Am=class{constructor(){this.vec=[]}reset(e){this.len=e<<1;for(let e=0;e<this.len;e++)this.vec[e]=-1;this.vec[e+1]=0,this.start=this.end=0}advance(e,t,n,r,i,a,o){for(let s=-e+this.start;s<=e-this.end;s+=2){let c=r+s,l=s==-e||s!=e&&this.vec[c-1]<this.vec[c+1]?this.vec[c+1]:this.vec[c-1]+1,u=l-s;for(;l<t&&u<n&&o(l,u);)l++,u++;if(this.vec[c]=l,l>t)this.end+=2;else if(u>n)this.start+=2;else if(i){let e=r+(t-n)-s;if(e>=0&&e<this.len&&i.vec[e]!=-1)if(a){let n=i.vec[e];if(n>=t-l)return[n,r+n-e]}else{let n=t-i.vec[e];if(l>=n)return[l,u]}}}return null}},jm=new Am,Mm=new Am;function Nm(e,t,n,r,i,a,o,s){let c=!1;return!eh(e,r)&&++r==n&&(c=!0),!eh(i,s)&&++s==o&&(c=!0),c?[new wm(t,n,a,o)]:Tm(e,t,r,i,a,s).concat(Tm(e,r,n,i,s,o))}function Pm(e,t){let n=1,r=Math.min(e,t);for(;n<r;)n<<=1;return n}function Fm(e,t,n,r,i,a){if(t==n||t==a||e.charCodeAt(t)!=r.charCodeAt(i))return 0;let o=Pm(n-t,a-i);for(let s=t,c=i;;){let i=s+o,l=c+o;if(i>n||l>a||e.slice(s,i)!=r.slice(c,l)){if(o==1)return s-t-+!eh(e,s);o>>=1}else if(i==n||l==a)return i-t;else s=i,c=l}}function Im(e,t,n,r,i,a){if(t==n||i==a||e.charCodeAt(n-1)!=r.charCodeAt(a-1))return 0;let o=Pm(n-t,a-i);for(let s=n,c=a;;){let a=s-o,l=c-o;if(a<t||l<i||e.slice(a,s)!=r.slice(l,c)){if(o==1)return n-s-+!eh(e,s);o>>=1}else if(a==t||l==i)return n-a;else s=a,c=l}}function Lm(e,t,n,r,i,a,o,s){let c=r.slice(i,a),l=null;for(;;){if(l||o<s)return l;for(let s=t+o;;){eh(e,s)||s++;let u=s+o;if(eh(e,u)||(u+=u==s+1?1:-1),u>=n)break;let d=e.slice(s,u),f=-1;for(;(f=c.indexOf(d,f+1))!=-1;){let o=Fm(e,u,n,r,i+f+d.length,a),c=Im(e,t,s,r,i,i+f),p=d.length+o+c;(!l||l[2]<p)&&(l=[s-c,i+f-c,p])}s=u}if(s<0)return l;o>>=1}}function Rm(e,t,n,r,i,a){let o=n-t,s=a-i;if(o<s){let o=Rm(r,i,a,e,t,n);return o&&[o[1],o[0],o[2]]}return o<4||s*2<o?null:Lm(e,t,n,r,i,a,Math.floor(o/4),-1)}function zm(e,t,n,r,i,a){Om=!0;let o=n-t,s=a-i,c;if(o<s){let s=Lm(r,i,a,e,t,n,Math.floor(o/6),50);c=s&&[s[1],s[0],s[2]]}else c=Lm(e,t,n,r,i,a,Math.floor(s/6),50);if(!c)return[new wm(t,n,i,a)];let[l,u,d]=c;return Tm(e,t,l,r,i,u).concat(Tm(e,l+d,n,r,u+d,a))}function Bm(e,t){for(let n=1;n<e.length;n++){let r=e[n-1],i=e[n];r.toA>i.fromA-t&&r.toB>i.fromB-t&&(e[n-1]=new wm(r.fromA,i.toA,r.fromB,i.toB),e.splice(n--,1))}}function Vm(e,t,n){for(;;){Bm(n,1);let r=!1;for(let i=0;i<n.length;i++){let a=n[i],o,s;(o=Fm(e,a.fromA,a.toA,t,a.fromB,a.toB))&&(a=n[i]=new wm(a.fromA+o,a.toA,a.fromB+o,a.toB)),(s=Im(e,a.fromA,a.toA,t,a.fromB,a.toB))&&(a=n[i]=new wm(a.fromA,a.toA-s,a.fromB,a.toB-s));let c=a.toA-a.fromA,l=a.toB-a.fromB;if(c&&l)continue;let u=a.fromA-(i?n[i-1].toA:0),d=(i<n.length-1?n[i+1].fromA:e.length)-a.toA;if(!u||!d)continue;let f=c?e.slice(a.fromA,a.toA):t.slice(a.fromB,a.toB);u<=f.length&&e.slice(a.fromA-u,a.fromA)==f.slice(f.length-u)?(n[i]=new wm(a.fromA-u,a.toA-u,a.fromB-u,a.toB-u),r=!0):d<=f.length&&e.slice(a.toA,a.toA+d)==f.slice(0,d)&&(n[i]=new wm(a.fromA+d,a.toA+d,a.fromB+d,a.toB+d),r=!0)}if(!r)break}return n}function Hm(e,t,n){for(let r=0,i=0;i<e.length;i++){let a=e[i],o=a.toA-a.fromA,s=a.toB-a.fromB;if(o&&s||o>3||s>3){let c=i==e.length-1?t.length:e[i+1].fromA,l=a.fromA-r,u=c-a.toA,d=Ym(t,a.fromA,l),f=Jm(t,a.toA,u),p=a.fromA-d,m=f-a.toA;if((!o||!s)&&p&&m){let l=Math.max(o,s),[u,h,g]=o?[t,a.fromA,a.toA]:[n,a.fromB,a.toB];l>p&&t.slice(d,a.fromA)==u.slice(g-p,g)?(a=e[i]=new wm(d,d+o,a.fromB-p,a.toB-p),d=a.fromA,f=Jm(t,a.toA,c-a.toA)):l>m&&t.slice(a.toA,f)==u.slice(h,h+m)&&(a=e[i]=new wm(f-o,f,a.fromB+m,a.toB+m),f=a.toA,d=Ym(t,a.fromA,a.fromA-r)),p=a.fromA-d,m=f-a.toA}if(p||m)a=e[i]=new wm(a.fromA-p,a.toA+m,a.fromB-p,a.toB+m);else if(!o){let t=Zm(n,a.fromB,a.toB),r,o=t<0?-1:Xm(n,a.toB,a.fromB);t>-1&&(r=t-a.fromB)<=u&&n.slice(a.fromB,t)==n.slice(a.toB,a.toB+r)?a=e[i]=a.offset(r):o>-1&&(r=a.toB-o)<=l&&n.slice(a.fromB-r,a.fromB)==n.slice(o,a.toB)&&(a=e[i]=a.offset(-r))}else if(!s){let n=Zm(t,a.fromA,a.toA),r,o=n<0?-1:Xm(t,a.toA,a.fromA);n>-1&&(r=n-a.fromA)<=u&&t.slice(a.fromA,n)==t.slice(a.toA,a.toA+r)?a=e[i]=a.offset(r):o>-1&&(r=a.toA-o)<=l&&t.slice(a.fromA-r,a.fromA)==t.slice(o,a.toA)&&(a=e[i]=a.offset(-r))}}r=a.toA}return Bm(e,3),e}var Um;try{Um=RegExp(`[\\p{Alphabetic}\\p{Number}]`,`u`)}catch{}function Wm(e){return e>48&&e<58||e>64&&e<91||e>96&&e<123}function Gm(e,t){if(t==e.length)return 0;let n=e.charCodeAt(t);return n<192?+!!Wm(n):Um?!Qm(n)||t==e.length-1?+!!Um.test(String.fromCharCode(n)):Um.test(e.slice(t,t+2))?2:0:0}function Km(e,t){if(!t)return 0;let n=e.charCodeAt(t-1);return n<192?+!!Wm(n):Um?!$m(n)||t==1?+!!Um.test(String.fromCharCode(n)):Um.test(e.slice(t-2,t))?2:0:0}var qm=8;function Jm(e,t,n){if(t==e.length||!Km(e,t))return t;for(let r=t,i=t+n,a=0;a<qm;a++){let t=Gm(e,r);if(!t||r+t>i)return r;r+=t}return t}function Ym(e,t,n){if(!t||!Gm(e,t))return t;for(let r=t,i=t-n,a=0;a<qm;a++){let t=Km(e,r);if(!t||r-t<i)return r;r-=t}return t}function Xm(e,t,n){for(;t!=n;t--)if(e.charCodeAt(t-1)==10)return t;return-1}function Zm(e,t,n){for(;t!=n;t++)if(e.charCodeAt(t)==10)return t;return-1}var Qm=e=>e>=55296&&e<=56319,$m=e=>e>=56320&&e<=57343;function eh(e,t){return!t||t==e.length||!Qm(e.charCodeAt(t-1))||!$m(e.charCodeAt(t))}function th(e,t,n){let r=n?.override;return r?r(e,t):(Em=(n?.scanLimit??1e9)>>1,Dm=n?.timeout?Date.now()+n.timeout:0,Om=!1,Vm(e,t,Tm(e,0,e.length,t,0,t.length)))}function nh(){return!Om}function rh(e,t,n){return Hm(th(e,t,n),e,t)}var ih=To.define({combine:e=>e[0]}),ah=Eo.define(),oh=To.define(),sh=bo.define({create(e){return null},update(e,t){for(let n of t.effects)n.is(ah)&&(e=n.value);for(let n of t.state.facet(oh))e=n(e,t);return e}});function ch(e){let t=e.field(sh,!1);if(!t)return null;let n=e.facet(ih);return{chunks:t,side:n?n.side:null}}var lh=class e{constructor(e,t,n,r,i,a=!0){this.changes=e,this.fromA=t,this.toA=n,this.fromB=r,this.toB=i,this.precise=a}offset(t,n){return t||n?new e(this.changes,this.fromA+t,this.toA+t,this.fromB+n,this.toB+n,this.precise):this}get endA(){return Math.max(this.fromA,this.toA-1)}get endB(){return Math.max(this.fromB,this.toB-1)}static build(e,t,n){return fh(rh(e.toString(),t.toString(),n),e,t,0,0,nh())}static updateA(e,t,n,r,i){return gh(hh(e,r,!0,n.length),e,t,n,i)}static updateB(e,t,n,r,i){return gh(hh(e,r,!1,t.length),e,t,n,i)}};function uh(e,t,n,r){let i=n.lineAt(e),a=r.lineAt(t);return i.to==e&&a.to==t&&e<n.length&&t<r.length?[e+1,t+1]:[i.from,a.from]}function dh(e,t,n,r){let i=n.lineAt(e),a=r.lineAt(t);return i.from==e&&a.from==t?[e,t]:[i.to+1,a.to+1]}function fh(e,t,n,r,i,a){let o=[];for(let s=0;s<e.length;s++){let c=e[s],[l,u]=uh(c.fromA+r,c.fromB+i,t,n),[d,f]=dh(c.toA+r,c.toB+i,t,n),p=[c.offset(-l+r,-u+i)];for(;s<e.length-1;){let a=e[s+1],[o,c]=uh(a.fromA+r,a.fromB+i,t,n);if(o>d+1&&c>f+1)break;p.push(a.offset(-l+r,-u+i)),[d,f]=dh(a.toA+r,a.toB+i,t,n),s++}o.push(new lh(p,l,Math.max(l,d),u,Math.max(u,f),a))}return o}var ph=1e3;function mh(e,t,n,r){let i=0,a=e.length;for(;;){if(i==a){let r=0,a=0;i&&({toA:r,toB:a}=e[i-1]);let o=t-(n?r:a);return[r+o,a+o]}let o=i+a>>1,s=e[o],[c,l]=n?[s.fromA,s.toA]:[s.fromB,s.toB];if(c>t)a=o;else if(l<=t)i=o+1;else return r?[s.fromA,s.fromB]:[s.toA,s.toB]}}function hh(e,t,n,r){let i=[];return t.iterChangedRanges((a,o,s,c)=>{let l=0,u=n?t.length:r,d=0,f=n?r:t.length;a>ph&&([l,d]=mh(e,a-ph,n,!0)),o<t.length-ph&&([u,f]=mh(e,o+ph,n,!1));let p=c-s-(o-a),m,[h,g]=n?[p,0]:[0,p];i.length&&(m=i[i.length-1]).toA>=l?i[i.length-1]={fromA:m.fromA,fromB:m.fromB,toA:u,toB:f,diffA:m.diffA+h,diffB:m.diffB+g}:i.push({fromA:l,toA:u,fromB:d,toB:f,diffA:h,diffB:g})}),i}function gh(e,t,n,r,i){if(!e.length)return t;let a=[];for(let o=0,s=0,c=0,l=0;;o++){let u=o==e.length?null:e[o],d=u?u.fromA+s:n.length,f=u?u.fromB+c:r.length;for(;l<t.length;){let e=t[l];if(u&&(e.toA+s>d||e.toB+c>f))break;a.push(e.offset(s,c)),l++}if(!u)break;let p=u.toA+s+u.diffA,m=u.toB+c+u.diffB,h=rh(n.sliceString(d,p),r.sliceString(f,m),i);for(let e of fh(h,n,r,d,f,nh()))a.push(e);for(s+=u.diffA,c+=u.diffB;l<t.length;){let e=t[l];if(e.fromA+s>p&&e.fromB+c>m)break;l++}}return a}var _h={scanLimit:500},vh=Do.fromClass(class{constructor(e){({deco:this.deco,gutter:this.gutter}=Oh(e))}update(e){(e.docChanged||e.viewportChanged||bh(e.startState,e.state)||xh(e.startState,e.state))&&({deco:this.deco,gutter:this.gutter}=Oh(e.view))}},{decorations:e=>e.deco}),yh=_o.low(jo({class:`cm-changeGutter`,markers:e=>e.plugin(vh)?.gutter||No.empty}));function bh(e,t){return e.field(sh,!1)!=t.field(sh,!1)}function xh(e,t){return e.facet(ih)!=t.facet(ih)}var Sh=Co.line({class:`cm-changedLine`}),Ch=Co.mark({class:`cm-changedText`}),wh=Co.mark({tagName:`ins`,class:`cm-insertedLine`}),Th=Co.mark({tagName:`del`,class:`cm-deletedLine`}),Eh=new class extends Ao{constructor(){super(...arguments),this.elementClass=`cm-changedLineGutter`}};function Dh(e,t,n,r,i,a){let o=n?e.fromA:e.fromB,s=n?e.toA:e.toB,c=0;if(o!=s){i.add(o,o,Sh),i.add(o,s,n?Th:wh),a&&a.add(o,o,Eh);for(let l=t.iterRange(o,s-1),u=o;!l.next().done;){if(l.lineBreak){u++,i.add(u,u,Sh),a&&a.add(u,u,Eh);continue}let t=u+l.value.length;if(r)for(;c<e.changes.length;){let r=e.changes[c],a=o+(n?r.fromA:r.fromB),s=o+(n?r.toA:r.toB),l=Math.max(u,a),d=Math.min(t,s);if(l<d&&i.add(l,d,Ch),s<t)c++;else break}u=t}}}function Oh(e){let t=e.state.field(sh),{side:n,highlightChanges:r,markGutter:i,overrideChunk:a}=e.state.facet(ih),o=n==`a`,s=new wo,c=i?new wo:null,{from:l,to:u}=e.viewport;for(let n of t){if((o?n.fromA:n.fromB)>=u)break;(o?n.toA:n.toB)>l&&(!a||!a(e.state,n,s,c))&&Dh(n,e.state.doc,o,r,s,c)}return{deco:s.finish(),gutter:c&&c.finish()}}var kh=class extends go{constructor(e){super(),this.height=e}eq(e){return this.height==e.height}toDOM(){let e=document.createElement(`div`);return e.className=`cm-mergeSpacer`,e.style.height=this.height+`px`,e}updateDOM(e){return e.style.height=this.height+`px`,!0}get estimatedHeight(){return this.height}ignoreEvent(){return!1}},Ah=Eo.define({map:(e,t)=>e.map(t)}),jh=bo.define({create:()=>Co.none,update:(e,t)=>{for(let e of t.effects)if(e.is(Ah))return e.value;return e.map(t.changes)},provide:e=>ko.decorations.from(e)}),Mh=.01;function Nh(e,t){if(e.size!=t.size)return!1;let n=e.iter(),r=t.iter();for(;n.value;){if(n.from!=r.from||Math.abs(n.value.spec.widget.height-r.value.spec.widget.height)>1)return!1;n.next(),r.next()}return!0}function Ph(e,t,n){let r=new wo,i=new wo,a=e.state.field(jh).iter(),o=t.state.field(jh).iter(),s=0,c=0,l=0,u=0,d=e.viewport,f=t.viewport;for(let p=0;;p++){let m=p<n.length?n[p]:null,h=m?m.fromA:e.state.doc.length,g=m?m.fromB:t.state.doc.length;if(s<h){let n=e.lineBlockAt(s).top+l-(t.lineBlockAt(c).top+u);n<-Mh?(l-=n,r.add(s,s,Co.widget({widget:new kh(-n),block:!0,side:-1}))):n>Mh&&(u+=n,i.add(c,c,Co.widget({widget:new kh(n),block:!0,side:-1})))}if(h>s+1e3&&s<d.from&&h>d.from&&c<f.from&&g>f.from){let e=Math.min(d.from-s,f.from-c);s+=e,c+=e,p--}else if(m)s=m.toA,c=m.toB;else break;for(;a.value&&a.from<s;)l-=a.value.spec.widget.height,a.next();for(;o.value&&o.from<c;)u-=o.value.spec.widget.height,o.next()}for(;a.value;)l-=a.value.spec.widget.height,a.next();for(;o.value;)u-=o.value.spec.widget.height,o.next();let p=e.contentHeight+l-(t.contentHeight+u);p<Mh?r.add(e.state.doc.length,e.state.doc.length,Co.widget({widget:new kh(-p),block:!0,side:1})):p>Mh&&i.add(t.state.doc.length,t.state.doc.length,Co.widget({widget:new kh(p),block:!0,side:1}));let m=r.finish(),h=i.finish();Nh(m,e.state.field(jh))||e.dispatch({effects:Ah.of(m)}),Nh(h,t.state.field(jh))||t.dispatch({effects:Ah.of(h)})}var Fh=Eo.define({map:(e,t)=>t.mapPos(e)}),Ih=class extends go{constructor(e){super(),this.lines=e}eq(e){return this.lines==e.lines}toDOM(e){let t=document.createElement(`div`);return t.className=`cm-collapsedLines`,t.textContent=e.state.phrase(`$ unchanged lines`,this.lines),t.addEventListener(`click`,t=>{let n=e.posAtDOM(t.target);e.dispatch({effects:Fh.of(n)});let{side:r,sibling:i}=e.state.facet(ih);i&&i().dispatch({effects:Fh.of(Lh(n,e.state.field(sh),r==`a`))})}),t}ignoreEvent(e){return e instanceof MouseEvent}get estimatedHeight(){return 27}get type(){return`collapsed-unchanged-code`}};function Lh(e,t,n){let r=0,i=0;for(let a=0;;a++){let o=a<t.length?t[a]:null;if(!o||(n?o.fromA:o.fromB)>=e)return i+(e-r);[r,i]=n?[o.toA,o.toB]:[o.toB,o.toA]}}var Rh=bo.define({create(e){return Co.none},update(e,t){e=e.map(t.changes);for(let n of t.effects)n.is(Fh)&&(e=e.update({filter:e=>e!=n.value}));return e},provide:e=>ko.decorations.from(e)});function zh({margin:e=3,minSize:t=4}){return Rh.init(n=>Bh(n,e,t))}function Bh(e,t,n){let r=new wo,i=e.facet(ih).side==`a`,a=e.field(sh),o=1;for(let s=0;;s++){let c=s<a.length?a[s]:null,l=s?o+t:1,u=c?e.doc.lineAt(i?c.fromA:c.fromB).number-1-t:e.doc.lines,d=u-l+1;if(d>=n&&r.add(e.doc.line(l).from,e.doc.line(u).to,Co.replace({widget:new Ih(d),block:!0})),!c)break;o=e.doc.lineAt(Math.min(e.doc.length,i?c.toA:c.toB)).number}return r.finish()}var Vh=ko.styleModule.of(new Mo({".cm-mergeView":{overflowY:`auto`},".cm-mergeViewEditors":{display:`flex`,alignItems:`stretch`},".cm-mergeViewEditor":{flexGrow:1,flexBasis:0,overflow:`hidden`},".cm-merge-revert":{width:`1.6em`,flexGrow:0,flexShrink:0,position:`relative`},".cm-merge-revert button":{position:`absolute`,display:`block`,width:`100%`,boxSizing:`border-box`,textAlign:`center`,background:`none`,border:`none`,font:`inherit`,cursor:`pointer`}})),Hh=ko.baseTheme({".cm-mergeView & .cm-scroller, .cm-mergeView &":{height:`auto !important`,overflowY:`visible !important`},"&.cm-merge-a .cm-changedLine, .cm-deletedChunk":{backgroundColor:`rgba(160, 128, 100, .08)`},"&.cm-merge-b .cm-changedLine, .cm-inlineChangedLine":{backgroundColor:`rgba(100, 160, 128, .08)`},"&light.cm-merge-a .cm-changedText, &light .cm-deletedChunk .cm-deletedText":{background:`linear-gradient(#ee443366, #ee443366) bottom/100% 2px no-repeat`},"&dark.cm-merge-a .cm-changedText, &dark .cm-deletedChunk .cm-deletedText":{background:`linear-gradient(#ffaa9966, #ffaa9966) bottom/100% 2px no-repeat`},"&light.cm-merge-b .cm-changedText":{background:`linear-gradient(#22bb22aa, #22bb22aa) bottom/100% 2px no-repeat`},"&dark.cm-merge-b .cm-changedText":{background:`linear-gradient(#88ff88aa, #88ff88aa) bottom/100% 2px no-repeat`},"&.cm-merge-b .cm-deletedText":{background:`#ff000033`},".cm-insertedLine, .cm-deletedLine, .cm-deletedLine del":{textDecoration:`none`},".cm-deletedChunk":{paddingLeft:`6px`,"& .cm-chunkButtons":{position:`absolute`,insetInlineEnd:`5px`},"& button":{border:`none`,cursor:`pointer`,color:`white`,margin:`0 2px`,borderRadius:`3px`,"&[name=accept]":{background:`#2a2`},"&[name=reject]":{background:`#d43`}}},".cm-collapsedLines":{padding:`5px 5px 5px 10px`,cursor:`pointer`,"&:before":{content:`"⦚"`,marginInlineEnd:`7px`},"&:after":{content:`"⦚"`,marginInlineStart:`7px`}},"&light .cm-collapsedLines":{color:`#444`,background:`linear-gradient(to bottom, transparent 0, #f3f3f3 30%, #f3f3f3 70%, transparent 100%)`},"&dark .cm-collapsedLines":{color:`#ddd`,background:`linear-gradient(to bottom, transparent 0, #222 30%, #222 70%, transparent 100%)`},".cm-changeGutter":{width:`3px`,paddingLeft:`1px`},"&light.cm-merge-a .cm-changedLineGutter, &light .cm-deletedLineGutter":{background:`#e43`},"&dark.cm-merge-a .cm-changedLineGutter, &dark .cm-deletedLineGutter":{background:`#fa9`},"&light.cm-merge-b .cm-changedLineGutter":{background:`#2b2`},"&dark.cm-merge-b .cm-changedLineGutter":{background:`#8f8`},".cm-inlineChangedLineGutter":{background:`#75d`}}),Uh=new Oo,Wh=new Oo,Gh=class{constructor(e){this.revertDOM=null,this.revertToA=!1,this.revertToLeft=!1,this.measuring=-1,this.diffConf=e.diffConfig||_h;let t=[_o.low(vh),Hh,Vh,jh,ko.updateListener.of(e=>{this.measuring<0&&(e.heightChanged||e.viewportChanged)&&!e.transactions.some(e=>e.effects.some(e=>e.is(Ah)))&&this.measure()})],n=[ih.of({side:`a`,sibling:()=>this.b,highlightChanges:e.highlightChanges!==!1,markGutter:e.gutter!==!1})];e.gutter!==!1&&n.push(yh);let r=yo.create({doc:e.a.doc,selection:e.a.selection,extensions:[e.a.extensions||[],ko.editorAttributes.of({class:`cm-merge-a`}),Wh.of(n),t]}),i=[ih.of({side:`b`,sibling:()=>this.a,highlightChanges:e.highlightChanges!==!1,markGutter:e.gutter!==!1})];e.gutter!==!1&&i.push(yh);let a=yo.create({doc:e.b.doc,selection:e.b.selection,extensions:[e.b.extensions||[],ko.editorAttributes.of({class:`cm-merge-b`}),Wh.of(i),t]});this.chunks=lh.build(r.doc,a.doc,this.diffConf);let o=[sh.init(()=>this.chunks),Uh.of(e.collapseUnchanged?zh(e.collapseUnchanged):[])];r=r.update({effects:Eo.appendConfig.of(o)}).state,a=a.update({effects:Eo.appendConfig.of(o)}).state,this.dom=document.createElement(`div`),this.dom.className=`cm-mergeView`,this.editorDOM=this.dom.appendChild(document.createElement(`div`)),this.editorDOM.className=`cm-mergeViewEditors`;let s=e.orientation||`a-b`,c=document.createElement(`div`);c.className=`cm-mergeViewEditor`;let l=document.createElement(`div`);l.className=`cm-mergeViewEditor`,this.editorDOM.appendChild(s==`a-b`?c:l),this.editorDOM.appendChild(s==`a-b`?l:c),this.a=new ko({state:r,parent:c,root:e.root,dispatchTransactions:e=>this.dispatch(e,this.a)}),this.b=new ko({state:a,parent:l,root:e.root,dispatchTransactions:e=>this.dispatch(e,this.b)}),this.setupRevertControls(!!e.revertControls,e.revertControls==`b-to-a`,e.renderRevertControl),e.parent&&e.parent.appendChild(this.dom),this.scheduleMeasure()}dispatch(e,t){if(e.some(e=>e.docChanged)){let n=e[e.length-1],r=e.reduce((e,t)=>e.compose(t.changes),vo.empty(e[0].startState.doc.length));this.chunks=t==this.a?lh.updateA(this.chunks,n.newDoc,this.b.state.doc,r,this.diffConf):lh.updateB(this.chunks,this.a.state.doc,n.newDoc,r,this.diffConf),t.update([...e,n.state.update({effects:ah.of(this.chunks)})]);let i=t==this.a?this.b:this.a;i.update([i.state.update({effects:ah.of(this.chunks)})]),this.scheduleMeasure()}else t.update(e)}reconfigure(e){if(`diffConfig`in e&&(this.diffConf=e.diffConfig),`orientation`in e){let t=e.orientation!=`b-a`;if(t!=(this.editorDOM.firstChild==this.a.dom.parentNode)){let e=this.a.dom.parentNode,n=this.b.dom.parentNode;e.remove(),n.remove(),this.editorDOM.insertBefore(t?e:n,this.editorDOM.firstChild),this.editorDOM.appendChild(t?n:e),this.revertToLeft=!this.revertToLeft,this.revertDOM&&(this.revertDOM.textContent=``)}}if(`revertControls`in e||`renderRevertControl`in e){let t=!!this.revertDOM,n=this.revertToA,r=this.renderRevert;`revertControls`in e&&(t=!!e.revertControls,n=e.revertControls==`b-to-a`),`renderRevertControl`in e&&(r=e.renderRevertControl),this.setupRevertControls(t,n,r)}let t=`highlightChanges`in e,n=`gutter`in e,r=`collapseUnchanged`in e;if(t||n||r){let i=[],a=[];if(t||n){let r=this.a.state.facet(ih),o=n?e.gutter!==!1:r.markGutter,s=t?e.highlightChanges!==!1:r.highlightChanges;i.push(Wh.reconfigure([ih.of({side:`a`,sibling:()=>this.b,highlightChanges:s,markGutter:o}),o?yh:[]])),a.push(Wh.reconfigure([ih.of({side:`b`,sibling:()=>this.a,highlightChanges:s,markGutter:o}),o?yh:[]]))}if(r){let t=Uh.reconfigure(e.collapseUnchanged?zh(e.collapseUnchanged):[]);i.push(t),a.push(t)}this.a.dispatch({effects:i}),this.b.dispatch({effects:a})}this.scheduleMeasure()}setupRevertControls(e,t,n){this.revertToA=t,this.revertToLeft=this.revertToA==(this.editorDOM.firstChild==this.a.dom.parentNode),this.renderRevert=n,!e&&this.revertDOM?(this.revertDOM.remove(),this.revertDOM=null):e&&!this.revertDOM?(this.revertDOM=this.editorDOM.insertBefore(document.createElement(`div`),this.editorDOM.firstChild.nextSibling),this.revertDOM.addEventListener(`mousedown`,e=>this.revertClicked(e)),this.revertDOM.className=`cm-merge-revert`):this.revertDOM&&(this.revertDOM.textContent=``)}scheduleMeasure(){this.measuring<0&&(this.measuring=(this.dom.ownerDocument.defaultView||window).requestAnimationFrame(()=>{this.measuring=-1,this.measure()}))}measure(){Ph(this.a,this.b,this.chunks),this.revertDOM&&this.updateRevertButtons()}updateRevertButtons(){let e=this.revertDOM,t=e.firstChild,n=this.a.viewport,r=this.b.viewport;for(let i=0;i<this.chunks.length;i++){let a=this.chunks[i];if(a.fromA>n.to||a.fromB>r.to)break;if(a.fromA<n.from||a.fromB<r.from)continue;let o=this.a.lineBlockAt(a.fromA).top+`px`;for(;t&&+t.dataset.chunk<i;)t=Kh(t);t&&t.dataset.chunk==String(i)?(t.style.top!=o&&(t.style.top=o),t=t.nextSibling):e.insertBefore(this.renderRevertButton(o,i),t)}for(;t;)t=Kh(t)}renderRevertButton(e,t){let n;if(this.renderRevert)n=this.renderRevert();else{n=document.createElement(`button`);let e=this.a.state.phrase(`Revert this chunk`);n.setAttribute(`aria-label`,e),n.setAttribute(`title`,e),n.textContent=this.revertToLeft?`⇜`:`⇝`}return n.style.top=e,n.setAttribute(`data-chunk`,String(t)),n}revertClicked(e){let t=e.target,n;for(;t&&t.parentNode!=this.revertDOM;)t=t.parentNode;if(t&&(n=this.chunks[t.dataset.chunk])){let[t,r,i,a,o,s]=this.revertToA?[this.b,this.a,n.fromB,n.toB,n.fromA,n.toA]:[this.a,this.b,n.fromA,n.toA,n.fromB,n.toB],c=t.state.sliceDoc(i,Math.max(i,a-1));i!=a&&s<=r.state.doc.length&&(c+=t.state.lineBreak),r.dispatch({changes:{from:o,to:Math.min(r.state.doc.length,s),insert:c},userEvent:`revert`}),e.preventDefault()}}destroy(){this.a.destroy(),this.b.destroy(),this.measuring>-1&&(this.dom.ownerDocument.defaultView||window).cancelAnimationFrame(this.measuring),this.dom.remove()}};function Kh(e){let t=e.nextSibling;return e.remove(),t}var qh=new class extends Ao{constructor(){super(...arguments),this.elementClass=`cm-deletedLineGutter`}},Jh=_o.low(jo({class:`cm-changeGutter`,markers:e=>e.plugin(vh)?.gutter||No.empty,widgetMarker:(e,t)=>t instanceof $h?qh:null}));function Yh(e){let t=typeof e.original==`string`?So.of(e.original.split(/\r?\n/)):e.original,n=e.diffConfig||_h;return[_o.low(vh),ig,Hh,ko.editorAttributes.of({class:`cm-merge-b`}),oh.of((e,t)=>{let r=t.effects.find(e=>e.is(Xh));return r&&(e=lh.updateA(e,r.value.doc,t.startState.doc,r.value.changes,n)),t.docChanged&&(e=lh.updateB(e,t.state.field(Zh),t.newDoc,t.changes,n)),e}),ih.of({highlightChanges:e.highlightChanges!==!1,markGutter:e.gutter!==!1,syntaxHighlightDeletions:e.syntaxHighlightDeletions!==!1,syntaxHighlightDeletionsMaxLength:3e3,mergeControls:e.mergeControls??!0,overrideChunk:e.allowInlineDiffs?ug:void 0,side:`b`}),Zh.init(()=>t),e.gutter===!1?[]:Jh,e.collapseUnchanged?zh(e.collapseUnchanged):[],sh.init(e=>lh.build(t,e.doc,n))]}var Xh=Eo.define(),Zh=bo.define({create:()=>So.empty,update(e,t){for(let n of t.effects)n.is(Xh)&&(e=n.value.doc);return e}}),Qh=new WeakMap,$h=class extends go{constructor(e){super(),this.buildDOM=e,this.dom=null}eq(e){return this.dom==e.dom}toDOM(e){return this.dom||=this.buildDOM(e)}};function eg(e,t,n){let r=Qh.get(t.changes);if(r)return r;let i=Co.widget({block:!0,side:-1,widget:new $h(r=>{let{highlightChanges:i,syntaxHighlightDeletions:a,syntaxHighlightDeletionsMaxLength:o,mergeControls:s}=e.facet(ih),c=document.createElement(`div`);if(c.className=`cm-deletedChunk`,s){let t=c.appendChild(document.createElement(`div`));t.className=`cm-chunkButtons`;let n=e=>{e.preventDefault(),tg(r,r.posAtDOM(c))},i=e=>{e.preventDefault(),ng(r,r.posAtDOM(c))};if(typeof s==`function`)t.appendChild(s(`accept`,n)),t.appendChild(s(`reject`,i));else{let r=t.appendChild(document.createElement(`button`));r.name=`accept`,r.textContent=e.phrase(`Accept`),r.onmousedown=n;let a=t.appendChild(document.createElement(`button`));a.name=`reject`,a.textContent=e.phrase(`Reject`),a.onmousedown=i}}if(n||t.fromA>=t.toA)return c;let l=r.state.field(Zh).sliceString(t.fromA,t.endA),u=a&&e.facet(Po),d=h(),f=t.changes,p=0,m=!1;function h(){let e=c.appendChild(document.createElement(`div`));return e.className=`cm-deletedLine`,e.appendChild(document.createElement(`del`))}function g(e,t,n){for(let r=e;r<t;){if(l.charAt(r)==`
14
14
  `){d.firstChild||d.appendChild(document.createElement(`br`)),d=h(),r++;continue}let e=t,a=n+(m?` cm-deletedText`:``),o=!1,s=l.indexOf(`
15
- `,r);if(s>-1&&s<t&&(e=s),i&&p<f.length){let t=Math.max(0,m?f[p].toA:f[p].fromA);t<=e&&(e=t,m&&p++,o=!0)}if(e>r){let t=document.createTextNode(l.slice(r,e));if(a){let e=d.appendChild(document.createElement(`span`));e.className=a,e.appendChild(t)}else d.appendChild(t);r=e}o&&(m=!m)}}if(u&&t.toA-t.fromA<=o){let t=u.parser.parse(l),n=0;xo(t,{style:t=>Fo(e,t)},(e,t,r)=>{e>n&&g(n,e,``),g(e,t,r),n=t}),g(n,l.length,``)}else g(0,l.length,``);return d.firstChild||d.appendChild(document.createElement(`br`)),c})});return Qh.set(t.changes,i),i}function tg(e,t){let{state:n}=e,r=t??n.selection.main.head,i=e.state.field(sh).find(e=>e.fromB<=r&&e.endB>=r);if(!i)return!1;let a=e.state.sliceDoc(i.fromB,Math.max(i.fromB,i.toB-1)),o=e.state.field(Zh);i.fromB!=i.toB&&i.toA<=o.length&&(a+=e.state.lineBreak);let s=vo.of({from:i.fromA,to:Math.min(o.length,i.toA),insert:a},o.length);return e.dispatch({effects:Xh.of({doc:s.apply(o),changes:s}),userEvent:`accept`}),!0}function ng(e,t){let{state:n}=e,r=t??n.selection.main.head,i=n.field(sh).find(e=>e.fromB<=r&&e.endB>=r);if(!i)return!1;let a=n.field(Zh).sliceString(i.fromA,Math.max(i.fromA,i.toA-1));return i.fromA!=i.toA&&i.toB<=n.doc.length&&(a+=n.lineBreak),e.dispatch({changes:{from:i.fromB,to:Math.min(n.doc.length,i.toB),insert:a},userEvent:`revert`}),!0}function rg(e){let t=new wo;for(let n of e.field(sh)){let r=e.facet(ih).overrideChunk&&og(e,n);t.add(n.fromB,n.fromB,eg(e,n,!!r))}return t.finish()}var ig=bo.define({create:e=>rg(e),update(e,t){return t.state.field(sh,!1)==t.startState.field(sh,!1)?e:rg(t.state)},provide:e=>ko.decorations.from(e)}),ag=new WeakMap;function og(e,t){let n=ag.get(t);if(n!==void 0)return n;n=null;let r=e.field(Zh),i=e.doc,a=r.lineAt(t.endA).number-r.lineAt(t.fromA).number+1,o=i.lineAt(t.endB).number-i.lineAt(t.fromB).number+1;abort:if(a==o&&a<10){let e=[],i=0,o=t.fromA,s=t.fromB;for(let n of t.changes){if(n.fromA<n.toA){i+=n.toA-n.fromA;let t=r.sliceString(o+n.fromA,o+n.toA);if(/\n/.test(t))break abort;e.push(Co.widget({widget:new sg(t),side:-1}).range(s+n.fromB))}n.fromB<n.toB&&e.push(Ch.range(s+n.fromB,s+n.toB))}i<t.endA-t.fromA-a*2&&(n=e)}return ag.set(t,n),n}var sg=class extends go{constructor(e){super(),this.text=e}eq(e){return this.text==e.text}toDOM(e){let t=document.createElement(`del`);return t.className=`cm-deletedText`,t.textContent=this.text,t}},cg=new class extends Ao{constructor(){super(...arguments),this.elementClass=`cm-inlineChangedLineGutter`}},lg=Co.line({class:`cm-inlineChangedLine`});function ug(e,t,n,r){let i=og(e,t),a=0;if(!i)return!1;for(let o=e.doc.lineAt(t.fromB);;){for(r&&r.add(o.from,o.from,cg),n.add(o.from,o.from,lg);a<i.length&&i[a].to<=o.to;){let e=i[a++];n.add(e.from,e.to,e.value)}if(o.to>=t.endB)break;o=e.doc.lineAt(o.to+1)}return!0}var dg=W({settings:{background:`var(--background)`,gutterBackground:`var(--muted)`}}),fg=gt({settings:{background:`var(--background)`,gutterBackground:`var(--muted)`}});function pg(e){let t=(0,$.c)(20),{oldContent:n,newContent:r,layout:i,conflictMode:a,onResolve:o,onAbort:s}=e,c=(0,Q.useRef)(null),l=(0,Q.useRef)(null),{resolvedTheme:u}=yr(),d=(0,Q.useRef)(o),f=(0,Q.useRef)(s),[p,m]=(0,Q.useState)(null),h;t[0]!==s||t[1]!==o?(h=()=>{d.current=o,f.current=s},t[0]=s,t[1]=o,t[2]=h):h=t[2],(0,Q.useEffect)(h);let g,v;t[3]!==a||t[4]!==i||t[5]!==r||t[6]!==n||t[7]!==u?(g=()=>{if(!c.current)return;let e=u===`dark`?dg:fg,t=[ko.editable.of(!1),yo.readOnly.of(!0)],o=[Ro,_(),...t,e,ko.lineWrapping];if(l.current&&=(l.current.destroy(),null),a){let t=new ko({doc:r,extensions:[Ro,_(),ko.editable.of(!1),e,ko.lineWrapping,Yh({original:n,highlightChanges:!0,gutter:!0,mergeControls:!0,collapseUnchanged:{margin:3,minSize:4}}),ko.updateListener.of(e=>{let t=ch(e.state);m(t?t.chunks.length:0)})],parent:c.current});l.current=t;let i=ch(t.state);m(i?i.chunks.length:0)}else i===`split`?l.current=new Gh({a:{doc:n,extensions:o},b:{doc:r,extensions:o},parent:c.current,highlightChanges:!0,gutter:!0,collapseUnchanged:{margin:3,minSize:4}}):l.current=new ko({doc:r,extensions:[...o,Yh({original:n,highlightChanges:!0,gutter:!0,mergeControls:!1,collapseUnchanged:{margin:3,minSize:4}})],parent:c.current});return()=>{l.current&&=(l.current.destroy(),null)}},v=[n,r,i,u,a],t[3]=a,t[4]=i,t[5]=r,t[6]=n,t[7]=u,t[8]=g,t[9]=v):(g=t[8],v=t[9]),(0,Q.useEffect)(g,v);let y;t[10]===Symbol.for(`react.memo_cache_sentinel`)?(y=function(){let e=l.current;!e||!(e instanceof ko)||d.current?.(e.state.doc.toString())},t[10]=y):y=t[10];let b=y,x=p===0,S=p===null?``:p===0?`All hunks resolved`:`${p} unresolved hunk${p===1?``:`s`}`,C;t[11]===Symbol.for(`react.memo_cache_sentinel`)?(C=(0,Z.jsx)(`div`,{ref:c,className:`diff-view min-h-0 flex-1 overflow-y-auto subtle-scrollbar`}),t[11]=C):C=t[11];let w;t[12]!==x||t[13]!==a||t[14]!==S||t[15]!==s||t[16]!==o?(w=a&&(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2 px-3 py-2 border-t shrink-0`,children:[(0,Z.jsx)(`span`,{className:`text-xs ${x?`text-emerald-600 dark:text-emerald-400`:`text-muted-foreground`}`,children:S}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[s&&(0,Z.jsx)(X,{variant:`ghost`,size:`sm`,onClick:s,children:`Exit merge`}),o&&(0,Z.jsx)(X,{variant:`default`,size:`sm`,disabled:!x,onClick:b,children:`Save resolution`})]})]}),t[12]=x,t[13]=a,t[14]=S,t[15]=s,t[16]=o,t[17]=w):w=t[17];let T;return t[18]===w?T=t[19]:(T=(0,Z.jsxs)(`div`,{className:`flex flex-col h-full`,children:[C,w]}),t[18]=w,t[19]=T),T}function mg(e){let t=(0,$.c)(4),n;t[0]===e?n=t[1]:({...n}=e,t[0]=e,t[1]=n);let r;return t[2]===n?r=t[3]:(r=(0,Z.jsx)(Ua,{"data-slot":`sheet`,...n}),t[2]=n,t[3]=r),r}function hg(e){let t=(0,$.c)(4),n;t[0]===e?n=t[1]:({...n}=e,t[0]=e,t[1]=n);let r;return t[2]===n?r=t[3]:(r=(0,Z.jsx)(Ka,{"data-slot":`sheet-portal`,...n}),t[2]=n,t[3]=r),r}function gg(e){let t=(0,$.c)(8),n,r;t[0]===e?(n=t[1],r=t[2]):({className:n,...r}=e,t[0]=e,t[1]=n,t[2]=r);let i;t[3]===n?i=t[4]:(i=Y(`fixed inset-0 z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0`,n),t[3]=n,t[4]=i);let a;return t[5]!==r||t[6]!==i?(a=(0,Z.jsx)(za,{"data-slot":`sheet-overlay`,className:i,...r}),t[5]=r,t[6]=i,t[7]=a):a=t[7],a}function _g(e){let t=(0,$.c)(17),n,r,i,a,o;t[0]===e?(n=t[1],r=t[2],i=t[3],a=t[4],o=t[5]):({className:r,children:n,side:a,showCloseButton:o,...i}=e,t[0]=e,t[1]=n,t[2]=r,t[3]=i,t[4]=a,t[5]=o);let s=a===void 0?`right`:a,c=o===void 0?!0:o,l;t[6]===Symbol.for(`react.memo_cache_sentinel`)?(l=(0,Z.jsx)(gg,{}),t[6]=l):l=t[6];let u;t[7]===r?u=t[8]:(u=Y(`fixed z-50 flex flex-col gap-4 bg-popover bg-clip-padding text-sm text-popover-foreground shadow-lg transition duration-200 ease-in-out data-[side=bottom]:inset-x-0 data-[side=bottom]:bottom-0 data-[side=bottom]:h-auto data-[side=bottom]:border-t data-[side=left]:inset-y-0 data-[side=left]:left-0 data-[side=left]:h-full data-[side=left]:w-3/4 data-[side=left]:border-r data-[side=right]:inset-y-0 data-[side=right]:right-0 data-[side=right]:h-full data-[side=right]:w-3/4 data-[side=right]:border-l data-[side=top]:inset-x-0 data-[side=top]:top-0 data-[side=top]:h-auto data-[side=top]:border-b data-[side=left]:sm:max-w-sm data-[side=right]:sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-[side=bottom]:data-open:slide-in-from-bottom-10 data-[side=left]:data-open:slide-in-from-left-10 data-[side=right]:data-open:slide-in-from-right-10 data-[side=top]:data-open:slide-in-from-top-10 data-closed:animate-out data-closed:fade-out-0 data-[side=bottom]:data-closed:slide-out-to-bottom-10 data-[side=left]:data-closed:slide-out-to-left-10 data-[side=right]:data-closed:slide-out-to-right-10 data-[side=top]:data-closed:slide-out-to-top-10`,r),t[7]=r,t[8]=u);let d;t[9]===c?d=t[10]:(d=c&&(0,Z.jsx)(Ha,{"data-slot":`sheet-close`,asChild:!0,children:(0,Z.jsxs)(X,{variant:`ghost`,className:`absolute top-3 right-3`,size:`icon-sm`,children:[(0,Z.jsx)(Fa,{}),(0,Z.jsx)(`span`,{className:`sr-only`,children:`Close`})]})}),t[9]=c,t[10]=d);let f;return t[11]!==n||t[12]!==i||t[13]!==s||t[14]!==u||t[15]!==d?(f=(0,Z.jsxs)(hg,{children:[l,(0,Z.jsxs)(Ya,{"data-slot":`sheet-content`,"data-side":s,className:u,...i,children:[n,d]})]}),t[11]=n,t[12]=i,t[13]=s,t[14]=u,t[15]=d,t[16]=f):f=t[16],f}function vg(e){let t=(0,$.c)(8),n,r;t[0]===e?(n=t[1],r=t[2]):({className:n,...r}=e,t[0]=e,t[1]=n,t[2]=r);let i;t[3]===n?i=t[4]:(i=Y(`flex flex-col gap-0.5 p-4`,n),t[3]=n,t[4]=i);let a;return t[5]!==r||t[6]!==i?(a=(0,Z.jsx)(`div`,{"data-slot":`sheet-header`,className:i,...r}),t[5]=r,t[6]=i,t[7]=a):a=t[7],a}function yg(e){let t=(0,$.c)(8),n,r;t[0]===e?(n=t[1],r=t[2]):({className:n,...r}=e,t[0]=e,t[1]=n,t[2]=r);let i;t[3]===n?i=t[4]:(i=Y(`font-heading text-base font-medium text-foreground`,n),t[3]=n,t[4]=i);let a;return t[5]!==r||t[6]!==i?(a=(0,Z.jsx)(Ba,{"data-slot":`sheet-title`,className:i,...r}),t[5]=r,t[6]=i,t[7]=a):a=t[7],a}async function bg(){try{let e=await fetch(`/api/sync/conflicts`);return e.ok?{conflicts:(await e.json()).conflicts??[]}:{conflicts:[],error:`server`}}catch{return{conflicts:[],error:`network`}}}async function xg(e){try{let t=await fetch(`/api/sync/conflict-content?file=${encodeURIComponent(e)}`);if(!t.ok)return{ours:``,theirs:``,base:``};let n=await t.json();return{ours:n.ours??``,theirs:n.theirs??``,base:n.base??``}}catch{return{ours:``,theirs:``,base:``}}}async function Sg(e,t,n){try{let r={file:e,strategy:t};return n!==void 0&&(r.content=n),(await fetch(`/api/sync/resolve-conflict`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r)})).ok}catch{return!1}}var Cg=`w-[98vw] !max-w-[98vw] h-[96vh] flex flex-col gap-0 sm:!max-w-[98vw]`;function wg(e){let t=(0,$.c)(31),{file:n,onResolve:r,onAbort:i}=e,[a,o]=(0,Q.useState)(null),s,c;if(t[0]===n?(s=t[1],c=t[2]):(s=()=>{let e=!1;return xg(n).then(t=>{e||o(t)}),()=>{e=!0}},c=[n],t[0]=n,t[1]=s,t[2]=c),(0,Q.useEffect)(s,c),a===null){let e;t[3]===i?e=t[4]:(e=e=>!e&&i(),t[3]=i,t[4]=e);let r;t[5]===n?r=t[6]:(r=(0,Z.jsx)(qa,{className:`shrink-0`,children:(0,Z.jsxs)(Ra,{children:[`Resolving: `,n]})}),t[5]=n,t[6]=r);let a;t[7]===Symbol.for(`react.memo_cache_sentinel`)?(a=(0,Z.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-sm text-muted-foreground`,children:`Loading`}),t[7]=a):a=t[7];let o;t[8]===r?o=t[9]:(o=(0,Z.jsxs)(Va,{className:Cg,children:[r,a]}),t[8]=r,t[9]=o);let s;return t[10]!==e||t[11]!==o?(s=(0,Z.jsx)(Ja,{open:!0,onOpenChange:e,children:o}),t[10]=e,t[11]=o,t[12]=s):s=t[12],s}let l;t[13]===i?l=t[14]:(l=e=>!e&&i(),t[13]=i,t[14]=l);let u;t[15]===n?u=t[16]:(u=(0,Z.jsxs)(Ra,{className:`text-sm font-medium`,children:[`Resolving: `,n]}),t[15]=n,t[16]=u);let d;t[17]===Symbol.for(`react.memo_cache_sentinel`)?(d=(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Red = your version (ours). Green = team's version (theirs). Accept each hunk to take theirs, reject to keep yours, then save.`}),t[17]=d):d=t[17];let f;t[18]===u?f=t[19]:(f=(0,Z.jsxs)(qa,{className:`px-4 pt-4 pb-2 shrink-0`,children:[u,d]}),t[18]=u,t[19]=f);let p;t[20]!==i||t[21]!==r||t[22]!==a.ours||t[23]!==a.theirs?(p=(0,Z.jsx)(`div`,{className:`flex-1 min-h-0 overflow-hidden`,children:(0,Z.jsx)(pg,{oldContent:a.ours,newContent:a.theirs,layout:`unified`,conflictMode:!0,onResolve:r,onAbort:i})}),t[20]=i,t[21]=r,t[22]=a.ours,t[23]=a.theirs,t[24]=p):p=t[24];let m;t[25]!==f||t[26]!==p?(m=(0,Z.jsxs)(Va,{className:`${Cg} p-0`,children:[f,p]}),t[25]=f,t[26]=p,t[27]=m):m=t[27];let h;return t[28]!==l||t[29]!==m?(h=(0,Z.jsx)(Ja,{open:!0,onOpenChange:l,children:m}),t[28]=l,t[29]=m,t[30]=h):h=t[30],h}function Tg(e){let t=(0,$.c)(50),{open:n,onOpenChange:r}=e,i;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(i=[],t[0]=i):i=t[0];let[a,o]=(0,Q.useState)(i),[s,c]=(0,Q.useState)(null),l;t[1]===Symbol.for(`react.memo_cache_sentinel`)?(l=new Set,t[1]=l):l=t[1];let[u,d]=(0,Q.useState)(l),f;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(f=new Set,t[2]=f):f=t[2];let[p,m]=(0,Q.useState)(f),[h,g]=(0,Q.useState)(null),_;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(_=function(){bg().then(e=>{let{conflicts:t,error:n}=e;c(n??null),o(t),d(e=>{let n=new Set(t.map(Eg));return new Set([...e].filter(e=>!n.has(e)))})})},t[3]=_):_=t[3];let v=_,y,b;t[4]===n?(y=t[5],b=t[6]):(y=()=>{n&&v()},b=[n],t[4]=n,t[5]=y,t[6]=b),(0,Q.useEffect)(y,b);let x,S;t[7]===n?(x=t[8],S=t[9]):(x=()=>_r(e=>{e.includes(`sync-status`)&&n&&v()}),S=[n],t[7]=n,t[8]=x,t[9]=S),(0,Q.useEffect)(x,S);let C,w;t[10]!==a.length||t[11]!==r||t[12]!==n||t[13]!==u.size?(w=()=>{n&&a.length>0&&u.size>=a.length&&(Xa.success(`All conflicts resolved — sync resuming`),r(!1),d(new Set))},C=[n,a.length,u.size,r],t[10]=a.length,t[11]=r,t[12]=n,t[13]=u.size,t[14]=C,t[15]=w):(C=t[14],w=t[15]),(0,Q.useEffect)(w,C);let T;t[16]===Symbol.for(`react.memo_cache_sentinel`)?(T=async function(e,t,n){m(t=>new Set([...t,e]));let r=await Sg(e,t,n);m(t=>{let n=new Set(t);return n.delete(e),n}),r?d(t=>new Set([...t,e])):Xa.error(`Failed to resolve ${e}`)},t[16]=T):T=t[16];let E=T,D;t[17]===Symbol.for(`react.memo_cache_sentinel`)?(D=function(e){g(e)},t[17]=D):D=t[17];let O=D,k;t[18]===h?k=t[19]:(k=async function(e){if(!h)return;let t=h;g(null),await E(t,`content`,e)},t[18]=h,t[19]=k);let A=k,j;t[20]===Symbol.for(`react.memo_cache_sentinel`)?(j=function(){g(null)},t[20]=j):j=t[20];let M=j,N;t[21]===r?N=t[22]:(N=async function(){try{(await fetch(`/api/sync/abort-merge`,{method:`POST`})).ok?Xa.info(`Merge aborted — sync paused`):Xa.error(`Failed to abort merge`)}catch{Xa.error(`Failed to abort merge — connection error`)}r(!1),d(new Set)},t[21]=r,t[22]=N);let P=N,F=a.length,I=u.size,L;t[23]===Symbol.for(`react.memo_cache_sentinel`)?(L=(0,Z.jsx)(yg,{className:`text-sm font-medium`,children:`Resolve conflicts`}),t[23]=L):L=t[23];let R;t[24]!==I||t[25]!==F?(R=F>0&&(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[I,` of `,F,` resolved`]}),t[24]=I,t[25]=F,t[26]=R):R=t[26];let z;t[27]===R?z=t[28]:(z=(0,Z.jsxs)(vg,{className:`px-4 py-3 border-b shrink-0`,children:[L,R]}),t[27]=R,t[28]=z);let B;t[29]!==a||t[30]!==s||t[31]!==u||t[32]!==p?(B=(0,Z.jsx)(`div`,{className:`flex-1 overflow-y-auto subtle-scrollbar`,children:s?(0,Z.jsxs)(`div`,{className:`px-4 py-6 text-sm text-center space-y-2`,children:[(0,Z.jsx)(`p`,{className:`text-destructive`,children:s===`network`?`Could not reach the sync server — check your connection.`:`Sync server error — try again in a moment.`}),(0,Z.jsx)(X,{variant:`outline`,size:`sm`,onClick:v,children:`Retry`})]}):a.length===0?(0,Z.jsx)(`p`,{className:`px-4 py-6 text-sm text-muted-foreground text-center`,children:`No conflicts found.`}):(0,Z.jsx)(`ul`,{className:`divide-y`,children:a.map(e=>{let t=u.has(e.file),n=p.has(e.file),r=e.file.split(`/`).pop()??e.file;return(0,Z.jsxs)(`li`,{className:`px-4 py-3 ${t?`opacity-50`:``}`,children:[(0,Z.jsxs)(`p`,{className:`text-sm font-medium truncate mb-2`,title:e.file,children:[t?`✓ `:``,r]}),!t&&(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-1`,children:[(0,Z.jsx)(X,{variant:`outline`,size:`xs`,disabled:n,onClick:()=>void E(e.file,`mine`),children:`Keep my version`}),(0,Z.jsx)(X,{variant:`outline`,size:`xs`,disabled:n,onClick:()=>void E(e.file,`theirs`),children:`Keep team's version`}),(0,Z.jsx)(X,{variant:`ghost`,size:`xs`,disabled:n,onClick:()=>O(e.file),children:`Resolve manually`})]})]},e.file)})})}),t[29]=a,t[30]=s,t[31]=u,t[32]=p,t[33]=B):B=t[33];let V;t[34]===P?V=t[35]:(V=(0,Z.jsx)(`div`,{className:`px-4 py-3 border-t shrink-0`,children:(0,Z.jsx)(X,{variant:`ghost`,size:`sm`,className:`w-full`,onClick:P,children:`Exit merge`})}),t[34]=P,t[35]=V);let H;t[36]!==z||t[37]!==B||t[38]!==V?(H=(0,Z.jsxs)(_g,{side:`right`,className:`w-80 sm:w-96 flex flex-col gap-0 p-0`,children:[z,B,V]}),t[36]=z,t[37]=B,t[38]=V,t[39]=H):H=t[39];let U;t[40]!==r||t[41]!==n||t[42]!==H?(U=(0,Z.jsx)(mg,{open:n,onOpenChange:r,children:H}),t[40]=r,t[41]=n,t[42]=H,t[43]=U):U=t[43];let W;t[44]!==A||t[45]!==h?(W=h&&(0,Z.jsx)(wg,{file:h,onResolve:e=>void A(e),onAbort:M}),t[44]=A,t[45]=h,t[46]=W):W=t[46];let G;return t[47]!==U||t[48]!==W?(G=(0,Z.jsxs)(Z.Fragment,{children:[U,W]}),t[47]=U,t[48]=W,t[49]=G):G=t[49],G}function Eg(e){return e.file}var Dg=5;async function Og(e){let t=await fetch(`/api/backlinks?docName=${encodeURIComponent(e)}`),n=await t.json().catch(()=>null);if(!t.ok){let e=ir.safeParse(n);throw e.success?Error(e.data.title):new Ce(`Failed to parse backlinks error response (HTTP ${t.status})`,{status:t.status})}let r=fn.safeParse(n);if(!r.success)throw new Ce(`Backlinks response did not match expected shape.`,{status:t.status});return r.data.backlinks}async function kg(e){let t=await fetch(`/api/forward-links?docName=${encodeURIComponent(e)}`),n=await t.json().catch(()=>null);if(!t.ok){let e=ir.safeParse(n);throw e.success?Error(e.data.title):new Ce(`Failed to parse forward-links error response (HTTP ${t.status})`,{status:t.status})}let r=Zn.safeParse(n);if(!r.success)throw new Ce(`Forward-links response did not match expected shape.`,{status:t.status});return r.data.forwardLinks}function Ag(e){let t=e.split(`/`);return t.length<=2?e:`…/${t.slice(-2).join(`/`)}`}function jg(e){window.location.hash=er(e)}function Mg(e){let t=(0,$.c)(9),{title:n,count:r,isLoading:i}=e,a;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(a=(0,Z.jsx)(Ie,{className:`size-3.5 text-muted-foreground transition-transform group-data-[state=closed]:-rotate-90`}),t[0]=a):a=t[0];let o;t[1]===n?o=t[2]:(o=(0,Z.jsxs)(`span`,{className:`flex items-center gap-2.5`,children:[a,(0,Z.jsx)(Gt,{children:n})]}),t[1]=n,t[2]=o);let s;t[3]!==r||t[4]!==i?(s=!i&&(0,Z.jsx)(Wt,{children:r}),t[3]=r,t[4]=i,t[5]=s):s=t[5];let c;return t[6]!==o||t[7]!==s?(c=(0,Z.jsxs)(R,{className:`group flex w-full cursor-pointer items-center justify-between px-5 py-3 text-left transition-colors hover:bg-muted/40`,children:[o,s]}),t[6]=o,t[7]=s,t[8]=c):c=t[8],c}function Ng(e){let t=(0,$.c)(7),{total:n,expanded:r,onToggle:i}=e;if(n<=Dg)return null;let a=n-Dg,o;t[0]===r?o=t[1]:(o=r?(0,Z.jsx)(Ie,{className:`size-3`}):(0,Z.jsx)(l,{className:`size-3`}),t[0]=r,t[1]=o);let s=r?`Show fewer`:`Show ${a} more`,c;return t[2]!==r||t[3]!==i||t[4]!==o||t[5]!==s?(c=(0,Z.jsxs)(`button`,{type:`button`,"aria-expanded":r,className:`mt-2 inline-flex cursor-pointer items-center gap-1 px-3 text-xs text-muted-foreground transition-colors hover:text-foreground`,onClick:i,children:[o,s]}),t[2]=r,t[3]=i,t[4]=o,t[5]=s,t[6]=c):c=t[6],c}function Pg(e){let t=(0,$.c)(38),{icon:n,iconColorClass:r,rowTooltip:i,title:a,path:o,anchor:s,snippet:c,titleHover:l,ariaLabel:u,href:d,external:f,disabled:p,onClick:m,hoverAction:h}=e,g=o!==void 0&&o!==a,_=r??`text-muted-foreground`,v;t[0]===_?v=t[1]:(v=Y(`mt-0.5 shrink-0`,_),t[0]=_,t[1]=v);let y;t[2]!==n||t[3]!==v?(y=(0,Z.jsx)(`span`,{className:v,children:n}),t[2]=n,t[3]=v,t[4]=y):y=t[4];let b=y,x;t[5]!==u||t[6]!==p||t[7]!==f||t[8]!==d||t[9]!==m||t[10]!==a||t[11]!==l?(x=d?(0,Z.jsxs)(`a`,{href:d,target:f?`_blank`:void 0,rel:f?`noopener noreferrer`:void 0,"aria-label":u,title:l,onClick:m,className:`block w-full truncate text-left font-medium text-foreground no-underline outline-none after:absolute after:inset-0 after:rounded-md focus-visible:after:ring-2 focus-visible:after:ring-ring`,children:[a,f?(0,Z.jsx)(`span`,{className:`sr-only`,children:` (opens in new tab)`}):null]}):(0,Z.jsx)(`button`,{type:`button`,"aria-label":u,title:l,disabled:p,onClick:m,className:Y(`block w-full truncate text-left font-medium text-foreground no-underline outline-none after:absolute after:inset-0 after:rounded-md focus-visible:after:ring-2 focus-visible:after:ring-ring`,`cursor-pointer bg-transparent p-0 disabled:cursor-not-allowed disabled:opacity-60`),children:a}),t[5]=u,t[6]=p,t[7]=f,t[8]=d,t[9]=m,t[10]=a,t[11]=l,t[12]=x):x=t[12];let S=x,C;t[13]===b?C=t[14]:(C=(0,Z.jsx)(`div`,{className:`mt-px flex items-center`,children:b}),t[13]=b,t[14]=C);let w;t[15]!==s||t[16]!==o||t[17]!==g?(w=g?(0,Z.jsxs)(`div`,{className:`truncate font-mono text-xs text-muted-foreground`,children:[o,s?(0,Z.jsxs)(`span`,{className:`ml-1`,children:[`· #`,s]}):null]}):null,t[15]=s,t[16]=o,t[17]=g,t[18]=w):w=t[18];let T;t[19]===c?T=t[20]:(T=c?(0,Z.jsx)(`p`,{className:`line-clamp-2 text-muted-foreground`,children:c}):null,t[19]=c,t[20]=T);let E;t[21]!==S||t[22]!==w||t[23]!==T?(E=(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-0.5 text-1sm`,children:[S,w,T]}),t[21]=S,t[22]=w,t[23]=T,t[24]=E):E=t[24];let D;t[25]===h?D=t[26]:(D=h?(0,Z.jsxs)(uo,{children:[(0,Z.jsx)(so,{asChild:!0,children:(0,Z.jsx)(`button`,{type:`button`,"aria-label":h.tooltip,disabled:h.disabled,className:`relative z-10 shrink-0 cursor-pointer rounded-md p-1 text-muted-foreground opacity-0 transition-opacity hover:bg-accent hover:text-foreground focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:bg-transparent disabled:hover:text-muted-foreground group-hover:opacity-100`,onClick:h.onClick,children:h.icon})}),(0,Z.jsx)(co,{side:`top`,children:h.tooltip})]}):null,t[25]=h,t[26]=D);let O;t[27]!==C||t[28]!==E||t[29]!==D?(O=(0,Z.jsxs)(`div`,{className:`group relative flex items-start gap-2.5 rounded-md px-3 py-2.5 transition-colors hover:bg-muted/80`,children:[C,E,D]}),t[27]=C,t[28]=E,t[29]=D,t[30]=O):O=t[30];let k=O;if(i){let e;t[31]===k?e=t[32]:(e=(0,Z.jsx)(so,{asChild:!0,children:k}),t[31]=k,t[32]=e);let n;t[33]===i?n=t[34]:(n=(0,Z.jsx)(co,{side:`top`,children:i}),t[33]=i,t[34]=n);let r;return t[35]!==e||t[36]!==n?(r=(0,Z.jsxs)(uo,{children:[e,n]}),t[35]=e,t[36]=n,t[37]=r):r=t[37],r}return k}function Fg(e){let t=(0,$.c)(33),{docName:n}=e,{folderPaths:r,pages:i,loading:a}=wr(),o,s;t[0]===n?(o=t[1],s=t[2]):(o=[`backlinks`,n],s=()=>Og(n),t[0]=n,t[1]=o,t[2]=s);let c;t[3]!==n||t[4]!==a||t[5]!==i?(c=!a&&i.has(n),t[3]=n,t[4]=a,t[5]=i,t[6]=c):c=t[6];let l;t[7]!==o||t[8]!==s||t[9]!==c?(l={queryKey:o,queryFn:s,enabled:c},t[7]=o,t[8]=s,t[9]=c,t[10]=l):l=t[10];let{data:u,isLoading:d,error:f}=Nt(l),m;t[11]===u?m=t[12]:(m=u===void 0?[]:u,t[11]=u,t[12]=m);let h=m,[g,_]=(0,Q.useState)(!1),[v,y]=(0,Q.useState)(n);v!==n&&(y(n),_(!1));let b;t[13]!==h||t[14]!==g?(b=g?h:h.slice(0,Dg),t[13]=h,t[14]=g,t[15]=b):b=t[15];let x=b,S;t[16]!==h.length||t[17]!==d?(S=(0,Z.jsx)(Mg,{title:`Backlinks`,count:h.length,isLoading:d}),t[16]=h.length,t[17]=d,t[18]=S):S=t[18];let C;t[19]!==h.length||t[20]!==f||t[21]!==g||t[22]!==r||t[23]!==d||t[24]!==i||t[25]!==x?(C=f?(0,Z.jsx)(`div`,{className:`px-3`,children:(0,Z.jsx)(jt,{children:f instanceof Error?f.message:`Failed to load backlinks`})}):h.length===0&&!d?(0,Z.jsx)(`div`,{className:`px-3`,children:(0,Z.jsx)(Rt,{children:`No pages link here yet.`})}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`flex flex-col gap-1`,children:x.map((e,t)=>{let n=Na(e.source,{pages:i,folderPaths:r});return(0,Z.jsx)(Pg,{icon:(0,Z.jsx)(p,{className:`size-3.5`}),title:e.title,path:Ag(e.source),titleHover:e.source,anchor:e.anchor,snippet:e.snippet,href:er(n.hashDocName,e.anchor)},`${e.source}-${t}`)})}),(0,Z.jsx)(Ng,{total:h.length,expanded:g,onToggle:()=>_(Ig)})]}),t[19]=h.length,t[20]=f,t[21]=g,t[22]=r,t[23]=d,t[24]=i,t[25]=x,t[26]=C):C=t[26];let w;t[27]!==d||t[28]!==C?(w=(0,Z.jsx)(N,{children:(0,Z.jsx)(`div`,{className:`px-2 pb-3`,"aria-busy":d,children:C})}),t[27]=d,t[28]=C,t[29]=w):w=t[29];let T;return t[30]!==w||t[31]!==S?(T=(0,Z.jsxs)(A,{defaultOpen:!0,children:[S,w]}),t[30]=w,t[31]=S,t[32]=T):T=t[32],T}function Ig(e){return!e}function Lg(e){let t=(0,$.c)(42),{docName:n}=e,{addPage:r,folderPaths:i,pages:a,pagesBySlug:o,loading:s}=wr(),c,l;t[0]===n?(c=t[1],l=t[2]):(c=[`forward-links`,n],l=()=>kg(n),t[0]=n,t[1]=c,t[2]=l);let u;t[3]!==n||t[4]!==a||t[5]!==s?(u=!s&&a.has(n),t[3]=n,t[4]=a,t[5]=s,t[6]=u):u=t[6];let f;t[7]!==c||t[8]!==l||t[9]!==u?(f={queryKey:c,queryFn:l,enabled:u},t[7]=c,t[8]=l,t[9]=u,t[10]=f):f=t[10];let{data:m,isLoading:h,error:g}=Nt(f),_;t[11]===m?_=t[12]:(_=m===void 0?[]:m,t[11]=m,t[12]=_);let v=_,[y,b]=(0,Q.useState)(null),[x,S]=(0,Q.useState)(!1),[C,w]=(0,Q.useState)(n);C!==n&&(w(n),S(!1),b(null));let T;t[13]!==x||t[14]!==v?(T=x?v:v.slice(0,Dg),t[13]=x,t[14]=v,t[15]=T):T=t[15];let E=T,D;t[16]!==r||t[17]!==y?(D=async function(e,t){if(!y){b(t);try{await U(e,{addPage:r,onCreated:jg}),b(null)}catch(e){let t=e;Xa.error(t instanceof Error?t.message:`Failed to create page`),b(null)}}},t[16]=r,t[17]=y,t[18]=D):D=t[18];let O=D,k;t[19]!==y||t[20]!==i||t[21]!==O||t[22]!==a||t[23]!==o||t[24]!==s?(k=function(e){if(e.kind===`external`){let t=e.title===e.url;return(0,Z.jsx)(Pg,{icon:(0,Z.jsx)(Ma,{className:`size-3.5`}),rowTooltip:`Opens in a new tab`,title:e.title,path:t?void 0:e.url,titleHover:e.url,snippet:e.snippet,href:e.url,external:!0},`ext:${e.url}`)}let t=d(e.docName,{pages:a,folderPaths:i,pagesBySlug:o}),n=!s&&t.kind===`create`,r=!s&&t.kind===`navigate`&&t.displayState===`folder`,c=Ag(e.docName),l=e.title===e.docName?c:e.title,u=`doc:${e.docName}:${e.anchor??``}`,f=er(t.kind===`navigate`?t.hashDocName:e.docName,e.anchor);if(n&&t.kind===`create`){let n={initialDir:t.initialDir,suggestedName:t.suggestedName};return(0,Z.jsx)(Pg,{icon:(0,Z.jsx)(Dn,{className:`size-3.5`}),iconColorClass:`text-amber-600 dark:text-amber-400`,rowTooltip:y===u?`Creating page`:`Missing page — click to create`,ariaLabel:y===u?`Creating page: ${e.title}.`:`Missing page: ${e.title}. Click to create.`,title:l,path:c,titleHover:e.docName,anchor:e.anchor,snippet:e.snippet,disabled:y!==null,onClick:()=>void O(n,u)},u)}if(r&&t.kind===`navigate`){let n=xt(t);return(0,Z.jsx)(Pg,{icon:(0,Z.jsx)(ks,{className:`size-3.5`}),iconColorClass:`text-sky-600 dark:text-sky-400`,ariaLabel:`Folder target: ${e.title}. Click to open the overview.`,title:l,path:c,titleHover:e.docName,anchor:e.anchor,snippet:e.snippet,href:f,hoverAction:{icon:(0,Z.jsx)(Fi,{className:`size-3.5`}),tooltip:y===u?`Creating index note`:`Create index note`,disabled:y!==null||n===null,onClick:()=>{n&&O(n,u)}}},u)}return(0,Z.jsx)(Pg,{icon:(0,Z.jsx)(p,{className:`size-3.5`}),title:l,path:c,titleHover:e.docName,anchor:e.anchor,snippet:e.snippet,href:f},u)},t[19]=y,t[20]=i,t[21]=O,t[22]=a,t[23]=o,t[24]=s,t[25]=k):k=t[25];let j=k,M;t[26]!==h||t[27]!==v.length?(M=(0,Z.jsx)(Mg,{title:`Outgoing`,count:v.length,isLoading:h}),t[26]=h,t[27]=v.length,t[28]=M):M=t[28];let P;t[29]!==g||t[30]!==x||t[31]!==h||t[32]!==v.length||t[33]!==j||t[34]!==E?(P=g?(0,Z.jsx)(`div`,{className:`px-3`,children:(0,Z.jsx)(jt,{children:g instanceof Error?g.message:`Failed to load outgoing links`})}):v.length===0&&!h?(0,Z.jsx)(`div`,{className:`px-3`,children:(0,Z.jsx)(Rt,{children:`This page doesn't link to anything yet.`})}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`flex flex-col gap-1`,children:E.map(j)}),(0,Z.jsx)(Ng,{total:v.length,expanded:x,onToggle:()=>S(Rg)})]}),t[29]=g,t[30]=x,t[31]=h,t[32]=v.length,t[33]=j,t[34]=E,t[35]=P):P=t[35];let F;t[36]!==h||t[37]!==P?(F=(0,Z.jsx)(N,{children:(0,Z.jsx)(`div`,{className:`px-2 pb-3`,"aria-busy":h,children:P})}),t[36]=h,t[37]=P,t[38]=F):F=t[38];let I;return t[39]!==M||t[40]!==F?(I=(0,Z.jsxs)(A,{defaultOpen:!0,children:[M,F]}),t[39]=M,t[40]=F,t[41]=I):I=t[41],I}function Rg(e){return!e}function zg(e){let t=(0,$.c)(11),{docName:n,className:r}=e,i=r===void 0?``:r,a;t[0]===n?a=t[1]:(a=(0,Z.jsx)(Fg,{docName:n}),t[0]=n,t[1]=a);let o;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(o=(0,Z.jsx)(Bi,{}),t[2]=o):o=t[2];let s;t[3]===n?s=t[4]:(s=(0,Z.jsx)(Lg,{docName:n}),t[3]=n,t[4]=s);let c;t[5]!==a||t[6]!==s?(c=(0,Z.jsxs)(Ht,{className:`px-0 py-0`,children:[a,o,s]}),t[5]=a,t[6]=s,t[7]=c):c=t[7];let l;return t[8]!==i||t[9]!==c?(l=(0,Z.jsx)(Kt,{className:i,children:c}),t[8]=i,t[9]=c,t[10]=l):l=t[10],l}var Bg=class{diff(e,t,n={}){let r;typeof n==`function`?(r=n,n={}):`callback`in n&&(r=n.callback);let i=this.castInput(e,n),a=this.castInput(t,n),o=this.removeEmpty(this.tokenize(i,n)),s=this.removeEmpty(this.tokenize(a,n));return this.diffWithOptionsObj(o,s,n,r)}diffWithOptionsObj(e,t,n,r){let i=e=>{if(e=this.postProcess(e,n),r){setTimeout(function(){r(e)},0);return}else return e},a=t.length,o=e.length,s=1,c=a+o;n.maxEditLength!=null&&(c=Math.min(c,n.maxEditLength));let l=n.timeout??1/0,u=Date.now()+l,d=[{oldPos:-1,lastComponent:void 0}],f=this.extractCommon(d[0],t,e,0,n);if(d[0].oldPos+1>=o&&f+1>=a)return i(this.buildValues(d[0].lastComponent,t,e));let p=-1/0,m=1/0,h=()=>{for(let r=Math.max(p,-s);r<=Math.min(m,s);r+=2){let s,c=d[r-1],l=d[r+1];c&&(d[r-1]=void 0);let u=!1;if(l){let e=l.oldPos-r;u=l&&0<=e&&e<a}let h=c&&c.oldPos+1<o;if(!u&&!h){d[r]=void 0;continue}if(s=!h||u&&c.oldPos<l.oldPos?this.addToPath(l,!0,!1,0,n):this.addToPath(c,!1,!0,1,n),f=this.extractCommon(s,t,e,r,n),s.oldPos+1>=o&&f+1>=a)return i(this.buildValues(s.lastComponent,t,e))||!0;d[r]=s,s.oldPos+1>=o&&(m=Math.min(m,r-1)),f+1>=a&&(p=Math.max(p,r+1))}s++};if(r)(function e(){setTimeout(function(){if(s>c||Date.now()>u)return r(void 0);h()||e()},0)})();else for(;s<=c&&Date.now()<=u;){let e=h();if(e)return e}}addToPath(e,t,n,r,i){let a=e.lastComponent;return a&&!i.oneChangePerToken&&a.added===t&&a.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:a.count+1,added:t,removed:n,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:a}}}extractCommon(e,t,n,r,i){let a=t.length,o=n.length,s=e.oldPos,c=s-r,l=0;for(;c+1<a&&s+1<o&&this.equals(n[s+1],t[c+1],i);)c++,s++,l++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return l&&!i.oneChangePerToken&&(e.lastComponent={count:l,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=s,c}equals(e,t,n){return n.comparator?n.comparator(e,t):e===t||!!n.ignoreCase&&e.toLowerCase()===t.toLowerCase()}removeEmpty(e){let t=[];for(let n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t}castInput(e,t){return e}tokenize(e,t){return Array.from(e)}join(e){return e.join(``)}postProcess(e,t){return e}get useLongestToken(){return!1}buildValues(e,t,n){let r=[],i;for(;e;)r.push(e),i=e.previousComponent,delete e.previousComponent,e=i;r.reverse();let a=r.length,o=0,s=0,c=0;for(;o<a;o++){let e=r[o];if(e.removed)e.value=this.join(n.slice(c,c+e.count)),c+=e.count;else{if(!e.added&&this.useLongestToken){let r=t.slice(s,s+e.count);r=r.map(function(e,t){let r=n[c+t];return r.length>e.length?r:e}),e.value=this.join(r)}else e.value=this.join(t.slice(s,s+e.count));s+=e.count,e.added||(c+=e.count)}}return r}};new class extends Bg{};function Vg(e,t){let n;for(n=0;n<e.length&&n<t.length;n++)if(e[n]!=t[n])return e.slice(0,n);return e.slice(0,n)}function Hg(e,t){let n;if(!e||!t||e[e.length-1]!=t[t.length-1])return``;for(n=0;n<e.length&&n<t.length;n++)if(e[e.length-(n+1)]!=t[t.length-(n+1)])return e.slice(-n);return e.slice(-n)}function Ug(e,t,n){if(e.slice(0,t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't start with prefix ${JSON.stringify(t)}; this is a bug`);return n+e.slice(t.length)}function Wg(e,t,n){if(!t)return e+n;if(e.slice(-t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't end with suffix ${JSON.stringify(t)}; this is a bug`);return e.slice(0,-t.length)+n}function Gg(e,t){return Ug(e,t,``)}function Kg(e,t){return Wg(e,t,``)}function qg(e,t){return t.slice(0,Jg(e,t))}function Jg(e,t){let n=0;e.length>t.length&&(n=e.length-t.length);let r=t.length;e.length<t.length&&(r=e.length);let i=Array(r),a=0;i[0]=0;for(let e=1;e<r;e++){for(t[e]==t[a]?i[e]=i[a]:i[e]=a;a>0&&t[e]!=t[a];)a=i[a];t[e]==t[a]&&a++}a=0;for(let r=n;r<e.length;r++){for(;a>0&&e[r]!=t[a];)a=i[a];e[r]==t[a]&&a++}return a}function Yg(e,t){let n=[];for(let r of Array.from(t.segment(e))){let e=r.segment;n.length&&/\s/.test(n[n.length-1])&&/\s/.test(e)?n[n.length-1]+=e:n.push(e)}return n}function Xg(e,t){if(t)return Qg(e,t)[1];let n;for(n=e.length-1;n>=0&&e[n].match(/\s/);n--);return e.substring(n+1)}function Zg(e,t){if(t)return Qg(e,t)[0];let n=e.match(/^\s*/);return n?n[0]:``}function Qg(e,t){if(!t)return[Zg(e),Xg(e)];if(t.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);let n=Yg(e,t),r=n[0],i=n[n.length-1];return[/\s/.test(r)?r:``,/\s/.test(i)?i:``]}var $g=`a-zA-Z0-9_\\u{AD}\\u{C0}-\\u{D6}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}`,e_=RegExp(`[${$g}]+|\\s+|[^${$g}]`,`ug`);new class extends Bg{equals(e,t,n){return n.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e.trim()===t.trim()}tokenize(e,t={}){let n;if(t.intlSegmenter){let r=t.intlSegmenter;if(r.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);n=Yg(e,r)}else n=e.match(e_)||[];let r=[],i=null;return n.forEach(e=>{/\s/.test(e)?i==null?r.push(e):r.push(r.pop()+e):i!=null&&/\s/.test(i)?r[r.length-1]==i?r.push(r.pop()+e):r.push(i+e):r.push(e),i=e}),r}join(e){return e.map((e,t)=>t==0?e:e.replace(/^\s+/,``)).join(``)}postProcess(e,t){if(!e||t.oneChangePerToken)return e;let n=null,r=null,i=null;return e.forEach(e=>{e.added?r=e:e.removed?i=e:((r||i)&&t_(n,i,r,e,t.intlSegmenter),n=e,r=null,i=null)}),(r||i)&&t_(n,i,r,null,t.intlSegmenter),e}};function t_(e,t,n,r,i){if(t&&n){let[a,o]=Qg(t.value,i),[s,c]=Qg(n.value,i);if(e){let r=Vg(a,s);e.value=Wg(e.value,s,r),t.value=Gg(t.value,r),n.value=Gg(n.value,r)}if(r){let e=Hg(o,c);r.value=Ug(r.value,c,e),t.value=Kg(t.value,e),n.value=Kg(n.value,e)}}else if(n){if(e){let e=Zg(n.value,i);n.value=n.value.substring(e.length)}if(r){let e=Zg(r.value,i);r.value=r.value.substring(e.length)}}else if(e&&r){let n=Zg(r.value,i),[a,o]=Qg(t.value,i),s=Vg(n,a);t.value=Gg(t.value,s);let c=Hg(Gg(n,s),o);t.value=Kg(t.value,c),r.value=Ug(r.value,n,c),e.value=Wg(e.value,n,n.slice(0,n.length-c.length))}else if(r){let e=Zg(r.value,i),n=qg(Xg(t.value,i),e);t.value=Kg(t.value,n)}else if(e){let n=qg(Xg(e.value,i),Zg(t.value,i));t.value=Gg(t.value,n)}}new class extends Bg{tokenize(e){let t=RegExp(`(\\r?\\n)|[${$g}]+|[^\\S\\n\\r]+|[^${$g}]`,`ug`);return e.match(t)||[]}};var n_=new class extends Bg{constructor(){super(...arguments),this.tokenize=i_}equals(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
15
+ `,r);if(s>-1&&s<t&&(e=s),i&&p<f.length){let t=Math.max(0,m?f[p].toA:f[p].fromA);t<=e&&(e=t,m&&p++,o=!0)}if(e>r){let t=document.createTextNode(l.slice(r,e));if(a){let e=d.appendChild(document.createElement(`span`));e.className=a,e.appendChild(t)}else d.appendChild(t);r=e}o&&(m=!m)}}if(u&&t.toA-t.fromA<=o){let t=u.parser.parse(l),n=0;xo(t,{style:t=>Fo(e,t)},(e,t,r)=>{e>n&&g(n,e,``),g(e,t,r),n=t}),g(n,l.length,``)}else g(0,l.length,``);return d.firstChild||d.appendChild(document.createElement(`br`)),c})});return Qh.set(t.changes,i),i}function tg(e,t){let{state:n}=e,r=t??n.selection.main.head,i=e.state.field(sh).find(e=>e.fromB<=r&&e.endB>=r);if(!i)return!1;let a=e.state.sliceDoc(i.fromB,Math.max(i.fromB,i.toB-1)),o=e.state.field(Zh);i.fromB!=i.toB&&i.toA<=o.length&&(a+=e.state.lineBreak);let s=vo.of({from:i.fromA,to:Math.min(o.length,i.toA),insert:a},o.length);return e.dispatch({effects:Xh.of({doc:s.apply(o),changes:s}),userEvent:`accept`}),!0}function ng(e,t){let{state:n}=e,r=t??n.selection.main.head,i=n.field(sh).find(e=>e.fromB<=r&&e.endB>=r);if(!i)return!1;let a=n.field(Zh).sliceString(i.fromA,Math.max(i.fromA,i.toA-1));return i.fromA!=i.toA&&i.toB<=n.doc.length&&(a+=n.lineBreak),e.dispatch({changes:{from:i.fromB,to:Math.min(n.doc.length,i.toB),insert:a},userEvent:`revert`}),!0}function rg(e){let t=new wo;for(let n of e.field(sh)){let r=e.facet(ih).overrideChunk&&og(e,n);t.add(n.fromB,n.fromB,eg(e,n,!!r))}return t.finish()}var ig=bo.define({create:e=>rg(e),update(e,t){return t.state.field(sh,!1)==t.startState.field(sh,!1)?e:rg(t.state)},provide:e=>ko.decorations.from(e)}),ag=new WeakMap;function og(e,t){let n=ag.get(t);if(n!==void 0)return n;n=null;let r=e.field(Zh),i=e.doc,a=r.lineAt(t.endA).number-r.lineAt(t.fromA).number+1,o=i.lineAt(t.endB).number-i.lineAt(t.fromB).number+1;abort:if(a==o&&a<10){let e=[],i=0,o=t.fromA,s=t.fromB;for(let n of t.changes){if(n.fromA<n.toA){i+=n.toA-n.fromA;let t=r.sliceString(o+n.fromA,o+n.toA);if(/\n/.test(t))break abort;e.push(Co.widget({widget:new sg(t),side:-1}).range(s+n.fromB))}n.fromB<n.toB&&e.push(Ch.range(s+n.fromB,s+n.toB))}i<t.endA-t.fromA-a*2&&(n=e)}return ag.set(t,n),n}var sg=class extends go{constructor(e){super(),this.text=e}eq(e){return this.text==e.text}toDOM(e){let t=document.createElement(`del`);return t.className=`cm-deletedText`,t.textContent=this.text,t}},cg=new class extends Ao{constructor(){super(...arguments),this.elementClass=`cm-inlineChangedLineGutter`}},lg=Co.line({class:`cm-inlineChangedLine`});function ug(e,t,n,r){let i=og(e,t),a=0;if(!i)return!1;for(let o=e.doc.lineAt(t.fromB);;){for(r&&r.add(o.from,o.from,cg),n.add(o.from,o.from,lg);a<i.length&&i[a].to<=o.to;){let e=i[a++];n.add(e.from,e.to,e.value)}if(o.to>=t.endB)break;o=e.doc.lineAt(o.to+1)}return!0}var dg=W({settings:{background:`var(--background)`,gutterBackground:`var(--muted)`}}),fg=gt({settings:{background:`var(--background)`,gutterBackground:`var(--muted)`}});function pg(e){let t=(0,$.c)(20),{oldContent:n,newContent:r,layout:i,conflictMode:a,onResolve:o,onAbort:s}=e,c=(0,Q.useRef)(null),l=(0,Q.useRef)(null),{resolvedTheme:u}=yr(),d=(0,Q.useRef)(o),f=(0,Q.useRef)(s),[p,m]=(0,Q.useState)(null),h;t[0]!==s||t[1]!==o?(h=()=>{d.current=o,f.current=s},t[0]=s,t[1]=o,t[2]=h):h=t[2],(0,Q.useEffect)(h);let g,v;t[3]!==a||t[4]!==i||t[5]!==r||t[6]!==n||t[7]!==u?(g=()=>{if(!c.current)return;let e=u===`dark`?dg:fg,t=[ko.editable.of(!1),yo.readOnly.of(!0)],o=[Ro,_(),...t,e,ko.lineWrapping];if(l.current&&=(l.current.destroy(),null),a){let t=new ko({doc:r,extensions:[Ro,_(),ko.editable.of(!1),e,ko.lineWrapping,Yh({original:n,highlightChanges:!0,gutter:!0,mergeControls:!0,collapseUnchanged:{margin:3,minSize:4}}),ko.updateListener.of(e=>{let t=ch(e.state);m(t?t.chunks.length:0)})],parent:c.current});l.current=t;let i=ch(t.state);m(i?i.chunks.length:0)}else i===`split`?l.current=new Gh({a:{doc:n,extensions:o},b:{doc:r,extensions:o},parent:c.current,highlightChanges:!0,gutter:!0,collapseUnchanged:{margin:3,minSize:4}}):l.current=new ko({doc:r,extensions:[...o,Yh({original:n,highlightChanges:!0,gutter:!0,mergeControls:!1,collapseUnchanged:{margin:3,minSize:4}})],parent:c.current});return()=>{l.current&&=(l.current.destroy(),null)}},v=[n,r,i,u,a],t[3]=a,t[4]=i,t[5]=r,t[6]=n,t[7]=u,t[8]=g,t[9]=v):(g=t[8],v=t[9]),(0,Q.useEffect)(g,v);let y;t[10]===Symbol.for(`react.memo_cache_sentinel`)?(y=function(){let e=l.current;!e||!(e instanceof ko)||d.current?.(e.state.doc.toString())},t[10]=y):y=t[10];let b=y,x=p===0,S=p===null?``:p===0?`All hunks resolved`:`${p} unresolved hunk${p===1?``:`s`}`,C;t[11]===Symbol.for(`react.memo_cache_sentinel`)?(C=(0,Z.jsx)(`div`,{ref:c,className:`diff-view min-h-0 flex-1 overflow-y-auto subtle-scrollbar`}),t[11]=C):C=t[11];let w;t[12]!==x||t[13]!==a||t[14]!==S||t[15]!==s||t[16]!==o?(w=a&&(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2 px-3 py-2 border-t shrink-0`,children:[(0,Z.jsx)(`span`,{className:`text-xs ${x?`text-emerald-600 dark:text-emerald-400`:`text-muted-foreground`}`,children:S}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[s&&(0,Z.jsx)(X,{variant:`ghost`,size:`sm`,onClick:s,children:`Exit merge`}),o&&(0,Z.jsx)(X,{variant:`default`,size:`sm`,disabled:!x,onClick:b,children:`Save resolution`})]})]}),t[12]=x,t[13]=a,t[14]=S,t[15]=s,t[16]=o,t[17]=w):w=t[17];let T;return t[18]===w?T=t[19]:(T=(0,Z.jsxs)(`div`,{className:`flex flex-col h-full`,children:[C,w]}),t[18]=w,t[19]=T),T}function mg(e){let t=(0,$.c)(4),n;t[0]===e?n=t[1]:({...n}=e,t[0]=e,t[1]=n);let r;return t[2]===n?r=t[3]:(r=(0,Z.jsx)(Ua,{"data-slot":`sheet`,...n}),t[2]=n,t[3]=r),r}function hg(e){let t=(0,$.c)(4),n;t[0]===e?n=t[1]:({...n}=e,t[0]=e,t[1]=n);let r;return t[2]===n?r=t[3]:(r=(0,Z.jsx)(Ka,{"data-slot":`sheet-portal`,...n}),t[2]=n,t[3]=r),r}function gg(e){let t=(0,$.c)(8),n,r;t[0]===e?(n=t[1],r=t[2]):({className:n,...r}=e,t[0]=e,t[1]=n,t[2]=r);let i;t[3]===n?i=t[4]:(i=Y(`fixed inset-0 z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0`,n),t[3]=n,t[4]=i);let a;return t[5]!==r||t[6]!==i?(a=(0,Z.jsx)(za,{"data-slot":`sheet-overlay`,className:i,...r}),t[5]=r,t[6]=i,t[7]=a):a=t[7],a}function _g(e){let t=(0,$.c)(17),n,r,i,a,o;t[0]===e?(n=t[1],r=t[2],i=t[3],a=t[4],o=t[5]):({className:r,children:n,side:a,showCloseButton:o,...i}=e,t[0]=e,t[1]=n,t[2]=r,t[3]=i,t[4]=a,t[5]=o);let s=a===void 0?`right`:a,c=o===void 0?!0:o,l;t[6]===Symbol.for(`react.memo_cache_sentinel`)?(l=(0,Z.jsx)(gg,{}),t[6]=l):l=t[6];let u;t[7]===r?u=t[8]:(u=Y(`fixed z-50 flex flex-col gap-4 bg-popover bg-clip-padding text-sm text-popover-foreground shadow-lg transition duration-200 ease-in-out data-[side=bottom]:inset-x-0 data-[side=bottom]:bottom-0 data-[side=bottom]:h-auto data-[side=bottom]:border-t data-[side=left]:inset-y-0 data-[side=left]:left-0 data-[side=left]:h-full data-[side=left]:w-3/4 data-[side=left]:border-r data-[side=right]:inset-y-0 data-[side=right]:right-0 data-[side=right]:h-full data-[side=right]:w-3/4 data-[side=right]:border-l data-[side=top]:inset-x-0 data-[side=top]:top-0 data-[side=top]:h-auto data-[side=top]:border-b data-[side=left]:sm:max-w-sm data-[side=right]:sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-[side=bottom]:data-open:slide-in-from-bottom-10 data-[side=left]:data-open:slide-in-from-left-10 data-[side=right]:data-open:slide-in-from-right-10 data-[side=top]:data-open:slide-in-from-top-10 data-closed:animate-out data-closed:fade-out-0 data-[side=bottom]:data-closed:slide-out-to-bottom-10 data-[side=left]:data-closed:slide-out-to-left-10 data-[side=right]:data-closed:slide-out-to-right-10 data-[side=top]:data-closed:slide-out-to-top-10`,r),t[7]=r,t[8]=u);let d;t[9]===c?d=t[10]:(d=c&&(0,Z.jsx)(Ha,{"data-slot":`sheet-close`,asChild:!0,children:(0,Z.jsxs)(X,{variant:`ghost`,className:`absolute top-3 right-3`,size:`icon-sm`,children:[(0,Z.jsx)(Fa,{}),(0,Z.jsx)(`span`,{className:`sr-only`,children:`Close`})]})}),t[9]=c,t[10]=d);let f;return t[11]!==n||t[12]!==i||t[13]!==s||t[14]!==u||t[15]!==d?(f=(0,Z.jsxs)(hg,{children:[l,(0,Z.jsxs)(Ya,{"data-slot":`sheet-content`,"data-side":s,className:u,...i,children:[n,d]})]}),t[11]=n,t[12]=i,t[13]=s,t[14]=u,t[15]=d,t[16]=f):f=t[16],f}function vg(e){let t=(0,$.c)(8),n,r;t[0]===e?(n=t[1],r=t[2]):({className:n,...r}=e,t[0]=e,t[1]=n,t[2]=r);let i;t[3]===n?i=t[4]:(i=Y(`flex flex-col gap-0.5 p-4`,n),t[3]=n,t[4]=i);let a;return t[5]!==r||t[6]!==i?(a=(0,Z.jsx)(`div`,{"data-slot":`sheet-header`,className:i,...r}),t[5]=r,t[6]=i,t[7]=a):a=t[7],a}function yg(e){let t=(0,$.c)(8),n,r;t[0]===e?(n=t[1],r=t[2]):({className:n,...r}=e,t[0]=e,t[1]=n,t[2]=r);let i;t[3]===n?i=t[4]:(i=Y(`font-heading text-base font-medium text-foreground`,n),t[3]=n,t[4]=i);let a;return t[5]!==r||t[6]!==i?(a=(0,Z.jsx)(Ba,{"data-slot":`sheet-title`,className:i,...r}),t[5]=r,t[6]=i,t[7]=a):a=t[7],a}async function bg(){try{let e=await fetch(`/api/sync/conflicts`);return e.ok?{conflicts:(await e.json()).conflicts??[]}:{conflicts:[],error:`server`}}catch{return{conflicts:[],error:`network`}}}async function xg(e){try{let t=await fetch(`/api/sync/conflict-content?file=${encodeURIComponent(e)}`);if(!t.ok)return{ours:``,theirs:``,base:``};let n=await t.json();return{ours:n.ours??``,theirs:n.theirs??``,base:n.base??``}}catch{return{ours:``,theirs:``,base:``}}}async function Sg(e,t,n){try{let r={file:e,strategy:t};return n!==void 0&&(r.content=n),(await fetch(`/api/sync/resolve-conflict`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r)})).ok}catch{return!1}}var Cg=`w-[98vw] !max-w-[98vw] h-[96vh] flex flex-col gap-0 sm:!max-w-[98vw]`;function wg(e){let t=(0,$.c)(31),{file:n,onResolve:r,onAbort:i}=e,[a,o]=(0,Q.useState)(null),s,c;if(t[0]===n?(s=t[1],c=t[2]):(s=()=>{let e=!1;return xg(n).then(t=>{e||o(t)}),()=>{e=!0}},c=[n],t[0]=n,t[1]=s,t[2]=c),(0,Q.useEffect)(s,c),a===null){let e;t[3]===i?e=t[4]:(e=e=>!e&&i(),t[3]=i,t[4]=e);let r;t[5]===n?r=t[6]:(r=(0,Z.jsx)(qa,{className:`shrink-0`,children:(0,Z.jsxs)(Ra,{children:[`Resolving: `,n]})}),t[5]=n,t[6]=r);let a;t[7]===Symbol.for(`react.memo_cache_sentinel`)?(a=(0,Z.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-sm text-muted-foreground`,children:`Loading`}),t[7]=a):a=t[7];let o;t[8]===r?o=t[9]:(o=(0,Z.jsxs)(Va,{className:Cg,children:[r,a]}),t[8]=r,t[9]=o);let s;return t[10]!==e||t[11]!==o?(s=(0,Z.jsx)(Ja,{open:!0,onOpenChange:e,children:o}),t[10]=e,t[11]=o,t[12]=s):s=t[12],s}let l;t[13]===i?l=t[14]:(l=e=>!e&&i(),t[13]=i,t[14]=l);let u;t[15]===n?u=t[16]:(u=(0,Z.jsxs)(Ra,{className:`text-sm font-medium`,children:[`Resolving: `,n]}),t[15]=n,t[16]=u);let d;t[17]===Symbol.for(`react.memo_cache_sentinel`)?(d=(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Red = your version (ours). Green = team's version (theirs). Accept each hunk to take theirs, reject to keep yours, then save.`}),t[17]=d):d=t[17];let f;t[18]===u?f=t[19]:(f=(0,Z.jsxs)(qa,{className:`px-4 pt-4 pb-2 shrink-0`,children:[u,d]}),t[18]=u,t[19]=f);let p;t[20]!==i||t[21]!==r||t[22]!==a.ours||t[23]!==a.theirs?(p=(0,Z.jsx)(`div`,{className:`flex-1 min-h-0 overflow-hidden`,children:(0,Z.jsx)(pg,{oldContent:a.ours,newContent:a.theirs,layout:`unified`,conflictMode:!0,onResolve:r,onAbort:i})}),t[20]=i,t[21]=r,t[22]=a.ours,t[23]=a.theirs,t[24]=p):p=t[24];let m;t[25]!==f||t[26]!==p?(m=(0,Z.jsxs)(Va,{className:`${Cg} p-0`,children:[f,p]}),t[25]=f,t[26]=p,t[27]=m):m=t[27];let h;return t[28]!==l||t[29]!==m?(h=(0,Z.jsx)(Ja,{open:!0,onOpenChange:l,children:m}),t[28]=l,t[29]=m,t[30]=h):h=t[30],h}function Tg(e){let t=(0,$.c)(50),{open:n,onOpenChange:r}=e,i;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(i=[],t[0]=i):i=t[0];let[a,o]=(0,Q.useState)(i),[s,c]=(0,Q.useState)(null),l;t[1]===Symbol.for(`react.memo_cache_sentinel`)?(l=new Set,t[1]=l):l=t[1];let[u,d]=(0,Q.useState)(l),f;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(f=new Set,t[2]=f):f=t[2];let[p,m]=(0,Q.useState)(f),[h,g]=(0,Q.useState)(null),_;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(_=function(){bg().then(e=>{let{conflicts:t,error:n}=e;c(n??null),o(t),d(e=>{let n=new Set(t.map(Eg));return new Set([...e].filter(e=>!n.has(e)))})})},t[3]=_):_=t[3];let v=_,y,b;t[4]===n?(y=t[5],b=t[6]):(y=()=>{n&&v()},b=[n],t[4]=n,t[5]=y,t[6]=b),(0,Q.useEffect)(y,b);let x,S;t[7]===n?(x=t[8],S=t[9]):(x=()=>_r(e=>{e.includes(`sync-status`)&&n&&v()}),S=[n],t[7]=n,t[8]=x,t[9]=S),(0,Q.useEffect)(x,S);let C,w;t[10]!==a.length||t[11]!==r||t[12]!==n||t[13]!==u.size?(w=()=>{n&&a.length>0&&u.size>=a.length&&(Xa.success(`All conflicts resolved — sync resuming`),r(!1),d(new Set))},C=[n,a.length,u.size,r],t[10]=a.length,t[11]=r,t[12]=n,t[13]=u.size,t[14]=C,t[15]=w):(C=t[14],w=t[15]),(0,Q.useEffect)(w,C);let T;t[16]===Symbol.for(`react.memo_cache_sentinel`)?(T=async function(e,t,n){m(t=>new Set([...t,e]));let r=await Sg(e,t,n);m(t=>{let n=new Set(t);return n.delete(e),n}),r?d(t=>new Set([...t,e])):Xa.error(`Failed to resolve ${e}`)},t[16]=T):T=t[16];let E=T,D;t[17]===Symbol.for(`react.memo_cache_sentinel`)?(D=function(e){g(e)},t[17]=D):D=t[17];let O=D,k;t[18]===h?k=t[19]:(k=async function(e){if(!h)return;let t=h;g(null),await E(t,`content`,e)},t[18]=h,t[19]=k);let A=k,j;t[20]===Symbol.for(`react.memo_cache_sentinel`)?(j=function(){g(null)},t[20]=j):j=t[20];let M=j,N;t[21]===r?N=t[22]:(N=async function(){try{(await fetch(`/api/sync/abort-merge`,{method:`POST`})).ok?Xa.info(`Merge aborted — sync paused`):Xa.error(`Failed to abort merge`)}catch{Xa.error(`Failed to abort merge — connection error`)}r(!1),d(new Set)},t[21]=r,t[22]=N);let P=N,F=a.length,I=u.size,L;t[23]===Symbol.for(`react.memo_cache_sentinel`)?(L=(0,Z.jsx)(yg,{className:`text-sm font-medium`,children:`Resolve conflicts`}),t[23]=L):L=t[23];let R;t[24]!==I||t[25]!==F?(R=F>0&&(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[I,` of `,F,` resolved`]}),t[24]=I,t[25]=F,t[26]=R):R=t[26];let z;t[27]===R?z=t[28]:(z=(0,Z.jsxs)(vg,{className:`px-4 py-3 border-b shrink-0`,children:[L,R]}),t[27]=R,t[28]=z);let B;t[29]!==a||t[30]!==s||t[31]!==u||t[32]!==p?(B=(0,Z.jsx)(`div`,{className:`flex-1 overflow-y-auto subtle-scrollbar`,children:s?(0,Z.jsxs)(`div`,{className:`px-4 py-6 text-sm text-center space-y-2`,children:[(0,Z.jsx)(`p`,{className:`text-destructive`,children:s===`network`?`Could not reach the sync server — check your connection.`:`Sync server error — try again in a moment.`}),(0,Z.jsx)(X,{variant:`outline`,size:`sm`,onClick:v,children:`Retry`})]}):a.length===0?(0,Z.jsx)(`p`,{className:`px-4 py-6 text-sm text-muted-foreground text-center`,children:`No conflicts found.`}):(0,Z.jsx)(`ul`,{className:`divide-y`,children:a.map(e=>{let t=u.has(e.file),n=p.has(e.file),r=e.file.split(`/`).pop()??e.file;return(0,Z.jsxs)(`li`,{className:`px-4 py-3 ${t?`opacity-50`:``}`,children:[(0,Z.jsxs)(`p`,{className:`text-sm font-medium truncate mb-2`,title:e.file,children:[t?`✓ `:``,r]}),!t&&(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-1`,children:[(0,Z.jsx)(X,{variant:`outline`,size:`xs`,disabled:n,onClick:()=>void E(e.file,`mine`),children:`Keep my version`}),(0,Z.jsx)(X,{variant:`outline`,size:`xs`,disabled:n,onClick:()=>void E(e.file,`theirs`),children:`Keep team's version`}),(0,Z.jsx)(X,{variant:`ghost`,size:`xs`,disabled:n,onClick:()=>O(e.file),children:`Resolve manually`})]})]},e.file)})})}),t[29]=a,t[30]=s,t[31]=u,t[32]=p,t[33]=B):B=t[33];let V;t[34]===P?V=t[35]:(V=(0,Z.jsx)(`div`,{className:`px-4 py-3 border-t shrink-0`,children:(0,Z.jsx)(X,{variant:`ghost`,size:`sm`,className:`w-full`,onClick:P,children:`Exit merge`})}),t[34]=P,t[35]=V);let H;t[36]!==z||t[37]!==B||t[38]!==V?(H=(0,Z.jsxs)(_g,{side:`right`,className:`w-80 sm:w-96 flex flex-col gap-0 p-0`,children:[z,B,V]}),t[36]=z,t[37]=B,t[38]=V,t[39]=H):H=t[39];let U;t[40]!==r||t[41]!==n||t[42]!==H?(U=(0,Z.jsx)(mg,{open:n,onOpenChange:r,children:H}),t[40]=r,t[41]=n,t[42]=H,t[43]=U):U=t[43];let W;t[44]!==A||t[45]!==h?(W=h&&(0,Z.jsx)(wg,{file:h,onResolve:e=>void A(e),onAbort:M}),t[44]=A,t[45]=h,t[46]=W):W=t[46];let G;return t[47]!==U||t[48]!==W?(G=(0,Z.jsxs)(Z.Fragment,{children:[U,W]}),t[47]=U,t[48]=W,t[49]=G):G=t[49],G}function Eg(e){return e.file}var Dg=5;async function Og(e){let t=await fetch(`/api/backlinks?docName=${encodeURIComponent(e)}`),n=await t.json().catch(()=>null);if(!t.ok){let e=ir.safeParse(n);throw e.success?Error(e.data.title):new Ce(`Failed to parse backlinks error response (HTTP ${t.status})`,{status:t.status})}let r=fn.safeParse(n);if(!r.success)throw new Ce(`Backlinks response did not match expected shape.`,{status:t.status});return r.data.backlinks}async function kg(e){let t=await fetch(`/api/forward-links?docName=${encodeURIComponent(e)}`),n=await t.json().catch(()=>null);if(!t.ok){let e=ir.safeParse(n);throw e.success?Error(e.data.title):new Ce(`Failed to parse forward-links error response (HTTP ${t.status})`,{status:t.status})}let r=Zn.safeParse(n);if(!r.success)throw new Ce(`Forward-links response did not match expected shape.`,{status:t.status});return r.data.forwardLinks}function Ag(e){let t=e.split(`/`);return t.length<=2?e:`…/${t.slice(-2).join(`/`)}`}function jg(e){window.location.hash=er(e)}function Mg(e){let t=(0,$.c)(9),{title:n,count:r,isLoading:i}=e,a;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(a=(0,Z.jsx)(Ie,{className:`size-3.5 text-muted-foreground transition-transform group-data-[state=closed]:-rotate-90`}),t[0]=a):a=t[0];let o;t[1]===n?o=t[2]:(o=(0,Z.jsxs)(`span`,{className:`flex items-center gap-2.5`,children:[a,(0,Z.jsx)(Gt,{children:n})]}),t[1]=n,t[2]=o);let s;t[3]!==r||t[4]!==i?(s=!i&&(0,Z.jsx)(Wt,{children:r}),t[3]=r,t[4]=i,t[5]=s):s=t[5];let c;return t[6]!==o||t[7]!==s?(c=(0,Z.jsxs)(R,{className:`group flex w-full cursor-pointer items-center justify-between px-5 py-3 text-left transition-colors hover:bg-muted/40`,children:[o,s]}),t[6]=o,t[7]=s,t[8]=c):c=t[8],c}function Ng(e){let t=(0,$.c)(7),{total:n,expanded:r,onToggle:i}=e;if(n<=Dg)return null;let a=n-Dg,o;t[0]===r?o=t[1]:(o=r?(0,Z.jsx)(Ie,{className:`size-3`}):(0,Z.jsx)(l,{className:`size-3`}),t[0]=r,t[1]=o);let s=r?`Show fewer`:`Show ${a} more`,c;return t[2]!==r||t[3]!==i||t[4]!==o||t[5]!==s?(c=(0,Z.jsxs)(`button`,{type:`button`,"aria-expanded":r,className:`mt-2 inline-flex cursor-pointer items-center gap-1 px-3 text-xs text-muted-foreground transition-colors hover:text-foreground`,onClick:i,children:[o,s]}),t[2]=r,t[3]=i,t[4]=o,t[5]=s,t[6]=c):c=t[6],c}function Pg(e){let t=(0,$.c)(38),{icon:n,iconColorClass:r,rowTooltip:i,title:a,path:o,anchor:s,snippet:c,titleHover:l,ariaLabel:u,href:d,external:f,disabled:p,onClick:m,hoverAction:h}=e,g=o!==void 0&&o!==a,_=r??`text-muted-foreground`,v;t[0]===_?v=t[1]:(v=Y(`mt-0.5 shrink-0`,_),t[0]=_,t[1]=v);let y;t[2]!==n||t[3]!==v?(y=(0,Z.jsx)(`span`,{className:v,children:n}),t[2]=n,t[3]=v,t[4]=y):y=t[4];let b=y,x;t[5]!==u||t[6]!==p||t[7]!==f||t[8]!==d||t[9]!==m||t[10]!==a||t[11]!==l?(x=d?(0,Z.jsxs)(`a`,{href:d,target:f?`_blank`:void 0,rel:f?`noopener noreferrer`:void 0,"aria-label":u,title:l,onClick:m,className:`block w-full truncate text-left font-medium text-foreground no-underline outline-none after:absolute after:inset-0 after:rounded-md focus-visible:after:ring-2 focus-visible:after:ring-ring`,children:[a,f?(0,Z.jsx)(`span`,{className:`sr-only`,children:` (opens in new tab)`}):null]}):(0,Z.jsx)(`button`,{type:`button`,"aria-label":u,title:l,disabled:p,onClick:m,className:Y(`block w-full truncate text-left font-medium text-foreground no-underline outline-none after:absolute after:inset-0 after:rounded-md focus-visible:after:ring-2 focus-visible:after:ring-ring`,`cursor-pointer bg-transparent p-0 disabled:cursor-not-allowed disabled:opacity-60`),children:a}),t[5]=u,t[6]=p,t[7]=f,t[8]=d,t[9]=m,t[10]=a,t[11]=l,t[12]=x):x=t[12];let S=x,C;t[13]===b?C=t[14]:(C=(0,Z.jsx)(`div`,{className:`mt-px flex items-center`,children:b}),t[13]=b,t[14]=C);let w;t[15]!==s||t[16]!==o||t[17]!==g?(w=g?(0,Z.jsxs)(`div`,{className:`truncate font-mono text-xs text-muted-foreground`,children:[o,s?(0,Z.jsxs)(`span`,{className:`ml-1`,children:[`· #`,s]}):null]}):null,t[15]=s,t[16]=o,t[17]=g,t[18]=w):w=t[18];let T;t[19]===c?T=t[20]:(T=c?(0,Z.jsx)(`p`,{className:`line-clamp-2 text-muted-foreground`,children:c}):null,t[19]=c,t[20]=T);let E;t[21]!==S||t[22]!==w||t[23]!==T?(E=(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-0.5 text-1sm`,children:[S,w,T]}),t[21]=S,t[22]=w,t[23]=T,t[24]=E):E=t[24];let D;t[25]===h?D=t[26]:(D=h?(0,Z.jsxs)(uo,{children:[(0,Z.jsx)(so,{asChild:!0,children:(0,Z.jsx)(`button`,{type:`button`,"aria-label":h.tooltip,disabled:h.disabled,className:`relative z-10 shrink-0 cursor-pointer rounded-md p-1 text-muted-foreground opacity-0 transition-opacity hover:bg-accent hover:text-foreground focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:bg-transparent disabled:hover:text-muted-foreground group-hover:opacity-100`,onClick:h.onClick,children:h.icon})}),(0,Z.jsx)(co,{side:`top`,children:h.tooltip})]}):null,t[25]=h,t[26]=D);let O;t[27]!==C||t[28]!==E||t[29]!==D?(O=(0,Z.jsxs)(`div`,{className:`group relative flex items-start gap-2.5 rounded-md px-3 py-2.5 transition-colors hover:bg-muted/80`,children:[C,E,D]}),t[27]=C,t[28]=E,t[29]=D,t[30]=O):O=t[30];let k=O;if(i){let e;t[31]===k?e=t[32]:(e=(0,Z.jsx)(so,{asChild:!0,children:k}),t[31]=k,t[32]=e);let n;t[33]===i?n=t[34]:(n=(0,Z.jsx)(co,{side:`top`,children:i}),t[33]=i,t[34]=n);let r;return t[35]!==e||t[36]!==n?(r=(0,Z.jsxs)(uo,{children:[e,n]}),t[35]=e,t[36]=n,t[37]=r):r=t[37],r}return k}function Fg(e){let t=(0,$.c)(33),{docName:n}=e,{folderPaths:r,pages:i,loading:a}=wr(),o,s;t[0]===n?(o=t[1],s=t[2]):(o=[`backlinks`,n],s=()=>Og(n),t[0]=n,t[1]=o,t[2]=s);let c;t[3]!==n||t[4]!==a||t[5]!==i?(c=!a&&i.has(n),t[3]=n,t[4]=a,t[5]=i,t[6]=c):c=t[6];let l;t[7]!==o||t[8]!==s||t[9]!==c?(l={queryKey:o,queryFn:s,enabled:c},t[7]=o,t[8]=s,t[9]=c,t[10]=l):l=t[10];let{data:u,isLoading:d,error:f}=Nt(l),m;t[11]===u?m=t[12]:(m=u===void 0?[]:u,t[11]=u,t[12]=m);let h=m,[g,_]=(0,Q.useState)(!1),[v,y]=(0,Q.useState)(n);v!==n&&(y(n),_(!1));let b;t[13]!==h||t[14]!==g?(b=g?h:h.slice(0,Dg),t[13]=h,t[14]=g,t[15]=b):b=t[15];let x=b,S;t[16]!==h.length||t[17]!==d?(S=(0,Z.jsx)(Mg,{title:`Backlinks`,count:h.length,isLoading:d}),t[16]=h.length,t[17]=d,t[18]=S):S=t[18];let C;t[19]!==h.length||t[20]!==f||t[21]!==g||t[22]!==r||t[23]!==d||t[24]!==i||t[25]!==x?(C=f?(0,Z.jsx)(`div`,{className:`px-3`,children:(0,Z.jsx)(jt,{children:f instanceof Error?f.message:`Failed to load backlinks`})}):h.length===0&&!d?(0,Z.jsx)(`div`,{className:`px-3`,children:(0,Z.jsx)(Rt,{children:`No pages link here yet.`})}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`flex flex-col gap-1`,children:x.map((e,t)=>{let n=Na(e.source,{pages:i,folderPaths:r});return(0,Z.jsx)(Pg,{icon:(0,Z.jsx)(p,{className:`size-3.5`}),title:e.title,path:Ag(e.source),titleHover:e.source,anchor:e.anchor,snippet:e.snippet,href:er(n.hashDocName,e.anchor)},`${e.source}-${t}`)})}),(0,Z.jsx)(Ng,{total:h.length,expanded:g,onToggle:()=>_(Ig)})]}),t[19]=h.length,t[20]=f,t[21]=g,t[22]=r,t[23]=d,t[24]=i,t[25]=x,t[26]=C):C=t[26];let w;t[27]!==d||t[28]!==C?(w=(0,Z.jsx)(N,{children:(0,Z.jsx)(`div`,{className:`px-2 pb-3`,"aria-busy":d,children:C})}),t[27]=d,t[28]=C,t[29]=w):w=t[29];let T;return t[30]!==w||t[31]!==S?(T=(0,Z.jsxs)(A,{defaultOpen:!0,children:[S,w]}),t[30]=w,t[31]=S,t[32]=T):T=t[32],T}function Ig(e){return!e}function Lg(e){let t=(0,$.c)(42),{docName:n}=e,{addPage:r,folderPaths:i,pages:a,pagesBySlug:o,loading:s}=wr(),c,l;t[0]===n?(c=t[1],l=t[2]):(c=[`forward-links`,n],l=()=>kg(n),t[0]=n,t[1]=c,t[2]=l);let u;t[3]!==n||t[4]!==a||t[5]!==s?(u=!s&&a.has(n),t[3]=n,t[4]=a,t[5]=s,t[6]=u):u=t[6];let f;t[7]!==c||t[8]!==l||t[9]!==u?(f={queryKey:c,queryFn:l,enabled:u},t[7]=c,t[8]=l,t[9]=u,t[10]=f):f=t[10];let{data:m,isLoading:h,error:g}=Nt(f),_;t[11]===m?_=t[12]:(_=m===void 0?[]:m,t[11]=m,t[12]=_);let v=_,[y,b]=(0,Q.useState)(null),[x,S]=(0,Q.useState)(!1),[C,w]=(0,Q.useState)(n);C!==n&&(w(n),S(!1),b(null));let T;t[13]!==x||t[14]!==v?(T=x?v:v.slice(0,Dg),t[13]=x,t[14]=v,t[15]=T):T=t[15];let E=T,D;t[16]!==r||t[17]!==y?(D=async function(e,t){if(!y){b(t);try{await U(e,{addPage:r,onCreated:jg}),b(null)}catch(e){let t=e;Xa.error(t instanceof Error?t.message:`Failed to create page`),b(null)}}},t[16]=r,t[17]=y,t[18]=D):D=t[18];let O=D,k;t[19]!==y||t[20]!==i||t[21]!==O||t[22]!==a||t[23]!==o||t[24]!==s?(k=function(e){if(e.kind===`external`){let t=e.title===e.url;return(0,Z.jsx)(Pg,{icon:(0,Z.jsx)(Ma,{className:`size-3.5`}),rowTooltip:`Opens in a new tab`,title:e.title,path:t?void 0:e.url,titleHover:e.url,snippet:e.snippet,href:e.url,external:!0},`ext:${e.url}`)}let t=d(e.docName,{pages:a,folderPaths:i,pagesBySlug:o}),n=!s&&t.kind===`create`,r=!s&&t.kind===`navigate`&&t.displayState===`folder`,c=Ag(e.docName),l=e.title===e.docName?c:e.title,u=`doc:${e.docName}:${e.anchor??``}`,f=er(t.kind===`navigate`?t.hashDocName:e.docName,e.anchor);if(n&&t.kind===`create`){let n={initialDir:t.initialDir,suggestedName:t.suggestedName};return(0,Z.jsx)(Pg,{icon:(0,Z.jsx)(Dn,{className:`size-3.5`}),iconColorClass:`text-amber-600 dark:text-amber-400`,rowTooltip:y===u?`Creating page`:`Missing page — click to create`,ariaLabel:y===u?`Creating page: ${e.title}.`:`Missing page: ${e.title}. Click to create.`,title:l,path:c,titleHover:e.docName,anchor:e.anchor,snippet:e.snippet,disabled:y!==null,onClick:()=>void O(n,u)},u)}if(r&&t.kind===`navigate`){let n=xt(t);return(0,Z.jsx)(Pg,{icon:(0,Z.jsx)(ks,{className:`size-3.5`}),iconColorClass:`text-sky-600 dark:text-sky-400`,ariaLabel:`Folder target: ${e.title}. Click to open the overview.`,title:l,path:c,titleHover:e.docName,anchor:e.anchor,snippet:e.snippet,href:f,hoverAction:{icon:(0,Z.jsx)(Fi,{className:`size-3.5`}),tooltip:y===u?`Creating index note`:`Create index note`,disabled:y!==null||n===null,onClick:()=>{n&&O(n,u)}}},u)}return(0,Z.jsx)(Pg,{icon:(0,Z.jsx)(p,{className:`size-3.5`}),title:l,path:c,titleHover:e.docName,anchor:e.anchor,snippet:e.snippet,href:f},u)},t[19]=y,t[20]=i,t[21]=O,t[22]=a,t[23]=o,t[24]=s,t[25]=k):k=t[25];let j=k,M;t[26]!==h||t[27]!==v.length?(M=(0,Z.jsx)(Mg,{title:`Outgoing`,count:v.length,isLoading:h}),t[26]=h,t[27]=v.length,t[28]=M):M=t[28];let P;t[29]!==g||t[30]!==x||t[31]!==h||t[32]!==v.length||t[33]!==j||t[34]!==E?(P=g?(0,Z.jsx)(`div`,{className:`px-3`,children:(0,Z.jsx)(jt,{children:g instanceof Error?g.message:`Failed to load outgoing links`})}):v.length===0&&!h?(0,Z.jsx)(`div`,{className:`px-3`,children:(0,Z.jsx)(Rt,{children:`This page doesn't link to anything yet.`})}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`flex flex-col gap-1`,children:E.map(j)}),(0,Z.jsx)(Ng,{total:v.length,expanded:x,onToggle:()=>S(Rg)})]}),t[29]=g,t[30]=x,t[31]=h,t[32]=v.length,t[33]=j,t[34]=E,t[35]=P):P=t[35];let F;t[36]!==h||t[37]!==P?(F=(0,Z.jsx)(N,{children:(0,Z.jsx)(`div`,{className:`px-2 pb-3`,"aria-busy":h,children:P})}),t[36]=h,t[37]=P,t[38]=F):F=t[38];let I;return t[39]!==M||t[40]!==F?(I=(0,Z.jsxs)(A,{defaultOpen:!0,children:[M,F]}),t[39]=M,t[40]=F,t[41]=I):I=t[41],I}function Rg(e){return!e}function zg(e){let t=(0,$.c)(11),{docName:n,className:r}=e,i=r===void 0?``:r,a;t[0]===n?a=t[1]:(a=(0,Z.jsx)(Lg,{docName:n}),t[0]=n,t[1]=a);let o;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(o=(0,Z.jsx)(Bi,{}),t[2]=o):o=t[2];let s;t[3]===n?s=t[4]:(s=(0,Z.jsx)(Fg,{docName:n}),t[3]=n,t[4]=s);let c;t[5]!==a||t[6]!==s?(c=(0,Z.jsxs)(Ht,{className:`px-0 py-0`,children:[a,o,s]}),t[5]=a,t[6]=s,t[7]=c):c=t[7];let l;return t[8]!==i||t[9]!==c?(l=(0,Z.jsx)(Kt,{className:i,children:c}),t[8]=i,t[9]=c,t[10]=l):l=t[10],l}var Bg=class{diff(e,t,n={}){let r;typeof n==`function`?(r=n,n={}):`callback`in n&&(r=n.callback);let i=this.castInput(e,n),a=this.castInput(t,n),o=this.removeEmpty(this.tokenize(i,n)),s=this.removeEmpty(this.tokenize(a,n));return this.diffWithOptionsObj(o,s,n,r)}diffWithOptionsObj(e,t,n,r){let i=e=>{if(e=this.postProcess(e,n),r){setTimeout(function(){r(e)},0);return}else return e},a=t.length,o=e.length,s=1,c=a+o;n.maxEditLength!=null&&(c=Math.min(c,n.maxEditLength));let l=n.timeout??1/0,u=Date.now()+l,d=[{oldPos:-1,lastComponent:void 0}],f=this.extractCommon(d[0],t,e,0,n);if(d[0].oldPos+1>=o&&f+1>=a)return i(this.buildValues(d[0].lastComponent,t,e));let p=-1/0,m=1/0,h=()=>{for(let r=Math.max(p,-s);r<=Math.min(m,s);r+=2){let s,c=d[r-1],l=d[r+1];c&&(d[r-1]=void 0);let u=!1;if(l){let e=l.oldPos-r;u=l&&0<=e&&e<a}let h=c&&c.oldPos+1<o;if(!u&&!h){d[r]=void 0;continue}if(s=!h||u&&c.oldPos<l.oldPos?this.addToPath(l,!0,!1,0,n):this.addToPath(c,!1,!0,1,n),f=this.extractCommon(s,t,e,r,n),s.oldPos+1>=o&&f+1>=a)return i(this.buildValues(s.lastComponent,t,e))||!0;d[r]=s,s.oldPos+1>=o&&(m=Math.min(m,r-1)),f+1>=a&&(p=Math.max(p,r+1))}s++};if(r)(function e(){setTimeout(function(){if(s>c||Date.now()>u)return r(void 0);h()||e()},0)})();else for(;s<=c&&Date.now()<=u;){let e=h();if(e)return e}}addToPath(e,t,n,r,i){let a=e.lastComponent;return a&&!i.oneChangePerToken&&a.added===t&&a.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:a.count+1,added:t,removed:n,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:a}}}extractCommon(e,t,n,r,i){let a=t.length,o=n.length,s=e.oldPos,c=s-r,l=0;for(;c+1<a&&s+1<o&&this.equals(n[s+1],t[c+1],i);)c++,s++,l++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return l&&!i.oneChangePerToken&&(e.lastComponent={count:l,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=s,c}equals(e,t,n){return n.comparator?n.comparator(e,t):e===t||!!n.ignoreCase&&e.toLowerCase()===t.toLowerCase()}removeEmpty(e){let t=[];for(let n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t}castInput(e,t){return e}tokenize(e,t){return Array.from(e)}join(e){return e.join(``)}postProcess(e,t){return e}get useLongestToken(){return!1}buildValues(e,t,n){let r=[],i;for(;e;)r.push(e),i=e.previousComponent,delete e.previousComponent,e=i;r.reverse();let a=r.length,o=0,s=0,c=0;for(;o<a;o++){let e=r[o];if(e.removed)e.value=this.join(n.slice(c,c+e.count)),c+=e.count;else{if(!e.added&&this.useLongestToken){let r=t.slice(s,s+e.count);r=r.map(function(e,t){let r=n[c+t];return r.length>e.length?r:e}),e.value=this.join(r)}else e.value=this.join(t.slice(s,s+e.count));s+=e.count,e.added||(c+=e.count)}}return r}};new class extends Bg{};function Vg(e,t){let n;for(n=0;n<e.length&&n<t.length;n++)if(e[n]!=t[n])return e.slice(0,n);return e.slice(0,n)}function Hg(e,t){let n;if(!e||!t||e[e.length-1]!=t[t.length-1])return``;for(n=0;n<e.length&&n<t.length;n++)if(e[e.length-(n+1)]!=t[t.length-(n+1)])return e.slice(-n);return e.slice(-n)}function Ug(e,t,n){if(e.slice(0,t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't start with prefix ${JSON.stringify(t)}; this is a bug`);return n+e.slice(t.length)}function Wg(e,t,n){if(!t)return e+n;if(e.slice(-t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't end with suffix ${JSON.stringify(t)}; this is a bug`);return e.slice(0,-t.length)+n}function Gg(e,t){return Ug(e,t,``)}function Kg(e,t){return Wg(e,t,``)}function qg(e,t){return t.slice(0,Jg(e,t))}function Jg(e,t){let n=0;e.length>t.length&&(n=e.length-t.length);let r=t.length;e.length<t.length&&(r=e.length);let i=Array(r),a=0;i[0]=0;for(let e=1;e<r;e++){for(t[e]==t[a]?i[e]=i[a]:i[e]=a;a>0&&t[e]!=t[a];)a=i[a];t[e]==t[a]&&a++}a=0;for(let r=n;r<e.length;r++){for(;a>0&&e[r]!=t[a];)a=i[a];e[r]==t[a]&&a++}return a}function Yg(e,t){let n=[];for(let r of Array.from(t.segment(e))){let e=r.segment;n.length&&/\s/.test(n[n.length-1])&&/\s/.test(e)?n[n.length-1]+=e:n.push(e)}return n}function Xg(e,t){if(t)return Qg(e,t)[1];let n;for(n=e.length-1;n>=0&&e[n].match(/\s/);n--);return e.substring(n+1)}function Zg(e,t){if(t)return Qg(e,t)[0];let n=e.match(/^\s*/);return n?n[0]:``}function Qg(e,t){if(!t)return[Zg(e),Xg(e)];if(t.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);let n=Yg(e,t),r=n[0],i=n[n.length-1];return[/\s/.test(r)?r:``,/\s/.test(i)?i:``]}var $g=`a-zA-Z0-9_\\u{AD}\\u{C0}-\\u{D6}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}`,e_=RegExp(`[${$g}]+|\\s+|[^${$g}]`,`ug`);new class extends Bg{equals(e,t,n){return n.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e.trim()===t.trim()}tokenize(e,t={}){let n;if(t.intlSegmenter){let r=t.intlSegmenter;if(r.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);n=Yg(e,r)}else n=e.match(e_)||[];let r=[],i=null;return n.forEach(e=>{/\s/.test(e)?i==null?r.push(e):r.push(r.pop()+e):i!=null&&/\s/.test(i)?r[r.length-1]==i?r.push(r.pop()+e):r.push(i+e):r.push(e),i=e}),r}join(e){return e.map((e,t)=>t==0?e:e.replace(/^\s+/,``)).join(``)}postProcess(e,t){if(!e||t.oneChangePerToken)return e;let n=null,r=null,i=null;return e.forEach(e=>{e.added?r=e:e.removed?i=e:((r||i)&&t_(n,i,r,e,t.intlSegmenter),n=e,r=null,i=null)}),(r||i)&&t_(n,i,r,null,t.intlSegmenter),e}};function t_(e,t,n,r,i){if(t&&n){let[a,o]=Qg(t.value,i),[s,c]=Qg(n.value,i);if(e){let r=Vg(a,s);e.value=Wg(e.value,s,r),t.value=Gg(t.value,r),n.value=Gg(n.value,r)}if(r){let e=Hg(o,c);r.value=Ug(r.value,c,e),t.value=Kg(t.value,e),n.value=Kg(n.value,e)}}else if(n){if(e){let e=Zg(n.value,i);n.value=n.value.substring(e.length)}if(r){let e=Zg(r.value,i);r.value=r.value.substring(e.length)}}else if(e&&r){let n=Zg(r.value,i),[a,o]=Qg(t.value,i),s=Vg(n,a);t.value=Gg(t.value,s);let c=Hg(Gg(n,s),o);t.value=Kg(t.value,c),r.value=Ug(r.value,n,c),e.value=Wg(e.value,n,n.slice(0,n.length-c.length))}else if(r){let e=Zg(r.value,i),n=qg(Xg(t.value,i),e);t.value=Kg(t.value,n)}else if(e){let n=qg(Xg(e.value,i),Zg(t.value,i));t.value=Gg(t.value,n)}}new class extends Bg{tokenize(e){let t=RegExp(`(\\r?\\n)|[${$g}]+|[^\\S\\n\\r]+|[^${$g}]`,`ug`);return e.match(t)||[]}};var n_=new class extends Bg{constructor(){super(...arguments),this.tokenize=i_}equals(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
16
16
  `))&&(e=e.trim()),(!n.newlineIsToken||!t.includes(`
17
17
  `))&&(t=t.trim())):n.ignoreNewlineAtEof&&!n.newlineIsToken&&(e.endsWith(`
18
18
  `)&&(e=e.slice(0,-1)),t.endsWith(`
@@ -48,7 +48,7 @@
48
48
  -->
49
49
  <script>(() => { let t = 'system'; try { const r = localStorage.getItem('ok-theme-v1'); if (r === 'light' || r === 'dark' || r === 'system') t = r; } catch {} let dark = t === 'dark'; if (t === 'system') { try { dark = window.matchMedia('(prefers-color-scheme: dark)').matches; } catch {} } if (dark) document.documentElement.classList.add('dark'); if (window.okDesktop) document.documentElement.classList.add('electron-mode'); })();</script>
50
50
  <style>html { background-color: #fafafa } html.dark { background-color: #171717 }</style>
51
- <script type="module" crossorigin src="./assets/index-Cpe78yvf.js"></script>
51
+ <script type="module" crossorigin src="./assets/index--ExYK6aw.js"></script>
52
52
  <link rel="modulepreload" crossorigin href="./assets/chunk-CFjPhJqf.js">
53
53
  <link rel="modulepreload" crossorigin href="./assets/preload-helper-2ej06EnG.js">
54
54
  <link rel="modulepreload" crossorigin href="./assets/w3c-keyname-B5t0fahT.js">
@@ -0,0 +1,2 @@
1
+ import{c as e,d as t,i as n,p as r}from"./init-JeGcMd-V.mjs";import{homedir as i}from"node:os";const a=[`-y`,`@inkeep/open-knowledge@latest`,`mcp`],o=[[`@inkeep/open-knowledge`,`mcp`],[`-y`,`@inkeep/open-knowledge`,`mcp`]];function s(e){if(e.command!==`npx`||!Array.isArray(e.args))return`preserved`;if(c(e.args,a))return`canonical`;for(let t of o)if(c(e.args,t))return`legacy-bare`;return`preserved`}function c(e,t){if(e.length!==t.length)return!1;for(let n=0;n<t.length;n++)if(e[n]!==t[n])return!1;return!0}function l(e){let n=e.logger??f,a=e.home??i(),o=[];for(let i of t){let t=r[i],s=u(()=>t.configPath(``,a));if(s!==null&&o.push(d({scope:`user`,editorId:i,target:t,home:a,cwd:``,configPath:s,configPathOverride:void 0,logger:n})),t.projectConfigPath){let r=t.projectConfigPath,a=u(()=>r(e.projectDir));a!==null&&o.push(d({scope:`project`,editorId:i,target:t,home:void 0,cwd:e.projectDir,configPath:a,configPathOverride:a,logger:n}))}}return{outcomes:o,repairedCount:o.filter(e=>e.outcome===`repaired`).length}}function u(e){try{return e()}catch{return null}}function d(t){let r={scope:t.scope,editorId:t.editorId,configPath:t.configPath},i=n(t.target,t.cwd,t.home,t.configPathOverride);if(i===null)return{...r,outcome:`no-entry`};let a=s(i);if(a===`canonical`)return{...r,outcome:`canonical`};if(a===`preserved`)return{...r,outcome:`preserved`};let o=e(t.target,t.cwd,{mode:`published`,skipAvailabilityCheck:!0},t.home,t.configPathOverride);if(o.action===`failed`){let e=o.error??`unknown write failure`;return t.logger({event:`mcp-config-repair-write-failed`,scope:t.scope,editorId:t.editorId,configPath:t.configPath,error:e}),{...r,outcome:`write-failed`,error:e}}return t.logger({event:`mcp-config-repair-applied`,scope:t.scope,editorId:t.editorId,configPath:t.configPath}),{...r,outcome:`repaired`}}function f(e){process.stderr.write(`${JSON.stringify(e)}\n`)}export{l as repairMcpConfigs};
2
+ //# sourceMappingURL=repair-mcp-configs-Cpbs7DO6.mjs.map
@@ -1,2 +1,2 @@
1
- import{c as e,p as t,s as n}from"./init-DoDYKuWt.mjs";import"./loader-DwY1uRWB.mjs";import"./preview-D0Cwj9ak.mjs";function r(r,i,a={}){let o=[];for(let n of i){let i=t[n],s=i.projectConfigPath?.(r);if(!s){o.push({editorId:n,outcome:`skipped-no-project-surface`});continue}let c;try{c=e(i,r,a,void 0,s)}catch(e){o.push({editorId:n,outcome:`failed`,error:e instanceof Error?e.message:String(e)});continue}if(c.action===`written`||c.action===`overwritten`){o.push({editorId:n,outcome:c.action});continue}if(c.action===`failed`){o.push({editorId:n,outcome:`failed`,error:c.error});continue}o.push({editorId:n,outcome:`failed`,error:`unexpected project-scope action: ${c.action}`})}return{editorOutcomes:o,claudeLaunchJson:i.includes(`claude`)?n(r,a):void 0}}export{r as t};
2
- //# sourceMappingURL=src-T_WN5ziD.mjs.map
1
+ import{c as e,p as t,s as n}from"./init-JeGcMd-V.mjs";import"./loader-ZLKIXjJM.mjs";import"./preview-BIVzSnXG.mjs";function r(r,i,a={}){let o=[];for(let n of i){let i=t[n],s=i.projectConfigPath?.(r);if(!s){o.push({editorId:n,outcome:`skipped-no-project-surface`});continue}let c;try{c=e(i,r,a,void 0,s)}catch(e){o.push({editorId:n,outcome:`failed`,error:e instanceof Error?e.message:String(e)});continue}if(c.action===`written`||c.action===`overwritten`){o.push({editorId:n,outcome:c.action});continue}if(c.action===`failed`){o.push({editorId:n,outcome:`failed`,error:c.error});continue}o.push({editorId:n,outcome:`failed`,error:`unexpected project-scope action: ${c.action}`})}return{editorOutcomes:o,claudeLaunchJson:i.includes(`claude`)?n(r,a):void 0}}export{r as t};
2
+ //# sourceMappingURL=src-DK12uoo0.mjs.map
@@ -0,0 +1 @@
1
+ import{l as e}from"./start-Ci3v8Z67.mjs";export{e as startCommand};
@@ -1,3 +1,3 @@
1
- import{n as e,t}from"./esm-CEs3LWY3.mjs";import{pn as n}from"./dist-BFaejI07.mjs";import{n as r}from"./constants-BMZzAuZK.mjs";import{spawn as i}from"node:child_process";import{join as a}from"node:path";import{closeSync as o,existsSync as s,mkdirSync as c,openSync as l,statSync as u}from"node:fs";import{homedir as d}from"node:os";import{setTimeout as f}from"node:timers/promises";const p=`Open Knowledge.app`,m=`/Applications/${p}`;function h(){return{platform:process.platform,env:process.env,execPath:process.execPath,isTTY:process.stdout.isTTY,statSync:e=>{try{return u(e,{throwIfNoEntry:!1})??null}catch{return null}}}}function g(e){if(e.env.ELECTRON_RUN_AS_NODE===`1`){let t=/(.+?\.app)\/Contents\/MacOS\//.exec(e.execPath);if(t?.[1])return t[1]}if(_(e,m))return m;let t=a(e.homeDir??d(),`Applications`,p);return _(e,t)?t:null}function _(e,t){try{let n=a(t,`Contents`,`MacOS`,`Open Knowledge`),r=e.statSync(n);return r&&typeof r.isFile==`function`?r.isFile():!1}catch{return!1}}function v(e){if(e.env.OK_FORCE_BROWSER===`1`)return{available:!1,reason:`force-browser`};if(e.platform!==`darwin`)return{available:!1,reason:`darwin-only`};let t;try{t=g(e)}catch{return{available:!1,reason:`stat-error`}}return t?e.env.OK_FORCE_DESKTOP===`1`?{available:!0,reason:`available`,bundlePath:t}:e.isTTY!==!0||e.env.SSH_CONNECTION||e.env.SSH_TTY?{available:!1,reason:`headless`,bundlePath:t}:{available:!0,reason:`available`,bundlePath:t}:{available:!1,reason:`no-bundle`}}function y(e){(e.log??(e=>console.error(e)))("Launching Open Knowledge desktop (use `ok start` for the browser server, or `OK_FORCE_BROWSER=1` to always skip)"),e.spawn(`open`,[`-b`,`com.inkeep.open-knowledge`],{detached:!0,stdio:`ignore`}).unref()}function b(e=`no-bundle`){switch(e){case`no-bundle`:return`Desktop app not found at ${m}. Install via DMG, or omit --mode for browser mode.`;case`darwin-only`:return`Desktop app is macOS-only on this release. Use --mode=browser, or omit --mode for the server fallback.`;case`headless`:return`Desktop launch is gated in headless contexts (CI, SSH, non-TTY stdout). Set OK_FORCE_DESKTOP=1 to override, or use --mode=browser.`;case`force-browser`:return`OK_FORCE_BROWSER=1 is set — desktop dispatch is disabled. Unset it to use --mode=app.`;case`stat-error`:return`Failed to inspect desktop bundle at ${m} (filesystem error). Check permissions or use --mode=browser.`;case`available`:return`Desktop app appears available at ${m} but launch dispatch did not fire (caller bug).`}}function x(){let e=process.execPath,t=process.argv[1];return t?{command:e,prefixArgs:[t]}:(console.warn(`[self-spawn] process.argv[1] is empty — falling back to \`npx @inkeep/open-knowledge\`. This re-introduces the version-drift surface that re-exec was fixing. Observed argv: ${JSON.stringify(process.argv)}`),{command:`npx`,prefixArgs:[`@inkeep/open-knowledge`]})}function S(e,t){return e.host??t.HOST??`localhost`}var C=class extends Error{cwd;constructor(e){super("This directory isn't set up yet. Run `ok init` first, then `ok start` again."),this.name=`OkDirMissingError`,this.cwd=e}};function w(e){return e.uiLock?e.isAlive(e.uiLock.pid)?{action:`skip`,reason:`alive`,pid:e.uiLock.pid,port:e.uiLock.port}:{action:`spawn`,reason:`stale`,stalePid:e.uiLock.pid}:{action:`spawn`,reason:`absent`}}function T(e){s(e.lockDir)||c(e.lockDir,{recursive:!0});let t=l(a(e.lockDir,`last-spawn-error.log`),`w`),n=e.spawn??i,{PORT:r,...u}=process.env,d=x();try{let r=n(d.command,[...d.prefixArgs,...e.args??[`ui`]],{detached:!0,stdio:[`ignore`,`ignore`,t],cwd:e.cwd,env:u});return r.unref(),r}finally{try{o(t)}catch{}}}async function E(e){let t=e.now()+e.timeoutMs;for(;e.now()<t;){let t=e.readUiLock();if(t&&t.port>0)return t.port;await e.sleep(e.pollIntervalMs)}let n=e.readUiLock();return n&&n.port>0?n.port:null}function D(e){let t=e.sigtermGraceMs??1e4,n=e.sigtermPollIntervalMs??200,r=e.sleep??(e=>f(e));return async()=>{try{let i=e.readUiLock();if(i&&e.isAlive(i.pid))try{e.killPid(i.pid,`SIGTERM`),e.log?.info({pid:i.pid,port:i.port},`idle-shutdown: SIGTERM UI sibling`);let a=Date.now()+t;for(;Date.now()<a&&e.isAlive(i.pid);)await r(n);if(e.isAlive(i.pid))try{e.killPid(i.pid,`SIGKILL`),e.log?.warn({pid:i.pid,graceMs:t},`idle-shutdown: SIGTERM grace expired — escalated to SIGKILL`)}catch(t){e.log?.error({pid:i.pid,err:t instanceof Error?t.message:String(t)},`idle-shutdown: SIGKILL failed`)}}catch(t){e.log?.warn({pid:i.pid,err:t instanceof Error?t.message:String(t)},`idle-shutdown: failed to SIGTERM UI sibling`)}}catch(t){e.log?.warn({err:t instanceof Error?t.message:String(t)},`idle-shutdown: UI lookup failed; proceeding with destroy`)}await e.destroy()}}async function O(e){let{config:t,cwd:r,host:i}=e,a=e.skipAutoInit??!1,o=e.skipUiAutoSpawn??!1,s=e.idleThresholdMs??18e5,{existsSync:c,mkdirSync:l}=await import(`node:fs`),{bootServer:u,getLogger:d,isProcessAlive:p,readUiLock:m,resolveContentDir:h}=await import(`./dist-JvyJrwkx.mjs`),g=e.log??d(`start`);if(!a&&!n(r))throw new C(r);let _=h(t,r);c(_)||(l(_,{recursive:!0}),g.info({contentDir:_},`Created content directory`));let v=null,y=await u({config:t,contentDir:_,projectDir:r,contentRoot:t.content.dir,port:e.port,host:i,quiet:!1,localOpCliArgs:[process.execPath,process.argv[1]],attachUiSibling:!0,idleShutdownMs:s,skipAutoInit:!0,spawnUiSiblingFn:async({lockDir:t})=>{if(v=w({uiLock:m(t),isAlive:p}),v.action===`spawn`&&!o)try{T({lockDir:t,cwd:r,spawn:e.spawn}),g.info({reason:v.reason},`[start] auto-spawned ok ui sibling`)}catch(e){console.warn(`[start] failed to auto-spawn ok ui: ${e instanceof Error?e.message:String(e)}`)}else v.action===`skip`&&g.info({port:v.port,pid:v.pid},`UI already running at port ${v.port}`)},idleShutdownHandler:e=>D({readUiLock:()=>m(y.lockDir),isAlive:p,killPid:(e,t)=>{process.kill(e,t)},destroy:e,log:g}),log:g});v||={action:`skip`,reason:`alive`,pid:0,port:0};let b=v,x=null;if(b.action===`skip`)x=b.port>0?b.port:null;else if(!o){let t=e.uiBindTimeoutMs??3e3;x=await E({readUiLock:()=>m(y.lockDir),now:Date.now,sleep:e=>f(e),timeoutMs:t,pollIntervalMs:50}),x===null&&g.warn({timeoutMs:t},`[start] ok ui did not bind within timeout — banner falls back to API URL`)}return{httpServer:y.httpServer,destroy:y.destroy,lockDir:y.lockDir,contentDir:_,port:y.port,ready:y.ready,degraded:y.degraded,uiSpawnDecision:v,resolvedUiPort:x}}function k(t){if(t===`browser`||t===`app`)return t;throw new e(`--mode must be 'browser' or 'app'`)}async function A(e,t){let{renderBanner:n}=await import(`./banner-4PRLiK-I.mjs`),{dim:i,error:a,warning:o}=await import(`./colors-T3xmlXQT.mjs`),s=process.cwd(),c=e,l=S(t,process.env),u=t.port===void 0?void 0:Number(t.port),d=process.env.PORT?Number(process.env.PORT):void 0,f=u??d,p;try{p=await O({config:c,cwd:s,host:l,port:f})}catch(e){e instanceof C&&(console.error(a(e.message)),process.exit(1));let t=j(e,s,await import(`./dist-JvyJrwkx.mjs`));t!==null&&(console.error(a(t)),process.exit(1)),console.error(`${a(`Failed to start:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exit(1)}let m=!1,h=async e=>{if(!m){m=!0,console.log(i(`\nShutting down (${e})`));try{await p.destroy()}catch(e){console.error(`${a(`destroy() failed:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exitCode=1}process.exit(process.exitCode??0)}};process.once(`SIGINT`,()=>{h(`SIGINT`)}),process.once(`SIGTERM`,()=>{h(`SIGTERM`)});let g=`http://${l}:${p.port}`,_=l===`0.0.0.0`||l===`::`?`http://0.0.0.0:${p.port}`:void 0,v=p.resolvedUiPort,y=v!==null&&v>0?`http://${l}:${v}`:g;console.log(n({name:`open-knowledge`,version:r,localUrl:y,apiUrl:y===g?void 0:g,networkUrl:_}));let b={"shadow-repo":`Version history and branch-switch safety unavailable`,"file-watcher":`External file changes will not sync to the editor`,"head-watcher":`Git branch switches may cause document inconsistency`};p.ready.then(async()=>{if(p.degraded.length>0){console.log();for(let e of p.degraded){let t=b[e]??`${e} (check server logs for details)`;console.warn(` ${o(`⚠`)} ${o(e)}: ${i(t)}`)}console.log()}if(t.open){let{openBrowser:e}=await import(`./open-browser-CoKDMbx5.mjs`);e(y)}}).catch(e=>{console.error(` ${a(`Server initialization failed:`)} ${e instanceof Error?e.message:String(e)}`)})}function j(e,t,n){let r=n.ServerLockCollisionError;if(r===void 0||!(e instanceof r))return null;try{let e=a(t,`.ok`),r=n.readServerLock(e);return r?r.kind===`interactive`?`Open Knowledge desktop is currently running on this project. Quit it or use --cwd to point elsewhere.`:r.kind===`mcp-spawned`?"An MCP-spawned server holds this lock; it should release on idle-shutdown (~30 min). Or run `ok stop`.":"Open Knowledge server is already running on this project — check `ok status` or `ok stop`.":"Open Knowledge server is already running on this project — check `ok status` or `ok stop`."}catch{return null}}function M(e){return new t(`start`).description(`Start the knowledge base collab server`).option(`-p, --port <port>`,`Server port`,void 0).option(`-H, --host <host>`,`Server host`,void 0).option(`--open`,`Open browser after start`).option(`--mode <mode>`,`Force dispatch mode: 'browser' or 'app'`,k).action(async t=>{let n=e();if(t.mode===`app`){t.open&&(process.stderr.write(`error: option '--mode=app' cannot be combined with '--open' (--open opens a browser tab against the local server, which app mode does not boot)
1
+ import{n as e,t}from"./esm-CEs3LWY3.mjs";import{pn as n}from"./dist-BFaejI07.mjs";import{n as r}from"./constants-BKcZ-SZr.mjs";import{spawn as i}from"node:child_process";import{join as a}from"node:path";import{closeSync as o,existsSync as s,mkdirSync as c,openSync as l,statSync as u}from"node:fs";import{homedir as d}from"node:os";import{setTimeout as f}from"node:timers/promises";const p=`Open Knowledge.app`,m=`/Applications/${p}`;function h(){return{platform:process.platform,env:process.env,execPath:process.execPath,isTTY:process.stdout.isTTY,statSync:e=>{try{return u(e,{throwIfNoEntry:!1})??null}catch{return null}}}}function g(e){if(e.env.ELECTRON_RUN_AS_NODE===`1`){let t=/(.+?\.app)\/Contents\/MacOS\//.exec(e.execPath);if(t?.[1])return t[1]}if(_(e,m))return m;let t=a(e.homeDir??d(),`Applications`,p);return _(e,t)?t:null}function _(e,t){try{let n=a(t,`Contents`,`MacOS`,`Open Knowledge`),r=e.statSync(n);return r&&typeof r.isFile==`function`?r.isFile():!1}catch{return!1}}function v(e){if(e.env.OK_FORCE_BROWSER===`1`)return{available:!1,reason:`force-browser`};if(e.platform!==`darwin`)return{available:!1,reason:`darwin-only`};let t;try{t=g(e)}catch{return{available:!1,reason:`stat-error`}}return t?e.env.OK_FORCE_DESKTOP===`1`?{available:!0,reason:`available`,bundlePath:t}:e.isTTY!==!0||e.env.SSH_CONNECTION||e.env.SSH_TTY?{available:!1,reason:`headless`,bundlePath:t}:{available:!0,reason:`available`,bundlePath:t}:{available:!1,reason:`no-bundle`}}function y(e){(e.log??(e=>console.error(e)))("Launching Open Knowledge desktop (use `ok start` for the browser server, or `OK_FORCE_BROWSER=1` to always skip)"),e.spawn(`open`,[`-b`,`com.inkeep.open-knowledge`],{detached:!0,stdio:`ignore`}).unref()}function b(e=`no-bundle`){switch(e){case`no-bundle`:return`Desktop app not found at ${m}. Install via DMG, or omit --mode for browser mode.`;case`darwin-only`:return`Desktop app is macOS-only on this release. Use --mode=browser, or omit --mode for the server fallback.`;case`headless`:return`Desktop launch is gated in headless contexts (CI, SSH, non-TTY stdout). Set OK_FORCE_DESKTOP=1 to override, or use --mode=browser.`;case`force-browser`:return`OK_FORCE_BROWSER=1 is set — desktop dispatch is disabled. Unset it to use --mode=app.`;case`stat-error`:return`Failed to inspect desktop bundle at ${m} (filesystem error). Check permissions or use --mode=browser.`;case`available`:return`Desktop app appears available at ${m} but launch dispatch did not fire (caller bug).`}}function x(){let e=process.execPath,t=process.argv[1];return t?{command:e,prefixArgs:[t]}:(console.warn(`[self-spawn] process.argv[1] is empty — falling back to \`npx @inkeep/open-knowledge\`. This re-introduces the version-drift surface that re-exec was fixing. Observed argv: ${JSON.stringify(process.argv)}`),{command:`npx`,prefixArgs:[`@inkeep/open-knowledge`]})}function S(e,t){return e.host??t.HOST??`localhost`}var C=class extends Error{cwd;constructor(e){super("This directory isn't set up yet. Run `ok init` first, then `ok start` again."),this.name=`OkDirMissingError`,this.cwd=e}};function w(e){return e.uiLock?e.isAlive(e.uiLock.pid)?{action:`skip`,reason:`alive`,pid:e.uiLock.pid,port:e.uiLock.port}:{action:`spawn`,reason:`stale`,stalePid:e.uiLock.pid}:{action:`spawn`,reason:`absent`}}function T(e){s(e.lockDir)||c(e.lockDir,{recursive:!0});let t=l(a(e.lockDir,`last-spawn-error.log`),`w`),n=e.spawn??i,{PORT:r,...u}=process.env,d=x();try{let r=n(d.command,[...d.prefixArgs,...e.args??[`ui`]],{detached:!0,stdio:[`ignore`,`ignore`,t],cwd:e.cwd,env:u});return r.unref(),r}finally{try{o(t)}catch{}}}async function E(e){let t=e.now()+e.timeoutMs;for(;e.now()<t;){let t=e.readUiLock();if(t&&t.port>0)return t.port;await e.sleep(e.pollIntervalMs)}let n=e.readUiLock();return n&&n.port>0?n.port:null}function D(e){let t=e.sigtermGraceMs??1e4,n=e.sigtermPollIntervalMs??200,r=e.sleep??(e=>f(e));return async()=>{try{let i=e.readUiLock();if(i&&e.isAlive(i.pid))try{e.killPid(i.pid,`SIGTERM`),e.log?.info({pid:i.pid,port:i.port},`idle-shutdown: SIGTERM UI sibling`);let a=Date.now()+t;for(;Date.now()<a&&e.isAlive(i.pid);)await r(n);if(e.isAlive(i.pid))try{e.killPid(i.pid,`SIGKILL`),e.log?.warn({pid:i.pid,graceMs:t},`idle-shutdown: SIGTERM grace expired — escalated to SIGKILL`)}catch(t){e.log?.error({pid:i.pid,err:t instanceof Error?t.message:String(t)},`idle-shutdown: SIGKILL failed`)}}catch(t){e.log?.warn({pid:i.pid,err:t instanceof Error?t.message:String(t)},`idle-shutdown: failed to SIGTERM UI sibling`)}}catch(t){e.log?.warn({err:t instanceof Error?t.message:String(t)},`idle-shutdown: UI lookup failed; proceeding with destroy`)}await e.destroy()}}async function O(e){let{config:t,cwd:r,host:i}=e,a=e.skipAutoInit??!1,o=e.skipUiAutoSpawn??!1,s=e.idleThresholdMs??18e5,{existsSync:c,mkdirSync:l}=await import(`node:fs`),{bootServer:u,getLogger:d,isProcessAlive:p,readUiLock:m,resolveContentDir:h}=await import(`./dist-JvyJrwkx.mjs`),g=e.log??d(`start`);if(!a&&!n(r))throw new C(r);try{(e.repairMcpConfigsFn??(await import(`./repair-mcp-configs-Cpbs7DO6.mjs`)).repairMcpConfigs)({projectDir:r})}catch(e){g.warn({err:e},`[start] mcp-config repair sweep failed; continuing`)}let _=h(t,r);c(_)||(l(_,{recursive:!0}),g.info({contentDir:_},`Created content directory`));let v=null,y=await u({config:t,contentDir:_,projectDir:r,contentRoot:t.content.dir,port:e.port,host:i,quiet:!1,localOpCliArgs:[process.execPath,process.argv[1]],attachUiSibling:!0,idleShutdownMs:s,skipAutoInit:!0,spawnUiSiblingFn:async({lockDir:t})=>{if(v=w({uiLock:m(t),isAlive:p}),v.action===`spawn`&&!o)try{T({lockDir:t,cwd:r,spawn:e.spawn}),g.info({reason:v.reason},`[start] auto-spawned ok ui sibling`)}catch(e){console.warn(`[start] failed to auto-spawn ok ui: ${e instanceof Error?e.message:String(e)}`)}else v.action===`skip`&&g.info({port:v.port,pid:v.pid},`UI already running at port ${v.port}`)},idleShutdownHandler:e=>D({readUiLock:()=>m(y.lockDir),isAlive:p,killPid:(e,t)=>{process.kill(e,t)},destroy:e,log:g}),log:g});v||={action:`skip`,reason:`alive`,pid:0,port:0};let b=v,x=null;if(b.action===`skip`)x=b.port>0?b.port:null;else if(!o){let t=e.uiBindTimeoutMs??3e3;x=await E({readUiLock:()=>m(y.lockDir),now:Date.now,sleep:e=>f(e),timeoutMs:t,pollIntervalMs:50}),x===null&&g.warn({timeoutMs:t},`[start] ok ui did not bind within timeout — banner falls back to API URL`)}return{httpServer:y.httpServer,destroy:y.destroy,lockDir:y.lockDir,contentDir:_,port:y.port,ready:y.ready,degraded:y.degraded,uiSpawnDecision:v,resolvedUiPort:x}}function k(t){if(t===`browser`||t===`app`)return t;throw new e(`--mode must be 'browser' or 'app'`)}async function A(e,t){let{renderBanner:n}=await import(`./banner-DdbR6AZr.mjs`),{dim:i,error:a,warning:o}=await import(`./colors-T3xmlXQT.mjs`),s=process.cwd(),c=e,l=S(t,process.env),u=t.port===void 0?void 0:Number(t.port),d=process.env.PORT?Number(process.env.PORT):void 0,f=u??d,p;try{p=await O({config:c,cwd:s,host:l,port:f})}catch(e){e instanceof C&&(console.error(a(e.message)),process.exit(1));let t=j(e,s,await import(`./dist-JvyJrwkx.mjs`));t!==null&&(console.error(a(t)),process.exit(1)),console.error(`${a(`Failed to start:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exit(1)}let m=!1,h=async e=>{if(!m){m=!0,console.log(i(`\nShutting down (${e})`));try{await p.destroy()}catch(e){console.error(`${a(`destroy() failed:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exitCode=1}process.exit(process.exitCode??0)}};process.once(`SIGINT`,()=>{h(`SIGINT`)}),process.once(`SIGTERM`,()=>{h(`SIGTERM`)});let g=`http://${l}:${p.port}`,_=l===`0.0.0.0`||l===`::`?`http://0.0.0.0:${p.port}`:void 0,v=p.resolvedUiPort,y=v!==null&&v>0?`http://${l}:${v}`:g;console.log(n({name:`open-knowledge`,version:r,localUrl:y,apiUrl:y===g?void 0:g,networkUrl:_}));let b={"shadow-repo":`Version history and branch-switch safety unavailable`,"file-watcher":`External file changes will not sync to the editor`,"head-watcher":`Git branch switches may cause document inconsistency`};p.ready.then(async()=>{if(p.degraded.length>0){console.log();for(let e of p.degraded){let t=b[e]??`${e} (check server logs for details)`;console.warn(` ${o(`⚠`)} ${o(e)}: ${i(t)}`)}console.log()}if(t.open){let{openBrowser:e}=await import(`./open-browser-BOeCxs2W.mjs`);e(y)}}).catch(e=>{console.error(` ${a(`Server initialization failed:`)} ${e instanceof Error?e.message:String(e)}`)})}function j(e,t,n){let r=n.ServerLockCollisionError;if(r===void 0||!(e instanceof r))return null;try{let e=a(t,`.ok`),r=n.readServerLock(e);return r?r.kind===`interactive`?`Open Knowledge desktop is currently running on this project. Quit it or use --cwd to point elsewhere.`:r.kind===`mcp-spawned`?"An MCP-spawned server holds this lock; it should release on idle-shutdown (~30 min). Or run `ok stop`.":"Open Knowledge server is already running on this project — check `ok status` or `ok stop`.":"Open Knowledge server is already running on this project — check `ok status` or `ok stop`."}catch{return null}}function M(e){return new t(`start`).description(`Start the knowledge base collab server`).option(`-p, --port <port>`,`Server port`,void 0).option(`-H, --host <host>`,`Server host`,void 0).option(`--open`,`Open browser after start`).option(`--mode <mode>`,`Force dispatch mode: 'browser' or 'app'`,k).action(async t=>{let n=e();if(t.mode===`app`){t.open&&(process.stderr.write(`error: option '--mode=app' cannot be combined with '--open' (--open opens a browser tab against the local server, which app mode does not boot)
2
2
  `),process.exit(2));let e=[];if(t.port!==void 0&&e.push(`--port`),t.host!==void 0&&e.push(`--host`),e.length>0){let t=process.env.OK_LOG_LEVEL??`info`;(t===`debug`||t===`trace`)&&console.error(`--mode=app: ignoring ${e.join(`, `)}`)}let n=v(h());if(n.available){y({spawn:i});return}console.error(b(n.reason)),process.exit(1)}await A(n,t)})}export{w as a,T as c,x as d,h as f,D as i,M as l,y as m,E as n,S as o,v as p,O as r,A as s,C as t,j as u};
3
- //# sourceMappingURL=start-Bi19bmNy.mjs.map
3
+ //# sourceMappingURL=start-Ci3v8Z67.mjs.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inkeep/open-knowledge",
3
- "version": "0.5.0-beta.14",
3
+ "version": "0.5.0-beta.15",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "repository": {
@@ -1,2 +0,0 @@
1
- import"./dist-BFaejI07.mjs";var e=`0.5.0-beta.14`;const t=`config.yml`,n=e;export{n,t};
2
- //# sourceMappingURL=constants-BMZzAuZK.mjs.map
@@ -1 +0,0 @@
1
- import{o as e}from"./init-DoDYKuWt.mjs";export{e as runInit};
@@ -1 +0,0 @@
1
- import{n as e}from"./loader-DwY1uRWB.mjs";export{e as loadConfig};
@@ -1 +0,0 @@
1
- import{n as e,t}from"./preview-D0Cwj9ak.mjs";export{t as formatPreviewBlock,e as previewContent};
@@ -1 +0,0 @@
1
- import{l as e}from"./start-Bi19bmNy.mjs";export{e as startCommand};