@lunora/cli 1.0.0-alpha.324 → 1.0.0-alpha.326
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 +21 -19
- package/dist/index.d.ts +21 -19
- package/dist/index.mjs +1 -1
- package/dist/packem_chunks/dispatch.mjs +1 -1
- package/dist/packem_chunks/handler.mjs +1 -1
- package/dist/packem_chunks/handler10.mjs +1 -1
- package/dist/packem_chunks/handler11.mjs +1 -1
- package/dist/packem_chunks/handler12.mjs +1 -1
- package/dist/packem_chunks/handler13.mjs +1 -1
- package/dist/packem_chunks/handler14.mjs +1 -1
- package/dist/packem_chunks/handler15.mjs +1 -1
- package/dist/packem_chunks/handler16.mjs +1 -1
- package/dist/packem_chunks/handler17.mjs +1 -1
- package/dist/packem_chunks/handler18.mjs +1 -1
- package/dist/packem_chunks/handler19.mjs +1 -1
- package/dist/packem_chunks/handler2.mjs +1 -1
- package/dist/packem_chunks/handler20.mjs +1 -1
- package/dist/packem_chunks/handler21.mjs +1 -1
- package/dist/packem_chunks/handler22.mjs +1 -1
- package/dist/packem_chunks/handler23.mjs +1 -1
- package/dist/packem_chunks/handler24.mjs +2 -2
- package/dist/packem_chunks/handler25.mjs +1 -1
- package/dist/packem_chunks/handler26.mjs +1 -1
- package/dist/packem_chunks/handler3.mjs +1 -1
- package/dist/packem_chunks/handler4.mjs +1 -1
- package/dist/packem_chunks/handler5.mjs +1 -1
- package/dist/packem_chunks/handler6.mjs +1 -1
- package/dist/packem_chunks/handler7.mjs +3 -3
- package/dist/packem_chunks/handler8.mjs +1 -1
- package/dist/packem_chunks/handler9.mjs +1 -1
- package/dist/packem_chunks/runCodegenCommand.mjs +1 -1
- package/dist/packem_chunks/runDeployCommand.mjs +3 -3
- package/dist/packem_chunks/runDevCommand.mjs +3 -0
- package/dist/packem_chunks/runInitCommand.mjs +17 -17
- package/dist/packem_chunks/runResetCommand.mjs +1 -1
- package/dist/packem_chunks/runRpcCommand.mjs +1 -1
- package/dist/packem_shared/COMMANDS-Cax5U9fX.mjs +1 -0
- package/dist/packem_shared/cli-D1ZleZMH.mjs +2 -0
- package/dist/packem_shared/command-B--jgXSc.mjs +1 -0
- package/dist/packem_shared/health-probe-Bw9JFfIy.mjs +1 -0
- package/dist/packem_shared/output-format-B4eQHi5y.mjs +2 -0
- package/dist/packem_shared/plan-B-KsxVne.mjs +5 -0
- package/dist/packem_shared/planDevCommand-BuJZzy-L.mjs +1 -0
- package/dist/packem_shared/render-lunora-error-DgaSmNLc.mjs +2 -0
- package/dist/packem_shared/secret-key-DsMeUoEg.mjs +1 -0
- package/dist/packem_shared/wrangler-secrets-CuUdFBaA.mjs +1 -0
- package/package.json +9 -9
- package/skills/lunora-quickstart/SKILL.md +15 -13
- package/dist/packem_chunks/planDevCommand.mjs +0 -7
- package/dist/packem_shared/COMMANDS-DdaAWPtr.mjs +0 -1
- package/dist/packem_shared/cli-DOpChqUe.mjs +0 -2
- package/dist/packem_shared/command-Mmxzxyr5.mjs +0 -1
- package/dist/packem_shared/render-lunora-error--4tmM6mt.mjs +0 -3
- package/dist/packem_shared/schema-drift-gate-BDCkQ1S6.mjs +0 -1
- package/dist/packem_shared/vectorize-metadata-dXpl2_Ar.mjs +0 -1
- package/dist/packem_shared/wrangler-secrets-C9lJnd5N.mjs +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{existsSync as m,mkdirSync as M,writeFileSync as w,readFileSync as
|
|
1
|
+
import{existsSync as m,mkdirSync as M,writeFileSync as w,readFileSync as x,readdirSync as ce,rmSync as T,lstatSync as de,mkdtempSync as ue,copyFileSync as Ge,renameSync as Ye}from"node:fs";import{tmpdir as pe}from"node:os";import{installArgsFor as he,execArgsFor as Je,detectFramework as Xe,isInteractive as y,LUNA_ART as Qe,LUNA_NAME as Ze,LUNA_SIGNOFF as et,BADGES as v,paintAnswer as tt,detectPackageManager as P,detectInstalledManagers as rt,runScriptCommand as at,detectLintTools as ot,addArgsFor as nt,applyLintIgnores as st}from"@lunora/config";import{walkSync as it}from"@visulima/fs";import{join as p,dirname as A,basename as _,resolve as me,relative as fe}from"@visulima/path";import{downloadTemplate as ge}from"giget";import{modify as lt,applyEdits as ct}from"jsonc-parser";import{join as K,dirname as dt}from"node:path";import{d as ut}from"../packem_shared/command-B--jgXSc.mjs";import{EXIT_CODE as f}from"../packem_shared/EXIT_CODE-08cwt3MK.mjs";import pt from"magic-string";import{Project as ht,SyntaxKind as g}from"ts-morph";import{P as q}from"../packem_shared/prompt-cancelled-BvsNxg_Q.mjs";import{m as ve,n as mt,o as we,q as ye,b as ft}from"../packem_shared/resolve-DUCSc7jQ.mjs";import{defaultSpawner as be}from"../packem_shared/createRecordingSpawner-sS7LEN7x.mjs";import{d as gt,e as vt,f as wt,a as ke,t as G,g as xe,h as yt,b as Ce,i as Se,w as bt,j as kt,k as Le,l as xt}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{A as Me,E as Ae,p as Ct,w as St,M as Lt,r as Mt,k as At,e as Et,c as Ee,l as Ne,i as Nt,f as _t}from"../packem_shared/storage-J4xhM4FU.mjs";import{r as It}from"../packem_shared/commands-CNqednoX.mjs";import{logStep as Q}from"../packem_shared/createLogger-Cl18I8AX.mjs";import{r as Rt}from"../packem_shared/lint-ignore-report-DKZagpqk.mjs";import $t from"node:dns/promises";const Y={bun:{githubCacheKey:void 0,githubSetupStep:` - uses: oven-sh/setup-bun@v2
|
|
2
2
|
`,gitlabImage:"oven/bun:1",gitlabProvisionScript:[],installCmd:"bun install --frozen-lockfile",lockfile:"bun.lockb"},npm:{githubCacheKey:"npm",githubSetupStep:"",gitlabImage:"node:22",gitlabProvisionScript:[],installCmd:"npm ci",lockfile:"package-lock.json"},pnpm:{githubCacheKey:"pnpm",githubSetupStep:` - uses: pnpm/action-setup@v4
|
|
3
3
|
with:
|
|
4
4
|
version: latest
|
|
@@ -7,7 +7,7 @@ ${e.githubSetupStep} - uses: actions/setup-node@v4
|
|
|
7
7
|
with:
|
|
8
8
|
node-version: 22
|
|
9
9
|
${e.githubCacheKey===void 0?"":` cache: ${e.githubCacheKey}
|
|
10
|
-
`} - run: ${e.installCmd}`,
|
|
10
|
+
`} - run: ${e.installCmd}`,Tt=e=>{const t=Y[e],r=t.githubCacheKey===void 0?`# (below) requires it — run \`${e} install\` locally and`:`# (below) and the ${e} cache both require it — run \`${e} install\` locally and`;return`name: Deploy
|
|
11
11
|
|
|
12
12
|
on:
|
|
13
13
|
push:
|
|
@@ -49,7 +49,7 @@ ${Z(t)}
|
|
|
49
49
|
steps:
|
|
50
50
|
${Z(t)}
|
|
51
51
|
- run: ${L(e,["deploy","--preview"])}
|
|
52
|
-
`},
|
|
52
|
+
`},Ot=e=>{const t=Y[e],r=[...t.gitlabProvisionScript,t.installCmd].map(a=>` - ${a}`).join(`
|
|
53
53
|
`);return`stages:
|
|
54
54
|
- deploy
|
|
55
55
|
|
|
@@ -84,16 +84,16 @@ preview:
|
|
|
84
84
|
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
|
|
85
85
|
script:
|
|
86
86
|
- ${L(e,["deploy","--preview"])}
|
|
87
|
-
`},_e={github:{file:K(".github","workflows","deploy.yml"),secretsHint:"repository secrets (Settings → Secrets and variables → Actions)"},gitlab:{file:".gitlab-ci.yml",secretsHint:"masked CI/CD variables (Settings → CI/CD → Variables)"}},Pt=(e,t)=>e==="github"?
|
|
87
|
+
`},_e={github:{file:K(".github","workflows","deploy.yml"),secretsHint:"repository secrets (Settings → Secrets and variables → Actions)"},gitlab:{file:".gitlab-ci.yml",secretsHint:"masked CI/CD variables (Settings → CI/CD → Variables)"}},Pt=(e,t)=>e==="github"?Tt(t):Ot(t),Dt=e=>e==="github"||e==="gitlab",Bt=(e,t,r,a={})=>{const o=K(e,_e[t].file);return m(o)&&a.overwrite!==!0?{path:o,skipped:!0,written:!1}:(M(dt(o),{recursive:!0}),w(o,Pt(t,r),"utf8"),{path:o,skipped:!1,written:!0})},jt=(e,t,r,a,o={})=>{const n=_e[t];try{const s=Bt(e,t,r,o);if(s.skipped)a.info(`--ci ${t}: ${n.file} already exists — left unchanged (re-run with overwrite to replace).`);else{const i=he(r),l=[i.command,...i.args].join(" "),{installCmd:c,lockfile:u}=Y[r];a.success(`--ci ${t}: wrote ${n.file}`),a.info(`--ci ${t}: set CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID as ${n.secretsHint} to enable deploys.`),a.info(`--ci ${t}: run \`${l}\` and commit ${u} before pushing — the pipeline runs \`${c}\`.`)}return s}catch(s){const i=s instanceof Error?s.message:String(s);return a.warn(`--ci ${t}: could not write ${n.file} (${i})`),{path:K(e,n.file),skipped:!1,written:!1}}},Ut={astro:"@lunora/react",none:"@lunora/react",nuxt:"@lunora/vue","react-router":"@lunora/react","solid-start":"@lunora/solid",sveltekit:"@lunora/svelte","tanstack-start":"@lunora/react","tanstack-start-solid":"@lunora/solid",vinext:"@lunora/react"},Vt=e=>{const t=Xe(e);return{...t,adapter:Ut[t.framework]}},$="lunora()",ee='import { lunora } from "@lunora/vite";',Ft="@lunora/vite",Wt="lunora",Ht=e=>{for(const t of e.getStatements()){if(t.getKind()!==g.ExportAssignment)continue;const r=t.asKindOrThrow(g.ExportAssignment).getExpression();if(r.getKind()!==g.CallExpression)continue;const a=r.asKindOrThrow(g.CallExpression);if(a.getExpression().getText()!=="defineConfig")continue;const o=a.getArguments()[0];if(o?.getKind()===g.ObjectLiteralExpression)return o.asKindOrThrow(g.ObjectLiteralExpression)}},zt=e=>{for(const t of e.getStatements()){if(t.getKind()!==g.ExportAssignment)continue;const r=t.asKindOrThrow(g.ExportAssignment).getExpression();if(r.getKind()===g.ObjectLiteralExpression)return r.asKindOrThrow(g.ObjectLiteralExpression)}},Kt=e=>e.getDescendantsOfKind(g.CallExpression).some(t=>t.getExpression().getText()===Wt),qt=e=>e.getImportDeclarations().some(t=>t.getModuleSpecifierValue()===Ft),Gt=e=>new ht({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}).createSourceFile("vite.config.ts",e,{overwrite:!0}),Yt=(e,t)=>{const r=t.getImportDeclarations().at(-1)?.getEnd()??0;r===0?e.prepend(`${ee}
|
|
88
88
|
`):e.appendLeft(r,`
|
|
89
|
-
${ee}`)},Jt=(e,t)=>{const r=t.getProperty("plugins");if(r===void 0){const s=t.getProperties(),i=t.getStart()+1;if(s.length===0){e.appendLeft(i,` plugins: [${
|
|
90
|
-
`);return}const a=r.getDescendantsOfKind(g.ArrayLiteralExpression)[0];if(a===void 0)return"the Vite config's `plugins` is not an array literal — add `lunora()` to it by hand";const o=a.getElements();if(o.length===0){e.appendLeft(a.getStart()+1
|
|
89
|
+
${ee}`)},Jt=(e,t)=>{const r=t.getProperty("plugins");if(r===void 0){const s=t.getProperties(),i=t.getStart()+1;if(s.length===0){e.appendLeft(i,` plugins: [${$}] `);return}const l=s[0];if(l===void 0)return"could not locate the start of the Vite config object's first property";e.appendLeft(l.getStart(),`plugins: [${$}],
|
|
90
|
+
`);return}const a=r.getDescendantsOfKind(g.ArrayLiteralExpression)[0];if(a===void 0)return"the Vite config's `plugins` is not an array literal — add `lunora()` to it by hand";const o=a.getElements();if(o.length===0){e.appendLeft(a.getStart()+1,$);return}const n=o[0];if(n===void 0)return"could not locate the first entry of the Vite config's `plugins` array";e.appendLeft(n.getStart(),`${$}, `)},Ie=e=>{const t=Gt(e);if(Kt(t))return{changed:!1,code:e,reason:"lunora plugin already present"};const r=Ht(t)??zt(t);if(r===void 0)return{changed:!1,code:e,reason:"could not locate a Vite config plugins array to patch"};const a=new pt(e);qt(t)||Yt(a,t);const o=Jt(a,r);return o!==void 0?{changed:!1,code:e,reason:o}:{changed:!0,code:a.toString()}},Xt=/enotfound|eai_again|econnrefused|etimedout|network|fetch failed|getaddrinfo/u,Qt=/404|not found|could not find|no such/u,Zt=(e,t)=>{const r=e instanceof Error?e.message:String(e),a=r.toLowerCase(),o=`failed to download template "${t.templateType}" from ${t.remote}: ${r}`;return Qt.test(a)?{hints:[`Check the template name "${t.templateType}" and the ref "${t.ref}".`,"List/inspect available templates, or target a branch/tag with `--ref <branch>`."],message:`template "${t.templateType}" not found at ${t.remote}: ${r}`}:Xt.test(a)?{hints:["You appear to be offline or unable to reach GitHub.","To scaffold without a network, point at a local template root: `lunora init --from <dir>`."],message:o}:{hints:["If this is a network/offline issue, scaffold from a local root with `lunora init --from <dir>`."],message:o}},O=async(e,t,r)=>{if(y()){await vt(v[e],t,r);return}if(process.stdout.write(`
|
|
91
91
|
`),r===void 0||r===""){Q(e,t);return}const a=r.split(`
|
|
92
92
|
`).map(o=>tt(o)).join(`
|
|
93
93
|
`);Q(e,`${t}
|
|
94
94
|
${a}`)},er=async e=>{if(y()){await gt();return}e.info(`
|
|
95
95
|
${Qe}
|
|
96
|
-
${Ze}: ${et}`)}
|
|
96
|
+
${Ze}: ${et}`)},Re=[{description:"LLMs via Workers AI (summarize, generate, stream)",label:"AI",value:"ai"},{description:"Sign-up / sign-in (asks which provider)",label:"Authentication",value:"auth"},{description:"Copy-in auth screens for your framework (sign in/up, reset, 2FA)",label:"Auth UI",value:"auth-ui"},{description:"Snapshot + restore your Durable Object data",label:"Backups",value:"backup"},{description:"Headless browser screenshots + PDFs",label:"Browser rendering",value:"browser"},{description:"Zero Trust identity via Cloudflare Access",label:"Cloudflare Access",value:"cloudflare-access"},{description:"Scheduled jobs via Cron Triggers (@lunora/scheduler)",label:"Cron jobs",value:"crons"},{description:"Cloudflare Email Workers + a dev mail catcher",label:"Transactional email",value:"email"},{description:"OpenFeature feature flags (ctx.flags)",label:"Feature flags",value:"flags"},{description:"External Postgres/MySQL via Hyperdrive",label:"Hyperdrive",value:"hyperdrive"},{description:"Stripe-first payments (checkout, subscription, webhooks)",label:"Payments",value:"payment"},{description:"Live presence / who's-online over hibernated WebSockets",label:"Presence",value:"presence"},{description:"Async message queues (push/pull consumers)",label:"Queues",value:"queue"},{description:"Typed R2 buckets + signed URLs (@lunora/storage)",label:"File storage",value:"storage"},{description:"Durable long-running workflows (step.do, sleep, branch)",label:"Workflows",value:"workflow"}],te=Re.map(e=>e.value),tr=e=>e==="email"?Ae:e,rr=(e,t)=>{const r=[];for(const a of e.split(",").map(o=>o.trim()).filter(Boolean))te.includes(a)?r.includes(a)||r.push(a):t(`init: unknown --add feature "${a}" — expected ${te.join(" | ")}; skipping.`);return r},$e=e=>e.resolveAuthUiItem===void 0?"auth-ui-react":e.resolveAuthUiItem(),ar=async e=>{const t=await Et(e.select),r=await Ee(e.text,e.projectName);return{label:"auth",names:[t],transformManifest:a=>Ne(a,r)}},or=async e=>{const t=await e.text(Lt,{placeholder:"you@yourdomain.com"}),r=Mt(t,a=>{e.logger.warn(a)});return{label:"email",names:[Ae],transformManifest:r===void 0?void 0:a=>At(a,r)}},nr=async(e,t)=>{const r=$e(e);if(r===void 0){e.logger.error(`init: ${Me}`);return}if(t)return{label:"auth-ui",names:[r]};const a=await Ee(e.text,e.projectName);return{label:"auth-ui",names:[r],transformManifest:o=>Ne(o,a)}},sr=async e=>{const t=await Ct(e.text,e.projectName);return{label:"storage",names:["storage"],transformManifest:r=>St(r,t)}},ir=(e,t)=>{const r=[];let a=!1;for(const o of t){if(o!=="auth-ui"){r.push({label:o,names:[tr(o)]});continue}const n=$e(e);if(n===void 0){e.logger.error(`init: ${Me}`),a=!0;continue}r.push({label:o,names:[n]})}return{plans:r,refused:a}},lr={auth:ar,"auth-ui":async(e,t)=>nr(e,t.includes("auth")),email:or,storage:sr},re=async e=>{if(e.preselected!==void 0&&e.preselected.length>0){const{plans:a,refused:o}=ir(e,e.preselected);return await e.applyAll(a)&&!o}if(!e.interactive)return e.logger.info("tip: add features later with `lunora add <ai|auth|backup|browser|cloudflare-access|crons|email|flags|hyperdrive|payment|presence|queue|storage|workflow>`."),!0;const t=await e.multiSelect("Which features do you want to add?",Re,{defaults:[]});if(t.length===0)return!0;const r=[];for(const a of t){const o=lr[a],n=o?await o(e,t):{label:a,names:[a]};n!==void 0&&r.push(n)}return await e.applyAll(r),!0},cr=[{description:"Adds an ignores entry to eslint.config.js",label:"ESLint",value:"eslint"},{description:"Writes .prettierignore",label:"Prettier",value:"prettier"},{description:"Adds negated patterns to biome.json",label:"Biome",value:"biome"},{description:"Writes ignorePatterns to .oxlintrc.json",label:"oxlint (oxc)",value:"oxlint"}],dr="Which linter/formatter do you use? We'll tell it to skip Lunora's generated files.",ur=async e=>{const t=e.interactive?await e.multiSelect(dr,cr,{defaults:e.detected}):[...e.detected];if(t.length===0)return[];const r=e.apply(t);return Rt(r,e.logger),r},I="M 259.500 10.552 C 220.080 15.859, 182.424 32.566, 152.500 58.025 C 110.179 94.031, 85.380 137.183, 77.518 188.500 C 75.410 202.255, 74.569 225.677, 75.796 236.466 C 76.757 244.917, 76.683 245.692, 74.518 249.966 C 63.118 272.466, 53.141 303.876, 51.382 322.799 L 50.718 329.943 71.960 320.471 C 83.643 315.262, 93.326 311, 93.478 311 C 93.630 311, 96.547 316.063, 99.959 322.250 C 103.371 328.438, 107.249 334.850, 108.577 336.500 L 110.990 339.500 110.981 336 C 110.977 334.075, 111.499 324.991, 112.143 315.813 L 113.312 299.127 121.406 293.336 C 132.495 285.403, 149.593 271.554, 161 261.268 C 171.556 251.748, 189.116 235, 188.540 235 C 188.337 235, 183.069 238.648, 176.835 243.106 C 142.318 267.789, 68.537 314, 63.646 314 C 61.843 314, 72.791 281.179, 80.905 262.259 C 92.233 235.845, 107.473 212.389, 132.106 183.453 L 138.451 176 148.268 176 C 176.192 176, 197.512 187.154, 212.868 209.797 C 216.470 215.108, 217.035 216.595, 216.477 219.297 C 211.386 243.968, 202.359 274.496, 193.797 296 C 183.898 320.861, 167.147 352.101, 152.395 373.215 L 147.004 380.930 152.891 385.830 C 161.400 392.911, 165.563 396, 166.594 395.998 C 167.092 395.998, 168.772 391.641, 170.327 386.317 C 176.279 365.934, 188.422 338.749, 200.942 317.778 C 223.060 280.731, 256.432 244.369, 294.500 215.836 C 309.956 204.252, 313.937 201.603, 314.719 202.385 C 315.116 202.783, 315.449 213.096, 315.460 225.304 C 315.474 241.855, 315.021 250.405, 313.680 258.924 C 307.009 301.272, 291.175 336.677, 263.112 372 C 255.259 381.883, 227.182 410.673, 218.516 417.727 L 213.532 421.783 223.439 424.880 C 281.705 443.093, 349.165 436.018, 398.616 406.508 C 446.728 377.797, 483.322 331.466, 497.366 281.481 C 503.381 260.075, 504.480 250.741, 504.491 221 C 504.501 191.997, 503.598 184.047, 497.987 163.732 C 484.768 115.871, 452.505 72.708, 407.718 42.964 C 381.051 25.254, 352.818 14.828, 319.695 10.460 C 305.932 8.645, 273.298 8.695, 259.500 10.552",N=`/* The welcome page is a full-bleed starter — reset the browser's default
|
|
97
97
|
body margin/padding so it sits flush; everything else is scoped under
|
|
98
98
|
.lunora-welcome (collision-safe). */
|
|
99
99
|
body {
|
|
@@ -1069,7 +1069,7 @@ render(
|
|
|
1069
1069
|
<\/script>
|
|
1070
1070
|
|
|
1071
1071
|
<App />
|
|
1072
|
-
`,
|
|
1072
|
+
`,kr=`import "./app.css";
|
|
1073
1073
|
|
|
1074
1074
|
import { mount } from "svelte";
|
|
1075
1075
|
|
|
@@ -1079,7 +1079,7 @@ import Root from "./Root.svelte";
|
|
|
1079
1079
|
const app = mount(Root, { target: document.getElementById("app")! });
|
|
1080
1080
|
|
|
1081
1081
|
export default app;
|
|
1082
|
-
`,B={react:{adapter:"@lunora/react",createViteTemplate:"react-ts",files:[{contents:vr,path:"src/main.tsx"},{contents:pr,path:"src/App.tsx"},{contents:N,path:"src/index.css"}],label:"React"},solid:{adapter:"@lunora/solid",createViteTemplate:"solid-ts",files:[{contents:yr,path:"src/index.tsx"},{contents:mr,path:"src/App.tsx"},{contents:N,path:"src/index.css"}],label:"Solid"},svelte:{adapter:"@lunora/svelte",createViteTemplate:"svelte-ts",files:[{contents:br,path:"src/Root.svelte"},{contents:
|
|
1082
|
+
`,B={react:{adapter:"@lunora/react",createViteTemplate:"react-ts",files:[{contents:vr,path:"src/main.tsx"},{contents:pr,path:"src/App.tsx"},{contents:N,path:"src/index.css"}],label:"React"},solid:{adapter:"@lunora/solid",createViteTemplate:"solid-ts",files:[{contents:yr,path:"src/index.tsx"},{contents:mr,path:"src/App.tsx"},{contents:N,path:"src/index.css"}],label:"Solid"},svelte:{adapter:"@lunora/svelte",createViteTemplate:"svelte-ts",files:[{contents:br,path:"src/Root.svelte"},{contents:kr,path:"src/main.ts"},{contents:fr,path:"src/App.svelte"},{contents:N,path:"src/app.css"}],label:"Svelte"},vanilla:{adapter:"lunorash/client",createViteTemplate:"vanilla-ts",files:[{contents:gr,path:"src/main.ts"},{contents:N,path:"src/style.css"}],label:"Vanilla"},vue:{adapter:"@lunora/vue",createViteTemplate:"vue-ts",files:[{contents:wr,path:"src/main.ts"},{contents:hr,path:"src/App.vue"},{contents:N,path:"src/style.css"}],label:"Vue"}},j=e=>Object.hasOwn(B,e),xr=`/**
|
|
1083
1083
|
* Rate-limit schema extension + plugin.
|
|
1084
1084
|
*
|
|
1085
1085
|
* Defines the \`ratelimit_buckets\` table used by \`createDbStore\` for durable,
|
|
@@ -1222,14 +1222,14 @@ export default app;
|
|
|
1222
1222
|
# Leave it unset to use the page origin; set it to point at a deployed Worker:
|
|
1223
1223
|
#
|
|
1224
1224
|
# VITE_LUNORA_URL=https://my-app.example.workers.dev
|
|
1225
|
-
`,Er={"@cloudflare/workers-types":"^4.20260611.1",wrangler:"^4.100.0"},C=(e,t,r,a)=>{const o=p(e,t);M(A(o),{recursive:!0}),w(o,r,"utf8"),a.push(o)},Nr=/\r?\n/,_r=e=>{const t=p(e,".gitignore"),r=m(t)?
|
|
1225
|
+
`,Er={"@cloudflare/workers-types":"^4.20260611.1",wrangler:"^4.100.0"},C=(e,t,r,a)=>{const o=p(e,t);M(A(o),{recursive:!0}),w(o,r,"utf8"),a.push(o)},Nr=/\r?\n/,_r=e=>{const t=p(e,".gitignore"),r=m(t)?x(t,"utf8"):"",a=new Set(r.split(Nr)),o=ae.filter(i=>!a.has(i));if(o.length===0)return;const n=o.some(i=>!i.startsWith("!"))?[...o.filter(i=>!i.startsWith("!")),...ae.filter(i=>i.startsWith("!"))]:o,s=r.length>0&&!r.endsWith(`
|
|
1226
1226
|
`)?`
|
|
1227
1227
|
`:"";w(t,`${r}${s}
|
|
1228
1228
|
# Lunora
|
|
1229
1229
|
${n.join(`
|
|
1230
1230
|
`)}
|
|
1231
|
-
`,"utf8")},U=e=>e==="lunorash"||e.startsWith("@lunora/"),Ir=(e,t,r,a)=>U(e)?a.get(e)??r:t,S=(e,t,r)=>({...e,[t]:r}),oe=(e,t,r)=>Object.fromEntries(Object.entries(e).map(([a,o])=>[a,Ir(a,o,t,r)]))
|
|
1232
|
-
`,"utf8")}
|
|
1231
|
+
`,"utf8")},U=e=>e==="lunorash"||e.startsWith("@lunora/"),Ir=(e,t,r,a)=>U(e)?a.get(e)??r:t,S=(e,t,r)=>({...e,[t]:r}),oe=(e,t,r)=>Object.fromEntries(Object.entries(e).map(([a,o])=>[a,Ir(a,o,t,r)])),Rr=async(e,t,r,a)=>{const o=p(e,"package.json"),n=JSON.parse(x(o,"utf8"));let s=S(n.dependencies??{},"lunorash",a);s=S(s,"@lunora/ratelimit",a),r.adapter.startsWith("@lunora/")&&(s=S(s,r.adapter,a));for(const[u,h]of Object.entries(r.extraDependencies??{}))s=S(s,u,h);let i=S(n.devDependencies??{},"@lunora/vite",a);i=S(i,"@lunora/studio",a);for(const[u,h]of Object.entries(Er))i=S(i,u,h);const l=[...Object.keys(s),...Object.keys(i)].filter(u=>U(u)),c=await ve(l,a);n.name=t,n.imports={...n.imports,"#lunora/*":"./lunora/*"},n.dependencies=oe(s,a,c),n.devDependencies=oe(i,a,c),n.scripts={...n.scripts,codegen:"lunora codegen",deploy:"vite build && lunora deploy"},w(o,`${JSON.stringify(n,void 0,4)}
|
|
1232
|
+
`,"utf8")},$r=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],Te=e=>$r.map(t=>p(e,t)).find(t=>m(t)),Tr=(e,t)=>{const r=Te(e);if(r===void 0){t.warn("overlay: no vite.config found in the create-vite base — add `lunora()` to your Vite plugins manually.");return}const a=Ie(x(r,"utf8"));a.changed&&w(r,a.code,"utf8")},Or=async e=>{const{adapter:t,distTag:r,logger:a,name:o,target:n}=e,s=[];C(n,p("lunora","ratelimit","schema.ts"),xr,s),C(n,p("lunora","schema.ts"),Cr,s),C(n,p("lunora","messages.ts"),Sr,s),C(n,p("src","server.ts"),Lr,s),C(n,"wrangler.jsonc",Mr.replaceAll("__NAME__",o),s),C(n,".env.example",Ar,s);for(const i of t.files)C(n,i.path,i.contents,s);return Tr(n,a),await Rr(n,o,t,r),_r(n),s},Pr=["lunar","silver","silent","waning","waxing","crescent","cosmic","stellar","orbital","gibbous","twilight","midnight","shimmering","drifting","weightless"],Dr=["moon","tide","crater","comet","eclipse","halo","orbit","nebula","voyager","lander","rover","beacon","harbor","meadow","fox"],ne=e=>e[Math.floor(Math.random()*e.length)],Br=()=>`${ne(Pr)}-${ne(Dr)}`,jr=async()=>$t.lookup("github.com").then(()=>!0,()=>!1),Ur=/^(?:gh|github):([^/]+)\/([^#/]+)(?:\/[^#]*)?(?:#(.+))?$/,Oe=e=>{const t=Ur.exec(e);if(t===null)return;const[,r,a,o]=t;if(!(r===void 0||a===void 0))return{owner:r,ref:o??"HEAD",repo:a}},Vr=async e=>{const t=Oe(e);if(t===void 0)return;const r=`https://codeload.github.com/${t.owner}/${t.repo}/tar.gz/${t.ref}`;try{const a=await fetch(r,{method:"HEAD"});return a.status===404?!1:a.ok?!0:void 0}catch{return}},Pe=async e=>e.isLocal||!(e.source===void 0||Oe(e.source)!==void 0)?!0:await jr()?e.source!==void 0&&await Vr(e.source)===!1?(e.logger.error(`template source not found: ${e.source} — double-check --ref / --source, or browse the templates at https://lunora.sh/docs.`),!1):!0:(e.logger.error("you appear to be offline — connect to the internet and try again, or scaffold from a local template with `--from <dir>`."),!1),k={extras:"Let's finish setting up your app.",framework:"Which framework should we launch?",git:"Initialize a new git repository? (optional)",install:"Install dependencies now?",name:"Where should we land your project?",nextHeader:"Liftoff confirmed — explore your project!",packageManager:"Which package manager?"},Fr=new Set([".gitignore",".html",".js",".json",".jsonc",".md",".mjs",".ts",".tsx"]),Wr=`import { defineConfig } from "vite";
|
|
1233
1233
|
import { lunora } from "@lunora/vite";
|
|
1234
1234
|
|
|
1235
1235
|
export default defineConfig({ plugins: [lunora()] });
|
|
@@ -1256,8 +1256,8 @@ export const send = mutation
|
|
|
1256
1256
|
.mutation(async ({ args }) => {
|
|
1257
1257
|
return { channelId: args.channelId, text: args.text };
|
|
1258
1258
|
});
|
|
1259
|
-
`,Kr="gh:anolilab/lunora/templates",qr=e=>{const t=e.lastIndexOf(".");return t===-1?!1:Fr.has(e.slice(t))},Gr=/^[a-z0-9_][a-z0-9\-_]*$/u,Yr=/([a-z0-9])([A-Z])/gu,Jr=/[^a-z0-9_]/gu,Xr=e=>{const t=e.replaceAll(Yr,"$1-$2").toLowerCase().replaceAll(Jr,"-").split("-").filter(r=>r.length>0);return t.length>0?t.join("-"):"my-app"},Qr=(e,t)=>e.replaceAll("{{name}}",t),Zr=async(e,t)=>{const r=new Set;for(const a of e)if(_(a)==="package.json")try{const o=JSON.parse(
|
|
1260
|
-
`),Be=e=>{const t=p(e,De);m(t)||w(t,aa(),"utf8")},V=e=>{const t=[];for(const r of it(e,{includeDirs:!1,includeFiles:!0}))de(r.path).isSymbolicLink()||t.push(r.path);return t},se="vitejs/vite",ie=(e,t)=>{for(const r of V(e)){const a=p(t,fe(e,r));M(A(a),{recursive:!0}),Ge(r,a)}},je=async(e,t,r)=>{const a=V(e),o=[],n=we(),s=await Zr(a,n);for(const i of a){const l=fe(e,i),c=p(t,l);M(A(c),{recursive:!0});const u=
|
|
1261
|
-
`),e.success(`scaffolded ${String(t.length)} files into ${r}`)},na=(e,t)=>{const{args:r,command:a}=nt(e,t);return`${a} ${r.join(" ")}`},Fe=(e,t)=>{let r=me(e);for(;;){if(t(r))return!0;const a=A(r);if(a===r)return!1;r=a}},sa=e=>{if(m(p(e,De)))return!0;const t=p(e,"package.json");if(!m(t))return!1;try{return JSON.parse(
|
|
1262
|
-
`))},da=e=>e.yes!==!0&&(e.installPrompt!==void 0||y()),ua=async(e,t)=>{if(!da(e)||X(A(t)))return;const r=rt(e.packageManagerProbe),[a]=r;if(a===void 0)return;if(!await(e.installPrompt?.confirmInstall??(async()=>Ce(
|
|
1263
|
-
`),t.info(d?.commit?`template: ${d.source} @ ${d.commit} (${String($.length)} files)`:`template: ${d?.source??h} (${String($.length)} files)`),J(t,b,s),{code:0,files:b,target:s}}catch(u){if(u instanceof q)throw u;const{hints:h,message:d}=Zt(u,{ref:ye(o),remote:H(i,n,o),templateType:i});t.error(d);for(const b of h)t.warn(b);return{code:1,files:[],target:s}}finally{O(l,{force:!0,recursive:!0})}},ma=e=>{for(const t of["_gitignore","_npmrc","_gitattributes"]){const r=p(e,t);m(r)&&Ye(r,p(e,`.${t.slice(1)}`))}},fa=async e=>{const{framework:t,logger:r,markComplete:a,name:o,overlayBaseFrom:n,target:s}=e,i=B[t],l=ue(p(pe(),"lunora-vite-base-"));try{let c;if(n!==void 0&&(c=p(n,`template-${i.createViteTemplate}`),!m(c)))return r.error(`create-vite base not found on disk: ${c}`),{code:f.NOT_FOUND,files:[],target:s};const u=async()=>{if(c!==void 0){ie(c,s);return}const d=p(l,"base"),b=await mt(se,"main",r),$=`github:${se}/packages/create-vite/template-${i.createViteTemplate}#${b}`;await ge($,{cwd:l,dir:d,force:!0,install:!1,silent:!0}),ma(d),ie(d,s)};let h=[];return await Le([{label:`create-vite (${i.label}) base ready`,run:u},{label:`Lunora overlay applied (${i.label})`,run:async()=>{h=await Tr({adapter:i,distTag:we(),logger:r,name:o,target:s})}}],{end:Ve,start:"Project initializing…"}),a(),J(r,h,s),{code:0,files:[...V(s)],target:s}}catch(c){if(c instanceof q)throw c;const u=c instanceof Error?c.message:String(c);return r.error(`failed to scaffold the ${i.label} base: ${u}`),{code:1,files:[],target:s}}finally{O(l,{force:!0,recursive:!0})}},z=(e,t,r,a,o)=>(o.error(`init --in-place: could not ${e} ${t}: ${r instanceof Error?r.message:String(r)}`),{code:1,files:[],target:a}),ga=(e,t)=>{const r=p(e,"vite.config.ts");try{w(r,Wr,"utf8")}catch(a){return z("write",r,a,e,t)}return t.success(`created ${r} with lunora() plugin`),{code:0,files:[r],target:e}},va=(e,t,r)=>{let a;try{a=k(e,"utf8")}catch(n){return z("read",e,n,t,r)}const o=Ie(a);if(!o.changed)return r.info(`${e}: ${o.reason??"no changes needed"}`),{code:0,files:[],target:t};try{w(e,o.code,"utf8")}catch(n){return z("write",e,n,t,r)}return r.success(`patched ${e} — added lunora() plugin`),{code:0,files:[e],target:t}},wa=(e,t)=>{const r=p(e,"lunora"),a=p(r,"schema.ts");if(m(a))return t.info(`lunora/ already present — left ${a} untouched`),[];const o=[];try{M(r,{recursive:!0}),w(a,Hr,"utf8"),o.push(a);const n=p(r,"messages.ts");m(n)||(w(n,zr,"utf8"),o.push(n)),t.success(`scaffolded lunora/ (${String(o.length)} file(s))`)}catch(n){const s=n instanceof Error?n.message:String(n);t.error(`init --here: could not scaffold lunora/: ${s}`)}return o},We=e=>e==="sveltekit"||e==="nuxt"||e==="astro",ya=(e,t,r)=>{const{adapter:a,class:o,framework:n}=e;r.info(""),r.info(`detected framework: ${n} (class ${o})`),r.info("next steps:");const s=[a,"@lunora/client","@lunora/runtime","@lunora/server"];We(n)||s.push("@lunora/vite"),r.info(` 1. install the adapter: ${na(t,s)}`),r.info(" 2. run codegen: lunora codegen"),o==="A"?(r.info(" 3. compose one worker: wrap your worker entry with"),r.info(" createWorker({ httpRouter: <your framework SSR handler>, shardDO: ShardDO, ... })"),r.info(` 4. add the provider: mount the ${a} provider in your root layout/route`),r.info(" 5. make a loader live: preloadQuery() in a loader, usePreloadedQuery() in the component"),r.info(" see https://lunora.sh/docs/frameworks/reactive-loaders")):o==="B"?(r.info(" 3. inject Lunora: mount Lunora realtime under /_lunora/* in your server hook"),r.info(` (${n} owns its Cloudflare adapter — Lunora composes into its server entry)`),r.info(` 4. add the provider: mount the ${a} provider in your root layout`),r.info(" 5. read the guide: https://lunora.sh/docs/frameworks/deploy")):(r.info(" 3. add the provider: wrap your app with the LunoraProvider from @lunora/react"),r.info(" 4. read the guide: https://lunora.sh/docs/frameworks/bring-your-framework")),r.info("")},ba=(e,t,r)=>{if(We(t))return r.info(`${t} wires Lunora through its server entry, not a lunora() Vite plugin — leaving the Vite config alone (see next steps)`),{code:0,files:[],target:e};const a=Oe(e);return a===void 0?ga(e,r):va(a,e,r)},xa=(e,t)=>{const r=Vt(e),a=ba(e,r.framework,t);if(a.code!==0)return a;const o=wa(e,t);return ya(r,P(e),t),{code:0,files:[...a.files,...o],target:e}},ka=e=>e.yes!==!0&&(e.prompt!==void 0||(e.interactive??y())),le=async(e,t,r)=>{r.dryRun!==!0&&await ur({apply:a=>st(e,a),detected:ot(e),interactive:t,logger:r.logger,multiSelect:r.lintPrompt??((a,o,n)=>ke(a,o,{...n,badge:v.add}))})},Ca=async(e,t)=>{const r=ka(e),a=e.add===void 0?[]:rr(e.add,s=>{e.logger.warn(s)}),n={applyAll:async s=>{if(s.length===0)return!0;if(e.dryRun===!0)return E(e.logger,`add ${s.map(d=>d.label).join(", ")}`),!0;const i=[],l=y()?{error:d=>{i.push({level:"error",message:d})},info:()=>{},success:()=>{},warn:d=>{i.push({level:"warn",message:d})}}:e.logger,c=s.map(d=>({running:`adding ${d.label}…`,task:()=>It({allowUnsafeSource:e.allowUnsafeSource,cwd:t,from:e.registryFrom,logger:l,names:[...d.names],ref:e.ref,source:e.registrySource,transformManifest:d.transformManifest,yes:!0})})),u=`added ${s.map(d=>d.label).join(", ")}`,h=await kt(v.add,c,u);for(const{level:d,message:b}of i)e.logger[d](b);return h.every(d=>d.code===0)},interactive:r,logger:e.logger,multiSelect:e.prompt?.multiSelect??((s,i,l)=>ke(s,i,{...l,badge:v.add})),preselected:a.length>0?a:void 0,projectName:_(t),resolveAuthUiItem:()=>{let s;try{const i=JSON.parse(k(p(t,"package.json"),"utf8"));s={...i.dependencies,...i.devDependencies}}catch{return"auth-ui-react"}if(!Nt(s))return _t(s)??"auth-ui-react"},select:e.prompt?.select??((s,i,l)=>G(s,i,{...l,badge:v.add})),text:e.prompt?.text??((s,i)=>xe(s,{...i,badge:v.add}))};if(a.length>0){const s=await re(n);return await le(t,r,e),s}return y()&&await yt(x.extras),await re(n),await le(t,r,e),!0},F="react",He=[{description:"React SPA — official create-vite base + the Lunora layer (the default)",label:"React",value:"react"},{description:"Vue SPA — create-vite base + Lunora",label:"Vue",value:"vue"},{description:"Solid SPA — create-vite base + Lunora",label:"Solid",value:"solid"},{description:"Solid 2.0 SPA — the Solid 2 line (@solidjs/web, vite-plugin-solid 3)",label:"Solid 2",value:"solid-v2"},{description:"Svelte SPA — create-vite base + Lunora",label:"Svelte",value:"svelte"},{description:"Next.js (App Router) — OpenNext on Cloudflare + a standalone Lunora worker",label:"Next.js",value:"next"},{description:"TanStack Start (React) — SSR with live-loader routes",label:"TanStack Start · React",value:"tanstack-start-react"},{description:"TanStack Start (Solid)",label:"TanStack Start · Solid",value:"tanstack-start-solid"},{description:"Next.js App Router on Vite (vinext) — composed into the Lunora worker (experimental)",label:"vinext · App Router",value:"vinext"},{description:"Next.js Pages Router on Vite (vinext) — composed into one worker (experimental)",label:"vinext · Pages Router",value:"vinext-pages"},{description:"React Router (v7, framework mode) — SSR composed into the Lunora worker",label:"React Router",value:"react-router"},{description:"Astro (islands) — single-worker, Lunora composed into the adapter worker",label:"Astro",value:"astro"},{description:"AnalogJS (Angular) — single-worker, Lunora mounted in Nitro",label:"Analog",value:"analog"},{description:"Nuxt (Vue) — single-worker, Lunora mounted in Nitro",label:"Nuxt",value:"nuxt"},{description:"SvelteKit — single-worker, Lunora composed into the adapter worker",label:"SvelteKit",value:"sveltekit"},{description:"React Native (Expo) — an iOS/Android/web app + a Lunora worker backend",label:"React Native · Expo",value:"expo"},{description:"Worker only — no frontend",label:"Standalone",value:"standalone"}],ze=Object.keys(B).join("|"),Ke=He.filter(e=>!j(e.value)).map(e=>e.value),qe=Ke.join("|"),Sa=e=>j(e)?{framework:e,kind:"overlay"}:{kind:"template",templateType:e},La=async e=>e.vite!==void 0?{framework:e.vite,kind:"overlay"}:e.templateType!==void 0?{kind:"template",templateType:e.templateType}:!y()||e.yes===!0?{framework:F,kind:"overlay"}:Sa(await G(x.framework,He,{badge:v.tmpl,default:F})??F),Ma=e=>{if(y()||e.yes===!0)return;const t=[];if(e.name===void 0&&t.push("a project name (`lunora init <name>`)"),e.templateType===void 0&&e.vite===void 0&&t.push(`a framework — \`--vite <${ze}>\` for an SPA, or \`-t <${qe}>\` for a bespoke template`),t.length!==0)return`lunora init can't prompt in a non-interactive terminal — provide ${t.join(" and ")}, or pass --yes to accept the defaults.`},Aa=async(e,t,r,a,o)=>j(t)?await Pe({isLocal:e.overlayBaseFrom!==void 0,logger:e.logger})?(M(a,{recursive:!0}),fa({framework:t,logger:e.logger,markComplete:o,name:r,overlayBaseFrom:e.overlayBaseFrom,target:a})):{code:1,files:[],target:a}:(e.logger.error(`init: unknown framework "${t}". Supported overlays: ${Object.keys(B).join(", ")}.`),{code:f.USAGE,files:[],target:a}),Ea=async(e,t,r,a,o)=>e.from!==void 0?await pa(e.from,t,a,r,e.logger,o):e.source!==void 0&&e.source.length>0&&!e.allowUnsafeSource&&!oa(e.source)?(e.logger.error(`init: refusing --source ${e.source} — only gh:, github:, or https:// sources are allowed (and may not contain ".."). Re-run with --allow-unsafe-source if you really want this.`),{code:f.USAGE,files:[],target:a}):await Pe({isLocal:!1,logger:e.logger,source:H(t,e.source,e.ref)})?ha({logger:e.logger,markComplete:o,name:r,ref:e.ref,source:e.source,target:a,templateType:t}):{code:1,files:[],target:a},Na=(e,t)=>{if(X(t))return;let r;try{r=P(e)}catch{return}r==="pnpm"&&Be(e)},_a=async(e,t,r)=>{await wt("realtime backend on Cloudflare Workers + Durable Objects");const a=Ma(e);if(a!==void 0)return e.logger.error(a),{code:f.USAGE,files:[],target:""};const o=Br(),n=e.name??await xe(x.name,{badge:v.dir,default:o,placeholder:o}),s=await La(e),i=n.trim();if(i.length===0)return e.logger.error("init: refusing an empty project name — pass a directory name (e.g. `lunora init my-app`)."),{code:f.USAGE,files:[],target:""};if(i.includes("/")||i.includes("\\")||i===".."||i===".")return e.logger.error(`init: refusing project name "${i}" — must not contain path separators or be "." / "..".`),{code:f.USAGE,files:[],target:""};if(!Gr.test(i))return e.logger.error(`init: refusing project name "${i}" — a Cloudflare Worker name must be lowercase letters, digits, "-" or "_" (starting with a letter, digit or "_"), and wrangler rejects anything else. Try \`${Xr(i)}\`.`),{code:f.USAGE,files:[],target:""};const l=me(t,i),c=de(l,{throwIfNoEntry:!1});if(c?.isSymbolicLink()===!0)return e.logger.error(`init: refusing to scaffold into "${l}" — it is a symlink. Remove it, or scaffold into a different directory name.`),{code:f.CONFLICT,files:[],target:l};const u=c!==void 0;if(u&&ce(l).length>0)return e.logger.error(`target directory not empty: ${l}`),{code:f.CONFLICT,files:[],target:l};if(e.dryRun===!0){const d=s.kind==="overlay"?`the ${s.framework} create-vite overlay`:`the ${s.templateType} template`;return E(e.logger,`scaffold ${d} into ${l}`),{code:0,files:[],target:l}}r.record(l,u);const h=s.kind==="overlay"?await Aa(e,s.framework,i,l,r.complete):await Ea(e,s.templateType,i,l,r.complete);return h.code===0&&Na(l,t),h},W=(e,t)=>{const{target:r,targetPreExisted:a}=e;if(!(r===void 0||!m(r))){if(a===!0)for(const o of ce(r))O(p(r,o),{force:!0,recursive:!0});else O(r,{force:!0,recursive:!0});t.info(`removed the partially-created project at ${r}`)}},Ia=async(e,t,r)=>e.inPlace!==!0?_a(e,t,r):e.dryRun===!0?(E(e.logger,`configure Lunora into ${t}`),{code:0,files:[],target:t}):xa(t,e.logger),$a=async(e,t,r)=>{const a=await Ca(e,t.target),o=e.inPlace===!0?void 0:await ua(e,t.target);if(e.inPlace!==!0){await la(e,t.target);const n=o??P(t.target);await ca(_(t.target),o,n,X(r)),await er(e.logger)}return a},Ra=(e,t,r)=>{if(t.code!==0||e.ci===void 0)return;if(e.dryRun===!0){E(e.logger,`scaffold a ${e.ci} CI deploy pipeline`);return}const a=e.inPlace===!0?r:t.target;try{const o=P(a);jt(a,e.ci,o,e.logger)}catch{e.logger.warn(`--ci ${e.ci}: could not detect a package manager for this project — skipped the CI pipeline.`)}},Oa=async e=>{const t=e.cwd??process.cwd(),r={};let a;try{a=await Ia(e,t,{complete:()=>{r.target=void 0},record:(o,n)=>{r.target=o,r.targetPreExisted=n}}),a.code===0&&a.target!==""?(r.target=void 0,await $a(e,a,t)||(a={...a,code:1})):a.code!==0&&W(r,e.logger)}catch(o){if(o instanceof q)return W(r,e.logger),process.stdout.write("\n ✖ Setup cancelled — run `lunora init` again whenever you're ready. 🌙\n"),{code:130,files:[],target:""};throw W(r,e.logger),o}return Ra(e,a,t),a},Ta=e=>typeof e=="string"&&Ke.includes(e),Pa=(e,t)=>{if(e!==void 0){if(Dt(e))return e;t.warn(`init: unknown --ci "${e}" — expected github | gitlab; skipping CI scaffold.`)}},Da=e=>e===void 0?{}:Ta(e)?{templateType:e}:j(e)?{vite:e}:{error:`init: unknown --template "${e}" — expected a bespoke template (${qe}) or an overlay framework (${ze}).`},no=ut(({argument:e,cwd:t,logger:r,options:a})=>{const o=Da(a.template);return"error"in o?(r.error(o.error),{code:f.USAGE}):Oa({add:a.add,allowUnsafeSource:a.allowUnsafeSource===!0,cwd:t,ci:Pa(a.ci,r),dryRun:a.dryRun===!0,from:a.from,inPlace:a.here===!0,interactive:a.interactive===!0?!0:void 0,logger:r,name:e[0],ref:a.ref,source:a.source,templateType:o.templateType,vite:a.vite??o.vite,yes:a.yes===!0})});export{He as FRAMEWORK_CHOICES,no as execute,Ta as isTemplate,Da as resolveTemplateFlag,H as resolveTemplateSource,Oa as runInitCommand};
|
|
1259
|
+
`,Kr="gh:anolilab/lunora/templates",qr=e=>{const t=e.lastIndexOf(".");return t===-1?!1:Fr.has(e.slice(t))},Gr=/^[a-z0-9_][a-z0-9\-_]*$/u,Yr=/([a-z0-9])([A-Z])/gu,Jr=/[^a-z0-9_]/gu,Xr=e=>{const t=e.replaceAll(Yr,"$1-$2").toLowerCase().replaceAll(Jr,"-").split("-").filter(r=>r.length>0);return t.length>0?t.join("-"):"my-app"},Qr=(e,t)=>e.replaceAll("{{name}}",t),Zr=async(e,t)=>{const r=new Set;for(const a of e)if(_(a)==="package.json")try{const o=JSON.parse(x(a,"utf8"));for(const n of["dependencies","devDependencies"])for(const s of Object.keys(o[n]??{}))U(s)&&r.add(s)}catch{}return ve(r,t)},ea=(e,t,r)=>{let a;try{a=JSON.parse(e)}catch{return e}let o=e;for(const n of["dependencies","devDependencies"])for(const s of Object.keys(a[n]??{})){if(!U(s))continue;const i=r.get(s)??t,l=lt(o,[n,s],i,{formattingOptions:{insertSpaces:!0,tabSize:4}});o=ct(o,l)}return o},ta=["@parcel/watcher","esbuild","lmdb","msgpackr-extract","rs-module-lexer","sharp","unrs-resolver","vue-demi","workerd"],ra=["cpu-features","protobufjs","ssh2"],De="pnpm-workspace.yaml",aa=()=>["# pnpm reads its settings from here (the package.json `pnpm` field is no longer read).","# Pre-approve the toolchain's native build scripts so `pnpm install` runs them","# without the interactive `pnpm approve-builds` step; deny the optional native","# builds a scaffold doesn't need (so no C/C++ toolchain is required).","allowBuilds:",...ta.map(e=>` '${e}': true`),...ra.map(e=>` '${e}': false`),""].join(`
|
|
1260
|
+
`),Be=e=>{const t=p(e,De);m(t)||w(t,aa(),"utf8")},V=e=>{const t=[];for(const r of it(e,{includeDirs:!1,includeFiles:!0}))de(r.path).isSymbolicLink()||t.push(r.path);return t},se="vitejs/vite",ie=(e,t)=>{for(const r of V(e)){const a=p(t,fe(e,r));M(A(a),{recursive:!0}),Ge(r,a)}},je=async(e,t,r)=>{const a=V(e),o=[],n=we(),s=await Zr(a,n);for(const i of a){const l=fe(e,i),c=p(t,l);M(A(c),{recursive:!0});const u=x(i);let h=qr(i)?Qr(u.toString("utf8"),r):void 0;h!==void 0&&_(i)==="package.json"&&(h=ea(h,n,s)),h===void 0?w(c,u):w(c,h,"utf8"),o.push(c)}return o},H=(e,t,r)=>t!==void 0&&t.length>0?t:`${Kr}/${e}#${ye(r)}`,oa=e=>e.includes("..")?!1:e.startsWith("gh:")||e.startsWith("github:")||e.startsWith("https://"),E=(e,t)=>{e.info(`[dry-run] would ${t}`)},Ue=(e,t,r)=>(e.error(`init: the template at ${r} contains no files — nothing was scaffolded. Check the template name, \`--source\` layout and \`--ref\`.`),{code:f.NOT_FOUND,files:[],target:t}),Ve="Template files copied.",J=(e,t,r)=>{y()&&process.stdout.write(`
|
|
1261
|
+
`),e.success(`scaffolded ${String(t.length)} files into ${r}`)},na=(e,t)=>{const{args:r,command:a}=nt(e,t);return`${a} ${r.join(" ")}`},Fe=(e,t)=>{let r=me(e);for(;;){if(t(r))return!0;const a=A(r);if(a===r)return!1;r=a}},sa=e=>{if(m(p(e,De)))return!0;const t=p(e,"package.json");if(!m(t))return!1;try{return JSON.parse(x(t,"utf8")).workspaces!==void 0}catch{return!1}},X=e=>Fe(e,sa),ia=e=>Fe(e,t=>m(p(t,".git"))),la=async(e,t)=>{if(e.yes===!0||!y()||ia(A(t)))return;if(!await Ce(k.git,{badge:v.git,defaultYes:!1})){await Se("Sounds good! You can always run git init manually.");return}if(e.dryRun===!0){E(e.logger,"initialize a git repository");return}const r=e.spawner??be;(await bt("Initializing a git repository…",()=>r({args:["init"],command:"git",cwd:t}))).code===0?await O("git","Initialized an empty git repository."):e.logger.warn("`git init` failed — initialize it yourself later with `git init`.")},ca=async(e,t,r,a)=>{const o=[{code:`cd ./${e}`,lead:"Enter your project directory using"}];t===void 0&&o.push({code:`${r} install`,lead:"Install dependencies with",tail:a?" from the workspace root":void 0}),o.push({code:at(r,"dev"),lead:"Run",tail:" to start the dev server."},{code:"lunora add",lead:"Add features like auth or storage using"});const n=[{code:"https://lunora.sh/docs",lead:"Read the docs at"},{code:"https://lunora.sh/chat",lead:"Stuck? Join the chat at"}];if(y()){await kt(v.next,k.nextHeader,o,n);return}const s=o.map(i=>`${i.lead} ${i.code}${i.tail??""}`);s.push("",...n.map(i=>`${i.lead} ${i.code}${i.tail??""}`)),await O("next",k.nextHeader,s.join(`
|
|
1262
|
+
`))},da=e=>e.yes!==!0&&(e.installPrompt!==void 0||y()),ua=async(e,t)=>{if(!da(e)||X(A(t)))return;const r=rt(e.packageManagerProbe),[a]=r;if(a===void 0)return;if(!await(e.installPrompt?.confirmInstall??(async()=>Ce(k.install,{badge:v.deps,defaultYes:!0})))()){await Se("No problem! Remember to install dependencies after setup.");return}let n=a;if(r.length>1&&(n=e.installPrompt?await e.installPrompt.selectManager(r):await G(k.packageManager,r.map(u=>({label:u,value:u})),{badge:v.deps,default:a})??a),e.dryRun===!0){E(e.logger,`install dependencies with ${n}`);return}n==="pnpm"&&Be(t);const s=e.spawner??be,{args:i,command:l}=he(n);await O("deps",`Installing dependencies with ${n}…`);const c=await s({args:i,command:l,cwd:t});if(c.code!==0){e.logger.warn(`\`${l} install\` exited with code ${String(c.code)} — run it yourself in ${_(t)}/.`);return}return await O("deps",`Dependencies installed with ${n}.`),n},pa=async(e,t,r,a,o,n)=>{const s=p(e,t);if(!m(s))return o.error(`template not found in local source: ${s}`),{code:f.NOT_FOUND,files:[],target:r};const i=await je(s,r,a);return i.length===0?Ue(o,r,s):(n(),J(o,i,r),{code:0,files:i,target:r})},ha=async e=>{const{logger:t,markComplete:r,name:a,ref:o,source:n,target:s,templateType:i}=e,l=ue(p(pe(),"lunora-init-fetch-")),c=p(l,"template");try{const u=n!==void 0&&n.length>0?o:await ft(o,t),h=H(i,n,u);let d,b=[];if(await Le([{label:`${i} template fetched`,run:async()=>{d=await ge(h,{cwd:l,dir:c,force:!0,install:!1,silent:!0})}},{label:`files copied into ${a}/`,run:async()=>{b=await je(c,s,a)}}],{end:Ve,start:"Project initializing…"}),b.length===0)return Ue(t,s,d?.source??h);r();const R=V(c);return y()&&process.stdout.write(`
|
|
1263
|
+
`),t.info(d?.commit?`template: ${d.source} @ ${d.commit} (${String(R.length)} files)`:`template: ${d?.source??h} (${String(R.length)} files)`),J(t,b,s),{code:0,files:b,target:s}}catch(u){if(u instanceof q)throw u;const{hints:h,message:d}=Zt(u,{ref:ye(o),remote:H(i,n,o),templateType:i});t.error(d);for(const b of h)t.warn(b);return{code:1,files:[],target:s}}finally{T(l,{force:!0,recursive:!0})}},ma=e=>{for(const t of["_gitignore","_npmrc","_gitattributes"]){const r=p(e,t);m(r)&&Ye(r,p(e,`.${t.slice(1)}`))}},fa=async e=>{const{framework:t,logger:r,markComplete:a,name:o,overlayBaseFrom:n,target:s}=e,i=B[t],l=ue(p(pe(),"lunora-vite-base-"));try{let c;if(n!==void 0&&(c=p(n,`template-${i.createViteTemplate}`),!m(c)))return r.error(`create-vite base not found on disk: ${c}`),{code:f.NOT_FOUND,files:[],target:s};const u=async()=>{if(c!==void 0){ie(c,s);return}const d=p(l,"base"),b=await mt(se,"main",r),R=`github:${se}/packages/create-vite/template-${i.createViteTemplate}#${b}`;await ge(R,{cwd:l,dir:d,force:!0,install:!1,silent:!0}),ma(d),ie(d,s)};let h=[];return await Le([{label:`create-vite (${i.label}) base ready`,run:u},{label:`Lunora overlay applied (${i.label})`,run:async()=>{h=await Or({adapter:i,distTag:we(),logger:r,name:o,target:s})}}],{end:Ve,start:"Project initializing…"}),a(),J(r,h,s),{code:0,files:[...V(s)],target:s}}catch(c){if(c instanceof q)throw c;const u=c instanceof Error?c.message:String(c);return r.error(`failed to scaffold the ${i.label} base: ${u}`),{code:1,files:[],target:s}}finally{T(l,{force:!0,recursive:!0})}},z=(e,t,r,a,o)=>(o.error(`init --in-place: could not ${e} ${t}: ${r instanceof Error?r.message:String(r)}`),{code:1,files:[],target:a}),ga=(e,t)=>{const r=p(e,"vite.config.ts");try{w(r,Wr,"utf8")}catch(a){return z("write",r,a,e,t)}return t.success(`created ${r} with lunora() plugin`),{code:0,files:[r],target:e}},va=(e,t,r)=>{let a;try{a=x(e,"utf8")}catch(n){return z("read",e,n,t,r)}const o=Ie(a);if(!o.changed)return r.info(`${e}: ${o.reason??"no changes needed"}`),{code:0,files:[],target:t};try{w(e,o.code,"utf8")}catch(n){return z("write",e,n,t,r)}return r.success(`patched ${e} — added lunora() plugin`),{code:0,files:[e],target:t}},wa=(e,t)=>{const r=p(e,"lunora"),a=p(r,"schema.ts");if(m(a))return t.info(`lunora/ already present — left ${a} untouched`),[];const o=[];try{M(r,{recursive:!0}),w(a,Hr,"utf8"),o.push(a);const n=p(r,"messages.ts");m(n)||(w(n,zr,"utf8"),o.push(n)),t.success(`scaffolded lunora/ (${String(o.length)} file(s))`)}catch(n){const s=n instanceof Error?n.message:String(n);t.error(`init --here: could not scaffold lunora/: ${s}`)}return o},We=e=>e==="sveltekit"||e==="nuxt"||e==="astro",ya=(e,t,r)=>{const{adapter:a,class:o,framework:n}=e;r.info(""),r.info(`detected framework: ${n} (class ${o})`),r.info("next steps:");const s=[a,"@lunora/client","@lunora/runtime","@lunora/server"];We(n)||s.push("@lunora/vite"),r.info(` 1. install the adapter: ${na(t,s)}`),r.info(" 2. run codegen: lunora codegen"),o==="A"?(r.info(" 3. compose one worker: wrap your worker entry with"),r.info(" createWorker({ httpRouter: <your framework SSR handler>, shardDO: ShardDO, ... })"),r.info(` 4. add the provider: mount the ${a} provider in your root layout/route`),r.info(" 5. make a loader live: preloadQuery() in a loader, usePreloadedQuery() in the component"),r.info(" see https://lunora.sh/docs/frameworks/reactive-loaders")):o==="B"?(r.info(" 3. inject Lunora: mount Lunora realtime under /_lunora/* in your server hook"),r.info(` (${n} owns its Cloudflare adapter — Lunora composes into its server entry)`),r.info(` 4. add the provider: mount the ${a} provider in your root layout`),r.info(" 5. read the guide: https://lunora.sh/docs/frameworks/deploy")):(r.info(" 3. add the provider: wrap your app with the LunoraProvider from @lunora/react"),r.info(" 4. read the guide: https://lunora.sh/docs/frameworks/bring-your-framework")),r.info("")},ba=(e,t,r)=>{if(We(t))return r.info(`${t} wires Lunora through its server entry, not a lunora() Vite plugin — leaving the Vite config alone (see next steps)`),{code:0,files:[],target:e};const a=Te(e);return a===void 0?ga(e,r):va(a,e,r)},ka=(e,t)=>{const r=Vt(e),a=ba(e,r.framework,t);if(a.code!==0)return a;const o=wa(e,t);return ya(r,P(e),t),{code:0,files:[...a.files,...o],target:e}},xa=e=>e.yes!==!0&&(e.prompt!==void 0||(e.interactive??y())),le=async(e,t,r)=>{r.dryRun!==!0&&await ur({apply:a=>st(e,a),detected:ot(e),interactive:t,logger:r.logger,multiSelect:r.lintPrompt??((a,o,n)=>xe(a,o,{...n,badge:v.add}))})},Ca=async(e,t)=>{const r=xa(e),a=e.add===void 0?[]:rr(e.add,s=>{e.logger.warn(s)}),n={applyAll:async s=>{if(s.length===0)return!0;if(e.dryRun===!0)return E(e.logger,`add ${s.map(d=>d.label).join(", ")}`),!0;const i=[],l=y()?{error:d=>{i.push({level:"error",message:d})},info:()=>{},success:()=>{},warn:d=>{i.push({level:"warn",message:d})}}:e.logger,c=s.map(d=>({running:`adding ${d.label}…`,task:()=>It({allowUnsafeSource:e.allowUnsafeSource,cwd:t,from:e.registryFrom,logger:l,names:[...d.names],ref:e.ref,source:e.registrySource,transformManifest:d.transformManifest,yes:!0})})),u=`added ${s.map(d=>d.label).join(", ")}`,h=await xt(v.add,c,u);for(const{level:d,message:b}of i)e.logger[d](b);return h.every(d=>d.code===0)},interactive:r,logger:e.logger,multiSelect:e.prompt?.multiSelect??((s,i,l)=>xe(s,i,{...l,badge:v.add})),preselected:a.length>0?a:void 0,projectName:_(t),resolveAuthUiItem:()=>{let s;try{const i=JSON.parse(x(p(t,"package.json"),"utf8"));s={...i.dependencies,...i.devDependencies}}catch{return"auth-ui-react"}if(!Nt(s))return _t(s)??"auth-ui-react"},select:e.prompt?.select??((s,i,l)=>G(s,i,{...l,badge:v.add})),text:e.prompt?.text??((s,i)=>ke(s,{...i,badge:v.add}))};if(a.length>0){const s=await re(n);return await le(t,r,e),s}return y()&&await yt(k.extras),await re(n),await le(t,r,e),!0},F="react",He=[{description:"React SPA — official create-vite base + the Lunora layer (the default)",label:"React",value:"react"},{description:"Vue SPA — create-vite base + Lunora",label:"Vue",value:"vue"},{description:"Solid SPA — create-vite base + Lunora",label:"Solid",value:"solid"},{description:"Solid 2.0 SPA — the Solid 2 line (@solidjs/web, vite-plugin-solid 3)",label:"Solid 2",value:"solid-v2"},{description:"Svelte SPA — create-vite base + Lunora",label:"Svelte",value:"svelte"},{description:"React SPA on Rsbuild — the Worker runs under wrangler dev behind the dev server",label:"React · Rsbuild",value:"rspack-react"},{description:"Next.js (App Router) — OpenNext on Cloudflare + a standalone Lunora worker",label:"Next.js",value:"next"},{description:"TanStack Start (React) — SSR with live-loader routes",label:"TanStack Start · React",value:"tanstack-start-react"},{description:"TanStack Start (React) on Rsbuild — SSR composed into the Lunora worker",label:"TanStack Start · React · Rsbuild",value:"tanstack-start-react-rspack"},{description:"TanStack Start (Solid)",label:"TanStack Start · Solid",value:"tanstack-start-solid"},{description:"Next.js App Router on Vite (vinext) — composed into the Lunora worker (experimental)",label:"vinext · App Router",value:"vinext"},{description:"Next.js Pages Router on Vite (vinext) — composed into one worker (experimental)",label:"vinext · Pages Router",value:"vinext-pages"},{description:"React Router (v7, framework mode) — SSR composed into the Lunora worker",label:"React Router",value:"react-router"},{description:"Astro (islands) — single-worker, Lunora composed into the adapter worker",label:"Astro",value:"astro"},{description:"AnalogJS (Angular) — single-worker, Lunora mounted in Nitro",label:"Analog",value:"analog"},{description:"Nuxt (Vue) — single-worker, Lunora mounted in Nitro",label:"Nuxt",value:"nuxt"},{description:"SvelteKit — single-worker, Lunora composed into the adapter worker",label:"SvelteKit",value:"sveltekit"},{description:"React Native (Expo) — an iOS/Android/web app + a Lunora worker backend",label:"React Native · Expo",value:"expo"},{description:"Worker only — no frontend",label:"Standalone",value:"standalone"}],ze=Object.keys(B).join("|"),Ke=He.filter(e=>!j(e.value)).map(e=>e.value),qe=Ke.join("|"),Sa=e=>j(e)?{framework:e,kind:"overlay"}:{kind:"template",templateType:e},La=async e=>e.vite!==void 0?{framework:e.vite,kind:"overlay"}:e.templateType!==void 0?{kind:"template",templateType:e.templateType}:!y()||e.yes===!0?{framework:F,kind:"overlay"}:Sa(await G(k.framework,He,{badge:v.tmpl,default:F})??F),Ma=e=>{if(y()||e.yes===!0)return;const t=[];if(e.name===void 0&&t.push("a project name (`lunora init <name>`)"),e.templateType===void 0&&e.vite===void 0&&t.push(`a framework — \`--vite <${ze}>\` for an SPA, or \`-t <${qe}>\` for a bespoke template`),t.length!==0)return`lunora init can't prompt in a non-interactive terminal — provide ${t.join(" and ")}, or pass --yes to accept the defaults.`},Aa=async(e,t,r,a,o)=>j(t)?await Pe({isLocal:e.overlayBaseFrom!==void 0,logger:e.logger})?(M(a,{recursive:!0}),fa({framework:t,logger:e.logger,markComplete:o,name:r,overlayBaseFrom:e.overlayBaseFrom,target:a})):{code:1,files:[],target:a}:(e.logger.error(`init: unknown framework "${t}". Supported overlays: ${Object.keys(B).join(", ")}.`),{code:f.USAGE,files:[],target:a}),Ea=async(e,t,r,a,o)=>e.from!==void 0?await pa(e.from,t,a,r,e.logger,o):e.source!==void 0&&e.source.length>0&&!e.allowUnsafeSource&&!oa(e.source)?(e.logger.error(`init: refusing --source ${e.source} — only gh:, github:, or https:// sources are allowed (and may not contain ".."). Re-run with --allow-unsafe-source if you really want this.`),{code:f.USAGE,files:[],target:a}):await Pe({isLocal:!1,logger:e.logger,source:H(t,e.source,e.ref)})?ha({logger:e.logger,markComplete:o,name:r,ref:e.ref,source:e.source,target:a,templateType:t}):{code:1,files:[],target:a},Na=(e,t)=>{if(X(t))return;let r;try{r=P(e)}catch{return}r==="pnpm"&&Be(e)},_a=async(e,t,r)=>{await wt("realtime backend on Cloudflare Workers + Durable Objects");const a=Ma(e);if(a!==void 0)return e.logger.error(a),{code:f.USAGE,files:[],target:""};const o=Br(),n=e.name??await ke(k.name,{badge:v.dir,default:o,placeholder:o}),s=await La(e),i=n.trim();if(i.length===0)return e.logger.error("init: refusing an empty project name — pass a directory name (e.g. `lunora init my-app`)."),{code:f.USAGE,files:[],target:""};if(i.includes("/")||i.includes("\\")||i===".."||i===".")return e.logger.error(`init: refusing project name "${i}" — must not contain path separators or be "." / "..".`),{code:f.USAGE,files:[],target:""};if(!Gr.test(i))return e.logger.error(`init: refusing project name "${i}" — a Cloudflare Worker name must be lowercase letters, digits, "-" or "_" (starting with a letter, digit or "_"), and wrangler rejects anything else. Try \`${Xr(i)}\`.`),{code:f.USAGE,files:[],target:""};const l=me(t,i),c=de(l,{throwIfNoEntry:!1});if(c?.isSymbolicLink()===!0)return e.logger.error(`init: refusing to scaffold into "${l}" — it is a symlink. Remove it, or scaffold into a different directory name.`),{code:f.CONFLICT,files:[],target:l};const u=c!==void 0;if(u&&ce(l).length>0)return e.logger.error(`target directory not empty: ${l}`),{code:f.CONFLICT,files:[],target:l};if(e.dryRun===!0){const d=s.kind==="overlay"?`the ${s.framework} create-vite overlay`:`the ${s.templateType} template`;return E(e.logger,`scaffold ${d} into ${l}`),{code:0,files:[],target:l}}r.record(l,u);const h=s.kind==="overlay"?await Aa(e,s.framework,i,l,r.complete):await Ea(e,s.templateType,i,l,r.complete);return h.code===0&&Na(l,t),h},W=(e,t)=>{const{target:r,targetPreExisted:a}=e;if(!(r===void 0||!m(r))){if(a===!0)for(const o of ce(r))T(p(r,o),{force:!0,recursive:!0});else T(r,{force:!0,recursive:!0});t.info(`removed the partially-created project at ${r}`)}},Ia=async(e,t,r)=>e.inPlace!==!0?_a(e,t,r):e.dryRun===!0?(E(e.logger,`configure Lunora into ${t}`),{code:0,files:[],target:t}):ka(t,e.logger),Ra=async(e,t,r)=>{const a=await Ca(e,t.target),o=e.inPlace===!0?void 0:await ua(e,t.target);if(e.inPlace!==!0){await la(e,t.target);const n=o??P(t.target);await ca(_(t.target),o,n,X(r)),await er(e.logger)}return a},$a=(e,t,r)=>{if(t.code!==0||e.ci===void 0)return;if(e.dryRun===!0){E(e.logger,`scaffold a ${e.ci} CI deploy pipeline`);return}const a=e.inPlace===!0?r:t.target;try{const o=P(a);jt(a,e.ci,o,e.logger)}catch{e.logger.warn(`--ci ${e.ci}: could not detect a package manager for this project — skipped the CI pipeline.`)}},Ta=async e=>{const t=e.cwd??process.cwd(),r={};let a;try{a=await Ia(e,t,{complete:()=>{r.target=void 0},record:(o,n)=>{r.target=o,r.targetPreExisted=n}}),a.code===0&&a.target!==""?(r.target=void 0,await Ra(e,a,t)||(a={...a,code:1})):a.code!==0&&W(r,e.logger)}catch(o){if(o instanceof q)return W(r,e.logger),process.stdout.write("\n ✖ Setup cancelled — run `lunora init` again whenever you're ready. 🌙\n"),{code:130,files:[],target:""};throw W(r,e.logger),o}return $a(e,a,t),a},Oa=e=>typeof e=="string"&&Ke.includes(e),Pa=(e,t)=>{if(e!==void 0){if(Dt(e))return e;t.warn(`init: unknown --ci "${e}" — expected github | gitlab; skipping CI scaffold.`)}},Da=e=>e===void 0?{}:Oa(e)?{templateType:e}:j(e)?{vite:e}:{error:`init: unknown --template "${e}" — expected a bespoke template (${qe}) or an overlay framework (${ze}).`},no=ut(({argument:e,cwd:t,logger:r,options:a})=>{const o=Da(a.template);return"error"in o?(r.error(o.error),{code:f.USAGE}):Ta({add:a.add,allowUnsafeSource:a.allowUnsafeSource===!0,cwd:t,ci:Pa(a.ci,r),dryRun:a.dryRun===!0,from:a.from,inPlace:a.here===!0,interactive:a.interactive===!0?!0:void 0,logger:r,name:e[0],ref:a.ref,source:a.source,templateType:o.templateType,vite:a.vite??o.vite,yes:a.yes===!0})});export{He as FRAMEWORK_CHOICES,no as execute,Oa as isTemplate,Da as resolveTemplateFlag,H as resolveTemplateSource,Ta as runInitCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as m,rmSync as d}from"node:fs";import{join as n,relative as f}from"@visulima/path";import{d as a}from"../packem_shared/command-
|
|
1
|
+
import{existsSync as m,rmSync as d}from"node:fs";import{join as n,relative as f}from"@visulima/path";import{d as a}from"../packem_shared/command-B--jgXSc.mjs";import{EXIT_CODE as s}from"../packem_shared/EXIT_CODE-08cwt3MK.mjs";import{b as l}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";const u=async e=>{const o=e.cwd??process.cwd(),t=[n(o,".wrangler","state")];if(e.all&&t.push(n(o,".lunora-cache")),!e.yes){const r=t.map(i=>f(o,i)).join(" and ");if(!process.stdin.isTTY&&e.confirm===void 0)return e.logger.error(`reset: stdin is not a TTY — re-run with --yes to confirm deleting ${r}`),{code:s.USAGE,removed:[]};if(!await(e.confirm??l)(`This will delete ${r}. Continue?`))return e.logger.info("reset: aborted"),{code:s.CANCELLED,removed:[]}}const c=[];for(const r of t)m(r)?(d(r,{force:!0,recursive:!0}),c.push(r),e.logger.success(`removed ${r}`)):e.logger.info(`skipped (not present): ${r}`);return{code:0,removed:c}},E=a(({cwd:e,logger:o,options:t})=>u({all:t.all===!0,cwd:e,logger:o,yes:t.yes===!0}));export{E as execute,u as runResetCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as h}from"@lunora/errors";import{r as S,d as b}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{r as N,a as _}from"../packem_shared/admin-url-BhF5ufg1.mjs";import{d as U}from"../packem_shared/command-
|
|
1
|
+
import{LunoraError as h}from"@lunora/errors";import{r as S,d as b}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{r as N,a as _}from"../packem_shared/admin-url-BhF5ufg1.mjs";import{d as U}from"../packem_shared/command-B--jgXSc.mjs";import{EXIT_CODE as u,exitCodeForStatus as p}from"../packem_shared/EXIT_CODE-08cwt3MK.mjs";import{r as E}from"../packem_shared/resolve-target-C_ZloTvd.mjs";const y=(r,a="--args")=>{if(r===void 0||r.length===0)return{};let e;try{e=JSON.parse(r)}catch(t){const s=t instanceof Error?t.message:String(t);throw new h("INTERNAL",`failed to parse ${a} as JSON: ${s}`,{cause:t})}if(typeof e!="object"||e===null||Array.isArray(e))throw new h("INTERNAL",`${a} must be a JSON object (e.g. '{"id":1}'), got ${Array.isArray(e)?"an array":typeof e}`);return e},P=/\/$/u,T="__lunora_admin__:runAs",I="__lunora_admin__:",O=async(r,a)=>{const e=await r.text();let t;try{t=JSON.parse(e)}catch{t=e}return a.info(JSON.stringify(t,void 0,2)),t},$=(r,a)=>{const e=a.body?.error?.code;a.runAs||a.status!==403||e!=="FORBIDDEN_SHARD"||r.info("this app authorizes per shard, so an anonymous call is denied — retry with --as <userId> to run as an authenticated user")},k=({args:r,claims:a,options:e,runAs:t})=>{const s=t?{args:{args:r,functionPath:e.functionPath,identity:a,userId:e.as},functionPath:T}:{args:r,functionPath:e.functionPath};return e.shard!==void 0&&(s.shardKey=e.shard),s},R=({cwd:r,logger:a,needsBearer:e,url:t})=>e?N(t,a,r):(E({cwd:r,url:t})??_(r)).replace(P,""),w=({args:r,claims:a},e)=>{try{return{args:y(r),claims:a===void 0?void 0:y(a,"--claims")}}catch(t){e.error(t instanceof Error?t.message:String(t));return}},D=async r=>{const a=r.cwd??process.cwd(),{logger:e}=r,t=r.as!==void 0&&r.as!=="";if(r.claims!==void 0&&!t){const d="--claims requires --as <userId> — extra identity claims only travel inside the admin-gated `runAs` dispatch.";return e.error(d),{body:void 0,code:u.USAGE,error:d,requestUrl:r.url??""}}const s=t||r.functionPath.startsWith(I),n=R({cwd:a,logger:e,needsBearer:s,url:r.url});if(n===void 0)return{body:void 0,code:u.USAGE,error:"could not resolve a usable worker URL",requestUrl:r.url??""};const o=`${n}/_lunora/rpc`,i=r.fetchImpl??globalThis.fetch;if(typeof i!="function")throw new TypeError("no fetch implementation available — pass --fetch via dependency injection or run on Node >= 18");const f=w(r,e);if(f===void 0)return{body:void 0,code:u.USAGE,error:"could not parse --args / --claims as JSON",requestUrl:o};const{source:v,token:l}=s?S({cwd:a,token:r.token,url:n}):{};if(s&&l===void 0){const d="admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)";return e.error(d),{body:void 0,code:u.AUTH,error:d,requestUrl:o}}l!==void 0&&e.debug?.(`admin bearer from ${b(v)}`);const g={"content-type":"application/json",...l===void 0?{}:{authorization:`Bearer ${l}`}},A=k({args:f.args,claims:f.claims,options:r,runAs:t});e.info(`POST ${o} -> ${r.functionPath}${t?` (as ${r.as??""})`:""}`);const c=await i(o,{body:JSON.stringify(A),headers:g,method:"POST"}),m=await O(c,e);return $(e,{body:m,runAs:t,status:c.status}),{body:m,code:c.ok?0:p(c.status),error:c.ok?void 0:`${r.functionPath} failed: HTTP ${String(c.status)}`,requestUrl:o}},j=U(async({argument:r,cwd:a,format:e,logger:t,options:s})=>{const n=r[0];if(!n){const i="missing function path. Usage: lunora run <functionPath> [--args <json>]";return t.error(i),{code:u.USAGE,error:i}}const o=await D({args:s.args,as:s.as,claims:s.claims,cwd:a,format:e,functionPath:n,logger:t,shard:s.shard,token:s.token,url:s.url});return{code:o.code,data:{functionPath:n,requestUrl:o.requestUrl,result:o.body},error:o.error}});export{j as execute,O as readAndLogBody,D as runRpcCommand};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{C as i,R as m,V as p,r as s}from"./cli-D1ZleZMH.mjs";import"./EXIT_CODE-08cwt3MK.mjs";import"./createLogger-Cl18I8AX.mjs";import"./render-lunora-error-DgaSmNLc.mjs";export{i as COMMANDS,m as REGISTERED_COMMAND_NAMES,p as VERSION,s as runCli};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{mkdirSync as A,readFileSync as S,lstatSync as D,writeFileSync as B}from"node:fs";import{join as m,dirname as y}from"node:path";import{fileURLToPath as E}from"node:url";import{isLunoraError as L,findSolutionByMessage as I}from"@lunora/errors";import{createCerebro as j}from"@visulima/cerebro";import T from"@visulima/cerebro/command/completion";import _ from"@visulima/cerebro/command/version";import{O as i}from"./output-format-B4eQHi5y.mjs";import{A as p,T as l}from"./deploy-target-DCWwiuAe.mjs";import{SDK_LANGUAGES as P}from"@lunora/codegen";import{exitCodeForError as U,EXIT_CODE as M}from"./EXIT_CODE-08cwt3MK.mjs";import{setCommandLogger as v,createLogger as x}from"./createLogger-Cl18I8AX.mjs";import{r as W}from"./render-lunora-error-DgaSmNLc.mjs";import{homedir as J}from"node:os";import{addArgsFor as F,detectPackageManager as K}from"@lunora/config";const H={argument:{description:"Feature or registry item: ai | auth | email | storage | crons | presence | queue | workflow | flags | backup | …",name:"feature",type:String},description:"Add a feature or registry item (ai, auth, email, storage, crons, …) to the current Lunora project",examples:[["lunora add auth","Add authentication (asks which provider)"],["lunora add auth --provider clerk","Add Clerk auth without prompting"],["lunora add auth-ui","Add copy-in auth screens for your framework (auto-detected)"],["lunora add email","Add transactional email (Cloudflare Email Workers + dev mail catcher)"],["lunora add storage","Add the R2 storage registry item (asks for the bucket name)"],["lunora add storage --bucket my-app-uploads","Add storage with a bucket name, no prompt"],["lunora add crons","Add the scheduled-jobs registry item"],["lunora add storage --ref alpha","Add an item from the alpha branch's registry"]],group:"Project",loader:()=>import("../packem_chunks/handler.mjs").then(e=>({default:e.execute})),name:"add",options:[{description:"auth: provider to use without prompting (auth | clerk | auth0)",name:"provider",type:String},{description:"auth: D1 database name to use without prompting (lowercase alphanumeric + hyphens)",name:"db",type:String},{description:"storage: R2 bucket name to use without prompting (lowercase alphanumeric + hyphens)",name:"bucket",type:String},{description:"email: verified destination address to use without prompting",name:"mail-to",type:String},{description:"Skip prompts (auth provider, DB name, bucket name, mail destination) and use the defaults",name:"yes",type:Boolean},{description:"Local registry root (offline; expects <name>/ subdirs)",name:"from",type:String},{description:"Override the remote registry source base (e.g. gh:owner/repo/registry)",name:"source",type:String},{description:"Fetch items from a git ref (branch, tag, or commit), e.g. --ref alpha. Overrides the version-derived default",name:"ref",type:String},{description:"Permit --source values outside gh:/github:/https://",name:"allow-unsafe-source",type:Boolean},i]},b="lunora.advisor.map.json",$={description:"Score your app's advisor findings into a health map, and gate CI on it",examples:[["lunora advisor","Score the app and write lunora.advisor.map.json"],["lunora advisor --all","Show every procedure as a check matrix"],["lunora advisor --entry messages#sendMessage","Inspect one procedure"],["lunora advisor --min-score 80","Exit non-zero when the score drops below 80"],["lunora advisor --baseline","Fail on any regression against the committed map"]],group:"Develop",loader:()=>import("../packem_chunks/handler19.mjs").then(e=>({default:e.execute})),name:"advisor",options:[{description:"Show every procedure as a check matrix, not just the ones with findings",name:"all",type:Boolean},{description:`Compare against a committed map and fail on regression (default ${b})`,name:"baseline",type:String},{description:"Inspect a single procedure by `file#exportName`",name:"entry",type:String},i,{description:"Exit non-zero when the global score is below this value (0-100)",name:"min-score",type:String},{description:`Where to write the map (default ${b})`,name:"out",type:String},{description:"Write the map artifact to disk (the default)",name:"write",type:Boolean},{description:"Don't write the map artifact to disk — report only",name:"no-write",type:Boolean}]},V={description:"Run wrangler dry-run and report bundle size, top modules, and _generated files",examples:[["lunora analyze","Report the worker bundle size + heaviest modules"]],group:"Deploy",loader:()=>import("../packem_chunks/handler2.mjs").then(e=>({default:e.execute})),name:"analyze",options:[i]},G={argument:{description:"create | list | restore <id|file> | retention | prune | pitr",name:"subcommand",type:String},description:"Managed snapshot backups (create | list | restore) to a directory or an R2 bucket, plus native point-in-time recovery (pitr)",examples:[["lunora backup create","Snapshot every table to a backup file"],["lunora backup list","List recorded snapshots"],["lunora backup list --format json","Same, as a single JSON document on stdout"],["lunora backup restore <id>","Restore a snapshot by id"],["lunora backup create --bucket default","Snapshot into an R2 bucket instead of a directory"],["lunora backup restore <id> --bucket default --verify","Restore from R2, checksum first"],["lunora backup retention","Show what the platform's retention would delete next"],["lunora backup prune","Delete the snapshots past the retention window (the only command that deletes backups)"],["lunora backup pitr --at 2026-06-01T00:00:00Z","Point-in-time recovery (≤30 days)"]],group:"Data",loader:()=>import("../packem_chunks/handler22.mjs").then(e=>({default:e.execute})),name:"backup",options:[{description:"Backup directory (default .lunora-backups)",name:"dir",type:String},{description:"Store snapshots in this R2 bucket instead of a directory (use `default` for the app's default bucket)",name:"bucket",type:String},{description:"Key prefix for bucket-backed snapshots (default backups/)",name:"prefix",type:String},{description:"restore: verify the snapshot's checksum before importing anything",name:"verify",type:Boolean},{description:"Comma-separated table allowlist (create)",name:"tables",type:String},i,{description:"pitr: time to read/restore to (ISO or epoch-ms, ≤30 days)",name:"at",type:String},{description:"pitr --restore: explicit bookmark to restore to (wins over --at)",name:"bookmark",type:String},{description:"pitr: perform a restore instead of just reading the bookmark",name:"restore",type:Boolean},{description:"pitr --restore: restart the shard now so recovery applies immediately",name:"restart",type:Boolean},{description:"pitr: target shard key (default: root shard)",name:"shard",type:String},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Confirm a destructive step without prompting: a production pitr --restore, or backup prune",name:"yes",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String}]},q={description:"Codegen + validate + bundle the Worker to disk without deploying",examples:[["lunora build","Bundle to .lunora/build without deploying"],["lunora build --out-dir dist-worker","Bundle to a custom directory"],["lunora build --emit-bindings bindings.json","Also write what the bundle needs provisioned, for an external deployer"]],group:"Deploy",loader:()=>import("../packem_chunks/handler20.mjs").then(e=>({default:e.execute})),name:"build",options:[{description:"Override the schema-drift gate for this run (build even with breaking schema drift and no migration; the committed baseline is not advanced)",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Write a JSON manifest of the bindings + crons the bundle needs to this path, for an IaC program to consume",name:"emit-bindings",type:String},i,{description:"Directory to write the bundled Worker to (default .lunora/build)",name:"out-dir",type:String},{description:"Fail the build on ERROR-level codegen advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail the build on ERROR-level codegen advisories (the gate defaults to on in CI, off locally). Never downgrades platform diagnostics.",name:"no-strict-advisories",type:Boolean},l]},z={description:"Run codegen for lunora/ functions and schema",examples:[["lunora codegen","Generate lunora/_generated/ from your schema + functions"]],group:"Develop",loader:()=>import("../packem_chunks/runCodegenCommand.mjs").then(e=>({default:e.execute})),name:"codegen",options:[{description:`Which API spec(s) to emit: ${p} (default openapi)`,name:"api-spec",type:String},i,{description:"Fail on ERROR-level advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail on ERROR-level advisories (the gate defaults to on in CI, off locally)",name:"no-strict-advisories",type:Boolean},l]},Y={argument:{description:"<build|push|images|list|info|delete> [args…]",name:"args",type:String},description:"Build/push container images and manage container instances (wraps wrangler containers)",examples:[["lunora containers build ./containers/transcoder --tag transcoder:v1","Build a container image with the local Docker engine"],["lunora containers build ./containers/transcoder --tag transcoder:v1 --push","Build and push to the Cloudflare Registry in one step"],["lunora containers push transcoder:v1","Push a locally-tagged image to the Cloudflare Registry"],["lunora containers images list","List images in your Cloudflare Registry"],["lunora containers list --format json","List container instances as JSON (also `info`, `images list`)"],["lunora containers images delete transcoder:v1","Delete an image to free registry storage"]],group:"Deploy",loader:()=>import("../packem_chunks/handler3.mjs").then(e=>({default:e.execute})),name:"containers",options:[{description:"build: push the image to the Cloudflare Registry after building",name:"push",type:Boolean},{description:"build: name:tag for the image (forwarded to wrangler --tag)",name:"tag",type:String},{description:"Cloudflare environment name",name:"env",type:String},{...i,description:"Output format: pretty (default) or json (read subcommands: list | info | images list)"}]},Q={description:"Codegen, validate wrangler, then wrangler deploy",examples:[["lunora deploy","Deploy to Cloudflare"],["lunora deploy --env production","Deploy to a named environment"],["lunora deploy --dry-run","Validate + bundle without publishing"],["lunora deploy --migrate --migrate-yes --migrate-url <url>","Deploy, then run pending data migrations"]],group:"Deploy",loader:()=>import("../packem_chunks/runDeployCommand.mjs").then(e=>({default:e.execute})),name:"deploy",options:[{description:"Override the schema-drift gate for this run (deploy even with breaking schema drift and no migration; the committed baseline is not advanced — use --update-schema-baseline to accept the new shape)",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Validate, bundle, and run pre-deploy gates without publishing (wrangler deploy --dry-run)",name:"dry-run",type:Boolean},{description:"Cloudflare environment name",name:"env",type:String},i,{description:"After the deploy, probe the new version's health route (/_lunora/health/ready, falling back to /_lunora/health) and fail if it never answers",name:"health-check",type:Boolean},{description:"After a successful deploy, run pending data migrations against the live worker",name:"migrate",type:Boolean},{description:"Skip codegen + the schema-drift gate (assumes `lunora build`/`prepare` already ran in this CI run). Wrangler still bundles the worker.",name:"prebuilt",type:Boolean},{description:"Admin bearer token for --migrate (falls back to LUNORA_ADMIN_TOKEN)",name:"migrate-token",type:String},{description:"Worker URL for --migrate (REQUIRED with --migrate; the deploy target URL is not captured automatically)",name:"migrate-url",type:String},{description:"Confirm running the production data migration triggered by --migrate (required with --migrate)",name:"migrate-yes",type:Boolean},{description:"Fail the deploy on ERROR-level codegen advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail the deploy on ERROR-level codegen advisories (the gate defaults to on in CI, off locally). Never downgrades platform diagnostics.",name:"no-strict-advisories",type:Boolean},{description:"Upload a preview version (wrangler versions upload) instead of going live — prints a preview URL; doesn't shift production traffic",name:"preview",type:Boolean},l,{description:"Deploy to a temporary Cloudflare account when unauthenticated (wrangler deploy --temporary; live ~60min, then claim or it's deleted). Wrangler errors if you're already authenticated.",name:"temporary",type:Boolean},{description:"Re-bless the committed schema baseline (lunora/.lunora-schema.json) with the current shape",name:"update-schema-baseline",type:Boolean}]},X={argument:{description:"list | inspect <version-id> | rollback [version-id] | promote <version-id>",name:"subcommand",type:String},description:"List deployments and roll back / promote / inspect Worker versions",examples:[["lunora deployments list","Show the 10 most recent deployments"],["lunora deployments inspect <version-id>","View a specific Worker version"],["lunora deployments rollback --yes","Roll back to the previous version"],["lunora deployments promote <version-id> --yes","Send 100% of traffic to a version"]],group:"Deploy",loader:()=>import("../packem_chunks/handler4.mjs").then(e=>({default:e.execute})),name:"deployments",options:[{description:"Cloudflare environment name",name:"env",type:String},{...i,description:"Output format: pretty (default) or json (`list` only)"},{description:"Reason/description recorded with a rollback or promote",name:"message",type:String},{description:"Confirm a rollback or promote (required — these change live traffic)",name:"yes",type:Boolean}]},Z={argument:{description:"Optional subcommand: stop (shut the running dev server down) | status (report it) | logs (print its captured output)",name:"args",type:String},description:"Run the dev stack: wrangler worker + studio + codegen watch",examples:[["lunora dev","Run the worker + studio + codegen watch"],["lunora dev --background","Run detached: blocks until ready, prints URL + PID, then returns"],["lunora dev stop","Stop the background/tracked dev server (idempotent)"],["lunora dev status","Report the running dev server (URL, PID, uptime, ready/starting)"],["lunora dev status --json","Same as JSON — poll `.ready` to gate a dependent step in a task graph"],["lunora dev logs","Print the captured dev-server log (background runs)"],["lunora dev --json","Stream machine-readable JSON log LINES (a stream, not a --format json document)"],["lunora dev --emit-bindings dev-manifest.json","Write what this worker needs + where it serves, for a task runner"],["lunora dev --no-studio","Skip the embedded studio server"],["lunora dev --worker-port 8080","Use a custom wrangler dev port"],["lunora dev --inspector-port 9235","Pin wrangler's devtools inspector port instead of letting it walk up from 9229"],["lunora dev --remote","Proxy D1/KV/R2 to the deployed worker (also LUNORA_REMOTE=1)"]],group:"Develop",loader:()=>import("../packem_chunks/runDevCommand.mjs").then(e=>({default:e.execute})),name:"dev",options:[{description:`Which API spec(s) codegen emits: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Write the binding manifest (plus the dev origin) to <file>, for a supervisor that owns the rest of the graph",name:"emit-bindings",type:String},{description:"wrangler dev inspector port, for `wrangler dev` only (defaults to `dev.inspector_port` in wrangler.jsonc; unset, wrangler probes upward from 9229 and can take a sibling worker's pinned port)",name:"inspector-port",type:Number},{description:"Studio server port (default 6173)",name:"port",type:Number},l,{description:"wrangler dev port (default 8787)",name:"worker-port",type:Number},{description:"Run the dev server as a managed background process (auto-enabled when an AI agent is detected; LUNORA_AGENT_MODE=0 disables)",name:"background",type:Boolean},{description:"Machine-readable JSON log lines while the server runs, and a JSON result for `dev status`/`dev stop` (also LUNORA_LOG_JSON=1; auto-enabled for AI agents)",name:"json",type:Boolean},{description:"How many trailing lines `lunora dev logs` prints (default 100, 0 = all)",name:"lines",type:Number},{description:"Serve the embedded studio at /__lunora (default)",name:"studio",type:Boolean},{description:"Don't start the embedded studio server",name:"no-studio",type:Boolean},{description:"Spawn wrangler dev for the worker (default)",name:"worker",type:Boolean},{description:"Don't spawn wrangler dev — an external task runner owns the worker; codegen watch + studio still run",name:"no-worker",type:Boolean},{description:"Run codegen on startup and watch for changes (default)",name:"codegen",type:Boolean},{description:"Don't run codegen — no watch, no startup generate (or set LUNORA_CODEGEN=0)",name:"no-codegen",type:Boolean},{description:"Proxy D1/KV/R2 bindings to the deployed worker (or set LUNORA_REMOTE=1)",name:"remote",type:Boolean}]},ee={argument:{description:"Optional path under the docs site (e.g. packages/studio)",name:"section",type:String},description:"Open the Lunora docs in your browser (optional [section] path)",examples:[["lunora docs","Open the Lunora docs"],["lunora docs packages/studio","Open a specific docs section"]],group:"Project",loader:()=>import("../packem_chunks/handler5.mjs").then(e=>({default:e.execute})),name:"docs"},te={description:"Preflight the current Lunora project (wrangler bindings, placeholders, dev secrets)",examples:[["lunora doctor","Run the project preflight checks"],["lunora doctor --format json","Emit the findings as a machine-readable JSON document"]],group:"Project",loader:()=>import("../packem_chunks/handler6.mjs").then(e=>({default:e.execute})),name:"doctor",options:[i]},re={argument:{description:"list | get <KEY> | set <KEY> <VALUE> | unset <KEY> | generate [KEY] | push | diff | doctor",name:"subcommand",type:String},description:"Manage .dev.vars and sync secrets via wrangler (list | get | set | unset | generate | push | diff | doctor)",examples:[["lunora env list","List .dev.vars keys"],["lunora env set API_KEY secret","Set a local variable"],["lunora env generate","Generate strong values for the project's secrets (print KEY=value)"],["lunora env generate AUTH_SECRET --set","Generate one secret and write it to .dev.vars"],["lunora env push --yes","Upload secrets to Cloudflare"],["lunora env diff","Compare local .dev.vars keys against Cloudflare"],["lunora env diff --format json","Same, as a single JSON document on stdout"]],group:"Data",loader:()=>import("../packem_chunks/handler7.mjs").then(e=>({default:e.execute})),name:"env",options:[{description:"Target this Cloudflare environment for `push`/`diff` (passes --env <name> to wrangler)",name:"env",type:String},{description:"Alias for --env production",name:"prod",type:Boolean},i,{description:"For `generate` — write the generated secrets into .dev.vars instead of printing them",name:"set",type:Boolean},{description:"Push secrets to a temporary-account deployment when unauthenticated (wrangler secret put --temporary). Errors if you're already authenticated.",name:"temporary",type:Boolean},{description:"Required for `push` — confirms uploading secrets to Cloudflare",name:"yes",type:Boolean}]},oe={description:"Run every *.eval.ts under evals/ via @lunora/testing's evaluate/agentHarness — no live worker needed",examples:[["lunora eval","Run every eval under evals/, print the aggregate table"],["lunora eval --threshold 0.8","Non-zero exit if any eval's average score falls below 0.8"],["lunora eval --dir evals/support --format json","Run a subset and emit a machine-readable result"]],group:"Develop",loader:()=>import("../packem_chunks/handler23.mjs").then(e=>({default:e.execute})),name:"eval",options:[{description:"Directory to discover *.eval.ts files under (default evals/)",name:"dir",type:String},i,{description:"Score gate every eval's average must meet ([0,1]); a per-eval `threshold` export wins over this for that eval",name:"threshold",type:Number}]},ne={argument:{description:"Optional path (alias for --out)",name:"path",type:String},description:"Stream NDJSON of every shard-local + global table from the worker",examples:[["lunora export --out backup.ndjson","Dump every table to an NDJSON file"],["lunora export --tables messages,users","Export only specific tables"],["lunora export --out backup.ndjson --format json","Write the dump to a file and report rows/bytes as JSON"]],group:"Data",loader:()=>import("../packem_chunks/handler8.mjs").then(e=>({default:e.execute})),name:"export",options:[{description:"Output file path (`-` for stdout, default)",name:"out",type:String},{description:"Comma-separated table allowlist",name:"tables",type:String},{...i,description:"Output format: pretty (default) or json — json needs --out <file>, since stdout carries the NDJSON"},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String}]},ae={argument:{description:"Source NDJSON file, or a `npx convex export --path <dir>` directory",name:"file",type:String},description:"Bulk-insert rows from an NDJSON file — or a Convex export directory — via the worker's admin endpoint",examples:[["lunora import backup.ndjson","Bulk-insert rows from an NDJSON file"],["lunora import ./convex-export","Import a `npx convex export --path` directory (ids are preserved, so no remapping)"],["lunora import ./convex-export --with-storage","Also migrate blobs (verified sha256 upload) + `{ $storage }` refs"],["lunora import ./convex-export --scan","Write a candidate `lunora/import-convex.json` storage-column mapping (imports nothing)"],["lunora import ./snapshot.zip --with-storage --verify","Import a `npx convex export --path` zip snapshot with blob + row-parity checks"],["lunora import ./supabase-csv --from supabase","Import a directory of `COPY … TO STDOUT WITH CSV HEADER` dumps"],["lunora import ./firestore-json --from firebase --verify","Import Firestore documents (REST/Admin-SDK JSON) with row-parity checks"]],group:"Data",loader:()=>import("../packem_chunks/handler9.mjs").then(e=>({default:e.execute})),name:"import",options:[{description:"Source reader for a dump that cannot be detected: supabase | firebase (Convex and NDJSON are auto-detected)",name:"from",type:String},{description:"Wrap each bare doc as `{table:<name>,doc:...}`",name:"table",type:String},i,{description:"Rows per HTTP request (default 500)",name:"batch-size",type:Number},{description:"Also migrate file storage — Convex `_storage` blobs, or a Supabase/Firebase bucket (verified upload)",name:"with-storage",type:Boolean},{description:"Directory of storage objects to upload alongside the rows (Firebase: after `gcloud storage cp -r`)",name:"storage-dir",type:String},{description:"Write a candidate `lunora/import-convex.json` storage-column mapping and exit",name:"scan",type:Boolean},{description:"Verify row parity + dangling-storage after import (non-zero exit on mismatch)",name:"verify",type:Boolean},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Confirm bulk-writing production (required with --prod)",name:"yes",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String}]},ie={description:"Print resolved project config: @lunora/* versions, wrangler summary, schema overview",examples:[["lunora info","Print resolved project config"],["lunora info --format json","Emit a JSON snapshot"],["lunora info --bindings","List what this Worker needs provisioned: bindings, crons, vars"],["lunora info --bindings --format json","Emit the manifest a deployer or task runner consumes"],["lunora info --bindings --out reqs.json","Write that manifest to a file"]],group:"Project",loader:()=>import("../packem_chunks/handler10.mjs").then(e=>({default:e.execute})),name:"info",options:[{description:"Report only what this Worker needs provisioned, as the binding manifest",name:"bindings",type:Boolean},i,{description:"With --bindings: write the manifest to <file> instead of stdout",name:"out",type:String}]},se={argument:{description:"Project name",name:"name",type:String},description:"Scaffold a new Lunora project",examples:[["lunora init my-app","Scaffold with the default (vite) template"],["lunora init my-app -t next","Scaffold a Next.js app"],["lunora init my-app -t tanstack-start-react","Scaffold a TanStack Start (React) app"],["lunora init my-app -t tanstack-start-solid","Scaffold a TanStack Start (Solid) app"],["lunora init my-app -t solid-v2","Scaffold a Solid 2.0 SPA"],["lunora init my-app -t rspack-react","Scaffold a React SPA on Rsbuild"],["lunora init my-app --ref alpha","Scaffold from the alpha branch's templates"],["lunora init --here","Add Lunora to the current project"],["lunora init my-app --ci github","Scaffold + add a GitHub Actions deploy pipeline"],["lunora init my-app --ci gitlab","Scaffold + add a GitLab CI deploy pipeline"]],group:"Project",loader:()=>import("../packem_chunks/runInitCommand.mjs").then(e=>({default:e.execute})),name:"init",options:[{alias:"t",description:"Template: analog | astro | expo | next | nuxt | react-router | rspack-react | solid-v2 | standalone | sveltekit | tanstack-start-react | tanstack-start-react-rspack | tanstack-start-solid | vinext | vinext-pages. Also accepts an overlay framework (react | vue | solid | svelte), same as --vite.",name:"template",type:String},{description:"Scaffold via the create-vite overlay for a framework (react | vue | solid | svelte | vanilla) — official create-vite base + Lunora layer",name:"vite",type:String},{description:"Local templates root to copy from (offline-friendly; expects <type>/ subdirs)",name:"from",type:String},{description:"Override the remote template source (e.g. gh:owner/repo/sub#ref)",name:"source",type:String},{description:"Fetch templates from a git ref (branch, tag, or commit), e.g. --ref alpha. Overrides the version-derived default",name:"ref",type:String},{description:"Permit --source values outside gh:/github:/https:// (e.g. local file://)",name:"allow-unsafe-source",type:Boolean},{description:"Add Lunora to the current project: detect the framework, patch the config, scaffold lunora/, print per-framework wiring steps",name:"here",type:Boolean},{alias:"i",description:"After scaffolding, offer to add auth + email (defaults on when stdin is a TTY)",name:"interactive",type:Boolean},{alias:"y",description:"Skip the auth/email offer; scaffold only",name:"yes",type:Boolean},{description:"Also scaffold a CI deploy pipeline: github (.github/workflows/deploy.yml) or gitlab (.gitlab-ci.yml)",name:"ci",type:String},{description:"Add features non-interactively after scaffolding (comma-separated): ai | auth | auth-ui | backup | browser | cloudflare-access | crons | email | flags | hyperdrive | payment | presence | queue | storage | workflow",name:"add",type:String},{description:"Walk through every step (prompts + output) without writing files, installing, or running git",name:"dry-run",type:Boolean}]},le={description:"Report write-conflict hot-spots, error rates, and latency outliers from a running Worker",examples:[["lunora insights","Report against the local dev worker"],["lunora insights --shard channel:demo","Scope the report to one shard"],["lunora insights --format json","Emit the raw report as JSON"],["lunora insights --prod --url https://app.example.com --token $LUNORA_ADMIN_TOKEN","Report against production"]],group:"Develop",loader:()=>import("../packem_chunks/handler11.mjs").then(e=>({default:e.execute})),name:"insights",options:[{description:"Explicit shard key (defaults to the root shard)",name:"shard",type:String},{description:"Max rows per section (default 10)",name:"limit",type:String},i,{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (or LUNORA_ADMIN_TOKEN)",name:"token",type:String}]},de={description:"Scaffold lunora/schema.ts (and list/get procedures) from an existing Postgres or MySQL database",examples:[["lunora introspect --url postgres://localhost/shop","Scaffold a schema + procedures from every table"],["lunora introspect --tables users,orders","Introspect only these tables (DATABASE_URL is read by default)"],["lunora introspect --dry-run","Print what would be written without touching the filesystem"],["lunora introspect --no-procedures --force","Regenerate just the schema, overwriting the existing file"]],group:"Data",loader:()=>import("../packem_chunks/handler25.mjs").then(e=>({default:e.execute})),name:"introspect",options:[{description:"Database connection string (default: $DATABASE_URL)",name:"url",type:String},{description:"Postgres schema (default `public`) or MySQL database name",name:"schema",type:String},{description:"Comma-separated table allow-list (default: every base table)",name:"tables",type:String},{description:"Also emit list/get procedure modules per table (the default)",name:"procedures",type:Boolean},{description:"Emit only the schema — skip the per-table list/get procedure modules",name:"no-procedures",type:Boolean},{description:"Overwrite files that already exist",name:"force",type:Boolean},{description:"Print what would be written without writing it",name:"dry-run",type:Boolean},i]},pe={description:"Link this checkout to its deployed Worker (writes .lunora/project.json)",examples:[["lunora link --url https://app.acme.workers.dev","Link to a deployed Worker URL"],["lunora link --url https://app.acme.workers.dev --env production","Link a named environment"],["lunora link --remove","Remove the link"]],group:"Deploy",loader:()=>import("../packem_chunks/handler12.mjs").then(e=>({default:e.execute})),name:"link",options:[{description:"Cloudflare environment name to record alongside the link",name:"env",type:String},{description:"Worker name (defaults to the `name` in wrangler config)",name:"name",type:String},{description:"Remove the existing link (.lunora/project.json)",name:"remove",type:Boolean},{description:"Deployed Worker URL to link (e.g. https://app.acme.workers.dev)",name:"url",type:String}]},ce={argument:{description:"Worker name (defaults to the name in wrangler config)",name:"worker",type:String},description:"Stream live logs from a deployed Worker, or read the durable log archive with --durable",group:"Deploy",loader:()=>import("../packem_chunks/handler24.mjs").then(e=>({default:e.execute})),name:"logs",options:[{description:"Cloudflare environment name",name:"env",type:String},i,{description:"Substring filter on log messages",name:"search",type:String},{description:"Filter by invocation status: ok, error, or canceled",name:"status",type:String},l,{description:"Tail a temporary-account deployment when unauthenticated (wrangler tail --temporary). Errors if you're already authenticated.",name:"temporary",type:Boolean},{description:"Read the durable log archive (pipelineLogSink → R2) via R2 SQL instead of tailing live",name:"durable",type:Boolean},{description:"durable: Iceberg table the Pipeline writes to (required with --durable)",name:"table",type:String},{description:"durable: Iceberg namespace (R2 Data Catalog database) the table lives in",name:"namespace",type:String},{description:"durable: lower time bound (epoch-millis or ISO 8601), inclusive",name:"since",type:String},{description:"durable: upper time bound (epoch-millis or ISO 8601), inclusive",name:"until",type:String},{description:"durable: exact severity filter (trace|debug|log|info|warn|error|fatal)",name:"level",type:String},{description:"durable: severity floor — this level and every more-severe one",name:"min-level",type:String},{description:"durable: keep function paths starting with this prefix (LIKE 'prefix%')",name:"function-prefix",type:String},{description:"durable: trace-id filter",name:"trace-id",type:String},{description:"durable: shard-key filter",name:"shard-key",type:String},{description:"durable: user-id filter",name:"user-id",type:String},{description:"durable: max rows (clamped to 1–10000; default 500)",name:"limit",type:String},{description:"durable: resume after a prior page — the opaque cursor token printed by the previous page (bare epoch-millis also accepted for back-compat)",name:"cursor",type:String},{description:"durable: emit one JSON object per line instead of a table",name:"ndjson",type:Boolean}]},ue={argument:{description:"install [client…] | uninstall [client…] | serve",name:"args",type:String},description:"Connect your AI editor to Lunora over MCP (docs search + this project's dev server)",examples:[["lunora mcp install","Install into every MCP client already configured here"],["lunora mcp install claude-code cursor","Install into specific clients"],["lunora mcp install --list","List the supported clients and their config files"],["lunora mcp install --docs-only","Install only the hosted documentation server"],["lunora mcp install --print","Show the config that would be written, without writing it"],["lunora mcp install --global","Force every server into the machine-wide config"],["lunora mcp uninstall","Remove Lunora's MCP servers from every supported client"],["lunora mcp uninstall cursor","Remove them from one client"],["lunora mcp uninstall --print","Show what would be removed, without removing it"],["lunora mcp serve","Run the stdio MCP server (this is what your editor spawns)"],["lunora mcp serve --allow-writes","Also expose the mutation/action tools"],["lunora mcp serve --token $LUNORA_ADMIN_TOKEN","Expose the observability tools (logs, issues, advisories, insights, migrations) too"]],group:"Develop",loader:()=>import("../packem_chunks/handler26.mjs").then(e=>({default:e.execute})),name:"mcp",options:[{description:"install: replace entries that already exist",name:"force",type:Boolean},{description:"install: list the supported clients and their config files",name:"list",type:Boolean},{description:"install/uninstall: print what would change instead of writing it",name:"print",type:Boolean},{description:"install/uninstall: only the hosted documentation server",name:"docs-only",type:Boolean},{description:"install/uninstall: only this project's local server",name:"local-only",type:Boolean},{description:"install/uninstall: the machine-wide config (install default: docs server global, local server per-project)",name:"global",type:Boolean},{description:"install/uninstall: this project's config instead of the machine-wide one",name:"project",type:Boolean},{description:"serve: also expose the mutation/action tools (default: read-only)",name:"allow-writes",type:Boolean},{description:"serve: expose the documentation tools (default)",name:"docs",type:Boolean},{description:"serve: skip the documentation tools",name:"no-docs",type:Boolean},{description:"Docs site origin backing the documentation tools (default https://lunora.sh)",name:"docs-url",type:String},{description:"serve: deployment URL to expose (default: the running dev server)",name:"url",type:String},{description:"serve: bearer token (default: LUNORA_ADMIN_TOKEN from the environment or .dev.vars). Also gates the observability tools (logs, issues, advisories, query insights, migration status) — without a token they are not exposed at all",name:"token",type:String}]},me={argument:{description:"generate | create | up | down | status | d1-to-hyperdrive [name|id]",name:"subcommand",type:String},description:"Schema (generate), online data (create | up | down | status), and backend (d1-to-hyperdrive) migrations",examples:[["lunora migrate generate","Diff lunora/schema.ts and emit a SQL migration"],["lunora migrate create add_users_email","Scaffold a data migration"],["lunora migrate up backfill-names","Run a data migration across shards"],["lunora migrate status backfill-names","Report a migration's per-shard status"],["lunora migrate status backfill-names --format json","Same, as a single JSON document on stdout"],["lunora migrate d1-to-hyperdrive --from-url https://old --to-url https://new","Copy .global() data from D1 to Hyperdrive"]],group:"Data",loader:()=>import("../packem_chunks/dispatch.mjs").then(e=>({default:e.execute})),name:"migrate",options:[{description:"Migration name slug (e.g. add_users_email)",name:"name",type:String},{description:"Target table for `create` (prompted for interactively when omitted)",name:"table",type:String},{description:"Preview a data migration without rewriting rows",name:"dry-run",type:Boolean},i,{description:"Rows per batch for a data migration",name:"batch-size",type:Number},{description:"Cap batches processed this run (maps to the runner's maxBatches)",name:"steps",type:Number},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String},{description:"Required with --prod for up/down — confirms running against production",name:"yes",type:Boolean},{description:"d1-to-hyperdrive: source (D1) worker URL (defaults to --url)",name:"from-url",type:String},{description:"d1-to-hyperdrive: source admin token (defaults to --token / LUNORA_ADMIN_TOKEN)",name:"from-token",type:String},{description:"d1-to-hyperdrive: target (Hyperdrive) worker URL (defaults to --url)",name:"to-url",type:String},{description:"d1-to-hyperdrive: target admin token (defaults to --token / LUNORA_ADMIN_TOKEN)",name:"to-token",type:String},{description:"d1-to-hyperdrive: comma-separated .global() tables to move (default: all global tables)",name:"tables",type:String},{description:"d1-to-hyperdrive: keep the intermediate NDJSON dump at this path",name:"out",type:String}]},ge={description:"Run codegen + binding reconcile + wrangler validation (no Vite) — for CI",examples:[["lunora prepare","Codegen + binding reconcile + validate (CI, before deploy)"]],group:"Deploy",loader:()=>import("../packem_chunks/handler13.mjs").then(e=>({default:e.execute})),name:"prepare",options:[{description:"Override the schema-drift gate for this run (proceed even with breaking schema drift and no migration; the committed baseline is not advanced)",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Fail on ERROR-level codegen advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail on ERROR-level codegen advisories (the gate defaults to on in CI, off locally). Never downgrades platform diagnostics.",name:"no-strict-advisories",type:Boolean},l,{description:"Re-bless the committed schema baseline (lunora/.lunora-schema.json) with the current shape",name:"update-schema-baseline",type:Boolean}]},he={argument:{description:"<add|list|view|build> [item names…]",name:"args",type:String},description:"Component registry: add/list/view items, or build the catalog",examples:[["lunora registry list","List available registry items"],["lunora registry add presence","Scaffold a registry item into lunora/"],["lunora registry build --from ./registry --check","Verify the committed catalog is current"]],group:"Project",loader:()=>import("../packem_chunks/handler14.mjs").then(e=>({default:e.execute})),name:"registry",options:[{description:"add: print the plan and stop without writing",name:"dry-run",type:Boolean},{description:"add: preview the file changes (content diff) and write nothing",name:"diff",type:Boolean},{description:"add: force-overwrite existing files (take the incoming copy)",name:"overwrite",type:Boolean},{description:"add: skip the package.json mutation confirmation prompt",name:"yes",type:Boolean},{description:"Local registry root (offline; expects <name>/ subdirs)",name:"from",type:String},{description:"Override the remote registry source base (e.g. gh:owner/repo/registry)",name:"source",type:String},{description:"Fetch items from a git ref (branch, tag, or commit), e.g. --ref alpha. Overrides the version-derived default",name:"ref",type:String},{description:"Permit --source values outside gh:/github:/https://",name:"allow-unsafe-source",type:Boolean},{...i,description:"Output format: pretty (default) or json (add plan / list)"},{description:"build: output path for the catalog (default <root>/index.json)",name:"out",type:String},{description:"build: verify the index is current instead of rewriting it",name:"check",type:Boolean}]},fe={description:"Clear local Miniflare state (and .lunora-cache with --all)",examples:[["lunora reset","Clear local Miniflare state"],["lunora reset --all","Also remove .lunora-cache"]],group:"Develop",loader:()=>import("../packem_chunks/runResetCommand.mjs").then(e=>({default:e.execute})),name:"reset",options:[{description:"Also remove .lunora-cache",name:"all",type:Boolean},{description:"Skip the confirmation prompt (required when stdin is not a TTY)",name:"yes",type:Boolean}]},ye={argument:{description:"install | check",name:"subcommand",type:String},description:"Install the Lunora agent skills (AI rules) into .agents/skills/, or check they're present",examples:[["lunora rules install","Copy the Lunora agent skills into .agents/skills/"],["lunora rules install --overwrite","Reinstall, replacing edited skill files"],["lunora rules check","Report which Lunora skills are installed"],["lunora rules check --strict","Exit non-zero when rules are missing (CI gate)"],["lunora rules install --dir packages/app","Install into a specific root instead of the workspace root"]],group:"Project",loader:()=>import("../packem_chunks/handler15.mjs").then(e=>({default:e.execute})),name:"rules",options:[{description:"Install/check root (default: the detected workspace root, not the current directory)",name:"dir",type:String},{description:"install: overwrite skill files that already exist (default: skip them)",name:"overwrite",type:Boolean},{description:"check: exit non-zero when the rules are missing (for CI gating)",name:"strict",type:Boolean}]},ve={argument:{description:"Function path (e.g. messages:send)",name:"functionPath",type:String},description:"Send a single RPC to a running Lunora Worker",examples:[[`lunora run messages:send --args '{"text":"hi"}'`,"Call a function with JSON args"],["lunora run messages:list --shard channel:demo","Target a specific shard"],["lunora run messages:list --as user_123","Run as an authenticated user (needed when the app gates on identity)"],["lunora run messages:list --format json","Emit the RPC result as a single JSON document on stdout"]],group:"Develop",loader:()=>import("../packem_chunks/runRpcCommand.mjs").then(e=>({default:e.execute})),name:"run",options:[{description:"JSON-encoded args object",name:"args",type:String},{description:"Run as this user id — dispatches through the admin-gated `runAs` op so identity-gated apps accept the call",name:"as",type:String},{description:`JSON-encoded extra identity claims to forge alongside --as (e.g. '{"org":"acme"}')`,name:"claims",type:String},{description:"Explicit shard key",name:"shard",type:String},i,{description:"Worker URL (defaults to the running dev server, else http://localhost:8787)",name:"url",type:String},{description:"Admin bearer for --as (prefer LUNORA_ADMIN_TOKEN or .dev.vars; --token is visible to other local processes via the process table)",name:"token",type:String}]},be={argument:{description:"<generate>",name:"args",type:String},description:"Generate a self-contained typed client SDK for another language from the project's OpenRPC surface",examples:[["lunora sdk generate --lang python","Emit a Python SDK, transport included, into ./sdk/python"],["lunora sdk generate --lang go --out ./clients/go","Choose the language and output directory"],["lunora sdk generate --lang dart","A Flutter-ready Dart client — live queries arrive as a Stream"],["lunora sdk generate --lang kotlin","Any of the registered targets; --lang lists them"],["lunora sdk generate --lang rust --from ./sdks","Copy the transport from a local checkout instead of fetching it"]],group:"Project",loader:()=>import("../packem_chunks/handler21.mjs").then(e=>({default:e.execute})),name:"sdk",options:[{description:`Target language: ${P.join(" | ")}`,name:"lang",type:String},{description:"Output directory (default ./sdk/<lang>)",name:"out",type:String},{description:"Path to the OpenRPC document (default ./lunora/_generated/openrpc.json)",name:"spec",type:String},{description:"Copy the transport from a local directory of per-language transports (the repo's `sdks/`) instead of fetching it",name:"from",type:String},{description:"Git ref to fetch the transport from (default: this CLI's own release tag, so the transport matches the generated surface)",name:"ref",type:String},{description:"Override the remote transport source base (default gh:anolilab/lunora/sdks)",name:"source",type:String},{description:"Permit --source values outside gh:/github:/https://",name:"allow-unsafe-source",type:Boolean}]},we={description:"Generate deterministic fake data from lunora/schema.ts and bulk-insert it via the worker's admin endpoint",examples:[["lunora seed","Seed every table with the default row count"],["lunora seed --table posts --count 50","Seed 50 posts; FK-parent tables are seeded automatically"],["lunora seed --reset","Wipe local .wrangler/state, then seed from scratch"],["lunora seed --seed 7 --dry-run","Print the NDJSON for seed 7 without inserting"],["lunora seed --format json","Report generated / inserted / conflicts per table as JSON"],["lunora seed --seed 7 --now 1785000000000","Byte-identical rows across runs (pins the clock too)"]],group:"Data",loader:()=>import("../packem_chunks/handler16.mjs").then(e=>({default:e.execute})),name:"seed",options:[{description:"Rows per table (default 10)",name:"count",type:Number},{description:"Seed only this table; its FK-parent tables are seeded automatically",name:"table",type:String},{description:"Deterministic seed — same value yields identical rows (default 0)",name:"seed",type:Number},{description:"Epoch-ms reference for time columns (createdAt, expiresAt, …). Pin it with --seed for byte-identical rows across runs; defaults to now",name:"now",type:Number},{description:"Print the generated NDJSON instead of inserting",name:"dry-run",type:Boolean},i,{description:"Wipe local .wrangler/state before seeding (local dev only)",name:"reset",type:Boolean},{description:"Rows per HTTP request (default 500)",name:"batch-size",type:Number},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String},{description:"Skip the confirmation prompt when seeding a non-local/production target",name:"yes",type:Boolean}]},ke={description:"Validate wrangler.jsonc + codegen dry-run + tsc --noEmit (no files written)",examples:[["lunora verify","Validate wrangler + codegen + tsc"],["lunora verify --no-typecheck","Skip the TypeScript type-check"],["lunora verify --health-url https://my-app.workers.dev","Also probe the deployment's /_lunora/health"],["lunora verify --env production","Validate the env.production view, as `lunora deploy --env production` will"]],group:"Deploy",loader:()=>import("../packem_chunks/handler17.mjs").then(e=>({default:e.execute})),name:"verify",options:[{description:"Treat breaking schema drift as a warning instead of a failure",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Cloudflare environment name — validate the env.<name> view of wrangler.jsonc, as `lunora deploy --env` does",name:"env",type:String},i,{description:"Probe this deployment's /_lunora/health endpoint (off by default; keeps verify offline-safe)",name:"health-url",type:String},{description:"Fail verification on ERROR-level codegen advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail verification on ERROR-level codegen advisories (the gate defaults to on in CI, off locally). Never downgrades platform diagnostics.",name:"no-strict-advisories",type:Boolean},{description:"Run the TypeScript type-check step (default)",name:"typecheck",type:Boolean},{description:"Skip the TypeScript type-check step",name:"no-typecheck",type:Boolean},l]},Se={description:"Open the Lunora studio in your browser (the running dev server's, or the default local one)",examples:[["lunora view","Open the studio for the running dev server"]],group:"Project",loader:()=>import("../packem_chunks/handler18.mjs").then(e=>({default:e.execute})),name:"view"},xe=(e,t)=>{const r=Array.from({length:t.length+1},(o,n)=>n);for(let o=1;o<=e.length;o+=1){let n=r[0]??0;r[0]=o;for(let a=1;a<=t.length;a+=1){const s=r[a]??0,c=e[o-1]===t[a-1]?0:1;r[a]=Math.min((r[a-1]??0)+1,s+1,n+c),n=s}}return r[t.length]??0},Re=(e,t)=>{let r,o=Number.POSITIVE_INFINITY;for(const a of t){const s=xe(e,a);s<o&&(o=s,r=a)}const n=Math.max(2,Math.ceil(e.length/3));return r!==void 0&&o<=n?r:void 0},Ce=e=>`https://registry.npmjs.org/@lunora/cli/${e}`,Ne=1440*60*1e3,Oe=1500,Ae="0.0.0",De=/^v/u,Be=new Set(["alpha","beta","next"]),g=e=>{const t=e.trim().replace(De,""),r=t.indexOf("-");return r===-1?{core:t,prerelease:""}:{core:t.slice(0,r),prerelease:t.slice(r+1)}},w=e=>{const[t,r,o]=g(e).core.split(".").map(n=>{const a=Number.parseInt(n,10);return Number.isFinite(a)?a:0});return[t??0,r??0,o??0]},Ee=(e,t)=>{const r=Number.parseInt(e,10),o=Number.parseInt(t,10);return String(r)===e&&String(o)===t?r>o?1:-1:e>t?1:-1},Le=(e,t)=>{if(e===t)return 0;if(e===""||t==="")return e===""?1:-1;const r=e.split("."),o=t.split(".");for(let n=0;n<Math.max(r.length,o.length);n+=1){const a=r[n],s=o[n];if(a===void 0||s===void 0)return a===void 0?-1:1;if(a!==s)return Ee(a,s)}return 0},Ie=(e,t)=>{const r=w(e),o=w(t);for(let n=0;n<3;n+=1)if((r[n]??0)!==(o[n]??0))return(r[n]??0)>(o[n]??0)?1:-1;return Le(g(e).prerelease,g(t).prerelease)},je=e=>{const t=g(e).prerelease.split(".")[0]??"";return Be.has(t)?t:"latest"},Te=(e,t)=>Ie(t,e)>0,_e=(e,t,r)=>t-e<r,Pe=(e,t,r="latest",o)=>{const n=`Update available for @lunora/cli: ${e} → ${t}`;if(o===void 0)return`${n} — add @lunora/cli@${r} as a dev dependency to update`;const{args:a,command:s}=F(o,[`@lunora/cli@${r}`],{dev:!0});return`${n} — run \`${s} ${a.join(" ")}\``},R=e=>m(e,"lunora-cli-update.json"),Ue=e=>{const t=e.XDG_CACHE_HOME&&e.XDG_CACHE_HOME.length>0?e.XDG_CACHE_HOME:m(J(),".cache"),r=m(t,"lunora");try{A(r,{mode:448,recursive:!0})}catch{}return r},Me=e=>{try{const t=JSON.parse(S(R(e),"utf8"));if(t!==null&&typeof t=="object"){const{checkedAt:r,latest:o}=t;if(typeof o=="string"&&typeof r=="number"){const{tag:n}=t;return{checkedAt:r,latest:o,...typeof n=="string"?{tag:n}:{}}}}}catch{}},k=(e,t)=>{try{const r=R(e);try{if(D(r).isSymbolicLink())return}catch{}B(r,`${JSON.stringify(t)}
|
|
2
|
+
`,"utf8")}catch{}},We=async(e,t)=>{try{const r=await e(Ce(t),{signal:AbortSignal.timeout(Oe)});if(!r.ok)return;const o=await r.json(),n=o!==null&&typeof o=="object"?o.version:void 0;return typeof n=="string"?n:void 0}catch{return}},Je=(e,t,r)=>e===Ae||!r||t.CI!==void 0||t.LUNORA_NO_UPDATE_NOTIFIER!==void 0,Fe=async e=>{const t=e.env??process.env,r=e.isTTY??process.stdout.isTTY;if(Je(e.current,t,r))return;const o=e.cacheDir??Ue(t),n=(e.now??Date.now)(),a=e.ttlMs??Ne,s=je(e.current),c=Me(o),O=c?.tag??"latest",h=c!==void 0&&O===s?c:void 0;let u=h?.latest;if(h===void 0||!_e(h.checkedAt,n,a)){const f=await We(e.fetchImpl??globalThis.fetch,s);f===void 0?k(o,{checkedAt:n,latest:e.current,tag:s}):(u=f,k(o,{checkedAt:n,latest:f,tag:s}))}u!==void 0&&Te(e.current,u)&&e.logger.warn(Pe(e.current,u,s,e.manager))},Ke=["init","add","dev","codegen","build","deploy","containers","prepare","link","deployments","logs","run","insights","reset","migrate","export","import","seed","backup","eval","verify","info","doctor","env","analyze","view","docs","registry","rules","mcp"],He=8,$e=()=>{try{let e=y(E(import.meta.url));for(let t=0;t<He;t+=1){try{const o=JSON.parse(S(m(e,"package.json"),"utf8")),n=o!==null&&typeof o=="object"?o:void 0;if(n?.name==="@lunora/cli"&&typeof n.version=="string"&&n.version.length>0)return n.version}catch{}const r=y(e);if(r===e)break;e=r}}catch{}return"0.0.0"},C=$e(),Ve=[se,H,Z,z,$,q,Q,Y,ge,pe,X,ce,ve,le,fe,me,ne,ae,we,de,G,oe,ke,ie,te,re,V,Se,ee,he,ye,ue,be],N=[...Ve,_,T],gt=N.map(e=>e.name),d=e=>e.replaceAll("{",String.raw`\{`).replaceAll("}",String.raw`\}`),Ge=e=>e.every(t=>typeof t=="string")?e.map(t=>d(t)):e.map(t=>typeof t=="string"?[d(t)]:t.map(r=>d(r))),qe=e=>({...e,...e.argument===void 0?{}:{argument:{...e.argument,description:d(e.argument.description??"")}},...e.description===void 0?{}:{description:d(e.description)},...e.examples===void 0?{}:{examples:Ge(e.examples)},...e.options===void 0?{}:{options:e.options.map(t=>({...t,description:d(t.description??"")}))}}),ze=e=>{const t={value:0},r=j("lunora",{argv:e.argv===void 0?void 0:[...e.argv],cwd:e.cwd,exit:o=>{t.value=typeof o=="number"?o:0},logger:e.logger,packageName:"@lunora/cli",packageVersion:C});for(const o of N)r.addCommand(qe(o));return{cli:r,exitCode:t}},Ye=/Command "(?<name>[^"]+)" not found/u,Qe=e=>{const t=x(),r=e instanceof Error?e.message:String(e),o=Ye.exec(r);if(!o?.groups)return L(e)||I(r)!==void 0?t.error(W(e)):t.error(r),U(e);const n=o.groups.name??"",a=Re(n,Ke);return t.error(`Unknown command "${n}".${a===void 0?"":` Did you mean "${a}"?`}`),t.info("Run `lunora --help` to list commands, or `lunora docs` to open the documentation."),M.USAGE},Xe=e=>({debug:t=>{e.debug(t)},error:t=>{e.error(t)},info:t=>{e.info(t)},success:t=>{e.info(t)},warn:t=>{e.warn(t)}}),ht=async(e={})=>{const{cli:t,exitCode:r}=ze(e);e.logger!==void 0&&v(Xe(e.logger));try{await t.run({shouldExitProcess:!1})}catch(n){return Qe(n)}finally{v(void 0)}let o;try{o=K(process.cwd())}catch{}return await Fe({current:C,logger:x(),manager:o}),r.value};export{Ke as C,b as D,gt as R,C as V,ht as r};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{isLunoraError as p,findSolutionByMessage as d}from"@lunora/errors";import{EXIT_CODE as c,exitCodeForError as f}from"./EXIT_CODE-08cwt3MK.mjs";import{createLogger as g}from"./createLogger-Cl18I8AX.mjs";import{p as u,l as E,a as C}from"./output-format-B4eQHi5y.mjs";import{P as L}from"./prompt-cancelled-BvsNxg_Q.mjs";import{r as F}from"./render-lunora-error-DgaSmNLc.mjs";const m=(t,r)=>{t!=="json"||r.delegated===!0||C({code:r.code,data:r.data,error:r.error})},O=t=>async r=>{const s=g(),a=u(r.commandName,r.options.format);if("error"in a){s.error(a.error),r.process.exit(c.USAGE);return}const{format:o}=a;try{const e=await t({argument:r.argument,cwd:r.process.cwd,format:o,logger:E(o,s),options:r.options});m(o,e),r.process.exit(e.code)}catch(e){if(e instanceof L){r.process.exit(c.CANCELLED);return}const n=e instanceof Error?e.message:String(e),i=f(e);s.error(p(e)||d(n)!==void 0?F(e):n),m(o,{code:i,error:n}),r.process.exit(i)}};export{O as d};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync as p,readFileSync as b,writeFileSync as S}from"node:fs";import{parseSchemaSnapshot as w,SchemaSnapshotParseError as y,evaluateSchemaDrift as k,serializeSchemaSnapshot as H}from"@lunora/codegen";const P=e=>{if(!p(e))return{status:"absent"};let r;try{r=b(e,"utf8")}catch{return{status:"corrupt"}}try{const a=w(r);return a===void 0?{status:"corrupt"}:{snapshot:a,status:"ok"}}catch(a){if(a instanceof y)return{status:"corrupt"};throw a}},v=(e,r)=>{S(e,H(r),"utf8")},$=e=>{const r=`schema-drift gate: the committed baseline ${e.snapshotPath} is unreadable or malformed, so schema drift cannot be checked. Fix it (e.g. resolve a merge conflict in lunora/.lunora-schema.json), or pass --update-schema-baseline to regenerate it from the current schema.`;return e.updateBaseline&&!e.readOnly?(e.logger.warn(`schema baseline was unreadable; regenerating from the current schema on success (--update-schema-baseline): ${e.snapshotPath}`),{blocked:!1,changes:[],reason:r,rebless:e.rebless}):(e.readOnly||e.logger.error(r),{blocked:!0,changes:[],reason:r})},O=(e,r)=>(r.readOnly||r.logger.error(e.reason),r.updateBaseline&&!r.readOnly?(r.logger.warn(`schema baseline will be re-blessed despite breaking drift on success (--update-schema-baseline): ${r.snapshotPath}`),{blocked:!1,changes:e.changes,reason:e.reason,rebless:r.rebless}):{blocked:!0,changes:e.changes,reason:e.reason}),E=e=>{const{allowDrift:r,codegen:a,command:h,logger:c,readOnly:i=!1,updateBaseline:t=!1}=e,s=a.schemaSnapshotPath,o=P(s),l={logger:c,readOnly:i,rebless:()=>{v(s,a.schemaSnapshot)},snapshotPath:s,updateBaseline:t};if(o.status==="corrupt")return $(l);const u=m=>k({allowDrift:m,baseline:o.status==="ok"?o.snapshot:void 0,command:h,current:a.schemaSnapshot,migrations:a.migrations}),n=u(r);if(n.blocked)return O(n,l);const g=r&&n.changes.length>0&&u(!1).blocked;return n.changes.length>0?(i||c.info(n.reason),g&&!t?(i||c.warn(`schema baseline left at its committed shape — --allow-schema-drift overrides this run only. Pass --update-schema-baseline to accept the new shape: ${s}`),{blocked:!1,changes:n.changes,reason:n.reason}):{blocked:!1,changes:n.changes,reason:n.reason,rebless:i?void 0:l.rebless}):{blocked:!1,changes:n.changes,reason:n.reason}},f="/_lunora/health",_="/_lunora/health/ready",T=(e,r=f)=>(e.endsWith("/")?e.slice(0,-1):e)+r,d=async(e,r,a)=>{let h={error:`health probe failed: no health path configured for ${e}`,url:e};for(const[c,i]of r.entries()){const t=T(e,i);let s;try{s=await a(t)}catch(o){const l=o instanceof Error?o.message:String(o);return{error:`health probe failed: could not reach ${t} (${l})`,url:t}}if(s.ok)return{url:t};if(h={error:`health probe failed: ${t} returned HTTP ${String(s.status)}`,url:t},s.status!==404||c===r.length-1)return h}return h},A=async e=>new Promise(r=>{setTimeout(r,e)}),F=async({attempts:e=1,baseUrl:r,delayMs:a=2e3,fetchImpl:h,paths:c=[f],sleep:i=A,timeoutMs:t=1e4})=>{const s=h??(u=>fetch(u,{signal:AbortSignal.timeout(t)})),o=Math.max(1,e);let l=await d(r,c,s);for(let u=1;u<o&&l.error!==void 0;u+=1)await i(a),l=await d(r,c,s);return l};export{_ as H,f as a,F as p,E as r};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{isProcessStreamLogger as o,createStderrLogger as e}from"./createLogger-Cl18I8AX.mjs";const n={description:"Output format: pretty (default) or json",name:"format",type:String},p=(r,t)=>t===void 0?{format:"pretty"}:t==="json"||t==="pretty"?{format:t}:{error:`${r}: unknown --format "${t}" — expected pretty | json`},a=(r,t)=>r==="json"&&o(t)?e():t,i=r=>{process.stdout.write(`${JSON.stringify(r,void 0,2)}
|
|
2
|
+
`)};export{n as O,i as a,a as l,p};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{existsSync as T,readFileSync as E,mkdirSync as re,openSync as N,closeSync as F,statSync as te,readSync as oe}from"node:fs";import{join as w,dirname as ne}from"node:path";import{targetRunsOwnDevServer as P,resolveProjectTarget as x,claimDevServerState as se,DEV_HANDOFF_ENV as ae,clearDevServerState as m,readDevServerState as y,readLiveDevServerState as C,isDevServerReady as A,detectFramework as M,readProjectDependencyNames as ie,DEV_LOG_FILE_ENV as ce,DEV_DAEMON_ENV as de,updateDevServerState as le,detectPackageManager as b,execArgsFor as U,isRecordedProcessCurrent as ue,DEV_LOG_FILE as ve,CODEGEN_ENV as j,isCodegenDisabled as ge,planToolchainInvocation as pe,toolchainExecArgs as V,resolveDeployDriver as G,DEV_VARS_FILE as W,runScriptCommand as fe,parseDevVariableEntries as me}from"@lunora/config";import{findWranglerFile as _,readWranglerJsonc as L,materializeRemoteWranglerConfig as we}from"@lunora/config/cloudflare";import{createServer as he}from"node:net";import{networkInterfaces as Se}from"node:os";import{spawnSync as D,spawn as ke}from"node:child_process";import{setTimeout as h}from"node:timers/promises";import{EXIT_CODE as B}from"./EXIT_CODE-08cwt3MK.mjs";import{a as p}from"./output-format-B4eQHi5y.mjs";import{spawnShellCompat as Ee}from"./createRecordingSpawner-sS7LEN7x.mjs";const Pe=12e4,K=250,ye=1e3,be="LUNORA_DEV_READY_TIMEOUT_MS",_e=e=>{if(e!==void 0)return e;const r=Number(process.env[be]??"");return Number.isFinite(r)&&r>0?r:Pe},Le=async(e,r)=>{try{const o=AbortSignal.timeout(ye);return await(await fetch(new URL("/_lunora/status",e),{redirect:"manual",signal:r===void 0?o:AbortSignal.any([r,o])})).body?.cancel(),!0}catch{return!1}},De=1e4,Oe=100,Ae=40,f=256*1024,Re=new Set(["nuxt","sveltekit"]),Ie=["@lunora/rspack","@lunora/vite"],O=e=>{if(Re.has(M(e).framework))return"framework-worker";const r=ie(e);return Ie.some(o=>r.has(o))?"vite":"wrangler"},H=e=>{const r=b(e);let o;try{const t=E(w(e,"package.json"),"utf8");o=JSON.parse(t).scripts?.dev}catch{}if(o===void 0||o.trim()===""||o.includes("lunora")){const t=U(r,"vite",["dev"]);return{args:t.args,command:t.command}}return{args:["run","dev"],command:r}},$e=e=>{re(ne(e.logPath),{recursive:!0});const r=N(e.logPath,"w",384);let o;const t=Ee(e.command,e.args);try{o=ke(t.command,t.args,{cwd:e.cwd,detached:!0,env:e.env,shell:t.shell,stdio:["ignore",r,r],windowsHide:!0})}finally{F(r)}return o.unref(),{exited:new Promise(n=>{o.on("error",()=>{n(1)}),o.on("exit",(s,a)=>{n(s??(a?1:0))})}),pid:o.pid}},Te=e=>{try{const{size:r}=te(e);if(r<=f)return E(e,"utf8");const o=N(e,"r");try{const t=Buffer.alloc(f),n=oe(o,t,0,f,r-f),s=t.toString("utf8",0,n);return s.slice(s.indexOf(`
|
|
2
|
+
`)+1)}finally{F(o)}}catch{return}},z=(e,r)=>{const o=Te(e);if(o===void 0)return[];const t=o.split(`
|
|
3
|
+
`);return t.at(-1)===""&&t.pop(),r>0?t.slice(-r):t},J=(e,r)=>r?.logFile??w(e,ve),Y=e=>{e.info(" Stop: lunora dev stop"),e.info(" Status: lunora dev status"),e.info(" Logs: lunora dev logs")},Ne=(e,r)=>{e.warn(`Dev server already running at ${r.url} (pid ${String(r.pid)})`),Y(e)},Fe=(e,r)=>{e.success(`Dev server running at ${r.url} (pid ${String(r.pid)})`),r.studioUrl!==void 0&&e.info(` Studio: ${r.studioUrl}`),Y(e)},xe=async e=>{const{child:r,cwd:o,deadline:t,pollIntervalMs:n,probe:s}=e,a=r.exited.then(i=>({exitCode:i}));for(;Date.now()<t;){const i=C(o);if(i!==void 0&&i.pid!==process.pid&&await s(i.url))return{state:i,status:"ready"};const c=await Promise.race([a,h(n)]);if(c!==void 0)return{...c,status:"exited"}}return{status:"timeout"}},Ce=async e=>{const{cwd:r,logger:o}=e,t=J(r,void 0),n=_e(e.readyTimeoutMs),s=(e.spawnDetached??$e)({args:e.command.args,command:e.command.command,cwd:r,env:{...process.env,...e.env,[de]:"1",[ce]:t,...process.env.FORCE_COLOR===void 0?{NO_COLOR:"1"}:{},...e.json?{LUNORA_LOG_JSON:"1"}:{}},logPath:t}),a=await xe({child:s,cwd:r,deadline:Date.now()+n,pollIntervalMs:e.pollIntervalMs??K,probe:e.probe??Le});if(a.status==="ready")return Fe(o,a.state),{code:0};if(a.status==="exited"){o.error(`dev server exited before becoming ready (exit code ${String(a.exitCode)}). Last output:`);for(const c of z(t,Ae))o.error(` ${c}`);return m(r,s.pid??process.pid),{code:a.exitCode===0?1:a.exitCode}}s.pid!==void 0&&y(r)?.pid===process.pid&&le(r,{logFile:t,pid:s.pid});const i=s.pid===void 0?"":` (pid ${String(s.pid)})`;return o.warn(`dev server did not confirm ready within ${String(Math.round(n/1e3))}s — it may still be compiling${i}. Check \`lunora dev status\` and \`lunora dev logs\`; \`lunora dev stop\` shuts it down.`),{code:B.UNAVAILABLE}},X=e=>e.codegen!==!1&&!ge(process.env[j]),q=e=>{const r={...e.remote===!0?{LUNORA_REMOTE:"1"}:{},...e.codegen===!1?{[j]:"0"}:{}};return Object.keys(r).length>0?{env:r}:{}},Me=(e,r)=>{const o=["dev"];return e.apiSpec!==void 0&&o.push("--api-spec",e.apiSpec),e.port!==void 0&&o.push("--port",String(e.port)),e.workerPort!==void 0&&o.push("--worker-port",String(e.workerPort)),e.inspectorPort!==void 0&&o.push("--inspector-port",String(e.inspectorPort)),e.emitBindings!==void 0&&o.push("--emit-bindings",e.emitBindings),e.codegen===!1&&o.push("--no-codegen"),e.studio===!1&&o.push("--no-studio"),e.worker===!1&&o.push("--no-worker"),e.target!==void 0&&o.push("--target",e.target),r&&o.push("--remote"),o},gr=async e=>{const{cwd:r,jsonLogs:o,logger:t,options:n,remote:s}=e,a=e.run??Ce,i=O(r),c=i==="vite"&&P(n.target??x(r))?"wrangler":i,u=c==="wrangler"?`http://localhost:${String(n.workerPort??8787)}`:"http://localhost:5173",d=se(r,{background:!0,mode:"cli",pid:process.pid,startedAt:new Date().toISOString(),url:u});if(!d.ok)return d.existing!==void 0&&Ne(t,d.existing),{code:0};const l={[ae]:String(process.pid)};try{return c==="vite"?await a({command:H(r),cwd:r,env:{...q({...n,remote:s}).env,...l},json:o,logger:t}):await a({command:{args:[process.argv[1]??"lunora",...Me(n,s)],command:process.execPath},cwd:r,env:l,json:o,logger:t})}finally{m(r,process.pid)}},Ue=e=>{try{const r=D("ps",["-o","pgid=","-p",String(e)],{encoding:"utf8"}),o=Number.parseInt(r.stdout.trim(),10);return Number.isInteger(o)&&o>0?o:void 0}catch{return}},je=(e,r,o=process.platform,t=D)=>{if(o==="win32"){try{t("taskkill",["/pid",String(e.pid),"/T","/F"],{stdio:"ignore"})}catch{}return}if(e.background===!0)try{r(-(Ue(e.pid)??e.pid),"SIGKILL");return}catch{}try{r(e.pid,"SIGKILL")}catch{}},Ve=(e,r)=>(r.json?p({pid:e.pid,stopped:!1}):r.logger.error(`dev server (pid ${String(e.pid)}) survived the force-kill — record kept; retry \`lunora dev stop\` or kill the process manually.`),{code:1}),Ge=async e=>{const{cwd:r,logger:o}=e,t=y(r),n=e.alive??(l=>l===t?.pid&&ue(t)),s=e.signal??((l,v)=>{process.kill(l,v)}),a=e.pollIntervalMs??K,i=e.stopGraceMs??De,c=e.platform??process.platform,u=e.spawnSyncImpl??D;if(t===void 0||!n(t.pid))return t!==void 0&&m(r,t.pid),e.json?p({running:!1,stopped:!1}):o.info("No dev server running."),{code:0};try{s(t.pid,"SIGTERM")}catch{}const d=Date.now()+i;for(;n(t.pid)&&Date.now()<d;)await h(a);return n(t.pid)&&(je(t,s,c,u),await h(a),n(t.pid))?Ve(t,e):(m(r,t.pid),e.json?p({pid:t.pid,stopped:!0}):o.success(`Stopped dev server (pid ${String(t.pid)}).`),{code:0})},We=e=>{const{cwd:r,logger:o}=e,t=C(r);if(t===void 0)return e.json?p({running:!1}):o.info("No dev server running."),{code:0};const n=e.now??Date.now,s=t.startedAt===void 0?Number.NaN:Date.parse(t.startedAt),a=Number.isFinite(s)?Math.max(0,Math.round((n()-s)/1e3)):void 0;if(e.json)return p({background:t.background===!0,logFile:t.logFile,mode:t.mode,pid:t.pid,ready:A(t),readyAt:t.readyAt,running:!0,startedAt:t.startedAt,studioUrl:t.studioUrl,uptimeSeconds:a,url:t.url}),{code:0};const i=[`pid ${String(t.pid)}`,...a===void 0?[]:[`uptime ${String(a)}s`],t.background===!0?"background":"foreground",A(t)?"ready":"starting"];return o.success(`Dev server running at ${t.url} (${i.join(", ")})`),t.studioUrl!==void 0&&o.info(` Studio: ${t.studioUrl}`),t.logFile!==void 0&&o.info(` Logs: lunora dev logs (${t.logFile})`),{code:0}},Be=e=>{const{cwd:r,logger:o}=e,t=y(r),n=J(r,t);if(!T(n))return o.info("No dev server logs found — output is captured when the server runs in background mode (`lunora dev --background`)."),{code:0};const s=z(n,e.lines??Oe);return s.length>0&&process.stdout.write(`${s.join(`
|
|
4
|
+
`)}
|
|
5
|
+
`),{code:0}},pr=e=>{const{cwd:r,json:o,lines:t,logger:n,subcommand:s}=e;if(s==="stop")return Ge({cwd:r,json:o,logger:n});if(s==="status")return We({cwd:r,json:o,logger:n});if(s==="logs")return Be({cwd:r,lines:t,logger:n});if(s!==void 0)return n.error(`dev: unknown subcommand "${s}" — expected stop | status | logs (or no subcommand to start the dev server)`),{code:B.USAGE}},fr=(e,r,o)=>P(e)?(r!=="wrangler"&&o.info(`target ${e} runs its own dev server, so lunora dev serves the worker on it — start the frontend's dev server separately`),"wrangler"):r,Ke=e=>{const{cwd:r,driver:o,options:t,studioPort:n,workerPort:s}=e,{projectConfig:a,toolchain:i}=o;if(a===void 0||i===void 0)throw new Error(`deploy target "${o.id}" runs its own dev server but ships no config projection or toolchain for it`);if(t.remote===!0)throw new Error(`--remote proxies bindings to Cloudflare; ${o.name} has no remote bindings to proxy to`);t.inspectorPort!==void 0&&t.logger.warn(`--inspector-port is a wrangler dev flag; ${o.name} dev has no inspector to pin`);const{command:c,commit:u,projection:d}=pe(o,r,"dev",v=>i.dev({configPath:v,extraArgs:["--port",String(s)]}));u(),d!==void 0&&d.dropped.length>0&&t.logger.info(`${o.name} ignores these wrangler keys, so its dev server runs without them: ${d.dropped.join(", ")}`);const l=V(b(r),c);return{flavor:"wrangler",ipv4LoopbackForced:!1,remote:{bindings:[],cleanup:()=>{},enabled:!1},runsCodegenWatch:X(t),studioEnabled:t.studio!==!1,studioPort:n,workerEnabled:t.worker!==!1,workerOrigin:`http://localhost:${String(s)}`,workerPort:s,wrangler:{args:l.args,command:l.command,cwd:r,tag:c.tool}}},He=64,Q="127.0.0.1",ze=65535,Je=(e,r=Q)=>new Promise(o=>{const t=he();t.once("error",()=>{o(!1)}),t.once("listening",()=>{t.close(()=>{o(!0)})}),t.listen(e,r)}),Ye=async(e,r=Q,o=He)=>{for(let t=e;t<e+o&&t<=ze;t+=1)if(await Je(t,r))return t;return e},Z=(e=Se)=>Object.values(e()).some(r=>r?.some(o=>o.internal&&o.address==="::1")),S="wrangler.dev.jsonc",k=6173,g=8787,R=5173,Xe=(e,r)=>{const o=()=>{};if(!e.remote)return{args:[],plan:{bindings:[],cleanup:o,enabled:!1}};const n=(e.materializeRemote??we)({enabled:!0,projectRoot:r}),s=n.remoteBindings.map(i=>`${i.binding} (${i.kind})`),{cleanup:a}=n;return n.configPath===void 0?{args:[],plan:{bindings:s,cleanup:a,enabled:!0,reason:n.reason}}:{args:["--config",n.configPath],plan:{bindings:s,cleanup:a,enabled:!0}}},I=e=>L(e).parsed?.dev?.ip,ee=(e,r,o)=>{if(o!==void 0){const n=w(e,o);if(T(n)&&I(n)!==void 0)return[]}const t=_(e);return t!==void 0&&I(t)!==void 0?[]:r()?[]:["--ip","127.0.0.1"]},qe=new Set(["127.0.0.1","::1","[::1]","localhost"]),Qe=(e,r)=>{let o;try{o=E(w(e,W),"utf8")}catch{return[]}const t=[];for(const n of me(o)){let s;try{s=new URL(n.value)}catch{continue}qe.has(s.hostname)&&s.port===String(r)&&t.push(n.key)}return t},$=async(e,r)=>{if(e.workerPort!==void 0)return e.workerPort;const o=_(r);if(o!==void 0){const{parsed:s}=L(o);if(typeof s?.dev?.port=="number")return s.dev.port}const t=await(e.findFreePort??Ye)(g);if(t===g)return t;const n=Qe(r,g);if(n.length>0)throw new Error(`port ${String(g)} is in use, but ${W} pins the worker origin to it (${n.join(", ")}). Serving on ${String(t)} would leave those URLs pointing at nothing. Stop whatever holds ${String(g)}, or run \`lunora dev --worker-port ${String(t)}\` and update those values to match.`);return t},Ze=(e,r)=>{if(e.inspectorPort!==void 0)return e.inspectorPort;const o=_(r);if(o===void 0)return;const{parsed:t}=L(o),n=t?.dev?.inspector_port;return typeof n=="number"?n:void 0},er=(e,r,o)=>{const t=ee(r,e.hasIpv6Loopback??Z,S),n=G(e.target??x(r));if(n.toolchain===void 0)throw new Error(`deploy target "${n.id}" has no dev server to run the worker sidecar`);const s=n.toolchain.dev({configPath:S,extraArgs:[...t,"--var","WORKER_ENV:development"]}),a=V(o,s);return{args:a.args,command:a.command,cwd:r,tag:"worker"}},rr=e=>{const r=e.cwd??process.cwd(),o=b(r),t=e.flavor??O(r);if(t==="vite"||t==="framework-worker"){const l=H(r);let v;return t==="framework-worker"&&(v=er(e,r,o)),e.worker===!1&&e.logger.warn(`--no-worker does not apply to the ${t} flavor: Vite owns the worker, codegen and studio in-process. Run your framework's dev script instead.`),e.inspectorPort!==void 0&&e.logger.warn(t==="framework-worker"?`--inspector-port does not apply to the ${t} flavor: pin \`dev.inspector_port\` in ${S} — that is the config the worker sidecar runs.`:`--inspector-port does not apply to the ${t} flavor: Vite owns the worker. Pin it in vite.config — \`lunora({ cloudflare: { inspectorPort: ${String(e.inspectorPort)} } })\`.`),{runsCodegenWatch:!1,flavor:t,ipv4LoopbackForced:!1,remote:{bindings:[],cleanup:()=>{},enabled:e.remote===!0},...v?{sidecar:v}:{},studioEnabled:!1,studioPort:e.port??k,workerEnabled:!0,workerOrigin:`http://localhost:${String(R)}`,workerPort:R,wrangler:{args:l.args,command:l.command,cwd:r,...q(e),tag:"vite"}}}const n=M(r),s=n.framework==="none"?void 0:`this project uses ${n.framework} — the worker runs inside Vite there. run \`${fe(o,"dev")}\` for the full app (frontend + HMR); \`lunora dev\` starts only the worker.`,a=e.workerPort??g,i=Xe(e,r),c=ee(r,e.hasIpv6Loopback??Z),u=e.inspectorPort===void 0?[]:["--inspector-port",String(e.inspectorPort)],d=U(o,"wrangler",["dev","--port",String(a),...u,...c,"--var","WORKER_ENV:development",...i.args]);return{runsCodegenWatch:X(e),flavor:t,frameworkHint:s,ipv4LoopbackForced:c.length>0,remote:i.plan,studioEnabled:e.studio!==!1,studioPort:e.port??k,workerEnabled:e.worker!==!1,workerOrigin:`http://localhost:${String(a)}`,workerPort:a,wrangler:{args:d.args,command:d.command,cwd:r,tag:"wrangler"}}},mr=async e=>{const r=e.cwd??process.cwd();if(e.target!==void 0&&P(e.target))return Ke({cwd:r,driver:G(e.target),options:e,studioPort:e.port??k,workerPort:await $(e,r)});const o=e.flavor??O(r),t=o==="wrangler"?await $(e,r):e.workerPort,n=o==="wrangler"?Ze(e,r):e.inspectorPort;return rr({...e,cwd:r,flavor:o,inspectorPort:n,workerPort:t})};export{K as P,pr as a,Ne as b,O as c,Le as d,fr as e,mr as f,X as g,Ze as h,$ as i,rr as p,_e as r,gr as s};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{f as r,p as a,h as s,i as l}from"./plan-B-KsxVne.mjs";export{r as buildDevPlan,a as planDevCommand,s as resolveInspectorPort,l as resolveWorkerPort};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{resolveHint as a,isLunoraError as r,flattenHint as c}from"@lunora/errors";import{VisulimaError as d,renderError as m}from"@visulima/error";import{exitCodeForError as h}from"./EXIT_CODE-08cwt3MK.mjs";const f={filterStacktrace:()=>!1,hideErrorCodeView:!0},g=(n,i={})=>{const e=n instanceof Error?n.message:String(n),o=a(r(n)?{code:n.code,hint:n.hint,message:e}:e),t=o===void 0?[]:c(o).split(`
|
|
2
|
+
`);r(n)&&(t.length>0&&t.push(""),t.push(`\`${n.code}\` — exits ${String(h(n))}. Run \`lunora docs exit-codes\` for the table.`));const s=new d({hint:t.length===0?void 0:t,message:i.reason===void 0?e:`${i.reason}: ${e}`,name:n instanceof Error&&n.name.length>0?n.name:"Error"});return s.stack="",m(s,f)};export{g as r};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const h=e=>{switch(e){case"boolean":return"boolean";case"date":case"number":case"timestamp":return"number";case"id":case"literal":case"string":return"string";default:return}},m=/already (?:exists|indexed)|duplicate/iu,i=e=>["vectorize","create-metadata-index",e.index,`--property-name=${e.property}`,`--type=${e.type}`],g=async(e,t)=>{try{return await e(t)}catch(r){return{code:1,stderr:r instanceof Error?r.message:String(r)}}},x=async e=>{const{cwd:t,entries:r,exec:s,logger:E,spawner:p}=e,a=[];for(const n of r){const o=await g(p,{args:[...s.args,...i(n)],captureStderr:!0,command:s.command,cwd:t,stdoutToStderr:!0});if(o.code===0){a.push({entry:n,status:"created"});continue}const c=`${o.stderr??""}${o.stdout??""}`;if(m.test(c)){a.push({entry:n,status:"exists"});continue}a.push({entry:n,error:c.trim()||`exit code ${String(o.code)}`,status:"failed"}),E.warn(`could not create the Vectorize metadata index for "${n.property}" on "${n.index}" — filters on that property will match nothing until it exists. Run: wrangler ${i(n).join(" ")}`)}return a},u=e=>e.endsWith("S")?e.slice(0,-1):e,d=e=>e.replaceAll(/([a-z\d])([A-Z])/gu,"$1_$2").toUpperCase().split(/[_-]+/u).filter(t=>t.length>0),l=new Set(["CREDENTIAL","DSN","PASSPHRASE","PASSWD","PASSWORD","SECRET","TOKEN"]),S=["ACCESS_KEY","API_KEY","ENCRYPTION_KEY","PRIVATE_KEY","SIGNING_KEY"],A=new RegExp(`(?:${[...l,...S.map(e=>e.replaceAll("_",""))].join("|")})S?$`,"iu"),_=e=>d(e).some(t=>t==="PUBLIC"||t==="PUBLISHABLE"),I=e=>{if(_(e))return!1;const t=d(e);if(t.some(s=>l.has(u(s))))return!0;const r=u(t.join("_"));return S.some(s=>r===s||r.endsWith(`_${s}`))||A.test(e)};export{i as c,x as e,I as i,h as m};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{resolveDeployDriver as c,resolveProjectTarget as d,toolchainExecArgs as l,detectPackageManager as i}from"@lunora/config";import{defaultSpawner as u}from"./createRecordingSpawner-sS7LEN7x.mjs";const m=async(e,t,o)=>{try{const r=await u({args:t,captureStderr:!0,captureStdoutSilently:!0,command:e,cwd:o});return{code:r.code,stderr:r.stderr??"",stdout:r.stdout??""}}catch(r){return{code:1,stderr:r instanceof Error?r.message:String(r),stdout:""}}},f=e=>{let t;try{t=JSON.parse(e)}catch{return}return Array.isArray(t)?[...t.map(r=>r!==null&&typeof r=="object"?r.name:void 0).filter(r=>typeof r=="string"&&r.length>0)].toSorted((r,a)=>r.localeCompare(a)):void 0},y=async e=>{const t=c(d(e.cwd)),o=t.toolchain?.secretList?.({environment:e.env,temporary:e.temporary});if(o===void 0)return{error:`deploy target "${t.id}" has no secret store to list`,names:[],ok:!1};const{args:r,command:a}=l(i(e.cwd),o),s=await(e.runner??m)(a,r,e.cwd);if(s.code!==0)return{error:s.stderr.trim()||`wrangler secret list exited ${String(s.code)}`,names:[],ok:!1};const n=f(s.stdout);return n===void 0?{error:"could not parse `wrangler secret list --format json` output",names:[],ok:!1}:{names:n,ok:!0}};export{y as l};
|