@graphql-markdown/core 1.16.2 → 1.17.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 (90) hide show
  1. package/dist/config.d.ts +17 -55
  2. package/dist/config.d.ts.map +1 -0
  3. package/dist/config.js +82 -94
  4. package/dist/const/patterns.d.ts +114 -0
  5. package/dist/const/patterns.d.ts.map +1 -0
  6. package/dist/const/patterns.js +116 -0
  7. package/dist/diff.d.ts +1 -0
  8. package/dist/diff.d.ts.map +1 -0
  9. package/dist/directives/normalize.d.ts +79 -0
  10. package/dist/directives/normalize.d.ts.map +1 -0
  11. package/dist/directives/normalize.js +91 -0
  12. package/dist/directives/validation.d.ts +146 -0
  13. package/dist/directives/validation.d.ts.map +1 -0
  14. package/dist/directives/validation.js +188 -0
  15. package/dist/event-emitter.d.ts +109 -0
  16. package/dist/event-emitter.d.ts.map +1 -0
  17. package/dist/event-emitter.js +138 -0
  18. package/dist/event-handlers.d.ts +19 -0
  19. package/dist/event-handlers.d.ts.map +1 -0
  20. package/dist/event-handlers.js +54 -0
  21. package/dist/event-map.d.ts +19 -0
  22. package/dist/event-map.d.ts.map +1 -0
  23. package/dist/event-map.js +35 -0
  24. package/dist/event-types.d.ts +313 -0
  25. package/dist/event-types.d.ts.map +1 -0
  26. package/dist/event-types.js +309 -0
  27. package/dist/events/base.d.ts +114 -0
  28. package/dist/events/base.d.ts.map +1 -0
  29. package/dist/events/base.js +148 -0
  30. package/dist/events/diff-check.d.ts +25 -0
  31. package/dist/events/diff-check.d.ts.map +1 -0
  32. package/dist/events/diff-check.js +26 -0
  33. package/dist/events/diff-events.d.ts +15 -0
  34. package/dist/events/diff-events.d.ts.map +1 -0
  35. package/dist/events/diff-events.js +17 -0
  36. package/dist/events/generate-index-metafile-events.d.ts +15 -0
  37. package/dist/events/generate-index-metafile-events.d.ts.map +1 -0
  38. package/dist/events/generate-index-metafile-events.js +17 -0
  39. package/dist/events/generate-index-metafile.d.ts +28 -0
  40. package/dist/events/generate-index-metafile.d.ts.map +1 -0
  41. package/dist/events/generate-index-metafile.js +29 -0
  42. package/dist/events/index.d.ts +19 -0
  43. package/dist/events/index.d.ts.map +1 -0
  44. package/dist/events/index.js +38 -0
  45. package/dist/events/render-homepage-events.d.ts +15 -0
  46. package/dist/events/render-homepage-events.d.ts.map +1 -0
  47. package/dist/events/render-homepage-events.js +17 -0
  48. package/dist/events/render-homepage.d.ts +22 -0
  49. package/dist/events/render-homepage.d.ts.map +1 -0
  50. package/dist/events/render-homepage.js +23 -0
  51. package/dist/events/render-root-types-events.d.ts +15 -0
  52. package/dist/events/render-root-types-events.d.ts.map +1 -0
  53. package/dist/events/render-root-types-events.js +17 -0
  54. package/dist/events/render-root-types.d.ts +22 -0
  55. package/dist/events/render-root-types.d.ts.map +1 -0
  56. package/dist/events/render-root-types.js +23 -0
  57. package/dist/events/render-type-entities-events.d.ts +15 -0
  58. package/dist/events/render-type-entities-events.d.ts.map +1 -0
  59. package/dist/events/render-type-entities-events.js +17 -0
  60. package/dist/events/render-type-entities.d.ts +25 -0
  61. package/dist/events/render-type-entities.d.ts.map +1 -0
  62. package/dist/events/render-type-entities.js +26 -0
  63. package/dist/events/schema-events.d.ts +15 -0
  64. package/dist/events/schema-events.d.ts.map +1 -0
  65. package/dist/events/schema-events.js +17 -0
  66. package/dist/events/schema-load.d.ts +22 -0
  67. package/dist/events/schema-load.d.ts.map +1 -0
  68. package/dist/events/schema-load.js +23 -0
  69. package/dist/generator.d.ts +1 -0
  70. package/dist/generator.d.ts.map +1 -0
  71. package/dist/generator.js +47 -5
  72. package/dist/graphql-config.d.ts +2 -1
  73. package/dist/graphql-config.d.ts.map +1 -0
  74. package/dist/graphql-config.js +16 -10
  75. package/dist/hooks.d.ts +10 -0
  76. package/dist/hooks.d.ts.map +1 -0
  77. package/dist/hooks.js +33 -0
  78. package/dist/index.d.ts +11 -0
  79. package/dist/index.d.ts.map +1 -0
  80. package/dist/index.js +11 -3
  81. package/dist/options/builder.d.ts +157 -0
  82. package/dist/options/builder.d.ts.map +1 -0
  83. package/dist/options/builder.js +215 -0
  84. package/dist/printer.d.ts +3 -2
  85. package/dist/printer.d.ts.map +1 -0
  86. package/dist/printer.js +1 -1
  87. package/dist/renderer.d.ts +76 -23
  88. package/dist/renderer.d.ts.map +1 -0
  89. package/dist/renderer.js +411 -67
  90. package/package.json +15 -15
