create-kerf 0.0.0-stage → 0.1.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 (128) hide show
  1. package/LICENSE +16 -0
  2. package/README.md +401 -2
  3. package/bin/create-kerf.mjs +121 -0
  4. package/package.json +37 -3
  5. package/scripts/tarballs.mjs +77 -0
  6. package/src/data.mjs +360 -0
  7. package/src/index.mjs +400 -0
  8. package/src/stack/pages.mjs +151 -0
  9. package/src/stack/schema.mjs +195 -0
  10. package/src/stack.mjs +293 -0
  11. package/src/templates.mjs +175 -0
  12. package/src/wizard.mjs +127 -0
  13. package/templates/admin/files/drizzle/.schema-hash +1 -0
  14. package/templates/admin/files/drizzle/0000_admin.sql +136 -0
  15. package/templates/admin/files/drizzle/meta/0000_snapshot.json +771 -0
  16. package/templates/admin/files/drizzle/meta/_journal.json +13 -0
  17. package/templates/admin/files/kerf.config.ts +31 -0
  18. package/templates/admin/files/public/favicon.svg +1 -0
  19. package/templates/admin/files/src/auth.server.ts +24 -0
  20. package/templates/admin/files/src/components/AuthPage.tsx +33 -0
  21. package/templates/admin/files/src/components/Failed.tsx +19 -0
  22. package/templates/admin/files/src/components/Logo.tsx +16 -0
  23. package/templates/admin/files/src/components/OrderDetail.tsx +93 -0
  24. package/templates/admin/files/src/components/OrdersFilters.tsx +44 -0
  25. package/templates/admin/files/src/components/OrdersTable.tsx +144 -0
  26. package/templates/admin/files/src/components/Overview.tsx +113 -0
  27. package/templates/admin/files/src/components/StatusBadge.tsx +12 -0
  28. package/templates/admin/files/src/db/schema.ts +68 -0
  29. package/templates/admin/files/src/lib/orders.ts +60 -0
  30. package/templates/admin/files/src/routes/404.tsx +20 -0
  31. package/templates/admin/files/src/routes/_error.tsx +20 -0
  32. package/templates/admin/files/src/routes/_layout.tsx +6 -0
  33. package/templates/admin/files/src/routes/admin/_layout.tsx +89 -0
  34. package/templates/admin/files/src/routes/admin/index.tsx +45 -0
  35. package/templates/admin/files/src/routes/admin/nested/_layout.tsx +35 -0
  36. package/templates/admin/files/src/routes/admin/nested/index.tsx +77 -0
  37. package/templates/admin/files/src/routes/admin/orders/[id].tsx +24 -0
  38. package/templates/admin/files/src/routes/admin/orders/index.tsx +28 -0
  39. package/templates/admin/files/src/routes/admin/per-row.tsx +81 -0
  40. package/templates/admin/files/src/routes/admin/slow.tsx +74 -0
  41. package/templates/admin/files/src/routes/index.tsx +13 -0
  42. package/templates/admin/files/src/routes/login.tsx +53 -0
  43. package/templates/admin/files/src/routes/signup.tsx +60 -0
  44. package/templates/admin/files/src/server/orders.ts +193 -0
  45. package/templates/admin/files/src/server/reports.ts +92 -0
  46. package/templates/admin/files/src/server/session.ts +45 -0
  47. package/templates/admin/files/src/theme.css +43 -0
  48. package/templates/admin/template.json +22 -0
  49. package/templates/catalog/files/drizzle/.schema-hash +1 -0
  50. package/templates/catalog/files/drizzle/0000_catalog.sql +47 -0
  51. package/templates/catalog/files/drizzle/meta/0000_snapshot.json +263 -0
  52. package/templates/catalog/files/drizzle/meta/_journal.json +13 -0
  53. package/templates/catalog/files/kerf.config.ts +30 -0
  54. package/templates/catalog/files/public/favicon.svg +1 -0
  55. package/templates/catalog/files/seed.sql +13 -0
  56. package/templates/catalog/files/src/components/AddToCart.tsx +22 -0
  57. package/templates/catalog/files/src/components/Aisles.tsx +31 -0
  58. package/templates/catalog/files/src/components/CartLines.tsx +96 -0
  59. package/templates/catalog/files/src/components/CartLink.tsx +29 -0
  60. package/templates/catalog/files/src/components/Failed.tsx +19 -0
  61. package/templates/catalog/files/src/components/Featured.tsx +19 -0
  62. package/templates/catalog/files/src/components/Filters.tsx +40 -0
  63. package/templates/catalog/files/src/components/Logo.tsx +16 -0
  64. package/templates/catalog/files/src/components/ProductArt.tsx +42 -0
  65. package/templates/catalog/files/src/components/ProductCard.tsx +42 -0
  66. package/templates/catalog/files/src/components/ProductList.tsx +65 -0
  67. package/templates/catalog/files/src/components/Related.tsx +19 -0
  68. package/templates/catalog/files/src/components/SiteFooter.tsx +9 -0
  69. package/templates/catalog/files/src/components/SiteHeader.tsx +16 -0
  70. package/templates/catalog/files/src/db/schema.ts +53 -0
  71. package/templates/catalog/files/src/lib/catalog.ts +35 -0
  72. package/templates/catalog/files/src/routes/404.tsx +18 -0
  73. package/templates/catalog/files/src/routes/_error.tsx +18 -0
  74. package/templates/catalog/files/src/routes/_layout.tsx +14 -0
  75. package/templates/catalog/files/src/routes/c/[slug].tsx +53 -0
  76. package/templates/catalog/files/src/routes/cart.tsx +29 -0
  77. package/templates/catalog/files/src/routes/index.tsx +84 -0
  78. package/templates/catalog/files/src/routes/p/[slug].tsx +67 -0
  79. package/templates/catalog/files/src/server/cart.ts +125 -0
  80. package/templates/catalog/files/src/server/catalog.ts +107 -0
  81. package/templates/catalog/files/src/theme.css +159 -0
  82. package/templates/catalog/template.json +20 -0
  83. package/templates/landing/files/.kerf/plugins.lock.json +42 -0
  84. package/templates/landing/files/assets/fonts/LICENSE-figtree.txt +93 -0
  85. package/templates/landing/files/assets/fonts/figtree.woff2 +0 -0
  86. package/templates/landing/files/assets/hero.webp +0 -0
  87. package/templates/landing/files/drizzle/.schema-hash +1 -0
  88. package/templates/landing/files/drizzle/0000_landing.sql +6 -0
  89. package/templates/landing/files/drizzle/meta/0000_snapshot.json +60 -0
  90. package/templates/landing/files/drizzle/meta/_journal.json +13 -0
  91. package/templates/landing/files/kerf.config.ts +44 -0
  92. package/templates/landing/files/public/favicon.svg +1 -0
  93. package/templates/landing/files/src/components/SiteFooter.tsx +24 -0
  94. package/templates/landing/files/src/components/SiteHeader.tsx +23 -0
  95. package/templates/landing/files/src/components/WaitlistForm.tsx +36 -0
  96. package/templates/landing/files/src/db/schema.ts +7 -0
  97. package/templates/landing/files/src/routes/404.tsx +24 -0
  98. package/templates/landing/files/src/routes/_error.tsx +24 -0
  99. package/templates/landing/files/src/routes/_layout.tsx +14 -0
  100. package/templates/landing/files/src/routes/index.tsx +130 -0
  101. package/templates/landing/files/src/routes/joined.tsx +30 -0
  102. package/templates/landing/files/src/routes/pricing.tsx +131 -0
  103. package/templates/landing/files/src/routes/privacy.tsx +56 -0
  104. package/templates/landing/files/src/server/waitlist.ts +13 -0
  105. package/templates/landing/files/src/theme.css +108 -0
  106. package/templates/landing/template.json +17 -0
  107. package/templates/todo/files/drizzle/.schema-hash +1 -0
  108. package/templates/todo/files/drizzle/0000_todo.sql +82 -0
  109. package/templates/todo/files/drizzle/meta/0000_snapshot.json +462 -0
  110. package/templates/todo/files/drizzle/meta/_journal.json +13 -0
  111. package/templates/todo/files/kerf.config.ts +30 -0
  112. package/templates/todo/files/public/favicon.svg +1 -0
  113. package/templates/todo/files/src/components/AuthPage.tsx +33 -0
  114. package/templates/todo/files/src/components/Logo.tsx +14 -0
  115. package/templates/todo/files/src/components/NewTodo.tsx +27 -0
  116. package/templates/todo/files/src/components/TodoList.tsx +101 -0
  117. package/templates/todo/files/src/db/schema.ts +18 -0
  118. package/templates/todo/files/src/lib/views.ts +13 -0
  119. package/templates/todo/files/src/routes/404.tsx +20 -0
  120. package/templates/todo/files/src/routes/_error.tsx +20 -0
  121. package/templates/todo/files/src/routes/_layout.tsx +6 -0
  122. package/templates/todo/files/src/routes/index.tsx +13 -0
  123. package/templates/todo/files/src/routes/login.tsx +53 -0
  124. package/templates/todo/files/src/routes/signup.tsx +57 -0
  125. package/templates/todo/files/src/routes/todos.tsx +87 -0
  126. package/templates/todo/files/src/server/todos.ts +98 -0
  127. package/templates/todo/files/src/theme.css +71 -0
  128. package/templates/todo/template.json +18 -0
