@contentbit/studio 1.0.0 → 2.0.0-next.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 (66) hide show
  1. package/README.md +19 -9
  2. package/dist/client/assets/api-aCc2x-IO.js +1 -0
  3. package/dist/client/assets/arrow-right-tp4VknZo.js +1 -0
  4. package/dist/client/assets/document-DIh3ZPXr.js +56 -0
  5. package/dist/client/assets/documents-CjBZYbQ4.js +1 -0
  6. package/dist/client/assets/file-code-corner-Fzc5liO9.js +1 -0
  7. package/dist/client/assets/file-text-B8O46COn.js +1 -0
  8. package/dist/client/assets/index-Cd04OFZT.js +11 -0
  9. package/dist/client/assets/page-BMU8eIrR.js +1 -0
  10. package/dist/client/assets/routes-WndCJoku.js +1 -0
  11. package/dist/client/assets/search-BnUPH8AI.js +1 -0
  12. package/dist/client/assets/styles-hAsz_paS.css +2 -0
  13. package/dist/client/assets/target-BMSXP2fU.js +1 -0
  14. package/dist/client/assets/templates-IJid1Zwh.js +1 -0
  15. package/dist/server/api.d.ts.map +1 -1
  16. package/dist/server/assets/_tanstack-start-manifest_v-WfZ3uz_l.js +69 -0
  17. package/dist/server/assets/api-CHfynRIj.js +342 -0
  18. package/dist/server/assets/{document-DSV89Ser.js → document-BjPXZ9gS.js} +2529 -1317
  19. package/dist/server/assets/{routes-FGdym0e5.js → documents-jT4KnSkA.js} +63 -112
  20. package/dist/server/assets/empty-plugin-adapters-Ctp1ZmyT.js +4 -0
  21. package/dist/server/assets/page--xw7NmtK.js +388 -0
  22. package/dist/server/assets/router-xI8HUWRI.js +125 -0
  23. package/dist/server/assets/routes-CfwU-Ww2.js +372 -0
  24. package/dist/server/assets/start-Dk-BJfGT.js +3 -0
  25. package/dist/server/assets/templates--9wK-MK9.js +123 -0
  26. package/dist/server/index.d.ts +2 -2
  27. package/dist/server/index.d.ts.map +1 -1
  28. package/dist/server/index.js +6104 -110
  29. package/dist/server/scan.d.ts +1 -2
  30. package/dist/server/scan.d.ts.map +1 -1
  31. package/dist/server/server.js +3150 -1878
  32. package/dist/server/site.d.ts +38 -0
  33. package/dist/server/site.d.ts.map +1 -0
  34. package/dist/server/types.d.ts +33 -31
  35. package/dist/server/types.d.ts.map +1 -1
  36. package/package.json +26 -15
  37. package/src/components/studio.test.ts +10 -0
  38. package/src/components/studio.tsx +209 -0
  39. package/src/lib/api.test.ts +80 -0
  40. package/src/lib/api.ts +68 -7
  41. package/src/routeTree.gen.ts +57 -3
  42. package/src/routes/document.tsx +34 -88
  43. package/src/routes/documents.tsx +433 -0
  44. package/src/routes/index.tsx +295 -414
  45. package/src/routes/page.tsx +401 -0
  46. package/src/routes/templates.tsx +104 -0
  47. package/src/server/api.ts +19 -3
  48. package/src/server/index.ts +31 -12
  49. package/src/server/scan.test.ts +31 -44
  50. package/src/server/scan.ts +56 -82
  51. package/src/server/site.test.ts +355 -0
  52. package/src/server/site.ts +164 -0
  53. package/src/server/types.ts +28 -30
  54. package/tsconfig.json +1 -1
  55. package/dist/client/assets/api-BX-WUPtV.js +0 -1
  56. package/dist/client/assets/document-BOMp4_F5.js +0 -65
  57. package/dist/client/assets/index-C0ybJ4zQ.js +0 -12
  58. package/dist/client/assets/routes-ACKdIhYm.js +0 -1
  59. package/dist/client/assets/styles-DogO4Wcf.css +0 -2
  60. package/dist/server/assets/_tanstack-start-manifest_v-BC1PNuB0.js +0 -25
  61. package/dist/server/assets/api-Bqt_atjc.js +0 -72
  62. package/dist/server/assets/document-BB_UYqNL.js +0 -9
  63. package/dist/server/assets/empty-plugin-adapters-De7E1vAI.js +0 -5
  64. package/dist/server/assets/router-BJiN6b7L.js +0 -63
  65. package/dist/server/assets/routes-p0tk6PAr.js +0 -20
  66. package/dist/server/assets/start-m8EQRpUf.js +0 -4
