@lunora/cli 1.0.0-alpha.23 → 1.0.0-alpha.231

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 (116) 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 +778 -346
  6. package/dist/index.d.ts +778 -346
  7. package/dist/index.mjs +1 -19
  8. package/dist/packem_chunks/handler.mjs +1 -150
  9. package/dist/packem_chunks/handler10.mjs +3 -16
  10. package/dist/packem_chunks/handler11.mjs +2 -22
  11. package/dist/packem_chunks/handler12.mjs +1 -192
  12. package/dist/packem_chunks/handler13.mjs +1 -131
  13. package/dist/packem_chunks/handler14.mjs +1 -65
  14. package/dist/packem_chunks/handler15.mjs +1 -58
  15. package/dist/packem_chunks/handler16.mjs +3 -79
  16. package/dist/packem_chunks/handler17.mjs +1 -43
  17. package/dist/packem_chunks/handler18.mjs +1 -105
  18. package/dist/packem_chunks/handler19.mjs +7 -170
  19. package/dist/packem_chunks/handler2.mjs +2 -114
  20. package/dist/packem_chunks/handler20.mjs +1 -89
  21. package/dist/packem_chunks/handler21.mjs +3 -94
  22. package/dist/packem_chunks/handler22.mjs +3 -0
  23. package/dist/packem_chunks/handler23.mjs +1 -0
  24. package/dist/packem_chunks/handler24.mjs +2 -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 -315
  34. package/dist/packem_chunks/planDevCommand.mjs +7 -509
  35. package/dist/packem_chunks/runCodegenCommand.mjs +4 -52
  36. package/dist/packem_chunks/runDeployCommand.mjs +7 -594
  37. package/dist/packem_chunks/runInitCommand.mjs +162 -1392
  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-rRB9TbDL.mjs +1 -0
  42. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-BMH-ZXl5.mjs +1 -0
  43. package/dist/packem_shared/admin-token-VdUnvnKW.mjs +1 -0
  44. package/dist/packem_shared/admin-url-BhF5ufg1.mjs +1 -0
  45. package/dist/packem_shared/binding-manifest-file-CQ1eQYy1.mjs +2 -0
  46. package/dist/packem_shared/buildRegistryIndex-DVmy8fHE.mjs +1 -0
  47. package/dist/packem_shared/catalog-Cbzph90w.mjs +1 -0
  48. package/dist/packem_shared/cli-DIb5Ay4K.mjs +3 -0
  49. package/dist/packem_shared/codegen-error-AmH54ofi.mjs +3 -0
  50. package/dist/packem_shared/command-DwC11Cwe.mjs +1 -0
  51. package/dist/packem_shared/commands-I18aR_DJ.mjs +15 -0
  52. package/dist/packem_shared/createLogger-hGafwf-3.mjs +2 -0
  53. package/dist/packem_shared/createRecordingSpawner-DJlNacZ6.mjs +1 -0
  54. package/dist/packem_shared/deploy-target-B0Xcb2jV.mjs +1 -0
  55. package/dist/packem_shared/diffSnapshots-DtC5Cs4Z.mjs +5 -0
  56. package/dist/packem_shared/docker-DpVxvYpL.mjs +1 -0
  57. package/dist/packem_shared/import-Dqd1MOOv.mjs +12 -0
  58. package/dist/packem_shared/insertSchemaExtension-DuiV6cba.mjs +8 -0
  59. package/dist/packem_shared/lint-ignore-report-DKZagpqk.mjs +2 -0
  60. package/dist/packem_shared/open-url-EnKy--w-.mjs +1 -0
  61. package/dist/packem_shared/output-format-DfogXx0p.mjs +2 -0
  62. package/dist/packem_shared/parseManifest-CwPTKdtS.mjs +1 -0
  63. package/dist/packem_shared/path-containment-CgxYZggb.mjs +1 -0
  64. package/dist/packem_shared/platform-diagnostics-Cn2g6Jh-.mjs +4 -0
  65. package/dist/packem_shared/prompt-cancelled-C8Sj7OqI.mjs +1 -0
  66. package/dist/packem_shared/resolve-B9ReA3FV.mjs +5 -0
  67. package/dist/packem_shared/resolve-target-BRvw8Pf7.mjs +1 -0
  68. package/dist/packem_shared/runAddCommand-BXea8slz.mjs +1 -0
  69. package/dist/packem_shared/runExportCommand-Dq-SpjAe.mjs +5 -0
  70. package/dist/packem_shared/schema-drift-gate-BDCkQ1S6.mjs +1 -0
  71. package/dist/packem_shared/schemaIrToSnapshot-e5fO6GRg.mjs +1 -0
  72. package/dist/packem_shared/shared-D-zCOmgY.mjs +1 -0
  73. package/dist/packem_shared/storage-B0ixDDxG.mjs +1 -0
  74. package/dist/packem_shared/tui-prompts-DzYd2fL3.mjs +4 -0
  75. package/dist/packem_shared/vectorize-metadata-dXpl2_Ar.mjs +1 -0
  76. package/dist/packem_shared/wrangler-name-Dsk5K1f-.mjs +1 -0
  77. package/dist/packem_shared/wrangler-secrets-CCdt0mUl.mjs +1 -0
  78. package/package.json +39 -17
  79. package/skills/README.md +35 -17
  80. package/skills/lunora/SKILL.md +65 -9
  81. package/skills/lunora-deploy/SKILL.md +42 -11
  82. package/skills/lunora-functions/SKILL.md +78 -15
  83. package/skills/lunora-migration-helper/SKILL.md +74 -21
  84. package/skills/lunora-performance-audit/SKILL.md +42 -9
  85. package/skills/lunora-quickstart/SKILL.md +93 -27
  86. package/skills/lunora-realtime/SKILL.md +58 -30
  87. package/skills/lunora-setup-auth/SKILL.md +23 -6
  88. package/skills/lunora-setup-hyperdrive/SKILL.md +33 -13
  89. package/skills/lunora-setup-mail/SKILL.md +34 -28
  90. package/skills/lunora-setup-scheduler/SKILL.md +18 -14
  91. package/skills/lunora-setup-storage/SKILL.md +182 -25
  92. package/dist/packem_shared/COMMANDS-Dwo9q7Bt.mjs +0 -947
  93. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Ck-2bU08.mjs +0 -244
  94. package/dist/packem_shared/admin-url-4UzT-CI4.mjs +0 -19
  95. package/dist/packem_shared/api-spec-CtA6ilu4.mjs +0 -13
  96. package/dist/packem_shared/buildRegistryIndex-BcYe607_.mjs +0 -38
  97. package/dist/packem_shared/command-BC30oSBW.mjs +0 -14
  98. package/dist/packem_shared/commands-hl0mRqqg.mjs +0 -845
  99. package/dist/packem_shared/createLogger-B40gPzQo.mjs +0 -78
  100. package/dist/packem_shared/createRecordingSpawner-DxI3mebw.mjs +0 -43
  101. package/dist/packem_shared/detect-package-manager-DYp7n3mJ.mjs +0 -61
  102. package/dist/packem_shared/diffSnapshots-BeDvvNiF.mjs +0 -161
  103. package/dist/packem_shared/docker-hMQ97KSQ.mjs +0 -21
  104. package/dist/packem_shared/insertSchemaExtension-DAqbfr9Z.mjs +0 -64
  105. package/dist/packem_shared/open-url-Dfq6fAyT.mjs +0 -41
  106. package/dist/packem_shared/output-format-wUvAN6AL.mjs +0 -17
  107. package/dist/packem_shared/parseArgs-YXFuKdEk.mjs +0 -56
  108. package/dist/packem_shared/parseManifest--vZf2FY1.mjs +0 -94
  109. package/dist/packem_shared/resolve-target-qbsJ_5sF.mjs +0 -16
  110. package/dist/packem_shared/runAddCommand-vJdgiR5t.mjs +0 -4
  111. package/dist/packem_shared/schema-drift-gate-BtBt0as0.mjs +0 -79
  112. package/dist/packem_shared/schemaIrToSnapshot-DdsljJT-.mjs +0 -43
  113. package/dist/packem_shared/storage-B7hHSTZP.mjs +0 -84
  114. package/dist/packem_shared/tui-prompts-M6OWsuyw.mjs +0 -663
  115. package/dist/packem_shared/wrangler-name-cy4yhm9j.mjs +0 -12
  116. package/dist/packem_shared/wrangler-secrets-P2_ZUR-k.mjs +0 -47
