kitcn 0.0.1 → 0.12.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.
Files changed (93) hide show
  1. package/bin/intent.js +3 -0
  2. package/dist/aggregate/index.d.ts +388 -0
  3. package/dist/aggregate/index.js +37 -0
  4. package/dist/api-entry-BckXqaLb.js +66 -0
  5. package/dist/auth/client/index.d.ts +37 -0
  6. package/dist/auth/client/index.js +217 -0
  7. package/dist/auth/config/index.d.ts +45 -0
  8. package/dist/auth/config/index.js +24 -0
  9. package/dist/auth/generated/index.d.ts +2 -0
  10. package/dist/auth/generated/index.js +3 -0
  11. package/dist/auth/http/index.d.ts +64 -0
  12. package/dist/auth/http/index.js +461 -0
  13. package/dist/auth/index.d.ts +221 -0
  14. package/dist/auth/index.js +1398 -0
  15. package/dist/auth/nextjs/index.d.ts +50 -0
  16. package/dist/auth/nextjs/index.js +81 -0
  17. package/dist/auth-store-Cljlmdmi.js +197 -0
  18. package/dist/builder-CBdG5W6A.js +1974 -0
  19. package/dist/caller-factory-cTXNvYdz.js +216 -0
  20. package/dist/cli.mjs +13255 -0
  21. package/dist/codegen-lF80HSWu.mjs +3416 -0
  22. package/dist/context-utils-HPC5nXzx.d.ts +17 -0
  23. package/dist/create-schema-odyF4kCy.js +156 -0
  24. package/dist/create-schema-orm-DOyiNDCx.js +246 -0
  25. package/dist/crpc/index.d.ts +105 -0
  26. package/dist/crpc/index.js +169 -0
  27. package/dist/customFunctions-C0voKmtx.js +144 -0
  28. package/dist/error-BZEnI7Sq.js +41 -0
  29. package/dist/generated-contract-disabled-Cih4eITO.js +50 -0
  30. package/dist/generated-contract-disabled-D-sOFy92.d.ts +354 -0
  31. package/dist/http-types-DqJubRPJ.d.ts +292 -0
  32. package/dist/meta-utils-0Pu0Nrap.js +117 -0
  33. package/dist/middleware-BUybuv9n.d.ts +34 -0
  34. package/dist/middleware-C2qTZ3V7.js +84 -0
  35. package/dist/orm/index.d.ts +17 -0
  36. package/dist/orm/index.js +10713 -0
  37. package/dist/plugins/index.d.ts +2 -0
  38. package/dist/plugins/index.js +3 -0
  39. package/dist/procedure-caller-DtxLmGwA.d.ts +1467 -0
  40. package/dist/procedure-caller-MWcxhQDv.js +349 -0
  41. package/dist/query-context-B8o6-8kC.js +1518 -0
  42. package/dist/query-context-CFZqIvD7.d.ts +42 -0
  43. package/dist/query-options-Dw7cOyXl.js +121 -0
  44. package/dist/ratelimit/index.d.ts +269 -0
  45. package/dist/ratelimit/index.js +856 -0
  46. package/dist/ratelimit/react/index.d.ts +76 -0
  47. package/dist/ratelimit/react/index.js +183 -0
  48. package/dist/react/index.d.ts +1284 -0
  49. package/dist/react/index.js +2526 -0
  50. package/dist/rsc/index.d.ts +276 -0
  51. package/dist/rsc/index.js +233 -0
  52. package/dist/runtime-CtvJPkur.js +2453 -0
  53. package/dist/server/index.d.ts +5 -0
  54. package/dist/server/index.js +6 -0
  55. package/dist/solid/index.d.ts +1221 -0
  56. package/dist/solid/index.js +2940 -0
  57. package/dist/transformer-DtDhR3Lc.js +194 -0
  58. package/dist/types-BTb_4BaU.d.ts +42 -0
  59. package/dist/types-BiJE7qxR.d.ts +4 -0
  60. package/dist/types-DEJpkIhw.d.ts +88 -0
  61. package/dist/types-HhO_R6pd.d.ts +213 -0
  62. package/dist/validators-B7oIJCAp.js +279 -0
  63. package/dist/validators-vzRKjBJC.d.ts +88 -0
  64. package/dist/watcher.mjs +96 -0
  65. package/dist/where-clause-compiler-DdjN63Io.d.ts +4756 -0
  66. package/package.json +107 -35
  67. package/skills/convex/SKILL.md +486 -0
  68. package/skills/convex/references/features/aggregates.md +353 -0
  69. package/skills/convex/references/features/auth-admin.md +446 -0
  70. package/skills/convex/references/features/auth-organizations.md +1141 -0
  71. package/skills/convex/references/features/auth-polar.md +579 -0
  72. package/skills/convex/references/features/auth.md +470 -0
  73. package/skills/convex/references/features/create-plugins.md +153 -0
  74. package/skills/convex/references/features/http.md +676 -0
  75. package/skills/convex/references/features/migrations.md +162 -0
  76. package/skills/convex/references/features/orm.md +1166 -0
  77. package/skills/convex/references/features/react.md +657 -0
  78. package/skills/convex/references/features/scheduling.md +267 -0
  79. package/skills/convex/references/features/testing.md +209 -0
  80. package/skills/convex/references/setup/auth.md +501 -0
  81. package/skills/convex/references/setup/biome.md +190 -0
  82. package/skills/convex/references/setup/doc-guidelines.md +145 -0
  83. package/skills/convex/references/setup/index.md +759 -0
  84. package/skills/convex/references/setup/next.md +116 -0
  85. package/skills/convex/references/setup/react.md +175 -0
  86. package/skills/convex/references/setup/server.md +473 -0
  87. package/skills/convex/references/setup/start.md +67 -0
  88. package/LICENSE +0 -21
  89. package/README.md +0 -0
  90. package/dist/index.d.mts +0 -5
  91. package/dist/index.d.mts.map +0 -1
  92. package/dist/index.mjs +0 -6
  93. package/dist/index.mjs.map +0 -1
