UNPKG

@posthog/nextjs-config

Version:

NextJS configuration helper for Posthog 🦔

64 lines (63 loc) • 2.29 kB
import { fileURLToPath as __webpack_fileURLToPath__ } from "node:url"; import { dirname as __webpack_dirname__ } from "node:path"; import path from "path"; import fs from "fs"; import { spawn } from "child_process"; var utils_dirname = __webpack_dirname__(__webpack_fileURLToPath__(import.meta.url)); function resolveBinaryPath(envPath, cwd, binName) { const envLocations = envPath.split(path.delimiter); const localLocations = buildLocalBinaryPaths(cwd); const directories = [ ...new Set([ ...envLocations, ...localLocations ]) ]; for (const directory of directories){ const binaryPath = path.join(directory, binName); if (fs.existsSync(binaryPath)) return binaryPath; } throw new Error(`Binary ${binName} not found`); } const buildLocalBinaryPaths = (cwd)=>{ const localPaths = getLocalPaths(path.resolve(cwd)).map((localPath)=>path.join(localPath, 'node_modules/.bin')); return localPaths; }; const getLocalPaths = (startPath)=>{ const paths = []; let currentPath = startPath; while(true){ paths.push(currentPath); const parentPath = path.resolve(currentPath, '..'); if (parentPath === currentPath) break; currentPath = parentPath; } return paths; }; async function callPosthogCli(args, env, verbose) { let binaryLocation; try { var _process_env_PATH; binaryLocation = resolveBinaryPath(null != (_process_env_PATH = process.env.PATH) ? _process_env_PATH : '', utils_dirname, 'posthog-cli'); } catch (e) { throw new Error(`Binary ${e} not found. Make sure postinstall script has been allowed for @posthog/cli`); } if (verbose) console.log('running posthog-cli from ', binaryLocation); const child = spawn(binaryLocation, [ ...args ], { stdio: verbose ? 'inherit' : 'ignore', env, cwd: process.cwd() }); await new Promise((resolve, reject)=>{ child.on('close', (code)=>{ if (0 === code) resolve(); else reject(new Error(`Command failed with code ${code}`)); }); child.on('error', (error)=>{ reject(error); }); }); } export { buildLocalBinaryPaths, callPosthogCli, resolveBinaryPath };