|
1 | 1 | import { readFile } from 'node:fs/promises'; |
| 2 | +import { createRequire } from 'node:module'; |
2 | 3 | import path from 'node:path'; |
3 | 4 | import { dirname } from 'node:path'; |
4 | 5 | import { fileURLToPath } from 'node:url'; |
@@ -29,8 +30,32 @@ async function loadDatabase(): Promise<ReaderModel | null> { |
29 | 30 | console.log('GeoLite2-City.mmdb loaded (local)', dbPathLocal); |
30 | 31 | return Reader.openBuffer(dbBuffer); |
31 | 32 | } catch { |
32 | | - console.error('GeoLite2-City.mmdb not found', { dbPath, dbPathLocal }); |
33 | | - return null; |
| 33 | + // Try node_modules resolution (for Vercel/serverless environments) |
| 34 | + try { |
| 35 | + const require = createRequire(import.meta.url); |
| 36 | + // Resolve the package entry point, then find package.json relative to it |
| 37 | + const packageEntry = require.resolve('@openpanel/geo'); |
| 38 | + let packageDir = path.dirname(packageEntry); |
| 39 | + // Walk up to find package.json (package entry might be in src/ or dist/) |
| 40 | + for (let i = 0; i < 3; i++) { |
| 41 | + try { |
| 42 | + await readFile(path.join(packageDir, 'package.json')); |
| 43 | + break; // Found package.json |
| 44 | + } catch { |
| 45 | + packageDir = path.dirname(packageDir); |
| 46 | + } |
| 47 | + } |
| 48 | + const nodeModulesPath = path.join(packageDir, filename); |
| 49 | + const dbBuffer = await readFile(nodeModulesPath); |
| 50 | + console.log( |
| 51 | + 'GeoLite2-City.mmdb loaded (node_modules)', |
| 52 | + nodeModulesPath, |
| 53 | + ); |
| 54 | + return Reader.openBuffer(dbBuffer); |
| 55 | + } catch { |
| 56 | + console.error('GeoLite2-City.mmdb not found (node_modules)'); |
| 57 | + return null; |
| 58 | + } |
34 | 59 | } |
35 | 60 | } |
36 | 61 | } |
|
0 commit comments