@kerf-js/start 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 (236) hide show
  1. package/LICENSE +16 -0
  2. package/README.md +1468 -2
  3. package/crate/Cargo.lock +1347 -0
  4. package/crate/Cargo.toml +72 -0
  5. package/crate/README.md +322 -0
  6. package/crate/rust-toolchain.toml +3 -0
  7. package/crate/src/build/emit.rs +103 -0
  8. package/crate/src/build.rs +367 -0
  9. package/crate/src/ctx.rs +186 -0
  10. package/crate/src/envelope.rs +163 -0
  11. package/crate/src/functions.rs +173 -0
  12. package/crate/src/lib.rs +118 -0
  13. package/crate/src/native.rs +212 -0
  14. package/crate/src/otel.rs +62 -0
  15. package/crate/src/server.rs +203 -0
  16. package/package.json +123 -3
  17. package/src/app.mjs +136 -0
  18. package/src/asset-receipt.d.mts +13 -0
  19. package/src/asset-receipt.mjs +61 -0
  20. package/src/auth/better-auth.ts +280 -0
  21. package/src/auth/drizzle.ts +17 -0
  22. package/src/auth/emails.ts +44 -0
  23. package/src/auth.ts +62 -0
  24. package/src/boot.ts +57 -0
  25. package/src/builtin.tsx +19 -0
  26. package/src/bus/postgres.ts +104 -0
  27. package/src/bus.ts +51 -0
  28. package/src/cache.ts +4 -0
  29. package/src/capture.ts +50 -0
  30. package/src/changes-sql.d.mts +20 -0
  31. package/src/changes-sql.mjs +115 -0
  32. package/src/changes.ts +352 -0
  33. package/src/channel/connections.ts +216 -0
  34. package/src/channel/socket.ts +396 -0
  35. package/src/channel-fake.ts +70 -0
  36. package/src/channel.ts +250 -0
  37. package/src/client.tsx +27 -0
  38. package/src/contract/describe.mjs +237 -0
  39. package/src/contract.mjs +299 -0
  40. package/src/cron.ts +74 -0
  41. package/src/data/after.ts +57 -0
  42. package/src/data/cache.ts +354 -0
  43. package/src/data/definitions.ts +94 -0
  44. package/src/data/draft.ts +104 -0
  45. package/src/data/foundation.ts +95 -0
  46. package/src/data/live-api.ts +22 -0
  47. package/src/data/mutation.ts +138 -0
  48. package/src/data/primitives.ts +135 -0
  49. package/src/data/query.ts +106 -0
  50. package/src/data/transport.ts +123 -0
  51. package/src/data/types.ts +333 -0
  52. package/src/data.ts +125 -0
  53. package/src/db/bun-sqlite.d.ts +13 -0
  54. package/src/db/changes-mysql.ts +126 -0
  55. package/src/db/changes-postgres.ts +238 -0
  56. package/src/db/changes-sqlite.ts +183 -0
  57. package/src/db/core.ts +95 -0
  58. package/src/db/index.ts +43 -0
  59. package/src/db/mysql.ts +84 -0
  60. package/src/db/postgres.ts +102 -0
  61. package/src/db/sqlite.ts +166 -0
  62. package/src/derive.d.mts +19 -0
  63. package/src/derive.mjs +237 -0
  64. package/src/dev-runtime.mjs +46 -0
  65. package/src/email.ts +146 -0
  66. package/src/exec/errors.ts +87 -0
  67. package/src/exec/impl.ts +21 -0
  68. package/src/exec/landing.ts +66 -0
  69. package/src/exec/limit.ts +25 -0
  70. package/src/exec/once.ts +24 -0
  71. package/src/exec/scope.ts +328 -0
  72. package/src/exec/touch.ts +80 -0
  73. package/src/exec/validation.ts +176 -0
  74. package/src/exec/warm.ts +50 -0
  75. package/src/exec.ts +400 -0
  76. package/src/extension.ts +48 -0
  77. package/src/first-paint.ts +74 -0
  78. package/src/form/value.ts +15 -0
  79. package/src/form.tsx +223 -0
  80. package/src/gate.css +6 -0
  81. package/src/hub/channels.ts +102 -0
  82. package/src/hub/connections.ts +147 -0
  83. package/src/hub/delivery.ts +62 -0
  84. package/src/hub/feed.ts +168 -0
  85. package/src/hub/presence.ts +64 -0
  86. package/src/hub/route.ts +159 -0
  87. package/src/hub/subscriptions.ts +213 -0
  88. package/src/hub/topic.ts +98 -0
  89. package/src/hub/tracked.ts +12 -0
  90. package/src/hub/types.ts +190 -0
  91. package/src/hub/view.ts +147 -0
  92. package/src/hub.ts +196 -0
  93. package/src/index.ts +184 -0
  94. package/src/inline.mjs +359 -0
  95. package/src/inspect/compare.mjs +162 -0
  96. package/src/inspect/routes.mjs +154 -0
  97. package/src/inspect/samples.mjs +59 -0
  98. package/src/inspect/url.mjs +2 -0
  99. package/src/inspect.mjs +239 -0
  100. package/src/jobs.ts +223 -0
  101. package/src/link/election.ts +178 -0
  102. package/src/link/lines.ts +27 -0
  103. package/src/link.ts +385 -0
  104. package/src/list-drizzle.ts +136 -0
  105. package/src/list.ts +315 -0
  106. package/src/listen.ts +54 -0
  107. package/src/live/api.ts +18 -0
  108. package/src/live/backoff.ts +6 -0
  109. package/src/live/frames.ts +42 -0
  110. package/src/live/read.ts +77 -0
  111. package/src/live/sub-types.ts +24 -0
  112. package/src/live/transport.ts +86 -0
  113. package/src/live/types.ts +52 -0
  114. package/src/live-fake.ts +57 -0
  115. package/src/live-target.mjs +231 -0
  116. package/src/live.ts +390 -0
  117. package/src/media.ts +50 -0
  118. package/src/migrations.mjs +27 -0
  119. package/src/mux-session.ts +6 -0
  120. package/src/mux.ts +232 -0
  121. package/src/og/DefaultCard.tsx +91 -0
  122. package/src/og/fonts.mjs +72 -0
  123. package/src/og/images.mjs +124 -0
  124. package/src/og/index.mjs +222 -0
  125. package/src/og/native.mjs +36 -0
  126. package/src/range.mjs +31 -0
  127. package/src/router.ts +199 -0
  128. package/src/routes.mjs +193 -0
  129. package/src/run/admission.ts +67 -0
  130. package/src/run/boot.tsx +115 -0
  131. package/src/run/cache-presentation.ts +67 -0
  132. package/src/run/cache.ts +254 -0
  133. package/src/run/helpers.ts +197 -0
  134. package/src/run/listeners.ts +166 -0
  135. package/src/run/navigation.ts +385 -0
  136. package/src/run/page-skeleton.tsx +35 -0
  137. package/src/run/prefetch.ts +129 -0
  138. package/src/run/retain-view.ts +18 -0
  139. package/src/run/shape-preparation.ts +97 -0
  140. package/src/run/shape-styles.ts +72 -0
  141. package/src/run/source-context/pin.ts +124 -0
  142. package/src/run/source-context.ts +311 -0
  143. package/src/run.tsx +74 -0
  144. package/src/rust/common.ts +163 -0
  145. package/src/rust/native.ts +282 -0
  146. package/src/rust.ts +207 -0
  147. package/src/server/background.ts +34 -0
  148. package/src/server/card.tsx +65 -0
  149. package/src/server/compression.ts +115 -0
  150. package/src/server/core.ts +70 -0
  151. package/src/server/cron.ts +49 -0
  152. package/src/server/dispatch.ts +73 -0
  153. package/src/server/form.ts +92 -0
  154. package/src/server/functions.ts +133 -0
  155. package/src/server/handler.ts +57 -0
  156. package/src/server/head.ts +96 -0
  157. package/src/server/health.ts +36 -0
  158. package/src/server/jobs.ts +112 -0
  159. package/src/server/lifecycle.ts +48 -0
  160. package/src/server/log.ts +42 -0
  161. package/src/server/media.ts +61 -0
  162. package/src/server/navigation-cache.ts +75 -0
  163. package/src/server/navigation.tsx +86 -0
  164. package/src/server/page-cold.ts +96 -0
  165. package/src/server/page-stream.tsx +181 -0
  166. package/src/server/page-types.ts +51 -0
  167. package/src/server/page-warm.ts +131 -0
  168. package/src/server/page.ts +69 -0
  169. package/src/server/payload.ts +89 -0
  170. package/src/server/prerender.ts +64 -0
  171. package/src/server/preview.tsx +67 -0
  172. package/src/server/render.ts +197 -0
  173. package/src/server/request.ts +192 -0
  174. package/src/server/resolver.ts +228 -0
  175. package/src/server/routes.ts +150 -0
  176. package/src/server/security.ts +50 -0
  177. package/src/server/services.ts +69 -0
  178. package/src/server/shutdown.ts +23 -0
  179. package/src/server/text.ts +29 -0
  180. package/src/server/types.ts +170 -0
  181. package/src/server.tsx +138 -0
  182. package/src/shape.d.mts +3 -0
  183. package/src/shape.mjs +97 -0
  184. package/src/share/display.ts +50 -0
  185. package/src/share/network.ts +119 -0
  186. package/src/share/receive.ts +70 -0
  187. package/src/share/state.ts +30 -0
  188. package/src/share/tab-queue.ts +28 -0
  189. package/src/share-server.ts +293 -0
  190. package/src/share.ts +397 -0
  191. package/src/sheets.mjs +87 -0
  192. package/src/sidecar/build.mjs +170 -0
  193. package/src/sidecar/cargo.mjs +164 -0
  194. package/src/sidecar/common.mjs +17 -0
  195. package/src/sidecar/dev-build.mjs +91 -0
  196. package/src/sidecar/dev-watch.mjs +88 -0
  197. package/src/sidecar/manifest.mjs +19 -0
  198. package/src/sidecar/process.mjs +58 -0
  199. package/src/sidecar/refresh.mjs +19 -0
  200. package/src/sidecar.mjs +162 -0
  201. package/src/socket/check.ts +50 -0
  202. package/src/socket/deliver.ts +16 -0
  203. package/src/socket/publish.ts +56 -0
  204. package/src/socket/rooms.ts +41 -0
  205. package/src/socket/route.ts +79 -0
  206. package/src/socket/shared.ts +26 -0
  207. package/src/socket/types.ts +48 -0
  208. package/src/socket.ts +400 -0
  209. package/src/stream.ts +22 -0
  210. package/src/verify/app.ts +39 -0
  211. package/src/verify/cleanup.ts +27 -0
  212. package/src/verify/database.ts +11 -0
  213. package/src/verify/live.ts +63 -0
  214. package/src/verify/notify.ts +35 -0
  215. package/src/verify/skip.ts +19 -0
  216. package/src/verify/support.ts +149 -0
  217. package/src/verify/timing.ts +15 -0
  218. package/src/verify/trigger.ts +14 -0
  219. package/src/verify.ts +152 -0
  220. package/src/view.tsx +132 -0
  221. package/src/vite/asset-bytes.mjs +95 -0
  222. package/src/vite/assets.mjs +117 -0
  223. package/src/vite/config-hooks.mjs +166 -0
  224. package/src/vite/dev-hooks.mjs +103 -0
  225. package/src/vite/dev.mjs +102 -0
  226. package/src/vite/entries.mjs +149 -0
  227. package/src/vite/module-hooks.mjs +290 -0
  228. package/src/vite/route-modules.mjs +289 -0
  229. package/src/vite/server-functions.mjs +222 -0
  230. package/src/vite/shape-entry-css.mjs +187 -0
  231. package/src/vite/shape-override.mjs +226 -0
  232. package/src/vite/shared.mjs +55 -0
  233. package/src/vite/sheets.mjs +92 -0
  234. package/src/vite/state.mjs +89 -0
  235. package/src/vite/syntax.mjs +139 -0
  236. package/src/vite.mjs +202 -0
