@lunora/cli 1.0.0-alpha.32 → 1.0.0-alpha.320

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 (122) hide show
  1. package/LICENSE.md +33 -0
  2. package/README.md +1 -1
  3. package/dist/bin.mjs +2 -10
  4. package/dist/index.d.mts +960 -370
  5. package/dist/index.d.ts +960 -370
  6. package/dist/index.mjs +1 -19
  7. package/dist/packem_chunks/dispatch.mjs +1 -0
  8. package/dist/packem_chunks/handler.mjs +1 -160
  9. package/dist/packem_chunks/handler10.mjs +1 -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 -80
  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 +1 -114
  20. package/dist/packem_chunks/handler20.mjs +1 -94
  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 -541
  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 -1430
  38. package/dist/packem_chunks/runResetCommand.mjs +1 -41
  39. package/dist/packem_chunks/runRpcCommand.mjs +1 -68
  40. package/dist/packem_shared/COMMANDS-DdaAWPtr.mjs +1 -0
  41. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-BgMPHEoe.mjs +1 -0
  42. package/dist/packem_shared/EXIT_CODE-08cwt3MK.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-Dc8D8AR6.mjs +1 -0
  47. package/dist/packem_shared/catalog-CahzmDLV.mjs +1 -0
  48. package/dist/packem_shared/cli-DOpChqUe.mjs +2 -0
  49. package/dist/packem_shared/codegen-error-AmH54ofi.mjs +3 -0
  50. package/dist/packem_shared/command-Mmxzxyr5.mjs +1 -0
  51. package/dist/packem_shared/commands-CNqednoX.mjs +13 -0
  52. package/dist/packem_shared/createLogger-Cl18I8AX.mjs +2 -0
  53. package/dist/packem_shared/createRecordingSpawner-sS7LEN7x.mjs +1 -0
  54. package/dist/packem_shared/deploy-target-DCWwiuAe.mjs +1 -0
  55. package/dist/packem_shared/diffSnapshots-WWwx-KvZ.mjs +5 -0
  56. package/dist/packem_shared/docker-DpVxvYpL.mjs +1 -0
  57. package/dist/packem_shared/import-D7qdpSmJ.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/parseManifest-CwPTKdtS.mjs +1 -0
  62. package/dist/packem_shared/path-containment-CgxYZggb.mjs +1 -0
  63. package/dist/packem_shared/platform-diagnostics-Cn2g6Jh-.mjs +4 -0
  64. package/dist/packem_shared/prompt-cancelled-BvsNxg_Q.mjs +1 -0
  65. package/dist/packem_shared/render-lunora-error--4tmM6mt.mjs +3 -0
  66. package/dist/packem_shared/resolve-DUCSc7jQ.mjs +5 -0
  67. package/dist/packem_shared/resolve-target-C_ZloTvd.mjs +1 -0
  68. package/dist/packem_shared/runAddCommand-Cf2q2y27.mjs +1 -0
  69. package/dist/packem_shared/runExportCommand-DxsJHYZt.mjs +5 -0
  70. package/dist/packem_shared/runMigrateGenerateCommand-CDHswpMU.mjs +11 -0
  71. package/dist/packem_shared/schema-drift-gate-BDCkQ1S6.mjs +1 -0
  72. package/dist/packem_shared/schemaIrToSnapshot-BjK-0IRo.mjs +1 -0
  73. package/dist/packem_shared/shared-D-zCOmgY.mjs +1 -0
  74. package/dist/packem_shared/storage-J4xhM4FU.mjs +1 -0
  75. package/dist/packem_shared/tui-prompts-B3YwUhGw.mjs +4 -0
  76. package/dist/packem_shared/vectorize-metadata-dXpl2_Ar.mjs +1 -0
  77. package/dist/packem_shared/wrangler-name-Dsk5K1f-.mjs +1 -0
  78. package/dist/packem_shared/wrangler-secrets-C9lJnd5N.mjs +1 -0
  79. package/package.json +39 -19
  80. package/skills/README.md +35 -17
  81. package/skills/lunora/SKILL.md +123 -9
  82. package/skills/lunora-create-package/SKILL.md +4 -3
  83. package/skills/lunora-deploy/SKILL.md +42 -11
  84. package/skills/lunora-functions/SKILL.md +120 -15
  85. package/skills/lunora-migration-helper/SKILL.md +74 -21
  86. package/skills/lunora-performance-audit/SKILL.md +78 -9
  87. package/skills/lunora-quickstart/SKILL.md +93 -27
  88. package/skills/lunora-realtime/SKILL.md +73 -39
  89. package/skills/lunora-setup-auth/SKILL.md +33 -6
  90. package/skills/lunora-setup-hyperdrive/SKILL.md +33 -13
  91. package/skills/lunora-setup-hyperdrive-global/SKILL.md +5 -0
  92. package/skills/lunora-setup-mail/SKILL.md +34 -28
  93. package/skills/lunora-setup-scheduler/SKILL.md +18 -14
  94. package/skills/lunora-setup-storage/SKILL.md +182 -25
  95. package/dist/packem_chunks/runMigrateGenerateCommand.mjs +0 -397
  96. package/dist/packem_shared/COMMANDS-B0ftFD_3.mjs +0 -948
  97. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Ck-2bU08.mjs +0 -244
  98. package/dist/packem_shared/admin-url-4UzT-CI4.mjs +0 -19
  99. package/dist/packem_shared/api-spec-CtA6ilu4.mjs +0 -13
  100. package/dist/packem_shared/buildRegistryIndex-BcYe607_.mjs +0 -38
  101. package/dist/packem_shared/codegen-error-DJG-ghs_.mjs +0 -31
  102. package/dist/packem_shared/command-D3lB_4Az.mjs +0 -19
  103. package/dist/packem_shared/commands-B-gR09Z_.mjs +0 -845
  104. package/dist/packem_shared/createLogger-B40gPzQo.mjs +0 -78
  105. package/dist/packem_shared/createRecordingSpawner-DxI3mebw.mjs +0 -43
  106. package/dist/packem_shared/detect-package-manager-DYp7n3mJ.mjs +0 -61
  107. package/dist/packem_shared/diffSnapshots-BeDvvNiF.mjs +0 -161
  108. package/dist/packem_shared/docker-hMQ97KSQ.mjs +0 -21
  109. package/dist/packem_shared/insertSchemaExtension-DAqbfr9Z.mjs +0 -64
  110. package/dist/packem_shared/open-url-Dfq6fAyT.mjs +0 -41
  111. package/dist/packem_shared/output-format-wUvAN6AL.mjs +0 -17
  112. package/dist/packem_shared/parseArgs-YXFuKdEk.mjs +0 -56
  113. package/dist/packem_shared/parseManifest--vZf2FY1.mjs +0 -94
  114. package/dist/packem_shared/prompt-cancelled-APzX1Im-.mjs +0 -9
  115. package/dist/packem_shared/resolve-target-qbsJ_5sF.mjs +0 -16
  116. package/dist/packem_shared/runAddCommand-bnY6-HKb.mjs +0 -4
  117. package/dist/packem_shared/schema-drift-gate-BtBt0as0.mjs +0 -79
  118. package/dist/packem_shared/schemaIrToSnapshot-DdsljJT-.mjs +0 -43
  119. package/dist/packem_shared/storage-BIsph-Vk.mjs +0 -84
  120. package/dist/packem_shared/tui-prompts-BjEN8XgP.mjs +0 -658
  121. package/dist/packem_shared/wrangler-name-cy4yhm9j.mjs +0 -12
  122. package/dist/packem_shared/wrangler-secrets-P2_ZUR-k.mjs +0 -47
