@lunora/cli 1.0.0-alpha.20 → 1.0.0-alpha.201

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 (111) hide show
  1. package/LICENSE.md +33 -0
  2. package/README.md +1 -1
  3. package/__assets__/package-og.svg +1 -1
  4. package/dist/bin.mjs +2 -10
  5. package/dist/index.d.mts +672 -337
  6. package/dist/index.d.ts +672 -337
  7. package/dist/index.mjs +1 -19
  8. package/dist/packem_chunks/handler.mjs +1 -150
  9. package/dist/packem_chunks/handler10.mjs +2 -22
  10. package/dist/packem_chunks/handler11.mjs +2 -192
  11. package/dist/packem_chunks/handler12.mjs +1 -131
  12. package/dist/packem_chunks/handler13.mjs +1 -65
  13. package/dist/packem_chunks/handler14.mjs +1 -58
  14. package/dist/packem_chunks/handler15.mjs +1 -79
  15. package/dist/packem_chunks/handler16.mjs +3 -43
  16. package/dist/packem_chunks/handler17.mjs +1 -105
  17. package/dist/packem_chunks/handler18.mjs +1 -170
  18. package/dist/packem_chunks/handler19.mjs +7 -89
  19. package/dist/packem_chunks/handler2.mjs +2 -114
  20. package/dist/packem_chunks/handler20.mjs +2 -94
  21. package/dist/packem_chunks/handler21.mjs +2 -311
  22. package/dist/packem_chunks/handler22.mjs +3 -0
  23. package/dist/packem_chunks/handler23.mjs +3 -0
  24. package/dist/packem_chunks/handler24.mjs +1 -0
  25. package/dist/packem_chunks/handler25.mjs +99 -0
  26. package/dist/packem_chunks/handler26.mjs +10 -0
  27. package/dist/packem_chunks/handler3.mjs +1 -204
  28. package/dist/packem_chunks/handler4.mjs +1 -33
  29. package/dist/packem_chunks/handler5.mjs +1 -49
  30. package/dist/packem_chunks/handler6.mjs +1 -91
  31. package/dist/packem_chunks/handler7.mjs +3 -42
  32. package/dist/packem_chunks/handler8.mjs +1 -174
  33. package/dist/packem_chunks/handler9.mjs +1 -16
  34. package/dist/packem_chunks/planDevCommand.mjs +7 -500
  35. package/dist/packem_chunks/runCodegenCommand.mjs +4 -52
  36. package/dist/packem_chunks/runDeployCommand.mjs +1 -504
  37. package/dist/packem_chunks/runInitCommand.mjs +1021 -1337
  38. package/dist/packem_chunks/runMigrateGenerateCommand.mjs +9 -395
  39. package/dist/packem_chunks/runResetCommand.mjs +1 -41
  40. package/dist/packem_chunks/runRpcCommand.mjs +1 -68
  41. package/dist/packem_shared/COMMANDS-su5nmqYP.mjs +1 -0
  42. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Nf7GsE6v.mjs +1 -0
  43. package/dist/packem_shared/admin-token-rxXZbVMZ.mjs +1 -0
  44. package/dist/packem_shared/admin-url-Cil3Or6N.mjs +1 -0
  45. package/dist/packem_shared/advisory-gate-Cl8IEFIj.mjs +1 -0
  46. package/dist/packem_shared/api-spec-lYyq4vL6.mjs +1 -0
  47. package/dist/packem_shared/buildRegistryIndex-Zi3bBqpc.mjs +1 -0
  48. package/dist/packem_shared/cli-RB-BoDnW.mjs +3 -0
  49. package/dist/packem_shared/codegen-error-C04fGQjf.mjs +3 -0
  50. package/dist/packem_shared/command-DwC11Cwe.mjs +1 -0
  51. package/dist/packem_shared/commands-BOgN2nF7.mjs +19 -0
  52. package/dist/packem_shared/createLogger-hGafwf-3.mjs +2 -0
  53. package/dist/packem_shared/createRecordingSpawner-DJlNacZ6.mjs +1 -0
  54. package/dist/packem_shared/deploy-target-D9GPy_tq.mjs +1 -0
  55. package/dist/packem_shared/detect-package-manager-DSaAqRof.mjs +1 -0
  56. package/dist/packem_shared/diffSnapshots-CIOFQN_a.mjs +5 -0
  57. package/dist/packem_shared/docker-DpVxvYpL.mjs +1 -0
  58. package/dist/packem_shared/health-probe-QEPfFdgJ.mjs +1 -0
  59. package/dist/packem_shared/import-CrVGrOt3.mjs +12 -0
  60. package/dist/packem_shared/insertSchemaExtension-DY4pA8wE.mjs +8 -0
  61. package/dist/packem_shared/lint-ignore-report-CDbcbtv7.mjs +2 -0
  62. package/dist/packem_shared/open-url-EnKy--w-.mjs +1 -0
  63. package/dist/packem_shared/output-format-DfogXx0p.mjs +2 -0
  64. package/dist/packem_shared/parseManifest-CwPTKdtS.mjs +1 -0
  65. package/dist/packem_shared/path-containment-CgxYZggb.mjs +1 -0
  66. package/dist/packem_shared/platform-diagnostics-uOXqysk3.mjs +4 -0
  67. package/dist/packem_shared/post-codegen-hook-DRdEoTsQ.mjs +1 -0
  68. package/dist/packem_shared/prompt-cancelled-C8Sj7OqI.mjs +1 -0
  69. package/dist/packem_shared/resolve-DZAGzg67.mjs +1 -0
  70. package/dist/packem_shared/resolve-target-C_ZloTvd.mjs +1 -0
  71. package/dist/packem_shared/runAddCommand-BXz-PXbb.mjs +1 -0
  72. package/dist/packem_shared/runExportCommand-DmXKEWSq.mjs +5 -0
  73. package/dist/packem_shared/schema-drift-gate-AscQpYH5.mjs +1 -0
  74. package/dist/packem_shared/schemaIrToSnapshot-qpRoV7HY.mjs +1 -0
  75. package/dist/packem_shared/shared-D-zCOmgY.mjs +1 -0
  76. package/dist/packem_shared/tui-prompts-Dd0pDuNr.mjs +4 -0
  77. package/dist/packem_shared/vectorize-metadata-DbziRKpX.mjs +1 -0
  78. package/dist/packem_shared/wrangler-name-Dsk5K1f-.mjs +1 -0
  79. package/dist/packem_shared/wrangler-secrets-CE7jcf8E.mjs +1 -0
  80. package/package.json +40 -17
  81. package/skills/README.md +35 -17
  82. package/skills/lunora/SKILL.md +65 -9
  83. package/skills/lunora-functions/SKILL.md +38 -3
  84. package/skills/lunora-migration-helper/SKILL.md +70 -17
  85. package/skills/lunora-performance-audit/SKILL.md +36 -6
  86. package/skills/lunora-quickstart/SKILL.md +90 -24
  87. package/skills/lunora-realtime/SKILL.md +58 -30
  88. package/dist/packem_shared/COMMANDS-D3h9Iwvl.mjs +0 -944
  89. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Ck-2bU08.mjs +0 -244
  90. package/dist/packem_shared/admin-url-4UzT-CI4.mjs +0 -19
  91. package/dist/packem_shared/api-spec-CtA6ilu4.mjs +0 -13
  92. package/dist/packem_shared/buildRegistryIndex-BcYe607_.mjs +0 -38
  93. package/dist/packem_shared/command-BC30oSBW.mjs +0 -14
  94. package/dist/packem_shared/commands-hl0mRqqg.mjs +0 -845
  95. package/dist/packem_shared/createLogger-B40gPzQo.mjs +0 -78
  96. package/dist/packem_shared/createRecordingSpawner-DxI3mebw.mjs +0 -43
  97. package/dist/packem_shared/detect-package-manager-DYp7n3mJ.mjs +0 -61
  98. package/dist/packem_shared/diffSnapshots-BeDvvNiF.mjs +0 -161
  99. package/dist/packem_shared/docker-hMQ97KSQ.mjs +0 -21
  100. package/dist/packem_shared/insertSchemaExtension-DAqbfr9Z.mjs +0 -64
  101. package/dist/packem_shared/open-url-Dfq6fAyT.mjs +0 -41
  102. package/dist/packem_shared/output-format-wUvAN6AL.mjs +0 -17
  103. package/dist/packem_shared/parseArgs-YXFuKdEk.mjs +0 -56
  104. package/dist/packem_shared/parseManifest--vZf2FY1.mjs +0 -94
  105. package/dist/packem_shared/resolve-target-qbsJ_5sF.mjs +0 -16
  106. package/dist/packem_shared/runAddCommand-vJdgiR5t.mjs +0 -4
  107. package/dist/packem_shared/schema-drift-gate-BtBt0as0.mjs +0 -79
  108. package/dist/packem_shared/schemaIrToSnapshot-DdsljJT-.mjs +0 -43
  109. package/dist/packem_shared/storage-B7hHSTZP.mjs +0 -84
  110. package/dist/packem_shared/tui-prompts-M6OWsuyw.mjs +0 -663
  111. package/dist/packem_shared/wrangler-name-cy4yhm9j.mjs +0 -12
@@ -1,23 +1,11 @@
1
- import { existsSync, mkdirSync, writeFileSync, readFileSync, readdirSync, rmSync, mkdtempSync, cpSync, renameSync } from 'node:fs';
2
- import { tmpdir } from 'node:os';
3
- import { detectFramework as detectFramework$1, isInteractive, LUNA_ART, LUNA_NAME, LUNA_SIGNOFF, paintAnswer, BADGES } from '@lunora/config';
4
- import { walkSync } from '@visulima/fs';
5
- import { join as join$1, dirname as dirname$1, basename, resolve, relative } from '@visulima/path';
6
- import { downloadTemplate } from 'giget';
7
- import { modify, applyEdits } from 'jsonc-parser';
8
- import { join, dirname } from 'node:path';
9
- import { d as defineHandler } from '../packem_shared/command-BC30oSBW.mjs';
10
- import { a as detectInstalledManagers, i as installArgsFor } from '../packem_shared/detect-package-manager-DYp7n3mJ.mjs';
11
- import MagicString from 'magic-string';
12
- import { Project, SyntaxKind } from 'ts-morph';
13
- import { c as resolveTagVersions, d as resolveSourceRef, e as resolveDistTag, r as runAddCommand } from '../packem_shared/commands-hl0mRqqg.mjs';
14
- import { defaultSpawner } from '../packem_shared/createRecordingSpawner-DxI3mebw.mjs';
15
- import { d as tuiMascot, e as tuiStep, P as PromptCancelledError, f as tuiMoonrise, t as tuiText, g as tuiHeadline, h as tuiInfo, a as tuiSelect, b as tuiConfirm, w as withTuiSpinner, i as tuiNextSteps, j as tuiTasks, k as tuiMultiSelect, l as withTuiBadgeProgress } from '../packem_shared/tui-prompts-M6OWsuyw.mjs';
16
- import { logStep } from '../packem_shared/createLogger-B40gPzQo.mjs';
17
- import { E as EMAIL_ITEM, p as promptBucketName, w as withStorageBucketName, M as MAIL_DESTINATION_PROMPT, r as resolveTypedDestination, f as withMailDestination, e as promptAuthProvider, c as promptDatabaseName, g as withAuthDatabaseName } from '../packem_shared/storage-B7hHSTZP.mjs';
18
- import dns from 'node:dns/promises';
19
-
20
- const GITHUB_CONTENT = `name: Deploy
1
+ import{existsSync as m,mkdirSync as M,writeFileSync as v,readFileSync as b,readdirSync as re,rmSync as $,mkdtempSync as oe,cpSync as G,renameSync as Re,lstatSync as Oe}from"node:fs";import{tmpdir as se}from"node:os";import{detectFramework as Te,isInteractive as g,LUNA_ART as Pe,LUNA_NAME as De,LUNA_SIGNOFF as Be,BADGES as f,paintAnswer as je,detectLintTools as Ve,applyLintIgnores as Ue}from"@lunora/config";import{walkSync as Fe}from"@visulima/fs";import{join as u,dirname as A,basename as E,resolve as ne,relative as He}from"@visulima/path";import{downloadTemplate as ie}from"giget";import{modify as We,applyEdits as ze}from"jsonc-parser";import{join as V,dirname as qe}from"node:path";import{i as le,e as Ke,d as U,c as Ge,b as Je,a as Ye}from"../packem_shared/detect-package-manager-DSaAqRof.mjs";import{d as Xe}from"../packem_shared/command-DwC11Cwe.mjs";import Qe from"magic-string";import{Project as Ze,SyntaxKind as w}from"ts-morph";import{P as F}from"../packem_shared/prompt-cancelled-C8Sj7OqI.mjs";import{h as ce,d as de,i as ue,b as et}from"../packem_shared/resolve-DZAGzg67.mjs";import{defaultSpawner as pe}from"../packem_shared/createRecordingSpawner-DJlNacZ6.mjs";import{d as tt,e as at,f as rt,a as he,t as H,g as me,h as ot,b as fe,i as ve,w as st,j as nt,k as ge,l as it}from"../packem_shared/tui-prompts-Dd0pDuNr.mjs";import{E as we,p as lt,w as ct,M as dt,r as ut,k as pt,f as ht,c as ye,l as be,e as mt,g as ft}from"../packem_shared/lint-ignore-report-CDbcbtv7.mjs";import{logStep as J}from"../packem_shared/createLogger-hGafwf-3.mjs";import vt from"node:dns/promises";import{r as gt}from"../packem_shared/commands-BOgN2nF7.mjs";const W={bun:{githubCacheKey:void 0,githubSetupStep:` - uses: oven-sh/setup-bun@v2
2
+ `,gitlabImage:"oven/bun:1",gitlabProvisionScript:[],installCmd:"bun install --frozen-lockfile",lockfile:"bun.lockb"},npm:{githubCacheKey:"npm",githubSetupStep:"",gitlabImage:"node:22",gitlabProvisionScript:[],installCmd:"npm ci",lockfile:"package-lock.json"},pnpm:{githubCacheKey:"pnpm",githubSetupStep:` - uses: pnpm/action-setup@v4
3
+ `,gitlabImage:"node:22",gitlabProvisionScript:["corepack enable"],installCmd:"pnpm install --frozen-lockfile",lockfile:"pnpm-lock.yaml"},yarn:{githubCacheKey:"yarn",githubSetupStep:"",gitlabImage:"node:22",gitlabProvisionScript:["corepack enable"],installCmd:"yarn install --frozen-lockfile",lockfile:"yarn.lock"}},C=(e,t)=>{const a=Ke(e,"lunora",t);return[a.command,...a.args].join(" ")},Y=e=>` - uses: actions/checkout@v4
4
+ ${e.githubSetupStep} - uses: actions/setup-node@v4
5
+ with:
6
+ node-version: 22
7
+ ${e.githubCacheKey===void 0?"":` cache: ${e.githubCacheKey}
8
+ `} - run: ${e.installCmd}`,wt=e=>{const t=W[e],a=t.githubCacheKey===void 0?`# (below) requires it — run \`${e} install\` locally and`:`# (below) and the ${e} cache both require it — run \`${e} install\` locally and`;return`name: Deploy
21
9
 
22
10
  on:
23
11
  push:
@@ -25,8 +13,8 @@ on:
25
13
  pull_request:
26
14
  workflow_dispatch:
27
15
 
28
- # Prerequisite: commit your pnpm-lock.yaml. \`pnpm install --frozen-lockfile\`
29
- # (below) and the pnpm cache both require it — run \`pnpm install\` locally and
16
+ # Prerequisite: commit your ${t.lockfile}. \`${t.installCmd}\`
17
+ ${a}
30
18
  # commit the lockfile before pushing, or the first CI run fails.
31
19
  #
32
20
  # Set these repository secrets (Settings → Secrets and variables → Actions):
@@ -44,16 +32,10 @@ jobs:
44
32
  permissions:
45
33
  contents: read
46
34
  steps:
47
- - uses: actions/checkout@v4
48
- - uses: pnpm/action-setup@v4
49
- - uses: actions/setup-node@v4
50
- with:
51
- node-version: 22
52
- cache: pnpm
53
- - run: pnpm install --frozen-lockfile
35
+ ${Y(t)}
54
36
  # Codegen + wrangler validation gate (no deploy) — fails fast on drift.
55
- - run: pnpm exec lunora prepare
56
- - run: pnpm exec lunora deploy
37
+ - run: ${C(e,["prepare"])}
38
+ - run: ${C(e,["deploy"])}
57
39
 
58
40
  # Preview version on every pull request — uploads a versioned preview URL;
59
41
  # production traffic is untouched.
@@ -63,31 +45,24 @@ jobs:
63
45
  permissions:
64
46
  contents: read
65
47
  steps:
66
- - uses: actions/checkout@v4
67
- - uses: pnpm/action-setup@v4
68
- - uses: actions/setup-node@v4
69
- with:
70
- node-version: 22
71
- cache: pnpm
72
- - run: pnpm install --frozen-lockfile
73
- - run: pnpm exec lunora deploy --preview
74
- `;
75
- const GITLAB_CONTENT = `stages:
48
+ ${Y(t)}
49
+ - run: ${C(e,["deploy","--preview"])}
50
+ `},yt=e=>{const t=W[e],a=[...t.gitlabProvisionScript,t.installCmd].map(r=>` - ${r}`).join(`
51
+ `);return`stages:
76
52
  - deploy
77
53
 
78
- # Prerequisite: commit your pnpm-lock.yaml. \`pnpm install --frozen-lockfile\`
79
- # (below) requires it — run \`pnpm install\` locally and commit the lockfile
54
+ # Prerequisite: commit your ${t.lockfile}. \`${t.installCmd}\`
55
+ # (below) requires it — run \`${e} install\` locally and commit the lockfile
80
56
  # before pushing, or the first pipeline fails.
81
57
  #
82
58
  # Set these as masked CI/CD variables (Settings → CI/CD → Variables):
83
59
  # CLOUDFLARE_API_TOKEN — a Workers-scoped API token
84
60
  # CLOUDFLARE_ACCOUNT_ID — your Cloudflare account id
85
61
  .lunora_base:
86
- image: node:22
62
+ image: ${t.gitlabImage}
87
63
  stage: deploy
88
64
  before_script:
89
- - corepack enable
90
- - pnpm install --frozen-lockfile
65
+ ${a}
91
66
 
92
67
  # Production deploy on the default branch.
93
68
  deploy:
@@ -96,8 +71,8 @@ deploy:
96
71
  - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
97
72
  script:
98
73
  # Codegen + wrangler validation gate (no deploy) — fails fast on drift.
99
- - pnpm exec lunora prepare
100
- - pnpm exec lunora deploy
74
+ - ${C(e,["prepare"])}
75
+ - ${C(e,["deploy"])}
101
76
 
102
77
  # Preview version on every merge request (versioned preview URL; production
103
78
  # traffic is untouched).
@@ -106,287 +81,923 @@ preview:
106
81
  rules:
107
82
  - if: $CI_PIPELINE_SOURCE == "merge_request_event"
108
83
  script:
