create-acrylblends 0.2.2 → 0.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +12 -1
  2. package/dist/index.d.ts +16 -1
  3. package/dist/index.js +301 -12
  4. package/dist/index.js.map +1 -1
  5. package/docs/framework/README.md +4 -3
  6. package/docs/framework/UPSTREAM.md +1 -1
  7. package/docs/framework/getting-started/aws-lambda.md +115 -0
  8. package/docs/framework/getting-started/bun.md +1 -3
  9. package/docs/framework/getting-started/cloudflare-pages.md +53 -0
  10. package/docs/framework/getting-started/cloudflare-workers.md +67 -0
  11. package/docs/framework/getting-started/lambda-edge.md +41 -0
  12. package/docs/framework/getting-started/netlify.md +25 -0
  13. package/docs/framework/getting-started/other-runtimes.md +20 -9
  14. package/docs/framework/getting-started/service-worker.md +31 -0
  15. package/docs/framework/getting-started/vercel.md +28 -0
  16. package/docs/framework/guides/client-modules.md +34 -0
  17. package/docs/framework/guides/create-acrylblends.md +40 -2
  18. package/docs/framework/guides/faq.md +2 -2
  19. package/docs/framework/helpers/conninfo.md +1 -1
  20. package/docs/framework/helpers/ssg.md +1 -1
  21. package/docs/framework/helpers/streaming.md +120 -0
  22. package/docs/framework/helpers/websocket.md +2 -2
  23. package/docs/framework/middleware/builtin/ip-restriction.md +1 -1
  24. package/docs/framework/upstream.json +3 -3
  25. package/package.json +3 -2
  26. package/templates/chat/gitignore +5 -0
  27. package/templates/chat/package.json +23 -0
  28. package/templates/chat/src/app.ts +6 -0
  29. package/templates/chat/src/chat-app.ts +96 -0
  30. package/templates/chat/src/client/chat.tsx +115 -0
  31. package/templates/chat/src/client/tsconfig.json +15 -0
  32. package/templates/chat/src/db.ts +59 -0
  33. package/templates/chat/src/index.ts +22 -0
  34. package/templates/chat/src/llm.ts +42 -0
  35. package/templates/chat/src/page.tsx +38 -0
  36. package/templates/chat/test/chat.test.ts +153 -0
  37. package/templates/chat/test/server.test.ts +59 -0
  38. package/templates/chat/tsconfig.json +19 -0
package/README.md CHANGED
@@ -15,6 +15,7 @@ It asks which template you want, creates `my-app`, and prints what to run next.
15
15
  | `nodejs` | an Acryl app served with `serve()` from `acrylblends/node-server`, with a test; run with Node.js 22.19 or newer |
16
16
  | `bun` (experimental) | the same app for Bun, with `export default app` |
17
17
  | `notes` | a full-stack starter: accounts (scrypt, cookie session), notes in SQLite (`node:sqlite`), validated forms, search, a JSON API with a typed test client, csrf on, a test for every route |
18
+ | `chat` | an AI chat starter: the answer streams token by token (Server-Sent Events) from an OpenAI-compatible API (DeepSeek by default, key only from `DEEPSEEK_API_KEY`), a client component with a Stop button that also stops the request to the model, history in SQLite, tests with a mock model |
18
19
  | `acryl-app` | a Cordis app built from plugins, with an agent that can extend it while it runs (the same app `npx acrylblends init --template agent` creates) |
19
20
 
20
21
  Every template includes `AGENTS.md`, `CLAUDE.md` and a copy of the framework documentation in `docs/framework/`, so a coding agent working in the folder reads the API from the folder.
@@ -29,7 +30,7 @@ npm create acrylblends@latest my-app -- --template nodejs --install --pm npm
29
30
 
30
31
  | Option | |
31
32
  | --- | --- |
32
- | `--template <name>` | `nodejs`, `notes`, `bun` or `acryl-app` |
33
+ | `--template <name>` | `nodejs`, `notes`, `chat`, `bun` or `acryl-app` |
33
34
  | `--install` | install the dependencies after creating the app |
34
35
  | `--pm <manager>` | `npm`, `pnpm`, `yarn` or `bun` (default: the one that ran the command) |
35
36
  | `-y`, `--yes` | ask nothing: template `nodejs`, directory `acrylblends-app` unless given |
@@ -73,3 +74,13 @@ MIT license.
73
74
  - a live character counter and an instant filter written as a small script in the page. When the client components of `acrylblends/jsx/dom` can be served without a bundler (planned for 0.7.2), they will replace that script here.
74
75
 
75
76
  `npx acrylblends add desktop` followed by `npm install` and `npm run desktop` runs it as a desktop window (see `docs/framework/getting-started/desktop.md`).
