@lunora/cli 1.0.0-alpha.356 → 1.0.0-alpha.358
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.
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as m,readFileSync as k,realpathSync as h}from"node:fs";import{join as u}from"node:path";import{readServiceBindings as A,readProjectTarget as R,DEFAULT_TARGET as S}from"@lunora/codegen";import{DEV_VARS_FILE as p,parseDevVariableEntries as x,isPlaceholderValue as _,readProjectDependencies as j,discoverSchemaInfo as L,inferLunoraBindings as I,resolveSchemaDirectory as O}from"@lunora/config";import{GLOBAL_FETCH_STRICTLY_PUBLIC_FLAG as f,resolveObservabilitySampling as E,findWranglerFile as N,readWranglerJsonc as C,validateWranglerProject as D,UNEXPORTED_CLASS_MARKER as v,detectCloudflareCliConfig as P,collectExportGaps as T}from"@lunora/config/cloudflare";import{i as U,m as F,c as G,a as V}from"../packem_shared/secret-key-B4aoLE0w.mjs";import{r as B,d as W}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{n as $}from"../packem_shared/cloudflare-credentials-lC5JtPLe.mjs";import{d as M}from"../packem_shared/command-CAXl2A1S.mjs";import{i as K}from"../packem_shared/path-containment-CgxYZggb.mjs";import{b,c as w,a as g}from"../packem_shared/variables-acxcvVQa.mjs";const z=(t,r)=>{const e=new Set,n=s=>{for(const[c,i]of Object.entries(s??{}))typeof i=="string"&&i.trim().length>0&&e.add(c)};n(t.vars);for(const s of Object.values(t.env??{}))n(s.vars);const o=u(r,p);if(m(o))try{n(Object.fromEntries(x(k(o,"utf8")).map(s=>[s.key,s.value])))}catch{}return e},H=(t,r,e,n)=>{if(t===void 0||!e)return;const o=z(t,r),s=o.has(b),c=t.ai?.binding;!s&&(typeof c!="string"||c.length===0)&&n.push({code:"ai-binding-missing",fix:`Run \`lunora dev\` (it adds the binding), add \`"ai": { "binding": "AI" }\` to wrangler.jsonc, or set ${b} to an OpenAI-compatible proxy.`,level:"warn",message:"the project uses ctx.ai (@lunora/ai / env.AI) but wrangler.jsonc declares no `ai` binding — model calls will fail at runtime."}),o.has(w)&&n.push({code:"ai-gateway-token-unused",fix:"Make the gateway unauthenticated for ctx.ai, or remove the token. A bring-your-own AI SDK provider built with `resolveAiGateway` does send it.",level:"warn",message:`${w} is set, but ctx.ai's Workers AI binding cannot send a gateway token — it is ignored on that path.`}),!s&&!o.has(g)&&n.push({code:"ai-gateway-default",fix:`Run \`lunora ai gateway\` to create a gateway for this app and write ${g} into wrangler vars.`,level:"info",message:`no ${g} in vars or ${p} — \`<provider>/<model>\` slugs route through the account's \`default\` AI Gateway.`})},q=(t,r,e)=>{if(t===void 0||!r)return;const n=[];(t.compatibility_flags??[]).includes(f)||n.push("the top level");for(const[o,s]of Object.entries(t.env??{}))s.compatibility_flags!==void 0&&!s.compatibility_flags.includes(f)&&n.push(`env.${o}`);n.length>0&&e.push({code:"cimd-fetch-not-strictly-public",fix:`Add "${f}" to "compatibility_flags" in wrangler.jsonc.`,level:"warn",message:`@lunora/auth/cimd/workers is imported, but ${n.join(", ")} of wrangler.jsonc lacks the ${f} compatibility flag — workersCimdFetch() refuses to build without it.`})},y=t=>{const{logs:r,traces:e}=E(t);return Object.entries({logs:r,traces:e}).filter(([,n])=>n.enabled&&n.headSamplingRate>=1).map(([n])=>n)},Y=(t,r)=>{if(t===void 0)return;const e=[],n=y(t.observability);n.length>0&&e.push(`${n.join(" + ")} (top level)`);for(const[o,s]of Object.entries(t.env??{})){if(s.observability===void 0)continue;const c=y(s.observability);c.length>0&&e.push(`${c.join(" + ")} (env.${o})`)}e.length!==0&&r.push({code:"observability-full-sampling",fix:"For a high-traffic Worker, lower head_sampling_rate in wrangler.jsonc: under observability for logs, under observability.traces for traces — e.g. 0.1 keeps 10% of requests. Lunora never changes a rate you set.",level:"info",message:`observability samples every request (head_sampling_rate 1) for ${e.join(", ")}. From 2026-12-01 Workers Observability is billed: Free caps ingestion at 0.5 GB/day; Paid includes 50 GB per billing cycle, then $0.25/GB.`})},J=(t,r)=>{for(const e of A(t).services)for(const n of e.publicScopes){const o=n===""?"":` (env.${n})`;r.push({code:"service-workers-dev",fix:`Set \`"workers_dev": false\`${o} in ${e.wranglerPath} — the app's service binding is its only way in, so internal auth (HMAC) can go too.`,level:"warn",message:`service ${e.name} (${e.worker}) is bound by the app but still public on workers.dev${o}.`})}},X=t=>{const r=t.trim();if(r==="")return!0;const e=r.toLowerCase();return e.includes("replace")||e.startsWith("<")&&e.endsWith(">")},Q=t=>{const r=N(t);if(r===void 0)return{parsed:void 0,path:void 0};const{parsed:e}=C(r);return{parsed:e,path:r}},Z=(t,r,e,n)=>{if(e===void 0){n.push({code:"wrangler-missing",fix:"Run `lunora init` (or `lunora dev`) to scaffold and reconcile wrangler.jsonc.",level:"fail",message:"wrangler.jsonc not found."});return}if(r===void 0){n.push({code:"wrangler-unparseable",fix:`Check ${e} is valid JSONC.`,level:"fail",message:`Could not parse ${e}.`});return}const{report:o}=D({projectRoot:t});for(const i of o.errors.filter(a=>a.includes(v)))n.push({code:"wrangler-class-unexported",level:"fail",message:i});for(const i of o.warnings.filter(a=>a.includes("LUNORA_ORIGIN_URL")))n.push({code:"scheduler-origin-missing",fix:"Set LUNORA_ORIGIN_URL in wrangler vars to the worker's public URL (or `wrangler secret put LUNORA_ORIGIN_URL`).",level:"warn",message:i});const s=i=>i.includes(v)||i.includes("SHARD");for(const i of o.errors.filter(a=>!s(a)))n.push({code:"wrangler-invalid",fix:"Fix the reported wrangler.jsonc problem; `lunora verify` reports the same set.",level:"fail",message:i});for(const i of o.warnings.filter(a=>!a.includes("LUNORA_ORIGIN_URL")))n.push({code:"wrangler-advisory",level:"warn",message:i});const c=o.errors.find(i=>i.includes("SHARD"));c===void 0?n.push({code:"wrangler-shard-binding-ok",level:"pass",message:"wrangler.jsonc present with a SHARD durable-object binding."}):n.push({code:"wrangler-shard-binding-missing",fix:"Run `lunora dev` to auto-reconcile, or add the binding manually.",level:"fail",message:c})},ee=(t,r)=>{m(u(t,"lunora.json"))&&r.push({code:"stale-lunora-json",fix:'Move `target` / `remote` into `lunora.config.ts` (`export default { target: "…" }`), then delete lunora.json.',level:"warn",message:"lunora.json is present but no longer read — lunora.config.* replaced it, so any `target` or `remote` in it is being ignored."})},ne=(t,r)=>{const e=P(t);e!==void 0&&r.push({code:"cf-config-present",fix:e.fix,level:"warn",message:e.message})},re=(t,r)=>{t===void 0||t.limits?.cpu_ms!==void 0||r.push({code:"cpu-limit-missing",fix:'Add `"limits": { "cpu_ms": 30000 }` to wrangler.jsonc, tuned to your slowest legitimate handler.',level:"info",message:"no limits.cpu_ms is set — a runaway handler can burn CPU up to the platform default before anything stops it."})},oe=(t,r)=>{const e=(t?.r2_buckets??[]).map(n=>n?.bucket_name).filter(n=>typeof n=="string"&&n.length>0);e.length!==0&&r.push({code:"r2-lifecycle-unset",fix:"wrangler r2 bucket lifecycle list <bucket> — add an abort-incomplete-multipart rule if none exists.",level:"info",message:`R2 bucket(s) ${e.join(", ")}: verify a lifecycle rule aborts incomplete multipart uploads — orphaned parts are billed but invisible in a listing.`})},te=(t,r)=>{const{error:e,info:n}=L(t,"lunora");if(e!==void 0){r.push({code:"schema-unreadable",fix:"Fix the parse error, then re-run `lunora doctor`. `lunora codegen` reports the same failure with the offending source.",level:"fail",message:`lunora/schema.ts could not be parsed, so every schema-derived check was skipped: ${e}`});return}for(const o of n?.vectorMetadata??[]){const s=F(o.kind);if(s===void 0){r.push({code:"vector-metadata-unfilterable",fix:"Filter on a string, number or boolean column, or drop it from `metadata`.",level:"warn",message:`vector index "${o.index}" declares metadata "${o.property}", whose type Vectorize cannot filter on.`});continue}r.push({code:"vector-metadata-index-required",fix:`wrangler ${G({index:o.index,property:o.property,type:s}).join(" ")}`,level:"info",message:`vector index "${o.index}" filters on metadata "${o.property}" — that needs a Vectorize metadata index (\`lunora deploy\` creates it).`})}},se=(t,r)=>{if(t===void 0)return;const e=(t.d1_databases??[]).filter(Boolean);for(const n of e){const o=typeof n.database_id=="string"?n.database_id:"";if(X(o)){const s=typeof n.binding=="string"&&n.binding.length>0?n.binding:"<unnamed>";r.push({code:"d1-placeholder-id",fix:"Run `wrangler d1 create <name>` and paste the returned database_id into wrangler.jsonc.",level:"fail",message:`D1 binding "${s}" has a placeholder database_id ("${o||"<empty>"}").`})}}},ae=(t,r)=>{if(t===void 0)return;const e=(t.send_email??[]).filter(Boolean);for(const n of e){const o=typeof n.destination_address=="string"?n.destination_address:"";if(o!==""&&_(o)){const s=typeof n.name=="string"&&n.name.length>0?n.name:"send_email";r.push({code:"email-destination-placeholder",fix:"Set destination_address to a verified Cloudflare Email Routing address.",level:"warn",message:`send_email binding "${s}" has a placeholder destination_address ("${o}").`})}}},ie=(t,r)=>{const e=u(t,p);if(!m(e))return;let n;try{n=k(e,"utf8")}catch{return}const o=x(n).filter(s=>U(s.key)&&_(s.value)).map(s=>s.key);o.length>0&&r.push({code:"dev-vars-missing-secret",fix:"Run `lunora dev` to auto-generate secrets, or fill them in by hand.",level:"warn",message:`${p} has unfilled secret value(s): ${o.join(", ")}.`})},ce=(t,r)=>{const{source:e}=B({cwd:t});e===void 0?r.push({code:"admin-token-missing",fix:"Set LUNORA_ADMIN_TOKEN (env or `.dev.vars`) to enable admin RPCs / studio.",level:"info",message:"LUNORA_ADMIN_TOKEN is not set."}):r.push({code:"admin-token-set",level:"pass",message:`LUNORA_ADMIN_TOKEN is set (${W(e)}).`})},le=async(t,r)=>{try{return await I({projectRoot:t,schemaDir:O(t)})}catch(e){r.push({code:"declared-export-unchecked",fix:"Make sure the worker entry resolves (see `lunora codegen`), then re-run.",level:"warn",message:`could not check whether declared containers/workflows/agents are re-exported by the worker entry: ${e instanceof Error?e.message:String(e)}`});return}},de=(t,r)=>{const e=T(t),n=[...t.containers.map(o=>({...o,kind:"container"})),...t.workflows.map(o=>({...o,kind:"workflow"})),...t.agents.map(o=>({...o,kind:"agent"}))];for(const o of n.filter(s=>s.exported))r.push({code:"declared-export-ok",level:"pass",message:`${o.kind} "${o.exportName}" is exported by the worker entry.`});for(const o of e)r.push({code:"declared-export-missing",fix:`Add \`export * from "./lunora/_generated/${o.module}"\` to your worker entry (or re-run \`vis generate lunora-${o.kind}\`).`,level:"fail",message:`${o.kind} "${o.exportName}" is declared but ${o.className} is not exported by the worker entry.`})},ue=/^[\^~><= ]+/u,fe=/^(?<core>\d+\.\d+\.\d+)(?:-(?<channel>[a-z]+)\.(?<counter>\d+))?$/u,pe=t=>{const r=t.replace(ue,"").trim(),e=fe.exec(r);if(!e?.groups)return;const{channel:n,core:o,counter:s}=e.groups;return{channel:n??"",core:o??"",counter:s===void 0?void 0:Number.parseInt(s,10),raw:r}},me=(t,r)=>{const e=j(t),n=[];for(const[a,l]of Object.entries(e)){if(a!=="lunorash"&&!a.startsWith("@lunora/"))continue;const d=pe(l);d&&n.push({name:a,version:d})}if(n.length<2)return;const o=a=>a.map(l=>`${l.name}@${l.version.raw}`).join(", "),s=new Set(n.map(a=>a.version.core)),c=new Set(n.map(a=>a.version.channel));if(s.size>1){r.push({code:"version-skew-cores",fix:'Run `pnpm update "@lunora/*" lunorash` (or `npm`/`yarn` equivalent) so every Lunora package moves to the same release.',level:"warn",message:`Lunora packages span ${String(s.size)} different versions: ${o(n)}.`});return}if(c.size>1){r.push({code:"version-skew-channels",fix:"Pick one channel (all stable, or all alpha/beta) and update the odd package out.",level:"warn",message:`Lunora packages mix release channels (${[...c].map(a=>a===""?"stable":a).join(" + ")}): ${o(n)}.`});return}const i=n.map(a=>a.version.counter).filter(a=>a!==void 0);if(i.length>1){const a=Math.min(...i),l=Math.max(...i);r.push({code:"version-counter-spread",level:"info",message:i.length===n.length&&a===l?`Lunora packages are all at ${[...c][0]??""}.${String(l)}.`:`Lunora pre-release counters span ${String(a)}–${String(l)}: ${o(n)}.`})}},ge=[u("@lunora","cli"),"lunorash"],he=(t,r,e)=>{if(r===void 0)return;const n=[];for(const s of ge){const c=u(t,"node_modules",s);if(m(c))try{n.push(h(c))}catch{}}if(n.length===0)return;let o;try{o=h(r)}catch{return}n.some(s=>K(s,o))||e.push({code:"cli-shadowed",fix:"Run the project's own CLI: `pnpm exec lunora …` (or `npx lunora …`).",level:"warn",message:`the running lunora (${o}) is not the project's own install (${n.join(", ")}).`})},ve={full:{code:"do-class-budget-full",level:"warn"},near:{code:"do-class-budget-near",level:"warn"},ok:{code:"do-class-budget-ok",level:"pass"},unchecked:{code:"do-class-budget-unchecked",level:"info"}},be=t=>{const r=new Map,e=(n,o)=>{const s=$(n);s!==void 0&&r.set(s,[...r.get(s)??[],o])};e(t?.account_id,"top level");for(const[n,o]of Object.entries(t?.env??{}))e(o?.account_id,`env.${n}`);return r},we=async(t,r,e,n)=>{if((R(t)??S)!=="cloudflare")return;const s=$((e.environment??process.env).CLOUDFLARE_ACCOUNT_ID)!==void 0?[]:[...be(r)],c=s.length===0?[[void 0,[]]]:s,i=await Promise.all(c.map(async([a,l])=>({accountId:a,blocks:l,budget:await V({accountId:a,environment:e.environment,fetch:e.fetch})})));for(const{accountId:a,blocks:l,budget:d}of i)n.push({...ve[d.verdict],message:i.length>1?`account ${String(a)} (${l.join(", ")}): ${d.message}`:d.message,...d.fix===void 0?{}:{fix:d.fix}})},ye=async t=>{const r=t.cwd??process.cwd(),e=[],{parsed:n,path:o}=Q(r);Z(r,n,o,e),ne(r,e),se(n,e),ae(n,e),re(n,e),oe(n,e),Y(n,e),ie(r,e),ce(r,e),me(r,e),te(r,e),ee(r,e),he(r,t.executablePath??process.argv[1],e),J(r,e);const s=await le(r,e);s!==void 0&&de(s,e),H(n,r,s?.usesAi===!0,e),await we(r,n,t,e),q(n,s?.usesCimdWorkers===!0,e);const c={fail:0,info:0,pass:0,warn:0};for(const a of e)c[a.level]+=1;const i=c.fail>0?1:0;return{code:i,findings:e,ok:i===0,summary:c}},ke={fail:"FAIL",info:"INFO",pass:"PASS",warn:"WARN"},xe=(t,r)=>{r.info("lunora doctor — project preflight");for(const o of t.findings){const s=`[${ke[o.level]}] ${o.message}`;o.level==="fail"?r.error(s):o.level==="warn"?r.warn(s):r.info(s),o.fix!==void 0&&o.level!=="pass"&&r.info(` fix: ${o.fix}`)}const{fail:e,warn:n}=t.summary;e>0?r.error(`${String(e)} failure(s), ${String(n)} warning(s).`):n>0?r.warn(`0 failures, ${String(n)} warning(s).`):r.success("all checks passed.")},_e=async t=>{const{logger:r}=t,e=await ye({...t});return xe(e,r),e},De=M(async({cwd:t,format:r,logger:e})=>{const n=await _e({cwd:t,format:r,logger:e});return{code:n.code,data:{findings:n.findings,summary:n.summary}}});export{De as execute,ye as runDoctor,_e as runDoctorCommand};
|
|
1
|
+
import{existsSync as g,readFileSync as x,realpathSync as b}from"node:fs";import{join as f}from"node:path";import{readServiceBindings as I,readProjectTarget as $,DEFAULT_TARGET as A}from"@lunora/codegen";import{DEV_VARS_FILE as p,parseDevVariableEntries as R,isPlaceholderValue as S,readProjectDependencies as L,discoverSchemaInfo as O,inferLunoraBindings as N,resolveSchemaDirectory as C}from"@lunora/config";import{GLOBAL_FETCH_STRICTLY_PUBLIC_FLAG as m,resolveObservabilitySampling as E,findWranglerFile as D,readWranglerJsonc as P,validateWranglerProject as T,UNEXPORTED_CLASS_MARKER as w,detectCloudflareCliConfig as F,collectExportGaps as U}from"@lunora/config/cloudflare";import{i as G,m as V,c as B,a as M,b as W}from"../packem_shared/secret-key-BCrqNJ68.mjs";import{r as K,d as z}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{n as j}from"../packem_shared/cloudflare-credentials-lC5JtPLe.mjs";import{d as H}from"../packem_shared/command-CAXl2A1S.mjs";import{i as J}from"../packem_shared/path-containment-CgxYZggb.mjs";import{b as y,c as k,a as h}from"../packem_shared/variables-acxcvVQa.mjs";const q=(t,r)=>{const e=new Set,n=s=>{for(const[c,i]of Object.entries(s??{}))typeof i=="string"&&i.trim().length>0&&e.add(c)};n(t.vars);for(const s of Object.values(t.env??{}))n(s.vars);const o=f(r,p);if(g(o))try{n(Object.fromEntries(R(x(o,"utf8")).map(s=>[s.key,s.value])))}catch{}return e},Y=(t,r,e,n)=>{if(t===void 0||!e)return;const o=q(t,r),s=o.has(y),c=t.ai?.binding;!s&&(typeof c!="string"||c.length===0)&&n.push({code:"ai-binding-missing",fix:`Run \`lunora dev\` (it adds the binding), add \`"ai": { "binding": "AI" }\` to wrangler.jsonc, or set ${y} to an OpenAI-compatible proxy.`,level:"warn",message:"the project uses ctx.ai (@lunora/ai / env.AI) but wrangler.jsonc declares no `ai` binding — model calls will fail at runtime."}),o.has(k)&&n.push({code:"ai-gateway-token-unused",fix:"Make the gateway unauthenticated for ctx.ai, or remove the token. A bring-your-own AI SDK provider built with `resolveAiGateway` does send it.",level:"warn",message:`${k} is set, but ctx.ai's Workers AI binding cannot send a gateway token — it is ignored on that path.`}),!s&&!o.has(h)&&n.push({code:"ai-gateway-default",fix:`Run \`lunora ai gateway\` to create a gateway for this app and write ${h} into wrangler vars.`,level:"info",message:`no ${h} in vars or ${p} — \`<provider>/<model>\` slugs route through the account's \`default\` AI Gateway.`})},X=(t,r,e)=>{if(t===void 0||!r)return;const n=[];(t.compatibility_flags??[]).includes(m)||n.push("the top level");for(const[o,s]of Object.entries(t.env??{}))s.compatibility_flags!==void 0&&!s.compatibility_flags.includes(m)&&n.push(`env.${o}`);n.length>0&&e.push({code:"cimd-fetch-not-strictly-public",fix:`Add "${m}" to "compatibility_flags" in wrangler.jsonc.`,level:"warn",message:`@lunora/auth/cimd/workers is imported, but ${n.join(", ")} of wrangler.jsonc lacks the ${m} compatibility flag — workersCimdFetch() refuses to build without it.`})},_=t=>{const{logs:r,traces:e}=E(t);return Object.entries({logs:r,traces:e}).filter(([,n])=>n.enabled&&n.headSamplingRate>=1).map(([n])=>n)},Q=(t,r)=>{if(t===void 0)return;const e=[],n=_(t.observability);n.length>0&&e.push(`${n.join(" + ")} (top level)`);for(const[o,s]of Object.entries(t.env??{})){if(s.observability===void 0)continue;const c=_(s.observability);c.length>0&&e.push(`${c.join(" + ")} (env.${o})`)}e.length!==0&&r.push({code:"observability-full-sampling",fix:"For a high-traffic Worker, lower head_sampling_rate in wrangler.jsonc: under observability for logs, under observability.traces for traces — e.g. 0.1 keeps 10% of requests. Lunora never changes a rate you set.",level:"info",message:`observability samples every request (head_sampling_rate 1) for ${e.join(", ")}. From 2026-12-01 Workers Observability is billed: Free caps ingestion at 0.5 GB/day; Paid includes 50 GB per billing cycle, then $0.25/GB.`})},Z=(t,r)=>{for(const e of I(t).services)for(const n of e.publicScopes){const o=n===""?"":` (env.${n})`;r.push({code:"service-workers-dev",fix:`Set \`"workers_dev": false\`${o} in ${e.wranglerPath} — the app's service binding is its only way in, so internal auth (HMAC) can go too.`,level:"warn",message:`service ${e.name} (${e.worker}) is bound by the app but still public on workers.dev${o}.`})}},ee=t=>{const r=t.trim();if(r==="")return!0;const e=r.toLowerCase();return e.includes("replace")||e.startsWith("<")&&e.endsWith(">")},ne=t=>{const r=D(t);if(r===void 0)return{parsed:void 0,path:void 0};const{parsed:e}=P(r);return{parsed:e,path:r}},re=(t,r,e,n)=>{if(e===void 0){n.push({code:"wrangler-missing",fix:"Run `lunora init` (or `lunora dev`) to scaffold and reconcile wrangler.jsonc.",level:"fail",message:"wrangler.jsonc not found."});return}if(r===void 0){n.push({code:"wrangler-unparseable",fix:`Check ${e} is valid JSONC.`,level:"fail",message:`Could not parse ${e}.`});return}const{report:o}=T({projectRoot:t});for(const i of o.errors.filter(a=>a.includes(w)))n.push({code:"wrangler-class-unexported",level:"fail",message:i});for(const i of o.warnings.filter(a=>a.includes("LUNORA_ORIGIN_URL")))n.push({code:"scheduler-origin-missing",fix:"Set LUNORA_ORIGIN_URL in wrangler vars to the worker's public URL (or `wrangler secret put LUNORA_ORIGIN_URL`).",level:"warn",message:i});const s=i=>i.includes(w)||i.includes("SHARD");for(const i of o.errors.filter(a=>!s(a)))n.push({code:"wrangler-invalid",fix:"Fix the reported wrangler.jsonc problem; `lunora verify` reports the same set.",level:"fail",message:i});for(const i of o.warnings.filter(a=>!a.includes("LUNORA_ORIGIN_URL")))n.push({code:"wrangler-advisory",level:"warn",message:i});const c=o.errors.find(i=>i.includes("SHARD"));c===void 0?n.push({code:"wrangler-shard-binding-ok",level:"pass",message:"wrangler.jsonc present with a SHARD durable-object binding."}):n.push({code:"wrangler-shard-binding-missing",fix:"Run `lunora dev` to auto-reconcile, or add the binding manually.",level:"fail",message:c})},te=(t,r)=>{g(f(t,"lunora.json"))&&r.push({code:"stale-lunora-json",fix:'Move `target` / `remote` into `lunora.config.ts` (`export default { target: "…" }`), then delete lunora.json.',level:"warn",message:"lunora.json is present but no longer read — lunora.config.* replaced it, so any `target` or `remote` in it is being ignored."})},oe=(t,r)=>{const e=F(t);e!==void 0&&r.push({code:"cf-config-present",fix:e.fix,level:"warn",message:e.message})},se=(t,r)=>{t===void 0||t.limits?.cpu_ms!==void 0||r.push({code:"cpu-limit-missing",fix:'Add `"limits": { "cpu_ms": 30000 }` to wrangler.jsonc, tuned to your slowest legitimate handler.',level:"info",message:"no limits.cpu_ms is set — a runaway handler can burn CPU up to the platform default before anything stops it."})},ae=(t,r)=>{const e=(t?.r2_buckets??[]).map(n=>n?.bucket_name).filter(n=>typeof n=="string"&&n.length>0);e.length!==0&&r.push({code:"r2-lifecycle-unset",fix:"wrangler r2 bucket lifecycle list <bucket> — add an abort-incomplete-multipart rule if none exists.",level:"info",message:`R2 bucket(s) ${e.join(", ")}: verify a lifecycle rule aborts incomplete multipart uploads — orphaned parts are billed but invisible in a listing.`})},ie=(t,r)=>{const{error:e,info:n}=O(t,"lunora");if(e!==void 0){r.push({code:"schema-unreadable",fix:"Fix the parse error, then re-run `lunora doctor`. `lunora codegen` reports the same failure with the offending source.",level:"fail",message:`lunora/schema.ts could not be parsed, so every schema-derived check was skipped: ${e}`});return}for(const o of n?.vectorMetadata??[]){const s=V(o.kind);if(s===void 0){r.push({code:"vector-metadata-unfilterable",fix:"Filter on a string, number or boolean column, or drop it from `metadata`.",level:"warn",message:`vector index "${o.index}" declares metadata "${o.property}", whose type Vectorize cannot filter on.`});continue}r.push({code:"vector-metadata-index-required",fix:`wrangler ${B({index:o.index,property:o.property,type:s}).join(" ")}`,level:"info",message:`vector index "${o.index}" filters on metadata "${o.property}" — that needs a Vectorize metadata index (\`lunora deploy\` creates it).`})}},ce=(t,r)=>{if(t===void 0)return;const e=(t.d1_databases??[]).filter(Boolean);for(const n of e){const o=typeof n.database_id=="string"?n.database_id:"";if(ee(o)){const s=typeof n.binding=="string"&&n.binding.length>0?n.binding:"<unnamed>";r.push({code:"d1-placeholder-id",fix:"Run `wrangler d1 create <name>` and paste the returned database_id into wrangler.jsonc.",level:"fail",message:`D1 binding "${s}" has a placeholder database_id ("${o||"<empty>"}").`})}}},le=(t,r)=>{if(t===void 0)return;const e=(t.send_email??[]).filter(Boolean);for(const n of e){const o=typeof n.destination_address=="string"?n.destination_address:"";if(o!==""&&S(o)){const s=typeof n.name=="string"&&n.name.length>0?n.name:"send_email";r.push({code:"email-destination-placeholder",fix:"Set destination_address to a verified Cloudflare Email Routing address.",level:"warn",message:`send_email binding "${s}" has a placeholder destination_address ("${o}").`})}}},de=(t,r)=>{const e=f(t,p);if(!g(e))return;let n;try{n=x(e,"utf8")}catch{return}const o=R(n).filter(s=>G(s.key)&&S(s.value)).map(s=>s.key);o.length>0&&r.push({code:"dev-vars-missing-secret",fix:"Run `lunora dev` to auto-generate secrets, or fill them in by hand.",level:"warn",message:`${p} has unfilled secret value(s): ${o.join(", ")}.`})},ue=(t,r)=>{const{source:e}=K({cwd:t});e===void 0?r.push({code:"admin-token-missing",fix:"Set LUNORA_ADMIN_TOKEN (env or `.dev.vars`) to enable admin RPCs / studio.",level:"info",message:"LUNORA_ADMIN_TOKEN is not set."}):r.push({code:"admin-token-set",level:"pass",message:`LUNORA_ADMIN_TOKEN is set (${z(e)}).`})},fe=async(t,r)=>{try{return await N({projectRoot:t,schemaDir:C(t)})}catch(e){r.push({code:"declared-export-unchecked",fix:"Make sure the worker entry resolves (see `lunora codegen`), then re-run.",level:"warn",message:`could not check whether declared containers/workflows/agents are re-exported by the worker entry: ${e instanceof Error?e.message:String(e)}`});return}},me=(t,r)=>{const e=U(t),n=[...t.containers.map(o=>({...o,kind:"container"})),...t.workflows.map(o=>({...o,kind:"workflow"})),...t.agents.map(o=>({...o,kind:"agent"}))];for(const o of n.filter(s=>s.exported))r.push({code:"declared-export-ok",level:"pass",message:`${o.kind} "${o.exportName}" is exported by the worker entry.`});for(const o of e)r.push({code:"declared-export-missing",fix:`Add \`export * from "./lunora/_generated/${o.module}"\` to your worker entry (or re-run \`vis generate lunora-${o.kind}\`).`,level:"fail",message:`${o.kind} "${o.exportName}" is declared but ${o.className} is not exported by the worker entry.`})},pe=/^[\^~><= ]+/u,ge=/^(?<core>\d+\.\d+\.\d+)(?:-(?<channel>[a-z]+)\.(?<counter>\d+))?$/u,he=t=>{const r=t.replace(pe,"").trim(),e=ge.exec(r);if(!e?.groups)return;const{channel:n,core:o,counter:s}=e.groups;return{channel:n??"",core:o??"",counter:s===void 0?void 0:Number.parseInt(s,10),raw:r}},ve=(t,r)=>{const e=L(t),n=[];for(const[a,l]of Object.entries(e)){if(a!=="lunorash"&&!a.startsWith("@lunora/"))continue;const d=he(l);d&&n.push({name:a,version:d})}if(n.length<2)return;const o=a=>a.map(l=>`${l.name}@${l.version.raw}`).join(", "),s=new Set(n.map(a=>a.version.core)),c=new Set(n.map(a=>a.version.channel));if(s.size>1){r.push({code:"version-skew-cores",fix:'Run `pnpm update "@lunora/*" lunorash` (or `npm`/`yarn` equivalent) so every Lunora package moves to the same release.',level:"warn",message:`Lunora packages span ${String(s.size)} different versions: ${o(n)}.`});return}if(c.size>1){r.push({code:"version-skew-channels",fix:"Pick one channel (all stable, or all alpha/beta) and update the odd package out.",level:"warn",message:`Lunora packages mix release channels (${[...c].map(a=>a===""?"stable":a).join(" + ")}): ${o(n)}.`});return}const i=n.map(a=>a.version.counter).filter(a=>a!==void 0);if(i.length>1){const a=Math.min(...i),l=Math.max(...i);r.push({code:"version-counter-spread",level:"info",message:i.length===n.length&&a===l?`Lunora packages are all at ${[...c][0]??""}.${String(l)}.`:`Lunora pre-release counters span ${String(a)}–${String(l)}: ${o(n)}.`})}},be=[f("@lunora","cli"),"lunorash"],we=(t,r,e)=>{if(r===void 0)return;const n=[];for(const s of be){const c=f(t,"node_modules",s);if(g(c))try{n.push(b(c))}catch{}}if(n.length===0)return;let o;try{o=b(r)}catch{return}n.some(s=>J(s,o))||e.push({code:"cli-shadowed",fix:"Run the project's own CLI: `pnpm exec lunora …` (or `npx lunora …`).",level:"warn",message:`the running lunora (${o}) is not the project's own install (${n.join(", ")}).`})},ye={full:{code:"do-class-budget-full",level:"warn"},near:{code:"do-class-budget-near",level:"warn"},ok:{code:"do-class-budget-ok",level:"pass"},unchecked:{code:"do-class-budget-unchecked",level:"info"}},ke=t=>{const r=new Map,e=(n,o)=>{const s=j(n);s!==void 0&&r.set(s,[...r.get(s)??[],o])};e(t?.account_id,"top level");for(const[n,o]of Object.entries(t?.env??{}))e(o?.account_id,`env.${n}`);return r},_e=async(t,r,e,n)=>{if(($(t)??A)!=="cloudflare")return;const s=j((e.environment??process.env).CLOUDFLARE_ACCOUNT_ID)!==void 0?[]:[...ke(r)],c=s.length===0?[[void 0,[]]]:s,i=await Promise.all(c.map(async([a,l])=>({accountId:a,blocks:l,budget:await M({accountId:a,environment:e.environment,fetch:e.fetch})})));for(const{accountId:a,blocks:l,budget:d}of i)n.push({...ye[d.verdict],message:i.length>1?`account ${String(a)} (${l.join(", ")}): ${d.message}`:d.message,...d.fix===void 0?{}:{fix:d.fix}})},xe={mismatch:{code:"artifacts-jurisdiction-mismatch",level:"fail"},missing:{code:"artifacts-namespace-missing",level:"fail"},ok:{code:"artifacts-jurisdiction-ok",level:"pass"},unchecked:{code:"artifacts-jurisdiction-unchecked",level:"warn"}},$e=async(t,r,e,n,o)=>{if(e===void 0||r===void 0||($(t)??A)!=="cloudflare")return;const s=[["",r],...Object.entries(r.env??{}).map(([a,l])=>[`env.${a}: `,l])],c=new Map;for(const[a,l]of s){const d=l.account_id??r.account_id;for(const u of l.artifacts??[]){const v=`${String(d)}/${String(u?.namespace)}`;typeof u?.binding=="string"&&typeof u.namespace=="string"&&!c.has(v)&&c.set(v,{accountId:d,binding:u.binding,label:a,namespace:u.namespace})}}const i=await Promise.all([...c.values()].map(async({label:a,...l})=>({check:await W({...l,environment:n.environment,fetch:n.fetch,jurisdiction:e}),label:a})));for(const{check:a,label:l}of i)o.push({...xe[a.verdict],message:`${l}${a.message}`,...a.fix===void 0?{}:{fix:a.fix}})},Ae=async t=>{const r=t.cwd??process.cwd(),e=[],{parsed:n,path:o}=ne(r);re(r,n,o,e),oe(r,e),ce(n,e),le(n,e),se(n,e),ae(n,e),Q(n,e),de(r,e),ue(r,e),ve(r,e),ie(r,e),te(r,e),we(r,t.executablePath??process.argv[1],e),Z(r,e);const s=await fe(r,e);s!==void 0&&me(s,e),Y(n,r,s?.usesAi===!0,e),await _e(r,n,t,e),await $e(r,n,s?.jurisdiction,t,e),X(n,s?.usesCimdWorkers===!0,e);const c={fail:0,info:0,pass:0,warn:0};for(const a of e)c[a.level]+=1;const i=c.fail>0?1:0;return{code:i,findings:e,ok:i===0,summary:c}},Re={fail:"FAIL",info:"INFO",pass:"PASS",warn:"WARN"},Se=(t,r)=>{r.info("lunora doctor — project preflight");for(const o of t.findings){const s=`[${Re[o.level]}] ${o.message}`;o.level==="fail"?r.error(s):o.level==="warn"?r.warn(s):r.info(s),o.fix!==void 0&&o.level!=="pass"&&r.info(` fix: ${o.fix}`)}const{fail:e,warn:n}=t.summary;e>0?r.error(`${String(e)} failure(s), ${String(n)} warning(s).`):n>0?r.warn(`0 failures, ${String(n)} warning(s).`):r.success("all checks passed.")},je=async t=>{const{logger:r}=t,e=await Ae({...t});return Se(e,r),e},Ge=H(async({cwd:t,format:r,logger:e})=>{const n=await je({cwd:t,format:r,logger:e});return{code:n.code,data:{findings:n.findings,summary:n.summary}}});export{Ge as execute,Ae as runDoctor,je as runDoctorCommand};
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import{join as J,dirname as X}from"node:path";import{discoverMigrations as Q,readServiceBindings as Z,runCodegen as ee}from"@lunora/codegen";import{readLinkedProject as I,execArgsFor as L,detectPackageManager as b,discoverContainerInfo as U,COMPOSED_WORKER_ENTRY as P,writeLinkedProject as re,discoverSchemaInfo as te,DEV_VARS_FILE as w,parseDevVariableEntries as O,isMintableSecretKey as x,packageNamesFromBindings as ne,inferLunoraBindings as B,resolveSchemaDirectory as F,requiredSecrets as ae,generateSecretValue as oe,toolchainExecArgs as R,upsertDevVariableLine as ie,writeDevVariablesFileAtomically as se,resolveDeployDriver as A,planToolchainInvocation as W,runPostCodegenHook as ce}from"@lunora/config";import{findWranglerFile as M,readWranglerJsonc as V,mergeWranglerEnvironment as le,warnCloudflareCliConfigOnce as de,validateWranglerProject as ue,reconcileWranglerBindings as ge,reconcileWranglerCompatibilityDate as me,reconcileWranglerCrons as fe,describePreservedCrons as he}from"@lunora/config/cloudflare";import{Spinner as ve}from"@visulima/spinner";import{r as pe,a as ye,e as we}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as ke,a as be}from"../packem_shared/deploy-target-DCWwiuAe.mjs";import{w as $e}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{d as Se}from"../packem_shared/command-CAXl2A1S.mjs";import{r as j}from"../packem_shared/wrangler-name-Dsk5K1f-.mjs";import{m as De,e as Ee,i as Re,a as Ae}from"../packem_shared/secret-key-B4aoLE0w.mjs";import{EXIT_CODE as h}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{containerBuildTag as je}from"@lunora/container";import{a as Ce,i as Pe}from"../packem_shared/docker-DpVxvYpL.mjs";import{defaultSpawner as $}from"../packem_shared/createRecordingSpawner-Ch7zuQQE.mjs";import{r as H}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{p as xe,H as _e,a as Te,r as Ne}from"../packem_shared/health-probe-Bw9JFfIy.mjs";import{existsSync as p,readFileSync as k,writeFileSync as G}from"node:fs";import{join as y}from"@visulima/path";import{Project as Ie}from"ts-morph";import{runMigrateDataCommand as Le}from"../packem_shared/runMigrateGenerateCommand-Ii_WMZEA.mjs";import{c as Ue}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{l as Oe}from"../packem_shared/wrangler-secrets-3chIVv3H.mjs";const Be=e=>{const{cwd:r,env:a,logger:t,mintedSecretsFile:n}=e;try{const o=I(r),i=o?.workerName??j(r),s=e.url??o?.workerUrl;t.success("deploy complete"),t.info(` worker: ${i??"(see wrangler output above)"}`),a!==void 0&&t.info(` env: ${a}`),s===void 0?t.info(" url: run `lunora link --url <https://your-worker>` to record it"):t.info(` url: ${s}`),n!==void 0&&t.info(` secrets: generated value(s) recorded in ${n}`),e.logsAvailable&&t.info(" logs: lunora logs")}catch{}},Fe=async e=>{if(e.targets.length===0)return{builtTags:[],code:0};if(!(e.railpackAvailable??Ce)()){const t="deploy blocked: a container uses `image: { build }` (Railpack), but Railpack isn't ready. Install the `railpack` CLI and start a BuildKit instance, e.g. `docker run --rm --privileged -d --name buildkit moby/buildkit` then `export BUILDKIT_HOST=docker-container://buildkit`. Alternatively switch the container's `image` to a Dockerfile path or a pre-built registry reference.";return e.logger.error(t),{builtTags:[],code:1,error:t}}const r=e.spawner??$,a=[];for(const t of e.targets){const n=je(t.exportName),o={args:["build",t.buildDir,"--name",n],command:"railpack",cwd:e.cwd},i=L(b(e.cwd),"wrangler",["containers","push",n]),s={args:i.args,command:i.command,cwd:e.cwd};e.logger.info(`railpack: building "${t.exportName}" → ${n} from ${t.buildDir}`);const c=await r(o);if(c.code!==0){const l=`railpack build failed for container "${t.exportName}" (${t.buildDir})`;return e.logger.error(l),{builtTags:a,code:c.code,error:l}}e.logger.info(`railpack: pushing ${n} to the Cloudflare Registry`);const d=await r(s);if(d.code!==0){const l=`wrangler containers push failed for "${t.exportName}" (${n})`;return e.logger.error(l),{builtTags:a,code:d.code,error:l}}a.push(n)}return{builtTags:a,code:0}},We=e=>{const a=[M(e),J(e,"package.json")].filter(t=>t!==void 0&&p(t)).map(t=>[t,k(t,"utf8")]);return()=>{for(const[t,n]of a)k(t,"utf8")!==n&&G(t,n,"utf8")}},K="<replace-with-d1-create-id>",_=e=>Array.isArray(e)?e.filter(r=>r!=null):void 0,C=(e,r)=>{const a=M(e);if(!a)return;const{parsed:t}=V(a);if(t===void 0)return;const{error:n,merged:o}=le(t,r),i=n===void 0?o:t,{containers:s,d1_databases:c,vars:d}=i;return{containers:_(s),d1_databases:_(c),vars:typeof d=="object"&&d!==null&&!Array.isArray(d)?d:void 0}},Me=/^127(?:\.\d{1,3}){3}$/,Ve=e=>{try{const{hostname:r}=new URL(e);return r==="localhost"||Me.test(r)||r==="::1"||r==="[::1]"}catch{return!1}},He=e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"),Ge=(e,r,a,t="deploy",n)=>{const o=(C(e,n)?.containers??[]).filter(s=>typeof s?.image=="string"&&He(s.image));if(o.length===0||a())return;const i=`${t} blocked: wrangler.jsonc declares ${String(o.length)} container(s) built from a local Dockerfile, but no Docker-compatible engine is available. Start Docker (or Colima), or point the container's \`image\` at a pre-built registry reference. Note: container images must target linux/amd64.`;return r.error(i),i},q=e=>p(y(e,P))?P:void 0,Ke=(e,r,a="deploy")=>{for(const t of U(e,"lunora").containers){const n=t.schedulingPolicy===void 0?t.image:void 0,i=[...n?.kind==="dockerfile"?[{field:"image",path:n.dockerfilePath}]:[],...Object.entries(t.schedulingPolicy==="durable_object"?t.images??{}:{}).flatMap(([s,c])=>c.kind==="dockerfile"?[{field:`images["${s}"]`,path:c.dockerfilePath}]:[])].find(s=>!p(y(e,s.path)));if(i!==void 0){const s=`${a} blocked: container "${t.exportName}" references a Dockerfile at "${i.path}" that does not exist. Create it or fix the \`${i.field}\` path in lunora/containers.ts.`;return r.error(s),s}if(n?.kind==="build"&&!p(y(e,n.buildDir))){const s=`${a} blocked: container "${t.exportName}" references a Railpack build directory "${n.buildDir}" that does not exist. Create it or fix the \`image.build\` path in lunora/containers.ts.`;return r.error(s),s}}},qe=(e,r)=>(C(e,r)?.d1_databases??[]).find(a=>a.database_id===K)?.binding,Ye=e=>{if(!e.migrate||e.dryRun||e.preview)return;if(e.migrateUrl===void 0){const a="--migrate requires --migrate-url <https://your-worker> — the deploy target URL is only known after wrangler runs, and this gate runs before it; refusing to default to localhost";return e.logger.error(a),a}if(e.migrateYes!==!0){const a="--migrate runs production data migrations after deploy. Re-run with --migrate-yes to confirm.";return e.logger.error(a),a}const r=e.migrateToken??process.env.LUNORA_ADMIN_TOKEN;if(r===void 0||r===""){const a="admin token required for --migrate — pass --migrate-token or set LUNORA_ADMIN_TOKEN";return e.logger.error(a),a}},ze=(e,r,a="deploy",t)=>{const n=qe(e,t);if(n===void 0)return;const o=`${a} blocked: the "${n}" D1 binding has a placeholder database_id ("${K}"). Run \`wrangler d1 create <name>\` to create the database, then replace the placeholder in wrangler.jsonc with the real id before deploying.`;return r.error(o),o},Je=(e,r,a="deploy",t)=>{const n=C(e,t)?.vars;if(!n)return;const o=Object.entries(n).filter(([,s])=>typeof s=="string"&&Ve(s)).map(([s])=>s).toSorted((s,c)=>s.localeCompare(c));if(o.length===0)return;const i=`${a} blocked: ${o.join(", ")} in wrangler.jsonc point at localhost. A deployed Worker can't reach a loopback address, so this silently breaks scheduled-job dispatch, reverse cross-shard relations, and auth callbacks. Set each to the deployed worker's public URL (or move it to a secret with \`wrangler secret put\`) before deploying.`;return r.error(i),i},Xe=(e,r,a)=>{const t=ze(e,r.logger,a,r.env);if(t!==void 0)return{code:h.USAGE,error:t};const n=Je(e,r.logger,a,r.env);if(n!==void 0)return{code:h.USAGE,error:n};const o=Ke(e,r.logger,a);if(o!==void 0)return{code:h.USAGE,error:o};const i=Ge(e,r.logger,r.dockerAvailable??Pe,a,r.env);return i===void 0?void 0:{code:h.MISSING_DEPENDENCY,error:i}},Qe=/https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u,Ze=/https:\/\/[^\s"'<>]+/u,er=e=>{if(e===void 0)return;const r=Qe.exec(e);return r?r[0]:Ze.exec(e)?.[0]},T=e=>e===void 0?"":` (--env ${e})`,rr=({cwd:e,env:r,logger:a,now:t,url:n})=>{if(n!==void 0)try{const o=I(e);if(o!==void 0){if(o.workerUrl===n&&o.env===r)return;a.warn(`link: .lunora/project.json records ${o.workerUrl??"(no url)"}${T(o.env)}, but this deploy published ${n}${T(r)}. Keeping the recorded value — run \`lunora link --url ${n}${r===void 0?"":` --env ${r}`}\` to update it.`);return}const i=(t??(()=>new Date().toISOString()))();re(e,{env:r,linkedAt:i,workerName:j(e),workerUrl:n}),a.success(`link: recorded ${n} in .lunora/project.json (run \`lunora link\` to change)`)}catch{}},tr=async(e,r)=>{const a=new Ie({skipAddingFilesFromTsConfig:!0}),t=y(r,"lunora");let n;try{n=Q(a,t)}catch(o){const i=o instanceof Error?o.message:String(o);return e.logger.warn(`--migrate: could not discover migrations (${i}); skipping`),0}if(n.length===0)return e.logger.info("--migrate: no data migrations declared in lunora/"),0;e.logger.info(`--migrate: running ${String(n.length)} migration(s) against deployed worker`);for(const o of n){e.logger.info(`--migrate: up "${o.id}" (table "${o.table}")`);const i={cwd:r,fetchImpl:e.fetchImpl,id:o.id,logger:e.logger,prod:!0,subcommand:"up",token:e.migrateToken,url:e.migrateUrl,yes:e.migrateYes===!0},s=await Le(i);if(s.code!==0)return e.logger.error(`--migrate: migration "${o.id}" failed — see output above`),s.code;e.logger.success(`--migrate: "${o.id}" applied`)}return 0},nr=async(e,r)=>{const{info:a}=te(r,"lunora"),t=a?.vectorMetadata??[];if(t.length===0)return;const n=[];for(const s of t){const c=De(s.kind);if(c===void 0){e.logger.warn(`vector index "${s.index}" declares metadata "${s.property}", whose column type cannot be filtered on in Vectorize — it is stored with each vector but no filter will match it.`);continue}n.push({index:s.index,property:s.property,type:c})}if(n.length===0)return;const i=(await Ee({cwd:r,entries:n,exec:L(b(r),"wrangler",[]),logger:e.logger,spawner:e.spawner??$})).filter(s=>s.status!=="failed").length;i>0&&e.logger.success(`vectorize metadata indexes ready: ${String(i)}/${String(n.length)}`)},N=5,ar=2e3,or=async(e,r,a)=>{if(e.healthCheck!==!0)return;const t=a??H({cwd:r,env:e.env});if(t===void 0){const o="--health-check: the deploy succeeded, but no URL to probe could be resolved — wrangler's output carried none and this checkout has no link for this environment. Run `lunora link --url <https://your-worker>` and re-deploy, or drop --health-check.";return e.logger.error(o),{error:o,ok:!1,url:""}}const n=await xe({attempts:N,baseUrl:t,delayMs:ar,fetchImpl:e.healthFetch,paths:[_e,Te],sleep:e.healthSleep});return n.error===void 0?(e.logger.success(`health check ok (${n.url})`),{ok:!0,url:n.url}):(e.logger.error(`--health-check: the deploy succeeded, but the new version did not answer after ${String(N)} attempt(s) — ${n.error}`),{error:n.error,ok:!1,url:n.url})},ir=async(e,r,a,t,n,o)=>{await nr(e,r);const i=e.migrate?await tr(e,r):0;return i===0&&n?.(),{code:i,descriptor:a,mintedSecretsFile:o,validation:t}},sr=async({cwd:e,descriptor:r,mintedSecretsFile:a,options:t,reblessSchemaBaseline:n,stdout:o,validation:i})=>{const s={deployedAt:new Date().toISOString(),dryRun:t.dryRun===!0,env:t.env,preview:t.preview===!0,url:t.dryRun===!0?void 0:er(o),workerName:j(e)};if(t.dryRun===!0||t.preview===!0)return t.healthCheck===!0&&t.logger.warn(`--health-check skipped: ${t.dryRun===!0?"a dry run publishes nothing":"a preview version serves no live traffic"}`),{code:0,deployment:s,descriptor:r,mintedSecretsFile:a,validation:i};t.temporary!==!0&&rr({cwd:e,env:t.env,logger:t.logger,url:s.url});const c=await or(t,e,s.url);return c?.error!==void 0?{code:h.UNAVAILABLE,deployment:s,descriptor:r,healthCheck:c,mintedSecretsFile:a,validation:i}:{...await ir(t,e,r,i,n,a),deployment:s,healthCheck:c}},cr=(e,r,a)=>{const t=y(e,w);if(!p(t))return;let n;try{n=O(k(t,"utf8")).length}catch{return}if(n===0)return;const o=a.toolchain?.secretPut!==void 0;r.warn(o?`Note: \`lunora deploy\` does not push secrets. ${w} has ${String(n)} key(s); if you changed them, run \`lunora env push --yes\` to update the deployed secrets.`:`Note: ${a.name} deploys read no secrets. ${w} has ${String(n)} key(s) that only the dev server sees; put the values the deployed worker needs in wrangler \`vars\`.`)},lr=async e=>{let r=[];try{r=ne(await B({projectRoot:e,schemaDir:F(e)}))}catch{}const a=ae(r).map(n=>n.key);let t=[];try{const n=y(e,w);p(n)&&(t=O(k(n,"utf8")).map(o=>o.key).filter(o=>Re(o)))}catch{}return[...new Set([...a,...t])]},dr=async(e,r,a,t)=>{const{logger:n}=r,o=r.spawner??$,i=b(e),s=r.env===void 0?"":` --env ${r.env}`,c=t.toolchain?.secretPut;if(c===void 0)return n.error(`deploy target "${t.id}" has no secret store; cannot push secrets`),{minted:[],ok:!1};const d=[];for(const l of a){const m=oe(),u=c({environment:r.env,key:l,temporary:r.temporary}),g=R(i,u),f=await o({args:g.args,command:g.command,cwd:e,input:m});if(f.code!==0)return n.error(`failed to push secret ${l} (exit ${String(f.code)}); set it manually with \`wrangler secret put ${l}${s}\`.`),{minted:d,ok:!1};d.push({key:l,value:m}),n.success(`generated + pushed ${l}`)}return{minted:d,ok:!0}},ur=/^[\w-]+$/u,D=[".dev.vars",".dev.vars.*","!.dev.vars.example"],gr=/\r?\n/u,mr=(e,r)=>{const a=y(e,".gitignore");try{const t=p(a)?k(a,"utf8"):"",n=new Set(t.split(gr).map(c=>c.trim())),o=D.filter(c=>!n.has(c));if(o.length===0)return;const i=o.some(c=>!c.startsWith("!"))?[...o.filter(c=>!c.startsWith("!")),...D.filter(c=>c.startsWith("!"))]:o,s=t.length>0&&!t.endsWith(`
|
|
1
|
+
import{join as Q,dirname as Z}from"node:path";import{discoverMigrations as ee,readServiceBindings as re,runCodegen as te}from"@lunora/codegen";import{readLinkedProject as U,execArgsFor as O,detectPackageManager as b,discoverContainerInfo as B,COMPOSED_WORKER_ENTRY as _,writeLinkedProject as ne,discoverSchemaInfo as F,DEV_VARS_FILE as w,parseDevVariableEntries as M,isMintableSecretKey as T,packageNamesFromBindings as ae,inferLunoraBindings as W,resolveSchemaDirectory as R,requiredSecrets as oe,generateSecretValue as ie,toolchainExecArgs as A,upsertDevVariableLine as se,writeDevVariablesFileAtomically as ce,resolveDeployDriver as j,planToolchainInvocation as V,runPostCodegenHook as le}from"@lunora/config";import{findWranglerFile as H,readWranglerJsonc as C,mergeWranglerEnvironment as G,warnCloudflareCliConfigOnce as de,validateWranglerProject as ue,reconcileWranglerBindings as ge,reconcileWranglerCompatibilityDate as me,reconcileWranglerCrons as fe,describePreservedCrons as ve}from"@lunora/config/cloudflare";import{Spinner as he}from"@visulima/spinner";import{r as pe,a as ye,e as we}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as ke,a as be}from"../packem_shared/deploy-target-DCWwiuAe.mjs";import{m as $e,e as Se,i as De,b as Ee,a as Re}from"../packem_shared/secret-key-BCrqNJ68.mjs";import{w as Ae}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{d as je}from"../packem_shared/command-CAXl2A1S.mjs";import{r as P}from"../packem_shared/wrangler-name-Dsk5K1f-.mjs";import{EXIT_CODE as v}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{containerBuildTag as Ce}from"@lunora/container";import{a as Pe,i as xe}from"../packem_shared/docker-DpVxvYpL.mjs";import{defaultSpawner as $}from"../packem_shared/createRecordingSpawner-Ch7zuQQE.mjs";import{r as K}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{p as _e,H as Te,a as Ne,r as Ie}from"../packem_shared/health-probe-Bw9JFfIy.mjs";import{existsSync as p,readFileSync as k,writeFileSync as q}from"node:fs";import{join as y}from"@visulima/path";import{Project as Le}from"ts-morph";import{runMigrateDataCommand as Ue}from"../packem_shared/runMigrateGenerateCommand-Ii_WMZEA.mjs";import{c as Oe}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{l as Be}from"../packem_shared/wrangler-secrets-3chIVv3H.mjs";const Fe=e=>{const{cwd:r,env:a,logger:t,mintedSecretsFile:n}=e;try{const o=U(r),i=o?.workerName??P(r),s=e.url??o?.workerUrl;t.success("deploy complete"),t.info(` worker: ${i??"(see wrangler output above)"}`),a!==void 0&&t.info(` env: ${a}`),s===void 0?t.info(" url: run `lunora link --url <https://your-worker>` to record it"):t.info(` url: ${s}`),n!==void 0&&t.info(` secrets: generated value(s) recorded in ${n}`),e.logsAvailable&&t.info(" logs: lunora logs")}catch{}},Me=async e=>{if(e.targets.length===0)return{builtTags:[],code:0};if(!(e.railpackAvailable??Pe)()){const t="deploy blocked: a container uses `image: { build }` (Railpack), but Railpack isn't ready. Install the `railpack` CLI and start a BuildKit instance, e.g. `docker run --rm --privileged -d --name buildkit moby/buildkit` then `export BUILDKIT_HOST=docker-container://buildkit`. Alternatively switch the container's `image` to a Dockerfile path or a pre-built registry reference.";return e.logger.error(t),{builtTags:[],code:1,error:t}}const r=e.spawner??$,a=[];for(const t of e.targets){const n=Ce(t.exportName),o={args:["build",t.buildDir,"--name",n],command:"railpack",cwd:e.cwd},i=O(b(e.cwd),"wrangler",["containers","push",n]),s={args:i.args,command:i.command,cwd:e.cwd};e.logger.info(`railpack: building "${t.exportName}" → ${n} from ${t.buildDir}`);const c=await r(o);if(c.code!==0){const l=`railpack build failed for container "${t.exportName}" (${t.buildDir})`;return e.logger.error(l),{builtTags:a,code:c.code,error:l}}e.logger.info(`railpack: pushing ${n} to the Cloudflare Registry`);const d=await r(s);if(d.code!==0){const l=`wrangler containers push failed for "${t.exportName}" (${n})`;return e.logger.error(l),{builtTags:a,code:d.code,error:l}}a.push(n)}return{builtTags:a,code:0}},We=e=>{const a=[H(e),Q(e,"package.json")].filter(t=>t!==void 0&&p(t)).map(t=>[t,k(t,"utf8")]);return()=>{for(const[t,n]of a)k(t,"utf8")!==n&&q(t,n,"utf8")}},Y="<replace-with-d1-create-id>",N=e=>Array.isArray(e)?e.filter(r=>r!=null):void 0,x=(e,r)=>{const a=H(e);if(!a)return;const{parsed:t}=C(a);if(t===void 0)return;const{error:n,merged:o}=G(t,r),i=n===void 0?o:t,{containers:s,d1_databases:c,vars:d}=i;return{containers:N(s),d1_databases:N(c),vars:typeof d=="object"&&d!==null&&!Array.isArray(d)?d:void 0}},Ve=/^127(?:\.\d{1,3}){3}$/,He=e=>{try{const{hostname:r}=new URL(e);return r==="localhost"||Ve.test(r)||r==="::1"||r==="[::1]"}catch{return!1}},Ge=e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"),Ke=(e,r,a,t="deploy",n)=>{const o=(x(e,n)?.containers??[]).filter(s=>typeof s?.image=="string"&&Ge(s.image));if(o.length===0||a())return;const i=`${t} blocked: wrangler.jsonc declares ${String(o.length)} container(s) built from a local Dockerfile, but no Docker-compatible engine is available. Start Docker (or Colima), or point the container's \`image\` at a pre-built registry reference. Note: container images must target linux/amd64.`;return r.error(i),i},z=e=>p(y(e,_))?_:void 0,qe=(e,r,a="deploy")=>{for(const t of B(e,"lunora").containers){const n=t.schedulingPolicy===void 0?t.image:void 0,i=[...n?.kind==="dockerfile"?[{field:"image",path:n.dockerfilePath}]:[],...Object.entries(t.schedulingPolicy==="durable_object"?t.images??{}:{}).flatMap(([s,c])=>c.kind==="dockerfile"?[{field:`images["${s}"]`,path:c.dockerfilePath}]:[])].find(s=>!p(y(e,s.path)));if(i!==void 0){const s=`${a} blocked: container "${t.exportName}" references a Dockerfile at "${i.path}" that does not exist. Create it or fix the \`${i.field}\` path in lunora/containers.ts.`;return r.error(s),s}if(n?.kind==="build"&&!p(y(e,n.buildDir))){const s=`${a} blocked: container "${t.exportName}" references a Railpack build directory "${n.buildDir}" that does not exist. Create it or fix the \`image.build\` path in lunora/containers.ts.`;return r.error(s),s}}},Ye=(e,r)=>(x(e,r)?.d1_databases??[]).find(a=>a.database_id===Y)?.binding,ze=e=>{if(!e.migrate||e.dryRun||e.preview)return;if(e.migrateUrl===void 0){const a="--migrate requires --migrate-url <https://your-worker> — the deploy target URL is only known after wrangler runs, and this gate runs before it; refusing to default to localhost";return e.logger.error(a),a}if(e.migrateYes!==!0){const a="--migrate runs production data migrations after deploy. Re-run with --migrate-yes to confirm.";return e.logger.error(a),a}const r=e.migrateToken??process.env.LUNORA_ADMIN_TOKEN;if(r===void 0||r===""){const a="admin token required for --migrate — pass --migrate-token or set LUNORA_ADMIN_TOKEN";return e.logger.error(a),a}},Je=(e,r,a="deploy",t)=>{const n=Ye(e,t);if(n===void 0)return;const o=`${a} blocked: the "${n}" D1 binding has a placeholder database_id ("${Y}"). Run \`wrangler d1 create <name>\` to create the database, then replace the placeholder in wrangler.jsonc with the real id before deploying.`;return r.error(o),o},Xe=(e,r,a="deploy",t)=>{const n=x(e,t)?.vars;if(!n)return;const o=Object.entries(n).filter(([,s])=>typeof s=="string"&&He(s)).map(([s])=>s).toSorted((s,c)=>s.localeCompare(c));if(o.length===0)return;const i=`${a} blocked: ${o.join(", ")} in wrangler.jsonc point at localhost. A deployed Worker can't reach a loopback address, so this silently breaks scheduled-job dispatch, reverse cross-shard relations, and auth callbacks. Set each to the deployed worker's public URL (or move it to a secret with \`wrangler secret put\`) before deploying.`;return r.error(i),i},Qe=(e,r,a)=>{const t=Je(e,r.logger,a,r.env);if(t!==void 0)return{code:v.USAGE,error:t};const n=Xe(e,r.logger,a,r.env);if(n!==void 0)return{code:v.USAGE,error:n};const o=qe(e,r.logger,a);if(o!==void 0)return{code:v.USAGE,error:o};const i=Ke(e,r.logger,r.dockerAvailable??xe,a,r.env);return i===void 0?void 0:{code:v.MISSING_DEPENDENCY,error:i}},Ze=/https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u,er=/https:\/\/[^\s"'<>]+/u,rr=e=>{if(e===void 0)return;const r=Ze.exec(e);return r?r[0]:er.exec(e)?.[0]},I=e=>e===void 0?"":` (--env ${e})`,tr=({cwd:e,env:r,logger:a,now:t,url:n})=>{if(n!==void 0)try{const o=U(e);if(o!==void 0){if(o.workerUrl===n&&o.env===r)return;a.warn(`link: .lunora/project.json records ${o.workerUrl??"(no url)"}${I(o.env)}, but this deploy published ${n}${I(r)}. Keeping the recorded value — run \`lunora link --url ${n}${r===void 0?"":` --env ${r}`}\` to update it.`);return}const i=(t??(()=>new Date().toISOString()))();ne(e,{env:r,linkedAt:i,workerName:P(e),workerUrl:n}),a.success(`link: recorded ${n} in .lunora/project.json (run \`lunora link\` to change)`)}catch{}},nr=async(e,r)=>{const a=new Le({skipAddingFilesFromTsConfig:!0}),t=y(r,"lunora");let n;try{n=ee(a,t)}catch(o){const i=o instanceof Error?o.message:String(o);return e.logger.warn(`--migrate: could not discover migrations (${i}); skipping`),0}if(n.length===0)return e.logger.info("--migrate: no data migrations declared in lunora/"),0;e.logger.info(`--migrate: running ${String(n.length)} migration(s) against deployed worker`);for(const o of n){e.logger.info(`--migrate: up "${o.id}" (table "${o.table}")`);const i={cwd:r,fetchImpl:e.fetchImpl,id:o.id,logger:e.logger,prod:!0,subcommand:"up",token:e.migrateToken,url:e.migrateUrl,yes:e.migrateYes===!0},s=await Ue(i);if(s.code!==0)return e.logger.error(`--migrate: migration "${o.id}" failed — see output above`),s.code;e.logger.success(`--migrate: "${o.id}" applied`)}return 0},ar=async(e,r)=>{const{info:a}=F(r,"lunora"),t=a?.vectorMetadata??[];if(t.length===0)return;const n=[];for(const s of t){const c=$e(s.kind);if(c===void 0){e.logger.warn(`vector index "${s.index}" declares metadata "${s.property}", whose column type cannot be filtered on in Vectorize — it is stored with each vector but no filter will match it.`);continue}n.push({index:s.index,property:s.property,type:c})}if(n.length===0)return;const i=(await Se({cwd:r,entries:n,exec:O(b(r),"wrangler",[]),logger:e.logger,spawner:e.spawner??$})).filter(s=>s.status!=="failed").length;i>0&&e.logger.success(`vectorize metadata indexes ready: ${String(i)}/${String(n.length)}`)},L=5,or=2e3,ir=async(e,r,a)=>{if(e.healthCheck!==!0)return;const t=a??K({cwd:r,env:e.env});if(t===void 0){const o="--health-check: the deploy succeeded, but no URL to probe could be resolved — wrangler's output carried none and this checkout has no link for this environment. Run `lunora link --url <https://your-worker>` and re-deploy, or drop --health-check.";return e.logger.error(o),{error:o,ok:!1,url:""}}const n=await _e({attempts:L,baseUrl:t,delayMs:or,fetchImpl:e.healthFetch,paths:[Te,Ne],sleep:e.healthSleep});return n.error===void 0?(e.logger.success(`health check ok (${n.url})`),{ok:!0,url:n.url}):(e.logger.error(`--health-check: the deploy succeeded, but the new version did not answer after ${String(L)} attempt(s) — ${n.error}`),{error:n.error,ok:!1,url:n.url})},sr=async(e,r,a,t,n,o)=>{await ar(e,r);const i=e.migrate?await nr(e,r):0;return i===0&&n?.(),{code:i,descriptor:a,mintedSecretsFile:o,validation:t}},cr=async({cwd:e,descriptor:r,mintedSecretsFile:a,options:t,reblessSchemaBaseline:n,stdout:o,validation:i})=>{const s={deployedAt:new Date().toISOString(),dryRun:t.dryRun===!0,env:t.env,preview:t.preview===!0,url:t.dryRun===!0?void 0:rr(o),workerName:P(e)};if(t.dryRun===!0||t.preview===!0)return t.healthCheck===!0&&t.logger.warn(`--health-check skipped: ${t.dryRun===!0?"a dry run publishes nothing":"a preview version serves no live traffic"}`),{code:0,deployment:s,descriptor:r,mintedSecretsFile:a,validation:i};t.temporary!==!0&&tr({cwd:e,env:t.env,logger:t.logger,url:s.url});const c=await ir(t,e,s.url);return c?.error!==void 0?{code:v.UNAVAILABLE,deployment:s,descriptor:r,healthCheck:c,mintedSecretsFile:a,validation:i}:{...await sr(t,e,r,i,n,a),deployment:s,healthCheck:c}},lr=(e,r,a)=>{const t=y(e,w);if(!p(t))return;let n;try{n=M(k(t,"utf8")).length}catch{return}if(n===0)return;const o=a.toolchain?.secretPut!==void 0;r.warn(o?`Note: \`lunora deploy\` does not push secrets. ${w} has ${String(n)} key(s); if you changed them, run \`lunora env push --yes\` to update the deployed secrets.`:`Note: ${a.name} deploys read no secrets. ${w} has ${String(n)} key(s) that only the dev server sees; put the values the deployed worker needs in wrangler \`vars\`.`)},dr=async e=>{let r=[];try{r=ae(await W({projectRoot:e,schemaDir:R(e)}))}catch{}const a=oe(r).map(n=>n.key);let t=[];try{const n=y(e,w);p(n)&&(t=M(k(n,"utf8")).map(o=>o.key).filter(o=>De(o)))}catch{}return[...new Set([...a,...t])]},ur=async(e,r,a,t)=>{const{logger:n}=r,o=r.spawner??$,i=b(e),s=r.env===void 0?"":` --env ${r.env}`,c=t.toolchain?.secretPut;if(c===void 0)return n.error(`deploy target "${t.id}" has no secret store; cannot push secrets`),{minted:[],ok:!1};const d=[];for(const l of a){const g=ie(),u=c({environment:r.env,key:l,temporary:r.temporary}),m=A(i,u),f=await o({args:m.args,command:m.command,cwd:e,input:g});if(f.code!==0)return n.error(`failed to push secret ${l} (exit ${String(f.code)}); set it manually with \`wrangler secret put ${l}${s}\`.`),{minted:d,ok:!1};d.push({key:l,value:g}),n.success(`generated + pushed ${l}`)}return{minted:d,ok:!0}},gr=/^[\w-]+$/u,D=[".dev.vars",".dev.vars.*","!.dev.vars.example"],mr=/\r?\n/u,fr=(e,r)=>{const a=y(e,".gitignore");try{const t=p(a)?k(a,"utf8"):"",n=new Set(t.split(mr).map(c=>c.trim())),o=D.filter(c=>!n.has(c));if(o.length===0)return;const i=o.some(c=>!c.startsWith("!"))?[...o.filter(c=>!c.startsWith("!")),...D.filter(c=>c.startsWith("!"))]:o,s=t.length>0&&!t.endsWith(`
|
|
2
2
|
`)?`
|
|
3
|
-
`:"";
|
|
3
|
+
`:"";q(a,`${t}${s}
|
|
4
4
|
# Lunora — never commit a minted secret
|
|
5
5
|
${i.join(`
|
|
6
6
|
`)}
|
|
7
|
-
`,"utf8"),r.info(`.gitignore: added ${o.join(", ")} so the recorded secret cannot be committed`)}catch(t){r.warn(`could not update .gitignore (${t instanceof Error?t.message:String(t)}) — add \`${D.join("` and `")}\` by hand before committing.`)}},fr=(e,r,a)=>{if(a.length===0)return;const t=a.map(s=>s.key).join(", ");if(r.env!==void 0&&!ur.test(r.env)){r.logger.warn(`${t}: minted and pushed for --env ${r.env}, but "${r.env}" isn't a safe filename fragment — the value could not be recorded. Capture it manually if you need it again.`);return}const n=r.env===void 0?w:`${w}.${r.env}`;mr(e,r.logger);const o=y(e,n);let i=p(o)?k(o,"utf8"):"";for(const s of a)i=ie(i,s.key,s.value);return se(o,i),r.logger.success(r.env===void 0?`${t}: value(s) recorded in ${n}`:`${t}: value(s) recorded in ${n} (kept separate from ${w} so \`lunora dev\` and a plain \`lunora env push\` don't inherit the --env ${r.env} value)`),n},hr=async(e,r,a,t)=>{if(r.dryRun===!0||r.preview===!0)return{};const{logger:n}=r,o=r.env===void 0?"":` --env ${r.env}`;let i;try{i=await(r.secretLister??Oe)({cwd:e,env:r.env,temporary:r.temporary})}catch{return{}}if(!i.ok)return{};const s=new Set(i.names),d=(await lr(e)).filter(u=>!s.has(u));if(d.length===0)return{};if(!a)return{error:`missing required secret(s) on the deploy target: ${d.join(", ")}. Set them with \`wrangler secret put <KEY>${o}\` (or \`lunora env generate --set\` then \`lunora env push --yes${o}\`), then re-deploy.`};for(const u of d.filter(g=>!x(g)))n.warn(`required secret ${u} is not set on the target — set it with: wrangler secret put ${u}${o}`);const l=d.filter(u=>x(u));if(l.length===0)return{};if(await(r.secretConfirm??Ue())(`${String(l.length)} required secret(s) not set on the target (${l.join(", ")}). Generate strong values and push them now?`)){const{minted:u,ok:g}=await dr(e,r,l,t),f=fr(e,r,u);return g?{mintedSecretsFile:f}:{error:"failed to push required secret(s) — set them manually and re-deploy",mintedSecretsFile:f}}return n.warn(`${String(l.length)} required secret(s) not set on the target: ${l.join(", ")}. Generate + push with \`lunora env generate --set\` then \`lunora env push --yes${o}\`.`),{}},Y=e=>e.format==="json"?!1:e.interactive!==void 0?e.interactive:process.stdout.isTTY&&!process.env.CI,vr=async(e,r)=>{if(r.dryRun===!0)return;const a=U(e,"lunora").containers.flatMap(n=>n.schedulingPolicy===void 0&&n.image.kind==="build"?[{buildDir:n.image.buildDir,exportName:n.exportName}]:[]);if(a.length===0)return;const t=await Fe({cwd:e,logger:r.logger,railpackAvailable:r.railpackAvailable,spawner:r.spawner,targets:a});return t.code===0?void 0:t.error??"railpack build failed"},pr=(e,r,a)=>{if(a!==void 0)try{const t=fe(e,a);t.changed&&r.success(`synced ${String(a.length)} cron trigger(s) → ${t.wranglerPath??"wrangler.jsonc"}`);for(const o of t.warnings)r.warn(o);const n=he(t.preserved);n!==void 0&&r.info(n)}catch(t){const n=t instanceof Error?t.message:String(t);r.warn(`cron trigger sync skipped: ${n}`)}},yr=async(e,r,a,t,n)=>{try{A(t);const o=await B({projectRoot:e,schemaDir:F(e)}),i=ge(e,o,n),s=i.wranglerPath??"wrangler.jsonc";if(i.added.length>0&&r.success(`provisioned bindings: ${i.added.join(", ")} → ${s}`),i.updated.length>0&&r.success(`updated bindings: ${i.updated.join(", ")} → ${s}`),i.devConfig!==void 0){const{added:c,path:d,updated:l}=i.devConfig;r.success(`dev sidecar bindings: ${[...c,...l].join(", ")} → ${d}`)}for(const c of i.warnings)r.warn(c)}catch(o){const i=o instanceof Error?o.message:String(o);r.warn(`binding inference skipped: ${i}`)}try{const o=me(e);o.changed&&r.success(`bumped compatibility_date to ${o.date??"unknown"} (Workers Cache enabled) → ${o.wranglerPath??"wrangler.jsonc"}`)}catch(o){const i=o instanceof Error?o.message:String(o);r.warn(`compatibility date sync skipped: ${i}`)}pr(e,r,a)},wr=async(e,r,a,t,n,o,i,s)=>{let c;r?(c=new ve({name:"dots"}),c.start("running codegen")):a.info("running codegen");try{const d=ee({apiSpec:t,projectRoot:e,target:n});c?.succeed("codegen complete"),c||a.success("codegen complete");const l=ye(d.platformDiagnostics,a);if(l.errors.length>0)return{error:l.errors.join("; ")};const{errorAdvisories:m,names:u,shouldBlock:g}=we(d.advisories,s);if(g){const v=`${m.length.toString()} ERROR-level ${m.length===1?"advisory":"advisories"} (${u.join(", ")}). Pass --no-strict-advisories to downgrade this to a warning and continue.`;return a.error(v),{error:v}}const f=await ce({cwd:e,logger:a,spawner:o,stdoutToStderr:i});return f.error!==void 0?{error:f.error}:{result:d}}catch(d){c?.failed("codegen failed");const l=d instanceof Error?d.message:String(d);return a.error(`codegen failed: ${l}`),{error:`codegen failed: ${l}`}}},kr=(e,r)=>({dryRun:r.dryRun,entry:q(e),environment:r.env,outDir:r.outDir,preview:r.preview,temporary:r.temporary}),z=(e,r,a)=>{const{toolchain:t}=a;if(t===void 0)throw new Error(`deploy target "${a.id}" has no command-line toolchain`);const n=kr(e,r);return W(a,e,"deploy",o=>t.deploy({...n,configPath:o}))},br=(e,r,a)=>{const t=z(e,r,a),n=q(e);return n!==void 0&&r.logger.info(`class-B composition: deploying ${n} (overrides wrangler main)`),r.temporary&&r.logger.info("temporary account: deploying to a short-lived Cloudflare account (~60min); wrangler will print a claim URL"),r.dryRun&&r.logger.info("dry run: validating + bundling without publishing"),r.outDir!==void 0&&r.logger.info(`build artifact: emitting bundle to ${r.outDir}`),t.commit(),t.projection!==void 0&&t.projection.dropped.length>0&&r.logger.warn(`${a.name} ignores these wrangler keys, so they were left out of ${t.projection.configPath}: ${t.projection.dropped.join(", ")}`),t.command},E=(e,r)=>({code:h.USAGE,descriptor:void 0,error:e,validation:{problems:[],wranglerPath:void 0},...r}),$r=(e,r)=>{for(const a of e.report?.warnings??[])r.warn(`wrangler.jsonc: ${a}`);if(e.problems.length===0)return!1;r.error("wrangler.jsonc validation failed:");for(const a of e.problems)r.error(` - ${a}`);return!0},Sr=(e,r,a)=>{const t=r.format==="json",n=r.dryRun!==!0,o=br(e,r,a),i=R(b(e),o);return{args:i.args,captureStdout:n&&!t,captureStdoutSilently:n&&t,command:i.command,cwd:e,stdoutToStderr:t&&!n}},Dr=async(e,r)=>{const a=e.cwd??process.cwd(),t=Y(e),n=pe(e),o={problems:[],wranglerPath:void 0},i=be(a,e.target);if(i.target===void 0){const u=i.error??"unknown deploy target";return e.logger.error(u),{error:u,validation:o}}const{target:s}=i;try{z(a,e,A(s))}catch(u){const g=u instanceof Error?u.message:String(u);return e.logger.error(g),{error:g,target:s,validation:o}}let c;if(!e.skipCodegen){const u=await wr(a,t,e.logger,e.apiSpec,s,e.spawner,e.format==="json",n);if(u.error!==void 0)return{error:u.error,target:s,validation:o};c=u.result}let d;if(c!==void 0){const u=Ne({allowDrift:e.allowSchemaDrift===!0,codegen:c,command:r,logger:e.logger,updateBaseline:e.updateSchemaBaseline===!0});if(u.blocked)return{error:`schema drift gate blocked ${r}`,schemaDrift:{blocked:!0,reason:u.reason},target:s,validation:o};d=u.rebless}await yr(a,e.logger,c?.cronTriggers,s,e.env);const l=Xe(a,e,r);if(l!==void 0)return{code:l.code,error:l.error,target:s,validation:o};const m=ue({environment:e.env,projectRoot:a});return $r(m,e.logger)?{error:"wrangler validation failed",target:s,validation:m}:{codegen:c,reblessSchemaBaseline:d,target:s,validation:m}},Er=e=>{if(e.skipServices===!0)return"--skip-services";if(e.preview===!0)return"--preview uploads the app version only";if(e.temporary===!0)return"--temporary deploys the app to a throwaway account"},Rr=async(e,r,a,t)=>{const{error:n,services:o}=Z(e);if(n!==void 0)return n;if(o.length===0)return;const{toolchain:i}=a,s=i===void 0?`target "${a.id}" has no deploy command`:Er(r);if(s!==void 0||i===void 0){const l=o.map(m=>m.worker).join(", ");r.logger.warn(`services not deployed (${s??""}): ${l} — deploy them yourself if the app calls anything new`);return}const c=b(e),d=[...new Map(o.map(l=>[l.wranglerPath,l])).values()];for(const l of d){const m=X(l.wranglerPath);let u;try{u=W(a,m,"deploy",v=>i.deploy({configPath:v??l.wranglerPath,dryRun:r.dryRun===!0,environment:r.env}))}catch(v){return`service ${l.name} (${l.worker}): ${v instanceof Error?v.message:String(v)}`}u.commit();const g=R(c,u.command);r.logger.info(`deploying service ${l.name} (${l.worker}) via ${g.command} ${g.args.join(" ")}`);const f=await t({args:g.args,command:g.command,cwd:m,stdoutToStderr:r.format==="json"});if(f.code!==0)return`service ${l.name} (${l.worker}): ${g.command} ${g.args.join(" ")} exited ${String(f.code)} — stopping before the app`}},Ar=async(e,r,a,t)=>{if(r!=="cloudflare")return;const n=e===void 0?void 0:V(e).parsed,o=(a===void 0?void 0:n?.env?.[a]?.account_id)??n?.account_id,i=await Ae({accountId:o});(i.verdict==="near"||i.verdict==="full")&&t.warn(i.fix===void 0?i.message:`${i.message} ${i.fix}`)},jr=async e=>{const r=e.cwd??process.cwd(),a=Y(e),t=await Dr(e,e.commandName??"deploy");if(t.error!==void 0){if(t.validation.problems.length>0)return{code:h.USAGE,descriptor:void 0,error:t.error,validation:t.validation};const S=t.schemaDrift===void 0?void 0:{schemaDrift:t.schemaDrift};return E(t.error,{...S,...t.code===void 0?{}:{code:t.code}})}const{reblessSchemaBaseline:n,validation:o}=t,i=A(t.target),s=Ye(e);if(s!==void 0)return E(s);const c=i.toolchain?.prebuildsContainerImages===!0?await vr(r,e):void 0;if(c!==void 0)return E(c);cr(r,e.logger,i),de(r,S=>{e.logger.warn(S)}),await Ar(o.wranglerPath,t.target,e.env,e.logger);const{error:d,mintedSecretsFile:l}=await hr(r,e,a,i);if(d!==void 0)return e.logger.error(d),{code:h.USAGE,descriptor:void 0,error:d,mintedSecretsFile:l,validation:o};const m=e.spawner??$,u=await Rr(r,e,i,m);if(u!==void 0)return{code:h.FAILURE,descriptor:void 0,error:u,mintedSecretsFile:l,validation:o};const g=Sr(r,e,i);e.logger.info(`deploying via ${g.command} ${g.args.join(" ")}`);const f=await m(g);return g.captureStdoutSilently===!0&&f.stdout!==void 0&&f.stdout!==""&&process.stderr.write(f.stdout),f.code!==0?{code:f.code,descriptor:g,mintedSecretsFile:l,validation:o}:{...await sr({cwd:r,descriptor:g,mintedSecretsFile:l,options:e,reblessSchemaBaseline:n,stdout:f.stdout,validation:o}),logsAvailable:i.toolchain?.tail!==void 0}},Cr=async e=>{const{logger:r}=e,a=e.dryRun===!0?We(e.cwd??process.cwd()):void 0;let t;try{if(t=await jr({...e,logger:r}),t.code===0&&e.emitBindings!==void 0){const{error:n}=$e({destination:e.emitBindings,logger:r,projectRoot:e.cwd??process.cwd()});n!==void 0&&(r.error(n),t={...t,code:h.USAGE})}}finally{a?.()}if(e.format==="json")return t;if(t.code===0&&e.dryRun!==!0&&e.preview!==!0)Be({cwd:e.cwd??process.cwd(),env:e.env,logger:e.logger,logsAvailable:t.logsAvailable===!0,mintedSecretsFile:t.mintedSecretsFile,url:t.deployment?.url});else if(t.code===0&&e.preview===!0){const n=t.deployment?.url;e.logger.success(n===void 0?"preview version uploaded":`preview version uploaded — ${n}`)}return t},Zr=Se(async({cwd:e,format:r,logger:a,options:t})=>{const n=await Cr({allowSchemaDrift:t.allowSchemaDrift===!0,apiSpec:ke(t.apiSpec),cwd:e,dryRun:t.dryRun===!0,env:t.env,format:r,healthCheck:t.healthCheck===!0,logger:a,migrate:t.migrate===!0,migrateToken:t.migrateToken,migrateUrl:H({cwd:e,env:t.env,url:t.migrateUrl}),migrateYes:t.migrateYes===!0,preview:t.preview===!0,skipCodegen:t.prebuilt===!0,skipServices:t.skipServices===!0,strictAdvisories:t.strictAdvisories,target:t.target,temporary:t.temporary===!0,updateSchemaBaseline:t.updateSchemaBaseline===!0});return{code:n.code,data:{deployment:n.deployment,healthCheck:n.healthCheck,mintedSecretsFile:n.mintedSecretsFile,schemaDrift:n.schemaDrift,validation:n.validation},error:n.error}});export{Zr as execute,yr as provisionBindings,Cr as runDeployCommand,Dr as runPreDeployPipeline};
|
|
7
|
+
`,"utf8"),r.info(`.gitignore: added ${o.join(", ")} so the recorded secret cannot be committed`)}catch(t){r.warn(`could not update .gitignore (${t instanceof Error?t.message:String(t)}) — add \`${D.join("` and `")}\` by hand before committing.`)}},vr=(e,r,a)=>{if(a.length===0)return;const t=a.map(s=>s.key).join(", ");if(r.env!==void 0&&!gr.test(r.env)){r.logger.warn(`${t}: minted and pushed for --env ${r.env}, but "${r.env}" isn't a safe filename fragment — the value could not be recorded. Capture it manually if you need it again.`);return}const n=r.env===void 0?w:`${w}.${r.env}`;fr(e,r.logger);const o=y(e,n);let i=p(o)?k(o,"utf8"):"";for(const s of a)i=se(i,s.key,s.value);return ce(o,i),r.logger.success(r.env===void 0?`${t}: value(s) recorded in ${n}`:`${t}: value(s) recorded in ${n} (kept separate from ${w} so \`lunora dev\` and a plain \`lunora env push\` don't inherit the --env ${r.env} value)`),n},hr=async(e,r,a,t)=>{if(r.dryRun===!0||r.preview===!0)return{};const{logger:n}=r,o=r.env===void 0?"":` --env ${r.env}`;let i;try{i=await(r.secretLister??Be)({cwd:e,env:r.env,temporary:r.temporary})}catch{return{}}if(!i.ok)return{};const s=new Set(i.names),d=(await dr(e)).filter(u=>!s.has(u));if(d.length===0)return{};if(!a)return{error:`missing required secret(s) on the deploy target: ${d.join(", ")}. Set them with \`wrangler secret put <KEY>${o}\` (or \`lunora env generate --set\` then \`lunora env push --yes${o}\`), then re-deploy.`};for(const u of d.filter(m=>!T(m)))n.warn(`required secret ${u} is not set on the target — set it with: wrangler secret put ${u}${o}`);const l=d.filter(u=>T(u));if(l.length===0)return{};if(await(r.secretConfirm??Oe())(`${String(l.length)} required secret(s) not set on the target (${l.join(", ")}). Generate strong values and push them now?`)){const{minted:u,ok:m}=await ur(e,r,l,t),f=vr(e,r,u);return m?{mintedSecretsFile:f}:{error:"failed to push required secret(s) — set them manually and re-deploy",mintedSecretsFile:f}}return n.warn(`${String(l.length)} required secret(s) not set on the target: ${l.join(", ")}. Generate + push with \`lunora env generate --set\` then \`lunora env push --yes${o}\`.`),{}},J=e=>e.format==="json"?!1:e.interactive!==void 0?e.interactive:process.stdout.isTTY&&!process.env.CI,pr=async(e,r)=>{if(r.dryRun===!0)return;const a=B(e,"lunora").containers.flatMap(n=>n.schedulingPolicy===void 0&&n.image.kind==="build"?[{buildDir:n.image.buildDir,exportName:n.exportName}]:[]);if(a.length===0)return;const t=await Me({cwd:e,logger:r.logger,railpackAvailable:r.railpackAvailable,spawner:r.spawner,targets:a});return t.code===0?void 0:t.error??"railpack build failed"},yr=(e,r,a)=>{if(a!==void 0)try{const t=fe(e,a);t.changed&&r.success(`synced ${String(a.length)} cron trigger(s) → ${t.wranglerPath??"wrangler.jsonc"}`);for(const o of t.warnings)r.warn(o);const n=ve(t.preserved);n!==void 0&&r.info(n)}catch(t){const n=t instanceof Error?t.message:String(t);r.warn(`cron trigger sync skipped: ${n}`)}},wr=async(e,r,a,t,n)=>{try{j(t);const o=await W({projectRoot:e,schemaDir:R(e)}),i=ge(e,o,n),s=i.wranglerPath??"wrangler.jsonc";if(i.added.length>0&&r.success(`provisioned bindings: ${i.added.join(", ")} → ${s}`),i.updated.length>0&&r.success(`updated bindings: ${i.updated.join(", ")} → ${s}`),i.devConfig!==void 0){const{added:c,path:d,updated:l}=i.devConfig;r.success(`dev sidecar bindings: ${[...c,...l].join(", ")} → ${d}`)}for(const c of i.warnings)r.warn(c)}catch(o){const i=o instanceof Error?o.message:String(o);r.warn(`binding inference skipped: ${i}`)}try{const o=me(e);o.changed&&r.success(`bumped compatibility_date to ${o.date??"unknown"} (Workers Cache enabled) → ${o.wranglerPath??"wrangler.jsonc"}`)}catch(o){const i=o instanceof Error?o.message:String(o);r.warn(`compatibility date sync skipped: ${i}`)}yr(e,r,a)},kr=async(e,r,a,t,n,o,i,s)=>{let c;r?(c=new he({name:"dots"}),c.start("running codegen")):a.info("running codegen");try{const d=te({apiSpec:t,projectRoot:e,target:n});c?.succeed("codegen complete"),c||a.success("codegen complete");const l=ye(d.platformDiagnostics,a);if(l.errors.length>0)return{error:l.errors.join("; ")};const{errorAdvisories:g,names:u,shouldBlock:m}=we(d.advisories,s);if(m){const h=`${g.length.toString()} ERROR-level ${g.length===1?"advisory":"advisories"} (${u.join(", ")}). Pass --no-strict-advisories to downgrade this to a warning and continue.`;return a.error(h),{error:h}}const f=await le({cwd:e,logger:a,spawner:o,stdoutToStderr:i});return f.error!==void 0?{error:f.error}:{result:d}}catch(d){c?.failed("codegen failed");const l=d instanceof Error?d.message:String(d);return a.error(`codegen failed: ${l}`),{error:`codegen failed: ${l}`}}},br=(e,r)=>({dryRun:r.dryRun,entry:z(e),environment:r.env,outDir:r.outDir,preview:r.preview,temporary:r.temporary}),X=(e,r,a)=>{const{toolchain:t}=a;if(t===void 0)throw new Error(`deploy target "${a.id}" has no command-line toolchain`);const n=br(e,r);return V(a,e,"deploy",o=>t.deploy({...n,configPath:o}))},$r=(e,r,a)=>{const t=X(e,r,a),n=z(e);return n!==void 0&&r.logger.info(`class-B composition: deploying ${n} (overrides wrangler main)`),r.temporary&&r.logger.info("temporary account: deploying to a short-lived Cloudflare account (~60min); wrangler will print a claim URL"),r.dryRun&&r.logger.info("dry run: validating + bundling without publishing"),r.outDir!==void 0&&r.logger.info(`build artifact: emitting bundle to ${r.outDir}`),t.commit(),t.projection!==void 0&&t.projection.dropped.length>0&&r.logger.warn(`${a.name} ignores these wrangler keys, so they were left out of ${t.projection.configPath}: ${t.projection.dropped.join(", ")}`),t.command},E=(e,r)=>({code:v.USAGE,descriptor:void 0,error:e,validation:{problems:[],wranglerPath:void 0},...r}),Sr=(e,r)=>{for(const a of e.report?.warnings??[])r.warn(`wrangler.jsonc: ${a}`);if(e.problems.length===0)return!1;r.error("wrangler.jsonc validation failed:");for(const a of e.problems)r.error(` - ${a}`);return!0},Dr=(e,r,a)=>{const t=r.format==="json",n=r.dryRun!==!0,o=$r(e,r,a),i=A(b(e),o);return{args:i.args,captureStdout:n&&!t,captureStdoutSilently:n&&t,command:i.command,cwd:e,stdoutToStderr:t&&!n}},Er=async(e,r)=>{const a=e.cwd??process.cwd(),t=J(e),n=pe(e),o={problems:[],wranglerPath:void 0},i=be(a,e.target);if(i.target===void 0){const u=i.error??"unknown deploy target";return e.logger.error(u),{error:u,validation:o}}const{target:s}=i;try{X(a,e,j(s))}catch(u){const m=u instanceof Error?u.message:String(u);return e.logger.error(m),{error:m,target:s,validation:o}}let c;if(!e.skipCodegen){const u=await kr(a,t,e.logger,e.apiSpec,s,e.spawner,e.format==="json",n);if(u.error!==void 0)return{error:u.error,target:s,validation:o};c=u.result}let d;if(c!==void 0){const u=Ie({allowDrift:e.allowSchemaDrift===!0,codegen:c,command:r,logger:e.logger,updateBaseline:e.updateSchemaBaseline===!0});if(u.blocked)return{error:`schema drift gate blocked ${r}`,schemaDrift:{blocked:!0,reason:u.reason},target:s,validation:o};d=u.rebless}await wr(a,e.logger,c?.cronTriggers,s,e.env);const l=Qe(a,e,r);if(l!==void 0)return{code:l.code,error:l.error,target:s,validation:o};const g=ue({environment:e.env,projectRoot:a});return Sr(g,e.logger)?{error:"wrangler validation failed",target:s,validation:g}:{codegen:c,reblessSchemaBaseline:d,target:s,validation:g}},Rr=e=>{if(e.skipServices===!0)return"--skip-services";if(e.preview===!0)return"--preview uploads the app version only";if(e.temporary===!0)return"--temporary deploys the app to a throwaway account"},Ar=async(e,r,a,t)=>{const{error:n,services:o}=re(e);if(n!==void 0)return n;if(o.length===0)return;const{toolchain:i}=a,s=i===void 0?`target "${a.id}" has no deploy command`:Rr(r);if(s!==void 0||i===void 0){const l=o.map(g=>g.worker).join(", ");r.logger.warn(`services not deployed (${s??""}): ${l} — deploy them yourself if the app calls anything new`);return}const c=b(e),d=[...new Map(o.map(l=>[l.wranglerPath,l])).values()];for(const l of d){const g=Z(l.wranglerPath);let u;try{u=V(a,g,"deploy",h=>i.deploy({configPath:h??l.wranglerPath,dryRun:r.dryRun===!0,environment:r.env}))}catch(h){return`service ${l.name} (${l.worker}): ${h instanceof Error?h.message:String(h)}`}u.commit();const m=A(c,u.command);r.logger.info(`deploying service ${l.name} (${l.worker}) via ${m.command} ${m.args.join(" ")}`);const f=await t({args:m.args,command:m.command,cwd:g,stdoutToStderr:r.format==="json"});if(f.code!==0)return`service ${l.name} (${l.worker}): ${m.command} ${m.args.join(" ")} exited ${String(f.code)} — stopping before the app`}},jr=async(e,r,a,t)=>{if(r!=="cloudflare")return;const n=e===void 0?void 0:C(e).parsed,o=(a===void 0?void 0:n?.env?.[a]?.account_id)??n?.account_id,i=await Re({accountId:o});(i.verdict==="near"||i.verdict==="full")&&t.warn(i.fix===void 0?i.message:`${i.message} ${i.fix}`)},Cr=async(e,r,a,t,n)=>{const o=a==="cloudflare"&&r!==void 0?C(r).parsed:void 0;if(o===void 0)return;const i=(G(o,t).merged.artifacts??[]).flatMap(g=>typeof g?.binding=="string"&&typeof g.namespace=="string"?[{binding:g.binding,namespace:g.namespace}]:[]),s=i.length===0?void 0:F(e,R(e)).info?.jurisdiction;if(s===void 0)return;const c=(t===void 0?void 0:o.env?.[t]?.account_id)??o.account_id,d=await Promise.all(i.map(async g=>Ee({...g,accountId:c,jurisdiction:s}))),l=[];for(const g of d){const u=g.fix===void 0?g.message:`${g.message} ${g.fix}`;g.verdict==="unchecked"?n.warn(u):g.verdict!=="ok"&&(n.error(u),l.push(u))}return l.length===0?void 0:l.join(`
|
|
8
|
+
`)},Pr=async e=>{const r=e.cwd??process.cwd(),a=J(e),t=await Er(e,e.commandName??"deploy");if(t.error!==void 0){if(t.validation.problems.length>0)return{code:v.USAGE,descriptor:void 0,error:t.error,validation:t.validation};const S=t.schemaDrift===void 0?void 0:{schemaDrift:t.schemaDrift};return E(t.error,{...S,...t.code===void 0?{}:{code:t.code}})}const{reblessSchemaBaseline:n,validation:o}=t,i=j(t.target),s=ze(e)??await Cr(r,o.wranglerPath,t.target,e.env,e.logger);if(s!==void 0)return E(s);const c=i.toolchain?.prebuildsContainerImages===!0?await pr(r,e):void 0;if(c!==void 0)return E(c);lr(r,e.logger,i),de(r,S=>{e.logger.warn(S)}),await jr(o.wranglerPath,t.target,e.env,e.logger);const{error:d,mintedSecretsFile:l}=await hr(r,e,a,i);if(d!==void 0)return e.logger.error(d),{code:v.USAGE,descriptor:void 0,error:d,mintedSecretsFile:l,validation:o};const g=e.spawner??$,u=await Ar(r,e,i,g);if(u!==void 0)return{code:v.FAILURE,descriptor:void 0,error:u,mintedSecretsFile:l,validation:o};const m=Dr(r,e,i);e.logger.info(`deploying via ${m.command} ${m.args.join(" ")}`);const f=await g(m);return m.captureStdoutSilently===!0&&f.stdout!==void 0&&f.stdout!==""&&process.stderr.write(f.stdout),f.code!==0?{code:f.code,descriptor:m,mintedSecretsFile:l,validation:o}:{...await cr({cwd:r,descriptor:m,mintedSecretsFile:l,options:e,reblessSchemaBaseline:n,stdout:f.stdout,validation:o}),logsAvailable:i.toolchain?.tail!==void 0}},xr=async e=>{const{logger:r}=e,a=e.dryRun===!0?We(e.cwd??process.cwd()):void 0;let t;try{if(t=await Pr({...e,logger:r}),t.code===0&&e.emitBindings!==void 0){const{error:n}=Ae({destination:e.emitBindings,logger:r,projectRoot:e.cwd??process.cwd()});n!==void 0&&(r.error(n),t={...t,code:v.USAGE})}}finally{a?.()}if(e.format==="json")return t;if(t.code===0&&e.dryRun!==!0&&e.preview!==!0)Fe({cwd:e.cwd??process.cwd(),env:e.env,logger:e.logger,logsAvailable:t.logsAvailable===!0,mintedSecretsFile:t.mintedSecretsFile,url:t.deployment?.url});else if(t.code===0&&e.preview===!0){const n=t.deployment?.url;e.logger.success(n===void 0?"preview version uploaded":`preview version uploaded — ${n}`)}return t},rt=je(async({cwd:e,format:r,logger:a,options:t})=>{const n=await xr({allowSchemaDrift:t.allowSchemaDrift===!0,apiSpec:ke(t.apiSpec),cwd:e,dryRun:t.dryRun===!0,env:t.env,format:r,healthCheck:t.healthCheck===!0,logger:a,migrate:t.migrate===!0,migrateToken:t.migrateToken,migrateUrl:K({cwd:e,env:t.env,url:t.migrateUrl}),migrateYes:t.migrateYes===!0,preview:t.preview===!0,skipCodegen:t.prebuilt===!0,skipServices:t.skipServices===!0,strictAdvisories:t.strictAdvisories,target:t.target,temporary:t.temporary===!0,updateSchemaBaseline:t.updateSchemaBaseline===!0});return{code:n.code,data:{deployment:n.deployment,healthCheck:n.healthCheck,mintedSecretsFile:n.mintedSecretsFile,schemaDrift:n.schemaDrift,validation:n.validation},error:n.error}});export{rt as execute,wr as provisionBindings,xr as runDeployCommand,Er as runPreDeployPipeline};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as $}from"./cloudflare-credentials-lC5JtPLe.mjs";const C="https://api.cloudflare.com/client/v4/accounts",b=async({accountId:e,apiToken:r,fetch:t,init:s,path:a})=>{const c=await(t??globalThis.fetch.bind(globalThis))(`${C}/${encodeURIComponent(e)}${a}`,{...s,headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}}),o=await c.text();let n;try{n=JSON.parse(o)}catch{return{ok:!1,status:c.status,text:o}}return!c.ok||typeof n!="object"||n===null||n.success===!1?{ok:!1,status:c.status,text:o}:{body:n,ok:!0}},v=5e3,p=(e,r,t)=>`POST https://api.cloudflare.com/client/v4/accounts/${e}/artifacts/namespaces with body { "namespace": "${r}", "jurisdiction": "${t}" }`,P=async e=>{const{binding:r,jurisdiction:t,namespace:s}=e,a=`Artifacts namespace "${s}" (binding ${r})`,{accountId:c,token:o}=$(e.environment??process.env,e.accountId);if(o===void 0||c===void 0)return{fix:"Set CLOUDFLARE_API_TOKEN (with Artifacts read access) and CLOUDFLARE_ACCOUNT_ID (or `account_id` in wrangler.jsonc) to check it.",message:`the jurisdiction of ${a} was not checked against the schema's "${t}".`,verdict:"unchecked"};let n;try{n=await b({accountId:c,apiToken:o,...e.fetch===void 0?{}:{fetch:e.fetch},init:{signal:AbortSignal.timeout(v)},path:`/artifacts/namespaces/${encodeURIComponent(s)}`})}catch(l){return{message:`the jurisdiction of ${a} could not be read (${l instanceof Error?l.message:String(l)}).`,verdict:"unchecked"}}if(!n.ok&&n.status===404)return{fix:`Create it before the first repo: ${p(c,s,t)}.`,message:`${a} does not exist, and the first repo create() would make it unrestricted — the schema pins data to "${t}".`,verdict:"missing"};if(!n.ok)return{...n.status===401||n.status===403?{fix:`Give CLOUDFLARE_API_TOKEN Artifacts read access on account ${c}.`}:{},message:`the jurisdiction of ${a} could not be read (HTTP ${String(n.status)}).`,verdict:"unchecked"};const{result:i}=n.body,u=typeof i=="object"&&i!==null&&"jurisdiction"in i?i.jurisdiction:void 0;return typeof u!="string"?{message:`the jurisdiction of ${a} could not be read (the response carried none).`,verdict:"unchecked"}:u===t?{message:`${a} is in the "${u}" jurisdiction, as the schema pins.`,verdict:"ok"}:{fix:`A namespace's jurisdiction cannot change: create one with ${p(c,"<name>",t)}, point the binding's "namespace" at it, and move the repos over.`,message:`${a} is in the "${u}" jurisdiction, but the schema pins data to "${t}".`,verdict:"mismatch"}},h=100,d=500,m=10,T=5e3,f="Delete the Workers you no longer need (old preview / staging deploys free their classes), or set `durableObjects: { merge: true }` in lunora.config before an app's first deploy so it spends one class instead of up to three.",k=e=>e>=d?{fix:f,message:`the Cloudflare account has ${String(e)} Durable Object classes — the Workers Paid cap is ${String(d)}, so a deploy that adds one will fail.`,verdict:"full"}:e>=d-m?{fix:f,message:`the Cloudflare account has ${String(e)} of ${String(d)} Durable Object classes (Workers Paid cap).`,verdict:"near"}:e>=h-m&&e<=h?{fix:f,message:`the Cloudflare account has ${String(e)} Durable Object classes — on Workers Free the cap is ${String(h)} (Paid: ${String(d)}).`,verdict:"near"}:{message:`the Cloudflare account has ${String(e)} Durable Object classes (caps: ${String(h)} Free, ${String(d)} Paid).`,verdict:"ok"},x=async(e={})=>{const{accountId:r,token:t}=$(e.environment??process.env,e.accountId);if(t===void 0||r===void 0)return{fix:"Set CLOUDFLARE_API_TOKEN (Workers Scripts Read) and CLOUDFLARE_ACCOUNT_ID (or `account_id` in wrangler.jsonc) to check it.",message:"the account's Durable Object class count was not checked.",verdict:"unchecked"};try{const s=await b({accountId:r,apiToken:t,...e.fetch===void 0?{}:{fetch:e.fetch},init:{signal:AbortSignal.timeout(T)},path:"/workers/durable_objects/namespaces?per_page=1"}),a=s.ok?s.body.result_info:void 0,c=typeof a=="object"&&a!==null&&"total_count"in a?a.total_count:void 0;return typeof c!="number"?{message:`the account's Durable Object class count could not be read${s.ok?"":` (HTTP ${String(s.status)})`}.`,verdict:"unchecked"}:k(c)}catch(s){return{message:`the account's Durable Object class count could not be read (${s instanceof Error?s.message:String(s)}).`,verdict:"unchecked"}}},D=e=>{switch(e){case"boolean":return"boolean";case"date":case"number":case"timestamp":return"number";case"id":case"literal":case"string":return"string";default:return}},j=/already (?:exists|indexed)|duplicate/iu,g=e=>["vectorize","create-metadata-index",e.index,`--property-name=${e.property}`,`--type=${e.type}`],y=async(e,r)=>{try{return await e(r)}catch(t){return{code:1,stderr:t instanceof Error?t.message:String(t)}}},w=async e=>{const{cwd:r,entries:t,exec:s,logger:a,spawner:c}=e,o=[];for(const n of t){const i=await y(c,{args:[...s.args,...g(n)],captureStderr:!0,command:s.command,cwd:r,stdoutToStderr:!0});if(i.code===0){o.push({entry:n,status:"created"});continue}const u=`${i.stderr??""}${i.stdout??""}`;if(j.test(u)){o.push({entry:n,status:"exists"});continue}o.push({entry:n,error:u.trim()||`exit code ${String(i.code)}`,status:"failed"}),a.warn(`could not create the Vectorize metadata index for "${n.property}" on "${n.index}" — filters on that property will match nothing until it exists. Run: wrangler ${g(n).join(" ")}`)}return o},S=e=>e.endsWith("S")?e.slice(0,-1):e,E=e=>e.replaceAll(/([a-z\d])([A-Z])/gu,"$1_$2").toUpperCase().split(/[_-]+/u).filter(r=>r.length>0),A=new Set(["CREDENTIAL","DSN","PASSPHRASE","PASSWD","PASSWORD","SECRET","TOKEN"]),_=["ACCESS_KEY","API_KEY","ENCRYPTION_KEY","PRIVATE_KEY","SIGNING_KEY"],O=new RegExp(`(?:${[...A,..._.map(e=>e.replaceAll("_",""))].join("|")})S?$`,"iu"),I=e=>E(e).some(r=>r==="PUBLIC"||r==="PUBLISHABLE"),L=e=>{if(I(e))return!1;const r=E(e);if(r.some(s=>A.has(S(s))))return!0;const t=S(r.join("_"));return _.some(s=>t===s||t.endsWith(`_${s}`))||O.test(e)};export{x as a,P as b,g as c,w as e,L as i,D as m};
|
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.358",
|
|
4
4
|
"description": "The Lunora CLI: init, dev, deploy, codegen, migrate, seed, doctor, insights, logs, registry, and the rest of the project commands",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agent-skills",
|
|
@@ -52,16 +52,16 @@
|
|
|
52
52
|
},
|
|
53
53
|
"dependencies": {
|
|
54
54
|
"@bomb.sh/tab": "0.0.22",
|
|
55
|
-
"@lunora/advisor": "1.0.0-alpha.
|
|
56
|
-
"@lunora/bindings": "1.0.0-alpha.
|
|
57
|
-
"@lunora/codegen": "1.0.0-alpha.
|
|
58
|
-
"@lunora/config": "1.0.0-alpha.
|
|
55
|
+
"@lunora/advisor": "1.0.0-alpha.196",
|
|
56
|
+
"@lunora/bindings": "1.0.0-alpha.100",
|
|
57
|
+
"@lunora/codegen": "1.0.0-alpha.273",
|
|
58
|
+
"@lunora/config": "1.0.0-alpha.317",
|
|
59
59
|
"@lunora/container": "1.0.0-alpha.69",
|
|
60
|
-
"@lunora/d1": "1.0.0-alpha.
|
|
60
|
+
"@lunora/d1": "1.0.0-alpha.167",
|
|
61
61
|
"@lunora/errors": "1.0.0-alpha.50",
|
|
62
|
-
"@lunora/mcp": "1.0.0-alpha.
|
|
63
|
-
"@lunora/runtime": "1.0.0-alpha.
|
|
64
|
-
"@lunora/seed": "1.0.0-alpha.
|
|
62
|
+
"@lunora/mcp": "1.0.0-alpha.221",
|
|
63
|
+
"@lunora/runtime": "1.0.0-alpha.184",
|
|
64
|
+
"@lunora/seed": "1.0.0-alpha.198",
|
|
65
65
|
"@visulima/cerebro": "3.1.2",
|
|
66
66
|
"@visulima/error": "6.1.0",
|
|
67
67
|
"@visulima/fs": "6.0.28",
|
|
@@ -277,8 +277,8 @@ await ctx.topics.signups.publish({ userId });
|
|
|
277
277
|
idempotent. A failed send rejects `publish`, and a retry re-delivers to the
|
|
278
278
|
subscriptions that already got it.
|
|
279
279
|
- A subscription is published to only through its topic, never `ctx.queues`.
|
|
280
|
-
The topic passed to `defineSubscription` must be a `defineTopic` export of
|
|
281
|
-
|
|
280
|
+
The topic passed to `defineSubscription` must be a `defineTopic` export of
|
|
281
|
+
`lunora/queues.ts` or a module's `queues.ts` (import it from there).
|
|
282
282
|
- Rate-limit public procedures that publish: one publish is one send per
|
|
283
283
|
subscription (`privileged_fanout_from_public_procedure` flags it).
|
|
284
284
|
|
|
@@ -297,6 +297,9 @@ export default defineModule({ description: "Invoices and payments", tables: ["in
|
|
|
297
297
|
|
|
298
298
|
- Write `description` and `tables` inline; codegen reads them without running
|
|
299
299
|
the file. Modules do not nest.
|
|
300
|
+
- A module can declare its own queues, topics and subscriptions in
|
|
301
|
+
`lunora/<module>/queues.ts`. Export names stay app-wide (`ctx.queues.<name>`),
|
|
302
|
+
so two queues files exporting the same name is a codegen error.
|
|
300
303
|
- `cross_module_table_write` warns when a function outside the owning module
|
|
301
304
|
writes an owned table (insert, `patch`/`replace`/`delete`, batch or facade),
|
|
302
305
|
including through a same-file helper. Move the write into the owning module:
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{r as b}from"./cloudflare-credentials-lC5JtPLe.mjs";const _="https://api.cloudflare.com/client/v4/accounts",A=async({accountId:e,apiToken:r,fetch:s,init:t,path:o})=>{const n=await(s??globalThis.fetch.bind(globalThis))(`${_}/${encodeURIComponent(e)}${o}`,{...t,headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}}),c=await n.text();let a;try{a=JSON.parse(c)}catch{return{ok:!1,status:n.status,text:c}}return!n.ok||typeof a!="object"||a===null||a.success===!1?{ok:!1,status:n.status,text:c}:{body:a,ok:!0}},l=100,i=500,S=10,C=5e3,d="Delete the Workers you no longer need (old preview / staging deploys free their classes), or set `durableObjects: { merge: true }` in lunora.config before an app's first deploy so it spends one class instead of up to three.",$=e=>e>=i?{fix:d,message:`the Cloudflare account has ${String(e)} Durable Object classes — the Workers Paid cap is ${String(i)}, so a deploy that adds one will fail.`,verdict:"full"}:e>=i-S?{fix:d,message:`the Cloudflare account has ${String(e)} of ${String(i)} Durable Object classes (Workers Paid cap).`,verdict:"near"}:e>=l-S&&e<=l?{fix:d,message:`the Cloudflare account has ${String(e)} Durable Object classes — on Workers Free the cap is ${String(l)} (Paid: ${String(i)}).`,verdict:"near"}:{message:`the Cloudflare account has ${String(e)} Durable Object classes (caps: ${String(l)} Free, ${String(i)} Paid).`,verdict:"ok"},P=async(e={})=>{const{accountId:r,token:s}=b(e.environment??process.env,e.accountId);if(s===void 0||r===void 0)return{fix:"Set CLOUDFLARE_API_TOKEN (Workers Scripts Read) and CLOUDFLARE_ACCOUNT_ID (or `account_id` in wrangler.jsonc) to check it.",message:"the account's Durable Object class count was not checked.",verdict:"unchecked"};try{const t=await A({accountId:r,apiToken:s,...e.fetch===void 0?{}:{fetch:e.fetch},init:{signal:AbortSignal.timeout(C)},path:"/workers/durable_objects/namespaces?per_page=1"}),o=t.ok?t.body.result_info:void 0,n=typeof o=="object"&&o!==null&&"total_count"in o?o.total_count:void 0;return typeof n!="number"?{message:`the account's Durable Object class count could not be read${t.ok?"":` (HTTP ${String(t.status)})`}.`,verdict:"unchecked"}:$(n)}catch(t){return{message:`the account's Durable Object class count could not be read (${t instanceof Error?t.message:String(t)}).`,verdict:"unchecked"}}},k=e=>{switch(e){case"boolean":return"boolean";case"date":case"number":case"timestamp":return"number";case"id":case"literal":case"string":return"string";default:return}},y=/already (?:exists|indexed)|duplicate/iu,f=e=>["vectorize","create-metadata-index",e.index,`--property-name=${e.property}`,`--type=${e.type}`],T=async(e,r)=>{try{return await e(r)}catch(s){return{code:1,stderr:s instanceof Error?s.message:String(s)}}},D=async e=>{const{cwd:r,entries:s,exec:t,logger:o,spawner:n}=e,c=[];for(const a of s){const u=await T(n,{args:[...t.args,...f(a)],captureStderr:!0,command:t.command,cwd:r,stdoutToStderr:!0});if(u.code===0){c.push({entry:a,status:"created"});continue}const p=`${u.stderr??""}${u.stdout??""}`;if(y.test(p)){c.push({entry:a,status:"exists"});continue}c.push({entry:a,error:p.trim()||`exit code ${String(u.code)}`,status:"failed"}),o.warn(`could not create the Vectorize metadata index for "${a.property}" on "${a.index}" — filters on that property will match nothing until it exists. Run: wrangler ${f(a).join(" ")}`)}return c},g=e=>e.endsWith("S")?e.slice(0,-1):e,h=e=>e.replaceAll(/([a-z\d])([A-Z])/gu,"$1_$2").toUpperCase().split(/[_-]+/u).filter(r=>r.length>0),m=new Set(["CREDENTIAL","DSN","PASSPHRASE","PASSWD","PASSWORD","SECRET","TOKEN"]),E=["ACCESS_KEY","API_KEY","ENCRYPTION_KEY","PRIVATE_KEY","SIGNING_KEY"],R=new RegExp(`(?:${[...m,...E.map(e=>e.replaceAll("_",""))].join("|")})S?$`,"iu"),I=e=>h(e).some(r=>r==="PUBLIC"||r==="PUBLISHABLE"),v=e=>{if(I(e))return!1;const r=h(e);if(r.some(t=>m.has(g(t))))return!0;const s=g(r.join("_"));return E.some(t=>s===t||s.endsWith(`_${t}`))||R.test(e)};export{P as a,f as c,D as e,v as i,k as m};
|