@graphql-markdown/core 1.16.3 → 1.17.1

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 +80 -89
  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 +136 -0
  18. package/dist/event-handlers.d.ts +22 -0
  19. package/dist/event-handlers.d.ts.map +1 -0
  20. package/dist/event-handlers.js +57 -0
  21. package/dist/event-map.d.ts +26 -0
  22. package/dist/event-map.d.ts.map +1 -0
  23. package/dist/event-map.js +43 -0
  24. package/dist/events/base.d.ts +119 -0
  25. package/dist/events/base.d.ts.map +1 -0
  26. package/dist/events/base.js +149 -0
  27. package/dist/events/diff-check.d.ts +25 -0
  28. package/dist/events/diff-check.d.ts.map +1 -0
  29. package/dist/events/diff-check.js +23 -0
  30. package/dist/events/diff-events.d.ts +15 -0
  31. package/dist/events/diff-events.d.ts.map +1 -0
  32. package/dist/events/diff-events.js +17 -0
  33. package/dist/events/generate-index-metafile-events.d.ts +15 -0
  34. package/dist/events/generate-index-metafile-events.d.ts.map +1 -0
  35. package/dist/events/generate-index-metafile-events.js +17 -0
  36. package/dist/events/generate-index-metafile.d.ts +25 -0
  37. package/dist/events/generate-index-metafile.d.ts.map +1 -0
  38. package/dist/events/generate-index-metafile.js +23 -0
  39. package/dist/events/index.d.ts +22 -0
  40. package/dist/events/index.d.ts.map +1 -0
  41. package/dist/events/index.js +43 -0
  42. package/dist/events/print-type-events.d.ts +33 -0
  43. package/dist/events/print-type-events.d.ts.map +1 -0
  44. package/dist/events/print-type-events.js +35 -0
  45. package/dist/events/print-type.d.ts +84 -0
  46. package/dist/events/print-type.d.ts.map +1 -0
  47. package/dist/events/print-type.js +73 -0
  48. package/dist/events/render-homepage-events.d.ts +15 -0
  49. package/dist/events/render-homepage-events.d.ts.map +1 -0
  50. package/dist/events/render-homepage-events.js +17 -0
  51. package/dist/events/render-homepage.d.ts +21 -0
  52. package/dist/events/render-homepage.d.ts.map +1 -0
  53. package/dist/events/render-homepage.js +23 -0
  54. package/dist/events/render-root-types-events.d.ts +15 -0
  55. package/dist/events/render-root-types-events.d.ts.map +1 -0
  56. package/dist/events/render-root-types-events.js +17 -0
  57. package/dist/events/render-root-types.d.ts +21 -0
  58. package/dist/events/render-root-types.d.ts.map +1 -0
  59. package/dist/events/render-root-types.js +23 -0
  60. package/dist/events/render-type-entities-events.d.ts +15 -0
  61. package/dist/events/render-type-entities-events.d.ts.map +1 -0
  62. package/dist/events/render-type-entities-events.js +17 -0
  63. package/dist/events/render-type-entities.d.ts +23 -0
  64. package/dist/events/render-type-entities.d.ts.map +1 -0
  65. package/dist/events/render-type-entities.js +23 -0
  66. package/dist/events/schema-events.d.ts +19 -0
  67. package/dist/events/schema-events.d.ts.map +1 -0
  68. package/dist/events/schema-events.js +21 -0
  69. package/dist/events/schema-load.d.ts +26 -0
  70. package/dist/events/schema-load.d.ts.map +1 -0
  71. package/dist/events/schema-load.js +23 -0
  72. package/dist/generator.d.ts +80 -1
  73. package/dist/generator.d.ts.map +1 -0
  74. package/dist/generator.js +244 -29
  75. package/dist/graphql-config.d.ts +2 -1
  76. package/dist/graphql-config.d.ts.map +1 -0
  77. package/dist/graphql-config.js +16 -10
  78. package/dist/index.d.ts +19 -0
  79. package/dist/index.d.ts.map +1 -0
  80. package/dist/index.js +26 -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 +4 -3
  85. package/dist/printer.d.ts.map +1 -0
  86. package/dist/printer.js +4 -4
  87. package/dist/renderer.d.ts +85 -32
  88. package/dist/renderer.d.ts.map +1 -0
  89. package/dist/renderer.js +411 -77
  90. package/package.json +11 -12
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Schema loading event constants.
3
+ *
4
+ * @packageDocumentation
5
+ */
6
+ /**
7
+ * Event names for schema loading lifecycle.
8
+ */
9
+ export declare const SchemaEvents: {
10
+ /** Emitted before loading GraphQL schema */
11
+ readonly BEFORE_LOAD: "schema:beforeLoad";
12
+ /** Emitted after loading GraphQL schema */
13
+ readonly AFTER_LOAD: "schema:afterLoad";
14
+ /** Emitted before mapping GraphQL schema */
15
+ readonly BEFORE_MAP: "schema:beforeMap";
16
+ /** Emitted after mapping GraphQL schema */
17
+ readonly AFTER_MAP: "schema:afterMap";
18
+ };
19
+ //# sourceMappingURL=schema-events.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema-events.d.ts","sourceRoot":"","sources":["../../src/events/schema-events.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH;;GAEG;AACH,eAAO,MAAM,YAAY;IACvB,4CAA4C;;IAE5C,2CAA2C;;IAE3C,4CAA4C;;IAE5C,2CAA2C;;CAEnC,CAAC"}
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ /**
3
+ * Schema loading event constants.
4
+ *
5
+ * @packageDocumentation
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.SchemaEvents = void 0;
9
+ /**
10
+ * Event names for schema loading lifecycle.
11
+ */
12
+ exports.SchemaEvents = {
13
+ /** Emitted before loading GraphQL schema */
14
+ BEFORE_LOAD: "schema:beforeLoad",
15
+ /** Emitted after loading GraphQL schema */
16
+ AFTER_LOAD: "schema:afterLoad",
17
+ /** Emitted before mapping GraphQL schema */
18
+ BEFORE_MAP: "schema:beforeMap",
19
+ /** Emitted after mapping GraphQL schema */
20
+ AFTER_MAP: "schema:afterMap",
21
+ };
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Schema loading event class.
3
+ *
4
+ * @packageDocumentation
5
+ */
6
+ import type { GraphQLSchema, Maybe, SchemaMap } from "@graphql-markdown/types";
7
+ import { CancellableEvent, CancellableEventOptions } from "./base";
8
+ /**
9
+ * Event emitted before/after loading a GraphQL schema.
10
+ *
11
+ * @category Events
12
+ */
13
+ export declare class SchemaEvent extends CancellableEvent {
14
+ /** Event data containing schema location, schema, and root types */
15
+ readonly data: {
16
+ schemaLocation?: string;
17
+ schema?: Maybe<GraphQLSchema>;
18
+ rootTypes?: Maybe<SchemaMap>;
19
+ };
20
+ constructor(data: {
21
+ schemaLocation?: string;
22
+ schema?: Maybe<GraphQLSchema>;
23
+ rootTypes?: Maybe<SchemaMap>;
24
+ }, options?: CancellableEventOptions);
25
+ }
26
+ //# sourceMappingURL=schema-load.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema-load.d.ts","sourceRoot":"","sources":["../../src/events/schema-load.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AAC/E,OAAO,EAAE,gBAAgB,EAAE,uBAAuB,EAAE,MAAM,QAAQ,CAAC;AAEnE;;;;GAIG;AACH,qBAAa,WAAY,SAAQ,gBAAgB;IAC/C,oEAAoE;IACpE,QAAQ,CAAC,IAAI,EAAE;QACb,cAAc,CAAC,EAAE,MAAM,CAAC;QACxB,MAAM,CAAC,EAAE,KAAK,CAAC,aAAa,CAAC,CAAC;QAC9B,SAAS,CAAC,EAAE,KAAK,CAAC,SAAS,CAAC,CAAC;KAC9B,CAAC;IAEF,YACE,IAAI,EAAE;QACJ,cAAc,CAAC,EAAE,MAAM,CAAC;QACxB,MAAM,CAAC,EAAE,KAAK,CAAC,aAAa,CAAC,CAAC;QAC9B,SAAS,CAAC,EAAE,KAAK,CAAC,SAAS,CAAC,CAAC;KAC9B,EACD,OAAO,CAAC,EAAE,uBAAuB,EAIlC;CACF"}
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ /**
3
+ * Schema loading event class.
4
+ *
5
+ * @packageDocumentation
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.SchemaEvent = void 0;
9
+ const base_1 = require("./base");
10
+ /**
11
+ * Event emitted before/after loading a GraphQL schema.
12
+ *
13
+ * @category Events
14
+ */
15
+ class SchemaEvent extends base_1.CancellableEvent {
16
+ /** Event data containing schema location, schema, and root types */
17
+ data;
18
+ constructor(data, options) {
19
+ super(options);
20
+ this.data = data;
21
+ }
22
+ }
23
+ exports.SchemaEvent = SchemaEvent;
@@ -7,7 +7,85 @@
7
7
  *