77
+
78
+ ## Templates from a repository or a package
79
+
80
+ ```sh
81
+ npm create acrylblends@latest my-app github:owner/repo[#ref]
82
+ npm create acrylblends@latest my-app @scope/name[@version]
83
+ npm create acrylblends@latest my-app ./template.tgz
84
+ ```
85
+
86
+ The source is downloaded as a tarball (never cloned) or packed with `npm pack --ignore-scripts`, unpacked, and read: it must hold an `acryl.template.json` (`name`, `description`, optional `plugins`), it is checked for secrets, and only then is the folder created. Nothing of the template is installed or run; if its `package.json` defines install scripts they are listed, and `--install` prints what will run before it runs. See the create-acrylblends guide in `docs/framework/guides/`.
package/dist/index.d.ts CHANGED
@@ -6,9 +6,20 @@
6
6
  export declare const PACKAGE = "acrylblends";
7
7
  export declare const CLASS = "Acryl";
8
8
  export declare const CREATE = "create-acrylblends";
9
+ /** The file that makes a folder a template other people can create apps from (`${CREATE} <name> github:owner/repo`). */
10
+ export declare const TEMPLATE_MANIFEST = "acryl.template.json";
11
+ //#endregion
12
+ //#region src/source.d.ts
13
+ /** How the bytes of a source are obtained; real by default, replaced in tests. */
14
+ interface Fetchers {
15
+ /** The body at a URL (a GitHub tarball). */
16
+ download(url: string): Promise<Uint8Array>;
17
+ /** `npm pack <spec> --ignore-scripts` into `dest`; the path of the tarball. */
18
+ pack(spec: string, dest: string): string;
19
+ }
9
20
  //#endregion
10
21
  //#region src/index.d.ts
11
- export declare const TEMPLATES: readonly ["nodejs", "notes", "bun", "acryl-app"];
22
+ export declare const TEMPLATES: readonly ["nodejs", "notes", "chat", "bun", "acryl-app"];
12
23
  export type Template = (typeof TEMPLATES)[number];
13
24
  export declare const PACKAGE_MANAGERS: readonly ["npm", "pnpm", "yarn", "bun"];
14
25
  export type PackageManager = (typeof PACKAGE_MANAGERS)[number];
@@ -32,6 +43,8 @@ export interface Io {
32
43
  ask: ((question: string) => Promise<string>) | undefined;
33
44
  /** Run a program, showing its output; resolves to the exit code. */
34
45
  run(command: string, args: string[], cwd: string): Promise<number>;
46
+ /** How a template source is fetched; the real network and npm by default. */
47
+ fetchers?: Fetchers;
35
48
  }
36
49
  export declare function processIo(): Io;
