@michaelthielemann/kestrel 1.4.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -36,7 +36,7 @@ static host. It is deliberately **not**:
36
36
  ## Features
37
37
 
38
38
  - **Runnable in one command** — `pnpm create kestrel` scaffolds a project that boots with a working
39
- `/admin`, prompting for the admin password and writing its hash; `kestrel init` does the same to an
39
+ `/admin`, asking you to choose the admin password and writing its hash; `kestrel init` does the same to an
40
40
  existing project without clobbering it, and `kestrel doctor` names whatever is still missing.
41
41
  - **Collection-driven** — declare collections + fields in TypeScript; Kestrel derives the SQLite tables, a
42
42
  typed CRUD REST API, and the full admin UI. The schema **migrates itself** (additive in dev; explicit
@@ -66,7 +66,7 @@ pnpm create kestrel my-site
66
66
  cd my-site && pnpm install && pnpm dev
67
67
  ```
68
68
 
69
- It asks for an admin password and writes a project that runs as-is: `nuxt.config.ts` extending the
69
+ It asks you to choose an admin password and writes a project that runs as-is: `nuxt.config.ts` extending the
70
70
  meta-layer, an `app.vue` that renders, a `.env` holding a fresh session secret and the scrypt hash of
71
71
  your password, and one example block. Sign in at <http://localhost:3000/admin>.
72
72
 
@@ -1,5 +1,6 @@
1
1
  <script setup lang="ts">
2
2
  import type { LayoutKey } from 'nuxt/app'
3
+ import type { SiteHead } from '../utils/site-head'
3
4
 
4
5
  // The record decides its own layout, so route-meta resolution is opted out of and this page renders the
5
6
  // `<NuxtLayout>` itself. Side effect worth knowing: the layout becomes a CHILD of the page, so it can read
@@ -41,6 +42,7 @@ const { data: resolved } = await useAsyncData(`page:${locale}:${path}`, () =>
41
42
  collection: string | null
42
43
  page: (RenderedPage & Record<string, unknown>) | null
43
44
  alternates?: Array<{ locale: string; path: string }>
45
+ site?: SiteHead | null
44
46
  }),
45
47
  )
46
48
  const page = computed(() => resolved.value?.page ?? null)
@@ -86,6 +88,11 @@ if (!page.value && path !== '/') throw createError({ statusCode: 404, statusMess
86
88
  // og:image) require a configured siteUrl and degrade away without one.
87
89
  const publicRc = useRuntimeConfig().public as { siteUrl?: string; siteName?: string }
88
90
  const seo = page.value?.seo ?? {}
91
+ const siteHead = resolved.value?.site ?? null
92
+ const fallbacks = siteHeadFallbacks(seo, siteHead)
93
+ // og:title stays the bare page title (og:site_name already carries the site); only <title> is composed.
94
+ const pageTitle = seo.title || page.value?.title
95
+ const documentTitle = composeTitle(pageTitle, siteHead)
89
96
  const head = buildPageHead({
90
97
  siteUrl: typeof publicRc.siteUrl === 'string' ? publicRc.siteUrl : '',
91
98
  siteName: typeof publicRc.siteName === 'string' ? publicRc.siteName : '',
@@ -93,9 +100,9 @@ const head = buildPageHead({
93
100
  locale,
94
101
  primary,
95
102
  prefixPrimary,
96
- title: seo.title || page.value?.title,
97
- description: seo.description || undefined,
98
- image: seo.$media?.image ?? null,
103
+ title: pageTitle,
104
+ description: fallbacks.description,
105
+ image: fallbacks.image,
99
106
  alternates: resolved.value?.alternates ?? [],
100
107
  })
101
108
 
@@ -111,8 +118,8 @@ useHead({
111
118
  ],
112
119
  })
113
120
  useSeoMeta({
114
- title: seo.title || page.value?.title,
115
- description: seo.description || undefined,
121
+ title: documentTitle,
122
+ description: fallbacks.description,
116
123
  robots: seo.noindex ? 'noindex, nofollow' : undefined,
117
124
  ogTitle: head.meta.ogTitle,
118
125
  ogDescription: head.meta.ogDescription,
@@ -0,0 +1,43 @@
1
+ export interface SiteHead {
2
+ baseTitle?: string | null
3
+ titleSeparator?: string | null
4
+ titlePosition?: 'before' | 'after' | null
5
+ description?: string | null
6
+ $media?: { image?: { src: string, width: number | null, height: number | null } | null } | null
7
+ }
8
+
9
+ const DEFAULT_SEPARATOR = '|'
10
+
11
+ const trimmed = (v: unknown): string | undefined => {
12
+ const s = typeof v === 'string' ? v.trim() : ''
13
+ return s || undefined
14
+ }
15
+
16
+ /**
17
+ * The `<title>` for a page. Only the document title is composed — `og:title` keeps the bare page title,
18
+ * because `og:site_name` already carries the site.
19
+ */
20
+ export function composeTitle(pageTitle: string | undefined | null, site: SiteHead | null | undefined): string | undefined {
21
+ const page = trimmed(pageTitle)
22
+ const base = trimmed(site?.baseTitle)
23
+ if (!base) return page
24
+ if (!page) return base
25
+ // Migrated content often carries the site name in the page title already; appending it again reads as a
26
+ // bug to every visitor who looks at the tab.
27
+ if (page === base || page.endsWith(base)) return page
28
+ // The separator is stored as a bare token and padded here: a `text` field trims on write, so a stored
29
+ // " | " would come back as "|" and glue the two titles together.
30
+ const separator = trimmed(site?.titleSeparator) ?? DEFAULT_SEPARATOR
31
+ return site?.titlePosition === 'before' ? `${base} ${separator} ${page}` : `${page} ${separator} ${base}`
32
+ }
33
+
34
+ /** The page wins, the site stands in, and both degrade to absent so the tags disappear entirely. */
35
+ export function siteHeadFallbacks(
36
+ seo: { description?: string | null, $media?: { image?: { src: string, width: number | null, height: number | null } | null } | null } | null | undefined,
37
+ site: SiteHead | null | undefined,
38
+ ): { description?: string, image: { src: string, width: number | null, height: number | null } | null } {
39
+ return {
40
+ description: trimmed(seo?.description) ?? trimmed(site?.description),
41
+ image: seo?.$media?.image ?? site?.$media?.image ?? null,
42
+ }
43
+ }
@@ -13,6 +13,14 @@ export default defineEventHandler((event) => {
13
13
  const locale = typeof q.locale === 'string' ? q.locale : undefined
14
14
  const isStaticRender = import.meta.prerender === true || isRendererContext()
15
15
  const publishedOnly = isStaticRender || event.context.readScope !== 'all'
16
- const resolved = resolvePage(useDb(), allCollections(), path, locale, publishedOnly)
17
- return { collection: resolved?.collection ?? null, page: resolved?.page ?? null, alternates: resolved?.alternates ?? [] }
16
+ const db = useDb()
17
+ const resolved = resolvePage(db, allCollections(), path, locale, publishedOnly)
18
+ // The site-wide head tier rides along on the fetch the page already awaits, so it reaches SSR and the
19
+ // prerender on a path that is known to work. Looked up through the registry, not imported, so a consumer
20
+ // that disables the collection gets `null` instead of a query against a table the schema never created.
21
+ // `depth: 1` resolves the sharing image into `$media`; `getSingleton` captures the read, so an edit
22
+ // re-publishes every route that embedded it.
23
+ const siteCollection = getCollection('site')
24
+ const site = siteCollection ? getSingleton(db, siteCollection, locale, false, 1) : null
25
+ return { collection: resolved?.collection ?? null, page: resolved?.page ?? null, alternates: resolved?.alternates ?? [], site }
18
26
  })
@@ -0,0 +1,44 @@
1
+ import { buildCollection } from '../../../fields/server/utils/buildCollection'
2
+ import { defineCollection } from '../../../core/server/utils/defineCollection'
3
+
4
+ // `siteUrl`/`siteName` stay in `kestrel.config` on purpose: the build needs them for canonical URLs, the
5
+ // sitemap and robots.txt, so they cannot live in the DB. What is here is editorial instead — and a write
6
+ // re-publishes the routes that embed it, which a config value frozen at module setup can never do.
7
+ const built = buildCollection(defineCollection({
8
+ name: 'site',
9
+ mode: 'single',
10
+ translatable: true,
11
+ builtin: true,
12
+ label: { singular: { en: 'Site', de: 'Website' }, plural: { en: 'Site', de: 'Website' } },
13
+ icon: 'globe',
14
+ fields: {
15
+ baseTitle: { type: 'text', label: { en: 'Base title', de: 'Basis-Titel' } },
16
+ titleSeparator: { type: 'text', label: { en: 'Title separator', de: 'Titel-Trenner' }, default: '|' },
17
+ titlePosition: {
18
+ type: 'choice',
19
+ label: { en: 'Base title position', de: 'Position des Basis-Titels' },
20
+ options: {
21
+ choices: [
22
+ { label: { en: 'After the page title', de: 'Nach dem Seitentitel' }, value: 'after' },
23
+ { label: { en: 'Before the page title', de: 'Vor dem Seitentitel' }, value: 'before' },
24
+ ],
25
+ display: 'buttons',
26
+ },
27
+ default: 'after',
28
+ },
29
+ description: {
30
+ type: 'text',
31
+ label: { en: 'Default meta description', de: 'Standard-Meta-Beschreibung' },
32
+ options: { multiline: true },
33
+ },
34
+ image: {
35
+ type: 'media',
36
+ label: { en: 'Default sharing image', de: 'Standard-Sharing-Bild' },
37
+ options: { accept: 'image' },
38
+ },
39
+ },
40
+ fieldLayout: [['baseTitle|2', 'titleSeparator|1'], 'titlePosition', 'description', 'image'],
41
+ }))
42
+
43
+ export const site = built.table
44
+ export default built
package/nuxt.config.ts CHANGED
@@ -83,22 +83,25 @@ export default defineNuxtConfig({
83
83
  vite: {
84
84
  build: { rollupOptions: { onwarn } },
85
85
  optimizeDeps: {
86
- // Nested "kestrel > dep" form: Vite resolves each dep from the `kestrel` PACKAGE's directory
87
- // rather than the (consumer) project root. Under pnpm these are kestrel's transitive deps and
88
- // are NOT hoisted into a consumer's top-level node_modules, so a bare specifier is
89
- // "Unresolvable" from the consumer root. In-repo `kestrel` is not a resolvable package name, so
90
- // Vite's nestedResolveBasedir falls back to the repo root where these deps ARE hoisted same
91
- // result. The runtime `import('@tiptap/...')` still reuses the pre-bundle (tryOptimizedResolve
92
- // matches the "> dep" id + src dir).
86
+ // Nested "<pkg> > dep" form: Vite resolves each dep from THIS package's directory rather than from
87
+ // the consumer's project root. It has to be the published name — under pnpm these are kestrel's
88
+ // transitive deps and are not hoisted into a consumer's top-level node_modules, so resolving from
89
+ // the root finds nothing. An unresolvable prefix is swallowed (`resolvePackageData(…)?.dir ||
90
+ // basedir`), and the entry then degrades to a bare lookup from the root: fine in-repo and for a
91
+ // hoisted npm/yarn consumer, silently unbundled for a pnpm one — which is why a stale prefix shows
92
+ // up only in a consumer's terminal. In-repo the name is likewise unresolvable and that same
93
+ // fallback lands on the repo root, where the deps ARE hoisted. The runtime `import('@tiptap/...')`
94
+ // still reuses the pre-bundle (tryOptimizedResolve matches the "> dep" id + src dir).
95
+ // `test/package.test.ts` pins the prefix to package.json's `name`.
93
96
  include: [
94
- 'kestrel > @internationalized/date',
95
- 'kestrel > @tiptap/extension-highlight',
96
- 'kestrel > @tiptap/extension-subscript',
97
- 'kestrel > @tiptap/extension-superscript',
98
- 'kestrel > @tiptap/extension-text-align',
99
- 'kestrel > @tiptap/starter-kit',
100
- 'kestrel > @tiptap/vue-3',
101
- 'kestrel > reka-ui',
97
+ '@michaelthielemann/kestrel > @internationalized/date',
98
+ '@michaelthielemann/kestrel > @tiptap/extension-highlight',
99
+ '@michaelthielemann/kestrel > @tiptap/extension-subscript',
100
+ '@michaelthielemann/kestrel > @tiptap/extension-superscript',
101
+ '@michaelthielemann/kestrel > @tiptap/extension-text-align',
102
+ '@michaelthielemann/kestrel > @tiptap/starter-kit',
103
+ '@michaelthielemann/kestrel > @tiptap/vue-3',
104
+ '@michaelthielemann/kestrel > reka-ui',
102
105
  ],
103
106
  },
