create-knit 0.9.0 → 0.10.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/index.mjs CHANGED
@@ -61,7 +61,7 @@ function localPackages() {
61
61
  const dir = process.env.KNIT_CREATE_TARBALLS
62
62
  if (!dir) return undefined
63
63
  const files = readdirSync(dir)
64
- const find = prefix => {
64
+ const find = (prefix) => {
65
65
  const file = files.find(f => f.startsWith(prefix) && f.endsWith('.tgz'))
66
66
  // internal: KNIT_CREATE_TARBALLS is only set by Knit's own tests
67
67
  if (!file) throw new Error(`KNIT_CREATE_TARBALLS: no ${prefix}*.tgz in ${dir}`)
@@ -91,15 +91,15 @@ function writeProject(target, name, examples) {
91
91
  packageManager: versions.packageManager,
92
92
  engines: { node: '>=22' },
93
93
  scripts: {
94
- manage: 'knit',
95
- dev: 'pnpm --filter web dev',
96
- build: 'pnpm --filter web build',
94
+ 'manage': 'knit',
95
+ 'dev': 'pnpm --filter web dev',
96
+ 'build': 'pnpm --filter web build',
97
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 .',
100
- check: 'knit check',
101
- test: 'knit test',
102
- services: 'docker compose up -d',
98
+ 'typecheck': 'pnpm -r typecheck && tsc -p tsconfig.test.json',
99
+ 'lint': 'eslint .',
100
+ 'check': 'knit check',
101
+ 'test': 'knit test',
102
+ 'services': 'docker compose up -d',
103
103
  'services:down': 'docker compose down',
104
104
  },
105
105
  devDependencies: {
@@ -109,10 +109,10 @@ function writeProject(target, name, examples) {
109
109
  '@nuxt/test-utils': versions.testUtils,
110
110
  '@types/node': versions.typesNode,
111
111
  '@types/pg': versions.typesPg,
112
- eslint: versions.eslint,
113
- pg: versions.pg,
114
- typescript: versions.typescript,
115
- vitest: versions.vitest,
112
+ 'eslint': versions.eslint,
113
+ 'pg': versions.pg,
114
+ 'typescript': versions.typescript,
115
+ 'vitest': versions.vitest,
116
116
  },
117
117
  // Project settings, read by the `knit` CLI and the core layer.
118
118
  knit: { app: 'apps/web', layersDir: 'layers', migrationsDir: 'server/database/migrations', template: versions.knit },
@@ -126,8 +126,8 @@ function writeProject(target, name, examples) {
126
126
  'allowBuilds:',
127
127
  ' esbuild: true',
128
128
  ' vue-demi: true',
129
- " '@parcel/watcher': true",
130
- " '@tailwindcss/oxide': true",
129
+ ' \'@parcel/watcher\': true',
130
+ ' \'@tailwindcss/oxide\': true',
131
131
  ' unrs-resolver: true',
132
132
  ' # Pulled in by OpenTelemetry\'s exporter (docs/observability.md); its script only prints a notice.',
133
133
  ' protobufjs: false',
@@ -145,21 +145,21 @@ function writeProject(target, name, examples) {
145
145
  dependencies: {
146
146
  '@knit-framework/core': core,
147
147
  ...Object.fromEntries(exampleLayers.map(l => [l, 'workspace:*'])),
148
- nuxt: versions.nuxt,
148
+ 'nuxt': versions.nuxt,
149
149
  },
150
- devDependencies: { '@nuxt/eslint': versions.nuxtEslint, eslint: versions.eslint, typescript: versions.typescript, 'vue-tsc': versions.vueTsc },
150
+ devDependencies: { '@nuxt/eslint': versions.nuxtEslint, 'eslint': versions.eslint, 'typescript': versions.typescript, 'vue-tsc': versions.vueTsc },
151
151
  }))
152
152
  writeFileSync(join(target, 'apps/web/nuxt.config.ts'), [
153
- "import { fileURLToPath } from 'node:url'",
153
+ 'import { fileURLToPath } from \'node:url\'',
154
154
  '',
155
155
  'export default defineNuxtConfig({',
156
156
  ' // Installed apps. `pnpm manage startapp <name>` adds new ones here.',
157
157
  ` extends: [${['@knit-framework/core', ...exampleLayers.map(l => `../../layers/${l}`)].map(e => `'${e}'`).join(', ')}],`,
158
- " modules: ['@nuxt/eslint'],",
159
- " compatibilityDate: '2026-11-01',",
158
+ ' modules: [\'@nuxt/eslint\'],',
159
+ ' compatibilityDate: \'2026-11-01\',',
160
160
  ' devtools: { enabled: true },',
161
161
  ' // `pnpm lint` runs from the workspace root (eslint.config.mjs there), so layers are linted too.',
162
- " eslint: { config: { rootDir: fileURLToPath(new URL('../..', import.meta.url)), autoInit: false } },",
162
+ ' eslint: { config: { rootDir: fileURLToPath(new URL(\'../..\', import.meta.url)), autoInit: false } },',
163
163
  '})',
164
164
  '',
165
165
  ].join('\n'))
@@ -173,7 +173,7 @@ function writeProject(target, name, examples) {
173
173
  writeFileSync(join(target, 'layers/.gitkeep'), '')
174
174
 
175
175
  writeFileSync(join(target, 'vitest.config.ts'), [
176
- "import { defineConfig } from 'vitest/config'",
176
+ 'import { defineConfig } from \'vitest/config\'',
177
177
  '',
178
178
  '// `pnpm test` (= `knit test`): unit tests of your apps, and e2e tests that build apps/web.',
179
179
  'export default defineConfig({',
@@ -181,8 +181,8 @@ function writeProject(target, name, examples) {
181
181
  ' // A project without tests yet is not a failure.',
182
182
  ' passWithNoTests: true,',
183
183
  ' projects: [',
184
- " { test: { name: 'unit', environment: 'node', include: ['layers/*/test/**/*.test.ts', 'apps/*/test/unit/**/*.test.ts'] } },",
185
- " { test: { name: 'e2e', environment: 'node', include: ['apps/*/test/e2e/**/*.test.ts'], testTimeout: 60_000, hookTimeout: 300_000, fileParallelism: false } },",
184
+ ' { test: { name: \'unit\', environment: \'node\', include: [\'layers/*/test/**/*.test.ts\', \'apps/*/test/unit/**/*.test.ts\'] } },',
185
+ ' { test: { name: \'e2e\', environment: \'node\', include: [\'apps/*/test/e2e/**/*.test.ts\'], testTimeout: 60_000, hookTimeout: 300_000, fileParallelism: false } },',
186
186
  ' ],',
187
187
  ' },',
188
188
  '})',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-knit",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
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": {
@@ -29,6 +29,7 @@ Don't read files to find out what exists. Ask Knit:
29
29
  | 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`) |
30
30
  | 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 |
31
31
  | Models | `layers/<app>/server/database/schema.ts` (tables named `<app>_<model>`, `relations()` next to them) |
32
+ | Model options | `defineModelMeta(table, { verboseName, ordering, searchFields, softDelete, history, search, policy })` below the tables in `schema.ts`. Say them once: the admin and every resource use the names, order and search fields unless they set their own |
32
33
  | Admin | `layers/<app>/admin.ts` → `registerAdminModel(table, { listDisplay, searchFields, … })`; `registerAdminPage`, `registerDashboardCard`; your admin components in `layers/<app>/app/admin/*.vue` (widgets, computed columns, panels, cards) |
33
34
  | A public REST API + forms | `layers/<app>/server/resources/<name>.ts` → `export default defineResource(table, { permissions, … })`; `<KnitModelForm resource="…">` in pages |
34
35
  | Pages / components | `layers/<app>/app/pages/**`, `app/components/**` (Nuxt conventions) |
@@ -48,6 +49,10 @@ Don't edit `node_modules/@knit-framework/*`: override instead (a page, component
48
49
  - **Cross-app references** import the table: `import { user } from '@knit-framework/core/schema'`.
49
50
  - **Permissions on the server:** `requirePermission(event, 'shop.change_product')`. In the UI, `useAuth().can(perm)` is display-only.
50
51
  - **Row-level rules** ("users change only their own rows") are a `policy` in the model's meta, not checks in each route. In your own routes, act as the user so it applies: `useModel(table).as(await requestActor(event))`; plain `useModel(table)` and `useDB()` skip it. See `node_modules/@knit-framework/core/docs/permissions.md`.
52
+ - **Soft delete:** a model with `softDelete` in its meta keeps deleted rows in the table. `useModel`, the admin and resources skip them; a raw `useDB()` query does not, so add `notDeletedWhere(table)` to its `where` (`pnpm manage describe` shows which models: `soft delete (deletedAt)`).
53
+ - **Sessions are cached for reads** (60 s, `NUXT_KNIT_AUTH_SESSION_CACHE`): `requireAuth`/`requirePermission` in a `GET` handler may see a session up to a minute old; writes, the admin API and anything after the user's own write are always fresh. See `node_modules/@knit-framework/core/docs/auth.md#session-cache` before relying on an instant ban in a `GET`.
54
+ - **Which permission goes where** (model permissions, admin switches, resource and endpoint rules, row policies): the table at the top of `node_modules/@knit-framework/core/docs/permissions.md`.
55
+ - **Public API only:** use what the API reference lists (`knit_reference`, `node_modules/@knit-framework/core/docs/reference/`). An export tagged `@internal` or missing from the reference is Knit's plumbing and may change in any release; one marked Experimental may change in a minor release.
51
56
  - **Custom JSON routes use `defineEndpoint`**, not a bare `defineEventHandler`: it requires a `permission`, validates `body`/`query`/`params` with zod (`z` comes from `@knit-framework/core/endpoints`; query and params arrive as strings, so `z.coerce`), answers with the same 422 `data.issues` as model validation, and lists the route in `/api/r/openapi.json`. Plain handlers are for non-JSON routes (downloads, redirects, raw-body webhooks). See `node_modules/@knit-framework/core/docs/endpoints.md`.
52
57
  - **Resources default to deny for writes.** List `fields` explicitly for public APIs. Server-set values (e.g. `authorId`) belong in `beforeCreate`.
53
58
  - **Files outside Nitro** (tasks, commands, seeds) don't get auto-imports: import from `@knit-framework/core/*` and use the `db`/`ctx.db` you are given.
@@ -67,10 +67,12 @@ NUXT_BETTER_AUTH_URL=
67
67
  # NUXT_KNIT_AUTH_TWO_FACTOR=optional
68
68
  # Passkeys (WebAuthn): true (default) | false
69
69
  # NUXT_KNIT_AUTH_PASSKEYS=true
70
+ # Seconds a session read may come from a signed cookie instead of the database (0 = always ask)
71
+ # NUXT_KNIT_AUTH_SESSION_CACHE=60
70
72
  # Organizations (docs/organizations.md): users create them, invite members and switch the active one
71
73
  # NUXT_KNIT_AUTH_ORGANIZATIONS_ENABLED=false
72
74
  # NUXT_KNIT_AUTH_ORGANIZATIONS_ALLOW_USER_TO_CREATE=true
73
- # Creator's role: owner (default) | admin
75
+ # Creator's role: always owner (admin is refused: the creator could not delete the organization)
74
76
  # NUXT_KNIT_AUTH_ORGANIZATIONS_CREATOR_ROLE=owner
75
77
  # Invitation lifetime in seconds (default 48 hours)
76
78
  # NUXT_KNIT_AUTH_ORGANIZATIONS_INVITATION_EXPIRES_IN=172800
@@ -108,9 +110,13 @@ NUXT_BETTER_AUTH_URL=
108
110
  # ── Site ────────────────────────────────────────────────────────────────────────
109
111
  # Public base URL for sitemaps and feeds (default: NUXT_BETTER_AUTH_URL, then the request)
110
112
  # NUXT_KNIT_SITE_URL=https://example.com
113
+ # Development only: more host names the Knit DevTools page works under (default: localhost,
114
+ # *.localhost, 127.0.0.1 and [::1], from this machine). Comma-separated; .name covers subdomains.
115
+ # NUXT_KNIT_DEV_ALLOWED_HOSTS=myapp.test
111
116
 
112
117
  # ── Security (headers, CSRF, CSP) ───────────────────────────────────────────────
113
- # Origin-based CSRF guard for cookie-authenticated POST/PUT/PATCH/DELETE to /api/** (default true)
118
+ # Origin-based CSRF guard for cookie-authenticated POST/PUT/PATCH/DELETE to /api/** and to
119
+ # defineEndpoint() routes outside it (default true)
114
120
  # NUXT_KNIT_SECURITY_CSRF=true
115
121
  # Extra origins allowed to make state-changing requests, comma-separated
116
122
  # NUXT_KNIT_SECURITY_TRUSTED_ORIGINS=https://app.example.com
@@ -14,13 +14,13 @@ Agents working in a Knit project: read AGENTS.md, and use the `knit` MCP server
14
14
 
15
15
  - [Development environment](node_modules/@knit-framework/core/docs/development.md): Native Node, or Docker Compose with Postgres and Mailpit
16
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
17
+ - [Models & data](node_modules/@knit-framework/core/docs/models.md): Tables, migrations, `useModel`, `defineModelMeta` (names, ordering, search fields), validators, `clean()`, signals, soft delete, change history, full-text search, Postgres
18
18
  - [Resources & forms](node_modules/@knit-framework/core/docs/resources.md): `defineResource` REST APIs, permissions, scoping, OpenAPI, `useResource`, `<KnitModelForm>`
19
19
  - [Custom endpoints](node_modules/@knit-framework/core/docs/endpoints.md): `defineEndpoint` routes with a permission, validated input and an entry in the OpenAPI document
20
20
  - [Rendering modes](node_modules/@knit-framework/core/docs/rendering.md): SSR by default; SPA per route, per path or per layer; prerender and caching
21
- - [Admin](node_modules/@knit-framework/core/docs/admin.md): `registerAdminModel` options, filters, actions, inlines, history, user tools, REST API
22
- - [Auth & permissions](node_modules/@knit-framework/core/docs/auth.md): Users, staff, superusers, groups, permissions, `/accounts/*` pages
23
- - [Row-level permissions](node_modules/@knit-framework/core/docs/permissions.md): `defineModelMeta(table, { policy })`, `useModel(table).as(actor)`, what the admin, resources and realtime apply
21
+ - [Admin](node_modules/@knit-framework/core/docs/admin.md): `registerAdminModel` options, filters, actions, inlines, history, trash, custom pages, dashboard cards, panels, computed columns and widgets, user tools, REST API
22
+ - [Auth & permissions](node_modules/@knit-framework/core/docs/auth.md): Users, staff, superusers, groups, permissions, `/accounts/*` pages, sign-in options, the session cache
23
+ - [Row-level permissions](node_modules/@knit-framework/core/docs/permissions.md): which permission goes where (model permissions, admin switches, resource rules, policies), `defineModelMeta(table, { policy })`, `useModel(table).as(actor)`, what the admin, resources and realtime apply
24
24
  - [Organizations](node_modules/@knit-framework/core/docs/organizations.md): `NUXT_KNIT_AUTH_ORGANIZATIONS_ENABLED`, invitations, roles, `inActiveOrganization` / `hasOrganizationRole` / `assignOrganization`, `useOrganization()`, `switchOrganization()` in tests
25
25
  - [Internationalization](node_modules/@knit-framework/core/docs/i18n.md): Translations, locales per layer, translating models, the language switcher
26
26
  - [Email](node_modules/@knit-framework/core/docs/email.md): `sendMail()`, mailers, templates, auth emails
@@ -32,13 +32,13 @@ Agents working in a Knit project: read AGENTS.md, and use the `knit` MCP server
32
32
  - [Observability](node_modules/@knit-framework/core/docs/observability.md): OpenTelemetry traces (NUXT_KNIT_TELEMETRY_ENABLED), what each span contains, `withSpan`
33
33
  - [Logging](node_modules/@knit-framework/core/docs/logging.md): LogLayer: pretty dev output, JSON in production, request logs, redaction
34
34
  - [Security](node_modules/@knit-framework/core/docs/security.md): CSRF, security headers, CSP
35
- - [Testing](node_modules/@knit-framework/core/docs/testing.md): Test databases, factories, the HTTP client, `pnpm test`
35
+ - [Testing](node_modules/@knit-framework/core/docs/testing.md): Test databases (PGlite, or Postgres with `KNIT_TEST_DATABASE_URL`), factories, the HTTP client, `pnpm test`
36
36
  - [Knit in Nuxt DevTools](node_modules/@knit-framework/core/docs/devtools.md): the dev-only Knit tab (models, routes, tasks, mail, realtime, errors, migrations), its actions and who may read it
37
37
  - [`manage` CLI](node_modules/@knit-framework/core/docs/cli.md): Every command, `startapp` and `generate`, JSON output for scripts and agents, seeds, custom commands
38
38
  - [Configuration](node_modules/@knit-framework/core/docs/configuration.md): Every environment variable and setting
39
39
  - [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)
40
40
  - [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
41
- - [Upgrading](node_modules/@knit-framework/core/docs/upgrading.md): updating the @knit-framework packages, migrating Knit's tables, removing the examples
41
+ - [Upgrading](node_modules/@knit-framework/core/docs/upgrading.md): updating the @knit-framework packages, migrating Knit's tables, what counts as public API, removing the examples
42
42
  - [How Knit works](node_modules/@knit-framework/core/docs/architecture.md): Discovery, generated modules, request lifecycle
43
43
  - [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
44
44
  - [Troubleshooting](node_modules/@knit-framework/core/docs/troubleshooting.md): Common errors and fixes
@@ -3,14 +3,11 @@ import { manyToMany, registerAdminModel, registerAdminPage, registerDashboardCar
3
3
  import { useModel, type ModelDatabase } from '@knit-framework/core/models'
4
4
  import { category, comment, post, postTag, tag } from './server/database/schema'
5
5
 
6
+ // Labels, the default order and the search fields come from each model's defineModelMeta (schema.ts).
6
7
  registerAdminModel(category, {
7
8
  icon: 'i-lucide-folder',
8
- label: 'Category',
9
- labelPlural: 'Categories',
10
9
  listDisplay: ['name', 'slug', 'createdAt'],
11
10
  listEditable: ['slug'],
12
- searchFields: ['name', 'slug'],
13
- ordering: ['name'],
14
11
  displayField: 'name',
15
12
  readonlyFields: ['createdAt'],
16
13
  prepopulatedFields: { slug: 'name' },
@@ -53,8 +50,6 @@ registerAdminModel(post, {
53
50
  listEditable: ['published'],
54
51
  listFilter: ['published', 'categoryId', 'authorId', 'publishedAt'],
55
52
  dateHierarchy: 'publishedAt',
56
- searchFields: ['title', 'slug', 'body'],
57
- ordering: ['-createdAt'],
58
53
  displayField: 'title',
59
54
  readonlyFields: ['createdAt', 'updatedAt'],
60
55
  prepopulatedFields: { slug: 'title' },
@@ -107,8 +102,6 @@ registerAdminModel(post, {
107
102
  registerAdminModel(tag, {
108
103
  icon: 'i-lucide-tag',
109
104
  listDisplay: ['name'],
110
- searchFields: ['name'],
111
- ordering: ['name'],
112
105
  displayField: 'name',
113
106
  })
114
107
 
@@ -117,7 +110,7 @@ registerAdminModel(comment, {
117
110
  listDisplay: ['body', 'postId', 'authorId', 'approved', 'createdAt'],
118
111
  listFilter: ['approved', 'postId', 'createdAt'],
119
112
  listEditable: ['approved'],
120
- searchFields: ['body'],
113
+ // Newest first here; the model's own order (oldest first) is for reading a thread.
121
114
  ordering: ['-createdAt'],
122
115
  displayField: 'body',
123
116
  readonlyFields: ['createdAt', 'updatedAt'],
@@ -1,8 +1,9 @@
1
- import { count, desc, eq } from 'drizzle-orm'
1
+ import { and, count, desc, eq } from 'drizzle-orm'
2
2
 
3
3
  /**
4
4
  * Data for the admin's Insights page (app/pages/admin/blog-insights.vue): the most commented posts
5
5
  * and posts per category. The page is linked only for `blog.view_post`; the endpoint checks it too.
6
+ * Raw reads of a soft-delete model: `notDeletedWhere(post)` keeps posts in the trash out of both.
6
7
  */
7
8
  export default defineEventHandler(async (event) => {
8
9
  await requirePermission(event, 'blog.view_post')
@@ -12,12 +13,13 @@ export default defineEventHandler(async (event) => {
12
13
  db.select({ id: post.id, title: post.title, comments: count(comment.id) })
13
14
  .from(post)
14
15
  .leftJoin(comment, eq(comment.postId, post.id))
16
+ .where(notDeletedWhere(post))
15
17
  .groupBy(post.id)
16
18
  .orderBy(desc(count(comment.id)), desc(post.id))
17
19
  .limit(5),
18
20
  db.select({ id: category.id, name: category.name, posts: count(post.id) })
19
21
  .from(category)
20
- .leftJoin(post, eq(post.categoryId, category.id))
22
+ .leftJoin(post, and(eq(post.categoryId, category.id), notDeletedWhere(post)))
21
23
  .groupBy(category.id)
22
24
  .orderBy(desc(count(post.id)), category.name),
23
25
  ])
@@ -117,11 +117,16 @@ defineModelMeta(category, {
117
117
  verboseName: 'category',
118
118
  verboseNamePlural: 'categories',
119
119
  ordering: ['name'],
120
+ searchFields: ['name', 'slug'],
120
121
  validators: { slug: [slugValidator] },
121
122
  })
122
123
 
124
+ defineModelMeta(tag, { ordering: ['name'], searchFields: ['name'] })
125
+
123
126
  defineModelMeta(post, {
124
127
  ordering: ['-createdAt'],
128
+ // What the admin search box and the posts API's `?q=` match when the search vector can't be used.
129
+ searchFields: ['title', 'slug', 'body'],
125
130
  // Deleting moves a post to the trash (restore it from the admin); every change is recorded, field by
126
131
  // field, in the change history; `useModel(post).search()` and `?q=` use the search vector.
127
132
  softDelete: 'deletedAt',
@@ -150,6 +155,7 @@ defineModelMeta(post, {
150
155
 
151
156
  defineModelMeta(comment, {
152
157
  ordering: ['createdAt'],
158
+ searchFields: ['body'],
153
159
  // Moderation, declared once: the comments API, the admin and the live comments channel all apply it.
154
160
  // Moderators (`blog.change_comment`) see every comment; signed-in users see approved comments and
155
161
  // their own pending ones; visitors see approved comments. Authors edit and delete their own.
@@ -9,7 +9,7 @@
9
9
  */
10
10
  import { and, eq, inArray } from 'drizzle-orm'
11
11
  import { user } from '@knit-framework/core/schema'
12
- import { ValidationError } from '@knit-framework/core/models'
12
+ import { notDeletedWhere, ValidationError } from '@knit-framework/core/models'
13
13
  import { defineResource } from '@knit-framework/core/resources'
14
14
  import { comment, post } from '../database/schema'
15
15
 
@@ -19,8 +19,6 @@ export default defineResource(comment, {
19
19
  readonlyFields: ['authorId', 'approved', 'createdAt', 'updatedAt'],
20
20
  labels: { body: 'Comment' },
21
21
  filterFields: ['postId', 'approved'],
22
- searchFields: ['body'],
23
- ordering: ['createdAt'],
24
22
  perPage: 50,
25
23
 
26
24
  permissions: {
@@ -37,7 +35,7 @@ export default defineResource(comment, {
37
35
  const postId = Number(data.postId)
38
36
  if (Number.isInteger(postId)) {
39
37
  const [target] = await ctx.db.select({ id: post.id }).from(post)
40
- .where(and(eq(post.id, postId), eq(post.published, true)))
38
+ .where(and(eq(post.id, postId), eq(post.published, true), notDeletedWhere(post)))
41
39
  if (!target) throw new ValidationError({ postId: 'Comments are only open on published posts.' })
42
40
  }
43
41
  return { ...data, authorId: ctx.user.id }
@@ -10,7 +10,6 @@ export default defineResource(post, {
10
10
  slug: 'posts',
11
11
  fields: ['id', 'title', 'slug', 'body', 'cover', 'published', 'publishedAt', 'categoryId'],
12
12
  readonlyFields: ['publishedAt'],
13
- searchFields: ['title', 'body'],
14
13
  filterFields: ['categoryId', 'publishedAt'],
15
14
  ordering: ['-publishedAt'],
16
15
  perPage: 10,
@@ -5,7 +5,7 @@
5
5
  * enqueue('blog.word-count', { postId: 1 }) // from any server route
6
6
  * pnpm manage runtask blog.word-count --payload '{"postId":1}'
7
7
  */
8
- import { count, eq } from 'drizzle-orm'
8
+ import { and, count, eq } from 'drizzle-orm'
9
9
  import { notDeletedWhere } from '@knit-framework/core/models'
10
10
  import { defineTask } from '@knit-framework/core/tasks'
11
11
  import { post } from '../database/schema'
@@ -21,7 +21,7 @@ export const wordCount = defineTask({
21
21
  const [row] = await ctx.db
22
22
  .select({ title: post.title, body: post.body })
23
23
  .from(post)
24
- .where(eq(post.id, payload.postId))
24
+ .where(and(eq(post.id, payload.postId), notDeletedWhere(post)))
25
25
  if (!row) throw new Error(`Post ${payload.postId} does not exist.`)
26
26
  const words = row.body.trim().split(/\s+/).filter(Boolean).length
27
27
  ctx.log(`"${row.title}" has ${words} word(s)`)
@@ -2,11 +2,14 @@
2
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
+ import { useModel, ValidationError } from '@knit-framework/core/models'
5
6
  import * as coreSchema from '@knit-framework/core/schema'
6
7
  import { createTestDatabase, defineFactory, type TestDatabase } from '@knit-framework/core/testing'
7
8
  import { eq } from 'drizzle-orm'
8
9
  import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'
9
10
  import * as blogSchema from '../server/database/schema'
11
+ import comments from '../server/resources/comments'
12
+ import { wordCount } from '../server/tasks/blog'
10
13
 
11
14
  const schema = { ...coreSchema, ...blogSchema }
12
15
  const categories = defineFactory(blogSchema.category, n => ({ name: `Category ${n}`, slug: `category-${n}` }))
@@ -43,4 +46,21 @@ describe('blog', () => {
43
46
  const [reloaded] = await t.db.select().from(blogSchema.post).where(eq(blogSchema.post.id, post.id))
44
47
  expect(reloaded?.categoryId).toBeNull()
45
48
  })
49
+
50
+ // Posts are a soft-delete model: raw reads narrow themselves with `notDeletedWhere(post)`.
51
+ it('a post in the trash is gone for the word-count task and closed for comments', async () => {
52
+ const post = await posts.create(t.db, { title: 'Trashed', body: 'three little words', published: true })
53
+ const context = { db: t.db, log: () => {} } as unknown as Parameters<typeof wordCount.definition.run>[1]
54
+ const commenting = { db: t.db, user: { id: 'reader' } } as unknown as Parameters<NonNullable<typeof comments.options.beforeCreate>>[1]
55
+ const comment = (): unknown => comments.options.beforeCreate!({ postId: post.id, body: 'Nice post' }, commenting)
56
+
57
+ expect(await wordCount.definition.run({ postId: post.id }, context)).toMatchObject({ words: 3 })
58
+ expect(await comment()).toMatchObject({ postId: post.id, authorId: 'reader' })
59
+
60
+ await useModel(blogSchema.post, { db: t.db }).delete(post.id)
61
+ await expect(wordCount.definition.run({ postId: post.id }, context)).rejects.toThrow(/does not exist/)
62
+ const error = await Promise.resolve().then(comment).catch((e: unknown) => e)
63
+ expect(error).toBeInstanceOf(ValidationError)
64
+ expect((error as ValidationError).fieldErrors['postId']).toBeDefined()
65
+ })
46
66
  })
@@ -1,5 +1,5 @@
1
1
  {
2
- "knit": "0.9.0",
2
+ "knit": "0.10.0",
3
3
  "nuxt": "^4.7.0",
4
4
  "drizzleOrm": "^0.45.4",
5
5
  "typescript": "^6.0.3",