pathResolver.js 2.37 KB
import { PathUtils } from '@/utils/recordManager/index.js'
import { DB_FILE } from './constants.js'
import { normalizePath } from './pathCache.js'
import { fileExists } from './fileIo.js'
import { getDefaultPackageRoots } from './packageName.js'
import { logStep } from './log.js'

const STAGE = '归并·路径'

export { getDefaultPackageRoots, getRuntimePackageName, getPackageNamesForMerge } from './packageName.js'

export function getAppId() {
  if (typeof plus !== 'undefined' && plus.runtime && plus.runtime.appid) {
    return plus.runtime.appid
  }
  return '__UNI__D3BD3DF'
}

/**
 * 从 doc 目录 fullPath 推导包根目录
 */
export function derivePackageRootFromDocPath(docPath) {
  const normalized = normalizePath(docPath)
  if (!normalized) return ''

  const appId = getAppId()
  const docSuffix = `/apps/${appId}/doc`
  if (normalized.endsWith(docSuffix)) {
    return normalized.substring(0, normalized.length - docSuffix.length)
  }

  const appsMarker = '/apps/'
  const appsIdx = normalized.indexOf(appsMarker)
  if (appsIdx > 0) {
    return normalized.substring(0, appsIdx)
  }

  if (normalized.endsWith('/doc')) {
    return normalized.substring(0, normalized.length - 4)
  }

  return normalized
}

export async function getCurrentPackageRoot() {
  const docPath = await PathUtils.getFilePath()
  const root = derivePackageRootFromDocPath(docPath)
  logStep(STAGE, '由 doc 路径推导包根', { doc: normalizePath(docPath), 包根: root })
  return root
}

/**
 * 包根下 zyzs.db 的候选绝对路径(无 file:// 前缀)
 */
export function resolveDbFilePaths(packageRoot) {
  const root = normalizePath(packageRoot)
  const appId = getAppId()
  return [
    `${root}/${DB_FILE}`,
    `${root}/apps/${appId}/doc/${DB_FILE}`
  ]
}

export async function findDbInPackageRoot(packageRoot) {
  const candidates = resolveDbFilePaths(packageRoot)
  logStep(STAGE, '开始探测数据库候选路径', { 包根: packageRoot, 候选数: candidates.length })

  for (let i = 0; i < candidates.length; i++) {
    const path = candidates[i]
    const exists = await fileExists(path)
    logStep(STAGE, `候选 (${i + 1}/${candidates.length})`, { 路径: path, 存在: exists })
    if (exists) {
      logStep(STAGE, '命中数据库文件', { 路径: path, 包根: packageRoot })
      return path
    }
  }

  logStep(STAGE, '未命中任何候选库', { 包根: packageRoot })
  return null
}