@prenta/cli 1.2.0 → 1.3.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 (36) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +153 -85
  3. package/CHANGELOG.md +13 -0
  4. package/dist/commands/chrome.d.ts.map +1 -1
  5. package/dist/commands/chrome.js +3 -2
  6. package/dist/commands/chrome.js.map +1 -1
  7. package/dist/commands/mcp.d.ts.map +1 -1
  8. package/dist/commands/mcp.js +29 -4
  9. package/dist/commands/mcp.js.map +1 -1
  10. package/dist/commands/migrate-meta.js +2 -2
  11. package/dist/commands/migrate-meta.js.map +1 -1
  12. package/dist/commands/migrate-schema.js +2 -2
  13. package/dist/commands/migrate-schema.js.map +1 -1
  14. package/dist/commands/seed.d.ts +25 -0
  15. package/dist/commands/seed.d.ts.map +1 -1
  16. package/dist/commands/seed.js +74 -7
  17. package/dist/commands/seed.js.map +1 -1
  18. package/dist/utils/import-typescript.d.ts +19 -1
  19. package/dist/utils/import-typescript.d.ts.map +1 -1
  20. package/dist/utils/import-typescript.js +56 -6
  21. package/dist/utils/import-typescript.js.map +1 -1
  22. package/dist/utils/load-project-config.js +2 -2
  23. package/dist/utils/load-project-config.js.map +1 -1
  24. package/package.json +2 -2
  25. package/src/__tests__/import-typescript-hooks.test.ts +37 -0
  26. package/src/__tests__/import-typescript.test.ts +46 -1
  27. package/src/__tests__/mcp-init.test.ts +48 -2
  28. package/src/__tests__/seed-sanitize.test.ts +160 -0
  29. package/src/__tests__/seed.test.ts +4 -0
  30. package/src/commands/chrome.ts +3 -2
  31. package/src/commands/mcp.ts +36 -7
  32. package/src/commands/migrate-meta.ts +2 -2
  33. package/src/commands/migrate-schema.ts +2 -2
  34. package/src/commands/seed.ts +96 -7
  35. package/src/utils/import-typescript.ts +58 -6
  36. package/src/utils/load-project-config.ts +2 -2
@@ -1,3 +1,4 @@
1
+ import { execFileSync } from 'node:child_process'
1
2
  import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises'
2
3
  import { tmpdir } from 'node:os'
3
4
  import path from 'node:path'
@@ -40,10 +41,16 @@ afterEach(async () => {
40
41
  })
41
42
 
