@lunora/cli 1.0.0-alpha.131 → 1.0.0-alpha.133

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 (49) hide show
  1. package/README.md +1 -1
  2. package/dist/bin.mjs +1 -1
  3. package/dist/index.d.mts +36 -7
  4. package/dist/index.d.ts +36 -7
  5. package/dist/index.mjs +1 -1
  6. package/dist/packem_chunks/handler.mjs +1 -1
  7. package/dist/packem_chunks/handler10.mjs +1 -1
  8. package/dist/packem_chunks/handler11.mjs +1 -1
  9. package/dist/packem_chunks/handler13.mjs +1 -1
  10. package/dist/packem_chunks/handler15.mjs +1 -1
  11. package/dist/packem_chunks/handler16.mjs +1 -1
  12. package/dist/packem_chunks/handler18.mjs +1 -1
  13. package/dist/packem_chunks/handler19.mjs +1 -1
  14. package/dist/packem_chunks/handler2.mjs +2 -2
  15. package/dist/packem_chunks/handler21.mjs +1 -1
  16. package/dist/packem_chunks/handler22.mjs +1 -1
  17. package/dist/packem_chunks/handler23.mjs +1 -99
  18. package/dist/packem_chunks/handler24.mjs +99 -11
  19. package/dist/packem_chunks/handler25.mjs +11 -0
  20. package/dist/packem_chunks/handler3.mjs +1 -1
  21. package/dist/packem_chunks/handler5.mjs +1 -1
  22. package/dist/packem_chunks/handler6.mjs +1 -1
  23. package/dist/packem_chunks/handler9.mjs +3 -8
  24. package/dist/packem_chunks/planDevCommand.mjs +6 -6
  25. package/dist/packem_chunks/runCodegenCommand.mjs +4 -4
  26. package/dist/packem_chunks/runDeployCommand.mjs +1 -1
  27. package/dist/packem_chunks/runInitCommand.mjs +68 -73
  28. package/dist/packem_chunks/runMigrateGenerateCommand.mjs +1 -1
  29. package/dist/packem_chunks/runRpcCommand.mjs +1 -1
  30. package/dist/packem_shared/COMMANDS-BEkrtuj_.mjs +1 -0
  31. package/dist/packem_shared/advisory-gate-yaOOyUQl.mjs +1 -0
  32. package/dist/packem_shared/cli-Cmbw5lEB.mjs +3 -0
  33. package/dist/packem_shared/commands-BvfzxKAa.mjs +19 -0
  34. package/dist/packem_shared/createRecordingSpawner-SKs4R1fc.mjs +1 -0
  35. package/dist/packem_shared/detect-package-manager-D9r2z_X6.mjs +1 -0
  36. package/dist/packem_shared/{post-codegen-hook-CjhP1OmV.mjs → post-codegen-hook-reEtIN59.mjs} +1 -1
  37. package/dist/packem_shared/resolve-target-CeiNrCAx.mjs +1 -0
  38. package/dist/packem_shared/runAddCommand-oQMYPkp6.mjs +1 -0
  39. package/dist/packem_shared/{storage-BazhWFmM.mjs → storage-CSzKwh4L.mjs} +1 -1
  40. package/dist/packem_shared/wrangler-secrets-DzYgUxU-.mjs +1 -0
  41. package/package.json +12 -12
  42. package/dist/packem_shared/COMMANDS-CCuhsVyI.mjs +0 -1
  43. package/dist/packem_shared/cli-0uJWyeda.mjs +0 -3
  44. package/dist/packem_shared/commands-C5pu77HK.mjs +0 -19
  45. package/dist/packem_shared/createRecordingSpawner-ByIqBepG.mjs +0 -1
  46. package/dist/packem_shared/detect-package-manager-C4aS7HE4.mjs +0 -1
  47. package/dist/packem_shared/resolve-target-vxaXHmvg.mjs +0 -1
  48. package/dist/packem_shared/runAddCommand-CuvJ0l7a.mjs +0 -1
  49. package/dist/packem_shared/wrangler-secrets-DHpbsDN9.mjs +0 -1
