@lunora/cli 1.0.0-alpha.210 → 1.0.0-alpha.211

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.
@@ -1,11 +1,11 @@
1
- import{existsSync as m,mkdirSync as M,writeFileSync as v,readFileSync as b,readdirSync as re,rmSync as $,mkdtempSync as oe,cpSync as G,renameSync as Re,lstatSync as Oe}from"node:fs";import{tmpdir as se}from"node:os";import{installArgsFor as ne,execArgsFor as Te,detectFramework as Pe,isInteractive as g,LUNA_ART as De,LUNA_NAME as Be,LUNA_SIGNOFF as je,BADGES as f,paintAnswer as Ve,detectPackageManager as V,detectInstalledManagers as Ue,runScriptCommand as Fe,detectLintTools as He,addArgsFor as We,applyLintIgnores as ze}from"@lunora/config";import{walkSync as qe}from"@visulima/fs";import{join as u,dirname as A,basename as E,resolve as ie,relative as Ke}from"@visulima/path";import{downloadTemplate as le}from"giget";import{modify as Ge,applyEdits as Je}from"jsonc-parser";import{join as U,dirname as Ye}from"node:path";import{d as Xe}from"../packem_shared/command-DwC11Cwe.mjs";import Qe from"magic-string";import{Project as Ze,SyntaxKind as w}from"ts-morph";import{P as F}from"../packem_shared/prompt-cancelled-C8Sj7OqI.mjs";import{h as ce,d as de,i as ue,b as et}from"../packem_shared/resolve-DZAGzg67.mjs";import{defaultSpawner as pe}from"../packem_shared/createRecordingSpawner-DJlNacZ6.mjs";import{d as tt,e as at,f as rt,a as he,t as H,g as me,h as ot,b as fe,i as ve,w as st,j as nt,k as ge,l as it}from"../packem_shared/tui-prompts-Dd0pDuNr.mjs";import{E as we,p as lt,w as ct,M as dt,r as ut,j as pt,e as ht,c as ye,k as be,f as mt}from"../packem_shared/storage-wIUel5Az.mjs";import{logStep as J}from"../packem_shared/createLogger-hGafwf-3.mjs";import{r as ft}from"../packem_shared/lint-ignore-report-DKZagpqk.mjs";import vt from"node:dns/promises";import{r as gt}from"../packem_shared/commands-BNKj7r1R.mjs";const W={bun:{githubCacheKey:void 0,githubSetupStep:` - uses: oven-sh/setup-bun@v2
1
+ import{existsSync as m,mkdirSync as M,writeFileSync as v,readFileSync as b,readdirSync as re,rmSync as _,mkdtempSync as oe,cpSync as G,renameSync as Oe,lstatSync as Pe}from"node:fs";import{tmpdir as ne}from"node:os";import{installArgsFor as se,execArgsFor as De,detectFramework as Be,isInteractive as g,LUNA_ART as je,LUNA_NAME as Ve,LUNA_SIGNOFF as Ue,BADGES as f,paintAnswer as Fe,detectPackageManager as U,detectInstalledManagers as He,runScriptCommand as We,detectLintTools as ze,addArgsFor as qe,applyLintIgnores as Ke}from"@lunora/config";import{walkSync as Ge}from"@visulima/fs";import{join as u,dirname as A,basename as E,resolve as ie,relative as Je}from"@visulima/path";import{downloadTemplate as le}from"giget";import{modify as Ye,applyEdits as Xe}from"jsonc-parser";import{join as F,dirname as Qe}from"node:path";import{d as Ze}from"../packem_shared/command-DwC11Cwe.mjs";import et from"magic-string";import{Project as tt,SyntaxKind as w}from"ts-morph";import{P as H}from"../packem_shared/prompt-cancelled-C8Sj7OqI.mjs";import{h as ce,d as de,i as ue,b as at}from"../packem_shared/resolve-DZAGzg67.mjs";import{defaultSpawner as pe}from"../packem_shared/createRecordingSpawner-DJlNacZ6.mjs";import{d as rt,e as ot,f as nt,a as he,t as W,g as me,h as st,b as fe,i as ve,w as it,j as lt,k as ge,l as ct}from"../packem_shared/tui-prompts-Dd0pDuNr.mjs";import{E as we,p as dt,w as ut,M as pt,r as ht,j as mt,e as ft,c as ye,k as be,f as vt}from"../packem_shared/storage-wIUel5Az.mjs";import{logStep as J}from"../packem_shared/createLogger-hGafwf-3.mjs";import{r as gt}from"../packem_shared/lint-ignore-report-DKZagpqk.mjs";import wt from"node:dns/promises";import{r as yt}from"../packem_shared/commands-BNKj7r1R.mjs";const z={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
- `,gitlabImage:"node:22",gitlabProvisionScript:["corepack enable"],installCmd:"pnpm install --frozen-lockfile",lockfile:"pnpm-lock.yaml"},yarn:{githubCacheKey:"yarn",githubSetupStep:"",gitlabImage:"node:22",gitlabProvisionScript:["corepack enable"],installCmd:"yarn install --frozen-lockfile",lockfile:"yarn.lock"}},C=(e,t)=>{const a=Te(e,"lunora",t);return[a.command,...a.args].join(" ")},Y=e=>` - uses: actions/checkout@v4
3
+ `,gitlabImage:"node:22",gitlabProvisionScript:["corepack enable"],installCmd:"pnpm install --frozen-lockfile",lockfile:"pnpm-lock.yaml"},yarn:{githubCacheKey:"yarn",githubSetupStep:"",gitlabImage:"node:22",gitlabProvisionScript:["corepack enable"],installCmd:"yarn install --frozen-lockfile",lockfile:"yarn.lock"}},C=(e,t)=>{const a=De(e,"lunora",t);return[a.command,...a.args].join(" ")},Y=e=>` - uses: actions/checkout@v4
4
4
  ${e.githubSetupStep} - uses: actions/setup-node@v4
5
5
  with:
6
6
  node-version: 22
7
7
  ${e.githubCacheKey===void 0?"":` cache: ${e.githubCacheKey}
