forked from rocicorp/mono
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate-docs.ts
More file actions
221 lines (187 loc) · 5.96 KB
/
generate-docs.ts
File metadata and controls
221 lines (187 loc) · 5.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
/* eslint-disable no-console */
import * as fs from 'node:fs';
import * as http from 'node:http';
import * as path from 'node:path';
import * as url from 'node:url';
import {Application, TSConfigReader} from 'typedoc';
import {WebSocket, WebSocketServer} from 'ws';
// Get the directory name using import.meta.url
const dirname = url.fileURLToPath(new URL('.', import.meta.url));
// Define a custom WebSocket server type with our notifyClients method
interface LiveReloadServer {
clients: Set<WebSocket>;
notifyClients: () => void;
}
// Create output directory if it doesn't exist
const outputDir = path.resolve(dirname, '../docs');
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, {recursive: true});
}
const entryPoints = [
path.resolve(dirname, '../src/zero.ts'),
path.resolve(dirname, '../src/react.ts'),
path.resolve(dirname, '../src/solid.ts'),
];
const options = {
entryPoints,
out: outputDir,
name: 'Zero API Documentation',
excludePrivate: true,
excludeProtected: true,
preserveWatchOutput: true,
};
let wsServer: LiveReloadServer | null = null;
// Start TypeDoc in watch mode
async function startTypedocWatcher() {
// Create TypeDoc application using the static factory method
const app = await Application.bootstrap(options);
// Add TSConfig reader
app.options.addReader(new TSConfigReader());
console.log(`Starting TypeDoc in watch mode`);
// Use convertAndWatch to watch for changes and regenerate documentation
await app.convertAndWatch(async project => {
if (project) {
console.log(`[TypeDoc] Documentation updated at ${outputDir}`);
await app.generateDocs(project, outputDir);
// Notify WebSocket clients to reload
if (wsServer) {
console.log('Notifying clients to reload');
wsServer.notifyClients();
}
} else {
console.error('[TypeDoc] Failed to generate documentation');
}
});
}
// Generate docs once without watch mode
async function generateDocsOnce() {
try {
// Create TypeDoc application using the static factory method
const app = await Application.bootstrap(options);
// Add TSConfig reader
app.options.addReader(new TSConfigReader());
// Generate docs
const project = await app.convert();
if (project) {
await app.generateDocs(project, outputDir);
// Verify files were created
const files = fs
.readdirSync(outputDir)
.filter(file => !file.startsWith('.'));
if (files.length === 0) {
throw new Error('No documentation files were generated');
}
console.log(`Documentation generated successfully at ${outputDir}`);
console.log(`Generated ${files.length} files`);
} else {
console.error('Failed to generate documentation');
}
} catch (error) {
console.error(
'Error generating documentation:',
error instanceof Error ? error.message : String(error),
);
}
}
// Create a simple web server for the documentation
function createServer(docsDir: string, port = 3000) {
const server = http.createServer((req, res) => {
// Add live reload script to HTML files
if (req.url === '/livereload.js') {
res.writeHead(200, {'Content-Type': 'text/javascript'});
res.end(`
const socket = new WebSocket('ws://localhost:${port + 1}');
socket.addEventListener('message', () => {
console.log('Reloading page...');
window.location.reload();
});
`);
return;
}
// Default to index.html for root path
let filePath = path.join(docsDir, req.url || '');
if (req.url === '/' || req.url === '') {
filePath = path.join(docsDir, 'index.html');
}
// Handle file serving
fs.readFile(filePath, (err, data) => {
if (err) {
if (err.code === 'ENOENT') {
res.writeHead(404);
res.end('File not found');
} else {
res.writeHead(500);
res.end('Server error');
}
return;
}
const ext = path.extname(filePath);
const contentType = getContentType(ext);
res.writeHead(200, {'Content-Type': contentType});
// Inject live reload script into HTML files
if (ext === '.html') {
const html = data.toString();
const injectedHtml = html.replace(
'</head>',
'<script src="/livereload.js"></script></head>',
);
res.end(injectedHtml);
} else {
res.end(data);
}
});
});
server.listen(port, () => {
console.log(`Documentation server running at http://localhost:${port}`);
});
return server;
}
// Create WebSocket server for live reload
function createWebSocketServer(port = 3001): LiveReloadServer {
const wss = new WebSocketServer({port});
console.log(`WebSocket server for live reload running on port ${port}`);
return {
clients: wss.clients,
notifyClients: () => {
for (const client of wss.clients) {
if (client.readyState === WebSocket.OPEN) {
client.send('reload');
}
}
},
};
}
function getContentType(ext: string) {
const contentTypes: Record<string, string> = {
'.html': 'text/html',
'.css': 'text/css',
'.js': 'text/javascript',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.svg': 'image/svg+xml',
};
return contentTypes[ext] || 'text/plain';
}
// Parse command line arguments
const args = process.argv.slice(2);
const runServer = args.includes('--server') || args.includes('-s');
const watchMode = args.includes('--watch') || args.includes('-w') || runServer;
// Run documentation generation based on mode
if (watchMode) {
void startTypedocWatcher();
} else {
void generateDocsOnce();
}
// Start server if requested
if (runServer) {
const docsDir = path.resolve(dirname, '../docs');
const httpServer = createServer(docsDir);
wsServer = createWebSocketServer();
// Handle termination
process.on('SIGINT', () => {
console.log('Stopping servers...');
httpServer.close();
process.exit(0);
});
}