8
8
  * @packageDocumentation
9
9
  */
10
- import type { GeneratorOptions } from "@graphql-markdown/types";
10
+ import type { DirectiveName, Formatter, GeneratorOptions, GraphQLDirective, GraphQLSchema, LoaderOption, Maybe, MetaInfo, PackageName, TypeDiffMethod } from "@graphql-markdown/types";
11
+ /**
12
+ * Supported file extensions for generated documentation files.
13
+ *
14
+ * @remarks
15
+ * - MDX: MDX file extension (.mdx) for React component-enabled markdown
16
+ * - MD: Standard markdown file extension (.md)
17
+ */
18
+ export declare const FILE_EXTENSION: {
19
+ readonly MDX: ".mdx";
20
+ readonly MD: ".md";
21
+ };
22
+ /**
23
+ * Asynchronously loads an MDX module dynamically.
24
+ *
25
+ * @param mdxParser - The MDX parser package name or path to import. Can be null or undefined.
26
+ * @returns A promise that resolves to the imported module, or undefined if:
27
+ * - The mdxParser parameter is null or undefined
28
+ * - An error occurs during import (logs a warning and returns undefined)
29
+ *
30
+ * @internal
31
+ */
32
+ export declare const loadMDXModule: (mdxParser: Maybe<string | PackageName>) => Promise<unknown>;
33
+ /**
34
+ * Extracts a formatter from an MDX module.
35
+ *
36
+ * Checks for formatter functions in the following order:
37
+ * 1. A `createMDXFormatter` factory function (for internal/advanced usage)
38
+ * 2. Individual exported formatter functions (e.g., `formatMDXBadge`, `formatMDXAdmonition`)
39
+ *
40
+ * @param mdxModule - The loaded MDX module that may contain formatter exports
41
+ * @param meta - Optional metadata to pass to the formatter factory
42
+ * @returns A partial Formatter with the found functions, or undefined if none found
43
+ *
44
+ * @internal
45
+ */
46
+ export declare const getFormatterFromMDXModule: (mdxModule: unknown, meta?: MetaInfo) => Partial<Formatter> | undefined;
47
+ /**
48
+ * Loads a GraphQL schema from the specified location using configured document loaders.
49
+ *
50
+ * @param schemaLocation - The location/path of the GraphQL schema to load (e.g., file path, URL, or glob pattern).
51
+ * @param loadersList - Optional loader configuration for customizing how the schema is loaded.
52
+ *
53
+ * @returns A promise that resolves to the loaded GraphQL schema, or undefined if:
54
+ * - The loaders cannot be initialized
55
+ * - An error occurs during schema loading
56
+ *
57
+ * @internal
58
+ */
59
+ export declare const loadGraphqlSchema: (schemaLocation: string, loadersList: Maybe<LoaderOption>) => Promise<Maybe<GraphQLSchema>>;
60
+ /**
61
+ * Checks if there are differences in the GraphQL schema compared to a previous version.
62
+ *
63
+ * @param schema - The GraphQL schema to check for differences.
64
+ * @param schemaLocation - The location/path of the schema file for logging purposes.
65
+ * @param diffMethod - The method to use for detecting differences. If set to `NONE`, changes detection is skipped.
66
+ * @param tmpDir - The temporary directory path used for storing and comparing schema versions.
67
+ *
68
+ * @returns A promise that resolves to `true` if changes are detected or if diff method is `NONE`,
69
+ * or `false` if no changes are detected.
70
+ *
71
+ * @remarks
72
+ * When no changes are detected, a log message is generated indicating that the schema is unchanged.
73
+ */
74
+ export declare const checkSchemaDifferences: (schema: GraphQLSchema, schemaLocation: string, diffMethod: Maybe<TypeDiffMethod>, tmpDir: string) => Promise<boolean>;
75
+ /**
76
+ * Resolves and retrieves GraphQL directive objects from the schema based on their names.
77
+ *
78
+ * Takes two lists of directive names (for "only" and "skip" documentation directives),
79
+ * looks them up in the provided GraphQL schema, and returns the resolved directive objects.
80
+ *
81
+ * @param onlyDocDirective - A directive name or array of directive names for "only" documentation filtering
82
+ * @param skipDocDirective - A directive name or array of directive names for "skip" documentation filtering
83
+ * @param schema - The GraphQL schema to resolve directives from
84
+ *
85
+ * @returns A tuple containing two arrays: the first with resolved "only" directives,
86
+ * the second with resolved "skip" directives. Only defined directives are included.
87
+ */
88
+ export declare const resolveSkipAndOnlyDirectives: (onlyDocDirective: Maybe<DirectiveName[] | DirectiveName>, skipDocDirective: Maybe<DirectiveName[] | DirectiveName>, schema: GraphQLSchema) => GraphQLDirective[][];
11
89
  /**
12
90
  * Main entry point for generating Markdown documentation from a GraphQL schema.
13
91
  *
@@ -22,3 +100,4 @@ import type { GeneratorOptions } from "@graphql-markdown/types";
22
100
  * @returns Promise that resolves when documentation is fully generated
23
101
  */
