UNPKG

@lunora/cli

Version:

The Lunora CLI: init, dev, deploy, codegen, migrate, seed, doctor, insights, logs, registry, and the rest of the project commands

11 lines (9 loc) 15.8 kB
import{V as R}from"../packem_shared/cli-oqj4ysM9.mjs";import{d as T}from"../packem_shared/command-DwC11Cwe.mjs";import{existsSync as u,readFileSync as v,mkdirSync as D,realpathSync as I,statSync as J,writeFileSync as W,chmodSync as z,renameSync as G,unlinkSync as H}from"node:fs";import{homedir as b}from"node:os";import{findWranglerFile as V}from"@lunora/config/cloudflare";import{join as s,dirname as K,relative as q}from"@visulima/path";import{d as B,e as X}from"../packem_shared/detect-package-manager-DSaAqRof.mjs";import{stringify as Z}from"smol-toml";import{parse as Q,modify as Y,applyEdits as ee}from"jsonc-parser";import{readLiveDevServerState as y}from"@lunora/config";import{resolveAdminToken as re}from"@lunora/config/studio-host";import{connectLocalStdio as te}from"@lunora/mcp";const f=e=>({args:[...e.args],command:e.command,...e.env===void 0?{}:{env:e.env}}),h=e=>e.transport==="http"?{type:"http",url:e.url}:f(e),ne=e=>e.transport==="http"?{httpUrl:e.url}:f(e),oe=e=>e.transport==="http"?{serverUrl:e.url}:f(e),ae=e=>({args:["-y","mcp-remote",e],command:"npx"}),le=e=>e.transport==="http"?ae(e.url):f(e),ce=e=>e.transport==="http"?{url:e.url}:f(e),se=e=>e.transport==="http"?{enabled:!0,type:"remote",url:e.url}:{command:[e.command,...e.args],enabled:!0,type:"local",...e.env===void 0?{}:{environment:e.env}},ie=e=>e.transport==="http"?{disabled:!1,type:"streamableHttp",url:e.url}:{disabled:!1,...f(e)},de=({home:e,platform:r})=>{if(r==="darwin")return{global:s(e,"Library","Application Support","Claude","claude_desktop_config.json")};if(r==="win32"){const t=process.env.APPDATA;return t===void 0||t===""?{}:{global:s(t,"Claude","claude_desktop_config.json")}}return r==="linux"?{global:s(e,".config","Claude","claude_desktop_config.json")}:{}},ue=(e,r)=>Z({mcp_servers:{[e]:r.transport==="http"?{url:r.url}:{args:[...r.args],command:r.command,...r.env===void 0?{}:{env:r.env}}}}),p=[{buildEntry:h,paths:({projectRoot:e})=>({project:s(e,".mcp.json")}),format:"json",id:"claude-code",key:"mcpServers",label:"Claude Code"},{buildEntry:h,paths:({home:e,projectRoot:r})=>({global:s(e,".cursor","mcp.json"),project:s(r,".cursor","mcp.json")}),format:"json",id:"cursor",key:"mcpServers",label:"Cursor"},{buildEntry:h,paths:({projectRoot:e})=>({project:s(e,".vscode","mcp.json")}),format:"json",id:"vscode",key:"servers",label:"VS Code (GitHub Copilot)"},{buildEntry:ne,paths:({home:e,projectRoot:r})=>({global:s(e,".gemini","settings.json"),project:s(r,".gemini","settings.json")}),format:"json",id:"gemini",key:"mcpServers",label:"Gemini CLI"},{buildEntry:le,paths:de,format:"json",id:"claude-desktop",key:"mcpServers",label:"Claude Desktop"},{buildEntry:oe,paths:({home:e})=>({global:s(e,".codeium","windsurf","mcp_config.json")}),format:"json",id:"windsurf",key:"mcpServers",label:"Windsurf"},{buildEntry:se,paths:({home:e,projectRoot:r})=>({global:s(e,".config","opencode","opencode.json"),project:s(r,"opencode.json")}),format:"json",id:"opencode",key:"mcp",label:"OpenCode"},{buildEntry:ie,paths:({home:e})=>({global:s(e,".cline","mcp.json")}),format:"json",id:"cline",key:"mcpServers",label:"Cline"},{buildEntry:ce,paths:({home:e})=>({global:s(e,".config","zed","settings.json")}),format:"json",id:"zed",key:"context_servers",label:"Zed"},{paths:({home:e,projectRoot:r})=>({global:s(e,".codex","config.toml"),project:s(r,".codex","config.toml")}),format:"manual",id:"codex",label:"Codex CLI",renderSnippet:ue}],O=p.map(e=>e.id),fe=e=>p.find(r=>r.id===e.toLowerCase()),C=(e,r)=>{let t=e,n;try{t=I(e),n=J(t).mode}catch{}const a=`${t}.lunora-${Math.random().toString(36).slice(2,10)}.tmp`;try{W(a,r,"utf8"),n!==void 0&&z(a,n),G(a,t)}catch(o){try{H(a)}catch{}throw o}},me={formattingOptions:{insertSpaces:!0,tabSize:4}},w=e=>{const r=[],t=Q(e,r,{allowTrailingComma:!0});return{errors:r,value:t}},g=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),S=(e,r,t)=>{if(!g(e))return;const n=e[r];return g(n)?n[t]:void 0},x=e=>{if(!u(e.path))return"absent";let r;try{r=v(e.path,"utf8")}catch{return"invalid"}if(r.trim().length===0)return"absent";const{errors:t,value:n}=w(r);return t.length>0||!g(n)?"invalid":S(n,e.key,e.name)===void 0?"absent":"present"},ge=e=>x(e)==="present",M=(e,r,t,n,a)=>{try{const o=Y(e,[t,n],a,me);o.length>0&&C(r,ee(e,o));return}catch(o){return o instanceof Error?o.message:String(o)}},pe=e=>{const{entry:r,force:t=!1,key:n,name:a,path:o}=e,l=u(o)?v(o,"utf8"):"";if(l.trim().length===0)return D(K(o),{recursive:!0}),C(o,`${JSON.stringify({[n]:{[a]:r}},void 0,4)} `),{action:"created",path:o};const{errors:c,value:i}=w(l);if(c.length>0)return{action:"invalid",error:`parse error at offset ${String(c[0]?.offset??0)}`,path:o};if(!g(i))return{action:"invalid",error:"the file's root is not a JSON object",path:o};const m=i[n];if(m!==void 0&&!g(m))return{action:"invalid",error:`"${n}" is not an object`,path:o};if(S(i,n,a)!==void 0&&!t)return{action:"skipped",path:o};const k=M(l,o,n,a,r);return k===void 0?{action:"updated",path:o}:{action:"invalid",error:k,path:o}},ve=e=>{const{key:r,name:t,path:n}=e;if(!u(n))return{action:"absent",path:n};let a;try{a=v(n,"utf8")}catch(i){return{action:"invalid",error:i instanceof Error?i.message:String(i),path:n}}const{errors:o,value:l}=w(a);if(o.length>0)return{action:"invalid",error:`parse error at offset ${String(o[0]?.offset??0)}`,path:n};if(S(l,r,t)===void 0)return{action:"absent",path:n};const c=M(a,n,r,t,void 0);return c===void 0?{action:"removed",path:n}:{action:"invalid",error:c,path:n}},he=["global","project"],d=(e,r)=>{const t=q(r,e);return t.length>0&&!t.startsWith("..")?t:e},ye=(e,r)=>{const t=e.paths(r);return he.flatMap(n=>{const a=t[n];return a===void 0?[]:[{client:e,path:a,scope:n}]})},be=(e,r,t,n)=>{const a=e.paths(r),o=t==="global"?"project":"global",l=a[t]??(n?void 0:a[o]);if(l!==void 0)return{client:e,path:l,scope:a[t]===void 0?o:t}},we=e=>p.filter(r=>Object.values(r.paths(e)).some(t=>u(t))),_=(e,r,t,n)=>{if(e.length===0)return r();const a=[];for(const o of e){const l=fe(o);if(l===void 0){t.error(`mcp ${n}: unknown client "${o}". Known clients: ${O.join(", ")}.`);return}a.push(l)}return a},Se=e=>e.client.format==="json",ke="https://lunora.sh/mcp",L="lunora-docs",N="lunora",je=e=>u(s(e,"lunora"))&&V(e)!==void 0,$e=e=>{const{args:r,command:t}=X(e,"lunora",["mcp","serve"]);return{args:r,command:t,transport:"stdio"}},Ee=e=>({transport:"http",url:e}),Oe=e=>({home:e.home,platform:e.platform,projectRoot:e.cwd}),U=(e,r,t)=>be(e,Oe(t),t.scope??r.preferredScope,t.scope!==void 0||!r.allowScopeFallback),Ce=(e,r,t)=>{const n=U(e,r,t);if(n===void 0){t.logger.warn(`${e.label}: has no ${t.scope??r.preferredScope}-scoped config — skipped "${r.name}".`);return}const{path:a}=n,o=e.buildEntry(r.spec);if(t.print===!0){const i=d(a,t.cwd);return t.force!==!0&&ge({key:e.key,name:r.name,path:a})?(t.logger.info(`${e.label}: "${r.name}" already configured in ${i} — a real install would skip it (re-run with --force to replace).`),{action:"printed",path:a}):(t.logger.info(`${e.label}${i} ${JSON.stringify({[e.key]:{[r.name]:o}},void 0,4)}`),{action:"printed",path:a})}const l=pe({entry:o,force:t.force===!0,key:e.key,name:r.name,path:a}),c=d(a,t.cwd);return l.action==="invalid"?t.logger.error(`${e.label}: ${c} is not valid JSON (${l.error??"unknown error"}) — left untouched.`):l.action==="skipped"?t.logger.info(`${e.label}: "${r.name}" already configured in ${c} — re-run with --force to replace it.`):t.logger.success(`${e.label}: ${l.action==="created"?"created":"updated"} ${c} with "${r.name}".`),{action:l.action,path:a}},xe=(e,r,t)=>{const n=U(e,r,t)?.path;if(n===void 0){t.logger.warn(`${e.label}: no known config location on ${t.platform} — skipped.`);return}return t.logger.info(`${e.label}: add this to ${d(n,t.cwd)} ${e.renderSnippet(r.name,r.spec)}`),{action:"printed",path:n}},Me=e=>{const r=[];return e.localOnly!==!0&&r.push({allowScopeFallback:!0,name:L,preferredScope:"global",spec:Ee(e.docsUrl??ke)}),e.docsOnly!==!0&&je(e.cwd)&&r.push({allowScopeFallback:!1,name:N,preferredScope:"project",spec:$e(B(e.cwd))}),r},_e=e=>{const r=e.home??b(),t=e.platform??process.platform;e.logger.info("Supported MCP clients:");for(const n of p){const a=n.paths({home:r,platform:t,projectRoot:e.cwd}),o=l=>{const c=a[l];return c===void 0?"—":d(c,e.cwd)};e.logger.info(` ${n.id.padEnd(15)} ${n.label.padEnd(24)} project: ${o("project").padEnd(30)} global: ${o("global")}`)}return{code:0,written:[]}},Le=e=>e.docsOnly===!0&&e.localOnly===!0?"`--docs-only` and `--local-only` are mutually exclusive — pass at most one.":"`--local-only` was set but this directory is not a Lunora project (no `lunora/` directory and wrangler config).",Ne=(e,r,t)=>{const n=[];for(const a of e)for(const o of r){const l=a.format==="json"?Ce(a,o,t):xe(a,o,t);l!==void 0&&n.push({action:l.action,client:a.id,path:l.path,server:o.name})}return n},Ue=e=>{const r=e.home??b(),t=e.platform??process.platform,n=_(e.clients,()=>we({home:r,platform:t,projectRoot:e.cwd}),e.logger,"install");if(n===void 0)return{code:1,written:[]};if(n.length===0)return e.logger.error(`mcp install: no MCP client config found — name one explicitly, e.g. \`lunora mcp install claude-code\`. Known clients: ${O.join(", ")}.`),{code:1,written:[]};e.clients.length===0&&e.logger.info(`Detected ${String(n.length)} configured client(s): ${n.map(l=>l.label).join(", ")}.`);const a=Me(e);if(a.length===0)return e.logger.error(`mcp install: nothing to install — ${Le(e)}`),{code:1,written:[]};const o=Ne(n,a,{...e,home:r,platform:t});return o.some(l=>l.action==="created"||l.action==="updated")&&e.logger.info("Restart your editor (or reload its MCP servers) to pick up the change."),{code:o.some(l=>l.action==="invalid")?1:0,written:o}},A=100,F=1e3,j=e=>({content:[{text:JSON.stringify(e,void 0,2),type:"text"}]}),Ae=e=>({content:[{text:e,type:"text"}]}),Fe=e=>{const r=typeof e=="string"?Number(e):e;return typeof r!="number"||!Number.isFinite(r)?A:Math.min(F,Math.max(1,Math.floor(r)))},Pe=(e,r)=>{const t=v(e,"utf8").split(` `);return t.at(-1)===""&&t.pop(),t.slice(-r).join(` `)},Re=e=>[{definition:{description:"Report whether a `lunora dev` server is running for this project, and its URL, studio URL, mode and uptime. Call this first when a query or mutation tool fails to connect.",inputSchema:{properties:{},type:"object"},name:"lunora_dev_status"},handle:async()=>{const r=y(e);return j(r===void 0?{hint:"Start it with `lunora dev` in the project directory.",running:!1}:{background:r.background===!0,logFile:r.logFile,mode:r.mode,pid:r.pid,running:!0,startedAt:r.startedAt,studioUrl:r.studioUrl,url:r.url})}},{definition:{description:"Return the tail of the running dev server's captured log — worker output, request errors, and stack traces. Only available when the server was started in the background (`lunora dev --background`); a foreground server prints to its own terminal.",inputSchema:{properties:{lines:{description:`How many trailing lines to return (default ${String(A)}, max ${String(F)})`,type:"number"}},type:"object"},name:"lunora_dev_logs"},handle:async r=>{const t=y(e);if(t===void 0)return{content:[{text:"no dev server is running — start one with `lunora dev`",type:"text"}],isError:!0};if(t.logFile===void 0||!u(t.logFile))return{content:[{text:"this dev server is not capturing its output to a file (it runs in the foreground) — restart it with `lunora dev --background` to make its logs readable here",type:"text"}],isError:!0};const n=Fe(r.lines),a=Pe(t.logFile,n);return Ae(a.length===0?"(the dev server log is empty)":a)}}],Te=new Set(["127.0.0.1","::1","localhost"]),P=e=>{try{const{hostname:r}=new URL(e);return Te.has(r.startsWith("[")?r.slice(1,-1):r)}catch{return!1}},$=e=>{const r=e.url??y(e.cwd)?.url;if(r===void 0||r.length===0)return;if(e.token!==void 0&&e.token.length>0)return{token:e.token,url:r};if(e.url!==void 0&&!P(e.url))return{url:r};const t=re(e.cwd);return t===void 0||t.length===0?{url:r}:{token:t,url:r}},De=async e=>{await new Promise(r=>{const t=()=>{r()};e.onclose=t,process.stdin.once("close",t),process.stdin.once("end",t)})},Ie=(e,r)=>{if(e===void 0)return"lunora mcp serve: ready (documentation tools). No dev server running yet — start `lunora dev` and the deployment tools start working, no restart needed.\n";if(e.token!==void 0)return`lunora mcp serve: ready — deployment at ${e.url} `;const n=r.url!==void 0&&!P(r.url)?"the project's admin token was NOT sent to this non-local --url; pass --token to authenticate deliberately":"no LUNORA_ADMIN_TOKEN in the environment or .dev.vars; the deployment tools will be refused until one is set";return`lunora mcp serve: ready — deployment at ${e.url} (${n}) `},Je=async(e,r=te)=>{const t=e.writeError??(o=>{process.stderr.write(o)});let n;try{n=await r({allowWrites:e.allowWrites===!0,deployment:()=>$(e),docs:e.noDocs===!0?!1:{...e.docsUrl===void 0?{}:{baseUrl:e.docsUrl}},extraTools:Re(e.cwd),version:e.version})}catch(o){const l=o instanceof Error?o.message:String(o);return t(`lunora mcp serve: failed to start — ${l} `),{code:1,deployment:void 0}}const a=$(e);return t(Ie(a,e)),await De(n),{code:0,deployment:a}},We=e=>{const r=[];return e.localOnly!==!0&&r.push(L),e.docsOnly!==!0&&r.push(N),r},ze=(e,r,t,n)=>{const a=ve({key:e.key,name:r,path:t}),o=d(t,n.cwd);return a.action==="removed"?n.logger.success(`${e.label}: removed "${r}" from ${o}.`):a.action==="invalid"&&n.logger.error(`${e.label}: ${o} is not valid JSON (${a.error??"unknown error"}) — left untouched.`),{action:a.action,path:t}},Ge=(e,r,t,n)=>{const a=x({key:e.key,name:r,path:t}),o=d(t,n.cwd);return a==="invalid"?(n.logger.error(`${e.label}: ${o} is not valid JSON — a real run would report it and exit non-zero.`),{action:"invalid",path:t}):a==="absent"?{action:"absent",path:t}:(n.logger.info(`${e.label}: would remove "${r}" from ${o}.`),{action:"removed",path:t})},He=(e,r,t)=>e.flatMap(n=>ye(n,r)).filter(Se).filter(n=>t===void 0||n.scope===t),Ve=e=>{const r=e.home??b(),t=e.platform??process.platform,n=_(e.clients,()=>p,e.logger,"uninstall");if(n===void 0)return{code:1,removed:[]};const a=We(e);if(a.length===0)return e.logger.error("mcp uninstall: nothing to remove — `--docs-only` and `--local-only` are mutually exclusive, pass at most one."),{code:1,removed:[]};const o=[],l={home:r,platform:t,projectRoot:e.cwd};for(const c of He(n,l,e.scope))for(const i of a){const m=e.print===!0?Ge(c.client,i,c.path,e):ze(c.client,i,c.path,e);m.action!=="absent"&&o.push({...m,client:c.client.id,server:i})}return o.length===0?e.logger.info("Nothing to remove — no Lunora MCP servers were configured in the clients checked."):e.print===!0&&e.logger.info("Nothing was changed — re-run without --print to remove these."),{code:o.some(c=>c.action==="invalid")?1:0,removed:o}},E=e=>e.global===!0?"global":e.project===!0?"project":void 0,Ke=async(e,r)=>{const{code:t}=await Je({allowWrites:r.allowWrites===!0,cwd:e,noDocs:r.docs===!1,version:R,...r.docsUrl===void 0?{}:{docsUrl:r.docsUrl},...r.token===void 0?{}:{token:r.token},...r.url===void 0?{}:{url:r.url}});return{code:t}},lr=T(async({argument:e,cwd:r,logger:t,options:n})=>{const[a,...o]=e;if(a==="serve")return Ke(r,n);if(a==="uninstall"){const l=E(n),{code:c}=Ve({clients:o,cwd:r,docsOnly:n.docsOnly===!0,localOnly:n.localOnly===!0,logger:t,print:n.print===!0,...l===void 0?{}:{scope:l}});return{code:c}}if(a==="install"){if(n.list===!0)return _e({cwd:r,logger:t});const l=E(n),{code:c}=Ue({clients:o,cwd:r,docsOnly:n.docsOnly===!0,force:n.force===!0,localOnly:n.localOnly===!0,logger:t,print:n.print===!0,...l===void 0?{}:{scope:l},...n.docsUrl===void 0?{}:{docsUrl:n.docsUrl}});return{code:c}}return t.error("mcp: unknown subcommand. Usage: lunora mcp <install|uninstall|serve>"),{code:1}});export{lr as execute};