pathResolver.js 2.12 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, '推导包根完成', { 包根: 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)
  for (let i = 0; i < candidates.length; i++) {
    const path = candidates[i]
    const exists = await fileExists(path)
    if (exists) {
      logStep(STAGE, '命中数据库文件', { 路径: path })
      return path
    }
  }
  return null
}