@graphql-markdown/core 1.21.2 → 1.23.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/dist/renderer.js CHANGED
@@ -1,11 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getRenderer = exports.Renderer = exports.getApiGroupFolder = exports.API_GROUPS = void 0;
3
+ exports.getRenderer = exports.Renderer = exports.logHandlerErrors = exports.getApiGroupFolder = exports.API_GROUPS = void 0;
4
4
  const node_path_1 = require("node:path");
5
5
  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 homepage_1 = require("./const/homepage");
9
10
  const validation_1 = require("./directives/validation");
10
11
  const event_emitter_1 = require("./event-emitter");
11
12
  const events_1 = require("./events");
@@ -90,7 +91,6 @@ var SidebarPosition;
90
91
  * @see {@link getApiGroupFolder} For usage with type categorization
91
92
  */
92
93
  // Used only by unit tests for direct whitebox coverage; not part of the production public API.
93
- // fallow-ignore-next-line unused-export
94
94
  exports.API_GROUPS = {
95
95
  operations: "operations",
96
96
  types: "types",
@@ -112,7 +112,6 @@ exports.API_GROUPS = {
112
112
  * ```
113
113
  */
114
114
  // Used only by unit tests for direct whitebox coverage; not part of the production public API.
115
- // fallow-ignore-next-line unused-export
116
115
  const getApiGroupFolder = (type, groups) => {
117
116
  let folderNames = exports.API_GROUPS;
118
117
  if ((0, validation_1.isGroupsObject)(groups)) {
@@ -247,6 +246,21 @@ class CategoryPositionManager {
247
246
  return this.categories.has(category);
248
247
  }
249
248
  }
249
+ /**
250
+ * Reports errors thrown by event handlers.
251
+ *
252
+ * Handler errors are collected rather than thrown, so without this they are
253
+ * dropped and the formatter's post-processing silently does nothing.
254
+ *
255
+ * @param eventName - Name of the emitted event
256
+ * @param errors - Errors collected from the handlers
257
+ */
258
+ const logHandlerErrors = (eventName, errors) => {
259
+ errors.forEach((error) => {
260
+ (0, logger_1.log)(`Error handler for ${eventName}: ${error.message}`, logger_1.LogLevel.error);
261
+ });
262
+ };
263
+ exports.logHandlerErrors = logHandlerErrors;
250
264
  /**
251
265
  * Core renderer class responsible for generating documentation files from GraphQL schema entities.
252
266
  * Handles the conversion of schema types to markdown/MDX documentation with proper organization.
@@ -260,7 +274,6 @@ class CategoryPositionManager {
260
274
  */
261
275
  // Value export used only by unit tests for direct whitebox coverage; the type is used
262
276
  // elsewhere via getRenderer()'s return type.
263
- // fallow-ignore-next-line unused-export
264
277
  class Renderer {
265
278
  group;
266
279
  outputDir;
@@ -268,6 +281,7 @@ class Renderer {
268
281
  prettify;
269
282
  options;
270
283
  mdxExtension;
284
+ outputAdapter;
271
285
  // mdxModuleIndexFileSupport: boolean;
272
286
  printer;
273
287
  rootLevelPositionManager;
@@ -275,16 +289,10 @@ class Renderer {
275
289
  /**
276
290
  * Creates a new Renderer instance.
277
291
  *
278
- * @param printer - The printer instance used to convert GraphQL types to markdown
279
- * @param outputDir - Directory where documentation will be generated
280
- * @param baseURL - Base URL for the documentation
281
- * @param group - Optional grouping configuration for schema entities
282
- * @param prettify - Whether to format the generated markdown
283
- * @param docOptions - Additional documentation options
284
- * @param mdxExtension - Optional MDX file extension to use
292
+ * @param options - Renderer construction options
285
293
  * @example
286
294
  */
287
- constructor(printer, outputDir, baseURL, group, prettify, docOptions, mdxExtension) {
295
+ constructor({ printer, outputDir, baseURL, group, prettify, docOptions, mdxExtension, outputAdapter = undefined, }) {
288
296
  this.printer = printer;
289
297
  this.group = group;
290
298
  this.outputDir = outputDir;
@@ -292,6 +300,7 @@ class Renderer {
292
300
  this.prettify = prettify;
293
301
  this.options = docOptions;
294
302
  this.mdxExtension = mdxExtension;
303
+ this.outputAdapter = outputAdapter ?? utils_1.fsOutputAdapter;
295
304
  // Initialize position managers for different hierarchy levels
296
305
  // rootLevelPositionManager: for root-level categories (Query, Mutation, Deprecated, etc.)
297
306
  this.rootLevelPositionManager = new CategoryPositionManager(docOptions?.categorySort, 1);
@@ -326,19 +335,23 @@ class Renderer {
326
335
  const event = new events_1.GenerateIndexMetafileEvent({
327
336
  dirPath,
328
337
  category,
338
+ outputAdapter: this.outputAdapter,
329
339
  options: {
330
340
  ...finalOptions,
331
341
  sidebarPosition,
332
342
  index: this.options?.index,
333
343
  },
334
344
  });
335
- const handlerErrors = await events.emitAsync(events_1.GenerateIndexMetafileEvents.BEFORE_GENERATE, event);
336
- if (Array.isArray(handlerErrors) && handlerErrors.length > 0) {
337
- handlerErrors.forEach((error) => {
338
- (0, logger_1.log)(`Error handler for ${events_1.GenerateIndexMetafileEvents.BEFORE_GENERATE}: ${error.message}`, logger_1.LogLevel.error);
339
- });
340
- }
341
- await events.emitAsync(events_1.GenerateIndexMetafileEvents.AFTER_GENERATE, new events_1.GenerateIndexMetafileEvent({ dirPath, category }));
345
+ // emitAsync resolves to an EmitResult, never an array: the previous
346
+ // Array.isArray() guard was always false, so handler errors went unreported
347
+ const { errors } = await events.emitAsync(events_1.GenerateIndexMetafileEvents.BEFORE_GENERATE, event);
348
+ (0, exports.logHandlerErrors)(events_1.GenerateIndexMetafileEvents.BEFORE_GENERATE, errors);
349
+ const { errors: afterErrors } = await events.emitAsync(events_1.GenerateIndexMetafileEvents.AFTER_GENERATE, new events_1.GenerateIndexMetafileEvent({
350
+ dirPath,
351
+ category,
352
+ outputAdapter: this.outputAdapter,
353
+ }));
354
+ (0, exports.logHandlerErrors)(events_1.GenerateIndexMetafileEvents.AFTER_GENERATE, afterErrors);
342
355
  }
343
356
  /**
344
357
  * Generates the directory path and metafiles for a specific schema entity type.
@@ -441,7 +454,7 @@ class Renderer {
441
454
  }
442
455
  }
443
456
  }
444
- return this.renderTypeEntities(dirPath, entityName, type[name], operationNamespaceParts);
457
+ return this.renderTypeEntities(dirPath, entityName, type[name], operationNamespaceParts, rootTypeName);
445
458
  }));
446
459
  }
447
460
  /**
@@ -450,10 +463,12 @@ class Renderer {
450
463
  * @param dirPath - The directory path where the file should be saved
451
464
  * @param name - The name of the type entity
452
465
  * @param type - The type entity to render
466
+ * @param operationNamespaceParts - The namespace parts for a namespaced operation
467
+ * @param entity - The schema entity kind being rendered, e.g. `queries`
453
468
  * @returns The category information for the rendered entity or undefined
454
469
  * @example
455
470
  */
456
- async renderTypeEntities(dirPath, name, type, operationNamespaceParts) {
471
+ async renderTypeEntities(dirPath, name, type, operationNamespaceParts, entity) {
457
472
  if (!(0, validation_1.isPath)(dirPath)) {
458
473
  throw new Error("Output directory is empty or not specified");
459
474
  }
@@ -494,6 +509,7 @@ class Renderer {
494
509
  ...(operationNamespaceParts === undefined
495
510
  ? {}
496
511
  : { operationNamespaceParts }),
512
+ ...(entity === undefined ? {} : { entity }),
497
513
  };
498
514
  content = await this.printer.printType(fileName, type, printOptions);
499
515
  if (typeof content !== "string" || content === "") {
@@ -505,7 +521,7 @@ class Renderer {
505
521
  (0, logger_1.log)(`An error occurred while processing "${name}": ${error instanceof Error ? error.message : String(error)}`, logger_1.LogLevel.warn);
506
522
  return undefined;
507
523
  }
508
- await (0, utils_1.saveFile)(filePath, content, this.prettify ? utils_1.prettifyMarkdown : undefined);
524
+ await this.writeOutput(filePath, content);
509
525
  const pagePath = (0, node_path_1.relative)(this.outputDir, filePath);
510
526
  const isFlat = isHierarchy(this.options, config_1.TypeHierarchy.FLAT);
511
527
  const page = isFlat
@@ -526,8 +542,10 @@ class Renderer {
526
542
  name,
527
543
  filePath,
528
544
  outputDir: this.outputDir,
545
+ outputAdapter: this.outputAdapter,
529
546
  });
530
- await events.emitAsync(events_1.RenderTypeEntitiesEvents.AFTER_RENDER, event);
547
+ const { errors } = await events.emitAsync(events_1.RenderTypeEntitiesEvents.AFTER_RENDER, event);
548
+ (0, exports.logHandlerErrors)(events_1.RenderTypeEntitiesEvents.AFTER_RENDER, errors);
531
549
  return {
532
550
  category,
533
551
  filePath,
@@ -598,13 +616,21 @@ class Renderer {
598
616
  const destLocation = (0, node_path_1.join)(this.outputDir, homePage);
599
617
  const slug = utils_1.pathUrl.resolve("/", this.baseURL);
600
618
  try {
601
- await (0, utils_1.copyFile)(homepageLocation, destLocation);
602
- const template = await (0, utils_1.readFile)(destLocation);
619
+ // Read the template from its source location rather than copying it into
620
+ // the output directory and reading it back: the round-trip wrote a file
621
+ // only to overwrite it a moment later, and it forced the destination to
622
+ // be readable, which a write-only output adapter is not.
623
+ //
624
+ // The built-in template is inlined, so the default path performs no
625
+ // filesystem read at all. Only a caller-supplied `homepage` path does.
626
+ const template = homepageLocation === config_1.ASSET_HOMEPAGE_LOCATION
627
+ ? homepage_1.DEFAULT_HOMEPAGE_TEMPLATE
628
+ : await (0, utils_1.readFile)(homepageLocation);
603
629
  const data = template
604
630
  .toString()
605
631
  .replaceAll("##baseURL##", slug)
606
632
  .replaceAll("##generated-date-time##", new Date().toLocaleString());
607
- await (0, utils_1.saveFile)(destLocation, data, this.prettify ? utils_1.prettifyMarkdown : undefined);
633
+ await this.writeOutput(destLocation, data);
608
634
  }
609
635
  catch (error) {
610
636
  (0, logger_1.log)(`An error occurred while processing the homepage ${homepageLocation}: ${error}`, logger_1.LogLevel.warn);
@@ -745,35 +771,58 @@ class Renderer {
745
771
  return (0, utils_1.slugify)(categoryName);
746
772
  }
747
773
  }
774
+ /**
775
+ * Sends a generated page to the configured output destination.
776
+ *
777
+ * Prettifying happens here rather than in the destination so every adapter
778
+ * receives identical content, and a custom adapter cannot accidentally skip
779
+ * the `pretty` option.
780
+ *
781
+ * @param filePath - Absolute path of the page, rooted at `outputDir`
782
+ * @param content - Rendered page content
783
+ */
784
+ async writeOutput(filePath, content) {
785
+ const output = this.prettify
786
+ ? ((await (0, utils_1.prettifyMarkdown)(content)) ?? content)
787
+ : content;
788
+ await this.outputAdapter.writeFile(filePath, output);
789
+ }
748
790
  }
749
791
  exports.Renderer = Renderer;
750
792
  /**
751
793
  * Factory function to create and initialize a Renderer instance.
752
794
  * Creates the output directory and returns a configured renderer.
753
795
  *
754
- * @param printer - The printer instance to use for rendering types
755
- * @param outputDir - The output directory for generated documentation
756
- * @param baseURL - The base URL for the documentation
757
- * @param group - Optional grouping configuration
758
- * @param prettify - Whether to prettify the output markdown
759
- * @param docOptions - Additional documentation options
760
- * @param mdxExtension - Extension to use for MDX files
796
+ * @param options - Renderer construction options
761
797
  * @returns A configured Renderer instance
762
798
  *
763
799
  * @example
764
800
  * ```typescript
765
- * const renderer = await getRenderer(
766
- * myPrinter,
767
- * './docs',
768
- * '/api',
769
- * groupConfig,
770
- * true,
771
- * { force: true, index: true }
772
- * );
801
+ * const renderer = await getRenderer({
802
+ * printer: myPrinter,
803
+ * outputDir: './docs',
804
+ * baseURL: '/api',
805
+ * group: groupConfig,
806
+ * prettify: true,
807
+ * docOptions: { force: true, index: true },
808
+ * mdxExtension: '.mdx',
809
+ * });
773
810
  * ```
774
811
  */
775
- const getRenderer = async (printer, outputDir, baseURL, group, prettify, docOptions, mdxExtension) => {
776
- await (0, utils_1.ensureDir)(outputDir, { forceEmpty: docOptions?.force });
777
- return new Renderer(printer, outputDir, baseURL, group, prettify, docOptions, mdxExtension);
812
+ const getRenderer = async ({ printer, outputDir, baseURL, group, prettify, docOptions, mdxExtension, outputAdapter = undefined, }) => {
813
+ const adapter = outputAdapter ?? utils_1.fsOutputAdapter;
814
+ // Optional on the interface: a destination with no directory concept (an
815
+ // object store, a CMS collection) has nothing to prepare.
816
+ await adapter.ensureDir?.(outputDir, { forceEmpty: docOptions?.force });
817
+ return new Renderer({
818
+ printer,
819
+ outputDir,
820
+ baseURL,
821
+ group,
822
+ prettify,
823
+ docOptions,
824
+ mdxExtension,
825
+ outputAdapter: adapter,
826
+ });
778
827
  };
779
828
  exports.getRenderer = getRenderer;
package/package.json CHANGED
@@ -5,7 +5,7 @@
5
5
  "bugs": {
6
6
  "url": "https://github.com/graphql-markdown/graphql-markdown/issues"
7
7
  },
8
- "version": "1.21.2",
8
+ "version": "1.23.0",
9
9
  "license": "MIT",
10
10
  "repository": {
11
11
  "type": "git",