create-knit 0.5.0 → 0.6.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/index.mjs CHANGED
@@ -115,7 +115,7 @@ function writeProject(target, name, examples) {
115
115
  vitest: versions.vitest,
116
116
  },
117
117
  // Project settings, read by the `knit` CLI and the core layer.
118
- knit: { app: 'apps/web', layersDir: 'layers', migrationsDir: 'server/database/migrations' },
118
+ knit: { app: 'apps/web', layersDir: 'layers', migrationsDir: 'server/database/migrations', template: versions.knit },
119
119
  }))
120
120
 
121
121
  writeFileSync(join(target, 'pnpm-workspace.yaml'), [
@@ -129,6 +129,8 @@ function writeProject(target, name, examples) {
129
129
  " '@parcel/watcher': true",
130
130
  " '@tailwindcss/oxide': true",
131
131
  ' unrs-resolver: true',
132
+ ' # Pulled in by OpenTelemetry\'s exporter (docs/observability.md); its script only prints a notice.',
133
+ ' protobufjs: false',
132
134
  ...(local ? ['', '# Local @knit-framework packages (KNIT_CREATE_TARBALLS)', 'overrides:', ` '@knit-framework/core': '${local.core}'`, ` '@knit-framework/cli': '${local.cli}'`] : []),
133
135
  '',
134
136
  ].join('\n'))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-knit",
3
- "version": "0.5.0",
3
+ "version": "0.6.1",
4
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": {
@@ -21,7 +21,7 @@ description: Add or change a model (Drizzle table) in a Knit app, end to end - s
21
21
  - Then run `pnpm manage makemigrations --name <slug>`.
22
22
  - If it says drizzle-kit must ask about a rename, split the change: add the new column, migrate, then drop the old one.
23
23
  5. **Apply it** with `pnpm manage migrate`. This works while `pnpm dev` runs, and `pnpm dev` also applies migrations when it starts.
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.
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). A running `pnpm dev` picks up a new or changed `admin.ts` without a restart.
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
27
  - `pnpm typecheck` and `pnpm lint` pass.
