UNPKG

@lunora/cli

Version:

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

4 lines (3 loc) • 6.37 kB
import{existsSync as R,readdirSync as E,readFileSync as O}from"node:fs";import{join as v}from"@visulima/path";import{r as A,t as I}from"./admin-token-VdUnvnKW.mjs";import{r as T,a as k}from"./admin-url-DJB8P6Jh.mjs";import{EXIT_CODE as u,exitCodeForStatus as f}from"./EXIT_CODE-DQVhSE-1.mjs";const w="/_lunora/admin/sql-migrations",F=new Set(["applied","baselined","ran"]),N=new Set(["applied","baselined","changed","pending","ran"]),q=e=>{const r=v(e,"lunora","migrations");return R(r)?E(r,{withFileTypes:!0}).filter(t=>t.isFile()&&t.name.endsWith(".sql")).map(t=>t.name).toSorted((t,n)=>+(t>n)-+(t<n)).map(t=>({name:t,sql:O(v(r,t),"utf8")})):[]},L=(e,r,t)=>{const n=r.skipped.length>0?`, ${String(r.skipped.length)} already in place`:"";if(e.info(`${r.state.padEnd(9)} ${r.name} (${String(r.statements.length)} statement(s)${n})`),t)for(const a of r.statements)e.info(` ${a.split(` `).join(` `)}`);(r.rootOnly?.length??0)>0&&r.state==="pending"&&e.warn(`${r.name} runs statements a migrations-scoped token may not run; it needs the root admin token.`),r.destructive.length>0&&r.state==="pending"&&e.warn(`${r.name} drops, renames, truncates or replaces data. It runs only with --allow-destructive.`)},D=async e=>{const r=await e.text();try{return JSON.parse(r)}catch{return r}},m=e=>{const r=e?.error?.code;return typeof r=="string"?r:void 0},_=(e,r)=>e?"plan":r?"baseline":"apply",Q=(e,r,t)=>{const n=T(e.url,e.logger,e.cwd);if(n===void 0)return{code:u.USAGE,files:[]};const{token:a}=A({cwd:r,token:e.token,url:n});if(!a){const o="admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)";return e.logger.error(o),{code:u.AUTH,error:o,files:[]}}if(!t&&I({prod:e.prod,url:n})&&!e.yes){const o=`migrate apply runs the SQL migrations against ${n}, which is not local. Re-run with --yes to confirm.`;return e.logger.error(o),{code:u.USAGE,error:o,files:[]}}return{baseUrl:n,token:a}},g=e=>Array.isArray(e)&&e.every(r=>typeof r=="string"),M=e=>{if(typeof e!="object"||e===null)return!1;const r=e;return typeof r.name=="string"&&typeof r.state=="string"&&N.has(r.state)&&g(r.destructive)&&g(r.skipped)&&g(r.statements)},C=e=>{const r=e?.refused;return Array.isArray(r)&&r.every(t=>typeof t=="string")?r:[]},x=(e,r)=>{const t=e?.files;if(!Array.isArray(t)||!t.every(M))return;const n=t.map(l=>l.name),a=new Set(n),o=r.map(l=>l.name);return a.size===n.length&&n.length===o.length&&o.every(l=>a.has(l))?t:void 0},G=(e,r)=>{const t=r===void 0?e.length-1:e.findIndex(n=>n.name===r);return new Set(e.slice(0,t+1).map(n=>n.name))},i=(e,r,t)=>(e.error(r),{code:t,error:r,files:[]}),P=(e,r)=>{const{baselineThrough:t}=e;if(e.baseline===!0&&t!==void 0)return i(e.logger,"pass either --baseline or --baseline-through, not both",u.USAGE);if(t!==void 0&&!r.some(n=>n.name===t))return i(e.logger,`--baseline-through ${t} names no file under lunora/migrations/`,u.USAGE)},j=(e,r,t,n)=>{if(e.status===404)return i(n,`the worker at ${t.baseUrl} has no ${w} route, so it predates \`migrate apply\`. Deploy a version of lunora that includes it, then re-run.`,u.NOT_FOUND);if(e.status===413)return i(n,`${t.baseUrl} refused the request: the SQL files in lunora/migrations/ together exceed the 8 MiB one request can carry. Split the files across deploys.`,f(e.status));if(e.status===400&&m(r)==="SQL_MIGRATIONS_NOT_CONFIGURED")return n.warn(`${t.baseUrl} has no D1 global plane, so the SQL files in lunora/migrations/ do not run there. Skipping them.`),{code:0,files:[]};if(m(r)==="MISCONFIGURED")return i(n,`${t.baseUrl} has a D1 binding but its worker options have no applySqlMigrations, so the SQL files in lunora/migrations/ cannot run. Pass applySqlMigrations built from applySqlMigrationFiles in @lunora/d1, then redeploy.`,f(e.status));if(m(r)==="ADMIN_SCOPE_REQUIRED")return i(n,`${t.baseUrl} refused migrate apply: this token has no migrations scope. Mint one with \`lunora admin-token create <name> --scope migrations\` and pass it as --token.`,f(e.status));if(m(r)==="MIGRATION_ROOT_REQUIRED")return i(n,`${t.baseUrl} refused migrate apply: a file runs statements that a migrations-scoped token may not run (a DROP, a row write, a trigger or a UNIQUE index). Run it with the root admin token; the dry run lists the statements.`,f(e.status));if(!e.ok)return n.info(JSON.stringify(r,void 0,2)),i(n,`migrate apply was refused by ${t.baseUrl} (HTTP ${String(e.status)}) — see the response above`,f(e.status))},B=(e,r,t)=>{if(t.dryRun){const s=e.filter(l=>l.state==="changed").map(l=>l.name);return s.length>0?i(t.logger,`${String(s.length)} SQL file(s) changed after they were applied: ${s.join(", ")}`,u.CONFLICT):t.refused.length>0?i(t.logger,`${String(t.refused.length)} SQL file(s) would be refused when applied: ${t.refused.join(", ")}. See the statements listed above.`,u.CONFLICT):void 0}const n=G(r,t.baselineThrough),a=e.filter(s=>n.has(s.name)&&!F.has(s.state)).map(s=>s.name);if(a.length===0)return;const o=a.length===1?"was":"were";return i(t.logger,`${a.join(", ")} ${o} not recorded by ${t.baseUrl}, so the run did not finish`,u.FAILURE)},V=async e=>{const r=e.cwd??process.cwd(),t=e.dryRun===!0,n=e.baseline===!0,{baselineThrough:a}=e,o=n||a!==void 0;if(e.prod&&e.url===void 0)return i(e.logger,"--prod requires an explicit --url (refusing to migrate the implicit localhost worker)",u.USAGE);const s=q(r),l=P(e,s);if(l!==void 0)return l;if(s.length===0)return e.logger.info("no SQL migration files under lunora/migrations/ — nothing to apply"),{code:0,files:[]};const d=Q(e,r,t);if("code"in d)return d;const p=`${d.baseUrl}${w}`,$=e.fetchImpl??k;e.logger.info(`POST ${p} -> ${_(t,o)} ${String(s.length)} SQL file(s)`);const y=await $(p,{body:JSON.stringify({baseline:n,baselineThrough:a,confirmDestructive:e.allowDestructive===!0,dryRun:t,files:s}),headers:{authorization:`Bearer ${d.token}`,"content-type":"application/json"},method:"POST"}),h=await D(y),S=j(y,h,d,e.logger);if(S!==void 0)return S;const c=x(h,s);if(c===void 0)return i(e.logger,`${d.baseUrl} answered ${t?"the plan":"the apply"} without a valid result for every SQL file — it may not support \`migrate apply\`, or a proxy answered for it`,u.FAILURE);for(const U of c)L(e.logger,U,t);const b=B(c,s,{baselineThrough:a,baseUrl:d.baseUrl,dryRun:t,logger:e.logger,refused:C(h)});return b!==void 0?{...b,files:c}:{code:0,files:c}};export{V as r};