@lunora/cli 1.0.0-alpha.460 → 1.0.0-alpha.462

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,19 +1,43 @@
1
- import{mkdirSync as Me,writeFileSync as H,existsSync as S,readFileSync as A,rmSync as W,mkdtempSync as Er,readdirSync as Fe,realpathSync as Ar,statSync as Ue}from"node:fs";import{dirname as M,join as k,resolve as L,relative as ee,extname as Tr,sep as ae}from"node:path";import{PROJECT_CONFIG_FILENAMES as Rr,isTestPath as se,discoverMigrations as _r,readServiceBindings as le,runCodegen as Dr}from"@lunora/codegen";import{readLinkedProject as Be,resolveSchemaDirectory as N,startDevProcess as Cr,acceptsConnection as Pr,resolveTargetOrThrow as ie,detectFramework as Nr,DEFAULT_BUNDLE_META_PATH as Or,STRICT_ADVISORIES_ENV as jr,LAZY_FUNCTIONS_ENV as Ir,BUNDLE_META_PATH_ENV as Lr,BUILD_TARGET_ENV as xr,BUILD_ROOT_ENV as Mr,canonicalPath as Fr,COMPOSED_WORKER_ENTRY as Se,discoverContainerInfo as He,D1_PLACEHOLDER_ID as $e,discoverSchemaInfo as ue,writeLinkedProject as Ur,DEV_VARS_FILE as P,parseDevVariableEntries as Ge,secretSourcesFromBindings as Br,inferLunoraBindings as qe,requiredSecrets as Hr,mintableSecretKeysFor as Gr,generateSecretValue as qr,upsertDevVariableLine as Vr,writeDevVariablesFileAtomically as Wr,isPlaceholderValue as Kr,ensureGitignoreEntries as zr,resolveLazyFunctions as J,resolveDeployDriver as Y,MissingBuildOutputError as Jr,clearApiSpecMarker as Yr,createDiscoveryCache as Xr,planToolchainInvocation as Ve,probeCelldToolchain as Qr,runPostCodegenHook as Zr,readApiSpecMarker as et}from"@lunora/config";import{bindingsNeedingDatabase as rt,findWranglerFile as O,readWranglerJsonc as D,mergeWranglerEnvironment as X,HYPERDRIVE_PLACEHOLDER_ID as We,applyModify as Ke,warnCloudflareCliConfigOnce as tt,validateWranglerProject as nt,wranglerCodegenInputs as ot,reconcileWranglerBindings as at,reconcileWranglerCompatibilityDate as st,reconcileWranglerCrons as it,describePreservedCrons as ct}from"@lunora/config/cloudflare";import{Spinner as dt}from"@visulima/spinner";import{r as ge,a as lt,e as ut}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as gt}from"../packem_shared/api-spec-lYyq4vL6.mjs";import{e as ft,m as ht,g as mt,i as ze,d as vt,b as pt}from"../packem_shared/vectorize-metadata-BVSF8z2h.mjs";import{w as yt}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{d as wt}from"../packem_shared/command-B6vu47iR.mjs";import{r as fe}from"../packem_shared/wrangler-name-Dsk5K1f-.mjs";import{a as kt}from"../packem_shared/deploy-target-resolve-BTCW1Iv4.mjs";import{EXIT_CODE as y}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";import{spawn as bt}from"node:child_process";import{randomUUID as Je,createHash as St}from"node:crypto";import{setTimeout as $t}from"node:timers/promises";import{toolchainExecArgs as F,detectPackageManager as j,execArgsFor as he}from"@lunora/config/cli";import{f as Et}from"../packem_shared/free-port-DjbFhaaT.mjs";import{containerBuildTag as At}from"@lunora/container";import{a as Tt,i as Rt}from"../packem_shared/docker-DpVxvYpL.mjs";import{defaultSpawner as x}from"../packem_shared/createRecordingSpawner-01ZngIwK.mjs";import{r as Ye}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{p as _t,H as Dt,a as Ct,r as Pt}from"../packem_shared/health-probe-Bw9JFfIy.mjs";import{runAdvisor as Nt,openShardAccess as Ee}from"@lunora/advisor";import{join as b,relative as U,dirname as Xe}from"@visulima/path";import{Project as Qe,SyntaxKind as p,Node as w}from"ts-morph";import{r as Ze,c as er}from"../packem_shared/cloudflare-credentials-BVmZnDZk.mjs";import{runMigrateDataCommand as Ot}from"../packem_shared/runMigrateGenerateCommand-Bd2W9t1k.mjs";import{c as jt}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{l as It}from"../packem_shared/wrangler-secrets-DlSlWvRH.mjs";const Lt=Object.freeze({edges:[],nodes:[],modules:[],unresolved:[],version:1}),xt=20,Ae=e=>`${e.from} -${e.kind}-> ${e.to}`,q=(e,r)=>{const t=new Set(e);return r.filter(n=>!t.has(n)).toSorted((n,o)=>n.localeCompare(o))},Mt=(e,r)=>{const t=e.modules.map(s=>s.name),n=r.modules.map(s=>s.name),o=e.edges.map(s=>Ae(s)),a=r.edges.map(s=>Ae(s));return{addedEdges:q(o,a),addedModules:q(t,n),removedEdges:q(a,o),removedModules:q(n,t)}},V=(e,r,t)=>{if(t.length===0)return[];const n=t.slice(0,xt).map(a=>` ${e} ${a}`),o=t.length-n.length;return[`${r}:`,...n,...o>0?[` … and ${o.toString()} more`]:[]]},Ft=e=>{const r=[...V("+","modules added",e.addedModules),...V("-","modules removed",e.removedModules),...V("+","edges added",e.addedEdges),...V("-","edges removed",e.removedEdges)];return r.length===0?void 0:`architecture changes since the last deploy:
1
+ import{mkdirSync as qe,writeFileSync as V,existsSync as b,readFileSync as E,rmSync as X,readdirSync as he,mkdtempSync as Cr,realpathSync as Nr,statSync as Ve}from"node:fs";import{dirname as U,join as y,resolve as O,relative as F,sep as B,extname as Or}from"node:path";import{PROJECT_CONFIG_FILENAMES as jr,isTestPath as le,discoverMigrations as Ir,readServiceBindings as me,runCodegen as Lr}from"@lunora/codegen";import{readLinkedProject as We,resolveSchemaDirectory as N,startDevProcess as xr,acceptsConnection as Mr,resolveTargetOrThrow as ue,detectFramework as Fr,DEFAULT_BUNDLE_META_PATH as Ur,STRICT_ADVISORIES_ENV as Br,LAZY_FUNCTIONS_ENV as Hr,BUNDLE_META_PATH_ENV as Gr,BUILD_TARGET_ENV as qr,BUILD_ROOT_ENV as Vr,canonicalPath as Wr,COMPOSED_WORKER_ENTRY as Re,discoverContainerInfo as ze,D1_PLACEHOLDER_ID as _e,discoverSchemaInfo as ve,writeLinkedProject as zr,DEV_VARS_FILE as C,parseDevVariableEntries as Ke,secretSourcesFromBindings as Kr,inferLunoraBindings as Je,requiredSecrets as Jr,mintableSecretKeysFor as Yr,generateSecretValue as Xr,upsertDevVariableLine as Qr,writeDevVariablesFileAtomically as Zr,isPlaceholderValue as et,ensureGitignoreEntries as rt,resolveLazyFunctions as ee,resolveDeployDriver as re,MissingBuildOutputError as tt,clearApiSpecMarker as nt,createDiscoveryCache as ot,planToolchainInvocation as Ye,probeCelldToolchain as at,runPostCodegenHook as st,readApiSpecMarker as it}from"@lunora/config";import{bindingsNeedingDatabase as ct,findWranglerFile as j,readWranglerJsonc as D,mergeWranglerEnvironment as te,HYPERDRIVE_PLACEHOLDER_ID as Xe,applyModify as Qe,warnCloudflareCliConfigOnce as dt,validateWranglerProject as lt,wranglerCodegenInputs as ut,reconcileWranglerBindings as gt,reconcileWranglerCompatibilityDate as ft,reconcileWranglerCrons as ht,describePreservedCrons as mt}from"@lunora/config/cloudflare";import{Spinner as vt}from"@visulima/spinner";import{r as pe,a as pt,e as yt}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as wt}from"../packem_shared/api-spec-lYyq4vL6.mjs";import{e as kt,m as bt,g as St,i as Ze,d as $t,b as Et}from"../packem_shared/vectorize-metadata-BVSF8z2h.mjs";import{w as At}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{d as Tt}from"../packem_shared/command-B6vu47iR.mjs";import{r as ye}from"../packem_shared/wrangler-name-Dsk5K1f-.mjs";import{a as Rt}from"../packem_shared/deploy-target-resolve-BTCW1Iv4.mjs";import{EXIT_CODE as w}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";import{spawn as _t}from"node:child_process";import{randomUUID as er,createHash as Dt}from"node:crypto";import{setTimeout as Pt}from"node:timers/promises";import{toolchainExecArgs as H,detectPackageManager as I,execArgsFor as we}from"@lunora/config/cli";import{f as Ct}from"../packem_shared/free-port-DjbFhaaT.mjs";import{containerBuildTag as Nt}from"@lunora/container";import{a as Ot,i as jt}from"../packem_shared/docker-DpVxvYpL.mjs";import{defaultSpawner as M}from"../packem_shared/createRecordingSpawner-01ZngIwK.mjs";import{r as rr}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{p as It,H as Lt,a as xt,r as Mt}from"../packem_shared/health-probe-Bw9JFfIy.mjs";import{runAdvisor as Ft,openShardAccess as De}from"@lunora/advisor";import{join as S,relative as G,dirname as tr}from"@visulima/path";import{Project as nr,SyntaxKind as p,Node as k}from"ts-morph";import{r as or,c as ar}from"../packem_shared/cloudflare-credentials-BVmZnDZk.mjs";import{runMigrateDataCommand as Ut}from"../packem_shared/runMigrateGenerateCommand-Bd2W9t1k.mjs";import{c as Bt}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{l as Ht}from"../packem_shared/wrangler-secrets-DlSlWvRH.mjs";const Gt=Object.freeze({edges:[],nodes:[],modules:[],unresolved:[],version:1}),qt=20,Pe=e=>`${e.from} -${e.kind}-> ${e.to}`,K=(e,r)=>{const t=new Set(e);return r.filter(n=>!t.has(n)).toSorted((n,o)=>n.localeCompare(o))},Vt=(e,r)=>{const t=e.modules.map(s=>s.name),n=r.modules.map(s=>s.name),o=e.edges.map(s=>Pe(s)),a=r.edges.map(s=>Pe(s));return{addedEdges:K(o,a),addedModules:K(t,n),removedEdges:K(a,o),removedModules:K(n,t)}},J=(e,r,t)=>{if(t.length===0)return[];const n=t.slice(0,qt).map(a=>` ${e} ${a}`),o=t.length-n.length;return[`${r}:`,...n,...o>0?[` … and ${o.toString()} more`]:[]]},Wt=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:
2
2
  ${r.join(`
3
- `)}`},Ut=(e,r)=>k(e,".lunora",r===void 0?"architecture.json":`architecture.${r}.json`),Bt=e=>{if(S(e))try{const r=JSON.parse(A(e,"utf8"));return r.version===1&&Array.isArray(r.modules)&&Array.isArray(r.edges)?r:void 0}catch{return}},Ht=e=>{const{cwd:r,environment:t,logger:n}=e,o=Ut(r,t),a=Bt(o),s=e.current??(a===void 0?void 0:Lt);if(s===void 0)return;const i=a===void 0?void 0:Ft(Mt(a,s));return i!==void 0&&n.info(i),()=>{try{Me(M(o),{recursive:!0}),H(o,`${JSON.stringify(s,void 0,2)}
4
- `,"utf8")}catch(c){n.warn(`could not record the deployed architecture at ${o}: ${c instanceof Error?c.message:String(c)}`)}}},Gt=e=>{const{cwd:r,env:t,logger:n,mintedSecretsFile:o}=e;try{const a=Be(r),s=a?.workerName??fe(r),i=e.url??a?.workerUrl;n.success("deploy complete"),n.info(` worker: ${s??"(see wrangler output above)"}`),t!==void 0&&n.info(` env: ${t}`),i===void 0?n.info(" url: run `lunora link --url <https://your-worker>` to record it"):n.info(` url: ${i}`),o!==void 0&&n.info(` secrets: generated value(s) recorded in ${o}`),e.logsAvailable&&n.info(" logs: lunora logs")}catch{}},qt=/\/index$/u,Vt=/[^\dA-Za-z]/gu,Wt=e=>e.replace(qt,"").split("/").map(r=>r.replaceAll(Vt,"_")),Kt=e=>Wt(e).join("_"),zt=18787,Te=3,rr=12e4,Jt=5e3,re=10,Yt=new Set([".js",".mjs",".mts",".ts",".tsx"]),Xt=/\(void 0\)|is not a function|before initialization|of undefined/u,Qt=e=>typeof e=="object"&&e!==null&&typeof e.functionPath=="string"&&typeof e.message=="string",Zt=e=>{const r=N(e),t=new Map;let n;try{n=Fe(k(e,r),{recursive:!0,encoding:"utf8"})}catch{return t}for(const o of n){const a=Tr(o);Yt.has(a)&&!o.split(ae).some(s=>s==="_generated"||s==="node_modules")&&t.set(Kt(o.slice(0,-a.length).split(ae).join("/")),k(r,o))}return t},en=(e,r)=>{const t=Zt(e),n=new Map;for(const{functionPath:o,message:a}of r){const s=o.lastIndexOf(":"),i=o.slice(0,s),c=`${i}\0${a}`,d=n.get(c)??{exports:[],message:a,namespace:i};d.exports.push(o.slice(s+1)),n.set(c,d)}return[...n.values()].map(({exports:o,message:a,namespace:s})=>{const i=Xt.test(a)?`
5
- hint: if this module is part of a circular import, an import it reads is still undefined while it evaluates`:"";return` ${t.get(s)??s} (${o.join(", ")}): ${a}${i}`})};class _ extends Error{skipped;constructor(r,t=!1){super(r),this.skipped=t}}const rn=(e,r)=>{const t=O(e),n=t===void 0?void 0:D(t).parsed;if(n===void 0)return{hasContainers:!1,main:void 0};const{merged:o}=X(n,r);return{hasContainers:(o.containers??[]).length>0,main:o.main}},tn=({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:a,main:s}=rn(t,n),i=e??s;if(typeof i!="string"||i.startsWith("virtual:")||!S(L(t,i)))return{skip:"the Worker entry is not a file on disk"};if(a)return{skip:"the project declares containers, which `wrangler dev` would build locally before the real container build"};const c=rt(t,process.env,n,r);return c.length===0?{main:i}:{skip:`the Hyperdrive binding ${c.join(", ")} has no local database for wrangler dev`}},nn=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(g=>{throw g instanceof Error&&g.name==="TimeoutError"?new _(`the smoke Worker booted but did not finish evaluating the lazy modules within ${String(rr/1e3)}s — a module may be awaiting something that never settles. Pass --no-smoke-load to ship anyway.`):g});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 a;try{a=JSON.parse(o)}catch{a=void 0}const{checked:s,failures:i,run:c}=a??{};if(typeof s=="number"&&Array.isArray(i)&&i.every(g=>Qt(g)))return c===r?{checked:s,failures:i}:void 0;const d=n.headers.get("content-type")??"no content type",l=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}${l===""?"":`: ${l}`}). 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.`)},ce=(e,r)=>{try{process.kill(-e,r)}catch{}},Re=e=>{try{return process.kill(-e,0),!0}catch{return!1}},on=e=>{const r=()=>{ce(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},te=async e=>{if(e===void 0)return;e.dispose();const{pid:r}=e;ce(r,"SIGTERM");const t=Date.now()+Jt;for(;Re(r)&&Date.now()<t;)await $t(50);Re(r)&&ce(r,"SIGKILL")},an=e=>Cr(e).catch(async r=>{if(!await Pr(e.port))throw r}),sn=(e,{checked:r,failures:t},n)=>{if(t.length===0){n.success(`${String(r)} lazy function(s) evaluate cleanly`);return}const o=en(e,t),a=o.length>re?[` …and ${String(o.length-re)} more module(s)`]:[];throw new _([`${String(t.length)} of ${String(r)} lazy function(s) fail to load:`,...o.slice(0,re),...a,"Fix the module, or pass --no-smoke-load to ship anyway."].join(`
6
- `))},cn=(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
+ `)}`},zt=(e,r)=>y(e,".lunora",r===void 0?"architecture.json":`architecture.${r}.json`),Kt=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}},Jt=e=>{const{cwd:r,environment:t,logger:n}=e,o=zt(r,t),a=Kt(o),s=e.current??(a===void 0?void 0:Gt);if(s===void 0)return;const i=a===void 0?void 0:Wt(Vt(a,s));return i!==void 0&&n.info(i),()=>{try{qe(U(o),{recursive:!0}),V(o,`${JSON.stringify(s,void 0,2)}
4
+ `,"utf8")}catch(c){n.warn(`could not record the deployed architecture at ${o}: ${c instanceof Error?c.message:String(c)}`)}}},Yt=e=>{const{cwd:r,env:t,logger:n,mintedSecretsFile:o}=e;try{const a=We(r),s=a?.workerName??ye(r),i=e.url??a?.workerUrl;n.success("deploy complete"),n.info(` worker: ${s??"(see wrangler output above)"}`),t!==void 0&&n.info(` env: ${t}`),i===void 0?n.info(" url: run `lunora link --url <https://your-worker>` to record it"):n.info(` url: ${i}`),o!==void 0&&n.info(` secrets: generated value(s) recorded in ${o}`),e.logsAvailable&&n.info(" logs: lunora logs")}catch{}},Xt=/\/index$/u,Qt=/[^\dA-Za-z]/gu,Zt=e=>e.replace(Xt,"").split("/").map(r=>r.replaceAll(Qt,"_")),en=e=>Zt(e).join("_"),rn=18787,Ce=3,sr=12e4,tn=5e3,se=10,ir=new Set([".js",".mjs",".mts",".ts",".tsx"]),nn=/\(void 0\)|is not a function|before initialization|of undefined/u,on=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",an=e=>{const r=N(e),t=new Map;let n;try{n=he(y(e,r),{recursive:!0,encoding:"utf8"})}catch{return t}for(const o of n){const a=Or(o);ir.has(a)&&!o.split(B).some(s=>s==="_generated"||s==="node_modules")&&t.set(en(o.slice(0,-a.length).split(B).join("/")),y(r,o))}return t},Ne=e=>nn.test(e)?`
5
+ hint: if this module is part of a circular import, an import it reads is still undefined while it evaluates`:"",sn=(e,r)=>{const t=an(e),n=new Map,o=[];for(const{deferred:a,functionPath:s,message:i}of r){if(a!==void 0){o.push(` ${s.slice(a.length+1)} (${a}): ${i}${Ne(i)}`);continue}const c=s.lastIndexOf(":"),l=s.slice(0,c),d=`${l}\0${i}`,g=n.get(d)??{exports:[],message:i,namespace:l};g.exports.push(s.slice(c+1)),n.set(d,g)}return[...[...n.values()].map(({exports:a,message:s,namespace:i})=>` ${t.get(i)??i} (${a.join(", ")}): ${s}${Ne(s)}`),...o]},Y=e=>{for(const r of ir)for(const t of[`${e}${r}`,y(e,`index${r}`)])if(b(t))return t},cn=(e,r)=>{const t=y(e,r,"_generated"),n=i=>{try{return E(y(t,i),"utf8")}catch{return""}},o=n("app.ts"),a=[],s=(i,c)=>{c!==void 0&&a.push({file:c,kind:i,label:F(e,c).split(B).join("/")})};return o.includes('import("./queues.js")')&&s("queue",Y(y(t,"queues"))),n("workflows.mjs").includes('import("../workflows.js")')&&s("workflow",Y(y(e,r,"workflows"))),(n("agents.mjs").includes('import("../agents.js")')||o.includes('import("../agents.js")'))&&s("agent",Y(y(e,r,"agents"))),a},dn=/\.[cm]?js$/u,ln=/(?:await|=>|return|[=[,])\s*import\(\s*"([^"]+)"\s*\)(?!\s*\.(?!(?:then|catch|finally)\b))/gu,un=(e,r,t)=>{const n=y(e,r,"_generated"),o=new Set(t.map(i=>i.file)),a=[];let s;try{s=he(n).filter(i=>i.endsWith(".mjs")&&i!=="functions.ts")}catch{return a}for(const i of s.toSorted((c,l)=>c.localeCompare(l)))for(const c of E(y(n,i),"utf8").matchAll(ln)){const l=c[1]??"",d=l.startsWith("."),g=d?Y(O(n,l.replace(dn,""))):l;g!==void 0&&!o.has(g)&&(o.add(g),a.push({file:g,kind:"module",label:d?F(e,g).split(B).join("/"):l}))}return a};class _ extends Error{skipped;constructor(r,t=!1){super(r),this.skipped=t}}const gn=(e,r)=>{const t=j(e),n=t===void 0?void 0:D(t).parsed;if(n===void 0)return{hasContainers:!1,main:void 0};const{merged:o}=te(n,r);return{hasContainers:(o.containers??[]).length>0,main:o.main}},fn=({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:a,main:s}=gn(t,n),i=e??s;if(typeof i!="string"||i.startsWith("virtual:")||!b(O(t,i)))return{skip:"the Worker entry is not a file on disk"};if(a)return{skip:"the project declares containers, which `wrangler dev` would build locally before the real container build"};const c=ct(t,process.env,n,r);return c.length===0?{main:i}:{skip:`the Hyperdrive binding ${c.join(", ")} has no local database for wrangler dev`}},hn=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(sr/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 a;try{a=JSON.parse(o)}catch{a=void 0}const{checked:s,deferredChecked:i=0,failures:c,run:l}=a??{};if(typeof s=="number"&&Array.isArray(c)&&c.every(u=>on(u)))return l===r?{checked:s,deferredChecked:i,failures:c}:void 0;const d=n.headers.get("content-type")??"no content type",g=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}${g===""?"":`: ${g}`}). 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.`)},ge=(e,r)=>{try{process.kill(-e,r)}catch{}},Oe=e=>{try{return process.kill(-e,0),!0}catch{return!1}},mn=e=>{const r=()=>{ge(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},ie=async e=>{if(e===void 0)return;e.dispose();const{pid:r}=e;ge(r,"SIGTERM");const t=Date.now()+tn;for(;Oe(r)&&Date.now()<t;)await Pt(50);Oe(r)&&ge(r,"SIGKILL")},vn=e=>xr(e).catch(async r=>{if(!await Mr(e.port))throw r}),pn=(e,{checked:r,deferredChecked:t,failures:n},o)=>{const a=t===0?`${String(r)} lazy function(s)`:`${String(r)} lazy function(s) and ${String(t)} deferred module(s)`;if(n.length===0){o.success(`${a} evaluate cleanly`);return}const s=sn(e,n),i=s.length>se?[` …and ${String(s.length-se)} 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:`,...s.slice(0,se),...i,"Fix the module, or pass --no-smoke-load to ship anyway."].join(`
6
+ `))},yn=(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(`
7
7
  `),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},dn=e=>{try{return Me(k(e,".lunora"),{recursive:!0}),Er(k(e,".lunora","smoke-"))}catch(r){throw new _(`could not create a directory for the check (${r instanceof Error?r.message:String(r)})`,!0)}},ln=async e=>{const{configPath:r,cwd:t,directory:n,environment:o,functionsFile:a,main:s,preferred:i,toolchain:c}=e;try{const d=k(n,"entry.ts"),l=Je();H(d,`export * from ${JSON.stringify(L(t,s))};
9
- import { loadAllFunctions } from ${JSON.stringify(a)};
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},wn=e=>{try{return qe(y(e,".lunora"),{recursive:!0}),Cr(y(e,".lunora","smoke-"))}catch(r){throw new _(`could not create a directory for the check (${r instanceof Error?r.message:String(r)})`,!0)}},kn=async e=>{const{configPath:r,cwd:t,deferred:n,directory:o,environment:a,functionsFile:s,main:i,preferred:c,toolchain:l}=e;try{const d=y(o,"entry.ts"),g=er();V(d,`export * from ${JSON.stringify(O(t,i))};
9
+ ${s===void 0?"":`import { loadAllFunctions } from ${JSON.stringify(s)};
10
+ `}
11
+ const runId = ${JSON.stringify(g)};
10
12
 
11
- const runId = ${JSON.stringify(l)};
13
+ // Deferred event modules, evaluated here so a module that throws on import blocks like a function module does.
14
+ const deferred = [
15
+ ${n.map(v=>` { kind: ${JSON.stringify(v.kind)}, label: ${JSON.stringify(v.label)}, load: () => import(${JSON.stringify(v.file)}) },`).join(`
16
+ `)}
17
+ ];
12
18
 
13
19
  export default {
14
20
  async fetch() {
15
- return Response.json({ ...(await loadAllFunctions()), run: runId });
21
+ const functions = ${s===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();
26
+
27
+ return undefined;
28
+ } catch (error) {
29
+ return { deferred: kind, functionPath: kind + ":" + label, message: error instanceof Error ? error.message : String(error) };
30
+ }
31
+ }),
32
+ );
33
+
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
+ });
16
40
  },