@@ -0,0 +1,26 @@
1
+ ---
2
+ name: knit-add-permission
3
+ description: Add a custom permission to a Knit app, enforce it on the server and grant it to a group or user - customPermissions, requirePermission, resource rules, seeds and a denied-request test. Use when asked to restrict who can do something, add a role-like capability ("only editors can publish"), or grant permissions in a Knit project.
4
+ ---
5
+
6
+ # Add a permission and grant it
7
+
8
+ 1. **Look first.**
9
+ - `knit_describe` with `section: "models"` lists each model's permissions (`<label>.view_<model>`, `add_`, `change_`, `delete_`).
10
+ - `knit_describe` with `section: "resources"` shows which rule guards each API action.
11
+ - The four model permissions may already be enough: use them before inventing a new one.
12
+ 2. **Declare a custom permission** in `layers/<app>/admin.ts`: `registerAdminModel(table, { customPermissions: ['publish_post'] })`. Its full name is `<label>.publish_post`, the label being the app label (`knit.app` in the layer's `nuxt.config.ts`).
13
+ 3. **Enforce it on the server.** The UI check `useAuth().can(perm)` only hides buttons.
14
+ - Server route: `await requirePermission(event, 'blog.publish_post')` in a route under `layers/<app>/server/api/` (auto-imported there).
15
+ - Resource: put the name in the action's rule, e.g. `permissions: { update: 'blog.publish_post' }` or `[isOwner('authorId'), 'blog.change_post']` (any rule allows).
16
+ 4. **Create the permission rows.** The server creates them when it starts. A running `pnpm dev` reloads on the `admin.ts` change; restart it if the permission is still unknown. Granting before that fails with `KNIT_E1903` (`knit_docs { "topic": "errors/KNIT_E1903" }`).
17
+ 5. **Grant it.**
18
+ - By hand: `/admin/auth/groups/:id` (a matrix per group) or `/admin/auth/users/:id`.
19
+ - In code (a seed or command): `permissionIds(db, [...])`, then `setGroupPermissions` and `addUserToGroup` from `@knit-framework/core/permissions`. The full seed is in the auth guide, "Grant a permission in code". Run it with `pnpm manage seed` (stop `pnpm dev` first on PGlite).
20
+ 6. **Verify.**
21
+ - `pnpm -s manage check --json` (MCP: `knit_check`) has no errors; `pnpm typecheck` passes.
22
+ - `knit_resource` shows the new rule on the resource's endpoints.
23
+ - An e2e test with one allowed request and one denied: 403 for a signed-in user without the permission, 401 when signed out. Follow the `knit-write-e2e-test` skill.
24
+ - Sign in as a user in the group and as one outside it, and try the action.
25
+
26
+ Guide: `knit_docs { "topic": "auth" }` (or `node_modules/@knit-framework/core/docs/auth.md`), section "Groups & permissions".
@@ -0,0 +1,25 @@
1
+ ---
2
+ name: knit-add-task
3
+ description: Add a background or scheduled task to a Knit app - generate it, write run(), enqueue it, schedule it with cron, run it by hand and test it. Use when asked for background work, a job, a queue, a cron job, or "do X every night" in a Knit project.
4
+ ---
5
+
6
+ # Add a background or scheduled task
7
+
8
+ 1. **Look first.**
9
+ - `knit_describe` with `section: "tasks"` (or `pnpm -s manage runtask --json`) lists the existing tasks and schedules.
10
+ - Note the backend: `NUXT_KNIT_TASKS_BACKEND` is `immediate` (default, runs in-process) or `database` (queued in a table, with retries).
11
+ 2. **Generate the file.** `pnpm manage generate task <app> <name>` writes `layers/<app>/server/tasks/<name>.ts` with task `<label>.<name>`. A running `pnpm dev` picks it up.
12
+ 3. **Write `run(payload, ctx)`.**
13
+ - Task files also run outside the server: no auto-imports. Import tables from `../database/schema` and use `ctx.db`.
14
+ - Write through `useModel(table, { db: ctx.db })` from `@knit-framework/core/models` so validators and signals run.
15
+ - Return something JSON-serialisable; throw to fail (the database backend retries up to `maxAttempts`).
16
+ - Scheduled work: add `schedule: '0 3 * * *'` (cron). It runs once per due time, however many processes run.
17
+ 4. **Enqueue it** from server code: `await enqueue('<label>.<name>', payload)` (auto-imported, checked against the task's payload type). Inside another task, use `ctx.enqueue(taskObject, payload)`.
18
+ 5. **Run it by hand.** `pnpm -s manage runtask <label>.<name> --payload '{"note":"hi"}' --json` prints `{ ok, result }` or `{ ok: false, error }`. On PGlite, stop `pnpm dev` first.
19
+ 6. **Test it.** Add `layers/<app>/test/tasks.test.ts` with `createTestDatabase` and `configureTasks()` before `enqueue()`, passing the task object, not its name. Copy the sample from the tasks guide, "Test a task" (it explains `KNIT_E1701`).
20
+ 7. **Verify.**
21
+ - `pnpm manage test --unit` and `pnpm typecheck` pass; `pnpm -s manage check --json` (MCP: `knit_check`) has no errors.
22
+ - `knit_describe` with `section: "tasks"` lists the task (and its schedule).
23
+ - With the database backend, the run appears in the queue table with status `succeeded` (the tasks guide, "Check that a task ran").
24
+
25
+ Guide: `knit_docs { "topic": "tasks" }` (or `node_modules/@knit-framework/core/docs/tasks.md`).
@@ -0,0 +1,22 @@
1
+ ---
2
+ name: knit-add-translation
3
+ description: Add or translate UI strings in a Knit app - t() in pages, layer locale files in every language, model and field labels for the admin, and a test that keeps the languages in step. Use when asked to translate a page or the admin, add a language, or add user-facing text in a Knit project.
4
+ ---
5
+
6
+ # Add or translate UI strings
7
+
8
+ 1. **Look first.**
9
+ - List `layers/<app>/i18n/locales/`: `pnpm manage startapp` writes `en.json`, `de.json` and `es.json` with the same keys.
10
+ - `knit_describe` with `section: "models"` gives each model's admin slug, the key used for model labels.
11
+ 2. **Use `t()` for every string** in pages and components: `const { t } = useI18n()`, then `t('shop.cart.title')`. Put your own keys under your app's namespace, never under `knit.*`. Plurals: `t('shop.cart.items', { count: n(items.length) }, items.length)`.
12
+ 3. **Admin labels** go under `knit.models.<slug>` (`label`, `labelPlural`, `fields.<field>`, `help.<field>`) and `knit.groups.<group key>`. English already comes from `admin.ts`; add other languages there.
13
+ 4. **Add the key to every locale file of the layer**, in the same place. A missing key silently falls back to English.
14
+ - A literal `{`, `}`, `@` or `|` breaks the whole language: write `{'@'}` for `@`.
15
+ - Pass sentence parts as named placeholders (`{model}`); don't glue fragments or lowercase in code.
16
+ 5. **A new language** is a new file, e.g. `layers/<app>/i18n/locales/fr.json`. Restart `pnpm dev` after adding a file; that is the only change that needs a restart.
17
+ 6. **Verify.**
18
+ - Add the key-parity test from the i18n guide ("Keep an app's languages in step") to `layers/<app>/test/locales.test.ts` if the layer has none, then run `pnpm manage test --unit`.
19
+ - `pnpm typecheck` passes.
20
+ - Open the page and the admin, switch the language in the user menu or with `<KnitLocaleSelect />`, and check that no English is left.
21
+
22
+ Guide: `knit_docs { "topic": "i18n" }` (or `node_modules/@knit-framework/core/docs/i18n.md`).
@@ -0,0 +1,27 @@
1
+ ---
2
+ name: knit-deploy
3
+ description: Deploy a Knit app to production - pick a host, set secrets, database, migrations, first admin, email and tasks, then verify with check --deploy and the health check. Use when asked to deploy, host, go live, ship to production, or prepare a Knit project for a server, Docker, Fly.io, Railway, Render, Vercel or Netlify.
4
+ ---
5
+
6
+ # Deploy to production
7
+
8
+ 1. **Look first.**
9
+ - `knit_docs { "topic": "deployment" }` has the host table and the checklist this skill follows.
10
+ - `knit_describe` with `section: "settings"` shows the current settings; `knit_describe` with `section: "tasks"` and `section: "channels"` tell you whether you need a worker and WebSockets.
11
+ 2. **Pick the host.** Long-running Node with a persistent disk works best (Docker, a VPS, Fly.io, Railway, Render). Vercel and Netlify have no WebSockets, worker or scheduled tasks. Read the host's page, e.g. `knit_docs { "topic": "deployment/fly" }`.
12
+ 3. **Make sure the build is clean.** `pnpm manage makemigrations --check` (no forgotten migration), `pnpm typecheck`, `pnpm manage test`, then `pnpm build`.
13
+ 4. **Set the production environment**, step by step from the guide's checklist:
14
+ - `NUXT_BETTER_AUTH_SECRET` (`openssl rand -base64 32`) and `NUXT_BETTER_AUTH_URL=https://your.domain`.
15
+ - Database: the embedded one for a single process with a persistent disk; otherwise `DATABASE_URL` (Postgres).
16
+ - Migrations: `NUXT_KNIT_AUTO_MIGRATE=always`, or `pnpm manage migrate` as a release step.
17
+ - `NUXT_MAIL_URL` and `NUXT_MAIL_FROM`; `NUXT_KNIT_TASKS_BACKEND=database` if there are tasks.
18
+ - Behind a TLS proxy: `NUXT_KNIT_SECURITY_TRUST_PROXY=true` and `NUXT_BETTER_AUTH_TRUST_PROXY=true`.
19
+ - Never commit secrets: set them in the host's settings, not in `apps/web/.env`.
20
+ 5. **Check before going live.** With those variables set, `pnpm -s manage check --deploy --json` (MCP: `knit_check` with `deploy: true`) has no errors. An error code has a page: `knit_docs { "topic": "errors/<code>" }`.
21
+ 6. **Deploy**, then create the first admin (the setup wizard is off in production): `KNIT_SUPERUSER_PASSWORD=… pnpm manage createsuperuser --no-input --email you@example.com`, where the CLI can reach the production database.
22
+ 7. **Verify.**
23
+ - The host's health check points at `/api/_knit/health`, and `curl https://your.domain/api/_knit/health` returns `{ "ok": true }`.
24
+ - Sign in at `/admin`; request a password reset to see that email is delivered.
25
+ - With tasks: enqueue one and see it succeed in the logs.
26
+
27
+ Guide: `knit_docs { "topic": "deployment" }` (or `node_modules/@knit-framework/core/docs/deployment/index.md`); settings in `knit_docs { "topic": "configuration" }`.
@@ -0,0 +1,26 @@
1
+ ---
2
+ name: knit-write-e2e-test
3
+ description: Write an end-to-end test for a Knit app that boots the real server and calls it over HTTP with createTestClient - first admin, sign-in, sign-up, allowed and denied requests. Use when asked to test an API, a permission, a page response or a whole flow over HTTP in a Knit project.
4
+ ---
5
+
6
+ # Write an end-to-end test
7
+
8
+ 1. **Look first.**
9
+ - `knit_routes` (or `pnpm -s manage routes --json`) lists the pages, API routes and resource endpoints to call.
10
+ - `knit_resource` with the slug gives the permission rule of each action: test one allowed and one denied request per rule.
11
+ - Logic without HTTP (a model, a task) belongs in a faster unit test: `pnpm manage generate test <app> <name> --table <export>`.
12
+ 2. **Create `apps/web/test/e2e/<name>.test.ts`.** Copy the sample from the testing guide, "End-to-end tests". It is self-contained:
13
+ - Set `NUXT_KNIT_DATA_DIR=memory://`, `NUXT_KNIT_AUTO_MIGRATE=always`, `NUXT_KNIT_ALLOW_SETUP=always` and a random `NUXT_BETTER_AUTH_SECRET` before `setup()`.
14
+ - `await setup({ rootDir: fileURLToPath(new URL('../..', import.meta.url)), server: true, browser: false })` from `@nuxt/test-utils/e2e`.
15
+ 3. **Make the users in `beforeAll`** (the server starts in `setup()`'s own hook):
16
+ - One `createTestClient(url('/'))` from `@knit-framework/core/testing` per user; each keeps its own cookies and sends the CSRF-safe `Origin`.
17
+ - First admin: `POST /api/_knit/setup` with `{ name, email, password }` (201), then `signIn(email, password)`. It is a superuser.
18
+ - Ordinary user: `POST /api/auth/sign-up/email` (200) also signs the client in.
19
+ 4. **Write the cases.** Responses are `{ status, data }` and never throw.
20
+ - Allowed: 200 or 201 and the returned data.
21
+ - Denied: 403 signed in, 401 signed out. Validation errors: 422 with `data.data.issues`.
22
+ - Tests in one file share the server and its data: create what each test needs, or order them.
23
+ 5. **Your schema changed?** Run `pnpm manage makemigrations --name <slug>` first: the server applies the migration files, not the schema.
24
+ 6. **Verify.** `pnpm manage test --e2e` passes (it builds the app; the first run is slow), and `pnpm typecheck` passes. Break the rule on purpose once (e.g. allow the denied action) and check the test fails.
25
+
26
+ Guide: `knit_docs { "topic": "testing" }` (or `node_modules/@knit-framework/core/docs/testing.md`).
@@ -17,7 +17,8 @@ Don't read files to find out what exists. Ask Knit:
17
17
  - `knit_migrations`, `knit_migration_plan`, `knit_pending_migration_sql`, `knit_sqlmigrate`.
18
18
  - `knit_docs`: the guides, e.g. `{ "topic": "models" }`. Also as MCP resources: `knit://docs/{topic}`, `knit://describe`, `knit://agents`.
19
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`.
20
+ - With `pnpm dev` running: `knit_errors` (recent server errors with hints and codes), `knit_outbox` (sent emails, e.g. a reset link), `knit_tasks` (task runs and the queue).
21
+ - Only when the server runs with `--allow-writes`: `knit_startapp`, `knit_generate`, `knit_makemigrations`, `knit_migrate`. Each takes `dryRun: true` to see what it would do first.
21
22
  - **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.
22
23
  - **Library docs:** the `nuxt`, `nuxt-ui` and `better-auth` MCP servers. Use them instead of guessing APIs.
23
24
 
@@ -51,7 +52,19 @@ Don't edit `node_modules/@knit-framework/*`: override instead (a page, component
51
52
  - **UI strings** go through `t()`; a literal `{`, `}`, `@` or `|` in a locale message breaks the whole language.
52
53
  - **Logging:** `useLogger('scope')` in server code, never `console.*`.
53
54
 
54
- ## 4. Change → verify loop
55
+ ## 4. Recipes
56
+
57
+ Step-by-step procedures for common jobs. Claude Code loads them as skills; any other agent can read and follow the file:
58
+
59
+ - Add or change a model: [`.claude/skills/knit-add-model/SKILL.md`](.claude/skills/knit-add-model/SKILL.md)
60
+ - Add a public API and forms: [`.claude/skills/knit-add-api/SKILL.md`](.claude/skills/knit-add-api/SKILL.md)
61
+ - Add a permission and grant it: [`.claude/skills/knit-add-permission/SKILL.md`](.claude/skills/knit-add-permission/SKILL.md)
62
+ - Add or translate UI strings: [`.claude/skills/knit-add-translation/SKILL.md`](.claude/skills/knit-add-translation/SKILL.md)
63
+ - Add a background or scheduled task: [`.claude/skills/knit-add-task/SKILL.md`](.claude/skills/knit-add-task/SKILL.md)
64
+ - Write an end-to-end test: [`.claude/skills/knit-write-e2e-test/SKILL.md`](.claude/skills/knit-write-e2e-test/SKILL.md)
65
+ - Deploy to production: [`.claude/skills/knit-deploy/SKILL.md`](.claude/skills/knit-deploy/SKILL.md)
66
+
67
+ ## 5. Change → verify loop
55
68
 
56
69
  ```bash
57
70
  pnpm -s manage check --json # schema, admin field names, settings, layers, migrations (or MCP: knit_check)
@@ -70,7 +83,7 @@ pnpm manage test --unit # fast; pnpm test runs e2e too (builds
70
83
  - **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`.
71
84
  - **Admin or API changes:** sign in at `/admin` and try list, create (including a validation error), edit and delete.
72
85
 
73
- ## 5. Gotchas
86
+ ## 6. Gotchas
74
87
 
75
88
  - **Relational queries need `relations()`.** `with: { author: true }` fails without a relation named `author`.
76
89
  - **Resources** must be *exported*. `_choices` for a foreign key goes through the target table's resource (no resource, no choices).
@@ -6,4 +6,4 @@ Project MCP servers (`.mcp.json`):
6
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`. New files: `pnpm manage startapp <app>` and `pnpm manage generate <kind> <app> <name>`.
9
+ Skills in `.claude/skills/`: `knit-add-model`, `knit-add-api`, `knit-add-permission`, `knit-add-translation`, `knit-add-task`, `knit-write-e2e-test`, `knit-deploy`. New files: `pnpm manage startapp <app>` and `pnpm manage generate <kind> <app> <name>`.
@@ -64,6 +64,12 @@ NUXT_BETTER_AUTH_URL=
64
64
  # Extra keys to redact, comma-separated (passwords, tokens, cookies… are always redacted)
65
65
  # NUXT_KNIT_LOG_REDACT=ssn,card.number
66
66
 
67
+ # ── Telemetry (OpenTelemetry traces, docs/observability.md) ─────────────────────
68
+ # Needs: pnpm add -w @opentelemetry/api @opentelemetry/sdk-node @opentelemetry/exporter-trace-otlp-http
69
+ # NUXT_KNIT_TELEMETRY_ENABLED=false
70
+ # NUXT_KNIT_TELEMETRY_SERVICE_NAME=knit
71
+ # OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
72
+
67
73
  # ── Site ────────────────────────────────────────────────────────────────────────
68
74
  # Public base URL for sitemaps and feeds (default: NUXT_BETTER_AUTH_URL, then the request)
69
75
  # NUXT_KNIT_SITE_URL=https://example.com
@@ -26,6 +26,7 @@ Agents working in a Knit project: read AGENTS.md, and use the `knit` MCP server
26
26
  - [Files & uploads](node_modules/@knit-framework/core/docs/files.md): `fileColumn`, uploads, disk/S3 storage
27
27
  - [Cache, messages & humanize](node_modules/@knit-framework/core/docs/utilities.md): `cached()`, flash messages, formatting helpers
28
28
  - [Sitemaps & feeds](node_modules/@knit-framework/core/docs/sitemaps-and-feeds.md): `/sitemap.xml`, RSS and Atom
29
+ - [Observability](node_modules/@knit-framework/core/docs/observability.md): OpenTelemetry traces (NUXT_KNIT_TELEMETRY_ENABLED), what each span contains, `withSpan`
29
30
  - [Logging](node_modules/@knit-framework/core/docs/logging.md): LogLayer: pretty dev output, JSON in production, request logs, redaction
30
31
  - [Security](node_modules/@knit-framework/core/docs/security.md): CSRF, security headers, CSP
31
32
  - [Testing](node_modules/@knit-framework/core/docs/testing.md): Test databases, factories, the HTTP client, `pnpm test`
@@ -1,5 +1,5 @@
1
1
  {
2
- "knit": "0.5.0",
2
+ "knit": "0.6.1",
3
3
  "nuxt": "^4.7.0",
4
4
  "drizzleOrm": "^0.45.4",
5
5
  "typescript": "^6.0.3",