Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

hmrFileEditor.ts

127 lines3.4 KB

1import { readFile, writeFile } from 'node:fs/promises'
2import path from 'node:path'
3​
4export function replaceAll(source: string, from: string, to: string) {
5 return source.split(from).join(to)
6}
7​
8export type HmrFileEditorOptions<TFileKey extends string> = {
9 rootDir?: string
10 files: Record<TFileKey, string>
11 normalizeSource?: (fileKey: TFileKey, source: string) => string
13​
14export function createHmrFileEditor<TFileKey extends string>(
15 options: HmrFileEditorOptions<TFileKey>,
16) {
17 const files = Object.fromEntries(
18 Object.entries(options.files).map(([key, filePath]) => [
19 key,
20 options.rootDir && !path.isAbsolute(filePath as string)
21 ? path.join(options.rootDir, filePath as string)
22 : (filePath as string),
23 ]),
24 ) as Record<TFileKey, string>
25 const originalContents: Partial<Record<TFileKey, string>> = {}
26 const pendingRestoreKeys = new Set<TFileKey>()
27 const normalizeSource =
28 options.normalizeSource ?? ((_fileKey: TFileKey, source: string) => source)
29​
30 async function captureOriginals() {
31 for (const [key, filePath] of Object.entries(files) as Array<
32 [TFileKey, string]
33 >) {
34 const current = await readFile(filePath, 'utf8')
35 const normalized = normalizeSource(key, current)
36​
37 if (normalized !== current) {
38 await writeFile(filePath, normalized)
39 pendingRestoreKeys.add(key)
40 }
41​
42 originalContents[key] = normalized
43 }
44 }
45​
46 const capturePromise = captureOriginals()
47​
48 async function restoreFiles(forceFileKeys: Iterable<TFileKey> = []) {
49 const forceRestoreKeys = new Set(forceFileKeys)
50 const restoredFileKeys: Array<TFileKey> = []
51​
52 for (const [key, filePath] of Object.entries(files) as Array<
53 [TFileKey, string]
54 >) {
55 const content = originalContents[key]
56 if (content === undefined) continue
57​
58 const current = await readFile(filePath, 'utf8')
59​
60 if (current !== content || forceRestoreKeys.has(key)) {
61 await writeFile(filePath, content)
62 restoredFileKeys.push(key)
63 }
64 }
65​
66 return restoredFileKeys
67 }
68​
69 async function replaceText(fileKey: TFileKey, from: string, to: string) {
70 const filePath = files[fileKey]
71 const source = await readFile(filePath, 'utf8')
72​
73 if (!source.includes(from)) {
74 throw new Error(`Expected file to include ${JSON.stringify(from)}`)
75 }
76​
77 await writeFile(filePath, source.replace(from, to))
78 }
79​
80 async function rewriteFile(
81 fileKey: TFileKey,
82 updater: (source: string) => string,
83 options: { allowNoop?: boolean } = {},
84 ) {
85 const filePath = files[fileKey]
86 const source = await readFile(filePath, 'utf8')
87 const updated = updater(source)
88​
89 if (updated === source && !options.allowNoop) {
90 throw new Error(`Expected ${filePath} to change during rewrite`)
91 }
92​
93 await writeFile(filePath, updated)
94 }
95​
96 async function replaceTextAndWait(
97 fileKey: TFileKey,
98 from: string,
99 to: string,
100 assertion: () => Promise<void>,
101 ) {
102 await replaceText(fileKey, from, to)
103 await assertion()
104 }
105​
106 async function rewriteFileAndWait(
107 fileKey: TFileKey,
108 updater: (source: string) => string,
109 assertion: () => Promise<void>,
110 options: { allowNoop?: boolean } = {},
111 ) {
112 await rewriteFile(fileKey, updater, options)
113 await assertion()
114 }
115​
116 return {
117 files,
118 pendingRestoreKeys,
119 capturePromise,
120 captureOriginals,
121 restoreFiles,
122 replaceText,
123 replaceTextAndWait,
124 rewriteFile,
125 rewriteFileAndWait,
126 }