@readme/markdown 14.10.3 → 14.11.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/main.node.js CHANGED
@@ -122390,12 +122390,60 @@ function restoreSnakeCase(placeholderName, mapping) {
122390
122390
  return matchingKey ? mapping[matchingKey] : placeholderName;
122391
122391
  }
122392
122392
 
122393
+ ;// ./processor/transform/mdxish/resolve-esm-imports.ts
122394
+
122395
+ // We provide React as a default module so that components can use hooks
122396
+ // and it's a common use case. Add other common libraries here.
122397
+ const defaultModuleRegistry = { react: (external_react_default()) };
122398
+ const isRecord = (value) => typeof value === 'object' && value !== null;
122399
+ // Get the value of a named export from a module
122400
+ const getModuleExport = (module, importedName) => isRecord(module) && importedName in module ? module[importedName] : undefined;
122401
+ /**
122402
+ * Turn `import` declarations into a flat map of binding → value.
122403
+ *
122404
+ * A "binding" is a mapping of a local name to the value of it in the module exports
122405
+ * Example: `import { useState } from 'react'` yields `{ useState: React.useState }`.
122406
+ *
122407
+ * Unsupported specifiers are skipped with a warning rather than throwing, so a
122408
+ * single unknown import can't break the rest of the document.
122409
+ */
122410
+ const collectImportValues = (importDeclarations, registry = defaultModuleRegistry) => {
122411
+ const importValues = {};
122412
+ importDeclarations.forEach(declaration => {
122413
+ const libraryName = declaration.source.value;
122414
+ if (typeof libraryName !== 'string')
122415
+ return;
122416
+ if (!(libraryName in registry)) {
122417
+ // eslint-disable-next-line no-console
122418
+ console.warn(`[WARNING] Cannot resolve import "${libraryName}"; it is not a supported library.`);
122419
+ return;
122420
+ }
122421
+ const module = registry[libraryName];
122422
+ declaration.specifiers.forEach(spec => {
122423
+ // Default (`import React`) and namespace (`import * as React`) both bind
122424
+ // the whole module under the local name.
122425
+ if (spec.type === 'ImportDefaultSpecifier' || spec.type === 'ImportNamespaceSpecifier') {
122426
+ importValues[spec.local.name] = module;
122427
+ }
122428
+ else if (spec.type === 'ImportSpecifier') {
122429
+ // Named imports (e.g. `import { useState } from 'react'`, useState is the import name)
122430
+ const importName = spec.imported.type === 'Identifier' ? spec.imported.name : spec.imported.value;
122431
+ if (typeof importName === 'string') {
122432
+ importValues[spec.local.name] = getModuleExport(module, importName);
122433
+ }
122434
+ }
122435
+ });
122436
+ });
122437
+ return importValues;
122438
+ };
122439
+
122393
122440
  ;// ./processor/transform/mdxish/evaluate-exports.ts
122394
122441
 
122395
122442
 
122396
122443
 
122397
122444
 
122398
122445
 
122446
+
122399
122447
  /**
122400
122448
  * Recursively extract all identifier names introduced by a binding pattern.
122401
122449
  * Handles destructuring (`{ a, b }`, `[x, y]`), rest elements (`...rest`),
@@ -122443,6 +122491,7 @@ const collectExportNames = (declaration) => {
122443
122491
  const evaluateExports = () => (tree, file) => {
122444
122492
  const programBody = [];
122445
122493
  const exportNames = [];
122494
+ const importDeclarations = [];
122446
122495
  const nodesToRemove = [];
122447
122496
  visit(tree, isMDXEsm, (node, index, parent) => {
122448
122497
  if (parent && typeof index === 'number') {
@@ -122456,6 +122505,10 @@ const evaluateExports = () => (tree, file) => {
122456
122505
  // handled the same as a named export — the inner declaration carries the
122457
122506
  // binding name
122458
122507
  estreeBody.forEach(statement => {
122508
+ if (statement.type === 'ImportDeclaration') {
122509
+ importDeclarations.push(statement);
122510
+ return;
122511
+ }
122459
122512
  let declaration = null;
122460
122513
  if (statement.type === 'ExportNamedDeclaration' && statement.declaration) {
122461
122514
  declaration = statement.declaration;
@@ -122483,9 +122536,11 @@ const evaluateExports = () => (tree, file) => {
122483
122536
  const program = { type: 'Program', sourceType: 'module', body: programBody };
122484
122537
  buildJsx(program, { runtime: 'classic', pragma: 'React.createElement', pragmaFrag: 'React.Fragment' });
122485
122538
  const { value: source } = toJs(program);
122539
+ // Make sure import values are available in the scope
122540
+ const importValues = collectImportValues(importDeclarations);
122486
122541
  // Evaluate and build on the expression source
122487
122542
  // Use react to compile JSX codes
122488
- const evaluatedExports = evaluate(`(() => { ${source}\nreturn { ${exportNames.join(', ')} }; })()`, { React: (external_react_default()) });
122543
+ const evaluatedExports = evaluate(`(() => { ${source}\nreturn { ${exportNames.join(', ')} }; })()`, { React: (external_react_default()), ...importValues });
122489
122544
  Object.assign(scope, evaluatedExports);
122490
122545
  }
122491
122546
  catch (error) {
@@ -124439,214 +124494,21 @@ const normalizeMdxJsxNodes = () => tree => {
124439
124494
  */
