contentbit 0.4.1 → 0.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.
Files changed (38) hide show
  1. package/README.md +7 -2
  2. package/dist/bin.js +1609 -1616
  3. package/dist/cli-format.d.ts +17 -0
  4. package/dist/cli-format.d.ts.map +1 -0
  5. package/dist/cli-format.js +63 -0
  6. package/dist/commands/agents.d.ts.map +1 -1
  7. package/dist/commands/agents.js +9 -188
  8. package/dist/commands/docs.d.ts.map +1 -1
  9. package/dist/commands/docs.js +4 -1
  10. package/dist/commands/doctor.d.ts.map +1 -1
  11. package/dist/commands/doctor.js +80 -146
  12. package/dist/commands/init-targets.d.ts +27 -0
  13. package/dist/commands/init-targets.d.ts.map +1 -0
  14. package/dist/commands/init-targets.js +280 -0
  15. package/dist/commands/init.d.ts.map +1 -1
  16. package/dist/commands/init.js +26 -313
  17. package/dist/commands/instructions.d.ts.map +1 -1
  18. package/dist/commands/instructions.js +4 -1
  19. package/dist/commands/links.d.ts.map +1 -1
  20. package/dist/commands/links.js +18 -14
  21. package/dist/commands/render.d.ts.map +1 -1
  22. package/dist/commands/render.js +17 -10
  23. package/dist/commands/stats.d.ts.map +1 -1
  24. package/dist/commands/stats.js +33 -34
  25. package/dist/commands/studio.d.ts.map +1 -1
  26. package/dist/commands/studio.js +14 -12
  27. package/dist/commands/validate.d.ts.map +1 -1
  28. package/dist/commands/validate.js +39 -41
  29. package/dist/content-project.d.ts +32 -0
  30. package/dist/content-project.d.ts.map +1 -0
  31. package/dist/content-project.js +34 -0
  32. package/dist/load-registry.d.ts +4 -1
  33. package/dist/load-registry.d.ts.map +1 -1
  34. package/dist/load-registry.js +4 -2
  35. package/dist/run.d.ts +10 -1
  36. package/dist/run.d.ts.map +1 -1
  37. package/dist/run.js +1613 -1618
  38. package/package.json +4 -5
@@ -5,22 +5,15 @@ import { join } from 'node:path';
5
5
  import { parseArgs } from 'node:util';
6
6
  import { loadRegistry } from '../load-registry.js';
7
7
  import { installAgentIntegration } from './agents.js';
8
- const TARGETS = ['react', 'html', 'markdown', 'astro'];
9
- /** Markdown library choices per target; the first entry is the default. */
10
- const MD_CHOICES = {
11
- react: ['react-markdown', 'none'],
12
- html: ['marked', 'markdown-it', 'none'],
13
- markdown: ['none'],
14
- // @contentbit/astro ships its own marked-based default; nothing to install.
15
- astro: ['none'],
16
- };
8
+ import { detectTarget, TARGET_ADAPTERS, TARGETS } from './init-targets.js';
17
9
  const REGISTRY_TEMPLATE = `// Custom block definitions for this project. The CLI and your app share
18
10
  // this module — Node 22.18+ imports TypeScript directly:
19
11
  //
20
12
  // contentbit validate "content/**/*.md" --registry ./blocks/registry.ts
21
13
  //
22
14
  // Definitions stay framework-free (the CLI and every render target use
23
- // them); React components live next door in blocks/components.tsx.
15
+ // them); render components live next door in blocks/components.tsx or
16
+ // framework-specific component files copied from the shadcn registry.
24
17
  // Docs: https://contentbit.dev/docs/guides/custom-blocks
25
18
  import { defineBlock, markdownBody, type BlockDefinition } from '@contentbit/core'
26
19
  import { z } from 'zod'
@@ -42,42 +35,6 @@ export const quote = defineBlock({
42
35
 
43
36
  export default [quote] satisfies BlockDefinition<unknown>[]
44
37
  `;
