@lunora/cli 1.0.0-alpha.467 → 1.0.0-alpha.469

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,43 +1,57 @@
1
- import{mkdirSync as Xe,writeFileSync as V,existsSync as b,readFileSync as E,rmSync as Q,readdirSync as ve,mkdtempSync as Hr,realpathSync as Wr,statSync as Qe}from"node:fs";import{dirname as U,join as y,resolve as N,relative as F,sep as B,extname as Gr}from"node:path";import{PROJECT_CONFIG_FILENAMES as Vr,isTestPath as fe,discoverMigrations as qr,readServiceBindings as pe,runCodegen as Kr}from"@lunora/codegen";import{readLinkedProject as ye,resolveSchemaDirectory as I,startDevProcess as zr,acceptsConnection as Jr,resolveTargetOrThrow as ge,detectFramework as Yr,DEFAULT_BUNDLE_META_PATH as Xr,STRICT_ADVISORIES_ENV as Qr,LAZY_FUNCTIONS_ENV as Zr,BUNDLE_META_PATH_ENV as et,BUILD_TARGET_ENV as rt,BUILD_ROOT_ENV as tt,canonicalPath as nt,COMPOSED_WORKER_ENTRY as Ce,discoverContainerInfo as Ze,D1_PLACEHOLDER_ID as Ie,discoverSchemaInfo as we,writeLinkedProject as ot,DEV_VARS_FILE as C,parseDevVariableEntries as er,secretSourcesFromBindings as st,inferLunoraBindings as rr,requiredSecrets as at,mintableSecretKeysFor as it,generateSecretValue as ct,upsertDevVariableLine as dt,writeDevVariablesFileAtomically as lt,isPlaceholderValue as ut,ensureGitignoreEntries as ft,resolveLazyFunctions as te,resolveDeployDriver as ne,MissingBuildOutputError as gt,clearApiSpecMarker as ht,createDiscoveryCache as mt,planToolchainInvocation as tr,probeCelldToolchain as vt,runPostCodegenHook as pt,readApiSpecMarker as yt}from"@lunora/config";import{bindingsNeedingDatabase as wt,findWranglerFile as O,readWranglerJsonc as R,mergeWranglerEnvironment as oe,HYPERDRIVE_PLACEHOLDER_ID as nr,applyModify as or,warnCloudflareCliConfigOnce as kt,validateWranglerProject as bt,wranglerCodegenInputs as $t,reconcileWranglerBindings as St,reconcileWranglerCompatibilityDate as Et,reconcileWranglerCrons as At,describePreservedCrons as Rt}from"@lunora/config/cloudflare";import{Spinner as Tt}from"@visulima/spinner";import{r as Pt}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{n as _t,r as Dt,a as Ct}from"../packem_shared/admin-url-DJB8P6Jh.mjs";import{r as ke,a as It,e as Ot}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as Nt}from"../packem_shared/api-spec-lYyq4vL6.mjs";import{e as jt,m as Lt,g as Mt,i as sr,d as xt,b as Ft}from"../packem_shared/vectorize-metadata-BVSF8z2h.mjs";import{w as Ut}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{d as Bt}from"../packem_shared/command-BpMv2n0o.mjs";import{r as be}from"../packem_shared/wrangler-name-Dsk5K1f-.mjs";import{a as Ht}from"../packem_shared/deploy-target-resolve-BTCW1Iv4.mjs";import{EXIT_CODE as w}from"../packem_shared/EXIT_CODE-DQVhSE-1.mjs";import{spawn as Wt}from"node:child_process";import{randomUUID as ar,createHash as Gt}from"node:crypto";import{setTimeout as Vt}from"node:timers/promises";import{toolchainExecArgs as H,detectPackageManager as j,execArgsFor as $e}from"@lunora/config/cli";import{f as qt}from"../packem_shared/free-port-DjbFhaaT.mjs";import{containerBuildTag as Kt}from"@lunora/container";import{a as zt,i as Jt}from"../packem_shared/docker-DpVxvYpL.mjs";import{defaultSpawner as x}from"../packem_shared/createRecordingSpawner-01ZngIwK.mjs";import{r as Se}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{p as Yt,H as Xt,a as Qt,r as Zt,c as en,b as rn}from"../packem_shared/health-probe-BLnoq_oC.mjs";import{runAdvisor as tn,openShardAccess as Oe}from"@lunora/advisor";import{join as $,relative as W,dirname as ir}from"@visulima/path";import{Project as cr,SyntaxKind as p,Node as k}from"ts-morph";import{r as dr,c as lr}from"../packem_shared/cloudflare-credentials-BVmZnDZk.mjs";import{runMigrateDataCommand as nn}from"../packem_shared/runMigrateGenerateCommand-CguLEIZp.mjs";import{c as on}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{l as sn}from"../packem_shared/wrangler-secrets-DlSlWvRH.mjs";const an=Object.freeze({edges:[],nodes:[],modules:[],unresolved:[],version:1}),cn=20,Ne=e=>`${e.from} -${e.kind}-> ${e.to}`,z=(e,r)=>{const t=new Set(e);return r.filter(n=>!t.has(n)).toSorted((n,o)=>n.localeCompare(o))},dn=(e,r)=>{const t=e.modules.map(a=>a.name),n=r.modules.map(a=>a.name),o=e.edges.map(a=>Ne(a)),s=r.edges.map(a=>Ne(a));return{addedEdges:z(o,s),addedModules:z(t,n),removedEdges:z(s,o),removedModules:z(n,t)}},J=(e,r,t)=>{if(t.length===0)return[];const n=t.slice(0,cn).map(s=>` ${e} ${s}`),o=t.length-n.length;return[`${r}:`,...n,...o>0?[` … and ${o.toString()} more`]:[]]},ln=e=>{const r=[...J("+","modules added",e.addedModules),...J("-","modules removed",e.removedModules),...J("+","edges added",e.addedEdges),...J("-","edges removed",e.removedEdges)];return r.length===0?void 0:`architecture changes since the last deploy:
1
+ import{mkdirSync as hr,writeFileSync as X,existsSync as b,readFileSync as E,readdirSync as K,statSync as Re,rmSync as oe,mkdtempSync as ot,realpathSync as st}from"node:fs";import{dirname as j,join as p,resolve as I,relative as L,sep as x,extname as it}from"node:path";import{PROJECT_CONFIG_FILENAMES as at,isTestPath as ye,discoverMigrations as ct,readServiceBindings as Te,runCodegen as dt}from"@lunora/codegen";import{readLinkedProject as _e,discoverSchemaInfo as Ce,resolveSchemaDirectory as M,startDevProcess as lt,acceptsConnection as ut,resolveTargetOrThrow as we,detectFramework as ft,DEFAULT_BUNDLE_META_PATH as gt,STRICT_ADVISORIES_ENV as ht,LAZY_FUNCTIONS_ENV as mt,BUNDLE_META_PATH_ENV as pt,BUILD_TARGET_ENV as vt,BUILD_ROOT_ENV as yt,canonicalPath as wt,COMPOSED_WORKER_ENTRY as He,discoverContainerInfo as mr,D1_PLACEHOLDER_ID as qe,writeLinkedProject as kt,DEV_VARS_FILE as N,parseDevVariableEntries as pr,secretSourcesFromBindings as bt,inferLunoraBindings as vr,requiredSecrets as $t,mintableSecretKeysFor as St,generateSecretValue as Et,upsertDevVariableLine as At,writeDevVariablesFileAtomically as Rt,isPlaceholderValue as Tt,ensureGitignoreEntries as _t,resolveLazyFunctions as ce,resolveDeployDriver as de,MissingBuildOutputError as Ct,clearApiSpecMarker as It,createDiscoveryCache as Pt,planToolchainInvocation as yr,probeCelldToolchain as jt,runPostCodegenHook as Ot,readApiSpecMarker as Dt}from"@lunora/config";import{findWranglerFile as O,readWranglerJsonc as P,HYPERDRIVE_PLACEHOLDER_ID as wr,applyModify as kr,bindingsNeedingDatabase as Nt,mergeWranglerEnvironment as le,warnCloudflareCliConfigOnce as Lt,validateWranglerProject as xt,wranglerCodegenInputs as Mt,reconcileWranglerBindings as Ft,reconcileWranglerCompatibilityDate as Ut,reconcileWranglerCrons as Bt,describePreservedCrons as Wt}from"@lunora/config/cloudflare";import{Spinner as Ht}from"@visulima/spinner";import{r as qt}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{n as Gt,r as Vt,a as Kt}from"../packem_shared/admin-url-DJB8P6Jh.mjs";import{r as Ie,a as zt,e as Jt}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as Yt}from"../packem_shared/api-spec-lYyq4vL6.mjs";import{e as Xt,m as Qt,g as Zt,i as br,d as en,b as rn}from"../packem_shared/vectorize-metadata-BVSF8z2h.mjs";import{w as tn}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{d as nn}from"../packem_shared/command-BpMv2n0o.mjs";import{r as Pe}from"../packem_shared/wrangler-name-Dsk5K1f-.mjs";import{a as on}from"../packem_shared/deploy-target-resolve-BTCW1Iv4.mjs";import{EXIT_CODE as w}from"../packem_shared/EXIT_CODE-DQVhSE-1.mjs";import{spawn as sn}from"node:child_process";import{createHash as an,randomUUID as $r}from"node:crypto";import{setTimeout as cn}from"node:timers/promises";import{stripVTControlCharacters as dn}from"node:util";import{toolchainExecArgs as z,detectPackageManager as F,execArgsFor as je}from"@lunora/config/cli";import{r as Sr,c as Er}from"../packem_shared/cloudflare-credentials-BVmZnDZk.mjs";import{f as ln}from"../packem_shared/free-port-DjbFhaaT.mjs";import{ts as k,Project as Ar,SyntaxKind as y,Node as $}from"ts-morph";import{l as V}from"../packem_shared/js-literal-FWLi94Lh.mjs";import{containerBuildTag as un}from"@lunora/container";import{a as fn,i as gn}from"../packem_shared/docker-DpVxvYpL.mjs";import{defaultSpawner as H}from"../packem_shared/createRecordingSpawner-01ZngIwK.mjs";import{r as Oe}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{p as hn,H as mn,a as pn,r as vn,c as yn,b as wn}from"../packem_shared/health-probe-BLnoq_oC.mjs";import{runAdvisor as kn,openShardAccess as Ge}from"@lunora/advisor";import{join as A,relative as J,dirname as Rr}from"@visulima/path";import{runMigrateDataCommand as bn}from"../packem_shared/runMigrateGenerateCommand-CguLEIZp.mjs";import{c as $n}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{l as Sn}from"../packem_shared/wrangler-secrets-DlSlWvRH.mjs";const En=Object.freeze({edges:[],nodes:[],modules:[],unresolved:[],version:1}),An=20,Ve=e=>`${e.from} -${e.kind}-> ${e.to}`,ee=(e,r)=>{const t=new Set(e);return r.filter(n=>!t.has(n)).toSorted((n,o)=>n.localeCompare(o))},Rn=(e,r)=>{const t=e.modules.map(i=>i.name),n=r.modules.map(i=>i.name),o=e.edges.map(i=>Ve(i)),s=r.edges.map(i=>Ve(i));return{addedEdges:ee(o,s),addedModules:ee(t,n),removedEdges:ee(s,o),removedModules:ee(n,t)}},re=(e,r,t)=>{if(t.length===0)return[];const n=t.slice(0,An).map(s=>` ${e} ${s}`),o=t.length-n.length;return[`${r}:`,...n,...o>0?[` … and ${o.toString()} more`]:[]]},Tn=e=>{const r=[...re("+","modules added",e.addedModules),...re("-","modules removed",e.removedModules),...re("+","edges added",e.addedEdges),...re("-","edges removed",e.removedEdges)];return r.length===0?void 0:`architecture changes since the last deploy:
2
2
  ${r.join(`
3
- `)}`},un=(e,r)=>y(e,".lunora",r===void 0?"architecture.json":`architecture.${r}.json`),fn=e=>{if(b(e))try{const r=JSON.parse(E(e,"utf8"));return r.version===1&&Array.isArray(r.modules)&&Array.isArray(r.edges)?r:void 0}catch{return}},gn=e=>{const{cwd:r,environment:t,logger:n}=e,o=un(r,t),s=fn(o),a=e.current??(s===void 0?void 0:an);if(a===void 0)return;const i=s===void 0?void 0:ln(dn(s,a));return i!==void 0&&n.info(i),()=>{try{Xe(U(o),{recursive:!0}),V(o,`${JSON.stringify(a,void 0,2)}
4
- `,"utf8")}catch(c){n.warn(`could not record the deployed architecture at ${o}: ${c instanceof Error?c.message:String(c)}`)}}},hn=e=>{const{cwd:r,env:t,logger:n,mintedSecretsFile:o}=e;try{const s=ye(r),a=s?.workerName??be(r),i=e.url??s?.workerUrl;n.success("deploy complete"),n.info(` worker: ${a??"(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{}},mn=/\/index$/u,vn=/[^\dA-Za-z]/gu,pn=e=>e.replace(mn,"").split("/").map(r=>r.replaceAll(vn,"_")),yn=e=>pn(e).join("_"),wn=18787,je=3,ur=12e4,kn=5e3,ce=10,fr=new Set([".js",".mjs",".mts",".ts",".tsx"]),bn=/\(void 0\)|is not a function|before initialization|of undefined/u,$n=e=>typeof e=="object"&&e!==null&&typeof e.functionPath=="string"&&(e.deferred===void 0||["agent","module","queue","workflow"].includes(e.deferred))&&typeof e.message=="string",Sn=e=>{const r=I(e),t=new Map;let n;try{n=ve(y(e,r),{recursive:!0,encoding:"utf8"})}catch{return t}for(const o of n){const s=Gr(o);fr.has(s)&&!o.split(B).some(a=>a==="_generated"||a==="node_modules")&&t.set(yn(o.slice(0,-s.length).split(B).join("/")),y(r,o))}return t},Le=e=>bn.test(e)?`
5
- hint: if this module is part of a circular import, an import it reads is still undefined while it evaluates`:"",En=(e,r)=>{const t=Sn(e),n=new Map,o=[];for(const{deferred:s,functionPath:a,message:i}of r){if(s!==void 0){o.push(` ${a.slice(s.length+1)} (${s}): ${i}${Le(i)}`);continue}const c=a.lastIndexOf(":"),l=a.slice(0,c),d=`${l}\0${i}`,f=n.get(d)??{exports:[],message:i,namespace:l};f.exports.push(a.slice(c+1)),n.set(d,f)}return[...[...n.values()].map(({exports:s,message:a,namespace:i})=>` ${t.get(i)??i} (${s.join(", ")}): ${a}${Le(a)}`),...o]},Y=e=>{for(const r of fr)for(const t of[`${e}${r}`,y(e,`index${r}`)])if(b(t))return t},An=(e,r)=>{const t=y(e,r,"_generated"),n=i=>{try{return E(y(t,i),"utf8")}catch{return""}},o=n("app.ts"),s=[],a=(i,c)=>{c!==void 0&&s.push({file:c,kind:i,label:F(e,c).split(B).join("/")})};return o.includes('import("./queues.js")')&&a("queue",Y(y(t,"queues"))),n("workflows.mjs").includes('import("../workflows.js")')&&a("workflow",Y(y(e,r,"workflows"))),(n("agents.mjs").includes('import("../agents.js")')||o.includes('import("../agents.js")'))&&a("agent",Y(y(e,r,"agents"))),s},Rn=/\.[cm]?js$/u,Tn=/(?:await|=>|return|[=[,])\s*import\(\s*"([^"]+)"\s*\)(?!\s*\.(?!(?:then|catch|finally)\b))/gu,Pn=(e,r,t)=>{const n=y(e,r,"_generated"),o=new Set(t.map(i=>i.file)),s=[];let a;try{a=ve(n).filter(i=>i.endsWith(".mjs")&&i!=="functions.ts")}catch{return s}for(const i of a.toSorted((c,l)=>c.localeCompare(l)))for(const c of E(y(n,i),"utf8").matchAll(Tn)){const l=c[1]??"",d=l.startsWith("."),f=d?Y(N(n,l.replace(Rn,""))):l;f!==void 0&&!o.has(f)&&(o.add(f),s.push({file:f,kind:"module",label:d?F(e,f).split(B).join("/"):l}))}return s};class _ extends Error{skipped;constructor(r,t=!1){super(r),this.skipped=t}}const _n=(e,r)=>{const t=O(e),n=t===void 0?void 0:R(t).parsed;if(n===void 0)return{hasContainers:!1,main:void 0};const{merged:o}=oe(n,r);return{hasContainers:(o.containers??[]).length>0,main:o.main}},Dn=({composedEntry:e,configPath:r,cwd:t,environment:n,toolchain:o})=>{if(o.devServer!=="workerd")return{skip:"this deploy target does not run on workerd"};const{hasContainers:s,main:a}=_n(t,n),i=e??a;if(typeof i!="string"||i.startsWith("virtual:")||!b(N(t,i)))return{skip:"the Worker entry is not a file on disk"};if(s)return{skip:"the project declares containers, which `wrangler dev` would build locally before the real container build"};const c=wt(t,process.env,n,r);return c.length===0?{main:i}:{skip:`the Hyperdrive binding ${c.join(", ")} has no local database for wrangler dev`}},Cn=async(e,r,t)=>{const n=await fetch(`http://127.0.0.1:${String(e)}/_lunora/__smoke_load`,{signal:AbortSignal.timeout(Math.max(0,t-Date.now()))}).catch(u=>{throw u instanceof Error&&u.name==="TimeoutError"?new _(`the smoke Worker booted but did not finish evaluating the lazy modules within ${String(ur/1e3)}s — a module may be awaiting something that never settles. Pass --no-smoke-load to ship anyway.`):u});if(n.status>=500)throw new _(`the smoke Worker booted but failed while evaluating the lazy modules (HTTP ${String(n.status)}). Pass --no-smoke-load to ship anyway.`);const o=await n.text().catch(()=>"");let s;try{s=JSON.parse(o)}catch{s=void 0}const{checked:a,deferredChecked:i=0,failures:c,run:l}=s??{};if(typeof a=="number"&&Array.isArray(c)&&c.every(u=>$n(u)))return l===r?{checked:a,deferredChecked:i,failures:c}:void 0;const d=n.headers.get("content-type")??"no content type",f=o.replaceAll(/\s+/gu," ").trim().slice(0,120);throw new _(`the smoke Worker answered with something other than the probe's result (HTTP ${String(n.status)}, ${d}${f===""?"":`: ${f}`}). A route that does not send /_lunora/* to the Worker first answers with the app's assets, so check run_worker_first. Pass --no-smoke-load to ship anyway.`)},he=(e,r)=>{try{process.kill(-e,r)}catch{}},Me=e=>{try{return process.kill(-e,0),!0}catch{return!1}},In=e=>{const r=()=>{he(e,"SIGKILL")},t=o=>{r(),process.kill(process.pid,o)},n=()=>{process.removeListener("exit",r),process.removeListener("SIGINT",t),process.removeListener("SIGTERM",t)};return process.once("exit",r),process.once("SIGINT",t),process.once("SIGTERM",t),n},de=async e=>{if(e===void 0)return;e.dispose();const{pid:r}=e;he(r,"SIGTERM");const t=Date.now()+kn;for(;Me(r)&&Date.now()<t;)await Vt(50);Me(r)&&he(r,"SIGKILL")},On=e=>zr(e).catch(async r=>{if(!await Jr(e.port))throw r}),Nn=(e,{checked:r,deferredChecked:t,failures:n},o)=>{const s=t===0?`${String(r)} lazy function(s)`:`${String(r)} lazy function(s) and ${String(t)} deferred module(s)`;if(n.length===0){o.success(`${s} evaluate cleanly`);return}const a=En(e,n),i=a.length>ce?[` …and ${String(a.length-ce)} more module(s)`]:[];throw new _([`${String(n.length)} of ${t===0?`${String(r)} lazy function(s)`:`${String(r+t)} lazy module(s)`} fail to load:`,...a.slice(0,ce),...i,"Fix the module, or pass --no-smoke-load to ship anyway."].join(`
6
- `))},jn=(e,r,t)=>{if(e instanceof _&&!e.skipped)return t.error(e.message),e.message;if(e instanceof _){t.warn(`smoke-load skipped: ${e.message}`);return}const n=r.slice(-5).join(`
3
+ `)}`},_n=(e,r)=>p(e,".lunora",r===void 0?"architecture.json":`architecture.${r}.json`),Cn=e=>{if(b(e))try{const r=JSON.parse(E(e,"utf8"));return r.version===1&&Array.isArray(r.modules)&&Array.isArray(r.edges)?r:void 0}catch{return}},In=e=>{const{cwd:r,environment:t,logger:n}=e,o=_n(r,t),s=Cn(o),i=e.current??(s===void 0?void 0:En);if(i===void 0)return;const a=s===void 0?void 0:Tn(Rn(s,i));return a!==void 0&&n.info(a),()=>{try{hr(j(o),{recursive:!0}),X(o,`${JSON.stringify(i,void 0,2)}
4
+ `,"utf8")}catch(c){n.warn(`could not record the deployed architecture at ${o}: ${c instanceof Error?c.message:String(c)}`)}}},Pn=e=>{const{cwd:r,env:t,logger:n,mintedSecretsFile:o}=e;try{const s=_e(r),i=s?.workerName??Pe(r),a=e.url??s?.workerUrl;n.success("deploy complete"),n.info(` worker: ${i??"(see wrangler output above)"}`),t!==void 0&&n.info(` env: ${t}`),a===void 0?n.info(" url: run `lunora link --url <https://your-worker>` to record it"):n.info(` url: ${a}`),o!==void 0&&n.info(` secrets: generated value(s) recorded in ${o}`),e.logsAvailable&&n.info(" logs: lunora logs")}catch{}},jn=/\/index$/u,On=/[^\dA-Za-z]/gu,Dn=e=>e.replace(jn,"").split("/").map(r=>r.replaceAll(On,"_")),Nn=e=>Dn(e).join("_"),Ln=/[^a-z0-9-]/gu,xn=/-$/u,Ke=7,Mn=(e,r)=>{const t=e.toLowerCase(),n=t.replaceAll(Ln,"-");if(n===t&&n.length<=r)return n;const o=an("sha256").update(t).digest("hex").slice(0,Ke-1);return`${n.slice(0,r-Ke).replace(xn,"")}-${o}`},Fn=32,Tr=15e3,Un=5432,Bn=3306,Wn=/[^A-Za-z0-9]/gu,Y=e=>`LUNORA_${e.replaceAll(Wn,"_").toUpperCase()}_URL`,Hn=e=>{const r=new Map;for(const t of e){const n=Y(t),o=r.get(n);if(o!==void 0)return{bindings:[o,t],variable:n};r.set(n,t)}},qn=(e,r)=>Mn(`${e}-${r}`,Fn),ze=e=>e==="postgresql"?"postgres":e==="mariadb"?"mysql":e,Gn=e=>e==="mysql"?Bn:Un,Vn=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===""?Gn(ze(t)):Number(r.port),scheme:ze(t),user:decodeURIComponent(r.username)}}catch{return}},Kn=(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 s of n)o=o.replaceAll(s,"<redacted>");return o.split(" ").map(s=>s.includes("://")?"<url>":s).join(" ")},_r=e=>(Array.isArray(e)?e:[]).flatMap((r,t)=>{const{binding:n,id:o}=typeof r=="object"&&r!==null?r:{};return typeof n=="string"&&o===wr?[{binding:n,index:t}]:[]}),se=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}`},zn=e=>typeof e=="string"||typeof e=="number"?e.toString():void 0,Jn=["scheme","host","port","database","user"],Yn=e=>e==="postgresql"?"postgres":e,Je=(e,r)=>{const t=zn(r);return e==="scheme"?Yn(t):t},Ye=50,Xn=async(e,r)=>{for(let t=1;t<=Ye;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 (${se(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(i=>i.name===r),s=typeof n.body.result_info=="object"&&n.body.result_info!==null?n.body.result_info:{};if(o!==void 0||typeof s.total_pages!="number"||t>=s.total_pages)return o}throw new Error(`the listing of Hyperdrive configs has more than ${String(Ye)} pages, so "${r}" can't be shown to be absent`)},Qn=async(e,r,t,n)=>{const o=n?{caching:{disabled:!0}}:{},s=await Xn(e,r);if(typeof s?.id=="string"){const c=Jn.filter(d=>Je(d,s.origin?.[d])!==Je(d,t[d]));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 l=await e(`/hyperdrive/configs/${encodeURIComponent(s.id)}`,{body:JSON.stringify({origin:t,...o}),method:"PATCH"});if(!l.ok)throw new Error(`updating its credentials failed (${se(l)})`);return{id:s.id,reused:!0}}const i=await e("/hyperdrive/configs",{body:JSON.stringify({name:r,origin:t,...o}),method:"POST"});if(!i.ok)throw new Error(`creating it failed (${se(i)})`);const{id:a}=typeof i.body.result=="object"&&i.body.result!==null?i.body.result:{};if(typeof a!="string")throw new TypeError("the response carried no id");return{id:a,reused:!1}},Zn=(e,r,t,n)=>r===void 0&&n?`${Y(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 ${Y(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.`,eo=async(e,r)=>{const t=qn(e.workerName,e.binding),{id:n,reused:o}=await Qn(async(s,i)=>Er({accountId:e.accountId,apiToken:e.token,...e.fetch===void 0?{}:{fetch:e.fetch},init:{...i,signal:AbortSignal.timeout(Tr)},path:s}),t,e.origin,e.disableCaching);return e.logger.success(`${o?"reusing":"created"} Hyperdrive config "${t}" for ${e.binding} → ${e.wranglerPath}`),{id:n,text:kr(r,[...e.path,e.index,"id"],n)}},ro=e=>e===void 0||e===""?void 0:e,De=e=>{const r=p(j(e),".wrangler","deploy","config.json");try{const{configPath:t}=JSON.parse(E(r,"utf8"));return typeof t=="string"?I(j(r),t):void 0}catch{return}},to=(e,r,t,n,o)=>{const s=De(e);if(s===void 0||s===e)return;if(n.built!==n.deployed){o.warn(`the build output ${s} 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 i;try{i=P(s)}catch{return}const a=_r(i.parsed?.hyperdrive).find(c=>c.binding===r);a!==void 0&&X(s,kr(i.text,["hyperdrive",a.index,"id"],t),"utf8")},no=(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}`},Ne=(e,r)=>{const t=O(e),n=t===void 0?void 0:P(t).parsed;if(t===void 0||n===void 0)return;const o=r===void 0?void 0:n.env?.[r],s=_r(r===void 0?n.hyperdrive:o?.hyperdrive);return s.length===0?void 0:{accountId:o?.account_id??n.account_id,entries:s,path:r===void 0?["hyperdrive"]:["env",r,"hyperdrive"],workerName:no(n,r),wranglerPath:t}},oo=(e,r,t)=>{const n=Hn(e.map(({binding:o})=>o));if(n!==void 0){const o=`deploy blocked: the Hyperdrive bindings ${n.bindings.map(s=>`"${s}"`).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:s,supplied:i}of e){const a=Zn(o,s,r,i);if(a!==void 0&&t.dryRun===!0)t.logger.warn(`dry run: ${a} A real deploy stops here.`);else if(a!==void 0){const c=`deploy blocked: ${a}`;return t.logger.error(c),c}}},so=async(e,r,t,n)=>{let o;try{o=await e(`/hyperdrive/configs/${encodeURIComponent(t)}`)}catch(i){n.warn(`could not check whether the "${r}" Hyperdrive config has query caching off (${i instanceof Error?i.message:String(i)}).`);return}if(!o.ok){n.warn(`could not check whether the "${r}" Hyperdrive config has query caching off (${se(o)}).`);return}const{caching:s}=typeof o.body.result=="object"&&o.body.result!==null?o.body.result:{};s?.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\`.`)},io=async(e,r)=>{const t=O(e.cwd),n=t===void 0?void 0:P(t).parsed,o=e.wranglerEnvironment===void 0?n:n?.env?.[e.wranglerEnvironment],{accountId:s,token:i}=Sr(r,o?.account_id??n?.account_id);if(s===void 0||i===void 0)return;const a=async(c,l)=>Er({accountId:s,apiToken:i,...e.fetch===void 0?{}:{fetch:e.fetch},init:{...l,signal:AbortSignal.timeout(Tr)},path:c});for(const c of Array.isArray(o?.hyperdrive)?o.hyperdrive:[]){const{binding:l,id:d}=typeof c=="object"&&c!==null?c:{};typeof l=="string"&&typeof d=="string"&&d!==wr&&await so(a,l,d,e.logger)}},ao=async e=>{const r=e.environment??process.env;e.disableCaching===!0&&e.checkOnly!==!0&&e.dryRun!==!0&&await io(e,r);const t=Ne(e.cwd,e.wranglerEnvironment);if(t===void 0)return;const{entries:n,path:o,wranglerPath:s}=t,{accountId:i,token:a}=Sr(r,t.accountId),c=n.map(({binding:d})=>{const u=r[Y(d)]??"";return{binding:d,origin:Vn(u),supplied:u!==""}}),l=oo(c,a!==void 0&&i!==void 0,e);if(l!==void 0)return l;if(!(e.dryRun===!0||e.checkOnly===!0))for(const[d,{binding:u,index:f}]of n.entries()){const h=c[d]?.origin;if(!(h===void 0||a===void 0||i===void 0))try{const{id:g,text:v}=await eo({accountId:i,binding:u,disableCaching:e.disableCaching===!0,fetch:e.fetch,index:f,logger:e.logger,origin:h,path:o,token:a,workerName:t.workerName,wranglerPath:s},E(s,"utf8"));X(s,v,"utf8"),to(s,u,g,{built:ro(r.CLOUDFLARE_ENV),deployed:e.wranglerEnvironment},e.logger)}catch(g){const v=g instanceof Error?g.message:String(g),m=`deploy blocked: the "${u}" Hyperdrive config could not be set up: ${Kn(v,c[d]?.origin)}`;return e.logger.error(m),m}}},co=(e,r)=>{const t=Ne(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 ${Y(t)} set to create the config, or put the id from \`wrangler hyperdrive create\` in wrangler.jsonc.`;return r.logger.error(n),n},lo=(e,r)=>{const t=Ne(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},Cr=async(e,r,t,n,o="create")=>{if(n!=="cloudflare")return;if(t==="prepare")return co(e,r);if(r.temporary===!0)return lo(e,r);const s=r.clientBuildEnvironment===void 0?void 0:{...process.env,CLOUDFLARE_ENV:r.clientBuildEnvironment},i=Ce(e,M(e),r.discoveryCache);return i.error!==void 0&&r.logger.warn(`could not read the schema (${i.error}), so Hyperdrive configs are set up with query caching off.`),ao({checkOnly:o==="check",cwd:e,disableCaching:i.error!==void 0||i.info?.hasHyperdriveGlobalTable===!0,dryRun:r.dryRun,environment:s,logger:r.logger,wranglerEnvironment:r.env})},he=[".ts",".tsx",".mts",".js",".mjs"],uo=/^[a-z]+:/u,Xe=/\.[cm]?js$/u,fo=e=>!e.startsWith(".")&&!e.startsWith("/")&&!e.startsWith("#")&&!uo.test(e),go=e=>e.split("/").slice(0,e.startsWith("@")?2:1).join("/"),ho=e=>e.split(x).some(r=>r==="_generated"||r==="node_modules"),mo=e=>e.split(x).includes("node_modules"),Qe=(e,r)=>{const t=I(j(e),r),n=Xe.test(t)?t.replace(Xe,""):void 0;return[t,...n===void 0?[]:he.map(s=>`${n}${s}`),...he.map(s=>`${t}${s}`),...he.map(s=>p(t,`index${s}`))].find(s=>b(s)&&Re(s).isFile())},po=/^lunora\.config\.[cm]?[jt]s$/u,ke=e=>{if(typeof e=="string")return e;if(typeof e=="object"&&e!==null)for(const[r,t]of Object.entries(e)){const n=r==="types"?void 0:ke(t);if(n!==void 0)return n}},vo=(e,r)=>{let t;try{t=JSON.parse(E(p(e,"package.json"),"utf8")).imports}catch{return}const n=ke(t?.[r]);if(n!==void 0)return n;for(const[o,s]of Object.entries(t??{})){const[i="",a=""]=o.split("*"),c=ke(s);if(c!==void 0&&o.includes("*")&&r.startsWith(i)&&r.endsWith(a)&&r.length>=o.length-1){const l=r.slice(i.length,r.length-a.length);return c.replaceAll("*",()=>l)}}},yo=(e,r)=>{const t=p(e,r,"_generated"),n=K(e).find(o=>po.test(o));return[...b(t)?K(t).filter(o=>o.endsWith(".ts")).map(o=>p(t,o)):[],...n===void 0?[]:[p(e,n)]]},wo=e=>{const r=k.findConfigFile(e,n=>k.sys.fileExists(n));if(r===void 0)return!1;const t=k.readConfigFile(r,n=>k.sys.readFile(n));return k.parseJsonConfigFileContent(t.config??{},k.sys,j(r)).options.verbatimModuleSyntax===!0},Ze=e=>e!==void 0&&(k.isNamedImports(e)||k.isNamedExports(e))&&e.elements.length>0&&e.elements.every(r=>r.isTypeOnly),ko=(e,r)=>{if(k.isImportDeclaration(e)){const{importClause:t}=e;return!(t?.phaseModifier===k.SyntaxKind.TypeKeyword||!r&&t?.name===void 0&&Ze(t?.namedBindings))&&k.isStringLiteral(e.moduleSpecifier)?e.moduleSpecifier.text:void 0}if(k.isExportDeclaration(e))return!(e.isTypeOnly||!r&&Ze(e.exportClause))&&e.moduleSpecifier!==void 0&&k.isStringLiteral(e.moduleSpecifier)?e.moduleSpecifier.text:void 0},bo=e=>{if(!k.isCallExpression(e)||e.expression.kind!==k.SyntaxKind.ImportKeyword)return;const[r]=e.arguments;return r!==void 0&&k.isStringLiteralLike(r)?r.text:void 0},$o=(e,r)=>{const t=k.createSourceFile(e,E(e,"utf8"),k.ScriptTarget.Latest,!1),n=[],o=[],s=i=>{const a=bo(i),c=a??ko(i,r);c?.startsWith(".")||c?.startsWith("#")?o.push(c):a!==void 0&&fo(a)&&n.push(a),k.forEachChild(i,s)};return s(t),{dynamicPackages:n,relative:o}},So=(e,r)=>{for(let t=e;;t=j(t)){if(b(p(t,"node_modules",r,"package.json")))return!0;if(j(t)===t)return!1}},Eo=(e,r,t)=>{const n=wo(e),o=new Set,s=new Set,i=r!==void 0&&b(I(e,r))?[I(e,r)]:yo(e,t);for(let a=i.shift();a!==void 0;a=i.shift())if(!o.has(a)&&!mo(L(e,a))){o.add(a);const{dynamicPackages:c,relative:l}=$o(a,n);if(!ho(L(e,a)))for(const d of c)s.add(d);i.push(...l.flatMap(d=>{if(!d.startsWith("#"))return Qe(a,d)??[];const u=vo(e,d);return u===void 0?[]:Qe(p(e,"package.json"),u)??[]}))}return[...s].filter(a=>So(e,go(a))).toSorted((a,c)=>a.localeCompare(c))},Ao=18787,er=3,be=12e4,Ro=5e3,W=10,Ir=new Set([".js",".mjs",".mts",".ts",".tsx"]),To=/\(void 0\)|is not a function|before initialization|of undefined/u,_o=e=>typeof e=="object"&&e!==null&&typeof e.functionPath=="string"&&(e.deferred===void 0||["agent","module","queue","workflow"].includes(e.deferred))&&typeof e.message=="string",Co=e=>{const r=M(e),t=new Map;let n;try{n=K(p(e,r),{recursive:!0,encoding:"utf8"})}catch{return t}for(const o of n){const s=it(o);Ir.has(s)&&!o.split(x).some(i=>i==="_generated"||i==="node_modules")&&t.set(Nn(o.slice(0,-s.length).split(x).join("/")),p(r,o))}return t},rr=e=>To.test(e)?`
5
+ hint: if this module is part of a circular import, an import it reads is still undefined while it evaluates`:"",Io=(e,r)=>{const t=Co(e),n=new Map,o=[];for(const{deferred:s,functionPath:i,message:a}of r){if(s!==void 0){o.push(` ${i.slice(s.length+1)} (${s}): ${a}${rr(a)}`);continue}const c=i.lastIndexOf(":"),l=i.slice(0,c),d=`${l}\0${a}`,u=n.get(d)??{exports:[],message:a,namespace:l};u.exports.push(i.slice(c+1)),n.set(d,u)}return[...[...n.values()].map(({exports:s,message:i,namespace:a})=>` ${t.get(a)??a} (${s.join(", ")}): ${i}${rr(i)}`),...o]},te=e=>{for(const r of Ir)for(const t of[`${e}${r}`,p(e,`index${r}`)])if(b(t))return t},Po=(e,r)=>{const t=p(e,r,"_generated"),n=a=>{try{return E(p(t,a),"utf8")}catch{return""}},o=n("app.ts"),s=[],i=(a,c)=>{c!==void 0&&s.push({file:c,kind:a,label:L(e,c).split(x).join("/")})};return o.includes('import("./queues.js")')&&i("queue",te(p(t,"queues"))),n("workflows.mjs").includes('import("../workflows.js")')&&i("workflow",te(p(e,r,"workflows"))),(n("agents.mjs").includes('import("../agents.js")')||o.includes('import("../agents.js")'))&&i("agent",te(p(e,r,"agents"))),s},jo=/\.[cm]?js$/u,Oo=/(?:await|=>|return|[=[,])\s*import\(\s*"([^"]+)"\s*\)(?!\s*\.(?!(?:then|catch|finally)\b))/gu,Do=(e,r,t)=>{const n=p(e,r,"_generated"),o=new Set(t.map(a=>a.file)),s=[];let i;try{i=K(n).filter(a=>a.endsWith(".mjs")&&a!=="functions.ts")}catch{return s}for(const a of i.toSorted((c,l)=>c.localeCompare(l)))for(const c of E(p(n,a),"utf8").matchAll(Oo)){const l=c[1]??"",d=l.startsWith("."),u=d?te(I(n,l.replace(jo,""))):l;u!==void 0&&!o.has(u)&&(o.add(u),s.push({file:u,kind:"module",label:d?L(e,u).split(x).join("/"):l}))}return s};class C extends Error{skipped;constructor(r,t=!1){super(r),this.skipped=t}}const No=/^[$_\p{ID_Start}][$\u200C\u200D\p{ID_Continue}]*$/u,Pr=(e,r,t)=>{const n=t??O(e),o=n===void 0?void 0:P(n).parsed;if(o===void 0)return{durableObjectClasses:[],hasContainers:!1,main:void 0,workflowClasses:[]};const{merged:s}=le(o,r),i=a=>[...new Set(a.flatMap(c=>c?.script_name===void 0&&typeof c?.class_name=="string"&&No.test(c.class_name)?[c.class_name]:[]))];return{durableObjectClasses:i(s.durable_objects?.bindings??[]),hasContainers:(s.containers??[]).length>0,main:s.main,workflowClasses:i(s.workflows??[])}},Lo=({composedEntry:e,configPath:r,cwd:t,environment:n,toolchain:o})=>{if(o.devServer!=="workerd")return{skip:"this deploy target does not run on workerd"};const{durableObjectClasses:s,hasContainers:i,main:a,workflowClasses:c}=Pr(t,n,r),l=e??a,d=r??O(t);let u;if(d!==void 0&&De(d)!==void 0)u={stubs:{durableObjects:s,workflows:c}};else if(typeof l=="string"&&!l.startsWith("virtual:")&&b(I(t,l)))u={main:l};else return{skip:"the Worker entry is not a file on disk"};if(i)return{skip:"the project declares containers, which `wrangler dev` would build locally before the real container build"};const f=Nt(t,process.env,n,r);return f.length>0?{skip:`the Hyperdrive binding ${f.join(", ")} has no local database for wrangler dev`}:{base:u,configFile:d}},xo=/The Workers runtime failed to start|Build failed with \d+ error/u,Mo=/\[ERROR\]|Uncaught/u,tr=e=>{const r=e.map(o=>dn(o).trim()).filter(o=>o!==""),t=r.filter(o=>Mo.test(o)),n=t.length>0?t.slice(0,10):r.slice(-10);return n.length===0?"":`
6
+ ${n.map(o=>` ${o}`).join(`
7
+ `)}`},$e=async e=>{const{deadline:r,output:t,pending:n,port:o,query:s,startupFailed:i}=e,a=await fetch(`http://127.0.0.1:${String(o)}/_lunora/__smoke_load?${s}`,{signal:AbortSignal.any([AbortSignal.timeout(Math.max(0,r-Date.now())),i])}).catch(d=>{throw i.aborted?new C(`the smoke Worker's runtime did not start, so nothing was evaluated:${tr(t)}
8
+ Fix the entry, or pass --no-smoke-load to ship anyway.`):d instanceof Error&&d.name==="TimeoutError"?new C(n===void 0?`the smoke Worker accepted the connection but answered no request within ${String(be/1e3)}s, so its runtime did not start:${tr(t)}
9
+ Pass --no-smoke-load to ship anyway.`:`the smoke Worker did not finish evaluating ${n} within ${String(be/1e3)}s — it may be awaiting something that never settles. Pass --no-smoke-load to ship anyway.`):d});if(a.status>=500)throw new C(`the smoke Worker booted but failed while ${n===void 0?"answering a request that evaluates nothing":`evaluating ${n}`} (HTTP ${String(a.status)}). Pass --no-smoke-load to ship anyway.`);const c=await a.text().catch(()=>"");let l;try{l=JSON.parse(c)}catch{l=void 0}return{body:typeof l=="object"&&l!==null?l:void 0,response:a,text:c}},Se=(e,r)=>{const t=e.headers.get("content-type")??"no content type",n=r.replaceAll(/\s+/gu," ").trim().slice(0,120);return new C(`the smoke Worker answered with something other than the probe's result (HTTP ${String(e.status)}, ${t}${n===""?"":`: ${n}`}). A route that does not send /_lunora/* to the Worker first answers with the app's assets, so check run_worker_first. Pass --no-smoke-load to ship anyway.`)},nr=async(e,r)=>{const t=await $e(e),n=t.body?.message;if(t.body?.run!==r||n!==void 0&&typeof n!="string")throw Se(t.response,t.text);return n},Fo=async e=>{const{deferred:r,functions:t,integrationModules:n,runId:o,...s}=e,i=await $e({...s,pending:void 0,query:"step=ping"});if(typeof i.body?.run!="string")throw Se(i.response,i.text);if(i.body.run!==o)return;let a=0,c=[];if(t){const d=await $e({...s,pending:"the lazy function modules",query:"step=functions"}),{checked:u,failures:f}=d.body??{};if(d.body?.run!==o||typeof u!="number"||!Array.isArray(f)||!f.every(h=>_o(h)))throw Se(d.response,d.text);a=u,c=f}for(const[d,u]of r.entries()){const f=await nr({...s,pending:`${u.kind} module ${u.label}`,query:`step=deferred&index=${String(d)}`},o);f!==void 0&&c.push({deferred:u.kind,functionPath:`${u.kind}:${u.label}`,message:f})}const l=[];for(const d of n){const u=await nr({...s,pending:`import(${JSON.stringify(d)})`,query:new URLSearchParams({specifier:d,step:"integration"}).toString()},o);u!==void 0&&l.push({message:u,specifier:d})}return{checked:a,deferredChecked:r.length,failures:c,integrations:{checked:n.length,failures:l}}},Ee=(e,r)=>{try{process.kill(-e,r)}catch{}},or=e=>{try{return process.kill(-e,0),!0}catch{return!1}},Uo=e=>{const r=()=>{Ee(e,"SIGKILL")},t=o=>{r(),process.kill(process.pid,o)},n=()=>{process.removeListener("exit",r),process.removeListener("SIGINT",t),process.removeListener("SIGTERM",t)};return process.once("exit",r),process.once("SIGINT",t),process.once("SIGTERM",t),n},me=async e=>{if(e===void 0)return;e.dispose();const{pid:r}=e;Ee(r,"SIGTERM");const t=Date.now()+Ro;for(;or(r)&&Date.now()<t;)await cn(50);or(r)&&Ee(r,"SIGKILL")},Bo=e=>lt(e).catch(async r=>{if(!await ut(e.port))throw r}),Wo=({checked:e,deferredChecked:r,integrations:t})=>[`${String(e)} lazy function(s)`,...r>0?[`${String(r)} deferred module(s)`]:[],...t.checked>0?[`${String(t.checked)} integration module(s) loaded with import()`]:[]].join(" and "),Ho=(e,r,t)=>{const{checked:n,deferredChecked:o,failures:s,integrations:i}=r;if(s.length===0&&i.failures.length===0){t.success(`${Wo(r)} evaluate cleanly`);return}const a=Io(e,s),c=a.length>W?[` …and ${String(a.length-W)} more module(s)`]:[];throw new C([...s.length===0?[]:[`${String(s.length)} of ${o===0?`${String(n)} lazy function(s)`:`${String(n+o)} lazy module(s)`} fail to load:`,...a.slice(0,W),...c],...i.failures.length===0?[]:[`${String(i.failures.length)} of ${String(i.checked)} integration module(s) fail to load in workerd (each would fail its first use instead):`,...i.failures.slice(0,W).map(({message:l,specifier:d})=>` import("${d}"): ${l}`),...i.failures.length>W?[` …and ${String(i.failures.length-W)} more integration module(s)`]:[]],"Fix the module, or pass --no-smoke-load to ship anyway."].join(`
10
+ `))},qo=(e,r,t)=>{if(e instanceof C&&!e.skipped)return t.error(e.message),e.message;if(e instanceof C){t.warn(`smoke-load skipped: ${e.message}`);return}const n=r.slice(-5).join(`
7
11
  `),o=`the smoke Worker did not start (${e instanceof Error?e.message:String(e)})${n===""?"":`
8
- ${n}`}. Either the entry fails when it loads, or local wrangler cannot run the project (a remote-only binding or a missing assets directory). Fix whichever it is, or pass --no-smoke-load to ship anyway.`;return t.error(o),o},Ln=e=>{try{return Xe(y(e,".lunora"),{recursive:!0}),Hr(y(e,".lunora","smoke-"))}catch(r){throw new _(`could not create a directory for the check (${r instanceof Error?r.message:String(r)})`,!0)}},Mn=async e=>{const{configPath:r,cwd:t,deferred:n,directory:o,environment:s,functionsFile:a,main:i,preferred:c,toolchain:l}=e;try{const d=y(o,"entry.ts"),f=ar();V(d,`export * from ${JSON.stringify(N(t,i))};
9
- ${a===void 0?"":`import { loadAllFunctions } from ${JSON.stringify(a)};
12
+ ${n}`}. Either the entry fails when it loads, or local wrangler cannot run the project (a remote-only binding or a missing assets directory). Fix whichever it is, or pass --no-smoke-load to ship anyway.`;return t.error(o),o},Go=e=>{try{return hr(p(e,".lunora"),{recursive:!0}),ot(p(e,".lunora","smoke-"))}catch(r){throw new C(`could not create a directory for the check (${r instanceof Error?r.message:String(r)})`,!0)}},Vo=(e,r)=>{if("main"in r)return`export * from ${V(I(e,r.main))};`;const{durableObjects:t,workflows:n}=r.stubs;return['import { DurableObject, WorkflowEntrypoint } from "cloudflare:workers";',...t.map(o=>`export class ${o} extends DurableObject {}`),...n.map(o=>`export class ${o} extends WorkflowEntrypoint { async run() {} }`)].join(`
13
+ `)},Ko=async e=>{const{base:r,configPath:t,cwd:n,deferred:o,directory:s,environment:i,functionsFile:a,integrationModules:c,preferred:l,toolchain:d}=e;try{const u=p(s,"entry.ts"),f=$r(),h=c.map(S=>` [${V(S)}, () => import(${V(S)})],`).join(`
14
+ `);X(u,`${Vo(n,r)}
15
+ ${a===void 0?"":`import { loadAllFunctions } from ${V(a)};
10
16
  `}