@@ -0,0 +1,162 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import { descriptionProblem } from '../derive.mjs'
4
+
5
+ const quote = (s) => JSON.stringify(s)
6
+ const short = (s, n = 70) => (s.length > n ? s.slice(0, n - 1) + '…' : s)
7
+
8
+ function compareLengths(own, words, at, push) {
9
+ const longTitle = own.find((p) => p.title.length > 60)
10
+ if (longTitle)
11
+ push(
12
+ 'H004',
13
+ 'warning',
14
+ at,
15
+ `The title is ${longTitle.title.length} characters (over 60): \`${longTitle.title}\`${own.length > 1 ? ` on ${longTitle.url}` : ''}.`,
16
+ )
17
+ const longText = own.find((p) => p.description && p.description.length > 160)
18
+ if (longText)
19
+ push(
20
+ 'H004',
21
+ 'warning',
22
+ at,
23
+ `The description is ${longText.description.length} characters (over 160)${own.length > 1 ? ` on ${longText.url}` : ''}.`,
24
+ )
25
+ const bad = own.filter(
26
+ (p) => p.description && words(p.source.description) && descriptionProblem(p.description),
27
+ )
28
+ if (bad[0])
29
+ push(
30
+ 'H015',
31
+ 'warning',
32
+ at,
33
+ `The description ${own.length > 1 ? `of ${bad[0].url}${bad.length > 1 ? ` (and ${bad.length - 1} more)` : ''} ` : ''}isn't a sentence: ${descriptionProblem(bad[0].description)}: ${quote(short(bad[0].description))}.`,
34
+ {
35
+ help: 'Write one plain sentence on what the page gives the reader. Never slice raw markdown or code into `description`.',
36
+ },
37
+ )
38
+ }
39
+
40
+ function compareRoute(route, entry, c) {
41
+ const { root, byRoute, site, push, metaExport, metaSnippet } = c
42
+ if (route.kind !== 'page') return
43
+ const own = byRoute.get(route) ?? []
44
+ const at = { file: route.file, path: entry.path }
45
+ const first = own[0]
46
+ const { present, reads } = metaExport(readFileSync(join(root, route.file), 'utf8'), route.file)
47
+ const words = (s) => s === 'route' || s === 'layout'
48
+ if (first && !(first.source.title === 'route' && first.source.description === 'route')) {
49
+ const missing = [
50
+ first.source.title !== 'route' && 'title',
51
+ first.source.description !== 'route' && 'description',
52
+ ]
53
+ .filter(Boolean)
54
+ .join(' and ')
55
+ const whence = (what, s, text) =>
56
+ `${what} ${s === 'auto' ? `comes from the page (${quote(short(text))})` : s === 'layout' ? 'comes from a layout' : s === 'config' ? 'is the site default' : 'is empty'}`
57
+ push(
58
+ 'H011',
59
+ 'warning',
60
+ at,
61
+ `${present ? `\`meta\` sets no ${missing}` : 'This page sets no `meta`'}: the ${[first.source.title !== 'route' && whence('title', first.source.title, first.title), first.source.description !== 'route' && whence('description', first.source.description, first.description ?? '')].filter(Boolean).join(', and the ')}. That works, but words written for this page are better.`,
62
+ {
63
+ help: metaSnippet(
64
+ route,
65
+ first.source.title === 'auto' ? stripTemplate(first.title, site.title) : '',
66
+ first.description,
67
+ ),
68
+ },
69
+ )
70
+ } else if (!first && !present)
71
+ push(
72
+ 'H011',
73
+ 'warning',
74
+ at,
75
+ 'This page sets no `meta`, so its title and description come from what it renders. Words written for the page are better.',
76
+ { help: metaSnippet(route) },
77
+ )
78
+
79
+ if (route.params.length && present && !reads)
80
+ push(
81
+ 'H014',
82
+ 'warning',
83
+ at,
84
+ 'This route has params, but its `meta` reads neither `data` nor `params`: every page of it has the same tags.',
85
+ { help: metaSnippet(route) },
86
+ )
87
+ else if (route.params.length && own.length > 1) {
88
+ const same = (key) => new Set(own.map((p) => p[key])).size === 1 && own[0][key]
89
+ for (const key of ['title', 'description'])
90
+ if (same(key))
91
+ push(
92
+ 'H014',
93
+ 'warning',
94
+ at,
95
+ `All ${own.length} pages of this route looked at have the same ${key} (${quote(short(own[0][key]))}), so a share or a search result can't tell them apart.`,
96
+ { help: metaSnippet(route) },
97
+ )
98
+ }
99
+
100
+ compareLengths(own, words, at, push)
101
+ }
102
+
103
+ /** The checks that take every page at once: is each one's text its own, and is it text at all? */
104
+ export function compare(c) {
105
+ const { root, entries, pages, site, known, metaExport, metaSnippet } = c
106
+ const out = []
107
+ const push = (code, severity, route, why, extra) =>
108
+ out.push({ code, severity, file: route.file, route: route.path, why, ...extra })
109
+ const byRoute = new Map()
110
+ for (const p of pages) byRoute.set(p.route, [...(byRoute.get(p.route) ?? []), p])
111
+
112
+ if (!known)
113
+ out.push({
114
+ code: 'H001',
115
+ severity: 'warning',
116
+ file: 'kerf.config.ts',
117
+ route: '*',
118
+ why: "`site.url` is not set: a build has no absolute URLs (no canonical, no og:url, a relative og:image), and a server takes them from the request's Host header. Crawlers don't resolve relative URLs.",
119
+ help: 'Set `site.url` in kerf.config.ts, or `KERF_SITE_URL` in the deploy environment.',
120
+ })
121
+
122
+ for (const { route, entry } of entries)
123
+ compareRoute(route, entry, { root, byRoute, site, push, metaExport, metaSnippet })
124
+
125
+ const clash = (key, code) => {
126
+ const groups = new Map()
127
+ for (const p of pages) if (p[key]) groups.set(p[key], [...(groups.get(p[key]) ?? []), p])
128
+ for (const [text, list] of groups) {
129
+ const routes = [...new Set(list.map((p) => p.route))]
130
+ if (routes.length < 2) continue // one param route's pages are H014's
131
+ const what =
132
+ key === 'title'
133
+ ? 'title'
134
+ : text === site.description
135
+ ? 'description (the site default)'
136
+ : 'description'
137
+ const a = routes[0]
138
+ push(
139
+ code,
140
+ 'warning',
141
+ { file: a.file, path: list[0].url },
142
+ `${routes.length} routes share this ${what}: ${list
143
+ .slice(0, 4)
144
+ .map((p) => p.url)
145
+ .join(
146
+ ', ',
147
+ )}${list.length > 4 ? `, and ${list.length - 4} more` : ''} (${quote(short(text))}).`,
148
+ { help: `Give each page its own ${key} in \`meta\`, from what is on it.` },
149
+ )
150
+ }
151
+ }
152
+ clash('title', 'H012')
153
+ clash('description', 'H013')
154
+ return out
155
+ }
156
+
157
+ const stripTemplate = (title, template) => {
158
+ const [a = '', b = ''] = template?.split('%s') ?? []
159
+ return title.startsWith(a) && title.endsWith(b)
160
+ ? title.slice(a.length, title.length - b.length)
161
+ : title
162
+ }
@@ -0,0 +1,154 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import { filePath } from '../routes.mjs'
4
+
5
+ /** `<data>`, `<data.name>`, `<data.user.name>`: reads become their own names, for meta run without a loader. */
6
+ function placeholder(path) {
7
+ const text = `<${path}>`
8
+ return new Proxy(function () {}, {
9
+ get(_, k) {
10
+ if (k === Symbol.toPrimitive || k === 'toString' || k === 'valueOf' || k === 'toJSON')
11
+ return () => text
12
+ if (typeof k === 'symbol') return undefined
13
+ return placeholder(`${path}.${k}`)
14
+ },
15
+ apply: () => text,
16
+ })
17
+ }
18
+
19
+ async function routeHead(route, layouts, mod, context, report) {
20
+ const { site, mergeMeta, cardPath, take, modules } = context
21
+ let head, status, url, data, redirect, source
22
+ if (route.kind !== 'page') {
23
+ const metas = [
24
+ ...layouts.map((l) => modules[l.file]?.meta),
25
+ mod.meta ?? { title: route.kind === '404' ? 'Not found' : 'Error' },
26
+ ]
27
+ head = mergeMeta(
28
+ site,
29
+ ...(await Promise.all(
30
+ metas.map((m) =>
31
+ typeof m === 'function' ? m({ params: {}, data: placeholder('data') }) : m,
32
+ ),
33
+ )),
34
+ )
35
+ head.og.image = undefined
36
+ status = route.kind === '404' ? 404 : 500
37
+ url = null
38
+ data = 'none'
39
+ } else if (!route.params.length) {
40
+ const r = await take(route, route.pattern, report)
41
+ ;({ head, status, source } = r)
42
+ redirect = r.redirect?.href
43
+ url = route.pattern
44
+ data = 'loaded'
45
+ if (status >= 500)
46
+ report(
47
+ 'H016',
48
+ 'info',
49
+ `This page answered ${status} here, so its metadata wasn't checked. It may need a database or an environment \`kerf check\` doesn't have.`,
50
+ )
51
+ } else {
52
+ const params = Object.fromEntries(route.params.map((p) => [p, `<${p}>`]))
53
+ url = route.pattern.replace(/\$([\w$]*)/g, (_, n) => `<${n || route.splat}>`)
54
+ const metas = []
55
+ for (const m of [...layouts.map((l) => modules[l.file]?.meta), mod.meta]) {
56
+ // `meta` can do what placeholders can't (`data.tags.join()`), and that's no fault: the samples run it for real.
57
+ try {
58
+ metas.push(typeof m === 'function' ? await m({ params, data: placeholder('data') }) : m)
59
+ } catch {}
60
+ }
61
+ head = mergeMeta(site, ...metas)
62
+ if (head.og.image === 'auto')
63
+ head.og.image = {
64
+ url: `/_kerf/og/${cardPath(url)}.png?v=<hash>`,
65
+ width: 1200,
66
+ height: 630,
67
+ }
68
+ status = 200
69
+ data = 'placeholder'
70
+ }
71
+ return { head, status, url, data, redirect, source }
72
+ }
73
+
74
+ function applyHead(entry, route, mod, resolved, context) {
75
+ const { head, status, url, data, redirect, source } = resolved
76
+ const { manifest, headTags, out } = context
77
+ const image = head.og.image
78
+ entry.url = url
79
+ entry.status = status
80
+ if (redirect !== undefined) {
81
+ // `load` redirects (research 27 §3): the response has no body, so no tags and no card.
82
+ Object.assign(entry, { redirect, data, card: null, image: 'none', meta: null, tags: [] })
83
+ out.push(entry)
84
+ return false
85
+ }
86
+ entry.data = data
87
+ entry.card = route.kind !== 'page' ? null : (route.card ?? manifest.defaultCard ?? 'built-in')
88
+ entry.image =
89
+ typeof image !== 'object' || !image
90
+ ? 'none'
91
+ : !image.url.startsWith('/_kerf/og/')
92
+ ? 'url'
93
+ : !route.params.length
94
+ ? 'build'
95
+ : mod.prerender
96
+ ? 'prerender+on-demand'
97
+ : 'on-demand'
98
+ entry.meta = JSON.parse(JSON.stringify(head))
99
+ entry.tags = url
100
+ ? headTags(head, url).map(([tag, attrs, text]) =>
101
+ text === undefined ? [tag, attrs] : [tag, attrs, text],
102
+ )
103
+ : headTags(head, '/')
104
+ if (source) entry.source = source
105
+ return true
106
+ }
107
+
108
+ async function inspectRoute(route, context) {
109
+ const { root, manifest, modules, h006, diagnostics, out, entries, preset } = context
110
+ const mod = modules[route.file] ?? {}
111
+ const layouts = route.layouts.map((id) => manifest.layouts.find((l) => l.id === id))
112
+ const entry = {
113
+ path: route.kind === 'page' ? filePath(manifest, route) : route.kind,
114
+ kind: route.kind,
115
+ file: route.file,
116
+ layouts: layouts.map((l) => l.file),
117
+ params: route.params,
118
+ }
119
+ const report = (code, severity, why, help) =>
120
+ diagnostics.push({
121
+ code,
122
+ severity,
123
+ file: route.file,
124
+ route: entry.path,
125
+ why,
126
+ ...(help && { help }),
127
+ })
128
+ for (const f of [route.file, ...entry.layouts])
129
+ h006(readFileSync(join(root, f), 'utf8'), f, (why, file) =>
130
+ diagnostics.push({ code: 'H006', severity: 'error', file, route: entry.path, why }),
131
+ )
132
+ const resolved = await routeHead(route, layouts, mod, context, report)
133
+ const { head, status } = resolved
134
+ if (!applyHead(entry, route, mod, resolved, context)) return
135
+ // Route-level checks on the merged result (the config-level ones run in `kerf check`).
136
+ if (preset === 'static' && entry.image === 'on-demand')
137
+ report(
138
+ 'H002',
139
+ 'error',
140
+ 'A param route with a generated card on a static-only preset: export `prerender` with the params to build, or set `og.image`.',
141
+ )
142
+ if (route.kind === 'page' && status === 200 && !route.params.length && !head.description)
143
+ report('H003', 'warning', 'No description after merging the config, layouts and route.')
144
+ entries.push({ route, entry, report })
145
+ out.push(entry)
146
+ }
147
+
148
+ /** Inspect each route in the same order as before. */
149
+ export async function inspectRoutes(context) {
150
+ const { manifest, entries } = context
151
+ for (const route of [...manifest.routes].sort((a, b) => a.params.length - b.params.length))
152
+ await inspectRoute(route, context)
153
+ return entries
154
+ }
@@ -0,0 +1,59 @@
1
+ import { fillPath } from './url.mjs'
2
+
3
+ /** A param route's real pages to run, at most: enough to compare them, and few enough for `kerf check`. */
4
+ const SAMPLES = 50
5
+
6
+ /** Run the real samples of param routes. */
7
+ export async function inspectSamples(entries, modules, seen, take) {
8
+ // The param routes' real pages: `prerender` first (what the build will make), then what rendered pages link to.
9
+ for (const { route, entry, report } of entries) {
10
+ if (route.kind !== 'page' || !route.params.length) continue
11
+ const mod = modules[route.file] ?? {}
12
+ let given = []
13
+ try {
14
+ given = (typeof mod.prerender === 'function' ? await mod.prerender() : mod.prerender) ?? []
15
+ } catch {}
16
+ if (!Array.isArray(given)) given = []
17
+ const urls = new Set(given.slice(0, SAMPLES).map((p) => fillPath(route, p)))
18
+ for (const [href, id] of seen) if (id === route.id && urls.size < SAMPLES) urls.add(href)
19
+ entry.samples = []
20
+ for (const u of urls) {
21
+ const r = await take(route, u, report)
22
+ if (r.status === 200 && !r.redirect)
23
+ entry.samples.push({
24
+ url: u,
25
+ title: r.head.title,
26
+ description: r.head.description,
27
+ image: typeof r.head.og.image === 'object' ? r.head.og.image?.url : undefined,
28
+ source: r.source,
29
+ })
30
+ }
31
+ entry.source = entry.samples[0]?.source
32
+ if (!entry.samples.length)
33
+ report(
34
+ 'H016',
35
+ 'info',
36
+ 'No real page of this route to look at, so only its source was checked. Export `prerender`, or link to one from a page.',
37
+ )
38
+ }
39
+ }
40
+
41
+ /** Draw one card for each route that has one. */
42
+ export async function inspectCards(entries, manifest, found, handler) {
43
+ // H005 and H008: a card only says what's wrong with it when it's drawn, so one page of each route with its own draws.
44
+ for (const { route, entry, report } of entries) {
45
+ const image = entry.samples?.[0]?.image ?? entry.meta?.og?.image?.url
46
+ if (
47
+ !(route.card || manifest.defaultCard) ||
48
+ !image?.startsWith('/_kerf/og/') ||
49
+ image.includes('<')
50
+ )
51
+ continue
52
+ found.length = 0
53
+ try {
54
+ await handler(new Request(`http://kerf.local${image}`))
55
+ } catch {}
56
+ for (const d of found)
57
+ if (d.code === 'H005' || d.code === 'H008') report(d.code, d.severity, d.message)
58
+ }
59
+ }
@@ -0,0 +1,2 @@
1
+ export const fillPath = (route, params) =>
2
+ route.pattern.replace(/\$([\w$]*)/g, (_, n) => String(params[n || route.splat]))
@@ -0,0 +1,239 @@
1
+ // `kerf routes --meta` (research 20 §5, §10; research 25 §7) and the route half of `kerf check`: every route's merged
2
+ // metadata and where its words came from, so an agent reviews every page's tags without a browser. Static routes run
3
+ // their loaders and render (one GET each, as a crawler's request would). Param routes run `meta` on placeholders
4
+ // (`params.id` is `<id>`, `data.name` is `<data.name>`), then on real samples: their `prerender` params and the links
5
+ // the rendered pages hold. Diagnostics H001–H007 and H011–H016 for each.
6
+
7
+ import { readFileSync } from 'node:fs'
8
+ import { join, resolve } from 'node:path'
9
+ import { createServer, parseSync } from 'vite'
10
+ import kerf from '@kerf-js/core/vite'
11
+ import kerfStart, { startDir } from './vite.mjs'
12
+ import { deployUrl } from './derive.mjs'
13
+ import { compare } from './inspect/compare.mjs'
14
+ import { inspectRoutes } from './inspect/routes.mjs'
15
+ import { inspectSamples, inspectCards } from './inspect/samples.mjs'
16
+ import { filePath, scanRoutes } from './routes.mjs'
17
+
18
+ const quote = (s) => JSON.stringify(s)
19
+
20
+ /** `/users/$id` → a matcher for the concrete paths of that route. */
21
+ const matcher = (pattern) =>
22
+ new RegExp(
23
+ '^' +
24
+ pattern
25
+ .replace(/[.+?^(){}|[\]\\]/g, '\\$&')
26
+ .replace(/\$[\w$]+/g, '[^/]+')
27
+ .replace(/\$$/, '.+') +
28
+ '/?$',
29
+ )
30
+
31
+ /** The same-site paths a page links to. */
32
+ const links = (html) => [...html.matchAll(/\shref="(\/[^"#?]*)/g)].map((m) => m[1])
33
+
34
+ /** @param {string} code @param {string} file `{ present, reads }`: does the module export `meta`, and does it read `data` or `params`? */
35
+ export function metaExport(code, file) {
36
+ let ast
37
+ try {
38
+ ast = parseSync(file, code, { lang: file.endsWith('x') ? 'tsx' : 'ts', sourceType: 'module' })
39
+ } catch {
40
+ return { present: true, reads: true }
41
+ }
42
+ for (const node of ast.program.body) {
43
+ if (node.type !== 'ExportNamedDeclaration') continue
44
+ if (node.specifiers?.some((s) => (s.exported?.name ?? s.exported?.value) === 'meta'))
45
+ return { present: true, reads: true } // from elsewhere: can't tell
46
+ const d = node.declaration
47
+ if (!d) continue
48
+ const decl =
49
+ d.type === 'VariableDeclaration'
50
+ ? d.declarations.find((x) => x.id?.name === 'meta')
51
+ : d.id?.name === 'meta'
52
+ ? d
53
+ : undefined
54
+ if (decl)
55
+ return {
56
+ present: true,
57
+ reads: /\b(?:data|params|args|props)\b/.test(code.slice(decl.start, decl.end)),
58
+ }
59
+ }
60
+ return { present: false, reads: false }
61
+ }
62
+
63
+ /** What to paste: the page's own words, as a starting point an agent improves. */
64
+ function metaSnippet(route, title, description) {
65
+ if (route.params.length)
66
+ return `export const meta: Meta<typeof load> = ({ data }) => ({ title: data.title, description: data.summary })`
67
+ return `export const meta: Meta = { title: ${quote(title || 'What this page is')}, description: ${quote(description || 'One sentence on what this page gives the reader.')} }`
68
+ }
69
+
70
+ /**
71
+ * Only what reading the source can tell, for an app whose routes can't run here (`kerf check` falls back to it):
72
+ * pages with no `meta`, and param routes whose `meta` reads neither `data` nor `params`.
73
+ */
74
+ export function staticRouteChecks(root) {
75
+ const manifest = scanRoutes(root)
76
+ const out = []
77
+ for (const route of manifest.routes) {
78
+ if (route.kind !== 'page') continue
79
+ const { present, reads } = metaExport(readFileSync(join(root, route.file), 'utf8'), route.file)
80
+ const path = filePath(manifest, route)
81
+ if (!present)
82
+ out.push({
83
+ code: 'H011',
84
+ severity: 'warning',
85
+ file: route.file,
86
+ route: path,
87
+ why: 'This page sets no `meta`, so its title and description come from what it renders. Words written for the page are better.',
88
+ help: metaSnippet(route),
89
+ })
90
+ else if (route.params.length && !reads)
91
+ out.push({
92
+ code: 'H014',
93
+ severity: 'warning',
94
+ file: route.file,
95
+ route: path,
96
+ why: 'This route has params, but its `meta` reads neither `data` nor `params`: every page of it has the same tags.',
97
+ help: metaSnippet(route),
98
+ })
99
+ }
100
+ return out
101
+ }
102
+
103
+ function makeTaker(found, run, seen, manifest, pages) {
104
+ /** One run of a real page: its diagnostics, and its place in the comparison. */
105
+ return async (route, url, report) => {
106
+ found.length = 0
107
+ const r = await run(url)
108
+ for (const d of found) report(d.code, d.severity, d.message.replace(/^H\d{3} /, ''))
109
+ if (r.html)
110
+ for (const href of links(r.html))
111
+ if (!seen.has(href))
112
+ seen.set(
113
+ href,
114
+ manifest.routes.find((x) => x.kind === 'page' && matcher(x.pattern).test(href))?.id,
115
+ )
116
+ if (r.status === 200 && !r.redirect)
117
+ pages.push({
118
+ route,
119
+ url,
120
+ title: r.head.title,
121
+ description: r.head.description,
122
+ source: r.source,
123
+ })
124
+ return r
125
+ }
126
+ }
127
+
128
+ /**
129
+ * @param {{ root: string, site?: object, preset?: string }} options `preset: 'static'` means no server at runtime (H002).
130
+ */
131
+ export async function routesMeta({ root, site = {}, preset }) {
132
+ root = resolve(root)
133
+ const server = await createServer({
134
+ root,
135
+ configFile: false,
136
+ logLevel: 'silent',
137
+ appType: 'custom',
138
+ server: { middlewareMode: true, hmr: false, ws: false },
139
+ plugins: [kerf({ hydratable: true, csp: site?.csp }), kerfStart({ root, site })],
140
+ })
141
+ try {
142
+ const { manifest, modules } = await server.ssrLoadModule('virtual:kerf/routes')
143
+ const { createHandler, cardPath } = await server.ssrLoadModule(join(startDir, 'server.tsx'))
144
+ const { mergeMeta, headTags } = await server.ssrLoadModule('@kerf-js/core/ssr')
145
+ await server.ssrLoadModule('virtual:kerf/fns').catch(() => {})
146
+ // An app's server code often validates its environment as it loads, and this may not be that environment. Its pages
147
+ // can still be looked at: one that needs it answers 500, which is H016.
148
+ const context = await server.ssrLoadModule('virtual:kerf/context').then(
149
+ (m) => m.default,
150
+ () => undefined,
151
+ )
152
+ const found = []
153
+ const known = deployUrl(site, process.env)
154
+ const handler = createHandler({
155
+ manifest,
156
+ modules,
157
+ site: known ? { ...site, url: known } : site,
158
+ context,
159
+ build: 'inspect',
160
+ requestOrigin: false,
161
+ onDiagnostic: (d) => found.push(d),
162
+ })
163
+ const run = (path) => handler.inspect(path, new Request(`http://kerf.local${path}`))
164
+ const out = []
165
+ const diagnostics = []
166
+ const pages = [] // { route, url, title, description, source }: what the rest compares
167
+ const seen = new Map() // path → the route's id, from the links on rendered pages
168
+
169
+ const take = makeTaker(found, run, seen, manifest, pages)
170
+
171
+ const entries = []
172
+ await inspectRoutes({
173
+ root,
174
+ manifest,
175
+ modules,
176
+ site,
177
+ mergeMeta,
178
+ cardPath,
179
+ take,
180
+ headTags,
181
+ h006,
182
+ diagnostics,
183
+ out,
184
+ entries,
185
+ preset,
186
+ })
187
+
188
+ await inspectSamples(entries, modules, seen, take)
189
+ await inspectCards(entries, manifest, found, handler)
190
+
191
+ diagnostics.push(...compare({ root, entries, pages, site, known, metaExport, metaSnippet }))
192
+ out.sort(
193
+ (a, b) =>
194
+ manifest.routes.findIndex((r) => r.file === a.file) -
195
+ manifest.routes.findIndex((r) => r.file === b.file),
196
+ )
197
+ return {
198
+ version: 1,
199
+ ok: !diagnostics.some((d) => d.severity === 'error'),
200
+ site,
201
+ routes: out,
202
+ diagnostics,
203
+ }
204
+ } finally {
205
+ await server.close()
206
+ }
207
+ }
208
+
209
+ /**
210
+ * H006, statically: `meta` is plain data from `params` and `data`, so its source reads no `.value` and creates or calls
211
+ * nothing reactive. The AST gives the export's exact source range.
212
+ */
213
+ export function h006(code, file, report) {
214
+ let ast
215
+ try {
216
+ ast = parseSync(file, code, { lang: file.endsWith('x') ? 'tsx' : 'ts', sourceType: 'module' })
217
+ } catch {
218
+ return
219
+ }
220
+ for (const node of ast.program.body) {
221
+ if (node.type !== 'ExportNamedDeclaration' || !node.declaration) continue
222
+ const d = node.declaration
223
+ const decl =
224
+ d.type === 'VariableDeclaration'
225
+ ? d.declarations.find((x) => x.id?.name === 'meta')
226
+ : d.id?.name === 'meta'
227
+ ? d
228
+ : undefined
229
+ if (!decl) continue
230
+ const src = code.slice(decl.start, decl.end)
231
+ const hit =
232
+ /\.value\b/.exec(src) ?? /\b(state|derived|resource|watch|use[A-Z]\w*)\s*\(/.exec(src)
233
+ if (hit)
234
+ report(
235
+ `\`meta\` ${hit[0].startsWith('.') ? 'reads a box (`.value`)' : `calls \`${hit[1]}()\``}: metadata is plain data, computed once per request from \`params\` and \`data\`.`,
236
+ file,
237
+ )
238
+ }
239
+ }