create-knit 0.3.2 → 0.5.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/README.md +19 -1
- package/index.mjs +54 -16
- 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 +19 -12
- package/template/base/CLAUDE.md +2 -2
- package/template/base/_gitignore +1 -1
- package/template/base/apps/web/.env.example +21 -8
- 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 +4 -4
- package/template/base/docker/Dockerfile.dockerignore +1 -1
- package/template/base/docker/docker-compose.prod.yml +1 -1
- package/template/base/eslint.config.mjs +12 -0
- package/template/base/llms.txt +48 -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
|
@@ -17,29 +17,35 @@ const versions = JSON.parse(readFileSync(join(template, 'versions.json'), 'utf8'
|
|
|
17
17
|
const color = (code, text) => (process.stdout.isTTY && !process.env.NO_COLOR ? `\x1b[${code}m${text}\x1b[0m` : text)
|
|
18
18
|
const bold = text => color('1', text)
|
|
19
19
|
const dim = text => color('2', text)
|
|
20
|
+
// A coded error (KNIT_E2101…); this script runs before @knit-framework/core is installed.
|
|
21
|
+
const fail = (code, message) => Object.assign(new Error(message), { code })
|
|
22
|
+
const errorDocs = code => `https://3ig.github.io/knit/docs/errors/${code}`
|
|
20
23
|
|
|
21
24
|
function usage() {
|
|
22
|
-
return `Usage: pnpm create knit [dir] [--examples | --no-examples] [--no-install]
|
|
25
|
+
return `Usage: pnpm create knit [dir] [--examples | --no-examples] [--no-install] [--no-git]
|
|
23
26
|
|
|
24
27
|
dir Folder to create (default: asked, or "my-knit-app")
|
|
25
28
|
--examples Include the example blog and dashboard apps (default when asked: yes)
|
|
26
29
|
--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)
|
|
30
|
+
--no-install Only write the files (skip \`pnpm install\` and the initial migration)
|
|
31
|
+
--no-git Don't run \`git init\` and make the first commit (also skipped inside an
|
|
32
|
+
existing repository, or when git is not installed)`
|
|
28
33
|
}
|
|
29
34
|
|
|
30
35
|
function parseArgs(argv) {
|
|
31
|
-
const opts = { dir: undefined, examples: undefined, install: true }
|
|
36
|
+
const opts = { dir: undefined, examples: undefined, install: true, git: true }
|
|
32
37
|
for (const arg of argv) {
|
|
33
38
|
if (arg === '--examples') opts.examples = true
|
|
34
39
|
else if (arg === '--no-examples') opts.examples = false
|
|
35
40
|
else if (arg === '--no-install') opts.install = false
|
|
41
|
+
else if (arg === '--no-git') opts.git = false
|
|
36
42
|
else if (arg === '-h' || arg === '--help') {
|
|
37
43
|
console.log(usage())
|
|
38
44
|
process.exit(0)
|
|
39
45
|
}
|
|
40
|
-
else if (arg.startsWith('-')) throw
|
|
46
|
+
else if (arg.startsWith('-')) throw fail('KNIT_E2101', `Unknown option ${arg}\n\n${usage()}`)
|
|
41
47
|
else if (!opts.dir) opts.dir = arg
|
|
42
|
-
else throw
|
|
48
|
+
else throw fail('KNIT_E2101', `Unexpected argument ${arg}\n\n${usage()}`)
|
|
43
49
|
}
|
|
44
50
|
return opts
|
|
45
51
|
}
|
|
@@ -57,6 +63,7 @@ function localPackages() {
|
|
|
57
63
|
const files = readdirSync(dir)
|
|
58
64
|
const find = prefix => {
|
|
59
65
|
const file = files.find(f => f.startsWith(prefix) && f.endsWith('.tgz'))
|
|
66
|
+
// internal: KNIT_CREATE_TARBALLS is only set by Knit's own tests
|
|
60
67
|
if (!file) throw new Error(`KNIT_CREATE_TARBALLS: no ${prefix}*.tgz in ${dir}`)
|
|
61
68
|
return `file:${resolve(dir, file)}`
|
|
62
69
|
}
|
|
@@ -87,7 +94,9 @@ function writeProject(target, name, examples) {
|
|
|
87
94
|
manage: 'knit',
|
|
88
95
|
dev: 'pnpm --filter web dev',
|
|
89
96
|
build: 'pnpm --filter web build',
|
|
90
|
-
|
|
97
|
+
// The app (and every layer it extends), then tests and commands, which run outside Nuxt.
|
|
98
|
+
typecheck: 'pnpm -r typecheck && tsc -p tsconfig.test.json',
|
|
99
|
+
lint: 'eslint .',
|
|
91
100
|
check: 'knit check',
|
|
92
101
|
test: 'knit test',
|
|
93
102
|
services: 'docker compose up -d',
|
|
@@ -95,15 +104,18 @@ function writeProject(target, name, examples) {
|
|
|
95
104
|
},
|
|
96
105
|
devDependencies: {
|
|
97
106
|
'@knit-framework/cli': cli,
|
|
107
|
+
// Also at the root, so `node_modules/@knit-framework/core/docs` (the guides) is there to read.
|
|
108
|
+
'@knit-framework/core': core,
|
|
98
109
|
'@nuxt/test-utils': versions.testUtils,
|
|
99
110
|
'@types/node': versions.typesNode,
|
|
100
111
|
'@types/pg': versions.typesPg,
|
|
112
|
+
eslint: versions.eslint,
|
|
101
113
|
pg: versions.pg,
|
|
102
114
|
typescript: versions.typescript,
|
|
103
115
|
vitest: versions.vitest,
|
|
104
116
|
},
|
|
105
|
-
//
|
|
106
|
-
|
|
117
|
+
// Project settings, read by the `knit` CLI and the core layer.
|
|
118
|
+
knit: { app: 'apps/web', layersDir: 'layers', migrationsDir: 'server/database/migrations' },
|
|
107
119
|
}))
|
|
108
120
|
|
|
109
121
|
writeFileSync(join(target, 'pnpm-workspace.yaml'), [
|
|
@@ -133,14 +145,19 @@ function writeProject(target, name, examples) {
|
|
|
133
145
|
...Object.fromEntries(exampleLayers.map(l => [l, 'workspace:*'])),
|
|
134
146
|
nuxt: versions.nuxt,
|
|
135
147
|
},
|
|
136
|
-
devDependencies: { typescript: versions.typescript, 'vue-tsc': versions.vueTsc },
|
|
148
|
+
devDependencies: { '@nuxt/eslint': versions.nuxtEslint, eslint: versions.eslint, typescript: versions.typescript, 'vue-tsc': versions.vueTsc },
|
|
137
149
|
}))
|
|
138
150
|
writeFileSync(join(target, 'apps/web/nuxt.config.ts'), [
|
|
151
|
+
"import { fileURLToPath } from 'node:url'",
|
|
152
|
+
'',
|
|
139
153
|
'export default defineNuxtConfig({',
|
|
140
|
-
' // Installed apps
|
|
154
|
+
' // Installed apps. `pnpm manage startapp <name>` adds new ones here.',
|
|
141
155
|
` extends: [${['@knit-framework/core', ...exampleLayers.map(l => `../../layers/${l}`)].map(e => `'${e}'`).join(', ')}],`,
|
|
156
|
+
" modules: ['@nuxt/eslint'],",
|
|
142
157
|
" compatibilityDate: '2026-11-01',",
|
|
143
158
|
' devtools: { enabled: true },',
|
|
159
|
+
' // `pnpm lint` runs from the workspace root (eslint.config.mjs there), so layers are linted too.',
|
|
160
|
+
" eslint: { config: { rootDir: fileURLToPath(new URL('../..', import.meta.url)), autoInit: false } },",
|
|
144
161
|
'})',
|
|
145
162
|
'',
|
|
146
163
|
].join('\n'))
|
|
@@ -159,6 +176,8 @@ function writeProject(target, name, examples) {
|
|
|
159
176
|
'// `pnpm test` (= `knit test`): unit tests of your apps, and e2e tests that build apps/web.',
|
|
160
177
|
'export default defineConfig({',
|
|
161
178
|
' test: {',
|
|
179
|
+
' // A project without tests yet is not a failure.',
|
|
180
|
+
' passWithNoTests: true,',
|
|
162
181
|
' projects: [',
|
|
163
182
|
" { test: { name: 'unit', environment: 'node', include: ['layers/*/test/**/*.test.ts', 'apps/*/test/unit/**/*.test.ts'] } },",
|
|
164
183
|
" { test: { name: 'e2e', environment: 'node', include: ['apps/*/test/e2e/**/*.test.ts'], testTimeout: 60_000, hookTimeout: 300_000, fileParallelism: false } },",
|
|
@@ -178,11 +197,12 @@ function writeProject(target, name, examples) {
|
|
|
178
197
|
'pnpm manage startapp shop # a new app in layers/shop',
|
|
179
198
|
'pnpm manage makemigrations && pnpm manage migrate',
|
|
180
199
|
'pnpm manage describe # everything this project contains',
|
|
200
|
+
'pnpm lint && pnpm typecheck && pnpm test # what CI runs (.github/workflows/ci.yml)',
|
|
181
201
|
'```',
|
|
182
202
|
'',
|
|
183
|
-
'- Guides: `node_modules/@knit-framework/core/docs/` (start with `getting-started.md`), or online at https://github.
|
|
203
|
+
'- Guides: `node_modules/@knit-framework/core/docs/` (start with `getting-started.md`), or online at https://3ig.github.io/knit/docs',
|
|
184
204
|
'- Agents: see `AGENTS.md`; the `knit` MCP server is configured in `.mcp.json`.',
|
|
185
|
-
'- Upgrading Knit: https://github.
|
|
205
|
+
'- Upgrading Knit: https://3ig.github.io/knit/docs/upgrading',
|
|
186
206
|
...(examples
|
|
187
207
|
? [
|
|
188
208
|
'',
|
|
@@ -197,6 +217,18 @@ function writeProject(target, name, examples) {
|
|
|
197
217
|
].join('\n'))
|
|
198
218
|
}
|
|
199
219
|
|
|
220
|
+
/**
|
|
221
|
+
* `git init` and a first commit, so the project starts with a clean history to diff against.
|
|
222
|
+
* Quietly does nothing without git, inside an existing repository, or when git can't commit
|
|
223
|
+
* (no user.name/user.email yet, a signing prompt…).
|
|
224
|
+
*/
|
|
225
|
+
function initGit(target) {
|
|
226
|
+
const git = (...args) => spawnSync('git', args, { cwd: target, stdio: 'ignore' }).status === 0
|
|
227
|
+
if (!git('--version') || git('rev-parse', '--is-inside-work-tree')) return false
|
|
228
|
+
if (!git('init', '--quiet')) return false
|
|
229
|
+
return git('add', '--all') && git('commit', '--quiet', '--message', 'Initial commit from create-knit')
|
|
230
|
+
}
|
|
231
|
+
|
|
200
232
|
function run(command, args, cwd) {
|
|
201
233
|
console.log(dim(`$ ${command} ${args.join(' ')}`))
|
|
202
234
|
const result = spawnSync(command, args, { cwd, stdio: 'inherit', shell: process.platform === 'win32' })
|
|
@@ -207,12 +239,12 @@ async function main() {
|
|
|
207
239
|
const opts = parseArgs(process.argv.slice(2))
|
|
208
240
|
const interactive = process.stdin.isTTY && process.stdout.isTTY
|
|
209
241
|
const rl = interactive ? createInterface({ input: process.stdin, output: process.stdout }) : undefined
|
|
210
|
-
console.log(`\n${bold('Knit')} ${dim(`v${versions.knit}`)}: the batteries-included
|
|
242
|
+
console.log(`\n${bold('Knit')} ${dim(`v${versions.knit}`)}: the batteries-included full-stack framework for TypeScript\n`)
|
|
211
243
|
|
|
212
244
|
try {
|
|
213
245
|
const dir = opts.dir ?? await ask(rl, 'Project folder?', 'my-knit-app')
|
|
214
246
|
const target = resolve(dir)
|
|
215
|
-
if (existsSync(target) && readdirSync(target).length) throw
|
|
247
|
+
if (existsSync(target) && readdirSync(target).length) throw fail('KNIT_E2102', `${dir} already exists and is not empty.`)
|
|
216
248
|
const examples = opts.examples ?? (rl ? !/^n/i.test(await ask(rl, 'Include the example apps (blog, dashboard)?', 'Y/n')) : true)
|
|
217
249
|
rl?.close()
|
|
218
250
|
|
|
@@ -226,12 +258,16 @@ async function main() {
|
|
|
226
258
|
if (!hasPnpm) {
|
|
227
259
|
console.log(`\npnpm is required (Knit projects are pnpm workspaces): ${bold('npm install -g pnpm')} or ${bold('corepack enable')}, then:`)
|
|
228
260
|
console.log(` cd ${cd} && pnpm install && pnpm manage makemigrations --name initial`)
|
|
261
|
+
if (opts.git) initGit(target)
|
|
229
262
|
return
|
|
230
263
|
}
|
|
231
|
-
if (!run('pnpm', ['install'], target)) throw
|
|
232
|
-
if (!run('pnpm', ['manage', 'makemigrations', '--name', 'initial'], target)) throw
|
|
264
|
+
if (!run('pnpm', ['install'], target)) throw fail('KNIT_E2010', 'pnpm install failed (see above).')
|
|
265
|
+
if (!run('pnpm', ['manage', 'makemigrations', '--name', 'initial'], target)) throw fail('KNIT_E2103', 'Creating the initial migration failed (see above).')
|
|
233
266
|
}
|
|
234
267
|
|
|
268
|
+
// Last, so the first commit holds the lockfile and the initial migration too.
|
|
269
|
+
if (opts.git && initGit(target)) console.log(dim('Initialized a git repository with the first commit.'))
|
|
270
|
+
|
|
235
271
|
console.log(`\n${bold('Next:')}`)
|
|
236
272
|
if (cd) console.log(` cd ${cd}`)
|
|
237
273
|
if (!opts.install) console.log(' pnpm install && pnpm manage makemigrations --name initial')
|
|
@@ -245,5 +281,7 @@ async function main() {
|
|
|
245
281
|
|
|
246
282
|
main().catch((error) => {
|
|
247
283
|
console.error(`\n${color('31', 'Error:')} ${error instanceof Error ? error.message : String(error)}`)
|
|
284
|
+
const code = error?.code
|
|
285
|
+
if (typeof code === 'string' && /^KNIT_E\d{4}$/.test(code)) console.error(dim(`See ${code} · ${errorDocs(code)}`))
|
|
248
286
|
process.exit(1)
|
|
249
287
|
})
|
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.5.0",
|
|
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,25 @@ 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.
|
|
14
|
-
- `
|
|
15
|
-
- `
|
|
16
|
-
- `
|
|
17
|
-
-
|
|
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.
|
|
15
|
+
- `knit_check`: run after changes. `knit_doctor`: when the environment seems broken (Node, packages, database, ports), then every check.
|
|
16
|
+
- `knit_reference`: the exact signature, import path, options and example of any Knit function, type, component, setting or command, e.g. `{ "symbol": "defineResource" }`. Use it instead of reading Knit's source.
|
|
17
|
+
- `knit_migrations`, `knit_migration_plan`, `knit_pending_migration_sql`, `knit_sqlmigrate`.
|
|
18
|
+
- `knit_docs`: the guides, e.g. `{ "topic": "models" }`. Also as MCP resources: `knit://docs/{topic}`, `knit://describe`, `knit://agents`.
|
|
19
|
+
- **Error codes:** an error with a code (`KNIT_E1203`) has a page that says why and how to fix it: read it with `knit_docs { "topic": "errors/KNIT_E1203" }` before changing code.
|
|
20
|
+
- Only when the server runs with `--allow-writes`: `knit_startapp`, `knit_generate`, `knit_makemigrations`, `knit_migrate`.
|
|
21
|
+
- **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
22
|
- **Library docs:** the `nuxt`, `nuxt-ui` and `better-auth` MCP servers. Use them instead of guessing APIs.
|
|
19
23
|
|
|
20
24
|
## 2. Where code goes
|
|
21
25
|
|
|
22
26
|
| You want | Put it in |
|
|
23
27
|
| --- | --- |
|
|
24
|
-
| A new app | `pnpm manage startapp <name>` → `layers/<name>/` (adds it to `apps/web/nuxt.config.ts` `extends`) |
|
|
28
|
+
| 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`) |
|
|
29
|
+
| 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
30
|
| Models | `layers/<app>/server/database/schema.ts` (tables named `<app>_<model>`, `relations()` next to them) |
|
|
26
31
|
| Admin | `layers/<app>/admin.ts` → `registerAdminModel(table, { listDisplay, searchFields, … })` |
|
|
27
32
|
| A public REST API + forms | `layers/<app>/server/resources/<name>.ts` → `export default defineResource(table, { permissions, … })`; `<KnitModelForm resource="…">` in pages |
|
|
@@ -33,7 +38,7 @@ Don't read files to find out what exists. Ask Knit:
|
|
|
33
38
|
| Translations | `layers/<app>/i18n/locales/{en,de,es}.json` |
|
|
34
39
|
| Settings | `apps/web/nuxt.config.ts`, env vars in `apps/web/.env` (see `apps/web/.env.example`) |
|
|
35
40
|
|
|
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/.
|
|
41
|
+
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
42
|
|
|
38
43
|
## 3. Conventions
|
|
39
44
|
|
|
@@ -49,16 +54,18 @@ Don't edit `node_modules/@knit-framework/*`: override instead (a page, component
|
|
|
49
54
|
## 4. Change → verify loop
|
|
50
55
|
|
|
51
56
|
```bash
|
|
52
|
-
pnpm -s manage check --json # schema, admin field names, layers, migrations (or MCP: knit_check)
|
|
57
|
+
pnpm -s manage check --json # schema, admin field names, settings, layers, migrations (or MCP: knit_check)
|
|
53
58
|
pnpm manage makemigrations --name <slug> # after a schema change; --dry-run to preview
|
|
54
59
|
pnpm manage migrate # works while pnpm dev runs; pnpm dev also applies on start
|
|
55
60
|
pnpm typecheck # must pass
|
|
61
|
+
pnpm lint # ESLint (projects created with `pnpm create knit`)
|
|
56
62
|
pnpm manage test --unit # fast; pnpm test runs e2e too (builds the app)
|
|
57
63
|
```
|
|
58
64
|
|
|
59
|
-
- **
|
|
65
|
+
- **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
66
|
- **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
67
|
- **PGlite is single-process.** `migrate`, `showmigrations`, `removemigration` and `check` go through a running `pnpm dev`. `shell`, `createsuperuser`, `loaddata` and similar need it stopped.
|
|
68
|
+
- **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
69
|
- **Undo an unapplied `makemigrations`** with `pnpm manage removemigration`.
|
|
63
70
|
- **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
71
|
- **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
|
@@ -9,15 +9,26 @@ NUXT_BETTER_AUTH_URL=
|
|
|
9
9
|
|
|
10
10
|
# Use a Postgres server instead of the embedded PGlite database (app + `pnpm manage`).
|
|
11
11
|
# DATABASE_URL=postgres://user:password@localhost:5432/knit
|
|
12
|
+
# When DATABASE_URL goes through a transaction pooler (PgBouncer, a provider's pooled URL): the direct
|
|
13
|
+
# connection, for migrations and the realtime listener (docs/postgres.md)
|
|
14
|
+
# DATABASE_DIRECT_URL=postgres://user:password@db.internal:5432/knit
|
|
15
|
+
# Postgres pool per server process, idle timeout (s), statement timeout (ms, 0 = none), TLS (require | no-verify)
|
|
16
|
+
# NUXT_KNIT_DATABASE_POOL_MAX=10
|
|
17
|
+
# NUXT_KNIT_DATABASE_IDLE_TIMEOUT=10
|
|
18
|
+
# NUXT_KNIT_DATABASE_STATEMENT_TIMEOUT=0
|
|
19
|
+
# NUXT_KNIT_DATABASE_SSL=
|
|
12
20
|
|
|
13
21
|
# PGlite data directory (relative to apps/web, or to the folder holding a deployed .output). Default: .data/pglite
|
|
14
|
-
#
|
|
22
|
+
# NUXT_KNIT_DATA_DIR=.data/pglite
|
|
23
|
+
|
|
24
|
+
# Read migrations from this folder at startup instead of the copy bundled into the build
|
|
25
|
+
# NUXT_KNIT_MIGRATIONS_DIR=server/database/migrations
|
|
15
26
|
|
|
16
27
|
# Apply pending migrations at startup: dev (default) | always | never
|
|
17
|
-
#
|
|
28
|
+
# NUXT_KNIT_AUTO_MIGRATE=dev
|
|
18
29
|
|
|
19
30
|
# First-admin setup wizard at /admin/setup: dev (default) | always | never
|
|
20
|
-
#
|
|
31
|
+
# NUXT_KNIT_ALLOW_SETUP=dev
|
|
21
32
|
|
|
22
33
|
# Site name used in auth emails. Default: Knit
|
|
23
34
|
# NUXT_BETTER_AUTH_APP_NAME=Knit
|
|
@@ -35,14 +46,14 @@ NUXT_BETTER_AUTH_URL=
|
|
|
35
46
|
# NUXT_MAIL_MAILER=
|
|
36
47
|
# SMTP connection URL, e.g. smtp://user:pass@smtp.example.com:587 or smtps://user:pass@host:465
|
|
37
48
|
# NUXT_MAIL_URL=
|
|
38
|
-
# Default sender
|
|
49
|
+
# Default sender address
|
|
39
50
|
# NUXT_MAIL_FROM=Knit <webmaster@localhost>
|
|
40
51
|
|
|
41
|
-
# Used by `pnpm manage createsuperuser --
|
|
42
|
-
#
|
|
52
|
+
# Used by `pnpm manage createsuperuser --no-input`
|
|
53
|
+
# KNIT_SUPERUSER_PASSWORD=
|
|
43
54
|
|
|
44
|
-
# Used by `pnpm manage changepassword <email> --
|
|
45
|
-
#
|
|
55
|
+
# Used by `pnpm manage changepassword <email> --no-input`
|
|
56
|
+
# KNIT_NEW_PASSWORD=
|
|
46
57
|
# ── Logging (LogLayer) ─────────────────────────────────────────────────────────
|
|
47
58
|
# trace | debug | info | warn | error | fatal (default: debug in dev, info in production)
|
|
48
59
|
# NUXT_KNIT_LOG_LEVEL=info
|
|
@@ -88,6 +99,8 @@ NUXT_BETTER_AUTH_URL=
|
|
|
88
99
|
# NUXT_KNIT_TASKS_POLL_INTERVAL=1000
|
|
89
100
|
# NUXT_KNIT_TASKS_MAX_ATTEMPTS=3
|
|
90
101
|
# NUXT_KNIT_TASKS_RETRY_DELAY=10
|
|
102
|
+
# Seconds after which a running task counts as interrupted (its worker died) and is queued again
|
|
103
|
+
# NUXT_KNIT_TASKS_STALE_AFTER=3600
|
|
91
104
|
|
|
92
105
|
# ── Realtime (SSE + WebSocket channels) ─────────────────────────────────────────
|
|
93
106
|
# memory (default, one process) | postgres (LISTEN/NOTIFY on DATABASE_URL: several
|
|
@@ -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
|
+
})
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
# docker build -f docker/Dockerfile -t knit . # the app (default target: runtime)
|
|
6
6
|
# docker build -f docker/Dockerfile -t knit-tools --target tools . # one-off `pnpm manage …` commands
|
|
7
7
|
#
|
|
8
|
-
# See docs/deployment
|
|
8
|
+
# See docs/deployment/.
|
|
9
9
|
|
|
10
10
|
ARG NODE_VERSION=24
|
|
11
11
|
|
|
@@ -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"]
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
# cp docker/.env.production.example docker/.env.production # then fill in the secrets
|
|
4
4
|
# docker compose -f docker/docker-compose.prod.yml --env-file docker/.env.production up -d --build
|
|
5
5
|
#
|
|
6
|
-
# See docs/deployment
|
|
6
|
+
# See docs/deployment/. Put a TLS-terminating proxy (Caddy, nginx, Traefik…) in front.
|
|
7
7
|
|
|
8
8
|
name: knit-prod
|
|
9
9
|
|
|
@@ -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,48 @@
|
|
|
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/index.md): production checklist, what Knit needs from a host, and one page per host (Docker, VPS with systemd and Caddy, Fly.io, Railway, Render; Vercel and Netlify with limits; Cloudflare not supported)
|
|
35
|
+
- [Postgres in production](node_modules/@knit-framework/core/docs/postgres.md): moving off PGlite, DATABASE_DIRECT_URL and poolers, zero-downtime migrations, backups, several instances
|
|
36
|
+
- [Upgrading](node_modules/@knit-framework/core/docs/upgrading.md): updating the @knit-framework packages, migrating Knit's tables, removing the examples
|
|
37
|
+
- [How Knit works](node_modules/@knit-framework/core/docs/architecture.md): Discovery, generated modules, request lifecycle
|
|
38
|
+
- [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
|
|
39
|
+
- [Troubleshooting](node_modules/@knit-framework/core/docs/troubleshooting.md): Common errors and fixes
|
|
40
|
+
- [API reference](node_modules/@knit-framework/core/docs/reference/index.md): every public function, type, component, setting and command with signatures and examples, generated from the source; `node_modules/@knit-framework/core/docs/reference/reference.json` has the same as data
|
|
41
|
+
- [Error codes](node_modules/@knit-framework/core/docs/errors/index.md): every `KNIT_E…` code with its cause and fix; read one as `node_modules/@knit-framework/core/docs/errors/<code>.md`
|
|
42
|
+
- [Roadmap](node_modules/@knit-framework/core/docs/roadmap.md): what's proposed next, and why
|
|
43
|
+
- [Coming from Django](node_modules/@knit-framework/core/docs/coming-from-django.md): every Django concept and its Knit equivalent
|
|
44
|
+
|
|
45
|
+
## Optional
|
|
46
|
+
|
|
47
|
+
- [Framework internals](node_modules/@knit-framework/core/AGENTS.md): how Knit works inside
|
|
48
|
+
- [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.5.0",
|
|
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
|
}
|