@contentbit/studio 0.4.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 (42) hide show
  1. package/README.md +46 -0
  2. package/dist/client/assets/api-C-Xwc2aB.js +1 -0
  3. package/dist/client/assets/document-Yk8nlK-k.js +1 -0
  4. package/dist/client/assets/index-BwvfKCmy.js +12 -0
  5. package/dist/client/assets/inter-cyrillic-ext-wght-normal-BOeWTOD4.woff2 +0 -0
  6. package/dist/client/assets/inter-cyrillic-wght-normal-DqGufNeO.woff2 +0 -0
  7. package/dist/client/assets/inter-greek-ext-wght-normal-DlzME5K_.woff2 +0 -0
  8. package/dist/client/assets/inter-greek-wght-normal-CkhJZR-_.woff2 +0 -0
  9. package/dist/client/assets/inter-latin-ext-wght-normal-DO1Apj_S.woff2 +0 -0
  10. package/dist/client/assets/inter-latin-wght-normal-Dx4kXJAl.woff2 +0 -0
  11. package/dist/client/assets/inter-vietnamese-wght-normal-CBcvBZtf.woff2 +0 -0
  12. package/dist/client/assets/routes-DHIbdBYB.js +1 -0
  13. package/dist/client/assets/styles-BGHadX26.css +2 -0
  14. package/dist/client/favicon.ico +0 -0
  15. package/dist/client/manifest.json +25 -0
  16. package/dist/client/robots.txt +3 -0
  17. package/dist/server/api.d.ts +4 -0
  18. package/dist/server/api.d.ts.map +1 -0
  19. package/dist/server/api.js +47 -0
  20. package/dist/server/assets/_tanstack-start-manifest_v-Djlrg1a7.js +25 -0
  21. package/dist/server/assets/api-Bqt_atjc.js +72 -0
  22. package/dist/server/assets/document-CxPFBdxd.js +265 -0
  23. package/dist/server/assets/document-DjmCb_Rp.js +9 -0
  24. package/dist/server/assets/empty-plugin-adapters-DKUlnwwl.js +5 -0
  25. package/dist/server/assets/router-D3JhQdql.js +63 -0
  26. package/dist/server/assets/routes-6jOjWQ0D.js +20 -0
  27. package/dist/server/assets/routes-BVJt9Z6a.js +386 -0
  28. package/dist/server/assets/start-q50h9Mc3.js +4 -0
  29. package/dist/server/index.d.ts +12 -0
  30. package/dist/server/index.d.ts.map +1 -0
  31. package/dist/server/index.js +108 -0
  32. package/dist/server/preview.d.ts +4 -0
  33. package/dist/server/preview.d.ts.map +1 -0
  34. package/dist/server/preview.js +19 -0
  35. package/dist/server/scan.d.ts +5 -0
  36. package/dist/server/scan.d.ts.map +1 -0
  37. package/dist/server/scan.js +352 -0
  38. package/dist/server/server.js +5520 -0
  39. package/dist/server/types.d.ts +111 -0
  40. package/dist/server/types.d.ts.map +1 -0
  41. package/dist/server/types.js +1 -0
  42. package/package.json +71 -0