24
102
  export declare const generateDocFromSchema: ({ baseURL, customDirective, diffMethod, docOptions, force, groupByDirective, homepageLocation, linkRoot, loaders: loadersList, loggerModule, mdxParser, metatags, onlyDocDirective, outputDir, prettify, printer: printerModule, printTypeOptions, schemaLocation, skipDocDirective, tmpDir, }: GeneratorOptions) => Promise<void>;
103
+ //# sourceMappingURL=generator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generator.d.ts","sourceRoot":"","sources":["../src/generator.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,KAAK,EAEV,aAAa,EACb,SAAS,EACT,gBAAgB,EAChB,gBAAgB,EAChB,aAAa,EACb,YAAY,EACZ,KAAK,EACL,QAAQ,EACR,WAAW,EAEX,cAAc,EAEf,MAAM,yBAAyB,CAAC;AAgCjC;;;;;;GAMG;AACH,eAAO,MAAM,cAAc;;;CAGjB,CAAC;AAgBX;;;;;;;;;GASG;AACH,eAAO,MAAM,aAAa,8DAczB,CAAC;AAgBF;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,yBAAyB,yEAkDrC,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,iBAAiB,6FAe7B,CAAC;AAEF;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,sBAAsB,wHAgBlC,CAAC;AAEF;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,4BAA4B,qKA0BxC,CAAC;AAEF;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,qBAAqB,qUA0NjC,CAAC"}
package/dist/generator.js CHANGED
@@ -33,7 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.generateDocFromSchema = void 0;
36
+ exports.generateDocFromSchema = exports.resolveSkipAndOnlyDirectives = exports.checkSchemaDifferences = exports.loadGraphqlSchema = exports.getFormatterFromMDXModule = exports.loadMDXModule = exports.FILE_EXTENSION = void 0;
37
37
  const logger_1 = __importStar(require("@graphql-markdown/logger"));
