@lunora/cli 1.0.0-alpha.214 → 1.0.0-alpha.216

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/dist/bin.mjs +1 -1
  2. package/dist/index.d.mts +36 -1
  3. package/dist/index.d.ts +36 -1
  4. package/dist/index.mjs +1 -1
  5. package/dist/packem_chunks/handler.mjs +1 -1
  6. package/dist/packem_chunks/handler10.mjs +1 -4
  7. package/dist/packem_chunks/handler11.mjs +4 -2
  8. package/dist/packem_chunks/handler12.mjs +2 -1
  9. package/dist/packem_chunks/handler13.mjs +1 -1
  10. package/dist/packem_chunks/handler14.mjs +1 -1
  11. package/dist/packem_chunks/handler15.mjs +1 -1
  12. package/dist/packem_chunks/handler16.mjs +1 -3
  13. package/dist/packem_chunks/handler17.mjs +3 -1
  14. package/dist/packem_chunks/handler18.mjs +1 -1
  15. package/dist/packem_chunks/handler19.mjs +1 -7
  16. package/dist/packem_chunks/handler2.mjs +1 -2
  17. package/dist/packem_chunks/handler20.mjs +7 -1
  18. package/dist/packem_chunks/handler21.mjs +1 -2
  19. package/dist/packem_chunks/handler22.mjs +2 -3
  20. package/dist/packem_chunks/handler23.mjs +3 -3
  21. package/dist/packem_chunks/handler24.mjs +3 -1
  22. package/dist/packem_chunks/handler25.mjs +1 -99
  23. package/dist/packem_chunks/handler26.mjs +99 -10
  24. package/dist/packem_chunks/handler27.mjs +10 -0
  25. package/dist/packem_chunks/handler3.mjs +2 -1
  26. package/dist/packem_chunks/handler4.mjs +1 -1
  27. package/dist/packem_chunks/handler5.mjs +1 -1
  28. package/dist/packem_chunks/handler6.mjs +1 -1
  29. package/dist/packem_chunks/handler7.mjs +1 -3
  30. package/dist/packem_chunks/handler8.mjs +3 -1
  31. package/dist/packem_chunks/handler9.mjs +1 -1
  32. package/dist/packem_chunks/planDevCommand.mjs +1 -1
  33. package/dist/packem_chunks/runCodegenCommand.mjs +2 -2
  34. package/dist/packem_chunks/runInitCommand.mjs +38 -38
  35. package/dist/packem_chunks/runMigrateGenerateCommand.mjs +6 -6
  36. package/dist/packem_chunks/runRpcCommand.mjs +1 -1
  37. package/dist/packem_shared/{COMMANDS-BuKOBthp.mjs → COMMANDS-Cf45cyJN.mjs} +1 -1
  38. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-CYq3UJmD.mjs +1 -0
  39. package/dist/packem_shared/admin-token-VdUnvnKW.mjs +1 -0
  40. package/dist/packem_shared/admin-url-BhF5ufg1.mjs +1 -0
  41. package/dist/packem_shared/buildRegistryIndex-BcJgAx76.mjs +1 -0
  42. package/dist/packem_shared/catalog-CJaormx0.mjs +1 -0
  43. package/dist/packem_shared/cli-CqNvbTR1.mjs +3 -0
  44. package/dist/packem_shared/commands-YfMX-Mto.mjs +19 -0
  45. package/dist/packem_shared/diffSnapshots-Cnoe8Ob4.mjs +5 -0
  46. package/dist/packem_shared/{import-CdHdZRjj.mjs → import-8FCB0cUX.mjs} +10 -10
  47. package/dist/packem_shared/platform-diagnostics-D0YzAdXm.mjs +4 -0
  48. package/dist/packem_shared/runAddCommand-vE21wRIK.mjs +1 -0
  49. package/dist/packem_shared/runDeployCommand-o64lz-UD.mjs +1 -0
  50. package/dist/packem_shared/runExportCommand-Dq-SpjAe.mjs +5 -0
  51. package/dist/packem_shared/schema-drift-gate-BDCkQ1S6.mjs +1 -0
  52. package/dist/packem_shared/schemaIrToSnapshot-ogkcpHjM.mjs +1 -0
  53. package/dist/packem_shared/{storage-wIUel5Az.mjs → storage-D5s4vbtJ.mjs} +1 -1
  54. package/package.json +11 -11
  55. package/dist/packem_chunks/runDeployCommand.mjs +0 -1
  56. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Cf8ZymM1.mjs +0 -1
  57. package/dist/packem_shared/admin-token-rxXZbVMZ.mjs +0 -1
  58. package/dist/packem_shared/admin-url-Cil3Or6N.mjs +0 -1
  59. package/dist/packem_shared/buildRegistryIndex-Zi3bBqpc.mjs +0 -1
  60. package/dist/packem_shared/cli-CiD-rkxB.mjs +0 -3
  61. package/dist/packem_shared/commands-BNKj7r1R.mjs +0 -19
  62. package/dist/packem_shared/diffSnapshots-CIOFQN_a.mjs +0 -5
  63. package/dist/packem_shared/platform-diagnostics-uOXqysk3.mjs +0 -4
  64. package/dist/packem_shared/runAddCommand-D1Dj8-pK.mjs +0 -1
  65. package/dist/packem_shared/runExportCommand-DmXKEWSq.mjs +0 -5
  66. package/dist/packem_shared/schema-drift-gate-Bt_plRtS.mjs +0 -1
  67. package/dist/packem_shared/schemaIrToSnapshot-qpRoV7HY.mjs +0 -1
