@contentbit/studio 0.7.2 → 1.0.0-rc.1

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.
package/README.md CHANGED
@@ -50,5 +50,7 @@ contentbit studio <globs...> \
50
50
 
51
51
  The CLI binds `127.0.0.1` by default, starts at port `4377` and lets Vite choose
52
52
  the next free port, and opens the browser unless `--no-open` is passed.
53
+ `--port 0` picks any free port. The CLI warns when `--host` is not a loopback
54
+ address, because Studio is then reachable from your network.
53
55
  Studio loads the generic block definitions by default; pass `--no-generic-blocks`
54
56
  when your registry should own the full block set.
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"AAIA,OAAO,EAAqD,KAAK,aAAa,EAAE,MAAM,MAAM,CAAA;AAI5F,OAAO,KAAK,EAAE,kBAAkB,EAAiB,MAAM,YAAY,CAAA;AAEnE,YAAY,EACV,kBAAkB,EAClB,cAAc,EACd,iBAAiB,EACjB,aAAa,EACb,WAAW,EACX,aAAa,GACd,MAAM,YAAY,CAAA;AACnB,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,WAAW,CAAA;AAEhE,MAAM,WAAW,YAAY;IAC3B,GAAG,EAAE,MAAM,CAAA;IACX,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAA;IACtB,MAAM,EAAE,OAAO,CAAC,IAAI,CAAC,CAAA;IACrB,IAAI,EAAE,aAAa,CAAA;CACpB;AAED,wBAAsB,WAAW,CAAC,OAAO,EAAE,kBAAkB,GAAG,OAAO,CAAC,YAAY,CAAC,CA0DpF"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"AAMA,OAAO,EAA6B,KAAK,aAAa,EAAE,MAAM,MAAM,CAAA;AAIpE,OAAO,KAAK,EAAE,kBAAkB,EAAiB,MAAM,YAAY,CAAA;AAEnE,YAAY,EACV,kBAAkB,EAClB,cAAc,EACd,iBAAiB,EACjB,aAAa,EACb,WAAW,EACX,aAAa,GACd,MAAM,YAAY,CAAA;AACnB,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,WAAW,CAAA;AAEhE,MAAM,WAAW,YAAY;IAC3B,GAAG,EAAE,MAAM,CAAA;IACX,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAA;IACtB,MAAM,EAAE,OAAO,CAAC,IAAI,CAAC,CAAA;IACrB,IAAI,EAAE,aAAa,CAAA;CACpB;AAED,wBAAsB,WAAW,CAAC,OAAO,EAAE,kBAAkB,GAAG,OAAO,CAAC,YAAY,CAAC,CAyDpF"}
@@ -1,24 +1,28 @@
1
1
  // src/server/index.ts
2
2
  import { spawn } from "node:child_process";
3
- import { existsSync } from "node:fs";
3
+ import { existsSync as existsSync2 } from "node:fs";
4
+ import { createRequire } from "node:module";
5
+ import { createServer as createNetServer } from "node:net";
4
6
  import { dirname, isAbsolute as isAbsolute2, join as join2, resolve } from "node:path";
5
7
  import { fileURLToPath } from "node:url";
6
- import { createServer, searchForWorkspaceRoot } from "vite";
8
+ import { createServer } from "vite";
7
9
 
8
10
  // src/server/scan.ts
9
11
  import {
10
12
  compareContentProjectFindings,
11
- createLinkGraphView,
13
+ createLinkGraphView as createLinkGraphView2,
12
14
  createSeoBrief,
13
15
  readContentPageFacts,
14
- summarizeContentProjectFindings
16
+ summarizeContentProjectFindings as summarizeContentProjectFindings2
15
17
  } from "@contentbit/core";
16
18
 
17
19
  // ../project/dist/index.js
18
20
  import { genericBlocks } from "@contentbit/blocks";