45
- /** blocks/components.tsx — React components for custom blocks, next to their definitions. */
46
- function blockComponentsTemplate(styled) {
47
- const body = styled
48
- ? ` return (
49
- <figure className="my-6 border-s-2 ps-4">
50
- <blockquote className="text-lg italic">{ctx.renderMarkdown(data.markdown)}</blockquote>
51
- <figcaption className="text-muted-foreground mt-2 text-sm">
52
- — {String(node.props.author)}
53
- {node.props.role ? \`, \${String(node.props.role)}\` : null}
54
- </figcaption>
55
- </figure>
56
- )`
57
- : ` return (
58
- <figure style={{ margin: '1.5rem 0', borderLeft: '2px solid #d4d4d4', paddingLeft: '1rem' }}>
59
- <blockquote style={{ fontStyle: 'italic' }}>{ctx.renderMarkdown(data.markdown)}</blockquote>
60
- <figcaption style={{ marginTop: '0.5rem', fontSize: '0.875rem', opacity: 0.7 }}>
61
- — {String(node.props.author)}
62
- {node.props.role ? \`, \${String(node.props.role)}\` : null}
63
- </figcaption>
64
- </figure>
65
- )`;
66
- return `import type { BlockComponent, BlockComponentProps } from '@contentbit/react'
67
-
68
- // One React component per custom block, keyed by block name. Definitions
69
- // live in ./registry.ts — add a block there, add its component here, and
70
- // the rest of the app never changes.
71
- function QuoteBlock({ node, ctx }: BlockComponentProps) {
72
- const data = node.data as { markdown: string }
73
- ${body}
74
- }
75
-
76
- export const blockComponents: Record<string, BlockComponent> = {
77
- quote: QuoteBlock,
78
- }
79
- `;
80
- }
81
38
  const EXAMPLE_CONTENT = `---
82
39
  slug: hello-content-blocks
83
40
  linksTo:
@@ -132,183 +89,6 @@ references in \`linksTo\` are rewritten to the current slug, while \`aliases\`
132
89
  stays as the rename record.
133
90
  :::
134
91
  `;
