create-lacspace-app 2.2.2 → 2.4.0

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/index.js CHANGED
@@ -35,7 +35,25 @@ function resolveContext(options = {}) {
35
35
  const raw = options.name ?? "my-app";
36
36
  const seg = raw.split(/[\\/]/).filter(Boolean).pop() ?? "my-app";
37
37
  const name = seg.toLowerCase().replace(/[^a-z0-9-_]/g, "-").replace(/^-+|-+$/g, "") || "my-app";
38
- return { name, template };
38
+ const features = normalizeFeatures(options.features);
39
+ const mode = options.mode === "dynamic" ? "dynamic" : "static";
40
+ return { name, template, features, mode };
41
+ }
42
+ function normalizeFeatures(requested) {
43
+ if (!requested || requested.length === 0) return [];
44
+ const seen = /* @__PURE__ */ new Set();
45
+ const out = [];
46
+ const unknown = [];
47
+ for (const raw of requested) {
48
+ const key = String(raw).toLowerCase().trim();
49
+ if (!key || seen.has(key)) continue;
50
+ seen.add(key);
51
+ const def = FEATURES.find((f) => f.key === key);
52
+ if (def) out.push(def);
53
+ else unknown.push(key);
54
+ }
55
+ if (unknown.length) console.warn(`create-lacspace-app: ignoring unknown feature(s): ${unknown.join(", ")}`);
56
+ return out;
39
57
  }
