@lunora/cli 1.0.0-alpha.217 → 1.0.0-alpha.218

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/dist/bin.mjs +1 -1
  2. package/dist/index.d.mts +8 -0
  3. package/dist/index.d.ts +8 -0
  4. package/dist/index.mjs +1 -1
  5. package/dist/packem_chunks/handler.mjs +1 -1
  6. package/dist/packem_chunks/handler10.mjs +4 -1
  7. package/dist/packem_chunks/handler11.mjs +2 -4
  8. package/dist/packem_chunks/handler12.mjs +1 -2
  9. package/dist/packem_chunks/handler13.mjs +1 -1
  10. package/dist/packem_chunks/handler14.mjs +1 -1
  11. package/dist/packem_chunks/handler15.mjs +1 -1
  12. package/dist/packem_chunks/handler16.mjs +3 -1
  13. package/dist/packem_chunks/handler17.mjs +1 -3
  14. package/dist/packem_chunks/handler18.mjs +1 -1
  15. package/dist/packem_chunks/handler19.mjs +7 -1
  16. package/dist/packem_chunks/handler2.mjs +2 -1
  17. package/dist/packem_chunks/handler20.mjs +1 -7
  18. package/dist/packem_chunks/handler21.mjs +3 -1
  19. package/dist/packem_chunks/handler22.mjs +3 -2
  20. package/dist/packem_chunks/handler23.mjs +1 -3
  21. package/dist/packem_chunks/handler24.mjs +2 -3
  22. package/dist/packem_chunks/handler25.mjs +99 -1
  23. package/dist/packem_chunks/handler26.mjs +10 -99
  24. package/dist/packem_chunks/handler3.mjs +1 -2
  25. package/dist/packem_chunks/handler4.mjs +1 -1
  26. package/dist/packem_chunks/handler5.mjs +1 -1
  27. package/dist/packem_chunks/handler6.mjs +1 -1
  28. package/dist/packem_chunks/handler7.mjs +3 -1
  29. package/dist/packem_chunks/handler8.mjs +1 -3
  30. package/dist/packem_chunks/handler9.mjs +1 -1
  31. package/dist/packem_chunks/planDevCommand.mjs +6 -6
  32. package/dist/packem_chunks/runDeployCommand.mjs +1 -0
  33. package/dist/packem_chunks/runInitCommand.mjs +89 -63
  34. package/dist/packem_chunks/runMigrateGenerateCommand.mjs +3 -3
  35. package/dist/packem_shared/{COMMANDS-Cf45cyJN.mjs → COMMANDS-BbQ3-hLn.mjs} +1 -1
  36. package/dist/packem_shared/{DEFAULT_IMPORT_BATCH_SIZE-CYq3UJmD.mjs → DEFAULT_IMPORT_BATCH_SIZE-BPQYMEmV.mjs} +1 -1
  37. package/dist/packem_shared/{buildRegistryIndex-BcJgAx76.mjs → buildRegistryIndex-DVmy8fHE.mjs} +1 -1
  38. package/dist/packem_shared/catalog-Cbzph90w.mjs +1 -0
  39. package/dist/packem_shared/cli-DOBnG22n.mjs +3 -0
  40. package/dist/packem_shared/commands-CLLQuHqU.mjs +15 -0
  41. package/dist/packem_shared/{diffSnapshots-Cnoe8Ob4.mjs → diffSnapshots-DtC5Cs4Z.mjs} +3 -3
  42. package/dist/packem_shared/{import-8FCB0cUX.mjs → import-DuHtoh4_.mjs} +7 -7
  43. package/dist/packem_shared/resolve-BWFT7RvE.mjs +5 -0
  44. package/dist/packem_shared/runAddCommand-BABRWlOb.mjs +1 -0
  45. package/dist/packem_shared/schemaIrToSnapshot-VpPguG3W.mjs +1 -0
  46. package/dist/packem_shared/{storage-D5s4vbtJ.mjs → storage-DlUnv7uG.mjs} +1 -1
  47. package/dist/packem_shared/vectorize-metadata-Br1QnnS8.mjs +1 -0
  48. package/package.json +11 -11
  49. package/skills/lunora-deploy/SKILL.md +42 -11
  50. package/skills/lunora-functions/SKILL.md +42 -14
  51. package/skills/lunora-migration-helper/SKILL.md +4 -4
  52. package/skills/lunora-performance-audit/SKILL.md +8 -5
  53. package/skills/lunora-quickstart/SKILL.md +3 -3
  54. package/skills/lunora-setup-auth/SKILL.md +23 -6
  55. package/skills/lunora-setup-hyperdrive/SKILL.md +33 -13
  56. package/skills/lunora-setup-mail/SKILL.md +34 -28
  57. package/skills/lunora-setup-scheduler/SKILL.md +15 -10
  58. package/skills/lunora-setup-storage/SKILL.md +182 -25
  59. package/dist/packem_chunks/handler27.mjs +0 -10
  60. package/dist/packem_shared/catalog-CJaormx0.mjs +0 -1
  61. package/dist/packem_shared/cli-CqNvbTR1.mjs +0 -3
  62. package/dist/packem_shared/commands-YfMX-Mto.mjs +0 -19
  63. package/dist/packem_shared/resolve-DZAGzg67.mjs +0 -1
  64. package/dist/packem_shared/runAddCommand-vE21wRIK.mjs +0 -1
  65. package/dist/packem_shared/runDeployCommand-o64lz-UD.mjs +0 -1
  66. package/dist/packem_shared/schemaIrToSnapshot-ogkcpHjM.mjs +0 -1
  67. package/dist/packem_shared/vectorize-metadata-DbziRKpX.mjs +0 -1
