This document is written for AI agents (and human contributors) who need to work on this repository. It explains the project's architecture, execution flow, conventions, and practical notes so you can make changes confidently and correctly.
export-codebase is a Node.js CLI tool that aggregates a project's text files into a single, well-structured output file (default: project.txt). Each file's content is prefixed with its relative path (e.g., // src/index.ts), and the output begins with a visual tree of the project structure.
It is designed for sharing or archiving a codebase in one file, and for feeding context to LLMs.
| Concern | Choice |
|---|---|
| Language | TypeScript (strict mode, ES2022 target) |
| Module system | ESM ("type": "module", module: NodeNext) |
| Runtime | Node.js >= 18 |
| Bundler | tsup (ESM output, single file, dts + sourcemaps, minified) |
| Package manager | npm (lockfile: package-lock.json) |
| Dependencies | chalk (colored output), fast-glob (file discovery), ignore (gitignore matching), minimist (CLI arg parsing) |
| Code style | Prettier (config in .prettierrc.json: no semicolons, double quotes, 120 print width, 2-space indent) |
.
├── src/
│ ├── index.ts # Entry point: orchestrates the whole flow
│ ├── args.ts # CLI argument parsing (minimist) → ProgramArgs
│ ├── constants.ts # Hardcoded ignore patterns + binary extension list
│ ├── file-utils.ts # File discovery, reading, gitignore loading, output writing
│ ├── formatter.ts # Project structure tree, file-size formatting, summary display
│ ├── help.ts # `--help` text
│ ├── logger.ts # Leveled console logger (log/info/warn/error/success)
│ └── version.ts # Reads package.json version for the help message
├── tsup.config.ts # Build configuration
├── tsconfig.json # TS compiler options (noEmit; tsup handles output)
├── package.json # Scripts, metadata, deps
├── push.sh # Deprecated release helper (was dev → main merge → npm publish)
└── README.md # User-facing docs
process starts
└─ src/index.ts main()
├─ parseArgs() → ProgramArgs | null (exits on --help)
├─ createLogger({silent}) → leveled logger
├─ loadGitignore() → Ignore instance from .gitignore (empty if missing)
├─ findFiles() → FileContent[] (path + content)
│ ├─ fast-glob "**/*" with HARDCODED_IGNORES + output filename
│ ├─ filter out .gitignore matches
│ ├─ filter out binary extensions
│ └─ read each file as utf-8 (failures are logged and skipped)
├─ writeOutputFile() → WriteResult
│ ├─ generateProjectStructure() → ASCII tree of the repo
│ ├─ concat: structure + `// <path>` + content for each file
│ └─ write file (trimEnd + trailing newline), stat it
└─ displaySummary() → file count, total lines, size (skipped if empty output)
Key detail: main() is an async IIFE with a catch-all at the bottom of index.ts that prints a styled "critical unexpected error" and exits with code 1. Keep that in mind when changing control flow.
- Parses args, builds the logger, runs the pipeline, displays the summary.
- Exits with code 1 if output writing fails or the summary is unexpectedly incomplete.
- Warns when the output file was created but is empty.
minimistwith aliases:-o/--output,-s/--silent,-h/--help, plus--include-hidden.- Returns
null(and the process exits 0) when--helpis passed. - Default output filename comes from
constants.ts.
DEFAULT_OUTPUT_FILENAME— default output name.HARDCODED_IGNORES— always-excluded patterns:node_modules,.git,.env/.env.*(but NOT.env.example), lock files (incl.Cargo.lock,go.sum), build outputs (dist,build,out,coverage, Rust'starget), Gocoverage.out, logs, OS junk.BINARY_EXTENSIONS— extension set for binary files that are skipped (incl. object/archive artifacts.o,.a,.rlib,.rmeta).MAX_FILE_SIZE_BYTES— files larger than this (1 MB) are skipped as too large for text context.
If you add an exclusion or file type, this is the file to edit.
loadGitignore(projectRoot, logger)— reads.gitignoreinto anignoreinstance; falls back to an empty instance (with a warning) if missing/unreadable.findFiles(...)— two-stage filtering:fast-globignoresHARDCODED_IGNORES+ the output filename (so it's never considered).- Per-file:
.gitignorecheck, binary extension check, thenstat+ size check (files overMAX_FILE_SIZE_BYTESare logged and skipped), then async read.
- Returns
FileContent[]with normalized (forward-slash) relative paths. - File reads happen concurrently via
Promise.all; unreadable/unreadable-sized files are logged and skipped (never fatal).
writeOutputFile(...)— builds the final string (structure + "\n\n"then per-file// <path>\n\n<content>\n\n), trims trailing whitespace, ensures one trailing newline, writes, and stats the file. Returns a discriminatedWriteResultunion.
generateProjectStructure(...)— recursivereaddirSyncwalk producing an ASCII tree (├──/└──), directories first, alphabetically sorted. UsesHARDCODED_IGNORES+ output filename +.gitignorefor filtering. Directory read errors become inline[Error reading directory: ...]lines instead of crashing.formatFileSize(bytes)— B / KB / MB.displaySummary(...)— colored summary block.
createLogger({silent}):log/inforespectsilent;warn/erroralways print (errors are always shown per the README contract);successalways prints. Noteerroraccepts an optional second payload.
displayHelp()— prints usage text with chalk styling; version is read dynamically viagetPackageVersion()(readspackage.jsonrelative to the module path, falls back to"N/A").
| Script | What it does |
|---|---|
npm run build |
Bundle with tsup (entry src/index.ts, ESM, dts, sourcemaps, minified) |
npm run dev |
tsup watch mode |
npm start |
Run the built CLI (node dist/index.js) |
npm run fulltest |
Build then run — the project's manual smoke test |
There is no automated test suite in this repo. Verify changes with npm run build (type safety + bundling) and npm run fulltest against a sample project (or the repo itself) to check behavior. Note the CLI writes its output file into the CWD, so run it in a scratch directory (or use -o with a throwaway name) when testing.
- No semicolons, double quotes, 2-space indent, 120-column print width (Prettier via
.prettierrc.json). Match existing style; consider runningnpx prettier --writeon touched files. - Use
.tsextensions in relative imports (./logger.ts) — required byallowImportingTsExtensions+ NodeNext. - Explicit types on exported functions; internal types (
Ignore) stay infile-utils.ts(see the comment inindex.ts). - Comments in the code explain why (e.g., why the output file is added to fast-glob ignores) — preserve that intent when editing.
- Errors are surfaced through the logger (colored), not raw throws, except the top-level catch-all.
- No framework, no tests directory, no lint config beyond Prettier — keep it simple.
- Releases are fully automated: pushing/merging to
maintriggers.github/workflows/publish.yml, which installs withnpm ci, builds, and runsnpm publish --provenancevia the npm trusted publisher (OIDC — no token secret needed). A version guard skips the publish step when the version is already on npm. push.shis deprecated/unused — do not treat it as the release path.- Bump
package.json'sversionbefore merging tomainto trigger a real publish. - The
.gitignoreexcludes.freebuff,.cursorrules,.windsurfrules,.vscode, and output files likeproject.txt/custom_output.txt— generated artifacts should not be committed.
- Change default ignore rules →
src/constants.ts(HARDCODED_IGNORES). - Add/remove a binary file type →
src/constants.ts(BINARY_EXTENSIONS). - Change output format (separator, header, structure tree) →
src/file-utils.ts(writeOutputFile) andsrc/formatter.ts. - Add a CLI flag →
src/args.ts(parsing) +src/help.ts(docs) + wire intoindex.ts/relevant modules. - Tweak logging behavior →
src/logger.ts. - Change file discovery →
src/file-utils.ts(findFiles+loadGitignore).
- Path normalization: file paths are normalized to forward slashes before gitignore/binary checks and stored in the output;
path.joinis used for actual filesystem access. Windows compatibility depends on this — don't introduce raw backslash comparisons. - The output file must never be processed: it is excluded in both
fast-globignores and the structure-tree ignores. If you change the default filename, both places already read from the constant, but keep the symmetry. .env.exampleis intentionally kept while all other.env*are dropped.- Large files are skipped by size:
MAX_FILE_SIZE_BYTES(1 MB) is enforced infindFilesviafs.statbefore reading. If you change the constant, keephelp.ts's "1 MB" text in sync. - Case sensitivity is OS-dependent (
caseSensitiveMatch: process.platform !== "win32"). ignoreinstances are cheap to create but stateful:structureSpecificIgnoresgets a fresh instance pergenerateProjectStructurecall;.gitignorerules are loaded once and reused for both file filtering and the tree.- The build target is
node18andfseventsis externalized (macOS optional dep) — don't use Node APIs newer than 18 without a good reason.