@skapxd/tree 1.0.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2016 Manraj Singh
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,99 @@
1
+ # @skapxd/tree
2
+
3
+ [![CI](https://github.com/skapxd/tree/actions/workflows/ci.yml/badge.svg)](https://github.com/skapxd/tree/actions/workflows/ci.yml)
4
+ [![npm version](https://badge.fury.io/js/@skapxd%2Ftree.svg)](https://badge.fury.io/js/@skapxd%2Ftree)
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
6
+
7
+ **Visualize your directory structure with professional ASCII art.**
8
+
9
+ A modern, TypeScript-based CLI tool designed to generate clean, tree-like diagrams of your folder structure. It is optimized for **Documentation** and **AI Context**, providing a token-efficient overview of your codebase.
10
+
11
+ ## 🚀 Quick Start (No Installation)
12
+
13
+ The fastest way to use it is with `npx`. It works instantly in any directory.
14
+
15
+ ```bash
16
+ # View current directory
17
+ npx @skapxd/tree
18
+
19
+ # View a specific folder
20
+ npx @skapxd/tree ./src
21
+ ```
22
+
23
+ ## 🤖 Optimized for AI Agents & LLMs
24
+
25
+ This tool is specifically designed to help AI Agents (like ChatGPT, Claude, Gemini, or GitHub Copilot) understand your project architecture **without consuming massive context windows**.
26
+
27
+ When you need an AI to understand your project structure, run this command and paste the output:
28
+
29
+ ```bash
30
+ npx @skapxd/tree ./src
31
+ ```
32
+
33
+ **Why is this better for AI?**
34
+ * **Context Focus:** By targeting `./src`, you provide the AI with only the relevant business logic, avoiding noise.
35
+ * **Token Efficient:** Uses minimal characters to convey maximum structural information.
36
+ * **High Contrast:** Distinct separation between folders and files helps LLMs parse the hierarchy accurately.
37
+
38
+ ## 🎨 Example Output
39
+
40
+ ```text
41
+ src
42
+ ├── index.ts
43
+ ├── cli.ts
44
+ ├── utils
45
+ │ ├── parser.ts
46
+ │ └── drawer.ts
47
+ └── components
48
+ ├── Button.tsx
49
+ └── Header.tsx
50
+ ```
51
+
52
+ ## ⚙️ Options
53
+
54
+ | Flag | Description | Example |
55
+ | :--- | :--- | :--- |
56
+ | `[dir]` | (Positional) Directory to scan. Defaults to current. | `npx @skapxd/tree ./src` |
57
+ | `-i`, `--ignore` | Regex pattern to ignore files/folders. | `-i "node_modules|dist"` |
58
+ | `-f`, `--only-folder` | Output only directories, hiding files. | `-f` |
59
+ | `-e`, `--export` | Save the output to a text file. | `-e structure.txt` |
60
+ | `-d`, `--directory` | (Alternative) Specify directory via flag. | `-d ./src` |
61
+
62
+ ## 📦 Installation (Optional)
63
+
64
+ If you use it frequently, you can install it globally:
65
+
66
+ ```bash
67
+ npm install -g @skapxd/tree
68
+ # or
69
+ pnpm add -g @skapxd/tree
70
+ ```
71
+
72
+ Then run it simply as:
73
+ ```bash
74
+ tree
75
+ # or
76
+ npx @skapxd/tree
77
+ ```
78
+
79
+ ## 🛠️ Development
80
+
81
+ This project uses **TypeScript**, **Tsup** for bundling, and **Vitest** for testing.
82
+
83
+ ```bash
84
+ # Install dependencies
85
+ yarn install
86
+
87
+ # Run in development mode
88
+ yarn dev
89
+
90
+ # Build for production
91
+ yarn build
92
+
93
+ # Run tests
94
+ yarn test
95
+ ```
96
+
97
+ ## 📄 License
98
+
99
+ MIT
package/dist/cli.cjs ADDED
@@ -0,0 +1,177 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
18
+ // If the importer is in node compatibility mode or this is not an ESM
19
+ // file that has been converted to a CommonJS file using a Babel-
20
+ // compatible transform (i.e. "__esModule" has not been set), then set
21
+ // "default" to the CommonJS "module.exports" for node compatibility.
22
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
23
+ mod
24
+ ));
25
+
26
+ // src/cli.ts
27
+ var import_commander = require("commander");
28
+ var import_fs2 = __toESM(require("fs"));
29
+ var import_path3 = __toESM(require("path"));
30
+
31
+ // src/parser.ts
32
+ var import_fs = __toESM(require("fs"));
33
+ var import_path = __toESM(require("path"));
34
+
35
+ // src/utils.ts
36
+ function sortDir(arr) {
37
+ let i = arr.length - 1;
38
+ while (i >= 0) {
39
+ if (typeof arr[i] === "object") {
40
+ const obj = arr.splice(i, 1);
41
+ arr.push(obj[0]);
42
+ }
43
+ i--;
44
+ }
45
+ return arr;
46
+ }
47
+ function parseIgnoreOption(ignoreStr) {
48
+ if (!ignoreStr) return null;
49
+ let cleanStr = ignoreStr.replace(/^\s*|\s*$/g, "");
50
+ if (/^\/.+\/$/.test(cleanStr)) {
51
+ cleanStr = cleanStr.replace(/(^\/)|(\/$)/g, "");
52
+ return new RegExp(cleanStr, "");
53
+ } else {
54
+ return new RegExp(cleanStr, "");
55
+ }
56
+ }
57
+
58
+ // src/parser.ts
59
+ function dirToJson(dirPath, ignoreRegex, onlyFolder) {
60
+ let stats;
61
+ try {
62
+ stats = import_fs.default.lstatSync(dirPath);
63
+ } catch (e) {
64
+ return null;
65
+ }
66
+ if (stats.isDirectory()) {
67
+ let dir = import_fs.default.readdirSync(dirPath);
68
+ if (ignoreRegex) {
69
+ dir = dir.filter((val) => {
70
+ return !ignoreRegex.test(val);
71
+ });
72
+ }
73
+ const children = dir.filter((child) => {
74
+ const childPath = import_path.default.join(dirPath, child);
75
+ try {
76
+ const childStats = import_fs.default.lstatSync(childPath);
77
+ return onlyFolder ? childStats.isDirectory() : true;
78
+ } catch {
79
+ return false;
80
+ }
81
+ }).map((child) => {
82
+ return dirToJson(import_path.default.join(dirPath, child), ignoreRegex, onlyFolder);
83
+ }).filter((c) => c !== null);
84
+ const dirName = import_path.default.basename(dirPath);
85
+ const structure = {};
86
+ structure[dirName] = sortDir(children);
87
+ return structure;
88
+ } else {
89
+ return import_path.default.basename(dirPath);
90
+ }
91
+ }
92
+
93
+ // src/drawer.ts
94
+ var characters = {
95
+ border: "\u2502 ",
96
+ contain: "\u251C\u2500\u2500 ",
97
+ last: "\u2514\u2500\u2500 "
98
+ };
99
+ var outputString = "";
100
+ function resetOutput() {
101
+ outputString = "";
102
+ }
103
+ function drawDirTree(name, children, prefix = "", isLast = true, isRoot = false) {
104
+ const { border, contain, last } = characters;
105
+ const branch = isRoot ? "" : isLast ? last : contain;
106
+ outputString += (outputString ? "\n" : "") + prefix + branch + name;
107
+ if (Array.isArray(children)) {
108
+ const newPrefix = isRoot ? "" : prefix + (isLast ? " " : border);
109
+ children.forEach((child, idx) => {
110
+ const childIsLast = idx === children.length - 1;
111
+ if (typeof child === "string") {
112
+ outputString += "\n" + newPrefix + (childIsLast ? last : contain) + child;
113
+ } else {
114
+ const keys = Object.keys(child);
115
+ if (keys.length > 0) {
116
+ const subName = keys[0];
117
+ const subChildren = child[subName];
118
+ drawDirTree(subName, subChildren, newPrefix, childIsLast, false);
119
+ }
120
+ }
121
+ });
122
+ }
123
+ }
124
+ function generateTreeString(structure) {
125
+ resetOutput();
126
+ if (typeof structure === "string") {
127
+ return structure;
128
+ }
129
+ const rootName = Object.keys(structure)[0];
130
+ if (rootName) {
131
+ const children = structure[rootName];
132
+ drawDirTree(rootName, children, "", true, true);
133
+ }
134
+ return outputString;
135
+ }
136
+
137
+ // src/index.ts
138
+ var import_path2 = __toESM(require("path"));
139
+ function tree(options) {
140
+ const ignoreRegex = parseIgnoreOption(options.ignore);
141
+ const targetPath = import_path2.default.resolve(options.directory);
142
+ const structure = dirToJson(targetPath, ignoreRegex, options.onlyFolder);
143
+ if (!structure) {
144
+ return null;
145
+ }
146
+ return generateTreeString(structure);
147
+ }
148
+
149
+ // src/cli.ts
150
+ var pkgPath = import_path3.default.join(__dirname, "../package.json");
151
+ var version = "0.0.0";
152
+ try {
153
+ const pkg = JSON.parse(import_fs2.default.readFileSync(pkgPath, "utf-8"));
154
+ version = pkg.version;
155
+ } catch {
156
+ }
157
+ import_commander.program.version(version).argument("[directory]", "Directory to generate structure tree").option("-d, --directory <dir>", "Specify a directory (alternative to positional argument)").option("-i, --ignore [ig]", "You can ignore specific directory name").option("-e, --export [epath]", "export into file").option("-f, --only-folder", "output folder only").action((dirArg, options) => {
158
+ const targetDir = dirArg || options.directory || process.cwd();
159
+ const output = tree({
160
+ directory: targetDir,
161
+ ignore: options.ignore,
162
+ onlyFolder: options.onlyFolder
163
+ });
164
+ if (!output) {
165
+ console.error(`Error: Could not read directory "${targetDir}"`);
166
+ process.exit(1);
167
+ }
168
+ console.log(output);
169
+ if (options.export) {
170
+ import_fs2.default.writeFile(options.export, output, (err) => {
171
+ if (err) throw err;
172
+ console.log("\n\nThe result has been saved into " + options.export);
173
+ });
174
+ }
175
+ });
176
+ import_commander.program.parse(process.argv);
177
+ //# sourceMappingURL=cli.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli.ts","../src/parser.ts","../src/utils.ts","../src/drawer.ts","../src/index.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { program } from 'commander';\nimport fs from 'fs';\nimport path from 'path';\nimport { tree } from './index';\n\n// We need to read package.json version. \n// In TS/ESM, import assertions are the way, or reading file sync.\n// For simplicity and compatibility, we'll read it.\nconst pkgPath = path.join(__dirname, '../package.json');\nlet version = '0.0.0';\ntry {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));\n version = pkg.version;\n} catch {\n // ignore\n}\n\nprogram\n .version(version)\n .argument('[directory]', 'Directory to generate structure tree')\n .option('-d, --directory <dir>', 'Specify a directory (alternative to positional argument)')\n .option('-i, --ignore [ig]', 'You can ignore specific directory name')\n .option('-e, --export [epath]', 'export into file')\n .option('-f, --only-folder', 'output folder only')\n .action((dirArg, options) => {\n const targetDir = dirArg || options.directory || process.cwd();\n\n const output = tree({\n directory: targetDir,\n ignore: options.ignore,\n onlyFolder: options.onlyFolder,\n });\n\n if (!output) {\n console.error(`Error: Could not read directory \"${targetDir}\"`);\n process.exit(1);\n }\n\n // Output to console\n console.log(output);\n\n // Export to file if requested\n if (options.export) {\n fs.writeFile(options.export, output, (err) => {\n if (err) throw err;\n console.log('\\n\\nThe result has been saved into ' + options.export);\n });\n }\n });\n\nprogram.parse(process.argv);\n","import fs from 'fs';\nimport path from 'path';\nimport { sortDir } from './utils';\n\nexport type TreeStructure = { [key: string]: (string | TreeStructure)[] } | string;\n\n/**\n * Recursively scans a directory and returns a JSON-like structure.\n * @param dirPath - The path to scan.\n * @param ignoreRegex - The regex to filter file/folder names.\n * @param onlyFolder - If true, only include directories.\n */\nexport function dirToJson(\n dirPath: string,\n ignoreRegex: RegExp | null,\n onlyFolder?: boolean\n): TreeStructure | null {\n let stats: fs.Stats;\n try {\n stats = fs.lstatSync(dirPath);\n } catch (e) {\n return null;\n }\n\n if (stats.isDirectory()) {\n let dir = fs.readdirSync(dirPath);\n\n if (ignoreRegex) {\n dir = dir.filter((val) => {\n return !ignoreRegex.test(val);\n });\n }\n\n // Map children to their structure\n const children = dir\n .filter((child) => {\n const childPath = path.join(dirPath, child);\n try {\n const childStats = fs.lstatSync(childPath);\n return onlyFolder ? childStats.isDirectory() : true;\n } catch {\n return false;\n }\n })\n .map((child) => {\n return dirToJson(path.join(dirPath, child), ignoreRegex, onlyFolder);\n })\n .filter((c): c is TreeStructure => c !== null); // Filter out nulls\n\n const dirName = path.basename(dirPath);\n const structure: TreeStructure = {};\n // @ts-expect-error - sortDir returns (string|object)[], compatible with TreeStructure's array\n structure[dirName] = sortDir(children);\n return structure;\n } else {\n return path.basename(dirPath);\n }\n}\n","/**\n * Sorts directory contents so that files come before folders.\n * Objects (directories) are put at the end.\n */\nexport function sortDir(arr: (string | object)[]): (string | object)[] {\n let i = arr.length - 1;\n while (i >= 0) {\n if (typeof arr[i] === 'object') {\n const obj = arr.splice(i, 1);\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n arr.push(obj[0]!);\n }\n i--;\n }\n return arr;\n}\n\n/**\n * Parses the ignore argument string into a RegExp object.\n * @param ignoreStr - The string passed via CLI (e.g. \"node_modules|dist\")\n */\nexport function parseIgnoreOption(ignoreStr?: string): RegExp | null {\n if (!ignoreStr) return null;\n\n let cleanStr = ignoreStr.replace(/^\\s*|\\s*$/g, '');\n\n // Check if it's already a regex format like /node_modules/\n if (/^\\/.+\\/$/.test(cleanStr)) {\n cleanStr = cleanStr.replace(/(^\\/)|(\\/$)/g, '');\n return new RegExp(cleanStr, '');\n } else {\n // Treat simple strings with pipes as regex OR, without escaping special chars excessively\n // to allow user provided regex-like strings (e.g. \"node_modules|.git\")\n return new RegExp(cleanStr, '');\n }\n}\n","import { type TreeStructure } from './parser';\n\nconst characters = {\n border: '│ ',\n contain: '├── ',\n last: '└── ',\n};\n\nlet outputString = '';\n\nfunction resetOutput() {\n outputString = '';\n}\n\n/**\n * Recursive function to draw the tree structure.\n */\nfunction drawDirTree(\n name: string,\n children: (string | TreeStructure)[],\n prefix = '',\n isLast = true,\n isRoot = false\n) {\n const { border, contain, last } = characters;\n const branch = isRoot ? '' : isLast ? last : contain;\n\n outputString += (outputString ? '\\n' : '') + prefix + branch + name;\n\n if (Array.isArray(children)) {\n const newPrefix = isRoot ? '' : prefix + (isLast ? ' ' : border);\n children.forEach((child, idx) => {\n const childIsLast = idx === children.length - 1;\n if (typeof child === 'string') {\n outputString += '\\n' + newPrefix + (childIsLast ? last : contain) + child;\n } else {\n // child is { subName: [subChildren] }\n const keys = Object.keys(child);\n if (keys.length > 0) {\n const subName = keys[0] as string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const subChildren = (child as any)[subName];\n drawDirTree(subName, subChildren, newPrefix, childIsLast, false);\n }\n }\n });\n }\n}\n\n/**\n * Main entry point to generate the tree string.\n */\nexport function generateTreeString(structure: TreeStructure): string {\n resetOutput();\n\n // If it's just a single file (string), return it\n if (typeof structure === 'string') {\n return structure;\n }\n\n // It's a directory object { rootName: [...] }\n const rootName = Object.keys(structure)[0];\n if (rootName) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const children = (structure as any)[rootName];\n drawDirTree(rootName, children, '', true, true);\n }\n\n return outputString;\n}\n","// Public API exports\nexport * from './parser';\nexport * from './drawer';\nexport * from './utils';\n\n// Re-export main functionality for programmatic use\nimport path from 'path';\nimport { dirToJson } from './parser';\nimport { generateTreeString } from './drawer';\nimport { parseIgnoreOption } from './utils';\n\nexport type TreeOptions = {\n directory: string;\n ignore?: string;\n onlyFolder?: boolean;\n};\n\n/**\n * Generates an ASCII tree string for the given directory.\n */\nexport function tree(options: TreeOptions): string | null {\n const ignoreRegex = parseIgnoreOption(options.ignore);\n const targetPath = path.resolve(options.directory);\n\n const structure = dirToJson(targetPath, ignoreRegex, options.onlyFolder);\n\n if (!structure) {\n return null;\n }\n\n return generateTreeString(structure);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,uBAAwB;AACxB,IAAAA,aAAe;AACf,IAAAC,eAAiB;;;ACJjB,gBAAe;AACf,kBAAiB;;;ACGV,SAAS,QAAQ,KAA+C;AACrE,MAAI,IAAI,IAAI,SAAS;AACrB,SAAO,KAAK,GAAG;AACb,QAAI,OAAO,IAAI,CAAC,MAAM,UAAU;AAC9B,YAAM,MAAM,IAAI,OAAO,GAAG,CAAC;AAE3B,UAAI,KAAK,IAAI,CAAC,CAAE;AAAA,IAClB;AACA;AAAA,EACF;AACA,SAAO;AACT;AAMO,SAAS,kBAAkB,WAAmC;AACnE,MAAI,CAAC,UAAW,QAAO;AAEvB,MAAI,WAAW,UAAU,QAAQ,cAAc,EAAE;AAGjD,MAAI,WAAW,KAAK,QAAQ,GAAG;AAC7B,eAAW,SAAS,QAAQ,gBAAgB,EAAE;AAC9C,WAAO,IAAI,OAAO,UAAU,EAAE;AAAA,EAChC,OAAO;AAGL,WAAO,IAAI,OAAO,UAAU,EAAE;AAAA,EAChC;AACF;;;ADvBO,SAAS,UACd,SACA,aACA,YACsB;AACtB,MAAI;AACJ,MAAI;AACF,YAAQ,UAAAC,QAAG,UAAU,OAAO;AAAA,EAC9B,SAAS,GAAG;AACV,WAAO;AAAA,EACT;AAEA,MAAI,MAAM,YAAY,GAAG;AACvB,QAAI,MAAM,UAAAA,QAAG,YAAY,OAAO;AAEhC,QAAI,aAAa;AACf,YAAM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7D,QAAM,SAAS,KAAK;AAAA,IAClB,WAAW;AAAA,IACX,QAAQ,QAAQ;AAAA,IAChB,YAAY,QAAQ;AAAA,EACtB,CAAC;AAED,MAAI,CAAC,QAAQ;AACX,YAAQ,MAAM,oCAAoC,SAAS,GAAG;AAC9D,YAAQ,KAAK,CAAC;AAAA,EAChB;AAGA,UAAQ,IAAI,MAAM;AAGlB,MAAI,QAAQ,QAAQ;AAClB,eAAAA,QAAG,UAAU,QAAQ,QAAQ,QAAQ,CAAC,QAAQ;AAC5C,UAAI,IAAK,OAAM;AACf,cAAQ,IAAI,wCAAwC,QAAQ,MAAM;AAAA,IACpE,CAAC;AAAA,EACH;AACF,CAAC;AAEH,yBAAQ,MAAM,QAAQ,IAAI;","names":["import_fs","import_path","fs","path","import_path","path","path","fs"]}
package/dist/cli.d.mts ADDED
@@ -0,0 +1 @@
1
+ #!/usr/bin/env node
package/dist/cli.d.ts ADDED
@@ -0,0 +1 @@
1
+ #!/usr/bin/env node
package/dist/cli.mjs ADDED
@@ -0,0 +1,154 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli.ts
4
+ import { program } from "commander";
5
+ import fs2 from "fs";
6
+ import path3 from "path";
7
+
8
+ // src/parser.ts
9
+ import fs from "fs";
10
+ import path from "path";
11
+
12
+ // src/utils.ts
13
+ function sortDir(arr) {
14
+ let i = arr.length - 1;
15
+ while (i >= 0) {
16
+ if (typeof arr[i] === "object") {
17
+ const obj = arr.splice(i, 1);
18
+ arr.push(obj[0]);
19
+ }
20
+ i--;
21
+ }
22
+ return arr;
23
+ }
24
+ function parseIgnoreOption(ignoreStr) {
25
+ if (!ignoreStr) return null;
26
+ let cleanStr = ignoreStr.replace(/^\s*|\s*$/g, "");
27
+ if (/^\/.+\/$/.test(cleanStr)) {
28
+ cleanStr = cleanStr.replace(/(^\/)|(\/$)/g, "");
29
+ return new RegExp(cleanStr, "");
30
+ } else {
31
+ return new RegExp(cleanStr, "");
32
+ }
33
+ }
34
+
35
+ // src/parser.ts
36
+ function dirToJson(dirPath, ignoreRegex, onlyFolder) {
37
+ let stats;
38
+ try {
39
+ stats = fs.lstatSync(dirPath);
40
+ } catch (e) {
41
+ return null;
42
+ }
43
+ if (stats.isDirectory()) {
44
+ let dir = fs.readdirSync(dirPath);
45
+ if (ignoreRegex) {
46
+ dir = dir.filter((val) => {
47
+ return !ignoreRegex.test(val);
48
+ });
49
+ }
50
+ const children = dir.filter((child) => {
51
+ const childPath = path.join(dirPath, child);
52
+ try {
53
+ const childStats = fs.lstatSync(childPath);
54
+ return onlyFolder ? childStats.isDirectory() : true;
55
+ } catch {
56
+ return false;
57
+ }
58
+ }).map((child) => {
59
+ return dirToJson(path.join(dirPath, child), ignoreRegex, onlyFolder);
60
+ }).filter((c) => c !== null);
61
+ const dirName = path.basename(dirPath);
62
+ const structure = {};
63
+ structure[dirName] = sortDir(children);
64
+ return structure;
65
+ } else {
66
+ return path.basename(dirPath);
67
+ }
68
+ }
69
+
70
+ // src/drawer.ts
71
+ var characters = {
72
+ border: "\u2502 ",
73
+ contain: "\u251C\u2500\u2500 ",
74
+ last: "\u2514\u2500\u2500 "
75
+ };
76
+ var outputString = "";
77
+ function resetOutput() {
78
+ outputString = "";
79
+ }
80
+ function drawDirTree(name, children, prefix = "", isLast = true, isRoot = false) {
81
+ const { border, contain, last } = characters;
82
+ const branch = isRoot ? "" : isLast ? last : contain;
83
+ outputString += (outputString ? "\n" : "") + prefix + branch + name;
84
+ if (Array.isArray(children)) {
85
+ const newPrefix = isRoot ? "" : prefix + (isLast ? " " : border);
86
+ children.forEach((child, idx) => {
87
+ const childIsLast = idx === children.length - 1;
88
+ if (typeof child === "string") {
89
+ outputString += "\n" + newPrefix + (childIsLast ? last : contain) + child;
90
+ } else {
91
+ const keys = Object.keys(child);
92
+ if (keys.length > 0) {
93
+ const subName = keys[0];
94
+ const subChildren = child[subName];
95
+ drawDirTree(subName, subChildren, newPrefix, childIsLast, false);
96
+ }
97
+ }
98
+ });
99
+ }
100
+ }
101
+ function generateTreeString(structure) {
102
+ resetOutput();
103
+ if (typeof structure === "string") {
104
+ return structure;
105
+ }
106
+ const rootName = Object.keys(structure)[0];
107
+ if (rootName) {
108
+ const children = structure[rootName];
109
+ drawDirTree(rootName, children, "", true, true);
110
+ }
111
+ return outputString;
112
+ }
113
+
114
+ // src/index.ts
115
+ import path2 from "path";
116
+ function tree(options) {
117
+ const ignoreRegex = parseIgnoreOption(options.ignore);
118
+ const targetPath = path2.resolve(options.directory);
119
+ const structure = dirToJson(targetPath, ignoreRegex, options.onlyFolder);
120
+ if (!structure) {
121
+ return null;
122
+ }
123
+ return generateTreeString(structure);
124
+ }
125
+
126
+ // src/cli.ts
127
+ var pkgPath = path3.join(__dirname, "../package.json");
128
+ var version = "0.0.0";
129
+ try {
130
+ const pkg = JSON.parse(fs2.readFileSync(pkgPath, "utf-8"));
131
+ version = pkg.version;
132
+ } catch {
133
+ }
134
+ program.version(version).argument("[directory]", "Directory to generate structure tree").option("-d, --directory <dir>", "Specify a directory (alternative to positional argument)").option("-i, --ignore [ig]", "You can ignore specific directory name").option("-e, --export [epath]", "export into file").option("-f, --only-folder", "output folder only").action((dirArg, options) => {
135
+ const targetDir = dirArg || options.directory || process.cwd();
136
+ const output = tree({
137
+ directory: targetDir,
138
+ ignore: options.ignore,
139
+ onlyFolder: options.onlyFolder
140
+ });
141
+ if (!output) {
142
+ console.error(`Error: Could not read directory "${targetDir}"`);
143
+ process.exit(1);
144
+ }
145
+ console.log(output);
146
+ if (options.export) {
147
+ fs2.writeFile(options.export, output, (err) => {
148
+ if (err) throw err;
149
+ console.log("\n\nThe result has been saved into " + options.export);
150
+ });
151
+ }
152
+ });
153
+ program.parse(process.argv);
154
+ //# sourceMappingURL=cli.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli.ts","../src/parser.ts","../src/utils.ts","../src/drawer.ts","../src/index.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { program } from 'commander';\nimport fs from 'fs';\nimport path from 'path';\nimport { tree } from './index';\n\n// We need to read package.json version. \n// In TS/ESM, import assertions are the way, or reading file sync.\n// For simplicity and compatibility, we'll read it.\nconst pkgPath = path.join(__dirname, '../package.json');\nlet version = '0.0.0';\ntry {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));\n version = pkg.version;\n} catch {\n // ignore\n}\n\nprogram\n .version(version)\n .argument('[directory]', 'Directory to generate structure tree')\n .option('-d, --directory <dir>', 'Specify a directory (alternative to positional argument)')\n .option('-i, --ignore [ig]', 'You can ignore specific directory name')\n .option('-e, --export [epath]', 'export into file')\n .option('-f, --only-folder', 'output folder only')\n .action((dirArg, options) => {\n const targetDir = dirArg || options.directory || process.cwd();\n\n const output = tree({\n directory: targetDir,\n ignore: options.ignore,\n onlyFolder: options.onlyFolder,\n });\n\n if (!output) {\n console.error(`Error: Could not read directory \"${targetDir}\"`);\n process.exit(1);\n }\n\n // Output to console\n console.log(output);\n\n // Export to file if requested\n if (options.export) {\n fs.writeFile(options.export, output, (err) => {\n if (err) throw err;\n console.log('\\n\\nThe result has been saved into ' + options.export);\n });\n }\n });\n\nprogram.parse(process.argv);\n","import fs from 'fs';\nimport path from 'path';\nimport { sortDir } from './utils';\n\nexport type TreeStructure = { [key: string]: (string | TreeStructure)[] } | string;\n\n/**\n * Recursively scans a directory and returns a JSON-like structure.\n * @param dirPath - The path to scan.\n * @param ignoreRegex - The regex to filter file/folder names.\n * @param onlyFolder - If true, only include directories.\n */\nexport function dirToJson(\n dirPath: string,\n ignoreRegex: RegExp | null,\n onlyFolder?: boolean\n): TreeStructure | null {\n let stats: fs.Stats;\n try {\n stats = fs.lstatSync(dirPath);\n } catch (e) {\n return null;\n }\n\n if (stats.isDirectory()) {\n let dir = fs.readdirSync(dirPath);\n\n if (ignoreRegex) {\n dir = dir.filter((val) => {\n return !ignoreRegex.test(val);\n });\n }\n\n // Map children to their structure\n const children = dir\n .filter((child) => {\n const childPath = path.join(dirPath, child);\n try {\n const childStats = fs.lstatSync(childPath);\n return onlyFolder ? childStats.isDirectory() : true;\n } catch {\n return false;\n }\n })\n .map((child) => {\n return dirToJson(path.join(dirPath, child), ignoreRegex, onlyFolder);\n })\n .filter((c): c is TreeStructure => c !== null); // Filter out nulls\n\n const dirName = path.basename(dirPath);\n const structure: TreeStructure = {};\n // @ts-expect-error - sortDir returns (string|object)[], compatible with TreeStructure's array\n structure[dirName] = sortDir(children);\n return structure;\n } else {\n return path.basename(dirPath);\n }\n}\n","/**\n * Sorts directory contents so that files come before folders.\n * Objects (directories) are put at the end.\n */\nexport function sortDir(arr: (string | object)[]): (string | object)[] {\n let i = arr.length - 1;\n while (i >= 0) {\n if (typeof arr[i] === 'object') {\n const obj = arr.splice(i, 1);\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n arr.push(obj[0]!);\n }\n i--;\n }\n return arr;\n}\n\n/**\n * Parses the ignore argument string into a RegExp object.\n * @param ignoreStr - The string passed via CLI (e.g. \"node_modules|dist\")\n */\nexport function parseIgnoreOption(ignoreStr?: string): RegExp | null {\n if (!ignoreStr) return null;\n\n let cleanStr = ignoreStr.replace(/^\\s*|\\s*$/g, '');\n\n // Check if it's already a regex format like /node_modules/\n if (/^\\/.+\\/$/.test(cleanStr)) {\n cleanStr = cleanStr.replace(/(^\\/)|(\\/$)/g, '');\n return new RegExp(cleanStr, '');\n } else {\n // Treat simple strings with pipes as regex OR, without escaping special chars excessively\n // to allow user provided regex-like strings (e.g. \"node_modules|.git\")\n return new RegExp(cleanStr, '');\n }\n}\n","import { type TreeStructure } from './parser';\n\nconst characters = {\n border: '│ ',\n contain: '├── ',\n last: '└── ',\n};\n\nlet outputString = '';\n\nfunction resetOutput() {\n outputString = '';\n}\n\n/**\n * Recursive function to draw the tree structure.\n */\nfunction drawDirTree(\n name: string,\n children: (string | TreeStructure)[],\n prefix = '',\n isLast = true,\n isRoot = false\n) {\n const { border, contain, last } = characters;\n const branch = isRoot ? '' : isLast ? last : contain;\n\n outputString += (outputString ? '\\n' : '') + prefix + branch + name;\n\n if (Array.isArray(children)) {\n const newPrefix = isRoot ? '' : prefix + (isLast ? ' ' : border);\n children.forEach((child, idx) => {\n const childIsLast = idx === children.length - 1;\n if (typeof child === 'string') {\n outputString += '\\n' + newPrefix + (childIsLast ? last : contain) + child;\n } else {\n // child is { subName: [subChildren] }\n const keys = Object.keys(child);\n if (keys.length > 0) {\n const subName = keys[0] as string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const subChildren = (child as any)[subName];\n drawDirTree(subName, subChildren, newPrefix, childIsLast, false);\n }\n }\n });\n }\n}\n\n/**\n * Main entry point to generate the tree string.\n */\nexport function generateTreeString(structure: TreeStructure): string {\n resetOutput();\n\n // If it's just a single file (string), return it\n if (typeof structure === 'string') {\n return structure;\n }\n\n // It's a directory object { rootName: [...] }\n const rootName = Object.keys(structure)[0];\n if (rootName) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const children = (structure as any)[rootName];\n drawDirTree(rootName, children, '', true, true);\n }\n\n return outputString;\n}\n","// Public API exports\nexport * from './parser';\nexport * from './drawer';\nexport * from './utils';\n\n// Re-export main functionality for programmatic use\nimport path from 'path';\nimport { dirToJson } from './parser';\nimport { generateTreeString } from './drawer';\nimport { parseIgnoreOption } from './utils';\n\nexport type TreeOptions = {\n directory: string;\n ignore?: string;\n onlyFolder?: boolean;\n};\n\n/**\n * Generates an ASCII tree string for the given directory.\n */\nexport function tree(options: TreeOptions): string | null {\n const ignoreRegex = parseIgnoreOption(options.ignore);\n const targetPath = path.resolve(options.directory);\n\n const structure = dirToJson(targetPath, ignoreRegex, options.onlyFolder);\n\n if (!structure) {\n return null;\n }\n\n return generateTreeString(structure);\n}\n"],"mappings":";;;AAEA,SAAS,eAAe;AACxB,OAAOA,SAAQ;AACf,OAAOC,WAAU;;;ACJjB,OAAO,QAAQ;AACf,OAAO,UAAU;;;ACGV,SAAS,QAAQ,KAA+C;AACrE,MAAI,IAAI,IAAI,SAAS;AACrB,SAAO,K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xD,QAAM,cAAc,kBAAkB,QAAQ,MAAM;AACpD,QAAM,aAAaC,MAAK,QAAQ,QAAQ,SAAS;AAEjD,QAAM,YAAY,UAAU,YAAY,aAAa,QAAQ,UAAU;AAEvE,MAAI,CAAC,WAAW;AACd,WAAO;AAAA,EACT;AAEA,SAAO,mBAAmB,SAAS;AACrC;;;AJrBA,IAAM,UAAUC,MAAK,KAAK,WAAW,iBAAiB;AACtD,IAAI,UAAU;AACd,IAAI;AACA,QAAM,MAAM,KAAK,MAAMC,IAAG,aAAa,SAAS,OAAO,CAAC;AACxD,YAAU,IAAI;AAClB,QAAQ;AAER;AAEA,QACG,QAAQ,OAAO,EACf,SAAS,eAAe,sCAAsC,EAC9D,OAAO,yBAAyB,0DAA0D,EAC1F,OAAO,qBAAqB,wCAAwC,EACpE,OAAO,wBAAwB,kBAAkB,EACjD,OAAO,qBAAqB,oBAAoB,EAChD,OAAO,CAAC,QAAQ,YAAY;AAC3B,QAAM,YAAY,UAAU,QAAQ,aAAa,QAAQ,IAAI;AAE7D,QAAM,SAAS,KAAK;AAAA,IAClB,WAAW;AAAA,IACX,QAAQ,QAAQ;AAAA,IAChB,YAAY,QAAQ;AAAA,EACtB,CAAC;AAED,MAAI,CAAC,QAAQ;AACX,YAAQ,MAAM,oCAAoC,SAAS,GAAG;AAC9D,YAAQ,KAAK,CAAC;AAAA,EAChB;AAGA,UAAQ,IAAI,MAAM;AAGlB,MAAI,QAAQ,QAAQ;AAClB,IAAAA,IAAG,UAAU,QAAQ,QAAQ,QAAQ,CAAC,QAAQ;AAC5C,UAAI,IAAK,OAAM;AACf,cAAQ,IAAI,wCAAwC,QAAQ,MAAM;AAAA,IACpE,CAAC;AAAA,EACH;AACF,CAAC;AAEH,QAAQ,MAAM,QAAQ,IAAI;","names":["fs","path","path","path","path","fs"]}
package/dist/index.cjs ADDED
@@ -0,0 +1,166 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ dirToJson: () => dirToJson,
34
+ generateTreeString: () => generateTreeString,
35
+ parseIgnoreOption: () => parseIgnoreOption,
36
+ sortDir: () => sortDir,
37
+ tree: () => tree
38
+ });
39
+ module.exports = __toCommonJS(index_exports);
40
+
41
+ // src/parser.ts
42
+ var import_fs = __toESM(require("fs"));
43
+ var import_path = __toESM(require("path"));
44
+
45
+ // src/utils.ts
46
+ function sortDir(arr) {
47
+ let i = arr.length - 1;
48
+ while (i >= 0) {
49
+ if (typeof arr[i] === "object") {
50
+ const obj = arr.splice(i, 1);
51
+ arr.push(obj[0]);
52
+ }
53
+ i--;
54
+ }
55
+ return arr;
56
+ }
57
+ function parseIgnoreOption(ignoreStr) {
58
+ if (!ignoreStr) return null;
59
+ let cleanStr = ignoreStr.replace(/^\s*|\s*$/g, "");
60
+ if (/^\/.+\/$/.test(cleanStr)) {
61
+ cleanStr = cleanStr.replace(/(^\/)|(\/$)/g, "");
62
+ return new RegExp(cleanStr, "");
63
+ } else {
64
+ return new RegExp(cleanStr, "");
65
+ }
66
+ }
67
+
68
+ // src/parser.ts
69
+ function dirToJson(dirPath, ignoreRegex, onlyFolder) {
70
+ let stats;
71
+ try {
72
+ stats = import_fs.default.lstatSync(dirPath);
73
+ } catch (e) {
74
+ return null;
75
+ }
76
+ if (stats.isDirectory()) {
77
+ let dir = import_fs.default.readdirSync(dirPath);
78
+ if (ignoreRegex) {
79
+ dir = dir.filter((val) => {
80
+ return !ignoreRegex.test(val);
81
+ });
82
+ }
83
+ const children = dir.filter((child) => {
84
+ const childPath = import_path.default.join(dirPath, child);
85
+ try {
86
+ const childStats = import_fs.default.lstatSync(childPath);
87
+ return onlyFolder ? childStats.isDirectory() : true;
88
+ } catch {
89
+ return false;
90
+ }
91
+ }).map((child) => {
92
+ return dirToJson(import_path.default.join(dirPath, child), ignoreRegex, onlyFolder);
93
+ }).filter((c) => c !== null);
94
+ const dirName = import_path.default.basename(dirPath);
95
+ const structure = {};
96
+ structure[dirName] = sortDir(children);
97
+ return structure;
98
+ } else {
99
+ return import_path.default.basename(dirPath);
100
+ }
101
+ }
102
+
103
+ // src/drawer.ts
104
+ var characters = {
105
+ border: "\u2502 ",
106
+ contain: "\u251C\u2500\u2500 ",
107
+ last: "\u2514\u2500\u2500 "
108
+ };
109
+ var outputString = "";
110
+ function resetOutput() {
111
+ outputString = "";
112
+ }
113
+ function drawDirTree(name, children, prefix = "", isLast = true, isRoot = false) {
114
+ const { border, contain, last } = characters;
115
+ const branch = isRoot ? "" : isLast ? last : contain;
116
+ outputString += (outputString ? "\n" : "") + prefix + branch + name;
117
+ if (Array.isArray(children)) {
118
+ const newPrefix = isRoot ? "" : prefix + (isLast ? " " : border);
119
+ children.forEach((child, idx) => {
120
+ const childIsLast = idx === children.length - 1;
121
+ if (typeof child === "string") {
122
+ outputString += "\n" + newPrefix + (childIsLast ? last : contain) + child;
123
+ } else {
124
+ const keys = Object.keys(child);
125
+ if (keys.length > 0) {
126
+ const subName = keys[0];
127
+ const subChildren = child[subName];
128
+ drawDirTree(subName, subChildren, newPrefix, childIsLast, false);
129
+ }
130
+ }
131
+ });
132
+ }
133
+ }
134
+ function generateTreeString(structure) {
135
+ resetOutput();
136
+ if (typeof structure === "string") {
137
+ return structure;
138
+ }
139
+ const rootName = Object.keys(structure)[0];
140
+ if (rootName) {
141
+ const children = structure[rootName];
142
+ drawDirTree(rootName, children, "", true, true);
143
+ }
144
+ return outputString;
145
+ }
146
+
147
+ // src/index.ts
148
+ var import_path2 = __toESM(require("path"));
149
+ function tree(options) {
150
+ const ignoreRegex = parseIgnoreOption(options.ignore);
151
+ const targetPath = import_path2.default.resolve(options.directory);
152
+ const structure = dirToJson(targetPath, ignoreRegex, options.onlyFolder);
153
+ if (!structure) {
154
+ return null;
155
+ }
156
+ return generateTreeString(structure);
157
+ }
158
+ // Annotate the CommonJS export names for ESM import in node:
159
+ 0 && (module.exports = {
160
+ dirToJson,
161
+ generateTreeString,
162
+ parseIgnoreOption,
163
+ sortDir,
164
+ tree
165
+ });
166
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/parser.ts","../src/utils.ts","../src/drawer.ts"],"sourcesContent":["// Public API exports\nexport * from './parser';\nexport * from './drawer';\nexport * from './utils';\n\n// Re-export main functionality for programmatic use\nimport path from 'path';\nimport { dirToJson } from './parser';\nimport { generateTreeString } from './drawer';\nimport { parseIgnoreOption } from './utils';\n\nexport type TreeOptions = {\n directory: string;\n ignore?: string;\n onlyFolder?: boolean;\n};\n\n/**\n * Generates an ASCII tree string for the given directory.\n */\nexport function tree(options: TreeOptions): string | null {\n const ignoreRegex = parseIgnoreOption(options.ignore);\n const targetPath = path.resolve(options.directory);\n\n const structure = dirToJson(targetPath, ignoreRegex, options.onlyFolder);\n\n if (!structure) {\n return null;\n }\n\n return generateTreeString(structure);\n}\n","import fs from 'fs';\nimport path from 'path';\nimport { sortDir } from './utils';\n\nexport type TreeStructure = { [key: string]: (string | TreeStructure)[] } | string;\n\n/**\n * Recursively scans a directory and returns a JSON-like structure.\n * @param dirPath - The path to scan.\n * @param ignoreRegex - The regex to filter file/folder names.\n * @param onlyFolder - If true, only include directories.\n */\nexport function dirToJson(\n dirPath: string,\n ignoreRegex: RegExp | null,\n onlyFolder?: boolean\n): TreeStructure | null {\n let stats: fs.Stats;\n try {\n stats = fs.lstatSync(dirPath);\n } catch (e) {\n return null;\n }\n\n if (stats.isDirectory()) {\n let dir = fs.readdirSync(dirPath);\n\n if (ignoreRegex) {\n dir = dir.filter((val) => {\n return !ignoreRegex.test(val);\n });\n }\n\n // Map children to their structure\n const children = dir\n .filter((child) => {\n const childPath = path.join(dirPath, child);\n try {\n const childStats = fs.lstatSync(childPath);\n return onlyFolder ? childStats.isDirectory() : true;\n } catch {\n return false;\n }\n })\n .map((child) => {\n return dirToJson(path.join(dirPath, child), ignoreRegex, onlyFolder);\n })\n .filter((c): c is TreeStructure => c !== null); // Filter out nulls\n\n const dirName = path.basename(dirPath);\n const structure: TreeStructure = {};\n // @ts-expect-error - sortDir returns (string|object)[], compatible with TreeStructure's array\n structure[dirName] = sortDir(children);\n return structure;\n } else {\n return path.basename(dirPath);\n }\n}\n","/**\n * Sorts directory contents so that files come before folders.\n * Objects (directories) are put at the end.\n */\nexport function sortDir(arr: (string | object)[]): (string | object)[] {\n let i = arr.length - 1;\n while (i >= 0) {\n if (typeof arr[i] === 'object') {\n const obj = arr.splice(i, 1);\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n arr.push(obj[0]!);\n }\n i--;\n }\n return arr;\n}\n\n/**\n * Parses the ignore argument string into a RegExp object.\n * @param ignoreStr - The string passed via CLI (e.g. \"node_modules|dist\")\n */\nexport function parseIgnoreOption(ignoreStr?: string): RegExp | null {\n if (!ignoreStr) return null;\n\n let cleanStr = ignoreStr.replace(/^\\s*|\\s*$/g, '');\n\n // Check if it's already a regex format like /node_modules/\n if (/^\\/.+\\/$/.test(cleanStr)) {\n cleanStr = cleanStr.replace(/(^\\/)|(\\/$)/g, '');\n return new RegExp(cleanStr, '');\n } else {\n // Treat simple strings with pipes as regex OR, without escaping special chars excessively\n // to allow user provided regex-like strings (e.g. \"node_modules|.git\")\n return new RegExp(cleanStr, '');\n }\n}\n","import { type TreeStructure } from './parser';\n\nconst characters = {\n border: '│ ',\n contain: '├── ',\n last: '└── ',\n};\n\nlet outputString = '';\n\nfunction resetOutput() {\n outputString = '';\n}\n\n/**\n * Recursive function to draw the tree structure.\n */\nfunction drawDirTree(\n name: string,\n children: (string | TreeStructure)[],\n prefix = '',\n isLast = true,\n isRoot = false\n) {\n const { border, contain, last } = characters;\n const branch = isRoot ? '' : isLast ? last : contain;\n\n outputString += (outputString ? '\\n' : '') + prefix + branch + name;\n\n if (Array.isArray(children)) {\n const newPrefix = isRoot ? '' : prefix + (isLast ? ' ' : border);\n children.forEach((child, idx) => {\n const childIsLast = idx === children.length - 1;\n if (typeof child === 'string') {\n outputString += '\\n' + newPrefix + (childIsLast ? last : contain) + child;\n } else {\n // child is { subName: [subChildren] }\n const keys = Object.keys(child);\n if (keys.length > 0) {\n const subName = keys[0] as string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const subChildren = (child as any)[subName];\n drawDirTree(subName, subChildren, newPrefix, childIsLast, false);\n }\n }\n });\n }\n}\n\n/**\n * Main entry point to generate the tree string.\n */\nexport function generateTreeString(structure: TreeStructure): string {\n resetOutput();\n\n // If it's just a single file (string), return it\n if (typeof structure === 'string') {\n return structure;\n }\n\n // It's a directory object { rootName: [...] }\n const rootName = Object.keys(structure)[0];\n if (rootName) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const children = (structure as any)[rootName];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WAAkC;AACnE,cAAY;AAGZ,MAAI,OAAO,cAAc,UAAU;AACjC,WAAO;AAAA,EACT;AAGA,QAAM,WAAW,OAAO,KAAK,SAAS,EAAE,CAAC;AACzC,MAAI,UAAU;AAEV,UAAM,WAAY,UAAkB,QAAQ;AAC5C,gBAAY,UAAU,UAAU,IAAI,MAAM,IAAI;AAAA,EAClD;AAEA,SAAO;AACT;;;AH/DA,IAAAC,eAAiB;AAcV,SAAS,KAAK,SAAqC;AACxD,QAAM,cAAc,kBAAkB,QAAQ,MAAM;AACpD,QAAM,aAAa,aAAAC,QAAK,QAAQ,QAAQ,SAAS;AAEjD,QAAM,YAAY,UAAU,YAAY,aAAa,QAAQ,UAAU;AAEvE,MAAI,CAAC,WAAW;AACd,WAAO;AAAA,EACT;AAEA,SAAO,mBAAmB,SAAS;AACrC;","names":["fs","path","import_path","path"]}
@@ -0,0 +1,38 @@
1
+ type TreeStructure = {
2
+ [key: string]: (string | TreeStructure)[];
3
+ } | string;
4
+ /**
5
+ * Recursively scans a directory and returns a JSON-like structure.
6
+ * @param dirPath - The path to scan.
7
+ * @param ignoreRegex - The regex to filter file/folder names.
8
+ * @param onlyFolder - If true, only include directories.
9
+ */
10
+ declare function dirToJson(dirPath: string, ignoreRegex: RegExp | null, onlyFolder?: boolean): TreeStructure | null;
11
+
12
+ /**
13
+ * Main entry point to generate the tree string.
14
+ */
15
+ declare function generateTreeString(structure: TreeStructure): string;
16
+
17
+ /**
18
+ * Sorts directory contents so that files come before folders.
19
+ * Objects (directories) are put at the end.
20
+ */
21
+ declare function sortDir(arr: (string | object)[]): (string | object)[];
22
+ /**
23
+ * Parses the ignore argument string into a RegExp object.
24
+ * @param ignoreStr - The string passed via CLI (e.g. "node_modules|dist")
25
+ */
26
+ declare function parseIgnoreOption(ignoreStr?: string): RegExp | null;
27
+
28
+ type TreeOptions = {
29
+ directory: string;
30
+ ignore?: string;
31
+ onlyFolder?: boolean;
32
+ };
33
+ /**
34
+ * Generates an ASCII tree string for the given directory.
35
+ */
36
+ declare function tree(options: TreeOptions): string | null;
37
+
38
+ export { type TreeOptions, type TreeStructure, dirToJson, generateTreeString, parseIgnoreOption, sortDir, tree };
@@ -0,0 +1,38 @@
1
+ type TreeStructure = {
2
+ [key: string]: (string | TreeStructure)[];
3
+ } | string;
4
+ /**
5
+ * Recursively scans a directory and returns a JSON-like structure.
6
+ * @param dirPath - The path to scan.
7
+ * @param ignoreRegex - The regex to filter file/folder names.
8
+ * @param onlyFolder - If true, only include directories.
9
+ */
10
+ declare function dirToJson(dirPath: string, ignoreRegex: RegExp | null, onlyFolder?: boolean): TreeStructure | null;
11
+
12
+ /**
13
+ * Main entry point to generate the tree string.
14
+ */
15
+ declare function generateTreeString(structure: TreeStructure): string;
16
+
17
+ /**
18
+ * Sorts directory contents so that files come before folders.
19
+ * Objects (directories) are put at the end.
20
+ */
21
+ declare function sortDir(arr: (string | object)[]): (string | object)[];
22
+ /**
23
+ * Parses the ignore argument string into a RegExp object.
24
+ * @param ignoreStr - The string passed via CLI (e.g. "node_modules|dist")
25
+ */
26
+ declare function parseIgnoreOption(ignoreStr?: string): RegExp | null;
27
+
28
+ type TreeOptions = {
29
+ directory: string;
30
+ ignore?: string;
31
+ onlyFolder?: boolean;
32
+ };
33
+ /**
34
+ * Generates an ASCII tree string for the given directory.
35
+ */
36
+ declare function tree(options: TreeOptions): string | null;
37
+
38
+ export { type TreeOptions, type TreeStructure, dirToJson, generateTreeString, parseIgnoreOption, sortDir, tree };
package/dist/index.mjs ADDED
@@ -0,0 +1,125 @@
1
+ // src/parser.ts
2
+ import fs from "fs";
3
+ import path from "path";
4
+
5
+ // src/utils.ts
6
+ function sortDir(arr) {
7
+ let i = arr.length - 1;
8
+ while (i >= 0) {
9
+ if (typeof arr[i] === "object") {
10
+ const obj = arr.splice(i, 1);
11
+ arr.push(obj[0]);
12
+ }
13
+ i--;
14
+ }
15
+ return arr;
16
+ }
17
+ function parseIgnoreOption(ignoreStr) {
18
+ if (!ignoreStr) return null;
19
+ let cleanStr = ignoreStr.replace(/^\s*|\s*$/g, "");
20
+ if (/^\/.+\/$/.test(cleanStr)) {
21
+ cleanStr = cleanStr.replace(/(^\/)|(\/$)/g, "");
22
+ return new RegExp(cleanStr, "");
23
+ } else {
24
+ return new RegExp(cleanStr, "");
25
+ }
26
+ }
27
+
28
+ // src/parser.ts
29
+ function dirToJson(dirPath, ignoreRegex, onlyFolder) {
30
+ let stats;
31
+ try {
32
+ stats = fs.lstatSync(dirPath);
33
+ } catch (e) {
34
+ return null;
35
+ }
36
+ if (stats.isDirectory()) {
37
+ let dir = fs.readdirSync(dirPath);
38
+ if (ignoreRegex) {
39
+ dir = dir.filter((val) => {
40
+ return !ignoreRegex.test(val);
41
+ });
42
+ }
43
+ const children = dir.filter((child) => {
44
+ const childPath = path.join(dirPath, child);
45
+ try {
46
+ const childStats = fs.lstatSync(childPath);
47
+ return onlyFolder ? childStats.isDirectory() : true;
48
+ } catch {
49
+ return false;
50
+ }
51
+ }).map((child) => {
52
+ return dirToJson(path.join(dirPath, child), ignoreRegex, onlyFolder);
53
+ }).filter((c) => c !== null);
54
+ const dirName = path.basename(dirPath);
55
+ const structure = {};
56
+ structure[dirName] = sortDir(children);
57
+ return structure;
58
+ } else {
59
+ return path.basename(dirPath);
60
+ }
61
+ }
62
+
63
+ // src/drawer.ts
64
+ var characters = {
65
+ border: "\u2502 ",
66
+ contain: "\u251C\u2500\u2500 ",
67
+ last: "\u2514\u2500\u2500 "
68
+ };
69
+ var outputString = "";
70
+ function resetOutput() {
71
+ outputString = "";
72
+ }
73
+ function drawDirTree(name, children, prefix = "", isLast = true, isRoot = false) {
74
+ const { border, contain, last } = characters;
75
+ const branch = isRoot ? "" : isLast ? last : contain;
76
+ outputString += (outputString ? "\n" : "") + prefix + branch + name;
77
+ if (Array.isArray(children)) {
78
+ const newPrefix = isRoot ? "" : prefix + (isLast ? " " : border);
79
+ children.forEach((child, idx) => {
80
+ const childIsLast = idx === children.length - 1;
81
+ if (typeof child === "string") {
82
+ outputString += "\n" + newPrefix + (childIsLast ? last : contain) + child;
83
+ } else {
84
+ const keys = Object.keys(child);
85
+ if (keys.length > 0) {
86
+ const subName = keys[0];
87
+ const subChildren = child[subName];
88
+ drawDirTree(subName, subChildren, newPrefix, childIsLast, false);
89
+ }
90
+ }
91
+ });
92
+ }
93
+ }
94
+ function generateTreeString(structure) {
95
+ resetOutput();
96
+ if (typeof structure === "string") {
97
+ return structure;
98
+ }
99
+ const rootName = Object.keys(structure)[0];
100
+ if (rootName) {
101
+ const children = structure[rootName];
102
+ drawDirTree(rootName, children, "", true, true);
103
+ }
104
+ return outputString;
105
+ }
106
+
107
+ // src/index.ts
108
+ import path2 from "path";
109
+ function tree(options) {
110
+ const ignoreRegex = parseIgnoreOption(options.ignore);
111
+ const targetPath = path2.resolve(options.directory);
112
+ const structure = dirToJson(targetPath, ignoreRegex, options.onlyFolder);
113
+ if (!structure) {
114
+ return null;
115
+ }
116
+ return generateTreeString(structure);
117
+ }
118
+ export {
119
+ dirToJson,
120
+ generateTreeString,
121
+ parseIgnoreOption,
122
+ sortDir,
123
+ tree
124
+ };
125
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/parser.ts","../src/utils.ts","../src/drawer.ts","../src/index.ts"],"sourcesContent":["import fs from 'fs';\nimport path from 'path';\nimport { sortDir } from './utils';\n\nexport type TreeStructure = { [key: string]: (string | TreeStructure)[] } | string;\n\n/**\n * Recursively scans a directory and returns a JSON-like structure.\n * @param dirPath - The path to scan.\n * @param ignoreRegex - The regex to filter file/folder names.\n * @param onlyFolder - If true, only include directories.\n */\nexport function dirToJson(\n dirPath: string,\n ignoreRegex: RegExp | null,\n onlyFolder?: boolean\n): TreeStructure | null {\n let stats: fs.Stats;\n try {\n stats = fs.lstatSync(dirPath);\n } catch (e) {\n return null;\n }\n\n if (stats.isDirectory()) {\n let dir = fs.readdirSync(dirPath);\n\n if (ignoreRegex) {\n dir = dir.filter((val) => {\n return !ignoreRegex.test(val);\n });\n }\n\n // Map children to their structure\n const children = dir\n .filter((child) => {\n const childPath = path.join(dirPath, child);\n try {\n const childStats = fs.lstatSync(childPath);\n return onlyFolder ? childStats.isDirectory() : true;\n } catch {\n return false;\n }\n })\n .map((child) => {\n return dirToJson(path.join(dirPath, child), ignoreRegex, onlyFolder);\n })\n .filter((c): c is TreeStructure => c !== null); // Filter out nulls\n\n const dirName = path.basename(dirPath);\n const structure: TreeStructure = {};\n // @ts-expect-error - sortDir returns (string|object)[], compatible with TreeStructure's array\n structure[dirName] = sortDir(children);\n return structure;\n } else {\n return path.basename(dirPath);\n }\n}\n","/**\n * Sorts directory contents so that files come before folders.\n * Objects (directories) are put at the end.\n */\nexport function sortDir(arr: (string | object)[]): (string | object)[] {\n let i = arr.length - 1;\n while (i >= 0) {\n if (typeof arr[i] === 'object') {\n const obj = arr.splice(i, 1);\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n arr.push(obj[0]!);\n }\n i--;\n }\n return arr;\n}\n\n/**\n * Parses the ignore argument string into a RegExp object.\n * @param ignoreStr - The string passed via CLI (e.g. \"node_modules|dist\")\n */\nexport function parseIgnoreOption(ignoreStr?: string): RegExp | null {\n if (!ignoreStr) return null;\n\n let cleanStr = ignoreStr.replace(/^\\s*|\\s*$/g, '');\n\n // Check if it's already a regex format like /node_modules/\n if (/^\\/.+\\/$/.test(cleanStr)) {\n cleanStr = cleanStr.replace(/(^\\/)|(\\/$)/g, '');\n return new RegExp(cleanStr, '');\n } else {\n // Treat simple strings with pipes as regex OR, without escaping special chars excessively\n // to allow user provided regex-like strings (e.g. \"node_modules|.git\")\n return new RegExp(cleanStr, '');\n }\n}\n","import { type TreeStructure } from './parser';\n\nconst characters = {\n border: '│ ',\n contain: '├── ',\n last: '└── ',\n};\n\nlet outputString = '';\n\nfunction resetOutput() {\n outputString = '';\n}\n\n/**\n * Recursive function to draw the tree structure.\n */\nfunction drawDirTree(\n name: string,\n children: (string | TreeStructure)[],\n prefix = '',\n isLast = true,\n isRoot = false\n) {\n const { border, contain, last } = characters;\n const branch = isRoot ? '' : isLast ? last : contain;\n\n outputString += (outputString ? '\\n' : '') + prefix + branch + name;\n\n if (Array.isArray(children)) {\n const newPrefix = isRoot ? '' : prefix + (isLast ? ' ' : border);\n children.forEach((child, idx) => {\n const childIsLast = idx === children.length - 1;\n if (typeof child === 'string') {\n outputString += '\\n' + newPrefix + (childIsLast ? last : contain) + child;\n } else {\n // child is { subName: [subChildren] }\n const keys = Object.keys(child);\n if (keys.length > 0) {\n const subName = keys[0] as string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const subChildren = (child as any)[subName];\n drawDirTree(subName, subChildren, newPrefix, childIsLast, false);\n }\n }\n });\n }\n}\n\n/**\n * Main entry point to generate the tree string.\n */\nexport function generateTreeString(structure: TreeStructure): string {\n resetOutput();\n\n // If it's just a single file (string), return it\n if (typeof structure === 'string') {\n return structure;\n }\n\n // It's a directory object { rootName: [...] }\n const rootName = Object.keys(structure)[0];\n if (rootName) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const children = (structure as any)[rootName];\n drawDirTree(rootName, children, '', true, true);\n }\n\n return outputString;\n}\n","// Public API exports\nexport * from './parser';\nexport * from './drawer';\nexport * from './utils';\n\n// Re-export main functionality for programmatic use\nimport path from 'path';\nimport { dirToJson } from './parser';\nimport { generateTreeString } from './drawer';\nimport { parseIgnoreOption } from './utils';\n\nexport type TreeOptions = {\n directory: string;\n ignore?: string;\n onlyFolder?: boolean;\n};\n\n/**\n * Generates an ASCII tree string for the given directory.\n */\nexport function tree(options: TreeOptions): string | null {\n const ignoreRegex = parseIgnoreOption(options.ignore);\n const targetPath = path.resolve(options.directory);\n\n const structure = dirToJson(targetPath, ignoreRegex, options.onlyFolder);\n\n if (!structure) {\n return null;\n }\n\n return generateTreeString(structure);\n}\n"],"mappings":";AAAA,OAAO,QAAQ;AACf,OAAO,UAAU;;;ACGV,SAAS,QAAQ,KAA+C;AACrE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AOA,WAAU;AAcV,SAAS,KAAK,SAAqC;AACxD,QAAM,cAAc,kBAAkB,QAAQ,MAAM;AACpD,QAAM,aAAaC,MAAK,QAAQ,QAAQ,SAAS;AAEjD,QAAM,YAAY,UAAU,YAAY,aAAa,QAAQ,UAAU;AAEvE,MAAI,CAAC,WAAW;AACd,WAAO;AAAA,EACT;AAEA,SAAO,mBAAmB,SAAS;AACrC;","names":["path","path"]}
package/package.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "name": "@skapxd/tree",
3
+ "version": "1.0.1",
4
+ "description": "A directory structure tree generator for CLI",
5
+ "main": "./dist/index.cjs",
6
+ "module": "./dist/index.mjs",
7
+ "types": "./dist/index.d.ts",
8
+ "bin": {
9
+ "tree": "./dist/cli.cjs"
10
+ },
11
+ "files": [
12
+ "dist"
13
+ ],
14
+ "scripts": {
15
+ "build": "tsup",
16
+ "dev": "tsup --watch",
17
+ "test": "vitest run -c vitest.unit.config.ts",
18
+ "test:ui": "vitest --ui -c vitest.unit.config.ts",
19
+ "test:coverage": "vitest run --coverage -c vitest.unit.config.ts",
20
+ "typecheck": "tsc --noEmit",
21
+ "start": "node dist/cli.cjs"
22
+ },
23
+ "keywords": [
24
+ "directory",
25
+ "tree",
26
+ "cli",
27
+ "ascii",
28
+ "structure"
29
+ ],
30
+ "author": "skapxd",
31
+ "license": "MIT",
32
+ "dependencies": {
33
+ "commander": "14.0.2"
34
+ },
35
+ "devDependencies": {
36
+ "@types/commander": "2.12.5",
37
+ "@types/node": "25.0.10",
38
+ "@vitest/coverage-v8": "4.0.17",
39
+ "@vitest/ui": "4.0.17",
40
+ "tsup": "8.5.1",
41
+ "typescript": "5.9.3",
42
+ "vitest": "4.0.18"
43
+ },
44
+ "repository": {
45
+ "type": "git",
46
+ "url": "https://github.com/skapxd/tree"
47
+ }
48
+ }