@contentbit/studio 0.4.0 → 0.4.2

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 (35) hide show
  1. package/LICENSE +21 -0
  2. package/components.json +25 -0
  3. package/dist/client/assets/{api-C-Xwc2aB.js → api-MWiK2l_P.js} +1 -1
  4. package/dist/client/assets/{document-Yk8nlK-k.js → document-w62o-wDp.js} +1 -1
  5. package/dist/client/assets/{index-BwvfKCmy.js → index-DTXIZgkK.js} +2 -2
  6. package/dist/client/assets/{routes-DHIbdBYB.js → routes-Dg9spe-7.js} +1 -1
  7. package/dist/client/assets/{styles-BGHadX26.css → styles-DxZJz8Oi.css} +1 -1
  8. package/dist/server/assets/_tanstack-start-manifest_v-wPlN1Hjy.js +25 -0
  9. package/dist/server/assets/{router-D3JhQdql.js → router-D4DnWGjU.js} +1 -1
  10. package/dist/server/index.d.ts.map +1 -1
  11. package/dist/server/index.js +13 -2
  12. package/dist/server/server.js +2 -2
  13. package/package.json +23 -18
  14. package/public/favicon.ico +0 -0
  15. package/public/manifest.json +25 -0
  16. package/public/robots.txt +3 -0
  17. package/src/components/ui/button.tsx +67 -0
  18. package/src/lib/api.ts +22 -0
  19. package/src/lib/utils.ts +6 -0
  20. package/src/logo.svg +12 -0
  21. package/src/routeTree.gen.ts +86 -0
  22. package/src/router.tsx +20 -0
  23. package/src/routes/__root.tsx +48 -0
  24. package/src/routes/document.tsx +268 -0
  25. package/src/routes/index.tsx +465 -0
  26. package/src/server/api.ts +58 -0
  27. package/src/server/index.ts +151 -0
  28. package/src/server/preview.ts +46 -0
  29. package/src/server/scan.test.ts +283 -0
  30. package/src/server/scan.ts +460 -0
  31. package/src/server/types.ts +109 -0
  32. package/src/styles.css +222 -0
  33. package/tsconfig.json +27 -0
  34. package/vite.config.ts +16 -0
  35. package/dist/server/assets/_tanstack-start-manifest_v-Djlrg1a7.js +0 -25