@@ -1,24 +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-D3lB_4Az.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 { P as PromptCancelledError } from '../packem_shared/prompt-cancelled-APzX1Im-.mjs';
14
- import { c as resolveTagVersions, d as resolveSourceRef, e as resolveDistTag, r as runAddCommand } from '../packem_shared/commands-B-gR09Z_.mjs';
15
- import { defaultSpawner } from '../packem_shared/createRecordingSpawner-DxI3mebw.mjs';
16
- import { d as tuiMascot, e as tuiStep, 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-BjEN8XgP.mjs';
17
- import { logStep } from '../packem_shared/createLogger-B40gPzQo.mjs';
18
- 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-BIsph-Vk.mjs';
19
- import dns from 'node:dns/promises';
20
-
21
- const GITHUB_CONTENT = `name: Deploy
1
+ import{existsSync as m,mkdirSync as M,writeFileSync as w,readFileSync as k,readdirSync as ce,rmSync as O,lstatSync as de,mkdtempSync as ue,copyFileSync as Ge,renameSync as Ye}from"node:fs";import{tmpdir as pe}from"node:os";import{installArgsFor as he,execArgsFor as Je,detectFramework as Xe,isInteractive as y,LUNA_ART as Qe,LUNA_NAME as Ze,LUNA_SIGNOFF as et,BADGES as v,paintAnswer as tt,detectPackageManager as P,detectInstalledManagers as rt,runScriptCommand as at,detectLintTools as ot,addArgsFor as nt,applyLintIgnores as st}from"@lunora/config";import{walkSync as it}from"@visulima/fs";import{join as p,dirname as A,basename as _,resolve as me,relative as fe}from"@visulima/path";import{downloadTemplate as ge}from"giget";import{modify as lt,applyEdits as ct}from"jsonc-parser";import{join as K,dirname as dt}from"node:path";import{d as ut}from"../packem_shared/command-Mmxzxyr5.mjs";import{EXIT_CODE as f}from"../packem_shared/EXIT_CODE-08cwt3MK.mjs";import pt from"magic-string";import{Project as ht,SyntaxKind as g}from"ts-morph";import{P as q}from"../packem_shared/prompt-cancelled-BvsNxg_Q.mjs";import{m as ve,n as mt,o as we,q as ye,b as ft}from"../packem_shared/resolve-DUCSc7jQ.mjs";import{defaultSpawner as be}from"../packem_shared/createRecordingSpawner-sS7LEN7x.mjs";import{d as gt,e as vt,f as wt,a as xe,t as G,g as ke,h as yt,b as Ce,i as Se,w as bt,j as xt,k as Le,l as kt}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{A as Me,E as Ae,p as Ct,w as St,M as Lt,r as Mt,k as At,e as Et,c as Ee,l as Ne,i as Nt,f as _t}from"../packem_shared/storage-J4xhM4FU.mjs";import{r as It}from"../packem_shared/commands-CNqednoX.mjs";import{logStep as Q}from"../packem_shared/createLogger-Cl18I8AX.mjs";import{r as $t}from"../packem_shared/lint-ignore-report-DKZagpqk.mjs";import Rt from"node:dns/promises";const Y={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"}},L=(e,t)=>{const r=Je(e,"lunora",t);return[r.command,...r.args].join(" ")},Z=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}`,Ot=e=>{const t=Y[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
22
11
 
23
12
  on:
24
13
  push:
@@ -26,8 +15,8 @@ on:
26
15
  pull_request:
27
16
  workflow_dispatch:
28
17
 
29
- # Prerequisite: commit your pnpm-lock.yaml. \`pnpm install --frozen-lockfile\`
30
- # (below) and the pnpm cache both require it — run \`pnpm install\` locally and
18
+ # Prerequisite: commit your ${t.lockfile}. \`${t.installCmd}\`
19
+ ${r}
31
20
  # commit the lockfile before pushing, or the first CI run fails.
32
21
  #
33
22
  # Set these repository secrets (Settings → Secrets and variables → Actions):
@@ -45,16 +34,10 @@ jobs:
45
34
  permissions:
46
35
  contents: read
47
36
  steps:
48
- - uses: actions/checkout@v4
49
- - uses: pnpm/action-setup@v4
50
- - uses: actions/setup-node@v4
51
- with:
52
- node-version: 22
53
- cache: pnpm
54
- - run: pnpm install --frozen-lockfile
37
+ ${Z(t)}
55
38
  # Codegen + wrangler validation gate (no deploy) — fails fast on drift.
56
- - run: pnpm exec lunora prepare
57
- - run: pnpm exec lunora deploy
39
+ - run: ${L(e,["prepare"])}
40
+ - run: ${L(e,["deploy"])}
58
41
 
59
42
  # Preview version on every pull request — uploads a versioned preview URL;
60
43
  # production traffic is untouched.
@@ -64,31 +47,24 @@ jobs:
64
47
  permissions:
65
48
  contents: read
66
49
  steps:
67
- - uses: actions/checkout@v4
68
- - uses: pnpm/action-setup@v4
69
- - uses: actions/setup-node@v4
70
- with:
71
- node-version: 22
72
- cache: pnpm
73
- - run: pnpm install --frozen-lockfile
74
- - run: pnpm exec lunora deploy --preview
75
- `;
76
- const GITLAB_CONTENT = `stages:
50
+ ${Z(t)}
51
+ - run: ${L(e,["deploy","--preview"])}
52
+ `},Tt=e=>{const t=Y[e],r=[...t.gitlabProvisionScript,t.installCmd].map(a=>` - ${a}`).join(`
53
+ `);return`stages:
77
54
  - deploy
78
55
 
79
- # Prerequisite: commit your pnpm-lock.yaml. \`pnpm install --frozen-lockfile\`
80
- # (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
81
58
  # before pushing, or the first pipeline fails.
82
59
  #
83
60
  # Set these as masked CI/CD variables (Settings → CI/CD → Variables):
84
61
  # CLOUDFLARE_API_TOKEN — a Workers-scoped API token
85
62
  # CLOUDFLARE_ACCOUNT_ID — your Cloudflare account id
86
63
  .lunora_base:
87
- image: node:22
64
+ image: ${t.gitlabImage}
88
65
  stage: deploy
89
66
  before_script:
90
- - corepack enable
91
- - pnpm install --frozen-lockfile
67
+ ${r}
92
68
 
93
69
  # Production deploy on the default branch.
94
70
  deploy:
@@ -97,8 +73,8 @@ deploy:
97
73
  - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
98
74
  script:
99
75
  # Codegen + wrangler validation gate (no deploy) — fails fast on drift.
100
- - pnpm exec lunora prepare
101
- - pnpm exec lunora deploy
76
+ - ${L(e,["prepare"])}
77
+ - ${L(e,["deploy"])}
102
78
 
103
79
  # Preview version on every merge request (versioned preview URL; production
104
80
  # traffic is untouched).
@@ -107,317 +83,17 @@ preview:
107
83
  rules:
108
84
  - if: $CI_PIPELINE_SOURCE == "merge_request_event"
109
85
  script:
110
- - pnpm exec lunora deploy --preview
111
- `;
112
- const WORKFLOWS = {
113
- github: {
114
- content: GITHUB_CONTENT,
115
- file: join(".github", "workflows", "deploy.yml"),
116
- secretsHint: "repository secrets (Settings → Secrets and variables → Actions)"
117
- },
118
- gitlab: {
119
- content: GITLAB_CONTENT,
120
- file: ".gitlab-ci.yml",
121
- secretsHint: "masked CI/CD variables (Settings → CI/CD → Variables)"
122
- }
123
- };
124
- const isCiProvider = (value) => value === "github" || value === "gitlab";
125
- const writeCiWorkflow = (projectRoot, provider, options = {}) => {
126
- const spec = WORKFLOWS[provider];
127
- const path = join(projectRoot, spec.file);
128
- if (existsSync(path) && options.overwrite !== true) {
129
- return { path, skipped: true, written: false };
130
- }
131
- mkdirSync(dirname(path), { recursive: true });
132
- writeFileSync(path, spec.content, "utf8");
133
- return { path, skipped: false, written: true };
134
- };
135
- const scaffoldCiWorkflow = (projectRoot, provider, logger, options = {}) => {
136
- const spec = WORKFLOWS[provider];
137
- try {
138
- const result = writeCiWorkflow(projectRoot, provider, options);
139
- if (result.skipped) {
140
- logger.info(`--ci ${provider}: ${spec.file} already exists — left unchanged (re-run with overwrite to replace).`);
141
- } else {
142
- logger.success(`--ci ${provider}: wrote ${spec.file}`);
143
- logger.info(`--ci ${provider}: set CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID as ${spec.secretsHint} to enable deploys.`);
144
- logger.info(
145
- `--ci ${provider}: run \`pnpm install\` and commit pnpm-lock.yaml before pushing — the pipeline runs \`pnpm install --frozen-lockfile\`.`
146
- );
147
- }
148
- return result;
149
- } catch (error) {
150
- const message = error instanceof Error ? error.message : String(error);
151
- logger.warn(`--ci ${provider}: could not write ${spec.file} (${message})`);
152
- return { path: join(projectRoot, spec.file), skipped: false, written: false };
153
- }
154
- };
155
-
156
- const ADAPTER_BY_FRAMEWORK = {
157
- astro: "@lunora/react",
158
- none: "@lunora/react",
159
- nuxt: "@lunora/vue",
160
- "react-router": "@lunora/react",
161
- "solid-start": "@lunora/solid",
162
- sveltekit: "@lunora/svelte",
163
- "tanstack-start": "@lunora/react",
164
- "tanstack-start-solid": "@lunora/solid"
165
- };
166
- const detectFramework = (root) => {
167
- const base = detectFramework$1(root);
168
- return { ...base, adapter: ADAPTER_BY_FRAMEWORK[base.framework] };
169
- };
170
-
171
- const LUNORA_CALL = "lunora()";
172
- const LUNORA_IMPORT = 'import { lunora } from "@lunora/vite";';
173
- const LUNORA_CALL_RE = /\blunora\s*\(/u;
174
- const LUNORA_VITE_DOUBLE = '"@lunora/vite"';
175
- const LUNORA_VITE_SINGLE = "'@lunora/vite'";
176
- const findDefineConfigObject = (sf) => {
177
- for (const statement of sf.getStatements()) {
178
- if (statement.getKind() !== SyntaxKind.ExportAssignment) {
179
- continue;
180
- }
181
- const expr = statement.asKindOrThrow(SyntaxKind.ExportAssignment).getExpression();
182
- if (expr.getKind() !== SyntaxKind.CallExpression) {
183
- continue;
184
- }
185
- const call = expr.asKindOrThrow(SyntaxKind.CallExpression);
186
- if (call.getExpression().getText() !== "defineConfig") {
187
- continue;
188
- }
189
- const argument = call.getArguments()[0];
190
- if (argument?.getKind() === SyntaxKind.ObjectLiteralExpression) {
191
- return argument.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);
192
- }
193
- }
194
- return void 0;
195
- };
196
- const findPlainExportObject = (sf) => {
197
- for (const statement of sf.getStatements()) {
198
- if (statement.getKind() !== SyntaxKind.ExportAssignment) {
199
- continue;
200
- }
201
- const expr = statement.asKindOrThrow(SyntaxKind.ExportAssignment).getExpression();
202
- if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {
203
- return expr.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);
204
- }
205
- }
206
- return void 0;
207
- };
208
- const findConfigObject = (sourceText) => {
209
- const project = new Project({
210
- compilerOptions: { allowJs: true },
211
- useInMemoryFileSystem: true
212
- });
213
- const sf = project.createSourceFile("vite.config.ts", sourceText, { overwrite: true });
214
- return findDefineConfigObject(sf) ?? findPlainExportObject(sf);
215
- };
216
- const importInsertPosition = (sourceText) => {
217
- const project = new Project({
218
- compilerOptions: { allowJs: true },
219
- useInMemoryFileSystem: true
220
- });
221
- const sf = project.createSourceFile("vite.config.ts", sourceText, { overwrite: true });
222
- const imports = sf.getImportDeclarations();
223
- if (imports.length === 0) {
224
- return 0;
225
- }
226
- const last = imports[imports.length - 1];
227
- if (last === void 0) {
228
- return 0;
229
- }
230
- return last.getEnd();
231
- };
232
- const addImport = (ms, source) => {
233
- const insertAt = importInsertPosition(source);
234
- if (insertAt === 0) {
235
- ms.prepend(`${LUNORA_IMPORT}
236
- `);
237
- } else {
238
- ms.appendLeft(insertAt, `
239
- ${LUNORA_IMPORT}`);
240
- }
241
- };
242
- const patchPluginsArray = (ms, configObject) => {
243
- const pluginsProp = configObject.getProperty("plugins");
244
- if (pluginsProp === void 0) {
245
- const properties = configObject.getProperties();
246
- const openBrace = configObject.getStart() + 1;
247
- if (properties.length === 0) {
248
- ms.appendLeft(openBrace, ` plugins: [${LUNORA_CALL}] `);
249
- } else {
250
- const firstProp = properties[0];
251
- if (firstProp !== void 0) {
252
- ms.appendLeft(firstProp.getStart(), `plugins: [${LUNORA_CALL}],
253
- `);
254
- }
255
- }
256
- return;
257
- }
258
- const arrayLit = pluginsProp.getDescendantsOfKind(SyntaxKind.ArrayLiteralExpression)[0];
259
- if (arrayLit === void 0) {
260
- return;
261
- }
262
- const elements = arrayLit.getElements();
263
- if (elements.length === 0) {
264
- ms.appendLeft(arrayLit.getStart() + 1, LUNORA_CALL);
265
- } else {
266
- const firstElement = elements[0];
267
- if (firstElement !== void 0) {
268
- ms.appendLeft(firstElement.getStart(), `${LUNORA_CALL}, `);
269
- }
270
- }
271
- };
272
- const patchViteConfig = (source) => {
273
- if (LUNORA_CALL_RE.test(source)) {
274
- return { changed: false, code: source, reason: "lunora plugin already present" };
275
- }
276
- const configObject = findConfigObject(source);
277
- if (configObject === void 0) {
278
- return { changed: false, code: source, reason: "could not locate a Vite config plugins array to patch" };
279
- }
280
- const ms = new MagicString(source);
281
- const alreadyImported = source.includes(LUNORA_VITE_DOUBLE) || source.includes(LUNORA_VITE_SINGLE);
282
- if (alreadyImported) {
283
- patchPluginsArray(ms, configObject);
284
- } else {
285
- addImport(ms, source);
286
- patchPluginsArray(ms, configObject);
287
- }
288
- return { changed: true, code: ms.toString() };
289
- };
290
-
291
- const NETWORK_ERROR_PATTERN = /enotfound|eai_again|econnrefused|etimedout|network|fetch failed|getaddrinfo/u;
292
- const NOT_FOUND_ERROR_PATTERN = /404|not found|could not find|no such/u;
293
- const describeDownloadFailure = (error, context) => {
294
- const raw = error instanceof Error ? error.message : String(error);
295
- const lower = raw.toLowerCase();
296
- const genericMessage = `failed to download template "${context.templateType}" from ${context.remote}: ${raw}`;
297
- if (NOT_FOUND_ERROR_PATTERN.test(lower)) {
298
- return {
299
- hints: [
300
- `Check the template name "${context.templateType}" and the ref "${context.ref}".`,
301
- "List/inspect available templates, or target a branch/tag with `--ref <branch>`."
302
- ],
303
- message: `template "${context.templateType}" not found at ${context.remote}: ${raw}`
304
- };
305
- }
306
- if (NETWORK_ERROR_PATTERN.test(lower)) {
307
- return {
308
- hints: [
309
- "You appear to be offline or unable to reach GitHub.",
310
- "To scaffold without a network, point at a local template root: `lunora init --from <dir>`."
311
- ],
312
- message: genericMessage
313
- };
314
- }
315
- return {
316
- hints: ["If this is a network/offline issue, scaffold from a local root with `lunora init --from <dir>`."],
317
- message: genericMessage
318
- };
319
- };
320
-
321
- const emitStep = async (type, message, answer) => {
322
- if (isInteractive()) {
323
- await tuiStep(BADGES[type], message, answer);
324
- return;
325
- }
326
- process.stdout.write("\n");
327
- if (answer === void 0 || answer === "") {
328
- logStep(type, message);
329
- return;
330
- }
331
- const dimmed = answer.split("\n").map((line) => paintAnswer(line)).join("\n");
332
- logStep(type, `${message}
333
- ${dimmed}`);
334
- };
335
- const emitMascot = async (logger) => {
336
- if (isInteractive()) {
337
- await tuiMascot();
338
- return;
339
- }
340
- logger.info(`
341
- ${LUNA_ART}
342
- ${LUNA_NAME}: ${LUNA_SIGNOFF}`);
343
- };
344
-
345
- const STACK_FEATURE_OPTIONS = [
346
- { description: "Sign-up / sign-in (asks which provider)", label: "Authentication", value: "auth" },
347
- { description: "Cloudflare Email Workers + a dev mail catcher", label: "Transactional email", value: "email" },
348
- { description: "Typed R2 buckets + signed URLs (@lunora/storage)", label: "File storage", value: "storage" },
349
- { description: "Token-bucket / sliding-window limits (@lunora/ratelimit)", label: "Rate limiting", value: "ratelimit" },
350
- { description: "Scheduled jobs via Cron Triggers (@lunora/scheduler)", label: "Cron jobs", value: "crons" },
351
- { description: "Live presence / who's-online over hibernated WebSockets", label: "Presence", value: "presence" },
352
- { description: "Snapshot + restore your Durable Object data", label: "Backups", value: "backup" }
353
- ];
354
- const STACK_FEATURE_VALUES = STACK_FEATURE_OPTIONS.map((option) => option.value);
355
- const featureItem = (feature) => feature === "email" ? EMAIL_ITEM : feature;
356
- const parseFeatureList = (raw, warn) => {
357
- const features = [];
358
- for (const part of raw.split(",").map((entry) => entry.trim()).filter(Boolean)) {
359
- if (STACK_FEATURE_VALUES.includes(part)) {
360
- if (!features.includes(part)) {
361
- features.push(part);
362
- }
363
- } else {
364
- warn(`init: unknown --add feature "${part}" — expected ${STACK_FEATURE_VALUES.join(" | ")}; skipping.`);
365
- }
366
- }
367
- return features;
368
- };
369
- const collectAuthFeature = async (deps) => {
370
- const provider = await promptAuthProvider(deps.select);
371
- const databaseName = await promptDatabaseName(deps.text, deps.projectName);
372
- return { label: "auth", names: [provider], transformManifest: (manifest) => withAuthDatabaseName(manifest, databaseName) };
373
- };
374
- const collectEmailFeature = async (deps) => {
375
- const answer = await deps.text(MAIL_DESTINATION_PROMPT, { placeholder: "you@yourdomain.com" });
376
- const destination = resolveTypedDestination(answer, (message) => {
377
- deps.logger.warn(message);
378
- });
379
- return {
380
- label: "email",
381
- names: [EMAIL_ITEM],
382
- transformManifest: destination === void 0 ? void 0 : (manifest) => withMailDestination(manifest, destination)
383
- };
384
- };
385
- const collectStorageFeature = async (deps) => {
386
- const bucketName = await promptBucketName(deps.text, deps.projectName);
387
- return { label: "storage", names: ["storage"], transformManifest: (manifest) => withStorageBucketName(manifest, bucketName) };
388
- };
389
- const FEATURE_COLLECTORS = {
390
- auth: collectAuthFeature,
391
- email: collectEmailFeature,
392
- storage: collectStorageFeature
393
- };
394
- const offerRegistryExtras = async (deps) => {
395
- if (deps.preselected !== void 0 && deps.preselected.length > 0) {
396
- await deps.applyAll(
397
- deps.preselected.map((feature) => {
398
- return { label: feature, names: [featureItem(feature)] };
399
- })
400
- );
401
- return;
402
- }
403
- if (!deps.interactive) {
404
- deps.logger.info("tip: add features later with `lunora add <auth|email|storage|ratelimit|crons|presence|backup>`.");
405
- return;
406
- }
407
- const picked = await deps.multiSelect("Which features do you want to add?", STACK_FEATURE_OPTIONS, { defaults: [] });
408
- if (picked.length === 0) {
409
- return;
410
- }
411
- const plans = [];
412
- for (const feature of picked) {
413
- const collect = FEATURE_COLLECTORS[feature];
414
- plans.push(collect ? await collect(deps) : { label: feature, names: [feature] });
415
- }
416
- await deps.applyAll(plans);
417
- };
418
-
419
- 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";
420
- const WELCOME_CSS = `/* The welcome page is a full-bleed starter — reset the browser's default
86
+ - ${L(e,["deploy","--preview"])}
87
+ `},_e={github:{file:K(".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)"}},Pt=(e,t)=>e==="github"?Ot(t):Tt(t),Dt=e=>e==="github"||e==="gitlab",Bt=(e,t,r,a={})=>{const o=K(e,_e[t].file);return m(o)&&a.overwrite!==!0?{path:o,skipped:!0,written:!1}:(M(dt(o),{recursive:!0}),w(o,Pt(t,r),"utf8"),{path:o,skipped:!1,written:!0})},jt=(e,t,r,a,o={})=>{const n=_e[t];try{const s=Bt(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=he(r),l=[i.command,...i.args].join(" "),{installCmd:c,lockfile:u}=Y[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 ${u} 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:K(e,n.file),skipped:!1,written:!1}}},Ut={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"},Vt=e=>{const t=Xe(e);return{...t,adapter:Ut[t.framework]}},R="lunora()",ee='import { lunora } from "@lunora/vite";',Ft="@lunora/vite",Wt="lunora",Ht=e=>{for(const t of e.getStatements()){if(t.getKind()!==g.ExportAssignment)continue;const r=t.asKindOrThrow(g.ExportAssignment).getExpression();if(r.getKind()!==g.CallExpression)continue;const a=r.asKindOrThrow(g.CallExpression);if(a.getExpression().getText()!=="defineConfig")continue;const o=a.getArguments()[0];if(o?.getKind()===g.ObjectLiteralExpression)return o.asKindOrThrow(g.ObjectLiteralExpression)}},zt=e=>{for(const t of e.getStatements()){if(t.getKind()!==g.ExportAssignment)continue;const r=t.asKindOrThrow(g.ExportAssignment).getExpression();if(r.getKind()===g.ObjectLiteralExpression)return r.asKindOrThrow(g.ObjectLiteralExpression)}},Kt=e=>e.getDescendantsOfKind(g.CallExpression).some(t=>t.getExpression().getText()===Wt),qt=e=>e.getImportDeclarations().some(t=>t.getModuleSpecifierValue()===Ft),Gt=e=>new ht({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}).createSourceFile("vite.config.ts",e,{overwrite:!0}),Yt=(e,t)=>{const r=t.getImportDeclarations().at(-1)?.getEnd()??0;r===0?e.prepend(`${ee}
88
+ `):e.appendLeft(r,`
89
+ ${ee}`)},Jt=(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: [${R}] `);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: [${R}],
90
+ `);return}const a=r.getDescendantsOfKind(g.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,R);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(),`${R}, `)},Ie=e=>{const t=Gt(e);if(Kt(t))return{changed:!1,code:e,reason:"lunora plugin already present"};const r=Ht(t)??zt(t);if(r===void 0)return{changed:!1,code:e,reason:"could not locate a Vite config plugins array to patch"};const a=new pt(e);qt(t)||Yt(a,t);const o=Jt(a,r);return o!==void 0?{changed:!1,code:e,reason:o}:{changed:!0,code:a.toString()}},Xt=/enotfound|eai_again|econnrefused|etimedout|network|fetch failed|getaddrinfo/u,Qt=/404|not found|could not find|no such/u,Zt=(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 Qt.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}`}:Xt.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(y()){await vt(v[e],t,r);return}if(process.stdout.write(`
91
+ `),r===void 0||r===""){Q(e,t);return}const a=r.split(`
92
+ `).map(o=>tt(o)).join(`
93
+ `);Q(e,`${t}
94
+ ${a}`)},er=async e=>{if(y()){await gt();return}e.info(`
95
+ ${Qe}
96
+ ${Ze}: ${et}`)},$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"}],te=$e.map(e=>e.value),tr=e=>e==="email"?Ae:e,rr=(e,t)=>{const r=[];for(const a of e.split(",").map(o=>o.trim()).filter(Boolean))te.includes(a)?r.includes(a)||r.push(a):t(`init: unknown --add feature "${a}" — expected ${te.join(" | ")}; skipping.`);return r},Re=e=>e.resolveAuthUiItem===void 0?"auth-ui-react":e.resolveAuthUiItem(),ar=async e=>{const t=await Et(e.select),r=await Ee(e.text,e.projectName);return{label:"auth",names:[t],transformManifest:a=>Ne(a,r)}},or=async e=>{const t=await e.text(Lt,{placeholder:"you@yourdomain.com"}),r=Mt(t,a=>{e.logger.warn(a)});return{label:"email",names:[Ae],transformManifest:r===void 0?void 0:a=>At(a,r)}},nr=async(e,t)=>{const r=Re(e);if(r===void 0){e.logger.error(`init: ${Me}`);return}if(t)return{label:"auth-ui",names:[r]};const a=await Ee(e.text,e.projectName);return{label:"auth-ui",names:[r],transformManifest:o=>Ne(o,a)}},sr=async e=>{const t=await Ct(e.text,e.projectName);return{label:"storage",names:["storage"],transformManifest:r=>St(r,t)}},ir=(e,t)=>{const r=[];let a=!1;for(const o of t){if(o!=="auth-ui"){r.push({label:o,names:[tr(o)]});continue}const n=Re(e);if(n===void 0){e.logger.error(`init: ${Me}`),a=!0;continue}r.push({label:o,names:[n]})}return{plans:r,refused:a}},lr={auth:ar,"auth-ui":async(e,t)=>nr(e,t.includes("auth")),email:or,storage:sr},re=async e=>{if(e.preselected!==void 0&&e.preselected.length>0){const{plans:a,refused:o}=ir(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=lr[a],n=o?await o(e,t):{label:a,names:[a]};n!==void 0&&r.push(n)}return await e.applyAll(r),!0},cr=[{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"}],dr="Which linter/formatter do you use? We'll tell it to skip Lunora's generated files.",ur=async e=>{const t=e.interactive?await e.multiSelect(dr,cr,{defaults:e.detected}):[...e.detected];if(t.length===0)return[];const r=e.apply(t);return $t(r,e.logger),r},I="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",N=`/* The welcome page is a full-bleed starter — reset the browser's default
421
97
  body margin/padding so it sits flush; everything else is scoped under
422
98
  .lunora-welcome (collision-safe). */
423
99
  body {
@@ -522,8 +198,7 @@ body {
522
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); }
523
199
 
524
200
  @media (prefers-reduced-motion: reduce) { .lunora-welcome * { transition: none !important; } }
525
- `;
526
- const REACT_APP = `import { useEffect, useState } from "react";
201
+ `,pr=`import { useEffect, useState } from "react";
527
202
 
528
203
  type Theme = "dark" | "light";
529
204
 
@@ -565,7 +240,7 @@ export default function App() {
565
240
  <div className="lw-wrap">
566
241
  <div className="brand">
567
242
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
568
- <path d="${LOGO_PATH}" fill="currentColor" fillRule="evenodd" />
243
+ <path d="${I}" fill="currentColor" fillRule="evenodd" />
569
244
  </svg>
570
245
  <span className="word">Lunora</span>
571
246
  </div>
@@ -684,8 +359,7 @@ export default function App() {
684
359
  </div>
685
360
  );
686
361
  }
687
- `;
688
- const VUE_APP = `<script setup lang="ts">
362
+ `,hr=`<script setup lang="ts">
689
363
  import { onMounted, ref } from "vue";
690
364
 
691
365
  // Default to "dark" for a stable first paint, then reconcile to the OS
@@ -725,7 +399,7 @@ const toggle = (): void => {
725
399
  <div class="lw-wrap">
726
400
  <div class="brand">
727
401
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
728
- <path d="${LOGO_PATH}" fill="currentColor" fill-rule="evenodd" />
402
+ <path d="${I}" fill="currentColor" fill-rule="evenodd" />
729
403
  </svg>
730
404
  <span class="word">Lunora</span>
731
405
  </div>
@@ -841,8 +515,7 @@ const toggle = (): void => {
841
515
  </div>
842
516
  </div>
843
517
  </template>
844
- `;
845
- const SOLID_APP = `import { createSignal, onMount } from "solid-js";
518
+ `,mr=`import { createSignal, onMount } from "solid-js";
846
519
 
847
520
  export default function App() {
848
521
  // Default to "dark" for a stable first paint, then reconcile to the OS
@@ -882,7 +555,7 @@ export default function App() {
882
555
  <div class="lw-wrap">
883
556
  <div class="brand">
884
557
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
885
- <path d="${LOGO_PATH}" fill="currentColor" fill-rule="evenodd" />
558
+ <path d="${I}" fill="currentColor" fill-rule="evenodd" />
886
559
  </svg>
887
560
  <span class="word">Lunora</span>
888
561
  </div>
@@ -1001,8 +674,7 @@ export default function App() {
1001
674
  </div>
1002
675
  );
1003
676
  }
1004
- `;
1005
- const SVELTE_APP = `<script lang="ts">
677
+ `,fr=`<script lang="ts">
1006
678
  import { onMount } from "svelte";
1007
679
 
1008
680
  // Default to "dark" for a stable first paint, then reconcile to the OS
@@ -1045,7 +717,7 @@ const SVELTE_APP = `<script lang="ts">
1045
717
  <div class="lw-wrap">
