liveProfiles.mjs 2.77 KB
/**
 * @file 人工触发的 Live 自动化配置。凭证只从环境变量读取,定义中不保存手机号或验证码。
 */

export const LIVE_PROFILE_DEFINITIONS = Object.freeze({
  'regional-dev-login': Object.freeze({
    environment: 'development',
    mode: 'login-only',
    baseUrl: 'http://dj.dev.glsx.com.cn/rop-dj-car-boutique',
    mobileEnv: 'LIVE_REGIONAL_DEV_MOBILE',
    codeEnv: 'LIVE_REGIONAL_DEV_CODE',
  }),
  'regional-test': Object.freeze({
    environment: 'test',
    mode: 'functional',
    baseUrl: 'http://dj.test.glsx.com.cn/rop-dj-car-boutique',
    mobileEnv: 'LIVE_REGIONAL_TEST_MOBILE',
    codeEnv: 'LIVE_REGIONAL_TEST_CODE',
    yqName: '流程测试园区门店',
    storeName: '波波的单店门店',
    sceneName: '精品升级',
  }),
})

function requiredValue(env, name, missing) {
  const value = String(env[name] ?? '').trim()
  if (!value) missing.push(name)
  return value
}

/**
 * 解析一个已批准的 Live 身份;运行时凭据不会进入静态配置。
 *
 * @param {string} profileName 配置名。
 * @param {NodeJS.ProcessEnv|Record<string, string>} env 运行时环境变量。
 * @returns {Readonly<object>} 已解析配置。
 */
export function resolveLiveProfile(profileName, env = process.env) {
  const normalizedName = String(profileName || '').trim()
  if (!normalizedName) throw new Error('Live profile is required')
  const definition = LIVE_PROFILE_DEFINITIONS[normalizedName]
  if (!definition) throw new Error(`Unknown live profile: ${normalizedName}`)

  const missing = []
  const mobile = requiredValue(env, definition.mobileEnv, missing)
  const code = requiredValue(env, definition.codeEnv, missing)
  if (missing.length) {
    throw new Error(`Missing Live environment variables: ${missing.join(', ')}`)
  }

  return Object.freeze({
    name: normalizedName,
    environment: definition.environment,
    mode: definition.mode,
    baseUrl: definition.baseUrl,
    mobile,
    code,
    ...(definition.yqName ? { yqName: definition.yqName } : {}),
    ...(definition.storeName ? { storeName: definition.storeName } : {}),
    ...(definition.sceneName ? { sceneName: definition.sceneName } : {}),
  })
}

/**
 * 校验功能 profile 和独立写入开关。
 *
 * @param {object} profile 已解析配置。
 * @param {NodeJS.ProcessEnv|Record<string, string>} env 运行时环境变量。
 * @returns {true} 校验通过。
 */
export function assertLiveWriteAllowed(profile, env = process.env) {
  if (!LIVE_PROFILE_DEFINITIONS[profile?.name]) {
    throw new Error('Approved Live profile is required')
  }
  if (profile.mode !== 'functional') {
    throw new Error(`${profile.name} does not allow Live writes`)
  }
  if (env.LIVE_ALLOW_WRITES !== '1') {
    throw new Error('LIVE_ALLOW_WRITES=1 is required for Live write tests')
  }
  return true
}