UNPKG

@lunora/cli

Version:

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

14 lines (8 loc) • 15.4 kB
import{existsSync as B,readFileSync as D,writeFileSync as V}from"node:fs";import{parseSchemaSnapshot as U,SchemaSnapshotParseError as W,evaluateSchemaDrift as K,serializeSchemaSnapshot as G}from"@lunora/codegen";import{decodeWire as v}from"@lunora/wire";import{f as O}from"./export-rows-EzdNDYpa.mjs";const J=new Set(["addedRequiredField","changedFieldKind","changedFieldShape","fieldOptionalToRequired","removedField"]),_=e=>e.table!==void 0&&(e.uniqueOn!==void 0||e.field!==void 0&&J.has(e.type)),L=10,M=e=>e.kind==="id"||e.kind==="storage"||[e.inner,e.keyType,e.valueType,...e.members??[],...Object.values(e.shape??{})].some(t=>t!==void 0&&M(t)),f=e=>e===null?"null":Array.isArray(e)?"array":e instanceof ArrayBuffer||ArrayBuffer.isView(e)?"bytes":typeof e,S=e=>f(e)==="object",q=/^-?\d+n$/u,z=/\$\{/u,N=e=>{const t=e.trim(),r=t[0];if(t.length>=2&&(r==="'"||r==="`")&&t.endsWith(r)){const n=t.slice(1,-1);return n.includes("\\")||z.test(n)||r==="'"&&n.includes("'")?void 0:{value:n}}if(q.test(t))return{value:BigInt(t.slice(0,-1))};try{return{value:JSON.parse(t)}}catch{return}},p=e=>typeof e=="number"&&Number.isFinite(e),A=(e,t)=>p(e)&&Math.abs(e)<=t,x={any:()=>!0,bigint:e=>typeof e=="bigint",boolean:e=>typeof e=="boolean",bytes:e=>e instanceof ArrayBuffer||ArrayBuffer.isView(e),date:p,geoPoint:e=>S(e)&&A(e.lat,90)&&A(e.lng,180),id:e=>typeof e=="string",null:e=>e===null,number:p,storage:e=>typeof e=="string",string:e=>typeof e=="string",timestamp:p},$=(e,t,r)=>{if(t!==void 0)for(const[n,o]of e){const s=m(o,t,r(n));if(s!==void 0)return s}},F={array:(e,t,r)=>Array.isArray(e)?$(e.map((n,o)=>[String(o),n]),t.inner,n=>`${r}[${n}]`):[r,`expected array, found ${f(e)}`],literal:(e,t,r)=>e===N(t.literalValue??"")?.value?void 0:[r,`expected the literal ${t.literalValue??"?"}, found a different ${f(e)}`],object:(e,t,r)=>S(e)?Q(e,t.shape??{},`${r}.`):[r,`expected object, found ${f(e)}`],record:(e,t,r)=>S(e)?$(Object.keys(e).map(n=>[n,n]),t.keyType,()=>`${r}[*]`)??$(Object.entries(e),t.valueType,()=>`${r}[*]`):[r,`expected record, found ${f(e)}`],union:(e,t,r)=>(t.members??[]).some(n=>m(e,n,r)===void 0)?void 0:[r,`matches no member of the union (found ${f(e)})`]},Y=(e,t,r,n)=>n(e)?typeof e=="string"&&t.stringMaxLength!==void 0&&e.length>t.stringMaxLength?[r,`longer than ${String(t.stringMaxLength)} characters`]:void 0:[r,`expected ${t.kind}, found ${f(e)}`],m=(e,t,r)=>{if(e===null&&t.column?.notNull===!1)return;if(t.kind==="optional")return e===void 0||t.inner===void 0?void 0:m(e,t.inner,r);const n=x[t.kind];if(e===void 0)return n?.(e)===!0?void 0:[r,"required, but missing"];if(n!==void 0)return Y(e,t,r,n);const o=F[t.kind];return o===void 0?[r,`has a \`${t.kind}\` validator this check does not know`]:o(e,t,r)},Q=(e,t,r)=>{if(Object.keys(e).some(n=>!Object.hasOwn(t,n)))return[`${r}*`,"holds a property the schema does not declare"];for(const[n,o]of Object.entries(t)){const s=m(e[n],o,`${r}${n}`);if(s!==void 0)return s}},j=(e,t)=>{if(e.sourceText!==void 0||e.unmodelledRefinement===!0||e.unresolvedShape===!0||e.hasRefinement===!0&&e.stringMaxLength===void 0)return`${t} has a validator or refinement that cannot be checked outside the worker`;if(e.kind==="literal"&&N(e.literalValue??"")===void 0)return`${t} is a \`v.literal()\` whose value is not a plain literal, so rows cannot be compared to it outside the worker`;if(e.kind==="from")return`${t} is a \`v.from()\` schema, which cannot be checked outside the worker`;if(e.kind!=="optional"&&x[e.kind]===void 0&&F[e.kind]===void 0)return`${t} has a \`${e.kind}\` validator this check does not know`;const r=[e.inner,e.keyType,e.valueType,...e.members??[],...Object.values(e.shape??{})];for(const n of r){const o=n===void 0?void 0:j(n,t);if(o!==void 0)return o}},X=(e,t,r,n)=>{const o=v(n[t]);return e.shardMode==="global"&&o===null&&r.kind==="optional"&&r.column?.notNull!==!1?void 0:o},Z=(e,t)=>{const r=o=>t[o]===void 0||e.table.shardMode==="global"&&t[o]===null,n=e.removed.find(o=>!r(o));if(n!==void 0)return[n,"is no longer declared, but the row still holds it"];for(const[o,s]of e.validated){const c=m(X(e.table,o,s,t),s,o);if(c!==void 0)return c}},E=e=>typeof e=="boolean"?e?"n:1":"n:0":typeof e=="number"||typeof e=="bigint"?`n:${e.toString()}`:typeof e=="string"?`s:${e}`:`j:${JSON.stringify(e)}`,ee=(e,t,r)=>{const n=typeof e.table.shardMode=="object"?E(v(t[e.table.shardMode.field])):"",o=typeof t._id=="string"?t._id:"(no _id)";for(const s of e.unique){const c=s.map(a=>v(t[a]));if(c.some(a=>a==null))continue;const d=JSON.stringify([e.table.name,s,n,c.map(a=>E(a))]),i=r.get(d);if(i===void 0)r.set(d,o);else return[s.join(" + "),i]}},te=(e,t)=>{if(t.length===0||t.some(r=>e.table.shape[r]===void 0))return`the unique constraint on ${e.table.name} names a field the current schema does not declare`;e.unique.push(t)},ne=(e,t)=>{if(t.uniqueOn!==void 0)return te(e,t.uniqueOn);const{field:r}=t;if(r===void 0)return`"${t.summary}" is not something stored rows can confirm`;const n=e.table.shape[r];if(t.type==="removedField"||n===void 0){e.removed.push(r);return}const o=(t.type==="changedFieldKind"||t.type==="changedFieldShape")&&M(n)?`${t.table}.${r} now references a different table or bucket, which a stored id cannot show`:j(n,`${t.table}.${r}`);return o===void 0&&e.validated.push([r,n]),o},re=(e,t)=>{const r=new Map;for(const n of e){if(!_(n))return{reason:`"${n.summary}" is not something stored rows can confirm`};const o=t.get(n.table);if(o===void 0)return{reason:`table ${n.table} is not in the current schema`};const s=r.get(n.table)??{removed:[],table:o,unique:[],validated:[]};r.set(n.table,s);const c=ne(s,n);if(c!==void 0)return{reason:c}}return{plans:r}},Te=async e=>{const t=re(e.changes,new Map(e.tables.map(i=>[i.name,i])));if("reason"in t)return{kind:"inconclusive",reason:t.reason};const{plans:r}=t;if(e.target===void 0)return{kind:"inconclusive",reason:"no deployed worker to read the stored rows from — pass --migrate-url (or record one with `lunora link`) and set LUNORA_ADMIN_TOKEN"};const n=[...r.keys()].toSorted((i,a)=>i.localeCompare(a)),o=[],s=new Map;let c=0,d=!1;try{await O(e.target,n,i=>{const a=r.get(i.table);if(a===void 0)return;c+=1;const u=ee(a,i.doc,s),h=u===void 0?Z(a,i.doc):[u[0],`duplicates ${u[1]}`];if(h!==void 0){if(o.length===L)return d=!0,!1;o.push({field:h[0],id:typeof i.doc._id=="string"?i.doc._id:"(no _id)",reason:h[1],table:i.table})}})}catch(i){return{kind:"inconclusive",reason:i instanceof Error?i.message:String(i)}}return o.length===0?{kind:"conforms",rows:c,tables:n}:{failures:o,kind:"fails",rows:c,truncated:d}},oe=e=>[`${String(e.failures.length)}${e.truncated?"+":""} stored row(s) do not fit the new schema${e.truncated?` (the first ${String(L)} shown)`:""}:`,...e.failures.map(t=>` - ${t.table} ${t.id}: ${t.field} ${t.reason}`)].join(` `),C=(e,t,r)=>{const n=e[t];return typeof n=="number"&&n<r},Oe=async e=>{const t=new Map;for(const n of e.changes)n.table!==void 0&&n.expiry!==void 0&&t.set(n.table,n.expiry);if(e.target===void 0)return"no deployed worker to read the stored rows from";const r=new Map([...t.keys()].map(n=>[n,0]));try{await O(e.target,[...t.keys()].toSorted((n,o)=>n.localeCompare(o)),n=>{const o=t.get(n.table);if(o===void 0||!C(n.doc,o.field,e.now-(o.after??0)))return;const{previous:s}=o;s!==void 0&&C(n.doc,s.field,e.now-(s.after??0))||r.set(n.table,(r.get(n.table)??0)+1)})}catch(n){return n instanceof Error?n.message:String(n)}return r},se=e=>{if(!B(e))return{status:"absent"};let t;try{t=D(e,"utf8")}catch{return{status:"corrupt"}}try{const r=U(t);return r===void 0?{status:"corrupt"}:{snapshot:r,status:"ok"}}catch(r){if(r instanceof W)return{status:"corrupt"};throw r}},ie=(e,t)=>{V(e,G(t),"utf8")},ce=e=>{const t=`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 delete it: the next run captures a fresh baseline from the current schema, checking nothing against the old one.`;return e.readOnly||e.logger.error(t),{blocked:!0,changes:[],reason:t}},ae=(e,t,r)=>e!==void 0?` — ${String(e)} stored row(s) are past the new cutoff and are deleted on the next sweep`:typeof t=="string"?` (the affected rows could not be counted: ${t})`:r?"":" (the affected rows are counted by `lunora deploy`, which reads the deployed worker)",de=async(e,t)=>{const r=e.filter(o=>o.expiry!==void 0);if(r.length===0)return"";if(t.readOnly||t.countExpiringRows===void 0)return` The rows the next sweep would delete were not counted: \`lunora ${t.command??"prepare"}\` does not read a deployment; \`lunora deploy\` counts them.`;const n=await t.countExpiringRows(r);return typeof n=="string"?` The rows the next sweep would delete could not be counted: ${n}.`:` ${r.map(o=>`Next sweep would delete ${String(n.get(o.table??"")??0)} stored row(s) of ${o.table??"?"}, which are past the new cutoff.`).join(` `)}`},H=async(e,t)=>{if(t.readOnly)return;const r=e.filter(s=>s.warning===!0),n=r.filter(s=>s.expiry!==void 0),o=n.length>0&&t.countExpiringRows!==void 0?await t.countExpiringRows(n):void 0;for(const s of r){const c=typeof o=="object"&&s.table!==void 0?o.get(s.table):void 0,d=s.expiry===void 0?"":ae(c,o,t.countExpiringRows!==void 0);t.logger.warn(`schema-drift warning: ${s.summary}${d}`)}},le=(e,t)=>(t.readOnly||t.logger.warn(`schema baseline left at its committed shape — --allow-schema-drift overrides this run only: ${t.snapshotPath}`),{blocked:!1,changes:e.changes,reason:e.reason}),ue=e=>e?.kind==="fails"?` ${oe(e)}`:e?.kind==="inconclusive"?` The stored rows were not checked: ${e.reason}.`:"",he=async(e,t)=>{const r=e.uncovered.filter(o=>_(o));if(!(!(r.length>0&&r.length===e.uncovered.length)||t.readOnly))return t.checkStoredRows===void 0?{kind:"inconclusive",reason:`\`lunora ${t.command??"prepare"}\` does not read a deployment; run \`lunora deploy\`, which checks the stored rows first`}:t.checkStoredRows(r)},fe=async(e,t)=>{const r=await he(e,t);if(r?.kind==="conforms")return t.logger.success(`schema-drift gate: all ${String(r.rows)} stored row(s) of ${r.tables.join(", ")} fit the new schema — the change needs no backfill`),await H(e.changes,t),{blocked:!1,changes:e.changes,reason:e.reason,rebless:t.rebless};const n=`${e.reason}${ue(r)}${await de(e.uncovered,t)}`;return t.readOnly||t.logger.error(n),{blocked:!0,changes:e.changes,reason:n}},_e=async e=>{const{allowDrift:t,checkStoredRows:r,codegen:n,command:o,countExpiringRows:s,logger:c,readOnly:d=!1}=e,i=n.schemaSnapshotPath,a=se(i),u={checkStoredRows:r,command:o,countExpiringRows:s,logger:c,readOnly:d,rebless:()=>{ie(i,n.schemaSnapshot)},snapshotPath:i};if(a.status==="corrupt")return ce(u);const h=w=>K({allowDrift:w,baseline:a.status==="ok"?a.snapshot:void 0,command:o,current:n.schemaSnapshot,indexReferences:n.indexReferences,migrations:n.migrations}),l=h(t);if(l.blocked)return fe(l,u);const k=t&&l.changes.length>0&&h(!1).blocked;return l.changes.length>0?(d||c.info(l.reason),k?le(l,u):(await H(l.changes,u),{blocked:!1,changes:l.changes,reason:l.reason,rebless:d?void 0:u.rebless})):{blocked:!1,changes:l.changes,reason:l.reason}},y="CF_ACCESS_CLIENT_ID",b="CF_ACCESS_CLIENT_SECRET",P="/_lunora/health",Le="/_lunora/health/ready",I=(e,t=P)=>(e.endsWith("/")?e.slice(0,-1):e)+t,ge=e=>e!==""&&Array.from({length:e.length},(t,r)=>e.codePointAt(r)??0).every(t=>t>32&&t<127),me=e=>{const t=e[y]??"",r=e[b]??"";if(t===""&&r==="")return{kind:"none"};if(t===""||r==="")return{kind:"partial",missing:t===""?y:b};const n=[[y,t],[b,r]].find(([,o])=>!ge(o??""));return n!==void 0?{kind:"invalid",variable:String(n[0])}:{headers:{"CF-Access-Client-Id":t,"CF-Access-Client-Secret":r},kind:"sent"}},pe=e=>URL.canParse(e)&&new URL(e).protocol==="https:",ye=(e,t)=>e.kind==="sent"&&!pe(t)?{kind:"insecure"}:e,be=e=>e.kind==="sent"?e.headers:{},ke=(e,t)=>{if(t.ok)return{kind:"ok"};if(t.status===404)return{kind:"not-found"};if(t.status===401||t.status===403)return{kind:"denied"};if(t.status<300||t.status>=400)return{kind:"other"};const r=t.headers.get("location")??"";let n;try{n=new URL(r,e)}catch{return{kind:"redirect",location:""}}if(n.hostname.endsWith(".cloudflareaccess.com")||n.pathname.startsWith("/cdn-cgi/access/"))return{kind:"access-login"};const o=new URL(e);return o.protocol==="http:"&&n.protocol==="https:"&&n.hostname===o.hostname&&n.port===""&&n.pathname===o.pathname&&n.search===o.search?{kind:"https-upgrade",location:n.href}:{kind:"redirect",location:n.origin==="null"?"":n.origin}},g=`${y} and ${b}`,we=(e,t)=>{const r="the host is behind Cloudflare Access, which redirected the probe to its login.",n="a service token the Access application allows (a Service Auth policy)";switch(e.kind){case"insecure":return`${r} ${g} are set, but the service token is sent only over https and ${t} is http; probe the https:// URL.`;case"partial":return`${r} Only one of ${g} is set; set ${e.missing} too, to ${n}, and the probe sends both.`;case"sent":return`Cloudflare Access refused the service token in ${g} and redirected to its login. Check that the Access application has a Service Auth policy that includes this token.`;default:return`${r} Set ${g} to ${n}, and the probe sends them.`}},$e=(e,t,r,n)=>{const o=e.from===void 0?"":` (redirected from ${e.from})`,s=`health probe failed: ${e.url}${o} returned HTTP ${String(t.status)}`;switch(r.kind){case"access-login":return`${s}: ${we(n,e.url)}`;case"denied":return n.kind==="sent"?`${s} with the Cloudflare Access service token from ${g} sent — if the host is behind Access, check that the token is current and a Service Auth policy includes it.`:n.kind==="insecure"?`${s}; the Cloudflare Access service token was not sent, because ${e.url} is not https.`:s;case"https-upgrade":case"redirect":{const c=n.kind==="sent"?"":r.location;return`${s}${c===""?"":` redirecting to ${c}`} — the health route does not redirect, so something in front of the Worker answered.`}default:return s}},R=async(e,t,r)=>{const n=ye(r,e.url);try{const o=await t(e.url,{headers:be(n),redirect:"manual"}),s=ke(e.url,o);return s.kind==="ok"?{outcome:s,url:e.url}:{error:$e(e,o,s,n),outcome:s,url:e.url}}catch(o){const s=o instanceof Error?o.message:String(o);return{error:`health probe failed: could not reach ${e.url} (${s})`,url:e.url}}},ve=async(e,t,r)=>{const n=t(),o=await R({url:e},n,r);return o.outcome?.kind==="https-upgrade"?R({from:e,url:o.outcome.location},n,r):o},T=async(e,t,r,n)=>{let o={error:`health probe failed: no health path configured for ${e}`,url:e};for(const[s,c]of t.entries()){const{error:d,outcome:i,url:a}=await ve(I(e,c),r,n);if(o=d===void 0?{url:a}:{error:d,url:a},i?.kind!=="not-found"||s===t.length-1)return o}return o},Se=async e=>new Promise(t=>{setTimeout(t,e)}),Me=async({attempts:e=1,baseUrl:t,delayMs:r=2e3,env:n=process.env,fetchImpl:o,paths:s=[P],sleep:c=Se,timeoutMs:d=1e4})=>{const i=me(n);if(i.kind==="invalid")return{error:`health probe not sent: ${i.variable} contains a character an HTTP header cannot carry (a line break or a space?). Set it to the service token's value alone.`,url:I(t,s[0])};const a=()=>{if(o!==void 0)return o;const l=AbortSignal.timeout(d);return async(k,w)=>fetch(k,{...w,signal:l})},u=Math.max(1,e);let h=await T(t,s,a,i);for(let l=1;l<u&&h.error!==void 0;l+=1)await c(r),h=await T(t,s,a,i);return h};export{Le as H,P as a,Te as b,Oe as c,Me as p,_e as r};