1046
718
  <div class="brand">
1047
719
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
1048
- <path d="${LOGO_PATH}" fill="currentColor" fill-rule="evenodd" />
720
+ <path d="${I}" fill="currentColor" fill-rule="evenodd" />
1049
721
  </svg>
1050
722
  <span class="word">Lunora</span>
1051
723
  </div>
@@ -1160,8 +832,7 @@ const SVELTE_APP = `<script lang="ts">
1160
832
  <div class="lw-foot">Running on Lunora · Vite + Svelte</div>
1161
833
  </div>
1162
834
  </div>
1163
- `;
1164
- const VANILLA_MAIN = `import "./style.css";
835
+ `,gr=`import "./style.css";
1165
836
 
1166
837
  import { LunoraClient } from "lunorash/client";
1167
838
 
@@ -1189,7 +860,7 @@ const welcomeHtml = \`
1189
860
  <div class="lw-wrap">
1190
861
  <div class="brand">
1191
862
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
1192
- <path d="${LOGO_PATH}" fill="currentColor" fill-rule="evenodd" />
863
+ <path d="${I}" fill="currentColor" fill-rule="evenodd" />
1193
864
  </svg>
1194
865
  <span class="word">Lunora</span>
1195
866
  </div>
@@ -1325,13 +996,10 @@ toggleButton.addEventListener("click", () => {
1325
996
  // Live demo: the message count of a demo channel re-renders on every delta.
1326
997
  const count = document.querySelector<HTMLSpanElement>("#lw-count")!;
1327
998
 
1328
- client.onUpdate(api.messages.list, { channelId: "channel:demo" }, (result) => {
999
+ client.subscribe(api.messages.list, { channelId: "channel:demo" }, (result) => {
1329
1000
  count.textContent = String(result.messages.length);
1330
1001
  });
1331
- `;
1332
-
1333
- const READ_URL = `const url = (import.meta.env.VITE_LUNORA_URL as string | undefined) ?? globalThis.location.origin;`;
1334
- const REACT_MAIN = `import "./index.css";
1002
+ `,D="const url = (import.meta.env.VITE_LUNORA_URL as string | undefined) ?? globalThis.location.origin;",vr=`import "./index.css";
1335
1003
 
1336
1004
  import { LunoraProvider } from "@lunora/react";
1337
1005
  import { LunoraClient } from "lunorash/client";
@@ -1343,7 +1011,7 @@ import App from "./App.tsx";
1343
1011
  // \`@lunora/vite\` runs the Worker on the same origin as Vite, so default to
1344
1012
  // \`location.origin\`. Point \`VITE_LUNORA_URL\` at a deployed Worker to develop
1345
1013
  // the client against production data.
1346
- ${READ_URL}
1014
+ ${D}
1347
1015
  const client = new LunoraClient({ url });
1348
1016
 
1349
1017
  const root = document.getElementById("root");
@@ -1359,8 +1027,7 @@ createRoot(root).render(
1359
1027
  </LunoraProvider>
1360
1028
  </StrictMode>,
1361
1029
  );
1362
- `;
1363
- const VUE_MAIN = `import "./style.css";
1030
+ `,wr=`import "./style.css";
1364
1031
 
1365
1032
  import { createLunora } from "@lunora/vue";
1366
1033
  import { LunoraClient } from "lunorash/client";
@@ -1369,43 +1036,40 @@ import { createApp } from "vue";
1369
1036
  import App from "./App.vue";
1370
1037
 
1371
1038
  // Provide one LunoraClient at the app root via the Vue plugin form.
1372
- ${READ_URL}
1039
+ ${D}
1373
1040
  createApp(App).use(createLunora(new LunoraClient({ url }))).mount("#app");
1374
- `;
1375
- const SOLID_INDEX = `import "./index.css";
1041
+ `,yr=`import "./index.css";
1376
1042
 
1377
- import { LunoraContext } from "@lunora/solid";
1043
+ import { LunoraProvider } from "@lunora/solid";
1378
1044
  import { LunoraClient } from "lunorash/client";
1379
1045
  import { render } from "solid-js/web";
1380
1046
 
1381
1047
  import App from "./App";
1382
1048
 
1383
- ${READ_URL}
1049
+ ${D}
1384
1050
  const client = new LunoraClient({ url });
1385
1051
  const root = document.getElementById("root");
1386
1052
 
1387
1053
  render(
1388
1054
  () => (
1389
- <LunoraContext.Provider value={client}>
1055
+ <LunoraProvider client={client}>
1390
1056
  <App />
1391
- </LunoraContext.Provider>
1057
+ </LunoraProvider>
1392
1058
  ),
1393
1059
  root!,
1394
1060
  );
1395
- `;
1396
- const SVELTE_ROOT = `<script lang="ts">
1061
+ `,br=`<script lang="ts">
1397
1062
  import { setLunoraClient } from "@lunora/svelte";
1398
1063
  import { LunoraClient } from "lunorash/client";
1399
1064
 
1400
1065
  import App from "./App.svelte";
1401
1066
 
1402
- ${READ_URL}
1067
+ ${D}
1403
1068
  setLunoraClient(new LunoraClient({ url }));
1404
1069
  <\/script>
1405
1070
 
1406
1071
  <App />
1407
- `;
1408
- const SVELTE_MAIN = `import "./app.css";
1072
+ `,xr=`import "./app.css";
1409
1073
 
1410
1074
  import { mount } from "svelte";
1411
1075
 
@@ -1415,62 +1079,60 @@ import Root from "./Root.svelte";
1415
1079
  const app = mount(Root, { target: document.getElementById("app")! });
1416
1080
 
1417
1081
  export default app;
1418
- `;
1419
- const ADAPTERS = {
1420
- react: {
1421
- adapter: "@lunora/react",
1422
- createViteTemplate: "react-ts",
1423
- files: [
1424
- { contents: REACT_MAIN, path: "src/main.tsx" },
1425
- { contents: REACT_APP, path: "src/App.tsx" },
1426
- { contents: WELCOME_CSS, path: "src/index.css" }
1427
- ],
1428
- label: "React"
1429
- },
1430
- solid: {
1431
- adapter: "@lunora/solid",
1432
- createViteTemplate: "solid",
1433
- files: [
1434
- { contents: SOLID_INDEX, path: "src/index.tsx" },
1435
- { contents: SOLID_APP, path: "src/App.tsx" },
1436
- { contents: WELCOME_CSS, path: "src/index.css" }
1437
- ],
1438
- label: "Solid"
1439
- },
1440
- svelte: {
1441
- adapter: "@lunora/svelte",
1442
- createViteTemplate: "svelte-ts",
1443
- files: [
1444
- { contents: SVELTE_ROOT, path: "src/Root.svelte" },
1445
- { contents: SVELTE_MAIN, path: "src/main.ts" },
1446
- { contents: SVELTE_APP, path: "src/App.svelte" },
1447
- { contents: WELCOME_CSS, path: "src/app.css" }
1448
- ],
1449
- label: "Svelte"
1450
- },
1451
- vanilla: {
1452
- adapter: "lunorash/client",
1453
- createViteTemplate: "vanilla-ts",
1454
- files: [
1455
- { contents: VANILLA_MAIN, path: "src/main.ts" },
1456
- { contents: WELCOME_CSS, path: "src/style.css" }
1457
- ],
1458
- label: "Vanilla"
1459
- },
1460
- vue: {
1461
- adapter: "@lunora/vue",
1462
- createViteTemplate: "vue-ts",
1463
- files: [
1464
- { contents: VUE_MAIN, path: "src/main.ts" },
1465
- { contents: VUE_APP, path: "src/App.vue" },
1466
- { contents: WELCOME_CSS, path: "src/style.css" }
1467
- ],
1468
- label: "Vue"
1469
- }
1470
- };
1471
- const isOverlayFramework = (value) => Object.hasOwn(ADAPTERS, value);
1082
+ `,B={react:{adapter:"@lunora/react",createViteTemplate:"react-ts",files:[{contents:vr,path:"src/main.tsx"},{contents:pr,path:"src/App.tsx"},{contents:N,path:"src/index.css"}],label:"React"},solid:{adapter:"@lunora/solid",createViteTemplate:"solid-ts",files:[{contents:yr,path:"src/index.tsx"},{contents:mr,path:"src/App.tsx"},{contents:N,path:"src/index.css"}],label:"Solid"},svelte:{adapter:"@lunora/svelte",createViteTemplate:"svelte-ts",files:[{contents:br,path:"src/Root.svelte"},{contents:xr,path:"src/main.ts"},{contents:fr,path:"src/App.svelte"},{contents:N,path:"src/app.css"}],label:"Svelte"},vanilla:{adapter:"lunorash/client",createViteTemplate:"vanilla-ts",files:[{contents:gr,path:"src/main.ts"},{contents:N,path:"src/style.css"}],label:"Vanilla"},vue:{adapter:"@lunora/vue",createViteTemplate:"vue-ts",files:[{contents:wr,path:"src/main.ts"},{contents:hr,path:"src/App.vue"},{contents:N,path:"src/style.css"}],label:"Vue"}},j=e=>Object.hasOwn(B,e),kr=`/**
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";
1472
1092
 
1473
- const LUNORA_SCHEMA = `import { defineSchema, defineTable, v } from "lunorash/server";
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;
1102
+
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
+ `,Cr=`import { ratelimit } from "./ratelimit/schema.js";
1135
+ import { defineSchema, defineTable, v } from "lunorash/server";
1474
1136
 
1475
1137
  export default defineSchema({
1476
1138
  messages: defineTable({
@@ -1479,25 +1141,40 @@ export default defineSchema({
1479
1141
  })
1480
1142
  .shardBy("channelId")
1481
1143
  .index("by_channel", ["channelId"]),
1482
- });
1483
- `;
1484
- const LUNORA_MESSAGES = `import { RateLimiter, rateLimit } from "@lunora/ratelimit";
1144
+ }).extend(ratelimit.extension);
1145
+ `,Sr=`import { rateLimit } from "lunorash/ratelimit";
1485
1146
 
1147
+ import { makeRateLimiter } from "./ratelimit/schema.js";
1148
+ import type { MutationCtx } from "#lunora/_generated/server.js";
1486
1149
  import { mutation, query, v } from "#lunora/_generated/server.js";
1487
1150
 
1488
1151
  /**
1489
- * One in-memory limiter so the public \`send\` mutation isn't an open flood target
1490
- * out of the box. The default store is in-memory (per-isolate, resets on
1491
- * eviction) — fine for a starter; run \`lunora add ratelimit\` for the durable,
1492
- * \`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.
1493
1157
  */
