@didnhdj/fnmap 0.1.13 → 0.1.14
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.
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/analyzer/index.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAEV,aAAa,EAMd,MAAM,UAAU,CAAC;AAGlB,OAAO,EAAE,uBAAuB,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/analyzer/index.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAEV,aAAa,EAMd,MAAM,UAAU,CAAC;AAGlB,OAAO,EAAE,uBAAuB,EAAqB,MAAM,SAAS,CAAC;AAKrE;;GAEG;AACH,wBAAgB,WAAW,CAAC,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,GAAG,IAAI,GAAG,aAAa,CA+YjF;AAoFD,OAAO,EAAE,uBAAuB,EAAE,CAAC"}
|
package/dist/analyzer/jsdoc.d.ts
CHANGED
|
@@ -1,6 +1,12 @@
|
|
|
1
|
-
import type { Comment } from '@babel/types';
|
|
1
|
+
import type { Comment, Node } from '@babel/types';
|
|
2
2
|
/**
|
|
3
3
|
* 从JSDoc注释中提取描述
|
|
4
|
+
* 优先级: @description标签 > 第一行非标签内容
|
|
4
5
|
*/
|
|
5
6
|
export declare function extractJSDocDescription(comment: Comment | null | undefined): string;
|
|
7
|
+
/**
|
|
8
|
+
* 从节点获取leadingComments,支持导出声明
|
|
9
|
+
* 当节点本身没有注释时,检查父节点(ExportNamedDeclaration/ExportDefaultDeclaration)
|
|
10
|
+
*/
|
|
11
|
+
export declare function getLeadingComment(node: Node, parent: Node | null | undefined): Comment | null;
|
|
6
12
|
//# sourceMappingURL=jsdoc.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"jsdoc.d.ts","sourceRoot":"","sources":["../../src/analyzer/jsdoc.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;
|
|
1
|
+
{"version":3,"file":"jsdoc.d.ts","sourceRoot":"","sources":["../../src/analyzer/jsdoc.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,cAAc,CAAC;AAElD;;;GAGG;AACH,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,GAAG,SAAS,GAAG,MAAM,CAqBnF;AAED;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,GAAG,IAAI,GAAG,SAAS,GAAG,OAAO,GAAG,IAAI,CAe7F"}
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const
|
|
3
|
-
`)}let w=!1,
|
|
2
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const C=require("fs"),h=require("path"),Fe=require("commander"),P=require("child_process"),Ie=require("@babel/parser"),z=require("@babel/traverse"),A={FILE_NOT_FOUND:"FILE_NOT_FOUND",FILE_READ_ERROR:"FILE_READ_ERROR",PARSE_ERROR:"PARSE_ERROR",CONFIG_ERROR:"CONFIG_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",PERMISSION_ERROR:"PERMISSION_ERROR",FILE_TOO_LARGE:"FILE_TOO_LARGE"};function Y(e){return"parseError"in e}function Ce(e){return e.success===!0}function be(e){return e.success===!1}function xe(e){return e.valid===!0}function Ae(e){return e.valid===!1}const x={reset:"\x1B[0m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",gray:"\x1B[90m",bold:"\x1B[1m"},K=10*1024*1024,X=50,W=[".js",".ts",".jsx",".tsx",".mjs"],ee=["node_modules",".git","dist","build",".next","coverage","__pycache__",".cache"],H={enable:!0,include:["**/*.js","**/*.ts","**/*.jsx","**/*.tsx","**/*.mjs"],exclude:[]};function le(e){if(!e||typeof e!="string")return{valid:!1,error:"File path is required and must be a string / 文件路径必须是字符串",errorType:A.VALIDATION_ERROR};if(!C.existsSync(e))return{valid:!1,error:`File not found: ${e} / 文件不存在: ${e}`,errorType:A.FILE_NOT_FOUND};try{const o=C.statSync(e);if(!o.isFile())return{valid:!1,error:`Path is not a file: ${e} / 路径不是文件: ${e}`,errorType:A.VALIDATION_ERROR};if(o.size>K)return{valid:!1,error:`File too large (${(o.size/1024/1024).toFixed(2)}MB > ${K/1024/1024}MB): ${e} / 文件过大`,errorType:A.FILE_TOO_LARGE}}catch(o){return{valid:!1,error:`Cannot access file: ${e}. Reason: ${o.message} / 无法访问文件`,errorType:A.PERMISSION_ERROR}}return{valid:!0}}function Q(e){if(!e||typeof e!="object")return{valid:!1,error:"Config must be an object / 配置必须是对象"};const o=e;return o.enable!==void 0&&typeof o.enable!="boolean"?{valid:!1,error:"Config.enable must be a boolean / enable 字段必须是布尔值"}:o.include!==void 0&&!Array.isArray(o.include)?{valid:!1,error:"Config.include must be an array / include 字段必须是数组"}:o.exclude!==void 0&&!Array.isArray(o.exclude)?{valid:!1,error:"Config.exclude must be an array / exclude 字段必须是数组"}:{valid:!0}}function q(e,o,s={}){const n=[o];return s.file&&n.push(`File: ${s.file}`),s.line!==void 0&&s.column!==void 0&&n.push(`Location: Line ${s.line}, Column ${s.column}`),s.suggestion&&n.push(`Suggestion: ${s.suggestion}`),n.join(`
|
|
3
|
+
`)}let w=!1,G=null;const $={error:e=>{w||console.error(`${x.red}✗${x.reset} ${e}`)},success:e=>{w||console.log(`${x.green}✓${x.reset} ${e}`)},info:e=>{w||console.log(e)},warn:e=>{w||console.warn(`${x.yellow}!${x.reset} ${e}`)},title:e=>{w||console.log(`${x.bold}${e}${x.reset}`)}};function fe(e){w=e}function ve(){return w}function de(){try{return require("../../package.json").version}catch{return"0.1.0"}}function ne(){return G=new Fe.Command,G.name("fnmap").description("AI code indexing tool - Analyzes JS/TS code structure and generates structured code maps").version(de(),"-v, --version","Show version number").option("-f, --files <files>","Process specified files (comma-separated)",e=>e.split(",").map(o=>o.trim()).filter(Boolean)).option("-d, --dir <dir>","Process all code files in directory").option("-p, --project <dir>","Specify project root directory",process.env.CLAUDE_PROJECT_DIR??process.cwd()).option("-c, --changed","Process only git changed files (staged + modified + untracked)").option("-s, --staged","Process only git staged files (for pre-commit hook)").option("-m, --mermaid [mode]","Generate Mermaid call graph (file=file-level, project=project-level)").option("-q, --quiet","Quiet mode").option("--init","Create default config file .fnmaprc").argument("[files...]","Directly specify file paths").allowUnknownOption(!1).addHelpText("after",`
|
|
4
4
|
Configuration files (by priority):
|
|
5
5
|
.fnmaprc JSON config file
|
|
6
6
|
.fnmaprc.json JSON config file
|
|
@@ -19,16 +19,16 @@ Examples:
|
|
|
19
19
|
$ fnmap --mermaid file --dir src Generate file-level call graphs
|
|
20
20
|
$ fnmap --mermaid project Generate project-level call graph
|
|
21
21
|
$ fnmap --init Create config file
|
|
22
|
-
`),
|
|
22
|
+
`),G}function M(){return G||ne()}const _e={get opts(){return M().opts.bind(M())},get args(){return M().args},get parse(){return M().parse.bind(M())}};function ue(e){const o=[".fnmaprc",".fnmaprc.json"];for(const n of o){const a=h.join(e,n);if(C.existsSync(a))try{const l=C.readFileSync(a,"utf-8");if(!l.trim()){$.warn(`Config file is empty: ${n}. Using default config / 配置文件为空,使用默认配置`);continue}let g;try{g=JSON.parse(l)}catch(d){const m=d,r=q(A.CONFIG_ERROR,`Failed to parse config file: ${n} / 配置文件解析失败`,{file:a,line:m.lineNumber,column:m.columnNumber,suggestion:"Check JSON syntax, ensure proper quotes and commas / 检查 JSON 语法,确保引号和逗号正确"});$.warn(r);continue}const p=Q(g);if(!p.valid){$.warn(`Invalid config in ${n}: ${p.error}`);continue}return{config:g,source:n}}catch(l){const g=l,p=q(A.FILE_READ_ERROR,`Failed to read config file: ${n} / 配置文件读取失败`,{file:a,suggestion:g.message});$.warn(p)}}const s=h.join(e,"package.json");if(C.existsSync(s))try{const n=JSON.parse(C.readFileSync(s,"utf-8"));if(n.fnmap){const a=Q(n.fnmap);if(!a.valid)$.warn(`Invalid fnmap config in package.json: ${a.error}`);else return{config:n.fnmap,source:"package.json#fnmap"}}}catch{}return{config:null,source:null}}function pe(e){return e?{...H,...e,exclude:[...e.exclude??[]]}:H}function te(e){return e.endsWith(".d.ts")||e.endsWith(".d.tsx")||e.endsWith(".d.mts")}function Ne(e){try{return P.execSync("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8"}).trim()}catch{return null}}function me(e,o=!1){const s=[];try{const n=Ne(e);if(!n)return[];let a;if(o)a=P.execSync("git diff --cached --name-only --diff-filter=ACMR",{cwd:e,encoding:"utf-8"});else{const p=P.execSync("git diff --cached --name-only --diff-filter=ACMR",{cwd:e,encoding:"utf-8"}),d=P.execSync("git diff --name-only --diff-filter=ACMR",{cwd:e,encoding:"utf-8"}),m=P.execSync("git ls-files --others --exclude-standard",{cwd:e,encoding:"utf-8"});a=`${p}
|
|
23
23
|
${d}
|
|
24
|
-
${m}`}const l=
|
|
25
|
-
`).map(p=>p.trim()).filter(Boolean).filter(p=>{const d=h.extname(p);return
|
|
26
|
-
`).map(n=>n.replace(/^\s*\*\s?/,"").trim());for(const n of s)if(n.startsWith("@description "))return n.slice(13).trim().slice(0,60);for(const n of s)if(n&&!n.startsWith("@")&&!n.startsWith("/"))return n.slice(0,60);return""}const J=typeof
|
|
27
|
-
`).map(
|
|
28
|
-
`)}function
|
|
29
|
-
`)}function ge(e,o){const s=["flowchart TD"],n=r=>"id_"+r.replace(/[^a-zA-Z0-9]/g,u=>`_${u.charCodeAt(0)}_`),
|
|
30
|
-
`)}function ye(e,o){const s=["flowchart TD"],n=d=>"id_"+d.replace(/[^a-zA-Z0-9]/g,m=>`_${m.charCodeAt(0)}_`),
|
|
31
|
-
`)}function
|
|
24
|
+
${m}`}const l=a.split(`
|
|
25
|
+
`).map(p=>p.trim()).filter(Boolean).filter(p=>{const d=h.extname(p);return W.includes(d)&&!te(p)}),g=[...new Set(l)];for(const p of g){const d=h.resolve(n,p);C.existsSync(d)&&d.startsWith(h.resolve(e))&&s.push(d)}}catch{return[]}return s}function Te(e){const o=[];if(!C.existsSync(e))return o;try{const s=C.readdirSync(e,{withFileTypes:!0});for(const n of s)if(n.isFile()){const a=h.extname(n.name);W.includes(a)&&!te(n.name)&&o.push(h.join(e,n.name))}}catch{return o}return o}function U(e,o=e,s=ee,n=0,a=new Set){const l=[];if(!C.existsSync(e))return $.warn(`Directory does not exist: ${e} / 目录不存在`),l;if(n>X)return $.warn(`Max directory depth (${X}) exceeded: ${e} / 超过最大目录深度`),l;let g;try{g=C.realpathSync(e)}catch(d){const m=d;return $.warn(`Cannot resolve real path: ${e}. Reason: ${m.message} / 无法解析真实路径`),l}if(a.has(g))return $.warn(`Circular reference detected, skipping: ${e} / 检测到循环引用`),l;a.add(g);let p;try{p=C.readdirSync(e,{withFileTypes:!0})}catch(d){const m=d;return m.code==="EACCES"||m.code==="EPERM"?$.warn(`Permission denied: ${e} / 权限不足`):$.warn(`Failed to read directory: ${e}. Reason: ${m.message} / 读取目录失败`),l}for(const d of p)try{const m=h.join(e,d.name);if(d.isDirectory())s.includes(d.name)||l.push(...U(m,o,s,n+1,a));else if(d.isFile()){const r=h.extname(d.name);W.includes(r)&&!te(d.name)&&l.push(h.relative(o,m))}}catch(m){const r=m;$.warn(`Error processing entry: ${d.name}. Reason: ${r.message} / 处理条目出错`)}return l}function k(e){if(!e)return"";const s=e.value.split(`
|
|
26
|
+
`).map(n=>n.replace(/^\s*\*\s?/,"").trim());for(const n of s)if(n.startsWith("@description "))return n.slice(13).trim().slice(0,60);for(const n of s)if(n&&!n.startsWith("@")&&!n.startsWith("/"))return n.slice(0,60);return""}function B(e,o){if(e.leadingComments&&e.leadingComments.length>0)return e.leadingComments[e.leadingComments.length-1]??null;if(o&&(o.type==="ExportNamedDeclaration"||o.type==="ExportDefaultDeclaration")){const s=o;if(s.leadingComments&&s.leadingComments.length>0)return s.leadingComments[s.leadingComments.length-1]??null}return null}const J=typeof z=="function"?z:z.default;function re(e,o){var f,S;if(e==null)return{parseError:"Code content is null or undefined / 代码内容为空",errorType:A.VALIDATION_ERROR};if(typeof e!="string")return{parseError:"Code must be a string / 代码必须是字符串类型",errorType:A.VALIDATION_ERROR};if(!e.trim())return{description:"",imports:[],functions:[],classes:[],constants:[],callGraph:{}};const s={description:"",imports:[],functions:[],classes:[],constants:[],callGraph:{}},n=e.match(/^\/\*\*[\s\S]*?\*\//);if(n){const t=n[0].split(`
|
|
27
|
+
`).map(i=>i.replace(/^\s*\*\s?/,"").trim()).filter(i=>i&&!i.startsWith("/")&&!i.startsWith("@ai"));for(const i of t)if(i.startsWith("@description ")){s.description=i.slice(13).trim();break}if(!s.description&&t.length>0){const i=t.find(y=>!y.startsWith("@"));i&&(s.description=i)}}let a;try{const c=o&&(o.endsWith(".ts")||o.endsWith(".tsx"));a=Ie.parse(e,{sourceType:"unambiguous",plugins:["jsx","classPrivateProperties","classPrivateMethods",...c?["typescript"]:[]]})}catch(c){const t=c;return{parseError:q(A.PARSE_ERROR,`Syntax error: ${t.message} / 语法错误`,{file:o??void 0,line:(f=t.loc)==null?void 0:f.line,column:(S=t.loc)==null?void 0:S.column,suggestion:"Check syntax errors in the file / 检查文件中的语法错误"}),loc:t.loc,errorType:A.PARSE_ERROR}}const l=new Map,g=new Map,p=new Map;function d(c){var i,y,I;let t=c;for(;t;){if(t.node.type==="FunctionDeclaration"){const E=t.node;if(E.id)return E.id.name}if(t.node.type==="ClassMethod"){const E=t.node,F=(i=t.parentPath)==null?void 0:i.parentPath,R=F==null?void 0:F.node,b=((y=R==null?void 0:R.id)==null?void 0:y.name)??"",v=((I=E.key)==null?void 0:I.name)??"";return b?`${b}.${v}`:v}if(t.node.type==="ArrowFunctionExpression"||t.node.type==="FunctionExpression"){const E=t.parent;if((E==null?void 0:E.type)==="VariableDeclarator"){const R=E.id;if(R!=null&&R.name)return R.name}}t=t.parentPath}return null}J(a,{VariableDeclarator(c){var i,y,I,E;const t=c.node;if(((i=t.init)==null?void 0:i.type)==="CallExpression"&&((y=t.init.callee)==null?void 0:y.type)==="Identifier"&&t.init.callee.name==="require"&&((E=(I=t.init.arguments)==null?void 0:I[0])==null?void 0:E.type)==="StringLiteral"){const F=t.init.arguments[0].value;if(l.has(F)||l.set(F,new Set),t.id.type==="Identifier"){const R=t.id.name;l.get(F).add(R),g.set(R,F),p.set(R,new Set)}else if(t.id.type==="ObjectPattern"){for(const R of t.id.properties)if(R.type==="ObjectProperty"&&R.key.type==="Identifier"){const b=R.value.type==="Identifier"?R.value.name:R.key.name;l.get(F).add(R.key.name),g.set(b,F),p.set(b,new Set)}}}},CallExpression(c){var i,y,I,E,F,R;const t=c.node;if(((i=t.callee)==null?void 0:i.type)==="Identifier"&&t.callee.name==="require"&&((I=(y=t.arguments)==null?void 0:y[0])==null?void 0:I.type)==="StringLiteral"){const b=c.parent;if((b==null?void 0:b.type)==="MemberExpression"&&((E=b.property)==null?void 0:E.type)==="Identifier"){const v=t.arguments[0].value;l.has(v)||l.set(v,new Set),l.get(v).add(b.property.name);const N=(F=c.parentPath)==null?void 0:F.parent;if((N==null?void 0:N.type)==="VariableDeclarator"){const T=N;((R=T.id)==null?void 0:R.type)==="Identifier"&&(g.set(T.id.name,v),p.set(T.id.name,new Set))}}}},ImportDeclaration(c){const t=c.node,i=t.source.value;l.has(i)||l.set(i,new Set);for(const y of t.specifiers){let I,E;if(y.type==="ImportDefaultSpecifier")I="default",E=y.local.name;else if(y.type==="ImportNamespaceSpecifier")I="*",E=y.local.name;else if(y.type==="ImportSpecifier"){const F=y.imported;I=F.type==="Identifier"?F.name:F.value,E=y.local.name}I&&E&&(l.get(i).add(I),g.set(E,i),p.set(E,new Set))}}}),J(a,{Identifier(c){const t=c.node.name;if(p.has(t)){const i=c.parent;if((i==null?void 0:i.type)==="VariableDeclarator"&&i.id===c.node||(i==null?void 0:i.type)==="ImportSpecifier"||(i==null?void 0:i.type)==="ImportDefaultSpecifier")return;const y=d(c);y&&p.get(t).add(y)}},FunctionDeclaration(c){var R,b,v,N,T;const t=c.node,i=((R=t.id)==null?void 0:R.name)??"[anonymous]",y=t.params.map(_=>{var D,L;return _.type==="Identifier"?_.name:_.type==="AssignmentPattern"&&((D=_.left)==null?void 0:D.type)==="Identifier"?_.left.name+"?":_.type==="RestElement"&&((L=_.argument)==null?void 0:L.type)==="Identifier"?"..."+_.argument.name:"?"}),I=((v=(b=t.loc)==null?void 0:b.start)==null?void 0:v.line)??0,E=((T=(N=t.loc)==null?void 0:N.end)==null?void 0:T.line)??0,F=k(B(t,c.parent));s.functions.push({name:i,params:y.join(","),startLine:I,endLine:E,description:F})},ClassDeclaration(c){var b,v,N,T,_,D,L,se,oe,ie;const t=c.node,i=((b=t.id)==null?void 0:b.name)??"[anonymous]",y=((N=(v=t.loc)==null?void 0:v.start)==null?void 0:N.line)??0,I=((_=(T=t.loc)==null?void 0:T.end)==null?void 0:_.line)??0,E=((D=t.superClass)==null?void 0:D.type)==="Identifier"?t.superClass.name:null,F=k(B(t,c.parent)),R=[];if((L=t.body)!=null&&L.body){for(const O of t.body.body)if(O.type==="ClassMethod"){const Ee=((se=O.key)==null?void 0:se.type)==="Identifier"?O.key.name:"[computed]",Se=O.params.map(j=>{var ce;return j.type==="Identifier"?j.name:j.type==="AssignmentPattern"&&((ce=j.left)==null?void 0:ce.type)==="Identifier"?j.left.name+"?":"?"}),Re=((ie=(oe=O.loc)==null?void 0:oe.start)==null?void 0:ie.line)??0;let ae="";const V=O.leadingComments;V&&V.length>0&&(ae=k(V[V.length-1])),R.push({name:Ee,params:Se.join(","),line:Re,static:O.static,kind:O.kind,description:ae})}}s.classes.push({name:i,superClass:E,startLine:y,endLine:I,methods:R,description:F})},VariableDeclaration(c){var y,I,E;const t=c.parent.type;if(t!=="Program"&&t!=="ExportNamedDeclaration")return;const i=c.node;if(i.kind==="const"){const F=k(B(i,c.parent));for(const R of i.declarations){const b=((y=R.id)==null?void 0:y.type)==="Identifier"?R.id.name:void 0;if(b&&b===b.toUpperCase()&&b.length>2){const v=((E=(I=i.loc)==null?void 0:I.start)==null?void 0:E.line)??0;s.constants.push({name:b,line:v,description:F})}}}}});for(const[c,t]of l){const i=new Set;for(const y of g.keys())if(g.get(y)===c&&p.has(y))for(const I of p.get(y))i.add(I);s.imports.push({module:c,members:Array.from(t),usedIn:Array.from(i)})}const m=new Set;for(const c of s.functions)m.add(c.name);for(const c of s.classes)for(const t of c.methods)m.add(t.name),m.add(`${c.name}.${t.name}`);const r=new Set(g.keys()),u=new Map;J(a,{CallExpression(c){var y,I;const t=c.node;let i=null;if(t.callee.type==="Identifier")i=t.callee.name;else if(t.callee.type==="MemberExpression"&&((y=t.callee.property)==null?void 0:y.type)==="Identifier"){const E=((I=t.callee.object)==null?void 0:I.type)==="Identifier"?t.callee.object.name:void 0,F=t.callee.property.name;E&&r.has(E)?i=`${E}.${F}`:i=F}if(i){const E=d(c);if(E&&E!==i){const F=m.has(i),R=r.has(i)||i.includes(".")&&r.has(i.split(".")[0]);(F||R)&&(u.has(E)||u.set(E,new Set),u.get(E).add(i))}}}}),s.callGraph={};for(const[c,t]of u)s.callGraph[c]=Array.from(t);return s.isPureType=Oe(a),s}function Oe(e){let o=!1;for(const s of e.program.body){switch(s.type){case"TSTypeAliasDeclaration":case"TSInterfaceDeclaration":case"TSEnumDeclaration":break;case"ImportDeclaration":s.importKind!=="type"&&s.specifiers.some(a=>a.type==="ImportSpecifier"?a.importKind!=="type":!0)&&s.specifiers.length>0&&(o=!0);break;case"ExportNamedDeclaration":if(s.exportKind==="type")break;if(s.declaration){const n=s.declaration.type;n!=="TSTypeAliasDeclaration"&&n!=="TSInterfaceDeclaration"&&(o=!0)}else s.specifiers&&s.specifiers.length>0&&s.specifiers.some(a=>a.type==="ExportSpecifier"?a.exportKind!=="type":!0)&&(o=!0);break;case"ExportDefaultDeclaration":o=!0;break;case"ExportAllDeclaration":s.exportKind!=="type"&&(o=!0);break;default:o=!0;break}if(o)break}return!o}function we(e,o){const s=[];let n=`/*@AI ${o}`;e.description&&(n+=` - ${e.description.slice(0,50)}`),s.push(n);for(const a of e.imports){const l=Array.isArray(a.members)?a.members.join(","):"";let g=`<${a.module}:${l}`;Array.isArray(a.usedIn)&&a.usedIn.length>0&&(g+=` ->${a.usedIn.join(",")}`),s.push(g)}for(const a of e.classes){let l=a.name;a.superClass&&(l+=`:${a.superClass}`),l+=` ${a.startLine}-${a.endLine}`,a.description&&(l+=` ${a.description}`),s.push(l);for(const g of a.methods){const p=g.static?" +":" .",d=g.kind==="get"?"get:":g.kind==="set"?"set:":"";let m=`${p}${d}${g.name}(${g.params}) ${g.line}`;g.description&&(m+=` ${g.description}`),s.push(m)}}for(const a of e.functions){let l=`${a.name}(${a.params}) ${a.startLine}-${a.endLine}`;a.description&&(l+=` ${a.description}`),s.push(l)}for(const a of e.constants){let l=`${a.name} ${a.line}`;a.description&&(l+=` ${a.description}`),s.push(l)}return s.push("@AI*/"),s.join(`
|
|
28
|
+
`)}function De(e){let o=e;return o=o.replace(/\/\*@AI[\s\S]*?@AI\*\/\s*/g,""),o=o.replace(/\/\*\*[\s\S]*?@ai-context-end[\s\S]*?\*\/\s*/g,""),o=o.replace(/^\/\*\*[\s\S]*?\*\/\s*\n?/,""),o}function Z(e,o){var n,a,l;const s=[`@FNMAP ${h.basename(e)}/`];for(const{relativePath:g,info:p}of o){let m=`#${h.basename(g)}`;p.description&&(m+=` ${p.description.slice(0,50)}`),s.push(m);for(const r of p.imports){const u=Array.isArray(r.members)?r.members.join(","):"";s.push(` <${r.module}:${u}`)}for(const r of p.classes){let u=` ${r.name}`;r.superClass&&(u+=`:${r.superClass}`),u+=` ${r.startLine}-${r.endLine}`,r.description&&(u+=` ${r.description}`),s.push(u);for(const f of r.methods){const S=f.static?" +":" .",c=f.kind==="get"?"get:":f.kind==="set"?"set:":"";let t=`${S}${c}${f.name}(${f.params}) ${f.line}`;f.description&&(t+=` ${f.description}`);const i=`${r.name}.${f.name}`,y=((n=p.callGraph)==null?void 0:n[i])??((a=p.callGraph)==null?void 0:a[f.name]);Array.isArray(y)&&y.length>0&&(t+=` →${y.join(",")}`),s.push(t)}}for(const r of p.functions){let u=` ${r.name}(${r.params}) ${r.startLine}-${r.endLine}`;r.description&&(u+=` ${r.description}`);const f=(l=p.callGraph)==null?void 0:l[r.name];Array.isArray(f)&&f.length>0&&(u+=` →${f.join(",")}`),s.push(u)}for(const r of p.constants){let u=` ${r.name} ${r.line}`;r.description&&(u+=` ${r.description}`),s.push(u)}}return s.push("@FNMAP"),s.join(`
|
|
29
|
+
`)}function ge(e,o){const s=["flowchart TD"],n=r=>"id_"+r.replace(/[^a-zA-Z0-9]/g,u=>`_${u.charCodeAt(0)}_`),a=r=>r.replace(/"/g,"#quot;"),l=o.functions.map(r=>r.name),g=[];for(const r of o.classes)for(const u of r.methods)g.push(`${r.name}.${u.name}`);const p=[...l,...g];if(p.length===0)return null;const d=h.basename(e,h.extname(e));s.push(` subgraph ${n(d)}["${d}"]`);for(const r of p)s.push(` ${n(r)}["${a(r)}"]`);s.push(" end");const m=o.callGraph??{};for(const[r,u]of Object.entries(m))if(Array.isArray(u)){for(const f of u)if(p.includes(f)||f.includes(".")){const S=p.includes(f)?f:f.split(".").pop();(p.includes(f)||p.some(c=>c.endsWith(S)))&&s.push(` ${n(r)} --> ${n(f)}`)}}return s.join(`
|
|
30
|
+
`)}function ye(e,o){const s=["flowchart TD"],n=d=>"id_"+d.replace(/[^a-zA-Z0-9]/g,m=>`_${m.charCodeAt(0)}_`),a=d=>d.replace(/"/g,"#quot;"),l=new Map,g=[];for(const{relativePath:d,info:m}of o){const r=h.basename(d,h.extname(d)),u=m.functions.map(t=>t.name),f=[];for(const t of m.classes)for(const i of t.methods)f.push(`${t.name}.${i.name}`);const S=[...u,...f];l.set(d,{fileName:r,functions:S});const c=m.callGraph??{};for(const[t,i]of Object.entries(c))if(Array.isArray(i))for(const y of i)g.push({file:d,fileName:r,caller:t,callee:y})}for(const[,{fileName:d,functions:m}]of l)if(m.length!==0){s.push(` subgraph ${n(d)}["${a(d)}"]`);for(const r of m)s.push(` ${n(d)}_${n(r)}["${a(r)}"]`);s.push(" end")}const p=new Set;for(const{fileName:d,caller:m,callee:r}of g){const u=`${n(d)}_${n(m)}`;let f=null;for(const[,{fileName:S,functions:c}]of l)if(c.includes(r)){f=`${n(S)}_${n(r)}`;break}if(!f){const S=[...l.keys()].find(c=>{var t;return((t=l.get(c))==null?void 0:t.fileName)===d});if(S){const c=l.get(S);c!=null&&c.functions.includes(r)&&(f=`${n(d)}_${n(r)}`)}}if(f){const S=`${u}-->${f}`;p.has(S)||(s.push(` ${u} --> ${f}`),p.add(S))}}return s.join(`
|
|
31
|
+
`)}function Le(e,o){const s=(o==null?void 0:o.filePath)??null;try{const n=re(e,s);return n?Y(n)?{success:!1,error:n.parseError,errorType:n.errorType,loc:n.loc}:{success:!0,info:n}:{success:!1,error:"Analysis returned null / 分析返回空值",errorType:A.PARSE_ERROR}}catch(n){return{success:!1,error:`Failed to process code / 处理代码失败: ${n.message}`,errorType:A.PARSE_ERROR}}}function he(e){const o=le(e);if(!o.valid)return{success:!1,error:o.error,errorType:o.errorType??A.VALIDATION_ERROR};try{const s=C.readFileSync(e,"utf-8"),n=re(s,e);return n?Y(n)?{success:!1,error:n.parseError,errorType:n.errorType,loc:n.loc}:{success:!0,info:n}:{success:!1,error:"Analysis returned null / 分析返回空值",errorType:A.PARSE_ERROR}}catch(s){const n=s;return{success:!1,error:q(A.FILE_READ_ERROR,"Failed to read or process file / 读取或处理文件失败",{file:e,suggestion:n.message}),errorType:A.FILE_READ_ERROR}}}const je=`
|
|
32
32
|
|
|
33
33
|
## .fnmap Code Index Format
|
|
34
34
|
|
|
@@ -53,8 +53,8 @@ The \`.fnmap\` file provides a structured code index for quick navigation. Read
|
|
|
53
53
|
1. Every global variable, function, class, and file module must have a **concise comment describing its purpose or functionality** - avoid describing anything else
|
|
54
54
|
2. When updating code, always update related comments to reflect the changes
|
|
55
55
|
3. Prefer encapsulating logic in functions rather than writing flat, sequential code
|
|
56
|
-
`;function Me(e){const o=["CLAUDE.md","AGENTS.md"],s=
|
|
56
|
+
`;function Me(e){const o=["CLAUDE.md","AGENTS.md"],s=C.readdirSync(e);for(const n of o){const a=s.find(l=>l.toLowerCase()===n.toLowerCase());if(a){const l=h.join(e,a);if(C.readFileSync(l,"utf-8").includes(".fnmap Code Index Format")){console.log(`${x.yellow}!${x.reset} ${a} already contains fnmap documentation`);continue}C.appendFileSync(l,je),console.log(`${x.green}✓${x.reset} Appended fnmap documentation to ${a}`)}}}function $e(){const e=ne();e.parse(process.argv);const o=e.opts(),s=e.args;o.quiet&&fe(!0);const n=h.resolve(o.project);if(o.init){const r=h.join(n,".fnmaprc");if(C.existsSync(r))console.log(`${x.yellow}!${x.reset} Config file already exists: .fnmaprc`);else{const u={enable:!0,include:["src/**/*.js","src/**/*.ts","src/**/*.jsx","src/**/*.tsx"],exclude:["node_modules","dist","build",".next","coverage","__pycache__",".cache"]};C.writeFileSync(r,JSON.stringify(u,null,2)),console.log(`${x.green}✓${x.reset} Created config file: .fnmaprc`)}Me(n);return}const a=[...o.files??[],...s].filter(r=>C.existsSync(r));let l=[],g=!1;if(o.changed||o.staged){const r=me(n,o.staged);if(r.length===0){$.info("No git changed code files detected");return}const u=new Set;for(const f of r)u.add(h.dirname(f));for(const f of u){const S=Te(f);l.push(...S)}}else if(a.length>0)g=!0,l=a.map(r=>h.isAbsolute(r)?r:h.resolve(n,r));else if(o.dir){const r=h.resolve(n,o.dir);l=U(r,n).map(f=>h.join(n,f))}else{const{config:r,source:u}=ue(n);if(r){if($.info(`Using config: ${u}`),r.enable===!1){$.info("Config file has enable set to false, skipping processing");return}const f=pe(r),S=[...ee,...f.exclude];if(f.include)for(const c of f.include){const t=c.replace(/\/\*\*\/.*$/,"").replace(/\*\*\/.*$/,""),i=t?h.resolve(n,t):n;if(C.existsSync(i)){const y=U(i,n,S);l.push(...y.map(I=>h.join(n,I)))}}}else{$.warn("No config file found. Use fnmap init to create config, or use --dir/--files to specify scope"),$.info(""),$.info("Supported config files: .fnmaprc, .fnmaprc.json, package.json#fnmap");return}}if(l.length===0){$.info("No files found to process");return}l=[...new Set(l)],$.info("=".repeat(50)),$.title("fnmap - AI Code Indexing Tool"),$.info("=".repeat(50));let p=0,d=0;const m=new Map;for(const r of l){const u=h.relative(n,r);$.info(`
|
|
57
57
|
Analyzing: ${u}`);const f=he(r);if(f.success){p++;const S=f.info;if(S.isPureType){$.info("Skipped (pure type file) / 跳过纯类型文件");continue}$.success(`Imports: ${S.imports.length}, Functions: ${S.functions.length}, Classes: ${S.classes.length}, Constants: ${S.constants.length}`);const c=h.dirname(r);m.has(c)||m.set(c,[]),m.get(c).push({relativePath:u,info:S})}else d++,$.error(f.error)}if(m.size>0)if($.info(`
|
|
58
|
-
Generating .fnmap index...`),g)for(const[r,u]of m)for(const{relativePath:f,info:S}of u)try{const c=Z(r,[{relativePath:f,info:S}]),t=h.basename(f,h.extname(f)),
|
|
59
|
-
Generating Mermaid call graphs...`),o.mermaid==="file"||o.mermaid===!0)for(const[r,u]of m)for(const{relativePath:f,info:S}of u)try{const c=ge(f,S);if(c){const t=h.basename(f,h.extname(f)),
|
|
60
|
-
`+"=".repeat(50)),$.info(`Complete! Analyzed: ${
|
|
58
|
+
Generating .fnmap index...`),g)for(const[r,u]of m)for(const{relativePath:f,info:S}of u)try{const c=Z(r,[{relativePath:f,info:S}]),t=h.basename(f,h.extname(f)),i=h.join(r,`${t}.fnmap`);C.writeFileSync(i,c),$.success(h.relative(n,i))}catch(c){const t=c;$.error(`Failed to generate .fnmap for ${f}: ${t.message}`)}else for(const[r,u]of m)try{const f=Z(r,u),S=h.join(r,".fnmap");C.writeFileSync(S,f),$.success(h.relative(n,S))}catch(f){const S=f;$.error(`Failed to generate .fnmap for ${h.relative(n,r)}: ${S.message}`)}if(o.mermaid&&m.size>0){if($.info(`
|
|
59
|
+
Generating Mermaid call graphs...`),o.mermaid==="file"||o.mermaid===!0)for(const[r,u]of m)for(const{relativePath:f,info:S}of u)try{const c=ge(f,S);if(c){const t=h.basename(f,h.extname(f)),i=h.join(r,`${t}.mermaid`);C.writeFileSync(i,c),$.success(h.relative(n,i))}}catch(c){const t=c;$.error(`Failed to generate mermaid for ${f}: ${t.message}`)}else if(o.mermaid==="project")try{const r=[];for(const[,S]of m)r.push(...S);const u=ye(n,r),f=h.join(n,".fnmap.mermaid");C.writeFileSync(f,u),$.success(h.relative(n,f))}catch(r){const u=r;$.error(`Failed to generate project mermaid: ${u.message}`)}}$.info(`
|
|
60
|
+
`+"=".repeat(50)),$.info(`Complete! Analyzed: ${x.green}${p}${x.reset}, Failed: ${d>0?x.red:""}${d}${x.reset}`),$.info("=".repeat(50))}require.main===module&&$e();exports.COLORS=x;exports.DEFAULT_CONFIG=H;exports.DEFAULT_EXCLUDES=ee;exports.ErrorTypes=A;exports.MAX_DIR_DEPTH=X;exports.MAX_FILE_SIZE=K;exports.SUPPORTED_EXTENSIONS=W;exports.analyzeFile=re;exports.extractJSDocDescription=k;exports.formatError=q;exports.generateAiMap=Z;exports.generateFileMermaid=ge;exports.generateHeader=we;exports.generateProjectMermaid=ye;exports.getGitChangedFiles=me;exports.getVersion=de;exports.isParseError=Y;exports.isProcessFailure=be;exports.isProcessSuccess=Ce;exports.isQuietMode=ve;exports.isValidationFailure=Ae;exports.isValidationSuccess=xe;exports.loadConfig=ue;exports.logger=$;exports.main=$e;exports.mergeConfig=pe;exports.processCode=Le;exports.processFile=he;exports.program=_e;exports.removeExistingHeaders=De;exports.scanDirectory=U;exports.setQuietMode=fe;exports.setupCLI=ne;exports.validateConfig=Q;exports.validateFilePath=le;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@didnhdj/fnmap",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.14",
|
|
4
4
|
"description": "AI code indexing tool for analyzing JS/TS code structure and generating structured code maps to help AI understand code quickly",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|