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

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.
Files changed (30) hide show
  1. package/dist/index.d.mts +76 -55
  2. package/dist/index.d.ts +76 -55
  3. package/dist/index.mjs +1 -1
  4. package/dist/packem_chunks/cli.mjs +2 -2
  5. package/dist/packem_chunks/dispatch.mjs +1 -1
  6. package/dist/packem_chunks/handler.mjs +10 -10
  7. package/dist/packem_chunks/handler12.mjs +1 -1
  8. package/dist/packem_chunks/handler15.mjs +2 -2
  9. package/dist/packem_chunks/handler17.mjs +1 -1
  10. package/dist/packem_chunks/handler24.mjs +3 -3
  11. package/dist/packem_chunks/handler6.mjs +1 -1
  12. package/dist/packem_chunks/handler7.mjs +1 -1
  13. package/dist/packem_chunks/runInitCommand.mjs +87 -63
  14. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-CyOfZWMk.mjs +1 -0
  15. package/dist/packem_shared/export-rows-EzdNDYpa.mjs +3 -0
  16. package/dist/packem_shared/health-probe-BLnoq_oC.mjs +13 -0
  17. package/dist/packem_shared/import-C-XRRHrZ.mjs +13 -0
  18. package/dist/packem_shared/runDeployCommand-2tEbutD6.mjs +1 -0
  19. package/dist/packem_shared/runExportCommand-Dy6pSX68.mjs +5 -0
  20. package/dist/packem_shared/{runMigrateGenerateCommand-Bd2W9t1k.mjs → runMigrateGenerateCommand-CFy3hXXu.mjs} +3 -3
  21. package/dist/packem_shared/shared-CV7ESvuj.mjs +2 -0
  22. package/package.json +11 -10
  23. package/skills/lunora-deploy/SKILL.md +18 -17
  24. package/skills/lunora-migration-helper/SKILL.md +25 -11
  25. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-5xxKz-zB.mjs +0 -1
  26. package/dist/packem_shared/health-probe-Bw9JFfIy.mjs +0 -1
  27. package/dist/packem_shared/import-DoAUdyfU.mjs +0 -13
  28. package/dist/packem_shared/runDeployCommand-Tgy9tGRV.mjs +0 -1
  29. package/dist/packem_shared/runExportCommand-DiMCQ-Il.mjs +0 -5
  30. package/dist/packem_shared/shared-D-zCOmgY.mjs +0 -1