40
58
  var pkgJson = (ctx) => JSON.stringify({
41
59
  name: ctx.name,
@@ -1892,6 +1910,10 @@ Because posts are just Markdown files, you can:
1892
1910
  Check the [first post](/blog/welcome) for the full Markdown reference.
1893
1911
  `;
1894
1912
  function buildFiles(ctx) {
1913
+ if (ctx.mode === "dynamic") return buildFullStack(ctx);
1914
+ return buildApp(ctx);
1915
+ }
1916
+ function buildApp(ctx) {
1895
1917
  const isBlog = ctx.template.key === "blog";
1896
1918
  const isDocs = ctx.template.key === "docs";
1897
1919
  const files = {
@@ -1962,8 +1984,529 @@ function buildFiles(ctx) {
1962
1984
  files["content/docs/installation.md"] = sampleDocInstall();
1963
1985
  files["content/docs/writing-content.md"] = sampleDocWriting();
1964
1986
  }
1987
+ applyFeatures(files, ctx);
1965
1988
  return files;
1966
1989
  }
1990
+ function applyFeatures(files, ctx) {
1991
+ const features = ctx.features;
1992
+ if (!features.length) return;
1993
+ for (const feat of features) {
1994
+ for (const [rel, content] of Object.entries(feat.files(ctx))) {
1995
+ files[rel] = content;
1996
+ }
1997
+ }
1998
+ const addDeps = {};
1999
+ const addScripts = {};
2000
+ for (const feat of features) {
2001
+ Object.assign(addDeps, feat.deps);
2002
+ if (feat.scripts) Object.assign(addScripts, feat.scripts);
2003
+ }
2004
+ if (files["package.json"]) {
2005
+ const pkg = JSON.parse(files["package.json"]);
2006
+ pkg.dependencies = { ...pkg.dependencies ?? {}, ...addDeps };
2007
+ if (Object.keys(addScripts).length) pkg.scripts = { ...pkg.scripts ?? {}, ...addScripts };
2008
+ files["package.json"] = JSON.stringify(pkg, null, 2) + "\n";
2009
+ }
2010
+ const existingEnv = new Set(
2011
+ (files[".env.example"] ?? "").split("\n").map((l) => l.match(/^\s*#?\s*([A-Z0-9_]+)=/)?.[1]).filter(Boolean)
2012
+ );
2013
+ const envLines = [];
2014
+ for (const feat of features) {
2015
+ if (!feat.env || Object.keys(feat.env).length === 0) continue;
2016
+ const fresh = Object.entries(feat.env).filter(([name]) => !existingEnv.has(name));
2017
+ if (fresh.length === 0) continue;
2018
+ envLines.push("", `# --- ${feat.label} (${feat.key}) ---`);
2019
+ for (const [name, comment] of fresh) {
2020
+ if (comment) envLines.push(`# ${comment}`);
2021
+ envLines.push(`${name}=`);
2022
+ existingEnv.add(name);
2023
+ }
2024
+ }
2025
+ if (envLines.length) {
2026
+ const base = files[".env.example"] ?? "";
2027
+ files[".env.example"] = (base.endsWith("\n") || base === "" ? base : base + "\n") + envLines.join("\n") + "\n";
2028
+ }
2029
+ files["LEARN.md"] = learnMd(ctx, features);
2030
+ }
2031
+ function learnMd(ctx, features) {
2032
+ const blocks = features.map((f) => {
2033
+ const steps = f.nextSteps.map((s) => `- [ ] ${s}`).join("\n");
2034
+ const learn = f.learn ? `
2035
+
2036
+ Learn more \u2192 ${f.learn}` : "";
2037
+ return `## ${f.label} \`(${f.key})\`
2038
+
2039
+ ${f.description}
2040
+
2041
+ ${steps}${learn}`;
2042
+ }).join("\n\n");
2043
+ return `# \u{1F9ED} Learn ${ctx.name}
2044
+
2045
+ You scaffolded **${ctx.template.label}** with ${features.length} feature add-on${features.length === 1 ? "" : "s"}:
2046
+ ${features.map((f) => `\`${f.key}\``).join(" \xB7 ")}.
2047
+
2048
+ Work through the checklist below \u2014 each item is a real next step.
2049
+
2050
+ ${blocks}
2051
+
2052
+ ---
2053
+
2054
+ Every add-on is built from zero-dependency \`@lacspace/*\` packages. Browse them all \u2192 https://lacspace.com/packages
2055
+ `;
2056
+ }
2057
+ var FEATURES = [
2058
+ {
2059
+ key: "ai-chat",
2060
+ label: "AI chat",
2061
+ description: "A streaming AI chat route + UI \u2014 free & local by default (Ollama), keyless.",
2062
+ deps: {
2063
+ "@lacspace/ai": "^1.1.0",
2064
+ "@lacspace/prompt": "^1.1.0",
2065
+ "@lacspace/stream": "^1.1.0",
2066
+ "@lacspace/providers": "^1.0.0",
2067
+ "@lacspace/memory": "^1.0.0",
2068
+ "@lacspace/moderation": "^1.0.0"
2069
+ },
2070
+ env: {
2071
+ LACSPACE_AI_PROVIDER: "Which provider preset to use (default: ollama \u2014 free & local, no key).",
2072
+ LACSPACE_AI_BASE_URL: "Override the provider base URL (default Ollama: http://localhost:11434).",
2073
+ LACSPACE_AI_MODEL: "Chat model id (default: llama3.2).",
2074
+ LACSPACE_AI_API_KEY: "Only needed for a hosted provider \u2014 leave blank for local Ollama."
2075
+ },
2076
+ files: (ctx) => ({
2077
+ "app/api/chat/route.ts": aiChatRoute(),
2078
+ "app/chat/page.tsx": aiChatPage(ctx)
2079
+ }),
2080
+ nextSteps: [
2081
+ "\u{1F193} Free local AI \u2014 install Ollama (https://ollama.com), then run `ollama pull llama3.2`.",
2082
+ "Run `npm run dev` and open http://localhost:3000/chat.",
2083
+ "Prefer a hosted model? Set LACSPACE_AI_* in .env (e.g. LACSPACE_AI_PROVIDER=groq + LACSPACE_AI_API_KEY=\u2026)."
2084
+ ],
2085
+ learn: "https://developer.lacspace.com/packages/ai"
2086
+ },
2087
+ {
2088
+ key: "rag",
2089
+ label: "RAG \u2014 chat with your docs",
2090
+ description: "Index your markdown/text and answer grounded questions with cited sources. Keyless & local (Ollama).",
2091
+ deps: {
2092
+ "@lacspace/rag": "^1.0.0",
2093
+ "@lacspace/embeddings": "^1.0.0",
2094
+ "@lacspace/vector": "^1.0.0",
2095
+ "@lacspace/chunk": "^1.1.0",
2096
+ "@lacspace/rerank": "^1.0.0",
2097
+ "@lacspace/providers": "^1.0.0",
2098
+ "@lacspace/ai": "^1.1.0"
2099
+ },
2100
+ scripts: { "rag:index": "node scripts/index-content.mjs" },
2101
+ env: {
2102
+ LACSPACE_AI_PROVIDER: "Which provider preset to use (default: ollama \u2014 free & local, no key).",
2103
+ LACSPACE_AI_BASE_URL: "Override the provider base URL (default Ollama: http://localhost:11434).",
2104
+ LACSPACE_AI_MODEL: "Chat model id used to answer (default: llama3.2).",
2105
+ LACSPACE_AI_API_KEY: "Only needed for a hosted provider \u2014 leave blank for local Ollama.",
2106
+ LACSPACE_EMBED_MODEL: "Embedding model id (default: nomic-embed-text)."
2107
+ },
2108
+ files: (ctx) => ({
2109
+ "content/welcome.md": ragSampleDoc(ctx),
2110
+ "scripts/index-content.mjs": ragIndexScript(),
2111
+ "app/api/ask/route.ts": ragAskRoute(),
2112
+ "app/ask/page.tsx": ragAskPage(ctx)
2113
+ }),
2114
+ nextSteps: [
2115
+ "\u{1F193} Free & local \u2014 install Ollama (https://ollama.com), then `ollama pull nomic-embed-text` and `ollama pull llama3.2`.",
2116
+ "Add markdown/text files to content/, then run `npm run rag:index` to build .rag-index.json.",
2117
+ "Run `npm run dev` and open http://localhost:3000/ask."
2118
+ ],
2119
+ learn: "https://developer.lacspace.com/packages/rag"
2120
+ }
2121
+ ];
2122
+ var aiChatRoute = (_ctx) => `import { resolveConfig } from "@lacspace/providers";
2123
+ import { stream } from "@lacspace/ai";
2124
+ import type { Message } from "@lacspace/ai";
2125
+ import { detectPromptInjection } from "@lacspace/moderation";
2126
+ import { toReadableStream } from "@lacspace/stream";
2127
+
2128
+ // This route runs on Node (it talks to your local Ollama / a hosted LLM).
2129
+ export const runtime = "nodejs";
2130
+ export const dynamic = "force-dynamic";
2131
+
2132
+ export async function POST(req: Request) {
2133
+ // 1. Read the conversation the <ChatUI/> sent us.
2134
+ const { messages } = (await req.json()) as { messages: Message[] };
2135
+
2136
+ // 2. Guard the newest user turn against prompt-injection / jailbreak attempts.
2137
+ // Learn more \u2192 https://developer.lacspace.com/packages/moderation
2138
+ const lastUser = [...messages].reverse().find((m) => m.role === "user");
2139
+ const userText = typeof lastUser?.content === "string" ? lastUser.content : "";
2140
+ const check = detectPromptInjection(userText);
2141
+ if (check.flagged) {
2142
+ return new Response(JSON.stringify({ error: "That message was blocked by the safety guard." }), {
2143
+ status: 400,
2144
+ headers: { "Content-Type": "application/json" },
2145
+ });
2146
+ }
2147
+
2148
+ // 3. Resolve provider config from env \u2014 KEYLESS by default (local Ollama).
2149
+ // Learn more \u2192 https://developer.lacspace.com/packages/providers
2150
+ const cfg = resolveConfig(process.env.LACSPACE_AI_PROVIDER ?? "ollama", {
2151
+ baseUrl: process.env.LACSPACE_AI_BASE_URL, // default: http://localhost:11434
2152
+ model: process.env.LACSPACE_AI_MODEL, // default: llama3.2
2153
+ apiKey: process.env.LACSPACE_AI_API_KEY, // only for hosted providers
2154
+ });
2155
+
2156
+ // Ollama speaks its own dialect but also exposes an OpenAI-compatible surface
2157
+ // at /v1 \u2014 so we always call it (and any hosted provider) as "openai-compatible".
2158
+ const baseUrl = cfg.apiStyle === "ollama" ? cfg.baseUrl.replace(/\\/+$/, "") + "/v1" : cfg.baseUrl;
2159
+ const model = cfg.model ?? "llama3.2";
2160
+
2161
+ // 4. Stream the reply. @lacspace/ai yields unified {type:"text", delta} chunks;
2162
+ // we encode each token and hand the stream to the browser via @lacspace/stream.
2163
+ // Learn more \u2192 https://developer.lacspace.com/packages/ai
2164
+ const encoder = new TextEncoder();
2165
+ async function* tokens() {
2166
+ for await (const chunk of stream({
2167
+ provider: "openai-compatible",
2168
+ baseUrl,
2169
+ apiKey: cfg.apiKey,
2170
+ model,
2171
+ headers: cfg.headers,
2172
+ messages,
2173
+ })) {
2174
+ if (chunk.type === "text") yield encoder.encode(chunk.delta);
2175
+ }
2176
+ }
2177
+
2178
+ // Learn more \u2192 https://developer.lacspace.com/packages/stream
2179
+ return new Response(toReadableStream(tokens()), {
2180
+ headers: { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-cache" },
2181
+ });
2182
+ }
2183
+ `;
2184
+ var aiChatPage = (ctx) => `"use client";
2185
+
2186
+ import { useState, useRef, useEffect } from "react";
2187
+
2188
+ interface Msg { role: "user" | "assistant"; content: string; }
2189
+
2190
+ export default function ChatPage() {
2191
+ const [messages, setMessages] = useState<Msg[]>([]);
2192
+ const [input, setInput] = useState("");
2193
+ const [busy, setBusy] = useState(false);
2194
+ const scroller = useRef<HTMLDivElement>(null);
2195
+
2196
+ useEffect(() => {
2197
+ scroller.current?.scrollTo({ top: scroller.current.scrollHeight, behavior: "smooth" });
2198
+ }, [messages]);
2199
+
2200
+ async function send(e: React.FormEvent) {
2201
+ e.preventDefault();
2202
+ const text = input.trim();
2203
+ if (!text || busy) return;
2204
+ setInput("");
2205
+ setBusy(true);
2206
+
2207
+ const next: Msg[] = [...messages, { role: "user", content: text }];
2208
+ setMessages([...next, { role: "assistant", content: "" }]);
2209
+
2210
+ try {
2211
+ const res = await fetch("/api/chat", {
2212
+ method: "POST",
2213
+ headers: { "Content-Type": "application/json" },
2214
+ body: JSON.stringify({ messages: next }),
2215
+ });
2216
+ if (!res.ok || !res.body) throw new Error("The chat endpoint returned an error.");
2217
+
2218
+ // Read the streamed reply token-by-token and append it live.
2219
+ const reader = res.body.getReader();
2220
+ const decoder = new TextDecoder();
2221
+ let acc = "";
2222
+ for (;;) {
2223
+ const { done, value } = await reader.read();
2224
+ if (done) break;
2225
+ acc += decoder.decode(value, { stream: true });
2226
+ setMessages([...next, { role: "assistant", content: acc }]);
2227
+ }
2228
+ } catch {
2229
+ setMessages([...next, { role: "assistant", content: "\u26A0\uFE0F Couldn't reach the model. Is Ollama running? (ollama.com)" }]);
2230
+ } finally {
2231
+ setBusy(false);
2232
+ }
2233
+ }
2234
+
2235
+ return (
2236
+ <section className="mx-auto flex min-h-[calc(100vh-4rem)] max-w-2xl flex-col px-6 py-10">
2237
+ <header className="mb-6">
2238
+ <p className="text-sm font-semibold uppercase tracking-widest gradient-text">AI \xB7 ${ctx.template.siteName}</p>
2239
+ <h1 className="mt-2 text-3xl font-bold sm:text-4xl">Chat</h1>
2240
+ <p className="mt-2 text-muted">Free &amp; local by default \u2014 powered by Ollama and the Lacspace AI Kit. No key required.</p>
2241
+ </header>
2242
+
2243
+ <div ref={scroller} className="flex-1 space-y-4 overflow-y-auto rounded-2xl border border-hairline bg-surface p-4">
2244
+ {messages.length === 0 && (
2245
+ <p className="py-16 text-center text-muted">Ask me anything to get started.</p>
2246
+ )}
2247
+ {messages.map((m, i) => (
2248
+ <div key={i} className={m.role === "user" ? "flex justify-end" : "flex justify-start"}>
2249
+ <div className={
2250
+ "max-w-[85%] whitespace-pre-wrap rounded-2xl px-4 py-2.5 text-sm leading-relaxed " +
2251
+ (m.role === "user" ? "gradient-bg on-accent" : "border border-hairline bg-app")
2252
+ }>
2253
+ {m.content || (busy ? "\u2026" : "")}
2254
+ </div>
2255
+ </div>
2256
+ ))}
2257
+ </div>
2258
+
2259
+ <form onSubmit={send} className="mt-4 flex gap-2">
2260
+ <input
2261
+ value={input}
2262
+ onChange={(e) => setInput(e.target.value)}
2263
+ placeholder="Type a message\u2026"
2264
+ className="w-full rounded-xl border border-hairline bg-surface px-4 py-3 outline-none focus:border-hairline"
2265
+ />
2266
+ <button
2267
+ type="submit"
2268
+ disabled={busy || !input.trim()}
2269
+ className="rounded-xl gradient-bg on-accent px-5 py-3 text-sm font-semibold shimmer disabled:opacity-50"
2270
+ >
2271
+ {busy ? "\u2026" : "Send"}
2272
+ </button>
2273
+ </form>
2274
+ </section>
2275
+ );
2276
+ }
2277
+ `;
2278
+ var ragSampleDoc = (ctx) => `# Welcome to ${ctx.template.siteName}
2279
+
2280
+ This markdown file lives in \`content/\`. Run \`npm run rag:index\` to chunk and embed
2281
+ everything under \`content/\` into a local vector index (\`.rag-index.json\`), then open
2282
+ \`/ask\` to ask grounded questions about it.
2283
+
2284
+ ## How this works
2285
+
2286
+ - **Chunking** \u2014 \`@lacspace/chunk\` splits each document into overlapping passages.
2287
+ - **Embeddings** \u2014 \`@lacspace/embeddings\` turns each passage into a vector using a
2288
+ local Ollama model (\`nomic-embed-text\`) \u2014 no API key needed.
2289
+ - **Retrieval** \u2014 \`@lacspace/vector\` + \`@lacspace/rag\` find the passages closest to
2290
+ your question, and \`@lacspace/rerank\` re-orders them for relevance.
2291
+ - **Answering** \u2014 \`@lacspace/ai\` writes a grounded answer and cites its sources.
2292
+
2293
+ ## Tips
2294
+
2295
+ Add your own \`.md\` or \`.txt\` files here, re-run \`npm run rag:index\`, and ask away.
2296
+ Everything runs on your machine \u2014 free, keyless and private.
2297
+ `;
2298
+ var ragIndexScript = (_ctx) => `// Build a local vector index from everything under content/.
2299
+ // Run: npm run rag:index (needs Ollama: \`ollama pull nomic-embed-text\`)
2300
+ import { readdir, readFile, writeFile, stat } from "node:fs/promises";
2301
+ import { join, extname, relative } from "node:path";
2302
+ import { splitText } from "@lacspace/chunk";
2303
+ import { embed } from "@lacspace/embeddings";
2304
+ import { createVectorStore } from "@lacspace/vector";
2305
+
2306
+ const ROOT = process.cwd();
2307
+ const CONTENT_DIR = join(ROOT, "content");
2308
+ const OUT = join(ROOT, ".rag-index.json");
2309
+
2310
+ // Which files to index (add more extensions if you like).
2311
+ const EXTS = new Set([".md", ".markdown", ".txt", ".mdx"]);
2312
+
2313
+ // Recursively collect readable files under content/.
2314
+ async function walk(dir) {
2315
+ const out = [];
2316
+ let entries = [];
2317
+ try { entries = await readdir(dir, { withFileTypes: true }); }
2318
+ catch { return out; }
2319
+ for (const e of entries) {
2320
+ const full = join(dir, e.name);
2321
+ if (e.isDirectory()) out.push(...(await walk(full)));
2322
+ else if (EXTS.has(extname(e.name).toLowerCase())) out.push(full);
2323
+ }
2324
+ return out;
2325
+ }
2326
+
2327
+ async function main() {
2328
+ const files = await walk(CONTENT_DIR);
2329
+ if (files.length === 0) {
2330
+ console.error("No content found. Add .md/.txt files under content/ and re-run.");
2331
+ process.exit(1);
2332
+ }
2333
+
2334
+ // 1. Chunk every document into overlapping passages via @lacspace/chunk.
2335
+ const records = [];
2336
+ for (const file of files) {
2337
+ const raw = await readFile(file, "utf8");
2338
+ const source = relative(CONTENT_DIR, file);
2339
+ const chunks = splitText(raw, { chunkSize: 900, chunkOverlap: 150 });
2340
+ chunks.forEach((chunk, i) => {
2341
+ records.push({ id: \`\${source}#\${i}\`, text: chunk.text, source });
2342
+ });
2343
+ }
2344
+
2345
+ // 2. Embed all passages with a local Ollama model (keyless) via @lacspace/embeddings.
2346
+ const model = process.env.LACSPACE_EMBED_MODEL ?? "nomic-embed-text";
2347
+ const baseUrl = process.env.LACSPACE_AI_BASE_URL ?? "http://localhost:11434";
2348
+ console.log(\`Embedding \${records.length} chunks with \${model}\u2026\`);
2349
+ const vectors = await embed(records.map((r) => r.text), { provider: "ollama", model, baseUrl });
2350
+
2351
+ // 3. Store them in an in-memory vector store, then serialise to .rag-index.json.
2352
+ const store = createVectorStore({ metric: "cosine" });
2353
+ store.upsert(records.map((r, i) => ({ id: r.id, vector: vectors[i], text: r.text, metadata: { source: r.source } })));
2354
+
2355
+ await writeFile(OUT, JSON.stringify(store.toJSON()));
2356
+ console.log(\`\u2713 Wrote \${OUT} (\${records.length} chunks from \${files.length} files).\`);
2357
+ }
2358
+
2359
+ main().catch((err) => { console.error(err); process.exit(1); });
2360
+ `;
2361
+ var ragAskRoute = (_ctx) => `import { readFile } from "node:fs/promises";
2362
+ import { join } from "node:path";
2363
+ import { fromJSON } from "@lacspace/vector";
2364
+ import { createEmbedder } from "@lacspace/embeddings";
2365
+ import { createRag } from "@lacspace/rag";
2366
+ import { rerank } from "@lacspace/rerank";
2367
+ import { resolveConfig } from "@lacspace/providers";
2368
+ import { chat } from "@lacspace/ai";
2369
+ import type { Message } from "@lacspace/ai";
2370
+
2371
+ export const runtime = "nodejs";
2372
+ export const dynamic = "force-dynamic";
2373
+
2374
+ export async function POST(req: Request) {
2375
+ const { question } = (await req.json()) as { question: string };
2376
+ if (!question || !question.trim()) {
2377
+ return Response.json({ error: "Ask a question." }, { status: 400 });
2378
+ }
2379
+
2380
+ // 1. Load the local index built by \`npm run rag:index\`.
2381
+ let store;
2382
+ try {
2383
+ const raw = await readFile(join(process.cwd(), ".rag-index.json"), "utf8");
2384
+ store = fromJSON(JSON.parse(raw));
2385
+ } catch {
2386
+ return Response.json({ error: "No index found. Run \`npm run rag:index\` first." }, { status: 503 });
2387
+ }
2388
+
2389
+ // 2. Config \u2014 keyless local Ollama by default.
2390
+ // Learn more \u2192 https://developer.lacspace.com/packages/providers
2391
+ const cfg = resolveConfig(process.env.LACSPACE_AI_PROVIDER ?? "ollama", {
2392
+ baseUrl: process.env.LACSPACE_AI_BASE_URL,
2393
+ model: process.env.LACSPACE_AI_MODEL,
2394
+ apiKey: process.env.LACSPACE_AI_API_KEY,
2395
+ });
2396
+ const embedModel = process.env.LACSPACE_EMBED_MODEL ?? "nomic-embed-text";
2397
+ const embedBaseUrl = cfg.apiStyle === "ollama" ? cfg.baseUrl : (process.env.LACSPACE_AI_BASE_URL ?? "http://localhost:11434");
2398
+
2399
+ // 3. Retrieve the closest passages via @lacspace/rag + @lacspace/embeddings.
2400
+ // Learn more \u2192 https://developer.lacspace.com/packages/rag
2401
+ const embedder = createEmbedder({ provider: "ollama", model: embedModel, baseUrl: embedBaseUrl });
2402
+ const rag = createRag({ embed: embedder, store });
2403
+ const hits = await rag.retrieve(question, { k: 8 });
2404
+
2405
+ // 4. Re-rank for relevance and keep the best few. @lacspace/rerank blends the
2406
+ // vector score with a lexical match \u2014 no second model call needed.
2407
+ // Learn more \u2192 https://developer.lacspace.com/packages/rerank
2408
+ const ranked = await rerank(question, hits.map((h) => ({ id: h.id, text: h.text, score: h.score })), { k: 4 });
2409
+
2410
+ // 5. Build a grounded prompt and answer with @lacspace/ai.
2411
+ // Learn more \u2192 https://developer.lacspace.com/packages/ai
2412
+ const context = ranked.map((d, i) => \`[\${i + 1}] \${d.text}\`).join("\\n\\n");
2413
+ const messages: Message[] = [
2414
+ { role: "system", content: "You answer strictly from the provided context. If the answer isn't there, say you don't know. Cite sources as [n]." },
2415
+ { role: "user", content: \`Context:\\n\${context}\\n\\nQuestion: \${question}\` },
2416
+ ];
2417
+
2418
+ const baseUrl = cfg.apiStyle === "ollama" ? cfg.baseUrl.replace(/\\/+$/, "") + "/v1" : cfg.baseUrl;
2419
+ const res = await chat({
2420
+ provider: "openai-compatible",
2421
+ baseUrl,
2422
+ apiKey: cfg.apiKey,
2423
+ model: cfg.model ?? "llama3.2",
2424
+ headers: cfg.headers,
2425
+ messages,
2426
+ });
2427
+
2428
+ const sources = ranked.map((d, i) => ({ n: i + 1, id: d.id }));
2429
+ return Response.json({ answer: res.text, sources });
2430
+ }
2431
+ `;
2432
+ var ragAskPage = (ctx) => `"use client";
2433
+
2434
+ import { useState } from "react";
2435
+
2436
+ interface Source { n: number; id: string; }
2437
+
2438
+ export default function AskPage() {
2439
+ const [question, setQuestion] = useState("");
2440
+ const [answer, setAnswer] = useState("");
2441
+ const [sources, setSources] = useState<Source[]>([]);
2442
+ const [busy, setBusy] = useState(false);
2443
+ const [error, setError] = useState("");
2444
+
2445
+ async function ask(e: React.FormEvent) {
2446
+ e.preventDefault();
2447
+ const q = question.trim();
2448
+ if (!q || busy) return;
2449
+ setBusy(true); setError(""); setAnswer(""); setSources([]);
2450
+ try {
2451
+ const res = await fetch("/api/ask", {
2452
+ method: "POST",
2453
+ headers: { "Content-Type": "application/json" },
2454
+ body: JSON.stringify({ question: q }),
2455
+ });
2456
+ const data = await res.json();
2457
+ if (!res.ok) throw new Error(data.error || "Something went wrong.");
2458
+ setAnswer(data.answer);
2459
+ setSources(data.sources ?? []);
2460
+ } catch (err) {
2461
+ setError(err instanceof Error ? err.message : "Something went wrong.");
2462
+ } finally {
2463
+ setBusy(false);
2464
+ }
2465
+ }
2466
+
2467
+ return (
2468
+ <section className="mx-auto max-w-2xl px-6 py-16">
2469
+ <p className="text-sm font-semibold uppercase tracking-widest gradient-text">RAG \xB7 ${ctx.template.siteName}</p>
2470
+ <h1 className="mt-2 text-3xl font-bold sm:text-4xl">Ask your content</h1>
2471
+ <p className="mt-2 text-muted">Grounded answers from your own docs \u2014 indexed and answered locally. Run <code className="rounded bg-panel px-1.5 py-0.5 text-sm">npm run rag:index</code> first.</p>
2472
+
2473
+ <form onSubmit={ask} className="mt-8 flex gap-2">
2474
+ <input
2475
+ value={question}
2476
+ onChange={(e) => setQuestion(e.target.value)}
2477
+ placeholder="What is this project about?"
2478
+ className="w-full rounded-xl border border-hairline bg-surface px-4 py-3 outline-none focus:border-hairline"
2479
+ />
2480
+ <button
2481
+ type="submit"
2482
+ disabled={busy || !question.trim()}
2483
+ className="rounded-xl gradient-bg on-accent px-5 py-3 text-sm font-semibold shimmer disabled:opacity-50"
2484
+ >
2485
+ {busy ? "\u2026" : "Ask"}
2486
+ </button>
2487
+ </form>
2488
+
2489
+ {error && <p className="mt-6 rounded-xl border border-red-400/40 bg-red-400/10 px-4 py-3 text-sm text-red-400">{error}</p>}
2490
+
2491
+ {answer && (
2492
+ <div className="mt-8 card p-6">
2493
+ <p className="whitespace-pre-wrap leading-relaxed">{answer}</p>
2494
+ {sources.length > 0 && (
2495
+ <div className="mt-5 border-t border-hairline pt-4">
2496
+ <p className="text-xs font-semibold uppercase tracking-widest text-muted">Sources</p>
2497
+ <ul className="mt-2 space-y-1 text-sm text-muted">
2498
+ {sources.map((s) => (
2499
+ <li key={s.n}>[{s.n}] <code className="text-fg">{s.id}</code></li>
2500
+ ))}
2501
+ </ul>
2502
+ </div>
2503
+ )}
2504
+ </div>
2505
+ )}
2506
+ </section>
2507
+ );
2508
+ }
2509
+ `;
1967
2510
  function pagesFor(ctx) {
1968
2511
  const k = ctx.template.key;
1969
2512
  if (k === "dashboard") {
@@ -4552,8 +5095,921 @@ var faqSection = (ctx) => {
4552
5095
  </div>
4553
5096
  </section>`;
4554
5097
  };
5098
+ var scope = (ctx) => `@${ctx.name}`;
5099
+ var typesPkgJson = (ctx) => JSON.stringify({
5100
+ name: `${scope(ctx)}/types`,
5101
+ version: "0.1.0",
5102
+ private: true,
5103
+ // Type-only package: it ships a single .d.ts (no runtime code, nothing to build).
5104
+ types: "./index.d.ts",
5105
+ exports: { ".": { types: "./index.d.ts" } }
5106
+ }, null, 2) + "\n";
5107
+ var sharedTypes = () => `// Shared API contract \u2014 imported by BOTH the frontend and the backend, so the two
5108
+ // can never drift. These are TYPE-ONLY (no runtime code), so importing them adds
5109
+ // nothing to either bundle. Edit here once; both sides update. Use \`import type\`.
5110
+
5111
+ /** A user, as returned by the API (no password; dates are ISO strings). */
5112
+ export interface User {
5113
+ id: string;
5114
+ email: string;
5115
+ name: string;
5116
+ createdAt: string;
5117
+ }
5118
+
5119
+ /** The response from POST /auth/register and POST /auth/login. */
5120
+ export interface AuthResponse {
5121
+ token: string;
5122
+ user: User;
5123
+ }
5124
+
5125
+ /** The shape of an error response from the API. */
5126
+ export interface ApiError {
5127
+ error: string;
5128
+ fields?: Record<string, string>;
5129
+ }
5130
+
5131
+ /** The example CRUD resource. Rename "Note" to your real domain object. */
5132
+ export interface Note {
5133
+ id: string;
5134
+ title: string;
5135
+ body: string;
5136
+ userId: string;
5137
+ createdAt: string;
5138
+ updatedAt: string;
5139
+ }
5140
+
5141
+ export interface CreateNoteInput {
5142
+ title: string;
5143
+ body?: string;
5144
+ }
5145
+
5146
+ export interface UpdateNoteInput {
5147
+ title?: string;
5148
+ body?: string;
5149
+ }
5150
+ `;
5151
+ var rootPkgJson = (ctx) => JSON.stringify({
5152
+ name: ctx.name,
5153
+ version: "0.1.0",
5154
+ private: true,
5155
+ workspaces: ["types", "backend", "frontend"],
5156
+ scripts: {
5157
+ // Run the API and the frontend together (concurrently), colourised + kill-all.
5158
+ dev: 'concurrently -k -n api,web -c blue,magenta "npm:dev:api" "npm:dev:web"',
5159
+ "dev:api": `npm run dev --workspace ${scope(ctx)}/backend`,
5160
+ "dev:web": `npm run dev --workspace ${scope(ctx)}/frontend`,
5161
+ build: `npm run build --workspace ${scope(ctx)}/backend && npm run build --workspace ${scope(ctx)}/frontend`,
5162
+ start: 'concurrently -k -n api,web -c blue,magenta "npm:start:api" "npm:start:web"',
5163
+ "start:api": `npm run start --workspace ${scope(ctx)}/backend`,
5164
+ "start:web": `npm run start --workspace ${scope(ctx)}/frontend`,
5165
+ typecheck: `npm run typecheck --workspace ${scope(ctx)}/backend`
5166
+ },
5167
+ devDependencies: { concurrently: "^9.1.0" },
5168
+ engines: { node: ">=18" }
5169
+ }, null, 2) + "\n";
5170
+ var dockerCompose = (ctx) => `# Local infrastructure for ${ctx.name}. Start it with: docker compose up -d
5171
+ # Optional \u2014 the API also runs with NO Redis, and against any MongoDB (e.g. Atlas).
5172
+ services:
5173
+ mongo:
5174
+ image: mongo:7
5175
+ restart: unless-stopped
5176
+ ports:
5177
+ - "27017:27017"
5178
+ volumes:
5179
+ - mongo-data:/data/db
5180
+ redis:
5181
+ image: redis:7-alpine
5182
+ restart: unless-stopped
5183
+ ports:
5184
+ - "6379:6379"
5185
+
5186
+ volumes:
5187
+ mongo-data:
5188
+ `;
5189
+ var rootGitignore = () => `node_modules
5190
+ .env
5191
+ .env.local
5192
+ *.log
5193
+ .DS_Store
5194
+ dist
5195
+ .next
5196
+ `;
5197
+ var rootEnvExample = (ctx) => `# ${ctx.name} \u2014 ONE .env for the whole monorepo. Copy it: cp .env.example .env
5198
+ # The defaults below let the app run locally with zero changes.
5199
+
5200
+ # --- Backend ---
5201
+ NODE_ENV=development
5202
+ PORT=4000
5203
+
5204
+ # MongoDB. With Docker (docker compose up -d) the default just works. Or paste a
5205
+ # free MongoDB Atlas connection string here.
5206
+ MONGODB_URI=mongodb://localhost:27017/${ctx.name}
5207
+
5208
+ # Signs JWTs. In production generate a strong value: openssl rand -hex 32
5209
+ JWT_SECRET=dev-secret-change-me
5210
+
5211
+ # Redis is OPTIONAL \u2014 leave empty to use the in-memory cache fallback.
5212
+ # With Docker, set it to: redis://localhost:6379
5213
+ REDIS_URL=
5214
+
5215
+ # Who may call the API (the frontend origin). Comma-separate for multiple.
5216
+ CORS_ORIGIN=http://localhost:3000
5217
+
5218
+ # --- Frontend ---
5219
+ # Where the browser calls the API. Unset = http://localhost:4000 (local default).
5220
+ # NEXT_PUBLIC_API_URL=http://localhost:4000
5221
+ `;
5222
+ var rootReadme = (ctx) => `# ${ctx.name}
5223
+
5224
+ A full-stack app scaffolded with [create-lacspace-app](https://www.npmjs.com/package/create-lacspace-app) \u2014 a **${ctx.template.label}** frontend + a real backend, wired together.
5225
+
5226
+ \`\`\`
5227
+ ${ctx.name}/
5228
+ \u251C\u2500 frontend/ Next.js 15 app (your UI) \u2014 talks to the API
5229
+ \u251C\u2500 backend/ Node \xB7 Express \xB7 MongoDB \xB7 Redis \xB7 TypeScript API
5230
+ \u251C\u2500 types/ Shared API types \u2014 imported by BOTH sides, so they can't drift
5231
+ \u2514\u2500 docker-compose.yml Mongo + Redis for local dev (optional)
5232
+ \`\`\`
5233
+
5234
+ ## Quick start
5235
+
5236
+ \`\`\`bash
5237
+ cp .env.example .env # one env file for everything (sensible defaults)
5238
+ docker compose up -d # optional: starts MongoDB + Redis locally
5239
+ npm install # installs all three workspaces at once
5240
+ npm run dev # runs the API (:4000) and the frontend (:3000) together
5241
+ \`\`\`
5242
+
5243
+ Then open **http://localhost:3000** \u2192 visit **/register**, create an account, and you'll land on **/account** \u2014 a protected page that reads/writes the example "notes" resource through the API.
5244
+
5245
+ **No Docker?** Point \`MONGODB_URI\` at any MongoDB (a free [Atlas](https://www.mongodb.com/atlas) cluster works). Redis is optional \u2014 leave \`REDIS_URL\` empty and the API uses an in-memory cache instead.
5246
+
5247
+ ## What's already built
5248
+
5249
+ - **Auth** \u2014 \`POST /auth/register\`, \`POST /auth/login\` (JWT), \`GET /auth/me\`. Passwords hashed with \`@lacspace/password\`, tokens signed/verified with \`@lacspace/jwt\`.
5250
+ - **Example CRUD** \u2014 \`/notes\` (list \xB7 create \xB7 read \xB7 update \xB7 delete), protected, per-user, with a per-user cache (Redis or in-memory) that busts on writes.
5251
+ - **Validation** \u2014 request bodies validated with \`@lacspace/validate\`; failures return a clean 400.
5252
+ - **Rate limiting** \u2014 auth endpoints throttled with \`@lacspace/rate-limit\`.
5253
+ - **Typed env** \u2014 \`@lacspace/env\` fails fast at boot if config is wrong.
5254
+
5255
+ Everything on the backend is built from zero-dependency \`@lacspace/*\` packages \u2192 https://lacspace.com/packages
5256
+
5257
+ ## Make it yours
5258
+
5259
+ Rename the \`Note\` resource (in \`types/index.d.ts\`, \`backend/src/models/note.ts\`, \`backend/src/routes/notes.ts\`) to your real domain object, then follow the same pattern for more resources. The shared \`types/\` package keeps the frontend and backend in lock-step.
5260
+ `;
5261
+ var frontendApiClient = (ctx) => `import type { AuthResponse, User, Note, CreateNoteInput, ApiError } from "${scope(ctx)}/types";
5262
+
5263
+ // how this works: a tiny typed fetch wrapper around the backend API. The response
5264
+ // shapes come from the shared "${scope(ctx)}/types" package \u2014 the SAME types the
5265
+ // backend uses \u2014 so the client and server can never disagree about the contract.
5266
+ const BASE = process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:4000";
5267
+ const TOKEN_KEY = "${ctx.name}_token";
5268
+
5269
+ export function getToken(): string | null {
5270
+ if (typeof window === "undefined") return null;
5271
+ try { return localStorage.getItem(TOKEN_KEY); } catch { return null; }
5272
+ }
5273
+ export function setToken(token: string | null): void {
5274
+ if (typeof window === "undefined") return;
5275
+ try { token ? localStorage.setItem(TOKEN_KEY, token) : localStorage.removeItem(TOKEN_KEY); } catch {}
5276
+ }
5277
+
5278
+ async function request<T>(path: string, init?: RequestInit): Promise<T> {
5279
+ const token = getToken();
5280
+ const res = await fetch(\`\${BASE}\${path}\`, {
5281
+ ...init,
5282
+ headers: {
5283
+ "Content-Type": "application/json",
5284
+ ...(token ? { Authorization: \`Bearer \${token}\` } : {}),
5285
+ ...(init?.headers ?? {}),
5286
+ },
5287
+ });
5288
+ if (!res.ok) {
5289
+ let message = "Request failed";
5290
+ try { message = ((await res.json()) as ApiError).error ?? message; } catch {}
5291
+ throw new Error(message);
5292
+ }
5293
+ if (res.status === 204) return undefined as T;
5294
+ return (await res.json()) as T;
5295
+ }
5296
+
5297
+ export const api = {
5298
+ register: (input: { name: string; email: string; password: string }) =>
5299
+ request<AuthResponse>("/auth/register", { method: "POST", body: JSON.stringify(input) }),
5300
+ login: (input: { email: string; password: string }) =>
5301
+ request<AuthResponse>("/auth/login", { method: "POST", body: JSON.stringify(input) }),
5302
+ me: () => request<User>("/auth/me"),
5303
+ listNotes: () => request<Note[]>("/notes"),
5304
+ createNote: (input: CreateNoteInput) =>
5305
+ request<Note>("/notes", { method: "POST", body: JSON.stringify(input) }),
5306
+ deleteNote: (id: string) => request<void>(\`/notes/\${id}\`, { method: "DELETE" }),
5307
+ };
5308
+ `;
5309
+ var frontendLoginPage = () => `"use client";
5310
+ import { useState } from "react";
5311
+ import { useRouter } from "next/navigation";
5312
+ import Link from "next/link";
5313
+ import { api, setToken } from "@/lib/api";
5314
+
5315
+ // how this works: posts to the backend /auth/login, stores the returned JWT, then
5316
+ // redirects to /account. Every request after this sends the token automatically.
5317
+ export default function LoginPage() {
5318
+ const router = useRouter();
5319
+ const [email, setEmail] = useState("");
5320
+ const [password, setPassword] = useState("");
5321
+ const [error, setError] = useState<string | null>(null);
5322
+ const [busy, setBusy] = useState(false);
5323
+
5324
+ async function onSubmit(e: React.FormEvent) {
5325
+ e.preventDefault();
5326
+ setBusy(true); setError(null);
5327
+ try {
5328
+ const { token } = await api.login({ email, password });
5329
+ setToken(token);
5330
+ router.push("/account");
5331
+ } catch (err) {
5332
+ setError(err instanceof Error ? err.message : "Something went wrong");
5333
+ } finally { setBusy(false); }
5334
+ }
5335
+
5336
+ return (
5337
+ <main className="mx-auto flex min-h-[70vh] max-w-sm flex-col justify-center px-6">
5338
+ <h1 className="text-2xl font-bold">Welcome back</h1>
5339
+ <p className="mt-1 text-muted">Sign in to your account.</p>
5340
+ <form onSubmit={onSubmit} className="mt-6 space-y-4">
5341
+ <input value={email} onChange={(e) => setEmail(e.target.value)} type="email" required placeholder="you@example.com" className="w-full rounded-xl border border-hairline bg-surface px-4 py-3 outline-none" />
5342
+ <input value={password} onChange={(e) => setPassword(e.target.value)} type="password" required placeholder="Password" className="w-full rounded-xl border border-hairline bg-surface px-4 py-3 outline-none" />
5343
+ {error && <p className="text-sm text-red-400">{error}</p>}
5344
+ <button disabled={busy} className="w-full rounded-full gradient-bg px-4 py-3 font-semibold on-accent transition hover:opacity-90 disabled:opacity-60">{busy ? "Signing in\u2026" : "Sign in"}</button>
5345
+ </form>
5346
+ <p className="mt-4 text-sm text-muted">No account? <Link href="/register" className="underline">Create one</Link></p>
5347
+ </main>
5348
+ );
5349
+ }
5350
+ `;
5351
+ var frontendRegisterPage = () => `"use client";
5352
+ import { useState } from "react";
5353
+ import { useRouter } from "next/navigation";
5354
+ import Link from "next/link";
5355
+ import { api, setToken } from "@/lib/api";
5356
+
5357
+ // how this works: posts to /auth/register, stores the JWT, redirects to /account.
5358
+ export default function RegisterPage() {
5359
+ const router = useRouter();
5360
+ const [name, setName] = useState("");
5361
+ const [email, setEmail] = useState("");
5362
+ const [password, setPassword] = useState("");
5363
+ const [error, setError] = useState<string | null>(null);
5364
+ const [busy, setBusy] = useState(false);
5365
+
5366
+ async function onSubmit(e: React.FormEvent) {
5367
+ e.preventDefault();
5368
+ setBusy(true); setError(null);
5369
+ try {
5370
+ const { token } = await api.register({ name, email, password });
5371
+ setToken(token);
5372
+ router.push("/account");
5373
+ } catch (err) {
5374
+ setError(err instanceof Error ? err.message : "Something went wrong");
5375
+ } finally { setBusy(false); }
5376
+ }
5377
+
5378
+ return (
5379
+ <main className="mx-auto flex min-h-[70vh] max-w-sm flex-col justify-center px-6">
5380
+ <h1 className="text-2xl font-bold">Create your account</h1>
5381
+ <p className="mt-1 text-muted">It takes a few seconds.</p>
5382
+ <form onSubmit={onSubmit} className="mt-6 space-y-4">
5383
+ <input value={name} onChange={(e) => setName(e.target.value)} required placeholder="Your name" className="w-full rounded-xl border border-hairline bg-surface px-4 py-3 outline-none" />
5384
+ <input value={email} onChange={(e) => setEmail(e.target.value)} type="email" required placeholder="you@example.com" className="w-full rounded-xl border border-hairline bg-surface px-4 py-3 outline-none" />
5385
+ <input value={password} onChange={(e) => setPassword(e.target.value)} type="password" required minLength={8} placeholder="Password (min 8 chars)" className="w-full rounded-xl border border-hairline bg-surface px-4 py-3 outline-none" />
5386
+ {error && <p className="text-sm text-red-400">{error}</p>}
5387
+ <button disabled={busy} className="w-full rounded-full gradient-bg px-4 py-3 font-semibold on-accent transition hover:opacity-90 disabled:opacity-60">{busy ? "Creating\u2026" : "Create account"}</button>
5388
+ </form>
5389
+ <p className="mt-4 text-sm text-muted">Already have one? <Link href="/login" className="underline">Sign in</Link></p>
5390
+ </main>
5391
+ );
5392
+ }
5393
+ `;
5394
+ var frontendAccountPage = (ctx) => `"use client";
5395
+ import { useEffect, useState } from "react";
5396
+ import { useRouter } from "next/navigation";
5397
+ import { api, getToken, setToken } from "@/lib/api";
5398
+ import type { User, Note } from "${scope(ctx)}/types";
5399
+
5400
+ // how this works: a PROTECTED page. On mount it calls /auth/me with the stored
5401
+ // token; if that fails it bounces to /login. Notes are the example CRUD resource.
5402
+ export default function AccountPage() {
5403
+ const router = useRouter();
5404
+ const [user, setUser] = useState<User | null>(null);
5405
+ const [notes, setNotes] = useState<Note[]>([]);
5406
+ const [title, setTitle] = useState("");
5407
+ const [body, setBody] = useState("");
5408
+ const [error, setError] = useState<string | null>(null);
5409
+
5410
+ useEffect(() => {
5411
+ if (!getToken()) { router.push("/login"); return; }
5412
+ (async () => {
5413
+ try {
5414
+ setUser(await api.me());
5415
+ setNotes(await api.listNotes());
5416
+ } catch { setToken(null); router.push("/login"); }
5417
+ })();
5418
+ }, [router]);
5419
+
5420
+ async function addNote(e: React.FormEvent) {
5421
+ e.preventDefault();
5422
+ setError(null);
5423
+ try {
5424
+ const note = await api.createNote({ title, body });
5425
+ setNotes((prev) => [note, ...prev]);
5426
+ setTitle(""); setBody("");
5427
+ } catch (err) { setError(err instanceof Error ? err.message : "Failed to save"); }
5428
+ }
5429
+ async function remove(id: string) {
5430
+ await api.deleteNote(id);
5431
+ setNotes((prev) => prev.filter((n) => n.id !== id));
5432
+ }
5433
+ function signOut() { setToken(null); router.push("/login"); }
5434
+
5435
+ if (!user) return <main className="mx-auto max-w-2xl px-6 py-16 text-muted">Loading\u2026</main>;
5436
+
5437
+ return (
5438
+ <main className="mx-auto max-w-2xl px-6 py-16">
5439
+ <div className="flex items-center justify-between">
5440
+ <div>
5441
+ <h1 className="text-2xl font-bold">Hi, {user.name}</h1>
5442
+ <p className="text-muted">{user.email}</p>
5443
+ </div>
5444
+ <button onClick={signOut} className="rounded-full border border-hairline px-4 py-2 text-sm transition hover:bg-surface">Sign out</button>
5445
+ </div>
5446
+
5447
+ <form onSubmit={addNote} className="mt-8 space-y-3 rounded-2xl border border-hairline bg-surface p-5">
5448
+ <h2 className="font-semibold">Add a note</h2>
5449
+ <input value={title} onChange={(e) => setTitle(e.target.value)} required placeholder="Title" className="w-full rounded-xl border border-hairline bg-app px-4 py-2 outline-none" />
5450
+ <textarea value={body} onChange={(e) => setBody(e.target.value)} placeholder="Write something\u2026" rows={3} className="w-full rounded-xl border border-hairline bg-app px-4 py-2 outline-none" />
5451
+ {error && <p className="text-sm text-red-400">{error}</p>}
5452
+ <button className="rounded-full gradient-bg px-4 py-2 text-sm font-semibold on-accent">Save note</button>
5453
+ </form>
5454
+
5455
+ <ul className="mt-6 space-y-3">
5456
+ {notes.length === 0 && <li className="text-muted">No notes yet \u2014 add your first above.</li>}
5457
+ {notes.map((n) => (
5458
+ <li key={n.id} className="flex items-start justify-between rounded-2xl border border-hairline p-4">
5459
+ <div>
5460
+ <p className="font-medium">{n.title}</p>
5461
+ {n.body && <p className="mt-1 text-sm text-muted">{n.body}</p>}
5462
+ </div>
5463
+ <button onClick={() => remove(n.id)} className="shrink-0 text-sm text-muted transition hover:text-red-400">Delete</button>
5464
+ </li>
5465
+ ))}
5466
+ </ul>
5467
+ </main>
5468
+ );
5469
+ }
5470
+ `;
5471
+ function buildFullStack(ctx) {
5472
+ const out = {};
5473
+ const s = scope(ctx);
5474
+ const app = buildApp(ctx);
5475
+ for (const [rel, content] of Object.entries(app)) out[`frontend/${rel}`] = content;
5476
+ const fpkg = JSON.parse(out["frontend/package.json"]);
5477
+ fpkg.name = `${s}/frontend`;
5478
+ fpkg.dependencies[`${s}/types`] = "*";
5479
+ out["frontend/package.json"] = JSON.stringify(fpkg, null, 2) + "\n";
5480
+ const fts = JSON.parse(out["frontend/tsconfig.json"]);
5481
+ fts.compilerOptions.paths[`${s}/types`] = ["../types/index.d.ts"];
5482
+ out["frontend/tsconfig.json"] = JSON.stringify(fts, null, 2) + "\n";
5483
+ const fenv = out["frontend/.env.example"] ?? "";
5484
+ out["frontend/.env.example"] = (fenv.endsWith("\n") || fenv === "" ? fenv : fenv + "\n") + "\n# The backend API base URL. Unset = http://localhost:4000 (local default).\n# NEXT_PUBLIC_API_URL=http://localhost:4000\n";
5485
+ out["frontend/lib/api.ts"] = frontendApiClient(ctx);
5486
+ out["frontend/app/login/page.tsx"] = frontendLoginPage();
5487
+ out["frontend/app/register/page.tsx"] = frontendRegisterPage();
5488
+ out["frontend/app/account/page.tsx"] = frontendAccountPage(ctx);
5489
+ Object.assign(out, backendFiles(ctx));
5490
+ out["types/package.json"] = typesPkgJson(ctx);
5491
+ out["types/index.d.ts"] = sharedTypes();
5492
+ out["package.json"] = rootPkgJson(ctx);
5493
+ out["docker-compose.yml"] = dockerCompose(ctx);
5494
+ out[".gitignore"] = rootGitignore();
5495
+ out[".env.example"] = rootEnvExample(ctx);
5496
+ out["README.md"] = rootReadme(ctx);
5497
+ return out;
5498
+ }
5499
+ var backendPkgJson = (ctx) => JSON.stringify({
5500
+ name: `${scope(ctx)}/backend`,
5501
+ version: "0.1.0",
5502
+ private: true,
5503
+ type: "module",
5504
+ main: "dist/index.js",
5505
+ scripts: {
5506
+ dev: "tsx watch src/index.ts",
5507
+ build: "tsc -p tsconfig.json",
5508
+ start: "node dist/index.js",
5509
+ typecheck: "tsc -p tsconfig.json --noEmit"
5510
+ },
5511
+ dependencies: {
5512
+ express: "^4.21.2",
5513
+ cors: "^2.8.5",
5514
+ mongoose: "^8.9.0",
5515
+ ioredis: "^5.4.2",
5516
+ dotenv: "^16.4.7",
5517
+ // ✨ Backend built on zero-dep @lacspace/* packages instead of the usual grab-bag.
5518
+ "@lacspace/env": "^1.1.0",
5519
+ "@lacspace/jwt": "^1.4.0",
5520
+ "@lacspace/password": "^1.1.0",
5521
+ "@lacspace/validate": "^1.1.0",
5522
+ "@lacspace/id": "^1.1.0",
5523
+ "@lacspace/rate-limit": "^1.2.0",
5524
+ "@lacspace/cache": "^1.1.0",
5525
+ [`${scope(ctx)}/types`]: "*"
5526
+ },
5527
+ devDependencies: {
5528
+ typescript: "^5.7.0",
5529
+ tsx: "^4.19.2",
5530
+ "@types/node": "^22.10.0",
5531
+ "@types/express": "^4.17.21",
5532
+ "@types/cors": "^2.8.17"
5533
+ }
5534
+ }, null, 2) + "\n";
5535
+ var backendTsconfig = (ctx) => JSON.stringify({
5536
+ compilerOptions: {
5537
+ target: "ES2022",
5538
+ module: "NodeNext",
5539
+ moduleResolution: "NodeNext",
5540
+ lib: ["ES2022"],
5541
+ esModuleInterop: true,
5542
+ allowSyntheticDefaultImports: true,
5543
+ strict: true,
5544
+ skipLibCheck: true,
5545
+ resolveJsonModule: true,
5546
+ outDir: "dist",
5547
+ rootDir: "src",
5548
+ sourceMap: true,
5549
+ types: ["node"],
5550
+ baseUrl: ".",
5551
+ paths: { [`${scope(ctx)}/types`]: ["../types/index.d.ts"] }
5552
+ },
5553
+ include: ["src/**/*"],
5554
+ exclude: ["node_modules", "dist"]
5555
+ }, null, 2) + "\n";
5556
+ var backendGitignore = () => `node_modules
5557
+ dist
5558
+ .env
5559
+ *.log
5560
+ `;
5561
+ var backendReadme = (ctx) => `# ${ctx.name} \u2014 API
5562
+
5563
+ Node \xB7 Express \xB7 MongoDB \xB7 Redis (optional) \xB7 TypeScript. Built on zero-dependency \`@lacspace/*\` packages.
5564
+
5565
+ Run it from the repo root with \`npm run dev\` (starts this API + the frontend). Standalone: \`npm run dev\` inside this folder.
5566
+
5567
+ ## Endpoints
5568
+
5569
+ | Method | Path | Auth | Description |
5570
+ |--------|------------------|------|--------------------------------|
5571
+ | GET | \`/health\` | \u2014 | Liveness check |
5572
+ | POST | \`/auth/register\` | \u2014 | Create an account \u2192 JWT + user |
5573
+ | POST | \`/auth/login\` | \u2014 | Log in \u2192 JWT + user |
5574
+ | GET | \`/auth/me\` | \u2713 | The current user |
5575
+ | GET | \`/notes\` | \u2713 | List your notes (cached) |
5576
+ | POST | \`/notes\` | \u2713 | Create a note |
5577
+ | GET | \`/notes/:id\` | \u2713 | Read one note |
5578
+ | PATCH | \`/notes/:id\` | \u2713 | Update a note |
5579
+ | DELETE | \`/notes/:id\` | \u2713 | Delete a note |
5580
+
5581
+ Send \`Authorization: Bearer <token>\` for the \u2713 routes (you get the token from register/login).
5582
+
5583
+ ## Layout
5584
+
5585
+ \`\`\`
5586
+ src/
5587
+ \u251C\u2500 index.ts boot: load env \u2192 connect Mongo \u2192 listen
5588
+ \u251C\u2500 load-env.ts loads the root .env (imported first)
5589
+ \u251C\u2500 env.ts typed, validated env (@lacspace/env)
5590
+ \u251C\u2500 app.ts the Express app (CORS, routes, error handler)
5591
+ \u251C\u2500 db.ts Mongoose connection
5592
+ \u251C\u2500 cache.ts Redis, or an in-memory fallback (@lacspace/cache)
5593
+ \u251C\u2500 http.ts HttpError + asyncHandler
5594
+ \u251C\u2500 validation.ts request schemas (@lacspace/validate)
5595
+ \u251C\u2500 middleware/ auth (@lacspace/jwt) + error handling
5596
+ \u251C\u2500 models/ Mongoose models (User, Note)
5597
+ \u2514\u2500 routes/ auth + notes (the example CRUD resource)
5598
+ \`\`\`
5599
+ `;
5600
+ var backendLoadEnv = () => `import { config } from "dotenv";
5601
+ import { resolve } from "node:path";
5602
+
5603
+ // how this works: the whole monorepo shares ONE .env at the repo root. When this
5604
+ // API runs via \`npm run dev\` its working directory is backend/, so the root .env
5605
+ // is one level up. This module is imported FIRST (before env.ts) so the variables
5606
+ // exist by the time anything reads them.
5607
+ config({ path: resolve(process.cwd(), "../.env") });
5608
+ config(); // also load backend/.env if you keep one (root values already set win)
5609
+ `;
5610
+ var backendEnv = (ctx) => `import { createEnv, str, port, oneOf } from "@lacspace/env";
5611
+
5612
+ // how this works: fail-fast, TYPED environment variables (@lacspace/env). Bad or
5613
+ // missing values throw at boot with a clear message. Sensible dev defaults mean it
5614
+ // runs with zero config against a local MongoDB; set real values in the root .env.
5615
+ export const env = createEnv({
5616
+ NODE_ENV: oneOf(["development", "production", "test"], { default: "development" }),
5617
+ PORT: port({ default: 4000 }),
5618
+ MONGODB_URI: str({ default: "mongodb://localhost:27017/${ctx.name}" }),
5619
+ JWT_SECRET: str({ default: "dev-secret-change-me" }),
5620
+ REDIS_URL: str({ optional: true }),
5621
+ CORS_ORIGIN: str({ default: "http://localhost:3000" }),
5622
+ });
5623
+
5624
+ if (env.NODE_ENV === "production" && env.JWT_SECRET === "dev-secret-change-me") {
5625
+ throw new Error("Set a strong JWT_SECRET in production (see .env.example).");
5626
+ }
5627
+ `;
5628
+ var backendIndex = (ctx) => `import "./load-env.js"; // MUST be first: fills process.env before anything reads it
5629
+ import { env } from "./env.js";
5630
+ import { connectDb } from "./db.js";
5631
+ import { createApp } from "./app.js";
5632
+
5633
+ // how this works: connect to MongoDB, build the Express app, then listen.
5634
+ async function main(): Promise<void> {
5635
+ await connectDb(env.MONGODB_URI);
5636
+ const app = createApp();
5637
+ app.listen(env.PORT, () => {
5638
+ console.log(\`\u{1F680} ${ctx.name} API ready on http://localhost:\${env.PORT}\`);
5639
+ });
5640
+ }
5641
+
5642
+ main().catch((err) => {
5643
+ console.error("Failed to start the API:", err);
5644
+ process.exit(1);
5645
+ });
5646
+ `;
5647
+ var backendDb = () => `import mongoose from "mongoose";
5648
+
5649
+ // how this works: opens the Mongoose connection. Call once at boot.
5650
+ export async function connectDb(uri: string): Promise<void> {
5651
+ mongoose.set("strictQuery", true);
5652
+ await mongoose.connect(uri);
5653
+ console.log("\u2714 MongoDB connected");
5654
+ }
5655
+ `;
5656
+ var backendCache = () => `import { createCache } from "@lacspace/cache";
5657
+ import { Redis } from "ioredis";
5658
+ import { env } from "./env.js";
5659
+
5660
+ // how this works: one cache interface, TWO backends. If REDIS_URL is set we use
5661
+ // Redis; otherwise we fall back to @lacspace/cache (zero-dep, in-memory) so the app
5662
+ // runs with NO Redis at all. The rest of the code doesn't care which is active.
5663
+ export interface Cache {
5664
+ get(key: string): Promise<string | null>;
5665
+ set(key: string, value: string, ttlSeconds?: number): Promise<void>;
5666
+ del(key: string): Promise<void>;
5667
+ readonly kind: "redis" | "memory";
5668
+ }
5669
+
5670
+ function redisCache(url: string): Cache {
5671
+ const client = new Redis(url, { maxRetriesPerRequest: 2 });
5672
+ client.on("error", (e: Error) => console.warn("\u26A0 Redis error:", e.message));
5673
+ return {
5674
+ kind: "redis",
5675
+ async get(key) { return client.get(key); },
5676
+ async set(key, value, ttl) { if (ttl) await client.set(key, value, "EX", ttl); else await client.set(key, value); },
5677
+ async del(key) { await client.del(key); },
5678
+ };
5679
+ }
5680
+
5681
+ function memoryCache(): Cache {
5682
+ const mem = createCache<string>({ max: 5000 });
5683
+ return {
5684
+ kind: "memory",
5685
+ async get(key) { return mem.get(key) ?? null; },
5686
+ async set(key, value, ttl) { mem.set(key, value, ttl ? ttl * 1000 : undefined); },
5687
+ async del(key) { mem.delete(key); },
5688
+ };
5689
+ }
5690
+
5691
+ export const cache: Cache = env.REDIS_URL ? redisCache(env.REDIS_URL) : memoryCache();
5692
+ console.log(\`\u2714 Cache: \${cache.kind}\${cache.kind === "memory" ? " (no REDIS_URL \u2014 in-memory fallback)" : ""}\`);
5693
+ `;
5694
+ var backendHttp = () => `import type { Request, Response, NextFunction, RequestHandler } from "express";
5695
+
5696
+ /** A simple HTTP error with a status code \u2014 throw it from any handler. */
5697
+ export class HttpError extends Error {
5698
+ status: number;
5699
+ constructor(status: number, message: string) {
5700
+ super(message);
5701
+ this.status = status;
5702
+ this.name = "HttpError";
5703
+ }
5704
+ }
5705
+
5706
+ // how this works: Express v4 doesn't catch rejected Promises from async handlers,
5707
+ // so wrap them \u2014 any thrown error is forwarded to the error middleware.
5708
+ export const asyncHandler =
5709
+ (fn: (req: Request, res: Response, next: NextFunction) => Promise<unknown>): RequestHandler =>
5710
+ (req, res, next) => { fn(req, res, next).catch(next); };
5711
+ `;
5712
+ var backendExpressTypes = () => `// Adds req.user (populated by requireAuth) to Express's Request type.
5713
+ import "express";
5714
+
5715
+ declare global {
5716
+ namespace Express {
5717
+ interface Request {
5718
+ user?: { sub: string; email: string; iat?: number; exp?: number; iss?: string };
5719
+ }
5720
+ }
5721
+ }
5722
+
5723
+ export {};
5724
+ `;
5725
+ var backendErrorMw = () => `import type { Request, Response, NextFunction } from "express";
5726
+ import { ValidationError } from "@lacspace/validate";
5727
+ import { HttpError } from "../http.js";
5728
+
5729
+ // how this works: ONE place that turns thrown errors into clean JSON responses.
5730
+ // Register it LAST (after all routes). Express identifies it by its 4 arguments.
5731
+ export function errorHandler(err: unknown, _req: Request, res: Response, _next: NextFunction): void {
5732
+ if (err instanceof ValidationError) {
5733
+ res.status(400).json({ error: "Validation failed", fields: err.flatten() });
5734
+ return;
5735
+ }
5736
+ if (err instanceof HttpError) {
5737
+ res.status(err.status).json({ error: err.message });
5738
+ return;
5739
+ }
5740
+ console.error(err);
5741
+ res.status(500).json({ error: "Internal server error" });
5742
+ }
5743
+ `;
5744
+ var backendAuthMw = (ctx) => `import type { RequestHandler } from "express";
5745
+ import { expressJwt } from "@lacspace/jwt";
5746
+ import { env } from "../env.js";
5747
+
5748
+ // how this works: verifies the "Authorization: Bearer <token>" header with
5749
+ // @lacspace/jwt and attaches the decoded payload to req.user (see express.d.ts).
5750
+ // Missing/invalid token \u2192 it responds 401 automatically. Put it on any route you
5751
+ // want protected: router.get("/secret", requireAuth, handler)
5752
+ // (@lacspace/jwt's middleware is framework-agnostic, so we cast it to Express's
5753
+ // RequestHandler \u2014 it's a standard (req, res, next) function underneath.)
5754
+ export const requireAuth = expressJwt(env.JWT_SECRET, { issuer: "${ctx.name}-api" }) as unknown as RequestHandler;
5755
+ `;
5756
+ var backendUserModel = () => `import mongoose from "mongoose";
5757
+ import { uuidv7 } from "@lacspace/id";
5758
+
5759
+ // how this works: the User fields. _id is a time-sortable UUID (@lacspace/id)
5760
+ // instead of an ObjectId, so ids are readable and orderable. We store only a
5761
+ // password HASH, never the raw password. (We DON'T extend mongoose.Document \u2014 that
5762
+ // would force _id to be an ObjectId; a plain interface lets _id be our string.)
5763
+ export interface UserDoc {
5764
+ _id: string;
5765
+ email: string;
5766
+ name: string;
5767
+ passwordHash: string;
5768
+ createdAt: Date;
5769
+ updatedAt: Date;
5770
+ }
5771
+
5772
+ const userSchema = new mongoose.Schema<UserDoc>(
5773
+ {
5774
+ _id: { type: String, default: () => uuidv7() },
5775
+ email: { type: String, required: true, unique: true, lowercase: true, trim: true },
5776
+ name: { type: String, required: true, trim: true },
5777
+ passwordHash: { type: String, required: true },
5778
+ },
5779
+ { timestamps: true },
5780
+ );
5781
+
5782
+ export const User =
5783
+ (mongoose.models.User as mongoose.Model<UserDoc>) ?? mongoose.model<UserDoc>("User", userSchema);
5784
+ `;
5785
+ var backendNoteModel = () => `import mongoose from "mongoose";
5786
+ import { uuidv7 } from "@lacspace/id";
5787
+
5788
+ // how this works: the example CRUD resource. Rename "Note" to your real domain
5789
+ // object (Task, Post, Product\u2026) and add fields \u2014 the routes follow the same shape.
5790
+ // (Plain interface, not mongoose.Document, so _id can be our string UUID.)
5791
+ export interface NoteDoc {
5792
+ _id: string;
5793
+ title: string;
5794
+ body: string;
5795
+ userId: string;
5796
+ createdAt: Date;
5797
+ updatedAt: Date;
5798
+ }
5799
+
5800
+ const noteSchema = new mongoose.Schema<NoteDoc>(
5801
+ {
5802
+ _id: { type: String, default: () => uuidv7() },
5803
+ title: { type: String, required: true, trim: true },
5804
+ body: { type: String, default: "" },
5805
+ userId: { type: String, required: true, index: true },
5806
+ },
5807
+ { timestamps: true },
5808
+ );
5809
+
5810
+ export const Note =
5811
+ (mongoose.models.Note as mongoose.Model<NoteDoc>) ?? mongoose.model<NoteDoc>("Note", noteSchema);
5812
+ `;
5813
+ var backendValidation = () => `import { v, type Infer } from "@lacspace/validate";
5814
+
5815
+ // how this works: Zod-like schemas (@lacspace/validate). .parse(body) throws a
5816
+ // ValidationError on bad input, which the error middleware turns into a clean 400
5817
+ // with per-field messages.
5818
+ export const RegisterInput = v.object({
5819
+ name: v.string().min(2).max(80),
5820
+ email: v.string().email(),
5821
+ password: v.string().min(8).max(200),
5822
+ });
5823
+
5824
+ export const LoginInput = v.object({
5825
+ email: v.string().email(),
5826
+ password: v.string().min(1),
5827
+ });
5828
+
5829
+ export const NoteInput = v.object({
5830
+ title: v.string().min(1).max(200),
5831
+ body: v.string().max(10_000).default(""),
5832
+ });
5833
+
5834
+ export type RegisterBody = Infer<typeof RegisterInput>;
5835
+ export type LoginBody = Infer<typeof LoginInput>;
5836
+ export type NoteBody = Infer<typeof NoteInput>;
5837
+ `;
5838
+ var backendAuthRoutes = (ctx) => `import express from "express";
5839
+ import { hash, verify as verifyPassword } from "@lacspace/password";
5840
+ import { sign } from "@lacspace/jwt";
5841
+ import { asyncHandler, HttpError } from "../http.js";
5842
+ import { requireAuth } from "../middleware/auth.js";
5843
+ import { User, type UserDoc } from "../models/user.js";
5844
+ import { env } from "../env.js";
5845
+ import { RegisterInput, LoginInput } from "../validation.js";
5846
+ import type { AuthResponse, User as UserDTO } from "${scope(ctx)}/types";
5847
+
5848
+ const ISSUER = "${ctx.name}-api";
5849
+ const WEEK = 60 * 60 * 24 * 7; // token lifetime, in seconds
5850
+ const router = express.Router();
5851
+
5852
+ function toDTO(u: UserDoc): UserDTO {
5853
+ return { id: String(u._id), email: u.email, name: u.name, createdAt: u.createdAt.toISOString() };
5854
+ }
5855
+ function tokenFor(u: UserDoc): Promise<string> {
5856
+ return sign({ sub: String(u._id), email: u.email }, env.JWT_SECRET, { expiresIn: WEEK, issuer: ISSUER });
5857
+ }
5858
+
5859
+ // POST /auth/register \u2014 create an account, return a JWT + the user.
5860
+ router.post("/register", asyncHandler(async (req, res) => {
5861
+ const { name, email, password } = RegisterInput.parse(req.body);
5862
+ if (await User.findOne({ email })) throw new HttpError(409, "That email is already registered");
5863
+ const passwordHash = await hash(password); // PBKDF2 via @lacspace/password
5864
+ const user = await User.create({ name, email, passwordHash });
5865
+ const out: AuthResponse = { token: await tokenFor(user), user: toDTO(user) };
5866
+ res.status(201).json(out);
5867
+ }));
5868
+
5869
+ // POST /auth/login \u2014 verify credentials, return a JWT + the user.
5870
+ router.post("/login", asyncHandler(async (req, res) => {
5871
+ const { email, password } = LoginInput.parse(req.body);
5872
+ const user = await User.findOne({ email });
5873
+ if (!user || !(await verifyPassword(password, user.passwordHash))) {
5874
+ throw new HttpError(401, "Invalid email or password");
5875
+ }
5876
+ const out: AuthResponse = { token: await tokenFor(user), user: toDTO(user) };
5877
+ res.json(out);
5878
+ }));
5879
+
5880
+ // GET /auth/me \u2014 the current user (requires a valid token).
5881
+ router.get("/me", requireAuth, asyncHandler(async (req, res) => {
5882
+ const user = await User.findById(req.user!.sub);
5883
+ if (!user) throw new HttpError(404, "User not found");
5884
+ res.json(toDTO(user));
5885
+ }));
5886
+
5887
+ export default router;
5888
+ `;
5889
+ var backendNoteRoutes = (ctx) => `import express from "express";
5890
+ import { asyncHandler, HttpError } from "../http.js";
5891
+ import { requireAuth } from "../middleware/auth.js";
5892
+ import { Note, type NoteDoc } from "../models/note.js";
5893
+ import { cache } from "../cache.js";
5894
+ import { NoteInput } from "../validation.js";
5895
+ import type { Note as NoteDTO } from "${scope(ctx)}/types";
5896
+
5897
+ const router = express.Router();
5898
+ router.use(requireAuth); // every /notes route requires a valid token
5899
+
5900
+ function toDTO(n: NoteDoc): NoteDTO {
5901
+ return {
5902
+ id: String(n._id),
5903
+ title: n.title,
5904
+ body: n.body,
5905
+ userId: String(n.userId),
5906
+ createdAt: n.createdAt.toISOString(),
5907
+ updatedAt: n.updatedAt.toISOString(),
5908
+ };
5909
+ }
5910
+ const listKey = (userId: string): string => \`notes:\${userId}\`;
5911
+
5912
+ // GET /notes \u2014 this user's notes. Cached for 30s (Redis or in-memory); every write
5913
+ // below busts the cache, so reads are fast but never stale after a change.
5914
+ router.get("/", asyncHandler(async (req, res) => {
5915
+ const userId = req.user!.sub;
5916
+ const cached = await cache.get(listKey(userId));
5917
+ if (cached) { res.json(JSON.parse(cached) as NoteDTO[]); return; }
5918
+ const notes = await Note.find({ userId }).sort({ createdAt: -1 });
5919
+ const dto = notes.map(toDTO);
5920
+ await cache.set(listKey(userId), JSON.stringify(dto), 30);
5921
+ res.json(dto);
5922
+ }));
5923
+
5924
+ // POST /notes \u2014 create a note.
5925
+ router.post("/", asyncHandler(async (req, res) => {
5926
+ const userId = req.user!.sub;
5927
+ const { title, body } = NoteInput.parse(req.body);
5928
+ const note = await Note.create({ title, body, userId });
5929
+ await cache.del(listKey(userId));
5930
+ res.status(201).json(toDTO(note));
5931
+ }));
5932
+
5933
+ // GET /notes/:id \u2014 one note (only if it's yours).
5934
+ router.get("/:id", asyncHandler(async (req, res) => {
5935
+ const note = await Note.findOne({ _id: req.params.id, userId: req.user!.sub });
5936
+ if (!note) throw new HttpError(404, "Note not found");
5937
+ res.json(toDTO(note));
5938
+ }));
5939
+
5940
+ // PATCH /notes/:id \u2014 update a note.
5941
+ router.patch("/:id", asyncHandler(async (req, res) => {
5942
+ const patch = NoteInput.partial().parse(req.body);
5943
+ const note = await Note.findOneAndUpdate({ _id: req.params.id, userId: req.user!.sub }, { $set: patch }, { new: true });
5944
+ if (!note) throw new HttpError(404, "Note not found");
5945
+ await cache.del(listKey(req.user!.sub));
5946
+ res.json(toDTO(note));
5947
+ }));
5948
+
5949
+ // DELETE /notes/:id \u2014 delete a note.
5950
+ router.delete("/:id", asyncHandler(async (req, res) => {
5951
+ const note = await Note.findOneAndDelete({ _id: req.params.id, userId: req.user!.sub });
5952
+ if (!note) throw new HttpError(404, "Note not found");
5953
+ await cache.del(listKey(req.user!.sub));
5954
+ res.status(204).end();
5955
+ }));
5956
+
5957
+ export default router;
5958
+ `;
5959
+ var backendApp = (ctx) => `import express from "express";
5960
+ import type { RequestHandler } from "express";
5961
+ import cors from "cors";
5962
+ import { rateLimit, expressRateLimit } from "@lacspace/rate-limit";
5963
+ import { env } from "./env.js";
5964
+ import { errorHandler } from "./middleware/error.js";
5965
+ import authRoutes from "./routes/auth.js";
5966
+ import noteRoutes from "./routes/notes.js";
5967
+
5968
+ // how this works: assembles the Express app \u2014 CORS for the frontend, JSON parsing,
5969
+ // a health check, the auth + notes routers, then the error handler LAST.
5970
+ export function createApp(): express.Express {
5971
+ const app = express();
5972
+
5973
+ app.use(cors({ origin: env.CORS_ORIGIN.split(",").map((o) => o.trim()), credentials: true }));
5974
+ app.use(express.json());
5975
+
5976
+ // Brute-force protection on auth: 20 requests / minute / IP (@lacspace/rate-limit).
5977
+ const authLimiter = expressRateLimit(rateLimit({ limit: 20, windowMs: 60_000 })) as unknown as RequestHandler;
5978
+
5979
+ app.get("/health", (_req, res) => { res.json({ ok: true, service: "${ctx.name}-api" }); });
5980
+ app.use("/auth", authLimiter, authRoutes);
5981
+ app.use("/notes", noteRoutes);
5982
+
5983
+ app.use(errorHandler);
5984
+ return app;
5985
+ }
5986
+ `;
5987
+ function backendFiles(ctx) {
5988
+ return {
5989
+ "backend/package.json": backendPkgJson(ctx),
5990
+ "backend/tsconfig.json": backendTsconfig(ctx),
5991
+ "backend/.gitignore": backendGitignore(),
5992
+ "backend/README.md": backendReadme(ctx),
5993
+ "backend/src/index.ts": backendIndex(ctx),
5994
+ "backend/src/load-env.ts": backendLoadEnv(),
5995
+ "backend/src/env.ts": backendEnv(ctx),
5996
+ "backend/src/db.ts": backendDb(),
5997
+ "backend/src/cache.ts": backendCache(),
5998
+ "backend/src/app.ts": backendApp(ctx),
5999
+ "backend/src/http.ts": backendHttp(),
6000
+ "backend/src/express.d.ts": backendExpressTypes(),
6001
+ "backend/src/validation.ts": backendValidation(),
6002
+ "backend/src/middleware/auth.ts": backendAuthMw(ctx),
6003
+ "backend/src/middleware/error.ts": backendErrorMw(),
6004
+ "backend/src/models/user.ts": backendUserModel(),
6005
+ "backend/src/models/note.ts": backendNoteModel(),
6006
+ "backend/src/routes/auth.ts": backendAuthRoutes(ctx),
6007
+ "backend/src/routes/notes.ts": backendNoteRoutes(ctx)
6008
+ };
6009
+ }
6010
+ var splitList = (s) => s.split(",").map((x) => x.trim()).filter(Boolean);
4555
6011
  function parseArgs(list) {
4556
- const a = { yes: false, install: true, git: true, pm: "npm", help: false };
6012
+ const a = { features: [], yes: false, install: true, git: true, pm: "npm", help: false };
4557
6013
  for (let i = 0; i < list.length; i++) {
4558
6014
  const arg = list[i];
4559
6015
  const next = () => list[++i] ?? "";
@@ -4563,10 +6019,21 @@ function parseArgs(list) {
4563
6019
  else if (arg === "--no-git") a.git = false;
4564
6020
  else if (arg === "--pm") a.pm = next();
4565
6021
  else if (arg === "--theme" || arg === "--accent") a.theme = next();
4566
- else if (arg === "-h" || arg === "--help") a.help = true;
6022
+ else if (arg === "--with" || arg === "--features") a.features.push(...splitList(next()));
6023
+ else if (arg === "--fullstack" || arg === "--full-stack" || arg === "--dynamic") a.mode = "dynamic";
6024
+ else if (arg === "--static") a.mode = "static";
6025
+ else if (arg === "--mode") {
6026
+ const m = next().toLowerCase();
6027
+ a.mode = m === "dynamic" ? "dynamic" : "static";
6028
+ } else if (arg.startsWith("--mode=")) {
6029
+ const m = arg.slice(7).toLowerCase();
6030
+ a.mode = m === "dynamic" ? "dynamic" : "static";
6031
+ } else if (arg === "-h" || arg === "--help") a.help = true;
4567
6032
  else if (arg.startsWith("--template=")) a.template = arg.slice(11);
4568
6033
  else if (arg.startsWith("--theme=")) a.theme = arg.slice(8);
4569
6034
  else if (arg.startsWith("--accent=")) a.theme = arg.slice(9);
6035
+ else if (arg.startsWith("--with=")) a.features.push(...splitList(arg.slice(7)));
6036
+ else if (arg.startsWith("--features=")) a.features.push(...splitList(arg.slice(11)));
4570
6037
  else if (!arg.startsWith("-") && !a.name) a.name = arg;
4571
6038
  }
4572
6039
  return a;
@@ -4661,6 +6128,10 @@ ${TEMPLATES.map((t) => ` ${t.key.padEnd(10)} ${t.description}`).join("\n")}
4661
6128
 
4662
6129
  ${c("bold", "Options")}
4663
6130
  -t, --template <key> Template (${TEMPLATES.map((t) => t.key).join(" | ")})
6131
+ --fullstack Full-stack monorepo: Next.js frontend + Node/Express/
6132
+ MongoDB/Redis backend (JWT auth + CRUD) + shared types
6133
+ ${c("dim", "(alias --dynamic; default is --static, a single Next.js app)")}
6134
+ --with <a,b> Feature add-ons, comma-separated (alias --features)
4664
6135
  --theme <name|hex> Accent: a preset, a "#hex", or "from,to" (e.g. --theme lacspace)
4665
6136
  --pm <npm|pnpm|yarn|bun> Package manager (default npm)
4666
6137
  --no-install Skip installing dependencies
@@ -4668,13 +6139,18 @@ ${c("bold", "Options")}
4668
6139
  -y, --yes Accept defaults (needs <name>)
4669
6140
  -h, --help Show this help
4670
6141
 
6142
+ ${c("bold", "Feature add-ons")} ${c("dim", "(--with) \u2014 free & keyless, local by default")}
6143
+ ${FEATURES.map((f) => ` ${f.key.padEnd(10)} ${f.description}`).join("\n")}
6144
+ ${c("dim", "e.g. npx create-lacspace-app my-app --template saas --with ai-chat,rag")}
6145
+
4671
6146
  ${c("bold", "Themes")} ${c("dim", "(--theme)")}
4672
6147
  ${Object.keys(THEMES).join(" \xB7 ")}
4673
6148
  ${c("dim", 'or a custom colour: --theme "#ff6a00" \xB7 --theme "#0bb9d9,#7c3aed"')}
4674
6149
 
4675
- ${c("bold", "Add sections to an existing app")}
4676
- npx create-lacspace-app add pricing faq testimonials
4677
- ${c("dim", "Drops prebuilt, themed sections into components/sections/ (and the UI kit if missing).")}
6150
+ ${c("bold", "Grow an existing app")}
6151
+ npx create-lacspace-app add pricing faq testimonials ${c("dim", "# prebuilt sections")}
6152
+ npx create-lacspace-app add ai-chat ${c("dim", "# a feature add-on")}
6153
+ ${c("dim", "Drops themed sections / feature files into your project (and the UI kit if missing).")}
4678
6154
  `;
4679
6155
  var SECTIONS = {
4680
6156
  hero: `import Link from "next/link";
@@ -4914,7 +6390,7 @@ function ensureUiKit(root) {
4914
6390
  var pascal = (s) => s.split(/[-_]/).map((p) => p.charAt(0).toUpperCase() + p.slice(1)).join("");
4915
6391
  function runAdd(rawNames) {
4916
6392
  stdout.write(`
4917
- ${c("bold", c("magenta", "\u25C6 create-lacspace-app add"))} ${c("dim", "\u2014 drop prebuilt sections into your app")}
6393
+ ${c("bold", c("magenta", "\u25C6 create-lacspace-app add"))} ${c("dim", "\u2014 drop prebuilt sections or a feature into your app")}
4918
6394
 
4919
6395
  `);
4920
6396
  const root = cwd();
@@ -4925,56 +6401,108 @@ ${c("bold", c("magenta", "\u25C6 create-lacspace-app add"))} ${c("dim", "\u2014
4925
6401
  }
4926
6402
  const wanted = rawNames.filter((n) => !n.startsWith("-")).map((n) => n.toLowerCase());
4927
6403
  if (wanted.length === 0 || rawNames.includes("--help") || rawNames.includes("-h")) {
4928
- stdout.write(`Usage: ${c("cyan", "npx create-lacspace-app add <section...>")}
6404
+ stdout.write(`Usage: ${c("cyan", "npx create-lacspace-app add <section|feature...>")}
4929
6405
 
4930
6406
  ${c("bold", "Available sections")}
4931
6407
  `);
4932
6408
  stdout.write(" " + Object.keys(SECTIONS).map((k) => c("cyan", k)).join(" ") + "\n");
4933
6409
  stdout.write(`
4934
- Example: ${c("cyan", "npx create-lacspace-app add pricing faq testimonials")}
6410
+ ${c("bold", "Available features")}
6411
+ `);
6412
+ stdout.write(" " + FEATURES.map((f) => c("cyan", f.key)).join(" ") + "\n");
6413
+ stdout.write(`
6414
+ Example: ${c("cyan", "npx create-lacspace-app add pricing faq")} ${c("dim", "or")} ${c("cyan", "add ai-chat")}
4935
6415
 
4936
6416
  `);
4937
6417
  return;
4938
6418
  }
4939
- const unknown = wanted.filter((n) => !(n in SECTIONS));
6419
+ const featKeys = wanted.filter((n) => FEATURES.some((f) => f.key === n));
6420
+ const sectionNames = wanted.filter((n) => n in SECTIONS);
6421
+ const unknown = wanted.filter((n) => !featKeys.includes(n) && !(n in SECTIONS));
4940
6422
  if (unknown.length) stdout.write(c("yellow", `! Unknown: ${unknown.join(", ")} ${c("dim", "(run with no args to list)")}
4941
6423
  `));
4942
- const toAdd = wanted.filter((n) => n in SECTIONS);
4943
- if (toAdd.length === 0) {
4944
- exit(1);
4945
- return;
4946
- }
4947
- const kitAdded = ensureUiKit(root);
4948
- if (kitAdded.length) stdout.write(` ${c("green", "\u2714")} Added the UI kit ${c("dim", "(" + kitAdded.length + " components)")}
6424
+ const addedFeatures = featKeys.map((k) => FEATURES.find((f) => f.key === k));
6425
+ if (addedFeatures.length) {
6426
+ const ctx = resolveContext({ name: basename(root), features: featKeys });
6427
+ for (const feat of addedFeatures) {
6428
+ stdout.write(`
6429
+ ${c("bold", `+ ${feat.label}`)} ${c("dim", `(${feat.key})`)}
4949
6430
  `);
4950
- const created = [];
4951
- for (const name of toAdd) {
4952
- const rel = `components/sections/${name}.tsx`;
4953
- const full = join(root, rel);
4954
- if (existsSync(full)) {
4955
- stdout.write(c("yellow", ` ~ ${rel} exists \u2014 skipped
6431
+ for (const [rel, content] of Object.entries(feat.files(ctx))) {
6432
+ const full = join(root, rel);
6433
+ if (existsSync(full)) {
6434
+ stdout.write(c("yellow", ` ~ ${rel} exists \u2014 skipped
4956
6435
  `));
4957
- continue;
4958
- }
4959
- mkdirSync(dirname(full), { recursive: true });
4960
- writeFileSync(full, SECTIONS[name]);
4961
- created.push(name);
4962
- stdout.write(` ${c("green", "\u2714")} ${c("dim", "+ " + rel)}
6436
+ continue;
6437
+ }
6438
+ mkdirSync(dirname(full), { recursive: true });
6439
+ writeFileSync(full, content);
6440
+ stdout.write(` ${c("green", "\u2714")} ${c("dim", "+ " + rel)}
6441
+ `);
6442
+ }
6443
+ stdout.write(`
6444
+ ${c("bold", "Add these dependencies")}:
6445
+ ${c("cyan", "npm i " + Object.entries(feat.deps).map(([n, v]) => `${n}@${v}`).join(" "))}
4963
6446
  `);
6447
+ if (feat.scripts && Object.keys(feat.scripts).length) {
6448
+ stdout.write(`
6449
+ ${c("bold", "Add to package.json scripts")}:
6450
+ `);
6451
+ for (const [n, v] of Object.entries(feat.scripts)) stdout.write(` ${c("cyan", `"${n}": "${v}"`)}
6452
+ `);
6453
+ }
6454
+ if (feat.env && Object.keys(feat.env).length) {
6455
+ stdout.write(`
6456
+ ${c("bold", "Add to .env")}:
6457
+ `);
6458
+ for (const [n, comment] of Object.entries(feat.env)) stdout.write(` ${c("cyan", n + "=")} ${c("dim", "# " + comment)}
6459
+ `);
6460
+ }
6461
+ stdout.write(`
6462
+ ${c("bold", "Next steps")}:
6463
+ `);
6464
+ for (const s of feat.nextSteps) stdout.write(` ${c("dim", "\u2022")} ${s}
6465
+ `);
6466
+ }
6467
+ stdout.write("\n");
4964
6468
  }
4965
- if (created.length) {
4966
- stdout.write(`
6469
+ if (sectionNames.length) {
6470
+ const kitAdded = ensureUiKit(root);
6471
+ if (kitAdded.length) stdout.write(` ${c("green", "\u2714")} Added the UI kit ${c("dim", "(" + kitAdded.length + " components)")}
6472
+ `);
6473
+ const created = [];
6474
+ for (const name of sectionNames) {
6475
+ const rel = `components/sections/${name}.tsx`;
6476
+ const full = join(root, rel);
6477
+ if (existsSync(full)) {
6478
+ stdout.write(c("yellow", ` ~ ${rel} exists \u2014 skipped
6479
+ `));
6480
+ continue;
6481
+ }
6482
+ mkdirSync(dirname(full), { recursive: true });
6483
+ writeFileSync(full, SECTIONS[name]);
6484
+ created.push(name);
6485
+ stdout.write(` ${c("green", "\u2714")} ${c("dim", "+ " + rel)}
6486
+ `);
6487
+ }
6488
+ if (created.length) {
6489
+ stdout.write(`
4967
6490
  ${c("bold", "Use them")} \u2014 import into any page:
4968
6491
  `);
4969
- for (const n of created) stdout.write(` ${c("cyan", `import { ${pascal(n)}Section } from "@/components/sections/${n}";`)}
6492
+ for (const n of created) stdout.write(` ${c("cyan", `import { ${pascal(n)}Section } from "@/components/sections/${n}";`)}
4970
6493
  `);
4971
- stdout.write(`
6494
+ stdout.write(`
4972
6495
  Then drop ${c("cyan", "<" + pascal(created[0]) + "Section />")} into your JSX.
4973
6496
  `);
4974
- stdout.write(`
6497
+ stdout.write(`
4975
6498
  ${c("dim", "Sections use the @lacspace UI kit + design tokens \u2014 best inside a create-lacspace-app project.")}
4976
6499
 
4977
6500
  `);
6501
+ }
6502
+ }
6503
+ if (!addedFeatures.length && !sectionNames.length) {
6504
+ exit(1);
6505
+ return;
4978
6506
  }
4979
6507
  }
4980
6508
  async function main() {
@@ -4994,7 +6522,9 @@ ${c("bold", c("magenta", "\u25C6 create-lacspace-app"))} ${c("dim", "\u2014 a go
4994
6522
  `);
4995
6523
  let name = args.name;
4996
6524
  let templateKey = args.template;
4997
- if (!args.yes) {
6525
+ let mode = args.mode ?? "static";
6526
+ const featureKeys = [...args.features];
6527
+ if (!args.yes && stdin.isTTY) {
4998
6528
  const rl = createInterface({ input: stdin, output: stdout });
4999
6529
  try {
5000
6530
  if (!name) name = (await rl.question(`${c("green", "?")} Project name ${c("dim", "(my-app)")}: `)).trim() || "my-app";
@@ -5009,6 +6539,34 @@ ${c("green", "?")} Template ${c("dim", "(1)")}: `)).trim() || "1";
5009
6539
  const idx = /^\d+$/.test(ans) ? parseInt(ans, 10) - 1 : TEMPLATES.findIndex((t) => t.key === ans);
5010
6540
  templateKey = TEMPLATES[idx]?.key ?? "personal";
5011
6541
  }
6542
+ if (args.mode === void 0) {
6543
+ stdout.write(`
6544
+ What kind of app?
6545
+ `);
6546
+ stdout.write(` ${c("cyan", "1")}. ${c("bold", "Static / frontend only")} ${c("dim", "\u2014 a single Next.js app (SEO site, marketing, blog, docs). Fast, deploy anywhere.")}
6547
+ `);
6548
+ stdout.write(` ${c("cyan", "2")}. ${c("bold", "Dynamic / full-stack")} ${c("dim", "\u2014 frontend + a Node\xB7Express\xB7MongoDB\xB7Redis API with working auth & CRUD, wired together.")}
6549
+ `);
6550
+ const ans = (await rl.question(`
6551
+ ${c("green", "?")} Type ${c("dim", "(1)")}: `)).trim() || "1";
6552
+ mode = ans === "2" || ans.toLowerCase().startsWith("dyn") || ans.toLowerCase().startsWith("full") ? "dynamic" : "static";
6553
+ }
6554
+ if (featureKeys.length === 0) {
6555
+ stdout.write(`
6556
+ Add feature add-ons? ${c("dim", "(free & keyless \u2014 local AI by default)")}
6557
+ `);
6558
+ FEATURES.forEach((f, i) => stdout.write(` ${c("cyan", String(i + 1))}. ${c("bold", f.label)} ${c("dim", "\u2014 " + f.description)}
6559
+ `));
6560
+ const ans = (await rl.question(`
6561
+ ${c("green", "?")} Add features? ${c("dim", "(comma-separated numbers, or Enter for none)")}: `)).trim();
6562
+ if (ans) {
6563
+ for (const tok of splitList(ans)) {
6564
+ const idx = /^\d+$/.test(tok) ? parseInt(tok, 10) - 1 : FEATURES.findIndex((f) => f.key === tok);
6565
+ const feat = FEATURES[idx];
6566
+ if (feat && !featureKeys.includes(feat.key)) featureKeys.push(feat.key);
6567
+ }
6568
+ }
6569
+ }
5012
6570
  } finally {
5013
6571
  rl.close();
5014
6572
  }
@@ -5033,14 +6591,18 @@ ${c("green", "?")} Template ${c("dim", "(1)")}: `)).trim() || "1";
5033
6591
  exit(1);
5034
6592
  return;
5035
6593
  }
5036
- const files = buildFiles({ name: projectName, template });
6594
+ const features = normalizeFeatures(featureKeys);
6595
+ const files = buildFiles({ name: projectName, template, features, mode });
5037
6596
  for (const [rel, content] of Object.entries(files)) {
5038
6597
  const full = join(dir, rel);
5039
6598
  mkdirSync(dirname(full), { recursive: true });
5040
6599
  writeFileSync(full, content);
5041
6600
  }
6601
+ const shape = mode === "dynamic" ? " \xB7 full-stack" : "";
5042
6602
  stdout.write(`
5043
- ${c("green", "\u2714")} Created ${c("bold", name)} ${c("dim", `(${template.label})`)}
6603
+ ${c("green", "\u2714")} Created ${c("bold", name)} ${c("dim", `(${template.label}${shape})`)}
6604
+ `);
6605
+ if (features.length) stdout.write(` ${c("green", "\u2714")} Feature add-ons: ${features.map((f) => c("cyan", f.key)).join(", ")}
5044
6606
  `);
5045
6607
  for (const rel of Object.keys(files)) stdout.write(` ${c("dim", "+ " + rel)}
5046
6608
  `);
@@ -5068,11 +6630,40 @@ ${c("bold", "Done! Next steps")}
5068
6630
  `);
5069
6631
  if (!args.install) stdout.write(` ${c("cyan", `${args.pm} install`)}
5070
6632
  `);
5071
- stdout.write(` ${c("cyan", run)}
6633
+ if (mode === "dynamic") {
6634
+ stdout.write(` ${c("cyan", "cp .env.example .env")} ${c("dim", "\u2014 then, optionally:")} ${c("cyan", "docker compose up -d")} ${c("dim", "(Mongo + Redis)")}
5072
6635
  `);
5073
- stdout.write(`
6636
+ stdout.write(` ${c("cyan", run)} ${c("dim", "\u2014 runs the API (:4000) and the frontend (:3000) together")}
6637
+ `);
6638
+ stdout.write(`
6639
+ ${c("dim", "backend \u2192")} ${c("cyan", "backend/src/")} ${c("dim", "(Express \xB7 MongoDB \xB7 Redis \xB7 JWT auth \xB7 example CRUD)")}
6640
+ `);
6641
+ stdout.write(` ${c("dim", "frontend \u2192")} ${c("cyan", "frontend/app/")} ${c("dim", "\xB7 shared API types \u2192")} ${c("cyan", "types/src/")}
6642
+ `);
6643
+ stdout.write(` ${c("dim", "No Docker? Point")} ${c("cyan", "MONGODB_URI")} ${c("dim", "at any MongoDB (e.g. free Atlas); Redis is optional.")}
6644
+ `);
6645
+ } else {
6646
+ stdout.write(` ${c("cyan", run)}
6647
+ `);
6648
+ stdout.write(`
5074
6649
  Edit ${c("cyan", "lib/site.ts")} (your SEO config) and ${c("cyan", "app/page.tsx")}.
5075
6650
  `);
6651
+ }
6652
+ if (features.length) {
6653
+ const hasAi = features.some((f) => f.key === "ai-chat" || f.key === "rag");
6654
+ stdout.write(`
6655
+ ${c("bold", "Your feature add-ons")} ${c("dim", "\u2014 details in LEARN.md")}
6656
+ `);
6657
+ if (hasAi) stdout.write(` ${c("green", "\u{1F193} Free & local AI")} ${c("dim", "\u2014 install Ollama (https://ollama.com); no API key required.")}
6658
+ `);
6659
+ for (const f of features) {
6660
+ stdout.write(`
6661
+ ${c("bold", f.label)} ${c("dim", `(${f.key})`)}
6662
+ `);
6663
+ for (const s of f.nextSteps) stdout.write(` ${c("dim", "\u2022")} ${s}
6664
+ `);
6665
+ }
6666
+ }
5076
6667
  stdout.write(`
5077
6668
  ${c("green", "Happy building!")} ${c("dim", "https://lacspace.com/packages")}
5078
6669
 
@@ -5089,4 +6680,4 @@ if (invokedAsCli) {
5089
6680
  });
5090
6681
  }
5091
6682
 
5092
- export { SECTIONS, TEMPLATES, buildFiles, resolveContext };
6683
+ export { FEATURES, SECTIONS, TEMPLATES, applyFeatures, buildFiles, normalizeFeatures, resolveContext };