docusaurus-plugin-generate-schema-docs 1.8.2 → 1.8.3

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.
@@ -1,11 +1,228 @@
1
- import React from 'react';
2
- import CodeBlock from '@theme/CodeBlock';
1
+ import React, { Fragment, useState } from 'react';
2
+ import Link from '@docusaurus/Link';
3
+
4
+ function isPlainObject(value) {
5
+ return (
6
+ value !== null &&
7
+ typeof value === 'object' &&
8
+ !Array.isArray(value) &&
9
+ Object.getPrototypeOf(value) === Object.prototype
10
+ );
11
+ }
12
+
13
+ function isExternalRef(value) {
14
+ return typeof value === 'string' && /^https?:\/\//.test(value);
15
+ }
16
+
17
+ function normalizePathSegments(pathValue) {
18
+ const normalized = pathValue.replace(/\\/g, '/');
19
+ const isAbsolute = normalized.startsWith('/');
20
+ const segments = normalized.split('/');
21
+ const resolvedSegments = [];
22
+
23
+ segments.forEach((segment) => {
24
+ if (!segment || segment === '.') return;
25
+ if (segment === '..') {
26
+ resolvedSegments.pop();
27
+ return;
28
+ }
29
+ resolvedSegments.push(segment);
30
+ });
31
+
32
+ return `${isAbsolute ? '/' : ''}${resolvedSegments.join('/')}`;
33
+ }
34
+
35
+ function dirname(pathValue) {
36
+ const normalized = normalizePathSegments(pathValue);
37
+ const segments = normalized.split('/');
38
+
39
+ if (segments.length <= 1) {
40
+ return normalized.startsWith('/') ? '/' : '.';
41
+ }
42
+
43
+ segments.pop();
44
+ const joined = segments.join('/');
45
+ return joined || '/';
46
+ }
47
+
48
+ function resolveLocalRef(currentPath, refValue) {
49
+ if (!currentPath || typeof refValue !== 'string') return null;
50
+ if (refValue.startsWith('#')) return null;
51
+ return normalizePathSegments(`${dirname(currentPath)}/${refValue}`);
52
+ }
53
+
54
+ function JsonIndent({ depth }) {
55
+ return <span>{' '.repeat(depth)}</span>;
56
+ }
57
+
58
+ function JsonPrimitive({
59
+ value,
60
+ propertyKey,
61
+ currentPath,
62
+ schemaSources,
63
+ onNavigate,
64
+ }) {
65
+ const interactiveRefClassName = 'schema-json-viewer__link';
66
+ const quotedValue = `${JSON.stringify(value)}`;
67
+
68
+ if (typeof value === 'string') {
69
+ if (propertyKey === '$ref') {
70
+ if (isExternalRef(value)) {
71
+ return (
72
+ <Link
73
+ className={interactiveRefClassName}
74
+ href={value}
75
+ target="_blank"
76
+ rel="noreferrer"
77
+ >
78
+ {quotedValue}
79
+ </Link>
80
+ );
81
+ }
82
+
83
+ const resolvedRef = resolveLocalRef(currentPath, value);
84
+ if (resolvedRef && schemaSources?.[resolvedRef]) {
85
+ return (
86
+ <button
87
+ type="button"
88
+ className={interactiveRefClassName}
89
+ onClick={() => onNavigate(resolvedRef)}
90
+ >
91
+ {quotedValue}
92
+ </button>
93
+ );
94
+ }
95
+ }
96
+
97
+ return <span className="token string">{quotedValue}</span>;
98
+ }
99
+
100
+ if (typeof value === 'number') {
101
+ return <span className="token number">{value}</span>;
102
+ }
103
+
104
+ if (typeof value === 'boolean') {
105
+ return <span className="token boolean">{String(value)}</span>;
106
+ }
107
+
108
+ return <span className="token null keyword">null</span>;
109
+ }
110
+
111
+ function JsonNode({
112
+ value,
113
+ depth,
114
+ currentPath,
115
+ schemaSources,
116
+ onNavigate,
117
+ propertyKey = null,
118
+ }) {
119
+ if (Array.isArray(value)) {
120
+ return (
121
+ <>
122
+ <span className="token punctuation">[</span>
123
+ {value.length > 0 && <br />}
124
+ {value.map((item, index) => (
125
+ <Fragment key={`${depth}-${index}`}>
126
+ <JsonIndent depth={depth + 1} />
127
+ <JsonNode
128
+ value={item}
129
+ depth={depth + 1}
130
+ currentPath={currentPath}
131
+ schemaSources={schemaSources}
132
+ onNavigate={onNavigate}
133
+ />
134
+ {index < value.length - 1 && (
135
+ <span className="token punctuation">,</span>
136
+ )}
137
+ <br />
138
+ </Fragment>
139
+ ))}
140
+ {value.length > 0 && <JsonIndent depth={depth} />}
141
+ <span className="token punctuation">]</span>
142
+ </>
143
+ );
144
+ }
145
+
146
+ if (isPlainObject(value)) {
147
+ const entries = Object.entries(value);
148
+ return (
149
+ <>
150
+ <span className="token punctuation">{'{'}</span>
151
+ {entries.length > 0 && <br />}
152
+ {entries.map(([key, child], index) => (
153
+ <Fragment key={`${depth}-${key}`}>
154
+ <JsonIndent depth={depth + 1} />
155
+ <span className="token property">{JSON.stringify(key)}</span>
156
+ <span className="token punctuation">: </span>
157
+ <JsonNode
158
+ value={child}
159
+ depth={depth + 1}
160
+ currentPath={currentPath}
161
+ schemaSources={schemaSources}
162
+ onNavigate={onNavigate}
163
+ propertyKey={key}
164
+ />
165
+ {index < entries.length - 1 && (
166
+ <span className="token punctuation">,</span>
167
+ )}
168
+ <br />
169
+ </Fragment>
170
+ ))}
171
+ {entries.length > 0 && <JsonIndent depth={depth} />}
172
+ <span className="token punctuation">{'}'}</span>
173
+ </>
174
+ );
175
+ }
176
+
177
+ return (
178
+ <JsonPrimitive
179
+ value={value}
180
+ propertyKey={propertyKey}
181
+ currentPath={currentPath}
182
+ schemaSources={schemaSources}
183
+ onNavigate={onNavigate}
184
+ />
185
+ );
186
+ }
187
+
188
+ export default function SchemaJsonViewer({
189
+ schema,
190
+ sourcePath = null,
191
+ schemaSources = null,
192
+ }) {
193
+ const resolvedSchemaSources =
194
+ schemaSources || (sourcePath ? { [sourcePath]: schema } : {});
195
+ const rootPath = sourcePath;
196
+ const [currentPath, setCurrentPath] = useState(rootPath);
197
+
198
+ const currentSchema =
199
+ (currentPath && resolvedSchemaSources?.[currentPath]) || schema;
3
200
 
4
- export default function SchemaJsonViewer({ schema }) {
5
201
  return (
6
202
  <details className="schema-json-viewer">
7
203
  <summary>View Raw JSON Schema</summary>
8
- <CodeBlock language="json">{JSON.stringify(schema, null, 2)}</CodeBlock>
204
+ {rootPath && currentPath !== rootPath ? (
205
+ <div className="schema-json-viewer__controls">
206
+ <button
207
+ type="button"
208
+ className="schema-json-viewer__link"
209
+ onClick={() => setCurrentPath(rootPath)}
210
+ >
211
+ Back to root
212
+ </button>
213
+ </div>
214
+ ) : null}
215
+ <pre data-language="json">
216
+ <code className="language-json">
217
+ <JsonNode
218
+ value={currentSchema}
219
+ depth={0}
220
+ currentPath={currentPath}
221
+ schemaSources={resolvedSchemaSources}
222
+ onNavigate={setCurrentPath}
223
+ />
224
+ </code>
225
+ </pre>
9
226
  </details>
10
227
  );
11
228
  }
@@ -1,4 +1,4 @@
1
- .required-row {
1
+ .property-cell--required {
2
2
  background-color: rgba(var(--ifm-color-danger-rgb), 0.05);
3
3
  }
4
4
 
@@ -26,6 +26,26 @@
26
26
  margin-bottom: 1em;
27
27
  }
28
28
 
29
+ .schema-json-viewer__controls {
30
+ margin: 0.5rem 0;
31
+ }
32
+
33
+ .schema-json-viewer__link {
34
+ appearance: none;
35
+ background: none;
36
+ border: none;
37
+ color: var(--ifm-link-color);
38
+ cursor: pointer;
39
+ font: inherit;
40
+ padding: 0;
41
+ text-decoration: none;
42
+ }
43
+
44
+ .schema-json-viewer__link:hover {
45
+ color: var(--ifm-link-hover-color);
46
+ text-decoration: underline;
47
+ }
48
+
29
49
  /* --- Property Name and Container Symbol Styles --- */
30
50
 
31
51
  .property-name {
@@ -34,6 +54,61 @@
34
54
  gap: 4px;
35
55
  }
36
56
 
57
+ .property-name--keyword {
58
+ align-items: center;
59
+ }
60
+
61
+ .property-keyword-wrapper {
62
+ position: relative;
63
+ display: inline-flex;
64
+ align-items: center;
65
+ }
66
+
67
+ .property-keyword-stack {
68
+ display: inline-flex;
69
+ flex-direction: column;
70
+ align-items: flex-start;
71
+ gap: 0.2rem;
72
+ }
73
+
74
+ .property-keyword {
75
+ font-size: 0.95em;
76
+ font-weight: 600;
77
+ }
78
+
79
+ .property-keyword-pattern {
80
+ font-size: 0.85em;
81
+ color: var(--ifm-color-emphasis-700);
82
+ }
83
+
84
+ .property-keyword-tooltip {
85
+ position: absolute;
86
+ left: 0;
87
+ bottom: calc(100% + 0.4rem);
88
+ z-index: 3;
89
+ min-width: 14rem;
90
+ max-width: 18rem;
91
+ padding: 0.5rem 0.625rem;
92
+ border-radius: 0.375rem;
93
+ background: var(--ifm-background-surface-color);
94
+ border: 1px solid var(--ifm-table-border-color);
95
+ box-shadow: var(--ifm-global-shadow-lw);
96
+ color: var(--ifm-font-color-base);
97
+ font-size: 0.8rem;
98
+ line-height: 1.35;
99
+ opacity: 0;
100
+ pointer-events: none;
101
+ transform: translateY(0.125rem);
102
+ transition:
103
+ opacity 120ms ease,
104
+ transform 120ms ease;
105
+ }
106
+
107
+ .property-keyword-wrapper:hover .property-keyword-tooltip {
108
+ opacity: 1;
109
+ transform: translateY(0);
110
+ }
111
+
37
112
  .container-symbol {
38
113
  font-family: var(--ifm-font-family-monospace);
39
114
  font-size: 0.9em;
@@ -67,6 +142,10 @@
67
142
  border-left: none;
68
143
  }
69
144
 
145
+ .schema-table td[colspan='5'] {
146
+ border-left: none;
147
+ }
148
+
70
149
  /*
71
150
  * Constraint-only continuation rows render a single cell; in those rows that
72
151
  * cell is also :first-child, but it still needs the separator before the
@@ -85,6 +164,18 @@
85
164
  box-shadow: inset 0 1px 0 var(--ifm-table-border-color);
86
165
  }
87
166
 
167
+ .schema-table tbody tr.schema-row--zebra-even {
168
+ background-color: var(--ifm-table-stripe-background);
169
+ }
170
+
171
+ .schema-table tbody tr.schema-row--zebra-odd {
172
+ background-color: transparent;
173
+ }
174
+
175
+ .schema-table tbody tr.schema-row--control {
176
+ background-color: transparent;
177
+ }
178
+
88
179
  /* --- Organigram Connector Line Styles --- */
89
180
 
90
181
  /*
@@ -108,10 +199,12 @@ td.has-children {
108
199
  td[class*='level-']::before {
109
200
  content: '';
110
201
  position: absolute;
111
- top: 0;
112
- bottom: 0;
202
+ top: -1px;
203
+ bottom: -1px;
113
204
  width: 0;
114
205
  border-left: 1px solid var(--ifm-table-border-color);
206
+ z-index: 1;
207
+ pointer-events: none;
115
208
  }
116
209
 
117
210
  /* Last items: stop vertical line at middle */
@@ -130,6 +223,8 @@ td[class*='level-']::after {
130
223
  height: 0;
131
224
  width: 0.75rem;
132
225
  border-bottom: 1px solid var(--ifm-table-border-color);
226
+ z-index: 1;
227
+ pointer-events: none;
133
228
  }
134
229
 
135
230
  /* --- Level-based positioning --- */
@@ -172,10 +267,6 @@ td.level-6::after {
172
267
 
173
268
  /* --- Choice Row Styles --- */
174
269
 
175
- .choice-row {
176
- background-color: var(--ifm-table-stripe-background);
177
- }
178
-
179
270
  .choice-row:hover {
180
271
  background-color: var(--ifm-hover-overlay);
181
272
  }
@@ -12,7 +12,11 @@ import ConditionalRows from './ConditionalRows';
12
12
  * @param {Array} props.tableData - Flat array of row objects
13
13
  * @param {Array} [props.bracketEnds] - Bracket descriptors that end on the last row
14
14
  */
15
- export default function SchemaRows({ tableData, bracketEnds }) {
15
+ export default function SchemaRows({
16
+ tableData,
17
+ bracketEnds,
18
+ stripeState = { current: 0 },
19
+ }) {
16
20
  if (!tableData) {
17
21
  return null;
18
22
  }
@@ -20,12 +24,15 @@ export default function SchemaRows({ tableData, bracketEnds }) {
20
24
  return tableData.map((row, index) => {
21
25
  const key = row.path.join('.');
22
26
  const isLast = index === tableData.length - 1;
27
+ const stripeIndex = stripeState.current++;
23
28
 
24
29
  if (row.type === 'choice') {
25
30
  return (
26
31
  <FoldableRows
27
32
  key={key}
28
33
  row={row}
34
+ stripeIndex={stripeIndex}
35
+ stripeState={stripeState}
29
36
  bracketEnds={isLast ? bracketEnds : undefined}
30
37
  />
31
38
  );
@@ -36,6 +43,8 @@ export default function SchemaRows({ tableData, bracketEnds }) {
36
43
  <ConditionalRows
37
44
  key={key}
38
45
  row={row}
46
+ stripeIndex={stripeIndex}
47
+ stripeState={stripeState}
39
48
  bracketEnds={isLast ? bracketEnds : undefined}
40
49
  />
41
50
  );
@@ -46,6 +55,7 @@ export default function SchemaRows({ tableData, bracketEnds }) {
46
55
  <PropertyRow
47
56
  key={key}
48
57
  row={row}
58
+ stripeIndex={stripeIndex}
49
59
  isLastInGroup={row.isLastInGroup}
50
60
  bracketEnds={isLast ? bracketEnds : undefined}
51
61
  />
@@ -1,7 +1,12 @@
1
1
  import path from 'path';
2
2
  import fs from 'fs';
3
3
  import { getPathsForVersion } from './helpers/path-helpers.js';
4
- import { readSchemas, writeDoc, createDir } from './helpers/file-system.js';
4
+ import {
5
+ readSchemas,
6
+ readSchemaSources,
7
+ writeDoc,
8
+ createDir,
9
+ } from './helpers/file-system.js';
5
10
  import { processOneOfSchema, slugify } from './helpers/schema-processing.js';
6
11
  import SchemaDocTemplate from './helpers/schema-doc-template.js';
7
12
  import ChoiceIndexTemplate from './helpers/choice-index-template.js';
@@ -37,6 +42,64 @@ function resolvePartial({
37
42
  };
38
43
  }
39
44
 
45
+ function isPlainObject(value) {
46
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
47
+ }
48
+
49
+ function toSchemaSourceKey(schemaDir, filePath) {
50
+ return path.relative(schemaDir, filePath).split(path.sep).join('/');
51
+ }
52
+
53
+ function resolveLocalSchemaRef(currentPath, ref) {
54
+ if (!ref || ref.startsWith('#') || /^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(ref)) {
55
+ return null;
56
+ }
57
+
58
+ const [fileRef] = ref.split('#');
59
+ return path
60
+ .normalize(path.join(path.dirname(currentPath), fileRef))
61
+ .split(path.sep)
62
+ .join('/');
63
+ }
64
+
65
+ function collectReachableSchemaSources(sourcePath, allSchemaSources) {
66
+ if (!sourcePath || !allSchemaSources[sourcePath]) return {};
67
+
68
+ const visited = new Set();
69
+ const reachableSources = {};
70
+
71
+ function walkSchema(currentPath) {
72
+ if (visited.has(currentPath) || !allSchemaSources[currentPath]) return;
73
+ visited.add(currentPath);
74
+
75
+ const schema = allSchemaSources[currentPath];
76
+ reachableSources[currentPath] = schema;
77
+
78
+ function walkNode(node) {
79
+ if (Array.isArray(node)) {
80
+ node.forEach(walkNode);
81
+ return;
82
+ }
83
+
84
+ if (!isPlainObject(node)) return;
85
+
86
+ if (typeof node.$ref === 'string') {
87
+ const resolvedRefPath = resolveLocalSchemaRef(currentPath, node.$ref);
88
+ if (resolvedRefPath) {
89
+ walkSchema(resolvedRefPath);
90
+ }
91
+ }
92
+
93
+ Object.values(node).forEach(walkNode);
94
+ }
95
+
96
+ walkNode(schema);
97
+ }
98
+
99
+ walkSchema(sourcePath);
100
+ return reachableSources;
101
+ }
102
+
40
103
  async function collectLeafEventNames(schema, filePath, eventNames) {
41
104
  if (!schema.oneOf) {
42
105
  eventNames.push(path.basename(filePath, '.json'));
@@ -86,6 +149,8 @@ async function generateAndWriteDoc(
86
149
  alreadyMergedSchema = null,
87
150
  editFilePath = null,
88
151
  partialNameConflicts = new Set(),
152
+ schemaSources = {},
153
+ schemaDir,
89
154
  ) {
90
155
  const { organizationName, projectName, siteDir, dataLayerName, version } =
91
156
  options;
@@ -134,6 +199,11 @@ async function generateAndWriteDoc(
134
199
  topPartialComponent: top.component,
135
200
  bottomPartialComponent: bottom.component,
136
201
  dataLayerName,
202
+ sourcePath: toSchemaSourceKey(schemaDir, editFilePath || filePath),
203
+ schemaSources: collectReachableSchemaSources(
204
+ toSchemaSourceKey(schemaDir, editFilePath || filePath),
205
+ schemaSources,
206
+ ),
137
207
  });
138
208
 
139
209
  const outputFilename = path.basename(filePath).replace('.json', '.mdx');
@@ -147,6 +217,8 @@ async function generateOneOfDocs(
147
217
  outputDir,
148
218
  options,
149
219
  partialNameConflicts,
220
+ schemaSources,
221
+ schemaDir,
150
222
  ) {
151
223
  const { organizationName, projectName, siteDir } = options;
152
224
  const editUrl = buildEditUrl(
@@ -165,6 +237,11 @@ async function generateOneOfDocs(
165
237
  schema,
166
238
  processedOptions: processed,
167
239
  editUrl,
240
+ sourcePath: toSchemaSourceKey(schemaDir, filePath),
241
+ schemaSources: collectReachableSchemaSources(
242
+ toSchemaSourceKey(schemaDir, filePath),
243
+ schemaSources,
244
+ ),
168
245
  });
169
246
  writeDoc(eventOutputDir, 'index.mdx', indexPageContent);
170
247
 
@@ -183,6 +260,8 @@ async function generateOneOfDocs(
183
260
  eventOutputDir,
184
261
  options,
185
262
  partialNameConflicts,
263
+ schemaSources,
264
+ schemaDir,
186
265
  );
187
266
  } else {
188
267
  await generateAndWriteDoc(
@@ -194,6 +273,8 @@ async function generateOneOfDocs(
194
273
  processedSchema,
195
274
  sourceFilePath || filePath,
196
275
  partialNameConflicts,
276
+ schemaSources,
277
+ schemaDir,
197
278
  );
198
279
  }
199
280
  }
@@ -205,6 +286,7 @@ export default async function generateEventDocs(options) {
205
286
 
206
287
  createDir(outputDir);
207
288
  const schemas = readSchemas(schemaDir);
289
+ const schemaSources = readSchemaSources(schemaDir);
208
290
  const partialNameConflicts = await getPartialNameConflicts(schemas);
209
291
 
210
292
  console.log(`🚀 Generating documentation for ${schemas.length} schemas...`);
@@ -229,6 +311,8 @@ export default async function generateEventDocs(options) {
229
311
  outputDir,
230
312
  options,
231
313
  partialNameConflicts,
314
+ schemaSources,
315
+ schemaDir,
232
316
  );
233
317
  } else {
234
318
  await generateAndWriteDoc(
@@ -240,6 +324,8 @@ export default async function generateEventDocs(options) {
240
324
  null,
241
325
  null,
242
326
  partialNameConflicts,
327
+ schemaSources,
328
+ schemaDir,
243
329
  );
244
330
  }
245
331
  }
@@ -1,5 +1,5 @@
1
1
  export default function ChoiceIndexTemplate(data) {
2
- const { schema, processedOptions, editUrl } = data;
2
+ const { schema, processedOptions, editUrl, sourcePath, schemaSources } = data;
3
3
 
4
4
  return `---
5
5
  title: ${schema.title}
@@ -18,6 +18,10 @@ ${processedOptions
18
18
  .map((option) => `- [${option.schema.title}](./${option.slug})`)
19
19
  .join('\n')}
20
20
 
21
- <SchemaJsonViewer schema={${JSON.stringify(schema)}} />
21
+ <SchemaJsonViewer
22
+ schema={${JSON.stringify(schema)}}
23
+ sourcePath={${JSON.stringify(sourcePath)}}
24
+ schemaSources={${JSON.stringify(schemaSources)}}
25
+ />
22
26
  `;
23
27
  }
@@ -23,6 +23,34 @@ export function readSchemas(directory) {
23
23
  });
24
24
  }
25
25
 
26
+ export function readSchemaSources(directory) {
27
+ const schemaSources = {};
28
+
29
+ function walk(currentDirectory) {
30
+ const entries = fs.readdirSync(currentDirectory, { withFileTypes: true });
31
+
32
+ entries.forEach((entry) => {
33
+ const entryPath = path.join(currentDirectory, entry.name);
34
+ if (entry.isDirectory()) {
35
+ walk(entryPath);
36
+ return;
37
+ }
38
+
39
+ if (!entry.name.endsWith('.json')) return;
40
+ const relativePath = path
41
+ .relative(directory, entryPath)
42
+ .split(path.sep)
43
+ .join('/');
44
+ schemaSources[relativePath] = JSON.parse(
45
+ fs.readFileSync(entryPath, 'utf-8'),
46
+ );
47
+ });
48
+ }
49
+
50
+ walk(directory);
51
+ return schemaSources;
52
+ }
53
+
26
54
  export function writeDoc(outputDir, fileName, content) {
27
55
  fs.writeFileSync(path.join(outputDir, fileName), content);
28
56
  console.log(
@@ -9,6 +9,8 @@ export default function MdxTemplate(data) {
9
9
  topPartialComponent,
10
10
  bottomPartialComponent,
11
11
  dataLayerName,
12
+ sourcePath,
13
+ schemaSources,
12
14
  } = data;
13
15
 
14
16
  return `---
@@ -33,7 +35,11 @@ ${topPartialComponent}
33
35
  schema={${JSON.stringify(mergedSchema)}}
34
36
  ${dataLayerName ? ` dataLayerName={'${dataLayerName}'}` : ''}
35
37
  />
36
- <SchemaJsonViewer schema={${JSON.stringify(schema)}} />
38
+ <SchemaJsonViewer
39
+ schema={${JSON.stringify(schema)}}
40
+ sourcePath={${JSON.stringify(sourcePath)}}
41
+ schemaSources={${JSON.stringify(schemaSources)}}
42
+ />
37
43
 
38
44
  ${bottomPartialComponent}
39
45
  `;