@lunora/cli 1.0.0-alpha.222 → 1.0.0-alpha.224

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.
package/dist/index.d.mts CHANGED
@@ -572,7 +572,8 @@ interface DeployCommandOptions {
572
572
  * live" from "went live" without inferring it from a missing `url`. A dry run
573
573
  * publishes nothing and therefore never carries a `url`.
574
574
  *
575
- * No `versionId`: the pinned wrangler (4.114.0) has no structured deploy output
575
+ * No `versionId`: the pinned wrangler (see the `wrangler` catalog entry in
576
+ * `pnpm-workspace.yaml`) has no structured deploy output
576
577
  * and no flag that returns the version id — it only prints it in prose, and
577
578
  * scraping a second value out of prose is exactly what this shouldn't do. The
578
579
  * id is available from `lunora deployments list` after the fact.
package/dist/index.d.ts CHANGED
@@ -572,7 +572,8 @@ interface DeployCommandOptions {
572
572
  * live" from "went live" without inferring it from a missing `url`. A dry run
573
573
  * publishes nothing and therefore never carries a `url`.
574
574
  *
575
- * No `versionId`: the pinned wrangler (4.114.0) has no structured deploy output
575
+ * No `versionId`: the pinned wrangler (see the `wrangler` catalog entry in
576
+ * `pnpm-workspace.yaml`) has no structured deploy output
576
577
  * and no flag that returns the version id — it only prints it in prose, and
577
578
  * scraping a second value out of prose is exactly what this shouldn't do. The
578
579
  * id is available from `lunora deployments list` after the fact.
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{C as o,V as a,r as n}from"./packem_shared/cli-DOBnG22n.mjs";import{runCodegenCommand as t}from"./packem_chunks/runCodegenCommand.mjs";import{runDeployCommand as p}from"./packem_chunks/runDeployCommand.mjs";import{planDevCommand as x,runDevCommand as i}from"./packem_chunks/planDevCommand.mjs";import{runInitCommand as C}from"./packem_chunks/runInitCommand.mjs";import{runMigrateGenerateCommand as u}from"./packem_chunks/runMigrateGenerateCommand.mjs";import{runResetCommand as g}from"./packem_chunks/runResetCommand.mjs";import{runRpcCommand as R}from"./packem_chunks/runRpcCommand.mjs";import{insertSchemaExtension as E}from"./packem_shared/insertSchemaExtension-DY4pA8wE.mjs";import{createLogger as A,pail as c}from"./packem_shared/createLogger-hGafwf-3.mjs";import{diffSnapshots as v,renderAddColumn as _,renderCreateIndex as b,renderCreateTable as h,renderDropIndex as y,renderDropTable as L,renderMigrationFile as O,validatorKindToSqlType as w}from"./packem_shared/diffSnapshots-DtC5Cs4Z.mjs";import{default as F}from"./packem_shared/schemaIrToSnapshot-VpPguG3W.mjs";import{createRecordingSpawner as U,defaultSpawner as V}from"./packem_shared/createRecordingSpawner-DJlNacZ6.mjs";import{default as G}from"./packem_shared/parseManifest-CwPTKdtS.mjs";import{D as Q,r as j}from"./packem_shared/import-DuHtoh4_.mjs";import{REQUIRED_COMPATIBILITY_DATE as H,REQUIRED_FLAG as K,validateWranglerProject as Y,validateWranglerConfig as Z}from"@lunora/config/cloudflare";import{b as z}from"./packem_shared/catalog-Cbzph90w.mjs";import{r as X,a as $,b as rr}from"./packem_shared/commands-CLLQuHqU.mjs";import{runExportCommand as or}from"./packem_shared/runExportCommand-Dq-SpjAe.mjs";export{o as COMMANDS,Q as DEFAULT_IMPORT_BATCH_SIZE,H as REQUIRED_COMPATIBILITY_DATE,K as REQUIRED_FLAG,a as VERSION,z as buildRegistryIndex,A as createLogger,U as createRecordingSpawner,V as defaultSpawner,v as diffSnapshots,E as insertSchemaExtension,c as pail,G as parseManifest,x as planDevCommand,_ as renderAddColumn,b as renderCreateIndex,h as renderCreateTable,y as renderDropIndex,L as renderDropTable,O as renderMigrationFile,X as runAddCommand,$ as runBuildIndexCommand,n as runCli,t as runCodegenCommand,p as runDeployCommand,i as runDevCommand,or as runExportCommand,j as runImportCommand,C as runInitCommand,u as runMigrateGenerateCommand,rr as runRegistryViewCommand,g as runResetCommand,R as runRpcCommand,F as schemaIrToSnapshot,Y as validateWrangler,Z as validateWranglerConfig,w as validatorKindToSqlType};
1
+ import{C as o,V as a,r as n}from"./packem_shared/cli-DOBnG22n.mjs";import{runCodegenCommand as t}from"./packem_chunks/runCodegenCommand.mjs";import{runDeployCommand as p}from"./packem_chunks/runDeployCommand.mjs";import{planDevCommand as x,runDevCommand as i}from"./packem_chunks/planDevCommand.mjs";import{runInitCommand as C}from"./packem_chunks/runInitCommand.mjs";import{runMigrateGenerateCommand as u}from"./packem_chunks/runMigrateGenerateCommand.mjs";import{runResetCommand as g}from"./packem_chunks/runResetCommand.mjs";import{runRpcCommand as R}from"./packem_chunks/runRpcCommand.mjs";import{insertSchemaExtension as E}from"./packem_shared/insertSchemaExtension-DY4pA8wE.mjs";import{createLogger as A,pail as c}from"./packem_shared/createLogger-hGafwf-3.mjs";import{diffSnapshots as v,renderAddColumn as _,renderCreateIndex as b,renderCreateTable as h,renderDropIndex as y,renderDropTable as L,renderMigrationFile as O,validatorKindToSqlType as w}from"./packem_shared/diffSnapshots-DtC5Cs4Z.mjs";import{default as F}from"./packem_shared/schemaIrToSnapshot-VpPguG3W.mjs";import{createRecordingSpawner as U,defaultSpawner as V}from"./packem_shared/createRecordingSpawner-DJlNacZ6.mjs";import{default as G}from"./packem_shared/parseManifest-CwPTKdtS.mjs";import{D as Q,r as j}from"./packem_shared/import-DuHtoh4_.mjs";import{REQUIRED_COMPATIBILITY_DATE as H,REQUIRED_FLAG as K,validateWranglerProject as Y,validateWranglerConfig as Z}from"@lunora/config/cloudflare";import{b as z}from"./packem_shared/catalog-Cbzph90w.mjs";import{r as X,a as $,b as rr}from"./packem_shared/commands-BadIgWaM.mjs";import{runExportCommand as or}from"./packem_shared/runExportCommand-Dq-SpjAe.mjs";export{o as COMMANDS,Q as DEFAULT_IMPORT_BATCH_SIZE,H as REQUIRED_COMPATIBILITY_DATE,K as REQUIRED_FLAG,a as VERSION,z as buildRegistryIndex,A as createLogger,U as createRecordingSpawner,V as defaultSpawner,v as diffSnapshots,E as insertSchemaExtension,c as pail,G as parseManifest,x as planDevCommand,_ as renderAddColumn,b as renderCreateIndex,h as renderCreateTable,y as renderDropIndex,L as renderDropTable,O as renderMigrationFile,X as runAddCommand,$ as runBuildIndexCommand,n as runCli,t as runCodegenCommand,p as runDeployCommand,i as runDevCommand,or as runExportCommand,j as runImportCommand,C as runInitCommand,u as runMigrateGenerateCommand,rr as runRegistryViewCommand,g as runResetCommand,R as runRpcCommand,F as schemaIrToSnapshot,Y as validateWrangler,Z as validateWranglerConfig,w as validatorKindToSqlType};
@@ -1 +1 @@
1
- import{existsSync as k,readFileSync as T}from"node:fs";import{applyLintIgnores as N,detectLintTools as I}from"@lunora/config";import{findWranglerFile as A}from"@lunora/config/cloudflare";import{join as v,basename as g}from"@visulima/path";import{d as D}from"../packem_shared/command-DwC11Cwe.mjs";import{r as S}from"../packem_shared/lint-ignore-report-DKZagpqk.mjs";import{v as U,l as L,i as M,p as _}from"../packem_shared/output-format-DfogXx0p.mjs";import{t as w,a as F}from"../packem_shared/tui-prompts-Dd0pDuNr.mjs";import{i as O}from"../packem_shared/resolve-BWFT7RvE.mjs";import{n as E,i as P,E as R,s as j,d as l,p,r as f,M as $,a as x,b as h,c as B,D as o,e as z,f as C,g as d,A as H,h as J,w as W,j as q,k as V}from"../packem_shared/storage-DlUnv7uG.mjs";import{r as G}from"../packem_shared/commands-CLLQuHqU.mjs";const K=e=>{const r=e.trim().toLowerCase();return J.find(a=>a.value===r||a.label.toLowerCase()===r||r==="auth0"&&a.value==="auth-auth0"||r==="clerk"&&a.value==="auth-clerk")?.value},y=e=>{try{const r=JSON.parse(T(v(e,"package.json"),"utf8"));return{...r.dependencies,...r.devDependencies}}catch{return{}}},Q=async e=>{const r=e.cwd??process.cwd(),t=C(y(r));return t!==void 0?t:e.yes===!0?(e.logger.warn(`add: couldn't detect your framework — using "${d}". Pass a specific item (e.g. \`lunora add auth-ui-vue\`) to override.`),d):await(e.promptSelect??((s,n,i)=>w(s,n,i)))("Which framework is your app?",H,{default:d})??d},X=async e=>{if(e.provider!==void 0&&e.provider!==""){const t=K(e.provider);return t===void 0?(e.logger.warn(`add: unknown --provider "${e.provider}" — using "${o}" (email & password).`),o):t}if(e.yes===!0)return o;const r=e.promptSelect??((t,a,s)=>w(t,a,s));return z(r)},m=e=>e.promptText??((r,t)=>F(r,t)),Y=async e=>{const r=g(e.cwd??process.cwd());if(e.bucket!==void 0&&e.bucket!==""){const t=j(e.bucket);if(t!==void 0)return t;const a=l(r);return e.logger.warn(`add: "${e.bucket}" isn't a valid R2 bucket name (lowercase alphanumeric + hyphens, 3–63 chars) — using "${a}".`),a}return e.yes===!0?l(r):p(m(e),r)},Z=async e=>{const r=t=>{e.logger.warn(`add: ${t}`)};if(e.mailTo!==void 0&&e.mailTo!=="")return f(e.mailTo,r);if(e.yes!==!0)return f(await m(e)($,{placeholder:"you@yourdomain.com"}),r)},ee=async e=>{const r=g(e.cwd??process.cwd());if(e.db!==void 0&&e.db!==""){const t=x(e.db);if(t!==void 0)return t;const a=h(r);return e.logger.warn(`add: "${e.db}" isn't a usable D1 database name — using "${a}".`),a}return e.yes===!0?h(r):B(m(e),r)},re=async(e,r)=>e.kind==="auth"?[await X(r)]:e.kind==="auth-ui"?[await Q(r)]:e.kind==="email"?[R]:[e.item],ae=(e,r)=>{S(N(e,I(e)),r)},te=e=>!O(e)||e.yes===!0,se=async e=>{const r=e.cwd??process.cwd(),t=e.feature===void 0?void 0:E(e.feature);if(t===void 0)return e.logger.error("add requires a feature or registry item. Usage: lunora add <auth|email|storage|crons|presence|…>"),{code:1,items:[]};if(!k(v(r,"lunora"))||A(r)===void 0)return e.logger.error("add: not a Lunora project here (need a lunora/ directory and a wrangler.jsonc). Run `lunora init` first."),{code:1,items:[]};if(t.kind==="auth-ui"&&P(y(r)))return e.logger.error("add: auth-ui has no React Native port — the screens render DOM elements and a stylesheet, which Metro has nothing to mount. Build the screens with React Native primitives against the same better-auth client (`@lunora/react-native/auth`); `lunora add auth` still installs the server half."),{code:1,items:[]};const a=await re(t,e),s=[];if(a.includes("storage")){const c=await Y(e);s.push(u=>W(u,c))}if(a.includes("mail")){const c=await Z(e);c!==void 0&&s.push(u=>q(u,c))}if(a.some(c=>c==="auth"||c.startsWith("auth-"))){const c=await ee(e);s.push(u=>V(u,c))}const n=s.length>0?c=>{let u=c;for(const b of s)u=b(u);return u}:void 0,i=await G({allowUnsafeSource:e.allowUnsafeSource,confirm:e.confirm,cwd:r,from:e.from,logger:e.logger,names:[...a],ref:e.ref,source:e.source,transformManifest:n,yes:te(e)});return i.code===0&&ae(r,e.logger),{code:i.code,items:a}},ge=D(async({argument:e,cwd:r,logger:t,options:a})=>{const s=U("add",a.format);if(s!==void 0)return t.error(s),{code:1};const n=L(a.format,t),i=await se({allowUnsafeSource:a.allowUnsafeSource===!0,bucket:a.bucket,cwd:r,db:a.db,feature:e[0],from:a.from,logger:n,mailTo:a.mailTo,provider:a.provider,ref:a.ref,source:a.source,yes:a.yes===!0});return M(a.format)&&_({code:i.code,items:i.items}),{code:i.code}});export{ge as execute,se as runAddFeature};
1
+ import{existsSync as k,readFileSync as T}from"node:fs";import{applyLintIgnores as N,detectLintTools as I}from"@lunora/config";import{findWranglerFile as A}from"@lunora/config/cloudflare";import{join as v,basename as g}from"@visulima/path";import{d as D}from"../packem_shared/command-DwC11Cwe.mjs";import{r as S}from"../packem_shared/lint-ignore-report-DKZagpqk.mjs";import{v as U,l as L,i as M,p as _}from"../packem_shared/output-format-DfogXx0p.mjs";import{t as w,a as F}from"../packem_shared/tui-prompts-DzYd2fL3.mjs";import{i as O}from"../packem_shared/resolve-B9ReA3FV.mjs";import{n as E,i as P,E as R,s as j,d as l,p,r as f,M as $,a as x,b as h,c as B,D as o,e as z,f as C,g as d,A as H,h as J,w as W,j as q,k as V}from"../packem_shared/storage-B08EcdWm.mjs";import{r as G}from"../packem_shared/commands-BadIgWaM.mjs";const K=e=>{const r=e.trim().toLowerCase();return J.find(a=>a.value===r||a.label.toLowerCase()===r||r==="auth0"&&a.value==="auth-auth0"||r==="clerk"&&a.value==="auth-clerk")?.value},y=e=>{try{const r=JSON.parse(T(v(e,"package.json"),"utf8"));return{...r.dependencies,...r.devDependencies}}catch{return{}}},Q=async e=>{const r=e.cwd??process.cwd(),t=C(y(r));return t!==void 0?t:e.yes===!0?(e.logger.warn(`add: couldn't detect your framework — using "${d}". Pass a specific item (e.g. \`lunora add auth-ui-vue\`) to override.`),d):await(e.promptSelect??((s,n,i)=>w(s,n,i)))("Which framework is your app?",H,{default:d})??d},X=async e=>{if(e.provider!==void 0&&e.provider!==""){const t=K(e.provider);return t===void 0?(e.logger.warn(`add: unknown --provider "${e.provider}" — using "${o}" (email & password).`),o):t}if(e.yes===!0)return o;const r=e.promptSelect??((t,a,s)=>w(t,a,s));return z(r)},m=e=>e.promptText??((r,t)=>F(r,t)),Y=async e=>{const r=g(e.cwd??process.cwd());if(e.bucket!==void 0&&e.bucket!==""){const t=j(e.bucket);if(t!==void 0)return t;const a=l(r);return e.logger.warn(`add: "${e.bucket}" isn't a valid R2 bucket name (lowercase alphanumeric + hyphens, 3–63 chars) — using "${a}".`),a}return e.yes===!0?l(r):p(m(e),r)},Z=async e=>{const r=t=>{e.logger.warn(`add: ${t}`)};if(e.mailTo!==void 0&&e.mailTo!=="")return f(e.mailTo,r);if(e.yes!==!0)return f(await m(e)($,{placeholder:"you@yourdomain.com"}),r)},ee=async e=>{const r=g(e.cwd??process.cwd());if(e.db!==void 0&&e.db!==""){const t=x(e.db);if(t!==void 0)return t;const a=h(r);return e.logger.warn(`add: "${e.db}" isn't a usable D1 database name — using "${a}".`),a}return e.yes===!0?h(r):B(m(e),r)},re=async(e,r)=>e.kind==="auth"?[await X(r)]:e.kind==="auth-ui"?[await Q(r)]:e.kind==="email"?[R]:[e.item],ae=(e,r)=>{S(N(e,I(e)),r)},te=e=>!O(e)||e.yes===!0,se=async e=>{const r=e.cwd??process.cwd(),t=e.feature===void 0?void 0:E(e.feature);if(t===void 0)return e.logger.error("add requires a feature or registry item. Usage: lunora add <auth|email|storage|crons|presence|…>"),{code:1,items:[]};if(!k(v(r,"lunora"))||A(r)===void 0)return e.logger.error("add: not a Lunora project here (need a lunora/ directory and a wrangler.jsonc). Run `lunora init` first."),{code:1,items:[]};if(t.kind==="auth-ui"&&P(y(r)))return e.logger.error("add: auth-ui has no React Native port — the screens render DOM elements and a stylesheet, which Metro has nothing to mount. Build the screens with React Native primitives against the same better-auth client (`@lunora/react-native/auth`); `lunora add auth` still installs the server half."),{code:1,items:[]};const a=await re(t,e),s=[];if(a.includes("storage")){const c=await Y(e);s.push(u=>W(u,c))}if(a.includes("mail")){const c=await Z(e);c!==void 0&&s.push(u=>q(u,c))}if(a.some(c=>c==="auth"||c.startsWith("auth-"))){const c=await ee(e);s.push(u=>V(u,c))}const n=s.length>0?c=>{let u=c;for(const b of s)u=b(u);return u}:void 0,i=await G({allowUnsafeSource:e.allowUnsafeSource,confirm:e.confirm,cwd:r,from:e.from,logger:e.logger,names:[...a],ref:e.ref,source:e.source,transformManifest:n,yes:te(e)});return i.code===0&&ae(r,e.logger),{code:i.code,items:a}},ge=D(async({argument:e,cwd:r,logger:t,options:a})=>{const s=U("add",a.format);if(s!==void 0)return t.error(s),{code:1};const n=L(a.format,t),i=await se({allowUnsafeSource:a.allowUnsafeSource===!0,bucket:a.bucket,cwd:r,db:a.db,feature:e[0],from:a.from,logger:n,mailTo:a.mailTo,provider:a.provider,ref:a.ref,source:a.source,yes:a.yes===!0});return M(a.format)&&_({code:i.code,items:i.items}),{code:i.code}});export{ge as execute,se as runAddFeature};
@@ -1 +1 @@
1
- import{d as c}from"../packem_shared/command-DwC11Cwe.mjs";import{r as d,b as s,a as n}from"../packem_shared/commands-CLLQuHqU.mjs";const w=c(({argument:a,cwd:u,logger:e,options:r})=>{const f=a[0],m=a.slice(1);return f==="add"?d({allowUnsafeSource:r.allowUnsafeSource===!0,cwd:u,diff:r.diff===!0,dryRun:r.dryRun===!0,from:r.from,json:r.json===!0,logger:e,names:m,overwrite:r.overwrite===!0,ref:r.ref,source:r.source,yes:r.yes===!0}):f==="list"?d({cwd:u,from:r.from,json:r.json===!0,list:!0,logger:e,names:[],ref:r.ref,source:r.source}):f==="view"?s({allowUnsafeSource:r.allowUnsafeSource===!0,cwd:u,from:r.from,logger:e,names:m,ref:r.ref,source:r.source}):f==="build"?n({check:r.check===!0,cwd:u,from:r.from,logger:e,names:[],out:r.out}):(e.error("registry: unknown subcommand. Usage: lunora registry <add|list|view|build> [names…]"),{code:1})});export{w as execute};
1
+ import{d as c}from"../packem_shared/command-DwC11Cwe.mjs";import{r as d,b as s,a as n}from"../packem_shared/commands-BadIgWaM.mjs";const w=c(({argument:a,cwd:u,logger:e,options:r})=>{const f=a[0],m=a.slice(1);return f==="add"?d({allowUnsafeSource:r.allowUnsafeSource===!0,cwd:u,diff:r.diff===!0,dryRun:r.dryRun===!0,from:r.from,json:r.json===!0,logger:e,names:m,overwrite:r.overwrite===!0,ref:r.ref,source:r.source,yes:r.yes===!0}):f==="list"?d({cwd:u,from:r.from,json:r.json===!0,list:!0,logger:e,names:[],ref:r.ref,source:r.source}):f==="view"?s({allowUnsafeSource:r.allowUnsafeSource===!0,cwd:u,from:r.from,logger:e,names:m,ref:r.ref,source:r.source}):f==="build"?n({check:r.check===!0,cwd:u,from:r.from,logger:e,names:[],out:r.out}):(e.error("registry: unknown subcommand. Usage: lunora registry <add|list|view|build> [names…]"),{code:1})});export{w as execute};
@@ -1,3 +1,3 @@
1
- import{existsSync as S}from"node:fs";import{mkdtemp as k,writeFile as v,rm as R}from"node:fs/promises";import{tmpdir as $}from"node:os";import{discoverSchema as j,schemaFromIr as T}from"@lunora/codegen";import{seedPlan as C}from"@lunora/seed";import{join as m}from"@visulima/path";import{Project as F}from"ts-morph";import{t as b}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{d as x}from"../packem_shared/command-DwC11Cwe.mjs";import{r as z}from"../packem_shared/resolve-target-BRvw8Pf7.mjs";import{b as I}from"../packem_shared/tui-prompts-Dd0pDuNr.mjs";import{runResetCommand as A}from"./runResetCommand.mjs";import{r as P}from"../packem_shared/import-DuHtoh4_.mjs";const N=(e,r)=>typeof r=="bigint"?Number(r):r instanceof ArrayBuffer?[...new Uint8Array(r)]:r,l=e=>({code:e,conflicts:0,generated:0,inserted:0,ndjson:""}),U=(e,r)=>{if(!S(r))return e.logger.error(`schema not found: ${r} — run \`vis generate lunora-table --name=<name>\` to create one`),l(1);if(e.reset===!0&&b({prod:e.prod,url:e.url}))return e.logger.error("--reset only clears local .wrangler/state and cannot be combined with --prod or a remote --url"),l(1)},W=async(e,r,t,n)=>{const d=await k(m($(),"lunora-seed-")),i=m(d,"rows.ndjson");await v(i,e,"utf8");try{const o=await P({batchSize:n.batchSize,cwd:t,fetchImpl:n.fetchImpl,file:i,logger:n.logger,prod:n.prod,token:n.token,url:n.url,yes:!0}),s=o.body?.conflicts??0;return s>0&&n.logger.warn(`${String(s)} 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:o.code,conflicts:s,generated:r,inserted:o.inserted,ndjson:e}}finally{await R(d,{force:!0,recursive:!0}).catch(()=>{})}},_=(e,r)=>{if(e.table===void 0||r.tables.some(n=>n.name===e.table))return;const t=r.tables.map(n=>n.name).join(", ");return e.logger.error(`unknown table "${e.table}" — schema defines: ${t||"(no tables)"}`),l(1)},B=async(e,r)=>{if(!b({prod:e.prod,url:e.url})||e.yes===!0)return;if(!process.stdin.isTTY&&e.confirm===void 0)return e.logger.error("seed: refusing to insert into a non-local target without confirmation — re-run with --yes"),l(1);if(!await(e.confirm??I)(`This will insert ${String(r)} generated row(s) into ${e.url??"the production worker"}. Continue?`))return e.logger.info("seed: aborted"),l(1)},D=async e=>{const r=e.cwd??process.cwd(),t=m(r,"lunora","schema.ts"),n=U(e,t);if(n!==void 0)return n;const d=new F({skipAddingFilesFromTsConfig:!0}),i=j(d,t),o=_(e,i);if(o!==void 0)return o;const s=T(i),g=C(s,{defaultCount:e.count??10,now:e.now,only:e.table===void 0?void 0:[e.table],seed:e.seed??0}),u=[];for(const{rows:f,table:h}of g)for(const y of f)u.push(JSON.stringify({doc:y,table:h},N));const c=u.length>0?`${u.join(`
1
+ import{existsSync as S}from"node:fs";import{mkdtemp as k,writeFile as v,rm as R}from"node:fs/promises";import{tmpdir as $}from"node:os";import{discoverSchema as j,schemaFromIr as T}from"@lunora/codegen";import{seedPlan as C}from"@lunora/seed";import{join as m}from"@visulima/path";import{Project as F}from"ts-morph";import{t as b}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{d as x}from"../packem_shared/command-DwC11Cwe.mjs";import{r as z}from"../packem_shared/resolve-target-BRvw8Pf7.mjs";import{b as I}from"../packem_shared/tui-prompts-DzYd2fL3.mjs";import{runResetCommand as A}from"./runResetCommand.mjs";import{r as P}from"../packem_shared/import-DuHtoh4_.mjs";const N=(e,r)=>typeof r=="bigint"?Number(r):r instanceof ArrayBuffer?[...new Uint8Array(r)]:r,l=e=>({code:e,conflicts:0,generated:0,inserted:0,ndjson:""}),U=(e,r)=>{if(!S(r))return e.logger.error(`schema not found: ${r} — run \`vis generate lunora-table --name=<name>\` to create one`),l(1);if(e.reset===!0&&b({prod:e.prod,url:e.url}))return e.logger.error("--reset only clears local .wrangler/state and cannot be combined with --prod or a remote --url"),l(1)},W=async(e,r,t,n)=>{const d=await k(m($(),"lunora-seed-")),i=m(d,"rows.ndjson");await v(i,e,"utf8");try{const o=await P({batchSize:n.batchSize,cwd:t,fetchImpl:n.fetchImpl,file:i,logger:n.logger,prod:n.prod,token:n.token,url:n.url,yes:!0}),s=o.body?.conflicts??0;return s>0&&n.logger.warn(`${String(s)} 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:o.code,conflicts:s,generated:r,inserted:o.inserted,ndjson:e}}finally{await R(d,{force:!0,recursive:!0}).catch(()=>{})}},_=(e,r)=>{if(e.table===void 0||r.tables.some(n=>n.name===e.table))return;const t=r.tables.map(n=>n.name).join(", ");return e.logger.error(`unknown table "${e.table}" — schema defines: ${t||"(no tables)"}`),l(1)},B=async(e,r)=>{if(!b({prod:e.prod,url:e.url})||e.yes===!0)return;if(!process.stdin.isTTY&&e.confirm===void 0)return e.logger.error("seed: refusing to insert into a non-local target without confirmation — re-run with --yes"),l(1);if(!await(e.confirm??I)(`This will insert ${String(r)} generated row(s) into ${e.url??"the production worker"}. Continue?`))return e.logger.info("seed: aborted"),l(1)},D=async e=>{const r=e.cwd??process.cwd(),t=m(r,"lunora","schema.ts"),n=U(e,t);if(n!==void 0)return n;const d=new F({skipAddingFilesFromTsConfig:!0}),i=j(d,t),o=_(e,i);if(o!==void 0)return o;const s=T(i),g=C(s,{defaultCount:e.count??10,now:e.now,only:e.table===void 0?void 0:[e.table],seed:e.seed??0}),u=[];for(const{rows:f,table:h}of g)for(const y of f)u.push(JSON.stringify({doc:y,table:h},N));const c=u.length>0?`${u.join(`
2
2
  `)}
3
3
  `:"",a=u.length;if(e.dryRun===!0)return c.length>0&&process.stdout.write(c),e.logger.info(`generated ${String(a)} row(s) across ${String(g.length)} table(s) — dry run, nothing inserted`),{code:0,conflicts:0,generated:a,inserted:0,ndjson:c};if(a===0)return e.logger.warn("no rows generated — nothing to insert"),{code:0,conflicts:0,generated:0,inserted:0,ndjson:c};if(e.reset===!0){const f=await A({confirm:e.confirm,cwd:r,logger:e.logger,yes:e.yes});if(f.code!==0)return{code:f.code,conflicts:0,generated:a,inserted:0,ndjson:c}}const w=await B(e,a);return w!==void 0?w:W(c,a,r,e)},Z=x(async({cwd:e,logger:r,options:t})=>({code:(await D({batchSize:t.batchSize,count:t.count,cwd:e,dryRun:t.dryRun===!0,logger:r,prod:t.prod===!0,reset:t.reset===!0,now:t.now,seed:t.seed,table:t.table,token:t.token,url:z({cwd:e,prod:t.prod===!0,url:t.url}),yes:t.yes===!0})).code}));export{Z as execute,D as runSeedCommand};
@@ -1,3 +1,3 @@
1
- import{writeFileSync as E,existsSync as w,cpSync as j,statSync as b,lstatSync as I,readdirSync as N,mkdirSync as D,readFileSync as M}from"node:fs";import{join as u,sep as x,relative as B,resolve as O,dirname as K}from"node:path";import{SDK_TARGETS as V,SDK_LANGUAGES as G,generateSdk as P,isTypedSchema as Q}from"@lunora/codegen";import{LunoraError as d}from"@lunora/errors";import{d as J}from"../packem_shared/command-DwC11Cwe.mjs";import{r as _,a as U,b as q,c as H,s as W}from"../packem_shared/resolve-BWFT7RvE.mjs";const $="gh:anolilab/lunora/sdks",v="lunora-transport.json",X=/_test\.|Tests?\./u,k=t=>t.startsWith("test_")||X.test(t),A=(t,n="")=>N(t).toSorted((e,r)=>e.localeCompare(r)).flatMap(e=>{const r=u(t,e),a=n.length>0?`${n}/${e}`:e;return b(r).isDirectory()?A(r,a):[a]}),C=(t,n)=>{const e=I(n);if(e.isSymbolicLink())throw new d("INTERNAL",`refusing to vendor "${B(t,n)}" — it is a symlink, not a regular file`);if(e.isDirectory())for(const r of N(n))k(r)||C(t,u(n,r))},F=(t,n,e,r)=>{const a=u(t,e);if(!w(a))throw new d("NOT_FOUND",`transport is missing ${e}`);C(t,a);const s=u(n,r);return j(a,s,{filter:o=>!k(o.slice(o.lastIndexOf(x)+1)),force:!0,recursive:!0}),b(s).isDirectory()?A(s).map(o=>`${r}/${o}`):[r]},R=(t,n)=>n.vendor.every(e=>w(u(t,e.from))),z=async(t,n)=>{const{language:e,logger:r,outputDirectory:a,registryOptions:s,target:o}=n,{cleanup:f,directory:h}=await H(e,{...s,ref:t},$);try{if(!R(h,o)){r.warn(`${$}/${e} does not exist at ${t}.`);return}return{files:o.vendor.flatMap(c=>F(h,a,c.from,c.to)).toSorted((c,l)=>c.localeCompare(l)),ref:t,source:`${$}/${e}`,versionMatched:t===_()}}finally{f()}},Y=(t,n)=>{const{language:e,outputDirectory:r,target:a}=n,s=u(t,e);if(!w(s))throw new d("NOT_FOUND",`no transport at ${s} — --from must point at a directory of per-language transports (the repo's \`sdks/\`)`);if(!R(s,a)){const o=a.vendor.map(f=>f.from).join(", ");throw new d("NOT_FOUND",`${s} is not a ${e} transport — expected it to contain ${o}`)}return{files:a.vendor.flatMap(o=>F(s,r,o.from,o.to)).toSorted((o,f)=>o.localeCompare(f)),ref:"local",source:s,versionMatched:!1}},Z=async t=>{const{allowUnsafeSource:n,from:e,language:r,logger:a,outputDirectory:s,ref:o,source:f,target:h}=t;if(e!==void 0)return Y(e,{language:r,outputDirectory:s,target:h});const c={allowUnsafeSource:n,logger:a,names:[],source:f},l=async i=>z(await q(i,a),{language:r,logger:a,outputDirectory:s,registryOptions:c,target:h});if(o!==void 0&&o.length>0){const i=await l(o);if(i===void 0)throw new d("NOT_FOUND",`--ref ${o} carries no ${r} transport — pick a ref that does, or pass --from <dir> to copy a local one`);return i}const m=_(),g=await l(m).catch(i=>{const y=i instanceof Error?i.message.split(`
1
+ import{writeFileSync as E,existsSync as w,cpSync as j,statSync as b,lstatSync as I,readdirSync as N,mkdirSync as D,readFileSync as M}from"node:fs";import{join as u,sep as x,relative as B,resolve as O,dirname as K}from"node:path";import{SDK_TARGETS as V,SDK_LANGUAGES as G,generateSdk as P,isTypedSchema as Q}from"@lunora/codegen";import{LunoraError as d}from"@lunora/errors";import{d as J}from"../packem_shared/command-DwC11Cwe.mjs";import{r as _,a as U,b as q,c as H,s as W}from"../packem_shared/resolve-B9ReA3FV.mjs";const $="gh:anolilab/lunora/sdks",v="lunora-transport.json",X=/_test\.|Tests?\./u,k=t=>t.startsWith("test_")||X.test(t),A=(t,n="")=>N(t).toSorted((e,r)=>e.localeCompare(r)).flatMap(e=>{const r=u(t,e),a=n.length>0?`${n}/${e}`:e;return b(r).isDirectory()?A(r,a):[a]}),C=(t,n)=>{const e=I(n);if(e.isSymbolicLink())throw new d("INTERNAL",`refusing to vendor "${B(t,n)}" — it is a symlink, not a regular file`);if(e.isDirectory())for(const r of N(n))k(r)||C(t,u(n,r))},F=(t,n,e,r)=>{const a=u(t,e);if(!w(a))throw new d("NOT_FOUND",`transport is missing ${e}`);C(t,a);const s=u(n,r);return j(a,s,{filter:o=>!k(o.slice(o.lastIndexOf(x)+1)),force:!0,recursive:!0}),b(s).isDirectory()?A(s).map(o=>`${r}/${o}`):[r]},R=(t,n)=>n.vendor.every(e=>w(u(t,e.from))),z=async(t,n)=>{const{language:e,logger:r,outputDirectory:a,registryOptions:s,target:o}=n,{cleanup:f,directory:h}=await H(e,{...s,ref:t},$);try{if(!R(h,o)){r.warn(`${$}/${e} does not exist at ${t}.`);return}return{files:o.vendor.flatMap(c=>F(h,a,c.from,c.to)).toSorted((c,l)=>c.localeCompare(l)),ref:t,source:`${$}/${e}`,versionMatched:t===_()}}finally{f()}},Y=(t,n)=>{const{language:e,outputDirectory:r,target:a}=n,s=u(t,e);if(!w(s))throw new d("NOT_FOUND",`no transport at ${s} — --from must point at a directory of per-language transports (the repo's \`sdks/\`)`);if(!R(s,a)){const o=a.vendor.map(f=>f.from).join(", ");throw new d("NOT_FOUND",`${s} is not a ${e} transport — expected it to contain ${o}`)}return{files:a.vendor.flatMap(o=>F(s,r,o.from,o.to)).toSorted((o,f)=>o.localeCompare(f)),ref:"local",source:s,versionMatched:!1}},Z=async t=>{const{allowUnsafeSource:n,from:e,language:r,logger:a,outputDirectory:s,ref:o,source:f,target:h}=t;if(e!==void 0)return Y(e,{language:r,outputDirectory:s,target:h});const c={allowUnsafeSource:n,logger:a,names:[],source:f},l=async i=>z(await q(i,a),{language:r,logger:a,outputDirectory:s,registryOptions:c,target:h});if(o!==void 0&&o.length>0){const i=await l(o);if(i===void 0)throw new d("NOT_FOUND",`--ref ${o} carries no ${r} transport — pick a ref that does, or pass --from <dir> to copy a local one`);return i}const m=_(),g=await l(m).catch(i=>{const y=i instanceof Error?i.message.split(`
2
2
  `)[0]??i.message:String(i);a.warn(`could not fetch the transport at ${m} (${y}).`)});if(g!==void 0)return g;const p=await l(void 0);if(p===void 0)throw new d("NOT_FOUND",`no ${r} transport at ${m} or on the release branch. This language may not be released yet — pass --from <dir> to copy one from a checkout, or --ref <tag> to name a ref that has it.`);return a.warn(`FALLBACK: the transport is NOT version-matched to this CLI (${U()}). Wanted ${m}, used ${p.ref}. The vendored wire protocol may not be the one this surface was generated against; ${v} records what was actually copied.`),p},ee=(t,n,e)=>{const r={cliVersion:U(),files:e.files,language:n,note:e.versionMatched?"Vendored by `lunora sdk generate` at the ref matching the CLI that generated the surface beside it. Regenerate with a newer CLI to upgrade.":"Vendored by `lunora sdk generate` from a ref that is NOT this CLI's release tag, so the transport and the generated surface may be different protocol vintages.",ref:e.ref,source:e.source,versionMatched:e.versionMatched};E(u(t,v),`${JSON.stringify(r,void 0,4)}
3
3
  `,"utf8")},te=u("lunora","_generated","openrpc.json"),re=t=>{if(!w(t))throw new d("NOT_FOUND",`no OpenRPC document at ${t} — run \`lunora codegen --api-spec openrpc\` (or \`--api-spec both\`) first, or pass --spec`);let n;try{n=JSON.parse(M(t,"utf8"))}catch(e){throw new d("BAD_REQUEST",`${t} is not valid JSON: ${e instanceof Error?e.message:String(e)}`)}if(n===null||typeof n!="object"||!Array.isArray(n.methods))throw new d("BAD_REQUEST",`${t} is not an OpenRPC document (no \`methods\` array)`);return n},de=J(async({argument:t,cwd:n,logger:e,options:r})=>{const a=t[0]??"generate";if(a!=="generate")throw new d("BAD_REQUEST",`unknown subcommand "${a}" — the only one is \`lunora sdk generate\``);const s=r.lang??"python",o=V[s];if(o===void 0)throw new d("BAD_REQUEST",`unsupported --lang "${s}" — expected one of: ${G.join(" | ")}`);const f=W("sdk generate",{allowUnsafeSource:r.allowUnsafeSource,logger:e,names:[],source:r.source});if(f!==void 0)throw new d("BAD_REQUEST",f);const h=O(n,r.spec??te),c=O(n,r.out??u("sdk",s)),l=re(h);l.methods.length===0&&e.warn(`${h} declares no methods — writing an empty SDK.`);const{files:m,undeclared:g,unrepresentable:p}=await P(l,o);D(c,{recursive:!0});const i=await Z({allowUnsafeSource:r.allowUnsafeSource,from:r.from,language:s,logger:e,outputDirectory:c,ref:r.ref,source:r.source,target:o});ee(c,s,i);for(const[S,L]of Object.entries(m)){const T=u(c,S);D(K(T),{recursive:!0}),E(T,L,"utf8")}const y=l.methods.filter(S=>!Q(S.result?.schema)).length;return e.success(`Generated ${s} SDK for ${String(l.methods.length)} function(s) → ${c}`),e.info(`Vendored the ${s} transport (${String(i.files.length)} file(s)) from ${i.source} @ ${i.ref}${i.versionMatched?" — version-matched to this CLI":""}; see ${v}.`),e.info(o.requires.length>0?`Install in the consuming project: ${o.requires.join(", ")}.`:"Nothing to install — the transport is vendored and needs only the standard library."),g.length>0&&e.warn(`${String(g.length)} schema(s) are not expressible as a named ${s} model, so those arguments or returns stay untyped: ${g.join(", ")}`),p.length>0&&e.warn(`${String(p.length)} function(s) take or return a \`v.bigint()\`/\`v.bytes()\`, which no generated model can carry — their parameters stay untyped, so pass wire values directly: ${p.join(", ")}`),y>0&&e.warn(`${String(y)} of ${String(l.methods.length)} function(s) return an untyped result — declare \`.output()\` on them for typed returns.`),{code:0}});export{de as execute};
@@ -1,7 +1,7 @@
1
- import{spawnSync as A,spawn as re}from"node:child_process";import{existsSync as $,watch as Te,readFileSync as N,mkdirSync as Re,openSync as te,closeSync as ne,statSync as _e,readSync as Le}from"node:fs";import{join as b,dirname as Ie}from"node:path";import{runCodegen as oe}from"@lunora/codegen";import{runPostCodegenHook as Oe,detectAgentRules as ie,updateDevServerState as C,readDevServerState as O,claimDevServerState as se,DEV_HANDOFF_ENV as R,clearDevServerState as y,readLiveDevServerState as P,isDevServerReady as G,detectFramework as ae,readProjectDependencyNames as Pe,DEV_LOG_FILE_ENV as ce,DEV_DAEMON_ENV as M,detectPackageManager as de,execArgsFor as D,isRecordedProcessCurrent as De,DEV_LOG_FILE as Ae,CODEGEN_ENV as le,isCodegenDisabled as $e,detectAiAgent as Ne,readProjectRemotePreference as Ce,inferLunoraBindings as Me,packageNamesFromBindings as xe,ensureDevVarsExample as Fe,ensureDevVariables as je,isInteractive as Ge,DEV_VARS_FILE as _,DEV_VARS_EXAMPLE_FILE as Ue,fillDevSecrets as Ve,DEV_BINDINGS_FILE as We,DEV_STATE_FILE as ue,claimAgentRulesHint as He,AGENT_RULES_HINT as Be,resolveDeployDriver as Ke,resolveProjectTarget as Ye,runScriptCommand as Je,discoverContainerInfo as Xe,streamContainerLogs as ze,parseDevVariableEntries as Qe,formatLunoraEvent as Ze}from"@lunora/config";import{resolveRemoteEnabled as qe,findWranglerFile as fe,readWranglerJsonc as ge,materializeRemoteWranglerConfig as er}from"@lunora/config/cloudflare";import{p as rr,a as tr}from"../packem_shared/deploy-target-B0Xcb2jV.mjs";import{w as nr}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{a as or}from"../packem_shared/codegen-error-AmH54ofi.mjs";import{r as ir}from"../packem_shared/platform-diagnostics-D0YzAdXm.mjs";import{d as sr}from"../packem_shared/command-DwC11Cwe.mjs";import{createServer as ar,connect as cr}from"node:net";import{forceJsonLogging as dr}from"../packem_shared/createLogger-hGafwf-3.mjs";import{networkInterfaces as lr}from"node:os";import{spawnShellCompat as ve}from"../packem_shared/createRecordingSpawner-DJlNacZ6.mjs";import{createServer as ur,request as fr}from"node:http";import{pipeline as gr}from"node:stream";import{loadStudioAssets as U,studioAssetsStamp as V,renderStudioHtml as vr,resolveAdminToken as mr,transportRejectionReason as W,SCHEMA_EDIT_ENDPOINT as pr,POLICY_SCAFFOLD_ENDPOINT as wr,SEED_ENDPOINT as hr,sendStudioDocument as Sr,serveJsonHandler as yr,isStandaloneModulePath as Er,readStandaloneAsset as br,assetContentType as kr,handleSchemaEditRequest as Tr,handlePolicyScaffoldRequest as Rr,handleSeedRequest as _r,applyStudioAssetCache as Lr}from"@lunora/config/studio-host";import{c as Ir}from"../packem_shared/tui-prompts-Dd0pDuNr.mjs";import{setTimeout as L}from"node:timers/promises";import{p as E}from"../packem_shared/output-format-DfogXx0p.mjs";const Or=100,Pr=300,Dr=/[/\\]/u,Ar=(e,r,n)=>{const{apiSpec:t,logger:o,projectRoot:i,target:s}=e;try{const a=oe({apiSpec:t,lunoraDirectory:r,projectRoot:i,target:s});o.success(`codegen: wrote ${r}/_generated (${n})`),ir(a.platformDiagnostics,o)}catch(a){return o.error(or(a,n)),!1}return!0},$r=e=>{const r=e.lunoraDirectory??"lunora",n=b(e.projectRoot,r),t=e.debounceMs??Or;let o=!1,i=!1,s=!1,a,c=0,u=Promise.resolve(),g;const m=new Promise(v=>{g=v}),p=v=>{o||(a=v,!i&&(i=!0,u=(async()=>{try{for(;a!==void 0;){const h=a;if(a=void 0,!!Ar(e,r,h)){s=!0;try{(await Oe({cwd:e.projectRoot,logger:e.logger,spawner:e.spawner,stdoutToStderr:e.jsonLogs})).ran&&(c=Date.now())}finally{s=!1}}}}catch(h){e.logger.error(`codegen watch: ${h instanceof Error?h.message:String(h)}`)}finally{i=!1,g()}})()))};p("startup");const l=v=>(e.logger.warn(`codegen watch unavailable (${v}) — schema edits will NOT auto-regenerate. Run \`lunora codegen\` manually after each edit.`),{close:()=>(o=!0,a=void 0,u),ready:m,watchAvailable:!1});let d,f;if(!$(n))return l(`no such directory: ${n}`);try{f=Te(n,{recursive:!0},(v,h)=>{if(!(typeof h=="string"&&h.split(Dr).includes("_generated"))){if(s||Date.now()-c<Pr){d&&(clearTimeout(d),d=void 0);return}d&&clearTimeout(d),d=setTimeout(()=>{p(`change: ${h??"?"}`)},t)}})}catch(v){return l(v instanceof Error?v.message:String(v))}const w=f;return{close:()=>(o=!0,a=void 0,d&&clearTimeout(d),w.close(),u),ready:m,watchAvailable:!0}},Nr=64,me="127.0.0.1",Cr=65535,Mr=(e,r=me)=>new Promise(n=>{const t=ar();t.once("error",()=>{n(!1)}),t.once("listening",()=>{t.close(()=>{n(!0)})}),t.listen(e,r)}),xr=async(e,r=me,n=Nr)=>{for(let t=e;t<e+n&&t<=Cr;t+=1)if(await Mr(t,r))return t;return e},H=(e=lr)=>Object.values(e()).some(r=>r?.some(n=>n.internal&&n.address==="::1")),B="/_lunora",K=e=>{const r=e.indexOf("?");return r===-1?e:e.slice(0,r)},Y=3e4,J=(e,r,n)=>{const t=fr({headers:{...e.headers,host:n.host},hostname:n.hostname,method:e.method,path:e.url,port:n.port},o=>{r.writeHead(o.statusCode??502,o.headers),gr(o,r,()=>{})});t.setTimeout(Y,()=>{t.destroy(new Error(`no response within ${String(Y)}ms`))}),t.on("error",o=>{if(r.headersSent){r.destroy();return}r.statusCode=o.message.startsWith("no response within")?504:502,r.end(`lunora dev: worker unreachable (${o.message})`)}),r.on("close",()=>{r.writableFinished||t.destroy()}),e.pipe(t)},Fr=5e3,jr=(e,r,n,t)=>{const o=cr({host:t.hostname,port:Number(t.port)},()=>{o.setTimeout(0);const i=[`${e.method??"GET"} ${e.url??"/"} HTTP/1.1`];for(const[s,a]of Object.entries(e.headers))if(s!=="host")for(const c of Array.isArray(a)?a:[a])c!==void 0&&i.push(`${s}: ${c}`);i.push(`host: ${t.host}`,"",""),o.write(i.join(`\r
2
- `)),n.length>0&&o.write(n),o.pipe(r),r.pipe(o)});o.setTimeout(Fr,()=>o.destroy()),o.on("error",()=>r.destroy()),r.on("error",()=>o.destroy())},Gr=async e=>{const r=e.host??"127.0.0.1",n=r==="127.0.0.1"||r==="localhost"||r==="::1",t=new URL(e.workerOrigin);let o=U(e.logger,import.meta.url),i=V(import.meta.url);const s=vr({adminToken:n?mr(e.cwd):void 0,basePath:"/",dataEditable:n,rulesInstalled:ie(e.cwd).installed,runAsIdentity:n,schemaEditable:n,scriptSrc:"/studio.js",styleHref:"/styles.css"}),a=(l,d,f,w,v)=>{Lr(l,d,v,i)||(d.statusCode=200,d.setHeader("Content-Type",w),d.end(f))},c=(l,d,f)=>{l.statusCode=d,l.setHeader("Content-Type","text/plain"),l.end(f)},u=(l,d,f,w)=>{if(n){yr(l,d,f,e.cwd);return}c(d,403,w)},g=(l,d,f)=>{const w=l==="/styles.css",v=Er(l);if(!w&&!v)return!1;const h=V(import.meta.url);if(h!==i&&(o=U(e.logger,import.meta.url),i=h),o===void 0)return c(f,501,"Lunora studio assets not found — install and build @lunora/studio."),!0;if(w)return a(d,f,o.styles,"text/css; charset=utf-8","styles.css"),!0;const k=l.slice(l.lastIndexOf("/")+1),j=br(k,import.meta.url);return j===void 0?(c(f,404,"Not found"),!0):(a(d,f,j,kr(k),k),!0)},m=Buffer.from(s),p=ur((l,d)=>{const f=K(l.url??"/");if(n){const v=W(l,e.logger);if(v!==void 0){c(d,403,v);return}}if(f.startsWith(B)){if(!n){c(d,403,"Lunora studio: the worker admin proxy is only available on a loopback bind.");return}J(l,d,t);return}if(f===pr){u(l,d,Tr,"Lunora schema editing is only available on loopback hosts in dev.");return}if(f===wr){u(l,d,Rr,"Lunora policy scaffolding is only available on loopback hosts in dev.");return}if(f===hr){u(l,d,_r,"Lunora data seeding is only available on loopback hosts in dev.");return}if(g(f,l,d))return;const w=l.headers["sec-fetch-mode"];if(n&&typeof w=="string"&&w!=="navigate"){J(l,d,t);return}Sr(d,m)});return p.on("upgrade",(l,d,f)=>{if(!n||W(l,e.logger)!==void 0){d.destroy();return}K(l.url??"").startsWith(B)?jr(l,d,f,t):d.destroy()}),await new Promise((l,d)=>{p.once("error",f=>{f.code==="EADDRINUSE"?d(new Error(`studio port ${String(e.port)} is already in use — pass a different port with --port, or stop the process using it`,{cause:f})):d(f)}),p.listen(e.port,r,()=>{l()})}),{close:()=>new Promise(l=>{p.close(()=>{l()})}),url:`http://${r==="0.0.0.0"||r==="::"?"localhost":r}:${String(e.port)}`}},Ur=12e4,x=250,Vr=1e3,Wr="LUNORA_DEV_READY_TIMEOUT_MS",pe=e=>{if(e!==void 0)return e;const r=Number(process.env[Wr]??"");return Number.isFinite(r)&&r>0?r:Ur},we=async(e,r)=>{try{const n=AbortSignal.timeout(Vr);return await(await fetch(new URL("/_lunora/status",e),{redirect:"manual",signal:r===void 0?n:AbortSignal.any([r,n])})).body?.cancel(),!0}catch{return!1}},Hr=async e=>{const{cwd:r,logger:n,origin:t,signal:o}=e,i=e.probe??we,s=pe(e.readyTimeoutMs),a=Date.now()+s,c=()=>o.aborted;for(;!c()&&Date.now()<a;){let u=!1;try{u=await i(t,o)}catch{}if(c()||Date.now()>=a)break;if(u)return C(r,{readyAt:new Date().toISOString()},{expectedPid:process.pid}),O(r)?.readyAt!==void 0;try{await L(x,void 0,{signal:o})}catch{}}return c()||n.warn(`server did not answer on ${t} within ${String(Math.round(s/1e3))}s — .lunora/dev.json will have no readyAt, so anything polling for readiness will keep waiting. The server itself is unaffected; raise LUNORA_DEV_READY_TIMEOUT_MS if it is just slow to boot.`),!1},Br=1e4,Kr=100,Yr=40,T=256*1024,Jr=new Set(["nuxt","sveltekit"]),F=e=>Jr.has(ae(e).framework)?"framework-worker":Pe(e).has("@lunora/vite")?"vite":"wrangler",he=e=>{const r=de(e);let n;try{const t=N(b(e,"package.json"),"utf8");n=JSON.parse(t).scripts?.dev}catch{}if(n===void 0||n.trim()===""||n.includes("lunora")){const t=D(r,"vite",["dev"]);return{args:t.args,command:t.command}}return{args:["run","dev"],command:r}},Xr=e=>{Re(Ie(e.logPath),{recursive:!0});const r=te(e.logPath,"w",384);let n;const t=ve(e.command,e.args);try{n=re(t.command,t.args,{cwd:e.cwd,detached:!0,env:e.env,shell:t.shell,stdio:["ignore",r,r],windowsHide:!0})}finally{ne(r)}return n.unref(),{exited:new Promise(o=>{n.on("error",()=>{o(1)}),n.on("exit",(i,s)=>{o(i??(s?1:0))})}),pid:n.pid}},zr=e=>{try{const{size:r}=_e(e);if(r<=T)return N(e,"utf8");const n=te(e,"r");try{const t=Buffer.alloc(T),o=Le(n,t,0,T,r-T),i=t.toString("utf8",0,o);return i.slice(i.indexOf(`
3
- `)+1)}finally{ne(n)}}catch{return}},Se=(e,r)=>{const n=zr(e);if(n===void 0)return[];const t=n.split(`
4
- `);return t.at(-1)===""&&t.pop(),r>0?t.slice(-r):t},ye=(e,r)=>r?.logFile??b(e,Ae),Ee=e=>{e.info(" Stop: lunora dev stop"),e.info(" Status: lunora dev status"),e.info(" Logs: lunora dev logs")},I=(e,r)=>{e.warn(`Dev server already running at ${r.url} (pid ${String(r.pid)})`),Ee(e)},Qr=(e,r)=>{e.success(`Dev server running at ${r.url} (pid ${String(r.pid)})`),r.studioUrl!==void 0&&e.info(` Studio: ${r.studioUrl}`),Ee(e)},Zr=async e=>{const{child:r,cwd:n,deadline:t,pollIntervalMs:o,probe:i}=e,s=r.exited.then(a=>({exitCode:a}));for(;Date.now()<t;){const a=P(n);if(a!==void 0&&a.pid!==process.pid&&await i(a.url))return{state:a,status:"ready"};const c=await Promise.race([s,L(o)]);if(c!==void 0)return{...c,status:"exited"}}return{status:"timeout"}},qr=async e=>{const{cwd:r,logger:n}=e,t=ye(r,void 0),o=pe(e.readyTimeoutMs),i=(e.spawnDetached??Xr)({args:e.command.args,command:e.command.command,cwd:r,env:{...process.env,...e.env,[M]:"1",[ce]:t,...process.env.FORCE_COLOR===void 0?{NO_COLOR:"1"}:{},...e.json?{LUNORA_LOG_JSON:"1"}:{}},logPath:t}),s=await Zr({child:i,cwd:r,deadline:Date.now()+o,pollIntervalMs:e.pollIntervalMs??x,probe:e.probe??we});if(s.status==="ready")return Qr(n,s.state),{code:0};if(s.status==="exited"){n.error(`dev server exited before becoming ready (exit code ${String(s.exitCode)}). Last output:`);for(const c of Se(t,Yr))n.error(` ${c}`);return y(r,i.pid??process.pid),{code:s.exitCode===0?1:s.exitCode}}i.pid!==void 0&&O(r)?.pid===process.pid&&C(r,{logFile:t,pid:i.pid});const a=i.pid===void 0?"":` (pid ${String(i.pid)})`;return n.warn(`dev server did not confirm ready within ${String(Math.round(o/1e3))}s — it may still be compiling${a}. Check \`lunora dev status\` and \`lunora dev logs\`; \`lunora dev stop\` shuts it down.`),{code:1}},be=e=>e.codegen!==!1&&!$e(process.env[le]),ke=e=>{const r={...e.remote===!0?{LUNORA_REMOTE:"1"}:{},...e.codegen===!1?{[le]:"0"}:{}};return Object.keys(r).length>0?{env:r}:{}},et=(e,r)=>{const n=["dev"];return e.apiSpec!==void 0&&n.push("--api-spec",e.apiSpec),e.port!==void 0&&n.push("--port",String(e.port)),e.workerPort!==void 0&&n.push("--worker-port",String(e.workerPort)),e.emitBindings!==void 0&&n.push("--emit-bindings",e.emitBindings),e.codegen===!1&&n.push("--no-codegen"),e.studio===!1&&n.push("--no-studio"),e.worker===!1&&n.push("--no-worker"),e.target!==void 0&&n.push("--target",e.target),r&&n.push("--remote"),n},rt=async e=>{const{cwd:r,jsonLogs:n,logger:t,options:o,remote:i}=e,s=e.run??qr,a=F(r),c=a==="wrangler"?`http://localhost:${String(o.workerPort??8787)}`:"http://localhost:5173",u=se(r,{background:!0,mode:"cli",pid:process.pid,startedAt:new Date().toISOString(),url:c});if(!u.ok)return u.existing!==void 0&&I(t,u.existing),{code:0};const g={[R]:String(process.pid)};try{return a==="vite"?await s({command:he(r),cwd:r,env:{...ke({...o,remote:i}).env,...g},json:n,logger:t}):await s({command:{args:[process.argv[1]??"lunora",...et(o,i)],command:process.execPath},cwd:r,env:g,json:n,logger:t})}finally{y(r,process.pid)}},tt=e=>{try{const r=A("ps",["-o","pgid=","-p",String(e)],{encoding:"utf8"}),n=Number.parseInt(r.stdout.trim(),10);return Number.isInteger(n)&&n>0?n:void 0}catch{return}},nt=(e,r,n=process.platform,t=A)=>{if(n==="win32"){try{t("taskkill",["/pid",String(e.pid),"/T","/F"],{stdio:"ignore"})}catch{}return}if(e.background===!0)try{r(-(tt(e.pid)??e.pid),"SIGKILL");return}catch{}try{r(e.pid,"SIGKILL")}catch{}},ot=(e,r)=>(r.json?E({pid:e.pid,stopped:!1}):r.logger.error(`dev server (pid ${String(e.pid)}) survived the force-kill — record kept; retry \`lunora dev stop\` or kill the process manually.`),{code:1}),it=async e=>{const{cwd:r,logger:n}=e,t=O(r),o=e.alive??(m=>m===t?.pid&&De(t)),i=e.signal??((m,p)=>{process.kill(m,p)}),s=e.pollIntervalMs??x,a=e.stopGraceMs??Br,c=e.platform??process.platform,u=e.spawnSyncImpl??A;if(t===void 0||!o(t.pid))return t!==void 0&&y(r,t.pid),e.json?E({running:!1,stopped:!1}):n.info("No dev server running."),{code:0};try{i(t.pid,"SIGTERM")}catch{}const g=Date.now()+a;for(;o(t.pid)&&Date.now()<g;)await L(s);return o(t.pid)&&(nt(t,i,c,u),await L(s),o(t.pid))?ot(t,e):(y(r,t.pid),e.json?E({pid:t.pid,stopped:!0}):n.success(`Stopped dev server (pid ${String(t.pid)}).`),{code:0})},st=e=>{const{cwd:r,logger:n}=e,t=P(r);if(t===void 0)return e.json?E({running:!1}):n.info("No dev server running."),{code:0};const o=e.now??Date.now,i=t.startedAt===void 0?Number.NaN:Date.parse(t.startedAt),s=Number.isFinite(i)?Math.max(0,Math.round((o()-i)/1e3)):void 0;if(e.json)return E({background:t.background===!0,logFile:t.logFile,mode:t.mode,pid:t.pid,ready:G(t),readyAt:t.readyAt,running:!0,startedAt:t.startedAt,studioUrl:t.studioUrl,uptimeSeconds:s,url:t.url}),{code:0};const a=[`pid ${String(t.pid)}`,...s===void 0?[]:[`uptime ${String(s)}s`],t.background===!0?"background":"foreground",G(t)?"ready":"starting"];return n.success(`Dev server running at ${t.url} (${a.join(", ")})`),t.studioUrl!==void 0&&n.info(` Studio: ${t.studioUrl}`),t.logFile!==void 0&&n.info(` Logs: lunora dev logs (${t.logFile})`),{code:0}},at=e=>{const{cwd:r,logger:n}=e,t=O(r),o=ye(r,t);if(!$(o))return n.info("No dev server logs found — output is captured when the server runs in background mode (`lunora dev --background`)."),{code:0};const i=Se(o,e.lines??Kr);return i.length>0&&process.stdout.write(`${i.join(`
1
+ import{spawnSync as $,spawn as re}from"node:child_process";import{existsSync as N,watch as Te,readFileSync as C,mkdirSync as Re,openSync as te,closeSync as ne,statSync as _e,readSync as Le}from"node:fs";import{join as b,dirname as Ie}from"node:path";import{runCodegen as oe}from"@lunora/codegen";import{runPostCodegenHook as Oe,detectAgentRules as ie,updateDevServerState as M,readDevServerState as O,claimDevServerState as se,DEV_HANDOFF_ENV as R,clearDevServerState as y,readLiveDevServerState as P,isDevServerReady as G,detectFramework as ae,readProjectDependencyNames as Pe,DEV_LOG_FILE_ENV as ce,DEV_DAEMON_ENV as x,detectPackageManager as de,execArgsFor as A,isRecordedProcessCurrent as De,DEV_LOG_FILE as Ae,CODEGEN_ENV as le,isCodegenDisabled as $e,detectAiAgent as Ne,readProjectRemotePreference as Ce,inferLunoraBindings as Me,packageNamesFromBindings as xe,ensureDevVarsExample as Fe,ensureDevVariables as je,isInteractive as Ge,DEV_VARS_FILE as _,DEV_VARS_EXAMPLE_FILE as Ue,fillDevSecrets as Ve,DEV_BINDINGS_FILE as We,DEV_STATE_FILE as ue,claimAgentRulesHint as He,AGENT_RULES_HINT as Be,resolveDeployDriver as Ke,resolveProjectTarget as Ye,runScriptCommand as Je,discoverContainerInfo as Xe,streamContainerLogs as ze,parseDevVariableEntries as Qe,formatLunoraEvent as Ze}from"@lunora/config";import{resolveRemoteEnabled as qe,findWranglerFile as fe,readWranglerJsonc as ge,materializeRemoteWranglerConfig as er}from"@lunora/config/cloudflare";import{p as rr,a as tr}from"../packem_shared/deploy-target-B0Xcb2jV.mjs";import{w as nr}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{a as or}from"../packem_shared/codegen-error-AmH54ofi.mjs";import{r as ir}from"../packem_shared/platform-diagnostics-D0YzAdXm.mjs";import{d as sr}from"../packem_shared/command-DwC11Cwe.mjs";import{createServer as ar,connect as cr}from"node:net";import{forceJsonLogging as dr}from"../packem_shared/createLogger-hGafwf-3.mjs";import{networkInterfaces as lr}from"node:os";import{spawnShellCompat as ve}from"../packem_shared/createRecordingSpawner-DJlNacZ6.mjs";import{createServer as ur,request as fr}from"node:http";import{pipeline as gr}from"node:stream";import{loadStudioAssets as U,studioAssetsStamp as V,renderStudioHtml as vr,resolveAdminToken as mr,transportRejectionReason as W,SCHEMA_EDIT_ENDPOINT as pr,POLICY_SCAFFOLD_ENDPOINT as wr,SEED_ENDPOINT as hr,sendStudioDocument as Sr,serveJsonHandler as yr,isStandaloneModulePath as Er,readStandaloneAsset as br,assetContentType as kr,handleSchemaEditRequest as Tr,handlePolicyScaffoldRequest as Rr,handleSeedRequest as _r,applyStudioAssetCache as Lr}from"@lunora/config/studio-host";import{c as Ir}from"../packem_shared/tui-prompts-DzYd2fL3.mjs";import{setTimeout as L}from"node:timers/promises";import{provisionBindings as Or}from"./runDeployCommand.mjs";import{p as E}from"../packem_shared/output-format-DfogXx0p.mjs";const Pr=100,Dr=300,Ar=/[/\\]/u,$r=(e,r,n)=>{const{apiSpec:t,logger:o,projectRoot:i,target:s}=e;try{const a=oe({apiSpec:t,lunoraDirectory:r,projectRoot:i,target:s});o.success(`codegen: wrote ${r}/_generated (${n})`),ir(a.platformDiagnostics,o)}catch(a){return o.error(or(a,n)),!1}return!0},Nr=e=>{const r=e.lunoraDirectory??"lunora",n=b(e.projectRoot,r),t=e.debounceMs??Pr;let o=!1,i=!1,s=!1,a,d=0,u=Promise.resolve(),g;const m=new Promise(v=>{g=v}),p=v=>{o||(a=v,!i&&(i=!0,u=(async()=>{try{for(;a!==void 0;){const h=a;if(a=void 0,!!$r(e,r,h)){s=!0;try{(await Oe({cwd:e.projectRoot,logger:e.logger,spawner:e.spawner,stdoutToStderr:e.jsonLogs})).ran&&(d=Date.now())}finally{s=!1}}}}catch(h){e.logger.error(`codegen watch: ${h instanceof Error?h.message:String(h)}`)}finally{i=!1,g()}})()))};p("startup");const l=v=>(e.logger.warn(`codegen watch unavailable (${v}) — schema edits will NOT auto-regenerate. Run \`lunora codegen\` manually after each edit.`),{close:()=>(o=!0,a=void 0,u),ready:m,watchAvailable:!1});let c,f;if(!N(n))return l(`no such directory: ${n}`);try{f=Te(n,{recursive:!0},(v,h)=>{if(!(typeof h=="string"&&h.split(Ar).includes("_generated"))){if(s||Date.now()-d<Dr){c&&(clearTimeout(c),c=void 0);return}c&&clearTimeout(c),c=setTimeout(()=>{p(`change: ${h??"?"}`)},t)}})}catch(v){return l(v instanceof Error?v.message:String(v))}const w=f;return{close:()=>(o=!0,a=void 0,c&&clearTimeout(c),w.close(),u),ready:m,watchAvailable:!0}},Cr=64,me="127.0.0.1",Mr=65535,xr=(e,r=me)=>new Promise(n=>{const t=ar();t.once("error",()=>{n(!1)}),t.once("listening",()=>{t.close(()=>{n(!0)})}),t.listen(e,r)}),Fr=async(e,r=me,n=Cr)=>{for(let t=e;t<e+n&&t<=Mr;t+=1)if(await xr(t,r))return t;return e},H=(e=lr)=>Object.values(e()).some(r=>r?.some(n=>n.internal&&n.address==="::1")),B="/_lunora",K=e=>{const r=e.indexOf("?");return r===-1?e:e.slice(0,r)},Y=3e4,J=(e,r,n)=>{const t=fr({headers:{...e.headers,host:n.host},hostname:n.hostname,method:e.method,path:e.url,port:n.port},o=>{r.writeHead(o.statusCode??502,o.headers),gr(o,r,()=>{})});t.setTimeout(Y,()=>{t.destroy(new Error(`no response within ${String(Y)}ms`))}),t.on("error",o=>{if(r.headersSent){r.destroy();return}r.statusCode=o.message.startsWith("no response within")?504:502,r.end(`lunora dev: worker unreachable (${o.message})`)}),r.on("close",()=>{r.writableFinished||t.destroy()}),e.pipe(t)},jr=5e3,Gr=(e,r,n,t)=>{const o=cr({host:t.hostname,port:Number(t.port)},()=>{o.setTimeout(0);const i=[`${e.method??"GET"} ${e.url??"/"} HTTP/1.1`];for(const[s,a]of Object.entries(e.headers))if(s!=="host")for(const d of Array.isArray(a)?a:[a])d!==void 0&&i.push(`${s}: ${d}`);i.push(`host: ${t.host}`,"",""),o.write(i.join(`\r
2
+ `)),n.length>0&&o.write(n),o.pipe(r),r.pipe(o)});o.setTimeout(jr,()=>o.destroy()),o.on("error",()=>r.destroy()),r.on("error",()=>o.destroy())},Ur=async e=>{const r=e.host??"127.0.0.1",n=r==="127.0.0.1"||r==="localhost"||r==="::1",t=new URL(e.workerOrigin);let o=U(e.logger,import.meta.url),i=V(import.meta.url);const s=vr({adminToken:n?mr(e.cwd):void 0,basePath:"/",dataEditable:n,rulesInstalled:ie(e.cwd).installed,runAsIdentity:n,schemaEditable:n,scriptSrc:"/studio.js",styleHref:"/styles.css"}),a=(l,c,f,w,v)=>{Lr(l,c,v,i)||(c.statusCode=200,c.setHeader("Content-Type",w),c.end(f))},d=(l,c,f)=>{l.statusCode=c,l.setHeader("Content-Type","text/plain"),l.end(f)},u=(l,c,f,w)=>{if(n){yr(l,c,f,e.cwd);return}d(c,403,w)},g=(l,c,f)=>{const w=l==="/styles.css",v=Er(l);if(!w&&!v)return!1;const h=V(import.meta.url);if(h!==i&&(o=U(e.logger,import.meta.url),i=h),o===void 0)return d(f,501,"Lunora studio assets not found — install and build @lunora/studio."),!0;if(w)return a(c,f,o.styles,"text/css; charset=utf-8","styles.css"),!0;const k=l.slice(l.lastIndexOf("/")+1),j=br(k,import.meta.url);return j===void 0?(d(f,404,"Not found"),!0):(a(c,f,j,kr(k),k),!0)},m=Buffer.from(s),p=ur((l,c)=>{const f=K(l.url??"/");if(n){const v=W(l,e.logger);if(v!==void 0){d(c,403,v);return}}if(f.startsWith(B)){if(!n){d(c,403,"Lunora studio: the worker admin proxy is only available on a loopback bind.");return}J(l,c,t);return}if(f===pr){u(l,c,Tr,"Lunora schema editing is only available on loopback hosts in dev.");return}if(f===wr){u(l,c,Rr,"Lunora policy scaffolding is only available on loopback hosts in dev.");return}if(f===hr){u(l,c,_r,"Lunora data seeding is only available on loopback hosts in dev.");return}if(g(f,l,c))return;const w=l.headers["sec-fetch-mode"];if(n&&typeof w=="string"&&w!=="navigate"){J(l,c,t);return}Sr(c,m)});return p.on("upgrade",(l,c,f)=>{if(!n||W(l,e.logger)!==void 0){c.destroy();return}K(l.url??"").startsWith(B)?Gr(l,c,f,t):c.destroy()}),await new Promise((l,c)=>{p.once("error",f=>{f.code==="EADDRINUSE"?c(new Error(`studio port ${String(e.port)} is already in use — pass a different port with --port, or stop the process using it`,{cause:f})):c(f)}),p.listen(e.port,r,()=>{l()})}),{close:()=>new Promise(l=>{p.close(()=>{l()})}),url:`http://${r==="0.0.0.0"||r==="::"?"localhost":r}:${String(e.port)}`}},Vr=12e4,F=250,Wr=1e3,Hr="LUNORA_DEV_READY_TIMEOUT_MS",pe=e=>{if(e!==void 0)return e;const r=Number(process.env[Hr]??"");return Number.isFinite(r)&&r>0?r:Vr},we=async(e,r)=>{try{const n=AbortSignal.timeout(Wr);return await(await fetch(new URL("/_lunora/status",e),{redirect:"manual",signal:r===void 0?n:AbortSignal.any([r,n])})).body?.cancel(),!0}catch{return!1}},Br=async e=>{const{cwd:r,logger:n,origin:t,signal:o}=e,i=e.probe??we,s=pe(e.readyTimeoutMs),a=Date.now()+s,d=()=>o.aborted;for(;!d()&&Date.now()<a;){let u=!1;try{u=await i(t,o)}catch{}if(d()||Date.now()>=a)break;if(u)return M(r,{readyAt:new Date().toISOString()},{expectedPid:process.pid}),O(r)?.readyAt!==void 0;try{await L(F,void 0,{signal:o})}catch{}}return d()||n.warn(`server did not answer on ${t} within ${String(Math.round(s/1e3))}s — .lunora/dev.json will have no readyAt, so anything polling for readiness will keep waiting. The server itself is unaffected; raise LUNORA_DEV_READY_TIMEOUT_MS if it is just slow to boot.`),!1},Kr=1e4,Yr=100,Jr=40,T=256*1024,Xr=new Set(["nuxt","sveltekit"]),D=e=>Xr.has(ae(e).framework)?"framework-worker":Pe(e).has("@lunora/vite")?"vite":"wrangler",he=e=>{const r=de(e);let n;try{const t=C(b(e,"package.json"),"utf8");n=JSON.parse(t).scripts?.dev}catch{}if(n===void 0||n.trim()===""||n.includes("lunora")){const t=A(r,"vite",["dev"]);return{args:t.args,command:t.command}}return{args:["run","dev"],command:r}},zr=e=>{Re(Ie(e.logPath),{recursive:!0});const r=te(e.logPath,"w",384);let n;const t=ve(e.command,e.args);try{n=re(t.command,t.args,{cwd:e.cwd,detached:!0,env:e.env,shell:t.shell,stdio:["ignore",r,r],windowsHide:!0})}finally{ne(r)}return n.unref(),{exited:new Promise(o=>{n.on("error",()=>{o(1)}),n.on("exit",(i,s)=>{o(i??(s?1:0))})}),pid:n.pid}},Qr=e=>{try{const{size:r}=_e(e);if(r<=T)return C(e,"utf8");const n=te(e,"r");try{const t=Buffer.alloc(T),o=Le(n,t,0,T,r-T),i=t.toString("utf8",0,o);return i.slice(i.indexOf(`
3
+ `)+1)}finally{ne(n)}}catch{return}},Se=(e,r)=>{const n=Qr(e);if(n===void 0)return[];const t=n.split(`
4
+ `);return t.at(-1)===""&&t.pop(),r>0?t.slice(-r):t},ye=(e,r)=>r?.logFile??b(e,Ae),Ee=e=>{e.info(" Stop: lunora dev stop"),e.info(" Status: lunora dev status"),e.info(" Logs: lunora dev logs")},I=(e,r)=>{e.warn(`Dev server already running at ${r.url} (pid ${String(r.pid)})`),Ee(e)},Zr=(e,r)=>{e.success(`Dev server running at ${r.url} (pid ${String(r.pid)})`),r.studioUrl!==void 0&&e.info(` Studio: ${r.studioUrl}`),Ee(e)},qr=async e=>{const{child:r,cwd:n,deadline:t,pollIntervalMs:o,probe:i}=e,s=r.exited.then(a=>({exitCode:a}));for(;Date.now()<t;){const a=P(n);if(a!==void 0&&a.pid!==process.pid&&await i(a.url))return{state:a,status:"ready"};const d=await Promise.race([s,L(o)]);if(d!==void 0)return{...d,status:"exited"}}return{status:"timeout"}},et=async e=>{const{cwd:r,logger:n}=e,t=ye(r,void 0),o=pe(e.readyTimeoutMs),i=(e.spawnDetached??zr)({args:e.command.args,command:e.command.command,cwd:r,env:{...process.env,...e.env,[x]:"1",[ce]:t,...process.env.FORCE_COLOR===void 0?{NO_COLOR:"1"}:{},...e.json?{LUNORA_LOG_JSON:"1"}:{}},logPath:t}),s=await qr({child:i,cwd:r,deadline:Date.now()+o,pollIntervalMs:e.pollIntervalMs??F,probe:e.probe??we});if(s.status==="ready")return Zr(n,s.state),{code:0};if(s.status==="exited"){n.error(`dev server exited before becoming ready (exit code ${String(s.exitCode)}). Last output:`);for(const d of Se(t,Jr))n.error(` ${d}`);return y(r,i.pid??process.pid),{code:s.exitCode===0?1:s.exitCode}}i.pid!==void 0&&O(r)?.pid===process.pid&&M(r,{logFile:t,pid:i.pid});const a=i.pid===void 0?"":` (pid ${String(i.pid)})`;return n.warn(`dev server did not confirm ready within ${String(Math.round(o/1e3))}s — it may still be compiling${a}. Check \`lunora dev status\` and \`lunora dev logs\`; \`lunora dev stop\` shuts it down.`),{code:1}},be=e=>e.codegen!==!1&&!$e(process.env[le]),ke=e=>{const r={...e.remote===!0?{LUNORA_REMOTE:"1"}:{},...e.codegen===!1?{[le]:"0"}:{}};return Object.keys(r).length>0?{env:r}:{}},rt=(e,r)=>{const n=["dev"];return e.apiSpec!==void 0&&n.push("--api-spec",e.apiSpec),e.port!==void 0&&n.push("--port",String(e.port)),e.workerPort!==void 0&&n.push("--worker-port",String(e.workerPort)),e.emitBindings!==void 0&&n.push("--emit-bindings",e.emitBindings),e.codegen===!1&&n.push("--no-codegen"),e.studio===!1&&n.push("--no-studio"),e.worker===!1&&n.push("--no-worker"),e.target!==void 0&&n.push("--target",e.target),r&&n.push("--remote"),n},tt=async e=>{const{cwd:r,jsonLogs:n,logger:t,options:o,remote:i}=e,s=e.run??et,a=D(r),d=a==="wrangler"?`http://localhost:${String(o.workerPort??8787)}`:"http://localhost:5173",u=se(r,{background:!0,mode:"cli",pid:process.pid,startedAt:new Date().toISOString(),url:d});if(!u.ok)return u.existing!==void 0&&I(t,u.existing),{code:0};const g={[R]:String(process.pid)};try{return a==="vite"?await s({command:he(r),cwd:r,env:{...ke({...o,remote:i}).env,...g},json:n,logger:t}):await s({command:{args:[process.argv[1]??"lunora",...rt(o,i)],command:process.execPath},cwd:r,env:g,json:n,logger:t})}finally{y(r,process.pid)}},nt=e=>{try{const r=$("ps",["-o","pgid=","-p",String(e)],{encoding:"utf8"}),n=Number.parseInt(r.stdout.trim(),10);return Number.isInteger(n)&&n>0?n:void 0}catch{return}},ot=(e,r,n=process.platform,t=$)=>{if(n==="win32"){try{t("taskkill",["/pid",String(e.pid),"/T","/F"],{stdio:"ignore"})}catch{}return}if(e.background===!0)try{r(-(nt(e.pid)??e.pid),"SIGKILL");return}catch{}try{r(e.pid,"SIGKILL")}catch{}},it=(e,r)=>(r.json?E({pid:e.pid,stopped:!1}):r.logger.error(`dev server (pid ${String(e.pid)}) survived the force-kill — record kept; retry \`lunora dev stop\` or kill the process manually.`),{code:1}),st=async e=>{const{cwd:r,logger:n}=e,t=O(r),o=e.alive??(m=>m===t?.pid&&De(t)),i=e.signal??((m,p)=>{process.kill(m,p)}),s=e.pollIntervalMs??F,a=e.stopGraceMs??Kr,d=e.platform??process.platform,u=e.spawnSyncImpl??$;if(t===void 0||!o(t.pid))return t!==void 0&&y(r,t.pid),e.json?E({running:!1,stopped:!1}):n.info("No dev server running."),{code:0};try{i(t.pid,"SIGTERM")}catch{}const g=Date.now()+a;for(;o(t.pid)&&Date.now()<g;)await L(s);return o(t.pid)&&(ot(t,i,d,u),await L(s),o(t.pid))?it(t,e):(y(r,t.pid),e.json?E({pid:t.pid,stopped:!0}):n.success(`Stopped dev server (pid ${String(t.pid)}).`),{code:0})},at=e=>{const{cwd:r,logger:n}=e,t=P(r);if(t===void 0)return e.json?E({running:!1}):n.info("No dev server running."),{code:0};const o=e.now??Date.now,i=t.startedAt===void 0?Number.NaN:Date.parse(t.startedAt),s=Number.isFinite(i)?Math.max(0,Math.round((o()-i)/1e3)):void 0;if(e.json)return E({background:t.background===!0,logFile:t.logFile,mode:t.mode,pid:t.pid,ready:G(t),readyAt:t.readyAt,running:!0,startedAt:t.startedAt,studioUrl:t.studioUrl,uptimeSeconds:s,url:t.url}),{code:0};const a=[`pid ${String(t.pid)}`,...s===void 0?[]:[`uptime ${String(s)}s`],t.background===!0?"background":"foreground",G(t)?"ready":"starting"];return n.success(`Dev server running at ${t.url} (${a.join(", ")})`),t.studioUrl!==void 0&&n.info(` Studio: ${t.studioUrl}`),t.logFile!==void 0&&n.info(` Logs: lunora dev logs (${t.logFile})`),{code:0}},ct=e=>{const{cwd:r,logger:n}=e,t=O(r),o=ye(r,t);if(!N(o))return n.info("No dev server logs found — output is captured when the server runs in background mode (`lunora dev --background`)."),{code:0};const i=Se(o,e.lines??Yr);return i.length>0&&process.stdout.write(`${i.join(`
5
5
  `)}
6
- `),{code:0}},ct=e=>{const{cwd:r,json:n,lines:t,logger:o,subcommand:i}=e;if(i==="stop")return it({cwd:r,json:n,logger:o});if(i==="status")return st({cwd:r,json:n,logger:o});if(i==="logs")return at({cwd:r,lines:t,logger:o});if(i!==void 0)return o.error(`dev: unknown subcommand "${i}" — expected stop | status | logs (or no subcommand to start the dev server)`),{code:1}},X="wrangler.dev.jsonc",z=6173,S=8787,Q=5173,dt=5e3,lt=(e,r)=>{const n=()=>{};if(!e.remote)return{args:[],plan:{bindings:[],cleanup:n,enabled:!1}};const o=(e.materializeRemote??er)({enabled:!0,projectRoot:r}),i=o.remoteBindings.map(a=>`${a.binding} (${a.kind})`),{cleanup:s}=o;return o.configPath===void 0?{args:[],plan:{bindings:i,cleanup:s,enabled:!0,reason:o.reason}}:{args:["--config",o.configPath],plan:{bindings:i,cleanup:s,enabled:!0}}},Z=e=>ge(e).parsed?.dev?.ip,q=(e,r,n)=>{if(n!==void 0){const o=b(e,n);if($(o)&&Z(o)!==void 0)return[]}const t=fe(e);return t!==void 0&&Z(t)!==void 0?[]:r()?[]:["--ip","127.0.0.1"]},ut=new Set(["127.0.0.1","::1","[::1]","localhost"]),ft=(e,r)=>{let n;try{n=N(b(e,_),"utf8")}catch{return[]}const t=[];for(const o of Qe(n)){let i;try{i=new URL(o.value)}catch{continue}ut.has(i.hostname)&&i.port===String(r)&&t.push(o.key)}return t},gt=async(e,r)=>{if(e.workerPort!==void 0)return e.workerPort;const n=fe(r);if(n!==void 0){const{parsed:i}=ge(n);if(typeof i?.dev?.port=="number")return i.dev.port}const t=await(e.findFreePort??xr)(S);if(t===S)return t;const o=ft(r,S);if(o.length>0)throw new Error(`port ${String(S)} is in use, but ${_} pins the worker origin to it (${o.join(", ")}). Serving on ${String(t)} would leave those URLs pointing at nothing. Stop whatever holds ${String(S)}, or run \`lunora dev --worker-port ${String(t)}\` and update those values to match.`);return t},vt=e=>{const r=e.cwd??process.cwd(),n=de(r),t=e.flavor??F(r);if(t==="vite"||t==="framework-worker"){const g=he(r);let m;if(t==="framework-worker"){const p=q(r,e.hasIpv6Loopback??H,X),l=Ke(Ye(r)).toolchain?.dev({configPath:X,extraArgs:[...p,"--var","WORKER_ENV:development"]}),d=D(n,l?.tool??"wrangler",l?.args??[]);m={args:d.args,command:d.command,cwd:r,tag:"worker"}}return e.worker===!1&&e.logger.warn(`--no-worker does not apply to the ${t} flavor: Vite owns the worker, codegen and studio in-process. Run your framework's dev script instead.`),{runsCodegenWatch:!1,flavor:t,ipv4LoopbackForced:!1,remote:{bindings:[],cleanup:()=>{},enabled:e.remote===!0},...m?{sidecar:m}:{},studioEnabled:!1,studioPort:e.port??z,workerEnabled:!0,workerOrigin:`http://localhost:${String(Q)}`,workerPort:Q,wrangler:{args:g.args,command:g.command,cwd:r,...ke(e),tag:"vite"}}}const o=ae(r),i=o.framework==="none"?void 0:`this project uses ${o.framework} — the worker runs inside Vite there. run \`${Je(n,"dev")}\` for the full app (frontend + HMR); \`lunora dev\` starts only the worker.`,s=e.workerPort??S,a=lt(e,r),c=q(r,e.hasIpv6Loopback??H),u=D(n,"wrangler",["dev","--port",String(s),...c,"--var","WORKER_ENV:development",...a.args]);return{runsCodegenWatch:be(e),flavor:t,frameworkHint:i,ipv4LoopbackForced:c.length>0,remote:a.plan,studioEnabled:e.studio!==!1,studioPort:e.port??z,workerEnabled:e.worker!==!1,workerOrigin:`http://localhost:${String(s)}`,workerPort:s,wrangler:{args:u.args,command:u.command,cwd:r,tag:"wrangler"}}},ee=(e,r,n,t)=>{if(e.length===0)return;const o=Ze(e);if(o){t[o.level](`[lunora] ${o.text}`);return}const i=`[${r}] ${e}`;n==="stderr"?t.warn(i):t.info(i)},mt=(e,r,n)=>{const t=(o,i)=>{if(!o)return;let s="";o.on("data",a=>{s+=a.toString("utf8");const c=s.split(`
7
- `);s=c.pop()??"";for(const u of c)ee(u.trimEnd(),r,i,n)}),o.on("end",()=>{ee(s.trimEnd(),r,i,n),s=""})};t(e.stdout,"stdout"),t(e.stderr,"stderr")},pt=(e,r)=>{const n=ve(e.command,e.args),t=re(n.command,n.args,{cwd:e.cwd??process.cwd(),env:e.env?{...process.env,...e.env}:process.env,shell:n.shell,stdio:["inherit","pipe","pipe"]});return mt(t,e.tag,r),{exited:new Promise(o=>{t.on("error",i=>{r.error(`[${e.tag}] failed to start: ${i.message}`),o(1)}),t.on("exit",(i,s)=>{o(i??(s?1:0))})}),kill:o=>{try{t.kill(o)}catch{}}}},wt=(e,r,n,t)=>{e.info(""),e.success("Lunora dev"),e.info(` ➜ Worker: ${r.workerOrigin}`),n!==void 0&&e.info(` ➜ Studio: ${n}`),r.runsCodegenWatch&&e.info(" ➜ Codegen: watching lunora/"),t!==void 0&&e.info(` ➜ Supervisor: ${t} (needs) · ${ue} (status)`),r.remote.enabled&&(r.remote.bindings.length>0?e.info(` ➜ Remote: ${r.remote.bindings.join(", ")} → deployed worker`):e.warn(` ➜ Remote: requested but inactive (${r.remote.reason??"no eligible bindings"}) — running fully local`)),e.info("")},ht=(e,r)=>{ie(r).installed||!He()||(e.info(` ⓘ ${Be}`),e.info(""))},St=(e,r)=>{if(process.env.LUNORA_CONTAINER_LOGS==="0")return;const t=Xe(e,"lunora").containers.map(o=>({className:o.className,exportName:o.exportName}));if(t.length!==0)return ze({containers:t,onLine:o=>{const i=`[container:${o.name}] ${o.text}`;o.level==="error"?r.warn(i):r.info(i)},onUnavailable:o=>{r.warn(`[container] Docker engine unreachable — container logs unavailable (${o})`)}})},yt=async e=>{e.readyProbe?.abort(),await e.codegen?.close().catch(()=>{}),e.containerLogs?.close(),await e.studio?.close().catch(()=>{});try{e.remoteCleanup?.()}catch{}},Et=async(e,r)=>{try{const t=await Me({projectRoot:r}),o=xe(t),i=(e.ensureExample??Fe)(r,o);i.length>0&&e.logger.info(`Updated .dev.vars.example with secrets for: ${o.join(", ")} (${i.join(", ")})`)}catch{}(await(e.ensureEnv??je)({confirm:Ir(),cwd:r,info:t=>{e.logger.info(t)}})).status==="declined"&&!Ge()&&e.logger.info(`hint: ${_} was not scaffolded (non-interactive run). Copy ${Ue} → ${_} and fill in secrets, or run \`lunora dev\` in an interactive terminal to scaffold automatically.`);try{(e.fillSecrets??Ve)({cwd:r,info:t=>{e.logger.info(t)}})}catch{}},bt=(e,r,n,t,o)=>{if(e.flavor!=="wrangler")return;t!==void 0&&C(r,{studioUrl:t});let i;try{i=St(r,n)}catch{}return wt(n,e,t,o),i},kt=(e,r)=>{const n=Number(process.env[R]),t=se(r,{background:process.env[M]==="1",logFile:process.env[ce],mode:"cli",pid:process.pid,startedAt:new Date().toISOString(),url:e.workerOrigin},Number.isInteger(n)&&n>0?{supersedePid:n}:void 0);return t.ok?void 0:t.existing},Tt=e=>{const{cwd:r,destination:n,logger:t,plan:o}=e,i=n!==void 0,s=n??We,a=nr({destination:s,dev:{...o.flavor==="wrangler"?{origin:o.workerOrigin}:{},statusFile:ue},logger:i?t:{...t,success:()=>{},warn:()=>{}},projectRoot:r});return a.error!==void 0?i?a:(t.debug?.(`skipped the default binding manifest: ${a.error}`),{}):{written:s}},Rt=async e=>{const r=e.cwd??process.cwd(),n=e.flavor??F(r),t=n==="wrangler"?await gt(e,r):e.workerPort;return vt({...e,cwd:r,flavor:n,workerPort:t})},_t=async e=>await new Promise(r=>{const n={},t=s=>{e.info(`received ${s} — shutting down`),n.sigint&&process.off("SIGINT",n.sigint),n.sigterm&&process.off("SIGTERM",n.sigterm),r(0)},o=()=>{t("SIGINT")},i=()=>{t("SIGTERM")};n.sigint=o,n.sigterm=i,process.on("SIGINT",o),process.on("SIGTERM",i)}),Lt=async(e,r,n)=>{let t=0,o;const i=u=>{e.kill(u),r?.kill(u)},s=()=>{t+=1,t===1?(n.info("received SIGINT — shutting down (press Ctrl-C again to force-kill)"),i("SIGTERM"),o=setTimeout(()=>{i("SIGKILL")},dt),o.unref()):i("SIGKILL")},a=()=>{i("SIGTERM")};process.on("SIGINT",s),process.on("SIGTERM",a);const c=await Promise.race([e.exited.then(u=>({code:u,who:"worker"})),...r===void 0?[]:[r.exited.then(u=>({code:u,who:"sidecar"}))]]);return r!==void 0&&(c.who==="sidecar"?(n.warn("[worker] the Lunora sidecar (wrangler dev) exited — shutting down the framework dev server"),e.kill("SIGTERM")):r.kill("SIGTERM"),await Promise.allSettled([e.exited,r.exited])),o&&clearTimeout(o),process.off("SIGINT",s),process.off("SIGTERM",a),c.code},It=async(e,r,n,t)=>{if(r.studioEnabled)try{return await(e.startStudio??Gr)({cwd:n,logger:{warnOnce:o=>{t.warn(o)}},port:r.studioPort,workerOrigin:r.workerOrigin})}catch(o){t.warn(`studio server failed to start (${o instanceof Error?o.message:String(o)}) — continuing without it`);return}},Ot=e=>{const r=[e.runsCodegenWatch?"codegen watch":void 0,e.studioEnabled?"studio":void 0].filter(t=>t!==void 0);return`--no-worker: not starting wrangler. ${r.length>0?`${r.join(" + ")} running`:"nothing else to run"}; your task runner owns the worker on ${e.workerOrigin}.`},Pt=(e,r,n,t,o)=>{if(!(e.sidecar===void 0||!be(r)))try{oe({apiSpec:r.apiSpec,lunoraDirectory:"lunora",projectRoot:n,target:o})}catch(i){t.warn(`codegen (pre-sidecar) failed: ${i instanceof Error?i.message:String(i)} — the framework dev server will retry`)}},Dt=async e=>{const r=await Rt(e),{logger:n}=e,t=r.wrangler.cwd??process.cwd(),o=tr(t,e.target);if(o.target===void 0)throw new Error(o.error??"unknown deploy target");const{target:i}=o,s={remoteCleanup:r.remote.cleanup};try{const a=Number(process.env[R]),c=P(t);if(c!==void 0&&c.pid!==process.pid&&c.pid!==a)return I(n,c),{code:0,plan:r};const u=kt(r,t);if(u!==void 0)return I(n,u),{code:0,plan:r};(r.flavor==="vite"||r.flavor==="framework-worker")&&(r.wrangler.env={...r.wrangler.env,[R]:String(process.pid)}),await Et(e,t),n.info(r.flavor==="vite"?"starting vite dev (worker + studio + codegen run inside Vite via @lunora/vite)":"starting wrangler dev + studio"),r.ipv4LoopbackForced&&n.info("no IPv6 loopback (::1) on this host — binding the worker to 127.0.0.1 (--ip) so wrangler dev doesn't crash. Pin `dev.ip` in wrangler.jsonc to override."),r.runsCodegenWatch&&(s.codegen=(e.startCodegen??$r)({apiSpec:e.apiSpec,jsonLogs:e.jsonLogs,logger:n,projectRoot:t,target:i})),s.studio=await It(e,r,t,n);const g=Tt({cwd:t,destination:e.emitBindings,logger:n,plan:r});if(g.error!==void 0)return n.error(g.error),{code:1,plan:r};await s.codegen?.ready;const m=s.studio?.url;r.frameworkHint!==void 0&&n.warn(r.frameworkHint);const p=()=>{r.flavor==="wrangler"&&(s.readyProbe=new AbortController,Hr({cwd:t,logger:n,origin:r.workerOrigin,probe:e.probeReady,signal:s.readyProbe.signal}))};if(!r.workerEnabled)return p(),n.info(Ot(r)),{code:await(e.waitForInterrupt??_t)(n),plan:r};Pt(r,e,t,n,i);const l=e.startWorker??pt,d=l(r.wrangler,n),f=r.sidecar===void 0?void 0:l(r.sidecar,n);return p(),s.containerLogs=bt(r,t,n,m,g.written),ht(n,t),{code:await Lt(d,f,n),plan:r}}finally{s.readyProbe?.abort(),y(t,process.pid),await yt(s)}},qt=sr(async({argument:e,cwd:r,logger:n,options:t})=>{const o=t.json===!0,i=ct({cwd:r,json:o,lines:t.lines,logger:n,subcommand:e[0]});if(i!==void 0)return i;const s=process.env[M]==="1",a=s?void 0:Ne(),c=o||a!==void 0;c&&dr(),a!==void 0&&t.background!==!0&&n.info(`AI agent detected (${a.name} via ${a.variable}) — starting the dev server in background mode with JSON logs. Set LUNORA_AGENT_MODE=0 to opt out.`);const u=qe({configPreference:Ce(r),envValue:process.env.LUNORA_REMOTE,flag:t.remote});if(!s&&(t.background===!0||a!==void 0)){const g=P(r);return g!==void 0?(I(n,g),{code:0}):rt({cwd:r,jsonLogs:c,logger:n,options:t,remote:u})}return Dt({apiSpec:rr(t.apiSpec),codegen:t.codegen===!1?!1:void 0,cwd:r,emitBindings:t.emitBindings,jsonLogs:c,logger:n,port:t.port,remote:u,studio:t.studio===!1?!1:void 0,target:t.target,workerPort:t.workerPort})});export{pt as defaultWorkerSpawner,F as detectDevFlavor,qt as execute,vt as planDevCommand,gt as resolveWorkerPort,Dt as runDevCommand};
6
+ `),{code:0}},dt=e=>{const{cwd:r,json:n,lines:t,logger:o,subcommand:i}=e;if(i==="stop")return st({cwd:r,json:n,logger:o});if(i==="status")return at({cwd:r,json:n,logger:o});if(i==="logs")return ct({cwd:r,lines:t,logger:o});if(i!==void 0)return o.error(`dev: unknown subcommand "${i}" — expected stop | status | logs (or no subcommand to start the dev server)`),{code:1}},X="wrangler.dev.jsonc",z=6173,S=8787,Q=5173,lt=5e3,ut=(e,r)=>{const n=()=>{};if(!e.remote)return{args:[],plan:{bindings:[],cleanup:n,enabled:!1}};const o=(e.materializeRemote??er)({enabled:!0,projectRoot:r}),i=o.remoteBindings.map(a=>`${a.binding} (${a.kind})`),{cleanup:s}=o;return o.configPath===void 0?{args:[],plan:{bindings:i,cleanup:s,enabled:!0,reason:o.reason}}:{args:["--config",o.configPath],plan:{bindings:i,cleanup:s,enabled:!0}}},Z=e=>ge(e).parsed?.dev?.ip,q=(e,r,n)=>{if(n!==void 0){const o=b(e,n);if(N(o)&&Z(o)!==void 0)return[]}const t=fe(e);return t!==void 0&&Z(t)!==void 0?[]:r()?[]:["--ip","127.0.0.1"]},ft=new Set(["127.0.0.1","::1","[::1]","localhost"]),gt=(e,r)=>{let n;try{n=C(b(e,_),"utf8")}catch{return[]}const t=[];for(const o of Qe(n)){let i;try{i=new URL(o.value)}catch{continue}ft.has(i.hostname)&&i.port===String(r)&&t.push(o.key)}return t},vt=async(e,r)=>{if(e.workerPort!==void 0)return e.workerPort;const n=fe(r);if(n!==void 0){const{parsed:i}=ge(n);if(typeof i?.dev?.port=="number")return i.dev.port}const t=await(e.findFreePort??Fr)(S);if(t===S)return t;const o=gt(r,S);if(o.length>0)throw new Error(`port ${String(S)} is in use, but ${_} pins the worker origin to it (${o.join(", ")}). Serving on ${String(t)} would leave those URLs pointing at nothing. Stop whatever holds ${String(S)}, or run \`lunora dev --worker-port ${String(t)}\` and update those values to match.`);return t},mt=e=>{const r=e.cwd??process.cwd(),n=de(r),t=e.flavor??D(r);if(t==="vite"||t==="framework-worker"){const g=he(r);let m;if(t==="framework-worker"){const p=q(r,e.hasIpv6Loopback??H,X),l=Ke(Ye(r)).toolchain?.dev({configPath:X,extraArgs:[...p,"--var","WORKER_ENV:development"]}),c=A(n,l?.tool??"wrangler",l?.args??[]);m={args:c.args,command:c.command,cwd:r,tag:"worker"}}return e.worker===!1&&e.logger.warn(`--no-worker does not apply to the ${t} flavor: Vite owns the worker, codegen and studio in-process. Run your framework's dev script instead.`),{runsCodegenWatch:!1,flavor:t,ipv4LoopbackForced:!1,remote:{bindings:[],cleanup:()=>{},enabled:e.remote===!0},...m?{sidecar:m}:{},studioEnabled:!1,studioPort:e.port??z,workerEnabled:!0,workerOrigin:`http://localhost:${String(Q)}`,workerPort:Q,wrangler:{args:g.args,command:g.command,cwd:r,...ke(e),tag:"vite"}}}const o=ae(r),i=o.framework==="none"?void 0:`this project uses ${o.framework} — the worker runs inside Vite there. run \`${Je(n,"dev")}\` for the full app (frontend + HMR); \`lunora dev\` starts only the worker.`,s=e.workerPort??S,a=ut(e,r),d=q(r,e.hasIpv6Loopback??H),u=A(n,"wrangler",["dev","--port",String(s),...d,"--var","WORKER_ENV:development",...a.args]);return{runsCodegenWatch:be(e),flavor:t,frameworkHint:i,ipv4LoopbackForced:d.length>0,remote:a.plan,studioEnabled:e.studio!==!1,studioPort:e.port??z,workerEnabled:e.worker!==!1,workerOrigin:`http://localhost:${String(s)}`,workerPort:s,wrangler:{args:u.args,command:u.command,cwd:r,tag:"wrangler"}}},ee=(e,r,n,t)=>{if(e.length===0)return;const o=Ze(e);if(o){t[o.level](`[lunora] ${o.text}`);return}const i=`[${r}] ${e}`;n==="stderr"?t.warn(i):t.info(i)},pt=(e,r,n)=>{const t=(o,i)=>{if(!o)return;let s="";o.on("data",a=>{s+=a.toString("utf8");const d=s.split(`
7
+ `);s=d.pop()??"";for(const u of d)ee(u.trimEnd(),r,i,n)}),o.on("end",()=>{ee(s.trimEnd(),r,i,n),s=""})};t(e.stdout,"stdout"),t(e.stderr,"stderr")},wt=(e,r)=>{const n=ve(e.command,e.args),t=re(n.command,n.args,{cwd:e.cwd??process.cwd(),env:e.env?{...process.env,...e.env}:process.env,shell:n.shell,stdio:["inherit","pipe","pipe"]});return pt(t,e.tag,r),{exited:new Promise(o=>{t.on("error",i=>{r.error(`[${e.tag}] failed to start: ${i.message}`),o(1)}),t.on("exit",(i,s)=>{o(i??(s?1:0))})}),kill:o=>{try{t.kill(o)}catch{}}}},ht=(e,r,n,t)=>{e.info(""),e.success("Lunora dev"),e.info(` ➜ Worker: ${r.workerOrigin}`),n!==void 0&&e.info(` ➜ Studio: ${n}`),r.runsCodegenWatch&&e.info(" ➜ Codegen: watching lunora/"),t!==void 0&&e.info(` ➜ Supervisor: ${t} (needs) · ${ue} (status)`),r.remote.enabled&&(r.remote.bindings.length>0?e.info(` ➜ Remote: ${r.remote.bindings.join(", ")} → deployed worker`):e.warn(` ➜ Remote: requested but inactive (${r.remote.reason??"no eligible bindings"}) — running fully local`)),e.info("")},St=(e,r)=>{ie(r).installed||!He()||(e.info(` ⓘ ${Be}`),e.info(""))},yt=(e,r)=>{if(process.env.LUNORA_CONTAINER_LOGS==="0")return;const t=Xe(e,"lunora").containers.map(o=>({className:o.className,exportName:o.exportName}));if(t.length!==0)return ze({containers:t,onLine:o=>{const i=`[container:${o.name}] ${o.text}`;o.level==="error"?r.warn(i):r.info(i)},onUnavailable:o=>{r.warn(`[container] Docker engine unreachable — container logs unavailable (${o})`)}})},Et=async e=>{e.readyProbe?.abort(),await e.codegen?.close().catch(()=>{}),e.containerLogs?.close(),await e.studio?.close().catch(()=>{});try{e.remoteCleanup?.()}catch{}},bt=async(e,r)=>{try{const t=await Me({projectRoot:r}),o=xe(t),i=(e.ensureExample??Fe)(r,o);i.length>0&&e.logger.info(`Updated .dev.vars.example with secrets for: ${o.join(", ")} (${i.join(", ")})`)}catch{}(await(e.ensureEnv??je)({confirm:Ir(),cwd:r,info:t=>{e.logger.info(t)}})).status==="declined"&&!Ge()&&e.logger.info(`hint: ${_} was not scaffolded (non-interactive run). Copy ${Ue} → ${_} and fill in secrets, or run \`lunora dev\` in an interactive terminal to scaffold automatically.`);try{(e.fillSecrets??Ve)({cwd:r,info:t=>{e.logger.info(t)}})}catch{}},kt=(e,r,n,t,o)=>{if(e.flavor!=="wrangler")return;t!==void 0&&M(r,{studioUrl:t});let i;try{i=yt(r,n)}catch{}return ht(n,e,t,o),i},Tt=(e,r)=>{const n=Number(process.env[R]),t=se(r,{background:process.env[x]==="1",logFile:process.env[ce],mode:"cli",pid:process.pid,startedAt:new Date().toISOString(),url:e.workerOrigin},Number.isInteger(n)&&n>0?{supersedePid:n}:void 0);return t.ok?void 0:t.existing},Rt=e=>{const{cwd:r,destination:n,logger:t,plan:o}=e,i=n!==void 0,s=n??We,a=nr({destination:s,dev:{...o.flavor==="wrangler"?{origin:o.workerOrigin}:{},statusFile:ue},logger:i?t:{...t,success:()=>{},warn:()=>{}},projectRoot:r});return a.error!==void 0?i?a:(t.debug?.(`skipped the default binding manifest: ${a.error}`),{}):{written:s}},_t=async e=>{const r=e.cwd??process.cwd(),n=e.flavor??D(r),t=n==="wrangler"?await vt(e,r):e.workerPort;return mt({...e,cwd:r,flavor:n,workerPort:t})},Lt=async e=>await new Promise(r=>{const n={},t=s=>{e.info(`received ${s} — shutting down`),n.sigint&&process.off("SIGINT",n.sigint),n.sigterm&&process.off("SIGTERM",n.sigterm),r(0)},o=()=>{t("SIGINT")},i=()=>{t("SIGTERM")};n.sigint=o,n.sigterm=i,process.on("SIGINT",o),process.on("SIGTERM",i)}),It=async(e,r,n)=>{let t=0,o;const i=u=>{e.kill(u),r?.kill(u)},s=()=>{t+=1,t===1?(n.info("received SIGINT — shutting down (press Ctrl-C again to force-kill)"),i("SIGTERM"),o=setTimeout(()=>{i("SIGKILL")},lt),o.unref()):i("SIGKILL")},a=()=>{i("SIGTERM")};process.on("SIGINT",s),process.on("SIGTERM",a);const d=await Promise.race([e.exited.then(u=>({code:u,who:"worker"})),...r===void 0?[]:[r.exited.then(u=>({code:u,who:"sidecar"}))]]);return r!==void 0&&(d.who==="sidecar"?(n.warn("[worker] the Lunora sidecar (wrangler dev) exited — shutting down the framework dev server"),e.kill("SIGTERM")):r.kill("SIGTERM"),await Promise.allSettled([e.exited,r.exited])),o&&clearTimeout(o),process.off("SIGINT",s),process.off("SIGTERM",a),d.code},Ot=async(e,r,n,t)=>{if(r.studioEnabled)try{return await(e.startStudio??Ur)({cwd:n,logger:{warnOnce:o=>{t.warn(o)}},port:r.studioPort,workerOrigin:r.workerOrigin})}catch(o){t.warn(`studio server failed to start (${o instanceof Error?o.message:String(o)}) — continuing without it`);return}},Pt=e=>{const r=[e.runsCodegenWatch?"codegen watch":void 0,e.studioEnabled?"studio":void 0].filter(t=>t!==void 0);return`--no-worker: not starting wrangler. ${r.length>0?`${r.join(" + ")} running`:"nothing else to run"}; your task runner owns the worker on ${e.workerOrigin}.`},Dt=(e,r,n,t,o)=>{if(!(e.sidecar===void 0||!be(r)))try{oe({apiSpec:r.apiSpec,lunoraDirectory:"lunora",projectRoot:n,target:o})}catch(i){t.warn(`codegen (pre-sidecar) failed: ${i instanceof Error?i.message:String(i)} — the framework dev server will retry`)}},At=async e=>{const{logger:r}=e,n=e.cwd??process.cwd(),t=e.flavor??D(n),o=tr(n,e.target);if(o.target===void 0)throw new Error(o.error??"unknown deploy target");const{target:i}=o;t==="wrangler"&&await Or(n,r,void 0,i,void 0);const s=await _t({...e,flavor:t}),a={remoteCleanup:s.remote.cleanup};try{const d=Number(process.env[R]),u=P(n);if(u!==void 0&&u.pid!==process.pid&&u.pid!==d)return I(r,u),{code:0,plan:s};const g=Tt(s,n);if(g!==void 0)return I(r,g),{code:0,plan:s};(s.flavor==="vite"||s.flavor==="framework-worker")&&(s.wrangler.env={...s.wrangler.env,[R]:String(process.pid)}),await bt(e,n),r.info(s.flavor==="vite"?"starting vite dev (worker + studio + codegen run inside Vite via @lunora/vite)":"starting wrangler dev + studio"),s.ipv4LoopbackForced&&r.info("no IPv6 loopback (::1) on this host — binding the worker to 127.0.0.1 (--ip) so wrangler dev doesn't crash. Pin `dev.ip` in wrangler.jsonc to override."),s.runsCodegenWatch&&(a.codegen=(e.startCodegen??Nr)({apiSpec:e.apiSpec,jsonLogs:e.jsonLogs,logger:r,projectRoot:n,target:i})),a.studio=await Ot(e,s,n,r);const m=Rt({cwd:n,destination:e.emitBindings,logger:r,plan:s});if(m.error!==void 0)return r.error(m.error),{code:1,plan:s};await a.codegen?.ready;const p=a.studio?.url;s.frameworkHint!==void 0&&r.warn(s.frameworkHint);const l=()=>{s.flavor==="wrangler"&&(a.readyProbe=new AbortController,Br({cwd:n,logger:r,origin:s.workerOrigin,probe:e.probeReady,signal:a.readyProbe.signal}))};if(!s.workerEnabled)return l(),r.info(Pt(s)),{code:await(e.waitForInterrupt??Lt)(r),plan:s};Dt(s,e,n,r,i);const c=e.startWorker??wt,f=c(s.wrangler,r),w=s.sidecar===void 0?void 0:c(s.sidecar,r);return l(),a.containerLogs=kt(s,n,r,p,m.written),St(r,n),{code:await It(f,w,r),plan:s}}finally{a.readyProbe?.abort(),y(n,process.pid),await Et(a)}},rn=sr(async({argument:e,cwd:r,logger:n,options:t})=>{const o=t.json===!0,i=dt({cwd:r,json:o,lines:t.lines,logger:n,subcommand:e[0]});if(i!==void 0)return i;const s=process.env[x]==="1",a=s?void 0:Ne(),d=o||a!==void 0;d&&dr(),a!==void 0&&t.background!==!0&&n.info(`AI agent detected (${a.name} via ${a.variable}) — starting the dev server in background mode with JSON logs. Set LUNORA_AGENT_MODE=0 to opt out.`);const u=qe({configPreference:Ce(r),envValue:process.env.LUNORA_REMOTE,flag:t.remote});if(!s&&(t.background===!0||a!==void 0)){const g=P(r);return g!==void 0?(I(n,g),{code:0}):tt({cwd:r,jsonLogs:d,logger:n,options:t,remote:u})}return At({apiSpec:rr(t.apiSpec),codegen:t.codegen===!1?!1:void 0,cwd:r,emitBindings:t.emitBindings,jsonLogs:d,logger:n,port:t.port,remote:u,studio:t.studio===!1?!1:void 0,target:t.target,workerPort:t.workerPort})});export{wt as defaultWorkerSpawner,D as detectDevFlavor,rn as execute,mt as planDevCommand,vt as resolveWorkerPort,At as runDevCommand};
@@ -1 +1,7 @@
1
- import{readFileSync as w,writeFileSync as O,existsSync as y}from"node:fs";import{runCodegen as H,discoverMigrations as B}from"@lunora/codegen";import{readLinkedProject as N,writeLinkedProject as M,execArgsFor as k,detectPackageManager as b,discoverContainerInfo as L,DEV_VARS_FILE as v,parseDevVariableEntries as T,isMintableSecretKey as E,runPostCodegenHook as W,resolveDeployDriver as D,inferLunoraBindings as _,packageNamesFromBindings as V,requiredSecrets as K,generateSecretValue as q,upsertDevVariableLine as Y,writeDevVariablesFileAtomically as G,discoverSchemaInfo as z}from"@lunora/config";import{findWranglerFile as j,validateWranglerProject as J,reconcileWranglerBindings as Q,reconcileWranglerCompatibilityDate as X,reconcileWranglerCrons as Z,readWranglerJsonc as ee}from"@lunora/config/cloudflare";import{join as h}from"@visulima/path";import{Spinner as re}from"@visulima/spinner";import{Project as te}from"ts-morph";import{i as ae,m as ne,e as oe}from"../packem_shared/vectorize-metadata-dXpl2_Ar.mjs";import{r as ie,e as se}from"../packem_shared/advisory-gate-Cl8IEFIj.mjs";import{p as ce,a as le}from"../packem_shared/deploy-target-B0Xcb2jV.mjs";import{r as R}from"../packem_shared/wrangler-name-Dsk5K1f-.mjs";import{w as de}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{d as ue}from"../packem_shared/command-DwC11Cwe.mjs";import{a as ge,i as me}from"../packem_shared/docker-DpVxvYpL.mjs";import{r as fe,p as he,H as ve,a as ye}from"../packem_shared/schema-drift-gate-BDCkQ1S6.mjs";import{v as pe,i as $,p as we,l as ke}from"../packem_shared/output-format-DfogXx0p.mjs";import{r as be}from"../packem_shared/platform-diagnostics-D0YzAdXm.mjs";import{containerBuildTag as $e}from"@lunora/container";import{defaultSpawner as S}from"../packem_shared/createRecordingSpawner-DJlNacZ6.mjs";import{a as I}from"../packem_shared/resolve-target-BRvw8Pf7.mjs";import{c as Se}from"../packem_shared/tui-prompts-Dd0pDuNr.mjs";import{l as De}from"../packem_shared/wrangler-secrets-CCdt0mUl.mjs";import{runMigrateDataCommand as Re}from"./runMigrateGenerateCommand.mjs";const Ce=/https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u,Ae=/https:\/\/[^\s"'<>]+/u,Ee=e=>{if(e===void 0)return;const r=Ce.exec(e);return r?r[0]:Ae.exec(e)?.[0]},P=e=>e===void 0?"":` (--env ${e})`,Pe=({cwd:e,env:r,logger:t,now:a,url:n})=>{if(n!==void 0)try{const o=N(e);if(o!==void 0){if(o.workerUrl===n&&o.env===r)return;t.warn(`link: .lunora/project.json records ${o.workerUrl??"(no url)"}${P(o.env)}, but this deploy published ${n}${P(r)}. Keeping the recorded value — run \`lunora link --url ${n}${r===void 0?"":` --env ${r}`}\` to update it.`);return}const i=(a??(()=>new Date().toISOString()))();M(e,{env:r,linkedAt:i,workerName:R(e),workerUrl:n}),t.success(`link: recorded ${n} in .lunora/project.json (run \`lunora link\` to change)`)}catch{}},xe=e=>{const{cwd:r,env:t,logger:a,mintedSecretsFile:n}=e;try{const o=N(r),i=o?.workerName??R(r),s=e.url??o?.workerUrl;a.success("deploy complete"),a.info(` worker: ${i??"(see wrangler output above)"}`),t!==void 0&&a.info(` env: ${t}`),s===void 0?a.info(" url: run `lunora link --url <https://your-worker>` to record it"):a.info(` url: ${s}`),n!==void 0&&a.info(` secrets: generated value(s) recorded in ${n}`),a.info(" logs: lunora logs")}catch{}},Ne=async e=>{if(e.targets.length===0)return{builtTags:[],code:0};if(!(e.railpackAvailable??ge)()){const a="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(a),{builtTags:[],code:1,error:a}}const r=e.spawner??S,t=[];for(const a of e.targets){const n=$e(a.exportName),o={args:["build",a.buildDir,"--name",n],command:"railpack",cwd:e.cwd},i=k(b(e.cwd),"wrangler",["containers","push",n]),s={args:i.args,command:i.command,cwd:e.cwd};e.logger.info(`railpack: building "${a.exportName}" → ${n} from ${a.buildDir}`);const l=await r(o);if(l.code!==0){const c=`railpack build failed for container "${a.exportName}" (${a.buildDir})`;return e.logger.error(c),{builtTags:t,code:l.code,error:c}}e.logger.info(`railpack: pushing ${n} to the Cloudflare Registry`);const d=await r(s);if(d.code!==0){const c=`wrangler containers push failed for "${a.exportName}" (${n})`;return e.logger.error(c),{builtTags:t,code:d.code,error:c}}t.push(n)}return{builtTags:t,code:0}},Le=e=>{const r=j(e),t=r===void 0?void 0:w(r,"utf8");return()=>{r!==void 0&&t!==void 0&&O(r,t,"utf8")}},U="<replace-with-d1-create-id>",C=e=>{const r=j(e);return r?ee(r).parsed:void 0},Te=["LUNORA_ORIGIN_URL","LUNORA_WORKER_ORIGIN","AUTH_URL"],_e=e=>{try{const{hostname:r}=new URL(e);return r==="localhost"||r==="127.0.0.1"||r==="::1"||r==="[::1]"}catch{return!1}},je=e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"),Ie=(e,r,t,a="deploy")=>{const n=(C(e)?.containers??[]).filter(i=>typeof i?.image=="string"&&je(i.image));if(n.length===0||t())return;const o=`${a} blocked: wrangler.jsonc declares ${String(n.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(o),o},Ue=e=>y(h(e,"src","worker.ts"))?"src/worker.ts":void 0,Fe=(e,r,t="deploy")=>{for(const a of L(e,"lunora").containers){const{image:n}=a;if(n.kind==="dockerfile"&&!y(h(e,n.dockerfilePath))){const o=`${t} blocked: container "${a.exportName}" references a Dockerfile at "${n.dockerfilePath}" that does not exist. Create it or fix the \`image\` path in lunora/containers.ts.`;return r.error(o),o}if(n.kind==="build"&&!y(h(e,n.buildDir))){const o=`${t} blocked: container "${a.exportName}" references a Railpack build directory "${n.buildDir}" that does not exist. Create it or fix the \`image.build\` path in lunora/containers.ts.`;return r.error(o),o}}},F=e=>$(e.format)?!1:e.interactive!==void 0?e.interactive:process.stdout.isTTY&&!process.env.CI,Oe=e=>(C(e)?.d1_databases??[]).find(r=>r.database_id===U)?.binding,He=async(e,r)=>{if(r.dryRun===!0)return;const t=L(e,"lunora").containers.filter(n=>n.image.kind==="build").map(n=>({buildDir:n.image.buildDir,exportName:n.exportName}));if(t.length===0)return;const a=await Ne({cwd:e,logger:r.logger,railpackAvailable:r.railpackAvailable,spawner:r.spawner,targets:t});return a.code===0?void 0:a.error??"railpack build failed"},Be=(e,r,t)=>{if(t!==void 0)try{const a=Z(e,t);a.changed&&r.success(`synced ${String(t.length)} cron trigger(s) → ${a.wranglerPath??"wrangler.jsonc"}`)}catch(a){const n=a instanceof Error?a.message:String(a);r.warn(`cron trigger sync skipped: ${n}`)}},Me=async(e,r,t,a,n)=>{try{D(a);const o=await _({projectRoot:e}),i=Q(e,o,n);i.changed&&r.success(`provisioned bindings: ${i.added.join(", ")} → ${i.wranglerPath??"wrangler.jsonc"}`);for(const s of i.warnings)r.warn(s)}catch(o){const i=o instanceof Error?o.message:String(o);r.warn(`binding inference skipped: ${i}`)}try{const o=X(e);o.changed&&r.success(`bumped compatibility_date to ${o.date??"unknown"} (Workers Cache enabled) → ${o.wranglerPath??"wrangler.jsonc"}`)}catch(o){const i=o instanceof Error?o.message:String(o);r.warn(`compatibility date sync skipped: ${i}`)}Be(e,r,t)},We=(e,r)=>{const t=h(e,v);if(!y(t))return;let a;try{a=T(w(t,"utf8")).length}catch{return}a!==0&&r.warn(`Note: \`lunora deploy\` does not push secrets. ${v} has ${String(a)} key(s); if you changed them, run \`lunora env push --yes\` to update the deployed secrets.`)},Ve=async e=>{let r=[];try{r=V(await _({projectRoot:e}))}catch{}const t=K(r).map(n=>n.key);let a=[];try{const n=h(e,v);y(n)&&(a=T(w(n,"utf8")).map(o=>o.key).filter(o=>ae(o)))}catch{}return[...new Set([...t,...a])]},Ke=async(e,r,t,a)=>{const{logger:n}=r,o=r.spawner??S,i=b(e),s=r.env===void 0?"":` --env ${r.env}`,{toolchain:l}=D(a);if(l===void 0)return n.error("deploy target has no command-line toolchain; cannot push secrets"),{minted:[],ok:!1};const d=[];for(const c of t){const g=q(),u=l.secretPut({environment:r.env,key:c,temporary:r.temporary}),m=k(i,u.tool,u.args),f=await o({args:m.args,command:m.command,cwd:e,input:g});if(f.code!==0)return n.error(`failed to push secret ${c} (exit ${String(f.code)}); set it manually with \`wrangler secret put ${c}${s}\`.`),{minted:d,ok:!1};d.push({key:c,value:g}),n.success(`generated + pushed ${c}`)}return{minted:d,ok:!0}},qe=/^[\w-]+$/u,Ye=(e,r,t)=>{if(t.length===0)return;const a=t.map(s=>s.key).join(", ");if(r.env!==void 0&&!qe.test(r.env)){r.logger.warn(`${a}: minted and pushed for --env ${r.env}, but "${r.env}" isn't a safe filename fragment — the value could not be recorded. Capture it manually if you need it again.`);return}const n=r.env===void 0?v:`${v}.${r.env}`,o=h(e,n);let i=y(o)?w(o,"utf8"):"";for(const s of t)i=Y(i,s.key,s.value);return G(o,i),r.logger.success(r.env===void 0?`${a}: value(s) recorded in ${n}`:`${a}: value(s) recorded in ${n} (kept separate from ${v} so \`lunora dev\` and a plain \`lunora env push\` don't inherit the --env ${r.env} value)`),n},Ge=async(e,r,t,a)=>{if(r.dryRun===!0||r.preview===!0)return{};const{logger:n}=r,o=r.env===void 0?"":` --env ${r.env}`;let i;try{i=await(r.secretLister??De)({cwd:e,env:r.env,temporary:r.temporary})}catch{return{}}if(!i.ok)return{};const s=new Set(i.names),d=(await Ve(e)).filter(u=>!s.has(u));if(d.length===0)return{};if(!t)return{error:`missing required secret(s) on the deploy target: ${d.join(", ")}. Set them with \`wrangler secret put <KEY>${o}\` (or \`lunora env generate --set\` then \`lunora env push --yes${o}\`), then re-deploy.`};for(const u of d.filter(m=>!E(m)))n.warn(`required secret ${u} is not set on the target — set it with: wrangler secret put ${u}${o}`);const c=d.filter(u=>E(u));if(c.length===0)return{};if(await(r.secretConfirm??Se())(`${String(c.length)} required secret(s) not set on the target (${c.join(", ")}). Generate strong values and push them now?`)){const{minted:u,ok:m}=await Ke(e,r,c,a),f=Ye(e,r,u);return m?{mintedSecretsFile:f}:{error:"failed to push required secret(s) — set them manually and re-deploy",mintedSecretsFile:f}}return n.warn(`${String(c.length)} required secret(s) not set on the target: ${c.join(", ")}. Generate + push with \`lunora env generate --set\` then \`lunora env push --yes${o}\`.`),{}},ze=async(e,r)=>{const t=new te({skipAddingFilesFromTsConfig:!0}),a=h(r,"lunora");let n;try{n=B(t,a)}catch(o){const i=o instanceof Error?o.message:String(o);return e.logger.warn(`--migrate: could not discover migrations (${i}); skipping`),0}if(n.length===0)return e.logger.info("--migrate: no data migrations declared in lunora/"),0;e.logger.info(`--migrate: running ${String(n.length)} migration(s) against deployed worker`);for(const o of n){e.logger.info(`--migrate: up "${o.id}" (table "${o.table}")`);const i={cwd:r,fetchImpl:e.fetchImpl,id:o.id,logger:e.logger,prod:!0,subcommand:"up",token:e.migrateToken,url:e.migrateUrl,yes:e.migrateYes===!0},s=await Re(i);if(s.code!==0)return e.logger.error(`--migrate: migration "${o.id}" failed — see output above`),s.code;e.logger.success(`--migrate: "${o.id}" applied`)}return 0},Je=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}},Qe=async(e,r,t,a,n,o,i,s)=>{let l;r?(l=new re({name:"dots"}),l.start("running codegen")):t.info("running codegen");try{const d=H({apiSpec:a,projectRoot:e,target:n});l?.succeed("codegen complete"),l||t.success("codegen complete");const c=be(d.platformDiagnostics,t);if(c.errors.length>0)return{error:c.errors.join("; ")};const{errorAdvisories:g,names:u,shouldBlock:m}=se(d.advisories,s);if(m){const A=`${g.length.toString()} ERROR-level ${g.length===1?"advisory":"advisories"} (${u.join(", ")}). Pass --no-strict-advisories to downgrade this to a warning and deploy anyway.`;return t.error(A),{error:A}}const f=await W({cwd:e,logger:t,spawner:o,stdoutToStderr:i});return f.error!==void 0?{error:f.error}:{result:d}}catch(d){l?.failed("codegen failed");const c=d instanceof Error?d.message:String(d);return t.error(`codegen failed: ${c}`),{error:`codegen failed: ${c}`}}},Xe=(e,r,t="deploy")=>{const a=Oe(e);if(a===void 0)return;const n=`${t} blocked: the "${a}" D1 binding has a placeholder database_id ("${U}"). Run \`wrangler d1 create <name>\` to create the database, then replace the placeholder in wrangler.jsonc with the real id before deploying.`;return r.error(n),n},Ze=(e,r,t="deploy")=>{const a=C(e)?.vars;if(!a)return;const n=Te.filter(i=>typeof a[i]=="string"&&_e(a[i]));if(n.length===0)return;const o=`${t} blocked: ${n.join(", ")} in wrangler.jsonc point at localhost. A deployed Worker can't reach a loopback address, so this silently breaks scheduled-job dispatch / 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(o),o},er=async(e,r)=>{const{info:t}=z(r,"lunora"),a=t?.vectorMetadata??[];if(a.length===0)return;const n=[];for(const s of a){const l=ne(s.kind);if(l===void 0){e.logger.warn(`vector index "${s.index}" declares metadata "${s.property}", whose column type cannot be filtered on in Vectorize — it is stored with each vector but no filter will match it.`);continue}n.push({index:s.index,property:s.property,type:l})}if(n.length===0)return;const i=(await oe({cwd:r,entries:n,exec:k(b(r),"wrangler",[]),logger:e.logger,spawner:e.spawner??S})).filter(s=>s.status!=="failed").length;i>0&&e.logger.success(`vectorize metadata indexes ready: ${String(i)}/${String(n.length)}`)},x=5,rr=2e3,tr=async(e,r,t)=>{if(e.healthCheck!==!0)return;const a=t??I({cwd:r,env:e.env});if(a===void 0){const o="--health-check: the deploy succeeded, but no URL to probe could be resolved — wrangler's output carried none and this checkout has no link for this environment. Run `lunora link --url <https://your-worker>` and re-deploy, or drop --health-check.";return e.logger.error(o),{error:o,ok:!1,url:""}}const n=await he({attempts:x,baseUrl:a,delayMs:rr,fetchImpl:e.healthFetch,paths:[ve,ye],sleep:e.healthSleep});return n.error===void 0?(e.logger.success(`health check ok (${n.url})`),{ok:!0,url:n.url}):(e.logger.error(`--health-check: the deploy succeeded, but the new version did not answer after ${String(x)} attempt(s) — ${n.error}`),{error:n.error,ok:!1,url:n.url})},ar=async(e,r,t,a,n,o)=>{await er(e,r);const i=e.migrate?await ze(e,r):0;return i===0&&n?.(),{code:i,descriptor:t,mintedSecretsFile:o,validation:a}},nr=(e,r,t)=>{const a=Xe(e,r.logger,t);if(a!==void 0)return a;const n=Ze(e,r.logger,t);if(n!==void 0)return n;const o=Fe(e,r.logger,t);return o!==void 0?o:Ie(e,r.logger,r.dockerAvailable??me,t)},or=(e,r,t)=>{const a=Ue(e);a!==void 0&&r.logger.info(`class-B composition: deploying ${a} (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}`);const n=D(t),o={dryRun:r.dryRun,entry:a,environment:r.env,outDir:r.outDir,preview:r.preview,temporary:r.temporary};if(n.toolchain===void 0)throw new Error(`deploy target "${n.id}" has no command-line toolchain`);return n.toolchain.deploy(o)},p=(e,r)=>({code:1,descriptor:void 0,error:e,validation:{problems:[],wranglerPath:void 0},...r}),ir=(e,r)=>{if(e.problems.length===0)return!1;r.error("wrangler.jsonc validation failed:");for(const t of e.problems)r.error(` - ${t}`);return!0},sr=(e,r,t)=>{const a=$(r.format),n=r.dryRun!==!0,o=or(e,r,t),i=k(b(e),o.tool,o.args);return{args:i.args,captureStdout:n&&!a,captureStdoutSilently:n&&a,command:i.command,cwd:e,stdoutToStderr:a&&!n}},cr=async({cwd:e,descriptor:r,mintedSecretsFile:t,options:a,reblessSchemaBaseline:n,stdout:o,validation:i})=>{const s={deployedAt:new Date().toISOString(),dryRun:a.dryRun===!0,env:a.env,preview:a.preview===!0,url:a.dryRun===!0?void 0:Ee(o),workerName:R(e)};if(a.dryRun===!0||a.preview===!0)return a.healthCheck===!0&&a.logger.warn(`--health-check skipped: ${a.dryRun===!0?"a dry run publishes nothing":"a preview version serves no live traffic"}`),{code:0,deployment:s,descriptor:r,mintedSecretsFile:t,validation:i};a.temporary!==!0&&Pe({cwd:e,env:a.env,logger:a.logger,url:s.url});const l=await tr(a,e,s.url);return l?.error!==void 0?{code:1,deployment:s,descriptor:r,healthCheck:l,mintedSecretsFile:t,validation:i}:{...await ar(a,e,r,i,n,t),deployment:s,healthCheck:l}},lr=async(e,r)=>{const t=e.cwd??process.cwd(),a=F(e),n=ie(e),o={problems:[],wranglerPath:void 0},i=le(t,e.target);if(i.target===void 0){const u=i.error??"unknown deploy target";return e.logger.error(u),{error:u,validation:o}}const{target:s}=i;let l;if(!e.skipCodegen){const u=await Qe(t,a,e.logger,e.apiSpec,s,e.spawner,$(e.format),n);if(u.error!==void 0)return{error:u.error,target:s,validation:o};l=u.result}let d;if(l!==void 0){const u=fe({allowDrift:e.allowSchemaDrift===!0,codegen:l,command:r,logger:e.logger,updateBaseline:e.updateSchemaBaseline===!0});if(u.blocked)return{error:`schema drift gate blocked ${r}`,schemaDrift:{blocked:!0,reason:u.reason},target:s,validation:o};d=u.rebless}await Me(t,e.logger,l?.cronTriggers,s,e.env);const c=nr(t,e,r);if(c!==void 0)return{error:c,target:s,validation:o};const g=J({environment:e.env,projectRoot:t});return ir(g,e.logger)?{error:"wrangler validation failed",target:s,validation:g}:{codegen:l,reblessSchemaBaseline:d,target:s,validation:g}},dr=async e=>{const r=e.cwd??process.cwd(),t=F(e),a=await lr(e,e.commandName??"deploy");if(a.error!==void 0){if(a.validation.problems.length>0)return{code:1,descriptor:void 0,error:a.error,validation:a.validation};const f=a.schemaDrift===void 0?void 0:{schemaDrift:a.schemaDrift};return p(a.error,f)}const{reblessSchemaBaseline:n,validation:o}=a,i=a.target,s=Je(e);if(s!==void 0)return p(s);const l=await He(r,e);if(l!==void 0)return p(l);We(r,e.logger);const{error:d,mintedSecretsFile:c}=await Ge(r,e,t,i);if(d!==void 0)return e.logger.error(d),{code:1,descriptor:void 0,error:d,mintedSecretsFile:c,validation:o};const g=sr(r,e,i);e.logger.info(`deploying via ${g.command} ${g.args.join(" ")}`);const m=await(e.spawner??S)(g);return g.captureStdoutSilently===!0&&m.stdout!==void 0&&m.stdout!==""&&process.stderr.write(m.stdout),m.code!==0?{code:m.code,descriptor:g,mintedSecretsFile:c,validation:o}:cr({cwd:r,descriptor:g,mintedSecretsFile:c,options:e,reblessSchemaBaseline:n,stdout:m.stdout,validation:o})},ur=async e=>{const r=pe("deploy",e.format);if(r!==void 0)return e.logger.error(r),p(r);const t=ke(e.format,e.logger),a=e.dryRun===!0?Le(e.cwd??process.cwd()):void 0;let n;try{if(n=await dr({...e,logger:t}),n.code===0&&e.emitBindings!==void 0){const{error:o}=de({destination:e.emitBindings,logger:t,projectRoot:e.cwd??process.cwd()});o!==void 0&&(t.error(o),n={...n,code:1})}}finally{a?.()}if($(e.format))return we(n),n;if(n.code===0&&e.dryRun!==!0&&e.preview!==!0)xe({cwd:e.cwd??process.cwd(),env:e.env,logger:e.logger,mintedSecretsFile:n.mintedSecretsFile,url:n.deployment?.url});else if(n.code===0&&e.preview===!0){const o=n.deployment?.url;e.logger.success(o===void 0?"preview version uploaded":`preview version uploaded — ${o}`)}return n},jr=ue(async({cwd:e,logger:r,options:t})=>({code:(await ur({allowSchemaDrift:t.allowSchemaDrift===!0,apiSpec:ce(t.apiSpec),cwd:e,dryRun:t.dryRun===!0,env:t.env,format:t.format,healthCheck:t.healthCheck===!0,logger:r,migrate:t.migrate===!0,migrateToken:t.migrateToken,migrateUrl:I({cwd:e,env:t.env,url:t.migrateUrl}),migrateYes:t.migrateYes===!0,preview:t.preview===!0,skipCodegen:t.prebuilt===!0,strictAdvisories:t.strictAdvisories,target:t.target,temporary:t.temporary===!0,updateSchemaBaseline:t.updateSchemaBaseline===!0})).code}));export{jr as execute,ur as runDeployCommand,lr as runPreDeployPipeline};
1
+ import{readFileSync as p,writeFileSync as T,existsSync as v}from"node:fs";import{runCodegen as B,discoverMigrations as V}from"@lunora/codegen";import{readLinkedProject as L,writeLinkedProject as K,execArgsFor as k,detectPackageManager as b,discoverContainerInfo as I,DEV_VARS_FILE as y,parseDevVariableEntries as U,isMintableSecretKey as P,runPostCodegenHook as q,resolveDeployDriver as D,inferLunoraBindings as O,packageNamesFromBindings as G,requiredSecrets as Y,generateSecretValue as z,upsertDevVariableLine as J,writeDevVariablesFileAtomically as Q,COMPOSED_WORKER_ENTRY as _,discoverSchemaInfo as X}from"@lunora/config";import{findWranglerFile as W,validateWranglerProject as Z,reconcileWranglerBindings as ee,reconcileWranglerCompatibilityDate as re,reconcileWranglerCrons as te,readWranglerJsonc as ne,mergeWranglerEnvironment as ae}from"@lunora/config/cloudflare";import{join as h}from"@visulima/path";import{Spinner as oe}from"@visulima/spinner";import{Project as ie}from"ts-morph";import{i as se,m as ce,e as le}from"../packem_shared/vectorize-metadata-dXpl2_Ar.mjs";import{r as de,e as ue}from"../packem_shared/advisory-gate-Cl8IEFIj.mjs";import{p as ge,a as me}from"../packem_shared/deploy-target-B0Xcb2jV.mjs";import{r as E}from"../packem_shared/wrangler-name-Dsk5K1f-.mjs";import{w as fe}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{d as he}from"../packem_shared/command-DwC11Cwe.mjs";import{a as ve,i as ye}from"../packem_shared/docker-DpVxvYpL.mjs";import{r as pe,p as we,H as ke,a as be}from"../packem_shared/schema-drift-gate-BDCkQ1S6.mjs";import{v as $e,i as $,p as Se,l as Re}from"../packem_shared/output-format-DfogXx0p.mjs";import{r as De}from"../packem_shared/platform-diagnostics-D0YzAdXm.mjs";import{containerBuildTag as Ee}from"@lunora/container";import{defaultSpawner as S}from"../packem_shared/createRecordingSpawner-DJlNacZ6.mjs";import{a as F}from"../packem_shared/resolve-target-BRvw8Pf7.mjs";import{c as Ae}from"../packem_shared/tui-prompts-DzYd2fL3.mjs";import{l as Ce}from"../packem_shared/wrangler-secrets-CCdt0mUl.mjs";import{runMigrateDataCommand as Pe}from"./runMigrateGenerateCommand.mjs";const _e=/https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u,Ne=/https:\/\/[^\s"'<>]+/u,xe=e=>{if(e===void 0)return;const r=_e.exec(e);return r?r[0]:Ne.exec(e)?.[0]},N=e=>e===void 0?"":` (--env ${e})`,je=({cwd:e,env:r,logger:t,now:n,url:a})=>{if(a!==void 0)try{const o=L(e);if(o!==void 0){if(o.workerUrl===a&&o.env===r)return;t.warn(`link: .lunora/project.json records ${o.workerUrl??"(no url)"}${N(o.env)}, but this deploy published ${a}${N(r)}. Keeping the recorded value — run \`lunora link --url ${a}${r===void 0?"":` --env ${r}`}\` to update it.`);return}const i=(n??(()=>new Date().toISOString()))();K(e,{env:r,linkedAt:i,workerName:E(e),workerUrl:a}),t.success(`link: recorded ${a} in .lunora/project.json (run \`lunora link\` to change)`)}catch{}},Te=e=>{const{cwd:r,env:t,logger:n,mintedSecretsFile:a}=e;try{const o=L(r),i=o?.workerName??E(r),s=e.url??o?.workerUrl;n.success("deploy complete"),n.info(` worker: ${i??"(see wrangler output above)"}`),t!==void 0&&n.info(` env: ${t}`),s===void 0?n.info(" url: run `lunora link --url <https://your-worker>` to record it"):n.info(` url: ${s}`),a!==void 0&&n.info(` secrets: generated value(s) recorded in ${a}`),n.info(" logs: lunora logs")}catch{}},Le=async e=>{if(e.targets.length===0)return{builtTags:[],code:0};if(!(e.railpackAvailable??ve)()){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??S,t=[];for(const n of e.targets){const a=Ee(n.exportName),o={args:["build",n.buildDir,"--name",a],command:"railpack",cwd:e.cwd},i=k(b(e.cwd),"wrangler",["containers","push",a]),s={args:i.args,command:i.command,cwd:e.cwd};e.logger.info(`railpack: building "${n.exportName}" → ${a} from ${n.buildDir}`);const c=await r(o);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 ${a} to the Cloudflare Registry`);const l=await r(s);if(l.code!==0){const d=`wrangler containers push failed for "${n.exportName}" (${a})`;return e.logger.error(d),{builtTags:t,code:l.code,error:d}}t.push(a)}return{builtTags:t,code:0}},Ie=e=>{const r=W(e),t=r===void 0?void 0:p(r,"utf8");return()=>{r!==void 0&&t!==void 0&&T(r,t,"utf8")}},H="<replace-with-d1-create-id>",x=e=>Array.isArray(e)?e.filter(r=>r!=null):void 0,A=(e,r)=>{const t=W(e);if(!t)return;const{parsed:n}=ne(t);if(n===void 0)return;const{error:a,merged:o}=ae(n,r),i=a===void 0?o:n,{containers:s,d1_databases:c,vars:l}=i;return{containers:x(s),d1_databases:x(c),vars:typeof l=="object"&&l!==null&&!Array.isArray(l)?l:void 0}},Ue=["LUNORA_ORIGIN_URL","LUNORA_WORKER_ORIGIN","AUTH_URL"],Oe=e=>{try{const{hostname:r}=new URL(e);return r==="localhost"||r==="127.0.0.1"||r==="::1"||r==="[::1]"}catch{return!1}},We=e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"),Fe=(e,r,t,n="deploy",a)=>{const o=(A(e,a)?.containers??[]).filter(s=>typeof s?.image=="string"&&We(s.image));if(o.length===0||t())return;const i=`${n} blocked: wrangler.jsonc declares ${String(o.length)} container(s) built from a local Dockerfile, but no Docker-compatible engine is available. Start Docker (or Colima), or point the container's \`image\` at a pre-built registry reference. Note: container images must target linux/amd64.`;return r.error(i),i},He=e=>v(h(e,_))?_:void 0,Me=(e,r,t="deploy")=>{for(const n of I(e,"lunora").containers){const{image:a}=n;if(a.kind==="dockerfile"&&!v(h(e,a.dockerfilePath))){const o=`${t} blocked: container "${n.exportName}" references a Dockerfile at "${a.dockerfilePath}" that does not exist. Create it or fix the \`image\` path in lunora/containers.ts.`;return r.error(o),o}if(a.kind==="build"&&!v(h(e,a.buildDir))){const o=`${t} blocked: container "${n.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(o),o}}},M=e=>$(e.format)?!1:e.interactive!==void 0?e.interactive:process.stdout.isTTY&&!process.env.CI,Be=(e,r)=>(A(e,r)?.d1_databases??[]).find(t=>t.database_id===H)?.binding,Ve=async(e,r)=>{if(r.dryRun===!0)return;const t=I(e,"lunora").containers.filter(a=>a.image.kind==="build").map(a=>({buildDir:a.image.buildDir,exportName:a.exportName}));if(t.length===0)return;const n=await Le({cwd:e,logger:r.logger,railpackAvailable:r.railpackAvailable,spawner:r.spawner,targets:t});return n.code===0?void 0:n.error??"railpack build failed"},Ke=(e,r,t)=>{if(t!==void 0)try{const n=te(e,t);n.changed&&r.success(`synced ${String(t.length)} cron trigger(s) → ${n.wranglerPath??"wrangler.jsonc"}`)}catch(n){const a=n instanceof Error?n.message:String(n);r.warn(`cron trigger sync skipped: ${a}`)}},qe=async(e,r,t,n,a)=>{try{D(n);const o=await O({projectRoot:e}),i=ee(e,o,a);i.changed&&r.success(`provisioned bindings: ${i.added.join(", ")} → ${i.wranglerPath??"wrangler.jsonc"}`);for(const s of i.warnings)r.warn(s)}catch(o){const i=o instanceof Error?o.message:String(o);r.warn(`binding inference skipped: ${i}`)}try{const o=re(e);o.changed&&r.success(`bumped compatibility_date to ${o.date??"unknown"} (Workers Cache enabled) → ${o.wranglerPath??"wrangler.jsonc"}`)}catch(o){const i=o instanceof Error?o.message:String(o);r.warn(`compatibility date sync skipped: ${i}`)}Ke(e,r,t)},Ge=(e,r)=>{const t=h(e,y);if(!v(t))return;let n;try{n=U(p(t,"utf8")).length}catch{return}n!==0&&r.warn(`Note: \`lunora deploy\` does not push secrets. ${y} has ${String(n)} key(s); if you changed them, run \`lunora env push --yes\` to update the deployed secrets.`)},Ye=async e=>{let r=[];try{r=G(await O({projectRoot:e}))}catch{}const t=Y(r).map(a=>a.key);let n=[];try{const a=h(e,y);v(a)&&(n=U(p(a,"utf8")).map(o=>o.key).filter(o=>se(o)))}catch{}return[...new Set([...t,...n])]},ze=async(e,r,t,n)=>{const{logger:a}=r,o=r.spawner??S,i=b(e),s=r.env===void 0?"":` --env ${r.env}`,{toolchain:c}=D(n);if(c===void 0)return a.error("deploy target has no command-line toolchain; cannot push secrets"),{minted:[],ok:!1};const l=[];for(const d of t){const g=z(),u=c.secretPut({environment:r.env,key:d,temporary:r.temporary}),m=k(i,u.tool,u.args),f=await o({args:m.args,command:m.command,cwd:e,input:g});if(f.code!==0)return a.error(`failed to push secret ${d} (exit ${String(f.code)}); set it manually with \`wrangler secret put ${d}${s}\`.`),{minted:l,ok:!1};l.push({key:d,value:g}),a.success(`generated + pushed ${d}`)}return{minted:l,ok:!0}},Je=/^[\w-]+$/u,R=[".dev.vars",".dev.vars.*","!.dev.vars.example"],Qe=/\r?\n/u,Xe=(e,r)=>{const t=h(e,".gitignore");try{const n=v(t)?p(t,"utf8"):"",a=new Set(n.split(Qe).map(c=>c.trim())),o=R.filter(c=>!a.has(c));if(o.length===0)return;const i=o.some(c=>!c.startsWith("!"))?[...o.filter(c=>!c.startsWith("!")),...R.filter(c=>c.startsWith("!"))]:o,s=n.length>0&&!n.endsWith(`
2
+ `)?`
3
+ `:"";T(t,`${n}${s}
4
+ # Lunora — never commit a minted secret
5
+ ${i.join(`
6
+ `)}
7
+ `,"utf8"),r.info(`.gitignore: added ${o.join(", ")} so the recorded secret cannot be committed`)}catch(n){r.warn(`could not update .gitignore (${n instanceof Error?n.message:String(n)}) — add \`${R.join("` and `")}\` by hand before committing.`)}},Ze=(e,r,t)=>{if(t.length===0)return;const n=t.map(s=>s.key).join(", ");if(r.env!==void 0&&!Je.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 a=r.env===void 0?y:`${y}.${r.env}`;Xe(e,r.logger);const o=h(e,a);let i=v(o)?p(o,"utf8"):"";for(const s of t)i=J(i,s.key,s.value);return Q(o,i),r.logger.success(r.env===void 0?`${n}: value(s) recorded in ${a}`:`${n}: value(s) recorded in ${a} (kept separate from ${y} so \`lunora dev\` and a plain \`lunora env push\` don't inherit the --env ${r.env} value)`),a},er=async(e,r,t,n)=>{if(r.dryRun===!0||r.preview===!0)return{};const{logger:a}=r,o=r.env===void 0?"":` --env ${r.env}`;let i;try{i=await(r.secretLister??Ce)({cwd:e,env:r.env,temporary:r.temporary})}catch{return{}}if(!i.ok)return{};const s=new Set(i.names),l=(await Ye(e)).filter(u=>!s.has(u));if(l.length===0)return{};if(!t)return{error:`missing required secret(s) on the deploy target: ${l.join(", ")}. Set them with \`wrangler secret put <KEY>${o}\` (or \`lunora env generate --set\` then \`lunora env push --yes${o}\`), then re-deploy.`};for(const u of l.filter(m=>!P(m)))a.warn(`required secret ${u} is not set on the target — set it with: wrangler secret put ${u}${o}`);const d=l.filter(u=>P(u));if(d.length===0)return{};if(await(r.secretConfirm??Ae())(`${String(d.length)} required secret(s) not set on the target (${d.join(", ")}). Generate strong values and push them now?`)){const{minted:u,ok:m}=await ze(e,r,d,n),f=Ze(e,r,u);return m?{mintedSecretsFile:f}:{error:"failed to push required secret(s) — set them manually and re-deploy",mintedSecretsFile:f}}return a.warn(`${String(d.length)} required secret(s) not set on the target: ${d.join(", ")}. Generate + push with \`lunora env generate --set\` then \`lunora env push --yes${o}\`.`),{}},rr=async(e,r)=>{const t=new ie({skipAddingFilesFromTsConfig:!0}),n=h(r,"lunora");let a;try{a=V(t,n)}catch(o){const i=o instanceof Error?o.message:String(o);return e.logger.warn(`--migrate: could not discover migrations (${i}); skipping`),0}if(a.length===0)return e.logger.info("--migrate: no data migrations declared in lunora/"),0;e.logger.info(`--migrate: running ${String(a.length)} migration(s) against deployed worker`);for(const o of a){e.logger.info(`--migrate: up "${o.id}" (table "${o.table}")`);const i={cwd:r,fetchImpl:e.fetchImpl,id:o.id,logger:e.logger,prod:!0,subcommand:"up",token:e.migrateToken,url:e.migrateUrl,yes:e.migrateYes===!0},s=await Pe(i);if(s.code!==0)return e.logger.error(`--migrate: migration "${o.id}" failed — see output above`),s.code;e.logger.success(`--migrate: "${o.id}" applied`)}return 0},tr=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}},nr=async(e,r,t,n,a,o,i,s)=>{let c;r?(c=new oe({name:"dots"}),c.start("running codegen")):t.info("running codegen");try{const l=B({apiSpec:n,projectRoot:e,target:a});c?.succeed("codegen complete"),c||t.success("codegen complete");const d=De(l.platformDiagnostics,t);if(d.errors.length>0)return{error:d.errors.join("; ")};const{errorAdvisories:g,names:u,shouldBlock:m}=ue(l.advisories,s);if(m){const C=`${g.length.toString()} ERROR-level ${g.length===1?"advisory":"advisories"} (${u.join(", ")}). Pass --no-strict-advisories to downgrade this to a warning and deploy anyway.`;return t.error(C),{error:C}}const f=await q({cwd:e,logger:t,spawner:o,stdoutToStderr:i});return f.error!==void 0?{error:f.error}:{result:l}}catch(l){c?.failed("codegen failed");const d=l instanceof Error?l.message:String(l);return t.error(`codegen failed: ${d}`),{error:`codegen failed: ${d}`}}},ar=(e,r,t="deploy",n)=>{const a=Be(e,n);if(a===void 0)return;const o=`${t} blocked: the "${a}" D1 binding has a placeholder database_id ("${H}"). Run \`wrangler d1 create <name>\` to create the database, then replace the placeholder in wrangler.jsonc with the real id before deploying.`;return r.error(o),o},or=(e,r,t="deploy",n)=>{const a=A(e,n)?.vars;if(!a)return;const o=Ue.filter(s=>typeof a[s]=="string"&&Oe(a[s]));if(o.length===0)return;const i=`${t} blocked: ${o.join(", ")} in wrangler.jsonc point at localhost. A deployed Worker can't reach a loopback address, so this silently breaks scheduled-job dispatch / auth callbacks. Set each to the deployed worker's public URL (or move it to a secret with \`wrangler secret put\`) before deploying.`;return r.error(i),i},ir=async(e,r)=>{const{info:t}=X(r,"lunora"),n=t?.vectorMetadata??[];if(n.length===0)return;const a=[];for(const s of n){const c=ce(s.kind);if(c===void 0){e.logger.warn(`vector index "${s.index}" declares metadata "${s.property}", whose column type cannot be filtered on in Vectorize — it is stored with each vector but no filter will match it.`);continue}a.push({index:s.index,property:s.property,type:c})}if(a.length===0)return;const i=(await le({cwd:r,entries:a,exec:k(b(r),"wrangler",[]),logger:e.logger,spawner:e.spawner??S})).filter(s=>s.status!=="failed").length;i>0&&e.logger.success(`vectorize metadata indexes ready: ${String(i)}/${String(a.length)}`)},j=5,sr=2e3,cr=async(e,r,t)=>{if(e.healthCheck!==!0)return;const n=t??F({cwd:r,env:e.env});if(n===void 0){const o="--health-check: the deploy succeeded, but no URL to probe could be resolved — wrangler's output carried none and this checkout has no link for this environment. Run `lunora link --url <https://your-worker>` and re-deploy, or drop --health-check.";return e.logger.error(o),{error:o,ok:!1,url:""}}const a=await we({attempts:j,baseUrl:n,delayMs:sr,fetchImpl:e.healthFetch,paths:[ke,be],sleep:e.healthSleep});return a.error===void 0?(e.logger.success(`health check ok (${a.url})`),{ok:!0,url:a.url}):(e.logger.error(`--health-check: the deploy succeeded, but the new version did not answer after ${String(j)} attempt(s) — ${a.error}`),{error:a.error,ok:!1,url:a.url})},lr=async(e,r,t,n,a,o)=>{await ir(e,r);const i=e.migrate?await rr(e,r):0;return i===0&&a?.(),{code:i,descriptor:t,mintedSecretsFile:o,validation:n}},dr=(e,r,t)=>{const n=ar(e,r.logger,t,r.env);if(n!==void 0)return n;const a=or(e,r.logger,t,r.env);if(a!==void 0)return a;const o=Me(e,r.logger,t);return o!==void 0?o:Fe(e,r.logger,r.dockerAvailable??ye,t,r.env)},ur=(e,r,t)=>{const n=He(e);n!==void 0&&r.logger.info(`class-B composition: deploying ${n} (overrides wrangler main)`),r.temporary&&r.logger.info("temporary account: deploying to a short-lived Cloudflare account (~60min); wrangler will print a claim URL"),r.dryRun&&r.logger.info("dry run: validating + bundling without publishing"),r.outDir!==void 0&&r.logger.info(`build artifact: emitting bundle to ${r.outDir}`);const a=D(t),o={dryRun:r.dryRun,entry:n,environment:r.env,outDir:r.outDir,preview:r.preview,temporary:r.temporary};if(a.toolchain===void 0)throw new Error(`deploy target "${a.id}" has no command-line toolchain`);return a.toolchain.deploy(o)},w=(e,r)=>({code:1,descriptor:void 0,error:e,validation:{problems:[],wranglerPath:void 0},...r}),gr=(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},mr=(e,r,t)=>{const n=$(r.format),a=r.dryRun!==!0,o=ur(e,r,t),i=k(b(e),o.tool,o.args);return{args:i.args,captureStdout:a&&!n,captureStdoutSilently:a&&n,command:i.command,cwd:e,stdoutToStderr:n&&!a}},fr=async({cwd:e,descriptor:r,mintedSecretsFile:t,options:n,reblessSchemaBaseline:a,stdout:o,validation:i})=>{const s={deployedAt:new Date().toISOString(),dryRun:n.dryRun===!0,env:n.env,preview:n.preview===!0,url:n.dryRun===!0?void 0:xe(o),workerName:E(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:s,descriptor:r,mintedSecretsFile:t,validation:i};n.temporary!==!0&&je({cwd:e,env:n.env,logger:n.logger,url:s.url});const c=await cr(n,e,s.url);return c?.error!==void 0?{code:1,deployment:s,descriptor:r,healthCheck:c,mintedSecretsFile:t,validation:i}:{...await lr(n,e,r,i,a,t),deployment:s,healthCheck:c}},hr=async(e,r)=>{const t=e.cwd??process.cwd(),n=M(e),a=de(e),o={problems:[],wranglerPath:void 0},i=me(t,e.target);if(i.target===void 0){const u=i.error??"unknown deploy target";return e.logger.error(u),{error:u,validation:o}}const{target:s}=i;let c;if(!e.skipCodegen){const u=await nr(t,n,e.logger,e.apiSpec,s,e.spawner,$(e.format),a);if(u.error!==void 0)return{error:u.error,target:s,validation:o};c=u.result}let l;if(c!==void 0){const u=pe({allowDrift:e.allowSchemaDrift===!0,codegen:c,command:r,logger:e.logger,updateBaseline:e.updateSchemaBaseline===!0});if(u.blocked)return{error:`schema drift gate blocked ${r}`,schemaDrift:{blocked:!0,reason:u.reason},target:s,validation:o};l=u.rebless}await qe(t,e.logger,c?.cronTriggers,s,e.env);const d=dr(t,e,r);if(d!==void 0)return{error:d,target:s,validation:o};const g=Z({environment:e.env,projectRoot:t});return gr(g,e.logger)?{error:"wrangler validation failed",target:s,validation:g}:{codegen:c,reblessSchemaBaseline:l,target:s,validation:g}},vr=async e=>{const r=e.cwd??process.cwd(),t=M(e),n=await hr(e,e.commandName??"deploy");if(n.error!==void 0){if(n.validation.problems.length>0)return{code:1,descriptor:void 0,error:n.error,validation:n.validation};const f=n.schemaDrift===void 0?void 0:{schemaDrift:n.schemaDrift};return w(n.error,f)}const{reblessSchemaBaseline:a,validation:o}=n,i=n.target,s=tr(e);if(s!==void 0)return w(s);const c=await Ve(r,e);if(c!==void 0)return w(c);Ge(r,e.logger);const{error:l,mintedSecretsFile:d}=await er(r,e,t,i);if(l!==void 0)return e.logger.error(l),{code:1,descriptor:void 0,error:l,mintedSecretsFile:d,validation:o};const g=mr(r,e,i);e.logger.info(`deploying via ${g.command} ${g.args.join(" ")}`);const m=await(e.spawner??S)(g);return g.captureStdoutSilently===!0&&m.stdout!==void 0&&m.stdout!==""&&process.stderr.write(m.stdout),m.code!==0?{code:m.code,descriptor:g,mintedSecretsFile:d,validation:o}:fr({cwd:r,descriptor:g,mintedSecretsFile:d,options:e,reblessSchemaBaseline:a,stdout:m.stdout,validation:o})},yr=async e=>{const r=$e("deploy",e.format);if(r!==void 0)return e.logger.error(r),w(r);const t=Re(e.format,e.logger),n=e.dryRun===!0?Ie(e.cwd??process.cwd()):void 0;let a;try{if(a=await vr({...e,logger:t}),a.code===0&&e.emitBindings!==void 0){const{error:o}=fe({destination:e.emitBindings,logger:t,projectRoot:e.cwd??process.cwd()});o!==void 0&&(t.error(o),a={...a,code:1})}}finally{n?.()}if($(e.format))return Se(a),a;if(a.code===0&&e.dryRun!==!0&&e.preview!==!0)Te({cwd:e.cwd??process.cwd(),env:e.env,logger:e.logger,mintedSecretsFile:a.mintedSecretsFile,url:a.deployment?.url});else if(a.code===0&&e.preview===!0){const o=a.deployment?.url;e.logger.success(o===void 0?"preview version uploaded":`preview version uploaded — ${o}`)}return a},Hr=he(async({cwd:e,logger:r,options:t})=>({code:(await yr({allowSchemaDrift:t.allowSchemaDrift===!0,apiSpec:ge(t.apiSpec),cwd:e,dryRun:t.dryRun===!0,env:t.env,format:t.format,healthCheck:t.healthCheck===!0,logger:r,migrate:t.migrate===!0,migrateToken:t.migrateToken,migrateUrl:F({cwd:e,env:t.env,url:t.migrateUrl}),migrateYes:t.migrateYes===!0,preview:t.preview===!0,skipCodegen:t.prebuilt===!0,strictAdvisories:t.strictAdvisories,target:t.target,temporary:t.temporary===!0,updateSchemaBaseline:t.updateSchemaBaseline===!0})).code}));export{Hr as execute,qe as provisionBindings,yr as runDeployCommand,hr as runPreDeployPipeline};