@mintlify/common 1.0.1118 → 1.0.1120

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.
@@ -122,21 +122,61 @@ export const remarkExtractTableOfContents = (mdxExtracts, pageMetadata) => {
122
122
  });
123
123
  }
124
124
  });
125
+ const pushEntry = (entry, level) => {
126
+ if (level !== undefined && Number(level) <= 2) {
127
+ hasTopLayer = true;
128
+ contents.push(entry);
129
+ return;
130
+ }
131
+ // Account if there is no first layer
132
+ let arrToPushInto = contents;
133
+ if (hasTopLayer) {
134
+ const lastTopLevel = contents.at(-1);
135
+ if (lastTopLevel &&
136
+ (lastTopLevel.tabId === undefined || lastTopLevel.tabId === entry.tabId) &&
137
+ (lastTopLevel.viewId === undefined || lastTopLevel.viewId === entry.viewId) &&
138
+ (lastTopLevel.variationIds === undefined ||
139
+ (entry.variationIds !== undefined &&
140
+ entry.variationIds.every((id) => { var _a; return (_a = lastTopLevel.variationIds) === null || _a === void 0 ? void 0 : _a.includes(id); })))) {
141
+ arrToPushInto = lastTopLevel.children;
142
+ }
143
+ }
144
+ arrToPushInto.push(entry);
145
+ };
125
146
  visit(tree, (node) => {
126
- var _a, _b, _c, _d, _e, _f;
147
+ var _a, _b, _c, _d, _e, _f, _g;
127
148
  if (excludedNodes.has(node))
128
149
  return;
129
150
  const currentTabId = tabContentMap.get(node);
130
151
  const currentViewId = viewContentMap.get(node);
131
152
  const currentVariationIds = variationContentMap.get(node);
153
+ if (node.type === 'mdxFlowExpression' || node.type === 'mdxTextExpression') {
154
+ const fragmentHeadings = (_a = node.data) === null || _a === void 0 ? void 0 : _a.tableOfContents;
155
+ if (!(fragmentHeadings === null || fragmentHeadings === void 0 ? void 0 : fragmentHeadings.length))
156
+ return;
157
+ // headings compiled inside an <MDX> fragment (see remarkMdxExpandExpressions); merged in
158
+ // document order, slugs registered so later page headings do not reuse them
159
+ const register = (entries) => {
160
+ var _a;
161
+ for (const entry of entries) {
162
+ seenSlugs.set(entry.slug, ((_a = seenSlugs.get(entry.slug)) !== null && _a !== void 0 ? _a : 0) + 1);
163
+ register(entry.children);
164
+ }
165
+ };
166
+ register(fragmentHeadings);
167
+ for (const heading of fragmentHeadings) {
168
+ pushEntry(Object.assign(Object.assign({}, heading), { tabId: currentTabId, viewId: currentViewId, variationIds: currentVariationIds }), heading.depth);
169
+ }
170
+ return;
171
+ }
132
172
  const isValidHeading = node.type === 'heading' && HEADING_LEVELS.includes(node.depth);
133
- const isValidMdxHeading = node.type === 'mdxJsxFlowElement' && HEADING_NAMES.includes((_a = node.name) !== null && _a !== void 0 ? _a : '');
173
+ const isValidMdxHeading = node.type === 'mdxJsxFlowElement' && HEADING_NAMES.includes((_b = node.name) !== null && _b !== void 0 ? _b : '');
134
174
  const isTransformedHeading = node.type === 'mdxJsxFlowElement' && node.name === 'Heading';
135
175
  const isValidUpdate = node.type === 'mdxJsxFlowElement' &&
136
176
  node.name === 'Update' &&
137
177
  node.attributes.some((attr) => 'name' in attr && attr.name === 'label');
138
178
  const stepTitleSize = node.type === 'mdxJsxFlowElement' && node.name === 'Step'
139
- ? ((_b = getStringAttribute(node.attributes, 'titleSize')) !== null && _b !== void 0 ? _b : inheritedStepTitleSizeMap.get(node))
179
+ ? ((_c = getStringAttribute(node.attributes, 'titleSize')) !== null && _c !== void 0 ? _c : inheritedStepTitleSizeMap.get(node))
140
180
  : undefined;
141
181
  const hasNoAnchor = node.type === 'mdxJsxFlowElement' &&
142
182
  node.attributes.some((attr) => 'name' in attr &&
@@ -145,7 +185,7 @@ export const remarkExtractTableOfContents = (mdxExtracts, pageMetadata) => {
145
185
  attr.value === 'true' ||
146
186
  (typeof attr.value === 'object' && attr.value.value === 'true')));
147
187
  const stepTitle = node.type === 'mdxJsxFlowElement' && node.name === 'Step'
148
- ? getTitleMarkdownText(node, (_c = getStringAttribute(node.attributes, 'title')) !== null && _c !== void 0 ? _c : '')
188
+ ? getTitleMarkdownText(node, (_d = getStringAttribute(node.attributes, 'title')) !== null && _d !== void 0 ? _d : '')
149
189
  : undefined;
150
190
  const isValidStep = node.type === 'mdxJsxFlowElement' &&
151
191
  node.name === 'Step' &&
@@ -154,7 +194,7 @@ export const remarkExtractTableOfContents = (mdxExtracts, pageMetadata) => {
154
194
  (stepTitle === null || stepTitle === void 0 ? void 0 : stepTitle.trim()) !== '';
155
195
  const hasIdAttribute = node.type === 'mdxJsxFlowElement' &&
156
196
  node.attributes.some((attr) => 'name' in attr && attr.name === 'id');
157
- const isAvoidedPageMode = AVOIDED_PAGE_MODES.includes((_d = pageMetadata === null || pageMetadata === void 0 ? void 0 : pageMetadata.mode) !== null && _d !== void 0 ? _d : '');
197
+ const isAvoidedPageMode = AVOIDED_PAGE_MODES.includes((_e = pageMetadata === null || pageMetadata === void 0 ? void 0 : pageMetadata.mode) !== null && _e !== void 0 ? _e : '');
158
198
  if (!isValidHeading &&
159
199
  !isValidMdxHeading &&
160
200
  !isTransformedHeading &&
@@ -172,7 +212,7 @@ export const remarkExtractTableOfContents = (mdxExtracts, pageMetadata) => {
172
212
  }
173
213
  else if ('name' in node && node.name === 'Step') {
174
214
  const titleSizeToLevel = { h2: 2, h3: 3, h4: 4 };
175
- level = (_e = titleSizeToLevel[stepTitleSize !== null && stepTitleSize !== void 0 ? stepTitleSize : '']) !== null && _e !== void 0 ? _e : 3;
215
+ level = (_f = titleSizeToLevel[stepTitleSize !== null && stepTitleSize !== void 0 ? stepTitleSize : '']) !== null && _f !== void 0 ? _f : 3;
176
216
  // @ts-expect-error we're assigning to depth despite the node not containing depth in the type
177
217
  node.depth = level;
178
218
  }
@@ -185,7 +225,7 @@ export const remarkExtractTableOfContents = (mdxExtracts, pageMetadata) => {
185
225
  level = levelAttr.value;
186
226
  }
187
227
  }
188
- else if ('name' in node && ((_f = node.name) === null || _f === void 0 ? void 0 : _f[1])) {
228
+ else if ('name' in node && ((_g = node.name) === null || _g === void 0 ? void 0 : _g[1])) {
189
229
  const num = Number(node.name[1]);
190
230
  level = !isNaN(num) ? num : undefined;
191
231
  if (level !== undefined) {
@@ -252,42 +292,15 @@ export const remarkExtractTableOfContents = (mdxExtracts, pageMetadata) => {
252
292
  node.name = node.name === 'Update' ? 'Update' : node.name === 'Step' ? 'Step' : 'Heading';
253
293
  // @ts-expect-error we've already written to 'depth' and so this should be safe
254
294
  const depth = node.depth;
255
- if (level !== undefined && Number(level) <= 2) {
256
- hasTopLayer = true;
257
- contents.push({
258
- title,
259
- slug,
260
- depth,
261
- children: [],
262
- tabId: currentTabId,
263
- viewId: currentViewId,
264
- variationIds: currentVariationIds,
265
- });
266
- }
267
- else {
268
- // Account if there is no first layer
269
- let arrToPushInto = contents;
270
- if (hasTopLayer) {
271
- const lastTopLevel = contents.at(-1);
272
- if (lastTopLevel &&
273
- (lastTopLevel.tabId === undefined || lastTopLevel.tabId === currentTabId) &&
274
- (lastTopLevel.viewId === undefined || lastTopLevel.viewId === currentViewId) &&
275
- (lastTopLevel.variationIds === undefined ||
276
- (currentVariationIds !== undefined &&
277
- currentVariationIds.every((id) => { var _a; return (_a = lastTopLevel.variationIds) === null || _a === void 0 ? void 0 : _a.includes(id); })))) {
278
- arrToPushInto = lastTopLevel.children;
279
- }
280
- }
281
- arrToPushInto.push({
282
- title,
283
- slug,
284
- depth,
285
- children: [],
286
- tabId: currentTabId,
287
- viewId: currentViewId,
288
- variationIds: currentVariationIds,
289
- });
290
- }
295
+ pushEntry({
296
+ title,
297
+ slug,
298
+ depth,
299
+ children: [],
300
+ tabId: currentTabId,
301
+ viewId: currentViewId,
302
+ variationIds: currentVariationIds,
303
+ }, level);
291
304
  });
292
305
  if (mdxExtracts) {
293
306
  mdxExtracts.tableOfContents = contents;
@@ -71,9 +71,10 @@ export declare const MAX_MDX_FRAGMENTS_PER_PAGE = 500;
71
71
  * `<p>` wrapper is unwrapped so it does not nest in the surrounding paragraph.
72
72
  *
73
73
  * Escaping: the fragment source is JSX text, so a literal brace must be written the JSX way,
74
- * e.g. `{'{'}` / `{'}'}`; that expression is then evaluated by MDX and renders the brace. For the
75
- * same reason a custom heading anchor cannot use `## Title {#id}` inside an expression fragment;
76
- * write `<h2 id="id">Title</h2>` instead. Nothing beyond dedenting is done to the recovered text.
74
+ * e.g. `{'{'}` / `{'}'}`; that expression is then evaluated by MDX and renders the brace. A custom
75
+ * heading anchor (`## Title {#id}`) is fine: `preprocessCustomHeadingIds` rewrites it before the
76
+ * expression is parsed, at any indent inside `<MDX>`. Nothing beyond dedenting is done to the
77
+ * recovered text.
77
78
  *
78
79
  * Components defined on the page (`export const Local = () => …`, and named snippet imports,
79
80
  * which prebuild rewrites into page exports) are passed into the fragment pipeline as known
@@ -86,9 +87,11 @@ export declare const MAX_MDX_FRAGMENTS_PER_PAGE = 500;
86
87
  * feeds the side panel / sticky examples.
87
88
  *
88
89
  * Table of contents: the fragment pipeline runs `remarkExtractTableOfContents` (it also rewrites
89
- * headings to `<Heading>`, so it cannot be skipped) into a fragment-scoped extracts object that is
90
- * discarded, so headings inside an expression fragment get ids but are not listed in the page's
91
- * table of contents yet — that merge is a follow-up PR.
90
+ * headings to `<Heading>`, so it cannot be skipped) into a fragment-scoped extracts object; the
91
+ * headings are stored on the expression node as `data.tableOfContents` and merged into the page
92
+ * TOC in document order by the page-level run. Headings of a branch that never renders are still
93
+ * listed, and a fragment heading that repeats a page heading's title keeps its own id — a
94
+ * render-time reconcile is the planned follow-up.
92
95
  */
93
96
  export declare const remarkMdxExpandExpressions: (options: RemarkMdxExpandExpressionsOptions) => (tree: Root) => Promise<void>;
94
97
  export declare const dedent: (text: string) => string;
@@ -61,9 +61,10 @@ export const MAX_MDX_FRAGMENTS_PER_PAGE = 500;
61
61
  * `<p>` wrapper is unwrapped so it does not nest in the surrounding paragraph.
62
62
  *
63
63
  * Escaping: the fragment source is JSX text, so a literal brace must be written the JSX way,
64
- * e.g. `{'{'}` / `{'}'}`; that expression is then evaluated by MDX and renders the brace. For the
65
- * same reason a custom heading anchor cannot use `## Title {#id}` inside an expression fragment;
66
- * write `<h2 id="id">Title</h2>` instead. Nothing beyond dedenting is done to the recovered text.
64
+ * e.g. `{'{'}` / `{'}'}`; that expression is then evaluated by MDX and renders the brace. A custom
65
+ * heading anchor (`## Title {#id}`) is fine: `preprocessCustomHeadingIds` rewrites it before the
66
+ * expression is parsed, at any indent inside `<MDX>`. Nothing beyond dedenting is done to the
67
+ * recovered text.
67
68
  *
68
69
  * Components defined on the page (`export const Local = () => …`, and named snippet imports,
69
70
  * which prebuild rewrites into page exports) are passed into the fragment pipeline as known
@@ -76,9 +77,11 @@ export const MAX_MDX_FRAGMENTS_PER_PAGE = 500;
76
77
  * feeds the side panel / sticky examples.
77
78
  *
78
79
  * Table of contents: the fragment pipeline runs `remarkExtractTableOfContents` (it also rewrites
79
- * headings to `<Heading>`, so it cannot be skipped) into a fragment-scoped extracts object that is
80
- * discarded, so headings inside an expression fragment get ids but are not listed in the page's
81
- * table of contents yet — that merge is a follow-up PR.
80
+ * headings to `<Heading>`, so it cannot be skipped) into a fragment-scoped extracts object; the
81
+ * headings are stored on the expression node as `data.tableOfContents` and merged into the page
82
+ * TOC in document order by the page-level run. Headings of a branch that never renders are still
83
+ * listed, and a fragment heading that repeats a page heading's title keeps its own id — a
84
+ * render-time reconcile is the planned follow-up.
82
85
  */
83
86
  export const remarkMdxExpandExpressions = (options) => (tree) => __awaiter(void 0, void 0, void 0, function* () {
84
87
  var _a, _b, _c;
@@ -124,6 +127,7 @@ const expandExpression = (node_1, options_1, _a) => __awaiter(void 0, [node_1, o
124
127
  const elements = collectMdxElements(expression);
125
128
  if (elements.length === 0)
126
129
  return;
130
+ const headings = [];
127
131
  let changed = false;
128
132
  for (const element of elements) {
129
133
  const opening = element.openingElement;
@@ -172,6 +176,9 @@ const expandExpression = (node_1, options_1, _a) => __awaiter(void 0, [node_1, o
172
176
  ? compiled.children
173
177
  : [compiled];
174
178
  changed = true;
179
+ if (fragmentExtracts.tableOfContents) {
180
+ headings.push(...fragmentExtracts.tableOfContents);
181
+ }
175
182
  }
176
183
  if (!changed)
177
184
  return;
@@ -183,6 +190,9 @@ const expandExpression = (node_1, options_1, _a) => __awaiter(void 0, [node_1, o
183
190
  };
184
191
  node.value = toJs(program, { handlers: jsxHandlers }).value.replace(/;\s*$/, '');
185
192
  node.data = Object.assign(Object.assign({}, node.data), { estree: program });
193
+ if (headings.length > 0) {
194
+ node.data.tableOfContents = headings;
195
+ }
186
196
  });
187
197
  const collectMdxElements = (expression) => {
188
198
  const elements = [];
@@ -16,6 +16,11 @@ export interface PreprocessCustomHeadingIdsOptions {
16
16
  *
17
17
  * Uses a line-by-line scan with fence state tracking to skip headings inside
18
18
  * code blocks, avoiding backtracking over large documents.
19
+ *
20
+ * Headings are matched with at most 3 spaces of indent (deeper is an indented code block),
21
+ * except inside an `<MDX>` block — including one nested in a `{…}` expression, where authors
22
+ * indent the body — whose content is dedented before parsing, so any indent is accepted there.
23
+ * Without this the `{#id}` would reach the expression parser as a JSX expression and fail.
19
24
  */
20
25
  export declare function preprocessCustomHeadingIds(content: string, options?: PreprocessCustomHeadingIdsOptions): string;
21
26
  export interface JsxHeadingElement extends MdxJsxFlowElement {
@@ -1,4 +1,12 @@
1
1
  const HEADING_ID_RE = /^( {0,3})(#{1,6})\s+(.+?)\s*\{\s*#([^}]+?)\s*\}\s*$/;
2
+ /**
3
+ * Inside an `<MDX>` block the body is dedented before it is parsed, so indentation carries no
4
+ * meaning there (4+ spaces is not an indented code block) and any indent may precede the heading.
5
+ */
6
+ const MDX_HEADING_ID_RE = /^(\s*)(#{1,6})\s+(.+?)\s*\{\s*#([^}]+?)\s*\}\s*$/;
7
+ // `<MDX>` or `<MDX className="x">`; not `<MDX />` (no body) and not `<MDXProvider>`
8
+ const MDX_OPEN_RE = /<MDX(?:\s[^>]*[^/>\s])?\s*>/g;
9
+ const MDX_CLOSE_RE = /<\/MDX\s*>/g;
2
10
  const UNSAFE_HTML_ATTR_CHARS = /[<>"]/g;
3
11
  /**
4
12
  * Characters to strip from custom heading IDs in the default (non-editor) path.
@@ -23,13 +31,19 @@ function normalizeCustomId(raw) {
23
31
  *
24
32
  * Uses a line-by-line scan with fence state tracking to skip headings inside
25
33
  * code blocks, avoiding backtracking over large documents.
34
+ *
35
+ * Headings are matched with at most 3 spaces of indent (deeper is an indented code block),
36
+ * except inside an `<MDX>` block — including one nested in a `{…}` expression, where authors
37
+ * indent the body — whose content is dedented before parsing, so any indent is accepted there.
38
+ * Without this the `{#id}` would reach the expression parser as a JSX expression and fail.
26
39
  */
27
40
  export function preprocessCustomHeadingIds(content, options) {
28
- var _a;
41
+ var _a, _b, _c, _d, _e;
29
42
  const lines = content.split('\n');
30
43
  const result = [];
31
44
  let fenceChar;
32
45
  let fenceCount = 0;
46
+ let mdxDepth = 0;
33
47
  for (const line of lines) {
34
48
  const stripped = line.trimStart();
35
49
  if (fenceChar !== undefined) {
@@ -46,7 +60,7 @@ export function preprocessCustomHeadingIds(content, options) {
46
60
  result.push(line);
47
61
  continue;
48
62
  }
49
- const heading = HEADING_ID_RE.exec(line);
63
+ const heading = (mdxDepth > 0 ? MDX_HEADING_ID_RE : HEADING_ID_RE).exec(line);
50
64
  if ((heading === null || heading === void 0 ? void 0 : heading[2]) && heading[3] && heading[4]) {
51
65
  const indent = (_a = heading[1]) !== null && _a !== void 0 ? _a : '';
52
66
  const level = heading[2].length;
@@ -56,6 +70,7 @@ export function preprocessCustomHeadingIds(content, options) {
56
70
  result.push(`${indent}<h${level} id="${sanitizedId}">`, `${indent}${heading[3]}`, `${indent}</h${level}>`);
57
71
  continue;
58
72
  }
73
+ mdxDepth = Math.max(0, mdxDepth + ((_c = (_b = line.match(MDX_OPEN_RE)) === null || _b === void 0 ? void 0 : _b.length) !== null && _c !== void 0 ? _c : 0) - ((_e = (_d = line.match(MDX_CLOSE_RE)) === null || _d === void 0 ? void 0 : _d.length) !== null && _e !== void 0 ? _e : 0));
59
74
  result.push(line);
60
75
  }
61
76
  return result.join('\n');
@@ -23,6 +23,40 @@ describe('preprocessCustomHeadingIds', () => {
23
23
  const input = ' ## Heading {#custom-id}';
24
24
  expect(preprocessCustomHeadingIds(input)).toBe(input);
25
25
  });
26
+ it('converts headings at any indent inside an <MDX> block', () => {
27
+ const input = `{variant === "fos" ? (
28
+ <MDX>
29
+ ### Request a token {#request-token}
30
+
31
+ Body
32
+ </MDX>
33
+ ) : null}
34
+
35
+ ## Still code {#not-converted}`;
36
+ const output = preprocessCustomHeadingIds(input);
37
+ expect(output).toContain(' <h3 id="request-token">\n Request a token\n </h3>');
38
+ // depth is back to 0 after </MDX>: 4-space indent is an indented code block again
39
+ expect(output).toContain(' ## Still code {#not-converted}');
40
+ });
41
+ it('leaves code fences inside an <MDX> block alone', () => {
42
+ const input = `<MDX>
43
+ \`\`\`md
44
+ ## Heading {#custom-id}
45
+ \`\`\`
46
+ </MDX>`;
47
+ expect(preprocessCustomHeadingIds(input)).toBe(input);
48
+ });
49
+ it('ignores an unrelated MDX-prefixed tag', () => {
50
+ const input = '<MDXProvider>\n ## Heading {#custom-id}\n</MDXProvider>';
51
+ expect(preprocessCustomHeadingIds(input)).toBe(input);
52
+ });
53
+ it('does not treat a self-closing <MDX /> as opening a block', () => {
54
+ // a self-closing tag has no body; the any-indent rule must not stay on for the rest of the file
55
+ for (const tag of ['<MDX />', '<MDX/>', '<MDX className="x" />']) {
56
+ const input = `${tag}\n\n ## Still code {#not-converted}`;
57
+ expect(preprocessCustomHeadingIds(input)).toBe(input);
58
+ }
59
+ });
26
60
  it('leaves tab-indented headings alone', () => {
27
61
  const input = '\t## Heading {#custom-id}';
28
62
  expect(preprocessCustomHeadingIds(input)).toBe(input);