38
38
  const graphql_1 = require("@graphql-markdown/graphql");
39
39
  const utils_1 = require("@graphql-markdown/utils");
@@ -41,6 +41,20 @@ const config_1 = require("./config");
41
41
  const diff_1 = require("./diff");
42
42
  const printer_1 = require("./printer");
43
43
  const renderer_1 = require("./renderer");
44
+ const event_emitter_1 = require("./event-emitter");
45
+ const events_1 = require("./events");
46
+ const event_handlers_1 = require("./event-handlers");
47
+ /**
48
+ * Supported file extensions for generated documentation files.
49
+ *
50
+ * @remarks
51
+ * - MDX: MDX file extension (.mdx) for React component-enabled markdown
52
+ * - MD: Standard markdown file extension (.md)
53
+ */
54
+ exports.FILE_EXTENSION = {
55
+ MDX: ".mdx",
56
+ MD: ".md",
57
+ };
44
58
  /**
45
59
  * Constant representing nanoseconds per second.
46
60
  *
@@ -55,54 +69,221 @@ const NS_PER_SEC = 1e9;
55
69
  */
56
70
  const SEC_DECIMALS = 3;
57
71
  /**
58
- * Main entry point for generating Markdown documentation from a GraphQL schema.
72
+ * Asynchronously loads an MDX module dynamically.
59
73
  *
60
- * This function coordinates the entire documentation generation process:
61
- * - Loads and validates the schema
62
- * - Checks for schema changes if diffing is enabled
63
- * - Processes directives and groups
64
- * - Initializes printers and renderers
65
- * - Generates markdown files
74
+ * @param mdxParser - The MDX parser package name or path to import. Can be null or undefined.
75
+ * @returns A promise that resolves to the imported module, or undefined if:
76
+ * - The mdxParser parameter is null or undefined
77
+ * - An error occurs during import (logs a warning and returns undefined)
66
78
  *
67
- * @param options - Complete configuration for the documentation generation
68
- * @returns Promise that resolves when documentation is fully generated
79
+ * @internal
69
80
  */
