Copilot commented on code in PR #497:
URL: https://github.com/apache/echarts-doc/pull/497#discussion_r3035187026


##########
build/build-llms.js:
##########
@@ -0,0 +1,366 @@
+/**
+ * Converts built part JSONs (HTML desc) to Markdown using turndown,
+ * and generates llms.txt + individual .md files.
+ *
+ * Mechanically converts documents/*-parts/*.json to llms-documents/ (.md 
files).
+ * Root files (e.g. option.md) are placed at llms-documents/, while part files
+ * (e.g. option.title.md) are placed at llms-documents/*-parts/.
+ * Type information is extracted from documents/*.json (full schema) via 
traverse.
+ *
+ * Prerequisites: JSON must be built first (node build.js --env dev)
+ * Usage: node build/build-llms.js --env dev
+ */
+const fs = require('fs');
+const fse = require('fs-extra');
+const path = require('path');
+const globby = require('globby');
+const TurndownService = require('turndown');
+const {gfm} = require('turndown-plugin-gfm');
+const {traverse} = require('../tool/schemaHelper');
+const {readConfigEnvFile} = require('./helper');
+
+// --- Constants ---
+
+const LANGUAGES = ['en', 'zh'];
+const OUTPUT_DIR_NAME = 'llms-documents';
+const MAX_HEADING_DEPTH = 6;
+
+const SECTION_LABELS = {
+    en: {'option-parts': 'Option', 'option-gl-parts': 'Option GL', 
'api-parts': 'API', 'tutorial-parts': 'Tutorial'},
+    zh: {'option-parts': '配置项 (Option)', 'option-gl-parts': 'Option GL', 
'api-parts': 'API', 'tutorial-parts': '教程 (Tutorial)'}
+};
+
+const LLMS_TXT_HEADER = [
+    '# Apache ECharts Documentation',
+    '',
+    '> Apache ECharts is a free, powerful charting and visualization library 
offering easy ways to add intuitive, interactive, and highly customizable 
charts to your commercial products.',
+    ''
+].join('\n');
+
+// --- Config ---
+
+const argv = require('yargs').argv;
+const envType = (argv.dev != null || argv.debug != null || argv.env === 'dev') 
? 'dev' : argv.env;
+if (!envType) throw new Error('--env MUST be specified');
+const config = readConfigEnvFile(envType);
+
+// --- Turndown ---
+
+const td = new TurndownService({headingStyle: 'atx', codeBlockStyle: 
'fenced'});
+td.use(gfm);
+td.addRule('iframe', {filter: 'iframe', replacement: () => ''});
+
+function htmlToMd(html) {
+    return html ? td.turndown(html).replace(/\n{3,}/g, '\n\n').trim() : '';
+}
+
+// --- Extract type info from full schema JSON ---
+
+/**
+ * Extract type and default value info from a full schema JSON by traversing
+ * the nested schema tree.
+ *
+ * @param {string} schemaJsonPath - path to schema JSON (e.g. 
"documents/option.json")
+ * @param {string} docName - e.g. "option", "api"
+ * @returns {Object<string, {type: string|null, default: string|null}>}
+ *   e.g. { "option.title.show": {type: "boolean", default: "true"} }
+ */
+function buildTypeMap(schemaJsonPath, docName) {
+    if (!fs.existsSync(schemaJsonPath)) return {};
+    const schema = JSON.parse(fs.readFileSync(schemaJsonPath, 'utf-8'));
+    const typeMap = {};
+    traverse(schema, docName, (schemaPath, node) => {
+        if (node.type || node.default != null) {
+            typeMap[schemaPath] = {
+                type: node.type ? (Array.isArray(node.type) ? 
node.type.join('|') : node.type) : null,
+                default: node.default != null
+                    ? (typeof node.default === 'object' ? 
JSON.stringify(node.default) : String(node.default))
+                    : null
+            };
+        }
+    });
+    return typeMap;
+}
+
+// --- Resolve links in HTML ---
+// Best-effort rewriting of <a href="#path"> and <a href="api.html#path"> in 
HTML
+// so that turndown produces markdown links pointing to the correct .md files.
+// Some source links have non-standard formats (e.g. missing "#", no dot 
separator)
+// that cannot be resolved; these are left as-is or linked to the root file.
+
+/**
+ * Split linkPath into a part key (first segment) and fragment (rest), matching
+ * the key against partKeys with case-insensitive and singular/plural fallback.
+ *
+ * @param {string} linkPath - e.g. "title.show", "echarts.init"
+ * @param {Set<string>} partKeys - e.g. Set{'title','series-bar','geo',...}
+ * @returns {{key: string, frag: string|null}|null}
+ *   e.g. "title.show"                    -> {key: "title", frag: "show"}
+ *        "angleAxis.axisLabel.interval"  -> {key: "angleAxis", frag: 
"axisLabel.interval"}
+ *        "geo"                           -> {key: "geo", frag: null}
+ *        "unknown"                       -> null
+ */
+function tryResolvePartKey(linkPath, partKeys) {
+    const [seg, ...rest] = linkPath.split('.');
+    const frag = rest.length > 0 ? rest.join('.') : null;
+
+    if (partKeys.has(seg)) return {key: seg, frag};
+
+    // Fallback: case-insensitive and singular/plural matching
+    const segL = seg.toLowerCase();
+    for (const k of partKeys) {
+        if (k.toLowerCase() === segL) return {key: k, frag};
+    }
+    for (const k of partKeys) {
+        const kl = k.toLowerCase();
+        if (kl === segL + 's' || kl + 's' === segL) return {key: k, frag};
+    }
+    return null;
+}
+
+/**
+ * Resolve a link path to an href pointing to the correct .md file.
+ * If partKeys contains a match, link to the individual part file;
+ * otherwise fall back to the root file.
+ *
+ * @param {string} linkPath - e.g. "title.show", "visualMap"
+ * @param {Set<string>} partKeys - keys of individual part files
+ * @param {string} pathPrefix - path prefix for part files
+ *   from part: "option"                -> "option.title.md"
+ *   from root: "option-parts/option"   -> "option-parts/option.title.md"
+ *   cross-doc: "../api-parts/api"      -> "../api-parts/api.echarts.md"
+ * @param {string} rootPath - path prefix for root file fallback
+ *   from part: "../option"  -> "../option.md#visualMap"
+ *   from root: "option"     -> "option.md#visualMap"
+ *   cross-doc: "../api"     -> "../api.md#events"
+ * @returns {string} resolved href attribute string
+ */
+function resolveLink(linkPath, partKeys, pathPrefix, rootPath) {
+    const resolved = tryResolvePartKey(linkPath, partKeys);
+    if (!resolved) {
+        return `href="${rootPath}.md#${linkPath}"`;
+    }
+    return `href="${pathPrefix}.${resolved.key}.md${resolved.frag ? '#' + 
resolved.frag : ''}"`;
+}
+
+/**
+ * Rewrite internal links and image paths in HTML before turndown conversion.
+ * Handles three patterns:
+ *   1. Same-doc:  href="#title.show"            -> href="option.title.md#show"
+ *   2. Cross-doc: href="api.html#echarts.init"  -> 
href="../api-parts/api.echarts.md#init"
+ *   3. Images:    src="documents/asset/img/..." -> 
src="../../documents/asset/img/..."
+ * Unresolvable links fall back to the root file.
+ *
+ * @param {string} html - HTML string containing <a href="..."> links
+ * @param {Object<string, Set<string>>} partKeysByDoc - part keys for all docs
+ * @param {string} docName - current doc name (e.g. "option")
+ * @param {boolean} isRoot - whether the current file is a root file
+ * @returns {string} HTML with rewritten href attributes and image paths
+ */
+function tryResolveHtmlLinks(html, partKeysByDoc, docName, isRoot) {
+    const partKeys = partKeysByDoc[docName];
+    // Path prefixes differ depending on whether current file is root or part:
+    //   root (llms-documents/option.md)              -> part: 
"option-parts/option", root: "option"
+    //   part (llms-documents/option-parts/option.*.md) -> part: "option",     
       root: "../option"
+    const sameDocPartPrefix = isRoot ? `${docName}-parts/${docName}` : docName;
+    const sameDocRootPath = isRoot ? docName : `../${docName}`;
+    const crossDocPrefix = isRoot ? '' : '../';
+
+    // Same-doc links: href="#title.show" -> href="option.title.md#show"
+    const resolved = html.replace(/href="#([^"]+)"/g, (match, linkPath) =>
+        partKeys ? resolveLink(linkPath, partKeys, sameDocPartPrefix, 
sameDocRootPath) : match
+    );
+
+    // Cross-doc links: href="api.html#echarts.init" -> 
href="../api-parts/api.echarts.md#init"
+    const crossResolved = resolved.replace(
+        /href="(option-gl|option|api|tutorial)\.html#([^"]+)"/g,
+        (match, targetDoc, fragment) => {
+            const keys = partKeysByDoc[targetDoc];
+            if (!keys) return match;
+            return resolveLink(fragment, keys, 
`${crossDocPrefix}${targetDoc}-parts/${targetDoc}`, 
`${crossDocPrefix}${targetDoc}`);
+        }
+    );
+
+    // Image paths: src="documents/asset/..." -> relative path to 
public/{lang}/documents/asset/
+    const imgPrefix = isRoot ? '../' : '../../';
+    return crossResolved.replace(
+        /src="(documents\/asset\/[^"]*)"/g,
+        (_, src) => `src="${imgPrefix}${src}"`
+    );
+}
+
+// --- Convert part JSON to Markdown ---
+
+function formatPropertyEntry(key, entry, typeInfo, linkResolver) {
+    const heading = '#'.repeat(Math.min(key.split('.').length + 1, 
MAX_HEADING_DEPTH)) + ' ' + key;
+    const meta = [
+        typeInfo && typeInfo.type && `- **Type**: \`${typeInfo.type}\``,
+        typeInfo && typeInfo.default != null && `- **Default**: 
\`${typeInfo.default}\``

Review Comment:
   When rendering metadata, `typeInfo.default != null` will suppress a captured 
default value of `null`. If you change default-capture to include null, also 
update this check to test for presence (e.g. `'default' in typeInfo`) so the 
output includes `- **Default**: `null`` when appropriate.
   ```suggestion
           typeInfo && Object.prototype.hasOwnProperty.call(typeInfo, 
'default') && `- **Default**: \`${typeInfo.default}\``
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to