@@ -1,11 +1,11 @@
1
- import{existsSync as m,mkdirSync as M,writeFileSync as v,readFileSync as b,readdirSync as ae,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 rt}from"../packem_shared/resolve-DZAGzg67.mjs";import{defaultSpawner as pe}from"../packem_shared/createRecordingSpawner-DJlNacZ6.mjs";import{d as at,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-D5s4vbtJ.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-YfMX-Mto.mjs";const z={bun:{githubCacheKey:void 0,githubSetupStep:` - uses: oven-sh/setup-bun@v2
1
+ import{existsSync as m,mkdirSync as L,writeFileSync as v,readFileSync as b,readdirSync as oe,rmSync as _,mkdtempSync as ne,copyFileSync as De,renameSync as Be,lstatSync as je}from"node:fs";import{tmpdir as se}from"node:os";import{installArgsFor as ie,execArgsFor as Ve,detectFramework as Ue,isInteractive as g,LUNA_ART as Fe,LUNA_NAME as He,LUNA_SIGNOFF as We,BADGES as f,paintAnswer as ze,detectPackageManager as F,detectInstalledManagers as qe,runScriptCommand as Ke,detectLintTools as Ge,addArgsFor as Je,applyLintIgnores as Ye}from"@lunora/config";import{walkSync as Xe}from"@visulima/fs";import{join as d,dirname as M,basename as N,resolve as le,relative as ce}from"@visulima/path";import{downloadTemplate as de}from"giget";import{modify as Qe,applyEdits as Ze}from"jsonc-parser";import{join as H,dirname as et}from"node:path";import{d as tt}from"../packem_shared/command-DwC11Cwe.mjs";import at from"magic-string";import{Project as rt,SyntaxKind as w}from"ts-morph";import{P as W}from"../packem_shared/prompt-cancelled-C8Sj7OqI.mjs";import{l as ue,m as ot,n as pe,o as he,b as nt}from"../packem_shared/resolve-BWFT7RvE.mjs";import{defaultSpawner as me}from"../packem_shared/createRecordingSpawner-DJlNacZ6.mjs";import{d as st,e as it,f as lt,a as fe,t as z,g as ve,h as ct,b as ge,i as we,w as dt,j as ut,k as ye,l as pt}from"../packem_shared/tui-prompts-Dd0pDuNr.mjs";import{E as be,p as ht,w as mt,M as ft,r as vt,j as gt,e as wt,c as xe,k as ke,f as yt}from"../packem_shared/storage-DlUnv7uG.mjs";import{logStep as G}from"../packem_shared/createLogger-hGafwf-3.mjs";import{r as bt}from"../packem_shared/lint-ignore-report-DKZagpqk.mjs";import xt from"node:dns/promises";import{r as kt}from"../packem_shared/commands-CLLQuHqU.mjs";const q={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 r=De(e,"lunora",t);return[r.command,...r.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"}},S=(e,t)=>{const a=Ve(e,"lunora",t);return[a.command,...a.args].join(" ")},J=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}`,bt=e=>{const t=z[e],r=t.githubCacheKey===void 0?`# (below) requires it — run \`${e} install\` locally and`:`# (below) and the ${e} cache both require it — run \`${e} install\` locally and`;return`name: Deploy
8
+ `} - run: ${e.installCmd}`,Ct=e=>{const t=q[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:
@@ -14,7 +14,7 @@ on:
14
14
  workflow_dispatch:
15
15
 
16
16
  # Prerequisite: commit your ${t.lockfile}. \`${t.installCmd}\`
17
- ${r}
17
+ ${a}
18
18
  # commit the lockfile before pushing, or the first CI run fails.
19
19
  #
20
20
  # Set these repository secrets (Settings → Secrets and variables → Actions):
@@ -32,10 +32,10 @@ jobs:
32
32
  permissions:
33
33
  contents: read
34
34
  steps:
35
- ${Y(t)}
35
+ ${J(t)}
36
36
  # Codegen + wrangler validation gate (no deploy) — fails fast on drift.
37
- - run: ${C(e,["prepare"])}
38
- - run: ${C(e,["deploy"])}
37
+ - run: ${S(e,["prepare"])}
38
+ - run: ${S(e,["deploy"])}
39
39
 
40
40
  # Preview version on every pull request — uploads a versioned preview URL;
41
41
  # production traffic is untouched.
@@ -45,9 +45,9 @@ ${Y(t)}
45
45
  permissions:
46
46
  contents: read
47
47
  steps:
48
- ${Y(t)}
49
- - run: ${C(e,["deploy","--preview"])}
50
- `},xt=e=>{const t=z[e],r=[...t.gitlabProvisionScript,t.installCmd].map(a=>` - ${a}`).join(`
48
+ ${J(t)}
49
+ - run: ${S(e,["deploy","--preview"])}
50
+ `},St=e=>{const t=q[e],a=[...t.gitlabProvisionScript,t.installCmd].map(r=>` - ${r}`).join(`
51
51
  `);return`stages:
52
52
  - deploy
53
53
 
@@ -62,7 +62,7 @@ ${Y(t)}
62
62
  image: ${t.gitlabImage}
63
63
  stage: deploy
64
64
  before_script:
65
- ${r}
65
+ ${a}
66
66
 
67
67
  # Production deploy on the default branch.
68
68
  deploy:
@@ -71,8 +71,8 @@ deploy:
71
71
  - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
72
72
  script:
73
73
  # Codegen + wrangler validation gate (no deploy) — fails fast on drift.
74
- - ${C(e,["prepare"])}
75
- - ${C(e,["deploy"])}
74
+ - ${S(e,["prepare"])}
75
+ - ${S(e,["deploy"])}
76
76
 
77
77
  # Preview version on every merge request (versioned preview URL; production
78
78
  # traffic is untouched).
@@ -81,17 +81,17 @@ preview:
81
81
  rules:
82
82
  - if: $CI_PIPELINE_SOURCE == "merge_request_event"
83
83
  script:
84
- - ${C(e,["deploy","--preview"])}
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,r,a={})=>{const o=F(e,xe[t].file);return m(o)&&a.overwrite!==!0?{path:o,skipped:!0,written:!1}:(M(Qe(o),{recursive:!0}),v(o,kt(t,r),"utf8"),{path:o,skipped:!1,written:!0})},Lt=(e,t,r,a,o={})=>{const n=xe[t];try{const s=St(e,t,r,o);if(s.skipped)a.info(`--ci ${t}: ${n.file} already exists — left unchanged (re-run with overwrite to replace).`);else{const i=se(r),l=[i.command,...i.args].join(" "),{installCmd:d,lockfile:c}=z[r];a.success(`--ci ${t}: wrote ${n.file}`),a.info(`--ci ${t}: set CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID as ${n.secretsHint} to enable deploys.`),a.info(`--ci ${t}: run \`${l}\` and commit ${c} before pushing — the pipeline runs \`${d}\`.`)}return s}catch(s){const i=s instanceof Error?s.message:String(s);return a.warn(`--ci ${t}: could not write ${n.file} (${i})`),{path: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 r=t.asKindOrThrow(w.ExportAssignment).getExpression();if(r.getKind()!==w.CallExpression)continue;const a=r.asKindOrThrow(w.CallExpression);if(a.getExpression().getText()!=="defineConfig")continue;const o=a.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 r=t.asKindOrThrow(w.ExportAssignment).getExpression();if(r.getKind()===w.ObjectLiteralExpression)return r.asKindOrThrow(w.ObjectLiteralExpression)}},Rt=e=>new tt({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}).createSourceFile("vite.config.ts",e,{overwrite:!0}),Tt=(e,t)=>{const r=t.getImportDeclarations().at(-1)?.getEnd()??0;r===0?e.prepend(`${X}
86
- `):e.appendLeft(r,`
87
- ${X}`)},Ot=(e,t)=>{const r=t.getProperty("plugins");if(r===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 a=r.getDescendantsOfKind(w.ArrayLiteralExpression)[0];if(a===void 0)return;const o=a.getElements();if(o.length===0)e.appendLeft(a.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),r=$t(t)??_t(t);if(r===void 0)return{changed:!1,code:e,reason:"could not locate a Vite config plugins array to patch"};const a=new et(e);return!e.includes(Nt)&&!e.includes(It)&&Tt(a,t),Ot(a,r),{changed:!0,code:a.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 r=e instanceof Error?e.message:String(e),a=r.toLowerCase(),o=`failed to download template "${t.templateType}" from ${t.remote}: ${r}`;return Dt.test(a)?{hints:[`Check the template name "${t.templateType}" and the ref "${t.ref}".`,"List/inspect available templates, or target a branch/tag with `--ref <branch>`."],message:`template "${t.templateType}" not found at ${t.remote}: ${r}`}:Pt.test(a)?{hints:["You appear to be offline or unable to reach GitHub.","To scaffold without a network, point at a local template root: `lunora init --from <dir>`."],message:o}:{hints:["If this is a network/offline issue, scaffold from a local root with `lunora init --from <dir>`."],message:o}},R=async(e,t,r)=>{if(g()){await ot(f[e],t,r);return}if(process.stdout.write(`
89
- `),r===void 0||r===""){J(e,t);return}const a=r.split(`
90
- `).map(o=>Fe(o)).join(`
91
- `);J(e,`${t}
92
- ${a}`)},jt=async e=>{if(g()){await at();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 r=[];for(const a of e.split(",").map(o=>o.trim()).filter(Boolean))Q.includes(a)?r.includes(a)||r.push(a):t(`init: unknown --add feature "${a}" — expected ${Q.join(" | ")}; skipping.`);return r},Ft=async e=>{const t=await ft(e.select),r=await ye(e.text,e.projectName);return{label:"auth",names:[t],transformManifest:a=>be(a,r)}},Ht=async e=>{const t=await e.text(pt,{placeholder:"you@yourdomain.com"}),r=ht(t,a=>{e.logger.warn(a)});return{label:"email",names:[we],transformManifest:r===void 0?void 0:a=>mt(a,r)}},Wt=async(e,t)=>{const r=e.resolveAuthUiItem?.()??"auth-ui-react";if(t)return{label:"auth-ui",names:[r]};const a=await ye(e.text,e.projectName);return{label:"auth-ui",names:[r],transformManifest:o=>be(o,a)}},zt=async e=>{const t=await dt(e.text,e.projectName);return{label:"storage",names:["storage"],transformManifest:r=>ut(r,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)return e.applyAll(e.preselected.map(a=>{const o=a==="auth-ui"?e.resolveAuthUiItem?.()??"auth-ui-react":Vt(a);return{label:a,names:[o]}}));if(!e.interactive)return e.logger.info("tip: add features later with `lunora add <ai|auth|backup|browser|cloudflare-access|crons|email|flags|hyperdrive|payment|presence|queue|storage|workflow>`."),!0;const t=await e.multiSelect("Which features do you want to add?",Ce,{defaults:[]});if(t.length===0)return!0;const r=[];for(const a of t){const o=qt[a];r.push(o?await o(e,t):{label:a,names:[a]})}return await e.applyAll(r),!0},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 r=e.apply(t);return gt(r,e.logger),r},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
84
+ - ${S(e,["deploy","--preview"])}
85
+ `},Ce={github:{file:H(".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)"}},Lt=(e,t)=>e==="github"?Ct(t):St(t),Mt=e=>e==="github"||e==="gitlab",At=(e,t,a,r={})=>{const o=H(e,Ce[t].file);return m(o)&&r.overwrite!==!0?{path:o,skipped:!0,written:!1}:(L(et(o),{recursive:!0}),v(o,Lt(t,a),"utf8"),{path:o,skipped:!1,written:!0})},Et=(e,t,a,r,o={})=>{const n=Ce[t];try{const s=At(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=ie(a),l=[i.command,...i.args].join(" "),{installCmd:u,lockfile:c}=q[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 \`${u}\`.`)}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:H(e,n.file),skipped:!1,written:!1}}},Nt={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"},It=e=>{const t=Ue(e);return{...t,adapter:Nt[t.framework]}},$="lunora()",Y='import { lunora } from "@lunora/vite";',$t=/\blunora\s*\(/u,_t='"@lunora/vite"',Rt="'@lunora/vite'",Tt=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)}},Ot=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)}},Pt=e=>new rt({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}).createSourceFile("vite.config.ts",e,{overwrite:!0}),Dt=(e,t)=>{const a=t.getImportDeclarations().at(-1)?.getEnd()??0;a===0?e.prepend(`${Y}
86
+ `):e.appendLeft(a,`
87
+ ${Y}`)},Bt=(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(),`${$}, `)}},Se=e=>{if($t.test(e))return{changed:!1,code:e,reason:"lunora plugin already present"};const t=Pt(e),a=Tt(t)??Ot(t);if(a===void 0)return{changed:!1,code:e,reason:"could not locate a Vite config plugins array to patch"};const r=new at(e);return!e.includes(_t)&&!e.includes(Rt)&&Dt(r,t),Bt(r,a),{changed:!0,code:r.toString()}},jt=/enotfound|eai_again|econnrefused|etimedout|network|fetch failed|getaddrinfo/u,Vt=/404|not found|could not find|no such/u,Ut=(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 Vt.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}`}:jt.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 it(f[e],t,a);return}if(process.stdout.write(`
89
+ `),a===void 0||a===""){G(e,t);return}const r=a.split(`
90
+ `).map(o=>ze(o)).join(`
91
+ `);G(e,`${t}
92
+ ${r}`)},Ft=async e=>{if(g()){await st();return}e.info(`
93
+ ${Fe}
94
+ ${He}: ${We}`)},Le=[{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"}],X=Le.map(e=>e.value),Ht=e=>e==="email"?be:e,Wt=(e,t)=>{const a=[];for(const r of e.split(",").map(o=>o.trim()).filter(Boolean))X.includes(r)?a.includes(r)||a.push(r):t(`init: unknown --add feature "${r}" — expected ${X.join(" | ")}; skipping.`);return a},zt=async e=>{const t=await wt(e.select),a=await xe(e.text,e.projectName);return{label:"auth",names:[t],transformManifest:r=>ke(r,a)}},qt=async e=>{const t=await e.text(ft,{placeholder:"you@yourdomain.com"}),a=vt(t,r=>{e.logger.warn(r)});return{label:"email",names:[be],transformManifest:a===void 0?void 0:r=>gt(r,a)}},Kt=async(e,t)=>{const a=e.resolveAuthUiItem?.()??"auth-ui-react";if(t)return{label:"auth-ui",names:[a]};const r=await xe(e.text,e.projectName);return{label:"auth-ui",names:[a],transformManifest:o=>ke(o,r)}},Gt=async e=>{const t=await ht(e.text,e.projectName);return{label:"storage",names:["storage"],transformManifest:a=>mt(a,t)}},Jt={auth:zt,"auth-ui":async(e,t)=>Kt(e,t.includes("auth")),email:qt,storage:Gt},Q=async e=>{if(e.preselected!==void 0&&e.preselected.length>0)return e.applyAll(e.preselected.map(r=>{const o=r==="auth-ui"?e.resolveAuthUiItem?.()??"auth-ui-react":Ht(r);return{label:r,names:[o]}}));if(!e.interactive)return e.logger.info("tip: add features later with `lunora add <ai|auth|backup|browser|cloudflare-access|crons|email|flags|hyperdrive|payment|presence|queue|storage|workflow>`."),!0;const t=await e.multiSelect("Which features do you want to add?",Le,{defaults:[]});if(t.length===0)return!0;const a=[];for(const r of t){const o=Jt[r];a.push(o?await o(e,t):{label:r,names:[r]})}return await e.applyAll(a),!0},Yt=[{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"}],Xt="Which linter/formatter do you use? We'll tell it to skip Lunora's generated files.",Qt=async e=>{const t=e.interactive?await e.multiSelect(Xt,Yt,{defaults:e.detected}):[...e.detected];if(t.length===0)return[];const a=e.apply(t);return bt(a,e.logger),a},I="M 259.500 10.552 C 220.080 15.859, 182.424 32.566, 152.500 58.025 C 110.179 94.031, 85.380 137.183, 77.518 188.500 C 75.410 202.255, 74.569 225.677, 75.796 236.466 C 76.757 244.917, 76.683 245.692, 74.518 249.966 C 63.118 272.466, 53.141 303.876, 51.382 322.799 L 50.718 329.943 71.960 320.471 C 83.643 315.262, 93.326 311, 93.478 311 C 93.630 311, 96.547 316.063, 99.959 322.250 C 103.371 328.438, 107.249 334.850, 108.577 336.500 L 110.990 339.500 110.981 336 C 110.977 334.075, 111.499 324.991, 112.143 315.813 L 113.312 299.127 121.406 293.336 C 132.495 285.403, 149.593 271.554, 161 261.268 C 171.556 251.748, 189.116 235, 188.540 235 C 188.337 235, 183.069 238.648, 176.835 243.106 C 142.318 267.789, 68.537 314, 63.646 314 C 61.843 314, 72.791 281.179, 80.905 262.259 C 92.233 235.845, 107.473 212.389, 132.106 183.453 L 138.451 176 148.268 176 C 176.192 176, 197.512 187.154, 212.868 209.797 C 216.470 215.108, 217.035 216.595, 216.477 219.297 C 211.386 243.968, 202.359 274.496, 193.797 296 C 183.898 320.861, 167.147 352.101, 152.395 373.215 L 147.004 380.930 152.891 385.830 C 161.400 392.911, 165.563 396, 166.594 395.998 C 167.092 395.998, 168.772 391.641, 170.327 386.317 C 176.279 365.934, 188.422 338.749, 200.942 317.778 C 223.060 280.731, 256.432 244.369, 294.500 215.836 C 309.956 204.252, 313.937 201.603, 314.719 202.385 C 315.116 202.783, 315.449 213.096, 315.460 225.304 C 315.474 241.855, 315.021 250.405, 313.680 258.924 C 307.009 301.272, 291.175 336.677, 263.112 372 C 255.259 381.883, 227.182 410.673, 218.516 417.727 L 213.532 421.783 223.439 424.880 C 281.705 443.093, 349.165 436.018, 398.616 406.508 C 446.728 377.797, 483.322 331.466, 497.366 281.481 C 503.381 260.075, 504.480 250.741, 504.491 221 C 504.501 191.997, 503.598 184.047, 497.987 163.732 C 484.768 115.871, 452.505 72.708, 407.718 42.964 C 381.051 25.254, 352.818 14.828, 319.695 10.460 C 305.932 8.645, 273.298 8.695, 259.500 10.552",E=`/* 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
- `,Yt=`import { useEffect, useState } from "react";
199
+ `,Zt=`import { useEffect, useState } from "react";
200
200
 
201
201
  type Theme = "dark" | "light";
202
202
 
@@ -238,7 +238,7 @@ export default function App() {
238
238
  <div className="lw-wrap">
239
239
  <div className="brand">
240
240
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
241
- <path d="${N}" fill="currentColor" fillRule="evenodd" />
241
+ <path d="${I}" fill="currentColor" fillRule="evenodd" />
242
242
  </svg>
243
243
  <span className="word">Lunora</span>
244
244
  </div>
@@ -357,7 +357,7 @@ export default function App() {
357
357
  </div>
358
358
  );
359
359
  }
360
- `,Xt=`<script setup lang="ts">
360
+ `,ea=`<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
@@ -397,7 +397,7 @@ const toggle = (): void => {
397
397
  <div class="lw-wrap">
398
398
  <div class="brand">
399
399
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
400
- <path d="${N}" fill="currentColor" fill-rule="evenodd" />
400
+ <path d="${I}" fill="currentColor" fill-rule="evenodd" />
401
401
  </svg>
402
402
  <span class="word">Lunora</span>
403
403
  </div>
@@ -513,7 +513,7 @@ const toggle = (): void => {
513
513
  </div>
514
514
  </div>
515
515
  </template>
516
- `,Qt=`import { createSignal, onMount } from "solid-js";
516
+ `,ta=`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
@@ -553,7 +553,7 @@ export default function App() {
553
553
  <div class="lw-wrap">
554
554
  <div class="brand">
555
555
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
556
- <path d="${N}" fill="currentColor" fill-rule="evenodd" />
556
+ <path d="${I}" fill="currentColor" fill-rule="evenodd" />
557
557
  </svg>
558
558
  <span class="word">Lunora</span>
559
559
  </div>
@@ -672,7 +672,7 @@ export default function App() {
672
672
  </div>
673
673
  );
674
674
  }
675
- `,Zt=`<script lang="ts">
675
+ `,aa=`<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
@@ -715,7 +715,7 @@ export default function App() {
715
715
  <div class="lw-wrap">
716
716
  <div class="brand">
717
717
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
718
- <path d="${N}" fill="currentColor" fill-rule="evenodd" />
718
+ <path d="${I}" fill="currentColor" fill-rule="evenodd" />
719
719
  </svg>
720
720
  <span class="word">Lunora</span>
721
721
  </div>
@@ -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
- `,er=`import "./style.css";
833
+ `,ra=`import "./style.css";
834
834
 
835
835
  import { LunoraClient } from "lunorash/client";
836
836
 
@@ -858,7 +858,7 @@ const welcomeHtml = \`
858
858
  <div class="lw-wrap">
859
859
  <div class="brand">
860
860
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
861
- <path d="${N}" fill="currentColor" fill-rule="evenodd" />
861
+ <path d="${I}" fill="currentColor" fill-rule="evenodd" />
862
862
  </svg>
863
863
  <span class="word">Lunora</span>
864
864
  </div>
@@ -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
- `,T="const url = (import.meta.env.VITE_LUNORA_URL as string | undefined) ?? globalThis.location.origin;",tr=`import "./index.css";
1000
+ `,T="const url = (import.meta.env.VITE_LUNORA_URL as string | undefined) ?? globalThis.location.origin;",oa=`import "./index.css";
1001
1001
 
1002
1002
  import { LunoraProvider } from "@lunora/react";
1003
1003
  import { LunoraClient } from "lunorash/client";
@@ -1025,7 +1025,7 @@ createRoot(root).render(
1025
1025
  </LunoraProvider>
1026
1026
  </StrictMode>,
1027
1027
  );
1028
- `,rr=`import "./style.css";
1028
+ `,na=`import "./style.css";
1029
1029
 
1030
1030
  import { createLunora } from "@lunora/vue";
1031
1031
  import { LunoraClient } from "lunorash/client";
@@ -1036,7 +1036,7 @@ import App from "./App.vue";
1036
1036
  // Provide one LunoraClient at the app root via the Vue plugin form.
1037
1037
  ${T}
1038
1038
  createApp(App).use(createLunora(new LunoraClient({ url }))).mount("#app");
1039
- `,ar=`import "./index.css";
1039
+ `,sa=`import "./index.css";
1040
1040
 
1041
1041
  import { LunoraProvider } from "@lunora/solid";
1042
1042
  import { LunoraClient } from "lunorash/client";
@@ -1056,7 +1056,7 @@ render(
1056
1056
  ),
1057
1057
  root!,
1058
1058
  );
1059
- `,or=`<script lang="ts">
1059
+ `,ia=`<script lang="ts">
1060
1060
  import { setLunoraClient } from "@lunora/svelte";
1061
1061
  import { LunoraClient } from "lunorash/client";
1062
1062
 
@@ -1067,7 +1067,7 @@ render(
1067
1067
  <\/script>
1068
1068
 
1069
1069
  <App />
1070
- `,nr=`import "./app.css";
1070
+ `,la=`import "./app.css";
1071
1071
 
1072
1072
  import { mount } from "svelte";
1073
1073
 
@@ -1077,12 +1077,24 @@ import Root from "./Root.svelte";
1077
1077
  const app = mount(Root, { target: document.getElementById("app")! });
1078
1078
 
1079
1079
  export default app;
1080
- `,O={react:{adapter:"@lunora/react",createViteTemplate:"react-ts",files:[{contents:tr,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:ar,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:or,path:"src/Root.svelte"},{contents:nr,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:er,path:"src/main.ts"},{contents:L,path:"src/style.css"}],label:"Vanilla"},vue:{adapter:"@lunora/vue",createViteTemplate:"vue-ts",files:[{contents:rr,path:"src/main.ts"},{contents:Xt,path:"src/App.vue"},{contents:L,path:"src/style.css"}],label:"Vue"}},P=e=>Object.hasOwn(O,e),sr=`import type { Middleware } from "lunorash/server";
1080
+ `,O={react:{adapter:"@lunora/react",createViteTemplate:"react-ts",files:[{contents:oa,path:"src/main.tsx"},{contents:Zt,path:"src/App.tsx"},{contents:E,path:"src/index.css"}],label:"React"},solid:{adapter:"@lunora/solid",createViteTemplate:"solid-ts",files:[{contents:sa,path:"src/index.tsx"},{contents:ta,path:"src/App.tsx"},{contents:E,path:"src/index.css"}],label:"Solid"},svelte:{adapter:"@lunora/svelte",createViteTemplate:"svelte-ts",files:[{contents:ia,path:"src/Root.svelte"},{contents:la,path:"src/main.ts"},{contents:aa,path:"src/App.svelte"},{contents:E,path:"src/app.css"}],label:"Svelte"},vanilla:{adapter:"lunorash/client",createViteTemplate:"vanilla-ts",files:[{contents:ra,path:"src/main.ts"},{contents:E,path:"src/style.css"}],label:"Vanilla"},vue:{adapter:"@lunora/vue",createViteTemplate:"vue-ts",files:[{contents:na,path:"src/main.ts"},{contents:ea,path:"src/App.vue"},{contents:E,path:"src/style.css"}],label:"Vue"}},P=e=>Object.hasOwn(O,e),ca=`/**
1081
+ * Rate-limit schema extension + plugin.
1082
+ *
1083
+ * Defines the \`ratelimit_buckets\` table used by \`createDbStore\` for durable,
1084
+ * DO-backed rate limiting. Included automatically in every Lunora project.
1085
+ */
1086
+ import type { Middleware } from "lunorash/server";
1081
1087
  import { defineSchemaExtension, defineTable, definePlugin, v } from "lunorash/server";
1082
1088
  import { createDbStore, RateLimiter } from "lunorash/ratelimit";
1083
1089
  import type { RateLimitConfigMap } from "lunorash/ratelimit";
1084
1090
 
1091
+ /**
1092
+ * Named limits this app enforces. This is the one place they live — add your own
1093
+ * and reference them by name from \`rateLimit(limiter, "<name>", …)\` (see
1094
+ * \`lunora/messages.ts\`).
1095
+ */
1085
1096
  export const limits = {
1097
+ /** Chat writes: 30 per caller per minute, refilling continuously over 60s. */
1086
1098
  send: { kind: "token bucket", period: 60_000, rate: 30 },
1087
1099
  } as const satisfies RateLimitConfigMap;
1088
1100
 
@@ -1117,7 +1129,7 @@ export const ratelimit = definePlugin("ratelimit", {
1117
1129
  }),
1118
1130
  middleware,
1119
1131
  });
1120
- `,ir=`import { ratelimit } from "./ratelimit/schema.js";
1132
+ `,da=`import { ratelimit } from "./ratelimit/schema.js";
1121
1133
  import { defineSchema, defineTable, v } from "lunorash/server";
1122
1134
 
1123
1135
  export default defineSchema({
@@ -1128,16 +1140,30 @@ export default defineSchema({
1128
1140
  .shardBy("channelId")
1129
1141
  .index("by_channel", ["channelId"]),
1130
1142
  }).extend(ratelimit.extension);
1131
- `,lr=`import { RateLimiter, rateLimit, createDbStore } from "lunorash/ratelimit";
1143
+ `,ua=`import { rateLimit } from "lunorash/ratelimit";
1132
1144
 
1145
+ import { makeRateLimiter } from "./ratelimit/schema.js";
1146
+ import type { MutationCtx } from "#lunora/_generated/server.js";
1133
1147
  import { mutation, query, v } from "#lunora/_generated/server.js";
1134
1148
 
1135
- const limiter = (ctx: { db: unknown }) => new RateLimiter({
1136
- config: {
1137
- send: { kind: "token bucket", period: 60_000, rate: 30 },
1138
- },
1139
- store: createDbStore({ db: ctx.db as never, table: "ratelimit_buckets" }),
1140
- });
1149
+ /**
1150
+ * The limiter comes from \`lunora/ratelimit/schema.ts\` — that file owns the named
1151
+ * limits and the durable store, so tuning \`send\` there is what changes this
1152
+ * procedure's budget. Build it from the generated \`MutationCtx\` so
1153
+ * \`rateLimit(limiter, …)\` infers the full procedure context: \`ctx.auth\`/\`ctx.ip\`
1154
+ * in the key callback and a typed \`ctx.db\` in the handler both depend on it.
1155
+ */
1156
+ const limiter = (ctx: MutationCtx) => makeRateLimiter(ctx);
1157
+
1158
+ /**
1159
+ * One bucket per caller, not one bucket for the whole app.
1160
+ *
1161
+ * \`ctx.auth.userId\` is \`null\` until you wire auth (\`lunora registry add auth\`),
1162
+ * so the \`ctx.ip\` fallback is what actually keys the limit in a fresh project —
1163
+ * Cloudflare's server-side \`CF-Connecting-IP\`, never a client header. Keying on
1164
+ * \`"anon"\` alone would let one script exhaust the budget for every user.
1165
+ */
1166
+ const byCaller = { key: (ctx: { auth: { userId?: null | string }; ip?: string }): string => ctx.auth.userId ?? ctx.ip ?? "anon" };
1141
1167
 
1142
1168
  export const list = query.input({ channelId: v.string().max(256), limit: v.optional(v.number()) }).query(async ({ args, ctx }) => {
1143
1169
  const messages = await ctx.db
@@ -1150,13 +1176,13 @@ export const list = query.input({ channelId: v.string().max(256), limit: v.optio
1150
1176
 
1151
1177
  export const send = mutation
1152
1178
  .input({ channelId: v.string().max(256), text: v.string().max(4096) })
1153
- .use(rateLimit(limiter, "send", { key: (ctx) => ctx.auth.userId ?? "anon" }))
1179
+ .use(rateLimit(limiter, "send", byCaller))
1154
1180
  .mutation(async ({ args, ctx }) => {
1155
1181
  const id = await ctx.db.insert("messages", { channelId: args.channelId, text: args.text });
1156
1182
 
1157
1183
  return { channelId: args.channelId, id, text: args.text };
1158
1184
  });
1159
- `,cr=`import type { ShardNamespaceLike } from "lunorash/runtime";
1185
+ `,pa=`import type { ShardNamespaceLike } from "lunorash/runtime";
1160
1186
 
1161
1187
  import { defineApp } from "../lunora/_generated/app.js";
1162
1188
 
@@ -1170,7 +1196,7 @@ const app = defineApp<Env>()
1170
1196
 
1171
1197
  export const ShardDO = app.ShardDO;
1172
1198
  export default app;
1173
- `,dr=`{
1199
+ `,ha=`{
1174
1200
  "$schema": "node_modules/wrangler/config-schema.json",
1175
1201
  "name": "__NAME__",
1176
1202
  "main": "src/server.ts",
@@ -1182,23 +1208,23 @@ export default app;
1182
1208
  "migrations": [{ "tag": "v1", "new_sqlite_classes": ["ShardDO"] }],
1183
1209
  "observability": { "enabled": true, "head_sampling_rate": 1 },
1184
1210
  }
1185
- `,ur=[".wrangler",".env",".env.*","!.env.example",".dev.vars",".dev.vars.*","!.dev.vars.example",".lunora/",".lunora-cache","lunora/_generated"],pr=`# Lunora endpoint for the browser client.
1211
+ `,ma=[".wrangler",".env",".env.*","!.env.example",".dev.vars",".dev.vars.*","!.dev.vars.example",".lunora/",".lunora-cache","lunora/_generated"],fa=`# Lunora endpoint for the browser client.
1186
1212
  # Vite statically replaces \`import.meta.env.VITE_LUNORA_URL\` at \`vite dev\` / build.
1187
1213
  # Leave it unset to use the page origin; set it to point at a deployed Worker:
1188
1214
  #
1189
1215
  # VITE_LUNORA_URL=https://my-app.example.workers.dev
1190
- `,hr={"@cloudflare/workers-types":"^4.20260611.1",wrangler:"^4.100.0"},x=(e,t,r,a)=>{const o=u(e,t);M(A(o),{recursive:!0}),v(o,r,"utf8"),a.push(o)},mr=/\r?\n/,fr=e=>{const t=u(e,".gitignore"),r=m(t)?b(t,"utf8"):"",a=new Set(r.split(mr)),o=ur.filter(s=>!a.has(s));if(o.length===0)return;const n=r.length>0&&!r.endsWith(`
1216
+ `,va={"@cloudflare/workers-types":"^4.20260611.1",wrangler:"^4.100.0"},x=(e,t,a,r)=>{const o=d(e,t);L(M(o),{recursive:!0}),v(o,a,"utf8"),r.push(o)},ga=/\r?\n/,wa=e=>{const t=d(e,".gitignore"),a=m(t)?b(t,"utf8"):"",r=new Set(a.split(ga)),o=ma.filter(s=>!r.has(s));if(o.length===0)return;const n=a.length>0&&!a.endsWith(`
1191
1217
  `)?`
1192
- `:"";v(t,`${r}${n}
1218
+ `:"";v(t,`${a}${n}
1193
1219
  # Lunora
1194
1220
  ${o.join(`
1195
1221
  `)}
1196
- `,"utf8")},D=e=>e==="lunorash"||e.startsWith("@lunora/"),vr=(e,t,r,a)=>D(e)?a.get(e)??r:t,k=(e,t,r)=>({...e,[t]:r}),ee=(e,t,r)=>Object.fromEntries(Object.entries(e).map(([a,o])=>[a,vr(a,o,t,r)])),gr=async(e,t,r,a)=>{const o=u(e,"package.json"),n=JSON.parse(b(o,"utf8"));let s=k(n.dependencies??{},"lunorash",a);s=k(s,"@lunora/ratelimit",a),r.adapter.startsWith("@lunora/")&&(s=k(s,r.adapter,a));for(const[c,p]of Object.entries(r.extraDependencies??{}))s=k(s,c,p);let i=k(n.devDependencies??{},"@lunora/vite",a);i=k(i,"@lunora/studio",a);for(const[c,p]of Object.entries(hr))i=k(i,c,p);const l=[...Object.keys(s),...Object.keys(i)].filter(c=>D(c)),d=await ce(l,a);n.name=t,n.imports={...n.imports,"#lunora/*":"./lunora/*"},n.dependencies=ee(s,a,d),n.devDependencies=ee(i,a,d),n.scripts={...n.scripts,codegen:"lunora codegen",deploy:"vite build && lunora deploy"},v(o,`${JSON.stringify(n,void 0,4)}
1197
- `,"utf8")},wr=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],Se=e=>wr.map(t=>u(e,t)).find(t=>m(t)),yr=(e,t)=>{const r=Se(e);if(r===void 0){t.warn("overlay: no vite.config found in the create-vite base — add `lunora()` to your Vite plugins manually.");return}const a=ke(b(r,"utf8"));a.changed&&v(r,a.code,"utf8")},br=async e=>{const{adapter:t,distTag:r,logger:a,name:o,target:n}=e,s=[];x(n,u("lunora","ratelimit","schema.ts"),sr,s),x(n,u("lunora","schema.ts"),ir,s),x(n,u("lunora","messages.ts"),lr,s),x(n,u("src","server.ts"),cr,s),x(n,"wrangler.jsonc",dr.replaceAll("__NAME__",o),s),x(n,".env.example",pr,s);for(const i of t.files)x(n,i.path,i.contents,s);return yr(n,a),await gr(n,o,t,r),fr(n),s},xr=["lunar","silver","silent","waning","waxing","crescent","cosmic","stellar","orbital","gibbous","twilight","midnight","shimmering","drifting","weightless"],kr=["moon","tide","crater","comet","eclipse","halo","orbit","nebula","voyager","lander","rover","beacon","harbor","meadow","fox"],te=e=>e[Math.floor(Math.random()*e.length)],Cr=()=>`${te(xr)}-${te(kr)}`,Sr=async()=>wt.lookup("github.com").then(()=>!0,()=>!1),Lr=/^(?:gh|github):([^/]+)\/([^#/]+)(?:\/[^#]*)?(?:#(.+))?$/,Le=e=>{const t=Lr.exec(e);if(t===null)return;const[,r,a,o]=t;if(!(r===void 0||a===void 0))return{owner:r,ref:o??"HEAD",repo:a}},Mr=async e=>{const t=Le(e);if(t===void 0)return;const r=`https://codeload.github.com/${t.owner}/${t.repo}/tar.gz/${t.ref}`;try{const a=await fetch(r,{method:"HEAD"});return a.status===404?!1:a.ok?!0:void 0}catch{return}},Me=async e=>e.isLocal||!(e.source===void 0||Le(e.source)!==void 0)?!0:await Sr()?e.source!==void 0&&await Mr(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?"},Ar=new Set([".gitignore",".html",".js",".json",".jsonc",".md",".mjs",".ts",".tsx"]),Er=`import { defineConfig } from "vite";
1222
+ `,"utf8")},D=e=>e==="lunorash"||e.startsWith("@lunora/"),ya=(e,t,a,r)=>D(e)?r.get(e)??a:t,k=(e,t,a)=>({...e,[t]:a}),Z=(e,t,a)=>Object.fromEntries(Object.entries(e).map(([r,o])=>[r,ya(r,o,t,a)])),ba=async(e,t,a,r)=>{const o=d(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(va))i=k(i,c,p);const l=[...Object.keys(s),...Object.keys(i)].filter(c=>D(c)),u=await ue(l,r);n.name=t,n.imports={...n.imports,"#lunora/*":"./lunora/*"},n.dependencies=Z(s,r,u),n.devDependencies=Z(i,r,u),n.scripts={...n.scripts,codegen:"lunora codegen",deploy:"vite build && lunora deploy"},v(o,`${JSON.stringify(n,void 0,4)}
1223
+ `,"utf8")},xa=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],Me=e=>xa.map(t=>d(e,t)).find(t=>m(t)),ka=(e,t)=>{const a=Me(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=Se(b(a,"utf8"));r.changed&&v(a,r.code,"utf8")},Ca=async e=>{const{adapter:t,distTag:a,logger:r,name:o,target:n}=e,s=[];x(n,d("lunora","ratelimit","schema.ts"),ca,s),x(n,d("lunora","schema.ts"),da,s),x(n,d("lunora","messages.ts"),ua,s),x(n,d("src","server.ts"),pa,s),x(n,"wrangler.jsonc",ha.replaceAll("__NAME__",o),s),x(n,".env.example",fa,s);for(const i of t.files)x(n,i.path,i.contents,s);return ka(n,r),await ba(n,o,t,a),wa(n),s},Sa=["lunar","silver","silent","waning","waxing","crescent","cosmic","stellar","orbital","gibbous","twilight","midnight","shimmering","drifting","weightless"],La=["moon","tide","crater","comet","eclipse","halo","orbit","nebula","voyager","lander","rover","beacon","harbor","meadow","fox"],ee=e=>e[Math.floor(Math.random()*e.length)],Ma=()=>`${ee(Sa)}-${ee(La)}`,Aa=async()=>xt.lookup("github.com").then(()=>!0,()=>!1),Ea=/^(?:gh|github):([^/]+)\/([^#/]+)(?:\/[^#]*)?(?:#(.+))?$/,Ae=e=>{const t=Ea.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}},Na=async e=>{const t=Ae(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}},Ee=async e=>e.isLocal||!(e.source===void 0||Ae(e.source)!==void 0)?!0:await Aa()?e.source!==void 0&&await Na(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?"},Ia=new Set([".gitignore",".html",".js",".json",".jsonc",".md",".mjs",".ts",".tsx"]),$a=`import { defineConfig } from "vite";
1198
1224
  import { lunora } from "@lunora/vite";
1199
1225
 
1200
1226
  export default defineConfig({ plugins: [lunora()] });
1201
- `,Nr=`import { defineSchema, defineTable, v } from "@lunora/server";
1227
+ `,_a=`import { defineSchema, defineTable, v } from "@lunora/server";
1202
1228
 
1203
1229
  export default defineSchema({
1204
1230
  messages: defineTable({
@@ -1208,7 +1234,7 @@ export default defineSchema({
1208
1234
  .shardBy("channelId")
1209
1235
  .index("by_channel", ["channelId"]),
1210
1236
  });
1211
- `,Ir=`import { mutation, query, v } from "./_generated/server";
1237
+ `,Ra=`import { mutation, query, v } from "./_generated/server";
1212
1238
 
1213
1239
  export const list = query
1214
1240
  .input({ channelId: v.id("channels"), limit: v.optional(v.number()) })
@@ -1221,8 +1247,8 @@ export const send = mutation
1221
1247
  .mutation(async ({ args }) => {
1222
1248
  return { channelId: args.channelId, text: args.text };
1223
1249
  });
1224
- `,$r="gh:anolilab/lunora/templates",_r=e=>{const t=e.lastIndexOf(".");return t===-1?!1:Ar.has(e.slice(t))},Rr=(e,t)=>e.replaceAll("{{name}}",t),Tr=async(e,t)=>{const r=new Set;for(const a of e)if(E(a)==="package.json")try{const o=JSON.parse(b(a,"utf8"));for(const n of["dependencies","devDependencies"])for(const s of Object.keys(o[n]??{}))D(s)&&r.add(s)}catch{}return ce(r,t)},Or=(e,t,r)=>{let a;try{a=JSON.parse(e)}catch{return e}let o=e;for(const n of["dependencies","devDependencies"])for(const s of Object.keys(a[n]??{})){if(!D(s))continue;const i=r.get(s)??t,l=Ye(o,[n,s],i,{formattingOptions:{insertSpaces:!0,tabSize:4}});o=Xe(o,l)}return o},Pr=["@parcel/watcher","esbuild","lmdb","msgpackr-extract","rs-module-lexer","sharp","unrs-resolver","vue-demi","workerd"],Dr=["cpu-features","protobufjs","ssh2"],Ae="pnpm-workspace.yaml",Br=()=>["# 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:",...Pr.map(e=>` '${e}': true`),...Dr.map(e=>` '${e}': false`),""].join(`
1225
- `),q=e=>{const t=[];for(const r of Ge(e,{includeDirs:!1,includeFiles:!0}))Pe(r.path).isSymbolicLink()||t.push(r.path);return t},Ee=async(e,t,r)=>{const a=q(e),o=[],n=de(),s=await Tr(a,n);for(const i of a){const l=Je(e,i),d=u(t,l);M(A(d),{recursive:!0});const c=b(i);let p=_r(i)?Rr(c.toString("utf8"),r):void 0;p!==void 0&&E(i)==="package.json"&&(p=Or(p,n,s)),p===void 0?v(d,c):v(d,p,"utf8"),o.push(d)}return o},j=(e,t,r)=>t!==void 0&&t.length>0?t:`${$r}/${e}#${ue(r)}`,jr=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,r)=>{g()&&process.stdout.write(`
1226
- `),e.success(`scaffolded ${String(t.length)} files into ${r}`)},Vr=(e,t)=>{const{args:r,command:a}=qe(e,t);return`${a} ${r.join(" ")}`},Ne=(e,t)=>{let r=ie(e);for(;;){if(t(r))return!0;const a=A(r);if(a===r)return!1;r=a}},Ur=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,Ur),Fr=e=>Ne(e,t=>m(u(t,".git"))),Hr=async(e,t)=>{if(e.yes===!0||!g()||Fr(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 r=e.spawner??pe;(await it("Initializing a git repository…",()=>r({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`.")},Wr=async(e,t,r,a)=>{const o=[{code:`cd ./${e}`,lead:"Enter your project directory using"}];t===void 0&&o.push({code:`${r} install`,lead:"Install dependencies with",tail:a?" from the workspace root":void 0}),o.push({code:We(r,"dev"),lead:"Run",tail:" to start the dev server."},{code:"lunora add",lead:"Add features like auth or storage using"});const n=[{code:"https://lunora.sh/docs",lead:"Read the docs at"},{code:"https://lunora.sh/chat",lead:"Stuck? Join the chat at"}];if(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
- `))},zr=e=>e.yes!==!0&&(e.installPrompt!==void 0||g()),qr=async(e,t)=>{if(!zr(e)||Ie(A(t)))return;const r=He(e.packageManagerProbe),[a]=r;if(a===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=a;if(r.length>1&&(n=e.installPrompt?await e.installPrompt.selectManager(r):await W(y.packageManager,r.map(c=>({label:c,value:c})),{badge:f.deps,default:a})??a),e.dryRun===!0){S(e.logger,`install dependencies with ${n}`);return}if(n==="pnpm"){const c=u(t,Ae);m(c)||v(c,Br(),"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},Kr=async(e,t,r,a,o)=>{const n=u(e,t);if(!m(n))return o.error(`template not found in local source: ${n}`),{code:1,files:[],target:r};const s=await Ee(n,r,a);return K(o,s,r),{code:0,files:s,target:r}},Gr=async e=>{const{logger:t,name:r,ref:a,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?a:await rt(a,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 ${r}/`,run:async()=>{h=await Ee(l,n,r)}}],{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(a),remote:j(s,o,a),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})}},Jr=e=>{for(const t of["_gitignore","_npmrc","_gitattributes"]){const r=u(e,t);m(r)&&Oe(r,u(e,`.${t.slice(1)}`))}},Yr=async e=>{const{framework:t,logger:r,name:a,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 r.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}),Jr(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 br({adapter:s,distTag:de(),logger:r,name:a,target:n})}}],{end:"Project initialized!",start:"Project initializing…"}),K(r,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 r.error(`failed to scaffold the ${s.label} base: ${d}`),{code:1,files:[],target:n}}finally{_(i,{force:!0,recursive:!0})}},V=(e,t,r,a,o)=>(o.error(`init --in-place: could not ${e} ${t}: ${r instanceof Error?r.message:String(r)}`),{code:1,files:[],target:a}),Xr=(e,t)=>{const r=u(e,"vite.config.ts");try{v(r,Er,"utf8")}catch(a){return V("write",r,a,e,t)}return t.success(`created ${r} with lunora() plugin`),{code:0,files:[r],target:e}},Qr=(e,t,r)=>{let a;try{a=b(e,"utf8")}catch(n){return V("read",e,n,t,r)}const o=ke(a);if(!o.changed)return r.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,r)}return r.success(`patched ${e} — added lunora() plugin`),{code:0,files:[e],target:t}},Zr=(e,t)=>{const r=u(e,"lunora"),a=u(r,"schema.ts");if(m(a))return t.info(`lunora/ already present — left ${a} untouched`),[];const o=[];try{M(r,{recursive:!0}),v(a,Nr,"utf8"),o.push(a);const n=u(r,"messages.ts");m(n)||(v(n,Ir,"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},ea=(e,t,r)=>{const{adapter:a,class:o,framework:n}=e;r.info(""),r.info(`detected framework: ${n} (class ${o})`),r.info("next steps:"),r.info(` 1. install the adapter: ${Vr(t,[a,"@lunora/client","@lunora/runtime","@lunora/server"])}`),r.info(" 2. run codegen: lunora codegen"),o==="A"?(r.info(" 3. compose one worker: wrap your worker entry with"),r.info(" createWorker({ httpRouter: <your framework SSR handler>, shardDO: ShardDO, ... })"),r.info(` 4. add the provider: mount the ${a} provider in your root layout/route`),r.info(" 5. make a loader live: preloadQuery() in a loader, usePreloadedQuery() in the component"),r.info(" see https://lunora.sh/docs/frameworks/reactive-loaders")):o==="B"?(r.info(" 3. inject Lunora: mount Lunora realtime under /_lunora/* in your server hook"),r.info(` (${n} owns its Cloudflare adapter — Lunora composes into its server entry)`),r.info(` 4. add the provider: mount the ${a} provider in your root layout`),r.info(" 5. read the guide: https://lunora.sh/docs/frameworks/deploy")):(r.info(" 3. add the provider: wrap your app with the LunoraProvider from @lunora/react"),r.info(" 4. read the guide: https://lunora.sh/docs/frameworks/bring-your-framework")),r.info("")},ta=(e,t,r)=>{const a=Se(e);return a===void 0?t==="sveltekit"||t==="nuxt"||t==="astro"?(r.info(`no Vite config found — ${t} wires Lunora through its server entry (see next steps)`),{code:0,files:[],target:e}):Xr(e,r):Qr(a,e,r)},ra=(e,t)=>{const r=At(e),a=ta(e,r.framework,t);if(a.code!==0)return a;const o=Zr(e,t);return ea(r,U(e),t),{code:0,files:[...a.files,...o],target:e}},aa=e=>e.yes!==!0&&(e.prompt!==void 0||(e.interactive??g())),re=async(e,t,r)=>{r.dryRun!==!0&&await Jt({apply:a=>Ke(e,a),detected:ze(e),interactive:t,logger:r.logger,multiSelect:r.lintPrompt??((a,o,n)=>me(a,o,{...n,badge:f.add}))})},oa=async(e,t)=>{const r=aa(e),a=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:r,logger:e.logger,multiSelect:e.prompt?.multiSelect??((s,i,l)=>me(s,i,{...l,badge:f.add})),preselected:a.length>0?a: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(a.length>0){const s=await Z(n);return await re(t,r,e),s}return g()&&await st(y.extras),await Z(n),await re(t,r,e),!0},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("|"),na=e=>P(e)?{framework:e,kind:"overlay"}:{kind:"template",templateType:e},sa=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"}:na(await W(y.framework,$e,{badge:f.tmpl,default:B})??B),ia=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.`},la=async(e,t,r,a)=>P(t)?await Me({isLocal:e.overlayBaseFrom!==void 0,logger:e.logger})?(M(a,{recursive:!0}),Yr({framework:t,logger:e.logger,name:r,overlayBaseFrom:e.overlayBaseFrom,target:a})):{code:1,files:[],target:a}:(e.logger.error(`init: unknown framework "${t}". Supported overlays: ${Object.keys(O).join(", ")}.`),{code:1,files:[],target:a}),ca=async(e,t,r,a)=>e.from!==void 0?await Kr(e.from,t,a,r,e.logger):e.source!==void 0&&e.source.length>0&&!e.allowUnsafeSource&&!jr(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:a}):await Me({isLocal:!1,logger:e.logger,source:j(t,e.source,e.ref)})?Gr({logger:e.logger,name:r,ref:e.ref,source:e.source,target:a,templateType:t}):{code:1,files:[],target:a},da=async(e,t,r)=>{await nt("realtime backend on Cloudflare Workers + Durable Objects");const a=ia(e);if(a!==void 0)return e.logger.error(a),{code:1,files:[],target:""};const o=Cr(),n=e.name??await he(y.name,{badge:f.dir,default:o,placeholder:o}),s=await sa(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&&ae(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 r(l,d),s.kind==="overlay"?la(e,s.framework,i,l):ca(e,s.templateType,i,l)},ua=(e,t)=>{const{target:r,targetPreExisted:a}=e;if(!(r===void 0||!m(r))){if(a===!0)for(const o of ae(r))_(u(r,o),{force:!0,recursive:!0});else _(r,{force:!0,recursive:!0});t.info(`removed the partially-created project at ${r}`)}},pa=async(e,t,r)=>e.inPlace!==!0?da(e,t,r):e.dryRun===!0?(S(e.logger,`configure Lunora into ${t}`),{code:0,files:[],target:t}):ra(t,e.logger),ha=async(e,t,r)=>{const a=await oa(e,t.target),o=e.inPlace===!0?void 0:await qr(e,t.target);if(e.inPlace!==!0){await Hr(e,t.target);const n=o??U(t.target);await Wr(E(t.target),o,n,Ie(r)),await jt(e.logger)}return a},ma=(e,t,r)=>{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 a=e.inPlace===!0?r:t.target;try{const o=U(a);Lt(a,e.ci,o,e.logger)}catch{e.logger.warn(`--ci ${e.ci}: could not detect a package manager for this project — skipped the CI pipeline.`)}},fa=async e=>{const t=e.cwd??process.cwd(),r={};let a;try{a=await pa(e,t,(o,n)=>{r.target=o,r.targetPreExisted=n}),a.code===0&&a.target!==""&&(r.target=void 0,await ha(e,a,t)||(a={...a,code:1}))}catch(o){if(o instanceof H)return ua(r,e.logger),process.stdout.write("\n ✖ Setup cancelled — run `lunora init` again whenever you're ready. 🌙\n"),{code:130,files:[],target:""};throw o}return ma(e,a,t),a},va=e=>typeof e=="string"&&Re.includes(e),ga=(e,t)=>{if(e!==void 0){if(Ct(e))return e;t.warn(`init: unknown --ci "${e}" — expected github | gitlab; skipping CI scaffold.`)}},wa=e=>e===void 0?{}:va(e)?{templateType:e}:P(e)?{vite:e}:{error:`init: unknown --template "${e}" — expected a bespoke template (${Te}) or an overlay framework (${_e}).`},ja=Ze(({argument:e,cwd:t,logger:r,options:a})=>{const o=wa(a.template);return"error"in o?(r.error(o.error),{code:1}):fa({add:a.add,allowUnsafeSource:a.allowUnsafeSource===!0,cwd:t,ci:ga(a.ci,r),dryRun:a.dryRun===!0,from:a.from,inPlace:a.here===!0,interactive:a.interactive===!0?!0:void 0,logger:r,name:e[0],ref:a.ref,source:a.source,templateType:o.templateType,vite:a.vite??o.vite,yes:a.yes===!0})});export{ja as execute,va as isTemplate,wa as resolveTemplateFlag,j as resolveTemplateSource,fa as runInitCommand};
1250
+ `,Ta="gh:anolilab/lunora/templates",Oa=e=>{const t=e.lastIndexOf(".");return t===-1?!1:Ia.has(e.slice(t))},Pa=(e,t)=>e.replaceAll("{{name}}",t),Da=async(e,t)=>{const a=new Set;for(const r of e)if(N(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 ue(a,t)},Ba=(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=Qe(o,[n,s],i,{formattingOptions:{insertSpaces:!0,tabSize:4}});o=Ze(o,l)}return o},ja=["@parcel/watcher","esbuild","lmdb","msgpackr-extract","rs-module-lexer","sharp","unrs-resolver","vue-demi","workerd"],Va=["cpu-features","protobufjs","ssh2"],Ne="pnpm-workspace.yaml",Ua=()=>["# 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:",...ja.map(e=>` '${e}': true`),...Va.map(e=>` '${e}': false`),""].join(`
1251
+ `),B=e=>{const t=[];for(const a of Xe(e,{includeDirs:!1,includeFiles:!0}))je(a.path).isSymbolicLink()||t.push(a.path);return t},te="vitejs/vite",ae=(e,t)=>{for(const a of B(e)){const r=d(t,ce(e,a));L(M(r),{recursive:!0}),De(a,r)}},Ie=async(e,t,a)=>{const r=B(e),o=[],n=pe(),s=await Da(r,n);for(const i of r){const l=ce(e,i),u=d(t,l);L(M(u),{recursive:!0});const c=b(i);let p=Oa(i)?Pa(c.toString("utf8"),a):void 0;p!==void 0&&N(i)==="package.json"&&(p=Ba(p,n,s)),p===void 0?v(u,c):v(u,p,"utf8"),o.push(u)}return o},V=(e,t,a)=>t!==void 0&&t.length>0?t:`${Ta}/${e}#${he(a)}`,Fa=e=>e.includes("..")?!1:e.startsWith("gh:")||e.startsWith("github:")||e.startsWith("https://"),A=(e,t)=>{e.info(`[dry-run] would ${t}`)},K=(e,t,a)=>{g()&&process.stdout.write(`
1252
+ `),e.success(`scaffolded ${String(t.length)} files into ${a}`)},Ha=(e,t)=>{const{args:a,command:r}=Je(e,t);return`${r} ${a.join(" ")}`},$e=(e,t)=>{let a=le(e);for(;;){if(t(a))return!0;const r=M(a);if(r===a)return!1;a=r}},Wa=e=>{if(m(d(e,Ne)))return!0;const t=d(e,"package.json");if(!m(t))return!1;try{return JSON.parse(b(t,"utf8")).workspaces!==void 0}catch{return!1}},_e=e=>$e(e,Wa),za=e=>$e(e,t=>m(d(t,".git"))),qa=async(e,t)=>{if(e.yes===!0||!g()||za(M(t)))return;if(!await ge(y.git,{badge:f.git,defaultYes:!1})){await we("Sounds good! You can always run git init manually.");return}if(e.dryRun===!0){A(e.logger,"initialize a git repository");return}const a=e.spawner??me;(await dt("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`.")},Ka=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:Ke(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 ut(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(`
1253
+ `))},Ga=e=>e.yes!==!0&&(e.installPrompt!==void 0||g()),Ja=async(e,t)=>{if(!Ga(e)||_e(M(t)))return;const a=qe(e.packageManagerProbe),[r]=a;if(r===void 0)return;if(!await(e.installPrompt?.confirmInstall??(async()=>ge(y.install,{badge:f.deps,defaultYes:!0})))()){await we("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 z(y.packageManager,a.map(c=>({label:c,value:c})),{badge:f.deps,default:r})??r),e.dryRun===!0){A(e.logger,`install dependencies with ${n}`);return}if(n==="pnpm"){const c=d(t,Ne);m(c)||v(c,Ua(),"utf8")}const s=e.spawner??me,{args:i,command:l}=ie(n);await R("deps",`Installing dependencies with ${n}…`);const u=await s({args:i,command:l,cwd:t});if(u.code!==0){e.logger.warn(`\`${l} install\` exited with code ${String(u.code)} — run it yourself in ${N(t)}/.`);return}return await R("deps",`Dependencies installed with ${n}.`),n},Ya=async(e,t,a,r,o)=>{const n=d(e,t);if(!m(n))return o.error(`template not found in local source: ${n}`),{code:1,files:[],target:a};const s=await Ie(n,a,r);return K(o,s,a),{code:0,files:s,target:a}},Xa=async e=>{const{logger:t,name:a,ref:r,source:o,target:n,templateType:s}=e,i=ne(d(se(),"lunora-init-fetch-")),l=d(i,"template");try{const u=o!==void 0&&o.length>0?r:await nt(r,t),c=V(s,o,u);let p,h=[];await ye([{label:`${s} template fetched`,run:async()=>{p=await de(c,{cwd:i,dir:l,force:!0,install:!1,silent:!0})}},{label:`files copied into ${a}/`,run:async()=>{h=await Ie(l,n,a)}}],{end:"Project initialized!",start:"Project initializing…"});const C=B(l);return g()&&process.stdout.write(`
1254
+ `),t.info(p?.commit?`template: ${p.source} @ ${p.commit} (${String(C.length)} files)`:`template: ${p?.source??c} (${String(C.length)} files)`),K(t,h,n),{code:0,files:h,target:n}}catch(u){if(u instanceof W)throw u;const{hints:c,message:p}=Ut(u,{ref:he(r),remote:V(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})}},Qa=e=>{for(const t of["_gitignore","_npmrc","_gitattributes"]){const a=d(e,t);m(a)&&Be(a,d(e,`.${t.slice(1)}`))}},Za=async e=>{const{framework:t,logger:a,name:r,overlayBaseFrom:o,target:n}=e,s=O[t],i=ne(d(se(),"lunora-vite-base-"));try{let l;if(o!==void 0&&(l=d(o,`template-${s.createViteTemplate}`),!m(l)))return a.error(`create-vite base not found on disk: ${l}`),{code:1,files:[],target:n};const u=async()=>{if(l!==void 0){ae(l,n);return}const p=d(i,"base"),h=await ot(te,"main",a),C=`github:${te}/packages/create-vite/template-${s.createViteTemplate}#${h}`;await de(C,{cwd:i,dir:p,force:!0,install:!1,silent:!0}),Qa(p),ae(p,n)};let c=[];return await ye([{label:`create-vite (${s.label}) base ready`,run:u},{label:`Lunora overlay applied (${s.label})`,run:async()=>{c=await Ca({adapter:s,distTag:pe(),logger:a,name:r,target:n})}}],{end:"Project initialized!",start:"Project initializing…"}),K(a,c,n),{code:0,files:[...B(n)],target:n}}catch(l){if(l instanceof W)throw l;const u=l instanceof Error?l.message:String(l);return a.error(`failed to scaffold the ${s.label} base: ${u}`),{code:1,files:[],target:n}}finally{_(i,{force:!0,recursive:!0})}},U=(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}),er=(e,t)=>{const a=d(e,"vite.config.ts");try{v(a,$a,"utf8")}catch(r){return U("write",a,r,e,t)}return t.success(`created ${a} with lunora() plugin`),{code:0,files:[a],target:e}},tr=(e,t,a)=>{let r;try{r=b(e,"utf8")}catch(n){return U("read",e,n,t,a)}const o=Se(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 U("write",e,n,t,a)}return a.success(`patched ${e} — added lunora() plugin`),{code:0,files:[e],target:t}},ar=(e,t)=>{const a=d(e,"lunora"),r=d(a,"schema.ts");if(m(r))return t.info(`lunora/ already present — left ${r} untouched`),[];const o=[];try{L(a,{recursive:!0}),v(r,_a,"utf8"),o.push(r);const n=d(a,"messages.ts");m(n)||(v(n,Ra,"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},rr=(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: ${Ha(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("")},or=(e,t,a)=>{const r=Me(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}):er(e,a):tr(r,e,a)},nr=(e,t)=>{const a=It(e),r=or(e,a.framework,t);if(r.code!==0)return r;const o=ar(e,t);return rr(a,F(e),t),{code:0,files:[...r.files,...o],target:e}},sr=e=>e.yes!==!0&&(e.prompt!==void 0||(e.interactive??g())),re=async(e,t,a)=>{a.dryRun!==!0&&await Qt({apply:r=>Ye(e,r),detected:Ge(e),interactive:t,logger:a.logger,multiSelect:a.lintPrompt??((r,o,n)=>ve(r,o,{...n,badge:f.add}))})},ir=async(e,t)=>{const a=sr(e),r=e.add===void 0?[]:Wt(e.add,s=>{e.logger.warn(s)}),n={applyAll:async s=>{if(s.length===0)return!0;if(e.dryRun===!0)return A(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,u=s.map(h=>({running:`adding ${h.label}…`,task:()=>kt({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 pt(f.add,u,c);for(const{level:h,message:C}of i)e.logger[h](C);return p.every(h=>h.code===0)},interactive:a,logger:e.logger,multiSelect:e.prompt?.multiSelect??((s,i,l)=>ve(s,i,{...l,badge:f.add})),preselected:r.length>0?r:void 0,projectName:N(t),resolveAuthUiItem:()=>{try{const s=JSON.parse(b(d(t,"package.json"),"utf8"));return yt({...s.dependencies,...s.devDependencies})??"auth-ui-react"}catch{return"auth-ui-react"}},select:e.prompt?.select??((s,i,l)=>z(s,i,{...l,badge:f.add})),text:e.prompt?.text??((s,i)=>fe(s,{...i,badge:f.add}))};if(r.length>0){const s=await Q(n);return await re(t,a,e),s}return g()&&await ct(y.extras),await Q(n),await re(t,a,e),!0},j="react",Re=[{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"}],Te=Object.keys(O).join("|"),Oe=Re.filter(e=>!P(e.value)).map(e=>e.value),Pe=Oe.join("|"),lr=e=>P(e)?{framework:e,kind:"overlay"}:{kind:"template",templateType:e},cr=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:j,kind:"overlay"}:lr(await z(y.framework,Re,{badge:f.tmpl,default:j})??j),dr=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 <${Te}>\` for an SPA, or \`-t <${Pe}>\` 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.`},ur=async(e,t,a,r)=>P(t)?await Ee({isLocal:e.overlayBaseFrom!==void 0,logger:e.logger})?(L(r,{recursive:!0}),Za({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}),pr=async(e,t,a,r)=>e.from!==void 0?await Ya(e.from,t,r,a,e.logger):e.source!==void 0&&e.source.length>0&&!e.allowUnsafeSource&&!Fa(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 Ee({isLocal:!1,logger:e.logger,source:V(t,e.source,e.ref)})?Xa({logger:e.logger,name:a,ref:e.ref,source:e.source,target:r,templateType:t}):{code:1,files:[],target:r},hr=async(e,t,a)=>{await lt("realtime backend on Cloudflare Workers + Durable Objects");const r=dr(e);if(r!==void 0)return e.logger.error(r),{code:1,files:[],target:""};const o=Ma(),n=e.name??await fe(y.name,{badge:f.dir,default:o,placeholder:o}),s=await cr(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=le(t,i),u=m(l);if(u&&oe(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 A(e.logger,`scaffold ${c} into ${l}`),{code:0,files:[],target:l}}return a(l,u),s.kind==="overlay"?ur(e,s.framework,i,l):pr(e,s.templateType,i,l)},mr=(e,t)=>{const{target:a,targetPreExisted:r}=e;if(!(a===void 0||!m(a))){if(r===!0)for(const o of oe(a))_(d(a,o),{force:!0,recursive:!0});else _(a,{force:!0,recursive:!0});t.info(`removed the partially-created project at ${a}`)}},fr=async(e,t,a)=>e.inPlace!==!0?hr(e,t,a):e.dryRun===!0?(A(e.logger,`configure Lunora into ${t}`),{code:0,files:[],target:t}):nr(t,e.logger),vr=async(e,t,a)=>{const r=await ir(e,t.target),o=e.inPlace===!0?void 0:await Ja(e,t.target);if(e.inPlace!==!0){await qa(e,t.target);const n=o??F(t.target);await Ka(N(t.target),o,n,_e(a)),await Ft(e.logger)}return r},gr=(e,t,a)=>{if(t.code!==0||e.ci===void 0)return;if(e.dryRun===!0){A(e.logger,`scaffold a ${e.ci} CI deploy pipeline`);return}const r=e.inPlace===!0?a:t.target;try{const o=F(r);Et(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.`)}},wr=async e=>{const t=e.cwd??process.cwd(),a={};let r;try{r=await fr(e,t,(o,n)=>{a.target=o,a.targetPreExisted=n}),r.code===0&&r.target!==""&&(a.target=void 0,await vr(e,r,t)||(r={...r,code:1}))}catch(o){if(o instanceof W)return mr(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 gr(e,r,t),r},yr=e=>typeof e=="string"&&Oe.includes(e),br=(e,t)=>{if(e!==void 0){if(Mt(e))return e;t.warn(`init: unknown --ci "${e}" — expected github | gitlab; skipping CI scaffold.`)}},xr=e=>e===void 0?{}:yr(e)?{templateType:e}:P(e)?{vite:e}:{error:`init: unknown --template "${e}" — expected a bespoke template (${Pe}) or an overlay framework (${Te}).`},Fr=tt(({argument:e,cwd:t,logger:a,options:r})=>{const o=xr(r.template);return"error"in o?(a.error(o.error),{code:1}):wr({add:r.add,allowUnsafeSource:r.allowUnsafeSource===!0,cwd:t,ci:br(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{Fr as execute,yr as isTemplate,xr as resolveTemplateFlag,V as resolveTemplateSource,wr as runInitCommand};