ossCache.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // 统一给 OSS/MinIO/静态域资源追加版本参数(用于绕过长缓存)。
  2. // 约束:不要用 Date.now() 常态化破缓存;默认用“可控版本号”,需要强刷时只改版本号即可。
  3. let _cachedVersion = null
  4. // TODO(config-hardcoded): 资源版本号当前写死,后续改为构建产物自动注入(如 commit hash / CI build number)。
  5. const STATIC_ASSETS_VERSION = '20260423'
  6. // 作为兜底版本号来源(构建期静态注入)
  7. // eslint-disable-next-line import/no-unresolved
  8. import manifest from '@/manifest.json'
  9. function fallbackVersionFromManifest() {
  10. try {
  11. const vn = String(manifest?.versionName || '').trim()
  12. const vc = String(manifest?.versionCode || '').trim()
  13. return [vn, vc].filter(Boolean).join('.')
  14. } catch {
  15. // ignore
  16. }
  17. return ''
  18. }
  19. /**
  20. * 统一版本号:
  21. * - 写死常量:`STATIC_ASSETS_VERSION`
  22. * - 兜底:manifest.versionName/versionCode
  23. * - 最终兜底:固定日期
  24. */
  25. export function getStaticAssetsVersion() {
  26. if (_cachedVersion != null) return _cachedVersion
  27. const v =
  28. STATIC_ASSETS_VERSION ||
  29. fallbackVersionFromManifest() ||
  30. '20260423'
  31. _cachedVersion = String(v || '').trim()
  32. return _cachedVersion
  33. }
  34. function hasSignedQuery(u) {
  35. // 预签名/鉴权 URL:追加参数可能导致签名失效,必须跳过
  36. return /(?:[?&](?:X-Amz-|x-amz-|OSSAccessKeyId|Signature|x-oss-|Expires)=)/.test(u)
  37. }
  38. function hasVersionParam(u) {
  39. return /(?:[?&]v=)/i.test(u)
  40. }
  41. function looksLikeOurObjectStorage(u) {
  42. // 只对我们自己的 OSS/MinIO/静态域处理,避免误伤第三方资源
  43. return (
  44. u.includes('/sqxp-static/') ||
  45. u.includes('/sanqiang/') ||
  46. u.includes('/minio/') ||
  47. /:\/\/(?:www\.)?chengyantek\.cn\//i.test(u) ||
  48. /:\/\/\d{1,3}(?:\.\d{1,3}){3}:20004\//.test(u)
  49. )
  50. }
  51. function appendQueryParam(url, key, value) {
  52. const sep = url.includes('?') ? '&' : '?'
  53. return `${url}${sep}${encodeURIComponent(key)}=${encodeURIComponent(value)}`
  54. }
  55. /**
  56. * 给 OSS/MinIO/静态域 URL 追加 `v=<version>`,用于“内容更新但 URL 不变”时强制刷新。
  57. *
  58. * - 已带 `v=`:不重复追加
  59. * - 预签名 URL:不追加(避免签名失效)
  60. * - 非 http(s) / // / 非本站存储域:不处理
  61. */
  62. export function withOssVersion(rawUrl, version = getStaticAssetsVersion()) {
  63. const u = String(rawUrl || '').trim()
  64. if (!u) return ''
  65. if (!(u.startsWith('http://') || u.startsWith('https://') || u.startsWith('//'))) return u
  66. if (!version) return u
  67. if (!looksLikeOurObjectStorage(u)) return u
  68. if (hasVersionParam(u)) return u
  69. if (hasSignedQuery(u)) return u
  70. return appendQueryParam(u, 'v', version)
  71. }