@lunora/cli 1.0.0-alpha.479 → 1.0.0-alpha.480
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.
- package/dist/packem_chunks/handler.mjs +14 -13
- package/dist/packem_chunks/handler30.mjs +13 -13
- package/dist/packem_chunks/runDevCommand.mjs +6 -6
- package/dist/packem_chunks/runInitCommand.mjs +69 -69
- package/package.json +8 -8
- package/skills/lunora-create-package/SKILL.md +3 -2
- package/skills/lunora-realtime/SKILL.md +4 -2
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
import{existsSync as f,mkdirSync as
|
|
1
|
+
import{existsSync as f,mkdirSync as I,writeFileSync as v,readFileSync as _,appendFileSync as lt,readdirSync as J,rmSync as P,lstatSync as ye,mkdtempSync as be,copyFileSync as ct,renameSync as dt}from"node:fs";import{tmpdir as ke}from"node:os";import{detectFramework as ut,DEV_VARS_EXAMPLE_FILE as xe,DEV_VARS_FILE as ht,isInteractive as k,LUNA_ART as pt,LUNA_NAME as mt,LUNA_SIGNOFF as ft,BADGES as w,paintAnswer as vt,detectLintTools as gt,readProjectDependencies as Ee,applyLintIgnores as wt,readProjectManifest as yt}from"@lunora/config";import{readJsonSync as bt,walkSync as kt}from"@visulima/fs";import{relative as j,join as u,dirname as S,basename as T,resolve as _e}from"@visulima/path";import{downloadTemplate as Ce}from"giget";import{modify as xt,applyEdits as Et}from"jsonc-parser";import{join as Q,dirname as _t}from"node:path";import{EXIT_CODE as g}from"../packem_shared/EXIT_CODE-DQVhSE-1.mjs";import{installArgsFor as Se,execArgsFor as Ct,detectPackageManager as V,detectInstalledManagers as St,runScriptCommand as Lt,addArgsFor as At}from"@lunora/config/cli";import{d as It}from"../packem_shared/command-BpMv2n0o.mjs";import Rt from"magic-string";import{Project as Ot,SyntaxKind as b,ts as y}from"ts-morph";import{P as X}from"../packem_shared/prompt-cancelled-BvsNxg_Q.mjs";import{l as Le,m as Tt,n as Ae,o as Ie,a as $t}from"../packem_shared/resolve-Bdc9KEUv.mjs";import{defaultSpawner as Re}from"../packem_shared/createRecordingSpawner-DchLi0gR.mjs";import{d as Mt,e as Nt,f as Pt,a as Oe,t as D,g as Te,h as Dt,b as $e,i as Me,w as Ut,j as jt,k as Ne,l as Vt}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{A as Pe,p as Bt,w as Ft,M as Wt,r as qt,E as De,k as Ht,e as Kt,c as Ue,l as je,i as zt,f as Gt}from"../packem_shared/storage-3GOIFVZm.mjs";import{r as Yt}from"../packem_shared/commands-CkuCMUP_.mjs";import{findWranglerFile as Jt,readWranglerJsonc as Qt,DEFAULT_OBSERVABILITY as Xt,CLOUDFLARE_TOOLCHAIN_VERSIONS as ne}from"@lunora/config/cloudflare";import{logStep as ae}from"../packem_shared/createLogger-4TujevyB.mjs";import{r as Zt}from"../packem_shared/lint-ignore-report-DKZagpqk.mjs";import er from"node:dns/promises";const Z={bun:{githubCacheKey:void 0,githubSetupStep:` - uses: oven-sh/setup-bun@v2
|
|
2
2
|
`,gitlabImage:"oven/bun:1",gitlabProvisionScript:[],installCmd:"bun install --frozen-lockfile",lockfile:"bun.lockb"},npm:{githubCacheKey:"npm",githubSetupStep:"",gitlabImage:"node:22",gitlabProvisionScript:[],installCmd:"npm ci",lockfile:"package-lock.json"},pnpm:{githubCacheKey:"pnpm",githubSetupStep:` - uses: pnpm/action-setup@v4
|
|
3
3
|
with:
|
|
4
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"}},
|
|
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"}},E=(e,t)=>{const r=Ct(e,"lunora",t);return[r.command,...r.args].join(" ")},M=(e,t,r="")=>` - uses: actions/checkout@v4
|
|
6
6
|
${t===void 0?"":` with:
|
|
7
7
|
ref: ${t}
|
|
8
8
|
`}${e.githubSetupStep} - uses: actions/setup-node@v4
|
|
9
9
|
with:
|
|
10
10
|
node-version: 22
|
|
11
11
|
${e.githubCacheKey===void 0?"":` cache: ${e.githubCacheKey}
|
|
12
|
-
`} - run: ${e.installCmd}${r}`,
|
|
12
|
+
`} - run: ${e.installCmd}${r}`,tr=e=>{const t=Z[e],r=t.githubCacheKey===void 0?`# (below) requires it — run \`${e} install\` locally and`:`# (below) and the ${e} cache both require it — run \`${e} install\` locally and`;return`name: Deploy
|
|
13
13
|
|
|
14
14
|
on:
|
|
15
15
|
push:
|
|
@@ -60,7 +60,7 @@ ${M(t)}
|
|
|
60
60
|
# only trusted when the project is linked and .lunora/ is not committed, so
|
|
61
61
|
# CI has no link: there the gate stays blocked, and a tightening needs a
|
|
62
62
|
# migration or --allow-schema-drift. A custom domain on a declared route works.
|
|
63
|
-
- run: ${
|
|
63
|
+
- run: ${E(e,["deploy","--migrate-url",'"${{ secrets.LUNORA_DEPLOY_URL }}"'])}
|
|
64
64
|
env:
|
|
65
65
|
CLOUDFLARE_API_TOKEN: \${{ secrets.CLOUDFLARE_API_TOKEN }}
|
|
66
66
|
CLOUDFLARE_ACCOUNT_ID: \${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
|
@@ -77,7 +77,7 @@ ${M(t)}
|
|
|
77
77
|
contents: read
|
|
78
78
|
steps:
|
|
79
79
|
${M(t)}
|
|
80
|
-
- run: ${
|
|
80
|
+
- run: ${E(e,["preview","deploy","${{ github.event.pull_request.number }}"])}
|
|
81
81
|
env:
|
|
82
82
|
CLOUDFLARE_API_TOKEN: \${{ secrets.CLOUDFLARE_PREVIEW_API_TOKEN }}
|
|
83
83
|
CLOUDFLARE_ACCOUNT_ID: \${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
|
@@ -115,7 +115,7 @@ ${M(t,"${{ github.event.pull_request.base.ref }}"," --ignore-scripts")}
|
|
|
115
115
|
# Exit 5 is "no record": the pull request never got a preview (refused, or opened before this workflow). The CLI
|
|
116
116
|
# answers it only when the head's identity is the base's; a head whose identity differs, or cannot be read, with no
|
|
117
117
|
# record under the base's fails the job, since the preview may be recorded under the head's.
|
|
118
|
-
- run: ${
|
|
118
|
+
- run: ${E(e,["preview","delete","${{ github.event.pull_request.number }}","--head-dir",'"$HEAD_DIR"'])} || [ "$?" -eq ${String(g.NOT_FOUND)} ]
|
|
119
119
|
env:
|
|
120
120
|
CLOUDFLARE_API_TOKEN: \${{ secrets.CLOUDFLARE_PREVIEW_API_TOKEN }}
|
|
121
121
|
CLOUDFLARE_ACCOUNT_ID: \${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
|
@@ -130,11 +130,11 @@ ${M(t,"${{ github.event.pull_request.base.ref }}"," --ignore-scripts")}
|
|
|
130
130
|
contents: read
|
|
131
131
|
steps:
|
|
132
132
|
${M(t)}
|
|
133
|
-
- run: ${
|
|
134
|
-
`},oe="lunora-preview-$CI_MERGE_REQUEST_IID",
|
|
133
|
+
- run: ${E(e,["deploy","--dry-run"])}
|
|
134
|
+
`},oe="lunora-preview-$CI_MERGE_REQUEST_IID",rr=e=>{const t=Z[e],r=[...t.gitlabProvisionScript,t.installCmd].map(s=>` - ${s}`).join(`
|
|
135
135
|
`),n=t.gitlabProvisionScript.map(s=>` - ${s}`).join(`
|
|
136
136
|
`),a=n===""?" []":`
|
|
137
|
-
${n}`,
|
|
137
|
+
${n}`,i=[n,` - ${t.installCmd} --ignore-scripts`].filter(s=>s!=="").join(`
|
|
138
138
|
`);return`stages:
|
|
139
139
|
- deploy
|
|
140
140
|
|
|
@@ -204,7 +204,7 @@ deploy:
|
|
|
204
204
|
# only trusted when the project is linked and .lunora/ is not committed, so
|
|
205
205
|
# CI has no link: there the gate stays blocked, and a tightening needs a
|
|
206
206
|
# migration or --allow-schema-drift. A custom domain on a declared route works.
|
|
207
|
-
- ${
|
|
207
|
+
- ${E(e,["deploy","--migrate-url",'"$LUNORA_DEPLOY_URL"'])}
|
|
208
208
|
|
|
209
209
|
# Every merge request from this project gets an isolated preview: its own
|
|
210
210
|
# Worker, Durable Objects, D1, KV and R2, never production's. GitLab runs the
|
|
@@ -242,7 +242,7 @@ preview:
|
|
|
242
242
|
on_stop: preview_delete
|
|
243
243
|
auto_stop_in: 2 weeks
|
|
244
244
|
script:
|
|
245
|
-
- ${
|
|
245
|
+
- ${E(e,["preview","deploy",'"$CI_MERGE_REQUEST_IID"'])}
|
|
246
246
|
|
|
247
247
|
# Deletes the preview Worker and every resource recorded for it. It installs in the
|
|
248
248
|
# job that holds the preview token, so dependency scripts are switched off: deleting
|
|
@@ -250,7 +250,7 @@ preview:
|
|
|
250
250
|
preview_delete:
|
|
251
251
|
extends: .lunora_base
|
|
252
252
|
before_script:
|
|
253
|
-
${
|
|
253
|
+
${i}
|
|
254
254
|
rules:
|
|
255
255
|
- if: $CI_PIPELINE_SOURCE == "merge_request_event" && $CI_MERGE_REQUEST_SOURCE_PROJECT_ID == $CI_PROJECT_ID
|
|
256
256
|
when: manual
|
|
@@ -260,7 +260,7 @@ ${o}
|
|
|
260
260
|
name: preview/$CI_MERGE_REQUEST_IID
|
|
261
261
|
action: stop
|
|
262
262
|
script:
|
|
263
|
-
- ${
|
|
263
|
+
- ${E(e,["preview","delete",'"$CI_MERGE_REQUEST_IID"'])}
|
|
264
264
|
|
|
265
265
|
# A fork's merge request runs without this project's CI/CD variables, so it
|
|
266
266
|
# runs the deploy pipeline, bundle included, and publishes nothing.
|
|
@@ -269,41 +269,41 @@ check:
|
|
|
269
269
|
rules:
|
|
270
270
|
- if: $CI_PIPELINE_SOURCE == "merge_request_event" && $CI_MERGE_REQUEST_SOURCE_PROJECT_ID != $CI_PROJECT_ID
|
|
271
271
|
script:
|
|
272
|
-
- ${
|
|
273
|
-
`},
|
|
272
|
+
- ${E(e,["deploy","--dry-run"])}
|
|
273
|
+
`},Ve={github:{file:Q(".github","workflows","deploy.yml"),secretsHint:"repository secrets (Settings → Secrets and variables → Actions)"},gitlab:{file:".gitlab-ci.yml",secretsHint:"CI/CD variables, Masked and Protected, scoped to the production environment (Settings → CI/CD → Variables)"}},nr=(e,t)=>e==="github"?tr(t):rr(t),ar=e=>e==="github"||e==="gitlab",or=(e,t,r,n={})=>{const a=Q(e,Ve[t].file);return f(a)&&n.overwrite!==!0?{path:a,skipped:!0,written:!1}:(I(_t(a),{recursive:!0}),v(a,nr(t,r),"utf8"),{path:a,skipped:!1,written:!0})},ir=(e,t,r,n,a={})=>{const i=Ve[t];try{const s=or(e,t,r,a);if(s.skipped)n.info(`--ci ${t}: ${i.file} already exists — left unchanged (re-run with overwrite to replace).`);else{const o=Se(r),l=[o.command,...o.args].join(" "),{installCmd:c,lockfile:d}=Z[r];n.success(`--ci ${t}: wrote ${i.file}`),n.info(`--ci ${t}: set CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID as ${i.secretsHint} to enable deploys.`),n.info(`--ci ${t}: run \`${l}\` and commit ${d} before pushing — the pipeline runs \`${c}\`.`)}return s}catch(s){const o=s instanceof Error?s.message:String(s);return n.warn(`--ci ${t}: could not write ${i.file} (${o})`),{path:Q(e,i.file),skipped:!1,written:!1}}},sr={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"},lr=e=>{const t=ut(e);return{...t,adapter:sr[t.framework]}},N="lunora()",ie='import { lunora } from "@lunora/vite";',cr="@lunora/vite",dr="lunora",ur=e=>{for(const t of e.getStatements()){if(t.getKind()!==b.ExportAssignment)continue;const r=t.asKindOrThrow(b.ExportAssignment).getExpression();if(r.getKind()!==b.CallExpression)continue;const n=r.asKindOrThrow(b.CallExpression);if(n.getExpression().getText()!=="defineConfig")continue;const a=n.getArguments()[0];if(a?.getKind()===b.ObjectLiteralExpression)return a.asKindOrThrow(b.ObjectLiteralExpression)}},hr=e=>{for(const t of e.getStatements()){if(t.getKind()!==b.ExportAssignment)continue;const r=t.asKindOrThrow(b.ExportAssignment).getExpression();if(r.getKind()===b.ObjectLiteralExpression)return r.asKindOrThrow(b.ObjectLiteralExpression)}},pr=e=>e.getDescendantsOfKind(b.CallExpression).some(t=>t.getExpression().getText()===dr),mr=e=>e.getImportDeclarations().some(t=>t.getModuleSpecifierValue()===cr),fr=e=>new Ot({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}).createSourceFile("vite.config.ts",e,{overwrite:!0}),vr=(e,t)=>{const r=t.getImportDeclarations().at(-1)?.getEnd()??0;r===0?e.prepend(`${ie}
|
|
274
274
|
`):e.appendLeft(r,`
|
|
275
|
-
${ie}`)},
|
|
276
|
-
`);return}const n=r.getDescendantsOfKind(
|
|
275
|
+
${ie}`)},gr=(e,t)=>{const r=t.getProperty("plugins");if(r===void 0){const s=t.getProperties(),o=t.getStart()+1;if(s.length===0){e.appendLeft(o,` plugins: [${N}] `);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: [${N}],
|
|
276
|
+
`);return}const n=r.getDescendantsOfKind(b.ArrayLiteralExpression)[0];if(n===void 0)return"the Vite config's `plugins` is not an array literal — add `lunora()` to it by hand";const a=n.getElements();if(a.length===0){e.appendLeft(n.getStart()+1,N);return}const i=a[0];if(i===void 0)return"could not locate the first entry of the Vite config's `plugins` array";e.appendLeft(i.getStart(),`${N}, `)},Be=e=>{const t=fr(e);if(pr(t))return{changed:!1,code:e,reason:"lunora plugin already present"};const r=ur(t)??hr(t);if(r===void 0)return{changed:!1,code:e,reason:"could not locate a Vite config plugins array to patch"};const n=new Rt(e);mr(t)||vr(n,t);const a=gr(n,r);return a!==void 0?{changed:!1,code:e,reason:a}:{changed:!0,code:n.toString()}},wr=/enotfound|eai_again|econnrefused|etimedout|network|fetch failed|getaddrinfo/u,yr=/404|not found|could not find|no such/u,br=(e,t)=>{const r=e instanceof Error?e.message:String(e),n=r.toLowerCase(),a=`failed to download template "${t.templateType}" from ${t.remote}: ${r}`;return yr.test(n)?{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}`}:wr.test(n)?{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:a}:{hints:["If this is a network/offline issue, scaffold from a local root with `lunora init --from <dir>`."],message:a}},Fe=[{description:"No sign-in yet; add it later with `lunora add auth`",label:"None",value:"none"},{description:"Users and sessions in your own D1, via better-auth (@lunora/auth)",label:"Lunora auth",value:"lunora"},{description:"Clerk owns the session; the Worker verifies its session token",label:"Clerk",value:"clerk"},{description:"WorkOS AuthKit owns the session; the Worker verifies its access token",label:"WorkOS AuthKit",value:"workos"},{description:"Auth0 owns the session; the Worker verifies its access token",label:"Auth0",value:"auth0"}],se=Fe.map(e=>e.value),ee={auth0:{clientSnippet:["// @auth0/auth0-react: <Auth0Provider authorizationParams={{ audience: AUTH0_AUDIENCE }} useRefreshTokens>","// const { getAccessTokenSilently, isLoading, user } = useAuth0();","// In a useEffect over [client, getAccessTokenSilently, isLoading, user?.sub]:","if (isLoading) return;","if (!user) return client.setAuthToken(null);","const fetchToken = () => getAccessTokenSilently().catch((error) => {",' if (["login_required", "missing_refresh_token"].includes(error?.error)) return null; // signed out'," throw error;","});","return setAuthTokenProvider(client, fetchToken, { subject: user.sub });"].join(`
|
|
277
277
|
`),envVars:["AUTH0_DOMAIN","AUTH0_AUDIENCE"],identity:"auth0Identity",identityFile:"auth0",item:"auth-auth0-jwt"},clerk:{clientSnippet:["// @clerk/react: const { getToken, isLoaded, isSignedIn, userId } = useAuth();","// In a useEffect over [client, getToken, isLoaded, isSignedIn, userId]:","if (!isLoaded) return;","if (!isSignedIn) return client.setAuthToken(null);","return setAuthTokenProvider(client, getToken, { subject: userId });"].join(`
|
|
278
278
|
`),envVars:["CLERK_PUBLISHABLE_KEY","CLERK_AUTHORIZED_PARTIES"],identity:"clerkIdentity",identityFile:"clerk",item:"auth-clerk-jwt"},workos:{clientSnippet:["// @workos-inc/authkit-react: const { getAccessToken, isLoading, user } = useAuth();","// In a useEffect over [client, getAccessToken, isLoading, user?.id]:","if (isLoading) return;","if (!user) return client.setAuthToken(null);","const fetchToken = () => getAccessToken().catch((error) => {"," if (error instanceof LoginRequiredError) return null; // signed out"," throw error;","});","return setAuthTokenProvider(client, fetchToken, { subject: user.id });"].join(`
|
|
279
|
-
`),envVars:["WORKOS_CLIENT_ID"],identity:"workosIdentity",identityFile:"workos",item:"auth-workos-jwt"}},
|
|
280
|
-
`,t);return a===-1?e.length:a}if(r==="/"&&e[t+1]==="*"){const a=e.indexOf("*/",t+2);return a===-1?e.length:a+2}if(r!=='"'&&r!=="'"&&r!=="`")return t;let n=t+1;for(;n<e.length&&e[n]!==r;)n+=e[n]==="\\"?2:1;return n+1},
|
|
281
|
-
${
|
|
282
|
-
${
|
|
279
|
+
`),envVars:["WORKOS_CLIENT_ID"],identity:"workosIdentity",identityFile:"workos",item:"auth-workos-jwt"}},kr=e=>Object.hasOwn(ee,e),xr=(e,t)=>{const r=e.trim().toLowerCase();return se.includes(r)?r:(t(`init: unknown --auth "${e}" — expected ${se.join(" | ")}; skipping auth.`),"none")},Er=["lunora/app.ts","src/app.ts","lunora/server.ts","src/server.ts","src/server/index.ts","src/server/index.tsx","src/index.ts","src/worker.ts"],_r="virtual:lunora/worker",Cr=["lunora.config.ts","lunora.config.mts","lunora.config.js","lunora.config.mjs"],Sr=["src","app","pages","plugins"],Lr=/\.(?:[jt]sx?|svelte|vue)$/u,le=/\n([\t ]*)\.build(?:FrameworkWorker)?\(/uy,Ar=new Set(["(","[","{"]),Ir=new Set([")","]","}"]),Rr=(e,t)=>{const r=e[t];if(r==="/"&&e[t+1]==="/"){const a=e.indexOf(`
|
|
280
|
+
`,t);return a===-1?e.length:a}if(r==="/"&&e[t+1]==="*"){const a=e.indexOf("*/",t+2);return a===-1?e.length:a+2}if(r!=='"'&&r!=="'"&&r!=="`")return t;let n=t+1;for(;n<e.length&&e[n]!==r;)n+=e[n]==="\\"?2:1;return n+1},Or=(e,t)=>{let r=0,n=t;for(;n<e.length;){const a=Rr(e,n);if(a!==n){n=a;continue}const i=e[n]??"";le.lastIndex=n;const s=r===0?le.exec(e)??void 0:void 0;if(s!==void 0)return{at:n,indent:s[1]??" "};if(r===0&&i===";")return{at:n,indent:" "};r+=Ar.has(i)?1:0,r-=Ir.has(i)?1:0,n+=1}},Tr=(e,t,r)=>{const n=j(S(u(e,t)),u(e,"lunora","identity",r.identityFile));return`${n.startsWith(".")?n:`./${n}`}.js`},$r=/\bresolveIdentity\b/u,Mr=/^import[^"']*["'][^"'\n]*["'][^\n]*\n/u,Nr=(e,t,r,n)=>{const a=r.indexOf("defineApp<"),i=a===-1?void 0:Or(r,a);if(i===void 0)return;if(r.includes(`${n.identity}(env)`))return{outcome:"already-wired"};if($r.test(r))return{outcome:"has-resolver"};const{at:s,indent:o}=i,l=`
|
|
281
|
+
${o}// Verify the provider's token on every request and feed it into ctx.auth (memoized for 5 s).
|
|
282
|
+
${o}.extend((env) => ({ resolveIdentity: ${n.identity}(env) }))`,c=`import { ${n.identity} } from "${Tr(e,t,n)}";
|
|
283
283
|
`,d=r.lastIndexOf(`
|
|
284
|
-
import `,a),p=d===-1?void 0:Mr.exec(r.slice(d+1)),m=p==null?0:d+1+p[0].length;return{outcome:"wired",patched:r.slice(0,m)+c+r.slice(m,s)+l+r.slice(s)}},
|
|
284
|
+
import `,a),p=d===-1?void 0:Mr.exec(r.slice(d+1)),m=p==null?0:d+1+p[0].length;return{outcome:"wired",patched:r.slice(0,m)+c+r.slice(m,s)+l+r.slice(s)}},Pr=(e,t)=>{for(const r of Er){const n=u(e,r),a=f(n)?Nr(e,r,_(n,"utf8"),t):void 0;if(a?.outcome==="wired"&&v(n,a.patched),a!==void 0)return{file:r,outcome:a.outcome}}},Dr=e=>{const t=Jt(e);return t!==void 0&&Qt(t).parsed?.main===_r},Ur=(e,t)=>{if(!(!Dr(e)||Cr.some(r=>f(u(e,r)))))return v(u(e,"lunora.config.ts"),`import type { AppBuilder, LunoraConfig } from "./lunora/_generated/app";
|
|
285
285
|
import { ${t.identity} } from "./lunora/identity/${t.identityFile}";
|
|
286
286
|
|
|
287
287
|
export default {
|
|
288
288
|
// Verify the provider's token on every request and feed it into ctx.auth (memoized for 5 s).
|
|
289
289
|
app: (app: AppBuilder<object>): AppBuilder<object> => app.extend((env) => ({ resolveIdentity: ${t.identity}(env) })),
|
|
290
290
|
} satisfies LunoraConfig<object>;
|
|
291
|
-
`),"lunora.config.ts"},
|
|
291
|
+
`),"lunora.config.ts"},We=(e,t=0)=>t>3||!f(e)?[]:J(e,{withFileTypes:!0}).flatMap(r=>{const n=u(e,r.name);return r.isDirectory()?r.name==="node_modules"?[]:We(n,t+1):Lr.test(r.name)?[n]:[]}),jr=/(<script\b[^>]*>)([\s\S]*?)<\/script\b[^>]*>/giu,Vr=/\.(?:svelte|vue)$/u,Br=(e,t)=>e.properties.some(r=>(y.isPropertyAssignment(r)||y.isShorthandPropertyAssignment(r))&&r.name.getText(t)==="authTokenOnUpgrade"),ce=e=>{const t=y.createSourceFile("client.tsx",e,y.ScriptTarget.Latest,!0,y.ScriptKind.TSX),r=[],n=s=>{if(Br(s,t))return;const o=s.properties.at(-1);r.push(o===void 0?{at:s.getStart(t)+1,text:" authTokenOnUpgrade: true "}:{at:o.getEnd(),text:", authTokenOnUpgrade: true"})},a=s=>{if(y.isNewExpression(s)&&y.isIdentifier(s.expression)&&s.expression.text==="LunoraClient"){const[o]=s.arguments??[];o!==void 0&&y.isObjectLiteralExpression(o)&&n(o)}else if(y.isCallExpression(s)&&y.isIdentifier(s.expression)&&s.expression.text==="provideLunora"){const[o]=s.arguments;o===void 0?r.push({at:s.getEnd()-1,text:"{ authTokenOnUpgrade: true }"}):y.isObjectLiteralExpression(o)&&n(o)}y.forEachChild(s,a)};if(a(t),r.length===0)return;let i=e;for(const{at:s,text:o}of r.toSorted((l,c)=>c.at-l.at))i=`${i.slice(0,s)}${o}${i.slice(s)}`;return i},Fr=(e,t)=>{if(!Vr.test(e))return ce(t);let r="",n=0;for(const a of t.matchAll(jr)){const[,i="",s=""]=a,o=a.index+i.length,l=ce(s);l!==void 0&&(r+=`${t.slice(n,o)}${l}`,n=o+s.length)}if(n!==0)return`${r}${t.slice(n)}`},Wr=e=>Sr.flatMap(t=>We(u(e,t))).filter(t=>{const r=Fr(t,_(t,"utf8"));return r===void 0?!1:(v(t,r),!0)}),qr=(e,t)=>{const r=u(e,xe),n=u(e,ht),a=f(r)?_(r,"utf8"):"",i=f(n)?_(n,"utf8").split(`
|
|
292
292
|
`):[],s=t.envVars.filter(c=>!a.split(`
|
|
293
|
-
`).some(d=>d.startsWith(`${c}=`)));if(s.length===0)return!1;const
|
|
293
|
+
`).some(d=>d.startsWith(`${c}=`)));if(s.length===0)return!1;const o=s.map(c=>i.find(d=>d.startsWith(`${c}=`))??`${c}=`),l=a.length===0||a.endsWith(`
|
|
294
294
|
`)?"":`
|
|
295
|
-
`;return
|
|
296
|
-
${
|
|
295
|
+
`;return lt(r,`${l}# ${t.item}: the identity provider the Worker verifies tokens from.
|
|
296
|
+
${o.join(`
|
|
297
297
|
`)}
|
|
298
|
-
`),!0},
|
|
298
|
+
`),!0},Hr=(e,t,r)=>{const n=ee[t],a=()=>{const o=Ur(e,n);return o===void 0?void 0:{file:o,outcome:"wired"}},i=Pr(e,n)??a();i===void 0?r.warn(`auth: add \`.extend((env) => ({ resolveIdentity: ${n.identity}(env) }))\` to your app builder (lunora.config.ts \`app\` hook or the Worker entry) — ${n.identity} is in lunora/identity/${n.identityFile}.ts.`):i.outcome==="already-wired"?r.info(`auth: ${i.file} already wires ${n.identity}; left as is.`):i.outcome==="has-resolver"?r.warn(`auth: ${i.file} already sets resolveIdentity, so it was left as is. Compose the two: \`resolveIdentity: composeIdentityResolvers([${n.identity}(env), <your resolver>])\` — ${n.identity} is in lunora/identity/${n.identityFile}.ts.`):r.success(`auth: wired ${n.identity} as resolveIdentity in ${i.file}`),qr(e,n)&&r.success(`auth: listed ${n.envVars.join(", ")} in ${xe}`);const s=Wr(e);for(const o of s)r.success(`auth: turned on authTokenOnUpgrade in ${j(e,o)}`);s.length===0&&r.warn("auth: no client construction found to turn on authTokenOnUpgrade; set it on your client by hand"),r.info(`auth: hand the provider's token to Lunora once signed in (setAuthTokenProvider from lunorash/client or @lunora/client):
|
|
299
299
|
${n.clientSnippet}
|
|
300
|
-
Fill in the env vars the item wrote to .dev.vars.`)},
|
|
300
|
+
Fill in the env vars the item wrote to .dev.vars.`)},U=async(e,t,r)=>{if(k()){await Nt(w[e],t,r);return}if(process.stdout.write(`
|
|
301
301
|
`),r===void 0||r===""){ae(e,t);return}const n=r.split(`
|
|
302
|
-
`).map(a=>
|
|
302
|
+
`).map(a=>vt(a)).join(`
|
|
303
303
|
`);ae(e,`${t}
|
|
304
|
-
${n}`)},
|
|
305
|
-
${
|
|
306
|
-
${
|
|
304
|
+
${n}`)},Kr=async e=>{if(k()){await Mt();return}e.info(`
|
|
305
|
+
${pt}
|
|
306
|
+
${mt}: ${ft}`)},qe=[{description:"LLMs via Workers AI (summarize, generate, stream)",label:"AI",value:"ai"},{description:"Sign-up / sign-in with @lunora/auth (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"}],de=qe.map(e=>e.value),ue=qe.filter(e=>e.value!=="auth"),He=new Set(["auth","auth-ui"]),zr=e=>e==="email"?De:e,Gr=(e,t)=>{const r=[];for(const n of e.split(",").map(a=>a.trim()).filter(Boolean))de.includes(n)?r.includes(n)||r.push(n):t(`init: unknown --add feature "${n}" — expected ${de.join(" | ")}; skipping.`);return r},Ke=e=>e.resolveAuthUiItem===void 0?"auth-ui-react":e.resolveAuthUiItem(),Yr=async e=>{const t=await Kt(e.select),r=await Ue(e.text,e.projectName);return{label:"auth",names:[t],transformManifest:n=>je(n,r)}},Jr=async e=>{const t=await e.text(Wt,{placeholder:"you@yourdomain.com"}),r=qt(t,n=>{e.logger.warn(n)});return{label:"email",names:[De],transformManifest:r===void 0?void 0:n=>Ht(n,r)}},Qr=async(e,t)=>{const r=Ke(e);if(r===void 0){e.logger.error(`init: ${Pe}`);return}if(t)return{label:"auth-ui",names:[r]};const n=await Ue(e.text,e.projectName);return{label:"auth-ui",names:[r],transformManifest:a=>je(a,n)}},Xr=async e=>{const t=await Bt(e.text,e.projectName);return{label:"storage",names:["storage"],transformManifest:r=>Ft(r,t)}},Zr=(e,t)=>{const r=[];let n=!1;for(const a of t){if(a!=="auth-ui"){r.push({label:a,names:[zr(a)]});continue}const i=Ke(e);if(i===void 0){e.logger.error(`init: ${Pe}`),n=!0;continue}r.push({label:a,names:[i]})}return{plans:r,refused:n}},ze=e=>e!==void 0&&kr(e)?{externalAuth:e,label:e,names:[ee[e].item]}:void 0,en={auth:Yr,"auth-ui":async(e,t)=>Qr(e,t.includes("auth")),email:Jr,storage:Xr},tn=async e=>{const t=ze(e.auth),r=e.auth!==void 0&&e.auth!=="lunora",n=new Set(r?(e.preselected??[]).filter(l=>He.has(l)):[]),a=(e.preselected??[]).filter(l=>!n.has(l));for(const l of n)e.logger.warn(`--auth ${String(e.auth)} rules out Lunora auth; ignoring \`${l}\` from --add.`);e.auth==="lunora"&&!a.includes("auth")&&a.unshift("auth");const{plans:i,refused:s}=Zr(e,a);return t!==void 0&&i.unshift(t),await e.applyAll(i)&&!s&&n.size===0},he=async e=>{if(e.preselected!==void 0&&e.preselected.length>0||e.auth!==void 0&&!e.interactive)return tn(e);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=e.auth??await e.selectAuth("Which auth do you want?",Fe,{default:"none"})??"none",r=ze(t),n=t==="lunora"?ue:ue.filter(o=>!He.has(o.value)),a=await e.multiSelect("Which features do you want to add?",n,{defaults:[]}),i=t==="lunora"&&!a.includes("auth")?["auth",...a]:a;if(i.length===0&&r===void 0)return!0;const s=r===void 0?[]:[r];for(const o of i){const l=en[o],c=l?await l(e,i):{label:o,names:[o]};c!==void 0&&s.push(c)}return await e.applyAll(s),!0},rn=[{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"}],nn="Which linter/formatter do you use? We'll tell it to skip Lunora's generated files.",an=async e=>{const t=e.interactive?await e.multiSelect(nn,rn,{defaults:e.detected}):[...e.detected];if(t.length===0)return[];const r=e.apply(t);return Zt(r,e.logger),r},$="M 259.500 10.552 C 220.080 15.859, 182.424 32.566, 152.500 58.025 C 110.179 94.031, 85.380 137.183, 77.518 188.500 C 75.410 202.255, 74.569 225.677, 75.796 236.466 C 76.757 244.917, 76.683 245.692, 74.518 249.966 C 63.118 272.466, 53.141 303.876, 51.382 322.799 L 50.718 329.943 71.960 320.471 C 83.643 315.262, 93.326 311, 93.478 311 C 93.630 311, 96.547 316.063, 99.959 322.250 C 103.371 328.438, 107.249 334.850, 108.577 336.500 L 110.990 339.500 110.981 336 C 110.977 334.075, 111.499 324.991, 112.143 315.813 L 113.312 299.127 121.406 293.336 C 132.495 285.403, 149.593 271.554, 161 261.268 C 171.556 251.748, 189.116 235, 188.540 235 C 188.337 235, 183.069 238.648, 176.835 243.106 C 142.318 267.789, 68.537 314, 63.646 314 C 61.843 314, 72.791 281.179, 80.905 262.259 C 92.233 235.845, 107.473 212.389, 132.106 183.453 L 138.451 176 148.268 176 C 176.192 176, 197.512 187.154, 212.868 209.797 C 216.470 215.108, 217.035 216.595, 216.477 219.297 C 211.386 243.968, 202.359 274.496, 193.797 296 C 183.898 320.861, 167.147 352.101, 152.395 373.215 L 147.004 380.930 152.891 385.830 C 161.400 392.911, 165.563 396, 166.594 395.998 C 167.092 395.998, 168.772 391.641, 170.327 386.317 C 176.279 365.934, 188.422 338.749, 200.942 317.778 C 223.060 280.731, 256.432 244.369, 294.500 215.836 C 309.956 204.252, 313.937 201.603, 314.719 202.385 C 315.116 202.783, 315.449 213.096, 315.460 225.304 C 315.474 241.855, 315.021 250.405, 313.680 258.924 C 307.009 301.272, 291.175 336.677, 263.112 372 C 255.259 381.883, 227.182 410.673, 218.516 417.727 L 213.532 421.783 223.439 424.880 C 281.705 443.093, 349.165 436.018, 398.616 406.508 C 446.728 377.797, 483.322 331.466, 497.366 281.481 C 503.381 260.075, 504.480 250.741, 504.491 221 C 504.501 191.997, 503.598 184.047, 497.987 163.732 C 484.768 115.871, 452.505 72.708, 407.718 42.964 C 381.051 25.254, 352.818 14.828, 319.695 10.460 C 305.932 8.645, 273.298 8.695, 259.500 10.552",O=`/* The welcome page is a full-bleed starter — reset the browser's default
|
|
307
307
|
body margin/padding so it sits flush; everything else is scoped under
|
|
308
308
|
.lunora-welcome (collision-safe). */
|
|
309
309
|
body {
|
|
@@ -408,7 +408,7 @@ body {
|
|
|
408
408
|
.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); }
|
|
409
409
|
|
|
410
410
|
@media (prefers-reduced-motion: reduce) { .lunora-welcome * { transition: none !important; } }
|
|
411
|
-
`,
|
|
411
|
+
`,on=`import { useEffect, useState } from "react";
|
|
412
412
|
|
|
413
413
|
type Theme = "dark" | "light";
|
|
414
414
|
|
|
@@ -450,7 +450,7 @@ export default function App() {
|
|
|
450
450
|
<div className="lw-wrap">
|
|
451
451
|
<div className="brand">
|
|
452
452
|
<svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
|
|
453
|
-
<path d="${
|
|
453
|
+
<path d="${$}" fill="currentColor" fillRule="evenodd" />
|
|
454
454
|
</svg>
|
|
455
455
|
<span className="word">Lunora</span>
|
|
456
456
|
</div>
|
|
@@ -569,7 +569,7 @@ export default function App() {
|
|
|
569
569
|
</div>
|
|
570
570
|
);
|
|
571
571
|
}
|
|
572
|
-
`,
|
|
572
|
+
`,sn=`<script setup lang="ts">
|
|
573
573
|
import { onMounted, ref } from "vue";
|
|
574
574
|
|
|
575
575
|
// Default to "dark" for a stable first paint, then reconcile to the OS
|
|
@@ -609,7 +609,7 @@ const toggle = (): void => {
|
|
|
609
609
|
<div class="lw-wrap">
|
|
610
610
|
<div class="brand">
|
|
611
611
|
<svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
|
|
612
|
-
<path d="${
|
|
612
|
+
<path d="${$}" fill="currentColor" fill-rule="evenodd" />
|
|
613
613
|
</svg>
|
|
614
614
|
<span class="word">Lunora</span>
|
|
615
615
|
</div>
|
|
@@ -725,7 +725,7 @@ const toggle = (): void => {
|
|
|
725
725
|
</div>
|
|
726
726
|
</div>
|
|
727
727
|
</template>
|
|
728
|
-
`,
|
|
728
|
+
`,ln=`import { createSignal, onMount } from "solid-js";
|
|
729
729
|
|
|
730
730
|
export default function App() {
|
|
731
731
|
// Default to "dark" for a stable first paint, then reconcile to the OS
|
|
@@ -765,7 +765,7 @@ export default function App() {
|
|
|
765
765
|
<div class="lw-wrap">
|
|
766
766
|
<div class="brand">
|
|
767
767
|
<svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
|
|
768
|
-
<path d="${
|
|
768
|
+
<path d="${$}" fill="currentColor" fill-rule="evenodd" />
|
|
769
769
|
</svg>
|
|
770
770
|
<span class="word">Lunora</span>
|
|
771
771
|
</div>
|
|
@@ -884,7 +884,7 @@ export default function App() {
|
|
|
884
884
|
</div>
|
|
885
885
|
);
|
|
886
886
|
}
|
|
887
|
-
`,
|
|
887
|
+
`,cn=`<script lang="ts">
|
|
888
888
|
import { onMount } from "svelte";
|
|
889
889
|
|
|
890
890
|
// Default to "dark" for a stable first paint, then reconcile to the OS
|
|
@@ -927,7 +927,7 @@ export default function App() {
|
|
|
927
927
|
<div class="lw-wrap">
|
|
928
928
|
<div class="brand">
|
|
929
929
|
<svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
|
|
930
|
-
<path d="${
|
|
930
|
+
<path d="${$}" fill="currentColor" fill-rule="evenodd" />
|
|
931
931
|
</svg>
|
|
932
932
|
<span class="word">Lunora</span>
|
|
933
933
|
</div>
|
|
@@ -1042,7 +1042,7 @@ export default function App() {
|
|
|
1042
1042
|
<div class="lw-foot">Running on Lunora · Vite + Svelte</div>
|
|
1043
1043
|
</div>
|
|
1044
1044
|
</div>
|
|
1045
|
-
`,
|
|
1045
|
+
`,dn=`import "./style.css";
|
|
1046
1046
|
|
|
1047
1047
|
import { LunoraClient } from "lunorash/client";
|
|
1048
1048
|
|
|
@@ -1070,7 +1070,7 @@ const welcomeHtml = \`
|
|
|
1070
1070
|
<div class="lw-wrap">
|
|
1071
1071
|
<div class="brand">
|
|
1072
1072
|
<svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
|
|
1073
|
-
<path d="${
|
|
1073
|
+
<path d="${$}" fill="currentColor" fill-rule="evenodd" />
|
|
1074
1074
|
</svg>
|
|
1075
1075
|
<span class="word">Lunora</span>
|
|
1076
1076
|
</div>
|
|
@@ -1209,7 +1209,7 @@ const count = document.querySelector<HTMLSpanElement>("#lw-count")!;
|
|
|
1209
1209
|
client.subscribe(api.messages.list, { channelId: "channel:demo" }, (result) => {
|
|
1210
1210
|
count.textContent = String(result.messages.length);
|
|
1211
1211
|
});
|
|
1212
|
-
`,
|
|
1212
|
+
`,B="const url = (import.meta.env.VITE_LUNORA_URL as string | undefined) ?? globalThis.location.origin;",un=`import "./index.css";
|
|
1213
1213
|
|
|
1214
1214
|
import { LunoraProvider } from "@lunora/react";
|
|
1215
1215
|
import { LunoraClient } from "lunorash/client";
|
|
@@ -1221,7 +1221,7 @@ import App from "./App.tsx";
|
|
|
1221
1221
|
// \`@lunora/vite\` runs the Worker on the same origin as Vite, so default to
|
|
1222
1222
|
// \`location.origin\`. Point \`VITE_LUNORA_URL\` at a deployed Worker to develop
|
|
1223
1223
|
// the client against production data.
|
|
1224
|
-
${
|
|
1224
|
+
${B}
|
|
1225
1225
|
const client = new LunoraClient({ url });
|
|
1226
1226
|
|
|
1227
1227
|
const root = document.getElementById("root");
|
|
@@ -1237,7 +1237,7 @@ createRoot(root).render(
|
|
|
1237
1237
|
</LunoraProvider>
|
|
1238
1238
|
</StrictMode>,
|
|
1239
1239
|
);
|
|
1240
|
-
`,
|
|
1240
|
+
`,hn=`import "./style.css";
|
|
1241
1241
|
|
|
1242
1242
|
import { createLunora } from "@lunora/vue";
|
|
1243
1243
|
import { LunoraClient } from "lunorash/client";
|
|
@@ -1246,9 +1246,9 @@ import { createApp } from "vue";
|
|
|
1246
1246
|
import App from "./App.vue";
|
|
1247
1247
|
|
|
1248
1248
|
// Provide one LunoraClient at the app root via the Vue plugin form.
|
|
1249
|
-
${
|
|
1249
|
+
${B}
|
|
1250
1250
|
createApp(App).use(createLunora(new LunoraClient({ url }))).mount("#app");
|
|
1251
|
-
`,
|
|
1251
|
+
`,pn=`import "./index.css";
|
|
1252
1252
|
|
|
1253
1253
|
import { LunoraProvider } from "@lunora/solid";
|
|
1254
1254
|
import { LunoraClient } from "lunorash/client";
|
|
@@ -1256,7 +1256,7 @@ import { render } from "solid-js/web";
|
|
|
1256
1256
|
|
|
1257
1257
|
import App from "./App";
|
|
1258
1258
|
|
|
1259
|
-
${
|
|
1259
|
+
${B}
|
|
1260
1260
|
const client = new LunoraClient({ url });
|
|
1261
1261
|
const root = document.getElementById("root");
|
|
1262
1262
|
|
|
@@ -1268,18 +1268,18 @@ render(
|
|
|
1268
1268
|
),
|
|
1269
1269
|
root!,
|
|
1270
1270
|
);
|
|
1271
|
-
`,
|
|
1271
|
+
`,mn=`<script lang="ts">
|
|
1272
1272
|
import { setLunoraClient } from "@lunora/svelte";
|
|
1273
1273
|
import { LunoraClient } from "lunorash/client";
|
|
1274
1274
|
|
|
1275
1275
|
import App from "./App.svelte";
|
|
1276
1276
|
|
|
1277
|
-
${
|
|
1277
|
+
${B}
|
|
1278
1278
|
setLunoraClient(new LunoraClient({ url }));
|
|
1279
1279
|
<\/script>
|
|
1280
1280
|
|
|
1281
1281
|
<App />
|
|
1282
|
-
`,
|
|
1282
|
+
`,fn=`import "./app.css";
|
|
1283
1283
|
|
|
1284
1284
|
import { mount } from "svelte";
|
|
1285
1285
|
|
|
@@ -1289,7 +1289,7 @@ import Root from "./Root.svelte";
|
|
|
1289
1289
|
const app = mount(Root, { target: document.getElementById("app")! });
|
|
1290
1290
|
|
|
1291
1291
|
export default app;
|
|
1292
|
-
`,
|
|
1292
|
+
`,F={react:{adapter:"@lunora/react",createViteTemplate:"react-ts",files:[{contents:un,path:"src/main.tsx"},{contents:on,path:"src/App.tsx"},{contents:O,path:"src/index.css"}],label:"React"},solid:{adapter:"@lunora/solid",createViteTemplate:"solid-ts",files:[{contents:pn,path:"src/index.tsx"},{contents:ln,path:"src/App.tsx"},{contents:O,path:"src/index.css"}],label:"Solid"},svelte:{adapter:"@lunora/svelte",createViteTemplate:"svelte-ts",files:[{contents:mn,path:"src/Root.svelte"},{contents:fn,path:"src/main.ts"},{contents:cn,path:"src/App.svelte"},{contents:O,path:"src/app.css"}],label:"Svelte"},vanilla:{adapter:"lunorash/client",createViteTemplate:"vanilla-ts",files:[{contents:dn,path:"src/main.ts"},{contents:O,path:"src/style.css"}],label:"Vanilla"},vue:{adapter:"@lunora/vue",createViteTemplate:"vue-ts",files:[{contents:hn,path:"src/main.ts"},{contents:sn,path:"src/App.vue"},{contents:O,path:"src/style.css"}],label:"Vue"}},W=e=>Object.hasOwn(F,e),vn=`/**
|
|
1293
1293
|
* Rate-limit schema extension + plugin.
|
|
1294
1294
|
*
|
|
1295
1295
|
* Defines the \`ratelimit_buckets\` table used by \`createDbStore\` for durable,
|
|
@@ -1365,7 +1365,7 @@ export const ratelimit = definePlugin("ratelimit", {
|
|
|
1365
1365
|
}),
|
|
1366
1366
|
middleware,
|
|
1367
1367
|
});
|
|
1368
|
-
`,
|
|
1368
|
+
`,gn=`import { ratelimit } from "./ratelimit/schema.js";
|
|
1369
1369
|
import { defineSchema, defineTable, v } from "lunorash/server";
|
|
1370
1370
|
|
|
1371
1371
|
export default defineSchema({
|
|
@@ -1376,7 +1376,7 @@ export default defineSchema({
|
|
|
1376
1376
|
.shardBy("channelId")
|
|
1377
1377
|
.index("by_channel", ["channelId"]),
|
|
1378
1378
|
}).extend(ratelimit.extension);
|
|
1379
|
-
`,
|
|
1379
|
+
`,wn=`import { rateLimit } from "lunorash/ratelimit";
|
|
1380
1380
|
|
|
1381
1381
|
import { makeRateLimiter } from "./ratelimit/schema.js";
|
|
1382
1382
|
import type { MutationCtx } from "#lunora/_generated/server.js";
|
|
@@ -1425,7 +1425,7 @@ export const send = mutation
|
|
|
1425
1425
|
|
|
1426
1426
|
return { channelId: args.channelId, id, text: args.text };
|
|
1427
1427
|
});
|
|
1428
|
-
`,
|
|
1428
|
+
`,yn=`import type { ShardNamespaceLike } from "lunorash/runtime";
|
|
1429
1429
|
|
|
1430
1430
|
import { defineApp } from "../lunora/_generated/app.js";
|
|
1431
1431
|
|
|
@@ -1443,7 +1443,7 @@ export const ShardDO = app.ShardDO;
|
|
|
1443
1443
|
// Records revoked named admin tokens where a restore of the shard cannot rewind them.
|
|
1444
1444
|
export { AdminRevocationDO } from "../lunora/_generated/adminRevocations.js";
|
|
1445
1445
|
export default app;
|
|
1446
|
-
`,
|
|
1446
|
+
`,bn=`{ ${Object.entries(Xt).map(([e,t])=>`${JSON.stringify(e)}: ${JSON.stringify(t)}`).join(", ")} }`,kn=`{
|
|
1447
1447
|
"$schema": "node_modules/wrangler/config-schema.json",
|
|
1448
1448
|
"name": "__NAME__",
|
|
1449
1449
|
"main": "src/server.ts",
|
|
@@ -1459,25 +1459,25 @@ export default app;
|
|
|
1459
1459
|
{ "tag": "v1", "new_sqlite_classes": ["ShardDO"] },
|
|
1460
1460
|
{ "tag": "v2", "new_sqlite_classes": ["AdminRevocationDO"] },
|
|
1461
1461
|
],
|
|
1462
|
-
"observability": ${
|
|
1462
|
+
"observability": ${bn},
|
|
1463
1463
|
}
|
|
1464
|
-
`,
|
|
1464
|
+
`,pe=[".wrangler",".env",".env.*","!.env.example",".dev.vars",".dev.vars.*","!.dev.vars.example",".lunora/",".lunora-cache","lunora/_generated"],xn=`# Lunora endpoint for the browser client.
|
|
1465
1465
|
# Vite statically replaces \`import.meta.env.VITE_LUNORA_URL\` at \`vite dev\` / build.
|
|
1466
1466
|
# Leave it unset to use the page origin; set it to point at a deployed Worker:
|
|
1467
1467
|
#
|
|
1468
1468
|
# VITE_LUNORA_URL=https://my-app.example.workers.dev
|
|
1469
|
-
`,
|
|
1469
|
+
`,En={"@cloudflare/workers-types":ne["@cloudflare/workers-types"],wrangler:ne.wrangler},L=(e,t,r,n)=>{const a=u(e,t);I(S(a),{recursive:!0}),v(a,r,"utf8"),n.push(a)},_n=/\r?\n/,Cn=e=>{const t=u(e,".gitignore"),r=f(t)?_(t,"utf8"):"",n=new Set(r.split(_n)),a=pe.filter(o=>!n.has(o));if(a.length===0)return;const i=a.some(o=>!o.startsWith("!"))?[...a.filter(o=>!o.startsWith("!")),...pe.filter(o=>o.startsWith("!"))]:a,s=r.length>0&&!r.endsWith(`
|
|
1470
1470
|
`)?`
|
|
1471
1471
|
`:"";v(t,`${r}${s}
|
|
1472
1472
|
# Lunora
|
|
1473
|
-
${
|
|
1473
|
+
${i.join(`
|
|
1474
1474
|
`)}
|
|
1475
|
-
`,"utf8")},
|
|
1476
|
-
`,"utf8")},
|
|
1475
|
+
`,"utf8")},q=e=>e==="lunorash"||e.startsWith("@lunora/"),Sn=(e,t,r,n)=>q(e)?n.get(e)??r:t,A=(e,t,r)=>({...e,[t]:r}),me=(e,t,r)=>Object.fromEntries(Object.entries(e).map(([n,a])=>[n,Sn(n,a,t,r)])),Ln=async(e,t,r,n)=>{const a=u(e,"package.json"),i=bt(a);let s=A(i.dependencies??{},"lunorash",n);s=A(s,"@lunora/ratelimit",n),r.adapter.startsWith("@lunora/")&&(s=A(s,r.adapter,n));for(const[d,p]of Object.entries(r.extraDependencies??{}))s=A(s,d,p);let o=A(i.devDependencies??{},"@lunora/vite",n);o=A(o,"@lunora/studio",n);for(const[d,p]of Object.entries(En))o=A(o,d,p);const l=[...Object.keys(s),...Object.keys(o)].filter(d=>q(d)),c=await Le(l,n);i.name=t,i.imports={...i.imports,"#lunora/*":"./lunora/*"},i.dependencies=me(s,n,c),i.devDependencies=me(o,n,c),i.scripts={...i.scripts,codegen:"lunora codegen",deploy:"lunora deploy"},v(a,`${JSON.stringify(i,void 0,4)}
|
|
1476
|
+
`,"utf8")},An=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],Ge=e=>An.map(t=>u(e,t)).find(t=>f(t)),In=(e,t)=>{const r=Ge(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 n=Be(_(r,"utf8"));n.changed&&v(r,n.code,"utf8")},Rn=async e=>{const{adapter:t,distTag:r,logger:n,name:a,target:i}=e,s=[];L(i,u("lunora","ratelimit","schema.ts"),vn,s),L(i,u("lunora","schema.ts"),gn,s),L(i,u("lunora","messages.ts"),wn,s),L(i,u("src","server.ts"),yn,s),L(i,"wrangler.jsonc",kn.replaceAll("__NAME__",a),s),L(i,".env.example",xn,s);for(const o of t.files)L(i,o.path,o.contents,s);return In(i,n),await Ln(i,a,t,r),Cn(i),s},On=["lunar","silver","silent","waning","waxing","crescent","cosmic","stellar","orbital","gibbous","twilight","midnight","shimmering","drifting","weightless"],Tn=["moon","tide","crater","comet","eclipse","halo","orbit","nebula","voyager","lander","rover","beacon","harbor","meadow","fox"],fe=e=>e[Math.floor(Math.random()*e.length)],$n=()=>`${fe(On)}-${fe(Tn)}`,Mn=async()=>er.lookup("github.com").then(()=>!0,()=>!1),Nn=/^(?:gh|github):([^/]+)\/([^#/]+)(?:\/[^#]*)?(?:#(.+))?$/,Ye=e=>{const t=Nn.exec(e);if(t===null)return;const[,r,n,a]=t;if(!(r===void 0||n===void 0))return{owner:r,ref:a??"HEAD",repo:n}},Pn=async e=>{const t=Ye(e);if(t===void 0)return;const r=`https://codeload.github.com/${t.owner}/${t.repo}/tar.gz/${t.ref}`;try{const n=await fetch(r,{method:"HEAD"});return n.status===404?!1:n.ok?!0:void 0}catch{return}},Je=async e=>e.isLocal||!(e.source===void 0||Ye(e.source)!==void 0)?!0:await Mn()?e.source!==void 0&&await Pn(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),C={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?"},Dn=new Set([".gitignore",".html",".js",".json",".jsonc",".md",".mjs",".ts",".tsx"]),Un=`import { defineConfig } from "vite";
|
|
1477
1477
|
import { lunora } from "@lunora/vite";
|
|
1478
1478
|
|
|
1479
1479
|
export default defineConfig({ plugins: [lunora()] });
|
|
1480
|
-
|
|
1480
|
+
`,jn=`import { defineSchema, defineTable, v } from "@lunora/server";
|
|
1481
1481
|
|
|
1482
1482
|
export default defineSchema({
|
|
1483
1483
|
messages: defineTable({
|
|
@@ -1487,7 +1487,7 @@ export default defineSchema({
|
|
|
1487
1487
|
.shardBy("channelId")
|
|
1488
1488
|
.index("by_channel", ["channelId"]),
|
|
1489
1489
|
});
|
|
1490
|
-
`,
|
|
1490
|
+
`,Vn=`import { mutation, query, v } from "./_generated/server";
|
|
1491
1491
|
|
|
1492
1492
|
export const list = query
|
|
1493
1493
|
.input({ channelId: v.string(), limit: v.optional(v.number()) })
|
|
@@ -1500,8 +1500,8 @@ export const send = mutation
|
|
|
1500
1500
|
.mutation(async ({ args }) => {
|
|
1501
1501
|
return { channelId: args.channelId, text: args.text };
|
|
1502
1502
|
});
|
|
1503
|
-
`,
|
|
1504
|
-
`),
|
|
1505
|
-
`),e.success(`scaffolded ${String(t.length)} files into ${r}`)},
|
|
1506
|
-
`))},
|
|
1507
|
-
`),t.info(m?.commit?`template: ${m.source} @ ${m.commit} (${String(k.length)} files)`:`template: ${m?.source??p} (${String(k.length)} files)`),te(t,h,s),{code:0,files:h,target:s}}catch(d){if(d instanceof X)throw d;const{hints:p,message:m}=yr(d,{ref:Le(a),remote:G(i,o,a),templateType:i});t.error(m);for(const h of p)t.warn(h);return{code:1,files:[],target:s}}finally{N(l,{force:!0,recursive:!0})}},aa=e=>{for(const t of["_gitignore","_npmrc","_gitattributes"]){const r=u(e,t);f(r)&&ct(r,u(e,`.${t.slice(1)}`))}},oa=async e=>{const{framework:t,logger:r,markComplete:n,name:a,overlayBaseFrom:o,target:s}=e,i=B[t],l=ye(u(be(),"lunora-vite-base-"));try{let c;if(o!==void 0&&(c=u(o,`template-${i.createViteTemplate}`),!f(c)))return r.error(`create-vite base not found on disk: ${c}`),{code:g.NOT_FOUND,files:[],target:s};const d=async()=>{if(c!==void 0){ve(c,s);return}const m=u(l,"base"),h=await Ot(fe,"main",r),k=`github:${fe}/packages/create-vite/template-${i.createViteTemplate}#${h}`;await _e(k,{cwd:l,dir:m,force:!0,install:!1,silent:!0}),aa(m),ve(m,s)};let p=[];return await $e([{label:`create-vite (${i.label}) base ready`,run:d},{label:`Lunora overlay applied (${i.label})`,run:async()=>{p=await Cn({adapter:i,distTag:Se(),logger:r,name:a,target:s})}}],{end:et,start:"Project initializing…"}),n(),te(r,p,s),{code:0,files:[...q(s)],target:s}}catch(c){if(c instanceof X)throw c;const d=c instanceof Error?c.message:String(c);return r.error(`failed to scaffold the ${i.label} base: ${d}`),{code:1,files:[],target:s}}finally{N(l,{force:!0,recursive:!0})}},Y=(e,t,r,n,a)=>(a.error(`init --in-place: could not ${e} ${t}: ${r instanceof Error?r.message:String(r)}`),{code:1,files:[],target:n}),ia=(e,t)=>{const r=u(e,"vite.config.ts");try{v(r,Mn,"utf8")}catch(n){return Y("write",r,n,e,t)}return t.success(`created ${r} with lunora() plugin`),{code:0,files:[r],target:e}},sa=(e,t,r)=>{let n;try{n=E(e,"utf8")}catch(o){return Y("read",e,o,t,r)}const a=Ve(n);if(!a.changed)return r.info(`${e}: ${a.reason??"no changes needed"}`),{code:0,files:[],target:t};try{v(e,a.code,"utf8")}catch(o){return Y("write",e,o,t,r)}return r.success(`patched ${e} — added lunora() plugin`),{code:0,files:[e],target:t}},la=(e,t)=>{const r=u(e,"lunora"),n=u(r,"schema.ts");if(f(n))return t.info(`lunora/ already present — left ${n} untouched`),[];const a=[];try{L(r,{recursive:!0}),v(n,$n,"utf8"),a.push(n);const o=u(r,"messages.ts");f(o)||(v(o,Nn,"utf8"),a.push(o)),t.success(`scaffolded lunora/ (${String(a.length)} file(s))`)}catch(o){const s=o instanceof Error?o.message:String(o);t.error(`init --here: could not scaffold lunora/: ${s}`)}return a},rt=e=>e==="sveltekit"||e==="nuxt"||e==="astro",ca=(e,t,r)=>{const{adapter:n,class:a,framework:o}=e;r.info(""),r.info(`detected framework: ${o} (class ${a})`),r.info("next steps:");const s=[n,"@lunora/client","@lunora/runtime","@lunora/server"];rt(o)||s.push("@lunora/vite"),r.info(` 1. install the adapter: ${Yn(t,s)}`),r.info(" 2. run codegen: lunora codegen"),a==="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 ${n} 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")):a==="B"?(r.info(" 3. inject Lunora: mount Lunora realtime under /_lunora/* in your server hook"),r.info(` (${o} owns its Cloudflare adapter — Lunora composes into its server entry)`),r.info(` 4. add the provider: mount the ${n} 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("")},da=(e,t,r)=>{if(rt(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 n=ze(e);return n===void 0?ia(e,r):sa(n,e,r)},ua=(e,t)=>{const r=sr(e),n=da(e,r.framework,t);if(n.code!==0)return n;const a=la(e,t);return ca(r,j(e),t),{code:0,files:[...n.files,...a],target:e}},ha=e=>e.yes!==!0&&(e.prompt!==void 0||(e.interactive??b())),ge=async(e,t,r)=>{r.dryRun!==!0&&await Zr({apply:n=>gt(e,n),detected:vt(e),interactive:t,logger:r.logger,multiSelect:r.lintPrompt??((n,a,o)=>Oe(n,a,{...o,badge:w.add}))})},pa=async(e,t)=>{const r=ha(e),n=e.add===void 0?[]:Wr(e.add,i=>{e.logger.warn(i)}),a=async i=>{if(i.length===0)return!0;if(e.dryRun===!0)return I(e.logger,`add ${i.map(h=>h.externalAuth===void 0?h.label:`${h.label} (and wire resolveIdentity)`).join(", ")}`),!0;const l=[],c=b()?{error:h=>{l.push({level:"error",message:h})},info:()=>{},success:()=>{},warn:h=>{l.push({level:"warn",message:h})}}:e.logger,d=i.map(h=>({running:`adding ${h.label}…`,task:()=>Gt({allowUnsafeSource:e.allowUnsafeSource,cwd:t,from:e.registryFrom,logger:c,names:[...h.names],ref:e.ref,source:e.registrySource,transformManifest:h.transformManifest,yes:!0})})),p=`added ${i.map(h=>h.label).join(", ")}`,m=await jt(w.add,d,p);for(const{level:h,message:k}of l)e.logger[h](k);for(const[h,k]of i.entries())k.externalAuth!==void 0&&m[h]?.code===0&&Vr(t,k.externalAuth,e.logger);return m.every(h=>h.code===0)},o=e.auth===void 0?void 0:kr(e.auth,i=>{e.logger.warn(i)}),s={applyAll:a,auth:o,interactive:r,logger:e.logger,multiSelect:e.prompt?.multiSelect??((i,l,c)=>Oe(i,l,{...c,badge:w.add})),preselected:n.length>0?n:void 0,projectName:O(t),resolveAuthUiItem:()=>{const i=xe(t);if(!Kt(i))return zt(i)??"auth-ui-react"},select:e.prompt?.select??((i,l,c)=>P(i,l,{...c,badge:w.add})),selectAuth:e.prompt===void 0?(i,l,c)=>P(i,l,{...c,badge:w.add}):e.prompt.selectAuth??(()=>Promise.resolve("none")),text:e.prompt?.text??((i,l)=>Re(i,{...l,badge:w.add}))};if(n.length>0||o!==void 0&&!r){const i=await ue(s);return await ge(t,r,e),i}return b()&&await Pt(_.extras),await ue(s),await ge(t,r,e),!0},K="react",nt=[{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:"React SPA on Rsbuild — the Worker runs under wrangler dev behind the dev server",label:"React · Rsbuild",value:"rspack-react"},{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 (React) on Rsbuild — SSR composed into the Lunora worker",label:"TanStack Start · React · Rsbuild",value:"tanstack-start-react-rspack"},{description:"SaaS kit — multi-tenant app on TanStack Start: organizations, projects, activity, admin",label:"SaaS kit",value:"saas"},{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:"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"}],at=Object.keys(B).join("|"),ot=nt.filter(e=>!F(e.value)).map(e=>e.value),it=ot.join("|"),ma=e=>F(e)?{framework:e,kind:"overlay"}:{kind:"template",templateType:e},fa=async e=>e.vite!==void 0?{framework:e.vite,kind:"overlay"}:e.templateType!==void 0?{kind:"template",templateType:e.templateType}:!b()||e.yes===!0?{framework:K,kind:"overlay"}:ma(await P(_.framework,nt,{badge:w.tmpl,default:K})??K),va=e=>{if(b()||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 <${at}>\` for an SPA, or \`-t <${it}>\` 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.`},ga=async(e,t,r,n,a)=>F(t)?await Ye({isLocal:e.overlayBaseFrom!==void 0,logger:e.logger})?(L(n,{recursive:!0}),oa({framework:t,logger:e.logger,markComplete:a,name:r,overlayBaseFrom:e.overlayBaseFrom,target:n})):{code:1,files:[],target:n}:(e.logger.error(`init: unknown framework "${t}". Supported overlays: ${Object.keys(B).join(", ")}.`),{code:g.USAGE,files:[],target:n}),wa=async(e,t,r,n,a)=>e.from!==void 0?await ra(e.from,t,n,r,e.logger,a):e.source!==void 0&&e.source.length>0&&!e.allowUnsafeSource&&!Gn(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:g.USAGE,files:[],target:n}):await Ye({isLocal:!1,logger:e.logger,source:G(t,e.source,e.ref)})?na({logger:e.logger,markComplete:a,name:r,ref:e.ref,source:e.source,target:n,templateType:t}):{code:1,files:[],target:n},ya=(e,t)=>{if(re(t))return;let r;try{r=j(e)}catch{return}r==="pnpm"&&Qe(e)},ba=async(e,t,r)=>{await Nt("realtime backend on Cloudflare Workers + Durable Objects");const n=va(e);if(n!==void 0)return e.logger.error(n),{code:g.USAGE,files:[],target:""};const a=Ln(),o=e.name??await Re(_.name,{badge:w.dir,default:a,placeholder:a}),s=await fa(e),i=o.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:g.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:g.USAGE,files:[],target:""};if(!Un.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 \`${Bn(i)}\`.`),{code:g.USAGE,files:[],target:""};const l=Ee(t,i),c=we(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:g.CONFLICT,files:[],target:l};const d=c!==void 0;if(d&&J(l).length>0)return e.logger.error(`target directory not empty: ${l}`),{code:g.CONFLICT,files:[],target:l};if(e.dryRun===!0){const m=s.kind==="overlay"?`the ${s.framework} create-vite overlay`:`the ${s.templateType} template`;return I(e.logger,`scaffold ${m} into ${l}`),{code:0,files:[],target:l}}r.record(l,d);const p=s.kind==="overlay"?await ga(e,s.framework,i,l,r.complete):await wa(e,s.templateType,i,l,r.complete);return p.code===0&&ya(l,t),p},z=(e,t)=>{const{target:r,targetPreExisted:n}=e;if(!(r===void 0||!f(r))){if(n===!0)for(const a of J(r))N(u(r,a),{force:!0,recursive:!0});else N(r,{force:!0,recursive:!0});t.info(`removed the partially-created project at ${r}`)}},ka=async(e,t,r)=>e.inPlace!==!0?ba(e,t,r):e.dryRun===!0?(I(e.logger,`configure Lunora into ${t}`),{code:0,files:[],target:t}):ua(t,e.logger),xa=async(e,t,r)=>{const n=await pa(e,t.target),a=e.inPlace===!0?void 0:await ta(e,t.target);if(e.inPlace!==!0){await Xn(e,t.target);const o=a??j(t.target);await Zn(O(t.target),a,o,re(r)),await Br(e.logger)}return n},Ea=(e,t,r)=>{if(t.code!==0||e.ci===void 0)return;if(e.dryRun===!0){I(e.logger,`scaffold a ${e.ci} CI deploy pipeline`);return}const n=e.inPlace===!0?r:t.target;try{const a=j(n);or(n,e.ci,a,e.logger)}catch{e.logger.warn(`--ci ${e.ci}: could not detect a package manager for this project — skipped the CI pipeline.`)}},_a=async e=>{const t=e.cwd??process.cwd(),r={};let n;try{n=await ka(e,t,{complete:()=>{r.target=void 0},record:(a,o)=>{r.target=a,r.targetPreExisted=o}}),n.code===0&&n.target!==""?(r.target=void 0,await xa(e,n,t)||(n={...n,code:1})):n.code!==0&&z(r,e.logger)}catch(a){if(a instanceof X)return z(r,e.logger),process.stdout.write("\n ✖ Setup cancelled — run `lunora init` again whenever you're ready. 🌙\n"),{code:130,files:[],target:""};throw z(r,e.logger),a}return Ea(e,n,t),n},Ca=e=>typeof e=="string"&&ot.includes(e),Aa=(e,t)=>{if(e!==void 0){if(nr(e))return e;t.warn(`init: unknown --ci "${e}" — expected github | gitlab; skipping CI scaffold.`)}},Sa=e=>e===void 0?{}:Ca(e)?{templateType:e}:F(e)?{vite:e}:{error:`init: unknown --template "${e}" — expected a bespoke template (${it}) or an overlay framework (${at}).`},Qa=Lt(({argument:e,cwd:t,logger:r,options:n})=>{const a=Sa(n.template);return"error"in a?(r.error(a.error),{code:g.USAGE}):_a({add:n.add,auth:n.auth,allowUnsafeSource:n.allowUnsafeSource===!0,cwd:t,ci:Aa(n.ci,r),dryRun:n.dryRun===!0,from:n.from,inPlace:n.here===!0,interactive:n.interactive===!0?!0:void 0,logger:r,name:e[0],ref:n.ref,source:n.source,templateType:a.templateType,vite:n.vite??a.vite,yes:n.yes===!0})});export{nt as FRAMEWORK_CHOICES,Qa as execute,Ca as isTemplate,Sa as resolveTemplateFlag,G as resolveTemplateSource,_a as runInitCommand};
|
|
1503
|
+
`,Bn="gh:anolilab/lunora/templates",Fn=e=>{const t=e.lastIndexOf(".");return t===-1?!1:Dn.has(e.slice(t))},Wn=/^[a-z0-9_][a-z0-9\-_]*$/u,qn=/([a-z0-9])([A-Z])/gu,Hn=/[^a-z0-9_]/gu,Kn=e=>{const t=e.replaceAll(qn,"$1-$2").toLowerCase().replaceAll(Hn,"-").split("-").filter(r=>r.length>0);return t.length>0?t.join("-"):"my-app"},zn=(e,t)=>e.replaceAll("{{name}}",t),Gn=async(e,t)=>{const r=new Set;for(const n of e)if(T(n)==="package.json")for(const a of Object.keys(Ee(S(n))))q(a)&&r.add(a);return Le(r,t)},Yn=(e,t,r)=>{let n;try{n=JSON.parse(e)}catch{return e}let a=e;for(const i of["dependencies","devDependencies"])for(const s of Object.keys(n[i]??{})){if(!q(s))continue;const o=r.get(s)??t,l=xt(a,[i,s],o,{formattingOptions:{insertSpaces:!0,tabSize:4}});a=Et(a,l)}return a},Jn=["@parcel/watcher","esbuild","lmdb","msgpackr-extract","rs-module-lexer","sharp","unrs-resolver","vue-demi","workerd"],Qn=["cpu-features","protobufjs","ssh2"],Qe="pnpm-workspace.yaml",Xn=()=>["# 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:",...Jn.map(e=>` '${e}': true`),...Qn.map(e=>` '${e}': false`),""].join(`
|
|
1504
|
+
`),Xe=e=>{const t=u(e,Qe);f(t)||v(t,Xn(),"utf8")},H=e=>{const t=[];for(const r of kt(e,{includeDirs:!1,includeFiles:!0}))ye(r.path).isSymbolicLink()||t.push(r.path);return t},ve="vitejs/vite",ge=(e,t)=>{for(const r of H(e)){const n=u(t,j(e,r));I(S(n),{recursive:!0}),ct(r,n)}},Ze=async(e,t,r)=>{const n=H(e),a=[],i=Ae(),s=await Gn(n,i);for(const o of n){const l=j(e,o),c=u(t,l);I(S(c),{recursive:!0});const d=_(o);let p=Fn(o)?zn(d.toString("utf8"),r):void 0;p!==void 0&&T(o)==="package.json"&&(p=Yn(p,i,s)),p===void 0?v(c,d):v(c,p,"utf8"),a.push(c)}return a},G=(e,t,r)=>t!==void 0&&t.length>0?t:`${Bn}/${e}#${Ie(r)}`,Zn=e=>e.includes("..")?!1:e.startsWith("gh:")||e.startsWith("github:")||e.startsWith("https://"),R=(e,t)=>{e.info(`[dry-run] would ${t}`)},et=(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:g.NOT_FOUND,files:[],target:t}),tt="Template files copied.",te=(e,t,r)=>{k()&&process.stdout.write(`
|
|
1505
|
+
`),e.success(`scaffolded ${String(t.length)} files into ${r}`)},ea=(e,t)=>{const{args:r,command:n}=At(e,t);return`${n} ${r.join(" ")}`},rt=(e,t)=>{let r=_e(e);for(;;){if(t(r))return!0;const n=S(r);if(n===r)return!1;r=n}},ta=e=>f(u(e,Qe))?!0:yt(e)?.workspaces!==void 0,re=e=>rt(e,ta),ra=e=>rt(e,t=>f(u(t,".git"))),na=async(e,t)=>{if(e.yes===!0||!k()||ra(S(t)))return;if(!await $e(C.git,{badge:w.git,defaultYes:!1})){await Me("Sounds good! You can always run git init manually.");return}if(e.dryRun===!0){R(e.logger,"initialize a git repository");return}const r=e.spawner??Re;(await Ut("Initializing a git repository…",()=>r({args:["init"],command:"git",cwd:t}))).code===0?await U("git","Initialized an empty git repository."):e.logger.warn("`git init` failed — initialize it yourself later with `git init`.")},aa=async(e,t,r,n)=>{const a=[{code:`cd ./${e}`,lead:"Enter your project directory using"}];t===void 0&&a.push({code:`${r} install`,lead:"Install dependencies with",tail:n?" from the workspace root":void 0}),a.push({code:Lt(r,"dev"),lead:"Run",tail:" to start the dev server."},{code:"lunora add",lead:"Add features like auth or storage using"});const i=[{code:"https://lunora.sh/docs",lead:"Read the docs at"},{code:"https://lunora.sh/chat",lead:"Stuck? Join the chat at"}];if(k()){await jt(w.next,C.nextHeader,a,i);return}const s=a.map(o=>`${o.lead} ${o.code}${o.tail??""}`);s.push("",...i.map(o=>`${o.lead} ${o.code}${o.tail??""}`)),await U("next",C.nextHeader,s.join(`
|
|
1506
|
+
`))},oa=e=>e.yes!==!0&&(e.installPrompt!==void 0||k()),ia=async(e,t)=>{if(!oa(e)||re(S(t)))return;const r=St(e.packageManagerProbe),[n]=r;if(n===void 0)return;if(!await(e.installPrompt?.confirmInstall??(async()=>$e(C.install,{badge:w.deps,defaultYes:!0})))()){await Me("No problem! Remember to install dependencies after setup.");return}let i=n;if(r.length>1&&(i=e.installPrompt?await e.installPrompt.selectManager(r):await D(C.packageManager,r.map(d=>({label:d,value:d})),{badge:w.deps,default:n})??n),e.dryRun===!0){R(e.logger,`install dependencies with ${i}`);return}i==="pnpm"&&Xe(t);const s=e.spawner??Re,{args:o,command:l}=Se(i);await U("deps",`Installing dependencies with ${i}…`);const c=await s({args:o,command:l,cwd:t});if(c.code!==0){e.logger.warn(`\`${l} install\` exited with code ${String(c.code)} — run it yourself in ${T(t)}/.`);return}return await U("deps",`Dependencies installed with ${i}.`),i},sa=async(e,t,r,n,a,i)=>{const s=u(e,t);if(!f(s))return a.error(`template not found in local source: ${s}`),{code:g.NOT_FOUND,files:[],target:r};const o=await Ze(s,r,n);return o.length===0?et(a,r,s):(i(),te(a,o,r),{code:0,files:o,target:r})},la=async e=>{const{logger:t,markComplete:r,name:n,ref:a,source:i,target:s,templateType:o}=e,l=be(u(ke(),"lunora-init-fetch-")),c=u(l,"template");try{const d=i!==void 0&&i.length>0?a:await $t(a,t),p=G(o,i,d);let m,h=[];if(await Ne([{label:`${o} template fetched`,run:async()=>{m=await Ce(p,{cwd:l,dir:c,force:!0,install:!1,silent:!0})}},{label:`files copied into ${n}/`,run:async()=>{h=await Ze(c,s,n)}}],{end:tt,start:"Project initializing…"}),h.length===0)return et(t,s,m?.source??p);r();const x=H(c);return k()&&process.stdout.write(`
|
|
1507
|
+
`),t.info(m?.commit?`template: ${m.source} @ ${m.commit} (${String(x.length)} files)`:`template: ${m?.source??p} (${String(x.length)} files)`),te(t,h,s),{code:0,files:h,target:s}}catch(d){if(d instanceof X)throw d;const{hints:p,message:m}=br(d,{ref:Ie(a),remote:G(o,i,a),templateType:o});t.error(m);for(const h of p)t.warn(h);return{code:1,files:[],target:s}}finally{P(l,{force:!0,recursive:!0})}},ca=e=>{for(const t of["_gitignore","_npmrc","_gitattributes"]){const r=u(e,t);f(r)&&dt(r,u(e,`.${t.slice(1)}`))}},da=async e=>{const{framework:t,logger:r,markComplete:n,name:a,overlayBaseFrom:i,target:s}=e,o=F[t],l=be(u(ke(),"lunora-vite-base-"));try{let c;if(i!==void 0&&(c=u(i,`template-${o.createViteTemplate}`),!f(c)))return r.error(`create-vite base not found on disk: ${c}`),{code:g.NOT_FOUND,files:[],target:s};const d=async()=>{if(c!==void 0){ge(c,s);return}const m=u(l,"base"),h=await Tt(ve,"main",r),x=`github:${ve}/packages/create-vite/template-${o.createViteTemplate}#${h}`;await Ce(x,{cwd:l,dir:m,force:!0,install:!1,silent:!0}),ca(m),ge(m,s)};let p=[];return await Ne([{label:`create-vite (${o.label}) base ready`,run:d},{label:`Lunora overlay applied (${o.label})`,run:async()=>{p=await Rn({adapter:o,distTag:Ae(),logger:r,name:a,target:s})}}],{end:tt,start:"Project initializing…"}),n(),te(r,p,s),{code:0,files:[...H(s)],target:s}}catch(c){if(c instanceof X)throw c;const d=c instanceof Error?c.message:String(c);return r.error(`failed to scaffold the ${o.label} base: ${d}`),{code:1,files:[],target:s}}finally{P(l,{force:!0,recursive:!0})}},Y=(e,t,r,n,a)=>(a.error(`init --in-place: could not ${e} ${t}: ${r instanceof Error?r.message:String(r)}`),{code:1,files:[],target:n}),ua=(e,t)=>{const r=u(e,"vite.config.ts");try{v(r,Un,"utf8")}catch(n){return Y("write",r,n,e,t)}return t.success(`created ${r} with lunora() plugin`),{code:0,files:[r],target:e}},ha=(e,t,r)=>{let n;try{n=_(e,"utf8")}catch(i){return Y("read",e,i,t,r)}const a=Be(n);if(!a.changed)return r.info(`${e}: ${a.reason??"no changes needed"}`),{code:0,files:[],target:t};try{v(e,a.code,"utf8")}catch(i){return Y("write",e,i,t,r)}return r.success(`patched ${e} — added lunora() plugin`),{code:0,files:[e],target:t}},pa=(e,t)=>{const r=u(e,"lunora"),n=u(r,"schema.ts");if(f(n))return t.info(`lunora/ already present — left ${n} untouched`),[];const a=[];try{I(r,{recursive:!0}),v(n,jn,"utf8"),a.push(n);const i=u(r,"messages.ts");f(i)||(v(i,Vn,"utf8"),a.push(i)),t.success(`scaffolded lunora/ (${String(a.length)} file(s))`)}catch(i){const s=i instanceof Error?i.message:String(i);t.error(`init --here: could not scaffold lunora/: ${s}`)}return a},nt=e=>e==="sveltekit"||e==="nuxt"||e==="astro",ma=(e,t,r)=>{const{adapter:n,class:a,framework:i}=e;r.info(""),r.info(`detected framework: ${i} (class ${a})`),r.info("next steps:");const s=[n,"@lunora/client","@lunora/runtime","@lunora/server"];nt(i)||s.push("@lunora/vite"),r.info(` 1. install the adapter: ${ea(t,s)}`),r.info(" 2. run codegen: lunora codegen"),a==="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 ${n} 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")):a==="B"?(r.info(" 3. inject Lunora: mount Lunora realtime under /_lunora/* in your server hook"),r.info(` (${i} owns its Cloudflare adapter — Lunora composes into its server entry)`),r.info(` 4. add the provider: mount the ${n} 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("")},fa=(e,t,r)=>{if(nt(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 n=Ge(e);return n===void 0?ua(e,r):ha(n,e,r)},va=(e,t)=>{const r=lr(e),n=fa(e,r.framework,t);if(n.code!==0)return n;const a=pa(e,t);return ma(r,V(e),t),{code:0,files:[...n.files,...a],target:e}},ga=e=>e.yes!==!0&&(e.prompt!==void 0||(e.interactive??k())),we=async(e,t,r)=>{r.dryRun!==!0&&await an({apply:n=>wt(e,n),detected:gt(e),interactive:t,logger:r.logger,multiSelect:r.lintPrompt??((n,a,i)=>Te(n,a,{...i,badge:w.add}))})},wa=async(e,t)=>{const r=ga(e),n=e.add===void 0?[]:Gr(e.add,o=>{e.logger.warn(o)}),a=async o=>{if(o.length===0)return!0;if(e.dryRun===!0)return R(e.logger,`add ${o.map(h=>h.externalAuth===void 0?h.label:`${h.label} (and wire resolveIdentity)`).join(", ")}`),!0;const l=[],c=k()?{error:h=>{l.push({level:"error",message:h})},info:()=>{},success:()=>{},warn:h=>{l.push({level:"warn",message:h})}}:e.logger,d=o.map(h=>({running:`adding ${h.label}…`,task:()=>Yt({allowUnsafeSource:e.allowUnsafeSource,cwd:t,from:e.registryFrom,logger:c,names:[...h.names],ref:e.ref,source:e.registrySource,transformManifest:h.transformManifest,yes:!0})})),p=`added ${o.map(h=>h.label).join(", ")}`,m=await Vt(w.add,d,p);for(const{level:h,message:x}of l)e.logger[h](x);for(const[h,x]of o.entries())x.externalAuth!==void 0&&m[h]?.code===0&&Hr(t,x.externalAuth,e.logger);return m.every(h=>h.code===0)},i=e.auth===void 0?void 0:xr(e.auth,o=>{e.logger.warn(o)}),s={applyAll:a,auth:i,interactive:r,logger:e.logger,multiSelect:e.prompt?.multiSelect??((o,l,c)=>Te(o,l,{...c,badge:w.add})),preselected:n.length>0?n:void 0,projectName:T(t),resolveAuthUiItem:()=>{const o=Ee(t);if(!zt(o))return Gt(o)??"auth-ui-react"},select:e.prompt?.select??((o,l,c)=>D(o,l,{...c,badge:w.add})),selectAuth:e.prompt===void 0?(o,l,c)=>D(o,l,{...c,badge:w.add}):e.prompt.selectAuth??(()=>Promise.resolve("none")),text:e.prompt?.text??((o,l)=>Oe(o,{...l,badge:w.add}))};if(n.length>0||i!==void 0&&!r){const o=await he(s);return await we(t,r,e),o}return k()&&await Dt(C.extras),await he(s),await we(t,r,e),!0},K="react",at=[{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:"React SPA on Rsbuild — the Worker runs under wrangler dev behind the dev server",label:"React · Rsbuild",value:"rspack-react"},{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 (React) on Rsbuild — SSR composed into the Lunora worker",label:"TanStack Start · React · Rsbuild",value:"tanstack-start-react-rspack"},{description:"SaaS kit — multi-tenant app on TanStack Start: organizations, projects, activity, admin",label:"SaaS kit",value:"saas"},{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:"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"}],ot=Object.keys(F).join("|"),it=at.filter(e=>!W(e.value)).map(e=>e.value),st=it.join("|"),ya=e=>W(e)?{framework:e,kind:"overlay"}:{kind:"template",templateType:e},ba=async e=>e.vite!==void 0?{framework:e.vite,kind:"overlay"}:e.templateType!==void 0?{kind:"template",templateType:e.templateType}:!k()||e.yes===!0?{framework:K,kind:"overlay"}:ya(await D(C.framework,at,{badge:w.tmpl,default:K})??K),ka=e=>{if(k()||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 <${ot}>\` for an SPA, or \`-t <${st}>\` 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.`},xa=async(e,t,r,n,a)=>W(t)?await Je({isLocal:e.overlayBaseFrom!==void 0,logger:e.logger})?(I(n,{recursive:!0}),da({framework:t,logger:e.logger,markComplete:a,name:r,overlayBaseFrom:e.overlayBaseFrom,target:n})):{code:1,files:[],target:n}:(e.logger.error(`init: unknown framework "${t}". Supported overlays: ${Object.keys(F).join(", ")}.`),{code:g.USAGE,files:[],target:n}),Ea=async(e,t,r,n,a)=>e.from!==void 0?await sa(e.from,t,n,r,e.logger,a):e.source!==void 0&&e.source.length>0&&!e.allowUnsafeSource&&!Zn(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:g.USAGE,files:[],target:n}):await Je({isLocal:!1,logger:e.logger,source:G(t,e.source,e.ref)})?la({logger:e.logger,markComplete:a,name:r,ref:e.ref,source:e.source,target:n,templateType:t}):{code:1,files:[],target:n},_a=(e,t)=>{if(re(t))return;let r;try{r=V(e)}catch{return}r==="pnpm"&&Xe(e)},Ca=async(e,t,r)=>{await Pt("realtime backend on Cloudflare Workers + Durable Objects");const n=ka(e);if(n!==void 0)return e.logger.error(n),{code:g.USAGE,files:[],target:""};const a=$n(),i=e.name??await Oe(C.name,{badge:w.dir,default:a,placeholder:a}),s=await ba(e),o=i.trim();if(o.length===0)return e.logger.error("init: refusing an empty project name — pass a directory name (e.g. `lunora init my-app`)."),{code:g.USAGE,files:[],target:""};if(o.includes("/")||o.includes("\\")||o===".."||o===".")return e.logger.error(`init: refusing project name "${o}" — must not contain path separators or be "." / "..".`),{code:g.USAGE,files:[],target:""};if(!Wn.test(o))return e.logger.error(`init: refusing project name "${o}" — a Cloudflare Worker name must be lowercase letters, digits, "-" or "_" (starting with a letter, digit or "_"), and wrangler rejects anything else. Try \`${Kn(o)}\`.`),{code:g.USAGE,files:[],target:""};const l=_e(t,o),c=ye(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:g.CONFLICT,files:[],target:l};const d=c!==void 0;if(d&&J(l).length>0)return e.logger.error(`target directory not empty: ${l}`),{code:g.CONFLICT,files:[],target:l};if(e.dryRun===!0){const m=s.kind==="overlay"?`the ${s.framework} create-vite overlay`:`the ${s.templateType} template`;return R(e.logger,`scaffold ${m} into ${l}`),{code:0,files:[],target:l}}r.record(l,d);const p=s.kind==="overlay"?await xa(e,s.framework,o,l,r.complete):await Ea(e,s.templateType,o,l,r.complete);return p.code===0&&_a(l,t),p},z=(e,t)=>{const{target:r,targetPreExisted:n}=e;if(!(r===void 0||!f(r))){if(n===!0)for(const a of J(r))P(u(r,a),{force:!0,recursive:!0});else P(r,{force:!0,recursive:!0});t.info(`removed the partially-created project at ${r}`)}},Sa=async(e,t,r)=>e.inPlace!==!0?Ca(e,t,r):e.dryRun===!0?(R(e.logger,`configure Lunora into ${t}`),{code:0,files:[],target:t}):va(t,e.logger),La=async(e,t,r)=>{const n=await wa(e,t.target),a=e.inPlace===!0?void 0:await ia(e,t.target);if(e.inPlace!==!0){await na(e,t.target);const i=a??V(t.target);await aa(T(t.target),a,i,re(r)),await Kr(e.logger)}return n},Aa=(e,t,r)=>{if(t.code!==0||e.ci===void 0)return;if(e.dryRun===!0){R(e.logger,`scaffold a ${e.ci} CI deploy pipeline`);return}const n=e.inPlace===!0?r:t.target;try{const a=V(n);ir(n,e.ci,a,e.logger)}catch{e.logger.warn(`--ci ${e.ci}: could not detect a package manager for this project — skipped the CI pipeline.`)}},Ia=async e=>{const t=e.cwd??process.cwd(),r={};let n;try{n=await Sa(e,t,{complete:()=>{r.target=void 0},record:(a,i)=>{r.target=a,r.targetPreExisted=i}}),n.code===0&&n.target!==""?(r.target=void 0,await La(e,n,t)||(n={...n,code:1})):n.code!==0&&z(r,e.logger)}catch(a){if(a instanceof X)return z(r,e.logger),process.stdout.write("\n ✖ Setup cancelled — run `lunora init` again whenever you're ready. 🌙\n"),{code:130,files:[],target:""};throw z(r,e.logger),a}return Aa(e,n,t),n},Ra=e=>typeof e=="string"&&it.includes(e),Oa=(e,t)=>{if(e!==void 0){if(ar(e))return e;t.warn(`init: unknown --ci "${e}" — expected github | gitlab; skipping CI scaffold.`)}},Ta=e=>e===void 0?{}:Ra(e)?{templateType:e}:W(e)?{vite:e}:{error:`init: unknown --template "${e}" — expected a bespoke template (${st}) or an overlay framework (${ot}).`},ro=It(({argument:e,cwd:t,logger:r,options:n})=>{const a=Ta(n.template);return"error"in a?(r.error(a.error),{code:g.USAGE}):Ia({add:n.add,auth:n.auth,allowUnsafeSource:n.allowUnsafeSource===!0,cwd:t,ci:Oa(n.ci,r),dryRun:n.dryRun===!0,from:n.from,inPlace:n.here===!0,interactive:n.interactive===!0?!0:void 0,logger:r,name:e[0],ref:n.ref,source:n.source,templateType:a.templateType,vite:n.vite??a.vite,yes:n.yes===!0})});export{at as FRAMEWORK_CHOICES,ro as execute,Ra as isTemplate,Ta as resolveTemplateFlag,G as resolveTemplateSource,Ia as runInitCommand};
|