@@ -0,0 +1,352 @@
1
+ import { genericBlocks } from '@contentbit/blocks';
2
+ import { analyzeDocument, buildLinkIndex, createBlockRegistry, extractFrontmatter, parseDocument, stripFrontmatter, validateDocument, validateLinks, } from '@contentbit/core';
3
+ import { readFile } from 'node:fs/promises';
4
+ import { basename, isAbsolute, join, relative } from 'node:path';
5
+ import { pathToFileURL } from 'node:url';
6
+ import { glob } from 'tinyglobby';
7
+ import { renderStudioPreview } from './preview.js';
8
+ const DEFAULT_MIN_SECTION_WORDS = 25;
9
+ const BLOCKLESS_WORDS = 250;
10
+ export async function scanProject(options) {
11
+ const context = await scanContext(options);
12
+ const blockUsage = {};
13
+ let words = 0;
14
+ let blocks = 0;
15
+ let links = 0;
16
+ let missingAlt = 0;
17
+ let withPrimary = 0;
18
+ let withSecondary = 0;
19
+ for (const file of context.summaries) {
20
+ words += file.words;
21
+ blocks += file.blocks;
22
+ links += file.links;
23
+ missingAlt += file.missingAlt;
24
+ if (file.keywords?.primary)
25
+ withPrimary++;
26
+ if ((file.keywords?.secondary?.length ?? 0) > 0)
27
+ withSecondary++;
28
+ for (const [name, count] of Object.entries(file.blockNames)) {
29
+ blockUsage[name] = (blockUsage[name] ?? 0) + count;
30
+ }
31
+ }
32
+ const summary = summarize(context.findings);
33
+ return {
34
+ root: options.cwd ?? process.cwd(),
35
+ files: context.summaries,
36
+ summary: {
37
+ files: context.summaries.length,
38
+ errors: summary.errors,
39
+ warnings: summary.warnings,
40
+ suggestions: summary.suggestions,
41
+ words,
42
+ blocks,
43
+ links,
44
+ missingAlt,
45
+ },
46
+ blockUsage,
47
+ keywordCoverage: {
48
+ total: context.summaries.length,
49
+ withPrimary,
50
+ withSecondary,
51
+ },
52
+ ...(context.index ? { linkGraph: graphSummary(context.index) } : {}),
53
+ findings: context.findings,
54
+ };
55
+ }
56
+ export async function scanDocument(options, requestedPath) {
57
+ const context = await scanContext(options);
58
+ const file = findAllowedFile(context, options.cwd ?? process.cwd(), requestedPath);
59
+ if (!file)
60
+ return null;
61
+ const source = context.sources.get(file);
62
+ const summary = context.summaries.find((item) => item.path === file);
63
+ if (!summary)
64
+ return null;
65
+ const validation = validateDocument(parseDocument(stripFrontmatter(source)), context.registry);
66
+ const previewHtml = renderStudioPreview(validation.document, (await options.previewComponents?.()) ?? {});
67
+ const stats = analyzeDocument(source, { path: file });
68
+ const page = context.index
69
+ ? [...context.index.pages.values()].find((entry) => entry.path === file)
70
+ : undefined;
71
+ return {
72
+ file: summary,
73
+ source,
74
+ frontmatter: context.frontmatter.get(file) ?? {},
75
+ stats,
76
+ findings: context.findings.filter((finding) => finding.file === file),
77
+ linksTo: page ? (page.linkRefs.length > 0 ? page.linkRefs : page.linksTo) : [],
78
+ linkedFrom: page
79
+ ? page.linkedFromRefs.length > 0
80
+ ? page.linkedFromRefs
81
+ : page.linkedFrom
82
+ : [],
83
+ previewHtml,
84
+ };
85
+ }
86
+ export async function scanGraph(options) {
87
+ const context = await scanContext(options);
88
+ if (!context.index)
89
+ return { nodes: [], edges: [] };
90
+ const summaryByPath = new Map(context.summaries.map((summary) => [summary.path, summary]));
91
+ const nodes = [...context.index.pages.values()].map((page) => ({
92
+ id: pageIdentity(page),
93
+ label: page.title ?? page.slug,
94
+ path: page.path,
95
+ status: summaryByPath.get(page.path)?.status ?? 'healthy',
96
+ slug: page.slug,
97
+ ...(page.key ? { key: page.key } : {}),
98
+ ...(page.locale ? { locale: page.locale } : {}),
99
+ }));
100
+ const pageByPath = new Map([...context.index.pages.values()].map((page) => [page.path, page]));
101
+ const edges = [];
102
+ for (const page of context.index.pages.values()) {
103
+ for (const ref of page.linkRefs) {
104
+ const target = [...context.index.pages.values()].find((candidate) => candidate.slug === ref.slug &&
105
+ candidate.key === ref.key &&
106
+ candidate.locale === ref.locale);
107
+ edges.push({
108
+ from: pageIdentity(page),
109
+ to: target ? pageIdentity(target) : undefined,
110
+ target: ref.target ?? ref.key ?? ref.slug,
111
+ status: target === page
112
+ ? 'self'
113
+ : ref.locale && ref.locale !== page.locale
114
+ ? 'cross-locale'
115
+ : 'resolved',
116
+ });
117
+ }
118
+ }
119
+ for (const finding of context.findings) {
120
+ if (finding.source !== 'links')
121
+ continue;
122
+ if (finding.code !== 'CB_LINK_UNRESOLVED' && finding.code !== 'CB_LINK_LOCALE_MISSING')
123
+ continue;
124
+ const page = pageByPath.get(finding.file);
125
+ if (!page)
126
+ continue;
127
+ edges.push({
128
+ from: pageIdentity(page),
129
+ target: targetFromMessage(finding.message) ?? 'unresolved',
130
+ status: 'unresolved',
131
+ });
132
+ }
133
+ return { nodes, edges };
134
+ }
135
+ async function scanContext(options) {
136
+ if (options.globs.length === 0)
137
+ throw new Error('studio: provide at least one file or glob.');
138
+ const cwd = options.cwd ?? process.cwd();
139
+ const files = (await glob(options.globs, { absolute: true, cwd })).sort();
140
+ if (files.length === 0)
141
+ throw new Error(`studio: no files matched ${options.globs.join(' ')}`);
142
+ const registry = await loadStudioRegistry(options.registryPath, cwd);
143
+ const sources = new Map();
144
+ const frontmatter = new Map();
145
+ const findings = [];
146
+ const summaries = [];
147
+ const linkInputs = [];
148
+ for (const file of files) {
149
+ const source = await readFile(file, 'utf8');
150
+ const fm = extractFrontmatter(source)?.data ?? {};
151
+ sources.set(file, source);
152
+ frontmatter.set(file, fm);
153
+ linkInputs.push({ path: file, data: fm });
154
+ const validation = validateDocument(parseDocument(stripFrontmatter(source)), registry);
155
+ for (const diagnostic of validation.diagnostics) {
156
+ findings.push(findingFromDiagnostic('validation', file, cwd, diagnostic));
157
+ }
158
+ const stats = analyzeDocument(source, { path: file });
159
+ findings.push(...statsFindings(file, cwd, stats, options.minSectionWords ?? DEFAULT_MIN_SECTION_WORDS));
160
+ summaries.push(fileSummary(file, cwd, fm, stats, findings.filter((finding) => finding.file === file), options));
161
+ }
162
+ let index;
163
+ if (hasLinkFrontmatter(linkInputs, options.linkOptions?.slugField)) {
164
+ for (const { file, diagnostic } of validateLinks(linkInputs, options.linkOptions)) {
165
+ findings.push(findingFromDiagnostic('links', file, cwd, diagnostic));
166
+ }
167
+ index = buildLinkIndex(linkInputs, options.linkOptions);
168
+ refreshSummaryFindings(summaries, findings);
169
+ }
170
+ findings.sort(compareFindings);
171
+ return { files, registry, sources, frontmatter, findings, summaries, linkInputs, index };
172
+ }
173
+ async function loadStudioRegistry(registryPath, cwd = process.cwd()) {
174
+ const registry = createBlockRegistry().use(genericBlocks());
175
+ if (!registryPath)
176
+ return registry;
177
+ const resolvedPath = isAbsolute(registryPath) ? registryPath : join(cwd, registryPath);
178
+ const mod = (await import(pathToFileURL(resolvedPath).href));
179
+ if (!Array.isArray(mod.default)) {
180
+ throw new Error(`--registry module must default-export an array of block definitions: ${resolvedPath}`);
181
+ }
182
+ registry.use(mod.default);
183
+ return registry;
184
+ }
185
+ function statsFindings(file, cwd, stats, minSectionWords) {
186
+ const findings = [];
187
+ for (const section of stats.outline) {
188
+ if (section.words < minSectionWords) {
189
+ findings.push({
190
+ severity: 'info',
191
+ source: 'stats',
192
+ code: 'CB_THIN_SECTION',
193
+ file,
194
+ relativePath: relativePath(cwd, file),
195
+ line: section.line,
196
+ column: 1,
197
+ message: `section "${section.text}" has ${section.words} words`,
198
+ hint: `Add detail or merge it with a nearby section. Threshold: ${minSectionWords} words.`,
199
+ });
200
+ }
201
+ }
202
+ if (stats.length.words >= BLOCKLESS_WORDS && stats.blocks.total === 0) {
203
+ findings.push({
204
+ severity: 'info',
205
+ source: 'stats',
206
+ code: 'CB_BLOCKLESS_DOCUMENT',
207
+ file,
208
+ relativePath: relativePath(cwd, file),
209
+ message: `document has ${stats.length.words} words and no structured blocks`,
210
+ hint: 'Consider a callout, steps, comparison, FAQ, or another registered block if it clarifies the page.',
211
+ });
212
+ }
213
+ if (stats.images.missingAlt > 0) {
214
+ findings.push({
215
+ severity: 'info',
216
+ source: 'stats',
217
+ code: 'CB_IMAGE_ALT_MISSING',
218
+ file,
219
+ relativePath: relativePath(cwd, file),
220
+ message: `${stats.images.missingAlt} image(s) are missing alt text`,
221
+ hint: 'Add descriptive alt text for meaningful images; use empty alt only for decorative images.',
222
+ });
223
+ }
224
+ return findings;
225
+ }
226
+ function findingFromDiagnostic(source, file, cwd, diagnostic) {
227
+ return {
228
+ severity: diagnostic.severity,
229
+ source,
230
+ code: diagnostic.code,
231
+ file,
232
+ relativePath: relativePath(cwd, file),
233
+ line: diagnostic.position.start.line,
234
+ column: diagnostic.position.start.column,
235
+ message: diagnostic.message,
236
+ ...(diagnostic.hint ? { hint: diagnostic.hint } : {}),
237
+ };
238
+ }
239
+ function fileSummary(file, cwd, frontmatter, stats, findings, options) {
240
+ const counts = summarize(findings);
241
+ const keywords = keywordData(frontmatter.keywords);
242
+ const slug = stringValue(frontmatter[options.linkOptions?.slugField ?? 'slug']);
243
+ const key = stringValue(frontmatter[options.linkOptions?.keyField ?? 'key']);
244
+ const locale = stringValue(frontmatter[options.linkOptions?.localeField ?? 'locale']);
245
+ return {
246
+ path: file,
247
+ relativePath: relativePath(cwd, file),
248
+ title: titleFor(file, frontmatter, stats),
249
+ ...(slug ? { slug } : {}),
250
+ ...(key ? { key } : {}),
251
+ ...(locale ? { locale } : {}),
252
+ ...(keywords ? { keywords } : {}),
253
+ words: stats.length.words,
254
+ readingMinutes: stats.length.readingMinutes,
255
+ blocks: stats.blocks.total,
256
+ blockNames: stats.blocks.byName,
257
+ links: stats.links.total,
258
+ externalLinks: stats.links.external,
259
+ missingAlt: stats.images.missingAlt,
260
+ findings: counts,
261
+ status: statusFor(counts),
262
+ };
263
+ }
264
+ function refreshSummaryFindings(summaries, findings) {
265
+ for (const summary of summaries) {
266
+ summary.findings = summarize(findings.filter((finding) => finding.file === summary.path));
267
+ summary.status = statusFor(summary.findings);
268
+ }
269
+ }
270
+ function titleFor(file, frontmatter, stats) {
271
+ return stringValue(frontmatter.title) ?? stats.outline[0]?.text ?? basename(file);
272
+ }
273
+ function keywordData(value) {
274
+ if (!value || typeof value !== 'object')
275
+ return undefined;
276
+ const record = value;
277
+ const primary = stringValue(record.primary);
278
+ const secondary = Array.isArray(record.secondary)
279
+ ? record.secondary.filter((item) => typeof item === 'string')
280
+ : undefined;
281
+ return primary || (secondary?.length ?? 0) > 0
282
+ ? { ...(primary ? { primary } : {}), ...(secondary ? { secondary } : {}) }
283
+ : undefined;
284
+ }
285
+ function summarize(findings) {
286
+ return {
287
+ errors: findings.filter((finding) => finding.severity === 'error').length,
288
+ warnings: findings.filter((finding) => finding.severity === 'warning').length,
289
+ suggestions: findings.filter((finding) => finding.severity === 'info').length,
290
+ };
291
+ }
292
+ function statusFor(findings) {
293
+ if (findings.errors > 0)
294
+ return 'error';
295
+ if (findings.warnings > 0)
296
+ return 'warning';
297
+ if (findings.suggestions > 0)
298
+ return 'suggestion';
299
+ return 'healthy';
300
+ }
301
+ function graphSummary(index) {
302
+ let links = 0;
303
+ for (const page of index.pages.values())
304
+ links += page.linksTo.length;
305
+ return {
306
+ pages: index.pages.size,
307
+ links,
308
+ orphans: [...index.pages.values()].filter((page) => page.linkedFrom.length === 0).length,
309
+ };
310
+ }
311
+ function hasLinkFrontmatter(inputs, configuredSlugField) {
312
+ const slugField = configuredSlugField ?? 'slug';
313
+ return inputs.some((input) => Object.prototype.hasOwnProperty.call(input.data, slugField));
314
+ }
315
+ function findAllowedFile(context, cwd, requestedPath) {
316
+ return (context.files.find((file) => file === requestedPath || relativePath(cwd, file) === requestedPath) ?? null);
317
+ }
318
+ function compareFindings(a, b) {
319
+ return (rank(a) - rank(b) ||
320
+ a.relativePath.localeCompare(b.relativePath) ||
321
+ (a.line ?? 0) - (b.line ?? 0) ||
322
+ (a.column ?? 0) - (b.column ?? 0) ||
323
+ a.code.localeCompare(b.code));
324
+ }
325
+ function rank(finding) {
326
+ if (finding.severity === 'error' && finding.source === 'validation')
327
+ return 0;
328
+ if (finding.severity === 'error' && finding.source === 'links')
329
+ return 1;
330
+ if (finding.severity === 'warning')
331
+ return 2;
332
+ if (finding.code === 'CB_THIN_SECTION')
333
+ return 3;
334
+ if (finding.code === 'CB_BLOCKLESS_DOCUMENT')
335
+ return 4;
336
+ if (finding.code === 'CB_IMAGE_ALT_MISSING')
337
+ return 5;
338
+ return 6;
339
+ }
340
+ function pageIdentity(page) {
341
+ return `${page.locale ?? ''}\0${page.key ?? page.slug}`;
342
+ }
343
+ function targetFromMessage(message) {
344
+ return message.match(/linksTo "([^"]+)"/)?.[1];
345
+ }
346
+ function stringValue(value) {
347
+ return typeof value === 'string' && value.trim().length > 0 ? value : undefined;
348
+ }
349
+ function relativePath(cwd, file) {
350
+ const rel = relative(cwd, file);
351
+ return rel.startsWith('..') ? file : rel;
352
+ }