{"version":3,"file":"runtime-utils.mjs","names":[],"sources":["../src/runtime-utils/path.ts"],"sourcesContent":["import { stat } from 'node:fs/promises';\nimport { join, dirname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\n/**\n * Universal ESM function to get the file path of the caller.\n * Works in Node.js, Deno, and Bun (native ESM environments).\n *\n * - Uses V8 structured stack traces when available (Node/Bun).\n * - Falls back to string-based stack parsing when necessary (e.g., Deno).\n * - Throws a descriptive error when the file path cannot be determined.\n */\n\nclass CallerFileError extends Error {\n  info: unknown;\n  constructor(message: string, info: unknown = {}) {\n    super(message);\n    this.name = 'CallerFileError';\n    this.info = info;\n  }\n}\n\n/**\n * Returns the absolute file path of the calling file.\n *\n * @param {number} depth - 1 = immediate caller, 2 = caller's caller, etc.\n * @returns {string} Absolute file path of the caller.\n * @throws {CallerFileError} If the caller file cannot be determined.\n */\nexport function getCallerFile(depth = 1) {\n  if (typeof depth !== 'number' || depth < 1) {\n    throw new CallerFileError('Invalid depth argument', { depth });\n  }\n\n  // --- Primary method: V8 structured stack trace (Node.js / Bun) ---\n  try {\n    const originalPrepare = Error.prepareStackTrace;\n    Error.prepareStackTrace = (_, structuredStackTrace) => structuredStackTrace;\n    const err = new Error();\n    const { stack } = err;\n    Error.prepareStackTrace = originalPrepare;\n\n    if (Array.isArray(stack)) {\n      const frame = stack[depth];\n      if (frame && typeof frame.getFileName === 'function') {\n        const file = frame.getFileName();\n        if (typeof file === 'string') return file;\n        throw new CallerFileError('CallSite#getFileName() returned null', {\n          frame,\n        });\n      } else {\n        throw new CallerFileError('Invalid or missing CallSite object', {\n          frame,\n        });\n      }\n    } else {\n      throw new CallerFileError('Structured stack trace unavailable', {\n        stack,\n      });\n    }\n  } catch (v8Error) {\n    // --- Fallback: plain text stack parsing (Deno and others) ---\n    try {\n      const stackStr = new Error().stack;\n      if (typeof stackStr !== 'string') {\n        throw new CallerFileError('Error.stack is not a string', {\n          stack: stackStr,\n        });\n      }\n\n      const lines = stackStr\n        .split('\\n')\n        .map((l) => l.trim())\n        .filter(Boolean);\n      const index = 1 + depth;\n      if (index >= lines.length) {\n        throw new CallerFileError('Stack trace too shallow', { lines });\n      }\n\n      const line = lines[index];\n\n      // Match file URLs or absolute paths\n      const match =\n        line.match(/(file:\\/\\/[^\\s)]+)/) ||\n        line.match(/(\\/[^:\\s)]+)(:\\d+){0,2}/) ||\n        line.match(/([A-Za-z]:\\\\[^:\\s)]+)(:\\d+){0,2}/);\n\n      if (!match) {\n        throw new CallerFileError('No file path pattern found in stack line', {\n          line,\n        });\n      }\n\n      const raw = match[1];\n      if (raw.startsWith('file://')) {\n        const url = new URL(raw);\n        return url.pathname;\n      }\n\n      return raw.replace(/:\\d+(:\\d+)?$/, '');\n    } catch (fallbackError) {\n      if (fallbackError instanceof CallerFileError) throw fallbackError;\n      throw new CallerFileError('Fallback stack parsing failed', {\n        cause: fallbackError,\n      });\n    }\n  }\n}\n\n/**\n * Returns the absolute file path of the calling file.\n *\n * @param {number} depth - 1 = immediate caller, 2 = caller's caller, etc.\n * @returns {string} Absolute file path of the caller.\n * @throws {CallerFileError} If the caller file cannot be determined.\n */\nexport function getCallerFilePath(depth = 1) {\n  const file = getCallerFile(depth + 1);\n  return file.startsWith('file:') ? fileURLToPath(file) : file;\n}\n\n/**\n * Returns the directory that contains the package.json\n * associated with the specified import.meta.url.\n *\n * If no package.json is found while walking up the directory tree,\n * an error will be thrown.\n */\nexport async function getPackageDir(\n  callerFilePath = getCallerFilePath(),\n): Promise<string> {\n  // const { stat } = await import('node:fs/promises');\n  // const { join, dirname } = await import('node:path');\n  // const { fileURLToPath } = await import('node:url');\n\n  let dir = dirname(callerFilePath);\n\n  while (true) {\n    const pkgJson = join(dir, 'package.json');\n\n    const exists = await stat(pkgJson)\n      .then(() => true)\n      .catch(() => false);\n    if (exists) return dir;\n\n    // Move to the parent directory\n    const parent = dirname(dir);\n    if (parent === dir) break;\n    dir = parent;\n  }\n\n  throw new Error(`package.json not found for: ${callerFilePath}`);\n}\n"],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