UNPKG

@lunora/cli

Version:

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

9 lines (8 loc) • 19.6 kB
import{projectConfigCandidatePaths as ee,readServiceBindings as ve,createCodegenProject as me,refreshCodegenProject as he,findTsconfig as we,PROJECT_CONFIG_FILENAMES as ye,runCodegen as te}from"@lunora/codegen";import{runPostCodegenHook as pe,resolveLazyFunctions as k,detectAgentRules as re,resolveSchemaDirectory as P,updateDevServerState as oe,readDevServerState as Se,DEV_DAEMON_ENV as ne,detectAiAgent as Ee,readProjectRemotePreference as be,readLiveDevServerState as ae,createDiscoveryCache as Re,DEV_HANDOFF_ENV as I,clearDevServerState as De,claimDevServerState as _e,DEV_LOG_FILE_ENV as ke,secretSourcesFromBindings as Pe,inferLunoraBindings as Te,ensureDevVarsExample as Ce,ensureDevVariables as $e,isInteractive as Ae,DEV_VARS_FILE as H,DEV_VARS_EXAMPLE_FILE as Oe,fillDevSecrets as Fe,checkDevEnv as Le,describeDevEnvCheck as Ie,DEV_BINDINGS_FILE as Ne,DEV_STATE_FILE as ie,writeCelldDevProjection as je,claimAgentRulesHint as Me,AGENT_RULES_HINT as We,devTriggerHints as He,formatDevBannerRow as xe}from"@lunora/config";import{WRANGLER_FILES as Ve,wranglerCodegenInputs as se,resolveRemoteEnabled as Ue,startLocalHyperdrive as Be,describeWithheld as ze}from"@lunora/config/cloudflare";import{p as Ge}from"../packem_shared/api-spec-lYyq4vL6.mjs";import{w as Xe}from"../packem_shared/binding-manifest-file-BZyQFSTF.mjs";import{createHash as Je}from"node:crypto";import{existsSync as A,watch as N,readFileSync as ce,statSync as Ye}from"node:fs";import{join as D,dirname as M}from"node:path";import{STUDIO_WRITE_TEMP_SUFFIX as Ke,consumeStudioWrite as x,loadStudioAssets as V,studioAssetsStamp as U,createStudioDocumentCache as Qe,renderStudioHtml as Ze,resolveAdminToken as qe,requestPathname as B,transportRejectionReason as z,SCHEMA_EDIT_ENDPOINT as et,POLICY_SCAFFOLD_ENDPOINT as tt,SEED_ENDPOINT as rt,ADVISOR_PROCEDURES_ENDPOINT as ot,sendStudioDocument as nt,serveJsonHandler as at,isStandaloneModulePath as it,readStandaloneAsset as st,assetContentType as ct,handleSchemaEditRequest as dt,handlePolicyScaffoldRequest as lt,handleSeedRequest as ut,handleAdvisorProceduresRequest as ft,sendStudioAsset as gt}from"@lunora/config/studio-host";import{LunoraError as vt}from"@lunora/errors";import{ts as G}from"ts-morph";import{a as mt}from"../packem_shared/codegen-error-AmH54ofi.mjs";import{a as ht}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{d as wt}from"../packem_shared/command-BpMv2n0o.mjs";import{a as yt}from"../packem_shared/deploy-target-resolve-BTCW1Iv4.mjs";import{EXIT_CODE as $}from"../packem_shared/EXIT_CODE-DQVhSE-1.mjs";import{forceJsonLogging as pt}from"../packem_shared/createLogger-4TujevyB.mjs";import{createServer as St,request as Et}from"node:http";import{connect as bt}from"node:net";import{pipeline as Rt}from"node:stream";import{c as Dt}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{setTimeout as _t}from"node:timers/promises";import{r as kt,d as Pt,P as Tt,a as Ct,b as j,c as $t,s as At,n as de,e as Ot,f as Ft,g as Lt,h as It,i as X,w as Nt,j as jt,k as Mt,t as Wt,l as Ht,m as xt,o as Vt}from"../packem_shared/plan-BF2E-dq4.mjs";import{b as Ut}from"./handler.mjs";const Bt=100,zt=/(?:\.[cm]?[jt]sx?|(?:^|[/\\])tsconfig(?:\..+)?\.json)$/u,L=300,J=/[/\\]/u,Y=e=>{try{return ce(e,"utf8")}catch{return""}},Gt=e=>{try{const{mtimeMs:t,size:o}=Ye(e);return`${String(t)}:${String(o)}`}catch{return""}},Xt=["pnpm-lock.yaml","package-lock.json","yarn.lock","bun.lock","node_modules/.modules.yaml","node_modules/.package-lock.json","node_modules/.yarn-integrity"],le=e=>{const t=M(e);return t===e?[e]:[e,...le(t)]},Jt=e=>{const t={...G.sys,onUnRecoverableConfigFileDiagnostic:()=>{},readDirectory:()=>[]},o=G.getParsedCommandLineOfConfigFile(e,{},t);return o===void 0?"":JSON.stringify(o.options)},Yt=(e,t)=>{const o=we(t),n=[...new Set([...ee(t),...ye.map(s=>D(e,s))])].map(s=>`${s} ${Y(s)}`),a=le(e).flatMap(s=>Xt.map(i=>`${D(s,i)} ${Gt(D(s,i))}`));return[o===void 0?"":`${o} ${Y(o)} ${Jt(o)}`,...n,...a].join("\0")},Kt=(e,t)=>{let o,r;return{drop:()=>{o=void 0},get:()=>{const n=Yt(e,t);return o===void 0||n!==r?(r=n,o=me(t)):he(o,t),o}}},Qt=(e,t,o,r)=>{const{apiSpec:n,lazyFunctions:a,logger:c,projectRoot:s,target:i}=e;try{const g=D(s,t,"schema.ts");if(!A(g))throw new vt("INTERNAL",`schema.ts not found at ${g}`);const h=te({apiSpec:n,lazyFunctions:k(a),lunoraDirectory:t,project:r.get(),projectRoot:s,target:i,...se(s)});c.success(`codegen: wrote ${t}/_generated (${o})`),ht(h.platformDiagnostics,c)}catch(g){return r.drop(),c.error(mt(g,o)),!1}return!0},K=e=>{const t=Je("sha256");for(const o of e){if(t.update(o).update("\0"),A(o)){t.update("present\0");try{t.update(ce(o))}catch{t.update("unreadable")}}else t.update("absent");t.update("\0")}return t.digest("hex")},Q=e=>e instanceof Error?e.stack??e.message:String(e),Zt=(e,t,o)=>{const r=[];for(const n of new Set([...e].map(a=>M(a))))if(A(n))try{const a=N(n,(c,s)=>{typeof s!="string"?t(void 0):e.has(D(n,s))&&t(s)});a.on("error",c=>{o(`codegen watch: stopped watching ${n} for lunora.config changes ${Q(c)}`),a.close()}),r.push(a)}catch(a){o(`codegen watch: could not watch ${n} for lunora.config changes ${Q(a)}`)}return r},qt=e=>{const t=e.lunoraDirectory??"lunora",o=D(e.projectRoot,t),r=e.debounceMs??Bt;let n=!1,a=!1,c=!1,s,i=0,g;const h=[...ee(o),...Ve.map(u=>D(e.projectRoot,u))];let p=Promise.resolve();const S=Kt(e.projectRoot,o);let d;const l=new Promise(u=>{d=u}),f=(u,m)=>{n||(s={codegen:m||s?.codegen===!0,reason:u},!a&&(a=!0,p=(async()=>{try{for(;s!==void 0;){const y=s;if(s=void 0,y.codegen&&(g=K(h)),!(y.codegen&&!Qt(e,t,y.reason,S))){c=!0;try{(await pe({cwd:e.projectRoot,logger:e.logger,spawner:e.spawner,stdoutToStderr:e.jsonLogs})).ran&&(i=Date.now())}finally{c=!1}}}}catch(y){e.logger.error(`codegen watch: ${y instanceof Error?y.message:String(y)}`)}finally{a=!1,d()}})()))};f("startup",!0);const w=u=>(e.logger.warn(`codegen watch unavailable (${u}) — schema edits will NOT auto-regenerate. Run \`lunora codegen\` manually after each edit.`),{close:()=>(n=!0,s=void 0,p),ready:l,watchAvailable:!1});let v,R;if(!A(o))return w(`no such directory: ${o}`);const E=new Set;let _=!1;const T=(u,m)=>{if(c||Date.now()-i<L){v&&(clearTimeout(v),v=void 0);let y=!1;for(const b of[...E,u])b!==void 0&&x(b)&&(y=!0);E.clear(),_=!1,y&&f(`change: ${m}`,!1);return}u===void 0?_=!0:E.add(u),v&&clearTimeout(v),v=setTimeout(()=>{const y=[...E].map(ge=>x(ge)),b=_||y.includes(!1);E.clear(),_=!1,f(`change: ${m}`,b)},r)},O=[],F=[],ue=new Set(h);let C;const W=u=>{if(!n){if(!c&&Date.now()-i>=L){clearTimeout(C),(u===void 0||K(h)!==g)&&T(void 0,u??"?");return}clearTimeout(C),C=setTimeout(()=>{W(u)},L)}};try{R=N(o,{recursive:!0},(u,m)=>{if(typeof m!="string"){T(void 0,"?");return}m.split(J).includes("_generated")||m.endsWith(Ke)||T(D(o,m),m)});for(const u of ve(e.projectRoot).services)if(u.rpcEntrypoint!==void 0){const m=N(M(u.wranglerPath),{recursive:!0},(y,b)=>{typeof b=="string"&&zt.test(b)&&!b.split(J).includes("node_modules")&&T(void 0,b)});m.on("error",y=>{e.logger.warn(`codegen watch: stopped watching service "${u.name}" (${y.message})`),m.close()}),O.push(m)}F.push(...Zt(ue,u=>{W(u)},u=>{e.logger.warn(u)}))}catch(u){R?.close();for(const m of O)m.close();for(const m of F)m.close();return w(u instanceof Error?u.message:String(u))}const fe=R;return{close:()=>{n=!0,s=void 0,v&&clearTimeout(v),clearTimeout(C),fe.close();for(const u of O)u.close();for(const u of F)u.close();return p},ready:l,watchAvailable:!0}},Z="/_lunora",er=3e4,q=(e,t,o,r=er)=>{const n=Et({headers:{...e.headers,host:o.host},hostname:o.hostname,method:e.method,path:e.url,port:o.port},a=>{n.setTimeout(0),t.writeHead(a.statusCode??502,a.headers),Rt(a,t,()=>{})});n.setTimeout(r,()=>{n.destroy(new Error(`no response within ${String(r)}ms`))}),n.on("error",a=>{if(t.headersSent){t.destroy();return}t.statusCode=a.message.startsWith("no response within")?504:502,t.end(`lunora dev: worker unreachable (${a.message})`)}),t.on("close",()=>{t.writableFinished||n.destroy()}),e.pipe(n)},tr=5e3,rr=(e,t,o,r)=>{const n=bt({host:r.hostname,port:Number(r.port)},()=>{n.setTimeout(0);const a=[`${e.method??"GET"} ${e.url??"/"} HTTP/1.1`];for(const[c,s]of Object.entries(e.headers))if(c!=="host")for(const i of Array.isArray(s)?s:[s])i!==void 0&&a.push(`${c}: ${i}`);a.push(`host: ${r.host}`,"",""),n.write(a.join(`\r `)),o.length>0&&n.write(o),n.pipe(t),t.pipe(n)});n.setTimeout(tr,()=>n.destroy()),n.on("error",()=>t.destroy()),t.on("error",()=>n.destroy())},or=async e=>{const t=e.host??"127.0.0.1",o=t==="127.0.0.1"||t==="localhost"||t==="::1",r=new URL(e.workerOrigin);let n=V(e.logger,import.meta.url),a=U(import.meta.url);const c=Qe(e.cwd,()=>Buffer.from(Ze({adminToken:o?qe(e.cwd):void 0,advisorProcedures:o,basePath:"/",dataEditable:o,rulesInstalled:re(e.cwd).installed,runAsIdentity:o,schemaEditable:o,scriptSrc:"/studio.js",styleHref:"/styles.css"}))),s=(d,l,f,w,v)=>{gt(d,l,f,w,v,a)},i=(d,l,f)=>{d.statusCode=l,d.setHeader("Content-Type","text/plain"),d.end(f)},g=P(e.cwd),h=(d,l,f,w)=>{if(o){at(d,l,f,e.cwd,{apiSpec:e.apiSpec,lazyFunctions:k(e.lazyFunctions),schemaDirectory:g});return}i(l,403,w)},p=(d,l,f)=>{const w=d==="/styles.css",v=it(d);if(!w&&!v)return!1;const R=U(import.meta.url);if(R!==a&&(n=V(e.logger,import.meta.url),a=R),n===void 0)return i(f,501,"Lunora studio assets not found — install and build @lunora/studio."),!0;if(w)return s(l,f,n.styles,"text/css; charset=utf-8","styles.css"),!0;const E=d.slice(d.lastIndexOf("/")+1),_=st(E,import.meta.url);return _===void 0?(i(f,404,"Not found"),!0):(s(l,f,_,ct(E),E),!0)};c();const S=St((d,l)=>{const f=B(d.url??"/");if(o){const v=z(d,e.logger);if(v!==void 0){i(l,403,v);return}}if(f.startsWith(Z)){if(!o){i(l,403,"Lunora studio: the worker admin proxy is only available on a loopback bind.");return}q(d,l,r);return}if(f===et){h(d,l,dt,"Lunora schema editing is only available on loopback hosts in dev.");return}if(f===tt){h(d,l,lt,"Lunora policy scaffolding is only available on loopback hosts in dev.");return}if(f===rt){h(d,l,ut,"Lunora data seeding is only available on loopback hosts in dev.");return}if(f===ot){h(d,l,ft,"Lunora advisor data is only available on loopback hosts in dev.");return}if(p(f,d,l))return;const w=d.headers["sec-fetch-mode"];if(o&&typeof w=="string"&&w!=="navigate"){q(d,l,r);return}nt(l,c())});return S.on("upgrade",(d,l,f)=>{if(!o||z(d,e.logger)!==void 0){l.destroy();return}B(d.url??"").startsWith(Z)?rr(d,l,f,r):l.destroy()}),await new Promise((d,l)=>{S.once("error",f=>{f.code==="EADDRINUSE"?l(new Error(`studio port ${String(e.port)} is already in use — pass a different port with --port, or stop the process using it`,{cause:f})):l(f)}),S.listen(e.port,t,()=>{d()})}),{close:()=>new Promise(d=>{S.close(()=>{d()})}),url:`http://${t==="0.0.0.0"||t==="::"?"localhost":t}:${String(e.port)}`}},nr=async e=>{const{cwd:t,logger:o,origin:r,signal:n}=e,a=e.probe??Pt,c=kt(e.readyTimeoutMs),s=Date.now()+c,i=()=>n.aborted;for(;!i()&&Date.now()<s;){let g=!1;try{g=await a(r,n)}catch{}if(i()||Date.now()>=s)break;if(g)return oe(t,{readyAt:new Date().toISOString()},{expectedPid:process.pid}),Se(t)?.readyAt!==void 0;try{await _t(Tt,void 0,{signal:n})}catch{}}return i()||o.warn(`server did not answer on ${r} within ${String(Math.round(c/1e3))}s — .lunora/dev.json will have no readyAt, so anything polling for readiness will keep waiting. The server itself is unaffected; raise LUNORA_DEV_READY_TIMEOUT_MS if it is just slow to boot.`),!1},ar=(e,t,o,r,n)=>{e.info(""),e.success("Lunora dev"),e.info(` ➜ Worker: ${t.workerOrigin}`),r!==void 0&&e.info(` ➜ Studio: ${r}`),t.runsCodegenWatch&&e.info(" ➜ Codegen: watching lunora/");for(const{label:a,text:c}of He({projectRoot:o,schemaDirectory:P(o),studioUrl:r}))e.info(xe(a,c,12));n!==void 0&&e.info(` ➜ Supervisor: ${n} (needs) · ${ie} (status)`),t.remote.enabled&&(t.remote.bindings.length>0?e.info(` ➜ Remote: ${t.remote.bindings.join(", ")} → deployed worker`):t.remote.reason!==void 0&&e.warn(` ➜ Remote: requested but inactive (${t.remote.reason}) — running fully local`));for(const a of t.remote.withheld)e.warn(` ➜ ${ze(a)}`);e.info("")},ir=(e,t)=>{re(t).installed||!Me()||(e.info(` ⓘ ${We}`),e.info(""))},sr=async(e,t,o)=>{if(o.flavor==="wrangler")try{const r=P(t),n=await Le({projectRoot:t,schemaDirectory:r,vars:{WORKER_ENV:"development"},withheld:o.remote.withheld.map(c=>c.binding)}),a=Ie(n,r);a!==void 0&&e[a.level](a.message)}catch{}},cr=async(e,t,o)=>{let r;try{r=Pe(await Te({cache:o,projectRoot:t,schemaDir:P(t)}))}catch{}if(r!==void 0)try{const a=(e.ensureExample??Ce)(t,r);if(a.length>0){const c=r.map(s=>s.includes(":")?`${s.replace(":"," (")})`:s);e.logger.info(`Updated .dev.vars.example with secrets for: ${c.join(", ")} (${a.join(", ")})`)}}catch{}const n=await(e.ensureEnv??$e)({confirm:Dt(),cwd:t,info:a=>{e.logger.info(a)},warn:a=>{e.logger.warn(a)}});if(n.status==="declined"&&!Ae()&&e.logger.info(`hint: ${H} was not scaffolded (non-interactive run). Copy ${Oe} → ${H} and fill in secrets, or run \`lunora dev\` in an interactive terminal to scaffold automatically.`),n.status!=="unreadable")try{(e.fillSecrets??Fe)({cwd:t,secretSources:r,info:a=>{e.logger.info(a)}})}catch{}},dr=(e,t,o,r,n)=>{if(e.flavor!=="wrangler")return;r!==void 0&&oe(t,{studioUrl:r});let a;try{a=Vt(t,o)}catch{}return ar(o,e,t,r,n),a},lr=(e,t)=>{const o=Number(process.env[I]),r=_e(t,{background:process.env[ne]==="1",logFile:process.env[ke],mode:"cli",pid:process.pid,startedAt:new Date().toISOString(),url:e.workerOrigin},Number.isInteger(o)&&o>0?{supersedePid:o}:void 0);return r.ok?void 0:r.existing},ur=e=>{const{cwd:t,destination:o,logger:r,plan:n}=e,a=o!==void 0,c=o??Ne,s=Xe({destination:c,dev:{...n.flavor==="wrangler"?{origin:n.workerOrigin}:{},statusFile:ie},logger:r,projectRoot:t,quiet:!a});return s.error!==void 0?a?s:(r.debug?.(`skipped the default binding manifest: ${s.error}`),{}):{written:c}},fr=async(e,t,o,r)=>{if(t.studioEnabled)try{return await(e.startStudio??or)({apiSpec:e.apiSpec,lazyFunctions:k(e.lazyFunctions),cwd:o,logger:{warnOnce:n=>{r.warn(n)}},port:t.studioPort,workerOrigin:t.workerOrigin})}catch(n){r.warn(`studio server failed to start (${n instanceof Error?n.message:String(n)}) — continuing without it`);return}},gr=e=>{const t=[e.runsCodegenWatch?"codegen watch":void 0,e.studioEnabled?"studio":void 0].filter(r=>r!==void 0);return`--no-worker: not starting wrangler. ${t.length>0?`${t.join(" + ")} running`:"nothing else to run"}; your task runner owns the worker on ${e.workerOrigin}.`},vr=(e,t,o,r,n)=>{if(!(e.sidecar===void 0||!Ht(t)))try{te({apiSpec:t.apiSpec,lazyFunctions:k(t.lazyFunctions),lunoraDirectory:P(o),projectRoot:o,target:n,...se(o)})}catch(a){r.warn(`codegen (pre-sidecar) failed: ${a instanceof Error?a.message:String(a)} — the framework dev server will retry`)}},mr=e=>e.flavor==="vite"?"starting vite dev (worker + studio + codegen run inside Vite via @lunora/vite)":`starting ${e.wrangler.tag} dev + studio`,hr=(e,t)=>{e.ipv4LoopbackForced&&t.info("no IPv6 loopback (::1) on this host — binding the worker to 127.0.0.1 (--ip) so wrangler dev doesn't crash. Pin `dev.ip` in wrangler.jsonc to override.")},wr=async(e,t,o,r)=>{if(e.celldSession!==!0||e.workerEnabled)return!0;try{for(const n of await(t.writeCelldProjection??je)({projectRoot:o}))r.warn(n);return!0}catch(n){return r.error(`could not write the celld projection: ${n instanceof Error?n.message:String(n)}`),!1}},yr=async(e,t,o,r,n)=>{try{return e.celldSession===!0?await xt({logger:n,port:e.workerPort,projectRoot:r,start:t.startCelldSession}):o(e.wrangler,n)}catch(a){n.error(`could not start the worker: ${a instanceof Error?a.message:String(a)}`);return}},pr=async(e,t,o)=>{const r=await(e.startHyperdrive??Be)({onWarning:n=>{o.warn(n)},projectRoot:t});return r!==void 0&&r.bindings.length>0&&o.info(`Hyperdrive ${r.bindings.join(", ")}: embedded Postgres (PGlite), data in .wrangler/state/lunora-pglite. Set CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_<BINDING> to use your own.`),r},Sr=async e=>{const{logger:t}=e,o=Re(),r=e.cwd??process.cwd(),n=e.flavor??Ot(r),a=yt(r,e.target);if(a.target===void 0)throw new Error(a.error??"unknown deploy target");const{target:c}=a,s=Ft(c,n,t);s==="wrangler"&&await Ut(r,t,void 0,c,void 0,o);const i=await Lt({...e,flavor:s,target:c}),g={remoteCleanup:i.remote.cleanup,serviceConfigCleanup:i.serviceConfigCleanup};try{const h=Number(process.env[I]),p=ae(r);if(p!==void 0&&p.pid!==process.pid&&p.pid!==h)return j(t,p),{code:0,plan:i};const S=lr(i,r);if(S!==void 0)return j(t,S),{code:0,plan:i};(i.flavor==="vite"||i.flavor==="framework-worker")&&(i.wrangler.env={...i.wrangler.env,[I]:String(process.pid)}),i.workerEnabled&&c==="cloudflare"&&(g.hyperdrive=await pr(e,r,t)),await cr(e,r,o),await sr(t,r,i),t.info(mr(i)),It(t,r),hr(i,t),i.runsCodegenWatch&&(g.codegen=(e.startCodegen??qt)({apiSpec:e.apiSpec,lazyFunctions:k(e.lazyFunctions),jsonLogs:e.jsonLogs,logger:t,lunoraDirectory:P(r),projectRoot:r,target:c})),g.studio=await fr(e,i,r,t);const d=ur({cwd:r,destination:e.emitBindings,logger:t,plan:i});if(d.error!==void 0)return t.error(d.error),{code:$.USAGE,plan:i};await g.codegen?.ready;const l=g.studio?.url;i.frameworkHint!==void 0&&t.warn(i.frameworkHint);const f=()=>{i.flavor==="wrangler"&&(g.readyProbe=new AbortController,nr({cwd:r,logger:t,origin:i.workerOrigin,probe:e.probeReady,signal:g.readyProbe.signal}))};if(!await wr(i,e,r,t))return{code:$.FAILURE,plan:i};if(!i.workerEnabled)return f(),t.info(gr(i)),g.tunnel=X({cwd:r,logger:t,plan:i,tunnel:e.tunnel}),{code:await(e.waitForInterrupt??Nt)(t),plan:i};vr(i,e,r,t,c);const w=e.startWorker??jt,v=await yr(i,e,w,r,t);if(v===void 0)return{code:$.FAILURE,plan:i};const R=i.sidecar===void 0?void 0:w(i.sidecar,t);return f(),g.containerLogs=dr(i,r,t,l,d.written),g.tunnel=X({cwd:r,logger:t,plan:i,tunnel:e.tunnel}),ir(t,r),{code:await Mt(v,R,t),plan:i}}finally{g.readyProbe?.abort(),De(r,process.pid),await Wt(g)}},Er=e=>({codegen:e.codegen===!1?!1:void 0,studio:e.studio===!1?!1:void 0,worker:e.worker===!1?!1:void 0}),br=e=>{if(e.local===!0&&e.remote===!0)return"`--local` and `--remote` are mutually exclusive — pass at most one.";const{entries:t,invalid:o}=de(e.allowMail);if(o.length>0)return`\`--allow-mail\` takes email addresses or '*@domain' — not ${o.map(r=>`"${r}"`).join(", ")}.`;if(t.length>0&&e.tunnel!==!0)return"`--allow-mail` only applies to a tunnel — add `--tunnel`."},Rr=e=>e.tunnel===!0?{allowMail:de(e.allowMail).entries}:void 0,Jr=wt(async({argument:e,cwd:t,logger:o,options:r})=>{const n=r.json===!0,a=Ct({cwd:t,json:n,lines:r.lines,logger:o,subcommand:e[0]});if(a!==void 0)return a;const c=process.env[ne]==="1",s=c?void 0:Ee(),i=n||s!==void 0;i&&pt(),s!==void 0&&r.background!==!0&&o.info(`AI agent detected (${s.name} via ${s.variable}) — starting the dev server in background mode with JSON logs. Set LUNORA_AGENT_MODE=0 to opt out.`);const g=br(r);if(g!==void 0)return o.error(`dev: ${g}`),{code:$.USAGE};const h=Rr(r),p=r.local===!0?!1:Ue({configPreference:be(t),envValue:process.env.LUNORA_REMOTE,flag:r.remote});if(!c&&(r.background===!0||s!==void 0)){const S=ae(t);return S!==void 0?(j(o,S),{code:0}):(h?.allowMail.length===0&&$t(o),At({cwd:t,jsonLogs:i,logger:o,options:r,remote:p}))}return Sr({apiSpec:Ge(r.apiSpec),cwd:t,emitBindings:r.emitBindings,inspectorPort:r.inspectorPort,lazyFunctions:k(r.lazyFunctions),jsonLogs:i,local:r.local,logger:o,port:r.port,remote:p,target:r.target,tunnel:h,workerPort:r.workerPort,...Er(r)})});export{br as devFlagConflict,Jr as execute,Er as negatableDevFlags,Sr as runDevCommand};