@@ -1,11 +1,11 @@
1
- import{existsSync as m,mkdirSync as M,writeFileSync as v,readFileSync as b,readdirSync as re,rmSync as _,mkdtempSync as oe,cpSync as G,renameSync as Oe,lstatSync as Pe}from"node:fs";import{tmpdir as ne}from"node:os";import{installArgsFor as se,execArgsFor as De,detectFramework as Be,isInteractive as g,LUNA_ART as je,LUNA_NAME as Ve,LUNA_SIGNOFF as Ue,BADGES as f,paintAnswer as Fe,detectPackageManager as U,detectInstalledManagers as He,runScriptCommand as We,detectLintTools as ze,addArgsFor as qe,applyLintIgnores as Ke}from"@lunora/config";import{walkSync as Ge}from"@visulima/fs";import{join as u,dirname as A,basename as E,resolve as ie,relative as Je}from"@visulima/path";import{downloadTemplate as le}from"giget";import{modify as Ye,applyEdits as Xe}from"jsonc-parser";import{join as F,dirname as Qe}from"node:path";import{d as Ze}from"../packem_shared/command-DwC11Cwe.mjs";import et from"magic-string";import{Project as tt,SyntaxKind as w}from"ts-morph";import{P as H}from"../packem_shared/prompt-cancelled-C8Sj7OqI.mjs";import{h as ce,d as de,i as ue,b as at}from"../packem_shared/resolve-DZAGzg67.mjs";import{defaultSpawner as pe}from"../packem_shared/createRecordingSpawner-DJlNacZ6.mjs";import{d as rt,e as ot,f as nt,a as he,t as W,g as me,h as st,b as fe,i as ve,w as it,j as lt,k as ge,l as ct}from"../packem_shared/tui-prompts-Dd0pDuNr.mjs";import{E as we,p as dt,w as ut,M as pt,r as ht,j as mt,e as ft,c as ye,k as be,f as vt}from"../packem_shared/storage-wIUel5Az.mjs";import{logStep as J}from"../packem_shared/createLogger-hGafwf-3.mjs";import{r as gt}from"../packem_shared/lint-ignore-report-DKZagpqk.mjs";import wt from"node:dns/promises";import{r as yt}from"../packem_shared/commands-BNKj7r1R.mjs";const z={bun:{githubCacheKey:void 0,githubSetupStep:` - uses: oven-sh/setup-bun@v2
1
+ import{existsSync as m,mkdirSync as M,writeFileSync as v,readFileSync as b,readdirSync as ae,rmSync as _,mkdtempSync as oe,cpSync as G,renameSync as Oe,lstatSync as Pe}from"node:fs";import{tmpdir as ne}from"node:os";import{installArgsFor as se,execArgsFor as De,detectFramework as Be,isInteractive as g,LUNA_ART as je,LUNA_NAME as Ve,LUNA_SIGNOFF as Ue,BADGES as f,paintAnswer as Fe,detectPackageManager as U,detectInstalledManagers as He,runScriptCommand as We,detectLintTools as ze,addArgsFor as qe,applyLintIgnores as Ke}from"@lunora/config";import{walkSync as Ge}from"@visulima/fs";import{join as u,dirname as A,basename as E,resolve as ie,relative as Je}from"@visulima/path";import{downloadTemplate as le}from"giget";import{modify as Ye,applyEdits as Xe}from"jsonc-parser";import{join as F,dirname as Qe}from"node:path";import{d as Ze}from"../packem_shared/command-DwC11Cwe.mjs";import et from"magic-string";import{Project as tt,SyntaxKind as w}from"ts-morph";import{P as H}from"../packem_shared/prompt-cancelled-C8Sj7OqI.mjs";import{h as ce,d as de,i as ue,b as rt}from"../packem_shared/resolve-DZAGzg67.mjs";import{defaultSpawner as pe}from"../packem_shared/createRecordingSpawner-DJlNacZ6.mjs";import{d as at,e as ot,f as nt,a as he,t as W,g as me,h as st,b as fe,i as ve,w as it,j as lt,k as ge,l as ct}from"../packem_shared/tui-prompts-Dd0pDuNr.mjs";import{E as we,p as dt,w as ut,M as pt,r as ht,j as mt,e as ft,c as ye,k as be,f as vt}from"../packem_shared/storage-D5s4vbtJ.mjs";import{logStep as J}from"../packem_shared/createLogger-hGafwf-3.mjs";import{r as gt}from"../packem_shared/lint-ignore-report-DKZagpqk.mjs";import wt from"node:dns/promises";import{r as yt}from"../packem_shared/commands-YfMX-Mto.mjs";const z={bun:{githubCacheKey:void 0,githubSetupStep:` - uses: oven-sh/setup-bun@v2
2
2
  `,gitlabImage:"oven/bun:1",gitlabProvisionScript:[],installCmd:"bun install --frozen-lockfile",lockfile:"bun.lockb"},npm:{githubCacheKey:"npm",githubSetupStep:"",gitlabImage:"node:22",gitlabProvisionScript:[],installCmd:"npm ci",lockfile:"package-lock.json"},pnpm:{githubCacheKey:"pnpm",githubSetupStep:` - uses: pnpm/action-setup@v4
3
- `,gitlabImage:"node:22",gitlabProvisionScript:["corepack enable"],installCmd:"pnpm install --frozen-lockfile",lockfile:"pnpm-lock.yaml"},yarn:{githubCacheKey:"yarn",githubSetupStep:"",gitlabImage:"node:22",gitlabProvisionScript:["corepack enable"],installCmd:"yarn install --frozen-lockfile",lockfile:"yarn.lock"}},C=(e,t)=>{const a=De(e,"lunora",t);return[a.command,...a.args].join(" ")},Y=e=>` - uses: actions/checkout@v4
3
+ `,gitlabImage:"node:22",gitlabProvisionScript:["corepack enable"],installCmd:"pnpm install --frozen-lockfile",lockfile:"pnpm-lock.yaml"},yarn:{githubCacheKey:"yarn",githubSetupStep:"",gitlabImage:"node:22",gitlabProvisionScript:["corepack enable"],installCmd:"yarn install --frozen-lockfile",lockfile:"yarn.lock"}},C=(e,t)=>{const r=De(e,"lunora",t);return[r.command,...r.args].join(" ")},Y=e=>` - uses: actions/checkout@v4
4
4
  ${e.githubSetupStep} - uses: actions/setup-node@v4
5
5
  with:
6
6
  node-version: 22
7
7
  ${e.githubCacheKey===void 0?"":` cache: ${e.githubCacheKey}
8
- `} - run: ${e.installCmd}`,bt=e=>{const t=z[e],a=t.githubCacheKey===void 0?`# (below) requires it — run \`${e} install\` locally and`:`# (below) and the ${e} cache both require it — run \`${e} install\` locally and`;return`name: Deploy
8
+ `} - run: ${e.installCmd}`,bt=e=>{const t=z[e],r=t.githubCacheKey===void 0?`# (below) requires it — run \`${e} install\` locally and`:`# (below) and the ${e} cache both require it — run \`${e} install\` locally and`;return`name: Deploy
9
9
 
10
10
  on:
11
11
  push:
@@ -14,7 +14,7 @@ on:
14
14
  workflow_dispatch:
15
15
 
16
16
  # Prerequisite: commit your ${t.lockfile}. \`${t.installCmd}\`
17
- ${a}
17
+ ${r}
18
18
  # commit the lockfile before pushing, or the first CI run fails.
19
19
  #
20
20
  # Set these repository secrets (Settings → Secrets and variables → Actions):
@@ -47,7 +47,7 @@ ${Y(t)}
47
47
  steps:
48
48
  ${Y(t)}
49
49
  - run: ${C(e,["deploy","--preview"])}
50
- `},xt=e=>{const t=z[e],a=[...t.gitlabProvisionScript,t.installCmd].map(r=>` - ${r}`).join(`
50
+ `},xt=e=>{const t=z[e],r=[...t.gitlabProvisionScript,t.installCmd].map(a=>` - ${a}`).join(`
51
51
  `);return`stages:
52
52
  - deploy
53
53
 
@@ -62,7 +62,7 @@ ${Y(t)}
62
62
  image: ${t.gitlabImage}
63
63
  stage: deploy
64
64
  before_script:
65
- ${a}
65
+ ${r}
66
66
 
67
67
  # Production deploy on the default branch.
68
68
  deploy:
@@ -82,16 +82,16 @@ preview:
82
82
  - if: $CI_PIPELINE_SOURCE == "merge_request_event"
83
83
  script:
84
84
  - ${C(e,["deploy","--preview"])}
85
- `},xe={github:{file:F(".github","workflows","deploy.yml"),secretsHint:"repository secrets (Settings → Secrets and variables → Actions)"},gitlab:{file:".gitlab-ci.yml",secretsHint:"masked CI/CD variables (Settings → CI/CD → Variables)"}},kt=(e,t)=>e==="github"?bt(t):xt(t),Ct=e=>e==="github"||e==="gitlab",St=(e,t,a,r={})=>{const o=F(e,xe[t].file);return m(o)&&r.overwrite!==!0?{path:o,skipped:!0,written:!1}:(M(Qe(o),{recursive:!0}),v(o,kt(t,a),"utf8"),{path:o,skipped:!1,written:!0})},Lt=(e,t,a,r,o={})=>{const n=xe[t];try{const s=St(e,t,a,o);if(s.skipped)r.info(`--ci ${t}: ${n.file} already exists — left unchanged (re-run with overwrite to replace).`);else{const i=se(a),l=[i.command,...i.args].join(" "),{installCmd:d,lockfile:c}=z[a];r.success(`--ci ${t}: wrote ${n.file}`),r.info(`--ci ${t}: set CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID as ${n.secretsHint} to enable deploys.`),r.info(`--ci ${t}: run \`${l}\` and commit ${c} before pushing — the pipeline runs \`${d}\`.`)}return s}catch(s){const i=s instanceof Error?s.message:String(s);return r.warn(`--ci ${t}: could not write ${n.file} (${i})`),{path:F(e,n.file),skipped:!1,written:!1}}},Mt={astro:"@lunora/react",none:"@lunora/react",nuxt:"@lunora/vue","react-router":"@lunora/react","solid-start":"@lunora/solid",sveltekit:"@lunora/svelte","tanstack-start":"@lunora/react","tanstack-start-solid":"@lunora/solid",vinext:"@lunora/react"},At=e=>{const t=Be(e);return{...t,adapter:Mt[t.framework]}},$="lunora()",X='import { lunora } from "@lunora/vite";',Et=/\blunora\s*\(/u,Nt='"@lunora/vite"',It="'@lunora/vite'",$t=e=>{for(const t of e.getStatements()){if(t.getKind()!==w.ExportAssignment)continue;const a=t.asKindOrThrow(w.ExportAssignment).getExpression();if(a.getKind()!==w.CallExpression)continue;const r=a.asKindOrThrow(w.CallExpression);if(r.getExpression().getText()!=="defineConfig")continue;const o=r.getArguments()[0];if(o?.getKind()===w.ObjectLiteralExpression)return o.asKindOrThrow(w.ObjectLiteralExpression)}},_t=e=>{for(const t of e.getStatements()){if(t.getKind()!==w.ExportAssignment)continue;const a=t.asKindOrThrow(w.ExportAssignment).getExpression();if(a.getKind()===w.ObjectLiteralExpression)return a.asKindOrThrow(w.ObjectLiteralExpression)}},Rt=e=>new tt({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}).createSourceFile("vite.config.ts",e,{overwrite:!0}),Tt=(e,t)=>{const a=t.getImportDeclarations().at(-1)?.getEnd()??0;a===0?e.prepend(`${X}
86
- `):e.appendLeft(a,`
87
- ${X}`)},Ot=(e,t)=>{const a=t.getProperty("plugins");if(a===void 0){const n=t.getProperties(),s=t.getStart()+1;if(n.length===0)e.appendLeft(s,` plugins: [${$}] `);else{const i=n[0];i!==void 0&&e.appendLeft(i.getStart(),`plugins: [${$}],
88
- `)}return}const r=a.getDescendantsOfKind(w.ArrayLiteralExpression)[0];if(r===void 0)return;const o=r.getElements();if(o.length===0)e.appendLeft(r.getStart()+1,$);else{const n=o[0];n!==void 0&&e.appendLeft(n.getStart(),`${$}, `)}},ke=e=>{if(Et.test(e))return{changed:!1,code:e,reason:"lunora plugin already present"};const t=Rt(e),a=$t(t)??_t(t);if(a===void 0)return{changed:!1,code:e,reason:"could not locate a Vite config plugins array to patch"};const r=new et(e);return!e.includes(Nt)&&!e.includes(It)&&Tt(r,t),Ot(r,a),{changed:!0,code:r.toString()}},Pt=/enotfound|eai_again|econnrefused|etimedout|network|fetch failed|getaddrinfo/u,Dt=/404|not found|could not find|no such/u,Bt=(e,t)=>{const a=e instanceof Error?e.message:String(e),r=a.toLowerCase(),o=`failed to download template "${t.templateType}" from ${t.remote}: ${a}`;return Dt.test(r)?{hints:[`Check the template name "${t.templateType}" and the ref "${t.ref}".`,"List/inspect available templates, or target a branch/tag with `--ref <branch>`."],message:`template "${t.templateType}" not found at ${t.remote}: ${a}`}:Pt.test(r)?{hints:["You appear to be offline or unable to reach GitHub.","To scaffold without a network, point at a local template root: `lunora init --from <dir>`."],message:o}:{hints:["If this is a network/offline issue, scaffold from a local root with `lunora init --from <dir>`."],message:o}},R=async(e,t,a)=>{if(g()){await ot(f[e],t,a);return}if(process.stdout.write(`
89
- `),a===void 0||a===""){J(e,t);return}const r=a.split(`
85
+ `},xe={github:{file:F(".github","workflows","deploy.yml"),secretsHint:"repository secrets (Settings → Secrets and variables → Actions)"},gitlab:{file:".gitlab-ci.yml",secretsHint:"masked CI/CD variables (Settings → CI/CD → Variables)"}},kt=(e,t)=>e==="github"?bt(t):xt(t),Ct=e=>e==="github"||e==="gitlab",St=(e,t,r,a={})=>{const o=F(e,xe[t].file);return m(o)&&a.overwrite!==!0?{path:o,skipped:!0,written:!1}:(M(Qe(o),{recursive:!0}),v(o,kt(t,r),"utf8"),{path:o,skipped:!1,written:!0})},Lt=(e,t,r,a,o={})=>{const n=xe[t];try{const s=St(e,t,r,o);if(s.skipped)a.info(`--ci ${t}: ${n.file} already exists — left unchanged (re-run with overwrite to replace).`);else{const i=se(r),l=[i.command,...i.args].join(" "),{installCmd:d,lockfile:c}=z[r];a.success(`--ci ${t}: wrote ${n.file}`),a.info(`--ci ${t}: set CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID as ${n.secretsHint} to enable deploys.`),a.info(`--ci ${t}: run \`${l}\` and commit ${c} before pushing — the pipeline runs \`${d}\`.`)}return s}catch(s){const i=s instanceof Error?s.message:String(s);return a.warn(`--ci ${t}: could not write ${n.file} (${i})`),{path:F(e,n.file),skipped:!1,written:!1}}},Mt={astro:"@lunora/react",none:"@lunora/react",nuxt:"@lunora/vue","react-router":"@lunora/react","solid-start":"@lunora/solid",sveltekit:"@lunora/svelte","tanstack-start":"@lunora/react","tanstack-start-solid":"@lunora/solid",vinext:"@lunora/react"},At=e=>{const t=Be(e);return{...t,adapter:Mt[t.framework]}},$="lunora()",X='import { lunora } from "@lunora/vite";',Et=/\blunora\s*\(/u,Nt='"@lunora/vite"',It="'@lunora/vite'",$t=e=>{for(const t of e.getStatements()){if(t.getKind()!==w.ExportAssignment)continue;const r=t.asKindOrThrow(w.ExportAssignment).getExpression();if(r.getKind()!==w.CallExpression)continue;const a=r.asKindOrThrow(w.CallExpression);if(a.getExpression().getText()!=="defineConfig")continue;const o=a.getArguments()[0];if(o?.getKind()===w.ObjectLiteralExpression)return o.asKindOrThrow(w.ObjectLiteralExpression)}},_t=e=>{for(const t of e.getStatements()){if(t.getKind()!==w.ExportAssignment)continue;const r=t.asKindOrThrow(w.ExportAssignment).getExpression();if(r.getKind()===w.ObjectLiteralExpression)return r.asKindOrThrow(w.ObjectLiteralExpression)}},Rt=e=>new tt({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}).createSourceFile("vite.config.ts",e,{overwrite:!0}),Tt=(e,t)=>{const r=t.getImportDeclarations().at(-1)?.getEnd()??0;r===0?e.prepend(`${X}
86
+ `):e.appendLeft(r,`
87
+ ${X}`)},Ot=(e,t)=>{const r=t.getProperty("plugins");if(r===void 0){const n=t.getProperties(),s=t.getStart()+1;if(n.length===0)e.appendLeft(s,` plugins: [${$}] `);else{const i=n[0];i!==void 0&&e.appendLeft(i.getStart(),`plugins: [${$}],
88
+ `)}return}const a=r.getDescendantsOfKind(w.ArrayLiteralExpression)[0];if(a===void 0)return;const o=a.getElements();if(o.length===0)e.appendLeft(a.getStart()+1,$);else{const n=o[0];n!==void 0&&e.appendLeft(n.getStart(),`${$}, `)}},ke=e=>{if(Et.test(e))return{changed:!1,code:e,reason:"lunora plugin already present"};const t=Rt(e),r=$t(t)??_t(t);if(r===void 0)return{changed:!1,code:e,reason:"could not locate a Vite config plugins array to patch"};const a=new et(e);return!e.includes(Nt)&&!e.includes(It)&&Tt(a,t),Ot(a,r),{changed:!0,code:a.toString()}},Pt=/enotfound|eai_again|econnrefused|etimedout|network|fetch failed|getaddrinfo/u,Dt=/404|not found|could not find|no such/u,Bt=(e,t)=>{const r=e instanceof Error?e.message:String(e),a=r.toLowerCase(),o=`failed to download template "${t.templateType}" from ${t.remote}: ${r}`;return Dt.test(a)?{hints:[`Check the template name "${t.templateType}" and the ref "${t.ref}".`,"List/inspect available templates, or target a branch/tag with `--ref <branch>`."],message:`template "${t.templateType}" not found at ${t.remote}: ${r}`}:Pt.test(a)?{hints:["You appear to be offline or unable to reach GitHub.","To scaffold without a network, point at a local template root: `lunora init --from <dir>`."],message:o}:{hints:["If this is a network/offline issue, scaffold from a local root with `lunora init --from <dir>`."],message:o}},R=async(e,t,r)=>{if(g()){await ot(f[e],t,r);return}if(process.stdout.write(`
89
+ `),r===void 0||r===""){J(e,t);return}const a=r.split(`
90
90
  `).map(o=>Fe(o)).join(`
91
91
  `);J(e,`${t}
92
- ${r}`)},jt=async e=>{if(g()){await rt();return}e.info(`
92
+ ${a}`)},jt=async e=>{if(g()){await at();return}e.info(`
93
93
  ${je}
94
- ${Ve}: ${Ue}`)},Ce=[{description:"LLMs via Workers AI (summarize, generate, stream)",label:"AI",value:"ai"},{description:"Sign-up / sign-in (asks which provider)",label:"Authentication",value:"auth"},{description:"Copy-in auth screens for your framework (sign in/up, reset, 2FA)",label:"Auth UI",value:"auth-ui"},{description:"Snapshot + restore your Durable Object data",label:"Backups",value:"backup"},{description:"Headless browser screenshots + PDFs",label:"Browser rendering",value:"browser"},{description:"Zero Trust identity via Cloudflare Access",label:"Cloudflare Access",value:"cloudflare-access"},{description:"Scheduled jobs via Cron Triggers (@lunora/scheduler)",label:"Cron jobs",value:"crons"},{description:"Cloudflare Email Workers + a dev mail catcher",label:"Transactional email",value:"email"},{description:"OpenFeature feature flags (ctx.flags)",label:"Feature flags",value:"flags"},{description:"External Postgres/MySQL via Hyperdrive",label:"Hyperdrive",value:"hyperdrive"},{description:"Stripe-first payments (checkout, subscription, webhooks)",label:"Payments",value:"payment"},{description:"Live presence / who's-online over hibernated WebSockets",label:"Presence",value:"presence"},{description:"Async message queues (push/pull consumers)",label:"Queues",value:"queue"},{description:"Typed R2 buckets + signed URLs (@lunora/storage)",label:"File storage",value:"storage"},{description:"Durable long-running workflows (step.do, sleep, branch)",label:"Workflows",value:"workflow"}],Q=Ce.map(e=>e.value),Vt=e=>e==="email"?we:e,Ut=(e,t)=>{const a=[];for(const r of e.split(",").map(o=>o.trim()).filter(Boolean))Q.includes(r)?a.includes(r)||a.push(r):t(`init: unknown --add feature "${r}" — expected ${Q.join(" | ")}; skipping.`);return a},Ft=async e=>{const t=await ft(e.select),a=await ye(e.text,e.projectName);return{label:"auth",names:[t],transformManifest:r=>be(r,a)}},Ht=async e=>{const t=await e.text(pt,{placeholder:"you@yourdomain.com"}),a=ht(t,r=>{e.logger.warn(r)});return{label:"email",names:[we],transformManifest:a===void 0?void 0:r=>mt(r,a)}},Wt=async(e,t)=>{const a=e.resolveAuthUiItem?.()??"auth-ui-react";if(t)return{label:"auth-ui",names:[a]};const r=await ye(e.text,e.projectName);return{label:"auth-ui",names:[a],transformManifest:o=>be(o,r)}},zt=async e=>{const t=await dt(e.text,e.projectName);return{label:"storage",names:["storage"],transformManifest:a=>ut(a,t)}},qt={auth:Ft,"auth-ui":async(e,t)=>Wt(e,t.includes("auth")),email:Ht,storage:zt},Z=async e=>{if(e.preselected!==void 0&&e.preselected.length>0){await e.applyAll(e.preselected.map(r=>{const o=r==="auth-ui"?e.resolveAuthUiItem?.()??"auth-ui-react":Vt(r);return{label:r,names:[o]}}));return}if(!e.interactive){e.logger.info("tip: add features later with `lunora add <ai|auth|backup|browser|cloudflare-access|crons|email|flags|hyperdrive|payment|presence|queue|storage|workflow>`.");return}const t=await e.multiSelect("Which features do you want to add?",Ce,{defaults:[]});if(t.length===0)return;const a=[];for(const r of t){const o=qt[r];a.push(o?await o(e,t):{label:r,names:[r]})}await e.applyAll(a)},Kt=[{description:"Adds an ignores entry to eslint.config.js",label:"ESLint",value:"eslint"},{description:"Writes .prettierignore",label:"Prettier",value:"prettier"},{description:"Adds negated patterns to biome.json",label:"Biome",value:"biome"},{description:"Writes ignorePatterns to .oxlintrc.json",label:"oxlint (oxc)",value:"oxlint"}],Gt="Which linter/formatter do you use? We'll tell it to skip Lunora's generated files.",Jt=async e=>{const t=e.interactive?await e.multiSelect(Gt,Kt,{defaults:e.detected}):[...e.detected];if(t.length===0)return[];const a=e.apply(t);return gt(a,e.logger),a},N="M 259.500 10.552 C 220.080 15.859, 182.424 32.566, 152.500 58.025 C 110.179 94.031, 85.380 137.183, 77.518 188.500 C 75.410 202.255, 74.569 225.677, 75.796 236.466 C 76.757 244.917, 76.683 245.692, 74.518 249.966 C 63.118 272.466, 53.141 303.876, 51.382 322.799 L 50.718 329.943 71.960 320.471 C 83.643 315.262, 93.326 311, 93.478 311 C 93.630 311, 96.547 316.063, 99.959 322.250 C 103.371 328.438, 107.249 334.850, 108.577 336.500 L 110.990 339.500 110.981 336 C 110.977 334.075, 111.499 324.991, 112.143 315.813 L 113.312 299.127 121.406 293.336 C 132.495 285.403, 149.593 271.554, 161 261.268 C 171.556 251.748, 189.116 235, 188.540 235 C 188.337 235, 183.069 238.648, 176.835 243.106 C 142.318 267.789, 68.537 314, 63.646 314 C 61.843 314, 72.791 281.179, 80.905 262.259 C 92.233 235.845, 107.473 212.389, 132.106 183.453 L 138.451 176 148.268 176 C 176.192 176, 197.512 187.154, 212.868 209.797 C 216.470 215.108, 217.035 216.595, 216.477 219.297 C 211.386 243.968, 202.359 274.496, 193.797 296 C 183.898 320.861, 167.147 352.101, 152.395 373.215 L 147.004 380.930 152.891 385.830 C 161.400 392.911, 165.563 396, 166.594 395.998 C 167.092 395.998, 168.772 391.641, 170.327 386.317 C 176.279 365.934, 188.422 338.749, 200.942 317.778 C 223.060 280.731, 256.432 244.369, 294.500 215.836 C 309.956 204.252, 313.937 201.603, 314.719 202.385 C 315.116 202.783, 315.449 213.096, 315.460 225.304 C 315.474 241.855, 315.021 250.405, 313.680 258.924 C 307.009 301.272, 291.175 336.677, 263.112 372 C 255.259 381.883, 227.182 410.673, 218.516 417.727 L 213.532 421.783 223.439 424.880 C 281.705 443.093, 349.165 436.018, 398.616 406.508 C 446.728 377.797, 483.322 331.466, 497.366 281.481 C 503.381 260.075, 504.480 250.741, 504.491 221 C 504.501 191.997, 503.598 184.047, 497.987 163.732 C 484.768 115.871, 452.505 72.708, 407.718 42.964 C 381.051 25.254, 352.818 14.828, 319.695 10.460 C 305.932 8.645, 273.298 8.695, 259.500 10.552",L=`/* The welcome page is a full-bleed starter — reset the browser's default
94
+ ${Ve}: ${Ue}`)},Ce=[{description:"LLMs via Workers AI (summarize, generate, stream)",label:"AI",value:"ai"},{description:"Sign-up / sign-in (asks which provider)",label:"Authentication",value:"auth"},{description:"Copy-in auth screens for your framework (sign in/up, reset, 2FA)",label:"Auth UI",value:"auth-ui"},{description:"Snapshot + restore your Durable Object data",label:"Backups",value:"backup"},{description:"Headless browser screenshots + PDFs",label:"Browser rendering",value:"browser"},{description:"Zero Trust identity via Cloudflare Access",label:"Cloudflare Access",value:"cloudflare-access"},{description:"Scheduled jobs via Cron Triggers (@lunora/scheduler)",label:"Cron jobs",value:"crons"},{description:"Cloudflare Email Workers + a dev mail catcher",label:"Transactional email",value:"email"},{description:"OpenFeature feature flags (ctx.flags)",label:"Feature flags",value:"flags"},{description:"External Postgres/MySQL via Hyperdrive",label:"Hyperdrive",value:"hyperdrive"},{description:"Stripe-first payments (checkout, subscription, webhooks)",label:"Payments",value:"payment"},{description:"Live presence / who's-online over hibernated WebSockets",label:"Presence",value:"presence"},{description:"Async message queues (push/pull consumers)",label:"Queues",value:"queue"},{description:"Typed R2 buckets + signed URLs (@lunora/storage)",label:"File storage",value:"storage"},{description:"Durable long-running workflows (step.do, sleep, branch)",label:"Workflows",value:"workflow"}],Q=Ce.map(e=>e.value),Vt=e=>e==="email"?we:e,Ut=(e,t)=>{const r=[];for(const a of e.split(",").map(o=>o.trim()).filter(Boolean))Q.includes(a)?r.includes(a)||r.push(a):t(`init: unknown --add feature "${a}" — expected ${Q.join(" | ")}; skipping.`);return r},Ft=async e=>{const t=await ft(e.select),r=await ye(e.text,e.projectName);return{label:"auth",names:[t],transformManifest:a=>be(a,r)}},Ht=async e=>{const t=await e.text(pt,{placeholder:"you@yourdomain.com"}),r=ht(t,a=>{e.logger.warn(a)});return{label:"email",names:[we],transformManifest:r===void 0?void 0:a=>mt(a,r)}},Wt=async(e,t)=>{const r=e.resolveAuthUiItem?.()??"auth-ui-react";if(t)return{label:"auth-ui",names:[r]};const a=await ye(e.text,e.projectName);return{label:"auth-ui",names:[r],transformManifest:o=>be(o,a)}},zt=async e=>{const t=await dt(e.text,e.projectName);return{label:"storage",names:["storage"],transformManifest:r=>ut(r,t)}},qt={auth:Ft,"auth-ui":async(e,t)=>Wt(e,t.includes("auth")),email:Ht,storage:zt},Z=async e=>{if(e.preselected!==void 0&&e.preselected.length>0)return e.applyAll(e.preselected.map(a=>{const o=a==="auth-ui"?e.resolveAuthUiItem?.()??"auth-ui-react":Vt(a);return{label:a,names:[o]}}));if(!e.interactive)return e.logger.info("tip: add features later with `lunora add <ai|auth|backup|browser|cloudflare-access|crons|email|flags|hyperdrive|payment|presence|queue|storage|workflow>`."),!0;const t=await e.multiSelect("Which features do you want to add?",Ce,{defaults:[]});if(t.length===0)return!0;const r=[];for(const a of t){const o=qt[a];r.push(o?await o(e,t):{label:a,names:[a]})}return await e.applyAll(r),!0},Kt=[{description:"Adds an ignores entry to eslint.config.js",label:"ESLint",value:"eslint"},{description:"Writes .prettierignore",label:"Prettier",value:"prettier"},{description:"Adds negated patterns to biome.json",label:"Biome",value:"biome"},{description:"Writes ignorePatterns to .oxlintrc.json",label:"oxlint (oxc)",value:"oxlint"}],Gt="Which linter/formatter do you use? We'll tell it to skip Lunora's generated files.",Jt=async e=>{const t=e.interactive?await e.multiSelect(Gt,Kt,{defaults:e.detected}):[...e.detected];if(t.length===0)return[];const r=e.apply(t);return gt(r,e.logger),r},N="M 259.500 10.552 C 220.080 15.859, 182.424 32.566, 152.500 58.025 C 110.179 94.031, 85.380 137.183, 77.518 188.500 C 75.410 202.255, 74.569 225.677, 75.796 236.466 C 76.757 244.917, 76.683 245.692, 74.518 249.966 C 63.118 272.466, 53.141 303.876, 51.382 322.799 L 50.718 329.943 71.960 320.471 C 83.643 315.262, 93.326 311, 93.478 311 C 93.630 311, 96.547 316.063, 99.959 322.250 C 103.371 328.438, 107.249 334.850, 108.577 336.500 L 110.990 339.500 110.981 336 C 110.977 334.075, 111.499 324.991, 112.143 315.813 L 113.312 299.127 121.406 293.336 C 132.495 285.403, 149.593 271.554, 161 261.268 C 171.556 251.748, 189.116 235, 188.540 235 C 188.337 235, 183.069 238.648, 176.835 243.106 C 142.318 267.789, 68.537 314, 63.646 314 C 61.843 314, 72.791 281.179, 80.905 262.259 C 92.233 235.845, 107.473 212.389, 132.106 183.453 L 138.451 176 148.268 176 C 176.192 176, 197.512 187.154, 212.868 209.797 C 216.470 215.108, 217.035 216.595, 216.477 219.297 C 211.386 243.968, 202.359 274.496, 193.797 296 C 183.898 320.861, 167.147 352.101, 152.395 373.215 L 147.004 380.930 152.891 385.830 C 161.400 392.911, 165.563 396, 166.594 395.998 C 167.092 395.998, 168.772 391.641, 170.327 386.317 C 176.279 365.934, 188.422 338.749, 200.942 317.778 C 223.060 280.731, 256.432 244.369, 294.500 215.836 C 309.956 204.252, 313.937 201.603, 314.719 202.385 C 315.116 202.783, 315.449 213.096, 315.460 225.304 C 315.474 241.855, 315.021 250.405, 313.680 258.924 C 307.009 301.272, 291.175 336.677, 263.112 372 C 255.259 381.883, 227.182 410.673, 218.516 417.727 L 213.532 421.783 223.439 424.880 C 281.705 443.093, 349.165 436.018, 398.616 406.508 C 446.728 377.797, 483.322 331.466, 497.366 281.481 C 503.381 260.075, 504.480 250.741, 504.491 221 C 504.501 191.997, 503.598 184.047, 497.987 163.732 C 484.768 115.871, 452.505 72.708, 407.718 42.964 C 381.051 25.254, 352.818 14.828, 319.695 10.460 C 305.932 8.645, 273.298 8.695, 259.500 10.552",L=`/* The welcome page is a full-bleed starter — reset the browser's default
95
95
  body margin/padding so it sits flush; everything else is scoped under
96
96
  .lunora-welcome (collision-safe). */
97
97
  body {
@@ -830,7 +830,7 @@ export default function App() {
830
830
  <div class="lw-foot">Running on Lunora · Vite + Svelte</div>
831
831
  </div>
832
832
  </div>
833
- `,ea=`import "./style.css";
833
+ `,er=`import "./style.css";
834
834
 
835
835
  import { LunoraClient } from "lunorash/client";
836
836
 
@@ -997,7 +997,7 @@ const count = document.querySelector<HTMLSpanElement>("#lw-count")!;
997
997
  client.onUpdate(api.messages.list, { channelId: "channel:demo" }, (result) => {
998
998
  count.textContent = String(result.messages.length);
999
999
  });
1000
- `,T="const url = (import.meta.env.VITE_LUNORA_URL as string | undefined) ?? globalThis.location.origin;",ta=`import "./index.css";
1000
+ `,T="const url = (import.meta.env.VITE_LUNORA_URL as string | undefined) ?? globalThis.location.origin;",tr=`import "./index.css";
1001
1001
 
1002
1002
  import { LunoraProvider } from "@lunora/react";
1003
1003
  import { LunoraClient } from "lunorash/client";
@@ -1025,7 +1025,7 @@ createRoot(root).render(
1025
1025
  </LunoraProvider>
1026
1026
  </StrictMode>,
1027
1027
  );
1028
- `,aa=`import "./style.css";
1028
+ `,rr=`import "./style.css";
1029
1029
 
1030
1030
  import { createLunora } from "@lunora/vue";
1031
1031
  import { LunoraClient } from "lunorash/client";
@@ -1036,7 +1036,7 @@ import App from "./App.vue";
1036
1036
  // Provide one LunoraClient at the app root via the Vue plugin form.
1037
1037
  ${T}
1038
1038
  createApp(App).use(createLunora(new LunoraClient({ url }))).mount("#app");
1039
- `,ra=`import "./index.css";
1039
+ `,ar=`import "./index.css";
1040
1040
 
1041
1041
  import { LunoraProvider } from "@lunora/solid";
1042
1042
  import { LunoraClient } from "lunorash/client";
@@ -1056,7 +1056,7 @@ render(
1056
1056
  ),
1057
1057
  root!,
1058
1058
  );
1059
- `,oa=`<script lang="ts">
1059
+ `,or=`<script lang="ts">
1060
1060
  import { setLunoraClient } from "@lunora/svelte";
1061
1061
  import { LunoraClient } from "lunorash/client";
1062
1062
 
@@ -1067,7 +1067,7 @@ render(
1067
1067
  <\/script>
1068
1068
 
1069
1069
  <App />
1070
- `,na=`import "./app.css";
1070
+ `,nr=`import "./app.css";
1071
1071
 
1072
1072
  import { mount } from "svelte";
1073
1073
 
@@ -1077,7 +1077,7 @@ import Root from "./Root.svelte";
1077
1077
  const app = mount(Root, { target: document.getElementById("app")! });
1078
1078
 
1079
1079
  export default app;
1080
- `,O={react:{adapter:"@lunora/react",createViteTemplate:"react-ts",files:[{contents:ta,path:"src/main.tsx"},{contents:Yt,path:"src/App.tsx"},{contents:L,path:"src/index.css"}],label:"React"},solid:{adapter:"@lunora/solid",createViteTemplate:"solid-ts",files:[{contents:ra,path:"src/index.tsx"},{contents:Qt,path:"src/App.tsx"},{contents:L,path:"src/index.css"}],label:"Solid"},svelte:{adapter:"@lunora/svelte",createViteTemplate:"svelte-ts",files:[{contents:oa,path:"src/Root.svelte"},{contents:na,path:"src/main.ts"},{contents:Zt,path:"src/App.svelte"},{contents:L,path:"src/app.css"}],label:"Svelte"},vanilla:{adapter:"lunorash/client",createViteTemplate:"vanilla-ts",files:[{contents:ea,path:"src/main.ts"},{contents:L,path:"src/style.css"}],label:"Vanilla"},vue:{adapter:"@lunora/vue",createViteTemplate:"vue-ts",files:[{contents:aa,path:"src/main.ts"},{contents:Xt,path:"src/App.vue"},{contents:L,path:"src/style.css"}],label:"Vue"}},P=e=>Object.hasOwn(O,e),sa=`import type { Middleware } from "lunorash/server";
1080
+ `,O={react:{adapter:"@lunora/react",createViteTemplate:"react-ts",files:[{contents:tr,path:"src/main.tsx"},{contents:Yt,path:"src/App.tsx"},{contents:L,path:"src/index.css"}],label:"React"},solid:{adapter:"@lunora/solid",createViteTemplate:"solid-ts",files:[{contents:ar,path:"src/index.tsx"},{contents:Qt,path:"src/App.tsx"},{contents:L,path:"src/index.css"}],label:"Solid"},svelte:{adapter:"@lunora/svelte",createViteTemplate:"svelte-ts",files:[{contents:or,path:"src/Root.svelte"},{contents:nr,path:"src/main.ts"},{contents:Zt,path:"src/App.svelte"},{contents:L,path:"src/app.css"}],label:"Svelte"},vanilla:{adapter:"lunorash/client",createViteTemplate:"vanilla-ts",files:[{contents:er,path:"src/main.ts"},{contents:L,path:"src/style.css"}],label:"Vanilla"},vue:{adapter:"@lunora/vue",createViteTemplate:"vue-ts",files:[{contents:rr,path:"src/main.ts"},{contents:Xt,path:"src/App.vue"},{contents:L,path:"src/style.css"}],label:"Vue"}},P=e=>Object.hasOwn(O,e),sr=`import type { Middleware } from "lunorash/server";
1081
1081
  import { defineSchemaExtension, defineTable, definePlugin, v } from "lunorash/server";
1082
1082
  import { createDbStore, RateLimiter } from "lunorash/ratelimit";
1083
1083
  import type { RateLimitConfigMap } from "lunorash/ratelimit";
@@ -1117,7 +1117,7 @@ export const ratelimit = definePlugin("ratelimit", {
1117
1117
  }),
1118
1118
  middleware,
1119
1119
  });
1120
- `,ia=`import { ratelimit } from "./ratelimit/schema.js";
1120
+ `,ir=`import { ratelimit } from "./ratelimit/schema.js";
1121
1121
  import { defineSchema, defineTable, v } from "lunorash/server";
1122
1122
 
1123
1123
  export default defineSchema({
@@ -1128,7 +1128,7 @@ export default defineSchema({
1128
1128
  .shardBy("channelId")
1129
1129
  .index("by_channel", ["channelId"]),
1130
1130
  }).extend(ratelimit.extension);
1131
- `,la=`import { RateLimiter, rateLimit, createDbStore } from "lunorash/ratelimit";
1131
+ `,lr=`import { RateLimiter, rateLimit, createDbStore } from "lunorash/ratelimit";
1132
1132
 
1133
1133
  import { mutation, query, v } from "#lunora/_generated/server.js";
1134
1134
 
@@ -1139,7 +1139,7 @@ const limiter = (ctx: { db: unknown }) => new RateLimiter({
1139
1139
  store: createDbStore({ db: ctx.db as never, table: "ratelimit_buckets" }),
1140
1140
  });
1141
1141
 
1142
- export const list = query.input({ channelId: v.string().meta({ schema: { maxLength: 256 } }), limit: v.optional(v.number()) }).query(async ({ args, ctx }) => {
1142
+ export const list = query.input({ channelId: v.string().max(256), limit: v.optional(v.number()) }).query(async ({ args, ctx }) => {
1143
1143
  const messages = await ctx.db
1144
1144
  .query("messages")
1145
1145
  .withIndex("by_channel", (q) => q.eq("channelId", args.channelId))
@@ -1149,14 +1149,14 @@ export const list = query.input({ channelId: v.string().meta({ schema: { maxLeng
1149
1149
  });
1150
1150
 
1151
1151
  export const send = mutation
1152
- .input({ channelId: v.string().meta({ schema: { maxLength: 256 } }), text: v.string().meta({ schema: { maxLength: 4096 } }) })
1152
+ .input({ channelId: v.string().max(256), text: v.string().max(4096) })
1153
1153
  .use(rateLimit(limiter, "send", { key: (ctx) => ctx.auth.userId ?? "anon" }))
1154
1154
  .mutation(async ({ args, ctx }) => {
1155
1155
  const id = await ctx.db.insert("messages", { channelId: args.channelId, text: args.text });
1156
1156
 
1157
1157
  return { channelId: args.channelId, id, text: args.text };
1158
1158
  });
1159
- `,ca=`import type { ShardNamespaceLike } from "lunorash/runtime";
1159
+ `,cr=`import type { ShardNamespaceLike } from "lunorash/runtime";
1160
1160
 
1161
1161
  import { defineApp } from "../lunora/_generated/app.js";
1162
1162
 
@@ -1170,7 +1170,7 @@ const app = defineApp<Env>()
1170
1170
 
1171
1171
  export const ShardDO = app.ShardDO;
1172
1172
  export default app;
1173
- `,da=`{
1173
+ `,dr=`{
1174
1174
  "$schema": "node_modules/wrangler/config-schema.json",
1175
1175
  "name": "__NAME__",
1176
1176
  "main": "src/server.ts",
@@ -1182,23 +1182,23 @@ export default app;
1182
1182
  "migrations": [{ "tag": "v1", "new_sqlite_classes": ["ShardDO"] }],
1183
1183
  "observability": { "enabled": true, "head_sampling_rate": 1 },
1184
1184
  }
1185
- `,ua=[".wrangler",".env",".env.*","!.env.example",".dev.vars",".dev.vars.*","!.dev.vars.example",".lunora/",".lunora-cache","lunora/_generated"],pa=`# Lunora endpoint for the browser client.
1185
+ `,ur=[".wrangler",".env",".env.*","!.env.example",".dev.vars",".dev.vars.*","!.dev.vars.example",".lunora/",".lunora-cache","lunora/_generated"],pr=`# Lunora endpoint for the browser client.
1186
1186
  # Vite statically replaces \`import.meta.env.VITE_LUNORA_URL\` at \`vite dev\` / build.
1187
1187
  # Leave it unset to use the page origin; set it to point at a deployed Worker:
1188
1188
  #
1189
1189
  # VITE_LUNORA_URL=https://my-app.example.workers.dev
1190
- `,ha={"@cloudflare/workers-types":"^4.20260611.1",wrangler:"^4.100.0"},x=(e,t,a,r)=>{const o=u(e,t);M(A(o),{recursive:!0}),v(o,a,"utf8"),r.push(o)},ma=/\r?\n/,fa=e=>{const t=u(e,".gitignore"),a=m(t)?b(t,"utf8"):"",r=new Set(a.split(ma)),o=ua.filter(s=>!r.has(s));if(o.length===0)return;const n=a.length>0&&!a.endsWith(`
1190
+ `,hr={"@cloudflare/workers-types":"^4.20260611.1",wrangler:"^4.100.0"},x=(e,t,r,a)=>{const o=u(e,t);M(A(o),{recursive:!0}),v(o,r,"utf8"),a.push(o)},mr=/\r?\n/,fr=e=>{const t=u(e,".gitignore"),r=m(t)?b(t,"utf8"):"",a=new Set(r.split(mr)),o=ur.filter(s=>!a.has(s));if(o.length===0)return;const n=r.length>0&&!r.endsWith(`
1191
1191
  `)?`
1192
- `:"";v(t,`${a}${n}
1192
+ `:"";v(t,`${r}${n}
1193
1193
  # Lunora
1194
1194
  ${o.join(`
1195
1195
  `)}
1196
- `,"utf8")},D=e=>e==="lunorash"||e.startsWith("@lunora/"),va=(e,t,a,r)=>D(e)?r.get(e)??a:t,k=(e,t,a)=>({...e,[t]:a}),ee=(e,t,a)=>Object.fromEntries(Object.entries(e).map(([r,o])=>[r,va(r,o,t,a)])),ga=async(e,t,a,r)=>{const o=u(e,"package.json"),n=JSON.parse(b(o,"utf8"));let s=k(n.dependencies??{},"lunorash",r);s=k(s,"@lunora/ratelimit",r),a.adapter.startsWith("@lunora/")&&(s=k(s,a.adapter,r));for(const[c,p]of Object.entries(a.extraDependencies??{}))s=k(s,c,p);let i=k(n.devDependencies??{},"@lunora/vite",r);i=k(i,"@lunora/studio",r);for(const[c,p]of Object.entries(ha))i=k(i,c,p);const l=[...Object.keys(s),...Object.keys(i)].filter(c=>D(c)),d=await ce(l,r);n.name=t,n.imports={...n.imports,"#lunora/*":"./lunora/*"},n.dependencies=ee(s,r,d),n.devDependencies=ee(i,r,d),n.scripts={...n.scripts,codegen:"lunora codegen",deploy:"vite build && lunora deploy"},v(o,`${JSON.stringify(n,void 0,4)}
1197
- `,"utf8")},wa=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],Se=e=>wa.map(t=>u(e,t)).find(t=>m(t)),ya=(e,t)=>{const a=Se(e);if(a===void 0){t.warn("overlay: no vite.config found in the create-vite base — add `lunora()` to your Vite plugins manually.");return}const r=ke(b(a,"utf8"));r.changed&&v(a,r.code,"utf8")},ba=async e=>{const{adapter:t,distTag:a,logger:r,name:o,target:n}=e,s=[];x(n,u("lunora","ratelimit","schema.ts"),sa,s),x(n,u("lunora","schema.ts"),ia,s),x(n,u("lunora","messages.ts"),la,s),x(n,u("src","server.ts"),ca,s),x(n,"wrangler.jsonc",da.replaceAll("__NAME__",o),s),x(n,".env.example",pa,s);for(const i of t.files)x(n,i.path,i.contents,s);return ya(n,r),await ga(n,o,t,a),fa(n),s},xa=["lunar","silver","silent","waning","waxing","crescent","cosmic","stellar","orbital","gibbous","twilight","midnight","shimmering","drifting","weightless"],ka=["moon","tide","crater","comet","eclipse","halo","orbit","nebula","voyager","lander","rover","beacon","harbor","meadow","fox"],te=e=>e[Math.floor(Math.random()*e.length)],Ca=()=>`${te(xa)}-${te(ka)}`,Sa=async()=>wt.lookup("github.com").then(()=>!0,()=>!1),La=/^(?:gh|github):([^/]+)\/([^#/]+)(?:\/[^#]*)?(?:#(.+))?$/,Le=e=>{const t=La.exec(e);if(t===null)return;const[,a,r,o]=t;if(!(a===void 0||r===void 0))return{owner:a,ref:o??"HEAD",repo:r}},Ma=async e=>{const t=Le(e);if(t===void 0)return;const a=`https://codeload.github.com/${t.owner}/${t.repo}/tar.gz/${t.ref}`;try{const r=await fetch(a,{method:"HEAD"});return r.status===404?!1:r.ok?!0:void 0}catch{return}},Me=async e=>e.isLocal||!(e.source===void 0||Le(e.source)!==void 0)?!0:await Sa()?e.source!==void 0&&await Ma(e.source)===!1?(e.logger.error(`template source not found: ${e.source} — double-check --ref / --source, or browse the templates at https://lunora.sh/docs.`),!1):!0:(e.logger.error("you appear to be offline — connect to the internet and try again, or scaffold from a local template with `--from <dir>`."),!1),y={extras:"Let's finish setting up your app.",framework:"Which framework should we launch?",git:"Initialize a new git repository? (optional)",install:"Install dependencies now?",name:"Where should we land your project?",nextHeader:"Liftoff confirmed — explore your project!",packageManager:"Which package manager?"},Aa=new Set([".gitignore",".html",".js",".json",".jsonc",".md",".mjs",".ts",".tsx"]),Ea=`import { defineConfig } from "vite";
1196
+ `,"utf8")},D=e=>e==="lunorash"||e.startsWith("@lunora/"),vr=(e,t,r,a)=>D(e)?a.get(e)??r:t,k=(e,t,r)=>({...e,[t]:r}),ee=(e,t,r)=>Object.fromEntries(Object.entries(e).map(([a,o])=>[a,vr(a,o,t,r)])),gr=async(e,t,r,a)=>{const o=u(e,"package.json"),n=JSON.parse(b(o,"utf8"));let s=k(n.dependencies??{},"lunorash",a);s=k(s,"@lunora/ratelimit",a),r.adapter.startsWith("@lunora/")&&(s=k(s,r.adapter,a));for(const[c,p]of Object.entries(r.extraDependencies??{}))s=k(s,c,p);let i=k(n.devDependencies??{},"@lunora/vite",a);i=k(i,"@lunora/studio",a);for(const[c,p]of Object.entries(hr))i=k(i,c,p);const l=[...Object.keys(s),...Object.keys(i)].filter(c=>D(c)),d=await ce(l,a);n.name=t,n.imports={...n.imports,"#lunora/*":"./lunora/*"},n.dependencies=ee(s,a,d),n.devDependencies=ee(i,a,d),n.scripts={...n.scripts,codegen:"lunora codegen",deploy:"vite build && lunora deploy"},v(o,`${JSON.stringify(n,void 0,4)}
1197
+ `,"utf8")},wr=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],Se=e=>wr.map(t=>u(e,t)).find(t=>m(t)),yr=(e,t)=>{const r=Se(e);if(r===void 0){t.warn("overlay: no vite.config found in the create-vite base — add `lunora()` to your Vite plugins manually.");return}const a=ke(b(r,"utf8"));a.changed&&v(r,a.code,"utf8")},br=async e=>{const{adapter:t,distTag:r,logger:a,name:o,target:n}=e,s=[];x(n,u("lunora","ratelimit","schema.ts"),sr,s),x(n,u("lunora","schema.ts"),ir,s),x(n,u("lunora","messages.ts"),lr,s),x(n,u("src","server.ts"),cr,s),x(n,"wrangler.jsonc",dr.replaceAll("__NAME__",o),s),x(n,".env.example",pr,s);for(const i of t.files)x(n,i.path,i.contents,s);return yr(n,a),await gr(n,o,t,r),fr(n),s},xr=["lunar","silver","silent","waning","waxing","crescent","cosmic","stellar","orbital","gibbous","twilight","midnight","shimmering","drifting","weightless"],kr=["moon","tide","crater","comet","eclipse","halo","orbit","nebula","voyager","lander","rover","beacon","harbor","meadow","fox"],te=e=>e[Math.floor(Math.random()*e.length)],Cr=()=>`${te(xr)}-${te(kr)}`,Sr=async()=>wt.lookup("github.com").then(()=>!0,()=>!1),Lr=/^(?:gh|github):([^/]+)\/([^#/]+)(?:\/[^#]*)?(?:#(.+))?$/,Le=e=>{const t=Lr.exec(e);if(t===null)return;const[,r,a,o]=t;if(!(r===void 0||a===void 0))return{owner:r,ref:o??"HEAD",repo:a}},Mr=async e=>{const t=Le(e);if(t===void 0)return;const r=`https://codeload.github.com/${t.owner}/${t.repo}/tar.gz/${t.ref}`;try{const a=await fetch(r,{method:"HEAD"});return a.status===404?!1:a.ok?!0:void 0}catch{return}},Me=async e=>e.isLocal||!(e.source===void 0||Le(e.source)!==void 0)?!0:await Sr()?e.source!==void 0&&await Mr(e.source)===!1?(e.logger.error(`template source not found: ${e.source} — double-check --ref / --source, or browse the templates at https://lunora.sh/docs.`),!1):!0:(e.logger.error("you appear to be offline — connect to the internet and try again, or scaffold from a local template with `--from <dir>`."),!1),y={extras:"Let's finish setting up your app.",framework:"Which framework should we launch?",git:"Initialize a new git repository? (optional)",install:"Install dependencies now?",name:"Where should we land your project?",nextHeader:"Liftoff confirmed — explore your project!",packageManager:"Which package manager?"},Ar=new Set([".gitignore",".html",".js",".json",".jsonc",".md",".mjs",".ts",".tsx"]),Er=`import { defineConfig } from "vite";
1198
1198
  import { lunora } from "@lunora/vite";
1199
1199
 
1200
1200
  export default defineConfig({ plugins: [lunora()] });
1201
- `,Na=`import { defineSchema, defineTable, v } from "@lunora/server";
1201
+ `,Nr=`import { defineSchema, defineTable, v } from "@lunora/server";
1202
1202
 
1203
1203
  export default defineSchema({
1204
1204
  messages: defineTable({
@@ -1208,7 +1208,7 @@ export default defineSchema({
1208
1208
  .shardBy("channelId")
1209
1209
  .index("by_channel", ["channelId"]),
1210
1210
  });
1211
- `,Ia=`import { mutation, query, v } from "./_generated/server";
1211
+ `,Ir=`import { mutation, query, v } from "./_generated/server";
1212
1212
 
1213
1213
  export const list = query
1214
1214
  .input({ channelId: v.id("channels"), limit: v.optional(v.number()) })
@@ -1221,8 +1221,8 @@ export const send = mutation
1221
1221
  .mutation(async ({ args }) => {
1222
1222
  return { channelId: args.channelId, text: args.text };
1223
1223
  });
1224
- `,$a="gh:anolilab/lunora/templates",_a=e=>{const t=e.lastIndexOf(".");return t===-1?!1:Aa.has(e.slice(t))},Ra=(e,t)=>e.replaceAll("{{name}}",t),Ta=async(e,t)=>{const a=new Set;for(const r of e)if(E(r)==="package.json")try{const o=JSON.parse(b(r,"utf8"));for(const n of["dependencies","devDependencies"])for(const s of Object.keys(o[n]??{}))D(s)&&a.add(s)}catch{}return ce(a,t)},Oa=(e,t,a)=>{let r;try{r=JSON.parse(e)}catch{return e}let o=e;for(const n of["dependencies","devDependencies"])for(const s of Object.keys(r[n]??{})){if(!D(s))continue;const i=a.get(s)??t,l=Ye(o,[n,s],i,{formattingOptions:{insertSpaces:!0,tabSize:4}});o=Xe(o,l)}return o},Pa=["@parcel/watcher","esbuild","lmdb","msgpackr-extract","rs-module-lexer","sharp","unrs-resolver","vue-demi","workerd"],Da=["cpu-features","protobufjs","ssh2"],Ae="pnpm-workspace.yaml",Ba=()=>["# pnpm reads its settings from here (the package.json `pnpm` field is no longer read).","# Pre-approve the toolchain's native build scripts so `pnpm install` runs them","# without the interactive `pnpm approve-builds` step; deny the optional native","# builds a scaffold doesn't need (so no C/C++ toolchain is required).","allowBuilds:",...Pa.map(e=>` '${e}': true`),...Da.map(e=>` '${e}': false`),""].join(`
1225
- `),q=e=>{const t=[];for(const a of Ge(e,{includeDirs:!1,includeFiles:!0}))Pe(a.path).isSymbolicLink()||t.push(a.path);return t},Ee=async(e,t,a)=>{const r=q(e),o=[],n=de(),s=await Ta(r,n);for(const i of r){const l=Je(e,i),d=u(t,l);M(A(d),{recursive:!0});const c=b(i);let p=_a(i)?Ra(c.toString("utf8"),a):void 0;p!==void 0&&E(i)==="package.json"&&(p=Oa(p,n,s)),p===void 0?v(d,c):v(d,p,"utf8"),o.push(d)}return o},j=(e,t,a)=>t!==void 0&&t.length>0?t:`${$a}/${e}#${ue(a)}`,ja=e=>e.includes("..")?!1:e.startsWith("gh:")||e.startsWith("github:")||e.startsWith("https://"),S=(e,t)=>{e.info(`[dry-run] would ${t}`)},K=(e,t,a)=>{g()&&process.stdout.write(`
1226
- `),e.success(`scaffolded ${String(t.length)} files into ${a}`)},Va=(e,t)=>{const{args:a,command:r}=qe(e,t);return`${r} ${a.join(" ")}`},Ne=(e,t)=>{let a=ie(e);for(;;){if(t(a))return!0;const r=A(a);if(r===a)return!1;a=r}},Ua=e=>{if(m(u(e,Ae)))return!0;const t=u(e,"package.json");if(!m(t))return!1;try{return JSON.parse(b(t,"utf8")).workspaces!==void 0}catch{return!1}},Ie=e=>Ne(e,Ua),Fa=e=>Ne(e,t=>m(u(t,".git"))),Ha=async(e,t)=>{if(e.yes===!0||!g()||Fa(A(t)))return;if(!await fe(y.git,{badge:f.git,defaultYes:!1})){await ve("Sounds good! You can always run git init manually.");return}if(e.dryRun===!0){S(e.logger,"initialize a git repository");return}const a=e.spawner??pe;(await it("Initializing a git repository…",()=>a({args:["init"],command:"git",cwd:t}))).code===0?await R("git","Initialized an empty git repository."):e.logger.warn("`git init` failed — initialize it yourself later with `git init`.")},Wa=async(e,t,a,r)=>{const o=[{code:`cd ./${e}`,lead:"Enter your project directory using"}];t===void 0&&o.push({code:`${a} install`,lead:"Install dependencies with",tail:r?" from the workspace root":void 0}),o.push({code:We(a,"dev"),lead:"Run",tail:" to start the dev server."},{code:"lunora add",lead:"Add features like auth or storage using"});const n=[{code:"https://lunora.sh/docs",lead:"Read the docs at"},{code:"https://lunora.sh/chat",lead:"Stuck? Join the chat at"}];if(g()){await lt(f.next,y.nextHeader,o,n);return}const s=o.map(i=>`${i.lead} ${i.code}${i.tail??""}`);s.push("",...n.map(i=>`${i.lead} ${i.code}${i.tail??""}`)),await R("next",y.nextHeader,s.join(`
1227
- `))},za=e=>e.yes!==!0&&(e.installPrompt!==void 0||g()),qa=async(e,t)=>{if(!za(e)||Ie(A(t)))return;const a=He(e.packageManagerProbe),[r]=a;if(r===void 0)return;if(!await(e.installPrompt?.confirmInstall??(async()=>fe(y.install,{badge:f.deps,defaultYes:!0})))()){await ve("No problem! Remember to install dependencies after setup.");return}let n=r;if(a.length>1&&(n=e.installPrompt?await e.installPrompt.selectManager(a):await W(y.packageManager,a.map(c=>({label:c,value:c})),{badge:f.deps,default:r})??r),e.dryRun===!0){S(e.logger,`install dependencies with ${n}`);return}if(n==="pnpm"){const c=u(t,Ae);m(c)||v(c,Ba(),"utf8")}const s=e.spawner??pe,{args:i,command:l}=se(n);await R("deps",`Installing dependencies with ${n}…`);const d=await s({args:i,command:l,cwd:t});if(d.code!==0){e.logger.warn(`\`${l} install\` exited with code ${String(d.code)} — run it yourself in ${E(t)}/.`);return}return await R("deps",`Dependencies installed with ${n}.`),n},Ka=async(e,t,a,r,o)=>{const n=u(e,t);if(!m(n))return o.error(`template not found in local source: ${n}`),{code:1,files:[],target:a};const s=await Ee(n,a,r);return K(o,s,a),{code:0,files:s,target:a}},Ga=async e=>{const{logger:t,name:a,ref:r,source:o,target:n,templateType:s}=e,i=oe(u(ne(),"lunora-init-fetch-")),l=u(i,"template");try{const d=o!==void 0&&o.length>0?r:await at(r,t),c=j(s,o,d);let p,h=[];await ge([{label:`${s} template fetched`,run:async()=>{p=await le(c,{cwd:i,dir:l,force:!0,install:!1,silent:!0})}},{label:`files copied into ${a}/`,run:async()=>{h=await Ee(l,n,a)}}],{end:"Project initialized!",start:"Project initializing…"});const I=q(l);return g()&&process.stdout.write(`
1228
- `),t.info(p?.commit?`template: ${p.source} @ ${p.commit} (${String(I.length)} files)`:`template: ${p?.source??c} (${String(I.length)} files)`),K(t,h,n),{code:0,files:h,target:n}}catch(d){if(d instanceof H)throw d;const{hints:c,message:p}=Bt(d,{ref:ue(r),remote:j(s,o,r),templateType:s});t.error(p);for(const h of c)t.warn(h);return{code:1,files:[],target:n}}finally{_(i,{force:!0,recursive:!0})}},Ja=e=>{for(const t of["_gitignore","_npmrc","_gitattributes"]){const a=u(e,t);m(a)&&Oe(a,u(e,`.${t.slice(1)}`))}},Ya=async e=>{const{framework:t,logger:a,name:r,overlayBaseFrom:o,target:n}=e,s=O[t],i=oe(u(ne(),"lunora-vite-base-"));try{let l;if(o!==void 0&&(l=u(o,`template-${s.createViteTemplate}`),!m(l)))return a.error(`create-vite base not found on disk: ${l}`),{code:1,files:[],target:n};const d=async()=>{if(l!==void 0){G(l,n,{recursive:!0});return}const p=u(i,"base"),h=`github:vitejs/vite/packages/create-vite/template-${s.createViteTemplate}#main`;await le(h,{cwd:i,dir:p,force:!0,install:!1,silent:!0}),Ja(p),G(p,n,{recursive:!0})};let c=[];return await ge([{label:`create-vite (${s.label}) base ready`,run:d},{label:`Lunora overlay applied (${s.label})`,run:async()=>{c=await ba({adapter:s,distTag:de(),logger:a,name:r,target:n})}}],{end:"Project initialized!",start:"Project initializing…"}),K(a,c,n),{code:0,files:[...q(n)],target:n}}catch(l){if(l instanceof H)throw l;const d=l instanceof Error?l.message:String(l);return a.error(`failed to scaffold the ${s.label} base: ${d}`),{code:1,files:[],target:n}}finally{_(i,{force:!0,recursive:!0})}},V=(e,t,a,r,o)=>(o.error(`init --in-place: could not ${e} ${t}: ${a instanceof Error?a.message:String(a)}`),{code:1,files:[],target:r}),Xa=(e,t)=>{const a=u(e,"vite.config.ts");try{v(a,Ea,"utf8")}catch(r){return V("write",a,r,e,t)}return t.success(`created ${a} with lunora() plugin`),{code:0,files:[a],target:e}},Qa=(e,t,a)=>{let r;try{r=b(e,"utf8")}catch(n){return V("read",e,n,t,a)}const o=ke(r);if(!o.changed)return a.info(`${e}: ${o.reason??"no changes needed"}`),{code:0,files:[],target:t};try{v(e,o.code,"utf8")}catch(n){return V("write",e,n,t,a)}return a.success(`patched ${e} — added lunora() plugin`),{code:0,files:[e],target:t}},Za=(e,t)=>{const a=u(e,"lunora"),r=u(a,"schema.ts");if(m(r))return t.info(`lunora/ already present — left ${r} untouched`),[];const o=[];try{M(a,{recursive:!0}),v(r,Na,"utf8"),o.push(r);const n=u(a,"messages.ts");m(n)||(v(n,Ia,"utf8"),o.push(n)),t.success(`scaffolded lunora/ (${String(o.length)} file(s))`)}catch(n){const s=n instanceof Error?n.message:String(n);t.error(`init --here: could not scaffold lunora/: ${s}`)}return o},er=(e,t,a)=>{const{adapter:r,class:o,framework:n}=e;a.info(""),a.info(`detected framework: ${n} (class ${o})`),a.info("next steps:"),a.info(` 1. install the adapter: ${Va(t,[r,"@lunora/client","@lunora/runtime","@lunora/server"])}`),a.info(" 2. run codegen: lunora codegen"),o==="A"?(a.info(" 3. compose one worker: wrap your worker entry with"),a.info(" createWorker({ httpRouter: <your framework SSR handler>, shardDO: ShardDO, ... })"),a.info(` 4. add the provider: mount the ${r} provider in your root layout/route`),a.info(" 5. make a loader live: preloadQuery() in a loader, usePreloadedQuery() in the component"),a.info(" see https://lunora.sh/docs/frameworks/reactive-loaders")):o==="B"?(a.info(" 3. inject Lunora: mount Lunora realtime under /_lunora/* in your server hook"),a.info(` (${n} owns its Cloudflare adapter — Lunora composes into its server entry)`),a.info(` 4. add the provider: mount the ${r} provider in your root layout`),a.info(" 5. read the guide: https://lunora.sh/docs/frameworks/deploy")):(a.info(" 3. add the provider: wrap your app with the LunoraProvider from @lunora/react"),a.info(" 4. read the guide: https://lunora.sh/docs/frameworks/bring-your-framework")),a.info("")},tr=(e,t,a)=>{const r=Se(e);return r===void 0?t==="sveltekit"||t==="nuxt"||t==="astro"?(a.info(`no Vite config found — ${t} wires Lunora through its server entry (see next steps)`),{code:0,files:[],target:e}):Xa(e,a):Qa(r,e,a)},ar=(e,t)=>{const a=At(e),r=tr(e,a.framework,t);if(r.code!==0)return r;const o=Za(e,t);return er(a,U(e),t),{code:0,files:[...r.files,...o],target:e}},rr=e=>e.yes!==!0&&(e.prompt!==void 0||(e.interactive??g())),ae=async(e,t,a)=>{a.dryRun!==!0&&await Jt({apply:r=>Ke(e,r),detected:ze(e),interactive:t,logger:a.logger,multiSelect:a.lintPrompt??((r,o,n)=>me(r,o,{...n,badge:f.add}))})},or=async(e,t)=>{const a=rr(e),r=e.add===void 0?[]:Ut(e.add,s=>{e.logger.warn(s)}),n={applyAll:async s=>{if(s.length===0)return!0;if(e.dryRun===!0)return S(e.logger,`add ${s.map(h=>h.label).join(", ")}`),!0;const i=[],l=g()?{error:h=>{i.push({level:"error",message:h})},info:()=>{},success:()=>{},warn:h=>{i.push({level:"warn",message:h})}}:e.logger,d=s.map(h=>({running:`adding ${h.label}…`,task:()=>yt({allowUnsafeSource:e.allowUnsafeSource,cwd:t,from:e.registryFrom,logger:l,names:[...h.names],ref:e.ref,source:e.registrySource,transformManifest:h.transformManifest,yes:!0})})),c=`added ${s.map(h=>h.label).join(", ")}`,p=await ct(f.add,d,c);for(const{level:h,message:I}of i)e.logger[h](I);return p.every(h=>h.code===0)},interactive:a,logger:e.logger,multiSelect:e.prompt?.multiSelect??((s,i,l)=>me(s,i,{...l,badge:f.add})),preselected:r.length>0?r:void 0,projectName:E(t),resolveAuthUiItem:()=>{try{const s=JSON.parse(b(u(t,"package.json"),"utf8"));return vt({...s.dependencies,...s.devDependencies})??"auth-ui-react"}catch{return"auth-ui-react"}},select:e.prompt?.select??((s,i,l)=>W(s,i,{...l,badge:f.add})),text:e.prompt?.text??((s,i)=>he(s,{...i,badge:f.add}))};if(r.length>0){await Z(n),await ae(t,a,e);return}g()&&await st(y.extras),await Z(n),await ae(t,a,e)},B="react",$e=[{description:"React SPA — official create-vite base + the Lunora layer (the default)",label:"React",value:"react"},{description:"Vue SPA — create-vite base + Lunora",label:"Vue",value:"vue"},{description:"Solid SPA — create-vite base + Lunora",label:"Solid",value:"solid"},{description:"Solid 2.0 SPA — the Solid 2 line (@solidjs/web, vite-plugin-solid 3)",label:"Solid 2",value:"solid-v2"},{description:"Svelte SPA — create-vite base + Lunora",label:"Svelte",value:"svelte"},{description:"Next.js (App Router) — OpenNext on Cloudflare + a standalone Lunora worker",label:"Next.js",value:"next"},{description:"TanStack Start (React) — SSR with live-loader routes",label:"TanStack Start · React",value:"tanstack-start-react"},{description:"TanStack Start (Solid)",label:"TanStack Start · Solid",value:"tanstack-start-solid"},{description:"Next.js App Router on Vite (vinext) — composed into the Lunora worker (experimental)",label:"vinext · App Router",value:"vinext"},{description:"Next.js Pages Router on Vite (vinext) — composed into one worker (experimental)",label:"vinext · Pages Router",value:"vinext-pages"},{description:"React Router (v7, framework mode) — SSR composed into the Lunora worker",label:"React Router",value:"react-router"},{description:"Astro + a standalone Lunora worker",label:"Astro",value:"astro"},{description:"AnalogJS (Angular) — single-worker, Lunora mounted in Nitro",label:"Analog",value:"analog"},{description:"Nuxt (Vue) — single-worker, Lunora mounted in Nitro",label:"Nuxt",value:"nuxt"},{description:"SvelteKit + a standalone Lunora worker",label:"SvelteKit",value:"sveltekit"},{description:"React Native (Expo) — an iOS/Android/web app + a Lunora worker backend",label:"React Native · Expo",value:"expo"},{description:"Worker only — no frontend",label:"Standalone",value:"standalone"}],_e=Object.keys(O).join("|"),Re=$e.filter(e=>!P(e.value)).map(e=>e.value),Te=Re.join("|"),nr=e=>P(e)?{framework:e,kind:"overlay"}:{kind:"template",templateType:e},sr=async e=>e.vite!==void 0?{framework:e.vite,kind:"overlay"}:e.templateType!==void 0?{kind:"template",templateType:e.templateType}:!g()||e.yes===!0?{framework:B,kind:"overlay"}:nr(await W(y.framework,$e,{badge:f.tmpl,default:B})??B),ir=e=>{if(g()||e.yes===!0)return;const t=[];if(e.name===void 0&&t.push("a project name (`lunora init <name>`)"),e.templateType===void 0&&e.vite===void 0&&t.push(`a framework — \`--vite <${_e}>\` for an SPA, or \`-t <${Te}>\` for a bespoke template`),t.length!==0)return`lunora init can't prompt in a non-interactive terminal — provide ${t.join(" and ")}, or pass --yes to accept the defaults.`},lr=async(e,t,a,r)=>P(t)?await Me({isLocal:e.overlayBaseFrom!==void 0,logger:e.logger})?(M(r,{recursive:!0}),Ya({framework:t,logger:e.logger,name:a,overlayBaseFrom:e.overlayBaseFrom,target:r})):{code:1,files:[],target:r}:(e.logger.error(`init: unknown framework "${t}". Supported overlays: ${Object.keys(O).join(", ")}.`),{code:1,files:[],target:r}),cr=async(e,t,a,r)=>e.from!==void 0?await Ka(e.from,t,r,a,e.logger):e.source!==void 0&&e.source.length>0&&!e.allowUnsafeSource&&!ja(e.source)?(e.logger.error(`init: refusing --source ${e.source} — only gh:, github:, or https:// sources are allowed (and may not contain ".."). Re-run with --allow-unsafe-source if you really want this.`),{code:1,files:[],target:r}):await Me({isLocal:!1,logger:e.logger,source:j(t,e.source,e.ref)})?Ga({logger:e.logger,name:a,ref:e.ref,source:e.source,target:r,templateType:t}):{code:1,files:[],target:r},dr=async(e,t,a)=>{await nt("realtime backend on Cloudflare Workers + Durable Objects");const r=ir(e);if(r!==void 0)return e.logger.error(r),{code:1,files:[],target:""};const o=Ca(),n=e.name??await he(y.name,{badge:f.dir,default:o,placeholder:o}),s=await sr(e),i=n.trim();if(i.length===0)return e.logger.error("init: refusing an empty project name — pass a directory name (e.g. `lunora init my-app`)."),{code:1,files:[],target:""};if(i.includes("/")||i.includes("\\")||i===".."||i===".")return e.logger.error(`init: refusing project name "${i}" — must not contain path separators or be "." / "..".`),{code:1,files:[],target:""};const l=ie(t,i),d=m(l);if(d&&re(l).length>0)return e.logger.error(`target directory not empty: ${l}`),{code:1,files:[],target:l};if(e.dryRun===!0){const c=s.kind==="overlay"?`the ${s.framework} create-vite overlay`:`the ${s.templateType} template`;return S(e.logger,`scaffold ${c} into ${l}`),{code:0,files:[],target:l}}return a(l,d),s.kind==="overlay"?lr(e,s.framework,i,l):cr(e,s.templateType,i,l)},ur=(e,t)=>{const{target:a,targetPreExisted:r}=e;if(!(a===void 0||!m(a))){if(r===!0)for(const o of re(a))_(u(a,o),{force:!0,recursive:!0});else _(a,{force:!0,recursive:!0});t.info(`removed the partially-created project at ${a}`)}},pr=async(e,t,a)=>e.inPlace!==!0?dr(e,t,a):e.dryRun===!0?(S(e.logger,`configure Lunora into ${t}`),{code:0,files:[],target:t}):ar(t,e.logger),hr=async(e,t,a)=>{await or(e,t.target);const r=e.inPlace===!0?void 0:await qa(e,t.target);if(e.inPlace!==!0){await Ha(e,t.target);const o=r??U(t.target);await Wa(E(t.target),r,o,Ie(a)),await jt(e.logger)}},mr=(e,t,a)=>{if(t.code!==0||e.ci===void 0)return;if(e.dryRun===!0){S(e.logger,`scaffold a ${e.ci} CI deploy pipeline`);return}const r=e.inPlace===!0?a:t.target;try{const o=U(r);Lt(r,e.ci,o,e.logger)}catch{e.logger.warn(`--ci ${e.ci}: could not detect a package manager for this project — skipped the CI pipeline.`)}},fr=async e=>{const t=e.cwd??process.cwd(),a={};let r;try{r=await pr(e,t,(o,n)=>{a.target=o,a.targetPreExisted=n}),r.code===0&&r.target!==""&&(a.target=void 0,await hr(e,r,t))}catch(o){if(o instanceof H)return ur(a,e.logger),process.stdout.write("\n ✖ Setup cancelled — run `lunora init` again whenever you're ready. 🌙\n"),{code:130,files:[],target:""};throw o}return mr(e,r,t),r},vr=e=>typeof e=="string"&&Re.includes(e),gr=(e,t)=>{if(e!==void 0){if(Ct(e))return e;t.warn(`init: unknown --ci "${e}" — expected github | gitlab; skipping CI scaffold.`)}},wr=e=>e===void 0?{}:vr(e)?{templateType:e}:P(e)?{vite:e}:{error:`init: unknown --template "${e}" — expected a bespoke template (${Te}) or an overlay framework (${_e}).`},jr=Ze(({argument:e,cwd:t,logger:a,options:r})=>{const o=wr(r.template);return"error"in o?(a.error(o.error),{code:1}):fr({add:r.add,allowUnsafeSource:r.allowUnsafeSource===!0,cwd:t,ci:gr(r.ci,a),dryRun:r.dryRun===!0,from:r.from,inPlace:r.here===!0,interactive:r.interactive===!0?!0:void 0,logger:a,name:e[0],ref:r.ref,source:r.source,templateType:o.templateType,vite:r.vite??o.vite,yes:r.yes===!0})});export{jr as execute,vr as isTemplate,wr as resolveTemplateFlag,j as resolveTemplateSource,fr as runInitCommand};
1224
+ `,$r="gh:anolilab/lunora/templates",_r=e=>{const t=e.lastIndexOf(".");return t===-1?!1:Ar.has(e.slice(t))},Rr=(e,t)=>e.replaceAll("{{name}}",t),Tr=async(e,t)=>{const r=new Set;for(const a of e)if(E(a)==="package.json")try{const o=JSON.parse(b(a,"utf8"));for(const n of["dependencies","devDependencies"])for(const s of Object.keys(o[n]??{}))D(s)&&r.add(s)}catch{}return ce(r,t)},Or=(e,t,r)=>{let a;try{a=JSON.parse(e)}catch{return e}let o=e;for(const n of["dependencies","devDependencies"])for(const s of Object.keys(a[n]??{})){if(!D(s))continue;const i=r.get(s)??t,l=Ye(o,[n,s],i,{formattingOptions:{insertSpaces:!0,tabSize:4}});o=Xe(o,l)}return o},Pr=["@parcel/watcher","esbuild","lmdb","msgpackr-extract","rs-module-lexer","sharp","unrs-resolver","vue-demi","workerd"],Dr=["cpu-features","protobufjs","ssh2"],Ae="pnpm-workspace.yaml",Br=()=>["# pnpm reads its settings from here (the package.json `pnpm` field is no longer read).","# Pre-approve the toolchain's native build scripts so `pnpm install` runs them","# without the interactive `pnpm approve-builds` step; deny the optional native","# builds a scaffold doesn't need (so no C/C++ toolchain is required).","allowBuilds:",...Pr.map(e=>` '${e}': true`),...Dr.map(e=>` '${e}': false`),""].join(`
1225
+ `),q=e=>{const t=[];for(const r of Ge(e,{includeDirs:!1,includeFiles:!0}))Pe(r.path).isSymbolicLink()||t.push(r.path);return t},Ee=async(e,t,r)=>{const a=q(e),o=[],n=de(),s=await Tr(a,n);for(const i of a){const l=Je(e,i),d=u(t,l);M(A(d),{recursive:!0});const c=b(i);let p=_r(i)?Rr(c.toString("utf8"),r):void 0;p!==void 0&&E(i)==="package.json"&&(p=Or(p,n,s)),p===void 0?v(d,c):v(d,p,"utf8"),o.push(d)}return o},j=(e,t,r)=>t!==void 0&&t.length>0?t:`${$r}/${e}#${ue(r)}`,jr=e=>e.includes("..")?!1:e.startsWith("gh:")||e.startsWith("github:")||e.startsWith("https://"),S=(e,t)=>{e.info(`[dry-run] would ${t}`)},K=(e,t,r)=>{g()&&process.stdout.write(`
1226
+ `),e.success(`scaffolded ${String(t.length)} files into ${r}`)},Vr=(e,t)=>{const{args:r,command:a}=qe(e,t);return`${a} ${r.join(" ")}`},Ne=(e,t)=>{let r=ie(e);for(;;){if(t(r))return!0;const a=A(r);if(a===r)return!1;r=a}},Ur=e=>{if(m(u(e,Ae)))return!0;const t=u(e,"package.json");if(!m(t))return!1;try{return JSON.parse(b(t,"utf8")).workspaces!==void 0}catch{return!1}},Ie=e=>Ne(e,Ur),Fr=e=>Ne(e,t=>m(u(t,".git"))),Hr=async(e,t)=>{if(e.yes===!0||!g()||Fr(A(t)))return;if(!await fe(y.git,{badge:f.git,defaultYes:!1})){await ve("Sounds good! You can always run git init manually.");return}if(e.dryRun===!0){S(e.logger,"initialize a git repository");return}const r=e.spawner??pe;(await it("Initializing a git repository…",()=>r({args:["init"],command:"git",cwd:t}))).code===0?await R("git","Initialized an empty git repository."):e.logger.warn("`git init` failed — initialize it yourself later with `git init`.")},Wr=async(e,t,r,a)=>{const o=[{code:`cd ./${e}`,lead:"Enter your project directory using"}];t===void 0&&o.push({code:`${r} install`,lead:"Install dependencies with",tail:a?" from the workspace root":void 0}),o.push({code:We(r,"dev"),lead:"Run",tail:" to start the dev server."},{code:"lunora add",lead:"Add features like auth or storage using"});const n=[{code:"https://lunora.sh/docs",lead:"Read the docs at"},{code:"https://lunora.sh/chat",lead:"Stuck? Join the chat at"}];if(g()){await lt(f.next,y.nextHeader,o,n);return}const s=o.map(i=>`${i.lead} ${i.code}${i.tail??""}`);s.push("",...n.map(i=>`${i.lead} ${i.code}${i.tail??""}`)),await R("next",y.nextHeader,s.join(`
1227
+ `))},zr=e=>e.yes!==!0&&(e.installPrompt!==void 0||g()),qr=async(e,t)=>{if(!zr(e)||Ie(A(t)))return;const r=He(e.packageManagerProbe),[a]=r;if(a===void 0)return;if(!await(e.installPrompt?.confirmInstall??(async()=>fe(y.install,{badge:f.deps,defaultYes:!0})))()){await ve("No problem! Remember to install dependencies after setup.");return}let n=a;if(r.length>1&&(n=e.installPrompt?await e.installPrompt.selectManager(r):await W(y.packageManager,r.map(c=>({label:c,value:c})),{badge:f.deps,default:a})??a),e.dryRun===!0){S(e.logger,`install dependencies with ${n}`);return}if(n==="pnpm"){const c=u(t,Ae);m(c)||v(c,Br(),"utf8")}const s=e.spawner??pe,{args:i,command:l}=se(n);await R("deps",`Installing dependencies with ${n}…`);const d=await s({args:i,command:l,cwd:t});if(d.code!==0){e.logger.warn(`\`${l} install\` exited with code ${String(d.code)} — run it yourself in ${E(t)}/.`);return}return await R("deps",`Dependencies installed with ${n}.`),n},Kr=async(e,t,r,a,o)=>{const n=u(e,t);if(!m(n))return o.error(`template not found in local source: ${n}`),{code:1,files:[],target:r};const s=await Ee(n,r,a);return K(o,s,r),{code:0,files:s,target:r}},Gr=async e=>{const{logger:t,name:r,ref:a,source:o,target:n,templateType:s}=e,i=oe(u(ne(),"lunora-init-fetch-")),l=u(i,"template");try{const d=o!==void 0&&o.length>0?a:await rt(a,t),c=j(s,o,d);let p,h=[];await ge([{label:`${s} template fetched`,run:async()=>{p=await le(c,{cwd:i,dir:l,force:!0,install:!1,silent:!0})}},{label:`files copied into ${r}/`,run:async()=>{h=await Ee(l,n,r)}}],{end:"Project initialized!",start:"Project initializing…"});const I=q(l);return g()&&process.stdout.write(`
1228
+ `),t.info(p?.commit?`template: ${p.source} @ ${p.commit} (${String(I.length)} files)`:`template: ${p?.source??c} (${String(I.length)} files)`),K(t,h,n),{code:0,files:h,target:n}}catch(d){if(d instanceof H)throw d;const{hints:c,message:p}=Bt(d,{ref:ue(a),remote:j(s,o,a),templateType:s});t.error(p);for(const h of c)t.warn(h);return{code:1,files:[],target:n}}finally{_(i,{force:!0,recursive:!0})}},Jr=e=>{for(const t of["_gitignore","_npmrc","_gitattributes"]){const r=u(e,t);m(r)&&Oe(r,u(e,`.${t.slice(1)}`))}},Yr=async e=>{const{framework:t,logger:r,name:a,overlayBaseFrom:o,target:n}=e,s=O[t],i=oe(u(ne(),"lunora-vite-base-"));try{let l;if(o!==void 0&&(l=u(o,`template-${s.createViteTemplate}`),!m(l)))return r.error(`create-vite base not found on disk: ${l}`),{code:1,files:[],target:n};const d=async()=>{if(l!==void 0){G(l,n,{recursive:!0});return}const p=u(i,"base"),h=`github:vitejs/vite/packages/create-vite/template-${s.createViteTemplate}#main`;await le(h,{cwd:i,dir:p,force:!0,install:!1,silent:!0}),Jr(p),G(p,n,{recursive:!0})};let c=[];return await ge([{label:`create-vite (${s.label}) base ready`,run:d},{label:`Lunora overlay applied (${s.label})`,run:async()=>{c=await br({adapter:s,distTag:de(),logger:r,name:a,target:n})}}],{end:"Project initialized!",start:"Project initializing…"}),K(r,c,n),{code:0,files:[...q(n)],target:n}}catch(l){if(l instanceof H)throw l;const d=l instanceof Error?l.message:String(l);return r.error(`failed to scaffold the ${s.label} base: ${d}`),{code:1,files:[],target:n}}finally{_(i,{force:!0,recursive:!0})}},V=(e,t,r,a,o)=>(o.error(`init --in-place: could not ${e} ${t}: ${r instanceof Error?r.message:String(r)}`),{code:1,files:[],target:a}),Xr=(e,t)=>{const r=u(e,"vite.config.ts");try{v(r,Er,"utf8")}catch(a){return V("write",r,a,e,t)}return t.success(`created ${r} with lunora() plugin`),{code:0,files:[r],target:e}},Qr=(e,t,r)=>{let a;try{a=b(e,"utf8")}catch(n){return V("read",e,n,t,r)}const o=ke(a);if(!o.changed)return r.info(`${e}: ${o.reason??"no changes needed"}`),{code:0,files:[],target:t};try{v(e,o.code,"utf8")}catch(n){return V("write",e,n,t,r)}return r.success(`patched ${e} — added lunora() plugin`),{code:0,files:[e],target:t}},Zr=(e,t)=>{const r=u(e,"lunora"),a=u(r,"schema.ts");if(m(a))return t.info(`lunora/ already present — left ${a} untouched`),[];const o=[];try{M(r,{recursive:!0}),v(a,Nr,"utf8"),o.push(a);const n=u(r,"messages.ts");m(n)||(v(n,Ir,"utf8"),o.push(n)),t.success(`scaffolded lunora/ (${String(o.length)} file(s))`)}catch(n){const s=n instanceof Error?n.message:String(n);t.error(`init --here: could not scaffold lunora/: ${s}`)}return o},ea=(e,t,r)=>{const{adapter:a,class:o,framework:n}=e;r.info(""),r.info(`detected framework: ${n} (class ${o})`),r.info("next steps:"),r.info(` 1. install the adapter: ${Vr(t,[a,"@lunora/client","@lunora/runtime","@lunora/server"])}`),r.info(" 2. run codegen: lunora codegen"),o==="A"?(r.info(" 3. compose one worker: wrap your worker entry with"),r.info(" createWorker({ httpRouter: <your framework SSR handler>, shardDO: ShardDO, ... })"),r.info(` 4. add the provider: mount the ${a} provider in your root layout/route`),r.info(" 5. make a loader live: preloadQuery() in a loader, usePreloadedQuery() in the component"),r.info(" see https://lunora.sh/docs/frameworks/reactive-loaders")):o==="B"?(r.info(" 3. inject Lunora: mount Lunora realtime under /_lunora/* in your server hook"),r.info(` (${n} owns its Cloudflare adapter — Lunora composes into its server entry)`),r.info(` 4. add the provider: mount the ${a} provider in your root layout`),r.info(" 5. read the guide: https://lunora.sh/docs/frameworks/deploy")):(r.info(" 3. add the provider: wrap your app with the LunoraProvider from @lunora/react"),r.info(" 4. read the guide: https://lunora.sh/docs/frameworks/bring-your-framework")),r.info("")},ta=(e,t,r)=>{const a=Se(e);return a===void 0?t==="sveltekit"||t==="nuxt"||t==="astro"?(r.info(`no Vite config found — ${t} wires Lunora through its server entry (see next steps)`),{code:0,files:[],target:e}):Xr(e,r):Qr(a,e,r)},ra=(e,t)=>{const r=At(e),a=ta(e,r.framework,t);if(a.code!==0)return a;const o=Zr(e,t);return ea(r,U(e),t),{code:0,files:[...a.files,...o],target:e}},aa=e=>e.yes!==!0&&(e.prompt!==void 0||(e.interactive??g())),re=async(e,t,r)=>{r.dryRun!==!0&&await Jt({apply:a=>Ke(e,a),detected:ze(e),interactive:t,logger:r.logger,multiSelect:r.lintPrompt??((a,o,n)=>me(a,o,{...n,badge:f.add}))})},oa=async(e,t)=>{const r=aa(e),a=e.add===void 0?[]:Ut(e.add,s=>{e.logger.warn(s)}),n={applyAll:async s=>{if(s.length===0)return!0;if(e.dryRun===!0)return S(e.logger,`add ${s.map(h=>h.label).join(", ")}`),!0;const i=[],l=g()?{error:h=>{i.push({level:"error",message:h})},info:()=>{},success:()=>{},warn:h=>{i.push({level:"warn",message:h})}}:e.logger,d=s.map(h=>({running:`adding ${h.label}…`,task:()=>yt({allowUnsafeSource:e.allowUnsafeSource,cwd:t,from:e.registryFrom,logger:l,names:[...h.names],ref:e.ref,source:e.registrySource,transformManifest:h.transformManifest,yes:!0})})),c=`added ${s.map(h=>h.label).join(", ")}`,p=await ct(f.add,d,c);for(const{level:h,message:I}of i)e.logger[h](I);return p.every(h=>h.code===0)},interactive:r,logger:e.logger,multiSelect:e.prompt?.multiSelect??((s,i,l)=>me(s,i,{...l,badge:f.add})),preselected:a.length>0?a:void 0,projectName:E(t),resolveAuthUiItem:()=>{try{const s=JSON.parse(b(u(t,"package.json"),"utf8"));return vt({...s.dependencies,...s.devDependencies})??"auth-ui-react"}catch{return"auth-ui-react"}},select:e.prompt?.select??((s,i,l)=>W(s,i,{...l,badge:f.add})),text:e.prompt?.text??((s,i)=>he(s,{...i,badge:f.add}))};if(a.length>0){const s=await Z(n);return await re(t,r,e),s}return g()&&await st(y.extras),await Z(n),await re(t,r,e),!0},B="react",$e=[{description:"React SPA — official create-vite base + the Lunora layer (the default)",label:"React",value:"react"},{description:"Vue SPA — create-vite base + Lunora",label:"Vue",value:"vue"},{description:"Solid SPA — create-vite base + Lunora",label:"Solid",value:"solid"},{description:"Solid 2.0 SPA — the Solid 2 line (@solidjs/web, vite-plugin-solid 3)",label:"Solid 2",value:"solid-v2"},{description:"Svelte SPA — create-vite base + Lunora",label:"Svelte",value:"svelte"},{description:"Next.js (App Router) — OpenNext on Cloudflare + a standalone Lunora worker",label:"Next.js",value:"next"},{description:"TanStack Start (React) — SSR with live-loader routes",label:"TanStack Start · React",value:"tanstack-start-react"},{description:"TanStack Start (Solid)",label:"TanStack Start · Solid",value:"tanstack-start-solid"},{description:"Next.js App Router on Vite (vinext) — composed into the Lunora worker (experimental)",label:"vinext · App Router",value:"vinext"},{description:"Next.js Pages Router on Vite (vinext) — composed into one worker (experimental)",label:"vinext · Pages Router",value:"vinext-pages"},{description:"React Router (v7, framework mode) — SSR composed into the Lunora worker",label:"React Router",value:"react-router"},{description:"Astro + a standalone Lunora worker",label:"Astro",value:"astro"},{description:"AnalogJS (Angular) — single-worker, Lunora mounted in Nitro",label:"Analog",value:"analog"},{description:"Nuxt (Vue) — single-worker, Lunora mounted in Nitro",label:"Nuxt",value:"nuxt"},{description:"SvelteKit + a standalone Lunora worker",label:"SvelteKit",value:"sveltekit"},{description:"React Native (Expo) — an iOS/Android/web app + a Lunora worker backend",label:"React Native · Expo",value:"expo"},{description:"Worker only — no frontend",label:"Standalone",value:"standalone"}],_e=Object.keys(O).join("|"),Re=$e.filter(e=>!P(e.value)).map(e=>e.value),Te=Re.join("|"),na=e=>P(e)?{framework:e,kind:"overlay"}:{kind:"template",templateType:e},sa=async e=>e.vite!==void 0?{framework:e.vite,kind:"overlay"}:e.templateType!==void 0?{kind:"template",templateType:e.templateType}:!g()||e.yes===!0?{framework:B,kind:"overlay"}:na(await W(y.framework,$e,{badge:f.tmpl,default:B})??B),ia=e=>{if(g()||e.yes===!0)return;const t=[];if(e.name===void 0&&t.push("a project name (`lunora init <name>`)"),e.templateType===void 0&&e.vite===void 0&&t.push(`a framework — \`--vite <${_e}>\` for an SPA, or \`-t <${Te}>\` for a bespoke template`),t.length!==0)return`lunora init can't prompt in a non-interactive terminal — provide ${t.join(" and ")}, or pass --yes to accept the defaults.`},la=async(e,t,r,a)=>P(t)?await Me({isLocal:e.overlayBaseFrom!==void 0,logger:e.logger})?(M(a,{recursive:!0}),Yr({framework:t,logger:e.logger,name:r,overlayBaseFrom:e.overlayBaseFrom,target:a})):{code:1,files:[],target:a}:(e.logger.error(`init: unknown framework "${t}". Supported overlays: ${Object.keys(O).join(", ")}.`),{code:1,files:[],target:a}),ca=async(e,t,r,a)=>e.from!==void 0?await Kr(e.from,t,a,r,e.logger):e.source!==void 0&&e.source.length>0&&!e.allowUnsafeSource&&!jr(e.source)?(e.logger.error(`init: refusing --source ${e.source} — only gh:, github:, or https:// sources are allowed (and may not contain ".."). Re-run with --allow-unsafe-source if you really want this.`),{code:1,files:[],target:a}):await Me({isLocal:!1,logger:e.logger,source:j(t,e.source,e.ref)})?Gr({logger:e.logger,name:r,ref:e.ref,source:e.source,target:a,templateType:t}):{code:1,files:[],target:a},da=async(e,t,r)=>{await nt("realtime backend on Cloudflare Workers + Durable Objects");const a=ia(e);if(a!==void 0)return e.logger.error(a),{code:1,files:[],target:""};const o=Cr(),n=e.name??await he(y.name,{badge:f.dir,default:o,placeholder:o}),s=await sa(e),i=n.trim();if(i.length===0)return e.logger.error("init: refusing an empty project name — pass a directory name (e.g. `lunora init my-app`)."),{code:1,files:[],target:""};if(i.includes("/")||i.includes("\\")||i===".."||i===".")return e.logger.error(`init: refusing project name "${i}" — must not contain path separators or be "." / "..".`),{code:1,files:[],target:""};const l=ie(t,i),d=m(l);if(d&&ae(l).length>0)return e.logger.error(`target directory not empty: ${l}`),{code:1,files:[],target:l};if(e.dryRun===!0){const c=s.kind==="overlay"?`the ${s.framework} create-vite overlay`:`the ${s.templateType} template`;return S(e.logger,`scaffold ${c} into ${l}`),{code:0,files:[],target:l}}return r(l,d),s.kind==="overlay"?la(e,s.framework,i,l):ca(e,s.templateType,i,l)},ua=(e,t)=>{const{target:r,targetPreExisted:a}=e;if(!(r===void 0||!m(r))){if(a===!0)for(const o of ae(r))_(u(r,o),{force:!0,recursive:!0});else _(r,{force:!0,recursive:!0});t.info(`removed the partially-created project at ${r}`)}},pa=async(e,t,r)=>e.inPlace!==!0?da(e,t,r):e.dryRun===!0?(S(e.logger,`configure Lunora into ${t}`),{code:0,files:[],target:t}):ra(t,e.logger),ha=async(e,t,r)=>{const a=await oa(e,t.target),o=e.inPlace===!0?void 0:await qr(e,t.target);if(e.inPlace!==!0){await Hr(e,t.target);const n=o??U(t.target);await Wr(E(t.target),o,n,Ie(r)),await jt(e.logger)}return a},ma=(e,t,r)=>{if(t.code!==0||e.ci===void 0)return;if(e.dryRun===!0){S(e.logger,`scaffold a ${e.ci} CI deploy pipeline`);return}const a=e.inPlace===!0?r:t.target;try{const o=U(a);Lt(a,e.ci,o,e.logger)}catch{e.logger.warn(`--ci ${e.ci}: could not detect a package manager for this project — skipped the CI pipeline.`)}},fa=async e=>{const t=e.cwd??process.cwd(),r={};let a;try{a=await pa(e,t,(o,n)=>{r.target=o,r.targetPreExisted=n}),a.code===0&&a.target!==""&&(r.target=void 0,await ha(e,a,t)||(a={...a,code:1}))}catch(o){if(o instanceof H)return ua(r,e.logger),process.stdout.write("\n ✖ Setup cancelled — run `lunora init` again whenever you're ready. 🌙\n"),{code:130,files:[],target:""};throw o}return ma(e,a,t),a},va=e=>typeof e=="string"&&Re.includes(e),ga=(e,t)=>{if(e!==void 0){if(Ct(e))return e;t.warn(`init: unknown --ci "${e}" — expected github | gitlab; skipping CI scaffold.`)}},wa=e=>e===void 0?{}:va(e)?{templateType:e}:P(e)?{vite:e}:{error:`init: unknown --template "${e}" — expected a bespoke template (${Te}) or an overlay framework (${_e}).`},ja=Ze(({argument:e,cwd:t,logger:r,options:a})=>{const o=wa(a.template);return"error"in o?(r.error(o.error),{code:1}):fa({add:a.add,allowUnsafeSource:a.allowUnsafeSource===!0,cwd:t,ci:ga(a.ci,r),dryRun:a.dryRun===!0,from:a.from,inPlace:a.here===!0,interactive:a.interactive===!0?!0:void 0,logger:r,name:e[0],ref:a.ref,source:a.source,templateType:o.templateType,vite:a.vite??o.vite,yes:a.yes===!0})});export{ja as execute,va as isTemplate,wa as resolveTemplateFlag,j as resolveTemplateSource,fa as runInitCommand};
@@ -1,11 +1,11 @@
1
- import{existsSync as m,mkdirSync as T,writeFileSync as h,mkdtempSync as N,rmSync as M,readFileSync as I}from"node:fs";import{tmpdir as R}from"node:os";import{discoverSchema as _,readPackageDependencies as U,discoverMigrations as x}from"@lunora/codegen";import{isInteractive as C,promptSelect as O,promptText as F}from"@lunora/config";import{LunoraError as y}from"@lunora/errors";import{join as c}from"@visulima/path";import{Project as b}from"ts-morph";import{r as P}from"../packem_shared/admin-url-Cil3Or6N.mjs";import{d as D}from"../packem_shared/command-DwC11Cwe.mjs";import{diffSnapshots as z,renderMigrationFile as L}from"../packem_shared/diffSnapshots-CIOFQN_a.mjs";import{r as j}from"../packem_shared/resolve-target-BRvw8Pf7.mjs";import q from"../packem_shared/schemaIrToSnapshot-qpRoV7HY.mjs";import{readAndLogBody as H}from"./runRpcCommand.mjs";import{runExportCommand as G}from"../packem_shared/runExportCommand-DmXKEWSq.mjs";import{r as B}from"../packem_shared/import-CdHdZRjj.mjs";const u="__lunora_reproject__",W=e=>{if(!e.startsWith(u))return;const r=e.slice(u.length);return r===""?void 0:r},J=".snapshot.json",k=/[^\da-z]+/gu,A=(e,r)=>{let n=0,t=e.length;for(;n<t&&e[n]===r;)n+=1;for(;t>n&&e[t-1]===r;)t-=1;return e.slice(n,t)},K=e=>{const r=A(e.toLowerCase().replaceAll(k,"_"),"_");return r===""?"auto":r},V=e=>{const r=(n,t=2)=>n.toString().padStart(t,"0");return`${String(e.getUTCFullYear())}${r(e.getUTCMonth()+1)}${r(e.getUTCDate())}${r(e.getUTCHours())}${r(e.getUTCMinutes())}${r(e.getUTCSeconds())}`},Z=e=>{if(m(e))try{const r=I(e,"utf8"),n=JSON.parse(r);if(n.version!==1)throw new y("INTERNAL",`unsupported snapshot version: ${n.version}`);return n}catch(r){const n=r instanceof Error?r.message:String(r);throw new y("INTERNAL",`failed to read ${e}: ${n}`,{cause:r})}},X=e=>{const r=e.cwd??process.cwd(),n=c(r,"lunora","schema.ts");if(!m(n))return e.logger.error(`schema not found: ${n} — run \`vis generate lunora-table --name=<name>\` to create one`),{code:1,empty:!0,migrationFile:""};const t=new b({skipAddingFilesFromTsConfig:!0}),a=_(t,n),s=q(a),o=c(r,"lunora","migrations"),i=c(o,J);let d;try{d=Z(i)}catch(g){return e.logger.error(g instanceof Error?g.message:String(g)),{code:1,empty:!0,migrationFile:""}}const l=z(d,s);if(l.empty)return e.logger.info("no schema changes detected — snapshot is already up to date"),{code:0,empty:!0,migrationFile:""};const v=(e.now??(()=>new Date))(),p=K(e.name??"auto"),w=`${V(v)}_${p}.sql`,f=c(o,w);T(o,{recursive:!0});const E=L(p,l,v.toISOString());return h(f,E,"utf8"),h(i,`${JSON.stringify(s,void 0,4)}
2
- `,"utf8"),e.logger.success(`wrote ${f}`),l.unsupported.length>0&&e.logger.warn(`${String(l.unsupported.length)} unsupported diff(s) — see the comment block in ${w} and write the SQL manually`),{code:0,empty:!1,migrationFile:f}},Q="migrations.ts",$=/^[A-Za-z_]\w*$/u,Y=new Set(["await","break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","function","if","implements","import","in","instanceof","interface","let","new","null","package","private","protected","public","return","static","super","switch","this","throw","true","try","typeof","var","void","while","with","yield"]),S=/^import\s*\{\s*defineMigration\s*\}\s*from\s*["'](?:@lunora\/server|lunorash\/server)["'][^\n]*$/mu,ee=e=>`import { defineMigration } from "${U(e)?.has("lunorash")??!1?"lunorash/server":"@lunora/server"}";`,re="__lunora_admin__:runMigration",te="__lunora_admin__:migrationStatus",ne="/_lunora/migrate",ae=e=>A(e.trim().toLowerCase().replaceAll(k,"-"),"-"),oe=e=>e.split("-").filter(r=>r.length>0).map((r,n)=>n===0?r:r.charAt(0).toUpperCase()+r.slice(1)).join(""),ie=e=>{const r=c(e,"lunora","schema.ts");if(!m(r))return[];try{const n=new b({skipAddingFilesFromTsConfig:!0});return _(n,r).tables.map(t=>t.name)}catch{return[]}},se=async e=>e.length>0?O("Which table does this migration iterate?",e.map(r=>({label:r,value:r}))):F("Target table for the migration: "),ce=async(e,r)=>{if(r.table!==void 0)return r.table;const n=r.promptTable??(C()?se:void 0);if(n===void 0){r.logger.error("migrate create requires a target table when not running interactively — re-run with --table <table>");return}const a=(await n(ie(e)))?.trim();if(a===void 0||a===""){r.logger.error("no table selected — re-run with --table <table>");return}return a},de=async e=>{const r=e.cwd??process.cwd(),n=ae(e.name);if(n==="")return e.logger.error(`invalid migration name: "${e.name}" — must contain at least one alphanumeric character`),{code:1,file:""};const t=oe(n);if(!$.test(t)||Y.has(t))return e.logger.error(`invalid migration name: "${e.name}" derives the export \`${t}\`, which is not a valid identifier — pick a name that starts with a letter and isn't a reserved word`),{code:1,file:""};const a=await ce(r,e);if(a===void 0)return{code:1,file:""};if(!$.test(a))return e.logger.error(`invalid table: "${a}" — must be a valid identifier ([A-Za-z_][A-Za-z0-9_]*)`),{code:1,file:""};const s=c(r,"lunora"),o=c(s,Q);let i=m(o)?I(o,"utf8"):"";if(i.includes(`id: "${n}"`)||new RegExp(String.raw`\bexport const ${t}\b`,"u").test(i))return e.logger.error(`a migration with id "${n}" (export \`${t}\`) already exists in ${o}`),{code:1,file:""};const d=ee(r);i.trim()===""?i=`${d}
1
+ import{existsSync as m,mkdirSync as I,writeFileSync as h,mkdtempSync as U,rmSync as R,readFileSync as _}from"node:fs";import{tmpdir as M}from"node:os";import{discoverSchema as k,readPackageDependencies as x,discoverMigrations as C}from"@lunora/codegen";import{isInteractive as O,promptSelect as F,promptText as P}from"@lunora/config";import{LunoraError as w}from"@lunora/errors";import{join as c}from"@visulima/path";import{Project as b}from"ts-morph";import{t as D}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{n as z,r as L}from"../packem_shared/admin-url-BhF5ufg1.mjs";import{d as j}from"../packem_shared/command-DwC11Cwe.mjs";import{diffSnapshots as q,renderMigrationFile as H}from"../packem_shared/diffSnapshots-Cnoe8Ob4.mjs";import{r as B}from"../packem_shared/resolve-target-BRvw8Pf7.mjs";import G from"../packem_shared/schemaIrToSnapshot-ogkcpHjM.mjs";import{readAndLogBody as W}from"./runRpcCommand.mjs";import{runExportCommand as J}from"../packem_shared/runExportCommand-Dq-SpjAe.mjs";import{r as K}from"../packem_shared/import-8FCB0cUX.mjs";const u="__lunora_reproject__",V=e=>{if(!e.startsWith(u))return;const r=e.slice(u.length);return r===""?void 0:r},Z=".snapshot.json",A=/[^\da-z]+/gu,E=(e,r)=>{let a=0,t=e.length;for(;a<t&&e[a]===r;)a+=1;for(;t>a&&e[t-1]===r;)t-=1;return e.slice(a,t)},X=e=>{const r=E(e.toLowerCase().replaceAll(A,"_"),"_");return r===""?"auto":r},Q=e=>{const r=(a,t=2)=>a.toString().padStart(t,"0");return`${String(e.getUTCFullYear())}${r(e.getUTCMonth()+1)}${r(e.getUTCDate())}${r(e.getUTCHours())}${r(e.getUTCMinutes())}${r(e.getUTCSeconds())}`},Y=e=>{if(m(e))try{const r=_(e,"utf8"),a=JSON.parse(r);if(a.version!==1)throw new w("INTERNAL",`unsupported snapshot version: ${a.version}`);return a}catch(r){const a=r instanceof Error?r.message:String(r);throw new w("INTERNAL",`failed to read ${e}: ${a}`,{cause:r})}},ee=e=>{const r=e.cwd??process.cwd(),a=c(r,"lunora","schema.ts");if(!m(a))return e.logger.error(`schema not found: ${a} — run \`vis generate lunora-table --name=<name>\` to create one`),{code:1,empty:!0,migrationFile:""};const t=new b({skipAddingFilesFromTsConfig:!0}),n=k(t,a),s=G(n),o=c(r,"lunora","migrations"),i=c(o,Z);let d;try{d=Y(i)}catch(g){return e.logger.error(g instanceof Error?g.message:String(g)),{code:1,empty:!0,migrationFile:""}}const l=q(d,s);if(l.empty)return e.logger.info("no schema changes detected — snapshot is already up to date"),{code:0,empty:!0,migrationFile:""};const v=(e.now??(()=>new Date))(),p=X(e.name??"auto"),y=`${Q(v)}_${p}.sql`,f=c(o,y);I(o,{recursive:!0});const N=H(p,l,v.toISOString());return h(f,N,"utf8"),h(i,`${JSON.stringify(s,void 0,4)}
2
+ `,"utf8"),e.logger.success(`wrote ${f}`),l.unsupported.length>0&&e.logger.warn(`${String(l.unsupported.length)} unsupported diff(s) — see the comment block in ${y} and write the SQL manually`),{code:0,empty:!1,migrationFile:f}},re="migrations.ts",$=/^[A-Za-z_]\w*$/u,te=new Set(["await","break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","function","if","implements","import","in","instanceof","interface","let","new","null","package","private","protected","public","return","static","super","switch","this","throw","true","try","typeof","var","void","while","with","yield"]),S=/^import\s*\{\s*defineMigration\s*\}\s*from\s*["'](?:@lunora\/server|lunorash\/server)["'][^\n]*$/mu,ae=e=>`import { defineMigration } from "${x(e)?.has("lunorash")??!1?"lunorash/server":"@lunora/server"}";`,ne="__lunora_admin__:runMigration",oe="__lunora_admin__:migrationStatus",ie="/_lunora/migrate",se=e=>E(e.trim().toLowerCase().replaceAll(A,"-"),"-"),ce=e=>e.split("-").filter(r=>r.length>0).map((r,a)=>a===0?r:r.charAt(0).toUpperCase()+r.slice(1)).join(""),de=e=>{const r=c(e,"lunora","schema.ts");if(!m(r))return[];try{const a=new b({skipAddingFilesFromTsConfig:!0});return k(a,r).tables.map(t=>t.name)}catch{return[]}},le=async e=>e.length>0?F("Which table does this migration iterate?",e.map(r=>({label:r,value:r}))):P("Target table for the migration: "),ue=async(e,r)=>{if(r.table!==void 0)return r.table;const a=r.promptTable??(O()?le:void 0);if(a===void 0){r.logger.error("migrate create requires a target table when not running interactively — re-run with --table <table>");return}const n=(await a(de(e)))?.trim();if(n===void 0||n===""){r.logger.error("no table selected — re-run with --table <table>");return}return n},me=async e=>{const r=e.cwd??process.cwd(),a=se(e.name);if(a==="")return e.logger.error(`invalid migration name: "${e.name}" — must contain at least one alphanumeric character`),{code:1,file:""};const t=ce(a);if(!$.test(t)||te.has(t))return e.logger.error(`invalid migration name: "${e.name}" derives the export \`${t}\`, which is not a valid identifier — pick a name that starts with a letter and isn't a reserved word`),{code:1,file:""};const n=await ue(r,e);if(n===void 0)return{code:1,file:""};if(!$.test(n))return e.logger.error(`invalid table: "${n}" — must be a valid identifier ([A-Za-z_][A-Za-z0-9_]*)`),{code:1,file:""};const s=c(r,"lunora"),o=c(s,re);let i=m(o)?_(o,"utf8"):"";if(i.includes(`id: "${a}"`)||new RegExp(String.raw`\bexport const ${t}\b`,"u").test(i))return e.logger.error(`a migration with id "${a}" (export \`${t}\`) already exists in ${o}`),{code:1,file:""};const d=ae(r);i.trim()===""?i=`${d}
3
3
  `:S.test(i)?i=i.replace(S,d):i=`${d}
4
4
  ${i}`;const l=`export const ${t} = defineMigration({
5
- id: "${n}",
6
- table: "${a}",
5
+ id: "${a}",
6
+ table: "${n}",
7
7
  up: (document) => document,
8
- });`;return T(s,{recursive:!0}),h(o,`${i.trimEnd()}
8
+ });`;return I(s,{recursive:!0}),h(o,`${i.trimEnd()}
9
9
 
10
10
  ${l}
11
- `,"utf8"),e.logger.success(`scaffolded migration "${n}" in ${o}`),{code:0,file:o}},le=(e,r)=>{const n=new b({skipAddingFilesFromTsConfig:!0});return x(n,c(e,"lunora")).find(a=>a.id===r)?.table},ue=(e,r)=>{const n=W(r.id);if(n!==void 0)return n;if(r.id.startsWith(u)){r.logger.error(`"${r.id}" names no table — use ${u}<table>`);return}let t;try{t=le(e,r.id)}catch(a){r.logger.error(a instanceof Error?a.message:String(a));return}if(t===void 0){r.logger.error(`migration "${r.id}" not found under lunora/ — declare it with defineMigration({ id: "${r.id}", ... })`);return}if(t===""){r.logger.error(`migration "${r.id}" must declare \`table\` as a static string literal`);return}return t},me=e=>{const r=e.cwd??process.cwd();if(e.prod&&e.url===void 0){e.logger.error("--prod requires an explicit --url (refusing to migrate the implicit localhost worker)");return}if(e.prod&&(e.subcommand==="up"||e.subcommand==="down")&&!e.yes){e.logger.error(`migrate ${e.subcommand} --prod runs the migration against production. Re-run with --yes to confirm.`);return}const n=e.token??process.env.LUNORA_ADMIN_TOKEN;if(!n){e.logger.error("admin token required — pass --token or set LUNORA_ADMIN_TOKEN");return}const t=ue(r,e);if(t===void 0)return;const a=P(e.url,e.logger,e.cwd);if(a===void 0)return;const s=e.fetchImpl??globalThis.fetch;if(typeof s!="function")throw new TypeError("no fetch implementation available — pass fetchImpl or run on Node >= 18");return{fetchImpl:s,requestUrl:`${a}${ne}`,table:t,token:n}},fe=e=>{const r={id:e.id};return e.subcommand==="status"||(r.direction=e.subcommand,e.dryRun&&(r.dryRun=!0),e.batchSize!==void 0&&(r.batchSize=e.batchSize),e.maxBatches!==void 0&&(r.maxBatches=e.maxBatches)),r},ge=async e=>{const r=me(e);if(r===void 0)return{body:void 0,code:1,requestUrl:""};const{fetchImpl:n,requestUrl:t,table:a,token:s}=r,o=e.subcommand==="status"?te:re,i=fe(e);e.logger.info(`POST ${t} -> ${e.subcommand} ${e.id} (table "${a}")`);const d=await n(t,{body:JSON.stringify({args:i,functionPath:o,table:a}),headers:{authorization:`Bearer ${s}`,"content-type":"application/json"},method:"POST"});return{body:await H(d,e.logger),code:d.ok?0:1,requestUrl:t}},he=async e=>{const{logger:r}=e,n=e.fromUrl??e.toUrl,t=e.toUrl??e.fromUrl;if(n!==void 0&&n===t)return r.error("source and target are the same deployment — pass distinct --from-url and --to-url so the D1 export and Hyperdrive import don't run against one database"),{code:1};const a=e.out===void 0?N(c(R(),"lunora-d1ps-")):void 0,s=e.out??c(a,"dump.ndjson");try{r.info(`Exporting .global() data from the D1 source (${n??"http://localhost:8787"}) …`);const o=await G({fetchImpl:e.fetchImpl,logger:r,out:s,prod:e.prod,tables:e.tables,token:e.fromToken,url:n});if(o.code!==0)return{code:o.code};r.info(`Exported ${String(o.rows)} row(s) (${String(o.bytes)} bytes).`),r.info(`Importing into the Hyperdrive target (${t??"http://localhost:8787"}) …`);const i=await B({batchSize:e.batchSize,fetchImpl:e.fetchImpl,file:s,logger:r,prod:e.prod,token:e.toToken,url:t});return i.code!==0?{code:i.code}:(i.inserted===o.rows?r.info(`✓ Migrated ${String(o.rows)} row(s) — counts match. Verify your app reads from Hyperdrive, then decommission the D1 binding.`):r.warn(`Imported ${String(i.inserted)} of ${String(o.rows)} exported row(s) — the remainder likely already existed in the target (see conflicts above). Re-run after resolving, or inspect the dump with --out.`),{code:0})}finally{a!==void 0&&M(a,{force:!0,recursive:!0})}},xe=D(({argument:e,cwd:r,logger:n,options:t})=>{const a=e[0];if(a==="generate")return X({cwd:r,logger:n,name:e[1]??t.name});if(a==="d1-to-hyperdrive")return he({batchSize:t.batchSize,fromToken:t.fromToken??t.token,fromUrl:t.fromUrl??t.url,logger:n,out:t.out,prod:t.prod===!0,tables:t.tables,toToken:t.toToken??t.token,toUrl:t.toUrl??t.url});if(a==="create"){const s=e[1]??t.name;return s?de({cwd:r,logger:n,name:s,table:t.table}):(n.error("migrate create requires a name. Usage: lunora migrate create <name> [--table <table>]"),{code:1})}if(a==="up"||a==="down"||a==="status"){const s=e[1]??t.name;return s?ge({batchSize:t.batchSize,cwd:r,dryRun:t.dryRun===!0,id:s,logger:n,maxBatches:t.steps,prod:t.prod===!0,subcommand:a,token:t.token,url:j({cwd:r,prod:t.prod===!0,url:t.url}),yes:t.yes===!0}):(n.error(`migrate ${a} requires a migration id. Usage: lunora migrate ${a} <id>`),{code:1})}return n.error(`unknown migrate subcommand: "${a??""}" — expected generate | create | up | down | status`),{code:1}});export{xe as execute,de as runMigrateCreateCommand,ge as runMigrateDataCommand,X as runMigrateGenerateCommand,he as runMigrateToHyperdriveCommand};
11
+ `,"utf8"),e.logger.success(`scaffolded migration "${a}" in ${o}`),{code:0,file:o}},fe=(e,r)=>{const a=new b({skipAddingFilesFromTsConfig:!0});return C(a,c(e,"lunora")).find(n=>n.id===r)?.table},ge=(e,r)=>{const a=V(r.id);if(a!==void 0)return a;if(r.id.startsWith(u)){r.logger.error(`"${r.id}" names no table — use ${u}<table>`);return}let t;try{t=fe(e,r.id)}catch(n){r.logger.error(n instanceof Error?n.message:String(n));return}if(t===void 0){r.logger.error(`migration "${r.id}" not found under lunora/ — declare it with defineMigration({ id: "${r.id}", ... })`);return}if(t===""){r.logger.error(`migration "${r.id}" must declare \`table\` as a static string literal`);return}return t},he=e=>{const r=e.cwd??process.cwd();if(e.prod&&e.url===void 0){e.logger.error("--prod requires an explicit --url (refusing to migrate the implicit localhost worker)");return}const a=e.token??process.env.LUNORA_ADMIN_TOKEN;if(!a){e.logger.error("admin token required — pass --token or set LUNORA_ADMIN_TOKEN");return}const t=ge(r,e);if(t===void 0)return;const n=L(e.url,e.logger,e.cwd);if(n===void 0)return;if((e.subcommand==="up"||e.subcommand==="down")&&D({prod:e.prod,url:n})&&!e.yes){e.logger.error(`migrate ${e.subcommand} runs the migration against ${n}, which is not local. Re-run with --yes to confirm.`);return}const s=e.fetchImpl??globalThis.fetch;if(typeof s!="function")throw new TypeError("no fetch implementation available — pass fetchImpl or run on Node >= 18");return{fetchImpl:s,requestUrl:`${n}${ie}`,table:t,token:a}},be=e=>{const r={id:e.id};return e.subcommand==="status"||(r.direction=e.subcommand,e.dryRun&&(r.dryRun=!0),e.batchSize!==void 0&&(r.batchSize=e.batchSize),e.maxBatches!==void 0&&(r.maxBatches=e.maxBatches)),r},ve=async e=>{const r=he(e);if(r===void 0)return{body:void 0,code:1,requestUrl:""};const{fetchImpl:a,requestUrl:t,table:n,token:s}=r,o=e.subcommand==="status"?oe:ne,i=be(e);e.logger.info(`POST ${t} -> ${e.subcommand} ${e.id} (table "${n}")`);const d=await a(t,{body:JSON.stringify({args:i,functionPath:o,table:n}),headers:{authorization:`Bearer ${s}`,"content-type":"application/json"},method:"POST"});return{body:await W(d,e.logger),code:d.ok?0:1,requestUrl:t}},T=e=>e===void 0?void 0:z(e),pe=async e=>{const{logger:r}=e,a=T(e.fromUrl??e.toUrl),t=T(e.toUrl??e.fromUrl);if(a===t)return r.error("source and target are the same deployment — pass distinct --from-url and --to-url so the D1 export and Hyperdrive import don't run against one database"),{code:1};const n=e.out===void 0?U(c(M(),"lunora-d1ps-")):void 0,s=e.out??c(n,"dump.ndjson");try{r.info(`Exporting .global() data from the D1 source (${a??"http://localhost:8787"}) …`);const o=await J({fetchImpl:e.fetchImpl,logger:r,out:s,prod:e.prod,tables:e.tables,token:e.fromToken,url:a});if(o.code!==0)return{code:o.code};r.info(`Exported ${String(o.rows)} row(s) (${String(o.bytes)} bytes).`),r.info(`Importing into the Hyperdrive target (${t??"http://localhost:8787"}) …`);const i=await K({batchSize:e.batchSize,fetchImpl:e.fetchImpl,file:s,logger:r,prod:e.prod,token:e.toToken,url:t,yes:e.yes});return i.code!==0?{code:i.code}:(i.inserted===o.rows?r.info(`✓ Migrated ${String(o.rows)} row(s) — counts match. Verify your app reads from Hyperdrive, then decommission the D1 binding.`):r.warn(`Imported ${String(i.inserted)} of ${String(o.rows)} exported row(s) — the remainder likely already existed in the target (see conflicts above). Re-run after resolving, or inspect the dump with --out.`),{code:0})}finally{n!==void 0&&R(n,{force:!0,recursive:!0})}},Pe=j(({argument:e,cwd:r,logger:a,options:t})=>{const n=e[0];if(n==="generate")return ee({cwd:r,logger:a,name:e[1]??t.name});if(n==="d1-to-hyperdrive")return pe({batchSize:t.batchSize,fromToken:t.fromToken??t.token,fromUrl:t.fromUrl??t.url,logger:a,out:t.out,prod:t.prod===!0,tables:t.tables,toToken:t.toToken??t.token,toUrl:t.toUrl??t.url,yes:t.yes===!0});if(n==="create"){const s=e[1]??t.name;return s?me({cwd:r,logger:a,name:s,table:t.table}):(a.error("migrate create requires a name. Usage: lunora migrate create <name> [--table <table>]"),{code:1})}if(n==="up"||n==="down"||n==="status"){const s=e[1]??t.name;return s?ve({batchSize:t.batchSize,cwd:r,dryRun:t.dryRun===!0,id:s,logger:a,maxBatches:t.steps,prod:t.prod===!0,subcommand:n,token:t.token,url:B({cwd:r,prod:t.prod===!0,url:t.url}),yes:t.yes===!0}):(a.error(`migrate ${n} requires a migration id. Usage: lunora migrate ${n} <id>`),{code:1})}return a.error(`unknown migrate subcommand: "${n??""}" — expected generate | create | up | down | status`),{code:1}});export{Pe as execute,me as runMigrateCreateCommand,ve as runMigrateDataCommand,ee as runMigrateGenerateCommand,pe as runMigrateToHyperdriveCommand};
@@ -1 +1 @@
1
- import{LunoraError as l}from"@lunora/errors";import{r as y,d as v}from"../packem_shared/admin-token-rxXZbVMZ.mjs";import{r as A,a as b}from"../packem_shared/admin-url-Cil3Or6N.mjs";import{d as N}from"../packem_shared/command-DwC11Cwe.mjs";import{a as _}from"../packem_shared/resolve-target-BRvw8Pf7.mjs";const f=(r,t="--args")=>{if(r===void 0||r.length===0)return{};let e;try{e=JSON.parse(r)}catch(a){const n=a instanceof Error?a.message:String(a);throw new l("INTERNAL",`failed to parse ${t} as JSON: ${n}`,{cause:a})}if(typeof e!="object"||e===null||Array.isArray(e))throw new l("INTERNAL",`${t} must be a JSON object (e.g. '{"id":1}'), got ${Array.isArray(e)?"an array":typeof e}`);return e},S=/\/$/u,P="__lunora_admin__:runAs",I="__lunora_admin__:",O=async(r,t)=>{const e=await r.text();let a;try{a=JSON.parse(e)}catch{a=e}return t.info(JSON.stringify(a,void 0,2)),a},$=(r,t)=>{const e=t.body?.error?.code;t.runAs||t.status!==403||e!=="FORBIDDEN_SHARD"||r.info("this app authorizes per shard, so an anonymous call is denied — retry with --as <userId> to run as an authenticated user")},R=({args:r,claims:t,options:e,runAs:a})=>{const n=a?{args:{args:r,functionPath:e.functionPath,identity:t,userId:e.as},functionPath:P}:{args:r,functionPath:e.functionPath};return e.shard!==void 0&&(n.shardKey=e.shard),n},T=({cwd:r,logger:t,needsBearer:e,url:a})=>e?A(a,t,r):(_({cwd:r,url:a})??b(r)).replace(S,""),k=({args:r,claims:t},e)=>{try{return{args:f(r),claims:t===void 0?void 0:f(t,"--claims")}}catch(a){e.error(a instanceof Error?a.message:String(a));return}},E=async r=>{const t=r.cwd??process.cwd(),e=r.as!==void 0&&r.as!=="";if(r.claims!==void 0&&!e)return r.logger.error("--claims requires --as <userId> — extra identity claims only travel inside the admin-gated `runAs` dispatch."),{body:void 0,code:1,requestUrl:r.url??""};const a=e||r.functionPath.startsWith(I),n=T({cwd:t,logger:r.logger,needsBearer:a,url:r.url});if(n===void 0)return{body:void 0,code:1,requestUrl:r.url??""};const s=`${n}/_lunora/rpc`,i=r.fetchImpl??globalThis.fetch;if(typeof i!="function")throw new TypeError("no fetch implementation available — pass --fetch via dependency injection or run on Node >= 18");const c=k(r,r.logger);if(c===void 0)return{body:void 0,code:1,requestUrl:s};const{source:g,token:o}=a?y({cwd:t,token:r.token,url:n}):{};if(a&&o===void 0)return r.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{body:void 0,code:1,requestUrl:s};o!==void 0&&r.logger.debug?.(`admin bearer from ${v(g)}`);const h={"content-type":"application/json",...o===void 0?{}:{authorization:`Bearer ${o}`}},m=R({args:c.args,claims:c.claims,options:r,runAs:e});r.logger.info(`POST ${s} -> ${r.functionPath}${e?` (as ${r.as??""})`:""}`);const d=await i(s,{body:JSON.stringify(m),headers:h,method:"POST"}),u=await O(d,r.logger);return $(r.logger,{body:u,runAs:e,status:d.status}),{body:u,code:d.ok?0:1,requestUrl:s}},L=N(({argument:r,cwd:t,logger:e,options:a})=>{const n=r[0];return n?E({args:a.args,as:a.as,claims:a.claims,cwd:t,functionPath:n,logger:e,shard:a.shard,token:a.token,url:a.url}):(e.error("missing function path. Usage: lunora run <functionPath> [--args <json>]"),{code:1})});export{L as execute,O as readAndLogBody,E as runRpcCommand};
1
+ import{LunoraError as l}from"@lunora/errors";import{r as y,d as v}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{r as A,a as b}from"../packem_shared/admin-url-BhF5ufg1.mjs";import{d as N}from"../packem_shared/command-DwC11Cwe.mjs";import{a as _}from"../packem_shared/resolve-target-BRvw8Pf7.mjs";const f=(r,t="--args")=>{if(r===void 0||r.length===0)return{};let e;try{e=JSON.parse(r)}catch(a){const n=a instanceof Error?a.message:String(a);throw new l("INTERNAL",`failed to parse ${t} as JSON: ${n}`,{cause:a})}if(typeof e!="object"||e===null||Array.isArray(e))throw new l("INTERNAL",`${t} must be a JSON object (e.g. '{"id":1}'), got ${Array.isArray(e)?"an array":typeof e}`);return e},S=/\/$/u,P="__lunora_admin__:runAs",I="__lunora_admin__:",O=async(r,t)=>{const e=await r.text();let a;try{a=JSON.parse(e)}catch{a=e}return t.info(JSON.stringify(a,void 0,2)),a},$=(r,t)=>{const e=t.body?.error?.code;t.runAs||t.status!==403||e!=="FORBIDDEN_SHARD"||r.info("this app authorizes per shard, so an anonymous call is denied — retry with --as <userId> to run as an authenticated user")},R=({args:r,claims:t,options:e,runAs:a})=>{const n=a?{args:{args:r,functionPath:e.functionPath,identity:t,userId:e.as},functionPath:P}:{args:r,functionPath:e.functionPath};return e.shard!==void 0&&(n.shardKey=e.shard),n},T=({cwd:r,logger:t,needsBearer:e,url:a})=>e?A(a,t,r):(_({cwd:r,url:a})??b(r)).replace(S,""),k=({args:r,claims:t},e)=>{try{return{args:f(r),claims:t===void 0?void 0:f(t,"--claims")}}catch(a){e.error(a instanceof Error?a.message:String(a));return}},E=async r=>{const t=r.cwd??process.cwd(),e=r.as!==void 0&&r.as!=="";if(r.claims!==void 0&&!e)return r.logger.error("--claims requires --as <userId> — extra identity claims only travel inside the admin-gated `runAs` dispatch."),{body:void 0,code:1,requestUrl:r.url??""};const a=e||r.functionPath.startsWith(I),n=T({cwd:t,logger:r.logger,needsBearer:a,url:r.url});if(n===void 0)return{body:void 0,code:1,requestUrl:r.url??""};const s=`${n}/_lunora/rpc`,i=r.fetchImpl??globalThis.fetch;if(typeof i!="function")throw new TypeError("no fetch implementation available — pass --fetch via dependency injection or run on Node >= 18");const c=k(r,r.logger);if(c===void 0)return{body:void 0,code:1,requestUrl:s};const{source:g,token:o}=a?y({cwd:t,token:r.token,url:n}):{};if(a&&o===void 0)return r.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{body:void 0,code:1,requestUrl:s};o!==void 0&&r.logger.debug?.(`admin bearer from ${v(g)}`);const h={"content-type":"application/json",...o===void 0?{}:{authorization:`Bearer ${o}`}},m=R({args:c.args,claims:c.claims,options:r,runAs:e});r.logger.info(`POST ${s} -> ${r.functionPath}${e?` (as ${r.as??""})`:""}`);const d=await i(s,{body:JSON.stringify(m),headers:h,method:"POST"}),u=await O(d,r.logger);return $(r.logger,{body:u,runAs:e,status:d.status}),{body:u,code:d.ok?0:1,requestUrl:s}},L=N(({argument:r,cwd:t,logger:e,options:a})=>{const n=r[0];return n?E({args:a.args,as:a.as,claims:a.claims,cwd:t,functionPath:n,logger:e,shard:a.shard,token:a.token,url:a.url}):(e.error("missing function path. Usage: lunora run <functionPath> [--args <json>]"),{code:1})});export{L as execute,O as readAndLogBody,E as runRpcCommand};
@@ -1 +1 @@
1
- import{C as a,R as s,V as C,r as N}from"./cli-CiD-rkxB.mjs";import"./createLogger-hGafwf-3.mjs";export{a as COMMANDS,s as REGISTERED_COMMAND_NAMES,C as VERSION,N as runCli};
1
+ import{C as a,R as s,V as C,r as N}from"./cli-CqNvbTR1.mjs";import"./createLogger-hGafwf-3.mjs";export{a as COMMANDS,s as REGISTERED_COMMAND_NAMES,C as VERSION,N as runCli};
@@ -0,0 +1 @@
1
+ import"./admin-token-VdUnvnKW.mjs";import"./admin-url-BhF5ufg1.mjs";import{D as a,r as i}from"./import-8FCB0cUX.mjs";import"./shared-D-zCOmgY.mjs";export{a as DEFAULT_IMPORT_BATCH_SIZE,i as runImportCommand};
@@ -0,0 +1 @@
1
+ import{readFileSync as c}from"node:fs";import{join as v}from"node:path";import{DEV_VARS_FILE as i,parseDevVariableEntries as u}from"@lunora/config";const n="LUNORA_ADMIN_TOKEN",f=new Set(["127.0.0.1","::1","[::1]","localhost"]),a=e=>{if(e===void 0||e==="")return!0;try{return f.has(new URL(e).hostname)}catch{return!1}},d=e=>{let r;try{r=c(v(e,i),"utf8")}catch{return}const o=u(r).find(t=>t.key===n);return o?.value===""?void 0:o?.value},A=({cwd:e,token:r,url:o})=>{if(r!==void 0&&r!=="")return{source:"flag",token:r};const t=process.env[n];if(t!==void 0&&t!=="")return{source:"env",token:t};if(!a(o))return{};const s=d(e);return s===void 0?{}:{source:"dev-vars",token:s}},E=({prod:e,url:r})=>e===!0||r===""||!a(r),_=e=>e==="flag"?"--token":e==="env"?n:i;export{_ as d,A as r,E as t};
@@ -0,0 +1 @@
1
+ import{readLiveDevServerState as a}from"@lunora/config";const l=new Set(["127.0.0.1","::1","[::1]","localhost"]),i=/\/$/u,n="http://localhost:8787",c=r=>r===void 0?n:a(r)?.url??n,d=r=>r.replace(i,""),u=(r,o,s)=>{const e=r??c(s);let t;try{t=new URL(e)}catch{o.error(`invalid --url: ${e}`);return}if(!l.has(t.hostname)&&t.protocol!=="https:"){o.error(`refusing to send the admin bearer over ${t.protocol}// to ${t.hostname} — use https for non-localhost targets`);return}return d(e)};export{c as a,d as n,u as r};
@@ -0,0 +1 @@
1
+ import{b as l,c as o,l as r}from"./catalog-CJaormx0.mjs";import"./parseManifest-CwPTKdtS.mjs";export{l as buildRegistryIndex,o as collectCatalog,r as listItemDirectories};
@@ -0,0 +1 @@
1
+ import{existsSync as a,readFileSync as o,readdirSync as p,statSync as u}from"node:fs";import{join as r}from"@visulima/path";import m from"./parseManifest-CwPTKdtS.mjs";const l=/[\u0000-\u0008\u000A-\u001F\u007F-\u009F\u202A-\u202E\u2066-\u2069]/gu,d=e=>e.replaceAll(l,""),n=e=>e===void 0?void 0:d(e),c=e=>p(e).filter(i=>{const s=r(e,i);return u(s).isDirectory()&&a(r(s,"registry.json"))}),A=e=>{const i=r(e,"index.json");if(a(i)){const s=JSON.parse(o(i,"utf8"));if(Array.isArray(s.items))return s.items.filter(t=>typeof t=="object"&&t!==null&&typeof t.name=="string").map(t=>({description:n(t.description),name:n(t.name)??t.name}))}return c(e).map(s=>{const t=JSON.parse(o(r(e,s,"registry.json"),"utf8"));return{description:n(t.description),name:s}})},g=e=>({items:c(e).map(s=>{const t=m(JSON.parse(o(r(e,s,"registry.json"),"utf8")),s);return{...t.description===void 0?{}:{description:t.description},name:t.name,...t.title===void 0?{}:{title:t.title}}}).toSorted((s,t)=>s.name.localeCompare(t.name))});export{g as b,A as c,c as l,d as s};