@lunora/cli 1.0.0-alpha.11 → 1.0.0-alpha.110
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/LICENSE.md +6 -0
- package/__assets__/package-og.svg +1 -1
- package/dist/bin.mjs +2 -10
- package/dist/index.d.mts +345 -320
- package/dist/index.d.ts +345 -320
- package/dist/index.mjs +1 -19
- package/dist/packem_chunks/handler.mjs +1 -150
- package/dist/packem_chunks/handler10.mjs +1 -22
- package/dist/packem_chunks/handler11.mjs +1 -192
- package/dist/packem_chunks/handler12.mjs +2 -131
- package/dist/packem_chunks/handler13.mjs +2 -65
- package/dist/packem_chunks/handler14.mjs +1 -58
- package/dist/packem_chunks/handler15.mjs +1 -79
- package/dist/packem_chunks/handler16.mjs +1 -43
- package/dist/packem_chunks/handler17.mjs +1 -105
- package/dist/packem_chunks/handler18.mjs +3 -170
- package/dist/packem_chunks/handler19.mjs +1 -89
- package/dist/packem_chunks/handler2.mjs +2 -114
- package/dist/packem_chunks/handler20.mjs +1 -94
- package/dist/packem_chunks/handler21.mjs +2 -311
- package/dist/packem_chunks/handler3.mjs +2 -204
- package/dist/packem_chunks/handler4.mjs +1 -33
- package/dist/packem_chunks/handler5.mjs +1 -49
- package/dist/packem_chunks/handler6.mjs +1 -91
- package/dist/packem_chunks/handler7.mjs +1 -42
- package/dist/packem_chunks/handler8.mjs +1 -174
- package/dist/packem_chunks/handler9.mjs +8 -16
- package/dist/packem_chunks/planDevCommand.mjs +7 -500
- package/dist/packem_chunks/runCodegenCommand.mjs +4 -52
- package/dist/packem_chunks/runDeployCommand.mjs +1 -504
- package/dist/packem_chunks/runInitCommand.mjs +996 -1265
- package/dist/packem_chunks/runMigrateGenerateCommand.mjs +9 -395
- package/dist/packem_chunks/runResetCommand.mjs +1 -41
- package/dist/packem_chunks/runRpcCommand.mjs +1 -68
- package/dist/packem_shared/COMMANDS-CExxeifl.mjs +3 -0
- package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-DL87PIEl.mjs +8 -0
- package/dist/packem_shared/admin-url-DfVehV3e.mjs +1 -0
- package/dist/packem_shared/api-spec-BENwiyUa.mjs +1 -0
- package/dist/packem_shared/buildRegistryIndex-DwySASBu.mjs +1 -0
- package/dist/packem_shared/codegen-error-DJN6pTH5.mjs +3 -0
- package/dist/packem_shared/command-Bjv4VmYA.mjs +1 -0
- package/dist/packem_shared/commands-BhX2Bo9B.mjs +19 -0
- package/dist/packem_shared/createLogger--C3x1FNE.mjs +2 -0
- package/dist/packem_shared/createRecordingSpawner-C8_7nffs.mjs +1 -0
- package/dist/packem_shared/detect-package-manager-B2eIuAiP.mjs +1 -0
- package/dist/packem_shared/diffSnapshots-9bDd9nOK.mjs +5 -0
- package/dist/packem_shared/docker-CKvYE9YF.mjs +1 -0
- package/dist/packem_shared/insertSchemaExtension-DZReBZ4_.mjs +8 -0
- package/dist/packem_shared/open-url-CTU_g9gr.mjs +1 -0
- package/dist/packem_shared/output-format-D7cKB-O5.mjs +2 -0
- package/dist/packem_shared/parseManifest-x3WsxKHz.mjs +1 -0
- package/dist/packem_shared/prompt-cancelled-C8Sj7OqI.mjs +1 -0
- package/dist/packem_shared/resolve-target-vxaXHmvg.mjs +1 -0
- package/dist/packem_shared/runAddCommand--TBYJQYi.mjs +1 -0
- package/dist/packem_shared/schema-drift-gate-CpqG-xP4.mjs +1 -0
- package/dist/packem_shared/schemaIrToSnapshot-Clwd2A8e.mjs +1 -0
- package/dist/packem_shared/storage-DOvAKGi4.mjs +1 -0
- package/dist/packem_shared/tui-prompts-CCt3jm1k.mjs +4 -0
- package/dist/packem_shared/wrangler-name-HIl0Z6yx.mjs +1 -0
- package/dist/packem_shared/wrangler-secrets-BMRJwKQU.mjs +1 -0
- package/package.json +21 -16
- package/skills/README.md +28 -14
- package/skills/lunora/SKILL.md +48 -9
- package/skills/lunora-functions/SKILL.md +38 -3
- package/skills/lunora-migration-helper/SKILL.md +36 -17
- package/skills/lunora-performance-audit/SKILL.md +36 -6
- package/skills/lunora-quickstart/SKILL.md +86 -24
- package/skills/lunora-realtime/SKILL.md +43 -30
- package/dist/packem_shared/COMMANDS-D3h9Iwvl.mjs +0 -944
- package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Ck-2bU08.mjs +0 -244
- package/dist/packem_shared/admin-url-4UzT-CI4.mjs +0 -19
- package/dist/packem_shared/api-spec-CtA6ilu4.mjs +0 -13
- package/dist/packem_shared/buildRegistryIndex-BcYe607_.mjs +0 -38
- package/dist/packem_shared/command-BC30oSBW.mjs +0 -14
- package/dist/packem_shared/commands-zs-0Es9F.mjs +0 -812
- package/dist/packem_shared/createLogger-B40gPzQo.mjs +0 -78
- package/dist/packem_shared/createRecordingSpawner-DxI3mebw.mjs +0 -43
- package/dist/packem_shared/detect-package-manager-DYp7n3mJ.mjs +0 -61
- package/dist/packem_shared/diffSnapshots-BeDvvNiF.mjs +0 -161
- package/dist/packem_shared/docker-hMQ97KSQ.mjs +0 -21
- package/dist/packem_shared/insertSchemaExtension-BuzF6-t2.mjs +0 -59
- package/dist/packem_shared/open-url-Dfq6fAyT.mjs +0 -41
- package/dist/packem_shared/output-format-wUvAN6AL.mjs +0 -17
- package/dist/packem_shared/parseArgs-YXFuKdEk.mjs +0 -56
- package/dist/packem_shared/parseManifest--vZf2FY1.mjs +0 -94
- package/dist/packem_shared/resolve-target-qbsJ_5sF.mjs +0 -16
- package/dist/packem_shared/runAddCommand-DWlzKNPC.mjs +0 -4
- package/dist/packem_shared/schema-drift-gate-BtBt0as0.mjs +0 -79
- package/dist/packem_shared/schemaIrToSnapshot-DdsljJT-.mjs +0 -43
- package/dist/packem_shared/storage-7faZve2Z.mjs +0 -84
- package/dist/packem_shared/tui-prompts-Dvlh5xWt.mjs +0 -663
- package/dist/packem_shared/wrangler-name-cy4yhm9j.mjs +0 -12
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{createWriteStream as T,createReadStream as x}from"node:fs";import{unlink as k,stat as I}from"node:fs/promises";import{LunoraError as S}from"@lunora/errors";import{a as O}from"./admin-url-DfVehV3e.mjs";const A="/_lunora/admin/export",E="/_lunora/admin/import",_=500,L=r=>{if(r===void 0)return;const t=r.split(",").map(o=>o.trim()).filter(o=>o.length>0);return t.length>0?t:void 0},N=async(r,t)=>{r.write(t)||await new Promise(o=>{r.once("drain",o)})},R=async(r,t)=>{const o=r.getReader(),u=new TextDecoder;let s=0,g=0,e="",a=!1;try{for(;!a;){const c=await o.read();if(a=c.done,c.value===void 0)continue;s+=c.value.length,e+=u.decode(c.value,{stream:!0});let l=e.indexOf(`
|
|
2
|
+
`);for(;l!==-1;){g+=1;const n=`${e.slice(0,l)}
|
|
3
|
+
`;await N(t,n),e=e.slice(l+1),l=e.indexOf(`
|
|
4
|
+
`)}}return e.length>0&&(g+=1,await N(t,`${e}
|
|
5
|
+
`)),{bytes:s,rows:g}}finally{o.releaseLock()}},P=async(r,t)=>{if(t!==void 0){r.destroy();try{await k(t)}catch{}}},M=async r=>{if(r.prod&&r.url===void 0)return r.logger.error("--prod requires an explicit --url (refusing to export from the implicit localhost worker)"),{bytes:0,code:1,rows:0};const t=r.token??process.env.LUNORA_ADMIN_TOKEN;if(!t)return r.logger.error("admin token required — pass --token or set LUNORA_ADMIN_TOKEN"),{bytes:0,code:1,rows:0};const o=O(r.url,r.logger);if(o===void 0)return{bytes:0,code:1,rows:0};const u=`${o}${A}`,s=L(r.tables),g=r.fetchImpl??globalThis.fetch;if(typeof g!="function")throw new TypeError("no fetch implementation available — pass fetchImpl or run on Node >= 18");r.logger.info(`POST ${u} -> export${s?` (tables: ${s.join(",")})`:""}`);const e=await g(u,{body:JSON.stringify(s?{tables:s}:{}),headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},method:"POST"});if(!e.ok){const d=await e.text();return r.logger.error(`export failed: HTTP ${String(e.status)}: ${d}`),{bytes:0,code:1,rows:0}}if(!e.body)return r.logger.error("export response carried no body"),{bytes:0,code:1,rows:0};const a=r.out===void 0||r.out==="-"?void 0:r.out,c=a===void 0?process.stdout:T(a,{encoding:"utf8"});let l,n;try{({bytes:l,rows:n}=await R(e.body,c))}catch(d){throw await P(c,a),d}return a!==void 0&&(await new Promise((d,w)=>{c.end(h=>{h?w(h):d()})}),r.logger.success(`wrote ${String(n)} rows to ${a} (${String(l)} bytes)`)),{bytes:l,code:0,rows:n}},U=async r=>{if(r.prod&&r.url===void 0){r.logger.error("--prod requires an explicit --url (refusing to import to the implicit localhost worker)");return}if(r.prod&&r.yes!==!0){r.logger.error("import --prod bulk-writes production. Re-run with --yes to confirm.");return}const t=r.token??process.env.LUNORA_ADMIN_TOKEN;if(!t){r.logger.error("admin token required — pass --token or set LUNORA_ADMIN_TOKEN");return}try{if(!(await I(r.file)).isFile()){r.logger.error(`not a file: ${r.file}`);return}}catch(s){const g=s instanceof Error?s.message:String(s);r.logger.error(`failed to stat ${r.file}: ${g}`);return}const o=O(r.url,r.logger);if(o===void 0)return;const u=r.fetchImpl??globalThis.fetch;if(typeof u!="function")throw new TypeError("no fetch implementation available — pass fetchImpl or run on Node >= 18");return{fetchImpl:u,requestUrl:`${o}${E}`,token:t}},C=async r=>{const t=await U(r);if(t===void 0)return{body:void 0,code:1,inserted:0};const{fetchImpl:o,requestUrl:u,token:s}=t,g=r.batchSize??_;r.logger.info(`POST ${u} -> import ${r.file}`);const e=x(r.file,{encoding:"utf8"}),a={},c=[];let l=0,n="",d=[],w=0;const h=async()=>{if(d.length===0)return;const p=d.join(`
|
|
6
|
+
`);d=[];const f=await o(u,{body:p,headers:{authorization:`Bearer ${s}`,"content-type":"application/x-ndjson"},method:"POST"});if(!f.ok){const m=await f.text().catch(()=>"<no body>");throw new S("INTERNAL",`import batch failed (HTTP ${String(f.status)}): ${m}`)}const i=await f.json();if(i.inserted)for(const[m,y]of Object.entries(i.inserted))a[m]=(a[m]??0)+y;Array.isArray(i.errors)&&c.push(...i.errors),typeof i.conflicts=="number"&&(l+=i.conflicts)},b=p=>{const f=p.trim();if(f.length===0)return;if(w+=1,r.table===void 0){d.push(f);return}let i;try{i=JSON.parse(f)}catch(m){const y=m instanceof Error?m.message:String(m);throw new S("INTERNAL",`invalid JSON on line ${String(w)}: ${y}`,{cause:m})}d.push(JSON.stringify({doc:i,table:r.table}))};for await(const p of e){const f=typeof p=="string"?p:p.toString("utf8");n+=f;let i=n.indexOf(`
|
|
7
|
+
`);for(;i!==-1;)b(n.slice(0,i)),n=n.slice(i+1),i=n.indexOf(`
|
|
8
|
+
`),d.length>=g&&await h()}n.length>0&&b(n),await h();const $=Object.values(a).reduce((p,f)=>p+f,0),v={conflicts:l,errors:c,inserted:a};return r.logger.info(JSON.stringify(v,void 0,2)),r.logger.success(`imported ${String($)} rows (${String(l)} conflicts, ${String(c.length)} errors)`),{body:v,code:c.length>0?1:0,inserted:$}};export{_ as DEFAULT_IMPORT_BATCH_SIZE,M as runExportCommand,C as runImportCommand};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const n=new Set(["127.0.0.1","::1","[::1]","localhost"]),s=/\/$/u,a=(r,e)=>{const o=r??"http://localhost:8787";let t;try{t=new URL(o)}catch{e.error(`invalid --url: ${o}`);return}if(!n.has(t.hostname)&&t.protocol!=="https:"){e.error(`refusing to send the admin bearer over ${t.protocol}// to ${t.hostname} — use https for non-localhost targets`);return}return o.replace(s,"")};export{a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as r}from"@lunora/errors";const o=["both","none","openapi","openrpc"],p=o.join(" | "),i=n=>{if(!(typeof n!="string"||n.length===0)){if(o.includes(n))return n;throw new r("INTERNAL",`invalid --api-spec "${n}" — expected one of: ${p}`)}};export{p,i as r};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync as a,readFileSync as n,readdirSync as m,statSync as p}from"node:fs";import{join as o}from"@visulima/path";import l from"./parseManifest-x3WsxKHz.mjs";const d=/[\u0000-\u001F\u007F-\u009F]/gu,s=t=>t===void 0?void 0:t.replaceAll(d,""),c=t=>m(t).filter(r=>{const e=o(t,r);return p(e).isDirectory()&&a(o(e,"registry.json"))}),S=t=>{const r=o(t,"index.json");if(a(r)){const e=JSON.parse(n(r,"utf8"));if(Array.isArray(e.items))return e.items.filter(i=>typeof i=="object"&&i!==null&&typeof i.name=="string").map(i=>({description:s(i.description),name:s(i.name)??i.name}))}return c(t).map(e=>{const i=JSON.parse(n(o(t,e,"registry.json"),"utf8"));return{description:s(i.description),name:e}})},g=t=>({items:c(t).map(r=>{const e=l(JSON.parse(n(o(t,r,"registry.json"),"utf8")),r);return{...e.description===void 0?{}:{description:e.description},name:e.name,...e.title===void 0?{}:{title:e.title}}}).toSorted((r,e)=>r.name.localeCompare(e.name))});export{g as buildRegistryIndex,S as collectCatalog,c as listItemDirectories};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{findLunoraSolution as n}from"@lunora/codegen";import{VisulimaError as a,renderError as s}from"@visulima/error";const d=r=>r.body.split(`
|
|
2
|
+
`).filter(e=>!e.startsWith("```")).join(`
|
|
3
|
+
`).replaceAll(/\*\*(.+?)\*\*/gu,"$1").replaceAll(/`([^`]+)`/gu,"$1"),l={filterStacktrace:()=>!1,hideErrorCodeView:!0},m=(r,e)=>{const o=r instanceof Error?r.message:String(r),t=n(o),i=new a({hint:t?[t.header,"",d(t)]:void 0,message:e===void 0?`codegen failed: ${o}`:`codegen failed (${e}): ${o}`,name:"CodegenError"});return i.stack="",s(i,l)},u=r=>{const e=n(r);if(e===void 0)return;const o=new a({hint:[d(e)],message:e.header,name:"Hint"});return o.stack="",s(o,l)};export{u as c,m as l};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createLogger as s}from"./createLogger--C3x1FNE.mjs";import{P as c,a}from"./prompt-cancelled-C8Sj7OqI.mjs";const p=t=>async r=>{const e=s();try{const{code:o}=await t({argument:r.argument,cwd:r.process.cwd,logger:e,options:r.options});r.process.exit(o)}catch(o){if(o instanceof c){r.process.exit(a);return}e.error(o instanceof Error?o.message:String(o)),r.process.exit(1)}};export{p as i};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import{existsSync as g,readFileSync as m,writeFileSync as h,mkdirSync as k,mkdtempSync as ee,rmSync as O}from"node:fs";import{dirname as w,join as l,relative as P}from"@visulima/path";import{DEV_VARS_FILE as te,parseDevVariableEntries as re,findWranglerFile as ne,readWranglerJsonc as oe}from"@lunora/config";import{modify as q,applyEdits as L,parse as se}from"jsonc-parser";import{fileURLToPath as ie}from"node:url";import{LunoraError as v}from"@lunora/errors";import{i as ae}from"./tui-prompts-CCt3jm1k.mjs";import{collectCatalog as ce,buildRegistryIndex as ue}from"./buildRegistryIndex-DwySASBu.mjs";import{insertSchemaExtension as fe}from"./insertSchemaExtension-DZReBZ4_.mjs";import{createHash as de}from"node:crypto";import{tmpdir as le}from"node:os";import{downloadTemplate as pe}from"giget";import ge from"./parseManifest-x3WsxKHz.mjs";const me="alpha",W="main",$e=new Set(["alpha","beta","next"]),he=/^[\w./@-]+$/,ye=e=>!e.includes("..")&&he.test(e),z=()=>{try{let e=w(ie(import.meta.url));for(let t=0;t<6;t+=1){const r=l(e,"package.json");if(g(r)){const o=JSON.parse(m(r,"utf8"));if(o.name==="@lunora/cli"&&typeof o.version=="string")return o.version}const n=w(e);if(n===e)break;e=n}}catch{}return"0.0.0"},M=e=>{if(e==="0.0.0")return me;const t=e.split("+")[0]??e,r=t.indexOf("-");if(r!==-1){const[n]=t.slice(r+1).split(".");if(n!==void 0&&$e.has(n))return n}return W},U=e=>{if(e!==void 0&&e.length>0){if(!ye(e))throw new v("INTERNAL",`invalid --ref "${e}" — a ref may contain letters, digits, ".", "_", "-", "/", "@" and must not contain "..".`);return e}return M(z())},j="anolilab/lunora",V=/^[0-9a-f]{40}$/iu,B=String.raw`\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)+)?(?:\+[0-9A-Za-z.-]+)?`,ve=new RegExp(String.raw`^v?${B}$`,"u"),we=new RegExp(String.raw`^(?:@[\w.-]+\/)?[\w.-]+@${B}$`,"u"),be=e=>V.test(e)||ve.test(e)||we.test(e),Se=()=>{const e=process.env.GITHUB_TOKEN??process.env.GH_TOKEN;return e!==void 0&&e.length>0?{authorization:`Bearer ${e}`}:{}},ke=async e=>{try{const t=await fetch(`https://api.github.com/repos/${j}/commits/${encodeURIComponent(e)}`,{headers:{accept:"application/vnd.github+json","user-agent":"lunora-cli",...Se()},signal:AbortSignal.timeout(1e4)});if(!t.ok)return;const r=await t.json();return typeof r.sha=="string"&&V.test(r.sha)?r.sha:void 0}catch{return}},je=async(e,t)=>{const r=U(e);if(be(r))return r;const n=await ke(r);return n===void 0?(t.warn(`could not pin ${j}#${r} to a commit — fetching the UNPINNED branch (set GITHUB_TOKEN if rate-limited).`),r):(t.info(`pinned ${j}#${r} → ${n}`),n)},xe="latest",Ne=(e=z())=>{const t=M(e);return t===W?xe:t},Oe="https://registry.npmjs.org",Re=()=>{const e=process.env.npm_config_registry,t=e!==void 0&&e.length>0?e:Oe;return t.endsWith("/")?t.slice(0,-1):t},Ae=async(e,t)=>{try{const r=await fetch(`${Re()}/${e.replaceAll("/","%2F")}`,{headers:{accept:"application/vnd.npm.install-v1+json"},signal:AbortSignal.timeout(1e4)});return r.ok?(await r.json())["dist-tags"]?.[t]:void 0}catch{return}},kt=async(e,t)=>{const r=new Map;return await Promise.all([...new Set(e)].map(async n=>{const o=await Ae(n,t);o!==void 0&&r.set(n,o)})),r},Ee=e=>{if(!e.startsWith("workspace:"))return e;const t=e.slice(10);return t===""||t==="*"||t==="^"||t==="~"?Ne():t},Te=new Set(["@lunora/client","@lunora/do","@lunora/ratelimit","@lunora/runtime","@lunora/server","@lunora/values"]),_e=/(['"])@lunora\/(client|do|ratelimit|runtime|server|values)(\/[^'"]*)?\1/gu,Je=e=>{const t=l(e,"package.json");if(!g(t))return!1;try{const r=JSON.parse(m(t,"utf8"));return r.dependencies?.lunorash!==void 0||r.devDependencies?.lunorash!==void 0}catch{return!1}},De=e=>e.replaceAll(_e,(t,r,n,o)=>`${r}lunorash/${n}${o??""}${r}`),R=(e,t,r,n="dependencies",o=!1)=>{const s=Object.entries(e);if(s.length===0)return[];const c=l(t,"package.json");if(!g(c))return r.warn(`package.json not found at ${c} — skipping dependency updates`),[];let a=m(c,"utf8");const i=JSON.parse(a),u=[];for(const[f,d]of s){if(o&&Te.has(f)){r.info(`dep provided by the lunorash umbrella, skipping: ${f}`);continue}if(i.dependencies?.[f]!==void 0||i.devDependencies?.[f]!==void 0){r.info(`dep already present: ${f}`);continue}const p=q(a,[n,f],Ee(d),{formattingOptions:{insertSpaces:!0,tabSize:4}});a=L(a,p),u.push(f)}return u.length>0&&(h(c,a,"utf8"),r.success(`added ${String(u.length)} ${n==="devDependencies"?"devDependency(ies)":"dependency(ies)"} to package.json: ${u.join(", ")}`)),u},Ie=(e,t,r)=>{if(e.length===0)return[];const n=l(t,te),o=g(n)?m(n,"utf8"):"",s=new Set(re(o).map(u=>u.key)),c=[],a=[],i=[];for(const u of e)u.secret&&a.push(u.name),!s.has(u.name)&&(u.description&&i.push(`# ${u.description}`),i.push(`${u.name}=${u.secret?"":u.value??""}`),c.push(u.name));if(c.length>0){const u=o===""||o.endsWith(`
|
|
2
|
+
`)?o:`${o}
|
|
3
|
+
`;h(n,`${u}${i.join(`
|
|
4
|
+
`)}
|
|
5
|
+
`,"utf8"),r.success(`scaffolded ${String(c.length)} env var(s) into .dev.vars: ${c.join(", ")}`)}return a.length>0&&r.info(`set secret value(s) locally in .dev.vars, then for production: ${a.map(u=>`wrangler secret put ${u}`).join("; ")}`),c},A=new Set(["ai","analytics_engine_datasets","browser","d1_databases","durable_objects","hyperdrive","kv_namespaces","mtls_certificates","queues","r2_buckets","send_email","services","vars","vectorize","version_metadata","workflows"]),Pe=(e,t,r)=>{if(e.length===0)return[];const n=["wrangler.jsonc","wrangler.json"].map(i=>l(t,i)).find(i=>g(i));if(!n)return r.warn("wrangler.jsonc not found — skipping binding updates"),[];let o=m(n,"utf8");const s=[],c=i=>Array.isArray(i),a=i=>{let u=se(o);for(const f of i){if(typeof u!="object"||u===null)return;u=u[f]}return u};for(const i of e){const u=i.path[0];if(u===void 0||!A.has(u)){r.warn(`skipping binding "${i.path.join(".")}" — only resource bindings (${[...A].join(", ")}) may be written, not exec/entrypoint keys`);continue}let{value:f}=i;if(c(f)){const p=a(i.path);if(c(p)){const $=new Set(p.map(y=>JSON.stringify(y)));f=[...p,...f.filter(y=>!$.has(JSON.stringify(y)))]}}const d=q(o,[...i.path],f,{formattingOptions:{insertSpaces:!0,tabSize:4}});d.length!==0&&(o=L(o,d),s.push(i.path.join(".")))}return s.length>0&&(h(n,o,"utf8"),r.success(`applied ${String(s.length)} binding(s) to ${n}: ${s.join(", ")}`)),s},qe=(e,t,r,n=!1)=>{const o=[],s=[];return e.deps&&o.push(...R(e.deps,t,r,"dependencies",n)),e.devDependencies&&o.push(...R(e.devDependencies,t,r,"devDependencies",n)),e.bindings&&s.push(...Pe(e.bindings,t,r)),e.envVars&&Ie(e.envVars,t,r),{bindings:s,deps:o}},Le=async(e,t)=>{const r=e.some(({manifest:i})=>Object.keys(i.deps??{}).length>0||Object.keys(i.devDependencies??{}).length>0),n=e.some(({manifest:i})=>(i.bindings??[]).length>0),o=t.source!==void 0&&t.source.length>0;if(!r&&!n&&!o||t.yes)return!0;const s=[];r&&s.push("add dependencies to package.json"),n&&s.push("write wrangler.jsonc bindings"),o&&s.push(`come from a non-default source (${String(t.source)})`);const c=s.join(", ");if(!process.stdin.isTTY&&t.confirm===void 0)return t.logger.error(`add: stdin is not a TTY and the requested items ${c} — re-run with --yes to confirm`),!1;const a=await(t.confirm??ae)(`The requested items ${c}. Continue?`);return a||t.logger.info("add: aborted"),a},S=1,We=".lunora-registry.json",F=e=>l(e,"lunora",We),ze=e=>typeof e!="object"||e===null||!("items"in e)?!1:typeof e.items=="object"&&e.items!==null,x=e=>de("sha256").update(e).digest("hex"),Me=e=>{const t=F(e);if(!g(t))return{items:{},version:S};try{const r=JSON.parse(m(t,"utf8"));if(ze(r))return{items:r.items,version:S}}catch{}return{items:{},version:S}},Ue=(e,t)=>{h(F(e),`${JSON.stringify(t,void 0,2)}
|
|
6
|
+
`,"utf8")},E=(e,t,r,n)=>{const o=e.items[t],s=o??{files:{}};o===void 0&&(e.items[t]=s),s.files[r]=x(n)},Ve=(e,t,r)=>e.items[t]?.files[r],T=e=>e===""?[]:e.split(`
|
|
7
|
+
`),Be=(e,t)=>{const r=T(e),n=T(t);let o=0;for(;o<r.length&&o<n.length&&r[o]===n[o];)o+=1;let s=r.length,c=n.length;for(;s>o&&c>o&&r[s-1]===n[c-1];)s-=1,c-=1;if(o===s&&o===c)return[];const a=[];for(let i=Math.max(0,o-3);i<o;i+=1)a.push(` ${r[i]??""}`);for(let i=o;i<s;i+=1)a.push(`- ${r[i]??""}`);for(let i=o;i<c;i+=1)a.push(`+ ${n[i]??""}`);for(let i=c;i<Math.min(n.length,c+3);i+=1)a.push(` ${n[i]??""}`);return a},Fe=/\.[cm]?[jt]sx?$/u,H=(e,t,r)=>{const n=m(l(e,t.from),"utf8");return r&&Fe.test(t.to)?De(n):n},He=(e,t,r,n,o,s,c)=>{const a=l(n,"lunora","schema.ts");if(s)return o.info(`~ would merge .extend(${t}.extension) into lunora/schema.ts (and create ${e.to} if absent)`),{kind:"skipped",path:a};const i=l(n,e.to);g(i)||(k(w(i),{recursive:!0}),h(i,H(r,e,c),"utf8"));const u=c?"lunorash/server":"@lunora/server",f=g(a)?m(a,"utf8"):`import { defineSchema } from "${u}";
|
|
8
|
+
|
|
9
|
+
export const schema = defineSchema({});
|
|
10
|
+
`,d=fe(f,t);if(d.ok)return k(w(a),{recursive:!0}),h(a,d.text,"utf8"),o.success(`merged .extend(${t}.extension) into lunora/schema.ts`),{kind:"written",path:a};if(d.reason==="already-applied")return o.warn(`lunora/schema.ts already extends "${t}" — skipping`),{kind:"skipped",path:a};throw d.reason==="invalid-identifier"?new v("INTERNAL",`schema-extension item "${t}" is not a valid JS identifier — it is spliced into lunora/schema.ts as \`import { ${t} }\` / \`.extend(${t}.extension)\`. Rename the item to a valid identifier (no leading digit, no "-").`):new v("INTERNAL",`schema-extension merge failed for "${t}": ${d.reason}`)},Ge=(e,t,r,n,o)=>{const s=Be(t,r);if(s.length===0){o.info(`= ${e.to} (unchanged)`);return}o.info(`${n?"~":"+"} ${e.to}`);for(const c of s)o.info(` ${c}`)},Ze=(e,t,r,n,o,s,c,a)=>{const i=l(n,e.to),u=H(r,e,a),f=g(i),d=f?m(i,"utf8"):"",p=X=>(k(w(i),{recursive:!0}),h(i,u,"utf8"),E(s,t,e.to,u),o.success(`${X}: ${e.to}`),{kind:"written",path:i});if(c.diff)return Ge(e,d,u,f,o),{kind:"skipped",path:i};if(!f)return p("write");const $=x(d);if($===x(u))return E(s,t,e.to,u),o.warn(`skip (exists): ${e.to}`),{kind:"skipped",path:i};if(c.overwrite)return p("overwrite");const y=Ve(s,t,e.to);return y===void 0?(o.warn(`skip (exists, untracked): ${e.to} — refusing to overwrite a file lunora didn't add (use --overwrite to force)`),{kind:"skipped",path:i}):y===$?p("update"):(h(`${i}.new`,u,"utf8"),o.warn(`conflict: ${e.to} has local edits and an upstream update — wrote ${e.to}.new (use --overwrite to take theirs)`),{kind:"skipped",path:i})},Ce=(e,t,r,n,o,s,c={},a=!1)=>e.merge==="schema-extension"?He(e,t,r,n,o,c.diff===!0,a):Ze(e,t,r,n,o,s,c,a),_=["src/server.ts","src/server/index.ts","src/server/index.tsx","src/index.ts","src/worker.ts"],Ke=e=>{const t=ne(e);if(t===void 0)return;const{parsed:r}=oe(t);return typeof r?.main=="string"?r.main:void 0},Ye=e=>{const t=Ke(e),r=t===void 0?_:[t,..._];for(const n of r){const o=l(e,n);if(!g(o))continue;const s=m(o,"utf8");if(!s.includes("createShardDO(")){if(n===t)break;continue}return{entryPath:o,main:n,source:s}}},Qe=(e,t,r)=>{const n=P(w(e),l(t,"lunora",r)).replaceAll("\\","/");return n.startsWith(".")?n:`./${n}`},Xe=(e,t)=>{for(const r of e){const n=`Add \`export * from "${`./lunora/${r.module}.js`}"\` to your worker entry`,o=r.comment?` (${r.comment})`:"";t.warn(`${n}${o}`)}return 0},et=(e,t,r,n)=>{const o=[];for(const s of e){const c=Qe(t,r,s.module),a=c.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`);new RegExp(String.raw`export\s+\*\s+from\s+["']${a}\.js["']`,"u").test(n)||(s.comment&&o.push(`
|
|
11
|
+
// ${s.comment}`),o.push(`export * from "${c}.js";`))}return o},tt=(e,t,r,n)=>{if(e.length===0)return 0;const o=Ye(t);if(o===void 0)return Xe(e,r);const s=et(e,o.entryPath,t,o.source);if(s.length===0)return 0;if(n){for(const a of s)a!==""&&r.info(`~ entrypoint: ${a}`);return s.length}const c=o.source.endsWith(`
|
|
12
|
+
`)?"":`
|
|
13
|
+
`;return h(o.entryPath,`${o.source}${c}${s.join(`
|
|
14
|
+
`)}
|
|
15
|
+
`,"utf8"),r.success(`wrote ${String(s.length)} entrypoint re-export(s) to ${P(t,o.entryPath)}`),s.length},J=(e,t,r,n={})=>{const o=[],s=[],c=[],a=[],i=Me(t),u=Je(t);for(const{directory:f,manifest:d}of e){for(const $ of d.files){const y=Ce($,d.name,f,t,r,i,n,u);(y.kind==="written"?o:s).push(y.path)}if(d.entrypointReexports!==void 0&&tt(d.entrypointReexports,t,r,n.diff===!0),n.diff)continue;const p=qe(d,t,r,u);c.push(...p.deps),a.push(...p.bindings)}return!n.diff&&Object.keys(i.items).length>0&&Ue(t,i),{bindings:a,deps:c,skipped:s,written:o}},G="gh:anolilab/lunora/registry",D=/^[A-Za-z0-9][\w-]*$/u,rt=e=>{if(!D.test(e))throw new v("INTERNAL",`invalid registry item name "${e}" — names must match ${D.source} (letters, digits, "-", "_"; no path separators or "..")`)},nt=e=>e.includes("..")?!1:e.startsWith("gh:")||e.startsWith("github:")||e.startsWith("https://"),ot=e=>e.from===void 0&&e.source!==void 0&&e.source.length>0&&!e.allowUnsafeSource&&!nt(e.source),N=(e,t)=>ot(t)?`${e}: refusing --source ${String(t.source)} — only gh:, github:, or https:// sources are allowed (and may not contain ".."). Re-run with --allow-unsafe-source if you really want this.`:void 0,Z=async(e,t,r)=>{const n=ee(l(le(),`lunora-${t}-fetch-`)),o=l(n,t);r.info(`fetching ${e}`);try{const s=await pe(e,{cwd:n,dir:o,force:!0,install:!1,silent:!0});return r.info(s.commit?`resolved ${s.source} @ ${s.commit}`:`resolved ${s.source}`),{cleanup:()=>{O(n,{force:!0,recursive:!0})},directory:o}}catch(s){throw O(n,{force:!0,recursive:!0}),s}},I=new WeakMap,C=async e=>{const t=I.get(e);if(t!==void 0)return t;const r=e.source!==void 0&&e.source.length>0?Promise.resolve(U(e.ref)):je(e.ref,e.logger);return I.set(e,r),r},K=async(e,t)=>{if(rt(e),t.from!==void 0){const n=l(t.from,e);if(!g(n))throw new v("INTERNAL",`registry item not found in local source: ${n}`);return{cleanup:()=>{},directory:n}}const r=t.source??G;return Z(`${r}/${e}#${await C(t)}`,"item",t.logger)},st=async e=>{if(e.from!==void 0){if(!g(e.from))throw new v("INTERNAL",`registry root not found: ${e.from}`);return{cleanup:()=>{},root:e.from}}const t=e.source??G,{cleanup:r,directory:n}=await Z(`${t}#${await C(e)}`,"registry",e.logger);return{cleanup:r,root:n}},Y=(e,t)=>{const r=JSON.parse(m(l(e,"registry.json"),"utf8"));return ge(r,t)},it=async(e,t)=>{const r=[],n=[],o=new Set,s=new Set,c=async a=>{if(o.has(a))return;if(s.has(a))throw new v("INTERNAL",`cyclic registry dependency detected at "${a}"`);s.add(a);const{cleanup:i,directory:u}=await K(a,t);n.push(i);const f=Y(u,a);for(const d of f.requires??[])await c(d);s.delete(a),o.add(a),r.push({directory:u,manifest:f})};try{for(const a of e)await c(a)}catch(a){for(const i of n)i();throw a}return{cleanups:n,items:r}},b=()=>({bindings:[],code:0,deps:[],skipped:[],written:[]}),jt=(e,t,r,n,o)=>e.bindings?{...e,bindings:e.bindings.map(s=>{if(s.path[0]!==t||!Array.isArray(s.value))return s;const c=s.value;return{...s,value:c.map(a=>typeof a=="object"&&a!==null&&a[r.key]===r.value?{...a,[n]:o}:a)}})}:e,Q=(e,t)=>{const r=t.title??t.description;e.info(`plan: ${t.name}${r?` — ${r}`:""}`);for(const n of t.files)e.info(` file ${n.to} (${n.merge})`);for(const[n,o]of Object.entries(t.deps??{}))e.info(` dep ${n}@${o}`);for(const[n,o]of Object.entries(t.devDependencies??{}))e.info(` dev ${n}@${o}`);for(const n of t.bindings??[])e.info(` bind ${n.path.join(".")} = ${JSON.stringify(n.value)}`);for(const n of t.envVars??[]){const o=n.secret?" (secret)":` = ${JSON.stringify(n.value??"")}`;e.info(` env ${n.name}${o}`)}for(const n of t.entrypointReexports??[]){const o=`./lunora/${n.module}`,s=n.comment?` // ${n.comment}`:"";e.info(` entry ${o}${s}`)}},at=e=>{const t=e.map(({manifest:r})=>({bindings:(r.bindings??[]).map(n=>({path:n.path.join("."),value:n.value})),deps:Object.keys(r.deps??{}),devDependencies:Object.keys(r.devDependencies??{}),entrypointReexports:(r.entrypointReexports??[]).map(n=>({module:n.module,...n.comment?{comment:n.comment}:{}})),envVars:(r.envVars??[]).map(n=>({name:n.name,...n.secret?{secret:!0}:{value:n.value??""}})),files:r.files.map(n=>({merge:n.merge,to:n.to})),name:r.name,requires:r.requires??[],title:r.title}));process.stdout.write(`${JSON.stringify({items:t},void 0,2)}
|
|
16
|
+
`)},ct=(e,t,r,n,o)=>{o.success(`add complete: ${String(r)} written, ${String(n)} skipped`),o.info("next steps:"),o.info(" lunora codegen # regenerate _generated/ so the new tables/functions appear"),t.length>0&&o.info(" pnpm install # install newly-added dependencies");for(const{manifest:s}of e)s.docs&&o.info(`${s.name}: ${s.docs}`)},ut=async e=>{const t=b(),r=N("list",e);if(r)return e.logger.error(r),{...t,code:1};let n=()=>{};try{const o=await st(e);n=o.cleanup;const s=ce(o.root);if(e.json)return process.stdout.write(`${JSON.stringify(s,void 0,2)}
|
|
17
|
+
`),t;e.logger.info(`available registry items (${String(s.length)}):`);for(const c of s)e.logger.info(` ${c.name}${c.description?` — ${c.description}`:""}`);return t}catch(o){return e.logger.error(`list failed: ${o instanceof Error?o.message:String(o)}`),{...t,code:1}}finally{n()}},xt=async e=>{const t=e.cwd??process.cwd(),r=b();if(e.list)return ut(e);if(e.names.length===0)return e.logger.error("add requires at least one item name. Usage: lunora registry add <name> [...names]"),{...r,code:1};const n=N("add",e);if(n)return e.logger.error(n),{...r,code:1};let o=[];try{const{cleanups:s,items:c}=await it(e.names,e);o=s;const{transformManifest:a}=e,i=a?c.map($=>({...$,manifest:a($.manifest)})):c;for(const{manifest:$}of i)Q(e.logger,$);if(e.json&&at(i),e.dryRun)return e.logger.info("dry-run: stopping before any files are written"),r;if(e.diff)return J(i,t,e.logger,{diff:!0}),e.logger.info("diff: preview only — re-run without --diff to apply"),r;if(!await Le(i,e))return{...r,code:1};const{bindings:u,deps:f,skipped:d,written:p}=J(i,t,e.logger,{overwrite:e.overwrite});return ct(i,f,p.length,d.length,e.logger),{bindings:u,code:0,deps:f,skipped:d,written:p}}catch(s){return e.logger.error(`add failed: ${s instanceof Error?s.message:String(s)}`),{...r,code:1}}finally{for(const s of o)s()}},Nt=async e=>{const t=b();if(e.names.length===0)return e.logger.error("view requires an item name. Usage: lunora registry view <name>"),{...t,code:1};const r=N("view",e);if(r)return e.logger.error(r),{...t,code:1};const n=[];try{for(const o of e.names){const{cleanup:s,directory:c}=await K(o,e);n.push(s);const a=Y(c,o);Q(e.logger,a);for(const i of a.files){e.logger.info(`--- ${i.to} (${i.merge}) ---`);const u=m(l(c,i.from),"utf8");for(const f of u.split(`
|
|
18
|
+
`))e.logger.info(f)}}return t}catch(o){return e.logger.error(`view failed: ${o instanceof Error?o.message:String(o)}`),{...t,code:1}}finally{for(const o of n)o()}},Ot=async e=>{const t=b(),r=e.from;if(r===void 0)return e.logger.error("registry build requires --from <registry root>"),{...t,code:1};if(!g(r))return e.logger.error(`registry root not found: ${r}`),{...t,code:1};const n=ue(r),o=e.out??l(r,"index.json");if(e.check){const s=g(o)?JSON.parse(m(o,"utf8")):{items:[]};return JSON.stringify(s.items??[])!==JSON.stringify(n.items)?(e.logger.error(`registry: ${o} is stale — run \`lunora registry build\` to regenerate it`),{...t,code:1}):(e.logger.success(`registry: ${o} is up to date (${String(n.items.length)} items)`),t)}return h(o,`${JSON.stringify({$schema:"./schema/registry.schema.json",...n},void 0,4)}
|
|
19
|
+
`,"utf8"),e.logger.success(`registry: wrote ${o} (${String(n.items.length)} items)`),t};export{Ne as L,xt as M,kt as P,ut as R,je as b,jt as d,U as g,Nt as k,Ot as q};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{STEP_BADGE_NAMES as p,LunoraReporter as u}from"@lunora/config";import{JsonReporter as g}from"@visulima/pail/reporter/json";import{createPail as l}from"@visulima/pail/server";let n,a=!1,t;const d=()=>{if(a)return!0;const r=process.env.LUNORA_LOG_JSON;return r==="1"||r==="true"},c=r=>new r,f=()=>a?[c(g)]:t!==void 0&&t.length>0?t:[c(d()?g:u)],v=()=>{a||(a=!0,n=void 0)},S={compose:(...r)=>r,console:()=>c(u),json:()=>c(g)},y=r=>{t=Array.isArray(r)?r:[r],n=void 0},m=Object.fromEntries(p.map(r=>[r,{label:r,logLevel:"informational"}])),o=()=>(n??=l({reporters:f(),scope:["lunora"],stderr:process.stderr,stdout:process.stdout,types:m}),n),A=()=>({debug:r=>{o().debug(r)},error:r=>{o().error(r)},info:r=>{o().info(r)},success:r=>{o().success(r)},warn:r=>{o().warn(r)}}),P=()=>{const r=(e,s)=>{process.stderr.write(`${e} ${s}
|
|
2
|
+
`)};return{debug:e=>{r("debug",e)},error:e=>{r("error",e)},info:e=>{r("info ",e)},success:e=>{r("ok ",e)},warn:e=>{r("warn ",e)}}},E=new Proxy({},{get(r,e){const s=o(),i=s[e];return typeof i=="function"?i.bind(s):i}}),O=(r,e)=>{o()[r](e)};export{y as configureLogHandlers,A as createLogger,P as createStderrLogger,v as forceJsonLogging,o as getPail,S as logHandlers,O as logStep,E as pail};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{spawn as l}from"node:child_process";const u=/[\s"%&<>^|]/u,m=/(\\*)"/gu,w=/(\\+)$/u,h=(t,e,n=process.platform)=>{if(n!=="win32"||t===process.execPath)return{args:[...e],command:t,shell:!1};const c=r=>r===""?'""':u.test(r)?`"${r.replaceAll(m,String.raw`$1$1\"`).replace(w,"$1$1")}"`:r;return{args:e.map(r=>c(r)),command:c(t),shell:!0}},S=t=>new Promise((e,n)=>{const c=typeof t.input=="string",r=t.captureStdout===!0;let p="inherit";r?p="pipe":t.stdoutToStderr&&(p=2);const a=h(t.command,t.args),s=l(a.command,a.args,{cwd:t.cwd??process.cwd(),env:t.env?{...process.env,...t.env}:process.env,shell:a.shell,stdio:[c?"pipe":"inherit",p,"inherit"]});let i="";r&&s.stdout&&s.stdout.on("data",o=>{i+=o.toString("utf8"),process.stdout.write(o)}),s.on("error",o=>{n(o)}),s.on("exit",(o,d)=>{e({code:o??(d?1:0),stdout:r?i:void 0})}),c&&s.stdin&&s.stdin.end(t.input)}),f=(t=0)=>{const e=[];return{calls:e,spawner:n=>(e.push({descriptor:n}),Promise.resolve({code:t}))}};export{f as createRecordingSpawner,S as defaultSpawner,h as spawnShellCompat};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{spawnSync as t}from"node:child_process";import{LunoraError as m}from"@lunora/errors";import{findPackageManagerSync as o,identifyInitiatingPackageManager as p}from"@visulima/package/package-manager";const c=["pnpm","bun","yarn","npm"],i=new Set(["bun","npm","pnpm","yarn"]),s=n=>i.has(n),u=n=>{try{return t(n,["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}},d=(n=u)=>c.filter(a=>n(a)),y=n=>({args:["install"],command:n}),b=n=>{try{return o(n).packageManager}catch{}const a=p();if(a!==void 0){const e=a.name==="cnpm"?"npm":a.name;if(s(e))return e}const[r]=d();if(r!==void 0)return r;throw new m("INTERNAL","Could not detect a package manager: no lock file or `packageManager` field was found, and none (pnpm, bun, yarn, npm) is installed on PATH.")},k=(n,a,r)=>n==="yarn"?{args:[a,...r],command:"yarn"}:n==="bun"?{args:["x",a,...r],command:"bun"}:n==="npm"?{args:["--",a,...r],command:"npx"}:{args:["exec",a,...r],command:"pnpm"},w=(n,a)=>n==="npm"?`npm run ${a}`:n==="bun"?`bun run ${a}`:`${n} ${a}`;export{k as M,b as P,y as d,w as k,d as t};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{quoteIdentifier as l,sqlAffinityForKind as f,frameworkColumnDdl as $,columnRef as y,physicalIndexName as u}from"@lunora/d1/dialect";const q=e=>f(e),d=(e,n)=>{const s=[l(e),n.sqlType];return n.nullable||s.push("NOT NULL"),s.join(" ")},T=e=>{const n=Object.entries(e.columns).map(([r,a])=>` ${d(r,a)}`),s=[...$().map(r=>` ${r}`),...n].join(`,
|
|
2
|
+
`);return`CREATE TABLE IF NOT EXISTS ${l(e.name)} (
|
|
3
|
+
${s}
|
|
4
|
+
);`},h=e=>`DROP TABLE IF EXISTS ${l(e)};`,b=(e,n,s)=>`ALTER TABLE ${l(e)} ADD COLUMN ${d(n,s)};`,m=(e,n)=>{const s=n.fields.map(r=>y(r)).join(", ");return`CREATE ${n.unique?"UNIQUE ":""}INDEX IF NOT EXISTS ${u(e,n.name)} ON ${l(e)} (${s});`},E=(e,n)=>`DROP INDEX IF EXISTS ${u(e,n)};`,L=(e,n,s,r,a)=>{s.sqlType!==r.sqlType&&a.push({kind:"columnTypeChange",summary:`column type change on ${e}.${n}: ${s.sqlType} → ${r.sqlType} (write SQL manually)`}),s.nullable!==r.nullable&&a.push({kind:"columnTypeChange",summary:`nullability change on ${e}.${n}: ${s.nullable?"NULL":"NOT NULL"} → ${r.nullable?"NULL":"NOT NULL"} (write SQL manually)`})},N=(e,n,s,r,a)=>{for(const[o,i]of Object.entries(s)){const t=n[o];if(t===void 0){r.push({kind:"addColumn",sql:b(e,o,i),summary:`ADD COLUMN ${e}.${o}`});continue}L(e,o,t,i,a)}for(const o of Object.keys(n))s[o]===void 0&&a.push({kind:"dropColumn",summary:`DROP COLUMN ${e}.${o} (SQLite drop-column requires careful migration — write SQL manually)`})},O=(e,n,s,r,a)=>{for(const[o,i]of Object.entries(s)){const t=n[o];if(t===void 0){r.push({kind:"createIndex",sql:m(e,i),summary:`CREATE INDEX ${o} ON ${e}`});continue}(!(t.fields.length===i.fields.length&&t.fields.every((p,c)=>p===i.fields[c]))||t.unique!==i.unique)&&a.push({kind:"indexRename",summary:`index ${o} changed on ${e} — drop+create manually if intentional`})}for(const o of Object.keys(n))s[o]===void 0&&r.push({kind:"dropIndex",sql:E(e,o),summary:`DROP INDEX ${o}`})},g=(e,n,s)=>{s.push({kind:"createTable",sql:T(n),summary:`CREATE TABLE ${e}`});for(const r of Object.values(n.indexes))s.push({kind:"createIndex",sql:m(e,r),summary:`CREATE INDEX ${r.name} ON ${e}`})},D=(e,n)=>{const s=e?.tables??{},r=[],a=[];for(const[o,i]of Object.entries(n.tables)){const t=s[o];if(t===void 0){g(o,i,r);continue}N(o,t.columns,i.columns,r,a),O(o,t.indexes,i.indexes,r,a)}for(const[o]of Object.entries(s))n.tables[o]===void 0&&r.push({kind:"dropTable",sql:h(o),summary:`DROP TABLE ${o}`});return{empty:r.length===0&&a.length===0,entries:r,unsupported:a}},C=(e,n,s)=>{const r=[`-- Lunora migration: ${e}`,`-- Generated at ${s}`,"-- This file was produced by `lunora migrate generate`. Review carefully before applying.",""];for(const a of n.entries)r.push(`-- ${a.summary}`,a.sql,"");if(n.unsupported.length>0){r.push("-- ---------------------------------------------------------------","-- The following deltas are NOT auto-generated in v0.1.","-- Write the appropriate SQL below by hand:","--");for(const a of n.unsupported)r.push(`-- * ${a.summary}`);r.push("-- ---------------------------------------------------------------","")}return n.empty&&r.push("-- No changes detected. Re-running `lunora migrate generate` will overwrite this file.",""),r.join(`
|
|
5
|
+
`)};export{D as diffSnapshots,b as renderAddColumn,m as renderCreateIndex,T as renderCreateTable,E as renderDropIndex,h as renderDropTable,C as renderMigrationFile,q as validatorKindToSqlType};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{spawnSync as r}from"node:child_process";const e=()=>{try{return r("docker",["info"],{stdio:"ignore"}).status===0}catch{return!1}},s=()=>{if(typeof process.env.BUILDKIT_HOST!="string"||process.env.BUILDKIT_HOST.length===0)return!1;try{return r("railpack",["--version"],{stdio:"ignore"}).status===0}catch{return!1}};export{s as o,e as r};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{Project as f,SyntaxKind as o,Node as i}from"ts-morph";const x=/^[A-Za-z_$][\w$]*$/u,s=r=>`// lunora:add:${r}:start`,a=r=>`// lunora:add:${r}:end`,p=r=>`./${r}/schema`,m=r=>{for(const e of r)if(e.getExpression().getText()==="defineSchema")return e},g=r=>{let e=r;for(let t=e.getParent();t!==void 0;t=e.getParent())if(i.isPropertyAccessExpression(t)&&t.getExpression()===e)e=t;else if(i.isCallExpression(t)&&t.getExpression()===e)e=t;else break;return e},E=(r,e)=>{if(!x.test(e))return{ok:!1,reason:"invalid-identifier"};if(r.includes(s(e)))return{ok:!1,reason:"already-applied"};const t=new f({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}).createSourceFile("schema.ts",r,{overwrite:!0}),l=t.getDescendantsOfKind(o.CallExpression),n=m(l);if(!n)return{ok:!1,reason:"no-define-schema"};if(n.getArguments()[0]?.getKind()!==o.ObjectLiteralExpression)return{ok:!1,reason:"non-object-argument"};const c=g(n).getEnd(),d=`
|
|
2
|
+
${s(e)}
|
|
3
|
+
.extend(${e}.extension)
|
|
4
|
+
${a(e)}
|
|
5
|
+
`;t.insertText(c,d);const u=`${s(e)}
|
|
6
|
+
import { ${e} } from "${p(e)}";
|
|
7
|
+
${a(e)}
|
|
8
|
+
`;return t.insertText(0,u),{ok:!0,text:t.getFullText()}};export{E as insertSchemaExtension};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{spawn as s}from"node:child_process";import{platform as a}from"node:os";import{LunoraError as n}from"@lunora/errors";const i=()=>{const e=a();return e==="darwin"?{args:[],command:"open"}:e==="win32"?{args:["/c","start",""],command:"cmd"}:{args:[],command:"xdg-open"}},d=e=>e.replaceAll("%","%25").replaceAll("&","%26").replaceAll("|","%7C").replaceAll("^","%5E").replaceAll("<","%3C").replaceAll(">","%3E").replaceAll("(","%28").replaceAll(")","%29").replaceAll('"',"%22").replaceAll("!","%21"),w=e=>new Promise((o,r)=>{const{args:t,command:c}=i(),p=a()==="win32"?d(e):e,l=s(c,[...t,p],{detached:!0,stdio:"ignore"});l.once("error",m=>{r(m)}),l.once("spawn",()=>{l.unref(),o()})}),h=async(e,o={})=>{let r;try{r=new URL(e)}catch{throw new n("INTERNAL",`Invalid URL: ${e}`)}if(r.protocol!=="http:"&&r.protocol!=="https:")throw new n("INTERNAL",`Refusing to open non-http(s) URL: ${e}`);await(o.opener??w)(e)};export{h as f};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createStderrLogger as o}from"./createLogger--C3x1FNE.mjs";const e=new Set(["json","pretty"]),i=(t,r)=>{if(r!==void 0&&!e.has(r))return`${t}: unknown --format "${r}" — expected pretty | json`},s=t=>t==="json",d=(t,r)=>s(t)?o():r,p=t=>{process.stdout.write(`${JSON.stringify(t,void 0,2)}
|
|
2
|
+
`)};export{p as d,i,s as r,d as s};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as i}from"@lunora/errors";const l=/[\r\n]/u,d=/^[A-Za-z_]\w*$/u,g=/^[A-Za-z0-9][\w-]*$/u,b=/^[\w.-]+(?:\/[\w.-]+)*$/u,L=(a,o)=>{if(typeof a!="object"||a===null)throw new i("INTERNAL",`registry.json for "${o}" is not an object`);const t=a,{name:s}=t;if(typeof s!="string"||s.length===0)throw new i("INTERNAL",`registry.json for "${o}" is missing a string "name"`);if(!g.test(s))throw new i("INTERNAL",`registry.json for "${o}": name "${s}" must match ${g.source} (letters, digits, "-", "_"; no path separators, "..", or code)`);const y=t.files;if(!Array.isArray(y))throw new TypeError(`registry.json for "${o}" is missing a "files" array`);const w=y.map((e,r)=>{if(typeof e!="object"||e===null)throw new i("INTERNAL",`registry.json "${o}": files[${String(r)}] is not an object`);const n=e,{from:f}=n,{to:p}=n,{merge:m}=n;if(typeof f!="string"||typeof p!="string")throw new TypeError(`registry.json "${o}": files[${String(r)}] needs string "from" and "to"`);if(m!=="create-or-skip"&&m!=="schema-extension")throw new i("INTERNAL",`registry.json "${o}": files[${String(r)}].merge must be "create-or-skip" or "schema-extension"`);for(const[R,c]of[["from",f],["to",p]])if(c.includes("..")||c.startsWith("/"))throw new i("INTERNAL",`registry.json "${o}": files[${String(r)}].${R} "${c}" must be a relative path without ".."`);return{from:f,merge:m,to:p}}),u=e=>typeof e=="object"&&e!==null?e:void 0,h=u(t.deps),$=u(t.devDependencies),A=Array.isArray(t.requires)?t.requires.filter(e=>typeof e=="string"):void 0,v=Array.isArray(t.bindings)?t.bindings.filter(e=>{if(typeof e!="object"||e===null)return!1;const r=e;return Array.isArray(r.path)&&r.path.every(n=>typeof n=="string")}):void 0,j=Array.isArray(t.entrypointReexports)?t.entrypointReexports.filter(e=>typeof e=="object"&&e!==null&&typeof e.module=="string").map(e=>{if(e.module.includes("..")||e.module.startsWith("/")||!b.test(e.module))throw new i("INTERNAL",`registry.json "${o}": entrypointReexports[].module "${e.module}" must be a safe relative module path without path traversal or unsafe characters`);const r={module:e.module};if(typeof e.comment=="string"){if(l.test(e.comment))throw new i("INTERNAL",`registry.json "${o}": entrypointReexports[].comment must not contain a newline`);r.comment=e.comment}return r}):void 0,N=Array.isArray(t.envVars)?t.envVars.filter(e=>typeof e=="object"&&e!==null&&typeof e.name=="string").map(e=>{const r=typeof e.value=="string";if(!d.test(e.name))throw new i("INTERNAL",`registry.json "${o}": envVars["${e.name}"].name must match ${d.source} (letters, digits, underscore; no "=" or newline)`);if(r&&l.test(e.value))throw new i("INTERNAL",`registry.json "${o}": envVars["${e.name}"].value must not contain a newline`);if(typeof e.description=="string"&&l.test(e.description))throw new i("INTERNAL",`registry.json "${o}": envVars["${e.name}"].description must not contain a newline`);return{...typeof e.description=="string"?{description:e.description}:{},name:e.name,secret:typeof e.secret=="boolean"?e.secret:!r,...r?{value:e.value}:{}}}):void 0;return{bindings:v,deps:h,description:typeof t.description=="string"?t.description:void 0,devDependencies:$,docs:typeof t.docs=="string"?t.docs:void 0,entrypointReexports:j,envVars:N,files:w,name:s,requires:A,title:typeof t.title=="string"?t.title:void 0}};export{L as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
class e extends Error{constructor(){super("cancelled"),this.name="PromptCancelledError"}}const o=130;export{e as P,o as a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{readLinkedProject as e}from"@lunora/config";const t=({cwd:o,url:r})=>r!==void 0&&r!==""?r:e(o)?.workerUrl,c=({cwd:o,prod:r,url:d})=>d!==void 0&&d!==""?d:r?e(o)?.workerUrl:void 0;export{c as s,t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"node:fs";import"@visulima/path";import{M as d,q as i,R as s,k as t}from"./commands-BhX2Bo9B.mjs";import"./buildRegistryIndex-DwySASBu.mjs";export{d as runAddCommand,i as runBuildIndexCommand,s as runListCommand,t as runRegistryViewCommand};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync as i,readFileSync as u,writeFileSync as d}from"node:fs";import{evaluateSchemaDrift as g,parseSchemaSnapshot as b,SchemaSnapshotParseError as p,serializeSchemaSnapshot as m}from"@lunora/codegen";const f=e=>{if(!i(e))return{status:"absent"};let s;try{s=u(e,"utf8")}catch{return{status:"corrupt"}}try{const a=b(s);return a===void 0?{status:"corrupt"}:{snapshot:a,status:"ok"}}catch(a){if(a instanceof p)return{status:"corrupt"};throw a}},S=(e,s)=>{d(e,m(s),"utf8")},k=e=>{const s=`schema-drift gate: the committed baseline ${e.snapshotPath} is unreadable or malformed, so schema drift cannot be checked. Fix it (e.g. resolve a merge conflict in lunora/.lunora-schema.json), or pass --update-schema-baseline to regenerate it from the current schema.`;return e.updateBaseline&&!e.readOnly?(e.logger.warn(`schema baseline was unreadable; regenerating from the current schema on success (--update-schema-baseline): ${e.snapshotPath}`),{blocked:!1,changes:[],reason:s,rebless:e.rebless}):(e.readOnly||e.logger.error(s),{blocked:!0,changes:[],reason:s})},y=(e,s)=>(s.readOnly||s.logger.error(e.reason),s.updateBaseline&&!s.readOnly?(s.logger.warn(`schema baseline will be re-blessed despite breaking drift on success (--update-schema-baseline): ${s.snapshotPath}`),{blocked:!1,changes:e.changes,reason:e.reason,rebless:s.rebless}):{blocked:!0,changes:e.changes,reason:e.reason}),P=e=>{const{allowDrift:s,codegen:a,logger:l,readOnly:t=!1,updateBaseline:h=!1}=e,n=a.schemaSnapshotPath,o=f(n),c={logger:l,readOnly:t,rebless:()=>{S(n,a.schemaSnapshot)},snapshotPath:n,updateBaseline:h};if(o.status==="corrupt")return k(c);const r=g({allowDrift:s,baseline:o.status==="ok"?o.snapshot:void 0,current:a.schemaSnapshot});return r.blocked?y(r,c):r.changes.length>0?(t||l.info(r.reason),{blocked:!1,changes:r.changes,reason:r.reason,rebless:t?void 0:c.rebless}):{blocked:!1,changes:r.changes,reason:r.reason}};export{P as k};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{validatorKindToSqlType as i}from"./diffSnapshots-9bDd9nOK.mjs";const r=e=>e.kind==="optional"&&e.inner?{nullable:!0,sqlType:i(e.inner.kind)}:{nullable:!1,sqlType:i(e.kind)},f=e=>e==="global",c=e=>{const s={};for(const o of e.tables){if(!f(o.shardMode))continue;const a={};for(const[n,t]of Object.entries(o.shape))a[n]=r(t);const l={};for(const n of o.indexes)l[n.name]={fields:[...n.fields],name:n.name,unique:n.unique??!1};s[o.name]={columns:a,indexes:l,name:o.name}}return{tables:s,version:1}};export{c as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{d as s}from"./commands-BhX2Bo9B.mjs";const d=/[^a-z0-9]+/u,r=(e,t,a)=>{let n=e.toLowerCase().split(d).filter(Boolean).join("-").slice(0,a);return n.endsWith("-")&&(n=n.slice(0,-1)),n.length>=t?n:void 0},u="DB",c="Name your D1 database (run `wrangler d1 create` to get its id, then put it in wrangler.jsonc)",l=e=>r(e,1,64),h="lunora-db",m=e=>l(`${e}-db`)??h,y=async(e,t)=>{const a=m(t);return l(await e(c,{default:a,placeholder:a}))??a},_=(e,t)=>s(e,"d1_databases",{key:"binding",value:u},"database_name",t),f=[{description:"Email + password on better-auth (default)",label:"Email & password",value:"auth"},{description:"Clerk-hosted auth",label:"Clerk",value:"auth-clerk"},{description:"Auth0 (OIDC)",label:"Auth0",value:"auth-auth0"}],i="auth",j=async e=>await e("Which auth provider?",f,{default:i})??i,C="mail",D=e=>{const t=e.trim();if(t==="")return;const a=t.toLowerCase();return a==="auth"?{kind:"auth"}:a==="email"||a==="mail"?{kind:"email"}:{item:a,kind:"item"}},p="SEND_EMAIL",A="Verified destination email for production delivery (blank = set it later in wrangler.jsonc)",$=e=>{const t=e.trim();if(t.length===0||t.includes(" "))return!1;const a=t.indexOf("@");if(a<=0||a!==t.lastIndexOf("@"))return!1;const n=t.slice(a+1);return n.length>=3&&n.includes(".")&&!n.startsWith(".")&&!n.endsWith(".")},E=(e,t)=>{const a=e.trim();if(a!==""){if(!$(a)){t(`"${a}" doesn't look like an email — leaving the placeholder; set destination_address in wrangler.jsonc.`);return}return a}},L=(e,t)=>s(e,"send_email",{key:"name",value:p},"destination_address",t),b="UPLOADS",k="Name your R2 bucket (you can rename it in wrangler.jsonc later)",o=e=>r(e,3,63),g="lunora-uploads",w=e=>o(`${e}-uploads`)??g,O=async(e,t)=>{const a=w(t);return o(await e(k,{default:a,placeholder:a}))??a},W=(e,t)=>s(e,"r2_buckets",{key:"binding",value:b},"bucket_name",t);export{w as a,A as b,m as c,E as d,y as e,i as f,j as g,f as h,o as i,_ as j,L as l,C as n,D as o,W as p,l as r,O as u};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{jsx as t,jsxs as c}from"react/jsx-runtime";import{isInteractive as m,ACCENT as b,LUNA_ART as oe,LUNA_NAME as se,LUNA_SIGNOFF as ce,BADGE_COLUMN_WIDTH as j,badgeLead as de,padBadge as ue,badgeWidth as K}from"@lunora/config";import{render as V}from"@visulima/tui";import"@visulima/tui/components/big-text";import{Box as d}from"@visulima/tui/components/box";import{CommandPalette as fe}from"@visulima/tui/components/command-palette";import{ConfirmInput as he}from"@visulima/tui/components/confirm-input";import{SelectInput as me}from"@visulima/tui/components/select-input";import{Spinner as ge}from"@visulima/tui/components/spinner";import{Text as o}from"@visulima/tui/components/text";import{TextInput as pe}from"@visulima/tui/components/text-input";import{useApp as $}from"@visulima/tui/hooks/use-app";import{useInput as W}from"@visulima/tui/hooks/use-input";import{useInterval as be}from"@visulima/tui/hooks/use-interval";import{useEffect as L,useState as x}from"react";import{P as Z}from"./prompt-cancelled-C8Sj7OqI.mjs";let H=!1;const F=()=>{H||(H=!0,process.getMaxListeners()<64&&process.setMaxListeners(64))},ve=({children:e,onCancel:r})=>{const{exit:n}=$();return W((a,l)=>{l.ctrl&&a==="c"&&(r(),n())}),e},z=e=>e instanceof Error?e:new Error(typeof e=="string"?e:"task failed"),J=10,we=8,I=({spec:e})=>c(o,{children:[t(o,{children:de(e.text)}),t(o,{backgroundColor:e.bg,bold:!0,color:e.fg,children:ue(e.text)})]}),ee=({badge:e,message:r})=>e===void 0?t(o,{bold:!0,children:r}):c(d,{children:[t(I,{spec:e}),t(o,{bold:!0,children:` ${r}`})]}),re=2,ne=" ".repeat(j-1),te=e=>" ".repeat(K(e)+1),xe=e=>e===void 0?re:K(e)+1,N=({badge:e,children:r,message:n})=>c(d,{flexDirection:"column",children:[t(ee,{badge:e,message:n}),t(d,{flexDirection:"column",marginLeft:xe(e),children:r})]}),S=({answer:e,badge:r,message:n})=>c(d,{flexDirection:"column",children:[t(ee,{badge:r,message:n}),e===""?null:t(o,{dimColor:!0,children:`${r===void 0?" ".repeat(re):te(r)}${e}`})]}),A=e=>{const{exit:r}=$(),[n,a]=x(void 0);return L(()=>{n!==void 0&&r()},[n,r]),{answer:n,submit:(l,i)=>{e(l),a(i)}}},$e=({children:e})=>{const{exit:r}=$();return L(()=>{r()},[r]),e},y=async e=>{F(),process.stdout.write(`
|
|
2
|
+
`);const r=V(t($e,{children:e}));try{await r.waitUntilExit()}catch{}finally{r.unmount()}},rr=async(e,r,n)=>{if(!m())return;const a=n===void 0||n===""?[]:n.split(`
|
|
3
|
+
`);await y(c(d,{flexDirection:"column",children:[c(d,{children:[t(I,{spec:e}),t(o,{bold:!0,children:` ${r}`})]}),a.map(l=>t(o,{dimColor:!0,children:`${te(e)}${l}`},l))]}))},G=async e=>{F(),process.stdout.write(`
|
|
4
|
+
`);const r={value:!1},n=V(t(ve,{onCancel:()=>{r.value=!0},children:e}),{exitOnCtrlC:!1});try{await n.waitUntilExit()}finally{n.unmount()}if(r.value)throw new Z},k=async(e,r)=>{let n=r;return await G(e(a=>{n=a})),n},le=e=>e.description===void 0?e.label:`${e.label} — ${e.description}`,O=()=>{const{exit:e}=$();W((r,n)=>{n.escape&&e()})},ye=({badge:e,finish:r,initialIndex:n,message:a,options:l})=>{const{answer:i,submit:u}=A(r);return O(),i!==void 0?t(S,{answer:i,badge:e,message:a}):t(N,{badge:e,message:a,children:t(me,{accentColor:b,initialIndex:n,items:l.map(s=>({key:s.value,label:le(s),value:s.value})),limit:J,onSelect:s=>{u(s.value,l.find(f=>f.value===s.value)?.label??s.value)}})})},Ce=({badge:e,finish:r,message:n,options:a})=>{const{exit:l}=$(),{answer:i,submit:u}=A(r);return i!==void 0?t(S,{answer:i,badge:e,message:n}):t(N,{badge:e,message:n,children:t(fe,{accentColor:b,autoFocus:!0,commands:a.map(s=>({description:s.description,id:s.value,label:s.label})),limit:J,onCancel:()=>{l()},onSelect:s=>{u(s,a.find(f=>f.value===s)?.label??s)},placeholder:"Type to filter…"})})},nr=async(e,r,n)=>{if(!m()||r.length===0)return n?.default;const{badge:a}=n??{};if(r.length>we)return k(i=>t(Ce,{badge:a,finish:i,message:e,options:r}),n?.default);const l=n?.default===void 0?-1:r.findIndex(i=>i.value===n.default);return k(i=>t(ye,{badge:a,finish:i,initialIndex:l>=0?l:void 0,message:e,options:r}),n?.default)},De=({badge:e,defaultValue:r,finish:n,message:a,placeholder:l})=>{const{answer:i,submit:u}=A(n);return O(),i!==void 0?t(S,{answer:i,badge:e,message:a}):t(N,{badge:e,message:a,children:t(pe,{defaultValue:r,onSubmit:s=>{const f=s.trim()===""?r:s.trim();u(f,f)},placeholder:l})})},tr=async(e,r)=>{const n=r?.default??"";if(!m())return n;const{badge:a}=r??{};return k(l=>t(De,{badge:a,defaultValue:n,finish:l,message:e,placeholder:r?.placeholder}),n)},ke=({badge:e,defaults:r,finish:n,message:a,options:l})=>{const{answer:i,submit:u}=A(n),[s,f]=x(0),[g,C]=x(()=>new Set(r));return O(),W((p,v)=>{if(!(i!==void 0||l.length===0)){if(v.upArrow)f(h=>(h-1+l.length)%l.length);else if(v.downArrow)f(h=>(h+1)%l.length);else if(p===" "){const h=l[s];h!==void 0&&C(w=>{const E=new Set(w);return E.has(h.value)?E.delete(h.value):E.add(h.value),E})}else if(v.return){const h=l.filter(w=>g.has(w.value));u(h.map(w=>w.value),h.length>0?h.map(w=>w.label).join(", "):"none")}}}),i!==void 0?t(S,{answer:i,badge:e,message:a}):t(N,{badge:e,message:a,children:c(d,{flexDirection:"column",children:[t(o,{dimColor:!0,children:"space toggles · enter confirms · esc cancels"}),l.map((p,v)=>{const h=v===s;return t(o,{color:h?b:void 0,children:`${h?"▸ ":" "}${g.has(p.value)?"◼":"◻"} ${le(p)}`},p.value)})]})})},lr=async(e,r,n)=>{const a=n?.defaults??[];if(!m()||r.length===0)return[...a];const{badge:l}=n??{};return k(i=>t(ke,{badge:l,defaults:a,finish:i,message:e,options:r}),[...a])},Ie=({badge:e,defaultYes:r,finish:n,message:a})=>{const{answer:l,submit:i}=A(n);return l!==void 0?t(S,{answer:l,badge:e,message:a}):c(d,{children:[e===void 0?null:t(I,{spec:e}),t(o,{bold:!0,children:e===void 0?`${a} `:` ${a} `}),t(he,{defaultChoice:r?"confirm":"cancel",onCancel:()=>{i(!1,"No")},onConfirm:()=>{i(!0,"Yes")}})]})},Se=async(e,r)=>{const n=r?.defaultYes===!0;if(!m())return n;const{badge:a}=r??{};return k(l=>t(Ie,{badge:a,defaultYes:n,finish:l,message:e}),!1)},ar=()=>m()?e=>Se(e,{defaultYes:!0}):()=>Promise.resolve(!1),P="#c8a8ff",U="#d9c8ff",Ae="#6b5b9a",M=({moon:e,prefix:r,suffix:n})=>c(d,{children:[t(o,{color:P,dimColor:!0,children:r}),typeof e=="string"?t(o,{color:U,children:e}):e,n===void 0?null:t(o,{color:P,children:n})]}),Q=({left:e,right:r})=>c(o,{color:U,children:[e,t(o,{color:Ae,children:"●●"}),r]}),Ee=()=>c(d,{flexDirection:"column",paddingX:1,children:[t(M,{moon:".-‐-.",prefix:"· ✦ · ",suffix:" ✦"}),t(M,{moon:t(Q,{left:"/",right:"\\"}),prefix:" ✦ · ",suffix:" ·"}),t(M,{moon:t(Q,{left:"\\",right:"/"}),prefix:" . ✦ · "}),c(d,{children:[t(o,{bold:!0,color:b,children:" lunora init "}),t(o,{dimColor:!0,children:"· moonrise sequence"}),t(o,{color:U})]})]}),ir=async e=>{m()&&await y(c(d,{flexDirection:"column",children:[t(Ee,{}),t(d,{paddingX:1,children:t(o,{dimColor:!0,children:e})})]}))},Te=({label:e})=>c(d,{children:[t(o,{color:b,children:t(ge,{type:"dots"})}),c(o,{children:[" ",e]})]}),or=async(e,r)=>{if(!m())return r();F();const n=V(t(Te,{label:e}));try{return await r()}finally{n.unmount()}},sr=async()=>{m()&&await y(c(d,{paddingX:1,children:[t(o,{color:U,children:oe}),c(d,{flexDirection:"column",marginLeft:2,children:[t(o,{bold:!0,color:b,children:se}),t(o,{children:ce})]})]}))},Le="#06b6d4",_=" ".repeat(9),cr=async e=>{m()&&await y(t(o,{bold:!0,children:`${_}${e}`}))},dr=async e=>{m()&&await y(c(d,{children:[t(o,{color:Le,children:`${ne}◼`}),t(o,{children:` ${e}`})]}))},ur=async(e,r,n,a)=>{m()&&await y(c(d,{flexDirection:"column",children:[c(d,{children:[t(I,{spec:e}),t(o,{bold:!0,children:` ${r}`})]}),t(d,{flexDirection:"column",marginTop:1,children:n.map(l=>c(o,{children:[`${_}${l.lead} `,t(o,{color:b,children:l.code}),l.tail??""]},l.lead))}),t(d,{flexDirection:"column",marginTop:1,children:a.map(l=>c(o,{children:[`${_}${l.lead} `,t(o,{color:b,children:l.code}),l.tail??""]},l.lead))})]}))},T=" ".repeat(j-1),q="#a855f7",ae="#06b6d4",D=[q,"#9b51f6","#8a5cf6","#6f86f6","#4aa6ef","#2bb6dd","#12bcd0",ae],B=D.length-2,X=(e,r)=>Array.from({length:Math.max(0,e)},()=>r),R=[...X(D.length-1,q),...D,...X(D.length-1,ae),...D.toReversed()],Y=R.map((e,r)=>{const n=R.slice(r,r+B);return[...n,...X(B-n.length,q)]}),Ne=" ".repeat(Math.max(0,j-B)),ie=({label:e})=>{const[r,n]=x(0);be(()=>{n(l=>(l+1)%Y.length)},90);const a=Y[r%Y.length]??[];return c(o,{children:[Ne,a.map((l,i)=>t(o,{color:l,children:"█"},i)),` ${e}`]})},Ue=({label:e,status:r})=>r==="running"?t(o,{color:b,children:`${T}▶ ${e}`}):r==="failed"?t(o,{color:"red",children:`${T}✖ ${e}`}):r==="done"?t(o,{dimColor:!0,children:`${T}■ ${e}`}):t(o,{dimColor:!0,children:`${T}□ ${e}`}),Me=async(e,r)=>{const n=[];let a;for(const[l,i]of e.entries()){r(l,"running");try{n.push(await i.run()),r(l,"done")}catch(u){r(l,"failed"),a=u;break}}return{failure:a,results:n}},Ye=(e,r,n,a)=>{let l=!0;return Me(e,(i,u)=>{l&&r(s=>s.map((f,g)=>g===i?u:f))}).then(({failure:i,results:u})=>{setTimeout(()=>{l&&(n(u,i),a())},400)}).catch(()=>{}),()=>{l=!1}},_e=({end:e,onSettle:r,start:n,tasks:a})=>{const{exit:l}=$(),[i,u]=x(()=>a.map(()=>"pending"));L(()=>Ye(a,u,r,l),[l,r,a]);const s=i.length>0&&i.every(f=>f==="done");return c(d,{flexDirection:"column",children:[s?c(d,{children:[t(o,{bold:!0,color:"green",children:`${ne}✔`}),t(o,{bold:!0,color:"green",children:` ${e}`})]}):t(ie,{label:n}),a.map((f,g)=>t(Ue,{label:f.label,status:i[g]??"pending"},f.label))]})},fr=async(e,r)=>{if(!m()){const l=[];for(const i of e)l.push(await i.run());return l}let n=[],a;if(await G(t(_e,{end:r.end,onSettle:(l,i)=>{n=l,a=i},start:r.start,tasks:e})),a!==void 0)throw z(a);return n},Be=async(e,r)=>{const n=[];let a;for(const[l,i]of e.entries()){r(l);try{n.push(await i.task())}catch(u){a=u;break}}return{failure:a,values:n}},Xe=({badge:e,done:r,onSettle:n,steps:a})=>{const{exit:l}=$(),[i,u]=x(0),[s,f]=x(!1);return L(()=>{let g=!0,C;return Be(a,p=>{g&&u(p)}).then(({failure:p,values:v})=>{if(g){if(p!==void 0){n({error:p,ok:!1}),l();return}f(!0),C=setTimeout(()=>{g&&(n({ok:!0,values:v}),l())},400)}}).catch(()=>{}),()=>{g=!1,C!==void 0&&clearTimeout(C)}},[l,n,a]),s?c(d,{children:[t(I,{spec:e}),t(o,{bold:!0,children:` ${r}`})]}):t(ie,{label:a[i]?.running??""})},hr=async(e,r,n)=>{if(!m()){const l=[];for(const i of r)l.push(await i.task());return l}let a;if(await G(t(Xe,{badge:e,done:n,onSettle:l=>{a=l},steps:r})),a===void 0)throw new Z;if(!a.ok)throw z(a.error);return a.values};export{ar as $,nr as B,tr as C,or as H,lr as I,ir as M,fr as Q,cr as U,ur as W,dr as X,sr as Y,rr as h,Se as i,hr as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{findWranglerFile as t,readWranglerJsonc as o}from"@lunora/config";const i=r=>{const e=t(r);if(!e)return;const{parsed:n}=o(e);return typeof n?.name=="string"&&n.name.length>0?n.name:void 0};export{i as d};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{execFile as c}from"node:child_process";import{M as d,P as i}from"./detect-package-manager-B2eIuAiP.mjs";const m=r=>r?typeof r.code=="number"?r.code:1:0,l=(r,t,e)=>new Promise(n=>{c(r,[...t],{cwd:e},(o,s,a)=>{n({code:m(o),stderr:a,stdout:s})})}),p=r=>{let t;try{t=JSON.parse(r)}catch{return}return Array.isArray(t)?[...t.map(e=>e!==null&&typeof e=="object"?e.name:void 0).filter(e=>typeof e=="string"&&e.length>0)].toSorted((e,n)=>e.localeCompare(n)):void 0},y=async r=>{const t=["secret","list","--format","json"];r.env!==void 0&&t.push("--env",r.env),r.temporary&&t.push("--temporary");const{args:e,command:n}=d(i(r.cwd),"wrangler",t),o=await(r.runner??l)(n,e,r.cwd);if(o.code!==0)return{error:o.stderr.trim()||`wrangler secret list exited ${String(o.code)}`,names:[],ok:!1};const s=p(o.stdout);return s===void 0?{error:"could not parse `wrangler secret list --format json` output",names:[],ok:!1}:{names:s,ok:!0}};export{y as f};
|
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.110",
|
|
4
4
|
"description": "The Lunora CLI: init, dev, deploy, codegen, run, reset, and migrate commands",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agent-skills",
|
|
@@ -51,23 +51,28 @@
|
|
|
51
51
|
"access": "public"
|
|
52
52
|
},
|
|
53
53
|
"dependencies": {
|
|
54
|
-
"@bomb.sh/tab": "0.0.
|
|
55
|
-
"@lunora/
|
|
56
|
-
"@lunora/
|
|
57
|
-
"@lunora/
|
|
58
|
-
"@lunora/
|
|
59
|
-
"@lunora/
|
|
60
|
-
"@
|
|
61
|
-
"@
|
|
62
|
-
"@
|
|
63
|
-
"@visulima/
|
|
64
|
-
"@visulima/
|
|
65
|
-
"@visulima/
|
|
54
|
+
"@bomb.sh/tab": "0.0.21",
|
|
55
|
+
"@lunora/bindings": "1.0.0-alpha.11",
|
|
56
|
+
"@lunora/codegen": "1.0.0-alpha.63",
|
|
57
|
+
"@lunora/config": "1.0.0-alpha.89",
|
|
58
|
+
"@lunora/container": "1.0.0-alpha.16",
|
|
59
|
+
"@lunora/d1": "1.0.0-alpha.45",
|
|
60
|
+
"@lunora/errors": "1.0.0-alpha.8",
|
|
61
|
+
"@lunora/runtime": "1.0.0-alpha.40",
|
|
62
|
+
"@lunora/seed": "1.0.0-alpha.38",
|
|
63
|
+
"@visulima/cerebro": "3.0.0",
|
|
64
|
+
"@visulima/error": "6.0.0",
|
|
65
|
+
"@visulima/fs": "5.0.5",
|
|
66
|
+
"@visulima/package": "5.0.5",
|
|
67
|
+
"@visulima/pail": "4.0.0",
|
|
68
|
+
"@visulima/path": "3.0.0",
|
|
69
|
+
"@visulima/spinner": "1.0.0",
|
|
70
|
+
"@visulima/tui": "1.0.5",
|
|
66
71
|
"cfonts": "^3.3.1",
|
|
67
|
-
"giget": "3.3.
|
|
72
|
+
"giget": "3.3.1",
|
|
68
73
|
"jsonc-parser": "^3.3.1",
|
|
69
|
-
"magic-string": "^
|
|
70
|
-
"react": "^19.2.
|
|
74
|
+
"magic-string": "^1.1.0",
|
|
75
|
+
"react": "^19.2.8",
|
|
71
76
|
"react-reconciler": "^0.33.0",
|
|
72
77
|
"ts-morph": "^28.0.0"
|
|
73
78
|
},
|
package/skills/README.md
CHANGED
|
@@ -9,21 +9,35 @@ framework correctly. They ship inside `@lunora/cli` and are discovered by the
|
|
|
9
9
|
Each skill is a `SKILL.md` with YAML frontmatter (`name`, `description`) in its
|
|
10
10
|
own directory:
|
|
11
11
|
|
|
12
|
-
| Skill
|
|
13
|
-
|
|
|
14
|
-
| `lunora`
|
|
15
|
-
| `lunora-quickstart`
|
|
16
|
-
| `lunora-functions`
|
|
17
|
-
| `lunora-realtime`
|
|
18
|
-
| `lunora-setup-auth`
|
|
19
|
-
| `lunora-setup-mail`
|
|
20
|
-
| `lunora-setup-storage`
|
|
21
|
-
| `lunora-setup-scheduler`
|
|
22
|
-
| `lunora-
|
|
23
|
-
| `lunora-
|
|
24
|
-
| `lunora-
|
|
25
|
-
| `lunora-
|
|
12
|
+
| Skill | Use for |
|
|
13
|
+
| -------------------------------- | ---------------------------------------------------------------------------- |
|
|
14
|
+
| `lunora` | Router — start here, then switch to the matching skill below. |
|
|
15
|
+
| `lunora-quickstart` | `lunora init` / adding Lunora to an app + first round-trip. |
|
|
16
|
+
| `lunora-functions` | Core authoring rules — schema, validators, query/mutation/action, `ctx.db`. |
|
|
17
|
+
| `lunora-realtime` | Client reactivity — live hooks, optimistic updates, `@lunora/db`. |
|
|
18
|
+
| `lunora-setup-auth` | Authentication via `lunora registry add auth` (+ providers). |
|
|
19
|
+
| `lunora-setup-mail` | Transactional email via `lunora registry add mail` — `sendEmail` actions. |
|
|
20
|
+
| `lunora-setup-storage` | R2 file storage via `lunora registry add storage` — signed upload/download. |
|
|
21
|
+
| `lunora-setup-scheduler` | Deferred (`ctx.scheduler`) + cron jobs (`lunora registry add crons`). |
|
|
22
|
+
| `lunora-setup-hyperdrive` | Existing Postgres/MySQL from an action — `ctx.sql`, non-reactive. |
|
|
23
|
+
| `lunora-setup-hyperdrive-global` | Postgres/MySQL as a reactive `.global()` backend; D1 → Hyperdrive migration. |
|
|
24
|
+
| `lunora-create-package` | Building a reusable registry item or `@lunora/*` package. |
|
|
25
|
+
| `lunora-migration-helper` | Schema/data migrations, `.global()` DDL flow, the drift gate. |
|
|
26
|
+
| `lunora-deploy` | Deploying to Cloudflare — wrangler bindings, secrets, the gate. |
|
|
27
|
+
| `lunora-performance-audit` | `lunora insights`, scans, indexes, OCC conflicts, sharding/`.global()`. |
|
|
26
28
|
|
|
27
29
|
These are mirrored into `.agents/skills/` and `.claude/skills/` (via symlinks)
|
|
28
30
|
so agents working inside this repo pick them up directly. The source of truth
|
|
29
31
|
lives here so the published `@lunora/cli` tarball carries them.
|
|
32
|
+
|
|
33
|
+
**Adding a skill?** Create it here, then mirror it through both hops:
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
ln -s ../../packages/cli/skills/<name> .agents/skills/<name>
|
|
37
|
+
ln -s ../../.agents/skills/<name> .claude/skills/<name>
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
`scripts/check-skill-mirrors.js` (run on every `pnpm install`) fails if a mirror
|
|
41
|
+
is missing, dangling, or has become a real directory — a copied directory keeps
|
|
42
|
+
resolving while it silently drifts from the source, so it is treated as an
|
|
43
|
+
error rather than a warning.
|
package/skills/lunora/SKILL.md
CHANGED
|
@@ -14,8 +14,9 @@ Lunora exposes a Convex-style functional API (`defineSchema`, `query`,
|
|
|
14
14
|
`mutation`, `action`) on top of Cloudflare Workers and Durable Objects. State
|
|
15
15
|
lives in a per-app `ShardDO` (SQLite, OCC, hibernated WebSocket subscriptions)
|
|
16
16
|
by default; `.shardBy(key)` partitions it across many DOs and `.global()`
|
|
17
|
-
replicates a table to D1
|
|
18
|
-
drives codegen and end-to-end
|
|
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.
|
|
19
20
|
|
|
20
21
|
If a more specific Lunora skill clearly matches the request, use that instead.
|
|
21
22
|
|
|
@@ -47,12 +48,13 @@ After codegen is green, use the most specific Lunora skill for the task:
|
|
|
47
48
|
- Wiring live data into a client (hooks, optimistic updates): `lunora-realtime`
|
|
48
49
|
- Authentication setup (email/password, OAuth, magic link, OTP):
|
|
49
50
|
`lunora-setup-auth`
|
|
50
|
-
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
51
|
+
- Transactional email: `lunora-setup-mail`
|
|
52
|
+
- R2 file storage (signed upload/download): `lunora-setup-storage`
|
|
53
|
+
- Deferred work (`ctx.scheduler`) and cron jobs: `lunora-setup-scheduler`
|
|
54
|
+
- Querying an **existing** Postgres/MySQL database from an action (`ctx.sql`,
|
|
55
|
+
non-reactive): `lunora-setup-hyperdrive`
|
|
56
|
+
- Using Postgres/MySQL as a **reactive `.global()` backend**, or migrating a D1
|
|
57
|
+
`.global()` dataset onto it: `lunora-setup-hyperdrive-global`
|
|
56
58
|
- Building a reusable capability — a registry item or an `@lunora/*` package:
|
|
57
59
|
`lunora-create-package`
|
|
58
60
|
- Planning or running a schema/data migration: `lunora-migration-helper`
|
|
@@ -64,6 +66,41 @@ After codegen is green, use the most specific Lunora skill for the task:
|
|
|
64
66
|
If one of those clearly matches the user's goal, switch to it instead of staying
|
|
65
67
|
in this skill.
|
|
66
68
|
|
|
69
|
+
## Capabilities Without a Dedicated Skill
|
|
70
|
+
|
|
71
|
+
Most other capabilities install as a **registry item** — `lunora registry add
|
|
72
|
+
<item>` scaffolds the `lunora/` glue, wrangler bindings, and env vars, then
|
|
73
|
+
prints post-install steps. Browse with `lunora registry list`; preview with
|
|
74
|
+
`lunora registry view <item>`. Read the installed item's README, and the
|
|
75
|
+
package's `docs/` for the API.
|
|
76
|
+
|
|
77
|
+
| Goal | Install / package |
|
|
78
|
+
| --------------------------------------------- | ------------------------------------------------------------ |
|
|
79
|
+
| Background jobs on Cloudflare Queues | `registry add queue` → `@lunora/queue` (`ctx.queues`) |
|
|
80
|
+
| Durable multi-step workflows | `registry add workflow` → `@lunora/workflow` (`ctx.runStep`) |
|
|
81
|
+
| Durable AI agents (tool loops, HITL, memory) | `@lunora/agent` (`defineAgent`) |
|
|
82
|
+
| Workers AI / RAG | `registry add ai` → `@lunora/ai` (`ctx.ai`, `defineRag`) |
|
|
83
|
+
| Feature flags (OpenFeature) | `registry add flags` → `@lunora/flags` (`ctx.flags`) |
|
|
84
|
+
| Payments (Stripe / Polar) | `registry add payment` → `@lunora/payment` |
|
|
85
|
+
| Rate limiting | `registry add ratelimit` → `@lunora/ratelimit` |
|
|
86
|
+
| Headless browser (action-only) | `registry add browser` → `@lunora/browser` (`ctx.browser`) |
|
|
87
|
+
| Cloudflare Containers | `@lunora/container` (`defineContainer`, `ctx.containers`) |
|
|
88
|
+
| Presence / who's-here | `registry add presence` |
|
|
89
|
+
| Cloudflare Access (Zero Trust) identity | `registry add cloudflare-access` |
|
|
90
|
+
| Backup / restore | `registry add backup` |
|
|
91
|
+
| Testing (in-memory harness, agent doubles) | `@lunora/testing` (`lunoraTest`) |
|
|
92
|
+
| Deterministic seed data | `@lunora/seed` + `lunora seed` |
|
|
93
|
+
| Local-first replica / offline mirror | `@lunora/replica` |
|
|
94
|
+
| Exposing the deployment to AI agents over MCP | `@lunora/mcp` |
|
|
95
|
+
|
|
96
|
+
Scaffolding inside this repo uses `vis generate lunora-<kind>` — `query`,
|
|
97
|
+
`mutation`, `action`, `http-route`, `table`, `cron`, `container`, `workflow`,
|
|
98
|
+
`queue`, `step`, `agent`, `flags`, `collections`, `package` (`vis generate
|
|
99
|
+
--list` for the full set). Most take a name: **always** pass it as
|
|
100
|
+
`--name=value`, since vis parses a space-separated `--name foo` as `--name=true`
|
|
101
|
+
plus a stray positional. `lunora-flags` and `lunora-collections` are singletons
|
|
102
|
+
and take no name.
|
|
103
|
+
|
|
67
104
|
## Core Mental Model
|
|
68
105
|
|
|
69
106
|
- **Functions** live in `lunora/*.ts` and are one of `query` (reactive read),
|
|
@@ -75,7 +112,9 @@ in this skill.
|
|
|
75
112
|
- **Reads go through indexes.** Prefer `ctx.db.query("t").withIndex(...)` over
|
|
76
113
|
`.filter(...)`; declare the index with `.index("by_x", ["x"])`.
|
|
77
114
|
- **Clients** subscribe over WebSocket. `useQuery`/`useMutation` (React, Vue,
|
|
78
|
-
Solid, Svelte) re-render the moment a
|
|
115
|
+
Solid, Svelte, React Native; signals in Angular) re-render the moment a
|
|
116
|
+
mutation changes the queried rows. Subscriptions run under the socket's
|
|
117
|
+
verified identity, so `rls()` / `ctx.auth` apply to live updates too.
|
|
79
118
|
|
|
80
119
|
## When Not to Use
|
|
81
120
|
|
|
@@ -150,9 +150,44 @@ Declare the index and constrain with `.withIndex`.
|
|
|
150
150
|
|
|
151
151
|
## Other `ctx` capabilities
|
|
152
152
|
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
153
|
+
Always available:
|
|
154
|
+
|
|
155
|
+
- `ctx.auth` — the resolved session (`ctx.auth.userId`).
|
|
156
|
+
- `ctx.scheduler` — `runAfter` / `runAt` for deferred work.
|
|
157
|
+
- `ctx.secrets` — Cloudflare Secrets Store.
|
|
158
|
+
- `ctx.span` / `ctx.trace` — the current span and a scoped tracing helper for
|
|
159
|
+
wide events.
|
|
160
|
+
|
|
161
|
+
Added by their package when wired. **A dependency in `package.json` is not
|
|
162
|
+
enough** — codegen scans the `lunora/` source set and flips a capability on only
|
|
163
|
+
when a file there imports the `@lunora/*` package or reads its `ctx.*` helper.
|
|
164
|
+
So write the call first, then run `lunora codegen` to surface the typed context:
|
|
165
|
+
|
|
166
|
+
| `ctx.*` | Package |
|
|
167
|
+
| ----------------------------------------------------------------------------------------- | ----------------------------- |
|
|
168
|
+
| `ctx.storage` | `@lunora/storage` (R2) |
|
|
169
|
+
| `ctx.ai` | `@lunora/ai` (Workers AI) |
|
|
170
|
+
| `ctx.flags` | `@lunora/flags` (OpenFeature) |
|
|
171
|
+
| `ctx.queues.<name>` | `@lunora/queue` |
|
|
172
|
+
| `ctx.workflows` / `ctx.runStep` | `@lunora/workflow` |
|
|
173
|
+
| `ctx.containers` | `@lunora/container` |
|
|
174
|
+
| `ctx.browser` (action-only) | `@lunora/browser` |
|
|
175
|
+
| `ctx.sql` (action-only) | `@lunora/hyperdrive` |
|
|
176
|
+
| `ctx.kv` / `ctx.images` / `ctx.analytics` / `ctx.pipelines` / `ctx.vectors` / `ctx.r2sql` | `@lunora/bindings` subpaths |
|
|
177
|
+
|
|
178
|
+
Two exceptions to the usage scan, and one extra requirement:
|
|
179
|
+
|
|
180
|
+
- **`ctx.flags` gates on a declaration file**, not on usage — codegen wires it
|
|
181
|
+
only when `lunora/flags.ts` exists (`vis generate lunora-flags` creates it).
|
|
182
|
+
`ctx.notify` / `ctx.push` work the same way via `lunora/notify.ts`.
|
|
183
|
+
- **`ctx.sql` also needs the real resource.** Codegen types the field, but the
|
|
184
|
+
connection needs a `HYPERDRIVE` binding (`wrangler hyperdrive create`) and an
|
|
185
|
+
explicit `createHyperdrive(ctx.env.HYPERDRIVE)` + driver adapter in the
|
|
186
|
+
action — see `lunora-setup-hyperdrive`. Bindings codegen can provision on its
|
|
187
|
+
own (e.g. `BROWSER` for `ctx.browser`) need no manual wrangler step.
|
|
188
|
+
|
|
189
|
+
`ctx.browser` and `ctx.sql` are **action-only** by design — they are
|
|
190
|
+
non-deterministic and would break query reactivity and mutation replay.
|
|
156
191
|
|
|
157
192
|
## HTTP endpoints
|
|
158
193
|
|
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
name: lunora-migration-helper
|
|
3
3
|
description: Plans Lunora schema and data migrations with widen-migrate-narrow. Use for
|
|
4
4
|
breaking schema changes, backfills, table reshaping, online data migrations
|
|
5
|
-
(`defineMigration` + `lunora migrate up`), the `.global()` D1
|
|
5
|
+
(`defineMigration` + `lunora migrate up`), the `.global()` D1 / Hyperdrive
|
|
6
|
+
structural flows, and the
|
|
6
7
|
pre-deploy schema-drift gate.
|
|
7
8
|
---
|
|
8
9
|
|
|
@@ -15,7 +16,7 @@ Safely change a Lunora schema and migrate data when making breaking changes.
|
|
|
15
16
|
- Adding required fields to existing tables.
|
|
16
17
|
- Changing field types or structure.
|
|
17
18
|
- Splitting/merging tables, renaming/removing fields.
|
|
18
|
-
- Reshaping `.global()` (D1-backed)
|
|
19
|
+
- Reshaping `.global()` tables (D1- or Hyperdrive-backed).
|
|
19
20
|
|
|
20
21
|
## When Not to Use
|
|
21
22
|
|
|
@@ -23,21 +24,35 @@ Safely change a Lunora schema and migrate data when making breaking changes.
|
|
|
23
24
|
- Adding **optional** fields that need no backfill.
|
|
24
25
|
- Adding new tables or indexes with no correctness concern.
|
|
25
26
|
|
|
26
|
-
##
|
|
27
|
+
## Storage Layers — Know Which You Are Migrating
|
|
27
28
|
|
|
28
|
-
Lunora tables live in one of
|
|
29
|
+
Lunora tables live in one of three backends, and they migrate differently:
|
|
29
30
|
|
|
30
31
|
- **ShardDO SQLite (default `root`, and `.shardBy(key)` tables).** State lives in
|
|
31
32
|
the per-app / per-shard Durable Object. Data is reshaped with **online data
|
|
32
33
|
migrations** — `defineMigration` declarations run by `lunora migrate up`,
|
|
33
34
|
resumable per shard.
|
|
34
|
-
- **`.global()`
|
|
35
|
-
|
|
36
|
-
applied by `@lunora/d1`'s runner at deploy time.
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
35
|
+
- **`.global()` on D1 (the default global backend).** Replicated to D1 for
|
|
36
|
+
cross-region reads. Structural DDL gets versioned **SQL migrations** via
|
|
37
|
+
`lunora migrate generate`, applied by `@lunora/d1`'s runner at deploy time.
|
|
38
|
+
- **`.global({ backend: "hyperdrive" })` on Postgres/MySQL.** The same reactive
|
|
39
|
+
`.global()` contract served over Cloudflare Hyperdrive. Structural DDL works
|
|
40
|
+
differently here: tables **auto-provision on first use** — the runtime applies
|
|
41
|
+
the DDL through the dialect — so there is no `lunora migrate generate` step
|
|
42
|
+
and no versioned SQL file to commit. See `lunora-setup-hyperdrive-global`.
|
|
43
|
+
|
|
44
|
+
So: a breaking structural change to a **D1-backed** `.global()` table needs a
|
|
45
|
+
generated SQL migration; the Hyperdrive-backed equivalent provisions itself. A
|
|
46
|
+
data backfill (any layer) is always an online `defineMigration`. All three
|
|
47
|
+
follow the same **widen → migrate → narrow** discipline — check the table's
|
|
48
|
+
backend before assuming which structural path applies.
|
|
49
|
+
|
|
50
|
+
> **Moving an existing dataset between global backends.** To move a `.global()`
|
|
51
|
+
> dataset from D1 onto Hyperdrive, use
|
|
52
|
+
> `lunora migrate d1-to-hyperdrive --from-url <d1-worker> --to-url <hd-worker>`
|
|
53
|
+
> (`--tables` scopes it; `--out` keeps the intermediate NDJSON dump). This is a
|
|
54
|
+
> backend move, not a schema change — the widen → migrate → narrow discipline
|
|
55
|
+
> below still governs any reshaping you do on either side of it.
|
|
41
56
|
|
|
42
57
|
## Key Principle: Widen, Migrate, Narrow
|
|
43
58
|
|
|
@@ -129,7 +144,10 @@ lunora migrate down backfill-display-name # revert (if `down` defined)
|
|
|
129
144
|
Useful flags: `--batch-size <n>`, `--steps <n>` (cap batches this run), and
|
|
130
145
|
`--prod --url <worker> --yes` to target production (with `LUNORA_ADMIN_TOKEN`).
|
|
131
146
|
|
|
132
|
-
## `.global()`
|
|
147
|
+
## `.global()` on D1 — Structural Migration Flow
|
|
148
|
+
|
|
149
|
+
This flow is **D1-specific**. Hyperdrive-backed globals auto-provision their DDL
|
|
150
|
+
at runtime and skip it entirely.
|
|
133
151
|
|
|
134
152
|
```bash
|
|
135
153
|
# 1. Edit lunora/schema.ts (widen: add the optional new field to the .global() table).
|
|
@@ -146,8 +164,8 @@ lunora deploy
|
|
|
146
164
|
```
|
|
147
165
|
|
|
148
166
|
`lunora migrate generate` only considers `.global()` tables (root/sharded tables
|
|
149
|
-
|
|
150
|
-
backfill data with an online migration between them.
|
|
167
|
+
live in ShardDO SQLite, not D1). Run it after each schema edit in the widen and
|
|
168
|
+
narrow steps; backfill data with an online migration between them.
|
|
151
169
|
|
|
152
170
|
## The Schema-Drift Gate
|
|
153
171
|
|
|
@@ -176,9 +194,10 @@ add the migration — not to bypass it.
|
|
|
176
194
|
transform before it touches real rows.
|
|
177
195
|
5. **Deleting a field prematurely.** Deprecate with `v.optional` + a comment;
|
|
178
196
|
delete only once nothing references it.
|
|
179
|
-
6. **Migrating the wrong layer.** A `.global()` structural change needs
|
|
180
|
-
migrate generate` (SQL); a
|
|
181
|
-
table's `.global()` /
|
|
197
|
+
6. **Migrating the wrong layer.** A D1-backed `.global()` structural change needs
|
|
198
|
+
`lunora migrate generate` (SQL); a Hyperdrive-backed one auto-provisions; a
|
|
199
|
+
data backfill needs a `defineMigration`. Check the table's `.global()` /
|
|
200
|
+
`.shardBy()` modifier — and, for `.global()`, its `backend` — first.
|
|
182
201
|
|
|
183
202
|
## Checklist
|
|
184
203
|
|