unwrap-namespace.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. #!/usr/bin/env bun
  2. /**
  3. * Unwrap a TypeScript `export namespace` into flat exports + barrel.
  4. *
  5. * Usage:
  6. * bun script/unwrap-namespace.ts src/bus/index.ts
  7. * bun script/unwrap-namespace.ts src/bus/index.ts --dry-run
  8. *
  9. * What it does:
  10. * 1. Reads the file and finds the `export namespace Foo { ... }` block
  11. * (uses ast-grep for accurate AST-based boundary detection)
  12. * 2. Removes the namespace wrapper and dedents the body
  13. * 3. Fixes self-references (e.g. Config.PermissionAction → PermissionAction)
  14. * 4. If the file is index.ts, renames it to <lowercase-name>.ts
  15. * 5. Creates/updates index.ts with `export * as Foo from "./<file>"`
  16. * 6. Rewrites import paths across src/, test/, and script/
  17. * 7. Fixes sibling imports within the same directory
  18. *
  19. * Requires: ast-grep (`brew install ast-grep` or `cargo install ast-grep`)
  20. */
  21. import path from "path"
  22. import fs from "fs"
  23. const args = process.argv.slice(2)
  24. const dryRun = args.includes("--dry-run")
  25. const filePath = args.find((a) => !a.startsWith("--"))
  26. if (!filePath) {
  27. console.error("Usage: bun script/unwrap-namespace.ts <file> [--dry-run]")
  28. process.exit(1)
  29. }
  30. const absPath = path.resolve(filePath)
  31. if (!fs.existsSync(absPath)) {
  32. console.error(`File not found: ${absPath}`)
  33. process.exit(1)
  34. }
  35. const src = fs.readFileSync(absPath, "utf-8")
  36. const lines = src.split("\n")
  37. // Use ast-grep to find the namespace boundaries accurately.
  38. // This avoids false matches from braces in strings, templates, comments, etc.
  39. const astResult = Bun.spawnSync(
  40. ["ast-grep", "run", "--pattern", "export namespace $NAME { $$$BODY }", "--lang", "typescript", "--json", absPath],
  41. { stdout: "pipe", stderr: "pipe" },
  42. )
  43. if (astResult.exitCode !== 0) {
  44. console.error("ast-grep failed:", astResult.stderr.toString())
  45. process.exit(1)
  46. }
  47. const matches = JSON.parse(astResult.stdout.toString()) as Array<{
  48. text: string
  49. range: { start: { line: number; column: number }; end: { line: number; column: number } }
  50. metaVariables: { single: Record<string, { text: string }>; multi: Record<string, Array<{ text: string }>> }
  51. }>
  52. if (matches.length === 0) {
  53. console.error("No `export namespace Foo { ... }` found in file")
  54. process.exit(1)
  55. }
  56. if (matches.length > 1) {
  57. console.error(`Found ${matches.length} namespaces — this script handles one at a time`)
  58. console.error("Namespaces found:")
  59. for (const m of matches) console.error(` ${m.metaVariables.single.NAME.text} (line ${m.range.start.line + 1})`)
  60. process.exit(1)
  61. }
  62. const match = matches[0]
  63. const nsName = match.metaVariables.single.NAME.text
  64. const nsLine = match.range.start.line // 0-indexed
  65. const closeLine = match.range.end.line // 0-indexed, the line with closing `}`
  66. console.log(`Found: export namespace ${nsName} { ... }`)
  67. console.log(` Lines ${nsLine + 1}–${closeLine + 1} (${closeLine - nsLine + 1} lines)`)
  68. // Build the new file content:
  69. // 1. Everything before the namespace declaration (imports, etc.)
  70. // 2. The namespace body, dedented by one level (2 spaces)
  71. // 3. Everything after the closing brace (rare, but possible)
  72. const before = lines.slice(0, nsLine)
  73. const body = lines.slice(nsLine + 1, closeLine)
  74. const after = lines.slice(closeLine + 1)
  75. // Dedent: remove exactly 2 leading spaces from each line
  76. const dedented = body.map((line) => {
  77. if (line === "") return ""
  78. if (line.startsWith(" ")) return line.slice(2)
  79. return line
  80. })
  81. let newContent = [...before, ...dedented, ...after].join("\n")
  82. // --- Fix self-references ---
  83. // After unwrapping, references like `Config.PermissionAction` inside the same file
  84. // need to become just `PermissionAction`. Only fix code positions, not strings.
  85. const exportedNames = new Set<string>()
  86. const exportRegex = /export\s+(?:const|function|class|interface|type|enum|abstract\s+class)\s+(\w+)/g
  87. for (const line of dedented) {
  88. for (const m of line.matchAll(exportRegex)) exportedNames.add(m[1])
  89. }
  90. const reExportRegex = /export\s*\{\s*([^}]+)\}/g
  91. for (const line of dedented) {
  92. for (const m of line.matchAll(reExportRegex)) {
  93. for (const name of m[1].split(",")) {
  94. const trimmed = name
  95. .trim()
  96. .split(/\s+as\s+/)
  97. .pop()!
  98. .trim()
  99. if (trimmed) exportedNames.add(trimmed)
  100. }
  101. }
  102. }
  103. let selfRefCount = 0
  104. if (exportedNames.size > 0) {
  105. const fixedLines = newContent.split("\n").map((line) => {
  106. // Split line into string-literal and code segments to avoid replacing inside strings
  107. const segments: Array<{ text: string; isString: boolean }> = []
  108. let i = 0
  109. let current = ""
  110. let inString: string | null = null
  111. while (i < line.length) {
  112. const ch = line[i]
  113. if (inString) {
  114. current += ch
  115. if (ch === "\\" && i + 1 < line.length) {
  116. current += line[i + 1]
  117. i += 2
  118. continue
  119. }
  120. if (ch === inString) {
  121. segments.push({ text: current, isString: true })
  122. current = ""
  123. inString = null
  124. }
  125. i++
  126. continue
  127. }
  128. if (ch === '"' || ch === "'" || ch === "`") {
  129. if (current) segments.push({ text: current, isString: false })
  130. current = ch
  131. inString = ch
  132. i++
  133. continue
  134. }
  135. if (ch === "/" && i + 1 < line.length && line[i + 1] === "/") {
  136. current += line.slice(i)
  137. segments.push({ text: current, isString: true })
  138. current = ""
  139. i = line.length
  140. continue
  141. }
  142. current += ch
  143. i++
  144. }
  145. if (current) segments.push({ text: current, isString: !!inString })
  146. return segments
  147. .map((seg) => {
  148. if (seg.isString) return seg.text
  149. let result = seg.text
  150. for (const name of exportedNames) {
  151. const pattern = `${nsName}.${name}`
  152. while (result.includes(pattern)) {
  153. const idx = result.indexOf(pattern)
  154. const charBefore = idx > 0 ? result[idx - 1] : " "
  155. const charAfter = idx + pattern.length < result.length ? result[idx + pattern.length] : " "
  156. if (/\w/.test(charBefore) || /\w/.test(charAfter)) break
  157. result = result.slice(0, idx) + name + result.slice(idx + pattern.length)
  158. selfRefCount++
  159. }
  160. }
  161. return result
  162. })
  163. .join("")
  164. })
  165. newContent = fixedLines.join("\n")
  166. }
  167. // Figure out file naming
  168. const dir = path.dirname(absPath)
  169. const basename = path.basename(absPath, ".ts")
  170. const isIndex = basename === "index"
  171. const implName = isIndex ? nsName.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase() : basename
  172. const implFile = path.join(dir, `${implName}.ts`)
  173. const indexFile = path.join(dir, "index.ts")
  174. const barrelLine = `export * as ${nsName} from "./${implName}"\n`
  175. console.log("")
  176. if (isIndex) {
  177. console.log(`Plan: rename ${basename}.ts → ${implName}.ts, create new index.ts barrel`)
  178. } else {
  179. console.log(`Plan: rewrite ${basename}.ts in place, create index.ts barrel`)
  180. }
  181. if (selfRefCount > 0) console.log(`Fixed ${selfRefCount} self-reference(s) (${nsName}.X → X)`)
  182. console.log("")
  183. if (dryRun) {
  184. console.log("--- DRY RUN ---")
  185. console.log("")
  186. console.log(`=== ${implName}.ts (first 30 lines) ===`)
  187. newContent
  188. .split("\n")
  189. .slice(0, 30)
  190. .forEach((l, i) => console.log(` ${i + 1}: ${l}`))
  191. console.log(" ...")
  192. console.log("")
  193. console.log(`=== index.ts ===`)
  194. console.log(` ${barrelLine.trim()}`)
  195. console.log("")
  196. if (!isIndex) {
  197. const relDir = path.relative(path.resolve("src"), dir)
  198. console.log(`=== Import rewrites (would apply) ===`)
  199. console.log(` ${relDir}/${basename}" → ${relDir}" across src/, test/, script/`)
  200. } else {
  201. console.log("No import rewrites needed (was index.ts)")
  202. }
  203. } else {
  204. if (isIndex) {
  205. fs.writeFileSync(implFile, newContent)
  206. fs.writeFileSync(indexFile, barrelLine)
  207. console.log(`Wrote ${implName}.ts (${newContent.split("\n").length} lines)`)
  208. console.log(`Wrote index.ts (barrel)`)
  209. } else {
  210. fs.writeFileSync(absPath, newContent)
  211. if (fs.existsSync(indexFile)) {
  212. const existing = fs.readFileSync(indexFile, "utf-8")
  213. if (!existing.includes(`export * as ${nsName}`)) {
  214. fs.appendFileSync(indexFile, barrelLine)
  215. console.log(`Appended to existing index.ts`)
  216. } else {
  217. console.log(`index.ts already has ${nsName} export`)
  218. }
  219. } else {
  220. fs.writeFileSync(indexFile, barrelLine)
  221. console.log(`Wrote index.ts (barrel)`)
  222. }
  223. console.log(`Rewrote ${basename}.ts (${newContent.split("\n").length} lines)`)
  224. }
  225. // --- Rewrite import paths across src/, test/, script/ ---
  226. const relDir = path.relative(path.resolve("src"), dir)
  227. if (!isIndex) {
  228. const oldTail = `${relDir}/${basename}`
  229. const searchDirs = ["src", "test", "script"].filter((d) => fs.existsSync(d))
  230. const rgResult = Bun.spawnSync(["rg", "-l", `from.*${oldTail}"`, ...searchDirs], {
  231. stdout: "pipe",
  232. stderr: "pipe",
  233. })
  234. const filesToRewrite = rgResult.stdout
  235. .toString()
  236. .trim()
  237. .split("\n")
  238. .filter((f) => f.length > 0)
  239. if (filesToRewrite.length > 0) {
  240. console.log(`\nRewriting imports in ${filesToRewrite.length} file(s)...`)
  241. for (const file of filesToRewrite) {
  242. const content = fs.readFileSync(file, "utf-8")
  243. fs.writeFileSync(file, content.replaceAll(`${oldTail}"`, `${relDir}"`))
  244. }
  245. console.log(` Done: ${oldTail}" → ${relDir}"`)
  246. } else {
  247. console.log("\nNo import rewrites needed")
  248. }
  249. } else {
  250. console.log("\nNo import rewrites needed (was index.ts)")
  251. }
  252. // --- Fix sibling imports within the same directory ---
  253. const siblingFiles = fs.readdirSync(dir).filter((f) => {
  254. if (!f.endsWith(".ts")) return false
  255. if (f === "index.ts" || f === `${implName}.ts`) return false
  256. return true
  257. })
  258. let siblingFixCount = 0
  259. for (const sibFile of siblingFiles) {
  260. const sibPath = path.join(dir, sibFile)
  261. const content = fs.readFileSync(sibPath, "utf-8")
  262. const pattern = new RegExp(`from\\s+["']\\./${basename}["']`, "g")
  263. if (pattern.test(content)) {
  264. fs.writeFileSync(sibPath, content.replace(pattern, `from "."`))
  265. siblingFixCount++
  266. }
  267. }
  268. if (siblingFixCount > 0) {
  269. console.log(`Fixed ${siblingFixCount} sibling import(s) in ${path.basename(dir)}/ (./${basename} → .)`)
  270. }
  271. }
  272. console.log("")
  273. console.log("=== Verify ===")
  274. console.log("")
  275. console.log("bunx --bun tsgo --noEmit # typecheck")
  276. console.log("bun run test # run tests")