70
- const generateDocFromSchema = async ({ baseURL, customDirective, diffMethod, docOptions, force, groupByDirective, homepageLocation, linkRoot, loaders: loadersList, loggerModule, mdxParser, metatags, onlyDocDirective, outputDir, prettify, printer: printerModule, printTypeOptions, schemaLocation, skipDocDirective, tmpDir, }) => {
71
- const start = process.hrtime.bigint();
72
- await (0, logger_1.default)(loggerModule);
81
+ const loadMDXModule = async (mdxParser) => {
82
+ return mdxParser !== undefined && mdxParser !== null
83
+ ? Promise.resolve(`${mdxParser}`).then(s => __importStar(require(s))).catch((err) => {
84
+ const errorMessage = err instanceof Error ? err.message : String(err ?? "Unknown error");
85
+ (0, logger_1.log)(`An error occurred while loading MDX formatter "${mdxParser}"\n${errorMessage}`, logger_1.LogLevel.warn);
86
+ return undefined;
87
+ })
88
+ : undefined;
89
+ };
90
+ exports.loadMDXModule = loadMDXModule;
91
+ /**
92
+ * List of formatter function names that can be exported individually from an MDX module.
93
+ */
94
+ const FORMATTER_FUNCTION_NAMES = [
95
+ "formatMDXBadge",
96
+ "formatMDXAdmonition",
97
+ "formatMDXBullet",
98
+ "formatMDXDetails",
99
+ "formatMDXFrontmatter",
100
+ "formatMDXLink",
101
+ "formatMDXNameEntity",
102
+ "formatMDXSpecifiedByLink",
103
+ ];
104
+ /**
105
+ * Extracts a formatter from an MDX module.
106
+ *
107
+ * Checks for formatter functions in the following order:
108
+ * 1. A `createMDXFormatter` factory function (for internal/advanced usage)
109
+ * 2. Individual exported formatter functions (e.g., `formatMDXBadge`, `formatMDXAdmonition`)
110
+ *
111
+ * @param mdxModule - The loaded MDX module that may contain formatter exports
112
+ * @param meta - Optional metadata to pass to the formatter factory
113
+ * @returns A partial Formatter with the found functions, or undefined if none found
114
+ *
115
+ * @internal
116
+ */
117
+ const getFormatterFromMDXModule = (mdxModule, meta) => {
118
+ if (!mdxModule || typeof mdxModule !== "object") {
119
+ return undefined;
120
+ }
121
+ const module = mdxModule;
122
+ // Check for createMDXFormatter on the module directly (internal/advanced usage)
123
+ if ("createMDXFormatter" in module &&
124
+ typeof module.createMDXFormatter === "function") {
125
+ return module.createMDXFormatter(meta);
126
+ }
127
+ // Check for createMDXFormatter on module.default (ESM default export)
128
+ const defaultExport = module.default;
129
+ if (defaultExport &&
130
+ "createMDXFormatter" in defaultExport &&
131
+ typeof defaultExport.createMDXFormatter === "function") {
132
+ return defaultExport.createMDXFormatter(meta);
133
+ }
134
+ // Check for individual formatter functions
135
+ const formatter = {};
136
+ let hasFormatter = false;
137
+ for (const funcName of FORMATTER_FUNCTION_NAMES) {
138
+ if (funcName in module && typeof module[funcName] === "function") {
139
+ formatter[funcName] = module[funcName];
140
+ hasFormatter = true;
141
+ }
142
+ else if (defaultExport &&
143
+ funcName in defaultExport &&
144
+ typeof defaultExport[funcName] === "function") {
145
+ formatter[funcName] =
146
+ defaultExport[funcName];
147
+ hasFormatter = true;
148
+ }
149
+ }
150
+ return hasFormatter ? formatter : undefined;
151
+ };
152
+ exports.getFormatterFromMDXModule = getFormatterFromMDXModule;
153
+ /**
154
+ * Loads a GraphQL schema from the specified location using configured document loaders.
155
+ *
156
+ * @param schemaLocation - The location/path of the GraphQL schema to load (e.g., file path, URL, or glob pattern).
157
+ * @param loadersList - Optional loader configuration for customizing how the schema is loaded.
158
+ *
159
+ * @returns A promise that resolves to the loaded GraphQL schema, or undefined if:
160
+ * - The loaders cannot be initialized
161
+ * - An error occurs during schema loading
162
+ *
163
+ * @internal
164
+ */
165
+ const loadGraphqlSchema = async (schemaLocation, loadersList) => {
73
166
  const loaders = await (0, graphql_1.getDocumentLoaders)(loadersList);
74
167
  if (!loaders) {
75
168
  (0, logger_1.log)(`An error occurred while loading GraphQL loader.\nCheck your dependencies and configuration.`, "error");
76
- return;
169
+ return undefined;
77
170
  }
78
- const schema = await (0, graphql_1.loadSchema)(schemaLocation, loaders);
171
+ return (0, graphql_1.loadSchema)(schemaLocation, loaders);
172
+ };
173
+ exports.loadGraphqlSchema = loadGraphqlSchema;
174
+ /**
175
+ * Checks if there are differences in the GraphQL schema compared to a previous version.
176
+ *
177
+ * @param schema - The GraphQL schema to check for differences.
178
+ * @param schemaLocation - The location/path of the schema file for logging purposes.
179
+ * @param diffMethod - The method to use for detecting differences. If set to `NONE`, changes detection is skipped.
180
+ * @param tmpDir - The temporary directory path used for storing and comparing schema versions.
181
+ *
182
+ * @returns A promise that resolves to `true` if changes are detected or if diff method is `NONE`,
183
+ * or `false` if no changes are detected.
184
+ *
185
+ * @remarks
186
+ * When no changes are detected, a log message is generated indicating that the schema is unchanged.
187
+ */
188
+ const checkSchemaDifferences = async (schema, schemaLocation, diffMethod, tmpDir) => {
189
+ let changed = true;
79
190
  if (diffMethod !== config_1.DiffMethod.NONE) {
80
- const changed = await (0, diff_1.hasChanges)(schema, tmpDir, diffMethod);
191
+ changed = await (0, diff_1.hasChanges)(schema, tmpDir, diffMethod);
81
192
  if (!changed) {
82
193
  (0, logger_1.log)(`No changes detected in schema "${(0, utils_1.toString)(schemaLocation)}".`);
83
194
  }
84
195
  }
85
- const [onlyDocDirectives, skipDocDirectives] = [
86
- onlyDocDirective,
87
- skipDocDirective,
88
- ].map((directiveList) => {
196
+ return changed;
197
+ };
198
+ exports.checkSchemaDifferences = checkSchemaDifferences;
199
+ /**
200
+ * Resolves and retrieves GraphQL directive objects from the schema based on their names.
201
+ *
202
+ * Takes two lists of directive names (for "only" and "skip" documentation directives),
203
+ * looks them up in the provided GraphQL schema, and returns the resolved directive objects.
204
+ *
205
+ * @param onlyDocDirective - A directive name or array of directive names for "only" documentation filtering
206
+ * @param skipDocDirective - A directive name or array of directive names for "skip" documentation filtering
207
+ * @param schema - The GraphQL schema to resolve directives from
208
+ *
209
+ * @returns A tuple containing two arrays: the first with resolved "only" directives,
210
+ * the second with resolved "skip" directives. Only defined directives are included.
211
+ */
212
+ const resolveSkipAndOnlyDirectives = (onlyDocDirective, skipDocDirective, schema) => {
213
+ return [onlyDocDirective, skipDocDirective].map((directive) => {
214
+ // Normalize to array and filter out null/undefined
215
+ let directiveList;
216
+ if (Array.isArray(directive)) {
217
+ directiveList = directive;
218
+ }
219
+ else if (directive) {
220
+ directiveList = [directive];
221
+ }
222
+ else {
223
+ directiveList = [];
224
+ }
89
225
  return directiveList
90
226
  .map((name) => {
91
227
  return schema.getDirective(name);
92
228
  })
93
229
  .filter((directive) => {
94
- return typeof directive !== "undefined";
230
+ return directive !== undefined;
95
231
  });
96
232
  });
233
+ };
234
+ exports.resolveSkipAndOnlyDirectives = resolveSkipAndOnlyDirectives;
235
+ /**
236
+ * Main entry point for generating Markdown documentation from a GraphQL schema.
237
+ *
238
+ * This function coordinates the entire documentation generation process:
239
+ * - Loads and validates the schema
240
+ * - Checks for schema changes if diffing is enabled
241
+ * - Processes directives and groups
242
+ * - Initializes printers and renderers
243
+ * - Generates markdown files
244
+ *
245
+ * @param options - Complete configuration for the documentation generation
246
+ * @returns Promise that resolves when documentation is fully generated
247
+ */
248
+ const generateDocFromSchema = async ({ baseURL, customDirective, diffMethod, docOptions, force, groupByDirective, homepageLocation, linkRoot, loaders: loadersList, loggerModule, mdxParser, metatags, onlyDocDirective, outputDir, prettify, printer: printerModule, printTypeOptions, schemaLocation, skipDocDirective, tmpDir, }) => {
249
+ const start = process.hrtime.bigint();
250
+ await (0, logger_1.default)(loggerModule);
251
+ const mdxModule = await (0, exports.loadMDXModule)(mdxParser);
252
+ // Register MDX lifecycle event handlers if mdxModule loaded successfully
253
+ // This must be called BEFORE getEvents() because it resets the singleton
254
+ (0, event_handlers_1.registerMDXEventHandlers)(mdxModule);
255
+ // Get events AFTER registration (registerMDXEventHandlers resets and recreates the singleton)
256
+ const events = (0, event_emitter_1.getEvents)();
257
+ await events.emitAsync(events_1.SchemaEvents.BEFORE_LOAD, new events_1.SchemaEvent({
258
+ schemaLocation: schemaLocation,
259
+ }));
260
+ const schema = await (0, exports.loadGraphqlSchema)(schemaLocation, loadersList);
261
+ await events.emitAsync(events_1.SchemaEvents.AFTER_LOAD, new events_1.SchemaEvent({
262
+ schemaLocation: schemaLocation,
263
+ schema,
264
+ }));
265
+ if (!schema) {
266
+ (0, logger_1.log)(`Failed to load GraphQL schema from location "${(0, utils_1.toString)(schemaLocation)}".`, "error");
267
+ return;
268
+ }
269
+ await events.emitAsync(events_1.DiffEvents.BEFORE_CHECK, new events_1.DiffCheckEvent({
270
+ schema,
271
+ outputDir: tmpDir,
272
+ }));
273
+ const schemaHasChanges = await (0, exports.checkSchemaDifferences)(schema, schemaLocation, diffMethod, tmpDir);
274
+ await events.emitAsync(events_1.DiffEvents.AFTER_CHECK, new events_1.DiffCheckEvent({ schemaHasChanges }));
275
+ const [onlyDocDirectives, skipDocDirectives] = (0, exports.resolveSkipAndOnlyDirectives)(onlyDocDirective, skipDocDirective, schema);
276
+ events.emit(events_1.SchemaEvents.BEFORE_MAP, new events_1.SchemaEvent({ schema }));
97
277
  const rootTypes = (0, graphql_1.getSchemaMap)(schema);
278
+ events.emit(events_1.SchemaEvents.AFTER_MAP, new events_1.SchemaEvent({ schema, rootTypes }));
98
279
  const customDirectives = (0, graphql_1.getCustomDirectives)(rootTypes, customDirective);
99
280
  const groups = (0, graphql_1.getGroups)(rootTypes, groupByDirective);
100
- const mdxModule = await (!mdxParser
101
- ? undefined
102
- : Promise.resolve(`${mdxParser}`).then(s => __importStar(require(s))).catch(() => {
103
- (0, logger_1.log)(`An error occurred while loading MDX formatter "${mdxParser}"`, logger_1.LogLevel.warn);
104
- return undefined;
105
- }));
281
+ // Extract formatter from the MDX module (for direct function calls)
282
+ const formatter = (0, exports.getFormatterFromMDXModule)(mdxModule, docOptions);
283
+ // Extract mdxDeclaration from the MDX module (if available)
284
+ const mdxDeclaration = mdxModule && typeof mdxModule === "object" && "mdxDeclaration" in mdxModule
285
+ ? mdxModule.mdxDeclaration
286
+ : undefined;
106
287
  const printer = await (0, printer_1.getPrinter)(
107
288
  // module mandatory
108
289
  printerModule,
@@ -124,18 +305,52 @@ const generateDocFromSchema = async ({ baseURL, customDirective, diffMethod, doc
124
305
  onlyDocDirectives,
125
306
  printTypeOptions,
126
307
  skipDocDirectives,
127
- }, mdxModule);
308
+ }, formatter, mdxDeclaration,
309
+ // Pass event emitter to enable print events
310
+ events);
311
+ // allow mdxModule to specify custom extension
312
+ let mdxExtension;
313
+ if (mdxModule &&
314
+ typeof mdxModule === "object" &&
315
+ "mdxExtension" in mdxModule) {
316
+ mdxExtension = mdxModule
317
+ .mdxExtension;
318
+ }
319
+ else if (mdxModule) {
320
+ mdxExtension = exports.FILE_EXTENSION.MDX;
321
+ }
322
+ else {
323
+ mdxExtension = exports.FILE_EXTENSION.MD;
324
+ }
128
325
  const renderer = await (0, renderer_1.getRenderer)(printer, outputDir, baseURL, groups, prettify, {
129
326
  ...docOptions,
130
327
  deprecated: printTypeOptions?.deprecated,
131
328
  force,
132
329
  hierarchy: printTypeOptions?.hierarchy,
133
- }, mdxModule);
330
+ }, mdxExtension);
331
+ // Pre-collect all categories before rendering to ensure consistent positions
332
+ renderer.preCollectCategories(Object.keys(rootTypes));
333
+ const beforeRenderRootTypesEvent = new events_1.RenderRootTypesEvent({
334
+ rootTypes,
335
+ });
336
+ await events.emitAsync(events_1.RenderRootTypesEvents.BEFORE_RENDER, beforeRenderRootTypesEvent);
134
337
  const pages = await Promise.all(Object.keys(rootTypes).map(async (name) => {
135
338
  const typeName = name;
136
339
  return renderer.renderRootTypes(typeName, rootTypes[typeName]);
137
340
  }));
341
+ const afterRenderRootTypesEvent = new events_1.RenderRootTypesEvent({
342
+ rootTypes,
343
+ });
344
+ await events.emitAsync(events_1.RenderRootTypesEvents.AFTER_RENDER, afterRenderRootTypesEvent);
345
+ const beforeRenderHomepageEvent = new events_1.RenderHomepageEvent({
346
+ outputDir,
347
+ });
348
+ await events.emitAsync(events_1.RenderHomepageEvents.BEFORE_RENDER, beforeRenderHomepageEvent);
138
349
  await renderer.renderHomepage(homepageLocation);
350
+ const afterRenderHomepageEvent = new events_1.RenderHomepageEvent({
351
+ outputDir,
352
+ });
353
+ await events.emitAsync(events_1.RenderHomepageEvents.AFTER_RENDER, afterRenderHomepageEvent);
139
354
  const duration = (Number(process.hrtime.bigint() - start) / NS_PER_SEC).toFixed(SEC_DECIMALS);
140
355
  (0, logger_1.log)(`Documentation successfully generated in "${outputDir}" with base URL "${baseURL}".`, "success");
141
356
  (0, logger_1.log)(`${pages.flat().length} pages generated in ${duration}s from schema "${(0, utils_1.toString)(schemaLocation)}".`);
@@ -71,7 +71,7 @@ export declare const setLoaderOptions: (loaders: LoaderOption, options: PackageO
71
71
  * @param id - The project ID to load configuration for.
72
72
  * @param options - Optional package options to apply.
73
73
  * @param throwOptions - Options for controlling throw behavior.
74
- * @returns The extension project configuration if found, otherwise undefined.
74
+ * @returns The extension project configuration if found, otherwise `undefined`.
75
75
  *
76
76
  * @throws Will throw an error if throwOnMissing or throwOnEmpty is true and
77
77
  * the corresponding condition is met.
@@ -91,3 +91,4 @@ export declare const setLoaderOptions: (loaders: LoaderOption, options: PackageO
91
91
  */
92
92
  export declare const loadConfiguration: (id: Maybe<string>, options?: Maybe<PackageOptionsConfig>, { throwOnMissing, throwOnEmpty }?: ThrowOptions) => Promise<Maybe<Readonly<ExtensionProjectConfig>>>;
93
93
  export {};
94
+ //# sourceMappingURL=graphql-config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"graphql-config.d.ts","sourceRoot":"","sources":["../src/graphql-config.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,KAAK,EAEV,sBAAsB,EACtB,2BAA2B,EAC3B,YAAY,EACZ,KAAK,EAEL,oBAAoB,EACrB,MAAM,yBAAyB,CAAC;AAUjC;;;GAGG;AACH,eAAO,MAAM,cAAc,oBAA8B,CAAC;AAE1D;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,sBAAsB,EAAE,2BAEpC,CAAC;AAEF;;;;;;GAMG;AACH,UAAU,YAAY;IACpB,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,YAAY,CAAC,EAAE,OAAO,CAAC;CACxB;AAWD;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,eAAO,MAAM,gBAAgB,wEAkB5B,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,eAAO,MAAM,iBAAiB,iKAsD7B,CAAC"}
@@ -35,6 +35,7 @@ var __importStar = (this && this.__importStar) || (function () {
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.loadConfiguration = exports.setLoaderOptions = exports.graphQLConfigExtension = exports.EXTENSION_NAME = void 0;
37
37
  const logger_1 = require("@graphql-markdown/logger");
38
+ const validation_1 = require("./directives/validation");
38
39
  /**
39
40
  * The name of the GraphQL Markdown extension.
40
41
  * Used to identify the extension in graphql-config.
@@ -57,6 +58,14 @@ const graphQLConfigExtension = () => {
57
58
  return { name: exports.EXTENSION_NAME };
58
59
  };
59
60
  exports.graphQLConfigExtension = graphQLConfigExtension;
61
+ /**
62
+ * Default throw options for loading configuration.
63
+ * @internal
64
+ */
65
+ const DEFAULT_THROW_OPTIONS = {
66
+ throwOnMissing: false,
67
+ throwOnEmpty: false,
68
+ };
60
69
  /**
61
70
  * Sets loader options for GraphQL Markdown loaders.
62
71
  *
@@ -82,7 +91,7 @@ exports.graphQLConfigExtension = graphQLConfigExtension;
82
91
  */
83
92
  const setLoaderOptions = (loaders, options) => {
84
93
  for (const loader in loaders) {
85
- if (typeof loaders[loader] === "string") {
94
+ if ((0, validation_1.isLoaderString)(loaders[loader])) {
86
95
  loaders[loader] = {
87
96
  module: loaders[loader],
88
97
  options,
@@ -108,7 +117,7 @@ exports.setLoaderOptions = setLoaderOptions;
108
117
  * @param id - The project ID to load configuration for.
109
118
  * @param options - Optional package options to apply.
110
119
  * @param throwOptions - Options for controlling throw behavior.
111
- * @returns The extension project configuration if found, otherwise undefined.
120
+ * @returns The extension project configuration if found, otherwise `undefined`.
112
121
  *
113
122
  * @throws Will throw an error if throwOnMissing or throwOnEmpty is true and
114
123
  * the corresponding condition is met.
@@ -126,10 +135,7 @@ exports.setLoaderOptions = setLoaderOptions;
126
135
  * );
127
136
  * ```
128
137
  */
129
- const loadConfiguration = async (id, options, { throwOnMissing, throwOnEmpty } = {
130
- throwOnMissing: false,
131
- throwOnEmpty: false,
132
- }) => {
138
+ const loadConfiguration = async (id, options, { throwOnMissing, throwOnEmpty } = DEFAULT_THROW_OPTIONS) => {
133
139
  let graphQLConfig;
134
140
  if (typeof id !== "string") {
135
141
  return undefined;
@@ -156,13 +162,13 @@ const loadConfiguration = async (id, options, { throwOnMissing, throwOnEmpty } =
156
162
  .extension(exports.EXTENSION_NAME);
157
163
  if (Array.isArray(projectConfig.schema)) {
158
164
  const schema = projectConfig.schema[0];
159
- if (typeof schema === "string") {
165
+ if ((0, validation_1.isSchemaString)(schema)) {
160
166
  projectConfig.schema = schema;
161
167
  }
162
- if (typeof projectConfig.schema === "object") {
168
+ else if ((0, validation_1.isSchemaObject)(schema)) {
163
169
  projectConfig.schema = Object.keys(schema)[0];
164
- if (typeof projectConfig.loaders !== "undefined") {
165
- projectConfig.loaders = (0, exports.setLoaderOptions)(projectConfig.loaders ?? {}, Object.values(schema)[0]);
170
+ if (projectConfig.loaders) {
171
+ projectConfig.loaders = (0, exports.setLoaderOptions)(projectConfig.loaders, Object.values(schema)[0]);
166
172
  }
167
173
  }
168
174
  }
package/dist/index.d.ts CHANGED
@@ -3,3 +3,22 @@
3
3
  */
4
4
  export { generateDocFromSchema } from "./generator";
5
5
  export { buildConfig } from "./config";
6
+ export { getEvents, resetEvents, type EmitResult } from "./event-emitter";
7
+ export { registerMDXEventHandlers } from "./event-handlers";
8
+ export { EVENT_CALLBACK_MAP } from "./event-map";
9
+ export { SchemaEvents } from "./events/schema-events";
10
+ export { DiffEvents } from "./events/diff-events";
11
+ export { RenderRootTypesEvents } from "./events/render-root-types-events";
12
+ export { RenderHomepageEvents } from "./events/render-homepage-events";
13
+ export { RenderTypeEntitiesEvents } from "./events/render-type-entities-events";
14
+ export { GenerateIndexMetafileEvents } from "./events/generate-index-metafile-events";
15
+ export { PrintTypeEvents } from "./events/print-type-events";
16
+ export type { CancellableEvent } from "./events/base";
17
+ export type { SchemaEvent as SchemaLoadEvent } from "./events/schema-load";
18
+ export type { DiffCheckEvent } from "./events/diff-check";
19
+ export type { RenderRootTypesEvent } from "./events/render-root-types";
20
+ export type { RenderHomepageEvent } from "./events/render-homepage";
21
+ export type { RenderTypeEntitiesEvent } from "./events/render-type-entities";
22
+ export type { GenerateIndexMetafileEvent } from "./events/generate-index-metafile";
23
+ export type { PrintCodeEvent, PrintCodeEventData, PrintTypeEvent, PrintTypeEventData, } from "./events/print-type";
24
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAGH,OAAO,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAGvC,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,KAAK,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC1E,OAAO,EAAE,wBAAwB,EAAE,MAAM,kBAAkB,CAAC;AAC5D,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAGjD,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AACtD,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAClD,OAAO,EAAE,qBAAqB,EAAE,MAAM,mCAAmC,CAAC;AAC1E,OAAO,EAAE,oBAAoB,EAAE,MAAM,iCAAiC,CAAC;AACvE,OAAO,EAAE,wBAAwB,EAAE,MAAM,sCAAsC,CAAC;AAChF,OAAO,EAAE,2BAA2B,EAAE,MAAM,yCAAyC,CAAC;AACtF,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAG7D,YAAY,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACtD,YAAY,EAAE,WAAW,IAAI,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAC3E,YAAY,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAC1D,YAAY,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AACvE,YAAY,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AACpE,YAAY,EAAE,uBAAuB,EAAE,MAAM,+BAA+B,CAAC;AAC7E,YAAY,EAAE,0BAA0B,EAAE,MAAM,kCAAkC,CAAC;AACnF,YAAY,EACV,cAAc,EACd,kBAAkB,EAClB,cAAc,EACd,kBAAkB,GACnB,MAAM,qBAAqB,CAAC"}