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

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 (110) 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 +731 -341
  6. package/dist/index.d.ts +731 -341
  7. package/dist/index.mjs +1 -19
  8. package/dist/packem_chunks/handler.mjs +1 -150
  9. package/dist/packem_chunks/handler10.mjs +4 -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 +1 -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 +118 -1383
  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-BKhYrmpZ.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/binding-manifest-file-CQ1eQYy1.mjs +2 -0
  48. package/dist/packem_shared/buildRegistryIndex-Zi3bBqpc.mjs +1 -0
  49. package/dist/packem_shared/cli-CrC0a7dH.mjs +3 -0
  50. package/dist/packem_shared/codegen-error-AmH54ofi.mjs +3 -0
  51. package/dist/packem_shared/command-DwC11Cwe.mjs +1 -0
  52. package/dist/packem_shared/commands-BNKj7r1R.mjs +19 -0
  53. package/dist/packem_shared/createLogger-hGafwf-3.mjs +2 -0
  54. package/dist/packem_shared/createRecordingSpawner-DJlNacZ6.mjs +1 -0
  55. package/dist/packem_shared/deploy-target-D9GPy_tq.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/import-CrVGrOt3.mjs +12 -0
  59. package/dist/packem_shared/insertSchemaExtension-DY4pA8wE.mjs +8 -0
  60. package/dist/packem_shared/lint-ignore-report-DKZagpqk.mjs +2 -0
  61. package/dist/packem_shared/open-url-EnKy--w-.mjs +1 -0
  62. package/dist/packem_shared/output-format-DfogXx0p.mjs +2 -0
  63. package/dist/packem_shared/parseManifest-CwPTKdtS.mjs +1 -0
  64. package/dist/packem_shared/path-containment-CgxYZggb.mjs +1 -0
  65. package/dist/packem_shared/platform-diagnostics-uOXqysk3.mjs +4 -0
  66. package/dist/packem_shared/prompt-cancelled-C8Sj7OqI.mjs +1 -0
  67. package/dist/packem_shared/resolve-DZAGzg67.mjs +1 -0
  68. package/dist/packem_shared/resolve-target-BRvw8Pf7.mjs +1 -0
  69. package/dist/packem_shared/runAddCommand-D1Dj8-pK.mjs +1 -0
  70. package/dist/packem_shared/runExportCommand-DmXKEWSq.mjs +5 -0
  71. package/dist/packem_shared/schema-drift-gate-DARCKocg.mjs +1 -0
  72. package/dist/packem_shared/schemaIrToSnapshot-qpRoV7HY.mjs +1 -0
  73. package/dist/packem_shared/shared-D-zCOmgY.mjs +1 -0
  74. package/dist/packem_shared/storage-wIUel5Az.mjs +1 -0
  75. package/dist/packem_shared/tui-prompts-Dd0pDuNr.mjs +4 -0
  76. package/dist/packem_shared/vectorize-metadata-DbziRKpX.mjs +1 -0
  77. package/dist/packem_shared/wrangler-name-Dsk5K1f-.mjs +1 -0
  78. package/dist/packem_shared/wrangler-secrets-CCdt0mUl.mjs +1 -0
  79. package/package.json +39 -17
  80. package/skills/README.md +35 -17
  81. package/skills/lunora/SKILL.md +65 -9
  82. package/skills/lunora-functions/SKILL.md +38 -3
  83. package/skills/lunora-migration-helper/SKILL.md +70 -17
  84. package/skills/lunora-performance-audit/SKILL.md +36 -6
  85. package/skills/lunora-quickstart/SKILL.md +90 -24
  86. package/skills/lunora-realtime/SKILL.md +58 -30
  87. package/dist/packem_shared/COMMANDS-D3h9Iwvl.mjs +0 -944
  88. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Ck-2bU08.mjs +0 -244
  89. package/dist/packem_shared/admin-url-4UzT-CI4.mjs +0 -19
  90. package/dist/packem_shared/api-spec-CtA6ilu4.mjs +0 -13
  91. package/dist/packem_shared/buildRegistryIndex-BcYe607_.mjs +0 -38
  92. package/dist/packem_shared/command-BC30oSBW.mjs +0 -14
  93. package/dist/packem_shared/commands-hl0mRqqg.mjs +0 -845
  94. package/dist/packem_shared/createLogger-B40gPzQo.mjs +0 -78
  95. package/dist/packem_shared/createRecordingSpawner-DxI3mebw.mjs +0 -43
  96. package/dist/packem_shared/detect-package-manager-DYp7n3mJ.mjs +0 -61
  97. package/dist/packem_shared/diffSnapshots-BeDvvNiF.mjs +0 -161
  98. package/dist/packem_shared/docker-hMQ97KSQ.mjs +0 -21
  99. package/dist/packem_shared/insertSchemaExtension-DAqbfr9Z.mjs +0 -64
  100. package/dist/packem_shared/open-url-Dfq6fAyT.mjs +0 -41
  101. package/dist/packem_shared/output-format-wUvAN6AL.mjs +0 -17
  102. package/dist/packem_shared/parseArgs-YXFuKdEk.mjs +0 -56
  103. package/dist/packem_shared/parseManifest--vZf2FY1.mjs +0 -94
  104. package/dist/packem_shared/resolve-target-qbsJ_5sF.mjs +0 -16
  105. package/dist/packem_shared/runAddCommand-vJdgiR5t.mjs +0 -4
  106. package/dist/packem_shared/schema-drift-gate-BtBt0as0.mjs +0 -79
  107. package/dist/packem_shared/schemaIrToSnapshot-DdsljJT-.mjs +0 -43
  108. package/dist/packem_shared/storage-B7hHSTZP.mjs +0 -84
  109. package/dist/packem_shared/tui-prompts-M6OWsuyw.mjs +0 -663
  110. 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{installArgsFor as ne,execArgsFor as Te,detectFramework as Pe,isInteractive as g,LUNA_ART as De,LUNA_NAME as Be,LUNA_SIGNOFF as je,BADGES as f,paintAnswer as Ve,detectPackageManager as V,detectInstalledManagers as Ue,runScriptCommand as Fe,detectLintTools as He,addArgsFor as We,applyLintIgnores as ze}from"@lunora/config";import{walkSync as qe}from"@visulima/fs";import{join as u,dirname as A,basename as E,resolve as ie,relative as Ke}from"@visulima/path";import{downloadTemplate as le}from"giget";import{modify as Ge,applyEdits as Je}from"jsonc-parser";import{join as U,dirname as Ye}from"node:path";import{d as Xe}from"../packem_shared/command-DwC11Cwe.mjs";import Qe from"magic-string";import{Project as Ze,SyntaxKind as w}from"ts-morph";import{P as F}from"../packem_shared/prompt-cancelled-C8Sj7OqI.mjs";import{h as ce,d as de,i as ue,b as et}from"../packem_shared/resolve-DZAGzg67.mjs";import{defaultSpawner as pe}from"../packem_shared/createRecordingSpawner-DJlNacZ6.mjs";import{d as tt,e as at,f as rt,a as he,t as H,g as me,h as ot,b as fe,i as ve,w as st,j as nt,k as ge,l as it}from"../packem_shared/tui-prompts-Dd0pDuNr.mjs";import{E as we,p as lt,w as ct,M as dt,r as ut,j as pt,e as ht,c as ye,k as be,f as mt}from"../packem_shared/storage-wIUel5Az.mjs";import{logStep as J}from"../packem_shared/createLogger-hGafwf-3.mjs";import{r as ft}from"../packem_shared/lint-ignore-report-DKZagpqk.mjs";import vt from"node:dns/promises";import{r as gt}from"../packem_shared/commands-BNKj7r1R.mjs";const W={bun:{githubCacheKey:void 0,githubSetupStep:` - uses: oven-sh/setup-bun@v2
2
+ `,gitlabImage:"oven/bun:1",gitlabProvisionScript:[],installCmd:"bun install --frozen-lockfile",lockfile:"bun.lockb"},npm:{githubCacheKey:"npm",githubSetupStep:"",gitlabImage:"node:22",gitlabProvisionScript:[],installCmd:"npm ci",lockfile:"package-lock.json"},pnpm:{githubCacheKey:"pnpm",githubSetupStep:` - uses: pnpm/action-setup@v4
3
+ `,gitlabImage:"node:22",gitlabProvisionScript:["corepack enable"],installCmd:"pnpm install --frozen-lockfile",lockfile:"pnpm-lock.yaml"},yarn:{githubCacheKey:"yarn",githubSetupStep:"",gitlabImage:"node:22",gitlabProvisionScript:["corepack enable"],installCmd:"yarn install --frozen-lockfile",lockfile:"yarn.lock"}},C=(e,t)=>{const a=Te(e,"lunora",t);return[a.command,...a.args].join(" ")},Y=e=>` - uses: actions/checkout@v4
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,17 @@ 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
- };
154
-
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
- };
169
-
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
- };
289
-
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
- };
313
-
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.`);
334
- }
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
362
- };
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
- })
369
- );
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);
386
- };
387
-
388
- const LOGO_PATH = "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";
389
- const WELCOME_CSS = `/* The welcome page is a full-bleed starter — reset the browser's default
84
+ - ${C(e,["deploy","--preview"])}
85
+ `},xe={github:{file:U(".github","workflows","deploy.yml"),secretsHint:"repository secrets (Settings → Secrets and variables → Actions)"},gitlab:{file:".gitlab-ci.yml",secretsHint:"masked CI/CD variables (Settings → CI/CD → Variables)"}},bt=(e,t)=>e==="github"?wt(t):yt(t),xt=e=>e==="github"||e==="gitlab",kt=(e,t,a,r={})=>{const o=U(e,xe[t].file);return m(o)&&r.overwrite!==!0?{path:o,skipped:!0,written:!1}:(M(Ye(o),{recursive:!0}),v(o,bt(t,a),"utf8"),{path:o,skipped:!1,written:!0})},Ct=(e,t,a,r,o={})=>{const s=xe[t];try{const n=kt(e,t,a,o);if(n.skipped)r.info(`--ci ${t}: ${s.file} already exists — left unchanged (re-run with overwrite to replace).`);else{const i=ne(a),l=[i.command,...i.args].join(" "),{installCmd:d,lockfile:c}=W[a];r.success(`--ci ${t}: wrote ${s.file}`),r.info(`--ci ${t}: set CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID as ${s.secretsHint} to enable deploys.`),r.info(`--ci ${t}: run \`${l}\` and commit ${c} before pushing — the pipeline runs \`${d}\`.`)}return n}catch(n){const i=n instanceof Error?n.message:String(n);return r.warn(`--ci ${t}: could not write ${s.file} (${i})`),{path:U(e,s.file),skipped:!1,written:!1}}},St={astro:"@lunora/react",none:"@lunora/react",nuxt:"@lunora/vue","react-router":"@lunora/react","solid-start":"@lunora/solid",sveltekit:"@lunora/svelte","tanstack-start":"@lunora/react","tanstack-start-solid":"@lunora/solid",vinext:"@lunora/react"},Lt=e=>{const t=Pe(e);return{...t,adapter:St[t.framework]}},_="lunora()",X='import { lunora } from "@lunora/vite";',Mt=/\blunora\s*\(/u,At='"@lunora/vite"',Et="'@lunora/vite'",Nt=e=>{for(const t of e.getStatements()){if(t.getKind()!==w.ExportAssignment)continue;const a=t.asKindOrThrow(w.ExportAssignment).getExpression();if(a.getKind()!==w.CallExpression)continue;const r=a.asKindOrThrow(w.CallExpression);if(r.getExpression().getText()!=="defineConfig")continue;const o=r.getArguments()[0];if(o?.getKind()===w.ObjectLiteralExpression)return o.asKindOrThrow(w.ObjectLiteralExpression)}},It=e=>{for(const t of e.getStatements()){if(t.getKind()!==w.ExportAssignment)continue;const a=t.asKindOrThrow(w.ExportAssignment).getExpression();if(a.getKind()===w.ObjectLiteralExpression)return a.asKindOrThrow(w.ObjectLiteralExpression)}},_t=e=>new Ze({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}).createSourceFile("vite.config.ts",e,{overwrite:!0}),$t=(e,t)=>{const a=t.getImportDeclarations().at(-1)?.getEnd()??0;a===0?e.prepend(`${X}
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=>Ve(o)).join(`
91
+ `);J(e,`${t}
92
+ ${r}`)},Dt=async e=>{if(g()){await tt();return}e.info(`
93
+ ${De}
94
+ ${Be}: ${je}`)},Ce=[{description:"LLMs via Workers AI (summarize, generate, stream)",label:"AI",value:"ai"},{description:"Sign-up / sign-in (asks which provider)",label:"Authentication",value:"auth"},{description:"Copy-in auth screens for your framework (sign in/up, reset, 2FA)",label:"Auth UI",value:"auth-ui"},{description:"Snapshot + restore your Durable Object data",label:"Backups",value:"backup"},{description:"Headless browser screenshots + PDFs",label:"Browser rendering",value:"browser"},{description:"Zero Trust identity via Cloudflare Access",label:"Cloudflare Access",value:"cloudflare-access"},{description:"Scheduled jobs via Cron Triggers (@lunora/scheduler)",label:"Cron jobs",value:"crons"},{description:"Cloudflare Email Workers + a dev mail catcher",label:"Transactional email",value:"email"},{description:"OpenFeature feature flags (ctx.flags)",label:"Feature flags",value:"flags"},{description:"External Postgres/MySQL via Hyperdrive",label:"Hyperdrive",value:"hyperdrive"},{description:"Stripe-first payments (checkout, subscription, webhooks)",label:"Payments",value:"payment"},{description:"Live presence / who's-online over hibernated WebSockets",label:"Presence",value:"presence"},{description:"Async message queues (push/pull consumers)",label:"Queues",value:"queue"},{description:"Typed R2 buckets + signed URLs (@lunora/storage)",label:"File storage",value:"storage"},{description:"Durable long-running workflows (step.do, sleep, branch)",label:"Workflows",value:"workflow"}],Q=Ce.map(e=>e.value),Bt=e=>e==="email"?we:e,jt=(e,t)=>{const a=[];for(const r of e.split(",").map(o=>o.trim()).filter(Boolean))Q.includes(r)?a.includes(r)||a.push(r):t(`init: unknown --add feature "${r}" — expected ${Q.join(" | ")}; skipping.`);return a},Vt=async e=>{const t=await ht(e.select),a=await ye(e.text,e.projectName);return{label:"auth",names:[t],transformManifest:r=>be(r,a)}},Ut=async e=>{const t=await e.text(dt,{placeholder:"you@yourdomain.com"}),a=ut(t,r=>{e.logger.warn(r)});return{label:"email",names:[we],transformManifest:a===void 0?void 0:r=>pt(r,a)}},Ft=async(e,t)=>{const a=e.resolveAuthUiItem?.()??"auth-ui-react";if(t)return{label:"auth-ui",names:[a]};const r=await ye(e.text,e.projectName);return{label:"auth-ui",names:[a],transformManifest:o=>be(o,r)}},Ht=async e=>{const t=await lt(e.text,e.projectName);return{label:"storage",names:["storage"],transformManifest:a=>ct(a,t)}},Wt={auth:Vt,"auth-ui":async(e,t)=>Ft(e,t.includes("auth")),email:Ut,storage:Ht},Z=async e=>{if(e.preselected!==void 0&&e.preselected.length>0){await e.applyAll(e.preselected.map(r=>{const o=r==="auth-ui"?e.resolveAuthUiItem?.()??"auth-ui-react":Bt(r);return{label:r,names:[o]}}));return}if(!e.interactive){e.logger.info("tip: add features later with `lunora add <ai|auth|backup|browser|cloudflare-access|crons|email|flags|hyperdrive|payment|presence|queue|storage|workflow>`.");return}const t=await e.multiSelect("Which features do you want to add?",Ce,{defaults:[]});if(t.length===0)return;const a=[];for(const r of t){const o=Wt[r];a.push(o?await o(e,t):{label:r,names:[r]})}await e.applyAll(a)},zt=[{description:"Adds an ignores entry to eslint.config.js",label:"ESLint",value:"eslint"},{description:"Writes .prettierignore",label:"Prettier",value:"prettier"},{description:"Adds negated patterns to biome.json",label:"Biome",value:"biome"},{description:"Writes ignorePatterns to .oxlintrc.json",label:"oxlint (oxc)",value:"oxlint"}],qt="Which linter/formatter do you use? We'll tell it to skip Lunora's generated files.",Kt=async e=>{const t=e.interactive?await e.multiSelect(qt,zt,{defaults:e.detected}):[...e.detected];if(t.length===0)return[];const a=e.apply(t);return ft(a,e.logger),a},N="M 259.500 10.552 C 220.080 15.859, 182.424 32.566, 152.500 58.025 C 110.179 94.031, 85.380 137.183, 77.518 188.500 C 75.410 202.255, 74.569 225.677, 75.796 236.466 C 76.757 244.917, 76.683 245.692, 74.518 249.966 C 63.118 272.466, 53.141 303.876, 51.382 322.799 L 50.718 329.943 71.960 320.471 C 83.643 315.262, 93.326 311, 93.478 311 C 93.630 311, 96.547 316.063, 99.959 322.250 C 103.371 328.438, 107.249 334.850, 108.577 336.500 L 110.990 339.500 110.981 336 C 110.977 334.075, 111.499 324.991, 112.143 315.813 L 113.312 299.127 121.406 293.336 C 132.495 285.403, 149.593 271.554, 161 261.268 C 171.556 251.748, 189.116 235, 188.540 235 C 188.337 235, 183.069 238.648, 176.835 243.106 C 142.318 267.789, 68.537 314, 63.646 314 C 61.843 314, 72.791 281.179, 80.905 262.259 C 92.233 235.845, 107.473 212.389, 132.106 183.453 L 138.451 176 148.268 176 C 176.192 176, 197.512 187.154, 212.868 209.797 C 216.470 215.108, 217.035 216.595, 216.477 219.297 C 211.386 243.968, 202.359 274.496, 193.797 296 C 183.898 320.861, 167.147 352.101, 152.395 373.215 L 147.004 380.930 152.891 385.830 C 161.400 392.911, 165.563 396, 166.594 395.998 C 167.092 395.998, 168.772 391.641, 170.327 386.317 C 176.279 365.934, 188.422 338.749, 200.942 317.778 C 223.060 280.731, 256.432 244.369, 294.500 215.836 C 309.956 204.252, 313.937 201.603, 314.719 202.385 C 315.116 202.783, 315.449 213.096, 315.460 225.304 C 315.474 241.855, 315.021 250.405, 313.680 258.924 C 307.009 301.272, 291.175 336.677, 263.112 372 C 255.259 381.883, 227.182 410.673, 218.516 417.727 L 213.532 421.783 223.439 424.880 C 281.705 443.093, 349.165 436.018, 398.616 406.508 C 446.728 377.797, 483.322 331.466, 497.366 281.481 C 503.381 260.075, 504.480 250.741, 504.491 221 C 504.501 191.997, 503.598 184.047, 497.987 163.732 C 484.768 115.871, 452.505 72.708, 407.718 42.964 C 381.051 25.254, 352.818 14.828, 319.695 10.460 C 305.932 8.645, 273.298 8.695, 259.500 10.552",L=`/* The welcome page is a full-bleed starter — reset the browser's default
390
95
  body margin/padding so it sits flush; everything else is scoped under
391
96
  .lunora-welcome (collision-safe). */
392
97
  body {
@@ -491,8 +196,7 @@ body {
491
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); }
492
197
 
493
198
  @media (prefers-reduced-motion: reduce) { .lunora-welcome * { transition: none !important; } }
494
- `;
495
- const REACT_APP = `import { useEffect, useState } from "react";
199
+ `,Gt=`import { useEffect, useState } from "react";
496
200
 
497
201
  type Theme = "dark" | "light";
498
202
 
@@ -534,7 +238,7 @@ export default function App() {
534
238
  <div className="lw-wrap">
535
239
  <div className="brand">
536
240
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
537
- <path d="${LOGO_PATH}" fill="currentColor" fillRule="evenodd" />
241
+ <path d="${N}" fill="currentColor" fillRule="evenodd" />
538
242
  </svg>
539
243
  <span className="word">Lunora</span>
540
244
  </div>
@@ -653,8 +357,7 @@ export default function App() {
653
357
  </div>
654
358
  );
655
359
  }
656
- `;
657
- const VUE_APP = `<script setup lang="ts">
360
+ `,Jt=`<script setup lang="ts">
658
361
  import { onMounted, ref } from "vue";
659
362
 
660
363
  // Default to "dark" for a stable first paint, then reconcile to the OS
@@ -694,7 +397,7 @@ const toggle = (): void => {
694
397
  <div class="lw-wrap">
695
398
  <div class="brand">
696
399
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
697
- <path d="${LOGO_PATH}" fill="currentColor" fill-rule="evenodd" />
400
+ <path d="${N}" fill="currentColor" fill-rule="evenodd" />
698
401
  </svg>
699
402
  <span class="word">Lunora</span>
700
403
  </div>
@@ -810,8 +513,7 @@ const toggle = (): void => {
810
513
  </div>
811
514
  </div>
812
515
  </template>
813
- `;
814
- const SOLID_APP = `import { createSignal, onMount } from "solid-js";
516
+ `,Yt=`import { createSignal, onMount } from "solid-js";
815
517
 
816
518
  export default function App() {
817
519
  // Default to "dark" for a stable first paint, then reconcile to the OS
@@ -851,7 +553,7 @@ export default function App() {
851
553
  <div class="lw-wrap">
852
554
  <div class="brand">
853
555
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
854
- <path d="${LOGO_PATH}" fill="currentColor" fill-rule="evenodd" />
556
+ <path d="${N}" fill="currentColor" fill-rule="evenodd" />
855
557
  </svg>
856
558
  <span class="word">Lunora</span>
857
559
  </div>
@@ -970,8 +672,7 @@ export default function App() {
970
672
  </div>
971
673
  );
972
674
  }
973
- `;
974
- const SVELTE_APP = `<script lang="ts">
675
+ `,Xt=`<script lang="ts">
975
676
  import { onMount } from "svelte";
976
677
 
977
678
  // Default to "dark" for a stable first paint, then reconcile to the OS
@@ -1014,7 +715,7 @@ const SVELTE_APP = `<script lang="ts">
1014
715
  <div class="lw-wrap">
1015
716
  <div class="brand">
1016
717
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
1017
- <path d="${LOGO_PATH}" fill="currentColor" fill-rule="evenodd" />
718
+ <path d="${N}" fill="currentColor" fill-rule="evenodd" />
1018
719
  </svg>
1019
720
  <span class="word">Lunora</span>
1020
721
  </div>
@@ -1129,8 +830,7 @@ const SVELTE_APP = `<script lang="ts">
1129
830
  <div class="lw-foot">Running on Lunora · Vite + Svelte</div>
1130
831
  </div>
1131
832
  </div>
1132
- `;
1133
- const VANILLA_MAIN = `import "./style.css";
833
+ `,Qt=`import "./style.css";
1134
834
 
1135
835
  import { LunoraClient } from "lunorash/client";
1136
836
 
@@ -1158,7 +858,7 @@ const welcomeHtml = \`
1158
858
  <div class="lw-wrap">
1159
859
  <div class="brand">
1160
860
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
1161
- <path d="${LOGO_PATH}" fill="currentColor" fill-rule="evenodd" />
861
+ <path d="${N}" fill="currentColor" fill-rule="evenodd" />
1162
862
  </svg>
1163
863
  <span class="word">Lunora</span>
1164
864
  </div>
@@ -1297,10 +997,7 @@ const count = document.querySelector<HTMLSpanElement>("#lw-count")!;
1297
997
  client.onUpdate(api.messages.list, { channelId: "channel:demo" }, (result) => {
1298
998
  count.textContent = String(result.messages.length);
1299
999
  });
1300
- `;
1301
-
1302
- const READ_URL = `const url = (import.meta.env.VITE_LUNORA_URL as string | undefined) ?? globalThis.location.origin;`;
1303
- const REACT_MAIN = `import "./index.css";
1000
+ `,O="const url = (import.meta.env.VITE_LUNORA_URL as string | undefined) ?? globalThis.location.origin;",Zt=`import "./index.css";
1304
1001
 
1305
1002
  import { LunoraProvider } from "@lunora/react";
1306
1003
  import { LunoraClient } from "lunorash/client";
@@ -1312,7 +1009,7 @@ import App from "./App.tsx";
1312
1009
  // \`@lunora/vite\` runs the Worker on the same origin as Vite, so default to
1313
1010
  // \`location.origin\`. Point \`VITE_LUNORA_URL\` at a deployed Worker to develop
1314
1011
  // the client against production data.
1315
- ${READ_URL}
1012
+ ${O}
1316
1013
  const client = new LunoraClient({ url });
1317
1014
 
1318
1015
  const root = document.getElementById("root");
@@ -1328,8 +1025,7 @@ createRoot(root).render(
1328
1025
  </LunoraProvider>
1329
1026
  </StrictMode>,
1330
1027
  );
1331
- `;
1332
- const VUE_MAIN = `import "./style.css";
1028
+ `,ea=`import "./style.css";
1333
1029
 
1334
1030
  import { createLunora } from "@lunora/vue";
1335
1031
  import { LunoraClient } from "lunorash/client";
@@ -1338,43 +1034,40 @@ import { createApp } from "vue";
1338
1034
  import App from "./App.vue";
1339
1035
 
1340
1036
  // Provide one LunoraClient at the app root via the Vue plugin form.
1341
- ${READ_URL}
1037
+ ${O}
1342
1038
  createApp(App).use(createLunora(new LunoraClient({ url }))).mount("#app");
1343
- `;
1344
- const SOLID_INDEX = `import "./index.css";
1039
+ `,ta=`import "./index.css";
1345
1040
 
1346
- import { LunoraContext } from "@lunora/solid";
1041
+ import { LunoraProvider } from "@lunora/solid";
1347
1042
  import { LunoraClient } from "lunorash/client";
1348
1043
  import { render } from "solid-js/web";
1349
1044
 
1350
1045
  import App from "./App";
1351
1046
 
1352
- ${READ_URL}
1047
+ ${O}
1353
1048
  const client = new LunoraClient({ url });
1354
1049
  const root = document.getElementById("root");
1355
1050
 
1356
1051
  render(
1357
1052
  () => (
1358
- <LunoraContext.Provider value={client}>
1053
+ <LunoraProvider client={client}>
1359
1054
  <App />
1360
- </LunoraContext.Provider>
1055
+ </LunoraProvider>
1361
1056
  ),
1362
1057
  root!,
1363
1058
  );
1364
- `;
1365
- const SVELTE_ROOT = `<script lang="ts">
1059
+ `,aa=`<script lang="ts">
1366
1060
  import { setLunoraClient } from "@lunora/svelte";
1367
1061
  import { LunoraClient } from "lunorash/client";
1368
1062
 
1369
1063
  import App from "./App.svelte";
1370
1064
 
1371
- ${READ_URL}
1065
+ ${O}
1372
1066
  setLunoraClient(new LunoraClient({ url }));
1373
1067
  <\/script>
1374
1068
 
1375
1069
  <App />
1376
- `;
1377
- const SVELTE_MAIN = `import "./app.css";
1070
+ `,ra=`import "./app.css";
1378
1071
 
1379
1072
  import { mount } from "svelte";
1380
1073
 
@@ -1384,62 +1077,48 @@ import Root from "./Root.svelte";
1384
1077
  const app = mount(Root, { target: document.getElementById("app")! });
1385
1078
 
1386
1079
  export default app;
1387
- `;
1388
- const ADAPTERS = {
1389
- react: {
1390
- adapter: "@lunora/react",
1391
- createViteTemplate: "react-ts",
1392
- files: [
1393
- { contents: REACT_MAIN, path: "src/main.tsx" },
1394
- { contents: REACT_APP, path: "src/App.tsx" },
1395
- { contents: WELCOME_CSS, path: "src/index.css" }
1396
- ],
1397
- label: "React"
1398
- },
1399
- solid: {
1400
- adapter: "@lunora/solid",
1401
- createViteTemplate: "solid",
1402
- files: [
1403
- { contents: SOLID_INDEX, path: "src/index.tsx" },
1404
- { contents: SOLID_APP, path: "src/App.tsx" },
1405
- { contents: WELCOME_CSS, path: "src/index.css" }
1406
- ],
1407
- label: "Solid"
1408
- },
1409
- svelte: {
1410
- adapter: "@lunora/svelte",
1411
- createViteTemplate: "svelte-ts",
1412
- files: [
1413
- { contents: SVELTE_ROOT, path: "src/Root.svelte" },
1414
- { contents: SVELTE_MAIN, path: "src/main.ts" },
1415
- { contents: SVELTE_APP, path: "src/App.svelte" },
1416
- { contents: WELCOME_CSS, path: "src/app.css" }
1417
- ],
1418
- label: "Svelte"
1419
- },
1420
- vanilla: {
1421
- adapter: "lunorash/client",
1422
- createViteTemplate: "vanilla-ts",
1423
- files: [
1424
- { contents: VANILLA_MAIN, path: "src/main.ts" },
1425
- { contents: WELCOME_CSS, path: "src/style.css" }
1426
- ],
1427
- label: "Vanilla"
1428
- },
1429
- vue: {
1430
- adapter: "@lunora/vue",
1431
- createViteTemplate: "vue-ts",
1432
- files: [
1433
- { contents: VUE_MAIN, path: "src/main.ts" },
1434
- { contents: VUE_APP, path: "src/App.vue" },
1435
- { contents: WELCOME_CSS, path: "src/style.css" }
1436
- ],
1437
- label: "Vue"
1438
- }
1439
- };
1440
- const isOverlayFramework = (value) => Object.hasOwn(ADAPTERS, value);
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";
1441
1084
 
1442
- const LUNORA_SCHEMA = `import { defineSchema, defineTable, v } from "lunorash/server";
1085
+ export const limits = {
1086
+ default: { kind: "token bucket", period: 60_000, rate: 10 },
1087
+ } as const satisfies RateLimitConfigMap;
1088
+
1089
+ export type LimitName = keyof typeof limits;
1090
+
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
+ });
1096
+
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
+ });
1104
+
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";
1443
1122
 
1444
1123
  export default defineSchema({
1445
1124
  messages: defineTable({
@@ -1448,22 +1127,16 @@ export default defineSchema({
1448
1127
  })
1449
1128
  .shardBy("channelId")
1450
1129
  .index("by_channel", ["channelId"]),
1451
- });
1452
- `;
1453
- const LUNORA_MESSAGES = `import { RateLimiter, rateLimit } from "@lunora/ratelimit";
1130
+ }).extend(ratelimit.extension);
1131
+ `,na=`import { RateLimiter, rateLimit, createDbStore } from "lunorash/ratelimit";
1454
1132
 
1455
1133
  import { mutation, query, v } from "#lunora/_generated/server.js";
1456
1134
 
1457
- /**
1458
- * One in-memory limiter so the public \`send\` mutation isn't an open flood target
1459
- * out of the box. The default store is in-memory (per-isolate, resets on
1460
- * eviction) — fine for a starter; run \`lunora add ratelimit\` for the durable,
1461
- * \`ctx.db\`-backed store when you ship to production.
1462
- */
1463
- const limiter = new RateLimiter({
1135
+ const limiter = (ctx: { db: unknown }) => new RateLimiter({
1464
1136
  config: {
1465
1137
  send: { kind: "token bucket", period: 60_000, rate: 30 },
1466
1138
  },
1139
+ store: createDbStore({ db: ctx.db as never, table: "ratelimit_buckets" }),
1467
1140
  });
1468
1141
 
1469
1142
  export const list = query.input({ channelId: v.string().meta({ schema: { maxLength: 256 } }), limit: v.optional(v.number()) }).query(async ({ args, ctx }) => {
@@ -1483,8 +1156,7 @@ export const send = mutation
1483
1156
 
1484
1157
  return { channelId: args.channelId, id, text: args.text };
1485
1158
  });
1486
- `;
1487
- const SERVER_ENTRY = `import type { ShardNamespaceLike } from "lunorash/runtime";
1159
+ `,ia=`import type { ShardNamespaceLike } from "lunorash/runtime";
1488
1160
 
1489
1161
  import { defineApp } from "../lunora/_generated/app.js";
1490
1162
 
@@ -1498,8 +1170,7 @@ const app = defineApp<Env>()
1498
1170
 
1499
1171
  export const ShardDO = app.ShardDO;
1500
1172
  export default app;
1501
- `;
1502
- const WRANGLER = `{
1173
+ `,la=`{
1503
1174
  "$schema": "node_modules/wrangler/config-schema.json",
1504
1175
  "name": "__NAME__",
1505
1176
  "main": "src/server.ts",
@@ -1511,206 +1182,23 @@ const WRANGLER = `{
1511
1182
  "migrations": [{ "tag": "v1", "new_sqlite_classes": ["ShardDO"] }],
1512
1183
  "observability": { "enabled": true, "head_sampling_rate": 1 },
1513
1184
  }
1514
- `;
1515
- const GITIGNORE_ADDITIONS = [".wrangler", ".env", ".env.*", "!.env.example", ".lunora/", ".lunora-cache", "lunora/_generated"];
1516
- 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.
1517
1186
  # Vite statically replaces \`import.meta.env.VITE_LUNORA_URL\` at \`vite dev\` / build.
1518
1187
  # Leave it unset to use the page origin; set it to point at a deployed Worker:
1519
1188
  #
1520
1189
  # VITE_LUNORA_URL=https://my-app.example.workers.dev
1521
- `;
1522
- const COMMON_DEV_DEPENDENCIES = {
1523
- "@cloudflare/workers-types": "^4.20260611.1",
1524
- wrangler: "^4.100.0"
1525
- };
1526
- const writeFile = (target, relativePath, contents, written) => {
1527
- const destination = join$1(target, relativePath);
1528
- mkdirSync(dirname$1(destination), { recursive: true });
1529
- writeFileSync(destination, contents, "utf8");
1530
- written.push(destination);
1531
- };
1532
- const NEWLINE = /\r?\n/;
1533
- const ensureGitignore = (target) => {
1534
- const path = join$1(target, ".gitignore");
1535
- const existing = existsSync(path) ? readFileSync(path, "utf8") : "";
1536
- const missing = GITIGNORE_ADDITIONS.filter((entry) => !existing.split(NEWLINE).includes(entry));
1537
- if (missing.length === 0) {
1538
- return;
1539
- }
1540
- const prefix = existing.length > 0 && !existing.endsWith("\n") ? "\n" : "";
1541
- 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}
1542
1193
  # Lunora
1543
- ${missing.join("\n")}
1544
- `, "utf8");
1545
- };
1546
- const isLunoraDep$1 = (name) => name === "lunorash" || name.startsWith("@lunora/");
1547
- const stampRange = (name, range, distTag, versions) => isLunoraDep$1(name) ? versions?.get(name) ?? distTag : range;
1548
- const withDependency = (map, name, range, distTag) => {
1549
- return { ...map, [name]: stampRange(name, range, distTag) };
1550
- };
1551
- const restampLunora = (map, distTag, versions) => Object.fromEntries(Object.entries(map).map(([name, range]) => [name, stampRange(name, range, distTag, versions)]));
1552
- const patchPackageJson = async (target, name, adapter, distTag) => {
1553
- const path = join$1(target, "package.json");
1554
- const parsed = JSON.parse(readFileSync(path, "utf8"));
1555
- let dependencies = withDependency(parsed.dependencies ?? {}, "lunorash", distTag, distTag);
1556
- dependencies = withDependency(dependencies, "@lunora/ratelimit", distTag, distTag);
1557
- if (adapter.adapter.startsWith("@lunora/")) {
1558
- dependencies = withDependency(dependencies, adapter.adapter, distTag, distTag);
1559
- }
1560
- for (const [depName, range] of Object.entries(adapter.extraDependencies ?? {})) {
1561
- dependencies = withDependency(dependencies, depName, range, distTag);
1562
- }
1563
- let devDependencies = withDependency(parsed.devDependencies ?? {}, "@lunora/vite", distTag, distTag);
1564
- devDependencies = withDependency(devDependencies, "@lunora/studio", distTag, distTag);
1565
- for (const [depName, range] of Object.entries(COMMON_DEV_DEPENDENCIES)) {
1566
- devDependencies = withDependency(devDependencies, depName, range, distTag);
1567
- }
1568
- const lunoraNames = [...Object.keys(dependencies), ...Object.keys(devDependencies)].filter((depName) => isLunoraDep$1(depName));
1569
- const versions = await resolveTagVersions(lunoraNames, distTag);
1570
- parsed.name = name;
1571
- parsed.imports = { ...parsed.imports, "#lunora/*": "./lunora/*" };
1572
- parsed.dependencies = restampLunora(dependencies, distTag, versions);
1573
- parsed.devDependencies = restampLunora(devDependencies, distTag, versions);
1574
- parsed.scripts = { ...parsed.scripts, codegen: "lunora codegen", deploy: "vite build && lunora deploy" };
1575
- writeFileSync(path, `${JSON.stringify(parsed, void 0, 4)}
1576
- `, "utf8");
1577
- };
1578
- const patchBaseViteConfig = (target, logger) => {
1579
- const candidate = ["vite.config.ts", "vite.config.mts", "vite.config.js", "vite.config.mjs"].map((file) => join$1(target, file)).find((path) => existsSync(path));
1580
- if (candidate === void 0) {
1581
- logger.warn("overlay: no vite.config found in the create-vite base — add `lunora()` to your Vite plugins manually.");
1582
- return;
1583
- }
1584
- const result = patchViteConfig(readFileSync(candidate, "utf8"));
1585
- if (result.changed) {
1586
- writeFileSync(candidate, result.code, "utf8");
1587
- }
1588
- };
1589
- const applyLunoraOverlay = async (options) => {
1590
- const { adapter, distTag, logger, name, target } = options;
1591
- const written = [];
1592
- writeFile(target, join$1("lunora", "schema.ts"), LUNORA_SCHEMA, written);
1593
- writeFile(target, join$1("lunora", "messages.ts"), LUNORA_MESSAGES, written);
1594
- writeFile(target, join$1("src", "server.ts"), SERVER_ENTRY, written);
1595
- writeFile(target, "wrangler.jsonc", WRANGLER.replaceAll("__NAME__", name), written);
1596
- writeFile(target, ".env.example", ENV_EXAMPLE, written);
1597
- for (const file of adapter.files) {
1598
- writeFile(target, file.path, file.contents, written);
1599
- }
1600
- patchBaseViteConfig(target, logger);
1601
- await patchPackageJson(target, name, adapter, distTag);
1602
- ensureGitignore(target);
1603
- return written;
1604
- };
1605
-
1606
- const ADJECTIVES = [
1607
- "lunar",
1608
- "silver",
1609
- "silent",
1610
- "waning",
1611
- "waxing",
1612
- "crescent",
1613
- "cosmic",
1614
- "stellar",
1615
- "orbital",
1616
- "gibbous",
1617
- "twilight",
1618
- "midnight",
1619
- "shimmering",
1620
- "drifting",
1621
- "weightless"
1622
- ];
1623
- const NOUNS = [
1624
- "moon",
1625
- "tide",
1626
- "crater",
1627
- "comet",
1628
- "eclipse",
1629
- "halo",
1630
- "orbit",
1631
- "nebula",
1632
- "voyager",
1633
- "lander",
1634
- "rover",
1635
- "beacon",
1636
- "harbor",
1637
- "meadow",
1638
- "fox"
1639
- ];
1640
- const pick = (items) => (
1641
- // eslint-disable-next-line sonarjs/pseudo-random -- cosmetic default project name, not a security decision.
1642
- items[Math.floor(Math.random() * items.length)]
1643
- );
1644
- const generateProjectName = () => `${pick(ADJECTIVES)}-${pick(NOUNS)}`;
1645
-
1646
- const isOnline = async () => dns.lookup("github.com").then(
1647
- () => true,
1648
- () => false
1649
- );
1650
- const GITHUB_SOURCE = /^(?:gh|github):([^/]+)\/([^#/]+)(?:\/[^#]*)?(?:#(.+))?$/;
1651
- const parseGitHubSource = (source) => {
1652
- const match = GITHUB_SOURCE.exec(source);
1653
- if (match === null) {
1654
- return void 0;
1655
- }
1656
- const [, owner, repo, ref] = match;
1657
- if (owner === void 0 || repo === void 0) {
1658
- return void 0;
1659
- }
1660
- return { owner, ref: ref ?? "HEAD", repo };
1661
- };
1662
- const templateRefExists = async (source) => {
1663
- const parsed = parseGitHubSource(source);
1664
- if (parsed === void 0) {
1665
- return void 0;
1666
- }
1667
- const url = `https://codeload.github.com/${parsed.owner}/${parsed.repo}/tar.gz/${parsed.ref}`;
1668
- try {
1669
- const response = await fetch(url, { method: "HEAD" });
1670
- if (response.status === 404) {
1671
- return false;
1672
- }
1673
- return response.ok ? true : void 0;
1674
- } catch {
1675
- return void 0;
1676
- }
1677
- };
1678
- const verifyRemoteTemplate = async (params) => {
1679
- if (params.isLocal) {
1680
- return true;
1681
- }
1682
- const isGitHubBacked = params.source === void 0 || parseGitHubSource(params.source) !== void 0;
1683
- if (!isGitHubBacked) {
1684
- return true;
1685
- }
1686
- if (!await isOnline()) {
1687
- params.logger.error("you appear to be offline — connect to the internet and try again, or scaffold from a local template with `--from <dir>`.");
1688
- return false;
1689
- }
1690
- if (params.source !== void 0 && await templateRefExists(params.source) === false) {
1691
- params.logger.error(`template source not found: ${params.source} — double-check --ref / --source, or browse the templates at https://lunora.sh/docs.`);
1692
- return false;
1693
- }
1694
- return true;
1695
- };
1696
-
1697
- const COPY = {
1698
- extras: "Let's finish setting up your app.",
1699
- framework: "Which framework should we launch?",
1700
- git: "Initialize a new git repository? (optional)",
1701
- install: "Install dependencies now?",
1702
- name: "Where should we land your project?",
1703
- nextHeader: "Liftoff confirmed — explore your project!",
1704
- packageManager: "Which package manager?"
1705
- };
1706
- const TEXT_EXTENSIONS = /* @__PURE__ */ new Set([".gitignore", ".html", ".js", ".json", ".jsonc", ".md", ".mjs", ".ts", ".tsx"]);
1707
- const VITE_CONFIG_CANDIDATES = ["vite.config.ts", "vite.config.mts", "vite.config.js", "vite.config.mjs"];
1708
- 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";
1709
1198
  import { lunora } from "@lunora/vite";
1710
1199
 
1711
1200
  export default defineConfig({ plugins: [lunora()] });
1712
- `;
1713
- const SAMPLE_SCHEMA = `import { defineSchema, defineTable, v } from "@lunora/server";
1201
+ `,Aa=`import { defineSchema, defineTable, v } from "@lunora/server";
1714
1202
 
1715
1203
  export default defineSchema({
1716
1204
  messages: defineTable({
@@ -1720,8 +1208,7 @@ export default defineSchema({
1720
1208
  .shardBy("channelId")
1721
1209
  .index("by_channel", ["channelId"]),
1722
1210
  });
1723
- `;
1724
- const SAMPLE_FUNCTION = `import { mutation, query, v } from "./_generated/server";
1211
+ `,Ea=`import { mutation, query, v } from "./_generated/server";
1725
1212
 
1726
1213
  export const list = query
1727
1214
  .input({ channelId: v.id("channels"), limit: v.optional(v.number()) })
@@ -1734,760 +1221,8 @@ export const send = mutation
1734
1221
  .mutation(async ({ args }) => {
1735
1222
  return { channelId: args.channelId, text: args.text };
1736
1223
  });
1737
- `;
1738
- const DEFAULT_SOURCE_BASE = "gh:anolilab/lunora/templates";
1739
- const isTextFile = (filePath) => {
1740
- const lastDot = filePath.lastIndexOf(".");
1741
- if (lastDot === -1) {
1742
- return false;
1743
- }
1744
- return TEXT_EXTENSIONS.has(filePath.slice(lastDot));
1745
- };
1746
- const substitute = (content, name) => content.replaceAll("{{name}}", name);
1747
- const isLunoraDep = (name) => name === "lunorash" || name.startsWith("@lunora/");
1748
- const resolveLunoraVersions = async (files, distTag) => {
1749
- const names = /* @__PURE__ */ new Set();
1750
- for (const file of files) {
1751
- if (basename(file) !== "package.json") {
1752
- continue;
1753
- }
1754
- try {
1755
- const parsed = JSON.parse(readFileSync(file, "utf8"));
1756
- for (const section of ["dependencies", "devDependencies"]) {
1757
- for (const name of Object.keys(parsed[section] ?? {})) {
1758
- if (isLunoraDep(name)) {
1759
- names.add(name);
1760
- }
1761
- }
1762
- }
1763
- } catch {
1764
- }
1765
- }
1766
- return resolveTagVersions(names, distTag);
1767
- };
1768
- const stampLunoraDeps = (packageJsonText, distTag, versions) => {
1769
- let parsed;
1770
- try {
1771
- parsed = JSON.parse(packageJsonText);
1772
- } catch {
1773
- return packageJsonText;
1774
- }
1775
- let text = packageJsonText;
1776
- for (const section of ["dependencies", "devDependencies"]) {
1777
- for (const name of Object.keys(parsed[section] ?? {})) {
1778
- if (!isLunoraDep(name)) {
1779
- continue;
1780
- }
1781
- const pin = versions.get(name) ?? distTag;
1782
- const edits = modify(text, [section, name], pin, { formattingOptions: { insertSpaces: true, tabSize: 4 } });
1783
- text = applyEdits(text, edits);
1784
- }
1785
- }
1786
- return text;
1787
- };
1788
- const PNPM_BUILT_DEPENDENCIES = ["esbuild", "sharp", "workerd"];
1789
- const PNPM_WORKSPACE_FILENAME = "pnpm-workspace.yaml";
1790
- const pnpmWorkspaceYaml = () => [
1791
- "# pnpm reads its settings from here (the package.json `pnpm` field is no longer read).",
1792
- "# Pre-approve the toolchain's native build scripts so `pnpm install` runs them",
1793
- "# without the interactive `pnpm approve-builds` step.",
1794
- "allowBuilds:",
1795
- ...PNPM_BUILT_DEPENDENCIES.map((name) => ` ${name}: true`),
1796
- ""
1797
- ].join("\n");
1798
- const collectFiles = (directory) => {
1799
- const out = [];
1800
- for (const entry of walkSync(directory, { includeDirs: false, includeFiles: true })) {
1801
- out.push(entry.path);
1802
- }
1803
- return out;
1804
- };
1805
- const copyTemplate = async (sourceDirectory, target, name) => {
1806
- const files = collectFiles(sourceDirectory);
1807
- const written = [];
1808
- const distTag = resolveDistTag();
1809
- const versions = await resolveLunoraVersions(files, distTag);
1810
- for (const source of files) {
1811
- const relativePath = relative(sourceDirectory, source);
1812
- const destination = join$1(target, relativePath);
1813
- mkdirSync(dirname$1(destination), { recursive: true });
1814
- const raw = readFileSync(source);
1815
- let text = isTextFile(source) ? substitute(raw.toString("utf8"), name) : void 0;
1816
- if (text !== void 0 && basename(source) === "package.json") {
1817
- text = stampLunoraDeps(text, distTag, versions);
1818
- }
1819
- if (text === void 0) {
1820
- writeFileSync(destination, raw);
1821
- } else {
1822
- writeFileSync(destination, text, "utf8");
1823
- }
1824
- written.push(destination);
1825
- }
1826
- return written;
1827
- };
1828
- const resolveTemplateSource = (templateType, source, ref) => {
1829
- if (source !== void 0 && source.length > 0) {
1830
- return source;
1831
- }
1832
- return `${DEFAULT_SOURCE_BASE}/${templateType}#${resolveSourceRef(ref)}`;
1833
- };
1834
- const isSafeSource = (source) => {
1835
- if (source.includes("..")) {
1836
- return false;
1837
- }
1838
- return source.startsWith("gh:") || source.startsWith("github:") || source.startsWith("https://");
1839
- };
1840
- const logWould = (logger, action) => {
1841
- logger.info(`[dry-run] would ${action}`);
1842
- };
1843
- const logScaffoldSuccess = (logger, written, target) => {
1844
- if (isInteractive()) {
1845
- process.stdout.write("\n");
1846
- }
1847
- logger.success(`scaffolded ${String(written.length)} files into ${target}`);
1848
- };
1849
- const runScriptCommand = (manager, script) => {
1850
- if (manager === "npm") {
1851
- return `npm run ${script}`;
1852
- }
1853
- if (manager === "bun") {
1854
- return `bun run ${script}`;
1855
- }
1856
- return `${manager} ${script}`;
1857
- };
1858
- const isInsideMonorepo = (startDirectory) => {
1859
- let directory = resolve(startDirectory);
1860
- for (; ; ) {
1861
- if (existsSync(join$1(directory, "pnpm-workspace.yaml"))) {
1862
- return true;
1863
- }
1864
- const packagePath = join$1(directory, "package.json");
1865
- if (existsSync(packagePath)) {
1866
- try {
1867
- const parsed = JSON.parse(readFileSync(packagePath, "utf8"));
1868
- if (parsed.workspaces !== void 0) {
1869
- return true;
1870
- }
1871
- } catch {
1872
- }
1873
- }
1874
- const parent = dirname$1(directory);
1875
- if (parent === directory) {
1876
- return false;
1877
- }
1878
- directory = parent;
1879
- }
1880
- };
1881
- const isInsideGitRepo = (startDirectory) => {
1882
- let directory = resolve(startDirectory);
1883
- for (; ; ) {
1884
- if (existsSync(join$1(directory, ".git"))) {
1885
- return true;
1886
- }
1887
- const parent = dirname$1(directory);
1888
- if (parent === directory) {
1889
- return false;
1890
- }
1891
- directory = parent;
1892
- }
1893
- };
1894
- const maybeOfferGit = async (options, target) => {
1895
- if (options.yes === true || !isInteractive() || isInsideGitRepo(dirname$1(target))) {
1896
- return;
1897
- }
1898
- if (!await tuiConfirm(COPY.git, { badge: BADGES.git, defaultYes: false })) {
1899
- await tuiInfo("Sounds good! You can always run git init manually.");
1900
- return;
1901
- }
1902
- if (options.dryRun === true) {
1903
- logWould(options.logger, "initialize a git repository");
1904
- return;
1905
- }
1906
- const spawner = options.spawner ?? defaultSpawner;
1907
- const result = await withTuiSpinner("Initializing a git repository…", () => spawner({ args: ["init"], command: "git", cwd: target }));
1908
- if (result.code === 0) {
1909
- await emitStep("git", "Initialized an empty git repository.");
1910
- } else {
1911
- options.logger.warn("`git init` failed — initialize it yourself later with `git init`.");
1912
- }
1913
- };
1914
- const printNextSteps = async (name, installed, insideMonorepo) => {
1915
- const manager = installed ?? "pnpm";
1916
- const steps = [{ code: `cd ./${name}`, lead: "Enter your project directory using" }];
1917
- if (installed === void 0) {
1918
- steps.push({ code: `${manager} install`, lead: "Install dependencies with", tail: insideMonorepo ? " from the workspace root" : void 0 });
1919
- }
1920
- steps.push(
1921
- { code: runScriptCommand(manager, "dev"), lead: "Run", tail: " to start the dev server." },
1922
- { code: "lunora add", lead: "Add features like auth or storage using" }
1923
- );
1924
- const help = [
1925
- { code: "https://lunora.sh/docs", lead: "Read the docs at" },
1926
- { code: "https://lunora.sh/chat", lead: "Stuck? Join the chat at" }
1927
- ];
1928
- if (isInteractive()) {
1929
- await tuiNextSteps(BADGES.next, COPY.nextHeader, steps, help);
1930
- return;
1931
- }
1932
- const lines = steps.map((step) => `${step.lead} ${step.code}${step.tail ?? ""}`);
1933
- lines.push("", ...help.map((line) => `${line.lead} ${line.code}${line.tail ?? ""}`));
1934
- await emitStep("next", COPY.nextHeader, lines.join("\n"));
1935
- };
1936
- const offerInstallIsInteractive = (options) => options.yes !== true && (options.installPrompt !== void 0 || isInteractive());
1937
- const maybeOfferInstall = async (options, target) => {
1938
- if (!offerInstallIsInteractive(options)) {
1939
- return void 0;
1940
- }
1941
- if (isInsideMonorepo(dirname$1(target))) {
1942
- return void 0;
1943
- }
1944
- const managers = detectInstalledManagers(options.packageManagerProbe);
1945
- const [defaultManager] = managers;
1946
- if (defaultManager === void 0) {
1947
- return void 0;
1948
- }
1949
- const confirm = options.installPrompt?.confirmInstall ?? (async () => tuiConfirm(COPY.install, { badge: BADGES.deps, defaultYes: true }));
1950
- if (!await confirm()) {
1951
- await tuiInfo("No problem! Remember to install dependencies after setup.");
1952
- return void 0;
1953
- }
1954
- let manager = defaultManager;
1955
- if (managers.length > 1) {
1956
- manager = options.installPrompt ? await options.installPrompt.selectManager(managers) : await tuiSelect(
1957
- COPY.packageManager,
1958
- managers.map((candidate) => {
1959
- return { label: candidate, value: candidate };
1960
- }),
1961
- { badge: BADGES.deps, default: defaultManager }
1962
- ) ?? defaultManager;
1963
- }
1964
- if (options.dryRun === true) {
1965
- logWould(options.logger, `install dependencies with ${manager}`);
1966
- return void 0;
1967
- }
1968
- if (manager === "pnpm") {
1969
- const workspacePath = join$1(target, PNPM_WORKSPACE_FILENAME);
1970
- if (!existsSync(workspacePath)) {
1971
- writeFileSync(workspacePath, pnpmWorkspaceYaml(), "utf8");
1972
- }
1973
- }
1974
- const spawner = options.spawner ?? defaultSpawner;
1975
- const { args, command } = installArgsFor(manager);
1976
- await emitStep("deps", `Installing dependencies with ${manager}…`);
1977
- const result = await spawner({ args, command, cwd: target });
1978
- if (result.code !== 0) {
1979
- options.logger.warn(`\`${command} install\` exited with code ${String(result.code)} — run it yourself in ${basename(target)}/.`);
1980
- return void 0;
1981
- }
1982
- await emitStep("deps", `Dependencies installed with ${manager}.`);
1983
- return manager;
1984
- };
1985
- const scaffoldFromLocal = async (fromRoot, templateType, target, name, logger) => {
1986
- const templateDirectory = join$1(fromRoot, templateType);
1987
- if (!existsSync(templateDirectory)) {
1988
- logger.error(`template not found in local source: ${templateDirectory}`);
1989
- return { code: 1, files: [], target };
1990
- }
1991
- const written = await copyTemplate(templateDirectory, target, name);
1992
- logScaffoldSuccess(logger, written, target);
1993
- return { code: 0, files: written, target };
1994
- };
1995
- const scaffoldFromRemote = async (options) => {
1996
- const { logger, name, ref, source, target, templateType } = options;
1997
- const stagingRoot = mkdtempSync(join$1(tmpdir(), "lunora-init-fetch-"));
1998
- const stagingDirectory = join$1(stagingRoot, "template");
1999
- try {
2000
- const remote = resolveTemplateSource(templateType, source, ref);
2001
- let downloaded;
2002
- let written = [];
2003
- await tuiTasks(
2004
- [
2005
- {
2006
- label: `${templateType} template fetched`,
2007
- run: async () => {
2008
- downloaded = await downloadTemplate(remote, {
2009
- cwd: stagingRoot,
2010
- dir: stagingDirectory,
2011
- force: true,
2012
- install: false,
2013
- silent: true
2014
- });
2015
- }
2016
- },
2017
- {
2018
- label: `files copied into ${name}/`,
2019
- run: async () => {
2020
- written = await copyTemplate(stagingDirectory, target, name);
2021
- }
2022
- }
2023
- ],
2024
- { end: "Project initialized!", start: "Project initializing…" }
2025
- );
2026
- const staged = collectFiles(stagingDirectory);
2027
- if (isInteractive()) {
2028
- process.stdout.write("\n");
2029
- }
2030
- logger.info(
2031
- downloaded?.commit ? `template: ${downloaded.source} @ ${downloaded.commit} (${String(staged.length)} files)` : `template: ${downloaded?.source ?? remote} (${String(staged.length)} files)`
2032
- );
2033
- logScaffoldSuccess(logger, written, target);
2034
- return { code: 0, files: written, target };
2035
- } catch (error) {
2036
- if (error instanceof PromptCancelledError) {
2037
- throw error;
2038
- }
2039
- const message = error instanceof Error ? error.message : String(error);
2040
- logger.error(`failed to download template: ${message}`);
2041
- return { code: 1, files: [], target };
2042
- } finally {
2043
- rmSync(stagingRoot, { force: true, recursive: true });
2044
- }
2045
- };
2046
- const renameCreateViteDotfiles = (directory) => {
2047
- for (const file of ["_gitignore", "_npmrc", "_gitattributes"]) {
2048
- const from = join$1(directory, file);
2049
- if (existsSync(from)) {
2050
- renameSync(from, join$1(directory, `.${file.slice(1)}`));
2051
- }
2052
- }
2053
- };
2054
- const scaffoldViteOverlay = async (options) => {
2055
- const { framework, logger, name, overlayBaseFrom, target } = options;
2056
- const adapter = ADAPTERS[framework];
2057
- const stagingRoot = mkdtempSync(join$1(tmpdir(), "lunora-vite-base-"));
2058
- try {
2059
- let localBase;
2060
- if (overlayBaseFrom !== void 0) {
2061
- localBase = join$1(overlayBaseFrom, `template-${adapter.createViteTemplate}`);
2062
- if (!existsSync(localBase)) {
2063
- logger.error(`create-vite base not found on disk: ${localBase}`);
2064
- return { code: 1, files: [], target };
2065
- }
2066
- }
2067
- const copyBase = async () => {
2068
- if (localBase !== void 0) {
2069
- cpSync(localBase, target, { recursive: true });
2070
- return;
2071
- }
2072
- const stagingDirectory = join$1(stagingRoot, "base");
2073
- const remote = `github:vitejs/vite/packages/create-vite/template-${adapter.createViteTemplate}#main`;
2074
- await downloadTemplate(remote, { cwd: stagingRoot, dir: stagingDirectory, force: true, install: false, silent: true });
2075
- renameCreateViteDotfiles(stagingDirectory);
2076
- cpSync(stagingDirectory, target, { recursive: true });
2077
- };
2078
- let written = [];
2079
- await tuiTasks(
2080
- [
2081
- { label: `create-vite (${adapter.label}) base ready`, run: copyBase },
2082
- {
2083
- label: `Lunora overlay applied (${adapter.label})`,
2084
- run: async () => {
2085
- written = await applyLunoraOverlay({ adapter, distTag: resolveDistTag(), logger, name, target });
2086
- }
2087
- }
2088
- ],
2089
- { end: "Project initialized!", start: "Project initializing…" }
2090
- );
2091
- logScaffoldSuccess(logger, written, target);
2092
- return { code: 0, files: [...collectFiles(target)], target };
2093
- } catch (error) {
2094
- if (error instanceof PromptCancelledError) {
2095
- throw error;
2096
- }
2097
- const message = error instanceof Error ? error.message : String(error);
2098
- logger.error(`failed to scaffold the ${adapter.label} base: ${message}`);
2099
- return { code: 1, files: [], target };
2100
- } finally {
2101
- rmSync(stagingRoot, { force: true, recursive: true });
2102
- }
2103
- };
2104
- const createMinimalViteConfig = (cwd, logger) => {
2105
- const target = join$1(cwd, "vite.config.ts");
2106
- try {
2107
- writeFileSync(target, MINIMAL_VITE_CONFIG, "utf8");
2108
- } catch (error) {
2109
- const message = error instanceof Error ? error.message : String(error);
2110
- logger.error(`init --in-place: could not write ${target}: ${message}`);
2111
- return { code: 1, files: [], target: cwd };
2112
- }
2113
- logger.success(`created ${target} with lunora() plugin`);
2114
- return { code: 0, files: [target], target: cwd };
2115
- };
2116
- const patchExistingViteConfig = (viteConfigPath, cwd, logger) => {
2117
- let source;
2118
- try {
2119
- source = readFileSync(viteConfigPath, "utf8");
2120
- } catch (error) {
2121
- const message = error instanceof Error ? error.message : String(error);
2122
- logger.error(`init --in-place: could not read ${viteConfigPath}: ${message}`);
2123
- return { code: 1, files: [], target: cwd };
2124
- }
2125
- const result = patchViteConfig(source);
2126
- if (!result.changed) {
2127
- logger.info(`${viteConfigPath}: ${result.reason ?? "no changes needed"}`);
2128
- return { code: 0, files: [], target: cwd };
2129
- }
2130
- try {
2131
- writeFileSync(viteConfigPath, result.code, "utf8");
2132
- } catch (error) {
2133
- const message = error instanceof Error ? error.message : String(error);
2134
- logger.error(`init --in-place: could not write ${viteConfigPath}: ${message}`);
2135
- return { code: 1, files: [], target: cwd };
2136
- }
2137
- logger.success(`patched ${viteConfigPath} — added lunora() plugin`);
2138
- return { code: 0, files: [viteConfigPath], target: cwd };
2139
- };
2140
- const scaffoldLunoraDirectory = (cwd, logger) => {
2141
- const lunoraDirectory = join$1(cwd, "lunora");
2142
- const schemaPath = join$1(lunoraDirectory, "schema.ts");
2143
- if (existsSync(schemaPath)) {
2144
- logger.info(`lunora/ already present — left ${schemaPath} untouched`);
2145
- return [];
2146
- }
2147
- const written = [];
2148
- try {
2149
- mkdirSync(lunoraDirectory, { recursive: true });
2150
- writeFileSync(schemaPath, SAMPLE_SCHEMA, "utf8");
2151
- written.push(schemaPath);
2152
- const functionPath = join$1(lunoraDirectory, "messages.ts");
2153
- if (!existsSync(functionPath)) {
2154
- writeFileSync(functionPath, SAMPLE_FUNCTION, "utf8");
2155
- written.push(functionPath);
2156
- }
2157
- logger.success(`scaffolded lunora/ (${String(written.length)} file(s))`);
2158
- } catch (error) {
2159
- const message = error instanceof Error ? error.message : String(error);
2160
- logger.error(`init --here: could not scaffold lunora/: ${message}`);
2161
- }
2162
- return written;
2163
- };
2164
- const printFrameworkNextSteps = (detection, logger) => {
2165
- const { adapter, class: frameworkClass, framework } = detection;
2166
- logger.info("");
2167
- logger.info(`detected framework: ${framework} (class ${frameworkClass})`);
2168
- logger.info("next steps:");
2169
- logger.info(` 1. install the adapter: pnpm add ${adapter} @lunora/client @lunora/runtime @lunora/server`);
2170
- logger.info(" 2. run codegen: lunora codegen");
2171
- if (frameworkClass === "A") {
2172
- logger.info(" 3. compose one worker: wrap your worker entry with");
2173
- logger.info(" createWorker({ httpRouter: <your framework SSR handler>, shardDO: ShardDO, ... })");
2174
- logger.info(` 4. add the provider: mount the ${adapter} provider in your root layout/route`);
2175
- logger.info(" 5. make a loader live: preloadQuery() in a loader, usePreloadedQuery() in the component");
2176
- logger.info(" see https://lunora.sh/docs/frameworks/reactive-loaders");
2177
- } else if (frameworkClass === "B") {
2178
- logger.info(" 3. inject Lunora: mount Lunora realtime under /_lunora/* in your server hook");
2179
- logger.info(` (${framework} owns its Cloudflare adapter — Lunora composes into its server entry)`);
2180
- logger.info(` 4. add the provider: mount the ${adapter} provider in your root layout`);
2181
- logger.info(" 5. read the guide: https://lunora.sh/docs/frameworks/deploy");
2182
- } else {
2183
- logger.info(" 3. add the provider: wrap your app with the LunoraProvider from @lunora/react");
2184
- logger.info(" 4. read the guide: https://lunora.sh/docs/frameworks/bring-your-framework");
2185
- }
2186
- logger.info("");
2187
- };
2188
- const findExistingViteConfig = (cwd) => {
2189
- for (const candidate of VITE_CONFIG_CANDIDATES) {
2190
- const full = join$1(cwd, candidate);
2191
- if (existsSync(full)) {
2192
- return full;
2193
- }
2194
- }
2195
- return void 0;
2196
- };
2197
- const patchOrCreateViteConfig = (cwd, framework, logger) => {
2198
- const viteConfigPath = findExistingViteConfig(cwd);
2199
- if (viteConfigPath === void 0) {
2200
- if (framework === "sveltekit" || framework === "nuxt" || framework === "astro") {
2201
- logger.info(`no Vite config found — ${framework} wires Lunora through its server entry (see next steps)`);
2202
- return { code: 0, files: [], target: cwd };
2203
- }
2204
- return createMinimalViteConfig(cwd, logger);
2205
- }
2206
- return patchExistingViteConfig(viteConfigPath, cwd, logger);
2207
- };
2208
- const runInPlaceInit = (cwd, logger) => {
2209
- const detection = detectFramework(cwd);
2210
- const viteResult = patchOrCreateViteConfig(cwd, detection.framework, logger);
2211
- if (viteResult.code !== 0) {
2212
- return viteResult;
2213
- }
2214
- const scaffolded = scaffoldLunoraDirectory(cwd, logger);
2215
- printFrameworkNextSteps(detection, logger);
2216
- return { code: 0, files: [...viteResult.files, ...scaffolded], target: cwd };
2217
- };
2218
- const offerIsInteractive = (options) => options.yes !== true && (options.prompt !== void 0 || (options.interactive ?? isInteractive()));
2219
- const maybeOfferExtras = async (options, projectDirectory) => {
2220
- const interactive = offerIsInteractive(options);
2221
- const preselected = options.add === void 0 ? [] : parseFeatureList(options.add, (message) => {
2222
- options.logger.warn(message);
2223
- });
2224
- const applyAll = async (plans) => {
2225
- if (plans.length === 0) {
2226
- return true;
2227
- }
2228
- if (options.dryRun === true) {
2229
- logWould(options.logger, `add ${plans.map((plan) => plan.label).join(", ")}`);
2230
- return true;
2231
- }
2232
- const buffered = [];
2233
- const applyLogger = isInteractive() ? {
2234
- error: (message) => {
2235
- buffered.push({ level: "error", message });
2236
- },
2237
- info: () => {
2238
- },
2239
- success: () => {
2240
- },
2241
- warn: (message) => {
2242
- buffered.push({ level: "warn", message });
2243
- }
2244
- } : options.logger;
2245
- const steps = plans.map((plan) => {
2246
- return {
2247
- running: `adding ${plan.label}…`,
2248
- task: () => runAddCommand({
2249
- allowUnsafeSource: options.allowUnsafeSource,
2250
- cwd: projectDirectory,
2251
- from: options.registryFrom,
2252
- logger: applyLogger,
2253
- names: [...plan.names],
2254
- ref: options.ref,
2255
- source: options.registrySource,
2256
- transformManifest: plan.transformManifest,
2257
- yes: true
2258
- })
2259
- };
2260
- });
2261
- const done = `added ${plans.map((plan) => plan.label).join(", ")}`;
2262
- const results = await withTuiBadgeProgress(BADGES.add, steps, done);
2263
- for (const { level, message } of buffered) {
2264
- options.logger[level](message);
2265
- }
2266
- return results.every((result) => result.code === 0);
2267
- };
2268
- const deps = {
2269
- applyAll,
2270
- interactive,
2271
- logger: options.logger,
2272
- multiSelect: options.prompt?.multiSelect ?? ((message, choices, settings) => tuiMultiSelect(message, choices, { ...settings, badge: BADGES.add })),
2273
- preselected: preselected.length > 0 ? preselected : void 0,
2274
- projectName: basename(projectDirectory),
2275
- select: options.prompt?.select ?? ((message, choices, settings) => tuiSelect(message, choices, { ...settings, badge: BADGES.add })),
2276
- text: options.prompt?.text ?? ((message, settings) => tuiText(message, { ...settings, badge: BADGES.add }))
2277
- };
2278
- if (preselected.length > 0) {
2279
- await offerRegistryExtras(deps);
2280
- return;
2281
- }
2282
- if (isInteractive()) {
2283
- await tuiHeadline(COPY.extras);
2284
- }
2285
- await offerRegistryExtras(deps);
2286
- };
2287
- const DEFAULT_FRAMEWORK = "react";
2288
- const FRAMEWORK_CHOICES = [
2289
- { description: "React SPA — official create-vite base + the Lunora layer (the default)", label: "React", value: "react" },
2290
- { description: "Vue SPA — create-vite base + Lunora", label: "Vue", value: "vue" },
2291
- { description: "Solid SPA — create-vite base + Lunora", label: "Solid", value: "solid" },
2292
- { description: "Svelte SPA — create-vite base + Lunora", label: "Svelte", value: "svelte" },
2293
- { description: "TanStack Start (React) — SSR with live-loader routes", label: "TanStack Start · React", value: "tanstack-start-react" },
2294
- { description: "TanStack Start (Solid)", label: "TanStack Start · Solid", value: "tanstack-start-solid" },
2295
- { description: "React Router (v7, framework mode) — SSR composed into the Lunora worker", label: "React Router", value: "react-router" },
2296
- { description: "Astro + a standalone Lunora worker", label: "Astro", value: "astro" },
2297
- { description: "AnalogJS (Angular) — single-worker, Lunora mounted in Nitro", label: "Analog", value: "analog" },
2298
- { description: "Nuxt (Vue) — single-worker, Lunora mounted in Nitro", label: "Nuxt", value: "nuxt" },
2299
- { description: "SvelteKit + a standalone Lunora worker", label: "SvelteKit", value: "sveltekit" },
2300
- { description: "Worker only — no frontend", label: "Standalone", value: "standalone" }
2301
- ];
2302
- const OVERLAY_VALUES = Object.keys(ADAPTERS).join("|");
2303
- const TEMPLATE_VALUES = FRAMEWORK_CHOICES.filter((choice) => !isOverlayFramework(choice.value)).map((choice) => choice.value).join("|");
2304
- const toScaffoldChoice = (value) => isOverlayFramework(value) ? { framework: value, kind: "overlay" } : { kind: "template", templateType: value };
2305
- const resolveScaffoldChoice = async (options) => {
2306
- if (options.vite !== void 0) {
2307
- return { framework: options.vite, kind: "overlay" };
2308
- }
2309
- if (options.templateType !== void 0) {
2310
- return { kind: "template", templateType: options.templateType };
2311
- }
2312
- if (!isInteractive() || options.yes === true) {
2313
- return { framework: DEFAULT_FRAMEWORK, kind: "overlay" };
2314
- }
2315
- return toScaffoldChoice(await tuiSelect(COPY.framework, FRAMEWORK_CHOICES, { badge: BADGES.tmpl, default: DEFAULT_FRAMEWORK }) ?? DEFAULT_FRAMEWORK);
2316
- };
2317
- const nonInteractiveInitError = (options) => {
2318
- if (isInteractive() || options.yes === true) {
2319
- return void 0;
2320
- }
2321
- const missing = [];
2322
- if (options.name === void 0) {
2323
- missing.push("a project name (`lunora init <name>`)");
2324
- }
2325
- if (options.templateType === void 0 && options.vite === void 0) {
2326
- missing.push(`a framework — \`--vite <${OVERLAY_VALUES}>\` for an SPA, or \`-t <${TEMPLATE_VALUES}>\` for a bespoke template`);
2327
- }
2328
- if (missing.length === 0) {
2329
- return void 0;
2330
- }
2331
- return `lunora init can't prompt in a non-interactive terminal — provide ${missing.join(" and ")}, or pass --yes to accept the defaults.`;
2332
- };
2333
- const scaffoldOverlayPath = async (options, framework, name, target) => {
2334
- if (!isOverlayFramework(framework)) {
2335
- options.logger.error(`init: unknown framework "${framework}". Supported overlays: ${Object.keys(ADAPTERS).join(", ")}.`);
2336
- return { code: 1, files: [], target };
2337
- }
2338
- if (!await verifyRemoteTemplate({ isLocal: options.overlayBaseFrom !== void 0, logger: options.logger })) {
2339
- return { code: 1, files: [], target };
2340
- }
2341
- mkdirSync(target, { recursive: true });
2342
- return scaffoldViteOverlay({ framework, logger: options.logger, name, overlayBaseFrom: options.overlayBaseFrom, target });
2343
- };
2344
- const scaffoldTemplatePath = async (options, templateType, name, target) => {
2345
- if (templateType === "next") {
2346
- options.logger.warn('template "next" is not yet available — re-run with `--vite react` or `-t standalone`.');
2347
- return { code: 1, files: [], target };
2348
- }
2349
- if (options.from !== void 0) {
2350
- return await scaffoldFromLocal(options.from, templateType, target, name, options.logger);
2351
- }
2352
- if (options.source !== void 0 && options.source.length > 0 && !options.allowUnsafeSource && !isSafeSource(options.source)) {
2353
- options.logger.error(
2354
- `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.`
2355
- );
2356
- return { code: 1, files: [], target };
2357
- }
2358
- if (!await verifyRemoteTemplate({ isLocal: false, logger: options.logger, source: resolveTemplateSource(templateType, options.source, options.ref) })) {
2359
- return { code: 1, files: [], target };
2360
- }
2361
- return scaffoldFromRemote({ logger: options.logger, name, ref: options.ref, source: options.source, target, templateType });
2362
- };
2363
- const scaffoldNewProject = async (options, cwd, recordTarget) => {
2364
- await tuiMoonrise("realtime backend on Cloudflare Workers + Durable Objects");
2365
- const blocked = nonInteractiveInitError(options);
2366
- if (blocked !== void 0) {
2367
- options.logger.error(blocked);
2368
- return { code: 1, files: [], target: "" };
2369
- }
2370
- const suggestedName = generateProjectName();
2371
- const name = options.name ?? await tuiText(COPY.name, { badge: BADGES.dir, default: suggestedName, placeholder: suggestedName });
2372
- const choice = await resolveScaffoldChoice(options);
2373
- if (name.includes("/") || name.includes("\\") || name === ".." || name === ".") {
2374
- options.logger.error(`init: refusing project name "${name}" — must not contain path separators or be "." / "..".`);
2375
- return { code: 1, files: [], target: "" };
2376
- }
2377
- const target = resolve(cwd, name);
2378
- const targetPreExisted = existsSync(target);
2379
- if (targetPreExisted) {
2380
- const entries = readdirSync(target);
2381
- if (entries.length > 0) {
2382
- options.logger.error(`target directory not empty: ${target}`);
2383
- return { code: 1, files: [], target };
2384
- }
2385
- }
2386
- if (options.dryRun === true) {
2387
- const what = choice.kind === "overlay" ? `the ${choice.framework} create-vite overlay` : `the ${choice.templateType} template`;
2388
- logWould(options.logger, `scaffold ${what} into ${target}`);
2389
- return { code: 0, files: [], target };
2390
- }
2391
- recordTarget(target, targetPreExisted);
2392
- return choice.kind === "overlay" ? scaffoldOverlayPath(options, choice.framework, name, target) : scaffoldTemplatePath(options, choice.templateType, name, target);
2393
- };
2394
- const resetScaffoldOnCancel = (cleanup, logger) => {
2395
- const { target, targetPreExisted } = cleanup;
2396
- if (target === void 0 || !existsSync(target)) {
2397
- return;
2398
- }
2399
- if (targetPreExisted === true) {
2400
- for (const entry of readdirSync(target)) {
2401
- rmSync(join$1(target, entry), { force: true, recursive: true });
2402
- }
2403
- } else {
2404
- rmSync(target, { force: true, recursive: true });
2405
- }
2406
- logger.info(`removed the partially-created project at ${target}`);
2407
- };
2408
- const runScaffoldStep = async (options, cwd, recordTarget) => {
2409
- if (options.inPlace !== true) {
2410
- return scaffoldNewProject(options, cwd, recordTarget);
2411
- }
2412
- if (options.dryRun === true) {
2413
- logWould(options.logger, `configure Lunora into ${cwd}`);
2414
- return { code: 0, files: [], target: cwd };
2415
- }
2416
- return runInPlaceInit(cwd, options.logger);
2417
- };
2418
- const runPostScaffold = async (options, result, cwd) => {
2419
- await maybeOfferExtras(options, result.target);
2420
- const installedManager = options.inPlace === true ? void 0 : await maybeOfferInstall(options, result.target);
2421
- if (options.inPlace !== true) {
2422
- await maybeOfferGit(options, result.target);
2423
- await printNextSteps(basename(result.target), installedManager, isInsideMonorepo(cwd));
2424
- await emitMascot(options.logger);
2425
- }
2426
- };
2427
- const scaffoldCiPipeline = (options, result, cwd) => {
2428
- if (result.code !== 0 || options.ci === void 0) {
2429
- return;
2430
- }
2431
- if (options.dryRun === true) {
2432
- logWould(options.logger, `scaffold a ${options.ci} CI deploy pipeline`);
2433
- return;
2434
- }
2435
- scaffoldCiWorkflow(options.inPlace === true ? cwd : result.target, options.ci, options.logger);
2436
- };
2437
- const runInitCommand = async (options) => {
2438
- const cwd = options.cwd ?? process.cwd();
2439
- const cleanup = {};
2440
- let result;
2441
- try {
2442
- result = await runScaffoldStep(options, cwd, (target, preExisted) => {
2443
- cleanup.target = target;
2444
- cleanup.targetPreExisted = preExisted;
2445
- });
2446
- if (result.code === 0 && result.target !== "") {
2447
- cleanup.target = void 0;
2448
- await runPostScaffold(options, result, cwd);
2449
- }
2450
- } catch (error) {
2451
- if (error instanceof PromptCancelledError) {
2452
- resetScaffoldOnCancel(cleanup, options.logger);
2453
- process.stdout.write("\n ✖ Setup cancelled — run `lunora init` again whenever you're ready. 🌙\n");
2454
- return { code: 130, files: [], target: "" };
2455
- }
2456
- throw error;
2457
- }
2458
- scaffoldCiPipeline(options, result, cwd);
2459
- return result;
2460
- };
2461
- 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";
2462
- const resolveCiProvider = (raw, logger) => {
2463
- if (raw === void 0) {
2464
- return void 0;
2465
- }
2466
- if (isCiProvider(raw)) {
2467
- return raw;
2468
- }
2469
- logger.warn(`init: unknown --ci "${raw}" — expected github | gitlab; skipping CI scaffold.`);
2470
- return void 0;
2471
- };
2472
- const execute = defineHandler(({ argument, cwd, logger, options }) => {
2473
- const templateType = options.template !== void 0 && isTemplate(options.template) ? options.template : void 0;
2474
- return runInitCommand({
2475
- add: options.add,
2476
- allowUnsafeSource: options.allowUnsafeSource === true,
2477
- cwd,
2478
- ci: resolveCiProvider(options.ci, logger),
2479
- dryRun: options.dryRun === true,
2480
- from: options.from,
2481
- inPlace: options.here === true,
2482
- interactive: options.interactive === true ? true : void 0,
2483
- logger,
2484
- name: argument[0],
2485
- ref: options.ref,
2486
- source: options.source,
2487
- templateType,
2488
- vite: options.vite,
2489
- yes: options.yes === true
2490
- });
2491
- });
2492
-
2493
- 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=Ge(o,[s,n],i,{formattingOptions:{insertSpaces:!0,tabSize:4}});o=Je(o,l)}return o},Oa=["@parcel/watcher","esbuild","lmdb","msgpackr-extract","rs-module-lexer","sharp","unrs-resolver","vue-demi","workerd"],Ta=["cpu-features","protobufjs","ssh2"],Ae="pnpm-workspace.yaml",Pa=()=>["# pnpm reads its settings from here (the package.json `pnpm` field is no longer read).","# Pre-approve the toolchain's native build scripts so `pnpm install` runs them","# without the interactive `pnpm approve-builds` step; deny the optional native","# builds a scaffold doesn't need (so no C/C++ toolchain is required).","allowBuilds:",...Oa.map(e=>` '${e}': true`),...Ta.map(e=>` '${e}': false`),""].join(`
1225
+ `),q=e=>{const t=[];for(const a of qe(e,{includeDirs:!1,includeFiles:!0}))Oe(a.path).isSymbolicLink()||t.push(a.path);return t},Ee=async(e,t,a)=>{const r=q(e),o=[],s=de(),n=await $a(r,s);for(const i of r){const l=Ke(e,i),d=u(t,l);M(A(d),{recursive:!0});const c=b(i);let p=Ia(i)?_a(c.toString("utf8"),a):void 0;p!==void 0&&E(i)==="package.json"&&(p=Ra(p,s,n)),p===void 0?v(d,c):v(d,p,"utf8"),o.push(d)}return o},B=(e,t,a)=>t!==void 0&&t.length>0?t:`${Na}/${e}#${ue(a)}`,Da=e=>e.includes("..")?!1:e.startsWith("gh:")||e.startsWith("github:")||e.startsWith("https://"),S=(e,t)=>{e.info(`[dry-run] would ${t}`)},K=(e,t,a)=>{g()&&process.stdout.write(`
1226
+ `),e.success(`scaffolded ${String(t.length)} files into ${a}`)},Ba=(e,t)=>{const{args:a,command:r}=We(e,t);return`${r} ${a.join(" ")}`},Ne=(e,t)=>{let a=ie(e);for(;;){if(t(a))return!0;const r=A(a);if(r===a)return!1;a=r}},ja=e=>{if(m(u(e,Ae)))return!0;const t=u(e,"package.json");if(!m(t))return!1;try{return JSON.parse(b(t,"utf8")).workspaces!==void 0}catch{return!1}},Ie=e=>Ne(e,ja),Va=e=>Ne(e,t=>m(u(t,".git"))),Ua=async(e,t)=>{if(e.yes===!0||!g()||Va(A(t)))return;if(!await fe(y.git,{badge:f.git,defaultYes:!1})){await ve("Sounds good! You can always run git init manually.");return}if(e.dryRun===!0){S(e.logger,"initialize a git repository");return}const a=e.spawner??pe;(await st("Initializing a git repository…",()=>a({args:["init"],command:"git",cwd:t}))).code===0?await R("git","Initialized an empty git repository."):e.logger.warn("`git init` failed — initialize it yourself later with `git init`.")},Fa=async(e,t,a,r)=>{const o=[{code:`cd ./${e}`,lead:"Enter your project directory using"}];t===void 0&&o.push({code:`${a} install`,lead:"Install dependencies with",tail:r?" from the workspace root":void 0}),o.push({code:Fe(a,"dev"),lead:"Run",tail:" to start the dev server."},{code:"lunora add",lead:"Add features like auth or storage using"});const s=[{code:"https://lunora.sh/docs",lead:"Read the docs at"},{code:"https://lunora.sh/chat",lead:"Stuck? Join the chat at"}];if(g()){await nt(f.next,y.nextHeader,o,s);return}const n=o.map(i=>`${i.lead} ${i.code}${i.tail??""}`);n.push("",...s.map(i=>`${i.lead} ${i.code}${i.tail??""}`)),await R("next",y.nextHeader,n.join(`
1227
+ `))},Ha=e=>e.yes!==!0&&(e.installPrompt!==void 0||g()),Wa=async(e,t)=>{if(!Ha(e)||Ie(A(t)))return;const a=Ue(e.packageManagerProbe),[r]=a;if(r===void 0)return;if(!await(e.installPrompt?.confirmInstall??(async()=>fe(y.install,{badge:f.deps,defaultYes:!0})))()){await ve("No problem! Remember to install dependencies after setup.");return}let s=r;if(a.length>1&&(s=e.installPrompt?await e.installPrompt.selectManager(a):await H(y.packageManager,a.map(c=>({label:c,value:c})),{badge:f.deps,default:r})??r),e.dryRun===!0){S(e.logger,`install dependencies with ${s}`);return}if(s==="pnpm"){const c=u(t,Ae);m(c)||v(c,Pa(),"utf8")}const n=e.spawner??pe,{args:i,command:l}=ne(s);await R("deps",`Installing dependencies with ${s}…`);const d=await n({args:i,command:l,cwd:t});if(d.code!==0){e.logger.warn(`\`${l} install\` exited with code ${String(d.code)} — run it yourself in ${E(t)}/.`);return}return await R("deps",`Dependencies installed with ${s}.`),s},za=async(e,t,a,r,o)=>{const s=u(e,t);if(!m(s))return o.error(`template not found in local source: ${s}`),{code:1,files:[],target:a};const n=await Ee(s,a,r);return K(o,n,a),{code:0,files:n,target:a}},qa=async e=>{const{logger:t,name:a,ref:r,source:o,target:s,templateType:n}=e,i=oe(u(se(),"lunora-init-fetch-")),l=u(i,"template");try{const d=o!==void 0&&o.length>0?r:await et(r,t),c=B(n,o,d);let p,h=[];await ge([{label:`${n} template fetched`,run:async()=>{p=await le(c,{cwd:i,dir:l,force:!0,install:!1,silent:!0})}},{label:`files copied into ${a}/`,run:async()=>{h=await Ee(l,s,a)}}],{end:"Project initialized!",start:"Project initializing…"});const I=q(l);return g()&&process.stdout.write(`
1228
+ `),t.info(p?.commit?`template: ${p.source} @ ${p.commit} (${String(I.length)} files)`:`template: ${p?.source??c} (${String(I.length)} files)`),K(t,h,s),{code:0,files:h,target:s}}catch(d){if(d instanceof F)throw d;const{hints:c,message:p}=Pt(d,{ref:ue(r),remote:B(n,o,r),templateType:n});t.error(p);for(const h of c)t.warn(h);return{code:1,files:[],target:s}}finally{$(i,{force:!0,recursive:!0})}},Ka=e=>{for(const t of["_gitignore","_npmrc","_gitattributes"]){const a=u(e,t);m(a)&&Re(a,u(e,`.${t.slice(1)}`))}},Ga=async e=>{const{framework:t,logger:a,name:r,overlayBaseFrom:o,target:s}=e,n=T[t],i=oe(u(se(),"lunora-vite-base-"));try{let l;if(o!==void 0&&(l=u(o,`template-${n.createViteTemplate}`),!m(l)))return a.error(`create-vite base not found on disk: ${l}`),{code:1,files:[],target:s};const d=async()=>{if(l!==void 0){G(l,s,{recursive:!0});return}const p=u(i,"base"),h=`github:vitejs/vite/packages/create-vite/template-${n.createViteTemplate}#main`;await le(h,{cwd:i,dir:p,force:!0,install:!1,silent:!0}),Ka(p),G(p,s,{recursive:!0})};let c=[];return await ge([{label:`create-vite (${n.label}) base ready`,run:d},{label:`Lunora overlay applied (${n.label})`,run:async()=>{c=await wa({adapter:n,distTag:de(),logger:a,name:r,target:s})}}],{end:"Project initialized!",start:"Project initializing…"}),K(a,c,s),{code:0,files:[...q(s)],target:s}}catch(l){if(l instanceof F)throw l;const d=l instanceof Error?l.message:String(l);return a.error(`failed to scaffold the ${n.label} base: ${d}`),{code:1,files:[],target:s}}finally{$(i,{force:!0,recursive:!0})}},j=(e,t,a,r,o)=>(o.error(`init --in-place: could not ${e} ${t}: ${a instanceof Error?a.message:String(a)}`),{code:1,files:[],target:r}),Ja=(e,t)=>{const a=u(e,"vite.config.ts");try{v(a,Ma,"utf8")}catch(r){return j("write",a,r,e,t)}return t.success(`created ${a} with lunora() plugin`),{code:0,files:[a],target:e}},Ya=(e,t,a)=>{let r;try{r=b(e,"utf8")}catch(s){return j("read",e,s,t,a)}const o=ke(r);if(!o.changed)return a.info(`${e}: ${o.reason??"no changes needed"}`),{code:0,files:[],target:t};try{v(e,o.code,"utf8")}catch(s){return j("write",e,s,t,a)}return a.success(`patched ${e} — added lunora() plugin`),{code:0,files:[e],target:t}},Xa=(e,t)=>{const a=u(e,"lunora"),r=u(a,"schema.ts");if(m(r))return t.info(`lunora/ already present — left ${r} untouched`),[];const o=[];try{M(a,{recursive:!0}),v(r,Aa,"utf8"),o.push(r);const s=u(a,"messages.ts");m(s)||(v(s,Ea,"utf8"),o.push(s)),t.success(`scaffolded lunora/ (${String(o.length)} file(s))`)}catch(s){const n=s instanceof Error?s.message:String(s);t.error(`init --here: could not scaffold lunora/: ${n}`)}return o},Qa=(e,t,a)=>{const{adapter:r,class:o,framework:s}=e;a.info(""),a.info(`detected framework: ${s} (class ${o})`),a.info("next steps:"),a.info(` 1. install the adapter: ${Ba(t,[r,"@lunora/client","@lunora/runtime","@lunora/server"])}`),a.info(" 2. run codegen: lunora codegen"),o==="A"?(a.info(" 3. compose one worker: wrap your worker entry with"),a.info(" createWorker({ httpRouter: <your framework SSR handler>, shardDO: ShardDO, ... })"),a.info(` 4. add the provider: mount the ${r} provider in your root layout/route`),a.info(" 5. make a loader live: preloadQuery() in a loader, usePreloadedQuery() in the component"),a.info(" see https://lunora.sh/docs/frameworks/reactive-loaders")):o==="B"?(a.info(" 3. inject Lunora: mount Lunora realtime under /_lunora/* in your server hook"),a.info(` (${s} owns its Cloudflare adapter — Lunora composes into its server entry)`),a.info(` 4. add the provider: mount the ${r} provider in your root layout`),a.info(" 5. read the guide: https://lunora.sh/docs/frameworks/deploy")):(a.info(" 3. add the provider: wrap your app with the LunoraProvider from @lunora/react"),a.info(" 4. read the guide: https://lunora.sh/docs/frameworks/bring-your-framework")),a.info("")},Za=(e,t,a)=>{const r=Se(e);return r===void 0?t==="sveltekit"||t==="nuxt"||t==="astro"?(a.info(`no Vite config found — ${t} wires Lunora through its server entry (see next steps)`),{code:0,files:[],target:e}):Ja(e,a):Ya(r,e,a)},er=(e,t)=>{const a=Lt(e),r=Za(e,a.framework,t);if(r.code!==0)return r;const o=Xa(e,t);return Qa(a,V(e),t),{code:0,files:[...r.files,...o],target:e}},tr=e=>e.yes!==!0&&(e.prompt!==void 0||(e.interactive??g())),ae=async(e,t,a)=>{a.dryRun!==!0&&await Kt({apply:r=>ze(e,r),detected:He(e),interactive:t,logger:a.logger,multiSelect:a.lintPrompt??((r,o,s)=>me(r,o,{...s,badge:f.add}))})},ar=async(e,t)=>{const a=tr(e),r=e.add===void 0?[]:jt(e.add,n=>{e.logger.warn(n)}),s={applyAll:async n=>{if(n.length===0)return!0;if(e.dryRun===!0)return S(e.logger,`add ${n.map(h=>h.label).join(", ")}`),!0;const i=[],l=g()?{error:h=>{i.push({level:"error",message:h})},info:()=>{},success:()=>{},warn:h=>{i.push({level:"warn",message:h})}}:e.logger,d=n.map(h=>({running:`adding ${h.label}…`,task:()=>gt({allowUnsafeSource:e.allowUnsafeSource,cwd:t,from:e.registryFrom,logger:l,names:[...h.names],ref:e.ref,source:e.registrySource,transformManifest:h.transformManifest,yes:!0})})),c=`added ${n.map(h=>h.label).join(", ")}`,p=await it(f.add,d,c);for(const{level:h,message:I}of i)e.logger[h](I);return p.every(h=>h.code===0)},interactive:a,logger:e.logger,multiSelect:e.prompt?.multiSelect??((n,i,l)=>me(n,i,{...l,badge:f.add})),preselected:r.length>0?r:void 0,projectName:E(t),resolveAuthUiItem:()=>{try{const n=JSON.parse(b(u(t,"package.json"),"utf8"));return mt({...n.dependencies,...n.devDependencies})??"auth-ui-react"}catch{return"auth-ui-react"}},select:e.prompt?.select??((n,i,l)=>H(n,i,{...l,badge:f.add})),text:e.prompt?.text??((n,i)=>he(n,{...i,badge:f.add}))};if(r.length>0){await Z(s),await ae(t,a,e);return}g()&&await ot(y.extras),await Z(s),await ae(t,a,e)},D="react",_e=[{description:"React SPA — official create-vite base + the Lunora layer (the default)",label:"React",value:"react"},{description:"Vue SPA — create-vite base + Lunora",label:"Vue",value:"vue"},{description:"Solid SPA — create-vite base + Lunora",label:"Solid",value:"solid"},{description:"Solid 2.0 SPA — the Solid 2 line (@solidjs/web, vite-plugin-solid 3)",label:"Solid 2",value:"solid-v2"},{description:"Svelte SPA — create-vite base + Lunora",label:"Svelte",value:"svelte"},{description:"Next.js (App Router) — OpenNext on Cloudflare + a standalone Lunora worker",label:"Next.js",value:"next"},{description:"TanStack Start (React) — SSR with live-loader routes",label:"TanStack Start · React",value:"tanstack-start-react"},{description:"TanStack Start (Solid)",label:"TanStack Start · Solid",value:"tanstack-start-solid"},{description:"Next.js App Router on Vite (vinext) — composed into the Lunora worker (experimental)",label:"vinext · App Router",value:"vinext"},{description:"Next.js Pages Router on Vite (vinext) — composed into one worker (experimental)",label:"vinext · Pages Router",value:"vinext-pages"},{description:"React Router (v7, framework mode) — SSR composed into the Lunora worker",label:"React Router",value:"react-router"},{description:"Astro + a standalone Lunora worker",label:"Astro",value:"astro"},{description:"AnalogJS (Angular) — single-worker, Lunora mounted in Nitro",label:"Analog",value:"analog"},{description:"Nuxt (Vue) — single-worker, Lunora mounted in Nitro",label:"Nuxt",value:"nuxt"},{description:"SvelteKit + a standalone Lunora worker",label:"SvelteKit",value:"sveltekit"},{description:"React Native (Expo) — an iOS/Android/web app + a Lunora worker backend",label:"React Native · Expo",value:"expo"},{description:"Worker only — no frontend",label:"Standalone",value:"standalone"}],rr=Object.keys(T).join("|"),$e=_e.filter(e=>!z(e.value)).map(e=>e.value),or=$e.join("|"),sr=e=>z(e)?{framework:e,kind:"overlay"}:{kind:"template",templateType:e},nr=async e=>e.vite!==void 0?{framework:e.vite,kind:"overlay"}:e.templateType!==void 0?{kind:"template",templateType:e.templateType}:!g()||e.yes===!0?{framework:D,kind:"overlay"}:sr(await H(y.framework,_e,{badge:f.tmpl,default:D})??D),ir=e=>{if(g()||e.yes===!0)return;const t=[];if(e.name===void 0&&t.push("a project name (`lunora init <name>`)"),e.templateType===void 0&&e.vite===void 0&&t.push(`a framework — \`--vite <${rr}>\` for an SPA, or \`-t <${or}>\` for a bespoke template`),t.length!==0)return`lunora init can't prompt in a non-interactive terminal — provide ${t.join(" and ")}, or pass --yes to accept the defaults.`},lr=async(e,t,a,r)=>z(t)?await Me({isLocal:e.overlayBaseFrom!==void 0,logger:e.logger})?(M(r,{recursive:!0}),Ga({framework:t,logger:e.logger,name:a,overlayBaseFrom:e.overlayBaseFrom,target:r})):{code:1,files:[],target:r}:(e.logger.error(`init: unknown framework "${t}". Supported overlays: ${Object.keys(T).join(", ")}.`),{code:1,files:[],target:r}),cr=async(e,t,a,r)=>e.from!==void 0?await za(e.from,t,r,a,e.logger):e.source!==void 0&&e.source.length>0&&!e.allowUnsafeSource&&!Da(e.source)?(e.logger.error(`init: refusing --source ${e.source} — only gh:, github:, or https:// sources are allowed (and may not contain ".."). Re-run with --allow-unsafe-source if you really want this.`),{code:1,files:[],target:r}):await Me({isLocal:!1,logger:e.logger,source:B(t,e.source,e.ref)})?qa({logger:e.logger,name:a,ref:e.ref,source:e.source,target:r,templateType:t}):{code:1,files:[],target:r},dr=async(e,t,a)=>{await rt("realtime backend on Cloudflare Workers + Durable Objects");const r=ir(e);if(r!==void 0)return e.logger.error(r),{code:1,files:[],target:""};const o=xa(),s=e.name??await he(y.name,{badge:f.dir,default:o,placeholder:o}),n=await nr(e),i=s.trim();if(i.length===0)return e.logger.error("init: refusing an empty project name — pass a directory name (e.g. `lunora init my-app`)."),{code:1,files:[],target:""};if(i.includes("/")||i.includes("\\")||i===".."||i===".")return e.logger.error(`init: refusing project name "${i}" — must not contain path separators or be "." / "..".`),{code:1,files:[],target:""};const l=ie(t,i),d=m(l);if(d&&re(l).length>0)return e.logger.error(`target directory not empty: ${l}`),{code:1,files:[],target:l};if(e.dryRun===!0){const c=n.kind==="overlay"?`the ${n.framework} create-vite overlay`:`the ${n.templateType} template`;return S(e.logger,`scaffold ${c} into ${l}`),{code:0,files:[],target:l}}return a(l,d),n.kind==="overlay"?lr(e,n.framework,i,l):cr(e,n.templateType,i,l)},ur=(e,t)=>{const{target:a,targetPreExisted:r}=e;if(!(a===void 0||!m(a))){if(r===!0)for(const o of re(a))$(u(a,o),{force:!0,recursive:!0});else $(a,{force:!0,recursive:!0});t.info(`removed the partially-created project at ${a}`)}},pr=async(e,t,a)=>e.inPlace!==!0?dr(e,t,a):e.dryRun===!0?(S(e.logger,`configure Lunora into ${t}`),{code:0,files:[],target:t}):er(t,e.logger),hr=async(e,t,a)=>{await ar(e,t.target);const r=e.inPlace===!0?void 0:await Wa(e,t.target);if(e.inPlace!==!0){await Ua(e,t.target);const o=r??V(t.target);await Fa(E(t.target),r,o,Ie(a)),await Dt(e.logger)}},mr=(e,t,a)=>{if(t.code!==0||e.ci===void 0)return;if(e.dryRun===!0){S(e.logger,`scaffold a ${e.ci} CI deploy pipeline`);return}const r=e.inPlace===!0?a:t.target;try{const o=V(r);Ct(r,e.ci,o,e.logger)}catch{e.logger.warn(`--ci ${e.ci}: could not detect a package manager for this project — skipped the CI pipeline.`)}},fr=async e=>{const t=e.cwd??process.cwd(),a={};let r;try{r=await pr(e,t,(o,s)=>{a.target=o,a.targetPreExisted=s}),r.code===0&&r.target!==""&&(a.target=void 0,await hr(e,r,t))}catch(o){if(o instanceof F)return ur(a,e.logger),process.stdout.write("\n ✖ Setup cancelled — run `lunora init` again whenever you're ready. 🌙\n"),{code:130,files:[],target:""};throw o}return mr(e,r,t),r},vr=e=>typeof e=="string"&&$e.includes(e),gr=(e,t)=>{if(e!==void 0){if(xt(e))return e;t.warn(`init: unknown --ci "${e}" — expected github | gitlab; skipping CI scaffold.`)}},Br=Xe(({argument:e,cwd:t,logger:a,options:r})=>{const o=r.template!==void 0&&vr(r.template)?r.template:void 0;return fr({add:r.add,allowUnsafeSource:r.allowUnsafeSource===!0,cwd:t,ci:gr(r.ci,a),dryRun:r.dryRun===!0,from:r.from,inPlace:r.here===!0,interactive:r.interactive===!0?!0:void 0,logger:a,name:e[0],ref:r.ref,source:r.source,templateType:o,vite:r.vite,yes:r.yes===!0})});export{Br as execute,vr as isTemplate,B as resolveTemplateSource,fr as runInitCommand};