structured-context 0.11.0 → 0.12.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.
- package/README.md +63 -22
- package/dist/api.d.ts +7 -5
- package/dist/api.js +4 -1
- package/dist/commands/diagram.d.ts +1 -0
- package/dist/commands/diagram.js +7 -1
- package/dist/commands/dump.d.ts +15 -2
- package/dist/commands/dump.js +18 -4
- package/dist/commands/render.d.ts +4 -0
- package/dist/commands/render.js +64 -9
- package/dist/commands/schemas.d.ts +2 -2
- package/dist/commands/schemas.js +114 -22
- package/dist/commands/show.d.ts +1 -0
- package/dist/commands/show.js +7 -1
- package/dist/commands/spaces.d.ts +3 -1
- package/dist/commands/spaces.js +11 -2
- package/dist/commands/validate-file.js +7 -4
- package/dist/commands/validate.js +38 -21
- package/dist/config.d.ts +18 -1
- package/dist/config.js +81 -10
- package/dist/filter/augment-nodes.d.ts +3 -1
- package/dist/filter/augment-nodes.js +12 -7
- package/dist/filter/filter-nodes.js +1 -1
- package/dist/index.js +39 -15
- package/dist/load-space-graph.d.ts +4 -2
- package/dist/load-space-graph.js +15 -4
- package/dist/plugins/loader.js +2 -2
- package/dist/plugins/markdown/extract-content-links.js +8 -29
- package/dist/plugins/markdown/index.js +8 -2
- package/dist/plugins/markdown/parse-embedded.d.ts +6 -0
- package/dist/plugins/markdown/parse-embedded.js +41 -7
- package/dist/plugins/markdown/read-space.js +38 -5
- package/dist/plugins/markdown/render-directory.d.ts +11 -0
- package/dist/plugins/markdown/render-directory.js +130 -0
- package/dist/plugins/mermaid/render-mermaid.js +2 -1
- package/dist/plugins/miro/sync.js +7 -6
- package/dist/plugins/util.d.ts +39 -1
- package/dist/plugins/util.js +139 -0
- package/dist/read/resolve-graph-edges.d.ts +1 -1
- package/dist/read/resolve-graph-edges.js +46 -27
- package/dist/read/wikilink-utils.d.ts +17 -0
- package/dist/read/wikilink-utils.js +40 -0
- package/dist/render/render.d.ts +3 -1
- package/dist/render/render.js +2 -2
- package/dist/schema/meta-schemas.d.ts +13 -0
- package/dist/schema/meta-schemas.js +50 -0
- package/dist/schema/metadata-contract.d.ts +343 -187
- package/dist/schema/metadata-contract.js +68 -30
- package/dist/schema/schema.d.ts +14 -8
- package/dist/schema/schema.js +277 -198
- package/dist/schema/validate-graph.d.ts +2 -1
- package/dist/schema/validate-graph.js +40 -23
- package/dist/schema/validate-rules.d.ts +5 -1
- package/dist/schema/validate-rules.js +20 -1
- package/dist/schemas/_knowledge_wiki.json +20 -20
- package/dist/schemas/_ost_strict.json +2 -2
- package/dist/schemas/_sctx_base.json +2 -2
- package/dist/schemas/_strategy_general.json +38 -38
- package/dist/schemas/generated/0.12.0/_structured_context_schema_meta.json +229 -0
- package/dist/schemas/generated/latest/_structured_context_schema_meta.json +229 -0
- package/dist/schemas/knowledge_wiki.json +10 -9
- package/dist/schemas/strategy_general.json +15 -14
- package/dist/schemas/strict_ost.json +17 -16
- package/dist/space-context.d.ts +3 -0
- package/dist/space-context.js +7 -2
- package/dist/space-graph.d.ts +9 -7
- package/dist/space-graph.js +7 -5
- package/dist/testing.d.ts +33 -0
- package/dist/testing.js +72 -0
- package/dist/types.d.ts +54 -13
- package/dist/validate.d.ts +3 -0
- package/dist/validate.js +19 -9
- package/docs/concepts.md +14 -4
- package/docs/config.md +8 -0
- package/docs/rules.md +49 -22
- package/docs/schemas.md +110 -35
- package/package.json +13 -8
- package/schemas/_knowledge_wiki.json +20 -20
- package/schemas/_ost_strict.json +2 -2
- package/schemas/_sctx_base.json +2 -2
- package/schemas/_strategy_general.json +38 -38
- package/schemas/generated/0.12.0/_structured_context_schema_meta.json +229 -0
- package/schemas/generated/latest/_structured_context_schema_meta.json +229 -0
- package/schemas/knowledge_wiki.json +10 -9
- package/schemas/strategy_general.json +15 -14
- package/schemas/strict_ost.json +17 -16
- package/dist/schemas/generated/_structured_context_schema_meta.json +0 -191
- package/schemas/generated/_structured_context_schema_meta.json +0 -191
package/dist/schema/schema.js
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
|
2
|
-
import { basename, dirname, join, resolve } from 'node:path';
|
|
2
|
+
import { basename, dirname, extname, join, resolve } from 'node:path';
|
|
3
3
|
import { fileURLToPath } from 'node:url';
|
|
4
|
-
import
|
|
5
|
-
import Ajv, {} from 'ajv';
|
|
4
|
+
import Ajv2020 from 'ajv/dist/2020';
|
|
6
5
|
import JSON5 from 'json5';
|
|
7
|
-
import {
|
|
6
|
+
import { SCHEMA_URI_SCHEME } from '../constants';
|
|
7
|
+
import { shortenPluginName } from '../plugins/util';
|
|
8
|
+
import { loadMetaSchemas } from './meta-schemas';
|
|
9
|
+
import { METADATA_SCHEMA, } from './metadata-contract';
|
|
8
10
|
import { isObject, mergeVariantProperties, resolveJsonPointer } from './schema-refs';
|
|
9
11
|
const packageDir = import.meta.url ? dirname(fileURLToPath(import.meta.url)) : '';
|
|
10
12
|
export let bundledSchemasDir = packageDir ? join(packageDir, '..', '..', 'schemas') : '';
|
|
@@ -12,9 +14,95 @@ export let bundledSchemasDir = packageDir ? join(packageDir, '..', '..', 'schema
|
|
|
12
14
|
export function setBundledSchemasDir(dir) {
|
|
13
15
|
bundledSchemasDir = dir;
|
|
14
16
|
}
|
|
15
|
-
const validateMetadataContract = new
|
|
17
|
+
const validateMetadataContract = new Ajv2020().compile(METADATA_SCHEMA);
|
|
18
|
+
/** File stem of each schema read from disk — the default name of the hierarchy it declares. */
|
|
19
|
+
const schemaFileStems = new WeakMap();
|
|
16
20
|
export function readRawSchema(schemaPath) {
|
|
17
|
-
|
|
21
|
+
const schema = JSON5.parse(readFileSync(resolve(schemaPath), 'utf-8'));
|
|
22
|
+
rewriteLegacyCoreRefs(schema, schemaPath);
|
|
23
|
+
schemaFileStems.set(schema, basename(schemaPath, extname(schemaPath)));
|
|
24
|
+
return schema;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Schema `$id` namespaces. Every `$id` uses the `sctx://` scheme, and its shape says where the schema comes from:
|
|
28
|
+
* - `sctx://core/<name>` — bundled with structured-context
|
|
29
|
+
* - `sctx://<plugin>/<name>` — contributed by a plugin, prefixed with the plugin's short name
|
|
30
|
+
* - `sctx://<name>` — local to a space's schema directory (a single segment, no path)
|
|
31
|
+
*/
|
|
32
|
+
const SCTX_SCHEME = `${SCHEMA_URI_SCHEME}://`;
|
|
33
|
+
export const CORE_SCHEMA_PREFIX = `${SCTX_SCHEME}core/`;
|
|
34
|
+
/**
|
|
35
|
+
* Bundled schema `$id`s from before the `sctx://core/` namespace. References to them keep resolving
|
|
36
|
+
* (with a deprecation warning) until 1.0, and local schemas may not claim them.
|
|
37
|
+
*/
|
|
38
|
+
const LEGACY_CORE_IDS = new Set([
|
|
39
|
+
'_sctx_base',
|
|
40
|
+
'_ost_strict',
|
|
41
|
+
'_strategy_general',
|
|
42
|
+
'_knowledge_wiki',
|
|
43
|
+
'strict_ost',
|
|
44
|
+
'strategy_general',
|
|
45
|
+
'knowledge_wiki',
|
|
46
|
+
].map((name) => `${SCTX_SCHEME}${name}`));
|
|
47
|
+
const warnedLegacyIds = new Set();
|
|
48
|
+
function upgradeLegacyCoreRef(ref, schemaPath) {
|
|
49
|
+
const hashIndex = ref.indexOf('#');
|
|
50
|
+
const id = hashIndex === -1 ? ref : ref.slice(0, hashIndex);
|
|
51
|
+
if (!LEGACY_CORE_IDS.has(id))
|
|
52
|
+
return ref;
|
|
53
|
+
const upgraded = `${CORE_SCHEMA_PREFIX}${id.slice(SCTX_SCHEME.length)}`;
|
|
54
|
+
if (!warnedLegacyIds.has(id)) {
|
|
55
|
+
warnedLegacyIds.add(id);
|
|
56
|
+
console.warn(`Warning: "${id}" is deprecated and will stop resolving in 1.0; use "${upgraded}" instead (referenced in ${schemaPath}).`);
|
|
57
|
+
}
|
|
58
|
+
return hashIndex === -1 ? upgraded : `${upgraded}${ref.slice(hashIndex)}`;
|
|
59
|
+
}
|
|
60
|
+
/** Rewrite references to legacy bundled `$id`s (in `$ref` and `$metadata.imports`) to their `sctx://core/` form. */
|
|
61
|
+
function rewriteLegacyCoreRefs(node, schemaPath) {
|
|
62
|
+
if (Array.isArray(node)) {
|
|
63
|
+
for (const item of node)
|
|
64
|
+
rewriteLegacyCoreRefs(item, schemaPath);
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
if (!isObject(node))
|
|
68
|
+
return;
|
|
69
|
+
if (typeof node.$ref === 'string')
|
|
70
|
+
node.$ref = upgradeLegacyCoreRef(node.$ref, schemaPath);
|
|
71
|
+
if (isObject(node.$metadata) && Array.isArray(node.$metadata.imports)) {
|
|
72
|
+
node.$metadata.imports = node.$metadata.imports.map((entry) => typeof entry === 'string' ? upgradeLegacyCoreRef(entry, schemaPath) : entry);
|
|
73
|
+
}
|
|
74
|
+
for (const value of Object.values(node))
|
|
75
|
+
rewriteLegacyCoreRefs(value, schemaPath);
|
|
76
|
+
}
|
|
77
|
+
/** Throw if `id` doesn't belong to the namespace of the source it was loaded from. */
|
|
78
|
+
function assertIdNamespace(id, source) {
|
|
79
|
+
if (source.kind === 'core') {
|
|
80
|
+
if (!id.startsWith(CORE_SCHEMA_PREFIX)) {
|
|
81
|
+
throw new Error(`Bundled schema $id "${id}" must start with "${CORE_SCHEMA_PREFIX}".`);
|
|
82
|
+
}
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
const where = source.kind === 'plugin' ? `schema in plugin "${source.pluginName}"` : `local schema in "${source.dir}"`;
|
|
86
|
+
const expected = source.kind === 'plugin' ? `"${SCTX_SCHEME}${source.shortName}/<name>"` : `"${SCTX_SCHEME}<name>"`;
|
|
87
|
+
if (!id.startsWith(SCTX_SCHEME)) {
|
|
88
|
+
throw new Error(`Schema namespace violation: ${where} uses $id "${id}". Use the form ${expected}.`);
|
|
89
|
+
}
|
|
90
|
+
const segments = id.slice(SCTX_SCHEME.length).split('/');
|
|
91
|
+
if (source.kind === 'plugin') {
|
|
92
|
+
if (source.shortName === 'core') {
|
|
93
|
+
throw new Error(`Schema namespace violation: plugin "${source.pluginName}" can't contribute schemas; "core" is reserved for bundled schemas.`);
|
|
94
|
+
}
|
|
95
|
+
if (segments.length < 2 || segments[0] !== source.shortName) {
|
|
96
|
+
throw new Error(`Schema namespace violation: ${where} uses $id "${id}". Use the form ${expected}.`);
|
|
97
|
+
}
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
if (segments.length !== 1) {
|
|
101
|
+
throw new Error(`Schema namespace violation: ${where} uses $id "${id}". Local schema $ids are a single name, ${expected}; "${SCTX_SCHEME}<prefix>/..." is reserved for bundled ("core") and plugin schemas.`);
|
|
102
|
+
}
|
|
103
|
+
if (LEGACY_CORE_IDS.has(id)) {
|
|
104
|
+
throw new Error(`Schema namespace violation: ${where} uses $id "${id}", which is reserved as an alias for "${CORE_SCHEMA_PREFIX}${segments[0]}" until 1.0. Choose another name.`);
|
|
105
|
+
}
|
|
18
106
|
}
|
|
19
107
|
/**
|
|
20
108
|
* Build a registry of all schemas in the given directory, keyed by $id.
|
|
@@ -38,35 +126,65 @@ function buildSchemaRegistry(dir, targetFile) {
|
|
|
38
126
|
return schemaRefRegistry;
|
|
39
127
|
}
|
|
40
128
|
/**
|
|
41
|
-
* Build the full
|
|
129
|
+
* Build the full multi-layer registry for a schema path:
|
|
42
130
|
* - Layer 1: bundled schemas/ dir (partials only, as fallback)
|
|
43
|
-
* - Layer 2: schema
|
|
44
|
-
*
|
|
131
|
+
* - Layer 2: plugin schema dirs (partials + target file if schemaPath is in this plugin's schemasDir)
|
|
132
|
+
* - Layer 3: schema's own dir (partials + target file)
|
|
133
|
+
* Throws if a lower-precedence schema collides with a reserved $id or violates namespace rules.
|
|
45
134
|
*/
|
|
46
|
-
export function buildFullRegistry(schemaPath) {
|
|
135
|
+
export function buildFullRegistry(schemaPath, pluginSchemas) {
|
|
47
136
|
const absPath = resolve(schemaPath);
|
|
48
137
|
const targetFile = basename(absPath);
|
|
49
138
|
const targetDir = dirname(absPath);
|
|
50
139
|
const schemaRefRegistry = new Map();
|
|
51
140
|
// Layer 1: bundled schemas/ dir (partials only)
|
|
52
141
|
for (const [id, schema] of buildSchemaRegistry(bundledSchemasDir)) {
|
|
142
|
+
assertIdNamespace(id, { kind: 'core' });
|
|
53
143
|
schemaRefRegistry.set(id, schema);
|
|
54
144
|
}
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
145
|
+
const bundledIds = new Set(schemaRefRegistry.keys());
|
|
146
|
+
for (const id of loadMetaSchemas(bundledSchemasDir).keys())
|
|
147
|
+
bundledIds.add(id);
|
|
148
|
+
// Layer 2: plugin schema dirs
|
|
149
|
+
const pluginIds = new Map(); // id -> pluginName
|
|
150
|
+
if (pluginSchemas) {
|
|
151
|
+
for (const { schemasDir, pluginName } of pluginSchemas) {
|
|
152
|
+
if (!existsSync(schemasDir))
|
|
153
|
+
continue;
|
|
154
|
+
const isTargetDir = resolve(schemasDir) === targetDir;
|
|
155
|
+
const shortName = shortenPluginName(pluginName);
|
|
156
|
+
for (const [id, schema] of buildSchemaRegistry(schemasDir, isTargetDir ? targetFile : undefined)) {
|
|
157
|
+
if (bundledIds.has(id)) {
|
|
158
|
+
throw new Error(`Schema collision: schema in plugin "${pluginName}" (${schemasDir}) uses $id "${id}" which is reserved by a default schema. Please use a unique $id for plugin schemas.`);
|
|
159
|
+
}
|
|
160
|
+
const existingPlugin = pluginIds.get(id);
|
|
161
|
+
if (existingPlugin) {
|
|
162
|
+
throw new Error(`Schema collision: schema in plugin "${pluginName}" (${schemasDir}) uses $id "${id}" which is already defined by plugin "${existingPlugin}".`);
|
|
163
|
+
}
|
|
164
|
+
assertIdNamespace(id, { kind: 'plugin', pluginName, shortName });
|
|
165
|
+
schemaRefRegistry.set(id, schema);
|
|
166
|
+
pluginIds.set(id, pluginName);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
// Layer 3: schema's own dir (partials + target file)
|
|
171
|
+
const isPluginDir = pluginSchemas?.some((p) => resolve(p.schemasDir) === targetDir);
|
|
172
|
+
if (targetDir !== bundledSchemasDir && !isPluginDir) {
|
|
173
|
+
const reservedIds = new Set(schemaRefRegistry.keys());
|
|
174
|
+
for (const id of loadMetaSchemas(bundledSchemasDir).keys())
|
|
175
|
+
reservedIds.add(id);
|
|
59
176
|
for (const [id, schema] of buildSchemaRegistry(targetDir, targetFile)) {
|
|
60
|
-
if (
|
|
61
|
-
throw new Error(`Schema collision:
|
|
177
|
+
if (reservedIds.has(id)) {
|
|
178
|
+
throw new Error(`Schema collision: local schema in ${targetDir} uses $id "${id}", which is already defined by a bundled or plugin schema. Choose another name.`);
|
|
62
179
|
}
|
|
180
|
+
assertIdNamespace(id, { kind: 'local', dir: targetDir });
|
|
63
181
|
schemaRefRegistry.set(id, schema);
|
|
64
182
|
}
|
|
65
183
|
}
|
|
66
184
|
return schemaRefRegistry;
|
|
67
185
|
}
|
|
68
186
|
function compileValidator(targetSchema, schemaRefRegistry) {
|
|
69
|
-
const ajv = new
|
|
187
|
+
const ajv = new Ajv2020();
|
|
70
188
|
ajv.addFormat('path', (value) => value.length > 0 && !value.includes('\0'));
|
|
71
189
|
ajv.addFormat('date', (value) => /^\d{4}-\d{2}-\d{2}$/.test(value));
|
|
72
190
|
ajv.addFormat('wikilink', (value) => /^\[\[.+\]\]$/.test(value));
|
|
@@ -77,37 +195,39 @@ function compileValidator(targetSchema, schemaRefRegistry) {
|
|
|
77
195
|
valid: true,
|
|
78
196
|
errors: false,
|
|
79
197
|
});
|
|
80
|
-
const
|
|
81
|
-
|
|
198
|
+
const metaSchemas = loadMetaSchemas(bundledSchemasDir);
|
|
199
|
+
for (const schema of metaSchemas.values())
|
|
200
|
+
ajv.addSchema(schema);
|
|
82
201
|
// Register all except target schema (AJV compiles targetSchema explicitly)
|
|
83
202
|
for (const [id, schema] of schemaRefRegistry) {
|
|
84
|
-
if (id === targetSchema.$id || id
|
|
203
|
+
if (id === targetSchema.$id || metaSchemas.has(id))
|
|
85
204
|
continue;
|
|
86
205
|
ajv.addSchema(schema);
|
|
87
206
|
}
|
|
88
207
|
return ajv.compile(targetSchema);
|
|
89
208
|
}
|
|
90
|
-
export function createValidator(schemaPath) {
|
|
91
|
-
return compileValidator(readRawSchema(schemaPath), buildFullRegistry(schemaPath));
|
|
209
|
+
export function createValidator(schemaPath, pluginSchemas) {
|
|
210
|
+
return compileValidator(readRawSchema(schemaPath), buildFullRegistry(schemaPath, pluginSchemas));
|
|
92
211
|
}
|
|
93
212
|
export function resolveNodeType(type, typeAliases) {
|
|
94
213
|
return typeAliases?.[type] ?? type;
|
|
95
214
|
}
|
|
96
|
-
const RULE_CATEGORIES = new Set(['validation', 'coherence', 'workflow', 'best-practice']);
|
|
97
|
-
const RULE_ALLOWED_KEYS = new Set(['id', 'category', 'description', 'check', 'type', 'scope', 'override']);
|
|
98
215
|
function readTopLevelMetadata(schema) {
|
|
99
216
|
const metadata = schema.$metadata;
|
|
100
217
|
if (!isObject(metadata))
|
|
101
218
|
return undefined;
|
|
219
|
+
const schemaId = typeof schema.$id === 'string' ? schema.$id : '(unknown schema)';
|
|
220
|
+
if (isObject(metadata.hierarchy) && '$ref' in metadata.hierarchy && Object.keys(metadata.hierarchy).length > 1) {
|
|
221
|
+
throw new Error(`Invalid $metadata in schema "${schemaId}": hierarchy both declares levels and selects a hierarchy with "$ref". Use one or the other.`);
|
|
222
|
+
}
|
|
102
223
|
if (!validateMetadataContract(metadata)) {
|
|
103
|
-
const schemaId = typeof schema.$id === 'string' ? schema.$id : '(unknown schema)';
|
|
104
224
|
const errors = validateMetadataContract.errors?.map((e) => `${e.instancePath || '(root)'} ${e.message}`).join('; ') ??
|
|
105
225
|
'unknown error';
|
|
106
226
|
throw new Error(`Invalid $metadata in schema "${schemaId}": ${errors}`);
|
|
107
227
|
}
|
|
108
228
|
return metadata;
|
|
109
229
|
}
|
|
110
|
-
function
|
|
230
|
+
function resolveMetadataRef(ref, currentRootSchema, schemaRefRegistry) {
|
|
111
231
|
if (ref.startsWith('#')) {
|
|
112
232
|
const pointer = ref.slice(1);
|
|
113
233
|
const rootId = typeof currentRootSchema.$id === 'string' ? currentRootSchema.$id : '(root schema)';
|
|
@@ -130,180 +250,140 @@ function resolveRefTargetForRule(ref, currentRootSchema, schemaRefRegistry) {
|
|
|
130
250
|
refKey: `${baseId}#${pointer}`,
|
|
131
251
|
};
|
|
132
252
|
}
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
return;
|
|
139
|
-
for (const [key, child] of Object.entries(value)) {
|
|
140
|
-
if (key === '$ref' && typeof child === 'string' && !child.startsWith('#')) {
|
|
141
|
-
const schemaId = child.split('#', 1)[0] ?? child;
|
|
142
|
-
if (!seen.has(schemaId)) {
|
|
143
|
-
seen.add(schemaId);
|
|
144
|
-
refs.push(schemaId);
|
|
145
|
-
}
|
|
146
|
-
continue;
|
|
147
|
-
}
|
|
148
|
-
walk(child);
|
|
149
|
-
}
|
|
150
|
-
};
|
|
151
|
-
walk(schema);
|
|
152
|
-
return refs;
|
|
153
|
-
}
|
|
253
|
+
/**
|
|
254
|
+
* Collect metadata providers in merge order: each schema's `$metadata.imports` depth-first, in
|
|
255
|
+
* order, then the schema's own metadata. Each schema contributes at most once. `$ref` does not
|
|
256
|
+
* import metadata.
|
|
257
|
+
*/
|
|
154
258
|
function collectMetadataProviders(rootSchema, schemaRefRegistry) {
|
|
155
259
|
const providers = [];
|
|
156
|
-
const
|
|
157
|
-
const
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
if (!referencedSchema)
|
|
260
|
+
const rootSchemaId = typeof rootSchema.$id === 'string' ? rootSchema.$id : '(root schema)';
|
|
261
|
+
const visitedSchemaIds = new Set([rootSchemaId]);
|
|
262
|
+
const walk = (schema, schemaId) => {
|
|
263
|
+
const metadata = readTopLevelMetadata(schema);
|
|
264
|
+
if (!metadata)
|
|
265
|
+
return;
|
|
266
|
+
for (const importId of metadata.imports ?? []) {
|
|
267
|
+
if (visitedSchemaIds.has(importId))
|
|
165
268
|
continue;
|
|
166
|
-
|
|
167
|
-
const
|
|
168
|
-
if (
|
|
169
|
-
|
|
269
|
+
visitedSchemaIds.add(importId);
|
|
270
|
+
const importedSchema = schemaRefRegistry.get(importId);
|
|
271
|
+
if (!importedSchema) {
|
|
272
|
+
throw new Error(`Cannot resolve import "${importId}" in schema "${schemaId}".`);
|
|
170
273
|
}
|
|
274
|
+
walk(importedSchema, importId);
|
|
171
275
|
}
|
|
276
|
+
providers.push({ schemaId, schema, metadata });
|
|
172
277
|
};
|
|
173
|
-
walk(rootSchema);
|
|
174
|
-
const rootMetadata = readTopLevelMetadata(rootSchema);
|
|
175
|
-
if (rootMetadata) {
|
|
176
|
-
const rootSchemaId = typeof rootSchema.$id === 'string' ? rootSchema.$id : '(root schema)';
|
|
177
|
-
providers.push({ schemaId: rootSchemaId, schema: rootSchema, metadata: rootMetadata });
|
|
178
|
-
}
|
|
278
|
+
walk(rootSchema, rootSchemaId);
|
|
179
279
|
return providers;
|
|
180
280
|
}
|
|
181
|
-
function
|
|
281
|
+
function isRefEntry(value) {
|
|
182
282
|
if (!isObject(value))
|
|
183
283
|
return false;
|
|
184
284
|
return typeof value.$ref === 'string' && value.$ref.length > 0 && Object.keys(value).length === 1;
|
|
185
285
|
}
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
if (
|
|
193
|
-
|
|
194
|
-
if (typeof record.description !== 'string' || record.description.length === 0)
|
|
195
|
-
return false;
|
|
196
|
-
if (typeof record.check !== 'string' || record.check.length === 0)
|
|
197
|
-
return false;
|
|
198
|
-
if ('type' in record && (typeof record.type !== 'string' || record.type.length === 0))
|
|
199
|
-
return false;
|
|
200
|
-
if ('scope' in record && record.scope !== 'global')
|
|
201
|
-
return false;
|
|
202
|
-
if ('override' in record && typeof record.override !== 'boolean')
|
|
203
|
-
return false;
|
|
204
|
-
for (const key of Object.keys(record)) {
|
|
205
|
-
if (!RULE_ALLOWED_KEYS.has(key))
|
|
206
|
-
return false;
|
|
207
|
-
}
|
|
208
|
-
return true;
|
|
209
|
-
}
|
|
210
|
-
function resolveRuleEntries(ruleEntry, provider, schemaRefRegistry, stack) {
|
|
211
|
-
if (isMetadataRule(ruleEntry)) {
|
|
212
|
-
return [ruleEntry];
|
|
213
|
-
}
|
|
214
|
-
if (!isRuleRefEntry(ruleEntry)) {
|
|
215
|
-
throw new Error(`Invalid rule entry in metadata from "${provider.schemaId}".`);
|
|
216
|
-
}
|
|
217
|
-
const target = resolveRefTargetForRule(ruleEntry.$ref, provider.schema, schemaRefRegistry);
|
|
218
|
-
if (stack.has(target.refKey)) {
|
|
219
|
-
throw new Error(`Cyclic rule import detected while loading metadata from "${provider.schemaId}": ${[...stack, target.refKey].join(' -> ')}`);
|
|
220
|
-
}
|
|
221
|
-
stack.add(target.refKey);
|
|
222
|
-
try {
|
|
223
|
-
const value = target.value;
|
|
224
|
-
const resolveArray = (arr) => {
|
|
225
|
-
const resolvedRules = [];
|
|
226
|
-
for (const child of arr) {
|
|
227
|
-
if (!isObject(child)) {
|
|
228
|
-
throw new Error(`Invalid rule import target for "${ruleEntry.$ref}" from "${provider.schemaId}". Rule sets must contain objects.`);
|
|
229
|
-
}
|
|
230
|
-
resolvedRules.push(...resolveRuleEntries(child, { ...provider, schema: target.rootSchema }, schemaRefRegistry, stack));
|
|
231
|
-
}
|
|
232
|
-
return resolvedRules;
|
|
233
|
-
};
|
|
234
|
-
if (Array.isArray(value)) {
|
|
235
|
-
return resolveArray(value);
|
|
236
|
-
}
|
|
237
|
-
if (isObject(value) && 'rules' in value) {
|
|
238
|
-
const nestedRules = value.rules;
|
|
239
|
-
if (!Array.isArray(nestedRules)) {
|
|
240
|
-
throw new Error(`Invalid rule import target for "${ruleEntry.$ref}" from "${provider.schemaId}". "rules" must be an array.`);
|
|
241
|
-
}
|
|
242
|
-
return resolveArray(nestedRules);
|
|
243
|
-
}
|
|
244
|
-
if (isObject(value)) {
|
|
245
|
-
return resolveRuleEntries(value, { ...provider, schema: target.rootSchema }, schemaRefRegistry, stack);
|
|
246
|
-
}
|
|
247
|
-
throw new Error(`Invalid rule import target for "${ruleEntry.$ref}" from "${provider.schemaId}". Expected a rule object or rule set.`);
|
|
248
|
-
}
|
|
249
|
-
finally {
|
|
250
|
-
stack.delete(target.refKey);
|
|
286
|
+
/**
|
|
287
|
+
* The single metadata merge rule: a duplicate key is an error unless the later entry sets
|
|
288
|
+
* `override: true`, in which case it replaces the earlier one (keeping its position).
|
|
289
|
+
*/
|
|
290
|
+
function mergeEntry(merged, key, label, value, override, providerId) {
|
|
291
|
+
const existing = merged.get(key);
|
|
292
|
+
if (existing && override !== true) {
|
|
293
|
+
throw new Error(`Duplicate ${label} found in "${existing.providerId}" and "${providerId}". Set "override": true on the later one to replace it.`);
|
|
251
294
|
}
|
|
295
|
+
merged.set(key, { providerId, value });
|
|
252
296
|
}
|
|
253
|
-
function
|
|
254
|
-
|
|
255
|
-
return normalized;
|
|
256
|
-
}
|
|
257
|
-
function areRulesEquivalent(left, right) {
|
|
258
|
-
return isDeepStrictEqual(normalizeRule(left), normalizeRule(right));
|
|
297
|
+
function values(merged) {
|
|
298
|
+
return [...merged.values()].map(({ value }) => value);
|
|
259
299
|
}
|
|
260
300
|
function extractMetadata(schema, schemaRefRegistry) {
|
|
261
301
|
const metadataProviders = collectMetadataProviders(schema, schemaRefRegistry);
|
|
262
|
-
|
|
263
|
-
|
|
302
|
+
// Hierarchies are merged by name; the declaring object is kept so a root `hierarchy: { $ref }`
|
|
303
|
+
// selection can be matched to it.
|
|
304
|
+
const mergedHierarchies = new Map();
|
|
305
|
+
let rootHierarchy;
|
|
306
|
+
let mainSelection;
|
|
307
|
+
const mergedAliases = new Map();
|
|
264
308
|
const mergedRules = new Map();
|
|
265
|
-
const mergedRelationships =
|
|
309
|
+
const mergedRelationships = new Map();
|
|
266
310
|
for (const provider of metadataProviders) {
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
311
|
+
const { schemaId, metadata } = provider;
|
|
312
|
+
const declaredHierarchy = metadata.hierarchy;
|
|
313
|
+
const isRoot = provider.schema === schema;
|
|
314
|
+
if (isRefEntry(declaredHierarchy)) {
|
|
315
|
+
// A hierarchy selection only applies when its schema is the root; imported schemas contribute
|
|
316
|
+
// their declared hierarchies, not their selections.
|
|
317
|
+
if (isRoot)
|
|
318
|
+
mainSelection = declaredHierarchy;
|
|
271
319
|
}
|
|
272
|
-
if (
|
|
273
|
-
|
|
320
|
+
else if (declaredHierarchy) {
|
|
321
|
+
const hierarchy = normalizeHierarchy(declaredHierarchy, provider);
|
|
322
|
+
const label = `hierarchy "${hierarchy.name}"`;
|
|
323
|
+
mergeEntry(mergedHierarchies, hierarchy.name, label, { declared: declaredHierarchy, hierarchy }, declaredHierarchy.override, schemaId);
|
|
324
|
+
if (isRoot)
|
|
325
|
+
rootHierarchy = declaredHierarchy;
|
|
274
326
|
}
|
|
275
|
-
|
|
276
|
-
|
|
327
|
+
for (const [alias, target] of Object.entries(metadata.aliases ?? {})) {
|
|
328
|
+
const [type, override] = typeof target === 'string' ? [target, false] : [target.type, target.override];
|
|
329
|
+
mergeEntry(mergedAliases, alias, `alias "${alias}"`, type, override, schemaId);
|
|
277
330
|
}
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
continue;
|
|
286
|
-
}
|
|
287
|
-
if (incomingRule.override === true) {
|
|
288
|
-
mergedRules.set(incomingRule.id, { providerId: provider.schemaId, rule: incomingRule });
|
|
289
|
-
continue;
|
|
290
|
-
}
|
|
291
|
-
if (!areRulesEquivalent(existingRule.rule, incomingRule)) {
|
|
292
|
-
throw new Error(`Conflicting rule "${incomingRule.id}" found in "${existingRule.providerId}" and "${provider.schemaId}". Set "override": true on the later rule to replace it.`);
|
|
293
|
-
}
|
|
294
|
-
}
|
|
295
|
-
}
|
|
331
|
+
for (const rel of metadata.relationships ?? []) {
|
|
332
|
+
const field = rel.field ?? 'parent';
|
|
333
|
+
const label = `relationship "${rel.parent} → ${rel.type}" (field "${field}")`;
|
|
334
|
+
mergeEntry(mergedRelationships, `${rel.parent}\0${rel.type}\0${field}`, label, rel, rel.override, schemaId);
|
|
335
|
+
}
|
|
336
|
+
for (const rule of metadata.rules ?? []) {
|
|
337
|
+
mergeEntry(mergedRules, rule.id, `rule "${rule.id}"`, rule, rule.override, schemaId);
|
|
296
338
|
}
|
|
297
339
|
}
|
|
340
|
+
const merged = values(mergedHierarchies);
|
|
341
|
+
const allHierarchies = merged.map(({ hierarchy }) => hierarchy);
|
|
342
|
+
validateHierarchyTypes(allHierarchies);
|
|
343
|
+
const findDeclared = (declared) => merged.find((entry) => entry.declared === declared)?.hierarchy;
|
|
344
|
+
let mainHierarchy = rootHierarchy ? findDeclared(rootHierarchy) : undefined;
|
|
345
|
+
if (mainSelection) {
|
|
346
|
+
const target = resolveMetadataRef(mainSelection.$ref, schema, schemaRefRegistry);
|
|
347
|
+
mainHierarchy = findDeclared(target.value);
|
|
348
|
+
if (!mainHierarchy) {
|
|
349
|
+
throw new Error(`Hierarchy $ref "${mainSelection.$ref}" does not point to a hierarchy declared by an imported schema. Expected a ref like "<schema $id>#/$metadata/hierarchy".`);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
else if (!mainHierarchy && allHierarchies.length === 1) {
|
|
353
|
+
mainHierarchy = allHierarchies[0];
|
|
354
|
+
}
|
|
355
|
+
else if (!mainHierarchy && allHierarchies.length > 1) {
|
|
356
|
+
const rootSchemaId = typeof schema.$id === 'string' ? schema.$id : '(root schema)';
|
|
357
|
+
throw new Error(`Schema "${rootSchemaId}" imports multiple hierarchies (${allHierarchies.map((h) => `"${h.name}"`).join(', ')}) but selects none as its main hierarchy. Declare one, or select one with "hierarchy": { "$ref": "<schema $id>#/$metadata/hierarchy" }.`);
|
|
358
|
+
}
|
|
359
|
+
const typeAliases = Object.fromEntries([...mergedAliases].map(([alias, { value }]) => [alias, value]));
|
|
360
|
+
const rules = values(mergedRules).map(({ override, ...rule }) => rule);
|
|
361
|
+
const relationships = values(mergedRelationships);
|
|
298
362
|
// Collect valid type names from the schema's oneOf list for validation
|
|
299
363
|
const validTypeNames = extractSchemaTypeNames(schema, schemaRefRegistry);
|
|
300
|
-
// Validate
|
|
301
|
-
validateMetadataReferences({
|
|
364
|
+
// Validate metadata references against valid type names
|
|
365
|
+
validateMetadataReferences({ allHierarchies, typeAliases, rules }, validTypeNames);
|
|
302
366
|
// Filter relationships to only include those where both parent and child types are valid
|
|
303
|
-
const filteredRelationships =
|
|
367
|
+
const filteredRelationships = relationships.filter((rel) => {
|
|
304
368
|
return validTypeNames.has(rel.parent) && validTypeNames.has(rel.type);
|
|
305
369
|
});
|
|
306
|
-
|
|
370
|
+
return {
|
|
371
|
+
hierarchy: mainHierarchy,
|
|
372
|
+
hierarchies: allHierarchies.length > 0 ? allHierarchies : undefined,
|
|
373
|
+
typeAliases: Object.keys(typeAliases).length > 0 ? typeAliases : undefined,
|
|
374
|
+
rules: rules.length > 0 ? rules : undefined,
|
|
375
|
+
relationships: filteredRelationships.length > 0
|
|
376
|
+
? filteredRelationships.map(({ override, ...rel }) => ({
|
|
377
|
+
...rel,
|
|
378
|
+
field: rel.field ?? 'parent',
|
|
379
|
+
fieldOn: rel.fieldOn === 'parent' ? 'parent' : 'child',
|
|
380
|
+
multiple: rel.multiple ?? false,
|
|
381
|
+
}))
|
|
382
|
+
: undefined,
|
|
383
|
+
};
|
|
384
|
+
}
|
|
385
|
+
function normalizeHierarchy(declared, provider) {
|
|
386
|
+
const levels = declared.levels.map((entry) => {
|
|
307
387
|
if (typeof entry === 'string') {
|
|
308
388
|
return { type: entry, field: 'parent', fieldOn: 'child', multiple: false, selfRef: false };
|
|
309
389
|
}
|
|
@@ -322,24 +402,24 @@ function extractMetadata(schema, schemaRefRegistry) {
|
|
|
322
402
|
};
|
|
323
403
|
});
|
|
324
404
|
return {
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
allowSkipLevels: mergedHierarchy?.allowSkipLevels,
|
|
329
|
-
}
|
|
330
|
-
: undefined,
|
|
331
|
-
typeAliases: Object.keys(mergedAliases).length > 0 ? mergedAliases : undefined,
|
|
332
|
-
rules: mergedRules.size > 0 ? [...mergedRules.values()].map(({ rule }) => normalizeRule(rule)) : undefined,
|
|
333
|
-
relationships: filteredRelationships.length > 0
|
|
334
|
-
? filteredRelationships.map((rel) => ({
|
|
335
|
-
...rel,
|
|
336
|
-
field: rel.field ?? 'parent',
|
|
337
|
-
fieldOn: rel.fieldOn === 'parent' ? 'parent' : 'child',
|
|
338
|
-
multiple: rel.multiple ?? false,
|
|
339
|
-
}))
|
|
340
|
-
: undefined,
|
|
405
|
+
name: declared.name ?? schemaFileStems.get(provider.schema) ?? provider.schemaId,
|
|
406
|
+
levels,
|
|
407
|
+
allowSkipLevels: declared.allowSkipLevels,
|
|
341
408
|
};
|
|
342
409
|
}
|
|
410
|
+
/** Each type may belong to at most one hierarchy. */
|
|
411
|
+
function validateHierarchyTypes(hierarchies) {
|
|
412
|
+
const typeOwners = new Map();
|
|
413
|
+
for (const hierarchy of hierarchies) {
|
|
414
|
+
for (const { type } of hierarchy.levels) {
|
|
415
|
+
const owner = typeOwners.get(type);
|
|
416
|
+
if (owner !== undefined && owner !== hierarchy.name) {
|
|
417
|
+
throw new Error(`Type "${type}" belongs to both hierarchy "${owner}" and hierarchy "${hierarchy.name}". Each type may belong to at most one hierarchy.`);
|
|
418
|
+
}
|
|
419
|
+
typeOwners.set(type, hierarchy.name);
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
}
|
|
343
423
|
function validateMetadataReferences(metadata, validTypes) {
|
|
344
424
|
// Skip validation if no types are defined (e.g., schemas without oneOf or placeholder schemas)
|
|
345
425
|
if (validTypes.size === 0) {
|
|
@@ -347,23 +427,22 @@ function validateMetadataReferences(metadata, validTypes) {
|
|
|
347
427
|
}
|
|
348
428
|
const errors = [];
|
|
349
429
|
// Validate hierarchy level types
|
|
350
|
-
|
|
351
|
-
for (const
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
errors.push(`Hierarchy level "${typeName}" is not a valid type in the schema's oneOf list`);
|
|
430
|
+
for (const hierarchy of metadata.allHierarchies) {
|
|
431
|
+
for (const { type } of hierarchy.levels) {
|
|
432
|
+
if (!validTypes.has(type)) {
|
|
433
|
+
errors.push(`Hierarchy "${hierarchy.name}" level "${type}" is not a valid type in the schema's oneOf list`);
|
|
355
434
|
}
|
|
356
435
|
}
|
|
357
436
|
}
|
|
358
437
|
// Validate alias targets (the values)
|
|
359
|
-
for (const [alias, target] of Object.entries(metadata.
|
|
438
|
+
for (const [alias, target] of Object.entries(metadata.typeAliases)) {
|
|
360
439
|
if (!validTypes.has(target)) {
|
|
361
440
|
errors.push(`Alias "${alias}" → "${target}" references type "${target}" which is not in the schema's oneOf list`);
|
|
362
441
|
}
|
|
363
442
|
}
|
|
364
443
|
// Note: relationships are filtered (not validated) - see extractMetadata
|
|
365
444
|
// Validate rule types
|
|
366
|
-
for (const
|
|
445
|
+
for (const rule of metadata.rules) {
|
|
367
446
|
if (rule.type && !validTypes.has(rule.type)) {
|
|
368
447
|
errors.push(`Rule "${rule.id}" has type "${rule.type}" which is not in the schema's oneOf list`);
|
|
369
448
|
}
|
|
@@ -401,12 +480,12 @@ export function extractEntityInfo(schema, schemaRefRegistry) {
|
|
|
401
480
|
export function extractSchemaTypeNames(schema, schemaRefRegistry) {
|
|
402
481
|
return new Set(extractEntityInfo(schema, schemaRefRegistry).map((e) => e.type));
|
|
403
482
|
}
|
|
404
|
-
export function loadMetadata(schemaPath) {
|
|
405
|
-
return extractMetadata(readRawSchema(schemaPath), buildFullRegistry(schemaPath));
|
|
483
|
+
export function loadMetadata(schemaPath, pluginSchemas) {
|
|
484
|
+
return extractMetadata(readRawSchema(schemaPath), buildFullRegistry(schemaPath, pluginSchemas));
|
|
406
485
|
}
|
|
407
|
-
export function loadSchema(schemaPath) {
|
|
486
|
+
export function loadSchema(schemaPath, pluginSchemas) {
|
|
408
487
|
const rawSchema = readRawSchema(schemaPath);
|
|
409
|
-
const schemaRefRegistry = buildFullRegistry(schemaPath);
|
|
488
|
+
const schemaRefRegistry = buildFullRegistry(schemaPath, pluginSchemas);
|
|
410
489
|
const schema = {
|
|
411
490
|
...rawSchema,
|
|
412
491
|
metadata: extractMetadata(rawSchema, schemaRefRegistry),
|
|
@@ -3,6 +3,7 @@ export interface GraphValidationResult {
|
|
|
3
3
|
violations: GraphViolation[];
|
|
4
4
|
refErrors: Array<{
|
|
5
5
|
file: string;
|
|
6
|
+
line?: number;
|
|
6
7
|
parent: string;
|
|
7
8
|
error: string;
|
|
8
9
|
}>;
|
|
@@ -15,7 +16,7 @@ export declare function validateGraph(nodes: SpaceNode[], metadata: SchemaMetada
|
|
|
15
16
|
/**
|
|
16
17
|
* Validate that resolved parents follow hierarchy level rules and relationship type constraints.
|
|
17
18
|
*
|
|
18
|
-
* For hierarchy edges (fieldOn:'child', source:'hierarchy'): validates level ordering.
|
|
19
|
+
* For hierarchy edges (fieldOn:'child', source:'hierarchy'): validates level ordering within the edge's hierarchy.
|
|
19
20
|
* For relationship edges (fieldOn:'child', source:'relationship'): validates parent type.
|
|
20
21
|
* For fieldOn:'parent' edges: validates child type, violation attributed to the field-owner node.
|
|
21
22
|
*
|