|
1 | 1 | // src/sdk-paths.ts |
2 | 2 | import fs from "fs"; |
3 | 3 | import path from "path"; |
4 | | -import { fileURLToPath } from "url"; |
5 | 4 |
|
6 | | -const __filename = fileURLToPath(import.meta.url); |
7 | | -const __dirname = path.dirname(__filename); |
| 5 | +// Find the SDK root by searching upward from current working directory |
| 6 | +// This approach works in all environments without needing import.meta or __dirname |
| 7 | +function findSDKRootSync(): string { |
| 8 | + let dir = process.cwd(); |
| 9 | + const maxUp = 10; // Search up to 10 levels |
8 | 10 |
|
9 | | -function findTemplatesDir(maxUp = 5): string { |
10 | | - let dir = __dirname; |
11 | | - for (let i = 0; i <= maxUp; i++) { |
12 | | - const candidate = path.join(dir, "templates"); |
13 | | - if (fs.existsSync(candidate)) return candidate; |
| 11 | + for (let i = 0; i < maxUp; i++) { |
| 12 | + const packageJsonPath = path.join(dir, "package.json"); |
| 13 | + if (fs.existsSync(packageJsonPath)) { |
| 14 | + try { |
| 15 | + const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8')); |
| 16 | + // Check if this is the kitdot package |
| 17 | + if (pkg.name === 'kitdot' || fs.existsSync(path.join(dir, 'templates'))) { |
| 18 | + return dir; |
| 19 | + } |
| 20 | + } catch (_e) { |
| 21 | + // Invalid package.json, continue searching |
| 22 | + } |
| 23 | + } |
14 | 24 | const parent = path.dirname(dir); |
15 | | - if (parent === dir) break; |
| 25 | + if (parent === dir) break; // Reached root |
16 | 26 | dir = parent; |
17 | 27 | } |
18 | | - throw new Error("templates folder not found (checked up from __dirname)"); |
| 28 | + |
| 29 | + // Fallback to cwd if we can't find the SDK root |
| 30 | + return process.cwd(); |
| 31 | +} |
| 32 | + |
| 33 | +// Cache the SDK root |
| 34 | +let _sdkRoot: string | null = null; |
| 35 | + |
| 36 | +function getSDKRoot(): string { |
| 37 | + if (!_sdkRoot) { |
| 38 | + _sdkRoot = findSDKRootSync(); |
| 39 | + } |
| 40 | + return _sdkRoot; |
| 41 | +} |
| 42 | + |
| 43 | +export async function findSDKRoot(): Promise<string> { |
| 44 | + return getSDKRoot(); |
| 45 | +} |
| 46 | + |
| 47 | +function findTemplatesDir(): string { |
| 48 | + const sdkRoot = getSDKRoot(); |
| 49 | + const templatesPath = path.join(sdkRoot, "templates"); |
| 50 | + |
| 51 | + if (fs.existsSync(templatesPath)) { |
| 52 | + return templatesPath; |
| 53 | + } |
| 54 | + |
| 55 | + throw new Error(`templates folder not found in SDK root: ${sdkRoot}`); |
19 | 56 | } |
20 | 57 |
|
21 | 58 | export function resolveTemplatePath(templatePath: string): string { |
|
0 commit comments