@@ -1,12 +1,12 @@
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:
1
+ import{mkdirSync as Qe,writeFileSync as V,existsSync as b,readFileSync as E,rmSync as Q,readdirSync as ve,mkdtempSync as Wr,realpathSync as Gr,statSync as Ze}from"node:fs";import{dirname as U,join as y,resolve as j,relative as F,sep as B,extname as Vr}from"node:path";import{PROJECT_CONFIG_FILENAMES as qr,isTestPath as ge,discoverMigrations as Kr,readServiceBindings as pe,runCodegen as zr}from"@lunora/codegen";import{readLinkedProject as ye,resolveSchemaDirectory as I,startDevProcess as Jr,acceptsConnection as Yr,resolveTargetOrThrow as fe,detectFramework as Xr,DEFAULT_BUNDLE_META_PATH as Qr,STRICT_ADVISORIES_ENV as Zr,LAZY_FUNCTIONS_ENV as et,BUNDLE_META_PATH_ENV as rt,BUILD_TARGET_ENV as tt,BUILD_ROOT_ENV as nt,canonicalPath as ot,COMPOSED_WORKER_ENTRY as Ce,discoverContainerInfo as er,D1_PLACEHOLDER_ID as Ie,discoverSchemaInfo as we,writeLinkedProject as st,DEV_VARS_FILE as C,parseDevVariableEntries as rr,secretSourcesFromBindings as at,inferLunoraBindings as tr,requiredSecrets as it,mintableSecretKeysFor as ct,generateSecretValue as dt,upsertDevVariableLine as lt,writeDevVariablesFileAtomically as ut,isPlaceholderValue as gt,ensureGitignoreEntries as ft,resolveLazyFunctions as te,resolveDeployDriver as ne,MissingBuildOutputError as ht,clearApiSpecMarker as mt,createDiscoveryCache as vt,planToolchainInvocation as nr,probeCelldToolchain as pt,runPostCodegenHook as yt,readApiSpecMarker as wt}from"@lunora/config";import{bindingsNeedingDatabase as kt,findWranglerFile as O,readWranglerJsonc as R,mergeWranglerEnvironment as oe,HYPERDRIVE_PLACEHOLDER_ID as or,applyModify as sr,warnCloudflareCliConfigOnce as bt,validateWranglerProject as $t,wranglerCodegenInputs as St,reconcileWranglerBindings as Et,reconcileWranglerCompatibilityDate as At,reconcileWranglerCrons as Rt,describePreservedCrons as Tt}from"@lunora/config/cloudflare";import{Spinner as Pt}from"@visulima/spinner";import{r as _t}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{n as Dt,r as Ct,a as It}from"../packem_shared/admin-url-DJB8P6Jh.mjs";import{r as ke,a as Ot,e as jt}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as Nt}from"../packem_shared/api-spec-lYyq4vL6.mjs";import{e as Lt,m as Mt,g as xt,i as ar,d as Ft,b as Ut}from"../packem_shared/vectorize-metadata-BVSF8z2h.mjs";import{w as Bt}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{d as Ht}from"../packem_shared/command-B6vu47iR.mjs";import{r as be}from"../packem_shared/wrangler-name-Dsk5K1f-.mjs";import{a as Wt}from"../packem_shared/deploy-target-resolve-BTCW1Iv4.mjs";import{EXIT_CODE as w}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";import{spawn as Gt}from"node:child_process";import{randomUUID as ir,createHash as Vt}from"node:crypto";import{setTimeout as qt}from"node:timers/promises";import{toolchainExecArgs as H,detectPackageManager as N,execArgsFor as $e}from"@lunora/config/cli";import{f as Kt}from"../packem_shared/free-port-DjbFhaaT.mjs";import{containerBuildTag as zt}from"@lunora/container";import{a as Jt,i as Yt}from"../packem_shared/docker-DpVxvYpL.mjs";import{defaultSpawner as x}from"../packem_shared/createRecordingSpawner-01ZngIwK.mjs";import{r as Se}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{p as Xt,H as Qt,a as Zt,r as en,c as rn,b as tn}from"../packem_shared/health-probe-BLnoq_oC.mjs";import{runAdvisor as nn,openShardAccess as Oe}from"@lunora/advisor";import{join as $,relative as W,dirname as cr}from"@visulima/path";import{Project as dr,SyntaxKind as p,Node as k}from"ts-morph";import{r as lr,c as ur}from"../packem_shared/cloudflare-credentials-BVmZnDZk.mjs";import{runMigrateDataCommand as on}from"../packem_shared/runMigrateGenerateCommand-CFy3hXXu.mjs";import{c as sn}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{l as an}from"../packem_shared/wrangler-secrets-DlSlWvRH.mjs";const cn=Object.freeze({edges:[],nodes:[],modules:[],unresolved:[],version:1}),dn=20,je=e=>`${e.from} -${e.kind}-> ${e.to}`,z=(e,r)=>{const t=new Set(e);return r.filter(n=>!t.has(n)).toSorted((n,o)=>n.localeCompare(o))},ln=(e,r)=>{const t=e.modules.map(a=>a.name),n=r.modules.map(a=>a.name),o=e.edges.map(a=>je(a)),s=r.edges.map(a=>je(a));return{addedEdges:z(o,s),addedModules:z(t,n),removedEdges:z(s,o),removedModules:z(n,t)}},J=(e,r,t)=>{if(t.length===0)return[];const n=t.slice(0,dn).map(s=>` ${e} ${s}`),o=t.length-n.length;return[`${r}:`,...n,...o>0?[` … and ${o.toString()} more`]:[]]},un=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
- `)}`},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(`
3
+ `)}`},gn=(e,r)=>y(e,".lunora",r===void 0?"architecture.json":`architecture.${r}.json`),fn=e=>{if(b(e))try{const r=JSON.parse(E(e,"utf8"));return r.version===1&&Array.isArray(r.modules)&&Array.isArray(r.edges)?r:void 0}catch{return}},hn=e=>{const{cwd:r,environment:t,logger:n}=e,o=gn(r,t),s=fn(o),a=e.current??(s===void 0?void 0:cn);if(a===void 0)return;const i=s===void 0?void 0:un(ln(s,a));return i!==void 0&&n.info(i),()=>{try{Qe(U(o),{recursive:!0}),V(o,`${JSON.stringify(a,void 0,2)}
4
+ `,"utf8")}catch(c){n.warn(`could not record the deployed architecture at ${o}: ${c instanceof Error?c.message:String(c)}`)}}},mn=e=>{const{cwd:r,env:t,logger:n,mintedSecretsFile:o}=e;try{const s=ye(r),a=s?.workerName??be(r),i=e.url??s?.workerUrl;n.success("deploy complete"),n.info(` worker: ${a??"(see wrangler output above)"}`),t!==void 0&&n.info(` env: ${t}`),i===void 0?n.info(" url: run `lunora link --url <https://your-worker>` to record it"):n.info(` url: ${i}`),o!==void 0&&n.info(` secrets: generated value(s) recorded in ${o}`),e.logsAvailable&&n.info(" logs: lunora logs")}catch{}},vn=/\/index$/u,pn=/[^\dA-Za-z]/gu,yn=e=>e.replace(vn,"").split("/").map(r=>r.replaceAll(pn,"_")),wn=e=>yn(e).join("_"),kn=18787,Ne=3,gr=12e4,bn=5e3,ce=10,fr=new Set([".js",".mjs",".mts",".ts",".tsx"]),$n=/\(void 0\)|is not a function|before initialization|of undefined/u,Sn=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",En=e=>{const r=I(e),t=new Map;let n;try{n=ve(y(e,r),{recursive:!0,encoding:"utf8"})}catch{return t}for(const o of n){const s=Vr(o);fr.has(s)&&!o.split(B).some(a=>a==="_generated"||a==="node_modules")&&t.set(wn(o.slice(0,-s.length).split(B).join("/")),y(r,o))}return t},Le=e=>$n.test(e)?`
5
+ hint: if this module is part of a circular import, an import it reads is still undefined while it evaluates`:"",An=(e,r)=>{const t=En(e),n=new Map,o=[];for(const{deferred:s,functionPath:a,message:i}of r){if(s!==void 0){o.push(` ${a.slice(s.length+1)} (${s}): ${i}${Le(i)}`);continue}const c=a.lastIndexOf(":"),l=a.slice(0,c),d=`${l}\0${i}`,g=n.get(d)??{exports:[],message:i,namespace:l};g.exports.push(a.slice(c+1)),n.set(d,g)}return[...[...n.values()].map(({exports:s,message:a,namespace:i})=>` ${t.get(i)??i} (${s.join(", ")}): ${a}${Le(a)}`),...o]},Y=e=>{for(const r of fr)for(const t of[`${e}${r}`,y(e,`index${r}`)])if(b(t))return t},Rn=(e,r)=>{const t=y(e,r,"_generated"),n=i=>{try{return E(y(t,i),"utf8")}catch{return""}},o=n("app.ts"),s=[],a=(i,c)=>{c!==void 0&&s.push({file:c,kind:i,label:F(e,c).split(B).join("/")})};return o.includes('import("./queues.js")')&&a("queue",Y(y(t,"queues"))),n("workflows.mjs").includes('import("../workflows.js")')&&a("workflow",Y(y(e,r,"workflows"))),(n("agents.mjs").includes('import("../agents.js")')||o.includes('import("../agents.js")'))&&a("agent",Y(y(e,r,"agents"))),s},Tn=/\.[cm]?js$/u,Pn=/(?:await|=>|return|[=[,])\s*import\(\s*"([^"]+)"\s*\)(?!\s*\.(?!(?:then|catch|finally)\b))/gu,_n=(e,r,t)=>{const n=y(e,r,"_generated"),o=new Set(t.map(i=>i.file)),s=[];let a;try{a=ve(n).filter(i=>i.endsWith(".mjs")&&i!=="functions.ts")}catch{return s}for(const i of a.toSorted((c,l)=>c.localeCompare(l)))for(const c of E(y(n,i),"utf8").matchAll(Pn)){const l=c[1]??"",d=l.startsWith("."),g=d?Y(j(n,l.replace(Tn,""))):l;g!==void 0&&!o.has(g)&&(o.add(g),s.push({file:g,kind:"module",label:d?F(e,g).split(B).join("/"):l}))}return s};class _ extends Error{skipped;constructor(r,t=!1){super(r),this.skipped=t}}const Dn=(e,r)=>{const t=O(e),n=t===void 0?void 0:R(t).parsed;if(n===void 0)return{hasContainers:!1,main:void 0};const{merged:o}=oe(n,r);return{hasContainers:(o.containers??[]).length>0,main:o.main}},Cn=({composedEntry:e,configPath:r,cwd:t,environment:n,toolchain:o})=>{if(o.devServer!=="workerd")return{skip:"this deploy target does not run on workerd"};const{hasContainers:s,main:a}=Dn(t,n),i=e??a;if(typeof i!="string"||i.startsWith("virtual:")||!b(j(t,i)))return{skip:"the Worker entry is not a file on disk"};if(s)return{skip:"the project declares containers, which `wrangler dev` would build locally before the real container build"};const c=kt(t,process.env,n,r);return c.length===0?{main:i}:{skip:`the Hyperdrive binding ${c.join(", ")} has no local database for wrangler dev`}},In=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(gr/1e3)}s — a module may be awaiting something that never settles. Pass --no-smoke-load to ship anyway.`):u});if(n.status>=500)throw new _(`the smoke Worker booted but failed while evaluating the lazy modules (HTTP ${String(n.status)}). Pass --no-smoke-load to ship anyway.`);const o=await n.text().catch(()=>"");let s;try{s=JSON.parse(o)}catch{s=void 0}const{checked:a,deferredChecked:i=0,failures:c,run:l}=s??{};if(typeof a=="number"&&Array.isArray(c)&&c.every(u=>Sn(u)))return l===r?{checked:a,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.`)},he=(e,r)=>{try{process.kill(-e,r)}catch{}},Me=e=>{try{return process.kill(-e,0),!0}catch{return!1}},On=e=>{const r=()=>{he(e,"SIGKILL")},t=o=>{r(),process.kill(process.pid,o)},n=()=>{process.removeListener("exit",r),process.removeListener("SIGINT",t),process.removeListener("SIGTERM",t)};return process.once("exit",r),process.once("SIGINT",t),process.once("SIGTERM",t),n},de=async e=>{if(e===void 0)return;e.dispose();const{pid:r}=e;he(r,"SIGTERM");const t=Date.now()+bn;for(;Me(r)&&Date.now()<t;)await qt(50);Me(r)&&he(r,"SIGKILL")},jn=e=>Jr(e).catch(async r=>{if(!await Yr(e.port))throw r}),Nn=(e,{checked:r,deferredChecked:t,failures:n},o)=>{const s=t===0?`${String(r)} lazy function(s)`:`${String(r)} lazy function(s) and ${String(t)} deferred module(s)`;if(n.length===0){o.success(`${s} evaluate cleanly`);return}const a=An(e,n),i=a.length>ce?[` …and ${String(a.length-ce)} more module(s)`]:[];throw new _([`${String(n.length)} of ${t===0?`${String(r)} lazy function(s)`:`${String(r+t)} lazy module(s)`} fail to load:`,...a.slice(0,ce),...i,"Fix the module, or pass --no-smoke-load to ship anyway."].join(`
6
+ `))},Ln=(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},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)};
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},Mn=e=>{try{return Qe(y(e,".lunora"),{recursive:!0}),Wr(y(e,".lunora","smoke-"))}catch(r){throw new _(`could not create a directory for the check (${r instanceof Error?r.message:String(r)})`,!0)}},xn=async e=>{const{configPath:r,cwd:t,deferred:n,directory:o,environment:s,functionsFile:a,main:i,preferred:c,toolchain:l}=e;try{const d=y(o,"entry.ts"),g=ir();V(d,`export * from ${JSON.stringify(j(t,i))};
9
+ ${a===void 0?"":`import { loadAllFunctions } from ${JSON.stringify(a)};
10
10
  `}
11
11
  const runId = ${JSON.stringify(g)};
12
12
 
@@ -18,7 +18,7 @@ ${n.map(v=>` { kind: ${JSON.stringify(v.kind)}, label: ${JSON.stringify(v.lab
18
18
 
19
19
  export default {
20
20
  async fetch() {
21
- const functions = ${s===void 0?"{ checked: 0, failures: [] }":"await loadAllFunctions()"};
21
+ const functions = ${a===void 0?"{ checked: 0, failures: [] }":"await loadAllFunctions()"};
22
22
  const loaded = await Promise.all(
23
23
  deferred.map(async ({ kind, label, load }) => {
24
24
  try {
@@ -39,5 +39,5 @@ export default {
39
39
  });
40
40
  },
41
41
  };
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};
42
+ `);const u=await Kt(c),{args:h,command:f}=H(N(t),l.dev({configPath:r===void 0?void 0:F(t,r),environment:s,extraArgs:[F(t,d),"--local","--local-protocol","http","--ip","127.0.0.1","--port",String(u),"--persist-to",F(t,y(o,"state"))]}));return{args:h,command:f,port:u,runId:g}}catch(d){throw new _(`could not prepare the check (${d instanceof Error?d.message:String(d)})`,!0)}},Fn=async e=>{const{configPath:r,cwd:t,environment:n,launcher:o,logger:s,toolchain:a}=e,i=y(t,I(t),"_generated","functions.ts"),c=b(i)&&E(i,"utf8").includes("export const loadAllFunctions"),l=I(t),d=Rn(t,l);if(!c&&d.length===0)return;const g=[...d,..._n(t,l,d)],u=Cn(e);if("skip"in u){s.warn(`smoke-load skipped: ${u.skip}, so lazy modules are not evaluated before deploy`);return}const{main:h}=u,f=[];let v,m;const T=Date.now()+gr,L=process.platform!=="win32",D=(P,S,q)=>{const M=Gt(P,[...S],{cwd:q.cwd,detached:L,shell:q.shell,stdio:["ignore","pipe","pipe"]});return L&&M.pid!==void 0&&(m={dispose:On(M.pid),pid:M.pid}),M};try{v=Mn(t),s.info("smoke-loading lazy function modules in workerd");let P=kn;for(let S=0;S<Ne;S+=1){const{args:q,command:M,port:ie,runId:Hr}=await xn({configPath:r,cwd:t,deferred:g,directory:v,environment:n,functionsFile:c?i:void 0,main:h,preferred:P,toolchain:a});P=ie+1;const De=await jn({args:q,command:M,cwd:t,spawn:o??D,label:"wrangler dev (smoke-load)",notFound:"`wrangler` was not found",onLine:K=>{f.push(K)},port:ie,readyTimeoutMs:Math.max(0,T-Date.now()),shell:process.platform==="win32"});if(De===void 0){await de(m),m=void 0;continue}try{const K=await In(ie,Hr,T);if(K!==void 0){Nn(t,K,s);return}}finally{await De.stop(),await de(m),m=void 0}}throw new _(`the smoke port was answered by other runs on all ${String(Ne)} attempts`,!0)}catch(P){return Ln(P,f,s)}finally{if(await de(m),v!==void 0)try{Q(v,{force:!0,recursive:!0})}catch{}}},Un=(e,r)=>r===void 0?e:j(e,r),Bn=async e=>{if(e.targets.length===0)return{builtTags:[],code:0};if(!(e.railpackAvailable??Jt)()){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=zt(n.exportName),s={args:["build",n.buildDir,"--name",o],command:"railpack",cwd:e.cwd},a=$e(N(e.cwd),"wrangler",["containers","push",o]),i={args:a.args,command:a.command,cwd:e.cwd};e.logger.info(`railpack: building "${n.exportName}" → ${o} from ${n.buildDir}`);const c=await r(s);if(c.code!==0){const d=`railpack build failed for container "${n.exportName}" (${n.buildDir})`;return e.logger.error(d),{builtTags:t,code:c.code,error:d}}e.logger.info(`railpack: pushing ${o} to the Cloudflare Registry`);const l=await r(i);if(l.code!==0){const d=`wrangler containers push failed for "${n.exportName}" (${o})`;return e.logger.error(d),{builtTags:t,code:l.code,error:d}}t.push(o)}return{builtTags:t,code:0}},Hn=new Set(["0.0.0.0","[::1]","[::]","localhost"]),Wn=[".local",".localhost"],Gn=["[fc","[fd"],Vn=/^\[fe[89ab][0-9a-f]:/u,qn=/^[a-z]+:\/\//u,xe=e=>{const r=e.split(".").map(Number);if(r.length!==4||r.some(o=>!Number.isInteger(o)))return!1;const[t=-1,n=-1]=r;return t===0||t===127||t===100&&n>=64&&n<=127||t===198&&(n===18||n===19)||t===10||t===192&&n===168||t===172&&n>=16&&n<=31||t===169&&n===254},Fe="[::ffff:",Kn=e=>{if(!e.startsWith(Fe)||!e.endsWith("]"))return;const r=e.slice(Fe.length,-1);if(r.includes("."))return r;const[t=0,n=0]=r.split(":").map(o=>Number.parseInt(o,16));return[Math.floor(t/256),t%256,Math.floor(n/256),n%256].join(".")},hr=e=>{let r=e.length;for(;r>0&&e[r-1]===".";)r-=1;return e.slice(0,r).toLowerCase()},zn=e=>{const r=e.toLowerCase(),t=Kn(r);return t!==void 0?xe(t):Hn.has(r)||Wn.some(n=>r.endsWith(n))||Gn.some(n=>r.startsWith(n))||Vn.test(r)||xe(r)},mr=e=>{const r=O(e);return r===void 0?void 0:R(r).parsed},vr=(e,r)=>{const t=typeof e?.name=="string"&&e.name!==""?e.name:void 0;if(r===void 0)return t;const n=e?.env?.[r]?.name;return typeof n=="string"&&n!==""?n:t===void 0?void 0:`${t}-${r}`},Z=(e,r)=>{let t=e.length;for(;t>0&&e[t-1]===r;)t-=1;return e.slice(0,t)},Jn=e=>{const r=e.replace(qn,""),t=r.indexOf("/"),n=(t===-1?r:r.slice(0,t)).toLowerCase(),o=t===-1?"":Z(r.slice(t),"*");return o==="/"?n:`${n}${o}`},Ue=e=>[e?.route,...Array.isArray(e?.routes)?e.routes:[]].flatMap(t=>{const n=typeof t=="string"?t:t?.pattern;return typeof n=="string"&&n!==""?[Jn(n)]:[]}),Yn=(e,r,t)=>{const n=t.indexOf("/"),o=n===-1?t:t.slice(0,n),s=n===-1?"":t.slice(n),a=o.startsWith("*");if(!(!(a?e.endsWith(o.slice(1)):e===o)||s!==""&&!`${Z(r,"/")}/`.startsWith(s)))return s.length*1e6+(a?0:5e5)+o.length},Xn=e=>e!==void 0&&(Object.hasOwn(e,"route")||Object.hasOwn(e,"routes")),pr=(e,r)=>{const t=Ue(e),o=[...new Set([...Object.keys(e?.env??{}),...r===void 0?[]:[r]])].map(s=>{const a=e?.env?.[s];return{id:`env:${s}`,label:`--env ${s}`,routes:Xn(a)?Ue(a):t}});return[{id:"top",label:"production",routes:t},...o]},Qn=(e,r,t,n)=>{const o=r===void 0?"top":`env:${r}`,s=pr(e,r).flatMap(c=>c.routes.flatMap(l=>{const d=Yn(t,n,l);return d===void 0?[]:[{block:c,score:d}]}));if(s.length===0)return{kind:"none"};const a=Math.max(...s.map(c=>c.score)),i=s.filter(c=>c.score===a);return i.some(c=>c.block.id===o)?{kind:"own"}:{kind:"other",label:i[0]?.block.label??"production"}},X=e=>Dt(`${e.origin}${e.pathname}`),Zn=(e,r,t,n,o)=>{const s=ye(e),a=s?.workerUrl!==void 0&&URL.canParse(s.workerUrl)?new URL(s.workerUrl):void 0;if(a===void 0)return;if(s?.env===r)return X(a)===X(t)?null:`${n}: this checkout is linked to ${X(a)}${o}`;const i=`${Z(a.pathname,"/")}/`;if(a.origin!==t.origin||!`${Z(t.pathname,"/")}/`.startsWith(i))return;const c=s?.env===void 0?"production":`--env ${s.env}`;return`${n}: this checkout links it to ${c}, not this deploy${o}`},yr=(e,r,t,n,o,s)=>{const a=Qn(e,r,t,n);if(a.kind==="other")return`${o}: wrangler routes it to ${a.label}, not this deploy${s}`;if(a.kind==="own")return;const i=pr(e,r);if(i.every(l=>l.routes.length===0))return;const c=i.find(l=>l.id===(r===void 0?"top":`env:${r}`))?.routes??[];return`${o}: this deploy${s} routes to ${c.length===0?"no declared route":c.join(", ")}, not ${t}`},eo=(e,r,t,n,o,s)=>{const a=mr(e);if(t.endsWith(".workers.dev")){const i=vr(a,r);return i!==void 0&&t.split(".")[0]!==i?`${o}: this deploy ships the Worker "${i}"${s}`:`${o}: no link ties this *.workers.dev host to your account${s}; run \`lunora link --url https://${t}${r===void 0?"":` --env ${r}`}\` once the Worker is deployed, then deploy again (or confirm the drift yourself with --allow-schema-drift)`}return yr(a,r,t,n,o,s)},ro=(e,r,t,n,o)=>{const s=mr(e),a=hr(t.hostname);if(a.endsWith(".workers.dev")){const i=vr(s,r);return i===void 0||a.split(".")[0]===i?void 0:`${n}: this deploy ships the Worker "${i}", not the one the link names${o}`}return yr(s,r,a,t.pathname,n,o)},to=(e,r,t)=>{let n;try{n=new URL(t)}catch{return`refused ${t} as the deployment to read rows from: it is not a URL`}const o=`refused ${X(n)} as the deployment to read rows from`,s=r===void 0?"":` (--env ${r})`,a=hr(n.hostname);if(zn(a))return`${o}: it is a local or private address, not the worker this deploy ships to`;const i=Zn(e,r,n,o,s);return i===void 0?eo(e,r,a,n.pathname,o,s):i??ro(e,r,n,o,s)},wr=e=>{const t=[O(e),y(e,"package.json"),y(e,"wrangler.dev.jsonc")].filter(n=>n!==void 0&&b(n)).map(n=>[n,E(n,"utf8")]);return()=>{for(const[n,o]of t)E(n,"utf8")!==o&&V(n,o,"utf8")}},no=(e,r=ir())=>j(e,".lunora",`vite-bundle-meta-${r}.json`),kr="LUNORA_CLIENT_BUILD",oo="virtual:lunora/worker",me=(e,r)=>["ts","mts","cts","js","mjs","cjs"].some(t=>b(y(e,`${r}.config.${t}`))),br=e=>me(e,"rsbuild")?"rsbuild":me(e,"vite")?"vite":void 0,so=e=>me(e,"vite")?"vite":br(e),ao=e=>{try{const{scripts:r}=JSON.parse(E(y(e,"package.json"),"utf8"));return typeof r?.build=="string"&&r.build!==""}catch{return!1}},se=(e,r)=>{if(process.env[kr]==="1")return;const t=O(e),n=t===void 0?void 0:R(t).parsed,o=n?.main===oo,s=(o?so(e):br(e))??(ao(e)?"script":void 0);if(s===void 0)return;const a=r===void 0?void 0:n?.env?.[r]?.assets?.directory,i=n?.assets?.directory??a;return o||Xr(e).class!=="C"||i!==void 0?s:void 0},io=async(e,r,t)=>{const n=t.spawner??x,o=N(e),s=r==="script"?{args:["run","build"],command:o}:$e(o,r,["build"]);t.logger.info(`running ${r} build before bundling the Worker`);const a=wr(e),i=t.bundleMetaPath??no(e);Q(y(e,Qr),{force:!0});try{const c=await n({args:s.args,command:s.command,cwd:e,env:{[nt]:ot(e),[tt]:t.target,[rt]:i,...t.lazyFunctions?{[et]:"1"}:{},...t.environment===void 0?{}:{CLOUDFLARE_ENV:t.environment},...t.strictAdvisories===!1?{[Zr]:"0"}:{},[kr]:"1"},stdoutToStderr:t.outputJson});return c.code===0?void 0:`${r} build failed with exit code ${String(c.code)}`}finally{a(),t.bundleMetaPath===void 0&&Q(i,{force:!0})}},ae=(e,r,t)=>r!==!1&&se(e,t)!==void 0,co=(e,r,t)=>ae(e,r,t)&&se(e,t)!=="script",Ee=e=>{const r=e.frameworkBuild===!1?void 0:se(e.cwd,e.environment);if(r===void 0||r==="script")return;if(e.apiSpec!==void 0)return`--api-spec is read from the ${r} plugin config when the client build runs; set it there, or pass --no-framework-build`;if(e.target!==void 0)try{fe(e.cwd,e.target)}catch(n){return n instanceof Error?n.message:String(n)}let t;try{t=fe(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`},$r=async e=>{const r=e.frameworkBuild===!1?void 0:se(e.cwd,e.environment);if(r===void 0)return;let t;try{t=e.target??fe(e.cwd)}catch(n){return n instanceof Error?n.message:String(n)}return io(e.cwd,r,{bundleMetaPath:e.bundleMetaPath,environment:e.environment,strictAdvisories:e.strictAdvisories,lazyFunctions:e.lazyFunctions,logger:e.logger,outputJson:e.outputJson,spawner:e.spawner,target:t})},Be=e=>Array.isArray(e)?e.filter(r=>r!=null):void 0,Ae=(e,r)=>{const t=O(e);if(!t)return;const{parsed:n}=R(t);if(n===void 0)return;const{error:o,merged:s}=oe(n,r),a=o===void 0?s:n,{containers:i,d1_databases:c,vars:l}=a;return{containers:Be(i),d1_databases:Be(c),vars:typeof l=="object"&&l!==null&&!Array.isArray(l)?l:void 0}},lo=/^127(?:\.\d{1,3}){3}$/,uo=e=>{try{const{hostname:r}=new URL(e);return r==="localhost"||lo.test(r)||r==="::1"||r==="[::1]"}catch{return!1}},go=e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"),fo=(e,r,t,n="deploy",o)=>{const s=(Ae(e,o)?.containers??[]).filter(i=>typeof i?.image=="string"&&go(i.image));if(s.length===0||t())return;const a=`${n} blocked: wrangler.jsonc declares ${String(s.length)} container(s) built from a local Dockerfile, but no Docker-compatible engine is available. Start Docker (or Colima), or point the container's \`image\` at a pre-built registry reference. Note: container images must target linux/amd64.`;return r.error(a),a},Re=e=>b($(e,Ce))?Ce:void 0,ho=(e,r,t="deploy",n)=>{for(const o of er(e,"lunora",n).containers){const s=o.schedulingPolicy===void 0?o.image:void 0,i=[...s?.kind==="dockerfile"?[{field:"image",path:s.dockerfilePath}]:[],...Object.entries(o.schedulingPolicy==="durable_object"?o.images??{}:{}).flatMap(([c,l])=>l.kind==="dockerfile"?[{field:`images["${c}"]`,path:l.dockerfilePath}]:[])].find(c=>!b($(e,c.path)));if(i!==void 0){const c=`${t} blocked: container "${o.exportName}" references a Dockerfile at "${i.path}" that does not exist. Create it or fix the \`${i.field}\` path in lunora/containers.ts.`;return r.error(c),c}if(s?.kind==="build"&&!b($(e,s.buildDir))){const c=`${t} blocked: container "${o.exportName}" references a Railpack build directory "${s.buildDir}" that does not exist. Create it or fix the \`image.build\` path in lunora/containers.ts.`;return r.error(c),c}}},mo=(e,r)=>r==="celld"?typeof e=="string"&&e!==Ie&&Lt(e):r==="cloudflare"&&e===Ie,vo=(e,r,t)=>(Ae(e,t)?.d1_databases??[]).find(n=>mo(n.database_id,r)),po=e=>{if(!e.migrate||e.dryRun)return;if(e.migrateUrl===void 0){const t="--migrate requires --migrate-url <https://your-worker> — the deploy target URL is only known after wrangler runs, and this gate runs before it; refusing to default to localhost";return e.logger.error(t),t}if(e.migrateYes!==!0){const t="--migrate runs production data migrations after deploy. Re-run with --migrate-yes to confirm.";return e.logger.error(t),t}const r=e.migrateToken??process.env.LUNORA_ADMIN_TOKEN;if(r===void 0||r===""){const t="admin token required for --migrate — pass --migrate-token or set LUNORA_ADMIN_TOKEN";return e.logger.error(t),t}},yo=(e,r,t,n,o)=>{const s=vo(e,n,o);if(s===void 0)return;const a=`${t} blocked: the "${s.binding??"<unnamed>"}" D1 binding has a placeholder database_id ("${s.database_id??""}")`,i=n==="celld"?`${a}, which celld would use as the database's identity. Set database_id to the database celld should use, then ${t} again.`:`${a}. Run \`lunora doctor --fix\` to create the database and write its id into wrangler.jsonc, or run \`wrangler d1 create <name>\` and paste the id in yourself.`;return r.error(i),i},wo=(e,r,t="deploy",n)=>{const o=Ae(e,n)?.vars;if(!o)return;const s=Object.entries(o).filter(([,i])=>typeof i=="string"&&uo(i)).map(([i])=>i).toSorted((i,c)=>i.localeCompare(c));if(s.length===0)return;const a=`${t} blocked: ${s.join(", ")} in wrangler.jsonc point at localhost. A deployed Worker can't reach a loopback address, so this silently breaks scheduled-job dispatch, reverse cross-shard relations, and auth callbacks. Set each to the deployed worker's public URL (or move it to a secret with \`wrangler secret put\`) before deploying.`;return r.error(a),a},ko=["vite.config.ts","vite.config.mts","vite.config.cts","vite.config.js","vite.config.mjs","vite.config.cjs",...qr],Sr=/\.(?:[cm]?[jt]s|tsx|jsx)$/u,Er=/\.(?:test|spec)\.[cm]?[jt]sx?$/u,Ar="allowUnauthenticatedShardAccess",bo=/[\\/]/u,Rr=new Set(["_generated","build","dist","node_modules"]),Tr=(e,r)=>{const t=W(e,r).split(bo);return Sr.test(r)&&!Er.test(r)&&!ge(t.join("/"))&&t.every(n=>n===".."||!n.startsWith(".")&&!Rr.has(n))},He=(e,r,t)=>{const{parsed:n}=R(r);if(n===void 0)return[];const{error:o,merged:s}=oe(n,t),{main:a}=o===void 0?s:n,i=typeof a=="string"?$(cr(r),a):void 0;return i!==void 0&&b(i)&&Tr(e,i)?[i]:[]},Te=e=>e===void 0?!1:e.getKind()===p.FalseKeyword?!0:k.isParenthesizedExpression(e)||k.isAsExpression(e)||k.isSatisfiesExpression(e)||k.isTypeAssertion(e)||k.isNonNullExpression(e)?Te(e.getExpression()):!1,$o=e=>{try{return Ze(e).isFile()}catch{return!1}},So=new Set(["ELOOP","ENOENT","ENOTDIR"]),ee=(e,r,t)=>{const n=r instanceof Error&&"code"in r&&typeof r.code=="string"?r.code:"";So.has(n)||t.push(e)},Eo=(e,r)=>{try{return Ze(e)}catch(t){ee(e,t,r);return}},Pr=(e,r)=>{try{return E(e,"utf8")}catch(t){ee(e,t,r);return}},_r=(e,r,t,n=new Set)=>{let o;try{o=Gr(r)}catch(a){return ee(r,a,t),[]}if(n.has(o))return[];n.add(o);let s;try{s=ve(r)}catch(a){return ee(r,a,t),[]}return s.flatMap(a=>{const i=$(r,a),c=Eo(i,t);if(c===void 0)return[];const l=W(e,i).split(B).join("/");return c.isDirectory()?Rr.has(a)||a.startsWith(".")||ge(`${l}/`)?[]:_r(e,i,t,n):c.isFile()&&Sr.test(a)&&!Er.test(a)&&!ge(l)?[i]:[]})},Ao=e=>{const r=k.isComputedPropertyName(e)?e.getExpression():e;return k.isStringLiteral(r)||k.isNoSubstitutionTemplateLiteral(r)?r.getLiteralValue():e.getText()},le=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],Ro=/\.(?:[cm]?js|jsx)$/u,To=(e,r)=>{if(!r.startsWith("."))return;const t=j(cr(e),r),n=t.replace(Ro,"");return[t,...le.map(s=>`${t}${s}`),...le.map(s=>$(t,`index${s}`)),...le.map(s=>`${n}${s}`)].find(s=>$o(s))},Po=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},_o=e=>{const r=e.getModuleReference();if(!k.isExternalModuleReference(r))return;const t=r.getExpression();return k.isStringLiteral(t)?t.getLiteralValue():void 0},Do=(e,r,t,n)=>{const o=new Set(e),s=[...e],a=[];for(let i=0;i<s.length;i+=1){const c=s[i]??"",l=Pr(c,n);if(l===void 0)continue;const d=r.createSourceFile(W(t,c),l,{overwrite:!0}),g=[...d.getImportDeclarations().map(u=>u.getModuleSpecifierValue()),...d.getExportDeclarations().map(u=>u.getModuleSpecifierValue()),...d.getDescendantsOfKind(p.ImportEqualsDeclaration).map(u=>_o(u)),...d.getDescendantsOfKind(p.CallExpression).map(u=>Po(u))].filter(u=>u!==void 0);for(const u of g){const h=To(c,u);h!==void 0&&Tr(t,h)&&!o.has(h)&&(o.add(h),a.push(h),s.push(h))}}return a},Co=e=>{const r=e.getArgumentExpression();return r!==void 0&&(k.isStringLiteral(r)||k.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},Io=e=>k.isPropertyAccessExpression(e)?e.getName():k.isElementAccessExpression(e)?Co(e):void 0,Oo=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]),jo=e=>{const r=e.getOperatorToken().getKind();return!Oo.has(r)||Io(e.getLeft())!==Ar?!1:r!==p.EqualsToken||!Te(e.getRight())},No=(e,r,t)=>{const n=[],o=[...new Set([I(e),"src"])].filter(g=>b($(e,g))),s=O(e),a=[...ko.map(g=>$(e,g)).filter(g=>b(g)),...s===void 0?[]:He(e,s,r),...t.flatMap(g=>He(e,g,r))],i=new dr({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}),c=o.flatMap(g=>_r($(e,g),$(e,g),n));return{sites:[...new Set([...c,...a,...Do([...a,...c],i,e,n)])].flatMap(g=>{const u=Pr(g,n);if(u===void 0)return[];const h=i.createSourceFile(W(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)&&Te(m.getInitializer());return Ao(m.getNameNode())===Ar&&!T}).map(m=>m.getStartLineNumber()),v=h.getDescendantsOfKind(p.BinaryExpression).filter(m=>jo(m)).map(m=>m.getStartLineNumber());return[...f,...v].map(m=>({file:W(e,g),line:m}))}),unreadable:n}},Lo=(e,r,t,n,o,s)=>{if(t!=="deploy")return;const{sites:a,unreadable:i}=No(e,o,s),c=nn({openShardAccess:a,schema:{tables:[]}},{lints:[Oe]});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(" ")} ${Oe.remediation}`;return r.error(d),d},Mo=(e,r,t,n)=>{const o=Lo(e,r.logger,t,r.allowOpenShards===!0,r.env,n);return o===void 0?void 0:{code:w.USAGE,error:o}},xo=(e,r,t,n)=>{const o=yo(e,r.logger,t,n,r.env);if(o!==void 0)return{code:w.USAGE,error:o};const s=wo(e,r.logger,t,r.env);if(s!==void 0)return{code:w.USAGE,error:s};const a=ho(e,r.logger,t,r.discoveryCache);if(a!==void 0)return{code:w.USAGE,error:a};const i=fo(e,r.logger,r.dockerAvailable??Yt,t,r.env);return i===void 0?void 0:{code:w.MISSING_DEPENDENCY,error:i}},We=32,Dr=15e3,Fo=5432,Uo=3306,Bo=/[^a-z0-9-]/gu,Ho=/[^A-Za-z0-9]/gu,Wo=/-$/u,G=e=>`LUNORA_${e.replaceAll(Ho,"_").toUpperCase()}_URL`,Go=e=>{const r=new Map;for(const t of e){const n=G(t),o=r.get(n);if(o!==void 0)return{bindings:[o,t],variable:n};r.set(n,t)}},Ge=7,Vo=(e,r)=>{const t=`${e}-${r}`.toLowerCase(),n=t.replaceAll(Bo,"-");if(n===t&&n.length<=We)return n;const o=Vt("sha256").update(t).digest("hex").slice(0,Ge-1);return`${n.slice(0,We-Ge).replace(Wo,"")}-${o}`},Ve=e=>e==="postgresql"?"postgres":e==="mariadb"?"mysql":e,qo=e=>e==="mysql"?Uo:Fo,Ko=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===""?qo(Ve(t)):Number(r.port),scheme:Ve(t),user:decodeURIComponent(r.username)}}catch{return}},zo=(e,r)=>{const t=typeof r?.password=="string"?r.password:"",n=t===""?[]:[t,JSON.stringify(t).slice(1,-1),encodeURIComponent(t)];let o=e;for(const s of n)o=o.replaceAll(s,"<redacted>");return o.split(" ").map(s=>s.includes("://")?"<url>":s).join(" ")},Cr=e=>(Array.isArray(e)?e:[]).flatMap((r,t)=>{const{binding:n,id:o}=typeof r=="object"&&r!==null?r:{};return typeof n=="string"&&o===or?[{binding:n,index:t}]:[]}),re=e=>{let r="";try{const{errors:t}=JSON.parse(e.text);r=(t??[]).flatMap(n=>typeof n.message=="string"?[n.message]:[]).slice(0,2).join("; ")}catch{}return r===""?`HTTP ${String(e.status)}`:`HTTP ${String(e.status)}: ${r}`},Jo=e=>typeof e=="string"||typeof e=="number"?e.toString():void 0,Yo=["scheme","host","port","database","user"],Xo=e=>e==="postgresql"?"postgres":e,qe=(e,r)=>{const t=Jo(r);return e==="scheme"?Xo(t):t},Ke=50,Qo=async(e,r)=>{for(let t=1;t<=Ke;t+=1){const n=await e(t===1?"/hyperdrive/configs":`/hyperdrive/configs?page=${String(t)}`);if(!n.ok)throw new Error(`listing Hyperdrive configs failed (${re(n)})`);if(!Array.isArray(n.body.result))throw new TypeError("the listing of Hyperdrive configs had no result list");const o=n.body.result.find(a=>a.name===r),s=typeof n.body.result_info=="object"&&n.body.result_info!==null?n.body.result_info:{};if(o!==void 0||typeof s.total_pages!="number"||t>=s.total_pages)return o}throw new Error(`the listing of Hyperdrive configs has more than ${String(Ke)} pages, so "${r}" can't be shown to be absent`)},Zo=async(e,r,t,n)=>{const o=n?{caching:{disabled:!0}}:{},s=await Qo(e,r);if(typeof s?.id=="string"){const c=Yo.filter(d=>qe(d,s.origin?.[d])!==qe(d,t[d]));if(c.length>0)throw new Error(`a Hyperdrive config named "${r}" already exists for a different origin, or one that can't be confirmed (${c.join(", ")}). Delete it, or rename the Worker, so the binding does not reach the wrong database.`);const l=await e(`/hyperdrive/configs/${encodeURIComponent(s.id)}`,{body:JSON.stringify({origin:t,...o}),method:"PATCH"});if(!l.ok)throw new Error(`updating its credentials failed (${re(l)})`);return{id:s.id,reused:!0}}const a=await e("/hyperdrive/configs",{body:JSON.stringify({name:r,origin:t,...o}),method:"POST"});if(!a.ok)throw new Error(`creating it failed (${re(a)})`);const{id:i}=typeof a.body.result=="object"&&a.body.result!==null?a.body.result:{};if(typeof i!="string")throw new TypeError("the response carried no id");return{id:i,reused:!1}},es=(e,r,t,n)=>r===void 0&&n?`${G(e)} is set but is not a usable connection string for the "${e}" Hyperdrive binding: it needs a postgres://, postgresql:// or mysql:// scheme, a host and a database name, with any special characters percent-encoded.`:r===void 0?`the "${e}" Hyperdrive binding has no config yet. Set ${G(e)} to its postgres:// or mysql:// connection string and Lunora creates the config, or run \`wrangler hyperdrive create\` and put its id in wrangler.jsonc.`:t?void 0:`creating the "${e}" Hyperdrive config needs CLOUDFLARE_API_TOKEN (Hyperdrive: Edit) and CLOUDFLARE_ACCOUNT_ID, or run \`wrangler hyperdrive create\` and put its id in wrangler.jsonc.`,rs=async(e,r)=>{const t=Vo(e.workerName,e.binding),{id:n,reused:o}=await Zo(async(s,a)=>ur({accountId:e.accountId,apiToken:e.token,...e.fetch===void 0?{}:{fetch:e.fetch},init:{...a,signal:AbortSignal.timeout(Dr)},path:s}),t,e.origin,e.disableCaching);return e.logger.success(`${o?"reusing":"created"} Hyperdrive config "${t}" for ${e.binding} → ${e.wranglerPath}`),{id:n,text:sr(r,[...e.path,e.index,"id"],n)}},ts=e=>e===void 0||e===""?void 0:e,Ir=e=>{const r=y(U(e),".wrangler","deploy","config.json");try{const{configPath:t}=JSON.parse(E(r,"utf8"));return typeof t=="string"?j(U(r),t):void 0}catch{return}},ns=(e,r,t,n,o)=>{const s=Ir(e);if(s===void 0||s===e)return;if(n.built!==n.deployed){o.warn(`the build output ${s} was made for ${n.built===void 0?"the default environment":`"${n.built}"`}, not ${n.deployed===void 0?"the default environment":`"${n.deployed}"`}, so the "${r}" Hyperdrive id was not written there. Build with CLOUDFLARE_ENV set to the environment you deploy, then deploy again.`);return}let a;try{a=R(s)}catch{return}const i=Cr(a.parsed?.hyperdrive).find(c=>c.binding===r);i!==void 0&&V(s,sr(a.text,["hyperdrive",i.index,"id"],t),"utf8")},os=(e,r)=>{const t=typeof e.name=="string"&&e.name!==""?e.name:"lunora";if(r===void 0)return t;const n=e.env?.[r]?.name;return typeof n=="string"&&n!==""?n:`${t}-${r}`},Pe=(e,r)=>{const t=O(e),n=t===void 0?void 0:R(t).parsed;if(t===void 0||n===void 0)return;const o=r===void 0?void 0:n.env?.[r],s=Cr(r===void 0?n.hyperdrive:o?.hyperdrive);return s.length===0?void 0:{accountId:o?.account_id??n.account_id,entries:s,path:r===void 0?["hyperdrive"]:["env",r,"hyperdrive"],workerName:os(n,r),wranglerPath:t}},ss=(e,r,t)=>{const n=Go(e.map(({binding:o})=>o));if(n!==void 0){const o=`deploy blocked: the Hyperdrive bindings ${n.bindings.map(s=>`"${s}"`).join(" and ")} both read ${n.variable} and would share one config. Rename one so their names differ in letters or digits, not only in punctuation.`;return t.logger.error(o),o}for(const{binding:o,origin:s,supplied:a}of e){const i=es(o,s,r,a);if(i!==void 0&&t.dryRun===!0)t.logger.warn(`dry run: ${i} A real deploy stops here.`);else if(i!==void 0){const c=`deploy blocked: ${i}`;return t.logger.error(c),c}}},as=async(e,r,t,n)=>{let o;try{o=await e(`/hyperdrive/configs/${encodeURIComponent(t)}`)}catch(a){n.warn(`could not check whether the "${r}" Hyperdrive config has query caching off (${a instanceof Error?a.message:String(a)}).`);return}if(!o.ok){n.warn(`could not check whether the "${r}" Hyperdrive config has query caching off (${re(o)}).`);return}const{caching:s}=typeof o.body.result=="object"&&o.body.result!==null?o.body.result:{};s?.disabled!==!0&&n.warn(`the "${r}" Hyperdrive config has query caching on, so .global() tables would read rows up to 75 s old. Run \`wrangler hyperdrive update ${t} --caching-disabled\`.`)},is=async(e,r)=>{const t=O(e.cwd),n=t===void 0?void 0:R(t).parsed,o=e.wranglerEnvironment===void 0?n:n?.env?.[e.wranglerEnvironment],{accountId:s,token:a}=lr(r,o?.account_id??n?.account_id);if(s===void 0||a===void 0)return;const i=async(c,l)=>ur({accountId:s,apiToken:a,...e.fetch===void 0?{}:{fetch:e.fetch},init:{...l,signal:AbortSignal.timeout(Dr)},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!==or&&await as(i,l,d,e.logger)}},cs=async e=>{const r=e.environment??process.env;e.disableCaching===!0&&e.checkOnly!==!0&&e.dryRun!==!0&&await is(e,r);const t=Pe(e.cwd,e.wranglerEnvironment);if(t===void 0)return;const{entries:n,path:o,wranglerPath:s}=t,{accountId:a,token:i}=lr(r,t.accountId),c=n.map(({binding:d})=>{const g=r[G(d)]??"";return{binding:d,origin:Ko(g),supplied:g!==""}}),l=ss(c,i!==void 0&&a!==void 0,e);if(l!==void 0)return l;if(!(e.dryRun===!0||e.checkOnly===!0))for(const[d,{binding:g,index:u}]of n.entries()){const h=c[d]?.origin;if(!(h===void 0||i===void 0||a===void 0))try{const{id:f,text:v}=await rs({accountId:a,binding:g,disableCaching:e.disableCaching===!0,fetch:e.fetch,index:u,logger:e.logger,origin:h,path:o,token:i,workerName:t.workerName,wranglerPath:s},E(s,"utf8"));V(s,v,"utf8"),ns(s,g,f,{built:ts(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: ${zo(v,c[d]?.origin)}`;return e.logger.error(m),m}}},ds=(e,r)=>{const t=Pe(e,r.env)?.entries[0]?.binding;if(t===void 0)return;const n=`prepare blocked: the "${t}" Hyperdrive binding still has its placeholder id. Run \`lunora deploy\` with ${G(t)} set to create the config, or put the id from \`wrangler hyperdrive create\` in wrangler.jsonc.`;return r.logger.error(n),n},ls=(e,r)=>{const t=Pe(e,r.env)?.entries[0]?.binding;if(t===void 0)return;const n=`deploy blocked: the "${t}" Hyperdrive binding has no config, and a --temporary deploy cannot create one: it would be made in your account while the Worker goes to a temporary one, which a temporary account has no database for. Deploy without --temporary.`;return r.logger.error(n),n},Or=async(e,r,t,n,o="create")=>{if(n!=="cloudflare")return;if(t==="prepare")return ds(e,r);if(r.temporary===!0)return ls(e,r);const s=r.clientBuildEnvironment===void 0?void 0:{...process.env,CLOUDFLARE_ENV:r.clientBuildEnvironment},a=we(e,I(e),r.discoveryCache);return a.error!==void 0&&r.logger.warn(`could not read the schema (${a.error}), so Hyperdrive configs are set up with query caching off.`),cs({checkOnly:o==="check",cwd:e,disableCaching:a.error!==void 0||a.info?.hasHyperdriveGlobalTable===!0,dryRun:r.dryRun,environment:s,logger:r.logger,wranglerEnvironment:r.env})},us=/https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u,gs=/https:\/\/[^\s"'<>]+/u,fs=e=>{if(e===void 0)return;const r=us.exec(e);return r?r[0]:gs.exec(e)?.[0]},ze=e=>e===void 0?"":` (--env ${e})`,hs=({cwd:e,env:r,logger:t,now:n,url:o})=>{if(o!==void 0)try{const s=ye(e);if(s!==void 0){if(s.workerUrl===o&&s.env===r)return;t.warn(`link: .lunora/project.json records ${s.workerUrl??"(no url)"}${ze(s.env)}, but this deploy published ${o}${ze(r)}. Keeping the recorded value — run \`lunora link --url ${o}${r===void 0?"":` --env ${r}`}\` to update it.`);return}const a=(n??(()=>new Date().toISOString()))();st(e,{env:r,linkedAt:a,workerName:be(e),workerUrl:o}),t.success(`link: recorded ${o} in .lunora/project.json (run \`lunora link\` to change)`)}catch{}},ms=async(e,r)=>{const t=new dr({skipAddingFilesFromTsConfig:!0}),n=$(r,"lunora");let o;try{o=Kr(t,n)}catch(s){const a=s instanceof Error?s.message:String(s);return e.logger.warn(`--migrate: could not discover migrations (${a}); skipping`),0}if(o.length===0)return e.logger.info("--migrate: no data migrations declared in lunora/"),0;e.logger.info(`--migrate: running ${String(o.length)} migration(s) against deployed worker`);for(const s of o){e.logger.info(`--migrate: up "${s.id}" (table "${s.table}")`);const a={cwd:r,fetchImpl:e.fetchImpl,id:s.id,logger:e.logger,prod:!0,subcommand:"up",token:e.migrateToken,url:e.migrateUrl,yes:e.migrateYes===!0},i=await on(a);if(i.code!==0)return e.logger.error(`--migrate: migration "${s.id}" failed — see output above`),i.code;e.logger.success(`--migrate: "${s.id}" applied`)}return 0},vs=async(e,r)=>{const{info:t}=we(r,"lunora",e.discoveryCache),n=t?.vectorMetadata??[];if(n.length===0)return;const o=[];for(const i of n){const c=Mt(i.kind);if(c===void 0){e.logger.warn(`vector index "${i.index}" declares metadata "${i.property}", whose column type cannot be filtered on in Vectorize — it is stored with each vector but no filter will match it.`);continue}o.push({index:i.index,property:i.property,type:c})}if(o.length===0)return;const a=(await xt({cwd:r,entries:o,exec:$e(N(r),"wrangler",[]),logger:e.logger,spawner:e.spawner??x})).filter(i=>i.status!=="failed").length;a>0&&e.logger.success(`vectorize metadata indexes ready: ${String(a)}/${String(o.length)}`)},Je=5,ps=2e3,ys=async(e,r,t)=>{if(e.healthCheck!==!0)return;const n=t??Se({cwd:r,env:e.env});if(n===void 0){const s="--health-check: the deploy succeeded, but no URL to probe could be resolved — wrangler's output carried none and this checkout has no link for this environment. Run `lunora link --url <https://your-worker>` and re-deploy, or drop --health-check.";return e.logger.error(s),{error:s,ok:!1,url:""}}const o=await Xt({attempts:Je,baseUrl:n,delayMs:ps,fetchImpl:e.healthFetch,paths:[Qt,Zt],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(Je)} attempt(s) — ${o.error}`),{error:o.error,ok:!1,url:o.url})},ws=async(e,r,t,n,o,s)=>{await vs(e,r);const a=e.migrate?await ms(e,r):0;return a===0&&o?.(),{code:a,descriptor:t,mintedSecretsFile:s,validation:n}},ks=async({cwd:e,descriptor:r,mintedSecretsFile:t,options:n,reblessSchemaBaseline:o,recordArchitecture:s,stdout:a,validation:i})=>{const c={deployedAt:new Date().toISOString(),dryRun:n.dryRun===!0,env:n.env,url:n.dryRun===!0?void 0:fs(a),workerName:be(e)};if(n.dryRun===!0)return n.healthCheck===!0&&n.logger.warn("--health-check skipped: a dry run publishes nothing"),{code:0,deployment:c,descriptor:r,mintedSecretsFile:t,validation:i};n.temporary!==!0&&(s?.(),hs({cwd:e,env:n.env,logger:n.logger,url:c.url}));const l=await ys(n,e,c.url);return l?.error!==void 0?{code:w.UNAVAILABLE,deployment:c,descriptor:r,healthCheck:l,mintedSecretsFile:t,validation:i}:{...await ws(n,e,r,i,o,t),deployment:c,healthCheck:l}},bs=(e,r,t)=>{const n=$(e,C);if(!b(n))return;let o;try{o=rr(E(n,"utf8")).length}catch{return}if(o===0)return;const s=t.toolchain?.secretPut!==void 0;r.warn(s?`Note: \`lunora deploy\` does not push secrets. ${C} has ${String(o)} key(s); if you changed them, run \`lunora env push --yes\` to update the deployed secrets.`:`Note: ${t.name} deploys read no secrets. ${C} has ${String(o)} key(s) that only the dev server sees; a key the app reads from env must be a \`vars\` entry in the deployed config, one it loads from a secret manager at runtime need not.`)},jr=async(e,r)=>{let t=[];try{t=at(await tr({cache:r,projectRoot:e,schemaDir:I(e)}))}catch{}const n=[...new Set(it(t).map(s=>s.key))];let o=[];try{const s=$(e,C);b(s)&&(o=rr(E(s,"utf8")).map(a=>a.key).filter(a=>ar(a)))}catch{}return{fromLocal:o.filter(s=>!n.includes(s)),fromPackages:n,mintableKeys:ct(t)}},$s=async(e,r,t,n)=>{const{logger:o}=r,s=r.spawner??x,a=N(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:dt()})),d=n.toolchain?.secretBulk;if(d!==void 0&&l.length>=2){const u=H(a,d({environment:r.env,temporary:r.temporary})),h=await s({args:u.args,command:u.command,cwd:e,input:JSON.stringify(Object.fromEntries(l.map(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(a,f),m=await s({args:v.args,command:v.command,cwd:e,input:h});if(m.code!==0)return o.error(`failed to push secret ${u} (exit ${String(m.code)}); set it manually with \`wrangler secret put ${u}${i}\`.`),{minted:g,ok:!1};g.push({key:u,value:h}),o.success(`generated + pushed ${u}`)}return{minted:g,ok:!0}},Ss=/^[\w-]+$/u,Ye=[".dev.vars",".dev.vars.*","!.dev.vars.example"],Es=(e,r)=>{try{const t=ft(e,Ye);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 \`${Ye.join("` and `")}\` by hand before committing.`)}},As=(e,r,t)=>{if(t.length===0)return;const n=t.map(i=>i.key).join(", ");if(r.env!==void 0&&!Ss.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}`;Es(e,r.logger);const s=$(e,o);let a=b(s)?E(s,"utf8"):"";for(const i of t)a=lt(a,i.key,i.value);return ut(s,a),r.logger.success(r.env===void 0?`${n}: value(s) recorded in ${o}`:`${n}: value(s) recorded in ${o} (kept separate from ${C} so \`lunora dev\` and a plain \`lunora env push\` don't inherit the --env ${r.env} value)`),o},Rs=/^<[^>]+>$/u,Ts=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===""||Rs.test(u)?!0:ar(d)&&gt(g)},s=d=>Object.hasOwn(n,d)?`${d} (empty or a placeholder)`:d,{fromLocal:a,fromPackages:i}=await jr(e,r.discoveryCache),c=a.filter(d=>o(d));c.length>0&&r.logger.warn(`${C} key(s) not set in the wrangler vars: ${c.map(d=>s(d)).join(", ")}. ${t.name} has no secret store: a key the app reads from env must be a \`vars\` entry; one it loads from a secret manager at runtime need not.`);const l=i.filter(d=>o(d));return l.length===0?{}:{error:`missing required secret(s) in the wrangler vars: ${l.map(d=>s(d)).join(", ")}. ${t.name} has no secret store and Lunora reads these from env, so each must be a real \`vars\` value in the config the deploy ships — write it there from your secret manager at deploy time rather than committing it. Add them, then re-deploy.`}},Ps=async(e,r,t,n)=>{if(r.dryRun===!0)return{};if(n.toolchain?.secretList===void 0)return Ts(e,r,n);const{logger:o}=r,s=r.env===void 0?"":` --env ${r.env}`;let a;try{a=await(r.secretLister??an)({cwd:e,env:r.env,target:n.id,temporary:r.temporary})}catch{return{}}if(!a.ok)return{};const i=new Set(a.names),{fromLocal:c,fromPackages:l,mintableKeys:d}=await jr(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>${s}\` (or \`lunora env generate --set\` then \`lunora env push --yes${s}\`), 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}${s}`);const u=g.filter(f=>d.has(f));if(u.length===0)return{};if(await(r.secretConfirm??sn())(`${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 $s(e,r,u,n),m=As(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${s}\`.`),{}},Nr=e=>e.format==="json"?!1:e.interactive!==void 0?e.interactive:process.stdout.isTTY&&!process.env.CI,_s=async(e,r)=>{if(r.dryRun===!0)return;const t=er(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 Bn({cwd:e,logger:r.logger,railpackAvailable:r.railpackAvailable,spawner:r.spawner,targets:t});return n.code===0?void 0:n.error??"railpack build failed"},Ds=(e,r,t)=>{if(t!==void 0)try{const n=Rt(e,t);n.changed&&r.success(`synced ${String(t.length)} cron trigger(s) → ${n.wranglerPath??"wrangler.jsonc"}`);for(const s of n.warnings)r.warn(s);const o=Tt(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}`)}},Cs=async(e,r,t,n,o,s)=>{try{ne(n);const a=await tr({cache:s,projectRoot:e,schemaDir:I(e)}),i=Et(e,a,{environment:o,target:n}),c=i.wranglerPath??"wrangler.jsonc";if(i.added.length>0&&r.success(`provisioned bindings: ${i.added.join(", ")} → ${c}`),i.updated.length>0&&r.success(`updated bindings: ${i.updated.join(", ")} → ${c}`),i.devConfig!==void 0){const{added:l,path:d,updated:g}=i.devConfig;r.success(`dev sidecar bindings: ${[...l,...g].join(", ")} → ${d}`)}for(const l of i.warnings)r.warn(l)}catch(a){const i=a instanceof Error?a.message:String(a);r.warn(`binding inference skipped: ${i}`)}try{const a=At(e);a.changed&&r.success(`bumped compatibility_date to ${a.date??"unknown"} (Workers Cache enabled) → ${a.wranglerPath??"wrangler.jsonc"}`)}catch(a){const i=a instanceof Error?a.message:String(a);r.warn(`compatibility date sync skipped: ${i}`)}Ds(e,r,t)},Is=async(e,r,t,n,o,s,a,i,c,l)=>{let d;r?(d=new Pt({name:"dots"}),d.start("running codegen")):t.info("running codegen");try{const g=zr({apiSpec:n,dryRun:!l,lazyFunctions:o,projectRoot:e,target:s,...St(e)});d?.succeed("codegen complete"),d||t.success("codegen complete");const u=Ot(g.platformDiagnostics,t);if(u.errors.length>0)return{error:u.errors.join("; ")};const{errorAdvisories:h,names:f,shouldBlock:v}=jt(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 yt({cwd:e,logger:t,spawner:a,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}`}}},Xe="--preview is not supported: Cloudflare gives a Worker that implements a Durable Object no version preview URL, and a version shares production's Durable Objects, D1 and R2. Deploy an isolated copy with `--env <name>` (its own Worker name, so its own Durable Object namespace, plus the env's own D1/R2 bindings), or validate without publishing with `--dry-run`.",Os=(e,r)=>({dryRun:r.dryRun,entry:Re(e),environment:r.env,outDir:r.outDir,temporary:r.temporary}),Lr=(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=Os(e,r);return nr(t,e,"deploy",s=>n.deploy({...o,configPath:s}))},js=(e,r,t)=>{const n=Lr(e,r,t),o=Re(e);return o!==void 0&&r.logger.info(`class-B composition: deploying ${o} (overrides wrangler main)`),r.temporary&&r.logger.info("temporary account: deploying to a short-lived Cloudflare account (~60min); wrangler will print a claim URL"),r.dryRun&&r.logger.info("dry run: validating + bundling without publishing"),r.outDir!==void 0&&r.logger.info(`build artifact: emitting bundle to ${r.outDir}`),n.commit(),n.projection!==void 0&&n.projection.dropped.length>0&&r.logger.warn(`${t.name} ignores these wrangler keys, so they were left out of ${n.projection.configPath}: ${n.projection.dropped.join(", ")}`),n.command},A={problems:[],wranglerPath:void 0},ue=(e,r)=>({code:w.USAGE,descriptor:void 0,error:e,validation:A,...r}),Ns=(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},Ls=(e,r,t)=>{const n=r.format==="json",o=r.dryRun!==!0,s=js(e,r,t),a=H(N(e),s);return{args:a.args,captureStdout:o&&!n,captureStdoutSilently:o&&n,command:a.command,cwd:e,stdoutToStderr:n&&!o}},_e=e=>{if(e.skipServices===!0)return"--skip-services";if(e.temporary===!0)return"--temporary deploys the app to a throwaway account"},Ms=(e,r)=>_e(r)===void 0?pe(e).services.map(t=>t.wranglerPath):[],Mr=(e,r,t,n,o)=>({cwd:e,environment:r.env,frameworkBuild:n,lazyFunctions:te(r.lazyFunctions),logger:r.logger,outputJson:r.format==="json"||r.clientBuildOutputJson===!0,spawner:o,strictAdvisories:ke(r),target:t.id}),xs=(e,r,t)=>{const{toolchain:n}=t,o=n===void 0?`target "${t.id}" has no deploy command`:_e(r);if(o!==void 0||n===void 0){const s=e.map(a=>a.worker).join(", ");r.logger.warn(`services not deployed (${o??""}): ${s} — deploy them yourself if the app calls anything new`);return}return n},xr=(e,r)=>{for(const t of e){const n=Ee(r(U(t.wranglerPath)));if(n!==void 0)return`service ${t.name} (${t.worker}): ${n}`}},Fs=(e,r,t)=>{const{error:n,services:o}=pe(e);if(n!==void 0||o.length===0)return;const s=ne(t);if(s.toolchain===void 0||_e(r)!==void 0)return;const a=r.skipCodegen===!0?!1:r.frameworkBuild,i=[...new Map(o.map(c=>[c.wranglerPath,c])).values()];return xr(i,c=>Mr(c,r,s,a,x))},Fr=(e,r,t)=>{const n=e.cwd??process.cwd(),o=Wt(n,e.target);if(o.target===void 0){const i=o.error??"unknown deploy target";return e.logger.error(i),{kind:"refused",error:i,validation:A}}if(e.preview===!0)return e.logger.error(Xe),{kind:"refused",code:w.USAGE,error:Xe,validation:A};try{Lr(n,e,ne(o.target))}catch(i){if(!(t&&i instanceof ht&&ae(n,e.skipCodegen===!0?!1:e.frameworkBuild,e.env))){const c=i instanceof Error?i.message:String(i);return e.logger.error(c),{kind:"refused",error:c,validation:A}}}const s=e.openShardGatePassed===!0?void 0:Mo(n,e,r,Ms(n,e));if(s!==void 0)return{kind:"refused",code:s.code,error:s.error,validation:A};const a=Fs(n,e,o.target);return a!==void 0?(e.logger.error(a),{kind:"refused",code:w.USAGE,error:a,validation:A}):{kind:"ok",target:o.target}},Us=(e,r)=>e.apiSpec??(e.clientBuildRan===!0?wt(r):void 0),Bs=async(e,r,t)=>{if(r!=="celld")return;const n=await(e.celldToolchain??pt)({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},Ur=(e,r)=>{const t=Se({cwd:e,env:r.env,url:r.migrateUrl}),n=t===void 0?void 0:to(e,r.env,t);if(n!==void 0)return{reason:n};const o=t===void 0?void 0:Ct(t,r.logger,e),s=o===void 0?void 0:_t({cwd:e,token:r.migrateToken,url:o}).token;return{target:o===void 0||!s?void 0:{baseUrl:o,fetchImpl:r.fetchImpl??It,token:s}}},Hs=(e,r,t)=>async n=>{const o=Ur(e,r);return"reason"in o?{kind:"inconclusive",reason:o.reason}:tn({changes:n,tables:t.schemaTables,target:o.target})},Ws=(e,r)=>async t=>{const n=Ur(e,r);return"reason"in n?n.reason:rn({changes:t,now:Date.now(),target:n.target})},Gs=(e,r,t,n)=>e==="deploy"?{checkStoredRows:Hs(r,t,n),countExpiringRows:Ws(r,t)}:{},Vs=async(e,r)=>{const t=e.cwd??process.cwd(),n=Nr(e),o=ke(e),s={problems:[],wranglerPath:void 0},a=Fr(e,r,!1);if(a.kind==="refused")return{code:a.code,error:a.error,validation:a.validation};const{target:i}=a,c=await Bs(e,i,r);if(c!==void 0)return e.logger.error(c),{code:w.MISSING_DEPENDENCY,error:c,target:i,validation:s};let l;if(!e.skipCodegen){const v=await Is(t,n,e.logger,Us(e,t),te(e.lazyFunctions),i,e.spawner,e.format==="json",o,e.clientBuildRan!==!0);if(v.error!==void 0)return{error:v.error,target:i,validation:A};l=v.result,e.discoveryCache?.clear()}let d;if(l!==void 0){const v=await en({allowDrift:e.allowSchemaDrift===!0,...Gs(r,t,e,l),codegen:l,command:r,logger:e.logger});if(v.blocked)return{error:`schema drift gate blocked ${r}`,schemaDrift:{blocked:!0,reason:v.reason},target:i,validation:s};d=v.rebless}const g=l&&hn({current:l.architecture,cwd:t,environment:e.env,logger:e.logger});await Cs(t,e.logger,l?.cronTriggers,i,e.env,e.discoveryCache);const u=await Or(t,e,r,i,"check");if(u!==void 0)return{error:u,target:i,validation:A};const h=xo(t,e,r,i);if(h!==void 0)return{code:h.code,error:h.error,target:i,validation:A};const f=$t({environment:e.env,projectRoot:t});return Ns(f,e.logger)?{error:"wrangler validation failed",target:i,validation:f}:{codegen:l,reblessSchemaBaseline:d,recordArchitecture:g,target:i,validation:f}},qs=e=>{Q(y(e,".wrangler","deploy","config.json"),{force:!0})},Ks=async(e,r,t)=>{const n=Ee(e);if(n!==void 0)return{built:!1,error:n};const o=ae(e.cwd,r,t);return o&&qs(e.cwd),{built:o,error:await $r(e)}},zs=(e,r,t)=>r||t===!1?Ir(e):void 0,Js=async(e,r,t,n)=>{const{error:o,services:s}=pe(e);if(o!==void 0)return{code:w.FAILURE,error:o};if(s.length===0)return;const a=xs(s,r,t);if(a===void 0)return;const i=N(e),c=[...new Map(s.map(u=>[u.wranglerPath,u])).values()],l=r.skipCodegen===!0?!1:r.frameworkBuild,d=u=>Mr(u,r,t,l,n),g=xr(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 Ks(f,l,r.env);if(m!==void 0){const S=`service ${u.name} (${u.worker}): ${m}`;return r.logger.error(S),{code:w.FAILURE,error:S}}const T=zs(u.wranglerPath,v,l);let L;try{L=nr(t,h,"deploy",S=>a.deploy({configPath:S??T??u.wranglerPath,dryRun:r.dryRun===!0,environment:r.env}))}catch(S){return{code:w.FAILURE,error:`service ${u.name} (${u.worker}): ${S instanceof Error?S.message:String(S)}`}}L.commit();const D=H(i,L.command);r.logger.info(`deploying service ${u.name} (${u.worker}) via ${D.command} ${D.args.join(" ")}`);const P=await n({args:D.args,command:D.command,cwd:h,stdoutToStderr:r.format==="json"});if(P.code!==0)return{code:w.FAILURE,error:`service ${u.name} (${u.worker}): ${D.command} ${D.args.join(" ")} exited ${String(P.code)} — stopping before the app`}}},Ys=async(e,r,t,n)=>{if(r!=="cloudflare")return;const o=e===void 0?void 0:R(e).parsed,s=(t===void 0?void 0:o?.env?.[t]?.account_id)??o?.account_id,a=await Ut({accountId:s});(a.verdict==="near"||a.verdict==="full")&&n.warn(a.fix===void 0?a.message:`${a.message} ${a.fix}`)},Xs=e=>e.dryRun!==!0&&e.temporary!==!0,Qs=e=>e.temporary===!0?"temporary":e.dryRun===!0?"preview":"defer",Zs=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},ea=(e,r,t)=>{const n=[];for(const o of e)if(o.verdict==="ok")o.changesAccount===!0&&r.info(o.message);else if(o.verdict==="unchecked"&&t==="preview")r.warn(`dry run: ${o.message}${o.fix===void 0?"":` ${o.fix}`} A real deploy stops here.`);else{const s=Zs(o);r.error(s),n.push(s)}return n},Br=async(e,r,t,n,o,s,a)=>{const i=t==="cloudflare"&&r!==void 0?R(r).parsed:void 0;if(i===void 0)return;const c=(oe(i,n).merged.artifacts??[]).flatMap(f=>typeof f?.binding=="string"&&typeof f.namespace=="string"?[{binding:f.binding,namespace:f.namespace}]:[]),l=c.length===0?void 0:we(e,I(e),s).info?.jurisdiction;if(l===void 0)return;const d=[...new Map(c.map(f=>[f.namespace,f])).values()];if(a==="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=>Ft({...f,accountId:g,create:a==="create",jurisdiction:l,missingOk:a==="defer"||a==="preview"}))),h=ea(u,o,a);return h.length===0?void 0:h.join(`
43
+ `)},ra=async(e,r,t,n,o,s)=>{const a=Xs(r)?await Br(e,s,o,r.env,r.logger,r.discoveryCache,"create"):void 0;if(a!==void 0)return{code:w.FAILURE,error:a};const i=await Or(e,r,"deploy",o);return i!==void 0?{code:w.FAILURE,error:i}:Js(e,r,t,n)},ta=async(e,r,t,n)=>{if(!(r.smokeLoad===!1||t.toolchain===void 0))return Fn({composedEntry:Re(e),configPath:n,cwd:e,environment:r.env,launcher:r.smokeLauncher,logger:r.logger,toolchain:t.toolchain})},na=async e=>{const r={...e,discoveryCache:e.discoveryCache??vt()},t=r.cwd??process.cwd(),n=Nr(r),o=await Vs(r,r.commandName??"deploy");if(o.error!==void 0){if(o.validation.problems.length>0)return{code:w.USAGE,descriptor:void 0,error:o.error,validation:o.validation};const m=o.schemaDrift===void 0?void 0:{schemaDrift:o.schemaDrift};return ue(o.error,{...m,...o.code===void 0?{}:{code:o.code}})}const{validation:s}=o,a=ne(o.target),i=po(r)??await Br(t,s.wranglerPath,o.target,r.env,r.logger,r.discoveryCache,Qs(r))??await ta(t,r,a,s.wranglerPath);if(i!==void 0)return ue(i);const c=a.toolchain?.prebuildsContainerImages===!0?await _s(t,r):void 0;if(c!==void 0)return ue(c);bs(t,r.logger,a),bt(t,m=>{r.logger.warn(m)}),await Ys(s.wranglerPath,o.target,r.env,r.logger);const{error:l,mintedSecretsFile:d}=await Ps(t,r,n,a);if(l!==void 0)return r.logger.error(l),{code:w.USAGE,descriptor:void 0,error:l,mintedSecretsFile:d,validation:s};const g=r.spawner??x,u=await ra(t,r,a,g,o.target,s.wranglerPath);if(u!==void 0)return{code:u.code,descriptor:void 0,error:u.error,mintedSecretsFile:d,validation:s};const h=Ls(t,r,a);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:s}:{...await ks({...o,cwd:t,descriptor:h,mintedSecretsFile:d,options:r,stdout:f.stdout}),logsAvailable:a.toolchain?.tail!==void 0}},oa=async e=>{const{logger:r}=e,t=e.cwd??process.cwd(),n={apiSpec:e.apiSpec,cwd:t,environment:e.env,bundleMetaPath:e.bundleMetaPath,frameworkBuild:e.skipCodegen===!0?!1:e.frameworkBuild,strictAdvisories:ke(e),lazyFunctions:te(e.lazyFunctions),logger:r,outputJson:e.format==="json"||e.clientBuildOutputJson===!0,spawner:e.spawner,target:e.target},o=Ee(n);if(o!==void 0)return r.error(o),{code:w.USAGE,descriptor:void 0,error:o,validation:A};mt(t);const s=await $r(n);if(s!==void 0)return r.error(s),{code:w.FAILURE,descriptor:void 0,error:s,validation:A}},sa=(e,r)=>{const t=r.skipCodegen===!0?!1:r.frameworkBuild;return ae(e,t,r.env)?r.env:void 0},aa=async e=>{const{logger:r}=e,t=e.cwd??process.cwd(),n=Fr(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 oa(e);if(o!==void 0)return o;const s=e.dryRun===!0?wr(t):void 0;let a;try{if(a=await na({...e,clientBuildEnvironment:sa(t,e),clientBuildRan:co(t,e.skipCodegen===!0?!1:e.frameworkBuild,e.env),logger:r,openShardGatePassed:!0}),a.code===0&&e.emitBindings!==void 0){const{error:i}=Bt({destination:e.emitBindings,logger:r,projectRoot:e.cwd??process.cwd()});i!==void 0&&(r.error(i),a={...a,code:w.USAGE})}}finally{s?.()}return e.format==="json"||a.code===0&&e.dryRun!==!0&&mn({cwd:e.cwd??process.cwd(),env:e.env,logger:e.logger,logsAvailable:a.logsAvailable===!0,mintedSecretsFile:a.mintedSecretsFile,url:a.deployment?.url}),a},Ua=Ht(async({cwd:e,format:r,logger:t,options:n})=>{const o=Un(e,n.root),s=await aa({allowOpenShards:n.allowOpenShards===!0,allowSchemaDrift:n.allowSchemaDrift===!0,apiSpec:Nt(n.apiSpec),frameworkBuild:n.prebuilt===!0?!1:n.frameworkBuild,lazyFunctions:te(n.lazyFunctions),cwd:o,dryRun:n.dryRun===!0,env:n.env,format:r,healthCheck:n.healthCheck===!0,logger:t,migrate:n.migrate===!0,migrateToken:n.migrateToken,migrateUrl:Se({cwd:o,env:n.env,url:n.migrateUrl}),migrateYes:n.migrateYes===!0,preview:n.preview===!0,skipCodegen:n.prebuilt===!0,skipServices:n.skipServices===!0,smokeLoad:n.smokeLoad,strictAdvisories:n.strictAdvisories,target:n.target,temporary:n.temporary===!0});return{code:s.code,data:{deployment:s.deployment,healthCheck:s.healthCheck,mintedSecretsFile:s.mintedSecretsFile,schemaDrift:s.schemaDrift,validation:s.validation},error:s.error}});export{Vs as a,Cs as b,Ua as e,Un as p,aa as r,ta as s,no 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{resolveLazyFunctions as c,resolveDeployDriver as t}from"@lunora/config";import{p as s}from"../packem_shared/api-spec-lYyq4vL6.mjs";import{d as l}from"../packem_shared/command-B6vu47iR.mjs";import{EXIT_CODE as o}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:c(r.lazyFunctions),cwd:a,logger:r.logger,spawner:r.spawner,strictAdvisories:r.strictAdvisories,target:r.target},"prepare");if(e.error!==void 0)return{code:e.code??o.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},t(e.target),e.validation.wranglerPath);return i!==void 0?{code:o.FAILURE,error:i,validation:e.validation}:(e.reblessSchemaBaseline?.(),r.logger.success("project is ready to deploy"),{code:0,validation:e.validation})},w=l(({cwd:r,logger:a,options:e})=>n({allowSchemaDrift:e.allowSchemaDrift===!0,apiSpec:s(e.apiSpec),lazyFunctions:c(e.lazyFunctions),cwd:r,logger:a,smokeLoad:e.smokeLoad,strictAdvisories:e.strictAdvisories,target:e.target}));export{w as execute,n as runPrepareCommand};
@@ -1,3 +1,3 @@
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(`
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 $}from"@lunora/seed";import{join as w}from"@visulima/path";import{Project as O}from"ts-morph";import{a as E}from"../packem_shared/shared-CV7ESvuj.mjs";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 u}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";import{a as F}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{b as p}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{runResetCommand as N}from"./runResetCommand.mjs";import{r as U}from"../packem_shared/import-C-XRRHrZ.mjs";const x=(e,r)=>typeof r=="bigint"?Number(r):r instanceof ArrayBuffer?[...new Uint8Array(r)]:r,f=(e,r)=>({code:e,error:r,ndjson:""}),I=(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(u.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(u.USAGE,o)}},z=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(()=>{})}},D=(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(u.USAGE,t)},_=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(u.USAGE,s)}if(!await(e.confirm??p)(`This will insert ${String(r)} generated row(s) into ${e.url??"the production worker"}. Continue?`))return e.logger.info("seed: aborted"),f(u.CANCELLED,"seed: aborted at the confirmation prompt")},G=e=>{const r=[];for(const{rows:o,table:t}of e)for(const n of o)r.push(JSON.stringify({doc:n,table:t},x));return{lines:r,ndjson:r.length>0?`${r.join(`
2
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};
3
+ ${E(r.length)}`:""}},L=async e=>{const r=e.cwd??process.cwd(),o=e.format==="json",t=w(r,"lunora","schema.ts"),n=I(e,t);if(n!==void 0)return n;const s=new O({skipAddingFilesFromTsConfig:!0}),d=C(s,t),a=D(e,d);if(a!==void 0)return a;const i=T(d),l=$(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}=G(l),m=h.length;if(e.dryRun===!0)return!o&&c.length>0&&process.stdout.write(c),e.logger.info(`generated ${String(m)} row(s) across ${String(l.length)} table(s) — dry run, nothing inserted`),{code:0,data:{conflicts:0,generated:m,inserted:0,rows:o?h.map(g=>JSON.parse(g)):void 0,tables:l.length},ndjson:c};if(m===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 _(e,m);return b!==void 0?b:z(c,m,l.length,r,e)},te=A(async({cwd:e,format:r,logger:o,options:t})=>{const n=await L({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:F({cwd:e,prod:t.prod===!0,url:t.url}),yes:t.yes===!0});return{code:n.code,data:n.data,error:n.error}});export{te as execute,L 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{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-BLnoq_oC.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=await $({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,3 +1,3 @@
1
- import z,{join as m,resolve as I}from"node:path";import{isInteractive as J,promptYesNo as W}from"@lunora/config";import{backupObjectKey as v,isBackupManifestEntry as D,normalizeBackupPrefix as Y,BACKUP_KEY_PREFIX as X,backupManifestKey as Q,isBackupManifestKey as V,backupObjectKeyOfManifest as G}from"@lunora/runtime";import{r as E,t as Z}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{r as A,a as T}from"../packem_shared/admin-url-DJB8P6Jh.mjs";import{d as ee}from"../packem_shared/command-B6vu47iR.mjs";import{EXIT_CODE as u,isRefusal as p,exitCodeForStatus as k}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";import{a as re}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{runExportCommand as te}from"../packem_shared/runExportCommand-DiMCQ-Il.mjs";import{b as ae,l as oe,M as U,u as ne,r as ie}from"../packem_shared/import-DoAUdyfU.mjs";import{readAndLogBody as y}from"./runRpcCommand.mjs";import{randomUUID as j,createHash as se}from"node:crypto";import{existsSync as N,createReadStream as ce,createWriteStream as de}from"node:fs";import{mkdir as ue,rm as b,rename as C,readFile as q,writeFile as le,realpath as _,mkdtemp as x}from"node:fs/promises";import{LunoraError as w}from"@lunora/errors";import{i as R}from"../packem_shared/path-containment-CgxYZggb.mjs";import{tmpdir as O}from"node:os";import{Readable as fe}from"node:stream";import{pipeline as me}from"node:stream/promises";const S="manifest.json",L=async e=>{const t=se("sha256");let r=0;for await(const a of ce(e)){const o=a;r+=o.byteLength,t.update(o)}return{bytes:r,sha256:t.digest("hex")}},P=async e=>{const t=m(e,S);if(!N(t))return[];let r;try{r=JSON.parse(await q(t,"utf8"))}catch(a){const o=a instanceof Error?a.message:String(a);throw new w("INTERNAL",`backup: ${t} exists but is not valid JSON (${o}) — refusing to overwrite it; fix or remove it manually`,{cause:a})}if(!Array.isArray(r))throw new TypeError(`backup: ${t} exists but is not a JSON array — refusing to overwrite it; fix or remove it manually`);return r.filter(a=>D(a))},ge=async(e,t)=>{const r=m(e,`${S}.${j()}.tmp`);try{await le(r,`${JSON.stringify(t,void 0,2)}
2
- `,"utf8"),await C(r,m(e,S))}catch(a){throw await b(r,{force:!0}),a}},he=async(e,t)=>{const r=I(e),a=I(r,t.file),o=()=>{throw new w("INTERNAL",`backup: entry ${t.id} points outside ${r} (${t.file}) — refusing to read it`)};if(R(r,a)||o(),!!N(a))return R(await _(r),await _(a))||o(),a},we=e=>{const t=r=>v("",r);return{commit:async(r,a)=>{await C(a,m(e,r))},label:e,list:async()=>P(e),locate:t,materialize:async(r,a)=>{const o=i=>i===void 0?void 0:{path:i,release:()=>Promise.resolve()};return o(r===void 0?N(a)?a:void 0:await he(e,r))},record:async r=>{const a=await P(e);a.push(r),await ge(e,a)},stage:async r=>{await ue(e,{recursive:!0});const a=m(e,`${t(r)}.${j()}.partial`);return{path:a,release:()=>b(a,{force:!0})}}}},be="/_lunora/admin/storage/object",ke="/_lunora/admin/storage",B=8,ye=(e,t=z)=>{const r=t.basename(e);return r===""||r==="."||r===".."?"snapshot.ndjson":r},pe=e=>{const{context:t,logger:r}=e,a=Y(e.prefix??X),o=`bucket ${t.bucket??"(default)"} under ${a}`,i=ae(t),n=c=>`${t.baseUrl}${be}?key=${encodeURIComponent(c)}${i}`,f=async c=>{const s=await t.fetchImpl(n(c),{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(!s.ok){const l=await s.text().catch(()=>"<no body>");throw new w("INTERNAL",`backup: could not read ${c} (HTTP ${String(s.status)}): ${l}`)}return s.text()},H=async c=>{try{const s=JSON.parse(await f(c));if(D(s))return s;r.warn(`backup: ignoring ${c} — not a backup manifest`)}catch(s){r.warn(`backup: ignoring ${c} — ${s instanceof Error?s.message:String(s)}`)}};return{commit:async(c,s,l)=>{if(l.bytes>U)throw new w("INTERNAL",`backup: the snapshot is ${String(l.bytes)} bytes, above the ${String(U)}-byte limit for a checksum-verified upload — nothing was written. Narrow it with \`--tables\`, or write it to a directory with \`--dir\` and move the file yourself (\`wrangler r2 object put\`).`);const d=await q(s);await ne(t,c,d,{contentType:"application/x-ndjson",id:c,sha256:l.sha256,size:l.bytes},r)},label:o,list:async()=>{const s=(await oe(t,a)).map(d=>d.key).filter(d=>V(d)),l=[];for(let d=0;d<s.length;d+=B){const g=await Promise.all(s.slice(d,d+B).map(async h=>H(h)));l.push(...g.filter(h=>h!==void 0))}return l.toSorted((d,g)=>d.id.localeCompare(g.id))},locate:c=>v(a,c),materialize:async(c,s)=>{const l=c?.file??s,d=await t.fetchImpl(n(l),{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(d.status===404)return;if(!d.ok||d.body===null){const $=await d.text().catch(()=>"<no body>");throw new w("INTERNAL",`backup: could not download ${l} (HTTP ${String(d.status)}): ${$}`)}const g=await x(m(O(),"lunora-backup-")),h=m(g,ye(l));try{await me(fe.from(d.body),de(h))}catch($){throw await b(g,{force:!0,recursive:!0}),$}return{path:h,release:async()=>b(g,{force:!0,recursive:!0})}},record:async c=>{const s=Q(c.file),l=await t.fetchImpl(`${t.baseUrl}${ke}?key=${encodeURIComponent(s)}${i}`,{body:`${JSON.stringify(c,void 0,2)}
3
- `,headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json"},method:"PUT"});if(!l.ok){const d=await l.text().catch(()=>"<no body>");throw new w("INTERNAL",`backup: snapshot ${c.file} was written but its manifest was not (HTTP ${String(l.status)}): ${d}`)}},stage:async c=>{const s=await x(m(O(),"lunora-backup-"));return{path:m(s,v("",c)),release:async()=>b(s,{force:!0,recursive:!0})}}}},$e=".lunora-backups",F="/_lunora/admin/backup/retention",ve="/_lunora/admin/backup/prune",Se="/_lunora/admin/pitr",Ee="__lunora_admin__:getPitrBookmark",Ae="__lunora_admin__:pitrRestore",Te=async(e,t)=>{const r=(e.now??(()=>new Date))().toISOString(),a=await t.stage(r);try{const o=await te({cwd:e.cwd,fetchImpl:e.fetchImpl,logger:e.logger,out:a.path,prod:e.prod,tables:e.tables,token:e.token,url:e.url});if(o.code!==0)return{code:o.code};const i=t.locate(r),n=await L(a.path);await t.commit(i,a.path,n);const f={bytes:n.bytes,createdAt:r,file:i,id:r,rows:o.rows,sha256:n.sha256,tables:e.tables};return await t.record(f),e.logger.success(`backup created: ${i} (${o.rows.toString()} rows, ${n.bytes.toString()} bytes)`),{code:0,entry:f}}finally{await a.release().catch(o=>{e.logger.warn(`backup: could not clean up staging (${o instanceof Error?o.message:String(o)})`)})}},Ne=async(e,t,r)=>{if(t?.sha256===void 0)return r.error(t===void 0?"--verify needs a recorded checksum, and a snapshot restored by path/key has no manifest entry — restore it by its backup id instead":`--verify: backup ${t.id} carries no recorded checksum — it was taken by a release before checksums existed`),{code:u.USAGE};const a=await L(e);if(a.sha256!==t.sha256)return r.error(`--verify: ${t.file} does not match its recorded checksum (expected ${t.sha256}, got ${a.sha256}) — nothing was imported`),{code:1};r.success(`verified ${t.file} against its recorded sha256`)},Ie=async(e,t)=>{const r=await t.list();if(r.length===0)return e.logger.info(`no backups found in ${t.label}`),{code:0,entries:[]};for(const a of r)e.logger.info(`${a.id} ${a.rows.toString()} rows ${a.bytes.toString()} bytes ${a.file}`);return{code:0,entries:r}},Ue=async(e,t)=>{const{target:r}=e;if(r===void 0||r.length===0)return e.logger.error("restore requires a backup id or file path. Usage: lunora backup restore <id|file>"),{code:u.USAGE};const o=(await t.list()).find(n=>n.id===r),i=await t.materialize(o,r);if(i===void 0)return e.logger.error(`backup not found: ${r}`),{code:u.NOT_FOUND};try{if(e.verify===!0){const f=await Ne(i.path,o,e.logger);if(f!==void 0)return f}const n=await ie({cwd:e.cwd,fetchImpl:e.fetchImpl,file:i.path,logger:e.logger,prod:e.prod,replace:e.replace,token:e.token,url:e.url,yes:e.yes});return{code:n.code,entry:o,restored:n.inserted+(n.replaced??0)}}finally{await i.release().catch(n=>{e.logger.warn(`backup: could not clean up the downloaded snapshot (${n instanceof Error?n.message:String(n)})`)})}},_e=e=>{if(e.prod&&e.url===void 0)return e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)"),{refused:u.USAGE};if(e.restore===!0&&e.at===void 0&&e.bookmark===void 0)return e.logger.error("pitr --restore requires --at <time> or --bookmark <bookmark>"),{refused:u.USAGE};const t=A(e.url,e.logger,e.cwd);if(t===void 0)return{refused:u.USAGE};if(e.restore===!0&&Z({prod:e.prod,url:t})&&e.yes!==!0)return e.logger.error(`pitr --restore restores data in place at ${t}, which is not local. Re-run with --yes to confirm.`),{refused:u.USAGE};const{token:r}=E({cwd:e.cwd??process.cwd(),token:e.token,url:t});return r?{fetchImpl:e.adminFetch??T,requestUrl:`${t}${Se}`,token:r}:(e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{refused:u.AUTH})},xe=(e,t)=>{const r={};return e.at!==void 0&&(r.time=e.at),t&&e.bookmark!==void 0&&(r.bookmark=e.bookmark),t&&e.restart===!0&&(r.restart=!0),r},Re=async e=>{const t=_e(e);if(p(t))return{code:t.refused};const r=e.restore===!0,a=r?Ae:Ee,o=xe(e,r),i=r?"restore":"bookmark";e.logger.info(`POST ${t.requestUrl} -> pitr ${i}${e.shard===void 0?"":` (shard "${e.shard}")`}`);const n=await t.fetchImpl(t.requestUrl,{body:JSON.stringify({args:o,functionPath:a,shardKey:e.shard}),headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json"},method:"POST"});return{body:await y(n,e.logger),code:n.ok?0:k(n.status)}},Oe=(e,t)=>{if(e.bucket===void 0)return e.prefix!==void 0?(e.logger.error("--prefix applies only to an R2 destination — pass --bucket alongside it, or use --dir to point at a local directory."),{refused:u.USAGE}):we(m(t,e.dir??$e));if(e.dir!==void 0)return e.logger.error("--dir applies only to a local destination and does not apply alongside --bucket — drop one."),{refused:u.USAGE};if(e.prod===!0&&e.url===void 0)return e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)"),{refused:u.USAGE};const r=A(e.url,e.logger,e.cwd);if(r===void 0)return{refused:u.USAGE};const{token:a}=E({cwd:t,token:e.token,url:r});if(!a)return e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{refused:u.AUTH};const o=e.fetchImpl??T;return pe({context:{baseUrl:r,bucket:e.bucket==="default"?void 0:e.bucket,fetchImpl:o,token:a},logger:e.logger,prefix:e.prefix})},M=e=>{const t=[e.bucket===void 0?void 0:"--bucket",e.prefix===void 0?void 0:"--prefix",e.dir===void 0?void 0:"--dir"].filter(i=>i!==void 0);if(t.length>0)return e.logger.error(`${t.join(" / ")} ${t.length===1?"does":"do"} not apply here — retention and prune act on the store the worker itself is configured with (\`backupStore\`), not a destination you name.`),{refused:u.USAGE};if(e.prod===!0&&e.url===void 0)return e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)"),{refused:u.USAGE};const r=A(e.url,e.logger,e.cwd);if(r===void 0)return{refused:u.USAGE};const{token:a}=E({cwd:e.cwd??process.cwd(),token:e.token,url:r});if(!a)return e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{refused:u.AUTH};const o=e.adminFetch??T;return{baseUrl:r,fetchImpl:o,token:a}},K=(e,t)=>{e.logger.info(`backup retention would keep the newest ${t.keep.toString()} of ${t.eligible.toString()} under ${t.prefix} and delete ${t.wouldDelete.length.toString()}`);for(const r of t.wouldDelete)e.logger.info(` ${G(r)}`)},Pe=async e=>{const t=M(e);if(p(t))return{code:t.refused};const r=await t.fetchImpl(`${t.baseUrl}${F}`,{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(!r.ok)return await y(r,e.logger),{code:k(r.status)};const a=await r.json();return a.cron===void 0?(e.logger.info("no scheduled backup is configured (`backupCron`), so retention would delete nothing"),{code:0,preview:a}):a.keep<=0?(e.logger.info(`retention is off for cron "${a.cron}" (\`backupRetain\` unset) — every snapshot under ${a.prefix} is kept`),{code:0,preview:a}):(K(e,a),a.eligible===0&&e.logger.info(`no snapshot under ${a.prefix} was written by this cron, so retention has nothing of its own to remove`),{code:0,preview:a})},Be=(e,t)=>{e.logger.success(`deleted ${t.deleted.length.toString()} backup(s)`);for(const r of t.deleted)e.logger.info(` ${G(r)}`);t.failed.length>0&&e.logger.warn(`${t.failed.length.toString()} could not be removed — the snapshot may be gone with its manifest left behind; run again to retry`),t.ignored>0&&e.logger.info(`${t.ignored.toString()} were already gone by the time the delete ran`),t.remaining>0&&e.logger.info(`${t.remaining.toString()} more are past the window — run \`lunora backup prune\` again`)},De=async e=>{const t=M(e);if(p(t))return{code:t.refused};const r=await t.fetchImpl(`${t.baseUrl}${F}`,{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(!r.ok)return await y(r,e.logger),{code:k(r.status)};const a=await r.json();if(a.keep<=0||a.cron===void 0)return e.logger.error("backup prune needs a retention window: set `backupRetain` (and `backupCron`) on the worker. Without one there is nothing past the window to remove."),{code:u.USAGE,preview:a};if(a.wouldDelete.length===0)return e.logger.info(`nothing to prune — ${a.eligible.toString()} snapshot(s) under ${a.prefix} and retention keeps the newest ${a.keep.toString()}`),{code:0,preview:a};if(K(e,a),e.yes!==!0){const n=e.confirm??(J()?W:void 0);if(n===void 0)return e.logger.error("refusing to delete backups without confirmation — re-run with --yes (there is no undo for an object-store delete)"),{code:u.USAGE,preview:a};if(!await n(`delete ${a.wouldDelete.length.toString()} backup(s)? This cannot be undone. [y/N] `))return e.logger.info("nothing was deleted"),{code:0,preview:a}}const o=await t.fetchImpl(`${t.baseUrl}${ve}`,{body:JSON.stringify({confirm:a.wouldDelete}),headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json"},method:"POST"});if(!o.ok)return await y(o,e.logger),{code:k(o.status),preview:a};const i=await o.json();return Be(e,i),{code:i.failed.length>0?1:0,deleted:i.deleted,preview:a}},Ge=async(e,t)=>{try{if(e.subcommand==="pitr")return await Re(e);if(e.subcommand==="retention")return await Pe(e);if(e.subcommand==="prune")return await De(e);const r=Oe(e,t);return p(r)?{code:r.refused}:e.subcommand==="create"?await Te(e,r):e.subcommand==="list"?await Ie(e,r):await Ue(e,r)}catch(r){return e.logger.error(r instanceof Error?r.message:String(r)),{code:1}}},je=async e=>{const t=e.cwd??process.cwd(),r=await Ge(e,t);return{...r,data:{subcommand:e.subcommand,...r.entries===void 0?{}:{entries:r.entries},...r.entry===void 0?{}:{entry:r.entry},...r.restored===void 0?{}:{restored:r.restored},...r.preview===void 0?{}:{preview:r.preview},...r.deleted===void 0?{}:{deleted:r.deleted},...r.body===void 0?{}:{result:r.body}}}},Ce=e=>e==="create"||e==="list"||e==="pitr"||e==="prune"||e==="restore"||e==="retention",nr=ee(async({argument:e,cwd:t,format:r,logger:a,options:o})=>{const i=e[0];if(!Ce(i)){const f=`backup: unknown subcommand "${i??""}" — expected create | list | restore | retention | prune | pitr`;return a.error(f),{code:u.USAGE,error:f}}const n=await je({at:o.at,bookmark:o.bookmark,bucket:o.bucket,cwd:t,dir:o.dir,format:r,logger:a,prefix:o.prefix,prod:o.prod===!0,replace:o.replace===!0,restart:o.restart===!0,restore:o.restore===!0,shard:o.shard,subcommand:i,tables:o.tables,target:e[1],token:o.token,url:re({cwd:t,prod:o.prod===!0,url:o.url}),verify:o.verify===!0,yes:o.yes===!0});return{code:n.code,data:n.data,error:n.error}});export{nr as execute,je as runBackupCommand};
1
+ import z,{join as m,resolve as U}from"node:path";import{isInteractive as J,promptYesNo as W}from"@lunora/config";import{backupObjectKey as S,isBackupManifestEntry as G,normalizeBackupPrefix as Y,BACKUP_KEY_PREFIX as X,backupManifestKey as Q,isBackupManifestKey as V,backupObjectKeyOfManifest as j}from"@lunora/runtime";import{r as A,t as Z}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{r as T,a as I}from"../packem_shared/admin-url-DJB8P6Jh.mjs";import{d as ee}from"../packem_shared/command-B6vu47iR.mjs";import{EXIT_CODE as u,isRefusal as $,exitCodeForStatus as y}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";import{a as re}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{runExportCommand as te}from"../packem_shared/runExportCommand-Dy6pSX68.mjs";import{b as ae,l as oe,M as _,u as ne,p as ie,a as se,r as ce}from"../packem_shared/import-C-XRRHrZ.mjs";import{readAndLogBody as p}from"./runRpcCommand.mjs";import{randomUUID as q,createHash as de}from"node:crypto";import{existsSync as N,createReadStream as ue,createWriteStream as le}from"node:fs";import{mkdir as fe,rm as k,rename as M,readFile as C,writeFile as me,realpath as R,mkdtemp as x}from"node:fs/promises";import{LunoraError as b}from"@lunora/errors";import{i as O}from"../packem_shared/path-containment-CgxYZggb.mjs";import{tmpdir as P}from"node:os";import{Readable as ge}from"node:stream";import{pipeline as he}from"node:stream/promises";const E="manifest.json",L=async e=>{const t=de("sha256");let r=0;for await(const a of ue(e)){const o=a;r+=o.byteLength,t.update(o)}return{bytes:r,sha256:t.digest("hex")}},B=async e=>{const t=m(e,E);if(!N(t))return[];let r;try{r=JSON.parse(await C(t,"utf8"))}catch(a){const o=a instanceof Error?a.message:String(a);throw new b("INTERNAL",`backup: ${t} exists but is not valid JSON (${o}) — refusing to overwrite it; fix or remove it manually`,{cause:a})}if(!Array.isArray(r))throw new TypeError(`backup: ${t} exists but is not a JSON array — refusing to overwrite it; fix or remove it manually`);return r.filter(a=>G(a))},we=async(e,t)=>{const r=m(e,`${E}.${q()}.tmp`);try{await me(r,`${JSON.stringify(t,void 0,2)}
2
+ `,"utf8"),await M(r,m(e,E))}catch(a){throw await k(r,{force:!0}),a}},be=async(e,t)=>{const r=U(e),a=U(r,t.file),o=()=>{throw new b("INTERNAL",`backup: entry ${t.id} points outside ${r} (${t.file}) — refusing to read it`)};if(O(r,a)||o(),!!N(a))return O(await R(r),await R(a))||o(),a},ke=e=>{const t=r=>S("",r);return{commit:async(r,a)=>{await M(a,m(e,r))},label:e,list:async()=>B(e),locate:t,materialize:async(r,a)=>{const o=i=>i===void 0?void 0:{path:i,release:()=>Promise.resolve()};return o(r===void 0?N(a)?a:void 0:await be(e,r))},record:async r=>{const a=await B(e);a.push(r),await we(e,a)},stage:async r=>{await fe(e,{recursive:!0});const a=m(e,`${t(r)}.${q()}.partial`);return{path:a,release:()=>k(a,{force:!0})}}}},ye="/_lunora/admin/storage/object",pe="/_lunora/admin/storage",D=8,$e=(e,t=z)=>{const r=t.basename(e);return r===""||r==="."||r===".."?"snapshot.ndjson":r},ve=e=>{const{context:t,logger:r}=e,a=Y(e.prefix??X),o=`bucket ${t.bucket??"(default)"} under ${a}`,i=ae(t),n=c=>`${t.baseUrl}${ye}?key=${encodeURIComponent(c)}${i}`,f=async c=>{const s=await t.fetchImpl(n(c),{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(!s.ok){const l=await s.text().catch(()=>"<no body>");throw new b("INTERNAL",`backup: could not read ${c} (HTTP ${String(s.status)}): ${l}`)}return s.text()},g=async c=>{try{const s=JSON.parse(await f(c));if(G(s))return s;r.warn(`backup: ignoring ${c} — not a backup manifest`)}catch(s){r.warn(`backup: ignoring ${c} — ${s instanceof Error?s.message:String(s)}`)}};return{commit:async(c,s,l)=>{if(l.bytes>_)throw new b("INTERNAL",`backup: the snapshot is ${String(l.bytes)} bytes, above the ${String(_)}-byte limit for a checksum-verified upload — nothing was written. Narrow it with \`--tables\`, or write it to a directory with \`--dir\` and move the file yourself (\`wrangler r2 object put\`).`);const d=await C(s);await ne(t,c,d,{contentType:"application/x-ndjson",id:c,sha256:l.sha256,size:l.bytes},r)},label:o,list:async()=>{const s=(await oe(t,a)).map(d=>d.key).filter(d=>V(d)),l=[];for(let d=0;d<s.length;d+=D){const h=await Promise.all(s.slice(d,d+D).map(async w=>g(w)));l.push(...h.filter(w=>w!==void 0))}return l.toSorted((d,h)=>d.id.localeCompare(h.id))},locate:c=>S(a,c),materialize:async(c,s)=>{const l=c?.file??s,d=await t.fetchImpl(n(l),{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(d.status===404)return;if(!d.ok||d.body===null){const v=await d.text().catch(()=>"<no body>");throw new b("INTERNAL",`backup: could not download ${l} (HTTP ${String(d.status)}): ${v}`)}const h=await x(m(P(),"lunora-backup-")),w=m(h,$e(l));try{await he(ge.from(d.body),le(w))}catch(v){throw await k(h,{force:!0,recursive:!0}),v}return{path:w,release:async()=>k(h,{force:!0,recursive:!0})}},record:async c=>{const s=Q(c.file),l=await t.fetchImpl(`${t.baseUrl}${pe}?key=${encodeURIComponent(s)}${i}`,{body:`${JSON.stringify(c,void 0,2)}
3
+ `,headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json"},method:"PUT"});if(!l.ok){const d=await l.text().catch(()=>"<no body>");throw new b("INTERNAL",`backup: snapshot ${c.file} was written but its manifest was not (HTTP ${String(l.status)}): ${d}`)}},stage:async c=>{const s=await x(m(P(),"lunora-backup-"));return{path:m(s,S("",c)),release:async()=>k(s,{force:!0,recursive:!0})}}}},Se=".lunora-backups",F="/_lunora/admin/backup/retention",Ee="/_lunora/admin/backup/prune",Ae="/_lunora/admin/pitr",Te="__lunora_admin__:getPitrBookmark",Ie="__lunora_admin__:pitrRestore",Ne=async(e,t)=>{const r=(e.now??(()=>new Date))().toISOString(),a=await t.stage(r);try{const o=await te({cwd:e.cwd,fetchImpl:e.fetchImpl,logger:e.logger,out:a.path,prod:e.prod,tables:e.tables,token:e.token,url:e.url});if(o.code!==0)return{code:o.code};const i=t.locate(r),n=await L(a.path);await t.commit(i,a.path,n);const f={bytes:n.bytes,createdAt:r,file:i,id:r,rows:o.rows,sha256:n.sha256,tables:e.tables};return await t.record(f),e.logger.success(`backup created: ${i} (${o.rows.toString()} rows, ${n.bytes.toString()} bytes)`),{code:0,entry:f}}finally{await a.release().catch(o=>{e.logger.warn(`backup: could not clean up staging (${o instanceof Error?o.message:String(o)})`)})}},Ue=async(e,t,r)=>{if(t?.sha256===void 0)return r.error(t===void 0?"--verify needs a recorded checksum, and a snapshot restored by path/key has no manifest entry — restore it by its backup id instead":`--verify: backup ${t.id} carries no recorded checksum — it was taken by a release before checksums existed`),{code:u.USAGE};const a=await L(e);if(a.sha256!==t.sha256)return r.error(`--verify: ${t.file} does not match its recorded checksum (expected ${t.sha256}, got ${a.sha256}) — nothing was imported`),{code:1};r.success(`verified ${t.file} against its recorded sha256`)},_e=async(e,t)=>{const r=await t.list();if(r.length===0)return e.logger.info(`no backups found in ${t.label}`),{code:0,entries:[]};for(const a of r)e.logger.info(`${a.id} ${a.rows.toString()} rows ${a.bytes.toString()} bytes ${a.file}`);return{code:0,entries:r}},Re=async(e,t)=>{const{target:r}=e;if(r===void 0||r.length===0)return e.logger.error("restore requires a backup id or file path. Usage: lunora backup restore <id|file>"),{code:u.USAGE};const o=(await t.list()).find(n=>n.id===r),i=await t.materialize(o,r);if(i===void 0)return e.logger.error(`backup not found: ${r}`),{code:u.NOT_FOUND};try{if(e.verify===!0){const f=await Ue(i.path,o,e.logger);if(f!==void 0)return f}const n=await ce({cwd:e.cwd,fetchImpl:e.fetchImpl,file:i.path,format:e.format,logger:e.logger,dryRun:e.dryRun,mode:e.mode??"require-empty",prod:e.prod,token:e.token,url:e.url,yes:e.yes});return{code:n.code,entry:o,...n.body?.plan===void 0?{}:{plan:n.body.plan},restored:n.inserted+(n.replaced??0)}}finally{await i.release().catch(n=>{e.logger.warn(`backup: could not clean up the downloaded snapshot (${n instanceof Error?n.message:String(n)})`)})}},xe=e=>{if(e.prod&&e.url===void 0)return e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)"),{refused:u.USAGE};if(e.restore===!0&&e.at===void 0&&e.bookmark===void 0)return e.logger.error("pitr --restore requires --at <time> or --bookmark <bookmark>"),{refused:u.USAGE};const t=T(e.url,e.logger,e.cwd);if(t===void 0)return{refused:u.USAGE};if(e.restore===!0&&Z({prod:e.prod,url:t})&&e.yes!==!0)return e.logger.error(`pitr --restore restores data in place at ${t}, which is not local. Re-run with --yes to confirm.`),{refused:u.USAGE};const{token:r}=A({cwd:e.cwd??process.cwd(),token:e.token,url:t});return r?{fetchImpl:e.adminFetch??I,requestUrl:`${t}${Ae}`,token:r}:(e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{refused:u.AUTH})},Oe=(e,t)=>{const r={};return e.at!==void 0&&(r.time=e.at),t&&e.bookmark!==void 0&&(r.bookmark=e.bookmark),t&&e.restart===!0&&(r.restart=!0),r},Pe=async e=>{const t=xe(e);if($(t))return{code:t.refused};const r=e.restore===!0,a=r?Ie:Te,o=Oe(e,r),i=r?"restore":"bookmark";e.logger.info(`POST ${t.requestUrl} -> pitr ${i}${e.shard===void 0?"":` (shard "${e.shard}")`}`);const n=await t.fetchImpl(t.requestUrl,{body:JSON.stringify({args:o,functionPath:a,shardKey:e.shard}),headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json"},method:"POST"});return{body:await p(n,e.logger),code:n.ok?0:y(n.status)}},Be=(e,t)=>{if(e.bucket===void 0)return e.prefix!==void 0?(e.logger.error("--prefix applies only to an R2 destination — pass --bucket alongside it, or use --dir to point at a local directory."),{refused:u.USAGE}):ke(m(t,e.dir??Se));if(e.dir!==void 0)return e.logger.error("--dir applies only to a local destination and does not apply alongside --bucket — drop one."),{refused:u.USAGE};if(e.prod===!0&&e.url===void 0)return e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)"),{refused:u.USAGE};const r=T(e.url,e.logger,e.cwd);if(r===void 0)return{refused:u.USAGE};const{token:a}=A({cwd:t,token:e.token,url:r});if(!a)return e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{refused:u.AUTH};const o=e.fetchImpl??I;return ve({context:{baseUrl:r,bucket:e.bucket==="default"?void 0:e.bucket,fetchImpl:o,token:a},logger:e.logger,prefix:e.prefix})},K=e=>{const t=[e.bucket===void 0?void 0:"--bucket",e.prefix===void 0?void 0:"--prefix",e.dir===void 0?void 0:"--dir"].filter(i=>i!==void 0);if(t.length>0)return e.logger.error(`${t.join(" / ")} ${t.length===1?"does":"do"} not apply here — retention and prune act on the store the worker itself is configured with (\`backupStore\`), not a destination you name.`),{refused:u.USAGE};if(e.prod===!0&&e.url===void 0)return e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)"),{refused:u.USAGE};const r=T(e.url,e.logger,e.cwd);if(r===void 0)return{refused:u.USAGE};const{token:a}=A({cwd:e.cwd??process.cwd(),token:e.token,url:r});if(!a)return e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{refused:u.AUTH};const o=e.adminFetch??I;return{baseUrl:r,fetchImpl:o,token:a}},H=(e,t)=>{e.logger.info(`backup retention would keep the newest ${t.keep.toString()} of ${t.eligible.toString()} under ${t.prefix} and delete ${t.wouldDelete.length.toString()}`);for(const r of t.wouldDelete)e.logger.info(` ${j(r)}`)},De=async e=>{const t=K(e);if($(t))return{code:t.refused};const r=await t.fetchImpl(`${t.baseUrl}${F}`,{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(!r.ok)return await p(r,e.logger),{code:y(r.status)};const a=await r.json();return a.cron===void 0?(e.logger.info("no scheduled backup is configured (`backupCron`), so retention would delete nothing"),{code:0,preview:a}):a.keep<=0?(e.logger.info(`retention is off for cron "${a.cron}" (\`backupRetain\` unset) — every snapshot under ${a.prefix} is kept`),{code:0,preview:a}):(H(e,a),a.eligible===0&&e.logger.info(`no snapshot under ${a.prefix} was written by this cron, so retention has nothing of its own to remove`),{code:0,preview:a})},Ge=(e,t)=>{e.logger.success(`deleted ${t.deleted.length.toString()} backup(s)`);for(const r of t.deleted)e.logger.info(` ${j(r)}`);t.failed.length>0&&e.logger.warn(`${t.failed.length.toString()} could not be removed — the snapshot may be gone with its manifest left behind; run again to retry`),t.ignored>0&&e.logger.info(`${t.ignored.toString()} were already gone by the time the delete ran`),t.remaining>0&&e.logger.info(`${t.remaining.toString()} more are past the window — run \`lunora backup prune\` again`)},je=async e=>{const t=K(e);if($(t))return{code:t.refused};const r=await t.fetchImpl(`${t.baseUrl}${F}`,{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(!r.ok)return await p(r,e.logger),{code:y(r.status)};const a=await r.json();if(a.keep<=0||a.cron===void 0)return e.logger.error("backup prune needs a retention window: set `backupRetain` (and `backupCron`) on the worker. Without one there is nothing past the window to remove."),{code:u.USAGE,preview:a};if(a.wouldDelete.length===0)return e.logger.info(`nothing to prune — ${a.eligible.toString()} snapshot(s) under ${a.prefix} and retention keeps the newest ${a.keep.toString()}`),{code:0,preview:a};if(H(e,a),e.yes!==!0){const n=e.confirm??(J()?W:void 0);if(n===void 0)return e.logger.error("refusing to delete backups without confirmation — re-run with --yes (there is no undo for an object-store delete)"),{code:u.USAGE,preview:a};if(!await n(`delete ${a.wouldDelete.length.toString()} backup(s)? This cannot be undone. [y/N] `))return e.logger.info("nothing was deleted"),{code:0,preview:a}}const o=await t.fetchImpl(`${t.baseUrl}${Ee}`,{body:JSON.stringify({confirm:a.wouldDelete}),headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json"},method:"POST"});if(!o.ok)return await p(o,e.logger),{code:y(o.status),preview:a};const i=await o.json();return Ge(e,i),{code:i.failed.length>0?1:0,deleted:i.deleted,preview:a}},qe=async(e,t)=>{try{if(e.subcommand==="pitr")return await Pe(e);if(e.subcommand==="retention")return await De(e);if(e.subcommand==="prune")return await je(e);const r=Be(e,t);return $(r)?{code:r.refused}:e.subcommand==="create"?await Ne(e,r):e.subcommand==="list"?await _e(e,r):await Re(e,r)}catch(r){return e.logger.error(r instanceof Error?r.message:String(r)),{code:1}}},Me=async e=>{const t=e.cwd??process.cwd(),r=await qe(e,t);return{...r,data:{subcommand:e.subcommand,...r.entries===void 0?{}:{entries:r.entries},...r.entry===void 0?{}:{entry:r.entry},...r.plan===void 0?{}:{plan:r.plan},...r.restored===void 0?{}:{restored:r.restored},...r.preview===void 0?{}:{preview:r.preview},...r.deleted===void 0?{}:{deleted:r.deleted},...r.body===void 0?{}:{result:r.body}}}},Ce=e=>e==="create"||e==="list"||e==="pitr"||e==="prune"||e==="restore"||e==="retention",sr=ee(async({argument:e,cwd:t,format:r,logger:a,options:o})=>{const i=e[0];if(!Ce(i)){const g=`backup: unknown subcommand "${i??""}" — expected create | list | restore | retention | prune | pitr`;return a.error(g),{code:u.USAGE,error:g}}const n=ie(o.mode,"require-empty");if(n===void 0){const g=`--mode ${String(o.mode)} is not a known mode. Expected one of: ${se.join(", ")}.`;return a.error(g),{code:u.USAGE,error:g}}const f=await Me({at:o.at,bookmark:o.bookmark,bucket:o.bucket,cwd:t,dir:o.dir,format:r,logger:a,prefix:o.prefix,dryRun:o.dryRun===!0,mode:n,prod:o.prod===!0,restart:o.restart===!0,restore:o.restore===!0,shard:o.shard,subcommand:i,tables:o.tables,target:e[1],token:o.token,url:re({cwd:t,prod:o.prod===!0,url:o.url}),verify:o.verify===!0,yes:o.yes===!0});return{code:f.code,data:f.data,error:f.error}});export{sr as execute,Me as runBackupCommand};
@@ -1 +1 @@
1
- import{d}from"../packem_shared/command-B6vu47iR.mjs";import{a as l}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{runExportCommand as m}from"../packem_shared/runExportCommand-DiMCQ-Il.mjs";const k=d(({argument:o,cwd:e,format:t,logger:u,options:r})=>m({cwd:e,format:t,logger:u,out:o[0]??r.out,prod:r.prod===!0,tables:r.tables,token:r.token,url:l({cwd:e,prod:r.prod===!0,url:r.url})}));export{k as execute};
1
+ import{d}from"../packem_shared/command-B6vu47iR.mjs";import{a as l}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{runExportCommand as m}from"../packem_shared/runExportCommand-Dy6pSX68.mjs";const k=d(({argument:o,cwd:e,format:t,logger:u,options:r})=>m({cwd:e,format:t,logger:u,out:o[0]??r.out,prod:r.prod===!0,tables:r.tables,token:r.token,url:l({cwd:e,prod:r.prod===!0,url:r.url})}));export{k as execute};
@@ -1 +1 @@
1
- import{d}from"../packem_shared/command-B6vu47iR.mjs";import{EXIT_CODE as m}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";import{a as l}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{I as u,r as n}from"../packem_shared/import-DoAUdyfU.mjs";const b=d(({argument:f,cwd:t,format:c,logger:a,options:r})=>{const o=f[0];if(!o){const e="import requires a path. Usage: lunora import <file.ndjson | convex-export-dir> [--table <name>]";return a.error(e),{code:m.USAGE,error:e}}if(r.from!==void 0&&!u.includes(r.from)){const e=`--from ${r.from} is not a known source. Expected one of: ${u.join(", ")}.`;return a.error(e),{code:m.USAGE,error:e}}return n({batchSize:r.batchSize,cwd:t,file:o,format:c,from:r.from,logger:a,prod:r.prod===!0,replace:r.replace===!0,scan:r.scan===!0,storageDir:r.storageDir,table:r.table,token:r.token,url:l({cwd:t,prod:r.prod===!0,url:r.url}),verify:r.verify===!0,withStorage:r.withStorage===!0,yes:r.yes===!0})});export{b as execute};
1
+ import{d as c}from"../packem_shared/command-B6vu47iR.mjs";import{EXIT_CODE as t}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";import{a as i}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{I as u,p as S,a as l,r as s}from"../packem_shared/import-C-XRRHrZ.mjs";const I=c(({argument:n,cwd:a,format:f,logger:o,options:r})=>{const d=n[0];if(!d){const e="import requires a path. Usage: lunora import <file.ndjson | convex-export-dir> [--table <name>]";return o.error(e),{code:t.USAGE,error:e}}if(r.from!==void 0&&!u.includes(r.from)){const e=`--from ${r.from} is not a known source. Expected one of: ${u.join(", ")}.`;return o.error(e),{code:t.USAGE,error:e}}const m=S(r.mode,"append");if(m===void 0){const e=`--mode ${String(r.mode)} is not a known mode. Expected one of: ${l.join(", ")}.`;return o.error(e),{code:t.USAGE,error:e}}return s({batchSize:r.batchSize,cwd:a,dryRun:r.dryRun===!0,file:d,format:f,from:r.from,logger:o,mode:m,prod:r.prod===!0,scan:r.scan===!0,storageDir:r.storageDir,table:r.table,token:r.token,url:i({cwd:a,prod:r.prod===!0,url:r.url}),verify:r.verify===!0,withStorage:r.withStorage===!0,yes:r.yes===!0})});export{I as execute};