124440
124495
  const JSX_COMMENT_REGEX = /\{\/\*[^*]*(?:\*(?!\/)[^*]*)*\*\/\}/g;
124441
124496
 
124442
- ;// ./processor/transform/mdxish/preprocess-jsx-expressions.ts
124443
-
124497
+ ;// ./processor/transform/mdxish/remove-jsx-comments.ts
124444
124498
 
124445
124499
  /**
124446
124500
  * Removes JSX-style comments (e.g., { /* comment *\/ }) from content.
124447
124501
  *
124448
- * @param content
124449
- * @returns Content with JSX comments removed
124450
- * @example
124502
+ * `@param` content
124503
+ * `@returns` Content with JSX comments removed
124504
+ * `@example`
124451
124505
  * ```typescript
124452
- * removeJSXComments('Text { /* comment *\/ } more text')
124453
- * // Returns: 'Text more text'
124506
+ * removeJSXComments('Text {/* comment *\/} more text') // => 'Text more text'
124454
124507
  * ```
124455
124508
  */
124456
124509
  function removeJSXComments(content) {
124457
124510
  return content.replace(JSX_COMMENT_REGEX, '');
124458
124511
  }
124459
- const HTML_ELEM_PLACEHOLDER_PREFIX = '___MDXISH_HTML_ELEM_';
124460
- const HTML_ELEM_PLACEHOLDER = new RegExp(`${HTML_ELEM_PLACEHOLDER_PREFIX}(\\d+)___`, 'g');
124461
- // Matches an HTML element that starts at a line boundary and ends at a line boundary.
124462
- // Allows optional leading indentation and lazily matches until the same closing tag.
124463
- const BLOCK_HTML_RE = /(?<=^|\n)[ \t]*<([a-z][a-zA-Z0-9]*)(?:\s[^>]*)?>[\s\S]*?<\/\1>[ \t]*(?=\n|$)/g;
124464
- /**
124465
- * Hides line-anchored HTML elements from the brace-escaping pass so we don't leak `\{`
124466
- * into rendered output (rehypeRaw renders the `\` literally, e.g. `<div>{foo</div>`).
124467
- *
124468
- * One carve-out: if an interior line at column 0 has bare text containing `{`, mdxish
124469
- * parses that line as a paragraph and the mdxExpression step would throw without an
124470
- * escape — so we leave that case to the brace balancer.
124471
- */
124472
- function protectHTMLElements(content) {
124473
- const htmlElements = [];
124474
- const protectedContent = content.replace(BLOCK_HTML_RE, match => {
124475
- // Look at the lines between the open and close tags. If any of them starts
124476
- // at column 0 with bare text (not whitespace, not another tag) and contains
124477
- // `{`, mdxish will parse that line as a paragraph and the brace as an MDX
124478
- // expression, which would throw an error. So we let the brace balancer escape it.
124479
- // Otherwise, we need to extract the sequence to protect it from the brace escaping.
124480
- const interior = match.split('\n').slice(1, -1);
124481
- const hazard = interior.some(line => line.length > 0 && line[0] !== ' ' && line[0] !== '\t' && line[0] !== '<' && line.includes('{'));
124482
- if (hazard)
124483
- return match;
124484
- htmlElements.push(match);
124485
- return `${HTML_ELEM_PLACEHOLDER_PREFIX}${htmlElements.length - 1}___`;
124486
- });
124487
- return { htmlElements, protectedContent };
124488
- }
124489
- function restoreHTMLElements(content, htmlElements) {
124490
- if (htmlElements.length === 0)
124491
- return content;
124492
- return content.replace(HTML_ELEM_PLACEHOLDER, (_m, idx) => htmlElements[parseInt(idx, 10)]);
124493
- }
124494
- const ESM_DECLARATION_START = /^(?:export|import)\b/;
124495
- /**
124496
- * Whether a line begins a top-level `export`/`import` declaration. Its braces
124497
- * are valid JS owned by the mdxjsEsm tokenizer (which tolerates blank lines),
124498
- * so escaping them would corrupt the source and break acorn parsing.
124499
- */
124500
- function startsEsmDeclaration(chars, lineStart) {
124501
- return ESM_DECLARATION_START.test(chars.slice(lineStart, lineStart + 7).join(''));
124502
- }
124503
- function isBlankLine(chars, lineStart) {
124504
- for (let i = lineStart; i < chars.length; i += 1) {
124505
- if (chars[i] === '\n')
124506
- return true;
124507
- if (chars[i] !== ' ' && chars[i] !== '\t')
124508
- return false;
124509
- }
124510
- return true;
124511
- }
124512
- /**
124513
- * Escapes unbalanced and paragraph-spanning braces so MDX doesn't trip on them.
124514
- */
124515
- function escapeProblematicBraces(content) {
124516
- const { htmlElements, protectedContent } = protectHTMLElements(content);
124517
- let strDelim = null;
124518
- let strEscaped = false;
124519
- // Track position of last newline (outside strings) to detect blank lines
124520
- // -2 means no recent newline
124521
- let lastNewlinePos = -2;
124522
- // Character state machine trackers
124523
- const toEscape = new Set();
124524
- // Convert to array of Unicode code points so that emojis and multi-byte characters are correctly tracked
124525
- const chars = Array.from(protectedContent);
124526
- const openStack = [];
124527
- // Whether the current top-level statement is an `export`/`import` declaration.
124528
- let insideEsmDeclaration = false;
124529
- for (let i = 0; i < chars.length; i += 1) {
124530
- const ch = chars[i];
124531
- // At a top-level (brace depth 0) line start, decide whether we're inside an
124532
- // ESM declaration. The flag persists across the declaration's own lines.
124533
- if (openStack.length === 0 && (i === 0 || chars[i - 1] === '\n')) {
124534
- if (startsEsmDeclaration(chars, i))
124535
- insideEsmDeclaration = true;
124536
- else if (isBlankLine(chars, i))
124537
- insideEsmDeclaration = false;
124538
- }
124539
- // Track string delimiters inside expressions to ignore braces within them
124540
- if (openStack.length > 0) {
124541
- if (strDelim) {
124542
- if (strEscaped)
124543
- strEscaped = false;
124544
- else if (ch === '\\')
124545
- strEscaped = true;
124546
- else if (ch === strDelim)
124547
- strDelim = null;
124548
- // eslint-disable-next-line no-continue
124549
- continue;
124550
- }
124551
- if (ch === '"' || ch === "'" || ch === '`') {
124552
- strDelim = ch;
124553
- // eslint-disable-next-line no-continue
124554
- continue;
124555
- }
124556
- if (ch === '\n') {
124557
- if (lastNewlinePos >= 0) {
124558
- const between = chars.slice(lastNewlinePos + 1, i).join('');
124559
- if (/^[ \t]*$/.test(between)) {
124560
- openStack.forEach(entry => { entry.hasBlankLine = true; });
124561
- }
124562
- }
124563
- lastNewlinePos = i;
124564
- }
124565
- }
124566
- // Skip already-escaped braces (odd run of preceding backslashes).
124567
- if (ch === '{' || ch === '}') {
124568
- let bs = 0;
124569
- for (let j = i - 1; j >= 0 && chars[j] === '\\'; j -= 1)
124570
- bs += 1;
124571
- if (bs % 2 === 1) {
124572
- // eslint-disable-next-line no-continue
124573
- continue;
124574
- }
124575
- }
124576
- if (ch === '{') {
124577
- // `=` (after whitespace) before `{` ⇒ JSX attribute expression. The
124578
- // mdxComponent tokenizer captures the whole component, so blank lines
124579
- // inside attribute values are harmless. Nested `{` inherits the flag.
124580
- let isAttrExpr = false;
124581
- for (let j = i - 1; j >= 0; j -= 1) {
124582
- const pc = chars[j];
124583
- if (pc === '=') {
124584
- isAttrExpr = true;
124585
- break;
124586
- }
124587
- if (pc !== ' ' && pc !== '\t')
124588
- break;
124589
- }
124590
- // Nested `{ ... }` inside an attribute value (e.g. `data={[{ ... }]}` or
124591
- // `data={{ a: { b: 1 } }}`) must inherit the same exemption; only the
124592
- // outer `{` is directly after `=`.
124593
- if (!isAttrExpr && openStack.length > 0 && openStack[openStack.length - 1].isAttrExpr) {
124594
- isAttrExpr = true;
124595
- }
124596
- openStack.push({ pos: i, hasBlankLine: false, isAttrExpr, isEsmDeclaration: insideEsmDeclaration });
124597
- lastNewlinePos = -2;
124598
- }
124599
- else if (ch === '}') {
124600
- if (openStack.length > 0) {
124601
- const entry = openStack.pop();
124602
- // The declaration's braces are closed; later top-level braces are not ESM.
124603
- if (openStack.length === 0)
124604
- insideEsmDeclaration = false;
124605
- // Pure `{/* ... */}` comments are handled downstream by the jsxComment
124606
- // tokenizer — escaping their braces would prevent it from running.
124607
- const isPureJsxComment = chars[entry.pos + 1] === '/' &&
124608
- chars[entry.pos + 2] === '*' &&
124609
- chars[i - 1] === '/' &&
124610
- chars[i - 2] === '*';
124611
- if (entry.hasBlankLine && !isPureJsxComment && !entry.isAttrExpr && !entry.isEsmDeclaration) {
124612
- toEscape.add(entry.pos);
124613
- toEscape.add(i);
124614
- }
124615
- }
124616
- else {
124617
- toEscape.add(i);
124618
- }
124619
- }
124620
- else if (ch === ';' && openStack.length === 0) {
124621
- // A top-level `;` ends the current statement, ESM or otherwise.
124622
- insideEsmDeclaration = false;
124623
- }
124624
- }
124625
- // Anything still open is unbalanced.
124626
- openStack.forEach(entry => {
124627
- if (!entry.isEsmDeclaration)
124628
- toEscape.add(entry.pos);
124629
- });
124630
- // Reconstruct the content with the escaped braces.
124631
- const escapedContent = toEscape.size === 0 ? protectedContent : chars.map((ch, i) => (toEscape.has(i) ? `\\${ch}` : ch)).join('');
124632
- return restoreHTMLElements(escapedContent, htmlElements);
124633
- }
124634
- /**
124635
- * Preprocesses JSX-like markdown content before parsing.
124636
- *
124637
- * JSX attribute expressions (`href={baseUrl}`) are no longer rewritten here —
124638
- * they flow through the tokenizer as `mdxJsxAttributeValueExpression` nodes
124639
- * and are evaluated at the hast handler step.
124640
- *
124641
- * @param content
124642
- * @returns Preprocessed content ready for markdown parsing
124643
- */
124644
- function preprocessJSXExpressions(content) {
124645
- const { protectedCode, protectedContent } = protectCodeBlocks(content);
124646
- let processed = escapeProblematicBraces(protectedContent);
124647
- processed = restoreCodeBlocks(processed, protectedCode);
124648
- return processed;
124649
- }
124650
124512
 