11
17
  const runId = ${JSON.stringify(f)};
12
18
 
13
- // Deferred event modules, evaluated here so a module that throws on import blocks like a function module does.
19
+ // Deferred event modules, evaluated one per request so a module that throws on import blocks like a function module does.
14
20
  const deferred = [
15
- ${n.map(v=>` { kind: ${JSON.stringify(v.kind)}, label: ${JSON.stringify(v.label)}, load: () => import(${JSON.stringify(v.file)}) },`).join(`
21
+ ${o.map(S=>` () => import(${V(S.file)}),`).join(`
16
22
  `)}
17
23
  ];
18
24
 
25
+ const integrationLoaders = new Map<string, () => Promise<unknown>>([
26
+ ${h}
27
+ ]);
28
+
19
29
  export default {
20
- async fetch() {
21
- const functions = ${a===void 0?"{ checked: 0, failures: [] }":"await loadAllFunctions()"};
22
- const loaded = await Promise.all(
23
- deferred.map(async ({ kind, label, load }) => {
24
- try {
25
- await load();
30
+ async fetch(request: Request) {
31
+ const url = new URL(request.url);
32
+ const step = url.searchParams.get("step");
33
+
34
+ if (step === "functions") {
35
+ return Response.json({ ...${a===void 0?"{ checked: 0, failures: [] }":"(await loadAllFunctions())"}, run: runId });
36
+ }
37
+
38
+ const load =
39
+ step === "deferred"
40
+ ? deferred[Number(url.searchParams.get("index"))]
41
+ : step === "integration"
42
+ ? integrationLoaders.get(url.searchParams.get("specifier") ?? "")
43
+ : undefined;
26
44
 
27
- return undefined;
28
- } catch (error) {
29
- return { deferred: kind, functionPath: kind + ":" + label, message: error instanceof Error ? error.message : String(error) };
30
- }
31
- }),
32
- );
45
+ if (load !== undefined) {
46
+ try {
47
+ await load();
48
+ } catch (error) {
49
+ return Response.json({ message: error instanceof Error ? error.message : String(error), run: runId });
50
+ }
51
+ }
33
52
 
34
- return Response.json({
35
- checked: functions.checked,
36
- deferredChecked: deferred.length,
37
- failures: [...functions.failures, ...loaded.filter((failure) => failure !== undefined)],
38
- run: runId,
39
- });
53
+ return Response.json({ run: runId });
40
54
  },
41
55
  };
42
- `);const u=await qt(c),{args:h,command:g}=H(j(t),l.dev({configPath:r===void 0?void 0:F(t,r),environment:s,extraArgs:[F(t,d),"--local","--local-protocol","http","--ip","127.0.0.1","--port",String(u),"--persist-to",F(t,y(o,"state"))]}));return{args:h,command:g,port:u,runId:f}}catch(d){throw new _(`could not prepare the check (${d instanceof Error?d.message:String(d)})`,!0)}},xn=async e=>{const{configPath:r,cwd:t,environment:n,launcher:o,logger:s,toolchain:a}=e,i=y(t,I(t),"_generated","functions.ts"),c=b(i)&&E(i,"utf8").includes("export const loadAllFunctions"),l=I(t),d=An(t,l);if(!c&&d.length===0)return;const f=[...d,...Pn(t,l,d)],u=Dn(e);if("skip"in u){s.warn(`smoke-load skipped: ${u.skip}, so lazy modules are not evaluated before deploy`);return}const{main:h}=u,g=[];let v,m;const T=Date.now()+ur,L=process.platform!=="win32",D=(P,S,q)=>{const M=Wt(P,[...S],{cwd:q.cwd,detached:L,shell:q.shell,stdio:["ignore","pipe","pipe"]});return L&&M.pid!==void 0&&(m={dispose:In(M.pid),pid:M.pid}),M};try{v=Ln(t),s.info("smoke-loading lazy function modules in workerd");let P=wn;for(let S=0;S<je;S+=1){const{args:q,command:M,port:ie,runId:Br}=await Mn({configPath:r,cwd:t,deferred:f,directory:v,environment:n,functionsFile:c?i:void 0,main:h,preferred:P,toolchain:a});P=ie+1;const De=await On({args:q,command:M,cwd:t,spawn:o??D,label:"wrangler dev (smoke-load)",notFound:"`wrangler` was not found",onLine:K=>{g.push(K)},port:ie,readyTimeoutMs:Math.max(0,T-Date.now()),shell:process.platform==="win32"});if(De===void 0){await de(m),m=void 0;continue}try{const K=await Cn(ie,Br,T);if(K!==void 0){Nn(t,K,s);return}}finally{await De.stop(),await de(m),m=void 0}}throw new _(`the smoke port was answered by other runs on all ${String(je)} attempts`,!0)}catch(P){return jn(P,g,s)}finally{if(await de(m),v!==void 0)try{Q(v,{force:!0,recursive:!0})}catch{}}},Fn=(e,r)=>r===void 0?e:N(e,r),Un=async e=>{if(e.targets.length===0)return{builtTags:[],code:0};if(!(e.railpackAvailable??zt)()){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=Kt(n.exportName),s={args:["build",n.buildDir,"--name",o],command:"railpack",cwd:e.cwd},a=$e(j(e.cwd),"wrangler",["containers","push",o]),i={args:a.args,command:a.command,cwd:e.cwd};e.logger.info(`railpack: building "${n.exportName}" → ${o} from ${n.buildDir}`);const c=await r(s);if(c.code!==0){const d=`railpack build failed for container "${n.exportName}" (${n.buildDir})`;return e.logger.error(d),{builtTags:t,code:c.code,error:d}}e.logger.info(`railpack: pushing ${o} to the Cloudflare Registry`);const l=await r(i);if(l.code!==0){const d=`wrangler containers push failed for "${n.exportName}" (${o})`;return e.logger.error(d),{builtTags:t,code:l.code,error:d}}t.push(o)}return{builtTags:t,code:0}},Bn=new Set(["0.0.0.0","[::1]","[::]","localhost"]),Hn=[".local",".localhost"],Wn=["[fc","[fd"],Gn=/^\[fe[89ab][0-9a-f]:/u,Vn=/^[a-z]+:\/\//u,xe=e=>{const r=e.split(".").map(Number);if(r.length!==4||r.some(o=>!Number.isInteger(o)))return!1;const[t=-1,n=-1]=r;return t===0||t===127||t===100&&n>=64&&n<=127||t===198&&(n===18||n===19)||t===10||t===192&&n===168||t===172&&n>=16&&n<=31||t===169&&n===254},Fe="[::ffff:",qn=e=>{if(!e.startsWith(Fe)||!e.endsWith("]"))return;const r=e.slice(Fe.length,-1);if(r.includes("."))return r;const[t=0,n=0]=r.split(":").map(o=>Number.parseInt(o,16));return[Math.floor(t/256),t%256,Math.floor(n/256),n%256].join(".")},gr=e=>{let r=e.length;for(;r>0&&e[r-1]===".";)r-=1;return e.slice(0,r).toLowerCase()},Kn=e=>{const r=e.toLowerCase(),t=qn(r);return t!==void 0?xe(t):Bn.has(r)||Hn.some(n=>r.endsWith(n))||Wn.some(n=>r.startsWith(n))||Gn.test(r)||xe(r)},hr=e=>{const r=O(e);return r===void 0?void 0:R(r).parsed},mr=(e,r)=>{const t=typeof e?.name=="string"&&e.name!==""?e.name:void 0;if(r===void 0)return t;const n=e?.env?.[r]?.name;return typeof n=="string"&&n!==""?n:t===void 0?void 0:`${t}-${r}`},Z=(e,r)=>{let t=e.length;for(;t>0&&e[t-1]===r;)t-=1;return e.slice(0,t)},zn=e=>{const r=e.replace(Vn,""),t=r.indexOf("/"),n=(t===-1?r:r.slice(0,t)).toLowerCase(),o=t===-1?"":Z(r.slice(t),"*");return o==="/"?n:`${n}${o}`},Ue=e=>[e?.route,...Array.isArray(e?.routes)?e.routes:[]].flatMap(t=>{const n=typeof t=="string"?t:t?.pattern;return typeof n=="string"&&n!==""?[zn(n)]:[]}),Jn=(e,r,t)=>{const n=t.indexOf("/"),o=n===-1?t:t.slice(0,n),s=n===-1?"":t.slice(n),a=o.startsWith("*");if(!(!(a?e.endsWith(o.slice(1)):e===o)||s!==""&&!`${Z(r,"/")}/`.startsWith(s)))return s.length*1e6+(a?0:5e5)+o.length},Yn=e=>e!==void 0&&(Object.hasOwn(e,"route")||Object.hasOwn(e,"routes")),vr=(e,r)=>{const t=Ue(e),o=[...new Set([...Object.keys(e?.env??{}),...r===void 0?[]:[r]])].map(s=>{const a=e?.env?.[s];return{id:`env:${s}`,label:`--env ${s}`,routes:Yn(a)?Ue(a):t}});return[{id:"top",label:"production",routes:t},...o]},Xn=(e,r,t,n)=>{const o=r===void 0?"top":`env:${r}`,s=vr(e,r).flatMap(c=>c.routes.flatMap(l=>{const d=Jn(t,n,l);return d===void 0?[]:[{block:c,score:d}]}));if(s.length===0)return{kind:"none"};const a=Math.max(...s.map(c=>c.score)),i=s.filter(c=>c.score===a);return i.some(c=>c.block.id===o)?{kind:"own"}:{kind:"other",label:i[0]?.block.label??"production"}},X=e=>_t(`${e.origin}${e.pathname}`),Qn=(e,r,t,n,o)=>{const s=ye(e),a=s?.workerUrl!==void 0&&URL.canParse(s.workerUrl)?new URL(s.workerUrl):void 0;if(a===void 0)return;if(s?.env===r)return X(a)===X(t)?null:`${n}: this checkout is linked to ${X(a)}${o}`;const i=`${Z(a.pathname,"/")}/`;if(a.origin!==t.origin||!`${Z(t.pathname,"/")}/`.startsWith(i))return;const c=s?.env===void 0?"production":`--env ${s.env}`;return`${n}: this checkout links it to ${c}, not this deploy${o}`},pr=(e,r,t,n,o,s)=>{const a=Xn(e,r,t,n);if(a.kind==="other")return`${o}: wrangler routes it to ${a.label}, not this deploy${s}`;if(a.kind==="own")return;const i=vr(e,r);if(i.every(l=>l.routes.length===0))return;const c=i.find(l=>l.id===(r===void 0?"top":`env:${r}`))?.routes??[];return`${o}: this deploy${s} routes to ${c.length===0?"no declared route":c.join(", ")}, not ${t}`},Zn=(e,r,t,n,o,s)=>{const a=hr(e);if(t.endsWith(".workers.dev")){const i=mr(a,r);return i!==void 0&&t.split(".")[0]!==i?`${o}: this deploy ships the Worker "${i}"${s}`:`${o}: no link ties this *.workers.dev host to your account${s}; run \`lunora link --url https://${t}${r===void 0?"":` --env ${r}`}\` once the Worker is deployed, then deploy again (or confirm the drift yourself with --allow-schema-drift)`}return pr(a,r,t,n,o,s)},eo=(e,r,t,n,o)=>{const s=hr(e),a=gr(t.hostname);if(a.endsWith(".workers.dev")){const i=mr(s,r);return i===void 0||a.split(".")[0]===i?void 0:`${n}: this deploy ships the Worker "${i}", not the one the link names${o}`}return pr(s,r,a,t.pathname,n,o)},ro=(e,r,t)=>{let n;try{n=new URL(t)}catch{return`refused ${t} as the deployment to read rows from: it is not a URL`}const o=`refused ${X(n)} as the deployment to read rows from`,s=r===void 0?"":` (--env ${r})`,a=gr(n.hostname);if(Kn(a))return`${o}: it is a local or private address, not the worker this deploy ships to`;const i=Qn(e,r,n,o,s);return i===void 0?Zn(e,r,a,n.pathname,o,s):i??eo(e,r,n,o,s)},yr=e=>{const t=[O(e),y(e,"package.json"),y(e,"wrangler.dev.jsonc")].filter(n=>n!==void 0&&b(n)).map(n=>[n,E(n,"utf8")]);return()=>{for(const[n,o]of t)E(n,"utf8")!==o&&V(n,o,"utf8")}},to=(e,r=ar())=>N(e,".lunora",`vite-bundle-meta-${r}.json`),wr="LUNORA_CLIENT_BUILD",no="virtual:lunora/worker",me=(e,r)=>["ts","mts","cts","js","mjs","cjs"].some(t=>b(y(e,`${r}.config.${t}`))),kr=e=>me(e,"rsbuild")?"rsbuild":me(e,"vite")?"vite":void 0,oo=e=>me(e,"vite")?"vite":kr(e),so=e=>{try{const{scripts:r}=JSON.parse(E(y(e,"package.json"),"utf8"));return typeof r?.build=="string"&&r.build!==""}catch{return!1}},se=(e,r)=>{if(process.env[wr]==="1")return;const t=O(e),n=t===void 0?void 0:R(t).parsed,o=n?.main===no,s=(o?oo(e):kr(e))??(so(e)?"script":void 0);if(s===void 0)return;const a=r===void 0?void 0:n?.env?.[r]?.assets?.directory,i=n?.assets?.directory??a;return o||Yr(e).class!=="C"||i!==void 0?s:void 0},ao=async(e,r,t)=>{const n=t.spawner??x,o=j(e),s=r==="script"?{args:["run","build"],command:o}:$e(o,r,["build"]);t.logger.info(`running ${r} build before bundling the Worker`);const a=yr(e),i=t.bundleMetaPath??to(e);Q(y(e,Xr),{force:!0});try{const c=await n({args:s.args,command:s.command,cwd:e,env:{[tt]:nt(e),[rt]:t.target,[et]:i,...t.lazyFunctions?{[Zr]:"1"}:{},...t.environment===void 0?{}:{CLOUDFLARE_ENV:t.environment},...t.strictAdvisories===!1?{[Qr]:"0"}:{},[wr]:"1"},stdoutToStderr:t.outputJson});return c.code===0?void 0:`${r} build failed with exit code ${String(c.code)}`}finally{a(),t.bundleMetaPath===void 0&&Q(i,{force:!0})}},ae=(e,r,t)=>r!==!1&&se(e,t)!==void 0,io=(e,r,t)=>ae(e,r,t)&&se(e,t)!=="script",Ee=e=>{const r=e.frameworkBuild===!1?void 0:se(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{ge(e.cwd,e.target)}catch(n){return n instanceof Error?n.message:String(n)}let t;try{t=ge(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`},br=async e=>{const r=e.frameworkBuild===!1?void 0:se(e.cwd,e.environment);if(r===void 0)return;let t;try{t=e.target??ge(e.cwd)}catch(n){return n instanceof Error?n.message:String(n)}return ao(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})},Be=e=>Array.isArray(e)?e.filter(r=>r!=null):void 0,Ae=(e,r)=>{const t=O(e);if(!t)return;const{parsed:n}=R(t);if(n===void 0)return;const{error:o,merged:s}=oe(n,r),a=o===void 0?s:n,{containers:i,d1_databases:c,vars:l}=a;return{containers:Be(i),d1_databases:Be(c),vars:typeof l=="object"&&l!==null&&!Array.isArray(l)?l:void 0}},co=/^127(?:\.\d{1,3}){3}$/,lo=e=>{try{const{hostname:r}=new URL(e);return r==="localhost"||co.test(r)||r==="::1"||r==="[::1]"}catch{return!1}},uo=e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"),fo=(e,r,t,n="deploy",o)=>{const s=(Ae(e,o)?.containers??[]).filter(i=>typeof i?.image=="string"&&uo(i.image));if(s.length===0||t())return;const a=`${n} blocked: wrangler.jsonc declares ${String(s.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(a),a},Re=e=>b($(e,Ce))?Ce:void 0,go=(e,r,t="deploy",n)=>{for(const o of Ze(e,"lunora",n).containers){const s=o.schedulingPolicy===void 0?o.image:void 0,i=[...s?.kind==="dockerfile"?[{field:"image",path:s.dockerfilePath}]:[],...Object.entries(o.schedulingPolicy==="durable_object"?o.images??{}:{}).flatMap(([c,l])=>l.kind==="dockerfile"?[{field:`images["${c}"]`,path:l.dockerfilePath}]:[])].find(c=>!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(s?.kind==="build"&&!b($(e,s.buildDir))){const c=`${t} blocked: container "${o.exportName}" references a Railpack build directory "${s.buildDir}" that does not exist. Create it or fix the \`image.build\` path in lunora/containers.ts.`;return r.error(c),c}}},ho=(e,r)=>r==="celld"?typeof e=="string"&&e!==Ie&&jt(e):r==="cloudflare"&&e===Ie,mo=(e,r,t)=>(Ae(e,t)?.d1_databases??[]).find(n=>ho(n.database_id,r)),vo=e=>{if(!e.migrate||e.dryRun)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}},po=(e,r,t,n,o)=>{const s=mo(e,n,o);if(s===void 0)return;const a=`${t} blocked: the "${s.binding??"<unnamed>"}" D1 binding has a placeholder database_id ("${s.database_id??""}")`,i=n==="celld"?`${a}, which celld would use as the database's identity. Set database_id to the database celld should use, then ${t} again.`:`${a}. 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},yo=(e,r,t="deploy",n)=>{const o=Ae(e,n)?.vars;if(!o)return;const s=Object.entries(o).filter(([,i])=>typeof i=="string"&&lo(i)).map(([i])=>i).toSorted((i,c)=>i.localeCompare(c));if(s.length===0)return;const a=`${t} blocked: ${s.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(a),a},wo=["vite.config.ts","vite.config.mts","vite.config.cts","vite.config.js","vite.config.mjs","vite.config.cjs",...Vr],$r=/\.(?:[cm]?[jt]s|tsx|jsx)$/u,Sr=/\.(?:test|spec)\.[cm]?[jt]sx?$/u,Er="allowUnauthenticatedShardAccess",ko=/[\\/]/u,Ar=new Set(["_generated","build","dist","node_modules"]),Rr=(e,r)=>{const t=W(e,r).split(ko);return $r.test(r)&&!Sr.test(r)&&!fe(t.join("/"))&&t.every(n=>n===".."||!n.startsWith(".")&&!Ar.has(n))},He=(e,r,t)=>{const{parsed:n}=R(r);if(n===void 0)return[];const{error:o,merged:s}=oe(n,t),{main:a}=o===void 0?s:n,i=typeof a=="string"?$(ir(r),a):void 0;return i!==void 0&&b(i)&&Rr(e,i)?[i]:[]},Te=e=>e===void 0?!1:e.getKind()===p.FalseKeyword?!0:k.isParenthesizedExpression(e)||k.isAsExpression(e)||k.isSatisfiesExpression(e)||k.isTypeAssertion(e)||k.isNonNullExpression(e)?Te(e.getExpression()):!1,bo=e=>{try{return Qe(e).isFile()}catch{return!1}},$o=new Set(["ELOOP","ENOENT","ENOTDIR"]),ee=(e,r,t)=>{const n=r instanceof Error&&"code"in r&&typeof r.code=="string"?r.code:"";$o.has(n)||t.push(e)},So=(e,r)=>{try{return Qe(e)}catch(t){ee(e,t,r);return}},Tr=(e,r)=>{try{return E(e,"utf8")}catch(t){ee(e,t,r);return}},Pr=(e,r,t,n=new Set)=>{let o;try{o=Wr(r)}catch(a){return ee(r,a,t),[]}if(n.has(o))return[];n.add(o);let s;try{s=ve(r)}catch(a){return ee(r,a,t),[]}return s.flatMap(a=>{const i=$(r,a),c=So(i,t);if(c===void 0)return[];const l=W(e,i).split(B).join("/");return c.isDirectory()?Ar.has(a)||a.startsWith(".")||fe(`${l}/`)?[]:Pr(e,i,t,n):c.isFile()&&$r.test(a)&&!Sr.test(a)&&!fe(l)?[i]:[]})},Eo=e=>{const r=k.isComputedPropertyName(e)?e.getExpression():e;return k.isStringLiteral(r)||k.isNoSubstitutionTemplateLiteral(r)?r.getLiteralValue():e.getText()},le=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],Ao=/\.(?:[cm]?js|jsx)$/u,Ro=(e,r)=>{if(!r.startsWith("."))return;const t=N(ir(e),r),n=t.replace(Ao,"");return[t,...le.map(s=>`${t}${s}`),...le.map(s=>$(t,`index${s}`)),...le.map(s=>`${n}${s}`)].find(s=>bo(s))},To=e=>{if(e.getExpression().getText()!=="require")return;const[r]=e.getArguments();return r!==void 0&&(k.isStringLiteral(r)||k.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},Po=e=>{const r=e.getModuleReference();if(!k.isExternalModuleReference(r))return;const t=r.getExpression();return k.isStringLiteral(t)?t.getLiteralValue():void 0},_o=(e,r,t,n)=>{const o=new Set(e),s=[...e],a=[];for(let i=0;i<s.length;i+=1){const c=s[i]??"",l=Tr(c,n);if(l===void 0)continue;const d=r.createSourceFile(W(t,c),l,{overwrite:!0}),f=[...d.getImportDeclarations().map(u=>u.getModuleSpecifierValue()),...d.getExportDeclarations().map(u=>u.getModuleSpecifierValue()),...d.getDescendantsOfKind(p.ImportEqualsDeclaration).map(u=>Po(u)),...d.getDescendantsOfKind(p.CallExpression).map(u=>To(u))].filter(u=>u!==void 0);for(const u of f){const h=Ro(c,u);h!==void 0&&Rr(t,h)&&!o.has(h)&&(o.add(h),a.push(h),s.push(h))}}return a},Do=e=>{const r=e.getArgumentExpression();return r!==void 0&&(k.isStringLiteral(r)||k.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},Co=e=>k.isPropertyAccessExpression(e)?e.getName():k.isElementAccessExpression(e)?Do(e):void 0,Io=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]),Oo=e=>{const r=e.getOperatorToken().getKind();return!Io.has(r)||Co(e.getLeft())!==Er?!1:r!==p.EqualsToken||!Te(e.getRight())},No=(e,r,t)=>{const n=[],o=[...new Set([I(e),"src"])].filter(f=>b($(e,f))),s=O(e),a=[...wo.map(f=>$(e,f)).filter(f=>b(f)),...s===void 0?[]:He(e,s,r),...t.flatMap(f=>He(e,f,r))],i=new cr({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}),c=o.flatMap(f=>Pr($(e,f),$(e,f),n));return{sites:[...new Set([...c,...a,..._o([...a,...c],i,e,n)])].flatMap(f=>{const u=Tr(f,n);if(u===void 0)return[];const h=i.createSourceFile(W(e,f),u,{overwrite:!0}),g=[...h.getDescendantsOfKind(p.PropertyAssignment),...h.getDescendantsOfKind(p.ShorthandPropertyAssignment),...h.getDescendantsOfKind(p.GetAccessor),...h.getDescendantsOfKind(p.MethodDeclaration)].filter(m=>{const T=k.isPropertyAssignment(m)&&Te(m.getInitializer());return Eo(m.getNameNode())===Er&&!T}).map(m=>m.getStartLineNumber()),v=h.getDescendantsOfKind(p.BinaryExpression).filter(m=>Oo(m)).map(m=>m.getStartLineNumber());return[...g,...v].map(m=>({file:W(e,f),line:m}))}),unreadable:n}},jo=(e,r,t,n,o,s)=>{if(t!=="deploy")return;const{sites:a,unreadable:i}=No(e,o,s),c=tn({openShardAccess:a,schema:{tables:[]}},{lints:[Oe]});if(c.length===0&&i.length===0)return;const l=[];if(c.length>0){const f=c.map(u=>`${String(u.metadata.file)}:${String(u.metadata.line)}`).join(", ");l.push(`${f} enable the open-shard option (any value but a literal false), so any caller may target any shard.`)}if(i.length>0&&l.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): ${l.join(" ")}`);return}const d=`deploy blocked (open_shard_access): ${l.join(" ")} ${Oe.remediation}`;return r.error(d),d},Lo=(e,r,t,n)=>{const o=jo(e,r.logger,t,r.allowOpenShards===!0,r.env,n);return o===void 0?void 0:{code:w.USAGE,error:o}},Mo=(e,r,t,n)=>{const o=po(e,r.logger,t,n,r.env);if(o!==void 0)return{code:w.USAGE,error:o};const s=yo(e,r.logger,t,r.env);if(s!==void 0)return{code:w.USAGE,error:s};const a=go(e,r.logger,t,r.discoveryCache);if(a!==void 0)return{code:w.USAGE,error:a};const i=fo(e,r.logger,r.dockerAvailable??Jt,t,r.env);return i===void 0?void 0:{code:w.MISSING_DEPENDENCY,error:i}},xo=/[^a-z0-9-]/gu,Fo=/-$/u,We=7,Uo=(e,r)=>{const t=e.toLowerCase(),n=t.replaceAll(xo,"-");if(n===t&&n.length<=r)return n;const o=Gt("sha256").update(t).digest("hex").slice(0,We-1);return`${n.slice(0,r-We).replace(Fo,"")}-${o}`},Bo=32,_r=15e3,Ho=5432,Wo=3306,Go=/[^A-Za-z0-9]/gu,G=e=>`LUNORA_${e.replaceAll(Go,"_").toUpperCase()}_URL`,Vo=e=>{const r=new Map;for(const t of e){const n=G(t),o=r.get(n);if(o!==void 0)return{bindings:[o,t],variable:n};r.set(n,t)}},qo=(e,r)=>Uo(`${e}-${r}`,Bo),Ge=e=>e==="postgresql"?"postgres":e==="mariadb"?"mysql":e,Ko=e=>e==="mysql"?Wo:Ho,zo=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===""?Ko(Ge(t)):Number(r.port),scheme:Ge(t),user:decodeURIComponent(r.username)}}catch{return}},Jo=(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 s of n)o=o.replaceAll(s,"<redacted>");return o.split(" ").map(s=>s.includes("://")?"<url>":s).join(" ")},Dr=e=>(Array.isArray(e)?e:[]).flatMap((r,t)=>{const{binding:n,id:o}=typeof r=="object"&&r!==null?r:{};return typeof n=="string"&&o===nr?[{binding:n,index:t}]:[]}),re=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}`},Yo=e=>typeof e=="string"||typeof e=="number"?e.toString():void 0,Xo=["scheme","host","port","database","user"],Qo=e=>e==="postgresql"?"postgres":e,Ve=(e,r)=>{const t=Yo(r);return e==="scheme"?Qo(t):t},qe=50,Zo=async(e,r)=>{for(let t=1;t<=qe;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 (${re(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(a=>a.name===r),s=typeof n.body.result_info=="object"&&n.body.result_info!==null?n.body.result_info:{};if(o!==void 0||typeof s.total_pages!="number"||t>=s.total_pages)return o}throw new Error(`the listing of Hyperdrive configs has more than ${String(qe)} pages, so "${r}" can't be shown to be absent`)},es=async(e,r,t,n)=>{const o=n?{caching:{disabled:!0}}:{},s=await Zo(e,r);if(typeof s?.id=="string"){const c=Xo.filter(d=>Ve(d,s.origin?.[d])!==Ve(d,t[d]));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 l=await e(`/hyperdrive/configs/${encodeURIComponent(s.id)}`,{body:JSON.stringify({origin:t,...o}),method:"PATCH"});if(!l.ok)throw new Error(`updating its credentials failed (${re(l)})`);return{id:s.id,reused:!0}}const a=await e("/hyperdrive/configs",{body:JSON.stringify({name:r,origin:t,...o}),method:"POST"});if(!a.ok)throw new Error(`creating it failed (${re(a)})`);const{id:i}=typeof a.body.result=="object"&&a.body.result!==null?a.body.result:{};if(typeof i!="string")throw new TypeError("the response carried no id");return{id:i,reused:!1}},rs=(e,r,t,n)=>r===void 0&&n?`${G(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 ${G(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.`,ts=async(e,r)=>{const t=qo(e.workerName,e.binding),{id:n,reused:o}=await es(async(s,a)=>lr({accountId:e.accountId,apiToken:e.token,...e.fetch===void 0?{}:{fetch:e.fetch},init:{...a,signal:AbortSignal.timeout(_r)},path:s}),t,e.origin,e.disableCaching);return e.logger.success(`${o?"reusing":"created"} Hyperdrive config "${t}" for ${e.binding} → ${e.wranglerPath}`),{id:n,text:or(r,[...e.path,e.index,"id"],n)}},ns=e=>e===void 0||e===""?void 0:e,Cr=e=>{const r=y(U(e),".wrangler","deploy","config.json");try{const{configPath:t}=JSON.parse(E(r,"utf8"));return typeof t=="string"?N(U(r),t):void 0}catch{return}},os=(e,r,t,n,o)=>{const s=Cr(e);if(s===void 0||s===e)return;if(n.built!==n.deployed){o.warn(`the build output ${s} 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 a;try{a=R(s)}catch{return}const i=Dr(a.parsed?.hyperdrive).find(c=>c.binding===r);i!==void 0&&V(s,or(a.text,["hyperdrive",i.index,"id"],t),"utf8")},ss=(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}`},Pe=(e,r)=>{const t=O(e),n=t===void 0?void 0:R(t).parsed;if(t===void 0||n===void 0)return;const o=r===void 0?void 0:n.env?.[r],s=Dr(r===void 0?n.hyperdrive:o?.hyperdrive);return s.length===0?void 0:{accountId:o?.account_id??n.account_id,entries:s,path:r===void 0?["hyperdrive"]:["env",r,"hyperdrive"],workerName:ss(n,r),wranglerPath:t}},as=(e,r,t)=>{const n=Vo(e.map(({binding:o})=>o));if(n!==void 0){const o=`deploy blocked: the Hyperdrive bindings ${n.bindings.map(s=>`"${s}"`).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:s,supplied:a}of e){const i=rs(o,s,r,a);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}}},is=async(e,r,t,n)=>{let o;try{o=await e(`/hyperdrive/configs/${encodeURIComponent(t)}`)}catch(a){n.warn(`could not check whether the "${r}" Hyperdrive config has query caching off (${a instanceof Error?a.message:String(a)}).`);return}if(!o.ok){n.warn(`could not check whether the "${r}" Hyperdrive config has query caching off (${re(o)}).`);return}const{caching:s}=typeof o.body.result=="object"&&o.body.result!==null?o.body.result:{};s?.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\`.`)},cs=async(e,r)=>{const t=O(e.cwd),n=t===void 0?void 0:R(t).parsed,o=e.wranglerEnvironment===void 0?n:n?.env?.[e.wranglerEnvironment],{accountId:s,token:a}=dr(r,o?.account_id??n?.account_id);if(s===void 0||a===void 0)return;const i=async(c,l)=>lr({accountId:s,apiToken:a,...e.fetch===void 0?{}:{fetch:e.fetch},init:{...l,signal:AbortSignal.timeout(_r)},path:c});for(const c of Array.isArray(o?.hyperdrive)?o.hyperdrive:[]){const{binding:l,id:d}=typeof c=="object"&&c!==null?c:{};typeof l=="string"&&typeof d=="string"&&d!==nr&&await is(i,l,d,e.logger)}},ds=async e=>{const r=e.environment??process.env;e.disableCaching===!0&&e.checkOnly!==!0&&e.dryRun!==!0&&await cs(e,r);const t=Pe(e.cwd,e.wranglerEnvironment);if(t===void 0)return;const{entries:n,path:o,wranglerPath:s}=t,{accountId:a,token:i}=dr(r,t.accountId),c=n.map(({binding:d})=>{const f=r[G(d)]??"";return{binding:d,origin:zo(f),supplied:f!==""}}),l=as(c,i!==void 0&&a!==void 0,e);if(l!==void 0)return l;if(!(e.dryRun===!0||e.checkOnly===!0))for(const[d,{binding:f,index:u}]of n.entries()){const h=c[d]?.origin;if(!(h===void 0||i===void 0||a===void 0))try{const{id:g,text:v}=await ts({accountId:a,binding:f,disableCaching:e.disableCaching===!0,fetch:e.fetch,index:u,logger:e.logger,origin:h,path:o,token:i,workerName:t.workerName,wranglerPath:s},E(s,"utf8"));V(s,v,"utf8"),os(s,f,g,{built:ns(r.CLOUDFLARE_ENV),deployed:e.wranglerEnvironment},e.logger)}catch(g){const v=g instanceof Error?g.message:String(g),m=`deploy blocked: the "${f}" Hyperdrive config could not be set up: ${Jo(v,c[d]?.origin)}`;return e.logger.error(m),m}}},ls=(e,r)=>{const t=Pe(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 ${G(t)} set to create the config, or put the id from \`wrangler hyperdrive create\` in wrangler.jsonc.`;return r.logger.error(n),n},us=(e,r)=>{const t=Pe(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},Ir=async(e,r,t,n,o="create")=>{if(n!=="cloudflare")return;if(t==="prepare")return ls(e,r);if(r.temporary===!0)return us(e,r);const s=r.clientBuildEnvironment===void 0?void 0:{...process.env,CLOUDFLARE_ENV:r.clientBuildEnvironment},a=we(e,I(e),r.discoveryCache);return a.error!==void 0&&r.logger.warn(`could not read the schema (${a.error}), so Hyperdrive configs are set up with query caching off.`),ds({checkOnly:o==="check",cwd:e,disableCaching:a.error!==void 0||a.info?.hasHyperdriveGlobalTable===!0,dryRun:r.dryRun,environment:s,logger:r.logger,wranglerEnvironment:r.env})},fs=/https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u,gs=/https:\/\/[^\s"'<>]+/u,hs=e=>{if(e===void 0)return;const r=fs.exec(e);return r?r[0]:gs.exec(e)?.[0]},Ke=e=>e===void 0?"":` (--env ${e})`,ms=({cwd:e,env:r,logger:t,now:n,url:o})=>{if(o!==void 0)try{const s=ye(e);if(s!==void 0){if(s.workerUrl===o&&s.env===r)return;t.warn(`link: .lunora/project.json records ${s.workerUrl??"(no url)"}${Ke(s.env)}, but this deploy published ${o}${Ke(r)}. Keeping the recorded value — run \`lunora link --url ${o}${r===void 0?"":` --env ${r}`}\` to update it.`);return}const a=(n??(()=>new Date().toISOString()))();ot(e,{env:r,linkedAt:a,workerName:be(e),workerUrl:o}),t.success(`link: recorded ${o} in .lunora/project.json (run \`lunora link\` to change)`)}catch{}},vs=async(e,r)=>{const t=new cr({skipAddingFilesFromTsConfig:!0}),n=$(r,"lunora");let o;try{o=qr(t,n)}catch(s){const a=s instanceof Error?s.message:String(s);return e.logger.warn(`--migrate: could not discover migrations (${a}); 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 s of o){e.logger.info(`--migrate: up "${s.id}" (table "${s.table}")`);const a={cwd:r,fetchImpl:e.fetchImpl,id:s.id,logger:e.logger,prod:!0,subcommand:"up",token:e.migrateToken,url:e.migrateUrl,yes:e.migrateYes===!0},i=await nn(a);if(i.code!==0)return e.logger.error(`--migrate: migration "${s.id}" failed — see output above`),i.code;e.logger.success(`--migrate: "${s.id}" applied`)}return 0},ps=async(e,r)=>{const{info:t}=we(r,"lunora",e.discoveryCache),n=t?.vectorMetadata??[];if(n.length===0)return;const o=[];for(const i of n){const c=Lt(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 a=(await Mt({cwd:r,entries:o,exec:$e(j(r),"wrangler",[]),logger:e.logger,spawner:e.spawner??x})).filter(i=>i.status!=="failed").length;a>0&&e.logger.success(`vectorize metadata indexes ready: ${String(a)}/${String(o.length)}`)},ze=5,ys=2e3,ws=async(e,r,t)=>{if(e.healthCheck!==!0)return;const n=t??Se({cwd:r,env:e.env});if(n===void 0){const s="--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(s),{error:s,ok:!1,url:""}}const o=await Yt({attempts:ze,baseUrl:n,delayMs:ys,fetchImpl:e.healthFetch,paths:[Xt,Qt],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(ze)} attempt(s) — ${o.error}`),{error:o.error,ok:!1,url:o.url})},ks=async(e,r,t,n,o,s)=>{e.isolatedPreview!==!0&&await ps(e,r);const a=e.migrate?await vs(e,r):0;return a===0&&o?.(),{code:a,descriptor:t,mintedSecretsFile:s,validation:n}},bs=async({cwd:e,descriptor:r,mintedSecretsFile:t,options:n,reblessSchemaBaseline:o,recordArchitecture:s,stdout:a,validation:i})=>{const c={deployedAt:new Date().toISOString(),dryRun:n.dryRun===!0,env:n.env,url:n.dryRun===!0?void 0:hs(a),workerName:be(e)};if(n.dryRun===!0)return n.healthCheck===!0&&n.logger.warn("--health-check skipped: a dry run publishes nothing"),{code:0,deployment:c,descriptor:r,mintedSecretsFile:t,validation:i};n.temporary!==!0&&n.isolatedPreview!==!0&&(s?.(),ms({cwd:e,env:n.env,logger:n.logger,url:c.url}));const l=await ws(n,e,c.url);if(l?.error!==void 0)return{code:w.UNAVAILABLE,deployment:c,descriptor:r,healthCheck:l,mintedSecretsFile:t,validation:i};const d=n.isolatedPreview===!0?void 0:o;return{...await ks(n,e,r,i,d,t),deployment:c,healthCheck:l}},$s=(e,r,t)=>{const n=$(e,C);if(!b(n))return;let o;try{o=er(E(n,"utf8")).length}catch{return}if(o===0)return;const s=t.toolchain?.secretPut!==void 0;r.warn(s?`Note: \`lunora deploy\` does not push secrets. ${C} 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. ${C} 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.`)},Or=async(e,r)=>{let t=[];try{t=st(await rr({cache:r,projectRoot:e,schemaDir:I(e)}))}catch{}const n=[...new Set(at(t).map(s=>s.key))];let o=[];try{const s=$(e,C);b(s)&&(o=er(E(s,"utf8")).map(a=>a.key).filter(a=>sr(a)))}catch{}return{fromLocal:o.filter(s=>!n.includes(s)),fromPackages:n,mintableKeys:it(t)}},Ss=async(e,r,t,n)=>{const{logger:o}=r,s=r.spawner??x,a=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 l=t.map(u=>({key:u,value:ct()})),d=n.toolchain?.secretBulk;if(d!==void 0&&l.length>=2){const u=H(a,d({environment:r.env,temporary:r.temporary})),h=await s({args:u.args,command:u.command,cwd:e,input:JSON.stringify(Object.fromEntries(l.map(g=>[g.key,g.value])))});if(h.code===0){for(const{key:g}of l)o.success(`generated + pushed ${g}`);return{minted:l,ok:!0}}o.warn(`bulk secret push failed (exit ${String(h.code)}); retrying one key at a time`)}const f=[];for(const{key:u,value:h}of l){const g=c({environment:r.env,key:u,temporary:r.temporary}),v=H(a,g),m=await s({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:f,ok:!1};f.push({key:u,value:h}),o.success(`generated + pushed ${u}`)}return{minted:f,ok:!0}},Es=/^[\w-]+$/u,Je=[".dev.vars",".dev.vars.*","!.dev.vars.example"],As=(e,r)=>{try{const t=ft(e,Je);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 \`${Je.join("` and `")}\` by hand before committing.`)}},Rs=(e,r,t)=>{if(t.length===0)return;const n=t.map(i=>i.key).join(", ");if(r.env!==void 0&&!Es.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?C:`${C}.${r.env}`;As(e,r.logger);const s=$(e,o);let a=b(s)?E(s,"utf8"):"";for(const i of t)a=dt(a,i.key,i.value);return lt(s,a),r.logger.success(r.env===void 0?`${n}: value(s) recorded in ${o}`:`${n}: value(s) recorded in ${o} (kept separate from ${C} so \`lunora dev\` and a plain \`lunora env push\` don't inherit the --env ${r.env} value)`),o},Ts=/^<[^>]+>$/u,Ps=async(e,r,t)=>{let n;try{n=t.projectConfig?.(e,"deploy").vars??{}}catch(d){return{error:d instanceof Error?d.message:String(d)}}const o=d=>{const f=n[d];if(typeof f!="string")return!0;const u=f.trim();return u===""||Ts.test(u)?!0:sr(d)&&ut(f)},s=d=>Object.hasOwn(n,d)?`${d} (empty or a placeholder)`:d,{fromLocal:a,fromPackages:i}=await Or(e,r.discoveryCache),c=a.filter(d=>o(d));c.length>0&&r.logger.warn(`${C} key(s) not set in the wrangler vars: ${c.map(d=>s(d)).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 l=i.filter(d=>o(d));return l.length===0?{}:{error:`missing required secret(s) in the wrangler vars: ${l.map(d=>s(d)).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.`}},_s=async(e,r,t,n)=>{if(r.dryRun===!0||r.isolatedPreview===!0)return{};if(n.toolchain?.secretList===void 0)return Ps(e,r,n);const{logger:o}=r,s=r.env===void 0?"":` --env ${r.env}`;let a;try{a=await(r.secretLister??sn)({cwd:e,env:r.env,target:n.id,temporary:r.temporary})}catch{return{}}if(!a.ok)return{};const i=new Set(a.names),{fromLocal:c,fromPackages:l,mintableKeys:d}=await Or(e,r.discoveryCache),f=[...l,...c].filter(g=>!i.has(g));if(f.length===0)return{};if(!t)return{error:`missing required secret(s) on the deploy target: ${f.join(", ")}. Set them with \`wrangler secret put <KEY>${s}\` (or \`lunora env generate --set\` then \`lunora env push --yes${s}\`), then re-deploy.`};for(const g of f.filter(v=>!d.has(v)))o.warn(`required secret ${g} is not set on the target — set it with: wrangler secret put ${g}${s}`);const u=f.filter(g=>d.has(g));if(u.length===0)return{};if(await(r.secretConfirm??on())(`${String(u.length)} required secret(s) not set on the target (${u.join(", ")}). Generate strong values and push them now?`)){const{minted:g,ok:v}=await Ss(e,r,u,n),m=Rs(e,r,g);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${s}\`.`),{}},Nr=e=>e.format==="json"?!1:e.interactive!==void 0?e.interactive:process.stdout.isTTY&&!process.env.CI,Ds=async(e,r)=>{if(r.dryRun===!0)return;const t=Ze(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 Un({cwd:e,logger:r.logger,railpackAvailable:r.railpackAvailable,spawner:r.spawner,targets:t});return n.code===0?void 0:n.error??"railpack build failed"},Cs=(e,r,t)=>{if(t!==void 0)try{const n=At(e,t);n.changed&&r.success(`synced ${String(t.length)} cron trigger(s) → ${n.wranglerPath??"wrangler.jsonc"}`);for(const s of n.warnings)r.warn(s);const o=Rt(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}`)}},Is=async(e,r,t,n,o,s)=>{try{ne(n);const a=await rr({cache:s,projectRoot:e,schemaDir:I(e)}),i=St(e,a,{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:l,path:d,updated:f}=i.devConfig;r.success(`dev sidecar bindings: ${[...l,...f].join(", ")} → ${d}`)}for(const l of i.warnings)r.warn(l)}catch(a){const i=a instanceof Error?a.message:String(a);r.warn(`binding inference skipped: ${i}`)}try{const a=Et(e);a.changed&&r.success(`bumped compatibility_date to ${a.date??"unknown"} (Workers Cache enabled) → ${a.wranglerPath??"wrangler.jsonc"}`)}catch(a){const i=a instanceof Error?a.message:String(a);r.warn(`compatibility date sync skipped: ${i}`)}Cs(e,r,t)},Os=async(e,r,t,n,o,s,a,i,c,l)=>{let d;r?(d=new Tt({name:"dots"}),d.start("running codegen")):t.info("running codegen");try{const f=Kr({apiSpec:n,dryRun:!l,lazyFunctions:o,projectRoot:e,target:s,...$t(e)});d?.succeed("codegen complete"),d||t.success("codegen complete");const u=It(f.platformDiagnostics,t);if(u.errors.length>0)return{error:u.errors.join("; ")};const{errorAdvisories:h,names:g,shouldBlock:v}=Ot(f.advisories,c);if(v){const T=`${h.length.toString()} ERROR-level ${h.length===1?"advisory":"advisories"} (${g.join(", ")}). Pass --no-strict-advisories to downgrade this to a warning and continue.`;return t.error(T),{error:T}}const m=l?await pt({cwd:e,logger:t,spawner:a,stdoutToStderr:i}):void 0;return m?.error!==void 0?{error:m.error}:{result:f}}catch(f){d?.failed("codegen failed");const u=f instanceof Error?f.message:String(f);return t.error(`codegen failed: ${u}`),{error:`codegen failed: ${u}`}}},Ye="--preview is not supported: Cloudflare gives a Worker that implements a Durable Object no version preview URL, and a version shares production's Durable Objects, D1 and R2. Deploy an isolated copy with `lunora preview deploy <name>` (its own Worker, Durable Object namespace, D1, R2 and KV; `lunora preview delete <name>` removes it), or validate without publishing with `--dry-run`.",Ns=(e,r)=>({dryRun:r.dryRun,entry:Re(e),environment:r.env,outDir:r.outDir,secretsFile:r.secretsFile,temporary:r.temporary}),jr=(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=Ns(e,r);return tr(t,e,"deploy",s=>n.deploy({...o,configPath:s}))},js=(e,r,t)=>{const n=jr(e,r,t),o=Re(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},A={problems:[],wranglerPath:void 0},ue=(e,r)=>({code:w.USAGE,descriptor:void 0,error:e,validation:A,...r}),Ls=(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},Ms=(e,r,t)=>{const n=r.format==="json",o=r.dryRun!==!0,s=js(e,r,t),a=H(j(e),s);return{args:a.args,captureStdout:o&&!n,captureStdoutSilently:o&&n,command:a.command,cwd:e,stdoutToStderr:n&&!o}},_e=e=>{if(e.skipServices===!0)return"--skip-services";if(e.isolatedPreview===!0)return"a preview never deploys services: they are production's Workers";if(e.temporary===!0)return"--temporary deploys the app to a throwaway account"},xs=(e,r)=>_e(r)===void 0?pe(e).services.map(t=>t.wranglerPath):[],Lr=(e,r,t,n,o)=>({cwd:e,environment:r.env,frameworkBuild:n,lazyFunctions:te(r.lazyFunctions),logger:r.logger,outputJson:r.format==="json"||r.clientBuildOutputJson===!0,spawner:o,strictAdvisories:ke(r),target:t.id}),Fs=(e,r,t)=>{const{toolchain:n}=t,o=n===void 0?`target "${t.id}" has no deploy command`:_e(r);if(o!==void 0||n===void 0){const s=e.map(a=>a.worker).join(", ");r.logger.warn(`services not deployed (${o??""}): ${s} — deploy them yourself if the app calls anything new`);return}return n},Mr=(e,r)=>{for(const t of e){const n=Ee(r(U(t.wranglerPath)));if(n!==void 0)return`service ${t.name} (${t.worker}): ${n}`}},Us=(e,r,t)=>{const{error:n,services:o}=pe(e);if(n!==void 0||o.length===0)return;const s=ne(t);if(s.toolchain===void 0||_e(r)!==void 0)return;const a=r.skipCodegen===!0?!1:r.frameworkBuild,i=[...new Map(o.map(c=>[c.wranglerPath,c])).values()];return Mr(i,c=>Lr(c,r,s,a,x))},xr=(e,r,t)=>{const n=e.cwd??process.cwd(),o=Ht(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:A}}if(e.preview===!0)return e.logger.error(Ye),{kind:"refused",code:w.USAGE,error:Ye,validation:A};try{jr(n,e,ne(o.target))}catch(i){if(!(t&&i instanceof gt&&ae(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:A}}}const s=e.openShardGatePassed===!0?void 0:Lo(n,e,r,xs(n,e));if(s!==void 0)return{kind:"refused",code:s.code,error:s.error,validation:A};const a=Us(n,e,o.target);return a!==void 0?(e.logger.error(a),{kind:"refused",code:w.USAGE,error:a,validation:A}):{kind:"ok",target:o.target}},Bs=(e,r)=>e.apiSpec??(e.clientBuildRan===!0?yt(r):void 0),Hs=async(e,r,t)=>{if(r!=="celld")return;const n=await(e.celldToolchain??vt)({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},Fr=(e,r)=>{const t=Se({cwd:e,env:r.env,url:r.migrateUrl}),n=t===void 0?void 0:ro(e,r.env,t);if(n!==void 0)return{reason:n};const o=t===void 0?void 0:Dt(t,r.logger,e),s=o===void 0?void 0:Pt({cwd:e,token:r.migrateToken,url:o}).token;return{target:o===void 0||!s?void 0:{baseUrl:o,fetchImpl:r.fetchImpl??Ct,token:s}}},Ws=(e,r,t)=>async n=>{const o=Fr(e,r);return"reason"in o?{kind:"inconclusive",reason:o.reason}:rn({changes:n,tables:t.schemaTables,target:o.target})},Gs=(e,r)=>async t=>{const n=Fr(e,r);return"reason"in n?n.reason:en({changes:t,now:Date.now(),target:n.target})},Vs=(e,r,t,n)=>e==="deploy"?{checkStoredRows:Ws(r,t,n),countExpiringRows:Gs(r,t)}:{},qs=async(e,r)=>{const t=e.cwd??process.cwd(),n=Nr(e),o=ke(e),s={problems:[],wranglerPath:void 0},a=xr(e,r,!1);if(a.kind==="refused")return{code:a.code,error:a.error,validation:a.validation};const{target:i}=a,c=await Hs(e,i,r);if(c!==void 0)return e.logger.error(c),{code:w.MISSING_DEPENDENCY,error:c,target:i,validation:s};let l;if(!e.skipCodegen){const v=await Os(t,n,e.logger,Bs(e,t),te(e.lazyFunctions),i,e.spawner,e.format==="json",o,e.clientBuildRan!==!0);if(v.error!==void 0)return{error:v.error,target:i,validation:A};l=v.result,e.discoveryCache?.clear()}let d;if(l!==void 0){const v=await Zt({allowDrift:e.allowSchemaDrift===!0,...Vs(r,t,e,l),codegen:l,command:r,logger:e.logger});if(v.blocked)return{error:`schema drift gate blocked ${r}`,schemaDrift:{blocked:!0,reason:v.reason},target:i,validation:s};d=v.rebless}const f=l&&gn({current:l.architecture,cwd:t,environment:e.env,logger:e.logger});await Is(t,e.logger,l?.cronTriggers,i,e.env,e.discoveryCache);const u=await Ir(t,e,r,i,"check");if(u!==void 0)return{error:u,target:i,validation:A};const h=Mo(t,e,r,i);if(h!==void 0)return{code:h.code,error:h.error,target:i,validation:A};const g=bt({environment:e.env,projectRoot:t});return Ls(g,e.logger)?{error:"wrangler validation failed",target:i,validation:g}:{codegen:l,reblessSchemaBaseline:d,recordArchitecture:f,target:i,validation:g}},Ks=e=>{Q(y(e,".wrangler","deploy","config.json"),{force:!0})},zs=async(e,r,t)=>{const n=Ee(e);if(n!==void 0)return{built:!1,error:n};const o=ae(e.cwd,r,t);return o&&Ks(e.cwd),{built:o,error:await br(e)}},Js=(e,r,t)=>r||t===!1?Cr(e):void 0,Ys=async(e,r,t,n)=>{const{error:o,services:s}=pe(e);if(o!==void 0)return{code:w.FAILURE,error:o};if(s.length===0)return;const a=Fs(s,r,t);if(a===void 0)return;const i=j(e),c=[...new Map(s.map(u=>[u.wranglerPath,u])).values()],l=r.skipCodegen===!0?!1:r.frameworkBuild,d=u=>Lr(u,r,t,l,n),f=Mr(c,d);if(f!==void 0)return r.logger.error(f),{code:w.USAGE,error:f};for(const u of c){const h=U(u.wranglerPath),g=d(h),{built:v,error:m}=await zs(g,l,r.env);if(m!==void 0){const S=`service ${u.name} (${u.worker}): ${m}`;return r.logger.error(S),{code:w.FAILURE,error:S}}const T=Js(u.wranglerPath,v,l);let L;try{L=tr(t,h,"deploy",S=>a.deploy({configPath:S??T??u.wranglerPath,dryRun:r.dryRun===!0,environment:r.env}))}catch(S){return{code:w.FAILURE,error:`service ${u.name} (${u.worker}): ${S instanceof Error?S.message:String(S)}`}}L.commit();const D=H(i,L.command);r.logger.info(`deploying service ${u.name} (${u.worker}) via ${D.command} ${D.args.join(" ")}`);const P=await n({args:D.args,command:D.command,cwd:h,stdoutToStderr:r.format==="json"});if(P.code!==0)return{code:w.FAILURE,error:`service ${u.name} (${u.worker}): ${D.command} ${D.args.join(" ")} exited ${String(P.code)} — stopping before the app`}}},Xs=async(e,r,t,n)=>{if(r!=="cloudflare")return;const o=e===void 0?void 0:R(e).parsed,s=(t===void 0?void 0:o?.env?.[t]?.account_id)??o?.account_id,a=await Ft({accountId:s});(a.verdict==="near"||a.verdict==="full")&&n.warn(a.fix===void 0?a.message:`${a.message} ${a.fix}`)},Qs=e=>e.dryRun!==!0&&e.temporary!==!0,Zs=e=>e.temporary===!0?"temporary":e.dryRun===!0?"preview":"defer",ea=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},ra=(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 s=ea(o);r.error(s),n.push(s)}return n},Ur=async(e,r,t,n,o,s,a)=>{const i=t==="cloudflare"&&r!==void 0?R(r).parsed:void 0;if(i===void 0)return;const c=(oe(i,n).merged.artifacts??[]).flatMap(g=>typeof g?.binding=="string"&&typeof g.namespace=="string"?[{binding:g.binding,namespace:g.namespace}]:[]),l=c.length===0?void 0:we(e,I(e),s).info?.jurisdiction;if(l===void 0)return;const d=[...new Map(c.map(g=>[g.namespace,g])).values()];if(a==="temporary"){o.warn(`--temporary deploys to a throwaway account, so the jurisdiction ("${l}") of Artifacts namespace ${d.map(g=>`"${g.namespace}"`).join(", ")} was not checked: it is created there on first use, in no jurisdiction.`);return}const f=(n===void 0?void 0:i.env?.[n]?.account_id)??i.account_id,u=await Promise.all(d.map(async g=>xt({...g,accountId:f,create:a==="create",jurisdiction:l,missingOk:a==="defer"||a==="preview"}))),h=ra(u,o,a);return h.length===0?void 0:h.join(`
43
- `)},ta=async(e,r,t,n,o,s)=>{const a=Qs(r)?await Ur(e,s,o,r.env,r.logger,r.discoveryCache,"create"):void 0;if(a!==void 0)return{code:w.FAILURE,error:a};const i=await Ir(e,r,"deploy",o);return i!==void 0?{code:w.FAILURE,error:i}:Ys(e,r,t,n)},na=async(e,r,t,n)=>{if(!(r.smokeLoad===!1||t.toolchain===void 0))return xn({composedEntry:Re(e),configPath:n,cwd:e,environment:r.env,launcher:r.smokeLauncher,logger:r.logger,toolchain:t.toolchain})},oa=async e=>{const r={...e,discoveryCache:e.discoveryCache??mt()},t=r.cwd??process.cwd(),n=Nr(r),o=await qs(r,r.commandName??"deploy");if(o.error!==void 0){if(o.validation.problems.length>0)return{code:w.USAGE,descriptor:void 0,error:o.error,validation:o.validation};const m=o.schemaDrift===void 0?void 0:{schemaDrift:o.schemaDrift};return ue(o.error,{...m,...o.code===void 0?{}:{code:o.code}})}const{validation:s}=o,a=ne(o.target),i=vo(r)??await Ur(t,s.wranglerPath,o.target,r.env,r.logger,r.discoveryCache,Zs(r))??await na(t,r,a,s.wranglerPath);if(i!==void 0)return ue(i);const c=a.toolchain?.prebuildsContainerImages===!0?await Ds(t,r):void 0;if(c!==void 0)return ue(c);$s(t,r.logger,a),kt(t,m=>{r.logger.warn(m)}),await Xs(s.wranglerPath,o.target,r.env,r.logger);const{error:l,mintedSecretsFile:d}=await _s(t,r,n,a);if(l!==void 0)return r.logger.error(l),{code:w.USAGE,descriptor:void 0,error:l,mintedSecretsFile:d,validation:s};const f=r.spawner??x,u=await ta(t,r,a,f,o.target,s.wranglerPath);if(u!==void 0)return{code:u.code,descriptor:void 0,error:u.error,mintedSecretsFile:d,validation:s};const h=Ms(t,r,a);r.logger.info(`deploying via ${h.command} ${h.args.join(" ")}`);const g=await f(h);return h.captureStdoutSilently===!0&&g.stdout!==void 0&&g.stdout!==""&&process.stderr.write(g.stdout),g.code!==0?{code:g.code,descriptor:h,mintedSecretsFile:d,validation:s}:{...await bs({...o,cwd:t,descriptor:h,mintedSecretsFile:d,options:r,stdout:g.stdout}),logsAvailable:a.toolchain?.tail!==void 0}},sa=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:ke(e),lazyFunctions:te(e.lazyFunctions),logger:r,outputJson:e.format==="json"||e.clientBuildOutputJson===!0,spawner:e.spawner,target:e.target},o=Ee(n);if(o!==void 0)return r.error(o),{code:w.USAGE,descriptor:void 0,error:o,validation:A};ht(t);const s=await br(n);if(s!==void 0)return r.error(s),{code:w.FAILURE,descriptor:void 0,error:s,validation:A}},aa=(e,r)=>{const t=r.skipCodegen===!0?!1:r.frameworkBuild;return ae(e,t,r.env)?r.env:void 0},ia=async e=>{const{logger:r}=e,t=e.cwd??process.cwd(),n=xr(e,e.commandName??"deploy",!0);if(n.kind==="refused")return{code:n.code??w.USAGE,descriptor:void 0,error:n.error,validation:n.validation};const o=await sa(e);if(o!==void 0)return o;const s=e.dryRun===!0?yr(t):void 0;let a;try{if(a=await oa({...e,clientBuildEnvironment:aa(t,e),clientBuildRan:io(t,e.skipCodegen===!0?!1:e.frameworkBuild,e.env),logger:r,openShardGatePassed:!0}),a.code===0&&e.emitBindings!==void 0){const{error:i}=Ut({destination:e.emitBindings,logger:r,projectRoot:e.cwd??process.cwd()});i!==void 0&&(r.error(i),a={...a,code:w.USAGE})}}finally{s?.()}return e.format==="json"||a.code===0&&e.dryRun!==!0&&e.isolatedPreview!==!0&&hn({cwd:e.cwd??process.cwd(),env:e.env,logger:e.logger,logsAvailable:a.logsAvailable===!0,mintedSecretsFile:a.mintedSecretsFile,url:a.deployment?.url}),a},Ba=Bt(async({cwd:e,format:r,logger:t,options:n})=>{const o=Fn(e,n.root),s=await ia({allowOpenShards:n.allowOpenShards===!0,allowSchemaDrift:n.allowSchemaDrift===!0,apiSpec:Nt(n.apiSpec),frameworkBuild:n.prebuilt===!0?!1:n.frameworkBuild,lazyFunctions:te(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:Se({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});return{code:s.code,data:{deployment:s.deployment,healthCheck:s.healthCheck,mintedSecretsFile:s.mintedSecretsFile,schemaDrift:s.schemaDrift,validation:s.validation},error:s.error}});export{qs as a,Is as b,Uo as c,yr as d,Or as e,Ba as f,Fn as p,ia as r,na as s,to as v};
56
+ `);const g=await ln(l),{args:v,command:m}=z(F(n),d.dev({configPath:t===void 0?void 0:L(n,t),environment:i,extraArgs:[L(n,u),"--local","--local-protocol","http","--ip","127.0.0.1","--port",String(g),"--persist-to",L(n,p(s,"state"))]}));return{args:v,command:m,port:g,runId:f}}catch(u){throw new C(`could not prepare the check (${u instanceof Error?u.message:String(u)})`,!0)}},zo=async e=>{const{composedEntry:r,cwd:t,environment:n,launcher:o,logger:s,toolchain:i}=e,a=M(t),c=p(t,a,"_generated","functions.ts"),l=b(c)&&E(c,"utf8").includes("export const loadAllFunctions"),d=l?c:void 0,u=Po(t,a);if(!l&&u.length===0)return;const f=[...u,...Do(t,a,u)],h=Lo(e);if("skip"in h){s.warn(`smoke-load skipped: ${h.skip}, so lazy modules and import()ed integration modules are not evaluated before deploy`);return}const{base:g,configFile:v}=h,m=Eo(t,r??Pr(t,n,e.configPath).main,a),S=[];let D,R;const q=Date.now()+be,T=process.platform!=="win32",tt=(U,Q,Z)=>{const B=sn(U,[...Q],{cwd:Z.cwd,detached:T,shell:Z.shell,stdio:["ignore","pipe","pipe"]});return T&&B.pid!==void 0&&(R={dispose:Uo(B.pid),pid:B.pid}),B};try{D=Go(t),s.info(d===void 0?"smoke-loading import()ed integration modules in workerd":"smoke-loading lazy function modules in workerd");let U=Ao;for(let Q=0;Q<er;Q+=1){const{args:Z,command:B,port:ge,runId:nt}=await Ko({base:g,configPath:v,cwd:t,deferred:f,directory:D,environment:n,functionsFile:d,integrationModules:m,preferred:U,toolchain:i}),Be=new AbortController;U=ge+1;const We=await Bo({args:Z,command:B,cwd:t,spawn:o??tt,label:"wrangler dev (smoke-load)",notFound:"`wrangler` was not found",onLine:G=>{S.push(G),xo.test(G)&&Be.abort()},port:ge,readyTimeoutMs:Math.max(0,q-Date.now()),shell:process.platform==="win32"});if(We===void 0){await me(R),R=void 0;continue}try{const G=await Fo({deadline:q,deferred:f,functions:d!==void 0,integrationModules:m,output:S,port:ge,runId:nt,startupFailed:Be.signal});if(G!==void 0){Ho(t,G,s);return}}finally{await We.stop(),await me(R),R=void 0}}throw new C(`the smoke port was answered by other runs on all ${String(er)} attempts`,!0)}catch(U){return qo(U,S,s)}finally{if(await me(R),D!==void 0)try{oe(D,{force:!0,recursive:!0})}catch{}}},Jo=(e,r)=>r===void 0?e:I(e,r),Yo=async e=>{if(e.targets.length===0)return{builtTags:[],code:0};if(!(e.railpackAvailable??fn)()){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??H,t=[];for(const n of e.targets){const o=un(n.exportName),s={args:["build",n.buildDir,"--name",o],command:"railpack",cwd:e.cwd},i=je(F(e.cwd),"wrangler",["containers","push",o]),a={args:i.args,command:i.command,cwd:e.cwd};e.logger.info(`railpack: building "${n.exportName}" → ${o} from ${n.buildDir}`);const c=await r(s);if(c.code!==0){const d=`railpack build failed for container "${n.exportName}" (${n.buildDir})`;return e.logger.error(d),{builtTags:t,code:c.code,error:d}}e.logger.info(`railpack: pushing ${o} to the Cloudflare Registry`);const l=await r(a);if(l.code!==0){const d=`wrangler containers push failed for "${n.exportName}" (${o})`;return e.logger.error(d),{builtTags:t,code:l.code,error:d}}t.push(o)}return{builtTags:t,code:0}},Xo=new Set(["0.0.0.0","[::1]","[::]","localhost"]),Qo=[".local",".localhost"],Zo=["[fc","[fd"],es=/^\[fe[89ab][0-9a-f]:/u,rs=/^[a-z]+:\/\//u,sr=e=>{const r=e.split(".").map(Number);if(r.length!==4||r.some(o=>!Number.isInteger(o)))return!1;const[t=-1,n=-1]=r;return t===0||t===127||t===100&&n>=64&&n<=127||t===198&&(n===18||n===19)||t===10||t===192&&n===168||t===172&&n>=16&&n<=31||t===169&&n===254},ir="[::ffff:",ts=e=>{if(!e.startsWith(ir)||!e.endsWith("]"))return;const r=e.slice(ir.length,-1);if(r.includes("."))return r;const[t=0,n=0]=r.split(":").map(o=>Number.parseInt(o,16));return[Math.floor(t/256),t%256,Math.floor(n/256),n%256].join(".")},jr=e=>{let r=e.length;for(;r>0&&e[r-1]===".";)r-=1;return e.slice(0,r).toLowerCase()},ns=e=>{const r=e.toLowerCase(),t=ts(r);return t!==void 0?sr(t):Xo.has(r)||Qo.some(n=>r.endsWith(n))||Zo.some(n=>r.startsWith(n))||es.test(r)||sr(r)},Or=e=>{const r=O(e);return r===void 0?void 0:P(r).parsed},Dr=(e,r)=>{const t=typeof e?.name=="string"&&e.name!==""?e.name:void 0;if(r===void 0)return t;const n=e?.env?.[r]?.name;return typeof n=="string"&&n!==""?n:t===void 0?void 0:`${t}-${r}`},ie=(e,r)=>{let t=e.length;for(;t>0&&e[t-1]===r;)t-=1;return e.slice(0,t)},os=e=>{const r=e.replace(rs,""),t=r.indexOf("/"),n=(t===-1?r:r.slice(0,t)).toLowerCase(),o=t===-1?"":ie(r.slice(t),"*");return o==="/"?n:`${n}${o}`},ar=e=>[e?.route,...Array.isArray(e?.routes)?e.routes:[]].flatMap(t=>{const n=typeof t=="string"?t:t?.pattern;return typeof n=="string"&&n!==""?[os(n)]:[]}),ss=(e,r,t)=>{const n=t.indexOf("/"),o=n===-1?t:t.slice(0,n),s=n===-1?"":t.slice(n),i=o.startsWith("*");if(!(!(i?e.endsWith(o.slice(1)):e===o)||s!==""&&!`${ie(r,"/")}/`.startsWith(s)))return s.length*1e6+(i?0:5e5)+o.length},is=e=>e!==void 0&&(Object.hasOwn(e,"route")||Object.hasOwn(e,"routes")),Nr=(e,r)=>{const t=ar(e),o=[...new Set([...Object.keys(e?.env??{}),...r===void 0?[]:[r]])].map(s=>{const i=e?.env?.[s];return{id:`env:${s}`,label:`--env ${s}`,routes:is(i)?ar(i):t}});return[{id:"top",label:"production",routes:t},...o]},as=(e,r,t,n)=>{const o=r===void 0?"top":`env:${r}`,s=Nr(e,r).flatMap(c=>c.routes.flatMap(l=>{const d=ss(t,n,l);return d===void 0?[]:[{block:c,score:d}]}));if(s.length===0)return{kind:"none"};const i=Math.max(...s.map(c=>c.score)),a=s.filter(c=>c.score===i);return a.some(c=>c.block.id===o)?{kind:"own"}:{kind:"other",label:a[0]?.block.label??"production"}},ne=e=>Gt(`${e.origin}${e.pathname}`),cs=(e,r,t,n,o)=>{const s=_e(e),i=s?.workerUrl!==void 0&&URL.canParse(s.workerUrl)?new URL(s.workerUrl):void 0;if(i===void 0)return;if(s?.env===r)return ne(i)===ne(t)?null:`${n}: this checkout is linked to ${ne(i)}${o}`;const a=`${ie(i.pathname,"/")}/`;if(i.origin!==t.origin||!`${ie(t.pathname,"/")}/`.startsWith(a))return;const c=s?.env===void 0?"production":`--env ${s.env}`;return`${n}: this checkout links it to ${c}, not this deploy${o}`},Lr=(e,r,t,n,o,s)=>{const i=as(e,r,t,n);if(i.kind==="other")return`${o}: wrangler routes it to ${i.label}, not this deploy${s}`;if(i.kind==="own")return;const a=Nr(e,r);if(a.every(l=>l.routes.length===0))return;const c=a.find(l=>l.id===(r===void 0?"top":`env:${r}`))?.routes??[];return`${o}: this deploy${s} routes to ${c.length===0?"no declared route":c.join(", ")}, not ${t}`},ds=(e,r,t,n,o,s)=>{const i=Or(e);if(t.endsWith(".workers.dev")){const a=Dr(i,r);return a!==void 0&&t.split(".")[0]!==a?`${o}: this deploy ships the Worker "${a}"${s}`:`${o}: no link ties this *.workers.dev host to your account${s}; run \`lunora link --url https://${t}${r===void 0?"":` --env ${r}`}\` once the Worker is deployed, then deploy again (or confirm the drift yourself with --allow-schema-drift)`}return Lr(i,r,t,n,o,s)},ls=(e,r,t,n,o)=>{const s=Or(e),i=jr(t.hostname);if(i.endsWith(".workers.dev")){const a=Dr(s,r);return a===void 0||i.split(".")[0]===a?void 0:`${n}: this deploy ships the Worker "${a}", not the one the link names${o}`}return Lr(s,r,i,t.pathname,n,o)},us=(e,r,t)=>{let n;try{n=new URL(t)}catch{return`refused ${t} as the deployment to read rows from: it is not a URL`}const o=`refused ${ne(n)} as the deployment to read rows from`,s=r===void 0?"":` (--env ${r})`,i=jr(n.hostname);if(ns(i))return`${o}: it is a local or private address, not the worker this deploy ships to`;const a=cs(e,r,n,o,s);return a===void 0?ds(e,r,i,n.pathname,o,s):a??ls(e,r,n,o,s)},xr=e=>{const t=[O(e),p(e,"package.json"),p(e,"wrangler.dev.jsonc")].filter(n=>n!==void 0&&b(n)).map(n=>[n,E(n,"utf8")]);return()=>{for(const[n,o]of t)E(n,"utf8")!==o&&X(n,o,"utf8")}},fs=(e,r=$r())=>I(e,".lunora",`vite-bundle-meta-${r}.json`),Mr="LUNORA_CLIENT_BUILD",gs="virtual:lunora/worker",Ae=(e,r)=>["ts","mts","cts","js","mjs","cjs"].some(t=>b(p(e,`${r}.config.${t}`))),Fr=e=>Ae(e,"rsbuild")?"rsbuild":Ae(e,"vite")?"vite":void 0,hs=e=>Ae(e,"vite")?"vite":Fr(e),ms=e=>{try{const{scripts:r}=JSON.parse(E(p(e,"package.json"),"utf8"));return typeof r?.build=="string"&&r.build!==""}catch{return!1}},ue=(e,r)=>{if(process.env[Mr]==="1")return;const t=O(e),n=t===void 0?void 0:P(t).parsed,o=n?.main===gs,s=(o?hs(e):Fr(e))??(ms(e)?"script":void 0);if(s===void 0)return;const i=r===void 0?void 0:n?.env?.[r]?.assets?.directory,a=n?.assets?.directory??i;return o||ft(e).class!=="C"||a!==void 0?s:void 0},ps=async(e,r,t)=>{const n=t.spawner??H,o=F(e),s=r==="script"?{args:["run","build"],command:o}:je(o,r,["build"]);t.logger.info(`running ${r} build before bundling the Worker`);const i=xr(e),a=t.bundleMetaPath??fs(e);oe(p(e,gt),{force:!0});try{const c=await n({args:s.args,command:s.command,cwd:e,env:{[yt]:wt(e),[vt]:t.target,[pt]:a,...t.lazyFunctions?{[mt]:"1"}:{},...t.environment===void 0?{}:{CLOUDFLARE_ENV:t.environment},...t.strictAdvisories===!1?{[ht]:"0"}:{},[Mr]:"1"},stdoutToStderr:t.outputJson});return c.code===0?void 0:`${r} build failed with exit code ${String(c.code)}`}finally{i(),t.bundleMetaPath===void 0&&oe(a,{force:!0})}},fe=(e,r,t)=>r!==!1&&ue(e,t)!==void 0,vs=(e,r,t)=>fe(e,r,t)&&ue(e,t)!=="script",Le=e=>{const r=e.frameworkBuild===!1?void 0:ue(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{we(e.cwd,e.target)}catch(n){return n instanceof Error?n.message:String(n)}let t;try{t=we(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`},Ur=async e=>{const r=e.frameworkBuild===!1?void 0:ue(e.cwd,e.environment);if(r===void 0)return;let t;try{t=e.target??we(e.cwd)}catch(n){return n instanceof Error?n.message:String(n)}return ps(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})},cr=e=>Array.isArray(e)?e.filter(r=>r!=null):void 0,xe=(e,r)=>{const t=O(e);if(!t)return;const{parsed:n}=P(t);if(n===void 0)return;const{error:o,merged:s}=le(n,r),i=o===void 0?s:n,{containers:a,d1_databases:c,vars:l}=i;return{containers:cr(a),d1_databases:cr(c),vars:typeof l=="object"&&l!==null&&!Array.isArray(l)?l:void 0}},ys=/^127(?:\.\d{1,3}){3}$/,ws=e=>{try{const{hostname:r}=new URL(e);return r==="localhost"||ys.test(r)||r==="::1"||r==="[::1]"}catch{return!1}},ks=e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"),bs=(e,r,t,n="deploy",o)=>{const s=(xe(e,o)?.containers??[]).filter(a=>typeof a?.image=="string"&&ks(a.image));if(s.length===0||t())return;const i=`${n} blocked: wrangler.jsonc declares ${String(s.length)} container(s) built from a local Dockerfile, but no Docker-compatible engine is available. Start Docker (or Colima), or point the container's \`image\` at a pre-built registry reference. Note: container images must target linux/amd64.`;return r.error(i),i},Me=e=>b(A(e,He))?He:void 0,$s=(e,r,t="deploy",n)=>{for(const o of mr(e,"lunora",n).containers){const s=o.schedulingPolicy===void 0?o.image:void 0,a=[...s?.kind==="dockerfile"?[{field:"image",path:s.dockerfilePath}]:[],...Object.entries(o.schedulingPolicy==="durable_object"?o.images??{}:{}).flatMap(([c,l])=>l.kind==="dockerfile"?[{field:`images["${c}"]`,path:l.dockerfilePath}]:[])].find(c=>!b(A(e,c.path)));if(a!==void 0){const c=`${t} blocked: container "${o.exportName}" references a Dockerfile at "${a.path}" that does not exist. Create it or fix the \`${a.field}\` path in lunora/containers.ts.`;return r.error(c),c}if(s?.kind==="build"&&!b(A(e,s.buildDir))){const c=`${t} blocked: container "${o.exportName}" references a Railpack build directory "${s.buildDir}" that does not exist. Create it or fix the \`image.build\` path in lunora/containers.ts.`;return r.error(c),c}}},Ss=(e,r)=>r==="celld"?typeof e=="string"&&e!==qe&&Xt(e):r==="cloudflare"&&e===qe,Es=(e,r,t)=>(xe(e,t)?.d1_databases??[]).find(n=>Ss(n.database_id,r)),As=e=>{if(!e.migrate||e.dryRun)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}},Rs=(e,r,t,n,o)=>{const s=Es(e,n,o);if(s===void 0)return;const i=`${t} blocked: the "${s.binding??"<unnamed>"}" D1 binding has a placeholder database_id ("${s.database_id??""}")`,a=n==="celld"?`${i}, which celld would use as the database's identity. Set database_id to the database celld should use, then ${t} again.`:`${i}. 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(a),a},Ts=(e,r,t="deploy",n)=>{const o=xe(e,n)?.vars;if(!o)return;const s=Object.entries(o).filter(([,a])=>typeof a=="string"&&ws(a)).map(([a])=>a).toSorted((a,c)=>a.localeCompare(c));if(s.length===0)return;const i=`${t} blocked: ${s.join(", ")} in wrangler.jsonc point at localhost. A deployed Worker can't reach a loopback address, so this silently breaks scheduled-job dispatch, reverse cross-shard relations, and auth callbacks. Set each to the deployed worker's public URL (or move it to a secret with \`wrangler secret put\`) before deploying.`;return r.error(i),i},_s=["vite.config.ts","vite.config.mts","vite.config.cts","vite.config.js","vite.config.mjs","vite.config.cjs",...at],Br=/\.(?:[cm]?[jt]s|tsx|jsx)$/u,Wr=/\.(?:test|spec)\.[cm]?[jt]sx?$/u,Hr="allowUnauthenticatedShardAccess",Cs=/[\\/]/u,qr=new Set(["_generated","build","dist","node_modules"]),Gr=(e,r)=>{const t=J(e,r).split(Cs);return Br.test(r)&&!Wr.test(r)&&!ye(t.join("/"))&&t.every(n=>n===".."||!n.startsWith(".")&&!qr.has(n))},dr=(e,r,t)=>{const{parsed:n}=P(r);if(n===void 0)return[];const{error:o,merged:s}=le(n,t),{main:i}=o===void 0?s:n,a=typeof i=="string"?A(Rr(r),i):void 0;return a!==void 0&&b(a)&&Gr(e,a)?[a]:[]},Fe=e=>e===void 0?!1:e.getKind()===y.FalseKeyword?!0:$.isParenthesizedExpression(e)||$.isAsExpression(e)||$.isSatisfiesExpression(e)||$.isTypeAssertion(e)||$.isNonNullExpression(e)?Fe(e.getExpression()):!1,Is=e=>{try{return Re(e).isFile()}catch{return!1}},Ps=new Set(["ELOOP","ENOENT","ENOTDIR"]),ae=(e,r,t)=>{const n=r instanceof Error&&"code"in r&&typeof r.code=="string"?r.code:"";Ps.has(n)||t.push(e)},js=(e,r)=>{try{return Re(e)}catch(t){ae(e,t,r);return}},Vr=(e,r)=>{try{return E(e,"utf8")}catch(t){ae(e,t,r);return}},Kr=(e,r,t,n=new Set)=>{let o;try{o=st(r)}catch(i){return ae(r,i,t),[]}if(n.has(o))return[];n.add(o);let s;try{s=K(r)}catch(i){return ae(r,i,t),[]}return s.flatMap(i=>{const a=A(r,i),c=js(a,t);if(c===void 0)return[];const l=J(e,a).split(x).join("/");return c.isDirectory()?qr.has(i)||i.startsWith(".")||ye(`${l}/`)?[]:Kr(e,a,t,n):c.isFile()&&Br.test(i)&&!Wr.test(i)&&!ye(l)?[a]:[]})},Os=e=>{const r=$.isComputedPropertyName(e)?e.getExpression():e;return $.isStringLiteral(r)||$.isNoSubstitutionTemplateLiteral(r)?r.getLiteralValue():e.getText()},pe=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],Ds=/\.(?:[cm]?js|jsx)$/u,Ns=(e,r)=>{if(!r.startsWith("."))return;const t=I(Rr(e),r),n=t.replace(Ds,"");return[t,...pe.map(s=>`${t}${s}`),...pe.map(s=>A(t,`index${s}`)),...pe.map(s=>`${n}${s}`)].find(s=>Is(s))},Ls=e=>{if(e.getExpression().getText()!=="require")return;const[r]=e.getArguments();return r!==void 0&&($.isStringLiteral(r)||$.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},xs=e=>{const r=e.getModuleReference();if(!$.isExternalModuleReference(r))return;const t=r.getExpression();return $.isStringLiteral(t)?t.getLiteralValue():void 0},Ms=(e,r,t,n)=>{const o=new Set(e),s=[...e],i=[];for(let a=0;a<s.length;a+=1){const c=s[a]??"",l=Vr(c,n);if(l===void 0)continue;const d=r.createSourceFile(J(t,c),l,{overwrite:!0}),u=[...d.getImportDeclarations().map(f=>f.getModuleSpecifierValue()),...d.getExportDeclarations().map(f=>f.getModuleSpecifierValue()),...d.getDescendantsOfKind(y.ImportEqualsDeclaration).map(f=>xs(f)),...d.getDescendantsOfKind(y.CallExpression).map(f=>Ls(f))].filter(f=>f!==void 0);for(const f of u){const h=Ns(c,f);h!==void 0&&Gr(t,h)&&!o.has(h)&&(o.add(h),i.push(h),s.push(h))}}return i},Fs=e=>{const r=e.getArgumentExpression();return r!==void 0&&($.isStringLiteral(r)||$.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},Us=e=>$.isPropertyAccessExpression(e)?e.getName():$.isElementAccessExpression(e)?Fs(e):void 0,Bs=new Set([y.AmpersandAmpersandEqualsToken,y.AmpersandEqualsToken,y.AsteriskAsteriskEqualsToken,y.AsteriskEqualsToken,y.BarBarEqualsToken,y.BarEqualsToken,y.CaretEqualsToken,y.EqualsToken,y.GreaterThanGreaterThanEqualsToken,y.GreaterThanGreaterThanGreaterThanEqualsToken,y.LessThanLessThanEqualsToken,y.MinusEqualsToken,y.PercentEqualsToken,y.PlusEqualsToken,y.QuestionQuestionEqualsToken,y.SlashEqualsToken]),Ws=e=>{const r=e.getOperatorToken().getKind();return!Bs.has(r)||Us(e.getLeft())!==Hr?!1:r!==y.EqualsToken||!Fe(e.getRight())},Hs=(e,r,t)=>{const n=[],o=[...new Set([M(e),"src"])].filter(u=>b(A(e,u))),s=O(e),i=[..._s.map(u=>A(e,u)).filter(u=>b(u)),...s===void 0?[]:dr(e,s,r),...t.flatMap(u=>dr(e,u,r))],a=new Ar({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}),c=o.flatMap(u=>Kr(A(e,u),A(e,u),n));return{sites:[...new Set([...c,...i,...Ms([...i,...c],a,e,n)])].flatMap(u=>{const f=Vr(u,n);if(f===void 0)return[];const h=a.createSourceFile(J(e,u),f,{overwrite:!0}),g=[...h.getDescendantsOfKind(y.PropertyAssignment),...h.getDescendantsOfKind(y.ShorthandPropertyAssignment),...h.getDescendantsOfKind(y.GetAccessor),...h.getDescendantsOfKind(y.MethodDeclaration)].filter(m=>{const S=$.isPropertyAssignment(m)&&Fe(m.getInitializer());return Os(m.getNameNode())===Hr&&!S}).map(m=>m.getStartLineNumber()),v=h.getDescendantsOfKind(y.BinaryExpression).filter(m=>Ws(m)).map(m=>m.getStartLineNumber());return[...g,...v].map(m=>({file:J(e,u),line:m}))}),unreadable:n}},qs=(e,r,t,n,o,s)=>{if(t!=="deploy")return;const{sites:i,unreadable:a}=Hs(e,o,s),c=kn({openShardAccess:i,schema:{tables:[]}},{lints:[Ge]});if(c.length===0&&a.length===0)return;const l=[];if(c.length>0){const u=c.map(f=>`${String(f.metadata.file)}:${String(f.metadata.line)}`).join(", ");l.push(`${u} enable the open-shard option (any value but a literal false), so any caller may target any shard.`)}if(a.length>0&&l.push(`could not read ${a.join(", ")}, so the open-shard option cannot be ruled out there.`),n){r.warn(`deploying past the open-shard gate (--allow-open-shards): ${l.join(" ")}`);return}const d=`deploy blocked (open_shard_access): ${l.join(" ")} ${Ge.remediation}`;return r.error(d),d},Gs=(e,r,t,n)=>{const o=qs(e,r.logger,t,r.allowOpenShards===!0,r.env,n);return o===void 0?void 0:{code:w.USAGE,error:o}},Vs=(e,r,t,n)=>{const o=Rs(e,r.logger,t,n,r.env);if(o!==void 0)return{code:w.USAGE,error:o};const s=Ts(e,r.logger,t,r.env);if(s!==void 0)return{code:w.USAGE,error:s};const i=$s(e,r.logger,t,r.discoveryCache);if(i!==void 0)return{code:w.USAGE,error:i};const a=bs(e,r.logger,r.dockerAvailable??gn,t,r.env);return a===void 0?void 0:{code:w.MISSING_DEPENDENCY,error:a}},Ks=/https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u,zs=/https:\/\/[^\s"'<>]+/u,Js=e=>{if(e===void 0)return;const r=Ks.exec(e);return r?r[0]:zs.exec(e)?.[0]},lr=e=>e===void 0?"":` (--env ${e})`,Ys=({cwd:e,env:r,logger:t,now:n,url:o})=>{if(o!==void 0)try{const s=_e(e);if(s!==void 0){if(s.workerUrl===o&&s.env===r)return;t.warn(`link: .lunora/project.json records ${s.workerUrl??"(no url)"}${lr(s.env)}, but this deploy published ${o}${lr(r)}. Keeping the recorded value — run \`lunora link --url ${o}${r===void 0?"":` --env ${r}`}\` to update it.`);return}const i=(n??(()=>new Date().toISOString()))();kt(e,{env:r,linkedAt:i,workerName:Pe(e),workerUrl:o}),t.success(`link: recorded ${o} in .lunora/project.json (run \`lunora link\` to change)`)}catch{}},Xs=async(e,r)=>{const t=new Ar({skipAddingFilesFromTsConfig:!0}),n=A(r,"lunora");let o;try{o=ct(t,n)}catch(s){const i=s instanceof Error?s.message:String(s);return e.logger.warn(`--migrate: could not discover migrations (${i}); 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 s of o){e.logger.info(`--migrate: up "${s.id}" (table "${s.table}")`);const i={cwd:r,fetchImpl:e.fetchImpl,id:s.id,logger:e.logger,prod:!0,subcommand:"up",token:e.migrateToken,url:e.migrateUrl,yes:e.migrateYes===!0},a=await bn(i);if(a.code!==0)return e.logger.error(`--migrate: migration "${s.id}" failed — see output above`),a.code;e.logger.success(`--migrate: "${s.id}" applied`)}return 0},Qs=async(e,r)=>{const{info:t}=Ce(r,"lunora",e.discoveryCache),n=t?.vectorMetadata??[];if(n.length===0)return;const o=[];for(const a of n){const c=Qt(a.kind);if(c===void 0){e.logger.warn(`vector index "${a.index}" declares metadata "${a.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:a.index,property:a.property,type:c})}if(o.length===0)return;const i=(await Zt({cwd:r,entries:o,exec:je(F(r),"wrangler",[]),logger:e.logger,spawner:e.spawner??H})).filter(a=>a.status!=="failed").length;i>0&&e.logger.success(`vectorize metadata indexes ready: ${String(i)}/${String(o.length)}`)},ur=5,Zs=2e3,ei=async(e,r,t)=>{if(e.healthCheck!==!0)return;const n=t??Oe({cwd:r,env:e.env});if(n===void 0){const s="--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(s),{error:s,ok:!1,url:""}}const o=await hn({attempts:ur,baseUrl:n,delayMs:Zs,fetchImpl:e.healthFetch,paths:[mn,pn],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(ur)} attempt(s) — ${o.error}`),{error:o.error,ok:!1,url:o.url})},ri=async(e,r,t,n,o,s)=>{e.isolatedPreview!==!0&&await Qs(e,r);const i=e.migrate?await Xs(e,r):0;return i===0&&o?.(),{code:i,descriptor:t,mintedSecretsFile:s,validation:n}},ti=async({cwd:e,descriptor:r,mintedSecretsFile:t,options:n,reblessSchemaBaseline:o,recordArchitecture:s,stdout:i,validation:a})=>{const c={deployedAt:new Date().toISOString(),dryRun:n.dryRun===!0,env:n.env,url:n.dryRun===!0?void 0:Js(i),workerName:Pe(e)};if(n.dryRun===!0)return n.healthCheck===!0&&n.logger.warn("--health-check skipped: a dry run publishes nothing"),{code:0,deployment:c,descriptor:r,mintedSecretsFile:t,validation:a};n.temporary!==!0&&n.isolatedPreview!==!0&&(s?.(),Ys({cwd:e,env:n.env,logger:n.logger,url:c.url}));const l=await ei(n,e,c.url);if(l?.error!==void 0)return{code:w.UNAVAILABLE,deployment:c,descriptor:r,healthCheck:l,mintedSecretsFile:t,validation:a};const d=n.isolatedPreview===!0?void 0:o;return{...await ri(n,e,r,a,d,t),deployment:c,healthCheck:l}},ni=(e,r,t)=>{const n=A(e,N);if(!b(n))return;let o;try{o=pr(E(n,"utf8")).length}catch{return}if(o===0)return;const s=t.toolchain?.secretPut!==void 0;r.warn(s?`Note: \`lunora deploy\` does not push secrets. ${N} 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. ${N} 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.`)},zr=async(e,r)=>{let t=[];try{t=bt(await vr({cache:r,projectRoot:e,schemaDir:M(e)}))}catch{}const n=[...new Set($t(t).map(s=>s.key))];let o=[];try{const s=A(e,N);b(s)&&(o=pr(E(s,"utf8")).map(i=>i.key).filter(i=>br(i)))}catch{}return{fromLocal:o.filter(s=>!n.includes(s)),fromPackages:n,mintableKeys:St(t)}},oi=async(e,r,t,n)=>{const{logger:o}=r,s=r.spawner??H,i=F(e),a=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 l=t.map(f=>({key:f,value:Et()})),d=n.toolchain?.secretBulk;if(d!==void 0&&l.length>=2){const f=z(i,d({environment:r.env,temporary:r.temporary})),h=await s({args:f.args,command:f.command,cwd:e,input:JSON.stringify(Object.fromEntries(l.map(g=>[g.key,g.value])))});if(h.code===0){for(const{key:g}of l)o.success(`generated + pushed ${g}`);return{minted:l,ok:!0}}o.warn(`bulk secret push failed (exit ${String(h.code)}); retrying one key at a time`)}const u=[];for(const{key:f,value:h}of l){const g=c({environment:r.env,key:f,temporary:r.temporary}),v=z(i,g),m=await s({args:v.args,command:v.command,cwd:e,input:h});if(m.code!==0)return o.error(`failed to push secret ${f} (exit ${String(m.code)}); set it manually with \`wrangler secret put ${f}${a}\`.`),{minted:u,ok:!1};u.push({key:f,value:h}),o.success(`generated + pushed ${f}`)}return{minted:u,ok:!0}},si=/^[\w-]+$/u,fr=[".dev.vars",".dev.vars.*","!.dev.vars.example"],ii=(e,r)=>{try{const t=_t(e,fr);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 \`${fr.join("` and `")}\` by hand before committing.`)}},ai=(e,r,t)=>{if(t.length===0)return;const n=t.map(a=>a.key).join(", ");if(r.env!==void 0&&!si.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?N:`${N}.${r.env}`;ii(e,r.logger);const s=A(e,o);let i=b(s)?E(s,"utf8"):"";for(const a of t)i=At(i,a.key,a.value);return Rt(s,i),r.logger.success(r.env===void 0?`${n}: value(s) recorded in ${o}`:`${n}: value(s) recorded in ${o} (kept separate from ${N} so \`lunora dev\` and a plain \`lunora env push\` don't inherit the --env ${r.env} value)`),o},ci=/^<[^>]+>$/u,di=async(e,r,t)=>{let n;try{n=t.projectConfig?.(e,"deploy").vars??{}}catch(d){return{error:d instanceof Error?d.message:String(d)}}const o=d=>{const u=n[d];if(typeof u!="string")return!0;const f=u.trim();return f===""||ci.test(f)?!0:br(d)&&Tt(u)},s=d=>Object.hasOwn(n,d)?`${d} (empty or a placeholder)`:d,{fromLocal:i,fromPackages:a}=await zr(e,r.discoveryCache),c=i.filter(d=>o(d));c.length>0&&r.logger.warn(`${N} key(s) not set in the wrangler vars: ${c.map(d=>s(d)).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 l=a.filter(d=>o(d));return l.length===0?{}:{error:`missing required secret(s) in the wrangler vars: ${l.map(d=>s(d)).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.`}},li=async(e,r,t,n)=>{if(r.dryRun===!0||r.isolatedPreview===!0)return{};if(n.toolchain?.secretList===void 0)return di(e,r,n);const{logger:o}=r,s=r.env===void 0?"":` --env ${r.env}`;let i;try{i=await(r.secretLister??Sn)({cwd:e,env:r.env,target:n.id,temporary:r.temporary})}catch{return{}}if(!i.ok)return{};const a=new Set(i.names),{fromLocal:c,fromPackages:l,mintableKeys:d}=await zr(e,r.discoveryCache),u=[...l,...c].filter(g=>!a.has(g));if(u.length===0)return{};if(!t)return{error:`missing required secret(s) on the deploy target: ${u.join(", ")}. Set them with \`wrangler secret put <KEY>${s}\` (or \`lunora env generate --set\` then \`lunora env push --yes${s}\`), then re-deploy.`};for(const g of u.filter(v=>!d.has(v)))o.warn(`required secret ${g} is not set on the target — set it with: wrangler secret put ${g}${s}`);const f=u.filter(g=>d.has(g));if(f.length===0)return{};if(await(r.secretConfirm??$n())(`${String(f.length)} required secret(s) not set on the target (${f.join(", ")}). Generate strong values and push them now?`)){const{minted:g,ok:v}=await oi(e,r,f,n),m=ai(e,r,g);return v?{mintedSecretsFile:m}:{error:"failed to push required secret(s) — set them manually and re-deploy",mintedSecretsFile:m}}return o.warn(`${String(f.length)} required secret(s) not set on the target: ${f.join(", ")}. Generate + push with \`lunora env generate --set\` then \`lunora env push --yes${s}\`.`),{}},Jr=e=>e.format==="json"?!1:e.interactive!==void 0?e.interactive:process.stdout.isTTY&&!process.env.CI,ui=async(e,r)=>{if(r.dryRun===!0)return;const t=mr(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 Yo({cwd:e,logger:r.logger,railpackAvailable:r.railpackAvailable,spawner:r.spawner,targets:t});return n.code===0?void 0:n.error??"railpack build failed"},fi=(e,r,t)=>{if(t!==void 0)try{const n=Bt(e,t);n.changed&&r.success(`synced ${String(t.length)} cron trigger(s) → ${n.wranglerPath??"wrangler.jsonc"}`);for(const s of n.warnings)r.warn(s);const o=Wt(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}`)}},gi=async(e,r,t,n,o,s)=>{try{de(n);const i=await vr({cache:s,projectRoot:e,schemaDir:M(e)}),a=Ft(e,i,{environment:o,target:n}),c=a.wranglerPath??"wrangler.jsonc";if(a.added.length>0&&r.success(`provisioned bindings: ${a.added.join(", ")} → ${c}`),a.updated.length>0&&r.success(`updated bindings: ${a.updated.join(", ")} → ${c}`),a.devConfig!==void 0){const{added:l,path:d,updated:u}=a.devConfig;r.success(`dev sidecar bindings: ${[...l,...u].join(", ")} → ${d}`)}for(const l of a.warnings)r.warn(l)}catch(i){const a=i instanceof Error?i.message:String(i);r.warn(`binding inference skipped: ${a}`)}try{const i=Ut(e);i.changed&&r.success(`bumped compatibility_date to ${i.date??"unknown"} (Workers Cache enabled) → ${i.wranglerPath??"wrangler.jsonc"}`)}catch(i){const a=i instanceof Error?i.message:String(i);r.warn(`compatibility date sync skipped: ${a}`)}fi(e,r,t)},hi=async(e,r,t,n,o,s,i,a,c,l)=>{let d;r?(d=new Ht({name:"dots"}),d.start("running codegen")):t.info("running codegen");try{const u=dt({apiSpec:n,dryRun:!l,lazyFunctions:o,projectRoot:e,target:s,...Mt(e)});d?.succeed("codegen complete"),d||t.success("codegen complete");const f=zt(u.platformDiagnostics,t);if(f.errors.length>0)return{error:f.errors.join("; ")};const{errorAdvisories:h,names:g,shouldBlock:v}=Jt(u.advisories,c);if(v){const S=`${h.length.toString()} ERROR-level ${h.length===1?"advisory":"advisories"} (${g.join(", ")}). Pass --no-strict-advisories to downgrade this to a warning and continue.`;return t.error(S),{error:S}}const m=l?await Ot({cwd:e,logger:t,spawner:i,stdoutToStderr:a}):void 0;return m?.error!==void 0?{error:m.error}:{result:u}}catch(u){d?.failed("codegen failed");const f=u instanceof Error?u.message:String(u);return t.error(`codegen failed: ${f}`),{error:`codegen failed: ${f}`}}},gr="--preview is not supported: Cloudflare gives a Worker that implements a Durable Object no version preview URL, and a version shares production's Durable Objects, D1 and R2. Deploy an isolated copy with `lunora preview deploy <name>` (its own Worker, Durable Object namespace, D1, R2 and KV; `lunora preview delete <name>` removes it), or validate without publishing with `--dry-run`.",mi=(e,r)=>({dryRun:r.dryRun,entry:Me(e),environment:r.env,outDir:r.outDir,secretsFile:r.secretsFile,temporary:r.temporary}),Yr=(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=mi(e,r);return yr(t,e,"deploy",s=>n.deploy({...o,configPath:s}))},pi=(e,r,t)=>{const n=Yr(e,r,t),o=Me(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},_={problems:[],wranglerPath:void 0},ve=(e,r)=>({code:w.USAGE,descriptor:void 0,error:e,validation:_,...r}),vi=(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},yi=(e,r,t)=>{const n=r.format==="json",o=r.dryRun!==!0,s=pi(e,r,t),i=z(F(e),s);return{args:i.args,captureStdout:o&&!n,captureStdoutSilently:o&&n,command:i.command,cwd:e,stdoutToStderr:n&&!o}},Ue=e=>{if(e.skipServices===!0)return"--skip-services";if(e.isolatedPreview===!0)return"a preview never deploys services: they are production's Workers";if(e.temporary===!0)return"--temporary deploys the app to a throwaway account"},wi=(e,r)=>Ue(r)===void 0?Te(e).services.map(t=>t.wranglerPath):[],Xr=(e,r,t,n,o)=>({cwd:e,environment:r.env,frameworkBuild:n,lazyFunctions:ce(r.lazyFunctions),logger:r.logger,outputJson:r.format==="json"||r.clientBuildOutputJson===!0,spawner:o,strictAdvisories:Ie(r),target:t.id}),ki=(e,r,t)=>{const{toolchain:n}=t,o=n===void 0?`target "${t.id}" has no deploy command`:Ue(r);if(o!==void 0||n===void 0){const s=e.map(i=>i.worker).join(", ");r.logger.warn(`services not deployed (${o??""}): ${s} — deploy them yourself if the app calls anything new`);return}return n},Qr=(e,r)=>{for(const t of e){const n=Le(r(j(t.wranglerPath)));if(n!==void 0)return`service ${t.name} (${t.worker}): ${n}`}},bi=(e,r,t)=>{const{error:n,services:o}=Te(e);if(n!==void 0||o.length===0)return;const s=de(t);if(s.toolchain===void 0||Ue(r)!==void 0)return;const i=r.skipCodegen===!0?!1:r.frameworkBuild,a=[...new Map(o.map(c=>[c.wranglerPath,c])).values()];return Qr(a,c=>Xr(c,r,s,i,H))},Zr=(e,r,t)=>{const n=e.cwd??process.cwd(),o=on(n,e.target);if(o.target===void 0){const a=o.error??"unknown deploy target";return e.logger.error(a),{kind:"refused",error:a,validation:_}}if(e.preview===!0)return e.logger.error(gr),{kind:"refused",code:w.USAGE,error:gr,validation:_};try{Yr(n,e,de(o.target))}catch(a){if(!(t&&a instanceof Ct&&fe(n,e.skipCodegen===!0?!1:e.frameworkBuild,e.env))){const c=a instanceof Error?a.message:String(a);return e.logger.error(c),{kind:"refused",error:c,validation:_}}}const s=e.openShardGatePassed===!0?void 0:Gs(n,e,r,wi(n,e));if(s!==void 0)return{kind:"refused",code:s.code,error:s.error,validation:_};const i=bi(n,e,o.target);return i!==void 0?(e.logger.error(i),{kind:"refused",code:w.USAGE,error:i,validation:_}):{kind:"ok",target:o.target}},$i=(e,r)=>e.apiSpec??(e.clientBuildRan===!0?Dt(r):void 0),Si=async(e,r,t)=>{if(r!=="celld")return;const n=await(e.celldToolchain??jt)({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},et=(e,r)=>{const t=Oe({cwd:e,env:r.env,url:r.migrateUrl}),n=t===void 0?void 0:us(e,r.env,t);if(n!==void 0)return{reason:n};const o=t===void 0?void 0:Vt(t,r.logger,e),s=o===void 0?void 0:qt({cwd:e,token:r.migrateToken,url:o}).token;return{target:o===void 0||!s?void 0:{baseUrl:o,fetchImpl:r.fetchImpl??Kt,token:s}}},Ei=(e,r,t)=>async n=>{const o=et(e,r);return"reason"in o?{kind:"inconclusive",reason:o.reason}:wn({changes:n,tables:t.schemaTables,target:o.target})},Ai=(e,r)=>async t=>{const n=et(e,r);return"reason"in n?n.reason:yn({changes:t,now:Date.now(),target:n.target})},Ri=(e,r,t,n)=>e==="deploy"?{checkStoredRows:Ei(r,t,n),countExpiringRows:Ai(r,t)}:{},Ti=async(e,r)=>{const t=e.cwd??process.cwd(),n=Jr(e),o=Ie(e),s={problems:[],wranglerPath:void 0},i=Zr(e,r,!1);if(i.kind==="refused")return{code:i.code,error:i.error,validation:i.validation};const{target:a}=i,c=await Si(e,a,r);if(c!==void 0)return e.logger.error(c),{code:w.MISSING_DEPENDENCY,error:c,target:a,validation:s};let l;if(!e.skipCodegen){const v=await hi(t,n,e.logger,$i(e,t),ce(e.lazyFunctions),a,e.spawner,e.format==="json",o,e.clientBuildRan!==!0);if(v.error!==void 0)return{error:v.error,target:a,validation:_};l=v.result,e.discoveryCache?.clear()}let d;if(l!==void 0){const v=await vn({allowDrift:e.allowSchemaDrift===!0,...Ri(r,t,e,l),codegen:l,command:r,logger:e.logger});if(v.blocked)return{error:`schema drift gate blocked ${r}`,schemaDrift:{blocked:!0,reason:v.reason},target:a,validation:s};d=v.rebless}const u=l&&In({current:l.architecture,cwd:t,environment:e.env,logger:e.logger});await gi(t,e.logger,l?.cronTriggers,a,e.env,e.discoveryCache);const f=await Cr(t,e,r,a,"check");if(f!==void 0)return{error:f,target:a,validation:_};const h=Vs(t,e,r,a);if(h!==void 0)return{code:h.code,error:h.error,target:a,validation:_};const g=xt({environment:e.env,projectRoot:t});return vi(g,e.logger)?{error:"wrangler validation failed",target:a,validation:g}:{codegen:l,reblessSchemaBaseline:d,recordArchitecture:u,target:a,validation:g}},_i=e=>{oe(p(e,".wrangler","deploy","config.json"),{force:!0})},Ci=async(e,r,t)=>{const n=Le(e);if(n!==void 0)return{built:!1,error:n};const o=fe(e.cwd,r,t);return o&&_i(e.cwd),{built:o,error:await Ur(e)}},Ii=(e,r,t)=>r||t===!1?De(e):void 0,Pi=async(e,r,t,n)=>{const{error:o,services:s}=Te(e);if(o!==void 0)return{code:w.FAILURE,error:o};if(s.length===0)return;const i=ki(s,r,t);if(i===void 0)return;const a=F(e),c=[...new Map(s.map(f=>[f.wranglerPath,f])).values()],l=r.skipCodegen===!0?!1:r.frameworkBuild,d=f=>Xr(f,r,t,l,n),u=Qr(c,d);if(u!==void 0)return r.logger.error(u),{code:w.USAGE,error:u};for(const f of c){const h=j(f.wranglerPath),g=d(h),{built:v,error:m}=await Ci(g,l,r.env);if(m!==void 0){const T=`service ${f.name} (${f.worker}): ${m}`;return r.logger.error(T),{code:w.FAILURE,error:T}}const S=Ii(f.wranglerPath,v,l);let D;try{D=yr(t,h,"deploy",T=>i.deploy({configPath:T??S??f.wranglerPath,dryRun:r.dryRun===!0,environment:r.env}))}catch(T){return{code:w.FAILURE,error:`service ${f.name} (${f.worker}): ${T instanceof Error?T.message:String(T)}`}}D.commit();const R=z(a,D.command);r.logger.info(`deploying service ${f.name} (${f.worker}) via ${R.command} ${R.args.join(" ")}`);const q=await n({args:R.args,command:R.command,cwd:h,stdoutToStderr:r.format==="json"});if(q.code!==0)return{code:w.FAILURE,error:`service ${f.name} (${f.worker}): ${R.command} ${R.args.join(" ")} exited ${String(q.code)} — stopping before the app`}}},ji=async(e,r,t,n)=>{if(r!=="cloudflare")return;const o=e===void 0?void 0:P(e).parsed,s=(t===void 0?void 0:o?.env?.[t]?.account_id)??o?.account_id,i=await rn({accountId:s});(i.verdict==="near"||i.verdict==="full")&&n.warn(i.fix===void 0?i.message:`${i.message} ${i.fix}`)},Oi=e=>e.dryRun!==!0&&e.temporary!==!0,Di=e=>e.temporary===!0?"temporary":e.dryRun===!0?"preview":"defer",Ni=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},Li=(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 s=Ni(o);r.error(s),n.push(s)}return n},rt=async(e,r,t,n,o,s,i)=>{const a=t==="cloudflare"&&r!==void 0?P(r).parsed:void 0;if(a===void 0)return;const c=(le(a,n).merged.artifacts??[]).flatMap(g=>typeof g?.binding=="string"&&typeof g.namespace=="string"?[{binding:g.binding,namespace:g.namespace}]:[]),l=c.length===0?void 0:Ce(e,M(e),s).info?.jurisdiction;if(l===void 0)return;const d=[...new Map(c.map(g=>[g.namespace,g])).values()];if(i==="temporary"){o.warn(`--temporary deploys to a throwaway account, so the jurisdiction ("${l}") of Artifacts namespace ${d.map(g=>`"${g.namespace}"`).join(", ")} was not checked: it is created there on first use, in no jurisdiction.`);return}const u=(n===void 0?void 0:a.env?.[n]?.account_id)??a.account_id,f=await Promise.all(d.map(async g=>en({...g,accountId:u,create:i==="create",jurisdiction:l,missingOk:i==="defer"||i==="preview"}))),h=Li(f,o,i);return h.length===0?void 0:h.join(`
57
+ `)},xi=async(e,r,t,n,o,s)=>{const i=Oi(r)?await rt(e,s,o,r.env,r.logger,r.discoveryCache,"create"):void 0;if(i!==void 0)return{code:w.FAILURE,error:i};const a=await Cr(e,r,"deploy",o);return a!==void 0?{code:w.FAILURE,error:a}:Pi(e,r,t,n)},Mi=async(e,r,t,n)=>{if(!(r.smokeLoad===!1||t.toolchain===void 0))return zo({composedEntry:Me(e),configPath:n,cwd:e,environment:r.env,launcher:r.smokeLauncher,logger:r.logger,toolchain:t.toolchain})},Fi=async e=>{const r={...e,discoveryCache:e.discoveryCache??Pt()},t=r.cwd??process.cwd(),n=Jr(r),o=await Ti(r,r.commandName??"deploy");if(o.error!==void 0){if(o.validation.problems.length>0)return{code:w.USAGE,descriptor:void 0,error:o.error,validation:o.validation};const m=o.schemaDrift===void 0?void 0:{schemaDrift:o.schemaDrift};return ve(o.error,{...m,...o.code===void 0?{}:{code:o.code}})}const{validation:s}=o,i=de(o.target),a=As(r)??await rt(t,s.wranglerPath,o.target,r.env,r.logger,r.discoveryCache,Di(r))??await Mi(t,r,i,s.wranglerPath);if(a!==void 0)return ve(a);const c=i.toolchain?.prebuildsContainerImages===!0?await ui(t,r):void 0;if(c!==void 0)return ve(c);ni(t,r.logger,i),Lt(t,m=>{r.logger.warn(m)}),await ji(s.wranglerPath,o.target,r.env,r.logger);const{error:l,mintedSecretsFile:d}=await li(t,r,n,i);if(l!==void 0)return r.logger.error(l),{code:w.USAGE,descriptor:void 0,error:l,mintedSecretsFile:d,validation:s};const u=r.spawner??H,f=await xi(t,r,i,u,o.target,s.wranglerPath);if(f!==void 0)return{code:f.code,descriptor:void 0,error:f.error,mintedSecretsFile:d,validation:s};const h=yi(t,r,i);r.logger.info(`deploying via ${h.command} ${h.args.join(" ")}`);const g=await u(h);return h.captureStdoutSilently===!0&&g.stdout!==void 0&&g.stdout!==""&&process.stderr.write(g.stdout),g.code!==0?{code:g.code,descriptor:h,mintedSecretsFile:d,validation:s}:{...await ti({...o,cwd:t,descriptor:h,mintedSecretsFile:d,options:r,stdout:g.stdout}),logsAvailable:i.toolchain?.tail!==void 0}},Ui=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:Ie(e),lazyFunctions:ce(e.lazyFunctions),logger:r,outputJson:e.format==="json"||e.clientBuildOutputJson===!0,spawner:e.spawner,target:e.target},o=Le(n);if(o!==void 0)return r.error(o),{code:w.USAGE,descriptor:void 0,error:o,validation:_};It(t);const s=await Ur(n);if(s!==void 0)return r.error(s),{code:w.FAILURE,descriptor:void 0,error:s,validation:_}},Bi=(e,r)=>{const t=r.skipCodegen===!0?!1:r.frameworkBuild;return fe(e,t,r.env)?r.env:void 0},Wi=async e=>{const{logger:r}=e,t=e.cwd??process.cwd(),n=Zr(e,e.commandName??"deploy",!0);if(n.kind==="refused")return{code:n.code??w.USAGE,descriptor:void 0,error:n.error,validation:n.validation};const o=await Ui(e);if(o!==void 0)return o;const s=e.dryRun===!0?xr(t):void 0;let i;try{if(i=await Fi({...e,clientBuildEnvironment:Bi(t,e),clientBuildRan:vs(t,e.skipCodegen===!0?!1:e.frameworkBuild,e.env),logger:r,openShardGatePassed:!0}),i.code===0&&e.emitBindings!==void 0){const{error:a}=tn({destination:e.emitBindings,logger:r,projectRoot:e.cwd??process.cwd()});a!==void 0&&(r.error(a),i={...i,code:w.USAGE})}}finally{s?.()}return e.format==="json"||i.code===0&&e.dryRun!==!0&&e.isolatedPreview!==!0&&Pn({cwd:e.cwd??process.cwd(),env:e.env,logger:e.logger,logsAvailable:i.logsAvailable===!0,mintedSecretsFile:i.mintedSecretsFile,url:i.deployment?.url}),i},Ea=nn(async({cwd:e,format:r,logger:t,options:n})=>{const o=Jo(e,n.root),s=await Wi({allowOpenShards:n.allowOpenShards===!0,allowSchemaDrift:n.allowSchemaDrift===!0,apiSpec:Yt(n.apiSpec),frameworkBuild:n.prebuilt===!0?!1:n.frameworkBuild,lazyFunctions:ce(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:Oe({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});return{code:s.code,data:{deployment:s.deployment,healthCheck:s.healthCheck,mintedSecretsFile:s.mintedSecretsFile,schemaDrift:s.schemaDrift,validation:s.validation},error:s.error}});export{Ti as a,gi as b,Mn as c,xr as d,zr as e,Ea as f,Jo as p,Wi as r,Mi as s,fs as v};