@@ -0,0 +1,759 @@
1
+ # kitcn Setup (Canonical, Greenfield)
2
+
3
+ Use this runbook to set up a project from scratch so agents can ship features end-to-end without additional setup context.
4
+
5
+ ## 1. Purpose and Scope
6
+
7
+ This document is the canonical setup reference for kitcn in `.claude`.
8
+
9
+ In scope:
10
+
11
+ - Greenfield setup from empty/new app
12
+ - ORM-first backend (`ctx.orm`)
13
+ - cRPC setup, auth setup, client setup, framework setup
14
+ - Optional modules and plugin setup gates
15
+
16
+ Out of scope:
17
+
18
+ - Migrations from existing Convex/Ents/legacy data-layer projects
19
+
20
+ If migration is needed, stop and use migration docs separately. Do not mix migration steps into this runbook.
21
+
22
+ ## 2. Agent Decision Intake
23
+
24
+ This is the **mandatory first prompt** for agents helping users set up kitcn.
25
+ Ask these questions before editing files.
26
+
27
+ ### 2.1 Ask These First (match `/www/content/docs/index.mdx`)
28
+
29
+ #### Required choices
30
+
31
+ | Feature | Options | Default |
32
+ | --------------- | --------------------------------------------------- | ------------------ |
33
+ | Bootstrap | CLI (`kitcn init` / `add`), Docs by section | CLI |
34
+ | React Framework | Next.js App Router, TanStack Start, Other | Next.js App Router |
35
+ | Database | ORM (`ctx.orm`) | ORM |
36
+
37
+ #### Optional features
38
+
39
+ | Feature | Options | When to include |
40
+ | ------------- | --------------------------------- | --------------------------------- |
41
+ | Auth | Better Auth, Custom, None | Most apps need auth |
42
+ | SSR/RSC | Yes, No | Next.js App Router apps |
43
+ | Triggers | Yes, No | Auto side effects on data changes |
44
+ | Aggregates | Yes, No | Counts, sums, leaderboards |
45
+ | Rate Limiting | Yes, No | API protection |
46
+ | Scheduling | Yes, No | Background jobs, delayed tasks |
47
+ | HTTP router | Yes, No | REST/webhook style endpoints |
48
+ | RLS | Yes, No | Runtime row-level access control |
49
+ | Auth plugins | admin, organizations, polar, none | Only when product requires them |
50
+
51
+ ### 2.2 First Prompt Template
52
+
53
+ Use this exact structure:
54
+
55
+ 1. Bootstrap: CLI (`kitcn init` / `add`) or docs by section?
56
+ 2. Framework: Next.js App Router, TanStack Start, or other?
57
+ 3. Database: ORM (`ctx.orm`) or other?
58
+ 4. Auth: Better Auth, custom auth, or no auth?
59
+ 5. Need SSR/RSC?
60
+ 6. Enable triggers?
61
+ 7. Enable aggregates?
62
+ 8. Enable rate limiting?
63
+ 9. Enable scheduling?
64
+ 10. Need HTTP router endpoints?
65
+ 11. Enable RLS?
66
+ 12. Any auth plugins (admin/organizations/polar)?
67
+
68
+ ### 2.3 Decision Mapping
69
+
70
+ Map answers to setup execution in this order:
71
+
72
+ 1. Build base setup first (non-auth only).
73
+ 2. Pass the non-auth baseline gate (Section 11.2) before starting auth work.
74
+ 3. If auth is enabled: add auth core.
75
+ 4. If auth is enabled: pass the auth sign-in gate (Section 11.3) before optional modules/plugins.
76
+ 5. Add framework branch (Next.js or TanStack Start).
77
+ 6. Add optional modules/plugins only when selected.
78
+ 7. If framework is `Other`, stop this runbook and route to non-setup docs (`react`, `server/*`) instead of guessing.
79
+
80
+ ## 3. Base Bootstrap
81
+
82
+ ### 3.1 Preferred bootstrap path
83
+
84
+ Quickstart path:
85
+
86
+ ```bash
87
+ mkdir my-app
88
+ cd my-app
89
+ bunx kitcn init -t next --yes
90
+ ```
91
+
92
+ Then start the long-running backend with `bunx kitcn dev`, run the
93
+ framework dev server (`bun dev` for the Next starter), and open `/convex` for
94
+ the scaffolded messages demo.
95
+
96
+ Use the CLI first:
97
+
98
+ ```bash
99
+ # Adopt the current supported app in place
100
+ bunx kitcn init --yes
101
+
102
+ # Adopt the current supported app on Concave
103
+ bunx kitcn --backend concave init --yes
104
+
105
+ # New Next.js app with deterministic shadcn bootstrap + first local Convex bootstrap
106
+ bunx kitcn init -t next --yes
107
+
108
+ # New Vite app with the React baseline + first local Convex bootstrap
109
+ bunx kitcn init -t vite --yes
110
+
111
+ # Nested app target
112
+ bunx kitcn init -t next --yes --cwd apps --name web
113
+ ```
114
+
115
+ Then add only the features you want:
116
+
117
+ ```bash
118
+ bunx kitcn add auth
119
+ bunx kitcn add ratelimit
120
+ bunx kitcn add resend
121
+ ```
122
+
123
+ `kitcn init -t next --yes` owns the kitcn integration layer for:
124
+
125
+ - `app/convex/page.tsx`
126
+ - `package.json`
127
+ - `tsconfig.json`
128
+ - `.env.local`
129
+ - `components/providers.tsx`
130
+ - `lib/convex/*`
131
+ - `convex/functions/messages.ts`
132
+ - `convex/functions/generated/messages.runtime.ts`
133
+ - `convex/functions/schema.ts`
134
+ - `convex/functions/http.ts`
135
+ - `convex/functions/generated/server.ts`
136
+ - `convex/lib/crpc.ts`
137
+ - `convex/lib/get-env.ts`
138
+ - `convex/shared/api.ts`
139
+ - `kitcn.json`
140
+
141
+ Template-mode `init -t next` preserves the shadcn-owned shell (`app/layout.tsx`, `app/page.tsx`, `app/globals.css`, `components/theme-provider.tsx`, `lib/utils.ts`, `components.json`, `eslint.config.mjs`, `next.config.mjs`, `postcss.config.mjs`) and only patches:
142
+
143
+ - `app/layout.tsx` to mount `Providers`
144
+ - `tsconfig.json` to add `@convex/*`
145
+ - `components.json` when `tailwind.css` needs to follow the resolved app root
146
+ - `package.json` to add `kitcn codegen` as `codegen` (or `convex:codegen` when `codegen` is already taken)
147
+
148
+ `init -t` also runs the first kitcn codegen pass so `convex/lib/crpc.ts` can import `../functions/generated/server` immediately.
149
+ Template-mode `init -t` also seeds a live messages demo route plus starter schema and
150
+ procedures, so the scaffold has one working query/mutation flow out of the box.
151
+ Template-mode `init -t` infers `src/` vs root app layouts and writes the Next client scaffold into the matching tree. Conflicting `src` + root layouts should fail instead of guessing.
152
+ Backend resolves from `--backend`, then `backend` in `kitcn.json`, then `convex`.
153
+
154
+ Universal scaffold rule:
155
+
156
+ 1. `init -t next` owns the stack everyone needs:
157
+ - typed `get-env`
158
+ - client core
159
+ - server core
160
+ - root + Convex tsconfig wiring
161
+ - `.gitignore` entries for `.convex/` and `.concave/`
162
+ - baseline scripts
163
+ - fixed `/convex` messages demo
164
+ 2. `kitcn init` bootstraps the app in both modes: with `-t` for fresh scaffold, without `-t` for in-place adoption.
165
+ 3. Optional capability belongs in `add`, not the base scaffold:
166
+ - `add auth`
167
+ - `add ratelimit`
168
+ - `add resend`
169
+ 4. `add auth` is the minimal auth bundle. It owns auth server/client files,
170
+ auth-aware provider wiring, auth env fields, and auth cRPC families.
171
+ 5. `add auth` does not own role/admin policy, orgs, or other app-policy layers.
172
+
173
+ Public template keys stay concrete:
174
+
175
+ - `next`
176
+ - `vite`
177
+
178
+ Internal scaffold modes stay broad:
179
+
180
+ - `next-app`
181
+ - `react`
182
+
183
+ Framework mapping:
184
+
185
+ - `next-app` -> `next-app`
186
+ - `next-pages`, `vite`, `react-router`, `tanstack-start`, `manual` -> `react`
187
+
188
+ React-mode notes:
189
+
190
+ 1. `init -t vite` scaffolds the universal baseline plus the React client core.
191
+ 2. It does not scaffold RSC helpers.
192
+ 3. It does not scaffold the `/convex` messages demo in v1.
193
+ 4. `add auth` on the React baseline follows the Better Auth React/Vite SPA shape and skips auth page/router UX in v1.
194
+
195
+ ### 3.2 Manual app creation and baseline packages
196
+
197
+ ```bash
198
+ bunx create-next-app@latest my-app --typescript --tailwind --eslint --app --src-dir
199
+ cd my-app
200
+ bun add convex kitcn zod @tanstack/react-query
201
+ ```
202
+
203
+ ### 3.3 Create baseline folders
204
+
205
+ ```bash
206
+ mkdir -p convex/functions convex/lib convex/shared src/lib/convex
207
+ ```
208
+
209
+ If the goal is full template-level backend parity, also scaffold:
210
+
211
+ ```bash
212
+ mkdir -p convex/functions/items convex/lib/auth convex/lib/emails convex/routers
213
+ ```
214
+
215
+ Recommended monolithic structure:
216
+
217
+ ```text
218
+ src/ # app/client
219
+ convex/functions/ # deployed Convex functions
220
+ convex/lib/ # backend helpers (not deployed as API)
221
+ convex/shared/ # shared types/meta imported by client
222
+ ```
223
+
224
+ ### 3.4 Configure Convex functions path and static codegen
225
+
226
+ **Create:** `convex.json`
227
+
228
+ ```json
229
+ {
230
+ "functions": "convex/functions",
231
+ "codegen": {
232
+ "staticApi": true,
233
+ "staticDataModel": true
234
+ }
235
+ }
236
+ ```
237
+
238
+ ### 3.5 Configure TypeScript aliases and strict function typing
239
+
240
+ **Edit:** `tsconfig.json`
241
+
242
+ ```json
243
+ {
244
+ "compilerOptions": {
245
+ "strict": true,
246
+ "strictFunctionTypes": false,
247
+ "types": ["node"],
248
+ "paths": {
249
+ "@/*": ["./src/*"],
250
+ "@convex/*": ["./convex/shared/*"]
251
+ }
252
+ }
253
+ }
254
+ ```
255
+
256
+ Type-clean baseline notes:
257
+
258
+ 1. Keep app/runtime node globals available (`types: ["node"]`) so `process.env` and server modules typecheck.
259
+ 2. Add test-only globals (for example `vitest/globals`) in a test-specific tsconfig instead of the main app tsconfig.
260
+ 3. If third-party declaration noise blocks setup, temporarily set `"skipLibCheck": true` and remove it once dependency versions are stabilized.
261
+ 4. In backend Convex files, import `./_generated/*` relatively; `@convex/*` is for shared generated surface (`convex/shared/*`).
262
+
263
+ ### 3.6 Enforce import boundaries (recommended)
264
+
265
+ **Edit:** `biome.jsonc`
266
+
267
+ ```jsonc
268
+ {
269
+ "extends": ["ultracite/core", "ultracite/react", "ultracite/next"],
270
+ "overrides": [
271
+ {
272
+ "includes": ["src/**/*.ts*"],
273
+ "linter": {
274
+ "rules": {
275
+ "style": {
276
+ "noRestrictedImports": {
277
+ "level": "error",
278
+ "options": {
279
+ "paths": {
280
+ "convex/values": {
281
+ "importNames": ["ConvexError"],
282
+ "message": "Use CRPCError from 'kitcn/crpc' instead.",
283
+ },
284
+ "convex/react": "Use useCRPC from '@/lib/convex/crpc' instead.",
285
+ "convex/nextjs": "Use caller from '@/lib/convex/rsc' instead.",
286
+ },
287
+ "patterns": [
288
+ {
289
+ "group": ["**/../convex/**"],
290
+ "message": "Use @convex/* alias instead of relative convex imports.",
291
+ },
292
+ ],
293
+ },
294
+ },
295
+ },
296
+ },
297
+ },
298
+ },
299
+ {
300
+ "includes": ["convex/**/*.ts*"],
301
+ "linter": {
302
+ "rules": {
303
+ "style": {
304
+ "noRestrictedImports": {
305
+ "level": "error",
306
+ "options": {
307
+ "patterns": [
308
+ {
309
+ "group": ["@/*", "**/src/**"],
310
+ "message": "Convex files cannot import from src/.",
311
+ },
312
+ ],
313
+ },
314
+ },
315
+ },
316
+ },
317
+ },
318
+ },
319
+ {
320
+ "includes": ["convex/shared/**/*.ts*"],
321
+ "linter": {
322
+ "rules": {
323
+ "style": {
324
+ "noRestrictedImports": {
325
+ "level": "error",
326
+ "options": {
327
+ "patterns": [
328
+ {
329
+ "group": ["**/convex/lib/**"],
330
+ "message": "convex/shared cannot import from convex/lib.",
331
+ },
332
+ ],
333
+ },
334
+ },
335
+ },
336
+ },
337
+ },
338
+ },
339
+ ],
340
+ }
341
+ ```
342
+
343
+ ## 4. Environment Variables
344
+
345
+ ### 4.1 Local
346
+
347
+ **Create:** `.env.local`
348
+
349
+ ```bash
350
+ # Convex WebSocket API
351
+ NEXT_PUBLIC_CONVEX_URL=http://localhost:3210
352
+
353
+ # Convex HTTP site URL
354
+ NEXT_PUBLIC_CONVEX_SITE_URL=http://localhost:3211
355
+
356
+ # App URL for Better Auth client
357
+ NEXT_PUBLIC_SITE_URL=http://localhost:3000
358
+ ```
359
+
360
+ ### 4.2 Cloud
361
+
362
+ ```bash
363
+ # Generated by Convex
364
+ NEXT_PUBLIC_CONVEX_URL=https://your-project.convex.cloud
365
+
366
+ # Must be set manually
367
+ NEXT_PUBLIC_CONVEX_SITE_URL=https://your-project.convex.site
368
+
369
+ NEXT_PUBLIC_SITE_URL=http://localhost:3000
370
+ ```
371
+
372
+ Rule: real-time URL uses `.cloud`; HTTP/router/caller URL uses `.site`.
373
+
374
+ ### 4.3 Typed env helper (recommended for full backend parity)
375
+
376
+ When multiple Convex functions and libs share env values (auth, billing, dev guards), create one typed helper:
377
+
378
+ **Create:** `convex/lib/get-env.ts`
379
+
380
+ ```ts
381
+ import { createEnv } from "kitcn/server";
382
+ import { z } from "zod";
383
+
384
+ export const getEnv = createEnv({
385
+ schema: z.object({
386
+ DEPLOY_ENV: z.string().default("production"),
387
+ SITE_URL: z.string().default("http://localhost:3000"),
388
+ BETTER_AUTH_SECRET: z.string(),
389
+ JWKS: z.string().optional(),
390
+ ADMIN: z
391
+ .string()
392
+ .default("")
393
+ .transform((s) => (s ? s.split(",") : []))
394
+ .pipe(z.array(z.string())),
395
+ RESEND_API_KEY: z.string().optional(),
396
+ POLAR_ACCESS_TOKEN: z.string().optional(),
397
+ POLAR_SERVER: z.enum(["production", "sandbox"]).default("sandbox"),
398
+ POLAR_PRODUCT_PREMIUM: z.string().optional(),
399
+ POLAR_WEBHOOK_SECRET: z.string().optional(),
400
+ }),
401
+ });
402
+ ```
403
+
404
+ Then prefer `getEnv()` in Convex code instead of scattered `process.env`.
405
+
406
+ ## 11. Dev Scripts and CLI Workflow
407
+
408
+ ### 11.0 Plugin scaffold inspection
409
+
410
+ Use the plugin CLI as a plan engine, not a blind writer:
411
+
412
+ 1. `bunx kitcn add <plugin> --dry-run` → compact full-plan summary.
413
+ 2. `bunx kitcn add <plugin> --diff [path]` → unified diffs for planned file changes.
414
+ 3. `bunx kitcn add <plugin> --view [path]` → rendered planned file contents.
415
+ 4. `bunx kitcn view <plugin>` → inspect resolved preset, selection source, docs link, files, operations.
416
+ 5. `bunx kitcn info --json` → project paths, versions, installed plugins, schema/lockfile mismatch, missing deps, scaffold drift.
417
+ 6. `bunx kitcn docs <topic...>` → local/public docs links for `cli`, `plugins`, `auth`, `orm`, `migrations`, `resend`, `ratelimit`.
418
+
419
+ Rules:
420
+
421
+ 1. `kitcn add <plugin>` bootstraps baseline files first when they are missing.
422
+ 2. `--diff [path]` / `--view [path]` match workspace-relative output path by exact match first, substring fallback.
423
+ 3. Preview scope includes scaffold files, env bootstrap, `kitcn.json`, schema registration, lockfile write, dependency install status, codegen/hooks, env reminders.
424
+
425
+ ### 11.1 Dev bootstrap functions (example parity mode)
426
+
427
+ If you want the same operational model as the scaffolded baseline, use these canonical snippets.
428
+
429
+ **Create:** `convex/functions/init.ts`
430
+
431
+ ```ts
432
+ import { z } from "zod";
433
+
434
+ import { createUser } from "../lib/auth/auth-helpers";
435
+ import { privateMutation } from "../lib/crpc";
436
+ import { getEnv } from "../lib/get-env";
437
+ import { createSeedHandler } from "./generated/seed.runtime";
438
+
439
+ export default privateMutation
440
+ .meta({ dev: true })
441
+
442
+ .mutation(async ({ ctx }) => {
443
+ const env = getEnv();
444
+ const adminEmails = env.ADMIN;
445
+
446
+ if (!adminEmails || adminEmails.length === 0) {
447
+ return null;
448
+ }
449
+
450
+ let isFirstInit = true;
451
+
452
+ for (const adminEmail of adminEmails) {
453
+ const existingUser = await ctx.orm.query.user.findFirst({
454
+ where: { email: adminEmail },
455
+ });
456
+
457
+ if (existingUser) {
458
+ isFirstInit = false;
459
+ continue;
460
+ }
461
+
462
+ await createUser(ctx, {
463
+ email: adminEmail,
464
+ name: "Admin",
465
+ role: "admin",
466
+ });
467
+ }
468
+
469
+ if (isFirstInit && getEnv().DEPLOY_ENV === "development") {
470
+ const handler = createSeedHandler(ctx);
471
+ await handler.seed({});
472
+ }
473
+
474
+ return null;
475
+ });
476
+ ```
477
+
478
+ **Create:** `convex/functions/reset.ts`
479
+
480
+ ```ts
481
+ /** biome-ignore-all lint/suspicious/noExplicitAny: dev */
482
+ import { eq } from "kitcn/orm";
483
+ import { CRPCError } from "kitcn/server";
484
+ import { z } from "zod";
485
+
486
+ import { privateAction, privateMutation } from "../lib/crpc";
487
+ import { getEnv } from "../lib/get-env";
488
+ import type { TableNames } from "./_generated/dataModel";
489
+ import { createResetCaller } from "./generated/reset.runtime";
490
+ import schema, { tables } from "./schema";
491
+
492
+ const DELETE_BATCH_SIZE = 64;
493
+ const excludedTables = new Set<TableNames>();
494
+
495
+ const assertDevOnly = () => {
496
+ if (getEnv().DEPLOY_ENV === "production") {
497
+ throw new CRPCError({
498
+ code: "FORBIDDEN",
499
+ message: "This function is only available in development",
500
+ });
501
+ }
502
+ };
503
+
504
+ export const reset = privateAction.action(async ({ ctx }) => {
505
+ assertDevOnly();
506
+ const caller = createResetCaller(ctx);
507
+
508
+ for (const tableName of Object.keys(schema.tables)) {
509
+ if (excludedTables.has(tableName as TableNames)) {
510
+ continue;
511
+ }
512
+
513
+ await caller.schedule.now.deletePage({
514
+ cursor: null,
515
+ tableName,
516
+ });
517
+ }
518
+
519
+ return null;
520
+ });
521
+
522
+ export const deletePage = privateMutation
523
+ .input(
524
+ z.object({
525
+ cursor: z.union([z.string(), z.null()]),
526
+ tableName: z.string(),
527
+ }),
528
+ )
529
+
530
+ .mutation(async ({ ctx, input }) => {
531
+ assertDevOnly();
532
+ const caller = createResetCaller(ctx);
533
+
534
+ const table = (tables as Record<string, any>)[input.tableName];
535
+ if (!table) {
536
+ throw new CRPCError({
537
+ code: "BAD_REQUEST",
538
+ message: `Unknown table: ${input.tableName}`,
539
+ });
540
+ }
541
+
542
+ const query = (ctx.orm.query as Record<string, any>)[input.tableName];
543
+ if (!query || typeof query.findMany !== "function") {
544
+ throw new CRPCError({
545
+ code: "BAD_REQUEST",
546
+ message: `Unknown query table: ${input.tableName}`,
547
+ });
548
+ }
549
+
550
+ const results = await query.findMany({
551
+ cursor: input.cursor,
552
+ limit: DELETE_BATCH_SIZE,
553
+ });
554
+
555
+ for (const row of results.page) {
556
+ try {
557
+ await ctx.orm.delete(table).where(eq(table.id, (row as any).id));
558
+ } catch {
559
+ // Can already be deleted by trigger or concurrent process.
560
+ }
561
+ }
562
+
563
+ if (!results.isDone) {
564
+ await caller.schedule.now.deletePage({
565
+ cursor: results.continueCursor,
566
+ tableName: input.tableName,
567
+ });
568
+ }
569
+
570
+ return null;
571
+ });
572
+ ```
573
+
574
+ `convex/functions/seed.ts` stays project-specific, but should expose a `privateMutation` entrypoint used by `init.ts`.
575
+
576
+ Recommended scripts:
577
+
578
+ ```json
579
+ {
580
+ "scripts": {
581
+ "convex:dev": "kitcn dev",
582
+ "verify": "kitcn verify",
583
+ "reset": "kitcn reset --yes --after init",
584
+ "seed": "convex run seed:seed",
585
+ "env:push": "kitcn env push",
586
+ "env:push:rotate": "kitcn env push --rotate"
587
+ }
588
+ }
589
+ ```
590
+
591
+ Set `dev.preRun = "init"` in `kitcn.json` when the
592
+ app owns an `init.ts` preflight.
593
+
594
+ CLI commands:
595
+
596
+ ```bash
597
+ bunx kitcn dev
598
+ # deterministic one-shot local runtime proof:
599
+ bunx kitcn verify
600
+ # optional fallback only if dev cannot run and backend is already active:
601
+ bunx kitcn codegen
602
+ bunx kitcn env push
603
+ bunx kitcn env push --prod
604
+ bunx kitcn env push --rotate
605
+ # deploy with automatic aggregate backfill:
606
+ bunx kitcn deploy --prod
607
+ # aggregate index management:
608
+ bunx kitcn aggregate rebuild --prod
609
+ bunx kitcn aggregate backfill --prod
610
+ # bundle analysis:
611
+ bunx kitcn analyze
612
+ ```
613
+
614
+ On backend `convex`, `kitcn dev` watches `convex/.env` during a local
615
+ dev session and auto-pushes later edits. Keep `env push` for `--prod`,
616
+ `--rotate`, or explicit repair against an already active deployment.
617
+
618
+ ### 11.2 Phase A gate: non-auth baseline (required before auth work)
619
+
620
+ Run these after base setup (Sections 3-5) and before starting Section 6:
621
+
622
+ ```bash
623
+ bunx kitcn verify
624
+ bunx convex run internal.seed.seed
625
+ bunx convex run internal.init.default
626
+ # run project checks after bootstrap smoke:
627
+ bun run typecheck || bunx tsc --noEmit
628
+ bun test
629
+ bun run build
630
+ ```
631
+
632
+ Then sanity-check runtime paths (non-auth only):
633
+
634
+ 1. Run one public query endpoint.
635
+ 2. Run one public mutation endpoint.
636
+ 3. Run one public HTTP route endpoint.
637
+ 4. Do not proceed to Section 6 until this gate is green.
638
+
639
+ ### 11.3 Phase B gate: auth sign-in working (required before optional modules/plugins)
640
+
641
+ Run this after Section 6 and before Sections 7-10:
642
+
643
+ ```bash
644
+ bunx kitcn verify
645
+ bun run typecheck || bunx tsc --noEmit
646
+ bun test
647
+ bun run build
648
+ ```
649
+
650
+ Then sanity-check auth runtime paths:
651
+
652
+ 1. Sign in successfully from `/auth` in headed browser.
653
+ 2. Run one protected query/mutation in signed-in context and confirm success.
654
+ 3. Run one protected endpoint in signed-out context and confirm `UNAUTHORIZED`.
655
+ 4. Do not proceed to optional modules/plugins until this gate is green.
656
+
657
+ ## 12. Final From-Scratch Execution Checklist
658
+
659
+ 1. `convex.json` configured with `functions: convex/functions` and static codegen enabled.
660
+ 2. `tsconfig.json` has `strictFunctionTypes: false` and `@convex/*` alias.
661
+ 3. `.env.local` has `NEXT_PUBLIC_CONVEX_URL` and `NEXT_PUBLIC_CONVEX_SITE_URL`.
662
+ 4. `schema.ts` + `relations` + generated `initCRPC` wiring are in place.
663
+ 5. `crpc.ts` builders exported and app procedures use `ctx.orm`.
664
+ 6. `kitcn dev` runs and generates `_generated` + `api.ts`.
665
+ 7. If auth enabled: `auth.config.ts`, `auth.ts`, `http.ts`, and env bootstrap
666
+ are complete.
667
+ 8. Client `CRPCProvider` + QueryClient + Convex provider are mounted.
668
+ 9. Framework branch is complete (Next.js or TanStack Start).
669
+ 10. If using typed envs: `convex/lib/get-env.ts` exists and Convex code reads through `getEnv()`.
670
+ 11. Optional modules/plugins added only if selected.
671
+ 12. If multiple components enabled: `convex/functions/convex.config.ts` composes all `app.use(...)` calls in one file.
672
+ 13. If organizations + invite mail enabled: `email.tsx` + invite template + resend component are wired.
673
+ 14. If dev bootstrap mode enabled: `init.ts`, `seed.ts`, `reset.ts` exist and scripts call them.
674
+ 15. If `Aggregates: No`, no aggregate helper/import/config references remain.
675
+ 16. Phase A gate (Section 11.2) passes before any auth implementation.
676
+ 17. If auth enabled: Phase B auth sign-in gate (Section 11.3) passes before optional modules/plugins.
677
+ 18. No legacy Ents patterns in setup code.
678
+ 19. NEVER use `@ts-nocheck` in app/convex source files.
679
+
680
+ ## 13. Troubleshooting
681
+
682
+ See the [Troubleshooting Reference](#troubleshooting-reference) at the bottom of this document for the full symptom/cause/fix matrix.
683
+
684
+ ## Coverage Matrix
685
+
686
+ Source coverage mapping used to build this runbook:
687
+
688
+ | Source | Mapped In Setup |
689
+ | ------------------------------------------------- | -------------------- |
690
+ | `www/content/docs/cli/registry.mdx` | Sections 3, 11 |
691
+ | `www/content/docs/quickstart.mdx` | Sections 3, 4, 11, 12 |
692
+ | `www/content/docs/server/setup.mdx` | Section 5.3 |
693
+ | `www/content/docs/auth/server.mdx` | Sections 6.1 - 6.10 |
694
+ | `www/content/docs/auth/client.mdx` | Section 7.1 |
695
+ | `www/content/docs/auth/server.mdx#triggers` | Section 6.3, 9.2 |
696
+ | `www/content/docs/react/index.mdx` | Sections 7.2 - 7.4 |
697
+ | `www/content/docs/nextjs/index.mdx` | Section 8.A |
698
+ | `www/content/docs/tanstack-start.mdx` | Section 8.B |
699
+ | `www/content/docs/server/http.mdx` | Sections 6.6, 9.6 |
700
+ | `www/content/docs/server/server-side-calls.mdx` | Section 8.A.1, 8.B.3 |
701
+ | `www/content/docs/plugins/ratelimit.mdx` | Section 9.4 |
702
+ | `www/content/docs/orm/queries/aggregates.mdx` | Section 9.3 |
703
+ | `www/content/docs/server/scheduling.mdx` | Section 9.5 |
704
+ | `www/content/docs/orm/queries/index.mdx` | Sections 5, 12 |
705
+ | `www/content/docs/orm/mutations/index.mdx` | Sections 5, 12 |
706
+ | `www/content/docs/orm/triggers.mdx` | Sections 9.2, 9.3 |
707
+ | `www/content/docs/orm/rls.mdx` | Section 9.1 |
708
+ | `www/content/docs/auth/plugins/admin.mdx` | Section 10.1 |
709
+ | `www/content/docs/auth/plugins/organizations.mdx` | Section 10.2 |
710
+ | `www/content/docs/auth/plugins/polar.mdx` | Section 10.3 |
711
+ | `www/content/docs/cli/backend.mdx` | Section 11 |
712
+
713
+ ### Template Coverage (Recreation Target)
714
+
715
+ This runbook + references map to the canonical template shape as follows:
716
+
717
+ | Example Group | Primary Setup Section | Additional Reference |
718
+ | --------------------------------------------------------------------------------------------------------- | ------------------------------- | ---------------------------------------- |
719
+ | Core infra (`schema.ts`, `functions/generated/`, `crpc.ts`, `http.ts`) | Sections 5, 6.6, 9.6 | `orm.md`, `http.md` |
720
+ | Shared contracts (`shared/api.ts`, `shared/auth-shared.ts`, `shared/polar-shared.ts`) | Sections 5.4, 6.3.2, 10.2, 10.3 | `auth-organizations.md` |
721
+ | Auth core (`auth.config.ts`, `auth.ts`) | Section 6 | `auth.md` |
722
+ | Auth plugins (`admin.ts`, `organization.ts`, `polar*`) | Section 10 | `auth-admin.md`, `auth-organizations.md` |
723
+ | Feature modules (`user.ts`, `projects.ts`, `tags.ts`, `todoComments.ts`, `public.ts`, `items/queries.ts`) | Sections 5, 6.3.1, 9 | core `SKILL.md`, `orm.md` |
724
+ | HTTP routers (`routers/health.ts`, `routers/todos.ts`, `routers/examples.ts`) | Section 9.6 | `http.md` |
725
+ | Aggregates + rate limits (`aggregates.ts`, `lib/plugins/ratelimit/plugin.ts`) | Sections 9.3, 9.4 | `aggregates.md`, `orm.md` |
726
+ | Scheduling + internals (`todoInternal.ts`, delayed jobs) | Sections 9.5, 11.1 | `scheduling.md` |
727
+ | Email + Resend (`functions/plugins/email.tsx`, `lib/plugins/resend/*`) | Section 9.7 | `auth-organizations.md` |
728
+ | Dev bootstrap (`init.ts`, `seed.ts`, `reset.ts`) | Section 11.1 | `testing.md` (for verification) |
729
+ | Generated outputs (`functions/_generated/*`, `functions/generated/`, `shared/api.ts`) | Section 5.5 | n/a (generated by CLI) |
730
+
731
+ ## Troubleshooting Reference
732
+
733
+ | Symptom | Likely Cause | Fix |
734
+ | ------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
735
+ | `@convex/api` not found | `kitcn dev` not run | Run `bunx kitcn dev` and regenerate API metadata |
736
+ | `Cannot prompt for input in non-interactive terminals` during bootstrap | Convex deployment selection still needs a local choice | Use `bunx kitcn verify` for local proof, or pass `--env-file` / deployment-target args so Convex can resolve the deployment without prompting |
737
+ | Can't find new local backend files under `~/.convex` | Convex now stores new local deployment state per project | Check `.convex/local/default/` in the current project root; treat `~/.convex/**` as legacy storage |
738
+ | `kitcn env push` fails to set auth vars | Target deployment is not active or not initialized | For local proof, run `bunx kitcn verify`. For remote targets, resolve deployment targeting, then rerun `bunx kitcn env push` |
739
+ | `Failed to analyze auth.js` with `Unexpected token` / `map is not a function` on JWKS | Static `JWKS` value is malformed JSON | Unset/fix `JWKS`; use `getAuthConfigProvider()` fallback or repush with `bunx kitcn env push` |
740
+ | `Local backend isn't running` during manual `kitcn codegen` | Convex local deployment not active | Prefer `bunx kitcn dev` (it already codegens); use manual `codegen` only as fallback with active backend |
741
+ | HTTP calls fail but queries work | `.site` URL missing or wrong | Set `NEXT_PUBLIC_CONVEX_SITE_URL` correctly |
742
+ | Auth works locally but fails in prod | JWKS not pushed | Run `bunx kitcn env push --prod` |
743
+ | Sign-in fails on `/auth` (loop, no session, or immediate sign-out) | Auth route/env/provider wiring mismatch | Recheck Sections 6.5-6.7 (`authMiddleware`, route registration, env push), verify provider credentials/URLs, then rerun Section 11.3 |
744
+ | `UNAUTHORIZED` on protected procedures | auth middleware not attaching `userId` | Ensure `getAuth(ctx)` + `getHeaders(ctx)` session lookup is in middleware |
745
+ | `ctx.orm` missing in handlers | Generated `initCRPC` not used | Use `initCRPC` from `../functions/generated/server` — ORM context is pre-wired |
746
+ | `Property 'insert'/'update' does not exist on type 'OrmReader'` | Using query context for mutations | Ensure mutation handlers use `publicMutation` / `protectedMutation` builders |
747
+ | `useCRPC must be used within CRPCProvider` | Provider chain not mounted around route tree | Wrap app with `AppConvexProvider` and verify `CRPCProvider` is inside QueryClientProvider (Section 7.4 / 8.A.4) |
748
+ | Route auth cookies not set | Missing CORS auth headers | Add `Better-Auth-Cookie` allow/expose headers + credentials |
749
+ | TanStack Start auth helper import errors | Using `kitcn/auth/nextjs` in Start app | Use TanStack Start exception with `@convex-dev/better-auth/*` helpers |
750
+ | `Returned promise will never resolve` from internal function | Trigger path is recursively querying/updating related rows or stale component wiring still runs | Isolate failing write with logs, disable/move trigger-side sync into explicit mutation helper, rerun `bunx kitcn verify`, then retry the runtime proof |
751
+ | Better Auth secret mismatch/warnings in setup flows | `BETTER_AUTH_SECRET` manually set inconsistently or low entropy | Let `bunx kitcn dev` manage local bootstrap, or regenerate/push via `bunx kitcn env push` for active non-local targets |
752
+ | `Invalid orderBy value. Use a column or asc()/desc()` | Wrong `orderBy` shape (`[{ field, direction }]`) | Use object form only, e.g. `orderBy: { updatedAt: "desc" }` |
753
+ | `Invalid argument id for db.get` while testing `NOT_FOUND` | Fabricated Convex document ID | Use real inserted IDs or non-ID lookup keys (slug/name/email) for not-found tests |
754
+ | Trigger side effects too slow | Heavy sync work inside trigger | Move heavy work to scheduled actions via `ctx.scheduler` |
755
+ | Rate limiter throws missing-table/setup guidance | local ratelimit scaffold missing or not registered | Run `bunx kitcn add ratelimit`, then ensure `convex/functions/schema.ts` imports `../lib/plugins/ratelimit/schema` |
756
+ | fallback `kitcn codegen` fails after disabling aggregates | Aggregate helper/import references still exist | Remove `app.use(aggregate...)`, `defineTriggers` aggregate handlers, and aggregate helper modules in the same change; prefer rerunning `kitcn verify` |
757
+ | Aggregate counts drift | trigger not registered in `defineTriggers` | Register `aggregate.trigger` in `defineTriggers` `change:` handler |
758
+ | Invite emails never send | Resend schema scaffold missing or not registered | Run `bunx kitcn add resend`, ensure `convex/functions/schema.ts` imports `../lib/plugins/resend/schema`, and wire `internal.plugins.email.sendTemplatedEmail` |
759
+ | Dev reset/seed commands do nothing | `init.ts`/`seed.ts`/`reset.ts` missing or not wired | Add dev bootstrap functions and scripts from Section 11.1 |