@@ -0,0 +1,46 @@
1
+ import type { BlockComponent } from '@contentbit/react'
2
+ import type { DocumentNode } from '@contentbit/core'
3
+ import type { ComponentType } from 'react'
4
+
5
+ import { ContentBlocks } from '@contentbit/react'
6
+ import { createElement } from 'react'
7
+ import { renderToStaticMarkup } from 'react-dom/server'
8
+ import ReactMarkdown from 'react-markdown'
9
+ import remarkGfm from 'remark-gfm'
10
+
11
+ interface FallbackProps {
12
+ name: string
13
+ body: string
14
+ }
15
+
16
+ export function renderStudioPreview(
17
+ document: DocumentNode,
18
+ components: Record<string, BlockComponent> = {},
19
+ ): string {
20
+ return renderToStaticMarkup(
21
+ createElement(ContentBlocks, {
22
+ document,
23
+ components,
24
+ renderMarkdown,
25
+ fallback: CustomBlockFallback,
26
+ }),
27
+ )
28
+ }
29
+
30
+ function renderMarkdown(markdown: string) {
31
+ return createElement(ReactMarkdown, { remarkPlugins: [remarkGfm] }, markdown)
32
+ }
33
+
34
+ const CustomBlockFallback: ComponentType<FallbackProps> = ({ name, body }) =>
35
+ createElement(
36
+ 'section',
37
+ { className: 'cb-custom-block', 'data-cb-custom': name },
38
+ createElement('div', { className: 'cb-custom-block-label' }, name),
39
+ createElement(
40
+ 'div',
41
+ { className: 'cb-custom-block-body' },
42
+ body.trim().length > 0
43
+ ? renderMarkdown(body)
44
+ : createElement('p', null, 'No preview component for this custom block yet.'),
45
+ ),
46
+ )
@@ -0,0 +1,283 @@
1
+ import { mkdir, mkdtemp, symlink, writeFile } from 'node:fs/promises'
2
+ import { tmpdir } from 'node:os'
3
+ import { dirname, join } from 'node:path'
4
+ import { fileURLToPath } from 'node:url'
5
+ import { afterEach, expect, test } from 'vitest'
6
+
7
+ import { scanDocument, scanGraph, scanProject } from './scan'
8
+ import { startStudio, type StudioServer } from './index'
9
+
10
+ const root = fileURLToPath(new URL('../../../..', import.meta.url))
11
+ const runningServers: StudioServer[] = []
12
+
13
+ afterEach(async () => {
14
+ await Promise.all(runningServers.splice(0).map((server) => server.close()))
15
+ })
16
+
17
+ test('scanProject returns health, block, keyword, and link summaries', async () => {
18
+ const dir = await fixture({
19
+ 'content/a.md': `---
20
+ slug: alpha
21
+ linksTo:
22
+ - beta
23
+ keywords:
24
+ primary: alpha topic
25
+ secondary: [studio, content]
26
+ ---
27
+
28
+ # Alpha
29
+
30
+ This introduction has enough words to be useful for the healthy fixture.
31
+
32
+ :::callout{type="tip" title="Keep going"}
33
+ This callout body has more than enough words to satisfy the minimum length.
34
+ :::
35
+ `,
36
+ 'content/b.md': `---
37
+ slug: beta
38
+ linksTo:
39
+ - alpha
40
+ keywords:
41
+ primary: beta topic
42
+ ---
43
+
44
+ # Beta
45
+
46
+ This second page closes the loop and keeps the graph free of dangling links.
47
+ `,
48
+ })
49
+
50
+ const project = await scanProject({
51
+ globs: ['content/*.md'],
52
+ cwd: dir,
53
+ minSectionWords: 0,
54
+ })
55
+
56
+ expect(project.summary.files).toBe(2)
57
+ expect(project.summary.errors).toBe(0)
58
+ expect(project.blockUsage.callout).toBe(1)
59
+ expect(project.keywordCoverage.withPrimary).toBe(2)
60
+ expect(project.keywordCoverage.withSecondary).toBe(1)
61
+ expect(project.linkGraph).toMatchObject({ pages: 2, links: 2, orphans: 0 })
62
+ })
63
+
64
+ test('scanProject ranks validation, link, and stats findings', async () => {
65
+ const dir = await fixture({
66
+ 'content/a.md': `---
67
+ slug: alpha
68
+ linksTo:
69
+ - missing-page
70
+ keywords:
71
+ primary: alpha topic
72
+ ---
73
+
74
+ # Tiny
75
+
76
+ Short.
77
+
78
+ ![ ](photo.jpg)
79
+
80
+ :::callout{type="surprise"}
81
+ Too short.
82
+ :::
83
+ `,
84
+ 'content/b.md': `---
85
+ slug: beta
86
+ ---
87
+
88
+ # ${longHeading()}
89
+
90
+ ${Array.from({ length: 260 }, (_, index) => `word${index}`).join(' ')}
91
+ `,
92
+ })
93
+
94
+ const project = await scanProject({ globs: ['content/*.md'], cwd: dir })
95
+ const codes = project.findings.map((finding) => finding.code)
96
+
97
+ expect(codes).toContain('CB_PROPS_INVALID')
98
+ expect(codes).toContain('CB_LINK_UNRESOLVED')
99
+ expect(codes).toContain('CB_THIN_SECTION')
100
+ expect(codes).toContain('CB_BLOCKLESS_DOCUMENT')
101
+ expect(codes).toContain('CB_IMAGE_ALT_MISSING')
102
+ expect(codes.indexOf('CB_PROPS_INVALID')).toBeLessThan(codes.indexOf('CB_LINK_UNRESOLVED'))
103
+ })
104
+
105
+ test('scanDocument rejects paths outside the matched content set', async () => {
106
+ const dir = await fixture({
107
+ 'content/a.md': '---\nslug: alpha\n---\n\n# Alpha\n\nBody.',
108
+ 'secret.md': '# Secret',
109
+ })
110
+
111
+ await expect(
112
+ scanDocument({ globs: ['content/*.md'], cwd: dir }, '../secret.md'),
113
+ ).resolves.toBeNull()
114
+ await expect(scanDocument({ globs: ['content/*.md'], cwd: dir }, 'secret.md')).resolves.toBeNull()
115
+ })
116
+
117
+ test('scanDocument validates custom registries and previews unknown renderers safely', async () => {
118
+ const dir = await fixture({
119
+ 'blocks/registry.mjs': `import { defineBlock, markdownBody } from '@contentbit/core'
120
+ import { z } from 'zod'
121
+
122
+ const quote = defineBlock({
123
+ name: 'quote',
124
+ props: z.object({}),
125
+ content: markdownBody({ minLength: 3 }),
126
+ })
127
+
128
+ export default [quote]
129
+ `,
130
+ 'content/a.md': `---
131
+ slug: alpha
132
+ ---
133
+
134
+ # Alpha
135
+
136
+ :::quote
137
+ Custom block content for the local registry.
138
+ :::
139
+ `,
140
+ })
141
+ await linkContentbitCore(dir)
142
+
143
+ const document = await scanDocument(
144
+ { globs: ['content/*.md'], cwd: dir, registryPath: 'blocks/registry.mjs', minSectionWords: 0 },
145
+ 'content/a.md',
146
+ )
147
+
148
+ expect(document?.findings.filter((finding) => finding.source === 'validation')).toEqual([])
149
+ expect(document?.file.blockNames.quote).toBe(1)
150
+ expect(document?.previewHtml).toContain('<h1>Alpha</h1>')
151
+ expect(document?.previewHtml).toContain('data-cb-custom="quote"')
152
+ expect(document?.previewHtml).toContain('<p>Custom block content for the local registry.</p>')
153
+ })
154
+
155
+ test('scanGraph returns resolved and unresolved edges', async () => {
156
+ const dir = await fixture({
157
+ 'content/a.md': '---\nslug: alpha\nlinksTo:\n - beta\n - missing\n---\n\n# Alpha\n\nBody.',
158
+ 'content/b.md': '---\nslug: beta\n---\n\n# Beta\n\nBody.',
159
+ })
160
+
161
+ const graph = await scanGraph({ globs: ['content/*.md'], cwd: dir, minSectionWords: 0 })
162
+
163
+ expect(graph.nodes).toHaveLength(2)
164
+ expect(graph.edges.some((edge) => edge.status === 'resolved' && edge.target === 'beta')).toBe(
165
+ true,
166
+ )
167
+ expect(
168
+ graph.edges.some((edge) => edge.status === 'unresolved' && edge.target === 'missing'),
169
+ ).toBe(true)
170
+ })
171
+
172
+ test('startStudio serves read-only local API responses on port 0', async () => {
173
+ const dir = await fixture({
174
+ 'content/a.md': '---\nslug: alpha\n---\n\n# Alpha\n\nReadable body.',
175
+ })
176
+ const server = await startStudio({
177
+ globs: ['content/*.md'],
178
+ cwd: dir,
179
+ port: 0,
180
+ open: false,
181
+ minSectionWords: 0,
182
+ })
183
+ runningServers.push(server)
184
+
185
+ const project = (await fetchJson(new URL('/api/project', server.url))) as {
186
+ summary: { files: number }
187
+ }
188
+ const blocked = await fetch(new URL('/api/document?path=../secret.md', server.url))
189
+ const write = await fetch(new URL('/api/project', server.url), { method: 'POST' })
190
+
191
+ expect(project.summary.files).toBe(1)
192
+ expect(blocked.status).toBe(404)
193
+ expect(write.status).toBe(405)
194
+ })
195
+
196
+ test('startStudio renders project block components from the registry folder', async () => {
197
+ const dir = await fixture({
198
+ 'blocks/registry.mjs': `import { defineBlock, markdownBody } from '@contentbit/core'
199
+ import { z } from 'zod'
200
+
201
+ const quote = defineBlock({
202
+ name: 'quote',
203
+ props: z.object({ author: z.string() }),
204
+ content: markdownBody({ minLength: 3 }),
205
+ })
206
+
207
+ export default [quote]
208
+ `,
209
+ 'blocks/components.tsx': `import { createElement } from 'react'
210
+ import type { BlockComponent } from '@contentbit/react'
211
+
212
+ export const blockComponents: Record<string, BlockComponent> = {
213
+ quote({ node, ctx }) {
214
+ const data = node.data as { markdown: string }
215
+ return createElement(
216
+ 'figure',
217
+ { 'data-project-block': 'quote' },
218
+ createElement('strong', null, String(node.props.author)),
219
+ ctx.renderMarkdown(data.markdown),
220
+ )
221
+ },
222
+ }
223
+ `,
224
+ 'content/a.md': `---
225
+ slug: alpha
226
+ ---
227
+
228
+ # Alpha
229
+
230
+ :::quote{author="Ada"}
231
+ **Custom block** content from the project.
232
+ :::
233
+ `,
234
+ })
235
+ await linkContentbitCore(dir)
236
+
237
+ const server = await startStudio({
238
+ globs: ['content/*.md'],
239
+ cwd: dir,
240
+ registryPath: 'blocks/registry.mjs',
241
+ port: 0,
242
+ open: false,
243
+ minSectionWords: 0,
244
+ })
245
+ runningServers.push(server)
246
+
247
+ const document = (await fetchJson(new URL('/api/document?path=content/a.md', server.url))) as {
248
+ previewHtml: string
249
+ }
250
+
251
+ expect(document.previewHtml).toContain('data-project-block="quote"')
252
+ expect(document.previewHtml).toContain('<strong>Ada</strong>')
253
+ expect(document.previewHtml).toContain('<strong>Custom block</strong>')
254
+ expect(document.previewHtml).not.toContain('data-cb-custom="quote"')
255
+ })
256
+
257
+ async function fixture(files: Record<string, string>): Promise<string> {
258
+ const dir = await mkdtemp(join(tmpdir(), 'cb-studio-'))
259
+ for (const [path, content] of Object.entries(files)) {
260
+ const fullPath = join(dir, path)
261
+ await mkdir(dirname(fullPath), { recursive: true })
262
+ await writeFile(fullPath, content, 'utf8')
263
+ }
264
+ return dir
265
+ }
266
+
267
+ async function linkContentbitCore(dir: string): Promise<void> {
268
+ await mkdir(join(dir, 'node_modules/@contentbit'), { recursive: true })
269
+ await symlink(join(root, 'packages/core'), join(dir, 'node_modules/@contentbit/core'))
270
+ await symlink(join(root, 'packages/react'), join(dir, 'node_modules/@contentbit/react'))
271
+ await symlink(join(root, 'packages/core/node_modules/zod'), join(dir, 'node_modules/zod'))
272
+ await symlink(join(root, 'packages/studio/node_modules/react'), join(dir, 'node_modules/react'))
273
+ }
274
+
275
+ async function fetchJson(url: URL): Promise<unknown> {
276
+ const response = await fetch(url)
277
+ if (!response.ok) throw new Error(`Request failed: ${response.status}`)
278
+ return response.json()
279
+ }
280
+
281
+ function longHeading(): string {
282
+ return 'Long Document'
283
+ }