@forinda/kickjs-cli 6.13.0 → 6.14.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.
Files changed (44) hide show
  1. package/dist/{agent-docs--YHAWIIm.mjs → agent-docs-C2haALAd.mjs} +3 -3
  2. package/dist/{agent-docs--YHAWIIm.mjs.map → agent-docs-C2haALAd.mjs.map} +1 -1
  3. package/dist/{agent-docs-0yI3L1Ky.mjs → agent-docs-DBG1-630.mjs} +2 -2
  4. package/dist/{build-CcS6daf-.mjs → build-B9zLzKK6.mjs} +2 -2
  5. package/dist/{build-BqNUj7A_.mjs → build-D107Lo9_.mjs} +3 -3
  6. package/dist/{build-BqNUj7A_.mjs.map → build-D107Lo9_.mjs.map} +1 -1
  7. package/dist/{builtins-q3q1QLLh.mjs → builtins-BCtNsR0y.mjs} +2 -2
  8. package/dist/{builtins-C1OmkSrd.mjs → builtins-e3AS8mDY.mjs} +21 -22
  9. package/dist/cli.mjs +2 -2
  10. package/dist/{config-CaJIat9M.mjs → config-Bd91Deni.mjs} +3 -3
  11. package/dist/{config-CaJIat9M.mjs.map → config-Bd91Deni.mjs.map} +1 -1
  12. package/dist/{config-D35jG3kj.mjs → config-JXb5eWzr.mjs} +2 -2
  13. package/dist/{doctor-9yPpCaR7.mjs → doctor-A2e4JiHm.mjs} +19 -20
  14. package/dist/doctor-A2e4JiHm.mjs.map +1 -0
  15. package/dist/{fullstack-CvfO1yD9.mjs → fullstack-C2ljL9go.mjs} +3 -3
  16. package/dist/{fullstack-BDHCqNm_.mjs → fullstack-NKB3CKSc.mjs} +4 -4
  17. package/dist/{fullstack-BDHCqNm_.mjs.map → fullstack-NKB3CKSc.mjs.map} +1 -1
  18. package/dist/index.d.mts +8 -0
  19. package/dist/index.d.mts.map +1 -1
  20. package/dist/index.mjs +2 -2
  21. package/dist/{plugin-BvgITdge.mjs → plugin-DIZVpr-Y.mjs} +2 -2
  22. package/dist/{plugin-nMxvR1Lr.mjs → plugin-IAXYJKSd.mjs} +3 -3
  23. package/dist/{plugin-nMxvR1Lr.mjs.map → plugin-IAXYJKSd.mjs.map} +1 -1
  24. package/dist/{project-BYH9LnTe.mjs → project-Be8dqixV.mjs} +5 -5
  25. package/dist/{project-BYH9LnTe.mjs.map → project-Be8dqixV.mjs.map} +1 -1
  26. package/dist/{project-dE-amvpe.mjs → project-CGLy8Tfo.mjs} +4 -4
  27. package/dist/{project-docs-DHgCC8-a.mjs → project-docs-DczYaG-9.mjs} +3 -2
  28. package/dist/{project-docs-0gAWhIiP.mjs → project-docs-XB_ywc0t.mjs} +4 -3
  29. package/dist/{project-docs-0gAWhIiP.mjs.map → project-docs-XB_ywc0t.mjs.map} +1 -1
  30. package/dist/{project-root-BLGs_jD5.mjs → project-root-BSsFHkw1.mjs} +2 -2
  31. package/dist/{project-root-a9w4DpIE.mjs → project-root-Czq-x9_O.mjs} +3 -3
  32. package/dist/{project-root-a9w4DpIE.mjs.map → project-root-Czq-x9_O.mjs.map} +1 -1
  33. package/dist/{prompts-CxksOWrb.mjs → prompts-B1eLtBWx.mjs} +2 -2
  34. package/dist/{prompts-CxksOWrb.mjs.map → prompts-B1eLtBWx.mjs.map} +1 -1
  35. package/dist/{rolldown-runtime-_yCKTnUY.mjs → rolldown-runtime-8EywpK-L.mjs} +1 -1
  36. package/dist/{run-plugins-BweCMpF_.mjs → run-plugins-Bw00bL3a.mjs} +6 -6
  37. package/dist/run-plugins-Bw00bL3a.mjs.map +1 -0
  38. package/dist/{typegen-kJNiIRAS.mjs → typegen-B1Y5HOKB.mjs} +4 -4
  39. package/dist/{typegen-CqY0NnhZ.mjs → typegen-D0HefmD-.mjs} +5 -5
  40. package/dist/{typegen-CqY0NnhZ.mjs.map → typegen-D0HefmD-.mjs.map} +1 -1
  41. package/dist/{types-DZBP-FTX.mjs → types-BxRl7XpJ.mjs} +1 -1
  42. package/package.json +11 -11
  43. package/dist/doctor-9yPpCaR7.mjs.map +0 -1
  44. package/dist/run-plugins-BweCMpF_.mjs.map +0 -1
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs-cli v6.13.0
2
+ * @forinda/kickjs-cli v6.14.1
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -634,13 +634,14 @@ plugins: [
634
634
  **Red flags**:
635
635
  - Any \`new SomeAdapter()\` / \`SomePlugin()\` literal inside \`bootstrap({ ... })\` instead of imported from a category folder.
636
636
  - Mixing middleware signatures: \`bootstrap({ middleware })\` is **raw Express** \`(req, res, next)\`; \`@Middleware()\` decorators are \`(ctx, next)\`; adapter middleware is raw Express again. Wrong shape in the wrong slot throws "Cannot read properties of undefined".
637
- - \`bootstrap({ register: ... })\` — that option doesn't exist. Use an inline plugin.`},{slug:`context-contributor`,frontmatterName:`kickjs-context-contributor`,description:`Use when a middleware's only job is to set ctx values consumed elsewhere — replace with defineHttpContextDecorator (HTTP) or defineContextDecorator (transport-agnostic).`,body:"**Pattern** (HTTP — most common):\n\n```ts\nimport { defineHttpContextDecorator, type RequestContext } from '@forinda/kickjs'\n\n// Augment ContextMeta — required for ctx.get('tenant') to be typed\ndeclare module '@forinda/kickjs' {\n interface ContextMeta {\n tenant: { id: string; name: string }\n }\n}\n\n// The `declare module` block above is all you need. `defineAugmentation` is\n// DEPRECATED — it only added a typegen catalogue entry, never any types.\n\nconst LoadTenant = defineHttpContextDecorator({\n key: 'tenant',\n deps: { repo: TENANT_REPO }, // typed DI\n resolve: (ctx, { repo }) => repo.findById(ctx.req.headers['x-tenant-id'] as string),\n})\n\nconst LoadProject = defineHttpContextDecorator({\n key: 'project',\n dependsOn: ['tenant'], // typo'd key = tsc error\n resolve: (ctx) => projectsRepo.find(ctx.get('tenant')!.id, ctx.params.id),\n})\n\n@LoadTenant\n@LoadProject\n@Get('/projects/:id')\ngetProject(ctx: RequestContext) {\n return ctx.get('project')\n}\n```\n\nUse `defineContextDecorator` (no Http prefix) only when the contributor must run across HTTP, WebSocket, queue, and cron transports — `Ctx` defaults to the smaller `ExecutionContext` surface (`get` / `set` / `requestId` only, no `req`).\n\n**Five precedence levels** (high → low):\n**method > class > module > adapter > global**\n\nSame-key collisions WITHIN a precedence level throw `DuplicateContributorError`. Across levels, the higher precedence silently overrides — a feature, not a bug, but debug it by giving resolvers distinguishable return values.\n\n**Boot-time validation**:\n- Cycles in `dependsOn` → `ContributorCycleError`.\n- `dependsOn` referring to an unknown key → `MissingContributorError`.\n- Both errors fail boot, not first request.\n\n**Critical rules — all stem from the same shared-via-ALS instance model**:\n- Every per-request stage (middleware → contributors → handler) gets its OWN `RequestContext` instance, but they all read/write the SAME `AsyncLocalStorage`-backed bag.\n- **`resolve` and `onError` must RETURN the value** — the runner writes it via `ctx.set(key, value)`. Direct property assignment (`ctx.tenant = …`) sticks to one instance only and the handler instance never sees it.\n- `ctx.set('tenant', x)` then `ctx.get('tenant')` works across instances. `ctx.req.headers[...]` works (the underlying node request is shared). Note it is a node `IncomingMessage` on Fastify and h3, not an `express.Request`.\n- Services with no `ctx` reference: `getRequestValue('tenant')` returns `MetaValue<'tenant'> | undefined` (typed via the augmented `ContextMeta`). For `requestId` use `getRequestStore()`.\n- **No `setRequestValue` — writes flow through `ctx.set` or a contributor's return value.** Avoids \"spooky action at a distance\" where any service can pollute the per-request bag.\n\n**Error matrix**:\n- `optional: true` — `resolve` throws → key left unset; downstream sees `ctx.get(key) === undefined`.\n- `optional: false` (default) + `onError` — return a fallback value to write; return `undefined` to skip; throw to forward to the request error handler.\n- `optional: false` + no `onError` — throw propagates straight to the request error handler.\n\n**Don't use this for**: response short-circuit, stream mutation, or pre-route-matching work — keep `@Middleware()` for those.\n\n**Red flags**:\n- `ctx.get('key')!` — the non-null assertion compiles even when the producing decorator isn't on the route. Use `ctx.require('key')`.\n- `contributors: [LoadX]` at a module / adapter / bootstrap site — those take registrations: `LoadX.registration` or `LoadX.with({ ... }).registration`.\n- A `paramDefaults` value that every call site overrides (`action: 'settings:read'`) — drop it and let the compiler require the field at each site.\n- `defineContextDecorator<'k', Deps, Params>(spec)` positional form for a parameterised contributor — use `.withParams<Params>()(spec)` or `deps` inference is lost.\n- `ctx.tenant = x` instead of returning the value from `resolve` — sticks to one instance only.\n- Reaching for `defineAugmentation` — deprecated, and it never affected types. The `declare module` block alone is what makes `ctx.get('tenant')` typed.\n- Plugin / adapter authors using bare keys (`'state'`) instead of namespaced (`'@my-plugin/state'`) — collides with adopter keys.\n- `getRequestValue<string>('traceId')` — generic is the **key** type, not value type."},{slug:`query-parsing-list-endpoint`,frontmatterName:`kickjs-query-parsing-list-endpoint`,description:`Use when adding a paginated/filterable list route — emit ctx.qs + ctx.paginate with an allow-list.`,body:"**Canonical list endpoint**:\n\n```ts\n@Get('/')\nasync list(ctx: Ctx<KickRoutes.TodoController['list']>) {\n const parsed = ctx.qs({\n filterable: ['status', 'priority', 'assigneeId'], // allow-list, MUST be set\n sortable: ['createdAt', 'updatedAt', 'priority'],\n searchColumns: ['title', 'description'], // free-text search targets\n })\n\n return ctx.paginate(async () => {\n const { data, total } = await this.service.list(parsed)\n return { data, total }\n }, parsed)\n}\n```\n\n**Operator format** (fixed): `?filter=field:op:value` where `op ∈ eq | neq | gt | gte | lt | lte | between | in | contains | starts | ends`. Sort is `?sort=field:asc|desc`. Only the first two colons are delimiters, so timestamps work (`createdAt:gt:2026-01-01T00:00:00Z`).\n\n**Drizzle adopters** — pass a `DrizzleQueryParamsConfig` with column refs:\n\n```ts\nconst TASK_QUERY_CONFIG = {\n filterable: { status: tasks.status, priority: tasks.priority },\n sortable: { createdAt: tasks.createdAt },\n searchColumns: [tasks.title, tasks.description],\n}\nconst parsed = ctx.qs(TASK_QUERY_CONFIG)\n```\n\n**ORM-agnostic builders** — implement `QueryBuilderAdapter<TResult, TConfig>` with `build(parsed, config)`. The Drizzle + Prisma adapters live here.\n\n**Red flags**:\n- Reading `req.query.status` directly — bypasses the allow-list; opens unbounded filtering. Use `ctx.qs({ filterable })`.\n- Omitting `filterable` / `sortable` allow-list — every client-supplied filter is **silently dropped** (security default, but looks like a bug).\n- Hand-building the pagination meta in the controller — inconsistent response shape across endpoints. Always use `ctx.paginate()`.\n- Returning a bare array from a list endpoint when pagination is implied — breaks the `PaginatedResponse<T>` contract.\n- Mixing string `searchable` config with column `searchColumns` (Drizzle) — silently no-ops.\n\n**Nuances**:\n- `limit` is capped at 100 server-side; `q` (search) is truncated to 200 chars. Don't re-validate client-side.\n- Sort direction defaults to `asc` when omitted (`?sort=createdAt` ≡ `?sort=createdAt:asc`)."},{slug:`use-asset-manager`,frontmatterName:`kickjs-use-asset-manager`,description:`Use when code reads template files / JSON fixtures via fs.readFile + path arithmetic — switch to assets.<ns>.<key>() and the kick.config.ts assetMap.`,body:"**Configure** `kick.config.ts`:\n\n```ts\nexport default defineConfig({\n assetMap: {\n mails: { src: 'src/templates/mails' },\n reports: { src: 'src/templates/reports', glob: '**/*.{ejs,html}' },\n },\n})\n```\n\n**Consume** via the typed Proxy — no `__dirname` arithmetic, dev/prod paths handled:\n\n```ts\nimport { assets } from '@forinda/kickjs'\n\nconst html = await assets.mails.welcome() // typed: tsc errors on bad key\n```\n\n**Class-field decorator** (lazy getter, swappable in tests):\n\n```ts\nclass WelcomeMailService {\n @Asset('mails/welcome') private welcomeTemplate!: () => Promise<string>\n\n async send(to: string) {\n const body = await this.welcomeTemplate()\n }\n}\n```\n\n**Dynamic dispatch** (CMS templates, codegen) — `resolveAsset(ns, key)` throws `UnknownAssetError` with `{ namespace, key }` fields when the key is missing.\n\n**Test fixtures** — swap via env override + cache clear:\n\n```ts\nbeforeEach(() => {\n process.env.KICK_ASSETS_ROOT = path.resolve('__fixtures__/assets')\n clearAssetCache()\n})\nafterEach(() => {\n delete process.env.KICK_ASSETS_ROOT\n clearAssetCache()\n})\n```\n\n**Red flags**:\n- Hand-rolled `process.env.NODE_ENV === 'production' ? join(__dirname, '../templates') : join(__dirname, 'templates')` — exactly what the asset manager replaces.\n- `keys: 'strip'` setting in `assetMap.<ns>` when basenames may collide — silent last-walk-wins data loss. Default `'auto'` keeps extensions only for colliding groups.\n- Non-default Vite `outDir` without mirroring in `kick.config.ts` — manifest writes at `dist/.kickjs-assets.json` but the resolver can't find it. Mirror via `build.outDir`.\n- Forgetting to re-run `kick typegen` after adding files — `assets.mails.newTemplate` is a tsc error even though the file ships. `kick dev` does this on-change; one-shot CI builds need `kick build` (or `kick build:assets` for manifest-only).\n- Same-name `welcome.ejs` + `welcome/login.ejs` — directory wins in the typed surface; the `.ejs` file still copies but isn't addressable.\n\n**Nuances**:\n- Resolution pipeline (cached): `KICK_ASSETS_ROOT` env override > built manifest at `build.outDir` / `dist` / `build` / `out` > dev-fallback in-memory walk. Manifest presence = \"running from built dist.\"\n- Dev-mode glob matcher is a lite implementation — `**/*`, `**/*.ext`, `**/*.{a,b}` are guaranteed; exotic globs warn-once and accept everything. Run `kick build:assets` to exercise the real glob engine."},{slug:`cli-commands-cheatsheet`,frontmatterName:`kickjs-cli-commands-cheatsheet`,description:`Use as a quick reference for the most common kick CLI workflows — scaffolding, dev/build/start, generation, inspection.`,body:`**Top commands**:
637
+ - \`bootstrap({ register: ... })\` — that option doesn't exist. Use an inline plugin.`},{slug:`context-contributor`,frontmatterName:`kickjs-context-contributor`,description:`Use when a middleware's only job is to set ctx values consumed elsewhere — replace with defineHttpContextDecorator (HTTP) or defineContextDecorator (transport-agnostic).`,body:"**Pattern** (HTTP — most common):\n\n```ts\nimport { defineHttpContextDecorator, type RequestContext } from '@forinda/kickjs'\n\n// Augment ContextMeta — required for ctx.get('tenant') to be typed\ndeclare module '@forinda/kickjs' {\n interface ContextMeta {\n tenant: { id: string; name: string }\n }\n}\n\n// The `declare module` block above is all you need. `defineAugmentation` is\n// DEPRECATED — it only added a typegen catalogue entry, never any types.\n\nconst LoadTenant = defineHttpContextDecorator({\n key: 'tenant',\n deps: { repo: TENANT_REPO }, // typed DI\n resolve: (ctx, { repo }) => repo.findById(ctx.req.headers['x-tenant-id'] as string),\n})\n\nconst LoadProject = defineHttpContextDecorator({\n key: 'project',\n dependsOn: ['tenant'], // typo'd key = tsc error\n resolve: (ctx) => projectsRepo.find(ctx.get('tenant')!.id, ctx.params.id),\n})\n\n@LoadTenant\n@LoadProject\n@Get('/projects/:id')\ngetProject(ctx: RequestContext) {\n return ctx.get('project')\n}\n```\n\nUse `defineContextDecorator` (no Http prefix) only when the contributor must run across HTTP, WebSocket, queue, and cron transports — `Ctx` defaults to the smaller `ExecutionContext` surface (`get` / `set` / `requestId` only, no `req`).\n\n**Five precedence levels** (high → low):\n**method > class > module > adapter > global**\n\nSame-key collisions WITHIN a precedence level throw `DuplicateContributorError`. Across levels, the higher precedence silently overrides — a feature, not a bug, but debug it by giving resolvers distinguishable return values.\n\n**Boot-time validation**:\n- Cycles in `dependsOn` → `ContributorCycleError`.\n- `dependsOn` referring to an unknown key → `MissingContributorError`.\n- Both errors fail boot, not first request.\n\n**Critical rules — all stem from the same shared-via-ALS instance model**:\n- Every per-request stage (middleware → contributors → handler) gets its OWN `RequestContext` instance, but they all read/write the SAME `AsyncLocalStorage`-backed bag.\n- **`resolve` and `onError` must RETURN the value** — the runner writes it via `ctx.set(key, value)`. Direct property assignment (`ctx.tenant = …`) sticks to one instance only and the handler instance never sees it.\n- `ctx.set('tenant', x)` then `ctx.get('tenant')` works across instances. `ctx.req.headers[...]` works (the underlying node request is shared). Note it is a node `IncomingMessage` on Fastify and h3, not an `express.Request`.\n- Services with no `ctx` reference: `getRequestValue('tenant')` returns `MetaValue<'tenant'> | undefined` (typed via the augmented `ContextMeta`). For `requestId` use `getRequestStore()`.\n- **No `setRequestValue` — writes flow through `ctx.set` or a contributor's return value.** Avoids \"spooky action at a distance\" where any service can pollute the per-request bag.\n\n**Error matrix**:\n- `optional: true` — `resolve` throws → key left unset; downstream sees `ctx.get(key) === undefined`.\n- `optional: false` (default) + `onError` — return a fallback value to write; return `undefined` to skip; throw to forward to the request error handler.\n- `optional: false` + no `onError` — throw propagates straight to the request error handler.\n\n**Don't use this for**: response short-circuit, stream mutation, or pre-route-matching work — keep `@Middleware()` for those.\n\n**Red flags**:\n- `ctx.get('key')!` — the non-null assertion compiles even when the producing decorator isn't on the route. Use `ctx.require('key')`.\n- `contributors: [LoadX]` at a module / adapter / bootstrap site — those take registrations: `LoadX.registration` or `LoadX.with({ ... }).registration`.\n- A `paramDefaults` value that every call site overrides (`action: 'settings:read'`) — drop it and let the compiler require the field at each site.\n- `defineContextDecorator<'k', Deps, Params>(spec)` positional form for a parameterised contributor — use `.withParams<Params>()(spec)` or `deps` inference is lost.\n- `ctx.tenant = x` instead of returning the value from `resolve` — sticks to one instance only.\n- Reaching for `defineAugmentation` — deprecated, and it never affected types. The `declare module` block alone is what makes `ctx.get('tenant')` typed.\n- Plugin / adapter authors using bare keys (`'state'`) instead of namespaced (`'@my-plugin/state'`) — collides with adopter keys.\n- `getRequestValue<string>('traceId')` — generic is the **key** type, not value type."},{slug:`guard-vs-middleware-vs-contributor`,frontmatterName:`kickjs-guard-vs-middleware-vs-contributor`,description:`Use when adding auth checks, request-scoped values, or anything "before the handler" — picks between a guard, a middleware, and a context contributor.`,body:"**KickJS has no guard primitive.** There is no `@Guard`, no `canActivate`, no guard\nclass to implement. A guard IS a middleware — the word only names a convention\nand a directory. If you are porting NestJS habits, this is the first thing to\nunlearn.\n\n| | Guard | Middleware | Context contributor |\n|---|---|---|---|\n| What it is | a middleware, by convention | a middleware | a declarative value producer |\n| Signature | `(ctx, next)` | `(ctx, next)` on `@Middleware()`, `(req, res, next)` in `bootstrap({ middleware })` | `resolve(ctx, deps)` returning a value |\n| Can end the request | yes | yes | **no** |\n| Runs | in the middleware stage | in the middleware stage | after ALL middleware |\n| Attached by | `@Middleware(fn)` | `@Middleware(fn)` or `bootstrap({ middleware })` | `@LoadX`, or a registration at module / adapter / bootstrap level |\n| Generator | `kick g guard <name>` | `kick g middleware <name>` | `kick g contributor <name>` |\n| Lands in | `src/guards/<name>.guard.ts` | `src/middleware/<name>.middleware.ts` | `src/contributors/<name>.contributor.ts` |\n\nAdd `-m <module>` to any of those generators to place the file inside a module\ninstead of the app-level directory.\n\n**Choosing**: does the thing ever need to STOP the request?\n- Yes, and it is authorization → guard.\n- Yes, anything else (rate limit, body rewrite, response stream, work before route matching) → middleware.\n- No, it only computes a value the handler or a service reads off `ctx` → contributor. Typed, ordered, boot-validated, and it cannot silently swallow the request.\n\n**Ordering — guards run BEFORE contributors.** Every runtime does the same\nthing: run `entry.middlewares` in order, bail if the response was written,\nthen run the contributor pipeline, then the handler. So:\n\n```ts\n// WRONG — tenant is always undefined here.\nexport async function tenantGuard(ctx: RequestContext, next: () => void) {\n const tenant = ctx.get('tenant') // contributors have not run yet\n if (!tenant) return ctx.problem.forbidden()\n next()\n}\n```\n\nA guard that needs a resolved value must resolve it itself, or the check\nbelongs in the contributor's own `resolve` (throw from there and the request\nerror handler takes over).\n\n**Write responses with `ctx.*`, never `ctx.res`.** `ctx.res` is the ENGINE-NATIVE\nresponse object, so `ctx.res.status(401).json(...)` only works on Express —\n`FastifyReply` has no `.json()` and h3's event has no `.status()`. Use\n`ctx.problem.unauthorized({ detail })` (RFC 9457) or `ctx.json(body, status)`;\nthose work on all four runtimes.\n\n**Guard shape**:\n\n```ts\nimport type { RequestContext } from '@forinda/kickjs'\n\nexport async function adminGuard(ctx: RequestContext, next: () => void): Promise<void> {\n const user = ctx.session?.user // requires the session middleware\n if (!user) {\n ctx.problem.unauthorized({ detail: 'Not signed in' })\n return // do NOT call next()\n }\n if (user.role !== 'admin') {\n ctx.problem.forbidden({ detail: 'Admin only' })\n return\n }\n next()\n}\n```\n\n```ts\n@Middleware(adminGuard)\n@Get('/admin/stats')\nstats(ctx: RequestContext) { ... }\n```\n\nRole checks that are purely declarative (`@Public()`, `@Roles('admin')`,\n`@Can(...)`) come from `@forinda/kickjs-auth` and need its adapter mounted.\nHand-write a guard only for logic those don't express.\n\n**Red flags**:\n- `class AdminGuard implements CanActivate` / `@UseGuards()` — NestJS, not KickJS. Export a `(ctx, next)` function and attach with `@Middleware()`.\n- A guard calling `next()` AND writing a response — pick one; writing then continuing double-sends.\n- A guard reading `ctx.get(...)` for a contributor-produced key — contributors have not run yet.\n- `ctx.res.status(403).json(...)` in a guard — Express-only. Use `ctx.problem.forbidden()`.\n- A \"guard\" that only sets a value and always calls `next()` — that is a contributor wearing a guard's name.\n- Passing a `(ctx, next)` guard to `bootstrap({ middleware })` — global middleware is connect-style `(req, res, next)`. Mount guards per-route with `@Middleware()`.\n"},{slug:`query-parsing-list-endpoint`,frontmatterName:`kickjs-query-parsing-list-endpoint`,description:`Use when adding a paginated/filterable list route — emit ctx.qs + ctx.paginate with an allow-list.`,body:"**Canonical list endpoint**:\n\n```ts\n@Get('/')\nasync list(ctx: Ctx<KickRoutes.TodoController['list']>) {\n const parsed = ctx.qs({\n filterable: ['status', 'priority', 'assigneeId'], // allow-list, MUST be set\n sortable: ['createdAt', 'updatedAt', 'priority'],\n searchColumns: ['title', 'description'], // free-text search targets\n })\n\n return ctx.paginate(async () => {\n const { data, total } = await this.service.list(parsed)\n return { data, total }\n }, parsed)\n}\n```\n\n**Operator format** (fixed): `?filter=field:op:value` where `op ∈ eq | neq | gt | gte | lt | lte | between | in | contains | starts | ends`. Sort is `?sort=field:asc|desc`. Only the first two colons are delimiters, so timestamps work (`createdAt:gt:2026-01-01T00:00:00Z`).\n\n**Drizzle adopters** — pass a `DrizzleQueryParamsConfig` with column refs:\n\n```ts\nconst TASK_QUERY_CONFIG = {\n filterable: { status: tasks.status, priority: tasks.priority },\n sortable: { createdAt: tasks.createdAt },\n searchColumns: [tasks.title, tasks.description],\n}\nconst parsed = ctx.qs(TASK_QUERY_CONFIG)\n```\n\n**ORM-agnostic builders** — implement `QueryBuilderAdapter<TResult, TConfig>` with `build(parsed, config)`. The Drizzle + Prisma adapters live here.\n\n**Red flags**:\n- Reading `req.query.status` directly — bypasses the allow-list; opens unbounded filtering. Use `ctx.qs({ filterable })`.\n- Omitting `filterable` / `sortable` allow-list — every client-supplied filter is **silently dropped** (security default, but looks like a bug).\n- Hand-building the pagination meta in the controller — inconsistent response shape across endpoints. Always use `ctx.paginate()`.\n- Returning a bare array from a list endpoint when pagination is implied — breaks the `PaginatedResponse<T>` contract.\n- Mixing string `searchable` config with column `searchColumns` (Drizzle) — silently no-ops.\n\n**Nuances**:\n- `limit` is capped at 100 server-side; `q` (search) is truncated to 200 chars. Don't re-validate client-side.\n- Sort direction defaults to `asc` when omitted (`?sort=createdAt` ≡ `?sort=createdAt:asc`)."},{slug:`use-asset-manager`,frontmatterName:`kickjs-use-asset-manager`,description:`Use when code reads template files / JSON fixtures via fs.readFile + path arithmetic — switch to assets.<ns>.<key>() and the kick.config.ts assetMap.`,body:"**Configure** `kick.config.ts`:\n\n```ts\nexport default defineConfig({\n assetMap: {\n mails: { src: 'src/templates/mails' },\n reports: { src: 'src/templates/reports', glob: '**/*.{ejs,html}' },\n },\n})\n```\n\n**Consume** via the typed Proxy — no `__dirname` arithmetic, dev/prod paths handled:\n\n```ts\nimport { assets } from '@forinda/kickjs'\n\nconst html = await assets.mails.welcome() // typed: tsc errors on bad key\n```\n\n**Class-field decorator** (lazy getter, swappable in tests):\n\n```ts\nclass WelcomeMailService {\n @Asset('mails/welcome') private welcomeTemplate!: () => Promise<string>\n\n async send(to: string) {\n const body = await this.welcomeTemplate()\n }\n}\n```\n\n**Dynamic dispatch** (CMS templates, codegen) — `resolveAsset(ns, key)` throws `UnknownAssetError` with `{ namespace, key }` fields when the key is missing.\n\n**Test fixtures** — swap via env override + cache clear:\n\n```ts\nbeforeEach(() => {\n process.env.KICK_ASSETS_ROOT = path.resolve('__fixtures__/assets')\n clearAssetCache()\n})\nafterEach(() => {\n delete process.env.KICK_ASSETS_ROOT\n clearAssetCache()\n})\n```\n\n**Red flags**:\n- Hand-rolled `process.env.NODE_ENV === 'production' ? join(__dirname, '../templates') : join(__dirname, 'templates')` — exactly what the asset manager replaces.\n- `keys: 'strip'` setting in `assetMap.<ns>` when basenames may collide — silent last-walk-wins data loss. Default `'auto'` keeps extensions only for colliding groups.\n- Non-default Vite `outDir` without mirroring in `kick.config.ts` — manifest writes at `dist/.kickjs-assets.json` but the resolver can't find it. Mirror via `build.outDir`.\n- Forgetting to re-run `kick typegen` after adding files — `assets.mails.newTemplate` is a tsc error even though the file ships. `kick dev` does this on-change; one-shot CI builds need `kick build` (or `kick build:assets` for manifest-only).\n- Same-name `welcome.ejs` + `welcome/login.ejs` — directory wins in the typed surface; the `.ejs` file still copies but isn't addressable.\n\n**Nuances**:\n- Resolution pipeline (cached): `KICK_ASSETS_ROOT` env override > built manifest at `build.outDir` / `dist` / `build` / `out` > dev-fallback in-memory walk. Manifest presence = \"running from built dist.\"\n- Dev-mode glob matcher is a lite implementation — `**/*`, `**/*.ext`, `**/*.{a,b}` are guaranteed; exotic globs warn-once and accept everything. Run `kick build:assets` to exercise the real glob engine."},{slug:`cli-commands-cheatsheet`,frontmatterName:`kickjs-cli-commands-cheatsheet`,description:`Use as a quick reference for the most common kick CLI workflows — scaffolding, dev/build/start, generation, inspection.`,body:`**Top commands**:
638
638
  - \`kick new <name>\` — start a new project (prompts for template / repo / pm).
639
639
  - \`kick dev\` — local dev server with Vite HMR.
640
640
  - \`kick build\` — production bundle via Vite.
641
641
  - \`kick start\` — run the built artifact (\`NODE_ENV=production\` auto-set).
642
642
  - \`kick g module <name>\` — add a feature module; structure follows \`pattern\` in \`kick.config.ts\`.
643
643
  - \`kick g scaffold <Name> <field:type>...\` — full CRUD module from field definitions.
644
+ - \`kick g guard <name>\` / \`kick g middleware <name>\` / \`kick g contributor <name>\` — the three "before the handler" shapes. A guard is a middleware by convention, NOT a separate primitive.
644
645
  - \`kick add <pkg>\` — install optional packages (auto-resolves peer deps + package manager).
645
646
  - \`kick g --list\` — list every available generator (built-ins + plugin-shipped).
646
647
  - \`kick info\` — environment / version dump for bug reports.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs-cli v6.13.0
2
+ * @forinda/kickjs-cli v6.14.1
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -634,13 +634,14 @@ plugins: [
634
634
  **Red flags**:
635
635
  - Any \`new SomeAdapter()\` / \`SomePlugin()\` literal inside \`bootstrap({ ... })\` instead of imported from a category folder.
636
636
  - Mixing middleware signatures: \`bootstrap({ middleware })\` is **raw Express** \`(req, res, next)\`; \`@Middleware()\` decorators are \`(ctx, next)\`; adapter middleware is raw Express again. Wrong shape in the wrong slot throws "Cannot read properties of undefined".
637
- - \`bootstrap({ register: ... })\` — that option doesn't exist. Use an inline plugin.`},{slug:`context-contributor`,frontmatterName:`kickjs-context-contributor`,description:`Use when a middleware's only job is to set ctx values consumed elsewhere — replace with defineHttpContextDecorator (HTTP) or defineContextDecorator (transport-agnostic).`,body:"**Pattern** (HTTP — most common):\n\n```ts\nimport { defineHttpContextDecorator, type RequestContext } from '@forinda/kickjs'\n\n// Augment ContextMeta — required for ctx.get('tenant') to be typed\ndeclare module '@forinda/kickjs' {\n interface ContextMeta {\n tenant: { id: string; name: string }\n }\n}\n\n// The `declare module` block above is all you need. `defineAugmentation` is\n// DEPRECATED — it only added a typegen catalogue entry, never any types.\n\nconst LoadTenant = defineHttpContextDecorator({\n key: 'tenant',\n deps: { repo: TENANT_REPO }, // typed DI\n resolve: (ctx, { repo }) => repo.findById(ctx.req.headers['x-tenant-id'] as string),\n})\n\nconst LoadProject = defineHttpContextDecorator({\n key: 'project',\n dependsOn: ['tenant'], // typo'd key = tsc error\n resolve: (ctx) => projectsRepo.find(ctx.get('tenant')!.id, ctx.params.id),\n})\n\n@LoadTenant\n@LoadProject\n@Get('/projects/:id')\ngetProject(ctx: RequestContext) {\n return ctx.get('project')\n}\n```\n\nUse `defineContextDecorator` (no Http prefix) only when the contributor must run across HTTP, WebSocket, queue, and cron transports — `Ctx` defaults to the smaller `ExecutionContext` surface (`get` / `set` / `requestId` only, no `req`).\n\n**Five precedence levels** (high → low):\n**method > class > module > adapter > global**\n\nSame-key collisions WITHIN a precedence level throw `DuplicateContributorError`. Across levels, the higher precedence silently overrides — a feature, not a bug, but debug it by giving resolvers distinguishable return values.\n\n**Boot-time validation**:\n- Cycles in `dependsOn` → `ContributorCycleError`.\n- `dependsOn` referring to an unknown key → `MissingContributorError`.\n- Both errors fail boot, not first request.\n\n**Critical rules — all stem from the same shared-via-ALS instance model**:\n- Every per-request stage (middleware → contributors → handler) gets its OWN `RequestContext` instance, but they all read/write the SAME `AsyncLocalStorage`-backed bag.\n- **`resolve` and `onError` must RETURN the value** — the runner writes it via `ctx.set(key, value)`. Direct property assignment (`ctx.tenant = …`) sticks to one instance only and the handler instance never sees it.\n- `ctx.set('tenant', x)` then `ctx.get('tenant')` works across instances. `ctx.req.headers[...]` works (the underlying node request is shared). Note it is a node `IncomingMessage` on Fastify and h3, not an `express.Request`.\n- Services with no `ctx` reference: `getRequestValue('tenant')` returns `MetaValue<'tenant'> | undefined` (typed via the augmented `ContextMeta`). For `requestId` use `getRequestStore()`.\n- **No `setRequestValue` — writes flow through `ctx.set` or a contributor's return value.** Avoids \"spooky action at a distance\" where any service can pollute the per-request bag.\n\n**Error matrix**:\n- `optional: true` — `resolve` throws → key left unset; downstream sees `ctx.get(key) === undefined`.\n- `optional: false` (default) + `onError` — return a fallback value to write; return `undefined` to skip; throw to forward to the request error handler.\n- `optional: false` + no `onError` — throw propagates straight to the request error handler.\n\n**Don't use this for**: response short-circuit, stream mutation, or pre-route-matching work — keep `@Middleware()` for those.\n\n**Red flags**:\n- `ctx.get('key')!` — the non-null assertion compiles even when the producing decorator isn't on the route. Use `ctx.require('key')`.\n- `contributors: [LoadX]` at a module / adapter / bootstrap site — those take registrations: `LoadX.registration` or `LoadX.with({ ... }).registration`.\n- A `paramDefaults` value that every call site overrides (`action: 'settings:read'`) — drop it and let the compiler require the field at each site.\n- `defineContextDecorator<'k', Deps, Params>(spec)` positional form for a parameterised contributor — use `.withParams<Params>()(spec)` or `deps` inference is lost.\n- `ctx.tenant = x` instead of returning the value from `resolve` — sticks to one instance only.\n- Reaching for `defineAugmentation` — deprecated, and it never affected types. The `declare module` block alone is what makes `ctx.get('tenant')` typed.\n- Plugin / adapter authors using bare keys (`'state'`) instead of namespaced (`'@my-plugin/state'`) — collides with adopter keys.\n- `getRequestValue<string>('traceId')` — generic is the **key** type, not value type."},{slug:`query-parsing-list-endpoint`,frontmatterName:`kickjs-query-parsing-list-endpoint`,description:`Use when adding a paginated/filterable list route — emit ctx.qs + ctx.paginate with an allow-list.`,body:"**Canonical list endpoint**:\n\n```ts\n@Get('/')\nasync list(ctx: Ctx<KickRoutes.TodoController['list']>) {\n const parsed = ctx.qs({\n filterable: ['status', 'priority', 'assigneeId'], // allow-list, MUST be set\n sortable: ['createdAt', 'updatedAt', 'priority'],\n searchColumns: ['title', 'description'], // free-text search targets\n })\n\n return ctx.paginate(async () => {\n const { data, total } = await this.service.list(parsed)\n return { data, total }\n }, parsed)\n}\n```\n\n**Operator format** (fixed): `?filter=field:op:value` where `op ∈ eq | neq | gt | gte | lt | lte | between | in | contains | starts | ends`. Sort is `?sort=field:asc|desc`. Only the first two colons are delimiters, so timestamps work (`createdAt:gt:2026-01-01T00:00:00Z`).\n\n**Drizzle adopters** — pass a `DrizzleQueryParamsConfig` with column refs:\n\n```ts\nconst TASK_QUERY_CONFIG = {\n filterable: { status: tasks.status, priority: tasks.priority },\n sortable: { createdAt: tasks.createdAt },\n searchColumns: [tasks.title, tasks.description],\n}\nconst parsed = ctx.qs(TASK_QUERY_CONFIG)\n```\n\n**ORM-agnostic builders** — implement `QueryBuilderAdapter<TResult, TConfig>` with `build(parsed, config)`. The Drizzle + Prisma adapters live here.\n\n**Red flags**:\n- Reading `req.query.status` directly — bypasses the allow-list; opens unbounded filtering. Use `ctx.qs({ filterable })`.\n- Omitting `filterable` / `sortable` allow-list — every client-supplied filter is **silently dropped** (security default, but looks like a bug).\n- Hand-building the pagination meta in the controller — inconsistent response shape across endpoints. Always use `ctx.paginate()`.\n- Returning a bare array from a list endpoint when pagination is implied — breaks the `PaginatedResponse<T>` contract.\n- Mixing string `searchable` config with column `searchColumns` (Drizzle) — silently no-ops.\n\n**Nuances**:\n- `limit` is capped at 100 server-side; `q` (search) is truncated to 200 chars. Don't re-validate client-side.\n- Sort direction defaults to `asc` when omitted (`?sort=createdAt` ≡ `?sort=createdAt:asc`)."},{slug:`use-asset-manager`,frontmatterName:`kickjs-use-asset-manager`,description:`Use when code reads template files / JSON fixtures via fs.readFile + path arithmetic — switch to assets.<ns>.<key>() and the kick.config.ts assetMap.`,body:"**Configure** `kick.config.ts`:\n\n```ts\nexport default defineConfig({\n assetMap: {\n mails: { src: 'src/templates/mails' },\n reports: { src: 'src/templates/reports', glob: '**/*.{ejs,html}' },\n },\n})\n```\n\n**Consume** via the typed Proxy — no `__dirname` arithmetic, dev/prod paths handled:\n\n```ts\nimport { assets } from '@forinda/kickjs'\n\nconst html = await assets.mails.welcome() // typed: tsc errors on bad key\n```\n\n**Class-field decorator** (lazy getter, swappable in tests):\n\n```ts\nclass WelcomeMailService {\n @Asset('mails/welcome') private welcomeTemplate!: () => Promise<string>\n\n async send(to: string) {\n const body = await this.welcomeTemplate()\n }\n}\n```\n\n**Dynamic dispatch** (CMS templates, codegen) — `resolveAsset(ns, key)` throws `UnknownAssetError` with `{ namespace, key }` fields when the key is missing.\n\n**Test fixtures** — swap via env override + cache clear:\n\n```ts\nbeforeEach(() => {\n process.env.KICK_ASSETS_ROOT = path.resolve('__fixtures__/assets')\n clearAssetCache()\n})\nafterEach(() => {\n delete process.env.KICK_ASSETS_ROOT\n clearAssetCache()\n})\n```\n\n**Red flags**:\n- Hand-rolled `process.env.NODE_ENV === 'production' ? join(__dirname, '../templates') : join(__dirname, 'templates')` — exactly what the asset manager replaces.\n- `keys: 'strip'` setting in `assetMap.<ns>` when basenames may collide — silent last-walk-wins data loss. Default `'auto'` keeps extensions only for colliding groups.\n- Non-default Vite `outDir` without mirroring in `kick.config.ts` — manifest writes at `dist/.kickjs-assets.json` but the resolver can't find it. Mirror via `build.outDir`.\n- Forgetting to re-run `kick typegen` after adding files — `assets.mails.newTemplate` is a tsc error even though the file ships. `kick dev` does this on-change; one-shot CI builds need `kick build` (or `kick build:assets` for manifest-only).\n- Same-name `welcome.ejs` + `welcome/login.ejs` — directory wins in the typed surface; the `.ejs` file still copies but isn't addressable.\n\n**Nuances**:\n- Resolution pipeline (cached): `KICK_ASSETS_ROOT` env override > built manifest at `build.outDir` / `dist` / `build` / `out` > dev-fallback in-memory walk. Manifest presence = \"running from built dist.\"\n- Dev-mode glob matcher is a lite implementation — `**/*`, `**/*.ext`, `**/*.{a,b}` are guaranteed; exotic globs warn-once and accept everything. Run `kick build:assets` to exercise the real glob engine."},{slug:`cli-commands-cheatsheet`,frontmatterName:`kickjs-cli-commands-cheatsheet`,description:`Use as a quick reference for the most common kick CLI workflows — scaffolding, dev/build/start, generation, inspection.`,body:`**Top commands**:
637
+ - \`bootstrap({ register: ... })\` — that option doesn't exist. Use an inline plugin.`},{slug:`context-contributor`,frontmatterName:`kickjs-context-contributor`,description:`Use when a middleware's only job is to set ctx values consumed elsewhere — replace with defineHttpContextDecorator (HTTP) or defineContextDecorator (transport-agnostic).`,body:"**Pattern** (HTTP — most common):\n\n```ts\nimport { defineHttpContextDecorator, type RequestContext } from '@forinda/kickjs'\n\n// Augment ContextMeta — required for ctx.get('tenant') to be typed\ndeclare module '@forinda/kickjs' {\n interface ContextMeta {\n tenant: { id: string; name: string }\n }\n}\n\n// The `declare module` block above is all you need. `defineAugmentation` is\n// DEPRECATED — it only added a typegen catalogue entry, never any types.\n\nconst LoadTenant = defineHttpContextDecorator({\n key: 'tenant',\n deps: { repo: TENANT_REPO }, // typed DI\n resolve: (ctx, { repo }) => repo.findById(ctx.req.headers['x-tenant-id'] as string),\n})\n\nconst LoadProject = defineHttpContextDecorator({\n key: 'project',\n dependsOn: ['tenant'], // typo'd key = tsc error\n resolve: (ctx) => projectsRepo.find(ctx.get('tenant')!.id, ctx.params.id),\n})\n\n@LoadTenant\n@LoadProject\n@Get('/projects/:id')\ngetProject(ctx: RequestContext) {\n return ctx.get('project')\n}\n```\n\nUse `defineContextDecorator` (no Http prefix) only when the contributor must run across HTTP, WebSocket, queue, and cron transports — `Ctx` defaults to the smaller `ExecutionContext` surface (`get` / `set` / `requestId` only, no `req`).\n\n**Five precedence levels** (high → low):\n**method > class > module > adapter > global**\n\nSame-key collisions WITHIN a precedence level throw `DuplicateContributorError`. Across levels, the higher precedence silently overrides — a feature, not a bug, but debug it by giving resolvers distinguishable return values.\n\n**Boot-time validation**:\n- Cycles in `dependsOn` → `ContributorCycleError`.\n- `dependsOn` referring to an unknown key → `MissingContributorError`.\n- Both errors fail boot, not first request.\n\n**Critical rules — all stem from the same shared-via-ALS instance model**:\n- Every per-request stage (middleware → contributors → handler) gets its OWN `RequestContext` instance, but they all read/write the SAME `AsyncLocalStorage`-backed bag.\n- **`resolve` and `onError` must RETURN the value** — the runner writes it via `ctx.set(key, value)`. Direct property assignment (`ctx.tenant = …`) sticks to one instance only and the handler instance never sees it.\n- `ctx.set('tenant', x)` then `ctx.get('tenant')` works across instances. `ctx.req.headers[...]` works (the underlying node request is shared). Note it is a node `IncomingMessage` on Fastify and h3, not an `express.Request`.\n- Services with no `ctx` reference: `getRequestValue('tenant')` returns `MetaValue<'tenant'> | undefined` (typed via the augmented `ContextMeta`). For `requestId` use `getRequestStore()`.\n- **No `setRequestValue` — writes flow through `ctx.set` or a contributor's return value.** Avoids \"spooky action at a distance\" where any service can pollute the per-request bag.\n\n**Error matrix**:\n- `optional: true` — `resolve` throws → key left unset; downstream sees `ctx.get(key) === undefined`.\n- `optional: false` (default) + `onError` — return a fallback value to write; return `undefined` to skip; throw to forward to the request error handler.\n- `optional: false` + no `onError` — throw propagates straight to the request error handler.\n\n**Don't use this for**: response short-circuit, stream mutation, or pre-route-matching work — keep `@Middleware()` for those.\n\n**Red flags**:\n- `ctx.get('key')!` — the non-null assertion compiles even when the producing decorator isn't on the route. Use `ctx.require('key')`.\n- `contributors: [LoadX]` at a module / adapter / bootstrap site — those take registrations: `LoadX.registration` or `LoadX.with({ ... }).registration`.\n- A `paramDefaults` value that every call site overrides (`action: 'settings:read'`) — drop it and let the compiler require the field at each site.\n- `defineContextDecorator<'k', Deps, Params>(spec)` positional form for a parameterised contributor — use `.withParams<Params>()(spec)` or `deps` inference is lost.\n- `ctx.tenant = x` instead of returning the value from `resolve` — sticks to one instance only.\n- Reaching for `defineAugmentation` — deprecated, and it never affected types. The `declare module` block alone is what makes `ctx.get('tenant')` typed.\n- Plugin / adapter authors using bare keys (`'state'`) instead of namespaced (`'@my-plugin/state'`) — collides with adopter keys.\n- `getRequestValue<string>('traceId')` — generic is the **key** type, not value type."},{slug:`guard-vs-middleware-vs-contributor`,frontmatterName:`kickjs-guard-vs-middleware-vs-contributor`,description:`Use when adding auth checks, request-scoped values, or anything "before the handler" — picks between a guard, a middleware, and a context contributor.`,body:"**KickJS has no guard primitive.** There is no `@Guard`, no `canActivate`, no guard\nclass to implement. A guard IS a middleware — the word only names a convention\nand a directory. If you are porting NestJS habits, this is the first thing to\nunlearn.\n\n| | Guard | Middleware | Context contributor |\n|---|---|---|---|\n| What it is | a middleware, by convention | a middleware | a declarative value producer |\n| Signature | `(ctx, next)` | `(ctx, next)` on `@Middleware()`, `(req, res, next)` in `bootstrap({ middleware })` | `resolve(ctx, deps)` returning a value |\n| Can end the request | yes | yes | **no** |\n| Runs | in the middleware stage | in the middleware stage | after ALL middleware |\n| Attached by | `@Middleware(fn)` | `@Middleware(fn)` or `bootstrap({ middleware })` | `@LoadX`, or a registration at module / adapter / bootstrap level |\n| Generator | `kick g guard <name>` | `kick g middleware <name>` | `kick g contributor <name>` |\n| Lands in | `src/guards/<name>.guard.ts` | `src/middleware/<name>.middleware.ts` | `src/contributors/<name>.contributor.ts` |\n\nAdd `-m <module>` to any of those generators to place the file inside a module\ninstead of the app-level directory.\n\n**Choosing**: does the thing ever need to STOP the request?\n- Yes, and it is authorization → guard.\n- Yes, anything else (rate limit, body rewrite, response stream, work before route matching) → middleware.\n- No, it only computes a value the handler or a service reads off `ctx` → contributor. Typed, ordered, boot-validated, and it cannot silently swallow the request.\n\n**Ordering — guards run BEFORE contributors.** Every runtime does the same\nthing: run `entry.middlewares` in order, bail if the response was written,\nthen run the contributor pipeline, then the handler. So:\n\n```ts\n// WRONG — tenant is always undefined here.\nexport async function tenantGuard(ctx: RequestContext, next: () => void) {\n const tenant = ctx.get('tenant') // contributors have not run yet\n if (!tenant) return ctx.problem.forbidden()\n next()\n}\n```\n\nA guard that needs a resolved value must resolve it itself, or the check\nbelongs in the contributor's own `resolve` (throw from there and the request\nerror handler takes over).\n\n**Write responses with `ctx.*`, never `ctx.res`.** `ctx.res` is the ENGINE-NATIVE\nresponse object, so `ctx.res.status(401).json(...)` only works on Express —\n`FastifyReply` has no `.json()` and h3's event has no `.status()`. Use\n`ctx.problem.unauthorized({ detail })` (RFC 9457) or `ctx.json(body, status)`;\nthose work on all four runtimes.\n\n**Guard shape**:\n\n```ts\nimport type { RequestContext } from '@forinda/kickjs'\n\nexport async function adminGuard(ctx: RequestContext, next: () => void): Promise<void> {\n const user = ctx.session?.user // requires the session middleware\n if (!user) {\n ctx.problem.unauthorized({ detail: 'Not signed in' })\n return // do NOT call next()\n }\n if (user.role !== 'admin') {\n ctx.problem.forbidden({ detail: 'Admin only' })\n return\n }\n next()\n}\n```\n\n```ts\n@Middleware(adminGuard)\n@Get('/admin/stats')\nstats(ctx: RequestContext) { ... }\n```\n\nRole checks that are purely declarative (`@Public()`, `@Roles('admin')`,\n`@Can(...)`) come from `@forinda/kickjs-auth` and need its adapter mounted.\nHand-write a guard only for logic those don't express.\n\n**Red flags**:\n- `class AdminGuard implements CanActivate` / `@UseGuards()` — NestJS, not KickJS. Export a `(ctx, next)` function and attach with `@Middleware()`.\n- A guard calling `next()` AND writing a response — pick one; writing then continuing double-sends.\n- A guard reading `ctx.get(...)` for a contributor-produced key — contributors have not run yet.\n- `ctx.res.status(403).json(...)` in a guard — Express-only. Use `ctx.problem.forbidden()`.\n- A \"guard\" that only sets a value and always calls `next()` — that is a contributor wearing a guard's name.\n- Passing a `(ctx, next)` guard to `bootstrap({ middleware })` — global middleware is connect-style `(req, res, next)`. Mount guards per-route with `@Middleware()`.\n"},{slug:`query-parsing-list-endpoint`,frontmatterName:`kickjs-query-parsing-list-endpoint`,description:`Use when adding a paginated/filterable list route — emit ctx.qs + ctx.paginate with an allow-list.`,body:"**Canonical list endpoint**:\n\n```ts\n@Get('/')\nasync list(ctx: Ctx<KickRoutes.TodoController['list']>) {\n const parsed = ctx.qs({\n filterable: ['status', 'priority', 'assigneeId'], // allow-list, MUST be set\n sortable: ['createdAt', 'updatedAt', 'priority'],\n searchColumns: ['title', 'description'], // free-text search targets\n })\n\n return ctx.paginate(async () => {\n const { data, total } = await this.service.list(parsed)\n return { data, total }\n }, parsed)\n}\n```\n\n**Operator format** (fixed): `?filter=field:op:value` where `op ∈ eq | neq | gt | gte | lt | lte | between | in | contains | starts | ends`. Sort is `?sort=field:asc|desc`. Only the first two colons are delimiters, so timestamps work (`createdAt:gt:2026-01-01T00:00:00Z`).\n\n**Drizzle adopters** — pass a `DrizzleQueryParamsConfig` with column refs:\n\n```ts\nconst TASK_QUERY_CONFIG = {\n filterable: { status: tasks.status, priority: tasks.priority },\n sortable: { createdAt: tasks.createdAt },\n searchColumns: [tasks.title, tasks.description],\n}\nconst parsed = ctx.qs(TASK_QUERY_CONFIG)\n```\n\n**ORM-agnostic builders** — implement `QueryBuilderAdapter<TResult, TConfig>` with `build(parsed, config)`. The Drizzle + Prisma adapters live here.\n\n**Red flags**:\n- Reading `req.query.status` directly — bypasses the allow-list; opens unbounded filtering. Use `ctx.qs({ filterable })`.\n- Omitting `filterable` / `sortable` allow-list — every client-supplied filter is **silently dropped** (security default, but looks like a bug).\n- Hand-building the pagination meta in the controller — inconsistent response shape across endpoints. Always use `ctx.paginate()`.\n- Returning a bare array from a list endpoint when pagination is implied — breaks the `PaginatedResponse<T>` contract.\n- Mixing string `searchable` config with column `searchColumns` (Drizzle) — silently no-ops.\n\n**Nuances**:\n- `limit` is capped at 100 server-side; `q` (search) is truncated to 200 chars. Don't re-validate client-side.\n- Sort direction defaults to `asc` when omitted (`?sort=createdAt` ≡ `?sort=createdAt:asc`)."},{slug:`use-asset-manager`,frontmatterName:`kickjs-use-asset-manager`,description:`Use when code reads template files / JSON fixtures via fs.readFile + path arithmetic — switch to assets.<ns>.<key>() and the kick.config.ts assetMap.`,body:"**Configure** `kick.config.ts`:\n\n```ts\nexport default defineConfig({\n assetMap: {\n mails: { src: 'src/templates/mails' },\n reports: { src: 'src/templates/reports', glob: '**/*.{ejs,html}' },\n },\n})\n```\n\n**Consume** via the typed Proxy — no `__dirname` arithmetic, dev/prod paths handled:\n\n```ts\nimport { assets } from '@forinda/kickjs'\n\nconst html = await assets.mails.welcome() // typed: tsc errors on bad key\n```\n\n**Class-field decorator** (lazy getter, swappable in tests):\n\n```ts\nclass WelcomeMailService {\n @Asset('mails/welcome') private welcomeTemplate!: () => Promise<string>\n\n async send(to: string) {\n const body = await this.welcomeTemplate()\n }\n}\n```\n\n**Dynamic dispatch** (CMS templates, codegen) — `resolveAsset(ns, key)` throws `UnknownAssetError` with `{ namespace, key }` fields when the key is missing.\n\n**Test fixtures** — swap via env override + cache clear:\n\n```ts\nbeforeEach(() => {\n process.env.KICK_ASSETS_ROOT = path.resolve('__fixtures__/assets')\n clearAssetCache()\n})\nafterEach(() => {\n delete process.env.KICK_ASSETS_ROOT\n clearAssetCache()\n})\n```\n\n**Red flags**:\n- Hand-rolled `process.env.NODE_ENV === 'production' ? join(__dirname, '../templates') : join(__dirname, 'templates')` — exactly what the asset manager replaces.\n- `keys: 'strip'` setting in `assetMap.<ns>` when basenames may collide — silent last-walk-wins data loss. Default `'auto'` keeps extensions only for colliding groups.\n- Non-default Vite `outDir` without mirroring in `kick.config.ts` — manifest writes at `dist/.kickjs-assets.json` but the resolver can't find it. Mirror via `build.outDir`.\n- Forgetting to re-run `kick typegen` after adding files — `assets.mails.newTemplate` is a tsc error even though the file ships. `kick dev` does this on-change; one-shot CI builds need `kick build` (or `kick build:assets` for manifest-only).\n- Same-name `welcome.ejs` + `welcome/login.ejs` — directory wins in the typed surface; the `.ejs` file still copies but isn't addressable.\n\n**Nuances**:\n- Resolution pipeline (cached): `KICK_ASSETS_ROOT` env override > built manifest at `build.outDir` / `dist` / `build` / `out` > dev-fallback in-memory walk. Manifest presence = \"running from built dist.\"\n- Dev-mode glob matcher is a lite implementation — `**/*`, `**/*.ext`, `**/*.{a,b}` are guaranteed; exotic globs warn-once and accept everything. Run `kick build:assets` to exercise the real glob engine."},{slug:`cli-commands-cheatsheet`,frontmatterName:`kickjs-cli-commands-cheatsheet`,description:`Use as a quick reference for the most common kick CLI workflows — scaffolding, dev/build/start, generation, inspection.`,body:`**Top commands**:
638
638
  - \`kick new <name>\` — start a new project (prompts for template / repo / pm).
639
639
  - \`kick dev\` — local dev server with Vite HMR.
640
640
  - \`kick build\` — production bundle via Vite.
641
641
  - \`kick start\` — run the built artifact (\`NODE_ENV=production\` auto-set).
642
642
  - \`kick g module <name>\` — add a feature module; structure follows \`pattern\` in \`kick.config.ts\`.
643
643
  - \`kick g scaffold <Name> <field:type>...\` — full CRUD module from field definitions.
644
+ - \`kick g guard <name>\` / \`kick g middleware <name>\` / \`kick g contributor <name>\` — the three "before the handler" shapes. A guard is a middleware by convention, NOT a separate primitive.
644
645
  - \`kick add <pkg>\` — install optional packages (auto-resolves peer deps + package manager).
645
646
  - \`kick g --list\` — list every available generator (built-ins + plugin-shipped).
646
647
  - \`kick info\` — environment / version dump for bug reports.
@@ -782,4 +783,4 @@ Codex / Cursor / Gemini / Claude Code without copy-pasting.
782
783
  CLI template. Hand-edited content is overwritten — keep customisation
783
784
  in \`.agents/COPILOT.local.md\`.
784
785
  `}export{C as a,u as c,w as i,f as l,b as n,y as o,T as r,v as s,x as t};
785
- //# sourceMappingURL=project-docs-0gAWhIiP.mjs.map
786
+ //# sourceMappingURL=project-docs-XB_ywc0t.mjs.map