File size: 2,373 Bytes
fea495a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { existsSync } from 'fs';
import { readFile, writeFile, mkdir } from 'fs/promises';
import { dirname, join } from 'path';
import { middlewareResponse } from './middleware-response';
import { devToolsConfigSchema } from '../shared/devtools-config-schema';
import { deepMerge } from '../shared/deepmerge';
const DEVTOOLS_CONFIG_FILENAME = 'next-devtools-config.json';
const DEVTOOLS_CONFIG_MIDDLEWARE_ENDPOINT = '/__nextjs_devtools_config';
export function devToolsConfigMiddleware(param) {
    let { distDir, sendUpdateSignal } = param;
    const configPath = join(distDir, 'cache', DEVTOOLS_CONFIG_FILENAME);
    return async function devToolsConfigMiddlewareHandler(req, res, next) {
        const { pathname } = new URL("http://n" + req.url);
        if (pathname !== DEVTOOLS_CONFIG_MIDDLEWARE_ENDPOINT) {
            return next();
        }
        if (req.method !== 'POST') {
            return middlewareResponse.methodNotAllowed(res);
        }
        const currentConfig = await getDevToolsConfig(distDir);
        const chunks = [];
        for await (const chunk of req){
            chunks.push(Buffer.from(chunk));
        }
        let body = Buffer.concat(chunks).toString('utf8');
        try {
            body = JSON.parse(body);
        } catch (error) {
            console.error('[Next.js DevTools] Invalid config body passed:', error);
            return middlewareResponse.badRequest(res);
        }
        const validation = devToolsConfigSchema.safeParse(body);
        if (!validation.success) {
            console.error('[Next.js DevTools] Invalid config passed:', validation.error.message);
            return middlewareResponse.badRequest(res);
        }
        const newConfig = deepMerge(currentConfig, validation.data);
        await writeFile(configPath, JSON.stringify(newConfig, null, 2));
        sendUpdateSignal(newConfig);
        return middlewareResponse.noContent(res);
    };
}
export async function getDevToolsConfig(distDir) {
    const configPath = join(distDir, 'cache', DEVTOOLS_CONFIG_FILENAME);
    if (!existsSync(configPath)) {
        await mkdir(dirname(configPath), {
            recursive: true
        });
        await writeFile(configPath, JSON.stringify({}));
        return {};
    }
    return JSON.parse(await readFile(configPath, 'utf8'));
}

//# sourceMappingURL=devtools-config-middleware.js.map