8
- `} - run: ${e.installCmd}`,wt=e=>{const t=W[e],a=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
8
+ `} - run: ${e.installCmd}`,bt=e=>{const t=z[e],a=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
9
9
 
10
10
  on:
11
11
  push:
@@ -47,7 +47,7 @@ ${Y(t)}
47
47
  steps:
48
48
  ${Y(t)}
49
49
  - run: ${C(e,["deploy","--preview"])}
50
- `},yt=e=>{const t=W[e],a=[...t.gitlabProvisionScript,t.installCmd].map(r=>` - ${r}`).join(`
50
+ `},xt=e=>{const t=z[e],a=[...t.gitlabProvisionScript,t.installCmd].map(r=>` - ${r}`).join(`
51
51
  `);return`stages:
52
52
  - deploy
53
53
 
@@ -82,16 +82,16 @@ preview:
82
82
  - if: $CI_PIPELINE_SOURCE == "merge_request_event"
83
83
  script:
84
84
  - ${C(e,["deploy","--preview"])}
85
- `},xe={github:{file:U(".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)"}},bt=(e,t)=>e==="github"?wt(t):yt(t),xt=e=>e==="github"||e==="gitlab",kt=(e,t,a,r={})=>{const o=U(e,xe[t].file);return m(o)&&r.overwrite!==!0?{path:o,skipped:!0,written:!1}:(M(Ye(o),{recursive:!0}),v(o,bt(t,a),"utf8"),{path:o,skipped:!1,written:!0})},Ct=(e,t,a,r,o={})=>{const s=xe[t];try{const n=kt(e,t,a,o);if(n.skipped)r.info(`--ci ${t}: ${s.file} already exists — left unchanged (re-run with overwrite to replace).`);else{const i=ne(a),l=[i.command,...i.args].join(" "),{installCmd:d,lockfile:c}=W[a];r.success(`--ci ${t}: wrote ${s.file}`),r.info(`--ci ${t}: set CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID as ${s.secretsHint} to enable deploys.`),r.info(`--ci ${t}: run \`${l}\` and commit ${c} before pushing — the pipeline runs \`${d}\`.`)}return n}catch(n){const i=n instanceof Error?n.message:String(n);return r.warn(`--ci ${t}: could not write ${s.file} (${i})`),{path:U(e,s.file),skipped:!1,written:!1}}},St={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"},Lt=e=>{const t=Pe(e);return{...t,adapter:St[t.framework]}},_="lunora()",X='import { lunora } from "@lunora/vite";',Mt=/\blunora\s*\(/u,At='"@lunora/vite"',Et="'@lunora/vite'",Nt=e=>{for(const t of e.getStatements()){if(t.getKind()!==w.ExportAssignment)continue;const a=t.asKindOrThrow(w.ExportAssignment).getExpression();if(a.getKind()!==w.CallExpression)continue;const r=a.asKindOrThrow(w.CallExpression);if(r.getExpression().getText()!=="defineConfig")continue;const o=r.getArguments()[0];if(o?.getKind()===w.ObjectLiteralExpression)return o.asKindOrThrow(w.ObjectLiteralExpression)}},It=e=>{for(const t of e.getStatements()){if(t.getKind()!==w.ExportAssignment)continue;const a=t.asKindOrThrow(w.ExportAssignment).getExpression();if(a.getKind()===w.ObjectLiteralExpression)return a.asKindOrThrow(w.ObjectLiteralExpression)}},_t=e=>new Ze({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}).createSourceFile("vite.config.ts",e,{overwrite:!0}),$t=(e,t)=>{const a=t.getImportDeclarations().at(-1)?.getEnd()??0;a===0?e.prepend(`${X}
85
+ `},xe={github:{file:F(".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)"}},kt=(e,t)=>e==="github"?bt(t):xt(t),Ct=e=>e==="github"||e==="gitlab",St=(e,t,a,r={})=>{const o=F(e,xe[t].file);return m(o)&&r.overwrite!==!0?{path:o,skipped:!0,written:!1}:(M(Qe(o),{recursive:!0}),v(o,kt(t,a),"utf8"),{path:o,skipped:!1,written:!0})},Lt=(e,t,a,r,o={})=>{const n=xe[t];try{const s=St(e,t,a,o);if(s.skipped)r.info(`--ci ${t}: ${n.file} already exists — left unchanged (re-run with overwrite to replace).`);else{const i=se(a),l=[i.command,...i.args].join(" "),{installCmd:d,lockfile:c}=z[a];r.success(`--ci ${t}: wrote ${n.file}`),r.info(`--ci ${t}: set CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID as ${n.secretsHint} to enable deploys.`),r.info(`--ci ${t}: run \`${l}\` and commit ${c} before pushing — the pipeline runs \`${d}\`.`)}return s}catch(s){const i=s instanceof Error?s.message:String(s);return r.warn(`--ci ${t}: could not write ${n.file} (${i})`),{path:F(e,n.file),skipped:!1,written:!1}}},Mt={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"},At=e=>{const t=Be(e);return{...t,adapter:Mt[t.framework]}},$="lunora()",X='import { lunora } from "@lunora/vite";',Et=/\blunora\s*\(/u,Nt='"@lunora/vite"',It="'@lunora/vite'",$t=e=>{for(const t of e.getStatements()){if(t.getKind()!==w.ExportAssignment)continue;const a=t.asKindOrThrow(w.ExportAssignment).getExpression();if(a.getKind()!==w.CallExpression)continue;const r=a.asKindOrThrow(w.CallExpression);if(r.getExpression().getText()!=="defineConfig")continue;const o=r.getArguments()[0];if(o?.getKind()===w.ObjectLiteralExpression)return o.asKindOrThrow(w.ObjectLiteralExpression)}},_t=e=>{for(const t of e.getStatements()){if(t.getKind()!==w.ExportAssignment)continue;const a=t.asKindOrThrow(w.ExportAssignment).getExpression();if(a.getKind()===w.ObjectLiteralExpression)return a.asKindOrThrow(w.ObjectLiteralExpression)}},Rt=e=>new tt({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}).createSourceFile("vite.config.ts",e,{overwrite:!0}),Tt=(e,t)=>{const a=t.getImportDeclarations().at(-1)?.getEnd()??0;a===0?e.prepend(`${X}
86
86
  `):e.appendLeft(a,`
87
- ${X}`)},Rt=(e,t)=>{const a=t.getProperty("plugins");if(a===void 0){const s=t.getProperties(),n=t.getStart()+1;if(s.length===0)e.appendLeft(n,` plugins: [${_}] `);else{const i=s[0];i!==void 0&&e.appendLeft(i.getStart(),`plugins: [${_}],
88
- `)}return}const r=a.getDescendantsOfKind(w.ArrayLiteralExpression)[0];if(r===void 0)return;const o=r.getElements();if(o.length===0)e.appendLeft(r.getStart()+1,_);else{const s=o[0];s!==void 0&&e.appendLeft(s.getStart(),`${_}, `)}},ke=e=>{if(Mt.test(e))return{changed:!1,code:e,reason:"lunora plugin already present"};const t=_t(e),a=Nt(t)??It(t);if(a===void 0)return{changed:!1,code:e,reason:"could not locate a Vite config plugins array to patch"};const r=new Qe(e);return!e.includes(At)&&!e.includes(Et)&&$t(r,t),Rt(r,a),{changed:!0,code:r.toString()}},Ot=/enotfound|eai_again|econnrefused|etimedout|network|fetch failed|getaddrinfo/u,Tt=/404|not found|could not find|no such/u,Pt=(e,t)=>{const a=e instanceof Error?e.message:String(e),r=a.toLowerCase(),o=`failed to download template "${t.templateType}" from ${t.remote}: ${a}`;return Tt.test(r)?{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}: ${a}`}:Ot.test(r)?{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}},R=async(e,t,a)=>{if(g()){await at(f[e],t,a);return}if(process.stdout.write(`
87
+ ${X}`)},Ot=(e,t)=>{const a=t.getProperty("plugins");if(a===void 0){const n=t.getProperties(),s=t.getStart()+1;if(n.length===0)e.appendLeft(s,` plugins: [${$}] `);else{const i=n[0];i!==void 0&&e.appendLeft(i.getStart(),`plugins: [${$}],
88
+ `)}return}const r=a.getDescendantsOfKind(w.ArrayLiteralExpression)[0];if(r===void 0)return;const o=r.getElements();if(o.length===0)e.appendLeft(r.getStart()+1,$);else{const n=o[0];n!==void 0&&e.appendLeft(n.getStart(),`${$}, `)}},ke=e=>{if(Et.test(e))return{changed:!1,code:e,reason:"lunora plugin already present"};const t=Rt(e),a=$t(t)??_t(t);if(a===void 0)return{changed:!1,code:e,reason:"could not locate a Vite config plugins array to patch"};const r=new et(e);return!e.includes(Nt)&&!e.includes(It)&&Tt(r,t),Ot(r,a),{changed:!0,code:r.toString()}},Pt=/enotfound|eai_again|econnrefused|etimedout|network|fetch failed|getaddrinfo/u,Dt=/404|not found|could not find|no such/u,Bt=(e,t)=>{const a=e instanceof Error?e.message:String(e),r=a.toLowerCase(),o=`failed to download template "${t.templateType}" from ${t.remote}: ${a}`;return Dt.test(r)?{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}: ${a}`}:Pt.test(r)?{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}},R=async(e,t,a)=>{if(g()){await ot(f[e],t,a);return}if(process.stdout.write(`
89
89
  `),a===void 0||a===""){J(e,t);return}const r=a.split(`
90
- `).map(o=>Ve(o)).join(`
90
+ `).map(o=>Fe(o)).join(`
91
91
  `);J(e,`${t}
92
- ${r}`)},Dt=async e=>{if(g()){await tt();return}e.info(`
93
- ${De}
94
- ${Be}: ${je}`)},Ce=[{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"}],Q=Ce.map(e=>e.value),Bt=e=>e==="email"?we:e,jt=(e,t)=>{const a=[];for(const r of e.split(",").map(o=>o.trim()).filter(Boolean))Q.includes(r)?a.includes(r)||a.push(r):t(`init: unknown --add feature "${r}" — expected ${Q.join(" | ")}; skipping.`);return a},Vt=async e=>{const t=await ht(e.select),a=await ye(e.text,e.projectName);return{label:"auth",names:[t],transformManifest:r=>be(r,a)}},Ut=async e=>{const t=await e.text(dt,{placeholder:"you@yourdomain.com"}),a=ut(t,r=>{e.logger.warn(r)});return{label:"email",names:[we],transformManifest:a===void 0?void 0:r=>pt(r,a)}},Ft=async(e,t)=>{const a=e.resolveAuthUiItem?.()??"auth-ui-react";if(t)return{label:"auth-ui",names:[a]};const r=await ye(e.text,e.projectName);return{label:"auth-ui",names:[a],transformManifest:o=>be(o,r)}},Ht=async e=>{const t=await lt(e.text,e.projectName);return{label:"storage",names:["storage"],transformManifest:a=>ct(a,t)}},Wt={auth:Vt,"auth-ui":async(e,t)=>Ft(e,t.includes("auth")),email:Ut,storage:Ht},Z=async e=>{if(e.preselected!==void 0&&e.preselected.length>0){await e.applyAll(e.preselected.map(r=>{const o=r==="auth-ui"?e.resolveAuthUiItem?.()??"auth-ui-react":Bt(r);return{label:r,names:[o]}}));return}if(!e.interactive){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>`.");return}const t=await e.multiSelect("Which features do you want to add?",Ce,{defaults:[]});if(t.length===0)return;const a=[];for(const r of t){const o=Wt[r];a.push(o?await o(e,t):{label:r,names:[r]})}await e.applyAll(a)},zt=[{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"}],qt="Which linter/formatter do you use? We'll tell it to skip Lunora's generated files.",Kt=async e=>{const t=e.interactive?await e.multiSelect(qt,zt,{defaults:e.detected}):[...e.detected];if(t.length===0)return[];const a=e.apply(t);return ft(a,e.logger),a},N="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",L=`/* The welcome page is a full-bleed starter — reset the browser's default
92
+ ${r}`)},jt=async e=>{if(g()){await rt();return}e.info(`
93
+ ${je}
94
+ ${Ve}: ${Ue}`)},Ce=[{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"}],Q=Ce.map(e=>e.value),Vt=e=>e==="email"?we:e,Ut=(e,t)=>{const a=[];for(const r of e.split(",").map(o=>o.trim()).filter(Boolean))Q.includes(r)?a.includes(r)||a.push(r):t(`init: unknown --add feature "${r}" — expected ${Q.join(" | ")}; skipping.`);return a},Ft=async e=>{const t=await ft(e.select),a=await ye(e.text,e.projectName);return{label:"auth",names:[t],transformManifest:r=>be(r,a)}},Ht=async e=>{const t=await e.text(pt,{placeholder:"you@yourdomain.com"}),a=ht(t,r=>{e.logger.warn(r)});return{label:"email",names:[we],transformManifest:a===void 0?void 0:r=>mt(r,a)}},Wt=async(e,t)=>{const a=e.resolveAuthUiItem?.()??"auth-ui-react";if(t)return{label:"auth-ui",names:[a]};const r=await ye(e.text,e.projectName);return{label:"auth-ui",names:[a],transformManifest:o=>be(o,r)}},zt=async e=>{const t=await dt(e.text,e.projectName);return{label:"storage",names:["storage"],transformManifest:a=>ut(a,t)}},qt={auth:Ft,"auth-ui":async(e,t)=>Wt(e,t.includes("auth")),email:Ht,storage:zt},Z=async e=>{if(e.preselected!==void 0&&e.preselected.length>0){await e.applyAll(e.preselected.map(r=>{const o=r==="auth-ui"?e.resolveAuthUiItem?.()??"auth-ui-react":Vt(r);return{label:r,names:[o]}}));return}if(!e.interactive){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>`.");return}const t=await e.multiSelect("Which features do you want to add?",Ce,{defaults:[]});if(t.length===0)return;const a=[];for(const r of t){const o=qt[r];a.push(o?await o(e,t):{label:r,names:[r]})}await e.applyAll(a)},Kt=[{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"}],Gt="Which linter/formatter do you use? We'll tell it to skip Lunora's generated files.",Jt=async e=>{const t=e.interactive?await e.multiSelect(Gt,Kt,{defaults:e.detected}):[...e.detected];if(t.length===0)return[];const a=e.apply(t);return gt(a,e.logger),a},N="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",L=`/* The welcome page is a full-bleed starter — reset the browser's default
95
95
  body margin/padding so it sits flush; everything else is scoped under
96
96
  .lunora-welcome (collision-safe). */
97
97
  body {
@@ -196,7 +196,7 @@ body {
196
196
  .lunora-welcome .lw-foot { text-align: center; padding-top: 26px; font-family: var(--mono); font-size: 11px; letter-spacing: .1em; text-transform: uppercase; color: var(--t-faint); }
197
197
 
198
198
  @media (prefers-reduced-motion: reduce) { .lunora-welcome * { transition: none !important; } }
199
- `,Gt=`import { useEffect, useState } from "react";
199
+ `,Yt=`import { useEffect, useState } from "react";
200
200
 
201
201
  type Theme = "dark" | "light";
202
202
 
@@ -357,7 +357,7 @@ export default function App() {
357
357
  </div>
358
358
  );
359
359
  }
360
- `,Jt=`<script setup lang="ts">
360
+ `,Xt=`<script setup lang="ts">
361
361
  import { onMounted, ref } from "vue";
362
362
 
363
363
  // Default to "dark" for a stable first paint, then reconcile to the OS
@@ -513,7 +513,7 @@ const toggle = (): void => {
513
513
  </div>
514
514
  </div>
515
515
  </template>
516
- `,Yt=`import { createSignal, onMount } from "solid-js";
516
+ `,Qt=`import { createSignal, onMount } from "solid-js";
517
517
 
518
518
  export default function App() {
519
519
  // Default to "dark" for a stable first paint, then reconcile to the OS
@@ -672,7 +672,7 @@ export default function App() {
672
672
  </div>
673
673
  );
674
674
  }
675
- `,Xt=`<script lang="ts">
675
+ `,Zt=`<script lang="ts">
676
676
  import { onMount } from "svelte";
677
677
 
678
678
  // Default to "dark" for a stable first paint, then reconcile to the OS
@@ -830,7 +830,7 @@ export default function App() {
830
830
  <div class="lw-foot">Running on Lunora · Vite + Svelte</div>
831
831
  </div>
832
832
  </div>
833
- `,Qt=`import "./style.css";
833
+ `,ea=`import "./style.css";
834
834
 
835
835
  import { LunoraClient } from "lunorash/client";
836
836
 
@@ -997,7 +997,7 @@ const count = document.querySelector<HTMLSpanElement>("#lw-count")!;
997
997
  client.onUpdate(api.messages.list, { channelId: "channel:demo" }, (result) => {
998
998
  count.textContent = String(result.messages.length);
999
999
  });
1000
- `,O="const url = (import.meta.env.VITE_LUNORA_URL as string | undefined) ?? globalThis.location.origin;",Zt=`import "./index.css";
1000
+ `,T="const url = (import.meta.env.VITE_LUNORA_URL as string | undefined) ?? globalThis.location.origin;",ta=`import "./index.css";
1001
1001
 
1002
1002
  import { LunoraProvider } from "@lunora/react";
1003
1003
  import { LunoraClient } from "lunorash/client";
@@ -1009,7 +1009,7 @@ import App from "./App.tsx";
1009
1009
  // \`@lunora/vite\` runs the Worker on the same origin as Vite, so default to
1010
1010
  // \`location.origin\`. Point \`VITE_LUNORA_URL\` at a deployed Worker to develop
1011
1011
  // the client against production data.
1012
- ${O}
1012
+ ${T}
1013
1013
  const client = new LunoraClient({ url });
1014
1014
 
1015
1015
  const root = document.getElementById("root");
@@ -1025,7 +1025,7 @@ createRoot(root).render(
1025
1025
  </LunoraProvider>
1026
1026
  </StrictMode>,
1027
1027
  );
1028
- `,ea=`import "./style.css";
1028
+ `,aa=`import "./style.css";
1029
1029
 
1030
1030
  import { createLunora } from "@lunora/vue";
1031
1031
  import { LunoraClient } from "lunorash/client";
@@ -1034,9 +1034,9 @@ import { createApp } from "vue";
1034
1034
  import App from "./App.vue";
1035
1035
 
1036
1036
  // Provide one LunoraClient at the app root via the Vue plugin form.
1037
- ${O}
1037
+ ${T}
1038
1038
  createApp(App).use(createLunora(new LunoraClient({ url }))).mount("#app");
1039
- `,ta=`import "./index.css";
1039
+ `,ra=`import "./index.css";
1040
1040
 
1041
1041
  import { LunoraProvider } from "@lunora/solid";
1042
1042
  import { LunoraClient } from "lunorash/client";
@@ -1044,7 +1044,7 @@ import { render } from "solid-js/web";
1044
1044
 
1045
1045
  import App from "./App";
1046
1046
 
1047
- ${O}
1047
+ ${T}
1048
1048
  const client = new LunoraClient({ url });
1049
1049
  const root = document.getElementById("root");
1050
1050
 
@@ -1056,18 +1056,18 @@ render(
1056
1056
  ),
1057
1057
  root!,
1058
1058
  );
1059
- `,aa=`<script lang="ts">
1059
+ `,oa=`<script lang="ts">
1060
1060
  import { setLunoraClient } from "@lunora/svelte";
1061
1061
  import { LunoraClient } from "lunorash/client";
1062
1062
 
1063
1063
  import App from "./App.svelte";
1064
1064
 
1065
- ${O}
1065
+ ${T}
1066
1066
  setLunoraClient(new LunoraClient({ url }));
1067
1067
  <\/script>
1068
1068
 
1069
1069
  <App />
1070
- `,ra=`import "./app.css";
1070
+ `,na=`import "./app.css";
1071
1071
 
1072
1072
  import { mount } from "svelte";
1073
1073
 
@@ -1077,7 +1077,7 @@ import Root from "./Root.svelte";
1077
1077
  const app = mount(Root, { target: document.getElementById("app")! });
1078
1078
 
1079
1079
  export default app;
1080
- `,T={react:{adapter:"@lunora/react",createViteTemplate:"react-ts",files:[{contents:Zt,path:"src/main.tsx"},{contents:Gt,path:"src/App.tsx"},{contents:L,path:"src/index.css"}],label:"React"},solid:{adapter:"@lunora/solid",createViteTemplate:"solid-ts",files:[{contents:ta,path:"src/index.tsx"},{contents:Yt,path:"src/App.tsx"},{contents:L,path:"src/index.css"}],label:"Solid"},svelte:{adapter:"@lunora/svelte",createViteTemplate:"svelte-ts",files:[{contents:aa,path:"src/Root.svelte"},{contents:ra,path:"src/main.ts"},{contents:Xt,path:"src/App.svelte"},{contents:L,path:"src/app.css"}],label:"Svelte"},vanilla:{adapter:"lunorash/client",createViteTemplate:"vanilla-ts",files:[{contents:Qt,path:"src/main.ts"},{contents:L,path:"src/style.css"}],label:"Vanilla"},vue:{adapter:"@lunora/vue",createViteTemplate:"vue-ts",files:[{contents:ea,path:"src/main.ts"},{contents:Jt,path:"src/App.vue"},{contents:L,path:"src/style.css"}],label:"Vue"}},z=e=>Object.hasOwn(T,e),oa=`import type { Middleware } from "lunorash/server";
1080
+ `,O={react:{adapter:"@lunora/react",createViteTemplate:"react-ts",files:[{contents:ta,path:"src/main.tsx"},{contents:Yt,path:"src/App.tsx"},{contents:L,path:"src/index.css"}],label:"React"},solid:{adapter:"@lunora/solid",createViteTemplate:"solid-ts",files:[{contents:ra,path:"src/index.tsx"},{contents:Qt,path:"src/App.tsx"},{contents:L,path:"src/index.css"}],label:"Solid"},svelte:{adapter:"@lunora/svelte",createViteTemplate:"svelte-ts",files:[{contents:oa,path:"src/Root.svelte"},{contents:na,path:"src/main.ts"},{contents:Zt,path:"src/App.svelte"},{contents:L,path:"src/app.css"}],label:"Svelte"},vanilla:{adapter:"lunorash/client",createViteTemplate:"vanilla-ts",files:[{contents:ea,path:"src/main.ts"},{contents:L,path:"src/style.css"}],label:"Vanilla"},vue:{adapter:"@lunora/vue",createViteTemplate:"vue-ts",files:[{contents:aa,path:"src/main.ts"},{contents:Xt,path:"src/App.vue"},{contents:L,path:"src/style.css"}],label:"Vue"}},P=e=>Object.hasOwn(O,e),sa=`import type { Middleware } from "lunorash/server";
1081
1081
  import { defineSchemaExtension, defineTable, definePlugin, v } from "lunorash/server";
1082
1082
  import { createDbStore, RateLimiter } from "lunorash/ratelimit";
1083
1083
  import type { RateLimitConfigMap } from "lunorash/ratelimit";
@@ -1117,7 +1117,7 @@ export const ratelimit = definePlugin("ratelimit", {
1117
1117
  }),
1118
1118
  middleware,
1119
1119
  });
1120
- `,sa=`import { ratelimit } from "./ratelimit/schema.js";
1120
+ `,ia=`import { ratelimit } from "./ratelimit/schema.js";
1121
1121
  import { defineSchema, defineTable, v } from "lunorash/server";
1122
1122
 
1123
1123
  export default defineSchema({
@@ -1128,7 +1128,7 @@ export default defineSchema({
1128
1128
  .shardBy("channelId")
1129
1129
  .index("by_channel", ["channelId"]),
1130
1130
  }).extend(ratelimit.extension);
1131
- `,na=`import { RateLimiter, rateLimit, createDbStore } from "lunorash/ratelimit";
1131
+ `,la=`import { RateLimiter, rateLimit, createDbStore } from "lunorash/ratelimit";
1132
1132
 
1133
1133
  import { mutation, query, v } from "#lunora/_generated/server.js";
1134
1134
 
@@ -1156,7 +1156,7 @@ export const send = mutation
1156
1156
 
1157
1157
  return { channelId: args.channelId, id, text: args.text };
1158
1158
  });
1159
- `,ia=`import type { ShardNamespaceLike } from "lunorash/runtime";
1159
+ `,ca=`import type { ShardNamespaceLike } from "lunorash/runtime";
1160
1160
 
1161
1161
  import { defineApp } from "../lunora/_generated/app.js";
1162
1162
 
@@ -1170,7 +1170,7 @@ const app = defineApp<Env>()
1170
1170
 
1171
1171
  export const ShardDO = app.ShardDO;
1172
1172
  export default app;
1173
- `,la=`{
1173
+ `,da=`{
1174
1174
  "$schema": "node_modules/wrangler/config-schema.json",
1175
1175
  "name": "__NAME__",
1176
1176
  "main": "src/server.ts",
@@ -1182,23 +1182,23 @@ export default app;
1182
1182
  "migrations": [{ "tag": "v1", "new_sqlite_classes": ["ShardDO"] }],
1183
1183
  "observability": { "enabled": true, "head_sampling_rate": 1 },
1184
1184
  }
1185
- `,ca=[".wrangler",".env",".env.*","!.env.example",".dev.vars",".dev.vars.*","!.dev.vars.example",".lunora/",".lunora-cache","lunora/_generated"],da=`# Lunora endpoint for the browser client.
1185
+ `,ua=[".wrangler",".env",".env.*","!.env.example",".dev.vars",".dev.vars.*","!.dev.vars.example",".lunora/",".lunora-cache","lunora/_generated"],pa=`# Lunora endpoint for the browser client.
1186
1186
  # Vite statically replaces \`import.meta.env.VITE_LUNORA_URL\` at \`vite dev\` / build.
1187
1187
  # Leave it unset to use the page origin; set it to point at a deployed Worker:
1188
1188
  #
1189
1189
  # VITE_LUNORA_URL=https://my-app.example.workers.dev
1190
- `,ua={"@cloudflare/workers-types":"^4.20260611.1",wrangler:"^4.100.0"},x=(e,t,a,r)=>{const o=u(e,t);M(A(o),{recursive:!0}),v(o,a,"utf8"),r.push(o)},pa=/\r?\n/,ha=e=>{const t=u(e,".gitignore"),a=m(t)?b(t,"utf8"):"",r=new Set(a.split(pa)),o=ca.filter(n=>!r.has(n));if(o.length===0)return;const s=a.length>0&&!a.endsWith(`
1190
+ `,ha={"@cloudflare/workers-types":"^4.20260611.1",wrangler:"^4.100.0"},x=(e,t,a,r)=>{const o=u(e,t);M(A(o),{recursive:!0}),v(o,a,"utf8"),r.push(o)},ma=/\r?\n/,fa=e=>{const t=u(e,".gitignore"),a=m(t)?b(t,"utf8"):"",r=new Set(a.split(ma)),o=ua.filter(s=>!r.has(s));if(o.length===0)return;const n=a.length>0&&!a.endsWith(`
1191
1191
  `)?`
1192
- `:"";v(t,`${a}${s}
1192
+ `:"";v(t,`${a}${n}
1193
1193
  # Lunora
1194
1194
  ${o.join(`
1195
1195
  `)}
1196
- `,"utf8")},P=e=>e==="lunorash"||e.startsWith("@lunora/"),ma=(e,t,a,r)=>P(e)?r.get(e)??a:t,k=(e,t,a)=>({...e,[t]:a}),ee=(e,t,a)=>Object.fromEntries(Object.entries(e).map(([r,o])=>[r,ma(r,o,t,a)])),fa=async(e,t,a,r)=>{const o=u(e,"package.json"),s=JSON.parse(b(o,"utf8"));let n=k(s.dependencies??{},"lunorash",r);n=k(n,"@lunora/ratelimit",r),a.adapter.startsWith("@lunora/")&&(n=k(n,a.adapter,r));for(const[c,p]of Object.entries(a.extraDependencies??{}))n=k(n,c,p);let i=k(s.devDependencies??{},"@lunora/vite",r);i=k(i,"@lunora/studio",r);for(const[c,p]of Object.entries(ua))i=k(i,c,p);const l=[...Object.keys(n),...Object.keys(i)].filter(c=>P(c)),d=await ce(l,r);s.name=t,s.imports={...s.imports,"#lunora/*":"./lunora/*"},s.dependencies=ee(n,r,d),s.devDependencies=ee(i,r,d),s.scripts={...s.scripts,codegen:"lunora codegen",deploy:"vite build && lunora deploy"},v(o,`${JSON.stringify(s,void 0,4)}
1197
- `,"utf8")},va=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],Se=e=>va.map(t=>u(e,t)).find(t=>m(t)),ga=(e,t)=>{const a=Se(e);if(a===void 0){t.warn("overlay: no vite.config found in the create-vite base — add `lunora()` to your Vite plugins manually.");return}const r=ke(b(a,"utf8"));r.changed&&v(a,r.code,"utf8")},wa=async e=>{const{adapter:t,distTag:a,logger:r,name:o,target:s}=e,n=[];x(s,u("lunora","ratelimit","schema.ts"),oa,n),x(s,u("lunora","schema.ts"),sa,n),x(s,u("lunora","messages.ts"),na,n),x(s,u("src","server.ts"),ia,n),x(s,"wrangler.jsonc",la.replaceAll("__NAME__",o),n),x(s,".env.example",da,n);for(const i of t.files)x(s,i.path,i.contents,n);return ga(s,r),await fa(s,o,t,a),ha(s),n},ya=["lunar","silver","silent","waning","waxing","crescent","cosmic","stellar","orbital","gibbous","twilight","midnight","shimmering","drifting","weightless"],ba=["moon","tide","crater","comet","eclipse","halo","orbit","nebula","voyager","lander","rover","beacon","harbor","meadow","fox"],te=e=>e[Math.floor(Math.random()*e.length)],xa=()=>`${te(ya)}-${te(ba)}`,ka=async()=>vt.lookup("github.com").then(()=>!0,()=>!1),Ca=/^(?:gh|github):([^/]+)\/([^#/]+)(?:\/[^#]*)?(?:#(.+))?$/,Le=e=>{const t=Ca.exec(e);if(t===null)return;const[,a,r,o]=t;if(!(a===void 0||r===void 0))return{owner:a,ref:o??"HEAD",repo:r}},Sa=async e=>{const t=Le(e);if(t===void 0)return;const a=`https://codeload.github.com/${t.owner}/${t.repo}/tar.gz/${t.ref}`;try{const r=await fetch(a,{method:"HEAD"});return r.status===404?!1:r.ok?!0:void 0}catch{return}},Me=async e=>e.isLocal||!(e.source===void 0||Le(e.source)!==void 0)?!0:await ka()?e.source!==void 0&&await Sa(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),y={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?"},La=new Set([".gitignore",".html",".js",".json",".jsonc",".md",".mjs",".ts",".tsx"]),Ma=`import { defineConfig } from "vite";
1196
+ `,"utf8")},D=e=>e==="lunorash"||e.startsWith("@lunora/"),va=(e,t,a,r)=>D(e)?r.get(e)??a:t,k=(e,t,a)=>({...e,[t]:a}),ee=(e,t,a)=>Object.fromEntries(Object.entries(e).map(([r,o])=>[r,va(r,o,t,a)])),ga=async(e,t,a,r)=>{const o=u(e,"package.json"),n=JSON.parse(b(o,"utf8"));let s=k(n.dependencies??{},"lunorash",r);s=k(s,"@lunora/ratelimit",r),a.adapter.startsWith("@lunora/")&&(s=k(s,a.adapter,r));for(const[c,p]of Object.entries(a.extraDependencies??{}))s=k(s,c,p);let i=k(n.devDependencies??{},"@lunora/vite",r);i=k(i,"@lunora/studio",r);for(const[c,p]of Object.entries(ha))i=k(i,c,p);const l=[...Object.keys(s),...Object.keys(i)].filter(c=>D(c)),d=await ce(l,r);n.name=t,n.imports={...n.imports,"#lunora/*":"./lunora/*"},n.dependencies=ee(s,r,d),n.devDependencies=ee(i,r,d),n.scripts={...n.scripts,codegen:"lunora codegen",deploy:"vite build && lunora deploy"},v(o,`${JSON.stringify(n,void 0,4)}
1197
+ `,"utf8")},wa=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],Se=e=>wa.map(t=>u(e,t)).find(t=>m(t)),ya=(e,t)=>{const a=Se(e);if(a===void 0){t.warn("overlay: no vite.config found in the create-vite base — add `lunora()` to your Vite plugins manually.");return}const r=ke(b(a,"utf8"));r.changed&&v(a,r.code,"utf8")},ba=async e=>{const{adapter:t,distTag:a,logger:r,name:o,target:n}=e,s=[];x(n,u("lunora","ratelimit","schema.ts"),sa,s),x(n,u("lunora","schema.ts"),ia,s),x(n,u("lunora","messages.ts"),la,s),x(n,u("src","server.ts"),ca,s),x(n,"wrangler.jsonc",da.replaceAll("__NAME__",o),s),x(n,".env.example",pa,s);for(const i of t.files)x(n,i.path,i.contents,s);return ya(n,r),await ga(n,o,t,a),fa(n),s},xa=["lunar","silver","silent","waning","waxing","crescent","cosmic","stellar","orbital","gibbous","twilight","midnight","shimmering","drifting","weightless"],ka=["moon","tide","crater","comet","eclipse","halo","orbit","nebula","voyager","lander","rover","beacon","harbor","meadow","fox"],te=e=>e[Math.floor(Math.random()*e.length)],Ca=()=>`${te(xa)}-${te(ka)}`,Sa=async()=>wt.lookup("github.com").then(()=>!0,()=>!1),La=/^(?:gh|github):([^/]+)\/([^#/]+)(?:\/[^#]*)?(?:#(.+))?$/,Le=e=>{const t=La.exec(e);if(t===null)return;const[,a,r,o]=t;if(!(a===void 0||r===void 0))return{owner:a,ref:o??"HEAD",repo:r}},Ma=async e=>{const t=Le(e);if(t===void 0)return;const a=`https://codeload.github.com/${t.owner}/${t.repo}/tar.gz/${t.ref}`;try{const r=await fetch(a,{method:"HEAD"});return r.status===404?!1:r.ok?!0:void 0}catch{return}},Me=async e=>e.isLocal||!(e.source===void 0||Le(e.source)!==void 0)?!0:await Sa()?e.source!==void 0&&await Ma(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),y={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?"},Aa=new Set([".gitignore",".html",".js",".json",".jsonc",".md",".mjs",".ts",".tsx"]),Ea=`import { defineConfig } from "vite";
1198
1198
  import { lunora } from "@lunora/vite";
1199
1199
 
1200
1200
  export default defineConfig({ plugins: [lunora()] });
1201
- `,Aa=`import { defineSchema, defineTable, v } from "@lunora/server";
1201
+ `,Na=`import { defineSchema, defineTable, v } from "@lunora/server";
1202
1202
 
1203
1203
  export default defineSchema({
1204
1204
  messages: defineTable({
@@ -1208,7 +1208,7 @@ export default defineSchema({
1208
1208
  .shardBy("channelId")
1209
1209
  .index("by_channel", ["channelId"]),
1210
1210
  });
1211
- `,Ea=`import { mutation, query, v } from "./_generated/server";
1211
+ `,Ia=`import { mutation, query, v } from "./_generated/server";
1212
1212
 
1213
1213
  export const list = query
1214
1214
  .input({ channelId: v.id("channels"), limit: v.optional(v.number()) })
@@ -1221,8 +1221,8 @@ export const send = mutation
1221
1221
  .mutation(async ({ args }) => {
1222
1222
  return { channelId: args.channelId, text: args.text };
1223
1223
  });
1224
- `,Na="gh:anolilab/lunora/templates",Ia=e=>{const t=e.lastIndexOf(".");return t===-1?!1:La.has(e.slice(t))},_a=(e,t)=>e.replaceAll("{{name}}",t),$a=async(e,t)=>{const a=new Set;for(const r of e)if(E(r)==="package.json")try{const o=JSON.parse(b(r,"utf8"));for(const s of["dependencies","devDependencies"])for(const n of Object.keys(o[s]??{}))P(n)&&a.add(n)}catch{}return ce(a,t)},Ra=(e,t,a)=>{let r;try{r=JSON.parse(e)}catch{return e}let o=e;for(const s of["dependencies","devDependencies"])for(const n of Object.keys(r[s]??{})){if(!P(n))continue;const i=a.get(n)??t,l=Ge(o,[s,n],i,{formattingOptions:{insertSpaces:!0,tabSize:4}});o=Je(o,l)}return o},Oa=["@parcel/watcher","esbuild","lmdb","msgpackr-extract","rs-module-lexer","sharp","unrs-resolver","vue-demi","workerd"],Ta=["cpu-features","protobufjs","ssh2"],Ae="pnpm-workspace.yaml",Pa=()=>["# 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:",...Oa.map(e=>` '${e}': true`),...Ta.map(e=>` '${e}': false`),""].join(`
1225
- `),q=e=>{const t=[];for(const a of qe(e,{includeDirs:!1,includeFiles:!0}))Oe(a.path).isSymbolicLink()||t.push(a.path);return t},Ee=async(e,t,a)=>{const r=q(e),o=[],s=de(),n=await $a(r,s);for(const i of r){const l=Ke(e,i),d=u(t,l);M(A(d),{recursive:!0});const c=b(i);let p=Ia(i)?_a(c.toString("utf8"),a):void 0;p!==void 0&&E(i)==="package.json"&&(p=Ra(p,s,n)),p===void 0?v(d,c):v(d,p,"utf8"),o.push(d)}return o},B=(e,t,a)=>t!==void 0&&t.length>0?t:`${Na}/${e}#${ue(a)}`,Da=e=>e.includes("..")?!1:e.startsWith("gh:")||e.startsWith("github:")||e.startsWith("https://"),S=(e,t)=>{e.info(`[dry-run] would ${t}`)},K=(e,t,a)=>{g()&&process.stdout.write(`
1226
- `),e.success(`scaffolded ${String(t.length)} files into ${a}`)},Ba=(e,t)=>{const{args:a,command:r}=We(e,t);return`${r} ${a.join(" ")}`},Ne=(e,t)=>{let a=ie(e);for(;;){if(t(a))return!0;const r=A(a);if(r===a)return!1;a=r}},ja=e=>{if(m(u(e,Ae)))return!0;const t=u(e,"package.json");if(!m(t))return!1;try{return JSON.parse(b(t,"utf8")).workspaces!==void 0}catch{return!1}},Ie=e=>Ne(e,ja),Va=e=>Ne(e,t=>m(u(t,".git"))),Ua=async(e,t)=>{if(e.yes===!0||!g()||Va(A(t)))return;if(!await fe(y.git,{badge:f.git,defaultYes:!1})){await ve("Sounds good! You can always run git init manually.");return}if(e.dryRun===!0){S(e.logger,"initialize a git repository");return}const a=e.spawner??pe;(await st("Initializing a git repository…",()=>a({args:["init"],command:"git",cwd:t}))).code===0?await R("git","Initialized an empty git repository."):e.logger.warn("`git init` failed — initialize it yourself later with `git init`.")},Fa=async(e,t,a,r)=>{const o=[{code:`cd ./${e}`,lead:"Enter your project directory using"}];t===void 0&&o.push({code:`${a} install`,lead:"Install dependencies with",tail:r?" from the workspace root":void 0}),o.push({code:Fe(a,"dev"),lead:"Run",tail:" to start the dev server."},{code:"lunora add",lead:"Add features like auth or storage using"});const s=[{code:"https://lunora.sh/docs",lead:"Read the docs at"},{code:"https://lunora.sh/chat",lead:"Stuck? Join the chat at"}];if(g()){await nt(f.next,y.nextHeader,o,s);return}const n=o.map(i=>`${i.lead} ${i.code}${i.tail??""}`);n.push("",...s.map(i=>`${i.lead} ${i.code}${i.tail??""}`)),await R("next",y.nextHeader,n.join(`
1227
- `))},Ha=e=>e.yes!==!0&&(e.installPrompt!==void 0||g()),Wa=async(e,t)=>{if(!Ha(e)||Ie(A(t)))return;const a=Ue(e.packageManagerProbe),[r]=a;if(r===void 0)return;if(!await(e.installPrompt?.confirmInstall??(async()=>fe(y.install,{badge:f.deps,defaultYes:!0})))()){await ve("No problem! Remember to install dependencies after setup.");return}let s=r;if(a.length>1&&(s=e.installPrompt?await e.installPrompt.selectManager(a):await H(y.packageManager,a.map(c=>({label:c,value:c})),{badge:f.deps,default:r})??r),e.dryRun===!0){S(e.logger,`install dependencies with ${s}`);return}if(s==="pnpm"){const c=u(t,Ae);m(c)||v(c,Pa(),"utf8")}const n=e.spawner??pe,{args:i,command:l}=ne(s);await R("deps",`Installing dependencies with ${s}…`);const d=await n({args:i,command:l,cwd:t});if(d.code!==0){e.logger.warn(`\`${l} install\` exited with code ${String(d.code)} — run it yourself in ${E(t)}/.`);return}return await R("deps",`Dependencies installed with ${s}.`),s},za=async(e,t,a,r,o)=>{const s=u(e,t);if(!m(s))return o.error(`template not found in local source: ${s}`),{code:1,files:[],target:a};const n=await Ee(s,a,r);return K(o,n,a),{code:0,files:n,target:a}},qa=async e=>{const{logger:t,name:a,ref:r,source:o,target:s,templateType:n}=e,i=oe(u(se(),"lunora-init-fetch-")),l=u(i,"template");try{const d=o!==void 0&&o.length>0?r:await et(r,t),c=B(n,o,d);let p,h=[];await ge([{label:`${n} template fetched`,run:async()=>{p=await le(c,{cwd:i,dir:l,force:!0,install:!1,silent:!0})}},{label:`files copied into ${a}/`,run:async()=>{h=await Ee(l,s,a)}}],{end:"Project initialized!",start:"Project initializing…"});const I=q(l);return g()&&process.stdout.write(`
1228
- `),t.info(p?.commit?`template: ${p.source} @ ${p.commit} (${String(I.length)} files)`:`template: ${p?.source??c} (${String(I.length)} files)`),K(t,h,s),{code:0,files:h,target:s}}catch(d){if(d instanceof F)throw d;const{hints:c,message:p}=Pt(d,{ref:ue(r),remote:B(n,o,r),templateType:n});t.error(p);for(const h of c)t.warn(h);return{code:1,files:[],target:s}}finally{$(i,{force:!0,recursive:!0})}},Ka=e=>{for(const t of["_gitignore","_npmrc","_gitattributes"]){const a=u(e,t);m(a)&&Re(a,u(e,`.${t.slice(1)}`))}},Ga=async e=>{const{framework:t,logger:a,name:r,overlayBaseFrom:o,target:s}=e,n=T[t],i=oe(u(se(),"lunora-vite-base-"));try{let l;if(o!==void 0&&(l=u(o,`template-${n.createViteTemplate}`),!m(l)))return a.error(`create-vite base not found on disk: ${l}`),{code:1,files:[],target:s};const d=async()=>{if(l!==void 0){G(l,s,{recursive:!0});return}const p=u(i,"base"),h=`github:vitejs/vite/packages/create-vite/template-${n.createViteTemplate}#main`;await le(h,{cwd:i,dir:p,force:!0,install:!1,silent:!0}),Ka(p),G(p,s,{recursive:!0})};let c=[];return await ge([{label:`create-vite (${n.label}) base ready`,run:d},{label:`Lunora overlay applied (${n.label})`,run:async()=>{c=await wa({adapter:n,distTag:de(),logger:a,name:r,target:s})}}],{end:"Project initialized!",start:"Project initializing…"}),K(a,c,s),{code:0,files:[...q(s)],target:s}}catch(l){if(l instanceof F)throw l;const d=l instanceof Error?l.message:String(l);return a.error(`failed to scaffold the ${n.label} base: ${d}`),{code:1,files:[],target:s}}finally{$(i,{force:!0,recursive:!0})}},j=(e,t,a,r,o)=>(o.error(`init --in-place: could not ${e} ${t}: ${a instanceof Error?a.message:String(a)}`),{code:1,files:[],target:r}),Ja=(e,t)=>{const a=u(e,"vite.config.ts");try{v(a,Ma,"utf8")}catch(r){return j("write",a,r,e,t)}return t.success(`created ${a} with lunora() plugin`),{code:0,files:[a],target:e}},Ya=(e,t,a)=>{let r;try{r=b(e,"utf8")}catch(s){return j("read",e,s,t,a)}const o=ke(r);if(!o.changed)return a.info(`${e}: ${o.reason??"no changes needed"}`),{code:0,files:[],target:t};try{v(e,o.code,"utf8")}catch(s){return j("write",e,s,t,a)}return a.success(`patched ${e} — added lunora() plugin`),{code:0,files:[e],target:t}},Xa=(e,t)=>{const a=u(e,"lunora"),r=u(a,"schema.ts");if(m(r))return t.info(`lunora/ already present — left ${r} untouched`),[];const o=[];try{M(a,{recursive:!0}),v(r,Aa,"utf8"),o.push(r);const s=u(a,"messages.ts");m(s)||(v(s,Ea,"utf8"),o.push(s)),t.success(`scaffolded lunora/ (${String(o.length)} file(s))`)}catch(s){const n=s instanceof Error?s.message:String(s);t.error(`init --here: could not scaffold lunora/: ${n}`)}return o},Qa=(e,t,a)=>{const{adapter:r,class:o,framework:s}=e;a.info(""),a.info(`detected framework: ${s} (class ${o})`),a.info("next steps:"),a.info(` 1. install the adapter: ${Ba(t,[r,"@lunora/client","@lunora/runtime","@lunora/server"])}`),a.info(" 2. run codegen: lunora codegen"),o==="A"?(a.info(" 3. compose one worker: wrap your worker entry with"),a.info(" createWorker({ httpRouter: <your framework SSR handler>, shardDO: ShardDO, ... })"),a.info(` 4. add the provider: mount the ${r} provider in your root layout/route`),a.info(" 5. make a loader live: preloadQuery() in a loader, usePreloadedQuery() in the component"),a.info(" see https://lunora.sh/docs/frameworks/reactive-loaders")):o==="B"?(a.info(" 3. inject Lunora: mount Lunora realtime under /_lunora/* in your server hook"),a.info(` (${s} owns its Cloudflare adapter — Lunora composes into its server entry)`),a.info(` 4. add the provider: mount the ${r} provider in your root layout`),a.info(" 5. read the guide: https://lunora.sh/docs/frameworks/deploy")):(a.info(" 3. add the provider: wrap your app with the LunoraProvider from @lunora/react"),a.info(" 4. read the guide: https://lunora.sh/docs/frameworks/bring-your-framework")),a.info("")},Za=(e,t,a)=>{const r=Se(e);return r===void 0?t==="sveltekit"||t==="nuxt"||t==="astro"?(a.info(`no Vite config found — ${t} wires Lunora through its server entry (see next steps)`),{code:0,files:[],target:e}):Ja(e,a):Ya(r,e,a)},er=(e,t)=>{const a=Lt(e),r=Za(e,a.framework,t);if(r.code!==0)return r;const o=Xa(e,t);return Qa(a,V(e),t),{code:0,files:[...r.files,...o],target:e}},tr=e=>e.yes!==!0&&(e.prompt!==void 0||(e.interactive??g())),ae=async(e,t,a)=>{a.dryRun!==!0&&await Kt({apply:r=>ze(e,r),detected:He(e),interactive:t,logger:a.logger,multiSelect:a.lintPrompt??((r,o,s)=>me(r,o,{...s,badge:f.add}))})},ar=async(e,t)=>{const a=tr(e),r=e.add===void 0?[]:jt(e.add,n=>{e.logger.warn(n)}),s={applyAll:async n=>{if(n.length===0)return!0;if(e.dryRun===!0)return S(e.logger,`add ${n.map(h=>h.label).join(", ")}`),!0;const i=[],l=g()?{error:h=>{i.push({level:"error",message:h})},info:()=>{},success:()=>{},warn:h=>{i.push({level:"warn",message:h})}}:e.logger,d=n.map(h=>({running:`adding ${h.label}…`,task:()=>gt({allowUnsafeSource:e.allowUnsafeSource,cwd:t,from:e.registryFrom,logger:l,names:[...h.names],ref:e.ref,source:e.registrySource,transformManifest:h.transformManifest,yes:!0})})),c=`added ${n.map(h=>h.label).join(", ")}`,p=await it(f.add,d,c);for(const{level:h,message:I}of i)e.logger[h](I);return p.every(h=>h.code===0)},interactive:a,logger:e.logger,multiSelect:e.prompt?.multiSelect??((n,i,l)=>me(n,i,{...l,badge:f.add})),preselected:r.length>0?r:void 0,projectName:E(t),resolveAuthUiItem:()=>{try{const n=JSON.parse(b(u(t,"package.json"),"utf8"));return mt({...n.dependencies,...n.devDependencies})??"auth-ui-react"}catch{return"auth-ui-react"}},select:e.prompt?.select??((n,i,l)=>H(n,i,{...l,badge:f.add})),text:e.prompt?.text??((n,i)=>he(n,{...i,badge:f.add}))};if(r.length>0){await Z(s),await ae(t,a,e);return}g()&&await ot(y.extras),await Z(s),await ae(t,a,e)},D="react",_e=[{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 + a standalone Lunora 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 + a standalone Lunora 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"}],rr=Object.keys(T).join("|"),$e=_e.filter(e=>!z(e.value)).map(e=>e.value),or=$e.join("|"),sr=e=>z(e)?{framework:e,kind:"overlay"}:{kind:"template",templateType:e},nr=async e=>e.vite!==void 0?{framework:e.vite,kind:"overlay"}:e.templateType!==void 0?{kind:"template",templateType:e.templateType}:!g()||e.yes===!0?{framework:D,kind:"overlay"}:sr(await H(y.framework,_e,{badge:f.tmpl,default:D})??D),ir=e=>{if(g()||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 <${rr}>\` for an SPA, or \`-t <${or}>\` 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.`},lr=async(e,t,a,r)=>z(t)?await Me({isLocal:e.overlayBaseFrom!==void 0,logger:e.logger})?(M(r,{recursive:!0}),Ga({framework:t,logger:e.logger,name:a,overlayBaseFrom:e.overlayBaseFrom,target:r})):{code:1,files:[],target:r}:(e.logger.error(`init: unknown framework "${t}". Supported overlays: ${Object.keys(T).join(", ")}.`),{code:1,files:[],target:r}),cr=async(e,t,a,r)=>e.from!==void 0?await za(e.from,t,r,a,e.logger):e.source!==void 0&&e.source.length>0&&!e.allowUnsafeSource&&!Da(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:1,files:[],target:r}):await Me({isLocal:!1,logger:e.logger,source:B(t,e.source,e.ref)})?qa({logger:e.logger,name:a,ref:e.ref,source:e.source,target:r,templateType:t}):{code:1,files:[],target:r},dr=async(e,t,a)=>{await rt("realtime backend on Cloudflare Workers + Durable Objects");const r=ir(e);if(r!==void 0)return e.logger.error(r),{code:1,files:[],target:""};const o=xa(),s=e.name??await he(y.name,{badge:f.dir,default:o,placeholder:o}),n=await nr(e),i=s.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:1,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:1,files:[],target:""};const l=ie(t,i),d=m(l);if(d&&re(l).length>0)return e.logger.error(`target directory not empty: ${l}`),{code:1,files:[],target:l};if(e.dryRun===!0){const c=n.kind==="overlay"?`the ${n.framework} create-vite overlay`:`the ${n.templateType} template`;return S(e.logger,`scaffold ${c} into ${l}`),{code:0,files:[],target:l}}return a(l,d),n.kind==="overlay"?lr(e,n.framework,i,l):cr(e,n.templateType,i,l)},ur=(e,t)=>{const{target:a,targetPreExisted:r}=e;if(!(a===void 0||!m(a))){if(r===!0)for(const o of re(a))$(u(a,o),{force:!0,recursive:!0});else $(a,{force:!0,recursive:!0});t.info(`removed the partially-created project at ${a}`)}},pr=async(e,t,a)=>e.inPlace!==!0?dr(e,t,a):e.dryRun===!0?(S(e.logger,`configure Lunora into ${t}`),{code:0,files:[],target:t}):er(t,e.logger),hr=async(e,t,a)=>{await ar(e,t.target);const r=e.inPlace===!0?void 0:await Wa(e,t.target);if(e.inPlace!==!0){await Ua(e,t.target);const o=r??V(t.target);await Fa(E(t.target),r,o,Ie(a)),await Dt(e.logger)}},mr=(e,t,a)=>{if(t.code!==0||e.ci===void 0)return;if(e.dryRun===!0){S(e.logger,`scaffold a ${e.ci} CI deploy pipeline`);return}const r=e.inPlace===!0?a:t.target;try{const o=V(r);Ct(r,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.`)}},fr=async e=>{const t=e.cwd??process.cwd(),a={};let r;try{r=await pr(e,t,(o,s)=>{a.target=o,a.targetPreExisted=s}),r.code===0&&r.target!==""&&(a.target=void 0,await hr(e,r,t))}catch(o){if(o instanceof F)return ur(a,e.logger),process.stdout.write("\n ✖ Setup cancelled — run `lunora init` again whenever you're ready. 🌙\n"),{code:130,files:[],target:""};throw o}return mr(e,r,t),r},vr=e=>typeof e=="string"&&$e.includes(e),gr=(e,t)=>{if(e!==void 0){if(xt(e))return e;t.warn(`init: unknown --ci "${e}" — expected github | gitlab; skipping CI scaffold.`)}},Br=Xe(({argument:e,cwd:t,logger:a,options:r})=>{const o=r.template!==void 0&&vr(r.template)?r.template:void 0;return fr({add:r.add,allowUnsafeSource:r.allowUnsafeSource===!0,cwd:t,ci:gr(r.ci,a),dryRun:r.dryRun===!0,from:r.from,inPlace:r.here===!0,interactive:r.interactive===!0?!0:void 0,logger:a,name:e[0],ref:r.ref,source:r.source,templateType:o,vite:r.vite,yes:r.yes===!0})});export{Br as execute,vr as isTemplate,B as resolveTemplateSource,fr as runInitCommand};
1224
+ `,$a="gh:anolilab/lunora/templates",_a=e=>{const t=e.lastIndexOf(".");return t===-1?!1:Aa.has(e.slice(t))},Ra=(e,t)=>e.replaceAll("{{name}}",t),Ta=async(e,t)=>{const a=new Set;for(const r of e)if(E(r)==="package.json")try{const o=JSON.parse(b(r,"utf8"));for(const n of["dependencies","devDependencies"])for(const s of Object.keys(o[n]??{}))D(s)&&a.add(s)}catch{}return ce(a,t)},Oa=(e,t,a)=>{let r;try{r=JSON.parse(e)}catch{return e}let o=e;for(const n of["dependencies","devDependencies"])for(const s of Object.keys(r[n]??{})){if(!D(s))continue;const i=a.get(s)??t,l=Ye(o,[n,s],i,{formattingOptions:{insertSpaces:!0,tabSize:4}});o=Xe(o,l)}return o},Pa=["@parcel/watcher","esbuild","lmdb","msgpackr-extract","rs-module-lexer","sharp","unrs-resolver","vue-demi","workerd"],Da=["cpu-features","protobufjs","ssh2"],Ae="pnpm-workspace.yaml",Ba=()=>["# 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:",...Pa.map(e=>` '${e}': true`),...Da.map(e=>` '${e}': false`),""].join(`
1225
+ `),q=e=>{const t=[];for(const a of Ge(e,{includeDirs:!1,includeFiles:!0}))Pe(a.path).isSymbolicLink()||t.push(a.path);return t},Ee=async(e,t,a)=>{const r=q(e),o=[],n=de(),s=await Ta(r,n);for(const i of r){const l=Je(e,i),d=u(t,l);M(A(d),{recursive:!0});const c=b(i);let p=_a(i)?Ra(c.toString("utf8"),a):void 0;p!==void 0&&E(i)==="package.json"&&(p=Oa(p,n,s)),p===void 0?v(d,c):v(d,p,"utf8"),o.push(d)}return o},j=(e,t,a)=>t!==void 0&&t.length>0?t:`${$a}/${e}#${ue(a)}`,ja=e=>e.includes("..")?!1:e.startsWith("gh:")||e.startsWith("github:")||e.startsWith("https://"),S=(e,t)=>{e.info(`[dry-run] would ${t}`)},K=(e,t,a)=>{g()&&process.stdout.write(`
1226
+ `),e.success(`scaffolded ${String(t.length)} files into ${a}`)},Va=(e,t)=>{const{args:a,command:r}=qe(e,t);return`${r} ${a.join(" ")}`},Ne=(e,t)=>{let a=ie(e);for(;;){if(t(a))return!0;const r=A(a);if(r===a)return!1;a=r}},Ua=e=>{if(m(u(e,Ae)))return!0;const t=u(e,"package.json");if(!m(t))return!1;try{return JSON.parse(b(t,"utf8")).workspaces!==void 0}catch{return!1}},Ie=e=>Ne(e,Ua),Fa=e=>Ne(e,t=>m(u(t,".git"))),Ha=async(e,t)=>{if(e.yes===!0||!g()||Fa(A(t)))return;if(!await fe(y.git,{badge:f.git,defaultYes:!1})){await ve("Sounds good! You can always run git init manually.");return}if(e.dryRun===!0){S(e.logger,"initialize a git repository");return}const a=e.spawner??pe;(await it("Initializing a git repository…",()=>a({args:["init"],command:"git",cwd:t}))).code===0?await R("git","Initialized an empty git repository."):e.logger.warn("`git init` failed — initialize it yourself later with `git init`.")},Wa=async(e,t,a,r)=>{const o=[{code:`cd ./${e}`,lead:"Enter your project directory using"}];t===void 0&&o.push({code:`${a} install`,lead:"Install dependencies with",tail:r?" from the workspace root":void 0}),o.push({code:We(a,"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(g()){await lt(f.next,y.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 R("next",y.nextHeader,s.join(`
1227
+ `))},za=e=>e.yes!==!0&&(e.installPrompt!==void 0||g()),qa=async(e,t)=>{if(!za(e)||Ie(A(t)))return;const a=He(e.packageManagerProbe),[r]=a;if(r===void 0)return;if(!await(e.installPrompt?.confirmInstall??(async()=>fe(y.install,{badge:f.deps,defaultYes:!0})))()){await ve("No problem! Remember to install dependencies after setup.");return}let n=r;if(a.length>1&&(n=e.installPrompt?await e.installPrompt.selectManager(a):await W(y.packageManager,a.map(c=>({label:c,value:c})),{badge:f.deps,default:r})??r),e.dryRun===!0){S(e.logger,`install dependencies with ${n}`);return}if(n==="pnpm"){const c=u(t,Ae);m(c)||v(c,Ba(),"utf8")}const s=e.spawner??pe,{args:i,command:l}=se(n);await R("deps",`Installing dependencies with ${n}…`);const d=await s({args:i,command:l,cwd:t});if(d.code!==0){e.logger.warn(`\`${l} install\` exited with code ${String(d.code)} — run it yourself in ${E(t)}/.`);return}return await R("deps",`Dependencies installed with ${n}.`),n},Ka=async(e,t,a,r,o)=>{const n=u(e,t);if(!m(n))return o.error(`template not found in local source: ${n}`),{code:1,files:[],target:a};const s=await Ee(n,a,r);return K(o,s,a),{code:0,files:s,target:a}},Ga=async e=>{const{logger:t,name:a,ref:r,source:o,target:n,templateType:s}=e,i=oe(u(ne(),"lunora-init-fetch-")),l=u(i,"template");try{const d=o!==void 0&&o.length>0?r:await at(r,t),c=j(s,o,d);let p,h=[];await ge([{label:`${s} template fetched`,run:async()=>{p=await le(c,{cwd:i,dir:l,force:!0,install:!1,silent:!0})}},{label:`files copied into ${a}/`,run:async()=>{h=await Ee(l,n,a)}}],{end:"Project initialized!",start:"Project initializing…"});const I=q(l);return g()&&process.stdout.write(`
1228
+ `),t.info(p?.commit?`template: ${p.source} @ ${p.commit} (${String(I.length)} files)`:`template: ${p?.source??c} (${String(I.length)} files)`),K(t,h,n),{code:0,files:h,target:n}}catch(d){if(d instanceof H)throw d;const{hints:c,message:p}=Bt(d,{ref:ue(r),remote:j(s,o,r),templateType:s});t.error(p);for(const h of c)t.warn(h);return{code:1,files:[],target:n}}finally{_(i,{force:!0,recursive:!0})}},Ja=e=>{for(const t of["_gitignore","_npmrc","_gitattributes"]){const a=u(e,t);m(a)&&Oe(a,u(e,`.${t.slice(1)}`))}},Ya=async e=>{const{framework:t,logger:a,name:r,overlayBaseFrom:o,target:n}=e,s=O[t],i=oe(u(ne(),"lunora-vite-base-"));try{let l;if(o!==void 0&&(l=u(o,`template-${s.createViteTemplate}`),!m(l)))return a.error(`create-vite base not found on disk: ${l}`),{code:1,files:[],target:n};const d=async()=>{if(l!==void 0){G(l,n,{recursive:!0});return}const p=u(i,"base"),h=`github:vitejs/vite/packages/create-vite/template-${s.createViteTemplate}#main`;await le(h,{cwd:i,dir:p,force:!0,install:!1,silent:!0}),Ja(p),G(p,n,{recursive:!0})};let c=[];return await ge([{label:`create-vite (${s.label}) base ready`,run:d},{label:`Lunora overlay applied (${s.label})`,run:async()=>{c=await ba({adapter:s,distTag:de(),logger:a,name:r,target:n})}}],{end:"Project initialized!",start:"Project initializing…"}),K(a,c,n),{code:0,files:[...q(n)],target:n}}catch(l){if(l instanceof H)throw l;const d=l instanceof Error?l.message:String(l);return a.error(`failed to scaffold the ${s.label} base: ${d}`),{code:1,files:[],target:n}}finally{_(i,{force:!0,recursive:!0})}},V=(e,t,a,r,o)=>(o.error(`init --in-place: could not ${e} ${t}: ${a instanceof Error?a.message:String(a)}`),{code:1,files:[],target:r}),Xa=(e,t)=>{const a=u(e,"vite.config.ts");try{v(a,Ea,"utf8")}catch(r){return V("write",a,r,e,t)}return t.success(`created ${a} with lunora() plugin`),{code:0,files:[a],target:e}},Qa=(e,t,a)=>{let r;try{r=b(e,"utf8")}catch(n){return V("read",e,n,t,a)}const o=ke(r);if(!o.changed)return a.info(`${e}: ${o.reason??"no changes needed"}`),{code:0,files:[],target:t};try{v(e,o.code,"utf8")}catch(n){return V("write",e,n,t,a)}return a.success(`patched ${e} — added lunora() plugin`),{code:0,files:[e],target:t}},Za=(e,t)=>{const a=u(e,"lunora"),r=u(a,"schema.ts");if(m(r))return t.info(`lunora/ already present — left ${r} untouched`),[];const o=[];try{M(a,{recursive:!0}),v(r,Na,"utf8"),o.push(r);const n=u(a,"messages.ts");m(n)||(v(n,Ia,"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},er=(e,t,a)=>{const{adapter:r,class:o,framework:n}=e;a.info(""),a.info(`detected framework: ${n} (class ${o})`),a.info("next steps:"),a.info(` 1. install the adapter: ${Va(t,[r,"@lunora/client","@lunora/runtime","@lunora/server"])}`),a.info(" 2. run codegen: lunora codegen"),o==="A"?(a.info(" 3. compose one worker: wrap your worker entry with"),a.info(" createWorker({ httpRouter: <your framework SSR handler>, shardDO: ShardDO, ... })"),a.info(` 4. add the provider: mount the ${r} provider in your root layout/route`),a.info(" 5. make a loader live: preloadQuery() in a loader, usePreloadedQuery() in the component"),a.info(" see https://lunora.sh/docs/frameworks/reactive-loaders")):o==="B"?(a.info(" 3. inject Lunora: mount Lunora realtime under /_lunora/* in your server hook"),a.info(` (${n} owns its Cloudflare adapter — Lunora composes into its server entry)`),a.info(` 4. add the provider: mount the ${r} provider in your root layout`),a.info(" 5. read the guide: https://lunora.sh/docs/frameworks/deploy")):(a.info(" 3. add the provider: wrap your app with the LunoraProvider from @lunora/react"),a.info(" 4. read the guide: https://lunora.sh/docs/frameworks/bring-your-framework")),a.info("")},tr=(e,t,a)=>{const r=Se(e);return r===void 0?t==="sveltekit"||t==="nuxt"||t==="astro"?(a.info(`no Vite config found — ${t} wires Lunora through its server entry (see next steps)`),{code:0,files:[],target:e}):Xa(e,a):Qa(r,e,a)},ar=(e,t)=>{const a=At(e),r=tr(e,a.framework,t);if(r.code!==0)return r;const o=Za(e,t);return er(a,U(e),t),{code:0,files:[...r.files,...o],target:e}},rr=e=>e.yes!==!0&&(e.prompt!==void 0||(e.interactive??g())),ae=async(e,t,a)=>{a.dryRun!==!0&&await Jt({apply:r=>Ke(e,r),detected:ze(e),interactive:t,logger:a.logger,multiSelect:a.lintPrompt??((r,o,n)=>me(r,o,{...n,badge:f.add}))})},or=async(e,t)=>{const a=rr(e),r=e.add===void 0?[]:Ut(e.add,s=>{e.logger.warn(s)}),n={applyAll:async s=>{if(s.length===0)return!0;if(e.dryRun===!0)return S(e.logger,`add ${s.map(h=>h.label).join(", ")}`),!0;const i=[],l=g()?{error:h=>{i.push({level:"error",message:h})},info:()=>{},success:()=>{},warn:h=>{i.push({level:"warn",message:h})}}:e.logger,d=s.map(h=>({running:`adding ${h.label}…`,task:()=>yt({allowUnsafeSource:e.allowUnsafeSource,cwd:t,from:e.registryFrom,logger:l,names:[...h.names],ref:e.ref,source:e.registrySource,transformManifest:h.transformManifest,yes:!0})})),c=`added ${s.map(h=>h.label).join(", ")}`,p=await ct(f.add,d,c);for(const{level:h,message:I}of i)e.logger[h](I);return p.every(h=>h.code===0)},interactive:a,logger:e.logger,multiSelect:e.prompt?.multiSelect??((s,i,l)=>me(s,i,{...l,badge:f.add})),preselected:r.length>0?r:void 0,projectName:E(t),resolveAuthUiItem:()=>{try{const s=JSON.parse(b(u(t,"package.json"),"utf8"));return vt({...s.dependencies,...s.devDependencies})??"auth-ui-react"}catch{return"auth-ui-react"}},select:e.prompt?.select??((s,i,l)=>W(s,i,{...l,badge:f.add})),text:e.prompt?.text??((s,i)=>he(s,{...i,badge:f.add}))};if(r.length>0){await Z(n),await ae(t,a,e);return}g()&&await st(y.extras),await Z(n),await ae(t,a,e)},B="react",$e=[{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 + a standalone Lunora 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 + a standalone Lunora 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"}],_e=Object.keys(O).join("|"),Re=$e.filter(e=>!P(e.value)).map(e=>e.value),Te=Re.join("|"),nr=e=>P(e)?{framework:e,kind:"overlay"}:{kind:"template",templateType:e},sr=async e=>e.vite!==void 0?{framework:e.vite,kind:"overlay"}:e.templateType!==void 0?{kind:"template",templateType:e.templateType}:!g()||e.yes===!0?{framework:B,kind:"overlay"}:nr(await W(y.framework,$e,{badge:f.tmpl,default:B})??B),ir=e=>{if(g()||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 <${_e}>\` for an SPA, or \`-t <${Te}>\` 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.`},lr=async(e,t,a,r)=>P(t)?await Me({isLocal:e.overlayBaseFrom!==void 0,logger:e.logger})?(M(r,{recursive:!0}),Ya({framework:t,logger:e.logger,name:a,overlayBaseFrom:e.overlayBaseFrom,target:r})):{code:1,files:[],target:r}:(e.logger.error(`init: unknown framework "${t}". Supported overlays: ${Object.keys(O).join(", ")}.`),{code:1,files:[],target:r}),cr=async(e,t,a,r)=>e.from!==void 0?await Ka(e.from,t,r,a,e.logger):e.source!==void 0&&e.source.length>0&&!e.allowUnsafeSource&&!ja(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:1,files:[],target:r}):await Me({isLocal:!1,logger:e.logger,source:j(t,e.source,e.ref)})?Ga({logger:e.logger,name:a,ref:e.ref,source:e.source,target:r,templateType:t}):{code:1,files:[],target:r},dr=async(e,t,a)=>{await nt("realtime backend on Cloudflare Workers + Durable Objects");const r=ir(e);if(r!==void 0)return e.logger.error(r),{code:1,files:[],target:""};const o=Ca(),n=e.name??await he(y.name,{badge:f.dir,default:o,placeholder:o}),s=await sr(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:1,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:1,files:[],target:""};const l=ie(t,i),d=m(l);if(d&&re(l).length>0)return e.logger.error(`target directory not empty: ${l}`),{code:1,files:[],target:l};if(e.dryRun===!0){const c=s.kind==="overlay"?`the ${s.framework} create-vite overlay`:`the ${s.templateType} template`;return S(e.logger,`scaffold ${c} into ${l}`),{code:0,files:[],target:l}}return a(l,d),s.kind==="overlay"?lr(e,s.framework,i,l):cr(e,s.templateType,i,l)},ur=(e,t)=>{const{target:a,targetPreExisted:r}=e;if(!(a===void 0||!m(a))){if(r===!0)for(const o of re(a))_(u(a,o),{force:!0,recursive:!0});else _(a,{force:!0,recursive:!0});t.info(`removed the partially-created project at ${a}`)}},pr=async(e,t,a)=>e.inPlace!==!0?dr(e,t,a):e.dryRun===!0?(S(e.logger,`configure Lunora into ${t}`),{code:0,files:[],target:t}):ar(t,e.logger),hr=async(e,t,a)=>{await or(e,t.target);const r=e.inPlace===!0?void 0:await qa(e,t.target);if(e.inPlace!==!0){await Ha(e,t.target);const o=r??U(t.target);await Wa(E(t.target),r,o,Ie(a)),await jt(e.logger)}},mr=(e,t,a)=>{if(t.code!==0||e.ci===void 0)return;if(e.dryRun===!0){S(e.logger,`scaffold a ${e.ci} CI deploy pipeline`);return}const r=e.inPlace===!0?a:t.target;try{const o=U(r);Lt(r,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.`)}},fr=async e=>{const t=e.cwd??process.cwd(),a={};let r;try{r=await pr(e,t,(o,n)=>{a.target=o,a.targetPreExisted=n}),r.code===0&&r.target!==""&&(a.target=void 0,await hr(e,r,t))}catch(o){if(o instanceof H)return ur(a,e.logger),process.stdout.write("\n ✖ Setup cancelled — run `lunora init` again whenever you're ready. 🌙\n"),{code:130,files:[],target:""};throw o}return mr(e,r,t),r},vr=e=>typeof e=="string"&&Re.includes(e),gr=(e,t)=>{if(e!==void 0){if(Ct(e))return e;t.warn(`init: unknown --ci "${e}" — expected github | gitlab; skipping CI scaffold.`)}},wr=e=>e===void 0?{}:vr(e)?{templateType:e}:P(e)?{vite:e}:{error:`init: unknown --template "${e}" — expected a bespoke template (${Te}) or an overlay framework (${_e}).`},jr=Ze(({argument:e,cwd:t,logger:a,options:r})=>{const o=wr(r.template);return"error"in o?(a.error(o.error),{code:1}):fr({add:r.add,allowUnsafeSource:r.allowUnsafeSource===!0,cwd:t,ci:gr(r.ci,a),dryRun:r.dryRun===!0,from:r.from,inPlace:r.here===!0,interactive:r.interactive===!0?!0:void 0,logger:a,name:e[0],ref:r.ref,source:r.source,templateType:o.templateType,vite:r.vite??o.vite,yes:r.yes===!0})});export{jr as execute,vr as isTemplate,wr as resolveTemplateFlag,j as resolveTemplateSource,fr as runInitCommand};
@@ -1,4 +1,4 @@
1
- import{existsSync as m,mkdirSync as T,writeFileSync as h,mkdtempSync as N,rmSync as M,readFileSync as I}from"node:fs";import{tmpdir as R}from"node:os";import{discoverSchema as _,readPackageDependencies as U,discoverMigrations as x}from"@lunora/codegen";import{isInteractive as C,promptSelect as O,promptText as F}from"@lunora/config";import{LunoraError as y}from"@lunora/errors";import{join as c}from"@visulima/path";import{Project as b}from"ts-morph";import{r as P}from"../packem_shared/admin-url-Cil3Or6N.mjs";import{d as D}from"../packem_shared/command-DwC11Cwe.mjs";import{diffSnapshots as z,renderMigrationFile as L}from"../packem_shared/diffSnapshots-CIOFQN_a.mjs";import{r as j}from"../packem_shared/resolve-target-BRvw8Pf7.mjs";import q from"../packem_shared/schemaIrToSnapshot-qpRoV7HY.mjs";import{readAndLogBody as H}from"./runRpcCommand.mjs";import{runExportCommand as G}from"../packem_shared/runExportCommand-DmXKEWSq.mjs";import{r as B}from"../packem_shared/import-CrVGrOt3.mjs";const u="__lunora_reproject__",W=e=>{if(!e.startsWith(u))return;const r=e.slice(u.length);return r===""?void 0:r},J=".snapshot.json",k=/[^\da-z]+/gu,A=(e,r)=>{let n=0,t=e.length;for(;n<t&&e[n]===r;)n+=1;for(;t>n&&e[t-1]===r;)t-=1;return e.slice(n,t)},K=e=>{const r=A(e.toLowerCase().replaceAll(k,"_"),"_");return r===""?"auto":r},V=e=>{const r=(n,t=2)=>n.toString().padStart(t,"0");return`${String(e.getUTCFullYear())}${r(e.getUTCMonth()+1)}${r(e.getUTCDate())}${r(e.getUTCHours())}${r(e.getUTCMinutes())}${r(e.getUTCSeconds())}`},Z=e=>{if(m(e))try{const r=I(e,"utf8"),n=JSON.parse(r);if(n.version!==1)throw new y("INTERNAL",`unsupported snapshot version: ${n.version}`);return n}catch(r){const n=r instanceof Error?r.message:String(r);throw new y("INTERNAL",`failed to read ${e}: ${n}`,{cause:r})}},X=e=>{const r=e.cwd??process.cwd(),n=c(r,"lunora","schema.ts");if(!m(n))return e.logger.error(`schema not found: ${n} — run \`vis generate lunora-table --name=<name>\` to create one`),{code:1,empty:!0,migrationFile:""};const t=new b({skipAddingFilesFromTsConfig:!0}),a=_(t,n),s=q(a),o=c(r,"lunora","migrations"),i=c(o,J);let d;try{d=Z(i)}catch(g){return e.logger.error(g instanceof Error?g.message:String(g)),{code:1,empty:!0,migrationFile:""}}const l=z(d,s);if(l.empty)return e.logger.info("no schema changes detected — snapshot is already up to date"),{code:0,empty:!0,migrationFile:""};const v=(e.now??(()=>new Date))(),p=K(e.name??"auto"),w=`${V(v)}_${p}.sql`,f=c(o,w);T(o,{recursive:!0});const E=L(p,l,v.toISOString());return h(f,E,"utf8"),h(i,`${JSON.stringify(s,void 0,4)}
1
+ import{existsSync as m,mkdirSync as T,writeFileSync as h,mkdtempSync as N,rmSync as M,readFileSync as I}from"node:fs";import{tmpdir as R}from"node:os";import{discoverSchema as _,readPackageDependencies as U,discoverMigrations as x}from"@lunora/codegen";import{isInteractive as C,promptSelect as O,promptText as F}from"@lunora/config";import{LunoraError as y}from"@lunora/errors";import{join as c}from"@visulima/path";import{Project as b}from"ts-morph";import{r as P}from"../packem_shared/admin-url-Cil3Or6N.mjs";import{d as D}from"../packem_shared/command-DwC11Cwe.mjs";import{diffSnapshots as z,renderMigrationFile as L}from"../packem_shared/diffSnapshots-CIOFQN_a.mjs";import{r as j}from"../packem_shared/resolve-target-BRvw8Pf7.mjs";import q from"../packem_shared/schemaIrToSnapshot-qpRoV7HY.mjs";import{readAndLogBody as H}from"./runRpcCommand.mjs";import{runExportCommand as G}from"../packem_shared/runExportCommand-DmXKEWSq.mjs";import{r as B}from"../packem_shared/import-CdHdZRjj.mjs";const u="__lunora_reproject__",W=e=>{if(!e.startsWith(u))return;const r=e.slice(u.length);return r===""?void 0:r},J=".snapshot.json",k=/[^\da-z]+/gu,A=(e,r)=>{let n=0,t=e.length;for(;n<t&&e[n]===r;)n+=1;for(;t>n&&e[t-1]===r;)t-=1;return e.slice(n,t)},K=e=>{const r=A(e.toLowerCase().replaceAll(k,"_"),"_");return r===""?"auto":r},V=e=>{const r=(n,t=2)=>n.toString().padStart(t,"0");return`${String(e.getUTCFullYear())}${r(e.getUTCMonth()+1)}${r(e.getUTCDate())}${r(e.getUTCHours())}${r(e.getUTCMinutes())}${r(e.getUTCSeconds())}`},Z=e=>{if(m(e))try{const r=I(e,"utf8"),n=JSON.parse(r);if(n.version!==1)throw new y("INTERNAL",`unsupported snapshot version: ${n.version}`);return n}catch(r){const n=r instanceof Error?r.message:String(r);throw new y("INTERNAL",`failed to read ${e}: ${n}`,{cause:r})}},X=e=>{const r=e.cwd??process.cwd(),n=c(r,"lunora","schema.ts");if(!m(n))return e.logger.error(`schema not found: ${n} — run \`vis generate lunora-table --name=<name>\` to create one`),{code:1,empty:!0,migrationFile:""};const t=new b({skipAddingFilesFromTsConfig:!0}),a=_(t,n),s=q(a),o=c(r,"lunora","migrations"),i=c(o,J);let d;try{d=Z(i)}catch(g){return e.logger.error(g instanceof Error?g.message:String(g)),{code:1,empty:!0,migrationFile:""}}const l=z(d,s);if(l.empty)return e.logger.info("no schema changes detected — snapshot is already up to date"),{code:0,empty:!0,migrationFile:""};const v=(e.now??(()=>new Date))(),p=K(e.name??"auto"),w=`${V(v)}_${p}.sql`,f=c(o,w);T(o,{recursive:!0});const E=L(p,l,v.toISOString());return h(f,E,"utf8"),h(i,`${JSON.stringify(s,void 0,4)}
2
2
  `,"utf8"),e.logger.success(`wrote ${f}`),l.unsupported.length>0&&e.logger.warn(`${String(l.unsupported.length)} unsupported diff(s) — see the comment block in ${w} and write the SQL manually`),{code:0,empty:!1,migrationFile:f}},Q="migrations.ts",$=/^[A-Za-z_]\w*$/u,Y=new Set(["await","break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","function","if","implements","import","in","instanceof","interface","let","new","null","package","private","protected","public","return","static","super","switch","this","throw","true","try","typeof","var","void","while","with","yield"]),S=/^import\s*\{\s*defineMigration\s*\}\s*from\s*["'](?:@lunora\/server|lunorash\/server)["'][^\n]*$/mu,ee=e=>`import { defineMigration } from "${U(e)?.has("lunorash")??!1?"lunorash/server":"@lunora/server"}";`,re="__lunora_admin__:runMigration",te="__lunora_admin__:migrationStatus",ne="/_lunora/migrate",ae=e=>A(e.trim().toLowerCase().replaceAll(k,"-"),"-"),oe=e=>e.split("-").filter(r=>r.length>0).map((r,n)=>n===0?r:r.charAt(0).toUpperCase()+r.slice(1)).join(""),ie=e=>{const r=c(e,"lunora","schema.ts");if(!m(r))return[];try{const n=new b({skipAddingFilesFromTsConfig:!0});return _(n,r).tables.map(t=>t.name)}catch{return[]}},se=async e=>e.length>0?O("Which table does this migration iterate?",e.map(r=>({label:r,value:r}))):F("Target table for the migration: "),ce=async(e,r)=>{if(r.table!==void 0)return r.table;const n=r.promptTable??(C()?se:void 0);if(n===void 0){r.logger.error("migrate create requires a target table when not running interactively — re-run with --table <table>");return}const a=(await n(ie(e)))?.trim();if(a===void 0||a===""){r.logger.error("no table selected — re-run with --table <table>");return}return a},de=async e=>{const r=e.cwd??process.cwd(),n=ae(e.name);if(n==="")return e.logger.error(`invalid migration name: "${e.name}" — must contain at least one alphanumeric character`),{code:1,file:""};const t=oe(n);if(!$.test(t)||Y.has(t))return e.logger.error(`invalid migration name: "${e.name}" derives the export \`${t}\`, which is not a valid identifier — pick a name that starts with a letter and isn't a reserved word`),{code:1,file:""};const a=await ce(r,e);if(a===void 0)return{code:1,file:""};if(!$.test(a))return e.logger.error(`invalid table: "${a}" — must be a valid identifier ([A-Za-z_][A-Za-z0-9_]*)`),{code:1,file:""};const s=c(r,"lunora"),o=c(s,Q);let i=m(o)?I(o,"utf8"):"";if(i.includes(`id: "${n}"`)||new RegExp(String.raw`\bexport const ${t}\b`,"u").test(i))return e.logger.error(`a migration with id "${n}" (export \`${t}\`) already exists in ${o}`),{code:1,file:""};const d=ee(r);i.trim()===""?i=`${d}
3
3
  `:S.test(i)?i=i.replace(S,d):i=`${d}
4
4
  ${i}`;const l=`export const ${t} = defineMigration({
@@ -1 +1 @@
1
- import{LunoraError as v}from"@lunora/errors";import{r as A,d as _}from"../packem_shared/admin-token-rxXZbVMZ.mjs";import{r as N,a as S}from"../packem_shared/admin-url-Cil3Or6N.mjs";import{d as b}from"../packem_shared/command-DwC11Cwe.mjs";import{a as P}from"../packem_shared/resolve-target-BRvw8Pf7.mjs";const h=(r,t="--args")=>{if(r===void 0||r.length===0)return{};try{return JSON.parse(r)}catch(e){const a=e instanceof Error?e.message:String(e);throw new v("INTERNAL",`failed to parse ${t} as JSON: ${a}`,{cause:e})}},I=/\/$/u,O="__lunora_admin__:runAs",k="__lunora_admin__:",T=async(r,t)=>{const e=await r.text();let a;try{a=JSON.parse(e)}catch{a=e}return t.info(JSON.stringify(a,void 0,2)),a},$=(r,t)=>{const e=t.body?.error?.code;t.runAs||t.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")},E=({args:r,claims:t,options:e,runAs:a})=>{const n=a?{args:{args:r,functionPath:e.functionPath,identity:t,userId:e.as},functionPath:O}:{args:r,functionPath:e.functionPath};return e.shard!==void 0&&(n.shardKey=e.shard),n},R=({cwd:r,logger:t,needsBearer:e,url:a})=>e?N(a,t,r):(P({cwd:r,url:a})??S(r)).replace(I,""),U=async r=>{const t=r.cwd??process.cwd(),e=r.as!==void 0&&r.as!=="",a=e||r.functionPath.startsWith(k),n=R({cwd:t,logger:r.logger,needsBearer:a,url:r.url});if(n===void 0)return{body:void 0,code:1,requestUrl:r.url??""};const s=`${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");let u,l;try{u=h(r.args),l=r.claims===void 0?void 0:h(r.claims,"--claims")}catch(d){return r.logger.error(d instanceof Error?d.message:String(d)),{body:void 0,code:1,requestUrl:s}}const{source:g,token:o}=a?A({cwd:t,token:r.token,url:n}):{};if(a&&o===void 0)return r.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{body:void 0,code:1,requestUrl:s};o!==void 0&&r.logger.debug?.(`admin bearer from ${_(g)}`);const m={"content-type":"application/json",...o===void 0?{}:{authorization:`Bearer ${o}`}},y=E({args:u,claims:l,options:r,runAs:e});r.logger.info(`POST ${s} -> ${r.functionPath}${e?` (as ${r.as??""})`:""}`);const c=await i(s,{body:JSON.stringify(y),headers:m,method:"POST"}),f=await T(c,r.logger);return $(r.logger,{body:f,runAs:e,status:c.status}),{body:f,code:c.ok?0:1,requestUrl:s}},L=b(({argument:r,cwd:t,logger:e,options:a})=>{const n=r[0];return n?U({args:a.args,as:a.as,claims:a.claims,cwd:t,functionPath:n,logger:e,shard:a.shard,token:a.token,url:a.url}):(e.error("missing function path. Usage: lunora run <functionPath> [--args <json>]"),{code:1})});export{L as execute,T as readAndLogBody,U as runRpcCommand};
1
+ import{LunoraError as l}from"@lunora/errors";import{r as y,d as v}from"../packem_shared/admin-token-rxXZbVMZ.mjs";import{r as A,a as b}from"../packem_shared/admin-url-Cil3Or6N.mjs";import{d as N}from"../packem_shared/command-DwC11Cwe.mjs";import{a as _}from"../packem_shared/resolve-target-BRvw8Pf7.mjs";const f=(r,t="--args")=>{if(r===void 0||r.length===0)return{};let e;try{e=JSON.parse(r)}catch(a){const n=a instanceof Error?a.message:String(a);throw new l("INTERNAL",`failed to parse ${t} as JSON: ${n}`,{cause:a})}if(typeof e!="object"||e===null||Array.isArray(e))throw new l("INTERNAL",`${t} must be a JSON object (e.g. '{"id":1}'), got ${Array.isArray(e)?"an array":typeof e}`);return e},S=/\/$/u,P="__lunora_admin__:runAs",I="__lunora_admin__:",O=async(r,t)=>{const e=await r.text();let a;try{a=JSON.parse(e)}catch{a=e}return t.info(JSON.stringify(a,void 0,2)),a},$=(r,t)=>{const e=t.body?.error?.code;t.runAs||t.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")},R=({args:r,claims:t,options:e,runAs:a})=>{const n=a?{args:{args:r,functionPath:e.functionPath,identity:t,userId:e.as},functionPath:P}:{args:r,functionPath:e.functionPath};return e.shard!==void 0&&(n.shardKey=e.shard),n},T=({cwd:r,logger:t,needsBearer:e,url:a})=>e?A(a,t,r):(_({cwd:r,url:a})??b(r)).replace(S,""),k=({args:r,claims:t},e)=>{try{return{args:f(r),claims:t===void 0?void 0:f(t,"--claims")}}catch(a){e.error(a instanceof Error?a.message:String(a));return}},E=async r=>{const t=r.cwd??process.cwd(),e=r.as!==void 0&&r.as!=="";if(r.claims!==void 0&&!e)return r.logger.error("--claims requires --as <userId> — extra identity claims only travel inside the admin-gated `runAs` dispatch."),{body:void 0,code:1,requestUrl:r.url??""};const a=e||r.functionPath.startsWith(I),n=T({cwd:t,logger:r.logger,needsBearer:a,url:r.url});if(n===void 0)return{body:void 0,code:1,requestUrl:r.url??""};const s=`${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 c=k(r,r.logger);if(c===void 0)return{body:void 0,code:1,requestUrl:s};const{source:g,token:o}=a?y({cwd:t,token:r.token,url:n}):{};if(a&&o===void 0)return r.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{body:void 0,code:1,requestUrl:s};o!==void 0&&r.logger.debug?.(`admin bearer from ${v(g)}`);const h={"content-type":"application/json",...o===void 0?{}:{authorization:`Bearer ${o}`}},m=R({args:c.args,claims:c.claims,options:r,runAs:e});r.logger.info(`POST ${s} -> ${r.functionPath}${e?` (as ${r.as??""})`:""}`);const d=await i(s,{body:JSON.stringify(m),headers:h,method:"POST"}),u=await O(d,r.logger);return $(r.logger,{body:u,runAs:e,status:d.status}),{body:u,code:d.ok?0:1,requestUrl:s}},L=N(({argument:r,cwd:t,logger:e,options:a})=>{const n=r[0];return n?E({args:a.args,as:a.as,claims:a.claims,cwd:t,functionPath:n,logger:e,shard:a.shard,token:a.token,url:a.url}):(e.error("missing function path. Usage: lunora run <functionPath> [--args <json>]"),{code:1})});export{L as execute,O as readAndLogBody,E as runRpcCommand};
@@ -1 +1 @@
1
- import{C as a,R as s,V as C,r as N}from"./cli-CrC0a7dH.mjs";import"./createLogger-hGafwf-3.mjs";export{a as COMMANDS,s as REGISTERED_COMMAND_NAMES,C as VERSION,N as runCli};
1
+ import{C as a,R as s,V as C,r as N}from"./cli-C37AI4tr.mjs";import"./createLogger-hGafwf-3.mjs";export{a as COMMANDS,s as REGISTERED_COMMAND_NAMES,C as VERSION,N as runCli};
@@ -1 +1 @@
1
- import"./admin-token-rxXZbVMZ.mjs";import"./admin-url-Cil3Or6N.mjs";import{D as a,r as i}from"./import-CrVGrOt3.mjs";import"./shared-D-zCOmgY.mjs";export{a as DEFAULT_IMPORT_BATCH_SIZE,i as runImportCommand};
1
+ import"./admin-token-rxXZbVMZ.mjs";import"./admin-url-Cil3Or6N.mjs";import{D as a,r as i}from"./import-CdHdZRjj.mjs";import"./shared-D-zCOmgY.mjs";export{a as DEFAULT_IMPORT_BATCH_SIZE,i as runImportCommand};