@@ -1,23 +1,13 @@
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 L,writeFileSync as g,readFileSync as x,readdirSync as ie,rmSync as R,lstatSync as le,mkdtempSync as ce,copyFileSync as Ke,renameSync as qe}from"node:fs";import{tmpdir as de}from"node:os";import{installArgsFor as ue,execArgsFor as Ge,detectFramework as Ye,isInteractive as v,LUNA_ART as Je,LUNA_NAME as Xe,LUNA_SIGNOFF as Qe,BADGES as f,paintAnswer as Ze,detectPackageManager as H,detectInstalledManagers as et,runScriptCommand as tt,detectLintTools as rt,addArgsFor as at,applyLintIgnores as ot}from"@lunora/config";import{walkSync as nt}from"@visulima/fs";import{join as p,dirname as M,basename as N,resolve as pe,relative as he}from"@visulima/path";import{downloadTemplate as me}from"giget";import{modify as st,applyEdits as it}from"jsonc-parser";import{join as z,dirname as lt}from"node:path";import{d as ct}from"../packem_shared/command-DwC11Cwe.mjs";import dt from"magic-string";import{Project as ut,SyntaxKind as w}from"ts-morph";import{P as K}from"../packem_shared/prompt-cancelled-C8Sj7OqI.mjs";import{l as fe,m as pt,n as ge,o as ve,b as ht}from"../packem_shared/resolve-B9ReA3FV.mjs";import{defaultSpawner as we}from"../packem_shared/createRecordingSpawner-DJlNacZ6.mjs";import{d as mt,e as ft,f as gt,a as ye,t as q,g as be,h as vt,b as xe,i as ke,w as wt,j as yt,k as Ce,l as bt}from"../packem_shared/tui-prompts-DzYd2fL3.mjs";import{A as Se,E as Le,p as xt,w as kt,M as Ct,r as St,k as Lt,e as Mt,c as Me,l as Ae,i as At,f as Et}from"../packem_shared/storage-B0ixDDxG.mjs";import{logStep as J}from"../packem_shared/createLogger-hGafwf-3.mjs";import{r as Nt}from"../packem_shared/lint-ignore-report-DKZagpqk.mjs";import _t from"node:dns/promises";import{r as It}from"../packem_shared/commands-I18aR_DJ.mjs";const G={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
+ with:
4
+ version: latest
5
+ `,gitlabImage:"node:22",gitlabProvisionScript:["corepack enable"],installCmd:"pnpm install --frozen-lockfile",lockfile:"pnpm-lock.yaml"},yarn:{githubCacheKey:"yarn",githubSetupStep:"",gitlabImage:"node:22",gitlabProvisionScript:["corepack enable"],installCmd:"yarn install --frozen-lockfile",lockfile:"yarn.lock"}},S=(e,t)=>{const r=Ge(e,"lunora",t);return[r.command,...r.args].join(" ")},X=e=>` - uses: actions/checkout@v4
6
+ ${e.githubSetupStep} - uses: actions/setup-node@v4
7
+ with:
8
+ node-version: 22
9
+ ${e.githubCacheKey===void 0?"":` cache: ${e.githubCacheKey}
10
+ `} - run: ${e.installCmd}`,$t=e=>{const t=G[e],r=t.githubCacheKey===void 0?`# (below) requires it run \`${e} install\` locally and`:`# (below) and the ${e} cache both require it — run \`${e} install\` locally and`;return`name: Deploy
21
11
 
22
12
  on:
23
13
  push:
@@ -25,8 +15,8 @@ on:
25
15
  pull_request:
26
16
  workflow_dispatch:
27
17
 
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
18
+ # Prerequisite: commit your ${t.lockfile}. \`${t.installCmd}\`
19
+ ${r}
30
20
  # commit the lockfile before pushing, or the first CI run fails.
31
21
  #
32
22
  # Set these repository secrets (Settings → Secrets and variables → Actions):
@@ -44,16 +34,10 @@ jobs:
44
34
  permissions:
45
35
  contents: read
46
36
  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
37
+ ${X(t)}
54
38
  # Codegen + wrangler validation gate (no deploy) — fails fast on drift.
55
- - run: pnpm exec lunora prepare
56
- - run: pnpm exec lunora deploy
39
+ - run: ${S(e,["prepare"])}
40
+ - run: ${S(e,["deploy"])}
57
41
 
58
42
  # Preview version on every pull request — uploads a versioned preview URL;
59
43
  # production traffic is untouched.
@@ -63,31 +47,24 @@ jobs:
63
47
  permissions:
64
48
  contents: read
65
49
  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:
50
+ ${X(t)}
51
+ - run: ${S(e,["deploy","--preview"])}
52
+ `},Rt=e=>{const t=G[e],r=[...t.gitlabProvisionScript,t.installCmd].map(a=>` - ${a}`).join(`
53
+ `);return`stages:
76
54
  - deploy
77
55
 
78
- # Prerequisite: commit your pnpm-lock.yaml. \`pnpm install --frozen-lockfile\`
79
- # (below) requires it — run \`pnpm install\` locally and commit the lockfile
56
+ # Prerequisite: commit your ${t.lockfile}. \`${t.installCmd}\`
57
+ # (below) requires it — run \`${e} install\` locally and commit the lockfile
80
58
  # before pushing, or the first pipeline fails.
81
59
  #
82
60
  # Set these as masked CI/CD variables (Settings → CI/CD → Variables):
83
61
  # CLOUDFLARE_API_TOKEN — a Workers-scoped API token
84
62
  # CLOUDFLARE_ACCOUNT_ID — your Cloudflare account id
85
63
  .lunora_base:
86
- image: node:22
64
+ image: ${t.gitlabImage}
87
65
  stage: deploy
88
66
  before_script:
89
- - corepack enable
90
- - pnpm install --frozen-lockfile
67
+ ${r}
91
68
 
92
69
  # Production deploy on the default branch.
93
70
  deploy:
@@ -96,8 +73,8 @@ deploy:
96
73
  - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
97
74
  script:
98
75
  # Codegen + wrangler validation gate (no deploy) — fails fast on drift.
99
- - pnpm exec lunora prepare
100
- - pnpm exec lunora deploy
76
+ - ${S(e,["prepare"])}
77
+ - ${S(e,["deploy"])}
101
78
 
102
79
  # Preview version on every merge request (versioned preview URL; production
103
80
  # traffic is untouched).
@@ -106,287 +83,17 @@ preview:
106
83
  rules:
107
84
  - if: $CI_PIPELINE_SOURCE == "merge_request_event"
108
85
  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
86
+ - ${S(e,["deploy","--preview"])}
87
+ `},Ee={github:{file:z(".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)"}},Tt=(e,t)=>e==="github"?$t(t):Rt(t),Ot=e=>e==="github"||e==="gitlab",Pt=(e,t,r,a={})=>{const o=z(e,Ee[t].file);return m(o)&&a.overwrite!==!0?{path:o,skipped:!0,written:!1}:(L(lt(o),{recursive:!0}),g(o,Tt(t,r),"utf8"),{path:o,skipped:!1,written:!0})},Dt=(e,t,r,a,o={})=>{const n=Ee[t];try{const s=Pt(e,t,r,o);if(s.skipped)a.info(`--ci ${t}: ${n.file} already exists — left unchanged (re-run with overwrite to replace).`);else{const i=ue(r),l=[i.command,...i.args].join(" "),{installCmd:c,lockfile:d}=G[r];a.success(`--ci ${t}: wrote ${n.file}`),a.info(`--ci ${t}: set CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID as ${n.secretsHint} to enable deploys.`),a.info(`--ci ${t}: run \`${l}\` and commit ${d} before pushing — the pipeline runs \`${c}\`.`)}return s}catch(s){const i=s instanceof Error?s.message:String(s);return a.warn(`--ci ${t}: could not write ${n.file} (${i})`),{path:z(e,n.file),skipped:!1,written:!1}}},Bt={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"},jt=e=>{const t=Ye(e);return{...t,adapter:Bt[t.framework]}},$="lunora()",Q='import { lunora } from "@lunora/vite";',Vt=/\blunora\s*\(/u,Ut='"@lunora/vite"',Ft="'@lunora/vite'",Wt=e=>{for(const t of e.getStatements()){if(t.getKind()!==w.ExportAssignment)continue;const r=t.asKindOrThrow(w.ExportAssignment).getExpression();if(r.getKind()!==w.CallExpression)continue;const a=r.asKindOrThrow(w.CallExpression);if(a.getExpression().getText()!=="defineConfig")continue;const o=a.getArguments()[0];if(o?.getKind()===w.ObjectLiteralExpression)return o.asKindOrThrow(w.ObjectLiteralExpression)}},Ht=e=>{for(const t of e.getStatements()){if(t.getKind()!==w.ExportAssignment)continue;const r=t.asKindOrThrow(w.ExportAssignment).getExpression();if(r.getKind()===w.ObjectLiteralExpression)return r.asKindOrThrow(w.ObjectLiteralExpression)}},zt=e=>new ut({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}).createSourceFile("vite.config.ts",e,{overwrite:!0}),Kt=(e,t)=>{const r=t.getImportDeclarations().at(-1)?.getEnd()??0;r===0?e.prepend(`${Q}
88
+ `):e.appendLeft(r,`
89
+ ${Q}`)},qt=(e,t)=>{const r=t.getProperty("plugins");if(r===void 0){const s=t.getProperties(),i=t.getStart()+1;if(s.length===0){e.appendLeft(i,` plugins: [${$}] `);return}const l=s[0];if(l===void 0)return"could not locate the start of the Vite config object's first property";e.appendLeft(l.getStart(),`plugins: [${$}],
90
+ `);return}const a=r.getDescendantsOfKind(w.ArrayLiteralExpression)[0];if(a===void 0)return"the Vite config's `plugins` is not an array literal — add `lunora()` to it by hand";const o=a.getElements();if(o.length===0){e.appendLeft(a.getStart()+1,$);return}const n=o[0];if(n===void 0)return"could not locate the first entry of the Vite config's `plugins` array";e.appendLeft(n.getStart(),`${$}, `)},Ne=e=>{if(Vt.test(e))return{changed:!1,code:e,reason:"lunora plugin already present"};const t=zt(e),r=Wt(t)??Ht(t);if(r===void 0)return{changed:!1,code:e,reason:"could not locate a Vite config plugins array to patch"};const a=new dt(e);!e.includes(Ut)&&!e.includes(Ft)&&Kt(a,t);const o=qt(a,r);return o!==void 0?{changed:!1,code:e,reason:o}:{changed:!0,code:a.toString()}},Gt=/enotfound|eai_again|econnrefused|etimedout|network|fetch failed|getaddrinfo/u,Yt=/404|not found|could not find|no such/u,Jt=(e,t)=>{const r=e instanceof Error?e.message:String(e),a=r.toLowerCase(),o=`failed to download template "${t.templateType}" from ${t.remote}: ${r}`;return Yt.test(a)?{hints:[`Check the template name "${t.templateType}" and the ref "${t.ref}".`,"List/inspect available templates, or target a branch/tag with `--ref <branch>`."],message:`template "${t.templateType}" not found at ${t.remote}: ${r}`}:Gt.test(a)?{hints:["You appear to be offline or unable to reach GitHub.","To scaffold without a network, point at a local template root: `lunora init --from <dir>`."],message:o}:{hints:["If this is a network/offline issue, scaffold from a local root with `lunora init --from <dir>`."],message:o}},T=async(e,t,r)=>{if(v()){await ft(f[e],t,r);return}if(process.stdout.write(`
91
+ `),r===void 0||r===""){J(e,t);return}const a=r.split(`
92
+ `).map(o=>Ze(o)).join(`
93
+ `);J(e,`${t}
94
+ ${a}`)},Xt=async e=>{if(v()){await mt();return}e.info(`
95
+ ${Je}
96
+ ${Xe}: ${Qe}`)},_e=[{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"}],Z=_e.map(e=>e.value),Qt=e=>e==="email"?Le:e,Zt=(e,t)=>{const r=[];for(const a of e.split(",").map(o=>o.trim()).filter(Boolean))Z.includes(a)?r.includes(a)||r.push(a):t(`init: unknown --add feature "${a}" — expected ${Z.join(" | ")}; skipping.`);return r},Ie=e=>e.resolveAuthUiItem===void 0?"auth-ui-react":e.resolveAuthUiItem(),er=async e=>{const t=await Mt(e.select),r=await Me(e.text,e.projectName);return{label:"auth",names:[t],transformManifest:a=>Ae(a,r)}},tr=async e=>{const t=await e.text(Ct,{placeholder:"you@yourdomain.com"}),r=St(t,a=>{e.logger.warn(a)});return{label:"email",names:[Le],transformManifest:r===void 0?void 0:a=>Lt(a,r)}},rr=async(e,t)=>{const r=Ie(e);if(r===void 0){e.logger.error(`init: ${Se}`);return}if(t)return{label:"auth-ui",names:[r]};const a=await Me(e.text,e.projectName);return{label:"auth-ui",names:[r],transformManifest:o=>Ae(o,a)}},ar=async e=>{const t=await xt(e.text,e.projectName);return{label:"storage",names:["storage"],transformManifest:r=>kt(r,t)}},or=(e,t)=>{const r=[];let a=!1;for(const o of t){if(o!=="auth-ui"){r.push({label:o,names:[Qt(o)]});continue}const n=Ie(e);if(n===void 0){e.logger.error(`init: ${Se}`),a=!0;continue}r.push({label:o,names:[n]})}return{plans:r,refused:a}},nr={auth:er,"auth-ui":async(e,t)=>rr(e,t.includes("auth")),email:tr,storage:ar},ee=async e=>{if(e.preselected!==void 0&&e.preselected.length>0){const{plans:a,refused:o}=or(e,e.preselected);return await e.applyAll(a)&&!o}if(!e.interactive)return e.logger.info("tip: add features later with `lunora add <ai|auth|backup|browser|cloudflare-access|crons|email|flags|hyperdrive|payment|presence|queue|storage|workflow>`."),!0;const t=await e.multiSelect("Which features do you want to add?",_e,{defaults:[]});if(t.length===0)return!0;const r=[];for(const a of t){const o=nr[a],n=o?await o(e,t):{label:a,names:[a]};n!==void 0&&r.push(n)}return await e.applyAll(r),!0},sr=[{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"}],ir="Which linter/formatter do you use? We'll tell it to skip Lunora's generated files.",lr=async e=>{const t=e.interactive?await e.multiSelect(ir,sr,{defaults:e.detected}):[...e.detected];if(t.length===0)return[];const r=e.apply(t);return Nt(r,e.logger),r},_="M 259.500 10.552 C 220.080 15.859, 182.424 32.566, 152.500 58.025 C 110.179 94.031, 85.380 137.183, 77.518 188.500 C 75.410 202.255, 74.569 225.677, 75.796 236.466 C 76.757 244.917, 76.683 245.692, 74.518 249.966 C 63.118 272.466, 53.141 303.876, 51.382 322.799 L 50.718 329.943 71.960 320.471 C 83.643 315.262, 93.326 311, 93.478 311 C 93.630 311, 96.547 316.063, 99.959 322.250 C 103.371 328.438, 107.249 334.850, 108.577 336.500 L 110.990 339.500 110.981 336 C 110.977 334.075, 111.499 324.991, 112.143 315.813 L 113.312 299.127 121.406 293.336 C 132.495 285.403, 149.593 271.554, 161 261.268 C 171.556 251.748, 189.116 235, 188.540 235 C 188.337 235, 183.069 238.648, 176.835 243.106 C 142.318 267.789, 68.537 314, 63.646 314 C 61.843 314, 72.791 281.179, 80.905 262.259 C 92.233 235.845, 107.473 212.389, 132.106 183.453 L 138.451 176 148.268 176 C 176.192 176, 197.512 187.154, 212.868 209.797 C 216.470 215.108, 217.035 216.595, 216.477 219.297 C 211.386 243.968, 202.359 274.496, 193.797 296 C 183.898 320.861, 167.147 352.101, 152.395 373.215 L 147.004 380.930 152.891 385.830 C 161.400 392.911, 165.563 396, 166.594 395.998 C 167.092 395.998, 168.772 391.641, 170.327 386.317 C 176.279 365.934, 188.422 338.749, 200.942 317.778 C 223.060 280.731, 256.432 244.369, 294.500 215.836 C 309.956 204.252, 313.937 201.603, 314.719 202.385 C 315.116 202.783, 315.449 213.096, 315.460 225.304 C 315.474 241.855, 315.021 250.405, 313.680 258.924 C 307.009 301.272, 291.175 336.677, 263.112 372 C 255.259 381.883, 227.182 410.673, 218.516 417.727 L 213.532 421.783 223.439 424.880 C 281.705 443.093, 349.165 436.018, 398.616 406.508 C 446.728 377.797, 483.322 331.466, 497.366 281.481 C 503.381 260.075, 504.480 250.741, 504.491 221 C 504.501 191.997, 503.598 184.047, 497.987 163.732 C 484.768 115.871, 452.505 72.708, 407.718 42.964 C 381.051 25.254, 352.818 14.828, 319.695 10.460 C 305.932 8.645, 273.298 8.695, 259.500 10.552",E=`/* The welcome page is a full-bleed starter — reset the browser's default
390
97
  body margin/padding so it sits flush; everything else is scoped under
391
98
  .lunora-welcome (collision-safe). */
392
99
  body {
@@ -491,8 +198,7 @@ body {
491
198
  .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
199
 
493
200
  @media (prefers-reduced-motion: reduce) { .lunora-welcome * { transition: none !important; } }
494
- `;
495
- const REACT_APP = `import { useEffect, useState } from "react";
201
+ `,cr=`import { useEffect, useState } from "react";
496
202
 
497
203
  type Theme = "dark" | "light";
498
204
 
@@ -534,7 +240,7 @@ export default function App() {
534
240
  <div className="lw-wrap">
535
241
  <div className="brand">
536
242
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
537
- <path d="${LOGO_PATH}" fill="currentColor" fillRule="evenodd" />
243
+ <path d="${_}" fill="currentColor" fillRule="evenodd" />
538
244
  </svg>
539
245
  <span className="word">Lunora</span>
540
246
  </div>
@@ -653,8 +359,7 @@ export default function App() {
653
359
  </div>
654
360
  );
655
361
  }
656
- `;
657
- const VUE_APP = `<script setup lang="ts">
362
+ `,dr=`<script setup lang="ts">
658
363
  import { onMounted, ref } from "vue";
659
364
 
660
365
  // Default to "dark" for a stable first paint, then reconcile to the OS
@@ -694,7 +399,7 @@ const toggle = (): void => {
694
399
  <div class="lw-wrap">
695
400
  <div class="brand">
696
401
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
697
- <path d="${LOGO_PATH}" fill="currentColor" fill-rule="evenodd" />
402
+ <path d="${_}" fill="currentColor" fill-rule="evenodd" />
698
403
  </svg>
699
404
  <span class="word">Lunora</span>
700
405
  </div>
@@ -810,8 +515,7 @@ const toggle = (): void => {
810
515
  </div>
811
516
  </div>
812
517
  </template>
813
- `;
814
- const SOLID_APP = `import { createSignal, onMount } from "solid-js";
518
+ `,ur=`import { createSignal, onMount } from "solid-js";
815
519
 
816
520
  export default function App() {
817
521
  // Default to "dark" for a stable first paint, then reconcile to the OS
@@ -851,7 +555,7 @@ export default function App() {
851
555
  <div class="lw-wrap">
852
556
  <div class="brand">
853
557
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
854
- <path d="${LOGO_PATH}" fill="currentColor" fill-rule="evenodd" />
558
+ <path d="${_}" fill="currentColor" fill-rule="evenodd" />
855
559
  </svg>
856
560
  <span class="word">Lunora</span>
857
561
  </div>
@@ -970,8 +674,7 @@ export default function App() {
970
674
  </div>
971
675
  );
972
676
  }
973
- `;
974
- const SVELTE_APP = `<script lang="ts">
677
+ `,pr=`<script lang="ts">
975
678
  import { onMount } from "svelte";
976
679
 
977
680
  // Default to "dark" for a stable first paint, then reconcile to the OS
@@ -1014,7 +717,7 @@ const SVELTE_APP = `<script lang="ts">
1014
717
  <div class="lw-wrap">
1015
718
  <div class="brand">
1016
719
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
1017
- <path d="${LOGO_PATH}" fill="currentColor" fill-rule="evenodd" />
720
+ <path d="${_}" fill="currentColor" fill-rule="evenodd" />
1018
721
  </svg>
1019
722
  <span class="word">Lunora</span>
1020
723
  </div>
@@ -1129,8 +832,7 @@ const SVELTE_APP = `<script lang="ts">
1129
832
  <div class="lw-foot">Running on Lunora · Vite + Svelte</div>
1130
833
  </div>
1131
834
  </div>
1132
- `;
1133
- const VANILLA_MAIN = `import "./style.css";
835
+ `,hr=`import "./style.css";
1134
836
 
1135
837
  import { LunoraClient } from "lunorash/client";
1136
838
 
@@ -1158,7 +860,7 @@ const welcomeHtml = \`
1158
860
  <div class="lw-wrap">
1159
861
  <div class="brand">
1160
862
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
1161
- <path d="${LOGO_PATH}" fill="currentColor" fill-rule="evenodd" />
863
+ <path d="${_}" fill="currentColor" fill-rule="evenodd" />
1162
864
  </svg>
1163
865
  <span class="word">Lunora</span>
1164
866
  </div>
@@ -1294,13 +996,10 @@ toggleButton.addEventListener("click", () => {
1294
996
  // Live demo: the message count of a demo channel re-renders on every delta.
1295
997
  const count = document.querySelector<HTMLSpanElement>("#lw-count")!;
1296
998
 
1297
- client.onUpdate(api.messages.list, { channelId: "channel:demo" }, (result) => {
999
+ client.subscribe(api.messages.list, { channelId: "channel:demo" }, (result) => {
1298
1000
  count.textContent = String(result.messages.length);
1299
1001
  });
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";
1002
+ `,O="const url = (import.meta.env.VITE_LUNORA_URL as string | undefined) ?? globalThis.location.origin;",mr=`import "./index.css";
1304
1003
 
1305
1004
  import { LunoraProvider } from "@lunora/react";
1306
1005
  import { LunoraClient } from "lunorash/client";
@@ -1312,7 +1011,7 @@ import App from "./App.tsx";
1312
1011
  // \`@lunora/vite\` runs the Worker on the same origin as Vite, so default to
1313
1012
  // \`location.origin\`. Point \`VITE_LUNORA_URL\` at a deployed Worker to develop
1314
1013
  // the client against production data.
1315
- ${READ_URL}
1014
+ ${O}
1316
1015
  const client = new LunoraClient({ url });
1317
1016
 
1318
1017
  const root = document.getElementById("root");
@@ -1328,8 +1027,7 @@ createRoot(root).render(
1328
1027
  </LunoraProvider>
1329
1028
  </StrictMode>,
1330
1029
  );
1331
- `;
1332
- const VUE_MAIN = `import "./style.css";
1030
+ `,fr=`import "./style.css";
1333
1031
 
1334
1032
  import { createLunora } from "@lunora/vue";
1335
1033
  import { LunoraClient } from "lunorash/client";
@@ -1338,43 +1036,40 @@ import { createApp } from "vue";
1338
1036
  import App from "./App.vue";
1339
1037
 
1340
1038
  // Provide one LunoraClient at the app root via the Vue plugin form.
1341
- ${READ_URL}
1039
+ ${O}
1342
1040
  createApp(App).use(createLunora(new LunoraClient({ url }))).mount("#app");
1343
- `;
1344
- const SOLID_INDEX = `import "./index.css";
1041
+ `,gr=`import "./index.css";
1345
1042
 
1346
- import { LunoraContext } from "@lunora/solid";
1043
+ import { LunoraProvider } from "@lunora/solid";
1347
1044
  import { LunoraClient } from "lunorash/client";
1348
1045
  import { render } from "solid-js/web";
1349
1046
 
1350
1047
  import App from "./App";
1351
1048
 
1352
- ${READ_URL}
1049
+ ${O}
1353
1050
  const client = new LunoraClient({ url });
1354
1051
  const root = document.getElementById("root");
1355
1052
 
1356
1053
  render(
1357
1054
  () => (
1358
- <LunoraContext.Provider value={client}>
1055
+ <LunoraProvider client={client}>
1359
1056
  <App />
1360
- </LunoraContext.Provider>
1057
+ </LunoraProvider>
1361
1058
  ),
1362
1059
  root!,
1363
1060
  );
1364
- `;
1365
- const SVELTE_ROOT = `<script lang="ts">
1061
+ `,vr=`<script lang="ts">
1366
1062
  import { setLunoraClient } from "@lunora/svelte";
1367
1063
  import { LunoraClient } from "lunorash/client";
1368
1064
 
1369
1065
  import App from "./App.svelte";
1370
1066
 
1371
- ${READ_URL}
1067
+ ${O}
1372
1068
  setLunoraClient(new LunoraClient({ url }));
1373
1069
  <\/script>
1374
1070
 
1375
1071
  <App />
1376
- `;
1377
- const SVELTE_MAIN = `import "./app.css";
1072
+ `,wr=`import "./app.css";
1378
1073
 
1379
1074
  import { mount } from "svelte";
1380
1075
 
@@ -1384,62 +1079,60 @@ import Root from "./Root.svelte";
1384
1079
  const app = mount(Root, { target: document.getElementById("app")! });
1385
1080
 
1386
1081
  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);
1082
+ `,P={react:{adapter:"@lunora/react",createViteTemplate:"react-ts",files:[{contents:mr,path:"src/main.tsx"},{contents:cr,path:"src/App.tsx"},{contents:E,path:"src/index.css"}],label:"React"},solid:{adapter:"@lunora/solid",createViteTemplate:"solid-ts",files:[{contents:gr,path:"src/index.tsx"},{contents:ur,path:"src/App.tsx"},{contents:E,path:"src/index.css"}],label:"Solid"},svelte:{adapter:"@lunora/svelte",createViteTemplate:"svelte-ts",files:[{contents:vr,path:"src/Root.svelte"},{contents:wr,path:"src/main.ts"},{contents:pr,path:"src/App.svelte"},{contents:E,path:"src/app.css"}],label:"Svelte"},vanilla:{adapter:"lunorash/client",createViteTemplate:"vanilla-ts",files:[{contents:hr,path:"src/main.ts"},{contents:E,path:"src/style.css"}],label:"Vanilla"},vue:{adapter:"@lunora/vue",createViteTemplate:"vue-ts",files:[{contents:fr,path:"src/main.ts"},{contents:dr,path:"src/App.vue"},{contents:E,path:"src/style.css"}],label:"Vue"}},D=e=>Object.hasOwn(P,e),yr=`/**
1083
+ * Rate-limit schema extension + plugin.
1084
+ *
1085
+ * Defines the \`ratelimit_buckets\` table used by \`createDbStore\` for durable,
1086
+ * DO-backed rate limiting. Included automatically in every Lunora project.
1087
+ */
1088
+ import type { Middleware } from "lunorash/server";
1089
+ import { defineSchemaExtension, defineTable, definePlugin, v } from "lunorash/server";
1090
+ import { createDbStore, RateLimiter } from "lunorash/ratelimit";
1091
+ import type { RateLimitConfigMap } from "lunorash/ratelimit";
1092
+
1093
+ /**
1094
+ * Named limits this app enforces. This is the one place they live — add your own
1095
+ * and reference them by name from \`rateLimit(limiter, "<name>", …)\` (see
1096
+ * \`lunora/messages.ts\`).
1097
+ */
1098
+ export const limits = {
1099
+ /** Chat writes: 30 per caller per minute, refilling continuously over 60s. */
1100
+ send: { kind: "token bucket", period: 60_000, rate: 30 },
1101
+ } as const satisfies RateLimitConfigMap;
1441
1102
 
1442
- const LUNORA_SCHEMA = `import { defineSchema, defineTable, v } from "lunorash/server";
1103
+ export type LimitName = keyof typeof limits;
1104
+
1105
+ export const makeRateLimiter = (ctx: { db: unknown }): RateLimiter<LimitName> =>
1106
+ new RateLimiter<LimitName>({
1107
+ config: limits,
1108
+ store: createDbStore({ db: ctx.db as never, table: "ratelimit_buckets" }),
1109
+ });
1110
+
1111
+ const middleware: Middleware<{ api?: Record<string, unknown>; db: unknown }, { api: Record<string, unknown>; db: unknown }> = ({ ctx, next }) =>
1112
+ next({
1113
+ ctx: {
1114
+ ...ctx,
1115
+ api: { ...ctx.api, ratelimit: makeRateLimiter(ctx) },
1116
+ },
1117
+ });
1118
+
1119
+ export const ratelimit = definePlugin("ratelimit", {
1120
+ extension: defineSchemaExtension("ratelimit", {
1121
+ tables: {
1122
+ buckets: defineTable({
1123
+ key: v.string(),
1124
+ value: v.number(),
1125
+ ts: v.number(),
1126
+ prev: v.optional(v.number()),
1127
+ })
1128
+ .index("by_key", ["key"])
1129
+ .externallyManaged(),
1130
+ },
1131
+ }),
1132
+ middleware,
1133
+ });
1134
+ `,br=`import { ratelimit } from "./ratelimit/schema.js";
1135
+ import { defineSchema, defineTable, v } from "lunorash/server";
1443
1136
 
1444
1137
  export default defineSchema({
1445
1138
  messages: defineTable({
@@ -1448,25 +1141,40 @@ export default defineSchema({
1448
1141
  })
1449
1142
  .shardBy("channelId")
1450
1143
  .index("by_channel", ["channelId"]),
1451
- });
1452
- `;
1453
- const LUNORA_MESSAGES = `import { RateLimiter, rateLimit } from "@lunora/ratelimit";
1144
+ }).extend(ratelimit.extension);
1145
+ `,xr=`import { rateLimit } from "lunorash/ratelimit";
1454
1146
 
1147
+ import { makeRateLimiter } from "./ratelimit/schema.js";
1148
+ import type { MutationCtx } from "#lunora/_generated/server.js";
1455
1149
  import { mutation, query, v } from "#lunora/_generated/server.js";
1456
1150
 
1457
1151
  /**
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.
1152
+ * The limiter comes from \`lunora/ratelimit/schema.ts\` that file owns the named
1153
+ * limits and the durable store, so tuning \`send\` there is what changes this
1154
+ * procedure's budget. Build it from the generated \`MutationCtx\` so
1155
+ * \`rateLimit(limiter, …)\` infers the full procedure context: \`ctx.auth\`/\`ctx.ip\`
1156
+ * in the key callback and a typed \`ctx.db\` in the handler both depend on it.
1462
1157
  */
1463
- const limiter = new RateLimiter({
1464
- config: {
1465
- send: { kind: "token bucket", period: 60_000, rate: 30 },
1466
- },
1467
- });
1158
+ const limiter = (ctx: MutationCtx) => makeRateLimiter(ctx);
1468
1159
 
1469
- export const list = query.input({ channelId: v.string().meta({ schema: { maxLength: 256 } }), limit: v.optional(v.number()) }).query(async ({ args, ctx }) => {
1160
+ /**
1161
+ * One bucket per caller, not one bucket for the whole app.
1162
+ *
1163
+ * \`ctx.auth.userId\` is \`null\` until you wire auth (\`lunora registry add auth\`),
1164
+ * so the \`ctx.ip\` fallback is what actually keys the limit in a fresh project.
1165
+ * Keying on \`"anon"\` alone would let one script exhaust the budget for every user.
1166
+ *
1167
+ * \`ctx.ip\` is Cloudflare's server-side \`CF-Connecting-IP\` and is populated ONLY
1168
+ * when the app runs on Cloudflare, where the edge stamps that header over
1169
+ * anything the client sent. Deploy this to another target and \`ctx.ip\` is
1170
+ * \`undefined\` by design — the runtime will not pass on a header the caller can
1171
+ * type — so every anonymous caller falls back to the shared \`"anon"\` bucket.
1172
+ * Off Cloudflare, key on something the caller cannot choose (an API key, a
1173
+ * signed session) before relying on this limit.
1174
+ */
1175
+ const byCaller = { key: (ctx: { auth: { userId?: null | string }; ip?: string }): string => ctx.auth.userId ?? ctx.ip ?? "anon" };
1176
+
1177
+ export const list = query.input({ channelId: v.string().max(256), limit: v.optional(v.number()) }).query(async ({ args, ctx }) => {
1470
1178
  const messages = await ctx.db
1471
1179
  .query("messages")
1472
1180
  .withIndex("by_channel", (q) => q.eq("channelId", args.channelId))
@@ -1476,15 +1184,14 @@ export const list = query.input({ channelId: v.string().meta({ schema: { maxLeng
1476
1184
  });
1477
1185
 
1478
1186
  export const send = mutation
1479
- .input({ channelId: v.string().meta({ schema: { maxLength: 256 } }), text: v.string().meta({ schema: { maxLength: 4096 } }) })
1480
- .use(rateLimit(limiter, "send", { key: (ctx) => ctx.auth.userId ?? "anon" }))
1187
+ .input({ channelId: v.string().max(256), text: v.string().max(4096) })
1188
+ .use(rateLimit(limiter, "send", byCaller))
1481
1189
  .mutation(async ({ args, ctx }) => {
1482
1190
  const id = await ctx.db.insert("messages", { channelId: args.channelId, text: args.text });
1483
1191
 
1484
1192
  return { channelId: args.channelId, id, text: args.text };
1485
1193
  });
1486
- `;
1487
- const SERVER_ENTRY = `import type { ShardNamespaceLike } from "lunorash/runtime";
1194
+ `,kr=`import type { ShardNamespaceLike } from "lunorash/runtime";
1488
1195
 
1489
1196
  import { defineApp } from "../lunora/_generated/app.js";
1490
1197
 
@@ -1498,8 +1205,7 @@ const app = defineApp<Env>()
1498
1205
 
1499
1206
  export const ShardDO = app.ShardDO;
1500
1207
  export default app;
1501
- `;
1502
- const WRANGLER = `{
1208
+ `,Cr=`{
1503
1209
  "$schema": "node_modules/wrangler/config-schema.json",
1504
1210
  "name": "__NAME__",
1505
1211
  "main": "src/server.ts",
@@ -1511,983 +1217,47 @@ const WRANGLER = `{
1511
1217
  "migrations": [{ "tag": "v1", "new_sqlite_classes": ["ShardDO"] }],
1512
1218
  "observability": { "enabled": true, "head_sampling_rate": 1 },
1513
1219
  }
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.
1220
+ `,te=[".wrangler",".env",".env.*","!.env.example",".dev.vars",".dev.vars.*","!.dev.vars.example",".lunora/",".lunora-cache","lunora/_generated"],Sr=`# Lunora endpoint for the browser client.
1517
1221
  # Vite statically replaces \`import.meta.env.VITE_LUNORA_URL\` at \`vite dev\` / build.
1518
1222
  # Leave it unset to use the page origin; set it to point at a deployed Worker:
1519
1223
  #
1520
1224
  # 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}
1225
+ `,Lr={"@cloudflare/workers-types":"^4.20260611.1",wrangler:"^4.100.0"},k=(e,t,r,a)=>{const o=p(e,t);L(M(o),{recursive:!0}),g(o,r,"utf8"),a.push(o)},Mr=/\r?\n/,Ar=e=>{const t=p(e,".gitignore"),r=m(t)?x(t,"utf8"):"",a=new Set(r.split(Mr)),o=te.filter(i=>!a.has(i));if(o.length===0)return;const n=o.some(i=>!i.startsWith("!"))?[...o.filter(i=>!i.startsWith("!")),...te.filter(i=>i.startsWith("!"))]:o,s=r.length>0&&!r.endsWith(`
1226
+ `)?`
1227
+ `:"";g(t,`${r}${s}
1542
1228
  # 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";
1229
+ ${n.join(`
1230
+ `)}
1231
+ `,"utf8")},B=e=>e==="lunorash"||e.startsWith("@lunora/"),Er=(e,t,r,a)=>B(e)?a.get(e)??r:t,C=(e,t,r)=>({...e,[t]:r}),re=(e,t,r)=>Object.fromEntries(Object.entries(e).map(([a,o])=>[a,Er(a,o,t,r)])),Nr=async(e,t,r,a)=>{const o=p(e,"package.json"),n=JSON.parse(x(o,"utf8"));let s=C(n.dependencies??{},"lunorash",a);s=C(s,"@lunora/ratelimit",a),r.adapter.startsWith("@lunora/")&&(s=C(s,r.adapter,a));for(const[d,h]of Object.entries(r.extraDependencies??{}))s=C(s,d,h);let i=C(n.devDependencies??{},"@lunora/vite",a);i=C(i,"@lunora/studio",a);for(const[d,h]of Object.entries(Lr))i=C(i,d,h);const l=[...Object.keys(s),...Object.keys(i)].filter(d=>B(d)),c=await fe(l,a);n.name=t,n.imports={...n.imports,"#lunora/*":"./lunora/*"},n.dependencies=re(s,a,c),n.devDependencies=re(i,a,c),n.scripts={...n.scripts,codegen:"lunora codegen",deploy:"vite build && lunora deploy"},g(o,`${JSON.stringify(n,void 0,4)}
1232
+ `,"utf8")},_r=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],$e=e=>_r.map(t=>p(e,t)).find(t=>m(t)),Ir=(e,t)=>{const r=$e(e);if(r===void 0){t.warn("overlay: no vite.config found in the create-vite base — add `lunora()` to your Vite plugins manually.");return}const a=Ne(x(r,"utf8"));a.changed&&g(r,a.code,"utf8")},$r=async e=>{const{adapter:t,distTag:r,logger:a,name:o,target:n}=e,s=[];k(n,p("lunora","ratelimit","schema.ts"),yr,s),k(n,p("lunora","schema.ts"),br,s),k(n,p("lunora","messages.ts"),xr,s),k(n,p("src","server.ts"),kr,s),k(n,"wrangler.jsonc",Cr.replaceAll("__NAME__",o),s),k(n,".env.example",Sr,s);for(const i of t.files)k(n,i.path,i.contents,s);return Ir(n,a),await Nr(n,o,t,r),Ar(n),s},Rr=["lunar","silver","silent","waning","waxing","crescent","cosmic","stellar","orbital","gibbous","twilight","midnight","shimmering","drifting","weightless"],Tr=["moon","tide","crater","comet","eclipse","halo","orbit","nebula","voyager","lander","rover","beacon","harbor","meadow","fox"],ae=e=>e[Math.floor(Math.random()*e.length)],Or=()=>`${ae(Rr)}-${ae(Tr)}`,Pr=async()=>_t.lookup("github.com").then(()=>!0,()=>!1),Dr=/^(?:gh|github):([^/]+)\/([^#/]+)(?:\/[^#]*)?(?:#(.+))?$/,Re=e=>{const t=Dr.exec(e);if(t===null)return;const[,r,a,o]=t;if(!(r===void 0||a===void 0))return{owner:r,ref:o??"HEAD",repo:a}},Br=async e=>{const t=Re(e);if(t===void 0)return;const r=`https://codeload.github.com/${t.owner}/${t.repo}/tar.gz/${t.ref}`;try{const a=await fetch(r,{method:"HEAD"});return a.status===404?!1:a.ok?!0:void 0}catch{return}},Te=async e=>e.isLocal||!(e.source===void 0||Re(e.source)!==void 0)?!0:await Pr()?e.source!==void 0&&await Br(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),b={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?"},jr=new Set([".gitignore",".html",".js",".json",".jsonc",".md",".mjs",".ts",".tsx"]),Vr=`import { defineConfig } from "vite";
1709
1233
  import { lunora } from "@lunora/vite";
1710
1234
 
1711
1235
  export default defineConfig({ plugins: [lunora()] });
1712
- `;
1713
- const SAMPLE_SCHEMA = `import { defineSchema, defineTable, v } from "@lunora/server";
1236
+ `,Ur=`import { defineSchema, defineTable, v } from "@lunora/server";
1714
1237
 
1715
1238
  export default defineSchema({
1716
1239
  messages: defineTable({
1717
- channelId: v.id("channels"),
1240
+ channelId: v.string(),
1718
1241
  text: v.string(),
1719
1242
  })
1720
1243
  .shardBy("channelId")
1721
1244
  .index("by_channel", ["channelId"]),
1722
1245
  });
1723
- `;
1724
- const SAMPLE_FUNCTION = `import { mutation, query, v } from "./_generated/server";
1246
+ `,Fr=`import { mutation, query, v } from "./_generated/server";
1725
1247
 
1726
1248
  export const list = query
1727
- .input({ channelId: v.id("channels"), limit: v.optional(v.number()) })
1249
+ .input({ channelId: v.string(), limit: v.optional(v.number()) })
1728
1250
  .query(async ({ args }) => {
1729
1251
  return { channelId: args.channelId, limit: args.limit ?? 50, messages: [] };
1730
1252
  });
1731
1253
 
1732
1254
  export const send = mutation
1733
- .input({ channelId: v.id("channels"), text: v.string() })
1255
+ .input({ channelId: v.string(), text: v.string() })
1734
1256
  .mutation(async ({ args }) => {
1735
1257
  return { channelId: args.channelId, text: args.text };
1736
1258
  });
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 };
1259
+ `,Wr="gh:anolilab/lunora/templates",Hr=e=>{const t=e.lastIndexOf(".");return t===-1?!1:jr.has(e.slice(t))},zr=/^[a-z0-9_][a-z0-9\-_]*$/u,Kr=/([a-z0-9])([A-Z])/gu,qr=/[^a-z0-9_]/gu,Gr=e=>{const t=e.replaceAll(Kr,"$1-$2").toLowerCase().replaceAll(qr,"-").split("-").filter(r=>r.length>0);return t.length>0?t.join("-"):"my-app"},Yr=(e,t)=>e.replaceAll("{{name}}",t),Jr=async(e,t)=>{const r=new Set;for(const a of e)if(N(a)==="package.json")try{const o=JSON.parse(x(a,"utf8"));for(const n of["dependencies","devDependencies"])for(const s of Object.keys(o[n]??{}))B(s)&&r.add(s)}catch{}return fe(r,t)},Xr=(e,t,r)=>{let a;try{a=JSON.parse(e)}catch{return e}let o=e;for(const n of["dependencies","devDependencies"])for(const s of Object.keys(a[n]??{})){if(!B(s))continue;const i=r.get(s)??t,l=st(o,[n,s],i,{formattingOptions:{insertSpaces:!0,tabSize:4}});o=it(o,l)}return o},Qr=["@parcel/watcher","esbuild","lmdb","msgpackr-extract","rs-module-lexer","sharp","unrs-resolver","vue-demi","workerd"],Zr=["cpu-features","protobufjs","ssh2"],Oe="pnpm-workspace.yaml",ea=()=>["# 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:",...Qr.map(e=>` '${e}': true`),...Zr.map(e=>` '${e}': false`),""].join(`
1260
+ `),j=e=>{const t=[];for(const r of nt(e,{includeDirs:!1,includeFiles:!0}))le(r.path).isSymbolicLink()||t.push(r.path);return t},oe="vitejs/vite",ne=(e,t)=>{for(const r of j(e)){const a=p(t,he(e,r));L(M(a),{recursive:!0}),Ke(r,a)}},Pe=async(e,t,r)=>{const a=j(e),o=[],n=ge(),s=await Jr(a,n);for(const i of a){const l=he(e,i),c=p(t,l);L(M(c),{recursive:!0});const d=x(i);let h=Hr(i)?Yr(d.toString("utf8"),r):void 0;h!==void 0&&N(i)==="package.json"&&(h=Xr(h,n,s)),h===void 0?g(c,d):g(c,h,"utf8"),o.push(c)}return o},F=(e,t,r)=>t!==void 0&&t.length>0?t:`${Wr}/${e}#${ve(r)}`,ta=e=>e.includes("..")?!1:e.startsWith("gh:")||e.startsWith("github:")||e.startsWith("https://"),A=(e,t)=>{e.info(`[dry-run] would ${t}`)},De=(e,t,r)=>(e.error(`init: the template at ${r} contains no files — nothing was scaffolded. Check the template name, \`--source\` layout and \`--ref\`.`),{code:1,files:[],target:t}),Be="Template files copied.",Y=(e,t,r)=>{v()&&process.stdout.write(`
1261
+ `),e.success(`scaffolded ${String(t.length)} files into ${r}`)},ra=(e,t)=>{const{args:r,command:a}=at(e,t);return`${a} ${r.join(" ")}`},je=(e,t)=>{let r=pe(e);for(;;){if(t(r))return!0;const a=M(r);if(a===r)return!1;r=a}},aa=e=>{if(m(p(e,Oe)))return!0;const t=p(e,"package.json");if(!m(t))return!1;try{return JSON.parse(x(t,"utf8")).workspaces!==void 0}catch{return!1}},Ve=e=>je(e,aa),oa=e=>je(e,t=>m(p(t,".git"))),na=async(e,t)=>{if(e.yes===!0||!v()||oa(M(t)))return;if(!await xe(b.git,{badge:f.git,defaultYes:!1})){await ke("Sounds good! You can always run git init manually.");return}if(e.dryRun===!0){A(e.logger,"initialize a git repository");return}const r=e.spawner??we;(await wt("Initializing a git repository…",()=>r({args:["init"],command:"git",cwd:t}))).code===0?await T("git","Initialized an empty git repository."):e.logger.warn("`git init` failed — initialize it yourself later with `git init`.")},sa=async(e,t,r,a)=>{const o=[{code:`cd ./${e}`,lead:"Enter your project directory using"}];t===void 0&&o.push({code:`${r} install`,lead:"Install dependencies with",tail:a?" from the workspace root":void 0}),o.push({code:tt(r,"dev"),lead:"Run",tail:" to start the dev server."},{code:"lunora add",lead:"Add features like auth or storage using"});const n=[{code:"https://lunora.sh/docs",lead:"Read the docs at"},{code:"https://lunora.sh/chat",lead:"Stuck? Join the chat at"}];if(v()){await yt(f.next,b.nextHeader,o,n);return}const s=o.map(i=>`${i.lead} ${i.code}${i.tail??""}`);s.push("",...n.map(i=>`${i.lead} ${i.code}${i.tail??""}`)),await T("next",b.nextHeader,s.join(`
1262
+ `))},ia=e=>e.yes!==!0&&(e.installPrompt!==void 0||v()),la=async(e,t)=>{if(!ia(e)||Ve(M(t)))return;const r=et(e.packageManagerProbe),[a]=r;if(a===void 0)return;if(!await(e.installPrompt?.confirmInstall??(async()=>xe(b.install,{badge:f.deps,defaultYes:!0})))()){await ke("No problem! Remember to install dependencies after setup.");return}let n=a;if(r.length>1&&(n=e.installPrompt?await e.installPrompt.selectManager(r):await q(b.packageManager,r.map(d=>({label:d,value:d})),{badge:f.deps,default:a})??a),e.dryRun===!0){A(e.logger,`install dependencies with ${n}`);return}if(n==="pnpm"){const d=p(t,Oe);m(d)||g(d,ea(),"utf8")}const s=e.spawner??we,{args:i,command:l}=ue(n);await T("deps",`Installing dependencies with ${n}…`);const c=await s({args:i,command:l,cwd:t});if(c.code!==0){e.logger.warn(`\`${l} install\` exited with code ${String(c.code)} — run it yourself in ${N(t)}/.`);return}return await T("deps",`Dependencies installed with ${n}.`),n},ca=async(e,t,r,a,o,n)=>{const s=p(e,t);if(!m(s))return o.error(`template not found in local source: ${s}`),{code:1,files:[],target:r};const i=await Pe(s,r,a);return i.length===0?De(o,r,s):(n(),Y(o,i,r),{code:0,files:i,target:r})},da=async e=>{const{logger:t,markComplete:r,name:a,ref:o,source:n,target:s,templateType:i}=e,l=ce(p(de(),"lunora-init-fetch-")),c=p(l,"template");try{const d=n!==void 0&&n.length>0?o:await ht(o,t),h=F(i,n,d);let u,y=[];if(await Ce([{label:`${i} template fetched`,run:async()=>{u=await me(h,{cwd:l,dir:c,force:!0,install:!1,silent:!0})}},{label:`files copied into ${a}/`,run:async()=>{y=await Pe(c,s,a)}}],{end:Be,start:"Project initializing…"}),y.length===0)return De(t,s,u?.source??h);r();const I=j(c);return v()&&process.stdout.write(`
1263
+ `),t.info(u?.commit?`template: ${u.source} @ ${u.commit} (${String(I.length)} files)`:`template: ${u?.source??h} (${String(I.length)} files)`),Y(t,y,s),{code:0,files:y,target:s}}catch(d){if(d instanceof K)throw d;const{hints:h,message:u}=Jt(d,{ref:ve(o),remote:F(i,n,o),templateType:i});t.error(u);for(const y of h)t.warn(y);return{code:1,files:[],target:s}}finally{R(l,{force:!0,recursive:!0})}},ua=e=>{for(const t of["_gitignore","_npmrc","_gitattributes"]){const r=p(e,t);m(r)&&qe(r,p(e,`.${t.slice(1)}`))}},pa=async e=>{const{framework:t,logger:r,markComplete:a,name:o,overlayBaseFrom:n,target:s}=e,i=P[t],l=ce(p(de(),"lunora-vite-base-"));try{let c;if(n!==void 0&&(c=p(n,`template-${i.createViteTemplate}`),!m(c)))return r.error(`create-vite base not found on disk: ${c}`),{code:1,files:[],target:s};const d=async()=>{if(c!==void 0){ne(c,s);return}const u=p(l,"base"),y=await pt(oe,"main",r),I=`github:${oe}/packages/create-vite/template-${i.createViteTemplate}#${y}`;await me(I,{cwd:l,dir:u,force:!0,install:!1,silent:!0}),ua(u),ne(u,s)};let h=[];return await Ce([{label:`create-vite (${i.label}) base ready`,run:d},{label:`Lunora overlay applied (${i.label})`,run:async()=>{h=await $r({adapter:i,distTag:ge(),logger:r,name:o,target:s})}}],{end:Be,start:"Project initializing…"}),a(),Y(r,h,s),{code:0,files:[...j(s)],target:s}}catch(c){if(c instanceof K)throw c;const d=c instanceof Error?c.message:String(c);return r.error(`failed to scaffold the ${i.label} base: ${d}`),{code:1,files:[],target:s}}finally{R(l,{force:!0,recursive:!0})}},W=(e,t,r,a,o)=>(o.error(`init --in-place: could not ${e} ${t}: ${r instanceof Error?r.message:String(r)}`),{code:1,files:[],target:a}),ha=(e,t)=>{const r=p(e,"vite.config.ts");try{g(r,Vr,"utf8")}catch(a){return W("write",r,a,e,t)}return t.success(`created ${r} with lunora() plugin`),{code:0,files:[r],target:e}},ma=(e,t,r)=>{let a;try{a=x(e,"utf8")}catch(n){return W("read",e,n,t,r)}const o=Ne(a);if(!o.changed)return r.info(`${e}: ${o.reason??"no changes needed"}`),{code:0,files:[],target:t};try{g(e,o.code,"utf8")}catch(n){return W("write",e,n,t,r)}return r.success(`patched ${e} — added lunora() plugin`),{code:0,files:[e],target:t}},fa=(e,t)=>{const r=p(e,"lunora"),a=p(r,"schema.ts");if(m(a))return t.info(`lunora/ already present — left ${a} untouched`),[];const o=[];try{L(r,{recursive:!0}),g(a,Ur,"utf8"),o.push(a);const n=p(r,"messages.ts");m(n)||(g(n,Fr,"utf8"),o.push(n)),t.success(`scaffolded lunora/ (${String(o.length)} file(s))`)}catch(n){const s=n instanceof Error?n.message:String(n);t.error(`init --here: could not scaffold lunora/: ${s}`)}return o},Ue=e=>e==="sveltekit"||e==="nuxt"||e==="astro",ga=(e,t,r)=>{const{adapter:a,class:o,framework:n}=e;r.info(""),r.info(`detected framework: ${n} (class ${o})`),r.info("next steps:");const s=[a,"@lunora/client","@lunora/runtime","@lunora/server"];Ue(n)||s.push("@lunora/vite"),r.info(` 1. install the adapter: ${ra(t,s)}`),r.info(" 2. run codegen: lunora codegen"),o==="A"?(r.info(" 3. compose one worker: wrap your worker entry with"),r.info(" createWorker({ httpRouter: <your framework SSR handler>, shardDO: ShardDO, ... })"),r.info(` 4. add the provider: mount the ${a} provider in your root layout/route`),r.info(" 5. make a loader live: preloadQuery() in a loader, usePreloadedQuery() in the component"),r.info(" see https://lunora.sh/docs/frameworks/reactive-loaders")):o==="B"?(r.info(" 3. inject Lunora: mount Lunora realtime under /_lunora/* in your server hook"),r.info(` (${n} owns its Cloudflare adapter — Lunora composes into its server entry)`),r.info(` 4. add the provider: mount the ${a} provider in your root layout`),r.info(" 5. read the guide: https://lunora.sh/docs/frameworks/deploy")):(r.info(" 3. add the provider: wrap your app with the LunoraProvider from @lunora/react"),r.info(" 4. read the guide: https://lunora.sh/docs/frameworks/bring-your-framework")),r.info("")},va=(e,t,r)=>{if(Ue(t))return r.info(`${t} wires Lunora through its server entry, not a lunora() Vite plugin — leaving the Vite config alone (see next steps)`),{code:0,files:[],target:e};const a=$e(e);return a===void 0?ha(e,r):ma(a,e,r)},wa=(e,t)=>{const r=jt(e),a=va(e,r.framework,t);if(a.code!==0)return a;const o=fa(e,t);return ga(r,H(e),t),{code:0,files:[...a.files,...o],target:e}},ya=e=>e.yes!==!0&&(e.prompt!==void 0||(e.interactive??v())),se=async(e,t,r)=>{r.dryRun!==!0&&await lr({apply:a=>ot(e,a),detected:rt(e),interactive:t,logger:r.logger,multiSelect:r.lintPrompt??((a,o,n)=>be(a,o,{...n,badge:f.add}))})},ba=async(e,t)=>{const r=ya(e),a=e.add===void 0?[]:Zt(e.add,s=>{e.logger.warn(s)}),n={applyAll:async s=>{if(s.length===0)return!0;if(e.dryRun===!0)return A(e.logger,`add ${s.map(u=>u.label).join(", ")}`),!0;const i=[],l=v()?{error:u=>{i.push({level:"error",message:u})},info:()=>{},success:()=>{},warn:u=>{i.push({level:"warn",message:u})}}:e.logger,c=s.map(u=>({running:`adding ${u.label}…`,task:()=>It({allowUnsafeSource:e.allowUnsafeSource,cwd:t,from:e.registryFrom,logger:l,names:[...u.names],ref:e.ref,source:e.registrySource,transformManifest:u.transformManifest,yes:!0})})),d=`added ${s.map(u=>u.label).join(", ")}`,h=await bt(f.add,c,d);for(const{level:u,message:y}of i)e.logger[u](y);return h.every(u=>u.code===0)},interactive:r,logger:e.logger,multiSelect:e.prompt?.multiSelect??((s,i,l)=>be(s,i,{...l,badge:f.add})),preselected:a.length>0?a:void 0,projectName:N(t),resolveAuthUiItem:()=>{let s;try{const i=JSON.parse(x(p(t,"package.json"),"utf8"));s={...i.dependencies,...i.devDependencies}}catch{return"auth-ui-react"}if(!At(s))return Et(s)??"auth-ui-react"},select:e.prompt?.select??((s,i,l)=>q(s,i,{...l,badge:f.add})),text:e.prompt?.text??((s,i)=>ye(s,{...i,badge:f.add}))};if(a.length>0){const s=await ee(n);return await se(t,r,e),s}return v()&&await vt(b.extras),await ee(n),await se(t,r,e),!0},V="react",Fe=[{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 (islands) — single-worker, Lunora composed into the adapter 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 — single-worker, Lunora composed into the adapter 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"}],We=Object.keys(P).join("|"),He=Fe.filter(e=>!D(e.value)).map(e=>e.value),ze=He.join("|"),xa=e=>D(e)?{framework:e,kind:"overlay"}:{kind:"template",templateType:e},ka=async e=>e.vite!==void 0?{framework:e.vite,kind:"overlay"}:e.templateType!==void 0?{kind:"template",templateType:e.templateType}:!v()||e.yes===!0?{framework:V,kind:"overlay"}:xa(await q(b.framework,Fe,{badge:f.tmpl,default:V})??V),Ca=e=>{if(v()||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 <${We}>\` for an SPA, or \`-t <${ze}>\` 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.`},Sa=async(e,t,r,a,o)=>D(t)?await Te({isLocal:e.overlayBaseFrom!==void 0,logger:e.logger})?(L(a,{recursive:!0}),pa({framework:t,logger:e.logger,markComplete:o,name:r,overlayBaseFrom:e.overlayBaseFrom,target:a})):{code:1,files:[],target:a}:(e.logger.error(`init: unknown framework "${t}". Supported overlays: ${Object.keys(P).join(", ")}.`),{code:1,files:[],target:a}),La=async(e,t,r,a,o)=>e.from!==void 0?await ca(e.from,t,a,r,e.logger,o):e.source!==void 0&&e.source.length>0&&!e.allowUnsafeSource&&!ta(e.source)?(e.logger.error(`init: refusing --source ${e.source} — only gh:, github:, or https:// sources are allowed (and may not contain ".."). Re-run with --allow-unsafe-source if you really want this.`),{code:1,files:[],target:a}):await Te({isLocal:!1,logger:e.logger,source:F(t,e.source,e.ref)})?da({logger:e.logger,markComplete:o,name:r,ref:e.ref,source:e.source,target:a,templateType:t}):{code:1,files:[],target:a},Ma=async(e,t,r)=>{await gt("realtime backend on Cloudflare Workers + Durable Objects");const a=Ca(e);if(a!==void 0)return e.logger.error(a),{code:1,files:[],target:""};const o=Or(),n=e.name??await ye(b.name,{badge:f.dir,default:o,placeholder:o}),s=await ka(e),i=n.trim();if(i.length===0)return e.logger.error("init: refusing an empty project name — pass a directory name (e.g. `lunora init my-app`)."),{code:1,files:[],target:""};if(i.includes("/")||i.includes("\\")||i===".."||i===".")return e.logger.error(`init: refusing project name "${i}" — must not contain path separators or be "." / "..".`),{code:1,files:[],target:""};if(!zr.test(i))return e.logger.error(`init: refusing project name "${i}" — a Cloudflare Worker name must be lowercase letters, digits, "-" or "_" (starting with a letter, digit or "_"), and wrangler rejects anything else. Try \`${Gr(i)}\`.`),{code:1,files:[],target:""};const l=pe(t,i),c=le(l,{throwIfNoEntry:!1});if(c?.isSymbolicLink()===!0)return e.logger.error(`init: refusing to scaffold into "${l}" — it is a symlink. Remove it, or scaffold into a different directory name.`),{code:1,files:[],target:l};const d=c!==void 0;if(d&&ie(l).length>0)return e.logger.error(`target directory not empty: ${l}`),{code:1,files:[],target:l};if(e.dryRun===!0){const h=s.kind==="overlay"?`the ${s.framework} create-vite overlay`:`the ${s.templateType} template`;return A(e.logger,`scaffold ${h} into ${l}`),{code:0,files:[],target:l}}return r.record(l,d),s.kind==="overlay"?Sa(e,s.framework,i,l,r.complete):La(e,s.templateType,i,l,r.complete)},U=(e,t)=>{const{target:r,targetPreExisted:a}=e;if(!(r===void 0||!m(r))){if(a===!0)for(const o of ie(r))R(p(r,o),{force:!0,recursive:!0});else R(r,{force:!0,recursive:!0});t.info(`removed the partially-created project at ${r}`)}},Aa=async(e,t,r)=>e.inPlace!==!0?Ma(e,t,r):e.dryRun===!0?(A(e.logger,`configure Lunora into ${t}`),{code:0,files:[],target:t}):wa(t,e.logger),Ea=async(e,t,r)=>{const a=await ba(e,t.target),o=e.inPlace===!0?void 0:await la(e,t.target);if(e.inPlace!==!0){await na(e,t.target);const n=o??H(t.target);await sa(N(t.target),o,n,Ve(r)),await Xt(e.logger)}return a},Na=(e,t,r)=>{if(t.code!==0||e.ci===void 0)return;if(e.dryRun===!0){A(e.logger,`scaffold a ${e.ci} CI deploy pipeline`);return}const a=e.inPlace===!0?r:t.target;try{const o=H(a);Dt(a,e.ci,o,e.logger)}catch{e.logger.warn(`--ci ${e.ci}: could not detect a package manager for this project — skipped the CI pipeline.`)}},_a=async e=>{const t=e.cwd??process.cwd(),r={};let a;try{a=await Aa(e,t,{complete:()=>{r.target=void 0},record:(o,n)=>{r.target=o,r.targetPreExisted=n}}),a.code===0&&a.target!==""?(r.target=void 0,await Ea(e,a,t)||(a={...a,code:1})):a.code!==0&&U(r,e.logger)}catch(o){if(o instanceof K)return U(r,e.logger),process.stdout.write("\n ✖ Setup cancelled — run `lunora init` again whenever you're ready. 🌙\n"),{code:130,files:[],target:""};throw U(r,e.logger),o}return Na(e,a,t),a},Ia=e=>typeof e=="string"&&He.includes(e),$a=(e,t)=>{if(e!==void 0){if(Ot(e))return e;t.warn(`init: unknown --ci "${e}" — expected github | gitlab; skipping CI scaffold.`)}},Ra=e=>e===void 0?{}:Ia(e)?{templateType:e}:D(e)?{vite:e}:{error:`init: unknown --template "${e}" — expected a bespoke template (${ze}) or an overlay framework (${We}).`},eo=ct(({argument:e,cwd:t,logger:r,options:a})=>{const o=Ra(a.template);return"error"in o?(r.error(o.error),{code:1}):_a({add:a.add,allowUnsafeSource:a.allowUnsafeSource===!0,cwd:t,ci:$a(a.ci,r),dryRun:a.dryRun===!0,from:a.from,inPlace:a.here===!0,interactive:a.interactive===!0?!0:void 0,logger:r,name:e[0],ref:a.ref,source:a.source,templateType:o.templateType,vite:a.vite??o.vite,yes:a.yes===!0})});export{eo as execute,Ia as isTemplate,Ra as resolveTemplateFlag,F as resolveTemplateSource,_a as runInitCommand};