package/dist/renderer.js CHANGED
@@ -6,6 +6,9 @@ const graphql_1 = require("@graphql-markdown/graphql");
6
6
  const utils_1 = require("@graphql-markdown/utils");
7
7
  const logger_1 = require("@graphql-markdown/logger");
8
8
  const config_1 = require("./config");
9
+ const validation_1 = require("./directives/validation");
10
+ const event_emitter_1 = require("./event-emitter");
11
+ const events_1 = require("./events");
9
12
  /**
10
13
  * Constant representing the string literal for deprecated entities.
11
14
  * Used for grouping deprecated schema entities when the deprecated option is set to "group".
@@ -73,7 +76,6 @@ var SidebarPosition;
73
76
  *
74
77
  * @property operations Folder name for GraphQL operations (queries, mutations, subscriptions)
75
78
  * @property types Folder name for GraphQL type definitions
76
- * @useDeclaredType
77
79
  *
78
80
  * @example
79
81
  * ```typescript
@@ -97,7 +99,6 @@ exports.API_GROUPS = {
97
99
  * @param type - The GraphQL schema entity to categorize
98
100
  * @param groups - Optional custom group naming configuration
99
101
  * @returns The folder name where the entity should be placed
100
- * @useDeclaredType
101
102
  *
102
103
  * @example
103
104
  * ```typescript
@@ -110,19 +111,39 @@ exports.API_GROUPS = {
110
111
  */