104
107
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@michaelthielemann/kestrel",
3
- "version": "1.4.0",
3
+ "version": "1.5.0",
4
4
  "description": "A slim, collection-driven Nuxt 4 CMS meta-layer with a runtime schema engine. Add `extends: ['@michaelthielemann/kestrel']`, define collections, and the database migrates itself.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Michael Thielemann <283621694+MichaelThielemann@users.noreply.github.com>",
@@ -1,5 +1,6 @@
1
1
  import { createInterface } from 'node:readline'
2
2
  import { hashPassword } from './lib/password.mjs'
3
+ import { Cancelled, promptPassword } from './lib/cli.mjs'
3
4
 
4
5
  // Not used at runtime: this prints a value an operator pastes into KESTREL_ADMIN_PASSWORD_HASH. Kept as a
5
6
  // standalone entry point because docs/consuming-kestrel.md tells consumers to run it straight out of
@@ -7,7 +8,18 @@ import { hashPassword } from './lib/password.mjs'
7
8
  const arg = process.argv[2]
8
9
  if (arg) {
9
10
  process.stdout.write(hashPassword(arg) + '\n')
11
+ } else if (process.stdin.isTTY) {
12
+ // Only the hash may reach stdout — an operator pipes it straight into a secret store.
13
+ try {
14
+ process.stdout.write(hashPassword(await promptPassword({ output: process.stderr })) + '\n')
15
+ } catch (err) {
16
+ if (!(err instanceof Cancelled)) throw err
17
+ process.stderr.write('cancelled\n')
18
+ process.exitCode = 1
19
+ }
10
20
  } else {
21
+ // `terminal: false` keeps the piped form (`echo pw | node hash-password.mjs`) working; it is only safe
22
+ // because stdin is not a tty here, so there is no line discipline echoing the password onto a screen.
11
23
  const rl = createInterface({ input: process.stdin, terminal: false })
12
24
  process.stderr.write('Enter password, then press Enter:\n')
13
25
  rl.on('line', (line) => {
@@ -2,7 +2,6 @@
2
2
  import { existsSync, mkdirSync, readFileSync } from 'node:fs'
3
3
  import { join, resolve, basename, relative } from 'node:path'
4
4
  import { fileURLToPath } from 'node:url'
5
- import { createInterface } from 'node:readline/promises'
6
5
  import { hashPassword, sessionSecret } from './lib/password.mjs'
7
6
  import { PACKAGE_NAME, diagnoseProject, mergeEnv, mergePackageJson, renderTemplate, targetName, toPackageName } from './lib/scaffold.mjs'
8
7
  import { Cancelled, MIN_PASSWORD_LENGTH, makePaint, out, parseArgs, promptPassword, readIf, readStdin, walk, write } from './lib/cli.mjs'
@@ -71,15 +70,12 @@ async function init(positional, flags) {
71
70
  out()
72
71
 
73
72
  if (password === undefined && !flags.yes && process.stdin.isTTY) {
74
- const rl = createInterface({ input: process.stdin, output: process.stdout })
75
73
  try {
76
- password = await promptPassword(rl, { warn: (m) => out(yellow(m)) })
74
+ password = await promptPassword({ warn: (m) => out(yellow(m)), note: (m) => out(dim(m)) })
77
75
  } catch (err) {
78
- rl.close()
79
76
  if (err instanceof Cancelled) fail('cancelled')
80
77
  throw err
81
78
  }
82
- rl.close()
83
79
  out()
84
80
  }
85
81
 
@@ -170,15 +166,14 @@ async function hashPasswordCommand(positional) {
170
166
  let password = positional[0]
171
167
  if (password === undefined) {
172
168
  if (process.stdin.isTTY) {
173
- const rl = createInterface({ input: process.stdin, output: process.stdout })
169
+ // Only the hash may reach stdout — an operator redirects it straight into a secret store.
170
+ const ask = (m) => process.stderr.write(`${m}\n`)
174
171
  try {
175
- password = await promptPassword(rl, { warn: (m) => out(yellow(m)) })
172
+ password = await promptPassword({ output: process.stderr, warn: (m) => ask(yellow(m)), note: (m) => ask(dim(m)) })
176
173
  } catch (err) {
177
- rl.close()
178
174
  if (err instanceof Cancelled) fail('cancelled')
179
175
  throw err
180
176
  }
181
- rl.close()
182
177
  } else password = await readStdin()
183
178
  }
184
179
  if (!password) fail('no password given')
@@ -1,5 +1,6 @@
1
1
  import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync, chmodSync } from 'node:fs'
2
2
  import { dirname, join, relative } from 'node:path'
3
+ import { createInterface } from 'node:readline/promises'
3
4
 
4
5
  export const MIN_PASSWORD_LENGTH = 8
5
6
 
@@ -65,44 +66,58 @@ export function walk(dir, base = dir) {
65
66
  return found
66
67
  }
67
68
 
68
- /**
69
- * Reads a line with the echo suppressed. readline echoes before we see the data event, so the fix is to
70
- * repaint the prompt over whatever was written — unconditionally, because a pasted secret arrives as one
71
- * chunk that ends in a newline and would otherwise be left on screen and in the scrollback.
72
- */
73
- async function askHidden(rl, question) {
74
- const repaint = () => process.stdout.write(`\u001b[2K\u001b[200D${question}`)
75
- process.stdin.on('data', repaint)
69
+ /** Reads a line the interface is configured never to echo, so the prompt is ours to draw and to close. */
70
+ async function askHidden(rl, question, write) {
71
+ write(question)
76
72
  try {
77
- return (await rl.question(question)).trim()
73
+ return (await rl.question('')).trim()
78
74
  } finally {
79
- process.stdin.off('data', repaint)
80
- repaint()
81
- process.stdout.write('\n')
75
+ write('\n')
82
76
  }
83
77
  }
84
78
 
85
79
  export class Cancelled extends Error {}
86
80
 
87
- /** Throws `Cancelled` on Ctrl-C / Ctrl-D so a caller can exit cleanly instead of on an AbortError stack. */
88
- export async function promptPassword(rl, { warn = out } = {}) {
89
- for (;;) {
90
- let first
91
- try {
92
- first = await askHidden(rl, 'Admin password: ')
93
- if (first.length < MIN_PASSWORD_LENGTH) {
94
- warn(` at least ${MIN_PASSWORD_LENGTH} characters, please`)
95
- continue
96
- }
97
- if (first !== (await askHidden(rl, 'Repeat password: '))) {
98
- warn(' the two entries differ — try again')
99
- continue
81
+ /**
82
+ * Owns its readline interface, because the two options that keep the secret off the screen can only be
83
+ * set at construction: `output: null` makes readline write nothing at all, and `terminal: true` still
84
+ * gives it the keypress handling (backspace, Ctrl-C, Ctrl-D) that would otherwise fall to the tty's own
85
+ * echoing line discipline. Erasing readline's echo afterwards cannot match that — a pasted secret arrives
86
+ * as one chunk that is echoed AND newlined in a single write, stranding the cleartext on a line no
87
+ * repaint can still reach, and a redirected stdout leaves `terminal` false with nothing to suppress.
88
+ *
89
+ * Throws `Cancelled` on Ctrl-C / Ctrl-D so a caller can exit cleanly instead of on an AbortError stack.
90
+ */
91
+ export async function promptPassword({
92
+ input = process.stdin,
93
+ output = process.stdout,
94
+ warn = (m) => output.write(`${m}\n`),
95
+ note = (m) => output.write(`${m}\n`),
96
+ } = {}) {
97
+ const draw = (s) => output.write(s)
98
+ const rl = createInterface({ input, output: null, terminal: true })
99
+ note(`Choose a password for /admin — at least ${MIN_PASSWORD_LENGTH} characters, kept only as a scrypt hash.`)
100
+ try {
101
+ for (;;) {
102
+ let first
103
+ try {
104
+ first = await askHidden(rl, 'New admin password: ', draw)
105
+ if (first.length < MIN_PASSWORD_LENGTH) {
106
+ warn(` too short — at least ${MIN_PASSWORD_LENGTH} characters`)
107
+ continue
108
+ }
109
+ if (first !== (await askHidden(rl, 'Repeat password: ', draw))) {
110
+ warn(' the two entries differ — try again')
111
+ continue
112
+ }
113
+ } catch (err) {
114
+ throw err?.code === 'ABORT_ERR' ? new Cancelled() : err
100
115
  }
101
- } catch (err) {
102
- throw err?.code === 'ABORT_ERR' ? new Cancelled() : err
116
+ if (first === undefined) throw new Cancelled()
117
+ return first
103
118
  }
104
- if (first === undefined) throw new Cancelled()
105
- return first
119
+ } finally {
120
+ rl.close()
106
121
  }
107
122
  }
108
123
 
@@ -8,7 +8,7 @@ pnpm install
8
8
  pnpm dev
9
9
  ```
10
10
 
11
- Admin: <http://localhost:3000/admin> — sign in with the password you chose during `kestrel init`.
11
+ Admin: <http://localhost:3000/admin> — sign in with the password you chose while scaffolding.
12
12
  Forgot it? `pnpm hash-password` prints a fresh hash for `KESTREL_ADMIN_PASSWORD_HASH` in `.env`.
13
13
 
14
14
  ## What is here