42
43
  describe('mcp:init', () => {
43
- it('creates both editor configs with placeholder key and git-ignores them', async () => {
44
+ it('creates Claude Code, Cursor, and VS Code configs with placeholder key and git-ignores them', async () => {
44
45
  await writeFile(path.join(projectDir, '.gitignore'), 'node_modules\n', 'utf8')
45
46
  await run()
46
47
 
48
+ const claude = await readJson('.mcp.json')
49
+ expect(claude.mcpServers.prenta.command).toBe('npx')
50
+ expect(claude.mcpServers.prenta.args).toEqual(['-y', '@prenta/mcp-server'])
51
+ expect(claude.mcpServers.prenta.env.PRENTA_BASE_URL).toBe('http://localhost:3000')
52
+ expect(claude.mcpServers.prenta.env.PRENTA_API_KEY).toBe('act_sk_REPLACE_WITH_YOUR_KEY')
53
+
47
54
  const cursor = await readJson('.cursor/mcp.json')
48
55
  expect(cursor.mcpServers.prenta.command).toBe('npx')
49
56
  expect(cursor.mcpServers.prenta.args).toEqual(['-y', '@prenta/mcp-server'])
@@ -55,13 +62,19 @@ describe('mcp:init', () => {
55
62
 
56
63
  const gitignore = await readFile(path.join(projectDir, '.gitignore'), 'utf8')
57
64
  expect(gitignore).toContain('node_modules')
65
+ expect(gitignore).toContain('.mcp.json')
58
66
  expect(gitignore).toContain('.cursor/mcp.json')
59
67
  expect(gitignore).toContain('.vscode/mcp.json')
60
68
  })
61
69
 
62
- it('applies --url and --key to both configs', async () => {
70
+ it('applies --url and --key to all three configs', async () => {
63
71
  await run(['--url', 'https://example.com', '--key', 'act_sk_real123'])
64
72
 
73
+ const claude = await readJson('.mcp.json')
74
+ expect(claude.mcpServers.prenta.env).toEqual({
75
+ PRENTA_BASE_URL: 'https://example.com',
76
+ PRENTA_API_KEY: 'act_sk_real123',
77
+ })
65
78
  const cursor = await readJson('.cursor/mcp.json')
66
79
  expect(cursor.mcpServers.prenta.env).toEqual({
67
80
  PRENTA_BASE_URL: 'https://example.com',
@@ -73,6 +86,11 @@ describe('mcp:init', () => {
73
86
 
74
87
  it('merges into an existing config without clobbering other servers', async () => {
75
88
  await mkdir(path.join(projectDir, '.cursor'), { recursive: true })
89
+ await writeFile(
90
+ path.join(projectDir, '.mcp.json'),
91
+ JSON.stringify({ mcpServers: { github: { command: 'github-mcp' } } }),
92
+ 'utf8',
93
+ )
76
94
  await writeFile(
77
95
  path.join(projectDir, '.cursor', 'mcp.json'),
78
96
  JSON.stringify({ mcpServers: { sentry: { command: 'sentry-mcp' } } }),
@@ -80,6 +98,10 @@ describe('mcp:init', () => {
80
98
  )
81
99
  await run()
82
100
 
101
+ const claude = await readJson('.mcp.json')
102
+ expect(claude.mcpServers.github).toEqual({ command: 'github-mcp' })
103
+ expect(claude.mcpServers.prenta).toBeDefined()
104
+
83
105
  const cursor = await readJson('.cursor/mcp.json')
84
106
  expect(cursor.mcpServers.sentry).toEqual({ command: 'sentry-mcp' })
85
107
  expect(cursor.mcpServers.prenta).toBeDefined()
@@ -115,6 +137,30 @@ describe('mcp:init', () => {
115
137
  expect(cursor.mcpServers.prenta).toBeDefined()
116
138
  })
117
139
 
140
+ it('refuses to write a real key into a config git already tracks', async () => {
141
+ const git = (...args: string[]) =>
142
+ execFileSync('git', args, { cwd: projectDir, stdio: 'ignore' })
143
+ git('init', '-q')
144
+ const shared = { mcpServers: { other: { command: 'other-server' } } }
145
+ await writeFile(path.join(projectDir, '.mcp.json'), JSON.stringify(shared), 'utf8')
146
+ git('add', '.mcp.json')
147
+
148
+ await run(['--key', 'act_sk_realkey123'])
149
+ expect(process.exitCode).toBe(1)
150
+ process.exitCode = 0
151
+
152
+ // The tracked file is untouched; the untracked editor configs get the key.
153
+ expect(await readJson('.mcp.json')).toEqual(shared)
154
+ const cursor = await readJson('.cursor/mcp.json')
155
+ expect(cursor.mcpServers.prenta.env.PRENTA_API_KEY).toBe('act_sk_realkey123')
156
+
157
+ // The placeholder is not a secret, so a tracked file can still be wired up.
158
+ await run()
159
+ const claude = await readJson('.mcp.json')
160
+ expect(claude.mcpServers.other).toEqual({ command: 'other-server' })
161
+ expect(claude.mcpServers.prenta.env.PRENTA_API_KEY).toBe('act_sk_REPLACE_WITH_YOUR_KEY')
162
+ })
163
+
118
164
  it('does not duplicate gitignore entries on re-runs', async () => {
119
165
  await run()
120
166
  await run(['--force'])
@@ -0,0 +1,160 @@
1
+ import * as core from '@prenta/core'
2
+ import { afterEach, describe, expect, it } from 'vitest'
3
+
4
+ import { sanitizeSeedDocumentData } from '../commands/seed.js'
5
+
6
+ // Real @prenta/core, not a mock: the point is what the shipped sanitiser does
7
+ // to Markdown, and that only declared `richText` fields reach it.
8
+ const sanitizers = core as unknown as Parameters<typeof sanitizeSeedDocumentData>[2]
9
+
10
+ const MARKDOWN = [
11
+ '# Deploying',
12
+ '',
13
+ '> Run this once per environment.',
14
+ '',
15
+ 'Open `https://<your-site>/admin` and sign in.',
16
+ '',
17
+ 'Use a <details> block for long output.',
18
+ ].join('\n')
19
+
20
+ function registerCollections(collections: Record<string, unknown>): void {
21
+ core.setPrentaConfig({ collections } as never)
22
+ }
23
+
24
+ afterEach(() => {
25
+ delete (globalThis as { __prentaConfig?: unknown }).__prentaConfig
26
+ })
27
+
28
+ describe('sanitizeSeedDocumentData', () => {
29
+ it('leaves Markdown in a declared text field exactly as written', () => {
30
+ registerCollections({
31
+ docs: { fields: { title: { type: 'text' }, body: { type: 'text' } } },
32
+ })
33
+
34
+ const out = sanitizeSeedDocumentData({ title: 'Deploying', body: MARKDOWN }, 'docs', sanitizers)
35
+
36
+ expect(out.body).toBe(MARKDOWN)
37
+ })
38
+
39
+ it('leaves textarea, select and json fields alone too', () => {
40
+ registerCollections({
41
+ docs: {
42
+ fields: {
43
+ summary: { type: 'textarea' },
44
+ meta: { type: 'json' },
45
+ },
46
+ },
47
+ })
48
+ const data = { summary: 'a > b and <placeholder>', meta: { note: 'x <y> z' } }
49
+
50
+ expect(sanitizeSeedDocumentData(data, 'docs', sanitizers)).toEqual(data)
51
+ })
52
+
53
+ it('still sanitises a declared richText field', () => {
54
+ registerCollections({ posts: { fields: { body: { type: 'richText' } } } })
55
+
56
+ const out = sanitizeSeedDocumentData(
57
+ { body: '<p>Hello</p><script>alert(1)</script>' },
58
+ 'posts',
59
+ sanitizers,
60
+ )
61
+
62
+ expect(out.body).toBe('<p>Hello</p>')
63
+ })
64
+
65
+ it('sanitises keys the collection does not declare', () => {
66
+ registerCollections({ docs: { fields: { body: { type: 'text' } } } })
67
+
68
+ const out = sanitizeSeedDocumentData(
69
+ { body: MARKDOWN, content: '<p>Hi</p><script>alert(1)</script>' },
70
+ 'docs',
71
+ sanitizers,
72
+ )
73
+
74
+ expect(out.body).toBe(MARKDOWN)
75
+ expect(out.content).toBe('<p>Hi</p>')
76
+ })
77
+
78
+ it('still sanitises a section whose type is not in the registry', () => {
79
+ // A project's custom section types are not registered in the CLI process,
80
+ // so the registry cannot say which of their slots hold HTML.
81
+ registerCollections({ pages: { fields: { title: { type: 'text' } } } })
82
+
83
+ const out = sanitizeSeedDocumentData(
84
+ {
85
+ title: 'Home',
86
+ sections: [
87
+ {
88
+ id: 's1',
89
+ sectionType: 'acme-custom-banner',
90
+ content: { body: '<p>Hi</p><script>alert(1)</script><img src=x onerror=alert(1)>' },
91
+ },
92
+ ],
93
+ },
94
+ 'pages',
95
+ sanitizers,
96
+ )
97
+
98
+ const stored = JSON.stringify(out.sections)
99
+ expect(stored).toContain('<p>Hi</p>')
100
+ expect(stored).not.toContain('<script')
101
+ expect(stored).not.toContain('onerror')
102
+ })
103
+
104
+ it('cleans the page-builder _layout tree', () => {
105
+ registerCollections({ pages: { fields: { title: { type: 'text' } } } })
106
+
107
+ const out = sanitizeSeedDocumentData(
108
+ {
109
+ title: 'Home',
110
+ _layout: {
111
+ type: 'container',
112
+ children: [{ type: 'block', data: { html: '<p>ok</p><script>alert(1)</script>' } }],
113
+ },
114
+ },
115
+ 'pages',
116
+ sanitizers,
117
+ )
118
+
119
+ expect(JSON.stringify(out._layout)).not.toContain('<script')
120
+ expect(JSON.stringify(out._layout)).toContain('<p>ok</p>')
121
+ })
122
+
123
+ it('falls back to the shape-based pass when the collection has no schema', () => {
124
+ registerCollections({ docs: { fields: { body: { type: 'text' } } } })
125
+
126
+ const out = sanitizeSeedDocumentData(
127
+ { content: '<p>Hi</p><script>alert(1)</script>' },
128
+ 'imported',
129
+ sanitizers,
130
+ )
131
+
132
+ expect(out.content).toBe('<p>Hi</p>')
133
+ })
134
+
135
+ it('falls back to the shape-based pass when no config is registered', () => {
136
+ const out = sanitizeSeedDocumentData(
137
+ { content: '<p>Hi</p><script>alert(1)</script>' },
138
+ 'pages',
139
+ sanitizers,
140
+ )
141
+
142
+ expect(out.content).toBe('<p>Hi</p>')
143
+ })
144
+
145
+ it('falls back when the installed core predates the schema-aware sanitiser', () => {
146
+ registerCollections({ docs: { fields: { body: { type: 'richText' } } } })
147
+ const olderCore = {
148
+ sanitizeHtml: core.sanitizeHtml,
149
+ getPrentaConfig: core.getPrentaConfig,
150
+ } as unknown as typeof sanitizers
151
+
152
+ const out = sanitizeSeedDocumentData(
153
+ { body: '<p>Hi</p><script>alert(1)</script>' },
154
+ 'docs',
155
+ olderCore,
156
+ )
157
+
158
+ expect(out.body).toBe('<p>Hi</p>')
159
+ })
160
+ })
@@ -5,6 +5,10 @@ vi.mock('@prenta/core', () => ({
5
5
  hashContent: vi.fn(async () => 'hash-1'),
6
6
  sanitizeHtml: vi.fn((value: string) => value.replace(/<script[\s\S]*?<\/script>/gi, '')),
7
7
  createInitialAdmin: vi.fn(),
8
+ // No project config registered: these tests cover the schemaless path.
9
+ getPrentaConfig: vi.fn(() => undefined),
10
+ sanitizeDocumentHtml: vi.fn((data: Record<string, unknown>) => data),
11
+ sanitizeLayoutTree: vi.fn((layout: unknown) => layout),
8
12
  }))
9
13
 
10
14
  import {
@@ -8,7 +8,7 @@ import type {
8
8
  RegionDefinition,
9
9
  RegionSchema,
10
10
  } from '@prenta/core'
11
- import { importProjectTypescript } from '../utils/import-typescript.js'
11
+ import { importProjectTypescript, projectModuleExports } from '../utils/import-typescript.js'
12
12
  import { logger } from '../utils/logger.js'
13
13
 
14
14
  const DEFAULT_SCHEMA_FILE = '.prenta/chrome.json'
@@ -143,7 +143,8 @@ export async function collectRegions(mod: unknown): Promise<RegionDefinition[]>
143
143
  if (typeof mod !== 'object' || mod === null) return []
144
144
  const { isRegionDefinition } = await chromeCore()
145
145
  const found = new Map<string, RegionDefinition>()
146
- for (const value of Object.values(mod as Record<string, unknown>)) {
146
+ // A CommonJS-compiled config keeps its named exports one level down.
147
+ for (const value of Object.values(projectModuleExports(mod))) {
147
148
  if (isRegionDefinition(value)) {
148
149
  if (found.has(value.region)) {
149
150
  throw new Error(`The config defines the ${value.region} region twice.`)
@@ -1,3 +1,4 @@
1
+ import { execFileSync } from 'node:child_process'
1
2
  import { existsSync } from 'node:fs'
2
3
  import { mkdir, readFile, writeFile } from 'node:fs/promises'
3
4
  import path from 'node:path'
@@ -9,11 +10,11 @@ import { logger } from '../utils/logger.js'
9
10
  * `prenta mcp:init` — retrofit the Prenta MCP server config onto an
10
11
  * existing project.
11
12
  *
12
- * New scaffolds (`npm create prenta`) emit `.cursor/mcp.json` and
13
+ * New scaffolds (`npm create prenta`) emit `.mcp.json`, `.cursor/mcp.json`, and
13
14
  * `.vscode/mcp.json` automatically; projects created before that feature (or
14
- * set up by hand) have no easy path. This command writes both editor configs,
15
+ * set up by hand) have no easy path. This command writes all three configs,
15
16
  * merging into existing files so other MCP servers are preserved, and ensures
16
- * both paths are git-ignored (a real `act_sk_...` key pasted into them must
17
+ * all paths are git-ignored (a real `act_sk_...` key pasted into them must
17
18
  * never be committed).
18
19
  */
19
20
 
@@ -49,6 +50,23 @@ interface MergeTarget {
49
50
 
50
51
  type MergeResult = 'created' | 'updated' | 'skipped' | 'error'
51
52
 
53
+ /**
54
+ * True when git already tracks `relPath`. Adding a tracked file to
55
+ * `.gitignore` does not untrack it, so a key written there would still be
56
+ * committed. Outside a git repository (or without git) nothing is tracked.
57
+ */
58
+ function isTrackedByGit(root: string, relPath: string): boolean {
59
+ try {
60
+ execFileSync('git', ['ls-files', '--error-unmatch', '--', relPath], {
61
+ cwd: root,
62
+ stdio: 'ignore',
63
+ })
64
+ return true
65
+ } catch {
66
+ return false
67
+ }
68
+ }
69
+
52
70
  /**
53
71
  * Create or merge one editor config. Existing files keep every other server
54
72
  * entry; an existing `prenta` entry is only replaced with `--force`.
@@ -123,7 +141,9 @@ async function ensureGitignored(root: string, relPaths: string[]): Promise<strin
123
141
  export function registerMcpCommand(program: Command): void {
124
142
  program
125
143
  .command('mcp:init')
126
- .description('Write .cursor/mcp.json + .vscode/mcp.json wiring the Prenta MCP server')
144
+ .description(
145
+ 'Write .mcp.json + .cursor/mcp.json + .vscode/mcp.json wiring the Prenta MCP server',
146
+ )
127
147
  .option('--url <baseUrl>', 'Base URL of the running CMS', 'http://localhost:3000')
128
148
  .option('--key <apiKey>', 'Prenta API key (act_sk_...)', PLACEHOLDER_KEY)
129
149
  .option('--force', 'Replace an existing "prenta" server entry (or unparseable config)')
@@ -137,12 +157,21 @@ export function registerMcpCommand(program: Command): void {
137
157
  }
138
158
 
139
159
  const targets: MergeTarget[] = [
160
+ { relPath: '.mcp.json', rootKey: 'mcpServers', entry: cursorEntry(opts) },
140
161
  { relPath: '.cursor/mcp.json', rootKey: 'mcpServers', entry: cursorEntry(opts) },
141
162
  { relPath: '.vscode/mcp.json', rootKey: 'servers', entry: vscodeEntry(opts) },
142
163
  ]
143
164
 
144
165
  let failed = false
145
166
  for (const target of targets) {
167
+ if (opts.key !== PLACEHOLDER_KEY && isTrackedByGit(root, target.relPath)) {
168
+ logger.error(
169
+ `${target.relPath} is tracked by git, so the key was not written to it. ` +
170
+ `Run "git rm --cached ${target.relPath}" and commit, then re-run this command.`,
171
+ )
172
+ failed = true
173
+ continue
174
+ }
146
175
  const result = await mergeConfigFile(root, target, Boolean(opts.force))
147
176
  if (result === 'created') logger.success(`Created ${target.relPath}`)
148
177
  else if (result === 'updated') logger.success(`Updated ${target.relPath}`)
@@ -164,11 +193,11 @@ export function registerMcpCommand(program: Command): void {
164
193
  ` 1. Mint an API key in ${chalk.cyan('Admin → Settings → API Keys')} (act_sk_...)`,
165
194
  )
166
195
  console.log(
167
- ` 2. Replace ${chalk.cyan(PLACEHOLDER_KEY)} in both config files with the real key`,
196
+ ` 2. Replace ${chalk.cyan(PLACEHOLDER_KEY)} in the MCP config files with the real key`,
168
197
  )
169
- console.log(' 3. Restart Cursor / VS Code so the MCP server is picked up')
198
+ console.log(' 3. Restart Claude Code / Cursor / VS Code so the MCP server is picked up')
170
199
  } else {
171
- console.log(' 1. Restart Cursor / VS Code so the MCP server is picked up')
200
+ console.log(' 1. Restart Claude Code / Cursor / VS Code so the MCP server is picked up')
172
201
  }
173
202
  if (opts.url === 'http://localhost:3000') {
174
203
  console.log(
@@ -2,7 +2,7 @@ import { Command } from 'commander'
2
2
  import { resolve } from 'node:path'
3
3
  import ora from 'ora'
4
4
  import { connectProjectDatabase } from '../utils/database.js'
5
- import { importProjectTypescript } from '../utils/import-typescript.js'
5
+ import { importProjectTypescript, projectDefaultExport } from '../utils/import-typescript.js'
6
6
  import { loadProjectEnv } from '../utils/load-dotenv.js'
7
7
  import { logger } from '../utils/logger.js'
8
8
 
@@ -19,7 +19,7 @@ async function loadProjectConfig(configPath: string): Promise<void> {
19
19
  default?: unknown
20
20
  config?: unknown
21
21
  }
22
- const config = mod.default ?? mod.config
22
+ const config = projectDefaultExport(mod, 'config')
23
23
  if (config && typeof config === 'object') {
24
24
  setPrentaConfig(config as never)
25
25
  }
@@ -2,7 +2,7 @@ import { Command } from 'commander'
2
2
  import { resolve } from 'node:path'
3
3
  import ora from 'ora'
4
4
  import { connectProjectDatabase } from '../utils/database.js'
5
- import { importProjectTypescript } from '../utils/import-typescript.js'
5
+ import { importProjectTypescript, projectDefaultExport } from '../utils/import-typescript.js'
6
6
  import { loadProjectEnv } from '../utils/load-dotenv.js'
7
7
  import { logger } from '../utils/logger.js'
8
8
 
@@ -19,7 +19,7 @@ async function loadProjectConfig(configPath: string): Promise<void> {
19
19
  default?: unknown
20
20
  config?: unknown
21
21
  }
22
- const config = mod.default ?? mod.config
22
+ const config = projectDefaultExport(mod, 'config')
23
23
  if (config && typeof config === 'object') {
24
24
  setPrentaConfig(config as never)
25
25
  }
@@ -7,7 +7,11 @@ import ora from 'ora'
7
7
  import { logger } from '../utils/logger.js'
8
8
  import { connectProjectDatabase } from '../utils/database.js'
9
9
  import { validateFormSeeds } from '../utils/form-seed.js'
10
- import { importProjectTypescript, toProjectFileUrl } from '../utils/import-typescript.js'
10
+ import {
11
+ importProjectTypescript,
12
+ projectDefaultExport,
13
+ toProjectFileUrl,
14
+ } from '../utils/import-typescript.js'
11
15
 
12
16
  async function confirm(question: string): Promise<boolean> {
13
17
  const rl = createInterface({ input: process.stdin, output: process.stdout })
@@ -350,7 +354,7 @@ async function loadSeedFile(filePath: string): Promise<unknown> {
350
354
  ? await importProjectTypescript(filePath)
351
355
  : await import(toProjectFileUrl(filePath))
352
356
 
353
- return (mod as { default?: unknown; seed?: unknown }).default ?? (mod as { seed?: unknown }).seed
357
+ return projectDefaultExport(mod, 'seed')
354
358
  }
355
359
 
356
360
  async function runSeed(options: SeedOptions): Promise<void> {
@@ -367,6 +371,7 @@ async function runSeed(options: SeedOptions): Promise<void> {
367
371
  try {
368
372
  seededDb = await connectProjectDatabase()
369
373
  const db = seededDb.db
374
+ await loadSeedConfig()
370
375
 
371
376
  if (options.reset) {
372
377
  const yes = await confirm('This will delete ALL existing documents and versions. Continue?')
@@ -423,15 +428,22 @@ export async function ensureSeedAdmin(db: any): Promise<{ id: string }> {
423
428
  return { id: result.userId }
424
429
  }
425
430
 
426
- function sanitizeSeedData(value: unknown, sanitizeHtml: (html: string) => string): unknown {
431
+ /**
432
+ * Sanitise a value whose field type is unknown: every string that looks like
433
+ * it contains a tag goes through the HTML sanitiser. This is a guess from the
434
+ * string's shape, so it damages plain text that merely contains angle brackets
435
+ * (Markdown blockquotes become `&gt;`, `<your-site>` placeholders vanish). Use
436
+ * it only where the schema cannot say what a field holds.
437
+ */
438
+ function sanitizeByShape(value: unknown, sanitizeHtml: (html: string) => string): unknown {
427
439
  if (Array.isArray(value)) {
428
- return value.map((item) => sanitizeSeedData(item, sanitizeHtml))
440
+ return value.map((item) => sanitizeByShape(item, sanitizeHtml))
429
441
  }
430
442
  if (value && typeof value === 'object') {
431
443
  return Object.fromEntries(
432
444
  Object.entries(value as Record<string, unknown>).map(([key, item]) => [
433
445
  key,
434
- sanitizeSeedData(item, sanitizeHtml),
446
+ sanitizeByShape(item, sanitizeHtml),
435
447
  ]),
436
448
  )
437
449
  }
@@ -441,14 +453,91 @@ function sanitizeSeedData(value: unknown, sanitizeHtml: (html: string) => string
441
453
  return value
442
454
  }
443
455
 
456
+ interface SeedSanitizers {
457
+ sanitizeHtml: (html: string) => string
458
+ sanitizeDocumentHtml: (
459
+ data: Record<string, unknown>,
460
+ collection: string,
461
+ options?: { onUnknownSection?: (section: Record<string, unknown>) => unknown },
462
+ ) => Record<string, unknown>
463
+ sanitizeLayoutTree: (layout: unknown) => unknown
464
+ getPrentaConfig: () =>
465
+ | { collections?: Record<string, { fields?: Record<string, unknown> } | undefined> }
466
+ | undefined
467
+ }
468
+
469
+ /**
470
+ * Sanitise a seed document the way an API write does: by field type.
471
+ *
472
+ * Fields the collection declares are handled by cms-core's
473
+ * `sanitizeDocumentHtml`, which sanitises `richText` (and the rich-text slots
474
+ * of `sections`) and leaves `text`, `textarea` and every other plain type
475
+ * exactly as written, so Markdown stored in a `text` field survives seeding.
476
+ * Keys the collection does not declare, and collections with no schema at all
477
+ * (no loadable `prenta.config.ts`, or an ad-hoc collection), keep the older
478
+ * shape-based pass so undeclared HTML is still cleaned before storage.
479
+ */
480
+ export function sanitizeSeedDocumentData(
481
+ data: Record<string, unknown>,
482
+ collection: string,
483
+ core: SeedSanitizers,
484
+ ): Record<string, unknown> {
485
+ const fields = core.getPrentaConfig?.()?.collections?.[collection]?.fields
486
+ // An installed @prenta/core older than the one that exports the schema-aware
487
+ // sanitiser gets the shape-based pass too.
488
+ const schemaAware =
489
+ typeof core.sanitizeDocumentHtml === 'function' && typeof core.sanitizeLayoutTree === 'function'
490
+ if (!schemaAware || !fields || Array.isArray(fields) || Object.keys(fields).length === 0) {
491
+ return sanitizeByShape(data, core.sanitizeHtml) as Record<string, unknown>
492
+ }
493
+ // The seed does not validate section types and has no registry entries for a
494
+ // project's custom ones, so a section the registry does not know keeps the
495
+ // shape-based pass rather than being stored unsanitised.
496
+ const bySchema = core.sanitizeDocumentHtml(data, collection, {
497
+ onUnknownSection: (section) => sanitizeByShape(section, core.sanitizeHtml),
498
+ })
499
+ const out: Record<string, unknown> = {}
500
+ for (const [key, value] of Object.entries(bySchema)) {
501
+ if (Object.hasOwn(fields, key) || key === 'sections') out[key] = value
502
+ else if (key === '_layout') out[key] = core.sanitizeLayoutTree(value)
503
+ else out[key] = sanitizeByShape(value, core.sanitizeHtml)
504
+ }
505
+ return out
506
+ }
507
+
508
+ /**
509
+ * Register the project's `prenta.config.ts` so the seed can sanitise by field
510
+ * type. A project without a loadable config still seeds; it falls back to the
511
+ * shape-based pass, and says so.
512
+ */
513
+ async function loadSeedConfig(configPath = 'prenta.config.ts'): Promise<void> {
514
+ try {
515
+ const { getPrentaConfig, setPrentaConfig } = await import('@prenta/core')
516
+ if (getPrentaConfig()) return
517
+ if (!existsSync(configPath)) return
518
+ const mod = (await importProjectTypescript(path.resolve(configPath))) as {
519
+ default?: unknown
520
+ config?: unknown
521
+ }
522
+ const config = projectDefaultExport(mod, 'config')
523
+ if (config && typeof config === 'object') setPrentaConfig(config as never)
524
+ } catch (err) {
525
+ const message = err instanceof Error ? err.message : String(err)
526
+ logger.warn(
527
+ `Could not load ${configPath} (${message}). Field types are unknown, so every seed string that looks like HTML will be sanitised, including Markdown in plain-text fields.`,
528
+ )
529
+ }
530
+ }
531
+
444
532
  export async function createSeedDocument(
445
533
  db: any,
446
534
  userId: string,
447
535
  doc: NormalizedSeedDocument,
448
536
  options: { upsert?: boolean } = {},
449
537
  ): Promise<'created' | 'updated'> {
450
- const { extractPlainText, hashContent, sanitizeHtml } = await import('@prenta/core')
451
- const data = sanitizeSeedData(doc.data, sanitizeHtml) as Record<string, unknown>
538
+ const core = await import('@prenta/core')
539
+ const { extractPlainText, hashContent } = core
540
+ const data = sanitizeSeedDocumentData(doc.data, doc.collection, core as SeedSanitizers)
452
541
  const serialized = JSON.stringify(data)
453
542
  const plainText = extractPlainText(serialized)
454
543
  const contentHash = await hashContent(serialized)
@@ -15,18 +15,70 @@ export function toProjectFileUrl(filePath: string): string {
15
15
  return pathToFileURL(path.resolve(filePath)).href
16
16
  }
17
17
 
18
+ /**
19
+ * Install tsx's process-wide hooks once: the ESM loader and the CommonJS
20
+ * `require` hook.
21
+ *
22
+ * Both are needed. A scaffolded project has no `"type": "module"`, so Node
23
+ * classifies its `.ts` files as CommonJS. The ESM loader compiles the entry
24
+ * file (`generated/prisma/client.ts`), but that file's own imports then run as
25
+ * `require('./internal/class')`, and on Node 22 only the CommonJS hook can
26
+ * resolve an extensionless TypeScript sibling. Without it every command that
27
+ * opens the project database fails with "Cannot find module './internal/class'".
28
+ */
29
+ async function registerTsx(): Promise<void> {
30
+ if (registered) return
31
+ const [esm, cjs] = await Promise.all([import('tsx/esm/api'), import('tsx/cjs/api')])
32
+ esm.register()
33
+ cjs.register()
34
+ registered = true
35
+ }
36
+
37
+ /**
38
+ * The exports a loaded project module actually declared.
39
+ *
40
+ * A scaffolded project has no `"type": "module"`, so tsx compiles its
41
+ * TypeScript to CommonJS: `export default config` and `export const header`
42
+ * become `module.exports = { __esModule: true, default: config, header }`.
43
+ * Imported from this ESM CLI, that whole object arrives as the namespace's
44
+ * `default`, one level above what the file exported. Reading the namespace
45
+ * directly therefore finds `{ default: config }` where the config should be
46
+ * (an object with no collections, plugins or storage) and no named exports at
47
+ * all, so every command that loaded `prenta.config.ts` ran as if it were empty.
48
+ */
49
+ export function projectModuleExports(mod: unknown): Record<string, unknown> {
50
+ if (!mod || typeof mod !== 'object') return {}
51
+ const namespace = mod as Record<string, unknown>
52
+ const outer = namespace.default
53
+ if (
54
+ outer &&
55
+ typeof outer === 'object' &&
56
+ !Array.isArray(outer) &&
57
+ (outer as Record<string, unknown>).__esModule === true
58
+ ) {
59
+ return outer as Record<string, unknown>
60
+ }
61
+ return namespace
62
+ }
63
+
64
+ /**
65
+ * The default export of a loaded project module, or the named export
66
+ * `fallbackName` when the file has no default.
67
+ */
68
+ export function projectDefaultExport(mod: unknown, fallbackName?: string): unknown {
69
+ const exported = projectModuleExports(mod)
70
+ if (exported.default !== undefined) return exported.default
71
+ return fallbackName ? exported[fallbackName] : undefined
72
+ }
73
+
18
74
  /**
19
75
  * Load a consumer TypeScript file (prenta.config.ts, lib/prisma.ts,
20
- * generated/prisma/client.ts) via tsx's process-wide ESM hook.
76
+ * generated/prisma/client.ts) via tsx's process-wide hooks.
21
77
  *
22
78
  * Do not use `tsImport()` — its namespaced loader is what produced the
23
79
  * Windows `?namespace=` crashes on adapter-pg and then enums.ts.
24
80
  */
25
81
  export async function importProjectTypescript(filePath: string): Promise<unknown> {
26
- if (!registered) {
27
- const { register } = await import('tsx/esm/api')
28
- register()
29
- registered = true
30
- }
82
+ await registerTsx()
31
83
  return import(toProjectFileUrl(filePath))
32
84
  }
@@ -1,5 +1,5 @@
1
1
  import { resolve } from 'node:path'
2
- import { importProjectTypescript } from './import-typescript.js'
2
+ import { importProjectTypescript, projectDefaultExport } from './import-typescript.js'
3
3
  import { logger } from './logger.js'
4
4
 
5
5
  /**
@@ -15,7 +15,7 @@ export async function loadProjectConfig(configPath: string): Promise<void> {
15
15
  default?: unknown
16
16
  config?: unknown
17
17
  }
18
- const config = mod.default ?? mod.config
18
+ const config = projectDefaultExport(mod, 'config')
19
19
  if (!config || typeof config !== 'object') return
20
20
  setPrentaConfig(config as never)
21
21