1494
- const limiter = new RateLimiter({
1495
- config: {
1496
- send: { kind: "token bucket", period: 60_000, rate: 30 },
1497
- },
1498
- });
1158
+ const limiter = (ctx: MutationCtx) => makeRateLimiter(ctx);
1159
+
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" };
1499
1176
 
1500
- export const list = query.input({ channelId: v.string().meta({ schema: { maxLength: 256 } }), limit: v.optional(v.number()) }).query(async ({ args, ctx }) => {
1177
+ export const list = query.input({ channelId: v.string().max(256), limit: v.optional(v.number()) }).query(async ({ args, ctx }) => {
1501
1178
  const messages = await ctx.db
1502
1179
  .query("messages")
1503
1180
  .withIndex("by_channel", (q) => q.eq("channelId", args.channelId))
@@ -1507,15 +1184,14 @@ export const list = query.input({ channelId: v.string().meta({ schema: { maxLeng
1507
1184
  });
1508
1185
 
1509
1186
  export const send = mutation
1510
- .input({ channelId: v.string().meta({ schema: { maxLength: 256 } }), text: v.string().meta({ schema: { maxLength: 4096 } }) })
1511
- .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))
1512
1189
  .mutation(async ({ args, ctx }) => {
1513
1190
  const id = await ctx.db.insert("messages", { channelId: args.channelId, text: args.text });
1514
1191
 
1515
1192
  return { channelId: args.channelId, id, text: args.text };
1516
1193
  });
1517
- `;
1518
- const SERVER_ENTRY = `import type { ShardNamespaceLike } from "lunorash/runtime";
1194
+ `,Lr=`import type { ShardNamespaceLike } from "lunorash/runtime";
1519
1195
 
1520
1196
  import { defineApp } from "../lunora/_generated/app.js";
1521
1197
 
@@ -1529,8 +1205,7 @@ const app = defineApp<Env>()
1529
1205
 
1530
1206
  export const ShardDO = app.ShardDO;
1531
1207
  export default app;
1532
- `;
1533
- const WRANGLER = `{
1208
+ `,Mr=`{
1534
1209
  "$schema": "node_modules/wrangler/config-schema.json",
1535
1210
  "name": "__NAME__",
1536
1211
  "main": "src/server.ts",
@@ -1542,990 +1217,47 @@ const WRANGLER = `{
1542
1217
  "migrations": [{ "tag": "v1", "new_sqlite_classes": ["ShardDO"] }],
1543
1218
  "observability": { "enabled": true, "head_sampling_rate": 1 },
1544
1219
  }
1545
- `;
1546
- const GITIGNORE_ADDITIONS = [".wrangler", ".env", ".env.*", "!.env.example", ".lunora/", ".lunora-cache", "lunora/_generated"];
1547
- const ENV_EXAMPLE = `# Lunora endpoint for the browser client.
1220
+ `,ae=[".wrangler",".env",".env.*","!.env.example",".dev.vars",".dev.vars.*","!.dev.vars.example",".lunora/",".lunora-cache","lunora/_generated"],Ar=`# Lunora endpoint for the browser client.
1548
1221
  # Vite statically replaces \`import.meta.env.VITE_LUNORA_URL\` at \`vite dev\` / build.
1549
1222
  # Leave it unset to use the page origin; set it to point at a deployed Worker:
1550
1223
  #
1551
1224
  # VITE_LUNORA_URL=https://my-app.example.workers.dev
1552
- `;
1553
- const COMMON_DEV_DEPENDENCIES = {
1554
- "@cloudflare/workers-types": "^4.20260611.1",
1555
- wrangler: "^4.100.0"
1556
- };
1557
- const writeFile = (target, relativePath, contents, written) => {
1558
- const destination = join$1(target, relativePath);
1559
- mkdirSync(dirname$1(destination), { recursive: true });
1560
- writeFileSync(destination, contents, "utf8");
1561
- written.push(destination);
1562
- };
1563
- const NEWLINE = /\r?\n/;
1564
- const ensureGitignore = (target) => {
1565
- const path = join$1(target, ".gitignore");
1566
- const existing = existsSync(path) ? readFileSync(path, "utf8") : "";
1567
- const missing = GITIGNORE_ADDITIONS.filter((entry) => !existing.split(NEWLINE).includes(entry));
1568
- if (missing.length === 0) {
1569
- return;
1570
- }
1571
- const prefix = existing.length > 0 && !existing.endsWith("\n") ? "\n" : "";
1572
- writeFileSync(path, `${existing}${prefix}
1225
+ `,Er={"@cloudflare/workers-types":"^4.20260611.1",wrangler:"^4.100.0"},C=(e,t,r,a)=>{const o=p(e,t);M(A(o),{recursive:!0}),w(o,r,"utf8"),a.push(o)},Nr=/\r?\n/,_r=e=>{const t=p(e,".gitignore"),r=m(t)?k(t,"utf8"):"",a=new Set(r.split(Nr)),o=ae.filter(i=>!a.has(i));if(o.length===0)return;const n=o.some(i=>!i.startsWith("!"))?[...o.filter(i=>!i.startsWith("!")),...ae.filter(i=>i.startsWith("!"))]:o,s=r.length>0&&!r.endsWith(`
1226
+ `)?`
1227
+ `:"";w(t,`${r}${s}
1573
1228
  # Lunora
1574
- ${missing.join("\n")}
1575
- `, "utf8");
1576
- };
1577
- const isLunoraDep$1 = (name) => name === "lunorash" || name.startsWith("@lunora/");
1578
- const stampRange = (name, range, distTag, versions) => isLunoraDep$1(name) ? versions?.get(name) ?? distTag : range;
1579
- const withDependency = (map, name, range, distTag) => {
1580
- return { ...map, [name]: stampRange(name, range, distTag) };
1581
- };
1582
- const restampLunora = (map, distTag, versions) => Object.fromEntries(Object.entries(map).map(([name, range]) => [name, stampRange(name, range, distTag, versions)]));
1583
- const patchPackageJson = async (target, name, adapter, distTag) => {
1584
- const path = join$1(target, "package.json");
1585
- const parsed = JSON.parse(readFileSync(path, "utf8"));
1586
- let dependencies = withDependency(parsed.dependencies ?? {}, "lunorash", distTag, distTag);
1587
- dependencies = withDependency(dependencies, "@lunora/ratelimit", distTag, distTag);
1588
- if (adapter.adapter.startsWith("@lunora/")) {
1589
- dependencies = withDependency(dependencies, adapter.adapter, distTag, distTag);
1590
- }
1591
- for (const [depName, range] of Object.entries(adapter.extraDependencies ?? {})) {
1592
- dependencies = withDependency(dependencies, depName, range, distTag);
1593
- }
1594
- let devDependencies = withDependency(parsed.devDependencies ?? {}, "@lunora/vite", distTag, distTag);
1595
- devDependencies = withDependency(devDependencies, "@lunora/studio", distTag, distTag);
1596
- for (const [depName, range] of Object.entries(COMMON_DEV_DEPENDENCIES)) {
1597
- devDependencies = withDependency(devDependencies, depName, range, distTag);
1598
- }
1599
- const lunoraNames = [...Object.keys(dependencies), ...Object.keys(devDependencies)].filter((depName) => isLunoraDep$1(depName));
1600
- const versions = await resolveTagVersions(lunoraNames, distTag);
1601
- parsed.name = name;
1602
- parsed.imports = { ...parsed.imports, "#lunora/*": "./lunora/*" };
1603
- parsed.dependencies = restampLunora(dependencies, distTag, versions);
1604
- parsed.devDependencies = restampLunora(devDependencies, distTag, versions);
1605
- parsed.scripts = { ...parsed.scripts, codegen: "lunora codegen", deploy: "vite build && lunora deploy" };
1606
- writeFileSync(path, `${JSON.stringify(parsed, void 0, 4)}
1607
- `, "utf8");
1608
- };
1609
- const patchBaseViteConfig = (target, logger) => {
1610
- const candidate = ["vite.config.ts", "vite.config.mts", "vite.config.js", "vite.config.mjs"].map((file) => join$1(target, file)).find((path) => existsSync(path));
1611
- if (candidate === void 0) {
1612
- logger.warn("overlay: no vite.config found in the create-vite base — add `lunora()` to your Vite plugins manually.");
1613
- return;
1614
- }
1615
- const result = patchViteConfig(readFileSync(candidate, "utf8"));
1616
- if (result.changed) {
1617
- writeFileSync(candidate, result.code, "utf8");
1618
- }
1619
- };
1620
- const applyLunoraOverlay = async (options) => {
1621
- const { adapter, distTag, logger, name, target } = options;
1622
- const written = [];
1623
- writeFile(target, join$1("lunora", "schema.ts"), LUNORA_SCHEMA, written);
1624
- writeFile(target, join$1("lunora", "messages.ts"), LUNORA_MESSAGES, written);
1625
- writeFile(target, join$1("src", "server.ts"), SERVER_ENTRY, written);
1626
- writeFile(target, "wrangler.jsonc", WRANGLER.replaceAll("__NAME__", name), written);
1627
- writeFile(target, ".env.example", ENV_EXAMPLE, written);
1628
- for (const file of adapter.files) {
1629
- writeFile(target, file.path, file.contents, written);
1630
- }
1631
- patchBaseViteConfig(target, logger);
1632
- await patchPackageJson(target, name, adapter, distTag);
1633
- ensureGitignore(target);
1634
- return written;
1635
- };
1636
-
1637
- const ADJECTIVES = [
1638
- "lunar",
1639
- "silver",
1640
- "silent",
1641
- "waning",
1642
- "waxing",
1643
- "crescent",
1644
- "cosmic",
1645
- "stellar",
1646
- "orbital",
1647
- "gibbous",
1648
- "twilight",
1649
- "midnight",
1650
- "shimmering",
1651
- "drifting",
1652
- "weightless"
1653
- ];
1654
- const NOUNS = [
1655
- "moon",
1656
- "tide",
1657
- "crater",
1658
- "comet",
1659
- "eclipse",
1660
- "halo",
1661
- "orbit",
1662
- "nebula",
1663
- "voyager",
1664
- "lander",
1665
- "rover",
1666
- "beacon",
1667
- "harbor",
1668
- "meadow",
1669
- "fox"
1670
- ];
1671
- const pick = (items) => (
1672
- // eslint-disable-next-line sonarjs/pseudo-random -- cosmetic default project name, not a security decision.
1673
- items[Math.floor(Math.random() * items.length)]
1674
- );
1675
- const generateProjectName = () => `${pick(ADJECTIVES)}-${pick(NOUNS)}`;
1676
-
1677
- const isOnline = async () => dns.lookup("github.com").then(
1678
- () => true,
1679
- () => false
1680
- );
1681
- const GITHUB_SOURCE = /^(?:gh|github):([^/]+)\/([^#/]+)(?:\/[^#]*)?(?:#(.+))?$/;
1682
- const parseGitHubSource = (source) => {
1683
- const match = GITHUB_SOURCE.exec(source);
1684
- if (match === null) {
1685
- return void 0;
1686
- }
1687
- const [, owner, repo, ref] = match;
1688
- if (owner === void 0 || repo === void 0) {
1689
- return void 0;
1690
- }
1691
- return { owner, ref: ref ?? "HEAD", repo };
1692
- };
1693
- const templateRefExists = async (source) => {
1694
- const parsed = parseGitHubSource(source);
1695
- if (parsed === void 0) {
1696
- return void 0;
1697
- }
1698
- const url = `https://codeload.github.com/${parsed.owner}/${parsed.repo}/tar.gz/${parsed.ref}`;
1699
- try {
1700
- const response = await fetch(url, { method: "HEAD" });
1701
- if (response.status === 404) {
1702
- return false;
1703
- }
1704
- return response.ok ? true : void 0;
1705
- } catch {
1706
- return void 0;
1707
- }
1708
- };
1709
- const verifyRemoteTemplate = async (params) => {
1710
- if (params.isLocal) {
1711
- return true;
1712
- }
1713
- const isGitHubBacked = params.source === void 0 || parseGitHubSource(params.source) !== void 0;
1714
- if (!isGitHubBacked) {
1715
- return true;
1716
- }
1717
- if (!await isOnline()) {
1718
- params.logger.error("you appear to be offline — connect to the internet and try again, or scaffold from a local template with `--from <dir>`.");
1719
- return false;
1720
- }
1721
- if (params.source !== void 0 && await templateRefExists(params.source) === false) {
1722
- params.logger.error(`template source not found: ${params.source} — double-check --ref / --source, or browse the templates at https://lunora.sh/docs.`);
1723
- return false;
1724
- }
1725
- return true;
1726
- };
1727
-
1728
- const COPY = {
1729
- extras: "Let's finish setting up your app.",
1730
- framework: "Which framework should we launch?",
1731
- git: "Initialize a new git repository? (optional)",
1732
- install: "Install dependencies now?",
1733
- name: "Where should we land your project?",
1734
- nextHeader: "Liftoff confirmed — explore your project!",
1735
- packageManager: "Which package manager?"
1736
- };
1737
- const TEXT_EXTENSIONS = /* @__PURE__ */ new Set([".gitignore", ".html", ".js", ".json", ".jsonc", ".md", ".mjs", ".ts", ".tsx"]);
1738
- const VITE_CONFIG_CANDIDATES = ["vite.config.ts", "vite.config.mts", "vite.config.js", "vite.config.mjs"];
1739
- const MINIMAL_VITE_CONFIG = `import { defineConfig } from "vite";
1229
+ ${n.join(`
1230
+ `)}
1231
+ `,"utf8")},U=e=>e==="lunorash"||e.startsWith("@lunora/"),Ir=(e,t,r,a)=>U(e)?a.get(e)??r:t,S=(e,t,r)=>({...e,[t]:r}),oe=(e,t,r)=>Object.fromEntries(Object.entries(e).map(([a,o])=>[a,Ir(a,o,t,r)])),$r=async(e,t,r,a)=>{const o=p(e,"package.json"),n=JSON.parse(k(o,"utf8"));let s=S(n.dependencies??{},"lunorash",a);s=S(s,"@lunora/ratelimit",a),r.adapter.startsWith("@lunora/")&&(s=S(s,r.adapter,a));for(const[u,h]of Object.entries(r.extraDependencies??{}))s=S(s,u,h);let i=S(n.devDependencies??{},"@lunora/vite",a);i=S(i,"@lunora/studio",a);for(const[u,h]of Object.entries(Er))i=S(i,u,h);const l=[...Object.keys(s),...Object.keys(i)].filter(u=>U(u)),c=await ve(l,a);n.name=t,n.imports={...n.imports,"#lunora/*":"./lunora/*"},n.dependencies=oe(s,a,c),n.devDependencies=oe(i,a,c),n.scripts={...n.scripts,codegen:"lunora codegen",deploy:"vite build && lunora deploy"},w(o,`${JSON.stringify(n,void 0,4)}
1232
+ `,"utf8")},Rr=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],Oe=e=>Rr.map(t=>p(e,t)).find(t=>m(t)),Or=(e,t)=>{const r=Oe(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=Ie(k(r,"utf8"));a.changed&&w(r,a.code,"utf8")},Tr=async e=>{const{adapter:t,distTag:r,logger:a,name:o,target:n}=e,s=[];C(n,p("lunora","ratelimit","schema.ts"),kr,s),C(n,p("lunora","schema.ts"),Cr,s),C(n,p("lunora","messages.ts"),Sr,s),C(n,p("src","server.ts"),Lr,s),C(n,"wrangler.jsonc",Mr.replaceAll("__NAME__",o),s),C(n,".env.example",Ar,s);for(const i of t.files)C(n,i.path,i.contents,s);return Or(n,a),await $r(n,o,t,r),_r(n),s},Pr=["lunar","silver","silent","waning","waxing","crescent","cosmic","stellar","orbital","gibbous","twilight","midnight","shimmering","drifting","weightless"],Dr=["moon","tide","crater","comet","eclipse","halo","orbit","nebula","voyager","lander","rover","beacon","harbor","meadow","fox"],ne=e=>e[Math.floor(Math.random()*e.length)],Br=()=>`${ne(Pr)}-${ne(Dr)}`,jr=async()=>Rt.lookup("github.com").then(()=>!0,()=>!1),Ur=/^(?:gh|github):([^/]+)\/([^#/]+)(?:\/[^#]*)?(?:#(.+))?$/,Te=e=>{const t=Ur.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}},Vr=async e=>{const t=Te(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}},Pe=async e=>e.isLocal||!(e.source===void 0||Te(e.source)!==void 0)?!0:await jr()?e.source!==void 0&&await Vr(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),x={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?"},Fr=new Set([".gitignore",".html",".js",".json",".jsonc",".md",".mjs",".ts",".tsx"]),Wr=`import { defineConfig } from "vite";
1740
1233
  import { lunora } from "@lunora/vite";
1741
1234
 
1742
1235
  export default defineConfig({ plugins: [lunora()] });
1743
- `;
1744
- const SAMPLE_SCHEMA = `import { defineSchema, defineTable, v } from "@lunora/server";
1236
+ `,Hr=`import { defineSchema, defineTable, v } from "@lunora/server";
1745
1237
 
1746
1238
  export default defineSchema({
1747
1239
  messages: defineTable({
1748
- channelId: v.id("channels"),
1240
+ channelId: v.string(),
1749
1241
  text: v.string(),
1750
1242
  })
1751
1243
  .shardBy("channelId")
1752
1244
  .index("by_channel", ["channelId"]),
1753
1245
  });
1754
- `;
1755
- const SAMPLE_FUNCTION = `import { mutation, query, v } from "./_generated/server";
1246
+ `,zr=`import { mutation, query, v } from "./_generated/server";
1756
1247
 
1757
1248
  export const list = query
1758
- .input({ channelId: v.id("channels"), limit: v.optional(v.number()) })
1249
+ .input({ channelId: v.string(), limit: v.optional(v.number()) })
1759
1250
  .query(async ({ args }) => {
1760
1251
  return { channelId: args.channelId, limit: args.limit ?? 50, messages: [] };
1761
1252
  });
1762
1253
 
1763
1254
  export const send = mutation
1764
- .input({ channelId: v.id("channels"), text: v.string() })
1255
+ .input({ channelId: v.string(), text: v.string() })
1765
1256
  .mutation(async ({ args }) => {
1766
1257
  return { channelId: args.channelId, text: args.text };
1767
1258
  });
1768
- `;
1769
- const DEFAULT_SOURCE_BASE = "gh:anolilab/lunora/templates";
1770
- const isTextFile = (filePath) => {
1771
- const lastDot = filePath.lastIndexOf(".");
1772
- if (lastDot === -1) {
1773
- return false;
1774
- }
1775
- return TEXT_EXTENSIONS.has(filePath.slice(lastDot));
1776
- };
1777
- const substitute = (content, name) => content.replaceAll("{{name}}", name);
1778
- const isLunoraDep = (name) => name === "lunorash" || name.startsWith("@lunora/");
1779
- const resolveLunoraVersions = async (files, distTag) => {
1780
- const names = /* @__PURE__ */ new Set();
1781
- for (const file of files) {
1782
- if (basename(file) !== "package.json") {
1783
- continue;
1784
- }
1785
- try {
1786
- const parsed = JSON.parse(readFileSync(file, "utf8"));
1787
- for (const section of ["dependencies", "devDependencies"]) {
1788
- for (const name of Object.keys(parsed[section] ?? {})) {
1789
- if (isLunoraDep(name)) {
1790
- names.add(name);
1791
- }
1792
- }
1793
- }
1794
- } catch {
1795
- }
1796
- }
1797
- return resolveTagVersions(names, distTag);
1798
- };
1799
- const stampLunoraDeps = (packageJsonText, distTag, versions) => {
1800
- let parsed;
1801
- try {
1802
- parsed = JSON.parse(packageJsonText);
1803
- } catch {
1804
- return packageJsonText;
1805
- }
1806
- let text = packageJsonText;
1807
- for (const section of ["dependencies", "devDependencies"]) {
1808
- for (const name of Object.keys(parsed[section] ?? {})) {
1809
- if (!isLunoraDep(name)) {
1810
- continue;
1811
- }
1812
- const pin = versions.get(name) ?? distTag;
1813
- const edits = modify(text, [section, name], pin, { formattingOptions: { insertSpaces: true, tabSize: 4 } });
1814
- text = applyEdits(text, edits);
1815
- }
1816
- }
1817
- return text;
1818
- };
1819
- const PNPM_BUILT_DEPENDENCIES = ["esbuild", "sharp", "workerd"];
1820
- const PNPM_WORKSPACE_FILENAME = "pnpm-workspace.yaml";
1821
- const pnpmWorkspaceYaml = () => [
1822
- "# pnpm reads its settings from here (the package.json `pnpm` field is no longer read).",
1823
- "# Pre-approve the toolchain's native build scripts so `pnpm install` runs them",
1824
- "# without the interactive `pnpm approve-builds` step.",
1825
- "allowBuilds:",
1826
- ...PNPM_BUILT_DEPENDENCIES.map((name) => ` ${name}: true`),
1827
- ""
1828
- ].join("\n");
1829
- const collectFiles = (directory) => {
1830
- const out = [];
1831
- for (const entry of walkSync(directory, { includeDirs: false, includeFiles: true })) {
1832
- out.push(entry.path);
1833
- }
1834
- return out;
1835
- };
1836
- const copyTemplate = async (sourceDirectory, target, name) => {
1837
- const files = collectFiles(sourceDirectory);
1838
- const written = [];
1839
- const distTag = resolveDistTag();
1840
- const versions = await resolveLunoraVersions(files, distTag);
1841
- for (const source of files) {
1842
- const relativePath = relative(sourceDirectory, source);
1843
- const destination = join$1(target, relativePath);
1844
- mkdirSync(dirname$1(destination), { recursive: true });
1845
- const raw = readFileSync(source);
1846
- let text = isTextFile(source) ? substitute(raw.toString("utf8"), name) : void 0;
1847
- if (text !== void 0 && basename(source) === "package.json") {
1848
- text = stampLunoraDeps(text, distTag, versions);
1849
- }
1850
- if (text === void 0) {
1851
- writeFileSync(destination, raw);
1852
- } else {
1853
- writeFileSync(destination, text, "utf8");
1854
- }
1855
- written.push(destination);
1856
- }
1857
- return written;
1858
- };
1859
- const resolveTemplateSource = (templateType, source, ref) => {
1860
- if (source !== void 0 && source.length > 0) {
1861
- return source;
1862
- }
1863
- return `${DEFAULT_SOURCE_BASE}/${templateType}#${resolveSourceRef(ref)}`;
1864
- };
1865
- const isSafeSource = (source) => {
1866
- if (source.includes("..")) {
1867
- return false;
1868
- }
1869
- return source.startsWith("gh:") || source.startsWith("github:") || source.startsWith("https://");
1870
- };
1871
- const logWould = (logger, action) => {
1872
- logger.info(`[dry-run] would ${action}`);
1873
- };
1874
- const logScaffoldSuccess = (logger, written, target) => {
1875
- if (isInteractive()) {
1876
- process.stdout.write("\n");
1877
- }
1878
- logger.success(`scaffolded ${String(written.length)} files into ${target}`);
1879
- };
1880
- const runScriptCommand = (manager, script) => {
1881
- if (manager === "npm") {
1882
- return `npm run ${script}`;
1883
- }
1884
- if (manager === "bun") {
1885
- return `bun run ${script}`;
1886
- }
1887
- return `${manager} ${script}`;
1888
- };
1889
- const isInsideMonorepo = (startDirectory) => {
1890
- let directory = resolve(startDirectory);
1891
- for (; ; ) {
1892
- if (existsSync(join$1(directory, "pnpm-workspace.yaml"))) {
1893
- return true;
1894
- }
1895
- const packagePath = join$1(directory, "package.json");
1896
- if (existsSync(packagePath)) {
1897
- try {
1898
- const parsed = JSON.parse(readFileSync(packagePath, "utf8"));
1899
- if (parsed.workspaces !== void 0) {
1900
- return true;
1901
- }
1902
- } catch {
1903
- }
1904
- }
1905
- const parent = dirname$1(directory);
1906
- if (parent === directory) {
1907
- return false;
1908
- }
1909
- directory = parent;
1910
- }
1911
- };
1912
- const isInsideGitRepo = (startDirectory) => {
1913
- let directory = resolve(startDirectory);
1914
- for (; ; ) {
1915
- if (existsSync(join$1(directory, ".git"))) {
1916
- return true;
1917
- }
1918
- const parent = dirname$1(directory);
1919
- if (parent === directory) {
1920
- return false;
1921
- }
1922
- directory = parent;
1923
- }
1924
- };
1925
- const maybeOfferGit = async (options, target) => {
1926
- if (options.yes === true || !isInteractive() || isInsideGitRepo(dirname$1(target))) {
1927
- return;
1928
- }
1929
- if (!await tuiConfirm(COPY.git, { badge: BADGES.git, defaultYes: false })) {
1930
- await tuiInfo("Sounds good! You can always run git init manually.");
1931
- return;
1932
- }
1933
- if (options.dryRun === true) {
1934
- logWould(options.logger, "initialize a git repository");
1935
- return;
1936
- }
1937
- const spawner = options.spawner ?? defaultSpawner;
1938
- const result = await withTuiSpinner("Initializing a git repository…", () => spawner({ args: ["init"], command: "git", cwd: target }));
1939
- if (result.code === 0) {
1940
- await emitStep("git", "Initialized an empty git repository.");
1941
- } else {
1942
- options.logger.warn("`git init` failed — initialize it yourself later with `git init`.");
1943
- }
1944
- };
1945
- const printNextSteps = async (name, installed, insideMonorepo) => {
1946
- const manager = installed ?? "pnpm";
1947
- const steps = [{ code: `cd ./${name}`, lead: "Enter your project directory using" }];
1948
- if (installed === void 0) {
1949
- steps.push({ code: `${manager} install`, lead: "Install dependencies with", tail: insideMonorepo ? " from the workspace root" : void 0 });
1950
- }
1951
- steps.push(
1952
- { code: runScriptCommand(manager, "dev"), lead: "Run", tail: " to start the dev server." },
1953
- { code: "lunora add", lead: "Add features like auth or storage using" }
1954
- );
1955
- const help = [
1956
- { code: "https://lunora.sh/docs", lead: "Read the docs at" },
1957
- { code: "https://lunora.sh/chat", lead: "Stuck? Join the chat at" }
1958
- ];
1959
- if (isInteractive()) {
1960
- await tuiNextSteps(BADGES.next, COPY.nextHeader, steps, help);
1961
- return;
1962
- }
1963
- const lines = steps.map((step) => `${step.lead} ${step.code}${step.tail ?? ""}`);
1964
- lines.push("", ...help.map((line) => `${line.lead} ${line.code}${line.tail ?? ""}`));
1965
- await emitStep("next", COPY.nextHeader, lines.join("\n"));
1966
- };
1967
- const offerInstallIsInteractive = (options) => options.yes !== true && (options.installPrompt !== void 0 || isInteractive());
1968
- const maybeOfferInstall = async (options, target) => {
1969
- if (!offerInstallIsInteractive(options)) {
1970
- return void 0;
1971
- }
1972
- if (isInsideMonorepo(dirname$1(target))) {
1973
- return void 0;
1974
- }
1975
- const managers = detectInstalledManagers(options.packageManagerProbe);
1976
- const [defaultManager] = managers;
1977
- if (defaultManager === void 0) {
1978
- return void 0;
1979
- }
1980
- const confirm = options.installPrompt?.confirmInstall ?? (async () => tuiConfirm(COPY.install, { badge: BADGES.deps, defaultYes: true }));
1981
- if (!await confirm()) {
1982
- await tuiInfo("No problem! Remember to install dependencies after setup.");
1983
- return void 0;
1984
- }
1985
- let manager = defaultManager;
1986
- if (managers.length > 1) {
1987
- manager = options.installPrompt ? await options.installPrompt.selectManager(managers) : await tuiSelect(
1988
- COPY.packageManager,
1989
- managers.map((candidate) => {
1990
- return { label: candidate, value: candidate };
1991
- }),
1992
- { badge: BADGES.deps, default: defaultManager }
1993
- ) ?? defaultManager;
1994
- }
1995
- if (options.dryRun === true) {
1996
- logWould(options.logger, `install dependencies with ${manager}`);
1997
- return void 0;
1998
- }
1999
- if (manager === "pnpm") {
2000
- const workspacePath = join$1(target, PNPM_WORKSPACE_FILENAME);
2001
- if (!existsSync(workspacePath)) {
2002
- writeFileSync(workspacePath, pnpmWorkspaceYaml(), "utf8");
2003
- }
2004
- }
2005
- const spawner = options.spawner ?? defaultSpawner;
2006
- const { args, command } = installArgsFor(manager);
2007
- await emitStep("deps", `Installing dependencies with ${manager}…`);
2008
- const result = await spawner({ args, command, cwd: target });
2009
- if (result.code !== 0) {
2010
- options.logger.warn(`\`${command} install\` exited with code ${String(result.code)} — run it yourself in ${basename(target)}/.`);
2011
- return void 0;
2012
- }
2013
- await emitStep("deps", `Dependencies installed with ${manager}.`);
2014
- return manager;
2015
- };
2016
- const scaffoldFromLocal = async (fromRoot, templateType, target, name, logger) => {
2017
- const templateDirectory = join$1(fromRoot, templateType);
2018
- if (!existsSync(templateDirectory)) {
2019
- logger.error(`template not found in local source: ${templateDirectory}`);
2020
- return { code: 1, files: [], target };
2021
- }
2022
- const written = await copyTemplate(templateDirectory, target, name);
2023
- logScaffoldSuccess(logger, written, target);
2024
- return { code: 0, files: written, target };
2025
- };
2026
- const scaffoldFromRemote = async (options) => {
2027
- const { logger, name, ref, source, target, templateType } = options;
2028
- const stagingRoot = mkdtempSync(join$1(tmpdir(), "lunora-init-fetch-"));
2029
- const stagingDirectory = join$1(stagingRoot, "template");
2030
- try {
2031
- const remote = resolveTemplateSource(templateType, source, ref);
2032
- let downloaded;
2033
- let written = [];
2034
- await tuiTasks(
2035
- [
2036
- {
2037
- label: `${templateType} template fetched`,
2038
- run: async () => {
2039
- downloaded = await downloadTemplate(remote, {
2040
- cwd: stagingRoot,
2041
- dir: stagingDirectory,
2042
- force: true,
2043
- install: false,
2044
- silent: true
2045
- });
2046
- }
2047
- },
2048
- {
2049
- label: `files copied into ${name}/`,
2050
- run: async () => {
2051
- written = await copyTemplate(stagingDirectory, target, name);
2052
- }
2053
- }
2054
- ],
2055
- { end: "Project initialized!", start: "Project initializing…" }
2056
- );
2057
- const staged = collectFiles(stagingDirectory);
2058
- if (isInteractive()) {
2059
- process.stdout.write("\n");
2060
- }
2061
- logger.info(
2062
- downloaded?.commit ? `template: ${downloaded.source} @ ${downloaded.commit} (${String(staged.length)} files)` : `template: ${downloaded?.source ?? remote} (${String(staged.length)} files)`
2063
- );
2064
- logScaffoldSuccess(logger, written, target);
2065
- return { code: 0, files: written, target };
2066
- } catch (error) {
2067
- if (error instanceof PromptCancelledError) {
2068
- throw error;
2069
- }
2070
- const { hints, message } = describeDownloadFailure(error, {
2071
- ref: resolveSourceRef(ref),
2072
- remote: resolveTemplateSource(templateType, source, ref),
2073
- templateType
2074
- });
2075
- logger.error(message);
2076
- for (const hint of hints) {
2077
- logger.warn(hint);
2078
- }
2079
- return { code: 1, files: [], target };
2080
- } finally {
2081
- rmSync(stagingRoot, { force: true, recursive: true });
2082
- }
2083
- };
2084
- const renameCreateViteDotfiles = (directory) => {
2085
- for (const file of ["_gitignore", "_npmrc", "_gitattributes"]) {
2086
- const from = join$1(directory, file);
2087
- if (existsSync(from)) {
2088
- renameSync(from, join$1(directory, `.${file.slice(1)}`));
2089
- }
2090
- }
2091
- };
2092
- const scaffoldViteOverlay = async (options) => {
2093
- const { framework, logger, name, overlayBaseFrom, target } = options;
2094
- const adapter = ADAPTERS[framework];
2095
- const stagingRoot = mkdtempSync(join$1(tmpdir(), "lunora-vite-base-"));
2096
- try {
2097
- let localBase;
2098
- if (overlayBaseFrom !== void 0) {
2099
- localBase = join$1(overlayBaseFrom, `template-${adapter.createViteTemplate}`);
2100
- if (!existsSync(localBase)) {
2101
- logger.error(`create-vite base not found on disk: ${localBase}`);
2102
- return { code: 1, files: [], target };
2103
- }
2104
- }
2105
- const copyBase = async () => {
2106
- if (localBase !== void 0) {
2107
- cpSync(localBase, target, { recursive: true });
2108
- return;
2109
- }
2110
- const stagingDirectory = join$1(stagingRoot, "base");
2111
- const remote = `github:vitejs/vite/packages/create-vite/template-${adapter.createViteTemplate}#main`;
2112
- await downloadTemplate(remote, { cwd: stagingRoot, dir: stagingDirectory, force: true, install: false, silent: true });
2113
- renameCreateViteDotfiles(stagingDirectory);
2114
- cpSync(stagingDirectory, target, { recursive: true });
2115
- };
2116
- let written = [];
2117
- await tuiTasks(
2118
- [
2119
- { label: `create-vite (${adapter.label}) base ready`, run: copyBase },
2120
- {
2121
- label: `Lunora overlay applied (${adapter.label})`,
2122
- run: async () => {
2123
- written = await applyLunoraOverlay({ adapter, distTag: resolveDistTag(), logger, name, target });
2124
- }
2125
- }
2126
- ],
2127
- { end: "Project initialized!", start: "Project initializing…" }
2128
- );
2129
- logScaffoldSuccess(logger, written, target);
2130
- return { code: 0, files: [...collectFiles(target)], target };
2131
- } catch (error) {
2132
- if (error instanceof PromptCancelledError) {
2133
- throw error;
2134
- }
2135
- const message = error instanceof Error ? error.message : String(error);
2136
- logger.error(`failed to scaffold the ${adapter.label} base: ${message}`);
2137
- return { code: 1, files: [], target };
2138
- } finally {
2139
- rmSync(stagingRoot, { force: true, recursive: true });
2140
- }
2141
- };
2142
- const createMinimalViteConfig = (cwd, logger) => {
2143
- const target = join$1(cwd, "vite.config.ts");
2144
- try {
2145
- writeFileSync(target, MINIMAL_VITE_CONFIG, "utf8");
2146
- } catch (error) {
2147
- const message = error instanceof Error ? error.message : String(error);
2148
- logger.error(`init --in-place: could not write ${target}: ${message}`);
2149
- return { code: 1, files: [], target: cwd };
2150
- }
2151
- logger.success(`created ${target} with lunora() plugin`);
2152
- return { code: 0, files: [target], target: cwd };
2153
- };
2154
- const patchExistingViteConfig = (viteConfigPath, cwd, logger) => {
2155
- let source;
2156
- try {
2157
- source = readFileSync(viteConfigPath, "utf8");
2158
- } catch (error) {
2159
- const message = error instanceof Error ? error.message : String(error);
2160
- logger.error(`init --in-place: could not read ${viteConfigPath}: ${message}`);
2161
- return { code: 1, files: [], target: cwd };
2162
- }
2163
- const result = patchViteConfig(source);
2164
- if (!result.changed) {
2165
- logger.info(`${viteConfigPath}: ${result.reason ?? "no changes needed"}`);
2166
- return { code: 0, files: [], target: cwd };
2167
- }
2168
- try {
2169
- writeFileSync(viteConfigPath, result.code, "utf8");
2170
- } catch (error) {
2171
- const message = error instanceof Error ? error.message : String(error);
2172
- logger.error(`init --in-place: could not write ${viteConfigPath}: ${message}`);
2173
- return { code: 1, files: [], target: cwd };
2174
- }
2175
- logger.success(`patched ${viteConfigPath} — added lunora() plugin`);
2176
- return { code: 0, files: [viteConfigPath], target: cwd };
2177
- };
2178
- const scaffoldLunoraDirectory = (cwd, logger) => {
2179
- const lunoraDirectory = join$1(cwd, "lunora");
2180
- const schemaPath = join$1(lunoraDirectory, "schema.ts");
2181
- if (existsSync(schemaPath)) {
2182
- logger.info(`lunora/ already present — left ${schemaPath} untouched`);
2183
- return [];
2184
- }
2185
- const written = [];
2186
- try {
2187
- mkdirSync(lunoraDirectory, { recursive: true });
2188
- writeFileSync(schemaPath, SAMPLE_SCHEMA, "utf8");
2189
- written.push(schemaPath);
2190
- const functionPath = join$1(lunoraDirectory, "messages.ts");
2191
- if (!existsSync(functionPath)) {
2192
- writeFileSync(functionPath, SAMPLE_FUNCTION, "utf8");
2193
- written.push(functionPath);
2194
- }
2195
- logger.success(`scaffolded lunora/ (${String(written.length)} file(s))`);
2196
- } catch (error) {
2197
- const message = error instanceof Error ? error.message : String(error);
2198
- logger.error(`init --here: could not scaffold lunora/: ${message}`);
2199
- }
2200
- return written;
2201
- };
2202
- const printFrameworkNextSteps = (detection, logger) => {
2203
- const { adapter, class: frameworkClass, framework } = detection;
2204
- logger.info("");
2205
- logger.info(`detected framework: ${framework} (class ${frameworkClass})`);
2206
- logger.info("next steps:");
2207
- logger.info(` 1. install the adapter: pnpm add ${adapter} @lunora/client @lunora/runtime @lunora/server`);
2208
- logger.info(" 2. run codegen: lunora codegen");
2209
- if (frameworkClass === "A") {
2210
- logger.info(" 3. compose one worker: wrap your worker entry with");
2211
- logger.info(" createWorker({ httpRouter: <your framework SSR handler>, shardDO: ShardDO, ... })");
2212
- logger.info(` 4. add the provider: mount the ${adapter} provider in your root layout/route`);
2213
- logger.info(" 5. make a loader live: preloadQuery() in a loader, usePreloadedQuery() in the component");
2214
- logger.info(" see https://lunora.sh/docs/frameworks/reactive-loaders");
2215
- } else if (frameworkClass === "B") {
2216
- logger.info(" 3. inject Lunora: mount Lunora realtime under /_lunora/* in your server hook");
2217
- logger.info(` (${framework} owns its Cloudflare adapter — Lunora composes into its server entry)`);
2218
- logger.info(` 4. add the provider: mount the ${adapter} provider in your root layout`);
2219
- logger.info(" 5. read the guide: https://lunora.sh/docs/frameworks/deploy");
2220
- } else {
2221
- logger.info(" 3. add the provider: wrap your app with the LunoraProvider from @lunora/react");
2222
- logger.info(" 4. read the guide: https://lunora.sh/docs/frameworks/bring-your-framework");
2223
- }
2224
- logger.info("");
2225
- };
2226
- const findExistingViteConfig = (cwd) => {
2227
- for (const candidate of VITE_CONFIG_CANDIDATES) {
2228
- const full = join$1(cwd, candidate);
2229
- if (existsSync(full)) {
2230
- return full;
2231
- }
2232
- }
2233
- return void 0;
2234
- };
2235
- const patchOrCreateViteConfig = (cwd, framework, logger) => {
2236
- const viteConfigPath = findExistingViteConfig(cwd);
2237
- if (viteConfigPath === void 0) {
2238
- if (framework === "sveltekit" || framework === "nuxt" || framework === "astro") {
2239
- logger.info(`no Vite config found — ${framework} wires Lunora through its server entry (see next steps)`);
2240
- return { code: 0, files: [], target: cwd };
2241
- }
2242
- return createMinimalViteConfig(cwd, logger);
2243
- }
2244
- return patchExistingViteConfig(viteConfigPath, cwd, logger);
2245
- };
2246
- const runInPlaceInit = (cwd, logger) => {
2247
- const detection = detectFramework(cwd);
2248
- const viteResult = patchOrCreateViteConfig(cwd, detection.framework, logger);
2249
- if (viteResult.code !== 0) {
2250
- return viteResult;
2251
- }
2252
- const scaffolded = scaffoldLunoraDirectory(cwd, logger);
2253
- printFrameworkNextSteps(detection, logger);
2254
- return { code: 0, files: [...viteResult.files, ...scaffolded], target: cwd };
2255
- };
2256
- const offerIsInteractive = (options) => options.yes !== true && (options.prompt !== void 0 || (options.interactive ?? isInteractive()));
2257
- const maybeOfferExtras = async (options, projectDirectory) => {
2258
- const interactive = offerIsInteractive(options);
2259
- const preselected = options.add === void 0 ? [] : parseFeatureList(options.add, (message) => {
2260
- options.logger.warn(message);
2261
- });
2262
- const applyAll = async (plans) => {
2263
- if (plans.length === 0) {
2264
- return true;
2265
- }
2266
- if (options.dryRun === true) {
2267
- logWould(options.logger, `add ${plans.map((plan) => plan.label).join(", ")}`);
2268
- return true;
2269
- }
2270
- const buffered = [];
2271
- const applyLogger = isInteractive() ? {
2272
- error: (message) => {
2273
- buffered.push({ level: "error", message });
2274
- },
2275
- info: () => {
2276
- },
2277
- success: () => {
2278
- },
2279
- warn: (message) => {
2280
- buffered.push({ level: "warn", message });
2281
- }
2282
- } : options.logger;
2283
- const steps = plans.map((plan) => {
2284
- return {
2285
- running: `adding ${plan.label}…`,
2286
- task: () => runAddCommand({
2287
- allowUnsafeSource: options.allowUnsafeSource,
2288
- cwd: projectDirectory,
2289
- from: options.registryFrom,
2290
- logger: applyLogger,
2291
- names: [...plan.names],
2292
- ref: options.ref,
2293
- source: options.registrySource,
2294
- transformManifest: plan.transformManifest,
2295
- yes: true
2296
- })
2297
- };
2298
- });
2299
- const done = `added ${plans.map((plan) => plan.label).join(", ")}`;
2300
- const results = await withTuiBadgeProgress(BADGES.add, steps, done);
2301
- for (const { level, message } of buffered) {
2302
- options.logger[level](message);
2303
- }
2304
- return results.every((result) => result.code === 0);
2305
- };
2306
- const deps = {
2307
- applyAll,
2308
- interactive,
2309
- logger: options.logger,
2310
- multiSelect: options.prompt?.multiSelect ?? ((message, choices, settings) => tuiMultiSelect(message, choices, { ...settings, badge: BADGES.add })),
2311
- preselected: preselected.length > 0 ? preselected : void 0,
2312
- projectName: basename(projectDirectory),
2313
- select: options.prompt?.select ?? ((message, choices, settings) => tuiSelect(message, choices, { ...settings, badge: BADGES.add })),
2314
- text: options.prompt?.text ?? ((message, settings) => tuiText(message, { ...settings, badge: BADGES.add }))
2315
- };
2316
- if (preselected.length > 0) {
2317
- await offerRegistryExtras(deps);
2318
- return;
2319
- }
2320
- if (isInteractive()) {
2321
- await tuiHeadline(COPY.extras);
2322
- }
2323
- await offerRegistryExtras(deps);
2324
- };
2325
- const DEFAULT_FRAMEWORK = "react";
2326
- const FRAMEWORK_CHOICES = [
2327
- { description: "React SPA — official create-vite base + the Lunora layer (the default)", label: "React", value: "react" },
2328
- { description: "Vue SPA — create-vite base + Lunora", label: "Vue", value: "vue" },
2329
- { description: "Solid SPA — create-vite base + Lunora", label: "Solid", value: "solid" },
2330
- { description: "Svelte SPA — create-vite base + Lunora", label: "Svelte", value: "svelte" },
2331
- { description: "TanStack Start (React) — SSR with live-loader routes", label: "TanStack Start · React", value: "tanstack-start-react" },
2332
- { description: "TanStack Start (Solid)", label: "TanStack Start · Solid", value: "tanstack-start-solid" },
2333
- { description: "React Router (v7, framework mode) — SSR composed into the Lunora worker", label: "React Router", value: "react-router" },
2334
- { description: "Astro + a standalone Lunora worker", label: "Astro", value: "astro" },
2335
- { description: "AnalogJS (Angular) — single-worker, Lunora mounted in Nitro", label: "Analog", value: "analog" },
2336
- { description: "Nuxt (Vue) — single-worker, Lunora mounted in Nitro", label: "Nuxt", value: "nuxt" },
2337
- { description: "SvelteKit + a standalone Lunora worker", label: "SvelteKit", value: "sveltekit" },
2338
- { description: "Worker only — no frontend", label: "Standalone", value: "standalone" }
2339
- ];
2340
- const OVERLAY_VALUES = Object.keys(ADAPTERS).join("|");
2341
- const TEMPLATE_VALUES = FRAMEWORK_CHOICES.filter((choice) => !isOverlayFramework(choice.value)).map((choice) => choice.value).join("|");
2342
- const toScaffoldChoice = (value) => isOverlayFramework(value) ? { framework: value, kind: "overlay" } : { kind: "template", templateType: value };
2343
- const resolveScaffoldChoice = async (options) => {
2344
- if (options.vite !== void 0) {
2345
- return { framework: options.vite, kind: "overlay" };
2346
- }
2347
- if (options.templateType !== void 0) {
2348
- return { kind: "template", templateType: options.templateType };
2349
- }
2350
- if (!isInteractive() || options.yes === true) {
2351
- return { framework: DEFAULT_FRAMEWORK, kind: "overlay" };
2352
- }
2353
- return toScaffoldChoice(await tuiSelect(COPY.framework, FRAMEWORK_CHOICES, { badge: BADGES.tmpl, default: DEFAULT_FRAMEWORK }) ?? DEFAULT_FRAMEWORK);
2354
- };
2355
- const nonInteractiveInitError = (options) => {
2356
- if (isInteractive() || options.yes === true) {
2357
- return void 0;
2358
- }
2359
- const missing = [];
2360
- if (options.name === void 0) {
2361
- missing.push("a project name (`lunora init <name>`)");
2362
- }
2363
- if (options.templateType === void 0 && options.vite === void 0) {
2364
- missing.push(`a framework — \`--vite <${OVERLAY_VALUES}>\` for an SPA, or \`-t <${TEMPLATE_VALUES}>\` for a bespoke template`);
2365
- }
2366
- if (missing.length === 0) {
2367
- return void 0;
2368
- }
2369
- return `lunora init can't prompt in a non-interactive terminal — provide ${missing.join(" and ")}, or pass --yes to accept the defaults.`;
2370
- };
2371
- const scaffoldOverlayPath = async (options, framework, name, target) => {
2372
- if (!isOverlayFramework(framework)) {
2373
- options.logger.error(`init: unknown framework "${framework}". Supported overlays: ${Object.keys(ADAPTERS).join(", ")}.`);
2374
- return { code: 1, files: [], target };
2375
- }
2376
- if (!await verifyRemoteTemplate({ isLocal: options.overlayBaseFrom !== void 0, logger: options.logger })) {
2377
- return { code: 1, files: [], target };
2378
- }
2379
- mkdirSync(target, { recursive: true });
2380
- return scaffoldViteOverlay({ framework, logger: options.logger, name, overlayBaseFrom: options.overlayBaseFrom, target });
2381
- };
2382
- const scaffoldTemplatePath = async (options, templateType, name, target) => {
2383
- if (templateType === "next") {
2384
- options.logger.warn('template "next" is not yet available — re-run with `--vite react` or `-t standalone`.');
2385
- return { code: 1, files: [], target };
2386
- }
2387
- if (options.from !== void 0) {
2388
- return await scaffoldFromLocal(options.from, templateType, target, name, options.logger);
2389
- }
2390
- if (options.source !== void 0 && options.source.length > 0 && !options.allowUnsafeSource && !isSafeSource(options.source)) {
2391
- options.logger.error(
2392
- `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.`
2393
- );
2394
- return { code: 1, files: [], target };
2395
- }
2396
- if (!await verifyRemoteTemplate({ isLocal: false, logger: options.logger, source: resolveTemplateSource(templateType, options.source, options.ref) })) {
2397
- return { code: 1, files: [], target };
2398
- }
2399
- return scaffoldFromRemote({ logger: options.logger, name, ref: options.ref, source: options.source, target, templateType });
2400
- };
2401
- const scaffoldNewProject = async (options, cwd, recordTarget) => {
2402
- await tuiMoonrise("realtime backend on Cloudflare Workers + Durable Objects");
2403
- const blocked = nonInteractiveInitError(options);
2404
- if (blocked !== void 0) {
2405
- options.logger.error(blocked);
2406
- return { code: 1, files: [], target: "" };
2407
- }
2408
- const suggestedName = generateProjectName();
2409
- const name = options.name ?? await tuiText(COPY.name, { badge: BADGES.dir, default: suggestedName, placeholder: suggestedName });
2410
- const choice = await resolveScaffoldChoice(options);
2411
- if (name.includes("/") || name.includes("\\") || name === ".." || name === ".") {
2412
- options.logger.error(`init: refusing project name "${name}" — must not contain path separators or be "." / "..".`);
2413
- return { code: 1, files: [], target: "" };
2414
- }
2415
- const target = resolve(cwd, name);
2416
- const targetPreExisted = existsSync(target);
2417
- if (targetPreExisted) {
2418
- const entries = readdirSync(target);
2419
- if (entries.length > 0) {
2420
- options.logger.error(`target directory not empty: ${target}`);
2421
- return { code: 1, files: [], target };
2422
- }
2423
- }
2424
- if (options.dryRun === true) {
2425
- const what = choice.kind === "overlay" ? `the ${choice.framework} create-vite overlay` : `the ${choice.templateType} template`;
2426
- logWould(options.logger, `scaffold ${what} into ${target}`);
2427
- return { code: 0, files: [], target };
2428
- }
2429
- recordTarget(target, targetPreExisted);
2430
- return choice.kind === "overlay" ? scaffoldOverlayPath(options, choice.framework, name, target) : scaffoldTemplatePath(options, choice.templateType, name, target);
2431
- };
2432
- const resetScaffoldOnCancel = (cleanup, logger) => {
2433
- const { target, targetPreExisted } = cleanup;
2434
- if (target === void 0 || !existsSync(target)) {
2435
- return;
2436
- }
2437
- if (targetPreExisted === true) {
2438
- for (const entry of readdirSync(target)) {
2439
- rmSync(join$1(target, entry), { force: true, recursive: true });
2440
- }
2441
- } else {
2442
- rmSync(target, { force: true, recursive: true });
2443
- }
2444
- logger.info(`removed the partially-created project at ${target}`);
2445
- };
2446
- const runScaffoldStep = async (options, cwd, recordTarget) => {
2447
- if (options.inPlace !== true) {
2448
- return scaffoldNewProject(options, cwd, recordTarget);
2449
- }
2450
- if (options.dryRun === true) {
2451
- logWould(options.logger, `configure Lunora into ${cwd}`);
2452
- return { code: 0, files: [], target: cwd };
2453
- }
2454
- return runInPlaceInit(cwd, options.logger);
2455
- };
2456
- const runPostScaffold = async (options, result, cwd) => {
2457
- await maybeOfferExtras(options, result.target);
2458
- const installedManager = options.inPlace === true ? void 0 : await maybeOfferInstall(options, result.target);
2459
- if (options.inPlace !== true) {
2460
- await maybeOfferGit(options, result.target);
2461
- await printNextSteps(basename(result.target), installedManager, isInsideMonorepo(cwd));
2462
- await emitMascot(options.logger);
2463
- }
2464
- };
2465
- const scaffoldCiPipeline = (options, result, cwd) => {
2466
- if (result.code !== 0 || options.ci === void 0) {
2467
- return;
2468
- }
2469
- if (options.dryRun === true) {
2470
- logWould(options.logger, `scaffold a ${options.ci} CI deploy pipeline`);
2471
- return;
2472
- }
2473
- scaffoldCiWorkflow(options.inPlace === true ? cwd : result.target, options.ci, options.logger);
2474
- };
2475
- const runInitCommand = async (options) => {
2476
- const cwd = options.cwd ?? process.cwd();
2477
- const cleanup = {};
2478
- let result;
2479
- try {
2480
- result = await runScaffoldStep(options, cwd, (target, preExisted) => {
2481
- cleanup.target = target;
2482
- cleanup.targetPreExisted = preExisted;
2483
- });
2484
- if (result.code === 0 && result.target !== "") {
2485
- cleanup.target = void 0;
2486
- await runPostScaffold(options, result, cwd);
2487
- }
2488
- } catch (error) {
2489
- if (error instanceof PromptCancelledError) {
2490
- resetScaffoldOnCancel(cleanup, options.logger);
2491
- process.stdout.write("\n ✖ Setup cancelled — run `lunora init` again whenever you're ready. 🌙\n");
2492
- return { code: 130, files: [], target: "" };
2493
- }
2494
- throw error;
2495
- }
2496
- scaffoldCiPipeline(options, result, cwd);
2497
- return result;
2498
- };
2499
- 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";
2500
- const resolveCiProvider = (raw, logger) => {
2501
- if (raw === void 0) {
2502
- return void 0;
2503
- }
2504
- if (isCiProvider(raw)) {
2505
- return raw;
2506
- }
2507
- logger.warn(`init: unknown --ci "${raw}" — expected github | gitlab; skipping CI scaffold.`);
2508
- return void 0;
2509
- };
2510
- const execute = defineHandler(({ argument, cwd, logger, options }) => {
2511
- const templateType = options.template !== void 0 && isTemplate(options.template) ? options.template : void 0;
2512
- return runInitCommand({
2513
- add: options.add,
2514
- allowUnsafeSource: options.allowUnsafeSource === true,
2515
- cwd,
2516
- ci: resolveCiProvider(options.ci, logger),
2517
- dryRun: options.dryRun === true,
2518
- from: options.from,
2519
- inPlace: options.here === true,
2520
- interactive: options.interactive === true ? true : void 0,
2521
- logger,
2522
- name: argument[0],
2523
- ref: options.ref,
2524
- source: options.source,
2525
- templateType,
2526
- vite: options.vite,
2527
- yes: options.yes === true
2528
- });
2529
- });
2530
-
2531
- export { execute, isTemplate, resolveTemplateSource, runInitCommand };
1259
+ `,Kr="gh:anolilab/lunora/templates",qr=e=>{const t=e.lastIndexOf(".");return t===-1?!1:Fr.has(e.slice(t))},Gr=/^[a-z0-9_][a-z0-9\-_]*$/u,Yr=/([a-z0-9])([A-Z])/gu,Jr=/[^a-z0-9_]/gu,Xr=e=>{const t=e.replaceAll(Yr,"$1-$2").toLowerCase().replaceAll(Jr,"-").split("-").filter(r=>r.length>0);return t.length>0?t.join("-"):"my-app"},Qr=(e,t)=>e.replaceAll("{{name}}",t),Zr=async(e,t)=>{const r=new Set;for(const a of e)if(_(a)==="package.json")try{const o=JSON.parse(k(a,"utf8"));for(const n of["dependencies","devDependencies"])for(const s of Object.keys(o[n]??{}))U(s)&&r.add(s)}catch{}return ve(r,t)},ea=(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(!U(s))continue;const i=r.get(s)??t,l=lt(o,[n,s],i,{formattingOptions:{insertSpaces:!0,tabSize:4}});o=ct(o,l)}return o},ta=["@parcel/watcher","esbuild","lmdb","msgpackr-extract","rs-module-lexer","sharp","unrs-resolver","vue-demi","workerd"],ra=["cpu-features","protobufjs","ssh2"],De="pnpm-workspace.yaml",aa=()=>["# 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:",...ta.map(e=>` '${e}': true`),...ra.map(e=>` '${e}': false`),""].join(`
1260
+ `),Be=e=>{const t=p(e,De);m(t)||w(t,aa(),"utf8")},V=e=>{const t=[];for(const r of it(e,{includeDirs:!1,includeFiles:!0}))de(r.path).isSymbolicLink()||t.push(r.path);return t},se="vitejs/vite",ie=(e,t)=>{for(const r of V(e)){const a=p(t,fe(e,r));M(A(a),{recursive:!0}),Ge(r,a)}},je=async(e,t,r)=>{const a=V(e),o=[],n=we(),s=await Zr(a,n);for(const i of a){const l=fe(e,i),c=p(t,l);M(A(c),{recursive:!0});const u=k(i);let h=qr(i)?Qr(u.toString("utf8"),r):void 0;h!==void 0&&_(i)==="package.json"&&(h=ea(h,n,s)),h===void 0?w(c,u):w(c,h,"utf8"),o.push(c)}return o},H=(e,t,r)=>t!==void 0&&t.length>0?t:`${Kr}/${e}#${ye(r)}`,oa=e=>e.includes("..")?!1:e.startsWith("gh:")||e.startsWith("github:")||e.startsWith("https://"),E=(e,t)=>{e.info(`[dry-run] would ${t}`)},Ue=(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:f.NOT_FOUND,files:[],target:t}),Ve="Template files copied.",J=(e,t,r)=>{y()&&process.stdout.write(`
1261
+ `),e.success(`scaffolded ${String(t.length)} files into ${r}`)},na=(e,t)=>{const{args:r,command:a}=nt(e,t);return`${a} ${r.join(" ")}`},Fe=(e,t)=>{let r=me(e);for(;;){if(t(r))return!0;const a=A(r);if(a===r)return!1;r=a}},sa=e=>{if(m(p(e,De)))return!0;const t=p(e,"package.json");if(!m(t))return!1;try{return JSON.parse(k(t,"utf8")).workspaces!==void 0}catch{return!1}},X=e=>Fe(e,sa),ia=e=>Fe(e,t=>m(p(t,".git"))),la=async(e,t)=>{if(e.yes===!0||!y()||ia(A(t)))return;if(!await Ce(x.git,{badge:v.git,defaultYes:!1})){await Se("Sounds good! You can always run git init manually.");return}if(e.dryRun===!0){E(e.logger,"initialize a git repository");return}const r=e.spawner??be;(await bt("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`.")},ca=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:at(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(y()){await xt(v.next,x.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",x.nextHeader,s.join(`
1262
+ `))},da=e=>e.yes!==!0&&(e.installPrompt!==void 0||y()),ua=async(e,t)=>{if(!da(e)||X(A(t)))return;const r=rt(e.packageManagerProbe),[a]=r;if(a===void 0)return;if(!await(e.installPrompt?.confirmInstall??(async()=>Ce(x.install,{badge:v.deps,defaultYes:!0})))()){await Se("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 G(x.packageManager,r.map(u=>({label:u,value:u})),{badge:v.deps,default:a})??a),e.dryRun===!0){E(e.logger,`install dependencies with ${n}`);return}n==="pnpm"&&Be(t);const s=e.spawner??be,{args:i,command:l}=he(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 ${_(t)}/.`);return}return await T("deps",`Dependencies installed with ${n}.`),n},pa=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:f.NOT_FOUND,files:[],target:r};const i=await je(s,r,a);return i.length===0?Ue(o,r,s):(n(),J(o,i,r),{code:0,files:i,target:r})},ha=async e=>{const{logger:t,markComplete:r,name:a,ref:o,source:n,target:s,templateType:i}=e,l=ue(p(pe(),"lunora-init-fetch-")),c=p(l,"template");try{const u=n!==void 0&&n.length>0?o:await ft(o,t),h=H(i,n,u);let d,b=[];if(await Le([{label:`${i} template fetched`,run:async()=>{d=await ge(h,{cwd:l,dir:c,force:!0,install:!1,silent:!0})}},{label:`files copied into ${a}/`,run:async()=>{b=await je(c,s,a)}}],{end:Ve,start:"Project initializing…"}),b.length===0)return Ue(t,s,d?.source??h);r();const $=V(c);return y()&&process.stdout.write(`
1263
+ `),t.info(d?.commit?`template: ${d.source} @ ${d.commit} (${String($.length)} files)`:`template: ${d?.source??h} (${String($.length)} files)`),J(t,b,s),{code:0,files:b,target:s}}catch(u){if(u instanceof q)throw u;const{hints:h,message:d}=Zt(u,{ref:ye(o),remote:H(i,n,o),templateType:i});t.error(d);for(const b of h)t.warn(b);return{code:1,files:[],target:s}}finally{O(l,{force:!0,recursive:!0})}},ma=e=>{for(const t of["_gitignore","_npmrc","_gitattributes"]){const r=p(e,t);m(r)&&Ye(r,p(e,`.${t.slice(1)}`))}},fa=async e=>{const{framework:t,logger:r,markComplete:a,name:o,overlayBaseFrom:n,target:s}=e,i=B[t],l=ue(p(pe(),"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:f.NOT_FOUND,files:[],target:s};const u=async()=>{if(c!==void 0){ie(c,s);return}const d=p(l,"base"),b=await mt(se,"main",r),$=`github:${se}/packages/create-vite/template-${i.createViteTemplate}#${b}`;await ge($,{cwd:l,dir:d,force:!0,install:!1,silent:!0}),ma(d),ie(d,s)};let h=[];return await Le([{label:`create-vite (${i.label}) base ready`,run:u},{label:`Lunora overlay applied (${i.label})`,run:async()=>{h=await Tr({adapter:i,distTag:we(),logger:r,name:o,target:s})}}],{end:Ve,start:"Project initializing…"}),a(),J(r,h,s),{code:0,files:[...V(s)],target:s}}catch(c){if(c instanceof q)throw c;const u=c instanceof Error?c.message:String(c);return r.error(`failed to scaffold the ${i.label} base: ${u}`),{code:1,files:[],target:s}}finally{O(l,{force:!0,recursive:!0})}},z=(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}),ga=(e,t)=>{const r=p(e,"vite.config.ts");try{w(r,Wr,"utf8")}catch(a){return z("write",r,a,e,t)}return t.success(`created ${r} with lunora() plugin`),{code:0,files:[r],target:e}},va=(e,t,r)=>{let a;try{a=k(e,"utf8")}catch(n){return z("read",e,n,t,r)}const o=Ie(a);if(!o.changed)return r.info(`${e}: ${o.reason??"no changes needed"}`),{code:0,files:[],target:t};try{w(e,o.code,"utf8")}catch(n){return z("write",e,n,t,r)}return r.success(`patched ${e} — added lunora() plugin`),{code:0,files:[e],target:t}},wa=(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{M(r,{recursive:!0}),w(a,Hr,"utf8"),o.push(a);const n=p(r,"messages.ts");m(n)||(w(n,zr,"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},We=e=>e==="sveltekit"||e==="nuxt"||e==="astro",ya=(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"];We(n)||s.push("@lunora/vite"),r.info(` 1. install the adapter: ${na(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("")},ba=(e,t,r)=>{if(We(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=Oe(e);return a===void 0?ga(e,r):va(a,e,r)},xa=(e,t)=>{const r=Vt(e),a=ba(e,r.framework,t);if(a.code!==0)return a;const o=wa(e,t);return ya(r,P(e),t),{code:0,files:[...a.files,...o],target:e}},ka=e=>e.yes!==!0&&(e.prompt!==void 0||(e.interactive??y())),le=async(e,t,r)=>{r.dryRun!==!0&&await ur({apply:a=>st(e,a),detected:ot(e),interactive:t,logger:r.logger,multiSelect:r.lintPrompt??((a,o,n)=>ke(a,o,{...n,badge:v.add}))})},Ca=async(e,t)=>{const r=ka(e),a=e.add===void 0?[]:rr(e.add,s=>{e.logger.warn(s)}),n={applyAll:async s=>{if(s.length===0)return!0;if(e.dryRun===!0)return E(e.logger,`add ${s.map(d=>d.label).join(", ")}`),!0;const i=[],l=y()?{error:d=>{i.push({level:"error",message:d})},info:()=>{},success:()=>{},warn:d=>{i.push({level:"warn",message:d})}}:e.logger,c=s.map(d=>({running:`adding ${d.label}…`,task:()=>It({allowUnsafeSource:e.allowUnsafeSource,cwd:t,from:e.registryFrom,logger:l,names:[...d.names],ref:e.ref,source:e.registrySource,transformManifest:d.transformManifest,yes:!0})})),u=`added ${s.map(d=>d.label).join(", ")}`,h=await kt(v.add,c,u);for(const{level:d,message:b}of i)e.logger[d](b);return h.every(d=>d.code===0)},interactive:r,logger:e.logger,multiSelect:e.prompt?.multiSelect??((s,i,l)=>ke(s,i,{...l,badge:v.add})),preselected:a.length>0?a:void 0,projectName:_(t),resolveAuthUiItem:()=>{let s;try{const i=JSON.parse(k(p(t,"package.json"),"utf8"));s={...i.dependencies,...i.devDependencies}}catch{return"auth-ui-react"}if(!Nt(s))return _t(s)??"auth-ui-react"},select:e.prompt?.select??((s,i,l)=>G(s,i,{...l,badge:v.add})),text:e.prompt?.text??((s,i)=>xe(s,{...i,badge:v.add}))};if(a.length>0){const s=await re(n);return await le(t,r,e),s}return y()&&await yt(x.extras),await re(n),await le(t,r,e),!0},F="react",He=[{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"}],ze=Object.keys(B).join("|"),Ke=He.filter(e=>!j(e.value)).map(e=>e.value),qe=Ke.join("|"),Sa=e=>j(e)?{framework:e,kind:"overlay"}:{kind:"template",templateType:e},La=async e=>e.vite!==void 0?{framework:e.vite,kind:"overlay"}:e.templateType!==void 0?{kind:"template",templateType:e.templateType}:!y()||e.yes===!0?{framework:F,kind:"overlay"}:Sa(await G(x.framework,He,{badge:v.tmpl,default:F})??F),Ma=e=>{if(y()||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 <${ze}>\` for an SPA, or \`-t <${qe}>\` 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.`},Aa=async(e,t,r,a,o)=>j(t)?await Pe({isLocal:e.overlayBaseFrom!==void 0,logger:e.logger})?(M(a,{recursive:!0}),fa({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(B).join(", ")}.`),{code:f.USAGE,files:[],target:a}),Ea=async(e,t,r,a,o)=>e.from!==void 0?await pa(e.from,t,a,r,e.logger,o):e.source!==void 0&&e.source.length>0&&!e.allowUnsafeSource&&!oa(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:f.USAGE,files:[],target:a}):await Pe({isLocal:!1,logger:e.logger,source:H(t,e.source,e.ref)})?ha({logger:e.logger,markComplete:o,name:r,ref:e.ref,source:e.source,target:a,templateType:t}):{code:1,files:[],target:a},Na=(e,t)=>{if(X(t))return;let r;try{r=P(e)}catch{return}r==="pnpm"&&Be(e)},_a=async(e,t,r)=>{await wt("realtime backend on Cloudflare Workers + Durable Objects");const a=Ma(e);if(a!==void 0)return e.logger.error(a),{code:f.USAGE,files:[],target:""};const o=Br(),n=e.name??await xe(x.name,{badge:v.dir,default:o,placeholder:o}),s=await La(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:f.USAGE,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:f.USAGE,files:[],target:""};if(!Gr.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 \`${Xr(i)}\`.`),{code:f.USAGE,files:[],target:""};const l=me(t,i),c=de(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:f.CONFLICT,files:[],target:l};const u=c!==void 0;if(u&&ce(l).length>0)return e.logger.error(`target directory not empty: ${l}`),{code:f.CONFLICT,files:[],target:l};if(e.dryRun===!0){const d=s.kind==="overlay"?`the ${s.framework} create-vite overlay`:`the ${s.templateType} template`;return E(e.logger,`scaffold ${d} into ${l}`),{code:0,files:[],target:l}}r.record(l,u);const h=s.kind==="overlay"?await Aa(e,s.framework,i,l,r.complete):await Ea(e,s.templateType,i,l,r.complete);return h.code===0&&Na(l,t),h},W=(e,t)=>{const{target:r,targetPreExisted:a}=e;if(!(r===void 0||!m(r))){if(a===!0)for(const o of ce(r))O(p(r,o),{force:!0,recursive:!0});else O(r,{force:!0,recursive:!0});t.info(`removed the partially-created project at ${r}`)}},Ia=async(e,t,r)=>e.inPlace!==!0?_a(e,t,r):e.dryRun===!0?(E(e.logger,`configure Lunora into ${t}`),{code:0,files:[],target:t}):xa(t,e.logger),$a=async(e,t,r)=>{const a=await Ca(e,t.target),o=e.inPlace===!0?void 0:await ua(e,t.target);if(e.inPlace!==!0){await la(e,t.target);const n=o??P(t.target);await ca(_(t.target),o,n,X(r)),await er(e.logger)}return a},Ra=(e,t,r)=>{if(t.code!==0||e.ci===void 0)return;if(e.dryRun===!0){E(e.logger,`scaffold a ${e.ci} CI deploy pipeline`);return}const a=e.inPlace===!0?r:t.target;try{const o=P(a);jt(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.`)}},Oa=async e=>{const t=e.cwd??process.cwd(),r={};let a;try{a=await Ia(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 $a(e,a,t)||(a={...a,code:1})):a.code!==0&&W(r,e.logger)}catch(o){if(o instanceof q)return W(r,e.logger),process.stdout.write("\n ✖ Setup cancelled — run `lunora init` again whenever you're ready. 🌙\n"),{code:130,files:[],target:""};throw W(r,e.logger),o}return Ra(e,a,t),a},Ta=e=>typeof e=="string"&&Ke.includes(e),Pa=(e,t)=>{if(e!==void 0){if(Dt(e))return e;t.warn(`init: unknown --ci "${e}" — expected github | gitlab; skipping CI scaffold.`)}},Da=e=>e===void 0?{}:Ta(e)?{templateType:e}:j(e)?{vite:e}:{error:`init: unknown --template "${e}" — expected a bespoke template (${qe}) or an overlay framework (${ze}).`},no=ut(({argument:e,cwd:t,logger:r,options:a})=>{const o=Da(a.template);return"error"in o?(r.error(o.error),{code:f.USAGE}):Oa({add:a.add,allowUnsafeSource:a.allowUnsafeSource===!0,cwd:t,ci:Pa(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{He as FRAMEWORK_CHOICES,no as execute,Ta as isTemplate,Da as resolveTemplateFlag,H as resolveTemplateSource,Oa as runInitCommand};