@lunora/cli 1.0.0-alpha.371 → 1.0.0-alpha.372
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.mjs +1 -1
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.mjs +1 -1
- package/dist/packem_chunks/handler10.mjs +1 -2
- package/dist/packem_chunks/handler11.mjs +1 -1
- package/dist/packem_chunks/handler12.mjs +1 -1
- package/dist/packem_chunks/handler13.mjs +3 -1
- package/dist/packem_chunks/handler14.mjs +1 -1
- package/dist/packem_chunks/handler15.mjs +1 -3
- package/dist/packem_chunks/handler16.mjs +1 -1
- package/dist/packem_chunks/handler17.mjs +7 -1
- package/dist/packem_chunks/handler18.mjs +1 -1
- package/dist/packem_chunks/handler19.mjs +3 -7
- package/dist/packem_chunks/handler20.mjs +3 -1
- package/dist/packem_chunks/handler21.mjs +1 -1
- package/dist/packem_chunks/handler22.mjs +2 -3
- package/dist/packem_chunks/handler23.mjs +1 -3
- package/dist/packem_chunks/handler24.mjs +99 -1
- package/dist/packem_chunks/handler25.mjs +10 -2
- package/dist/packem_chunks/handler26.mjs +1 -1
- package/dist/packem_chunks/handler3.mjs +1 -1
- package/dist/packem_chunks/handler4.mjs +3 -1
- package/dist/packem_chunks/handler5.mjs +1 -1
- package/dist/packem_chunks/handler6.mjs +1 -3
- package/dist/packem_chunks/handler7.mjs +1 -1
- package/dist/packem_chunks/handler8.mjs +2 -1
- package/dist/packem_chunks/handler9.mjs +1 -1
- package/dist/packem_chunks/runDeployCommand.mjs +1 -1
- package/dist/packem_shared/{COMMANDS-B3ETRBZq.mjs → COMMANDS-DKQ655_4.mjs} +1 -1
- package/dist/packem_shared/cli-C74xjzMK.mjs +2 -0
- package/dist/packem_shared/cloudflare-credentials-BVmZnDZk.mjs +1 -0
- package/dist/packem_shared/{docker-DpVxvYpL.mjs → docker-AqLAkOyY.mjs} +1 -1
- package/dist/packem_shared/secret-key-6bCftsxj.mjs +1 -0
- package/dist/packem_shared/variables-CPYyJtsL.mjs +1 -0
- package/package.json +5 -5
- package/skills/lunora-deploy/SKILL.md +4 -4
- package/dist/packem_chunks/handler27.mjs +0 -99
- package/dist/packem_chunks/handler28.mjs +0 -10
- package/dist/packem_chunks/handler29.mjs +0 -1
- package/dist/packem_shared/cli-DVVI8I8G.mjs +0 -2
- package/dist/packem_shared/cloudflare-credentials-lC5JtPLe.mjs +0 -1
- package/dist/packem_shared/cloudflare-rest--YUlUUlB.mjs +0 -1
- package/dist/packem_shared/secret-key-Bc77jm1S.mjs +0 -1
- package/dist/packem_shared/variables-acxcvVQa.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-
|
|
2
|
+
import{r as e}from"./packem_shared/cli-C74xjzMK.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
|
@@ -3,7 +3,7 @@ import { ensureDevVariables, ensureDevVarsExample, fillDevSecrets, startCelldDev
|
|
|
3
3
|
import { materializeRemoteWranglerConfig, materializeServiceDevConfigs } from '@lunora/config/cloudflare';
|
|
4
4
|
export { REQUIRED_COMPATIBILITY_DATE, REQUIRED_FLAG, type WranglerProjectValidationOptions as WranglerValidationOptions, type WranglerValidationReport, type WranglerProjectValidationResult as WranglerValidationResult, validateWranglerProject as validateWrangler, validateWranglerConfig } from '@lunora/config/cloudflare';
|
|
5
5
|
/** Every command name the CLI registers (drives the `CommandName` type + tests). */
|
|
6
|
-
declare const COMMANDS: readonly ["init", "add", "dev", "codegen", "build", "deploy", "
|
|
6
|
+
declare const COMMANDS: readonly ["init", "add", "dev", "codegen", "build", "deploy", "prepare", "link", "cloudflare", "logs", "run", "insights", "reset", "migrate", "export", "import", "seed", "shards", "backup", "eval", "verify", "info", "doctor", "env", "analyze", "view", "docs", "registry", "rules", "mcp"];
|
|
7
7
|
type CommandName = (typeof COMMANDS)[number];
|
|
8
8
|
declare const VERSION: string;
|
|
9
9
|
interface RunCliOptions {
|
|
@@ -706,7 +706,7 @@ interface DeployCommandOptions {
|
|
|
706
706
|
* `pnpm-workspace.yaml`) has no structured deploy output
|
|
707
707
|
* and no flag that returns the version id — it only prints it in prose, and
|
|
708
708
|
* scraping a second value out of prose is exactly what this shouldn't do. The
|
|
709
|
-
* id is available from `lunora deployments list` after the fact.
|
|
709
|
+
* id is available from `lunora cloudflare deployments list` after the fact.
|
|
710
710
|
*/
|
|
711
711
|
interface DeployedIdentity {
|
|
712
712
|
/** ISO-8601 stamp taken when the wrangler invocation returned. */
|
package/dist/index.d.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { ensureDevVariables, ensureDevVarsExample, fillDevSecrets, startCelldDev
|
|
|
3
3
|
import { materializeRemoteWranglerConfig, materializeServiceDevConfigs } from '@lunora/config/cloudflare';
|
|
4
4
|
export { REQUIRED_COMPATIBILITY_DATE, REQUIRED_FLAG, type WranglerProjectValidationOptions as WranglerValidationOptions, type WranglerValidationReport, type WranglerProjectValidationResult as WranglerValidationResult, validateWranglerProject as validateWrangler, validateWranglerConfig } from '@lunora/config/cloudflare';
|
|
5
5
|
/** Every command name the CLI registers (drives the `CommandName` type + tests). */
|
|
6
|
-
declare const COMMANDS: readonly ["init", "add", "dev", "codegen", "build", "deploy", "
|
|
6
|
+
declare const COMMANDS: readonly ["init", "add", "dev", "codegen", "build", "deploy", "prepare", "link", "cloudflare", "logs", "run", "insights", "reset", "migrate", "export", "import", "seed", "shards", "backup", "eval", "verify", "info", "doctor", "env", "analyze", "view", "docs", "registry", "rules", "mcp"];
|
|
7
7
|
type CommandName = (typeof COMMANDS)[number];
|
|
8
8
|
declare const VERSION: string;
|
|
9
9
|
interface RunCliOptions {
|
|
@@ -706,7 +706,7 @@ interface DeployCommandOptions {
|
|
|
706
706
|
* `pnpm-workspace.yaml`) has no structured deploy output
|
|
707
707
|
* and no flag that returns the version id — it only prints it in prose, and
|
|
708
708
|
* scraping a second value out of prose is exactly what this shouldn't do. The
|
|
709
|
-
* id is available from `lunora deployments list` after the fact.
|
|
709
|
+
* id is available from `lunora cloudflare deployments list` after the fact.
|
|
710
710
|
*/
|
|
711
711
|
interface DeployedIdentity {
|
|
712
712
|
/** ISO-8601 stamp taken when the wrangler invocation returned. */
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{C as o,V as a,r as n}from"./packem_shared/cli-
|
|
1
|
+
import{C as o,V as a,r as n}from"./packem_shared/cli-C74xjzMK.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-DJeIwzFu.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-Ch7zuQQE.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-DgUDxkA8.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,2 +1 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`)},i=(r,o,t)=>(r.error(o),{code:t,error:o}),F=r=>r===void 0||!Number.isFinite(r)||r<=0?_:Math.floor(r),A=async r=>{const{logger:o}=r;if(r.prod&&r.url===void 0)return i(o,"--prod requires an explicit --url (refusing to report from the implicit localhost worker)",u.USAGE);const t=M(r.url,o,r.cwd);if(t===void 0)return{code:u.USAGE,error:"could not resolve a usable worker URL"};const{token:n}=v({cwd:r.cwd??process.cwd(),token:r.token,url:t});if(!n)return i(o,"admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)",u.AUTH);const a=`${t}/_lunora/rpc`,e=y,s={args:{},functionPath:O};r.shard!==void 0&&(s.shardKey=r.shard),o.info(`POST ${a} -> insights`);const l=await e(a,{body:JSON.stringify(s),headers:{authorization:`Bearer ${n}`,"content-type":"application/json"},method:"POST"}),c=await l.text();if(!l.ok)return i(o,`insights failed: HTTP ${String(l.status)}: ${c}`,T(l.status));let d;try{d=JSON.parse(c)}catch{return i(o,`insights failed: worker returned non-JSON: ${c}`,1)}const S=d.result??d,{functions:h}=S;if(!Array.isArray(h))return i(o,"insights failed: response carried no `functions` array",1);const g=k(h,F(r.limit));return r.format!=="json"&&o.info(E(g)),{code:0,report:g}},L=x(async({cwd:r,format:o,logger:t,options:n})=>{const a=n.limit===void 0?void 0:Number.parseInt(n.limit,10),e=await A({cwd:r,fetchImpl:void 0,format:o,limit:a,logger:t,prod:n.prod,shard:n.shard,token:n.token,url:I({cwd:r,prod:n.prod===!0,url:n.url})});return{code:e.code,data:e.report,error:e.error}});export{k as buildInsightsReport,L as execute,E as formatInsightsReport,A as runInsightsCommand};
|
|
1
|
+
import{p as i}from"../packem_shared/deploy-target-DCWwiuAe.mjs";import{d as c}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as t}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{runPreDeployPipeline as d}from"./runDeployCommand.mjs";const l=async r=>{const a=r.cwd??process.cwd(),e=await d({allowSchemaDrift:r.allowSchemaDrift,apiSpec:r.apiSpec,cwd:a,logger:r.logger,spawner:r.spawner,strictAdvisories:r.strictAdvisories,target:r.target,updateSchemaBaseline:r.updateSchemaBaseline},"prepare");return e.error!==void 0?{code:e.code??t.USAGE,error:e.error,...e.schemaDrift===void 0?{}:{schemaDrift:e.schemaDrift},validation:e.validation}:(e.reblessSchemaBaseline?.(),r.logger.success("project is ready to deploy"),{code:0,validation:e.validation})},S=c(({cwd:r,logger:a,options:e})=>l({allowSchemaDrift:e.allowSchemaDrift===!0,apiSpec:i(e.apiSpec),cwd:r,logger:a,strictAdvisories:e.strictAdvisories,target:e.target,updateSchemaBaseline:e.updateSchemaBaseline===!0}));export{S as execute,l as runPrepareCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{d as l}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as n}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{r as s,b as t,a as o}from"../packem_shared/commands-DgUDxkA8.mjs";const y=l(({argument:a,cwd:u,format:m,logger:e,options:r})=>{const f=a[0],c=a.slice(1);if(f==="add")return s({allowUnsafeSource:r.allowUnsafeSource===!0,cwd:u,diff:r.diff===!0,dryRun:r.dryRun===!0,format:m,from:r.from,logger:e,names:c,overwrite:r.overwrite===!0,ref:r.ref,source:r.source,yes:r.yes===!0});if(f==="list")return s({allowUnsafeSource:r.allowUnsafeSource===!0,cwd:u,format:m,from:r.from,list:!0,logger:e,names:[],ref:r.ref,source:r.source});if(f==="view")return t({allowUnsafeSource:r.allowUnsafeSource===!0,cwd:u,from:r.from,logger:e,names:c,ref:r.ref,source:r.source});if(f==="build")return o({check:r.check===!0,cwd:u,from:r.from,logger:e,names:[],out:r.out});const d="registry: unknown subcommand. Usage: lunora registry <add|list|view|build> [names…]";return e.error(d),{code:n.USAGE,error:d}});export{y as execute};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{existsSync as u,readdirSync as d,statSync as g,mkdirSync as h,writeFileSync as w,readFileSync as y}from"node:fs";import{fileURLToPath as v}from"node:url";import{AGENT_RULES_DIR as a,detectAgentRules as R,LUNORA_SKILL_NAMES as L}from"@lunora/config";import{join as i,relative as A,resolve as E,dirname as m}from"@visulima/path";import{f as I}from"../packem_shared/cli-manifest-CRet0egA.mjs";import{d as $}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as _}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";const b=(e=m(v(import.meta.url)))=>{const r=I(e),t=r===void 0?void 0:i(r,"skills");return t!==void 0&&u(t)?t:void 0},j=e=>d(e).filter(r=>{const t=i(e,r);return g(t).isDirectory()&&u(i(t,"SKILL.md"))}),f=(e,r,t)=>{h(r,{recursive:!0});let n=!1;for(const o of d(e)){const l=i(e,o),s=i(r,o);if(g(l).isDirectory()){n=f(l,s,t)||n;continue}u(s)&&!t||(w(s,y(l)),n=!0)}return n},D=["pnpm-workspace.yaml","pnpm-lock.yaml","yarn.lock","package-lock.json","bun.lock","bun.lockb",".git"],O=e=>{let r=e;for(;;){if(D.some(n=>u(i(r,n))))return r;const t=m(r);if(t===r)return e;r=t}},k=(e,r)=>r===void 0?O(e):E(e,r),U=e=>{const r=e.cwd??process.cwd(),t=k(r,e.dir),n=e.overwrite===!0,o=b();if(o===void 0)return e.logger.error("rules: could not locate the bundled skills (is @lunora/cli installed correctly?)."),{code:1,installed:[],skipped:[]};const l=[],s=[];for(const c of j(o)){const S=i(t,a,c);f(i(o,c),S,n)?l.push(c):s.push(c)}const p=A(r,i(t,a))||a;return l.length>0&&e.logger.success(`Installed ${String(l.length)} Lunora skill(s) into ${p}/: ${l.join(", ")}.`),s.length>0&&e.logger.info(`Skipped ${String(s.length)} existing skill(s) (re-run with --overwrite to replace): ${s.join(", ")}.`),e.logger.info("Your AI coding agent will pick these up automatically. Start with the `lunora` skill."),{code:0,installed:l,skipped:s}},x=e=>{const r=e.cwd??process.cwd(),t=k(r,e.dir),n=R(t);return n.installed?(e.logger.success(`Lunora agent rules are installed (${String(n.present.length)}/${String(L.length)} skills).`),n.missing.length>0&&e.logger.info(`Missing: ${n.missing.join(", ")}. Run \`lunora rules install\` to add them.`),{code:0,installed:n.present,skipped:[]}):(e.logger.warn("Lunora agent rules are not installed. Run `lunora rules install` so your AI agent knows how to use Lunora."),{code:e.strict===!0?1:0,installed:n.present,skipped:[]})},G=$(({argument:e,cwd:r,logger:t,options:n})=>{const o=e[0]??"check";return o==="install"?U({cwd:r,dir:n.dir,logger:t,overwrite:n.overwrite===!0}):o==="check"?x({cwd:r,dir:n.dir,logger:t,strict:n.strict===!0}):(t.error("rules: unknown subcommand. Usage: lunora rules <install|check>"),{code:_.USAGE})});export{G as execute,j as listBundledSkills,b as resolveBundledSkillsDirectory,x as runRulesCheck,U as runRulesInstall};
|
|
@@ -1 +1,3 @@
|
|
|
1
|
-
import{d as
|
|
1
|
+
import{existsSync as S}from"node:fs";import{mkdtemp as v,writeFile as k,rm as j}from"node:fs/promises";import{tmpdir as R}from"node:os";import{discoverSchema as C,schemaFromIr as T}from"@lunora/codegen";import{seedPlan as $}from"@lunora/seed";import{join as w}from"@visulima/path";import{Project as A}from"ts-morph";import{t as y}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{d as E}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as u}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{a as F}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{b as N}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{runResetCommand as U}from"./runResetCommand.mjs";import{r as I}from"../packem_shared/import-BRM1hs7j.mjs";const O=(e,r)=>typeof r=="bigint"?Number(r):r instanceof ArrayBuffer?[...new Uint8Array(r)]:r,f=(e,r)=>({code:e,error:r,ndjson:""}),x=(e,r)=>{if(!S(r)){const o=`schema not found: ${r} — run \`vis generate lunora-table --name=<name>\` to create one`;return e.logger.error(o),f(u.NOT_FOUND,o)}if(e.reset===!0&&y({prod:e.prod,url:e.url})){const o="--reset only clears local .wrangler/state and cannot be combined with --prod or a remote --url";return e.logger.error(o),f(u.USAGE,o)}},z=async(e,r,o,t,n)=>{const s=await v(w(R(),"lunora-seed-")),d=w(s,"rows.ndjson");await k(d,e,"utf8");try{const a=await I({batchSize:n.batchSize,cwd:t,fetchImpl:n.fetchImpl,file:d,logger:n.logger,prod:n.prod,token:n.token,url:n.url,yes:!0}),i=a.body?.conflicts??0;return i>0&&n.logger.warn(`${String(i)} row(s) skipped — their _id already exists. Seeding is deterministic; re-run with --reset to wipe local state first, or a different --seed for fresh ids.`),{code:a.code,data:{conflicts:i,generated:r,inserted:a.inserted,tables:o},ndjson:e,...a.error===void 0?{}:{error:a.error}}}finally{await j(s,{force:!0,recursive:!0}).catch(()=>{})}},D=(e,r)=>{if(e.table===void 0||r.tables.some(n=>n.name===e.table))return;const o=r.tables.map(n=>n.name).join(", "),t=`unknown table "${e.table}" — schema defines: ${o||"(no tables)"}`;return e.logger.error(t),f(u.USAGE,t)},_=async(e,r)=>{if(!y({prod:e.prod,url:e.url})||e.yes===!0)return;if(!process.stdin.isTTY&&e.confirm===void 0){const s="seed: refusing to insert into a non-local target without confirmation — re-run with --yes";return e.logger.error(s),f(u.USAGE,s)}if(!await(e.confirm??N)(`This will insert ${String(r)} generated row(s) into ${e.url??"the production worker"}. Continue?`))return e.logger.info("seed: aborted"),f(u.CANCELLED,"seed: aborted at the confirmation prompt")},G=e=>{const r=[];for(const{rows:o,table:t}of e)for(const n of o)r.push(JSON.stringify({doc:n,table:t},O));return{lines:r,ndjson:r.length>0?`${r.join(`
|
|
2
|
+
`)}
|
|
3
|
+
`:""}},P=async e=>{const r=e.cwd??process.cwd(),o=e.format==="json",t=w(r,"lunora","schema.ts"),n=x(e,t);if(n!==void 0)return n;const s=new A({skipAddingFilesFromTsConfig:!0}),d=C(s,t),a=D(e,d);if(a!==void 0)return a;const i=T(d),l=$(i,{defaultCount:e.count??10,now:e.now,only:e.table===void 0?void 0:[e.table],seed:e.seed??0}),{lines:h,ndjson:c}=G(l),m=h.length;if(e.dryRun===!0)return!o&&c.length>0&&process.stdout.write(c),e.logger.info(`generated ${String(m)} row(s) across ${String(l.length)} table(s) — dry run, nothing inserted`),{code:0,data:{conflicts:0,generated:m,inserted:0,rows:o?h.map(g=>JSON.parse(g)):void 0,tables:l.length},ndjson:c};if(m===0)return e.logger.warn("no rows generated — nothing to insert"),{code:0,data:{conflicts:0,generated:0,inserted:0,tables:l.length},ndjson:c};if(e.reset===!0){const g=await U({confirm:e.confirm,cwd:r,logger:e.logger,yes:e.yes});if(g.code!==0)return{code:g.code,error:"seed: --reset could not clear local state",ndjson:c}}const b=await _(e,m);return b!==void 0?b:z(c,m,l.length,r,e)},ee=E(async({cwd:e,format:r,logger:o,options:t})=>{const n=await P({batchSize:t.batchSize,count:t.count,cwd:e,dryRun:t.dryRun===!0,format:r,logger:o,prod:t.prod===!0,reset:t.reset===!0,now:t.now,seed:t.seed,table:t.table,token:t.token,url:F({cwd:e,prod:t.prod===!0,url:t.url}),yes:t.yes===!0});return{code:n.code,data:n.data,error:n.error}});export{ee as execute,P as runSeedCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{r as $}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{r as S,a as p}from"../packem_shared/admin-url-DJB8P6Jh.mjs";import{d as k}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as u,exitCodeForStatus as b}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{a as y}from"../packem_shared/resolve-target-C_ZloTvd.mjs";const w="/_lunora/admin/shard-registry/prune",f=["prune"],d=(e,r,a)=>(e.error(r),{code:a,error:r}),g=(e,r,a)=>{for(const{shardKey:t,table:n}of r.released)e.info(`${a?"would release":"released"} ${t} (${n})`);for(const{message:t,shardKey:n,tables:l}of r.failed)e.error(`could not check ${n} (${l.join(", ")}) — kept: ${t}`);const s=`${String(r.released.length)} ${a?"would be released":"released"}, ${String(r.kept.length)} kept (still hold rows), ${String(r.failed.length)} unreachable`;r.failed.length>0?e.warn(`${s} — re-run to retry the unreachable shards`):e.success(s)},A=async e=>{const{logger:r}=e;if(!f.includes(e.subcommand))return d(r,`shards: unknown subcommand "${e.subcommand??""}" — expected ${f.join(" | ")}`,u.USAGE);if(e.prod&&e.url===void 0)return d(r,"--prod requires an explicit --url (refusing to prune the implicit localhost worker)",u.USAGE);const a=S(e.url,r,e.cwd);if(a===void 0)return{code:u.USAGE,error:"could not resolve a usable worker URL"};const{token:s}=$({cwd:e.cwd??process.cwd(),token:e.token,url:a});if(!s)return d(r,"admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)",u.AUTH);const t=`${a}${w}`,n=e.fetchImpl??p,l=e.tables?.split(",").map(h=>h.trim()).filter(h=>h!==""),i=e.dryRun===!0;r.info(`POST ${t} -> shards prune${i?" (dry run)":""}`);const c=await n(t,{body:JSON.stringify({dryRun:i,...l===void 0?{}:{tables:l}}),headers:{authorization:`Bearer ${s}`,"content-type":"application/json"},method:"POST"}),m=await c.text();if(!c.ok)return d(r,`shards prune failed: HTTP ${String(c.status)}: ${m}`,b(c.status));let o;try{o=JSON.parse(m)}catch{return d(r,`shards prune failed: worker returned non-JSON: ${m}`,1)}return e.format!=="json"&&g(r,o,i),o.failed.length>0?{code:1,error:`shards prune: ${String(o.failed.length)} shard(s) could not be checked`,result:o}:{code:0,result:o}},E=k(async({argument:e,cwd:r,format:a,logger:s,options:t})=>{const n=await A({cwd:r,dryRun:t.dryRun===!0,format:a,logger:s,prod:t.prod,subcommand:e[0],tables:t.tables,token:t.token,url:y({cwd:r,prod:t.prod===!0,url:t.url})});return{code:n.code,data:n.result,error:n.error}});export{E as execute,A as runShardsCommand};
|
|
@@ -1,3 +1 @@
|
|
|
1
|
-
import{existsSync as
|
|
2
|
-
`)}
|
|
3
|
-
`:""}},P=async e=>{const r=e.cwd??process.cwd(),o=e.format==="json",t=w(r,"lunora","schema.ts"),n=x(e,t);if(n!==void 0)return n;const s=new A({skipAddingFilesFromTsConfig:!0}),d=C(s,t),a=D(e,d);if(a!==void 0)return a;const i=T(d),l=$(i,{defaultCount:e.count??10,now:e.now,only:e.table===void 0?void 0:[e.table],seed:e.seed??0}),{lines:h,ndjson:c}=G(l),m=h.length;if(e.dryRun===!0)return!o&&c.length>0&&process.stdout.write(c),e.logger.info(`generated ${String(m)} row(s) across ${String(l.length)} table(s) — dry run, nothing inserted`),{code:0,data:{conflicts:0,generated:m,inserted:0,rows:o?h.map(g=>JSON.parse(g)):void 0,tables:l.length},ndjson:c};if(m===0)return e.logger.warn("no rows generated — nothing to insert"),{code:0,data:{conflicts:0,generated:0,inserted:0,tables:l.length},ndjson:c};if(e.reset===!0){const g=await U({confirm:e.confirm,cwd:r,logger:e.logger,yes:e.yes});if(g.code!==0)return{code:g.code,error:"seed: --reset could not clear local state",ndjson:c}}const b=await _(e,m);return b!==void 0?b:z(c,m,l.length,r,e)},ee=E(async({cwd:e,format:r,logger:o,options:t})=>{const n=await P({batchSize:t.batchSize,count:t.count,cwd:e,dryRun:t.dryRun===!0,format:r,logger:o,prod:t.prod===!0,reset:t.reset===!0,now:t.now,seed:t.seed,table:t.table,token:t.token,url:F({cwd:e,prod:t.prod===!0,url:t.url}),yes:t.yes===!0});return{code:n.code,data:n.data,error:n.error}});export{ee as execute,P as runSeedCommand};
|
|
1
|
+
import{existsSync as p}from"node:fs";import{join as m}from"node:path";import{runCodegen as u}from"@lunora/codegen";import{validateWranglerProject as g,wranglerCodegenInputs as v}from"@lunora/config/cloudflare";import{a as w,e as y,r as S}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as k,r as j}from"../packem_shared/deploy-target-DCWwiuAe.mjs";import{r as E}from"../packem_shared/codegen-error-AmH54ofi.mjs";import{d as A}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as D}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{r as R,p as $}from"../packem_shared/health-probe-Bw9JFfIy.mjs";import{defaultSpawner as b}from"../packem_shared/createRecordingSpawner-Ch7zuQQE.mjs";import{execArgsFor as U,detectPackageManager as x}from"@lunora/config";const P=async(r,a,t)=>{if(!p(m(r,"tsconfig.json")))return{warning:"no tsconfig.json found — skipping TypeScript type-check"};const o=U(x(r),"tsc",["--noEmit","-p","tsconfig.json"]),e=await a({args:o.args,command:o.command,cwd:r,stdoutToStderr:t==="json"});return e.code===0?{}:{error:`type errors: tsc --noEmit exited ${String(e.code)}`}},T=async(r,a)=>{if(r.healthUrl===void 0||r.healthUrl==="")return;const t=await $({baseUrl:r.healthUrl,fetchImpl:r.healthFetch});if(t.error===void 0){a.success(`verify: health probe ok (${t.url})`);return}return t.error},C=(r,a)=>{const{errorAdvisories:t,names:o,shouldBlock:e}=y(r,S(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.`},H=(r,a,t,o)=>{if(a.length===0&&t.length===0)return r.success("verify: project is valid"),{code:0,errors:[],warnings:[],wranglerPath:o};if(t.length>0){r.warn("verify: warnings:");for(const e of t)r.warn(` - ${e}`)}if(a.length>0){r.error("verify: errors:");for(const e of a){r.error(` - ${e}`);const s=E(e);s!==void 0&&r.error(s)}return{code:1,error:a[0],errors:a,warnings:t,wranglerPath:o}}return r.success("verify: project is valid (with warnings)"),{code:0,errors:[],warnings:t,wranglerPath:o}},I=async r=>{const a=r.cwd??process.cwd(),{logger:t}=r,o=g({environment:r.env,projectRoot:a}),e=[...o.report.errors],s=[...o.report.warnings];try{const n=j(a,r.target);if(n.target===void 0){const c=n.error??"unknown deploy target";return t.error(c),{code:D.USAGE,error:c,errors:[c],warnings:[],wranglerPath:void 0}}const i=u({apiSpec:r.apiSpec,dryRun:!0,projectRoot:a,target:n.target,...v(a)}),f=w(i.platformDiagnostics,t);e.push(...f.errors),s.push(...f.warnings);const l=C(i.advisories,r);l!==void 0&&e.push(l);const h=R({allowDrift:r.allowSchemaDrift===!0,codegen:i,command:"verify",logger:t,readOnly:!0});h.blocked&&e.push(h.reason)}catch(n){const i=n instanceof Error?n.message:String(n);e.push(`codegen failed: ${i}`)}if(r.typecheck!==!1){const n=await P(a,r.spawner??b,r.format??"pretty");n.error!==void 0&&e.push(n.error),n.warning!==void 0&&s.push(n.warning)}const d=await T(r,t);return d!==void 0&&e.push(d),H(t,e,s,o.wranglerPath)},K=A(async({cwd:r,format:a,logger:t,options:o})=>{const e=await I({allowSchemaDrift:o.allowSchemaDrift===!0,apiSpec:k(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{K as execute,I as runVerifyCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{readLiveDevServerState as c}from"@lunora/config";import{d as i}from"../packem_shared/command-CAXl2A1S.mjs";import{o as a}from"../packem_shared/open-url-EnKy--w-.mjs";const n="http://127.0.0.1:6173",d="/__lunora",u=/\/$/u,l=r=>{const e=c(r);return e===void 0?n:e.studioUrl!==void 0?e.studioUrl:e.mode==="vite"?`${e.url.replace(u,"")}${d}`:n},m=async r=>{const e=l(r.cwd??process.cwd()),{logger:t}=r;t.info(`opening ${e}`);try{await a(e,{opener:r.opener})}catch(o){const s=o instanceof Error?o.message:String(o);return t.error(`view: failed to open URL: ${s}`),{code:1,url:e}}return{code:0,url:e}},v=i(({cwd:r,logger:e})=>m({cwd:r,logger:e}));export{v as execute,m as runViewCommand};
|
|
@@ -1 +1,7 @@
|
|
|
1
|
-
import{existsSync as p}from"node:fs";import{join as
|
|
1
|
+
import{writeFileSync as h,existsSync as S,readFileSync as p}from"node:fs";import{isAbsolute as w,join as v}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{wranglerCodegenInputs as M}from"@lunora/config/cloudflare";import{d as D}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as E}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{D as u}from"../packem_shared/cli-C74xjzMK.mjs";const l={clean:"·",exempt:"–",failing:"✗",warned:"!"},d=(e,r)=>e.length>=r?e:e+" ".repeat(r-e.length),R=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}`,F=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},k=(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("",...F(r)),o.join(`
|
|
2
|
+
`)},C=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),...C(i))}return n.join(`
|
|
3
|
+
`)},I=(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
|
+
`)}const t=[`${R(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(`
|
|
5
|
+
`);t.push(""," rules fired:");for(const o of n.checks)t.push(` [${o.level}] ${o.name} −${String(o.weight)}${o.occurrences>1?` (×${String(o.occurrences)})`:""}`);return t.join(`
|
|
6
|
+
`)},L=new Date(0).toISOString(),m=(e,r)=>w(r)?r:v(e,r),N=e=>{if(e===void 0)return{value:void 0};if(e===null||e==="")return{error:"--min-score needs a value between 0 and 100"};const r=Number(e);return Number.isFinite(r)&&r>=0&&r<=100?{value:r}:{error:"--min-score must be a number between 0 and 100"}},P=(e,r,n)=>{const t=m(r,n===null||n===""?u:n);if(!S(t))return{error:`baseline not found at ${t} — generate one with \`lunora advisor\` and commit it`};const o=x(JSON.parse(p(t,"utf8")));return o===void 0?{error:`baseline at ${t} is malformed — regenerate it with \`lunora advisor\``}:{comparison:j(e,o)}},_=e=>`baseline is not comparable (${e}) — regenerate it; this run verified nothing`,G=(e,r,n)=>r.entry!==void 0?I(e,r.entry):r.all===!0?B(e):k(e,n),H=e=>{const r=e.cwd??process.cwd(),n=e.format==="json",{logger:t}=e,o=N(e.minScore);if("error"in o)return e.logger.error(o.error),{code:E.USAGE,error:o.error};const{advisorContext:i,advisories:$}=A({dryRun:!0,projectRoot:r,...M(r)}),a=y(i?.procedureProtections??[],$,{generatedAt:e.generatedAt??L}),s={map:a};if(e.baseline!==void 0){const c=P(a,r,e.baseline);if("error"in c)return e.logger.error(c.error),{...s,error:c.error};s.comparison=c.comparison,c.comparison.comparable||e.logger.error(_(c.comparison.reason))}if(e.write!==!1){const c=m(r,e.out??u);h(c,`${JSON.stringify(a,void 0,4)}
|
|
7
|
+
`,"utf8"),s.written=c}return s.belowMinScore=o.value!==void 0&&a.score<o.value,s.belowMinScore&&t.error(`advisor score ${String(a.score)} is below the required ${String(o.value)}`),n||(t.info(G(a,e,s.comparison)),s.written!==void 0&&t.success(`wrote ${s.written}`)),s},J=e=>e.error!==void 0||e.belowMinScore===!0?!0:e.comparison!==void 0&&(!e.comparison.comparable||e.comparison.regressed),V=D(({cwd:e,format:r,logger:n,options:t})=>{const o=H({all:t.all,baseline:t.baseline,cwd:e,entry:t.entry,format:r,logger:n,minScore:t.minScore,out:t.out,write:t.write});return{code:o.code??(J(o)?1:0),data:{belowMinScore:o.belowMinScore,comparison:o.comparison,map:o.map,written:o.written},error:o.error}});export{V as execute,H as runAdvisorCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
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-Ch7zuQQE.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,7 +1,3 @@
|
|
|
1
|
-
import{writeFileSync as
|
|
2
|
-
`)
|
|
3
|
-
|
|
4
|
-
`)}const t=[`${R(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(`
|
|
5
|
-
`);t.push(""," rules fired:");for(const o of n.checks)t.push(` [${o.level}] ${o.name} −${String(o.weight)}${o.occurrences>1?` (×${String(o.occurrences)})`:""}`);return t.join(`
|
|
6
|
-
`)},L=new Date(0).toISOString(),m=(e,r)=>w(r)?r:v(e,r),N=e=>{if(e===void 0)return{value:void 0};if(e===null||e==="")return{error:"--min-score needs a value between 0 and 100"};const r=Number(e);return Number.isFinite(r)&&r>=0&&r<=100?{value:r}:{error:"--min-score must be a number between 0 and 100"}},P=(e,r,n)=>{const t=m(r,n===null||n===""?u:n);if(!S(t))return{error:`baseline not found at ${t} — generate one with \`lunora advisor\` and commit it`};const o=x(JSON.parse(p(t,"utf8")));return o===void 0?{error:`baseline at ${t} is malformed — regenerate it with \`lunora advisor\``}:{comparison:j(e,o)}},_=e=>`baseline is not comparable (${e}) — regenerate it; this run verified nothing`,G=(e,r,n)=>r.entry!==void 0?I(e,r.entry):r.all===!0?B(e):k(e,n),H=e=>{const r=e.cwd??process.cwd(),n=e.format==="json",{logger:t}=e,o=N(e.minScore);if("error"in o)return e.logger.error(o.error),{code:E.USAGE,error:o.error};const{advisorContext:i,advisories:$}=A({dryRun:!0,projectRoot:r,...M(r)}),a=y(i?.procedureProtections??[],$,{generatedAt:e.generatedAt??L}),s={map:a};if(e.baseline!==void 0){const c=P(a,r,e.baseline);if("error"in c)return e.logger.error(c.error),{...s,error:c.error};s.comparison=c.comparison,c.comparison.comparable||e.logger.error(_(c.comparison.reason))}if(e.write!==!1){const c=m(r,e.out??u);h(c,`${JSON.stringify(a,void 0,4)}
|
|
7
|
-
`,"utf8"),s.written=c}return s.belowMinScore=o.value!==void 0&&a.score<o.value,s.belowMinScore&&t.error(`advisor score ${String(a.score)} is below the required ${String(o.value)}`),n||(t.info(G(a,e,s.comparison)),s.written!==void 0&&t.success(`wrote ${s.written}`)),s},J=e=>e.error!==void 0||e.belowMinScore===!0?!0:e.comparison!==void 0&&(!e.comparison.comparable||e.comparison.regressed),V=D(({cwd:e,format:r,logger:n,options:t})=>{const o=H({all:t.all,baseline:t.baseline,cwd:e,entry:t.entry,format:r,logger:n,minScore:t.minScore,out:t.out,write:t.write});return{code:o.code??(J(o)?1:0),data:{belowMinScore:o.belowMinScore,comparison:o.comparison,map:o.map,written:o.written},error:o.error}});export{V as execute,H as runAdvisorCommand};
|
|
1
|
+
import{writeFileSync as E,existsSync as w,cpSync as j,statSync as b,lstatSync as I,readdirSync as N,mkdirSync as D,readFileSync as M}from"node:fs";import{join as u,sep as x,relative as B,resolve as O,dirname as K}from"node:path";import{SDK_TARGETS as V,SDK_LANGUAGES as G,generateSdk as P,isTypedSchema as Q}from"@lunora/codegen";import{LunoraError as d}from"@lunora/errors";import{d as J}from"../packem_shared/command-CAXl2A1S.mjs";import{r as _,a as q,b as H,s as W}from"../packem_shared/resolve-BrsV4Qyc.mjs";import{r as U}from"../packem_shared/cli-manifest-CRet0egA.mjs";const $="gh:anolilab/lunora/sdks",v="lunora-transport.json",X=/_test\.|Tests?\./u,k=t=>t.startsWith("test_")||X.test(t),A=(t,o="")=>N(t).toSorted((e,r)=>e.localeCompare(r)).flatMap(e=>{const r=u(t,e),a=o.length>0?`${o}/${e}`:e;return b(r).isDirectory()?A(r,a):[a]}),C=(t,o)=>{const e=I(o);if(e.isSymbolicLink())throw new d("INTERNAL",`refusing to vendor "${B(t,o)}" — it is a symlink, not a regular file`);if(e.isDirectory())for(const r of N(o))k(r)||C(t,u(o,r))},F=(t,o,e,r)=>{const a=u(t,e);if(!w(a))throw new d("NOT_FOUND",`transport is missing ${e}`);C(t,a);const s=u(o,r);return j(a,s,{filter:n=>!k(n.slice(n.lastIndexOf(x)+1)),force:!0,recursive:!0}),b(s).isDirectory()?A(s).map(n=>`${r}/${n}`):[r]},R=(t,o)=>o.vendor.every(e=>w(u(t,e.from))),z=async(t,o)=>{const{language:e,logger:r,outputDirectory:a,registryOptions:s,target:n}=o,{cleanup:f,directory:h}=await H(e,{...s,ref:t},$);try{if(!R(h,n)){r.warn(`${$}/${e} does not exist at ${t}.`);return}return{files:n.vendor.flatMap(c=>F(h,a,c.from,c.to)).toSorted((c,l)=>c.localeCompare(l)),ref:t,source:`${$}/${e}`,versionMatched:t===_()}}finally{f()}},Y=(t,o)=>{const{language:e,outputDirectory:r,target:a}=o,s=u(t,e);if(!w(s))throw new d("NOT_FOUND",`no transport at ${s} — --from must point at a directory of per-language transports (the repo's \`sdks/\`)`);if(!R(s,a)){const n=a.vendor.map(f=>f.from).join(", ");throw new d("NOT_FOUND",`${s} is not a ${e} transport — expected it to contain ${n}`)}return{files:a.vendor.flatMap(n=>F(s,r,n.from,n.to)).toSorted((n,f)=>n.localeCompare(f)),ref:"local",source:s,versionMatched:!1}},Z=async t=>{const{allowUnsafeSource:o,from:e,language:r,logger:a,outputDirectory:s,ref:n,source:f,target:h}=t;if(e!==void 0)return Y(e,{language:r,outputDirectory:s,target:h});const c={allowUnsafeSource:o,logger:a,names:[],source:f},l=async i=>z(await q(i,a),{language:r,logger:a,outputDirectory:s,registryOptions:c,target:h});if(n!==void 0&&n.length>0){const i=await l(n);if(i===void 0)throw new d("NOT_FOUND",`--ref ${n} carries no ${r} transport — pick a ref that does, or pass --from <dir> to copy a local one`);return i}const p=_(),g=await l(p).catch(i=>{const y=i instanceof Error?i.message.split(`
|
|
2
|
+
`)[0]??i.message:String(i);a.warn(`could not fetch the transport at ${p} (${y}).`)});if(g!==void 0)return g;const m=await l(void 0);if(m===void 0)throw new d("NOT_FOUND",`no ${r} transport at ${p} or on the release branch. This language may not be released yet — pass --from <dir> to copy one from a checkout, or --ref <tag> to name a ref that has it.`);return a.warn(`FALLBACK: the transport is NOT version-matched to this CLI (${U()}). Wanted ${p}, used ${m.ref}. The vendored wire protocol may not be the one this surface was generated against; ${v} records what was actually copied.`),m},ee=(t,o,e)=>{const r={cliVersion:U(),files:e.files,language:o,note:e.versionMatched?"Vendored by `lunora sdk generate` at the ref matching the CLI that generated the surface beside it. Regenerate with a newer CLI to upgrade.":"Vendored by `lunora sdk generate` from a ref that is NOT this CLI's release tag, so the transport and the generated surface may be different protocol vintages.",ref:e.ref,source:e.source,versionMatched:e.versionMatched};E(u(t,v),`${JSON.stringify(r,void 0,4)}
|
|
3
|
+
`,"utf8")},te=u("lunora","_generated","openrpc.json"),re=t=>{if(!w(t))throw new d("NOT_FOUND",`no OpenRPC document at ${t} — run \`lunora codegen --api-spec openrpc\` (or \`--api-spec both\`) first, or pass --spec`);let o;try{o=JSON.parse(M(t,"utf8"))}catch(e){throw new d("BAD_REQUEST",`${t} is not valid JSON: ${e instanceof Error?e.message:String(e)}`)}if(o===null||typeof o!="object"||!Array.isArray(o.methods))throw new d("BAD_REQUEST",`${t} is not an OpenRPC document (no \`methods\` array)`);return o},le=J(async({argument:t,cwd:o,logger:e,options:r})=>{const a=t[0]??"generate";if(a!=="generate")throw new d("BAD_REQUEST",`unknown subcommand "${a}" — the only one is \`lunora sdk generate\``);const s=r.lang??"python",n=V[s];if(n===void 0)throw new d("BAD_REQUEST",`unsupported --lang "${s}" — expected one of: ${G.join(" | ")}`);const f=W("sdk generate",{allowUnsafeSource:r.allowUnsafeSource,logger:e,names:[],source:r.source});if(f!==void 0)throw new d("BAD_REQUEST",f);const h=O(o,r.spec??te),c=O(o,r.out??u("sdk",s)),l=re(h);l.methods.length===0&&e.warn(`${h} declares no methods — writing an empty SDK.`);const{files:p,undeclared:g,unrepresentable:m}=await P(l,n);D(c,{recursive:!0});const i=await Z({allowUnsafeSource:r.allowUnsafeSource,from:r.from,language:s,logger:e,outputDirectory:c,ref:r.ref,source:r.source,target:n});ee(c,s,i);for(const[S,L]of Object.entries(p)){const T=u(c,S);D(K(T),{recursive:!0}),E(T,L,"utf8")}const y=l.methods.filter(S=>!Q(S.result?.schema)).length;return e.success(`Generated ${s} SDK for ${String(l.methods.length)} function(s) → ${c}`),e.info(`Vendored the ${s} transport (${String(i.files.length)} file(s)) from ${i.source} @ ${i.ref}${i.versionMatched?" — version-matched to this CLI":""}; see ${v}.`),e.info(n.requires.length>0?`Install in the consuming project: ${n.requires.join(", ")}.`:"Nothing to install — the transport is vendored and needs only the standard library."),g.length>0&&e.warn(`${String(g.length)} schema(s) are not expressible as a named ${s} model, so those arguments or returns stay untyped: ${g.join(", ")}`),m.length>0&&e.warn(`${String(m.length)} function(s) take or return a \`v.bigint()\`/\`v.bytes()\`, which no generated model can carry — their parameters stay untyped, so pass wire values directly: ${m.join(", ")}`),y>0&&e.warn(`${String(y)} of ${String(l.methods.length)} function(s) return an untyped result — declare \`.output()\` on them for typed returns.`),{code:0}});export{le as execute};
|
|
@@ -1 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import z,{join as m,resolve as I}from"node:path";import{isInteractive as J,promptYesNo as W}from"@lunora/config";import{backupObjectKey as v,isBackupManifestEntry as D,normalizeBackupPrefix as Y,BACKUP_KEY_PREFIX as X,backupManifestKey as Q,isBackupManifestKey as V,backupObjectKeyOfManifest as G}from"@lunora/runtime";import{r as E,t as Z}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{r as A,a as T}from"../packem_shared/admin-url-DJB8P6Jh.mjs";import{d as ee}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as u,isRefusal as p,exitCodeForStatus as k}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{a as re}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{runExportCommand as te}from"../packem_shared/runExportCommand-slAq5BCF.mjs";import{b as ae,l as oe,M as U,u as ne,r as ie}from"../packem_shared/import-BRM1hs7j.mjs";import{readAndLogBody as y}from"./runRpcCommand.mjs";import{randomUUID as j,createHash as se}from"node:crypto";import{existsSync as N,createReadStream as ce,createWriteStream as de}from"node:fs";import{mkdir as ue,rm as b,rename as C,readFile as q,writeFile as le,realpath as _,mkdtemp as x}from"node:fs/promises";import{LunoraError as w}from"@lunora/errors";import{i as R}from"../packem_shared/path-containment-CgxYZggb.mjs";import{tmpdir as O}from"node:os";import{Readable as fe}from"node:stream";import{pipeline as me}from"node:stream/promises";const S="manifest.json",L=async e=>{const t=se("sha256");let r=0;for await(const a of ce(e)){const o=a;r+=o.byteLength,t.update(o)}return{bytes:r,sha256:t.digest("hex")}},P=async e=>{const t=m(e,S);if(!N(t))return[];let r;try{r=JSON.parse(await q(t,"utf8"))}catch(a){const o=a instanceof Error?a.message:String(a);throw new w("INTERNAL",`backup: ${t} exists but is not valid JSON (${o}) — refusing to overwrite it; fix or remove it manually`,{cause:a})}if(!Array.isArray(r))throw new TypeError(`backup: ${t} exists but is not a JSON array — refusing to overwrite it; fix or remove it manually`);return r.filter(a=>D(a))},ge=async(e,t)=>{const r=m(e,`${S}.${j()}.tmp`);try{await le(r,`${JSON.stringify(t,void 0,2)}
|
|
2
|
+
`,"utf8"),await C(r,m(e,S))}catch(a){throw await b(r,{force:!0}),a}},he=async(e,t)=>{const r=I(e),a=I(r,t.file),o=()=>{throw new w("INTERNAL",`backup: entry ${t.id} points outside ${r} (${t.file}) — refusing to read it`)};if(R(r,a)||o(),!!N(a))return R(await _(r),await _(a))||o(),a},we=e=>{const t=r=>v("",r);return{commit:async(r,a)=>{await C(a,m(e,r))},label:e,list:async()=>P(e),locate:t,materialize:async(r,a)=>{const o=i=>i===void 0?void 0:{path:i,release:()=>Promise.resolve()};return o(r===void 0?N(a)?a:void 0:await he(e,r))},record:async r=>{const a=await P(e);a.push(r),await ge(e,a)},stage:async r=>{await ue(e,{recursive:!0});const a=m(e,`${t(r)}.${j()}.partial`);return{path:a,release:()=>b(a,{force:!0})}}}},be="/_lunora/admin/storage/object",ke="/_lunora/admin/storage",B=8,ye=(e,t=z)=>{const r=t.basename(e);return r===""||r==="."||r===".."?"snapshot.ndjson":r},pe=e=>{const{context:t,logger:r}=e,a=Y(e.prefix??X),o=`bucket ${t.bucket??"(default)"} under ${a}`,i=ae(t),n=c=>`${t.baseUrl}${be}?key=${encodeURIComponent(c)}${i}`,f=async c=>{const s=await t.fetchImpl(n(c),{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(!s.ok){const l=await s.text().catch(()=>"<no body>");throw new w("INTERNAL",`backup: could not read ${c} (HTTP ${String(s.status)}): ${l}`)}return s.text()},H=async c=>{try{const s=JSON.parse(await f(c));if(D(s))return s;r.warn(`backup: ignoring ${c} — not a backup manifest`)}catch(s){r.warn(`backup: ignoring ${c} — ${s instanceof Error?s.message:String(s)}`)}};return{commit:async(c,s,l)=>{if(l.bytes>U)throw new w("INTERNAL",`backup: the snapshot is ${String(l.bytes)} bytes, above the ${String(U)}-byte limit for a checksum-verified upload — nothing was written. Narrow it with \`--tables\`, or write it to a directory with \`--dir\` and move the file yourself (\`wrangler r2 object put\`).`);const d=await q(s);await ne(t,c,d,{contentType:"application/x-ndjson",id:c,sha256:l.sha256,size:l.bytes},r)},label:o,list:async()=>{const s=(await oe(t,a)).map(d=>d.key).filter(d=>V(d)),l=[];for(let d=0;d<s.length;d+=B){const g=await Promise.all(s.slice(d,d+B).map(async h=>H(h)));l.push(...g.filter(h=>h!==void 0))}return l.toSorted((d,g)=>d.id.localeCompare(g.id))},locate:c=>v(a,c),materialize:async(c,s)=>{const l=c?.file??s,d=await t.fetchImpl(n(l),{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(d.status===404)return;if(!d.ok||d.body===null){const $=await d.text().catch(()=>"<no body>");throw new w("INTERNAL",`backup: could not download ${l} (HTTP ${String(d.status)}): ${$}`)}const g=await x(m(O(),"lunora-backup-")),h=m(g,ye(l));try{await me(fe.from(d.body),de(h))}catch($){throw await b(g,{force:!0,recursive:!0}),$}return{path:h,release:async()=>b(g,{force:!0,recursive:!0})}},record:async c=>{const s=Q(c.file),l=await t.fetchImpl(`${t.baseUrl}${ke}?key=${encodeURIComponent(s)}${i}`,{body:`${JSON.stringify(c,void 0,2)}
|
|
3
|
+
`,headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json"},method:"PUT"});if(!l.ok){const d=await l.text().catch(()=>"<no body>");throw new w("INTERNAL",`backup: snapshot ${c.file} was written but its manifest was not (HTTP ${String(l.status)}): ${d}`)}},stage:async c=>{const s=await x(m(O(),"lunora-backup-"));return{path:m(s,v("",c)),release:async()=>b(s,{force:!0,recursive:!0})}}}},$e=".lunora-backups",F="/_lunora/admin/backup/retention",ve="/_lunora/admin/backup/prune",Se="/_lunora/admin/pitr",Ee="__lunora_admin__:getPitrBookmark",Ae="__lunora_admin__:pitrRestore",Te=async(e,t)=>{const r=(e.now??(()=>new Date))().toISOString(),a=await t.stage(r);try{const o=await te({cwd:e.cwd,fetchImpl:e.fetchImpl,logger:e.logger,out:a.path,prod:e.prod,tables:e.tables,token:e.token,url:e.url});if(o.code!==0)return{code:o.code};const i=t.locate(r),n=await L(a.path);await t.commit(i,a.path,n);const f={bytes:n.bytes,createdAt:r,file:i,id:r,rows:o.rows,sha256:n.sha256,tables:e.tables};return await t.record(f),e.logger.success(`backup created: ${i} (${o.rows.toString()} rows, ${n.bytes.toString()} bytes)`),{code:0,entry:f}}finally{await a.release().catch(o=>{e.logger.warn(`backup: could not clean up staging (${o instanceof Error?o.message:String(o)})`)})}},Ne=async(e,t,r)=>{if(t?.sha256===void 0)return r.error(t===void 0?"--verify needs a recorded checksum, and a snapshot restored by path/key has no manifest entry — restore it by its backup id instead":`--verify: backup ${t.id} carries no recorded checksum — it was taken by a release before checksums existed`),{code:u.USAGE};const a=await L(e);if(a.sha256!==t.sha256)return r.error(`--verify: ${t.file} does not match its recorded checksum (expected ${t.sha256}, got ${a.sha256}) — nothing was imported`),{code:1};r.success(`verified ${t.file} against its recorded sha256`)},Ie=async(e,t)=>{const r=await t.list();if(r.length===0)return e.logger.info(`no backups found in ${t.label}`),{code:0,entries:[]};for(const a of r)e.logger.info(`${a.id} ${a.rows.toString()} rows ${a.bytes.toString()} bytes ${a.file}`);return{code:0,entries:r}},Ue=async(e,t)=>{const{target:r}=e;if(r===void 0||r.length===0)return e.logger.error("restore requires a backup id or file path. Usage: lunora backup restore <id|file>"),{code:u.USAGE};const o=(await t.list()).find(n=>n.id===r),i=await t.materialize(o,r);if(i===void 0)return e.logger.error(`backup not found: ${r}`),{code:u.NOT_FOUND};try{if(e.verify===!0){const f=await Ne(i.path,o,e.logger);if(f!==void 0)return f}const n=await ie({cwd:e.cwd,fetchImpl:e.fetchImpl,file:i.path,logger:e.logger,prod:e.prod,token:e.token,url:e.url,yes:e.yes});return{code:n.code,entry:o,restored:n.inserted}}finally{await i.release().catch(n=>{e.logger.warn(`backup: could not clean up the downloaded snapshot (${n instanceof Error?n.message:String(n)})`)})}},_e=e=>{if(e.prod&&e.url===void 0)return e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)"),{refused:u.USAGE};if(e.restore===!0&&e.at===void 0&&e.bookmark===void 0)return e.logger.error("pitr --restore requires --at <time> or --bookmark <bookmark>"),{refused:u.USAGE};const t=A(e.url,e.logger,e.cwd);if(t===void 0)return{refused:u.USAGE};if(e.restore===!0&&Z({prod:e.prod,url:t})&&e.yes!==!0)return e.logger.error(`pitr --restore restores data in place at ${t}, which is not local. Re-run with --yes to confirm.`),{refused:u.USAGE};const{token:r}=E({cwd:e.cwd??process.cwd(),token:e.token,url:t});return r?{fetchImpl:e.adminFetch??T,requestUrl:`${t}${Se}`,token:r}:(e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{refused:u.AUTH})},xe=(e,t)=>{const r={};return e.at!==void 0&&(r.time=e.at),t&&e.bookmark!==void 0&&(r.bookmark=e.bookmark),t&&e.restart===!0&&(r.restart=!0),r},Re=async e=>{const t=_e(e);if(p(t))return{code:t.refused};const r=e.restore===!0,a=r?Ae:Ee,o=xe(e,r),i=r?"restore":"bookmark";e.logger.info(`POST ${t.requestUrl} -> pitr ${i}${e.shard===void 0?"":` (shard "${e.shard}")`}`);const n=await t.fetchImpl(t.requestUrl,{body:JSON.stringify({args:o,functionPath:a,shardKey:e.shard}),headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json"},method:"POST"});return{body:await y(n,e.logger),code:n.ok?0:k(n.status)}},Oe=(e,t)=>{if(e.bucket===void 0)return e.prefix!==void 0?(e.logger.error("--prefix applies only to an R2 destination — pass --bucket alongside it, or use --dir to point at a local directory."),{refused:u.USAGE}):we(m(t,e.dir??$e));if(e.dir!==void 0)return e.logger.error("--dir applies only to a local destination and does not apply alongside --bucket — drop one."),{refused:u.USAGE};if(e.prod===!0&&e.url===void 0)return e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)"),{refused:u.USAGE};const r=A(e.url,e.logger,e.cwd);if(r===void 0)return{refused:u.USAGE};const{token:a}=E({cwd:t,token:e.token,url:r});if(!a)return e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{refused:u.AUTH};const o=e.fetchImpl??T;return pe({context:{baseUrl:r,bucket:e.bucket==="default"?void 0:e.bucket,fetchImpl:o,token:a},logger:e.logger,prefix:e.prefix})},M=e=>{const t=[e.bucket===void 0?void 0:"--bucket",e.prefix===void 0?void 0:"--prefix",e.dir===void 0?void 0:"--dir"].filter(i=>i!==void 0);if(t.length>0)return e.logger.error(`${t.join(" / ")} ${t.length===1?"does":"do"} not apply here — retention and prune act on the store the worker itself is configured with (\`backupStore\`), not a destination you name.`),{refused:u.USAGE};if(e.prod===!0&&e.url===void 0)return e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)"),{refused:u.USAGE};const r=A(e.url,e.logger,e.cwd);if(r===void 0)return{refused:u.USAGE};const{token:a}=E({cwd:e.cwd??process.cwd(),token:e.token,url:r});if(!a)return e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{refused:u.AUTH};const o=e.adminFetch??T;return{baseUrl:r,fetchImpl:o,token:a}},K=(e,t)=>{e.logger.info(`backup retention would keep the newest ${t.keep.toString()} of ${t.eligible.toString()} under ${t.prefix} and delete ${t.wouldDelete.length.toString()}`);for(const r of t.wouldDelete)e.logger.info(` ${G(r)}`)},Pe=async e=>{const t=M(e);if(p(t))return{code:t.refused};const r=await t.fetchImpl(`${t.baseUrl}${F}`,{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(!r.ok)return await y(r,e.logger),{code:k(r.status)};const a=await r.json();return a.cron===void 0?(e.logger.info("no scheduled backup is configured (`backupCron`), so retention would delete nothing"),{code:0,preview:a}):a.keep<=0?(e.logger.info(`retention is off for cron "${a.cron}" (\`backupRetain\` unset) — every snapshot under ${a.prefix} is kept`),{code:0,preview:a}):(K(e,a),a.eligible===0&&e.logger.info(`no snapshot under ${a.prefix} was written by this cron, so retention has nothing of its own to remove`),{code:0,preview:a})},Be=(e,t)=>{e.logger.success(`deleted ${t.deleted.length.toString()} backup(s)`);for(const r of t.deleted)e.logger.info(` ${G(r)}`);t.failed.length>0&&e.logger.warn(`${t.failed.length.toString()} could not be removed — the snapshot may be gone with its manifest left behind; run again to retry`),t.ignored>0&&e.logger.info(`${t.ignored.toString()} were already gone by the time the delete ran`),t.remaining>0&&e.logger.info(`${t.remaining.toString()} more are past the window — run \`lunora backup prune\` again`)},De=async e=>{const t=M(e);if(p(t))return{code:t.refused};const r=await t.fetchImpl(`${t.baseUrl}${F}`,{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(!r.ok)return await y(r,e.logger),{code:k(r.status)};const a=await r.json();if(a.keep<=0||a.cron===void 0)return e.logger.error("backup prune needs a retention window: set `backupRetain` (and `backupCron`) on the worker. Without one there is nothing past the window to remove."),{code:u.USAGE,preview:a};if(a.wouldDelete.length===0)return e.logger.info(`nothing to prune — ${a.eligible.toString()} snapshot(s) under ${a.prefix} and retention keeps the newest ${a.keep.toString()}`),{code:0,preview:a};if(K(e,a),e.yes!==!0){const n=e.confirm??(J()?W:void 0);if(n===void 0)return e.logger.error("refusing to delete backups without confirmation — re-run with --yes (there is no undo for an object-store delete)"),{code:u.USAGE,preview:a};if(!await n(`delete ${a.wouldDelete.length.toString()} backup(s)? This cannot be undone. [y/N] `))return e.logger.info("nothing was deleted"),{code:0,preview:a}}const o=await t.fetchImpl(`${t.baseUrl}${ve}`,{body:JSON.stringify({confirm:a.wouldDelete}),headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json"},method:"POST"});if(!o.ok)return await y(o,e.logger),{code:k(o.status),preview:a};const i=await o.json();return Be(e,i),{code:i.failed.length>0?1:0,deleted:i.deleted,preview:a}},Ge=async(e,t)=>{try{if(e.subcommand==="pitr")return await Re(e);if(e.subcommand==="retention")return await Pe(e);if(e.subcommand==="prune")return await De(e);const r=Oe(e,t);return p(r)?{code:r.refused}:e.subcommand==="create"?await Te(e,r):e.subcommand==="list"?await Ie(e,r):await Ue(e,r)}catch(r){return e.logger.error(r instanceof Error?r.message:String(r)),{code:1}}},je=async e=>{const t=e.cwd??process.cwd(),r=await Ge(e,t);return{...r,data:{subcommand:e.subcommand,...r.entries===void 0?{}:{entries:r.entries},...r.entry===void 0?{}:{entry:r.entry},...r.restored===void 0?{}:{restored:r.restored},...r.preview===void 0?{}:{preview:r.preview},...r.deleted===void 0?{}:{deleted:r.deleted},...r.body===void 0?{}:{result:r.body}}}},Ce=e=>e==="create"||e==="list"||e==="pitr"||e==="prune"||e==="restore"||e==="retention",nr=ee(async({argument:e,cwd:t,format:r,logger:a,options:o})=>{const i=e[0];if(!Ce(i)){const f=`backup: unknown subcommand "${i??""}" — expected create | list | restore | retention | prune | pitr`;return a.error(f),{code:u.USAGE,error:f}}const n=await je({at:o.at,bookmark:o.bookmark,bucket:o.bucket,cwd:t,dir:o.dir,format:r,logger:a,prefix:o.prefix,prod:o.prod===!0,restart:o.restart===!0,restore:o.restore===!0,shard:o.shard,subcommand:i,tables:o.tables,target:e[1],token:o.token,url:re({cwd:t,prod:o.prod===!0,url:o.url}),verify:o.verify===!0,yes:o.yes===!0});return{code:n.code,data:n.data,error:n.error}});export{nr as execute,je as runBackupCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{join as
|
|
1
|
+
import{readdirSync as g,lstatSync as S,existsSync as y}from"node:fs";import{join as E,basename as T}from"node:path";import{pathToFileURL as w}from"node:url";import{d as R}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as u}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";const l=".eval.ts",$=new Set([".git","_generated","dist","node_modules"]),v=(e,s=[])=>{let r;try{r=g(e)}catch{return s}for(const t of r){const o=E(e,t);let n;try{n=S(o)}catch{continue}if(n.isDirectory()){if($.has(t))continue;v(o,s)}else n.isFile()&&t.endsWith(l)&&s.push(o)}return s.toSorted((t,o)=>t.localeCompare(o))},_=e=>typeof e=="object"&&e!==null&&typeof e.run=="function",m=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1,F="evals",O='"lunora eval" needs native TypeScript execution — run Node ≥23.6, or a TS loader/transform (tracked in plans/245-eval-runner-design.md §8.3)',N=/unknown file extension ".ts"/i,p=e=>e instanceof Error?e.code==="ERR_UNKNOWN_FILE_EXTENSION"?!0:N.test(e.message):!1,f=e=>T(e,l),x=e=>({average:e.result?.average,error:e.error,items:e.result?.items,name:e.name,passed:e.passed,path:e.path,threshold:e.threshold}),b=e=>({evals:e.evals.map(s=>x(s))}),i=(e,s,r)=>(e.error(s),{code:r,error:s,evals:[]}),A=(e,s,r)=>{if(!y(e))return r.info(`eval: no "${s}" directory — nothing to run`),[];const t=v(e);return t.length===0&&r.info(`eval: no ${l} files found under "${s}"`),t},I=async e=>{const r=(await import(w(e).href)).default;if(!_(r))throw new Error("does not default-export an eval module (expected `{ run(): Promise<EvalResult>, name?, threshold? }`)");return r},L=async(e,s)=>{let r;try{r=await I(e)}catch(n){if(p(n))throw n;return{error:n instanceof Error?n.message:String(n),name:f(e),passed:!1,path:e}}const t=r.name??f(e);if(r.threshold!==void 0&&!m(r.threshold))return{error:`invalid \`threshold\` export: must be a number in [0, 1] — received ${JSON.stringify(r.threshold)}`,name:t,passed:!1,path:e};const o=r.threshold??s;try{const n=await r.run(),a=o===void 0||n.average>=o;return{name:t,passed:a,path:e,result:n,threshold:o}}catch(n){return{error:n instanceof Error?n.message:String(n),name:t,passed:!1,path:e,threshold:o}}},U=async(e,s)=>{const r=[];for(const t of e)r.push(await L(t,s));return r},D=e=>{if(e.error!==void 0)return`ERROR: ${e.error}`;const s=e.passed?"pass":"FAIL",r=e.result?.items.length??0;return`${s} (${String(r)} cases)`},C=e=>{if(e.length===0)return[];const s=Math.max(4,...e.map(t=>t.name.length)),r=[`${"NAME".padEnd(s)} SCORE THRESHOLD STATUS`];for(const t of e){const o=t.result===void 0?"—":t.result.average.toFixed(3),n=t.threshold===void 0?"—":t.threshold.toFixed(3);r.push(`${t.name.padEnd(s)} ${o.padEnd(6)} ${n.padEnd(9)} ${D(t)}`)}return r},M=async e=>{const s=e.cwd??process.cwd(),{logger:r}=e;if(e.threshold!==void 0&&!m(e.threshold))return i(r,`eval: --threshold must be a number in [0, 1] — received "${String(e.threshold)}"`,u.USAGE);const t=e.dir??F,o=E(s,t),n=A(o,t,r);let a;try{a=await U(n,e.threshold)}catch(d){if(!p(d))throw d;return i(r,O,1)}if(e.threshold!==void 0&&a.length===0){const d=`eval: --threshold ${String(e.threshold)} was set but 0 eval files were discovered under "${t}" — nothing was gated`;return i(r,d,u.USAGE)}for(const d of C(a))r.info(d);const c=a.filter(d=>!d.passed),h=c.length>0?1:0;return h===0?r.success(`eval: ${String(a.length)} eval(s) passed`):r.error(`eval: ${String(c.length)}/${String(a.length)} eval(s) failed`),{code:h,evals:a}},V=R(async({cwd:e,format:s,logger:r,options:t})=>{const o=await M({cwd:e,dir:t.dir,format:s,logger:r,threshold:t.threshold});return{code:o.code,data:b(o),error:o.error}});export{V as execute,M as runEvalCommand};
|
|
@@ -1,3 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`)
|
|
3
|
-
`,"utf8")},te=u("lunora","_generated","openrpc.json"),re=t=>{if(!w(t))throw new d("NOT_FOUND",`no OpenRPC document at ${t} — run \`lunora codegen --api-spec openrpc\` (or \`--api-spec both\`) first, or pass --spec`);let o;try{o=JSON.parse(M(t,"utf8"))}catch(e){throw new d("BAD_REQUEST",`${t} is not valid JSON: ${e instanceof Error?e.message:String(e)}`)}if(o===null||typeof o!="object"||!Array.isArray(o.methods))throw new d("BAD_REQUEST",`${t} is not an OpenRPC document (no \`methods\` array)`);return o},le=J(async({argument:t,cwd:o,logger:e,options:r})=>{const a=t[0]??"generate";if(a!=="generate")throw new d("BAD_REQUEST",`unknown subcommand "${a}" — the only one is \`lunora sdk generate\``);const s=r.lang??"python",n=V[s];if(n===void 0)throw new d("BAD_REQUEST",`unsupported --lang "${s}" — expected one of: ${G.join(" | ")}`);const f=W("sdk generate",{allowUnsafeSource:r.allowUnsafeSource,logger:e,names:[],source:r.source});if(f!==void 0)throw new d("BAD_REQUEST",f);const h=O(o,r.spec??te),c=O(o,r.out??u("sdk",s)),l=re(h);l.methods.length===0&&e.warn(`${h} declares no methods — writing an empty SDK.`);const{files:p,undeclared:g,unrepresentable:m}=await P(l,n);D(c,{recursive:!0});const i=await Z({allowUnsafeSource:r.allowUnsafeSource,from:r.from,language:s,logger:e,outputDirectory:c,ref:r.ref,source:r.source,target:n});ee(c,s,i);for(const[S,L]of Object.entries(p)){const T=u(c,S);D(K(T),{recursive:!0}),E(T,L,"utf8")}const y=l.methods.filter(S=>!Q(S.result?.schema)).length;return e.success(`Generated ${s} SDK for ${String(l.methods.length)} function(s) → ${c}`),e.info(`Vendored the ${s} transport (${String(i.files.length)} file(s)) from ${i.source} @ ${i.ref}${i.versionMatched?" — version-matched to this CLI":""}; see ${v}.`),e.info(n.requires.length>0?`Install in the consuming project: ${n.requires.join(", ")}.`:"Nothing to install — the transport is vendored and needs only the standard library."),g.length>0&&e.warn(`${String(g.length)} schema(s) are not expressible as a named ${s} model, so those arguments or returns stay untyped: ${g.join(", ")}`),m.length>0&&e.warn(`${String(m.length)} function(s) take or return a \`v.bigint()\`/\`v.bytes()\`, which no generated model can carry — their parameters stay untyped, so pass wire values directly: ${m.join(", ")}`),y>0&&e.warn(`${String(y)} of ${String(l.methods.length)} function(s) return an untyped result — declare \`.output()\` on them for typed returns.`),{code:0}});export{le as execute};
|
|
1
|
+
import{readLinkedProject as h,resolveDeployDriver as b,toolchainExecArgs as y,detectPackageManager as w}from"@lunora/config";import{d as E}from"../packem_shared/command-CAXl2A1S.mjs";import{r as L}from"../packem_shared/deploy-target-DCWwiuAe.mjs";import{EXIT_CODE as m}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{defaultSpawner as S}from"../packem_shared/createRecordingSpawner-Ch7zuQQE.mjs";import{createR2Sql as _}from"@lunora/bindings/r2sql";import{createPipelineLogReader as T}from"@lunora/runtime";const p=["trace","debug","log","info","warn","error","fatal"],C=new Set(p),v=/^\d+$/,f=(e,r)=>{if(e===void 0)return;const a=e.trim();if(v.test(a))return Number(a);const n=Date.parse(a);if(Number.isNaN(n))throw new TypeError(`logs: invalid ${r} "${e}" — pass epoch-millis or an ISO 8601 date`);return n},I=e=>Buffer.from(JSON.stringify(e),"utf8").toString("base64url"),$=e=>{const r=e.trim();if(v.test(r))return{ts:Number(r)};let a;try{a=JSON.parse(Buffer.from(r,"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,t=a.seen,s=Array.isArray(t)?t.filter(i=>typeof i=="string"):void 0;return s!==void 0&&s.length>0?{seen:s,ts:n}:{ts:n}},g=(e,r)=>{if(e!==void 0){if(!C.has(e))throw new TypeError(`logs: invalid ${r} "${e}" — expected one of trace, debug, log, info, warn, error, fatal`);return e}},R=e=>{const r={},a=f(e.since,"--since");a!==void 0&&(r.sinceTs=a);const n=f(e.until,"--until");n!==void 0&&(r.untilTs=n);const t=g(e.level,"--level");t!==void 0&&(r.level=t);const s=g(e.minLevel,"--min-level");if(s!==void 0&&(r.minLevel=s),e.functionPrefix!==void 0&&(r.functionPathPrefix=e.functionPrefix),e.traceId!==void 0&&(r.traceId=e.traceId),e.shardKey!==void 0&&(r.shardKey=e.shardKey),e.userId!==void 0&&(r.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`);r.limit=i}return e.cursor!==void 0&&(r.cursor=$(e.cursor)),r},N=e=>{const r=new Date(e.ts).toISOString(),a=e.level.toUpperCase().padEnd(5);return`${r} ${a} ${e.functionPath} ${e.message}`},O=async e=>{const r=e.environment??process.env,a=r.R2_SQL_ACCOUNT_ID,n=r.R2_SQL_TOKEN,t=r.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"),(t===void 0||t.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:m.USAGE,error:"not configured"};let i;try{i=R(e)}catch(o){return e.logger.error(o instanceof Error?o.message:String(o)),{code:m.USAGE,error:"invalid option"}}const u=_({accountId:a,apiToken:n,bucket:t,fetch:e.fetch}),c=await T(u,{namespace:e.namespace,table:e.table}).query(i);for(const o of c.rows)process.stdout.write(`${e.ndjson===!0?JSON.stringify(o):N(o)}
|
|
2
|
+
`);return c.rows.length===0?e.logger.info("logs --durable: no matching log records"):c.nextCursor!==void 0&&e.logger.info(`logs --durable: more rows available — pass --cursor ${I(c.nextCursor)} for the next page`),{code:0,rows:c.rows}},x=async e=>{const r=e.cwd??process.cwd(),a=e.env??h(r)?.env,n=L(r,e.target);if(n.target===void 0){const d=`logs: ${n.error??"no deploy target"}`;return e.logger.error(d),{code:m.USAGE,descriptor:void 0,error:d}}const t=b(n.target),s=t.toolchain?.tail;if(s===void 0){const d=`logs: deploy target "${t.id}" has no log tail`;return e.logger.error(d),{code:m.USAGE,descriptor:void 0,error:d}}const i=s({environment:a,format:e.format,search:e.search,status:e.status,temporary:e.temporary,worker:e.worker}),u=y(w(r),i),l={args:u.args,command:u.command,cwd:r};return e.logger.info(`tailing logs via ${l.command} ${l.args.join(" ")}`),{code:(await(e.spawner??S)(l)).code,delegated:!0,descriptor:l}},j=E(async({argument:e,cwd:r,format:a,logger:n,options:t})=>{if(t.durable===!0){const s=await O({cursor:t.cursor,functionPrefix:t.functionPrefix,level:t.level,limit:t.limit,logger:n,minLevel:t.minLevel,namespace:t.namespace,ndjson:t.ndjson===!0,shardKey:t.shardKey,since:t.since,table:t.table,traceId:t.traceId,until:t.until,userId:t.userId});return{...s,...s.rows===void 0?{}:{delegated:!0}}}return x({cwd:r,env:t.env,format:a,logger:n,search:t.search,status:t.status,target:t.target,temporary:t.temporary===!0,worker:e[0]})});export{j as execute,x as runLogsCommand};
|
|
@@ -1,3 +1 @@
|
|
|
1
|
-
import z,{join as m,resolve as I}from"node:path";import{isInteractive as J,promptYesNo as W}from"@lunora/config";import{backupObjectKey as v,isBackupManifestEntry as D,normalizeBackupPrefix as Y,BACKUP_KEY_PREFIX as X,backupManifestKey as Q,isBackupManifestKey as V,backupObjectKeyOfManifest as G}from"@lunora/runtime";import{r as E,t as Z}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{r as A,a as T}from"../packem_shared/admin-url-DJB8P6Jh.mjs";import{d as ee}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as u,isRefusal as p,exitCodeForStatus as k}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{a as re}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{runExportCommand as te}from"../packem_shared/runExportCommand-slAq5BCF.mjs";import{b as ae,l as oe,M as U,u as ne,r as ie}from"../packem_shared/import-BRM1hs7j.mjs";import{readAndLogBody as y}from"./runRpcCommand.mjs";import{randomUUID as j,createHash as se}from"node:crypto";import{existsSync as N,createReadStream as ce,createWriteStream as de}from"node:fs";import{mkdir as ue,rm as b,rename as C,readFile as q,writeFile as le,realpath as _,mkdtemp as x}from"node:fs/promises";import{LunoraError as w}from"@lunora/errors";import{i as R}from"../packem_shared/path-containment-CgxYZggb.mjs";import{tmpdir as O}from"node:os";import{Readable as fe}from"node:stream";import{pipeline as me}from"node:stream/promises";const S="manifest.json",L=async e=>{const t=se("sha256");let r=0;for await(const a of ce(e)){const o=a;r+=o.byteLength,t.update(o)}return{bytes:r,sha256:t.digest("hex")}},P=async e=>{const t=m(e,S);if(!N(t))return[];let r;try{r=JSON.parse(await q(t,"utf8"))}catch(a){const o=a instanceof Error?a.message:String(a);throw new w("INTERNAL",`backup: ${t} exists but is not valid JSON (${o}) — refusing to overwrite it; fix or remove it manually`,{cause:a})}if(!Array.isArray(r))throw new TypeError(`backup: ${t} exists but is not a JSON array — refusing to overwrite it; fix or remove it manually`);return r.filter(a=>D(a))},ge=async(e,t)=>{const r=m(e,`${S}.${j()}.tmp`);try{await le(r,`${JSON.stringify(t,void 0,2)}
|
|
2
|
-
`,"utf8"),await C(r,m(e,S))}catch(a){throw await b(r,{force:!0}),a}},he=async(e,t)=>{const r=I(e),a=I(r,t.file),o=()=>{throw new w("INTERNAL",`backup: entry ${t.id} points outside ${r} (${t.file}) — refusing to read it`)};if(R(r,a)||o(),!!N(a))return R(await _(r),await _(a))||o(),a},we=e=>{const t=r=>v("",r);return{commit:async(r,a)=>{await C(a,m(e,r))},label:e,list:async()=>P(e),locate:t,materialize:async(r,a)=>{const o=i=>i===void 0?void 0:{path:i,release:()=>Promise.resolve()};return o(r===void 0?N(a)?a:void 0:await he(e,r))},record:async r=>{const a=await P(e);a.push(r),await ge(e,a)},stage:async r=>{await ue(e,{recursive:!0});const a=m(e,`${t(r)}.${j()}.partial`);return{path:a,release:()=>b(a,{force:!0})}}}},be="/_lunora/admin/storage/object",ke="/_lunora/admin/storage",B=8,ye=(e,t=z)=>{const r=t.basename(e);return r===""||r==="."||r===".."?"snapshot.ndjson":r},pe=e=>{const{context:t,logger:r}=e,a=Y(e.prefix??X),o=`bucket ${t.bucket??"(default)"} under ${a}`,i=ae(t),n=c=>`${t.baseUrl}${be}?key=${encodeURIComponent(c)}${i}`,f=async c=>{const s=await t.fetchImpl(n(c),{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(!s.ok){const l=await s.text().catch(()=>"<no body>");throw new w("INTERNAL",`backup: could not read ${c} (HTTP ${String(s.status)}): ${l}`)}return s.text()},H=async c=>{try{const s=JSON.parse(await f(c));if(D(s))return s;r.warn(`backup: ignoring ${c} — not a backup manifest`)}catch(s){r.warn(`backup: ignoring ${c} — ${s instanceof Error?s.message:String(s)}`)}};return{commit:async(c,s,l)=>{if(l.bytes>U)throw new w("INTERNAL",`backup: the snapshot is ${String(l.bytes)} bytes, above the ${String(U)}-byte limit for a checksum-verified upload — nothing was written. Narrow it with \`--tables\`, or write it to a directory with \`--dir\` and move the file yourself (\`wrangler r2 object put\`).`);const d=await q(s);await ne(t,c,d,{contentType:"application/x-ndjson",id:c,sha256:l.sha256,size:l.bytes},r)},label:o,list:async()=>{const s=(await oe(t,a)).map(d=>d.key).filter(d=>V(d)),l=[];for(let d=0;d<s.length;d+=B){const g=await Promise.all(s.slice(d,d+B).map(async h=>H(h)));l.push(...g.filter(h=>h!==void 0))}return l.toSorted((d,g)=>d.id.localeCompare(g.id))},locate:c=>v(a,c),materialize:async(c,s)=>{const l=c?.file??s,d=await t.fetchImpl(n(l),{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(d.status===404)return;if(!d.ok||d.body===null){const $=await d.text().catch(()=>"<no body>");throw new w("INTERNAL",`backup: could not download ${l} (HTTP ${String(d.status)}): ${$}`)}const g=await x(m(O(),"lunora-backup-")),h=m(g,ye(l));try{await me(fe.from(d.body),de(h))}catch($){throw await b(g,{force:!0,recursive:!0}),$}return{path:h,release:async()=>b(g,{force:!0,recursive:!0})}},record:async c=>{const s=Q(c.file),l=await t.fetchImpl(`${t.baseUrl}${ke}?key=${encodeURIComponent(s)}${i}`,{body:`${JSON.stringify(c,void 0,2)}
|
|
3
|
-
`,headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json"},method:"PUT"});if(!l.ok){const d=await l.text().catch(()=>"<no body>");throw new w("INTERNAL",`backup: snapshot ${c.file} was written but its manifest was not (HTTP ${String(l.status)}): ${d}`)}},stage:async c=>{const s=await x(m(O(),"lunora-backup-"));return{path:m(s,v("",c)),release:async()=>b(s,{force:!0,recursive:!0})}}}},$e=".lunora-backups",F="/_lunora/admin/backup/retention",ve="/_lunora/admin/backup/prune",Se="/_lunora/admin/pitr",Ee="__lunora_admin__:getPitrBookmark",Ae="__lunora_admin__:pitrRestore",Te=async(e,t)=>{const r=(e.now??(()=>new Date))().toISOString(),a=await t.stage(r);try{const o=await te({cwd:e.cwd,fetchImpl:e.fetchImpl,logger:e.logger,out:a.path,prod:e.prod,tables:e.tables,token:e.token,url:e.url});if(o.code!==0)return{code:o.code};const i=t.locate(r),n=await L(a.path);await t.commit(i,a.path,n);const f={bytes:n.bytes,createdAt:r,file:i,id:r,rows:o.rows,sha256:n.sha256,tables:e.tables};return await t.record(f),e.logger.success(`backup created: ${i} (${o.rows.toString()} rows, ${n.bytes.toString()} bytes)`),{code:0,entry:f}}finally{await a.release().catch(o=>{e.logger.warn(`backup: could not clean up staging (${o instanceof Error?o.message:String(o)})`)})}},Ne=async(e,t,r)=>{if(t?.sha256===void 0)return r.error(t===void 0?"--verify needs a recorded checksum, and a snapshot restored by path/key has no manifest entry — restore it by its backup id instead":`--verify: backup ${t.id} carries no recorded checksum — it was taken by a release before checksums existed`),{code:u.USAGE};const a=await L(e);if(a.sha256!==t.sha256)return r.error(`--verify: ${t.file} does not match its recorded checksum (expected ${t.sha256}, got ${a.sha256}) — nothing was imported`),{code:1};r.success(`verified ${t.file} against its recorded sha256`)},Ie=async(e,t)=>{const r=await t.list();if(r.length===0)return e.logger.info(`no backups found in ${t.label}`),{code:0,entries:[]};for(const a of r)e.logger.info(`${a.id} ${a.rows.toString()} rows ${a.bytes.toString()} bytes ${a.file}`);return{code:0,entries:r}},Ue=async(e,t)=>{const{target:r}=e;if(r===void 0||r.length===0)return e.logger.error("restore requires a backup id or file path. Usage: lunora backup restore <id|file>"),{code:u.USAGE};const o=(await t.list()).find(n=>n.id===r),i=await t.materialize(o,r);if(i===void 0)return e.logger.error(`backup not found: ${r}`),{code:u.NOT_FOUND};try{if(e.verify===!0){const f=await Ne(i.path,o,e.logger);if(f!==void 0)return f}const n=await ie({cwd:e.cwd,fetchImpl:e.fetchImpl,file:i.path,logger:e.logger,prod:e.prod,token:e.token,url:e.url,yes:e.yes});return{code:n.code,entry:o,restored:n.inserted}}finally{await i.release().catch(n=>{e.logger.warn(`backup: could not clean up the downloaded snapshot (${n instanceof Error?n.message:String(n)})`)})}},_e=e=>{if(e.prod&&e.url===void 0)return e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)"),{refused:u.USAGE};if(e.restore===!0&&e.at===void 0&&e.bookmark===void 0)return e.logger.error("pitr --restore requires --at <time> or --bookmark <bookmark>"),{refused:u.USAGE};const t=A(e.url,e.logger,e.cwd);if(t===void 0)return{refused:u.USAGE};if(e.restore===!0&&Z({prod:e.prod,url:t})&&e.yes!==!0)return e.logger.error(`pitr --restore restores data in place at ${t}, which is not local. Re-run with --yes to confirm.`),{refused:u.USAGE};const{token:r}=E({cwd:e.cwd??process.cwd(),token:e.token,url:t});return r?{fetchImpl:e.adminFetch??T,requestUrl:`${t}${Se}`,token:r}:(e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{refused:u.AUTH})},xe=(e,t)=>{const r={};return e.at!==void 0&&(r.time=e.at),t&&e.bookmark!==void 0&&(r.bookmark=e.bookmark),t&&e.restart===!0&&(r.restart=!0),r},Re=async e=>{const t=_e(e);if(p(t))return{code:t.refused};const r=e.restore===!0,a=r?Ae:Ee,o=xe(e,r),i=r?"restore":"bookmark";e.logger.info(`POST ${t.requestUrl} -> pitr ${i}${e.shard===void 0?"":` (shard "${e.shard}")`}`);const n=await t.fetchImpl(t.requestUrl,{body:JSON.stringify({args:o,functionPath:a,shardKey:e.shard}),headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json"},method:"POST"});return{body:await y(n,e.logger),code:n.ok?0:k(n.status)}},Oe=(e,t)=>{if(e.bucket===void 0)return e.prefix!==void 0?(e.logger.error("--prefix applies only to an R2 destination — pass --bucket alongside it, or use --dir to point at a local directory."),{refused:u.USAGE}):we(m(t,e.dir??$e));if(e.dir!==void 0)return e.logger.error("--dir applies only to a local destination and does not apply alongside --bucket — drop one."),{refused:u.USAGE};if(e.prod===!0&&e.url===void 0)return e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)"),{refused:u.USAGE};const r=A(e.url,e.logger,e.cwd);if(r===void 0)return{refused:u.USAGE};const{token:a}=E({cwd:t,token:e.token,url:r});if(!a)return e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{refused:u.AUTH};const o=e.fetchImpl??T;return pe({context:{baseUrl:r,bucket:e.bucket==="default"?void 0:e.bucket,fetchImpl:o,token:a},logger:e.logger,prefix:e.prefix})},M=e=>{const t=[e.bucket===void 0?void 0:"--bucket",e.prefix===void 0?void 0:"--prefix",e.dir===void 0?void 0:"--dir"].filter(i=>i!==void 0);if(t.length>0)return e.logger.error(`${t.join(" / ")} ${t.length===1?"does":"do"} not apply here — retention and prune act on the store the worker itself is configured with (\`backupStore\`), not a destination you name.`),{refused:u.USAGE};if(e.prod===!0&&e.url===void 0)return e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)"),{refused:u.USAGE};const r=A(e.url,e.logger,e.cwd);if(r===void 0)return{refused:u.USAGE};const{token:a}=E({cwd:e.cwd??process.cwd(),token:e.token,url:r});if(!a)return e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{refused:u.AUTH};const o=e.adminFetch??T;return{baseUrl:r,fetchImpl:o,token:a}},K=(e,t)=>{e.logger.info(`backup retention would keep the newest ${t.keep.toString()} of ${t.eligible.toString()} under ${t.prefix} and delete ${t.wouldDelete.length.toString()}`);for(const r of t.wouldDelete)e.logger.info(` ${G(r)}`)},Pe=async e=>{const t=M(e);if(p(t))return{code:t.refused};const r=await t.fetchImpl(`${t.baseUrl}${F}`,{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(!r.ok)return await y(r,e.logger),{code:k(r.status)};const a=await r.json();return a.cron===void 0?(e.logger.info("no scheduled backup is configured (`backupCron`), so retention would delete nothing"),{code:0,preview:a}):a.keep<=0?(e.logger.info(`retention is off for cron "${a.cron}" (\`backupRetain\` unset) — every snapshot under ${a.prefix} is kept`),{code:0,preview:a}):(K(e,a),a.eligible===0&&e.logger.info(`no snapshot under ${a.prefix} was written by this cron, so retention has nothing of its own to remove`),{code:0,preview:a})},Be=(e,t)=>{e.logger.success(`deleted ${t.deleted.length.toString()} backup(s)`);for(const r of t.deleted)e.logger.info(` ${G(r)}`);t.failed.length>0&&e.logger.warn(`${t.failed.length.toString()} could not be removed — the snapshot may be gone with its manifest left behind; run again to retry`),t.ignored>0&&e.logger.info(`${t.ignored.toString()} were already gone by the time the delete ran`),t.remaining>0&&e.logger.info(`${t.remaining.toString()} more are past the window — run \`lunora backup prune\` again`)},De=async e=>{const t=M(e);if(p(t))return{code:t.refused};const r=await t.fetchImpl(`${t.baseUrl}${F}`,{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(!r.ok)return await y(r,e.logger),{code:k(r.status)};const a=await r.json();if(a.keep<=0||a.cron===void 0)return e.logger.error("backup prune needs a retention window: set `backupRetain` (and `backupCron`) on the worker. Without one there is nothing past the window to remove."),{code:u.USAGE,preview:a};if(a.wouldDelete.length===0)return e.logger.info(`nothing to prune — ${a.eligible.toString()} snapshot(s) under ${a.prefix} and retention keeps the newest ${a.keep.toString()}`),{code:0,preview:a};if(K(e,a),e.yes!==!0){const n=e.confirm??(J()?W:void 0);if(n===void 0)return e.logger.error("refusing to delete backups without confirmation — re-run with --yes (there is no undo for an object-store delete)"),{code:u.USAGE,preview:a};if(!await n(`delete ${a.wouldDelete.length.toString()} backup(s)? This cannot be undone. [y/N] `))return e.logger.info("nothing was deleted"),{code:0,preview:a}}const o=await t.fetchImpl(`${t.baseUrl}${ve}`,{body:JSON.stringify({confirm:a.wouldDelete}),headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json"},method:"POST"});if(!o.ok)return await y(o,e.logger),{code:k(o.status),preview:a};const i=await o.json();return Be(e,i),{code:i.failed.length>0?1:0,deleted:i.deleted,preview:a}},Ge=async(e,t)=>{try{if(e.subcommand==="pitr")return await Re(e);if(e.subcommand==="retention")return await Pe(e);if(e.subcommand==="prune")return await De(e);const r=Oe(e,t);return p(r)?{code:r.refused}:e.subcommand==="create"?await Te(e,r):e.subcommand==="list"?await Ie(e,r):await Ue(e,r)}catch(r){return e.logger.error(r instanceof Error?r.message:String(r)),{code:1}}},je=async e=>{const t=e.cwd??process.cwd(),r=await Ge(e,t);return{...r,data:{subcommand:e.subcommand,...r.entries===void 0?{}:{entries:r.entries},...r.entry===void 0?{}:{entry:r.entry},...r.restored===void 0?{}:{restored:r.restored},...r.preview===void 0?{}:{preview:r.preview},...r.deleted===void 0?{}:{deleted:r.deleted},...r.body===void 0?{}:{result:r.body}}}},Ce=e=>e==="create"||e==="list"||e==="pitr"||e==="prune"||e==="restore"||e==="retention",nr=ee(async({argument:e,cwd:t,format:r,logger:a,options:o})=>{const i=e[0];if(!Ce(i)){const f=`backup: unknown subcommand "${i??""}" — expected create | list | restore | retention | prune | pitr`;return a.error(f),{code:u.USAGE,error:f}}const n=await je({at:o.at,bookmark:o.bookmark,bucket:o.bucket,cwd:t,dir:o.dir,format:r,logger:a,prefix:o.prefix,prod:o.prod===!0,restart:o.restart===!0,restore:o.restore===!0,shard:o.shard,subcommand:i,tables:o.tables,target:e[1],token:o.token,url:re({cwd:t,prod:o.prod===!0,url:o.url}),verify:o.verify===!0,yes:o.yes===!0});return{code:n.code,data:n.data,error:n.error}});export{nr as execute,je as runBackupCommand};
|
|
1
|
+
import{existsSync as g,readFileSync as x,realpathSync as b}from"node:fs";import{join as f}from"node:path";import{readServiceBindings as I,readProjectTarget as $,DEFAULT_TARGET as A}from"@lunora/codegen";import{DEV_VARS_FILE as p,parseDevVariableEntries as R,isPlaceholderValue as S,readProjectDependencies as L,discoverSchemaInfo as O,inferLunoraBindings as N,resolveSchemaDirectory as C}from"@lunora/config";import{GLOBAL_FETCH_STRICTLY_PUBLIC_FLAG as m,resolveObservabilitySampling as E,findWranglerFile as D,readWranglerJsonc as P,validateWranglerProject as T,UNEXPORTED_CLASS_MARKER as w,detectCloudflareCliConfig as F,collectExportGaps as U}from"@lunora/config/cloudflare";import{i as G,m as V,c as B,a as M,b as W}from"../packem_shared/secret-key-6bCftsxj.mjs";import{r as K,d as z}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{n as j}from"../packem_shared/cloudflare-credentials-BVmZnDZk.mjs";import{d as H}from"../packem_shared/command-CAXl2A1S.mjs";import{i as J}from"../packem_shared/path-containment-CgxYZggb.mjs";import{A as k,a as y,b as h}from"../packem_shared/variables-CPYyJtsL.mjs";const q=(t,r)=>{const e=new Set,n=s=>{for(const[c,i]of Object.entries(s??{}))typeof i=="string"&&i.trim().length>0&&e.add(c)};n(t.vars);for(const s of Object.values(t.env??{}))n(s.vars);const o=f(r,p);if(g(o))try{n(Object.fromEntries(R(x(o,"utf8")).map(s=>[s.key,s.value])))}catch{}return e},Y=(t,r,e,n)=>{if(t===void 0||!e)return;const o=q(t,r),s=o.has(k),c=t.ai?.binding;!s&&(typeof c!="string"||c.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."}),o.has(y)&&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:`${y} is set, but ctx.ai's Workers AI binding cannot send a gateway token — it is ignored on that path.`}),!s&&!o.has(h)&&n.push({code:"ai-gateway-default",fix:`Run \`lunora cloudflare ai-gateway\` to create a gateway for this app and write ${h} into wrangler vars.`,level:"info",message:`no ${h} in vars or ${p} — \`<provider>/<model>\` slugs route through the account's \`default\` AI Gateway.`})},X=(t,r,e)=>{if(t===void 0||!r)return;const n=[];(t.compatibility_flags??[]).includes(m)||n.push("the top level");for(const[o,s]of Object.entries(t.env??{}))s.compatibility_flags!==void 0&&!s.compatibility_flags.includes(m)&&n.push(`env.${o}`);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.`})},_=t=>{const{logs:r,traces:e}=E(t);return Object.entries({logs:r,traces:e}).filter(([,n])=>n.enabled&&n.headSamplingRate>=1).map(([n])=>n)},Q=(t,r)=>{if(t===void 0)return;const e=[],n=_(t.observability);n.length>0&&e.push(`${n.join(" + ")} (top level)`);for(const[o,s]of Object.entries(t.env??{})){if(s.observability===void 0)continue;const c=_(s.observability);c.length>0&&e.push(`${c.join(" + ")} (env.${o})`)}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=(t,r)=>{for(const e of I(t).services)for(const n of e.publicScopes){const o=n===""?"":` (env.${n})`;r.push({code:"service-workers-dev",fix:`If ${e.name} has no public route (custom domain or route, including ones set outside ${e.wranglerPath}), set \`"workers_dev": false\`${o}. Keep its internal auth (HMAC) either way.`,level:"warn",message:`service ${e.name} (${e.worker}) has no route in its wrangler config and still serves on workers.dev${o}; a custom domain set elsewhere would also be public.`})}},ee=t=>{const r=t.trim();if(r==="")return!0;const e=r.toLowerCase();return e.includes("replace")||e.startsWith("<")&&e.endsWith(">")},ne=t=>{const r=D(t);if(r===void 0)return{parsed:void 0,path:void 0};const{parsed:e}=P(r);return{parsed:e,path:r}},re=(t,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:o}=T({projectRoot:t});for(const i of o.errors.filter(a=>a.includes(w)))n.push({code:"wrangler-class-unexported",level:"fail",message:i});for(const i of o.warnings.filter(a=>a.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(w)||i.includes("SHARD");for(const i of o.errors.filter(a=>!s(a)))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 o.warnings.filter(a=>!a.includes("LUNORA_ORIGIN_URL")))n.push({code:"wrangler-advisory",level:"warn",message:i});const c=o.errors.find(i=>i.includes("SHARD"));c===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:c})},te=(t,r)=>{g(f(t,"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."})},oe=(t,r)=>{const e=F(t);e!==void 0&&r.push({code:"cf-config-present",fix:e.fix,level:"warn",message:e.message})},se=(t,r)=>{t===void 0||t.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."})},ae=(t,r)=>{const e=(t?.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.`})},ie=(t,r)=>{const{error:e,info:n}=O(t,"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 o of n?.vectorMetadata??[]){const s=V(o.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 "${o.index}" declares metadata "${o.property}", whose type Vectorize cannot filter on.`});continue}r.push({code:"vector-metadata-index-required",fix:`wrangler ${B({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).`})}},ce=(t,r)=>{if(t===void 0)return;const e=(t.d1_databases??[]).filter(Boolean);for(const n of e){const o=typeof n.database_id=="string"?n.database_id:"";if(ee(o)){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 ("${o||"<empty>"}").`})}}},le=(t,r)=>{if(t===void 0)return;const e=(t.send_email??[]).filter(Boolean);for(const n of e){const o=typeof n.destination_address=="string"?n.destination_address:"";if(o!==""&&S(o)){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 ("${o}").`})}}},de=(t,r)=>{const e=f(t,p);if(!g(e))return;let n;try{n=x(e,"utf8")}catch{return}const o=R(n).filter(s=>G(s.key)&&S(s.value)).map(s=>s.key);o.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:`${p} has unfilled secret value(s): ${o.join(", ")}.`})},ue=(t,r)=>{const{source:e}=K({cwd:t});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 (${z(e)}).`})},fe=async(t,r)=>{try{return await N({projectRoot:t,schemaDir:C(t)})}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}},me=(t,r)=>{const e=U(t),n=[...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 n.filter(s=>s.exported))r.push({code:"declared-export-ok",level:"pass",message:`${o.kind} "${o.exportName}" is exported by the worker entry.`});for(const o of e)r.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.`})},pe=/^[\^~><= ]+/u,ge=/^(?<core>\d+\.\d+\.\d+)(?:-(?<channel>[a-z]+)\.(?<counter>\d+))?$/u,he=t=>{const r=t.replace(pe,"").trim(),e=ge.exec(r);if(!e?.groups)return;const{channel:n,core:o,counter:s}=e.groups;return{channel:n??"",core:o??"",counter:s===void 0?void 0:Number.parseInt(s,10),raw:r}},ve=(t,r)=>{const e=L(t),n=[];for(const[a,l]of Object.entries(e)){if(a!=="lunorash"&&!a.startsWith("@lunora/"))continue;const d=he(l);d&&n.push({name:a,version:d})}if(n.length<2)return;const o=a=>a.map(l=>`${l.name}@${l.version.raw}`).join(", "),s=new Set(n.map(a=>a.version.core)),c=new Set(n.map(a=>a.version.channel));if(s.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(s.size)} different versions: ${o(n)}.`});return}if(c.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 (${[...c].map(a=>a===""?"stable":a).join(" + ")}): ${o(n)}.`});return}const i=n.map(a=>a.version.counter).filter(a=>a!==void 0);if(i.length>1){const a=Math.min(...i),l=Math.max(...i);r.push({code:"version-counter-spread",level:"info",message:i.length===n.length&&a===l?`Lunora packages are all at ${[...c][0]??""}.${String(l)}.`:`Lunora pre-release counters span ${String(a)}–${String(l)}: ${o(n)}.`})}},be=[f("@lunora","cli"),"lunorash"],we=(t,r,e)=>{if(r===void 0)return;const n=[];for(const s of be){const c=f(t,"node_modules",s);if(g(c))try{n.push(b(c))}catch{}}if(n.length===0)return;let o;try{o=b(r)}catch{return}n.some(s=>J(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 (${n.join(", ")}).`})},ke={full:{code:"do-class-budget-full",level:"warn"},near:{code:"do-class-budget-near",level:"warn"},ok:{code:"do-class-budget-ok",level:"pass"},unchecked:{code:"do-class-budget-unchecked",level:"info"}},ye=t=>{const r=new Map,e=(n,o)=>{const s=j(n);s!==void 0&&r.set(s,[...r.get(s)??[],o])};e(t?.account_id,"top level");for(const[n,o]of Object.entries(t?.env??{}))e(o?.account_id,`env.${n}`);return r},_e=async(t,r,e,n)=>{if(($(t)??A)!=="cloudflare")return;const s=j((e.environment??process.env).CLOUDFLARE_ACCOUNT_ID)!==void 0?[]:[...ye(r)],c=s.length===0?[[void 0,[]]]:s,i=await Promise.all(c.map(async([a,l])=>({accountId:a,blocks:l,budget:await M({accountId:a,environment:e.environment,fetch:e.fetch})})));for(const{accountId:a,blocks:l,budget:d}of i)n.push({...ke[d.verdict],message:i.length>1?`account ${String(a)} (${l.join(", ")}): ${d.message}`:d.message,...d.fix===void 0?{}:{fix:d.fix}})},xe={mismatch:{code:"artifacts-jurisdiction-mismatch",level:"fail"},missing:{code:"artifacts-namespace-missing",level:"fail"},ok:{code:"artifacts-jurisdiction-ok",level:"pass"},unchecked:{code:"artifacts-jurisdiction-unchecked",level:"warn"}},$e=async(t,r,e,n,o)=>{if(e===void 0||r===void 0||($(t)??A)!=="cloudflare")return;const s=[["",r],...Object.entries(r.env??{}).map(([a,l])=>[`env.${a}: `,l])],c=new Map;for(const[a,l]of s){const d=l.account_id??r.account_id;for(const u of l.artifacts??[]){const v=`${String(d)}/${String(u?.namespace)}`;typeof u?.binding=="string"&&typeof u.namespace=="string"&&!c.has(v)&&c.set(v,{accountId:d,binding:u.binding,label:a,namespace:u.namespace})}}const i=await Promise.all([...c.values()].map(async({label:a,...l})=>({check:await W({...l,environment:n.environment,fetch:n.fetch,jurisdiction:e}),label:a})));for(const{check:a,label:l}of i)o.push({...xe[a.verdict],message:`${l}${a.message}`,...a.fix===void 0?{}:{fix:a.fix}})},Ae=async t=>{const r=t.cwd??process.cwd(),e=[],{parsed:n,path:o}=ne(r);re(r,n,o,e),oe(r,e),ce(n,e),le(n,e),se(n,e),ae(n,e),Q(n,e),de(r,e),ue(r,e),ve(r,e),ie(r,e),te(r,e),we(r,t.executablePath??process.argv[1],e),Z(r,e);const s=await fe(r,e);s!==void 0&&me(s,e),Y(n,r,s?.usesAi===!0,e),await _e(r,n,t,e),await $e(r,n,s?.jurisdiction,t,e),X(n,s?.usesCimdWorkers===!0,e);const c={fail:0,info:0,pass:0,warn:0};for(const a of e)c[a.level]+=1;const i=c.fail>0?1:0;return{code:i,findings:e,ok:i===0,summary:c}},Re={fail:"FAIL",info:"INFO",pass:"PASS",warn:"WARN"},Se=(t,r)=>{r.info("lunora doctor — project preflight");for(const o of t.findings){const s=`[${Re[o.level]}] ${o.message}`;o.level==="fail"?r.error(s):o.level==="warn"?r.warn(s):r.info(s),o.fix!==void 0&&o.level!=="pass"&&r.info(` fix: ${o.fix}`)}const{fail:e,warn:n}=t.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.")},je=async t=>{const{logger:r}=t,e=await Ae({...t});return Se(e,r),e},Ge=H(async({cwd:t,format:r,logger:e})=>{const n=await je({cwd:t,format:r,logger:e});return{code:n.code,data:{findings:n.findings,summary:n.summary}}});export{Ge as execute,Ae as runDoctor,je as runDoctorCommand};
|