@@ -0,0 +1,195 @@
1
+ export const authTablesFile = (db) =>
2
+ ({
3
+ sqlite: () =>
4
+ `import { integer, sqliteTable, text } from 'drizzle-orm/sqlite-core'\n${authTablesSqlite()}`,
5
+ postgres: () =>
6
+ `import { boolean, pgTable, text, timestamp } from 'drizzle-orm/pg-core'\n${authTablesPg()}`,
7
+ mysql: () =>
8
+ `import { boolean, mysqlTable, text, timestamp, varchar } from 'drizzle-orm/mysql-core'\n${authTablesMysql()}`,
9
+ })[db]()
10
+
11
+ const camel = (column) => column.replace(/_(\w)/g, (_, c) => c.toUpperCase())
12
+
13
+ /** A template's `src/db/auth.ts`: Better Auth's own column names with time zones, as examples/shared/pg/schema.sql has them. */
14
+ export const sharedAuthTables = () =>
15
+ `import { boolean, pgTable, text, timestamp } from 'drizzle-orm/pg-core'\n${authTablesPg().replace(
16
+ /(text|boolean|timestamp)\('(\w+)'\)/g,
17
+ (_, type, column) =>
18
+ `${type}('${camel(column)}'${type === 'timestamp' ? ', { withTimezone: true }' : ''})`,
19
+ )}`
20
+
21
+ export function sqliteSchema(auth) {
22
+ const owner = auth
23
+ ? `\n userId: text('user_id').notNull().references(() => user.id, { onDelete: 'cascade' }),`
24
+ : ''
25
+ return `import { integer, sqliteTable, text } from 'drizzle-orm/sqlite-core'
26
+ ${auth ? authTablesSqlite() : ''}
27
+ export const todos = sqliteTable('todos', {
28
+ id: text('id').primaryKey(),${owner}
29
+ title: text('title').notNull(),
30
+ done: integer('done', { mode: 'boolean' }).notNull().default(false),
31
+ createdAt: integer('created_at').notNull(),
32
+ })
33
+ `
34
+ }
35
+
36
+ export function pgSchema(auth) {
37
+ const owner = auth
38
+ ? `\n userId: text('user_id').notNull().references(() => user.id, { onDelete: 'cascade' }),`
39
+ : ''
40
+ return `import { bigint, boolean, pgTable, text${auth ? ', timestamp' : ''} } from 'drizzle-orm/pg-core'
41
+ ${auth ? authTablesPg() : ''}
42
+ export const todos = pgTable('todos', {
43
+ id: text('id').primaryKey(),${owner}
44
+ title: text('title').notNull(),
45
+ done: boolean('done').notNull().default(false),
46
+ createdAt: bigint('created_at', { mode: 'number' }).notNull(),
47
+ })
48
+ `
49
+ }
50
+
51
+ // MySQL can't index a TEXT column, so ids, keys and anything unique are VARCHAR. Otherwise Postgres's tables hold.
52
+ const authTablesMysql = () =>
53
+ authTablesPg()
54
+ .replaceAll('pgTable', 'mysqlTable')
55
+ .replace(
56
+ /text\('(id|user_id|email|token|account_id|provider_id|identifier)'\)/g,
57
+ "varchar('$1', { length: 255 })",
58
+ )
59
+ .replace(/timestamp\('(\w+)'\)/g, "timestamp('$1', { fsp: 3 })")
60
+
61
+ export function mysqlSchema(auth) {
62
+ const owner = auth
63
+ ? `\n userId: varchar('user_id', { length: 255 }).notNull().references(() => user.id, { onDelete: 'cascade' }),`
64
+ : ''
65
+ return `import { bigint, boolean, mysqlTable, ${auth ? 'text, timestamp, ' : ''}varchar } from 'drizzle-orm/mysql-core'
66
+ ${auth ? authTablesMysql() : ''}
67
+ export const todos = mysqlTable('todos', {
68
+ id: varchar('id', { length: 36 }).primaryKey(),${owner}
69
+ title: varchar('title', { length: 200 }).notNull(),
70
+ done: boolean('done').notNull().default(false),
71
+ createdAt: bigint('created_at', { mode: 'number' }).notNull(),
72
+ })
73
+ `
74
+ }
75
+
76
+ const authTablesSqlite = () => {
77
+ const when = (col, opts = '.notNull()') => `integer('${col}', { mode: 'timestamp_ms' })${opts}`
78
+ return `
79
+ // Better Auth's tables: it reads and writes them through Drizzle, with these names.
80
+ export const user = sqliteTable('user', {
81
+ id: text('id').primaryKey(),
82
+ name: text('name').notNull(),
83
+ email: text('email').notNull().unique(),
84
+ emailVerified: integer('email_verified', { mode: 'boolean' }).notNull(),
85
+ image: text('image'),
86
+ createdAt: ${when('created_at')},
87
+ updatedAt: ${when('updated_at')},
88
+ })
89
+
90
+ export const session = sqliteTable('session', {
91
+ id: text('id').primaryKey(),
92
+ expiresAt: ${when('expires_at')},
93
+ token: text('token').notNull().unique(),
94
+ createdAt: ${when('created_at')},
95
+ updatedAt: ${when('updated_at')},
96
+ ipAddress: text('ip_address'),
97
+ userAgent: text('user_agent'),
98
+ userId: text('user_id').notNull().references(() => user.id, { onDelete: 'cascade' }),
99
+ })
100
+
101
+ export const account = sqliteTable('account', {
102
+ id: text('id').primaryKey(),
103
+ accountId: text('account_id').notNull(),
104
+ providerId: text('provider_id').notNull(),
105
+ userId: text('user_id').notNull().references(() => user.id, { onDelete: 'cascade' }),
106
+ accessToken: text('access_token'),
107
+ refreshToken: text('refresh_token'),
108
+ idToken: text('id_token'),
109
+ accessTokenExpiresAt: ${when('access_token_expires_at', '')},
110
+ refreshTokenExpiresAt: ${when('refresh_token_expires_at', '')},
111
+ scope: text('scope'),
112
+ password: text('password'),
113
+ createdAt: ${when('created_at')},
114
+ updatedAt: ${when('updated_at')},
115
+ })
116
+
117
+ export const verification = sqliteTable('verification', {
118
+ id: text('id').primaryKey(),
119
+ identifier: text('identifier').notNull(),
120
+ value: text('value').notNull(),
121
+ expiresAt: ${when('expires_at')},
122
+ createdAt: ${when('created_at', '')},
123
+ updatedAt: ${when('updated_at', '')},
124
+ })
125
+
126
+ export const jwks = sqliteTable('jwks', {
127
+ id: text('id').primaryKey(),
128
+ publicKey: text('public_key').notNull(),
129
+ privateKey: text('private_key').notNull(),
130
+ createdAt: ${when('created_at')},
131
+ expiresAt: ${when('expires_at', '')},
132
+ alg: text('alg'),
133
+ crv: text('crv'),
134
+ })
135
+ `
136
+ }
137
+
138
+ const authTablesPg = () => `
139
+ // Better Auth's tables: it reads and writes them through Drizzle, with these names.
140
+ export const user = pgTable('user', {
141
+ id: text('id').primaryKey(),
142
+ name: text('name').notNull(),
143
+ email: text('email').notNull().unique(),
144
+ emailVerified: boolean('email_verified').notNull(),
145
+ image: text('image'),
146
+ createdAt: timestamp('created_at').notNull(),
147
+ updatedAt: timestamp('updated_at').notNull(),
148
+ })
149
+
150
+ export const session = pgTable('session', {
151
+ id: text('id').primaryKey(),
152
+ expiresAt: timestamp('expires_at').notNull(),
153
+ token: text('token').notNull().unique(),
154
+ createdAt: timestamp('created_at').notNull(),
155
+ updatedAt: timestamp('updated_at').notNull(),
156
+ ipAddress: text('ip_address'),
157
+ userAgent: text('user_agent'),
158
+ userId: text('user_id').notNull().references(() => user.id, { onDelete: 'cascade' }),
159
+ })
160
+
161
+ export const account = pgTable('account', {
162
+ id: text('id').primaryKey(),
163
+ accountId: text('account_id').notNull(),
164
+ providerId: text('provider_id').notNull(),
165
+ userId: text('user_id').notNull().references(() => user.id, { onDelete: 'cascade' }),
166
+ accessToken: text('access_token'),
167
+ refreshToken: text('refresh_token'),
168
+ idToken: text('id_token'),
169
+ accessTokenExpiresAt: timestamp('access_token_expires_at'),
170
+ refreshTokenExpiresAt: timestamp('refresh_token_expires_at'),
171
+ scope: text('scope'),
172
+ password: text('password'),
173
+ createdAt: timestamp('created_at').notNull(),
174
+ updatedAt: timestamp('updated_at').notNull(),
175
+ })
176
+
177
+ export const verification = pgTable('verification', {
178
+ id: text('id').primaryKey(),
179
+ identifier: text('identifier').notNull(),
180
+ value: text('value').notNull(),
181
+ expiresAt: timestamp('expires_at').notNull(),
182
+ createdAt: timestamp('created_at'),
183
+ updatedAt: timestamp('updated_at'),
184
+ })
185
+
186
+ export const jwks = pgTable('jwks', {
187
+ id: text('id').primaryKey(),
188
+ publicKey: text('public_key').notNull(),
189
+ privateKey: text('private_key').notNull(),
190
+ createdAt: timestamp('created_at').notNull(),
191
+ expiresAt: timestamp('expires_at'),
192
+ alg: text('alg'),
193
+ crv: text('crv'),
194
+ })
195
+ `
package/src/stack.mjs ADDED
@@ -0,0 +1,293 @@
1
+ // The `--db` and `--auth` part of a scaffold: a database, a todo app on it, and with `--auth` a
2
+ // sign-in/sign-up flow and a guarded `/todos`. Pinned versions, so a scaffold builds what the matrix tested.
3
+ import { readFileSync } from 'node:fs'
4
+ import {
5
+ nativeAuthSql,
6
+ nativeFiles,
7
+ prismaAdapterPackage,
8
+ prismaAuthModels,
9
+ prismaFiles,
10
+ } from './data.mjs'
11
+ import { authTablesFile, sqliteSchema, pgSchema, mysqlSchema } from './stack/schema.mjs'
12
+ import { loginPage } from './stack/pages.mjs'
13
+ export { sharedAuthTables } from './stack/schema.mjs'
14
+ export {
15
+ tailwindPackages,
16
+ TAILWIND_VITE,
17
+ TAILWIND_CSS,
18
+ classes,
19
+ controls,
20
+ todosPage,
21
+ loginPage,
22
+ } from './stack/pages.mjs'
23
+
24
+ /** The version a scaffold pins for each package it adds that isn't kerf's own: what the matrix tested. */
25
+ export const VERSIONS = {
26
+ '@types/node': '26.6.5',
27
+ '@t3-oss/env-core': '0.13.11',
28
+ 'better-auth': '1.7.14',
29
+ 'drizzle-kit': '0.31.11',
30
+ 'drizzle-orm': '0.45.4',
31
+ 'drizzle-zod': '0.8.3',
32
+ kysely: '0.29.7',
33
+ mysql2: '3.24.6',
34
+ postgres: '4.0.0',
35
+ zod: '4.6.7',
36
+ prisma: '7.10.1',
37
+ '@prisma/client': '7.10.1',
38
+ '@prisma/adapter-libsql': '7.10.1',
39
+ '@prisma/adapter-pg': '7.10.1',
40
+ '@prisma/adapter-mariadb': '7.10.1',
41
+ }
42
+
43
+ const pin = (...names) => Object.fromEntries(names.map((n) => [n, VERSIONS[n]]))
44
+
45
+ const drivers = (db) => (db === 'postgres' ? ['postgres'] : db === 'mysql' ? ['mysql2'] : [])
46
+
47
+ /** Every scaffold pins what it shipped with: this package and kerf's others go out at one version. */
48
+ export const VERSION = JSON.parse(
49
+ readFileSync(new URL('../package.json', import.meta.url), 'utf8'),
50
+ ).version
51
+
52
+ /** The pinned dependencies of a database, data layer and auth choice. */
53
+ export function stackDeps({ db, auth, layer = 'drizzle', version = VERSION }) {
54
+ if (db === 'none') return { deps: {}, dev: {} }
55
+ const base = pin('@t3-oss/env-core', 'zod', ...(auth ? ['better-auth'] : []))
56
+ if (layer === 'native')
57
+ return {
58
+ deps: {
59
+ ...base,
60
+ ...pin(...drivers(db), ...(auth ? ['kysely'] : [])),
61
+ '@kerf-js/db': version,
62
+ },
63
+ dev: pin('@types/node'),
64
+ }
65
+ if (layer === 'prisma')
66
+ return {
67
+ deps: { ...base, ...pin('@prisma/client', prismaAdapterPackage(db)), '@kerf-js/db': version },
68
+ dev: pin('prisma', '@types/node'),
69
+ }
70
+ return {
71
+ deps: pin(
72
+ '@t3-oss/env-core',
73
+ 'drizzle-orm',
74
+ 'drizzle-zod',
75
+ 'zod',
76
+ ...drivers(db),
77
+ ...(auth ? ['better-auth'] : []),
78
+ ),
79
+ dev: pin('drizzle-kit', '@types/node'),
80
+ }
81
+ }
82
+
83
+ /** Sign-in on an app with a database, for `kerf add auth`: new files only, and what to add to the existing ones. */
84
+ export function authFiles({ db, layer, ui }) {
85
+ const files = stackFiles({ db, layer, auth: true, name: 'app', secret: '' })
86
+ const out = {
87
+ 'src/auth.server.ts': files['src/auth.server.ts'],
88
+ 'src/server/session.ts': files['src/server/session.ts'],
89
+ 'src/routes/login.tsx': loginPage(ui),
90
+ }
91
+ return {
92
+ files: out,
93
+ context: files['src/context.server.ts'],
94
+ tables: {
95
+ drizzle: authTablesFile(db),
96
+ prisma: prismaAuthModels(db),
97
+ native: nativeAuthSql(db),
98
+ }[layer],
99
+ }
100
+ }
101
+
102
+ /** The files of a database, data layer and auth choice, as `{ path: text }`. */
103
+ export function stackFiles({ db, auth, name, secret, layer = 'drizzle' }) {
104
+ const shared = {
105
+ '.env': envFile({ db, auth, name, secret }),
106
+ '.env.example': envFile({ db, auth, name, secret: '' }),
107
+ 'src/env.server.ts': envModule({ db, auth }),
108
+ 'src/context.server.ts': context(auth),
109
+ 'src/routes/todos/index.tsx': '', // filled by the caller, which knows the UI kit
110
+ ...(auth && {
111
+ 'src/server/session.ts': sessionServer(),
112
+ 'src/routes/todos/_layout.tsx': guard(),
113
+ }),
114
+ }
115
+ if (layer === 'native') return { ...shared, ...nativeFiles({ db, auth }) }
116
+ if (layer === 'prisma') return { ...shared, ...prismaFiles({ db, auth }) }
117
+ return { ...shared, ...drizzleFiles({ db, auth }) }
118
+ }
119
+
120
+ function drizzleFiles({ db, auth }) {
121
+ return {
122
+ 'drizzle.config.ts': `import { defineConfig } from 'drizzle-kit'\n\nexport default defineConfig({ dialect: '${{ postgres: 'postgresql', sqlite: 'sqlite', mysql: 'mysql' }[db]}', schema: './src/db/schema.ts', out: './drizzle' })\n`,
123
+ 'src/db/schema.ts': { postgres: pgSchema, sqlite: sqliteSchema, mysql: mysqlSchema }[db](auth),
124
+ 'src/db/index.server.ts': `import { createDb } from '@kerf-js/start/db/${db}'\nimport { env } from '../env.server'\nimport * as schema from './schema'\n\nexport const db = createDb({ schema, url: env.DATABASE_URL })\n`,
125
+ 'src/server/todos.ts': todosServer(auth, db),
126
+ ...(auth && {
127
+ 'src/auth.server.ts': `import { createAuth } from '@kerf-js/start/auth/better-auth'\nimport { drizzleAuth } from '@kerf-js/start/auth/drizzle'\nimport { db } from '#/db/index.server'\nimport * as schema from './db/schema'\nimport { env } from './env.server'\n\nexport default createAuth({ db, secret: env.BETTER_AUTH_SECRET, options: { database: drizzleAuth(db, schema) } })\n`,
128
+ }),
129
+ }
130
+ }
131
+
132
+ const database = (name) => name.replace(/[^a-z0-9_]/g, '_')
133
+ const envFile = ({ db, auth, name, secret }) =>
134
+ ({
135
+ postgres: `DATABASE_URL=postgres://localhost:5432/${database(name)}\n`,
136
+ mysql: `DATABASE_URL=mysql://root@localhost:3306/${database(name)}\n`,
137
+ sqlite: 'DATABASE_URL=file:.data/app.db\n',
138
+ })[db] + (auth ? `BETTER_AUTH_SECRET=${secret}\nBETTER_AUTH_URL=http://localhost:5173\n` : '')
139
+
140
+ const envModule = ({ db, auth }) => `import { createEnv } from '@t3-oss/env-core'
141
+ import { z } from 'zod'
142
+
143
+ // Checked when the server starts. A build holds no secrets, so \`kerf build\` skips it.
144
+ export const env = createEnv({
145
+ server: {
146
+ DATABASE_URL: ${db !== 'sqlite' ? 'z.url()' : "z.string().min(1).default('file:.data/app.db')"},${auth ? '\n BETTER_AUTH_SECRET: z.string().min(32),' : ''}
147
+ },
148
+ runtimeEnv: process.env,
149
+ emptyStringAsUndefined: true,
150
+ skipValidation: !!process.env.KERF_BUILD,
151
+ })
152
+ `
153
+
154
+ /** `src/context.server.ts`: the database on `ctx`, and the session with auth. */
155
+ export const context = (auth) =>
156
+ auth
157
+ ? `import { session } from '@kerf-js/start/auth'
158
+ import auth from '#/auth.server'
159
+ import { db } from '#/db/index.server'
160
+
161
+ export default async ({ request }: { request: Request }) => ({ db, ...(await session(auth, request)) })
162
+
163
+ type Session = Awaited<ReturnType<typeof auth.session>>
164
+
165
+ declare module '@kerf-js/start' {
166
+ interface Context {
167
+ db: typeof db
168
+ user: Session['user']
169
+ session: Session['session']
170
+ }
171
+ }
172
+ `
173
+ : `import { db } from '#/db/index.server'
174
+
175
+ export default () => ({ db })
176
+
177
+ declare module '@kerf-js/start' {
178
+ interface Context {
179
+ db: typeof db
180
+ }
181
+ }
182
+ `
183
+
184
+ function todosServer(auth, db) {
185
+ const use = auth ? `\n auth: 'user',` : ''
186
+ const mine = auth
187
+ ? `and(eq(todos.id, input.id), eq(todos.userId, ctx.user.id))`
188
+ : `eq(todos.id, input.id)`
189
+ // MySQL has no \`returning\`.
190
+ const returning = db === 'mysql' ? '' : '.returning()'
191
+ return `import { mutation, query } from '@kerf-js/start'
192
+ import { schemasOf } from '@kerf-js/start/db'
193
+ import { ${auth ? 'and, ' : ''}asc, eq, not } from 'drizzle-orm'
194
+ import { z } from 'zod'
195
+ import * as schema from '#/db/schema'
196
+
197
+ const { todos } = schema
198
+ const schemas = schemasOf(schema, { todos: { title: (s: z.ZodString) => s.trim().min(1).max(200) } })
199
+ const byId = z.object({ id: z.string() })
200
+
201
+ export const listTodos = query({
202
+ tags: ['todos'],${use}
203
+ run: ({ ctx }) => ctx.db.select().from(todos)${auth ? '.where(eq(todos.userId, ctx.user.id))' : ''}.orderBy(asc(todos.createdAt)),
204
+ })
205
+
206
+ export const addTodo = mutation({
207
+ input: schemas.todos.insert.pick({ title: true }),${use}
208
+ invalidates: ['todos'],
209
+ optimistic: ({ input }, cache) =>
210
+ cache.update(listTodos, undefined, list => void list.push({ id: \`tmp:\${input.title}\`,${auth ? " userId: ''," : ''} title: input.title, done: false, createdAt: 0 })),
211
+ run: async ({ input, ctx }) => {
212
+ ${
213
+ db === 'mysql'
214
+ ? `const row = { id: crypto.randomUUID(),${auth ? ' userId: ctx.user.id,' : ''} title: input.title, createdAt: Date.now() }
215
+ await ctx.db.insert(todos).values(row)
216
+ return { ...row, done: false }`
217
+ : `const [row] = await ctx.db.insert(todos).values({ id: crypto.randomUUID(),${auth ? ' userId: ctx.user.id,' : ''} title: input.title, createdAt: Date.now() }).returning()
218
+ return row`
219
+ }
220
+ },
221
+ })
222
+
223
+ export const toggleTodo = mutation({
224
+ input: byId,${use}
225
+ invalidates: ['todos'],
226
+ optimistic: ({ input }, cache) =>
227
+ cache.update(listTodos, undefined, list => {
228
+ const t = list.find(x => x.id === input.id)
229
+ if (t) t.done = !t.done
230
+ }),
231
+ run: ({ input, ctx }) => ctx.db.update(todos).set({ done: not(todos.done) }).where(${mine})${returning},
232
+ })
233
+
234
+ export const deleteTodo = mutation({
235
+ input: byId,${use}
236
+ invalidates: ['todos'],
237
+ optimistic: ({ input }, cache) => cache.update(listTodos, undefined, list => list.filter(x => x.id !== input.id)),
238
+ run: ({ input, ctx }) => ctx.db.delete(todos).where(${mine})${returning},
239
+ })
240
+ `
241
+ }
242
+
243
+ const sessionServer = () => `import { mutation, query, redirect } from '@kerf-js/start'
244
+ import { forward } from '@kerf-js/start/auth'
245
+ import { z } from 'zod'
246
+ import auth from '#/auth.server'
247
+
248
+ const credentials = z.object({ email: z.email(), password: z.string().min(8) })
249
+
250
+ /** Who is signed in, or null. */
251
+ export const me = query({
252
+ tags: ['session'],
253
+ run: ({ ctx }) => (ctx.user ? { id: ctx.user.id, name: ctx.user.name, email: ctx.user.email } : null),
254
+ })
255
+
256
+ export const signUp = mutation({
257
+ auth: 'public',
258
+ input: credentials.extend({ name: z.string().trim().min(1) }),
259
+ run: async ({ input, ctx }) => {
260
+ await forward(ctx, auth.api.signUpEmail({ body: input, headers: ctx.request.headers, asResponse: true }))
261
+ redirect('/todos')
262
+ },
263
+ })
264
+
265
+ export const signIn = mutation({
266
+ auth: 'public',
267
+ input: credentials,
268
+ run: async ({ input, ctx }) => {
269
+ await forward(ctx, auth.api.signInEmail({ body: input, headers: ctx.request.headers, asResponse: true }))
270
+ redirect('/todos')
271
+ },
272
+ })
273
+
274
+ export const signOut = mutation({
275
+ auth: 'public',
276
+ run: async ({ ctx }) => {
277
+ await forward(ctx, auth.api.signOut({ headers: ctx.request.headers, asResponse: true }))
278
+ redirect('/login')
279
+ },
280
+ })
281
+ `
282
+
283
+ const guard = () => `import { redirect, type LoadArgs, type RouteProps } from '@kerf-js/start'
284
+
285
+ // The guard: a layout's \`load\` runs before its pages', so nothing under /todos runs for a visitor.
286
+ export const load = ({ ctx }: LoadArgs) => {
287
+ if (!ctx.user) redirect('/login')
288
+ }
289
+
290
+ export default function TodosLayout(props: RouteProps) {
291
+ return <>{props.children}</>
292
+ }
293
+ `
@@ -0,0 +1,175 @@
1
+ // `--template`: a real app in `templates/<name>/`, laid over the scaffold. `template.json` holds what it
2
+ // `requires` (db, auth), its `pages`, its `veneer()` options and any `dependencies` of its own; `files/` is copied as it is.
3
+ // A template's Drizzle schema is one dialect's, so it names that dialect, and its `drizzle/` ships with it
4
+ // (scripts/template-migrations.mjs): the app runs on a fresh database, and on one that already has these tables.
5
+
6
+ import { existsSync, readdirSync, readFileSync } from 'node:fs'
7
+ import { join, relative, sep } from 'node:path'
8
+ import { fileURLToPath } from 'node:url'
9
+
10
+ /** What `--template` takes: the apps a scaffold can start as. */
11
+ export const TEMPLATES = ['landing', 'todo', 'admin', 'catalog']
12
+
13
+ const templates = fileURLToPath(new URL('../templates/', import.meta.url))
14
+ const utf8 = new TextDecoder('utf-8', { fatal: true })
15
+
16
+ /** Text as a string, and an image or a font as the bytes it is. */
17
+ function contents(file) {
18
+ const bytes = readFileSync(file)
19
+ try {
20
+ return utf8.decode(bytes)
21
+ } catch {
22
+ return bytes
23
+ }
24
+ }
25
+
26
+ function tree(dir, base = dir) {
27
+ return Object.fromEntries(
28
+ readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
29
+ const path = join(dir, entry.name)
30
+ return entry.isDirectory()
31
+ ? Object.entries(tree(path, base))
32
+ : [[relative(base, path).split(sep).join('/'), contents(path)]]
33
+ }),
34
+ )
35
+ }
36
+
37
+ const needed = ({ db }) => [
38
+ 'src/theme.css',
39
+ 'src/routes/_layout.tsx',
40
+ 'src/routes/index.tsx',
41
+ ...(db === 'none'
42
+ ? []
43
+ : ['src/db/schema.ts', 'drizzle/meta/_journal.json', 'drizzle/.schema-hash']),
44
+ ]
45
+
46
+ export function loadTemplate(name) {
47
+ if (!TEMPLATES.includes(name))
48
+ throw new Error(`--template must be one of ${TEMPLATES.join(', ')} (got "${name}")`)
49
+ const manifest = join(templates, name, 'template.json')
50
+ if (!existsSync(manifest)) throw new Error(`the ${name} template isn't written yet`)
51
+ const {
52
+ requires = {},
53
+ pages = [],
54
+ veneer,
55
+ dependencies = {},
56
+ } = JSON.parse(readFileSync(manifest, 'utf8'))
57
+ const { db = 'none', auth = false } = requires
58
+ if (!['postgres', 'none'].includes(db))
59
+ throw new Error(
60
+ `the ${name} template's requires.db must be postgres or none (got ${JSON.stringify(db)})`,
61
+ )
62
+ const files = tree(join(templates, name, 'files'))
63
+ const missing = needed({ db }).filter((file) => !(file in files))
64
+ if (missing.length) throw new Error(`the ${name} template has no ${missing.join(', ')}`)
65
+ return { name, requires: { db, auth }, pages, veneer, dependencies, files }
66
+ }
67
+
68
+ /** The choices with what the template implies filled in. A choice it can't work with is refused, not ignored. */
69
+ export function withTemplate(options) {
70
+ if (!options.template) return options
71
+ const {
72
+ requires: { db, auth },
73
+ files,
74
+ } = loadTemplate(options.template)
75
+ const refuse = (flag, wants) => {
76
+ throw new Error(`the ${options.template} template needs ${flag} ${wants}`)
77
+ }
78
+ if (![undefined, 'veneer'].includes(options.ui)) refuse('--ui', 'veneer')
79
+ if (![undefined, 'drizzle'].includes(options.layer)) refuse('--layer', 'drizzle')
80
+ if (![undefined, db].includes(options.db)) refuse('--db', db)
81
+ if (options.auth !== undefined && Boolean(options.auth) !== auth)
82
+ refuse('sign-in', auth ? 'on' : 'off')
83
+ // Its fonts and media are plugin options in code, which a json or yaml config has no place for.
84
+ const config = 'kerf.config.ts' in files ? 'ts' : options.config
85
+ if (![undefined, config].includes(options.config)) refuse('--config', config)
86
+ return {
87
+ ...options,
88
+ ui: 'veneer',
89
+ layer: 'drizzle',
90
+ db,
91
+ auth: options.auth ?? auth,
92
+ ...(config && { config }),
93
+ }
94
+ }
95
+
96
+ /**
97
+ * drizzle-kit's Postgres migration, made safe to run over tables that are already there: `create` only what's missing, and
98
+ * a foreign key only where the column has none, so an existing schema's differently named constraint isn't doubled.
99
+ */
100
+ export function idempotent(sql) {
101
+ return sql
102
+ .replace(/^CREATE TABLE "/gm, 'CREATE TABLE IF NOT EXISTS "')
103
+ .replace(/^CREATE (UNIQUE )?INDEX "/gm, 'CREATE $1INDEX IF NOT EXISTS "')
104
+ .replace(
105
+ /^ALTER TABLE ("\w+") ADD CONSTRAINT "\w+" FOREIGN KEY \("(\w+)"\).*?;/gm,
106
+ (statement, table, column) =>
107
+ `DO $$ BEGIN\n IF NOT EXISTS (SELECT 1 FROM pg_constraint c JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = c.conkey[1] WHERE c.conrelid = '${table}'::regclass AND c.contype = 'f' AND a.attname = '${column}') THEN\n ${statement}\n END IF;\nEND $$;`,
108
+ )
109
+ }
110
+
111
+ const DATA = {
112
+ drizzle: 'Tables are in `src/db/schema.ts`; after changing it run `npx kerf db generate`.',
113
+ prisma: 'Tables are in `prisma/schema.prisma`; after changing it run `npx kerf db generate`.',
114
+ native: 'Tables are SQL in `migrations/`; `npx kerf db generate <name>` starts a new one.',
115
+ }
116
+ const LOOK = {
117
+ veneer:
118
+ "The look is `veneer({ seed, dials, radius, fonts, tokens })` in the kerf config; `kerf check` fails with D010 if a pair can't pass.",
119
+ headless: "The look is `src/app.css`, over veneer's `--veneer-*` tokens.",
120
+ tailwind: 'The look is Tailwind utilities; `src/app.css` is the entry.',
121
+ none: 'The look is `src/app.css`.',
122
+ }
123
+
124
+ /** The scaffold's AGENTS.md: enough to start. `kerf agents-md` writes the full reference over it. */
125
+ export function agentsFile({ ui, db, layer, shipped, auth }) {
126
+ return [
127
+ '# AGENTS.md',
128
+ '',
129
+ "This is a **kerf** app (fine-grained reactive TSX). It is not React: components run once, state is a box, and React hooks don't exist.",
130
+ '',
131
+ '## Run',
132
+ '',
133
+ '- `npx kerf dev`: the dev server.',
134
+ '- `npx kerf build`, then `npx kerf start`: production.',
135
+ '- `npx kerf check --json` after every change: each diagnostic has a code, a location, why, and a fix.',
136
+ '- `npx kerf docs <topic>`: rules, props, lists, async, testing, config, diagnostics.',
137
+ ...(db !== 'none' && !shipped
138
+ ? [
139
+ '- `npx kerf db generate` before the first run: the first migration. Migrations apply on the next request.',
140
+ ]
141
+ : []),
142
+ ...(shipped
143
+ ? [
144
+ '- Set `DATABASE_URL` in `.env` to an empty database. `drizzle/` applies on the first request; there is nothing to run.',
145
+ ]
146
+ : []),
147
+ '',
148
+ '## Where things go',
149
+ '',
150
+ "- `src/routes/`: pages, by file path. `_layout.tsx` wraps what's beside it.",
151
+ ...(shipped?.length
152
+ ? [`- This template's pages: ${shipped.map((p) => `\`${p}\``).join(', ')}.`]
153
+ : []),
154
+ ...(db === 'none'
155
+ ? []
156
+ : [
157
+ '- `src/server/`: `query` and `mutation` functions; call them from any component.',
158
+ `- ${DATA[layer]}`,
159
+ '- `.env`: secrets and `DATABASE_URL`, checked by `src/env.server.ts`.',
160
+ ]),
161
+ ...(auth === true
162
+ ? [
163
+ '- `src/auth.server.ts`: Better Auth. Login is an opaque session in the database, in an HTTP-only cookie, never a JWT. Pages may answer from its signed cookie cache for 5 minutes (`session.cookieCache`); mutations always read the database. JWTs are for API access only (`api` in `createAuth`, `npx kerf docs start`).',
164
+ ]
165
+ : []),
166
+ '- `npx kerf map` writes `.kerf/map.md`: what this app has and what to call for each part.',
167
+ '',
168
+ '## Theming',
169
+ '',
170
+ shipped
171
+ ? "`src/theme.css` is this app's CSS: override `--veneer-*` tokens and style `[data-scope]` parts there. The brand, dials and radius are `veneer({ seed, dials, radius })` in the kerf config."
172
+ : LOOK[ui],
173
+ '',
174
+ ].join('\n')
175
+ }