create-knit 0.3.2 → 0.4.1
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/README.md +19 -1
- package/index.mjs +43 -11
- package/package.json +6 -5
- package/template/base/.claude/skills/knit-add-api/SKILL.md +5 -4
- package/template/base/.claude/skills/knit-add-model/SKILL.md +3 -2
- package/template/base/.github/workflows/ci.yml +31 -0
- package/template/base/.vscode/extensions.json +8 -0
- package/template/base/.vscode/settings.json +10 -0
- package/template/base/AGENTS.md +15 -10
- package/template/base/CLAUDE.md +2 -2
- package/template/base/_gitignore +1 -1
- package/template/base/apps/web/.env.example +6 -6
- package/template/base/apps/web/app/pages/index.vue +1 -1
- package/template/base/apps/web/test/e2e/smoke.test.ts +36 -0
- package/template/base/docker/Dockerfile +3 -3
- package/template/base/docker/Dockerfile.dockerignore +1 -1
- package/template/base/eslint.config.mjs +12 -0
- package/template/base/llms.txt +45 -0
- package/template/base/renovate.json +11 -0
- package/template/base/tsconfig.test.json +26 -0
- package/template/examples/apps/web/app/pages/platform.vue +1 -1
- package/template/examples/layers/example-blog/admin.ts +1 -1
- package/template/examples/layers/example-blog/app/pages/blog/[slug].vue +5 -5
- package/template/examples/layers/example-blog/app/pages/blog/stats.vue +1 -3
- package/template/examples/layers/example-blog/server/api/blog/word-count.post.ts +3 -2
- package/template/examples/layers/example-blog/server/channels/comments.ts +3 -2
- package/template/examples/layers/example-blog/server/database/schema.ts +5 -6
- package/template/examples/layers/example-blog/server/resources/comments.ts +2 -3
- package/template/examples/layers/example-blog/server/resources/posts.ts +1 -1
- package/template/examples/layers/example-blog/test/blog.test.ts +1 -1
- package/template/versions.json +3 -1
package/README.md
CHANGED
|
@@ -8,11 +8,29 @@ pnpm create knit my-app --no-examples # start empty
|
|
|
8
8
|
npm create knit@latest my-app # also works; the project itself uses pnpm
|
|
9
9
|
```
|
|
10
10
|
|
|
11
|
-
It writes the project, runs `pnpm install
|
|
11
|
+
It writes the project, runs `pnpm install`, creates the initial migration (`--no-install` skips both) and makes the first git commit (`--no-git` skips it; so does running inside an existing repository). Then:
|
|
12
12
|
|
|
13
13
|
```bash
|
|
14
14
|
cd my-app
|
|
15
15
|
pnpm dev # open http://localhost:3000/admin
|
|
16
16
|
```
|
|
17
17
|
|
|
18
|
+
## What you get
|
|
19
|
+
|
|
20
|
+
- `apps/web`: your site, extending `@knit-framework/core` (admin, auth, accounts pages, REST resources, tasks, realtime).
|
|
21
|
+
- `layers/`: your apps. With `--examples`: a blog with live comments and a client-rendered dashboard. Add your own with `pnpm manage startapp <name>`.
|
|
22
|
+
- Tooling: ESLint (`pnpm lint`), a CI workflow (`.github/workflows/ci.yml`: lint, typecheck, checks, tests, build), a Renovate config, editor settings and an end-to-end smoke test (`apps/web/test/e2e/smoke.test.ts`).
|
|
23
|
+
- For coding agents: `AGENTS.md`, `llms.txt`, skills, and MCP configuration for Claude Code, Cursor and VS Code, including the project's own `knit` server.
|
|
24
|
+
- Docker: a development `docker-compose.yml` (Postgres, Mailpit) and a production `docker/Dockerfile`.
|
|
25
|
+
|
|
26
|
+
## Options
|
|
27
|
+
|
|
28
|
+
| Flag | Meaning |
|
|
29
|
+
| --- | --- |
|
|
30
|
+
| `--examples` / `--no-examples` | Include the example apps, or start empty (asked when omitted) |
|
|
31
|
+
| `--no-install` | Only write the files: skip `pnpm install` and the initial migration |
|
|
32
|
+
| `--no-git` | Don't run `git init` and make the first commit |
|
|
33
|
+
|
|
34
|
+
Documentation: https://3ig.github.io/knit/
|
|
35
|
+
|
|
18
36
|
License: MIT
|
package/index.mjs
CHANGED
|
@@ -19,20 +19,23 @@ const bold = text => color('1', text)
|
|
|
19
19
|
const dim = text => color('2', text)
|
|
20
20
|
|
|
21
21
|
function usage() {
|
|
22
|
-
return `Usage: pnpm create knit [dir] [--examples | --no-examples] [--no-install]
|
|
22
|
+
return `Usage: pnpm create knit [dir] [--examples | --no-examples] [--no-install] [--no-git]
|
|
23
23
|
|
|
24
24
|
dir Folder to create (default: asked, or "my-knit-app")
|
|
25
25
|
--examples Include the example blog and dashboard apps (default when asked: yes)
|
|
26
26
|
--no-examples Start empty: just the core layer, ready for \`pnpm manage startapp\`
|
|
27
|
-
--no-install Only write the files (skip \`pnpm install\` and the initial migration)
|
|
27
|
+
--no-install Only write the files (skip \`pnpm install\` and the initial migration)
|
|
28
|
+
--no-git Don't run \`git init\` and make the first commit (also skipped inside an
|
|
29
|
+
existing repository, or when git is not installed)`
|
|
28
30
|
}
|
|
29
31
|
|
|
30
32
|
function parseArgs(argv) {
|
|
31
|
-
const opts = { dir: undefined, examples: undefined, install: true }
|
|
33
|
+
const opts = { dir: undefined, examples: undefined, install: true, git: true }
|
|
32
34
|
for (const arg of argv) {
|
|
33
35
|
if (arg === '--examples') opts.examples = true
|
|
34
36
|
else if (arg === '--no-examples') opts.examples = false
|
|
35
37
|
else if (arg === '--no-install') opts.install = false
|
|
38
|
+
else if (arg === '--no-git') opts.git = false
|
|
36
39
|
else if (arg === '-h' || arg === '--help') {
|
|
37
40
|
console.log(usage())
|
|
38
41
|
process.exit(0)
|
|
@@ -87,7 +90,9 @@ function writeProject(target, name, examples) {
|
|
|
87
90
|
manage: 'knit',
|
|
88
91
|
dev: 'pnpm --filter web dev',
|
|
89
92
|
build: 'pnpm --filter web build',
|
|
90
|
-
|
|
93
|
+
// The app (and every layer it extends), then tests and commands, which run outside Nuxt.
|
|
94
|
+
typecheck: 'pnpm -r typecheck && tsc -p tsconfig.test.json',
|
|
95
|
+
lint: 'eslint .',
|
|
91
96
|
check: 'knit check',
|
|
92
97
|
test: 'knit test',
|
|
93
98
|
services: 'docker compose up -d',
|
|
@@ -95,15 +100,18 @@ function writeProject(target, name, examples) {
|
|
|
95
100
|
},
|
|
96
101
|
devDependencies: {
|
|
97
102
|
'@knit-framework/cli': cli,
|
|
103
|
+
// Also at the root, so `node_modules/@knit-framework/core/docs` (the guides) is there to read.
|
|
104
|
+
'@knit-framework/core': core,
|
|
98
105
|
'@nuxt/test-utils': versions.testUtils,
|
|
99
106
|
'@types/node': versions.typesNode,
|
|
100
107
|
'@types/pg': versions.typesPg,
|
|
108
|
+
eslint: versions.eslint,
|
|
101
109
|
pg: versions.pg,
|
|
102
110
|
typescript: versions.typescript,
|
|
103
111
|
vitest: versions.vitest,
|
|
104
112
|
},
|
|
105
|
-
//
|
|
106
|
-
|
|
113
|
+
// Project settings, read by the `knit` CLI and the core layer.
|
|
114
|
+
knit: { app: 'apps/web', layersDir: 'layers', migrationsDir: 'server/database/migrations' },
|
|
107
115
|
}))
|
|
108
116
|
|
|
109
117
|
writeFileSync(join(target, 'pnpm-workspace.yaml'), [
|
|
@@ -133,14 +141,19 @@ function writeProject(target, name, examples) {
|
|
|
133
141
|
...Object.fromEntries(exampleLayers.map(l => [l, 'workspace:*'])),
|
|
134
142
|
nuxt: versions.nuxt,
|
|
135
143
|
},
|
|
136
|
-
devDependencies: { typescript: versions.typescript, 'vue-tsc': versions.vueTsc },
|
|
144
|
+
devDependencies: { '@nuxt/eslint': versions.nuxtEslint, eslint: versions.eslint, typescript: versions.typescript, 'vue-tsc': versions.vueTsc },
|
|
137
145
|
}))
|
|
138
146
|
writeFileSync(join(target, 'apps/web/nuxt.config.ts'), [
|
|
147
|
+
"import { fileURLToPath } from 'node:url'",
|
|
148
|
+
'',
|
|
139
149
|
'export default defineNuxtConfig({',
|
|
140
|
-
' // Installed apps
|
|
150
|
+
' // Installed apps. `pnpm manage startapp <name>` adds new ones here.',
|
|
141
151
|
` extends: [${['@knit-framework/core', ...exampleLayers.map(l => `../../layers/${l}`)].map(e => `'${e}'`).join(', ')}],`,
|
|
152
|
+
" modules: ['@nuxt/eslint'],",
|
|
142
153
|
" compatibilityDate: '2026-11-01',",
|
|
143
154
|
' devtools: { enabled: true },',
|
|
155
|
+
' // `pnpm lint` runs from the workspace root (eslint.config.mjs there), so layers are linted too.',
|
|
156
|
+
" eslint: { config: { rootDir: fileURLToPath(new URL('../..', import.meta.url)), autoInit: false } },",
|
|
144
157
|
'})',
|
|
145
158
|
'',
|
|
146
159
|
].join('\n'))
|
|
@@ -159,6 +172,8 @@ function writeProject(target, name, examples) {
|
|
|
159
172
|
'// `pnpm test` (= `knit test`): unit tests of your apps, and e2e tests that build apps/web.',
|
|
160
173
|
'export default defineConfig({',
|
|
161
174
|
' test: {',
|
|
175
|
+
' // A project without tests yet is not a failure.',
|
|
176
|
+
' passWithNoTests: true,',
|
|
162
177
|
' projects: [',
|
|
163
178
|
" { test: { name: 'unit', environment: 'node', include: ['layers/*/test/**/*.test.ts', 'apps/*/test/unit/**/*.test.ts'] } },",
|
|
164
179
|
" { test: { name: 'e2e', environment: 'node', include: ['apps/*/test/e2e/**/*.test.ts'], testTimeout: 60_000, hookTimeout: 300_000, fileParallelism: false } },",
|
|
@@ -178,11 +193,12 @@ function writeProject(target, name, examples) {
|
|
|
178
193
|
'pnpm manage startapp shop # a new app in layers/shop',
|
|
179
194
|
'pnpm manage makemigrations && pnpm manage migrate',
|
|
180
195
|
'pnpm manage describe # everything this project contains',
|
|
196
|
+
'pnpm lint && pnpm typecheck && pnpm test # what CI runs (.github/workflows/ci.yml)',
|
|
181
197
|
'```',
|
|
182
198
|
'',
|
|
183
|
-
'- Guides: `node_modules/@knit-framework/core/docs/` (start with `getting-started.md`), or online at https://github.
|
|
199
|
+
'- Guides: `node_modules/@knit-framework/core/docs/` (start with `getting-started.md`), or online at https://3ig.github.io/knit/docs',
|
|
184
200
|
'- Agents: see `AGENTS.md`; the `knit` MCP server is configured in `.mcp.json`.',
|
|
185
|
-
'- Upgrading Knit: https://github.
|
|
201
|
+
'- Upgrading Knit: https://3ig.github.io/knit/docs/upgrading',
|
|
186
202
|
...(examples
|
|
187
203
|
? [
|
|
188
204
|
'',
|
|
@@ -197,6 +213,18 @@ function writeProject(target, name, examples) {
|
|
|
197
213
|
].join('\n'))
|
|
198
214
|
}
|
|
199
215
|
|
|
216
|
+
/**
|
|
217
|
+
* `git init` and a first commit, so the project starts with a clean history to diff against.
|
|
218
|
+
* Quietly does nothing without git, inside an existing repository, or when git can't commit
|
|
219
|
+
* (no user.name/user.email yet, a signing prompt…).
|
|
220
|
+
*/
|
|
221
|
+
function initGit(target) {
|
|
222
|
+
const git = (...args) => spawnSync('git', args, { cwd: target, stdio: 'ignore' }).status === 0
|
|
223
|
+
if (!git('--version') || git('rev-parse', '--is-inside-work-tree')) return false
|
|
224
|
+
if (!git('init', '--quiet')) return false
|
|
225
|
+
return git('add', '--all') && git('commit', '--quiet', '--message', 'Initial commit from create-knit')
|
|
226
|
+
}
|
|
227
|
+
|
|
200
228
|
function run(command, args, cwd) {
|
|
201
229
|
console.log(dim(`$ ${command} ${args.join(' ')}`))
|
|
202
230
|
const result = spawnSync(command, args, { cwd, stdio: 'inherit', shell: process.platform === 'win32' })
|
|
@@ -207,7 +235,7 @@ async function main() {
|
|
|
207
235
|
const opts = parseArgs(process.argv.slice(2))
|
|
208
236
|
const interactive = process.stdin.isTTY && process.stdout.isTTY
|
|
209
237
|
const rl = interactive ? createInterface({ input: process.stdin, output: process.stdout }) : undefined
|
|
210
|
-
console.log(`\n${bold('Knit')} ${dim(`v${versions.knit}`)}: the batteries-included
|
|
238
|
+
console.log(`\n${bold('Knit')} ${dim(`v${versions.knit}`)}: the batteries-included full-stack framework for TypeScript\n`)
|
|
211
239
|
|
|
212
240
|
try {
|
|
213
241
|
const dir = opts.dir ?? await ask(rl, 'Project folder?', 'my-knit-app')
|
|
@@ -226,12 +254,16 @@ async function main() {
|
|
|
226
254
|
if (!hasPnpm) {
|
|
227
255
|
console.log(`\npnpm is required (Knit projects are pnpm workspaces): ${bold('npm install -g pnpm')} or ${bold('corepack enable')}, then:`)
|
|
228
256
|
console.log(` cd ${cd} && pnpm install && pnpm manage makemigrations --name initial`)
|
|
257
|
+
if (opts.git) initGit(target)
|
|
229
258
|
return
|
|
230
259
|
}
|
|
231
260
|
if (!run('pnpm', ['install'], target)) throw new Error('pnpm install failed (see above).')
|
|
232
261
|
if (!run('pnpm', ['manage', 'makemigrations', '--name', 'initial'], target)) throw new Error('Creating the initial migration failed (see above).')
|
|
233
262
|
}
|
|
234
263
|
|
|
264
|
+
// Last, so the first commit holds the lockfile and the initial migration too.
|
|
265
|
+
if (opts.git && initGit(target)) console.log(dim('Initialized a git repository with the first commit.'))
|
|
266
|
+
|
|
235
267
|
console.log(`\n${bold('Next:')}`)
|
|
236
268
|
if (cd) console.log(` cd ${cd}`)
|
|
237
269
|
if (!opts.install) console.log(' pnpm install && pnpm manage makemigrations --name initial')
|
package/package.json
CHANGED
|
@@ -1,22 +1,23 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "create-knit",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Create a Knit project: `pnpm create knit my-app
|
|
3
|
+
"version": "0.4.1",
|
|
4
|
+
"description": "Create a Knit project: `pnpm create knit my-app`. Knit is the batteries-included full-stack framework for TypeScript, on Nuxt.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
7
7
|
"type": "git",
|
|
8
8
|
"url": "git+https://github.com/3ig/knit.git",
|
|
9
9
|
"directory": "packages/create-knit"
|
|
10
10
|
},
|
|
11
|
-
"homepage": "https://github.
|
|
11
|
+
"homepage": "https://3ig.github.io/knit/",
|
|
12
12
|
"bugs": "https://github.com/3ig/knit/issues",
|
|
13
13
|
"keywords": [
|
|
14
14
|
"knit",
|
|
15
15
|
"create",
|
|
16
16
|
"scaffold",
|
|
17
17
|
"nuxt",
|
|
18
|
-
"
|
|
19
|
-
"
|
|
18
|
+
"framework",
|
|
19
|
+
"full-stack",
|
|
20
|
+
"batteries-included"
|
|
20
21
|
],
|
|
21
22
|
"type": "module",
|
|
22
23
|
"bin": {
|
|
@@ -8,7 +8,7 @@ description: Expose a Knit model as a public REST API with permissions (defineRe
|
|
|
8
8
|
1. **Look first.**
|
|
9
9
|
- `knit_describe` with `section: "resources"` lists the existing APIs and their permission rules.
|
|
10
10
|
- `knit_model` with the table describes its fields.
|
|
11
|
-
2. **
|
|
11
|
+
2. **Generate the file, then edit it.** `pnpm manage generate resource <app> <name> --table <export>` writes `layers/<app>/server/resources/<name>.ts` with explicit fields and safe permissions (public reads, model permissions for writes). Adjust it to what the task needs, for example:
|
|
12
12
|
|
|
13
13
|
```ts
|
|
14
14
|
import { defineResource, isOwner } from '@knit-framework/core/resources'
|
|
@@ -28,14 +28,15 @@ description: Expose a Knit model as a public REST API with permissions (defineRe
|
|
|
28
28
|
- Writes are denied unless a rule allows them.
|
|
29
29
|
- `scope(ctx)` limits which rows each user can see.
|
|
30
30
|
- Foreign-key choices need a resource for the *target* table.
|
|
31
|
-
3. **
|
|
31
|
+
3. **No restart needed:** a running `pnpm dev` picks up new resource files by itself.
|
|
32
32
|
4. **Try it.**
|
|
33
33
|
- `GET /api/r/products` returns `{ items, total, page, perPage, pages }`.
|
|
34
34
|
- `/api/r/docs` and `/api/r/openapi.json` document it.
|
|
35
35
|
- With curl, cookie-carrying writes need no `Origin` header, or the server's own (CSRF guard).
|
|
36
|
-
5. **UI:** `
|
|
36
|
+
5. **UI:** `pnpm manage generate page <app> <name> --table <export>` writes a page that lists the rows through the resource. `useResource('products').list({ … })` is typed from the slug (rows, inputs and filter keys). `<KnitModelForm resource="products" :fields="['name', 'price']" @saved="refresh" />` gives a form with validation errors per field.
|
|
37
37
|
6. **Verify.**
|
|
38
|
-
- `
|
|
38
|
+
- `knit_resource` (or `pnpm -s manage routes --json --kind resources`) shows the endpoints and the permission each one needs.
|
|
39
|
+
- `knit_check` / `pnpm -s manage check --json`, `pnpm typecheck` and `pnpm lint`.
|
|
39
40
|
- An e2e test with `createTestClient` from `@knit-framework/core/testing` covering one allowed and one denied write.
|
|
40
41
|
|
|
41
42
|
Guide: `knit_docs` topic `resources` (or `node_modules/@knit-framework/core/docs/resources.md`).
|
|
@@ -8,7 +8,7 @@ description: Add or change a model (Drizzle table) in a Knit app, end to end - s
|
|
|
8
8
|
1. **Look first.** Call the `knit` MCP tool `knit_describe` with `section: "models"` (or run `pnpm -s manage describe --json`). Note the app's label and the existing tables, and that relations are named for `with:`.
|
|
9
9
|
2. **Pick the app.**
|
|
10
10
|
- The layer is `layers/<app>/`.
|
|
11
|
-
- No suitable app yet: run `pnpm manage startapp <name
|
|
11
|
+
- No suitable app yet: run `pnpm manage startapp <name>` (it writes a starter model with admin, API, page, seed and test to copy from); a running `pnpm dev` restarts itself and picks it up.
|
|
12
12
|
- The table name must be `<label>_<model>`, the label being `knit.app` in the layer's `nuxt.config.ts` or the layer name in snake_case.
|
|
13
13
|
3. **Edit `layers/<app>/server/database/schema.ts`.**
|
|
14
14
|
- Use explicit snake_case column names, e.g. `createdAt: timestamp('created_at', …)`.
|
|
@@ -24,7 +24,8 @@ description: Add or change a model (Drizzle table) in a Knit app, end to end - s
|
|
|
24
24
|
6. **Admin:** register the table in `layers/<app>/admin.ts` with `registerAdminModel(table, { listDisplay, searchFields, listFilter, ordering, readonlyFields })`, using field *keys* (camelCase JS names). Restart `pnpm dev` if `admin.ts` is new.
|
|
25
25
|
7. **Verify.**
|
|
26
26
|
- `pnpm -s manage check --json` (MCP: `knit_check`) has no errors. It catches unknown admin fields, missing prefixes and clashes.
|
|
27
|
-
- `pnpm typecheck`
|
|
27
|
+
- `pnpm typecheck` and `pnpm lint` pass.
|
|
28
|
+
- Add a test: `pnpm manage generate test <app> <name> --table <export>`, then `pnpm manage test --unit`.
|
|
28
29
|
- Then open `/admin` and create a record, including one that fails validation.
|
|
29
30
|
8. **Writes in code** go through `useModel(table)`, not raw `useDB().insert`, so validators and signals run.
|
|
30
31
|
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
name: CI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [main]
|
|
6
|
+
pull_request:
|
|
7
|
+
|
|
8
|
+
concurrency:
|
|
9
|
+
group: ci-${{ github.ref }}
|
|
10
|
+
cancel-in-progress: true
|
|
11
|
+
|
|
12
|
+
jobs:
|
|
13
|
+
check:
|
|
14
|
+
runs-on: ubuntu-latest
|
|
15
|
+
steps:
|
|
16
|
+
- uses: actions/checkout@v4
|
|
17
|
+
- uses: pnpm/action-setup@v4
|
|
18
|
+
- uses: actions/setup-node@v4
|
|
19
|
+
with:
|
|
20
|
+
node-version: 24
|
|
21
|
+
cache: pnpm
|
|
22
|
+
- run: pnpm install --frozen-lockfile
|
|
23
|
+
- run: pnpm lint
|
|
24
|
+
- run: pnpm typecheck
|
|
25
|
+
- run: pnpm manage check
|
|
26
|
+
- run: pnpm manage makemigrations --check # schema changes need a migration
|
|
27
|
+
- run: pnpm test
|
|
28
|
+
- run: pnpm build
|
|
29
|
+
env:
|
|
30
|
+
# Only so the build has a value; production reads the real secret from its environment.
|
|
31
|
+
NUXT_BETTER_AUTH_SECRET: ci-only-secret-not-used-anywhere-0123456789
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
{
|
|
2
|
+
"typescript.tsdk": "node_modules/typescript/lib",
|
|
3
|
+
"files.associations": {
|
|
4
|
+
"*.css": "tailwindcss"
|
|
5
|
+
},
|
|
6
|
+
"tailwindCSS.experimental.configFile": "node_modules/@knit-framework/core/app/assets/css/main.css",
|
|
7
|
+
"editor.codeActionsOnSave": {
|
|
8
|
+
"source.fixAll.eslint": "explicit"
|
|
9
|
+
}
|
|
10
|
+
}
|
package/template/base/AGENTS.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# AGENTS.md: building an app with Knit
|
|
2
2
|
|
|
3
|
-
Knit is a
|
|
3
|
+
Knit is a batteries-included full-stack TypeScript framework on Nuxt 4: **layers are apps**, **Drizzle tables are models**, the **admin is generated**, and **`pnpm manage`** is the CLI. Humans read [`README.md`](README.md) and the guides in [`node_modules/@knit-framework/core/docs/`](node_modules/@knit-framework/core/docs/README.md).
|
|
4
4
|
|
|
5
5
|
Curious how Knit works inside? Read [`node_modules/@knit-framework/core/AGENTS.md`](node_modules/@knit-framework/core/AGENTS.md).
|
|
6
6
|
|
|
@@ -8,20 +8,23 @@ Curious how Knit works inside? Read [`node_modules/@knit-framework/core/AGENTS.m
|
|
|
8
8
|
|
|
9
9
|
Don't read files to find out what exists. Ask Knit:
|
|
10
10
|
|
|
11
|
-
- **MCP:** the `knit` server (`.mcp.json`, `.cursor/mcp.json`, `.vscode/mcp.json`) has read-only tools:
|
|
12
|
-
- `knit_describe`: apps, models with columns, foreign keys and `with:` relations, admin, resources and their permission rules, tasks, channels,
|
|
13
|
-
- `knit_model`: one model.
|
|
11
|
+
- **MCP:** the `knit` server (`.mcp.json`, `.cursor/mcp.json`, `.vscode/mcp.json`) has read-only tools with structured output:
|
|
12
|
+
- `knit_describe`: apps, models with columns, foreign keys and `with:` relations, admin, resources and their permission rules, tasks, channels, routes, commands, migrations. Pass `section` to get one part.
|
|
13
|
+
- `knit_model`, `knit_resource`: one model; one resource with its endpoints and permission rules.
|
|
14
|
+
- `knit_routes`, `knit_openapi`: pages, API routes and resource endpoints; the resources' OpenAPI document.
|
|
14
15
|
- `knit_check`: run after changes.
|
|
15
|
-
- `knit_migrations`, `knit_pending_migration_sql`, `knit_sqlmigrate`.
|
|
16
|
-
- `knit_docs`: the guides, e.g. `{ "topic": "models" }`.
|
|
17
|
-
-
|
|
16
|
+
- `knit_migrations`, `knit_migration_plan`, `knit_pending_migration_sql`, `knit_sqlmigrate`.
|
|
17
|
+
- `knit_docs`: the guides, e.g. `{ "topic": "models" }`. Also as MCP resources: `knit://docs/{topic}`, `knit://describe`, `knit://agents`.
|
|
18
|
+
- Only when the server runs with `--allow-writes`: `knit_startapp`, `knit_generate`, `knit_makemigrations`, `knit_migrate`.
|
|
19
|
+
- **CLI:** `pnpm -s manage describe --json` (the same document; `--section <name>` for one part), `routes --json`, `openapi`, `check --json`, `showmigrations --json`, `runtask --json`. Commands that change things take `--json` too (`startapp`, `generate`, `makemigrations`, `migrate`, …). `-s` keeps pnpm's banner out of the JSON.
|
|
18
20
|
- **Library docs:** the `nuxt`, `nuxt-ui` and `better-auth` MCP servers. Use them instead of guessing APIs.
|
|
19
21
|
|
|
20
22
|
## 2. Where code goes
|
|
21
23
|
|
|
22
24
|
| You want | Put it in |
|
|
23
25
|
| --- | --- |
|
|
24
|
-
| A new app | `pnpm manage startapp <name>` → `layers/<name>/` (adds it to `apps/web/nuxt.config.ts` `extends`) |
|
|
26
|
+
| A new app | `pnpm manage startapp <name>` → `layers/<name>/` with a model, admin, API, page, seed, command and test (adds it to `apps/web/nuxt.config.ts` `extends`) |
|
|
27
|
+
| One more file in an app | `pnpm manage generate <resource\|task\|channel\|command\|test\|page> <app> <name> [--table <export>]`: start from the generated file instead of writing it from scratch |
|
|
25
28
|
| Models | `layers/<app>/server/database/schema.ts` (tables named `<app>_<model>`, `relations()` next to them) |
|
|
26
29
|
| Admin | `layers/<app>/admin.ts` → `registerAdminModel(table, { listDisplay, searchFields, … })` |
|
|
27
30
|
| A public REST API + forms | `layers/<app>/server/resources/<name>.ts` → `export default defineResource(table, { permissions, … })`; `<KnitModelForm resource="…">` in pages |
|
|
@@ -33,7 +36,7 @@ Don't read files to find out what exists. Ask Knit:
|
|
|
33
36
|
| Translations | `layers/<app>/i18n/locales/{en,de,es}.json` |
|
|
34
37
|
| Settings | `apps/web/nuxt.config.ts`, env vars in `apps/web/.env` (see `apps/web/.env.example`) |
|
|
35
38
|
|
|
36
|
-
Don't edit `node_modules/@knit-framework/*`: override instead (a page, component or translation with the same name in your app wins). Never edit generated files: `.nuxt/**`, `apps/web/.
|
|
39
|
+
Don't edit `node_modules/@knit-framework/*`: override instead (a page, component or translation with the same name in your app wins). Never edit generated files: `.nuxt/**`, `apps/web/.knit/**`, and the migrations in `apps/web/server/database/migrations/**` (regenerate them instead).
|
|
37
40
|
|
|
38
41
|
## 3. Conventions
|
|
39
42
|
|
|
@@ -53,12 +56,14 @@ pnpm -s manage check --json # schema, admin field names, layers, mi
|
|
|
53
56
|
pnpm manage makemigrations --name <slug> # after a schema change; --dry-run to preview
|
|
54
57
|
pnpm manage migrate # works while pnpm dev runs; pnpm dev also applies on start
|
|
55
58
|
pnpm typecheck # must pass
|
|
59
|
+
pnpm lint # ESLint (projects created with `pnpm create knit`)
|
|
56
60
|
pnpm manage test --unit # fast; pnpm test runs e2e too (builds the app)
|
|
57
61
|
```
|
|
58
62
|
|
|
59
|
-
- **
|
|
63
|
+
- **No restart needed for new files:** a running `pnpm dev` picks up a new schema, `admin.ts`, resource, task or channel by itself, and applies new migrations when it reloads (or run `pnpm manage migrate`). Only a new locale file needs a `pnpm dev` restart.
|
|
60
64
|
- **Without a terminal**, `makemigrations` can't answer drizzle-kit's "renamed or new?" question. Split the change: add the new column, migrate, then remove the old one.
|
|
61
65
|
- **PGlite is single-process.** `migrate`, `showmigrations`, `removemigration` and `check` go through a running `pnpm dev`. `shell`, `createsuperuser`, `loaddata` and similar need it stopped.
|
|
66
|
+
- **No terminal, no prompts.** `flush`, `createsuperuser` and `changepassword` fail instead of asking: pass `--no-input` (passwords come from `KNIT_SUPERUSER_PASSWORD` / `KNIT_NEW_PASSWORD`).
|
|
62
67
|
- **Undo an unapplied `makemigrations`** with `pnpm manage removemigration`.
|
|
63
68
|
- **Tests:** `createTestDatabase`, `defineFactory`, `createTestClient` from `@knit-framework/core/testing`; app tests in `layers/<app>/test/*.test.ts`. See `node_modules/@knit-framework/core/docs/testing.md`.
|
|
64
69
|
- **Admin or API changes:** sign in at `/admin` and try list, create (including a validation error), edit and delete.
|
package/template/base/CLAUDE.md
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
Read and follow [AGENTS.md](AGENTS.md); it is the single source of truth for building with Knit.
|
|
4
4
|
|
|
5
5
|
Project MCP servers (`.mcp.json`):
|
|
6
|
-
- `knit`: this project's models, resources, routes, checks, migrations and Knit's guides. Start with `knit_describe`.
|
|
6
|
+
- `knit`: this project's models, resources, routes, OpenAPI, checks, migrations and Knit's guides. Start with `knit_describe`. It only reads unless started with `--allow-writes`.
|
|
7
7
|
- `nuxt`, `nuxt-ui`, `better-auth`: library APIs; use them instead of guessing.
|
|
8
8
|
|
|
9
|
-
Skills in `.claude/skills/`: `knit-add-model`, `knit-add-api`.
|
|
9
|
+
Skills in `.claude/skills/`: `knit-add-model`, `knit-add-api`. New files: `pnpm manage startapp <app>` and `pnpm manage generate <kind> <app> <name>`.
|
package/template/base/_gitignore
CHANGED
|
@@ -11,13 +11,13 @@ NUXT_BETTER_AUTH_URL=
|
|
|
11
11
|
# DATABASE_URL=postgres://user:password@localhost:5432/knit
|
|
12
12
|
|
|
13
13
|
# PGlite data directory (relative to apps/web, or to the folder holding a deployed .output). Default: .data/pglite
|
|
14
|
-
#
|
|
14
|
+
# NUXT_KNIT_DATA_DIR=.data/pglite
|
|
15
15
|
|
|
16
16
|
# Apply pending migrations at startup: dev (default) | always | never
|
|
17
|
-
#
|
|
17
|
+
# NUXT_KNIT_AUTO_MIGRATE=dev
|
|
18
18
|
|
|
19
19
|
# First-admin setup wizard at /admin/setup: dev (default) | always | never
|
|
20
|
-
#
|
|
20
|
+
# NUXT_KNIT_ALLOW_SETUP=dev
|
|
21
21
|
|
|
22
22
|
# Site name used in auth emails. Default: Knit
|
|
23
23
|
# NUXT_BETTER_AUTH_APP_NAME=Knit
|
|
@@ -35,14 +35,14 @@ NUXT_BETTER_AUTH_URL=
|
|
|
35
35
|
# NUXT_MAIL_MAILER=
|
|
36
36
|
# SMTP connection URL, e.g. smtp://user:pass@smtp.example.com:587 or smtps://user:pass@host:465
|
|
37
37
|
# NUXT_MAIL_URL=
|
|
38
|
-
# Default sender
|
|
38
|
+
# Default sender address
|
|
39
39
|
# NUXT_MAIL_FROM=Knit <webmaster@localhost>
|
|
40
40
|
|
|
41
41
|
# Used by `pnpm manage createsuperuser --noinput`
|
|
42
|
-
#
|
|
42
|
+
# KNIT_SUPERUSER_PASSWORD=
|
|
43
43
|
|
|
44
44
|
# Used by `pnpm manage changepassword <email> --noinput`
|
|
45
|
-
#
|
|
45
|
+
# KNIT_NEW_PASSWORD=
|
|
46
46
|
# ── Logging (LogLayer) ─────────────────────────────────────────────────────────
|
|
47
47
|
# trace | debug | info | warn | error | fatal (default: debug in dev, info in production)
|
|
48
48
|
# NUXT_KNIT_LOG_LEVEL=info
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Smoke test: builds the app, boots the production server on an in-memory database and checks
|
|
3
|
+
* that it answers. Run with `pnpm test` (or `pnpm manage test --e2e`).
|
|
4
|
+
* More: `createTestClient` from `@knit-framework/core/testing` signs in and keeps cookies.
|
|
5
|
+
*/
|
|
6
|
+
import { randomBytes } from 'node:crypto'
|
|
7
|
+
import { fileURLToPath } from 'node:url'
|
|
8
|
+
import { setup, url } from '@nuxt/test-utils/e2e'
|
|
9
|
+
import { describe, expect, it } from 'vitest'
|
|
10
|
+
|
|
11
|
+
Object.assign(process.env, {
|
|
12
|
+
NUXT_KNIT_DATA_DIR: 'memory://',
|
|
13
|
+
NUXT_KNIT_AUTO_MIGRATE: 'always',
|
|
14
|
+
NUXT_BETTER_AUTH_SECRET: randomBytes(32).toString('base64'),
|
|
15
|
+
})
|
|
16
|
+
|
|
17
|
+
await setup({
|
|
18
|
+
rootDir: fileURLToPath(new URL('../..', import.meta.url)),
|
|
19
|
+
server: true,
|
|
20
|
+
browser: false,
|
|
21
|
+
})
|
|
22
|
+
|
|
23
|
+
describe('smoke', () => {
|
|
24
|
+
it('answers the health check', async () => {
|
|
25
|
+
const response = await fetch(url('/api/_knit/health'))
|
|
26
|
+
expect(response.status).toBe(200)
|
|
27
|
+
expect(await response.json()).toMatchObject({ ok: true })
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
it('renders the admin sign-in page', async () => {
|
|
31
|
+
const response = await fetch(url('/admin/login'))
|
|
32
|
+
expect(response.status).toBe(200)
|
|
33
|
+
expect(response.headers.get('content-type')).toContain('text/html')
|
|
34
|
+
expect(await response.text()).toContain('id="__nuxt"')
|
|
35
|
+
})
|
|
36
|
+
})
|
|
@@ -47,9 +47,9 @@ ENV NODE_ENV=production \
|
|
|
47
47
|
HOST=0.0.0.0 \
|
|
48
48
|
PORT=3000 \
|
|
49
49
|
# Apply pending migrations on start (set to `never` to run them as a separate release step).
|
|
50
|
-
|
|
50
|
+
NUXT_KNIT_AUTO_MIGRATE=always \
|
|
51
51
|
# Persistent data when using the embedded PGlite database and local file storage.
|
|
52
|
-
|
|
52
|
+
NUXT_KNIT_DATA_DIR=/data/pglite \
|
|
53
53
|
NUXT_KNIT_STORAGE_DIR=/data/uploads \
|
|
54
54
|
NUXT_KNIT_CACHE_BASE=/data/cache
|
|
55
55
|
WORKDIR /app
|
|
@@ -60,5 +60,5 @@ USER node
|
|
|
60
60
|
VOLUME ["/data"]
|
|
61
61
|
EXPOSE 3000
|
|
62
62
|
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
|
|
63
|
-
CMD node -e "fetch('http://127.0.0.1:'+(process.env.PORT||3000)+'/api/
|
|
63
|
+
CMD node -e "fetch('http://127.0.0.1:'+(process.env.PORT||3000)+'/api/_knit/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"
|
|
64
64
|
CMD ["node", "apps/web/.output/server/index.mjs"]
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// `pnpm lint` for the whole workspace: apps/web and every app in layers/.
|
|
3
|
+
// The base config is generated by @nuxt/eslint (`nuxt prepare`, which `pnpm install` runs).
|
|
4
|
+
import withNuxt from './apps/web/.nuxt/eslint.config.mjs'
|
|
5
|
+
|
|
6
|
+
export default withNuxt(
|
|
7
|
+
{
|
|
8
|
+
// Generated or local-only folders.
|
|
9
|
+
ignores: ['**/.data/**', '**/.knit/**', '**/.inspectdb/**', '**/server/database/migrations/**'],
|
|
10
|
+
},
|
|
11
|
+
// Your own rules go here, e.g. { rules: { 'no-console': 'warn' } }
|
|
12
|
+
)
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# Knit
|
|
2
|
+
|
|
3
|
+
> Knit is a batteries-included full-stack TypeScript framework on Nuxt 4: layers are apps, Drizzle tables are models, the admin is generated, BetterAuth handles accounts and permissions, and `pnpm manage` is the CLI. PGlite runs with zero setup; Postgres via DATABASE_URL.
|
|
4
|
+
|
|
5
|
+
Agents working in a Knit project: read AGENTS.md, and use the `knit` MCP server (`pnpm -s manage mcp`) or `pnpm -s manage describe --json` to learn the project before reading files.
|
|
6
|
+
|
|
7
|
+
## Start
|
|
8
|
+
|
|
9
|
+
- [AGENTS.md](AGENTS.md): rules for agents building an app
|
|
10
|
+
- [README](README.md): overview and quick start
|
|
11
|
+
- [Working with AI agents](node_modules/@knit-framework/core/docs/ai-agents.md): the MCP server, describe, skills
|
|
12
|
+
|
|
13
|
+
## Guides
|
|
14
|
+
|
|
15
|
+
- [Development environment](node_modules/@knit-framework/core/docs/development.md): Native Node, or Docker Compose with Postgres and Mailpit
|
|
16
|
+
- [Getting started](node_modules/@knit-framework/core/docs/getting-started.md): Install, project layout, your first app end to end
|
|
17
|
+
- [Models & data](node_modules/@knit-framework/core/docs/models.md): Tables, migrations, `useModel`, validators, `clean()`, signals, Postgres
|
|
18
|
+
- [Resources & forms](node_modules/@knit-framework/core/docs/resources.md): `defineResource` REST APIs, permissions, scoping, OpenAPI, `useResource`, `<KnitModelForm>`
|
|
19
|
+
- [Rendering modes](node_modules/@knit-framework/core/docs/rendering.md): SSR by default; SPA per route, per path or per layer; prerender and caching
|
|
20
|
+
- [Admin](node_modules/@knit-framework/core/docs/admin.md): `registerAdminModel` options, filters, actions, inlines, history, user tools, REST API
|
|
21
|
+
- [Auth & permissions](node_modules/@knit-framework/core/docs/auth.md): Users, staff, superusers, groups, permissions, `/accounts/*` pages
|
|
22
|
+
- [Internationalization](node_modules/@knit-framework/core/docs/i18n.md): Translations, locales per layer, translating models, the language switcher
|
|
23
|
+
- [Email](node_modules/@knit-framework/core/docs/email.md): `sendMail()`, mailers, templates, auth emails
|
|
24
|
+
- [Background tasks](node_modules/@knit-framework/core/docs/tasks.md): `defineTask`, `enqueue`, the worker, cron schedules
|
|
25
|
+
- [Realtime](node_modules/@knit-framework/core/docs/realtime.md): Channels over SSE and WebSocket, `publish`, `broadcastModel`, `useRealtime`, scaling with Postgres
|
|
26
|
+
- [Files & uploads](node_modules/@knit-framework/core/docs/files.md): `fileColumn`, uploads, disk/S3 storage
|
|
27
|
+
- [Cache, messages & humanize](node_modules/@knit-framework/core/docs/utilities.md): `cached()`, flash messages, formatting helpers
|
|
28
|
+
- [Sitemaps & feeds](node_modules/@knit-framework/core/docs/sitemaps-and-feeds.md): `/sitemap.xml`, RSS and Atom
|
|
29
|
+
- [Logging](node_modules/@knit-framework/core/docs/logging.md): LogLayer: pretty dev output, JSON in production, request logs, redaction
|
|
30
|
+
- [Security](node_modules/@knit-framework/core/docs/security.md): CSRF, security headers, CSP
|
|
31
|
+
- [Testing](node_modules/@knit-framework/core/docs/testing.md): Test databases, factories, the HTTP client, `pnpm test`
|
|
32
|
+
- [`manage` CLI](node_modules/@knit-framework/core/docs/cli.md): Every command, `startapp` and `generate`, JSON output for scripts and agents, seeds, custom commands
|
|
33
|
+
- [Configuration](node_modules/@knit-framework/core/docs/configuration.md): Every environment variable and setting
|
|
34
|
+
- [Deployment](node_modules/@knit-framework/core/docs/deployment.md): Production checklist, build and run
|
|
35
|
+
- [Upgrading](node_modules/@knit-framework/core/docs/upgrading.md): updating the @knit-framework packages, migrating Knit's tables, removing the examples
|
|
36
|
+
- [How Knit works](node_modules/@knit-framework/core/docs/architecture.md): Discovery, generated modules, request lifecycle
|
|
37
|
+
- [Working with AI agents](node_modules/@knit-framework/core/docs/ai-agents.md): `AGENTS.md`, the `knit` MCP server (tools, resources, write tools), `describe`, `routes`, `openapi`, skills
|
|
38
|
+
- [Troubleshooting](node_modules/@knit-framework/core/docs/troubleshooting.md): Common errors and fixes
|
|
39
|
+
- [Roadmap](node_modules/@knit-framework/core/docs/roadmap.md): what's proposed next, and why
|
|
40
|
+
- [Coming from Django](node_modules/@knit-framework/core/docs/coming-from-django.md): every Django concept and its Knit equivalent
|
|
41
|
+
|
|
42
|
+
## Optional
|
|
43
|
+
|
|
44
|
+
- [Framework internals](node_modules/@knit-framework/core/AGENTS.md): how Knit works inside
|
|
45
|
+
- [Changelog](https://github.com/3ig/knit/blob/main/CHANGELOG.md)
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
|
|
3
|
+
"extends": ["config:recommended"],
|
|
4
|
+
"packageRules": [
|
|
5
|
+
{
|
|
6
|
+
"description": "Knit's packages are released together: update them in one pull request.",
|
|
7
|
+
"groupName": "Knit",
|
|
8
|
+
"matchPackageNames": ["@knit-framework/**"]
|
|
9
|
+
}
|
|
10
|
+
]
|
|
11
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
{
|
|
2
|
+
// Code that runs outside Nuxt: tests, management commands and config files.
|
|
3
|
+
// `pnpm typecheck` checks it after the app itself (`nuxt typecheck` in apps/web).
|
|
4
|
+
"compilerOptions": {
|
|
5
|
+
"target": "ES2022",
|
|
6
|
+
"module": "ESNext",
|
|
7
|
+
"moduleResolution": "Bundler",
|
|
8
|
+
"strict": true,
|
|
9
|
+
"noUncheckedIndexedAccess": true,
|
|
10
|
+
"esModuleInterop": true,
|
|
11
|
+
"skipLibCheck": true,
|
|
12
|
+
"resolveJsonModule": true,
|
|
13
|
+
"isolatedModules": true,
|
|
14
|
+
"verbatimModuleSyntax": true,
|
|
15
|
+
"forceConsistentCasingInFileNames": true,
|
|
16
|
+
"noEmit": true,
|
|
17
|
+
"types": ["node"]
|
|
18
|
+
},
|
|
19
|
+
"include": [
|
|
20
|
+
"vitest.config.ts",
|
|
21
|
+
"layers/*/test/**/*.ts",
|
|
22
|
+
"layers/*/commands/**/*.ts",
|
|
23
|
+
"apps/*/test/**/*.ts",
|
|
24
|
+
"apps/*/commands/**/*.ts"
|
|
25
|
+
]
|
|
26
|
+
}
|
|
@@ -18,7 +18,7 @@ registerAdminModel(category, {
|
|
|
18
18
|
slug: 'URL-friendly identifier. Filled in from the name while creating.',
|
|
19
19
|
description: 'Optional. Shown on the category page.',
|
|
20
20
|
},
|
|
21
|
-
//
|
|
21
|
+
// Inline: edit the category's posts on its change form.
|
|
22
22
|
inlines: [
|
|
23
23
|
tabularInline(post, { fkField: 'categoryId', fields: ['title', 'slug', 'published', 'publishedAt'], extra: 1 }),
|
|
24
24
|
],
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
<script setup lang="ts">
|
|
2
|
-
import { fileUrl } from '#
|
|
3
|
-
import { resourceParseError } from '#
|
|
4
|
-
import type { comment } from '../../../server/database/schema'
|
|
2
|
+
import { fileUrl } from '#knit/files-types'
|
|
3
|
+
import { resourceParseError } from '#knit/resources-types'
|
|
5
4
|
|
|
6
5
|
const route = useRoute()
|
|
7
6
|
const { t, locale } = useI18n()
|
|
@@ -16,7 +15,8 @@ useHead({ title: () => post.value?.title ?? t('blog.post') })
|
|
|
16
15
|
const { user, loggedIn, ready, fetchSession } = useAuth()
|
|
17
16
|
if (!ready.value) await fetchSession()
|
|
18
17
|
|
|
19
|
-
|
|
18
|
+
// Typed from the slug: rows are what the resource's `serialize()` returns (with `author`).
|
|
19
|
+
const comments = useResource('comments')
|
|
20
20
|
const { items, total, refresh } = comments.list({
|
|
21
21
|
key: `blog-comments:${slug.value}`,
|
|
22
22
|
filters: () => ({ postId: post.value?.id }),
|
|
@@ -124,8 +124,8 @@ const loginUrl = computed(() => `/accounts/login?redirect=${encodeURIComponent(r
|
|
|
124
124
|
</div>
|
|
125
125
|
<KnitModelForm
|
|
126
126
|
v-if="editing === c.id"
|
|
127
|
-
resource="comments"
|
|
128
127
|
:id="c.id"
|
|
128
|
+
resource="comments"
|
|
129
129
|
:fields="['body']"
|
|
130
130
|
hide-labels
|
|
131
131
|
cancelable
|
|
@@ -1,6 +1,4 @@
|
|
|
1
1
|
<script setup lang="ts">
|
|
2
|
-
import type { post } from '../../../server/database/schema'
|
|
3
|
-
|
|
4
2
|
/**
|
|
5
3
|
* Route-level opt-out: only this page skips server-side rendering. The rest of /blog stays
|
|
6
4
|
* server-rendered. (Equivalent to `routeRules: { '/blog/stats': { ssr: false } }`.)
|
|
@@ -10,7 +8,7 @@ defineRouteRules({ ssr: false })
|
|
|
10
8
|
const { t } = useI18n()
|
|
11
9
|
useHead({ title: () => t('blog.stats.title') })
|
|
12
10
|
|
|
13
|
-
const posts = useResource
|
|
11
|
+
const posts = useResource('posts').list({ perPage: 100, key: 'blog-stats' })
|
|
14
12
|
const words = computed(() => posts.items.value.reduce((sum, p) => sum + String(p.body ?? '').split(/\s+/).filter(Boolean).length, 0))
|
|
15
13
|
// Read from the browser: something the server could not know.
|
|
16
14
|
const readingSpeed = ref(Number(localStorage.getItem('knit:wpm')) || 230)
|
|
@@ -9,8 +9,9 @@ export default defineEventHandler(async (event) => {
|
|
|
9
9
|
if (!Number.isInteger(postId) || postId < 1) throw createError({ statusCode: 400, statusMessage: 'Expected { postId: number }' })
|
|
10
10
|
|
|
11
11
|
const task = await enqueue('blog.word-count', { postId })
|
|
12
|
-
|
|
13
|
-
|
|
12
|
+
// `task.result` is typed from the task's `run()` (see server/tasks/blog.ts).
|
|
13
|
+
if (task.status === 'succeeded' && task.result) {
|
|
14
|
+
const { words, title } = task.result
|
|
14
15
|
flash(event, { type: 'success', title: `${intcomma(words)} word${pluralize(words)}`, description: `in “${title}”` })
|
|
15
16
|
}
|
|
16
17
|
else if (task.status === 'failed') {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Live comments for one post
|
|
2
|
+
* Live comments for one post.
|
|
3
3
|
* `server/database/schema.ts` broadcasts comment writes here with `broadcastModel`.
|
|
4
4
|
*
|
|
5
5
|
* Anyone may listen, but moderation still applies to what each subscriber receives:
|
|
@@ -26,7 +26,8 @@ function isCommentEvent(value: unknown): value is CommentEvent {
|
|
|
26
26
|
|
|
27
27
|
export const postComments = defineChannel('comments:post:{id}', {
|
|
28
28
|
description: 'Comment created/updated/deleted events for one post',
|
|
29
|
-
|
|
29
|
+
// `ctx.params` is typed from the pattern: `{ id: string }`.
|
|
30
|
+
authorize: ctx => /^\d+$/.test(ctx.params.id),
|
|
30
31
|
filter(message, ctx) {
|
|
31
32
|
if (ctx.can(MODERATE)) return true
|
|
32
33
|
if (!isCommentEvent(message.data)) return false
|
|
@@ -20,7 +20,7 @@ export const post = pgTable(
|
|
|
20
20
|
title: varchar('title', { length: 200 }).notNull(),
|
|
21
21
|
slug: varchar('slug', { length: 220 }).notNull().unique(),
|
|
22
22
|
body: text('body').notNull().default(''),
|
|
23
|
-
/** Optional cover image
|
|
23
|
+
/** Optional cover image; the admin shows an upload widget. */
|
|
24
24
|
cover: fileColumn('cover'),
|
|
25
25
|
published: boolean('published').notNull().default(false),
|
|
26
26
|
publishedAt: timestamp('published_at', { withTimezone: true }),
|
|
@@ -52,7 +52,7 @@ export const postTag = pgTable(
|
|
|
52
52
|
)
|
|
53
53
|
|
|
54
54
|
/**
|
|
55
|
-
* Reader comments
|
|
55
|
+
* Reader comments, linked to the post and the user.
|
|
56
56
|
* Exposed publicly by `server/resources/comments.ts`; moderated in the admin.
|
|
57
57
|
*/
|
|
58
58
|
export const comment = pgTable(
|
|
@@ -97,7 +97,7 @@ export const postRelations = relations(post, ({ one, many }) => ({
|
|
|
97
97
|
author: one(user, { fields: [post.authorId], references: [user.id] }),
|
|
98
98
|
}))
|
|
99
99
|
|
|
100
|
-
// Model options and validation
|
|
100
|
+
// Model options and validation.
|
|
101
101
|
// They live next to the tables because both the server and `pnpm manage` load this file.
|
|
102
102
|
// Enforced by `useModel(table)` on every create/update.
|
|
103
103
|
const SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
|
|
@@ -137,7 +137,7 @@ defineModelMeta(comment, {
|
|
|
137
137
|
},
|
|
138
138
|
})
|
|
139
139
|
|
|
140
|
-
// Signals (
|
|
140
|
+
// Signals (before save). Receivers run inside the write's transaction.
|
|
141
141
|
signals.preSave.connect(post, ({ instance }) => {
|
|
142
142
|
if (typeof instance.title === 'string') instance.title = instance.title.trim()
|
|
143
143
|
})
|
|
@@ -145,8 +145,7 @@ signals.preSave.connect(comment, ({ instance }) => {
|
|
|
145
145
|
if (typeof instance.body === 'string') instance.body = instance.body.trim()
|
|
146
146
|
})
|
|
147
147
|
|
|
148
|
-
// Realtime (
|
|
149
|
-
// through useModel (the site, the admin's "Approve selected", tasks) is published, after commit,
|
|
148
|
+
// Realtime: every comment write through useModel (the site, the admin's "Approve selected", tasks) is published, after commit,
|
|
150
149
|
// on `comments:post:<id>`. Who receives what is decided by `server/channels/comments.ts`.
|
|
151
150
|
broadcastModel(comment, {
|
|
152
151
|
channel: row => `comments:post:${row.postId}`,
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Public comments API
|
|
3
|
-
* object permission + `perform_create`), served at `/api/r/comments`.
|
|
2
|
+
* Public comments API, served at `/api/r/comments`.
|
|
4
3
|
*
|
|
5
4
|
* - Anyone lists approved comments: `GET /api/r/comments?postId=3`.
|
|
6
5
|
* - Signed-in users comment; the author comes from the session and `approved` is read-only.
|
|
@@ -55,7 +54,7 @@ export default defineResource(comment, {
|
|
|
55
54
|
return data
|
|
56
55
|
},
|
|
57
56
|
|
|
58
|
-
// One query for every author on the page
|
|
57
|
+
// One query for every author on the page.
|
|
59
58
|
async prefetch(rows, ctx) {
|
|
60
59
|
const ids = [...new Set(rows.map(r => r.authorId))]
|
|
61
60
|
if (!ids.length) return new Map<string, string>()
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Public, read-only posts API
|
|
2
|
+
* Public, read-only posts API.
|
|
3
3
|
* Visitors see published posts; editors with `blog.change_post` see drafts too and may write.
|
|
4
4
|
* It also makes `postId` options (`/api/r/comments/_choices/postId`) available to forms.
|
|
5
5
|
*/
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Example app test
|
|
2
|
+
* Example app test. Copy this pattern into your own layers:
|
|
3
3
|
* a fresh in-memory database per file, typed factories, and plain Drizzle queries.
|
|
4
4
|
*/
|
|
5
5
|
import * as coreSchema from '@knit-framework/core/schema'
|
package/template/versions.json
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
{
|
|
2
|
-
"knit": "0.
|
|
2
|
+
"knit": "0.4.1",
|
|
3
3
|
"nuxt": "^4.7.0",
|
|
4
4
|
"drizzleOrm": "^0.45.4",
|
|
5
5
|
"typescript": "^6.0.3",
|
|
@@ -9,5 +9,7 @@
|
|
|
9
9
|
"pg": "^8.23.1",
|
|
10
10
|
"typesPg": "^8.23.1",
|
|
11
11
|
"typesNode": "^26.6.11",
|
|
12
|
+
"eslint": "^10.16.0",
|
|
13
|
+
"nuxtEslint": "^1.17.0",
|
|
12
14
|
"packageManager": "pnpm@12.21.0"
|
|
13
15
|
}
|