@lunora/cli 1.0.0-alpha.362 → 1.0.0-alpha.364
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.
- package/dist/packem_chunks/handler6.mjs +2 -2
- package/dist/packem_chunks/runDeployCommand.mjs +1 -1
- package/dist/packem_chunks/runDevCommand.mjs +2 -2
- package/package.json +11 -11
- package/skills/lunora/SKILL.md +140 -164
- package/skills/lunora-create-package/SKILL.md +97 -85
- package/skills/lunora-deploy/SKILL.md +175 -144
- package/skills/lunora-functions/SKILL.md +186 -85
- package/skills/lunora-migration-helper/SKILL.md +146 -174
- package/skills/lunora-performance-audit/SKILL.md +135 -162
- package/skills/lunora-quickstart/SKILL.md +128 -195
- package/skills/lunora-realtime/SKILL.md +137 -130
- package/skills/lunora-setup-auth/SKILL.md +157 -124
- package/skills/lunora-setup-hyperdrive/SKILL.md +101 -104
- package/skills/lunora-setup-hyperdrive-global/SKILL.md +92 -94
- package/skills/lunora-setup-mail/SKILL.md +83 -117
- package/skills/lunora-setup-scheduler/SKILL.md +130 -99
- package/skills/lunora-setup-storage/SKILL.md +83 -149
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{existsSync as E,readFileSync as P}from"node:fs";import{join as D}from"node:path";import{DEV_VARS_FILE as m,DEV_VARS_KEY_PATTERN as b,writeDevVariablesFileAtomically as w,removeDevVariableLine as K,upsertDevVariableLine as _,isPlaceholderValue as S,detectPackageManager as j,resolveDeployDriver as z,resolveProjectTarget as M,toolchainExecArgs as T,generateSecretValue as C,DEV_VARS_EXAMPLE_FILE as g,parseDevVariableEntries as G,
|
|
2
|
-
`),{code:0,data:{key:r.key,subcommand:"get",value:s.value},descriptors:[]}):(t.error(`env: ${r.key} is not set in ${m}`),{code:d.NOT_FOUND,descriptors:[]})},Q=e=>{const{devVariablesPath:o,logger:t,options:r}=e;if(!r.key)return t.error("env set requires a key. Usage: lunora env set <KEY> <VALUE>"),{code:d.USAGE,descriptors:[]};if(!b.test(r.key))return t.error(`env: invalid key "${r.key}" — must match [A-Za-z_][A-Za-z0-9_]*`),{code:d.USAGE,descriptors:[]};if(r.value===void 0)return t.error("env set requires a value. Usage: lunora env set <KEY> <VALUE>"),{code:d.USAGE,descriptors:[]};if(X.test(r.value))return t.error(`env: value for "${r.key}" contains a newline, which .dev.vars cannot represent`),{code:d.USAGE,descriptors:[]};if(H.test(r.value))return t.error(`env: value for "${r.key}" contains a double-quote or backslash, which .dev.vars cannot round-trip`),{code:d.USAGE,descriptors:[]};const s=h(o);return w(o,_(s,r.key,r.value)),t.success(`env: set ${r.key} (${
|
|
1
|
+
import{existsSync as E,readFileSync as P}from"node:fs";import{join as D}from"node:path";import{DEV_VARS_FILE as m,DEV_VARS_KEY_PATTERN as b,writeDevVariablesFileAtomically as w,removeDevVariableLine as K,upsertDevVariableLine as _,isPlaceholderValue as S,detectPackageManager as j,resolveDeployDriver as z,resolveProjectTarget as M,toolchainExecArgs as T,generateSecretValue as C,DEV_VARS_EXAMPLE_FILE as g,parseDevVariableEntries as G,secretSourcesFromBindings as O,inferLunoraBindings as Y,resolveSchemaDirectory as F,requiredSecrets as q,isMintableSecretKey as U}from"@lunora/config";import{d as Z}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as d}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{defaultSpawner as B}from"../packem_shared/createRecordingSpawner-Ch7zuQQE.mjs";import{l as I}from"../packem_shared/wrangler-secrets-3chIVv3H.mjs";const X=/[\r\n]/u,H=/["\\]/u,L=e=>new Map(G(e).map(o=>[o.key,o])),h=e=>E(e)?P(e,"utf8"):"",R=e=>e.length<=4?"****":`${e.slice(0,4)}${"*".repeat(Math.min(8,e.length-4))}`,p=e=>L(h(e)),$=e=>e.env??(e.prod===!0?"production":void 0),W=e=>{const o=p(e.devVariablesPath),t={file:m,keys:[...o.keys()],subcommand:"list"};if(o.size===0)return e.logger.info(`${m}: (empty)`),{code:0,data:t,descriptors:[]};for(const r of o.values())e.logger.info(`${r.key}=${R(r.value)}`);return{code:0,data:t,descriptors:[]}},J=e=>{const{devVariablesPath:o,logger:t,options:r}=e;if(!r.key)return t.error("env get requires a key. Usage: lunora env get <KEY>"),{code:d.USAGE,descriptors:[]};const s=p(o).get(r.key);return s?(r.format!=="json"&&process.stdout.write(`${s.value}
|
|
2
|
+
`),{code:0,data:{key:r.key,subcommand:"get",value:s.value},descriptors:[]}):(t.error(`env: ${r.key} is not set in ${m}`),{code:d.NOT_FOUND,descriptors:[]})},Q=e=>{const{devVariablesPath:o,logger:t,options:r}=e;if(!r.key)return t.error("env set requires a key. Usage: lunora env set <KEY> <VALUE>"),{code:d.USAGE,descriptors:[]};if(!b.test(r.key))return t.error(`env: invalid key "${r.key}" — must match [A-Za-z_][A-Za-z0-9_]*`),{code:d.USAGE,descriptors:[]};if(r.value===void 0)return t.error("env set requires a value. Usage: lunora env set <KEY> <VALUE>"),{code:d.USAGE,descriptors:[]};if(X.test(r.value))return t.error(`env: value for "${r.key}" contains a newline, which .dev.vars cannot represent`),{code:d.USAGE,descriptors:[]};if(H.test(r.value))return t.error(`env: value for "${r.key}" contains a double-quote or backslash, which .dev.vars cannot round-trip`),{code:d.USAGE,descriptors:[]};const s=h(o);return w(o,_(s,r.key,r.value)),t.success(`env: set ${r.key} (${R(r.value)}) in ${m}`),{code:0,data:{key:r.key,subcommand:"set"},descriptors:[]}},x=e=>{const{devVariablesPath:o,logger:t,options:r}=e;if(!r.key)return t.error("env unset requires a key. Usage: lunora env unset <KEY>"),{code:d.USAGE,descriptors:[]};if(!b.test(r.key))return t.error(`env: invalid key "${r.key}" — must match [A-Za-z_][A-Za-z0-9_]*`),{code:d.USAGE,descriptors:[]};const s=h(o);return L(s).has(r.key)?(w(o,K(s,r.key)),t.success(`env: unset ${r.key} in ${m}`),{code:0,data:{key:r.key,removed:!0,subcommand:"unset"},descriptors:[]}):(t.warn(`env: ${r.key} was not set in ${m}`),{code:0,data:{key:r.key,removed:!1,subcommand:"unset"},descriptors:[]})},ee=async e=>{const{devVariablesPath:o,logger:t,options:r}=e;if(!r.yes)return t.error("env push uploads secrets to Cloudflare. Re-run with --yes to confirm."),{code:d.USAGE,descriptors:[]};const s=p(o);if(s.size===0)return t.warn(`${m}: nothing to push (empty)`),{code:0,data:{pushed:[],subcommand:"push",target:$(r)},descriptors:[]};const n=[...s.values()].filter(a=>S(a.value)).map(a=>a.key);if(n.length>0)return t.error(`env push: refusing to upload placeholder value(s) for ${n.join(", ")} — run \`lunora env doctor\` to review, and \`lunora env generate --set\` (or \`lunora env set <KEY> <VALUE>\`) to fill them, then re-run.`),{code:d.USAGE,descriptors:[]};const c=r.spawner??B,u=r.cwd??process.cwd(),l=j(u),i=[],v=$(r),f=z(M(u)),y=f.toolchain?.secretPut;if(y===void 0)return t.error(`deploy target "${f.id}" has no secret store; cannot push secrets`),{code:d.USAGE,descriptors:[]};for(const a of s.values()){const N=y({environment:v,key:a.key,temporary:r.temporary}),A=T(l,N),V={args:A.args,command:A.command,cwd:u,input:a.value};i.push(V),t.info(`pushing ${a.key} -> wrangler secret${v===void 0?"":` (${v})`}`);const k=await c(V);if(k.code!==0)return t.error(`env push: failed at ${a.key} (exit ${String(k.code)})`),{code:k.code,descriptors:i}}return t.success(`env: pushed ${String(s.size)} secret(s)`),{code:0,data:{pushed:[...s.keys()],subcommand:"push",target:v},descriptors:i}},re=e=>(e.options.secretLister??I)({cwd:e.cwd,env:$(e.options),temporary:e.options.temporary}),te=async e=>{const{devVariablesPath:o,logger:t}=e,r=await re(e);if(!r.ok)return t.error(`env diff: ${r.error??"failed to list remote secrets"}`),{code:1,descriptors:[]};const s=new Set(p(o).keys()),n=new Set(r.names),c=[...s].filter(i=>!n.has(i)).toSorted((i,v)=>i.localeCompare(v)),u=r.names.filter(i=>!s.has(i)),l=[...s].filter(i=>n.has(i)).toSorted((i,v)=>i.localeCompare(v));for(const i of c)t.info(`local only (run \`lunora env push\`): ${i}`);for(const i of u)t.info(`remote only (in Cloudflare, not ${m}): ${i}`);return t.info(`in both: ${String(l.length)} secret(s)`),c.length===0&&u.length===0&&t.success("env diff: local and remote secret names match"),{code:0,data:{both:l,localOnly:c,remoteOnly:u,subcommand:"diff"},descriptors:[]}},se=e=>{const{cwd:o,devVariablesPath:t,logger:r}=e,s=D(o,g);if(!E(s))return r.info(`env doctor: no ${g} to check against — nothing to validate.`),{code:0,data:{extra:[],missing:[],ok:!0,placeholders:[],subcommand:"doctor"},descriptors:[]};const n=G(P(s,"utf8")).map(a=>a.key),c=p(t);if(!E(t))return r.error(`env doctor: ${m} is missing. Run \`lunora dev\` to scaffold it, or \`lunora env set <KEY> <VALUE>\`.`),r.info(`expected (from ${g}): ${n.join(", ")}`),{code:d.NOT_FOUND,descriptors:[]};const u=n.filter(a=>!c.has(a)),l=[...c.values()].filter(a=>S(a.value)).map(a=>a.key),i=new Set(n),v=[...c.keys()].filter(a=>!i.has(a));for(const a of u)r.error(`missing: ${a} is in ${g} but not ${m}`);for(const a of l)r.error(`unset: ${a} still has a placeholder value`);for(const a of v)r.info(`extra: ${a} is set locally but not listed in ${g}`);const f=u.length===0&&l.length===0,y={extra:v,missing:u,ok:f,placeholders:l,subcommand:"doctor"};return f?(r.success(`env doctor: ${m} looks good (${String(c.size)} var(s)).`),{code:0,data:y,descriptors:[]}):{code:1,data:y,descriptors:[]}},oe=async e=>{let o=[];try{o=O(await Y({projectRoot:e.cwd,schemaDir:F(e.cwd)}))}catch{}const t=q(o).map(s=>s.key).filter(s=>U(s)),r=[...p(e.devVariablesPath).keys()].filter(s=>U(s));return[...new Set([...t,...r])]},ne=(e,o,t)=>{const r=p(e),s=n=>{const c=r.get(n);return c!==void 0&&c.value!==""&&!S(c.value)};return{live:o.filter(n=>s(n.key)).map(n=>n.key),writable:t?o:o.filter(n=>!s(n.key))}},ae=(e,o)=>{const{devVariablesPath:t,logger:r,options:s}=e,{live:n,writable:c}=ne(t,o,s.yes===!0);if(c.length===0)return r.error(`env generate --set: ${n.join(", ")} already hold(s) a live secret and rotating it is irreversible (outstanding signed URLs and bearers stop verifying). Re-run with --yes to rotate anyway.`),{code:d.USAGE,descriptors:[]};n.length>0&&r.warn(`env generate --set: left ${n.join(", ")} untouched (already set) — re-run with --yes to rotate them too`);let u=h(t);for(const l of c)u=_(u,l.key,l.value);return w(t,u),r.success(`env: generated ${String(c.length)} secret(s) into ${m}: ${c.map(l=>l.key).join(", ")}`),{code:0,data:{subcommand:"generate",written:c.map(l=>l.key)},descriptors:[]}},ce=async e=>{const{logger:o,options:t}=e;let r;if(t.key===void 0){if(r=await oe(e),r.length===0)return o.info("env generate: no locally-generatable secrets for this project. Name one explicitly: lunora env generate <KEY>"),{code:0,data:{secrets:[],subcommand:"generate"},descriptors:[]}}else{if(!b.test(t.key))return o.error(`env: invalid key "${t.key}" — must match [A-Za-z_][A-Za-z0-9_]*`),{code:d.USAGE,descriptors:[]};r=[t.key]}const s=r.map(n=>({key:n,value:C()}));if(t.set===!0)return ae(e,s);if(t.format!=="json")for(const n of s)process.stdout.write(`${n.key}=${n.value}
|
|
3
3
|
`);return{code:0,data:{secrets:s,subcommand:"generate"},descriptors:[]}},ie=async e=>{const{options:o}=e;switch(o.subcommand){case"diff":return te(e);case"doctor":return se(e);case"generate":return ce(e);case"get":return J(e);case"list":return W(e);case"push":return ee(e);case"set":return Q(e);case"unset":return x(e);default:return e.logger.error(`env: unknown subcommand "${o.subcommand}"`),{code:d.USAGE,descriptors:[]}}},de=async e=>{const o=e.cwd??process.cwd(),t={cwd:o,devVariablesPath:D(o,m),logger:e.logger,options:e};return ie(t)},ue=new Set(["diff","doctor","generate","get","list","push","set","unset"]),le=e=>typeof e=="string"&&ue.has(e),ke=Z(({argument:e,cwd:o,format:t,logger:r,options:s})=>{const n=e[0];if(!le(n)){const c=`env: unknown subcommand "${n??""}" — expected list | get | set | unset | push | diff | doctor | generate`;return r.error(c),{code:d.USAGE,error:c}}return de({cwd:o,env:s.env,format:t,key:e[1],logger:r,prod:s.prod===!0,set:s.set===!0,subcommand:n,temporary:s.temporary===!0,value:e[2],yes:s.yes===!0})});export{ke as execute,de as runEnvCommand};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{dirname as F,join as B}from"node:path";import{discoverMigrations as te,readServiceBindings as ne,runCodegen as oe}from"@lunora/codegen";import{readLinkedProject as W,execArgsFor as H,detectPackageManager as b,discoverContainerInfo as V,COMPOSED_WORKER_ENTRY as N,writeLinkedProject as ae,discoverSchemaInfo as G,DEV_VARS_FILE as w,parseDevVariableEntries as K,isMintableSecretKey as I,
|
|
1
|
+
import{dirname as F,join as B}from"node:path";import{discoverMigrations as te,readServiceBindings as ne,runCodegen as oe}from"@lunora/codegen";import{readLinkedProject as W,execArgsFor as H,detectPackageManager as b,discoverContainerInfo as V,COMPOSED_WORKER_ENTRY as N,writeLinkedProject as ae,discoverSchemaInfo as G,DEV_VARS_FILE as w,parseDevVariableEntries as K,isMintableSecretKey as I,secretSourcesFromBindings as ie,inferLunoraBindings as q,resolveSchemaDirectory as R,requiredSecrets as se,generateSecretValue as ce,toolchainExecArgs as j,upsertDevVariableLine as de,writeDevVariablesFileAtomically as le,resolveDeployDriver as C,planToolchainInvocation as Y,runPostCodegenHook as ue}from"@lunora/config";import{findWranglerFile as z,readWranglerJsonc as P,mergeWranglerEnvironment as J,warnCloudflareCliConfigOnce as ge,validateWranglerProject as me,reconcileWranglerBindings as fe,reconcileWranglerCompatibilityDate as ve,reconcileWranglerCrons as he,describePreservedCrons as pe}from"@lunora/config/cloudflare";import{Spinner as ye}from"@visulima/spinner";import{r as we,a as ke,e as be}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as $e,a as Se}from"../packem_shared/deploy-target-DCWwiuAe.mjs";import{mkdirSync as De,writeFileSync as x,existsSync as p,readFileSync as k}from"node:fs";import{m as Ee,e as Ae,i as Re,b as je,a as Ce}from"../packem_shared/secret-key-BCrqNJ68.mjs";import{w as Pe}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{d as xe}from"../packem_shared/command-CAXl2A1S.mjs";import{r as _}from"../packem_shared/wrangler-name-Dsk5K1f-.mjs";import{EXIT_CODE as h}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{containerBuildTag as _e}from"@lunora/container";import{a as Te,i as Ne}from"../packem_shared/docker-DpVxvYpL.mjs";import{defaultSpawner as D}from"../packem_shared/createRecordingSpawner-Ch7zuQQE.mjs";import{r as X}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{p as Ie,H as Le,a as Me,r as Ue}from"../packem_shared/health-probe-Bw9JFfIy.mjs";import{join as y}from"@visulima/path";import{Project as Oe}from"ts-morph";import{runMigrateDataCommand as Fe}from"../packem_shared/runMigrateGenerateCommand-Ii_WMZEA.mjs";import{c as Be}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{l as We}from"../packem_shared/wrangler-secrets-3chIVv3H.mjs";const He=Object.freeze({edges:[],nodes:[],modules:[],unresolved:[],version:1}),Ve=20,L=e=>`${e.from} -${e.kind}-> ${e.to}`,$=(e,r)=>{const o=new Set(e);return r.filter(t=>!o.has(t)).toSorted((t,n)=>t.localeCompare(n))},Ge=(e,r)=>{const o=e.modules.map(i=>i.name),t=r.modules.map(i=>i.name),n=e.edges.map(i=>L(i)),a=r.edges.map(i=>L(i));return{addedEdges:$(n,a),addedModules:$(o,t),removedEdges:$(a,n),removedModules:$(t,o)}},S=(e,r,o)=>{if(o.length===0)return[];const t=o.slice(0,Ve).map(a=>` ${e} ${a}`),n=o.length-t.length;return[`${r}:`,...t,...n>0?[` … and ${n.toString()} more`]:[]]},Ke=e=>{const r=[...S("+","modules added",e.addedModules),...S("-","modules removed",e.removedModules),...S("+","edges added",e.addedEdges),...S("-","edges removed",e.removedEdges)];return r.length===0?void 0:`architecture changes since the last deploy:
|
|
2
2
|
${r.join(`
|
|
3
3
|
`)}`},qe=(e,r)=>B(e,".lunora",r===void 0?"architecture.json":`architecture.${r}.json`),Ye=e=>{if(p(e))try{const r=JSON.parse(k(e,"utf8"));return r.version===1&&Array.isArray(r.modules)&&Array.isArray(r.edges)?r:void 0}catch{return}},ze=e=>{const{cwd:r,environment:o,logger:t}=e,n=qe(r,o),a=Ye(n),i=e.current??(a===void 0?void 0:He);if(i===void 0)return;const s=a===void 0?void 0:Ke(Ge(a,i));return s!==void 0&&t.info(s),()=>{try{De(F(n),{recursive:!0}),x(n,`${JSON.stringify(i,void 0,2)}
|
|
4
4
|
`,"utf8")}catch(c){t.warn(`could not record the deployed architecture at ${n}: ${c instanceof Error?c.message:String(c)}`)}}},Je=e=>{const{cwd:r,env:o,logger:t,mintedSecretsFile:n}=e;try{const a=W(r),i=a?.workerName??_(r),s=e.url??a?.workerUrl;t.success("deploy complete"),t.info(` worker: ${i??"(see wrangler output above)"}`),o!==void 0&&t.info(` env: ${o}`),s===void 0?t.info(" url: run `lunora link --url <https://your-worker>` to record it"):t.info(` url: ${s}`),n!==void 0&&t.info(` secrets: generated value(s) recorded in ${n}`),e.logsAvailable&&t.info(" logs: lunora logs")}catch{}},Xe=async e=>{if(e.targets.length===0)return{builtTags:[],code:0};if(!(e.railpackAvailable??Te)()){const t="deploy blocked: a container uses `image: { build }` (Railpack), but Railpack isn't ready. Install the `railpack` CLI and start a BuildKit instance, e.g. `docker run --rm --privileged -d --name buildkit moby/buildkit` then `export BUILDKIT_HOST=docker-container://buildkit`. Alternatively switch the container's `image` to a Dockerfile path or a pre-built registry reference.";return e.logger.error(t),{builtTags:[],code:1,error:t}}const r=e.spawner??D,o=[];for(const t of e.targets){const n=_e(t.exportName),a={args:["build",t.buildDir,"--name",n],command:"railpack",cwd:e.cwd},i=H(b(e.cwd),"wrangler",["containers","push",n]),s={args:i.args,command:i.command,cwd:e.cwd};e.logger.info(`railpack: building "${t.exportName}" → ${n} from ${t.buildDir}`);const c=await r(a);if(c.code!==0){const d=`railpack build failed for container "${t.exportName}" (${t.buildDir})`;return e.logger.error(d),{builtTags:o,code:c.code,error:d}}e.logger.info(`railpack: pushing ${n} to the Cloudflare Registry`);const l=await r(s);if(l.code!==0){const d=`wrangler containers push failed for "${t.exportName}" (${n})`;return e.logger.error(d),{builtTags:o,code:l.code,error:d}}o.push(n)}return{builtTags:o,code:0}},Qe=e=>{const o=[z(e),B(e,"package.json")].filter(t=>t!==void 0&&p(t)).map(t=>[t,k(t,"utf8")]);return()=>{for(const[t,n]of o)k(t,"utf8")!==n&&x(t,n,"utf8")}},Q="<replace-with-d1-create-id>",M=e=>Array.isArray(e)?e.filter(r=>r!=null):void 0,T=(e,r)=>{const o=z(e);if(!o)return;const{parsed:t}=P(o);if(t===void 0)return;const{error:n,merged:a}=J(t,r),i=n===void 0?a:t,{containers:s,d1_databases:c,vars:l}=i;return{containers:M(s),d1_databases:M(c),vars:typeof l=="object"&&l!==null&&!Array.isArray(l)?l:void 0}},Ze=/^127(?:\.\d{1,3}){3}$/,er=e=>{try{const{hostname:r}=new URL(e);return r==="localhost"||Ze.test(r)||r==="::1"||r==="[::1]"}catch{return!1}},rr=e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"),tr=(e,r,o,t="deploy",n)=>{const a=(T(e,n)?.containers??[]).filter(s=>typeof s?.image=="string"&&rr(s.image));if(a.length===0||o())return;const i=`${t} blocked: wrangler.jsonc declares ${String(a.length)} container(s) built from a local Dockerfile, but no Docker-compatible engine is available. Start Docker (or Colima), or point the container's \`image\` at a pre-built registry reference. Note: container images must target linux/amd64.`;return r.error(i),i},Z=e=>p(y(e,N))?N:void 0,nr=(e,r,o="deploy")=>{for(const t of V(e,"lunora").containers){const n=t.schedulingPolicy===void 0?t.image:void 0,i=[...n?.kind==="dockerfile"?[{field:"image",path:n.dockerfilePath}]:[],...Object.entries(t.schedulingPolicy==="durable_object"?t.images??{}:{}).flatMap(([s,c])=>c.kind==="dockerfile"?[{field:`images["${s}"]`,path:c.dockerfilePath}]:[])].find(s=>!p(y(e,s.path)));if(i!==void 0){const s=`${o} blocked: container "${t.exportName}" references a Dockerfile at "${i.path}" that does not exist. Create it or fix the \`${i.field}\` path in lunora/containers.ts.`;return r.error(s),s}if(n?.kind==="build"&&!p(y(e,n.buildDir))){const s=`${o} blocked: container "${t.exportName}" references a Railpack build directory "${n.buildDir}" that does not exist. Create it or fix the \`image.build\` path in lunora/containers.ts.`;return r.error(s),s}}},or=(e,r)=>(T(e,r)?.d1_databases??[]).find(o=>o.database_id===Q)?.binding,ar=e=>{if(!e.migrate||e.dryRun||e.preview)return;if(e.migrateUrl===void 0){const o="--migrate requires --migrate-url <https://your-worker> — the deploy target URL is only known after wrangler runs, and this gate runs before it; refusing to default to localhost";return e.logger.error(o),o}if(e.migrateYes!==!0){const o="--migrate runs production data migrations after deploy. Re-run with --migrate-yes to confirm.";return e.logger.error(o),o}const r=e.migrateToken??process.env.LUNORA_ADMIN_TOKEN;if(r===void 0||r===""){const o="admin token required for --migrate — pass --migrate-token or set LUNORA_ADMIN_TOKEN";return e.logger.error(o),o}},ir=(e,r,o="deploy",t)=>{const n=or(e,t);if(n===void 0)return;const a=`${o} blocked: the "${n}" D1 binding has a placeholder database_id ("${Q}"). Run \`wrangler d1 create <name>\` to create the database, then replace the placeholder in wrangler.jsonc with the real id before deploying.`;return r.error(a),a},sr=(e,r,o="deploy",t)=>{const n=T(e,t)?.vars;if(!n)return;const a=Object.entries(n).filter(([,s])=>typeof s=="string"&&er(s)).map(([s])=>s).toSorted((s,c)=>s.localeCompare(c));if(a.length===0)return;const i=`${o} blocked: ${a.join(", ")} in wrangler.jsonc point at localhost. A deployed Worker can't reach a loopback address, so this silently breaks scheduled-job dispatch, reverse cross-shard relations, and auth callbacks. Set each to the deployed worker's public URL (or move it to a secret with \`wrangler secret put\`) before deploying.`;return r.error(i),i},cr=(e,r,o)=>{const t=ir(e,r.logger,o,r.env);if(t!==void 0)return{code:h.USAGE,error:t};const n=sr(e,r.logger,o,r.env);if(n!==void 0)return{code:h.USAGE,error:n};const a=nr(e,r.logger,o);if(a!==void 0)return{code:h.USAGE,error:a};const i=tr(e,r.logger,r.dockerAvailable??Ne,o,r.env);return i===void 0?void 0:{code:h.MISSING_DEPENDENCY,error:i}},dr=/https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u,lr=/https:\/\/[^\s"'<>]+/u,ur=e=>{if(e===void 0)return;const r=dr.exec(e);return r?r[0]:lr.exec(e)?.[0]},U=e=>e===void 0?"":` (--env ${e})`,gr=({cwd:e,env:r,logger:o,now:t,url:n})=>{if(n!==void 0)try{const a=W(e);if(a!==void 0){if(a.workerUrl===n&&a.env===r)return;o.warn(`link: .lunora/project.json records ${a.workerUrl??"(no url)"}${U(a.env)}, but this deploy published ${n}${U(r)}. Keeping the recorded value — run \`lunora link --url ${n}${r===void 0?"":` --env ${r}`}\` to update it.`);return}const i=(t??(()=>new Date().toISOString()))();ae(e,{env:r,linkedAt:i,workerName:_(e),workerUrl:n}),o.success(`link: recorded ${n} in .lunora/project.json (run \`lunora link\` to change)`)}catch{}},mr=async(e,r)=>{const o=new Oe({skipAddingFilesFromTsConfig:!0}),t=y(r,"lunora");let n;try{n=te(o,t)}catch(a){const i=a instanceof Error?a.message:String(a);return e.logger.warn(`--migrate: could not discover migrations (${i}); skipping`),0}if(n.length===0)return e.logger.info("--migrate: no data migrations declared in lunora/"),0;e.logger.info(`--migrate: running ${String(n.length)} migration(s) against deployed worker`);for(const a of n){e.logger.info(`--migrate: up "${a.id}" (table "${a.table}")`);const i={cwd:r,fetchImpl:e.fetchImpl,id:a.id,logger:e.logger,prod:!0,subcommand:"up",token:e.migrateToken,url:e.migrateUrl,yes:e.migrateYes===!0},s=await Fe(i);if(s.code!==0)return e.logger.error(`--migrate: migration "${a.id}" failed — see output above`),s.code;e.logger.success(`--migrate: "${a.id}" applied`)}return 0},fr=async(e,r)=>{const{info:o}=G(r,"lunora"),t=o?.vectorMetadata??[];if(t.length===0)return;const n=[];for(const s of t){const c=Ee(s.kind);if(c===void 0){e.logger.warn(`vector index "${s.index}" declares metadata "${s.property}", whose column type cannot be filtered on in Vectorize — it is stored with each vector but no filter will match it.`);continue}n.push({index:s.index,property:s.property,type:c})}if(n.length===0)return;const i=(await Ae({cwd:r,entries:n,exec:H(b(r),"wrangler",[]),logger:e.logger,spawner:e.spawner??D})).filter(s=>s.status!=="failed").length;i>0&&e.logger.success(`vectorize metadata indexes ready: ${String(i)}/${String(n.length)}`)},O=5,vr=2e3,hr=async(e,r,o)=>{if(e.healthCheck!==!0)return;const t=o??X({cwd:r,env:e.env});if(t===void 0){const a="--health-check: the deploy succeeded, but no URL to probe could be resolved — wrangler's output carried none and this checkout has no link for this environment. Run `lunora link --url <https://your-worker>` and re-deploy, or drop --health-check.";return e.logger.error(a),{error:a,ok:!1,url:""}}const n=await Ie({attempts:O,baseUrl:t,delayMs:vr,fetchImpl:e.healthFetch,paths:[Le,Me],sleep:e.healthSleep});return n.error===void 0?(e.logger.success(`health check ok (${n.url})`),{ok:!0,url:n.url}):(e.logger.error(`--health-check: the deploy succeeded, but the new version did not answer after ${String(O)} attempt(s) — ${n.error}`),{error:n.error,ok:!1,url:n.url})},pr=async(e,r,o,t,n,a)=>{await fr(e,r);const i=e.migrate?await mr(e,r):0;return i===0&&n?.(),{code:i,descriptor:o,mintedSecretsFile:a,validation:t}},yr=async({cwd:e,descriptor:r,mintedSecretsFile:o,options:t,reblessSchemaBaseline:n,recordArchitecture:a,stdout:i,validation:s})=>{const c={deployedAt:new Date().toISOString(),dryRun:t.dryRun===!0,env:t.env,preview:t.preview===!0,url:t.dryRun===!0?void 0:ur(i),workerName:_(e)};if(t.dryRun===!0||t.preview===!0)return t.healthCheck===!0&&t.logger.warn(`--health-check skipped: ${t.dryRun===!0?"a dry run publishes nothing":"a preview version serves no live traffic"}`),{code:0,deployment:c,descriptor:r,mintedSecretsFile:o,validation:s};t.temporary!==!0&&(a?.(),gr({cwd:e,env:t.env,logger:t.logger,url:c.url}));const l=await hr(t,e,c.url);return l?.error!==void 0?{code:h.UNAVAILABLE,deployment:c,descriptor:r,healthCheck:l,mintedSecretsFile:o,validation:s}:{...await pr(t,e,r,s,n,o),deployment:c,healthCheck:l}},wr=(e,r,o)=>{const t=y(e,w);if(!p(t))return;let n;try{n=K(k(t,"utf8")).length}catch{return}if(n===0)return;const a=o.toolchain?.secretPut!==void 0;r.warn(a?`Note: \`lunora deploy\` does not push secrets. ${w} has ${String(n)} key(s); if you changed them, run \`lunora env push --yes\` to update the deployed secrets.`:`Note: ${o.name} deploys read no secrets. ${w} has ${String(n)} key(s) that only the dev server sees; put the values the deployed worker needs in wrangler \`vars\`.`)},kr=async e=>{let r=[];try{r=ie(await q({projectRoot:e,schemaDir:R(e)}))}catch{}const o=se(r).map(n=>n.key);let t=[];try{const n=y(e,w);p(n)&&(t=K(k(n,"utf8")).map(a=>a.key).filter(a=>Re(a)))}catch{}return[...new Set([...o,...t])]},br=async(e,r,o,t)=>{const{logger:n}=r,a=r.spawner??D,i=b(e),s=r.env===void 0?"":` --env ${r.env}`,c=t.toolchain?.secretPut;if(c===void 0)return n.error(`deploy target "${t.id}" has no secret store; cannot push secrets`),{minted:[],ok:!1};const l=[];for(const d of o){const g=ce(),m=c({environment:r.env,key:d,temporary:r.temporary}),u=j(i,m),f=await a({args:u.args,command:u.command,cwd:e,input:g});if(f.code!==0)return n.error(`failed to push secret ${d} (exit ${String(f.code)}); set it manually with \`wrangler secret put ${d}${s}\`.`),{minted:l,ok:!1};l.push({key:d,value:g}),n.success(`generated + pushed ${d}`)}return{minted:l,ok:!0}},$r=/^[\w-]+$/u,E=[".dev.vars",".dev.vars.*","!.dev.vars.example"],Sr=/\r?\n/u,Dr=(e,r)=>{const o=y(e,".gitignore");try{const t=p(o)?k(o,"utf8"):"",n=new Set(t.split(Sr).map(c=>c.trim())),a=E.filter(c=>!n.has(c));if(a.length===0)return;const i=a.some(c=>!c.startsWith("!"))?[...a.filter(c=>!c.startsWith("!")),...E.filter(c=>c.startsWith("!"))]:a,s=t.length>0&&!t.endsWith(`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{readServiceBindings as U,runCodegen as M}from"@lunora/codegen";import{runPostCodegenHook as G,detectAgentRules as F,updateDevServerState as W,readDevServerState as X,DEV_DAEMON_ENV as x,detectAiAgent as Y,readProjectRemotePreference as J,readLiveDevServerState as V,DEV_HANDOFF_ENV as k,clearDevServerState as K,claimDevServerState as z,DEV_LOG_FILE_ENV as Q,inferLunoraBindings as Z,resolveSchemaDirectory as q,
|
|
2
|
-
`)),t.length>0&&a.write(t),a.pipe(r),r.pipe(a)});a.setTimeout(dr,()=>a.destroy()),a.on("error",()=>r.destroy()),r.on("error",()=>a.destroy())},ur=async e=>{const r=e.host??"127.0.0.1",t=r==="127.0.0.1"||r==="localhost"||r==="::1",n=new URL(e.workerOrigin);let a=A(e.logger,import.meta.url),i=P(import.meta.url);const u=De({adminToken:t?_e(e.cwd):void 0,basePath:"/",dataEditable:t,rulesInstalled:F(e.cwd).installed,runAsIdentity:t,schemaEditable:t,scriptSrc:"/studio.js",styleHref:"/styles.css"}),o=(c,s,l,m,S)=>{Me(c,s,S,i)||(s.statusCode=200,s.setHeader("Content-Type",m),s.end(l))},d=(c,s,l)=>{c.statusCode=s,c.setHeader("Content-Type","text/plain"),c.end(l)},v=(c,s,l,m)=>{if(t){Oe(c,s,l,e.cwd,{apiSpec:e.apiSpec});return}d(s,403,m)},h=(c,s,l)=>{const m=c==="/styles.css",S=$e(c);if(!m&&!S)return!1;const p=P(import.meta.url);if(p!==i&&(a=A(e.logger,import.meta.url),i=p),a===void 0)return d(l,501,"Lunora studio assets not found — install and build @lunora/studio."),!0;if(m)return o(s,l,a.styles,"text/css; charset=utf-8","styles.css"),!0;const f=c.slice(c.lastIndexOf("/")+1),g=Ce(f,import.meta.url);return g===void 0?(d(l,404,"Not found"),!0):(o(s,l,g,Le(f),f),!0)},y=Buffer.from(u),w=pe((c,s)=>{const l=O(c.url??"/");if(t){const S=$(c,e.logger);if(S!==void 0){d(s,403,S);return}}if(l.startsWith(N)){if(!t){d(s,403,"Lunora studio: the worker admin proxy is only available on a loopback bind.");return}j(c,s,n);return}if(l===Te){v(c,s,Ne,"Lunora schema editing is only available on loopback hosts in dev.");return}if(l===Re){v(c,s,Ie,"Lunora policy scaffolding is only available on loopback hosts in dev.");return}if(l===Ae){v(c,s,je,"Lunora data seeding is only available on loopback hosts in dev.");return}if(h(l,c,s))return;const m=c.headers["sec-fetch-mode"];if(t&&typeof m=="string"&&m!=="navigate"){j(c,s,n);return}Pe(s,y)});return w.on("upgrade",(c,s,l)=>{if(!t||$(c,e.logger)!==void 0){s.destroy();return}O(c.url??"").startsWith(N)?lr(c,s,l,n):s.destroy()}),await new Promise((c,s)=>{w.once("error",l=>{l.code==="EADDRINUSE"?s(new Error(`studio port ${String(e.port)} is already in use — pass a different port with --port, or stop the process using it`,{cause:l})):s(l)}),w.listen(e.port,r,()=>{c()})}),{close:()=>new Promise(c=>{w.close(()=>{c()})}),url:`http://${r==="0.0.0.0"||r==="::"?"localhost":r}:${String(e.port)}`}},fr=async e=>{const{cwd:r,logger:t,origin:n,signal:a}=e,i=e.probe??Ve,u=xe(e.readyTimeoutMs),o=Date.now()+u,d=()=>a.aborted;for(;!d()&&Date.now()<o;){let v=!1;try{v=await i(n,a)}catch{}if(d()||Date.now()>=o)break;if(v)return W(r,{readyAt:new Date().toISOString()},{expectedPid:process.pid}),X(r)?.readyAt!==void 0;try{await We(He,void 0,{signal:a})}catch{}}return d()||t.warn(`server did not answer on ${n} within ${String(Math.round(u/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},gr=(e,r,t,n)=>{e.info(""),e.success("Lunora dev"),e.info(` ➜ Worker: ${r.workerOrigin}`),t!==void 0&&e.info(` ➜ Studio: ${t}`),r.runsCodegenWatch&&e.info(" ➜ Codegen: watching lunora/"),n!==void 0&&e.info(` ➜ Supervisor: ${n} (needs) · ${H} (status)`),r.remote.enabled&&(r.remote.bindings.length>0?e.info(` ➜ Remote: ${r.remote.bindings.join(", ")} → deployed worker`):e.warn(` ➜ Remote: requested but inactive (${r.remote.reason??"no eligible bindings"}) — running fully local`)),e.info("")},vr=(e,r)=>{F(r).installed||!se()||(e.info(` ⓘ ${ce}`),e.info(""))},mr=async(e,r)=>{try{const n=await Z({projectRoot:r,schemaDir:q(r)}),a=ee(n),i=(e.ensureExample??re)(r,a);i.length>0
|
|
1
|
+
import{readServiceBindings as U,runCodegen as M}from"@lunora/codegen";import{runPostCodegenHook as G,detectAgentRules as F,updateDevServerState as W,readDevServerState as X,DEV_DAEMON_ENV as x,detectAiAgent as Y,readProjectRemotePreference as J,readLiveDevServerState as V,DEV_HANDOFF_ENV as k,clearDevServerState as K,claimDevServerState as z,DEV_LOG_FILE_ENV as Q,inferLunoraBindings as Z,resolveSchemaDirectory as q,secretSourcesFromBindings as ee,ensureDevVarsExample as re,ensureDevVariables as te,isInteractive as ne,DEV_VARS_FILE as T,DEV_VARS_EXAMPLE_FILE as oe,fillDevSecrets as ae,DEV_BINDINGS_FILE as ie,DEV_STATE_FILE as H,claimAgentRulesHint as se,AGENT_RULES_HINT as ce}from"@lunora/config";import{resolveRemoteEnabled as de}from"@lunora/config/cloudflare";import{p as le,a as ue}from"../packem_shared/deploy-target-DCWwiuAe.mjs";import{w as fe}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{existsSync as ge,watch as R}from"node:fs";import{join as ve,dirname as me}from"node:path";import{a as we}from"../packem_shared/codegen-error-AmH54ofi.mjs";import{a as he}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{d as Se}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as D}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{forceJsonLogging as ye}from"../packem_shared/createLogger-Cl18I8AX.mjs";import{createServer as pe,request as Ee}from"node:http";import{connect as be}from"node:net";import{pipeline as ke}from"node:stream";import{loadStudioAssets as A,studioAssetsStamp as P,renderStudioHtml as De,resolveAdminToken as _e,requestPathname as O,transportRejectionReason as $,SCHEMA_EDIT_ENDPOINT as Te,POLICY_SCAFFOLD_ENDPOINT as Re,SEED_ENDPOINT as Ae,sendStudioDocument as Pe,serveJsonHandler as Oe,isStandaloneModulePath as $e,readStandaloneAsset as Ce,assetContentType as Le,handleSchemaEditRequest as Ne,handlePolicyScaffoldRequest as Ie,handleSeedRequest as je,applyStudioAssetCache as Me}from"@lunora/config/studio-host";import{c as Fe}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{setTimeout as We}from"node:timers/promises";import{r as xe,d as Ve,P as He,a as Be,b as _,c as Ue,s as Ge,n as B,e as Xe,f as Ye,g as Je,h as Ke,i as C,w as ze,j as Qe,k as Ze,t as qe,l as er,m as rr,o as tr}from"../packem_shared/plan-DJeIwzFu.mjs";import{provisionBindings as nr}from"./runDeployCommand.mjs";const or=100,ar=/(?:\.[cm]?[jt]sx?|(?:^|[/\\])tsconfig(?:\..+)?\.json)$/u,ir=300,L=/[/\\]/u,sr=(e,r,t)=>{const{apiSpec:n,logger:a,projectRoot:i,target:u}=e;try{const o=M({apiSpec:n,lunoraDirectory:r,projectRoot:i,target:u});a.success(`codegen: wrote ${r}/_generated (${t})`),he(o.platformDiagnostics,a)}catch(o){return a.error(we(o,t)),!1}return!0},cr=e=>{const r=e.lunoraDirectory??"lunora",t=ve(e.projectRoot,r),n=e.debounceMs??or;let a=!1,i=!1,u=!1,o,d=0,v=Promise.resolve(),h;const y=new Promise(f=>{h=f}),w=f=>{a||(o=f,!i&&(i=!0,v=(async()=>{try{for(;o!==void 0;){const g=o;if(o=void 0,!!sr(e,r,g)){u=!0;try{(await G({cwd:e.projectRoot,logger:e.logger,spawner:e.spawner,stdoutToStderr:e.jsonLogs})).ran&&(d=Date.now())}finally{u=!1}}}}catch(g){e.logger.error(`codegen watch: ${g instanceof Error?g.message:String(g)}`)}finally{i=!1,h()}})()))};w("startup");const c=f=>(e.logger.warn(`codegen watch unavailable (${f}) — schema edits will NOT auto-regenerate. Run \`lunora codegen\` manually after each edit.`),{close:()=>(a=!0,o=void 0,v),ready:y,watchAvailable:!1});let s,l;if(!ge(t))return c(`no such directory: ${t}`);const m=f=>{if(u||Date.now()-d<ir){s&&(clearTimeout(s),s=void 0);return}s&&clearTimeout(s),s=setTimeout(()=>{w(`change: ${f??"?"}`)},n)},S=[];try{l=R(t,{recursive:!0},(f,g)=>{typeof g=="string"&&g.split(L).includes("_generated")||m(g)});for(const f of U(e.projectRoot).services)if(f.rpcEntrypoint!==void 0){const g=R(me(f.wranglerPath),{recursive:!0},(b,E)=>{typeof E=="string"&&ar.test(E)&&!E.split(L).includes("node_modules")&&m(E)});g.on("error",b=>{e.logger.warn(`codegen watch: stopped watching service "${f.name}" (${b.message})`),g.close()}),S.push(g)}}catch(f){l?.close();for(const g of S)g.close();return c(f instanceof Error?f.message:String(f))}const p=l;return{close:()=>{a=!0,o=void 0,s&&clearTimeout(s),p.close();for(const f of S)f.close();return v},ready:y,watchAvailable:!0}},N="/_lunora",I=3e4,j=(e,r,t)=>{const n=Ee({headers:{...e.headers,host:t.host},hostname:t.hostname,method:e.method,path:e.url,port:t.port},a=>{r.writeHead(a.statusCode??502,a.headers),ke(a,r,()=>{})});n.setTimeout(I,()=>{n.destroy(new Error(`no response within ${String(I)}ms`))}),n.on("error",a=>{if(r.headersSent){r.destroy();return}r.statusCode=a.message.startsWith("no response within")?504:502,r.end(`lunora dev: worker unreachable (${a.message})`)}),r.on("close",()=>{r.writableFinished||n.destroy()}),e.pipe(n)},dr=5e3,lr=(e,r,t,n)=>{const a=be({host:n.hostname,port:Number(n.port)},()=>{a.setTimeout(0);const i=[`${e.method??"GET"} ${e.url??"/"} HTTP/1.1`];for(const[u,o]of Object.entries(e.headers))if(u!=="host")for(const d of Array.isArray(o)?o:[o])d!==void 0&&i.push(`${u}: ${d}`);i.push(`host: ${n.host}`,"",""),a.write(i.join(`\r
|
|
2
|
+
`)),t.length>0&&a.write(t),a.pipe(r),r.pipe(a)});a.setTimeout(dr,()=>a.destroy()),a.on("error",()=>r.destroy()),r.on("error",()=>a.destroy())},ur=async e=>{const r=e.host??"127.0.0.1",t=r==="127.0.0.1"||r==="localhost"||r==="::1",n=new URL(e.workerOrigin);let a=A(e.logger,import.meta.url),i=P(import.meta.url);const u=De({adminToken:t?_e(e.cwd):void 0,basePath:"/",dataEditable:t,rulesInstalled:F(e.cwd).installed,runAsIdentity:t,schemaEditable:t,scriptSrc:"/studio.js",styleHref:"/styles.css"}),o=(c,s,l,m,S)=>{Me(c,s,S,i)||(s.statusCode=200,s.setHeader("Content-Type",m),s.end(l))},d=(c,s,l)=>{c.statusCode=s,c.setHeader("Content-Type","text/plain"),c.end(l)},v=(c,s,l,m)=>{if(t){Oe(c,s,l,e.cwd,{apiSpec:e.apiSpec});return}d(s,403,m)},h=(c,s,l)=>{const m=c==="/styles.css",S=$e(c);if(!m&&!S)return!1;const p=P(import.meta.url);if(p!==i&&(a=A(e.logger,import.meta.url),i=p),a===void 0)return d(l,501,"Lunora studio assets not found — install and build @lunora/studio."),!0;if(m)return o(s,l,a.styles,"text/css; charset=utf-8","styles.css"),!0;const f=c.slice(c.lastIndexOf("/")+1),g=Ce(f,import.meta.url);return g===void 0?(d(l,404,"Not found"),!0):(o(s,l,g,Le(f),f),!0)},y=Buffer.from(u),w=pe((c,s)=>{const l=O(c.url??"/");if(t){const S=$(c,e.logger);if(S!==void 0){d(s,403,S);return}}if(l.startsWith(N)){if(!t){d(s,403,"Lunora studio: the worker admin proxy is only available on a loopback bind.");return}j(c,s,n);return}if(l===Te){v(c,s,Ne,"Lunora schema editing is only available on loopback hosts in dev.");return}if(l===Re){v(c,s,Ie,"Lunora policy scaffolding is only available on loopback hosts in dev.");return}if(l===Ae){v(c,s,je,"Lunora data seeding is only available on loopback hosts in dev.");return}if(h(l,c,s))return;const m=c.headers["sec-fetch-mode"];if(t&&typeof m=="string"&&m!=="navigate"){j(c,s,n);return}Pe(s,y)});return w.on("upgrade",(c,s,l)=>{if(!t||$(c,e.logger)!==void 0){s.destroy();return}O(c.url??"").startsWith(N)?lr(c,s,l,n):s.destroy()}),await new Promise((c,s)=>{w.once("error",l=>{l.code==="EADDRINUSE"?s(new Error(`studio port ${String(e.port)} is already in use — pass a different port with --port, or stop the process using it`,{cause:l})):s(l)}),w.listen(e.port,r,()=>{c()})}),{close:()=>new Promise(c=>{w.close(()=>{c()})}),url:`http://${r==="0.0.0.0"||r==="::"?"localhost":r}:${String(e.port)}`}},fr=async e=>{const{cwd:r,logger:t,origin:n,signal:a}=e,i=e.probe??Ve,u=xe(e.readyTimeoutMs),o=Date.now()+u,d=()=>a.aborted;for(;!d()&&Date.now()<o;){let v=!1;try{v=await i(n,a)}catch{}if(d()||Date.now()>=o)break;if(v)return W(r,{readyAt:new Date().toISOString()},{expectedPid:process.pid}),X(r)?.readyAt!==void 0;try{await We(He,void 0,{signal:a})}catch{}}return d()||t.warn(`server did not answer on ${n} within ${String(Math.round(u/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},gr=(e,r,t,n)=>{e.info(""),e.success("Lunora dev"),e.info(` ➜ Worker: ${r.workerOrigin}`),t!==void 0&&e.info(` ➜ Studio: ${t}`),r.runsCodegenWatch&&e.info(" ➜ Codegen: watching lunora/"),n!==void 0&&e.info(` ➜ Supervisor: ${n} (needs) · ${H} (status)`),r.remote.enabled&&(r.remote.bindings.length>0?e.info(` ➜ Remote: ${r.remote.bindings.join(", ")} → deployed worker`):e.warn(` ➜ Remote: requested but inactive (${r.remote.reason??"no eligible bindings"}) — running fully local`)),e.info("")},vr=(e,r)=>{F(r).installed||!se()||(e.info(` ⓘ ${ce}`),e.info(""))},mr=async(e,r)=>{try{const n=await Z({projectRoot:r,schemaDir:q(r)}),a=ee(n),i=(e.ensureExample??re)(r,a);if(i.length>0){const u=a.map(o=>o.includes(":")?`${o.replace(":"," (")})`:o);e.logger.info(`Updated .dev.vars.example with secrets for: ${u.join(", ")} (${i.join(", ")})`)}}catch{}(await(e.ensureEnv??te)({confirm:Fe(),cwd:r,info:n=>{e.logger.info(n)}})).status==="declined"&&!ne()&&e.logger.info(`hint: ${T} was not scaffolded (non-interactive run). Copy ${oe} → ${T} and fill in secrets, or run \`lunora dev\` in an interactive terminal to scaffold automatically.`);try{(e.fillSecrets??ae)({cwd:r,info:n=>{e.logger.info(n)}})}catch{}},wr=(e,r,t,n,a)=>{if(e.flavor!=="wrangler")return;n!==void 0&&W(r,{studioUrl:n});let i;try{i=tr(r,t)}catch{}return gr(t,e,n,a),i},hr=(e,r)=>{const t=Number(process.env[k]),n=z(r,{background:process.env[x]==="1",logFile:process.env[Q],mode:"cli",pid:process.pid,startedAt:new Date().toISOString(),url:e.workerOrigin},Number.isInteger(t)&&t>0?{supersedePid:t}:void 0);return n.ok?void 0:n.existing},Sr=e=>{const{cwd:r,destination:t,logger:n,plan:a}=e,i=t!==void 0,u=t??ie,o=fe({destination:u,dev:{...a.flavor==="wrangler"?{origin:a.workerOrigin}:{},statusFile:H},logger:i?n:{...n,success:()=>{},warn:()=>{}},projectRoot:r});return o.error!==void 0?i?o:(n.debug?.(`skipped the default binding manifest: ${o.error}`),{}):{written:u}},yr=async(e,r,t,n)=>{if(r.studioEnabled)try{return await(e.startStudio??ur)({apiSpec:e.apiSpec,cwd:t,logger:{warnOnce:a=>{n.warn(a)}},port:r.studioPort,workerOrigin:r.workerOrigin})}catch(a){n.warn(`studio server failed to start (${a instanceof Error?a.message:String(a)}) — continuing without it`);return}},pr=e=>{const r=[e.runsCodegenWatch?"codegen watch":void 0,e.studioEnabled?"studio":void 0].filter(n=>n!==void 0);return`--no-worker: not starting wrangler. ${r.length>0?`${r.join(" + ")} running`:"nothing else to run"}; your task runner owns the worker on ${e.workerOrigin}.`},Er=(e,r,t,n,a)=>{if(!(e.sidecar===void 0||!er(r)))try{M({apiSpec:r.apiSpec,lunoraDirectory:"lunora",projectRoot:t,target:a})}catch(i){n.warn(`codegen (pre-sidecar) failed: ${i instanceof Error?i.message:String(i)} — the framework dev server will retry`)}},br=e=>e.flavor==="vite"?"starting vite dev (worker + studio + codegen run inside Vite via @lunora/vite)":`starting ${e.wrangler.tag} dev + studio`,kr=async(e,r,t,n,a)=>{try{return e.celldSession===!0?await rr({logger:a,port:e.workerPort,projectRoot:n,start:r.startCelldSession}):t(e.wrangler,a)}catch(i){a.error(`could not start the worker: ${i instanceof Error?i.message:String(i)}`);return}},Dr=async e=>{const{logger:r}=e,t=e.cwd??process.cwd(),n=e.flavor??Xe(t),a=ue(t,e.target);if(a.target===void 0)throw new Error(a.error??"unknown deploy target");const{target:i}=a,u=Ye(i,n,r);u==="wrangler"&&await nr(t,r,void 0,i,void 0);const o=await Je({...e,flavor:u,target:i}),d={remoteCleanup:o.remote.cleanup,serviceConfigCleanup:o.serviceConfigCleanup};try{const v=Number(process.env[k]),h=V(t);if(h!==void 0&&h.pid!==process.pid&&h.pid!==v)return _(r,h),{code:0,plan:o};const y=hr(o,t);if(y!==void 0)return _(r,y),{code:0,plan:o};(o.flavor==="vite"||o.flavor==="framework-worker")&&(o.wrangler.env={...o.wrangler.env,[k]:String(process.pid)}),await mr(e,t),r.info(br(o)),Ke(r,t),o.ipv4LoopbackForced&&r.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."),o.runsCodegenWatch&&(d.codegen=(e.startCodegen??cr)({apiSpec:e.apiSpec,jsonLogs:e.jsonLogs,logger:r,projectRoot:t,target:i})),d.studio=await yr(e,o,t,r);const w=Sr({cwd:t,destination:e.emitBindings,logger:r,plan:o});if(w.error!==void 0)return r.error(w.error),{code:D.USAGE,plan:o};await d.codegen?.ready;const c=d.studio?.url;o.frameworkHint!==void 0&&r.warn(o.frameworkHint);const s=()=>{o.flavor==="wrangler"&&(d.readyProbe=new AbortController,fr({cwd:t,logger:r,origin:o.workerOrigin,probe:e.probeReady,signal:d.readyProbe.signal}))};if(!o.workerEnabled)return s(),r.info(pr(o)),d.tunnel=C({cwd:t,logger:r,plan:o,tunnel:e.tunnel}),{code:await(e.waitForInterrupt??ze)(r),plan:o};Er(o,e,t,r,i);const l=e.startWorker??Qe,m=await kr(o,e,l,t,r);if(m===void 0)return{code:D.FAILURE,plan:o};const S=o.sidecar===void 0?void 0:l(o.sidecar,r);return s(),d.containerLogs=wr(o,t,r,c,w.written),d.tunnel=C({cwd:t,logger:r,plan:o,tunnel:e.tunnel}),vr(r,t),{code:await Ze(m,S,r),plan:o}}finally{d.readyProbe?.abort(),K(t,process.pid),await qe(d)}},_r=e=>({codegen:e.codegen===!1?!1:void 0,studio:e.studio===!1?!1:void 0,worker:e.worker===!1?!1:void 0}),Tr=e=>{if(e.local===!0&&e.remote===!0)return"`--local` and `--remote` are mutually exclusive — pass at most one.";const{entries:r,invalid:t}=B(e.allowMail);if(t.length>0)return`\`--allow-mail\` takes email addresses or '*@domain' — not ${t.map(n=>`"${n}"`).join(", ")}.`;if(r.length>0&&e.tunnel!==!0)return"`--allow-mail` only applies to a tunnel — add `--tunnel`."},Rr=e=>e.tunnel===!0?{allowMail:B(e.allowMail).entries}:void 0,Jr=Se(async({argument:e,cwd:r,logger:t,options:n})=>{const a=n.json===!0,i=Be({cwd:r,json:a,lines:n.lines,logger:t,subcommand:e[0]});if(i!==void 0)return i;const u=process.env[x]==="1",o=u?void 0:Y(),d=a||o!==void 0;d&&ye(),o!==void 0&&n.background!==!0&&t.info(`AI agent detected (${o.name} via ${o.variable}) — starting the dev server in background mode with JSON logs. Set LUNORA_AGENT_MODE=0 to opt out.`);const v=Tr(n);if(v!==void 0)return t.error(`dev: ${v}`),{code:D.USAGE};const h=Rr(n),y=n.local===!0?!1:de({configPreference:J(r),envValue:process.env.LUNORA_REMOTE,flag:n.remote});if(!u&&(n.background===!0||o!==void 0)){const w=V(r);return w!==void 0?(_(t,w),{code:0}):(h?.allowMail.length===0&&Ue(t),Ge({cwd:r,jsonLogs:d,logger:t,options:n,remote:y}))}return Dr({apiSpec:le(n.apiSpec),cwd:r,emitBindings:n.emitBindings,inspectorPort:n.inspectorPort,jsonLogs:d,local:n.local,logger:t,port:n.port,remote:y,target:n.target,tunnel:h,workerPort:n.workerPort,..._r(n)})});export{Tr as devFlagConflict,Jr as execute,_r as negatableDevFlags,Dr as runDevCommand};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/cli",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.364",
|
|
4
4
|
"description": "The Lunora CLI: init, dev, deploy, codegen, migrate, seed, doctor, insights, logs, registry, and the rest of the project commands",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agent-skills",
|
|
@@ -52,16 +52,16 @@
|
|
|
52
52
|
},
|
|
53
53
|
"dependencies": {
|
|
54
54
|
"@bomb.sh/tab": "0.0.22",
|
|
55
|
-
"@lunora/advisor": "1.0.0-alpha.
|
|
56
|
-
"@lunora/bindings": "1.0.0-alpha.
|
|
57
|
-
"@lunora/codegen": "1.0.0-alpha.
|
|
58
|
-
"@lunora/config": "1.0.0-alpha.
|
|
59
|
-
"@lunora/container": "1.0.0-alpha.
|
|
60
|
-
"@lunora/d1": "1.0.0-alpha.
|
|
61
|
-
"@lunora/errors": "1.0.0-alpha.51",
|
|
62
|
-
"@lunora/mcp": "1.0.0-alpha.
|
|
63
|
-
"@lunora/runtime": "1.0.0-alpha.
|
|
64
|
-
"@lunora/seed": "1.0.0-alpha.
|
|
55
|
+
"@lunora/advisor": "1.0.0-alpha.200",
|
|
56
|
+
"@lunora/bindings": "1.0.0-alpha.102",
|
|
57
|
+
"@lunora/codegen": "1.0.0-alpha.278",
|
|
58
|
+
"@lunora/config": "1.0.0-alpha.323",
|
|
59
|
+
"@lunora/container": "1.0.0-alpha.71",
|
|
60
|
+
"@lunora/d1": "1.0.0-alpha.168",
|
|
61
|
+
"@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
|
|
62
|
+
"@lunora/mcp": "1.0.0-alpha.224",
|
|
63
|
+
"@lunora/runtime": "1.0.0-alpha.186",
|
|
64
|
+
"@lunora/seed": "1.0.0-alpha.202",
|
|
65
65
|
"@visulima/cerebro": "3.1.2",
|
|
66
66
|
"@visulima/error": "6.1.0",
|
|
67
67
|
"@visulima/fs": "6.0.28",
|
package/skills/lunora/SKILL.md
CHANGED
|
@@ -1,197 +1,173 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: lunora
|
|
3
|
-
description: Routes general Lunora requests to the right
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
3
|
+
description: Routes general Lunora requests to the right Lunora skill and gives the
|
|
4
|
+
shared mental model (codegen loop, generated `api`/`internal` references,
|
|
5
|
+
review commands, add-on capabilities, the `@lunora/mcp` server). Use when the
|
|
6
|
+
user asks which Lunora skill to use, gives an underspecified task in a project
|
|
7
|
+
with a `lunora/` directory or `lunorash`/`@lunora/*` dependencies, asks to
|
|
8
|
+
review or audit Lunora code, asks about an add-on without its own skill
|
|
9
|
+
(queues, workflows, agents, AI, flags, payments, notifications), or wants to
|
|
10
|
+
expose a deployment to an AI agent over MCP.
|
|
7
11
|
---
|
|
8
12
|
|
|
9
13
|
# Lunora
|
|
10
14
|
|
|
11
|
-
|
|
15
|
+
Lunora is a type-safe, real-time backend on Cloudflare Workers + Durable
|
|
16
|
+
Objects. Functions are chainable `query` / `mutation` / `action` builders; state
|
|
17
|
+
lives in one `ShardDO` per app by default (SQLite, OCC, hibernated WebSocket
|
|
18
|
+
subscriptions). `.shardBy(key)` partitions a table across many DOs and
|
|
19
|
+
`.global()` replicates it to D1 (or Postgres/MySQL over Hyperdrive) for
|
|
20
|
+
cross-region reads. Codegen produces the types the client and server share.
|
|
12
21
|
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
lives in a per-app `ShardDO` (SQLite, OCC, hibernated WebSocket subscriptions)
|
|
16
|
-
by default; `.shardBy(key)` partitions it across many DOs and `.global()`
|
|
17
|
-
replicates a table to D1 — or to Postgres/MySQL over Hyperdrive — for
|
|
18
|
-
low-latency cross-region reads. A Vite plugin drives codegen and end-to-end
|
|
19
|
-
type sync.
|
|
22
|
+
If a project-level `AGENTS.md` / `CLAUDE.md` exists, read it first; it overrides
|
|
23
|
+
these defaults. If a more specific Lunora skill matches, switch to it.
|
|
20
24
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
## Start Here
|
|
24
|
-
|
|
25
|
-
Before writing or changing any `lunora/` code, make sure the generated types are
|
|
26
|
-
current — they are the contract the client and server share.
|
|
25
|
+
## The feedback loop
|
|
27
26
|
|
|
28
27
|
```bash
|
|
29
|
-
lunora codegen
|
|
28
|
+
lunora codegen # regenerate lunora/_generated/ from lunora/schema.ts + function files
|
|
29
|
+
lunora verify # wrangler config + codegen dry-run + tsc --noEmit; writes nothing
|
|
30
30
|
```
|
|
31
31
|
|
|
32
|
-
|
|
33
|
-
`
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
these defaults.
|
|
32
|
+
`lunora codegen` writes `lunora/_generated/` (`api.ts`, `internal.ts`,
|
|
33
|
+
`server.ts`, `dataModel.ts`, `shard.ts`, `app.ts`, `openapi.ts`, …; it prints
|
|
34
|
+
the exact list) and reports schema advisories and platform diagnostics. It does
|
|
35
|
+
not run `tsc`, so use `lunora verify` as the check that the code you wrote is
|
|
36
|
+
done. Its `tsc --noEmit` step runs only when the project has a `tsconfig.json`
|
|
37
|
+
(otherwise it warns and skips) and is turned off by `--no-typecheck`. `lunora dev` re-runs codegen on save, and `lunora deploy` runs it too.
|
|
38
|
+
Scaffolded projects gitignore `lunora/_generated/`; never hand-edit it.
|
|
40
39
|
|
|
41
|
-
## Route to the
|
|
42
|
-
|
|
43
|
-
After codegen is green, use the most specific Lunora skill for the task:
|
|
40
|
+
## Route to the right skill
|
|
44
41
|
|
|
45
42
|
- New project, or adding Lunora to an existing app: `lunora-quickstart`
|
|
46
43
|
- Writing or reviewing schema + functions (the core authoring rules):
|
|
47
44
|
`lunora-functions`
|
|
48
45
|
- Wiring live data into a client (hooks, optimistic updates): `lunora-realtime`
|
|
49
|
-
- Authentication
|
|
50
|
-
`lunora-setup-auth`
|
|
46
|
+
- Authentication (email/password, OAuth, magic link, OTP): `lunora-setup-auth`
|
|
51
47
|
- Transactional email: `lunora-setup-mail`
|
|
52
48
|
- R2 file storage (signed upload/download): `lunora-setup-storage`
|
|
53
49
|
- Deferred work (`ctx.scheduler`) and cron jobs: `lunora-setup-scheduler`
|
|
54
|
-
- Querying an
|
|
50
|
+
- Querying an existing Postgres/MySQL database from an action (`ctx.sql`,
|
|
55
51
|
non-reactive): `lunora-setup-hyperdrive`
|
|
56
|
-
-
|
|
52
|
+
- Postgres/MySQL as a reactive `.global()` backend, or migrating a D1
|
|
57
53
|
`.global()` dataset onto it: `lunora-setup-hyperdrive-global`
|
|
58
|
-
- Building a reusable capability
|
|
54
|
+
- Building a reusable capability (registry item or `@lunora/*` package):
|
|
59
55
|
`lunora-create-package`
|
|
60
|
-
-
|
|
61
|
-
- Deploying
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
56
|
+
- Schema/data migrations: `lunora-migration-helper`
|
|
57
|
+
- Deploying (wrangler, bindings, secrets, the drift gate): `lunora-deploy`
|
|
58
|
+
- Slow queries, scans, write conflicts: `lunora-performance-audit`
|
|
59
|
+
|
|
60
|
+
### Reviewing existing `lunora/` code
|
|
65
61
|
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
anything:
|
|
62
|
+
There is no review skill because two commands do the mechanical part. Run them
|
|
63
|
+
before reading code by hand:
|
|
69
64
|
|
|
70
65
|
```bash
|
|
71
|
-
lunora verify #
|
|
72
|
-
lunora advisor #
|
|
66
|
+
lunora verify # does it build and typecheck
|
|
67
|
+
lunora advisor # static + runtime lint set, scored per procedure
|
|
73
68
|
```
|
|
74
69
|
|
|
75
|
-
`lunora advisor`
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
in
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
`
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
`@lunora/
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
70
|
+
`lunora advisor` covers RLS coverage, ownership and identity checks, fail-open
|
|
71
|
+
guards, input validators, unindexed reads, non-deterministic calls in queries,
|
|
72
|
+
SQL interpolation and leaked secrets. It prints each finding's lint id and
|
|
73
|
+
category, so read its output rather than guessing rule names. `--entry
|
|
74
|
+
<file>#<export>` inspects one procedure; `--min-score` / `--baseline` gate CI.
|
|
75
|
+
Once it is clean, a by-hand pass against `lunora-functions` is worth the tokens.
|
|
76
|
+
|
|
77
|
+
## Core mental model
|
|
78
|
+
|
|
79
|
+
- Functions live in `lunora/**/*.ts` and import their builders from the
|
|
80
|
+
generated server module: `query` (reactive read), `mutation` (transactional
|
|
81
|
+
write), `action` (side effects, `fetch`, no direct db). `internalQuery` /
|
|
82
|
+
`internalMutation` / `internalAction` are not callable from clients.
|
|
83
|
+
- Schema lives in `lunora/schema.ts` (`defineSchema` + `defineTable`, validators
|
|
84
|
+
from `v.*`), imported from `lunorash/server` or `@lunora/server`.
|
|
85
|
+
- Function references mirror the folder tree: `lunora/billing/invoices.ts`
|
|
86
|
+
exporting `create` is `api.billing.invoices.create`. Public references come
|
|
87
|
+
from `_generated/api`, internal ones from `_generated/internal` (kept separate
|
|
88
|
+
so client bundles never carry internal names). A reference is a plain
|
|
89
|
+
`{ __lunoraRef: "billing_invoices:create" }` object; there is no `anyApi`
|
|
90
|
+
proxy.
|
|
91
|
+
- Reads go through indexes: declare `.index("by_x", ["x"])` and query with
|
|
92
|
+
`ctx.db.query("t").withIndex("by_x", (q) => q.eq("x", value))`, not
|
|
93
|
+
`.filter(...)`.
|
|
94
|
+
- Clients subscribe over WebSocket; `useQuery` re-renders when a mutation
|
|
95
|
+
changes the queried rows. Subscriptions run under the socket's verified
|
|
96
|
+
identity, so `rls()` and `ctx.auth` apply to live updates too.
|
|
97
|
+
|
|
98
|
+
## Capabilities without a dedicated skill
|
|
99
|
+
|
|
100
|
+
Most add-ons install as a registry item: `lunora add <feature>` (or
|
|
101
|
+
`lunora registry add <item>`) scaffolds the `lunora/` glue, wrangler bindings
|
|
102
|
+
and `.dev.vars` entries, then prints post-install steps. Browse with
|
|
103
|
+
`lunora registry list`, preview with `lunora registry view <item>`. Read the
|
|
104
|
+
installed item's README and the package's `docs/` for the API.
|
|
105
|
+
|
|
106
|
+
| Goal | Install / package |
|
|
107
|
+
| --------------------------------------------- | ---------------------------------------------------------- |
|
|
108
|
+
| Background jobs on Cloudflare Queues | `lunora add queue` → `@lunora/queue` (`ctx.queues`) |
|
|
109
|
+
| Durable multi-step workflows | `lunora add workflow` → `@lunora/workflow` (`ctx.runStep`) |
|
|
110
|
+
| Durable AI agents (tool loops, HITL, memory) | `@lunora/agent` (`defineAgent`) |
|
|
111
|
+
| Workers AI / RAG | `lunora add ai` → `@lunora/ai` (`ctx.ai`, `defineRag`) |
|
|
112
|
+
| Feature flags (OpenFeature) | `lunora add flags` → `@lunora/flags` (`ctx.flags`) |
|
|
113
|
+
| Payments (Stripe / Polar) | `lunora add payment` → `@lunora/payment` |
|
|
114
|
+
| Agent payments (x402) | `@lunora/x402` |
|
|
115
|
+
| Push / in-app / webhook notifications | `@lunora/notify` (`ctx.notify`, `ctx.push`) |
|
|
116
|
+
| Rate limiting | `lunora add ratelimit` → `@lunora/ratelimit` |
|
|
117
|
+
| Headless browser (action-only) | `lunora add browser` → `@lunora/browser` (`ctx.browser`) |
|
|
118
|
+
| Cloudflare Containers | `@lunora/container` (`defineContainer`, `ctx.containers`) |
|
|
119
|
+
| Presence / who's-here | `lunora add presence` |
|
|
120
|
+
| Cloudflare Access (Zero Trust) identity | `lunora add cloudflare-access` |
|
|
121
|
+
| Backup / restore | `lunora add backup` |
|
|
122
|
+
| Testing (in-memory harness, agent doubles) | `@lunora/testing` (`lunoraTest`) |
|
|
123
|
+
| Deterministic seed data | `@lunora/seed` + `lunora seed` |
|
|
124
|
+
| Local-first replica / offline mirror | `@lunora/replica` |
|
|
125
|
+
| Exposing the deployment to AI agents over MCP | `@lunora/mcp` (below) |
|
|
126
|
+
|
|
127
|
+
Inside the Lunora monorepo, `vis generate lunora-<kind>` scaffolds code:
|
|
128
|
+
`query`, `mutation`, `action`, `http-route`, `table`, `cron`, `container`,
|
|
129
|
+
`workflow`, `queue`, `step`, `agent`, `package`, plus the no-name singletons
|
|
130
|
+
`flags`, `auth-do` and `collections` (`vis generate --list` for the set). Pass
|
|
131
|
+
names as `--name=value`: vis parses `--name foo` as `--name=true` plus a stray
|
|
132
|
+
positional.
|
|
133
|
+
|
|
134
|
+
## Exposing a deployment over MCP
|
|
135
|
+
|
|
136
|
+
Two entry points:
|
|
137
|
+
|
|
138
|
+
- `lunora mcp install` wires an editor (Claude Code, Cursor, …) to the hosted
|
|
139
|
+
docs server plus this project's dev server; `lunora mcp serve` is the stdio
|
|
140
|
+
server those entries spawn (`--allow-writes`, `--token` opt into more).
|
|
141
|
+
- The `lunora-mcp` binary from `@lunora/mcp` fronts a deployed Worker. It needs
|
|
142
|
+
`LUNORA_URL` and `LUNORA_ADMIN_TOKEN`. Every tool reads admin-gated routes, so
|
|
143
|
+
the token cannot be scoped down; safety comes from the gates below.
|
|
144
|
+
|
|
145
|
+
Always advertised: `lunora_list_functions`, `lunora_list_tables` (`.global()`
|
|
146
|
+
tables with row counts), `lunora_get_function_schema`, `lunora_run_query`
|
|
147
|
+
(read-only), and `lunora_explain_error`, which explains an error `code` or
|
|
148
|
+
message from the catalog compiled into `@lunora/errors` and needs no
|
|
149
|
+
deployment. Use it before guessing what a Lunora error means.
|
|
150
|
+
|
|
151
|
+
Everything else sits behind an env gate that both hides the tool and refuses it
|
|
152
|
+
at dispatch. All default to off; enable one only when the answer to "may a model
|
|
153
|
+
see this?" is yes.
|
|
146
154
|
|
|
147
155
|
- `LUNORA_MCP_ALLOW_WRITES` → `lunora_run_mutation`, `lunora_run_action`.
|
|
148
156
|
- `LUNORA_MCP_ALLOW_OBSERVABILITY` → the five `lunora_get_*` tools (logs,
|
|
149
157
|
issues, advisories, query insights, migration status). Read-only, but they
|
|
150
|
-
return production log lines and error messages
|
|
151
|
-
|
|
152
|
-
- `LUNORA_MCP_ALLOW_DATA_READS` → `lunora_find_related`.
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
`proposedAction`, an `actionDigest`, and the `expiresAt` it is valid until (ten
|
|
167
|
-
minutes). The client shows that to a human, then calls the same tool again with
|
|
168
|
-
the identical `functionPath`, `args` and `shardKey`, plus `confirmed: true` and
|
|
169
|
-
that digest.
|
|
170
|
-
|
|
171
|
-
Editing anything produces a different digest and needs a fresh proposal; an
|
|
172
|
-
expired digest is refused rather than quietly re-proposed. Be precise about what
|
|
173
|
-
this buys: the digest binds the **call**, proving the write that runs is exactly
|
|
174
|
-
the one proposed on this deployment inside the window. It does **not** prove a
|
|
175
|
-
human ever saw it — an MCP server has no channel to a person, and a client that
|
|
176
|
-
asks nobody can echo the digest straight back. Enabling writes is the operator
|
|
177
|
-
asserting that the client on the other end does the asking.
|
|
178
|
-
|
|
179
|
-
## Core Mental Model
|
|
180
|
-
|
|
181
|
-
- **Functions** live in `lunora/*.ts` and are one of `query` (reactive read),
|
|
182
|
-
`mutation` (transactional write), or `action` (side effects / `fetch` / no
|
|
183
|
-
direct db). `internalQuery` / `internalMutation` / `internalAction` are the
|
|
184
|
-
non-public variants.
|
|
185
|
-
- **Schema** lives in `lunora/schema.ts` via `defineSchema` + `defineTable`,
|
|
186
|
-
with validators from `v.*` (re-exported by `@lunora/server`).
|
|
187
|
-
- **Reads go through indexes.** Prefer `ctx.db.query("t").withIndex(...)` over
|
|
188
|
-
`.filter(...)`; declare the index with `.index("by_x", ["x"])`.
|
|
189
|
-
- **Clients** subscribe over WebSocket. `useQuery`/`useMutation` (React, Vue,
|
|
190
|
-
Solid, Svelte, React Native; signals in Angular) re-render the moment a
|
|
191
|
-
mutation changes the queried rows. Subscriptions run under the socket's
|
|
192
|
-
verified identity, so `rls()` / `ctx.auth` apply to live updates too.
|
|
193
|
-
|
|
194
|
-
## When Not to Use
|
|
195
|
-
|
|
196
|
-
- The user has already named a more specific Lunora workflow.
|
|
197
|
-
- Another Lunora skill obviously fits the request better.
|
|
158
|
+
return production log lines and error messages, which then reach the model
|
|
159
|
+
provider.
|
|
160
|
+
- `LUNORA_MCP_ALLOW_DATA_READS` → `lunora_find_related`. It returns raw rows
|
|
161
|
+
read through the admin writer, with RLS and column masks bypassed. It is kept
|
|
162
|
+
separate from observability so enabling logs never also hands over rows.
|
|
163
|
+
- `LUNORA_MCP_ALLOW_AGENTS` (with `LUNORA_MCP_AGENTS="name:description;…"`) →
|
|
164
|
+
the `agent_<name>` tools and `lunora_agent_status`.
|
|
165
|
+
|
|
166
|
+
Writes are a two-step handshake. The first `lunora_run_mutation` /
|
|
167
|
+
`lunora_run_action` call does not execute; it returns `status:
|
|
168
|
+
"action_required"` with `proposedAction`, an `actionDigest`, and an `expiresAt`
|
|
169
|
+
ten minutes out. The client shows that to a human, then repeats the call with
|
|
170
|
+
identical `functionPath`, `args` and `shardKey` plus `confirmed: true` and the
|
|
171
|
+
digest. Any edit needs a fresh proposal, and an expired digest is refused. The
|
|
172
|
+
digest proves the write that runs is the one proposed; it does not prove a human
|
|
173
|
+
saw it, so enabling writes means trusting the client to ask.
|