@@ -1,4 +1,11 @@
1
- import{existsSync as h,mkdirSync as L,writeFileSync as m,readFileSync as b,readdirSync as X,rmSync as I,mkdtempSync as Y,lstatSync as Me,cpSync as W,renameSync as Le}from"node:fs";import{tmpdir as Z}from"node:os";import{detectFramework as Se,isInteractive as g,LUNA_ART as Ae,LUNA_NAME as Ne,LUNA_SIGNOFF as Ie,paintAnswer as _e,BADGES as f}from"@lunora/config";import{walkSync as Re}from"@visulima/fs";import{join as p,dirname as $,basename as S,resolve as B,relative as Te}from"@visulima/path";import{downloadTemplate as ee}from"giget";import{modify as Oe,applyEdits as je}from"jsonc-parser";import{join as E,dirname as Be}from"node:path";import{i as Ee}from"../packem_shared/command-Bjv4VmYA.mjs";import{P as te,t as Pe,d as De,l as ze}from"../packem_shared/detect-package-manager-C4aS7HE4.mjs";import Ue from"magic-string";import{Project as ae,SyntaxKind as v}from"ts-morph";import{P}from"../packem_shared/prompt-cancelled-C8Sj7OqI.mjs";import{P as re,g as oe,b as Ve,L as se,k as He}from"../packem_shared/commands-C5pu77HK.mjs";import{defaultSpawner as ie}from"../packem_shared/createRecordingSpawner-ByIqBepG.mjs";import{Y as We,h as qe,M as Fe,C as ne,U as Ke,i as le,X as ce,B as D,H as Je,W as Qe,Q as de,I as Ge,t as Xe}from"../packem_shared/tui-prompts-CCt3jm1k.mjs";import{l as pe,u as Ye,p as Ze,b as et,a as tt,m as at,n as rt,f as ue,q as he,h as ot}from"../packem_shared/storage-BazhWFmM.mjs";import{logStep as q}from"../packem_shared/createLogger--C3x1FNE.mjs";import st from"node:dns/promises";const it=`name: Deploy
1
+ import{existsSync as h,mkdirSync as S,writeFileSync as m,readFileSync as b,readdirSync as te,rmSync as _,mkdtempSync as ae,lstatSync as Ne,cpSync as K,renameSync as Ie}from"node:fs";import{tmpdir as re}from"node:os";import{detectFramework as _e,isInteractive as g,LUNA_ART as Re,LUNA_NAME as Te,LUNA_SIGNOFF as je,paintAnswer as Oe,BADGES as f}from"@lunora/config";import{walkSync as Be}from"@visulima/fs";import{join as p,dirname as C,basename as A,resolve as E,relative as Ee}from"@visulima/path";import{downloadTemplate as oe}from"giget";import{modify as Pe,applyEdits as De}from"jsonc-parser";import{join as P,dirname as Ue}from"node:path";import{p as se,M as Ve,l as D,t as ze,f as He}from"../packem_shared/detect-package-manager-D9r2z_X6.mjs";import{i as We}from"../packem_shared/command-Bjv4VmYA.mjs";import qe from"magic-string";import{Project as ie,SyntaxKind as v}from"ts-morph";import{P as U}from"../packem_shared/prompt-cancelled-C8Sj7OqI.mjs";import{P as ne,g as le,b as Fe,L as ce,I as Ke}from"../packem_shared/commands-BvfzxKAa.mjs";import{defaultSpawner as de}from"../packem_shared/createRecordingSpawner-SKs4R1fc.mjs";import{Y as Je,h as Qe,M as Ge,C as pe,U as Xe,i as ue,X as he,B as V,H as Ye,W as Ze,Q as me,I as et,t as tt}from"../packem_shared/tui-prompts-CCt3jm1k.mjs";import{l as ge,u as at,p as rt,b as ot,a as st,m as it,n as nt,f as ve,q as fe,h as lt}from"../packem_shared/storage-CSzKwh4L.mjs";import{logStep as J}from"../packem_shared/createLogger--C3x1FNE.mjs";import ct from"node:dns/promises";const z={bun:{githubCacheKey:void 0,githubSetupStep:` - uses: oven-sh/setup-bun@v2
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"}},$=(e,t)=>{const a=Ve(e,"lunora",t);return[a.command,...a.args].join(" ")},Q=e=>` - uses: actions/checkout@v4
4
+ ${e.githubSetupStep} - uses: actions/setup-node@v4
5
+ with:
6
+ node-version: 22
7
+ ${e.githubCacheKey===void 0?"":` cache: ${e.githubCacheKey}
8
+ `} - run: ${e.installCmd}`,dt=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
2
9
 
3
10
  on:
4
11
  push:
@@ -6,8 +13,8 @@ on:
6
13
  pull_request:
7
14
  workflow_dispatch:
8
15
 
9
- # Prerequisite: commit your pnpm-lock.yaml. \`pnpm install --frozen-lockfile\`
10
- # (below) and the pnpm cache both require it — run \`pnpm install\` locally and
16
+ # Prerequisite: commit your ${t.lockfile}. \`${t.installCmd}\`
17
+ ${a}
11
18
  # commit the lockfile before pushing, or the first CI run fails.
12
19
  #
13
20
  # Set these repository secrets (Settings → Secrets and variables → Actions):
@@ -25,16 +32,10 @@ jobs:
25
32
  permissions:
26
33
  contents: read
27
34
  steps:
28
- - uses: actions/checkout@v4
29
- - uses: pnpm/action-setup@v4
30
- - uses: actions/setup-node@v4
31
- with:
32
- node-version: 22
33
- cache: pnpm
34
- - run: pnpm install --frozen-lockfile
35
+ ${Q(t)}
35
36
  # Codegen + wrangler validation gate (no deploy) — fails fast on drift.
36
- - run: pnpm exec lunora prepare
37
- - run: pnpm exec lunora deploy
37
+ - run: ${$(e,["prepare"])}
38
+ - run: ${$(e,["deploy"])}
38
39
 
39
40
  # Preview version on every pull request — uploads a versioned preview URL;
40
41
  # production traffic is untouched.
@@ -44,30 +45,24 @@ jobs:
44
45
  permissions:
45
46
  contents: read
46
47
  steps:
47
- - uses: actions/checkout@v4
48
- - uses: pnpm/action-setup@v4
49
- - uses: actions/setup-node@v4
50
- with:
51
- node-version: 22
52
- cache: pnpm
53
- - run: pnpm install --frozen-lockfile
54
- - run: pnpm exec lunora deploy --preview
55
- `,nt=`stages:
48
+ ${Q(t)}
49
+ - run: ${$(e,["deploy","--preview"])}
50
+ `},pt=e=>{const t=z[e],a=[...t.gitlabProvisionScript,t.installCmd].map(r=>` - ${r}`).join(`
51
+ `);return`stages:
56
52
  - deploy
57
53
 
58
- # Prerequisite: commit your pnpm-lock.yaml. \`pnpm install --frozen-lockfile\`
59
- # (below) requires it — run \`pnpm install\` locally and commit the lockfile
54
+ # Prerequisite: commit your ${t.lockfile}. \`${t.installCmd}\`
55
+ # (below) requires it — run \`${e} install\` locally and commit the lockfile
60
56
  # before pushing, or the first pipeline fails.
61
57
  #
62
58
  # Set these as masked CI/CD variables (Settings → CI/CD → Variables):
63
59
  # CLOUDFLARE_API_TOKEN — a Workers-scoped API token
64
60
  # CLOUDFLARE_ACCOUNT_ID — your Cloudflare account id
65
61
  .lunora_base:
66
- image: node:22
62
+ image: ${t.gitlabImage}
67
63
  stage: deploy
68
64
  before_script:
69
- - corepack enable
70
- - pnpm install --frozen-lockfile
65
+ ${a}
71
66
 
72
67
  # Production deploy on the default branch.
73
68
  deploy:
@@ -76,8 +71,8 @@ deploy:
76
71
  - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
77
72
  script:
78
73
  # Codegen + wrangler validation gate (no deploy) — fails fast on drift.
79
- - pnpm exec lunora prepare
80
- - pnpm exec lunora deploy
74
+ - ${$(e,["prepare"])}
75
+ - ${$(e,["deploy"])}
81
76
 
82
77
  # Preview version on every merge request (versioned preview URL; production
83
78
  # traffic is untouched).
@@ -86,17 +81,17 @@ preview:
86
81
  rules:
87
82
  - if: $CI_PIPELINE_SOURCE == "merge_request_event"
88
83
  script:
89
- - pnpm exec lunora deploy --preview
90
- `,me={github:{content:it,file:E(".github","workflows","deploy.yml"),secretsHint:"repository secrets (Settings → Secrets and variables → Actions)"},gitlab:{content:nt,file:".gitlab-ci.yml",secretsHint:"masked CI/CD variables (Settings → CI/CD → Variables)"}},lt=e=>e==="github"||e==="gitlab",ct=(e,t,a={})=>{const r=me[t],o=E(e,r.file);return h(o)&&a.overwrite!==!0?{path:o,skipped:!0,written:!1}:(L(Be(o),{recursive:!0}),m(o,r.content,"utf8"),{path:o,skipped:!1,written:!0})},dt=(e,t,a,r={})=>{const o=me[t];try{const s=ct(e,t,r);return s.skipped?a.info(`--ci ${t}: ${o.file} already exists — left unchanged (re-run with overwrite to replace).`):(a.success(`--ci ${t}: wrote ${o.file}`),a.info(`--ci ${t}: set CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID as ${o.secretsHint} to enable deploys.`),a.info(`--ci ${t}: run \`pnpm install\` and commit pnpm-lock.yaml before pushing — the pipeline runs \`pnpm install --frozen-lockfile\`.`)),s}catch(s){const i=s instanceof Error?s.message:String(s);return a.warn(`--ci ${t}: could not write ${o.file} (${i})`),{path:E(e,o.file),skipped:!1,written:!1}}},pt={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"},ut=e=>{const t=Se(e);return{...t,adapter:pt[t.framework]}},N="lunora()",F='import { lunora } from "@lunora/vite";',ht=/\blunora\s*\(/u,mt='"@lunora/vite"',gt="'@lunora/vite'",vt=e=>{for(const t of e.getStatements()){if(t.getKind()!==v.ExportAssignment)continue;const a=t.asKindOrThrow(v.ExportAssignment).getExpression();if(a.getKind()!==v.CallExpression)continue;const r=a.asKindOrThrow(v.CallExpression);if(r.getExpression().getText()!=="defineConfig")continue;const o=r.getArguments()[0];if(o?.getKind()===v.ObjectLiteralExpression)return o.asKindOrThrow(v.ObjectLiteralExpression)}},ft=e=>{for(const t of e.getStatements()){if(t.getKind()!==v.ExportAssignment)continue;const a=t.asKindOrThrow(v.ExportAssignment).getExpression();if(a.getKind()===v.ObjectLiteralExpression)return a.asKindOrThrow(v.ObjectLiteralExpression)}},wt=e=>{const t=new ae({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}).createSourceFile("vite.config.ts",e,{overwrite:!0});return vt(t)??ft(t)},yt=e=>{const t=new ae({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}).createSourceFile("vite.config.ts",e,{overwrite:!0}).getImportDeclarations();if(t.length===0)return 0;const a=t[t.length-1];return a===void 0?0:a.getEnd()},bt=(e,t)=>{const a=yt(t);a===0?e.prepend(`${F}
84
+ - ${$(e,["deploy","--preview"])}
85
+ `},we={github:{file:P(".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)"}},ut=(e,t)=>e==="github"?dt(t):pt(t),ht=e=>e==="github"||e==="gitlab",mt=(e,t,a,r={})=>{const o=P(e,we[t].file);return h(o)&&r.overwrite!==!0?{path:o,skipped:!0,written:!1}:(S(Ue(o),{recursive:!0}),m(o,ut(t,a),"utf8"),{path:o,skipped:!1,written:!0})},gt=(e,t,a,r,o={})=>{const s=we[t];try{const i=mt(e,t,a,o);if(i.skipped)r.info(`--ci ${t}: ${s.file} already exists — left unchanged (re-run with overwrite to replace).`);else{const n=se(a),l=[n.command,...n.args].join(" "),{installCmd:d,lockfile:u}=z[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 ${u} before pushing — the pipeline runs \`${d}\`.`)}return i}catch(i){const n=i instanceof Error?i.message:String(i);return r.warn(`--ci ${t}: could not write ${s.file} (${n})`),{path:P(e,s.file),skipped:!1,written:!1}}},vt={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"},ft=e=>{const t=_e(e);return{...t,adapter:vt[t.framework]}},I="lunora()",G='import { lunora } from "@lunora/vite";',wt=/\blunora\s*\(/u,yt='"@lunora/vite"',bt="'@lunora/vite'",kt=e=>{for(const t of e.getStatements()){if(t.getKind()!==v.ExportAssignment)continue;const a=t.asKindOrThrow(v.ExportAssignment).getExpression();if(a.getKind()!==v.CallExpression)continue;const r=a.asKindOrThrow(v.CallExpression);if(r.getExpression().getText()!=="defineConfig")continue;const o=r.getArguments()[0];if(o?.getKind()===v.ObjectLiteralExpression)return o.asKindOrThrow(v.ObjectLiteralExpression)}},xt=e=>{for(const t of e.getStatements()){if(t.getKind()!==v.ExportAssignment)continue;const a=t.asKindOrThrow(v.ExportAssignment).getExpression();if(a.getKind()===v.ObjectLiteralExpression)return a.asKindOrThrow(v.ObjectLiteralExpression)}},$t=e=>{const t=new ie({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}).createSourceFile("vite.config.ts",e,{overwrite:!0});return kt(t)??xt(t)},Ct=e=>{const t=new ie({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}).createSourceFile("vite.config.ts",e,{overwrite:!0}).getImportDeclarations();if(t.length===0)return 0;const a=t[t.length-1];return a===void 0?0:a.getEnd()},Mt=(e,t)=>{const a=Ct(t);a===0?e.prepend(`${G}
91
86
  `):e.appendLeft(a,`
92
- ${F}`)},xt=(e,t)=>{const a=t.getProperty("plugins");if(a===void 0){const s=t.getProperties(),i=t.getStart()+1;if(s.length===0)e.appendLeft(i,` plugins: [${N}] `);else{const n=s[0];n!==void 0&&e.appendLeft(n.getStart(),`plugins: [${N}],
93
- `)}return}const r=a.getDescendantsOfKind(v.ArrayLiteralExpression)[0];if(r===void 0)return;const o=r.getElements();if(o.length===0)e.appendLeft(r.getStart()+1,N);else{const s=o[0];s!==void 0&&e.appendLeft(s.getStart(),`${N}, `)}},ge=e=>{if(ht.test(e))return{changed:!1,code:e,reason:"lunora plugin already present"};const t=wt(e);if(t===void 0)return{changed:!1,code:e,reason:"could not locate a Vite config plugins array to patch"};const a=new Ue(e);return e.includes(mt)||e.includes(gt)||bt(a,e),xt(a,t),{changed:!0,code:a.toString()}},kt=/enotfound|eai_again|econnrefused|etimedout|network|fetch failed|getaddrinfo/u,$t=/404|not found|could not find|no such/u,Ct=(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 $t.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}`}:kt.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}},_=async(e,t,a)=>{if(g()){await qe(f[e],t,a);return}if(process.stdout.write(`
94
- `),a===void 0||a===""){q(e,t);return}const r=a.split(`
95
- `).map(o=>_e(o)).join(`
96
- `);q(e,`${t}
97
- ${r}`)},Mt=async e=>{if(g()){await We();return}e.info(`
98
- ${Ae}
99
- ${Ne}: ${Ie}`)},ve=[{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"}],K=ve.map(e=>e.value),Lt=e=>e==="email"?pe:e,St=(e,t)=>{const a=[];for(const r of e.split(",").map(o=>o.trim()).filter(Boolean))K.includes(r)?a.includes(r)||a.push(r):t(`init: unknown --add feature "${r}" — expected ${K.join(" | ")}; skipping.`);return a},At=async e=>{const t=await rt(e.select),a=await ue(e.text,e.projectName);return{label:"auth",names:[t],transformManifest:r=>he(r,a)}},Nt=async e=>{const t=await e.text(et,{placeholder:"you@yourdomain.com"}),a=tt(t,r=>{e.logger.warn(r)});return{label:"email",names:[pe],transformManifest:a===void 0?void 0:r=>at(r,a)}},It=async(e,t)=>{const a=e.resolveAuthUiItem?.()??"auth-ui-react";if(t)return{label:"auth-ui",names:[a]};const r=await ue(e.text,e.projectName);return{label:"auth-ui",names:[a],transformManifest:o=>he(o,r)}},_t=async e=>{const t=await Ye(e.text,e.projectName);return{label:"storage",names:["storage"],transformManifest:a=>Ze(a,t)}},Rt={auth:At,"auth-ui":async(e,t)=>It(e,t.includes("auth")),email:Nt,storage:_t},J=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":Lt(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?",ve,{defaults:[]});if(t.length===0)return;const a=[];for(const r of t){const o=Rt[r];a.push(o?await o(e,t):{label:r,names:[r]})}await e.applyAll(a)},A="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",M=`/* The welcome page is a full-bleed starter — reset the browser's default
87
+ ${G}`)},Lt=(e,t)=>{const a=t.getProperty("plugins");if(a===void 0){const s=t.getProperties(),i=t.getStart()+1;if(s.length===0)e.appendLeft(i,` plugins: [${I}] `);else{const n=s[0];n!==void 0&&e.appendLeft(n.getStart(),`plugins: [${I}],
88
+ `)}return}const r=a.getDescendantsOfKind(v.ArrayLiteralExpression)[0];if(r===void 0)return;const o=r.getElements();if(o.length===0)e.appendLeft(r.getStart()+1,I);else{const s=o[0];s!==void 0&&e.appendLeft(s.getStart(),`${I}, `)}},ye=e=>{if(wt.test(e))return{changed:!1,code:e,reason:"lunora plugin already present"};const t=$t(e);if(t===void 0)return{changed:!1,code:e,reason:"could not locate a Vite config plugins array to patch"};const a=new qe(e);return e.includes(yt)||e.includes(bt)||Mt(a,e),Lt(a,t),{changed:!0,code:a.toString()}},St=/enotfound|eai_again|econnrefused|etimedout|network|fetch failed|getaddrinfo/u,At=/404|not found|could not find|no such/u,Nt=(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 At.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}`}:St.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 Qe(f[e],t,a);return}if(process.stdout.write(`
89
+ `),a===void 0||a===""){J(e,t);return}const r=a.split(`
90
+ `).map(o=>Oe(o)).join(`
91
+ `);J(e,`${t}
92
+ ${r}`)},It=async e=>{if(g()){await Je();return}e.info(`
93
+ ${Re}
94
+ ${Te}: ${je}`)},be=[{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=be.map(e=>e.value),_t=e=>e==="email"?ge:e,Rt=(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},Tt=async e=>{const t=await nt(e.select),a=await ve(e.text,e.projectName);return{label:"auth",names:[t],transformManifest:r=>fe(r,a)}},jt=async e=>{const t=await e.text(ot,{placeholder:"you@yourdomain.com"}),a=st(t,r=>{e.logger.warn(r)});return{label:"email",names:[ge],transformManifest:a===void 0?void 0:r=>it(r,a)}},Ot=async(e,t)=>{const a=e.resolveAuthUiItem?.()??"auth-ui-react";if(t)return{label:"auth-ui",names:[a]};const r=await ve(e.text,e.projectName);return{label:"auth-ui",names:[a],transformManifest:o=>fe(o,r)}},Bt=async e=>{const t=await at(e.text,e.projectName);return{label:"storage",names:["storage"],transformManifest:a=>rt(a,t)}},Et={auth:Tt,"auth-ui":async(e,t)=>Ot(e,t.includes("auth")),email:jt,storage:Bt},Y=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":_t(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?",be,{defaults:[]});if(t.length===0)return;const a=[];for(const r of t){const o=Et[r];a.push(o?await o(e,t):{label:r,names:[r]})}await e.applyAll(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
100
95
  body margin/padding so it sits flush; everything else is scoped under
101
96
  .lunora-welcome (collision-safe). */
102
97
  body {
@@ -201,7 +196,7 @@ body {
201
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); }
202
197
 
203
198
  @media (prefers-reduced-motion: reduce) { .lunora-welcome * { transition: none !important; } }
204
- `,Tt=`import { useEffect, useState } from "react";
199
+ `,Pt=`import { useEffect, useState } from "react";
205
200
 
206
201
  type Theme = "dark" | "light";
207
202
 
@@ -243,7 +238,7 @@ export default function App() {
243
238
  <div className="lw-wrap">
244
239
  <div className="brand">
245
240
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
246
- <path d="${A}" fill="currentColor" fillRule="evenodd" />
241
+ <path d="${N}" fill="currentColor" fillRule="evenodd" />
247
242
  </svg>
248
243
  <span className="word">Lunora</span>
249
244
  </div>
@@ -362,7 +357,7 @@ export default function App() {
362
357
  </div>
363
358
  );
364
359
  }
365
- `,Ot=`<script setup lang="ts">
360
+ `,Dt=`<script setup lang="ts">
366
361
  import { onMounted, ref } from "vue";
367
362
 
368
363
  // Default to "dark" for a stable first paint, then reconcile to the OS
@@ -402,7 +397,7 @@ const toggle = (): void => {
402
397
  <div class="lw-wrap">
403
398
  <div class="brand">
404
399
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
405
- <path d="${A}" fill="currentColor" fill-rule="evenodd" />
400
+ <path d="${N}" fill="currentColor" fill-rule="evenodd" />
406
401
  </svg>
407
402
  <span class="word">Lunora</span>
408
403
  </div>
@@ -518,7 +513,7 @@ const toggle = (): void => {
518
513
  </div>
519
514
  </div>
520
515
  </template>
521
- `,jt=`import { createSignal, onMount } from "solid-js";
516
+ `,Ut=`import { createSignal, onMount } from "solid-js";
522
517
 
523
518
  export default function App() {
524
519
  // Default to "dark" for a stable first paint, then reconcile to the OS
@@ -558,7 +553,7 @@ export default function App() {
558
553
  <div class="lw-wrap">
559
554
  <div class="brand">
560
555
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
561
- <path d="${A}" fill="currentColor" fill-rule="evenodd" />
556
+ <path d="${N}" fill="currentColor" fill-rule="evenodd" />
562
557
  </svg>
563
558
  <span class="word">Lunora</span>
564
559
  </div>
@@ -677,7 +672,7 @@ export default function App() {
677
672
  </div>
678
673
  );
679
674
  }
680
- `,Bt=`<script lang="ts">
675
+ `,Vt=`<script lang="ts">
681
676
  import { onMount } from "svelte";
682
677
 
683
678
  // Default to "dark" for a stable first paint, then reconcile to the OS
@@ -720,7 +715,7 @@ export default function App() {
720
715
  <div class="lw-wrap">
721
716
  <div class="brand">
722
717
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
723
- <path d="${A}" fill="currentColor" fill-rule="evenodd" />
718
+ <path d="${N}" fill="currentColor" fill-rule="evenodd" />
724
719
  </svg>
725
720
  <span class="word">Lunora</span>
726
721
  </div>
@@ -835,7 +830,7 @@ export default function App() {
835
830
  <div class="lw-foot">Running on Lunora · Vite + Svelte</div>
836
831
  </div>
837
832
  </div>
838
- `,Et=`import "./style.css";
833
+ `,zt=`import "./style.css";
839
834
 
840
835
  import { LunoraClient } from "lunorash/client";
841
836
 
@@ -863,7 +858,7 @@ const welcomeHtml = \`
863
858
  <div class="lw-wrap">
864
859
  <div class="brand">
865
860
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
866
- <path d="${A}" fill="currentColor" fill-rule="evenodd" />
861
+ <path d="${N}" fill="currentColor" fill-rule="evenodd" />
867
862
  </svg>
868
863
  <span class="word">Lunora</span>
869
864
  </div>
@@ -1002,7 +997,7 @@ const count = document.querySelector<HTMLSpanElement>("#lw-count")!;
1002
997
  client.onUpdate(api.messages.list, { channelId: "channel:demo" }, (result) => {
1003
998
  count.textContent = String(result.messages.length);
1004
999
  });
1005
- `,R="const url = (import.meta.env.VITE_LUNORA_URL as string | undefined) ?? globalThis.location.origin;",Pt=`import "./index.css";
1000
+ `,T="const url = (import.meta.env.VITE_LUNORA_URL as string | undefined) ?? globalThis.location.origin;",Ht=`import "./index.css";
1006
1001
 
1007
1002
  import { LunoraProvider } from "@lunora/react";
1008
1003
  import { LunoraClient } from "lunorash/client";
@@ -1014,7 +1009,7 @@ import App from "./App.tsx";
1014
1009
  // \`@lunora/vite\` runs the Worker on the same origin as Vite, so default to
1015
1010
  // \`location.origin\`. Point \`VITE_LUNORA_URL\` at a deployed Worker to develop
1016
1011
  // the client against production data.
1017
- ${R}
1012
+ ${T}
1018
1013
  const client = new LunoraClient({ url });
1019
1014
 
1020
1015
  const root = document.getElementById("root");
@@ -1030,7 +1025,7 @@ createRoot(root).render(
1030
1025
  </LunoraProvider>
1031
1026
  </StrictMode>,
1032
1027
  );
1033
- `,Dt=`import "./style.css";
1028
+ `,Wt=`import "./style.css";
1034
1029
 
1035
1030
  import { createLunora } from "@lunora/vue";
1036
1031
  import { LunoraClient } from "lunorash/client";
@@ -1039,9 +1034,9 @@ import { createApp } from "vue";
1039
1034
  import App from "./App.vue";
1040
1035
 
1041
1036
  // Provide one LunoraClient at the app root via the Vue plugin form.
1042
- ${R}
1037
+ ${T}
1043
1038
  createApp(App).use(createLunora(new LunoraClient({ url }))).mount("#app");
1044
- `,zt=`import "./index.css";
1039
+ `,qt=`import "./index.css";
1045
1040
 
1046
1041
  import { LunoraContext } from "@lunora/solid";
1047
1042
  import { LunoraClient } from "lunorash/client";
@@ -1049,7 +1044,7 @@ import { render } from "solid-js/web";
1049
1044
 
1050
1045
  import App from "./App";
1051
1046
 
1052
- ${R}
1047
+ ${T}
1053
1048
  const client = new LunoraClient({ url });
1054
1049
  const root = document.getElementById("root");
1055
1050
 
@@ -1061,18 +1056,18 @@ render(
1061
1056
  ),
1062
1057
  root!,
1063
1058
  );
1064
- `,Ut=`<script lang="ts">
1059
+ `,Ft=`<script lang="ts">
1065
1060
  import { setLunoraClient } from "@lunora/svelte";
1066
1061
  import { LunoraClient } from "lunorash/client";
1067
1062
 
1068
1063
  import App from "./App.svelte";
1069
1064
 
1070
- ${R}
1065
+ ${T}
1071
1066
  setLunoraClient(new LunoraClient({ url }));
1072
1067
  <\/script>
1073
1068
 
1074
1069
  <App />
1075
- `,Vt=`import "./app.css";
1070
+ `,Kt=`import "./app.css";
1076
1071
 
1077
1072
  import { mount } from "svelte";
1078
1073
 
@@ -1082,7 +1077,7 @@ import Root from "./Root.svelte";
1082
1077
  const app = mount(Root, { target: document.getElementById("app")! });
1083
1078
 
1084
1079
  export default app;
1085
- `,T={react:{adapter:"@lunora/react",createViteTemplate:"react-ts",files:[{contents:Pt,path:"src/main.tsx"},{contents:Tt,path:"src/App.tsx"},{contents:M,path:"src/index.css"}],label:"React"},solid:{adapter:"@lunora/solid",createViteTemplate:"solid-ts",files:[{contents:zt,path:"src/index.tsx"},{contents:jt,path:"src/App.tsx"},{contents:M,path:"src/index.css"}],label:"Solid"},svelte:{adapter:"@lunora/svelte",createViteTemplate:"svelte-ts",files:[{contents:Ut,path:"src/Root.svelte"},{contents:Vt,path:"src/main.ts"},{contents:Bt,path:"src/App.svelte"},{contents:M,path:"src/app.css"}],label:"Svelte"},vanilla:{adapter:"lunorash/client",createViteTemplate:"vanilla-ts",files:[{contents:Et,path:"src/main.ts"},{contents:M,path:"src/style.css"}],label:"Vanilla"},vue:{adapter:"@lunora/vue",createViteTemplate:"vue-ts",files:[{contents:Dt,path:"src/main.ts"},{contents:Ot,path:"src/App.vue"},{contents:M,path:"src/style.css"}],label:"Vue"}},z=e=>Object.hasOwn(T,e),Ht=`import type { Middleware } from "lunorash/server";
1080
+ `,j={react:{adapter:"@lunora/react",createViteTemplate:"react-ts",files:[{contents:Ht,path:"src/main.tsx"},{contents:Pt,path:"src/App.tsx"},{contents:L,path:"src/index.css"}],label:"React"},solid:{adapter:"@lunora/solid",createViteTemplate:"solid-ts",files:[{contents:qt,path:"src/index.tsx"},{contents:Ut,path:"src/App.tsx"},{contents:L,path:"src/index.css"}],label:"Solid"},svelte:{adapter:"@lunora/svelte",createViteTemplate:"svelte-ts",files:[{contents:Ft,path:"src/Root.svelte"},{contents:Kt,path:"src/main.ts"},{contents:Vt,path:"src/App.svelte"},{contents:L,path:"src/app.css"}],label:"Svelte"},vanilla:{adapter:"lunorash/client",createViteTemplate:"vanilla-ts",files:[{contents:zt,path:"src/main.ts"},{contents:L,path:"src/style.css"}],label:"Vanilla"},vue:{adapter:"@lunora/vue",createViteTemplate:"vue-ts",files:[{contents:Wt,path:"src/main.ts"},{contents:Dt,path:"src/App.vue"},{contents:L,path:"src/style.css"}],label:"Vue"}},H=e=>Object.hasOwn(j,e),Jt=`import type { Middleware } from "lunorash/server";
1086
1081
  import { defineSchemaExtension, defineTable, definePlugin, v } from "lunorash/server";
1087
1082
  import { createDbStore, RateLimiter } from "lunorash/ratelimit";
1088
1083
  import type { RateLimitConfigMap } from "lunorash/ratelimit";
@@ -1122,7 +1117,7 @@ export const ratelimit = definePlugin("ratelimit", {
1122
1117
  }),
1123
1118
  middleware,
1124
1119
  });
1125
- `,Wt=`import { ratelimit } from "./ratelimit/schema.js";
1120
+ `,Qt=`import { ratelimit } from "./ratelimit/schema.js";
1126
1121
  import { defineSchema, defineTable, v } from "lunorash/server";
1127
1122
 
1128
1123
  export default defineSchema({
@@ -1133,7 +1128,7 @@ export default defineSchema({
1133
1128
  .shardBy("channelId")
1134
1129
  .index("by_channel", ["channelId"]),
1135
1130
  }).extend(ratelimit.extension);
1136
- `,qt=`import { RateLimiter, rateLimit, createDbStore } from "lunorash/ratelimit";
1131
+ `,Gt=`import { RateLimiter, rateLimit, createDbStore } from "lunorash/ratelimit";
1137
1132
 
1138
1133
  import { mutation, query, v } from "#lunora/_generated/server.js";
1139
1134
 
@@ -1161,7 +1156,7 @@ export const send = mutation
1161
1156
 
1162
1157
  return { channelId: args.channelId, id, text: args.text };
1163
1158
  });
1164
- `,Ft=`import type { ShardNamespaceLike } from "lunorash/runtime";
1159
+ `,Xt=`import type { ShardNamespaceLike } from "lunorash/runtime";
1165
1160
 
1166
1161
  import { defineApp } from "../lunora/_generated/app.js";
1167
1162
 
@@ -1175,7 +1170,7 @@ const app = defineApp<Env>()
1175
1170
 
1176
1171
  export const ShardDO = app.ShardDO;
1177
1172
  export default app;
1178
- `,Kt=`{
1173
+ `,Yt=`{
1179
1174
  "$schema": "node_modules/wrangler/config-schema.json",
1180
1175
  "name": "__NAME__",
1181
1176
  "main": "src/server.ts",
@@ -1187,23 +1182,23 @@ export default app;
1187
1182
  "migrations": [{ "tag": "v1", "new_sqlite_classes": ["ShardDO"] }],
1188
1183
  "observability": { "enabled": true, "head_sampling_rate": 1 },
1189
1184
  }
1190
- `,Jt=[".wrangler",".env",".env.*","!.env.example",".dev.vars",".dev.vars.*","!.dev.vars.example",".lunora/",".lunora-cache","lunora/_generated"],Qt=`# Lunora endpoint for the browser client.
1185
+ `,Zt=[".wrangler",".env",".env.*","!.env.example",".dev.vars",".dev.vars.*","!.dev.vars.example",".lunora/",".lunora-cache","lunora/_generated"],ea=`# Lunora endpoint for the browser client.
1191
1186
  # Vite statically replaces \`import.meta.env.VITE_LUNORA_URL\` at \`vite dev\` / build.
1192
1187
  # Leave it unset to use the page origin; set it to point at a deployed Worker:
1193
1188
  #
1194
1189
  # VITE_LUNORA_URL=https://my-app.example.workers.dev
1195
- `,Gt={"@cloudflare/workers-types":"^4.20260611.1",wrangler:"^4.100.0"},x=(e,t,a,r)=>{const o=p(e,t);L($(o),{recursive:!0}),m(o,a,"utf8"),r.push(o)},Xt=/\r?\n/,Yt=e=>{const t=p(e,".gitignore"),a=h(t)?b(t,"utf8"):"",r=Jt.filter(s=>!a.split(Xt).includes(s));if(r.length===0)return;const o=a.length>0&&!a.endsWith(`
1190
+ `,ta={"@cloudflare/workers-types":"^4.20260611.1",wrangler:"^4.100.0"},k=(e,t,a,r)=>{const o=p(e,t);S(C(o),{recursive:!0}),m(o,a,"utf8"),r.push(o)},aa=/\r?\n/,ra=e=>{const t=p(e,".gitignore"),a=h(t)?b(t,"utf8"):"",r=Zt.filter(s=>!a.split(aa).includes(s));if(r.length===0)return;const o=a.length>0&&!a.endsWith(`
1196
1191
  `)?`
1197
1192
  `:"";m(t,`${a}${o}
1198
1193
  # Lunora
1199
1194
  ${r.join(`
1200
1195
  `)}
1201
- `,"utf8")},fe=e=>e==="lunorash"||e.startsWith("@lunora/"),we=(e,t,a,r)=>fe(e)?r?.get(e)??a:t,k=(e,t,a,r)=>({...e,[t]:we(t,a,r)}),Q=(e,t,a)=>Object.fromEntries(Object.entries(e).map(([r,o])=>[r,we(r,o,t,a)])),Zt=async(e,t,a,r)=>{const o=p(e,"package.json"),s=JSON.parse(b(o,"utf8"));let i=k(s.dependencies??{},"lunorash",r,r);i=k(i,"@lunora/ratelimit",r,r),a.adapter.startsWith("@lunora/")&&(i=k(i,a.adapter,r,r));for(const[u,l]of Object.entries(a.extraDependencies??{}))i=k(i,u,l,r);let n=k(s.devDependencies??{},"@lunora/vite",r,r);n=k(n,"@lunora/studio",r,r);for(const[u,l]of Object.entries(Gt))n=k(n,u,l,r);const c=[...Object.keys(i),...Object.keys(n)].filter(u=>fe(u)),d=await re(c,r);s.name=t,s.imports={...s.imports,"#lunora/*":"./lunora/*"},s.dependencies=Q(i,r,d),s.devDependencies=Q(n,r,d),s.scripts={...s.scripts,codegen:"lunora codegen",deploy:"vite build && lunora deploy"},m(o,`${JSON.stringify(s,void 0,4)}
1202
- `,"utf8")},ea=(e,t)=>{const a=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"].map(o=>p(e,o)).find(o=>h(o));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=ge(b(a,"utf8"));r.changed&&m(a,r.code,"utf8")},ta=async e=>{const{adapter:t,distTag:a,logger:r,name:o,target:s}=e,i=[];x(s,p("lunora","ratelimit","schema.ts"),Ht,i),x(s,p("lunora","schema.ts"),Wt,i),x(s,p("lunora","messages.ts"),qt,i),x(s,p("src","server.ts"),Ft,i),x(s,"wrangler.jsonc",Kt.replaceAll("__NAME__",o),i),x(s,".env.example",Qt,i);for(const n of t.files)x(s,n.path,n.contents,i);return ea(s,r),await Zt(s,o,t,a),Yt(s),i},aa=["lunar","silver","silent","waning","waxing","crescent","cosmic","stellar","orbital","gibbous","twilight","midnight","shimmering","drifting","weightless"],ra=["moon","tide","crater","comet","eclipse","halo","orbit","nebula","voyager","lander","rover","beacon","harbor","meadow","fox"],G=e=>e[Math.floor(Math.random()*e.length)],oa=()=>`${G(aa)}-${G(ra)}`,sa=async()=>st.lookup("github.com").then(()=>!0,()=>!1),ia=/^(?:gh|github):([^/]+)\/([^#/]+)(?:\/[^#]*)?(?:#(.+))?$/,ye=e=>{const t=ia.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=ye(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}},be=async e=>e.isLocal||!(e.source===void 0||ye(e.source)!==void 0)?!0:await sa()?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?"},la=new Set([".gitignore",".html",".js",".json",".jsonc",".md",".mjs",".ts",".tsx"]),ca=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],da=`import { defineConfig } from "vite";
1196
+ `,"utf8")},ke=e=>e==="lunorash"||e.startsWith("@lunora/"),xe=(e,t,a,r)=>ke(e)?r?.get(e)??a:t,x=(e,t,a,r)=>({...e,[t]:xe(t,a,r)}),Z=(e,t,a)=>Object.fromEntries(Object.entries(e).map(([r,o])=>[r,xe(r,o,t,a)])),oa=async(e,t,a,r)=>{const o=p(e,"package.json"),s=JSON.parse(b(o,"utf8"));let i=x(s.dependencies??{},"lunorash",r,r);i=x(i,"@lunora/ratelimit",r,r),a.adapter.startsWith("@lunora/")&&(i=x(i,a.adapter,r,r));for(const[u,c]of Object.entries(a.extraDependencies??{}))i=x(i,u,c,r);let n=x(s.devDependencies??{},"@lunora/vite",r,r);n=x(n,"@lunora/studio",r,r);for(const[u,c]of Object.entries(ta))n=x(n,u,c,r);const l=[...Object.keys(i),...Object.keys(n)].filter(u=>ke(u)),d=await ne(l,r);s.name=t,s.imports={...s.imports,"#lunora/*":"./lunora/*"},s.dependencies=Z(i,r,d),s.devDependencies=Z(n,r,d),s.scripts={...s.scripts,codegen:"lunora codegen",deploy:"vite build && lunora deploy"},m(o,`${JSON.stringify(s,void 0,4)}
1197
+ `,"utf8")},sa=(e,t)=>{const a=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"].map(o=>p(e,o)).find(o=>h(o));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=ye(b(a,"utf8"));r.changed&&m(a,r.code,"utf8")},ia=async e=>{const{adapter:t,distTag:a,logger:r,name:o,target:s}=e,i=[];k(s,p("lunora","ratelimit","schema.ts"),Jt,i),k(s,p("lunora","schema.ts"),Qt,i),k(s,p("lunora","messages.ts"),Gt,i),k(s,p("src","server.ts"),Xt,i),k(s,"wrangler.jsonc",Yt.replaceAll("__NAME__",o),i),k(s,".env.example",ea,i);for(const n of t.files)k(s,n.path,n.contents,i);return sa(s,r),await oa(s,o,t,a),ra(s),i},na=["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)],ca=()=>`${ee(na)}-${ee(la)}`,da=async()=>ct.lookup("github.com").then(()=>!0,()=>!1),pa=/^(?:gh|github):([^/]+)\/([^#/]+)(?:\/[^#]*)?(?:#(.+))?$/,$e=e=>{const t=pa.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}},ua=async e=>{const t=$e(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}},Ce=async e=>e.isLocal||!(e.source===void 0||$e(e.source)!==void 0)?!0:await da()?e.source!==void 0&&await ua(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?"},ha=new Set([".gitignore",".html",".js",".json",".jsonc",".md",".mjs",".ts",".tsx"]),ma=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],ga=`import { defineConfig } from "vite";
1203
1198
  import { lunora } from "@lunora/vite";
1204
1199
 
1205
1200
  export default defineConfig({ plugins: [lunora()] });
1206
- `,pa=`import { defineSchema, defineTable, v } from "@lunora/server";
1201
+ `,va=`import { defineSchema, defineTable, v } from "@lunora/server";
1207
1202
 
1208
1203
  export default defineSchema({
1209
1204
  messages: defineTable({
@@ -1213,7 +1208,7 @@ export default defineSchema({
1213
1208
  .shardBy("channelId")
1214
1209
  .index("by_channel", ["channelId"]),
1215
1210
  });
1216
- `,ua=`import { mutation, query, v } from "./_generated/server";
1211
+ `,fa=`import { mutation, query, v } from "./_generated/server";
1217
1212
 
1218
1213
  export const list = query
1219
1214
  .input({ channelId: v.id("channels"), limit: v.optional(v.number()) })
@@ -1226,8 +1221,8 @@ export const send = mutation
1226
1221
  .mutation(async ({ args }) => {
1227
1222
  return { channelId: args.channelId, text: args.text };
1228
1223
  });
1229
- `,ha="gh:anolilab/lunora/templates",ma=e=>{const t=e.lastIndexOf(".");return t===-1?!1:la.has(e.slice(t))},ga=(e,t)=>e.replaceAll("{{name}}",t),xe=e=>e==="lunorash"||e.startsWith("@lunora/"),va=async(e,t)=>{const a=new Set;for(const r of e)if(S(r)==="package.json")try{const o=JSON.parse(b(r,"utf8"));for(const s of["dependencies","devDependencies"])for(const i of Object.keys(o[s]??{}))xe(i)&&a.add(i)}catch{}return re(a,t)},fa=(e,t,a)=>{let r;try{r=JSON.parse(e)}catch{return e}let o=e;for(const s of["dependencies","devDependencies"])for(const i of Object.keys(r[s]??{})){if(!xe(i))continue;const n=a.get(i)??t,c=Oe(o,[s,i],n,{formattingOptions:{insertSpaces:!0,tabSize:4}});o=je(o,c)}return o},wa=["@parcel/watcher","esbuild","lmdb","msgpackr-extract","rs-module-lexer","sharp","unrs-resolver","vue-demi","workerd"],ya=["cpu-features","protobufjs","ssh2"],ba="pnpm-workspace.yaml",xa=()=>["# 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:",...wa.map(e=>` '${e}': true`),...ya.map(e=>` '${e}': false`),""].join(`
1230
- `),U=e=>{const t=[];for(const a of Re(e,{includeDirs:!1,includeFiles:!0}))Me(a.path).isSymbolicLink()||t.push(a.path);return t},ke=async(e,t,a)=>{const r=U(e),o=[],s=se(),i=await va(r,s);for(const n of r){const c=Te(e,n),d=p(t,c);L($(d),{recursive:!0});const u=b(n);let l=ma(n)?ga(u.toString("utf8"),a):void 0;l!==void 0&&S(n)==="package.json"&&(l=fa(l,s,i)),l===void 0?m(d,u):m(d,l,"utf8"),o.push(d)}return o},j=(e,t,a)=>t!==void 0&&t.length>0?t:`${ha}/${e}#${oe(a)}`,ka=e=>e.includes("..")?!1:e.startsWith("gh:")||e.startsWith("github:")||e.startsWith("https://"),C=(e,t)=>{e.info(`[dry-run] would ${t}`)},V=(e,t,a)=>{g()&&process.stdout.write(`
1231
- `),e.success(`scaffolded ${String(t.length)} files into ${a}`)},$a=(e,t)=>`${e} ${e==="npm"?"install":"add"} ${t.join(" ")}`,$e=e=>{let t=B(e);for(;;){if(h(p(t,"pnpm-workspace.yaml")))return!0;const a=p(t,"package.json");if(h(a))try{if(JSON.parse(b(a,"utf8")).workspaces!==void 0)return!0}catch{}const r=$(t);if(r===t)return!1;t=r}},Ca=e=>{let t=B(e);for(;;){if(h(p(t,".git")))return!0;const a=$(t);if(a===t)return!1;t=a}},Ma=async(e,t)=>{if(e.yes===!0||!g()||Ca($(t)))return;if(!await le(y.git,{badge:f.git,defaultYes:!1})){await ce("Sounds good! You can always run git init manually.");return}if(e.dryRun===!0){C(e.logger,"initialize a git repository");return}const a=e.spawner??ie;(await Je("Initializing a git repository…",()=>a({args:["init"],command:"git",cwd:t}))).code===0?await _("git","Initialized an empty git repository."):e.logger.warn("`git init` failed — initialize it yourself later with `git init`.")},La=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:ze(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 Qe(f.next,y.nextHeader,o,s);return}const i=o.map(n=>`${n.lead} ${n.code}${n.tail??""}`);i.push("",...s.map(n=>`${n.lead} ${n.code}${n.tail??""}`)),await _("next",y.nextHeader,i.join(`
1232
- `))},Sa=e=>e.yes!==!0&&(e.installPrompt!==void 0||g()),Aa=async(e,t)=>{if(!Sa(e)||$e($(t)))return;const a=Pe(e.packageManagerProbe),[r]=a;if(r===void 0)return;if(!await(e.installPrompt?.confirmInstall??(async()=>le(y.install,{badge:f.deps,defaultYes:!0})))()){await ce("No problem! Remember to install dependencies after setup.");return}let o=r;if(a.length>1&&(o=e.installPrompt?await e.installPrompt.selectManager(a):await D(y.packageManager,a.map(d=>({label:d,value:d})),{badge:f.deps,default:r})??r),e.dryRun===!0){C(e.logger,`install dependencies with ${o}`);return}if(o==="pnpm"){const d=p(t,ba);h(d)||m(d,xa(),"utf8")}const s=e.spawner??ie,{args:i,command:n}=De(o);await _("deps",`Installing dependencies with ${o}…`);const c=await s({args:i,command:n,cwd:t});if(c.code!==0){e.logger.warn(`\`${n} install\` exited with code ${String(c.code)} — run it yourself in ${S(t)}/.`);return}return await _("deps",`Dependencies installed with ${o}.`),o},Na=async(e,t,a,r,o)=>{const s=p(e,t);if(!h(s))return o.error(`template not found in local source: ${s}`),{code:1,files:[],target:a};const i=await ke(s,a,r);return V(o,i,a),{code:0,files:i,target:a}},Ia=async e=>{const{logger:t,name:a,ref:r,source:o,target:s,templateType:i}=e,n=Y(p(Z(),"lunora-init-fetch-")),c=p(n,"template");try{const d=o!==void 0&&o.length>0?r:await Ve(r,t),u=j(i,o,d);let l,w=[];await de([{label:`${i} template fetched`,run:async()=>{l=await ee(u,{cwd:n,dir:c,force:!0,install:!1,silent:!0})}},{label:`files copied into ${a}/`,run:async()=>{w=await ke(c,s,a)}}],{end:"Project initialized!",start:"Project initializing…"});const H=U(c);return g()&&process.stdout.write(`
1233
- `),t.info(l?.commit?`template: ${l.source} @ ${l.commit} (${String(H.length)} files)`:`template: ${l?.source??u} (${String(H.length)} files)`),V(t,w,s),{code:0,files:w,target:s}}catch(d){if(d instanceof P)throw d;const{hints:u,message:l}=Ct(d,{ref:oe(r),remote:j(i,o,r),templateType:i});t.error(l);for(const w of u)t.warn(w);return{code:1,files:[],target:s}}finally{I(n,{force:!0,recursive:!0})}},_a=e=>{for(const t of["_gitignore","_npmrc","_gitattributes"]){const a=p(e,t);h(a)&&Le(a,p(e,`.${t.slice(1)}`))}},Ra=async e=>{const{framework:t,logger:a,name:r,overlayBaseFrom:o,target:s}=e,i=T[t],n=Y(p(Z(),"lunora-vite-base-"));try{let c;if(o!==void 0&&(c=p(o,`template-${i.createViteTemplate}`),!h(c)))return a.error(`create-vite base not found on disk: ${c}`),{code:1,files:[],target:s};const d=async()=>{if(c!==void 0){W(c,s,{recursive:!0});return}const l=p(n,"base"),w=`github:vitejs/vite/packages/create-vite/template-${i.createViteTemplate}#main`;await ee(w,{cwd:n,dir:l,force:!0,install:!1,silent:!0}),_a(l),W(l,s,{recursive:!0})};let u=[];return await de([{label:`create-vite (${i.label}) base ready`,run:d},{label:`Lunora overlay applied (${i.label})`,run:async()=>{u=await ta({adapter:i,distTag:se(),logger:a,name:r,target:s})}}],{end:"Project initialized!",start:"Project initializing…"}),V(a,u,s),{code:0,files:[...U(s)],target:s}}catch(c){if(c instanceof P)throw c;const d=c instanceof Error?c.message:String(c);return a.error(`failed to scaffold the ${i.label} base: ${d}`),{code:1,files:[],target:s}}finally{I(n,{force:!0,recursive:!0})}},Ta=(e,t)=>{const a=p(e,"vite.config.ts");try{m(a,da,"utf8")}catch(r){const o=r instanceof Error?r.message:String(r);return t.error(`init --in-place: could not write ${a}: ${o}`),{code:1,files:[],target:e}}return t.success(`created ${a} with lunora() plugin`),{code:0,files:[a],target:e}},Oa=(e,t,a)=>{let r;try{r=b(e,"utf8")}catch(s){const i=s instanceof Error?s.message:String(s);return a.error(`init --in-place: could not read ${e}: ${i}`),{code:1,files:[],target:t}}const o=ge(r);if(!o.changed)return a.info(`${e}: ${o.reason??"no changes needed"}`),{code:0,files:[],target:t};try{m(e,o.code,"utf8")}catch(s){const i=s instanceof Error?s.message:String(s);return a.error(`init --in-place: could not write ${e}: ${i}`),{code:1,files:[],target:t}}return a.success(`patched ${e} — added lunora() plugin`),{code:0,files:[e],target:t}},ja=(e,t)=>{const a=p(e,"lunora"),r=p(a,"schema.ts");if(h(r))return t.info(`lunora/ already present — left ${r} untouched`),[];const o=[];try{L(a,{recursive:!0}),m(r,pa,"utf8"),o.push(r);const s=p(a,"messages.ts");h(s)||(m(s,ua,"utf8"),o.push(s)),t.success(`scaffolded lunora/ (${String(o.length)} file(s))`)}catch(s){const i=s instanceof Error?s.message:String(s);t.error(`init --here: could not scaffold lunora/: ${i}`)}return o},Ba=(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: ${$a(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("")},Ea=e=>{for(const t of ca){const a=p(e,t);if(h(a))return a}},Pa=(e,t,a)=>{const r=Ea(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}):Ta(e,a):Oa(r,e,a)},Da=(e,t)=>{const a=ut(e),r=Pa(e,a.framework,t);if(r.code!==0)return r;const o=ja(e,t);return Ba(a,te(e),t),{code:0,files:[...r.files,...o],target:e}},za=e=>e.yes!==!0&&(e.prompt!==void 0||(e.interactive??g())),Ua=async(e,t)=>{const a=za(e),r=e.add===void 0?[]:St(e.add,s=>{e.logger.warn(s)}),o={applyAll:async s=>{if(s.length===0)return!0;if(e.dryRun===!0)return C(e.logger,`add ${s.map(l=>l.label).join(", ")}`),!0;const i=[],n=g()?{error:l=>{i.push({level:"error",message:l})},info:()=>{},success:()=>{},warn:l=>{i.push({level:"warn",message:l})}}:e.logger,c=s.map(l=>({running:`adding ${l.label}…`,task:()=>He({allowUnsafeSource:e.allowUnsafeSource,cwd:t,from:e.registryFrom,logger:n,names:[...l.names],ref:e.ref,source:e.registrySource,transformManifest:l.transformManifest,yes:!0})})),d=`added ${s.map(l=>l.label).join(", ")}`,u=await Xe(f.add,c,d);for(const{level:l,message:w}of i)e.logger[l](w);return u.every(l=>l.code===0)},interactive:a,logger:e.logger,multiSelect:e.prompt?.multiSelect??((s,i,n)=>Ge(s,i,{...n,badge:f.add})),preselected:r.length>0?r:void 0,projectName:S(t),resolveAuthUiItem:()=>{try{const s=JSON.parse(b(p(t,"package.json"),"utf8"));return ot({...s.dependencies,...s.devDependencies})??"auth-ui-react"}catch{return"auth-ui-react"}},select:e.prompt?.select??((s,i,n)=>D(s,i,{...n,badge:f.add})),text:e.prompt?.text??((s,i)=>ne(s,{...i,badge:f.add}))};if(r.length>0){await J(o);return}g()&&await Ke(y.extras),await J(o)},O="react",Ce=[{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:"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:"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"}],Va=Object.keys(T).join("|"),Ha=Ce.filter(e=>!z(e.value)).map(e=>e.value).join("|"),Wa=e=>z(e)?{framework:e,kind:"overlay"}:{kind:"template",templateType:e},qa=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:O,kind:"overlay"}:Wa(await D(y.framework,Ce,{badge:f.tmpl,default:O})??O),Fa=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 <${Va}>\` for an SPA, or \`-t <${Ha}>\` 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.`},Ka=async(e,t,a,r)=>z(t)?await be({isLocal:e.overlayBaseFrom!==void 0,logger:e.logger})?(L(r,{recursive:!0}),Ra({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}),Ja=async(e,t,a,r)=>e.from!==void 0?await Na(e.from,t,r,a,e.logger):e.source!==void 0&&e.source.length>0&&!e.allowUnsafeSource&&!ka(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 be({isLocal:!1,logger:e.logger,source:j(t,e.source,e.ref)})?Ia({logger:e.logger,name:a,ref:e.ref,source:e.source,target:r,templateType:t}):{code:1,files:[],target:r},Qa=async(e,t,a)=>{await Fe("realtime backend on Cloudflare Workers + Durable Objects");const r=Fa(e);if(r!==void 0)return e.logger.error(r),{code:1,files:[],target:""};const o=oa(),s=e.name??await ne(y.name,{badge:f.dir,default:o,placeholder:o}),i=await qa(e),n=s.trim();if(n.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(n.includes("/")||n.includes("\\")||n===".."||n===".")return e.logger.error(`init: refusing project name "${n}" — must not contain path separators or be "." / "..".`),{code:1,files:[],target:""};const c=B(t,n),d=h(c);if(d&&X(c).length>0)return e.logger.error(`target directory not empty: ${c}`),{code:1,files:[],target:c};if(e.dryRun===!0){const u=i.kind==="overlay"?`the ${i.framework} create-vite overlay`:`the ${i.templateType} template`;return C(e.logger,`scaffold ${u} into ${c}`),{code:0,files:[],target:c}}return a(c,d),i.kind==="overlay"?Ka(e,i.framework,n,c):Ja(e,i.templateType,n,c)},Ga=(e,t)=>{const{target:a,targetPreExisted:r}=e;if(!(a===void 0||!h(a))){if(r===!0)for(const o of X(a))I(p(a,o),{force:!0,recursive:!0});else I(a,{force:!0,recursive:!0});t.info(`removed the partially-created project at ${a}`)}},Xa=async(e,t,a)=>e.inPlace!==!0?Qa(e,t,a):e.dryRun===!0?(C(e.logger,`configure Lunora into ${t}`),{code:0,files:[],target:t}):Da(t,e.logger),Ya=async(e,t,a)=>{await Ua(e,t.target);const r=e.inPlace===!0?void 0:await Aa(e,t.target);if(e.inPlace!==!0){await Ma(e,t.target);const o=r??te(t.target);await La(S(t.target),r,o,$e(a)),await Mt(e.logger)}},Za=(e,t,a)=>{if(!(t.code!==0||e.ci===void 0)){if(e.dryRun===!0){C(e.logger,`scaffold a ${e.ci} CI deploy pipeline`);return}dt(e.inPlace===!0?a:t.target,e.ci,e.logger)}},er=async e=>{const t=e.cwd??process.cwd(),a={};let r;try{r=await Xa(e,t,(o,s)=>{a.target=o,a.targetPreExisted=s}),r.code===0&&r.target!==""&&(a.target=void 0,await Ya(e,r,t))}catch(o){if(o instanceof P)return Ga(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 Za(e,r,t),r},tr=e=>e==="analog"||e==="astro"||e==="expo"||e==="next"||e==="nuxt"||e==="react-router"||e==="standalone"||e==="sveltekit"||e==="tanstack-start-react"||e==="tanstack-start-solid",ar=(e,t)=>{if(e!==void 0){if(lt(e))return e;t.warn(`init: unknown --ci "${e}" — expected github | gitlab; skipping CI scaffold.`)}},kr=Ee(({argument:e,cwd:t,logger:a,options:r})=>{const o=r.template!==void 0&&tr(r.template)?r.template:void 0;return er({add:r.add,allowUnsafeSource:r.allowUnsafeSource===!0,cwd:t,ci:ar(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{kr as execute,tr as isTemplate,j as resolveTemplateSource,er as runInitCommand};
1224
+ `,wa="gh:anolilab/lunora/templates",ya=e=>{const t=e.lastIndexOf(".");return t===-1?!1:ha.has(e.slice(t))},ba=(e,t)=>e.replaceAll("{{name}}",t),Me=e=>e==="lunorash"||e.startsWith("@lunora/"),ka=async(e,t)=>{const a=new Set;for(const r of e)if(A(r)==="package.json")try{const o=JSON.parse(b(r,"utf8"));for(const s of["dependencies","devDependencies"])for(const i of Object.keys(o[s]??{}))Me(i)&&a.add(i)}catch{}return ne(a,t)},xa=(e,t,a)=>{let r;try{r=JSON.parse(e)}catch{return e}let o=e;for(const s of["dependencies","devDependencies"])for(const i of Object.keys(r[s]??{})){if(!Me(i))continue;const n=a.get(i)??t,l=Pe(o,[s,i],n,{formattingOptions:{insertSpaces:!0,tabSize:4}});o=De(o,l)}return o},$a=["@parcel/watcher","esbuild","lmdb","msgpackr-extract","rs-module-lexer","sharp","unrs-resolver","vue-demi","workerd"],Ca=["cpu-features","protobufjs","ssh2"],Ma="pnpm-workspace.yaml",La=()=>["# 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:",...$a.map(e=>` '${e}': true`),...Ca.map(e=>` '${e}': false`),""].join(`
1225
+ `),W=e=>{const t=[];for(const a of Be(e,{includeDirs:!1,includeFiles:!0}))Ne(a.path).isSymbolicLink()||t.push(a.path);return t},Le=async(e,t,a)=>{const r=W(e),o=[],s=ce(),i=await ka(r,s);for(const n of r){const l=Ee(e,n),d=p(t,l);S(C(d),{recursive:!0});const u=b(n);let c=ya(n)?ba(u.toString("utf8"),a):void 0;c!==void 0&&A(n)==="package.json"&&(c=xa(c,s,i)),c===void 0?m(d,u):m(d,c,"utf8"),o.push(d)}return o},B=(e,t,a)=>t!==void 0&&t.length>0?t:`${wa}/${e}#${le(a)}`,Sa=e=>e.includes("..")?!1:e.startsWith("gh:")||e.startsWith("github:")||e.startsWith("https://"),M=(e,t)=>{e.info(`[dry-run] would ${t}`)},q=(e,t,a)=>{g()&&process.stdout.write(`
1226
+ `),e.success(`scaffolded ${String(t.length)} files into ${a}`)},Aa=(e,t)=>`${e} ${e==="npm"?"install":"add"} ${t.join(" ")}`,Se=e=>{let t=E(e);for(;;){if(h(p(t,"pnpm-workspace.yaml")))return!0;const a=p(t,"package.json");if(h(a))try{if(JSON.parse(b(a,"utf8")).workspaces!==void 0)return!0}catch{}const r=C(t);if(r===t)return!1;t=r}},Na=e=>{let t=E(e);for(;;){if(h(p(t,".git")))return!0;const a=C(t);if(a===t)return!1;t=a}},Ia=async(e,t)=>{if(e.yes===!0||!g()||Na(C(t)))return;if(!await ue(y.git,{badge:f.git,defaultYes:!1})){await he("Sounds good! You can always run git init manually.");return}if(e.dryRun===!0){M(e.logger,"initialize a git repository");return}const a=e.spawner??de;(await Ye("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`.")},_a=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:He(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 Ze(f.next,y.nextHeader,o,s);return}const i=o.map(n=>`${n.lead} ${n.code}${n.tail??""}`);i.push("",...s.map(n=>`${n.lead} ${n.code}${n.tail??""}`)),await R("next",y.nextHeader,i.join(`
1227
+ `))},Ra=e=>e.yes!==!0&&(e.installPrompt!==void 0||g()),Ta=async(e,t)=>{if(!Ra(e)||Se(C(t)))return;const a=ze(e.packageManagerProbe),[r]=a;if(r===void 0)return;if(!await(e.installPrompt?.confirmInstall??(async()=>ue(y.install,{badge:f.deps,defaultYes:!0})))()){await he("No problem! Remember to install dependencies after setup.");return}let o=r;if(a.length>1&&(o=e.installPrompt?await e.installPrompt.selectManager(a):await V(y.packageManager,a.map(d=>({label:d,value:d})),{badge:f.deps,default:r})??r),e.dryRun===!0){M(e.logger,`install dependencies with ${o}`);return}if(o==="pnpm"){const d=p(t,Ma);h(d)||m(d,La(),"utf8")}const s=e.spawner??de,{args:i,command:n}=se(o);await R("deps",`Installing dependencies with ${o}…`);const l=await s({args:i,command:n,cwd:t});if(l.code!==0){e.logger.warn(`\`${n} install\` exited with code ${String(l.code)} — run it yourself in ${A(t)}/.`);return}return await R("deps",`Dependencies installed with ${o}.`),o},ja=async(e,t,a,r,o)=>{const s=p(e,t);if(!h(s))return o.error(`template not found in local source: ${s}`),{code:1,files:[],target:a};const i=await Le(s,a,r);return q(o,i,a),{code:0,files:i,target:a}},Oa=async e=>{const{logger:t,name:a,ref:r,source:o,target:s,templateType:i}=e,n=ae(p(re(),"lunora-init-fetch-")),l=p(n,"template");try{const d=o!==void 0&&o.length>0?r:await Fe(r,t),u=B(i,o,d);let c,w=[];await me([{label:`${i} template fetched`,run:async()=>{c=await oe(u,{cwd:n,dir:l,force:!0,install:!1,silent:!0})}},{label:`files copied into ${a}/`,run:async()=>{w=await Le(l,s,a)}}],{end:"Project initialized!",start:"Project initializing…"});const F=W(l);return g()&&process.stdout.write(`
1228
+ `),t.info(c?.commit?`template: ${c.source} @ ${c.commit} (${String(F.length)} files)`:`template: ${c?.source??u} (${String(F.length)} files)`),q(t,w,s),{code:0,files:w,target:s}}catch(d){if(d instanceof U)throw d;const{hints:u,message:c}=Nt(d,{ref:le(r),remote:B(i,o,r),templateType:i});t.error(c);for(const w of u)t.warn(w);return{code:1,files:[],target:s}}finally{_(n,{force:!0,recursive:!0})}},Ba=e=>{for(const t of["_gitignore","_npmrc","_gitattributes"]){const a=p(e,t);h(a)&&Ie(a,p(e,`.${t.slice(1)}`))}},Ea=async e=>{const{framework:t,logger:a,name:r,overlayBaseFrom:o,target:s}=e,i=j[t],n=ae(p(re(),"lunora-vite-base-"));try{let l;if(o!==void 0&&(l=p(o,`template-${i.createViteTemplate}`),!h(l)))return a.error(`create-vite base not found on disk: ${l}`),{code:1,files:[],target:s};const d=async()=>{if(l!==void 0){K(l,s,{recursive:!0});return}const c=p(n,"base"),w=`github:vitejs/vite/packages/create-vite/template-${i.createViteTemplate}#main`;await oe(w,{cwd:n,dir:c,force:!0,install:!1,silent:!0}),Ba(c),K(c,s,{recursive:!0})};let u=[];return await me([{label:`create-vite (${i.label}) base ready`,run:d},{label:`Lunora overlay applied (${i.label})`,run:async()=>{u=await ia({adapter:i,distTag:ce(),logger:a,name:r,target:s})}}],{end:"Project initialized!",start:"Project initializing…"}),q(a,u,s),{code:0,files:[...W(s)],target:s}}catch(l){if(l instanceof U)throw l;const d=l instanceof Error?l.message:String(l);return a.error(`failed to scaffold the ${i.label} base: ${d}`),{code:1,files:[],target:s}}finally{_(n,{force:!0,recursive:!0})}},Pa=(e,t)=>{const a=p(e,"vite.config.ts");try{m(a,ga,"utf8")}catch(r){const o=r instanceof Error?r.message:String(r);return t.error(`init --in-place: could not write ${a}: ${o}`),{code:1,files:[],target:e}}return t.success(`created ${a} with lunora() plugin`),{code:0,files:[a],target:e}},Da=(e,t,a)=>{let r;try{r=b(e,"utf8")}catch(s){const i=s instanceof Error?s.message:String(s);return a.error(`init --in-place: could not read ${e}: ${i}`),{code:1,files:[],target:t}}const o=ye(r);if(!o.changed)return a.info(`${e}: ${o.reason??"no changes needed"}`),{code:0,files:[],target:t};try{m(e,o.code,"utf8")}catch(s){const i=s instanceof Error?s.message:String(s);return a.error(`init --in-place: could not write ${e}: ${i}`),{code:1,files:[],target:t}}return a.success(`patched ${e} — added lunora() plugin`),{code:0,files:[e],target:t}},Ua=(e,t)=>{const a=p(e,"lunora"),r=p(a,"schema.ts");if(h(r))return t.info(`lunora/ already present — left ${r} untouched`),[];const o=[];try{S(a,{recursive:!0}),m(r,va,"utf8"),o.push(r);const s=p(a,"messages.ts");h(s)||(m(s,fa,"utf8"),o.push(s)),t.success(`scaffolded lunora/ (${String(o.length)} file(s))`)}catch(s){const i=s instanceof Error?s.message:String(s);t.error(`init --here: could not scaffold lunora/: ${i}`)}return o},Va=(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: ${Aa(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=>{for(const t of ma){const a=p(e,t);if(h(a))return a}},Ha=(e,t,a)=>{const r=za(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}):Pa(e,a):Da(r,e,a)},Wa=(e,t)=>{const a=ft(e),r=Ha(e,a.framework,t);if(r.code!==0)return r;const o=Ua(e,t);return Va(a,D(e),t),{code:0,files:[...r.files,...o],target:e}},qa=e=>e.yes!==!0&&(e.prompt!==void 0||(e.interactive??g())),Fa=async(e,t)=>{const a=qa(e),r=e.add===void 0?[]:Rt(e.add,s=>{e.logger.warn(s)}),o={applyAll:async s=>{if(s.length===0)return!0;if(e.dryRun===!0)return M(e.logger,`add ${s.map(c=>c.label).join(", ")}`),!0;const i=[],n=g()?{error:c=>{i.push({level:"error",message:c})},info:()=>{},success:()=>{},warn:c=>{i.push({level:"warn",message:c})}}:e.logger,l=s.map(c=>({running:`adding ${c.label}…`,task:()=>Ke({allowUnsafeSource:e.allowUnsafeSource,cwd:t,from:e.registryFrom,logger:n,names:[...c.names],ref:e.ref,source:e.registrySource,transformManifest:c.transformManifest,yes:!0})})),d=`added ${s.map(c=>c.label).join(", ")}`,u=await tt(f.add,l,d);for(const{level:c,message:w}of i)e.logger[c](w);return u.every(c=>c.code===0)},interactive:a,logger:e.logger,multiSelect:e.prompt?.multiSelect??((s,i,n)=>et(s,i,{...n,badge:f.add})),preselected:r.length>0?r:void 0,projectName:A(t),resolveAuthUiItem:()=>{try{const s=JSON.parse(b(p(t,"package.json"),"utf8"));return lt({...s.dependencies,...s.devDependencies})??"auth-ui-react"}catch{return"auth-ui-react"}},select:e.prompt?.select??((s,i,n)=>V(s,i,{...n,badge:f.add})),text:e.prompt?.text??((s,i)=>pe(s,{...i,badge:f.add}))};if(r.length>0){await Y(o);return}g()&&await Xe(y.extras),await Y(o)},O="react",Ae=[{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:"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:"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"}],Ka=Object.keys(j).join("|"),Ja=Ae.filter(e=>!H(e.value)).map(e=>e.value).join("|"),Qa=e=>H(e)?{framework:e,kind:"overlay"}:{kind:"template",templateType:e},Ga=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:O,kind:"overlay"}:Qa(await V(y.framework,Ae,{badge:f.tmpl,default:O})??O),Xa=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 <${Ka}>\` for an SPA, or \`-t <${Ja}>\` 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.`},Ya=async(e,t,a,r)=>H(t)?await Ce({isLocal:e.overlayBaseFrom!==void 0,logger:e.logger})?(S(r,{recursive:!0}),Ea({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(j).join(", ")}.`),{code:1,files:[],target:r}),Za=async(e,t,a,r)=>e.from!==void 0?await ja(e.from,t,r,a,e.logger):e.source!==void 0&&e.source.length>0&&!e.allowUnsafeSource&&!Sa(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 Ce({isLocal:!1,logger:e.logger,source:B(t,e.source,e.ref)})?Oa({logger:e.logger,name:a,ref:e.ref,source:e.source,target:r,templateType:t}):{code:1,files:[],target:r},er=async(e,t,a)=>{await Ge("realtime backend on Cloudflare Workers + Durable Objects");const r=Xa(e);if(r!==void 0)return e.logger.error(r),{code:1,files:[],target:""};const o=ca(),s=e.name??await pe(y.name,{badge:f.dir,default:o,placeholder:o}),i=await Ga(e),n=s.trim();if(n.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(n.includes("/")||n.includes("\\")||n===".."||n===".")return e.logger.error(`init: refusing project name "${n}" — must not contain path separators or be "." / "..".`),{code:1,files:[],target:""};const l=E(t,n),d=h(l);if(d&&te(l).length>0)return e.logger.error(`target directory not empty: ${l}`),{code:1,files:[],target:l};if(e.dryRun===!0){const u=i.kind==="overlay"?`the ${i.framework} create-vite overlay`:`the ${i.templateType} template`;return M(e.logger,`scaffold ${u} into ${l}`),{code:0,files:[],target:l}}return a(l,d),i.kind==="overlay"?Ya(e,i.framework,n,l):Za(e,i.templateType,n,l)},tr=(e,t)=>{const{target:a,targetPreExisted:r}=e;if(!(a===void 0||!h(a))){if(r===!0)for(const o of te(a))_(p(a,o),{force:!0,recursive:!0});else _(a,{force:!0,recursive:!0});t.info(`removed the partially-created project at ${a}`)}},ar=async(e,t,a)=>e.inPlace!==!0?er(e,t,a):e.dryRun===!0?(M(e.logger,`configure Lunora into ${t}`),{code:0,files:[],target:t}):Wa(t,e.logger),rr=async(e,t,a)=>{await Fa(e,t.target);const r=e.inPlace===!0?void 0:await Ta(e,t.target);if(e.inPlace!==!0){await Ia(e,t.target);const o=r??D(t.target);await _a(A(t.target),r,o,Se(a)),await It(e.logger)}},or=(e,t,a)=>{if(t.code!==0||e.ci===void 0)return;if(e.dryRun===!0){M(e.logger,`scaffold a ${e.ci} CI deploy pipeline`);return}const r=e.inPlace===!0?a:t.target;try{const o=D(r);gt(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.`)}},sr=async e=>{const t=e.cwd??process.cwd(),a={};let r;try{r=await ar(e,t,(o,s)=>{a.target=o,a.targetPreExisted=s}),r.code===0&&r.target!==""&&(a.target=void 0,await rr(e,r,t))}catch(o){if(o instanceof U)return tr(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 or(e,r,t),r},ir=e=>e==="analog"||e==="astro"||e==="expo"||e==="next"||e==="nuxt"||e==="react-router"||e==="standalone"||e==="sveltekit"||e==="tanstack-start-react"||e==="tanstack-start-solid",nr=(e,t)=>{if(e!==void 0){if(ht(e))return e;t.warn(`init: unknown --ci "${e}" — expected github | gitlab; skipping CI scaffold.`)}},Sr=We(({argument:e,cwd:t,logger:a,options:r})=>{const o=r.template!==void 0&&ir(r.template)?r.template:void 0;return sr({add:r.add,allowUnsafeSource:r.allowUnsafeSource===!0,cwd:t,ci:nr(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{Sr as execute,ir as isTemplate,B as resolveTemplateSource,sr as runInitCommand};
@@ -1,4 +1,4 @@
1
- import{existsSync as m,mkdirSync as S,writeFileSync as f,mkdtempSync as C,rmSync as I,readFileSync as k}from"node:fs";import{tmpdir as M}from"node:os";import{discoverSchema as T,readPackageDependencies as N,discoverMigrations as z}from"@lunora/codegen";import{isInteractive as A,promptSelect as E,promptText as F}from"@lunora/config";import{LunoraError as $}from"@lunora/errors";import{join as c}from"@visulima/path";import{Project as h}from"ts-morph";import{u as O}from"../packem_shared/admin-url-Ca-KI3d_.mjs";import{i as R}from"../packem_shared/command-Bjv4VmYA.mjs";import{diffSnapshots as q,renderMigrationFile as D}from"../packem_shared/diffSnapshots-9bDd9nOK.mjs";import{s as L}from"../packem_shared/resolve-target-vxaXHmvg.mjs";import j from"../packem_shared/schemaIrToSnapshot-Clwd2A8e.mjs";import{runExportCommand as B,runImportCommand as H}from"../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-xn-frBqK.mjs";const J=".snapshot.json",x=/[^\da-z]+/gu,U=(r,e)=>{let o=0,t=r.length;for(;o<t&&r[o]===e;)o+=1;for(;t>o&&r[t-1]===e;)t-=1;return r.slice(o,t)},P=r=>{const e=U(r.toLowerCase().replaceAll(x,"_"),"_");return e===""?"auto":e},Z=r=>{const e=(o,t=2)=>o.toString().padStart(t,"0");return`${String(r.getUTCFullYear())}${e(r.getUTCMonth()+1)}${e(r.getUTCDate())}${e(r.getUTCHours())}${e(r.getUTCMinutes())}${e(r.getUTCSeconds())}`},K=r=>{if(m(r))try{const e=k(r,"utf8"),o=JSON.parse(e);if(o.version!==1)throw new $("INTERNAL",`unsupported snapshot version: ${o.version}`);return o}catch(e){const o=e instanceof Error?e.message:String(e);throw new $("INTERNAL",`failed to read ${r}: ${o}`,{cause:e})}},Q=r=>{const e=r.cwd??process.cwd(),o=c(e,"lunora","schema.ts");if(!m(o))return r.logger.error(`schema not found: ${o} — run \`vis generate lunora-table --name=<name>\` to create one`),{code:1,empty:!0,migrationFile:""};const t=new h({skipAddingFilesFromTsConfig:!0}),n=T(t,o),s=j(n),i=c(e,"lunora","migrations"),a=c(i,J);let d;try{d=K(a)}catch(p){return r.logger.error(p instanceof Error?p.message:String(p)),{code:1,empty:!0,migrationFile:""}}const l=q(d,s);if(l.empty)return r.logger.info("no schema changes detected — snapshot is already up to date"),{code:0,empty:!0,migrationFile:""};const u=(r.now??(()=>new Date))(),w=P(r.name??"auto"),b=`${Z(u)}_${w}.sql`,g=c(i,b);S(i,{recursive:!0});const _=D(w,l,u.toISOString());return f(g,_,"utf8"),f(a,`${JSON.stringify(s,void 0,4)}
1
+ import{existsSync as m,mkdirSync as S,writeFileSync as f,mkdtempSync as C,rmSync as I,readFileSync as k}from"node:fs";import{tmpdir as M}from"node:os";import{discoverSchema as T,readPackageDependencies as N,discoverMigrations as z}from"@lunora/codegen";import{isInteractive as A,promptSelect as E,promptText as F}from"@lunora/config";import{LunoraError as $}from"@lunora/errors";import{join as c}from"@visulima/path";import{Project as h}from"ts-morph";import{u as O}from"../packem_shared/admin-url-Ca-KI3d_.mjs";import{i as R}from"../packem_shared/command-Bjv4VmYA.mjs";import{diffSnapshots as q,renderMigrationFile as D}from"../packem_shared/diffSnapshots-9bDd9nOK.mjs";import{d as L}from"../packem_shared/resolve-target-CeiNrCAx.mjs";import j from"../packem_shared/schemaIrToSnapshot-Clwd2A8e.mjs";import{runExportCommand as B,runImportCommand as H}from"../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-xn-frBqK.mjs";const J=".snapshot.json",x=/[^\da-z]+/gu,U=(r,e)=>{let o=0,t=r.length;for(;o<t&&r[o]===e;)o+=1;for(;t>o&&r[t-1]===e;)t-=1;return r.slice(o,t)},P=r=>{const e=U(r.toLowerCase().replaceAll(x,"_"),"_");return e===""?"auto":e},Z=r=>{const e=(o,t=2)=>o.toString().padStart(t,"0");return`${String(r.getUTCFullYear())}${e(r.getUTCMonth()+1)}${e(r.getUTCDate())}${e(r.getUTCHours())}${e(r.getUTCMinutes())}${e(r.getUTCSeconds())}`},K=r=>{if(m(r))try{const e=k(r,"utf8"),o=JSON.parse(e);if(o.version!==1)throw new $("INTERNAL",`unsupported snapshot version: ${o.version}`);return o}catch(e){const o=e instanceof Error?e.message:String(e);throw new $("INTERNAL",`failed to read ${r}: ${o}`,{cause:e})}},Q=r=>{const e=r.cwd??process.cwd(),o=c(e,"lunora","schema.ts");if(!m(o))return r.logger.error(`schema not found: ${o} — run \`vis generate lunora-table --name=<name>\` to create one`),{code:1,empty:!0,migrationFile:""};const t=new h({skipAddingFilesFromTsConfig:!0}),n=T(t,o),s=j(n),i=c(e,"lunora","migrations"),a=c(i,J);let d;try{d=K(a)}catch(p){return r.logger.error(p instanceof Error?p.message:String(p)),{code:1,empty:!0,migrationFile:""}}const l=q(d,s);if(l.empty)return r.logger.info("no schema changes detected — snapshot is already up to date"),{code:0,empty:!0,migrationFile:""};const u=(r.now??(()=>new Date))(),w=P(r.name??"auto"),b=`${Z(u)}_${w}.sql`,g=c(i,b);S(i,{recursive:!0});const _=D(w,l,u.toISOString());return f(g,_,"utf8"),f(a,`${JSON.stringify(s,void 0,4)}
2
2
  `,"utf8"),r.logger.success(`wrote ${g}`),l.unsupported.length>0&&r.logger.warn(`${String(l.unsupported.length)} unsupported diff(s) — see the comment block in ${b} and write the SQL manually`),{code:0,empty:!1,migrationFile:g}},W="migrations.ts",y=/^[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"]),v=/^import\s*\{\s*defineMigration\s*\}\s*from\s*["'](?:@lunora\/server|lunorash\/server)["'][^\n]*$/mu,G=r=>`import { defineMigration } from "${N(r)?.has("lunorash")??!1?"lunorash/server":"@lunora/server"}";`,V="__lunora_admin__:runMigration",X="__lunora_admin__:migrationStatus",rr="/_lunora/migrate",er=r=>U(r.trim().toLowerCase().replaceAll(x,"-"),"-"),tr=r=>r.split("-").filter(e=>e.length>0).map((e,o)=>o===0?e:e.charAt(0).toUpperCase()+e.slice(1)).join(""),or=r=>{const e=c(r,"lunora","schema.ts");if(!m(e))return[];try{const o=new h({skipAddingFilesFromTsConfig:!0});return T(o,e).tables.map(t=>t.name)}catch{return[]}},nr=async r=>r.length>0?E("Which table does this migration iterate?",r.map(e=>({label:e,value:e}))):F("Target table for the migration: "),ir=async(r,e)=>{if(e.table!==void 0)return e.table;const o=e.promptTable??(A()?nr:void 0);if(o===void 0){e.logger.error("migrate create requires a target table when not running interactively — re-run with --table <table>");return}const t=(await o(or(r)))?.trim();if(t===void 0||t===""){e.logger.error("no table selected — re-run with --table <table>");return}return t},ar=async r=>{const e=r.cwd??process.cwd(),o=er(r.name);if(o==="")return r.logger.error(`invalid migration name: "${r.name}" — must contain at least one alphanumeric character`),{code:1,file:""};const t=tr(o);if(!y.test(t)||Y.has(t))return r.logger.error(`invalid migration name: "${r.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 n=await ir(e,r);if(n===void 0)return{code:1,file:""};if(!y.test(n))return r.logger.error(`invalid table: "${n}" — must be a valid identifier ([A-Za-z_][A-Za-z0-9_]*)`),{code:1,file:""};const s=c(e,"lunora"),i=c(s,W);let a=m(i)?k(i,"utf8"):"";if(a.includes(`id: "${o}"`)||new RegExp(String.raw`\bexport const ${t}\b`,"u").test(a))return r.logger.error(`a migration with id "${o}" (export \`${t}\`) already exists in ${i}`),{code:1,file:""};const d=G(e);a.trim()===""?a=`${d}
3
3
  `:v.test(a)?a=a.replace(v,d):a=`${d}
4
4
  ${a}`;const l=`export const ${t} = defineMigration({
@@ -1 +1 @@
1
- import{LunoraError as v}from"@lunora/errors";import{l as w,v as _}from"../packem_shared/admin-token-DV5A9T5b.mjs";import{u as N,s as $}from"../packem_shared/admin-url-Ca-KI3d_.mjs";import{i as b}from"../packem_shared/command-Bjv4VmYA.mjs";import{t as P}from"../packem_shared/resolve-target-vxaXHmvg.mjs";const f=(r,e="--args")=>{if(r===void 0||r.length===0)return{};try{return JSON.parse(r)}catch(o){const t=o instanceof Error?o.message:String(o);throw new v("INTERNAL",`failed to parse ${e} as JSON: ${t}`,{cause:o})}},S=/\/$/u,O="__lunora_admin__:runAs",k="__lunora_admin__:",A=(r,e)=>{const o=e.body?.error?.code;e.runAs||e.status!==403||o!=="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:e,options:o,runAs:t})=>{const a=t?{args:{args:r,functionPath:o.functionPath,identity:e,userId:o.as},functionPath:O}:{args:r,functionPath:o.functionPath};return o.shard!==void 0&&(a.shardKey=o.shard),a},I=({cwd:r,logger:e,needsBearer:o,url:t})=>o?N(t,e,r):(P({cwd:r,url:t})??$(r)).replace(S,""),T=async r=>{const e=r.cwd??process.cwd(),o=r.as!==void 0&&r.as!=="",t=o||r.functionPath.startsWith(k),a=I({cwd:e,logger:r.logger,needsBearer:t,url:r.url});if(a===void 0)return{body:void 0,code:1,requestUrl:r.url??""};const s=`${a}/_lunora/rpc`,u=r.fetchImpl??globalThis.fetch;if(typeof u!="function")throw new TypeError("no fetch implementation available — pass --fetch via dependency injection or run on Node >= 18");let l,g;try{l=f(r.args),g=r.claims===void 0?void 0:f(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:m,token:n}=t?w({cwd:e,token:r.token,url:a}):{};if(t&&n===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};n!==void 0&&r.logger.debug?.(`admin bearer from ${_(m)}`);const p={"content-type":"application/json",...n===void 0?{}:{authorization:`Bearer ${n}`}},y=E({args:l,claims:g,options:r,runAs:o});r.logger.info(`POST ${s} -> ${r.functionPath}${o?` (as ${r.as??""})`:""}`);const c=await u(s,{body:JSON.stringify(y),headers:p,method:"POST"}),h=await c.text();let i;try{i=JSON.parse(h)}catch{i=h}return r.logger.info(JSON.stringify(i,void 0,2)),A(r.logger,{body:i,runAs:o,status:c.status}),{body:i,code:c.ok?0:1,requestUrl:s}},D=b(({argument:r,cwd:e,logger:o,options:t})=>{const a=r[0];return a?T({args:t.args,as:t.as,claims:t.claims,cwd:e,functionPath:a,logger:o,shard:t.shard,token:t.token,url:t.url}):(o.error("missing function path. Usage: lunora run <functionPath> [--args <json>]"),{code:1})});export{D as execute,T as runRpcCommand};
1
+ import{LunoraError as v}from"@lunora/errors";import{l as w,v as _}from"../packem_shared/admin-token-DV5A9T5b.mjs";import{u as N,s as $}from"../packem_shared/admin-url-Ca-KI3d_.mjs";import{i as b}from"../packem_shared/command-Bjv4VmYA.mjs";import{i as P}from"../packem_shared/resolve-target-CeiNrCAx.mjs";const f=(r,e="--args")=>{if(r===void 0||r.length===0)return{};try{return JSON.parse(r)}catch(o){const t=o instanceof Error?o.message:String(o);throw new v("INTERNAL",`failed to parse ${e} as JSON: ${t}`,{cause:o})}},S=/\/$/u,O="__lunora_admin__:runAs",k="__lunora_admin__:",A=(r,e)=>{const o=e.body?.error?.code;e.runAs||e.status!==403||o!=="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:e,options:o,runAs:t})=>{const a=t?{args:{args:r,functionPath:o.functionPath,identity:e,userId:o.as},functionPath:O}:{args:r,functionPath:o.functionPath};return o.shard!==void 0&&(a.shardKey=o.shard),a},I=({cwd:r,logger:e,needsBearer:o,url:t})=>o?N(t,e,r):(P({cwd:r,url:t})??$(r)).replace(S,""),T=async r=>{const e=r.cwd??process.cwd(),o=r.as!==void 0&&r.as!=="",t=o||r.functionPath.startsWith(k),a=I({cwd:e,logger:r.logger,needsBearer:t,url:r.url});if(a===void 0)return{body:void 0,code:1,requestUrl:r.url??""};const s=`${a}/_lunora/rpc`,u=r.fetchImpl??globalThis.fetch;if(typeof u!="function")throw new TypeError("no fetch implementation available — pass --fetch via dependency injection or run on Node >= 18");let l,g;try{l=f(r.args),g=r.claims===void 0?void 0:f(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:m,token:n}=t?w({cwd:e,token:r.token,url:a}):{};if(t&&n===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};n!==void 0&&r.logger.debug?.(`admin bearer from ${_(m)}`);const p={"content-type":"application/json",...n===void 0?{}:{authorization:`Bearer ${n}`}},y=E({args:l,claims:g,options:r,runAs:o});r.logger.info(`POST ${s} -> ${r.functionPath}${o?` (as ${r.as??""})`:""}`);const c=await u(s,{body:JSON.stringify(y),headers:p,method:"POST"}),h=await c.text();let i;try{i=JSON.parse(h)}catch{i=h}return r.logger.info(JSON.stringify(i,void 0,2)),A(r.logger,{body:i,runAs:o,status:c.status}),{body:i,code:c.ok?0:1,requestUrl:s}},D=b(({argument:r,cwd:e,logger:o,options:t})=>{const a=r[0];return a?T({args:t.args,as:t.as,claims:t.claims,cwd:e,functionPath:a,logger:o,shard:t.shard,token:t.token,url:t.url}):(o.error("missing function path. Usage: lunora run <functionPath> [--args <json>]"),{code:1})});export{D as execute,T as runRpcCommand};
@@ -0,0 +1 @@
1
+ import"node:fs";import"node:path";import"node:url";import"@lunora/errors";import"@visulima/cerebro";import"@visulima/cerebro/command/completion";import"@visulima/cerebro/command/version";import{p as S,t as A,i as C,f as D}from"./cli-Cmbw5lEB.mjs";import"./detect-package-manager-D9r2z_X6.mjs";import"./createLogger--C3x1FNE.mjs";export{S as COMMANDS,A as REGISTERED_COMMAND_NAMES,C as VERSION,D as runCli};
@@ -0,0 +1 @@
1
+ import{errorAdvisoryNames as t}from"@lunora/codegen";const n=r=>r.strictAdvisories??(process.env.CI!==void 0&&process.env.CI!==""),v=(r,e)=>{const o=r.filter(s=>s.level==="ERROR");return{errorAdvisories:o,names:t(r),shouldBlock:o.length>0&&e}};export{v as n,n as t};