37
50
  export interface CreateOptions {
@@ -40,6 +53,8 @@ export interface CreateOptions {
40
53
  install: boolean;
41
54
  pm: PackageManager | undefined;
42
55
  yes: boolean;
56
+ /** `github:owner/repo[#ref]`, `@scope/name` or a packed `.tgz`: a template from outside this package. */
57
+ source: string | undefined;
43
58
  }
44
59
  export declare function isTemplate(value: string): value is Template;
45
60
  export declare function parseCreateOptions(argv: readonly string[]): CreateOptions;
package/dist/index.js CHANGED
@@ -1,10 +1,12 @@
1
1
  import { createRequire } from "node:module";
2
- import { spawn } from "node:child_process";
3
- import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
2
+ import { spawn, spawnSync } from "node:child_process";
3
+ import { cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
4
5
  import { basename, dirname, join, resolve } from "node:path";
5
6
  import { createInterface } from "node:readline/promises";
6
7
  import { fileURLToPath } from "node:url";
7
8
  import { parseArgs } from "node:util";
9
+ import { findSecrets } from "@webboxes/app-persistence";
8
10
  //#region src/names.ts
9
11
  /**
10
12
  * The one place this package names the framework. The templates are written with `__PACKAGE__` and `__RANGE__` (the range is stamped at create time from the framework version this package carries, see `frameworkRange`), and the text of `AGENTS.md` with
@@ -13,6 +15,195 @@ import { parseArgs } from "node:util";
13
15
  const PACKAGE = "acrylblends";
14
16
  const CLASS = "Acryl";
15
17
  const CREATE = "create-acrylblends";
18
+ /** The file that makes a folder a template other people can create apps from (`${CREATE} <name> github:owner/repo`). */
19
+ const TEMPLATE_MANIFEST = "acryl.template.json";
20
+ //#endregion
21
+ //#region src/source.ts
22
+ /**
23
+ * Templates from outside this package: `github:owner/repo[#ref]`, a scoped npm package (`@scope/name[@version]`) or a packed tarball on disk.
24
+ * A source is only ever downloaded and unpacked: no git clone (hooks), no lifecycle script (`npm pack --ignore-scripts`), nothing of it is run.
25
+ */
26
+ /** A source that cannot be used; the message says why and is shown as it is. */
27
+ var SourceError = class extends Error {
28
+ name = "SourceError";
29
+ };
30
+ const SOURCE_FORMS = `github:owner/repo[#ref], @scope/name[@version], or a packed .tgz file`;
31
+ const LIMITS = {
32
+ files: 5e3,
33
+ bytes: 52428800
34
+ };
35
+ /** Recognise a source argument, or return `undefined` when it is not one (so the caller can report a usage error). */
36
+ function parseSource(text, cwd) {
37
+ const github = /^github:([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)(?:#([A-Za-z0-9_./-]+))?$/.exec(text);
38
+ if (github) return {
39
+ kind: "github",
40
+ owner: github[1],
41
+ repo: github[2],
42
+ ref: github[3]
43
+ };
44
+ if (text.startsWith("github:")) throw new SourceError(`"${text}" is not github:owner/repo[#ref]`);
45
+ if (/^@[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*(@[A-Za-z0-9._-]+)?$/.test(text)) return {
46
+ kind: "npm",
47
+ spec: text
48
+ };
49
+ if (text.startsWith("@")) throw new SourceError(`"${text}" is not @scope/name[@version]`);
50
+ if (/\.(tgz|tar\.gz)$/.test(text)) {
51
+ const path = resolve(cwd, text);
52
+ if (!existsSync(path)) throw new SourceError(`${path} does not exist`);
53
+ return {
54
+ kind: "tarball",
55
+ path
56
+ };
57
+ }
58
+ }
59
+ const realFetchers = {
60
+ async download(url) {
61
+ const response = await fetch(url, { redirect: "follow" });
62
+ if (!response.ok) throw new SourceError(`${url} answered ${response.status}`);
63
+ return new Uint8Array(await response.arrayBuffer());
64
+ },
65
+ pack(spec, dest) {
66
+ const result = spawnSync("npm", [
67
+ "pack",
68
+ spec,
69
+ "--ignore-scripts",
70
+ "--json",
71
+ "--pack-destination",
72
+ dest
73
+ ], {
74
+ encoding: "utf8",
75
+ shell: false,
76
+ env: {
77
+ ...process.env,
78
+ npm_config_ignore_scripts: "true"
79
+ }
80
+ });
81
+ if (result.status !== 0) throw new SourceError(`npm could not pack ${spec}: ${(result.stderr || result.stdout).trim().split("\n").at(-1)}`);
82
+ const file = JSON.parse(result.stdout)[0]?.filename;
83
+ if (!file) throw new SourceError(`npm packed nothing for ${spec}`);
84
+ return join(dest, file);
85
+ }
86
+ };
87
+ /** Unpack a tarball into `dir`, dropping its single top folder; refuses links, paths that leave the folder, and archives that are too big. */
88
+ function extract(tarball, dir) {
89
+ const list = spawnSync("tar", ["-tzf", tarball], {
90
+ encoding: "utf8",
91
+ maxBuffer: 67108864
92
+ });
93
+ if (list.status !== 0) throw new SourceError(`${tarball} is not a readable tar.gz archive`);
94
+ const entries = list.stdout.split("\n").filter(Boolean);
95
+ if (entries.length > LIMITS.files) throw new SourceError(`the template has more than ${LIMITS.files} files`);
96
+ for (const entry of entries) if (entry.startsWith("/") || entry.split("/").includes("..")) throw new SourceError(`the archive holds a path that leaves its folder: ${entry}`);
97
+ mkdirSync(dir, { recursive: true });
98
+ const run = spawnSync("tar", [
99
+ "-xzf",
100
+ tarball,
101
+ "-C",
102
+ dir,
103
+ "--strip-components=1"
104
+ ], { encoding: "utf8" });
105
+ if (run.status !== 0) throw new SourceError(`could not unpack ${tarball}: ${run.stderr.trim()}`);
106
+ let bytes = 0;
107
+ const walk = (folder) => {
108
+ for (const entry of readdirSync(folder)) {
109
+ const path = join(folder, entry);
110
+ const info = lstatSync(path);
111
+ if (info.isSymbolicLink()) throw new SourceError(`the template holds a symbolic link (${path.slice(dir.length + 1)}); links are not allowed`);
112
+ if (info.isDirectory()) walk(path);
113
+ else bytes += info.size;
114
+ }
115
+ };
116
+ walk(dir);
117
+ if (bytes > LIMITS.bytes) throw new SourceError(`the template is larger than ${LIMITS.bytes / 1024 / 1024} MB`);
118
+ }
119
+ /** Download or pack a source and unpack it into `dir` (which must not exist yet). Nothing in it is run. */
120
+ async function fetchSource(source, dir, scratch, fetchers) {
121
+ mkdirSync(scratch, { recursive: true });
122
+ let tarball;
123
+ if (source.kind === "tarball") tarball = source.path;
124
+ else if (source.kind === "npm") tarball = fetchers.pack(source.spec, scratch);
125
+ else {
126
+ tarball = join(scratch, "source.tar.gz");
127
+ writeFileSync(tarball, await fetchers.download(`https://codeload.github.com/${source.owner}/${source.repo}/tar.gz/${source.ref ?? "HEAD"}`));
128
+ }
129
+ extract(tarball, dir);
130
+ }
131
+ /** Read and check `acryl.template.json`; a source without it is not a template. */
132
+ function readManifest(dir) {
133
+ const file = join(dir, TEMPLATE_MANIFEST);
134
+ if (!existsSync(file)) throw new SourceError(`this source has no ${TEMPLATE_MANIFEST}, so it is not a template: add one with a name and a description (see the create-acrylblends guide)`);
135
+ let data;
136
+ try {
137
+ data = JSON.parse(readFileSync(file, "utf8"));
138
+ } catch {
139
+ throw new SourceError(`${TEMPLATE_MANIFEST} is not valid JSON`);
140
+ }
141
+ const m = data;
142
+ if (typeof m.name !== "string" || m.name.trim() === "") throw new SourceError(`${TEMPLATE_MANIFEST} needs a "name"`);
143
+ if (typeof m.description !== "string") throw new SourceError(`${TEMPLATE_MANIFEST} needs a "description"`);
144
+ const plugins = m.plugins ?? [];
145
+ if (!Array.isArray(plugins) || plugins.some((p) => typeof p !== "string" || !/^[a-z][a-z0-9-]*$/.test(p))) throw new SourceError(`"plugins" in ${TEMPLATE_MANIFEST} is a list of plugin names such as "desktop"`);
146
+ return {
147
+ name: m.name,
148
+ description: m.description,
149
+ plugins
150
+ };
151
+ }
152
+ const SKIP = /* @__PURE__ */ new Set([
153
+ ".git",
154
+ "node_modules",
155
+ TEMPLATE_MANIFEST
156
+ ]);
157
+ /** Lifecycle scripts npm runs on `npm install` in the app's own folder. */
158
+ const LIFECYCLE = [
159
+ "preinstall",
160
+ "install",
161
+ "postinstall",
162
+ "prepublish",
163
+ "preprepare",
164
+ "prepare",
165
+ "postprepare"
166
+ ];
167
+ const isText = (buffer) => !buffer.subarray(0, 8e3).includes(0);
168
+ /**
169
+ * Copy the unpacked template into `target`, replacing the placeholders of the built-in templates, naming the app, and pointing a dependency on the framework at
170
+ * the release this package carries. Returns the files written (relative paths) and the lifecycle scripts the app's package.json defines.
171
+ */
172
+ function writeTemplate(from, target, stamp, range, name) {
173
+ const files = [];
174
+ const walk = (src, dst, prefix) => {
175
+ mkdirSync(dst, { recursive: true });
176
+ for (const entry of readdirSync(src, { withFileTypes: true })) {
177
+ if (SKIP.has(entry.name)) continue;
178
+ const outName = prefix === "" && entry.name === "gitignore" ? ".gitignore" : entry.name;
179
+ if (entry.isDirectory()) walk(join(src, entry.name), join(dst, outName), `${prefix}${entry.name}/`);
180
+ else {
181
+ const buffer = readFileSync(join(src, entry.name));
182
+ writeFileSync(join(dst, outName), isText(buffer) ? stamp(buffer.toString("utf8")) : buffer);
183
+ files.push(`${prefix}${outName}`);
184
+ }
185
+ }
186
+ };
187
+ walk(from, target, "");
188
+ const lifecycle = {};
189
+ const pkgFile = join(target, "package.json");
190
+ if (existsSync(pkgFile)) {
191
+ const pkg = JSON.parse(readFileSync(pkgFile, "utf8"));
192
+ pkg.name = name;
193
+ for (const group of [pkg.dependencies, pkg.devDependencies]) if (group?.["acrylblends"] !== void 0) group[PACKAGE] = range;
194
+ writeFileSync(pkgFile, `${JSON.stringify(pkg, null, 2)}\n`);
195
+ for (const script of LIFECYCLE) if (typeof pkg.scripts?.[script] === "string") lifecycle[script] = pkg.scripts[script];
196
+ }
197
+ return {
198
+ files,
199
+ lifecycle
200
+ };
201
+ }
202
+ /** Remove a folder tree quietly. */
203
+ const removeTree = (path) => rmSync(path, {
204
+ recursive: true,
205
+ force: true
206
+ });
16
207
  //#endregion
17
208
  //#region src/spawn.ts
18
209
  /**
@@ -49,6 +240,7 @@ function packageManagerInvocation(command, args, platform = process.platform, en
49
240
  const TEMPLATES = [
50
241
  "nodejs",
51
242
  "notes",
243
+ "chat",
52
244
  "bun",
53
245
  "acryl-app"
54
246
  ];
@@ -63,11 +255,17 @@ const VERSION = createRequire(import.meta.url)("../package.json").version;
63
255
  const HELP = `${CREATE} ${VERSION} - create an ${CLASS} app
64
256
 
65
257
  Usage:
66
- npm create ${PACKAGE}@latest [directory] [-- options]
258
+ npm create ${PACKAGE}@latest [directory] [source] [-- options]
259
+
260
+ A source makes the app from someone else's template (it is downloaded and unpacked, nothing in it runs):
261
+ github:owner/repo[#ref] a GitHub repository, as a tarball (no clone)
262
+ @scope/name[@version] an npm package (npm pack --ignore-scripts)
263
+ ./template.tgz a packed template on disk
264
+ A template is a folder with an ${TEMPLATE_MANIFEST} (name, description, plugins).
67
265
 
68
266
  Options:
69
- --template <name> nodejs, notes, bun (experimental), acryl-app (asked when not given)
70
- --install install the dependencies after creating the app
267
+ --template <name> nodejs, notes, chat, bun (experimental), acryl-app (asked when not given)
268
+ --install install the dependencies after creating the app (the lifecycle scripts it will run are listed first)
71
269
  --pm <manager> ${PACKAGE_MANAGERS.join(", ")} (default: the one that ran this command, else npm)
72
270
  -y, --yes ask nothing: template nodejs unless --template is given, directory ${PACKAGE}-app
73
271
  -h, --help show this help
@@ -117,7 +315,8 @@ function parseCreateOptions(argv) {
117
315
  throw new UsageError(error.message);
118
316
  }
119
317
  const { values, positionals } = parsed;
120
- if (positionals.length > 1) throw new UsageError("takes at most one directory");
318
+ if (positionals.length > 2) throw new UsageError("takes a directory and at most one template source");
319
+ if (positionals[1] !== void 0 && values.template !== void 0) throw new UsageError("give a template source or --template, not both");
121
320
  if (values.template !== void 0 && !isTemplate(values.template)) throw new UsageError(`unknown template "${values.template}" (${TEMPLATES.join(", ")})`);
122
321
  if (values.pm !== void 0 && !PACKAGE_MANAGERS.includes(values.pm)) throw new UsageError(`unknown package manager "${values.pm}" (${PACKAGE_MANAGERS.join(", ")})`);
123
322
  return {
@@ -125,7 +324,8 @@ function parseCreateOptions(argv) {
125
324
  template: values.template,
126
325
  install: values.install === true,
127
326
  pm: values.pm,
128
- yes: values.yes === true
327
+ yes: values.yes === true,
328
+ source: positionals[1]
129
329
  };
130
330
  }
131
331
  const parse = (argv) => parseArgs({
@@ -177,12 +377,14 @@ function agentsText(template, name) {
177
377
  const run = {
178
378
  nodejs: "npm run dev",
179
379
  notes: "npm run dev",
380
+ chat: "npm run dev",
180
381
  bun: "bun run dev"
181
382
  }[template];
182
- const desktopNote = template === "nodejs" || template === "notes" ? `\nTo run it as a desktop window: \`npx ${PACKAGE} add desktop\`, \`npm install\`, then \`npm run desktop\` (see \`docs/framework/getting-started/desktop.md\`).` : "";
383
+ const desktopNote = template === "nodejs" || template === "notes" || template === "chat" ? `\nTo run it as a desktop window: \`npx ${PACKAGE} add desktop\`, \`npm install\`, then \`npm run desktop\` (see \`docs/framework/getting-started/desktop.md\`).` : "";
183
384
  const test = {
184
385
  nodejs: "npm test` and `npm run check",
185
386
  notes: "npm test` and `npm run check",
387
+ chat: "npm test` and `npm run check",
186
388
  bun: "bun test` and `bun run check"
187
389
  }[template];
188
390
  return `# ${name}
@@ -196,7 +398,7 @@ subpath (\`'${PACKAGE}/cors'\`, \`'${PACKAGE}/validator'\`, ...). Parts marked "
196
398
 
197
399
  ## This app
198
400
 
199
- Run it with \`${run}\`. The routes are in \`${template === "bun" ? "src/index.ts" : template === "notes" ? "src/notes-app.ts" : "src/app.ts"}\`; an app is a function from \`Request\` to \`Response\`,
401
+ Run it with \`${run}\`. The routes are in \`${template === "bun" ? "src/index.ts" : template === "notes" ? "src/notes-app.ts" : template === "chat" ? "src/chat-app.ts" : "src/app.ts"}\`; an app is a function from \`Request\` to \`Response\`,
200
402
  so test a route with \`await app.request('/path')\` and no server.${desktopNote}
201
403
 
202
404
  ${template === "notes" ? `
@@ -221,6 +423,19 @@ Read \`docs/framework/getting-started/deploy.md\`. In short:
221
423
  - Put the SQLite file outside the code folder (\`NOTES_DB=/var/lib/notes/notes.db\`) and back it up.
222
424
  - Behind an HTTPS reverse proxy set \`TRUST_PROXY=1\` and \`PUBLIC_ORIGIN=https://your.site\`, or the cookie is not \`Secure\` and csrf refuses form posts.
223
425
  - \`npm test\` includes a test that starts the server and stops it with SIGTERM; keep it passing if you change \`src/index.ts\`.
426
+ ` : ""}${template === "chat" ? `
427
+ ## Structure (a chat app: a streamed answer, history in a database)
428
+
429
+ - \`src/llm.ts\`: \`Llm\`, what the app needs from a model (messages in, pieces out, an aborted signal stops the work), and \`openAiCompatible\`, which calls an OpenAI-compatible chat completions API with \`stream: true\`. The base URL is \`DEEPSEEK_BASE_URL\` (default \`https://api.deepseek.com\`), the model \`DEEPSEEK_MODEL\` (default \`deepseek-chat\`), the key **only** the environment variable \`DEEPSEEK_API_KEY\`, read at the moment of the call: never write it to a file, a response or a log.
430
+ - \`src/db.ts\`: \`openDb()\` (SQLite through \`node:sqlite\`; the file is \`chat.db\` or \`$CHAT_DB\`) and \`chatStore(db)\`. The routes only call \`chatStore\`; keep SQL out of them.
431
+ - \`src/chat-app.ts\`: \`createApp(db, llm)\`. \`POST /api/chat\` answers Server-Sent Events: \`meta\` (the conversation id), a \`token\` per piece, then \`done\` or \`error\`. The request's signal (\`c.req.raw.signal\`) goes to the model call, so a closed tab or the Stop button stops the request to the model; what had arrived is kept.
432
+ - \`src/client/chat.tsx\`: the client component (own \`tsconfig.json\`, browser types): sends the message with \`fetch\`, reads the events as they arrive, shows the answer growing, and aborts on Stop. \`clientModules\` compiles it when the browser asks; \`npm run build\` compiles it once into \`dist/client\`. See \`docs/framework/guides/client-modules.md\`.
433
+ - \`test/chat.test.ts\` tests every route with a mock \`Llm\` (never the network); keep it that way. \`test/server.test.ts\` starts the real server and stops it with a signal.
434
+ - To try it with a real model: \`DEEPSEEK_API_KEY=... npm run dev\`.
435
+
436
+ ## Before you ship
437
+
438
+ Read \`docs/framework/getting-started/deploy.md\`. In short: \`npm ci --omit=dev\`, \`npm run build\`, \`NODE_ENV=production npm start\`; the app listens on \`127.0.0.1\` (\`HOST=0.0.0.0\` only in a container); the SQLite file goes outside the code folder (\`CHAT_DB=/var/lib/chat/chat.db\`) and is backed up; the model key is an environment variable of the service (a root-only environment file for systemd), never a file in the repository. Anyone who can reach the app can spend your key: put it behind a login or on a private network before it is public.
224
439
  ` : ""}
225
440
  ## Things that surprise people
226
441
 
@@ -228,7 +443,7 @@ Read \`docs/framework/getting-started/deploy.md\`. In short:
228
443
  - A \`json\` validator target reads the body only with a JSON \`Content-Type\`; a failure answers 400 with \`{ error, issues: [{ message, path }] }\`.
229
444
  - \`throw new HTTPException(404, { message })\` answers an error response (plain text).
230
445
  - \`testClient(app)\` from \`'${PACKAGE}/testing'\` types only routes chained on the \`new ${CLASS}()\` expression (\`new ${CLASS}().get(...).post(...)\`); headers such as a cookie go in the second argument of each call.
231
- - **JSX:** ${template === "nodejs" || template === "notes" ? "Write pages in `.tsx` (see `src/" + (template === "notes" ? "views.tsx" : "page.tsx") + "`): the scripts in `package.json` run Node.js with `--import acrylblends/node-server/register`, which compiles `.tsx` with this app's own `typescript`, and `tsconfig.json` sets `jsx: react-jsx` with `jsxImportSource: acrylblends/jsx`. Render a component with `.toString()` and return it with `c.html(...)`. A command that starts the app without those scripts (a bare `node src/index.ts`) cannot load a `.tsx` file. Without a build step you can write the call JSX compiles to instead: `jsx('h1', { class: 'title' }, 'Hello')` from `'acrylblends/jsx'`, children after the props. See `docs/framework/guides/jsx.md`." : "Bun compiles `.tsx` itself: write pages in `.tsx`, render a component with `.toString()` and return it with `c.html(...)`. `jsx('h1', { class: 'title' }, 'Hello')` from `'acrylblends/jsx'` (children after the props) is the same thing without JSX syntax. See `docs/framework/guides/jsx.md`."}
446
+ - **JSX:** ${template === "nodejs" || template === "notes" || template === "chat" ? "Write pages in `.tsx` (see `src/" + (template === "notes" ? "views.tsx" : "page.tsx") + "`): the scripts in `package.json` run Node.js with `--import acrylblends/node-server/register`, which compiles `.tsx` with this app's own `typescript`, and `tsconfig.json` sets `jsx: react-jsx` with `jsxImportSource: acrylblends/jsx`. Render a component with `.toString()` and return it with `c.html(...)`. A command that starts the app without those scripts (a bare `node src/index.ts`) cannot load a `.tsx` file. Without a build step you can write the call JSX compiles to instead: `jsx('h1', { class: 'title' }, 'Hello')` from `'acrylblends/jsx'`, children after the props. See `docs/framework/guides/jsx.md`." : "Bun compiles `.tsx` itself: write pages in `.tsx`, render a component with `.toString()` and return it with `c.html(...)`. `jsx('h1', { class: 'title' }, 'Hello')` from `'acrylblends/jsx'` (children after the props) is the same thing without JSX syntax. See `docs/framework/guides/jsx.md`."}
232
447
  ${template === "nodejs" ? `- **Client components** (run in the browser) live in \`src/client/\`, which has its own \`tsconfig.json\` (DOM types, no Node types); \`clientModules\` in \`src/app.ts\` compiles them when the browser asks, and \`npm run build\` compiles them once for production. See \`src/client/counter.tsx\` and \`docs/framework/guides/client-modules.md\`.\n` : ""}
233
448
  ## Before you say you are done
234
449
 
@@ -271,6 +486,78 @@ function acrylblendsBin() {
271
486
  if (!bin) throw new Error(`${PACKAGE} has no command to create an app with`);
272
487
  return join(dirname(pkgFile), bin);
273
488
  }
489
+ /** The lifecycle scripts a template defines and the line that says when they run. */
490
+ const describeScripts = (scripts) => Object.entries(scripts).map(([key, value]) => ` ${key}: ${value}`).join("\n");
491
+ /** Files whose text is checked for secrets: the template's own, not the framework docs copied in. */
492
+ function textFiles(root) {
493
+ const found = [];
494
+ const walk = (dir, prefix) => {
495
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
496
+ if (entry.name === "node_modules" || entry.name === ".git" || prefix === "" && entry.name === "docs") continue;
497
+ if (entry.isDirectory()) walk(join(dir, entry.name), `${prefix}${entry.name}/`);
498
+ else {
499
+ const buffer = readFileSync(join(dir, entry.name));
500
+ if (!buffer.subarray(0, 8e3).includes(0)) found.push({
501
+ path: `${prefix}${entry.name}`,
502
+ text: buffer.toString("utf8")
503
+ });
504
+ }
505
+ }
506
+ };
507
+ walk(root, "");
508
+ return found;
509
+ }
510
+ /**
511
+ * Create an app from a template source (`github:`, `@scope/name`, a packed tarball). The source is fetched and unpacked into a scratch folder, checked
512
+ * (manifest, secrets), and only then copied to the target; nothing in it is installed or run unless `--install`, which lists the scripts first.
513
+ */
514
+ async function createFromSource(options, target, directory, io) {
515
+ if (!isEmpty(target)) {
516
+ io.stderr.write(`error: ${target} is not empty; nothing was changed\n`);
517
+ return 1;
518
+ }
519
+ const scratch = mkdtempSync(join(tmpdir(), "create-acrylblends-"));
520
+ try {
521
+ const source = parseSource(options.source, io.cwd);
522
+ if (!source) throw new UsageError(`unknown template source "${options.source}" (${SOURCE_FORMS})`);
523
+ const name = nameFrom(target);
524
+ await fetchSource(source, join(scratch, "source"), join(scratch, "download"), io.fetchers ?? realFetchers);
525
+ const manifest = readManifest(join(scratch, "source"));
526
+ const staged = join(scratch, "app");
527
+ const { files, lifecycle } = writeTemplate(join(scratch, "source"), staged, (text) => replacePlaceholders(text, name), frameworkRange(), name);
528
+ if (!existsSync(join(staged, "AGENTS.md"))) writeFileSync(join(staged, "AGENTS.md"), `# ${name}\n\nAn ${CLASS} app made from the template "${manifest.name}": ${manifest.description}\n\nThe framework's API is in \`docs/framework/\` (start at \`docs/framework/README.md\`).\n`);
529
+ if (!existsSync(join(staged, "CLAUDE.md"))) writeFileSync(join(staged, "CLAUDE.md"), "@AGENTS.md\n");
530
+ const found = findSecrets(textFiles(staged));
531
+ if (found.length > 0) {
532
+ io.stderr.write(`error: the template holds what looks like a secret, so nothing was created:\n${found.map((f) => ` ${f.path}:${f.line} (${f.kind})`).join("\n")}\n`);
533
+ return 1;
534
+ }
535
+ copyDocs(staged);
536
+ cpSync(staged, target, { recursive: true });
537
+ io.stdout.write(`created ${name} from ${manifest.name} (${manifest.description}) in ${target}: ${files.length} files, ${CLASS} docs in docs/framework\n`);
538
+ if (manifest.plugins.length > 0) io.stdout.write(`it needs these plugins: ${manifest.plugins.join(", ")}; add them with: npx ${PACKAGE} add ${manifest.plugins.join(" ")}\n`);
539
+ const pm = options.pm ?? PACKAGE_MANAGERS.find((m) => (io.env.npm_config_user_agent ?? "").startsWith(`${m}/`)) ?? "npm";
540
+ const hasScripts = Object.keys(lifecycle).length > 0;
541
+ if (options.install) {
542
+ const pkg = JSON.parse(readFileSync(join(target, "package.json"), "utf8"));
543
+ io.stdout.write(`running ${pm} install in ${directory}. This installs: ${[...Object.keys(pkg.dependencies ?? {}), ...Object.keys(pkg.devDependencies ?? {})].join(", ") || "nothing"}${hasScripts ? `\nand runs the template's own lifecycle scripts:\n${describeScripts(lifecycle)}` : ""}\n(the dependencies' install scripts run too unless your ${pm} is set to ignore them)\n`);
544
+ if (await io.run(pm, ["install"], target) !== 0) {
545
+ io.stderr.write(`error: ${pm} install failed; run it yourself in ${directory}\n`);
546
+ return 1;
547
+ }
548
+ } else if (hasScripts) io.stdout.write(`nothing was installed or run. The template defines ${LIFECYCLE.filter((k) => lifecycle[k]).join(", ")}, which ${pm} install would run:\n${describeScripts(lifecycle)}\nread them first, or pass --install to run them.\n`);
549
+ io.stdout.write(`\nNext:\n cd ${directory}\n${options.install ? "" : ` ${pm} install\n`} see the template's README or package.json scripts\n`);
550
+ return 0;
551
+ } catch (error) {
552
+ if (error instanceof SourceError) {
553
+ io.stderr.write(`error: ${error.message}\nnothing was changed\n`);
554
+ return 1;
555
+ }
556
+ throw error;
557
+ } finally {
558
+ removeTree(scratch);
559
+ }
560
+ }
274
561
  /** Create the app. Returns the exit code: 0 done, 1 refused or failed, 2 a usage error. Never calls `process.exit`. */
275
562
  async function runCreate(argv, io = processIo()) {
276
563
  try {
@@ -286,8 +573,9 @@ async function runCreate(argv, io = processIo()) {
286
573
  const ask = options.yes ? void 0 : io.ask;
287
574
  const directory = options.directory ?? (ask ? (await ask(`Project directory (acrylblends-app): `)).trim() || `acrylblends-app` : `acrylblends-app`);
288
575
  const target = resolve(io.cwd, directory);
576
+ if (options.source !== void 0) return await createFromSource(options, target, directory, io);
289
577
  const template = options.template ?? (ask ? await (async () => {
290
- const answer = (await ask(`Which template do you want to use? (nodejs, notes, bun (experimental), acryl-app) [nodejs]: `)).trim() || "nodejs";
578
+ const answer = (await ask(`Which template do you want to use? (nodejs, notes, chat, bun (experimental), acryl-app) [nodejs]: `)).trim() || "nodejs";
291
579
  if (!isTemplate(answer)) throw new UsageError(`unknown template "${answer}" (${TEMPLATES.join(", ")})`);
292
580
  return answer;
293
581
  })() : "nodejs");
@@ -321,6 +609,7 @@ async function runCreate(argv, io = processIo()) {
321
609
  const start = {
322
610
  nodejs: `${pm} run dev`,
323
611
  notes: `${pm} run dev`,
612
+ chat: `${pm} run dev`,
324
613
  bun: "bun run dev",
325
614
  "acryl-app": `${pm} run dev`
326
615
  }[template];
@@ -336,6 +625,6 @@ async function runCreate(argv, io = processIo()) {
336
625
  }
337
626
  }
338
627
  //#endregion
339
- export { CLASS, CREATE, HELP, PACKAGE, PACKAGE_MANAGERS, TEMPLATES, UsageError, VERSION, agentsText, frameworkRange, isTemplate, nameFrom, parseCreateOptions, processIo, replacePlaceholders, runCreate };
628
+ export { CLASS, CREATE, HELP, PACKAGE, PACKAGE_MANAGERS, TEMPLATES, TEMPLATE_MANIFEST, UsageError, VERSION, agentsText, frameworkRange, isTemplate, nameFrom, parseCreateOptions, processIo, replacePlaceholders, runCreate };
340
629
 
341
630
  //# sourceMappingURL=index.js.map