135
- /** The wrapper component: styled pack or headless, with or without a Markdown lib. */
136
- function reactComponent(styled, mdWired, blocksImport) {
137
- const mdImport = mdWired ? "import ReactMarkdown from 'react-markdown'\n" : '';
138
- const mdProp = mdWired
139
- ? '\n renderMarkdown={(md) => <ReactMarkdown>{md}</ReactMarkdown>}'
140
- : `\n // TODO: plug your Markdown library in here, e.g. react-markdown.
141
- // One function renders all prose: https://contentbit.dev/docs/guides/markdown
142
- // renderMarkdown={(md) => <Markdown source={md} />}`;
143
- const rendererImport = styled
144
- ? `\n// The styled pack installed by shadcn. Yours to edit.
145
- import { ContentRenderer } from '@/components/content-blocks/content-renderer'`
146
- : '';
147
- const renderer = styled ? 'ContentRenderer' : 'ContentBlocks';
148
- const reactImport = styled ? '' : "import { ContentBlocks } from '@contentbit/react'\n";
149
- return `'use client'
150
-
151
- import { genericBlocks } from '@contentbit/blocks'
152
- import { createBlockRegistry, parseDocument, stripFrontmatter, validateDocument } from '@contentbit/core'
153
- ${reactImport}${mdImport}${rendererImport}
154
- // Everything block-related lives in the blocks/ folder: definitions in
155
- // registry.ts (shared with the validate CLI), components in components.tsx.
156
- import customBlocks from '${blocksImport}/registry'
157
- import { blockComponents } from '${blocksImport}/components'
158
-
159
- const registry = createBlockRegistry().use(genericBlocks()).use(customBlocks)
160
-
161
- export function Content({ source }: { source: string }) {
162
- const result = validateDocument(parseDocument(stripFrontmatter(source)), registry)
163
- return (
164
- <${renderer}
165
- document={result.document}
166
- components={blockComponents}${mdProp}
167
- />
168
- )
169
- }
170
- `;
171
- }
172
- function htmlRenderScript(md) {
173
- const wiring = md === 'marked'
174
- ? `import { marked } from 'marked'
175
-
176
- const renderMarkdown = (md) => marked.parse(md, { async: false })`
177
- : md === 'markdown-it'
178
- ? `import MarkdownIt from 'markdown-it'
179
-
180
- const mdIt = new MarkdownIt() // html: false by default — raw HTML stays escaped
181
- const renderMarkdown = (md) => mdIt.render(md)`
182
- : `// TODO: plug a Markdown library in here (marked, markdown-it, remark).
183
- const renderMarkdown = undefined`;
184
- return `// Render content/example.md to example.html. Run: node scripts/render-example.mjs
185
- import { genericBlocks } from '@contentbit/blocks'
186
- import { createBlockRegistry, parseDocument, stripFrontmatter, validateDocument } from '@contentbit/core'
187
- import { renderToHtml } from '@contentbit/html'
188
- import { readFile, writeFile } from 'node:fs/promises'
189
- ${wiring}
190
-
191
- const source = await readFile('content/example.md', 'utf8')
192
- const registry = createBlockRegistry().use(genericBlocks())
193
- const result = validateDocument(parseDocument(stripFrontmatter(source)), registry)
194
- const html = renderToHtml(result.document, { renderMarkdown })
195
- await writeFile('example.html', html, 'utf8')
196
- console.log('wrote example.html')
197
- `;
198
- }
199
- /** Where the component and example page belong for the detected framework. */
200
- function detectFramework(cwd, deps) {
201
- if ((deps['@tanstack/react-start'] || deps['@tanstack/react-router']) &&
202
- existsSync(join(cwd, 'src/routes'))) {
203
- return {
204
- framework: 'tanstack',
205
- componentPath: 'src/components/content-blocks.tsx',
206
- pagePath: 'src/routes/example.tsx',
207
- };
208
- }
209
- if (deps.next) {
210
- const appDir = existsSync(join(cwd, 'src/app')) ? 'src/app' : 'app';
211
- if (existsSync(join(cwd, appDir))) {
212
- return {
213
- framework: 'next',
214
- componentPath: 'components/content-blocks.tsx',
215
- pagePath: `${appDir}/example/page.tsx`,
216
- };
217
- }
218
- }
219
- return { framework: null, componentPath: 'components/content-blocks.tsx', pagePath: null };
220
- }
221
- const TANSTACK_PAGE = `import { createFileRoute } from '@tanstack/react-router'
222
-
223
- import { Content } from '../components/content-blocks'
224
- // Vite's ?raw import inlines the Markdown as a string at build time.
225
- import source from '../../content/example.md?raw'
226
-
227
- export const Route = createFileRoute('/example')({ component: ExamplePage })
228
-
229
- function ExamplePage() {
230
- return (
231
- <main style={{ maxWidth: '42rem', margin: '0 auto', padding: '3rem 1.5rem' }}>
232
- <Content source={source} />
233
- </main>
234
- )
235
- }
236
- `;
237
- const NEXT_PAGE = `import { readFile } from 'node:fs/promises'
238
-
239
- // If your project has no "@/" path alias, switch to a relative import.
240
- import { Content } from '@/components/content-blocks'
241
-
242
- export default async function ExamplePage() {
243
- const source = await readFile('content/example.md', 'utf8')
244
- return (
245
- <main style={{ maxWidth: '42rem', margin: '0 auto', padding: '3rem 1.5rem' }}>
246
- <Content source={source} />
247
- </main>
248
- )
249
- }
250
- `;
251
- const ASTRO_CONTENT_CONFIG = `import { defineCollection } from 'astro:content'
252
- import { glob } from 'astro/loaders'
253
-
254
- export const collections = {
255
- articles: defineCollection({
256
- // Astro's builtin Markdown loader. Entry bodies are parsed and validated
257
- // where they render (see src/pages/example.astro); \`contentbit validate\`
258
- // covers the same files in CI.
259
- loader: glob({ pattern: '**/*.md', base: './content' }),
260
- }),
261
- }
262
- `;
263
- const ASTRO_QUOTE_BLOCK = `---
264
- // The Astro component for the custom \`quote\` block defined in blocks/registry.ts.
265
- // Block props arrive as component props; nested content arrives via <slot />.
266
- interface Props {
267
- author: string
268
- role?: string
269
- }
270
-
271
- const { author, role } = Astro.props
272
- ---
273
-
274
- <figure style="margin: 1.5rem 0; border-left: 2px solid #d4d4d4; padding-left: 1rem;">
275
- <blockquote style="font-style: italic;"><slot /></blockquote>
276
- <figcaption style="margin-top: 0.5rem; font-size: 0.875rem; opacity: 0.7;">
277
- — {author}{role ? \`, \${role}\` : null}
278
- </figcaption>
279
- </figure>
280
- `;
281
- /** The example page: styled pack renderer or the headless ContentBlocks. */
282
- function astroPage(styled) {
283
- const importLine = styled
284
- ? "import ContentRenderer from '../components/content-blocks/content-renderer.astro'"
285
- : "import { ContentBlocks } from '@contentbit/astro/components'";
286
- const renderer = styled ? 'ContentRenderer' : 'ContentBlocks';
287
- return `---
288
- import { genericBlocks } from '@contentbit/blocks'
289
- import { createBlockRegistry, parseDocument, validateDocument } from '@contentbit/core'
290
- import { getEntry } from 'astro:content'
291
-
292
- ${importLine}
293
-
294
- // Definitions in blocks/registry.ts are shared with the validate CLI.
295
- import customBlocks from '../../blocks/registry'
296
- import QuoteBlock from '../../blocks/QuoteBlock.astro'
297
-
298
- // Entry ids are the file path relative to the collection base, minus ".md".
299
- const entry = await getEntry('articles', 'example')
300
- if (!entry?.body) throw new Error('Entry "example" not found in the articles collection.')
301
-
302
- const registry = createBlockRegistry().use(genericBlocks()).use(customBlocks)
303
- // Static pages render at build time, so invalid blocks fail the build here.
304
- const result = validateDocument(parseDocument(entry.body), registry)
305
- ---
306
-
307
- <main style="max-width: 42rem; margin: 0 auto; padding: 3rem 1.5rem;">
308
- <${renderer} document={result.document} components={{ quote: QuoteBlock }} />
309
- </main>
310
- `;
311
- }
312
92
  function detectPackageManager(cwd) {
313
93
  // The project's lockfile outranks however the CLI itself was launched.
314
94
  const locks = [
@@ -367,7 +147,7 @@ async function installStyledPack(cwd, pack, noInstall, io) {
367
147
  io.stdout(`installing the styled pack: shadcn add ${pack}`);
368
148
  const code = await runInstall(bin, [...prefix, 'shadcn@latest', 'add', pack, '--yes'], cwd);
369
149
  if (code !== 0)
370
- io.stderr('styled pack install failed; falling back to headless defaults');
150
+ io.stderr('styled pack install failed; falling back to the headless renderer');
371
151
  return code === 0;
372
152
  }
373
153
  /** Write a file unless it already exists; returns what happened for the summary. */
@@ -407,10 +187,9 @@ export async function initCommand(args, io) {
407
187
  io.stderr('No package.json found. Run this inside a project (npm init first).');
408
188
  return 1;
409
189
  }
190
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies };
410
191
  // Resolve the render target: flag > prompt (interactive) > detection.
411
- const hasReact = Boolean(pkg.dependencies?.react ?? pkg.devDependencies?.react);
412
- const hasAstro = Boolean(pkg.dependencies?.astro ?? pkg.devDependencies?.astro);
413
- const detected = hasAstro ? 'astro' : hasReact ? 'react' : 'html';
192
+ const detected = detectTarget(deps);
414
193
  let target;
415
194
  if (values.target) {
416
195
  if (!TARGETS.includes(values.target)) {
@@ -427,7 +206,6 @@ export async function initCommand(args, io) {
427
206
  options: [
428
207
  { value: 'react', label: 'React', hint: 'ContentBlocks component' },
429
208
  { value: 'astro', label: 'Astro', hint: 'content collections + .astro components' },
430
- { value: 'html', label: 'Static HTML', hint: 'renderToHtml, no framework' },
431
209
  { value: 'markdown', label: 'Plain Markdown', hint: 'fallback rendering only' },
432
210
  ],
433
211
  });
@@ -438,9 +216,10 @@ export async function initCommand(args, io) {
438
216
  else {
439
217
  target = detected;
440
218
  }
219
+ const adapter = TARGET_ADAPTERS[target];
441
220
  // Resolve the Markdown library: flag > prompt (interactive) > target default.
442
221
  // The default gives working prose rendering out of the box; 'none' opts out.
443
- const choices = MD_CHOICES[target];
222
+ const choices = adapter.markdownChoices;
444
223
  let md;
445
224
  if (values.md) {
446
225
  if (!choices.includes(values.md)) {
@@ -468,15 +247,7 @@ export async function initCommand(args, io) {
468
247
  md = choices[0];
469
248
  }
470
249
  // Install runtime packages plus the CLI as a dev dependency.
471
- const runtime = ['@contentbit/core', '@contentbit/blocks', 'zod'];
472
- if (target === 'react')
473
- runtime.push('@contentbit/react');
474
- if (target === 'html')
475
- runtime.push('@contentbit/html');
476
- if (target === 'astro')
477
- runtime.push('@contentbit/astro');
478
- if (md !== 'none')
479
- runtime.push(md);
250
+ const runtime = adapter.runtimeDependencies(md);
480
251
  if (values['no-install']) {
481
252
  io.stdout(`skipped install: ${runtime.join(' ')} + contentbit (dev)`);
482
253
  }
@@ -492,63 +263,22 @@ export async function initCommand(args, io) {
492
263
  return 1;
493
264
  }
494
265
  }
266
+ const plan = await adapter.createPlan({
267
+ cwd,
268
+ deps,
269
+ md,
270
+ noPage: Boolean(values['no-page']),
271
+ noStyled: Boolean(values['no-styled']),
272
+ io,
273
+ installStyledPack: (pack) => installStyledPack(cwd, pack, values['no-install'], io),
274
+ });
495
275
  // Scaffold project files; never overwrite.
496
276
  const files = [
497
277
  ['blocks/registry.ts', REGISTRY_TEMPLATE],
498
278
  ['content/example.md', EXAMPLE_CONTENT],
499
279
  ['content/related.md', RELATED_CONTENT],
280
+ ...plan.files,
500
281
  ];
501
- const layout = detectFramework(cwd, { ...pkg.dependencies, ...pkg.devDependencies });
502
- // shadcn project? Pull the styled component pack from the contentbit registry.
503
- let styled = false;
504
- const componentsJsonPath = join(cwd, 'components.json');
505
- if (target === 'react' && !values['no-styled'] && existsSync(componentsJsonPath)) {
506
- styled = await installStyledPack(cwd, '@contentbit/generic-pack', values['no-install'], io);
507
- }
508
- if (target === 'react') {
509
- const depth = layout.componentPath.split('/').length - 1;
510
- const blocksImport = `${'../'.repeat(depth)}blocks`;
511
- files.push(['blocks/components.tsx', blockComponentsTemplate(styled)]);
512
- files.push([
513
- layout.componentPath,
514
- reactComponent(styled, md === 'react-markdown', blocksImport),
515
- ]);
516
- // A visible page in the framework's own routing convention.
517
- if (!values['no-page'] && layout.pagePath) {
518
- files.push([layout.pagePath, layout.framework === 'tanstack' ? TANSTACK_PAGE : NEXT_PAGE]);
519
- }
520
- }
521
- if (target === 'html') {
522
- files.push([
523
- 'scripts/render-example.mjs',
524
- htmlRenderScript(md),
525
- ]);
526
- }
527
- if (target === 'astro') {
528
- let astroStyled = false;
529
- if (!values['no-styled'] && existsSync(componentsJsonPath)) {
530
- astroStyled = await installStyledPack(cwd, '@contentbit/astro-pack', values['no-install'], io);
531
- }
532
- files.push(['blocks/QuoteBlock.astro', ASTRO_QUOTE_BLOCK]);
533
- // Every config filename Astro resolves (src/content.config.* plus the
534
- // legacy src/content/config.* location), so we never scaffold a second
535
- // config that Astro would silently ignore.
536
- const configCandidates = ['ts', 'mts', 'mjs', 'js'].flatMap((ext) => [
537
- `src/content.config.${ext}`,
538
- `src/content/config.${ext}`,
539
- ]);
540
- const existingConfig = configCandidates.find((p) => existsSync(join(cwd, p)));
541
- if (existingConfig) {
542
- io.stdout(`content config exists (${existingConfig}); add this collection manually:`);
543
- io.stdout(ASTRO_CONTENT_CONFIG);
544
- io.stdout('the example page expects the "articles" collection above');
545
- }
546
- else {
547
- files.push(['src/content.config.ts', ASTRO_CONTENT_CONFIG]);
548
- }
549
- if (!values['no-page'])
550
- files.push(['src/pages/example.astro', astroPage(astroStyled)]);
551
- }
552
282
  for (const [rel, content] of files) {
553
283
  const result = await scaffold(join(cwd, rel), content);
554
284
  io.stdout(`${result}: ${rel}`);
@@ -601,30 +331,13 @@ export async function initCommand(args, io) {
601
331
  }
602
332
  io.stdout('');
603
333
  io.stdout('Done. Next steps:');
604
- io.stdout(` 1. Browse content locally: ${detectPackageManager(cwd)} run studio`);
605
- io.stdout(` Inspect content health: ${detectPackageManager(cwd)} run content:doctor`);
606
- io.stdout(` Validate the starter content: ${detectPackageManager(cwd)} run content:check`);
607
- io.stdout(` Build the link index: ${detectPackageManager(cwd)} run content:links`);
608
- if (target === 'react') {
609
- if (!values['no-page'] && layout.pagePath) {
610
- io.stdout(' 2. Start the dev server and open /example to see the article rendered.');
611
- }
612
- else {
613
- io.stdout(' 2. Render it: import { Content } from "./components/content-blocks"');
614
- io.stdout(' <Content source={...content/example.md as a string} />');
615
- }
616
- io.stdout(' 3. Styled components: pnpm dlx shadcn@latest add @contentbit/generic-pack');
617
- }
618
- else if (target === 'astro') {
619
- io.stdout(' 2. Start the dev server and open /example to see the article rendered.');
620
- io.stdout(' 3. Styled components: pnpm dlx shadcn@latest add @contentbit/astro-pack');
621
- }
622
- else if (target === 'html') {
623
- io.stdout(' 2. Render it: node scripts/render-example.mjs && open example.html');
624
- }
625
- else {
626
- io.stdout(' 2. Render it: contentbit render content/example.md --target markdown');
627
- }
334
+ const pm = detectPackageManager(cwd);
335
+ io.stdout(` 1. Browse content locally: ${pm} run studio`);
336
+ io.stdout(` Inspect content health: ${pm} run content:doctor`);
337
+ io.stdout(` Validate the starter content: ${pm} run content:check`);
338
+ io.stdout(` Build the link index: ${pm} run content:links`);
339
+ for (const line of plan.nextSteps)
340
+ io.stdout(line);
628
341
  io.stdout(' Docs: https://contentbit.dev/docs');
629
342
  return 0;
630
343
  }
@@ -1 +1 @@
1
- {"version":3,"file":"instructions.d.ts","sourceRoot":"","sources":["../../src/commands/instructions.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,WAAW,CAAA;AAInC,wBAAsB,mBAAmB,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAkBjF"}
1
+ {"version":3,"file":"instructions.d.ts","sourceRoot":"","sources":["../../src/commands/instructions.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,WAAW,CAAA;AAInC,wBAAsB,mBAAmB,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAqBjF"}
@@ -7,10 +7,13 @@ export async function instructionsCommand(args, io) {
7
7
  audience: { type: 'string', default: 'llm' },
8
8
  'no-examples': { type: 'boolean', default: false },
9
9
  registry: { type: 'string' },
10
+ 'no-generic-blocks': { type: 'boolean', default: false },
10
11
  out: { type: 'string' },
11
12
  },
12
13
  });
13
- const registry = await loadRegistry(values.registry);
14
+ const registry = await loadRegistry(values.registry, {
15
+ includeGenericBlocks: !values['no-generic-blocks'],
16
+ });
14
17
  const guide = registry.toAuthoringGuide({
15
18
  audience: values.audience === 'human' ? 'human' : 'llm',
16
19
  includeExamples: !values['no-examples'],
@@ -1 +1 @@
1
- {"version":3,"file":"links.d.ts","sourceRoot":"","sources":["../../src/commands/links.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,WAAW,CAAA;AAKnC,wBAAsB,YAAY,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAuF1E"}
1
+ {"version":3,"file":"links.d.ts","sourceRoot":"","sources":["../../src/commands/links.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,WAAW,CAAA;AAOnC,wBAAsB,YAAY,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CA0F1E"}
@@ -1,8 +1,9 @@
1
- import { aliasReplacementsForPage, buildLinkIndex, extractFrontmatter, formatDiagnostic, serializeLinkIndex, validateLinks, } from '@contentbit/core';
1
+ import { aliasReplacementsForPage, buildLinkIndex, extractFrontmatter, serializeLinkIndex, validateLinks, } from '@contentbit/core';
2
2
  import { mkdir, readFile } from 'node:fs/promises';
3
3
  import { dirname, join } from 'node:path';
4
4
  import { parseArgs } from 'node:util';
5
- import { glob } from 'tinyglobby';
5
+ import { formatDiagnosticForCli, formatRows, section } from '../cli-format.js';
6
+ import { resolveContentFiles } from '../content-project.js';
6
7
  import { linkResolverOptions } from '../link-options.js';
7
8
  import { collectLinkInputs } from '../links-io.js';
8
9
  export async function linksCommand(args, io) {
@@ -19,21 +20,13 @@ export async function linksCommand(args, io) {
19
20
  'default-locale': { type: 'string' },
20
21
  },
21
22
  });
22
- if (positionals.length === 0) {
23
- io.stderr('links: provide at least one file or glob.');
24
- return 2;
25
- }
26
- const files = (await glob(positionals, { absolute: true })).sort();
27
- if (files.length === 0) {
28
- io.stderr(`links: no files matched ${positionals.join(' ')}`);
29
- return 2;
30
- }
23
+ const files = await resolveContentFiles(positionals, 'links');
31
24
  const inputs = await collectLinkInputs(files);
32
25
  const linkOptions = linkResolverOptions(values);
33
26
  let errors = 0;
34
27
  let warnings = 0;
35
28
  for (const { file, diagnostic } of validateLinks(inputs, linkOptions)) {
36
- io.stderr(formatDiagnostic(diagnostic, file));
29
+ io.stderr(formatDiagnosticForCli(diagnostic, file));
37
30
  if (diagnostic.severity === 'error')
38
31
  errors++;
39
32
  else if (diagnostic.severity === 'warning')
@@ -88,8 +81,19 @@ export async function linksCommand(args, io) {
88
81
  for (const p of index.pages.values())
89
82
  edges += p.linksTo.length;
90
83
  const orphans = [...index.pages.values()].filter((p) => p.linkedFrom.length === 0).length;
91
- io.stdout(`${index.pages.size} page(s), ${edges} link(s), ${orphans} orphan(s): ${errors} errors, ${warnings} warnings`);
92
- io.stdout(`index written to ${outPath}`);
84
+ io.stdout([
85
+ section('Link Index'),
86
+ ...formatRows([
87
+ { label: 'Pages', value: index.pages.size },
88
+ { label: 'Links', value: edges },
89
+ { label: 'Orphans', value: orphans, tone: orphans > 0 ? 'warning' : 'success' },
90
+ { label: 'Errors', value: errors, tone: errors > 0 ? 'error' : 'success' },
91
+ { label: 'Warnings', value: warnings, tone: warnings > 0 ? 'warning' : 'success' },
92
+ ]),
93
+ '',
94
+ section('Written'),
95
+ ` ${outPath}`,
96
+ ].join('\n'));
93
97
  return errors > 0 ? 1 : 0;
94
98
  }
95
99
  function escapeRe(s) {
@@ -1 +1 @@
1
- {"version":3,"file":"render.d.ts","sourceRoot":"","sources":["../../src/commands/render.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,WAAW,CAAA;AAInC,wBAAsB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CA6B3E"}
1
+ {"version":3,"file":"render.d.ts","sourceRoot":"","sources":["../../src/commands/render.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,WAAW,CAAA;AAKnC,wBAAsB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAiC3E"}
@@ -1,38 +1,45 @@
1
1
  import { genericMarkdownRenderers } from '@contentbit/blocks';
2
- import { formatDiagnostic, parseDocument, renderToMarkdown, stripFrontmatter, validateDocument, } from '@contentbit/core';
3
- import { renderToHtml } from '@contentbit/html';
2
+ import { parseDocument, renderToMarkdown, stripFrontmatter, validateDocument, } from '@contentbit/core';
4
3
  import { readFile } from 'node:fs/promises';
5
4
  import { parseArgs } from 'node:util';
5
+ import { formatDiagnosticForCli } from '../cli-format.js';
6
6
  import { loadRegistry } from '../load-registry.js';
7
7
  export async function renderCommand(args, io) {
8
8
  const { values, positionals } = parseArgs({
9
9
  args,
10
10
  allowPositionals: true,
11
11
  options: {
12
- target: { type: 'string', default: 'html' },
12
+ target: { type: 'string', default: 'markdown' },
13
13
  registry: { type: 'string' },
14
+ 'no-generic-blocks': { type: 'boolean', default: false },
14
15
  out: { type: 'string' },
15
16
  },
16
17
  });
17
18
  const file = positionals[0];
18
- if (!file || (values.target !== 'html' && values.target !== 'markdown')) {
19
- io.stderr('render: usage: render <file> --target html|markdown [--out <file>]');
19
+ if (!file || values.target !== 'markdown') {
20
+ io.stderr('render: usage: render <file> [--target markdown] ' +
21
+ '[--registry <module.ts>] [--no-generic-blocks] [--out <file>]');
20
22
  return 2;
21
23
  }
22
- const registry = await loadRegistry(values.registry);
24
+ const includeGenericBlocks = !values['no-generic-blocks'];
25
+ const registry = await loadRegistry(values.registry, { includeGenericBlocks });
23
26
  const source = await readFile(file, 'utf8');
24
27
  const result = validateDocument(parseDocument(stripFrontmatter(source)), registry);
25
28
  if (!result.ok) {
26
29
  for (const d of result.diagnostics)
27
- io.stderr(formatDiagnostic(d, file));
30
+ io.stderr(formatDiagnosticForCli(d, file));
28
31
  return 1;
29
32
  }
30
- const output = values.target === 'html'
31
- ? renderToHtml(result.document)
32
- : renderToMarkdown(result.document, { renderers: genericMarkdownRenderers });
33
+ const output = renderToMarkdown(result.document, {
34
+ renderers: includeGenericBlocks ? genericMarkdownRenderers : genericMarkdownFallbackRenderers,
35
+ });
33
36
  if (values.out)
34
37
  await io.writeFile(values.out, output);
35
38
  else
36
39
  io.stdout(output);
37
40
  return 0;
38
41
  }
42
+ const genericMarkdownFallbackRenderers = Object.fromEntries(Object.keys(genericMarkdownRenderers).map((name) => [
43
+ name,
44
+ ((node) => `${node.body}\n`),
45
+ ]));
@@ -1 +1 @@
1
- {"version":3,"file":"stats.d.ts","sourceRoot":"","sources":["../../src/commands/stats.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,WAAW,CAAA;AAuBnC,wBAAsB,YAAY,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CA2B1E"}
1
+ {"version":3,"file":"stats.d.ts","sourceRoot":"","sources":["../../src/commands/stats.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,WAAW,CAAA;AAOnC,wBAAsB,YAAY,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAkB1E"}
@@ -1,49 +1,48 @@
1
- import { analyzeDocument, parseDocument, stripFrontmatter, validateDocument, } from '@contentbit/core';
1
+ import { analyzeDocument } from '@contentbit/core';
2
2
  import { readFile } from 'node:fs/promises';
3
3
  import { parseArgs } from 'node:util';
4
- import { glob } from 'tinyglobby';
5
- import { loadRegistry } from '../load-registry.js';
6
- async function fileStats(file, registry) {
7
- const source = await readFile(file, 'utf8');
8
- const stats = analyzeDocument(source, { path: file });
9
- if (registry) {
10
- const result = validateDocument(parseDocument(stripFrontmatter(source)), registry);
11
- let errors = 0;
12
- let warnings = 0;
13
- for (const d of result.diagnostics) {
14
- if (d.severity === 'error')
15
- errors++;
16
- else if (d.severity === 'warning')
17
- warnings++;
18
- }
19
- stats.validation = { errors, warnings };
20
- }
21
- return stats;
22
- }
4
+ import { loadContentProject, resolveContentFiles } from '../content-project.js';
23
5
  export async function statsCommand(args, io) {
24
6
  const { values, positionals } = parseArgs({
25
7
  args,
26
8
  allowPositionals: true,
27
9
  options: {
28
10
  registry: { type: 'string' },
11
+ 'no-generic-blocks': { type: 'boolean', default: false },
29
12
  'no-validate': { type: 'boolean', default: false },
30
13
  },
31
14
  });
32
- if (positionals.length === 0) {
33
- io.stderr('stats: provide at least one file or glob.');
34
- return 2;
35
- }
36
- const files = await glob(positionals, { absolute: true });
37
- if (files.length === 0) {
38
- io.stderr(`stats: no files matched ${positionals.join(' ')}`);
39
- return 2;
40
- }
41
- const registry = values['no-validate'] ? null : await loadRegistry(values.registry);
42
- const all = [];
43
- for (const file of files.sort()) {
44
- all.push(await fileStats(file, registry));
45
- }
15
+ const all = values['no-validate']
16
+ ? await statsOnly(positionals)
17
+ : await statsWithValidation(values, positionals);
46
18
  // A single file keeps the flat object shape; multiple files emit an array.
47
19
  io.stdout(JSON.stringify(all.length === 1 ? all[0] : all, null, 2));
48
20
  return 0;
49
21
  }
22
+ /** Default path: cross the loaded-content-project seam so stats and the other
23
+ * read-commands share one validation path. */
24
+ async function statsWithValidation(values, positionals) {
25
+ const { scan } = await loadContentProject({
26
+ cmd: 'stats',
27
+ positionals,
28
+ registry: values.registry,
29
+ includeGenericBlocks: !values['no-generic-blocks'],
30
+ linkOptions: {},
31
+ });
32
+ return scan.files.map((file) => {
33
+ let errors = 0;
34
+ let warnings = 0;
35
+ for (const d of file.validation.diagnostics) {
36
+ if (d.severity === 'error')
37
+ errors++;
38
+ else if (d.severity === 'warning')
39
+ warnings++;
40
+ }
41
+ return { ...file.stats, validation: { errors, warnings } };
42
+ });
43
+ }
44
+ /** `--no-validate`: stats only, no registry, no scan. */
45
+ async function statsOnly(positionals) {
46
+ const files = await resolveContentFiles(positionals, 'stats');
47
+ return Promise.all(files.map(async (file) => analyzeDocument(await readFile(file, 'utf8'), { path: file })));
48
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"studio.d.ts","sourceRoot":"","sources":["../../src/commands/studio.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,WAAW,CAAA;AAInC,wBAAsB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAiE3E"}
1
+ {"version":3,"file":"studio.d.ts","sourceRoot":"","sources":["../../src/commands/studio.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,WAAW,CAAA;AAMnC,wBAAsB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAmE3E"}