17
41
  };
18
- `);const g=await Et(i),{args:u,command:h}=F(j(t),c.dev({configPath:r===void 0?void 0:ee(t,r),environment:o,extraArgs:[ee(t,d),"--local","--local-protocol","http","--ip","127.0.0.1","--port",String(g),"--persist-to",ee(t,k(n,"state"))]}));return{args:u,command:h,port:g,runId:l}}catch(d){throw new _(`could not prepare the check (${d instanceof Error?d.message:String(d)})`,!0)}},un=async e=>{const{configPath:r,cwd:t,environment:n,launcher:o,logger:a,toolchain:s}=e,i=k(t,N(t),"_generated","functions.ts");if(!S(i)||!A(i,"utf8").includes("export const loadAllFunctions"))return;const c=tn(e);if("skip"in c){a.warn(`smoke-load skipped: ${c.skip}, so lazy modules are not evaluated before deploy`);return}const{main:d}=c,l=[];let g,u;const h=Date.now()+rr,f=process.platform!=="win32",v=(m,E,C)=>{const $=bt(m,[...E],{cwd:C.cwd,detached:f,shell:C.shell,stdio:["ignore","pipe","pipe"]});return f&&$.pid!==void 0&&(u={dispose:on($.pid),pid:$.pid}),$};try{g=dn(t),a.info("smoke-loading lazy function modules in workerd");let m=zt;for(let E=0;E<Te;E+=1){const{args:C,command:$,port:I,runId:T}=await ln({configPath:r,cwd:t,directory:g,environment:n,functionsFile:i,main:d,preferred:m,toolchain:s});m=I+1;const be=await an({args:C,command:$,cwd:t,spawn:o??v,label:"wrangler dev (smoke-load)",notFound:"`wrangler` was not found",onLine:G=>{l.push(G)},port:I,readyTimeoutMs:Math.max(0,h-Date.now()),shell:process.platform==="win32"});if(be===void 0){await te(u),u=void 0;continue}try{const G=await nn(I,T,h);if(G!==void 0){sn(t,G,a);return}}finally{await be.stop(),await te(u),u=void 0}}throw new _(`the smoke port was answered by other runs on all ${String(Te)} attempts`,!0)}catch(m){return cn(m,l,a)}finally{if(await te(u),g!==void 0)try{W(g,{force:!0,recursive:!0})}catch{}}},gn=(e,r)=>r===void 0?e:L(e,r),fn=async e=>{if(e.targets.length===0)return{builtTags:[],code:0};if(!(e.railpackAvailable??Tt)()){const n="deploy blocked: a container uses `image: { build }` (Railpack), but Railpack isn't ready. Install the `railpack` CLI and start a BuildKit instance, e.g. `docker run --rm --privileged -d --name buildkit moby/buildkit` then `export BUILDKIT_HOST=docker-container://buildkit`. Alternatively switch the container's `image` to a Dockerfile path or a pre-built registry reference.";return e.logger.error(n),{builtTags:[],code:1,error:n}}const r=e.spawner??x,t=[];for(const n of e.targets){const o=At(n.exportName),a={args:["build",n.buildDir,"--name",o],command:"railpack",cwd:e.cwd},s=he(j(e.cwd),"wrangler",["containers","push",o]),i={args:s.args,command:s.command,cwd:e.cwd};e.logger.info(`railpack: building "${n.exportName}" → ${o} from ${n.buildDir}`);const c=await r(a);if(c.code!==0){const l=`railpack build failed for container "${n.exportName}" (${n.buildDir})`;return e.logger.error(l),{builtTags:t,code:c.code,error:l}}e.logger.info(`railpack: pushing ${o} to the Cloudflare Registry`);const d=await r(i);if(d.code!==0){const l=`wrangler containers push failed for "${n.exportName}" (${o})`;return e.logger.error(l),{builtTags:t,code:d.code,error:l}}t.push(o)}return{builtTags:t,code:0}},tr=e=>{const t=[O(e),k(e,"package.json"),k(e,"wrangler.dev.jsonc")].filter(n=>n!==void 0&&S(n)).map(n=>[n,A(n,"utf8")]);return()=>{for(const[n,o]of t)A(n,"utf8")!==o&&H(n,o,"utf8")}},hn=(e,r=Je())=>L(e,".lunora",`vite-bundle-meta-${r}.json`),nr="LUNORA_CLIENT_BUILD",mn="virtual:lunora/worker",de=(e,r)=>["ts","mts","cts","js","mjs","cjs"].some(t=>S(k(e,`${r}.config.${t}`))),or=e=>de(e,"rsbuild")?"rsbuild":de(e,"vite")?"vite":void 0,vn=e=>de(e,"vite")?"vite":or(e),pn=e=>{try{const{scripts:r}=JSON.parse(A(k(e,"package.json"),"utf8"));return typeof r?.build=="string"&&r.build!==""}catch{return!1}},Q=(e,r)=>{if(process.env[nr]==="1")return;const t=O(e),n=t===void 0?void 0:D(t).parsed,o=n?.main===mn,a=(o?vn(e):or(e))??(pn(e)?"script":void 0);if(a===void 0)return;const s=r===void 0?void 0:n?.env?.[r]?.assets?.directory,i=n?.assets?.directory??s;return o||Nr(e).class!=="C"||i!==void 0?a:void 0},yn=async(e,r,t)=>{const n=t.spawner??x,o=j(e),a=r==="script"?{args:["run","build"],command:o}:he(o,r,["build"]);t.logger.info(`running ${r} build before bundling the Worker`);const s=tr(e),i=t.bundleMetaPath??hn(e);W(k(e,Or),{force:!0});try{const c=await n({args:a.args,command:a.command,cwd:e,env:{[Mr]:Fr(e),[xr]:t.target,[Lr]:i,...t.lazyFunctions?{[Ir]:"1"}:{},...t.environment===void 0?{}:{CLOUDFLARE_ENV:t.environment},...t.strictAdvisories===!1?{[jr]:"0"}:{},[nr]:"1"},stdoutToStderr:t.outputJson});return c.code===0?void 0:`${r} build failed with exit code ${String(c.code)}`}finally{s(),t.bundleMetaPath===void 0&&W(i,{force:!0})}},Z=(e,r,t)=>r!==!1&&Q(e,t)!==void 0,wn=(e,r,t)=>Z(e,r,t)&&Q(e,t)!=="script",me=e=>{const r=e.frameworkBuild===!1?void 0:Q(e.cwd,e.environment);if(r===void 0||r==="script")return;if(e.apiSpec!==void 0)return`--api-spec is read from the ${r} plugin config when the client build runs; set it there, or pass --no-framework-build`;if(e.target!==void 0)try{ie(e.cwd,e.target)}catch(n){return n instanceof Error?n.message:String(n)}let t;try{t=ie(e.cwd)}catch(n){return`the project's configured target cannot be used, and the ${r} plugin reads it: ${n instanceof Error?n.message:String(n)}`}if(e.target!==void 0&&e.target!==t)return`this run targets "${e.target}", but the project's target is "${t}", which the ${r} plugin reads; set it in the project config, or pass --no-framework-build`},ar=async e=>{const r=e.frameworkBuild===!1?void 0:Q(e.cwd,e.environment);if(r===void 0)return;let t;try{t=e.target??ie(e.cwd)}catch(n){return n instanceof Error?n.message:String(n)}return yn(e.cwd,r,{bundleMetaPath:e.bundleMetaPath,environment:e.environment,strictAdvisories:e.strictAdvisories,lazyFunctions:e.lazyFunctions,logger:e.logger,outputJson:e.outputJson,spawner:e.spawner,target:t})},_e=e=>Array.isArray(e)?e.filter(r=>r!=null):void 0,ve=(e,r)=>{const t=O(e);if(!t)return;const{parsed:n}=D(t);if(n===void 0)return;const{error:o,merged:a}=X(n,r),s=o===void 0?a:n,{containers:i,d1_databases:c,vars:d}=s;return{containers:_e(i),d1_databases:_e(c),vars:typeof d=="object"&&d!==null&&!Array.isArray(d)?d:void 0}},kn=/^127(?:\.\d{1,3}){3}$/,bn=e=>{try{const{hostname:r}=new URL(e);return r==="localhost"||kn.test(r)||r==="::1"||r==="[::1]"}catch{return!1}},Sn=e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"),$n=(e,r,t,n="deploy",o)=>{const a=(ve(e,o)?.containers??[]).filter(i=>typeof i?.image=="string"&&Sn(i.image));if(a.length===0||t())return;const s=`${n} blocked: wrangler.jsonc declares ${String(a.length)} container(s) built from a local Dockerfile, but no Docker-compatible engine is available. Start Docker (or Colima), or point the container's \`image\` at a pre-built registry reference. Note: container images must target linux/amd64.`;return r.error(s),s},pe=e=>S(b(e,Se))?Se:void 0,En=(e,r,t="deploy",n)=>{for(const o of He(e,"lunora",n).containers){const a=o.schedulingPolicy===void 0?o.image:void 0,i=[...a?.kind==="dockerfile"?[{field:"image",path:a.dockerfilePath}]:[],...Object.entries(o.schedulingPolicy==="durable_object"?o.images??{}:{}).flatMap(([c,d])=>d.kind==="dockerfile"?[{field:`images["${c}"]`,path:d.dockerfilePath}]:[])].find(c=>!S(b(e,c.path)));if(i!==void 0){const c=`${t} blocked: container "${o.exportName}" references a Dockerfile at "${i.path}" that does not exist. Create it or fix the \`${i.field}\` path in lunora/containers.ts.`;return r.error(c),c}if(a?.kind==="build"&&!S(b(e,a.buildDir))){const c=`${t} blocked: container "${o.exportName}" references a Railpack build directory "${a.buildDir}" that does not exist. Create it or fix the \`image.build\` path in lunora/containers.ts.`;return r.error(c),c}}},An=(e,r)=>r==="celld"?typeof e=="string"&&e!==$e&&ft(e):r==="cloudflare"&&e===$e,Tn=(e,r,t)=>(ve(e,t)?.d1_databases??[]).find(n=>An(n.database_id,r)),Rn=e=>{if(!e.migrate||e.dryRun||e.preview)return;if(e.migrateUrl===void 0){const t="--migrate requires --migrate-url <https://your-worker> — the deploy target URL is only known after wrangler runs, and this gate runs before it; refusing to default to localhost";return e.logger.error(t),t}if(e.migrateYes!==!0){const t="--migrate runs production data migrations after deploy. Re-run with --migrate-yes to confirm.";return e.logger.error(t),t}const r=e.migrateToken??process.env.LUNORA_ADMIN_TOKEN;if(r===void 0||r===""){const t="admin token required for --migrate — pass --migrate-token or set LUNORA_ADMIN_TOKEN";return e.logger.error(t),t}},_n=(e,r,t,n,o)=>{const a=Tn(e,n,o);if(a===void 0)return;const s=`${t} blocked: the "${a.binding??"<unnamed>"}" D1 binding has a placeholder database_id ("${a.database_id??""}")`,i=n==="celld"?`${s}, which celld would use as the database's identity. Set database_id to the database celld should use, then ${t} again.`:`${s}. Run \`lunora doctor --fix\` to create the database and write its id into wrangler.jsonc, or run \`wrangler d1 create <name>\` and paste the id in yourself.`;return r.error(i),i},Dn=(e,r,t="deploy",n)=>{const o=ve(e,n)?.vars;if(!o)return;const a=Object.entries(o).filter(([,i])=>typeof i=="string"&&bn(i)).map(([i])=>i).toSorted((i,c)=>i.localeCompare(c));if(a.length===0)return;const s=`${t} blocked: ${a.join(", ")} in wrangler.jsonc point at localhost. A deployed Worker can't reach a loopback address, so this silently breaks scheduled-job dispatch, reverse cross-shard relations, and auth callbacks. Set each to the deployed worker's public URL (or move it to a secret with \`wrangler secret put\`) before deploying.`;return r.error(s),s},Cn=["vite.config.ts","vite.config.mts","vite.config.cts","vite.config.js","vite.config.mjs","vite.config.cjs",...Rr],sr=/\.(?:[cm]?[jt]s|tsx|jsx)$/u,ir=/\.(?:test|spec)\.[cm]?[jt]sx?$/u,cr="allowUnauthenticatedShardAccess",Pn=/[\\/]/u,dr=new Set(["_generated","build","dist","node_modules"]),lr=(e,r)=>{const t=U(e,r).split(Pn);return sr.test(r)&&!ir.test(r)&&!se(t.join("/"))&&t.every(n=>n===".."||!n.startsWith(".")&&!dr.has(n))},De=(e,r,t)=>{const{parsed:n}=D(r);if(n===void 0)return[];const{error:o,merged:a}=X(n,t),{main:s}=o===void 0?a:n,i=typeof s=="string"?b(Xe(r),s):void 0;return i!==void 0&&S(i)&&lr(e,i)?[i]:[]},ye=e=>e===void 0?!1:e.getKind()===p.FalseKeyword?!0:w.isParenthesizedExpression(e)||w.isAsExpression(e)||w.isSatisfiesExpression(e)||w.isTypeAssertion(e)||w.isNonNullExpression(e)?ye(e.getExpression()):!1,Nn=e=>{try{return Ue(e).isFile()}catch{return!1}},On=new Set(["ELOOP","ENOENT","ENOTDIR"]),K=(e,r,t)=>{const n=r instanceof Error&&"code"in r&&typeof r.code=="string"?r.code:"";On.has(n)||t.push(e)},jn=(e,r)=>{try{return Ue(e)}catch(t){K(e,t,r);return}},ur=(e,r)=>{try{return A(e,"utf8")}catch(t){K(e,t,r);return}},gr=(e,r,t,n=new Set)=>{let o;try{o=Ar(r)}catch(s){return K(r,s,t),[]}if(n.has(o))return[];n.add(o);let a;try{a=Fe(r)}catch(s){return K(r,s,t),[]}return a.flatMap(s=>{const i=b(r,s),c=jn(i,t);if(c===void 0)return[];const d=U(e,i).split(ae).join("/");return c.isDirectory()?dr.has(s)||s.startsWith(".")||se(`${d}/`)?[]:gr(e,i,t,n):c.isFile()&&sr.test(s)&&!ir.test(s)&&!se(d)?[i]:[]})},In=e=>{const r=w.isComputedPropertyName(e)?e.getExpression():e;return w.isStringLiteral(r)||w.isNoSubstitutionTemplateLiteral(r)?r.getLiteralValue():e.getText()},ne=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],Ln=/\.(?:[cm]?js|jsx)$/u,xn=(e,r)=>{if(!r.startsWith("."))return;const t=L(Xe(e),r),n=t.replace(Ln,"");return[t,...ne.map(a=>`${t}${a}`),...ne.map(a=>b(t,`index${a}`)),...ne.map(a=>`${n}${a}`)].find(a=>Nn(a))},Mn=e=>{if(e.getExpression().getText()!=="require")return;const[r]=e.getArguments();return r!==void 0&&(w.isStringLiteral(r)||w.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},Fn=e=>{const r=e.getModuleReference();if(!w.isExternalModuleReference(r))return;const t=r.getExpression();return w.isStringLiteral(t)?t.getLiteralValue():void 0},Un=(e,r,t,n)=>{const o=new Set(e),a=[...e],s=[];for(let i=0;i<a.length;i+=1){const c=a[i]??"",d=ur(c,n);if(d===void 0)continue;const l=r.createSourceFile(U(t,c),d,{overwrite:!0}),g=[...l.getImportDeclarations().map(u=>u.getModuleSpecifierValue()),...l.getExportDeclarations().map(u=>u.getModuleSpecifierValue()),...l.getDescendantsOfKind(p.ImportEqualsDeclaration).map(u=>Fn(u)),...l.getDescendantsOfKind(p.CallExpression).map(u=>Mn(u))].filter(u=>u!==void 0);for(const u of g){const h=xn(c,u);h!==void 0&&lr(t,h)&&!o.has(h)&&(o.add(h),s.push(h),a.push(h))}}return s},Bn=e=>{const r=e.getArgumentExpression();return r!==void 0&&(w.isStringLiteral(r)||w.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},Hn=e=>w.isPropertyAccessExpression(e)?e.getName():w.isElementAccessExpression(e)?Bn(e):void 0,Gn=new Set([p.AmpersandAmpersandEqualsToken,p.AmpersandEqualsToken,p.AsteriskAsteriskEqualsToken,p.AsteriskEqualsToken,p.BarBarEqualsToken,p.BarEqualsToken,p.CaretEqualsToken,p.EqualsToken,p.GreaterThanGreaterThanEqualsToken,p.GreaterThanGreaterThanGreaterThanEqualsToken,p.LessThanLessThanEqualsToken,p.MinusEqualsToken,p.PercentEqualsToken,p.PlusEqualsToken,p.QuestionQuestionEqualsToken,p.SlashEqualsToken]),qn=e=>{const r=e.getOperatorToken().getKind();return!Gn.has(r)||Hn(e.getLeft())!==cr?!1:r!==p.EqualsToken||!ye(e.getRight())},Vn=(e,r,t)=>{const n=[],o=[...new Set([N(e),"src"])].filter(g=>S(b(e,g))),a=O(e),s=[...Cn.map(g=>b(e,g)).filter(g=>S(g)),...a===void 0?[]:De(e,a,r),...t.flatMap(g=>De(e,g,r))],i=new Qe({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}),c=o.flatMap(g=>gr(b(e,g),b(e,g),n));return{sites:[...new Set([...c,...s,...Un([...s,...c],i,e,n)])].flatMap(g=>{const u=ur(g,n);if(u===void 0)return[];const h=i.createSourceFile(U(e,g),u,{overwrite:!0}),f=[...h.getDescendantsOfKind(p.PropertyAssignment),...h.getDescendantsOfKind(p.ShorthandPropertyAssignment),...h.getDescendantsOfKind(p.GetAccessor),...h.getDescendantsOfKind(p.MethodDeclaration)].filter(m=>{const E=w.isPropertyAssignment(m)&&ye(m.getInitializer());return In(m.getNameNode())===cr&&!E}).map(m=>m.getStartLineNumber()),v=h.getDescendantsOfKind(p.BinaryExpression).filter(m=>qn(m)).map(m=>m.getStartLineNumber());return[...f,...v].map(m=>({file:U(e,g),line:m}))}),unreadable:n}},Wn=(e,r,t,n,o,a)=>{if(t!=="deploy")return;const{sites:s,unreadable:i}=Vn(e,o,a),c=Nt({openShardAccess:s,schema:{tables:[]}},{lints:[Ee]});if(c.length===0&&i.length===0)return;const d=[];if(c.length>0){const g=c.map(u=>`${String(u.metadata.file)}:${String(u.metadata.line)}`).join(", ");d.push(`${g} enable the open-shard option (any value but a literal false), so any caller may target any shard.`)}if(i.length>0&&d.push(`could not read ${i.join(", ")}, so the open-shard option cannot be ruled out there.`),n){r.warn(`deploying past the open-shard gate (--allow-open-shards): ${d.join(" ")}`);return}const l=`deploy blocked (open_shard_access): ${d.join(" ")} ${Ee.remediation}`;return r.error(l),l},Kn=(e,r,t,n)=>{const o=Wn(e,r.logger,t,r.allowOpenShards===!0,r.env,n);return o===void 0?void 0:{code:y.USAGE,error:o}},zn=(e,r,t,n)=>{const o=_n(e,r.logger,t,n,r.env);if(o!==void 0)return{code:y.USAGE,error:o};const a=Dn(e,r.logger,t,r.env);if(a!==void 0)return{code:y.USAGE,error:a};const s=En(e,r.logger,t,r.discoveryCache);if(s!==void 0)return{code:y.USAGE,error:s};const i=$n(e,r.logger,r.dockerAvailable??Rt,t,r.env);return i===void 0?void 0:{code:y.MISSING_DEPENDENCY,error:i}},Ce=32,fr=15e3,Jn=5432,Yn=3306,Xn=/[^a-z0-9-]/gu,Qn=/[^A-Za-z0-9]/gu,Zn=/-$/u,B=e=>`LUNORA_${e.replaceAll(Qn,"_").toUpperCase()}_URL`,eo=e=>{const r=new Map;for(const t of e){const n=B(t),o=r.get(n);if(o!==void 0)return{bindings:[o,t],variable:n};r.set(n,t)}},Pe=7,ro=(e,r)=>{const t=`${e}-${r}`.toLowerCase(),n=t.replaceAll(Xn,"-");if(n===t&&n.length<=Ce)return n;const o=St("sha256").update(t).digest("hex").slice(0,Pe-1);return`${n.slice(0,Ce-Pe).replace(Zn,"")}-${o}`},Ne=e=>e==="postgresql"?"postgres":e==="mariadb"?"mysql":e,to=e=>e==="mysql"?Yn:Jn,no=e=>{try{const r=new URL(e),t=r.protocol.slice(0,-1),n=decodeURIComponent(r.pathname.slice(1));return!["mariadb","mysql","postgres","postgresql"].includes(t)||r.hostname===""||n===""?void 0:{database:n,host:r.hostname,password:decodeURIComponent(r.password),port:r.port===""?to(Ne(t)):Number(r.port),scheme:Ne(t),user:decodeURIComponent(r.username)}}catch{return}},oo=(e,r)=>{const t=typeof r?.password=="string"?r.password:"",n=t===""?[]:[t,JSON.stringify(t).slice(1,-1),encodeURIComponent(t)];let o=e;for(const a of n)o=o.replaceAll(a,"<redacted>");return o.split(" ").map(a=>a.includes("://")?"<url>":a).join(" ")},hr=e=>(Array.isArray(e)?e:[]).flatMap((r,t)=>{const{binding:n,id:o}=typeof r=="object"&&r!==null?r:{};return typeof n=="string"&&o===We?[{binding:n,index:t}]:[]}),z=e=>{let r="";try{const{errors:t}=JSON.parse(e.text);r=(t??[]).flatMap(n=>typeof n.message=="string"?[n.message]:[]).slice(0,2).join("; ")}catch{}return r===""?`HTTP ${String(e.status)}`:`HTTP ${String(e.status)}: ${r}`},ao=e=>typeof e=="string"||typeof e=="number"?e.toString():void 0,so=["scheme","host","port","database","user"],io=e=>e==="postgresql"?"postgres":e,Oe=(e,r)=>{const t=ao(r);return e==="scheme"?io(t):t},je=50,co=async(e,r)=>{for(let t=1;t<=je;t+=1){const n=await e(t===1?"/hyperdrive/configs":`/hyperdrive/configs?page=${String(t)}`);if(!n.ok)throw new Error(`listing Hyperdrive configs failed (${z(n)})`);if(!Array.isArray(n.body.result))throw new TypeError("the listing of Hyperdrive configs had no result list");const o=n.body.result.find(s=>s.name===r),a=typeof n.body.result_info=="object"&&n.body.result_info!==null?n.body.result_info:{};if(o!==void 0||typeof a.total_pages!="number"||t>=a.total_pages)return o}throw new Error(`the listing of Hyperdrive configs has more than ${String(je)} pages, so "${r}" can't be shown to be absent`)},lo=async(e,r,t,n)=>{const o=n?{caching:{disabled:!0}}:{},a=await co(e,r);if(typeof a?.id=="string"){const c=so.filter(l=>Oe(l,a.origin?.[l])!==Oe(l,t[l]));if(c.length>0)throw new Error(`a Hyperdrive config named "${r}" already exists for a different origin, or one that can't be confirmed (${c.join(", ")}). Delete it, or rename the Worker, so the binding does not reach the wrong database.`);const d=await e(`/hyperdrive/configs/${encodeURIComponent(a.id)}`,{body:JSON.stringify({origin:t,...o}),method:"PATCH"});if(!d.ok)throw new Error(`updating its credentials failed (${z(d)})`);return{id:a.id,reused:!0}}const s=await e("/hyperdrive/configs",{body:JSON.stringify({name:r,origin:t,...o}),method:"POST"});if(!s.ok)throw new Error(`creating it failed (${z(s)})`);const{id:i}=typeof s.body.result=="object"&&s.body.result!==null?s.body.result:{};if(typeof i!="string")throw new TypeError("the response carried no id");return{id:i,reused:!1}},uo=(e,r,t,n)=>r===void 0&&n?`${B(e)} is set but is not a usable connection string for the "${e}" Hyperdrive binding: it needs a postgres://, postgresql:// or mysql:// scheme, a host and a database name, with any special characters percent-encoded.`:r===void 0?`the "${e}" Hyperdrive binding has no config yet. Set ${B(e)} to its postgres:// or mysql:// connection string and Lunora creates the config, or run \`wrangler hyperdrive create\` and put its id in wrangler.jsonc.`:t?void 0:`creating the "${e}" Hyperdrive config needs CLOUDFLARE_API_TOKEN (Hyperdrive: Edit) and CLOUDFLARE_ACCOUNT_ID, or run \`wrangler hyperdrive create\` and put its id in wrangler.jsonc.`,go=async(e,r)=>{const t=ro(e.workerName,e.binding),{id:n,reused:o}=await lo(async(a,s)=>er({accountId:e.accountId,apiToken:e.token,...e.fetch===void 0?{}:{fetch:e.fetch},init:{...s,signal:AbortSignal.timeout(fr)},path:a}),t,e.origin,e.disableCaching);return e.logger.success(`${o?"reusing":"created"} Hyperdrive config "${t}" for ${e.binding} → ${e.wranglerPath}`),{id:n,text:Ke(r,[...e.path,e.index,"id"],n)}},fo=e=>e===void 0||e===""?void 0:e,mr=e=>{const r=k(M(e),".wrangler","deploy","config.json");try{const{configPath:t}=JSON.parse(A(r,"utf8"));return typeof t=="string"?L(M(r),t):void 0}catch{return}},ho=(e,r,t,n,o)=>{const a=mr(e);if(a===void 0||a===e)return;if(n.built!==n.deployed){o.warn(`the build output ${a} was made for ${n.built===void 0?"the default environment":`"${n.built}"`}, not ${n.deployed===void 0?"the default environment":`"${n.deployed}"`}, so the "${r}" Hyperdrive id was not written there. Build with CLOUDFLARE_ENV set to the environment you deploy, then deploy again.`);return}let s;try{s=D(a)}catch{return}const i=hr(s.parsed?.hyperdrive).find(c=>c.binding===r);i!==void 0&&H(a,Ke(s.text,["hyperdrive",i.index,"id"],t),"utf8")},mo=(e,r)=>{const t=typeof e.name=="string"&&e.name!==""?e.name:"lunora";if(r===void 0)return t;const n=e.env?.[r]?.name;return typeof n=="string"&&n!==""?n:`${t}-${r}`},we=(e,r)=>{const t=O(e),n=t===void 0?void 0:D(t).parsed;if(t===void 0||n===void 0)return;const o=r===void 0?void 0:n.env?.[r],a=hr(r===void 0?n.hyperdrive:o?.hyperdrive);return a.length===0?void 0:{accountId:o?.account_id??n.account_id,entries:a,path:r===void 0?["hyperdrive"]:["env",r,"hyperdrive"],workerName:mo(n,r),wranglerPath:t}},vo=(e,r,t)=>{const n=eo(e.map(({binding:o})=>o));if(n!==void 0){const o=`deploy blocked: the Hyperdrive bindings ${n.bindings.map(a=>`"${a}"`).join(" and ")} both read ${n.variable} and would share one config. Rename one so their names differ in letters or digits, not only in punctuation.`;return t.logger.error(o),o}for(const{binding:o,origin:a,supplied:s}of e){const i=uo(o,a,r,s);if(i!==void 0&&t.dryRun===!0)t.logger.warn(`dry run: ${i} A real deploy stops here.`);else if(i!==void 0){const c=`deploy blocked: ${i}`;return t.logger.error(c),c}}},po=async(e,r,t,n)=>{let o;try{o=await e(`/hyperdrive/configs/${encodeURIComponent(t)}`)}catch(s){n.warn(`could not check whether the "${r}" Hyperdrive config has query caching off (${s instanceof Error?s.message:String(s)}).`);return}if(!o.ok){n.warn(`could not check whether the "${r}" Hyperdrive config has query caching off (${z(o)}).`);return}const{caching:a}=typeof o.body.result=="object"&&o.body.result!==null?o.body.result:{};a?.disabled!==!0&&n.warn(`the "${r}" Hyperdrive config has query caching on, so .global() tables would read rows up to 75 s old. Run \`wrangler hyperdrive update ${t} --caching-disabled\`.`)},yo=async(e,r)=>{const t=O(e.cwd),n=t===void 0?void 0:D(t).parsed,o=e.wranglerEnvironment===void 0?n:n?.env?.[e.wranglerEnvironment],{accountId:a,token:s}=Ze(r,o?.account_id??n?.account_id);if(a===void 0||s===void 0)return;const i=async(c,d)=>er({accountId:a,apiToken:s,...e.fetch===void 0?{}:{fetch:e.fetch},init:{...d,signal:AbortSignal.timeout(fr)},path:c});for(const c of Array.isArray(o?.hyperdrive)?o.hyperdrive:[]){const{binding:d,id:l}=typeof c=="object"&&c!==null?c:{};typeof d=="string"&&typeof l=="string"&&l!==We&&await po(i,d,l,e.logger)}},wo=async e=>{const r=e.environment??process.env;e.disableCaching===!0&&e.checkOnly!==!0&&e.dryRun!==!0&&await yo(e,r);const t=we(e.cwd,e.wranglerEnvironment);if(t===void 0)return;const{entries:n,path:o,wranglerPath:a}=t,{accountId:s,token:i}=Ze(r,t.accountId),c=n.map(({binding:l})=>{const g=r[B(l)]??"";return{binding:l,origin:no(g),supplied:g!==""}}),d=vo(c,i!==void 0&&s!==void 0,e);if(d!==void 0)return d;if(!(e.dryRun===!0||e.checkOnly===!0))for(const[l,{binding:g,index:u}]of n.entries()){const h=c[l]?.origin;if(!(h===void 0||i===void 0||s===void 0))try{const{id:f,text:v}=await go({accountId:s,binding:g,disableCaching:e.disableCaching===!0,fetch:e.fetch,index:u,logger:e.logger,origin:h,path:o,token:i,workerName:t.workerName,wranglerPath:a},A(a,"utf8"));H(a,v,"utf8"),ho(a,g,f,{built:fo(r.CLOUDFLARE_ENV),deployed:e.wranglerEnvironment},e.logger)}catch(f){const v=f instanceof Error?f.message:String(f),m=`deploy blocked: the "${g}" Hyperdrive config could not be set up: ${oo(v,c[l]?.origin)}`;return e.logger.error(m),m}}},ko=(e,r)=>{const t=we(e,r.env)?.entries[0]?.binding;if(t===void 0)return;const n=`prepare blocked: the "${t}" Hyperdrive binding still has its placeholder id. Run \`lunora deploy\` with ${B(t)} set to create the config, or put the id from \`wrangler hyperdrive create\` in wrangler.jsonc.`;return r.logger.error(n),n},bo=(e,r)=>{const t=we(e,r.env)?.entries[0]?.binding;if(t===void 0)return;const n=`deploy blocked: the "${t}" Hyperdrive binding has no config, and a --temporary deploy cannot create one: it would be made in your account while the Worker goes to a temporary one, which a temporary account has no database for. Deploy without --temporary.`;return r.logger.error(n),n},vr=async(e,r,t,n,o="create")=>{if(n!=="cloudflare")return;if(t==="prepare")return ko(e,r);if(r.temporary===!0)return bo(e,r);const a=r.clientBuildEnvironment===void 0?void 0:{...process.env,CLOUDFLARE_ENV:r.clientBuildEnvironment},s=ue(e,N(e),r.discoveryCache);return s.error!==void 0&&r.logger.warn(`could not read the schema (${s.error}), so Hyperdrive configs are set up with query caching off.`),wo({checkOnly:o==="check",cwd:e,disableCaching:s.error!==void 0||s.info?.hasHyperdriveGlobalTable===!0,dryRun:r.dryRun,environment:a,logger:r.logger,wranglerEnvironment:r.env})},So=/https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u,$o=/https:\/\/[^\s"'<>]+/u,Eo=e=>{if(e===void 0)return;const r=So.exec(e);return r?r[0]:$o.exec(e)?.[0]},Ie=e=>e===void 0?"":` (--env ${e})`,Ao=({cwd:e,env:r,logger:t,now:n,url:o})=>{if(o!==void 0)try{const a=Be(e);if(a!==void 0){if(a.workerUrl===o&&a.env===r)return;t.warn(`link: .lunora/project.json records ${a.workerUrl??"(no url)"}${Ie(a.env)}, but this deploy published ${o}${Ie(r)}. Keeping the recorded value — run \`lunora link --url ${o}${r===void 0?"":` --env ${r}`}\` to update it.`);return}const s=(n??(()=>new Date().toISOString()))();Ur(e,{env:r,linkedAt:s,workerName:fe(e),workerUrl:o}),t.success(`link: recorded ${o} in .lunora/project.json (run \`lunora link\` to change)`)}catch{}},To=async(e,r)=>{const t=new Qe({skipAddingFilesFromTsConfig:!0}),n=b(r,"lunora");let o;try{o=_r(t,n)}catch(a){const s=a instanceof Error?a.message:String(a);return e.logger.warn(`--migrate: could not discover migrations (${s}); skipping`),0}if(o.length===0)return e.logger.info("--migrate: no data migrations declared in lunora/"),0;e.logger.info(`--migrate: running ${String(o.length)} migration(s) against deployed worker`);for(const a of o){e.logger.info(`--migrate: up "${a.id}" (table "${a.table}")`);const s={cwd:r,fetchImpl:e.fetchImpl,id:a.id,logger:e.logger,prod:!0,subcommand:"up",token:e.migrateToken,url:e.migrateUrl,yes:e.migrateYes===!0},i=await Ot(s);if(i.code!==0)return e.logger.error(`--migrate: migration "${a.id}" failed — see output above`),i.code;e.logger.success(`--migrate: "${a.id}" applied`)}return 0},Ro=async(e,r)=>{const{info:t}=ue(r,"lunora",e.discoveryCache),n=t?.vectorMetadata??[];if(n.length===0)return;const o=[];for(const i of n){const c=ht(i.kind);if(c===void 0){e.logger.warn(`vector index "${i.index}" declares metadata "${i.property}", whose column type cannot be filtered on in Vectorize — it is stored with each vector but no filter will match it.`);continue}o.push({index:i.index,property:i.property,type:c})}if(o.length===0)return;const s=(await mt({cwd:r,entries:o,exec:he(j(r),"wrangler",[]),logger:e.logger,spawner:e.spawner??x})).filter(i=>i.status!=="failed").length;s>0&&e.logger.success(`vectorize metadata indexes ready: ${String(s)}/${String(o.length)}`)},Le=5,_o=2e3,Do=async(e,r,t)=>{if(e.healthCheck!==!0)return;const n=t??Ye({cwd:r,env:e.env});if(n===void 0){const a="--health-check: the deploy succeeded, but no URL to probe could be resolved — wrangler's output carried none and this checkout has no link for this environment. Run `lunora link --url <https://your-worker>` and re-deploy, or drop --health-check.";return e.logger.error(a),{error:a,ok:!1,url:""}}const o=await _t({attempts:Le,baseUrl:n,delayMs:_o,fetchImpl:e.healthFetch,paths:[Dt,Ct],sleep:e.healthSleep});return o.error===void 0?(e.logger.success(`health check ok (${o.url})`),{ok:!0,url:o.url}):(e.logger.error(`--health-check: the deploy succeeded, but the new version did not answer after ${String(Le)} attempt(s) — ${o.error}`),{error:o.error,ok:!1,url:o.url})},Co=async(e,r,t,n,o,a)=>{await Ro(e,r);const s=e.migrate?await To(e,r):0;return s===0&&o?.(),{code:s,descriptor:t,mintedSecretsFile:a,validation:n}},Po=async({cwd:e,descriptor:r,mintedSecretsFile:t,options:n,reblessSchemaBaseline:o,recordArchitecture:a,stdout:s,validation:i})=>{const c={deployedAt:new Date().toISOString(),dryRun:n.dryRun===!0,env:n.env,preview:n.preview===!0,url:n.dryRun===!0?void 0:Eo(s),workerName:fe(e)};if(n.dryRun===!0||n.preview===!0)return n.healthCheck===!0&&n.logger.warn(`--health-check skipped: ${n.dryRun===!0?"a dry run publishes nothing":"a preview version serves no live traffic"}`),{code:0,deployment:c,descriptor:r,mintedSecretsFile:t,validation:i};n.temporary!==!0&&(a?.(),Ao({cwd:e,env:n.env,logger:n.logger,url:c.url}));const d=await Do(n,e,c.url);return d?.error!==void 0?{code:y.UNAVAILABLE,deployment:c,descriptor:r,healthCheck:d,mintedSecretsFile:t,validation:i}:{...await Co(n,e,r,i,o,t),deployment:c,healthCheck:d}},No=(e,r,t)=>{const n=b(e,P);if(!S(n))return;let o;try{o=Ge(A(n,"utf8")).length}catch{return}if(o===0)return;const a=t.toolchain?.secretPut!==void 0;r.warn(a?`Note: \`lunora deploy\` does not push secrets. ${P} has ${String(o)} key(s); if you changed them, run \`lunora env push --yes\` to update the deployed secrets.`:`Note: ${t.name} deploys read no secrets. ${P} has ${String(o)} key(s) that only the dev server sees; a key the app reads from env must be a \`vars\` entry in the deployed config, one it loads from a secret manager at runtime need not.`)},pr=async(e,r)=>{let t=[];try{t=Br(await qe({cache:r,projectRoot:e,schemaDir:N(e)}))}catch{}const n=[...new Set(Hr(t).map(a=>a.key))];let o=[];try{const a=b(e,P);S(a)&&(o=Ge(A(a,"utf8")).map(s=>s.key).filter(s=>ze(s)))}catch{}return{fromLocal:o.filter(a=>!n.includes(a)),fromPackages:n,mintableKeys:Gr(t)}},Oo=async(e,r,t,n)=>{const{logger:o}=r,a=r.spawner??x,s=j(e),i=r.env===void 0?"":` --env ${r.env}`,c=n.toolchain?.secretPut;if(c===void 0)return o.error(`deploy target "${n.id}" has no secret store; cannot push secrets`),{minted:[],ok:!1};const d=t.map(u=>({key:u,value:qr()})),l=n.toolchain?.secretBulk;if(l!==void 0&&d.length>=2){const u=F(s,l({environment:r.env,temporary:r.temporary})),h=await a({args:u.args,command:u.command,cwd:e,input:JSON.stringify(Object.fromEntries(d.map(f=>[f.key,f.value])))});if(h.code===0){for(const{key:f}of d)o.success(`generated + pushed ${f}`);return{minted:d,ok:!0}}o.warn(`bulk secret push failed (exit ${String(h.code)}); retrying one key at a time`)}const g=[];for(const{key:u,value:h}of d){const f=c({environment:r.env,key:u,temporary:r.temporary}),v=F(s,f),m=await a({args:v.args,command:v.command,cwd:e,input:h});if(m.code!==0)return o.error(`failed to push secret ${u} (exit ${String(m.code)}); set it manually with \`wrangler secret put ${u}${i}\`.`),{minted:g,ok:!1};g.push({key:u,value:h}),o.success(`generated + pushed ${u}`)}return{minted:g,ok:!0}},jo=/^[\w-]+$/u,xe=[".dev.vars",".dev.vars.*","!.dev.vars.example"],Io=(e,r)=>{try{const t=zr(e,xe);t.length>0&&r.info(`.gitignore: added ${t.join(", ")} so the recorded secret cannot be committed`)}catch(t){r.warn(`could not update .gitignore (${t instanceof Error?t.message:String(t)}) — add \`${xe.join("` and `")}\` by hand before committing.`)}},Lo=(e,r,t)=>{if(t.length===0)return;const n=t.map(i=>i.key).join(", ");if(r.env!==void 0&&!jo.test(r.env)){r.logger.warn(`${n}: minted and pushed for --env ${r.env}, but "${r.env}" isn't a safe filename fragment — the value could not be recorded. Capture it manually if you need it again.`);return}const o=r.env===void 0?P:`${P}.${r.env}`;Io(e,r.logger);const a=b(e,o);let s=S(a)?A(a,"utf8"):"";for(const i of t)s=Vr(s,i.key,i.value);return Wr(a,s),r.logger.success(r.env===void 0?`${n}: value(s) recorded in ${o}`:`${n}: value(s) recorded in ${o} (kept separate from ${P} so \`lunora dev\` and a plain \`lunora env push\` don't inherit the --env ${r.env} value)`),o},xo=/^<[^>]+>$/u,Mo=async(e,r,t)=>{let n;try{n=t.projectConfig?.(e,"deploy").vars??{}}catch(l){return{error:l instanceof Error?l.message:String(l)}}const o=l=>{const g=n[l];if(typeof g!="string")return!0;const u=g.trim();return u===""||xo.test(u)?!0:ze(l)&&Kr(g)},a=l=>Object.hasOwn(n,l)?`${l} (empty or a placeholder)`:l,{fromLocal:s,fromPackages:i}=await pr(e,r.discoveryCache),c=s.filter(l=>o(l));c.length>0&&r.logger.warn(`${P} key(s) not set in the wrangler vars: ${c.map(l=>a(l)).join(", ")}. ${t.name} has no secret store: a key the app reads from env must be a \`vars\` entry; one it loads from a secret manager at runtime need not.`);const d=i.filter(l=>o(l));return d.length===0?{}:{error:`missing required secret(s) in the wrangler vars: ${d.map(l=>a(l)).join(", ")}. ${t.name} has no secret store and Lunora reads these from env, so each must be a real \`vars\` value in the config the deploy ships — write it there from your secret manager at deploy time rather than committing it. Add them, then re-deploy.`}},Fo=async(e,r,t,n)=>{if(r.dryRun===!0||r.preview===!0)return{};if(n.toolchain?.secretList===void 0)return Mo(e,r,n);const{logger:o}=r,a=r.env===void 0?"":` --env ${r.env}`;let s;try{s=await(r.secretLister??It)({cwd:e,env:r.env,target:n.id,temporary:r.temporary})}catch{return{}}if(!s.ok)return{};const i=new Set(s.names),{fromLocal:c,fromPackages:d,mintableKeys:l}=await pr(e,r.discoveryCache),g=[...d,...c].filter(f=>!i.has(f));if(g.length===0)return{};if(!t)return{error:`missing required secret(s) on the deploy target: ${g.join(", ")}. Set them with \`wrangler secret put <KEY>${a}\` (or \`lunora env generate --set\` then \`lunora env push --yes${a}\`), then re-deploy.`};for(const f of g.filter(v=>!l.has(v)))o.warn(`required secret ${f} is not set on the target — set it with: wrangler secret put ${f}${a}`);const u=g.filter(f=>l.has(f));if(u.length===0)return{};if(await(r.secretConfirm??jt())(`${String(u.length)} required secret(s) not set on the target (${u.join(", ")}). Generate strong values and push them now?`)){const{minted:f,ok:v}=await Oo(e,r,u,n),m=Lo(e,r,f);return v?{mintedSecretsFile:m}:{error:"failed to push required secret(s) — set them manually and re-deploy",mintedSecretsFile:m}}return o.warn(`${String(u.length)} required secret(s) not set on the target: ${u.join(", ")}. Generate + push with \`lunora env generate --set\` then \`lunora env push --yes${a}\`.`),{}},yr=e=>e.format==="json"?!1:e.interactive!==void 0?e.interactive:process.stdout.isTTY&&!process.env.CI,Uo=async(e,r)=>{if(r.dryRun===!0)return;const t=He(e,"lunora",r.discoveryCache).containers.flatMap(o=>o.schedulingPolicy===void 0&&o.image.kind==="build"?[{buildDir:o.image.buildDir,exportName:o.exportName}]:[]);if(t.length===0)return;const n=await fn({cwd:e,logger:r.logger,railpackAvailable:r.railpackAvailable,spawner:r.spawner,targets:t});return n.code===0?void 0:n.error??"railpack build failed"},Bo=(e,r,t)=>{if(t!==void 0)try{const n=it(e,t);n.changed&&r.success(`synced ${String(t.length)} cron trigger(s) → ${n.wranglerPath??"wrangler.jsonc"}`);for(const a of n.warnings)r.warn(a);const o=ct(n.preserved);o!==void 0&&r.info(o)}catch(n){const o=n instanceof Error?n.message:String(n);r.warn(`cron trigger sync skipped: ${o}`)}},Ho=async(e,r,t,n,o,a)=>{try{Y(n);const s=await qe({cache:a,projectRoot:e,schemaDir:N(e)}),i=at(e,s,{environment:o,target:n}),c=i.wranglerPath??"wrangler.jsonc";if(i.added.length>0&&r.success(`provisioned bindings: ${i.added.join(", ")} → ${c}`),i.updated.length>0&&r.success(`updated bindings: ${i.updated.join(", ")} → ${c}`),i.devConfig!==void 0){const{added:d,path:l,updated:g}=i.devConfig;r.success(`dev sidecar bindings: ${[...d,...g].join(", ")} → ${l}`)}for(const d of i.warnings)r.warn(d)}catch(s){const i=s instanceof Error?s.message:String(s);r.warn(`binding inference skipped: ${i}`)}try{const s=st(e);s.changed&&r.success(`bumped compatibility_date to ${s.date??"unknown"} (Workers Cache enabled) → ${s.wranglerPath??"wrangler.jsonc"}`)}catch(s){const i=s instanceof Error?s.message:String(s);r.warn(`compatibility date sync skipped: ${i}`)}Bo(e,r,t)},Go=async(e,r,t,n,o,a,s,i,c,d)=>{let l;r?(l=new dt({name:"dots"}),l.start("running codegen")):t.info("running codegen");try{const g=Dr({apiSpec:n,dryRun:!d,lazyFunctions:o,projectRoot:e,target:a,...ot(e)});l?.succeed("codegen complete"),l||t.success("codegen complete");const u=lt(g.platformDiagnostics,t);if(u.errors.length>0)return{error:u.errors.join("; ")};const{errorAdvisories:h,names:f,shouldBlock:v}=ut(g.advisories,c);if(v){const E=`${h.length.toString()} ERROR-level ${h.length===1?"advisory":"advisories"} (${f.join(", ")}). Pass --no-strict-advisories to downgrade this to a warning and continue.`;return t.error(E),{error:E}}const m=d?await Zr({cwd:e,logger:t,spawner:s,stdoutToStderr:i}):void 0;return m?.error!==void 0?{error:m.error}:{result:g}}catch(g){l?.failed("codegen failed");const u=g instanceof Error?g.message:String(g);return t.error(`codegen failed: ${u}`),{error:`codegen failed: ${u}`}}},qo=(e,r)=>({dryRun:r.dryRun,entry:pe(e),environment:r.env,outDir:r.outDir,preview:r.preview,temporary:r.temporary}),wr=(e,r,t)=>{const{toolchain:n}=t;if(n===void 0)throw new Error(`deploy target "${t.id}" has no command-line toolchain`);const o=qo(e,r);return Ve(t,e,"deploy",a=>n.deploy({...o,configPath:a}))},Vo=(e,r,t)=>{const n=wr(e,r,t),o=pe(e);return o!==void 0&&r.logger.info(`class-B composition: deploying ${o} (overrides wrangler main)`),r.temporary&&r.logger.info("temporary account: deploying to a short-lived Cloudflare account (~60min); wrangler will print a claim URL"),r.dryRun&&r.logger.info("dry run: validating + bundling without publishing"),r.outDir!==void 0&&r.logger.info(`build artifact: emitting bundle to ${r.outDir}`),n.commit(),n.projection!==void 0&&n.projection.dropped.length>0&&r.logger.warn(`${t.name} ignores these wrangler keys, so they were left out of ${n.projection.configPath}: ${n.projection.dropped.join(", ")}`),n.command},R={problems:[],wranglerPath:void 0},oe=(e,r)=>({code:y.USAGE,descriptor:void 0,error:e,validation:R,...r}),Wo=(e,r)=>{for(const t of e.report?.warnings??[])r.warn(`wrangler.jsonc: ${t}`);if(e.problems.length===0)return!1;r.error("wrangler.jsonc validation failed:");for(const t of e.problems)r.error(` - ${t}`);return!0},Ko=(e,r,t)=>{const n=r.format==="json",o=r.dryRun!==!0,a=Vo(e,r,t),s=F(j(e),a);return{args:s.args,captureStdout:o&&!n,captureStdoutSilently:o&&n,command:s.command,cwd:e,stdoutToStderr:n&&!o}},ke=e=>{if(e.skipServices===!0)return"--skip-services";if(e.preview===!0)return"--preview uploads the app version only";if(e.temporary===!0)return"--temporary deploys the app to a throwaway account"},zo=(e,r)=>ke(r)===void 0?le(e).services.map(t=>t.wranglerPath):[],kr=(e,r,t,n,o)=>({cwd:e,environment:r.env,frameworkBuild:n,lazyFunctions:J(r.lazyFunctions),logger:r.logger,outputJson:r.format==="json"||r.clientBuildOutputJson===!0,spawner:o,strictAdvisories:ge(r),target:t.id}),Jo=(e,r,t)=>{const{toolchain:n}=t,o=n===void 0?`target "${t.id}" has no deploy command`:ke(r);if(o!==void 0||n===void 0){const a=e.map(s=>s.worker).join(", ");r.logger.warn(`services not deployed (${o??""}): ${a} — deploy them yourself if the app calls anything new`);return}return n},br=(e,r)=>{for(const t of e){const n=me(r(M(t.wranglerPath)));if(n!==void 0)return`service ${t.name} (${t.worker}): ${n}`}},Yo=(e,r,t)=>{const{error:n,services:o}=le(e);if(n!==void 0||o.length===0)return;const a=Y(t);if(a.toolchain===void 0||ke(r)!==void 0)return;const s=r.skipCodegen===!0?!1:r.frameworkBuild,i=[...new Map(o.map(c=>[c.wranglerPath,c])).values()];return br(i,c=>kr(c,r,a,s,x))},Sr=(e,r,t)=>{const n=e.cwd??process.cwd(),o=kt(n,e.target);if(o.target===void 0){const i=o.error??"unknown deploy target";return e.logger.error(i),{kind:"refused",error:i,validation:R}}try{wr(n,e,Y(o.target))}catch(i){if(!(t&&i instanceof Jr&&Z(n,e.skipCodegen===!0?!1:e.frameworkBuild,e.env))){const c=i instanceof Error?i.message:String(i);return e.logger.error(c),{kind:"refused",error:c,validation:R}}}const a=e.openShardGatePassed===!0?void 0:Kn(n,e,r,zo(n,e));if(a!==void 0)return{kind:"refused",code:a.code,error:a.error,validation:R};const s=Yo(n,e,o.target);return s!==void 0?(e.logger.error(s),{kind:"refused",code:y.USAGE,error:s,validation:R}):{kind:"ok",target:o.target}},Xo=(e,r)=>e.apiSpec??(e.clientBuildRan===!0?et(r):void 0),Qo=async(e,r,t)=>{if(r!=="celld")return;const n=await(e.celldToolchain??Qr)({dryRun:t==="prepare"||e.dryRun===!0,env:process.env,purpose:"deploy"});for(const o of n.warnings)e.logger.warn(o);return n.errors.length>0?n.errors.join("; "):void 0},Zo=async(e,r)=>{const t=e.cwd??process.cwd(),n=yr(e),o=ge(e),a={problems:[],wranglerPath:void 0},s=Sr(e,r,!1);if(s.kind==="refused")return{code:s.code,error:s.error,validation:s.validation};const{target:i}=s,c=await Qo(e,i,r);if(c!==void 0)return e.logger.error(c),{code:y.MISSING_DEPENDENCY,error:c,target:i,validation:a};let d;if(!e.skipCodegen){const v=await Go(t,n,e.logger,Xo(e,t),J(e.lazyFunctions),i,e.spawner,e.format==="json",o,e.clientBuildRan!==!0);if(v.error!==void 0)return{error:v.error,target:i,validation:R};d=v.result,e.discoveryCache?.clear()}let l;if(d!==void 0){const v=Pt({allowDrift:e.allowSchemaDrift===!0,codegen:d,command:r,logger:e.logger,updateBaseline:e.updateSchemaBaseline===!0});if(v.blocked)return{error:`schema drift gate blocked ${r}`,schemaDrift:{blocked:!0,reason:v.reason},target:i,validation:a};l=v.rebless}const g=d&&Ht({current:d.architecture,cwd:t,environment:e.env,logger:e.logger});await Ho(t,e.logger,d?.cronTriggers,i,e.env,e.discoveryCache);const u=await vr(t,e,r,i,"check");if(u!==void 0)return{error:u,target:i,validation:R};const h=zn(t,e,r,i);if(h!==void 0)return{code:h.code,error:h.error,target:i,validation:R};const f=nt({environment:e.env,projectRoot:t});return Wo(f,e.logger)?{error:"wrangler validation failed",target:i,validation:f}:{codegen:d,reblessSchemaBaseline:l,recordArchitecture:g,target:i,validation:f}},ea=e=>{W(k(e,".wrangler","deploy","config.json"),{force:!0})},ra=async(e,r,t)=>{const n=me(e);if(n!==void 0)return{built:!1,error:n};const o=Z(e.cwd,r,t);return o&&ea(e.cwd),{built:o,error:await ar(e)}},ta=(e,r,t)=>r||t===!1?mr(e):void 0,na=async(e,r,t,n)=>{const{error:o,services:a}=le(e);if(o!==void 0)return{code:y.FAILURE,error:o};if(a.length===0)return;const s=Jo(a,r,t);if(s===void 0)return;const i=j(e),c=[...new Map(a.map(u=>[u.wranglerPath,u])).values()],d=r.skipCodegen===!0?!1:r.frameworkBuild,l=u=>kr(u,r,t,d,n),g=br(c,l);if(g!==void 0)return r.logger.error(g),{code:y.USAGE,error:g};for(const u of c){const h=M(u.wranglerPath),f=l(h),{built:v,error:m}=await ra(f,d,r.env);if(m!==void 0){const T=`service ${u.name} (${u.worker}): ${m}`;return r.logger.error(T),{code:y.FAILURE,error:T}}const E=ta(u.wranglerPath,v,d);let C;try{C=Ve(t,h,"deploy",T=>s.deploy({configPath:T??E??u.wranglerPath,dryRun:r.dryRun===!0,environment:r.env}))}catch(T){return{code:y.FAILURE,error:`service ${u.name} (${u.worker}): ${T instanceof Error?T.message:String(T)}`}}C.commit();const $=F(i,C.command);r.logger.info(`deploying service ${u.name} (${u.worker}) via ${$.command} ${$.args.join(" ")}`);const I=await n({args:$.args,command:$.command,cwd:h,stdoutToStderr:r.format==="json"});if(I.code!==0)return{code:y.FAILURE,error:`service ${u.name} (${u.worker}): ${$.command} ${$.args.join(" ")} exited ${String(I.code)} — stopping before the app`}}},oa=async(e,r,t,n)=>{if(r!=="cloudflare")return;const o=e===void 0?void 0:D(e).parsed,a=(t===void 0?void 0:o?.env?.[t]?.account_id)??o?.account_id,s=await pt({accountId:a});(s.verdict==="near"||s.verdict==="full")&&n.warn(s.fix===void 0?s.message:`${s.message} ${s.fix}`)},aa=e=>e.dryRun!==!0&&e.temporary!==!0,sa=e=>e.temporary===!0?"temporary":e.dryRun===!0?"preview":"defer",ia=e=>{const r=e.fix===void 0?e.message:`${e.message} ${e.fix}`;return e.verdict==="unchecked"?`${r} The deploy stops until it can be checked, as a namespace made by the first repo is unrestricted.`:r},ca=(e,r,t)=>{const n=[];for(const o of e)if(o.verdict==="ok")o.changesAccount===!0&&r.info(o.message);else if(o.verdict==="unchecked"&&t==="preview")r.warn(`dry run: ${o.message}${o.fix===void 0?"":` ${o.fix}`} A real deploy stops here.`);else{const a=ia(o);r.error(a),n.push(a)}return n},$r=async(e,r,t,n,o,a,s)=>{const i=t==="cloudflare"&&r!==void 0?D(r).parsed:void 0;if(i===void 0)return;const c=(X(i,n).merged.artifacts??[]).flatMap(f=>typeof f?.binding=="string"&&typeof f.namespace=="string"?[{binding:f.binding,namespace:f.namespace}]:[]),d=c.length===0?void 0:ue(e,N(e),a).info?.jurisdiction;if(d===void 0)return;const l=[...new Map(c.map(f=>[f.namespace,f])).values()];if(s==="temporary"){o.warn(`--temporary deploys to a throwaway account, so the jurisdiction ("${d}") of Artifacts namespace ${l.map(f=>`"${f.namespace}"`).join(", ")} was not checked: it is created there on first use, in no jurisdiction.`);return}const g=(n===void 0?void 0:i.env?.[n]?.account_id)??i.account_id,u=await Promise.all(l.map(async f=>vt({...f,accountId:g,create:s==="create",jurisdiction:d,missingOk:s==="defer"||s==="preview"}))),h=ca(u,o,s);return h.length===0?void 0:h.join(`
19
- `)},da=async(e,r,t,n,o,a)=>{const s=aa(r)?await $r(e,a,o,r.env,r.logger,r.discoveryCache,"create"):void 0;if(s!==void 0)return{code:y.FAILURE,error:s};const i=await vr(e,r,"deploy",o);return i!==void 0?{code:y.FAILURE,error:i}:na(e,r,t,n)},la=async(e,r,t,n)=>{if(!(r.smokeLoad===!1||t.toolchain===void 0))return un({composedEntry:pe(e),configPath:n,cwd:e,environment:r.env,launcher:r.smokeLauncher,logger:r.logger,toolchain:t.toolchain})},ua=async e=>{const r={...e,discoveryCache:e.discoveryCache??Xr()},t=r.cwd??process.cwd(),n=yr(r),o=await Zo(r,r.commandName??"deploy");if(o.error!==void 0){if(o.validation.problems.length>0)return{code:y.USAGE,descriptor:void 0,error:o.error,validation:o.validation};const m=o.schemaDrift===void 0?void 0:{schemaDrift:o.schemaDrift};return oe(o.error,{...m,...o.code===void 0?{}:{code:o.code}})}const{validation:a}=o,s=Y(o.target),i=Rn(r)??await $r(t,a.wranglerPath,o.target,r.env,r.logger,r.discoveryCache,sa(r))??await la(t,r,s,a.wranglerPath);if(i!==void 0)return oe(i);const c=s.toolchain?.prebuildsContainerImages===!0?await Uo(t,r):void 0;if(c!==void 0)return oe(c);No(t,r.logger,s),tt(t,m=>{r.logger.warn(m)}),await oa(a.wranglerPath,o.target,r.env,r.logger);const{error:d,mintedSecretsFile:l}=await Fo(t,r,n,s);if(d!==void 0)return r.logger.error(d),{code:y.USAGE,descriptor:void 0,error:d,mintedSecretsFile:l,validation:a};const g=r.spawner??x,u=await da(t,r,s,g,o.target,a.wranglerPath);if(u!==void 0)return{code:u.code,descriptor:void 0,error:u.error,mintedSecretsFile:l,validation:a};const h=Ko(t,r,s);r.logger.info(`deploying via ${h.command} ${h.args.join(" ")}`);const f=await g(h);return h.captureStdoutSilently===!0&&f.stdout!==void 0&&f.stdout!==""&&process.stderr.write(f.stdout),f.code!==0?{code:f.code,descriptor:h,mintedSecretsFile:l,validation:a}:{...await Po({...o,cwd:t,descriptor:h,mintedSecretsFile:l,options:r,stdout:f.stdout}),logsAvailable:s.toolchain?.tail!==void 0}},ga=async e=>{const{logger:r}=e,t=e.cwd??process.cwd(),n={apiSpec:e.apiSpec,cwd:t,environment:e.env,bundleMetaPath:e.bundleMetaPath,frameworkBuild:e.skipCodegen===!0?!1:e.frameworkBuild,strictAdvisories:ge(e),lazyFunctions:J(e.lazyFunctions),logger:r,outputJson:e.format==="json"||e.clientBuildOutputJson===!0,spawner:e.spawner,target:e.target},o=me(n);if(o!==void 0)return r.error(o),{code:y.USAGE,descriptor:void 0,error:o,validation:R};Yr(t);const a=await ar(n);if(a!==void 0)return r.error(a),{code:y.FAILURE,descriptor:void 0,error:a,validation:R}},fa=(e,r)=>{const t=r.skipCodegen===!0?!1:r.frameworkBuild;return Z(e,t,r.env)?r.env:void 0},ha=async e=>{const{logger:r}=e,t=e.cwd??process.cwd(),n=Sr(e,e.commandName??"deploy",!0);if(n.kind==="refused")return{code:n.code??y.USAGE,descriptor:void 0,error:n.error,validation:n.validation};const o=await ga(e);if(o!==void 0)return o;const a=e.dryRun===!0?tr(t):void 0;let s;try{if(s=await ua({...e,clientBuildEnvironment:fa(t,e),clientBuildRan:wn(t,e.skipCodegen===!0?!1:e.frameworkBuild,e.env),logger:r,openShardGatePassed:!0}),s.code===0&&e.emitBindings!==void 0){const{error:i}=yt({destination:e.emitBindings,logger:r,projectRoot:e.cwd??process.cwd()});i!==void 0&&(r.error(i),s={...s,code:y.USAGE})}}finally{a?.()}if(e.format==="json")return s;if(s.code===0&&e.dryRun!==!0&&e.preview!==!0)Gt({cwd:e.cwd??process.cwd(),env:e.env,logger:e.logger,logsAvailable:s.logsAvailable===!0,mintedSecretsFile:s.mintedSecretsFile,url:s.deployment?.url});else if(s.code===0&&e.preview===!0){const i=s.deployment?.url;e.logger.success(i===void 0?"preview version uploaded":`preview version uploaded — ${i}`)}return s},Wa=wt(async({cwd:e,format:r,logger:t,options:n})=>{const o=gn(e,n.root),a=await ha({allowOpenShards:n.allowOpenShards===!0,allowSchemaDrift:n.allowSchemaDrift===!0,apiSpec:gt(n.apiSpec),frameworkBuild:n.prebuilt===!0?!1:n.frameworkBuild,lazyFunctions:J(n.lazyFunctions),cwd:o,dryRun:n.dryRun===!0,env:n.env,format:r,healthCheck:n.healthCheck===!0,logger:t,migrate:n.migrate===!0,migrateToken:n.migrateToken,migrateUrl:Ye({cwd:o,env:n.env,url:n.migrateUrl}),migrateYes:n.migrateYes===!0,preview:n.preview===!0,skipCodegen:n.prebuilt===!0,skipServices:n.skipServices===!0,smokeLoad:n.smokeLoad,strictAdvisories:n.strictAdvisories,target:n.target,temporary:n.temporary===!0,updateSchemaBaseline:n.updateSchemaBaseline===!0});return{code:a.code,data:{deployment:a.deployment,healthCheck:a.healthCheck,mintedSecretsFile:a.mintedSecretsFile,schemaDrift:a.schemaDrift,validation:a.validation},error:a.error}});export{Zo as a,Ho as b,Wa as e,gn as p,ha as r,la as s,hn as v};
42
+ `);const u=await Ct(c),{args:h,command:f}=H(I(t),l.dev({configPath:r===void 0?void 0:F(t,r),environment:a,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:f,port:u,runId:g}}catch(d){throw new _(`could not prepare the check (${d instanceof Error?d.message:String(d)})`,!0)}},bn=async e=>{const{configPath:r,cwd:t,environment:n,launcher:o,logger:a,toolchain:s}=e,i=y(t,N(t),"_generated","functions.ts"),c=b(i)&&E(i,"utf8").includes("export const loadAllFunctions"),l=N(t),d=cn(t,l);if(!c&&d.length===0)return;const g=[...d,...un(t,l,d)],u=fn(e);if("skip"in u){a.warn(`smoke-load skipped: ${u.skip}, so lazy modules are not evaluated before deploy`);return}const{main:h}=u,f=[];let v,m;const T=Date.now()+sr,L=process.platform!=="win32",P=(R,$,W)=>{const x=_t(R,[...$],{cwd:W.cwd,detached:L,shell:W.shell,stdio:["ignore","pipe","pipe"]});return L&&x.pid!==void 0&&(m={dispose:mn(x.pid),pid:x.pid}),x};try{v=wn(t),a.info("smoke-loading lazy function modules in workerd");let R=rn;for(let $=0;$<Ce;$+=1){const{args:W,command:x,port:ae,runId:Pr}=await kn({configPath:r,cwd:t,deferred:g,directory:v,environment:n,functionsFile:c?i:void 0,main:h,preferred:R,toolchain:s});R=ae+1;const Te=await vn({args:W,command:x,cwd:t,spawn:o??P,label:"wrangler dev (smoke-load)",notFound:"`wrangler` was not found",onLine:z=>{f.push(z)},port:ae,readyTimeoutMs:Math.max(0,T-Date.now()),shell:process.platform==="win32"});if(Te===void 0){await ie(m),m=void 0;continue}try{const z=await hn(ae,Pr,T);if(z!==void 0){pn(t,z,a);return}}finally{await Te.stop(),await ie(m),m=void 0}}throw new _(`the smoke port was answered by other runs on all ${String(Ce)} attempts`,!0)}catch(R){return yn(R,f,a)}finally{if(await ie(m),v!==void 0)try{X(v,{force:!0,recursive:!0})}catch{}}},Sn=(e,r)=>r===void 0?e:O(e,r),$n=async e=>{if(e.targets.length===0)return{builtTags:[],code:0};if(!(e.railpackAvailable??Ot)()){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??M,t=[];for(const n of e.targets){const o=Nt(n.exportName),a={args:["build",n.buildDir,"--name",o],command:"railpack",cwd:e.cwd},s=we(I(e.cwd),"wrangler",["containers","push",o]),i={args:s.args,command:s.command,cwd:e.cwd};e.logger.info(`railpack: building "${n.exportName}" → ${o} from ${n.buildDir}`);const c=await r(a);if(c.code!==0){const 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}},cr=e=>{const t=[j(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")}},En=(e,r=er())=>O(e,".lunora",`vite-bundle-meta-${r}.json`),dr="LUNORA_CLIENT_BUILD",An="virtual:lunora/worker",fe=(e,r)=>["ts","mts","cts","js","mjs","cjs"].some(t=>b(y(e,`${r}.config.${t}`))),lr=e=>fe(e,"rsbuild")?"rsbuild":fe(e,"vite")?"vite":void 0,Tn=e=>fe(e,"vite")?"vite":lr(e),Rn=e=>{try{const{scripts:r}=JSON.parse(E(y(e,"package.json"),"utf8"));return typeof r?.build=="string"&&r.build!==""}catch{return!1}},ne=(e,r)=>{if(process.env[dr]==="1")return;const t=j(e),n=t===void 0?void 0:D(t).parsed,o=n?.main===An,a=(o?Tn(e):lr(e))??(Rn(e)?"script":void 0);if(a===void 0)return;const s=r===void 0?void 0:n?.env?.[r]?.assets?.directory,i=n?.assets?.directory??s;return o||Fr(e).class!=="C"||i!==void 0?a:void 0},_n=async(e,r,t)=>{const n=t.spawner??M,o=I(e),a=r==="script"?{args:["run","build"],command:o}:we(o,r,["build"]);t.logger.info(`running ${r} build before bundling the Worker`);const s=cr(e),i=t.bundleMetaPath??En(e);X(y(e,Ur),{force:!0});try{const c=await n({args:a.args,command:a.command,cwd:e,env:{[Vr]:Wr(e),[qr]:t.target,[Gr]:i,...t.lazyFunctions?{[Hr]:"1"}:{},...t.environment===void 0?{}:{CLOUDFLARE_ENV:t.environment},...t.strictAdvisories===!1?{[Br]:"0"}:{},[dr]:"1"},stdoutToStderr:t.outputJson});return c.code===0?void 0:`${r} build failed with exit code ${String(c.code)}`}finally{s(),t.bundleMetaPath===void 0&&X(i,{force:!0})}},oe=(e,r,t)=>r!==!1&&ne(e,t)!==void 0,Dn=(e,r,t)=>oe(e,r,t)&&ne(e,t)!=="script",ke=e=>{const r=e.frameworkBuild===!1?void 0:ne(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{ue(e.cwd,e.target)}catch(n){return n instanceof Error?n.message:String(n)}let t;try{t=ue(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:ne(e.cwd,e.environment);if(r===void 0)return;let t;try{t=e.target??ue(e.cwd)}catch(n){return n instanceof Error?n.message:String(n)}return _n(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})},je=e=>Array.isArray(e)?e.filter(r=>r!=null):void 0,be=(e,r)=>{const t=j(e);if(!t)return;const{parsed:n}=D(t);if(n===void 0)return;const{error:o,merged:a}=te(n,r),s=o===void 0?a:n,{containers:i,d1_databases:c,vars:l}=s;return{containers:je(i),d1_databases:je(c),vars:typeof l=="object"&&l!==null&&!Array.isArray(l)?l:void 0}},Pn=/^127(?:\.\d{1,3}){3}$/,Cn=e=>{try{const{hostname:r}=new URL(e);return r==="localhost"||Pn.test(r)||r==="::1"||r==="[::1]"}catch{return!1}},Nn=e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"),On=(e,r,t,n="deploy",o)=>{const a=(be(e,o)?.containers??[]).filter(i=>typeof i?.image=="string"&&Nn(i.image));if(a.length===0||t())return;const s=`${n} blocked: wrangler.jsonc declares ${String(a.length)} container(s) built from a local Dockerfile, but no Docker-compatible engine is available. Start Docker (or Colima), or point the container's \`image\` at a pre-built registry reference. Note: container images must target linux/amd64.`;return r.error(s),s},Se=e=>b(S(e,Re))?Re:void 0,jn=(e,r,t="deploy",n)=>{for(const o of ze(e,"lunora",n).containers){const a=o.schedulingPolicy===void 0?o.image:void 0,i=[...a?.kind==="dockerfile"?[{field:"image",path:a.dockerfilePath}]:[],...Object.entries(o.schedulingPolicy==="durable_object"?o.images??{}:{}).flatMap(([c,l])=>l.kind==="dockerfile"?[{field:`images["${c}"]`,path:l.dockerfilePath}]:[])].find(c=>!b(S(e,c.path)));if(i!==void 0){const c=`${t} blocked: container "${o.exportName}" references a Dockerfile at "${i.path}" that does not exist. Create it or fix the \`${i.field}\` path in lunora/containers.ts.`;return r.error(c),c}if(a?.kind==="build"&&!b(S(e,a.buildDir))){const c=`${t} blocked: container "${o.exportName}" references a Railpack build directory "${a.buildDir}" that does not exist. Create it or fix the \`image.build\` path in lunora/containers.ts.`;return r.error(c),c}}},In=(e,r)=>r==="celld"?typeof e=="string"&&e!==_e&&kt(e):r==="cloudflare"&&e===_e,Ln=(e,r,t)=>(be(e,t)?.d1_databases??[]).find(n=>In(n.database_id,r)),xn=e=>{if(!e.migrate||e.dryRun||e.preview)return;if(e.migrateUrl===void 0){const t="--migrate requires --migrate-url <https://your-worker> — the deploy target URL is only known after wrangler runs, and this gate runs before it; refusing to default to localhost";return e.logger.error(t),t}if(e.migrateYes!==!0){const t="--migrate runs production data migrations after deploy. Re-run with --migrate-yes to confirm.";return e.logger.error(t),t}const r=e.migrateToken??process.env.LUNORA_ADMIN_TOKEN;if(r===void 0||r===""){const t="admin token required for --migrate — pass --migrate-token or set LUNORA_ADMIN_TOKEN";return e.logger.error(t),t}},Mn=(e,r,t,n,o)=>{const a=Ln(e,n,o);if(a===void 0)return;const s=`${t} blocked: the "${a.binding??"<unnamed>"}" D1 binding has a placeholder database_id ("${a.database_id??""}")`,i=n==="celld"?`${s}, which celld would use as the database's identity. Set database_id to the database celld should use, then ${t} again.`:`${s}. Run \`lunora doctor --fix\` to create the database and write its id into wrangler.jsonc, or run \`wrangler d1 create <name>\` and paste the id in yourself.`;return r.error(i),i},Fn=(e,r,t="deploy",n)=>{const o=be(e,n)?.vars;if(!o)return;const a=Object.entries(o).filter(([,i])=>typeof i=="string"&&Cn(i)).map(([i])=>i).toSorted((i,c)=>i.localeCompare(c));if(a.length===0)return;const s=`${t} blocked: ${a.join(", ")} in wrangler.jsonc point at localhost. A deployed Worker can't reach a loopback address, so this silently breaks scheduled-job dispatch, reverse cross-shard relations, and auth callbacks. Set each to the deployed worker's public URL (or move it to a secret with \`wrangler secret put\`) before deploying.`;return r.error(s),s},Un=["vite.config.ts","vite.config.mts","vite.config.cts","vite.config.js","vite.config.mjs","vite.config.cjs",...jr],gr=/\.(?:[cm]?[jt]s|tsx|jsx)$/u,fr=/\.(?:test|spec)\.[cm]?[jt]sx?$/u,hr="allowUnauthenticatedShardAccess",Bn=/[\\/]/u,mr=new Set(["_generated","build","dist","node_modules"]),vr=(e,r)=>{const t=G(e,r).split(Bn);return gr.test(r)&&!fr.test(r)&&!le(t.join("/"))&&t.every(n=>n===".."||!n.startsWith(".")&&!mr.has(n))},Ie=(e,r,t)=>{const{parsed:n}=D(r);if(n===void 0)return[];const{error:o,merged:a}=te(n,t),{main:s}=o===void 0?a:n,i=typeof s=="string"?S(tr(r),s):void 0;return i!==void 0&&b(i)&&vr(e,i)?[i]:[]},$e=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)?$e(e.getExpression()):!1,Hn=e=>{try{return Ve(e).isFile()}catch{return!1}},Gn=new Set(["ELOOP","ENOENT","ENOTDIR"]),Q=(e,r,t)=>{const n=r instanceof Error&&"code"in r&&typeof r.code=="string"?r.code:"";Gn.has(n)||t.push(e)},qn=(e,r)=>{try{return Ve(e)}catch(t){Q(e,t,r);return}},pr=(e,r)=>{try{return E(e,"utf8")}catch(t){Q(e,t,r);return}},yr=(e,r,t,n=new Set)=>{let o;try{o=Nr(r)}catch(s){return Q(r,s,t),[]}if(n.has(o))return[];n.add(o);let a;try{a=he(r)}catch(s){return Q(r,s,t),[]}return a.flatMap(s=>{const i=S(r,s),c=qn(i,t);if(c===void 0)return[];const l=G(e,i).split(B).join("/");return c.isDirectory()?mr.has(s)||s.startsWith(".")||le(`${l}/`)?[]:yr(e,i,t,n):c.isFile()&&gr.test(s)&&!fr.test(s)&&!le(l)?[i]:[]})},Vn=e=>{const r=k.isComputedPropertyName(e)?e.getExpression():e;return k.isStringLiteral(r)||k.isNoSubstitutionTemplateLiteral(r)?r.getLiteralValue():e.getText()},ce=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],Wn=/\.(?:[cm]?js|jsx)$/u,zn=(e,r)=>{if(!r.startsWith("."))return;const t=O(tr(e),r),n=t.replace(Wn,"");return[t,...ce.map(a=>`${t}${a}`),...ce.map(a=>S(t,`index${a}`)),...ce.map(a=>`${n}${a}`)].find(a=>Hn(a))},Kn=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},Jn=e=>{const r=e.getModuleReference();if(!k.isExternalModuleReference(r))return;const t=r.getExpression();return k.isStringLiteral(t)?t.getLiteralValue():void 0},Yn=(e,r,t,n)=>{const o=new Set(e),a=[...e],s=[];for(let i=0;i<a.length;i+=1){const c=a[i]??"",l=pr(c,n);if(l===void 0)continue;const d=r.createSourceFile(G(t,c),l,{overwrite:!0}),g=[...d.getImportDeclarations().map(u=>u.getModuleSpecifierValue()),...d.getExportDeclarations().map(u=>u.getModuleSpecifierValue()),...d.getDescendantsOfKind(p.ImportEqualsDeclaration).map(u=>Jn(u)),...d.getDescendantsOfKind(p.CallExpression).map(u=>Kn(u))].filter(u=>u!==void 0);for(const u of g){const h=zn(c,u);h!==void 0&&vr(t,h)&&!o.has(h)&&(o.add(h),s.push(h),a.push(h))}}return s},Xn=e=>{const r=e.getArgumentExpression();return r!==void 0&&(k.isStringLiteral(r)||k.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},Qn=e=>k.isPropertyAccessExpression(e)?e.getName():k.isElementAccessExpression(e)?Xn(e):void 0,Zn=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]),eo=e=>{const r=e.getOperatorToken().getKind();return!Zn.has(r)||Qn(e.getLeft())!==hr?!1:r!==p.EqualsToken||!$e(e.getRight())},ro=(e,r,t)=>{const n=[],o=[...new Set([N(e),"src"])].filter(g=>b(S(e,g))),a=j(e),s=[...Un.map(g=>S(e,g)).filter(g=>b(g)),...a===void 0?[]:Ie(e,a,r),...t.flatMap(g=>Ie(e,g,r))],i=new nr({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}),c=o.flatMap(g=>yr(S(e,g),S(e,g),n));return{sites:[...new Set([...c,...s,...Yn([...s,...c],i,e,n)])].flatMap(g=>{const u=pr(g,n);if(u===void 0)return[];const h=i.createSourceFile(G(e,g),u,{overwrite:!0}),f=[...h.getDescendantsOfKind(p.PropertyAssignment),...h.getDescendantsOfKind(p.ShorthandPropertyAssignment),...h.getDescendantsOfKind(p.GetAccessor),...h.getDescendantsOfKind(p.MethodDeclaration)].filter(m=>{const T=k.isPropertyAssignment(m)&&$e(m.getInitializer());return Vn(m.getNameNode())===hr&&!T}).map(m=>m.getStartLineNumber()),v=h.getDescendantsOfKind(p.BinaryExpression).filter(m=>eo(m)).map(m=>m.getStartLineNumber());return[...f,...v].map(m=>({file:G(e,g),line:m}))}),unreadable:n}},to=(e,r,t,n,o,a)=>{if(t!=="deploy")return;const{sites:s,unreadable:i}=ro(e,o,a),c=Ft({openShardAccess:s,schema:{tables:[]}},{lints:[De]});if(c.length===0&&i.length===0)return;const l=[];if(c.length>0){const g=c.map(u=>`${String(u.metadata.file)}:${String(u.metadata.line)}`).join(", ");l.push(`${g} 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(" ")} ${De.remediation}`;return r.error(d),d},no=(e,r,t,n)=>{const o=to(e,r.logger,t,r.allowOpenShards===!0,r.env,n);return o===void 0?void 0:{code:w.USAGE,error:o}},oo=(e,r,t,n)=>{const o=Mn(e,r.logger,t,n,r.env);if(o!==void 0)return{code:w.USAGE,error:o};const a=Fn(e,r.logger,t,r.env);if(a!==void 0)return{code:w.USAGE,error:a};const s=jn(e,r.logger,t,r.discoveryCache);if(s!==void 0)return{code:w.USAGE,error:s};const i=On(e,r.logger,r.dockerAvailable??jt,t,r.env);return i===void 0?void 0:{code:w.MISSING_DEPENDENCY,error:i}},Le=32,wr=15e3,ao=5432,so=3306,io=/[^a-z0-9-]/gu,co=/[^A-Za-z0-9]/gu,lo=/-$/u,q=e=>`LUNORA_${e.replaceAll(co,"_").toUpperCase()}_URL`,uo=e=>{const r=new Map;for(const t of e){const n=q(t),o=r.get(n);if(o!==void 0)return{bindings:[o,t],variable:n};r.set(n,t)}},xe=7,go=(e,r)=>{const t=`${e}-${r}`.toLowerCase(),n=t.replaceAll(io,"-");if(n===t&&n.length<=Le)return n;const o=Dt("sha256").update(t).digest("hex").slice(0,xe-1);return`${n.slice(0,Le-xe).replace(lo,"")}-${o}`},Me=e=>e==="postgresql"?"postgres":e==="mariadb"?"mysql":e,fo=e=>e==="mysql"?so:ao,ho=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===""?fo(Me(t)):Number(r.port),scheme:Me(t),user:decodeURIComponent(r.username)}}catch{return}},mo=(e,r)=>{const t=typeof r?.password=="string"?r.password:"",n=t===""?[]:[t,JSON.stringify(t).slice(1,-1),encodeURIComponent(t)];let o=e;for(const a of n)o=o.replaceAll(a,"<redacted>");return o.split(" ").map(a=>a.includes("://")?"<url>":a).join(" ")},kr=e=>(Array.isArray(e)?e:[]).flatMap((r,t)=>{const{binding:n,id:o}=typeof r=="object"&&r!==null?r:{};return typeof n=="string"&&o===Xe?[{binding:n,index:t}]:[]}),Z=e=>{let r="";try{const{errors:t}=JSON.parse(e.text);r=(t??[]).flatMap(n=>typeof n.message=="string"?[n.message]:[]).slice(0,2).join("; ")}catch{}return r===""?`HTTP ${String(e.status)}`:`HTTP ${String(e.status)}: ${r}`},vo=e=>typeof e=="string"||typeof e=="number"?e.toString():void 0,po=["scheme","host","port","database","user"],yo=e=>e==="postgresql"?"postgres":e,Fe=(e,r)=>{const t=vo(r);return e==="scheme"?yo(t):t},Ue=50,wo=async(e,r)=>{for(let t=1;t<=Ue;t+=1){const n=await e(t===1?"/hyperdrive/configs":`/hyperdrive/configs?page=${String(t)}`);if(!n.ok)throw new Error(`listing Hyperdrive configs failed (${Z(n)})`);if(!Array.isArray(n.body.result))throw new TypeError("the listing of Hyperdrive configs had no result list");const o=n.body.result.find(s=>s.name===r),a=typeof n.body.result_info=="object"&&n.body.result_info!==null?n.body.result_info:{};if(o!==void 0||typeof a.total_pages!="number"||t>=a.total_pages)return o}throw new Error(`the listing of Hyperdrive configs has more than ${String(Ue)} pages, so "${r}" can't be shown to be absent`)},ko=async(e,r,t,n)=>{const o=n?{caching:{disabled:!0}}:{},a=await wo(e,r);if(typeof a?.id=="string"){const c=po.filter(d=>Fe(d,a.origin?.[d])!==Fe(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(a.id)}`,{body:JSON.stringify({origin:t,...o}),method:"PATCH"});if(!l.ok)throw new Error(`updating its credentials failed (${Z(l)})`);return{id:a.id,reused:!0}}const s=await e("/hyperdrive/configs",{body:JSON.stringify({name:r,origin:t,...o}),method:"POST"});if(!s.ok)throw new Error(`creating it failed (${Z(s)})`);const{id:i}=typeof s.body.result=="object"&&s.body.result!==null?s.body.result:{};if(typeof i!="string")throw new TypeError("the response carried no id");return{id:i,reused:!1}},bo=(e,r,t,n)=>r===void 0&&n?`${q(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 ${q(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.`,So=async(e,r)=>{const t=go(e.workerName,e.binding),{id:n,reused:o}=await ko(async(a,s)=>ar({accountId:e.accountId,apiToken:e.token,...e.fetch===void 0?{}:{fetch:e.fetch},init:{...s,signal:AbortSignal.timeout(wr)},path:a}),t,e.origin,e.disableCaching);return e.logger.success(`${o?"reusing":"created"} Hyperdrive config "${t}" for ${e.binding} → ${e.wranglerPath}`),{id:n,text:Qe(r,[...e.path,e.index,"id"],n)}},$o=e=>e===void 0||e===""?void 0:e,br=e=>{const r=y(U(e),".wrangler","deploy","config.json");try{const{configPath:t}=JSON.parse(E(r,"utf8"));return typeof t=="string"?O(U(r),t):void 0}catch{return}},Eo=(e,r,t,n,o)=>{const a=br(e);if(a===void 0||a===e)return;if(n.built!==n.deployed){o.warn(`the build output ${a} was made for ${n.built===void 0?"the default environment":`"${n.built}"`}, not ${n.deployed===void 0?"the default environment":`"${n.deployed}"`}, so the "${r}" Hyperdrive id was not written there. Build with CLOUDFLARE_ENV set to the environment you deploy, then deploy again.`);return}let s;try{s=D(a)}catch{return}const i=kr(s.parsed?.hyperdrive).find(c=>c.binding===r);i!==void 0&&V(a,Qe(s.text,["hyperdrive",i.index,"id"],t),"utf8")},Ao=(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}`},Ee=(e,r)=>{const t=j(e),n=t===void 0?void 0:D(t).parsed;if(t===void 0||n===void 0)return;const o=r===void 0?void 0:n.env?.[r],a=kr(r===void 0?n.hyperdrive:o?.hyperdrive);return a.length===0?void 0:{accountId:o?.account_id??n.account_id,entries:a,path:r===void 0?["hyperdrive"]:["env",r,"hyperdrive"],workerName:Ao(n,r),wranglerPath:t}},To=(e,r,t)=>{const n=uo(e.map(({binding:o})=>o));if(n!==void 0){const o=`deploy blocked: the Hyperdrive bindings ${n.bindings.map(a=>`"${a}"`).join(" and ")} both read ${n.variable} and would share one config. Rename one so their names differ in letters or digits, not only in punctuation.`;return t.logger.error(o),o}for(const{binding:o,origin:a,supplied:s}of e){const i=bo(o,a,r,s);if(i!==void 0&&t.dryRun===!0)t.logger.warn(`dry run: ${i} A real deploy stops here.`);else if(i!==void 0){const c=`deploy blocked: ${i}`;return t.logger.error(c),c}}},Ro=async(e,r,t,n)=>{let o;try{o=await e(`/hyperdrive/configs/${encodeURIComponent(t)}`)}catch(s){n.warn(`could not check whether the "${r}" Hyperdrive config has query caching off (${s instanceof Error?s.message:String(s)}).`);return}if(!o.ok){n.warn(`could not check whether the "${r}" Hyperdrive config has query caching off (${Z(o)}).`);return}const{caching:a}=typeof o.body.result=="object"&&o.body.result!==null?o.body.result:{};a?.disabled!==!0&&n.warn(`the "${r}" Hyperdrive config has query caching on, so .global() tables would read rows up to 75 s old. Run \`wrangler hyperdrive update ${t} --caching-disabled\`.`)},_o=async(e,r)=>{const t=j(e.cwd),n=t===void 0?void 0:D(t).parsed,o=e.wranglerEnvironment===void 0?n:n?.env?.[e.wranglerEnvironment],{accountId:a,token:s}=or(r,o?.account_id??n?.account_id);if(a===void 0||s===void 0)return;const i=async(c,l)=>ar({accountId:a,apiToken:s,...e.fetch===void 0?{}:{fetch:e.fetch},init:{...l,signal:AbortSignal.timeout(wr)},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!==Xe&&await Ro(i,l,d,e.logger)}},Do=async e=>{const r=e.environment??process.env;e.disableCaching===!0&&e.checkOnly!==!0&&e.dryRun!==!0&&await _o(e,r);const t=Ee(e.cwd,e.wranglerEnvironment);if(t===void 0)return;const{entries:n,path:o,wranglerPath:a}=t,{accountId:s,token:i}=or(r,t.accountId),c=n.map(({binding:d})=>{const g=r[q(d)]??"";return{binding:d,origin:ho(g),supplied:g!==""}}),l=To(c,i!==void 0&&s!==void 0,e);if(l!==void 0)return l;if(!(e.dryRun===!0||e.checkOnly===!0))for(const[d,{binding:g,index:u}]of n.entries()){const h=c[d]?.origin;if(!(h===void 0||i===void 0||s===void 0))try{const{id:f,text:v}=await So({accountId:s,binding:g,disableCaching:e.disableCaching===!0,fetch:e.fetch,index:u,logger:e.logger,origin:h,path:o,token:i,workerName:t.workerName,wranglerPath:a},E(a,"utf8"));V(a,v,"utf8"),Eo(a,g,f,{built:$o(r.CLOUDFLARE_ENV),deployed:e.wranglerEnvironment},e.logger)}catch(f){const v=f instanceof Error?f.message:String(f),m=`deploy blocked: the "${g}" Hyperdrive config could not be set up: ${mo(v,c[d]?.origin)}`;return e.logger.error(m),m}}},Po=(e,r)=>{const t=Ee(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 ${q(t)} set to create the config, or put the id from \`wrangler hyperdrive create\` in wrangler.jsonc.`;return r.logger.error(n),n},Co=(e,r)=>{const t=Ee(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},Sr=async(e,r,t,n,o="create")=>{if(n!=="cloudflare")return;if(t==="prepare")return Po(e,r);if(r.temporary===!0)return Co(e,r);const a=r.clientBuildEnvironment===void 0?void 0:{...process.env,CLOUDFLARE_ENV:r.clientBuildEnvironment},s=ve(e,N(e),r.discoveryCache);return s.error!==void 0&&r.logger.warn(`could not read the schema (${s.error}), so Hyperdrive configs are set up with query caching off.`),Do({checkOnly:o==="check",cwd:e,disableCaching:s.error!==void 0||s.info?.hasHyperdriveGlobalTable===!0,dryRun:r.dryRun,environment:a,logger:r.logger,wranglerEnvironment:r.env})},No=/https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u,Oo=/https:\/\/[^\s"'<>]+/u,jo=e=>{if(e===void 0)return;const r=No.exec(e);return r?r[0]:Oo.exec(e)?.[0]},Be=e=>e===void 0?"":` (--env ${e})`,Io=({cwd:e,env:r,logger:t,now:n,url:o})=>{if(o!==void 0)try{const a=We(e);if(a!==void 0){if(a.workerUrl===o&&a.env===r)return;t.warn(`link: .lunora/project.json records ${a.workerUrl??"(no url)"}${Be(a.env)}, but this deploy published ${o}${Be(r)}. Keeping the recorded value — run \`lunora link --url ${o}${r===void 0?"":` --env ${r}`}\` to update it.`);return}const s=(n??(()=>new Date().toISOString()))();zr(e,{env:r,linkedAt:s,workerName:ye(e),workerUrl:o}),t.success(`link: recorded ${o} in .lunora/project.json (run \`lunora link\` to change)`)}catch{}},Lo=async(e,r)=>{const t=new nr({skipAddingFilesFromTsConfig:!0}),n=S(r,"lunora");let o;try{o=Ir(t,n)}catch(a){const s=a instanceof Error?a.message:String(a);return e.logger.warn(`--migrate: could not discover migrations (${s}); skipping`),0}if(o.length===0)return e.logger.info("--migrate: no data migrations declared in lunora/"),0;e.logger.info(`--migrate: running ${String(o.length)} migration(s) against deployed worker`);for(const a of o){e.logger.info(`--migrate: up "${a.id}" (table "${a.table}")`);const s={cwd:r,fetchImpl:e.fetchImpl,id:a.id,logger:e.logger,prod:!0,subcommand:"up",token:e.migrateToken,url:e.migrateUrl,yes:e.migrateYes===!0},i=await Ut(s);if(i.code!==0)return e.logger.error(`--migrate: migration "${a.id}" failed — see output above`),i.code;e.logger.success(`--migrate: "${a.id}" applied`)}return 0},xo=async(e,r)=>{const{info:t}=ve(r,"lunora",e.discoveryCache),n=t?.vectorMetadata??[];if(n.length===0)return;const o=[];for(const i of n){const c=bt(i.kind);if(c===void 0){e.logger.warn(`vector index "${i.index}" declares metadata "${i.property}", whose column type cannot be filtered on in Vectorize — it is stored with each vector but no filter will match it.`);continue}o.push({index:i.index,property:i.property,type:c})}if(o.length===0)return;const s=(await St({cwd:r,entries:o,exec:we(I(r),"wrangler",[]),logger:e.logger,spawner:e.spawner??M})).filter(i=>i.status!=="failed").length;s>0&&e.logger.success(`vectorize metadata indexes ready: ${String(s)}/${String(o.length)}`)},He=5,Mo=2e3,Fo=async(e,r,t)=>{if(e.healthCheck!==!0)return;const n=t??rr({cwd:r,env:e.env});if(n===void 0){const a="--health-check: the deploy succeeded, but no URL to probe could be resolved — wrangler's output carried none and this checkout has no link for this environment. Run `lunora link --url <https://your-worker>` and re-deploy, or drop --health-check.";return e.logger.error(a),{error:a,ok:!1,url:""}}const o=await It({attempts:He,baseUrl:n,delayMs:Mo,fetchImpl:e.healthFetch,paths:[Lt,xt],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(He)} attempt(s) — ${o.error}`),{error:o.error,ok:!1,url:o.url})},Uo=async(e,r,t,n,o,a)=>{await xo(e,r);const s=e.migrate?await Lo(e,r):0;return s===0&&o?.(),{code:s,descriptor:t,mintedSecretsFile:a,validation:n}},Bo=async({cwd:e,descriptor:r,mintedSecretsFile:t,options:n,reblessSchemaBaseline:o,recordArchitecture:a,stdout:s,validation:i})=>{const c={deployedAt:new Date().toISOString(),dryRun:n.dryRun===!0,env:n.env,preview:n.preview===!0,url:n.dryRun===!0?void 0:jo(s),workerName:ye(e)};if(n.dryRun===!0||n.preview===!0)return n.healthCheck===!0&&n.logger.warn(`--health-check skipped: ${n.dryRun===!0?"a dry run publishes nothing":"a preview version serves no live traffic"}`),{code:0,deployment:c,descriptor:r,mintedSecretsFile:t,validation:i};n.temporary!==!0&&(a?.(),Io({cwd:e,env:n.env,logger:n.logger,url:c.url}));const l=await Fo(n,e,c.url);return l?.error!==void 0?{code:w.UNAVAILABLE,deployment:c,descriptor:r,healthCheck:l,mintedSecretsFile:t,validation:i}:{...await Uo(n,e,r,i,o,t),deployment:c,healthCheck:l}},Ho=(e,r,t)=>{const n=S(e,C);if(!b(n))return;let o;try{o=Ke(E(n,"utf8")).length}catch{return}if(o===0)return;const a=t.toolchain?.secretPut!==void 0;r.warn(a?`Note: \`lunora deploy\` does not push secrets. ${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.`)},$r=async(e,r)=>{let t=[];try{t=Kr(await Je({cache:r,projectRoot:e,schemaDir:N(e)}))}catch{}const n=[...new Set(Jr(t).map(a=>a.key))];let o=[];try{const a=S(e,C);b(a)&&(o=Ke(E(a,"utf8")).map(s=>s.key).filter(s=>Ze(s)))}catch{}return{fromLocal:o.filter(a=>!n.includes(a)),fromPackages:n,mintableKeys:Yr(t)}},Go=async(e,r,t,n)=>{const{logger:o}=r,a=r.spawner??M,s=I(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:Xr()})),d=n.toolchain?.secretBulk;if(d!==void 0&&l.length>=2){const u=H(s,d({environment:r.env,temporary:r.temporary})),h=await a({args:u.args,command:u.command,cwd:e,input:JSON.stringify(Object.fromEntries(l.map(f=>[f.key,f.value])))});if(h.code===0){for(const{key:f}of l)o.success(`generated + pushed ${f}`);return{minted:l,ok:!0}}o.warn(`bulk secret push failed (exit ${String(h.code)}); retrying one key at a time`)}const g=[];for(const{key:u,value:h}of l){const f=c({environment:r.env,key:u,temporary:r.temporary}),v=H(s,f),m=await a({args:v.args,command:v.command,cwd:e,input:h});if(m.code!==0)return o.error(`failed to push secret ${u} (exit ${String(m.code)}); set it manually with \`wrangler secret put ${u}${i}\`.`),{minted:g,ok:!1};g.push({key:u,value:h}),o.success(`generated + pushed ${u}`)}return{minted:g,ok:!0}},qo=/^[\w-]+$/u,Ge=[".dev.vars",".dev.vars.*","!.dev.vars.example"],Vo=(e,r)=>{try{const t=rt(e,Ge);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 \`${Ge.join("` and `")}\` by hand before committing.`)}},Wo=(e,r,t)=>{if(t.length===0)return;const n=t.map(i=>i.key).join(", ");if(r.env!==void 0&&!qo.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}`;Vo(e,r.logger);const a=S(e,o);let s=b(a)?E(a,"utf8"):"";for(const i of t)s=Qr(s,i.key,i.value);return Zr(a,s),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},zo=/^<[^>]+>$/u,Ko=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 g=n[d];if(typeof g!="string")return!0;const u=g.trim();return u===""||zo.test(u)?!0:Ze(d)&&et(g)},a=d=>Object.hasOwn(n,d)?`${d} (empty or a placeholder)`:d,{fromLocal:s,fromPackages:i}=await $r(e,r.discoveryCache),c=s.filter(d=>o(d));c.length>0&&r.logger.warn(`${C} key(s) not set in the wrangler vars: ${c.map(d=>a(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=>a(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.`}},Jo=async(e,r,t,n)=>{if(r.dryRun===!0||r.preview===!0)return{};if(n.toolchain?.secretList===void 0)return Ko(e,r,n);const{logger:o}=r,a=r.env===void 0?"":` --env ${r.env}`;let s;try{s=await(r.secretLister??Ht)({cwd:e,env:r.env,target:n.id,temporary:r.temporary})}catch{return{}}if(!s.ok)return{};const i=new Set(s.names),{fromLocal:c,fromPackages:l,mintableKeys:d}=await $r(e,r.discoveryCache),g=[...l,...c].filter(f=>!i.has(f));if(g.length===0)return{};if(!t)return{error:`missing required secret(s) on the deploy target: ${g.join(", ")}. Set them with \`wrangler secret put <KEY>${a}\` (or \`lunora env generate --set\` then \`lunora env push --yes${a}\`), then re-deploy.`};for(const f of g.filter(v=>!d.has(v)))o.warn(`required secret ${f} is not set on the target — set it with: wrangler secret put ${f}${a}`);const u=g.filter(f=>d.has(f));if(u.length===0)return{};if(await(r.secretConfirm??Bt())(`${String(u.length)} required secret(s) not set on the target (${u.join(", ")}). Generate strong values and push them now?`)){const{minted:f,ok:v}=await Go(e,r,u,n),m=Wo(e,r,f);return v?{mintedSecretsFile:m}:{error:"failed to push required secret(s) — set them manually and re-deploy",mintedSecretsFile:m}}return o.warn(`${String(u.length)} required secret(s) not set on the target: ${u.join(", ")}. Generate + push with \`lunora env generate --set\` then \`lunora env push --yes${a}\`.`),{}},Er=e=>e.format==="json"?!1:e.interactive!==void 0?e.interactive:process.stdout.isTTY&&!process.env.CI,Yo=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 $n({cwd:e,logger:r.logger,railpackAvailable:r.railpackAvailable,spawner:r.spawner,targets:t});return n.code===0?void 0:n.error??"railpack build failed"},Xo=(e,r,t)=>{if(t!==void 0)try{const n=ht(e,t);n.changed&&r.success(`synced ${String(t.length)} cron trigger(s) → ${n.wranglerPath??"wrangler.jsonc"}`);for(const a of n.warnings)r.warn(a);const o=mt(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}`)}},Qo=async(e,r,t,n,o,a)=>{try{re(n);const s=await Je({cache:a,projectRoot:e,schemaDir:N(e)}),i=gt(e,s,{environment:o,target:n}),c=i.wranglerPath??"wrangler.jsonc";if(i.added.length>0&&r.success(`provisioned bindings: ${i.added.join(", ")} → ${c}`),i.updated.length>0&&r.success(`updated bindings: ${i.updated.join(", ")} → ${c}`),i.devConfig!==void 0){const{added:l,path:d,updated:g}=i.devConfig;r.success(`dev sidecar bindings: ${[...l,...g].join(", ")} → ${d}`)}for(const l of i.warnings)r.warn(l)}catch(s){const i=s instanceof Error?s.message:String(s);r.warn(`binding inference skipped: ${i}`)}try{const s=ft(e);s.changed&&r.success(`bumped compatibility_date to ${s.date??"unknown"} (Workers Cache enabled) → ${s.wranglerPath??"wrangler.jsonc"}`)}catch(s){const i=s instanceof Error?s.message:String(s);r.warn(`compatibility date sync skipped: ${i}`)}Xo(e,r,t)},Zo=async(e,r,t,n,o,a,s,i,c,l)=>{let d;r?(d=new vt({name:"dots"}),d.start("running codegen")):t.info("running codegen");try{const g=Lr({apiSpec:n,dryRun:!l,lazyFunctions:o,projectRoot:e,target:a,...ut(e)});d?.succeed("codegen complete"),d||t.success("codegen complete");const u=pt(g.platformDiagnostics,t);if(u.errors.length>0)return{error:u.errors.join("; ")};const{errorAdvisories:h,names:f,shouldBlock:v}=yt(g.advisories,c);if(v){const T=`${h.length.toString()} ERROR-level ${h.length===1?"advisory":"advisories"} (${f.join(", ")}). Pass --no-strict-advisories to downgrade this to a warning and continue.`;return t.error(T),{error:T}}const m=l?await st({cwd:e,logger:t,spawner:s,stdoutToStderr:i}):void 0;return m?.error!==void 0?{error:m.error}:{result:g}}catch(g){d?.failed("codegen failed");const u=g instanceof Error?g.message:String(g);return t.error(`codegen failed: ${u}`),{error:`codegen failed: ${u}`}}},ea=(e,r)=>({dryRun:r.dryRun,entry:Se(e),environment:r.env,outDir:r.outDir,preview:r.preview,temporary:r.temporary}),Ar=(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=ea(e,r);return Ye(t,e,"deploy",a=>n.deploy({...o,configPath:a}))},ra=(e,r,t)=>{const n=Ar(e,r,t),o=Se(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},de=(e,r)=>({code:w.USAGE,descriptor:void 0,error:e,validation:A,...r}),ta=(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},na=(e,r,t)=>{const n=r.format==="json",o=r.dryRun!==!0,a=ra(e,r,t),s=H(I(e),a);return{args:s.args,captureStdout:o&&!n,captureStdoutSilently:o&&n,command:s.command,cwd:e,stdoutToStderr:n&&!o}},Ae=e=>{if(e.skipServices===!0)return"--skip-services";if(e.preview===!0)return"--preview uploads the app version only";if(e.temporary===!0)return"--temporary deploys the app to a throwaway account"},oa=(e,r)=>Ae(r)===void 0?me(e).services.map(t=>t.wranglerPath):[],Tr=(e,r,t,n,o)=>({cwd:e,environment:r.env,frameworkBuild:n,lazyFunctions:ee(r.lazyFunctions),logger:r.logger,outputJson:r.format==="json"||r.clientBuildOutputJson===!0,spawner:o,strictAdvisories:pe(r),target:t.id}),aa=(e,r,t)=>{const{toolchain:n}=t,o=n===void 0?`target "${t.id}" has no deploy command`:Ae(r);if(o!==void 0||n===void 0){const a=e.map(s=>s.worker).join(", ");r.logger.warn(`services not deployed (${o??""}): ${a} — deploy them yourself if the app calls anything new`);return}return n},Rr=(e,r)=>{for(const t of e){const n=ke(r(U(t.wranglerPath)));if(n!==void 0)return`service ${t.name} (${t.worker}): ${n}`}},sa=(e,r,t)=>{const{error:n,services:o}=me(e);if(n!==void 0||o.length===0)return;const a=re(t);if(a.toolchain===void 0||Ae(r)!==void 0)return;const s=r.skipCodegen===!0?!1:r.frameworkBuild,i=[...new Map(o.map(c=>[c.wranglerPath,c])).values()];return Rr(i,c=>Tr(c,r,a,s,M))},_r=(e,r,t)=>{const n=e.cwd??process.cwd(),o=Rt(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}}try{Ar(n,e,re(o.target))}catch(i){if(!(t&&i instanceof tt&&oe(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 a=e.openShardGatePassed===!0?void 0:no(n,e,r,oa(n,e));if(a!==void 0)return{kind:"refused",code:a.code,error:a.error,validation:A};const s=sa(n,e,o.target);return s!==void 0?(e.logger.error(s),{kind:"refused",code:w.USAGE,error:s,validation:A}):{kind:"ok",target:o.target}},ia=(e,r)=>e.apiSpec??(e.clientBuildRan===!0?it(r):void 0),ca=async(e,r,t)=>{if(r!=="celld")return;const n=await(e.celldToolchain??at)({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},da=async(e,r)=>{const t=e.cwd??process.cwd(),n=Er(e),o=pe(e),a={problems:[],wranglerPath:void 0},s=_r(e,r,!1);if(s.kind==="refused")return{code:s.code,error:s.error,validation:s.validation};const{target:i}=s,c=await ca(e,i,r);if(c!==void 0)return e.logger.error(c),{code:w.MISSING_DEPENDENCY,error:c,target:i,validation:a};let l;if(!e.skipCodegen){const v=await Zo(t,n,e.logger,ia(e,t),ee(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=Mt({allowDrift:e.allowSchemaDrift===!0,codegen:l,command:r,logger:e.logger,updateBaseline:e.updateSchemaBaseline===!0});if(v.blocked)return{error:`schema drift gate blocked ${r}`,schemaDrift:{blocked:!0,reason:v.reason},target:i,validation:a};d=v.rebless}const g=l&&Jt({current:l.architecture,cwd:t,environment:e.env,logger:e.logger});await Qo(t,e.logger,l?.cronTriggers,i,e.env,e.discoveryCache);const u=await Sr(t,e,r,i,"check");if(u!==void 0)return{error:u,target:i,validation:A};const h=oo(t,e,r,i);if(h!==void 0)return{code:h.code,error:h.error,target:i,validation:A};const f=lt({environment:e.env,projectRoot:t});return ta(f,e.logger)?{error:"wrangler validation failed",target:i,validation:f}:{codegen:l,reblessSchemaBaseline:d,recordArchitecture:g,target:i,validation:f}},la=e=>{X(y(e,".wrangler","deploy","config.json"),{force:!0})},ua=async(e,r,t)=>{const n=ke(e);if(n!==void 0)return{built:!1,error:n};const o=oe(e.cwd,r,t);return o&&la(e.cwd),{built:o,error:await ur(e)}},ga=(e,r,t)=>r||t===!1?br(e):void 0,fa=async(e,r,t,n)=>{const{error:o,services:a}=me(e);if(o!==void 0)return{code:w.FAILURE,error:o};if(a.length===0)return;const s=aa(a,r,t);if(s===void 0)return;const i=I(e),c=[...new Map(a.map(u=>[u.wranglerPath,u])).values()],l=r.skipCodegen===!0?!1:r.frameworkBuild,d=u=>Tr(u,r,t,l,n),g=Rr(c,d);if(g!==void 0)return r.logger.error(g),{code:w.USAGE,error:g};for(const u of c){const h=U(u.wranglerPath),f=d(h),{built:v,error:m}=await ua(f,l,r.env);if(m!==void 0){const $=`service ${u.name} (${u.worker}): ${m}`;return r.logger.error($),{code:w.FAILURE,error:$}}const T=ga(u.wranglerPath,v,l);let L;try{L=Ye(t,h,"deploy",$=>s.deploy({configPath:$??T??u.wranglerPath,dryRun:r.dryRun===!0,environment:r.env}))}catch($){return{code:w.FAILURE,error:`service ${u.name} (${u.worker}): ${$ instanceof Error?$.message:String($)}`}}L.commit();const P=H(i,L.command);r.logger.info(`deploying service ${u.name} (${u.worker}) via ${P.command} ${P.args.join(" ")}`);const R=await n({args:P.args,command:P.command,cwd:h,stdoutToStderr:r.format==="json"});if(R.code!==0)return{code:w.FAILURE,error:`service ${u.name} (${u.worker}): ${P.command} ${P.args.join(" ")} exited ${String(R.code)} — stopping before the app`}}},ha=async(e,r,t,n)=>{if(r!=="cloudflare")return;const o=e===void 0?void 0:D(e).parsed,a=(t===void 0?void 0:o?.env?.[t]?.account_id)??o?.account_id,s=await Et({accountId:a});(s.verdict==="near"||s.verdict==="full")&&n.warn(s.fix===void 0?s.message:`${s.message} ${s.fix}`)},ma=e=>e.dryRun!==!0&&e.temporary!==!0,va=e=>e.temporary===!0?"temporary":e.dryRun===!0?"preview":"defer",pa=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},ya=(e,r,t)=>{const n=[];for(const o of e)if(o.verdict==="ok")o.changesAccount===!0&&r.info(o.message);else if(o.verdict==="unchecked"&&t==="preview")r.warn(`dry run: ${o.message}${o.fix===void 0?"":` ${o.fix}`} A real deploy stops here.`);else{const a=pa(o);r.error(a),n.push(a)}return n},Dr=async(e,r,t,n,o,a,s)=>{const i=t==="cloudflare"&&r!==void 0?D(r).parsed:void 0;if(i===void 0)return;const c=(te(i,n).merged.artifacts??[]).flatMap(f=>typeof f?.binding=="string"&&typeof f.namespace=="string"?[{binding:f.binding,namespace:f.namespace}]:[]),l=c.length===0?void 0:ve(e,N(e),a).info?.jurisdiction;if(l===void 0)return;const d=[...new Map(c.map(f=>[f.namespace,f])).values()];if(s==="temporary"){o.warn(`--temporary deploys to a throwaway account, so the jurisdiction ("${l}") of Artifacts namespace ${d.map(f=>`"${f.namespace}"`).join(", ")} was not checked: it is created there on first use, in no jurisdiction.`);return}const g=(n===void 0?void 0:i.env?.[n]?.account_id)??i.account_id,u=await Promise.all(d.map(async f=>$t({...f,accountId:g,create:s==="create",jurisdiction:l,missingOk:s==="defer"||s==="preview"}))),h=ya(u,o,s);return h.length===0?void 0:h.join(`
43
+ `)},wa=async(e,r,t,n,o,a)=>{const s=ma(r)?await Dr(e,a,o,r.env,r.logger,r.discoveryCache,"create"):void 0;if(s!==void 0)return{code:w.FAILURE,error:s};const i=await Sr(e,r,"deploy",o);return i!==void 0?{code:w.FAILURE,error:i}:fa(e,r,t,n)},ka=async(e,r,t,n)=>{if(!(r.smokeLoad===!1||t.toolchain===void 0))return bn({composedEntry:Se(e),configPath:n,cwd:e,environment:r.env,launcher:r.smokeLauncher,logger:r.logger,toolchain:t.toolchain})},ba=async e=>{const r={...e,discoveryCache:e.discoveryCache??ot()},t=r.cwd??process.cwd(),n=Er(r),o=await da(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 de(o.error,{...m,...o.code===void 0?{}:{code:o.code}})}const{validation:a}=o,s=re(o.target),i=xn(r)??await Dr(t,a.wranglerPath,o.target,r.env,r.logger,r.discoveryCache,va(r))??await ka(t,r,s,a.wranglerPath);if(i!==void 0)return de(i);const c=s.toolchain?.prebuildsContainerImages===!0?await Yo(t,r):void 0;if(c!==void 0)return de(c);Ho(t,r.logger,s),dt(t,m=>{r.logger.warn(m)}),await ha(a.wranglerPath,o.target,r.env,r.logger);const{error:l,mintedSecretsFile:d}=await Jo(t,r,n,s);if(l!==void 0)return r.logger.error(l),{code:w.USAGE,descriptor:void 0,error:l,mintedSecretsFile:d,validation:a};const g=r.spawner??M,u=await wa(t,r,s,g,o.target,a.wranglerPath);if(u!==void 0)return{code:u.code,descriptor:void 0,error:u.error,mintedSecretsFile:d,validation:a};const h=na(t,r,s);r.logger.info(`deploying via ${h.command} ${h.args.join(" ")}`);const f=await g(h);return h.captureStdoutSilently===!0&&f.stdout!==void 0&&f.stdout!==""&&process.stderr.write(f.stdout),f.code!==0?{code:f.code,descriptor:h,mintedSecretsFile:d,validation:a}:{...await Bo({...o,cwd:t,descriptor:h,mintedSecretsFile:d,options:r,stdout:f.stdout}),logsAvailable:s.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:pe(e),lazyFunctions:ee(e.lazyFunctions),logger:r,outputJson:e.format==="json"||e.clientBuildOutputJson===!0,spawner:e.spawner,target:e.target},o=ke(n);if(o!==void 0)return r.error(o),{code:w.USAGE,descriptor:void 0,error:o,validation:A};nt(t);const a=await ur(n);if(a!==void 0)return r.error(a),{code:w.FAILURE,descriptor:void 0,error:a,validation:A}},$a=(e,r)=>{const t=r.skipCodegen===!0?!1:r.frameworkBuild;return oe(e,t,r.env)?r.env:void 0},Ea=async e=>{const{logger:r}=e,t=e.cwd??process.cwd(),n=_r(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 a=e.dryRun===!0?cr(t):void 0;let s;try{if(s=await ba({...e,clientBuildEnvironment:$a(t,e),clientBuildRan:Dn(t,e.skipCodegen===!0?!1:e.frameworkBuild,e.env),logger:r,openShardGatePassed:!0}),s.code===0&&e.emitBindings!==void 0){const{error:i}=At({destination:e.emitBindings,logger:r,projectRoot:e.cwd??process.cwd()});i!==void 0&&(r.error(i),s={...s,code:w.USAGE})}}finally{a?.()}if(e.format==="json")return s;if(s.code===0&&e.dryRun!==!0&&e.preview!==!0)Yt({cwd:e.cwd??process.cwd(),env:e.env,logger:e.logger,logsAvailable:s.logsAvailable===!0,mintedSecretsFile:s.mintedSecretsFile,url:s.deployment?.url});else if(s.code===0&&e.preview===!0){const i=s.deployment?.url;e.logger.success(i===void 0?"preview version uploaded":`preview version uploaded — ${i}`)}return s},ts=Tt(async({cwd:e,format:r,logger:t,options:n})=>{const o=Sn(e,n.root),a=await Ea({allowOpenShards:n.allowOpenShards===!0,allowSchemaDrift:n.allowSchemaDrift===!0,apiSpec:wt(n.apiSpec),frameworkBuild:n.prebuilt===!0?!1:n.frameworkBuild,lazyFunctions:ee(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:rr({cwd:o,env:n.env,url:n.migrateUrl}),migrateYes:n.migrateYes===!0,preview:n.preview===!0,skipCodegen:n.prebuilt===!0,skipServices:n.skipServices===!0,smokeLoad:n.smokeLoad,strictAdvisories:n.strictAdvisories,target:n.target,temporary:n.temporary===!0,updateSchemaBaseline:n.updateSchemaBaseline===!0});return{code:a.code,data:{deployment:a.deployment,healthCheck:a.healthCheck,mintedSecretsFile:a.mintedSecretsFile,schemaDrift:a.schemaDrift,validation:a.validation},error:a.error}});export{da as a,Qo as b,ts as e,Sn as p,Ea as r,ka as s,En as v};
@@ -1 +1 @@
1
- import{resolveLazyFunctions as t,resolveDeployDriver as o}from"@lunora/config";import{p as l}from"../packem_shared/api-spec-lYyq4vL6.mjs";import{d as s}from"../packem_shared/command-B6vu47iR.mjs";import{EXIT_CODE as c}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";import{a as d,s as m}from"./handler.mjs";const n=async r=>{const a=r.cwd??process.cwd(),e=await d({allowSchemaDrift:r.allowSchemaDrift,apiSpec:r.apiSpec,lazyFunctions:t(r.lazyFunctions),cwd:a,logger:r.logger,spawner:r.spawner,strictAdvisories:r.strictAdvisories,target:r.target,updateSchemaBaseline:r.updateSchemaBaseline},"prepare");if(e.error!==void 0)return{code:e.code??c.USAGE,error:e.error,...e.schemaDrift===void 0?{}:{schemaDrift:e.schemaDrift},validation:e.validation};const i=await m(a,{env:void 0,logger:r.logger,smokeLauncher:r.smokeLauncher,smokeLoad:r.smokeLoad},o(e.target),e.validation.wranglerPath);return i!==void 0?{code:c.FAILURE,error:i,validation:e.validation}:(e.reblessSchemaBaseline?.(),r.logger.success("project is ready to deploy"),{code:0,validation:e.validation})},h=s(({cwd:r,logger:a,options:e})=>n({allowSchemaDrift:e.allowSchemaDrift===!0,apiSpec:l(e.apiSpec),lazyFunctions:t(e.lazyFunctions),cwd:r,logger:a,smokeLoad:e.smokeLoad,strictAdvisories:e.strictAdvisories,target:e.target,updateSchemaBaseline:e.updateSchemaBaseline===!0}));export{h as execute,n as runPrepareCommand};
1
+ import{r as h}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{r as k,a as v}from"../packem_shared/admin-url-DJB8P6Jh.mjs";import{d as m}from"../packem_shared/command-B6vu47iR.mjs";import{EXIT_CODE as d,exitCodeForStatus as w}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";import{a as f}from"../packem_shared/resolve-target-C_ZloTvd.mjs";const A="/_lunora/admin/pause",i=(e,r,o)=>(e.error(r),{code:o,error:r}),l=e=>e.paused?`paused${e.pausedAt===void 0?"":` since ${new Date(e.pausedAt).toISOString()}`}${e.reason===void 0?"":` — ${e.reason}`}`:"running",p=async e=>{const{logger:r}=e;if(e.prod&&e.url===void 0)return i(r,`--prod requires an explicit --url (refusing to ${e.action} the implicit localhost worker)`,d.USAGE);const o=k(e.url,r,e.cwd);if(o===void 0)return{code:d.USAGE,error:"could not resolve a usable worker URL"};const{token:n}=h({cwd:e.cwd??process.cwd(),token:e.token,url:o});if(!n)return i(r,"admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)",d.AUTH);const t=`${o}${A}`,a=e.fetchImpl??v,s=e.action==="status"?await a(t,{headers:{authorization:`Bearer ${n}`},method:"GET"}):await a(t,{body:JSON.stringify({paused:e.action==="pause",...e.reason===void 0?{}:{reason:e.reason}}),headers:{authorization:`Bearer ${n}`,"content-type":"application/json"},method:"POST"}),u=await s.text();if(!s.ok)return i(r,`${e.action} failed: HTTP ${String(s.status)}: ${u}`,w(s.status));let c;try{c=JSON.parse(u)}catch{return i(r,`${e.action} failed: worker returned non-JSON: ${u}`,1)}return e.format!=="json"&&(c.supported?e.action==="status"?r.info(l(c)):r.success(`${o}: ${l(c)}`):r.warn("this deployment has no scheduler, so it cannot be paused")),{code:0,result:c}},$=(e,r)=>{if(e==="resume")return r.length===0?void 0:`resume takes no arguments, got "${r.join(" ")}"`;if(r.length>1||r.length===1&&r[0]!=="status")return`unknown arguments "${r.join(" ")}" — expected status, or none to pause`},O=m(async({argument:e,cwd:r,format:o,logger:n,options:t})=>{const a=$("pause",e);if(a!==void 0)return n.error(`pause: ${a}`),{code:d.USAGE,error:a};const[s]=e,u=await p({action:s==="status"?"status":"pause",cwd:r,format:o,logger:n,prod:t.prod,reason:t.reason,token:t.token,url:f({cwd:r,prod:t.prod===!0,url:t.url})});return{code:u.code,data:u.result,error:u.error}}),T=m(async({argument:e,cwd:r,format:o,logger:n,options:t})=>{const a=$("resume",e);if(a!==void 0)return n.error(`resume: ${a}`),{code:d.USAGE,error:a};const s=await p({action:"resume",cwd:r,format:o,logger:n,prod:t.prod,token:t.token,url:f({cwd:r,prod:t.prod===!0,url:t.url})});return{code:s.code,data:s.result,error:s.error}});export{O as executePause,T as executeResume,$ as pauseUsageError,p as runPauseCommand};
@@ -1 +1 @@
1
- import{d as l}from"../packem_shared/command-B6vu47iR.mjs";import{EXIT_CODE as n}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";import{r as s,b as t,a as o}from"../packem_shared/commands-DC3ZX1yk.mjs";const y=l(({argument:a,cwd:u,format:m,logger:e,options:r})=>{const f=a[0],c=a.slice(1);if(f==="add")return s({allowUnsafeSource:r.allowUnsafeSource===!0,cwd:u,diff:r.diff===!0,dryRun:r.dryRun===!0,format:m,from:r.from,logger:e,names:c,overwrite:r.overwrite===!0,ref:r.ref,source:r.source,yes:r.yes===!0});if(f==="list")return s({allowUnsafeSource:r.allowUnsafeSource===!0,cwd:u,format:m,from:r.from,list:!0,logger:e,names:[],ref:r.ref,source:r.source});if(f==="view")return t({allowUnsafeSource:r.allowUnsafeSource===!0,cwd:u,from:r.from,logger:e,names:c,ref:r.ref,source:r.source});if(f==="build")return o({check:r.check===!0,cwd:u,from:r.from,logger:e,names:[],out:r.out});const d="registry: unknown subcommand. Usage: lunora registry <add|list|view|build> [names…]";return e.error(d),{code:n.USAGE,error:d}});export{y as execute};
1
+ import{resolveLazyFunctions as t,resolveDeployDriver as o}from"@lunora/config";import{p as l}from"../packem_shared/api-spec-lYyq4vL6.mjs";import{d as s}from"../packem_shared/command-B6vu47iR.mjs";import{EXIT_CODE as c}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";import{a as d,s as m}from"./handler.mjs";const n=async r=>{const a=r.cwd??process.cwd(),e=await d({allowSchemaDrift:r.allowSchemaDrift,apiSpec:r.apiSpec,lazyFunctions:t(r.lazyFunctions),cwd:a,logger:r.logger,spawner:r.spawner,strictAdvisories:r.strictAdvisories,target:r.target,updateSchemaBaseline:r.updateSchemaBaseline},"prepare");if(e.error!==void 0)return{code:e.code??c.USAGE,error:e.error,...e.schemaDrift===void 0?{}:{schemaDrift:e.schemaDrift},validation:e.validation};const i=await m(a,{env:void 0,logger:r.logger,smokeLauncher:r.smokeLauncher,smokeLoad:r.smokeLoad},o(e.target),e.validation.wranglerPath);return i!==void 0?{code:c.FAILURE,error:i,validation:e.validation}:(e.reblessSchemaBaseline?.(),r.logger.success("project is ready to deploy"),{code:0,validation:e.validation})},h=s(({cwd:r,logger:a,options:e})=>n({allowSchemaDrift:e.allowSchemaDrift===!0,apiSpec:l(e.apiSpec),lazyFunctions:t(e.lazyFunctions),cwd:r,logger:a,smokeLoad:e.smokeLoad,strictAdvisories:e.strictAdvisories,target:e.target,updateSchemaBaseline:e.updateSchemaBaseline===!0}));export{h as execute,n as runPrepareCommand};
@@ -1 +1 @@
1
- import{existsSync as u,readdirSync as d,statSync as g,mkdirSync as h,writeFileSync as w,readFileSync as y}from"node:fs";import{fileURLToPath as v}from"node:url";import{AGENT_RULES_DIR as a,detectAgentRules as R,LUNORA_SKILL_NAMES as L}from"@lunora/config";import{join as i,relative as A,resolve as E,dirname as m}from"@visulima/path";import{f as I}from"../packem_shared/cli-manifest-DoQ_3bzs.mjs";import{d as $}from"../packem_shared/command-B6vu47iR.mjs";import{EXIT_CODE as _}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";const b=(e=m(v(import.meta.url)))=>{const r=I(e),t=r===void 0?void 0:i(r,"skills");return t!==void 0&&u(t)?t:void 0},j=e=>d(e).filter(r=>{const t=i(e,r);return g(t).isDirectory()&&u(i(t,"SKILL.md"))}),f=(e,r,t)=>{h(r,{recursive:!0});let n=!1;for(const o of d(e)){const l=i(e,o),s=i(r,o);if(g(l).isDirectory()){n=f(l,s,t)||n;continue}u(s)&&!t||(w(s,y(l)),n=!0)}return n},D=["pnpm-workspace.yaml","pnpm-lock.yaml","yarn.lock","package-lock.json","bun.lock","bun.lockb",".git"],O=e=>{let r=e;for(;;){if(D.some(n=>u(i(r,n))))return r;const t=m(r);if(t===r)return e;r=t}},k=(e,r)=>r===void 0?O(e):E(e,r),U=e=>{const r=e.cwd??process.cwd(),t=k(r,e.dir),n=e.overwrite===!0,o=b();if(o===void 0)return e.logger.error("rules: could not locate the bundled skills (is @lunora/cli installed correctly?)."),{code:1,installed:[],skipped:[]};const l=[],s=[];for(const c of j(o)){const S=i(t,a,c);f(i(o,c),S,n)?l.push(c):s.push(c)}const p=A(r,i(t,a))||a;return l.length>0&&e.logger.success(`Installed ${String(l.length)} Lunora skill(s) into ${p}/: ${l.join(", ")}.`),s.length>0&&e.logger.info(`Skipped ${String(s.length)} existing skill(s) (re-run with --overwrite to replace): ${s.join(", ")}.`),e.logger.info("Your AI coding agent will pick these up automatically. Start with the `lunora` skill."),{code:0,installed:l,skipped:s}},x=e=>{const r=e.cwd??process.cwd(),t=k(r,e.dir),n=R(t);return n.installed?(e.logger.success(`Lunora agent rules are installed (${String(n.present.length)}/${String(L.length)} skills).`),n.missing.length>0&&e.logger.info(`Missing: ${n.missing.join(", ")}. Run \`lunora rules install\` to add them.`),{code:0,installed:n.present,skipped:[]}):(e.logger.warn("Lunora agent rules are not installed. Run `lunora rules install` so your AI agent knows how to use Lunora."),{code:e.strict===!0?1:0,installed:n.present,skipped:[]})},G=$(({argument:e,cwd:r,logger:t,options:n})=>{const o=e[0]??"check";return o==="install"?U({cwd:r,dir:n.dir,logger:t,overwrite:n.overwrite===!0}):o==="check"?x({cwd:r,dir:n.dir,logger:t,strict:n.strict===!0}):(t.error("rules: unknown subcommand. Usage: lunora rules <install|check>"),{code:_.USAGE})});export{G as execute,j as listBundledSkills,b as resolveBundledSkillsDirectory,x as runRulesCheck,U as runRulesInstall};
1
+ import{d as l}from"../packem_shared/command-B6vu47iR.mjs";import{EXIT_CODE as n}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";import{r as s,b as t,a as o}from"../packem_shared/commands-DC3ZX1yk.mjs";const y=l(({argument:a,cwd:u,format:m,logger:e,options:r})=>{const f=a[0],c=a.slice(1);if(f==="add")return s({allowUnsafeSource:r.allowUnsafeSource===!0,cwd:u,diff:r.diff===!0,dryRun:r.dryRun===!0,format:m,from:r.from,logger:e,names:c,overwrite:r.overwrite===!0,ref:r.ref,source:r.source,yes:r.yes===!0});if(f==="list")return s({allowUnsafeSource:r.allowUnsafeSource===!0,cwd:u,format:m,from:r.from,list:!0,logger:e,names:[],ref:r.ref,source:r.source});if(f==="view")return t({allowUnsafeSource:r.allowUnsafeSource===!0,cwd:u,from:r.from,logger:e,names:c,ref:r.ref,source:r.source});if(f==="build")return o({check:r.check===!0,cwd:u,from:r.from,logger:e,names:[],out:r.out});const d="registry: unknown subcommand. Usage: lunora registry <add|list|view|build> [names…]";return e.error(d),{code:n.USAGE,error:d}});export{y as execute};
@@ -1,3 +1 @@
1
- import{existsSync as S}from"node:fs";import{mkdtemp as v,writeFile as k,rm as j}from"node:fs/promises";import{tmpdir as R}from"node:os";import{discoverSchema as C,schemaFromIr as T}from"@lunora/codegen";import{seedPlan as O}from"@lunora/seed";import{join as w}from"@visulima/path";import{Project as $}from"ts-morph";import{t as y}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{d as A}from"../packem_shared/command-B6vu47iR.mjs";import{EXIT_CODE as m}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";import{a as E}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{b as F}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{runResetCommand as N}from"./runResetCommand.mjs";import{r as U}from"../packem_shared/import-DoAUdyfU.mjs";const I=(e,r)=>typeof r=="bigint"?Number(r):r instanceof ArrayBuffer?[...new Uint8Array(r)]:r,f=(e,r)=>({code:e,error:r,ndjson:""}),p=(e,r)=>{if(!S(r)){const o=`schema not found: ${r} — run \`vis generate lunora-table --name=<name>\` to create one`;return e.logger.error(o),f(m.NOT_FOUND,o)}if(e.reset===!0&&y({prod:e.prod,url:e.url})){const o="--reset only clears local .wrangler/state and cannot be combined with --prod or a remote --url";return e.logger.error(o),f(m.USAGE,o)}},x=async(e,r,o,t,n)=>{const s=await v(w(R(),"lunora-seed-")),d=w(s,"rows.ndjson");await k(d,e,"utf8");try{const a=await U({batchSize:n.batchSize,cwd:t,fetchImpl:n.fetchImpl,file:d,logger:n.logger,prod:n.prod,token:n.token,url:n.url,yes:!0}),i=a.body?.conflicts??0;return i>0&&n.logger.warn(`${String(i)} row(s) skipped — their _id already exists. Seeding is deterministic; re-run with --reset to wipe local state first, or a different --seed for fresh ids.`),{code:a.code,data:{conflicts:i,generated:r,inserted:a.inserted,tables:o},ndjson:e,...a.error===void 0?{}:{error:a.error}}}finally{await j(s,{force:!0,recursive:!0}).catch(()=>{})}},z=(e,r)=>{if(e.table===void 0||r.tables.some(n=>n.name===e.table))return;const o=r.tables.map(n=>n.name).join(", "),t=`unknown table "${e.table}" — schema defines: ${o||"(no tables)"}`;return e.logger.error(t),f(m.USAGE,t)},D=async(e,r)=>{if(!y({prod:e.prod,url:e.url})||e.yes===!0)return;if(!process.stdin.isTTY&&e.confirm===void 0){const s="seed: refusing to insert into a non-local target without confirmation — re-run with --yes";return e.logger.error(s),f(m.USAGE,s)}if(!await(e.confirm??F)(`This will insert ${String(r)} generated row(s) into ${e.url??"the production worker"}. Continue?`))return e.logger.info("seed: aborted"),f(m.CANCELLED,"seed: aborted at the confirmation prompt")},_=e=>{const r=[];for(const{rows:o,table:t}of e)for(const n of o)r.push(JSON.stringify({doc:n,table:t},I));return{lines:r,ndjson:r.length>0?`${r.join(`
2
- `)}
3
- `:""}},G=async e=>{const r=e.cwd??process.cwd(),o=e.format==="json",t=w(r,"lunora","schema.ts"),n=p(e,t);if(n!==void 0)return n;const s=new $({skipAddingFilesFromTsConfig:!0}),d=C(s,t),a=z(e,d);if(a!==void 0)return a;const i=T(d),l=O(i,{allowOrphans:e.allowOrphans===!0,defaultCount:e.count??10,now:e.now,only:e.table===void 0?void 0:[e.table],seed:e.seed??0}),{lines:h,ndjson:c}=_(l),u=h.length;if(e.dryRun===!0)return!o&&c.length>0&&process.stdout.write(c),e.logger.info(`generated ${String(u)} row(s) across ${String(l.length)} table(s) — dry run, nothing inserted`),{code:0,data:{conflicts:0,generated:u,inserted:0,rows:o?h.map(g=>JSON.parse(g)):void 0,tables:l.length},ndjson:c};if(u===0)return e.logger.warn("no rows generated — nothing to insert"),{code:0,data:{conflicts:0,generated:0,inserted:0,tables:l.length},ndjson:c};if(e.reset===!0){const g=await N({confirm:e.confirm,cwd:r,logger:e.logger,yes:e.yes});if(g.code!==0)return{code:g.code,error:"seed: --reset could not clear local state",ndjson:c}}const b=await D(e,u);return b!==void 0?b:x(c,u,l.length,r,e)},ee=A(async({cwd:e,format:r,logger:o,options:t})=>{const n=await G({allowOrphans:t.allowOrphans===!0,batchSize:t.batchSize,count:t.count,cwd:e,dryRun:t.dryRun===!0,format:r,logger:o,prod:t.prod===!0,reset:t.reset===!0,now:t.now,seed:t.seed,table:t.table,token:t.token,url:E({cwd:e,prod:t.prod===!0,url:t.url}),yes:t.yes===!0});return{code:n.code,data:n.data,error:n.error}});export{ee as execute,G as runSeedCommand};
1
+ import{existsSync as u,readdirSync as d,statSync as g,mkdirSync as h,writeFileSync as w,readFileSync as y}from"node:fs";import{fileURLToPath as v}from"node:url";import{AGENT_RULES_DIR as a,detectAgentRules as R,LUNORA_SKILL_NAMES as L}from"@lunora/config";import{join as i,relative as A,resolve as E,dirname as m}from"@visulima/path";import{f as I}from"../packem_shared/cli-manifest-DoQ_3bzs.mjs";import{d as $}from"../packem_shared/command-B6vu47iR.mjs";import{EXIT_CODE as _}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";const b=(e=m(v(import.meta.url)))=>{const r=I(e),t=r===void 0?void 0:i(r,"skills");return t!==void 0&&u(t)?t:void 0},j=e=>d(e).filter(r=>{const t=i(e,r);return g(t).isDirectory()&&u(i(t,"SKILL.md"))}),f=(e,r,t)=>{h(r,{recursive:!0});let n=!1;for(const o of d(e)){const l=i(e,o),s=i(r,o);if(g(l).isDirectory()){n=f(l,s,t)||n;continue}u(s)&&!t||(w(s,y(l)),n=!0)}return n},D=["pnpm-workspace.yaml","pnpm-lock.yaml","yarn.lock","package-lock.json","bun.lock","bun.lockb",".git"],O=e=>{let r=e;for(;;){if(D.some(n=>u(i(r,n))))return r;const t=m(r);if(t===r)return e;r=t}},k=(e,r)=>r===void 0?O(e):E(e,r),U=e=>{const r=e.cwd??process.cwd(),t=k(r,e.dir),n=e.overwrite===!0,o=b();if(o===void 0)return e.logger.error("rules: could not locate the bundled skills (is @lunora/cli installed correctly?)."),{code:1,installed:[],skipped:[]};const l=[],s=[];for(const c of j(o)){const S=i(t,a,c);f(i(o,c),S,n)?l.push(c):s.push(c)}const p=A(r,i(t,a))||a;return l.length>0&&e.logger.success(`Installed ${String(l.length)} Lunora skill(s) into ${p}/: ${l.join(", ")}.`),s.length>0&&e.logger.info(`Skipped ${String(s.length)} existing skill(s) (re-run with --overwrite to replace): ${s.join(", ")}.`),e.logger.info("Your AI coding agent will pick these up automatically. Start with the `lunora` skill."),{code:0,installed:l,skipped:s}},x=e=>{const r=e.cwd??process.cwd(),t=k(r,e.dir),n=R(t);return n.installed?(e.logger.success(`Lunora agent rules are installed (${String(n.present.length)}/${String(L.length)} skills).`),n.missing.length>0&&e.logger.info(`Missing: ${n.missing.join(", ")}. Run \`lunora rules install\` to add them.`),{code:0,installed:n.present,skipped:[]}):(e.logger.warn("Lunora agent rules are not installed. Run `lunora rules install` so your AI agent knows how to use Lunora."),{code:e.strict===!0?1:0,installed:n.present,skipped:[]})},G=$(({argument:e,cwd:r,logger:t,options:n})=>{const o=e[0]??"check";return o==="install"?U({cwd:r,dir:n.dir,logger:t,overwrite:n.overwrite===!0}):o==="check"?x({cwd:r,dir:n.dir,logger:t,strict:n.strict===!0}):(t.error("rules: unknown subcommand. Usage: lunora rules <install|check>"),{code:_.USAGE})});export{G as execute,j as listBundledSkills,b as resolveBundledSkillsDirectory,x as runRulesCheck,U as runRulesInstall};
@@ -1 +1,3 @@
1
- import{r as $}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{r as S,a as p}from"../packem_shared/admin-url-DJB8P6Jh.mjs";import{d as k}from"../packem_shared/command-B6vu47iR.mjs";import{EXIT_CODE as u,exitCodeForStatus as b}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";import{a as y}from"../packem_shared/resolve-target-C_ZloTvd.mjs";const w="/_lunora/admin/shard-registry/prune",f=["prune"],d=(e,r,a)=>(e.error(r),{code:a,error:r}),g=(e,r,a)=>{for(const{shardKey:t,table:n}of r.released)e.info(`${a?"would release":"released"} ${t} (${n})`);for(const{message:t,shardKey:n,tables:l}of r.failed)e.error(`could not check ${n} (${l.join(", ")}) — kept: ${t}`);const s=`${String(r.released.length)} ${a?"would be released":"released"}, ${String(r.kept.length)} kept (still hold rows), ${String(r.failed.length)} unreachable`;r.failed.length>0?e.warn(`${s} — re-run to retry the unreachable shards`):e.success(s)},A=async e=>{const{logger:r}=e;if(!f.includes(e.subcommand))return d(r,`shards: unknown subcommand "${e.subcommand??""}" — expected ${f.join(" | ")}`,u.USAGE);if(e.prod&&e.url===void 0)return d(r,"--prod requires an explicit --url (refusing to prune the implicit localhost worker)",u.USAGE);const a=S(e.url,r,e.cwd);if(a===void 0)return{code:u.USAGE,error:"could not resolve a usable worker URL"};const{token:s}=$({cwd:e.cwd??process.cwd(),token:e.token,url:a});if(!s)return d(r,"admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)",u.AUTH);const t=`${a}${w}`,n=e.fetchImpl??p,l=e.tables?.split(",").map(h=>h.trim()).filter(h=>h!==""),i=e.dryRun===!0;r.info(`POST ${t} -> shards prune${i?" (dry run)":""}`);const c=await n(t,{body:JSON.stringify({dryRun:i,...l===void 0?{}:{tables:l}}),headers:{authorization:`Bearer ${s}`,"content-type":"application/json"},method:"POST"}),m=await c.text();if(!c.ok)return d(r,`shards prune failed: HTTP ${String(c.status)}: ${m}`,b(c.status));let o;try{o=JSON.parse(m)}catch{return d(r,`shards prune failed: worker returned non-JSON: ${m}`,1)}return e.format!=="json"&&g(r,o,i),o.failed.length>0?{code:1,error:`shards prune: ${String(o.failed.length)} shard(s) could not be checked`,result:o}:{code:0,result:o}},E=k(async({argument:e,cwd:r,format:a,logger:s,options:t})=>{const n=await A({cwd:r,dryRun:t.dryRun===!0,format:a,logger:s,prod:t.prod,subcommand:e[0],tables:t.tables,token:t.token,url:y({cwd:r,prod:t.prod===!0,url:t.url})});return{code:n.code,data:n.result,error:n.error}});export{E as execute,A as runShardsCommand};
1
+ import{existsSync as S}from"node:fs";import{mkdtemp as v,writeFile as k,rm as j}from"node:fs/promises";import{tmpdir as R}from"node:os";import{discoverSchema as C,schemaFromIr as T}from"@lunora/codegen";import{seedPlan as O}from"@lunora/seed";import{join as w}from"@visulima/path";import{Project as $}from"ts-morph";import{t as y}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{d as A}from"../packem_shared/command-B6vu47iR.mjs";import{EXIT_CODE as m}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";import{a as E}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{b as F}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{runResetCommand as N}from"./runResetCommand.mjs";import{r as U}from"../packem_shared/import-DoAUdyfU.mjs";const I=(e,r)=>typeof r=="bigint"?Number(r):r instanceof ArrayBuffer?[...new Uint8Array(r)]:r,f=(e,r)=>({code:e,error:r,ndjson:""}),p=(e,r)=>{if(!S(r)){const o=`schema not found: ${r} — run \`vis generate lunora-table --name=<name>\` to create one`;return e.logger.error(o),f(m.NOT_FOUND,o)}if(e.reset===!0&&y({prod:e.prod,url:e.url})){const o="--reset only clears local .wrangler/state and cannot be combined with --prod or a remote --url";return e.logger.error(o),f(m.USAGE,o)}},x=async(e,r,o,t,n)=>{const s=await v(w(R(),"lunora-seed-")),d=w(s,"rows.ndjson");await k(d,e,"utf8");try{const a=await U({batchSize:n.batchSize,cwd:t,fetchImpl:n.fetchImpl,file:d,logger:n.logger,prod:n.prod,token:n.token,url:n.url,yes:!0}),i=a.body?.conflicts??0;return i>0&&n.logger.warn(`${String(i)} row(s) skipped — their _id already exists. Seeding is deterministic; re-run with --reset to wipe local state first, or a different --seed for fresh ids.`),{code:a.code,data:{conflicts:i,generated:r,inserted:a.inserted,tables:o},ndjson:e,...a.error===void 0?{}:{error:a.error}}}finally{await j(s,{force:!0,recursive:!0}).catch(()=>{})}},z=(e,r)=>{if(e.table===void 0||r.tables.some(n=>n.name===e.table))return;const o=r.tables.map(n=>n.name).join(", "),t=`unknown table "${e.table}" — schema defines: ${o||"(no tables)"}`;return e.logger.error(t),f(m.USAGE,t)},D=async(e,r)=>{if(!y({prod:e.prod,url:e.url})||e.yes===!0)return;if(!process.stdin.isTTY&&e.confirm===void 0){const s="seed: refusing to insert into a non-local target without confirmation — re-run with --yes";return e.logger.error(s),f(m.USAGE,s)}if(!await(e.confirm??F)(`This will insert ${String(r)} generated row(s) into ${e.url??"the production worker"}. Continue?`))return e.logger.info("seed: aborted"),f(m.CANCELLED,"seed: aborted at the confirmation prompt")},_=e=>{const r=[];for(const{rows:o,table:t}of e)for(const n of o)r.push(JSON.stringify({doc:n,table:t},I));return{lines:r,ndjson:r.length>0?`${r.join(`
2
+ `)}
3
+ `:""}},G=async e=>{const r=e.cwd??process.cwd(),o=e.format==="json",t=w(r,"lunora","schema.ts"),n=p(e,t);if(n!==void 0)return n;const s=new $({skipAddingFilesFromTsConfig:!0}),d=C(s,t),a=z(e,d);if(a!==void 0)return a;const i=T(d),l=O(i,{allowOrphans:e.allowOrphans===!0,defaultCount:e.count??10,now:e.now,only:e.table===void 0?void 0:[e.table],seed:e.seed??0}),{lines:h,ndjson:c}=_(l),u=h.length;if(e.dryRun===!0)return!o&&c.length>0&&process.stdout.write(c),e.logger.info(`generated ${String(u)} row(s) across ${String(l.length)} table(s) — dry run, nothing inserted`),{code:0,data:{conflicts:0,generated:u,inserted:0,rows:o?h.map(g=>JSON.parse(g)):void 0,tables:l.length},ndjson:c};if(u===0)return e.logger.warn("no rows generated — nothing to insert"),{code:0,data:{conflicts:0,generated:0,inserted:0,tables:l.length},ndjson:c};if(e.reset===!0){const g=await N({confirm:e.confirm,cwd:r,logger:e.logger,yes:e.yes});if(g.code!==0)return{code:g.code,error:"seed: --reset could not clear local state",ndjson:c}}const b=await D(e,u);return b!==void 0?b:x(c,u,l.length,r,e)},ee=A(async({cwd:e,format:r,logger:o,options:t})=>{const n=await G({allowOrphans:t.allowOrphans===!0,batchSize:t.batchSize,count:t.count,cwd:e,dryRun:t.dryRun===!0,format:r,logger:o,prod:t.prod===!0,reset:t.reset===!0,now:t.now,seed:t.seed,table:t.table,token:t.token,url:E({cwd:e,prod:t.prod===!0,url:t.url}),yes:t.yes===!0});return{code:n.code,data:n.data,error:n.error}});export{ee as execute,G as runSeedCommand};
@@ -1 +1 @@
1
- import{existsSync as h}from"node:fs";import{join as p}from"node:path";import{runCodegen as g}from"@lunora/codegen";import{resolveLazyFunctions as u}from"@lunora/config";import{validateWranglerProject as v,wranglerCodegenInputs as y}from"@lunora/config/cloudflare";import{a as w,e as S,r as k}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as j}from"../packem_shared/api-spec-lYyq4vL6.mjs";import{r as E}from"../packem_shared/codegen-error-AmH54ofi.mjs";import{d as A}from"../packem_shared/command-B6vu47iR.mjs";import{r as D}from"../packem_shared/deploy-target-resolve-BTCW1Iv4.mjs";import{EXIT_CODE as R}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";import{r as $,p as b}from"../packem_shared/health-probe-Bw9JFfIy.mjs";import{defaultSpawner as F}from"../packem_shared/createRecordingSpawner-01ZngIwK.mjs";import{execArgsFor as U,detectPackageManager as x}from"@lunora/config/cli";const P=async(r,a,t)=>{if(!h(p(r,"tsconfig.json")))return{warning:"no tsconfig.json found — skipping TypeScript type-check"};const o=U(x(r),"tsc",["--noEmit","-p","tsconfig.json"]),e=await a({args:o.args,command:o.command,cwd:r,stdoutToStderr:t==="json"});return e.code===0?{}:{error:`type errors: tsc --noEmit exited ${String(e.code)}`}},T=async(r,a)=>{if(r.healthUrl===void 0||r.healthUrl==="")return;const t=await b({baseUrl:r.healthUrl,fetchImpl:r.healthFetch});if(t.error===void 0){a.success(`verify: health probe ok (${t.url})`);return}return t.error},z=(r,a)=>{const{errorAdvisories:t,names:o,shouldBlock:e}=S(r,k(a));if(e)return`${t.length.toString()} ERROR-level ${t.length===1?"advisory":"advisories"} (${o.join(", ")}). Pass --no-strict-advisories to downgrade this to a warning and continue.`},C=(r,a,t,o)=>{if(a.length===0&&t.length===0)return r.success("verify: project is valid"),{code:0,errors:[],warnings:[],wranglerPath:o};if(t.length>0){r.warn("verify: warnings:");for(const e of t)r.warn(` - ${e}`)}if(a.length>0){r.error("verify: errors:");for(const e of a){r.error(` - ${e}`);const s=E(e);s!==void 0&&r.error(s)}return{code:1,error:a[0],errors:a,warnings:t,wranglerPath:o}}return r.success("verify: project is valid (with warnings)"),{code:0,errors:[],warnings:t,wranglerPath:o}},H=async r=>{const a=r.cwd??process.cwd(),{logger:t}=r,o=v({environment:r.env,projectRoot:a}),e=[...o.report.errors],s=[...o.report.warnings];try{const n=D(a,r.target);if(n.target===void 0){const c=n.error??"unknown deploy target";return t.error(c),{code:R.USAGE,error:c,errors:[c],warnings:[],wranglerPath:void 0}}const i=g({apiSpec:r.apiSpec,lazyFunctions:u(r.lazyFunctions),dryRun:!0,projectRoot:a,target:n.target,...y(a)}),l=w(i.platformDiagnostics,t);e.push(...l.errors),s.push(...l.warnings);const f=z(i.advisories,r);f!==void 0&&e.push(f);const m=$({allowDrift:r.allowSchemaDrift===!0,codegen:i,command:"verify",logger:t,readOnly:!0});m.blocked&&e.push(m.reason)}catch(n){const i=n instanceof Error?n.message:String(n);e.push(`codegen failed: ${i}`)}if(r.typecheck!==!1){const n=await P(a,r.spawner??F,r.format??"pretty");n.error!==void 0&&e.push(n.error),n.warning!==void 0&&s.push(n.warning)}const d=await T(r,t);return d!==void 0&&e.push(d),C(t,e,s,o.wranglerPath)},Q=A(async({cwd:r,format:a,logger:t,options:o})=>{const e=await H({allowSchemaDrift:o.allowSchemaDrift===!0,apiSpec:j(o.apiSpec),lazyFunctions:u(o.lazyFunctions),cwd:r,env:o.env,format:a,healthUrl:o.healthUrl,logger:t,strictAdvisories:o.strictAdvisories,target:o.target,typecheck:o.typecheck===!1?!1:void 0});return{code:e.code,data:{errors:e.errors,warnings:e.warnings,wranglerPath:e.wranglerPath},error:e.error}});export{Q as execute,H as runVerifyCommand};
1
+ import{r as $}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{r as S,a as p}from"../packem_shared/admin-url-DJB8P6Jh.mjs";import{d as k}from"../packem_shared/command-B6vu47iR.mjs";import{EXIT_CODE as u,exitCodeForStatus as b}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";import{a as y}from"../packem_shared/resolve-target-C_ZloTvd.mjs";const w="/_lunora/admin/shard-registry/prune",f=["prune"],d=(e,r,a)=>(e.error(r),{code:a,error:r}),g=(e,r,a)=>{for(const{shardKey:t,table:n}of r.released)e.info(`${a?"would release":"released"} ${t} (${n})`);for(const{message:t,shardKey:n,tables:l}of r.failed)e.error(`could not check ${n} (${l.join(", ")}) — kept: ${t}`);const s=`${String(r.released.length)} ${a?"would be released":"released"}, ${String(r.kept.length)} kept (still hold rows), ${String(r.failed.length)} unreachable`;r.failed.length>0?e.warn(`${s} — re-run to retry the unreachable shards`):e.success(s)},A=async e=>{const{logger:r}=e;if(!f.includes(e.subcommand))return d(r,`shards: unknown subcommand "${e.subcommand??""}" — expected ${f.join(" | ")}`,u.USAGE);if(e.prod&&e.url===void 0)return d(r,"--prod requires an explicit --url (refusing to prune the implicit localhost worker)",u.USAGE);const a=S(e.url,r,e.cwd);if(a===void 0)return{code:u.USAGE,error:"could not resolve a usable worker URL"};const{token:s}=$({cwd:e.cwd??process.cwd(),token:e.token,url:a});if(!s)return d(r,"admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)",u.AUTH);const t=`${a}${w}`,n=e.fetchImpl??p,l=e.tables?.split(",").map(h=>h.trim()).filter(h=>h!==""),i=e.dryRun===!0;r.info(`POST ${t} -> shards prune${i?" (dry run)":""}`);const c=await n(t,{body:JSON.stringify({dryRun:i,...l===void 0?{}:{tables:l}}),headers:{authorization:`Bearer ${s}`,"content-type":"application/json"},method:"POST"}),m=await c.text();if(!c.ok)return d(r,`shards prune failed: HTTP ${String(c.status)}: ${m}`,b(c.status));let o;try{o=JSON.parse(m)}catch{return d(r,`shards prune failed: worker returned non-JSON: ${m}`,1)}return e.format!=="json"&&g(r,o,i),o.failed.length>0?{code:1,error:`shards prune: ${String(o.failed.length)} shard(s) could not be checked`,result:o}:{code:0,result:o}},E=k(async({argument:e,cwd:r,format:a,logger:s,options:t})=>{const n=await A({cwd:r,dryRun:t.dryRun===!0,format:a,logger:s,prod:t.prod,subcommand:e[0],tables:t.tables,token:t.token,url:y({cwd:r,prod:t.prod===!0,url:t.url})});return{code:n.code,data:n.result,error:n.error}});export{E as execute,A as runShardsCommand};
@@ -1 +1 @@
1
- import{readLiveDevServerState as c}from"@lunora/config";import{d as i}from"../packem_shared/command-B6vu47iR.mjs";import{o as a}from"../packem_shared/open-url-EnKy--w-.mjs";const n="http://127.0.0.1:6173",d="/__lunora",u=/\/$/u,l=r=>{const e=c(r);return e===void 0?n:e.studioUrl!==void 0?e.studioUrl:e.mode==="vite"?`${e.url.replace(u,"")}${d}`:n},m=async r=>{const e=l(r.cwd??process.cwd()),{logger:t}=r;t.info(`opening ${e}`);try{await a(e,{opener:r.opener})}catch(o){const s=o instanceof Error?o.message:String(o);return t.error(`view: failed to open URL: ${s}`),{code:1,url:e}}return{code:0,url:e}},v=i(({cwd:r,logger:e})=>m({cwd:r,logger:e}));export{v as execute,m as runViewCommand};
1
+ import{existsSync as h}from"node:fs";import{join as p}from"node:path";import{runCodegen as g}from"@lunora/codegen";import{resolveLazyFunctions as u}from"@lunora/config";import{validateWranglerProject as v,wranglerCodegenInputs as y}from"@lunora/config/cloudflare";import{a as w,e as S,r as k}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as j}from"../packem_shared/api-spec-lYyq4vL6.mjs";import{r as E}from"../packem_shared/codegen-error-AmH54ofi.mjs";import{d as A}from"../packem_shared/command-B6vu47iR.mjs";import{r as D}from"../packem_shared/deploy-target-resolve-BTCW1Iv4.mjs";import{EXIT_CODE as R}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";import{r as $,p as b}from"../packem_shared/health-probe-Bw9JFfIy.mjs";import{defaultSpawner as F}from"../packem_shared/createRecordingSpawner-01ZngIwK.mjs";import{execArgsFor as U,detectPackageManager as x}from"@lunora/config/cli";const P=async(r,a,t)=>{if(!h(p(r,"tsconfig.json")))return{warning:"no tsconfig.json found — skipping TypeScript type-check"};const o=U(x(r),"tsc",["--noEmit","-p","tsconfig.json"]),e=await a({args:o.args,command:o.command,cwd:r,stdoutToStderr:t==="json"});return e.code===0?{}:{error:`type errors: tsc --noEmit exited ${String(e.code)}`}},T=async(r,a)=>{if(r.healthUrl===void 0||r.healthUrl==="")return;const t=await b({baseUrl:r.healthUrl,fetchImpl:r.healthFetch});if(t.error===void 0){a.success(`verify: health probe ok (${t.url})`);return}return t.error},z=(r,a)=>{const{errorAdvisories:t,names:o,shouldBlock:e}=S(r,k(a));if(e)return`${t.length.toString()} ERROR-level ${t.length===1?"advisory":"advisories"} (${o.join(", ")}). Pass --no-strict-advisories to downgrade this to a warning and continue.`},C=(r,a,t,o)=>{if(a.length===0&&t.length===0)return r.success("verify: project is valid"),{code:0,errors:[],warnings:[],wranglerPath:o};if(t.length>0){r.warn("verify: warnings:");for(const e of t)r.warn(` - ${e}`)}if(a.length>0){r.error("verify: errors:");for(const e of a){r.error(` - ${e}`);const s=E(e);s!==void 0&&r.error(s)}return{code:1,error:a[0],errors:a,warnings:t,wranglerPath:o}}return r.success("verify: project is valid (with warnings)"),{code:0,errors:[],warnings:t,wranglerPath:o}},H=async r=>{const a=r.cwd??process.cwd(),{logger:t}=r,o=v({environment:r.env,projectRoot:a}),e=[...o.report.errors],s=[...o.report.warnings];try{const n=D(a,r.target);if(n.target===void 0){const c=n.error??"unknown deploy target";return t.error(c),{code:R.USAGE,error:c,errors:[c],warnings:[],wranglerPath:void 0}}const i=g({apiSpec:r.apiSpec,lazyFunctions:u(r.lazyFunctions),dryRun:!0,projectRoot:a,target:n.target,...y(a)}),l=w(i.platformDiagnostics,t);e.push(...l.errors),s.push(...l.warnings);const f=z(i.advisories,r);f!==void 0&&e.push(f);const m=$({allowDrift:r.allowSchemaDrift===!0,codegen:i,command:"verify",logger:t,readOnly:!0});m.blocked&&e.push(m.reason)}catch(n){const i=n instanceof Error?n.message:String(n);e.push(`codegen failed: ${i}`)}if(r.typecheck!==!1){const n=await P(a,r.spawner??F,r.format??"pretty");n.error!==void 0&&e.push(n.error),n.warning!==void 0&&s.push(n.warning)}const d=await T(r,t);return d!==void 0&&e.push(d),C(t,e,s,o.wranglerPath)},Q=A(async({cwd:r,format:a,logger:t,options:o})=>{const e=await H({allowSchemaDrift:o.allowSchemaDrift===!0,apiSpec:j(o.apiSpec),lazyFunctions:u(o.lazyFunctions),cwd:r,env:o.env,format:a,healthUrl:o.healthUrl,logger:t,strictAdvisories:o.strictAdvisories,target:o.target,typecheck:o.typecheck===!1?!1:void 0});return{code:e.code,data:{errors:e.errors,warnings:e.warnings,wranglerPath:e.wranglerPath},error:e.error}});export{Q as execute,H as runVerifyCommand};
@@ -1 +1 @@
1
- import{d as f}from"../packem_shared/command-B6vu47iR.mjs";import{EXIT_CODE as y}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";import{runRpcCommand as l}from"./runRpcCommand.mjs";const i="__lunora_admin__:createWorkflowInstance",N="__lunora_admin__:sendWorkflowEvent",u="Usage: lunora workflow create <exportName> [--id <id>] [--params <json>] | lunora workflow send-event <exportName> <instanceId> <eventType> [--payload <json>]",m=r=>{if(r===void 0)return{value:void 0};try{return{value:JSON.parse(r)}}catch{return}},n=(r,e)=>(r.error(e),{body:void 0,code:y.USAGE,error:e,requestUrl:""}),s=r=>{const{body:e}=r;return typeof e=="object"&&e!==null&&"result"in e?{...r,body:e.result}:r},p=async r=>{const{logger:e}=r,d={cwd:r.cwd,fetchImpl:r.fetchImpl,format:r.format,logger:e,token:r.token,url:r.url};if(r.subcommand==="create"){const a=m(r.params);return r.exportName?a===void 0?n(e,"could not parse --params as JSON"):s(await l({...d,args:JSON.stringify({exportName:r.exportName,...r.id===void 0?{}:{id:r.id},params:a.value}),functionPath:i})):n(e,u)}if(r.subcommand==="send-event"){const a=m(r.payload);return!r.exportName||!r.id||!r.type?n(e,u):a===void 0?n(e,"could not parse --payload as JSON"):s(await l({...d,args:JSON.stringify({exportName:r.exportName,id:r.id,payload:a.value,type:r.type}),functionPath:N}))}return n(e,`workflow: unknown subcommand "${r.subcommand??""}". ${u}`)},k=f(async({argument:r,cwd:e,format:d,logger:a,options:t})=>{const c=r[0],o=await p({cwd:e,exportName:r[1],format:d,id:c==="send-event"?r[2]:t.id,logger:a,params:t.params,payload:t.payload,subcommand:c,token:t.token,type:r[3],url:t.url});return{code:o.code,data:o.body,error:o.error}});export{k as execute,p as runWorkflowCommand};
1
+ import{readLiveDevServerState as c}from"@lunora/config";import{d as i}from"../packem_shared/command-B6vu47iR.mjs";import{o as a}from"../packem_shared/open-url-EnKy--w-.mjs";const n="http://127.0.0.1:6173",d="/__lunora",u=/\/$/u,l=r=>{const e=c(r);return e===void 0?n:e.studioUrl!==void 0?e.studioUrl:e.mode==="vite"?`${e.url.replace(u,"")}${d}`:n},m=async r=>{const e=l(r.cwd??process.cwd()),{logger:t}=r;t.info(`opening ${e}`);try{await a(e,{opener:r.opener})}catch(o){const s=o instanceof Error?o.message:String(o);return t.error(`view: failed to open URL: ${s}`),{code:1,url:e}}return{code:0,url:e}},v=i(({cwd:r,logger:e})=>m({cwd:r,logger:e}));export{v as execute,m as runViewCommand};