WIP: A simple cli for daily tangled use cases and AI integration. This is for my personal use right now, but happy if others get mileage from it! :)
1#!/usr/bin/env node
2/**
3 * Post-process generated lexicon files to fix imports for ES modules
4 *
5 * This script:
6 * 1. Adds .js extensions to relative imports
7 * 2. Fixes multiformats/cid imports to use main package export
8 * 3. Ensures proper TypeScript compatibility with NodeNext module resolution
9 */
10
11import { readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
12import { join } from 'node:path';
13
14// Recursively find all .ts files in a directory
15function findTsFiles(dir, fileList = []) {
16 const files = readdirSync(dir);
17
18 for (const file of files) {
19 const filePath = join(dir, file);
20 const stat = statSync(filePath);
21
22 if (stat.isDirectory()) {
23 findTsFiles(filePath, fileList);
24 } else if (file.endsWith('.ts')) {
25 fileList.push(filePath);
26 }
27 }
28
29 return fileList;
30}
31
32// Find all generated TypeScript files in src/lexicon
33const files = findTsFiles('src/lexicon');
34
35let filesFixed = 0;
36let totalChanges = 0;
37
38for (const file of files) {
39 const content = readFileSync(file, 'utf-8');
40 let modified = content;
41 let fileChanges = 0;
42
43 // Fix multiformats/cid import to use main package export
44 // TypeScript can't resolve the subpath export with NodeNext resolution
45 const multiformatsCidRegex = /from\s+['"]multiformats\/cid['"]/g;
46 if (multiformatsCidRegex.test(modified)) {
47 modified = modified.replace(multiformatsCidRegex, "from 'multiformats'");
48 fileChanges++;
49 }
50
51 // Fix relative imports without .js extension
52 // Match: from '../../something' or from "../something"
53 // But don't match if it already has an extension
54 const relativeImportRegex = /from\s+['"](\.\.[^'"]*?)(?<!\.js|\.ts)['"]/g;
55 modified = modified.replace(relativeImportRegex, (_match, path) => {
56 fileChanges++;
57 return `from '${path}.js'`;
58 });
59
60 if (fileChanges > 0) {
61 writeFileSync(file, modified, 'utf-8');
62 filesFixed++;
63 totalChanges += fileChanges;
64 console.log(`✓ Fixed ${fileChanges} import(s) in ${file}`);
65 }
66}
67
68console.log(`\n✓ Fixed ${totalChanges} imports in ${filesFixed} files`);