111
112
  const getApiGroupFolder = (type, groups) => {
112
113
  let folderNames = exports.API_GROUPS;
113
- if (groups && typeof groups === "object") {
114
+ if ((0, validation_1.isGroupsObject)(groups)) {
114
115
  folderNames = { ...exports.API_GROUPS, ...groups };
115
116
  }
116
117
  return (0, graphql_1.isApiType)(type) ? folderNames.operations : folderNames.types;
117
118
  };
118
119
  exports.getApiGroupFolder = getApiGroupFolder;
120
+ /**
121
+ * Strips numeric prefix from a folder name if categorySort is enabled.
122
+ * Converts folder names like "01-query" back to "query" for category identification.
123
+ *
124
+ * This is needed when extracting category names from file paths that were created
125
+ * with categorySort enabled. The regex matches leading two-digit numbers
126
+ * followed by a hyphen.
127
+ *
128
+ * @param folderName - The folder name to strip (e.g., "01-query", "02-mutations")
129
+ * @returns The folder name without prefix (e.g., "query", "mutations")
130
+ *
131
+ * @example
132
+ * ```typescript
133
+ * stripNumericPrefix("01-query"); // Returns "query"
134
+ * stripNumericPrefix("02-mutations"); // Returns "mutations"
135
+ * stripNumericPrefix("objects"); // Returns "objects" (no prefix to strip)
136
+ * ```
137
+ */
138
+ const stripNumericPrefix = (folderName) => {
139
+ return folderName.replace(/^\d{2}-/, "");
140
+ };
119
141
  /**
120
142
  * Type guard function that checks if the provided options include a specific hierarchy configuration.
121
143
  *
122
144
  * @param options - The renderer options to check
123
145
  * @param hierarchy - The hierarchy type to check for
124
146
  * @returns True if the options contain the specified hierarchy configuration
125
- * @useDeclaredType
126
147
  *
127
148
  * @example
128
149
  * ```typescript
@@ -132,15 +153,105 @@ exports.getApiGroupFolder = getApiGroupFolder;
132
153
  * ```
133
154
  */
134
155
  const isHierarchy = (options, hierarchy) => {
135
- return (options?.hierarchy?.[hierarchy] && true);
156
+ return options?.hierarchy?.[hierarchy] !== undefined;
136
157
  };
137
- const isPath = (path) => {
138
- return typeof path === "string" && path !== "";
158
+ /**
159
+ * Default natural sorting function for categories.
160
+ * Sorts categories alphabetically using localeCompare.
161
+ *
162
+ * @param a - First category name
163
+ * @param b - Second category name
164
+ * @returns Comparison result for sorting
165
+ */
166
+ const naturalSort = (a, b) => {
167
+ return a.localeCompare(b);
139
168
  };
169
+ /**
170
+ * Manages category positions for the sidebar.
171
+ * Supports two modes:
172
+ * 1. Pre-registration: categories are registered upfront, positions computed once
173
+ * 2. On-demand: positions are computed as categories are encountered
174
+ *
175
+ */
176
+ class CategoryPositionManager {
177
+ categories = new Set();
178
+ positionCache = new Map();
179
+ positionsComputed = false;
180
+ sortFn;
181
+ basePosition;
182
+ /**
183
+ * Creates a new CategoryPositionManager.
184
+ *
185
+ * @param sortFn - Function to sort categories (defaults to natural/alphabetical)
186
+ * @param basePosition - Starting position for categories (defaults to 1)
187
+ */
188
+ constructor(sortFn, basePosition = 1) {
189
+ this.sortFn = sortFn === "natural" || !sortFn ? naturalSort : sortFn;
190
+ this.basePosition = basePosition;
191
+ }
192
+ /**
193
+ * Pre-registers a batch of category names.
194
+ * This should be called before rendering to ensure consistent positioning.
195
+ *
196
+ * @param categoryNames - Array of category names to register
197
+ */
198
+ registerCategories(categoryNames) {
199
+ for (const name of categoryNames) {
200
+ this.categories.add(name);
201
+ }
202
+ }
203
+ /**
204
+ * Computes positions for all registered categories.
205
+ * This is called either manually after registration or automatically on first getPosition call.
206
+ */
207
+ computePositions() {
208
+ if (this.positionsComputed) {
209
+ return;
210
+ }
211
+ const sorted = Array.from(this.categories).sort(this.sortFn);
212
+ for (let index = 0; index < sorted.length; index++) {
213
+ this.positionCache.set(sorted[index], this.basePosition + index);
214
+ }
215
+ this.positionsComputed = true;
216
+ }
217
+ /**
218
+ * Gets the assigned position for a category.
219
+ * If category positions haven't been computed yet, computes them first.
220
+ *
221
+ * @param category - The category name
222
+ * @returns The position assigned to this category or basePosition if not found
223
+ */
224
+ getPosition(category) {
225
+ // Ensure positions are computed first (uses pre-registered categories)
226
+ if (!this.positionsComputed) {
227
+ this.computePositions();
228
+ }
229
+ // Return cached position or base position if not found
230
+ // NOTE: We don't dynamically add categories here to avoid breaking
231
+ // pre-computed positions. This ensures consistent positioning even if
232
+ // getPosition is called for categories that weren't pre-registered.
233
+ return this.positionCache.get(category) ?? this.basePosition;
234
+ }
235
+ /**
236
+ * Check if a category was pre-registered without triggering recomputation.
237
+ * Used to determine hierarchy level (root vs nested) without side effects.
238
+ *
239
+ * @param category - Category name to check
240
+ * @returns true if category was pre-registered
241
+ */
242
+ isRegistered(category) {
243
+ return this.categories.has(category);
244
+ }
245
+ }
140
246
  /**
141
247
  * Core renderer class responsible for generating documentation files from GraphQL schema entities.
142
248
  * Handles the conversion of schema types to markdown/MDX documentation with proper organization.
143
- * @useDeclaredType
249
+ *
250
+ * HIERARCHY LEVELS WHEN categorySort IS ENABLED:
251
+ * - Level 0 (root): Query, Mutation, Subscription, Custom Groups → 01-Query, 02-Mutation, etc.
252
+ * - Level 1 (under root): Specific types within each root → 01-Objects, 02-Enums, etc.
253
+ *
254
+ * Each level has its own CategoryPositionManager that restarts numbering at 1.
144
255
  * @example
145
256
  */
146
257
  class Renderer {
@@ -150,8 +261,10 @@ class Renderer {
150
261
  prettify;
151
262
  options;
152
263
  mdxModule;
153
- mdxModuleIndexFileSupport;
264
+ // mdxModuleIndexFileSupport: boolean;
154
265
  printer;
266
+ rootLevelPositionManager;
267
+ categoryPositionManager;
155
268
  /**
156
269
  * Creates a new Renderer instance.
157
270
  *
@@ -172,21 +285,11 @@ class Renderer {
172
285
  this.prettify = prettify;
173
286
  this.options = docOptions;
174
287
  this.mdxModule = mdxModule;
175
- this.mdxModuleIndexFileSupport = this.hasMDXIndexFileSupport(mdxModule);
176
- }
177
- /**
178
- * Checks if the provided module supports MDX index file generation.
179
- *
180
- * @param module - The module to check for MDX support
181
- * @returns True if the module supports index metafile generation
182
- * @useDeclaredType
183
- * @example
184
- */
185
- hasMDXIndexFileSupport(module = this.mdxModule) {
186
- return !!(module &&
187
- typeof module === "object" &&
188
- "generateIndexMetafile" in module &&
189
- typeof module.generateIndexMetafile === "function");
288
+ // Initialize position managers for different hierarchy levels
289
+ // rootLevelPositionManager: for root-level categories (Query, Mutation, Deprecated, etc.)
290
+ this.rootLevelPositionManager = new CategoryPositionManager(docOptions?.categorySort, 1);
291
+ // categoryPositionManager: for categories within each root type (e.g., under Query)
292
+ this.categoryPositionManager = new CategoryPositionManager(docOptions?.categorySort, 1);
190
293
  }
191
294
  /**
192
295
  * Generates an index metafile for a category directory if MDX support is available.
@@ -195,7 +298,6 @@ class Renderer {
195
298
  * @param category - The category name
196
299
  * @param options - Configuration options for the index
197
300
  * @returns Promise that resolves when the index is generated
198
- * @useDeclaredType
199
301
  *
200
302
  * @example
201
303
  * ```typescript
@@ -205,13 +307,31 @@ class Renderer {
205
307
  * });
206
308
  * ```
207
309
  */
208
- async generateIndexMetafile(dirPath, category, options = {
209
- collapsible: true,
210
- collapsed: true,
211
- }) {
212
- if (this.mdxModuleIndexFileSupport) {
213
- await this.mdxModule.generateIndexMetafile(dirPath, category, { ...options, index: this.options?.index });
310
+ async generateIndexMetafile(dirPath, category, options) {
311
+ const defaultOptions = {
312
+ collapsible: true,
313
+ collapsed: true,
314
+ };
315
+ const finalOptions = options ?? defaultOptions;
316
+ const sidebarPosition = finalOptions.sidebarPosition ??
317
+ this.categoryPositionManager.getPosition(category);
318
+ const events = (0, event_emitter_1.getEvents)();
319
+ const event = new events_1.GenerateIndexMetafileEvent({
320
+ dirPath,
321
+ category,
322
+ options: {
323
+ ...finalOptions,
324
+ sidebarPosition,
325
+ index: this.options?.index,
326
+ },
327
+ });
328
+ const handlerErrors = await events.emitAsync(events_1.GenerateIndexMetafileEvents.BEFORE_GENERATE, event);
329
+ if (Array.isArray(handlerErrors) && handlerErrors.length > 0) {
330
+ handlerErrors.forEach((error) => {
331
+ (0, logger_1.log)(`Error handler for ${events_1.GenerateIndexMetafileEvents.BEFORE_GENERATE}: ${error.message}`, logger_1.LogLevel.error);
332
+ });
214
333
  }
334
+ await events.emitAsync(events_1.GenerateIndexMetafileEvents.AFTER_GENERATE, new events_1.GenerateIndexMetafileEvent({ dirPath, category }));
215
335
  }
216
336
  /**
217
337
  * Generates the directory path and metafiles for a specific schema entity type.
@@ -221,44 +341,57 @@ class Renderer {
221
341
  * @param name - The name of the schema entity
222
342
  * @param rootTypeName - The root type name this entity belongs to
223
343
  * @returns The generated directory path
224
- * @useDeclaredType
225
344
  * @example
226
345
  */
227
346
  async generateCategoryMetafileType(type, name, rootTypeName) {
228
347
  let dirPath = this.outputDir;
229
- if (!isPath(dirPath)) {
348
+ if (!(0, validation_1.isPath)(dirPath)) {
230
349
  throw new Error("Output directory is empty or not specified");
231
350
  }
232
351
  if (isHierarchy(this.options, config_1.TypeHierarchy.FLAT)) {
233
352
  return dirPath;
234
353
  }
235
- const useApiGroup = isHierarchy(this.options, config_1.TypeHierarchy.API)
236
- ? this.options.hierarchy[config_1.TypeHierarchy.API]
237
- : !this.options?.hierarchy;
238
- if (useApiGroup) {
239
- const typeCat = (0, exports.getApiGroupFolder)(type, useApiGroup);
240
- dirPath = (0, node_path_1.join)(dirPath, (0, utils_1.slugify)(typeCat));
241
- await this.generateIndexMetafile(dirPath, typeCat, {
242
- collapsible: false,
243
- collapsed: false,
244
- styleClass: CATEGORY_STYLE_CLASS.API,
245
- });
246
- }
354
+ // Deprecated gets highest priority - at ROOT level before even custom groups
247
355
  if (this.options?.deprecated === "group" && (0, graphql_1.isDeprecated)(type)) {
248
- dirPath = (0, node_path_1.join)(dirPath, (0, utils_1.slugify)(DEPRECATED));
356
+ const formattedDeprecated = this.formatCategoryFolderName(DEPRECATED, true);
357
+ dirPath = (0, node_path_1.join)(dirPath, formattedDeprecated);
249
358
  await this.generateIndexMetafile(dirPath, DEPRECATED, {
250
359
  sidebarPosition: SidebarPosition.LAST,
251
360
  styleClass: CATEGORY_STYLE_CLASS.DEPRECATED,
252
361
  });
253
362
  }
363
+ // Custom groups come after deprecated but before hierarchy levels
254
364
  if (this.group &&
255
365
  rootTypeName in this.group &&
256
366
  name in this.group[rootTypeName]) {
257
367
  const rootGroup = this.group[rootTypeName][name] ?? "";
258
- dirPath = (0, node_path_1.join)(dirPath, (0, utils_1.slugify)(rootGroup));
368
+ // Custom groups are always at ROOT level (they come after deprecated in hierarchy priority)
369
+ const formattedRootGroup = this.formatCategoryFolderName(rootGroup, true);
370
+ dirPath = (0, node_path_1.join)(dirPath, formattedRootGroup);
259
371
  await this.generateIndexMetafile(dirPath, rootGroup);
260
372
  }
261
- dirPath = (0, node_path_1.join)(dirPath, (0, utils_1.slugify)(rootTypeName));
373
+ const useApiGroup = isHierarchy(this.options, config_1.TypeHierarchy.API)
374
+ ? this.options.hierarchy[config_1.TypeHierarchy.API]
375
+ : !isHierarchy(this.options, config_1.TypeHierarchy.ENTITY);
376
+ if (useApiGroup) {
377
+ const typeCat = (0, exports.getApiGroupFolder)(type, useApiGroup);
378
+ // API groups are root-level if no custom groups exist, nested if custom groups exist
379
+ const isApiGroupRootLevel = !this.group;
380
+ const formattedTypeCat = this.formatCategoryFolderName(typeCat, isApiGroupRootLevel);
381
+ dirPath = (0, node_path_1.join)(dirPath, formattedTypeCat);
382
+ await this.generateIndexMetafile(dirPath, typeCat, {
383
+ collapsible: false,
384
+ collapsed: false,
385
+ styleClass: CATEGORY_STYLE_CLASS.API,
386
+ });
387
+ }
388
+ // Entity categories are:
389
+ // - Root-level in entity hierarchy (only when no custom groups exist)
390
+ // - Nested in API hierarchy
391
+ // - Nested in entity hierarchy when custom groups exist
392
+ const isRootTypeLevelCat = useApiGroup ? false : !this.group;
393
+ const formattedRootTypeName = this.formatCategoryFolderName(rootTypeName, isRootTypeLevelCat);
394
+ dirPath = (0, node_path_1.join)(dirPath, formattedRootTypeName);
262
395
  await this.generateIndexMetafile(dirPath, rootTypeName);
263
396
  return dirPath;
264
397
  }
@@ -268,7 +401,6 @@ class Renderer {
268
401
  * @param rootTypeName - The name of the root type (e.g., "Query", "Mutation")
269
402
  * @param type - The type object containing all entities to render
270
403
  * @returns Array of rendered categories or undefined
271
- * @useDeclaredType
272
404
  * @example
273
405
  */
274
406
  async renderRootTypes(rootTypeName, type) {
@@ -276,16 +408,12 @@ class Renderer {
276
408
  return undefined;
277
409
  }
278
410
  const isFlat = isHierarchy(this.options, config_1.TypeHierarchy.FLAT);
279
- return Promise.all(Object.keys(type)
280
- .map(async (name) => {
411
+ return Promise.all(Object.keys(type).map(async (name) => {
281
412
  let dirPath = this.outputDir;
282
413
  if (!isFlat) {
283
414
  dirPath = await this.generateCategoryMetafileType(type[name], name, rootTypeName);
284
415
  }
285
416
  return this.renderTypeEntities(dirPath, name, type[name]);
286
- })
287
- .filter((res) => {
288
- return typeof res !== "undefined";
289
417
  }));
290
418
  }
291
419
  /**
@@ -295,21 +423,49 @@ class Renderer {
295
423
  * @param name - The name of the type entity
296
424
  * @param type - The type entity to render
297
425
  * @returns The category information for the rendered entity or undefined
298
- * @useDeclaredType
299
426
  * @example
300
427
  */
301
428
  async renderTypeEntities(dirPath, name, type) {
302
- if (!isPath(dirPath)) {
429
+ if (!(0, validation_1.isPath)(dirPath)) {
303
430
  throw new Error("Output directory is empty or not specified");
304
431
  }
305
- const PageRegex = /(?<category>[A-Za-z0-9-]+)[\\/]+(?<pageId>[A-Za-z0-9-]+).mdx?$/;
306
- const PageRegexFlat = /(?<pageId>[A-Za-z0-9-]+).mdx?$/;
307
- const extension = this.mdxModule ? "mdx" : "md";
432
+ // Regex patterns to parse page metadata from file paths
433
+ // Matches: path/to/category/page-name.md(x) or path\to\category\page-name.md(x)
434
+ // Only allows alphanumeric and hyphens in category and page names
435
+ // NOSONAR - pattern is safe, hyphen in character class doesn't cause backtracking
436
+ const PageRegex = /(?<category>[a-z0-9-]+)[\\/]+(?<pageId>[a-z0-9-]+)\.mdx?$/i; // NOSONAR
437
+ const PageRegexFlat = /(?<pageId>[a-z0-9-]+)\.mdx?$/i; // NOSONAR
438
+ // allow mdxModule to specify custom extension
439
+ let extension = "md";
440
+ if (this.mdxModule &&
441
+ typeof this.mdxModule === "object" &&
442
+ "extension" in this.mdxModule &&
443
+ typeof this.mdxModule.extension === "string") {
444
+ extension = this.mdxModule.extension;
445
+ }
446
+ else if (this.mdxModule) {
447
+ extension = "mdx";
448
+ }
308
449
  const fileName = (0, utils_1.slugify)(name);
309
450
  const filePath = (0, node_path_1.join)((0, node_path_1.normalize)(dirPath), `${fileName}.${extension}`);
310
451
  let content;
311
452
  try {
312
- content = this.printer.printType(fileName, type, this.options);
453
+ const printOptions = {
454
+ ...this.options,
455
+ formatCategoryFolderName: (categoryName) => {
456
+ // Determine if this category should use root or nested formatting
457
+ // First check if category was pre-registered as a root-level category
458
+ if (this.rootLevelPositionManager.isRegistered(categoryName)) {
459
+ return this.formatCategoryFolderName(categoryName, true);
460
+ }
461
+ // If not root-level, check if it's a nested category
462
+ // Nested categories are handled dynamically without pre-registration
463
+ // in some hierarchies (like API hierarchy where entity categories are
464
+ // scoped within their parent API group)
465
+ return this.formatCategoryFolderName(categoryName, false);
466
+ },
467
+ };
468
+ content = this.printer.printType(fileName, type, printOptions);
313
469
  if (typeof content !== "string" || content === "") {
314
470
  return undefined;
315
471
  }
@@ -328,29 +484,83 @@ class Renderer {
328
484
  (0, logger_1.log)(`An error occurred while processing file ${filePath} for type "${type}"`, logger_1.LogLevel.warn);
329
485
  return undefined;
330
486
  }
487
+ // Strip numeric prefix from category if it was applied when categorySort is enabled
488
+ const extractedCategory = isFlat
489
+ ? page.groups.pageId
490
+ : stripNumericPrefix(page.groups.category);
331
491
  const slug = isFlat
332
492
  ? page.groups.pageId
333
- : utils_1.pathUrl.join(page.groups.category, page.groups.pageId);
334
- const category = isFlat ? "schema" : (0, utils_1.startCase)(page.groups.category);
493
+ : utils_1.pathUrl.join(extractedCategory, page.groups.pageId);
494
+ const category = isFlat ? "schema" : (0, utils_1.startCase)(extractedCategory);
495
+ const events = (0, event_emitter_1.getEvents)();
496
+ const event = new events_1.RenderTypeEntitiesEvent({
497
+ name,
498
+ filePath,
499
+ });
500
+ await events.emitAsync(events_1.RenderTypeEntitiesEvents.AFTER_RENDER, event);
335
501
  return {
336
502
  category,
337
503
  slug,
338
504
  };
339
505
  }
506
+ /**
507
+ * Pre-collects all category names that will be generated during rendering.
508
+ * This allows the position manager to assign consistent positions before
509
+ * any files are written.
510
+ *
511
+ * HIERARCHY LEVELS:
512
+ * - Root level: Query, Mutation, Subscription, Deprecated (when grouped), custom root groups
513
+ * - Nested level: operations/types (API groups), custom groups under roots
514
+ *
515
+ * CRITICAL: Categories registered must match the NAMES USED BY THE PRINTER
516
+ * when generating links. The printer uses plural forms from ROOT_TYPE_LOCALE:
517
+ * "operations", "objects", "directives", "enums", "inputs", "interfaces",
518
+ * "mutations", "queries", "scalars", "subscriptions", "unions"
519
+ *
520
+ * NOT the folder names: "operations", "types"
521
+ *
522
+ * @param rootTypeNames - Array of root type names from the schema
523
+ */
524
+ preCollectCategories(rootTypeNames) {
525
+ const rootCategories = new Set();
526
+ const nestedCategories = new Set();
527
+ // Skip if flat hierarchy
528
+ if (isHierarchy(this.options, config_1.TypeHierarchy.FLAT)) {
529
+ return;
530
+ }
531
+ // Determine if using API hierarchy
532
+ const useApiGroup = isHierarchy(this.options, config_1.TypeHierarchy.API)
533
+ ? this.options.hierarchy[config_1.TypeHierarchy.API]
534
+ : !isHierarchy(this.options, config_1.TypeHierarchy.ENTITY);
535
+ // Register custom groups at root level
536
+ this.registerCustomGroups(rootCategories);
537
+ // Register categories based on hierarchy type
538
+ if (useApiGroup) {
539
+ this.registerApiGroupCategories(rootCategories, nestedCategories, this.group !== undefined);
540
+ }
541
+ else {
542
+ this.registerEntityCategories(rootCategories, nestedCategories, rootTypeNames, this.group !== undefined);
543
+ }
544
+ // Deprecated category - when grouped, it goes to root level
545
+ if (this.options?.deprecated === "group") {
546
+ rootCategories.add(DEPRECATED);
547
+ }
548
+ // Register collected categories with position managers
549
+ this.registerCategoriesWithManagers(rootCategories, nestedCategories);
550
+ }
340
551
  /**
341
552
  * Renders the homepage for the documentation from a template file.
342
553
  * Replaces placeholders in the template with actual values.
343
554
  *
344
555
  * @param homepageLocation - Path to the homepage template file
345
556
  * @returns Promise that resolves when the homepage is rendered
346
- * @useDeclaredType
347
557
  * @example
348
558
  */
349
559
  async renderHomepage(homepageLocation) {
350
560
  if (typeof homepageLocation !== "string") {
351
561
  return;
352
562
  }
353
- if (!isPath(this.outputDir)) {
563
+ if (!(0, validation_1.isPath)(this.outputDir)) {
354
564
  throw new Error("Output directory is empty or not specified");
355
565
  }
356
566
  const homePage = (0, node_path_1.basename)(homepageLocation);
@@ -361,14 +571,149 @@ class Renderer {
361
571
  const template = await (0, utils_1.readFile)(destLocation);
362
572
  const data = template
363
573
  .toString()
364
- .replace(/##baseURL##/gm, slug)
365
- .replace(/##generated-date-time##/gm, new Date().toLocaleString());
574
+ .replaceAll("##baseURL##", slug)
575
+ .replaceAll("##generated-date-time##", new Date().toLocaleString());
366
576
  await (0, utils_1.saveFile)(destLocation, data, this.prettify ? utils_1.prettifyMarkdown : undefined);
367
577
  }
368
578
  catch (error) {
369
579
  (0, logger_1.log)(`An error occurred while processing the homepage ${homepageLocation}: ${error}`, logger_1.LogLevel.warn);
370
580
  }
371
581
  }
582
+ /**
583
+ * Registers custom group names from the current group configuration.
584
+ * Custom groups are always registered at the ROOT level.
585
+ *
586
+ * @param rootCategories - Set to add custom group names to
587
+ */
588
+ registerCustomGroups(rootCategories) {
589
+ if (!this.group) {
590
+ return;
591
+ }
592
+ for (const rootTypeName in this.group) {
593
+ for (const name in this.group[rootTypeName]) {
594
+ const groupName = this.group[rootTypeName][name];
595
+ if (groupName) {
596
+ rootCategories.add(groupName);
597
+ }
598
+ }
599
+ }
600
+ }
601
+ /**
602
+ * Registers API group categories (operations/types) based on hierarchy and group configuration.
603
+ *
604
+ * @param rootCategories - Set to add root-level categories
605
+ * @param nestedCategories - Set to add nested-level categories
606
+ * @param hasCustomGroups - Whether custom groups are configured
607
+ */
608
+ registerApiGroupCategories(rootCategories, nestedCategories, hasCustomGroups) {
609
+ if (hasCustomGroups) {
610
+ // Custom groups exist: operations/types are nested
611
+ nestedCategories.add(exports.API_GROUPS.operations);
612
+ nestedCategories.add(exports.API_GROUPS.types);
613
+ }
614
+ else {
615
+ // No custom groups: operations/types are at ROOT level
616
+ rootCategories.add(exports.API_GROUPS.operations);
617
+ rootCategories.add(exports.API_GROUPS.types);
618
+ }
619
+ // Entity categories for API group - plural forms from ROOT_TYPE_LOCALE
620
+ const entityCategoryNames = [
621
+ "directives",
622
+ "enums",
623
+ "inputs",
624
+ "interfaces",
625
+ "mutations",
626
+ "objects",
627
+ "queries",
628
+ "scalars",
629
+ "subscriptions",
630
+ "unions",
631
+ ];
632
+ for (const categoryName of entityCategoryNames) {
633
+ nestedCategories.add(categoryName);
634
+ }
635
+ }
636
+ /**
637
+ * Registers entity hierarchy categories based on configuration.
638
+ *
639
+ * @param rootCategories - Set to add root-level categories
640
+ * @param nestedCategories - Set to add nested-level categories
641
+ * @param rootTypeNames - Array of root type names from schema
642
+ * @param hasCustomGroups - Whether custom groups are configured
643
+ */
644
+ registerEntityCategories(rootCategories, nestedCategories, rootTypeNames, hasCustomGroups) {
645
+ for (const name of rootTypeNames) {
646
+ if (hasCustomGroups) {
647
+ // If custom groups exist, entity names go nested under them
648
+ nestedCategories.add(name);
649
+ }
650
+ else {
651
+ // If no custom groups, entity names are at root
652
+ rootCategories.add(name);
653
+ }
654
+ }
655
+ }
656
+ /**
657
+ * Registers collected categories with appropriate position managers.
658
+ * Handles both hierarchical numbering (when categorySort is enabled) and traditional modes.
659
+ *
660
+ * @param rootCategories - Set of root-level categories
661
+ * @param nestedCategories - Set of nested-level categories
662
+ */
663
+ registerCategoriesWithManagers(rootCategories, nestedCategories) {
664
+ const hasCategorySort = this.options?.categorySort !== undefined;
665
+ if (hasCategorySort) {
666
+ // Register with hierarchical numbering when categorySort is enabled
667
+ this.rootLevelPositionManager.registerCategories(Array.from(rootCategories));
668
+ this.rootLevelPositionManager.computePositions();
669
+ this.categoryPositionManager.registerCategories(Array.from(nestedCategories));
670
+ this.categoryPositionManager.computePositions();
671
+ }
672
+ else {
673
+ // Traditional separate handling when categorySort is not defined
674
+ this.rootLevelPositionManager.registerCategories(Array.from(rootCategories));
675
+ this.rootLevelPositionManager.computePositions();
676
+ if (nestedCategories.size > 0) {
677
+ this.categoryPositionManager.registerCategories(Array.from(nestedCategories));
678
+ this.categoryPositionManager.computePositions();
679
+ }
680
+ }
681
+ }
682
+ /**
683
+ * Formats a category folder name, optionally prefixing with an order number.
684
+ *
685
+ * Supports hierarchical numbering:
686
+ * - Root level items (Query, Mutation, etc.) use rootLevelPositionManager
687
+ * - Nested items (groups, types within roots) use categoryPositionManager
688
+ *
689
+ * @param categoryName - The category name to format
690
+ * @param isRootLevel - Whether this category is at the root level (default: false for nested)
691
+ * @returns The formatted folder name (e.g., "01-objects" if prefix is enabled)
692
+ * @private
693
+ */
694
+ formatCategoryFolderName(categoryName, isRootLevel = false) {
695
+ const hasCategorySort = this.options?.categorySort !== undefined;
696
+ if (!hasCategorySort) {
697
+ return (0, utils_1.slugify)(categoryName);
698
+ }
699
+ try {
700
+ // Choose the appropriate position manager based on hierarchy level
701
+ const manager = isRootLevel
702
+ ? this.rootLevelPositionManager
703
+ : this.categoryPositionManager;
704
+ const position = manager.getPosition(categoryName);
705
+ if (!position) {
706
+ return (0, utils_1.slugify)(categoryName);
707
+ }
708
+ const paddedPosition = String(position).padStart(2, "0");
709
+ const slugifiedName = (0, utils_1.slugify)(categoryName);
710
+ const result = `${paddedPosition}-${slugifiedName}`;
711
+ return result;
712
+ }
713
+ catch {
714
+ return (0, utils_1.slugify)(categoryName);
715
+ }
716
+ }
372
717
  }
373
718
  exports.Renderer = Renderer;
374
719
  /**
@@ -383,7 +728,6 @@ exports.Renderer = Renderer;
383
728
  * @param docOptions - Additional documentation options
384
729
  * @param mdxModule - Optional MDX module for enhanced features
385
730
  * @returns A configured Renderer instance
386
- * @useDeclaredType
387
731
  *
388
732
  * @example
389
733
  * ```typescript