Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions docs/config.md
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,28 @@ Controls how headings, lists and tables inside a node become embedded nodes, key
- **`tables`** — set to `true` to extract embedded table-row nodes (default `false`; markdown tables stay as node content).
- **`yamlBlocks`** — set to `true` to merge fenced `yaml` code blocks into node fields (default `false`; fenced `yaml` blocks stay as node content).

## JSON plugin config

Enable the built-in `json` plugin (`sctx-json`) per space under `plugins.json` to parse `.json` and `.json5` files (parsed with JSON5; a single node object or an array of node objects) and `.jsonl` files (one JSON node object per line) alongside markdown:

```json
{
"spaces": [
{
"name": "my-space",
"path": "/path/to/space",
"plugins": {
"json": {}
}
}
]
}
```

With an empty config (`{}`), the plugin scans the space's `path` for `**/*.json`, `**/*.json5`, and `**/*.jsonl`. Optional fields:

- **`path`** — directory or single `.json`/`.json5`/`.jsonl` file to read instead of the space's `path` (relative paths resolve from the config root).

## Filter views

Named filter expressions can be defined per space under `views`. Each view has an `expression` field:
Expand Down
1 change: 1 addition & 0 deletions src/plugins/builtin-names.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { normalizePluginName } from './util';
/** Names of the plugins bundled with structured-context. Each built-in plugin takes its `name` from here. */
export const BUILTIN_PLUGIN_NAMES = {
markdown: `${PLUGIN_PREFIX}markdown`,
json: `${PLUGIN_PREFIX}json`,
mermaid: `${PLUGIN_PREFIX}mermaid`,
mapViews: `${PLUGIN_PREFIX}map-views`,
miro: `${PLUGIN_PREFIX}miro`,
Expand Down
9 changes: 8 additions & 1 deletion src/plugins/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
import { jsonPlugin } from './json';
import { mapViewsPlugin } from './map-views';
import { markdownPlugin } from './markdown';
import { mermaidPlugin } from './mermaid';
import { miroPlugin } from './miro';
import type { StructuredContextPlugin } from './util';

/** All built-in plugins, in default load order. */
export const builtinPlugins: StructuredContextPlugin[] = [markdownPlugin, mermaidPlugin, miroPlugin, mapViewsPlugin];
export const builtinPlugins: StructuredContextPlugin[] = [
markdownPlugin,
jsonPlugin,
mermaidPlugin,
miroPlugin,
mapViewsPlugin,
];
208 changes: 208 additions & 0 deletions src/plugins/json/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
import { existsSync, readFileSync, statSync } from 'node:fs';
import { basename, isAbsolute, join, relative, resolve } from 'node:path';
import fg from 'fast-glob';
import type { FromSchema } from 'json-schema-to-ts';
import JSON5 from 'json5';
import type { BaseNode, NodeId, ParseIssue } from '../../types';
import { BUILTIN_PLUGIN_NAMES } from '../builtin-names';
import type { ParseOptions, ParseResult, PluginContext, StructuredContextPlugin } from '../util';

const JSON_GLOBS = ['**/*.json', '**/*.json5', '**/*.jsonl'];

const JSON_CONFIG_SCHEMA = {
type: 'object',
properties: {
path: { type: 'string', format: 'path' },
},
additionalProperties: false,
} as const;

type JsonPluginConfig = FromSchema<typeof JSON_CONFIG_SCHEMA>;

function isJsonFile(file: string): boolean {
const lower = file.toLowerCase();
return lower.endsWith('.json') || lower.endsWith('.json5') || lower.endsWith('.jsonl');
}

function isPlainObject(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}

function pathLinkTargets(file: string): string[] {
const segments = file
.replace(/\\/g, '/')
.replace(/\.json[5l]?$/i, '')
.split('/');
return segments.map((_, i) => segments.slice(i).join('/'));
}

function recordToNode(
raw: unknown,
file: string,
fallbackId: string,
line: number,
extraTargets: string[],
parseIssues: ParseIssue[],
): BaseNode | null {
if (!isPlainObject(raw)) {
parseIssues.push({
source: { file, line },
severity: 'warning',
type: 'no-type',
message: 'Expected a JSON object for node',
});
return null;
}

if (typeof raw.type !== 'string' || raw.type.trim() === '') {
parseIssues.push({
source: { file, line },
severity: 'warning',
type: 'no-type',
message: 'No type specified',
});
return null;
}

const explicitId = typeof raw.id === 'string' && raw.id.trim() !== '' ? raw.id : undefined;
const id = (explicitId ?? fallbackId) as NodeId;
const explicitTitle = typeof raw.title === 'string' ? raw.title : undefined;
const title = explicitTitle ?? (typeof raw.name === 'string' ? raw.name : id);

return {
id,
title,
schemaData: { title, ...raw },
linkTargets: [...new Set([id, ...(explicitTitle !== undefined ? [explicitTitle] : []), ...extraTargets])],
type: raw.type,
source: { file, line },
...(typeof raw.content === 'string' ? { content: raw.content } : {}),
};
}

function parseJsonFile(file: string, content: string, nodes: BaseNode[], parseIssues: ParseIssue[]): void {
const isJsonl = file.toLowerCase().endsWith('.jsonl');

if (isJsonl) {
const lines = content.split(/\r?\n/);
for (let i = 0; i < lines.length; i++) {
const trimmed = lines[i]!.trim();
if (!trimmed) continue;
const lineNumber = i + 1;
let parsed: unknown;
try {
parsed = JSON.parse(trimmed);
} catch (err) {
parseIssues.push({
source: { file, line: lineNumber },
severity: 'error',
type: 'parse',
message: err instanceof Error ? err.message : String(err),
});
continue;
}
const node = recordToNode(parsed, file, `${file}:${lineNumber}`, lineNumber, [], parseIssues);
if (node) nodes.push(node);
}
return;
}

let parsed: unknown;
try {
parsed = JSON5.parse(content);
} catch (err) {
parseIssues.push({
source: { file, line: 1 },
severity: 'error',
type: 'parse',
message: err instanceof Error ? err.message : String(err),
});
return;
}

if (Array.isArray(parsed)) {
for (let i = 0; i < parsed.length; i++) {
const node = recordToNode(parsed[i], file, `${file}#${i}`, 1, [], parseIssues);
if (node) nodes.push(node);
}
return;
}

const node = recordToNode(parsed, file, file, 1, pathLinkTargets(file), parseIssues);
if (node) nodes.push(node);
}

async function parse(context: PluginContext, options?: ParseOptions): Promise<ParseResult | null> {
const cfg = (context.pluginConfig ?? {}) as JsonPluginConfig;
const targetPath = cfg.path ?? context.space.path;
if (!existsSync(targetPath)) return null;

const stat = statSync(targetPath);
const nodes: BaseNode[] = [];
const parseIssues: ParseIssue[] = [];

if (stat.isFile()) {
if (!isJsonFile(targetPath)) return null;
if (options?.files !== undefined) {
const absTarget = resolve(targetPath);
const touched = options.files.some((rel) => resolve(context.space.path, rel) === absTarget);
if (!touched) return null;
}
const file = basename(targetPath);
const content = readFileSync(targetPath, 'utf-8');
parseJsonFile(file, content, nodes, parseIssues);
return {
nodes,
parseIssues,
diagnostics: { kind: 'file' },
...(options?.files !== undefined ? { partial: true } : {}),
};
}

const resolvedSchema = resolve(context.resolvedSchemaPath);
const absTarget = resolve(targetPath);
const isPartial = options?.files !== undefined;
let files: string[];

if (options?.files !== undefined) {
const relevant: string[] = [];
for (const rel of options.files) {
const abs = resolve(context.space.path, rel);
const relToTarget = relative(absTarget, abs).replace(/\\/g, '/');
if (relToTarget.startsWith('..') || isAbsolute(relToTarget)) continue;
if (!isJsonFile(relToTarget) || relToTarget.split('/').some((segment) => segment.startsWith('.'))) continue;
relevant.push(relToTarget);
}
if (relevant.length === 0) return null;
files = relevant.filter((rel) => {
const abs = resolve(targetPath, rel);
return abs !== resolvedSchema && existsSync(abs) && statSync(abs).isFile();
});
} else {
const found = await fg(JSON_GLOBS, {
cwd: targetPath,
followSymbolicLinks: true,
ignore: ['**/node_modules/**'],
});
files = found.filter((rel) => resolve(targetPath, rel) !== resolvedSchema);
if (files.length === 0) return null;
}

for (const file of files) {
const content = readFileSync(join(targetPath, file), 'utf-8');
parseJsonFile(file, content, nodes, parseIssues);
}

return {
nodes,
parseIssues,
diagnostics: { kind: 'directory' },
...(isPartial ? { partial: true } : {}),
};
}

export const jsonPlugin: StructuredContextPlugin = {
name: BUILTIN_PLUGIN_NAMES.json,
configSchema: JSON_CONFIG_SCHEMA,
parse,
};
1 change: 1 addition & 0 deletions src/plugins/markdown/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ export function getMarkdownConfig(plugins?: Record<string, Record<string, unknow

async function parse(context: PluginContext, options?: ParseOptions): Promise<ParseResult | null> {
if (statSync(context.space.path).isFile()) {
if (!context.space.path.toLowerCase().endsWith('.md')) return null;
return readSpaceOnAPage(context);
}
return await readSpaceDirectory(context, options?.files ? { files: options.files } : undefined);
Expand Down
91 changes: 82 additions & 9 deletions src/read/read-space.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { loadPlugins } from '../plugins/loader';
import type { ParseOptions, ParseResult } from '../plugins/util';
import { BUILTIN_PLUGIN_NAMES, isBuiltinPluginName } from '../plugins/builtin-names';
import { type LoadedPlugin, loadPlugins } from '../plugins/loader';
import { normalizePluginName, type ParseOptions, type ParseResult } from '../plugins/util';
import type { BaseNode, ReadSpaceResult, SpaceContext } from '../types';
import { resolveGraphEdges } from './resolve-graph-edges';

const MAX_PARSE_CONCURRENCY = 4;

function normalizeFile(file: string): string {
return file.replace(/\\/g, '/').replace(/^\.\//, '');
}
Expand All @@ -29,22 +32,92 @@ function toReadSpaceResult(
};
}

function hasParsedContent(result: ParseResult): boolean {
return result.nodes.length > 0 || result.parseIssues.length > 0 || (result.excludedPages?.length ?? 0) > 0;
}

async function runParseBatch(
plugins: LoadedPlugin[],
context: SpaceContext,
options?: ParseOptions,
): Promise<Array<{ name: string; result: ParseResult }>> {
const results: Array<{ name: string; result: ParseResult } | null> = new Array(plugins.length).fill(null);
let nextIndex = 0;

const worker = async (): Promise<void> => {
for (;;) {
const i = nextIndex++;
if (i >= plugins.length) return;
const { plugin, pluginConfig } = plugins[i]!;
const result = await plugin.parse!({ ...context, pluginConfig }, options);
if (result !== null) {
results[i] = { name: plugin.name, result };
}
}
};

const concurrency = Math.min(MAX_PARSE_CONCURRENCY, plugins.length);
await Promise.all(Array.from({ length: concurrency }, () => worker()));
return results.filter((entry): entry is { name: string; result: ParseResult } => entry !== null);
}

function mergeParseResults(matched: Array<{ name: string; result: ParseResult }>): {
source: string;
result: ParseResult;
} {
if (matched.length === 1) {
return { source: matched[0]!.name, result: matched[0]!.result };
}

const active = matched.filter((m) => hasParsedContent(m.result));
const sourceNames = (active.length > 0 ? active : matched).map((m) => m.name);
const excludedPages = matched.flatMap((m) => m.result.excludedPages ?? []);
const fieldSources = Object.assign({}, ...matched.map((m) => m.result.fieldSources ?? {}));
const diagnostics = Object.assign({}, ...matched.map((m) => m.result.diagnostics));

return {
source: sourceNames.join(', '),
result: {
nodes: matched.flatMap((m) => m.result.nodes),
parseIssues: matched.flatMap((m) => m.result.parseIssues),
...(excludedPages.length > 0 ? { excludedPages } : {}),
...(Object.keys(fieldSources).length > 0 ? { fieldSources } : {}),
diagnostics,
...(matched.every((m) => m.result.partial) ? { partial: true } : {}),
},
};
}

async function dispatchParse(
context: SpaceContext,
options?: ParseOptions,
): Promise<{ source: string; result: ParseResult }> {
const pluginMap: Record<string, Record<string, unknown>> = context.space?.plugins ?? {};
const loaded = await loadPlugins(pluginMap, context.configDir);
const configuredNames = new Set(Object.keys(pluginMap).map(normalizePluginName));

for (const { plugin, pluginConfig } of loaded) {
if (!plugin.parse) continue;
const result = await plugin.parse({ ...context, pluginConfig }, options);
if (result !== null) {
return { source: plugin.name, result };
}
const parsePlugins = loaded.filter((entry) => entry.plugin.parse);
const configured = parsePlugins.filter((entry) => configuredNames.has(entry.plugin.name));
const defaultMarkdown = parsePlugins.find((entry) => entry.plugin.name === BUILTIN_PLUGIN_NAMES.markdown);
const hasCustomConfigured = configured.some((entry) => !isBuiltinPluginName(entry.plugin.name));

// Configured parse plugins run in parallel and merge. Markdown is included automatically
// when no third-party parse plugin is configured, and acts as fallback if configured ones return null.
const primary =
!hasCustomConfigured && defaultMarkdown && !configuredNames.has(defaultMarkdown.plugin.name)
? [defaultMarkdown, ...configured]
: configured;

let matched = await runParseBatch(primary, context, options);
if (matched.length === 0 && defaultMarkdown && !primary.includes(defaultMarkdown)) {
matched = await runParseBatch([defaultMarkdown], context, options);
}

if (matched.length === 0) {
throw new Error(`No plugin handled space at: ${context.space.path}`);
}

throw new Error(`No plugin handled space at: ${context.space.path}`);
return mergeParseResults(matched);
}

export async function readSpace(context: SpaceContext): Promise<ReadSpaceResult> {
Expand Down
Loading