@lunora/cli 1.0.0-alpha.337 → 1.0.0-alpha.339

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/dist/bin.mjs +1 -1
  2. package/dist/index.d.mts +22 -0
  3. package/dist/index.d.ts +22 -0
  4. package/dist/index.mjs +1 -1
  5. package/dist/packem_chunks/handler.mjs +1 -1
  6. package/dist/packem_chunks/handler17.mjs +1 -1
  7. package/dist/packem_chunks/handler19.mjs +1 -1
  8. package/dist/packem_chunks/handler2.mjs +1 -1
  9. package/dist/packem_chunks/handler21.mjs +1 -1
  10. package/dist/packem_chunks/handler25.mjs +1 -1
  11. package/dist/packem_chunks/handler26.mjs +1 -1
  12. package/dist/packem_chunks/handler28.mjs +1 -1
  13. package/dist/packem_chunks/handler3.mjs +1 -1
  14. package/dist/packem_chunks/handler4.mjs +1 -1
  15. package/dist/packem_chunks/handler6.mjs +3 -3
  16. package/dist/packem_chunks/runCodegenCommand.mjs +3 -3
  17. package/dist/packem_chunks/runDeployCommand.mjs +3 -3
  18. package/dist/packem_chunks/runDevCommand.mjs +2 -2
  19. package/dist/packem_chunks/runInitCommand.mjs +38 -38
  20. package/dist/packem_shared/{COMMANDS-wxNr9kj9.mjs → COMMANDS-DRMcVnnw.mjs} +1 -1
  21. package/dist/packem_shared/cli-CG_JgNKu.mjs +2 -0
  22. package/dist/packem_shared/createRecordingSpawner-CYhdPBD5.mjs +1 -0
  23. package/dist/packem_shared/index-oHZBGBwB.mjs +1 -0
  24. package/dist/packem_shared/plan-Cqn2uvTo.mjs +5 -0
  25. package/dist/packem_shared/{planDevCommand-Bto0lJPd.mjs → planDevCommand-KxbFGmBZ.mjs} +1 -1
  26. package/dist/packem_shared/storage-ChJtQ9E4.mjs +1 -0
  27. package/dist/packem_shared/{wrangler-secrets-CuUdFBaA.mjs → wrangler-secrets-Bqi6kLuq.mjs} +1 -1
  28. package/package.json +10 -10
  29. package/dist/packem_shared/cli-C4OL2wM9.mjs +0 -2
  30. package/dist/packem_shared/createRecordingSpawner-sS7LEN7x.mjs +0 -1
  31. package/dist/packem_shared/plan-Dc6C_AGu.mjs +0 -6
  32. package/dist/packem_shared/storage-iyNnV-2G.mjs +0 -1
