@lunora/cli 1.0.0-alpha.454 → 1.0.0-alpha.456

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,4 +1,4 @@
1
- import{mkdirSync as Me,writeFileSync as H,existsSync as S,readFileSync as A,rmSync as W,mkdtempSync as Er,readdirSync as Fe,realpathSync as Ar,statSync as Ue}from"node:fs";import{dirname as M,join as k,resolve as L,relative as ee,extname as Tr,sep as ae}from"node:path";import{PROJECT_CONFIG_FILENAMES as Rr,isTestPath as se,discoverMigrations as _r,readServiceBindings as le,runCodegen as Dr}from"@lunora/codegen";import{readLinkedProject as Be,resolveSchemaDirectory as N,startDevProcess as Cr,acceptsConnection as Pr,resolveTargetOrThrow as ie,detectFramework as Nr,DEFAULT_BUNDLE_META_PATH as Or,STRICT_ADVISORIES_ENV as jr,LAZY_FUNCTIONS_ENV as Ir,BUNDLE_META_PATH_ENV as Lr,BUILD_TARGET_ENV as xr,BUILD_ROOT_ENV as Mr,canonicalPath as Fr,COMPOSED_WORKER_ENTRY as Se,discoverContainerInfo as He,D1_PLACEHOLDER_ID as $e,discoverSchemaInfo as ue,writeLinkedProject as Ur,DEV_VARS_FILE as P,parseDevVariableEntries as Ge,secretSourcesFromBindings as Br,inferLunoraBindings as qe,requiredSecrets as Hr,mintableSecretKeysFor as Gr,generateSecretValue as qr,upsertDevVariableLine as Vr,writeDevVariablesFileAtomically as Wr,isPlaceholderValue as Kr,ensureGitignoreEntries as zr,resolveLazyFunctions as J,resolveDeployDriver as Y,MissingBuildOutputError as Jr,clearApiSpecMarker as Yr,createDiscoveryCache as Xr,planToolchainInvocation as Ve,probeCelldToolchain as Qr,runPostCodegenHook as Zr,readApiSpecMarker as et}from"@lunora/config";import{bindingsNeedingDatabase as rt,findWranglerFile as O,readWranglerJsonc as D,mergeWranglerEnvironment as X,HYPERDRIVE_PLACEHOLDER_ID as We,applyModify as Ke,warnCloudflareCliConfigOnce as tt,validateWranglerProject as nt,wranglerCodegenInputs as ot,reconcileWranglerBindings as at,reconcileWranglerCompatibilityDate as st,reconcileWranglerCrons as it,describePreservedCrons as ct}from"@lunora/config/cloudflare";import{Spinner as dt}from"@visulima/spinner";import{r as ge,a as lt,e as ut}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as gt}from"../packem_shared/api-spec-lYyq4vL6.mjs";import{i as ft,m as ht,g as mt,c as ze,f as vt,e as pt}from"../packem_shared/vectorize-metadata-DOB1akh6.mjs";import{w as yt}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{d as wt}from"../packem_shared/command-B6vu47iR.mjs";import{r as fe}from"../packem_shared/wrangler-name-Dsk5K1f-.mjs";import{a as kt}from"../packem_shared/deploy-target-resolve-BTCW1Iv4.mjs";import{EXIT_CODE as y}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";import{spawn as bt}from"node:child_process";import{randomUUID as Je,createHash as St}from"node:crypto";import{setTimeout as $t}from"node:timers/promises";import{toolchainExecArgs as F,detectPackageManager as j,execArgsFor as he}from"@lunora/config/cli";import{f as Et}from"../packem_shared/free-port-DjbFhaaT.mjs";import{containerBuildTag as At}from"@lunora/container";import{a as Tt,i as Rt}from"../packem_shared/docker-DpVxvYpL.mjs";import{defaultSpawner as x}from"../packem_shared/createRecordingSpawner-01ZngIwK.mjs";import{r as Ye}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{p as _t,H as Dt,a as Ct,r as Pt}from"../packem_shared/health-probe-Bw9JFfIy.mjs";import{runAdvisor as Nt,openShardAccess as Ee}from"@lunora/advisor";import{join as b,relative as U,dirname as Xe}from"@visulima/path";import{Project as Qe,SyntaxKind as p,Node as w}from"ts-morph";import{r as Ze,c as er}from"../packem_shared/cloudflare-credentials-BVmZnDZk.mjs";import{runMigrateDataCommand as Ot}from"../packem_shared/runMigrateGenerateCommand-Bd2W9t1k.mjs";import{c as jt}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{l as It}from"../packem_shared/wrangler-secrets-DlSlWvRH.mjs";const Lt=Object.freeze({edges:[],nodes:[],modules:[],unresolved:[],version:1}),xt=20,Ae=e=>`${e.from} -${e.kind}-> ${e.to}`,q=(e,r)=>{const t=new Set(e);return r.filter(n=>!t.has(n)).toSorted((n,o)=>n.localeCompare(o))},Mt=(e,r)=>{const t=e.modules.map(s=>s.name),n=r.modules.map(s=>s.name),o=e.edges.map(s=>Ae(s)),a=r.edges.map(s=>Ae(s));return{addedEdges:q(o,a),addedModules:q(t,n),removedEdges:q(a,o),removedModules:q(n,t)}},V=(e,r,t)=>{if(t.length===0)return[];const n=t.slice(0,xt).map(a=>` ${e} ${a}`),o=t.length-n.length;return[`${r}:`,...n,...o>0?[` … and ${o.toString()} more`]:[]]},Ft=e=>{const r=[...V("+","modules added",e.addedModules),...V("-","modules removed",e.removedModules),...V("+","edges added",e.addedEdges),...V("-","edges removed",e.removedEdges)];return r.length===0?void 0:`architecture changes since the last deploy:
1
+ import{mkdirSync as Me,writeFileSync as H,existsSync as S,readFileSync as A,rmSync as W,mkdtempSync as Er,readdirSync as Fe,realpathSync as Ar,statSync as Ue}from"node:fs";import{dirname as M,join as k,resolve as L,relative as ee,extname as Tr,sep as ae}from"node:path";import{PROJECT_CONFIG_FILENAMES as Rr,isTestPath as se,discoverMigrations as _r,readServiceBindings as le,runCodegen as Dr}from"@lunora/codegen";import{readLinkedProject as Be,resolveSchemaDirectory as N,startDevProcess as Cr,acceptsConnection as Pr,resolveTargetOrThrow as ie,detectFramework as Nr,DEFAULT_BUNDLE_META_PATH as Or,STRICT_ADVISORIES_ENV as jr,LAZY_FUNCTIONS_ENV as Ir,BUNDLE_META_PATH_ENV as Lr,BUILD_TARGET_ENV as xr,BUILD_ROOT_ENV as Mr,canonicalPath as Fr,COMPOSED_WORKER_ENTRY as Se,discoverContainerInfo as He,D1_PLACEHOLDER_ID as $e,discoverSchemaInfo as ue,writeLinkedProject as Ur,DEV_VARS_FILE as P,parseDevVariableEntries as Ge,secretSourcesFromBindings as Br,inferLunoraBindings as qe,requiredSecrets as Hr,mintableSecretKeysFor as Gr,generateSecretValue as qr,upsertDevVariableLine as Vr,writeDevVariablesFileAtomically as Wr,isPlaceholderValue as Kr,ensureGitignoreEntries as zr,resolveLazyFunctions as J,resolveDeployDriver as Y,MissingBuildOutputError as Jr,clearApiSpecMarker as Yr,createDiscoveryCache as Xr,planToolchainInvocation as Ve,probeCelldToolchain as Qr,runPostCodegenHook as Zr,readApiSpecMarker as et}from"@lunora/config";import{bindingsNeedingDatabase as rt,findWranglerFile as O,readWranglerJsonc as D,mergeWranglerEnvironment as X,HYPERDRIVE_PLACEHOLDER_ID as We,applyModify as Ke,warnCloudflareCliConfigOnce as tt,validateWranglerProject as nt,wranglerCodegenInputs as ot,reconcileWranglerBindings as at,reconcileWranglerCompatibilityDate as st,reconcileWranglerCrons as it,describePreservedCrons as ct}from"@lunora/config/cloudflare";import{Spinner as dt}from"@visulima/spinner";import{r as ge,a as lt,e as ut}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as gt}from"../packem_shared/api-spec-lYyq4vL6.mjs";import{e as ft,m as ht,g as mt,i as ze,d as vt,b as pt}from"../packem_shared/vectorize-metadata-BVSF8z2h.mjs";import{w as yt}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{d as wt}from"../packem_shared/command-B6vu47iR.mjs";import{r as fe}from"../packem_shared/wrangler-name-Dsk5K1f-.mjs";import{a as kt}from"../packem_shared/deploy-target-resolve-BTCW1Iv4.mjs";import{EXIT_CODE as y}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";import{spawn as bt}from"node:child_process";import{randomUUID as Je,createHash as St}from"node:crypto";import{setTimeout as $t}from"node:timers/promises";import{toolchainExecArgs as F,detectPackageManager as j,execArgsFor as he}from"@lunora/config/cli";import{f as Et}from"../packem_shared/free-port-DjbFhaaT.mjs";import{containerBuildTag as At}from"@lunora/container";import{a as Tt,i as Rt}from"../packem_shared/docker-DpVxvYpL.mjs";import{defaultSpawner as x}from"../packem_shared/createRecordingSpawner-01ZngIwK.mjs";import{r as Ye}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{p as _t,H as Dt,a as Ct,r as Pt}from"../packem_shared/health-probe-Bw9JFfIy.mjs";import{runAdvisor as Nt,openShardAccess as Ee}from"@lunora/advisor";import{join as b,relative as U,dirname as Xe}from"@visulima/path";import{Project as Qe,SyntaxKind as p,Node as w}from"ts-morph";import{r as Ze,c as er}from"../packem_shared/cloudflare-credentials-BVmZnDZk.mjs";import{runMigrateDataCommand as Ot}from"../packem_shared/runMigrateGenerateCommand-Bd2W9t1k.mjs";import{c as jt}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{l as It}from"../packem_shared/wrangler-secrets-DlSlWvRH.mjs";const Lt=Object.freeze({edges:[],nodes:[],modules:[],unresolved:[],version:1}),xt=20,Ae=e=>`${e.from} -${e.kind}-> ${e.to}`,q=(e,r)=>{const t=new Set(e);return r.filter(n=>!t.has(n)).toSorted((n,o)=>n.localeCompare(o))},Mt=(e,r)=>{const t=e.modules.map(s=>s.name),n=r.modules.map(s=>s.name),o=e.edges.map(s=>Ae(s)),a=r.edges.map(s=>Ae(s));return{addedEdges:q(o,a),addedModules:q(t,n),removedEdges:q(a,o),removedModules:q(n,t)}},V=(e,r,t)=>{if(t.length===0)return[];const n=t.slice(0,xt).map(a=>` ${e} ${a}`),o=t.length-n.length;return[`${r}:`,...n,...o>0?[` … and ${o.toString()} more`]:[]]},Ft=e=>{const r=[...V("+","modules added",e.addedModules),...V("-","modules removed",e.removedModules),...V("+","edges added",e.addedEdges),...V("-","edges removed",e.removedEdges)];return r.length===0?void 0:`architecture changes since the last deploy:
2
2
  ${r.join(`
3
3
  `)}`},Ut=(e,r)=>k(e,".lunora",r===void 0?"architecture.json":`architecture.${r}.json`),Bt=e=>{if(S(e))try{const r=JSON.parse(A(e,"utf8"));return r.version===1&&Array.isArray(r.modules)&&Array.isArray(r.edges)?r:void 0}catch{return}},Ht=e=>{const{cwd:r,environment:t,logger:n}=e,o=Ut(r,t),a=Bt(o),s=e.current??(a===void 0?void 0:Lt);if(s===void 0)return;const i=a===void 0?void 0:Ft(Mt(a,s));return i!==void 0&&n.info(i),()=>{try{Me(M(o),{recursive:!0}),H(o,`${JSON.stringify(s,void 0,2)}
4
4
  `,"utf8")}catch(c){n.warn(`could not record the deployed architecture at ${o}: ${c instanceof Error?c.message:String(c)}`)}}},Gt=e=>{const{cwd:r,env:t,logger:n,mintedSecretsFile:o}=e;try{const a=Be(r),s=a?.workerName??fe(r),i=e.url??a?.workerUrl;n.success("deploy complete"),n.info(` worker: ${s??"(see wrangler output above)"}`),t!==void 0&&n.info(` env: ${t}`),i===void 0?n.info(" url: run `lunora link --url <https://your-worker>` to record it"):n.info(` url: ${i}`),o!==void 0&&n.info(` secrets: generated value(s) recorded in ${o}`),e.logsAvailable&&n.info(" logs: lunora logs")}catch{}},qt=/\/index$/u,Vt=/[^\dA-Za-z]/gu,Wt=e=>e.replace(qt,"").split("/").map(r=>r.replaceAll(Vt,"_")),Kt=e=>Wt(e).join("_"),zt=18787,Te=3,rr=12e4,Jt=5e3,re=10,Yt=new Set([".js",".mjs",".mts",".ts",".tsx"]),Xt=/\(void 0\)|is not a function|before initialization|of undefined/u,Qt=e=>typeof e=="object"&&e!==null&&typeof e.functionPath=="string"&&typeof e.message=="string",Zt=e=>{const r=N(e),t=new Map;let n;try{n=Fe(k(e,r),{recursive:!0,encoding:"utf8"})}catch{return t}for(const o of n){const a=Tr(o);Yt.has(a)&&!o.split(ae).some(s=>s==="_generated"||s==="node_modules")&&t.set(Kt(o.slice(0,-a.length).split(ae).join("/")),k(r,o))}return t},en=(e,r)=>{const t=Zt(e),n=new Map;for(const{functionPath:o,message:a}of r){const s=o.lastIndexOf(":"),i=o.slice(0,s),c=`${i}\0${a}`,d=n.get(c)??{exports:[],message:a,namespace:i};d.exports.push(o.slice(s+1)),n.set(c,d)}return[...n.values()].map(({exports:o,message:a,namespace:s})=>{const i=Xt.test(a)?`
@@ -15,5 +15,5 @@ export default {
15
15
  return Response.json({ ...(await loadAllFunctions()), run: runId });
16
16
  },
17
17
  };