109
- - pnpm exec lunora deploy --preview
110
- `;
111
- const WORKFLOWS = {
112
- github: {
113
- content: GITHUB_CONTENT,
114
- file: join(".github", "workflows", "deploy.yml"),
115
- secretsHint: "repository secrets (Settings → Secrets and variables → Actions)"
116
- },
117
- gitlab: {
118
- content: GITLAB_CONTENT,
119
- file: ".gitlab-ci.yml",
120
- secretsHint: "masked CI/CD variables (Settings CI/CD Variables)"
121
- }
122
- };
123
- const isCiProvider = (value) => value === "github" || value === "gitlab";
124
- const writeCiWorkflow = (projectRoot, provider, options = {}) => {
125
- const spec = WORKFLOWS[provider];
126
- const path = join(projectRoot, spec.file);
127
- if (existsSync(path) && options.overwrite !== true) {
128
- return { path, skipped: true, written: false };
129
- }
130
- mkdirSync(dirname(path), { recursive: true });
131
- writeFileSync(path, spec.content, "utf8");
132
- return { path, skipped: false, written: true };
133
- };
134
- const scaffoldCiWorkflow = (projectRoot, provider, logger, options = {}) => {
135
- const spec = WORKFLOWS[provider];
136
- try {
137
- const result = writeCiWorkflow(projectRoot, provider, options);
138
- if (result.skipped) {
139
- logger.info(`--ci ${provider}: ${spec.file} already exists — left unchanged (re-run with overwrite to replace).`);
140
- } else {
141
- logger.success(`--ci ${provider}: wrote ${spec.file}`);
142
- logger.info(`--ci ${provider}: set CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID as ${spec.secretsHint} to enable deploys.`);
143
- logger.info(
144
- `--ci ${provider}: run \`pnpm install\` and commit pnpm-lock.yaml before pushing — the pipeline runs \`pnpm install --frozen-lockfile\`.`
145
- );
146
- }
147
- return result;
148
- } catch (error) {
149
- const message = error instanceof Error ? error.message : String(error);
150
- logger.warn(`--ci ${provider}: could not write ${spec.file} (${message})`);
151
- return { path: join(projectRoot, spec.file), skipped: false, written: false };
152
- }
153
- };
84
+ - ${C(e,["deploy","--preview"])}
85
+ `},xe={github:{file:V(".github","workflows","deploy.yml"),secretsHint:"repository secrets (Settings → Secrets and variables → Actions)"},gitlab:{file:".gitlab-ci.yml",secretsHint:"masked CI/CD variables (Settings → CI/CD → Variables)"}},bt=(e,t)=>e==="github"?wt(t):yt(t),xt=e=>e==="github"||e==="gitlab",kt=(e,t,a,r={})=>{const o=V(e,xe[t].file);return m(o)&&r.overwrite!==!0?{path:o,skipped:!0,written:!1}:(M(qe(o),{recursive:!0}),v(o,bt(t,a),"utf8"),{path:o,skipped:!1,written:!0})},Ct=(e,t,a,r,o={})=>{const s=xe[t];try{const n=kt(e,t,a,o);if(n.skipped)r.info(`--ci ${t}: ${s.file} already exists — left unchanged (re-run with overwrite to replace).`);else{const i=le(a),l=[i.command,...i.args].join(" "),{installCmd:d,lockfile:c}=W[a];r.success(`--ci ${t}: wrote ${s.file}`),r.info(`--ci ${t}: set CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID as ${s.secretsHint} to enable deploys.`),r.info(`--ci ${t}: run \`${l}\` and commit ${c} before pushing — the pipeline runs \`${d}\`.`)}return n}catch(n){const i=n instanceof Error?n.message:String(n);return r.warn(`--ci ${t}: could not write ${s.file} (${i})`),{path:V(e,s.file),skipped:!1,written:!1}}},St={astro:"@lunora/react",none:"@lunora/react",nuxt:"@lunora/vue","react-router":"@lunora/react","solid-start":"@lunora/solid",sveltekit:"@lunora/svelte","tanstack-start":"@lunora/react","tanstack-start-solid":"@lunora/solid",vinext:"@lunora/react"},Lt=e=>{const t=Te(e);return{...t,adapter:St[t.framework]}},_="lunora()",X='import { lunora } from "@lunora/vite";',Mt=/\blunora\s*\(/u,At='"@lunora/vite"',Et="'@lunora/vite'",Nt=e=>{for(const t of e.getStatements()){if(t.getKind()!==w.ExportAssignment)continue;const a=t.asKindOrThrow(w.ExportAssignment).getExpression();if(a.getKind()!==w.CallExpression)continue;const r=a.asKindOrThrow(w.CallExpression);if(r.getExpression().getText()!=="defineConfig")continue;const o=r.getArguments()[0];if(o?.getKind()===w.ObjectLiteralExpression)return o.asKindOrThrow(w.ObjectLiteralExpression)}},It=e=>{for(const t of e.getStatements()){if(t.getKind()!==w.ExportAssignment)continue;const a=t.asKindOrThrow(w.ExportAssignment).getExpression();if(a.getKind()===w.ObjectLiteralExpression)return a.asKindOrThrow(w.ObjectLiteralExpression)}},_t=e=>new Ze({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}).createSourceFile("vite.config.ts",e,{overwrite:!0}),$t=(e,t)=>{const a=t.getImportDeclarations().at(-1)?.getEnd()??0;a===0?e.prepend(`${X}
86
+ `):e.appendLeft(a,`
87
+ ${X}`)},Rt=(e,t)=>{const a=t.getProperty("plugins");if(a===void 0){const s=t.getProperties(),n=t.getStart()+1;if(s.length===0)e.appendLeft(n,` plugins: [${_}] `);else{const i=s[0];i!==void 0&&e.appendLeft(i.getStart(),`plugins: [${_}],
88
+ `)}return}const r=a.getDescendantsOfKind(w.ArrayLiteralExpression)[0];if(r===void 0)return;const o=r.getElements();if(o.length===0)e.appendLeft(r.getStart()+1,_);else{const s=o[0];s!==void 0&&e.appendLeft(s.getStart(),`${_}, `)}},ke=e=>{if(Mt.test(e))return{changed:!1,code:e,reason:"lunora plugin already present"};const t=_t(e),a=Nt(t)??It(t);if(a===void 0)return{changed:!1,code:e,reason:"could not locate a Vite config plugins array to patch"};const r=new Qe(e);return!e.includes(At)&&!e.includes(Et)&&$t(r,t),Rt(r,a),{changed:!0,code:r.toString()}},Ot=/enotfound|eai_again|econnrefused|etimedout|network|fetch failed|getaddrinfo/u,Tt=/404|not found|could not find|no such/u,Pt=(e,t)=>{const a=e instanceof Error?e.message:String(e),r=a.toLowerCase(),o=`failed to download template "${t.templateType}" from ${t.remote}: ${a}`;return Tt.test(r)?{hints:[`Check the template name "${t.templateType}" and the ref "${t.ref}".`,"List/inspect available templates, or target a branch/tag with `--ref <branch>`."],message:`template "${t.templateType}" not found at ${t.remote}: ${a}`}:Ot.test(r)?{hints:["You appear to be offline or unable to reach GitHub.","To scaffold without a network, point at a local template root: `lunora init --from <dir>`."],message:o}:{hints:["If this is a network/offline issue, scaffold from a local root with `lunora init --from <dir>`."],message:o}},R=async(e,t,a)=>{if(g()){await at(f[e],t,a);return}if(process.stdout.write(`
89
+ `),a===void 0||a===""){J(e,t);return}const r=a.split(`
90
+ `).map(o=>je(o)).join(`
91
+ `);J(e,`${t}
92
+ ${r}`)},Dt=async e=>{if(g()){await tt();return}e.info(`
93
+ ${Pe}
94
+ ${De}: ${Be}`)},Ce=[{description:"LLMs via Workers AI (summarize, generate, stream)",label:"AI",value:"ai"},{description:"Sign-up / sign-in (asks which provider)",label:"Authentication",value:"auth"},{description:"Copy-in auth screens for your framework (sign in/up, reset, 2FA)",label:"Auth UI",value:"auth-ui"},{description:"Snapshot + restore your Durable Object data",label:"Backups",value:"backup"},{description:"Headless browser screenshots + PDFs",label:"Browser rendering",value:"browser"},{description:"Zero Trust identity via Cloudflare Access",label:"Cloudflare Access",value:"cloudflare-access"},{description:"Scheduled jobs via Cron Triggers (@lunora/scheduler)",label:"Cron jobs",value:"crons"},{description:"Cloudflare Email Workers + a dev mail catcher",label:"Transactional email",value:"email"},{description:"OpenFeature feature flags (ctx.flags)",label:"Feature flags",value:"flags"},{description:"External Postgres/MySQL via Hyperdrive",label:"Hyperdrive",value:"hyperdrive"},{description:"Stripe-first payments (checkout, subscription, webhooks)",label:"Payments",value:"payment"},{description:"Live presence / who's-online over hibernated WebSockets",label:"Presence",value:"presence"},{description:"Async message queues (push/pull consumers)",label:"Queues",value:"queue"},{description:"Typed R2 buckets + signed URLs (@lunora/storage)",label:"File storage",value:"storage"},{description:"Durable long-running workflows (step.do, sleep, branch)",label:"Workflows",value:"workflow"}],Q=Ce.map(e=>e.value),Bt=e=>e==="email"?we:e,jt=(e,t)=>{const a=[];for(const r of e.split(",").map(o=>o.trim()).filter(Boolean))Q.includes(r)?a.includes(r)||a.push(r):t(`init: unknown --add feature "${r}" — expected ${Q.join(" | ")}; skipping.`);return a},Vt=async e=>{const t=await ht(e.select),a=await ye(e.text,e.projectName);return{label:"auth",names:[t],transformManifest:r=>be(r,a)}},Ut=async e=>{const t=await e.text(dt,{placeholder:"you@yourdomain.com"}),a=ut(t,r=>{e.logger.warn(r)});return{label:"email",names:[we],transformManifest:a===void 0?void 0:r=>pt(r,a)}},Ft=async(e,t)=>{const a=e.resolveAuthUiItem?.()??"auth-ui-react";if(t)return{label:"auth-ui",names:[a]};const r=await ye(e.text,e.projectName);return{label:"auth-ui",names:[a],transformManifest:o=>be(o,r)}},Ht=async e=>{const t=await lt(e.text,e.projectName);return{label:"storage",names:["storage"],transformManifest:a=>ct(a,t)}},Wt={auth:Vt,"auth-ui":async(e,t)=>Ft(e,t.includes("auth")),email:Ut,storage:Ht},Z=async e=>{if(e.preselected!==void 0&&e.preselected.length>0){await e.applyAll(e.preselected.map(r=>{const o=r==="auth-ui"?e.resolveAuthUiItem?.()??"auth-ui-react":Bt(r);return{label:r,names:[o]}}));return}if(!e.interactive){e.logger.info("tip: add features later with `lunora add <ai|auth|backup|browser|cloudflare-access|crons|email|flags|hyperdrive|payment|presence|queue|storage|workflow>`.");return}const t=await e.multiSelect("Which features do you want to add?",Ce,{defaults:[]});if(t.length===0)return;const a=[];for(const r of t){const o=Wt[r];a.push(o?await o(e,t):{label:r,names:[r]})}await e.applyAll(a)},zt=[{description:"Adds an ignores entry to eslint.config.js",label:"ESLint",value:"eslint"},{description:"Writes .prettierignore",label:"Prettier",value:"prettier"},{description:"Adds negated patterns to biome.json",label:"Biome",value:"biome"},{description:"Writes ignorePatterns to .oxlintrc.json",label:"oxlint (oxc)",value:"oxlint"}],qt="Which linter/formatter do you use? We'll tell it to skip Lunora's generated files.",Kt=async e=>{const t=e.interactive?await e.multiSelect(qt,zt,{defaults:e.detected}):[...e.detected];if(t.length===0)return[];const a=e.apply(t);return mt(a,e.logger),a},N="M 259.500 10.552 C 220.080 15.859, 182.424 32.566, 152.500 58.025 C 110.179 94.031, 85.380 137.183, 77.518 188.500 C 75.410 202.255, 74.569 225.677, 75.796 236.466 C 76.757 244.917, 76.683 245.692, 74.518 249.966 C 63.118 272.466, 53.141 303.876, 51.382 322.799 L 50.718 329.943 71.960 320.471 C 83.643 315.262, 93.326 311, 93.478 311 C 93.630 311, 96.547 316.063, 99.959 322.250 C 103.371 328.438, 107.249 334.850, 108.577 336.500 L 110.990 339.500 110.981 336 C 110.977 334.075, 111.499 324.991, 112.143 315.813 L 113.312 299.127 121.406 293.336 C 132.495 285.403, 149.593 271.554, 161 261.268 C 171.556 251.748, 189.116 235, 188.540 235 C 188.337 235, 183.069 238.648, 176.835 243.106 C 142.318 267.789, 68.537 314, 63.646 314 C 61.843 314, 72.791 281.179, 80.905 262.259 C 92.233 235.845, 107.473 212.389, 132.106 183.453 L 138.451 176 148.268 176 C 176.192 176, 197.512 187.154, 212.868 209.797 C 216.470 215.108, 217.035 216.595, 216.477 219.297 C 211.386 243.968, 202.359 274.496, 193.797 296 C 183.898 320.861, 167.147 352.101, 152.395 373.215 L 147.004 380.930 152.891 385.830 C 161.400 392.911, 165.563 396, 166.594 395.998 C 167.092 395.998, 168.772 391.641, 170.327 386.317 C 176.279 365.934, 188.422 338.749, 200.942 317.778 C 223.060 280.731, 256.432 244.369, 294.500 215.836 C 309.956 204.252, 313.937 201.603, 314.719 202.385 C 315.116 202.783, 315.449 213.096, 315.460 225.304 C 315.474 241.855, 315.021 250.405, 313.680 258.924 C 307.009 301.272, 291.175 336.677, 263.112 372 C 255.259 381.883, 227.182 410.673, 218.516 417.727 L 213.532 421.783 223.439 424.880 C 281.705 443.093, 349.165 436.018, 398.616 406.508 C 446.728 377.797, 483.322 331.466, 497.366 281.481 C 503.381 260.075, 504.480 250.741, 504.491 221 C 504.501 191.997, 503.598 184.047, 497.987 163.732 C 484.768 115.871, 452.505 72.708, 407.718 42.964 C 381.051 25.254, 352.818 14.828, 319.695 10.460 C 305.932 8.645, 273.298 8.695, 259.500 10.552",L=`/* The welcome page is a full-bleed starter — reset the browser's default
95
+ body margin/padding so it sits flush; everything else is scoped under
96
+ .lunora-welcome (collision-safe). */
97
+ body {
98
+ margin: 0;
99
+ padding: 0;
100
+ }
154
101
 
155
- const ADAPTER_BY_FRAMEWORK = {
156
- astro: "@lunora/react",
157
- none: "@lunora/react",
158
- nuxt: "@lunora/vue",
159
- "react-router": "@lunora/react",
160
- "solid-start": "@lunora/solid",
161
- sveltekit: "@lunora/svelte",
162
- "tanstack-start": "@lunora/react",
163
- "tanstack-start-solid": "@lunora/solid"
164
- };
165
- const detectFramework = (root) => {
166
- const base = detectFramework$1(root);
167
- return { ...base, adapter: ADAPTER_BY_FRAMEWORK[base.framework] };
168
- };
102
+ .lunora-welcome {
103
+ --cyan: hsl(186 84% 56%); --violet: hsl(256 72% 68%); --rose: hsl(330 80% 64%);
104
+ --ribbon: linear-gradient(115deg, var(--cyan), var(--violet) 52%, var(--rose));
105
+ --sans: "Geist Sans", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
106
+ --mono: "Geist Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace;
107
+ /* NIGHT (default) */
108
+ --bg: #0e0e11; --surface: hsl(240 12% 8% / 0.72); --surface-2: hsl(240 11% 11% / 0.82);
109
+ --line: hsl(0 0% 100% / 0.08); --line-2: hsl(0 0% 100% / 0.14);
110
+ --t-display: hsl(228 30% 97%); --t-primary: hsl(228 26% 90%); --t-secondary: hsl(228 12% 62%); --t-faint: hsl(228 10% 44%);
111
+ --logo: hsl(228 30% 97%); --accent: var(--violet); --shot-bg: hsl(240 12% 6%);
112
+ --glow-1: hsl(256 80% 52% / 0.30); --glow-2: hsl(196 84% 52% / 0.13); --arc: hsl(256 60% 70% / 0.11);
169
113
 
170
- const LUNORA_CALL = "lunora()";
171
- const LUNORA_IMPORT = 'import { lunora } from "@lunora/vite";';
172
- const LUNORA_CALL_RE = /\blunora\s*\(/u;
173
- const LUNORA_VITE_DOUBLE = '"@lunora/vite"';
174
- const LUNORA_VITE_SINGLE = "'@lunora/vite'";
175
- const findDefineConfigObject = (sf) => {
176
- for (const statement of sf.getStatements()) {
177
- if (statement.getKind() !== SyntaxKind.ExportAssignment) {
178
- continue;
179
- }
180
- const expr = statement.asKindOrThrow(SyntaxKind.ExportAssignment).getExpression();
181
- if (expr.getKind() !== SyntaxKind.CallExpression) {
182
- continue;
183
- }
184
- const call = expr.asKindOrThrow(SyntaxKind.CallExpression);
185
- if (call.getExpression().getText() !== "defineConfig") {
186
- continue;
187
- }
188
- const argument = call.getArguments()[0];
189
- if (argument?.getKind() === SyntaxKind.ObjectLiteralExpression) {
190
- return argument.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);
191
- }
192
- }
193
- return void 0;
194
- };
195
- const findPlainExportObject = (sf) => {
196
- for (const statement of sf.getStatements()) {
197
- if (statement.getKind() !== SyntaxKind.ExportAssignment) {
198
- continue;
199
- }
200
- const expr = statement.asKindOrThrow(SyntaxKind.ExportAssignment).getExpression();
201
- if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {
202
- return expr.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);
203
- }
204
- }
205
- return void 0;
206
- };
207
- const findConfigObject = (sourceText) => {
208
- const project = new Project({
209
- compilerOptions: { allowJs: true },
210
- useInMemoryFileSystem: true
211
- });
212
- const sf = project.createSourceFile("vite.config.ts", sourceText, { overwrite: true });
213
- return findDefineConfigObject(sf) ?? findPlainExportObject(sf);
214
- };
215
- const importInsertPosition = (sourceText) => {
216
- const project = new Project({
217
- compilerOptions: { allowJs: true },
218
- useInMemoryFileSystem: true
219
- });
220
- const sf = project.createSourceFile("vite.config.ts", sourceText, { overwrite: true });
221
- const imports = sf.getImportDeclarations();
222
- if (imports.length === 0) {
223
- return 0;
224
- }
225
- const last = imports[imports.length - 1];
226
- if (last === void 0) {
227
- return 0;
228
- }
229
- return last.getEnd();
230
- };
231
- const addImport = (ms, source) => {
232
- const insertAt = importInsertPosition(source);
233
- if (insertAt === 0) {
234
- ms.prepend(`${LUNORA_IMPORT}
235
- `);
236
- } else {
237
- ms.appendLeft(insertAt, `
238
- ${LUNORA_IMPORT}`);
239
- }
240
- };
241
- const patchPluginsArray = (ms, configObject) => {
242
- const pluginsProp = configObject.getProperty("plugins");
243
- if (pluginsProp === void 0) {
244
- const properties = configObject.getProperties();
245
- const openBrace = configObject.getStart() + 1;
246
- if (properties.length === 0) {
247
- ms.appendLeft(openBrace, ` plugins: [${LUNORA_CALL}] `);
248
- } else {
249
- const firstProp = properties[0];
250
- if (firstProp !== void 0) {
251
- ms.appendLeft(firstProp.getStart(), `plugins: [${LUNORA_CALL}],
252
- `);
253
- }
254
- }
255
- return;
256
- }
257
- const arrayLit = pluginsProp.getDescendantsOfKind(SyntaxKind.ArrayLiteralExpression)[0];
258
- if (arrayLit === void 0) {
259
- return;
260
- }
261
- const elements = arrayLit.getElements();
262
- if (elements.length === 0) {
263
- ms.appendLeft(arrayLit.getStart() + 1, LUNORA_CALL);
264
- } else {
265
- const firstElement = elements[0];
266
- if (firstElement !== void 0) {
267
- ms.appendLeft(firstElement.getStart(), `${LUNORA_CALL}, `);
268
- }
269
- }
270
- };
271
- const patchViteConfig = (source) => {
272
- if (LUNORA_CALL_RE.test(source)) {
273
- return { changed: false, code: source, reason: "lunora plugin already present" };
274
- }
275
- const configObject = findConfigObject(source);
276
- if (configObject === void 0) {
277
- return { changed: false, code: source, reason: "could not locate a Vite config plugins array to patch" };
278
- }
279
- const ms = new MagicString(source);
280
- const alreadyImported = source.includes(LUNORA_VITE_DOUBLE) || source.includes(LUNORA_VITE_SINGLE);
281
- if (alreadyImported) {
282
- patchPluginsArray(ms, configObject);
283
- } else {
284
- addImport(ms, source);
285
- patchPluginsArray(ms, configObject);
286
- }
287
- return { changed: true, code: ms.toString() };
288
- };
114
+ position: relative; min-height: 100vh; background: var(--bg); color: var(--t-primary);
115
+ font-family: var(--sans); line-height: 1.55; -webkit-font-smoothing: antialiased; overflow-x: hidden;
116
+ transition: background .3s, color .3s;
117
+ }
118
+ .lunora-welcome[data-theme="light"] {
119
+ --bg: hsl(228 32% 97%); --surface: hsl(0 0% 100% / 0.82); --surface-2: hsl(0 0% 100% / 0.95);
120
+ --line: hsl(228 16% 88%); --line-2: hsl(228 14% 80%);
121
+ --t-display: hsl(240 14% 10%); --t-primary: hsl(240 12% 18%); --t-secondary: hsl(235 9% 42%); --t-faint: hsl(235 8% 58%);
122
+ --logo: hsl(240 16% 9%); --accent: hsl(256 58% 56%); --shot-bg: hsl(228 26% 99%);
123
+ --glow-1: hsl(256 80% 60% / 0.14); --glow-2: hsl(196 84% 58% / 0.08); --arc: hsl(256 40% 55% / 0.12);
124
+ }
125
+ .lunora-welcome *, .lunora-welcome *::before, .lunora-welcome *::after { box-sizing: border-box; }
126
+ .lunora-welcome a { color: inherit; text-decoration: none; }
127
+ .lunora-welcome button { font-family: inherit; cursor: pointer; }
128
+ .lunora-welcome ::selection { background: hsl(256 72% 68% / 0.3); }
129
+ .lunora-welcome code { font-family: var(--mono); }
289
130
 
290
- const emitStep = async (type, message, answer) => {
291
- if (isInteractive()) {
292
- await tuiStep(BADGES[type], message, answer);
293
- return;
294
- }
295
- process.stdout.write("\n");
296
- if (answer === void 0 || answer === "") {
297
- logStep(type, message);
298
- return;
299
- }
300
- const dimmed = answer.split("\n").map((line) => paintAnswer(line)).join("\n");
301
- logStep(type, `${message}
302
- ${dimmed}`);
303
- };
304
- const emitMascot = async (logger) => {
305
- if (isInteractive()) {
306
- await tuiMascot();
307
- return;
308
- }
309
- logger.info(`
310
- ${LUNA_ART}
311
- ${LUNA_NAME}: ${LUNA_SIGNOFF}`);
312
- };
131
+ /* glow background */
132
+ .lunora-welcome .lw-bg { position: fixed; inset: 0; z-index: 0; pointer-events: none; overflow: hidden; }
133
+ .lunora-welcome .lw-bg .glow { position: absolute; left: 50%; top: -4%; width: 860px; height: 720px; transform: translateX(-50%);
134
+ border-radius: 50%; background: radial-gradient(circle at 50% 50%, var(--glow-1), var(--glow-2) 40%, transparent 66%); }
135
+ .lunora-welcome .lw-bg .arc { position: absolute; left: 50%; border-radius: 50%; border: 1px solid var(--arc); transform: translateX(-50%); }
136
+ .lunora-welcome .lw-bg .arc.a1 { top: -340px; width: 980px; height: 980px; }
137
+ .lunora-welcome .lw-bg .arc.a2 { top: -240px; width: 720px; height: 720px; opacity: .7; }
138
+
139
+ /* theme toggle */
140
+ .lunora-welcome .lw-toggle { position: fixed; z-index: 5; top: 20px; right: clamp(16px,4vw,36px); display: inline-flex; align-items: center;
141
+ gap: 7px; border: 1px solid var(--line-2); background: var(--surface); backdrop-filter: blur(12px); color: var(--t-secondary);
142
+ font-family: var(--mono); font-size: 10.5px; letter-spacing: .1em; text-transform: uppercase; padding: 7px 11px; transition: .15s; }
143
+ .lunora-welcome .lw-toggle:hover { color: var(--t-display); border-color: var(--accent); }
144
+ .lunora-welcome .lw-toggle svg { width: 13px; height: 13px; }
145
+
146
+ .lunora-welcome .lw-wrap { position: relative; z-index: 2; width: 100%; max-width: 1080px; margin: 0 auto;
147
+ padding: clamp(44px,8vh,92px) clamp(20px,5vw,48px); display: flex; flex-direction: column; min-height: 100vh; }
148
+ .lunora-welcome .brand { display: flex; align-items: center; justify-content: center; gap: 15px; margin-bottom: clamp(38px,6vh,68px); color: var(--logo); }
149
+ .lunora-welcome .brand svg { width: 54px; height: auto; display: block; }
150
+ .lunora-welcome .brand .word { font-size: 34px; font-weight: 600; letter-spacing: -0.03em; color: var(--t-display); }
151
+
152
+ .lunora-welcome .grid { display: grid; grid-template-columns: 1.06fr 0.94fr; gap: 16px; align-items: stretch; flex: 1; max-height: 580px; }
153
+ @media (max-width: 820px) { .lunora-welcome .grid { grid-template-columns: 1fr; max-height: none; } }
154
+
155
+ .lunora-welcome .card { border: 1px solid var(--line); background: var(--surface); backdrop-filter: blur(10px); transition: border-color .2s, background .2s; }
156
+ .lunora-welcome .card:hover { border-color: var(--line-2); background: var(--surface-2); }
157
+ .lunora-welcome .card:hover .arrow { color: var(--accent); transform: translateX(3px); }
158
+ .lunora-welcome .arrow { color: var(--t-faint); transition: color .2s, transform .2s; }
159
+ .lunora-welcome .arrow svg { width: 20px; height: 20px; display: block; }
160
+ .lunora-welcome .ic { display: grid; place-items: center; color: var(--accent);
161
+ border: 1px solid color-mix(in oklab, var(--accent) 36%, transparent); background: color-mix(in oklab, var(--accent) 12%, transparent); }
162
+ .lunora-welcome .ic svg { display: block; }
163
+
164
+ /* left feature card — stretches to fill the box height */
165
+ .lunora-welcome .feature { padding: clamp(18px,2vw,24px); display: flex; flex-direction: column; }
166
+ .lunora-welcome .shot { border: 1px solid var(--line); overflow: hidden; background: var(--shot-bg);
167
+ -webkit-mask-image: linear-gradient(to bottom, #000 56%, transparent 100%); mask-image: linear-gradient(to bottom, #000 56%, transparent 100%); }
168
+ .lunora-welcome .shot .top { display: flex; align-items: center; gap: 12px; padding: 11px 14px; border-bottom: 1px solid var(--line); }
169
+ .lunora-welcome .shot .wm { display: flex; align-items: center; gap: 7px; font-size: 12px; font-weight: 600; color: var(--t-primary); }
170
+ .lunora-welcome .shot .wm i { width: 11px; height: 11px; background: var(--ribbon); -webkit-mask: radial-gradient(circle,#000 60%,transparent 62%); mask: radial-gradient(circle,#000 60%,transparent 62%); }
171
+ .lunora-welcome .shot .search { flex: 1; height: 22px; border: 1px solid var(--line); border-radius: 4px; }
172
+ .lunora-welcome .shot .ver { font-family: var(--mono); font-size: 8px; letter-spacing: .08em; color: var(--t-faint); }
173
+ .lunora-welcome .shot .body { display: grid; grid-template-columns: 92px 1fr; min-height: 224px; }
174
+ .lunora-welcome .shot .nav { border-right: 1px solid var(--line); padding: 14px 12px; display: flex; flex-direction: column; gap: 11px; }
175
+ .lunora-welcome .shot .nav i, .lunora-welcome .shot .doc i { height: 5px; border-radius: 2px; background: var(--line); }
176
+ .lunora-welcome .shot .doc { padding: 16px 18px; display: flex; flex-direction: column; gap: 9px; }
177
+ .lunora-welcome .shot .doc .h { height: 8px; width: 46%; border-radius: 2px; background: var(--line-2); margin-bottom: 5px; }
178
+ .lunora-welcome .shot .doc .accent { height: 5px; width: 26%; border-radius: 2px; background: var(--accent); }
179
+ .lunora-welcome .feature .info { margin-top: auto; padding-top: clamp(18px,2.4vh,28px); }
180
+ .lunora-welcome .feature .ic { width: 40px; height: 40px; margin-bottom: 15px; }
181
+ .lunora-welcome .feature .ic svg { width: 19px; height: 19px; }
182
+ .lunora-welcome .feature h2 { margin: 0 0 10px; font-size: 19px; font-weight: 600; letter-spacing: -0.015em; color: var(--t-display); }
183
+ .lunora-welcome .feature .row { display: flex; align-items: flex-end; gap: 16px; }
184
+ .lunora-welcome .feature p { margin: 0; color: var(--t-secondary); font-size: 14px; max-width: 50ch; }
185
+ .lunora-welcome .feature .row .arrow { margin-left: auto; }
186
+
187
+ /* right stack — smaller cards, spread to align bottoms with the feature */
188
+ .lunora-welcome .stack { display: flex; flex-direction: column; gap: 16px; height: 100%; }
189
+ .lunora-welcome .mini { flex: 1; padding: 15px 17px; display: flex; align-items: center; gap: 16px; min-height: 0; }
190
+ .lunora-welcome .mini .mc { flex: 1; }
191
+ .lunora-welcome .mini .ic { width: 32px; height: 32px; margin-bottom: 10px; }
192
+ .lunora-welcome .mini .ic svg { width: 16px; height: 16px; }
193
+ .lunora-welcome .mini h3 { margin: 0 0 5px; font-size: 16px; font-weight: 600; letter-spacing: -0.01em; color: var(--t-display); }
194
+ .lunora-welcome .mini p { margin: 0; color: var(--t-secondary); font-size: 12.5px; line-height: 1.45; }
195
+
196
+ .lunora-welcome .lw-foot { text-align: center; padding-top: 26px; font-family: var(--mono); font-size: 11px; letter-spacing: .1em; text-transform: uppercase; color: var(--t-faint); }
197
+
198
+ @media (prefers-reduced-motion: reduce) { .lunora-welcome * { transition: none !important; } }
199
+ `,Gt=`import { useEffect, useState } from "react";
200
+
201
+ type Theme = "dark" | "light";
202
+
203
+ export default function App() {
204
+ // Default to "dark" for a stable first paint, then reconcile to the OS
205
+ // preference; the toggle takes over after that.
206
+ const [theme, setTheme] = useState<Theme>("dark");
207
+
208
+ useEffect(() => {
209
+ if (typeof window !== "undefined" && window.matchMedia("(prefers-color-scheme: light)").matches) {
210
+ setTheme("light");
211
+ }
212
+ }, []);
213
+
214
+ const isLight = theme === "light";
313
215
 
314
- const STACK_FEATURE_OPTIONS = [
315
- { description: "Sign-up / sign-in (asks which provider)", label: "Authentication", value: "auth" },
316
- { description: "Cloudflare Email Workers + a dev mail catcher", label: "Transactional email", value: "email" },
317
- { description: "Typed R2 buckets + signed URLs (@lunora/storage)", label: "File storage", value: "storage" },
318
- { description: "Token-bucket / sliding-window limits (@lunora/ratelimit)", label: "Rate limiting", value: "ratelimit" },
319
- { description: "Scheduled jobs via Cron Triggers (@lunora/scheduler)", label: "Cron jobs", value: "crons" },
320
- { description: "Live presence / who's-online over hibernated WebSockets", label: "Presence", value: "presence" },
321
- { description: "Snapshot + restore your Durable Object data", label: "Backups", value: "backup" }
322
- ];
323
- const STACK_FEATURE_VALUES = STACK_FEATURE_OPTIONS.map((option) => option.value);
324
- const featureItem = (feature) => feature === "email" ? EMAIL_ITEM : feature;
325
- const parseFeatureList = (raw, warn) => {
326
- const features = [];
327
- for (const part of raw.split(",").map((entry) => entry.trim()).filter(Boolean)) {
328
- if (STACK_FEATURE_VALUES.includes(part)) {
329
- if (!features.includes(part)) {
330
- features.push(part);
331
- }
332
- } else {
333
- warn(`init: unknown --add feature "${part}" expected ${STACK_FEATURE_VALUES.join(" | ")}; skipping.`);
216
+ return (
217
+ <div className="lunora-welcome" data-theme={theme}>
218
+ <div className="lw-bg">
219
+ <div className="arc a1" />
220
+ <div className="arc a2" />
221
+ <div className="glow" />
222
+ </div>
223
+
224
+ <button className="lw-toggle" type="button" aria-label="Toggle color theme" onClick={() => setTheme(isLight ? "dark" : "light")}>
225
+ {isLight ? (
226
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8">
227
+ <path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z" />
228
+ </svg>
229
+ ) : (
230
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8">
231
+ <circle cx="12" cy="12" r="4" />
232
+ <path d="M12 2v2M12 20v2M4 12H2M22 12h-2M5 5l1.5 1.5M17.5 17.5 19 19M19 5l-1.5 1.5M6.5 17.5 5 19" />
233
+ </svg>
234
+ )}
235
+ <span>{isLight ? "Ivory" : "Night"}</span>
236
+ </button>
237
+
238
+ <div className="lw-wrap">
239
+ <div className="brand">
240
+ <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
241
+ <path d="${N}" fill="currentColor" fillRule="evenodd" />
242
+ </svg>
243
+ <span className="word">Lunora</span>
244
+ </div>
245
+
246
+ <div className="grid">
247
+ <a className="card feature" href="https://lunora.sh/docs">
248
+ <div className="shot" aria-hidden="true">
249
+ <div className="top">
250
+ <span className="wm">
251
+ <i /> Lunora
252
+ </span>
253
+ <span className="search" />
254
+ <span className="ver">v0.1</span>
255
+ </div>
256
+ <div className="body">
257
+ <div className="nav">
258
+ <i style={{ width: "80%" }} />
259
+ <i style={{ width: "60%" }} />
260
+ <i style={{ width: "72%" }} />
261
+ <i style={{ width: "50%" }} />
262
+ <i style={{ width: "66%" }} />
263
+ <i style={{ width: "44%" }} />
264
+ <i style={{ width: "58%" }} />
265
+ </div>
266
+ <div className="doc">
267
+ <span className="h" />
268
+ <i style={{ width: "92%" }} />
269
+ <i style={{ width: "88%" }} />
270
+ <span className="accent" />
271
+ <i style={{ width: "80%" }} />
272
+ <i style={{ width: "90%" }} />
273
+ <i style={{ width: "72%" }} />
274
+ <i style={{ width: "84%" }} />
275
+ <i style={{ width: "78%" }} />
276
+ </div>
277
+ </div>
278
+ </div>
279
+ <div className="info">
280
+ <span className="ic">
281
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7">
282
+ <path d="M4 5a2 2 0 0 1 2-2h9l5 5v11a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2z" />
283
+ <path d="M14 3v5h5" />
284
+ </svg>
285
+ </span>
286
+ <h2>Documentation</h2>
287
+ <div className="row">
288
+ <p>
289
+ Schemas, queries, live subscriptions, sharding, and edge deploy — start to finish. New here or coming from Convex or tRPC,
290
+ you'll have a live app fast.
291
+ </p>
292
+ <span className="arrow">
293
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
294
+ <path d="M5 12h14M13 6l6 6-6 6" />
295
+ </svg>
296
+ </span>
297
+ </div>
298
+ </div>
299
+ </a>
300
+
301
+ <div className="stack">
302
+ <a className="card mini" href="https://lunora.sh/blog">
303
+ <div className="mc">
304
+ <span className="ic">
305
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7">
306
+ <path d="M5 4h11a1 1 0 0 1 1 1v14a1 1 0 0 1-1 1H6a2 2 0 0 1-2-2V5a1 1 0 0 1 1-1zM8 8h7M8 12h7M8 16h4" />
307
+ </svg>
308
+ </span>
309
+ <h3>Blog</h3>
310
+ <p>Product updates, deep dives, and what's new in Lunora.</p>
311
+ </div>
312
+ <span className="arrow">
313
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
314
+ <path d="M5 12h14M13 6l6 6-6 6" />
315
+ </svg>
316
+ </span>
317
+ </a>
318
+ <a className="card mini" href="/_lunora">
319
+ <div className="mc">
320
+ <span className="ic">
321
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7">
322
+ <rect x="3" y="3" width="18" height="18" rx="1" />
323
+ <path d="M3 9h18M9 21V9" />
324
+ </svg>
325
+ </span>
326
+ <h3>Lunora Studio</h3>
327
+ <p>Local admin for schema, data, logs, and advisors.</p>
328
+ </div>
329
+ <span className="arrow">
330
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
331
+ <path d="M5 12h14M13 6l6 6-6 6" />
332
+ </svg>
333
+ </span>
334
+ </a>
335
+ <a className="card mini" href="https://lunora.sh/packages">
336
+ <div className="mc">
337
+ <span className="ic">
338
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7">
339
+ <path d="M12 2 3 7v10l9 5 9-5V7z" />
340
+ <path d="M3 7l9 5 9-5M12 12v10" />
341
+ </svg>
342
+ </span>
343
+ <h3>Cloudflare ecosystem</h3>
344
+ <p>Auth, mail, storage, AI, payments — one deploy.</p>
345
+ </div>
346
+ <span className="arrow">
347
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
348
+ <path d="M5 12h14M13 6l6 6-6 6" />
349
+ </svg>
350
+ </span>
351
+ </a>
352
+ </div>
353
+ </div>
354
+
355
+ <div className="lw-foot">Running on Lunora · Vite + React</div>
356
+ </div>
357
+ </div>
358
+ );
359
+ }
360
+ `,Jt=`<script setup lang="ts">
361
+ import { onMounted, ref } from "vue";
362
+
363
+ // Default to "dark" for a stable first paint, then reconcile to the OS
364
+ // preference; the toggle takes over after that.
365
+ const theme = ref<"dark" | "light">("dark");
366
+
367
+ onMounted(() => {
368
+ if (window.matchMedia("(prefers-color-scheme: light)").matches) {
369
+ theme.value = "light";
334
370
  }
335
- }
336
- return features;
337
- };
338
- const collectAuthFeature = async (deps) => {
339
- const provider = await promptAuthProvider(deps.select);
340
- const databaseName = await promptDatabaseName(deps.text, deps.projectName);
341
- return { label: "auth", names: [provider], transformManifest: (manifest) => withAuthDatabaseName(manifest, databaseName) };
342
- };
343
- const collectEmailFeature = async (deps) => {
344
- const answer = await deps.text(MAIL_DESTINATION_PROMPT, { placeholder: "you@yourdomain.com" });
345
- const destination = resolveTypedDestination(answer, (message) => {
346
- deps.logger.warn(message);
347
- });
348
- return {
349
- label: "email",
350
- names: [EMAIL_ITEM],
351
- transformManifest: destination === void 0 ? void 0 : (manifest) => withMailDestination(manifest, destination)
352
- };
353
- };
354
- const collectStorageFeature = async (deps) => {
355
- const bucketName = await promptBucketName(deps.text, deps.projectName);
356
- return { label: "storage", names: ["storage"], transformManifest: (manifest) => withStorageBucketName(manifest, bucketName) };
357
- };
358
- const FEATURE_COLLECTORS = {
359
- auth: collectAuthFeature,
360
- email: collectEmailFeature,
361
- storage: collectStorageFeature
371
+ });
372
+
373
+ const toggle = (): void => {
374
+ theme.value = theme.value === "light" ? "dark" : "light";
362
375
  };
363
- const offerRegistryExtras = async (deps) => {
364
- if (deps.preselected !== void 0 && deps.preselected.length > 0) {
365
- await deps.applyAll(
366
- deps.preselected.map((feature) => {
367
- return { label: feature, names: [featureItem(feature)] };
368
- })
376
+ <\/script>
377
+
378
+ <template>
379
+ <div class="lunora-welcome" :data-theme="theme">
380
+ <div class="lw-bg">
381
+ <div class="arc a1" />
382
+ <div class="arc a2" />
383
+ <div class="glow" />
384
+ </div>
385
+
386
+ <button class="lw-toggle" type="button" aria-label="Toggle color theme" @click="toggle">
387
+ <svg v-if="theme === 'light'" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8">
388
+ <path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z" />
389
+ </svg>
390
+ <svg v-else viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8">
391
+ <circle cx="12" cy="12" r="4" />
392
+ <path d="M12 2v2M12 20v2M4 12H2M22 12h-2M5 5l1.5 1.5M17.5 17.5 19 19M19 5l-1.5 1.5M6.5 17.5 5 19" />
393
+ </svg>
394
+ <span>{{ theme === "light" ? "Ivory" : "Night" }}</span>
395
+ </button>
396
+
397
+ <div class="lw-wrap">
398
+ <div class="brand">
399
+ <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
400
+ <path d="${N}" fill="currentColor" fill-rule="evenodd" />
401
+ </svg>
402
+ <span class="word">Lunora</span>
403
+ </div>
404
+
405
+ <div class="grid">
406
+ <a class="card feature" href="https://lunora.sh/docs">
407
+ <div class="shot" aria-hidden="true">
408
+ <div class="top">
409
+ <span class="wm"><i /> Lunora</span>
410
+ <span class="search" />
411
+ <span class="ver">v0.1</span>
412
+ </div>
413
+ <div class="body">
414
+ <div class="nav">
415
+ <i style="width: 80%" />
416
+ <i style="width: 60%" />
417
+ <i style="width: 72%" />
418
+ <i style="width: 50%" />
419
+ <i style="width: 66%" />
420
+ <i style="width: 44%" />
421
+ <i style="width: 58%" />
422
+ </div>
423
+ <div class="doc">
424
+ <span class="h" />
425
+ <i style="width: 92%" />
426
+ <i style="width: 88%" />
427
+ <span class="accent" />
428
+ <i style="width: 80%" />
429
+ <i style="width: 90%" />
430
+ <i style="width: 72%" />
431
+ <i style="width: 84%" />
432
+ <i style="width: 78%" />
433
+ </div>
434
+ </div>
435
+ </div>
436
+ <div class="info">
437
+ <span class="ic">
438
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7">
439
+ <path d="M4 5a2 2 0 0 1 2-2h9l5 5v11a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2z" />
440
+ <path d="M14 3v5h5" />
441
+ </svg>
442
+ </span>
443
+ <h2>Documentation</h2>
444
+ <div class="row">
445
+ <p>
446
+ Schemas, queries, live subscriptions, sharding, and edge deploy — start to finish. New here or coming from Convex or tRPC,
447
+ you'll have a live app fast.
448
+ </p>
449
+ <span class="arrow">
450
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
451
+ <path d="M5 12h14M13 6l6 6-6 6" />
452
+ </svg>
453
+ </span>
454
+ </div>
455
+ </div>
456
+ </a>
457
+
458
+ <div class="stack">
459
+ <a class="card mini" href="https://lunora.sh/blog">
460
+ <div class="mc">
461
+ <span class="ic">
462
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7">
463
+ <path d="M5 4h11a1 1 0 0 1 1 1v14a1 1 0 0 1-1 1H6a2 2 0 0 1-2-2V5a1 1 0 0 1 1-1zM8 8h7M8 12h7M8 16h4" />
464
+ </svg>
465
+ </span>
466
+ <h3>Blog</h3>
467
+ <p>Product updates, deep dives, and what's new in Lunora.</p>
468
+ </div>
469
+ <span class="arrow">
470
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
471
+ <path d="M5 12h14M13 6l6 6-6 6" />
472
+ </svg>
473
+ </span>
474
+ </a>
475
+ <a class="card mini" href="/_lunora">
476
+ <div class="mc">
477
+ <span class="ic">
478
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7">
479
+ <rect x="3" y="3" width="18" height="18" rx="1" />
480
+ <path d="M3 9h18M9 21V9" />
481
+ </svg>
482
+ </span>
483
+ <h3>Lunora Studio</h3>
484
+ <p>Local admin for schema, data, logs, and advisors.</p>
485
+ </div>
486
+ <span class="arrow">
487
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
488
+ <path d="M5 12h14M13 6l6 6-6 6" />
489
+ </svg>
490
+ </span>
491
+ </a>
492
+ <a class="card mini" href="https://lunora.sh/packages">
493
+ <div class="mc">
494
+ <span class="ic">
495
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7">
496
+ <path d="M12 2 3 7v10l9 5 9-5V7z" />
497
+ <path d="M3 7l9 5 9-5M12 12v10" />
498
+ </svg>
499
+ </span>
500
+ <h3>Cloudflare ecosystem</h3>
501
+ <p>Auth, mail, storage, AI, payments — one deploy.</p>
502
+ </div>
503
+ <span class="arrow">
504
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
505
+ <path d="M5 12h14M13 6l6 6-6 6" />
506
+ </svg>
507
+ </span>
508
+ </a>
509
+ </div>
510
+ </div>
511
+
512
+ <div class="lw-foot">Running on Lunora · Vite + Vue</div>
513
+ </div>
514
+ </div>
515
+ </template>
516
+ `,Yt=`import { createSignal, onMount } from "solid-js";
517
+
518
+ export default function App() {
519
+ // Default to "dark" for a stable first paint, then reconcile to the OS
520
+ // preference; the toggle takes over after that.
521
+ const [theme, setTheme] = createSignal<"dark" | "light">("dark");
522
+
523
+ onMount(() => {
524
+ if (window.matchMedia("(prefers-color-scheme: light)").matches) {
525
+ setTheme("light");
526
+ }
527
+ });
528
+
529
+ const isLight = () => theme() === "light";
530
+
531
+ return (
532
+ <div class="lunora-welcome" data-theme={theme()}>
533
+ <div class="lw-bg">
534
+ <div class="arc a1" />
535
+ <div class="arc a2" />
536
+ <div class="glow" />
537
+ </div>
538
+
539
+ <button class="lw-toggle" type="button" aria-label="Toggle color theme" onClick={() => setTheme(isLight() ? "dark" : "light")}>
540
+ {isLight() ? (
541
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8">
542
+ <path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z" />
543
+ </svg>
544
+ ) : (
545
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8">
546
+ <circle cx="12" cy="12" r="4" />
547
+ <path d="M12 2v2M12 20v2M4 12H2M22 12h-2M5 5l1.5 1.5M17.5 17.5 19 19M19 5l-1.5 1.5M6.5 17.5 5 19" />
548
+ </svg>
549
+ )}
550
+ <span>{isLight() ? "Ivory" : "Night"}</span>
551
+ </button>
552
+
553
+ <div class="lw-wrap">
554
+ <div class="brand">
555
+ <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
556
+ <path d="${N}" fill="currentColor" fill-rule="evenodd" />
557
+ </svg>
558
+ <span class="word">Lunora</span>
559
+ </div>
560
+
561
+ <div class="grid">
562
+ <a class="card feature" href="https://lunora.sh/docs">
563
+ <div class="shot" aria-hidden="true">
564
+ <div class="top">
565
+ <span class="wm">
566
+ <i /> Lunora
567
+ </span>
568
+ <span class="search" />
569
+ <span class="ver">v0.1</span>
570
+ </div>
571
+ <div class="body">
572
+ <div class="nav">
573
+ <i style={{ width: "80%" }} />
574
+ <i style={{ width: "60%" }} />
575
+ <i style={{ width: "72%" }} />
576
+ <i style={{ width: "50%" }} />
577
+ <i style={{ width: "66%" }} />
578
+ <i style={{ width: "44%" }} />
579
+ <i style={{ width: "58%" }} />
580
+ </div>
581
+ <div class="doc">
582
+ <span class="h" />
583
+ <i style={{ width: "92%" }} />
584
+ <i style={{ width: "88%" }} />
585
+ <span class="accent" />
586
+ <i style={{ width: "80%" }} />
587
+ <i style={{ width: "90%" }} />
588
+ <i style={{ width: "72%" }} />
589
+ <i style={{ width: "84%" }} />
590
+ <i style={{ width: "78%" }} />
591
+ </div>
592
+ </div>
593
+ </div>
594
+ <div class="info">
595
+ <span class="ic">
596
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7">
597
+ <path d="M4 5a2 2 0 0 1 2-2h9l5 5v11a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2z" />
598
+ <path d="M14 3v5h5" />
599
+ </svg>
600
+ </span>
601
+ <h2>Documentation</h2>
602
+ <div class="row">
603
+ <p>
604
+ Schemas, queries, live subscriptions, sharding, and edge deploy — start to finish. New here or coming from Convex or tRPC,
605
+ you'll have a live app fast.
606
+ </p>
607
+ <span class="arrow">
608
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
609
+ <path d="M5 12h14M13 6l6 6-6 6" />
610
+ </svg>
611
+ </span>
612
+ </div>
613
+ </div>
614
+ </a>
615
+
616
+ <div class="stack">
617
+ <a class="card mini" href="https://lunora.sh/blog">
618
+ <div class="mc">
619
+ <span class="ic">
620
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7">
621
+ <path d="M5 4h11a1 1 0 0 1 1 1v14a1 1 0 0 1-1 1H6a2 2 0 0 1-2-2V5a1 1 0 0 1 1-1zM8 8h7M8 12h7M8 16h4" />
622
+ </svg>
623
+ </span>
624
+ <h3>Blog</h3>
625
+ <p>Product updates, deep dives, and what's new in Lunora.</p>
626
+ </div>
627
+ <span class="arrow">
628
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
629
+ <path d="M5 12h14M13 6l6 6-6 6" />
630
+ </svg>
631
+ </span>
632
+ </a>
633
+ <a class="card mini" href="/_lunora">
634
+ <div class="mc">
635
+ <span class="ic">
636
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7">
637
+ <rect x="3" y="3" width="18" height="18" rx="1" />
638
+ <path d="M3 9h18M9 21V9" />
639
+ </svg>
640
+ </span>
641
+ <h3>Lunora Studio</h3>
642
+ <p>Local admin for schema, data, logs, and advisors.</p>
643
+ </div>
644
+ <span class="arrow">
645
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
646
+ <path d="M5 12h14M13 6l6 6-6 6" />
647
+ </svg>
648
+ </span>
649
+ </a>
650
+ <a class="card mini" href="https://lunora.sh/packages">
651
+ <div class="mc">
652
+ <span class="ic">
653
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7">
654
+ <path d="M12 2 3 7v10l9 5 9-5V7z" />
655
+ <path d="M3 7l9 5 9-5M12 12v10" />
656
+ </svg>
657
+ </span>
658
+ <h3>Cloudflare ecosystem</h3>
659
+ <p>Auth, mail, storage, AI, payments — one deploy.</p>
660
+ </div>
661
+ <span class="arrow">
662
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
663
+ <path d="M5 12h14M13 6l6 6-6 6" />
664
+ </svg>
665
+ </span>
666
+ </a>
667
+ </div>
668
+ </div>
669
+
670
+ <div class="lw-foot">Running on Lunora · Vite + Solid</div>
671
+ </div>
672
+ </div>
369
673
  );
370
- return;
371
- }
372
- if (!deps.interactive) {
373
- deps.logger.info("tip: add features later with `lunora add <auth|email|storage|ratelimit|crons|presence|backup>`.");
374
- return;
375
- }
376
- const picked = await deps.multiSelect("Which features do you want to add?", STACK_FEATURE_OPTIONS, { defaults: [] });
377
- if (picked.length === 0) {
378
- return;
379
- }
380
- const plans = [];
381
- for (const feature of picked) {
382
- const collect = FEATURE_COLLECTORS[feature];
383
- plans.push(collect ? await collect(deps) : { label: feature, names: [feature] });
384
- }
385
- await deps.applyAll(plans);
674
+ }
675
+ `,Xt=`<script lang="ts">
676
+ import { onMount } from "svelte";
677
+
678
+ // Default to "dark" for a stable first paint, then reconcile to the OS
679
+ // preference; the toggle takes over after that.
680
+ let theme = $state<"dark" | "light">("dark");
681
+ const isLight = $derived(theme === "light");
682
+
683
+ onMount(() => {
684
+ if (window.matchMedia("(prefers-color-scheme: light)").matches) {
685
+ theme = "light";
686
+ }
687
+ });
688
+
689
+ const toggle = (): void => {
690
+ theme = theme === "light" ? "dark" : "light";
691
+ };
692
+ <\/script>
693
+
694
+ <div class="lunora-welcome" data-theme={theme}>
695
+ <div class="lw-bg">
696
+ <div class="arc a1"></div>
697
+ <div class="arc a2"></div>
698
+ <div class="glow"></div>
699
+ </div>
700
+
701
+ <button class="lw-toggle" type="button" aria-label="Toggle color theme" onclick={toggle}>
702
+ {#if isLight}
703
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8">
704
+ <path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z" />
705
+ </svg>
706
+ {:else}
707
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8">
708
+ <circle cx="12" cy="12" r="4" />
709
+ <path d="M12 2v2M12 20v2M4 12H2M22 12h-2M5 5l1.5 1.5M17.5 17.5 19 19M19 5l-1.5 1.5M6.5 17.5 5 19" />
710
+ </svg>
711
+ {/if}
712
+ <span>{isLight ? "Ivory" : "Night"}</span>
713
+ </button>
714
+
715
+ <div class="lw-wrap">
716
+ <div class="brand">
717
+ <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
718
+ <path d="${N}" fill="currentColor" fill-rule="evenodd" />
719
+ </svg>
720
+ <span class="word">Lunora</span>
721
+ </div>
722
+
723
+ <div class="grid">
724
+ <a class="card feature" href="https://lunora.sh/docs">
725
+ <div class="shot" aria-hidden="true">
726
+ <div class="top">
727
+ <span class="wm"><i></i> Lunora</span>
728
+ <span class="search"></span>
729
+ <span class="ver">v0.1</span>
730
+ </div>
731
+ <div class="body">
732
+ <div class="nav">
733
+ <i style="width: 80%"></i>
734
+ <i style="width: 60%"></i>
735
+ <i style="width: 72%"></i>
736
+ <i style="width: 50%"></i>
737
+ <i style="width: 66%"></i>
738
+ <i style="width: 44%"></i>
739
+ <i style="width: 58%"></i>
740
+ </div>
741
+ <div class="doc">
742
+ <span class="h"></span>
743
+ <i style="width: 92%"></i>
744
+ <i style="width: 88%"></i>
745
+ <span class="accent"></span>
746
+ <i style="width: 80%"></i>
747
+ <i style="width: 90%"></i>
748
+ <i style="width: 72%"></i>
749
+ <i style="width: 84%"></i>
750
+ <i style="width: 78%"></i>
751
+ </div>
752
+ </div>
753
+ </div>
754
+ <div class="info">
755
+ <span class="ic">
756
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7">
757
+ <path d="M4 5a2 2 0 0 1 2-2h9l5 5v11a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2z" />
758
+ <path d="M14 3v5h5" />
759
+ </svg>
760
+ </span>
761
+ <h2>Documentation</h2>
762
+ <div class="row">
763
+ <p>
764
+ Schemas, queries, live subscriptions, sharding, and edge deploy — start to finish. New here or coming from Convex or tRPC,
765
+ you'll have a live app fast.
766
+ </p>
767
+ <span class="arrow">
768
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
769
+ <path d="M5 12h14M13 6l6 6-6 6" />
770
+ </svg>
771
+ </span>
772
+ </div>
773
+ </div>
774
+ </a>
775
+
776
+ <div class="stack">
777
+ <a class="card mini" href="https://lunora.sh/blog">
778
+ <div class="mc">
779
+ <span class="ic">
780
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7">
781
+ <path d="M5 4h11a1 1 0 0 1 1 1v14a1 1 0 0 1-1 1H6a2 2 0 0 1-2-2V5a1 1 0 0 1 1-1zM8 8h7M8 12h7M8 16h4" />
782
+ </svg>
783
+ </span>
784
+ <h3>Blog</h3>
785
+ <p>Product updates, deep dives, and what's new in Lunora.</p>
786
+ </div>
787
+ <span class="arrow">
788
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
789
+ <path d="M5 12h14M13 6l6 6-6 6" />
790
+ </svg>
791
+ </span>
792
+ </a>
793
+ <a class="card mini" href="/_lunora">
794
+ <div class="mc">
795
+ <span class="ic">
796
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7">
797
+ <rect x="3" y="3" width="18" height="18" rx="1" />
798
+ <path d="M3 9h18M9 21V9" />
799
+ </svg>
800
+ </span>
801
+ <h3>Lunora Studio</h3>
802
+ <p>Local admin for schema, data, logs, and advisors.</p>
803
+ </div>
804
+ <span class="arrow">
805
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
806
+ <path d="M5 12h14M13 6l6 6-6 6" />
807
+ </svg>
808
+ </span>
809
+ </a>
810
+ <a class="card mini" href="https://lunora.sh/packages">
811
+ <div class="mc">
812
+ <span class="ic">
813
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7">
814
+ <path d="M12 2 3 7v10l9 5 9-5V7z" />
815
+ <path d="M3 7l9 5 9-5M12 12v10" />
816
+ </svg>
817
+ </span>
818
+ <h3>Cloudflare ecosystem</h3>
819
+ <p>Auth, mail, storage, AI, payments — one deploy.</p>
820
+ </div>
821
+ <span class="arrow">
822
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
823
+ <path d="M5 12h14M13 6l6 6-6 6" />
824
+ </svg>
825
+ </span>
826
+ </a>
827
+ </div>
828
+ </div>
829
+
830
+ <div class="lw-foot">Running on Lunora · Vite + Svelte</div>
831
+ </div>
832
+ </div>
833
+ `,Qt=`import "./style.css";
834
+
835
+ import { LunoraClient } from "lunorash/client";
836
+
837
+ import { api } from "#lunora/_generated/api.js";
838
+
839
+ // \`@lunora/vite\` runs the Worker on the same origin as Vite, so default to
840
+ // \`location.origin\`. Point \`VITE_LUNORA_URL\` at a deployed Worker to develop
841
+ // the client against production data.
842
+ const url = (import.meta.env.VITE_LUNORA_URL as string | undefined) ?? globalThis.location.origin;
843
+ const client = new LunoraClient({ url });
844
+
845
+ const MOON_ICON = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z" /></svg>';
846
+ const SUN_ICON =
847
+ '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><circle cx="12" cy="12" r="4" /><path d="M12 2v2M12 20v2M4 12H2M22 12h-2M5 5l1.5 1.5M17.5 17.5 19 19M19 5l-1.5 1.5M6.5 17.5 5 19" /></svg>';
848
+
849
+ const welcomeHtml = \`
850
+ <div class="lw-bg">
851
+ <div class="arc a1"></div>
852
+ <div class="arc a2"></div>
853
+ <div class="glow"></div>
854
+ </div>
855
+
856
+ <button class="lw-toggle" type="button" aria-label="Toggle color theme"></button>
857
+
858
+ <div class="lw-wrap">
859
+ <div class="brand">
860
+ <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
861
+ <path d="${N}" fill="currentColor" fill-rule="evenodd" />
862
+ </svg>
863
+ <span class="word">Lunora</span>
864
+ </div>
865
+
866
+ <div class="grid">
867
+ <a class="card feature" href="https://lunora.sh/docs">
868
+ <div class="shot" aria-hidden="true">
869
+ <div class="top">
870
+ <span class="wm"><i></i> Lunora</span>
871
+ <span class="search"></span>
872
+ <span class="ver">v0.1</span>
873
+ </div>
874
+ <div class="body">
875
+ <div class="nav">
876
+ <i style="width: 80%"></i>
877
+ <i style="width: 60%"></i>
878
+ <i style="width: 72%"></i>
879
+ <i style="width: 50%"></i>
880
+ <i style="width: 66%"></i>
881
+ <i style="width: 44%"></i>
882
+ <i style="width: 58%"></i>
883
+ </div>
884
+ <div class="doc">
885
+ <span class="h"></span>
886
+ <i style="width: 92%"></i>
887
+ <i style="width: 88%"></i>
888
+ <span class="accent"></span>
889
+ <i style="width: 80%"></i>
890
+ <i style="width: 90%"></i>
891
+ <i style="width: 72%"></i>
892
+ <i style="width: 84%"></i>
893
+ <i style="width: 78%"></i>
894
+ </div>
895
+ </div>
896
+ </div>
897
+ <div class="info">
898
+ <span class="ic">
899
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7">
900
+ <path d="M4 5a2 2 0 0 1 2-2h9l5 5v11a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2z" />
901
+ <path d="M14 3v5h5" />
902
+ </svg>
903
+ </span>
904
+ <h2>Documentation</h2>
905
+ <div class="row">
906
+ <p>
907
+ Schemas, queries, live subscriptions, sharding, and edge deploy — start to finish. New here or coming from Convex or tRPC,
908
+ you'll have a live app fast.
909
+ </p>
910
+ <span class="arrow">
911
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
912
+ <path d="M5 12h14M13 6l6 6-6 6" />
913
+ </svg>
914
+ </span>
915
+ </div>
916
+ </div>
917
+ </a>
918
+
919
+ <div class="stack">
920
+ <a class="card mini" href="https://lunora.sh/blog">
921
+ <div class="mc">
922
+ <span class="ic">
923
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7">
924
+ <path d="M5 4h11a1 1 0 0 1 1 1v14a1 1 0 0 1-1 1H6a2 2 0 0 1-2-2V5a1 1 0 0 1 1-1zM8 8h7M8 12h7M8 16h4" />
925
+ </svg>
926
+ </span>
927
+ <h3>Blog</h3>
928
+ <p>Product updates, deep dives, and what's new in Lunora.</p>
929
+ </div>
930
+ <span class="arrow">
931
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
932
+ <path d="M5 12h14M13 6l6 6-6 6" />
933
+ </svg>
934
+ </span>
935
+ </a>
936
+ <a class="card mini" href="/_lunora">
937
+ <div class="mc">
938
+ <span class="ic">
939
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7">
940
+ <rect x="3" y="3" width="18" height="18" rx="1" />
941
+ <path d="M3 9h18M9 21V9" />
942
+ </svg>
943
+ </span>
944
+ <h3>Lunora Studio</h3>
945
+ <p>Local admin for schema, data, logs, and advisors.</p>
946
+ </div>
947
+ <span class="arrow">
948
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
949
+ <path d="M5 12h14M13 6l6 6-6 6" />
950
+ </svg>
951
+ </span>
952
+ </a>
953
+ <a class="card mini" href="https://lunora.sh/packages">
954
+ <div class="mc">
955
+ <span class="ic">
956
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7">
957
+ <path d="M12 2 3 7v10l9 5 9-5V7z" />
958
+ <path d="M3 7l9 5 9-5M12 12v10" />
959
+ </svg>
960
+ </span>
961
+ <h3>Cloudflare ecosystem</h3>
962
+ <p>Auth, mail, storage, AI, payments — one deploy.</p>
963
+ </div>
964
+ <span class="arrow">
965
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
966
+ <path d="M5 12h14M13 6l6 6-6 6" />
967
+ </svg>
968
+ </span>
969
+ </a>
970
+ </div>
971
+ </div>
972
+
973
+ <div class="lw-foot">Running on Lunora · Vite + Vanilla · <span id="lw-count">0</span> messages</div>
974
+ </div>
975
+ \`;
976
+
977
+ const root = document.querySelector<HTMLDivElement>("#app")!;
978
+ root.classList.add("lunora-welcome");
979
+ root.innerHTML = welcomeHtml;
980
+
981
+ // Theme toggle: flip the root's data-theme + swap the button's icon/label.
982
+ const toggleButton = root.querySelector<HTMLButtonElement>(".lw-toggle")!;
983
+
984
+ const paintToggle = (theme: "dark" | "light"): void => {
985
+ root.dataset.theme = theme;
986
+ toggleButton.innerHTML = \`\${theme === "light" ? MOON_ICON : SUN_ICON}<span>\${theme === "light" ? "Ivory" : "Night"}</span>\`;
386
987
  };
387
988
 
388
- const READ_URL = `const url = (import.meta.env.VITE_LUNORA_URL as string | undefined) ?? globalThis.location.origin;`;
389
- const REACT_MAIN = `import "./index.css";
989
+ paintToggle(window.matchMedia("(prefers-color-scheme: light)").matches ? "light" : "dark");
990
+ toggleButton.addEventListener("click", () => {
991
+ paintToggle(root.dataset.theme === "light" ? "dark" : "light");
992
+ });
993
+
994
+ // Live demo: the message count of a demo channel re-renders on every delta.
995
+ const count = document.querySelector<HTMLSpanElement>("#lw-count")!;
996
+
997
+ client.onUpdate(api.messages.list, { channelId: "channel:demo" }, (result) => {
998
+ count.textContent = String(result.messages.length);
999
+ });
1000
+ `,O="const url = (import.meta.env.VITE_LUNORA_URL as string | undefined) ?? globalThis.location.origin;",Zt=`import "./index.css";
390
1001
 
391
1002
  import { LunoraProvider } from "@lunora/react";
392
1003
  import { LunoraClient } from "lunorash/client";
@@ -398,7 +1009,7 @@ import App from "./App.tsx";
398
1009
  // \`@lunora/vite\` runs the Worker on the same origin as Vite, so default to
399
1010
  // \`location.origin\`. Point \`VITE_LUNORA_URL\` at a deployed Worker to develop
400
1011
  // the client against production data.
401
- ${READ_URL}
1012
+ ${O}
402
1013
  const client = new LunoraClient({ url });
403
1014
 
404
1015
  const root = document.getElementById("root");
@@ -414,8 +1025,7 @@ createRoot(root).render(
414
1025
  </LunoraProvider>
415
1026
  </StrictMode>,
416
1027
  );
417
- `;
418
- const VUE_MAIN = `import "./style.css";
1028
+ `,ea=`import "./style.css";
419
1029
 
420
1030
  import { createLunora } from "@lunora/vue";
421
1031
  import { LunoraClient } from "lunorash/client";
@@ -424,43 +1034,40 @@ import { createApp } from "vue";
424
1034
  import App from "./App.vue";
425
1035
 
426
1036
  // Provide one LunoraClient at the app root via the Vue plugin form.
427
- ${READ_URL}
1037
+ ${O}
428
1038
  createApp(App).use(createLunora(new LunoraClient({ url }))).mount("#app");
429
- `;
430
- const SOLID_INDEX = `import "./index.css";
1039
+ `,ta=`import "./index.css";
431
1040
 
432
- import { LunoraContext } from "@lunora/solid";
1041
+ import { LunoraProvider } from "@lunora/solid";
433
1042
  import { LunoraClient } from "lunorash/client";
434
1043
  import { render } from "solid-js/web";
435
1044
 
436
1045
  import App from "./App";
437
1046
 
438
- ${READ_URL}
1047
+ ${O}
439
1048
  const client = new LunoraClient({ url });
440
1049
  const root = document.getElementById("root");
441
1050
 
442
1051
  render(
443
1052
  () => (
444
- <LunoraContext.Provider value={client}>
1053
+ <LunoraProvider client={client}>
445
1054
  <App />
446
- </LunoraContext.Provider>
1055
+ </LunoraProvider>
447
1056
  ),
448
1057
  root!,
449
1058
  );
450
- `;
451
- const SVELTE_ROOT = `<script lang="ts">
1059
+ `,aa=`<script lang="ts">
452
1060
  import { setLunoraClient } from "@lunora/svelte";
453
1061
  import { LunoraClient } from "lunorash/client";
454
1062
 
455
1063
  import App from "./App.svelte";
456
1064
 
457
- ${READ_URL}
1065
+ ${O}
458
1066
  setLunoraClient(new LunoraClient({ url }));
459
1067
  <\/script>
460
1068
 
461
1069
  <App />
462
- `;
463
- const SVELTE_MAIN = `import "./app.css";
1070
+ `,ra=`import "./app.css";
464
1071
 
465
1072
  import { mount } from "svelte";
466
1073
 
@@ -470,52 +1077,48 @@ import Root from "./Root.svelte";
470
1077
  const app = mount(Root, { target: document.getElementById("app")! });
471
1078
 
472
1079
  export default app;
473
- `;
474
- const VANILLA_MAIN = `import "./style.css";
1080
+ `,T={react:{adapter:"@lunora/react",createViteTemplate:"react-ts",files:[{contents:Zt,path:"src/main.tsx"},{contents:Gt,path:"src/App.tsx"},{contents:L,path:"src/index.css"}],label:"React"},solid:{adapter:"@lunora/solid",createViteTemplate:"solid-ts",files:[{contents:ta,path:"src/index.tsx"},{contents:Yt,path:"src/App.tsx"},{contents:L,path:"src/index.css"}],label:"Solid"},svelte:{adapter:"@lunora/svelte",createViteTemplate:"svelte-ts",files:[{contents:aa,path:"src/Root.svelte"},{contents:ra,path:"src/main.ts"},{contents:Xt,path:"src/App.svelte"},{contents:L,path:"src/app.css"}],label:"Svelte"},vanilla:{adapter:"lunorash/client",createViteTemplate:"vanilla-ts",files:[{contents:Qt,path:"src/main.ts"},{contents:L,path:"src/style.css"}],label:"Vanilla"},vue:{adapter:"@lunora/vue",createViteTemplate:"vue-ts",files:[{contents:ea,path:"src/main.ts"},{contents:Jt,path:"src/App.vue"},{contents:L,path:"src/style.css"}],label:"Vue"}},z=e=>Object.hasOwn(T,e),oa=`import type { Middleware } from "lunorash/server";
1081
+ import { defineSchemaExtension, defineTable, definePlugin, v } from "lunorash/server";
1082
+ import { createDbStore, RateLimiter } from "lunorash/ratelimit";
1083
+ import type { RateLimitConfigMap } from "lunorash/ratelimit";
475
1084
 
476
- import { LunoraClient } from "lunorash/client";
477
-
478
- import { api } from "../lunora/_generated/api";
479
-
480
- // Vanilla starter: no framework provider — talk to Lunora through the client
481
- // directly. \`@lunora/vite\` runs the Worker on the same origin as Vite.
482
- ${READ_URL}
483
- const client = new LunoraClient({ url });
1085
+ export const limits = {
1086
+ default: { kind: "token bucket", period: 60_000, rate: 10 },
1087
+ } as const satisfies RateLimitConfigMap;
484
1088
 
485
- const root = document.querySelector<HTMLDivElement>("#app")!;
486
-
487
- const heading = document.createElement("h1");
488
- heading.textContent = "Vite + Lunora";
1089
+ export type LimitName = keyof typeof limits;
489
1090
 
490
- const output = document.createElement("pre");
491
- root.replaceChildren(heading, output);
492
-
493
- const render = (messages: unknown): void => {
494
- // textContent (not innerHTML) — never inject server data as markup.
495
- output.textContent = JSON.stringify(messages, null, 2);
496
- };
1091
+ export const makeRateLimiter = (ctx: { db: unknown }): RateLimiter<LimitName> =>
1092
+ new RateLimiter<LimitName>({
1093
+ config: limits,
1094
+ store: createDbStore({ db: ctx.db as never, table: "ratelimit_buckets" }),
1095
+ });
497
1096
 
498
- // Live subscription: the list re-renders on every server delta.
499
- client.onUpdate(api.messages.list, { channelId: "channel:demo" }, render);
500
- `;
501
- const ADAPTERS = {
502
- react: { adapter: "@lunora/react", createViteTemplate: "react-ts", files: [{ contents: REACT_MAIN, path: "src/main.tsx" }], label: "React" },
503
- solid: { adapter: "@lunora/solid", createViteTemplate: "solid", files: [{ contents: SOLID_INDEX, path: "src/index.tsx" }], label: "Solid" },
504
- svelte: {
505
- adapter: "@lunora/svelte",
506
- createViteTemplate: "svelte-ts",
507
- files: [
508
- { contents: SVELTE_ROOT, path: "src/Root.svelte" },
509
- { contents: SVELTE_MAIN, path: "src/main.ts" }
510
- ],
511
- label: "Svelte"
512
- },
513
- vanilla: { adapter: "lunorash/client", createViteTemplate: "vanilla-ts", files: [{ contents: VANILLA_MAIN, path: "src/main.ts" }], label: "Vanilla" },
514
- vue: { adapter: "@lunora/vue", createViteTemplate: "vue-ts", files: [{ contents: VUE_MAIN, path: "src/main.ts" }], label: "Vue" }
515
- };
516
- const isOverlayFramework = (value) => Object.hasOwn(ADAPTERS, value);
1097
+ const middleware: Middleware<{ api?: Record<string, unknown>; db: unknown }, { api: Record<string, unknown>; db: unknown }> = ({ ctx, next }) =>
1098
+ next({
1099
+ ctx: {
1100
+ ...ctx,
1101
+ api: { ...ctx.api, ratelimit: makeRateLimiter(ctx) },
1102
+ },
1103
+ });
517
1104
 
518
- const LUNORA_SCHEMA = `import { defineSchema, defineTable, v } from "lunorash/server";
1105
+ export const ratelimit = definePlugin("ratelimit", {
1106
+ extension: defineSchemaExtension("ratelimit", {
1107
+ tables: {
1108
+ buckets: defineTable({
1109
+ key: v.string(),
1110
+ value: v.number(),
1111
+ ts: v.number(),
1112
+ prev: v.optional(v.number()),
1113
+ })
1114
+ .index("by_key", ["key"])
1115
+ .externallyManaged(),
1116
+ },
1117
+ }),
1118
+ middleware,
1119
+ });
1120
+ `,sa=`import { ratelimit } from "./ratelimit/schema.js";
1121
+ import { defineSchema, defineTable, v } from "lunorash/server";
519
1122
 
520
1123
  export default defineSchema({
521
1124
  messages: defineTable({
@@ -524,19 +1127,36 @@ export default defineSchema({
524
1127
  })
525
1128
  .shardBy("channelId")
526
1129
  .index("by_channel", ["channelId"]),
527
- });
528
- `;
529
- const LUNORA_MESSAGES = `import { mutation, query, v } from "./_generated/server.js";
1130
+ }).extend(ratelimit.extension);
1131
+ `,na=`import { RateLimiter, rateLimit, createDbStore } from "lunorash/ratelimit";
530
1132
 
531
- export const list = query.input({ channelId: v.string(), limit: v.optional(v.number()) }).query(async ({ args }) => {
532
- return { channelId: args.channelId, limit: args.limit ?? 50, messages: [] };
1133
+ import { mutation, query, v } from "#lunora/_generated/server.js";
1134
+
1135
+ const limiter = (ctx: { db: unknown }) => new RateLimiter({
1136
+ config: {
1137
+ send: { kind: "token bucket", period: 60_000, rate: 30 },
1138
+ },
1139
+ store: createDbStore({ db: ctx.db as never, table: "ratelimit_buckets" }),
533
1140
  });
534
1141
 
535
- export const send = mutation.input({ channelId: v.string(), text: v.string() }).mutation(async ({ args }) => {
536
- return { channelId: args.channelId, text: args.text };
1142
+ export const list = query.input({ channelId: v.string().meta({ schema: { maxLength: 256 } }), limit: v.optional(v.number()) }).query(async ({ args, ctx }) => {
1143
+ const messages = await ctx.db
1144
+ .query("messages")
1145
+ .withIndex("by_channel", (q) => q.eq("channelId", args.channelId))
1146
+ .take(args.limit ?? 50);
1147
+
1148
+ return { channelId: args.channelId, messages };
537
1149
  });
538
- `;
539
- const SERVER_ENTRY = `import type { ShardNamespaceLike } from "lunorash/runtime";
1150
+
1151
+ export const send = mutation
1152
+ .input({ channelId: v.string().meta({ schema: { maxLength: 256 } }), text: v.string().meta({ schema: { maxLength: 4096 } }) })
1153
+ .use(rateLimit(limiter, "send", { key: (ctx) => ctx.auth.userId ?? "anon" }))
1154
+ .mutation(async ({ args, ctx }) => {
1155
+ const id = await ctx.db.insert("messages", { channelId: args.channelId, text: args.text });
1156
+
1157
+ return { channelId: args.channelId, id, text: args.text };
1158
+ });
1159
+ `,ia=`import type { ShardNamespaceLike } from "lunorash/runtime";
540
1160
 
541
1161
  import { defineApp } from "../lunora/_generated/app.js";
542
1162
 
@@ -550,8 +1170,7 @@ const app = defineApp<Env>()
550
1170
 
551
1171
  export const ShardDO = app.ShardDO;
552
1172
  export default app;
553
- `;
554
- const WRANGLER = `{
1173
+ `,la=`{
555
1174
  "$schema": "node_modules/wrangler/config-schema.json",
556
1175
  "name": "__NAME__",
557
1176
  "main": "src/server.ts",
@@ -563,205 +1182,23 @@ const WRANGLER = `{
563
1182
  "migrations": [{ "tag": "v1", "new_sqlite_classes": ["ShardDO"] }],
564
1183
  "observability": { "enabled": true, "head_sampling_rate": 1 },
565
1184
  }
566
- `;
567
- const GITIGNORE_ADDITIONS = [".wrangler", ".env", ".env.*", "!.env.example", ".lunora/", ".lunora-cache", "lunora/_generated"];
568
- const ENV_EXAMPLE = `# Lunora endpoint for the browser client.
1185
+ `,ca=[".wrangler",".env",".env.*","!.env.example",".dev.vars",".dev.vars.*","!.dev.vars.example",".lunora/",".lunora-cache","lunora/_generated"],da=`# Lunora endpoint for the browser client.
569
1186
  # Vite statically replaces \`import.meta.env.VITE_LUNORA_URL\` at \`vite dev\` / build.
570
1187
  # Leave it unset to use the page origin; set it to point at a deployed Worker:
571
1188
  #
572
1189
  # VITE_LUNORA_URL=https://my-app.example.workers.dev
573
- `;
574
- const COMMON_DEV_DEPENDENCIES = {
575
- "@cloudflare/workers-types": "^4.20260611.1",
576
- wrangler: "^4.100.0"
577
- };
578
- const writeFile = (target, relativePath, contents, written) => {
579
- const destination = join$1(target, relativePath);
580
- mkdirSync(dirname$1(destination), { recursive: true });
581
- writeFileSync(destination, contents, "utf8");
582
- written.push(destination);
583
- };
584
- const NEWLINE = /\r?\n/;
585
- const ensureGitignore = (target) => {
586
- const path = join$1(target, ".gitignore");
587
- const existing = existsSync(path) ? readFileSync(path, "utf8") : "";
588
- const missing = GITIGNORE_ADDITIONS.filter((entry) => !existing.split(NEWLINE).includes(entry));
589
- if (missing.length === 0) {
590
- return;
591
- }
592
- const prefix = existing.length > 0 && !existing.endsWith("\n") ? "\n" : "";
593
- writeFileSync(path, `${existing}${prefix}
1190
+ `,ua={"@cloudflare/workers-types":"^4.20260611.1",wrangler:"^4.100.0"},x=(e,t,a,r)=>{const o=u(e,t);M(A(o),{recursive:!0}),v(o,a,"utf8"),r.push(o)},pa=/\r?\n/,ha=e=>{const t=u(e,".gitignore"),a=m(t)?b(t,"utf8"):"",r=new Set(a.split(pa)),o=ca.filter(n=>!r.has(n));if(o.length===0)return;const s=a.length>0&&!a.endsWith(`
1191
+ `)?`
1192
+ `:"";v(t,`${a}${s}
594
1193
  # Lunora
595
- ${missing.join("\n")}
596
- `, "utf8");
597
- };
598
- const isLunoraDep$1 = (name) => name === "lunorash" || name.startsWith("@lunora/");
599
- const stampRange = (name, range, distTag, versions) => isLunoraDep$1(name) ? versions?.get(name) ?? distTag : range;
600
- const withDependency = (map, name, range, distTag) => {
601
- return { ...map, [name]: stampRange(name, range, distTag) };
602
- };
603
- const restampLunora = (map, distTag, versions) => Object.fromEntries(Object.entries(map).map(([name, range]) => [name, stampRange(name, range, distTag, versions)]));
604
- const patchPackageJson = async (target, name, adapter, distTag) => {
605
- const path = join$1(target, "package.json");
606
- const parsed = JSON.parse(readFileSync(path, "utf8"));
607
- let dependencies = withDependency(parsed.dependencies ?? {}, "lunorash", distTag, distTag);
608
- if (adapter.adapter.startsWith("@lunora/")) {
609
- dependencies = withDependency(dependencies, adapter.adapter, distTag, distTag);
610
- }
611
- for (const [depName, range] of Object.entries(adapter.extraDependencies ?? {})) {
612
- dependencies = withDependency(dependencies, depName, range, distTag);
613
- }
614
- let devDependencies = withDependency(parsed.devDependencies ?? {}, "@lunora/vite", distTag, distTag);
615
- devDependencies = withDependency(devDependencies, "@lunora/studio", distTag, distTag);
616
- for (const [depName, range] of Object.entries(COMMON_DEV_DEPENDENCIES)) {
617
- devDependencies = withDependency(devDependencies, depName, range, distTag);
618
- }
619
- const lunoraNames = [...Object.keys(dependencies), ...Object.keys(devDependencies)].filter((depName) => isLunoraDep$1(depName));
620
- const versions = await resolveTagVersions(lunoraNames, distTag);
621
- parsed.name = name;
622
- parsed.imports = { ...parsed.imports, "#lunora/*": "./lunora/*" };
623
- parsed.dependencies = restampLunora(dependencies, distTag, versions);
624
- parsed.devDependencies = restampLunora(devDependencies, distTag, versions);
625
- parsed.scripts = { ...parsed.scripts, codegen: "lunora codegen", deploy: "vite build && lunora deploy" };
626
- writeFileSync(path, `${JSON.stringify(parsed, void 0, 4)}
627
- `, "utf8");
628
- };
629
- const patchBaseViteConfig = (target, logger) => {
630
- const candidate = ["vite.config.ts", "vite.config.mts", "vite.config.js", "vite.config.mjs"].map((file) => join$1(target, file)).find((path) => existsSync(path));
631
- if (candidate === void 0) {
632
- logger.warn("overlay: no vite.config found in the create-vite base — add `lunora()` to your Vite plugins manually.");
633
- return;
634
- }
635
- const result = patchViteConfig(readFileSync(candidate, "utf8"));
636
- if (result.changed) {
637
- writeFileSync(candidate, result.code, "utf8");
638
- }
639
- };
640
- const applyLunoraOverlay = async (options) => {
641
- const { adapter, distTag, logger, name, target } = options;
642
- const written = [];
643
- writeFile(target, join$1("lunora", "schema.ts"), LUNORA_SCHEMA, written);
644
- writeFile(target, join$1("lunora", "messages.ts"), LUNORA_MESSAGES, written);
645
- writeFile(target, join$1("src", "server.ts"), SERVER_ENTRY, written);
646
- writeFile(target, "wrangler.jsonc", WRANGLER.replaceAll("__NAME__", name), written);
647
- writeFile(target, ".env.example", ENV_EXAMPLE, written);
648
- for (const file of adapter.files) {
649
- writeFile(target, file.path, file.contents, written);
650
- }
651
- patchBaseViteConfig(target, logger);
652
- await patchPackageJson(target, name, adapter, distTag);
653
- ensureGitignore(target);
654
- return written;
655
- };
656
-
657
- const ADJECTIVES = [
658
- "lunar",
659
- "silver",
660
- "silent",
661
- "waning",
662
- "waxing",
663
- "crescent",
664
- "cosmic",
665
- "stellar",
666
- "orbital",
667
- "gibbous",
668
- "twilight",
669
- "midnight",
670
- "shimmering",
671
- "drifting",
672
- "weightless"
673
- ];
674
- const NOUNS = [
675
- "moon",
676
- "tide",
677
- "crater",
678
- "comet",
679
- "eclipse",
680
- "halo",
681
- "orbit",
682
- "nebula",
683
- "voyager",
684
- "lander",
685
- "rover",
686
- "beacon",
687
- "harbor",
688
- "meadow",
689
- "fox"
690
- ];
691
- const pick = (items) => (
692
- // eslint-disable-next-line sonarjs/pseudo-random -- cosmetic default project name, not a security decision.
693
- items[Math.floor(Math.random() * items.length)]
694
- );
695
- const generateProjectName = () => `${pick(ADJECTIVES)}-${pick(NOUNS)}`;
696
-
697
- const isOnline = async () => dns.lookup("github.com").then(
698
- () => true,
699
- () => false
700
- );
701
- const GITHUB_SOURCE = /^(?:gh|github):([^/]+)\/([^#/]+)(?:\/[^#]*)?(?:#(.+))?$/;
702
- const parseGitHubSource = (source) => {
703
- const match = GITHUB_SOURCE.exec(source);
704
- if (match === null) {
705
- return void 0;
706
- }
707
- const [, owner, repo, ref] = match;
708
- if (owner === void 0 || repo === void 0) {
709
- return void 0;
710
- }
711
- return { owner, ref: ref ?? "HEAD", repo };
712
- };
713
- const templateRefExists = async (source) => {
714
- const parsed = parseGitHubSource(source);
715
- if (parsed === void 0) {
716
- return void 0;
717
- }
718
- const url = `https://codeload.github.com/${parsed.owner}/${parsed.repo}/tar.gz/${parsed.ref}`;
719
- try {
720
- const response = await fetch(url, { method: "HEAD" });
721
- if (response.status === 404) {
722
- return false;
723
- }
724
- return response.ok ? true : void 0;
725
- } catch {
726
- return void 0;
727
- }
728
- };
729
- const verifyRemoteTemplate = async (params) => {
730
- if (params.isLocal) {
731
- return true;
732
- }
733
- const isGitHubBacked = params.source === void 0 || parseGitHubSource(params.source) !== void 0;
734
- if (!isGitHubBacked) {
735
- return true;
736
- }
737
- if (!await isOnline()) {
738
- params.logger.error("you appear to be offline — connect to the internet and try again, or scaffold from a local template with `--from <dir>`.");
739
- return false;
740
- }
741
- if (params.source !== void 0 && await templateRefExists(params.source) === false) {
742
- params.logger.error(`template source not found: ${params.source} — double-check --ref / --source, or browse the templates at https://lunora.sh/docs.`);
743
- return false;
744
- }
745
- return true;
746
- };
747
-
748
- const COPY = {
749
- extras: "Let's finish setting up your app.",
750
- framework: "Which framework should we launch?",
751
- git: "Initialize a new git repository? (optional)",
752
- install: "Install dependencies now?",
753
- name: "Where should we land your project?",
754
- nextHeader: "Liftoff confirmed — explore your project!",
755
- packageManager: "Which package manager?"
756
- };
757
- const TEXT_EXTENSIONS = /* @__PURE__ */ new Set([".gitignore", ".html", ".js", ".json", ".jsonc", ".md", ".mjs", ".ts", ".tsx"]);
758
- const VITE_CONFIG_CANDIDATES = ["vite.config.ts", "vite.config.mts", "vite.config.js", "vite.config.mjs"];
759
- const MINIMAL_VITE_CONFIG = `import { defineConfig } from "vite";
1194
+ ${o.join(`
1195
+ `)}
1196
+ `,"utf8")},P=e=>e==="lunorash"||e.startsWith("@lunora/"),ma=(e,t,a,r)=>P(e)?r.get(e)??a:t,k=(e,t,a)=>({...e,[t]:a}),ee=(e,t,a)=>Object.fromEntries(Object.entries(e).map(([r,o])=>[r,ma(r,o,t,a)])),fa=async(e,t,a,r)=>{const o=u(e,"package.json"),s=JSON.parse(b(o,"utf8"));let n=k(s.dependencies??{},"lunorash",r);n=k(n,"@lunora/ratelimit",r),a.adapter.startsWith("@lunora/")&&(n=k(n,a.adapter,r));for(const[c,p]of Object.entries(a.extraDependencies??{}))n=k(n,c,p);let i=k(s.devDependencies??{},"@lunora/vite",r);i=k(i,"@lunora/studio",r);for(const[c,p]of Object.entries(ua))i=k(i,c,p);const l=[...Object.keys(n),...Object.keys(i)].filter(c=>P(c)),d=await ce(l,r);s.name=t,s.imports={...s.imports,"#lunora/*":"./lunora/*"},s.dependencies=ee(n,r,d),s.devDependencies=ee(i,r,d),s.scripts={...s.scripts,codegen:"lunora codegen",deploy:"vite build && lunora deploy"},v(o,`${JSON.stringify(s,void 0,4)}
1197
+ `,"utf8")},va=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],Se=e=>va.map(t=>u(e,t)).find(t=>m(t)),ga=(e,t)=>{const a=Se(e);if(a===void 0){t.warn("overlay: no vite.config found in the create-vite base — add `lunora()` to your Vite plugins manually.");return}const r=ke(b(a,"utf8"));r.changed&&v(a,r.code,"utf8")},wa=async e=>{const{adapter:t,distTag:a,logger:r,name:o,target:s}=e,n=[];x(s,u("lunora","ratelimit","schema.ts"),oa,n),x(s,u("lunora","schema.ts"),sa,n),x(s,u("lunora","messages.ts"),na,n),x(s,u("src","server.ts"),ia,n),x(s,"wrangler.jsonc",la.replaceAll("__NAME__",o),n),x(s,".env.example",da,n);for(const i of t.files)x(s,i.path,i.contents,n);return ga(s,r),await fa(s,o,t,a),ha(s),n},ya=["lunar","silver","silent","waning","waxing","crescent","cosmic","stellar","orbital","gibbous","twilight","midnight","shimmering","drifting","weightless"],ba=["moon","tide","crater","comet","eclipse","halo","orbit","nebula","voyager","lander","rover","beacon","harbor","meadow","fox"],te=e=>e[Math.floor(Math.random()*e.length)],xa=()=>`${te(ya)}-${te(ba)}`,ka=async()=>vt.lookup("github.com").then(()=>!0,()=>!1),Ca=/^(?:gh|github):([^/]+)\/([^#/]+)(?:\/[^#]*)?(?:#(.+))?$/,Le=e=>{const t=Ca.exec(e);if(t===null)return;const[,a,r,o]=t;if(!(a===void 0||r===void 0))return{owner:a,ref:o??"HEAD",repo:r}},Sa=async e=>{const t=Le(e);if(t===void 0)return;const a=`https://codeload.github.com/${t.owner}/${t.repo}/tar.gz/${t.ref}`;try{const r=await fetch(a,{method:"HEAD"});return r.status===404?!1:r.ok?!0:void 0}catch{return}},Me=async e=>e.isLocal||!(e.source===void 0||Le(e.source)!==void 0)?!0:await ka()?e.source!==void 0&&await Sa(e.source)===!1?(e.logger.error(`template source not found: ${e.source} — double-check --ref / --source, or browse the templates at https://lunora.sh/docs.`),!1):!0:(e.logger.error("you appear to be offline — connect to the internet and try again, or scaffold from a local template with `--from <dir>`."),!1),y={extras:"Let's finish setting up your app.",framework:"Which framework should we launch?",git:"Initialize a new git repository? (optional)",install:"Install dependencies now?",name:"Where should we land your project?",nextHeader:"Liftoff confirmed — explore your project!",packageManager:"Which package manager?"},La=new Set([".gitignore",".html",".js",".json",".jsonc",".md",".mjs",".ts",".tsx"]),Ma=`import { defineConfig } from "vite";
760
1198
  import { lunora } from "@lunora/vite";
761
1199
 
762
1200
  export default defineConfig({ plugins: [lunora()] });
763
- `;
764
- const SAMPLE_SCHEMA = `import { defineSchema, defineTable, v } from "@lunora/server";
1201
+ `,Aa=`import { defineSchema, defineTable, v } from "@lunora/server";
765
1202
 
766
1203
  export default defineSchema({
767
1204
  messages: defineTable({
@@ -771,8 +1208,7 @@ export default defineSchema({
771
1208
  .shardBy("channelId")
772
1209
  .index("by_channel", ["channelId"]),
773
1210
  });
774
- `;
775
- const SAMPLE_FUNCTION = `import { mutation, query, v } from "./_generated/server";
1211
+ `,Ea=`import { mutation, query, v } from "./_generated/server";
776
1212
 
777
1213
  export const list = query
778
1214
  .input({ channelId: v.id("channels"), limit: v.optional(v.number()) })
@@ -785,760 +1221,8 @@ export const send = mutation
785
1221
  .mutation(async ({ args }) => {
786
1222
  return { channelId: args.channelId, text: args.text };
787
1223
  });
788
- `;
789
- const DEFAULT_SOURCE_BASE = "gh:anolilab/lunora/templates";
790
- const isTextFile = (filePath) => {
791
- const lastDot = filePath.lastIndexOf(".");
792
- if (lastDot === -1) {
793
- return false;
794
- }
795
- return TEXT_EXTENSIONS.has(filePath.slice(lastDot));
796
- };
797
- const substitute = (content, name) => content.replaceAll("{{name}}", name);
798
- const isLunoraDep = (name) => name === "lunorash" || name.startsWith("@lunora/");
799
- const resolveLunoraVersions = async (files, distTag) => {
800
- const names = /* @__PURE__ */ new Set();
801
- for (const file of files) {
802
- if (basename(file) !== "package.json") {
803
- continue;
804
- }
805
- try {
806
- const parsed = JSON.parse(readFileSync(file, "utf8"));
807
- for (const section of ["dependencies", "devDependencies"]) {
808
- for (const name of Object.keys(parsed[section] ?? {})) {
809
- if (isLunoraDep(name)) {
810
- names.add(name);
811
- }
812
- }
813
- }
814
- } catch {
815
- }
816
- }
817
- return resolveTagVersions(names, distTag);
818
- };
819
- const stampLunoraDeps = (packageJsonText, distTag, versions) => {
820
- let parsed;
821
- try {
822
- parsed = JSON.parse(packageJsonText);
823
- } catch {
824
- return packageJsonText;
825
- }
826
- let text = packageJsonText;
827
- for (const section of ["dependencies", "devDependencies"]) {
828
- for (const name of Object.keys(parsed[section] ?? {})) {
829
- if (!isLunoraDep(name)) {
830
- continue;
831
- }
832
- const pin = versions.get(name) ?? distTag;
833
- const edits = modify(text, [section, name], pin, { formattingOptions: { insertSpaces: true, tabSize: 4 } });
834
- text = applyEdits(text, edits);
835
- }
836
- }
837
- return text;
838
- };
839
- const PNPM_BUILT_DEPENDENCIES = ["esbuild", "sharp", "workerd"];
840
- const PNPM_WORKSPACE_FILENAME = "pnpm-workspace.yaml";
841
- const pnpmWorkspaceYaml = () => [
842
- "# pnpm reads its settings from here (the package.json `pnpm` field is no longer read).",
843
- "# Pre-approve the toolchain's native build scripts so `pnpm install` runs them",
844
- "# without the interactive `pnpm approve-builds` step.",
845
- "allowBuilds:",
846
- ...PNPM_BUILT_DEPENDENCIES.map((name) => ` ${name}: true`),
847
- ""
848
- ].join("\n");
849
- const collectFiles = (directory) => {
850
- const out = [];
851
- for (const entry of walkSync(directory, { includeDirs: false, includeFiles: true })) {
852
- out.push(entry.path);
853
- }
854
- return out;
855
- };
856
- const copyTemplate = async (sourceDirectory, target, name) => {
857
- const files = collectFiles(sourceDirectory);
858
- const written = [];
859
- const distTag = resolveDistTag();
860
- const versions = await resolveLunoraVersions(files, distTag);
861
- for (const source of files) {
862
- const relativePath = relative(sourceDirectory, source);
863
- const destination = join$1(target, relativePath);
864
- mkdirSync(dirname$1(destination), { recursive: true });
865
- const raw = readFileSync(source);
866
- let text = isTextFile(source) ? substitute(raw.toString("utf8"), name) : void 0;
867
- if (text !== void 0 && basename(source) === "package.json") {
868
- text = stampLunoraDeps(text, distTag, versions);
869
- }
870
- if (text === void 0) {
871
- writeFileSync(destination, raw);
872
- } else {
873
- writeFileSync(destination, text, "utf8");
874
- }
875
- written.push(destination);
876
- }
877
- return written;
878
- };
879
- const resolveTemplateSource = (templateType, source, ref) => {
880
- if (source !== void 0 && source.length > 0) {
881
- return source;
882
- }
883
- return `${DEFAULT_SOURCE_BASE}/${templateType}#${resolveSourceRef(ref)}`;
884
- };
885
- const isSafeSource = (source) => {
886
- if (source.includes("..")) {
887
- return false;
888
- }
889
- return source.startsWith("gh:") || source.startsWith("github:") || source.startsWith("https://");
890
- };
891
- const logWould = (logger, action) => {
892
- logger.info(`[dry-run] would ${action}`);
893
- };
894
- const logScaffoldSuccess = (logger, written, target) => {
895
- if (isInteractive()) {
896
- process.stdout.write("\n");
897
- }
898
- logger.success(`scaffolded ${String(written.length)} files into ${target}`);
899
- };
900
- const runScriptCommand = (manager, script) => {
901
- if (manager === "npm") {
902
- return `npm run ${script}`;
903
- }
904
- if (manager === "bun") {
905
- return `bun run ${script}`;
906
- }
907
- return `${manager} ${script}`;
908
- };
909
- const isInsideMonorepo = (startDirectory) => {
910
- let directory = resolve(startDirectory);
911
- for (; ; ) {
912
- if (existsSync(join$1(directory, "pnpm-workspace.yaml"))) {
913
- return true;
914
- }
915
- const packagePath = join$1(directory, "package.json");
916
- if (existsSync(packagePath)) {
917
- try {
918
- const parsed = JSON.parse(readFileSync(packagePath, "utf8"));
919
- if (parsed.workspaces !== void 0) {
920
- return true;
921
- }
922
- } catch {
923
- }
924
- }
925
- const parent = dirname$1(directory);
926
- if (parent === directory) {
927
- return false;
928
- }
929
- directory = parent;
930
- }
931
- };
932
- const isInsideGitRepo = (startDirectory) => {
933
- let directory = resolve(startDirectory);
934
- for (; ; ) {
935
- if (existsSync(join$1(directory, ".git"))) {
936
- return true;
937
- }
938
- const parent = dirname$1(directory);
939
- if (parent === directory) {
940
- return false;
941
- }
942
- directory = parent;
943
- }
944
- };
945
- const maybeOfferGit = async (options, target) => {
946
- if (options.yes === true || !isInteractive() || isInsideGitRepo(dirname$1(target))) {
947
- return;
948
- }
949
- if (!await tuiConfirm(COPY.git, { badge: BADGES.git, defaultYes: false })) {
950
- await tuiInfo("Sounds good! You can always run git init manually.");
951
- return;
952
- }
953
- if (options.dryRun === true) {
954
- logWould(options.logger, "initialize a git repository");
955
- return;
956
- }
957
- const spawner = options.spawner ?? defaultSpawner;
958
- const result = await withTuiSpinner("Initializing a git repository…", () => spawner({ args: ["init"], command: "git", cwd: target }));
959
- if (result.code === 0) {
960
- await emitStep("git", "Initialized an empty git repository.");
961
- } else {
962
- options.logger.warn("`git init` failed — initialize it yourself later with `git init`.");
963
- }
964
- };
965
- const printNextSteps = async (name, installed, insideMonorepo) => {
966
- const manager = installed ?? "pnpm";
967
- const steps = [{ code: `cd ./${name}`, lead: "Enter your project directory using" }];
968
- if (installed === void 0) {
969
- steps.push({ code: `${manager} install`, lead: "Install dependencies with", tail: insideMonorepo ? " from the workspace root" : void 0 });
970
- }
971
- steps.push(
972
- { code: runScriptCommand(manager, "dev"), lead: "Run", tail: " to start the dev server." },
973
- { code: "lunora add", lead: "Add features like auth or storage using" }
974
- );
975
- const help = [
976
- { code: "https://lunora.sh/docs", lead: "Read the docs at" },
977
- { code: "https://lunora.sh/chat", lead: "Stuck? Join the chat at" }
978
- ];
979
- if (isInteractive()) {
980
- await tuiNextSteps(BADGES.next, COPY.nextHeader, steps, help);
981
- return;
982
- }
983
- const lines = steps.map((step) => `${step.lead} ${step.code}${step.tail ?? ""}`);
984
- lines.push("", ...help.map((line) => `${line.lead} ${line.code}${line.tail ?? ""}`));
985
- await emitStep("next", COPY.nextHeader, lines.join("\n"));
986
- };
987
- const offerInstallIsInteractive = (options) => options.yes !== true && (options.installPrompt !== void 0 || isInteractive());
988
- const maybeOfferInstall = async (options, target) => {
989
- if (!offerInstallIsInteractive(options)) {
990
- return void 0;
991
- }
992
- if (isInsideMonorepo(dirname$1(target))) {
993
- return void 0;
994
- }
995
- const managers = detectInstalledManagers(options.packageManagerProbe);
996
- const [defaultManager] = managers;
997
- if (defaultManager === void 0) {
998
- return void 0;
999
- }
1000
- const confirm = options.installPrompt?.confirmInstall ?? (async () => tuiConfirm(COPY.install, { badge: BADGES.deps, defaultYes: true }));
1001
- if (!await confirm()) {
1002
- await tuiInfo("No problem! Remember to install dependencies after setup.");
1003
- return void 0;
1004
- }
1005
- let manager = defaultManager;
1006
- if (managers.length > 1) {
1007
- manager = options.installPrompt ? await options.installPrompt.selectManager(managers) : await tuiSelect(
1008
- COPY.packageManager,
1009
- managers.map((candidate) => {
1010
- return { label: candidate, value: candidate };
1011
- }),
1012
- { badge: BADGES.deps, default: defaultManager }
1013
- ) ?? defaultManager;
1014
- }
1015
- if (options.dryRun === true) {
1016
- logWould(options.logger, `install dependencies with ${manager}`);
1017
- return void 0;
1018
- }
1019
- if (manager === "pnpm") {
1020
- const workspacePath = join$1(target, PNPM_WORKSPACE_FILENAME);
1021
- if (!existsSync(workspacePath)) {
1022
- writeFileSync(workspacePath, pnpmWorkspaceYaml(), "utf8");
1023
- }
1024
- }
1025
- const spawner = options.spawner ?? defaultSpawner;
1026
- const { args, command } = installArgsFor(manager);
1027
- await emitStep("deps", `Installing dependencies with ${manager}…`);
1028
- const result = await spawner({ args, command, cwd: target });
1029
- if (result.code !== 0) {
1030
- options.logger.warn(`\`${command} install\` exited with code ${String(result.code)} — run it yourself in ${basename(target)}/.`);
1031
- return void 0;
1032
- }
1033
- await emitStep("deps", `Dependencies installed with ${manager}.`);
1034
- return manager;
1035
- };
1036
- const scaffoldFromLocal = async (fromRoot, templateType, target, name, logger) => {
1037
- const templateDirectory = join$1(fromRoot, templateType);
1038
- if (!existsSync(templateDirectory)) {
1039
- logger.error(`template not found in local source: ${templateDirectory}`);
1040
- return { code: 1, files: [], target };
1041
- }
1042
- const written = await copyTemplate(templateDirectory, target, name);
1043
- logScaffoldSuccess(logger, written, target);
1044
- return { code: 0, files: written, target };
1045
- };
1046
- const scaffoldFromRemote = async (options) => {
1047
- const { logger, name, ref, source, target, templateType } = options;
1048
- const stagingRoot = mkdtempSync(join$1(tmpdir(), "lunora-init-fetch-"));
1049
- const stagingDirectory = join$1(stagingRoot, "template");
1050
- try {
1051
- const remote = resolveTemplateSource(templateType, source, ref);
1052
- let downloaded;
1053
- let written = [];
1054
- await tuiTasks(
1055
- [
1056
- {
1057
- label: `${templateType} template fetched`,
1058
- run: async () => {
1059
- downloaded = await downloadTemplate(remote, {
1060
- cwd: stagingRoot,
1061
- dir: stagingDirectory,
1062
- force: true,
1063
- install: false,
1064
- silent: true
1065
- });
1066
- }
1067
- },
1068
- {
1069
- label: `files copied into ${name}/`,
1070
- run: async () => {
1071
- written = await copyTemplate(stagingDirectory, target, name);
1072
- }
1073
- }
1074
- ],
1075
- { end: "Project initialized!", start: "Project initializing…" }
1076
- );
1077
- const staged = collectFiles(stagingDirectory);
1078
- if (isInteractive()) {
1079
- process.stdout.write("\n");
1080
- }
1081
- logger.info(
1082
- downloaded?.commit ? `template: ${downloaded.source} @ ${downloaded.commit} (${String(staged.length)} files)` : `template: ${downloaded?.source ?? remote} (${String(staged.length)} files)`
1083
- );
1084
- logScaffoldSuccess(logger, written, target);
1085
- return { code: 0, files: written, target };
1086
- } catch (error) {
1087
- if (error instanceof PromptCancelledError) {
1088
- throw error;
1089
- }
1090
- const message = error instanceof Error ? error.message : String(error);
1091
- logger.error(`failed to download template: ${message}`);
1092
- return { code: 1, files: [], target };
1093
- } finally {
1094
- rmSync(stagingRoot, { force: true, recursive: true });
1095
- }
1096
- };
1097
- const renameCreateViteDotfiles = (directory) => {
1098
- for (const file of ["_gitignore", "_npmrc", "_gitattributes"]) {
1099
- const from = join$1(directory, file);
1100
- if (existsSync(from)) {
1101
- renameSync(from, join$1(directory, `.${file.slice(1)}`));
1102
- }
1103
- }
1104
- };
1105
- const scaffoldViteOverlay = async (options) => {
1106
- const { framework, logger, name, overlayBaseFrom, target } = options;
1107
- const adapter = ADAPTERS[framework];
1108
- const stagingRoot = mkdtempSync(join$1(tmpdir(), "lunora-vite-base-"));
1109
- try {
1110
- let localBase;
1111
- if (overlayBaseFrom !== void 0) {
1112
- localBase = join$1(overlayBaseFrom, `template-${adapter.createViteTemplate}`);
1113
- if (!existsSync(localBase)) {
1114
- logger.error(`create-vite base not found on disk: ${localBase}`);
1115
- return { code: 1, files: [], target };
1116
- }
1117
- }
1118
- const copyBase = async () => {
1119
- if (localBase !== void 0) {
1120
- cpSync(localBase, target, { recursive: true });
1121
- return;
1122
- }
1123
- const stagingDirectory = join$1(stagingRoot, "base");
1124
- const remote = `github:vitejs/vite/packages/create-vite/template-${adapter.createViteTemplate}#main`;
1125
- await downloadTemplate(remote, { cwd: stagingRoot, dir: stagingDirectory, force: true, install: false, silent: true });
1126
- renameCreateViteDotfiles(stagingDirectory);
1127
- cpSync(stagingDirectory, target, { recursive: true });
1128
- };
1129
- let written = [];
1130
- await tuiTasks(
1131
- [
1132
- { label: `create-vite (${adapter.label}) base ready`, run: copyBase },
1133
- {
1134
- label: `Lunora overlay applied (${adapter.label})`,
1135
- run: async () => {
1136
- written = await applyLunoraOverlay({ adapter, distTag: resolveDistTag(), logger, name, target });
1137
- }
1138
- }
1139
- ],
1140
- { end: "Project initialized!", start: "Project initializing…" }
1141
- );
1142
- logScaffoldSuccess(logger, written, target);
1143
- return { code: 0, files: [...collectFiles(target)], target };
1144
- } catch (error) {
1145
- if (error instanceof PromptCancelledError) {
1146
- throw error;
1147
- }
1148
- const message = error instanceof Error ? error.message : String(error);
1149
- logger.error(`failed to scaffold the ${adapter.label} base: ${message}`);
1150
- return { code: 1, files: [], target };
1151
- } finally {
1152
- rmSync(stagingRoot, { force: true, recursive: true });
1153
- }
1154
- };
1155
- const createMinimalViteConfig = (cwd, logger) => {
1156
- const target = join$1(cwd, "vite.config.ts");
1157
- try {
1158
- writeFileSync(target, MINIMAL_VITE_CONFIG, "utf8");
1159
- } catch (error) {
1160
- const message = error instanceof Error ? error.message : String(error);
1161
- logger.error(`init --in-place: could not write ${target}: ${message}`);
1162
- return { code: 1, files: [], target: cwd };
1163
- }
1164
- logger.success(`created ${target} with lunora() plugin`);
1165
- return { code: 0, files: [target], target: cwd };
1166
- };
1167
- const patchExistingViteConfig = (viteConfigPath, cwd, logger) => {
1168
- let source;
1169
- try {
1170
- source = readFileSync(viteConfigPath, "utf8");
1171
- } catch (error) {
1172
- const message = error instanceof Error ? error.message : String(error);
1173
- logger.error(`init --in-place: could not read ${viteConfigPath}: ${message}`);
1174
- return { code: 1, files: [], target: cwd };
1175
- }
1176
- const result = patchViteConfig(source);
1177
- if (!result.changed) {
1178
- logger.info(`${viteConfigPath}: ${result.reason ?? "no changes needed"}`);
1179
- return { code: 0, files: [], target: cwd };
1180
- }
1181
- try {
1182
- writeFileSync(viteConfigPath, result.code, "utf8");
1183
- } catch (error) {
1184
- const message = error instanceof Error ? error.message : String(error);
1185
- logger.error(`init --in-place: could not write ${viteConfigPath}: ${message}`);
1186
- return { code: 1, files: [], target: cwd };
1187
- }
1188
- logger.success(`patched ${viteConfigPath} — added lunora() plugin`);
1189
- return { code: 0, files: [viteConfigPath], target: cwd };
1190
- };
1191
- const scaffoldLunoraDirectory = (cwd, logger) => {
1192
- const lunoraDirectory = join$1(cwd, "lunora");
1193
- const schemaPath = join$1(lunoraDirectory, "schema.ts");
1194
- if (existsSync(schemaPath)) {
1195
- logger.info(`lunora/ already present — left ${schemaPath} untouched`);
1196
- return [];
1197
- }
1198
- const written = [];
1199
- try {
1200
- mkdirSync(lunoraDirectory, { recursive: true });
1201
- writeFileSync(schemaPath, SAMPLE_SCHEMA, "utf8");
1202
- written.push(schemaPath);
1203
- const functionPath = join$1(lunoraDirectory, "messages.ts");
1204
- if (!existsSync(functionPath)) {
1205
- writeFileSync(functionPath, SAMPLE_FUNCTION, "utf8");
1206
- written.push(functionPath);
1207
- }
1208
- logger.success(`scaffolded lunora/ (${String(written.length)} file(s))`);
1209
- } catch (error) {
1210
- const message = error instanceof Error ? error.message : String(error);
1211
- logger.error(`init --here: could not scaffold lunora/: ${message}`);
1212
- }
1213
- return written;
1214
- };
1215
- const printFrameworkNextSteps = (detection, logger) => {
1216
- const { adapter, class: frameworkClass, framework } = detection;
1217
- logger.info("");
1218
- logger.info(`detected framework: ${framework} (class ${frameworkClass})`);
1219
- logger.info("next steps:");
1220
- logger.info(` 1. install the adapter: pnpm add ${adapter} @lunora/client @lunora/runtime @lunora/server`);
1221
- logger.info(" 2. run codegen: lunora codegen");
1222
- if (frameworkClass === "A") {
1223
- logger.info(" 3. compose one worker: wrap your worker entry with");
1224
- logger.info(" createWorker({ httpRouter: <your framework SSR handler>, shardDO: ShardDO, ... })");
1225
- logger.info(` 4. add the provider: mount the ${adapter} provider in your root layout/route`);
1226
- logger.info(" 5. make a loader live: preloadQuery() in a loader, usePreloadedQuery() in the component");
1227
- logger.info(" see https://lunora.sh/docs/frameworks/reactive-loaders");
1228
- } else if (frameworkClass === "B") {
1229
- logger.info(" 3. inject Lunora: mount Lunora realtime under /_lunora/* in your server hook");
1230
- logger.info(` (${framework} owns its Cloudflare adapter — Lunora composes into its server entry)`);
1231
- logger.info(` 4. add the provider: mount the ${adapter} provider in your root layout`);
1232
- logger.info(" 5. read the guide: https://lunora.sh/docs/frameworks/deploy");
1233
- } else {
1234
- logger.info(" 3. add the provider: wrap your app with the LunoraProvider from @lunora/react");
1235
- logger.info(" 4. read the guide: https://lunora.sh/docs/frameworks/bring-your-framework");
1236
- }
1237
- logger.info("");
1238
- };
1239
- const findExistingViteConfig = (cwd) => {
1240
- for (const candidate of VITE_CONFIG_CANDIDATES) {
1241
- const full = join$1(cwd, candidate);
1242
- if (existsSync(full)) {
1243
- return full;
1244
- }
1245
- }
1246
- return void 0;
1247
- };
1248
- const patchOrCreateViteConfig = (cwd, framework, logger) => {
1249
- const viteConfigPath = findExistingViteConfig(cwd);
1250
- if (viteConfigPath === void 0) {
1251
- if (framework === "sveltekit" || framework === "nuxt" || framework === "astro") {
1252
- logger.info(`no Vite config found — ${framework} wires Lunora through its server entry (see next steps)`);
1253
- return { code: 0, files: [], target: cwd };
1254
- }
1255
- return createMinimalViteConfig(cwd, logger);
1256
- }
1257
- return patchExistingViteConfig(viteConfigPath, cwd, logger);
1258
- };
1259
- const runInPlaceInit = (cwd, logger) => {
1260
- const detection = detectFramework(cwd);
1261
- const viteResult = patchOrCreateViteConfig(cwd, detection.framework, logger);
1262
- if (viteResult.code !== 0) {
1263
- return viteResult;
1264
- }
1265
- const scaffolded = scaffoldLunoraDirectory(cwd, logger);
1266
- printFrameworkNextSteps(detection, logger);
1267
- return { code: 0, files: [...viteResult.files, ...scaffolded], target: cwd };
1268
- };
1269
- const offerIsInteractive = (options) => options.yes !== true && (options.prompt !== void 0 || (options.interactive ?? isInteractive()));
1270
- const maybeOfferExtras = async (options, projectDirectory) => {
1271
- const interactive = offerIsInteractive(options);
1272
- const preselected = options.add === void 0 ? [] : parseFeatureList(options.add, (message) => {
1273
- options.logger.warn(message);
1274
- });
1275
- const applyAll = async (plans) => {
1276
- if (plans.length === 0) {
1277
- return true;
1278
- }
1279
- if (options.dryRun === true) {
1280
- logWould(options.logger, `add ${plans.map((plan) => plan.label).join(", ")}`);
1281
- return true;
1282
- }
1283
- const buffered = [];
1284
- const applyLogger = isInteractive() ? {
1285
- error: (message) => {
1286
- buffered.push({ level: "error", message });
1287
- },
1288
- info: () => {
1289
- },
1290
- success: () => {
1291
- },
1292
- warn: (message) => {
1293
- buffered.push({ level: "warn", message });
1294
- }
1295
- } : options.logger;
1296
- const steps = plans.map((plan) => {
1297
- return {
1298
- running: `adding ${plan.label}…`,
1299
- task: () => runAddCommand({
1300
- allowUnsafeSource: options.allowUnsafeSource,
1301
- cwd: projectDirectory,
1302
- from: options.registryFrom,
1303
- logger: applyLogger,
1304
- names: [...plan.names],
1305
- ref: options.ref,
1306
- source: options.registrySource,
1307
- transformManifest: plan.transformManifest,
1308
- yes: true
1309
- })
1310
- };
1311
- });
1312
- const done = `added ${plans.map((plan) => plan.label).join(", ")}`;
1313
- const results = await withTuiBadgeProgress(BADGES.add, steps, done);
1314
- for (const { level, message } of buffered) {
1315
- options.logger[level](message);
1316
- }
1317
- return results.every((result) => result.code === 0);
1318
- };
1319
- const deps = {
1320
- applyAll,
1321
- interactive,
1322
- logger: options.logger,
1323
- multiSelect: options.prompt?.multiSelect ?? ((message, choices, settings) => tuiMultiSelect(message, choices, { ...settings, badge: BADGES.add })),
1324
- preselected: preselected.length > 0 ? preselected : void 0,
1325
- projectName: basename(projectDirectory),
1326
- select: options.prompt?.select ?? ((message, choices, settings) => tuiSelect(message, choices, { ...settings, badge: BADGES.add })),
1327
- text: options.prompt?.text ?? ((message, settings) => tuiText(message, { ...settings, badge: BADGES.add }))
1328
- };
1329
- if (preselected.length > 0) {
1330
- await offerRegistryExtras(deps);
1331
- return;
1332
- }
1333
- if (isInteractive()) {
1334
- await tuiHeadline(COPY.extras);
1335
- }
1336
- await offerRegistryExtras(deps);
1337
- };
1338
- const DEFAULT_FRAMEWORK = "react";
1339
- const FRAMEWORK_CHOICES = [
1340
- { description: "React SPA — official create-vite base + the Lunora layer (the default)", label: "React", value: "react" },
1341
- { description: "Vue SPA — create-vite base + Lunora", label: "Vue", value: "vue" },
1342
- { description: "Solid SPA — create-vite base + Lunora", label: "Solid", value: "solid" },
1343
- { description: "Svelte SPA — create-vite base + Lunora", label: "Svelte", value: "svelte" },
1344
- { description: "TanStack Start (React) — SSR with live-loader routes", label: "TanStack Start · React", value: "tanstack-start-react" },
1345
- { description: "TanStack Start (Solid)", label: "TanStack Start · Solid", value: "tanstack-start-solid" },
1346
- { description: "React Router (v7, framework mode) — SSR composed into the Lunora worker", label: "React Router", value: "react-router" },
1347
- { description: "Astro + a standalone Lunora worker", label: "Astro", value: "astro" },
1348
- { description: "AnalogJS (Angular) — single-worker, Lunora mounted in Nitro", label: "Analog", value: "analog" },
1349
- { description: "Nuxt (Vue) — single-worker, Lunora mounted in Nitro", label: "Nuxt", value: "nuxt" },
1350
- { description: "SvelteKit + a standalone Lunora worker", label: "SvelteKit", value: "sveltekit" },
1351
- { description: "Worker only — no frontend", label: "Standalone", value: "standalone" }
1352
- ];
1353
- const OVERLAY_VALUES = Object.keys(ADAPTERS).join("|");
1354
- const TEMPLATE_VALUES = FRAMEWORK_CHOICES.filter((choice) => !isOverlayFramework(choice.value)).map((choice) => choice.value).join("|");
1355
- const toScaffoldChoice = (value) => isOverlayFramework(value) ? { framework: value, kind: "overlay" } : { kind: "template", templateType: value };
1356
- const resolveScaffoldChoice = async (options) => {
1357
- if (options.vite !== void 0) {
1358
- return { framework: options.vite, kind: "overlay" };
1359
- }
1360
- if (options.templateType !== void 0) {
1361
- return { kind: "template", templateType: options.templateType };
1362
- }
1363
- if (!isInteractive() || options.yes === true) {
1364
- return { framework: DEFAULT_FRAMEWORK, kind: "overlay" };
1365
- }
1366
- return toScaffoldChoice(await tuiSelect(COPY.framework, FRAMEWORK_CHOICES, { badge: BADGES.tmpl, default: DEFAULT_FRAMEWORK }) ?? DEFAULT_FRAMEWORK);
1367
- };
1368
- const nonInteractiveInitError = (options) => {
1369
- if (isInteractive() || options.yes === true) {
1370
- return void 0;
1371
- }
1372
- const missing = [];
1373
- if (options.name === void 0) {
1374
- missing.push("a project name (`lunora init <name>`)");
1375
- }
1376
- if (options.templateType === void 0 && options.vite === void 0) {
1377
- missing.push(`a framework — \`--vite <${OVERLAY_VALUES}>\` for an SPA, or \`-t <${TEMPLATE_VALUES}>\` for a bespoke template`);
1378
- }
1379
- if (missing.length === 0) {
1380
- return void 0;
1381
- }
1382
- return `lunora init can't prompt in a non-interactive terminal — provide ${missing.join(" and ")}, or pass --yes to accept the defaults.`;
1383
- };
1384
- const scaffoldOverlayPath = async (options, framework, name, target) => {
1385
- if (!isOverlayFramework(framework)) {
1386
- options.logger.error(`init: unknown framework "${framework}". Supported overlays: ${Object.keys(ADAPTERS).join(", ")}.`);
1387
- return { code: 1, files: [], target };
1388
- }
1389
- if (!await verifyRemoteTemplate({ isLocal: options.overlayBaseFrom !== void 0, logger: options.logger })) {
1390
- return { code: 1, files: [], target };
1391
- }
1392
- mkdirSync(target, { recursive: true });
1393
- return scaffoldViteOverlay({ framework, logger: options.logger, name, overlayBaseFrom: options.overlayBaseFrom, target });
1394
- };
1395
- const scaffoldTemplatePath = async (options, templateType, name, target) => {
1396
- if (templateType === "next") {
1397
- options.logger.warn('template "next" is not yet available — re-run with `--vite react` or `-t standalone`.');
1398
- return { code: 1, files: [], target };
1399
- }
1400
- if (options.from !== void 0) {
1401
- return await scaffoldFromLocal(options.from, templateType, target, name, options.logger);
1402
- }
1403
- if (options.source !== void 0 && options.source.length > 0 && !options.allowUnsafeSource && !isSafeSource(options.source)) {
1404
- options.logger.error(
1405
- `init: refusing --source ${options.source} — only gh:, github:, or https:// sources are allowed (and may not contain ".."). Re-run with --allow-unsafe-source if you really want this.`
1406
- );
1407
- return { code: 1, files: [], target };
1408
- }
1409
- if (!await verifyRemoteTemplate({ isLocal: false, logger: options.logger, source: resolveTemplateSource(templateType, options.source, options.ref) })) {
1410
- return { code: 1, files: [], target };
1411
- }
1412
- return scaffoldFromRemote({ logger: options.logger, name, ref: options.ref, source: options.source, target, templateType });
1413
- };
1414
- const scaffoldNewProject = async (options, cwd, recordTarget) => {
1415
- await tuiMoonrise("realtime backend on Cloudflare Workers + Durable Objects");
1416
- const blocked = nonInteractiveInitError(options);
1417
- if (blocked !== void 0) {
1418
- options.logger.error(blocked);
1419
- return { code: 1, files: [], target: "" };
1420
- }
1421
- const suggestedName = generateProjectName();
1422
- const name = options.name ?? await tuiText(COPY.name, { badge: BADGES.dir, default: suggestedName, placeholder: suggestedName });
1423
- const choice = await resolveScaffoldChoice(options);
1424
- if (name.includes("/") || name.includes("\\") || name === ".." || name === ".") {
1425
- options.logger.error(`init: refusing project name "${name}" — must not contain path separators or be "." / "..".`);
1426
- return { code: 1, files: [], target: "" };
1427
- }
1428
- const target = resolve(cwd, name);
1429
- const targetPreExisted = existsSync(target);
1430
- if (targetPreExisted) {
1431
- const entries = readdirSync(target);
1432
- if (entries.length > 0) {
1433
- options.logger.error(`target directory not empty: ${target}`);
1434
- return { code: 1, files: [], target };
1435
- }
1436
- }
1437
- if (options.dryRun === true) {
1438
- const what = choice.kind === "overlay" ? `the ${choice.framework} create-vite overlay` : `the ${choice.templateType} template`;
1439
- logWould(options.logger, `scaffold ${what} into ${target}`);
1440
- return { code: 0, files: [], target };
1441
- }
1442
- recordTarget(target, targetPreExisted);
1443
- return choice.kind === "overlay" ? scaffoldOverlayPath(options, choice.framework, name, target) : scaffoldTemplatePath(options, choice.templateType, name, target);
1444
- };
1445
- const resetScaffoldOnCancel = (cleanup, logger) => {
1446
- const { target, targetPreExisted } = cleanup;
1447
- if (target === void 0 || !existsSync(target)) {
1448
- return;
1449
- }
1450
- if (targetPreExisted === true) {
1451
- for (const entry of readdirSync(target)) {
1452
- rmSync(join$1(target, entry), { force: true, recursive: true });
1453
- }
1454
- } else {
1455
- rmSync(target, { force: true, recursive: true });
1456
- }
1457
- logger.info(`removed the partially-created project at ${target}`);
1458
- };
1459
- const runScaffoldStep = async (options, cwd, recordTarget) => {
1460
- if (options.inPlace !== true) {
1461
- return scaffoldNewProject(options, cwd, recordTarget);
1462
- }
1463
- if (options.dryRun === true) {
1464
- logWould(options.logger, `configure Lunora into ${cwd}`);
1465
- return { code: 0, files: [], target: cwd };
1466
- }
1467
- return runInPlaceInit(cwd, options.logger);
1468
- };
1469
- const runPostScaffold = async (options, result, cwd) => {
1470
- await maybeOfferExtras(options, result.target);
1471
- const installedManager = options.inPlace === true ? void 0 : await maybeOfferInstall(options, result.target);
1472
- if (options.inPlace !== true) {
1473
- await maybeOfferGit(options, result.target);
1474
- await printNextSteps(basename(result.target), installedManager, isInsideMonorepo(cwd));
1475
- await emitMascot(options.logger);
1476
- }
1477
- };
1478
- const scaffoldCiPipeline = (options, result, cwd) => {
1479
- if (result.code !== 0 || options.ci === void 0) {
1480
- return;
1481
- }
1482
- if (options.dryRun === true) {
1483
- logWould(options.logger, `scaffold a ${options.ci} CI deploy pipeline`);
1484
- return;
1485
- }
1486
- scaffoldCiWorkflow(options.inPlace === true ? cwd : result.target, options.ci, options.logger);
1487
- };
1488
- const runInitCommand = async (options) => {
1489
- const cwd = options.cwd ?? process.cwd();
1490
- const cleanup = {};
1491
- let result;
1492
- try {
1493
- result = await runScaffoldStep(options, cwd, (target, preExisted) => {
1494
- cleanup.target = target;
1495
- cleanup.targetPreExisted = preExisted;
1496
- });
1497
- if (result.code === 0 && result.target !== "") {
1498
- cleanup.target = void 0;
1499
- await runPostScaffold(options, result, cwd);
1500
- }
1501
- } catch (error) {
1502
- if (error instanceof PromptCancelledError) {
1503
- resetScaffoldOnCancel(cleanup, options.logger);
1504
- process.stdout.write("\n ✖ Setup cancelled — run `lunora init` again whenever you're ready. 🌙\n");
1505
- return { code: 130, files: [], target: "" };
1506
- }
1507
- throw error;
1508
- }
1509
- scaffoldCiPipeline(options, result, cwd);
1510
- return result;
1511
- };
1512
- const isTemplate = (value) => value === "analog" || value === "astro" || value === "next" || value === "nuxt" || value === "react-router" || value === "standalone" || value === "sveltekit" || value === "tanstack-start-react" || value === "tanstack-start-solid";
1513
- const resolveCiProvider = (raw, logger) => {
1514
- if (raw === void 0) {
1515
- return void 0;
1516
- }
1517
- if (isCiProvider(raw)) {
1518
- return raw;
1519
- }
1520
- logger.warn(`init: unknown --ci "${raw}" — expected github | gitlab; skipping CI scaffold.`);
1521
- return void 0;
1522
- };
1523
- const execute = defineHandler(({ argument, cwd, logger, options }) => {
1524
- const templateType = options.template !== void 0 && isTemplate(options.template) ? options.template : void 0;
1525
- return runInitCommand({
1526
- add: options.add,
1527
- allowUnsafeSource: options.allowUnsafeSource === true,
1528
- cwd,
1529
- ci: resolveCiProvider(options.ci, logger),
1530
- dryRun: options.dryRun === true,
1531
- from: options.from,
1532
- inPlace: options.here === true,
1533
- interactive: options.interactive === true ? true : void 0,
1534
- logger,
1535
- name: argument[0],
1536
- ref: options.ref,
1537
- source: options.source,
1538
- templateType,
1539
- vite: options.vite,
1540
- yes: options.yes === true
1541
- });
1542
- });
1543
-
1544
- export { execute, isTemplate, resolveTemplateSource, runInitCommand };
1224
+ `,Na="gh:anolilab/lunora/templates",Ia=e=>{const t=e.lastIndexOf(".");return t===-1?!1:La.has(e.slice(t))},_a=(e,t)=>e.replaceAll("{{name}}",t),$a=async(e,t)=>{const a=new Set;for(const r of e)if(E(r)==="package.json")try{const o=JSON.parse(b(r,"utf8"));for(const s of["dependencies","devDependencies"])for(const n of Object.keys(o[s]??{}))P(n)&&a.add(n)}catch{}return ce(a,t)},Ra=(e,t,a)=>{let r;try{r=JSON.parse(e)}catch{return e}let o=e;for(const s of["dependencies","devDependencies"])for(const n of Object.keys(r[s]??{})){if(!P(n))continue;const i=a.get(n)??t,l=We(o,[s,n],i,{formattingOptions:{insertSpaces:!0,tabSize:4}});o=ze(o,l)}return o},Oa=["@parcel/watcher","esbuild","lmdb","msgpackr-extract","rs-module-lexer","sharp","unrs-resolver","vue-demi","workerd"],Ta=["cpu-features","protobufjs","ssh2"],Ae="pnpm-workspace.yaml",Pa=()=>["# pnpm reads its settings from here (the package.json `pnpm` field is no longer read).","# Pre-approve the toolchain's native build scripts so `pnpm install` runs them","# without the interactive `pnpm approve-builds` step; deny the optional native","# builds a scaffold doesn't need (so no C/C++ toolchain is required).","allowBuilds:",...Oa.map(e=>` '${e}': true`),...Ta.map(e=>` '${e}': false`),""].join(`
1225
+ `),q=e=>{const t=[];for(const a of Fe(e,{includeDirs:!1,includeFiles:!0}))Oe(a.path).isSymbolicLink()||t.push(a.path);return t},Ee=async(e,t,a)=>{const r=q(e),o=[],s=de(),n=await $a(r,s);for(const i of r){const l=He(e,i),d=u(t,l);M(A(d),{recursive:!0});const c=b(i);let p=Ia(i)?_a(c.toString("utf8"),a):void 0;p!==void 0&&E(i)==="package.json"&&(p=Ra(p,s,n)),p===void 0?v(d,c):v(d,p,"utf8"),o.push(d)}return o},B=(e,t,a)=>t!==void 0&&t.length>0?t:`${Na}/${e}#${ue(a)}`,Da=e=>e.includes("..")?!1:e.startsWith("gh:")||e.startsWith("github:")||e.startsWith("https://"),S=(e,t)=>{e.info(`[dry-run] would ${t}`)},K=(e,t,a)=>{g()&&process.stdout.write(`
1226
+ `),e.success(`scaffolded ${String(t.length)} files into ${a}`)},Ba=(e,t)=>{const{args:a,command:r}=Je(e,t);return`${r} ${a.join(" ")}`},Ne=(e,t)=>{let a=ne(e);for(;;){if(t(a))return!0;const r=A(a);if(r===a)return!1;a=r}},ja=e=>{if(m(u(e,Ae)))return!0;const t=u(e,"package.json");if(!m(t))return!1;try{return JSON.parse(b(t,"utf8")).workspaces!==void 0}catch{return!1}},Ie=e=>Ne(e,ja),Va=e=>Ne(e,t=>m(u(t,".git"))),Ua=async(e,t)=>{if(e.yes===!0||!g()||Va(A(t)))return;if(!await fe(y.git,{badge:f.git,defaultYes:!1})){await ve("Sounds good! You can always run git init manually.");return}if(e.dryRun===!0){S(e.logger,"initialize a git repository");return}const a=e.spawner??pe;(await st("Initializing a git repository…",()=>a({args:["init"],command:"git",cwd:t}))).code===0?await R("git","Initialized an empty git repository."):e.logger.warn("`git init` failed — initialize it yourself later with `git init`.")},Fa=async(e,t,a,r)=>{const o=[{code:`cd ./${e}`,lead:"Enter your project directory using"}];t===void 0&&o.push({code:`${a} install`,lead:"Install dependencies with",tail:r?" from the workspace root":void 0}),o.push({code:Ye(a,"dev"),lead:"Run",tail:" to start the dev server."},{code:"lunora add",lead:"Add features like auth or storage using"});const s=[{code:"https://lunora.sh/docs",lead:"Read the docs at"},{code:"https://lunora.sh/chat",lead:"Stuck? Join the chat at"}];if(g()){await nt(f.next,y.nextHeader,o,s);return}const n=o.map(i=>`${i.lead} ${i.code}${i.tail??""}`);n.push("",...s.map(i=>`${i.lead} ${i.code}${i.tail??""}`)),await R("next",y.nextHeader,n.join(`
1227
+ `))},Ha=e=>e.yes!==!0&&(e.installPrompt!==void 0||g()),Wa=async(e,t)=>{if(!Ha(e)||Ie(A(t)))return;const a=Ge(e.packageManagerProbe),[r]=a;if(r===void 0)return;if(!await(e.installPrompt?.confirmInstall??(async()=>fe(y.install,{badge:f.deps,defaultYes:!0})))()){await ve("No problem! Remember to install dependencies after setup.");return}let s=r;if(a.length>1&&(s=e.installPrompt?await e.installPrompt.selectManager(a):await H(y.packageManager,a.map(c=>({label:c,value:c})),{badge:f.deps,default:r})??r),e.dryRun===!0){S(e.logger,`install dependencies with ${s}`);return}if(s==="pnpm"){const c=u(t,Ae);m(c)||v(c,Pa(),"utf8")}const n=e.spawner??pe,{args:i,command:l}=le(s);await R("deps",`Installing dependencies with ${s}…`);const d=await n({args:i,command:l,cwd:t});if(d.code!==0){e.logger.warn(`\`${l} install\` exited with code ${String(d.code)} — run it yourself in ${E(t)}/.`);return}return await R("deps",`Dependencies installed with ${s}.`),s},za=async(e,t,a,r,o)=>{const s=u(e,t);if(!m(s))return o.error(`template not found in local source: ${s}`),{code:1,files:[],target:a};const n=await Ee(s,a,r);return K(o,n,a),{code:0,files:n,target:a}},qa=async e=>{const{logger:t,name:a,ref:r,source:o,target:s,templateType:n}=e,i=oe(u(se(),"lunora-init-fetch-")),l=u(i,"template");try{const d=o!==void 0&&o.length>0?r:await et(r,t),c=B(n,o,d);let p,h=[];await ge([{label:`${n} template fetched`,run:async()=>{p=await ie(c,{cwd:i,dir:l,force:!0,install:!1,silent:!0})}},{label:`files copied into ${a}/`,run:async()=>{h=await Ee(l,s,a)}}],{end:"Project initialized!",start:"Project initializing…"});const I=q(l);return g()&&process.stdout.write(`
1228
+ `),t.info(p?.commit?`template: ${p.source} @ ${p.commit} (${String(I.length)} files)`:`template: ${p?.source??c} (${String(I.length)} files)`),K(t,h,s),{code:0,files:h,target:s}}catch(d){if(d instanceof F)throw d;const{hints:c,message:p}=Pt(d,{ref:ue(r),remote:B(n,o,r),templateType:n});t.error(p);for(const h of c)t.warn(h);return{code:1,files:[],target:s}}finally{$(i,{force:!0,recursive:!0})}},Ka=e=>{for(const t of["_gitignore","_npmrc","_gitattributes"]){const a=u(e,t);m(a)&&Re(a,u(e,`.${t.slice(1)}`))}},Ga=async e=>{const{framework:t,logger:a,name:r,overlayBaseFrom:o,target:s}=e,n=T[t],i=oe(u(se(),"lunora-vite-base-"));try{let l;if(o!==void 0&&(l=u(o,`template-${n.createViteTemplate}`),!m(l)))return a.error(`create-vite base not found on disk: ${l}`),{code:1,files:[],target:s};const d=async()=>{if(l!==void 0){G(l,s,{recursive:!0});return}const p=u(i,"base"),h=`github:vitejs/vite/packages/create-vite/template-${n.createViteTemplate}#main`;await ie(h,{cwd:i,dir:p,force:!0,install:!1,silent:!0}),Ka(p),G(p,s,{recursive:!0})};let c=[];return await ge([{label:`create-vite (${n.label}) base ready`,run:d},{label:`Lunora overlay applied (${n.label})`,run:async()=>{c=await wa({adapter:n,distTag:de(),logger:a,name:r,target:s})}}],{end:"Project initialized!",start:"Project initializing…"}),K(a,c,s),{code:0,files:[...q(s)],target:s}}catch(l){if(l instanceof F)throw l;const d=l instanceof Error?l.message:String(l);return a.error(`failed to scaffold the ${n.label} base: ${d}`),{code:1,files:[],target:s}}finally{$(i,{force:!0,recursive:!0})}},j=(e,t,a,r,o)=>(o.error(`init --in-place: could not ${e} ${t}: ${a instanceof Error?a.message:String(a)}`),{code:1,files:[],target:r}),Ja=(e,t)=>{const a=u(e,"vite.config.ts");try{v(a,Ma,"utf8")}catch(r){return j("write",a,r,e,t)}return t.success(`created ${a} with lunora() plugin`),{code:0,files:[a],target:e}},Ya=(e,t,a)=>{let r;try{r=b(e,"utf8")}catch(s){return j("read",e,s,t,a)}const o=ke(r);if(!o.changed)return a.info(`${e}: ${o.reason??"no changes needed"}`),{code:0,files:[],target:t};try{v(e,o.code,"utf8")}catch(s){return j("write",e,s,t,a)}return a.success(`patched ${e} — added lunora() plugin`),{code:0,files:[e],target:t}},Xa=(e,t)=>{const a=u(e,"lunora"),r=u(a,"schema.ts");if(m(r))return t.info(`lunora/ already present — left ${r} untouched`),[];const o=[];try{M(a,{recursive:!0}),v(r,Aa,"utf8"),o.push(r);const s=u(a,"messages.ts");m(s)||(v(s,Ea,"utf8"),o.push(s)),t.success(`scaffolded lunora/ (${String(o.length)} file(s))`)}catch(s){const n=s instanceof Error?s.message:String(s);t.error(`init --here: could not scaffold lunora/: ${n}`)}return o},Qa=(e,t,a)=>{const{adapter:r,class:o,framework:s}=e;a.info(""),a.info(`detected framework: ${s} (class ${o})`),a.info("next steps:"),a.info(` 1. install the adapter: ${Ba(t,[r,"@lunora/client","@lunora/runtime","@lunora/server"])}`),a.info(" 2. run codegen: lunora codegen"),o==="A"?(a.info(" 3. compose one worker: wrap your worker entry with"),a.info(" createWorker({ httpRouter: <your framework SSR handler>, shardDO: ShardDO, ... })"),a.info(` 4. add the provider: mount the ${r} provider in your root layout/route`),a.info(" 5. make a loader live: preloadQuery() in a loader, usePreloadedQuery() in the component"),a.info(" see https://lunora.sh/docs/frameworks/reactive-loaders")):o==="B"?(a.info(" 3. inject Lunora: mount Lunora realtime under /_lunora/* in your server hook"),a.info(` (${s} owns its Cloudflare adapter — Lunora composes into its server entry)`),a.info(` 4. add the provider: mount the ${r} provider in your root layout`),a.info(" 5. read the guide: https://lunora.sh/docs/frameworks/deploy")):(a.info(" 3. add the provider: wrap your app with the LunoraProvider from @lunora/react"),a.info(" 4. read the guide: https://lunora.sh/docs/frameworks/bring-your-framework")),a.info("")},Za=(e,t,a)=>{const r=Se(e);return r===void 0?t==="sveltekit"||t==="nuxt"||t==="astro"?(a.info(`no Vite config found — ${t} wires Lunora through its server entry (see next steps)`),{code:0,files:[],target:e}):Ja(e,a):Ya(r,e,a)},er=(e,t)=>{const a=Lt(e),r=Za(e,a.framework,t);if(r.code!==0)return r;const o=Xa(e,t);return Qa(a,U(e),t),{code:0,files:[...r.files,...o],target:e}},tr=e=>e.yes!==!0&&(e.prompt!==void 0||(e.interactive??g())),ae=async(e,t,a)=>{a.dryRun!==!0&&await Kt({apply:r=>Ue(e,r),detected:Ve(e),interactive:t,logger:a.logger,multiSelect:a.lintPrompt??((r,o,s)=>me(r,o,{...s,badge:f.add}))})},ar=async(e,t)=>{const a=tr(e),r=e.add===void 0?[]:jt(e.add,n=>{e.logger.warn(n)}),s={applyAll:async n=>{if(n.length===0)return!0;if(e.dryRun===!0)return S(e.logger,`add ${n.map(h=>h.label).join(", ")}`),!0;const i=[],l=g()?{error:h=>{i.push({level:"error",message:h})},info:()=>{},success:()=>{},warn:h=>{i.push({level:"warn",message:h})}}:e.logger,d=n.map(h=>({running:`adding ${h.label}…`,task:()=>gt({allowUnsafeSource:e.allowUnsafeSource,cwd:t,from:e.registryFrom,logger:l,names:[...h.names],ref:e.ref,source:e.registrySource,transformManifest:h.transformManifest,yes:!0})})),c=`added ${n.map(h=>h.label).join(", ")}`,p=await it(f.add,d,c);for(const{level:h,message:I}of i)e.logger[h](I);return p.every(h=>h.code===0)},interactive:a,logger:e.logger,multiSelect:e.prompt?.multiSelect??((n,i,l)=>me(n,i,{...l,badge:f.add})),preselected:r.length>0?r:void 0,projectName:E(t),resolveAuthUiItem:()=>{try{const n=JSON.parse(b(u(t,"package.json"),"utf8"));return ft({...n.dependencies,...n.devDependencies})??"auth-ui-react"}catch{return"auth-ui-react"}},select:e.prompt?.select??((n,i,l)=>H(n,i,{...l,badge:f.add})),text:e.prompt?.text??((n,i)=>he(n,{...i,badge:f.add}))};if(r.length>0){await Z(s),await ae(t,a,e);return}g()&&await ot(y.extras),await Z(s),await ae(t,a,e)},D="react",_e=[{description:"React SPA — official create-vite base + the Lunora layer (the default)",label:"React",value:"react"},{description:"Vue SPA — create-vite base + Lunora",label:"Vue",value:"vue"},{description:"Solid SPA — create-vite base + Lunora",label:"Solid",value:"solid"},{description:"Solid 2.0 SPA — the Solid 2 line (@solidjs/web, vite-plugin-solid 3)",label:"Solid 2",value:"solid-v2"},{description:"Svelte SPA — create-vite base + Lunora",label:"Svelte",value:"svelte"},{description:"Next.js (App Router) — OpenNext on Cloudflare + a standalone Lunora worker",label:"Next.js",value:"next"},{description:"TanStack Start (React) — SSR with live-loader routes",label:"TanStack Start · React",value:"tanstack-start-react"},{description:"TanStack Start (Solid)",label:"TanStack Start · Solid",value:"tanstack-start-solid"},{description:"Next.js App Router on Vite (vinext) — composed into the Lunora worker (experimental)",label:"vinext · App Router",value:"vinext"},{description:"Next.js Pages Router on Vite (vinext) — composed into one worker (experimental)",label:"vinext · Pages Router",value:"vinext-pages"},{description:"React Router (v7, framework mode) — SSR composed into the Lunora worker",label:"React Router",value:"react-router"},{description:"Astro + a standalone Lunora worker",label:"Astro",value:"astro"},{description:"AnalogJS (Angular) — single-worker, Lunora mounted in Nitro",label:"Analog",value:"analog"},{description:"Nuxt (Vue) — single-worker, Lunora mounted in Nitro",label:"Nuxt",value:"nuxt"},{description:"SvelteKit + a standalone Lunora worker",label:"SvelteKit",value:"sveltekit"},{description:"React Native (Expo) — an iOS/Android/web app + a Lunora worker backend",label:"React Native · Expo",value:"expo"},{description:"Worker only — no frontend",label:"Standalone",value:"standalone"}],rr=Object.keys(T).join("|"),$e=_e.filter(e=>!z(e.value)).map(e=>e.value),or=$e.join("|"),sr=e=>z(e)?{framework:e,kind:"overlay"}:{kind:"template",templateType:e},nr=async e=>e.vite!==void 0?{framework:e.vite,kind:"overlay"}:e.templateType!==void 0?{kind:"template",templateType:e.templateType}:!g()||e.yes===!0?{framework:D,kind:"overlay"}:sr(await H(y.framework,_e,{badge:f.tmpl,default:D})??D),ir=e=>{if(g()||e.yes===!0)return;const t=[];if(e.name===void 0&&t.push("a project name (`lunora init <name>`)"),e.templateType===void 0&&e.vite===void 0&&t.push(`a framework — \`--vite <${rr}>\` for an SPA, or \`-t <${or}>\` for a bespoke template`),t.length!==0)return`lunora init can't prompt in a non-interactive terminal — provide ${t.join(" and ")}, or pass --yes to accept the defaults.`},lr=async(e,t,a,r)=>z(t)?await Me({isLocal:e.overlayBaseFrom!==void 0,logger:e.logger})?(M(r,{recursive:!0}),Ga({framework:t,logger:e.logger,name:a,overlayBaseFrom:e.overlayBaseFrom,target:r})):{code:1,files:[],target:r}:(e.logger.error(`init: unknown framework "${t}". Supported overlays: ${Object.keys(T).join(", ")}.`),{code:1,files:[],target:r}),cr=async(e,t,a,r)=>e.from!==void 0?await za(e.from,t,r,a,e.logger):e.source!==void 0&&e.source.length>0&&!e.allowUnsafeSource&&!Da(e.source)?(e.logger.error(`init: refusing --source ${e.source} — only gh:, github:, or https:// sources are allowed (and may not contain ".."). Re-run with --allow-unsafe-source if you really want this.`),{code:1,files:[],target:r}):await Me({isLocal:!1,logger:e.logger,source:B(t,e.source,e.ref)})?qa({logger:e.logger,name:a,ref:e.ref,source:e.source,target:r,templateType:t}):{code:1,files:[],target:r},dr=async(e,t,a)=>{await rt("realtime backend on Cloudflare Workers + Durable Objects");const r=ir(e);if(r!==void 0)return e.logger.error(r),{code:1,files:[],target:""};const o=xa(),s=e.name??await he(y.name,{badge:f.dir,default:o,placeholder:o}),n=await nr(e),i=s.trim();if(i.length===0)return e.logger.error("init: refusing an empty project name — pass a directory name (e.g. `lunora init my-app`)."),{code:1,files:[],target:""};if(i.includes("/")||i.includes("\\")||i===".."||i===".")return e.logger.error(`init: refusing project name "${i}" — must not contain path separators or be "." / "..".`),{code:1,files:[],target:""};const l=ne(t,i),d=m(l);if(d&&re(l).length>0)return e.logger.error(`target directory not empty: ${l}`),{code:1,files:[],target:l};if(e.dryRun===!0){const c=n.kind==="overlay"?`the ${n.framework} create-vite overlay`:`the ${n.templateType} template`;return S(e.logger,`scaffold ${c} into ${l}`),{code:0,files:[],target:l}}return a(l,d),n.kind==="overlay"?lr(e,n.framework,i,l):cr(e,n.templateType,i,l)},ur=(e,t)=>{const{target:a,targetPreExisted:r}=e;if(!(a===void 0||!m(a))){if(r===!0)for(const o of re(a))$(u(a,o),{force:!0,recursive:!0});else $(a,{force:!0,recursive:!0});t.info(`removed the partially-created project at ${a}`)}},pr=async(e,t,a)=>e.inPlace!==!0?dr(e,t,a):e.dryRun===!0?(S(e.logger,`configure Lunora into ${t}`),{code:0,files:[],target:t}):er(t,e.logger),hr=async(e,t,a)=>{await ar(e,t.target);const r=e.inPlace===!0?void 0:await Wa(e,t.target);if(e.inPlace!==!0){await Ua(e,t.target);const o=r??U(t.target);await Fa(E(t.target),r,o,Ie(a)),await Dt(e.logger)}},mr=(e,t,a)=>{if(t.code!==0||e.ci===void 0)return;if(e.dryRun===!0){S(e.logger,`scaffold a ${e.ci} CI deploy pipeline`);return}const r=e.inPlace===!0?a:t.target;try{const o=U(r);Ct(r,e.ci,o,e.logger)}catch{e.logger.warn(`--ci ${e.ci}: could not detect a package manager for this project — skipped the CI pipeline.`)}},fr=async e=>{const t=e.cwd??process.cwd(),a={};let r;try{r=await pr(e,t,(o,s)=>{a.target=o,a.targetPreExisted=s}),r.code===0&&r.target!==""&&(a.target=void 0,await hr(e,r,t))}catch(o){if(o instanceof F)return ur(a,e.logger),process.stdout.write("\n ✖ Setup cancelled — run `lunora init` again whenever you're ready. 🌙\n"),{code:130,files:[],target:""};throw o}return mr(e,r,t),r},vr=e=>typeof e=="string"&&$e.includes(e),gr=(e,t)=>{if(e!==void 0){if(xt(e))return e;t.warn(`init: unknown --ci "${e}" — expected github | gitlab; skipping CI scaffold.`)}},Br=Xe(({argument:e,cwd:t,logger:a,options:r})=>{const o=r.template!==void 0&&vr(r.template)?r.template:void 0;return fr({add:r.add,allowUnsafeSource:r.allowUnsafeSource===!0,cwd:t,ci:gr(r.ci,a),dryRun:r.dryRun===!0,from:r.from,inPlace:r.here===!0,interactive:r.interactive===!0?!0:void 0,logger:a,name:e[0],ref:r.ref,source:r.source,templateType:o,vite:r.vite,yes:r.yes===!0})});export{Br as execute,vr as isTemplate,B as resolveTemplateSource,fr as runInitCommand};