package/dist/bin.mjs CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import{r as e}from"./packem_shared/cli-C4OL2wM9.mjs";try{const r=await e();process.exit(r)}catch(r){process.stderr.write(`${r instanceof Error?r.message:String(r)}
2
+ import{r as e}from"./packem_shared/cli-CG_JgNKu.mjs";try{const r=await e();process.exit(r)}catch(r){process.stderr.write(`${r instanceof Error?r.message:String(r)}
3
3
  `),process.exit(1)}
package/dist/index.d.mts CHANGED
@@ -910,6 +910,26 @@ interface WorkerProcess {
910
910
  type WorkerSpawner = (descriptor: SpawnDescriptor & {
911
911
  tag: string;
912
912
  }, logger: Logger) => WorkerProcess;
913
+ /** What a long-lived child runs: the one-shot descriptor's command/args/cwd/env, plus how to spawn it. */
914
+ interface LongLivedDescriptor {
915
+ args: ReadonlyArray<string>;
916
+ command: string;
917
+ cwd?: string;
918
+ /** A real executable, never a package-manager shim — spawned without a shell, with stdin ignored. */
919
+ direct?: boolean;
920
+ env?: Readonly<Record<string, string>>;
921
+ }
922
+ /** Spawns a long-lived child and streams its output line by line. Injectable for tests. */
923
+ type LongLivedSpawner = (descriptor: LongLivedDescriptor, onLine: (line: string, kind: "stderr" | "stdout") => void, onError?: (error: Error) => void) => WorkerProcess;
924
+ /** A `--tunnel` request, built once from the parsed flags. */
925
+ interface DevTunnelRequest {
926
+ /** Normalized `--allow-mail` entries, passed to cloudflared as `--allowed-mail`; empty opens a PUBLIC tunnel. */
927
+ allowMail: ReadonlyArray<string>;
928
+ /** Injection seam for tests — the one-shot spawner the `cloudflared --version` probe runs through. */
929
+ spawner?: Spawner;
930
+ /** Injection seam for tests — starts the long-lived `cloudflared tunnel` child. */
931
+ startChild?: LongLivedSpawner;
932
+ }
913
933
  interface DevCommandOptions {
914
934
  /** Which API spec(s) the codegen watcher emits. Defaults to codegen's `"openapi"` when omitted. */
915
935
  apiSpec?: ApiSpec;
@@ -967,6 +987,8 @@ interface DevCommandOptions {
967
987
  studio?: boolean;
968
988
  /** Deploy target the emitted `ctx.*` surface is tailored to. Resolved by the caller; falls back to `"target"` in `lunora.config.*`, then `"cloudflare"`. */
969
989
  target?: string;
990
+ /** `--tunnel`: share the worker's origin through a Cloudflare quick tunnel. Absent means no tunnel. */
991
+ tunnel?: DevTunnelRequest;
970
992
  /**
971
993
  * Injection seam for tests — defaults to parking until SIGINT.
972
994
  *
package/dist/index.d.ts CHANGED
@@ -910,6 +910,26 @@ interface WorkerProcess {
910
910
  type WorkerSpawner = (descriptor: SpawnDescriptor & {
911
911
  tag: string;
912
912
  }, logger: Logger) => WorkerProcess;
913
+ /** What a long-lived child runs: the one-shot descriptor's command/args/cwd/env, plus how to spawn it. */
914
+ interface LongLivedDescriptor {
915
+ args: ReadonlyArray<string>;
916
+ command: string;
917
+ cwd?: string;
918
+ /** A real executable, never a package-manager shim — spawned without a shell, with stdin ignored. */
919
+ direct?: boolean;
920
+ env?: Readonly<Record<string, string>>;
921
+ }
922
+ /** Spawns a long-lived child and streams its output line by line. Injectable for tests. */
923
+ type LongLivedSpawner = (descriptor: LongLivedDescriptor, onLine: (line: string, kind: "stderr" | "stdout") => void, onError?: (error: Error) => void) => WorkerProcess;
924
+ /** A `--tunnel` request, built once from the parsed flags. */
925
+ interface DevTunnelRequest {
926
+ /** Normalized `--allow-mail` entries, passed to cloudflared as `--allowed-mail`; empty opens a PUBLIC tunnel. */
927
+ allowMail: ReadonlyArray<string>;
928
+ /** Injection seam for tests — the one-shot spawner the `cloudflared --version` probe runs through. */
929
+ spawner?: Spawner;
930
+ /** Injection seam for tests — starts the long-lived `cloudflared tunnel` child. */
931
+ startChild?: LongLivedSpawner;
932
+ }
913
933
  interface DevCommandOptions {
914
934
  /** Which API spec(s) the codegen watcher emits. Defaults to codegen's `"openapi"` when omitted. */
915
935
  apiSpec?: ApiSpec;
@@ -967,6 +987,8 @@ interface DevCommandOptions {
967
987
  studio?: boolean;
968
988
  /** Deploy target the emitted `ctx.*` surface is tailored to. Resolved by the caller; falls back to `"target"` in `lunora.config.*`, then `"cloudflare"`. */
969
989
  target?: string;
990
+ /** `--tunnel`: share the worker's origin through a Cloudflare quick tunnel. Absent means no tunnel. */
991
+ tunnel?: DevTunnelRequest;
970
992
  /**
971
993
  * Injection seam for tests — defaults to parking until SIGINT.
972
994
  *
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{C as o,V as a,r as n}from"./packem_shared/cli-C4OL2wM9.mjs";import{runCodegenCommand as m}from"./packem_chunks/runCodegenCommand.mjs";import{runDeployCommand as p}from"./packem_chunks/runDeployCommand.mjs";import{runDevCommand as f}from"./packem_chunks/runDevCommand.mjs";import{p as i}from"./packem_shared/plan-Dc6C_AGu.mjs";import{runInitCommand as l}from"./packem_chunks/runInitCommand.mjs";import{runMigrateGenerateCommand as I}from"./packem_shared/runMigrateGenerateCommand-Ii_WMZEA.mjs";import{runResetCommand as g}from"./packem_chunks/runResetCommand.mjs";import{runRpcCommand as T}from"./packem_chunks/runRpcCommand.mjs";import{EXIT_CODE as S,exitCodeForCode as A,exitCodeForError as c,exitCodeForStatus as M}from"./packem_shared/EXIT_CODE-D_XCixv8.mjs";import{insertSchemaExtension as v}from"./packem_shared/insertSchemaExtension-DuiV6cba.mjs";import{createLogger as b,pail as O}from"./packem_shared/createLogger-Cl18I8AX.mjs";import{diffSnapshots as y,renderAddColumn as L,renderCreateIndex as w,renderCreateTable as B,renderDropIndex as P,renderDropTable as U,renderMigrationFile as V,validatorKindToSqlType as W}from"./packem_shared/diffSnapshots-WWwx-KvZ.mjs";import{default as N}from"./packem_shared/schemaIrToSnapshot-BjK-0IRo.mjs";import{createRecordingSpawner as j,defaultSpawner as q}from"./packem_shared/createRecordingSpawner-sS7LEN7x.mjs";import{default as K}from"./packem_shared/parseManifest-CwPTKdtS.mjs";import{D as Y,r as Z}from"./packem_shared/import-BRM1hs7j.mjs";import{REQUIRED_COMPATIBILITY_DATE as z,REQUIRED_FLAG as J,validateWranglerProject as $,validateWranglerConfig as rr}from"@lunora/config/cloudflare";import{b as or}from"./packem_shared/catalog-CahzmDLV.mjs";import{r as nr,a as tr,b as mr}from"./packem_shared/commands-Cg06JNO2.mjs";import{runExportCommand as pr}from"./packem_shared/runExportCommand-slAq5BCF.mjs";export{o as COMMANDS,Y as DEFAULT_IMPORT_BATCH_SIZE,S as EXIT_CODE,z as REQUIRED_COMPATIBILITY_DATE,J as REQUIRED_FLAG,a as VERSION,or as buildRegistryIndex,b as createLogger,j as createRecordingSpawner,q as defaultSpawner,y as diffSnapshots,A as exitCodeForCode,c as exitCodeForError,M as exitCodeForStatus,v as insertSchemaExtension,O as pail,K as parseManifest,i as planDevCommand,L as renderAddColumn,w as renderCreateIndex,B as renderCreateTable,P as renderDropIndex,U as renderDropTable,V as renderMigrationFile,nr as runAddCommand,tr as runBuildIndexCommand,n as runCli,m as runCodegenCommand,p as runDeployCommand,f as runDevCommand,pr as runExportCommand,Z as runImportCommand,l as runInitCommand,I as runMigrateGenerateCommand,mr as runRegistryViewCommand,g as runResetCommand,T as runRpcCommand,N as schemaIrToSnapshot,$ as validateWrangler,rr as validateWranglerConfig,W as validatorKindToSqlType};
1
+ import{C as o,V as a,r as n}from"./packem_shared/cli-CG_JgNKu.mjs";import{runCodegenCommand as m}from"./packem_chunks/runCodegenCommand.mjs";import{runDeployCommand as p}from"./packem_chunks/runDeployCommand.mjs";import{runDevCommand as f}from"./packem_chunks/runDevCommand.mjs";import{p as i}from"./packem_shared/plan-Cqn2uvTo.mjs";import{runInitCommand as l}from"./packem_chunks/runInitCommand.mjs";import{runMigrateGenerateCommand as I}from"./packem_shared/runMigrateGenerateCommand-Ii_WMZEA.mjs";import{runResetCommand as g}from"./packem_chunks/runResetCommand.mjs";import{runRpcCommand as T}from"./packem_chunks/runRpcCommand.mjs";import{EXIT_CODE as S,exitCodeForCode as A,exitCodeForError as c,exitCodeForStatus as M}from"./packem_shared/EXIT_CODE-D_XCixv8.mjs";import{insertSchemaExtension as v}from"./packem_shared/insertSchemaExtension-DuiV6cba.mjs";import{createLogger as b,pail as O}from"./packem_shared/createLogger-Cl18I8AX.mjs";import{diffSnapshots as y,renderAddColumn as L,renderCreateIndex as w,renderCreateTable as B,renderDropIndex as P,renderDropTable as U,renderMigrationFile as V,validatorKindToSqlType as W}from"./packem_shared/diffSnapshots-WWwx-KvZ.mjs";import{default as N}from"./packem_shared/schemaIrToSnapshot-BjK-0IRo.mjs";import{createRecordingSpawner as j,defaultSpawner as q}from"./packem_shared/createRecordingSpawner-CYhdPBD5.mjs";import{default as K}from"./packem_shared/parseManifest-CwPTKdtS.mjs";import{D as Y,r as Z}from"./packem_shared/import-BRM1hs7j.mjs";import{REQUIRED_COMPATIBILITY_DATE as z,REQUIRED_FLAG as J,validateWranglerProject as $,validateWranglerConfig as rr}from"@lunora/config/cloudflare";import{b as or}from"./packem_shared/catalog-CahzmDLV.mjs";import{r as nr,a as tr,b as mr}from"./packem_shared/commands-Cg06JNO2.mjs";import{runExportCommand as pr}from"./packem_shared/runExportCommand-slAq5BCF.mjs";export{o as COMMANDS,Y as DEFAULT_IMPORT_BATCH_SIZE,S as EXIT_CODE,z as REQUIRED_COMPATIBILITY_DATE,J as REQUIRED_FLAG,a as VERSION,or as buildRegistryIndex,b as createLogger,j as createRecordingSpawner,q as defaultSpawner,y as diffSnapshots,A as exitCodeForCode,c as exitCodeForError,M as exitCodeForStatus,v as insertSchemaExtension,O as pail,K as parseManifest,i as planDevCommand,L as renderAddColumn,w as renderCreateIndex,B as renderCreateTable,P as renderDropIndex,U as renderDropTable,V as renderMigrationFile,nr as runAddCommand,tr as runBuildIndexCommand,n as runCli,m as runCodegenCommand,p as runDeployCommand,f as runDevCommand,pr as runExportCommand,Z as runImportCommand,l as runInitCommand,I as runMigrateGenerateCommand,mr as runRegistryViewCommand,g as runResetCommand,T as runRpcCommand,N as schemaIrToSnapshot,$ as validateWrangler,rr as validateWranglerConfig,W as validatorKindToSqlType};
@@ -1 +1 @@
1
- import{existsSync as k,readFileSync as A}from"node:fs";import{applyLintIgnores as I,detectLintTools as N}from"@lunora/config";import{findWranglerFile as U}from"@lunora/config/cloudflare";import{join as w,basename as h}from"@visulima/path";import{d as S}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as o}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{r as D}from"../packem_shared/lint-ignore-report-DKZagpqk.mjs";import{t as y,a as E}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{i as _}from"../packem_shared/resolve-DUCSc7jQ.mjs";import{r as L}from"../packem_shared/commands-Cg06JNO2.mjs";import{n as M,i as O,A as P,E as R,s as j,d as f,p as $,r as g,M as F,a as C,b as v,c as p,D as m,e as x,f as H,g as i,h as z,j as B,w as G,k as W,l as V}from"../packem_shared/storage-iyNnV-2G.mjs";const q=e=>{const r=e.trim().toLowerCase();return B.find(a=>a.value===r||a.label.toLowerCase()===r||r==="auth0"&&a.value==="auth-auth0"||r==="clerk"&&a.value==="auth-clerk")?.value},T=e=>{try{const r=JSON.parse(A(w(e,"package.json"),"utf8"));return{...r.dependencies,...r.devDependencies}}catch{return{}}},J=async e=>{const r=e.cwd??process.cwd(),t=H(T(r));return t!==void 0?t:e.yes===!0?(e.logger.warn(`add: couldn't detect your framework — using "${i}". Pass a specific item (e.g. \`lunora add auth-ui-vue\`) to override.`),i):await(e.promptSelect??((c,n,d)=>y(c,n,d)))("Which framework is your app?",z,{default:i})??i},X=async e=>{if(e.provider!==void 0&&e.provider!==""){const t=q(e.provider);return t===void 0?(e.logger.warn(`add: unknown --provider "${e.provider}" — using "${m}" (email & password).`),m):t}if(e.yes===!0)return m;const r=e.promptSelect??((t,a,c)=>y(t,a,c));return x(r)},l=e=>e.promptText??((r,t)=>E(r,t)),K=async e=>{const r=h(e.cwd??process.cwd());if(e.bucket!==void 0&&e.bucket!==""){const t=j(e.bucket);if(t!==void 0)return t;const a=f(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?f(r):$(l(e),r)},Q=async e=>{const r=t=>{e.logger.warn(`add: ${t}`)};if(e.mailTo!==void 0&&e.mailTo!=="")return g(e.mailTo,r);if(e.yes!==!0)return g(await l(e)(F,{placeholder:"you@yourdomain.com"}),r)},Y=async e=>{const r=h(e.cwd??process.cwd());if(e.db!==void 0&&e.db!==""){const t=C(e.db);if(t!==void 0)return t;const a=v(r);return e.logger.warn(`add: "${e.db}" isn't a usable D1 database name — using "${a}".`),a}return e.yes===!0?v(r):p(l(e),r)},Z=async(e,r)=>e.kind==="auth"?[await X(r)]:e.kind==="auth-ui"?[await J(r)]:e.kind==="email"?[R]:[e.item],ee=(e,r)=>{D(I(e,N(e)),r)},re=e=>!_(e)||e.yes===!0,ae=async e=>{const r=e.cwd??process.cwd(),t=e.feature===void 0?void 0:M(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:o.USAGE,items:[]};if(!k(w(r,"lunora"))||U(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:o.USAGE,items:[]};if(t.kind==="auth-ui"&&O(T(r)))return e.logger.error(`add: ${P}`),{code:o.USAGE,items:[]};const a=await Z(t,e),c=[];if(a.includes("storage")){const s=await K(e);c.push(u=>G(u,s))}if(a.includes("mail")){const s=await Q(e);s!==void 0&&c.push(u=>W(u,s))}if(a.some(s=>s==="auth"||s.startsWith("auth-"))){const s=await Y(e);c.push(u=>V(u,s))}const n=c.length>0?s=>{let u=s;for(const b of c)u=b(u);return u}:void 0,d=await L({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:re(e)});return d.code===0&&ee(r,e.logger),{code:d.code,items:a}},ge=S(async({argument:e,cwd:r,logger:t,options:a})=>{const c=await ae({allowUnsafeSource:a.allowUnsafeSource===!0,bucket:a.bucket,cwd:r,db:a.db,feature:e[0],from:a.from,logger:t,mailTo:a.mailTo,provider:a.provider,ref:a.ref,source:a.source,yes:a.yes===!0});return{code:c.code,data:{items:c.items},...c.error===void 0?{}:{error:c.error}}});export{ge as execute,ae as runAddFeature};
1
+ import{existsSync as k,readFileSync as A}from"node:fs";import{applyLintIgnores as I,detectLintTools as N}from"@lunora/config";import{findWranglerFile as U}from"@lunora/config/cloudflare";import{join as w,basename as h}from"@visulima/path";import{d as S}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as o}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{r as D}from"../packem_shared/lint-ignore-report-DKZagpqk.mjs";import{t as y,a as E}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{i as _}from"../packem_shared/resolve-DUCSc7jQ.mjs";import{r as L}from"../packem_shared/commands-Cg06JNO2.mjs";import{n as M,i as O,A as P,E as R,s as j,d as f,p as $,r as g,M as F,a as C,b as v,c as p,D as m,e as x,f as H,g as i,h as z,j as B,w as G,k as W,l as V}from"../packem_shared/storage-ChJtQ9E4.mjs";const q=e=>{const r=e.trim().toLowerCase();return B.find(a=>a.value===r||a.label.toLowerCase()===r||r==="auth0"&&a.value==="auth-auth0"||r==="clerk"&&a.value==="auth-clerk")?.value},T=e=>{try{const r=JSON.parse(A(w(e,"package.json"),"utf8"));return{...r.dependencies,...r.devDependencies}}catch{return{}}},J=async e=>{const r=e.cwd??process.cwd(),t=H(T(r));return t!==void 0?t:e.yes===!0?(e.logger.warn(`add: couldn't detect your framework — using "${i}". Pass a specific item (e.g. \`lunora add auth-ui-vue\`) to override.`),i):await(e.promptSelect??((c,n,d)=>y(c,n,d)))("Which framework is your app?",z,{default:i})??i},X=async e=>{if(e.provider!==void 0&&e.provider!==""){const t=q(e.provider);return t===void 0?(e.logger.warn(`add: unknown --provider "${e.provider}" — using "${m}" (email & password).`),m):t}if(e.yes===!0)return m;const r=e.promptSelect??((t,a,c)=>y(t,a,c));return x(r)},l=e=>e.promptText??((r,t)=>E(r,t)),K=async e=>{const r=h(e.cwd??process.cwd());if(e.bucket!==void 0&&e.bucket!==""){const t=j(e.bucket);if(t!==void 0)return t;const a=f(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?f(r):$(l(e),r)},Q=async e=>{const r=t=>{e.logger.warn(`add: ${t}`)};if(e.mailTo!==void 0&&e.mailTo!=="")return g(e.mailTo,r);if(e.yes!==!0)return g(await l(e)(F,{placeholder:"you@yourdomain.com"}),r)},Y=async e=>{const r=h(e.cwd??process.cwd());if(e.db!==void 0&&e.db!==""){const t=C(e.db);if(t!==void 0)return t;const a=v(r);return e.logger.warn(`add: "${e.db}" isn't a usable D1 database name — using "${a}".`),a}return e.yes===!0?v(r):p(l(e),r)},Z=async(e,r)=>e.kind==="auth"?[await X(r)]:e.kind==="auth-ui"?[await J(r)]:e.kind==="email"?[R]:[e.item],ee=(e,r)=>{D(I(e,N(e)),r)},re=e=>!_(e)||e.yes===!0,ae=async e=>{const r=e.cwd??process.cwd(),t=e.feature===void 0?void 0:M(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:o.USAGE,items:[]};if(!k(w(r,"lunora"))||U(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:o.USAGE,items:[]};if(t.kind==="auth-ui"&&O(T(r)))return e.logger.error(`add: ${P}`),{code:o.USAGE,items:[]};const a=await Z(t,e),c=[];if(a.includes("storage")){const s=await K(e);c.push(u=>G(u,s))}if(a.includes("mail")){const s=await Q(e);s!==void 0&&c.push(u=>W(u,s))}if(a.some(s=>s==="auth"||s.startsWith("auth-"))){const s=await Y(e);c.push(u=>V(u,s))}const n=c.length>0?s=>{let u=s;for(const b of c)u=b(u);return u}:void 0,d=await L({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:re(e)});return d.code===0&&ee(r,e.logger),{code:d.code,items:a}},ge=S(async({argument:e,cwd:r,logger:t,options:a})=>{const c=await ae({allowUnsafeSource:a.allowUnsafeSource===!0,bucket:a.bucket,cwd:r,db:a.db,feature:e[0],from:a.from,logger:t,mailTo:a.mailTo,provider:a.provider,ref:a.ref,source:a.source,yes:a.yes===!0});return{code:c.code,data:{items:c.items},...c.error===void 0?{}:{error:c.error}}});export{ge as execute,ae as runAddFeature};
@@ -1 +1 @@
1
- import{existsSync as m}from"node:fs";import{join as p}from"node:path";import{runCodegen as u}from"@lunora/codegen";import{a as v,e as g,r as y}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as w,r as S}from"../packem_shared/deploy-target-DCWwiuAe.mjs";import{r as k}from"../packem_shared/codegen-error-AmH54ofi.mjs";import{d as j}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as E}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{r as A,p as D}from"../packem_shared/health-probe-Bw9JFfIy.mjs";import{defaultSpawner as R}from"../packem_shared/createRecordingSpawner-sS7LEN7x.mjs";import{validateWranglerProject as $}from"@lunora/config/cloudflare";import{execArgsFor as b,detectPackageManager as U}from"@lunora/config";const x=async(r,a,t)=>{if(!m(p(r,"tsconfig.json")))return{warning:"no tsconfig.json found — skipping TypeScript type-check"};const o=b(U(r),"tsc",["--noEmit","-p","tsconfig.json"]),e=await a({args:o.args,command:o.command,cwd:r,stdoutToStderr:t==="json"});return e.code===0?{}:{error:`type errors: tsc --noEmit exited ${String(e.code)}`}},P=async(r,a)=>{if(r.healthUrl===void 0||r.healthUrl==="")return;const t=await D({baseUrl:r.healthUrl,fetchImpl:r.healthFetch});if(t.error===void 0){a.success(`verify: health probe ok (${t.url})`);return}return t.error},T=(r,a)=>{const{errorAdvisories:t,names:o,shouldBlock:e}=g(r,y(a));if(e)return`${t.length.toString()} ERROR-level ${t.length===1?"advisory":"advisories"} (${o.join(", ")}). Pass --no-strict-advisories to downgrade this to a warning and continue.`},C=(r,a,t,o)=>{if(a.length===0&&t.length===0)return r.success("verify: project is valid"),{code:0,errors:[],warnings:[],wranglerPath:o};if(t.length>0){r.warn("verify: warnings:");for(const e of t)r.warn(` - ${e}`)}if(a.length>0){r.error("verify: errors:");for(const e of a){r.error(` - ${e}`);const n=k(e);n!==void 0&&r.error(n)}return{code:1,error:a[0],errors:a,warnings:t,wranglerPath:o}}return r.success("verify: project is valid (with warnings)"),{code:0,errors:[],warnings:t,wranglerPath:o}},H=async r=>{const a=r.cwd??process.cwd(),{logger:t}=r,o=$({environment:r.env,projectRoot:a}),e=[...o.report.errors],n=[...o.report.warnings];try{const s=S(a,r.target);if(s.target===void 0){const c=s.error??"unknown deploy target";return t.error(c),{code:E.USAGE,error:c,errors:[c],warnings:[],wranglerPath:void 0}}const i=u({apiSpec:r.apiSpec,dryRun:!0,projectRoot:a,target:s.target}),f=v(i.platformDiagnostics,t);e.push(...f.errors),n.push(...f.warnings);const l=T(i.advisories,r);l!==void 0&&e.push(l);const h=A({allowDrift:r.allowSchemaDrift===!0,codegen:i,command:"verify",logger:t,readOnly:!0});h.blocked&&e.push(h.reason)}catch(s){const i=s instanceof Error?s.message:String(s);e.push(`codegen failed: ${i}`)}if(r.typecheck!==!1){const s=await x(a,r.spawner??R,r.format??"pretty");s.error!==void 0&&e.push(s.error),s.warning!==void 0&&n.push(s.warning)}const d=await P(r,t);return d!==void 0&&e.push(d),C(t,e,n,o.wranglerPath)},J=j(async({cwd:r,format:a,logger:t,options:o})=>{const e=await H({allowSchemaDrift:o.allowSchemaDrift===!0,apiSpec:w(o.apiSpec),cwd:r,env:o.env,format:a,healthUrl:o.healthUrl,logger:t,strictAdvisories:o.strictAdvisories,target:o.target,typecheck:o.typecheck===!1?!1:void 0});return{code:e.code,data:{errors:e.errors,warnings:e.warnings,wranglerPath:e.wranglerPath},error:e.error}});export{J as execute,H as runVerifyCommand};
1
+ import{existsSync as m}from"node:fs";import{join as p}from"node:path";import{runCodegen as u}from"@lunora/codegen";import{a as v,e as g,r as y}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as w,r as S}from"../packem_shared/deploy-target-DCWwiuAe.mjs";import{r as k}from"../packem_shared/codegen-error-AmH54ofi.mjs";import{d as j}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as E}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{r as A,p as D}from"../packem_shared/health-probe-Bw9JFfIy.mjs";import{defaultSpawner as R}from"../packem_shared/createRecordingSpawner-CYhdPBD5.mjs";import{validateWranglerProject as $}from"@lunora/config/cloudflare";import{execArgsFor as b,detectPackageManager as U}from"@lunora/config";const x=async(r,a,t)=>{if(!m(p(r,"tsconfig.json")))return{warning:"no tsconfig.json found — skipping TypeScript type-check"};const o=b(U(r),"tsc",["--noEmit","-p","tsconfig.json"]),e=await a({args:o.args,command:o.command,cwd:r,stdoutToStderr:t==="json"});return e.code===0?{}:{error:`type errors: tsc --noEmit exited ${String(e.code)}`}},P=async(r,a)=>{if(r.healthUrl===void 0||r.healthUrl==="")return;const t=await D({baseUrl:r.healthUrl,fetchImpl:r.healthFetch});if(t.error===void 0){a.success(`verify: health probe ok (${t.url})`);return}return t.error},T=(r,a)=>{const{errorAdvisories:t,names:o,shouldBlock:e}=g(r,y(a));if(e)return`${t.length.toString()} ERROR-level ${t.length===1?"advisory":"advisories"} (${o.join(", ")}). Pass --no-strict-advisories to downgrade this to a warning and continue.`},C=(r,a,t,o)=>{if(a.length===0&&t.length===0)return r.success("verify: project is valid"),{code:0,errors:[],warnings:[],wranglerPath:o};if(t.length>0){r.warn("verify: warnings:");for(const e of t)r.warn(` - ${e}`)}if(a.length>0){r.error("verify: errors:");for(const e of a){r.error(` - ${e}`);const n=k(e);n!==void 0&&r.error(n)}return{code:1,error:a[0],errors:a,warnings:t,wranglerPath:o}}return r.success("verify: project is valid (with warnings)"),{code:0,errors:[],warnings:t,wranglerPath:o}},H=async r=>{const a=r.cwd??process.cwd(),{logger:t}=r,o=$({environment:r.env,projectRoot:a}),e=[...o.report.errors],n=[...o.report.warnings];try{const s=S(a,r.target);if(s.target===void 0){const c=s.error??"unknown deploy target";return t.error(c),{code:E.USAGE,error:c,errors:[c],warnings:[],wranglerPath:void 0}}const i=u({apiSpec:r.apiSpec,dryRun:!0,projectRoot:a,target:s.target}),f=v(i.platformDiagnostics,t);e.push(...f.errors),n.push(...f.warnings);const l=T(i.advisories,r);l!==void 0&&e.push(l);const h=A({allowDrift:r.allowSchemaDrift===!0,codegen:i,command:"verify",logger:t,readOnly:!0});h.blocked&&e.push(h.reason)}catch(s){const i=s instanceof Error?s.message:String(s);e.push(`codegen failed: ${i}`)}if(r.typecheck!==!1){const s=await x(a,r.spawner??R,r.format??"pretty");s.error!==void 0&&e.push(s.error),s.warning!==void 0&&n.push(s.warning)}const d=await P(r,t);return d!==void 0&&e.push(d),C(t,e,n,o.wranglerPath)},J=j(async({cwd:r,format:a,logger:t,options:o})=>{const e=await H({allowSchemaDrift:o.allowSchemaDrift===!0,apiSpec:w(o.apiSpec),cwd:r,env:o.env,format:a,healthUrl:o.healthUrl,logger:t,strictAdvisories:o.strictAdvisories,target:o.target,typecheck:o.typecheck===!1?!1:void 0});return{code:e.code,data:{errors:e.errors,warnings:e.warnings,wranglerPath:e.wranglerPath},error:e.error}});export{J as execute,H as runVerifyCommand};
@@ -1,4 +1,4 @@
1
- import{writeFileSync as h,existsSync as S,readFileSync as p}from"node:fs";import{isAbsolute as v,join as w}from"node:path";import{byCodepoint as b,scoreAdvisor as y,parseAdvisorMap as x,compareToBaseline as j}from"@lunora/advisor";import{runCodegen as A}from"@lunora/codegen";import{d as M}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as D}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{D as u}from"../packem_shared/cli-C4OL2wM9.mjs";const l={clean:"·",exempt:"–",failing:"✗",warned:"!"},d=(e,r)=>e.length>=r?e:e+" ".repeat(r-e.length),E=e=>`${e.id} (${e.visibility} ${e.kind})`,f=e=>{let r=0;for(const n of e)r=Math.max(r,n.id.length);return r},g=(e,r)=>` ${d(String(e.score),3)} ${l[e.coverage]} ${d(e.id,r)} ${e.visibility} ${e.kind}`,R=e=>{if(!e.comparable)return[` baseline not comparable (${e.reason}) — regenerate it; this run cannot verify anything`];if(!e.regressed)return[` no regression against baseline (score ${e.scoreDelta>=0?"+":""}${String(e.scoreDelta)})`];const r=[` REGRESSED against baseline (score ${e.scoreDelta>=0?"+":""}${String(e.scoreDelta)})`];for(const n of e.dropped)r.push(` ${n.id}: ${String(n.before)} → ${String(n.after)}`);for(const n of e.newFailing)r.push(` ${n}: now failing`);for(const n of e.worsened)r.push(` ${n}: more findings than the baseline`);return e.projectRegressed&&r.push(" project: new schema/config rules fired"),r},F=(e,r)=>{const n=e.procedures.filter(i=>i.coverage!=="clean"&&i.coverage!=="exempt"),t=f(n),o=[`advisor health ${String(e.score)}/100 — ${e.grade}`,` ${String(e.summary.clean)} clean · ${String(e.summary.warned)} warned · ${String(e.summary.failing)} failing · ${String(e.summary.exempt)} exempt (${String(e.summary.procedures)} procedures, ${String(e.summary.rulesFired)} rules fired)`];return e.project.checks.length>0&&o.push("",` project ${String(e.project.score)}/100 — ${e.project.checks.map(i=>i.name).join(", ")}`),n.length>0&&o.push("",...n.map(i=>g(i,t)),""," run with --all for every procedure, or --entry <file#export> for one"),r!==void 0&&o.push("",...R(r)),o.join(`
1
+ import{writeFileSync as h,existsSync as S,readFileSync as p}from"node:fs";import{isAbsolute as v,join as w}from"node:path";import{byCodepoint as b,scoreAdvisor as y,parseAdvisorMap as x,compareToBaseline as j}from"@lunora/advisor";import{runCodegen as A}from"@lunora/codegen";import{d as M}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as D}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{D as u}from"../packem_shared/cli-CG_JgNKu.mjs";const l={clean:"·",exempt:"–",failing:"✗",warned:"!"},d=(e,r)=>e.length>=r?e:e+" ".repeat(r-e.length),E=e=>`${e.id} (${e.visibility} ${e.kind})`,f=e=>{let r=0;for(const n of e)r=Math.max(r,n.id.length);return r},g=(e,r)=>` ${d(String(e.score),3)} ${l[e.coverage]} ${d(e.id,r)} ${e.visibility} ${e.kind}`,R=e=>{if(!e.comparable)return[` baseline not comparable (${e.reason}) — regenerate it; this run cannot verify anything`];if(!e.regressed)return[` no regression against baseline (score ${e.scoreDelta>=0?"+":""}${String(e.scoreDelta)})`];const r=[` REGRESSED against baseline (score ${e.scoreDelta>=0?"+":""}${String(e.scoreDelta)})`];for(const n of e.dropped)r.push(` ${n.id}: ${String(n.before)} → ${String(n.after)}`);for(const n of e.newFailing)r.push(` ${n}: now failing`);for(const n of e.worsened)r.push(` ${n}: more findings than the baseline`);return e.projectRegressed&&r.push(" project: new schema/config rules fired"),r},F=(e,r)=>{const n=e.procedures.filter(i=>i.coverage!=="clean"&&i.coverage!=="exempt"),t=f(n),o=[`advisor health ${String(e.score)}/100 — ${e.grade}`,` ${String(e.summary.clean)} clean · ${String(e.summary.warned)} warned · ${String(e.summary.failing)} failing · ${String(e.summary.exempt)} exempt (${String(e.summary.procedures)} procedures, ${String(e.summary.rulesFired)} rules fired)`];return e.project.checks.length>0&&o.push("",` project ${String(e.project.score)}/100 — ${e.project.checks.map(i=>i.name).join(", ")}`),n.length>0&&o.push("",...n.map(i=>g(i,t)),""," run with --all for every procedure, or --entry <file#export> for one"),r!==void 0&&o.push("",...R(r)),o.join(`
2
2
  `)},k=e=>e.coverage==="exempt"?[` exempt: ${e.exemptReason===void 0||e.exemptReason===""?"no reason given":e.exemptReason}`]:e.checks.map(r=>{const n=r.occurrences>1?`, ×${String(r.occurrences)}`:"";return` ${r.name} (−${String(r.weight)}${n})`}),T=e=>{const r=new Map;for(const n of e){const t=r.get(n.file);t===void 0?r.set(n.file,[n]):t.push(n)}return[...r].toSorted(([n],[t])=>b(n,t))},B=e=>{const r=f(e.procedures),n=[`advisor health ${String(e.score)}/100 — ${e.grade}`,"",` legend: ${l.clean} clean ${l.warned} warned ${l.failing} failing ${l.exempt} exempt`];for(const[t,o]of T(e.procedures)){n.push("",` ${t}`);for(const i of o)n.push(g(i,r),...k(i))}return n.join(`
3
3
  `)},C=(e,r)=>{const n=e.procedures.find(o=>o.id===r);if(n===void 0){const o=e.procedures.slice(0,10).map(i=>` ${i.id}`);return[`no procedure ${r} in the map. Known ids:`,...o,e.procedures.length>10?" …":""].filter(Boolean).join(`
4
4
  `)}const t=[`${E(n)} — ${String(n.score)}/100, ${n.coverage}`,` weight in the global mean: ${String(n.weight)}`];if(n.checks.length===0)return t.push(""," no rule fired"),t.join(`
@@ -1 +1 @@
1
- import{mkdtempSync as p,rmSync as u,existsSync as m,readdirSync as $,statSync as g}from"node:fs";import{tmpdir as S}from"node:os";import{join as y,relative as w}from"node:path";import{d as z}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as B}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{defaultSpawner as F}from"../packem_shared/createRecordingSpawner-sS7LEN7x.mjs";import{execArgsFor as h,detectPackageManager as x}from"@lunora/config";const v=e=>{const t=[],n=o=>{for(const s of $(o)){const r=y(o,s),i=g(r);i.isDirectory()?n(r):i.isFile()&&t.push({path:w(e,r),sizeBytes:i.size})}};return n(e),t},l=e=>e<1024?`${String(e)} B`:e<1024*1024?`${(e/1024).toFixed(1)} KiB`:`${(e/(1024*1024)).toFixed(2)} MiB`,M=e=>{const t=v(e),n=t.toSorted((r,i)=>i.sizeBytes-r.sizeBytes),o=t.reduce((r,i)=>r+i.sizeBytes,0);return{generatedFiles:t.filter(r=>r.path.includes("_generated")),outdir:e,topModules:n.slice(0,10),totalBytes:o,totalFiles:t.length}},O=(e,t)=>{if(t.info(`outdir: ${e.outdir}`),t.info(`total: ${String(e.totalFiles)} files, ${l(e.totalBytes)}`),e.topModules.length>0){t.info(""),t.info("top modules by size:");for(const n of e.topModules)t.info(` ${l(n.sizeBytes).padStart(10," ")} ${n.path}`)}if(e.generatedFiles.length>0){t.info(""),t.info(`_generated/ files: ${String(e.generatedFiles.length)}`);for(const n of e.generatedFiles)t.info(` ${l(n.sizeBytes).padStart(10," ")} ${n.path}`)}},j=async e=>{const t=e.cwd??process.cwd(),n=e.format==="json",{logger:o}=e;let s,r,i=!1;if(e.inspectOnly)s=e.inspectOnly;else{s=p(y(S(),"lunora-analyze-")),i=!0;const a=h(x(t),"wrangler",["deploy","--dry-run","--outdir",s]);r={args:a.args,command:a.command,cwd:t,stdoutToStderr:n},o.info(`analyze: building via ${r.command} ${r.args.join(" ")}`);const d=await(e.spawner??F)(r);if(d.code!==0){const f=`analyze: wrangler dry-run failed (exit ${String(d.code)})`;return o.error(f),u(s,{force:!0,recursive:!0}),{code:d.code,descriptor:r,error:f,report:void 0}}}try{if(!m(s)){const c=`analyze: outdir not found at ${s}`;return o.error(c),{code:B.NOT_FOUND,descriptor:r,error:c,report:void 0}}const a=M(s);return n||O(a,o),{code:0,descriptor:r,report:a}}finally{if(i&&m(s))try{u(s,{force:!0,recursive:!0})}catch{}}},N=z(async({cwd:e,format:t,logger:n})=>{const o=await j({cwd:e,format:t,logger:n});return{code:o.code,data:o.report,error:o.error}});export{N as execute,j as runAnalyzeCommand};
1
+ import{mkdtempSync as p,rmSync as u,existsSync as m,readdirSync as $,statSync as g}from"node:fs";import{tmpdir as S}from"node:os";import{join as y,relative as w}from"node:path";import{d as z}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as B}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{defaultSpawner as F}from"../packem_shared/createRecordingSpawner-CYhdPBD5.mjs";import{execArgsFor as h,detectPackageManager as x}from"@lunora/config";const v=e=>{const t=[],n=o=>{for(const s of $(o)){const r=y(o,s),i=g(r);i.isDirectory()?n(r):i.isFile()&&t.push({path:w(e,r),sizeBytes:i.size})}};return n(e),t},l=e=>e<1024?`${String(e)} B`:e<1024*1024?`${(e/1024).toFixed(1)} KiB`:`${(e/(1024*1024)).toFixed(2)} MiB`,M=e=>{const t=v(e),n=t.toSorted((r,i)=>i.sizeBytes-r.sizeBytes),o=t.reduce((r,i)=>r+i.sizeBytes,0);return{generatedFiles:t.filter(r=>r.path.includes("_generated")),outdir:e,topModules:n.slice(0,10),totalBytes:o,totalFiles:t.length}},O=(e,t)=>{if(t.info(`outdir: ${e.outdir}`),t.info(`total: ${String(e.totalFiles)} files, ${l(e.totalBytes)}`),e.topModules.length>0){t.info(""),t.info("top modules by size:");for(const n of e.topModules)t.info(` ${l(n.sizeBytes).padStart(10," ")} ${n.path}`)}if(e.generatedFiles.length>0){t.info(""),t.info(`_generated/ files: ${String(e.generatedFiles.length)}`);for(const n of e.generatedFiles)t.info(` ${l(n.sizeBytes).padStart(10," ")} ${n.path}`)}},j=async e=>{const t=e.cwd??process.cwd(),n=e.format==="json",{logger:o}=e;let s,r,i=!1;if(e.inspectOnly)s=e.inspectOnly;else{s=p(y(S(),"lunora-analyze-")),i=!0;const a=h(x(t),"wrangler",["deploy","--dry-run","--outdir",s]);r={args:a.args,command:a.command,cwd:t,stdoutToStderr:n},o.info(`analyze: building via ${r.command} ${r.args.join(" ")}`);const d=await(e.spawner??F)(r);if(d.code!==0){const f=`analyze: wrangler dry-run failed (exit ${String(d.code)})`;return o.error(f),u(s,{force:!0,recursive:!0}),{code:d.code,descriptor:r,error:f,report:void 0}}}try{if(!m(s)){const c=`analyze: outdir not found at ${s}`;return o.error(c),{code:B.NOT_FOUND,descriptor:r,error:c,report:void 0}}const a=M(s);return n||O(a,o),{code:0,descriptor:r,report:a}}finally{if(i&&m(s))try{u(s,{force:!0,recursive:!0})}catch{}}},N=z(async({cwd:e,format:t,logger:n})=>{const o=await j({cwd:e,format:t,logger:n});return{code:o.code,data:o.report,error:o.error}});export{N as execute,j as runAnalyzeCommand};
@@ -1 +1 @@
1
- import{join as u,resolve as m}from"node:path";import{p as f}from"../packem_shared/deploy-target-DCWwiuAe.mjs";import{d as p}from"../packem_shared/command-CAXl2A1S.mjs";import{defaultSpawner as w}from"../packem_shared/createRecordingSpawner-sS7LEN7x.mjs";import{runDeployCommand as y}from"./runDeployCommand.mjs";import{readdirSync as g,readFileSync as S}from"node:fs";import{gzipSync as b}from"node:zlib";const d=64*1024*1024,h=e=>!e.endsWith(".map")&&e!=="bundle-meta.json"&&e!=="README.md",v=e=>{let n;try{n=g(e,{recursive:!0,withFileTypes:!0})}catch{return}let o=0,r=0,t=0;for(const i of n){if(!i.isFile()||!h(i.name))continue;const a=S(u(i.parentPath,i.name));o+=1,t+=a.byteLength,r+=b(a).byteLength}return o===0?void 0:{files:o,gzipBytes:r,rawBytes:t}},l=".lunora/build",B=async e=>w({...e,stdoutToStderr:!0}),c=e=>`${(e/1024).toFixed(1)} KiB`,D=async e=>{const n=e.outDir??l,o=e.format==="json",{logger:r}=e,t=await y({allowSchemaDrift:e.allowSchemaDrift,apiSpec:e.apiSpec,commandName:"build",cwd:e.cwd,dryRun:!0,emitBindings:e.emitBindings,format:void 0,interactive:o?!1:void 0,logger:r,outDir:n,spawner:e.spawner??(o?B:void 0),strictAdvisories:e.strictAdvisories,target:e.target});if(t.code!==0)return t;r.success(`build complete — bundle written to ${n}`);const i=v(m(e.cwd??process.cwd(),n));if(i===void 0)r.warn(`could not weigh the bundle — nothing uploadable was found in ${n}`);else{const a=(i.rawBytes/d*100).toFixed(1),s=`bundle: ${c(i.rawBytes)} raw across ${String(i.files)} file(s) — ${a}% of Cloudflare's 64 MiB uncompressed Worker size limit (${c(i.gzipBytes)} gzipped, for reference; there is no compressed limit)`;i.rawBytes>d?r.warn(`${s} — Cloudflare will reject this upload`):r.info(s)}return{...t,bundle:i}},R=p(async({cwd:e,format:n,logger:o,options:r})=>{const t=await D({allowSchemaDrift:r.allowSchemaDrift===!0,apiSpec:f(r.apiSpec),cwd:e,emitBindings:r.emitBindings,format:n,logger:o,outDir:r.outDir,strictAdvisories:r.strictAdvisories,target:r.target});return{code:t.code,data:{bundle:t.bundle,deployment:t.deployment,outDir:r.outDir??l,validation:t.validation},error:t.error}});export{R as execute,D as runBuildCommand};
1
+ import{join as u,resolve as m}from"node:path";import{p as f}from"../packem_shared/deploy-target-DCWwiuAe.mjs";import{d as p}from"../packem_shared/command-CAXl2A1S.mjs";import{defaultSpawner as w}from"../packem_shared/createRecordingSpawner-CYhdPBD5.mjs";import{runDeployCommand as y}from"./runDeployCommand.mjs";import{readdirSync as g,readFileSync as S}from"node:fs";import{gzipSync as b}from"node:zlib";const d=64*1024*1024,h=e=>!e.endsWith(".map")&&e!=="bundle-meta.json"&&e!=="README.md",v=e=>{let n;try{n=g(e,{recursive:!0,withFileTypes:!0})}catch{return}let o=0,r=0,t=0;for(const i of n){if(!i.isFile()||!h(i.name))continue;const a=S(u(i.parentPath,i.name));o+=1,t+=a.byteLength,r+=b(a).byteLength}return o===0?void 0:{files:o,gzipBytes:r,rawBytes:t}},l=".lunora/build",B=async e=>w({...e,stdoutToStderr:!0}),c=e=>`${(e/1024).toFixed(1)} KiB`,D=async e=>{const n=e.outDir??l,o=e.format==="json",{logger:r}=e,t=await y({allowSchemaDrift:e.allowSchemaDrift,apiSpec:e.apiSpec,commandName:"build",cwd:e.cwd,dryRun:!0,emitBindings:e.emitBindings,format:void 0,interactive:o?!1:void 0,logger:r,outDir:n,spawner:e.spawner??(o?B:void 0),strictAdvisories:e.strictAdvisories,target:e.target});if(t.code!==0)return t;r.success(`build complete — bundle written to ${n}`);const i=v(m(e.cwd??process.cwd(),n));if(i===void 0)r.warn(`could not weigh the bundle — nothing uploadable was found in ${n}`);else{const a=(i.rawBytes/d*100).toFixed(1),s=`bundle: ${c(i.rawBytes)} raw across ${String(i.files)} file(s) — ${a}% of Cloudflare's 64 MiB uncompressed Worker size limit (${c(i.gzipBytes)} gzipped, for reference; there is no compressed limit)`;i.rawBytes>d?r.warn(`${s} — Cloudflare will reject this upload`):r.info(s)}return{...t,bundle:i}},R=p(async({cwd:e,format:n,logger:o,options:r})=>{const t=await D({allowSchemaDrift:r.allowSchemaDrift===!0,apiSpec:f(r.apiSpec),cwd:e,emitBindings:r.emitBindings,format:n,logger:o,outDir:r.outDir,strictAdvisories:r.strictAdvisories,target:r.target});return{code:t.code,data:{bundle:t.bundle,deployment:t.deployment,outDir:r.outDir??l,validation:t.validation},error:t.error}});export{R as execute,D as runBuildCommand};
@@ -1,2 +1,2 @@
1
- import{readLinkedProject as v,resolveDeployDriver as h,toolchainExecArgs as b,detectPackageManager as y}from"@lunora/config";import{d as w}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as d}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{defaultSpawner as L}from"../packem_shared/createRecordingSpawner-sS7LEN7x.mjs";import{createR2Sql as S}from"@lunora/bindings/r2sql";import{createPipelineLogReader as _}from"@lunora/runtime";const E=["trace","debug","log","info","warn","error","fatal"],T=new Set(E),f=/^\d+$/,u=(e,t)=>{if(e===void 0)return;const a=e.trim();if(f.test(a))return Number(a);const n=Date.parse(a);if(Number.isNaN(n))throw new TypeError(`logs: invalid ${t} "${e}" — pass epoch-millis or an ISO 8601 date`);return n},C=e=>Buffer.from(JSON.stringify(e),"utf8").toString("base64url"),I=e=>{const t=e.trim();if(f.test(t))return{ts:Number(t)};let a;try{a=JSON.parse(Buffer.from(t,"base64url").toString("utf8"))}catch{throw new TypeError(`logs: invalid --cursor "${e}" — expected the token printed by the previous page (or a bare epoch-millis ts)`)}if(typeof a!="object"||a===null||typeof a.ts!="number"||!Number.isFinite(a.ts))throw new TypeError(`logs: invalid --cursor "${e}" — expected the token printed by the previous page (or a bare epoch-millis ts)`);const{ts:n}=a,r=a.seen,s=Array.isArray(r)?r.filter(i=>typeof i=="string"):void 0;return s!==void 0&&s.length>0?{seen:s,ts:n}:{ts:n}},m=(e,t)=>{if(e!==void 0){if(!T.has(e))throw new TypeError(`logs: invalid ${t} "${e}" — expected one of trace, debug, log, info, warn, error, fatal`);return e}},p=e=>{const t={},a=u(e.since,"--since");a!==void 0&&(t.sinceTs=a);const n=u(e.until,"--until");n!==void 0&&(t.untilTs=n);const r=m(e.level,"--level");r!==void 0&&(t.level=r);const s=m(e.minLevel,"--min-level");if(s!==void 0&&(t.minLevel=s),e.functionPrefix!==void 0&&(t.functionPathPrefix=e.functionPrefix),e.traceId!==void 0&&(t.traceId=e.traceId),e.shardKey!==void 0&&(t.shardKey=e.shardKey),e.userId!==void 0&&(t.userId=e.userId),e.limit!==void 0){const i=Number(e.limit);if(!Number.isFinite(i))throw new TypeError(`logs: invalid --limit "${e.limit}" — expected a number`);t.limit=i}return e.cursor!==void 0&&(t.cursor=I(e.cursor)),t},R=e=>{const t=new Date(e.ts).toISOString(),a=e.level.toUpperCase().padEnd(5);return`${t} ${a} ${e.functionPath} ${e.message}`},$=async e=>{const t=e.environment??process.env,a=t.R2_SQL_ACCOUNT_ID,n=t.R2_SQL_TOKEN,r=t.R2_SQL_BUCKET,s=[];if((a===void 0||a.length===0)&&s.push("R2_SQL_ACCOUNT_ID"),(n===void 0||n.length===0)&&s.push("R2_SQL_TOKEN"),(r===void 0||r.length===0)&&s.push("R2_SQL_BUCKET"),(e.table===void 0||e.table.length===0)&&s.push("--table"),s.length>0)return e.logger.error(`logs --durable: R2 SQL not configured (missing ${s.join(", ")}). The Pipeline must write to an R2 Data Catalog (Iceberg) table, and you must supply R2_SQL_ACCOUNT_ID / R2_SQL_TOKEN / R2_SQL_BUCKET plus --table — see the observability docs.`),{code:d.USAGE,error:"not configured"};let i;try{i=p(e)}catch(c){return e.logger.error(c instanceof Error?c.message:String(c)),{code:d.USAGE,error:"invalid option"}}const o=S({accountId:a,apiToken:n,bucket:r,fetch:e.fetch}),l=await _(o,{namespace:e.namespace,table:e.table}).query(i);for(const c of l.rows)process.stdout.write(`${e.ndjson===!0?JSON.stringify(c):R(c)}
1
+ import{readLinkedProject as v,resolveDeployDriver as h,toolchainExecArgs as b,detectPackageManager as y}from"@lunora/config";import{d as w}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as d}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{defaultSpawner as L}from"../packem_shared/createRecordingSpawner-CYhdPBD5.mjs";import{createR2Sql as S}from"@lunora/bindings/r2sql";import{createPipelineLogReader as _}from"@lunora/runtime";const E=["trace","debug","log","info","warn","error","fatal"],T=new Set(E),f=/^\d+$/,u=(e,t)=>{if(e===void 0)return;const a=e.trim();if(f.test(a))return Number(a);const n=Date.parse(a);if(Number.isNaN(n))throw new TypeError(`logs: invalid ${t} "${e}" — pass epoch-millis or an ISO 8601 date`);return n},C=e=>Buffer.from(JSON.stringify(e),"utf8").toString("base64url"),I=e=>{const t=e.trim();if(f.test(t))return{ts:Number(t)};let a;try{a=JSON.parse(Buffer.from(t,"base64url").toString("utf8"))}catch{throw new TypeError(`logs: invalid --cursor "${e}" — expected the token printed by the previous page (or a bare epoch-millis ts)`)}if(typeof a!="object"||a===null||typeof a.ts!="number"||!Number.isFinite(a.ts))throw new TypeError(`logs: invalid --cursor "${e}" — expected the token printed by the previous page (or a bare epoch-millis ts)`);const{ts:n}=a,r=a.seen,s=Array.isArray(r)?r.filter(i=>typeof i=="string"):void 0;return s!==void 0&&s.length>0?{seen:s,ts:n}:{ts:n}},m=(e,t)=>{if(e!==void 0){if(!T.has(e))throw new TypeError(`logs: invalid ${t} "${e}" — expected one of trace, debug, log, info, warn, error, fatal`);return e}},p=e=>{const t={},a=u(e.since,"--since");a!==void 0&&(t.sinceTs=a);const n=u(e.until,"--until");n!==void 0&&(t.untilTs=n);const r=m(e.level,"--level");r!==void 0&&(t.level=r);const s=m(e.minLevel,"--min-level");if(s!==void 0&&(t.minLevel=s),e.functionPrefix!==void 0&&(t.functionPathPrefix=e.functionPrefix),e.traceId!==void 0&&(t.traceId=e.traceId),e.shardKey!==void 0&&(t.shardKey=e.shardKey),e.userId!==void 0&&(t.userId=e.userId),e.limit!==void 0){const i=Number(e.limit);if(!Number.isFinite(i))throw new TypeError(`logs: invalid --limit "${e.limit}" — expected a number`);t.limit=i}return e.cursor!==void 0&&(t.cursor=I(e.cursor)),t},R=e=>{const t=new Date(e.ts).toISOString(),a=e.level.toUpperCase().padEnd(5);return`${t} ${a} ${e.functionPath} ${e.message}`},$=async e=>{const t=e.environment??process.env,a=t.R2_SQL_ACCOUNT_ID,n=t.R2_SQL_TOKEN,r=t.R2_SQL_BUCKET,s=[];if((a===void 0||a.length===0)&&s.push("R2_SQL_ACCOUNT_ID"),(n===void 0||n.length===0)&&s.push("R2_SQL_TOKEN"),(r===void 0||r.length===0)&&s.push("R2_SQL_BUCKET"),(e.table===void 0||e.table.length===0)&&s.push("--table"),s.length>0)return e.logger.error(`logs --durable: R2 SQL not configured (missing ${s.join(", ")}). The Pipeline must write to an R2 Data Catalog (Iceberg) table, and you must supply R2_SQL_ACCOUNT_ID / R2_SQL_TOKEN / R2_SQL_BUCKET plus --table — see the observability docs.`),{code:d.USAGE,error:"not configured"};let i;try{i=p(e)}catch(c){return e.logger.error(c instanceof Error?c.message:String(c)),{code:d.USAGE,error:"invalid option"}}const o=S({accountId:a,apiToken:n,bucket:r,fetch:e.fetch}),l=await _(o,{namespace:e.namespace,table:e.table}).query(i);for(const c of l.rows)process.stdout.write(`${e.ndjson===!0?JSON.stringify(c):R(c)}
2
2
  `);return l.rows.length===0?e.logger.info("logs --durable: no matching log records"):l.nextCursor!==void 0&&e.logger.info(`logs --durable: more rows available — pass --cursor ${C(l.nextCursor)} for the next page`),{code:0,rows:l.rows}},N=async e=>{const t=e.cwd??process.cwd(),a=e.env??v(t)?.env,n=h(e.target),r=n.toolchain?.tail;if(r===void 0){const c=`logs: deploy target "${n.id}" has no log tail`;return e.logger.error(c),{code:d.USAGE,descriptor:void 0,error:c}}const s=r({environment:a,format:e.format,search:e.search,status:e.status,temporary:e.temporary,worker:e.worker}),i=b(y(t),s),o={args:i.args,command:i.command,cwd:t};return e.logger.info(`tailing logs via ${o.command} ${o.args.join(" ")}`),{code:(await(e.spawner??L)(o)).code,delegated:!0,descriptor:o}},U=w(async({argument:e,cwd:t,format:a,logger:n,options:r})=>{if(r.durable===!0){const s=await $({cursor:r.cursor,functionPrefix:r.functionPrefix,level:r.level,limit:r.limit,logger:n,minLevel:r.minLevel,namespace:r.namespace,ndjson:r.ndjson===!0,shardKey:r.shardKey,since:r.since,table:r.table,traceId:r.traceId,until:r.until,userId:r.userId});return{...s,...s.rows===void 0?{}:{delegated:!0}}}return N({cwd:t,env:r.env,format:a,logger:n,search:r.search,status:r.status,target:r.target,temporary:r.temporary===!0,worker:e[0]})});export{U as execute,N as runLogsCommand};
@@ -1 +1 @@
1
- import{existsSync as f,readFileSync as v,realpathSync as b}from"node:fs";import{join as u}from"node:path";import{DEV_VARS_FILE as h,parseDevVariableEntries as $,isPlaceholderValue as A,discoverSchemaInfo as R,inferLunoraBindings as S}from"@lunora/config";import{GLOBAL_FETCH_STRICTLY_PUBLIC_FLAG as m,findWranglerFile as j,readWranglerJsonc as L,validateWranglerProject as I,UNEXPORTED_CLASS_MARKER as y,collectExportGaps as N}from"@lunora/config/cloudflare";import{i as O,m as E,c as C}from"../packem_shared/secret-key-DsMeUoEg.mjs";import{r as P,d as D}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{d as V}from"../packem_shared/command-CAXl2A1S.mjs";import{i as F}from"../packem_shared/path-containment-CgxYZggb.mjs";import{b as k,c as _,a as g}from"../packem_shared/variables-acxcvVQa.mjs";import{readServiceBindings as U}from"@lunora/codegen";const G=(t,n)=>{const e=new Set,r=s=>{for(const[a,i]of Object.entries(s??{}))typeof i=="string"&&i.trim().length>0&&e.add(a)};r(t.vars);for(const s of Object.values(t.env??{}))r(s.vars);const o=u(n,h);if(f(o))try{r(Object.fromEntries($(v(o,"utf8")).map(s=>[s.key,s.value])))}catch{}return e},T=(t,n,e,r)=>{if(t===void 0||!e)return;const o=G(t,n),s=o.has(k),a=t.ai?.binding;!s&&(typeof a!="string"||a.length===0)&&r.push({code:"ai-binding-missing",fix:`Run \`lunora dev\` (it adds the binding), add \`"ai": { "binding": "AI" }\` to wrangler.jsonc, or set ${k} to an OpenAI-compatible proxy.`,level:"warn",message:"the project uses ctx.ai (@lunora/ai / env.AI) but wrangler.jsonc declares no `ai` binding — model calls will fail at runtime."}),o.has(_)&&r.push({code:"ai-gateway-token-unused",fix:"Make the gateway unauthenticated for ctx.ai, or remove the token. A bring-your-own AI SDK provider built with `resolveAiGateway` does send it.",level:"warn",message:`${_} is set, but ctx.ai's Workers AI binding cannot send a gateway token — it is ignored on that path.`}),!s&&!o.has(g)&&r.push({code:"ai-gateway-default",fix:`Run \`lunora ai gateway\` to create a gateway for this app and write ${g} into wrangler vars.`,level:"info",message:`no ${g} in vars or ${h} — \`<provider>/<model>\` slugs route through the account's \`default\` AI Gateway.`})},W=(t,n,e)=>{if(t===void 0||!n)return;const r=[];(t.compatibility_flags??[]).includes(m)||r.push("the top level");for(const[o,s]of Object.entries(t.env??{}))s.compatibility_flags!==void 0&&!s.compatibility_flags.includes(m)&&r.push(`env.${o}`);r.length>0&&e.push({code:"cimd-fetch-not-strictly-public",fix:`Add "${m}" to "compatibility_flags" in wrangler.jsonc.`,level:"warn",message:`@lunora/auth/cimd/workers is imported, but ${r.join(", ")} of wrangler.jsonc lacks the ${m} compatibility flag — workersCimdFetch() refuses to build without it.`})},x=t=>{const n=[],e=t?.logs?.enabled??t?.enabled??!0,r=t?.logs?.head_sampling_rate??t?.head_sampling_rate??1;return e&&r>=1&&n.push("logs"),t?.traces?.enabled===!0&&(t.traces.head_sampling_rate??1)>=1&&n.push("traces"),n},M=(t,n)=>{if(t===void 0)return;const e=[],r=x(t.observability);r.length>0&&e.push(`${r.join(" + ")} (top level)`);for(const[o,s]of Object.entries(t.env??{})){if(s.observability===void 0)continue;const a=x(s.observability);a.length>0&&e.push(`${a.join(" + ")} (env.${o})`)}e.length!==0&&n.push({code:"observability-full-sampling",fix:"For a high-traffic Worker, lower head_sampling_rate in wrangler.jsonc: under observability for logs, under observability.traces for traces — e.g. 0.1 keeps 10% of requests. Lunora never changes a rate you set.",level:"info",message:`observability samples every request (head_sampling_rate 1) for ${e.join(", ")}. From 2026-12-01 Workers Observability is billed: Free caps ingestion at 0.5 GB/day; Paid includes 50 GB per billing cycle, then $0.25/GB.`})},B=(t,n)=>{for(const e of U(t).services)for(const r of e.publicScopes){const o=r===""?"":` (env.${r})`;n.push({code:"service-workers-dev",fix:`Set \`"workers_dev": false\`${o} in ${e.wranglerPath} — the app's service binding is its only way in, so internal auth (HMAC) can go too.`,level:"warn",message:`service ${e.name} (${e.worker}) is bound by the app but still public on workers.dev${o}.`})}},K=t=>{const n=t.trim();if(n==="")return!0;const e=n.toLowerCase();return e.includes("replace")||e.startsWith("<")&&e.endsWith(">")},z=t=>{const n=j(t);if(n===void 0)return{parsed:void 0,path:void 0};const{parsed:e}=L(n);return{parsed:e,path:n}},H=(t,n,e,r)=>{if(e===void 0){r.push({code:"wrangler-missing",fix:"Run `lunora init` (or `lunora dev`) to scaffold and reconcile wrangler.jsonc.",level:"fail",message:"wrangler.jsonc not found."});return}if(n===void 0){r.push({code:"wrangler-unparseable",fix:`Check ${e} is valid JSONC.`,level:"fail",message:`Could not parse ${e}.`});return}const{report:o}=I({projectRoot:t});for(const i of o.errors.filter(l=>l.includes(y)))r.push({code:"wrangler-class-unexported",level:"fail",message:i});for(const i of o.warnings.filter(l=>l.includes("LUNORA_ORIGIN_URL")))r.push({code:"scheduler-origin-missing",fix:"Set LUNORA_ORIGIN_URL in wrangler vars to the worker's public URL (or `wrangler secret put LUNORA_ORIGIN_URL`).",level:"warn",message:i});const s=i=>i.includes(y)||i.includes("SHARD");for(const i of o.errors.filter(l=>!s(l)))r.push({code:"wrangler-invalid",fix:"Fix the reported wrangler.jsonc problem; `lunora verify` reports the same set.",level:"fail",message:i});for(const i of o.warnings.filter(l=>!l.includes("LUNORA_ORIGIN_URL")))r.push({code:"wrangler-advisory",level:"warn",message:i});const a=o.errors.find(i=>i.includes("SHARD"));a===void 0?r.push({code:"wrangler-shard-binding-ok",level:"pass",message:"wrangler.jsonc present with a SHARD durable-object binding."}):r.push({code:"wrangler-shard-binding-missing",fix:"Run `lunora dev` to auto-reconcile, or add the binding manually.",level:"fail",message:a})},q=(t,n)=>{f(u(t,"lunora.json"))&&n.push({code:"stale-lunora-json",fix:'Move `target` / `remote` into `lunora.config.ts` (`export default { target: "…" }`), then delete lunora.json.',level:"warn",message:"lunora.json is present but no longer read — lunora.config.* replaced it, so any `target` or `remote` in it is being ignored."})},Y=(t,n)=>{t===void 0||t.limits?.cpu_ms!==void 0||n.push({code:"cpu-limit-missing",fix:'Add `"limits": { "cpu_ms": 30000 }` to wrangler.jsonc, tuned to your slowest legitimate handler.',level:"info",message:"no limits.cpu_ms is set — a runaway handler can burn CPU up to the platform default before anything stops it."})},J=(t,n)=>{const e=(t?.r2_buckets??[]).map(r=>r?.bucket_name).filter(r=>typeof r=="string"&&r.length>0);e.length!==0&&n.push({code:"r2-lifecycle-unset",fix:"wrangler r2 bucket lifecycle list <bucket> — add an abort-incomplete-multipart rule if none exists.",level:"info",message:`R2 bucket(s) ${e.join(", ")}: verify a lifecycle rule aborts incomplete multipart uploads — orphaned parts are billed but invisible in a listing.`})},X=(t,n)=>{const{error:e,info:r}=R(t,"lunora");if(e!==void 0){n.push({code:"schema-unreadable",fix:"Fix the parse error, then re-run `lunora doctor`. `lunora codegen` reports the same failure with the offending source.",level:"fail",message:`lunora/schema.ts could not be parsed, so every schema-derived check was skipped: ${e}`});return}for(const o of r?.vectorMetadata??[]){const s=E(o.kind);if(s===void 0){n.push({code:"vector-metadata-unfilterable",fix:"Filter on a string, number or boolean column, or drop it from `metadata`.",level:"warn",message:`vector index "${o.index}" declares metadata "${o.property}", whose type Vectorize cannot filter on.`});continue}n.push({code:"vector-metadata-index-required",fix:`wrangler ${C({index:o.index,property:o.property,type:s}).join(" ")}`,level:"info",message:`vector index "${o.index}" filters on metadata "${o.property}" — that needs a Vectorize metadata index (\`lunora deploy\` creates it).`})}},Q=(t,n)=>{if(t===void 0)return;const e=(t.d1_databases??[]).filter(Boolean);for(const r of e){const o=typeof r.database_id=="string"?r.database_id:"";if(K(o)){const s=typeof r.binding=="string"&&r.binding.length>0?r.binding:"<unnamed>";n.push({code:"d1-placeholder-id",fix:"Run `wrangler d1 create <name>` and paste the returned database_id into wrangler.jsonc.",level:"fail",message:`D1 binding "${s}" has a placeholder database_id ("${o||"<empty>"}").`})}}},Z=(t,n)=>{if(t===void 0)return;const e=(t.send_email??[]).filter(Boolean);for(const r of e){const o=typeof r.destination_address=="string"?r.destination_address:"";if(o!==""&&A(o)){const s=typeof r.name=="string"&&r.name.length>0?r.name:"send_email";n.push({code:"email-destination-placeholder",fix:"Set destination_address to a verified Cloudflare Email Routing address.",level:"warn",message:`send_email binding "${s}" has a placeholder destination_address ("${o}").`})}}},ee=(t,n)=>{const e=u(t,h);if(!f(e))return;let r;try{r=v(e,"utf8")}catch{return}const o=$(r).filter(s=>O(s.key)&&A(s.value)).map(s=>s.key);o.length>0&&n.push({code:"dev-vars-missing-secret",fix:"Run `lunora dev` to auto-generate secrets, or fill them in by hand.",level:"warn",message:`${h} has unfilled secret value(s): ${o.join(", ")}.`})},ne=(t,n)=>{const{source:e}=P({cwd:t});e===void 0?n.push({code:"admin-token-missing",fix:"Set LUNORA_ADMIN_TOKEN (env or `.dev.vars`) to enable admin RPCs / studio.",level:"info",message:"LUNORA_ADMIN_TOKEN is not set."}):n.push({code:"admin-token-set",level:"pass",message:`LUNORA_ADMIN_TOKEN is set (${D(e)}).`})},re=async(t,n)=>{try{return await S({projectRoot:t})}catch(e){n.push({code:"declared-export-unchecked",fix:"Make sure the worker entry resolves (see `lunora codegen`), then re-run.",level:"warn",message:`could not check whether declared containers/workflows/agents are re-exported by the worker entry: ${e instanceof Error?e.message:String(e)}`});return}},te=(t,n)=>{const e=N(t),r=[...t.containers.map(o=>({...o,kind:"container"})),...t.workflows.map(o=>({...o,kind:"workflow"})),...t.agents.map(o=>({...o,kind:"agent"}))];for(const o of r.filter(s=>s.exported))n.push({code:"declared-export-ok",level:"pass",message:`${o.kind} "${o.exportName}" is exported by the worker entry.`});for(const o of e)n.push({code:"declared-export-missing",fix:`Add \`export * from "./lunora/_generated/${o.module}"\` to your worker entry (or re-run \`vis generate lunora-${o.kind}\`).`,level:"fail",message:`${o.kind} "${o.exportName}" is declared but ${o.className} is not exported by the worker entry.`})},oe=/^[\^~><= ]+/u,se=/^(?<core>\d+\.\d+\.\d+)(?:-(?<channel>[a-z]+)\.(?<counter>\d+))?$/u,ae=t=>{const n=t.replace(oe,"").trim(),e=se.exec(n);if(!e?.groups)return;const{channel:r,core:o,counter:s}=e.groups;return{channel:r??"",core:o??"",counter:s===void 0?void 0:Number.parseInt(s,10),raw:n}},ie=(t,n)=>{const e=u(t,"package.json");if(!f(e))return;let r;try{r=JSON.parse(v(e,"utf8"))}catch{return}const o={...r.devDependencies,...r.dependencies},s=[];for(const[c,d]of Object.entries(o)){if(c!=="lunorash"&&!c.startsWith("@lunora/"))continue;const w=ae(d);w&&s.push({name:c,version:w})}if(s.length<2)return;const a=c=>c.map(d=>`${d.name}@${d.version.raw}`).join(", "),i=new Set(s.map(c=>c.version.core)),l=new Set(s.map(c=>c.version.channel));if(i.size>1){n.push({code:"version-skew-cores",fix:'Run `pnpm update "@lunora/*" lunorash` (or `npm`/`yarn` equivalent) so every Lunora package moves to the same release.',level:"warn",message:`Lunora packages span ${String(i.size)} different versions: ${a(s)}.`});return}if(l.size>1){n.push({code:"version-skew-channels",fix:"Pick one channel (all stable, or all alpha/beta) and update the odd package out.",level:"warn",message:`Lunora packages mix release channels (${[...l].map(c=>c===""?"stable":c).join(" + ")}): ${a(s)}.`});return}const p=s.map(c=>c.version.counter).filter(c=>c!==void 0);if(p.length>1){const c=Math.min(...p),d=Math.max(...p);n.push({code:"version-counter-spread",level:"info",message:p.length===s.length&&c===d?`Lunora packages are all at ${[...l][0]??""}.${String(d)}.`:`Lunora pre-release counters span ${String(c)}–${String(d)}: ${a(s)}.`})}},ce=[u("@lunora","cli"),"lunorash"],le=(t,n,e)=>{if(n===void 0)return;const r=[];for(const s of ce){const a=u(t,"node_modules",s);if(f(a))try{r.push(b(a))}catch{}}if(r.length===0)return;let o;try{o=b(n)}catch{return}r.some(s=>F(s,o))||e.push({code:"cli-shadowed",fix:"Run the project's own CLI: `pnpm exec lunora …` (or `npx lunora …`).",level:"warn",message:`the running lunora (${o}) is not the project's own install (${r.join(", ")}).`})},de=async t=>{const n=t.cwd??process.cwd(),e=[],{parsed:r,path:o}=z(n);H(n,r,o,e),Q(r,e),Z(r,e),Y(r,e),J(r,e),M(r,e),ee(n,e),ne(n,e),ie(n,e),X(n,e),q(n,e),le(n,t.executablePath??process.argv[1],e),B(n,e);const s=await re(n,e);s!==void 0&&te(s,e),T(r,n,s?.usesAi===!0,e),W(r,s?.usesCimdWorkers===!0,e);const a={fail:0,info:0,pass:0,warn:0};for(const l of e)a[l.level]+=1;const i=a.fail>0?1:0;return{code:i,findings:e,ok:i===0,summary:a}},ue={fail:"FAIL",info:"INFO",pass:"PASS",warn:"WARN"},fe=(t,n)=>{n.info("lunora doctor — project preflight");for(const o of t.findings){const s=`[${ue[o.level]}] ${o.message}`;o.level==="fail"?n.error(s):o.level==="warn"?n.warn(s):n.info(s),o.fix!==void 0&&o.level!=="pass"&&n.info(` fix: ${o.fix}`)}const{fail:e,warn:r}=t.summary;e>0?n.error(`${String(e)} failure(s), ${String(r)} warning(s).`):r>0?n.warn(`0 failures, ${String(r)} warning(s).`):n.success("all checks passed.")},pe=async t=>{const{logger:n}=t,e=await de({...t});return fe(e,n),e},$e=V(async({cwd:t,format:n,logger:e})=>{const r=await pe({cwd:t,format:n,logger:e});return{code:r.code,data:{findings:r.findings,summary:r.summary}}});export{$e as execute,de as runDoctor,pe as runDoctorCommand};
1
+ import{existsSync as f,readFileSync as v,realpathSync as w}from"node:fs";import{join as u}from"node:path";import{DEV_VARS_FILE as h,parseDevVariableEntries as $,isPlaceholderValue as A,discoverSchemaInfo as R,inferLunoraBindings as S,resolveSchemaDirectory as j}from"@lunora/config";import{GLOBAL_FETCH_STRICTLY_PUBLIC_FLAG as m,resolveObservabilitySampling as L,findWranglerFile as I,readWranglerJsonc as O,validateWranglerProject as N,UNEXPORTED_CLASS_MARKER as y,collectExportGaps as E}from"@lunora/config/cloudflare";import{i as C,m as D,c as P}from"../packem_shared/secret-key-DsMeUoEg.mjs";import{r as V,d as F}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{d as U}from"../packem_shared/command-CAXl2A1S.mjs";import{i as G}from"../packem_shared/path-containment-CgxYZggb.mjs";import{b as k,c as x,a as g}from"../packem_shared/variables-acxcvVQa.mjs";import{readServiceBindings as T}from"@lunora/codegen";const W=(o,r)=>{const e=new Set,n=s=>{for(const[a,i]of Object.entries(s??{}))typeof i=="string"&&i.trim().length>0&&e.add(a)};n(o.vars);for(const s of Object.values(o.env??{}))n(s.vars);const t=u(r,h);if(f(t))try{n(Object.fromEntries($(v(t,"utf8")).map(s=>[s.key,s.value])))}catch{}return e},M=(o,r,e,n)=>{if(o===void 0||!e)return;const t=W(o,r),s=t.has(k),a=o.ai?.binding;!s&&(typeof a!="string"||a.length===0)&&n.push({code:"ai-binding-missing",fix:`Run \`lunora dev\` (it adds the binding), add \`"ai": { "binding": "AI" }\` to wrangler.jsonc, or set ${k} to an OpenAI-compatible proxy.`,level:"warn",message:"the project uses ctx.ai (@lunora/ai / env.AI) but wrangler.jsonc declares no `ai` binding — model calls will fail at runtime."}),t.has(x)&&n.push({code:"ai-gateway-token-unused",fix:"Make the gateway unauthenticated for ctx.ai, or remove the token. A bring-your-own AI SDK provider built with `resolveAiGateway` does send it.",level:"warn",message:`${x} is set, but ctx.ai's Workers AI binding cannot send a gateway token — it is ignored on that path.`}),!s&&!t.has(g)&&n.push({code:"ai-gateway-default",fix:`Run \`lunora ai gateway\` to create a gateway for this app and write ${g} into wrangler vars.`,level:"info",message:`no ${g} in vars or ${h} — \`<provider>/<model>\` slugs route through the account's \`default\` AI Gateway.`})},B=(o,r,e)=>{if(o===void 0||!r)return;const n=[];(o.compatibility_flags??[]).includes(m)||n.push("the top level");for(const[t,s]of Object.entries(o.env??{}))s.compatibility_flags!==void 0&&!s.compatibility_flags.includes(m)&&n.push(`env.${t}`);n.length>0&&e.push({code:"cimd-fetch-not-strictly-public",fix:`Add "${m}" to "compatibility_flags" in wrangler.jsonc.`,level:"warn",message:`@lunora/auth/cimd/workers is imported, but ${n.join(", ")} of wrangler.jsonc lacks the ${m} compatibility flag — workersCimdFetch() refuses to build without it.`})},_=o=>{const{logs:r,traces:e}=L(o);return Object.entries({logs:r,traces:e}).filter(([,n])=>n.enabled&&n.headSamplingRate>=1).map(([n])=>n)},K=(o,r)=>{if(o===void 0)return;const e=[],n=_(o.observability);n.length>0&&e.push(`${n.join(" + ")} (top level)`);for(const[t,s]of Object.entries(o.env??{})){if(s.observability===void 0)continue;const a=_(s.observability);a.length>0&&e.push(`${a.join(" + ")} (env.${t})`)}e.length!==0&&r.push({code:"observability-full-sampling",fix:"For a high-traffic Worker, lower head_sampling_rate in wrangler.jsonc: under observability for logs, under observability.traces for traces — e.g. 0.1 keeps 10% of requests. Lunora never changes a rate you set.",level:"info",message:`observability samples every request (head_sampling_rate 1) for ${e.join(", ")}. From 2026-12-01 Workers Observability is billed: Free caps ingestion at 0.5 GB/day; Paid includes 50 GB per billing cycle, then $0.25/GB.`})},z=(o,r)=>{for(const e of T(o).services)for(const n of e.publicScopes){const t=n===""?"":` (env.${n})`;r.push({code:"service-workers-dev",fix:`Set \`"workers_dev": false\`${t} in ${e.wranglerPath} — the app's service binding is its only way in, so internal auth (HMAC) can go too.`,level:"warn",message:`service ${e.name} (${e.worker}) is bound by the app but still public on workers.dev${t}.`})}},H=o=>{const r=o.trim();if(r==="")return!0;const e=r.toLowerCase();return e.includes("replace")||e.startsWith("<")&&e.endsWith(">")},q=o=>{const r=I(o);if(r===void 0)return{parsed:void 0,path:void 0};const{parsed:e}=O(r);return{parsed:e,path:r}},Y=(o,r,e,n)=>{if(e===void 0){n.push({code:"wrangler-missing",fix:"Run `lunora init` (or `lunora dev`) to scaffold and reconcile wrangler.jsonc.",level:"fail",message:"wrangler.jsonc not found."});return}if(r===void 0){n.push({code:"wrangler-unparseable",fix:`Check ${e} is valid JSONC.`,level:"fail",message:`Could not parse ${e}.`});return}const{report:t}=N({projectRoot:o});for(const i of t.errors.filter(l=>l.includes(y)))n.push({code:"wrangler-class-unexported",level:"fail",message:i});for(const i of t.warnings.filter(l=>l.includes("LUNORA_ORIGIN_URL")))n.push({code:"scheduler-origin-missing",fix:"Set LUNORA_ORIGIN_URL in wrangler vars to the worker's public URL (or `wrangler secret put LUNORA_ORIGIN_URL`).",level:"warn",message:i});const s=i=>i.includes(y)||i.includes("SHARD");for(const i of t.errors.filter(l=>!s(l)))n.push({code:"wrangler-invalid",fix:"Fix the reported wrangler.jsonc problem; `lunora verify` reports the same set.",level:"fail",message:i});for(const i of t.warnings.filter(l=>!l.includes("LUNORA_ORIGIN_URL")))n.push({code:"wrangler-advisory",level:"warn",message:i});const a=t.errors.find(i=>i.includes("SHARD"));a===void 0?n.push({code:"wrangler-shard-binding-ok",level:"pass",message:"wrangler.jsonc present with a SHARD durable-object binding."}):n.push({code:"wrangler-shard-binding-missing",fix:"Run `lunora dev` to auto-reconcile, or add the binding manually.",level:"fail",message:a})},J=(o,r)=>{f(u(o,"lunora.json"))&&r.push({code:"stale-lunora-json",fix:'Move `target` / `remote` into `lunora.config.ts` (`export default { target: "…" }`), then delete lunora.json.',level:"warn",message:"lunora.json is present but no longer read — lunora.config.* replaced it, so any `target` or `remote` in it is being ignored."})},X=(o,r)=>{o===void 0||o.limits?.cpu_ms!==void 0||r.push({code:"cpu-limit-missing",fix:'Add `"limits": { "cpu_ms": 30000 }` to wrangler.jsonc, tuned to your slowest legitimate handler.',level:"info",message:"no limits.cpu_ms is set — a runaway handler can burn CPU up to the platform default before anything stops it."})},Q=(o,r)=>{const e=(o?.r2_buckets??[]).map(n=>n?.bucket_name).filter(n=>typeof n=="string"&&n.length>0);e.length!==0&&r.push({code:"r2-lifecycle-unset",fix:"wrangler r2 bucket lifecycle list <bucket> — add an abort-incomplete-multipart rule if none exists.",level:"info",message:`R2 bucket(s) ${e.join(", ")}: verify a lifecycle rule aborts incomplete multipart uploads — orphaned parts are billed but invisible in a listing.`})},Z=(o,r)=>{const{error:e,info:n}=R(o,"lunora");if(e!==void 0){r.push({code:"schema-unreadable",fix:"Fix the parse error, then re-run `lunora doctor`. `lunora codegen` reports the same failure with the offending source.",level:"fail",message:`lunora/schema.ts could not be parsed, so every schema-derived check was skipped: ${e}`});return}for(const t of n?.vectorMetadata??[]){const s=D(t.kind);if(s===void 0){r.push({code:"vector-metadata-unfilterable",fix:"Filter on a string, number or boolean column, or drop it from `metadata`.",level:"warn",message:`vector index "${t.index}" declares metadata "${t.property}", whose type Vectorize cannot filter on.`});continue}r.push({code:"vector-metadata-index-required",fix:`wrangler ${P({index:t.index,property:t.property,type:s}).join(" ")}`,level:"info",message:`vector index "${t.index}" filters on metadata "${t.property}" — that needs a Vectorize metadata index (\`lunora deploy\` creates it).`})}},ee=(o,r)=>{if(o===void 0)return;const e=(o.d1_databases??[]).filter(Boolean);for(const n of e){const t=typeof n.database_id=="string"?n.database_id:"";if(H(t)){const s=typeof n.binding=="string"&&n.binding.length>0?n.binding:"<unnamed>";r.push({code:"d1-placeholder-id",fix:"Run `wrangler d1 create <name>` and paste the returned database_id into wrangler.jsonc.",level:"fail",message:`D1 binding "${s}" has a placeholder database_id ("${t||"<empty>"}").`})}}},ne=(o,r)=>{if(o===void 0)return;const e=(o.send_email??[]).filter(Boolean);for(const n of e){const t=typeof n.destination_address=="string"?n.destination_address:"";if(t!==""&&A(t)){const s=typeof n.name=="string"&&n.name.length>0?n.name:"send_email";r.push({code:"email-destination-placeholder",fix:"Set destination_address to a verified Cloudflare Email Routing address.",level:"warn",message:`send_email binding "${s}" has a placeholder destination_address ("${t}").`})}}},re=(o,r)=>{const e=u(o,h);if(!f(e))return;let n;try{n=v(e,"utf8")}catch{return}const t=$(n).filter(s=>C(s.key)&&A(s.value)).map(s=>s.key);t.length>0&&r.push({code:"dev-vars-missing-secret",fix:"Run `lunora dev` to auto-generate secrets, or fill them in by hand.",level:"warn",message:`${h} has unfilled secret value(s): ${t.join(", ")}.`})},te=(o,r)=>{const{source:e}=V({cwd:o});e===void 0?r.push({code:"admin-token-missing",fix:"Set LUNORA_ADMIN_TOKEN (env or `.dev.vars`) to enable admin RPCs / studio.",level:"info",message:"LUNORA_ADMIN_TOKEN is not set."}):r.push({code:"admin-token-set",level:"pass",message:`LUNORA_ADMIN_TOKEN is set (${F(e)}).`})},oe=async(o,r)=>{try{return await S({projectRoot:o,schemaDir:j(o)})}catch(e){r.push({code:"declared-export-unchecked",fix:"Make sure the worker entry resolves (see `lunora codegen`), then re-run.",level:"warn",message:`could not check whether declared containers/workflows/agents are re-exported by the worker entry: ${e instanceof Error?e.message:String(e)}`});return}},se=(o,r)=>{const e=E(o),n=[...o.containers.map(t=>({...t,kind:"container"})),...o.workflows.map(t=>({...t,kind:"workflow"})),...o.agents.map(t=>({...t,kind:"agent"}))];for(const t of n.filter(s=>s.exported))r.push({code:"declared-export-ok",level:"pass",message:`${t.kind} "${t.exportName}" is exported by the worker entry.`});for(const t of e)r.push({code:"declared-export-missing",fix:`Add \`export * from "./lunora/_generated/${t.module}"\` to your worker entry (or re-run \`vis generate lunora-${t.kind}\`).`,level:"fail",message:`${t.kind} "${t.exportName}" is declared but ${t.className} is not exported by the worker entry.`})},ae=/^[\^~><= ]+/u,ie=/^(?<core>\d+\.\d+\.\d+)(?:-(?<channel>[a-z]+)\.(?<counter>\d+))?$/u,ce=o=>{const r=o.replace(ae,"").trim(),e=ie.exec(r);if(!e?.groups)return;const{channel:n,core:t,counter:s}=e.groups;return{channel:n??"",core:t??"",counter:s===void 0?void 0:Number.parseInt(s,10),raw:r}},le=(o,r)=>{const e=u(o,"package.json");if(!f(e))return;let n;try{n=JSON.parse(v(e,"utf8"))}catch{return}const t={...n.devDependencies,...n.dependencies},s=[];for(const[c,d]of Object.entries(t)){if(c!=="lunorash"&&!c.startsWith("@lunora/"))continue;const b=ce(d);b&&s.push({name:c,version:b})}if(s.length<2)return;const a=c=>c.map(d=>`${d.name}@${d.version.raw}`).join(", "),i=new Set(s.map(c=>c.version.core)),l=new Set(s.map(c=>c.version.channel));if(i.size>1){r.push({code:"version-skew-cores",fix:'Run `pnpm update "@lunora/*" lunorash` (or `npm`/`yarn` equivalent) so every Lunora package moves to the same release.',level:"warn",message:`Lunora packages span ${String(i.size)} different versions: ${a(s)}.`});return}if(l.size>1){r.push({code:"version-skew-channels",fix:"Pick one channel (all stable, or all alpha/beta) and update the odd package out.",level:"warn",message:`Lunora packages mix release channels (${[...l].map(c=>c===""?"stable":c).join(" + ")}): ${a(s)}.`});return}const p=s.map(c=>c.version.counter).filter(c=>c!==void 0);if(p.length>1){const c=Math.min(...p),d=Math.max(...p);r.push({code:"version-counter-spread",level:"info",message:p.length===s.length&&c===d?`Lunora packages are all at ${[...l][0]??""}.${String(d)}.`:`Lunora pre-release counters span ${String(c)}–${String(d)}: ${a(s)}.`})}},de=[u("@lunora","cli"),"lunorash"],ue=(o,r,e)=>{if(r===void 0)return;const n=[];for(const s of de){const a=u(o,"node_modules",s);if(f(a))try{n.push(w(a))}catch{}}if(n.length===0)return;let t;try{t=w(r)}catch{return}n.some(s=>G(s,t))||e.push({code:"cli-shadowed",fix:"Run the project's own CLI: `pnpm exec lunora …` (or `npx lunora …`).",level:"warn",message:`the running lunora (${t}) is not the project's own install (${n.join(", ")}).`})},fe=async o=>{const r=o.cwd??process.cwd(),e=[],{parsed:n,path:t}=q(r);Y(r,n,t,e),ee(n,e),ne(n,e),X(n,e),Q(n,e),K(n,e),re(r,e),te(r,e),le(r,e),Z(r,e),J(r,e),ue(r,o.executablePath??process.argv[1],e),z(r,e);const s=await oe(r,e);s!==void 0&&se(s,e),M(n,r,s?.usesAi===!0,e),B(n,s?.usesCimdWorkers===!0,e);const a={fail:0,info:0,pass:0,warn:0};for(const l of e)a[l.level]+=1;const i=a.fail>0?1:0;return{code:i,findings:e,ok:i===0,summary:a}},pe={fail:"FAIL",info:"INFO",pass:"PASS",warn:"WARN"},me=(o,r)=>{r.info("lunora doctor — project preflight");for(const t of o.findings){const s=`[${pe[t.level]}] ${t.message}`;t.level==="fail"?r.error(s):t.level==="warn"?r.warn(s):r.info(s),t.fix!==void 0&&t.level!=="pass"&&r.info(` fix: ${t.fix}`)}const{fail:e,warn:n}=o.summary;e>0?r.error(`${String(e)} failure(s), ${String(n)} warning(s).`):n>0?r.warn(`0 failures, ${String(n)} warning(s).`):r.success("all checks passed.")},he=async o=>{const{logger:r}=o,e=await fe({...o});return me(e,r),e},Re=U(async({cwd:o,format:r,logger:e})=>{const n=await he({cwd:o,format:r,logger:e});return{code:n.code,data:{findings:n.findings,summary:n.summary}}});export{Re as execute,fe as runDoctor,he as runDoctorCommand};
@@ -1,4 +1,4 @@
1
- import{V as R}from"../packem_shared/cli-C4OL2wM9.mjs";import{d as G}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as d}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{existsSync as f,readFileSync as h,mkdirSync as J,realpathSync as W,statSync as V,writeFileSync as z,chmodSync as H,renameSync as K,unlinkSync as q}from"node:fs";import{homedir as w}from"node:os";import{findWranglerFile as X}from"@lunora/config/cloudflare";import{join as s,dirname as B,relative as Z}from"@visulima/path";import{stringify as Q}from"smol-toml";import{parse as Y,modify as ee,applyEdits as re}from"jsonc-parser";import{detectPackageManager as te,execArgsFor as ne,readLiveDevServerState as S,DEV_STATE_DIR as oe}from"@lunora/config";import{resolveAdminToken as ae}from"@lunora/config/studio-host";import{connectLocalStdio as le}from"@lunora/mcp";import{resolve as y}from"node:path";import{i as ce}from"../packem_shared/path-containment-CgxYZggb.mjs";const m=e=>({args:[...e.args],command:e.command,...e.env===void 0?{}:{env:e.env}}),b=e=>e.transport==="http"?{type:"http",url:e.url}:m(e),se=e=>e.transport==="http"?{httpUrl:e.url}:m(e),ie=e=>e.transport==="http"?{serverUrl:e.url}:m(e),de=e=>({args:["-y","mcp-remote",e],command:"npx"}),ue=e=>e.transport==="http"?de(e.url):m(e),fe=e=>e.transport==="http"?{url:e.url}:m(e),me=e=>e.transport==="http"?{enabled:!0,type:"remote",url:e.url}:{command:[e.command,...e.args],enabled:!0,type:"local",...e.env===void 0?{}:{environment:e.env}},pe=e=>e.transport==="http"?{disabled:!1,type:"streamableHttp",url:e.url}:{disabled:!1,...m(e)},ge=({home:e,platform:r})=>{if(r==="darwin")return{global:s(e,"Library","Application Support","Claude","claude_desktop_config.json")};if(r==="win32"){const t=process.env.APPDATA;return t===void 0||t===""?{}:{global:s(t,"Claude","claude_desktop_config.json")}}return r==="linux"?{global:s(e,".config","Claude","claude_desktop_config.json")}:{}},ve=(e,r)=>Q({mcp_servers:{[e]:r.transport==="http"?{url:r.url}:{args:[...r.args],command:r.command,...r.env===void 0?{}:{env:r.env}}}}),v=[{buildEntry:b,paths:({projectRoot:e})=>({project:s(e,".mcp.json")}),format:"json",id:"claude-code",key:"mcpServers",label:"Claude Code"},{buildEntry:b,paths:({home:e,projectRoot:r})=>({global:s(e,".cursor","mcp.json"),project:s(r,".cursor","mcp.json")}),format:"json",id:"cursor",key:"mcpServers",label:"Cursor"},{buildEntry:b,paths:({projectRoot:e})=>({project:s(e,".vscode","mcp.json")}),format:"json",id:"vscode",key:"servers",label:"VS Code (GitHub Copilot)"},{buildEntry:se,paths:({home:e,projectRoot:r})=>({global:s(e,".gemini","settings.json"),project:s(r,".gemini","settings.json")}),format:"json",id:"gemini",key:"mcpServers",label:"Gemini CLI"},{buildEntry:ue,paths:ge,format:"json",id:"claude-desktop",key:"mcpServers",label:"Claude Desktop"},{buildEntry:ie,paths:({home:e})=>({global:s(e,".codeium","windsurf","mcp_config.json")}),format:"json",id:"windsurf",key:"mcpServers",label:"Windsurf"},{buildEntry:me,paths:({home:e,projectRoot:r})=>({global:s(e,".config","opencode","opencode.json"),project:s(r,"opencode.json")}),format:"json",id:"opencode",key:"mcp",label:"OpenCode"},{buildEntry:pe,paths:({home:e})=>({global:s(e,".cline","mcp.json")}),format:"json",id:"cline",key:"mcpServers",label:"Cline"},{buildEntry:fe,paths:({home:e})=>({global:s(e,".config","zed","settings.json")}),format:"json",id:"zed",key:"context_servers",label:"Zed"},{paths:({home:e,projectRoot:r})=>({global:s(e,".codex","config.toml"),project:s(r,".codex","config.toml")}),format:"manual",id:"codex",label:"Codex CLI",renderSnippet:ve}],x=v.map(e=>e.id),he=e=>v.find(r=>r.id===e.toLowerCase()),M=(e,r)=>{let t=e,n;try{t=W(e),n=V(t).mode}catch{}const a=`${t}.lunora-${Math.random().toString(36).slice(2,10)}.tmp`;try{z(a,r,"utf8"),n!==void 0&&H(a,n),K(a,t)}catch(o){try{q(a)}catch{}throw o}},ye={formattingOptions:{insertSpaces:!0,tabSize:4}},k=e=>{const r=[],t=Y(e,r,{allowTrailingComma:!0});return{errors:r,value:t}},g=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),E=(e,r,t)=>{if(!g(e))return;const n=e[r];return g(n)?n[t]:void 0},L=e=>{if(!f(e.path))return"absent";let r;try{r=h(e.path,"utf8")}catch{return"invalid"}if(r.trim().length===0)return"absent";const{errors:t,value:n}=k(r);return t.length>0||!g(n)?"invalid":E(n,e.key,e.name)===void 0?"absent":"present"},be=e=>L(e)==="present",U=(e,r,t,n,a)=>{try{const o=ee(e,[t,n],a,ye);o.length>0&&M(r,re(e,o));return}catch(o){return o instanceof Error?o.message:String(o)}},Se=e=>{const{entry:r,force:t=!1,key:n,name:a,path:o}=e,l=f(o)?h(o,"utf8"):"";if(l.trim().length===0)return J(B(o),{recursive:!0}),M(o,`${JSON.stringify({[n]:{[a]:r}},void 0,4)}
1
+ import{V as R}from"../packem_shared/cli-CG_JgNKu.mjs";import{d as G}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as d}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{existsSync as f,readFileSync as h,mkdirSync as J,realpathSync as W,statSync as V,writeFileSync as z,chmodSync as H,renameSync as K,unlinkSync as q}from"node:fs";import{homedir as w}from"node:os";import{findWranglerFile as X}from"@lunora/config/cloudflare";import{join as s,dirname as B,relative as Z}from"@visulima/path";import{stringify as Q}from"smol-toml";import{parse as Y,modify as ee,applyEdits as re}from"jsonc-parser";import{detectPackageManager as te,execArgsFor as ne,readLiveDevServerState as S,DEV_STATE_DIR as oe}from"@lunora/config";import{resolveAdminToken as ae}from"@lunora/config/studio-host";import{connectLocalStdio as le}from"@lunora/mcp";import{resolve as y}from"node:path";import{i as ce}from"../packem_shared/path-containment-CgxYZggb.mjs";const m=e=>({args:[...e.args],command:e.command,...e.env===void 0?{}:{env:e.env}}),b=e=>e.transport==="http"?{type:"http",url:e.url}:m(e),se=e=>e.transport==="http"?{httpUrl:e.url}:m(e),ie=e=>e.transport==="http"?{serverUrl:e.url}:m(e),de=e=>({args:["-y","mcp-remote",e],command:"npx"}),ue=e=>e.transport==="http"?de(e.url):m(e),fe=e=>e.transport==="http"?{url:e.url}:m(e),me=e=>e.transport==="http"?{enabled:!0,type:"remote",url:e.url}:{command:[e.command,...e.args],enabled:!0,type:"local",...e.env===void 0?{}:{environment:e.env}},pe=e=>e.transport==="http"?{disabled:!1,type:"streamableHttp",url:e.url}:{disabled:!1,...m(e)},ge=({home:e,platform:r})=>{if(r==="darwin")return{global:s(e,"Library","Application Support","Claude","claude_desktop_config.json")};if(r==="win32"){const t=process.env.APPDATA;return t===void 0||t===""?{}:{global:s(t,"Claude","claude_desktop_config.json")}}return r==="linux"?{global:s(e,".config","Claude","claude_desktop_config.json")}:{}},ve=(e,r)=>Q({mcp_servers:{[e]:r.transport==="http"?{url:r.url}:{args:[...r.args],command:r.command,...r.env===void 0?{}:{env:r.env}}}}),v=[{buildEntry:b,paths:({projectRoot:e})=>({project:s(e,".mcp.json")}),format:"json",id:"claude-code",key:"mcpServers",label:"Claude Code"},{buildEntry:b,paths:({home:e,projectRoot:r})=>({global:s(e,".cursor","mcp.json"),project:s(r,".cursor","mcp.json")}),format:"json",id:"cursor",key:"mcpServers",label:"Cursor"},{buildEntry:b,paths:({projectRoot:e})=>({project:s(e,".vscode","mcp.json")}),format:"json",id:"vscode",key:"servers",label:"VS Code (GitHub Copilot)"},{buildEntry:se,paths:({home:e,projectRoot:r})=>({global:s(e,".gemini","settings.json"),project:s(r,".gemini","settings.json")}),format:"json",id:"gemini",key:"mcpServers",label:"Gemini CLI"},{buildEntry:ue,paths:ge,format:"json",id:"claude-desktop",key:"mcpServers",label:"Claude Desktop"},{buildEntry:ie,paths:({home:e})=>({global:s(e,".codeium","windsurf","mcp_config.json")}),format:"json",id:"windsurf",key:"mcpServers",label:"Windsurf"},{buildEntry:me,paths:({home:e,projectRoot:r})=>({global:s(e,".config","opencode","opencode.json"),project:s(r,"opencode.json")}),format:"json",id:"opencode",key:"mcp",label:"OpenCode"},{buildEntry:pe,paths:({home:e})=>({global:s(e,".cline","mcp.json")}),format:"json",id:"cline",key:"mcpServers",label:"Cline"},{buildEntry:fe,paths:({home:e})=>({global:s(e,".config","zed","settings.json")}),format:"json",id:"zed",key:"context_servers",label:"Zed"},{paths:({home:e,projectRoot:r})=>({global:s(e,".codex","config.toml"),project:s(r,".codex","config.toml")}),format:"manual",id:"codex",label:"Codex CLI",renderSnippet:ve}],x=v.map(e=>e.id),he=e=>v.find(r=>r.id===e.toLowerCase()),M=(e,r)=>{let t=e,n;try{t=W(e),n=V(t).mode}catch{}const a=`${t}.lunora-${Math.random().toString(36).slice(2,10)}.tmp`;try{z(a,r,"utf8"),n!==void 0&&H(a,n),K(a,t)}catch(o){try{q(a)}catch{}throw o}},ye={formattingOptions:{insertSpaces:!0,tabSize:4}},k=e=>{const r=[],t=Y(e,r,{allowTrailingComma:!0});return{errors:r,value:t}},g=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),E=(e,r,t)=>{if(!g(e))return;const n=e[r];return g(n)?n[t]:void 0},L=e=>{if(!f(e.path))return"absent";let r;try{r=h(e.path,"utf8")}catch{return"invalid"}if(r.trim().length===0)return"absent";const{errors:t,value:n}=k(r);return t.length>0||!g(n)?"invalid":E(n,e.key,e.name)===void 0?"absent":"present"},be=e=>L(e)==="present",U=(e,r,t,n,a)=>{try{const o=ee(e,[t,n],a,ye);o.length>0&&M(r,re(e,o));return}catch(o){return o instanceof Error?o.message:String(o)}},Se=e=>{const{entry:r,force:t=!1,key:n,name:a,path:o}=e,l=f(o)?h(o,"utf8"):"";if(l.trim().length===0)return J(B(o),{recursive:!0}),M(o,`${JSON.stringify({[n]:{[a]:r}},void 0,4)}
2
2
  `),{action:"created",path:o};const{errors:c,value:i}=k(l);if(c.length>0)return{action:"invalid",error:`parse error at offset ${String(c[0]?.offset??0)}`,path:o};if(!g(i))return{action:"invalid",error:"the file's root is not a JSON object",path:o};const p=i[n];if(p!==void 0&&!g(p))return{action:"invalid",error:`"${n}" is not an object`,path:o};if(E(i,n,a)!==void 0&&!t)return{action:"skipped",path:o};const $=U(l,o,n,a,r);return $===void 0?{action:"updated",path:o}:{action:"invalid",error:$,path:o}},we=e=>{const{key:r,name:t,path:n}=e;if(!f(n))return{action:"absent",path:n};let a;try{a=h(n,"utf8")}catch(i){return{action:"invalid",error:i instanceof Error?i.message:String(i),path:n}}const{errors:o,value:l}=k(a);if(o.length>0)return{action:"invalid",error:`parse error at offset ${String(o[0]?.offset??0)}`,path:n};if(E(l,r,t)===void 0)return{action:"absent",path:n};const c=U(a,n,r,t,void 0);return c===void 0?{action:"removed",path:n}:{action:"invalid",error:c,path:n}},ke=["global","project"],u=(e,r)=>{const t=Z(r,e);return t.length>0&&!t.startsWith("..")?t:e},Ee=(e,r)=>{const t=e.paths(r);return ke.flatMap(n=>{const a=t[n];return a===void 0?[]:[{client:e,path:a,scope:n}]})},$e=(e,r,t,n)=>{const a=e.paths(r),o=t==="global"?"project":"global",l=a[t]??(n?void 0:a[o]);if(l!==void 0)return{client:e,path:l,scope:a[t]===void 0?o:t}},je=e=>v.filter(r=>Object.values(r.paths(e)).some(t=>f(t))),A=(e,r,t,n)=>{if(e.length===0)return r();const a=[];for(const o of e){const l=he(o);if(l===void 0){t.error(`mcp ${n}: unknown client "${o}". Known clients: ${x.join(", ")}.`);return}a.push(l)}return a},Oe=e=>e.client.format==="json",Ce="https://lunora.sh/mcp",N="lunora-docs",D="lunora",_e=e=>f(s(e,"lunora"))&&X(e)!==void 0,xe=e=>{const{args:r,command:t}=ne(e,"lunora",["mcp","serve"]);return{args:r,command:t,transport:"stdio"}},Me=e=>({transport:"http",url:e}),Le=e=>({home:e.home,platform:e.platform,projectRoot:e.cwd}),T=(e,r,t)=>$e(e,Le(t),t.scope??r.preferredScope,t.scope!==void 0||!r.allowScopeFallback),Ue=(e,r,t)=>{const n=T(e,r,t);if(n===void 0){t.logger.warn(`${e.label}: has no ${t.scope??r.preferredScope}-scoped config — skipped "${r.name}".`);return}const{path:a}=n,o=e.buildEntry(r.spec);if(t.print===!0){const i=u(a,t.cwd);return t.force!==!0&&be({key:e.key,name:r.name,path:a})?(t.logger.info(`${e.label}: "${r.name}" already configured in ${i} — a real install would skip it (re-run with --force to replace).`),{action:"printed",path:a}):(t.logger.info(`${e.label} → ${i}
3
3
  ${JSON.stringify({[e.key]:{[r.name]:o}},void 0,4)}`),{action:"printed",path:a})}const l=Se({entry:o,force:t.force===!0,key:e.key,name:r.name,path:a}),c=u(a,t.cwd);return l.action==="invalid"?t.logger.error(`${e.label}: ${c} is not valid JSON (${l.error??"unknown error"}) — left untouched.`):l.action==="skipped"?t.logger.info(`${e.label}: "${r.name}" already configured in ${c} — re-run with --force to replace it.`):t.logger.success(`${e.label}: ${l.action==="created"?"created":"updated"} ${c} with "${r.name}".`),{action:l.action,path:a}},Ae=(e,r,t)=>{const n=T(e,r,t)?.path;if(n===void 0){t.logger.warn(`${e.label}: no known config location on ${t.platform} — skipped.`);return}return t.logger.info(`${e.label}: add this to ${u(n,t.cwd)}
4
4
 
@@ -1 +1 @@
1
- import{d as h}from"../packem_shared/command-CAXl2A1S.mjs";import{i as p}from"../packem_shared/docker-DpVxvYpL.mjs";import{EXIT_CODE as m}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{defaultSpawner as S}from"../packem_shared/createRecordingSpawner-sS7LEN7x.mjs";import{execArgsFor as w,detectPackageManager as v}from"@lunora/config";const u=new Set(["build","delete","images","info","list","push"]),b=new Set(["build","push"]),f=new Set(["images list","info","list"]),E=async e=>{const[r,...t]=e.argument;if(r===void 0||!u.has(r)){const n=`lunora containers requires a subcommand: ${[...u].toSorted((i,d)=>i.localeCompare(d)).join(" | ")}. Example: lunora containers build ./containers/app --tag app:v1 --push`;return e.logger.error(n),{code:m.USAGE,error:n}}const o=e.format==="json",s=r==="images"?`images ${t[0]??""}`.trim():r;if(o&&!f.has(s)){const n=`containers ${s}: --format json is only available for the read subcommands (${[...f].toSorted((i,d)=>i.localeCompare(d)).join(" | ")}) — wrangler has no JSON rendering for the rest.`;return e.logger.error(n),{code:m.USAGE,error:n}}if(b.has(r)&&!(e.dockerAvailable??p)()){const n=`containers ${r} needs a running Docker-compatible engine (it builds/pushes images locally). Start Docker or Colima and retry. Note: container images must target linux/amd64.`;return e.logger.error(n),{code:m.MISSING_DEPENDENCY,error:n}}const a=["containers",r,...t];o&&a.push("--json"),e.tag!==void 0&&a.push("--tag",e.tag),e.push===!0&&a.push("--push"),e.env!==void 0&&a.push("--env",e.env);const l=e.cwd??process.cwd(),g=w(v(l),"wrangler",a),c={args:g.args,command:g.command,cwd:l};return e.logger.info(`running ${c.command} ${c.args.join(" ")}`),{code:(await(e.spawner??S)(c)).code,delegated:o,descriptor:c}},k=h(async({argument:e,cwd:r,format:t,logger:o,options:s})=>{const a=await E({argument:e,cwd:r,env:s.env,format:t,logger:o,push:s.push===!0,tag:s.tag});return{code:a.code,delegated:a.delegated,error:a.error}});export{k as execute,E as runContainersCommand};
1
+ import{d as h}from"../packem_shared/command-CAXl2A1S.mjs";import{i as p}from"../packem_shared/docker-DpVxvYpL.mjs";import{EXIT_CODE as m}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{defaultSpawner as S}from"../packem_shared/createRecordingSpawner-CYhdPBD5.mjs";import{execArgsFor as w,detectPackageManager as v}from"@lunora/config";const u=new Set(["build","delete","images","info","list","push"]),b=new Set(["build","push"]),f=new Set(["images list","info","list"]),E=async e=>{const[r,...t]=e.argument;if(r===void 0||!u.has(r)){const n=`lunora containers requires a subcommand: ${[...u].toSorted((i,d)=>i.localeCompare(d)).join(" | ")}. Example: lunora containers build ./containers/app --tag app:v1 --push`;return e.logger.error(n),{code:m.USAGE,error:n}}const o=e.format==="json",s=r==="images"?`images ${t[0]??""}`.trim():r;if(o&&!f.has(s)){const n=`containers ${s}: --format json is only available for the read subcommands (${[...f].toSorted((i,d)=>i.localeCompare(d)).join(" | ")}) — wrangler has no JSON rendering for the rest.`;return e.logger.error(n),{code:m.USAGE,error:n}}if(b.has(r)&&!(e.dockerAvailable??p)()){const n=`containers ${r} needs a running Docker-compatible engine (it builds/pushes images locally). Start Docker or Colima and retry. Note: container images must target linux/amd64.`;return e.logger.error(n),{code:m.MISSING_DEPENDENCY,error:n}}const a=["containers",r,...t];o&&a.push("--json"),e.tag!==void 0&&a.push("--tag",e.tag),e.push===!0&&a.push("--push"),e.env!==void 0&&a.push("--env",e.env);const l=e.cwd??process.cwd(),g=w(v(l),"wrangler",a),c={args:g.args,command:g.command,cwd:l};return e.logger.info(`running ${c.command} ${c.args.join(" ")}`),{code:(await(e.spawner??S)(c)).code,delegated:o,descriptor:c}},k=h(async({argument:e,cwd:r,format:t,logger:o,options:s})=>{const a=await E({argument:e,cwd:r,env:s.env,format:t,logger:o,push:s.push===!0,tag:s.tag});return{code:a.code,delegated:a.delegated,error:a.error}});export{k as execute,E as runContainersCommand};
@@ -1 +1 @@
1
- import{d as i}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as c}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{defaultSpawner as l}from"../packem_shared/createRecordingSpawner-sS7LEN7x.mjs";import{execArgsFor as u,detectPackageManager as g}from"@lunora/config";const a=(e,r)=>(r!==void 0&&e.push("--env",r),e),f=e=>{const r=a(["deployments","list"],e.env);return e.format==="json"&&r.push("--json"),r},v=e=>{switch(e.subcommand){case"inspect":return e.versionId===void 0?{error:"deployments inspect requires a version id. Usage: lunora deployments inspect <version-id>"}:{args:a(["versions","view",e.versionId],e.env)};case"list":return{args:f(e)};case"promote":{if(e.versionId===void 0)return{error:"deployments promote requires a version id. Usage: lunora deployments promote <version-id> --yes"};if(!e.yes)return{error:"deployments promote shifts 100% of live traffic. Re-run with --yes to confirm."};const r=a(["versions","deploy",`${e.versionId}@100%`,"--yes"],e.env);return e.message!==void 0&&r.push("--message",e.message),{args:r}}case"rollback":{if(!e.yes)return{error:"deployments rollback changes the live version. Re-run with --yes to confirm."};const r=a(["rollback"],e.env);return e.versionId!==void 0&&r.push(e.versionId),r.push("--yes"),e.message!==void 0&&r.push("--message",e.message),{args:r}}default:return{error:`deployments: unknown subcommand "${e.subcommand}"`}}},y=async e=>{if(e.format==="json"&&e.subcommand!=="list"){const m=`deployments ${e.subcommand}: --format json is only available for \`deployments list\` — wrangler has no JSON rendering for the others.`;return e.logger.error(m),{code:c.USAGE,descriptor:void 0,error:m}}const{args:r,error:t}=v(e);if(t!==void 0||r===void 0)return e.logger.error(t??"deployments: nothing to run"),{code:c.USAGE,descriptor:void 0,error:t};const{logger:d}=e,n=e.cwd??process.cwd(),o=u(g(n),"wrangler",r),s={args:o.args,command:o.command,cwd:n};return d.info(`${s.command} ${s.args.join(" ")}`),{code:(await(e.spawner??l)(s)).code,delegated:e.format==="json",descriptor:s}},p=e=>e==="list"||e==="inspect"||e==="rollback"||e==="promote",A=i(({argument:e,cwd:r,format:t,logger:d,options:n})=>{const o=e[0];if(!p(o)){const s=`deployments: unknown subcommand "${o??""}" — expected list | inspect | rollback | promote`;return d.error(s),{code:c.USAGE,error:s}}return y({cwd:r,env:n.env,format:t,logger:d,message:n.message,subcommand:o,versionId:e[1],yes:n.yes===!0})});export{A as execute,y as runDeploymentsCommand};
1
+ import{d as i}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as c}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{defaultSpawner as l}from"../packem_shared/createRecordingSpawner-CYhdPBD5.mjs";import{execArgsFor as u,detectPackageManager as g}from"@lunora/config";const a=(e,r)=>(r!==void 0&&e.push("--env",r),e),f=e=>{const r=a(["deployments","list"],e.env);return e.format==="json"&&r.push("--json"),r},v=e=>{switch(e.subcommand){case"inspect":return e.versionId===void 0?{error:"deployments inspect requires a version id. Usage: lunora deployments inspect <version-id>"}:{args:a(["versions","view",e.versionId],e.env)};case"list":return{args:f(e)};case"promote":{if(e.versionId===void 0)return{error:"deployments promote requires a version id. Usage: lunora deployments promote <version-id> --yes"};if(!e.yes)return{error:"deployments promote shifts 100% of live traffic. Re-run with --yes to confirm."};const r=a(["versions","deploy",`${e.versionId}@100%`,"--yes"],e.env);return e.message!==void 0&&r.push("--message",e.message),{args:r}}case"rollback":{if(!e.yes)return{error:"deployments rollback changes the live version. Re-run with --yes to confirm."};const r=a(["rollback"],e.env);return e.versionId!==void 0&&r.push(e.versionId),r.push("--yes"),e.message!==void 0&&r.push("--message",e.message),{args:r}}default:return{error:`deployments: unknown subcommand "${e.subcommand}"`}}},y=async e=>{if(e.format==="json"&&e.subcommand!=="list"){const m=`deployments ${e.subcommand}: --format json is only available for \`deployments list\` — wrangler has no JSON rendering for the others.`;return e.logger.error(m),{code:c.USAGE,descriptor:void 0,error:m}}const{args:r,error:t}=v(e);if(t!==void 0||r===void 0)return e.logger.error(t??"deployments: nothing to run"),{code:c.USAGE,descriptor:void 0,error:t};const{logger:d}=e,n=e.cwd??process.cwd(),o=u(g(n),"wrangler",r),s={args:o.args,command:o.command,cwd:n};return d.info(`${s.command} ${s.args.join(" ")}`),{code:(await(e.spawner??l)(s)).code,delegated:e.format==="json",descriptor:s}},p=e=>e==="list"||e==="inspect"||e==="rollback"||e==="promote",A=i(({argument:e,cwd:r,format:t,logger:d,options:n})=>{const o=e[0];if(!p(o)){const s=`deployments: unknown subcommand "${o??""}" — expected list | inspect | rollback | promote`;return d.error(s),{code:c.USAGE,error:s}}return y({cwd:r,env:n.env,format:t,logger:d,message:n.message,subcommand:o,versionId:e[1],yes:n.yes===!0})});export{A as execute,y as runDeploymentsCommand};
@@ -1,3 +1,3 @@
1
- import{existsSync as E,readFileSync as P}from"node:fs";import{join as _}from"node:path";import{DEV_VARS_FILE as m,DEV_VARS_KEY_PATTERN as b,writeDevVariablesFileAtomically as w,removeDevVariableLine as K,upsertDevVariableLine as D,isPlaceholderValue as S,detectPackageManager as j,resolveDeployDriver as z,resolveProjectTarget as M,toolchainExecArgs as T,generateSecretValue as C,DEV_VARS_EXAMPLE_FILE as g,parseDevVariableEntries as G,packageNamesFromBindings as O,inferLunoraBindings as Y,requiredSecrets as F,isMintableSecretKey as U}from"@lunora/config";import{d as q}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as d}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{defaultSpawner as Z}from"../packem_shared/createRecordingSpawner-sS7LEN7x.mjs";import{l as B}from"../packem_shared/wrangler-secrets-CuUdFBaA.mjs";const I=/[\r\n]/u,X=/["\\]/u,L=e=>new Map(G(e).map(o=>[o.key,o])),h=e=>E(e)?P(e,"utf8"):"",N=e=>e.length<=4?"****":`${e.slice(0,4)}${"*".repeat(Math.min(8,e.length-4))}`,p=e=>L(h(e)),$=e=>e.env??(e.prod===!0?"production":void 0),H=e=>{const o=p(e.devVariablesPath),t={file:m,keys:[...o.keys()],subcommand:"list"};if(o.size===0)return e.logger.info(`${m}: (empty)`),{code:0,data:t,descriptors:[]};for(const r of o.values())e.logger.info(`${r.key}=${N(r.value)}`);return{code:0,data:t,descriptors:[]}},W=e=>{const{devVariablesPath:o,logger:t,options:r}=e;if(!r.key)return t.error("env get requires a key. Usage: lunora env get <KEY>"),{code:d.USAGE,descriptors:[]};const s=p(o).get(r.key);return s?(r.format!=="json"&&process.stdout.write(`${s.value}
2
- `),{code:0,data:{key:r.key,subcommand:"get",value:s.value},descriptors:[]}):(t.error(`env: ${r.key} is not set in ${m}`),{code:d.NOT_FOUND,descriptors:[]})},J=e=>{const{devVariablesPath:o,logger:t,options:r}=e;if(!r.key)return t.error("env set requires a key. Usage: lunora env set <KEY> <VALUE>"),{code:d.USAGE,descriptors:[]};if(!b.test(r.key))return t.error(`env: invalid key "${r.key}" — must match [A-Za-z_][A-Za-z0-9_]*`),{code:d.USAGE,descriptors:[]};if(r.value===void 0)return t.error("env set requires a value. Usage: lunora env set <KEY> <VALUE>"),{code:d.USAGE,descriptors:[]};if(I.test(r.value))return t.error(`env: value for "${r.key}" contains a newline, which .dev.vars cannot represent`),{code:d.USAGE,descriptors:[]};if(X.test(r.value))return t.error(`env: value for "${r.key}" contains a double-quote or backslash, which .dev.vars cannot round-trip`),{code:d.USAGE,descriptors:[]};const s=h(o);return w(o,D(s,r.key,r.value)),t.success(`env: set ${r.key} (${N(r.value)}) in ${m}`),{code:0,data:{key:r.key,subcommand:"set"},descriptors:[]}},Q=e=>{const{devVariablesPath:o,logger:t,options:r}=e;if(!r.key)return t.error("env unset requires a key. Usage: lunora env unset <KEY>"),{code:d.USAGE,descriptors:[]};if(!b.test(r.key))return t.error(`env: invalid key "${r.key}" — must match [A-Za-z_][A-Za-z0-9_]*`),{code:d.USAGE,descriptors:[]};const s=h(o);return L(s).has(r.key)?(w(o,K(s,r.key)),t.success(`env: unset ${r.key} in ${m}`),{code:0,data:{key:r.key,removed:!0,subcommand:"unset"},descriptors:[]}):(t.warn(`env: ${r.key} was not set in ${m}`),{code:0,data:{key:r.key,removed:!1,subcommand:"unset"},descriptors:[]})},x=async e=>{const{devVariablesPath:o,logger:t,options:r}=e;if(!r.yes)return t.error("env push uploads secrets to Cloudflare. Re-run with --yes to confirm."),{code:d.USAGE,descriptors:[]};const s=p(o);if(s.size===0)return t.warn(`${m}: nothing to push (empty)`),{code:0,data:{pushed:[],subcommand:"push",target:$(r)},descriptors:[]};const n=[...s.values()].filter(a=>S(a.value)).map(a=>a.key);if(n.length>0)return t.error(`env push: refusing to upload placeholder value(s) for ${n.join(", ")} — run \`lunora env doctor\` to review, and \`lunora env generate --set\` (or \`lunora env set <KEY> <VALUE>\`) to fill them, then re-run.`),{code:d.USAGE,descriptors:[]};const c=r.spawner??Z,u=r.cwd??process.cwd(),l=j(u),i=[],v=$(r),f=z(M(u)),y=f.toolchain?.secretPut;if(y===void 0)return t.error(`deploy target "${f.id}" has no secret store; cannot push secrets`),{code:d.USAGE,descriptors:[]};for(const a of s.values()){const R=y({environment:v,key:a.key,temporary:r.temporary}),A=T(l,R),V={args:A.args,command:A.command,cwd:u,input:a.value};i.push(V),t.info(`pushing ${a.key} -> wrangler secret${v===void 0?"":` (${v})`}`);const k=await c(V);if(k.code!==0)return t.error(`env push: failed at ${a.key} (exit ${String(k.code)})`),{code:k.code,descriptors:i}}return t.success(`env: pushed ${String(s.size)} secret(s)`),{code:0,data:{pushed:[...s.keys()],subcommand:"push",target:v},descriptors:i}},ee=e=>(e.options.secretLister??B)({cwd:e.cwd,env:$(e.options),temporary:e.options.temporary}),re=async e=>{const{devVariablesPath:o,logger:t}=e,r=await ee(e);if(!r.ok)return t.error(`env diff: ${r.error??"failed to list remote secrets"}`),{code:1,descriptors:[]};const s=new Set(p(o).keys()),n=new Set(r.names),c=[...s].filter(i=>!n.has(i)).toSorted((i,v)=>i.localeCompare(v)),u=r.names.filter(i=>!s.has(i)),l=[...s].filter(i=>n.has(i)).toSorted((i,v)=>i.localeCompare(v));for(const i of c)t.info(`local only (run \`lunora env push\`): ${i}`);for(const i of u)t.info(`remote only (in Cloudflare, not ${m}): ${i}`);return t.info(`in both: ${String(l.length)} secret(s)`),c.length===0&&u.length===0&&t.success("env diff: local and remote secret names match"),{code:0,data:{both:l,localOnly:c,remoteOnly:u,subcommand:"diff"},descriptors:[]}},te=e=>{const{cwd:o,devVariablesPath:t,logger:r}=e,s=_(o,g);if(!E(s))return r.info(`env doctor: no ${g} to check against — nothing to validate.`),{code:0,data:{extra:[],missing:[],ok:!0,placeholders:[],subcommand:"doctor"},descriptors:[]};const n=G(P(s,"utf8")).map(a=>a.key),c=p(t);if(!E(t))return r.error(`env doctor: ${m} is missing. Run \`lunora dev\` to scaffold it, or \`lunora env set <KEY> <VALUE>\`.`),r.info(`expected (from ${g}): ${n.join(", ")}`),{code:d.NOT_FOUND,descriptors:[]};const u=n.filter(a=>!c.has(a)),l=[...c.values()].filter(a=>S(a.value)).map(a=>a.key),i=new Set(n),v=[...c.keys()].filter(a=>!i.has(a));for(const a of u)r.error(`missing: ${a} is in ${g} but not ${m}`);for(const a of l)r.error(`unset: ${a} still has a placeholder value`);for(const a of v)r.info(`extra: ${a} is set locally but not listed in ${g}`);const f=u.length===0&&l.length===0,y={extra:v,missing:u,ok:f,placeholders:l,subcommand:"doctor"};return f?(r.success(`env doctor: ${m} looks good (${String(c.size)} var(s)).`),{code:0,data:y,descriptors:[]}):{code:1,data:y,descriptors:[]}},se=async e=>{let o=[];try{o=O(await Y({projectRoot:e.cwd}))}catch{}const t=F(o).map(s=>s.key).filter(s=>U(s)),r=[...p(e.devVariablesPath).keys()].filter(s=>U(s));return[...new Set([...t,...r])]},oe=(e,o,t)=>{const r=p(e),s=n=>{const c=r.get(n);return c!==void 0&&c.value!==""&&!S(c.value)};return{live:o.filter(n=>s(n.key)).map(n=>n.key),writable:t?o:o.filter(n=>!s(n.key))}},ne=(e,o)=>{const{devVariablesPath:t,logger:r,options:s}=e,{live:n,writable:c}=oe(t,o,s.yes===!0);if(c.length===0)return r.error(`env generate --set: ${n.join(", ")} already hold(s) a live secret and rotating it is irreversible (outstanding signed URLs and bearers stop verifying). Re-run with --yes to rotate anyway.`),{code:d.USAGE,descriptors:[]};n.length>0&&r.warn(`env generate --set: left ${n.join(", ")} untouched (already set) — re-run with --yes to rotate them too`);let u=h(t);for(const l of c)u=D(u,l.key,l.value);return w(t,u),r.success(`env: generated ${String(c.length)} secret(s) into ${m}: ${c.map(l=>l.key).join(", ")}`),{code:0,data:{subcommand:"generate",written:c.map(l=>l.key)},descriptors:[]}},ae=async e=>{const{logger:o,options:t}=e;let r;if(t.key===void 0){if(r=await se(e),r.length===0)return o.info("env generate: no locally-generatable secrets for this project. Name one explicitly: lunora env generate <KEY>"),{code:0,data:{secrets:[],subcommand:"generate"},descriptors:[]}}else{if(!b.test(t.key))return o.error(`env: invalid key "${t.key}" — must match [A-Za-z_][A-Za-z0-9_]*`),{code:d.USAGE,descriptors:[]};r=[t.key]}const s=r.map(n=>({key:n,value:C()}));if(t.set===!0)return ne(e,s);if(t.format!=="json")for(const n of s)process.stdout.write(`${n.key}=${n.value}
3
- `);return{code:0,data:{secrets:s,subcommand:"generate"},descriptors:[]}},ce=async e=>{const{options:o}=e;switch(o.subcommand){case"diff":return re(e);case"doctor":return te(e);case"generate":return ae(e);case"get":return W(e);case"list":return H(e);case"push":return x(e);case"set":return J(e);case"unset":return Q(e);default:return e.logger.error(`env: unknown subcommand "${o.subcommand}"`),{code:d.USAGE,descriptors:[]}}},ie=async e=>{const o=e.cwd??process.cwd(),t={cwd:o,devVariablesPath:_(o,m),logger:e.logger,options:e};return ce(t)},de=new Set(["diff","doctor","generate","get","list","push","set","unset"]),ue=e=>typeof e=="string"&&de.has(e),he=q(({argument:e,cwd:o,format:t,logger:r,options:s})=>{const n=e[0];if(!ue(n)){const c=`env: unknown subcommand "${n??""}" — expected list | get | set | unset | push | diff | doctor | generate`;return r.error(c),{code:d.USAGE,error:c}}return ie({cwd:o,env:s.env,format:t,key:e[1],logger:r,prod:s.prod===!0,set:s.set===!0,subcommand:n,temporary:s.temporary===!0,value:e[2],yes:s.yes===!0})});export{he as execute,ie as runEnvCommand};
1
+ import{existsSync as E,readFileSync as P}from"node:fs";import{join as D}from"node:path";import{DEV_VARS_FILE as m,DEV_VARS_KEY_PATTERN as b,writeDevVariablesFileAtomically as w,removeDevVariableLine as K,upsertDevVariableLine as _,isPlaceholderValue as S,detectPackageManager as j,resolveDeployDriver as z,resolveProjectTarget as M,toolchainExecArgs as T,generateSecretValue as C,DEV_VARS_EXAMPLE_FILE as g,parseDevVariableEntries as G,packageNamesFromBindings as O,inferLunoraBindings as Y,resolveSchemaDirectory as F,requiredSecrets as q,isMintableSecretKey as U}from"@lunora/config";import{d as Z}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as d}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{defaultSpawner as B}from"../packem_shared/createRecordingSpawner-CYhdPBD5.mjs";import{l as I}from"../packem_shared/wrangler-secrets-Bqi6kLuq.mjs";const X=/[\r\n]/u,H=/["\\]/u,L=e=>new Map(G(e).map(o=>[o.key,o])),h=e=>E(e)?P(e,"utf8"):"",N=e=>e.length<=4?"****":`${e.slice(0,4)}${"*".repeat(Math.min(8,e.length-4))}`,p=e=>L(h(e)),$=e=>e.env??(e.prod===!0?"production":void 0),W=e=>{const o=p(e.devVariablesPath),t={file:m,keys:[...o.keys()],subcommand:"list"};if(o.size===0)return e.logger.info(`${m}: (empty)`),{code:0,data:t,descriptors:[]};for(const r of o.values())e.logger.info(`${r.key}=${N(r.value)}`);return{code:0,data:t,descriptors:[]}},J=e=>{const{devVariablesPath:o,logger:t,options:r}=e;if(!r.key)return t.error("env get requires a key. Usage: lunora env get <KEY>"),{code:d.USAGE,descriptors:[]};const s=p(o).get(r.key);return s?(r.format!=="json"&&process.stdout.write(`${s.value}
2
+ `),{code:0,data:{key:r.key,subcommand:"get",value:s.value},descriptors:[]}):(t.error(`env: ${r.key} is not set in ${m}`),{code:d.NOT_FOUND,descriptors:[]})},Q=e=>{const{devVariablesPath:o,logger:t,options:r}=e;if(!r.key)return t.error("env set requires a key. Usage: lunora env set <KEY> <VALUE>"),{code:d.USAGE,descriptors:[]};if(!b.test(r.key))return t.error(`env: invalid key "${r.key}" — must match [A-Za-z_][A-Za-z0-9_]*`),{code:d.USAGE,descriptors:[]};if(r.value===void 0)return t.error("env set requires a value. Usage: lunora env set <KEY> <VALUE>"),{code:d.USAGE,descriptors:[]};if(X.test(r.value))return t.error(`env: value for "${r.key}" contains a newline, which .dev.vars cannot represent`),{code:d.USAGE,descriptors:[]};if(H.test(r.value))return t.error(`env: value for "${r.key}" contains a double-quote or backslash, which .dev.vars cannot round-trip`),{code:d.USAGE,descriptors:[]};const s=h(o);return w(o,_(s,r.key,r.value)),t.success(`env: set ${r.key} (${N(r.value)}) in ${m}`),{code:0,data:{key:r.key,subcommand:"set"},descriptors:[]}},x=e=>{const{devVariablesPath:o,logger:t,options:r}=e;if(!r.key)return t.error("env unset requires a key. Usage: lunora env unset <KEY>"),{code:d.USAGE,descriptors:[]};if(!b.test(r.key))return t.error(`env: invalid key "${r.key}" — must match [A-Za-z_][A-Za-z0-9_]*`),{code:d.USAGE,descriptors:[]};const s=h(o);return L(s).has(r.key)?(w(o,K(s,r.key)),t.success(`env: unset ${r.key} in ${m}`),{code:0,data:{key:r.key,removed:!0,subcommand:"unset"},descriptors:[]}):(t.warn(`env: ${r.key} was not set in ${m}`),{code:0,data:{key:r.key,removed:!1,subcommand:"unset"},descriptors:[]})},ee=async e=>{const{devVariablesPath:o,logger:t,options:r}=e;if(!r.yes)return t.error("env push uploads secrets to Cloudflare. Re-run with --yes to confirm."),{code:d.USAGE,descriptors:[]};const s=p(o);if(s.size===0)return t.warn(`${m}: nothing to push (empty)`),{code:0,data:{pushed:[],subcommand:"push",target:$(r)},descriptors:[]};const n=[...s.values()].filter(a=>S(a.value)).map(a=>a.key);if(n.length>0)return t.error(`env push: refusing to upload placeholder value(s) for ${n.join(", ")} — run \`lunora env doctor\` to review, and \`lunora env generate --set\` (or \`lunora env set <KEY> <VALUE>\`) to fill them, then re-run.`),{code:d.USAGE,descriptors:[]};const c=r.spawner??B,u=r.cwd??process.cwd(),l=j(u),i=[],v=$(r),f=z(M(u)),y=f.toolchain?.secretPut;if(y===void 0)return t.error(`deploy target "${f.id}" has no secret store; cannot push secrets`),{code:d.USAGE,descriptors:[]};for(const a of s.values()){const R=y({environment:v,key:a.key,temporary:r.temporary}),A=T(l,R),V={args:A.args,command:A.command,cwd:u,input:a.value};i.push(V),t.info(`pushing ${a.key} -> wrangler secret${v===void 0?"":` (${v})`}`);const k=await c(V);if(k.code!==0)return t.error(`env push: failed at ${a.key} (exit ${String(k.code)})`),{code:k.code,descriptors:i}}return t.success(`env: pushed ${String(s.size)} secret(s)`),{code:0,data:{pushed:[...s.keys()],subcommand:"push",target:v},descriptors:i}},re=e=>(e.options.secretLister??I)({cwd:e.cwd,env:$(e.options),temporary:e.options.temporary}),te=async e=>{const{devVariablesPath:o,logger:t}=e,r=await re(e);if(!r.ok)return t.error(`env diff: ${r.error??"failed to list remote secrets"}`),{code:1,descriptors:[]};const s=new Set(p(o).keys()),n=new Set(r.names),c=[...s].filter(i=>!n.has(i)).toSorted((i,v)=>i.localeCompare(v)),u=r.names.filter(i=>!s.has(i)),l=[...s].filter(i=>n.has(i)).toSorted((i,v)=>i.localeCompare(v));for(const i of c)t.info(`local only (run \`lunora env push\`): ${i}`);for(const i of u)t.info(`remote only (in Cloudflare, not ${m}): ${i}`);return t.info(`in both: ${String(l.length)} secret(s)`),c.length===0&&u.length===0&&t.success("env diff: local and remote secret names match"),{code:0,data:{both:l,localOnly:c,remoteOnly:u,subcommand:"diff"},descriptors:[]}},se=e=>{const{cwd:o,devVariablesPath:t,logger:r}=e,s=D(o,g);if(!E(s))return r.info(`env doctor: no ${g} to check against — nothing to validate.`),{code:0,data:{extra:[],missing:[],ok:!0,placeholders:[],subcommand:"doctor"},descriptors:[]};const n=G(P(s,"utf8")).map(a=>a.key),c=p(t);if(!E(t))return r.error(`env doctor: ${m} is missing. Run \`lunora dev\` to scaffold it, or \`lunora env set <KEY> <VALUE>\`.`),r.info(`expected (from ${g}): ${n.join(", ")}`),{code:d.NOT_FOUND,descriptors:[]};const u=n.filter(a=>!c.has(a)),l=[...c.values()].filter(a=>S(a.value)).map(a=>a.key),i=new Set(n),v=[...c.keys()].filter(a=>!i.has(a));for(const a of u)r.error(`missing: ${a} is in ${g} but not ${m}`);for(const a of l)r.error(`unset: ${a} still has a placeholder value`);for(const a of v)r.info(`extra: ${a} is set locally but not listed in ${g}`);const f=u.length===0&&l.length===0,y={extra:v,missing:u,ok:f,placeholders:l,subcommand:"doctor"};return f?(r.success(`env doctor: ${m} looks good (${String(c.size)} var(s)).`),{code:0,data:y,descriptors:[]}):{code:1,data:y,descriptors:[]}},oe=async e=>{let o=[];try{o=O(await Y({projectRoot:e.cwd,schemaDir:F(e.cwd)}))}catch{}const t=q(o).map(s=>s.key).filter(s=>U(s)),r=[...p(e.devVariablesPath).keys()].filter(s=>U(s));return[...new Set([...t,...r])]},ne=(e,o,t)=>{const r=p(e),s=n=>{const c=r.get(n);return c!==void 0&&c.value!==""&&!S(c.value)};return{live:o.filter(n=>s(n.key)).map(n=>n.key),writable:t?o:o.filter(n=>!s(n.key))}},ae=(e,o)=>{const{devVariablesPath:t,logger:r,options:s}=e,{live:n,writable:c}=ne(t,o,s.yes===!0);if(c.length===0)return r.error(`env generate --set: ${n.join(", ")} already hold(s) a live secret and rotating it is irreversible (outstanding signed URLs and bearers stop verifying). Re-run with --yes to rotate anyway.`),{code:d.USAGE,descriptors:[]};n.length>0&&r.warn(`env generate --set: left ${n.join(", ")} untouched (already set) — re-run with --yes to rotate them too`);let u=h(t);for(const l of c)u=_(u,l.key,l.value);return w(t,u),r.success(`env: generated ${String(c.length)} secret(s) into ${m}: ${c.map(l=>l.key).join(", ")}`),{code:0,data:{subcommand:"generate",written:c.map(l=>l.key)},descriptors:[]}},ce=async e=>{const{logger:o,options:t}=e;let r;if(t.key===void 0){if(r=await oe(e),r.length===0)return o.info("env generate: no locally-generatable secrets for this project. Name one explicitly: lunora env generate <KEY>"),{code:0,data:{secrets:[],subcommand:"generate"},descriptors:[]}}else{if(!b.test(t.key))return o.error(`env: invalid key "${t.key}" — must match [A-Za-z_][A-Za-z0-9_]*`),{code:d.USAGE,descriptors:[]};r=[t.key]}const s=r.map(n=>({key:n,value:C()}));if(t.set===!0)return ae(e,s);if(t.format!=="json")for(const n of s)process.stdout.write(`${n.key}=${n.value}
3
+ `);return{code:0,data:{secrets:s,subcommand:"generate"},descriptors:[]}},ie=async e=>{const{options:o}=e;switch(o.subcommand){case"diff":return te(e);case"doctor":return se(e);case"generate":return ce(e);case"get":return J(e);case"list":return W(e);case"push":return ee(e);case"set":return Q(e);case"unset":return x(e);default:return e.logger.error(`env: unknown subcommand "${o.subcommand}"`),{code:d.USAGE,descriptors:[]}}},de=async e=>{const o=e.cwd??process.cwd(),t={cwd:o,devVariablesPath:D(o,m),logger:e.logger,options:e};return ie(t)},ue=new Set(["diff","doctor","generate","get","list","push","set","unset"]),le=e=>typeof e=="string"&&ue.has(e),ke=Z(({argument:e,cwd:o,format:t,logger:r,options:s})=>{const n=e[0];if(!le(n)){const c=`env: unknown subcommand "${n??""}" — expected list | get | set | unset | push | diff | doctor | generate`;return r.error(c),{code:d.USAGE,error:c}}return de({cwd:o,env:s.env,format:t,key:e[1],logger:r,prod:s.prod===!0,set:s.set===!0,subcommand:n,temporary:s.temporary===!0,value:e[2],yes:s.yes===!0})});export{ke as execute,de as runEnvCommand};
@@ -1,4 +1,4 @@
1
- import{runCodegen as v}from"@lunora/codegen";import{applyLintIgnores as h,detectLintTools as w,inferLunoraBindings as $}from"@lunora/config";import{collectWranglerSecretVariables as y,collectExportGaps as A}from"@lunora/config/cloudflare";import{r as T,a as S,e as x}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as k,r as D}from"../packem_shared/deploy-target-DCWwiuAe.mjs";import{d as b}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as C}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{r as E}from"../packem_shared/lint-ignore-report-DKZagpqk.mjs";const u=3,R=r=>{const s=r.cwd??process.cwd(),{logger:t}=r,e=T(r),o=D(s,r.target);if(o.target===void 0)return r.logger.error(o.error??"unknown deploy target"),{advisories:[],code:C.USAGE,cronTriggers:[],error:o.error??"unknown deploy target",failedAdvisories:0,outputDirectory:""};const{target:a}=o,i=v({apiSpec:r.apiSpec,projectRoot:s,target:a,wranglerVariables:y(s)}),d={advisories:i.advisories.map(n=>({detail:n.detail,level:n.level,name:n.name,remediation:n.remediation})),cronTriggers:i.cronTriggers,failedAdvisories:0,outputDirectory:i.outputDirectory};if(t.success(`codegen wrote ${i.writtenFiles.join(", ")} to ${i.outputDirectory}`),i.advisories.length>0){const n=i.advisories.length,f=i.advisories.map(c=>` [${c.level}] ${c.name} — ${c.detail}
1
+ import{runCodegen as f}from"@lunora/codegen";import{applyLintIgnores as h,detectLintTools as w,inferLunoraBindings as y,resolveSchemaDirectory as $}from"@lunora/config";import{collectWranglerSecretVariables as A,collectExportGaps as S}from"@lunora/config/cloudflare";import{r as T,a as D,e as x}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as k,r as b}from"../packem_shared/deploy-target-DCWwiuAe.mjs";import{d as C}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as E}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{r as I}from"../packem_shared/lint-ignore-report-DKZagpqk.mjs";const u=3,L=r=>{const s=r.cwd??process.cwd(),{logger:t}=r,e=T(r),o=b(s,r.target);if(o.target===void 0)return r.logger.error(o.error??"unknown deploy target"),{advisories:[],code:E.USAGE,cronTriggers:[],error:o.error??"unknown deploy target",failedAdvisories:0,outputDirectory:""};const{target:a}=o,i=f({apiSpec:r.apiSpec,projectRoot:s,target:a,wranglerVariables:A(s)}),d={advisories:i.advisories.map(n=>({detail:n.detail,level:n.level,name:n.name,remediation:n.remediation})),cronTriggers:i.cronTriggers,failedAdvisories:0,outputDirectory:i.outputDirectory};if(t.success(`codegen wrote ${i.writtenFiles.join(", ")} to ${i.outputDirectory}`),i.advisories.length>0){const n=i.advisories.length,v=i.advisories.map(c=>` [${c.level}] ${c.name} — ${c.detail}
2
2
  ↳ ${c.remediation}`);t.warn(`${n.toString()} schema ${n===1?"advisory":"advisories"}:
3
- ${f.join(`
4
- `)}`)}const g=S(i.platformDiagnostics,t);g.errors.length>0&&(d.error=g.errors.join("; "));const{errorAdvisories:l,names:p,shouldBlock:m}=x(d.advisories,e);return m&&t.error(`${l.length.toString()} ERROR-level ${l.length===1?"advisory":"advisories"} (${p.join(", ")}). Codegen wrote its output; this exit code is the gate. Pass --no-strict-advisories to downgrade it to a warning.`),i.cronTriggers.length>u&&t.warn(`${i.cronTriggers.length.toString()} distinct cron expressions declared — Cloudflare allows at most ${u.toString()} Cron Triggers per Worker. Consolidate schedules (jobs can share one expression) or move finer-grained work to Durable Object alarms via @lunora/scheduler (runAfter/runAt).`),{...d,failedAdvisories:e?l.length:0}},I=async(r,s)=>{let t;try{t=A(await $({projectRoot:r}))}catch(e){s.warn(`could not check whether declared containers/workflows/agents are re-exported by the worker entry: ${e instanceof Error?e.message:String(e)}. Run \`lunora doctor\` to check explicitly.`);return}for(const e of t)s.warn(`${e.kind} "${e.exportName}" is declared but ${e.className} is not exported by the worker entry — add \`export * from "./lunora/_generated/${e.module}"\` so wrangler can provision its binding. Until then it deploys with nothing to run.`)},L=(r,s)=>{try{E(h(r,w(r)),s)}catch{}},V=b(async({cwd:r,format:s,logger:t,options:e})=>{const o=R({apiSpec:k(e.apiSpec),cwd:r,format:s,logger:t,strictAdvisories:e.strictAdvisories,target:e.target});if(o.outputDirectory!==""){const a=t;L(r,a),await I(r,a)}return{code:o.code??(o.error===void 0&&o.failedAdvisories===0?0:1),data:{advisories:o.advisories,cronTriggers:o.cronTriggers,failedAdvisories:o.failedAdvisories,outputDirectory:o.outputDirectory},error:o.error}});export{V as execute,R as runCodegenCommand};
3
+ ${v.join(`
4
+ `)}`)}const g=D(i.platformDiagnostics,t);g.errors.length>0&&(d.error=g.errors.join("; "));const{errorAdvisories:l,names:p,shouldBlock:m}=x(d.advisories,e);return m&&t.error(`${l.length.toString()} ERROR-level ${l.length===1?"advisory":"advisories"} (${p.join(", ")}). Codegen wrote its output; this exit code is the gate. Pass --no-strict-advisories to downgrade it to a warning.`),i.cronTriggers.length>u&&t.warn(`${i.cronTriggers.length.toString()} distinct cron expressions declared — Cloudflare allows at most ${u.toString()} Cron Triggers per Worker. Consolidate schedules (jobs can share one expression) or move finer-grained work to Durable Object alarms via @lunora/scheduler (runAfter/runAt).`),{...d,failedAdvisories:e?l.length:0}},R=async(r,s)=>{let t;try{t=S(await y({projectRoot:r,schemaDir:$(r)}))}catch(e){s.warn(`could not check whether declared containers/workflows/agents are re-exported by the worker entry: ${e instanceof Error?e.message:String(e)}. Run \`lunora doctor\` to check explicitly.`);return}for(const e of t)s.warn(`${e.kind} "${e.exportName}" is declared but ${e.className} is not exported by the worker entry — add \`export * from "./lunora/_generated/${e.module}"\` so wrangler can provision its binding. Until then it deploys with nothing to run.`)},G=(r,s)=>{try{I(h(r,w(r)),s)}catch{}},W=C(async({cwd:r,format:s,logger:t,options:e})=>{const o=L({apiSpec:k(e.apiSpec),cwd:r,format:s,logger:t,strictAdvisories:e.strictAdvisories,target:e.target});if(o.outputDirectory!==""){const a=t;G(r,a),await R(r,a)}return{code:o.code??(o.error===void 0&&o.failedAdvisories===0?0:1),data:{advisories:o.advisories,cronTriggers:o.cronTriggers,failedAdvisories:o.failedAdvisories,outputDirectory:o.outputDirectory},error:o.error}});export{W as execute,L as runCodegenCommand};
@@ -1,7 +1,7 @@
1
- import{join as Y,dirname as z}from"node:path";import{discoverMigrations as J,readServiceBindings as X,runCodegen as Q}from"@lunora/codegen";import{readLinkedProject as N,execArgsFor as I,detectPackageManager as b,discoverContainerInfo as L,COMPOSED_WORKER_ENTRY as C,writeLinkedProject as Z,discoverSchemaInfo as ee,DEV_VARS_FILE as w,parseDevVariableEntries as U,isMintableSecretKey as P,packageNamesFromBindings as re,inferLunoraBindings as F,requiredSecrets as te,generateSecretValue as ne,toolchainExecArgs as E,upsertDevVariableLine as ae,writeDevVariablesFileAtomically as oe,resolveDeployDriver as R,planToolchainInvocation as O,runPostCodegenHook as ie}from"@lunora/config";import{findWranglerFile as W,readWranglerJsonc as se,mergeWranglerEnvironment as ce,validateWranglerProject as le,reconcileWranglerBindings as de,reconcileWranglerCompatibilityDate as ue,reconcileWranglerCrons as ge,describePreservedCrons as me}from"@lunora/config/cloudflare";import{Spinner as fe}from"@visulima/spinner";import{r as he,a as ve,e as pe}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as ye,a as we}from"../packem_shared/deploy-target-DCWwiuAe.mjs";import{w as ke}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{d as be}from"../packem_shared/command-CAXl2A1S.mjs";import{r as A}from"../packem_shared/wrangler-name-Dsk5K1f-.mjs";import{EXIT_CODE as h}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{containerBuildTag as $e}from"@lunora/container";import{a as Se,i as De}from"../packem_shared/docker-DpVxvYpL.mjs";import{defaultSpawner as $}from"../packem_shared/createRecordingSpawner-sS7LEN7x.mjs";import{r as M}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{p as Ee,H as Re,a as Ae,r as je}from"../packem_shared/health-probe-Bw9JFfIy.mjs";import{existsSync as p,readFileSync as k,writeFileSync as B}from"node:fs";import{join as y}from"@visulima/path";import{Project as Ce}from"ts-morph";import{m as Pe,e as xe,i as Te}from"../packem_shared/secret-key-DsMeUoEg.mjs";import{runMigrateDataCommand as _e}from"../packem_shared/runMigrateGenerateCommand-Ii_WMZEA.mjs";import{c as Ne}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{l as Ie}from"../packem_shared/wrangler-secrets-CuUdFBaA.mjs";const Le=e=>{const{cwd:r,env:a,logger:t,mintedSecretsFile:n}=e;try{const o=N(r),i=o?.workerName??A(r),s=e.url??o?.workerUrl;t.success("deploy complete"),t.info(` worker: ${i??"(see wrangler output above)"}`),a!==void 0&&t.info(` env: ${a}`),s===void 0?t.info(" url: run `lunora link --url <https://your-worker>` to record it"):t.info(` url: ${s}`),n!==void 0&&t.info(` secrets: generated value(s) recorded in ${n}`),e.logsAvailable&&t.info(" logs: lunora logs")}catch{}},Ue=async e=>{if(e.targets.length===0)return{builtTags:[],code:0};if(!(e.railpackAvailable??Se)()){const t="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(t),{builtTags:[],code:1,error:t}}const r=e.spawner??$,a=[];for(const t of e.targets){const n=$e(t.exportName),o={args:["build",t.buildDir,"--name",n],command:"railpack",cwd:e.cwd},i=I(b(e.cwd),"wrangler",["containers","push",n]),s={args:i.args,command:i.command,cwd:e.cwd};e.logger.info(`railpack: building "${t.exportName}" → ${n} from ${t.buildDir}`);const c=await r(o);if(c.code!==0){const l=`railpack build failed for container "${t.exportName}" (${t.buildDir})`;return e.logger.error(l),{builtTags:a,code:c.code,error:l}}e.logger.info(`railpack: pushing ${n} to the Cloudflare Registry`);const d=await r(s);if(d.code!==0){const l=`wrangler containers push failed for "${t.exportName}" (${n})`;return e.logger.error(l),{builtTags:a,code:d.code,error:l}}a.push(n)}return{builtTags:a,code:0}},Fe=e=>{const a=[W(e),Y(e,"package.json")].filter(t=>t!==void 0&&p(t)).map(t=>[t,k(t,"utf8")]);return()=>{for(const[t,n]of a)k(t,"utf8")!==n&&B(t,n,"utf8")}},V="<replace-with-d1-create-id>",x=e=>Array.isArray(e)?e.filter(r=>r!=null):void 0,j=(e,r)=>{const a=W(e);if(!a)return;const{parsed:t}=se(a);if(t===void 0)return;const{error:n,merged:o}=ce(t,r),i=n===void 0?o:t,{containers:s,d1_databases:c,vars:d}=i;return{containers:x(s),d1_databases:x(c),vars:typeof d=="object"&&d!==null&&!Array.isArray(d)?d:void 0}},Oe=/^127(?:\.\d{1,3}){3}$/,We=e=>{try{const{hostname:r}=new URL(e);return r==="localhost"||Oe.test(r)||r==="::1"||r==="[::1]"}catch{return!1}},Me=e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"),Be=(e,r,a,t="deploy",n)=>{const o=(j(e,n)?.containers??[]).filter(s=>typeof s?.image=="string"&&Me(s.image));if(o.length===0||a())return;const i=`${t} 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},H=e=>p(y(e,C))?C:void 0,Ve=(e,r,a="deploy")=>{for(const t of L(e,"lunora").containers){const n=t.schedulingPolicy===void 0?t.image:void 0,i=[...n?.kind==="dockerfile"?[{field:"image",path:n.dockerfilePath}]:[],...Object.entries(t.schedulingPolicy==="durable_object"?t.images??{}:{}).flatMap(([s,c])=>c.kind==="dockerfile"?[{field:`images["${s}"]`,path:c.dockerfilePath}]:[])].find(s=>!p(y(e,s.path)));if(i!==void 0){const s=`${a} blocked: container "${t.exportName}" references a Dockerfile at "${i.path}" that does not exist. Create it or fix the \`${i.field}\` path in lunora/containers.ts.`;return r.error(s),s}if(n?.kind==="build"&&!p(y(e,n.buildDir))){const s=`${a} blocked: container "${t.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(s),s}}},He=(e,r)=>(j(e,r)?.d1_databases??[]).find(a=>a.database_id===V)?.binding,Ge=e=>{if(!e.migrate||e.dryRun||e.preview)return;if(e.migrateUrl===void 0){const a="--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(a),a}if(e.migrateYes!==!0){const a="--migrate runs production data migrations after deploy. Re-run with --migrate-yes to confirm.";return e.logger.error(a),a}const r=e.migrateToken??process.env.LUNORA_ADMIN_TOKEN;if(r===void 0||r===""){const a="admin token required for --migrate — pass --migrate-token or set LUNORA_ADMIN_TOKEN";return e.logger.error(a),a}},Ke=(e,r,a="deploy",t)=>{const n=He(e,t);if(n===void 0)return;const o=`${a} blocked: the "${n}" D1 binding has a placeholder database_id ("${V}"). 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},qe=(e,r,a="deploy",t)=>{const n=j(e,t)?.vars;if(!n)return;const o=Object.entries(n).filter(([,s])=>typeof s=="string"&&We(s)).map(([s])=>s).toSorted((s,c)=>s.localeCompare(c));if(o.length===0)return;const i=`${a} 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, reverse cross-shard relations, and auth callbacks. Set each to the deployed worker's public URL (or move it to a secret with \`wrangler secret put\`) before deploying.`;return r.error(i),i},Ye=(e,r,a)=>{const t=Ke(e,r.logger,a,r.env);if(t!==void 0)return{code:h.USAGE,error:t};const n=qe(e,r.logger,a,r.env);if(n!==void 0)return{code:h.USAGE,error:n};const o=Ve(e,r.logger,a);if(o!==void 0)return{code:h.USAGE,error:o};const i=Be(e,r.logger,r.dockerAvailable??De,a,r.env);return i===void 0?void 0:{code:h.MISSING_DEPENDENCY,error:i}},ze=/https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u,Je=/https:\/\/[^\s"'<>]+/u,Xe=e=>{if(e===void 0)return;const r=ze.exec(e);return r?r[0]:Je.exec(e)?.[0]},T=e=>e===void 0?"":` (--env ${e})`,Qe=({cwd:e,env:r,logger:a,now:t,url:n})=>{if(n!==void 0)try{const o=N(e);if(o!==void 0){if(o.workerUrl===n&&o.env===r)return;a.warn(`link: .lunora/project.json records ${o.workerUrl??"(no url)"}${T(o.env)}, but this deploy published ${n}${T(r)}. Keeping the recorded value — run \`lunora link --url ${n}${r===void 0?"":` --env ${r}`}\` to update it.`);return}const i=(t??(()=>new Date().toISOString()))();Z(e,{env:r,linkedAt:i,workerName:A(e),workerUrl:n}),a.success(`link: recorded ${n} in .lunora/project.json (run \`lunora link\` to change)`)}catch{}},Ze=async(e,r)=>{const a=new Ce({skipAddingFilesFromTsConfig:!0}),t=y(r,"lunora");let n;try{n=J(a,t)}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 _e(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},er=async(e,r)=>{const{info:a}=ee(r,"lunora"),t=a?.vectorMetadata??[];if(t.length===0)return;const n=[];for(const s of t){const c=Pe(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}n.push({index:s.index,property:s.property,type:c})}if(n.length===0)return;const i=(await xe({cwd:r,entries:n,exec:I(b(r),"wrangler",[]),logger:e.logger,spawner:e.spawner??$})).filter(s=>s.status!=="failed").length;i>0&&e.logger.success(`vectorize metadata indexes ready: ${String(i)}/${String(n.length)}`)},_=5,rr=2e3,tr=async(e,r,a)=>{if(e.healthCheck!==!0)return;const t=a??M({cwd:r,env:e.env});if(t===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 Ee({attempts:_,baseUrl:t,delayMs:rr,fetchImpl:e.healthFetch,paths:[Re,Ae],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(_)} attempt(s) — ${n.error}`),{error:n.error,ok:!1,url:n.url})},nr=async(e,r,a,t,n,o)=>{await er(e,r);const i=e.migrate?await Ze(e,r):0;return i===0&&n?.(),{code:i,descriptor:a,mintedSecretsFile:o,validation:t}},ar=async({cwd:e,descriptor:r,mintedSecretsFile:a,options:t,reblessSchemaBaseline:n,stdout:o,validation:i})=>{const s={deployedAt:new Date().toISOString(),dryRun:t.dryRun===!0,env:t.env,preview:t.preview===!0,url:t.dryRun===!0?void 0:Xe(o),workerName:A(e)};if(t.dryRun===!0||t.preview===!0)return t.healthCheck===!0&&t.logger.warn(`--health-check skipped: ${t.dryRun===!0?"a dry run publishes nothing":"a preview version serves no live traffic"}`),{code:0,deployment:s,descriptor:r,mintedSecretsFile:a,validation:i};t.temporary!==!0&&Qe({cwd:e,env:t.env,logger:t.logger,url:s.url});const c=await tr(t,e,s.url);return c?.error!==void 0?{code:h.UNAVAILABLE,deployment:s,descriptor:r,healthCheck:c,mintedSecretsFile:a,validation:i}:{...await nr(t,e,r,i,n,a),deployment:s,healthCheck:c}},or=(e,r,a)=>{const t=y(e,w);if(!p(t))return;let n;try{n=U(k(t,"utf8")).length}catch{return}if(n===0)return;const o=a.toolchain?.secretPut!==void 0;r.warn(o?`Note: \`lunora deploy\` does not push secrets. ${w} has ${String(n)} key(s); if you changed them, run \`lunora env push --yes\` to update the deployed secrets.`:`Note: ${a.name} deploys read no secrets. ${w} has ${String(n)} key(s) that only the dev server sees; put the values the deployed worker needs in wrangler \`vars\`.`)},ir=async e=>{let r=[];try{r=re(await F({projectRoot:e}))}catch{}const a=te(r).map(n=>n.key);let t=[];try{const n=y(e,w);p(n)&&(t=U(k(n,"utf8")).map(o=>o.key).filter(o=>Te(o)))}catch{}return[...new Set([...a,...t])]},sr=async(e,r,a,t)=>{const{logger:n}=r,o=r.spawner??$,i=b(e),s=r.env===void 0?"":` --env ${r.env}`,c=t.toolchain?.secretPut;if(c===void 0)return n.error(`deploy target "${t.id}" has no secret store; cannot push secrets`),{minted:[],ok:!1};const d=[];for(const l of a){const m=ne(),u=c({environment:r.env,key:l,temporary:r.temporary}),g=E(i,u),f=await o({args:g.args,command:g.command,cwd:e,input:m});if(f.code!==0)return n.error(`failed to push secret ${l} (exit ${String(f.code)}); set it manually with \`wrangler secret put ${l}${s}\`.`),{minted:d,ok:!1};d.push({key:l,value:m}),n.success(`generated + pushed ${l}`)}return{minted:d,ok:!0}},cr=/^[\w-]+$/u,S=[".dev.vars",".dev.vars.*","!.dev.vars.example"],lr=/\r?\n/u,dr=(e,r)=>{const a=y(e,".gitignore");try{const t=p(a)?k(a,"utf8"):"",n=new Set(t.split(lr).map(c=>c.trim())),o=S.filter(c=>!n.has(c));if(o.length===0)return;const i=o.some(c=>!c.startsWith("!"))?[...o.filter(c=>!c.startsWith("!")),...S.filter(c=>c.startsWith("!"))]:o,s=t.length>0&&!t.endsWith(`
1
+ import{join as z,dirname as J}from"node:path";import{discoverMigrations as X,readServiceBindings as Q,runCodegen as Z}from"@lunora/codegen";import{readLinkedProject as N,execArgsFor as I,detectPackageManager as b,discoverContainerInfo as L,COMPOSED_WORKER_ENTRY as C,writeLinkedProject as ee,discoverSchemaInfo as re,DEV_VARS_FILE as w,parseDevVariableEntries as U,isMintableSecretKey as P,packageNamesFromBindings as te,inferLunoraBindings as F,resolveSchemaDirectory as O,requiredSecrets as ne,generateSecretValue as ae,toolchainExecArgs as E,upsertDevVariableLine as oe,writeDevVariablesFileAtomically as ie,resolveDeployDriver as R,planToolchainInvocation as W,runPostCodegenHook as se}from"@lunora/config";import{findWranglerFile as M,readWranglerJsonc as ce,mergeWranglerEnvironment as le,validateWranglerProject as de,reconcileWranglerBindings as ue,reconcileWranglerCompatibilityDate as ge,reconcileWranglerCrons as me,describePreservedCrons as fe}from"@lunora/config/cloudflare";import{Spinner as he}from"@visulima/spinner";import{r as ve,a as pe,e as ye}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as we,a as ke}from"../packem_shared/deploy-target-DCWwiuAe.mjs";import{w as be}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{d as $e}from"../packem_shared/command-CAXl2A1S.mjs";import{r as A}from"../packem_shared/wrangler-name-Dsk5K1f-.mjs";import{EXIT_CODE as h}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{containerBuildTag as Se}from"@lunora/container";import{a as De,i as Ee}from"../packem_shared/docker-DpVxvYpL.mjs";import{defaultSpawner as $}from"../packem_shared/createRecordingSpawner-CYhdPBD5.mjs";import{r as B}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{p as Re,H as Ae,a as je,r as Ce}from"../packem_shared/health-probe-Bw9JFfIy.mjs";import{existsSync as p,readFileSync as k,writeFileSync as V}from"node:fs";import{join as y}from"@visulima/path";import{Project as Pe}from"ts-morph";import{m as xe,e as Te,i as _e}from"../packem_shared/secret-key-DsMeUoEg.mjs";import{runMigrateDataCommand as Ne}from"../packem_shared/runMigrateGenerateCommand-Ii_WMZEA.mjs";import{c as Ie}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{l as Le}from"../packem_shared/wrangler-secrets-Bqi6kLuq.mjs";const Ue=e=>{const{cwd:r,env:a,logger:t,mintedSecretsFile:n}=e;try{const o=N(r),i=o?.workerName??A(r),s=e.url??o?.workerUrl;t.success("deploy complete"),t.info(` worker: ${i??"(see wrangler output above)"}`),a!==void 0&&t.info(` env: ${a}`),s===void 0?t.info(" url: run `lunora link --url <https://your-worker>` to record it"):t.info(` url: ${s}`),n!==void 0&&t.info(` secrets: generated value(s) recorded in ${n}`),e.logsAvailable&&t.info(" logs: lunora logs")}catch{}},Fe=async e=>{if(e.targets.length===0)return{builtTags:[],code:0};if(!(e.railpackAvailable??De)()){const t="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(t),{builtTags:[],code:1,error:t}}const r=e.spawner??$,a=[];for(const t of e.targets){const n=Se(t.exportName),o={args:["build",t.buildDir,"--name",n],command:"railpack",cwd:e.cwd},i=I(b(e.cwd),"wrangler",["containers","push",n]),s={args:i.args,command:i.command,cwd:e.cwd};e.logger.info(`railpack: building "${t.exportName}" → ${n} from ${t.buildDir}`);const c=await r(o);if(c.code!==0){const l=`railpack build failed for container "${t.exportName}" (${t.buildDir})`;return e.logger.error(l),{builtTags:a,code:c.code,error:l}}e.logger.info(`railpack: pushing ${n} to the Cloudflare Registry`);const d=await r(s);if(d.code!==0){const l=`wrangler containers push failed for "${t.exportName}" (${n})`;return e.logger.error(l),{builtTags:a,code:d.code,error:l}}a.push(n)}return{builtTags:a,code:0}},Oe=e=>{const a=[M(e),z(e,"package.json")].filter(t=>t!==void 0&&p(t)).map(t=>[t,k(t,"utf8")]);return()=>{for(const[t,n]of a)k(t,"utf8")!==n&&V(t,n,"utf8")}},H="<replace-with-d1-create-id>",x=e=>Array.isArray(e)?e.filter(r=>r!=null):void 0,j=(e,r)=>{const a=M(e);if(!a)return;const{parsed:t}=ce(a);if(t===void 0)return;const{error:n,merged:o}=le(t,r),i=n===void 0?o:t,{containers:s,d1_databases:c,vars:d}=i;return{containers:x(s),d1_databases:x(c),vars:typeof d=="object"&&d!==null&&!Array.isArray(d)?d:void 0}},We=/^127(?:\.\d{1,3}){3}$/,Me=e=>{try{const{hostname:r}=new URL(e);return r==="localhost"||We.test(r)||r==="::1"||r==="[::1]"}catch{return!1}},Be=e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"),Ve=(e,r,a,t="deploy",n)=>{const o=(j(e,n)?.containers??[]).filter(s=>typeof s?.image=="string"&&Be(s.image));if(o.length===0||a())return;const i=`${t} 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},G=e=>p(y(e,C))?C:void 0,He=(e,r,a="deploy")=>{for(const t of L(e,"lunora").containers){const n=t.schedulingPolicy===void 0?t.image:void 0,i=[...n?.kind==="dockerfile"?[{field:"image",path:n.dockerfilePath}]:[],...Object.entries(t.schedulingPolicy==="durable_object"?t.images??{}:{}).flatMap(([s,c])=>c.kind==="dockerfile"?[{field:`images["${s}"]`,path:c.dockerfilePath}]:[])].find(s=>!p(y(e,s.path)));if(i!==void 0){const s=`${a} blocked: container "${t.exportName}" references a Dockerfile at "${i.path}" that does not exist. Create it or fix the \`${i.field}\` path in lunora/containers.ts.`;return r.error(s),s}if(n?.kind==="build"&&!p(y(e,n.buildDir))){const s=`${a} blocked: container "${t.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(s),s}}},Ge=(e,r)=>(j(e,r)?.d1_databases??[]).find(a=>a.database_id===H)?.binding,Ke=e=>{if(!e.migrate||e.dryRun||e.preview)return;if(e.migrateUrl===void 0){const a="--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(a),a}if(e.migrateYes!==!0){const a="--migrate runs production data migrations after deploy. Re-run with --migrate-yes to confirm.";return e.logger.error(a),a}const r=e.migrateToken??process.env.LUNORA_ADMIN_TOKEN;if(r===void 0||r===""){const a="admin token required for --migrate — pass --migrate-token or set LUNORA_ADMIN_TOKEN";return e.logger.error(a),a}},qe=(e,r,a="deploy",t)=>{const n=Ge(e,t);if(n===void 0)return;const o=`${a} blocked: the "${n}" 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},Ye=(e,r,a="deploy",t)=>{const n=j(e,t)?.vars;if(!n)return;const o=Object.entries(n).filter(([,s])=>typeof s=="string"&&Me(s)).map(([s])=>s).toSorted((s,c)=>s.localeCompare(c));if(o.length===0)return;const i=`${a} 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, reverse cross-shard relations, and auth callbacks. Set each to the deployed worker's public URL (or move it to a secret with \`wrangler secret put\`) before deploying.`;return r.error(i),i},ze=(e,r,a)=>{const t=qe(e,r.logger,a,r.env);if(t!==void 0)return{code:h.USAGE,error:t};const n=Ye(e,r.logger,a,r.env);if(n!==void 0)return{code:h.USAGE,error:n};const o=He(e,r.logger,a);if(o!==void 0)return{code:h.USAGE,error:o};const i=Ve(e,r.logger,r.dockerAvailable??Ee,a,r.env);return i===void 0?void 0:{code:h.MISSING_DEPENDENCY,error:i}},Je=/https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u,Xe=/https:\/\/[^\s"'<>]+/u,Qe=e=>{if(e===void 0)return;const r=Je.exec(e);return r?r[0]:Xe.exec(e)?.[0]},T=e=>e===void 0?"":` (--env ${e})`,Ze=({cwd:e,env:r,logger:a,now:t,url:n})=>{if(n!==void 0)try{const o=N(e);if(o!==void 0){if(o.workerUrl===n&&o.env===r)return;a.warn(`link: .lunora/project.json records ${o.workerUrl??"(no url)"}${T(o.env)}, but this deploy published ${n}${T(r)}. Keeping the recorded value — run \`lunora link --url ${n}${r===void 0?"":` --env ${r}`}\` to update it.`);return}const i=(t??(()=>new Date().toISOString()))();ee(e,{env:r,linkedAt:i,workerName:A(e),workerUrl:n}),a.success(`link: recorded ${n} in .lunora/project.json (run \`lunora link\` to change)`)}catch{}},er=async(e,r)=>{const a=new Pe({skipAddingFilesFromTsConfig:!0}),t=y(r,"lunora");let n;try{n=X(a,t)}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 Ne(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},rr=async(e,r)=>{const{info:a}=re(r,"lunora"),t=a?.vectorMetadata??[];if(t.length===0)return;const n=[];for(const s of t){const c=xe(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}n.push({index:s.index,property:s.property,type:c})}if(n.length===0)return;const i=(await Te({cwd:r,entries:n,exec:I(b(r),"wrangler",[]),logger:e.logger,spawner:e.spawner??$})).filter(s=>s.status!=="failed").length;i>0&&e.logger.success(`vectorize metadata indexes ready: ${String(i)}/${String(n.length)}`)},_=5,tr=2e3,nr=async(e,r,a)=>{if(e.healthCheck!==!0)return;const t=a??B({cwd:r,env:e.env});if(t===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 Re({attempts:_,baseUrl:t,delayMs:tr,fetchImpl:e.healthFetch,paths:[Ae,je],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(_)} attempt(s) — ${n.error}`),{error:n.error,ok:!1,url:n.url})},ar=async(e,r,a,t,n,o)=>{await rr(e,r);const i=e.migrate?await er(e,r):0;return i===0&&n?.(),{code:i,descriptor:a,mintedSecretsFile:o,validation:t}},or=async({cwd:e,descriptor:r,mintedSecretsFile:a,options:t,reblessSchemaBaseline:n,stdout:o,validation:i})=>{const s={deployedAt:new Date().toISOString(),dryRun:t.dryRun===!0,env:t.env,preview:t.preview===!0,url:t.dryRun===!0?void 0:Qe(o),workerName:A(e)};if(t.dryRun===!0||t.preview===!0)return t.healthCheck===!0&&t.logger.warn(`--health-check skipped: ${t.dryRun===!0?"a dry run publishes nothing":"a preview version serves no live traffic"}`),{code:0,deployment:s,descriptor:r,mintedSecretsFile:a,validation:i};t.temporary!==!0&&Ze({cwd:e,env:t.env,logger:t.logger,url:s.url});const c=await nr(t,e,s.url);return c?.error!==void 0?{code:h.UNAVAILABLE,deployment:s,descriptor:r,healthCheck:c,mintedSecretsFile:a,validation:i}:{...await ar(t,e,r,i,n,a),deployment:s,healthCheck:c}},ir=(e,r,a)=>{const t=y(e,w);if(!p(t))return;let n;try{n=U(k(t,"utf8")).length}catch{return}if(n===0)return;const o=a.toolchain?.secretPut!==void 0;r.warn(o?`Note: \`lunora deploy\` does not push secrets. ${w} has ${String(n)} key(s); if you changed them, run \`lunora env push --yes\` to update the deployed secrets.`:`Note: ${a.name} deploys read no secrets. ${w} has ${String(n)} key(s) that only the dev server sees; put the values the deployed worker needs in wrangler \`vars\`.`)},sr=async e=>{let r=[];try{r=te(await F({projectRoot:e,schemaDir:O(e)}))}catch{}const a=ne(r).map(n=>n.key);let t=[];try{const n=y(e,w);p(n)&&(t=U(k(n,"utf8")).map(o=>o.key).filter(o=>_e(o)))}catch{}return[...new Set([...a,...t])]},cr=async(e,r,a,t)=>{const{logger:n}=r,o=r.spawner??$,i=b(e),s=r.env===void 0?"":` --env ${r.env}`,c=t.toolchain?.secretPut;if(c===void 0)return n.error(`deploy target "${t.id}" has no secret store; cannot push secrets`),{minted:[],ok:!1};const d=[];for(const l of a){const m=ae(),u=c({environment:r.env,key:l,temporary:r.temporary}),g=E(i,u),f=await o({args:g.args,command:g.command,cwd:e,input:m});if(f.code!==0)return n.error(`failed to push secret ${l} (exit ${String(f.code)}); set it manually with \`wrangler secret put ${l}${s}\`.`),{minted:d,ok:!1};d.push({key:l,value:m}),n.success(`generated + pushed ${l}`)}return{minted:d,ok:!0}},lr=/^[\w-]+$/u,S=[".dev.vars",".dev.vars.*","!.dev.vars.example"],dr=/\r?\n/u,ur=(e,r)=>{const a=y(e,".gitignore");try{const t=p(a)?k(a,"utf8"):"",n=new Set(t.split(dr).map(c=>c.trim())),o=S.filter(c=>!n.has(c));if(o.length===0)return;const i=o.some(c=>!c.startsWith("!"))?[...o.filter(c=>!c.startsWith("!")),...S.filter(c=>c.startsWith("!"))]:o,s=t.length>0&&!t.endsWith(`
2
2
  `)?`
3
- `:"";B(a,`${t}${s}
3
+ `:"";V(a,`${t}${s}
4
4
  # Lunora — never commit a minted secret
5
5
  ${i.join(`
6
6
  `)}
7
- `,"utf8"),r.info(`.gitignore: added ${o.join(", ")} so the recorded secret cannot be committed`)}catch(t){r.warn(`could not update .gitignore (${t instanceof Error?t.message:String(t)}) — add \`${S.join("` and `")}\` by hand before committing.`)}},ur=(e,r,a)=>{if(a.length===0)return;const t=a.map(s=>s.key).join(", ");if(r.env!==void 0&&!cr.test(r.env)){r.logger.warn(`${t}: 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?w:`${w}.${r.env}`;dr(e,r.logger);const o=y(e,n);let i=p(o)?k(o,"utf8"):"";for(const s of a)i=ae(i,s.key,s.value);return oe(o,i),r.logger.success(r.env===void 0?`${t}: value(s) recorded in ${n}`:`${t}: value(s) recorded in ${n} (kept separate from ${w} so \`lunora dev\` and a plain \`lunora env push\` don't inherit the --env ${r.env} value)`),n},gr=async(e,r,a,t)=>{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??Ie)({cwd:e,env:r.env,temporary:r.temporary})}catch{return{}}if(!i.ok)return{};const s=new Set(i.names),d=(await ir(e)).filter(u=>!s.has(u));if(d.length===0)return{};if(!a)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(g=>!P(g)))n.warn(`required secret ${u} is not set on the target — set it with: wrangler secret put ${u}${o}`);const l=d.filter(u=>P(u));if(l.length===0)return{};if(await(r.secretConfirm??Ne())(`${String(l.length)} required secret(s) not set on the target (${l.join(", ")}). Generate strong values and push them now?`)){const{minted:u,ok:g}=await sr(e,r,l,t),f=ur(e,r,u);return g?{mintedSecretsFile:f}:{error:"failed to push required secret(s) — set them manually and re-deploy",mintedSecretsFile:f}}return n.warn(`${String(l.length)} required secret(s) not set on the target: ${l.join(", ")}. Generate + push with \`lunora env generate --set\` then \`lunora env push --yes${o}\`.`),{}},G=e=>e.format==="json"?!1:e.interactive!==void 0?e.interactive:process.stdout.isTTY&&!process.env.CI,mr=async(e,r)=>{if(r.dryRun===!0)return;const a=L(e,"lunora").containers.flatMap(n=>n.schedulingPolicy===void 0&&n.image.kind==="build"?[{buildDir:n.image.buildDir,exportName:n.exportName}]:[]);if(a.length===0)return;const t=await Ue({cwd:e,logger:r.logger,railpackAvailable:r.railpackAvailable,spawner:r.spawner,targets:a});return t.code===0?void 0:t.error??"railpack build failed"},fr=(e,r,a)=>{if(a!==void 0)try{const t=ge(e,a);t.changed&&r.success(`synced ${String(a.length)} cron trigger(s) → ${t.wranglerPath??"wrangler.jsonc"}`);for(const o of t.warnings)r.warn(o);const n=me(t.preserved);n!==void 0&&r.info(n)}catch(t){const n=t instanceof Error?t.message:String(t);r.warn(`cron trigger sync skipped: ${n}`)}},hr=async(e,r,a,t,n)=>{try{R(t);const o=await F({projectRoot:e}),i=de(e,o,n),s=i.wranglerPath??"wrangler.jsonc";if(i.added.length>0&&r.success(`provisioned bindings: ${i.added.join(", ")} → ${s}`),i.updated.length>0&&r.success(`updated bindings: ${i.updated.join(", ")} → ${s}`),i.devConfig!==void 0){const{added:c,path:d,updated:l}=i.devConfig;r.success(`dev sidecar bindings: ${[...c,...l].join(", ")} → ${d}`)}for(const c of i.warnings)r.warn(c)}catch(o){const i=o instanceof Error?o.message:String(o);r.warn(`binding inference skipped: ${i}`)}try{const o=ue(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}`)}fr(e,r,a)},vr=async(e,r,a,t,n,o,i,s)=>{let c;r?(c=new fe({name:"dots"}),c.start("running codegen")):a.info("running codegen");try{const d=Q({apiSpec:t,projectRoot:e,target:n});c?.succeed("codegen complete"),c||a.success("codegen complete");const l=ve(d.platformDiagnostics,a);if(l.errors.length>0)return{error:l.errors.join("; ")};const{errorAdvisories:m,names:u,shouldBlock:g}=pe(d.advisories,s);if(g){const v=`${m.length.toString()} ERROR-level ${m.length===1?"advisory":"advisories"} (${u.join(", ")}). Pass --no-strict-advisories to downgrade this to a warning and continue.`;return a.error(v),{error:v}}const f=await ie({cwd:e,logger:a,spawner:o,stdoutToStderr:i});return f.error!==void 0?{error:f.error}:{result:d}}catch(d){c?.failed("codegen failed");const l=d instanceof Error?d.message:String(d);return a.error(`codegen failed: ${l}`),{error:`codegen failed: ${l}`}}},pr=(e,r)=>({dryRun:r.dryRun,entry:H(e),environment:r.env,outDir:r.outDir,preview:r.preview,temporary:r.temporary}),K=(e,r,a)=>{const{toolchain:t}=a;if(t===void 0)throw new Error(`deploy target "${a.id}" has no command-line toolchain`);const n=pr(e,r);return O(a,e,"deploy",o=>t.deploy({...n,configPath:o}))},yr=(e,r,a)=>{const t=K(e,r,a),n=H(e);return 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}`),t.commit(),t.projection!==void 0&&t.projection.dropped.length>0&&r.logger.warn(`${a.name} ignores these wrangler keys, so they were left out of ${t.projection.configPath}: ${t.projection.dropped.join(", ")}`),t.command},D=(e,r)=>({code:h.USAGE,descriptor:void 0,error:e,validation:{problems:[],wranglerPath:void 0},...r}),wr=(e,r)=>{for(const a of e.report?.warnings??[])r.warn(`wrangler.jsonc: ${a}`);if(e.problems.length===0)return!1;r.error("wrangler.jsonc validation failed:");for(const a of e.problems)r.error(` - ${a}`);return!0},kr=(e,r,a)=>{const t=r.format==="json",n=r.dryRun!==!0,o=yr(e,r,a),i=E(b(e),o);return{args:i.args,captureStdout:n&&!t,captureStdoutSilently:n&&t,command:i.command,cwd:e,stdoutToStderr:t&&!n}},br=async(e,r)=>{const a=e.cwd??process.cwd(),t=G(e),n=he(e),o={problems:[],wranglerPath:void 0},i=we(a,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;try{K(a,e,R(s))}catch(u){const g=u instanceof Error?u.message:String(u);return e.logger.error(g),{error:g,target:s,validation:o}}let c;if(!e.skipCodegen){const u=await vr(a,t,e.logger,e.apiSpec,s,e.spawner,e.format==="json",n);if(u.error!==void 0)return{error:u.error,target:s,validation:o};c=u.result}let d;if(c!==void 0){const u=je({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};d=u.rebless}await hr(a,e.logger,c?.cronTriggers,s,e.env);const l=Ye(a,e,r);if(l!==void 0)return{code:l.code,error:l.error,target:s,validation:o};const m=le({environment:e.env,projectRoot:a});return wr(m,e.logger)?{error:"wrangler validation failed",target:s,validation:m}:{codegen:c,reblessSchemaBaseline:d,target:s,validation:m}},$r=e=>{if(e.skipServices===!0)return"--skip-services";if(e.preview===!0)return"--preview uploads the app version only";if(e.temporary===!0)return"--temporary deploys the app to a throwaway account"},Sr=async(e,r,a,t)=>{const{error:n,services:o}=X(e);if(n!==void 0)return n;if(o.length===0)return;const{toolchain:i}=a,s=i===void 0?`target "${a.id}" has no deploy command`:$r(r);if(s!==void 0||i===void 0){const l=o.map(m=>m.worker).join(", ");r.logger.warn(`services not deployed (${s??""}): ${l} — deploy them yourself if the app calls anything new`);return}const c=b(e),d=[...new Map(o.map(l=>[l.wranglerPath,l])).values()];for(const l of d){const m=z(l.wranglerPath);let u;try{u=O(a,m,"deploy",v=>i.deploy({configPath:v??l.wranglerPath,dryRun:r.dryRun===!0,environment:r.env}))}catch(v){return`service ${l.name} (${l.worker}): ${v instanceof Error?v.message:String(v)}`}u.commit();const g=E(c,u.command);r.logger.info(`deploying service ${l.name} (${l.worker}) via ${g.command} ${g.args.join(" ")}`);const f=await t({args:g.args,command:g.command,cwd:m,stdoutToStderr:r.format==="json"});if(f.code!==0)return`service ${l.name} (${l.worker}): ${g.command} ${g.args.join(" ")} exited ${String(f.code)} — stopping before the app`}},Dr=async e=>{const r=e.cwd??process.cwd(),a=G(e),t=await br(e,e.commandName??"deploy");if(t.error!==void 0){if(t.validation.problems.length>0)return{code:h.USAGE,descriptor:void 0,error:t.error,validation:t.validation};const q=t.schemaDrift===void 0?void 0:{schemaDrift:t.schemaDrift};return D(t.error,{...q,...t.code===void 0?{}:{code:t.code}})}const{reblessSchemaBaseline:n,validation:o}=t,i=R(t.target),s=Ge(e);if(s!==void 0)return D(s);const c=i.toolchain?.prebuildsContainerImages===!0?await mr(r,e):void 0;if(c!==void 0)return D(c);or(r,e.logger,i);const{error:d,mintedSecretsFile:l}=await gr(r,e,a,i);if(d!==void 0)return e.logger.error(d),{code:h.USAGE,descriptor:void 0,error:d,mintedSecretsFile:l,validation:o};const m=e.spawner??$,u=await Sr(r,e,i,m);if(u!==void 0)return{code:h.FAILURE,descriptor:void 0,error:u,mintedSecretsFile:l,validation:o};const g=kr(r,e,i);e.logger.info(`deploying via ${g.command} ${g.args.join(" ")}`);const f=await m(g);return g.captureStdoutSilently===!0&&f.stdout!==void 0&&f.stdout!==""&&process.stderr.write(f.stdout),f.code!==0?{code:f.code,descriptor:g,mintedSecretsFile:l,validation:o}:{...await ar({cwd:r,descriptor:g,mintedSecretsFile:l,options:e,reblessSchemaBaseline:n,stdout:f.stdout,validation:o}),logsAvailable:i.toolchain?.tail!==void 0}},Er=async e=>{const{logger:r}=e,a=e.dryRun===!0?Fe(e.cwd??process.cwd()):void 0;let t;try{if(t=await Dr({...e,logger:r}),t.code===0&&e.emitBindings!==void 0){const{error:n}=ke({destination:e.emitBindings,logger:r,projectRoot:e.cwd??process.cwd()});n!==void 0&&(r.error(n),t={...t,code:h.USAGE})}}finally{a?.()}if(e.format==="json")return t;if(t.code===0&&e.dryRun!==!0&&e.preview!==!0)Le({cwd:e.cwd??process.cwd(),env:e.env,logger:e.logger,logsAvailable:t.logsAvailable===!0,mintedSecretsFile:t.mintedSecretsFile,url:t.deployment?.url});else if(t.code===0&&e.preview===!0){const n=t.deployment?.url;e.logger.success(n===void 0?"preview version uploaded":`preview version uploaded — ${n}`)}return t},zr=be(async({cwd:e,format:r,logger:a,options:t})=>{const n=await Er({allowSchemaDrift:t.allowSchemaDrift===!0,apiSpec:ye(t.apiSpec),cwd:e,dryRun:t.dryRun===!0,env:t.env,format:r,healthCheck:t.healthCheck===!0,logger:a,migrate:t.migrate===!0,migrateToken:t.migrateToken,migrateUrl:M({cwd:e,env:t.env,url:t.migrateUrl}),migrateYes:t.migrateYes===!0,preview:t.preview===!0,skipCodegen:t.prebuilt===!0,skipServices:t.skipServices===!0,strictAdvisories:t.strictAdvisories,target:t.target,temporary:t.temporary===!0,updateSchemaBaseline:t.updateSchemaBaseline===!0});return{code:n.code,data:{deployment:n.deployment,healthCheck:n.healthCheck,mintedSecretsFile:n.mintedSecretsFile,schemaDrift:n.schemaDrift,validation:n.validation},error:n.error}});export{zr as execute,hr as provisionBindings,Er as runDeployCommand,br as runPreDeployPipeline};
7
+ `,"utf8"),r.info(`.gitignore: added ${o.join(", ")} so the recorded secret cannot be committed`)}catch(t){r.warn(`could not update .gitignore (${t instanceof Error?t.message:String(t)}) — add \`${S.join("` and `")}\` by hand before committing.`)}},gr=(e,r,a)=>{if(a.length===0)return;const t=a.map(s=>s.key).join(", ");if(r.env!==void 0&&!lr.test(r.env)){r.logger.warn(`${t}: 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?w:`${w}.${r.env}`;ur(e,r.logger);const o=y(e,n);let i=p(o)?k(o,"utf8"):"";for(const s of a)i=oe(i,s.key,s.value);return ie(o,i),r.logger.success(r.env===void 0?`${t}: value(s) recorded in ${n}`:`${t}: value(s) recorded in ${n} (kept separate from ${w} so \`lunora dev\` and a plain \`lunora env push\` don't inherit the --env ${r.env} value)`),n},mr=async(e,r,a,t)=>{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??Le)({cwd:e,env:r.env,temporary:r.temporary})}catch{return{}}if(!i.ok)return{};const s=new Set(i.names),d=(await sr(e)).filter(u=>!s.has(u));if(d.length===0)return{};if(!a)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(g=>!P(g)))n.warn(`required secret ${u} is not set on the target — set it with: wrangler secret put ${u}${o}`);const l=d.filter(u=>P(u));if(l.length===0)return{};if(await(r.secretConfirm??Ie())(`${String(l.length)} required secret(s) not set on the target (${l.join(", ")}). Generate strong values and push them now?`)){const{minted:u,ok:g}=await cr(e,r,l,t),f=gr(e,r,u);return g?{mintedSecretsFile:f}:{error:"failed to push required secret(s) — set them manually and re-deploy",mintedSecretsFile:f}}return n.warn(`${String(l.length)} required secret(s) not set on the target: ${l.join(", ")}. Generate + push with \`lunora env generate --set\` then \`lunora env push --yes${o}\`.`),{}},K=e=>e.format==="json"?!1:e.interactive!==void 0?e.interactive:process.stdout.isTTY&&!process.env.CI,fr=async(e,r)=>{if(r.dryRun===!0)return;const a=L(e,"lunora").containers.flatMap(n=>n.schedulingPolicy===void 0&&n.image.kind==="build"?[{buildDir:n.image.buildDir,exportName:n.exportName}]:[]);if(a.length===0)return;const t=await Fe({cwd:e,logger:r.logger,railpackAvailable:r.railpackAvailable,spawner:r.spawner,targets:a});return t.code===0?void 0:t.error??"railpack build failed"},hr=(e,r,a)=>{if(a!==void 0)try{const t=me(e,a);t.changed&&r.success(`synced ${String(a.length)} cron trigger(s) → ${t.wranglerPath??"wrangler.jsonc"}`);for(const o of t.warnings)r.warn(o);const n=fe(t.preserved);n!==void 0&&r.info(n)}catch(t){const n=t instanceof Error?t.message:String(t);r.warn(`cron trigger sync skipped: ${n}`)}},vr=async(e,r,a,t,n)=>{try{R(t);const o=await F({projectRoot:e,schemaDir:O(e)}),i=ue(e,o,n),s=i.wranglerPath??"wrangler.jsonc";if(i.added.length>0&&r.success(`provisioned bindings: ${i.added.join(", ")} → ${s}`),i.updated.length>0&&r.success(`updated bindings: ${i.updated.join(", ")} → ${s}`),i.devConfig!==void 0){const{added:c,path:d,updated:l}=i.devConfig;r.success(`dev sidecar bindings: ${[...c,...l].join(", ")} → ${d}`)}for(const c of i.warnings)r.warn(c)}catch(o){const i=o instanceof Error?o.message:String(o);r.warn(`binding inference skipped: ${i}`)}try{const o=ge(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}`)}hr(e,r,a)},pr=async(e,r,a,t,n,o,i,s)=>{let c;r?(c=new he({name:"dots"}),c.start("running codegen")):a.info("running codegen");try{const d=Z({apiSpec:t,projectRoot:e,target:n});c?.succeed("codegen complete"),c||a.success("codegen complete");const l=pe(d.platformDiagnostics,a);if(l.errors.length>0)return{error:l.errors.join("; ")};const{errorAdvisories:m,names:u,shouldBlock:g}=ye(d.advisories,s);if(g){const v=`${m.length.toString()} ERROR-level ${m.length===1?"advisory":"advisories"} (${u.join(", ")}). Pass --no-strict-advisories to downgrade this to a warning and continue.`;return a.error(v),{error:v}}const f=await se({cwd:e,logger:a,spawner:o,stdoutToStderr:i});return f.error!==void 0?{error:f.error}:{result:d}}catch(d){c?.failed("codegen failed");const l=d instanceof Error?d.message:String(d);return a.error(`codegen failed: ${l}`),{error:`codegen failed: ${l}`}}},yr=(e,r)=>({dryRun:r.dryRun,entry:G(e),environment:r.env,outDir:r.outDir,preview:r.preview,temporary:r.temporary}),q=(e,r,a)=>{const{toolchain:t}=a;if(t===void 0)throw new Error(`deploy target "${a.id}" has no command-line toolchain`);const n=yr(e,r);return W(a,e,"deploy",o=>t.deploy({...n,configPath:o}))},wr=(e,r,a)=>{const t=q(e,r,a),n=G(e);return 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}`),t.commit(),t.projection!==void 0&&t.projection.dropped.length>0&&r.logger.warn(`${a.name} ignores these wrangler keys, so they were left out of ${t.projection.configPath}: ${t.projection.dropped.join(", ")}`),t.command},D=(e,r)=>({code:h.USAGE,descriptor:void 0,error:e,validation:{problems:[],wranglerPath:void 0},...r}),kr=(e,r)=>{for(const a of e.report?.warnings??[])r.warn(`wrangler.jsonc: ${a}`);if(e.problems.length===0)return!1;r.error("wrangler.jsonc validation failed:");for(const a of e.problems)r.error(` - ${a}`);return!0},br=(e,r,a)=>{const t=r.format==="json",n=r.dryRun!==!0,o=wr(e,r,a),i=E(b(e),o);return{args:i.args,captureStdout:n&&!t,captureStdoutSilently:n&&t,command:i.command,cwd:e,stdoutToStderr:t&&!n}},$r=async(e,r)=>{const a=e.cwd??process.cwd(),t=K(e),n=ve(e),o={problems:[],wranglerPath:void 0},i=ke(a,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;try{q(a,e,R(s))}catch(u){const g=u instanceof Error?u.message:String(u);return e.logger.error(g),{error:g,target:s,validation:o}}let c;if(!e.skipCodegen){const u=await pr(a,t,e.logger,e.apiSpec,s,e.spawner,e.format==="json",n);if(u.error!==void 0)return{error:u.error,target:s,validation:o};c=u.result}let d;if(c!==void 0){const u=Ce({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};d=u.rebless}await vr(a,e.logger,c?.cronTriggers,s,e.env);const l=ze(a,e,r);if(l!==void 0)return{code:l.code,error:l.error,target:s,validation:o};const m=de({environment:e.env,projectRoot:a});return kr(m,e.logger)?{error:"wrangler validation failed",target:s,validation:m}:{codegen:c,reblessSchemaBaseline:d,target:s,validation:m}},Sr=e=>{if(e.skipServices===!0)return"--skip-services";if(e.preview===!0)return"--preview uploads the app version only";if(e.temporary===!0)return"--temporary deploys the app to a throwaway account"},Dr=async(e,r,a,t)=>{const{error:n,services:o}=Q(e);if(n!==void 0)return n;if(o.length===0)return;const{toolchain:i}=a,s=i===void 0?`target "${a.id}" has no deploy command`:Sr(r);if(s!==void 0||i===void 0){const l=o.map(m=>m.worker).join(", ");r.logger.warn(`services not deployed (${s??""}): ${l} — deploy them yourself if the app calls anything new`);return}const c=b(e),d=[...new Map(o.map(l=>[l.wranglerPath,l])).values()];for(const l of d){const m=J(l.wranglerPath);let u;try{u=W(a,m,"deploy",v=>i.deploy({configPath:v??l.wranglerPath,dryRun:r.dryRun===!0,environment:r.env}))}catch(v){return`service ${l.name} (${l.worker}): ${v instanceof Error?v.message:String(v)}`}u.commit();const g=E(c,u.command);r.logger.info(`deploying service ${l.name} (${l.worker}) via ${g.command} ${g.args.join(" ")}`);const f=await t({args:g.args,command:g.command,cwd:m,stdoutToStderr:r.format==="json"});if(f.code!==0)return`service ${l.name} (${l.worker}): ${g.command} ${g.args.join(" ")} exited ${String(f.code)} — stopping before the app`}},Er=async e=>{const r=e.cwd??process.cwd(),a=K(e),t=await $r(e,e.commandName??"deploy");if(t.error!==void 0){if(t.validation.problems.length>0)return{code:h.USAGE,descriptor:void 0,error:t.error,validation:t.validation};const Y=t.schemaDrift===void 0?void 0:{schemaDrift:t.schemaDrift};return D(t.error,{...Y,...t.code===void 0?{}:{code:t.code}})}const{reblessSchemaBaseline:n,validation:o}=t,i=R(t.target),s=Ke(e);if(s!==void 0)return D(s);const c=i.toolchain?.prebuildsContainerImages===!0?await fr(r,e):void 0;if(c!==void 0)return D(c);ir(r,e.logger,i);const{error:d,mintedSecretsFile:l}=await mr(r,e,a,i);if(d!==void 0)return e.logger.error(d),{code:h.USAGE,descriptor:void 0,error:d,mintedSecretsFile:l,validation:o};const m=e.spawner??$,u=await Dr(r,e,i,m);if(u!==void 0)return{code:h.FAILURE,descriptor:void 0,error:u,mintedSecretsFile:l,validation:o};const g=br(r,e,i);e.logger.info(`deploying via ${g.command} ${g.args.join(" ")}`);const f=await m(g);return g.captureStdoutSilently===!0&&f.stdout!==void 0&&f.stdout!==""&&process.stderr.write(f.stdout),f.code!==0?{code:f.code,descriptor:g,mintedSecretsFile:l,validation:o}:{...await or({cwd:r,descriptor:g,mintedSecretsFile:l,options:e,reblessSchemaBaseline:n,stdout:f.stdout,validation:o}),logsAvailable:i.toolchain?.tail!==void 0}},Rr=async e=>{const{logger:r}=e,a=e.dryRun===!0?Oe(e.cwd??process.cwd()):void 0;let t;try{if(t=await Er({...e,logger:r}),t.code===0&&e.emitBindings!==void 0){const{error:n}=be({destination:e.emitBindings,logger:r,projectRoot:e.cwd??process.cwd()});n!==void 0&&(r.error(n),t={...t,code:h.USAGE})}}finally{a?.()}if(e.format==="json")return t;if(t.code===0&&e.dryRun!==!0&&e.preview!==!0)Ue({cwd:e.cwd??process.cwd(),env:e.env,logger:e.logger,logsAvailable:t.logsAvailable===!0,mintedSecretsFile:t.mintedSecretsFile,url:t.deployment?.url});else if(t.code===0&&e.preview===!0){const n=t.deployment?.url;e.logger.success(n===void 0?"preview version uploaded":`preview version uploaded — ${n}`)}return t},Jr=$e(async({cwd:e,format:r,logger:a,options:t})=>{const n=await Rr({allowSchemaDrift:t.allowSchemaDrift===!0,apiSpec:we(t.apiSpec),cwd:e,dryRun:t.dryRun===!0,env:t.env,format:r,healthCheck:t.healthCheck===!0,logger:a,migrate:t.migrate===!0,migrateToken:t.migrateToken,migrateUrl:B({cwd:e,env:t.env,url:t.migrateUrl}),migrateYes:t.migrateYes===!0,preview:t.preview===!0,skipCodegen:t.prebuilt===!0,skipServices:t.skipServices===!0,strictAdvisories:t.strictAdvisories,target:t.target,temporary:t.temporary===!0,updateSchemaBaseline:t.updateSchemaBaseline===!0});return{code:n.code,data:{deployment:n.deployment,healthCheck:n.healthCheck,mintedSecretsFile:n.mintedSecretsFile,schemaDrift:n.schemaDrift,validation:n.validation},error:n.error}});export{Jr as execute,vr as provisionBindings,Rr as runDeployCommand,$r as runPreDeployPipeline};