18
- `);const g=await Et(i),{args:u,command:h}=F(j(t),c.dev({configPath:r===void 0?void 0:ee(t,r),environment:o,extraArgs:[ee(t,d),"--local","--local-protocol","http","--ip","127.0.0.1","--port",String(g),"--persist-to",ee(t,k(n,"state"))]}));return{args:u,command:h,port:g,runId:l}}catch(d){throw new _(`could not prepare the check (${d instanceof Error?d.message:String(d)})`,!0)}},un=async e=>{const{configPath:r,cwd:t,environment:n,launcher:o,logger:a,toolchain:s}=e,i=k(t,N(t),"_generated","functions.ts");if(!S(i)||!A(i,"utf8").includes("export const loadAllFunctions"))return;const c=tn(e);if("skip"in c){a.warn(`smoke-load skipped: ${c.skip}, so lazy modules are not evaluated before deploy`);return}const{main:d}=c,l=[];let g,u;const h=Date.now()+rr,f=process.platform!=="win32",v=(m,E,C)=>{const $=bt(m,[...E],{cwd:C.cwd,detached:f,shell:C.shell,stdio:["ignore","pipe","pipe"]});return f&&$.pid!==void 0&&(u={dispose:on($.pid),pid:$.pid}),$};try{g=dn(t),a.info("smoke-loading lazy function modules in workerd");let m=zt;for(let E=0;E<Te;E+=1){const{args:C,command:$,port:I,runId:T}=await ln({configPath:r,cwd:t,directory:g,environment:n,functionsFile:i,main:d,preferred:m,toolchain:s});m=I+1;const be=await an({args:C,command:$,cwd:t,spawn:o??v,label:"wrangler dev (smoke-load)",notFound:"`wrangler` was not found",onLine:G=>{l.push(G)},port:I,readyTimeoutMs:Math.max(0,h-Date.now()),shell:process.platform==="win32"});if(be===void 0){await te(u),u=void 0;continue}try{const G=await nn(I,T,h);if(G!==void 0){sn(t,G,a);return}}finally{await be.stop(),await te(u),u=void 0}}throw new _(`the smoke port was answered by other runs on all ${String(Te)} attempts`,!0)}catch(m){return cn(m,l,a)}finally{if(await te(u),g!==void 0)try{W(g,{force:!0,recursive:!0})}catch{}}},gn=(e,r)=>r===void 0?e:L(e,r),fn=async e=>{if(e.targets.length===0)return{builtTags:[],code:0};if(!(e.railpackAvailable??Tt)()){const n="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(n),{builtTags:[],code:1,error:n}}const r=e.spawner??x,t=[];for(const n of e.targets){const o=At(n.exportName),a={args:["build",n.buildDir,"--name",o],command:"railpack",cwd:e.cwd},s=he(j(e.cwd),"wrangler",["containers","push",o]),i={args:s.args,command:s.command,cwd:e.cwd};e.logger.info(`railpack: building "${n.exportName}" → ${o} from ${n.buildDir}`);const c=await r(a);if(c.code!==0){const l=`railpack build failed for container "${n.exportName}" (${n.buildDir})`;return e.logger.error(l),{builtTags:t,code:c.code,error:l}}e.logger.info(`railpack: pushing ${o} to the Cloudflare Registry`);const d=await r(i);if(d.code!==0){const l=`wrangler containers push failed for "${n.exportName}" (${o})`;return e.logger.error(l),{builtTags:t,code:d.code,error:l}}t.push(o)}return{builtTags:t,code:0}},tr=e=>{const t=[O(e),k(e,"package.json"),k(e,"wrangler.dev.jsonc")].filter(n=>n!==void 0&&S(n)).map(n=>[n,A(n,"utf8")]);return()=>{for(const[n,o]of t)A(n,"utf8")!==o&&H(n,o,"utf8")}},hn=(e,r=Je())=>L(e,".lunora",`vite-bundle-meta-${r}.json`),nr="LUNORA_CLIENT_BUILD",mn="virtual:lunora/worker",de=(e,r)=>["ts","mts","cts","js","mjs","cjs"].some(t=>S(k(e,`${r}.config.${t}`))),or=e=>de(e,"rsbuild")?"rsbuild":de(e,"vite")?"vite":void 0,vn=e=>de(e,"vite")?"vite":or(e),pn=e=>{try{const{scripts:r}=JSON.parse(A(k(e,"package.json"),"utf8"));return typeof r?.build=="string"&&r.build!==""}catch{return!1}},Q=(e,r)=>{if(process.env[nr]==="1")return;const t=O(e),n=t===void 0?void 0:D(t).parsed,o=n?.main===mn,a=(o?vn(e):or(e))??(pn(e)?"script":void 0);if(a===void 0)return;const s=r===void 0?void 0:n?.env?.[r]?.assets?.directory,i=n?.assets?.directory??s;return o||Nr(e).class!=="C"||i!==void 0?a:void 0},yn=async(e,r,t)=>{const n=t.spawner??x,o=j(e),a=r==="script"?{args:["run","build"],command:o}:he(o,r,["build"]);t.logger.info(`running ${r} build before bundling the Worker`);const s=tr(e),i=t.bundleMetaPath??hn(e);W(k(e,Or),{force:!0});try{const c=await n({args:a.args,command:a.command,cwd:e,env:{[Mr]:Fr(e),[xr]:t.target,[Lr]:i,...t.lazyFunctions?{[Ir]:"1"}:{},...t.environment===void 0?{}:{CLOUDFLARE_ENV:t.environment},...t.strictAdvisories===!1?{[jr]:"0"}:{},[nr]:"1"},stdoutToStderr:t.outputJson});return c.code===0?void 0:`${r} build failed with exit code ${String(c.code)}`}finally{s(),t.bundleMetaPath===void 0&&W(i,{force:!0})}},Z=(e,r,t)=>r!==!1&&Q(e,t)!==void 0,wn=(e,r,t)=>Z(e,r,t)&&Q(e,t)!=="script",me=e=>{const r=e.frameworkBuild===!1?void 0:Q(e.cwd,e.environment);if(r===void 0||r==="script")return;if(e.apiSpec!==void 0)return`--api-spec is read from the ${r} plugin config when the client build runs; set it there, or pass --no-framework-build`;if(e.target!==void 0)try{ie(e.cwd,e.target)}catch(n){return n instanceof Error?n.message:String(n)}let t;try{t=ie(e.cwd)}catch(n){return`the project's configured target cannot be used, and the ${r} plugin reads it: ${n instanceof Error?n.message:String(n)}`}if(e.target!==void 0&&e.target!==t)return`this run targets "${e.target}", but the project's target is "${t}", which the ${r} plugin reads; set it in the project config, or pass --no-framework-build`},ar=async e=>{const r=e.frameworkBuild===!1?void 0:Q(e.cwd,e.environment);if(r===void 0)return;let t;try{t=e.target??ie(e.cwd)}catch(n){return n instanceof Error?n.message:String(n)}return yn(e.cwd,r,{bundleMetaPath:e.bundleMetaPath,environment:e.environment,strictAdvisories:e.strictAdvisories,lazyFunctions:e.lazyFunctions,logger:e.logger,outputJson:e.outputJson,spawner:e.spawner,target:t})},_e=e=>Array.isArray(e)?e.filter(r=>r!=null):void 0,ve=(e,r)=>{const t=O(e);if(!t)return;const{parsed:n}=D(t);if(n===void 0)return;const{error:o,merged:a}=X(n,r),s=o===void 0?a:n,{containers:i,d1_databases:c,vars:d}=s;return{containers:_e(i),d1_databases:_e(c),vars:typeof d=="object"&&d!==null&&!Array.isArray(d)?d:void 0}},kn=/^127(?:\.\d{1,3}){3}$/,bn=e=>{try{const{hostname:r}=new URL(e);return r==="localhost"||kn.test(r)||r==="::1"||r==="[::1]"}catch{return!1}},Sn=e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"),$n=(e,r,t,n="deploy",o)=>{const a=(ve(e,o)?.containers??[]).filter(i=>typeof i?.image=="string"&&Sn(i.image));if(a.length===0||t())return;const s=`${n} blocked: wrangler.jsonc declares ${String(a.length)} container(s) built from a local Dockerfile, but no Docker-compatible engine is available. Start Docker (or Colima), or point the container's \`image\` at a pre-built registry reference. Note: container images must target linux/amd64.`;return r.error(s),s},pe=e=>S(b(e,Se))?Se:void 0,En=(e,r,t="deploy",n)=>{for(const o of He(e,"lunora",n).containers){const a=o.schedulingPolicy===void 0?o.image:void 0,i=[...a?.kind==="dockerfile"?[{field:"image",path:a.dockerfilePath}]:[],...Object.entries(o.schedulingPolicy==="durable_object"?o.images??{}:{}).flatMap(([c,d])=>d.kind==="dockerfile"?[{field:`images["${c}"]`,path:d.dockerfilePath}]:[])].find(c=>!S(b(e,c.path)));if(i!==void 0){const c=`${t} blocked: container "${o.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(c),c}if(a?.kind==="build"&&!S(b(e,a.buildDir))){const c=`${t} blocked: container "${o.exportName}" references a Railpack build directory "${a.buildDir}" that does not exist. Create it or fix the \`image.build\` path in lunora/containers.ts.`;return r.error(c),c}}},An=(e,r)=>r==="celld"?typeof e=="string"&&e!==$e&&ft(e):r==="cloudflare"&&e===$e,Tn=(e,r,t)=>(ve(e,t)?.d1_databases??[]).find(n=>An(n.database_id,r)),Rn=e=>{if(!e.migrate||e.dryRun||e.preview)return;if(e.migrateUrl===void 0){const t="--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(t),t}if(e.migrateYes!==!0){const t="--migrate runs production data migrations after deploy. Re-run with --migrate-yes to confirm.";return e.logger.error(t),t}const r=e.migrateToken??process.env.LUNORA_ADMIN_TOKEN;if(r===void 0||r===""){const t="admin token required for --migrate — pass --migrate-token or set LUNORA_ADMIN_TOKEN";return e.logger.error(t),t}},_n=(e,r,t,n,o)=>{const a=Tn(e,n,o);if(a===void 0)return;const s=`${t} blocked: the "${a.binding??"<unnamed>"}" D1 binding has a placeholder database_id ("${a.database_id??""}")`,i=n==="celld"?`${s}, which celld would use as the database's identity. Set database_id to the database celld should use, then ${t} again.`:`${s}. 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(i),i},Dn=(e,r,t="deploy",n)=>{const o=ve(e,n)?.vars;if(!o)return;const a=Object.entries(o).filter(([,i])=>typeof i=="string"&&bn(i)).map(([i])=>i).toSorted((i,c)=>i.localeCompare(c));if(a.length===0)return;const s=`${t} blocked: ${a.join(", ")} in wrangler.jsonc point at localhost. A deployed Worker can't reach a loopback address, so this silently breaks scheduled-job dispatch, reverse cross-shard relations, and auth callbacks. Set each to the deployed worker's public URL (or move it to a secret with \`wrangler secret put\`) before deploying.`;return r.error(s),s},Cn=["vite.config.ts","vite.config.mts","vite.config.cts","vite.config.js","vite.config.mjs","vite.config.cjs",...Rr],sr=/\.(?:[cm]?[jt]s|tsx|jsx)$/u,ir=/\.(?:test|spec)\.[cm]?[jt]sx?$/u,cr="allowUnauthenticatedShardAccess",Pn=/[\\/]/u,dr=new Set(["_generated","build","dist","node_modules"]),lr=(e,r)=>{const t=U(e,r).split(Pn);return sr.test(r)&&!ir.test(r)&&!se(t.join("/"))&&t.every(n=>n===".."||!n.startsWith(".")&&!dr.has(n))},De=(e,r,t)=>{const{parsed:n}=D(r);if(n===void 0)return[];const{error:o,merged:a}=X(n,t),{main:s}=o===void 0?a:n,i=typeof s=="string"?b(Xe(r),s):void 0;return i!==void 0&&S(i)&&lr(e,i)?[i]:[]},ye=e=>e===void 0?!1:e.getKind()===p.FalseKeyword?!0:w.isParenthesizedExpression(e)||w.isAsExpression(e)||w.isSatisfiesExpression(e)||w.isTypeAssertion(e)||w.isNonNullExpression(e)?ye(e.getExpression()):!1,Nn=e=>{try{return Ue(e).isFile()}catch{return!1}},On=new Set(["ELOOP","ENOENT","ENOTDIR"]),K=(e,r,t)=>{const n=r instanceof Error&&"code"in r&&typeof r.code=="string"?r.code:"";On.has(n)||t.push(e)},jn=(e,r)=>{try{return Ue(e)}catch(t){K(e,t,r);return}},ur=(e,r)=>{try{return A(e,"utf8")}catch(t){K(e,t,r);return}},gr=(e,r,t,n=new Set)=>{let o;try{o=Ar(r)}catch(s){return K(r,s,t),[]}if(n.has(o))return[];n.add(o);let a;try{a=Fe(r)}catch(s){return K(r,s,t),[]}return a.flatMap(s=>{const i=b(r,s),c=jn(i,t);if(c===void 0)return[];const d=U(e,i).split(ae).join("/");return c.isDirectory()?dr.has(s)||s.startsWith(".")||se(`${d}/`)?[]:gr(e,i,t,n):c.isFile()&&sr.test(s)&&!ir.test(s)&&!se(d)?[i]:[]})},In=e=>{const r=w.isComputedPropertyName(e)?e.getExpression():e;return w.isStringLiteral(r)||w.isNoSubstitutionTemplateLiteral(r)?r.getLiteralValue():e.getText()},ne=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],Ln=/\.(?:[cm]?js|jsx)$/u,xn=(e,r)=>{if(!r.startsWith("."))return;const t=L(Xe(e),r),n=t.replace(Ln,"");return[t,...ne.map(a=>`${t}${a}`),...ne.map(a=>b(t,`index${a}`)),...ne.map(a=>`${n}${a}`)].find(a=>Nn(a))},Mn=e=>{if(e.getExpression().getText()!=="require")return;const[r]=e.getArguments();return r!==void 0&&(w.isStringLiteral(r)||w.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},Fn=e=>{const r=e.getModuleReference();if(!w.isExternalModuleReference(r))return;const t=r.getExpression();return w.isStringLiteral(t)?t.getLiteralValue():void 0},Un=(e,r,t,n)=>{const o=new Set(e),a=[...e],s=[];for(let i=0;i<a.length;i+=1){const c=a[i]??"",d=ur(c,n);if(d===void 0)continue;const l=r.createSourceFile(U(t,c),d,{overwrite:!0}),g=[...l.getImportDeclarations().map(u=>u.getModuleSpecifierValue()),...l.getExportDeclarations().map(u=>u.getModuleSpecifierValue()),...l.getDescendantsOfKind(p.ImportEqualsDeclaration).map(u=>Fn(u)),...l.getDescendantsOfKind(p.CallExpression).map(u=>Mn(u))].filter(u=>u!==void 0);for(const u of g){const h=xn(c,u);h!==void 0&&lr(t,h)&&!o.has(h)&&(o.add(h),s.push(h),a.push(h))}}return s},Bn=e=>{const r=e.getArgumentExpression();return r!==void 0&&(w.isStringLiteral(r)||w.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},Hn=e=>w.isPropertyAccessExpression(e)?e.getName():w.isElementAccessExpression(e)?Bn(e):void 0,Gn=new Set([p.AmpersandAmpersandEqualsToken,p.AmpersandEqualsToken,p.AsteriskAsteriskEqualsToken,p.AsteriskEqualsToken,p.BarBarEqualsToken,p.BarEqualsToken,p.CaretEqualsToken,p.EqualsToken,p.GreaterThanGreaterThanEqualsToken,p.GreaterThanGreaterThanGreaterThanEqualsToken,p.LessThanLessThanEqualsToken,p.MinusEqualsToken,p.PercentEqualsToken,p.PlusEqualsToken,p.QuestionQuestionEqualsToken,p.SlashEqualsToken]),qn=e=>{const r=e.getOperatorToken().getKind();return!Gn.has(r)||Hn(e.getLeft())!==cr?!1:r!==p.EqualsToken||!ye(e.getRight())},Vn=(e,r,t)=>{const n=[],o=[...new Set([N(e),"src"])].filter(g=>S(b(e,g))),a=O(e),s=[...Cn.map(g=>b(e,g)).filter(g=>S(g)),...a===void 0?[]:De(e,a,r),...t.flatMap(g=>De(e,g,r))],i=new Qe({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}),c=o.flatMap(g=>gr(b(e,g),b(e,g),n));return{sites:[...new Set([...c,...s,...Un([...s,...c],i,e,n)])].flatMap(g=>{const u=ur(g,n);if(u===void 0)return[];const h=i.createSourceFile(U(e,g),u,{overwrite:!0}),f=[...h.getDescendantsOfKind(p.PropertyAssignment),...h.getDescendantsOfKind(p.ShorthandPropertyAssignment),...h.getDescendantsOfKind(p.GetAccessor),...h.getDescendantsOfKind(p.MethodDeclaration)].filter(m=>{const E=w.isPropertyAssignment(m)&&ye(m.getInitializer());return In(m.getNameNode())===cr&&!E}).map(m=>m.getStartLineNumber()),v=h.getDescendantsOfKind(p.BinaryExpression).filter(m=>qn(m)).map(m=>m.getStartLineNumber());return[...f,...v].map(m=>({file:U(e,g),line:m}))}),unreadable:n}},Wn=(e,r,t,n,o,a)=>{if(t!=="deploy")return;const{sites:s,unreadable:i}=Vn(e,o,a),c=Nt({openShardAccess:s,schema:{tables:[]}},{lints:[Ee]});if(c.length===0&&i.length===0)return;const d=[];if(c.length>0){const g=c.map(u=>`${String(u.metadata.file)}:${String(u.metadata.line)}`).join(", ");d.push(`${g} enable the open-shard option (any value but a literal false), so any caller may target any shard.`)}if(i.length>0&&d.push(`could not read ${i.join(", ")}, so the open-shard option cannot be ruled out there.`),n){r.warn(`deploying past the open-shard gate (--allow-open-shards): ${d.join(" ")}`);return}const l=`deploy blocked (open_shard_access): ${d.join(" ")} ${Ee.remediation}`;return r.error(l),l},Kn=(e,r,t,n)=>{const o=Wn(e,r.logger,t,r.allowOpenShards===!0,r.env,n);return o===void 0?void 0:{code:y.USAGE,error:o}},zn=(e,r,t,n)=>{const o=_n(e,r.logger,t,n,r.env);if(o!==void 0)return{code:y.USAGE,error:o};const a=Dn(e,r.logger,t,r.env);if(a!==void 0)return{code:y.USAGE,error:a};const s=En(e,r.logger,t,r.discoveryCache);if(s!==void 0)return{code:y.USAGE,error:s};const i=$n(e,r.logger,r.dockerAvailable??Rt,t,r.env);return i===void 0?void 0:{code:y.MISSING_DEPENDENCY,error:i}},Ce=32,fr=15e3,Jn=5432,Yn=3306,Xn=/[^a-z0-9-]/gu,Qn=/[^A-Za-z0-9]/gu,Zn=/-$/u,B=e=>`LUNORA_${e.replaceAll(Qn,"_").toUpperCase()}_URL`,eo=e=>{const r=new Map;for(const t of e){const n=B(t),o=r.get(n);if(o!==void 0)return{bindings:[o,t],variable:n};r.set(n,t)}},Pe=7,ro=(e,r)=>{const t=`${e}-${r}`.toLowerCase(),n=t.replaceAll(Xn,"-");if(n===t&&n.length<=Ce)return n;const o=St("sha256").update(t).digest("hex").slice(0,Pe-1);return`${n.slice(0,Ce-Pe).replace(Zn,"")}-${o}`},Ne=e=>e==="postgresql"?"postgres":e==="mariadb"?"mysql":e,to=e=>e==="mysql"?Yn:Jn,no=e=>{try{const r=new URL(e),t=r.protocol.slice(0,-1),n=decodeURIComponent(r.pathname.slice(1));return!["mariadb","mysql","postgres","postgresql"].includes(t)||r.hostname===""||n===""?void 0:{database:n,host:r.hostname,password:decodeURIComponent(r.password),port:r.port===""?to(Ne(t)):Number(r.port),scheme:Ne(t),user:decodeURIComponent(r.username)}}catch{return}},oo=(e,r)=>{const t=typeof r?.password=="string"?r.password:"",n=t===""?[]:[t,JSON.stringify(t).slice(1,-1),encodeURIComponent(t)];let o=e;for(const a of n)o=o.replaceAll(a,"<redacted>");return o.split(" ").map(a=>a.includes("://")?"<url>":a).join(" ")},hr=e=>(Array.isArray(e)?e:[]).flatMap((r,t)=>{const{binding:n,id:o}=typeof r=="object"&&r!==null?r:{};return typeof n=="string"&&o===We?[{binding:n,index:t}]:[]}),z=e=>{let r="";try{const{errors:t}=JSON.parse(e.text);r=(t??[]).flatMap(n=>typeof n.message=="string"?[n.message]:[]).slice(0,2).join("; ")}catch{}return r===""?`HTTP ${String(e.status)}`:`HTTP ${String(e.status)}: ${r}`},ao=e=>typeof e=="string"||typeof e=="number"?e.toString():void 0,so=["scheme","host","port","database","user"],io=e=>e==="postgresql"?"postgres":e,Oe=(e,r)=>{const t=ao(r);return e==="scheme"?io(t):t},je=50,co=async(e,r)=>{for(let t=1;t<=je;t+=1){const n=await e(t===1?"/hyperdrive/configs":`/hyperdrive/configs?page=${String(t)}`);if(!n.ok)throw new Error(`listing Hyperdrive configs failed (${z(n)})`);if(!Array.isArray(n.body.result))throw new TypeError("the listing of Hyperdrive configs had no result list");const o=n.body.result.find(s=>s.name===r),a=typeof n.body.result_info=="object"&&n.body.result_info!==null?n.body.result_info:{};if(o!==void 0||typeof a.total_pages!="number"||t>=a.total_pages)return o}throw new Error(`the listing of Hyperdrive configs has more than ${String(je)} pages, so "${r}" can't be shown to be absent`)},lo=async(e,r,t,n)=>{const o=n?{caching:{disabled:!0}}:{},a=await co(e,r);if(typeof a?.id=="string"){const c=so.filter(l=>Oe(l,a.origin?.[l])!==Oe(l,t[l]));if(c.length>0)throw new Error(`a Hyperdrive config named "${r}" already exists for a different origin, or one that can't be confirmed (${c.join(", ")}). Delete it, or rename the Worker, so the binding does not reach the wrong database.`);const d=await e(`/hyperdrive/configs/${encodeURIComponent(a.id)}`,{body:JSON.stringify({origin:t,...o}),method:"PATCH"});if(!d.ok)throw new Error(`updating its credentials failed (${z(d)})`);return{id:a.id,reused:!0}}const s=await e("/hyperdrive/configs",{body:JSON.stringify({name:r,origin:t,...o}),method:"POST"});if(!s.ok)throw new Error(`creating it failed (${z(s)})`);const{id:i}=typeof s.body.result=="object"&&s.body.result!==null?s.body.result:{};if(typeof i!="string")throw new TypeError("the response carried no id");return{id:i,reused:!1}},uo=(e,r,t,n)=>r===void 0&&n?`${B(e)} is set but is not a usable connection string for the "${e}" Hyperdrive binding: it needs a postgres://, postgresql:// or mysql:// scheme, a host and a database name, with any special characters percent-encoded.`:r===void 0?`the "${e}" Hyperdrive binding has no config yet. Set ${B(e)} to its postgres:// or mysql:// connection string and Lunora creates the config, or run \`wrangler hyperdrive create\` and put its id in wrangler.jsonc.`:t?void 0:`creating the "${e}" Hyperdrive config needs CLOUDFLARE_API_TOKEN (Hyperdrive: Edit) and CLOUDFLARE_ACCOUNT_ID, or run \`wrangler hyperdrive create\` and put its id in wrangler.jsonc.`,go=async(e,r)=>{const t=ro(e.workerName,e.binding),{id:n,reused:o}=await lo(async(a,s)=>er({accountId:e.accountId,apiToken:e.token,...e.fetch===void 0?{}:{fetch:e.fetch},init:{...s,signal:AbortSignal.timeout(fr)},path:a}),t,e.origin,e.disableCaching);return e.logger.success(`${o?"reusing":"created"} Hyperdrive config "${t}" for ${e.binding} → ${e.wranglerPath}`),{id:n,text:Ke(r,[...e.path,e.index,"id"],n)}},fo=e=>e===void 0||e===""?void 0:e,mr=e=>{const r=k(M(e),".wrangler","deploy","config.json");try{const{configPath:t}=JSON.parse(A(r,"utf8"));return typeof t=="string"?L(M(r),t):void 0}catch{return}},ho=(e,r,t,n,o)=>{const a=mr(e);if(a===void 0||a===e)return;if(n.built!==n.deployed){o.warn(`the build output ${a} was made for ${n.built===void 0?"the default environment":`"${n.built}"`}, not ${n.deployed===void 0?"the default environment":`"${n.deployed}"`}, so the "${r}" Hyperdrive id was not written there. Build with CLOUDFLARE_ENV set to the environment you deploy, then deploy again.`);return}let s;try{s=D(a)}catch{return}const i=hr(s.parsed?.hyperdrive).find(c=>c.binding===r);i!==void 0&&H(a,Ke(s.text,["hyperdrive",i.index,"id"],t),"utf8")},mo=(e,r)=>{const t=typeof e.name=="string"&&e.name!==""?e.name:"lunora";if(r===void 0)return t;const n=e.env?.[r]?.name;return typeof n=="string"&&n!==""?n:`${t}-${r}`},we=(e,r)=>{const t=O(e),n=t===void 0?void 0:D(t).parsed;if(t===void 0||n===void 0)return;const o=r===void 0?void 0:n.env?.[r],a=hr(r===void 0?n.hyperdrive:o?.hyperdrive);return a.length===0?void 0:{accountId:o?.account_id??n.account_id,entries:a,path:r===void 0?["hyperdrive"]:["env",r,"hyperdrive"],workerName:mo(n,r),wranglerPath:t}},vo=(e,r,t)=>{const n=eo(e.map(({binding:o})=>o));if(n!==void 0){const o=`deploy blocked: the Hyperdrive bindings ${n.bindings.map(a=>`"${a}"`).join(" and ")} both read ${n.variable} and would share one config. Rename one so their names differ in letters or digits, not only in punctuation.`;return t.logger.error(o),o}for(const{binding:o,origin:a,supplied:s}of e){const i=uo(o,a,r,s);if(i!==void 0&&t.dryRun===!0)t.logger.warn(`dry run: ${i} A real deploy stops here.`);else if(i!==void 0){const c=`deploy blocked: ${i}`;return t.logger.error(c),c}}},po=async(e,r,t,n)=>{let o;try{o=await e(`/hyperdrive/configs/${encodeURIComponent(t)}`)}catch(s){n.warn(`could not check whether the "${r}" Hyperdrive config has query caching off (${s instanceof Error?s.message:String(s)}).`);return}if(!o.ok){n.warn(`could not check whether the "${r}" Hyperdrive config has query caching off (${z(o)}).`);return}const{caching:a}=typeof o.body.result=="object"&&o.body.result!==null?o.body.result:{};a?.disabled!==!0&&n.warn(`the "${r}" Hyperdrive config has query caching on, so .global() tables would read rows up to 75 s old. Run \`wrangler hyperdrive update ${t} --caching-disabled\`.`)},yo=async(e,r)=>{const t=O(e.cwd),n=t===void 0?void 0:D(t).parsed,o=e.wranglerEnvironment===void 0?n:n?.env?.[e.wranglerEnvironment],{accountId:a,token:s}=Ze(r,o?.account_id??n?.account_id);if(a===void 0||s===void 0)return;const i=async(c,d)=>er({accountId:a,apiToken:s,...e.fetch===void 0?{}:{fetch:e.fetch},init:{...d,signal:AbortSignal.timeout(fr)},path:c});for(const c of Array.isArray(o?.hyperdrive)?o.hyperdrive:[]){const{binding:d,id:l}=typeof c=="object"&&c!==null?c:{};typeof d=="string"&&typeof l=="string"&&l!==We&&await po(i,d,l,e.logger)}},wo=async e=>{const r=e.environment??process.env;e.disableCaching===!0&&e.checkOnly!==!0&&e.dryRun!==!0&&await yo(e,r);const t=we(e.cwd,e.wranglerEnvironment);if(t===void 0)return;const{entries:n,path:o,wranglerPath:a}=t,{accountId:s,token:i}=Ze(r,t.accountId),c=n.map(({binding:l})=>{const g=r[B(l)]??"";return{binding:l,origin:no(g),supplied:g!==""}}),d=vo(c,i!==void 0&&s!==void 0,e);if(d!==void 0)return d;if(!(e.dryRun===!0||e.checkOnly===!0))for(const[l,{binding:g,index:u}]of n.entries()){const h=c[l]?.origin;if(!(h===void 0||i===void 0||s===void 0))try{const{id:f,text:v}=await go({accountId:s,binding:g,disableCaching:e.disableCaching===!0,fetch:e.fetch,index:u,logger:e.logger,origin:h,path:o,token:i,workerName:t.workerName,wranglerPath:a},A(a,"utf8"));H(a,v,"utf8"),ho(a,g,f,{built:fo(r.CLOUDFLARE_ENV),deployed:e.wranglerEnvironment},e.logger)}catch(f){const v=f instanceof Error?f.message:String(f),m=`deploy blocked: the "${g}" Hyperdrive config could not be set up: ${oo(v,c[l]?.origin)}`;return e.logger.error(m),m}}},ko=(e,r)=>{const t=we(e,r.env)?.entries[0]?.binding;if(t===void 0)return;const n=`prepare blocked: the "${t}" Hyperdrive binding still has its placeholder id. Run \`lunora deploy\` with ${B(t)} set to create the config, or put the id from \`wrangler hyperdrive create\` in wrangler.jsonc.`;return r.logger.error(n),n},bo=(e,r)=>{const t=we(e,r.env)?.entries[0]?.binding;if(t===void 0)return;const n=`deploy blocked: the "${t}" Hyperdrive binding has no config, and a --temporary deploy cannot create one: it would be made in your account while the Worker goes to a temporary one, which a temporary account has no database for. Deploy without --temporary.`;return r.logger.error(n),n},vr=async(e,r,t,n,o="create")=>{if(n!=="cloudflare")return;if(t==="prepare")return ko(e,r);if(r.temporary===!0)return bo(e,r);const a=r.clientBuildEnvironment===void 0?void 0:{...process.env,CLOUDFLARE_ENV:r.clientBuildEnvironment},s=ue(e,N(e),r.discoveryCache);return s.error!==void 0&&r.logger.warn(`could not read the schema (${s.error}), so Hyperdrive configs are set up with query caching off.`),wo({checkOnly:o==="check",cwd:e,disableCaching:s.error!==void 0||s.info?.hasHyperdriveGlobalTable===!0,dryRun:r.dryRun,environment:a,logger:r.logger,wranglerEnvironment:r.env})},So=/https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u,$o=/https:\/\/[^\s"'<>]+/u,Eo=e=>{if(e===void 0)return;const r=So.exec(e);return r?r[0]:$o.exec(e)?.[0]},Ie=e=>e===void 0?"":` (--env ${e})`,Ao=({cwd:e,env:r,logger:t,now:n,url:o})=>{if(o!==void 0)try{const a=Be(e);if(a!==void 0){if(a.workerUrl===o&&a.env===r)return;t.warn(`link: .lunora/project.json records ${a.workerUrl??"(no url)"}${Ie(a.env)}, but this deploy published ${o}${Ie(r)}. Keeping the recorded value — run \`lunora link --url ${o}${r===void 0?"":` --env ${r}`}\` to update it.`);return}const s=(n??(()=>new Date().toISOString()))();Ur(e,{env:r,linkedAt:s,workerName:fe(e),workerUrl:o}),t.success(`link: recorded ${o} in .lunora/project.json (run \`lunora link\` to change)`)}catch{}},To=async(e,r)=>{const t=new Qe({skipAddingFilesFromTsConfig:!0}),n=b(r,"lunora");let o;try{o=_r(t,n)}catch(a){const s=a instanceof Error?a.message:String(a);return e.logger.warn(`--migrate: could not discover migrations (${s}); skipping`),0}if(o.length===0)return e.logger.info("--migrate: no data migrations declared in lunora/"),0;e.logger.info(`--migrate: running ${String(o.length)} migration(s) against deployed worker`);for(const a of o){e.logger.info(`--migrate: up "${a.id}" (table "${a.table}")`);const s={cwd:r,fetchImpl:e.fetchImpl,id:a.id,logger:e.logger,prod:!0,subcommand:"up",token:e.migrateToken,url:e.migrateUrl,yes:e.migrateYes===!0},i=await Ot(s);if(i.code!==0)return e.logger.error(`--migrate: migration "${a.id}" failed — see output above`),i.code;e.logger.success(`--migrate: "${a.id}" applied`)}return 0},Ro=async(e,r)=>{const{info:t}=ue(r,"lunora",e.discoveryCache),n=t?.vectorMetadata??[];if(n.length===0)return;const o=[];for(const i of n){const c=ht(i.kind);if(c===void 0){e.logger.warn(`vector index "${i.index}" declares metadata "${i.property}", whose column type cannot be filtered on in Vectorize — it is stored with each vector but no filter will match it.`);continue}o.push({index:i.index,property:i.property,type:c})}if(o.length===0)return;const s=(await mt({cwd:r,entries:o,exec:he(j(r),"wrangler",[]),logger:e.logger,spawner:e.spawner??x})).filter(i=>i.status!=="failed").length;s>0&&e.logger.success(`vectorize metadata indexes ready: ${String(s)}/${String(o.length)}`)},Le=5,_o=2e3,Do=async(e,r,t)=>{if(e.healthCheck!==!0)return;const n=t??Ye({cwd:r,env:e.env});if(n===void 0){const a="--health-check: the deploy succeeded, but no URL to probe could be resolved — wrangler's output carried none and this checkout has no link for this environment. Run `lunora link --url <https://your-worker>` and re-deploy, or drop --health-check.";return e.logger.error(a),{error:a,ok:!1,url:""}}const o=await _t({attempts:Le,baseUrl:n,delayMs:_o,fetchImpl:e.healthFetch,paths:[Dt,Ct],sleep:e.healthSleep});return o.error===void 0?(e.logger.success(`health check ok (${o.url})`),{ok:!0,url:o.url}):(e.logger.error(`--health-check: the deploy succeeded, but the new version did not answer after ${String(Le)} attempt(s) — ${o.error}`),{error:o.error,ok:!1,url:o.url})},Co=async(e,r,t,n,o,a)=>{await Ro(e,r);const s=e.migrate?await To(e,r):0;return s===0&&o?.(),{code:s,descriptor:t,mintedSecretsFile:a,validation:n}},Po=async({cwd:e,descriptor:r,mintedSecretsFile:t,options:n,reblessSchemaBaseline:o,recordArchitecture:a,stdout:s,validation:i})=>{const c={deployedAt:new Date().toISOString(),dryRun:n.dryRun===!0,env:n.env,preview:n.preview===!0,url:n.dryRun===!0?void 0:Eo(s),workerName:fe(e)};if(n.dryRun===!0||n.preview===!0)return n.healthCheck===!0&&n.logger.warn(`--health-check skipped: ${n.dryRun===!0?"a dry run publishes nothing":"a preview version serves no live traffic"}`),{code:0,deployment:c,descriptor:r,mintedSecretsFile:t,validation:i};n.temporary!==!0&&(a?.(),Ao({cwd:e,env:n.env,logger:n.logger,url:c.url}));const d=await Do(n,e,c.url);return d?.error!==void 0?{code:y.UNAVAILABLE,deployment:c,descriptor:r,healthCheck:d,mintedSecretsFile:t,validation:i}:{...await Co(n,e,r,i,o,t),deployment:c,healthCheck:d}},No=(e,r,t)=>{const n=b(e,P);if(!S(n))return;let o;try{o=Ge(A(n,"utf8")).length}catch{return}if(o===0)return;const a=t.toolchain?.secretPut!==void 0;r.warn(a?`Note: \`lunora deploy\` does not push secrets. ${P} has ${String(o)} key(s); if you changed them, run \`lunora env push --yes\` to update the deployed secrets.`:`Note: ${t.name} deploys read no secrets. ${P} has ${String(o)} key(s) that only the dev server sees; a key the app reads from env must be a \`vars\` entry in the deployed config, one it loads from a secret manager at runtime need not.`)},pr=async(e,r)=>{let t=[];try{t=Br(await qe({cache:r,projectRoot:e,schemaDir:N(e)}))}catch{}const n=[...new Set(Hr(t).map(a=>a.key))];let o=[];try{const a=b(e,P);S(a)&&(o=Ge(A(a,"utf8")).map(s=>s.key).filter(s=>ze(s)))}catch{}return{fromLocal:o.filter(a=>!n.includes(a)),fromPackages:n,mintableKeys:Gr(t)}},Oo=async(e,r,t,n)=>{const{logger:o}=r,a=r.spawner??x,s=j(e),i=r.env===void 0?"":` --env ${r.env}`,c=n.toolchain?.secretPut;if(c===void 0)return o.error(`deploy target "${n.id}" has no secret store; cannot push secrets`),{minted:[],ok:!1};const d=t.map(u=>({key:u,value:qr()})),l=n.toolchain?.secretBulk;if(l!==void 0&&d.length>=2){const u=F(s,l({environment:r.env,temporary:r.temporary})),h=await a({args:u.args,command:u.command,cwd:e,input:JSON.stringify(Object.fromEntries(d.map(f=>[f.key,f.value])))});if(h.code===0){for(const{key:f}of d)o.success(`generated + pushed ${f}`);return{minted:d,ok:!0}}o.warn(`bulk secret push failed (exit ${String(h.code)}); retrying one key at a time`)}const g=[];for(const{key:u,value:h}of d){const f=c({environment:r.env,key:u,temporary:r.temporary}),v=F(s,f),m=await a({args:v.args,command:v.command,cwd:e,input:h});if(m.code!==0)return o.error(`failed to push secret ${u} (exit ${String(m.code)}); set it manually with \`wrangler secret put ${u}${i}\`.`),{minted:g,ok:!1};g.push({key:u,value:h}),o.success(`generated + pushed ${u}`)}return{minted:g,ok:!0}},jo=/^[\w-]+$/u,xe=[".dev.vars",".dev.vars.*","!.dev.vars.example"],Io=(e,r)=>{try{const t=zr(e,xe);t.length>0&&r.info(`.gitignore: added ${t.join(", ")} so the recorded secret cannot be committed`)}catch(t){r.warn(`could not update .gitignore (${t instanceof Error?t.message:String(t)}) — add \`${xe.join("` and `")}\` by hand before committing.`)}},Lo=(e,r,t)=>{if(t.length===0)return;const n=t.map(i=>i.key).join(", ");if(r.env!==void 0&&!jo.test(r.env)){r.logger.warn(`${n}: 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 o=r.env===void 0?P:`${P}.${r.env}`;Io(e,r.logger);const a=b(e,o);let s=S(a)?A(a,"utf8"):"";for(const i of t)s=Vr(s,i.key,i.value);return Wr(a,s),r.logger.success(r.env===void 0?`${n}: value(s) recorded in ${o}`:`${n}: value(s) recorded in ${o} (kept separate from ${P} so \`lunora dev\` and a plain \`lunora env push\` don't inherit the --env ${r.env} value)`),o},xo=/^<[^>]+>$/u,Mo=async(e,r,t)=>{let n;try{n=t.projectConfig?.(e,"deploy").vars??{}}catch(l){return{error:l instanceof Error?l.message:String(l)}}const o=l=>{const g=n[l];if(typeof g!="string")return!0;const u=g.trim();return u===""||xo.test(u)?!0:ze(l)&&Kr(g)},a=l=>Object.hasOwn(n,l)?`${l} (empty or a placeholder)`:l,{fromLocal:s,fromPackages:i}=await pr(e,r.discoveryCache),c=s.filter(l=>o(l));c.length>0&&r.logger.warn(`${P} key(s) not set in the wrangler vars: ${c.map(l=>a(l)).join(", ")}. ${t.name} has no secret store: a key the app reads from env must be a \`vars\` entry; one it loads from a secret manager at runtime need not.`);const d=i.filter(l=>o(l));return d.length===0?{}:{error:`missing required secret(s) in the wrangler vars: ${d.map(l=>a(l)).join(", ")}. ${t.name} has no secret store and Lunora reads these from env, so each must be a real \`vars\` value in the config the deploy ships — write it there from your secret manager at deploy time rather than committing it. Add them, then re-deploy.`}},Fo=async(e,r,t,n)=>{if(r.dryRun===!0||r.preview===!0)return{};if(n.toolchain?.secretList===void 0)return Mo(e,r,n);const{logger:o}=r,a=r.env===void 0?"":` --env ${r.env}`;let s;try{s=await(r.secretLister??It)({cwd:e,env:r.env,target:n.id,temporary:r.temporary})}catch{return{}}if(!s.ok)return{};const i=new Set(s.names),{fromLocal:c,fromPackages:d,mintableKeys:l}=await pr(e,r.discoveryCache),g=[...d,...c].filter(f=>!i.has(f));if(g.length===0)return{};if(!t)return{error:`missing required secret(s) on the deploy target: ${g.join(", ")}. Set them with \`wrangler secret put <KEY>${a}\` (or \`lunora env generate --set\` then \`lunora env push --yes${a}\`), then re-deploy.`};for(const f of g.filter(v=>!l.has(v)))o.warn(`required secret ${f} is not set on the target — set it with: wrangler secret put ${f}${a}`);const u=g.filter(f=>l.has(f));if(u.length===0)return{};if(await(r.secretConfirm??jt())(`${String(u.length)} required secret(s) not set on the target (${u.join(", ")}). Generate strong values and push them now?`)){const{minted:f,ok:v}=await Oo(e,r,u,n),m=Lo(e,r,f);return v?{mintedSecretsFile:m}:{error:"failed to push required secret(s) — set them manually and re-deploy",mintedSecretsFile:m}}return o.warn(`${String(u.length)} required secret(s) not set on the target: ${u.join(", ")}. Generate + push with \`lunora env generate --set\` then \`lunora env push --yes${a}\`.`),{}},yr=e=>e.format==="json"?!1:e.interactive!==void 0?e.interactive:process.stdout.isTTY&&!process.env.CI,Uo=async(e,r)=>{if(r.dryRun===!0)return;const t=He(e,"lunora",r.discoveryCache).containers.flatMap(o=>o.schedulingPolicy===void 0&&o.image.kind==="build"?[{buildDir:o.image.buildDir,exportName:o.exportName}]:[]);if(t.length===0)return;const n=await fn({cwd:e,logger:r.logger,railpackAvailable:r.railpackAvailable,spawner:r.spawner,targets:t});return n.code===0?void 0:n.error??"railpack build failed"},Bo=(e,r,t)=>{if(t!==void 0)try{const n=it(e,t);n.changed&&r.success(`synced ${String(t.length)} cron trigger(s) → ${n.wranglerPath??"wrangler.jsonc"}`);for(const a of n.warnings)r.warn(a);const o=ct(n.preserved);o!==void 0&&r.info(o)}catch(n){const o=n instanceof Error?n.message:String(n);r.warn(`cron trigger sync skipped: ${o}`)}},Ho=async(e,r,t,n,o,a)=>{try{Y(n);const s=await qe({cache:a,projectRoot:e,schemaDir:N(e)}),i=at(e,s,{environment:o,target:n}),c=i.wranglerPath??"wrangler.jsonc";if(i.added.length>0&&r.success(`provisioned bindings: ${i.added.join(", ")} → ${c}`),i.updated.length>0&&r.success(`updated bindings: ${i.updated.join(", ")} → ${c}`),i.devConfig!==void 0){const{added:d,path:l,updated:g}=i.devConfig;r.success(`dev sidecar bindings: ${[...d,...g].join(", ")} → ${l}`)}for(const d of i.warnings)r.warn(d)}catch(s){const i=s instanceof Error?s.message:String(s);r.warn(`binding inference skipped: ${i}`)}try{const s=st(e);s.changed&&r.success(`bumped compatibility_date to ${s.date??"unknown"} (Workers Cache enabled) → ${s.wranglerPath??"wrangler.jsonc"}`)}catch(s){const i=s instanceof Error?s.message:String(s);r.warn(`compatibility date sync skipped: ${i}`)}Bo(e,r,t)},Go=async(e,r,t,n,o,a,s,i,c,d)=>{let l;r?(l=new dt({name:"dots"}),l.start("running codegen")):t.info("running codegen");try{const g=Dr({apiSpec:n,dryRun:!d,lazyFunctions:o,projectRoot:e,target:a,...ot(e)});l?.succeed("codegen complete"),l||t.success("codegen complete");const u=lt(g.platformDiagnostics,t);if(u.errors.length>0)return{error:u.errors.join("; ")};const{errorAdvisories:h,names:f,shouldBlock:v}=ut(g.advisories,c);if(v){const E=`${h.length.toString()} ERROR-level ${h.length===1?"advisory":"advisories"} (${f.join(", ")}). Pass --no-strict-advisories to downgrade this to a warning and continue.`;return t.error(E),{error:E}}const m=d?await Zr({cwd:e,logger:t,spawner:s,stdoutToStderr:i}):void 0;return m?.error!==void 0?{error:m.error}:{result:g}}catch(g){l?.failed("codegen failed");const u=g instanceof Error?g.message:String(g);return t.error(`codegen failed: ${u}`),{error:`codegen failed: ${u}`}}},qo=(e,r)=>({dryRun:r.dryRun,entry:pe(e),environment:r.env,outDir:r.outDir,preview:r.preview,temporary:r.temporary}),wr=(e,r,t)=>{const{toolchain:n}=t;if(n===void 0)throw new Error(`deploy target "${t.id}" has no command-line toolchain`);const o=qo(e,r);return Ve(t,e,"deploy",a=>n.deploy({...o,configPath:a}))},Vo=(e,r,t)=>{const n=wr(e,r,t),o=pe(e);return o!==void 0&&r.logger.info(`class-B composition: deploying ${o} (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}`),n.commit(),n.projection!==void 0&&n.projection.dropped.length>0&&r.logger.warn(`${t.name} ignores these wrangler keys, so they were left out of ${n.projection.configPath}: ${n.projection.dropped.join(", ")}`),n.command},R={problems:[],wranglerPath:void 0},oe=(e,r)=>({code:y.USAGE,descriptor:void 0,error:e,validation:R,...r}),Wo=(e,r)=>{for(const t of e.report?.warnings??[])r.warn(`wrangler.jsonc: ${t}`);if(e.problems.length===0)return!1;r.error("wrangler.jsonc validation failed:");for(const t of e.problems)r.error(` - ${t}`);return!0},Ko=(e,r,t)=>{const n=r.format==="json",o=r.dryRun!==!0,a=Vo(e,r,t),s=F(j(e),a);return{args:s.args,captureStdout:o&&!n,captureStdoutSilently:o&&n,command:s.command,cwd:e,stdoutToStderr:n&&!o}},ke=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"},zo=(e,r)=>ke(r)===void 0?le(e).services.map(t=>t.wranglerPath):[],kr=(e,r,t,n,o)=>({cwd:e,environment:r.env,frameworkBuild:n,lazyFunctions:J(r.lazyFunctions),logger:r.logger,outputJson:r.format==="json"||r.clientBuildOutputJson===!0,spawner:o,strictAdvisories:ge(r),target:t.id}),Jo=(e,r,t)=>{const{toolchain:n}=t,o=n===void 0?`target "${t.id}" has no deploy command`:ke(r);if(o!==void 0||n===void 0){const a=e.map(s=>s.worker).join(", ");r.logger.warn(`services not deployed (${o??""}): ${a} — deploy them yourself if the app calls anything new`);return}return n},br=(e,r)=>{for(const t of e){const n=me(r(M(t.wranglerPath)));if(n!==void 0)return`service ${t.name} (${t.worker}): ${n}`}},Yo=(e,r,t)=>{const{error:n,services:o}=le(e);if(n!==void 0||o.length===0)return;const a=Y(t);if(a.toolchain===void 0||ke(r)!==void 0)return;const s=r.skipCodegen===!0?!1:r.frameworkBuild,i=[...new Map(o.map(c=>[c.wranglerPath,c])).values()];return br(i,c=>kr(c,r,a,s,x))},Sr=(e,r,t)=>{const n=e.cwd??process.cwd(),o=kt(n,e.target);if(o.target===void 0){const i=o.error??"unknown deploy target";return e.logger.error(i),{kind:"refused",error:i,validation:R}}try{wr(n,e,Y(o.target))}catch(i){if(!(t&&i instanceof Jr&&Z(n,e.skipCodegen===!0?!1:e.frameworkBuild,e.env))){const c=i instanceof Error?i.message:String(i);return e.logger.error(c),{kind:"refused",error:c,validation:R}}}const a=e.openShardGatePassed===!0?void 0:Kn(n,e,r,zo(n,e));if(a!==void 0)return{kind:"refused",code:a.code,error:a.error,validation:R};const s=Yo(n,e,o.target);return s!==void 0?(e.logger.error(s),{kind:"refused",code:y.USAGE,error:s,validation:R}):{kind:"ok",target:o.target}},Xo=(e,r)=>e.apiSpec??(e.clientBuildRan===!0?et(r):void 0),Qo=async(e,r,t)=>{if(r!=="celld")return;const n=await(e.celldToolchain??Qr)({dryRun:t==="prepare"||e.dryRun===!0,env:process.env,purpose:"deploy"});for(const o of n.warnings)e.logger.warn(o);return n.errors.length>0?n.errors.join("; "):void 0},Zo=async(e,r)=>{const t=e.cwd??process.cwd(),n=yr(e),o=ge(e),a={problems:[],wranglerPath:void 0},s=Sr(e,r,!1);if(s.kind==="refused")return{code:s.code,error:s.error,validation:s.validation};const{target:i}=s,c=await Qo(e,i,r);if(c!==void 0)return e.logger.error(c),{code:y.MISSING_DEPENDENCY,error:c,target:i,validation:a};let d;if(!e.skipCodegen){const v=await Go(t,n,e.logger,Xo(e,t),J(e.lazyFunctions),i,e.spawner,e.format==="json",o,e.clientBuildRan!==!0);if(v.error!==void 0)return{error:v.error,target:i,validation:R};d=v.result,e.discoveryCache?.clear()}let l;if(d!==void 0){const v=Pt({allowDrift:e.allowSchemaDrift===!0,codegen:d,command:r,logger:e.logger,updateBaseline:e.updateSchemaBaseline===!0});if(v.blocked)return{error:`schema drift gate blocked ${r}`,schemaDrift:{blocked:!0,reason:v.reason},target:i,validation:a};l=v.rebless}const g=d&&Ht({current:d.architecture,cwd:t,environment:e.env,logger:e.logger});await Ho(t,e.logger,d?.cronTriggers,i,e.env,e.discoveryCache);const u=await vr(t,e,r,i,"check");if(u!==void 0)return{error:u,target:i,validation:R};const h=zn(t,e,r,i);if(h!==void 0)return{code:h.code,error:h.error,target:i,validation:R};const f=nt({environment:e.env,projectRoot:t});return Wo(f,e.logger)?{error:"wrangler validation failed",target:i,validation:f}:{codegen:d,reblessSchemaBaseline:l,recordArchitecture:g,target:i,validation:f}},ea=e=>{W(k(e,".wrangler","deploy","config.json"),{force:!0})},ra=async(e,r,t)=>{const n=me(e);if(n!==void 0)return{built:!1,error:n};const o=Z(e.cwd,r,t);return o&&ea(e.cwd),{built:o,error:await ar(e)}},ta=(e,r,t)=>r||t===!1?mr(e):void 0,na=async(e,r,t,n)=>{const{error:o,services:a}=le(e);if(o!==void 0)return{code:y.FAILURE,error:o};if(a.length===0)return;const s=Jo(a,r,t);if(s===void 0)return;const i=j(e),c=[...new Map(a.map(u=>[u.wranglerPath,u])).values()],d=r.skipCodegen===!0?!1:r.frameworkBuild,l=u=>kr(u,r,t,d,n),g=br(c,l);if(g!==void 0)return r.logger.error(g),{code:y.USAGE,error:g};for(const u of c){const h=M(u.wranglerPath),f=l(h),{built:v,error:m}=await ra(f,d,r.env);if(m!==void 0){const T=`service ${u.name} (${u.worker}): ${m}`;return r.logger.error(T),{code:y.FAILURE,error:T}}const E=ta(u.wranglerPath,v,d);let C;try{C=Ve(t,h,"deploy",T=>s.deploy({configPath:T??E??u.wranglerPath,dryRun:r.dryRun===!0,environment:r.env}))}catch(T){return{code:y.FAILURE,error:`service ${u.name} (${u.worker}): ${T instanceof Error?T.message:String(T)}`}}C.commit();const $=F(i,C.command);r.logger.info(`deploying service ${u.name} (${u.worker}) via ${$.command} ${$.args.join(" ")}`);const I=await n({args:$.args,command:$.command,cwd:h,stdoutToStderr:r.format==="json"});if(I.code!==0)return{code:y.FAILURE,error:`service ${u.name} (${u.worker}): ${$.command} ${$.args.join(" ")} exited ${String(I.code)} — stopping before the app`}}},oa=async(e,r,t,n)=>{if(r!=="cloudflare")return;const o=e===void 0?void 0:D(e).parsed,a=(t===void 0?void 0:o?.env?.[t]?.account_id)??o?.account_id,s=await pt({accountId:a});(s.verdict==="near"||s.verdict==="full")&&n.warn(s.fix===void 0?s.message:`${s.message} ${s.fix}`)},aa=e=>e.dryRun!==!0&&e.temporary!==!0,sa=e=>e.temporary===!0?"temporary":e.dryRun===!0?"preview":"defer",ia=e=>{const r=e.fix===void 0?e.message:`${e.message} ${e.fix}`;return e.verdict==="unchecked"?`${r} The deploy stops until it can be checked, as a namespace made by the first repo is unrestricted.`:r},ca=(e,r,t)=>{const n=[];for(const o of e)if(o.verdict==="ok")o.changesAccount===!0&&r.info(o.message);else if(o.verdict==="unchecked"&&t==="preview")r.warn(`dry run: ${o.message}${o.fix===void 0?"":` ${o.fix}`} A real deploy stops here.`);else{const a=ia(o);r.error(a),n.push(a)}return n},$r=async(e,r,t,n,o,a,s)=>{const i=t==="cloudflare"&&r!==void 0?D(r).parsed:void 0;if(i===void 0)return;const c=(X(i,n).merged.artifacts??[]).flatMap(f=>typeof f?.binding=="string"&&typeof f.namespace=="string"?[{binding:f.binding,namespace:f.namespace}]:[]),d=c.length===0?void 0:ue(e,N(e),a).info?.jurisdiction;if(d===void 0)return;const l=[...new Map(c.map(f=>[f.namespace,f])).values()];if(s==="temporary"){o.warn(`--temporary deploys to a throwaway account, so the jurisdiction ("${d}") of Artifacts namespace ${l.map(f=>`"${f.namespace}"`).join(", ")} was not checked: it is created there on first use, in no jurisdiction.`);return}const g=(n===void 0?void 0:i.env?.[n]?.account_id)??i.account_id,u=await Promise.all(l.map(async f=>vt({...f,accountId:g,create:s==="create",jurisdiction:d,missingOk:s==="defer"||s==="preview"}))),h=ca(u,o,s);return h.length===0?void 0:h.join(`
18
+ `);const g=await Et(i),{args:u,command:h}=F(j(t),c.dev({configPath:r===void 0?void 0:ee(t,r),environment:o,extraArgs:[ee(t,d),"--local","--local-protocol","http","--ip","127.0.0.1","--port",String(g),"--persist-to",ee(t,k(n,"state"))]}));return{args:u,command:h,port:g,runId:l}}catch(d){throw new _(`could not prepare the check (${d instanceof Error?d.message:String(d)})`,!0)}},un=async e=>{const{configPath:r,cwd:t,environment:n,launcher:o,logger:a,toolchain:s}=e,i=k(t,N(t),"_generated","functions.ts");if(!S(i)||!A(i,"utf8").includes("export const loadAllFunctions"))return;const c=tn(e);if("skip"in c){a.warn(`smoke-load skipped: ${c.skip}, so lazy modules are not evaluated before deploy`);return}const{main:d}=c,l=[];let g,u;const h=Date.now()+rr,f=process.platform!=="win32",v=(m,E,C)=>{const $=bt(m,[...E],{cwd:C.cwd,detached:f,shell:C.shell,stdio:["ignore","pipe","pipe"]});return f&&$.pid!==void 0&&(u={dispose:on($.pid),pid:$.pid}),$};try{g=dn(t),a.info("smoke-loading lazy function modules in workerd");let m=zt;for(let E=0;E<Te;E+=1){const{args:C,command:$,port:I,runId:T}=await ln({configPath:r,cwd:t,directory:g,environment:n,functionsFile:i,main:d,preferred:m,toolchain:s});m=I+1;const be=await an({args:C,command:$,cwd:t,spawn:o??v,label:"wrangler dev (smoke-load)",notFound:"`wrangler` was not found",onLine:G=>{l.push(G)},port:I,readyTimeoutMs:Math.max(0,h-Date.now()),shell:process.platform==="win32"});if(be===void 0){await te(u),u=void 0;continue}try{const G=await nn(I,T,h);if(G!==void 0){sn(t,G,a);return}}finally{await be.stop(),await te(u),u=void 0}}throw new _(`the smoke port was answered by other runs on all ${String(Te)} attempts`,!0)}catch(m){return cn(m,l,a)}finally{if(await te(u),g!==void 0)try{W(g,{force:!0,recursive:!0})}catch{}}},gn=(e,r)=>r===void 0?e:L(e,r),fn=async e=>{if(e.targets.length===0)return{builtTags:[],code:0};if(!(e.railpackAvailable??Tt)()){const n="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(n),{builtTags:[],code:1,error:n}}const r=e.spawner??x,t=[];for(const n of e.targets){const o=At(n.exportName),a={args:["build",n.buildDir,"--name",o],command:"railpack",cwd:e.cwd},s=he(j(e.cwd),"wrangler",["containers","push",o]),i={args:s.args,command:s.command,cwd:e.cwd};e.logger.info(`railpack: building "${n.exportName}" → ${o} from ${n.buildDir}`);const c=await r(a);if(c.code!==0){const l=`railpack build failed for container "${n.exportName}" (${n.buildDir})`;return e.logger.error(l),{builtTags:t,code:c.code,error:l}}e.logger.info(`railpack: pushing ${o} to the Cloudflare Registry`);const d=await r(i);if(d.code!==0){const l=`wrangler containers push failed for "${n.exportName}" (${o})`;return e.logger.error(l),{builtTags:t,code:d.code,error:l}}t.push(o)}return{builtTags:t,code:0}},tr=e=>{const t=[O(e),k(e,"package.json"),k(e,"wrangler.dev.jsonc")].filter(n=>n!==void 0&&S(n)).map(n=>[n,A(n,"utf8")]);return()=>{for(const[n,o]of t)A(n,"utf8")!==o&&H(n,o,"utf8")}},hn=(e,r=Je())=>L(e,".lunora",`vite-bundle-meta-${r}.json`),nr="LUNORA_CLIENT_BUILD",mn="virtual:lunora/worker",de=(e,r)=>["ts","mts","cts","js","mjs","cjs"].some(t=>S(k(e,`${r}.config.${t}`))),or=e=>de(e,"rsbuild")?"rsbuild":de(e,"vite")?"vite":void 0,vn=e=>de(e,"vite")?"vite":or(e),pn=e=>{try{const{scripts:r}=JSON.parse(A(k(e,"package.json"),"utf8"));return typeof r?.build=="string"&&r.build!==""}catch{return!1}},Q=(e,r)=>{if(process.env[nr]==="1")return;const t=O(e),n=t===void 0?void 0:D(t).parsed,o=n?.main===mn,a=(o?vn(e):or(e))??(pn(e)?"script":void 0);if(a===void 0)return;const s=r===void 0?void 0:n?.env?.[r]?.assets?.directory,i=n?.assets?.directory??s;return o||Nr(e).class!=="C"||i!==void 0?a:void 0},yn=async(e,r,t)=>{const n=t.spawner??x,o=j(e),a=r==="script"?{args:["run","build"],command:o}:he(o,r,["build"]);t.logger.info(`running ${r} build before bundling the Worker`);const s=tr(e),i=t.bundleMetaPath??hn(e);W(k(e,Or),{force:!0});try{const c=await n({args:a.args,command:a.command,cwd:e,env:{[Mr]:Fr(e),[xr]:t.target,[Lr]:i,...t.lazyFunctions?{[Ir]:"1"}:{},...t.environment===void 0?{}:{CLOUDFLARE_ENV:t.environment},...t.strictAdvisories===!1?{[jr]:"0"}:{},[nr]:"1"},stdoutToStderr:t.outputJson});return c.code===0?void 0:`${r} build failed with exit code ${String(c.code)}`}finally{s(),t.bundleMetaPath===void 0&&W(i,{force:!0})}},Z=(e,r,t)=>r!==!1&&Q(e,t)!==void 0,wn=(e,r,t)=>Z(e,r,t)&&Q(e,t)!=="script",me=e=>{const r=e.frameworkBuild===!1?void 0:Q(e.cwd,e.environment);if(r===void 0||r==="script")return;if(e.apiSpec!==void 0)return`--api-spec is read from the ${r} plugin config when the client build runs; set it there, or pass --no-framework-build`;if(e.target!==void 0)try{ie(e.cwd,e.target)}catch(n){return n instanceof Error?n.message:String(n)}let t;try{t=ie(e.cwd)}catch(n){return`the project's configured target cannot be used, and the ${r} plugin reads it: ${n instanceof Error?n.message:String(n)}`}if(e.target!==void 0&&e.target!==t)return`this run targets "${e.target}", but the project's target is "${t}", which the ${r} plugin reads; set it in the project config, or pass --no-framework-build`},ar=async e=>{const r=e.frameworkBuild===!1?void 0:Q(e.cwd,e.environment);if(r===void 0)return;let t;try{t=e.target??ie(e.cwd)}catch(n){return n instanceof Error?n.message:String(n)}return yn(e.cwd,r,{bundleMetaPath:e.bundleMetaPath,environment:e.environment,strictAdvisories:e.strictAdvisories,lazyFunctions:e.lazyFunctions,logger:e.logger,outputJson:e.outputJson,spawner:e.spawner,target:t})},_e=e=>Array.isArray(e)?e.filter(r=>r!=null):void 0,ve=(e,r)=>{const t=O(e);if(!t)return;const{parsed:n}=D(t);if(n===void 0)return;const{error:o,merged:a}=X(n,r),s=o===void 0?a:n,{containers:i,d1_databases:c,vars:d}=s;return{containers:_e(i),d1_databases:_e(c),vars:typeof d=="object"&&d!==null&&!Array.isArray(d)?d:void 0}},kn=/^127(?:\.\d{1,3}){3}$/,bn=e=>{try{const{hostname:r}=new URL(e);return r==="localhost"||kn.test(r)||r==="::1"||r==="[::1]"}catch{return!1}},Sn=e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"),$n=(e,r,t,n="deploy",o)=>{const a=(ve(e,o)?.containers??[]).filter(i=>typeof i?.image=="string"&&Sn(i.image));if(a.length===0||t())return;const s=`${n} blocked: wrangler.jsonc declares ${String(a.length)} container(s) built from a local Dockerfile, but no Docker-compatible engine is available. Start Docker (or Colima), or point the container's \`image\` at a pre-built registry reference. Note: container images must target linux/amd64.`;return r.error(s),s},pe=e=>S(b(e,Se))?Se:void 0,En=(e,r,t="deploy",n)=>{for(const o of He(e,"lunora",n).containers){const a=o.schedulingPolicy===void 0?o.image:void 0,i=[...a?.kind==="dockerfile"?[{field:"image",path:a.dockerfilePath}]:[],...Object.entries(o.schedulingPolicy==="durable_object"?o.images??{}:{}).flatMap(([c,d])=>d.kind==="dockerfile"?[{field:`images["${c}"]`,path:d.dockerfilePath}]:[])].find(c=>!S(b(e,c.path)));if(i!==void 0){const c=`${t} blocked: container "${o.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(c),c}if(a?.kind==="build"&&!S(b(e,a.buildDir))){const c=`${t} blocked: container "${o.exportName}" references a Railpack build directory "${a.buildDir}" that does not exist. Create it or fix the \`image.build\` path in lunora/containers.ts.`;return r.error(c),c}}},An=(e,r)=>r==="celld"?typeof e=="string"&&e!==$e&&ft(e):r==="cloudflare"&&e===$e,Tn=(e,r,t)=>(ve(e,t)?.d1_databases??[]).find(n=>An(n.database_id,r)),Rn=e=>{if(!e.migrate||e.dryRun||e.preview)return;if(e.migrateUrl===void 0){const t="--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(t),t}if(e.migrateYes!==!0){const t="--migrate runs production data migrations after deploy. Re-run with --migrate-yes to confirm.";return e.logger.error(t),t}const r=e.migrateToken??process.env.LUNORA_ADMIN_TOKEN;if(r===void 0||r===""){const t="admin token required for --migrate — pass --migrate-token or set LUNORA_ADMIN_TOKEN";return e.logger.error(t),t}},_n=(e,r,t,n,o)=>{const a=Tn(e,n,o);if(a===void 0)return;const s=`${t} blocked: the "${a.binding??"<unnamed>"}" D1 binding has a placeholder database_id ("${a.database_id??""}")`,i=n==="celld"?`${s}, which celld would use as the database's identity. Set database_id to the database celld should use, then ${t} again.`:`${s}. Run \`lunora doctor --fix\` to create the database and write its id into wrangler.jsonc, or run \`wrangler d1 create <name>\` and paste the id in yourself.`;return r.error(i),i},Dn=(e,r,t="deploy",n)=>{const o=ve(e,n)?.vars;if(!o)return;const a=Object.entries(o).filter(([,i])=>typeof i=="string"&&bn(i)).map(([i])=>i).toSorted((i,c)=>i.localeCompare(c));if(a.length===0)return;const s=`${t} blocked: ${a.join(", ")} in wrangler.jsonc point at localhost. A deployed Worker can't reach a loopback address, so this silently breaks scheduled-job dispatch, reverse cross-shard relations, and auth callbacks. Set each to the deployed worker's public URL (or move it to a secret with \`wrangler secret put\`) before deploying.`;return r.error(s),s},Cn=["vite.config.ts","vite.config.mts","vite.config.cts","vite.config.js","vite.config.mjs","vite.config.cjs",...Rr],sr=/\.(?:[cm]?[jt]s|tsx|jsx)$/u,ir=/\.(?:test|spec)\.[cm]?[jt]sx?$/u,cr="allowUnauthenticatedShardAccess",Pn=/[\\/]/u,dr=new Set(["_generated","build","dist","node_modules"]),lr=(e,r)=>{const t=U(e,r).split(Pn);return sr.test(r)&&!ir.test(r)&&!se(t.join("/"))&&t.every(n=>n===".."||!n.startsWith(".")&&!dr.has(n))},De=(e,r,t)=>{const{parsed:n}=D(r);if(n===void 0)return[];const{error:o,merged:a}=X(n,t),{main:s}=o===void 0?a:n,i=typeof s=="string"?b(Xe(r),s):void 0;return i!==void 0&&S(i)&&lr(e,i)?[i]:[]},ye=e=>e===void 0?!1:e.getKind()===p.FalseKeyword?!0:w.isParenthesizedExpression(e)||w.isAsExpression(e)||w.isSatisfiesExpression(e)||w.isTypeAssertion(e)||w.isNonNullExpression(e)?ye(e.getExpression()):!1,Nn=e=>{try{return Ue(e).isFile()}catch{return!1}},On=new Set(["ELOOP","ENOENT","ENOTDIR"]),K=(e,r,t)=>{const n=r instanceof Error&&"code"in r&&typeof r.code=="string"?r.code:"";On.has(n)||t.push(e)},jn=(e,r)=>{try{return Ue(e)}catch(t){K(e,t,r);return}},ur=(e,r)=>{try{return A(e,"utf8")}catch(t){K(e,t,r);return}},gr=(e,r,t,n=new Set)=>{let o;try{o=Ar(r)}catch(s){return K(r,s,t),[]}if(n.has(o))return[];n.add(o);let a;try{a=Fe(r)}catch(s){return K(r,s,t),[]}return a.flatMap(s=>{const i=b(r,s),c=jn(i,t);if(c===void 0)return[];const d=U(e,i).split(ae).join("/");return c.isDirectory()?dr.has(s)||s.startsWith(".")||se(`${d}/`)?[]:gr(e,i,t,n):c.isFile()&&sr.test(s)&&!ir.test(s)&&!se(d)?[i]:[]})},In=e=>{const r=w.isComputedPropertyName(e)?e.getExpression():e;return w.isStringLiteral(r)||w.isNoSubstitutionTemplateLiteral(r)?r.getLiteralValue():e.getText()},ne=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],Ln=/\.(?:[cm]?js|jsx)$/u,xn=(e,r)=>{if(!r.startsWith("."))return;const t=L(Xe(e),r),n=t.replace(Ln,"");return[t,...ne.map(a=>`${t}${a}`),...ne.map(a=>b(t,`index${a}`)),...ne.map(a=>`${n}${a}`)].find(a=>Nn(a))},Mn=e=>{if(e.getExpression().getText()!=="require")return;const[r]=e.getArguments();return r!==void 0&&(w.isStringLiteral(r)||w.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},Fn=e=>{const r=e.getModuleReference();if(!w.isExternalModuleReference(r))return;const t=r.getExpression();return w.isStringLiteral(t)?t.getLiteralValue():void 0},Un=(e,r,t,n)=>{const o=new Set(e),a=[...e],s=[];for(let i=0;i<a.length;i+=1){const c=a[i]??"",d=ur(c,n);if(d===void 0)continue;const l=r.createSourceFile(U(t,c),d,{overwrite:!0}),g=[...l.getImportDeclarations().map(u=>u.getModuleSpecifierValue()),...l.getExportDeclarations().map(u=>u.getModuleSpecifierValue()),...l.getDescendantsOfKind(p.ImportEqualsDeclaration).map(u=>Fn(u)),...l.getDescendantsOfKind(p.CallExpression).map(u=>Mn(u))].filter(u=>u!==void 0);for(const u of g){const h=xn(c,u);h!==void 0&&lr(t,h)&&!o.has(h)&&(o.add(h),s.push(h),a.push(h))}}return s},Bn=e=>{const r=e.getArgumentExpression();return r!==void 0&&(w.isStringLiteral(r)||w.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},Hn=e=>w.isPropertyAccessExpression(e)?e.getName():w.isElementAccessExpression(e)?Bn(e):void 0,Gn=new Set([p.AmpersandAmpersandEqualsToken,p.AmpersandEqualsToken,p.AsteriskAsteriskEqualsToken,p.AsteriskEqualsToken,p.BarBarEqualsToken,p.BarEqualsToken,p.CaretEqualsToken,p.EqualsToken,p.GreaterThanGreaterThanEqualsToken,p.GreaterThanGreaterThanGreaterThanEqualsToken,p.LessThanLessThanEqualsToken,p.MinusEqualsToken,p.PercentEqualsToken,p.PlusEqualsToken,p.QuestionQuestionEqualsToken,p.SlashEqualsToken]),qn=e=>{const r=e.getOperatorToken().getKind();return!Gn.has(r)||Hn(e.getLeft())!==cr?!1:r!==p.EqualsToken||!ye(e.getRight())},Vn=(e,r,t)=>{const n=[],o=[...new Set([N(e),"src"])].filter(g=>S(b(e,g))),a=O(e),s=[...Cn.map(g=>b(e,g)).filter(g=>S(g)),...a===void 0?[]:De(e,a,r),...t.flatMap(g=>De(e,g,r))],i=new Qe({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}),c=o.flatMap(g=>gr(b(e,g),b(e,g),n));return{sites:[...new Set([...c,...s,...Un([...s,...c],i,e,n)])].flatMap(g=>{const u=ur(g,n);if(u===void 0)return[];const h=i.createSourceFile(U(e,g),u,{overwrite:!0}),f=[...h.getDescendantsOfKind(p.PropertyAssignment),...h.getDescendantsOfKind(p.ShorthandPropertyAssignment),...h.getDescendantsOfKind(p.GetAccessor),...h.getDescendantsOfKind(p.MethodDeclaration)].filter(m=>{const E=w.isPropertyAssignment(m)&&ye(m.getInitializer());return In(m.getNameNode())===cr&&!E}).map(m=>m.getStartLineNumber()),v=h.getDescendantsOfKind(p.BinaryExpression).filter(m=>qn(m)).map(m=>m.getStartLineNumber());return[...f,...v].map(m=>({file:U(e,g),line:m}))}),unreadable:n}},Wn=(e,r,t,n,o,a)=>{if(t!=="deploy")return;const{sites:s,unreadable:i}=Vn(e,o,a),c=Nt({openShardAccess:s,schema:{tables:[]}},{lints:[Ee]});if(c.length===0&&i.length===0)return;const d=[];if(c.length>0){const g=c.map(u=>`${String(u.metadata.file)}:${String(u.metadata.line)}`).join(", ");d.push(`${g} enable the open-shard option (any value but a literal false), so any caller may target any shard.`)}if(i.length>0&&d.push(`could not read ${i.join(", ")}, so the open-shard option cannot be ruled out there.`),n){r.warn(`deploying past the open-shard gate (--allow-open-shards): ${d.join(" ")}`);return}const l=`deploy blocked (open_shard_access): ${d.join(" ")} ${Ee.remediation}`;return r.error(l),l},Kn=(e,r,t,n)=>{const o=Wn(e,r.logger,t,r.allowOpenShards===!0,r.env,n);return o===void 0?void 0:{code:y.USAGE,error:o}},zn=(e,r,t,n)=>{const o=_n(e,r.logger,t,n,r.env);if(o!==void 0)return{code:y.USAGE,error:o};const a=Dn(e,r.logger,t,r.env);if(a!==void 0)return{code:y.USAGE,error:a};const s=En(e,r.logger,t,r.discoveryCache);if(s!==void 0)return{code:y.USAGE,error:s};const i=$n(e,r.logger,r.dockerAvailable??Rt,t,r.env);return i===void 0?void 0:{code:y.MISSING_DEPENDENCY,error:i}},Ce=32,fr=15e3,Jn=5432,Yn=3306,Xn=/[^a-z0-9-]/gu,Qn=/[^A-Za-z0-9]/gu,Zn=/-$/u,B=e=>`LUNORA_${e.replaceAll(Qn,"_").toUpperCase()}_URL`,eo=e=>{const r=new Map;for(const t of e){const n=B(t),o=r.get(n);if(o!==void 0)return{bindings:[o,t],variable:n};r.set(n,t)}},Pe=7,ro=(e,r)=>{const t=`${e}-${r}`.toLowerCase(),n=t.replaceAll(Xn,"-");if(n===t&&n.length<=Ce)return n;const o=St("sha256").update(t).digest("hex").slice(0,Pe-1);return`${n.slice(0,Ce-Pe).replace(Zn,"")}-${o}`},Ne=e=>e==="postgresql"?"postgres":e==="mariadb"?"mysql":e,to=e=>e==="mysql"?Yn:Jn,no=e=>{try{const r=new URL(e),t=r.protocol.slice(0,-1),n=decodeURIComponent(r.pathname.slice(1));return!["mariadb","mysql","postgres","postgresql"].includes(t)||r.hostname===""||n===""?void 0:{database:n,host:r.hostname,password:decodeURIComponent(r.password),port:r.port===""?to(Ne(t)):Number(r.port),scheme:Ne(t),user:decodeURIComponent(r.username)}}catch{return}},oo=(e,r)=>{const t=typeof r?.password=="string"?r.password:"",n=t===""?[]:[t,JSON.stringify(t).slice(1,-1),encodeURIComponent(t)];let o=e;for(const a of n)o=o.replaceAll(a,"<redacted>");return o.split(" ").map(a=>a.includes("://")?"<url>":a).join(" ")},hr=e=>(Array.isArray(e)?e:[]).flatMap((r,t)=>{const{binding:n,id:o}=typeof r=="object"&&r!==null?r:{};return typeof n=="string"&&o===We?[{binding:n,index:t}]:[]}),z=e=>{let r="";try{const{errors:t}=JSON.parse(e.text);r=(t??[]).flatMap(n=>typeof n.message=="string"?[n.message]:[]).slice(0,2).join("; ")}catch{}return r===""?`HTTP ${String(e.status)}`:`HTTP ${String(e.status)}: ${r}`},ao=e=>typeof e=="string"||typeof e=="number"?e.toString():void 0,so=["scheme","host","port","database","user"],io=e=>e==="postgresql"?"postgres":e,Oe=(e,r)=>{const t=ao(r);return e==="scheme"?io(t):t},je=50,co=async(e,r)=>{for(let t=1;t<=je;t+=1){const n=await e(t===1?"/hyperdrive/configs":`/hyperdrive/configs?page=${String(t)}`);if(!n.ok)throw new Error(`listing Hyperdrive configs failed (${z(n)})`);if(!Array.isArray(n.body.result))throw new TypeError("the listing of Hyperdrive configs had no result list");const o=n.body.result.find(s=>s.name===r),a=typeof n.body.result_info=="object"&&n.body.result_info!==null?n.body.result_info:{};if(o!==void 0||typeof a.total_pages!="number"||t>=a.total_pages)return o}throw new Error(`the listing of Hyperdrive configs has more than ${String(je)} pages, so "${r}" can't be shown to be absent`)},lo=async(e,r,t,n)=>{const o=n?{caching:{disabled:!0}}:{},a=await co(e,r);if(typeof a?.id=="string"){const c=so.filter(l=>Oe(l,a.origin?.[l])!==Oe(l,t[l]));if(c.length>0)throw new Error(`a Hyperdrive config named "${r}" already exists for a different origin, or one that can't be confirmed (${c.join(", ")}). Delete it, or rename the Worker, so the binding does not reach the wrong database.`);const d=await e(`/hyperdrive/configs/${encodeURIComponent(a.id)}`,{body:JSON.stringify({origin:t,...o}),method:"PATCH"});if(!d.ok)throw new Error(`updating its credentials failed (${z(d)})`);return{id:a.id,reused:!0}}const s=await e("/hyperdrive/configs",{body:JSON.stringify({name:r,origin:t,...o}),method:"POST"});if(!s.ok)throw new Error(`creating it failed (${z(s)})`);const{id:i}=typeof s.body.result=="object"&&s.body.result!==null?s.body.result:{};if(typeof i!="string")throw new TypeError("the response carried no id");return{id:i,reused:!1}},uo=(e,r,t,n)=>r===void 0&&n?`${B(e)} is set but is not a usable connection string for the "${e}" Hyperdrive binding: it needs a postgres://, postgresql:// or mysql:// scheme, a host and a database name, with any special characters percent-encoded.`:r===void 0?`the "${e}" Hyperdrive binding has no config yet. Set ${B(e)} to its postgres:// or mysql:// connection string and Lunora creates the config, or run \`wrangler hyperdrive create\` and put its id in wrangler.jsonc.`:t?void 0:`creating the "${e}" Hyperdrive config needs CLOUDFLARE_API_TOKEN (Hyperdrive: Edit) and CLOUDFLARE_ACCOUNT_ID, or run \`wrangler hyperdrive create\` and put its id in wrangler.jsonc.`,go=async(e,r)=>{const t=ro(e.workerName,e.binding),{id:n,reused:o}=await lo(async(a,s)=>er({accountId:e.accountId,apiToken:e.token,...e.fetch===void 0?{}:{fetch:e.fetch},init:{...s,signal:AbortSignal.timeout(fr)},path:a}),t,e.origin,e.disableCaching);return e.logger.success(`${o?"reusing":"created"} Hyperdrive config "${t}" for ${e.binding} → ${e.wranglerPath}`),{id:n,text:Ke(r,[...e.path,e.index,"id"],n)}},fo=e=>e===void 0||e===""?void 0:e,mr=e=>{const r=k(M(e),".wrangler","deploy","config.json");try{const{configPath:t}=JSON.parse(A(r,"utf8"));return typeof t=="string"?L(M(r),t):void 0}catch{return}},ho=(e,r,t,n,o)=>{const a=mr(e);if(a===void 0||a===e)return;if(n.built!==n.deployed){o.warn(`the build output ${a} was made for ${n.built===void 0?"the default environment":`"${n.built}"`}, not ${n.deployed===void 0?"the default environment":`"${n.deployed}"`}, so the "${r}" Hyperdrive id was not written there. Build with CLOUDFLARE_ENV set to the environment you deploy, then deploy again.`);return}let s;try{s=D(a)}catch{return}const i=hr(s.parsed?.hyperdrive).find(c=>c.binding===r);i!==void 0&&H(a,Ke(s.text,["hyperdrive",i.index,"id"],t),"utf8")},mo=(e,r)=>{const t=typeof e.name=="string"&&e.name!==""?e.name:"lunora";if(r===void 0)return t;const n=e.env?.[r]?.name;return typeof n=="string"&&n!==""?n:`${t}-${r}`},we=(e,r)=>{const t=O(e),n=t===void 0?void 0:D(t).parsed;if(t===void 0||n===void 0)return;const o=r===void 0?void 0:n.env?.[r],a=hr(r===void 0?n.hyperdrive:o?.hyperdrive);return a.length===0?void 0:{accountId:o?.account_id??n.account_id,entries:a,path:r===void 0?["hyperdrive"]:["env",r,"hyperdrive"],workerName:mo(n,r),wranglerPath:t}},vo=(e,r,t)=>{const n=eo(e.map(({binding:o})=>o));if(n!==void 0){const o=`deploy blocked: the Hyperdrive bindings ${n.bindings.map(a=>`"${a}"`).join(" and ")} both read ${n.variable} and would share one config. Rename one so their names differ in letters or digits, not only in punctuation.`;return t.logger.error(o),o}for(const{binding:o,origin:a,supplied:s}of e){const i=uo(o,a,r,s);if(i!==void 0&&t.dryRun===!0)t.logger.warn(`dry run: ${i} A real deploy stops here.`);else if(i!==void 0){const c=`deploy blocked: ${i}`;return t.logger.error(c),c}}},po=async(e,r,t,n)=>{let o;try{o=await e(`/hyperdrive/configs/${encodeURIComponent(t)}`)}catch(s){n.warn(`could not check whether the "${r}" Hyperdrive config has query caching off (${s instanceof Error?s.message:String(s)}).`);return}if(!o.ok){n.warn(`could not check whether the "${r}" Hyperdrive config has query caching off (${z(o)}).`);return}const{caching:a}=typeof o.body.result=="object"&&o.body.result!==null?o.body.result:{};a?.disabled!==!0&&n.warn(`the "${r}" Hyperdrive config has query caching on, so .global() tables would read rows up to 75 s old. Run \`wrangler hyperdrive update ${t} --caching-disabled\`.`)},yo=async(e,r)=>{const t=O(e.cwd),n=t===void 0?void 0:D(t).parsed,o=e.wranglerEnvironment===void 0?n:n?.env?.[e.wranglerEnvironment],{accountId:a,token:s}=Ze(r,o?.account_id??n?.account_id);if(a===void 0||s===void 0)return;const i=async(c,d)=>er({accountId:a,apiToken:s,...e.fetch===void 0?{}:{fetch:e.fetch},init:{...d,signal:AbortSignal.timeout(fr)},path:c});for(const c of Array.isArray(o?.hyperdrive)?o.hyperdrive:[]){const{binding:d,id:l}=typeof c=="object"&&c!==null?c:{};typeof d=="string"&&typeof l=="string"&&l!==We&&await po(i,d,l,e.logger)}},wo=async e=>{const r=e.environment??process.env;e.disableCaching===!0&&e.checkOnly!==!0&&e.dryRun!==!0&&await yo(e,r);const t=we(e.cwd,e.wranglerEnvironment);if(t===void 0)return;const{entries:n,path:o,wranglerPath:a}=t,{accountId:s,token:i}=Ze(r,t.accountId),c=n.map(({binding:l})=>{const g=r[B(l)]??"";return{binding:l,origin:no(g),supplied:g!==""}}),d=vo(c,i!==void 0&&s!==void 0,e);if(d!==void 0)return d;if(!(e.dryRun===!0||e.checkOnly===!0))for(const[l,{binding:g,index:u}]of n.entries()){const h=c[l]?.origin;if(!(h===void 0||i===void 0||s===void 0))try{const{id:f,text:v}=await go({accountId:s,binding:g,disableCaching:e.disableCaching===!0,fetch:e.fetch,index:u,logger:e.logger,origin:h,path:o,token:i,workerName:t.workerName,wranglerPath:a},A(a,"utf8"));H(a,v,"utf8"),ho(a,g,f,{built:fo(r.CLOUDFLARE_ENV),deployed:e.wranglerEnvironment},e.logger)}catch(f){const v=f instanceof Error?f.message:String(f),m=`deploy blocked: the "${g}" Hyperdrive config could not be set up: ${oo(v,c[l]?.origin)}`;return e.logger.error(m),m}}},ko=(e,r)=>{const t=we(e,r.env)?.entries[0]?.binding;if(t===void 0)return;const n=`prepare blocked: the "${t}" Hyperdrive binding still has its placeholder id. Run \`lunora deploy\` with ${B(t)} set to create the config, or put the id from \`wrangler hyperdrive create\` in wrangler.jsonc.`;return r.logger.error(n),n},bo=(e,r)=>{const t=we(e,r.env)?.entries[0]?.binding;if(t===void 0)return;const n=`deploy blocked: the "${t}" Hyperdrive binding has no config, and a --temporary deploy cannot create one: it would be made in your account while the Worker goes to a temporary one, which a temporary account has no database for. Deploy without --temporary.`;return r.logger.error(n),n},vr=async(e,r,t,n,o="create")=>{if(n!=="cloudflare")return;if(t==="prepare")return ko(e,r);if(r.temporary===!0)return bo(e,r);const a=r.clientBuildEnvironment===void 0?void 0:{...process.env,CLOUDFLARE_ENV:r.clientBuildEnvironment},s=ue(e,N(e),r.discoveryCache);return s.error!==void 0&&r.logger.warn(`could not read the schema (${s.error}), so Hyperdrive configs are set up with query caching off.`),wo({checkOnly:o==="check",cwd:e,disableCaching:s.error!==void 0||s.info?.hasHyperdriveGlobalTable===!0,dryRun:r.dryRun,environment:a,logger:r.logger,wranglerEnvironment:r.env})},So=/https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u,$o=/https:\/\/[^\s"'<>]+/u,Eo=e=>{if(e===void 0)return;const r=So.exec(e);return r?r[0]:$o.exec(e)?.[0]},Ie=e=>e===void 0?"":` (--env ${e})`,Ao=({cwd:e,env:r,logger:t,now:n,url:o})=>{if(o!==void 0)try{const a=Be(e);if(a!==void 0){if(a.workerUrl===o&&a.env===r)return;t.warn(`link: .lunora/project.json records ${a.workerUrl??"(no url)"}${Ie(a.env)}, but this deploy published ${o}${Ie(r)}. Keeping the recorded value — run \`lunora link --url ${o}${r===void 0?"":` --env ${r}`}\` to update it.`);return}const s=(n??(()=>new Date().toISOString()))();Ur(e,{env:r,linkedAt:s,workerName:fe(e),workerUrl:o}),t.success(`link: recorded ${o} in .lunora/project.json (run \`lunora link\` to change)`)}catch{}},To=async(e,r)=>{const t=new Qe({skipAddingFilesFromTsConfig:!0}),n=b(r,"lunora");let o;try{o=_r(t,n)}catch(a){const s=a instanceof Error?a.message:String(a);return e.logger.warn(`--migrate: could not discover migrations (${s}); skipping`),0}if(o.length===0)return e.logger.info("--migrate: no data migrations declared in lunora/"),0;e.logger.info(`--migrate: running ${String(o.length)} migration(s) against deployed worker`);for(const a of o){e.logger.info(`--migrate: up "${a.id}" (table "${a.table}")`);const s={cwd:r,fetchImpl:e.fetchImpl,id:a.id,logger:e.logger,prod:!0,subcommand:"up",token:e.migrateToken,url:e.migrateUrl,yes:e.migrateYes===!0},i=await Ot(s);if(i.code!==0)return e.logger.error(`--migrate: migration "${a.id}" failed — see output above`),i.code;e.logger.success(`--migrate: "${a.id}" applied`)}return 0},Ro=async(e,r)=>{const{info:t}=ue(r,"lunora",e.discoveryCache),n=t?.vectorMetadata??[];if(n.length===0)return;const o=[];for(const i of n){const c=ht(i.kind);if(c===void 0){e.logger.warn(`vector index "${i.index}" declares metadata "${i.property}", whose column type cannot be filtered on in Vectorize — it is stored with each vector but no filter will match it.`);continue}o.push({index:i.index,property:i.property,type:c})}if(o.length===0)return;const s=(await mt({cwd:r,entries:o,exec:he(j(r),"wrangler",[]),logger:e.logger,spawner:e.spawner??x})).filter(i=>i.status!=="failed").length;s>0&&e.logger.success(`vectorize metadata indexes ready: ${String(s)}/${String(o.length)}`)},Le=5,_o=2e3,Do=async(e,r,t)=>{if(e.healthCheck!==!0)return;const n=t??Ye({cwd:r,env:e.env});if(n===void 0){const a="--health-check: the deploy succeeded, but no URL to probe could be resolved — wrangler's output carried none and this checkout has no link for this environment. Run `lunora link --url <https://your-worker>` and re-deploy, or drop --health-check.";return e.logger.error(a),{error:a,ok:!1,url:""}}const o=await _t({attempts:Le,baseUrl:n,delayMs:_o,fetchImpl:e.healthFetch,paths:[Dt,Ct],sleep:e.healthSleep});return o.error===void 0?(e.logger.success(`health check ok (${o.url})`),{ok:!0,url:o.url}):(e.logger.error(`--health-check: the deploy succeeded, but the new version did not answer after ${String(Le)} attempt(s) — ${o.error}`),{error:o.error,ok:!1,url:o.url})},Co=async(e,r,t,n,o,a)=>{await Ro(e,r);const s=e.migrate?await To(e,r):0;return s===0&&o?.(),{code:s,descriptor:t,mintedSecretsFile:a,validation:n}},Po=async({cwd:e,descriptor:r,mintedSecretsFile:t,options:n,reblessSchemaBaseline:o,recordArchitecture:a,stdout:s,validation:i})=>{const c={deployedAt:new Date().toISOString(),dryRun:n.dryRun===!0,env:n.env,preview:n.preview===!0,url:n.dryRun===!0?void 0:Eo(s),workerName:fe(e)};if(n.dryRun===!0||n.preview===!0)return n.healthCheck===!0&&n.logger.warn(`--health-check skipped: ${n.dryRun===!0?"a dry run publishes nothing":"a preview version serves no live traffic"}`),{code:0,deployment:c,descriptor:r,mintedSecretsFile:t,validation:i};n.temporary!==!0&&(a?.(),Ao({cwd:e,env:n.env,logger:n.logger,url:c.url}));const d=await Do(n,e,c.url);return d?.error!==void 0?{code:y.UNAVAILABLE,deployment:c,descriptor:r,healthCheck:d,mintedSecretsFile:t,validation:i}:{...await Co(n,e,r,i,o,t),deployment:c,healthCheck:d}},No=(e,r,t)=>{const n=b(e,P);if(!S(n))return;let o;try{o=Ge(A(n,"utf8")).length}catch{return}if(o===0)return;const a=t.toolchain?.secretPut!==void 0;r.warn(a?`Note: \`lunora deploy\` does not push secrets. ${P} has ${String(o)} key(s); if you changed them, run \`lunora env push --yes\` to update the deployed secrets.`:`Note: ${t.name} deploys read no secrets. ${P} has ${String(o)} key(s) that only the dev server sees; a key the app reads from env must be a \`vars\` entry in the deployed config, one it loads from a secret manager at runtime need not.`)},pr=async(e,r)=>{let t=[];try{t=Br(await qe({cache:r,projectRoot:e,schemaDir:N(e)}))}catch{}const n=[...new Set(Hr(t).map(a=>a.key))];let o=[];try{const a=b(e,P);S(a)&&(o=Ge(A(a,"utf8")).map(s=>s.key).filter(s=>ze(s)))}catch{}return{fromLocal:o.filter(a=>!n.includes(a)),fromPackages:n,mintableKeys:Gr(t)}},Oo=async(e,r,t,n)=>{const{logger:o}=r,a=r.spawner??x,s=j(e),i=r.env===void 0?"":` --env ${r.env}`,c=n.toolchain?.secretPut;if(c===void 0)return o.error(`deploy target "${n.id}" has no secret store; cannot push secrets`),{minted:[],ok:!1};const d=t.map(u=>({key:u,value:qr()})),l=n.toolchain?.secretBulk;if(l!==void 0&&d.length>=2){const u=F(s,l({environment:r.env,temporary:r.temporary})),h=await a({args:u.args,command:u.command,cwd:e,input:JSON.stringify(Object.fromEntries(d.map(f=>[f.key,f.value])))});if(h.code===0){for(const{key:f}of d)o.success(`generated + pushed ${f}`);return{minted:d,ok:!0}}o.warn(`bulk secret push failed (exit ${String(h.code)}); retrying one key at a time`)}const g=[];for(const{key:u,value:h}of d){const f=c({environment:r.env,key:u,temporary:r.temporary}),v=F(s,f),m=await a({args:v.args,command:v.command,cwd:e,input:h});if(m.code!==0)return o.error(`failed to push secret ${u} (exit ${String(m.code)}); set it manually with \`wrangler secret put ${u}${i}\`.`),{minted:g,ok:!1};g.push({key:u,value:h}),o.success(`generated + pushed ${u}`)}return{minted:g,ok:!0}},jo=/^[\w-]+$/u,xe=[".dev.vars",".dev.vars.*","!.dev.vars.example"],Io=(e,r)=>{try{const t=zr(e,xe);t.length>0&&r.info(`.gitignore: added ${t.join(", ")} so the recorded secret cannot be committed`)}catch(t){r.warn(`could not update .gitignore (${t instanceof Error?t.message:String(t)}) — add \`${xe.join("` and `")}\` by hand before committing.`)}},Lo=(e,r,t)=>{if(t.length===0)return;const n=t.map(i=>i.key).join(", ");if(r.env!==void 0&&!jo.test(r.env)){r.logger.warn(`${n}: 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 o=r.env===void 0?P:`${P}.${r.env}`;Io(e,r.logger);const a=b(e,o);let s=S(a)?A(a,"utf8"):"";for(const i of t)s=Vr(s,i.key,i.value);return Wr(a,s),r.logger.success(r.env===void 0?`${n}: value(s) recorded in ${o}`:`${n}: value(s) recorded in ${o} (kept separate from ${P} so \`lunora dev\` and a plain \`lunora env push\` don't inherit the --env ${r.env} value)`),o},xo=/^<[^>]+>$/u,Mo=async(e,r,t)=>{let n;try{n=t.projectConfig?.(e,"deploy").vars??{}}catch(l){return{error:l instanceof Error?l.message:String(l)}}const o=l=>{const g=n[l];if(typeof g!="string")return!0;const u=g.trim();return u===""||xo.test(u)?!0:ze(l)&&Kr(g)},a=l=>Object.hasOwn(n,l)?`${l} (empty or a placeholder)`:l,{fromLocal:s,fromPackages:i}=await pr(e,r.discoveryCache),c=s.filter(l=>o(l));c.length>0&&r.logger.warn(`${P} key(s) not set in the wrangler vars: ${c.map(l=>a(l)).join(", ")}. ${t.name} has no secret store: a key the app reads from env must be a \`vars\` entry; one it loads from a secret manager at runtime need not.`);const d=i.filter(l=>o(l));return d.length===0?{}:{error:`missing required secret(s) in the wrangler vars: ${d.map(l=>a(l)).join(", ")}. ${t.name} has no secret store and Lunora reads these from env, so each must be a real \`vars\` value in the config the deploy ships — write it there from your secret manager at deploy time rather than committing it. Add them, then re-deploy.`}},Fo=async(e,r,t,n)=>{if(r.dryRun===!0||r.preview===!0)return{};if(n.toolchain?.secretList===void 0)return Mo(e,r,n);const{logger:o}=r,a=r.env===void 0?"":` --env ${r.env}`;let s;try{s=await(r.secretLister??It)({cwd:e,env:r.env,target:n.id,temporary:r.temporary})}catch{return{}}if(!s.ok)return{};const i=new Set(s.names),{fromLocal:c,fromPackages:d,mintableKeys:l}=await pr(e,r.discoveryCache),g=[...d,...c].filter(f=>!i.has(f));if(g.length===0)return{};if(!t)return{error:`missing required secret(s) on the deploy target: ${g.join(", ")}. Set them with \`wrangler secret put <KEY>${a}\` (or \`lunora env generate --set\` then \`lunora env push --yes${a}\`), then re-deploy.`};for(const f of g.filter(v=>!l.has(v)))o.warn(`required secret ${f} is not set on the target — set it with: wrangler secret put ${f}${a}`);const u=g.filter(f=>l.has(f));if(u.length===0)return{};if(await(r.secretConfirm??jt())(`${String(u.length)} required secret(s) not set on the target (${u.join(", ")}). Generate strong values and push them now?`)){const{minted:f,ok:v}=await Oo(e,r,u,n),m=Lo(e,r,f);return v?{mintedSecretsFile:m}:{error:"failed to push required secret(s) — set them manually and re-deploy",mintedSecretsFile:m}}return o.warn(`${String(u.length)} required secret(s) not set on the target: ${u.join(", ")}. Generate + push with \`lunora env generate --set\` then \`lunora env push --yes${a}\`.`),{}},yr=e=>e.format==="json"?!1:e.interactive!==void 0?e.interactive:process.stdout.isTTY&&!process.env.CI,Uo=async(e,r)=>{if(r.dryRun===!0)return;const t=He(e,"lunora",r.discoveryCache).containers.flatMap(o=>o.schedulingPolicy===void 0&&o.image.kind==="build"?[{buildDir:o.image.buildDir,exportName:o.exportName}]:[]);if(t.length===0)return;const n=await fn({cwd:e,logger:r.logger,railpackAvailable:r.railpackAvailable,spawner:r.spawner,targets:t});return n.code===0?void 0:n.error??"railpack build failed"},Bo=(e,r,t)=>{if(t!==void 0)try{const n=it(e,t);n.changed&&r.success(`synced ${String(t.length)} cron trigger(s) → ${n.wranglerPath??"wrangler.jsonc"}`);for(const a of n.warnings)r.warn(a);const o=ct(n.preserved);o!==void 0&&r.info(o)}catch(n){const o=n instanceof Error?n.message:String(n);r.warn(`cron trigger sync skipped: ${o}`)}},Ho=async(e,r,t,n,o,a)=>{try{Y(n);const s=await qe({cache:a,projectRoot:e,schemaDir:N(e)}),i=at(e,s,{environment:o,target:n}),c=i.wranglerPath??"wrangler.jsonc";if(i.added.length>0&&r.success(`provisioned bindings: ${i.added.join(", ")} → ${c}`),i.updated.length>0&&r.success(`updated bindings: ${i.updated.join(", ")} → ${c}`),i.devConfig!==void 0){const{added:d,path:l,updated:g}=i.devConfig;r.success(`dev sidecar bindings: ${[...d,...g].join(", ")} → ${l}`)}for(const d of i.warnings)r.warn(d)}catch(s){const i=s instanceof Error?s.message:String(s);r.warn(`binding inference skipped: ${i}`)}try{const s=st(e);s.changed&&r.success(`bumped compatibility_date to ${s.date??"unknown"} (Workers Cache enabled) → ${s.wranglerPath??"wrangler.jsonc"}`)}catch(s){const i=s instanceof Error?s.message:String(s);r.warn(`compatibility date sync skipped: ${i}`)}Bo(e,r,t)},Go=async(e,r,t,n,o,a,s,i,c,d)=>{let l;r?(l=new dt({name:"dots"}),l.start("running codegen")):t.info("running codegen");try{const g=Dr({apiSpec:n,dryRun:!d,lazyFunctions:o,projectRoot:e,target:a,...ot(e)});l?.succeed("codegen complete"),l||t.success("codegen complete");const u=lt(g.platformDiagnostics,t);if(u.errors.length>0)return{error:u.errors.join("; ")};const{errorAdvisories:h,names:f,shouldBlock:v}=ut(g.advisories,c);if(v){const E=`${h.length.toString()} ERROR-level ${h.length===1?"advisory":"advisories"} (${f.join(", ")}). Pass --no-strict-advisories to downgrade this to a warning and continue.`;return t.error(E),{error:E}}const m=d?await Zr({cwd:e,logger:t,spawner:s,stdoutToStderr:i}):void 0;return m?.error!==void 0?{error:m.error}:{result:g}}catch(g){l?.failed("codegen failed");const u=g instanceof Error?g.message:String(g);return t.error(`codegen failed: ${u}`),{error:`codegen failed: ${u}`}}},qo=(e,r)=>({dryRun:r.dryRun,entry:pe(e),environment:r.env,outDir:r.outDir,preview:r.preview,temporary:r.temporary}),wr=(e,r,t)=>{const{toolchain:n}=t;if(n===void 0)throw new Error(`deploy target "${t.id}" has no command-line toolchain`);const o=qo(e,r);return Ve(t,e,"deploy",a=>n.deploy({...o,configPath:a}))},Vo=(e,r,t)=>{const n=wr(e,r,t),o=pe(e);return o!==void 0&&r.logger.info(`class-B composition: deploying ${o} (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}`),n.commit(),n.projection!==void 0&&n.projection.dropped.length>0&&r.logger.warn(`${t.name} ignores these wrangler keys, so they were left out of ${n.projection.configPath}: ${n.projection.dropped.join(", ")}`),n.command},R={problems:[],wranglerPath:void 0},oe=(e,r)=>({code:y.USAGE,descriptor:void 0,error:e,validation:R,...r}),Wo=(e,r)=>{for(const t of e.report?.warnings??[])r.warn(`wrangler.jsonc: ${t}`);if(e.problems.length===0)return!1;r.error("wrangler.jsonc validation failed:");for(const t of e.problems)r.error(` - ${t}`);return!0},Ko=(e,r,t)=>{const n=r.format==="json",o=r.dryRun!==!0,a=Vo(e,r,t),s=F(j(e),a);return{args:s.args,captureStdout:o&&!n,captureStdoutSilently:o&&n,command:s.command,cwd:e,stdoutToStderr:n&&!o}},ke=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"},zo=(e,r)=>ke(r)===void 0?le(e).services.map(t=>t.wranglerPath):[],kr=(e,r,t,n,o)=>({cwd:e,environment:r.env,frameworkBuild:n,lazyFunctions:J(r.lazyFunctions),logger:r.logger,outputJson:r.format==="json"||r.clientBuildOutputJson===!0,spawner:o,strictAdvisories:ge(r),target:t.id}),Jo=(e,r,t)=>{const{toolchain:n}=t,o=n===void 0?`target "${t.id}" has no deploy command`:ke(r);if(o!==void 0||n===void 0){const a=e.map(s=>s.worker).join(", ");r.logger.warn(`services not deployed (${o??""}): ${a} — deploy them yourself if the app calls anything new`);return}return n},br=(e,r)=>{for(const t of e){const n=me(r(M(t.wranglerPath)));if(n!==void 0)return`service ${t.name} (${t.worker}): ${n}`}},Yo=(e,r,t)=>{const{error:n,services:o}=le(e);if(n!==void 0||o.length===0)return;const a=Y(t);if(a.toolchain===void 0||ke(r)!==void 0)return;const s=r.skipCodegen===!0?!1:r.frameworkBuild,i=[...new Map(o.map(c=>[c.wranglerPath,c])).values()];return br(i,c=>kr(c,r,a,s,x))},Sr=(e,r,t)=>{const n=e.cwd??process.cwd(),o=kt(n,e.target);if(o.target===void 0){const i=o.error??"unknown deploy target";return e.logger.error(i),{kind:"refused",error:i,validation:R}}try{wr(n,e,Y(o.target))}catch(i){if(!(t&&i instanceof Jr&&Z(n,e.skipCodegen===!0?!1:e.frameworkBuild,e.env))){const c=i instanceof Error?i.message:String(i);return e.logger.error(c),{kind:"refused",error:c,validation:R}}}const a=e.openShardGatePassed===!0?void 0:Kn(n,e,r,zo(n,e));if(a!==void 0)return{kind:"refused",code:a.code,error:a.error,validation:R};const s=Yo(n,e,o.target);return s!==void 0?(e.logger.error(s),{kind:"refused",code:y.USAGE,error:s,validation:R}):{kind:"ok",target:o.target}},Xo=(e,r)=>e.apiSpec??(e.clientBuildRan===!0?et(r):void 0),Qo=async(e,r,t)=>{if(r!=="celld")return;const n=await(e.celldToolchain??Qr)({dryRun:t==="prepare"||e.dryRun===!0,env:process.env,purpose:"deploy"});for(const o of n.warnings)e.logger.warn(o);return n.errors.length>0?n.errors.join("; "):void 0},Zo=async(e,r)=>{const t=e.cwd??process.cwd(),n=yr(e),o=ge(e),a={problems:[],wranglerPath:void 0},s=Sr(e,r,!1);if(s.kind==="refused")return{code:s.code,error:s.error,validation:s.validation};const{target:i}=s,c=await Qo(e,i,r);if(c!==void 0)return e.logger.error(c),{code:y.MISSING_DEPENDENCY,error:c,target:i,validation:a};let d;if(!e.skipCodegen){const v=await Go(t,n,e.logger,Xo(e,t),J(e.lazyFunctions),i,e.spawner,e.format==="json",o,e.clientBuildRan!==!0);if(v.error!==void 0)return{error:v.error,target:i,validation:R};d=v.result,e.discoveryCache?.clear()}let l;if(d!==void 0){const v=Pt({allowDrift:e.allowSchemaDrift===!0,codegen:d,command:r,logger:e.logger,updateBaseline:e.updateSchemaBaseline===!0});if(v.blocked)return{error:`schema drift gate blocked ${r}`,schemaDrift:{blocked:!0,reason:v.reason},target:i,validation:a};l=v.rebless}const g=d&&Ht({current:d.architecture,cwd:t,environment:e.env,logger:e.logger});await Ho(t,e.logger,d?.cronTriggers,i,e.env,e.discoveryCache);const u=await vr(t,e,r,i,"check");if(u!==void 0)return{error:u,target:i,validation:R};const h=zn(t,e,r,i);if(h!==void 0)return{code:h.code,error:h.error,target:i,validation:R};const f=nt({environment:e.env,projectRoot:t});return Wo(f,e.logger)?{error:"wrangler validation failed",target:i,validation:f}:{codegen:d,reblessSchemaBaseline:l,recordArchitecture:g,target:i,validation:f}},ea=e=>{W(k(e,".wrangler","deploy","config.json"),{force:!0})},ra=async(e,r,t)=>{const n=me(e);if(n!==void 0)return{built:!1,error:n};const o=Z(e.cwd,r,t);return o&&ea(e.cwd),{built:o,error:await ar(e)}},ta=(e,r,t)=>r||t===!1?mr(e):void 0,na=async(e,r,t,n)=>{const{error:o,services:a}=le(e);if(o!==void 0)return{code:y.FAILURE,error:o};if(a.length===0)return;const s=Jo(a,r,t);if(s===void 0)return;const i=j(e),c=[...new Map(a.map(u=>[u.wranglerPath,u])).values()],d=r.skipCodegen===!0?!1:r.frameworkBuild,l=u=>kr(u,r,t,d,n),g=br(c,l);if(g!==void 0)return r.logger.error(g),{code:y.USAGE,error:g};for(const u of c){const h=M(u.wranglerPath),f=l(h),{built:v,error:m}=await ra(f,d,r.env);if(m!==void 0){const T=`service ${u.name} (${u.worker}): ${m}`;return r.logger.error(T),{code:y.FAILURE,error:T}}const E=ta(u.wranglerPath,v,d);let C;try{C=Ve(t,h,"deploy",T=>s.deploy({configPath:T??E??u.wranglerPath,dryRun:r.dryRun===!0,environment:r.env}))}catch(T){return{code:y.FAILURE,error:`service ${u.name} (${u.worker}): ${T instanceof Error?T.message:String(T)}`}}C.commit();const $=F(i,C.command);r.logger.info(`deploying service ${u.name} (${u.worker}) via ${$.command} ${$.args.join(" ")}`);const I=await n({args:$.args,command:$.command,cwd:h,stdoutToStderr:r.format==="json"});if(I.code!==0)return{code:y.FAILURE,error:`service ${u.name} (${u.worker}): ${$.command} ${$.args.join(" ")} exited ${String(I.code)} — stopping before the app`}}},oa=async(e,r,t,n)=>{if(r!=="cloudflare")return;const o=e===void 0?void 0:D(e).parsed,a=(t===void 0?void 0:o?.env?.[t]?.account_id)??o?.account_id,s=await pt({accountId:a});(s.verdict==="near"||s.verdict==="full")&&n.warn(s.fix===void 0?s.message:`${s.message} ${s.fix}`)},aa=e=>e.dryRun!==!0&&e.temporary!==!0,sa=e=>e.temporary===!0?"temporary":e.dryRun===!0?"preview":"defer",ia=e=>{const r=e.fix===void 0?e.message:`${e.message} ${e.fix}`;return e.verdict==="unchecked"?`${r} The deploy stops until it can be checked, as a namespace made by the first repo is unrestricted.`:r},ca=(e,r,t)=>{const n=[];for(const o of e)if(o.verdict==="ok")o.changesAccount===!0&&r.info(o.message);else if(o.verdict==="unchecked"&&t==="preview")r.warn(`dry run: ${o.message}${o.fix===void 0?"":` ${o.fix}`} A real deploy stops here.`);else{const a=ia(o);r.error(a),n.push(a)}return n},$r=async(e,r,t,n,o,a,s)=>{const i=t==="cloudflare"&&r!==void 0?D(r).parsed:void 0;if(i===void 0)return;const c=(X(i,n).merged.artifacts??[]).flatMap(f=>typeof f?.binding=="string"&&typeof f.namespace=="string"?[{binding:f.binding,namespace:f.namespace}]:[]),d=c.length===0?void 0:ue(e,N(e),a).info?.jurisdiction;if(d===void 0)return;const l=[...new Map(c.map(f=>[f.namespace,f])).values()];if(s==="temporary"){o.warn(`--temporary deploys to a throwaway account, so the jurisdiction ("${d}") of Artifacts namespace ${l.map(f=>`"${f.namespace}"`).join(", ")} was not checked: it is created there on first use, in no jurisdiction.`);return}const g=(n===void 0?void 0:i.env?.[n]?.account_id)??i.account_id,u=await Promise.all(l.map(async f=>vt({...f,accountId:g,create:s==="create",jurisdiction:d,missingOk:s==="defer"||s==="preview"}))),h=ca(u,o,s);return h.length===0?void 0:h.join(`
19
19
  `)},da=async(e,r,t,n,o,a)=>{const s=aa(r)?await $r(e,a,o,r.env,r.logger,r.discoveryCache,"create"):void 0;if(s!==void 0)return{code:y.FAILURE,error:s};const i=await vr(e,r,"deploy",o);return i!==void 0?{code:y.FAILURE,error:i}:na(e,r,t,n)},la=async(e,r,t,n)=>{if(!(r.smokeLoad===!1||t.toolchain===void 0))return un({composedEntry:pe(e),configPath:n,cwd:e,environment:r.env,launcher:r.smokeLauncher,logger:r.logger,toolchain:t.toolchain})},ua=async e=>{const r={...e,discoveryCache:e.discoveryCache??Xr()},t=r.cwd??process.cwd(),n=yr(r),o=await Zo(r,r.commandName??"deploy");if(o.error!==void 0){if(o.validation.problems.length>0)return{code:y.USAGE,descriptor:void 0,error:o.error,validation:o.validation};const m=o.schemaDrift===void 0?void 0:{schemaDrift:o.schemaDrift};return oe(o.error,{...m,...o.code===void 0?{}:{code:o.code}})}const{validation:a}=o,s=Y(o.target),i=Rn(r)??await $r(t,a.wranglerPath,o.target,r.env,r.logger,r.discoveryCache,sa(r))??await la(t,r,s,a.wranglerPath);if(i!==void 0)return oe(i);const c=s.toolchain?.prebuildsContainerImages===!0?await Uo(t,r):void 0;if(c!==void 0)return oe(c);No(t,r.logger,s),tt(t,m=>{r.logger.warn(m)}),await oa(a.wranglerPath,o.target,r.env,r.logger);const{error:d,mintedSecretsFile:l}=await Fo(t,r,n,s);if(d!==void 0)return r.logger.error(d),{code:y.USAGE,descriptor:void 0,error:d,mintedSecretsFile:l,validation:a};const g=r.spawner??x,u=await da(t,r,s,g,o.target,a.wranglerPath);if(u!==void 0)return{code:u.code,descriptor:void 0,error:u.error,mintedSecretsFile:l,validation:a};const h=Ko(t,r,s);r.logger.info(`deploying via ${h.command} ${h.args.join(" ")}`);const f=await g(h);return h.captureStdoutSilently===!0&&f.stdout!==void 0&&f.stdout!==""&&process.stderr.write(f.stdout),f.code!==0?{code:f.code,descriptor:h,mintedSecretsFile:l,validation:a}:{...await Po({...o,cwd:t,descriptor:h,mintedSecretsFile:l,options:r,stdout:f.stdout}),logsAvailable:s.toolchain?.tail!==void 0}},ga=async e=>{const{logger:r}=e,t=e.cwd??process.cwd(),n={apiSpec:e.apiSpec,cwd:t,environment:e.env,bundleMetaPath:e.bundleMetaPath,frameworkBuild:e.skipCodegen===!0?!1:e.frameworkBuild,strictAdvisories:ge(e),lazyFunctions:J(e.lazyFunctions),logger:r,outputJson:e.format==="json"||e.clientBuildOutputJson===!0,spawner:e.spawner,target:e.target},o=me(n);if(o!==void 0)return r.error(o),{code:y.USAGE,descriptor:void 0,error:o,validation:R};Yr(t);const a=await ar(n);if(a!==void 0)return r.error(a),{code:y.FAILURE,descriptor:void 0,error:a,validation:R}},fa=(e,r)=>{const t=r.skipCodegen===!0?!1:r.frameworkBuild;return Z(e,t,r.env)?r.env:void 0},ha=async e=>{const{logger:r}=e,t=e.cwd??process.cwd(),n=Sr(e,e.commandName??"deploy",!0);if(n.kind==="refused")return{code:n.code??y.USAGE,descriptor:void 0,error:n.error,validation:n.validation};const o=await ga(e);if(o!==void 0)return o;const a=e.dryRun===!0?tr(t):void 0;let s;try{if(s=await ua({...e,clientBuildEnvironment:fa(t,e),clientBuildRan:wn(t,e.skipCodegen===!0?!1:e.frameworkBuild,e.env),logger:r,openShardGatePassed:!0}),s.code===0&&e.emitBindings!==void 0){const{error:i}=yt({destination:e.emitBindings,logger:r,projectRoot:e.cwd??process.cwd()});i!==void 0&&(r.error(i),s={...s,code:y.USAGE})}}finally{a?.()}if(e.format==="json")return s;if(s.code===0&&e.dryRun!==!0&&e.preview!==!0)Gt({cwd:e.cwd??process.cwd(),env:e.env,logger:e.logger,logsAvailable:s.logsAvailable===!0,mintedSecretsFile:s.mintedSecretsFile,url:s.deployment?.url});else if(s.code===0&&e.preview===!0){const i=s.deployment?.url;e.logger.success(i===void 0?"preview version uploaded":`preview version uploaded — ${i}`)}return s},Wa=wt(async({cwd:e,format:r,logger:t,options:n})=>{const o=gn(e,n.root),a=await ha({allowOpenShards:n.allowOpenShards===!0,allowSchemaDrift:n.allowSchemaDrift===!0,apiSpec:gt(n.apiSpec),frameworkBuild:n.prebuilt===!0?!1:n.frameworkBuild,lazyFunctions:J(n.lazyFunctions),cwd:o,dryRun:n.dryRun===!0,env:n.env,format:r,healthCheck:n.healthCheck===!0,logger:t,migrate:n.migrate===!0,migrateToken:n.migrateToken,migrateUrl:Ye({cwd:o,env:n.env,url:n.migrateUrl}),migrateYes:n.migrateYes===!0,preview:n.preview===!0,skipCodegen:n.prebuilt===!0,skipServices:n.skipServices===!0,smokeLoad:n.smokeLoad,strictAdvisories:n.strictAdvisories,target:n.target,temporary:n.temporary===!0,updateSchemaBaseline:n.updateSchemaBaseline===!0});return{code:a.code,data:{deployment:a.deployment,healthCheck:a.healthCheck,mintedSecretsFile:a.mintedSecretsFile,schemaDrift:a.schemaDrift,validation:a.validation},error:a.error}});export{Zo as a,Ho as b,Wa as e,gn as p,ha as r,la as s,hn as v};
@@ -1 +1,99 @@
1
- import{existsSync as v,readFileSync as R,realpathSync as y}from"node:fs";import{join as f}from"node:path";import{readProjectTarget as p,DEFAULT_TARGET as m,readServiceBindings as D}from"@lunora/codegen";import{DEV_VARS_FILE as g,parseDevVariableEntries as S,D1_PLACEHOLDER_ID as N,isPlaceholderValue as I,readProjectDependencies as T,discoverSchemaInfo as U,inferLunoraBindings as P,resolveSchemaDirectory as B,probeCelldToolchain as F}from"@lunora/config";import{GLOBAL_FETCH_STRICTLY_PUBLIC_FLAG as h,resolveObservabilitySampling as G,findWranglerFile as L,readWranglerJsonc as j,buildBindingManifest as M,validateWranglerProject as V,UNEXPORTED_CLASS_MARKER as k,detectCloudflareCliConfig as W,collectExportGaps as K}from"@lunora/config/cloudflare";import{a as H,i as z,b as J,c as q,m as Y,d as X,e as Q,f as Z}from"../packem_shared/vectorize-metadata-DOB1akh6.mjs";import{r as ee,d as ne}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{n as E}from"../packem_shared/cloudflare-credentials-BVmZnDZk.mjs";import{d as oe}from"../packem_shared/command-B6vu47iR.mjs";import{i as te}from"../packem_shared/path-containment-CgxYZggb.mjs";import{A as _,a as x,b}from"../packem_shared/variables-CPYyJtsL.mjs";const re=(r,o)=>{const e=new Set,n=s=>{for(const[i,c]of Object.entries(s??{}))typeof c=="string"&&c.trim().length>0&&e.add(i)};n(r.vars);for(const s of Object.values(r.env??{}))n(s.vars);const t=f(o,g);if(v(t))try{n(Object.fromEntries(S(R(t,"utf8")).map(s=>[s.key,s.value])))}catch{}return e},se=(r,o,e,n)=>{if(r===void 0||!e)return;const t=re(r,o),s=t.has(_),i=r.ai?.binding;!s&&(typeof i!="string"||i.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 ${_} 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."}),t.has(x)&&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:`${x} is set, but ctx.ai's Workers AI binding cannot send a gateway token — it is ignored on that path.`}),!s&&!t.has(b)&&n.push({code:"ai-gateway-default",fix:`Run \`lunora cloudflare ai-gateway\` to create a gateway for this app and write ${b} into wrangler vars.`,level:"info",message:`no ${b} in vars or ${g} — \`<provider>/<model>\` slugs route through the account's \`default\` AI Gateway.`})},ae=(r,o,e)=>{if(r===void 0||!o)return;const n=[];(r.compatibility_flags??[]).includes(h)||n.push("the top level");for(const[t,s]of Object.entries(r.env??{}))s.compatibility_flags!==void 0&&!s.compatibility_flags.includes(h)&&n.push(`env.${t}`);n.length>0&&e.push({code:"cimd-fetch-not-strictly-public",fix:`Add "${h}" to "compatibility_flags" in wrangler.jsonc.`,level:"warn",message:`@lunora/auth/cimd/workers is imported, but ${n.join(", ")} of wrangler.jsonc lacks the ${h} compatibility flag — workersCimdFetch() refuses to build without it.`})},$=r=>{const{logs:o,traces:e}=G(r);return Object.entries({logs:o,traces:e}).filter(([,n])=>n.enabled&&n.headSamplingRate>=1).map(([n])=>n)},ie=(r,o)=>{if(r===void 0)return;const e=[],n=$(r.observability);n.length>0&&e.push(`${n.join(" + ")} (top level)`);for(const[t,s]of Object.entries(r.env??{})){if(s.observability===void 0)continue;const i=$(s.observability);i.length>0&&e.push(`${i.join(" + ")} (env.${t})`)}e.length!==0&&o.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.`})},C={ai:"Workers AI",browser:"Browser Rendering",images:"Cloudflare Images (Image Transformations)"},A=["Argo Smart Routing","Log Explorer"],ce=r=>{const o=[["top level",r],...Object.entries(r.env??{}).flatMap(([n,t])=>t?[[`env.${n}`,t]]:[])],e=new Map;for(const[n,t]of o)for(const s of M(t).bindings)C[s.type]!==void 0&&e.set(s.type,[...e.get(s.type)??[],n]);return e},le=(r,o)=>{if((p(r)??m)!=="cloudflare")return;const e=L(r),n=e===void 0?void 0:j(e).parsed;if(n!==void 0)for(const[t,s]of ce(n)){const i=C[t]??t;o.push({code:"paid-product-bound",fix:"Create an account budget alert in the dashboard: Manage Account > Billing > Billable Usage > Create budget alert. Lunora cannot create or read one.",level:"info",message:`${i} is bound (${s.join(", ")}) and billed per use. No documented usage-alert product covers it, and lunora cannot read budget alerts, so an account budget alert is the only cap.`})}o.push({code:"paid-product-unknown",level:"info",message:`enablement of ${A.join(" and ")} cannot be read by lunora (dashboard settings); check the dashboard if your account uses ${A.length>1?"them":"it"}.`})},de=(r,o)=>{for(const e of D(r).services)for(const n of e.publicScopes){const t=n===""?"":` (env.${n})`;o.push({code:"service-workers-dev",fix:`If ${e.name} has no public route (custom domain or route, including ones set outside ${e.wranglerPath}), set \`"workers_dev": false\`${t}. Keep its internal auth (HMAC) either way.`,level:"warn",message:`service ${e.name} (${e.worker}) has no route in its wrangler config and still serves on workers.dev${t}; a custom domain set elsewhere would also be public.`})}},O=r=>{const o=L(r);if(o===void 0)return{parsed:void 0,path:void 0};const{parsed:e}=j(o);return{parsed:e,path:o}},ue=(r,o,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(o===void 0){n.push({code:"wrangler-unparseable",fix:`Check ${e} is valid JSONC.`,level:"fail",message:`Could not parse ${e}.`});return}const{report:t}=V({projectRoot:r});for(const c of t.errors.filter(a=>a.includes(k)))n.push({code:"wrangler-class-unexported",level:"fail",message:c});for(const c of t.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:c});const s=c=>c.includes(k)||c.includes("SHARD");for(const c of t.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:c});for(const c of t.warnings.filter(a=>!a.includes("LUNORA_ORIGIN_URL")))n.push({code:"wrangler-advisory",level:"warn",message:c});const i=t.errors.find(c=>c.includes("SHARD"));i===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:i})},fe=(r,o)=>{v(f(r,"lunora.json"))&&o.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."})},pe=(r,o)=>{const e=W(r);e!==void 0&&o.push({code:"cf-config-present",fix:e.fix,level:"warn",message:e.message})},me=(r,o)=>{r===void 0||r.limits?.cpu_ms!==void 0||o.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."})},he=(r,o)=>{const e=(r?.r2_buckets??[]).map(n=>n?.bucket_name).filter(n=>typeof n=="string"&&n.length>0);e.length!==0&&o.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.`})},ge=(r,o)=>{const{error:e,info:n}=U(r,"lunora");if(e!==void 0){o.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 t of n?.vectorMetadata??[]){const s=Y(t.kind);if(s===void 0){o.push({code:"vector-metadata-unfilterable",fix:"Filter on a string, number or boolean column, or drop it from `metadata`.",level:"warn",message:`vector index "${t.index}" declares metadata "${t.property}", whose type Vectorize cannot filter on.`});continue}o.push({code:"vector-metadata-index-required",fix:`wrangler ${X({index:t.index,property:t.property,type:s}).join(" ")}`,level:"info",message:`vector index "${t.index}" filters on metadata "${t.property}" — that needs a Vectorize metadata index (\`lunora deploy\` creates it).`})}},ve=(r,o,e)=>{if(o===void 0)return;const n=(p(r)??m)==="celld",t=(o.d1_databases??[]).filter(Boolean);for(const s of t){const i=typeof s.database_id=="string"?s.database_id:"";if(n?z(i)&&i!==N:J(i)){const a=typeof s.binding=="string"&&s.binding.length>0?s.binding:"<unnamed>";e.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 "${a}" has a placeholder database_id ("${i||"<empty>"}").`})}}},be=(r,o)=>{if(r===void 0)return;const e=(r.send_email??[]).filter(Boolean);for(const n of e){const t=typeof n.destination_address=="string"?n.destination_address:"";if(t!==""&&I(t)){const s=typeof n.name=="string"&&n.name.length>0?n.name:"send_email";o.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 ("${t}").`})}}},we=(r,o)=>{const e=f(r,g);if(!v(e))return;let n;try{n=R(e,"utf8")}catch{return}const t=S(n).filter(s=>q(s.key)&&I(s.value)).map(s=>s.key);t.length>0&&o.push({code:"dev-vars-missing-secret",fix:"Run `lunora dev` to auto-generate secrets, or fill them in by hand.",level:"warn",message:`${g} has unfilled secret value(s): ${t.join(", ")}.`})},ye=(r,o)=>{const{source:e}=ee({cwd:r});e===void 0?o.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."}):o.push({code:"admin-token-set",level:"pass",message:`LUNORA_ADMIN_TOKEN is set (${ne(e)}).`})},ke=async(r,o)=>{try{return await P({projectRoot:r,schemaDir:B(r)})}catch(e){o.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}},_e=(r,o)=>{const e=K(r),n=[...r.containers.map(t=>({...t,kind:"container"})),...r.workflows.map(t=>({...t,kind:"workflow"})),...r.agents.map(t=>({...t,kind:"agent"}))];for(const t of n.filter(s=>s.exported))o.push({code:"declared-export-ok",level:"pass",message:`${t.kind} "${t.exportName}" is exported by the worker entry.`});for(const t of e)o.push({code:"declared-export-missing",fix:`Add \`export * from "./lunora/_generated/${t.module}"\` to your worker entry (or re-run \`vis generate lunora-${t.kind}\`).`,level:"fail",message:`${t.kind} "${t.exportName}" is declared but ${t.className} is not exported by the worker entry.`})},xe=/^[\^~><= ]+/u,$e=/^(?<core>\d+\.\d+\.\d+)(?:-(?<channel>[a-z]+)\.(?<counter>\d+))?$/u,Ae=r=>{const o=r.replace(xe,"").trim(),e=$e.exec(o);if(!e?.groups)return;const{channel:n,core:t,counter:s}=e.groups;return{channel:n??"",core:t??"",counter:s===void 0?void 0:Number.parseInt(s,10),raw:o}},Re=(r,o)=>{const e=T(r),n=[];for(const[a,l]of Object.entries(e)){if(a!=="lunorash"&&!a.startsWith("@lunora/"))continue;const d=Ae(l);d&&n.push({name:a,version:d})}if(n.length<2)return;const t=a=>a.map(l=>`${l.name}@${l.version.raw}`).join(", "),s=new Set(n.map(a=>a.version.core)),i=new Set(n.map(a=>a.version.channel));if(s.size>1){o.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: ${t(n)}.`});return}if(i.size>1){o.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 (${[...i].map(a=>a===""?"stable":a).join(" + ")}): ${t(n)}.`});return}const c=n.map(a=>a.version.counter).filter(a=>a!==void 0);if(c.length>1){const a=Math.min(...c),l=Math.max(...c);o.push({code:"version-counter-spread",level:"info",message:c.length===n.length&&a===l?`Lunora packages are all at ${[...i][0]??""}.${String(l)}.`:`Lunora pre-release counters span ${String(a)}–${String(l)}: ${t(n)}.`})}},Se=[f("@lunora","cli"),"lunorash"],Ie=(r,o,e)=>{if(o===void 0)return;const n=[];for(const s of Se){const i=f(r,"node_modules",s);if(v(i))try{n.push(y(i))}catch{}}if(n.length===0)return;let t;try{t=y(o)}catch{return}n.some(s=>te(s,t))||e.push({code:"cli-shadowed",fix:"Run the project's own CLI: `pnpm exec lunora …` (or `npx lunora …`).",level:"warn",message:`the running lunora (${t}) is not the project's own install (${n.join(", ")}).`})},Le={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"}},je=r=>{const o=new Map,e=(n,t)=>{const s=E(n);s!==void 0&&o.set(s,[...o.get(s)??[],t])};e(r?.account_id,"top level");for(const[n,t]of Object.entries(r?.env??{}))e(t?.account_id,`env.${n}`);return o},Ee=async(r,o,e,n)=>{if((p(r)??m)!=="cloudflare")return;const s=E((e.environment??process.env).CLOUDFLARE_ACCOUNT_ID)!==void 0?[]:[...je(o)],i=s.length===0?[[void 0,[]]]:s,c=await Promise.all(i.map(async([a,l])=>({accountId:a,blocks:l,budget:await Q({accountId:a,environment:e.environment,fetch:e.fetch})})));for(const{accountId:a,blocks:l,budget:d}of c)n.push({...Le[d.verdict],message:c.length>1?`account ${String(a)} (${l.join(", ")}): ${d.message}`:d.message,...d.fix===void 0?{}:{fix:d.fix}})},Ce="CELLD_BUCKET is not set — a live `lunora deploy` needs it to name the fleet bucket; `lunora dev` and a dry run do not.",Oe=async(r,o,e)=>{if((p(r)??m)!=="celld")return;const n={...process.env,...o.environment},t=await F({dryRun:!0,env:n,purpose:"deploy"}),s=(n.CELLD_BUCKET??"").trim()===""?[...t.warnings,Ce]:t.warnings;for(const i of t.errors)e.push({code:"celld-toolchain-missing",level:"fail",message:i});for(const i of s)e.push({code:"celld-toolchain-warn",level:"warn",message:i});t.errors.length===0&&s.length===0&&e.push({code:"celld-toolchain-ok",level:"pass",message:"celld, esbuild and CELLD_BUCKET are in place for a deploy."})},De={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"}},Ne=async(r,o,e,n,t)=>{if(e===void 0||o===void 0||(p(r)??m)!=="cloudflare")return;const s=[["",o],...Object.entries(o.env??{}).map(([a,l])=>[`env.${a}: `,l])],i=new Map;for(const[a,l]of s){const d=l.account_id??o.account_id;for(const u of l.artifacts??[]){const w=`${String(d)}/${String(u?.namespace)}`;typeof u?.binding=="string"&&typeof u.namespace=="string"&&!i.has(w)&&i.set(w,{accountId:d,binding:u.binding,label:a,namespace:u.namespace})}}const c=await Promise.all([...i.values()].map(async({label:a,...l})=>({check:await Z({...l,environment:n.environment,fetch:n.fetch,jurisdiction:e,missingOk:!0}),label:a})));for(const{check:a,label:l}of c)t.push({...De[a.verdict],message:`${l}${a.message}`,...a.fix===void 0?{}:{fix:a.fix}})},Te=async r=>{const o=r.cwd??process.cwd(),e=[],{parsed:n,path:t}=O(o);ue(o,n,t,e),pe(o,e),ve(o,n,e),be(n,e),me(n,e),he(n,e),ie(n,e),we(o,e),ye(o,e),Re(o,e),ge(o,e),fe(o,e),Ie(o,r.executablePath??process.argv[1],e),de(o,e),le(o,e);const s=await ke(o,e);s!==void 0&&_e(s,e),se(n,o,s?.usesAi===!0,e),await Oe(o,r,e),await Ee(o,n,r,e),await Ne(o,n,s?.jurisdiction,r,e),ae(n,s?.usesCimdWorkers===!0,e);const i={fail:0,info:0,pass:0,warn:0};for(const a of e)i[a.level]+=1;const c=i.fail>0?1:0;return{code:c,findings:e,ok:c===0,summary:i}},Ue={fail:"FAIL",info:"INFO",pass:"PASS",warn:"WARN"},Pe=(r,o)=>{o.info("lunora doctor — project preflight");for(const t of r.findings){const s=`[${Ue[t.level]}] ${t.message}`;t.level==="fail"?o.error(s):t.level==="warn"?o.warn(s):o.info(s),t.fix!==void 0&&t.level!=="pass"&&o.info(` fix: ${t.fix}`)}const{fail:e,warn:n}=r.summary;e>0?o.error(`${String(e)} failure(s), ${String(n)} warning(s).`):n>0?o.warn(`0 failures, ${String(n)} warning(s).`):o.success("all checks passed.")},Be=async r=>{const{logger:o}=r,e=await Te({...r});return Pe(e,o),e},Xe=oe(async({cwd:r,format:o,logger:e,options:n})=>{if(n.fix===!0){const{path:s}=O(r),i=await H({configPath:s,cwd:r,dryRun:n.dryRun===!0,logger:e});for(const c of i.applied)e.info(`fix: ${c}`);for(const c of i.skipped)e.warn(`not fixed: ${c}`)}const t=await Be({cwd:r,format:o,logger:e});return{code:t.code,data:{findings:t.findings,summary:t.summary}}});export{Xe as execute,Te as runDoctor,Be as runDoctorCommand};
1
+ import{existsSync as O,readFileSync as k}from"node:fs";import{writeFile as I,mkdir as U}from"node:fs/promises";import{parseSchema as B,applyAdditiveEdit as F,projectUsesUmbrella as Y}from"@lunora/config";import{join as _}from"@visulima/path";import{d as q}from"../packem_shared/command-B6vu47iR.mjs";import{EXIT_CODE as L}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";import{createRequire as P}from"node:module";import{LunoraError as N}from"@lunora/errors";import{addArgsFor as H,detectPackageManager as K}from"@lunora/config/cli";const j=/^\//,G=(e,r)=>{try{const{args:n,command:t}=H(K(e),[r],{dev:!0});return`${t} ${n.join(" ")}`}catch{return`<your-package-manager> add -D ${r}`}},T=(e,r,n)=>{const t=P(_(n,"noop.cjs"));try{t.resolve(e)}catch{throw new N("INTERNAL",`\`lunora introspect\` needs the \`${r}\` driver to read this database, and it isn't installed.
2
+
3
+ Install it in your project:
4
+
5
+ ${G(n,r)}`)}return t(e)},Q=e=>{const r=e.slice(0,Math.max(0,e.indexOf(":"))).toLowerCase();if(r==="postgres"||r==="postgresql")return"postgres";if(r==="mysql"||r==="mariadb")return"mysql";throw new N("INTERNAL",`Unrecognised database URL scheme \`${r}\`. Expected a \`postgres://\`, \`postgresql://\`, \`mysql://\`, or \`mariadb://\` connection string.`)},J=e=>{try{const r=new URL(e).pathname.replace(j,"");return r===""?void 0:decodeURIComponent(r)}catch{return}},W=async(e,r,n,t=process.cwd())=>{if(r==="postgres"){const m=T("pg","pg",t).Client,u=new m({connectionString:e});return await u.connect(),{close:async()=>{await u.end()},execute:async(l,p)=>(await u.query(l,[...p])).rows,schema:n??"public"}}const a=T("mysql2/promise","mysql2",t).createConnection,o=await a(e),i=n??J(e);if(i===void 0)throw new N("INTERNAL","A MySQL connection string must name a database (`mysql://host/<database>`), or pass `--schema`.");return{close:async()=>{await o.end()},execute:async(c,m)=>{const[u]=await o.execute(c,[...m]);return Array.isArray(u)?u:[]},schema:i}},h=new Set(["_creationTime","_id"]),X={bigint:"v.bigint()",bigserial:"v.bigint()",bit:"v.string()",bool:"v.boolean()",boolean:"v.boolean()",box:"v.string()",bpchar:"v.string()",bytea:"v.bytes()",char:"v.string()",character:"v.string()","character varying":"v.string()",cidr:"v.string()",circle:"v.string()",citext:"v.string()",date:"v.date()","double precision":"v.number()",float4:"v.number()",float8:"v.number()",inet:"v.string()",int:"v.number()",int2:"v.number()",int4:"v.number()",int8:"v.bigint()",integer:"v.number()",interval:"v.string()",json:"v.any()",jsonb:"v.any()",line:"v.string()",lseg:"v.string()",macaddr:"v.string()",money:"v.number()",name:"v.string()",numeric:"v.number()",path:"v.string()",point:"v.string()",polygon:"v.string()",real:"v.number()",serial:"v.number()",smallint:"v.number()",smallserial:"v.number()",text:"v.string()",time:"v.string()","time with time zone":"v.string()","time without time zone":"v.string()",timestamp:"v.timestamp()","timestamp with time zone":"v.timestamp()","timestamp without time zone":"v.timestamp()",timestamptz:"v.timestamp()",tsquery:"v.string()",tsvector:"v.string()",uuid:"v.string()",varbit:"v.string()",varchar:"v.string()",xml:"v.string()"},z={bigint:"v.bigint()",binary:"v.bytes()",bit:"v.number()",blob:"v.bytes()",char:"v.string()",date:"v.date()",datetime:"v.timestamp()",decimal:"v.number()",double:"v.number()",enum:"v.string()",float:"v.number()",int:"v.number()",integer:"v.number()",json:"v.any()",longblob:"v.bytes()",longtext:"v.string()",mediumblob:"v.bytes()",mediumint:"v.number()",mediumtext:"v.string()",numeric:"v.number()",set:"v.string()",smallint:"v.number()",text:"v.string()",time:"v.string()",timestamp:"v.timestamp()",tinyblob:"v.bytes()",tinyint:"v.number()",tinytext:"v.string()",varbinary:"v.bytes()",varchar:"v.string()",year:"v.number()"},w=(e,r)=>{const t=(r==="postgres"?X:z)[e.dataType],s=e.references===void 0?t:`v.id(${JSON.stringify(e.references.table)})`;let a=s??"v.any()";for(let o=0;o<e.arrayDepth;o+=1)a=`v.array(${a})`;return e.nullable&&(a=`v.optional(${a})`),{expression:a,known:s!==void 0}},M=/^[A-Z_$][\w$]*$/i,Z=/[^\dA-Z]+(.)?/gi,V=/^\d+/,ee=/[^\w-]/g,ne=/[\u003C\u003E\u002F\u2028\u2029]/g,te={"/":String.raw`\u002F`,"\u2028":String.raw`\u2028`,"\u2029":String.raw`\u2029`,"<":String.raw`\u003C`,">":String.raw`\u003E`},f=e=>JSON.stringify(e).replaceAll(ne,r=>te[r]??r),S=e=>M.test(e)?e:f(e),re=e=>M.test(e)?`.${e}`:`[${f(e)}]`,x=e=>e.replaceAll("*/",String.raw`*\/`),ae=e=>{const r=e.replaceAll(ee,"_");return r===""?"table":r},se=e=>{const n=e.replaceAll(Z,(t,s)=>s?.toUpperCase()??"").replace(V,"");return n===""?"table":`${n.charAt(0).toLowerCase()}${n.slice(1)}`},C=e=>e.columns.filter(r=>!h.has(r.name)),oe=e=>{const r=new Set(e.primaryKey);for(const n of e.indexes)for(const t of n.columns)r.add(t);for(const n of e.columns)n.references!==void 0&&r.add(n.name);return[...r].filter(n=>!h.has(n))},D=(e,r,n,t)=>e.references===void 0||r.has(e.references.table)?e:(t.push(`${n}.${e.name}: references \`${e.references.table}\`, which isn't in the generated schema — emitted as a plain column instead of \`v.id(...)\`.`),{arrayDepth:e.arrayDepth,dataType:e.dataType,name:e.name,nullable:e.nullable}),ie=(e,r,n,t)=>{const s=[];for(const o of e.columns){if(h.has(o.name)){t.push(`${e.name}.${o.name}: skipped — \`${o.name}\` is a Lunora system column. Rename it in the source database or map it by hand.`);continue}const i=D(o,n,e.name,t),{expression:c,known:m}=w(i,r);!m&&i.references===void 0&&(t.push(`${e.name}.${o.name}: no mapping for SQL type \`${o.dataType}\` — emitted as \`v.any()\`.`),s.push(` // TODO: \`${x(o.dataType)}\` has no direct validator; narrow this.`)),s.push(` ${S(o.name)}: ${c},`)}const a=[' .global({ backend: "hyperdrive" })'];if(e.primaryKey.length>0&&e.primaryKey.every(o=>!h.has(o))){const o=e.primaryKey.map(i=>f(i)).join(", ");a.push(` .index(${f(`by_${e.primaryKey.join("_")}`)}, [${o}], { unique: true })`)}for(const o of e.indexes){const i=o.columns.filter(u=>!h.has(u));if(i.length===0)continue;const c=i.map(u=>f(u)).join(", "),m=o.unique?", { unique: true }":"";a.push(` .index(${f(o.name)}, [${c}]${m})`)}return` ${S(e.name)}: defineTable({
6
+ ${s.join(`
7
+ `)}
8
+ })
9
+ ${a.join(`
10
+ `)},`},ce=(e,r,n)=>{const t=new Set(e.tables.map(a=>a.name)),s=e.tables.map(a=>ie(a,e.dialect,t,n)).join(`
11
+ `);return`/**
12
+ * Generated by \`lunora introspect\` from an existing ${e.dialect==="postgres"?"Postgres":"MySQL"} database.
13
+ *
14
+ * This file is a STARTING POINT, not a build artifact — it is written once and is
15
+ * yours to edit. Review it before shipping: column types are mapped
16
+ * conservatively, and every table is \`.global({ backend: "hyperdrive" })\` because
17
+ * its rows live in the external database. Re-running \`lunora introspect\` will not
18
+ * overwrite it unless you pass \`--force\`.
19
+ */
20
+ import { defineSchema, defineTable, v } from "${r.serverImport}";
21
+
22
+ export default defineSchema({
23
+ ${s}
24
+ });
25
+ `},me=(e,r,n,t=new Set([e.name]),s=[])=>{const a=se(e.name),o=oe(e),i=new Map(C(e).map(l=>[l.name,l])),c=o.map(l=>{const p=i.get(l);if(p===void 0)return;const v=D({...p,nullable:!1},t,e.name,[]),{expression:d,known:A}=w(v,r);return!A&&v.references===void 0&&s.push(`${e.name}.${l}: filter falls back to \`v.any()\` (no mapping for SQL type \`${p.dataType}\`).`),` ${S(l)}: ${d},`}).filter(l=>l!==void 0),m=[f("_creationTime"),...o.map(l=>f(l))].join(", "),u=`ctx.db${re(e.name)}`;return`/**
26
+ * Generated by \`lunora introspect\` for the \`${x(e.name)}\` table — a
27
+ * starting point you own and edit.
28
+ *
29
+ * Both procedures are RPC-only. Add \`.expose({ rest: true })\` once you've decided
30
+ * this data should be public, and gate them with your auth/RLS middleware first —
31
+ * \`introspect\` cannot know who is allowed to read this table.
32
+ */
33
+ import { defineListArgs, v } from "${n.serverImport}";
34
+
35
+ import type { Doc } from "./_generated/dataModel";
36
+ import { c } from "./_generated/server";
37
+
38
+ const ${a}List = defineListArgs<Doc<${f(e.name)}>>()({
39
+ // Only index-backed columns are published as filterable, so a caller cannot
40
+ // reach a column you did not choose to expose. Note that \`contains\` and the
41
+ // negative operators still scan — narrow this list, and review it, before
42
+ // adding \`.expose({ rest: true })\`.
43
+ filter: {
44
+ ${c.join(`
45
+ `)}
46
+ },
47
+ orderBy: [${m}],
48
+ });
49
+
50
+ export const list = c.query.input(${a}List.args).query(({ args, ctx }) => ${u}.findMany(${a}List.toQueryArgs(args)));
51
+
52
+ export const get = c.query.input({ id: v.id(${f(e.name)}) }).query(({ args, ctx }) => ${u}.get(args.id));
53
+ `},le=(e,r)=>{const n=[],t=new Set(e.tables.map(a=>a.name)),s=[{contents:ce(e,r,n),path:"schema.ts"}];if(r.procedures){const a=new Map([["schema","the generated schema module"]]);for(const o of e.tables){if(C(o).length===0){n.push(`${o.name}: no usable columns — procedure module skipped.`);continue}const i=ae(o.name);i!==o.name&&n.push(`${o.name}: written as \`${i}.ts\` — the table name isn't usable as a filename.`);const c=a.get(i);if(c!==void 0){n.push(`${o.name}: procedure module skipped — its filename \`${i}.ts\` collides with table \`${c}\`.`);continue}a.set(i,o.name),s.push({contents:me(o,e.dialect,r,t,n),path:`${i}.ts`})}}return{files:s,warnings:n}},y=/^[A-Z_$][\w$]*$/i,ue=e=>e.startsWith("v.optional(")&&e.endsWith(")")?e.slice(11,-1):e,de=(e,r,n)=>{const t=[],s=new Set(r?.columns.map(a=>a.name));for(const a of e.columns){if(h.has(a.name)||s.has(a.name))continue;if(!y.test(a.name)){n.warnings.push(`${e.name}.${a.name}: skipped — column names must be bare identifiers to merge.`);continue}const o=a.references!==void 0&&!n.present.has(a.references.table),{expression:i}=w(o?{...a,references:void 0}:a,n.dialect);t.push({column:a.name,kind:"addOptionalColumn",table:e.name,validator:ue(i)}),!a.nullable&&r!==void 0&&n.warnings.push(`${e.name}.${a.name}: added as \`v.optional(...)\` — a required column on an existing table needs a backfill migration.`)}return t},pe=(e,r,n)=>{const t=[],s=new Set(r?.indexes.map(a=>a.name));for(const a of e.indexes){const o=a.columns.filter(i=>!h.has(i));if(!(s.has(a.name)||o.length===0)){if(!y.test(a.name)||!o.every(i=>y.test(i))){n.push(`${e.name}: index \`${a.name}\` skipped — index and column names must be bare identifiers to merge.`);continue}t.push({fields:o,kind:"addIndex",name:a.name,table:e.name,...a.unique?{unique:!0}:{}})}}return t},ge=(e,r,n)=>{const t=[],s=[],a=new Map(r.map(i=>[i.name,i])),o=new Set([...a.keys(),...e.tables.map(i=>i.name)]);for(const i of e.tables){if(!y.test(i.name)){s.push(`${i.name}: skipped — merging into an existing schema needs a table name that is a bare identifier.`);continue}const c=a.get(i.name);c===void 0&&t.push({global:{backend:"hyperdrive"},kind:"addTable",table:i.name}),t.push(...de(i,c,{dialect:n,present:o,warnings:s}),...pe(i,c,s))}return{edits:t,warnings:s}},fe=(e,r,n)=>{const t=B(e);if(!t.ok)return{applied:0,warnings:[`lunora/schema.ts could not be parsed (${t.reason}) — leave it alone and merge by hand, or pass --force.`]};const s=ge(r,t.tables,n),a=[...s.warnings];let o=e,i=0;for(const c of s.edits){const m=F(o,c);m.ok?(o=m.text,i+=1):a.push(`${c.table}: skipped one edit (${m.reason}).`)}return{applied:i,warnings:a,...i===0?{}:{text:o}}},g=(e,r)=>{const n=e[r]??e[r.toLowerCase()]??e[r.toUpperCase()];return typeof n=="string"?n:typeof n=="number"||typeof n=="bigint"||typeof n=="boolean"?String(n):""},ve=`
54
+ SELECT c.table_name, c.column_name, c.is_nullable, c.data_type, c.udt_name
55
+ FROM information_schema.columns c
56
+ JOIN information_schema.tables t
57
+ ON t.table_schema = c.table_schema AND t.table_name = c.table_name
58
+ WHERE c.table_schema = $1 AND t.table_type = 'BASE TABLE'
59
+ ORDER BY c.table_name, c.ordinal_position`,be=`
60
+ SELECT tc.table_name, kcu.column_name
61
+ FROM information_schema.table_constraints tc
62
+ JOIN information_schema.key_column_usage kcu
63
+ ON kcu.constraint_name = tc.constraint_name AND kcu.table_schema = tc.table_schema
64
+ WHERE tc.table_schema = $1 AND tc.constraint_type = 'PRIMARY KEY'
65
+ ORDER BY tc.table_name, kcu.ordinal_position`,he=`
66
+ SELECT tc.table_name, kcu.column_name, ccu.table_name AS foreign_table, ccu.column_name AS foreign_column
67
+ FROM information_schema.table_constraints tc
68
+ JOIN information_schema.key_column_usage kcu
69
+ ON kcu.constraint_name = tc.constraint_name AND kcu.table_schema = tc.table_schema
70
+ JOIN information_schema.constraint_column_usage ccu
71
+ ON ccu.constraint_name = tc.constraint_name AND ccu.table_schema = tc.table_schema
72
+ WHERE tc.table_schema = $1 AND tc.constraint_type = 'FOREIGN KEY'`,Ee=`
73
+ SELECT t.relname AS table_name, i.relname AS index_name, ix.indisunique AS is_unique, a.attname AS column_name
74
+ FROM pg_class t
75
+ JOIN pg_index ix ON t.oid = ix.indrelid
76
+ JOIN pg_class i ON i.oid = ix.indexrelid
77
+ JOIN pg_namespace n ON n.oid = t.relnamespace
78
+ CROSS JOIN LATERAL unnest(ix.indkey) WITH ORDINALITY AS k(attnum, ord)
79
+ JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum
80
+ WHERE n.nspname = $1 AND t.relkind = 'r' AND NOT ix.indisprimary
81
+ ORDER BY t.relname, i.relname, k.ord`,_e=`
82
+ SELECT c.TABLE_NAME, c.COLUMN_NAME, c.IS_NULLABLE, c.DATA_TYPE
83
+ FROM information_schema.COLUMNS c
84
+ JOIN information_schema.TABLES t
85
+ ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME
86
+ WHERE c.TABLE_SCHEMA = ? AND t.TABLE_TYPE = 'BASE TABLE'
87
+ ORDER BY c.TABLE_NAME, c.ORDINAL_POSITION`,ye=`
88
+ SELECT TABLE_NAME, COLUMN_NAME
89
+ FROM information_schema.KEY_COLUMN_USAGE
90
+ WHERE TABLE_SCHEMA = ? AND CONSTRAINT_NAME = 'PRIMARY'
91
+ ORDER BY TABLE_NAME, ORDINAL_POSITION`,Ae=`
92
+ SELECT TABLE_NAME, COLUMN_NAME, REFERENCED_TABLE_NAME AS foreign_table, REFERENCED_COLUMN_NAME AS foreign_column
93
+ FROM information_schema.KEY_COLUMN_USAGE
94
+ WHERE TABLE_SCHEMA = ? AND REFERENCED_TABLE_NAME IS NOT NULL`,Se=`
95
+ SELECT TABLE_NAME, INDEX_NAME AS index_name, NON_UNIQUE, COLUMN_NAME
96
+ FROM information_schema.STATISTICS
97
+ WHERE TABLE_SCHEMA = ? AND INDEX_NAME <> 'PRIMARY'
98
+ ORDER BY TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX`,E=e=>{const r=new Map;for(const n of e){const t=g(n,"table_name"),s=r.get(t);s===void 0?r.set(t,[n]):s.push(n)}return r},Ne=(e,r)=>{const n=g(e,"data_type").toLowerCase();if(r!=="postgres")return{arrayDepth:0,dataType:n};const t=g(e,"udt_name").toLowerCase();return n==="array"&&t.startsWith("_")?{arrayDepth:1,dataType:t.slice(1)}:{arrayDepth:0,dataType:t===""?n:t}},we=(e,r)=>{const n=new Map;for(const t of e){const s=g(t,"index_name"),a=r==="postgres"?g(t,"is_unique")==="true":g(t,"NON_UNIQUE")==="0",o=n.get(s);o===void 0?n.set(s,{columns:[g(t,"column_name")],unique:a}):o.columns.push(g(t,"column_name"))}return[...n.entries()].map(([t,s])=>({columns:s.columns,name:t,unique:s.unique}))},Re=async(e,r,n)=>{const t=r==="postgres",[s,a,o,i]=await Promise.all([e(t?ve:_e,[n]),e(t?be:ye,[n]),e(t?he:Ae,[n]),e(t?Ee:Se,[n])]),c=E(a),m=E(o),u=E(i),l=[];for(const[p,v]of E(s)){const d=new Map((m.get(p)??[]).map(b=>[g(b,"column_name"),{column:g(b,"foreign_column"),table:g(b,"foreign_table")}])),A=v.map(b=>{const R=g(b,"column_name"),$=d.get(R);return{...Ne(b,r),name:R,nullable:g(b,"is_nullable").toUpperCase()==="YES",...$===void 0?{}:{references:$}}});l.push({columns:A,indexes:we(u.get(p)??[],r),name:p,primaryKey:(c.get(p)??[]).map(b=>g(b,"column_name"))})}return l.sort((p,v)=>p.name.localeCompare(v.name)),{dialect:r,tables:l}},$e=e=>Y(e)?"lunorash/server":"@lunora/server",Le=async(e,r,n)=>{const t=_(r,e.path);return O(t)&&n.force!==!0?(n.logger.warn(`skipped lunora/${e.path} — it already exists (pass --force to overwrite)`),!1):n.dryRun===!0?(n.logger.info(`would write lunora/${e.path} (${String(e.contents.split(`
99
+ `).length)} lines)`),!1):(await U(r,{recursive:!0}),await I(t,e.contents,"utf8"),n.logger.info(`wrote lunora/${e.path}`),!0)},Te=(e,r)=>{const n=r.tables;if(n===void 0||n.length===0)return e.tables;for(const t of n)e.tables.some(s=>s.name===t)||r.logger.warn(`--tables: no table named "${t}" exists in this schema — skipped.`);return e.tables.filter(t=>n.includes(t.name))},Oe=async(e,r,n,t)=>{const s=fe(k(e,"utf8"),r,n);for(const a of s.warnings)t.logger.warn(a);return s.text===void 0?(t.logger.info("lunora/schema.ts is already up to date with the database."),!1):t.dryRun===!0?(t.logger.info(`would merge ${String(s.applied)} addition(s) into lunora/schema.ts`),!1):(await I(e,s.text,"utf8"),t.logger.info(`merged ${String(s.applied)} addition(s) into lunora/schema.ts`),!0)},Ie=async e=>{const r=e.cwd??process.cwd();if(e.connection===void 0&&(e.url===void 0||e.url==="")){const d="`lunora introspect` needs a database URL: pass --url, or set DATABASE_URL.";return e.logger.error(d),{code:L.USAGE,error:d,written:[]}}const n=e.connection===void 0?Q(e.url):e.dialect??"postgres",t=e.connection??await W(e.url,n,e.schema,r);let s;try{s=await Re(t.execute,n,t.schema)}finally{e.connection===void 0&&await t.close()}const a=Te(s,e);if(a.length===0){const d="no tables found to introspect — check --schema and --tables.";return e.logger.error(d),{code:L.NOT_FOUND,error:d,written:[]}}const{files:o,warnings:i}=le({...s,tables:a},{procedures:e.procedures!==!1,serverImport:$e(r)}),c=_(r,"lunora"),m=[],u=_(c,"schema.ts"),l=O(u)&&e.force!==!0,p=l?o.filter(d=>d.path!=="schema.ts"):o;l&&await Oe(u,{...s,tables:a},n,e)&&m.push("schema.ts");for(const d of p)await Le(d,c,e)&&m.push(d.path);for(const d of i)e.logger.warn(d);e.logger.info(`introspected ${String(a.length)} table(s) from ${n}. Review the generated files before running \`lunora dev\`.`);const v=a.map(d=>d.name);return{code:0,dialect:n,tables:v,written:m}},qe=q(async({cwd:e,format:r,logger:n,options:t})=>{const s=await Ie({cwd:e,dryRun:t.dryRun===!0,force:t.force===!0,format:r,logger:n,procedures:t.procedures!==!1,schema:t.schema,tables:t.tables===void 0?void 0:t.tables.split(",").map(a=>a.trim()),url:t.url??process.env.DATABASE_URL});return{code:s.code,data:s.dialect===void 0?void 0:{dialect:s.dialect,dryRun:t.dryRun===!0,tables:s.tables??[],written:s.written},error:s.error}});export{qe as execute,$e as resolveServerImport,Ie as runIntrospectCommand};