@posthog/nextjs-config
Version:
NextJS configuration helper for Posthog 🦔
49 lines (48 loc) • 1.77 kB
JavaScript
import promises from "fs/promises";
import path from "path";
const SOURCE_MAPPING_URL_COMMENT = /^[ \t]*\/\/
async function stripDanglingSourceMapComments(distDir) {
let jsFiles;
try {
jsFiles = await listJsFiles(path.join(distDir, 'static'));
} catch (e) {
return;
}
for (const file of jsFiles)try {
await stripDanglingComment(file);
} catch (e) {}
}
async function listJsFiles(dir) {
const files = [];
for (const entry of (await promises.readdir(dir, {
withFileTypes: true
}))){
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) files.push(...await listJsFiles(fullPath));
else if (entry.isFile() && /\.[mc]?js$/.test(fullPath)) files.push(fullPath);
}
return files;
}
async function stripDanglingComment(file) {
const content = await promises.readFile(file, 'utf8');
const match = [
...content.matchAll(SOURCE_MAPPING_URL_COMMENT)
].pop();
if (!match) return;
var _match_;
const url = (null != (_match_ = match[1]) ? _match_ : '').trim();
if ('' === url || url.startsWith('data:') || url.startsWith('http://') || url.startsWith('https://') || url.startsWith('//') || await exists(path.resolve(path.dirname(file), url))) return;
let lineEnd = match.index + match[0].length;
if ('\r' === content[lineEnd]) lineEnd += 1;
if ('\n' === content[lineEnd]) lineEnd += 1;
await promises.writeFile(file, content.slice(0, match.index) + content.slice(lineEnd), 'utf8');
}
async function exists(filePath) {
try {
await promises.access(filePath);
return true;
} catch (e) {
return false;
}
}
export { stripDanglingSourceMapComments };