19
- import { createBlockRegistry, scanContentProject } from "@contentbit/core";
21
+ import { createBlockRegistry, createLinkGraphView, discoverContentProject, scanContentProject, summarizeContentProjectFindings } from "@contentbit/core";
22
+ import { createHash } from "node:crypto";
23
+ import { existsSync } from "node:fs";
20
24
  import { readFile } from "node:fs/promises";
21
- import { isAbsolute, join } from "node:path";
25
+ import { isAbsolute, join, relative } from "node:path";
22
26
  import { pathToFileURL } from "node:url";
23
27
  import { glob } from "tinyglobby";
24
28
  var ProjectLoadError = class extends Error {
@@ -50,9 +54,12 @@ async function loadRegistry(registryPath, options = {}) {
50
54
  if (!registryPath)
51
55
  return registry;
52
56
  const resolvedPath = isAbsolute(registryPath) ? registryPath : join(options.cwd ?? process.cwd(), registryPath);
57
+ if (!existsSync(resolvedPath)) {
58
+ throw new ProjectLoadError(2, `Registry module not found: ${resolvedPath}`);
59
+ }
53
60
  let mod;
54
61
  try {
55
- mod = await import(pathToFileURL(resolvedPath).href);
62
+ mod = await importFresh(resolvedPath);
56
63
  } catch (err) {
57
64
  if (err instanceof Error && "code" in err && err.code === "ERR_UNKNOWN_FILE_EXTENSION") {
58
65
  throw new Error(`Importing a TypeScript registry needs Node 22.18+ (native type stripping): ${resolvedPath}`);
@@ -65,6 +72,14 @@ async function loadRegistry(registryPath, options = {}) {
65
72
  registry.use(mod.default);
66
73
  return registry;
67
74
  }
75
+ async function importFresh(path) {
76
+ const url = pathToFileURL(path);
77
+ const source = await readFile(path).catch(() => void 0);
78
+ if (source) {
79
+ url.searchParams.set("v", createHash("sha256").update(source).digest("hex").slice(0, 16));
80
+ }
81
+ return import(url.href);
82
+ }
68
83
  async function loadContentProject(input) {
69
84
  const files = await resolveContentFiles(input.positionals, input.cmd, {
70
85
  cwd: input.cwd,
@@ -84,7 +99,7 @@ async function loadContentProject(input) {
84
99
  }
85
100
 
86
101
  // src/server/scan.ts
87
- import { basename, relative } from "node:path";
102
+ import { basename, relative as relative2 } from "node:path";
88
103
 
89
104
  // src/server/preview.ts
90
105
  import { ContentBlocks } from "@contentbit/react";
@@ -202,7 +217,7 @@ async function scanGraph(options) {
202
217
  const context = await scanContext(options);
203
218
  if (!context.index) return { nodes: [], edges: [] };
204
219
  const summaryByPath = new Map(context.summaries.map((summary) => [summary.path, summary]));
205
- const view = createLinkGraphView(context.index, context.scan.linkDiagnostics ?? []);
220
+ const view = createLinkGraphView2(context.index, context.scan.linkDiagnostics ?? []);
206
221
  const nodes = view.nodes.map((node) => ({
207
222
  id: node.id,
208
223
  label: node.label,
@@ -295,7 +310,7 @@ function titleFor(file, frontmatter, stats) {
295
310
  return stringValue(frontmatter.title) ?? stats.outline[0]?.text ?? basename(file);
296
311
  }
297
312
  function summarize(findings) {
298
- return summarizeContentProjectFindings(findings);
313
+ return summarizeContentProjectFindings2(findings);
299
314
  }
300
315
  function statusFor(findings) {
301
316
  if (findings.errors > 0) return "error";
@@ -315,7 +330,7 @@ function stringValue(value) {
315
330
  return typeof value === "string" && value.trim().length > 0 ? value : void 0;
316
331
  }
317
332
  function relativePath(cwd, file) {
318
- const rel = relative(cwd, file);
333
+ const rel = relative2(cwd, file);
319
334
  return rel.startsWith("..") ? file : rel;
320
335
  }
321
336
 
@@ -368,9 +383,12 @@ function sendJson(res, status, body) {
368
383
  async function startStudio(options) {
369
384
  const root = findPackageRoot();
370
385
  const host = options.host ?? "127.0.0.1";
371
- const port = options.port ?? 4377;
386
+ const port = options.port === 0 ? await freePort(host) : options.port ?? 4377;
372
387
  const cwd = options.cwd ?? process.cwd();
373
- const fsAllow = [.../* @__PURE__ */ new Set([root, searchForWorkspaceRoot(root), cwd])];
388
+ const fontRoot = dirname(
389
+ createRequire(join2(root, "package.json")).resolve("@fontsource-variable/inter/package.json")
390
+ );
391
+ const fsAllow = [root, fontRoot];
374
392
  const apiOptions = {
375
393
  globs: options.globs,
376
394
  cwd,
@@ -413,7 +431,7 @@ async function startStudio(options) {
413
431
  async function loadProjectComponents(vite, options) {
414
432
  const merged = {};
415
433
  for (const candidate of componentCandidates(options)) {
416
- if (!existsSync(candidate.path)) continue;
434
+ if (!existsSync2(candidate.path)) continue;
417
435
  let mod;
418
436
  try {
419
437
  mod = await vite.ssrLoadModule(candidate.path);
@@ -464,10 +482,20 @@ function studioApiPlugin(options) {
464
482
  }
465
483
  };
466
484
  }
485
+ async function freePort(host) {
486
+ const server = createNetServer();
487
+ await new Promise((resolve2, reject) => {
488
+ server.once("error", reject);
489
+ server.listen(0, host, resolve2);
490
+ });
491
+ const { port } = server.address();
492
+ await new Promise((resolve2) => server.close(resolve2));
493
+ return port;
494
+ }
467
495
  function findPackageRoot() {
468
496
  let dir = dirname(fileURLToPath(import.meta.url));
469
497
  for (; ; ) {
470
- if (existsSync(join2(dir, "package.json"))) return dir;
498
+ if (existsSync2(join2(dir, "package.json"))) return dir;
471
499
  const next = dirname(dir);
472
500
  if (next === dir) throw new Error("Could not locate @contentbit/studio package root.");
473
501
  dir = next;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@contentbit/studio",
3
- "version": "0.7.2",
3
+ "version": "1.0.0-rc.1",
4
4
  "description": "Local read-only content studio for contentbit projects.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -30,9 +30,9 @@
30
30
  "dependencies": {
31
31
  "@fontsource-variable/inter": "^5.2.8",
32
32
  "@tailwindcss/vite": "^4",
33
- "@tanstack/react-router": "latest",
34
- "@tanstack/react-start": "latest",
35
- "@tanstack/router-plugin": "latest",
33
+ "@tanstack/react-router": "1.170.17",
34
+ "@tanstack/react-start": "1.168.27",
35
+ "@tanstack/router-plugin": "1.168.19",
36
36
  "@vitejs/plugin-react": "^6",
37
37
  "class-variance-authority": "^0.7.1",
38
38
  "clsx": "^2.1.1",
@@ -48,9 +48,9 @@
48
48
  "tinyglobby": "^0.2.10",
49
49
  "tw-animate-css": "^1.4.0",
50
50
  "vite": "^8",
51
- "@contentbit/blocks": "0.7.2",
52
- "@contentbit/core": "0.7.2",
53
- "@contentbit/react": "0.7.2"
51
+ "@contentbit/blocks": "1.0.0-rc.1",
52
+ "@contentbit/core": "1.0.0-rc.1",
53
+ "@contentbit/react": "1.0.0-rc.1"
54
54
  },
55
55
  "devDependencies": {
56
56
  "@testing-library/dom": "^10.4.1",
@@ -2,7 +2,7 @@ import * as React from 'react'
2
2
  import { cva, type VariantProps } from 'class-variance-authority'
3
3
  import { Slot } from 'radix-ui'
4
4
 
5
- import { cn } from '@/lib/utils'
5
+ import { cn } from '../../lib/utils'
6
6
 
7
7
  const buttonVariants = cva(
8
8
  "group/button inline-flex shrink-0 items-center justify-center rounded-lg border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
@@ -20,9 +20,9 @@ import {
20
20
  import type { ReactNode } from 'react'
21
21
  import { useEffect, useMemo, useState } from 'react'
22
22
 
23
- import { Button } from '@/components/ui/button'
24
- import { fetchDocument } from '@/lib/api'
25
- import type { StudioDocument, StudioFinding } from '@/server/types'
23
+ import { Button } from '../components/ui/button'
24
+ import { fetchDocument } from '../lib/api'
25
+ import type { StudioDocument, StudioFinding } from '../server/types'
26
26
 
27
27
  interface DocumentSearch {
28
28
  path: string
@@ -14,9 +14,9 @@ import {
14
14
  import type { ReactNode } from 'react'
15
15
  import { useEffect, useMemo, useState } from 'react'
16
16
 
17
- import { Button } from '@/components/ui/button'
18
- import { fetchGraph, fetchProject } from '@/lib/api'
19
- import type { StudioFileSummary, StudioGraph, StudioProject, StudioStatus } from '@/server/types'
17
+ import { Button } from '../components/ui/button'
18
+ import { fetchGraph, fetchProject } from '../lib/api'
19
+ import type { StudioFileSummary, StudioGraph, StudioProject, StudioStatus } from '../server/types'
20
20
 
21
21
  type StatusFilter = 'all' | StudioStatus
22
22
  type SortKey = 'document' | 'status' | 'blocks' | 'keywords' | 'findings'
@@ -1,8 +1,10 @@
1
1
  import { spawn } from 'node:child_process'
2
2
  import { existsSync } from 'node:fs'
3
+ import { createRequire } from 'node:module'
4
+ import { createServer as createNetServer, type AddressInfo } from 'node:net'
3
5
  import { dirname, isAbsolute, join, resolve } from 'node:path'
4
6
  import { fileURLToPath } from 'node:url'
5
- import { createServer, searchForWorkspaceRoot, type Plugin, type ViteDevServer } from 'vite'
7
+ import { createServer, type Plugin, type ViteDevServer } from 'vite'
6
8
  import type { BlockComponent } from '@contentbit/react'
7
9
 
8
10
  import { handleStudioApiRequest } from './api.js'
@@ -28,19 +30,18 @@ export interface StudioServer {
28
30
  export async function startStudio(options: StartStudioOptions): Promise<StudioServer> {
29
31
  const root = findPackageRoot()
30
32
  const host = options.host ?? '127.0.0.1'
31
- const port = options.port ?? 4377
33
+ // Vite treats port 0 as unset and falls back to 5173.
34
+ const port = options.port === 0 ? await freePort(host) : (options.port ?? 4377)
32
35
  const cwd = options.cwd ?? process.cwd()
33
- // Vite serves only files under `fs.allow`. We need:
34
- // - `root`: the Studio package itself (its built UI and source).
35
- // - `searchForWorkspaceRoot(root)`: the workspace that hoists Studio's deps,
36
- // so packaged fonts and other Vite-served dependency assets resolve when
37
- // Studio is installed into a monorepo.
38
- // - `cwd`: the consuming project, so Studio can read its content/blocks.
39
- // We deliberately do NOT add `searchForWorkspaceRoot(cwd)`: in a project with
40
- // no workspace marker, Vite walks up past the git root to the nearest ancestor
41
- // `package.json`, which can expose an unexpectedly broad directory over HTTP
42
- // (notably with `--host`).
43
- const fsAllow = [...new Set([root, searchForWorkspaceRoot(root), cwd])]
36
+ // Vite serves `/@fs/` files from `fs.allow` and the modules the UI imports.
37
+ // The UI reads the project only through /api/*, and previews and project
38
+ // components render on the server, so the list holds the Studio package and
39
+ // the font its stylesheet loads by url(). A project or workspace root here
40
+ // would serve every file under it, to the network with --host.
41
+ const fontRoot = dirname(
42
+ createRequire(join(root, 'package.json')).resolve('@fontsource-variable/inter/package.json'),
43
+ )
44
+ const fsAllow = [root, fontRoot]
44
45
  const apiOptions: StudioOptions = {
45
46
  globs: options.globs,
46
47
  cwd,
@@ -161,6 +162,17 @@ function studioApiPlugin(options: StudioOptions): Plugin {
161
162
  }
162
163
  }
163
164
 
165
+ async function freePort(host: string): Promise<number> {
166
+ const server = createNetServer()
167
+ await new Promise<void>((resolve, reject) => {
168
+ server.once('error', reject)
169
+ server.listen(0, host, resolve)
170
+ })
171
+ const { port } = server.address() as AddressInfo
172
+ await new Promise((resolve) => server.close(resolve))
173
+ return port
174
+ }
175
+
164
176
  function findPackageRoot(): string {
165
177
  let dir = dirname(fileURLToPath(import.meta.url))
166
178
  for (;;) {
@@ -383,6 +383,74 @@ test('startStudio serves read-only local API responses on port 0', async () => {
383
383
  expect(write.status).toBe(405)
384
384
  })
385
385
 
386
+ test('startStudio with port 0 listens on an OS-assigned port and reports it', async () => {
387
+ const dir = await fixture({ 'content/a.md': '# Alpha\n\nReadable body.\n' })
388
+ const server = await startStudio({ globs: ['content/*.md'], cwd: dir, port: 0, open: false })
389
+ runningServers.push(server)
390
+
391
+ const port = Number(new URL(server.url).port)
392
+ const project = await fetch(new URL('/api/project', server.url))
393
+
394
+ expect(project.status).toBe(200)
395
+ // Operating systems assign port 0 from their ephemeral range (32768 and up
396
+ // on Linux, 49152 and up on macOS and Windows). Vite's own fallback scans up
397
+ // from 5173, and Studio's default starts at 4377.
398
+ expect(port).toBeGreaterThanOrEqual(32768)
399
+ })
400
+
401
+ test('startStudio serves its UI fonts but not other project files', async () => {
402
+ const dir = await fixture({
403
+ 'content/a.md': '# Alpha\n\nReadable body.\n',
404
+ 'secrets.json': '{"token":"s3cret"}\n',
405
+ })
406
+ const server = await startStudio({ globs: ['content/*.md'], cwd: dir, port: 0, open: false })
407
+ runningServers.push(server)
408
+
409
+ const html = await (await fetch(server.url)).text()
410
+ const stylesheets = [...html.matchAll(/<link rel="stylesheet" href="([^"]+)"/g)].map((m) => m[1])
411
+ const css = await Promise.all(
412
+ stylesheets.map(async (href) => {
413
+ const response = await fetch(new URL(href, server.url), { headers: { accept: 'text/css' } })
414
+ return response.text()
415
+ }),
416
+ )
417
+ const fonts = css.flatMap((text) =>
418
+ [...text.matchAll(/url\(["']?([^"')]+\.woff2)/g)].map((m) => m[1]),
419
+ )
420
+ const fontStatuses = await Promise.all(
421
+ fonts.map(async (font) => (await fetch(new URL(font, server.url))).status),
422
+ )
423
+ const secret = await fetch(new URL(`/@fs${join(dir, 'secrets.json')}`, server.url))
424
+
425
+ expect(fonts.length).toBeGreaterThan(0)
426
+ expect(new Set(fontStatuses)).toEqual(new Set([200]))
427
+ expect(secret.status).toBe(403)
428
+ expect(await secret.text()).not.toContain('s3cret')
429
+ })
430
+
431
+ test('scanProject validates against the registry as it is on disk now', async () => {
432
+ const dir = await fixture({
433
+ 'blocks/registry.mjs': 'export default []\n',
434
+ 'content/a.md': '# Alpha\n\n:::shout\nHello there.\n:::\n',
435
+ })
436
+ await linkContentbitCore(dir)
437
+ const errors = async () =>
438
+ (
439
+ await scanProject({ globs: ['content/*.md'], cwd: dir, registryPath: 'blocks/registry.mjs' })
440
+ ).findings
441
+ .filter((finding) => finding.severity === 'error')
442
+ .map((finding) => finding.code)
443
+
444
+ expect(await errors()).toEqual(['CB_UNKNOWN_BLOCK'])
445
+ await writeFile(
446
+ join(dir, 'blocks/registry.mjs'),
447
+ `import { defineBlock, markdownBody } from '@contentbit/core'
448
+ export default [defineBlock({ name: 'shout', description: 'Shouts.', content: markdownBody() })]
449
+ `,
450
+ )
451
+ expect(await errors()).toEqual([])
452
+ })
453
+
386
454
  test('startStudio renders project block components from the registry folder', async () => {
387
455
  const dir = await fixture({
388
456
  'blocks/registry.mjs': `import { defineBlock, markdownBody } from '@contentbit/core'
@@ -444,6 +512,29 @@ slug: alpha
444
512
  expect(document.previewHtml).not.toContain('data-cb-custom="quote"')
445
513
  })
446
514
 
515
+ test('startStudio resolves copied renderers using the consuming project aliases', async () => {
516
+ const dir = await fixture({
517
+ 'tsconfig.json': JSON.stringify({
518
+ compilerOptions: { paths: { '@/*': ['./src/*'] } },
519
+ include: ['src/**/*.tsx'],
520
+ }),
521
+ 'src/components/content-blocks/content-renderer.tsx': `import { Callout } from '@/components/ui/project-callout'
522
+ export const styledComponents = { callout: Callout }
523
+ `,
524
+ 'src/components/ui/project-callout.tsx': `import { createElement } from 'react'
525
+ export function Callout() { return createElement('aside', { 'data-project-styled': 'callout' }, 'Project callout') }
526
+ `,
527
+ 'content/a.md': '# Alpha\n\n:::callout{type="tip"}\nUseful body.\n:::\n',
528
+ })
529
+ await linkContentbitCore(dir)
530
+ const server = await startStudio({ globs: ['content/*.md'], cwd: dir, port: 0, open: false })
531
+ runningServers.push(server)
532
+ const document = (await fetchJson(new URL('/api/document?path=content/a.md', server.url))) as {
533
+ previewHtml: string
534
+ }
535
+ expect(document.previewHtml).toContain('data-project-styled="callout"')
536
+ })
537
+
447
538
  async function fixture(files: Record<string, string>): Promise<string> {
448
539
  const dir = await mkdtemp(join(tmpdir(), 'cb-studio-'))
449
540
  for (const [path, content] of Object.entries(files)) {
package/vite.config.ts CHANGED
@@ -2,13 +2,12 @@ import { defineConfig } from 'vite'
2
2
  import { tanstackStart } from '@tanstack/react-start/plugin/vite'
3
3
  import viteReact from '@vitejs/plugin-react'
4
4
  import tailwindcss from '@tailwindcss/vite'
5
- import { fileURLToPath } from 'node:url'
6
5
 
7
6
  const config = defineConfig({
8
7
  resolve: {
9
- alias: {
10
- '@': fileURLToPath(new URL('./src', import.meta.url)),
11
- },
8
+ // Project preview components use their own tsconfig paths. Studio keeps its
9
+ // imports relative so the two applications do not share an alias namespace.
10
+ tsconfigPaths: true,
12
11
  },
13
12
  plugins: [tailwindcss(), tanstackStart(), viteReact()],
14
13
  })