@@ -0,0 +1,355 @@
1
+ import { mkdir, mkdtemp, realpath, writeFile } from 'node:fs/promises'
2
+ import { connect } from 'node:net'
3
+ import { tmpdir } from 'node:os'
4
+ import { dirname, join } from 'node:path'
5
+ import { afterEach, assert, expect, test } from 'vitest'
6
+
7
+ import { startStudio, type StudioServer } from './index'
8
+ import { scanDocument, scanProject } from './scan'
9
+ import { scanPage, scanSite } from './site'
10
+ import type { StudioOptions } from './types'
11
+
12
+ const runningServers: StudioServer[] = []
13
+
14
+ afterEach(async () => {
15
+ await Promise.all(runningServers.splice(0).map((server) => server.close()))
16
+ })
17
+
18
+ const page = (title: string, path: string, main: string) =>
19
+ `<!doctype html><html lang="en"><head><title>${title}</title><meta name="description" content="${title}."><link rel="canonical" href="https://bakery.example${path}"></head><body><header><a href="/">Home</a><a href="/about/">About</a><a href="/contact/">Contact</a></header><main>${main}</main></body></html>`
20
+
21
+ const markdown = (title: string, type: string, body: string, extra = '') =>
22
+ `---\ntitle: ${title}\ndescription: ${title}.\ntype: ${type}\n${extra}---\n\n${body}`
23
+
24
+ const bakery = {
25
+ 'package.json': JSON.stringify({ devDependencies: { astro: '^5.0.0' } }),
26
+ 'content/blog/sourdough.md': markdown(
27
+ 'Sourdough',
28
+ 'recipe',
29
+ '# Sourdough\n\nFlour and water.\n\n## Starter\n\nFeed it daily. Then [rye](/blog/rye/#rye) and [a lost loaf](/blog/lost/).\n',
30
+ 'keywords:\n primary: sourdough bread\n',
31
+ ),
32
+ 'content/blog/rye.md': markdown(
33
+ 'Rye',
34
+ 'note',
35
+ '# Rye\n\nRye flour, like [sourdough](/blog/sourdough/).\n',
36
+ ),
37
+ // Spelt's title and description are rye's: a duplicate the built pages report.
38
+ 'content/blog/spelt.md': markdown('Rye', 'note', '# Spelt\n\nSpelt flour.\n'),
39
+ 'dist/index.html': page(
40
+ 'Bakery',
41
+ '/',
42
+ '<h1>Bakery</h1><p>Start with <a href="/blog/sourdough/">our sourdough</a>.</p>',
43
+ ),
44
+ 'dist/blog/sourdough/index.html': page(
45
+ 'Sourdough',
46
+ '/blog/sourdough/',
47
+ '<h1 id="sourdough">Sourdough</h1><p>Flour and water.</p><h2 id="starter">Starter</h2><p>Feed it daily. Then <a href="/blog/rye/#rye">rye</a> and <a href="/blog/lost/">a lost loaf</a>.</p>',
48
+ ),
49
+ 'dist/blog/rye/index.html': page(
50
+ 'Rye',
51
+ '/blog/rye/',
52
+ '<h1 id="rye">Rye</h1><p>Rye flour, like <a href="/blog/sourdough/">sourdough</a>.</p>',
53
+ ),
54
+ 'dist/blog/spelt/index.html': page('Rye', '/blog/spelt/', '<h1>Spelt</h1><p>Spelt flour.</p>'),
55
+ 'dist/about/index.html': page('About', '/about/', '<h1>About</h1><p>Only the header.</p>'),
56
+ }
57
+
58
+ const seoConfig = {
59
+ pageTypes: {
60
+ recipe: { requiredSections: [{ id: 'method', headings: ['Method'] }] },
61
+ note: {},
62
+ },
63
+ }
64
+
65
+ function options(cwd: string, extra: Partial<StudioOptions> = {}): StudioOptions {
66
+ return {
67
+ globs: ['content/**/*.md'],
68
+ cwd,
69
+ linkOptions: { routes: { [join(cwd, 'content/blog')]: '/blog/{path}/' } },
70
+ loadSeo: () => Promise.resolve({ config: seoConfig }),
71
+ ...extra,
72
+ }
73
+ }
74
+
75
+ test('scanSite lists every built page with its source, findings and the template findings', async () => {
76
+ const dir = await fixture(bakery)
77
+
78
+ const site = await scanSite(options(dir))
79
+ if (site.kind !== 'built') throw new Error(`expected a build, got ${site.kind}`)
80
+
81
+ expect(site.markdownFiles).toBe(3)
82
+ expect(site.context.build).toBe(join(dir, 'dist'))
83
+ expect(site.context.origin).toEqual({ url: 'https://bakery.example', source: 'canonicals' })
84
+ expect(site.context.pages.map(({ path, source }) => [path, source])).toEqual([
85
+ ['/', undefined],
86
+ ['/about/', undefined],
87
+ ['/blog/rye/', join(dir, 'content/blog/rye.md')],
88
+ ['/blog/sourdough/', join(dir, 'content/blog/sourdough.md')],
89
+ ['/blog/spelt/', join(dir, 'content/blog/spelt.md')],
90
+ ])
91
+ expect(site.context.unlinked).toEqual(['/about/', '/blog/spelt/'])
92
+
93
+ // The header's Contact link is missing on every page: one template finding, not five.
94
+ expect(site.context.templateFindings).toHaveLength(1)
95
+ expect(site.context.templateFindings[0]).toMatchObject({
96
+ code: 'CB_LINK_PAGE_MISSING',
97
+ origin: {
98
+ kind: 'template',
99
+ pages: ['/', '/about/', '/blog/rye/', '/blog/sourdough/', '/blog/spelt/'],
100
+ },
101
+ })
102
+ // /about/ has only the template finding. Sourdough adds its lost loaf link and the Method
103
+ // section its Markdown lacks. Spelt adds a duplicate title and a duplicate description.
104
+ expect(site.findingCountsByPage['/about/']).toEqual({ errors: 1, warnings: 0 })
105
+ expect(site.findingCountsByPage['/blog/sourdough/']).toEqual({ errors: 2, warnings: 1 })
106
+ expect(site.findingCountsByPage['/blog/spelt/']).toEqual({ errors: 1, warnings: 2 })
107
+ expect(site.summary).toEqual({ pages: 5, errors: 2, warnings: 5, ignored: 0 })
108
+ expect(site.staleSources).toEqual([])
109
+ })
110
+
111
+ test('scanSite counts findings only on built pages and lists the ones on no built page', async () => {
112
+ const dir = await fixture({
113
+ ...bakery,
114
+ 'content/blog/rolls.md': markdown('Rolls', 'note', '# Rolls\n\nSoft rolls.\n'),
115
+ 'dist/sitemap.xml':
116
+ '<urlset><url><loc>https://bakery.example/</loc></url><url><loc>https://bakery.example/gone/</loc></url></urlset>',
117
+ })
118
+
119
+ const site = await scanSite(options(dir))
120
+ if (site.kind !== 'built') throw new Error(`expected a build, got ${site.kind}`)
121
+
122
+ const built = new Set<string>(site.context.pages.map(({ path }) => path))
123
+ expect(Object.keys(site.findingCountsByPage).filter((path) => !built.has(path))).toEqual([])
124
+ expect(
125
+ site.unbuiltFindings.map(({ code, origin }) => [
126
+ code,
127
+ origin.kind === 'template' ? origin.pages : origin.page,
128
+ ]),
129
+ ).toEqual([
130
+ ['CB_SITE_SOURCE_NOT_BUILT', '/blog/rolls/'],
131
+ ['CB_SITE_SITEMAP_URL_NOT_BUILT', '/gone/'],
132
+ ])
133
+ })
134
+
135
+ test('scanPage gives a page context: served facts, outline, links with placement, findings and contract', async () => {
136
+ const dir = await fixture(bakery)
137
+
138
+ const found = await scanPage(options(dir), '/blog/sourdough/')
139
+ assert(found)
140
+ const { context } = found
141
+
142
+ expect(found.root).toBe(dir)
143
+ expect(context.url).toBe('https://bakery.example/blog/sourdough/')
144
+ expect(context.source).toEqual({
145
+ file: join(dir, 'content/blog/sourdough.md'),
146
+ route: '/blog/sourdough/',
147
+ })
148
+ expect(context.served).toMatchObject({ title: 'Sourdough', canonical: context.url, lang: 'en' })
149
+ expect(context.declared).toMatchObject({
150
+ type: 'recipe',
151
+ keywords: { primary: 'sourdough bread' },
152
+ })
153
+ expect(context.outline.map(({ level, text, words }) => [level, text, words])).toEqual([
154
+ [1, 'Sourdough', 4],
155
+ [2, 'Starter', 10],
156
+ ])
157
+ expect(context.linksIn).toEqual([
158
+ { from: '/', text: 'our sourdough', placement: 'content' },
159
+ { from: '/blog/rye/', text: 'sourdough', placement: 'content' },
160
+ ])
161
+ expect(context.linksOut.map(({ text, placement, target }) => [text, placement, target])).toEqual([
162
+ ['Home', 'layout', { kind: 'page', page: '/' }],
163
+ ['About', 'layout', { kind: 'page', page: '/about/' }],
164
+ ['Contact', 'layout', { kind: 'missing', path: '/contact/' }],
165
+ ['rye', 'content', { kind: 'page', page: '/blog/rye/', anchor: 'rye' }],
166
+ ['a lost loaf', 'content', { kind: 'missing', path: '/blog/lost/' }],
167
+ ])
168
+ expect(context.findings.map(({ code, origin }) => [code, origin.kind])).toEqual([
169
+ ['CB_LINK_PAGE_MISSING', 'template'],
170
+ ['CB_LINK_PAGE_MISSING', 'source'],
171
+ ])
172
+ expect(context.findings[1].origin).toMatchObject({
173
+ file: join(dir, 'content/blog/sourdough.md'),
174
+ line: 15,
175
+ })
176
+ expect(context.contentFindings.map(({ code }) => code)).toEqual(['CB_SEO_SECTION_MISSING'])
177
+ expect(context.contract?.acceptanceChecks).toContain('Document includes section: Method.')
178
+ })
179
+
180
+ test('scanPage finds nothing for a path the build does not have', async () => {
181
+ const dir = await fixture(bakery)
182
+
183
+ await expect(scanPage(options(dir), '/blog/lost/')).resolves.toBeNull()
184
+ })
185
+
186
+ test('the Markdown views leave out the findings a built page owns, and link to that page', async () => {
187
+ const dir = await fixture(bakery)
188
+ const markdownOnly = await fixture(withoutBuild(bakery))
189
+ const codes = async (cwd: string) =>
190
+ (await scanProject(options(cwd))).findings.map(({ code }) => code)
191
+
192
+ // Without a build the Markdown check reports the shared title; with one, the built pages do.
193
+ expect(await codes(markdownOnly)).toContain('CB_TITLE_DUPLICATE')
194
+ expect(await codes(dir)).not.toContain('CB_TITLE_DUPLICATE')
195
+ const document = await scanDocument(options(dir), 'content/blog/sourdough.md')
196
+ expect(document?.pages).toEqual(['/blog/sourdough/'])
197
+ expect((await scanDocument(options(markdownOnly), 'content/blog/sourdough.md'))?.pages).toEqual(
198
+ [],
199
+ )
200
+ })
201
+
202
+ test('a document links to every built page of its file, as context finds them all', async () => {
203
+ const dir = await fixture({
204
+ ...bakery,
205
+ 'dist/blog/rye.html': page('Rye', '/blog/rye', '<h1>Rye</h1><p>Rye flour.</p>'),
206
+ })
207
+
208
+ expect((await scanDocument(options(dir), 'content/blog/rye.md'))?.pages).toEqual([
209
+ '/blog/rye',
210
+ '/blog/rye/',
211
+ ])
212
+ })
213
+
214
+ test('scanSite without a build says where it looked and how to build', async () => {
215
+ const dir = await fixture(withoutBuild(bakery))
216
+
217
+ expect(await scanSite(options(dir))).toEqual({
218
+ kind: 'unbuilt',
219
+ root: dir,
220
+ markdownFiles: 3,
221
+ searched: ['dist', 'dist/client', 'out', 'build', '_site', 'public'].map((folder) =>
222
+ join(dir, folder),
223
+ ),
224
+ buildCommand: 'astro build',
225
+ })
226
+ })
227
+
228
+ test('a build with no Markdown gets every built-page view and an empty Markdown view', async () => {
229
+ const dir = await fixture(withoutMarkdown(bakery))
230
+ const studio = options(dir, { globs: [] })
231
+
232
+ const site = await scanSite(studio)
233
+ if (site.kind !== 'built') throw new Error(`expected a build, got ${site.kind}`)
234
+ expect(site.markdownFiles).toBe(0)
235
+ expect(site.context.pages.map(({ path }) => path)).toHaveLength(5)
236
+ expect(site.context.pages.every(({ source }) => source === undefined)).toBe(true)
237
+ expect((await scanPage(studio, '/blog/rye/'))?.context.linksIn).toEqual([
238
+ { from: '/blog/sourdough/', text: 'rye', anchor: 'rye', placement: 'content' },
239
+ ])
240
+ expect((await scanProject(studio)).summary.files).toBe(0)
241
+ })
242
+
243
+ test('scanSite reads the build folder passed instead of the detected one', async () => {
244
+ const dir = await fixture({
245
+ ...withoutBuild(bakery),
246
+ 'site/index.html': page('Elsewhere', '/', '<h1>Elsewhere</h1>'),
247
+ })
248
+
249
+ const site = await scanSite(options(dir, { build: join(dir, 'site') }))
250
+ expect(site.kind === 'built' && site.context.pages.map(({ path }) => path)).toEqual(['/'])
251
+ })
252
+
253
+ test('scanSite reads a relative site.buildPath against cwd, not the folder Studio runs from', async () => {
254
+ const dir = await fixture({
255
+ ...withoutBuild(bakery),
256
+ 'web/index.html': page('Elsewhere', '/', '<h1>Elsewhere</h1>'),
257
+ })
258
+
259
+ const site = await scanSite(options(dir, { site: { buildPath: 'web' } }))
260
+ expect(site.kind === 'built' && site.context.build).toBe(join(dir, 'web'))
261
+ })
262
+
263
+ test('scanSite takes the origin of an http or https URL and refuses anything else', async () => {
264
+ const dir = await fixture(bakery)
265
+
266
+ const site = await scanSite(options(dir, { origin: 'https://www.bakery.example/blog/' }))
267
+ expect(site.kind === 'built' && site.context.origin).toEqual({
268
+ url: 'https://www.bakery.example',
269
+ source: 'flag',
270
+ })
271
+ await expect(scanSite(options(dir, { origin: 'bakery.example' }))).rejects.toThrow(
272
+ 'studio: origin must be an absolute http or https URL, not "bakery.example".',
273
+ )
274
+ })
275
+
276
+ test('startStudio serves the site and page context endpoints from the build folder passed, relative to cwd', async () => {
277
+ const dir = await fixture(
278
+ Object.fromEntries(
279
+ Object.entries(bakery).map(([path, text]) => [path.replace(/^dist\//, 'web/'), text]),
280
+ ),
281
+ )
282
+ const server = await startStudio({
283
+ ...options(dir),
284
+ build: 'web',
285
+ origin: 'https://www.bakery.example',
286
+ port: 0,
287
+ open: false,
288
+ })
289
+ runningServers.push(server)
290
+ const get = (path: string) => fetch(new URL(path, server.url))
291
+
292
+ const site = await get('/api/site')
293
+ const context = await get('/api/page?path=%2Fblog%2Fsourdough%2F')
294
+ const missing = await get('/api/page?path=%2Fblog%2Flost%2F')
295
+ const noPath = await get('/api/page')
296
+
297
+ expect(site.status).toBe(200)
298
+ expect(await site.json()).toMatchObject({
299
+ kind: 'built',
300
+ context: {
301
+ build: join(dir, 'web'),
302
+ origin: { url: 'https://www.bakery.example', source: 'flag' },
303
+ pages: { length: 5 },
304
+ },
305
+ })
306
+ expect(context.status).toBe(200)
307
+ expect(await context.json()).toMatchObject({ context: { page: '/blog/sourdough/' } })
308
+ expect(missing.status).toBe(404)
309
+ expect(await missing.json()).toEqual({ error: 'The build has no page /blog/lost/.' })
310
+ expect(noPath.status).toBe(400)
311
+ })
312
+
313
+ test('a request whose URL Studio cannot parse gets an error, and Studio keeps serving', async () => {
314
+ const dir = await fixture(bakery)
315
+ const server = await startStudio({ ...options(dir), port: 0, open: false })
316
+ runningServers.push(server)
317
+
318
+ const malformed = await statusLine(server.url, '//[')
319
+ const site = await fetch(new URL('/api/site', server.url))
320
+
321
+ expect(malformed).toBe('HTTP/1.1 500 Internal Server Error')
322
+ expect(site.status).toBe(200)
323
+ })
324
+
325
+ function statusLine(url: string, path: string): Promise<string> {
326
+ const { hostname, host, port } = new URL(url)
327
+ return new Promise((resolve, reject) => {
328
+ let response = ''
329
+ const socket = connect(Number(port), hostname, () =>
330
+ socket.write(`GET ${path} HTTP/1.1\r\nHost: ${host}\r\nConnection: close\r\n\r\n`),
331
+ )
332
+ socket.setEncoding('utf8')
333
+ socket.on('data', (chunk: string) => (response += chunk))
334
+ socket.on('error', reject)
335
+ socket.on('close', () => resolve(response.split('\r\n')[0]))
336
+ })
337
+ }
338
+
339
+ function withoutBuild(files: Record<string, string>): Record<string, string> {
340
+ return Object.fromEntries(Object.entries(files).filter(([path]) => !path.startsWith('dist/')))
341
+ }
342
+
343
+ function withoutMarkdown(files: Record<string, string>): Record<string, string> {
344
+ return Object.fromEntries(Object.entries(files).filter(([path]) => !path.startsWith('content/')))
345
+ }
346
+
347
+ async function fixture(files: Record<string, string>): Promise<string> {
348
+ const dir = await realpath(await mkdtemp(join(tmpdir(), 'cb-studio-site-')))
349
+ for (const [path, content] of Object.entries(files)) {
350
+ const fullPath = join(dir, path)
351
+ await mkdir(dirname(fullPath), { recursive: true })
352
+ await writeFile(fullPath, content, 'utf8')
353
+ }
354
+ return dir
355
+ }
@@ -0,0 +1,164 @@
1
+ import {
2
+ findingPages,
3
+ httpOrigin,
4
+ pageContext,
5
+ siteContext,
6
+ type ContentFinding,
7
+ type HttpOrigin,
8
+ type PageContext,
9
+ type PagePath,
10
+ type SiteCheck,
11
+ type SiteContext,
12
+ type SiteFinding,
13
+ type SiteSources,
14
+ } from '@contentbit/built-site'
15
+ import { buildCommand, loadSite, siteCheck, type LoadedSite } from '@contentbit/project'
16
+
17
+ import type { StudioOptions } from './types.js'
18
+
19
+ export type {
20
+ ContentFinding,
21
+ LinkOutTarget,
22
+ PageContext,
23
+ SiteContext,
24
+ SiteFinding,
25
+ } from '@contentbit/built-site'
26
+
27
+ export interface FindingCounts {
28
+ errors: number
29
+ warnings: number
30
+ }
31
+
32
+ export type StudioSite =
33
+ | {
34
+ kind: 'built'
35
+ root: string
36
+ markdownFiles: number
37
+ context: SiteContext
38
+ summary: SiteCheck['summary']
39
+ agentGuidanceFindings: ContentFinding[]
40
+ /** The findings about the check settings, such as an ignore entry that matches no finding. */
41
+ configFindings: ContentFinding[]
42
+ /** The errors and warnings on each built page, template findings included. */
43
+ findingCountsByPage: Record<string, FindingCounts>
44
+ /** The findings on no built page, such as a sitemap URL or a source document never built. */
45
+ unbuiltFindings: SiteFinding[]
46
+ staleSources: string[]
47
+ }
48
+ | {
49
+ kind: 'unbuilt'
50
+ root: string
51
+ markdownFiles: number
52
+ searched: string[]
53
+ buildCommand: string
54
+ }
55
+
56
+ export interface StudioPage {
57
+ root: string
58
+ context: PageContext
59
+ }
60
+
61
+ const inFlight = new WeakMap<StudioOptions, Promise<LoadedSite>>()
62
+
63
+ export function loadSiteOrJoinInFlight(options: StudioOptions): Promise<LoadedSite> {
64
+ const current = inFlight.get(options)
65
+ if (current) return current
66
+ const read = readSite(options).finally(() => inFlight.delete(options))
67
+ inFlight.set(options, read)
68
+ return read
69
+ }
70
+
71
+ function readSite(options: StudioOptions): Promise<LoadedSite> {
72
+ return loadSite({
73
+ cmd: 'studio',
74
+ root: options.cwd ?? process.cwd(),
75
+ globs: options.globs,
76
+ registry: options.registryPath,
77
+ includeGenericBlocks: options.includeGenericBlocks,
78
+ blocks: options.blocks,
79
+ linkOptions: options.linkOptions ?? {},
80
+ loadSeo: options.loadSeo ?? (() => Promise.resolve({})),
81
+ build: options.build,
82
+ origin: options.origin === undefined ? undefined : parseOrigin(options.origin),
83
+ site: options.site,
84
+ check: options.check,
85
+ agentGuidanceFindings: options.agentGuidanceFindings,
86
+ })
87
+ }
88
+
89
+ function parseOrigin(value: string): HttpOrigin {
90
+ const origin = httpOrigin(value)
91
+ if (!origin) {
92
+ throw new Error(
93
+ `studio: origin must be an absolute http or https URL, not ${JSON.stringify(value)}.`,
94
+ )
95
+ }
96
+ return origin
97
+ }
98
+
99
+ export async function scanSite(options: StudioOptions): Promise<StudioSite> {
100
+ const loaded = await loadSiteOrJoinInFlight(options)
101
+ const { root, markdown } = loaded
102
+ const markdownFiles = markdown?.files.length ?? 0
103
+ if (!loaded.site) {
104
+ return {
105
+ kind: 'unbuilt',
106
+ root,
107
+ markdownFiles,
108
+ searched: loaded.searched,
109
+ buildCommand: buildCommand(root),
110
+ }
111
+ }
112
+ const check = siteCheck(loaded)
113
+ return {
114
+ kind: 'built',
115
+ root,
116
+ markdownFiles,
117
+ context: siteContext(loaded),
118
+ summary: check.summary,
119
+ agentGuidanceFindings: loaded.agentFindings,
120
+ configFindings: loaded.configFindings,
121
+ findingCountsByPage: findingCountsByPage(loaded),
122
+ unbuiltFindings: (loaded.findings ?? []).filter((finding) =>
123
+ findingPages(finding).every((page) => !builtPaths(loaded).has(page)),
124
+ ),
125
+ staleSources: check.staleSources ?? [],
126
+ }
127
+ }
128
+
129
+ export async function scanPage(options: StudioOptions, path: string): Promise<StudioPage | null> {
130
+ const loaded = await loadSiteOrJoinInFlight(options)
131
+ if (!loaded.site) return null
132
+ const page = loaded.site.pages.find((candidate) => candidate.path === path)
133
+ return page ? { root: loaded.root, context: pageContext(loaded, page) } : null
134
+ }
135
+
136
+ export function pagesByFile(sources: SiteSources | undefined): Map<string, PagePath[]> {
137
+ const pages = new Map<string, PagePath[]>()
138
+ for (const [page, { file }] of sources?.pages ?? []) {
139
+ pages.set(file, [...(pages.get(file) ?? []), page])
140
+ }
141
+ return pages
142
+ }
143
+
144
+ function builtPaths({ site }: LoadedSite): Set<string> {
145
+ return new Set(site?.pages.map(({ path }) => path))
146
+ }
147
+
148
+ function findingCountsByPage(loaded: LoadedSite): Record<string, FindingCounts> {
149
+ const counts: Record<string, FindingCounts> = {}
150
+ const built = builtPaths(loaded)
151
+ const add = (page: string, severity: string) => {
152
+ if (!built.has(page) || (severity !== 'error' && severity !== 'warning')) return
153
+ counts[page] ??= { errors: 0, warnings: 0 }
154
+ counts[page][severity === 'error' ? 'errors' : 'warnings']++
155
+ }
156
+ for (const finding of loaded.findings ?? []) {
157
+ for (const page of findingPages(finding)) add(page, finding.severity)
158
+ }
159
+ const pagesOfFile = pagesByFile(loaded.sources)
160
+ for (const { file, severity } of loaded.contentFindings) {
161
+ for (const page of pagesOfFile.get(file) ?? []) add(page, severity)
162
+ }
163
+ return counts
164
+ }
@@ -1,9 +1,18 @@
1
- import type { DocumentStats, LinkReference, LinkResolverOptions, SeoBrief } from '@contentbit/core'
1
+ import type {
2
+ ContentbitCheckConfig,
3
+ ContentProjectFinding,
4
+ DocumentStats,
5
+ LinkResolverOptions,
6
+ SeoBrief,
7
+ } from '@contentbit/core'
2
8
  import type { BlockComponent } from '@contentbit/react'
3
9
 
4
10
  export type StudioSeverity = 'error' | 'warning' | 'info'
5
11
  export type StudioStatus = 'error' | 'warning' | 'suggestion' | 'healthy'
6
- export type StudioFindingSource = 'validation' | 'links' | 'stats' | 'integrity' | 'seo'
12
+ /** `page` marks a built-page finding that check puts at a line of a Markdown file. */
13
+ export type StudioFindingSource = 'validation' | 'links' | 'stats' | 'integrity' | 'seo' | 'page'
14
+
15
+ export type AgentGuidanceFinding = Omit<ContentProjectFinding, 'source'> & { source: 'agents' }
7
16
 
8
17
  export interface StudioFinding {
9
18
  severity: StudioSeverity
@@ -64,7 +73,6 @@ export interface StudioProject {
64
73
  }
65
74
  blockUsage: Record<string, number>
66
75
  keywordCoverage: { total: number; withPrimary: number; withSecondary: number }
67
- linkGraph?: { pages: number; links: number; orphans: number }
68
76
  seo?: {
69
77
  schemaVersion: string
70
78
  pages: number
@@ -73,6 +81,7 @@ export interface StudioProject {
73
81
  findings: number
74
82
  }
75
83
  findings: StudioFinding[]
84
+ agentGuidanceFindings: AgentGuidanceFinding[]
76
85
  }
77
86
 
78
87
  export interface StudioDocument {
@@ -80,44 +89,33 @@ export interface StudioDocument {
80
89
  source: string
81
90
  frontmatter: Record<string, unknown>
82
91
  stats: DocumentStats
92
+ /** The findings check puts at this file: its built-page findings, then its Markdown findings. */
83
93
  findings: StudioFinding[]
84
- linksTo: string[] | LinkReference[]
85
- linkedFrom: string[] | LinkReference[]
86
94
  seoBrief?: SeoBrief
87
95
  previewHtml: string
88
- }
89
-
90
- export interface StudioGraphNode {
91
- id: string
92
- label: string
93
- path: string
94
- status: StudioStatus
95
- slug?: string
96
- key?: string
97
- locale?: string
98
- }
99
-
100
- export interface StudioGraphEdge {
101
- from: string
102
- to?: string
103
- target: string
104
- status: 'resolved' | 'unresolved' | 'cross-locale' | 'self'
105
- }
106
-
107
- export interface StudioGraph {
108
- nodes: StudioGraphNode[]
109
- edges: StudioGraphEdge[]
96
+ /** The paths of the built pages this file is the source of. */
97
+ pages: string[]
110
98
  }
111
99
 
112
100
  export interface StudioOptions {
113
101
  globs: string[]
114
102
  registryPath?: string
115
103
  includeGenericBlocks?: boolean
104
+ /** Whether the project defines blocks, so Studio lists block findings as check does. */
105
+ blocks?: boolean
116
106
  cwd?: string
117
107
  linkOptions?: LinkResolverOptions
118
- minSectionWords?: number
119
- seoConfig?: unknown
120
- seoConfigPath?: string
108
+ /** Called on each read of the site that matches Markdown files, so a refresh shows an edited config. */
109
+ loadSeo?: () => Promise<{ config?: unknown; path?: string }>
110
+ /** Called with the matched Markdown files each time Studio summarizes the built pages or the documents; each view counts its findings and lists them, as check does. */
111
+ agentGuidanceFindings?: (files: string[]) => Promise<AgentGuidanceFinding[]>
112
+ /** The build folder to read instead of site.buildPath or a detected one. A relative path resolves against cwd, as globs do. */
113
+ build?: string
114
+ /** An http or https origin to use instead of site.origin or the pages' canonicals. */
115
+ origin?: string
116
+ site?: { buildPath?: string; origin?: string; draftField?: string; dateField?: string }
117
+ /** The check settings of the contentbit config at file, so Studio reports the findings check does. */
118
+ check?: ContentbitCheckConfig & { file: string }
121
119
  previewComponents?: () => Promise<Record<string, BlockComponent> | undefined>
122
120
  }
123
121
 
package/tsconfig.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "target": "ES2022",
5
5
  "jsx": "react-jsx",
6
6
  "module": "ESNext",
7
- "lib": ["ES2022", "DOM", "DOM.Iterable"],
7
+ "lib": ["ES2023", "DOM", "DOM.Iterable"],
8
8
  "types": ["vite/client"],
9
9
  "paths": {
10
10
  "@/*": ["./src/*"]