124651
124513
  ;// ./processor/transform/mdxish/resolve-deferred-attribute-expression-props.ts
124652
124514
 
@@ -125621,6 +125483,85 @@ function jsxTable() {
125621
125483
  ;// ./lib/micromark/jsx-table/index.ts
125622
125484
 
125623
125485
 
125486
+ ;// ./lib/micromark/mdx-expression-lenient/syntax.ts
125487
+
125488
+
125489
+ /**
125490
+ * Lenient MDX text-expression tokenizer (agnostic / no acorn).
125491
+ *
125492
+ * Matches a balanced `{ ... }` run — tracking nested braces and spanning soft
125493
+ * line breaks — and emits the standard `mdxTextExpression*` tokens so the
125494
+ * upstream `mdxExpressionFromMarkdown()` builds the node.
125495
+ *
125496
+ * Reimplements the official micromark mdxExpression, but an unbalanced brace that
125497
+ * reaches end of input returns `nok` instead of throwing: micromark rolls back
125498
+ * and the `{` renders as literal text, making the pipeline forgiving of stray
125499
+ * braces that upstream would hard-error on.
125500
+ */
125501
+ function tokenizeTextExpression(effects, ok, nok) {
125502
+ let depth = 0;
125503
+ return start;
125504
+ function start(code) {
125505
+ if (code !== codes.leftCurlyBrace)
125506
+ return nok(code);
125507
+ effects.enter('mdxTextExpression');
125508
+ effects.enter('mdxTextExpressionMarker');
125509
+ effects.consume(code);
125510
+ effects.exit('mdxTextExpressionMarker');
125511
+ return before;
125512
+ }
125513
+ function before(code) {
125514
+ if (code === codes.eof) {
125515
+ effects.exit('mdxTextExpression');
125516
+ return nok(code);
125517
+ }
125518
+ if (markdownLineEnding(code)) {
125519
+ effects.enter('lineEnding');
125520
+ effects.consume(code);
125521
+ effects.exit('lineEnding');
125522
+ return before;
125523
+ }
125524
+ if (code === codes.rightCurlyBrace && depth === 0) {
125525
+ return close(code);
125526
+ }
125527
+ effects.enter('mdxTextExpressionChunk');
125528
+ return inside(code);
125529
+ }
125530
+ function inside(code) {
125531
+ if (code === codes.eof || markdownLineEnding(code)) {
125532
+ effects.exit('mdxTextExpressionChunk');
125533
+ return before(code);
125534
+ }
125535
+ if (code === codes.rightCurlyBrace && depth === 0) {
125536
+ effects.exit('mdxTextExpressionChunk');
125537
+ return close(code);
125538
+ }
125539
+ if (code === codes.leftCurlyBrace)
125540
+ depth += 1;
125541
+ else if (code === codes.rightCurlyBrace)
125542
+ depth -= 1;
125543
+ effects.consume(code);
125544
+ return inside;
125545
+ }
125546
+ function close(code) {
125547
+ effects.enter('mdxTextExpressionMarker');
125548
+ effects.consume(code);
125549
+ effects.exit('mdxTextExpressionMarker');
125550
+ effects.exit('mdxTextExpression');
125551
+ return ok;
125552
+ }
125553
+ }
125554
+ function mdxExpressionLenient() {
125555
+ return {
125556
+ text: {
125557
+ [codes.leftCurlyBrace]: {
125558
+ name: 'mdxTextExpression',
125559
+ tokenize: tokenizeTextExpression,
125560
+ },
125561
+ },
125562
+ };
125563
+ }
125564
+
125624
125565
  ;// ./lib/utils/mdxish/mdxish-load-components.ts
125625
125566
 
125626
125567
 
@@ -125733,7 +125674,7 @@ const defaultTransformers = [
125733
125674
  * 1. Normalize malformed table separator syntax (e.g., `|: ---` → `| :---`)
125734
125675
  * 2. Terminate HTML flow blocks so subsequent content isn't swallowed
125735
125676
  * 3. Close invalid "self-closing" HTML tags (e.g., `<i />` → `<i></i>`)
125736
- * 4. Escape problematic braces so MDX expression parsing doesn't choke
125677
+ * 4. Normalize compact ATX headings (e.g., `#Heading` `# Heading`)
125737
125678
  * 5. Replace snake_case component names with parser-safe placeholders
125738
125679
  */
125739
125680
  function preprocessContent(content, opts) {
@@ -125742,7 +125683,6 @@ function preprocessContent(content, opts) {
125742
125683
  result = terminateHtmlFlowBlocks(result);
125743
125684
  result = closeSelfClosingHtmlTags(result);
125744
125685
  result = normalizeCompactHeadings(result);
125745
- result = preprocessJSXExpressions(result);
125746
125686
  return processSnakeCaseComponent(result, { knownComponents });
125747
125687
  }
125748
125688
  function mdxishAstProcessor(mdContent, opts = {}) {
@@ -125759,12 +125699,8 @@ function mdxishAstProcessor(mdContent, opts = {}) {
125759
125699
  acc[key] = String(value);
125760
125700
  return acc;
125761
125701
  }, {});
125762
- // Get mdxExpression extension and remove its flow construct to prevent
125763
- // `{...}` from interrupting paragraphs (which breaks multiline magic blocks)
125764
- const mdxExprExt = mdxExpression({ allowEmpty: true });
125765
- const mdxExprTextOnly = {
125766
- text: mdxExprExt.text,
125767
- };
125702
+ // Parser extension for MDX expressions {}
125703
+ const mdxExprTextOnly = mdxExpressionLenient();
125768
125704
  const micromarkExts = [
125769
125705
  jsxTable(),
125770
125706
  magicBlock(),