完成JC-ArtList与JC-Salon端侧清理和统一命名
This commit is contained in:
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* Purpose: ACCOUNT_REGEX supports account.ts by holding or executing the account regex page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const ACCOUNT_REGEX = /^[A-Za-z0-9]+$/
|
||||
/**
|
||||
* Purpose: ACCOUNT_SANITIZE_REGEX supports account.ts by holding or executing the account sanitize regex page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const ACCOUNT_SANITIZE_REGEX = /[^A-Za-z0-9]/g
|
||||
|
||||
/**
|
||||
* Purpose: ACCOUNT_RULE_MESSAGE supports account.ts by holding or executing the account rule message page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const ACCOUNT_RULE_MESSAGE = '账号只能包含字母和数字'
|
||||
|
||||
/**
|
||||
* Purpose: sanitizeAccountInput supports account.ts by holding or executing the sanitize account input page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const sanitizeAccountInput = (value: string) => (value || '').replace(ACCOUNT_SANITIZE_REGEX, '')
|
||||
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* Purpose: LoadingInstance supports action-loading.ts by holding or executing the loading instance page or API role.
|
||||
* Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
import { ElLoading, type LoadingInstance } from 'element-plus'
|
||||
import 'element-plus/es/components/loading/style/css'
|
||||
|
||||
/**
|
||||
* Purpose: GlobalLoadingOptions supports action-loading.ts by holding or executing the global loading options page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface GlobalLoadingOptions {
|
||||
text?: string
|
||||
lock?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: activeLoadingCount supports action-loading.ts by holding or executing the active loading count page or API role.
|
||||
* Usage: import, call, read, or update this let from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
let activeLoadingCount = 0
|
||||
let loadingInstance: LoadingInstance | null = null
|
||||
|
||||
/**
|
||||
* Purpose: openGlobalLoading supports action-loading.ts by holding or executing the open global loading page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const openGlobalLoading = (options?: GlobalLoadingOptions) => {
|
||||
activeLoadingCount += 1
|
||||
|
||||
if (typeof window === 'undefined' || loadingInstance) {
|
||||
return
|
||||
}
|
||||
|
||||
loadingInstance = ElLoading.service({
|
||||
lock: options?.lock ?? true,
|
||||
text: options?.text ?? '\u52a0\u8f7d\u4e2d',
|
||||
background: 'rgba(255, 255, 255, 0.72)'
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: closeGlobalLoading supports action-loading.ts by holding or executing the close global loading page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const closeGlobalLoading = () => {
|
||||
activeLoadingCount = Math.max(0, activeLoadingCount - 1)
|
||||
|
||||
if (activeLoadingCount > 0) {
|
||||
return
|
||||
}
|
||||
|
||||
loadingInstance?.close()
|
||||
loadingInstance = null
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: runWithGlobalLoading supports action-loading.ts by holding or executing the run with global loading page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const runWithGlobalLoading = async <T>(
|
||||
task: (() => Promise<T>) | Promise<T>,
|
||||
options?: GlobalLoadingOptions
|
||||
) => {
|
||||
openGlobalLoading(options)
|
||||
|
||||
try {
|
||||
if (typeof task === 'function') {
|
||||
return await task()
|
||||
}
|
||||
|
||||
return await task
|
||||
} finally {
|
||||
closeGlobalLoading()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { BUY_NOW_MODE, getBuyNowProductIdFromQuery, isBuyNowCartItem } from './buy-now'
|
||||
|
||||
describe('buy-now checkout mode', () => {
|
||||
it('reads the target product id only when cart query is in buyNow mode', () => {
|
||||
expect(getBuyNowProductIdFromQuery({ mode: BUY_NOW_MODE, productId: '1001' })).toBe('1001')
|
||||
expect(getBuyNowProductIdFromQuery({ mode: 'cart', productId: '1001' })).toBe('')
|
||||
})
|
||||
|
||||
it('uses the first query value when vue-router provides array values', () => {
|
||||
expect(getBuyNowProductIdFromQuery({ mode: [BUY_NOW_MODE], productId: ['2002', '3003'] })).toBe('2002')
|
||||
})
|
||||
|
||||
it('matches numeric and string product ids for cart selection', () => {
|
||||
expect(isBuyNowCartItem(1001, '1001')).toBe(true)
|
||||
expect(isBuyNowCartItem('1002', '1001')).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,15 @@
|
||||
export const BUY_NOW_MODE = 'buyNow'
|
||||
|
||||
type QueryValue = string | string[] | null | undefined
|
||||
|
||||
const firstQueryValue = (value: QueryValue) => Array.isArray(value) ? value[0] : value
|
||||
|
||||
export const getBuyNowProductIdFromQuery = (query: Record<string, unknown>) => {
|
||||
const mode = firstQueryValue(query.mode as QueryValue)
|
||||
const productId = firstQueryValue(query.productId as QueryValue)
|
||||
return mode === BUY_NOW_MODE && productId ? String(productId) : ''
|
||||
}
|
||||
|
||||
export const isBuyNowCartItem = (itemProductId: unknown, buyNowProductId: string) => {
|
||||
return Boolean(buyNowProductId) && String(itemProductId || '') === String(buyNowProductId)
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { cartApi } from '@/api/cart'
|
||||
import { toOptionalIdString } from '@/utils/id'
|
||||
|
||||
/**
|
||||
* Purpose: fetchCartProductIdSet supports cart-state.ts by holding or executing the fetch cart product id set page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const fetchCartProductIdSet = async () => {
|
||||
try {
|
||||
const response = await cartApi.getCartList() as unknown as Array<{ productId?: string | number }>
|
||||
return new Set(
|
||||
(Array.isArray(response) ? response : [])
|
||||
.map(item => toOptionalIdString(item && item.productId))
|
||||
.filter((id): id is string => Boolean(id))
|
||||
)
|
||||
} catch (error) {
|
||||
return new Set<string>()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: hasCartProduct supports cart-state.ts by holding or executing the has cart product page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const hasCartProduct = (cartProductIdSet: Set<string>, productId: unknown) => {
|
||||
const normalizedId = toOptionalIdString(productId)
|
||||
return Boolean(normalizedId && cartProductIdSet.has(normalizedId))
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: withAddedCartProduct supports cart-state.ts by holding or executing the with added cart product page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const withAddedCartProduct = (cartProductIdSet: Set<string>, productId: unknown) => {
|
||||
const next = new Set(cartProductIdSet || [])
|
||||
const normalizedId = toOptionalIdString(productId)
|
||||
if (normalizedId) {
|
||||
next.add(normalizedId)
|
||||
}
|
||||
return next
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { createChunkUploadTask, type ChunkUploadApi } from './chunk-upload'
|
||||
|
||||
const createFile = (size: number) => new File([new Uint8Array(size)], 'large.png', {
|
||||
type: 'image/png',
|
||||
lastModified: 1
|
||||
})
|
||||
|
||||
describe('chunk-upload', () => {
|
||||
it('uploads chunks with the requested concurrency', async () => {
|
||||
const releaseCallbacks: Array<() => void> = []
|
||||
let activeUploads = 0
|
||||
let maxActiveUploads = 0
|
||||
|
||||
const api: ChunkUploadApi<string> = {
|
||||
initUpload: vi.fn().mockResolvedValue({
|
||||
uploadId: 'upload-1',
|
||||
chunkSize: 2,
|
||||
totalChunks: 4,
|
||||
uploadedChunks: []
|
||||
}),
|
||||
uploadChunk: vi.fn((_payload, config) => {
|
||||
activeUploads += 1
|
||||
maxActiveUploads = Math.max(maxActiveUploads, activeUploads)
|
||||
config?.onUploadProgress?.({ loaded: 2, total: 2 } as never)
|
||||
return new Promise(resolve => {
|
||||
releaseCallbacks.push(() => {
|
||||
activeUploads -= 1
|
||||
resolve(true)
|
||||
})
|
||||
})
|
||||
}),
|
||||
completeUpload: vi.fn().mockResolvedValue('done'),
|
||||
cancelUpload: vi.fn()
|
||||
}
|
||||
|
||||
const task = createChunkUploadTask({
|
||||
file: createFile(8),
|
||||
scene: 'test-image',
|
||||
concurrency: 3,
|
||||
api
|
||||
})
|
||||
|
||||
await vi.waitFor(() => expect(maxActiveUploads).toBe(3))
|
||||
while (releaseCallbacks.length) {
|
||||
releaseCallbacks.shift()?.()
|
||||
await Promise.resolve()
|
||||
}
|
||||
|
||||
await expect(task.promise).resolves.toMatchObject({
|
||||
response: 'done',
|
||||
uploadId: 'upload-1'
|
||||
})
|
||||
expect(api.uploadChunk).toHaveBeenCalledTimes(4)
|
||||
expect(api.completeUpload).toHaveBeenCalledWith('upload-1')
|
||||
})
|
||||
|
||||
it('skips already uploaded chunks', async () => {
|
||||
const api: ChunkUploadApi<string> = {
|
||||
initUpload: vi.fn().mockResolvedValue({
|
||||
uploadId: 'upload-2',
|
||||
chunkSize: 2,
|
||||
totalChunks: 3,
|
||||
uploadedChunks: [0, 2]
|
||||
}),
|
||||
uploadChunk: vi.fn().mockResolvedValue(true),
|
||||
completeUpload: vi.fn().mockResolvedValue('done')
|
||||
}
|
||||
|
||||
const task = createChunkUploadTask({
|
||||
file: createFile(6),
|
||||
scene: 'test-image',
|
||||
concurrency: 3,
|
||||
api
|
||||
})
|
||||
|
||||
await expect(task.promise).resolves.toMatchObject({ response: 'done' })
|
||||
expect(api.uploadChunk).toHaveBeenCalledTimes(1)
|
||||
expect(api.uploadChunk).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ chunkIndex: 1 }),
|
||||
expect.any(Object)
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,197 @@
|
||||
import type { AxiosProgressEvent } from 'axios'
|
||||
|
||||
export interface ChunkUploadSession {
|
||||
uploadId: string
|
||||
chunkSize: number
|
||||
totalChunks: number
|
||||
uploadedChunks: number[]
|
||||
}
|
||||
|
||||
export interface ChunkUploadInitRequest {
|
||||
fileName: string
|
||||
fileSize: number
|
||||
contentType: string
|
||||
fileFingerprint: string
|
||||
scene: string
|
||||
}
|
||||
|
||||
export interface ChunkUploadApi<TResponse> {
|
||||
initUpload: (payload: ChunkUploadInitRequest) => Promise<ChunkUploadSession>
|
||||
uploadChunk: (
|
||||
payload: { uploadId: string; chunkIndex: number; totalChunks: number; chunk: Blob },
|
||||
config?: { signal?: AbortSignal; onUploadProgress?: (event: AxiosProgressEvent) => void }
|
||||
) => Promise<unknown>
|
||||
completeUpload: (uploadId: string) => Promise<TResponse>
|
||||
cancelUpload?: (uploadId: string) => Promise<unknown>
|
||||
}
|
||||
|
||||
export interface ChunkUploadOptions<TResponse> {
|
||||
file: File
|
||||
scene: string
|
||||
api: ChunkUploadApi<TResponse>
|
||||
concurrency: number
|
||||
preprocessFile?: (file: File) => Promise<File>
|
||||
onProgress?: (percent: number) => void
|
||||
}
|
||||
|
||||
export interface ChunkUploadResult<TResponse> {
|
||||
response: TResponse
|
||||
uploadId: string
|
||||
processedFile: File
|
||||
}
|
||||
|
||||
export interface ChunkUploadTask<TResponse> {
|
||||
promise: Promise<ChunkUploadResult<TResponse>>
|
||||
cancel: () => void
|
||||
getUploadId: () => string
|
||||
}
|
||||
|
||||
const computeFileFingerprint = async (file: File) => {
|
||||
const fingerprintSeed = `${file.name}|${file.size}|${file.lastModified}|${file.type}`
|
||||
if (!window.crypto?.subtle) {
|
||||
return btoa(unescape(encodeURIComponent(fingerprintSeed)))
|
||||
}
|
||||
const buffer = new TextEncoder().encode(fingerprintSeed)
|
||||
const hashBuffer = await window.crypto.subtle.digest('SHA-256', buffer)
|
||||
const hashArray = Array.from(new Uint8Array(hashBuffer))
|
||||
return hashArray.map(byte => byte.toString(16).padStart(2, '0')).join('')
|
||||
}
|
||||
|
||||
const getChunkSizeByIndex = (fileSize: number, chunkSize: number, chunkIndex: number) => {
|
||||
const start = chunkIndex * chunkSize
|
||||
const end = Math.min(start + chunkSize, fileSize)
|
||||
return Math.max(end - start, 0)
|
||||
}
|
||||
|
||||
const calculateUploadedBytes = (fileSize: number, chunkSize: number, uploadedChunks: number[]) =>
|
||||
uploadedChunks.reduce((total, chunkIndex) => total + getChunkSizeByIndex(fileSize, chunkSize, chunkIndex), 0)
|
||||
|
||||
const normalizeConcurrency = (concurrency: number) => {
|
||||
if (!Number.isFinite(concurrency) || concurrency < 1) {
|
||||
return 1
|
||||
}
|
||||
return Math.floor(concurrency)
|
||||
}
|
||||
|
||||
const createPendingChunkIndexes = (totalChunks: number, uploadedChunkSet: Set<number>) => {
|
||||
const chunkIndexes: number[] = []
|
||||
for (let chunkIndex = 0; chunkIndex < totalChunks; chunkIndex++) {
|
||||
if (!uploadedChunkSet.has(chunkIndex)) {
|
||||
chunkIndexes.push(chunkIndex)
|
||||
}
|
||||
}
|
||||
return chunkIndexes
|
||||
}
|
||||
|
||||
export const createChunkUploadTask = <TResponse>(options: ChunkUploadOptions<TResponse>): ChunkUploadTask<TResponse> => {
|
||||
const abortController = new AbortController()
|
||||
let uploadId = ''
|
||||
let cancelled = false
|
||||
|
||||
const cleanupCancelledSession = async () => {
|
||||
if (uploadId && options.api.cancelUpload) {
|
||||
await options.api.cancelUpload(uploadId).catch(() => undefined)
|
||||
}
|
||||
}
|
||||
|
||||
const promise = (async () => {
|
||||
const processedFile = options.preprocessFile ? await options.preprocessFile(options.file) : options.file
|
||||
const fileFingerprint = await computeFileFingerprint(processedFile)
|
||||
const session = await options.api.initUpload({
|
||||
fileName: processedFile.name,
|
||||
fileSize: processedFile.size,
|
||||
contentType: processedFile.type || 'application/octet-stream',
|
||||
fileFingerprint,
|
||||
scene: options.scene
|
||||
})
|
||||
|
||||
uploadId = session.uploadId
|
||||
if (cancelled) {
|
||||
await cleanupCancelledSession()
|
||||
throw new Error('上传已取消')
|
||||
}
|
||||
|
||||
const uploadedChunkSet = new Set(session.uploadedChunks || [])
|
||||
let uploadedBytes = calculateUploadedBytes(processedFile.size, session.chunkSize, Array.from(uploadedChunkSet))
|
||||
const uploadingChunkBytes = new Map<number, number>()
|
||||
const pendingChunkIndexes = createPendingChunkIndexes(session.totalChunks, uploadedChunkSet)
|
||||
const concurrency = Math.min(normalizeConcurrency(options.concurrency), Math.max(pendingChunkIndexes.length, 1))
|
||||
|
||||
const emitProgress = (limit: number) => {
|
||||
const inFlightBytes = Array.from(uploadingChunkBytes.values()).reduce((total, loaded) => total + loaded, 0)
|
||||
const percent = ((uploadedBytes + inFlightBytes) / Math.max(processedFile.size, 1)) * 100
|
||||
options.onProgress?.(Math.min(percent, limit))
|
||||
}
|
||||
|
||||
options.onProgress?.(Math.min((uploadedBytes / Math.max(processedFile.size, 1)) * 100, 100))
|
||||
|
||||
let nextChunkIndexCursor = 0
|
||||
const uploadNextChunk = async (): Promise<void> => {
|
||||
const chunkIndex = pendingChunkIndexes[nextChunkIndexCursor]
|
||||
nextChunkIndexCursor += 1
|
||||
if (chunkIndex === undefined) {
|
||||
return
|
||||
}
|
||||
if (cancelled) {
|
||||
await cleanupCancelledSession()
|
||||
throw new Error('上传已取消')
|
||||
}
|
||||
|
||||
const start = chunkIndex * session.chunkSize
|
||||
const end = Math.min(start + session.chunkSize, processedFile.size)
|
||||
const chunk = processedFile.slice(start, end)
|
||||
const chunkBytes = end - start
|
||||
|
||||
await options.api.uploadChunk(
|
||||
{
|
||||
uploadId: session.uploadId,
|
||||
chunkIndex,
|
||||
totalChunks: session.totalChunks,
|
||||
chunk
|
||||
},
|
||||
{
|
||||
signal: abortController.signal,
|
||||
onUploadProgress: (event) => {
|
||||
const loaded = Math.min(event.loaded || 0, chunkBytes)
|
||||
uploadingChunkBytes.set(chunkIndex, loaded)
|
||||
emitProgress(99.9)
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
uploadedChunkSet.add(chunkIndex)
|
||||
uploadedBytes += chunkBytes
|
||||
uploadingChunkBytes.delete(chunkIndex)
|
||||
options.onProgress?.(Math.min((uploadedBytes / Math.max(processedFile.size, 1)) * 100, 99.9))
|
||||
|
||||
await uploadNextChunk()
|
||||
}
|
||||
|
||||
await Promise.all(Array.from({ length: concurrency }, () => uploadNextChunk()))
|
||||
|
||||
if (cancelled) {
|
||||
await cleanupCancelledSession()
|
||||
throw new Error('上传已取消')
|
||||
}
|
||||
|
||||
const response = await options.api.completeUpload(session.uploadId)
|
||||
options.onProgress?.(100)
|
||||
return {
|
||||
response,
|
||||
uploadId: session.uploadId,
|
||||
processedFile
|
||||
}
|
||||
})()
|
||||
|
||||
return {
|
||||
promise,
|
||||
cancel: () => {
|
||||
cancelled = true
|
||||
abortController.abort()
|
||||
if (uploadId && options.api.cancelUpload) {
|
||||
void options.api.cancelUpload(uploadId).catch(() => undefined)
|
||||
}
|
||||
},
|
||||
getUploadId: () => uploadId
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { buildRatingStars, normalizeCommentRating } from './comment-review'
|
||||
|
||||
describe('comment review helpers', () => {
|
||||
it('normalizes comment ratings for display and submit', () => {
|
||||
expect(normalizeCommentRating(undefined)).toBe(5)
|
||||
expect(normalizeCommentRating(0)).toBe(1)
|
||||
expect(normalizeCommentRating(6)).toBe(5)
|
||||
expect(normalizeCommentRating('3')).toBe(3)
|
||||
})
|
||||
|
||||
it('builds filled and empty star states from a rating', () => {
|
||||
expect(buildRatingStars(3)).toEqual([true, true, true, false, false])
|
||||
expect(buildRatingStars(5)).toEqual([true, true, true, true, true])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,12 @@
|
||||
export const normalizeCommentRating = (value: unknown, fallback = 5) => {
|
||||
const numeric = Number(value ?? fallback)
|
||||
if (!Number.isFinite(numeric)) {
|
||||
return fallback
|
||||
}
|
||||
return Math.min(5, Math.max(1, Math.round(numeric)))
|
||||
}
|
||||
|
||||
export const buildRatingStars = (rating: unknown) => {
|
||||
const normalized = normalizeCommentRating(rating)
|
||||
return Array.from({ length: 5 }, (_, index) => index < normalized)
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* Purpose: DraftStorageMode supports form-draft.ts by holding or executing the draft storage mode page or API role.
|
||||
* Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export type DraftStorageMode = 'local' | 'session'
|
||||
|
||||
/**
|
||||
* Purpose: DraftRecord supports form-draft.ts by holding or executing the draft record page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface DraftRecord<T> {
|
||||
savedAt: number
|
||||
payload: T
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: getStorage supports form-draft.ts by holding or executing the get storage page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const getStorage = (mode: DraftStorageMode) => (mode === 'session' ? window.sessionStorage : window.localStorage)
|
||||
|
||||
/**
|
||||
* Purpose: buildDraftStorageKey supports form-draft.ts by holding or executing the build draft storage key page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const buildDraftStorageKey = (...parts: Array<string | number | undefined | null>) => {
|
||||
const normalizedParts = parts
|
||||
.filter((part): part is string | number => part !== undefined && part !== null && String(part).trim().length > 0)
|
||||
.map(part => String(part).trim())
|
||||
return `fingertipdesigner:draft:${normalizedParts.join(':')}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: saveDraftRecord supports form-draft.ts by holding or executing the save draft record page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const saveDraftRecord = <T>(key: string, payload: T, mode: DraftStorageMode = 'local') => {
|
||||
const record: DraftRecord<T> = {
|
||||
savedAt: Date.now(),
|
||||
payload
|
||||
}
|
||||
getStorage(mode).setItem(key, JSON.stringify(record))
|
||||
return record
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: loadDraftRecord supports form-draft.ts by holding or executing the load draft record page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const loadDraftRecord = <T>(key: string, mode: DraftStorageMode = 'local') => {
|
||||
const rawValue = getStorage(mode).getItem(key)
|
||||
if (!rawValue) {
|
||||
return null
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(rawValue) as DraftRecord<T>
|
||||
} catch {
|
||||
getStorage(mode).removeItem(key)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: clearDraftRecord supports form-draft.ts by holding or executing the clear draft record page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const clearDraftRecord = (key: string, mode: DraftStorageMode = 'local') => {
|
||||
getStorage(mode).removeItem(key)
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* Purpose: IdType supports id.ts by holding or executing the id type page or API role.
|
||||
* Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export type IdType = string | number
|
||||
|
||||
/**
|
||||
* Purpose: isEmptyId supports id.ts by holding or executing the is empty id page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const isEmptyId = (value: unknown): value is undefined | null | '' => {
|
||||
return value === undefined || value === null || `${value}`.trim() === ''
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: toIdString supports id.ts by holding or executing the to id string page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const toIdString = (value: IdType) => String(value)
|
||||
|
||||
// 前端统一把雪花 ID 视为字符串语义处理,避免任何 Number 转换带来的精度污染。
|
||||
export const toOptionalIdString = (value: unknown) => {
|
||||
if (isEmptyId(value)) {
|
||||
return undefined
|
||||
}
|
||||
return String(value).trim()
|
||||
}
|
||||
|
||||
// 比较 ID 时统一做字符串归一化,兼容接口返回 string / number 两种情况。
|
||||
export const sameId = (left: unknown, right: unknown) => {
|
||||
const leftId = toOptionalIdString(left)
|
||||
const rightId = toOptionalIdString(right)
|
||||
return leftId !== undefined && leftId === rightId
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
/**
|
||||
* Purpose: DEFAULT_MAX_IMAGE_SIZE supports image-upload.ts by holding or executing the default max image size page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const DEFAULT_MAX_IMAGE_SIZE = 5 * 1024 * 1024
|
||||
/**
|
||||
* Purpose: AUTO_COMPRESS_TYPES supports image-upload.ts by holding or executing the auto compress types page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const AUTO_COMPRESS_TYPES = new Set(['image/jpeg', 'image/jpg', 'image/png', 'image/webp'])
|
||||
|
||||
/**
|
||||
* Purpose: inferImageMimeType supports image-upload.ts by holding or executing the infer image mime type page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const inferImageMimeType = (file: File) => {
|
||||
if (file.type) return file.type.toLowerCase()
|
||||
const name = file.name.toLowerCase().split(/[?#]/)[0] || ''
|
||||
if (name.endsWith('.jpg') || name.endsWith('.jpeg')) return 'image/jpeg'
|
||||
if (name.endsWith('.png')) return 'image/png'
|
||||
if (name.endsWith('.webp')) return 'image/webp'
|
||||
if (name.endsWith('.gif')) return 'image/gif'
|
||||
return ''
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: ImageCompressionResult supports image-upload.ts by holding or executing the image compression result page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface ImageCompressionResult {
|
||||
file: File
|
||||
originalSize: number
|
||||
finalSize: number
|
||||
compressed: boolean
|
||||
converted: boolean
|
||||
skippedReason?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: QUALITY_STEPS supports image-upload.ts by holding or executing the quality steps page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const QUALITY_STEPS = [0.92, 0.84, 0.76, 0.68, 0.6, 0.52]
|
||||
/**
|
||||
* Purpose: SCALE_STEPS supports image-upload.ts by holding or executing the scale steps page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const SCALE_STEPS = [1, 0.9, 0.8, 0.7, 0.6, 0.5]
|
||||
|
||||
/**
|
||||
* Purpose: loadImageElement supports image-upload.ts by holding or executing the load image element page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const loadImageElement = (file: File) => {
|
||||
return new Promise<HTMLImageElement>((resolve, reject) => {
|
||||
const image = new Image()
|
||||
const objectUrl = URL.createObjectURL(file)
|
||||
|
||||
image.onload = () => {
|
||||
URL.revokeObjectURL(objectUrl)
|
||||
resolve(image)
|
||||
}
|
||||
|
||||
image.onerror = () => {
|
||||
URL.revokeObjectURL(objectUrl)
|
||||
reject(new Error('图片读取失败'))
|
||||
}
|
||||
|
||||
image.src = objectUrl
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: canvasToBlob supports image-upload.ts by holding or executing the canvas to blob page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const canvasToBlob = (canvas: HTMLCanvasElement, type: string, quality?: number) => {
|
||||
return new Promise<Blob>((resolve, reject) => {
|
||||
canvas.toBlob(
|
||||
(blob) => {
|
||||
if (!blob) {
|
||||
reject(new Error('图片压缩失败'))
|
||||
return
|
||||
}
|
||||
resolve(blob)
|
||||
},
|
||||
type,
|
||||
quality
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: getOutputExtension supports image-upload.ts by holding or executing the get output extension page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const getOutputExtension = (type: string) => {
|
||||
if (type === 'image/png') {
|
||||
return '.png'
|
||||
}
|
||||
if (type === 'image/webp') {
|
||||
return '.webp'
|
||||
}
|
||||
return '.jpg'
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: buildOutputName supports image-upload.ts by holding or executing the build output name page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const buildOutputName = (fileName: string, type: string) => {
|
||||
const extension = getOutputExtension(type)
|
||||
const dotIndex = fileName.lastIndexOf('.')
|
||||
const baseName = dotIndex > -1 ? fileName.slice(0, dotIndex) : fileName
|
||||
return `${baseName}${extension}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: drawImageToCanvas supports image-upload.ts by holding or executing the draw image to canvas page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const drawImageToCanvas = (image: HTMLImageElement, width: number, height: number, mimeType: string) => {
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = width
|
||||
canvas.height = height
|
||||
|
||||
const context = canvas.getContext('2d')
|
||||
if (!context) {
|
||||
throw new Error('无法初始化图片压缩画布')
|
||||
}
|
||||
|
||||
if (mimeType !== 'image/png') {
|
||||
context.fillStyle = '#ffffff'
|
||||
context.fillRect(0, 0, width, height)
|
||||
}
|
||||
|
||||
context.drawImage(image, 0, 0, width, height)
|
||||
return canvas
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: toCompressedFile supports image-upload.ts by holding or executing the to compressed file page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const toCompressedFile = (blob: Blob, sourceFile: File, mimeType: string) => {
|
||||
return new File([blob], buildOutputName(sourceFile.name, mimeType), {
|
||||
type: mimeType,
|
||||
lastModified: sourceFile.lastModified
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: getPreferredMimeTypes supports image-upload.ts by holding or executing the get preferred mime types page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const getPreferredMimeTypes = (file: File) => {
|
||||
if (file.type === 'image/png') {
|
||||
return ['image/png', 'image/jpeg']
|
||||
}
|
||||
if (file.type === 'image/webp') {
|
||||
return ['image/webp', 'image/jpeg']
|
||||
}
|
||||
return ['image/jpeg']
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: formatFileSize supports image-upload.ts by holding or executing the format file size page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const formatFileSize = (bytes: number) => {
|
||||
if (bytes >= 1024 * 1024) {
|
||||
return `${(bytes / 1024 / 1024).toFixed(2)}MB`
|
||||
}
|
||||
return `${(bytes / 1024).toFixed(0)}KB`
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: compressImageIfNeeded supports image-upload.ts by holding or executing the compress image if needed page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const compressImageIfNeeded = async (
|
||||
file: File,
|
||||
maxSize = DEFAULT_MAX_IMAGE_SIZE
|
||||
): Promise<ImageCompressionResult> => {
|
||||
const sourceType = inferImageMimeType(file)
|
||||
if (!sourceType.startsWith('image/')) {
|
||||
return {
|
||||
file,
|
||||
originalSize: file.size,
|
||||
finalSize: file.size,
|
||||
compressed: false,
|
||||
converted: false,
|
||||
skippedReason: '仅支持图片文件上传'
|
||||
}
|
||||
}
|
||||
|
||||
if (file.size <= maxSize) {
|
||||
return {
|
||||
file,
|
||||
originalSize: file.size,
|
||||
finalSize: file.size,
|
||||
compressed: false,
|
||||
converted: false
|
||||
}
|
||||
}
|
||||
|
||||
if (!AUTO_COMPRESS_TYPES.has(sourceType)) {
|
||||
return {
|
||||
file,
|
||||
originalSize: file.size,
|
||||
finalSize: file.size,
|
||||
compressed: false,
|
||||
converted: false,
|
||||
skippedReason: '当前图片格式暂不支持自动压缩,请手动处理后重试'
|
||||
}
|
||||
}
|
||||
|
||||
const image = await loadImageElement(file)
|
||||
const preferredMimeTypes = getPreferredMimeTypes(new File([file], file.name, { type: sourceType || file.type }))
|
||||
let bestBlob: Blob | null = null
|
||||
let bestMimeType = sourceType || file.type
|
||||
|
||||
for (const scale of SCALE_STEPS) {
|
||||
const width = Math.max(1, Math.round(image.naturalWidth * scale))
|
||||
const height = Math.max(1, Math.round(image.naturalHeight * scale))
|
||||
|
||||
for (const mimeType of preferredMimeTypes) {
|
||||
const canvas = drawImageToCanvas(image, width, height, mimeType)
|
||||
const qualitySteps = mimeType === 'image/png' ? [undefined] : QUALITY_STEPS
|
||||
|
||||
for (const quality of qualitySteps) {
|
||||
const blob = await canvasToBlob(canvas, mimeType, quality)
|
||||
|
||||
if (!bestBlob || blob.size < bestBlob.size) {
|
||||
bestBlob = blob
|
||||
bestMimeType = mimeType
|
||||
}
|
||||
|
||||
if (blob.size <= maxSize) {
|
||||
const compressedFile = toCompressedFile(blob, file, mimeType)
|
||||
return {
|
||||
file: compressedFile,
|
||||
originalSize: file.size,
|
||||
finalSize: blob.size,
|
||||
compressed: true,
|
||||
converted: mimeType !== file.type
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!bestBlob) {
|
||||
throw new Error('图片压缩失败')
|
||||
}
|
||||
|
||||
const compressedFile = toCompressedFile(bestBlob, file, bestMimeType)
|
||||
return {
|
||||
file: compressedFile,
|
||||
originalSize: file.size,
|
||||
finalSize: bestBlob.size,
|
||||
compressed: true,
|
||||
converted: bestMimeType !== file.type
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: MAX_IMAGE_UPLOAD_SIZE supports image-upload.ts by holding or executing the max image upload size page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const MAX_IMAGE_UPLOAD_SIZE = DEFAULT_MAX_IMAGE_SIZE
|
||||
@@ -0,0 +1,89 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { resolveOrderReviewFocus } from './order-review-focus'
|
||||
|
||||
const orders = [
|
||||
{
|
||||
id: 10,
|
||||
items: [
|
||||
{ id: 1001, productTitle: '猫眼款' }
|
||||
]
|
||||
},
|
||||
{
|
||||
id: 11,
|
||||
items: [
|
||||
{ id: 1101, productTitle: '法式款' }
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
describe('resolveOrderReviewFocus', () => {
|
||||
it('focuses the exact pending review from message query parameters', () => {
|
||||
const result = resolveOrderReviewFocus({
|
||||
orders,
|
||||
pendingReviews: [{ id: 99, orderId: 10, orderItemId: 1001 }],
|
||||
orderReviews: {},
|
||||
query: { reviewId: 99 }
|
||||
})
|
||||
|
||||
expect(result.status).toBe('pending')
|
||||
expect(result.focusOrderId).toBe('10')
|
||||
expect(result.focusOrderItemId).toBe('1001')
|
||||
expect(result.focusReviewId).toBe('99')
|
||||
})
|
||||
|
||||
it('reports a friendly submitted state when the reminder was already handled', () => {
|
||||
const result = resolveOrderReviewFocus({
|
||||
orders,
|
||||
pendingReviews: [],
|
||||
orderReviews: {
|
||||
10: [{ id: 99, orderId: 10, orderItemId: 1001, status: 1 }]
|
||||
},
|
||||
query: { reviewId: 99 }
|
||||
})
|
||||
|
||||
expect(result.status).toBe('submitted')
|
||||
expect(result.focusOrderId).toBe('10')
|
||||
expect(result.focusOrderItemId).toBe('1001')
|
||||
expect(result.message).toContain('已处理')
|
||||
})
|
||||
|
||||
it('chooses the first pending review for profile pending-review entry', () => {
|
||||
const result = resolveOrderReviewFocus({
|
||||
orders,
|
||||
pendingReviews: [{ id: 88, orderId: 11, orderItemId: 1101 }],
|
||||
orderReviews: {},
|
||||
query: { review: 'pending' }
|
||||
})
|
||||
|
||||
expect(result.status).toBe('pending')
|
||||
expect(result.focusOrderId).toBe('11')
|
||||
expect(result.focusOrderItemId).toBe('1101')
|
||||
expect(result.focusReviewId).toBe('88')
|
||||
})
|
||||
|
||||
it('keeps an order-level focus when only orderId is provided', () => {
|
||||
const result = resolveOrderReviewFocus({
|
||||
orders,
|
||||
pendingReviews: [],
|
||||
orderReviews: {},
|
||||
query: { orderId: 10 }
|
||||
})
|
||||
|
||||
expect(result.status).toBe('order')
|
||||
expect(result.focusOrderId).toBe('10')
|
||||
expect(result.focusOrderItemId).toBe('')
|
||||
})
|
||||
|
||||
it('keeps the order visible when a review id is stale but orderId still exists', () => {
|
||||
const result = resolveOrderReviewFocus({
|
||||
orders,
|
||||
pendingReviews: [],
|
||||
orderReviews: {},
|
||||
query: { orderId: 10, reviewId: 404 }
|
||||
})
|
||||
|
||||
expect(result.status).toBe('missing')
|
||||
expect(result.focusOrderId).toBe('10')
|
||||
expect(result.message).toContain('失效')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,120 @@
|
||||
import type { OrderArtistReviewVO } from '@/api/order'
|
||||
|
||||
type QueryValue = string | number | null | undefined | Array<string | number | null | undefined>
|
||||
|
||||
interface OrderLike {
|
||||
id?: unknown
|
||||
items?: Array<{ id?: unknown }>
|
||||
}
|
||||
|
||||
interface ResolveOrderReviewFocusOptions {
|
||||
orders: OrderLike[]
|
||||
pendingReviews: OrderArtistReviewVO[]
|
||||
orderReviews: Record<string, OrderArtistReviewVO[]>
|
||||
query: Record<string, QueryValue>
|
||||
}
|
||||
|
||||
export interface OrderReviewFocusResult {
|
||||
status: 'none' | 'pending' | 'submitted' | 'missing' | 'order'
|
||||
focusOrderId: string
|
||||
focusOrderItemId: string
|
||||
focusReviewId: string
|
||||
message: string
|
||||
}
|
||||
|
||||
const toText = (value: QueryValue | unknown) => {
|
||||
if (Array.isArray(value)) {
|
||||
return value[0] === undefined || value[0] === null ? '' : String(value[0])
|
||||
}
|
||||
return value === undefined || value === null ? '' : String(value)
|
||||
}
|
||||
|
||||
const sameId = (left: unknown, right: unknown) => {
|
||||
const leftText = toText(left)
|
||||
const rightText = toText(right)
|
||||
return leftText !== '' && leftText === rightText
|
||||
}
|
||||
|
||||
const flattenSubmittedReviews = (orderReviews: Record<string, OrderArtistReviewVO[]>) => {
|
||||
return Object.values(orderReviews).flat().filter(review => Number(review.status) === 1 || Boolean(review.rating))
|
||||
}
|
||||
|
||||
const findOrder = (orders: OrderLike[], orderId: string) => {
|
||||
return orders.find(order => sameId(order.id, orderId))
|
||||
}
|
||||
|
||||
const buildResult = (
|
||||
status: OrderReviewFocusResult['status'],
|
||||
review?: OrderArtistReviewVO,
|
||||
fallbackOrderId = '',
|
||||
message = ''
|
||||
): OrderReviewFocusResult => ({
|
||||
status,
|
||||
focusOrderId: toText(review?.orderId) || fallbackOrderId,
|
||||
focusOrderItemId: toText(review?.orderItemId),
|
||||
focusReviewId: toText(review?.id),
|
||||
message
|
||||
})
|
||||
|
||||
export const resolveOrderReviewFocus = ({
|
||||
orders,
|
||||
pendingReviews,
|
||||
orderReviews,
|
||||
query
|
||||
}: ResolveOrderReviewFocusOptions): OrderReviewFocusResult => {
|
||||
const reviewId = toText(query.reviewId)
|
||||
const orderId = toText(query.orderId)
|
||||
const orderItemId = toText(query.orderItemId)
|
||||
const reviewMode = toText(query.review)
|
||||
const submittedReviews = flattenSubmittedReviews(orderReviews)
|
||||
|
||||
if (reviewId) {
|
||||
const pending = pendingReviews.find(review => sameId(review.id, reviewId))
|
||||
if (pending) {
|
||||
return buildResult('pending', pending, '', '已为你定位到待评价订单。')
|
||||
}
|
||||
const submitted = submittedReviews.find(review => sameId(review.id, reviewId))
|
||||
if (submitted) {
|
||||
return buildResult('submitted', submitted, '', '这条评价提醒已处理,可查看已评价内容。')
|
||||
}
|
||||
return {
|
||||
status: 'missing',
|
||||
focusOrderId: findOrder(orders, orderId) ? orderId : '',
|
||||
focusOrderItemId: orderItemId,
|
||||
focusReviewId: reviewId,
|
||||
message: '这条评价提醒已失效,可在订单页查看最新状态。'
|
||||
}
|
||||
}
|
||||
|
||||
if (reviewMode === 'pending') {
|
||||
const firstPending = pendingReviews[0]
|
||||
if (firstPending) {
|
||||
return buildResult('pending', firstPending, '', '已为你定位到待评价订单。')
|
||||
}
|
||||
return {
|
||||
status: 'missing',
|
||||
focusOrderId: '',
|
||||
focusOrderItemId: '',
|
||||
focusReviewId: '',
|
||||
message: '暂无待评价订单。'
|
||||
}
|
||||
}
|
||||
|
||||
if (orderId && findOrder(orders, orderId)) {
|
||||
return {
|
||||
status: 'order',
|
||||
focusOrderId: orderId,
|
||||
focusOrderItemId: orderItemId,
|
||||
focusReviewId: '',
|
||||
message: ''
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
status: 'none',
|
||||
focusOrderId: '',
|
||||
focusOrderItemId: '',
|
||||
focusReviewId: '',
|
||||
message: ''
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const publicGetSignedUrl = vi.fn()
|
||||
|
||||
vi.mock('@/api/file', () => ({
|
||||
fileApi: {
|
||||
getSignedUrl: publicGetSignedUrl
|
||||
}
|
||||
}))
|
||||
|
||||
|
||||
describe('public-image-assets', () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules()
|
||||
vi.clearAllMocks()
|
||||
publicGetSignedUrl.mockResolvedValue({ data: 'img.yunail.art/signed.jpg?token=1' })
|
||||
})
|
||||
|
||||
it('prefers direct image urls over signing file ids', async () => {
|
||||
const { resolvePublicImageUrls } = await import('./public-image-assets')
|
||||
|
||||
await expect(resolvePublicImageUrls({
|
||||
imageUrls: ['http://img.yunail.art/direct.jpg'],
|
||||
imageFileIds: '42'
|
||||
}, 'fallback.png')).resolves.toEqual(['http://img.yunail.art/direct.jpg'])
|
||||
expect(publicGetSignedUrl).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('normalizes direct image urls without scheme', async () => {
|
||||
const { resolvePublicImageUrls } = await import('./public-image-assets')
|
||||
|
||||
await expect(resolvePublicImageUrls({
|
||||
imageUrls: ['img.yunail.art/direct.jpg?token=1']
|
||||
}, 'fallback.png')).resolves.toEqual(['http://img.yunail.art/direct.jpg?token=1'])
|
||||
})
|
||||
|
||||
it('signs public file ids when direct urls are missing', async () => {
|
||||
const { resolvePublicImageUrls, resolvePublicImageUrlsSync } = await import('./public-image-assets')
|
||||
|
||||
expect(resolvePublicImageUrlsSync({ imageFileIds: '42' }, 'fallback.png')).toEqual(['fallback.png'])
|
||||
await expect(resolvePublicImageUrls({ imageFileIds: '42' }, 'fallback.png')).resolves.toEqual([
|
||||
'http://img.yunail.art/signed.jpg?token=1'
|
||||
])
|
||||
expect(publicGetSignedUrl).toHaveBeenCalledWith('42')
|
||||
})
|
||||
|
||||
it('extracts legacy file ids from old file urls', async () => {
|
||||
const { getDirectPublicImageUrls, getPublicImageFileIds } = await import('./public-image-assets')
|
||||
|
||||
const record = {
|
||||
imageUrl: '/api/file/get/325517232303947776',
|
||||
imageFileIds: '325517232303947776,325517220106911744'
|
||||
}
|
||||
|
||||
expect(getDirectPublicImageUrls(record)).toEqual([])
|
||||
expect(getPublicImageFileIds(record)).toEqual(['325517232303947776', '325517220106911744'])
|
||||
})
|
||||
|
||||
it('uses fallback when no image source is available', async () => {
|
||||
const { resolvePublicImageUrls } = await import('./public-image-assets')
|
||||
|
||||
await expect(resolvePublicImageUrls({}, 'fallback.png')).resolves.toEqual(['fallback.png'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,97 @@
|
||||
import { DEFAULT_PRODUCT_IMAGE } from '@/constants'
|
||||
import type { IdType } from '@/utils/id'
|
||||
import {
|
||||
extractLegacyFileId,
|
||||
getCachedSignedImageUrl,
|
||||
getCachedSignedImageUrlSync,
|
||||
parseImageFileIds,
|
||||
refreshCachedSignedImageUrl
|
||||
} from '@/utils/signed-image-cache'
|
||||
|
||||
export interface PublicImageRecord {
|
||||
imageUrls?: string[] | string | null
|
||||
imageFileIds?: string[] | string | null
|
||||
coverImageUrl?: string | null
|
||||
coverImageUrls?: string[] | string | null
|
||||
coverImageFileId?: string[] | string | null
|
||||
imageUrl?: string | null
|
||||
}
|
||||
|
||||
const normalizePublicUrl = (value: unknown): string => {
|
||||
const source = String(value || '').replace(/[`]/g, '').trim()
|
||||
if (!source) return ''
|
||||
if (/^\/?api\/file\/get\/\d+/i.test(source)) return ''
|
||||
if (/^(https?:)?\/\//i.test(source) || /^(data|blob):/i.test(source) || source.startsWith('/')) {
|
||||
return source.startsWith('//') ? `http:${source}` : source
|
||||
}
|
||||
if (source.includes('/') || /\.(jpg|jpeg|png|gif|webp|bmp|svg)(\?|#|$)/i.test(source)) {
|
||||
return `http://${source}`
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
const normalizeUrlList = (value: unknown): string[] => {
|
||||
const rawValues = Array.isArray(value) ? value : String(value || '').split(',')
|
||||
return Array.from(new Set(rawValues.map(normalizePublicUrl).filter(Boolean)))
|
||||
}
|
||||
|
||||
export const getPublicImageFileIds = (record: PublicImageRecord): string[] => {
|
||||
const rawFileIds = [
|
||||
...(Array.isArray(record.coverImageFileId) ? record.coverImageFileId : parseImageFileIds(String(record.coverImageFileId || ''))),
|
||||
...(Array.isArray(record.imageFileIds) ? record.imageFileIds : parseImageFileIds(String(record.imageFileIds || ''))),
|
||||
extractLegacyFileId(record.coverImageUrl),
|
||||
extractLegacyFileId(record.imageUrl)
|
||||
]
|
||||
return Array.from(new Set(rawFileIds.map(id => String(id || '').trim()).filter(Boolean)))
|
||||
}
|
||||
|
||||
export const getDirectPublicImageUrls = (record: PublicImageRecord): string[] => {
|
||||
return Array.from(new Set([
|
||||
...normalizeUrlList(record.coverImageUrls),
|
||||
...normalizeUrlList(record.coverImageUrl),
|
||||
...normalizeUrlList(record.imageUrls),
|
||||
...normalizeUrlList(record.imageUrl)
|
||||
]))
|
||||
}
|
||||
|
||||
export const resolvePublicImageUrlsSync = (
|
||||
record: PublicImageRecord,
|
||||
fallback = DEFAULT_PRODUCT_IMAGE
|
||||
): string[] => {
|
||||
const directUrls = getDirectPublicImageUrls(record)
|
||||
if (directUrls.length) return directUrls
|
||||
|
||||
const cachedUrls = getPublicImageFileIds(record)
|
||||
.map(fileId => getCachedSignedImageUrlSync(fileId, 'public'))
|
||||
.filter(Boolean)
|
||||
if (cachedUrls.length) return cachedUrls
|
||||
|
||||
return fallback ? [fallback] : []
|
||||
}
|
||||
|
||||
export const resolvePublicImageUrls = async (
|
||||
record: PublicImageRecord,
|
||||
fallback = DEFAULT_PRODUCT_IMAGE
|
||||
): Promise<string[]> => {
|
||||
const directUrls = getDirectPublicImageUrls(record)
|
||||
if (directUrls.length) return directUrls
|
||||
|
||||
const signedUrls = await Promise.all(getPublicImageFileIds(record).map(fileId => getCachedSignedImageUrl(fileId, '', 'public')))
|
||||
const usableUrls = signedUrls.filter(Boolean)
|
||||
if (usableUrls.length) return usableUrls
|
||||
|
||||
return fallback ? [fallback] : []
|
||||
}
|
||||
|
||||
export const resolvePublicImageUrl = async (
|
||||
record: PublicImageRecord,
|
||||
fallback = DEFAULT_PRODUCT_IMAGE
|
||||
): Promise<string> => {
|
||||
const urls = await resolvePublicImageUrls(record, fallback)
|
||||
return urls[0] || fallback
|
||||
}
|
||||
|
||||
export const refreshPublicImageUrl = async (
|
||||
fileId: IdType | null | undefined,
|
||||
fallback = DEFAULT_PRODUCT_IMAGE
|
||||
): Promise<string> => refreshCachedSignedImageUrl(fileId, fallback, 'public')
|
||||
@@ -0,0 +1,25 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { buildRecoveryActions, getRecoveryMessage, recoveryRouteFor } from './recovery'
|
||||
|
||||
describe('recovery utils', () => {
|
||||
it('normalizes error messages with fallback text', () => {
|
||||
expect(getRecoveryMessage(new Error('网络开小差了'), '请求失败')).toBe('网络开小差了')
|
||||
expect(getRecoveryMessage('', '请求失败')).toBe('请求失败')
|
||||
})
|
||||
|
||||
it('adds default routes and primary action state', () => {
|
||||
const actions = buildRecoveryActions([
|
||||
{ key: 'retry', text: '重试' },
|
||||
{ key: 'orders', text: '查看订单' },
|
||||
{ key: 'cart', text: '返回购物车' }
|
||||
])
|
||||
const retryAction = actions[0]
|
||||
const ordersAction = actions[1]
|
||||
const cartAction = actions[2]
|
||||
|
||||
expect(retryAction?.primary).toBe(true)
|
||||
expect(ordersAction?.route).toBe('/orders')
|
||||
expect(cartAction?.route).toBe('/cart')
|
||||
expect(recoveryRouteFor('products')).toBe('/products')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,43 @@
|
||||
export type RecoveryActionKey = 'retry' | 'orders' | 'cart' | 'products' | 'profile' | 'contact'
|
||||
|
||||
export interface RecoveryAction {
|
||||
key: RecoveryActionKey
|
||||
text: string
|
||||
route?: string
|
||||
primary?: boolean
|
||||
}
|
||||
|
||||
const DEFAULT_ROUTES: Record<string, string> = {
|
||||
orders: '/orders',
|
||||
cart: '/cart',
|
||||
products: '/products',
|
||||
profile: '/profile'
|
||||
}
|
||||
|
||||
export const getRecoveryMessage = (error: unknown, fallbackMessage: string): string => {
|
||||
if (error instanceof Error && error.message.trim()) {
|
||||
return error.message.trim()
|
||||
}
|
||||
if (typeof error === 'string' && error.trim()) {
|
||||
return error.trim()
|
||||
}
|
||||
if (error && typeof error === 'object' && 'message' in error) {
|
||||
const message = String((error as { message?: unknown }).message || '').trim()
|
||||
if (message) {
|
||||
return message
|
||||
}
|
||||
}
|
||||
return fallbackMessage
|
||||
}
|
||||
|
||||
export const recoveryRouteFor = (key: RecoveryActionKey): string => DEFAULT_ROUTES[key] || ''
|
||||
|
||||
export const buildRecoveryActions = (actions: RecoveryAction[]): RecoveryAction[] => (
|
||||
actions
|
||||
.filter(action => action.key && action.text)
|
||||
.map((action, index) => ({
|
||||
...action,
|
||||
route: action.route || recoveryRouteFor(action.key),
|
||||
primary: action.primary ?? index === 0
|
||||
}))
|
||||
)
|
||||
@@ -0,0 +1,51 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import type { InternalAxiosRequestConfig } from 'axios'
|
||||
import { createHash, createHmac } from 'node:crypto'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { attachRequestSignature } from './request-signature'
|
||||
|
||||
describe('request signature', () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.unstubAllGlobals()
|
||||
localStorage.clear()
|
||||
})
|
||||
|
||||
it('falls back when Web Crypto subtle digest is unavailable', async () => {
|
||||
vi.spyOn(Date, 'now').mockReturnValue(1700000000000)
|
||||
vi.stubGlobal('crypto', {
|
||||
randomUUID: () => 'fallback-id'
|
||||
})
|
||||
|
||||
const config = {
|
||||
method: 'post',
|
||||
baseURL: '/api',
|
||||
url: '/order/checkout-preview',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
data: {
|
||||
items: []
|
||||
}
|
||||
} as unknown as InternalAxiosRequestConfig
|
||||
|
||||
await attachRequestSignature(config, 'access-token')
|
||||
|
||||
const headers = config.headers as Record<string, string>
|
||||
const payloadHash = createHash('sha256').update(JSON.stringify({ items: [] })).digest('hex')
|
||||
const canonical = [
|
||||
'POST',
|
||||
'/order/checkout-preview',
|
||||
'1700000000000',
|
||||
'1700000000000-fallback-id',
|
||||
payloadHash
|
||||
].join('\n')
|
||||
const expectedSignature = createHmac('sha256', 'access-token').update(canonical).digest('hex')
|
||||
|
||||
expect(headers['X-Timestamp']).toBe('1700000000000')
|
||||
expect(headers['X-Nonce']).toBe('1700000000000-fallback-id')
|
||||
expect(headers['X-Sign-Version']).toBe('v1')
|
||||
expect(headers['X-Signature']).toBe(expectedSignature)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,462 @@
|
||||
import type { InternalAxiosRequestConfig } from 'axios'
|
||||
|
||||
/**
|
||||
* Purpose: HEADER_TIMESTAMP supports request-signature.ts by holding or executing the header timestamp page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const HEADER_TIMESTAMP = 'X-Timestamp'
|
||||
/**
|
||||
* Purpose: HEADER_NONCE supports request-signature.ts by holding or executing the header nonce page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const HEADER_NONCE = 'X-Nonce'
|
||||
/**
|
||||
* Purpose: HEADER_SIGNATURE supports request-signature.ts by holding or executing the header signature page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const HEADER_SIGNATURE = 'X-Signature'
|
||||
/**
|
||||
* Purpose: HEADER_SIGNATURE_VERSION supports request-signature.ts by holding or executing the header signature version page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const HEADER_SIGNATURE_VERSION = 'X-Sign-Version'
|
||||
/**
|
||||
* Purpose: DEVICE_ID_HEADER supports request-signature.ts by holding or executing the device id header page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const DEVICE_ID_HEADER = 'X-Device-Id'
|
||||
/**
|
||||
* Purpose: DEVICE_ID_STORAGE_KEY supports request-signature.ts by holding or executing the device id storage key page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const DEVICE_ID_STORAGE_KEY = 'fingertipdesigner-device-id'
|
||||
/**
|
||||
* Purpose: SIGNATURE_VERSION supports request-signature.ts by holding or executing the signature version page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const SIGNATURE_VERSION = 'v1'
|
||||
|
||||
/**
|
||||
* Purpose: HeaderContainer supports request-signature.ts by holding or executing the header container page or API role.
|
||||
* Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
type HeaderContainer = Record<string, unknown> & {
|
||||
set?: (name: string, value: string) => void
|
||||
get?: (name: string) => unknown
|
||||
}
|
||||
|
||||
const SHA256_K = new Uint32Array([
|
||||
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
|
||||
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
||||
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
||||
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
|
||||
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
||||
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
||||
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
||||
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
|
||||
])
|
||||
|
||||
/**
|
||||
* Purpose: RequestSignatureOptions supports request-signature.ts by holding or executing the request signature options page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
interface RequestSignatureOptions {
|
||||
authFree?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: isSafeMethod supports request-signature.ts by holding or executing the is safe method page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function isSafeMethod(method?: string) {
|
||||
return ['GET', 'HEAD', 'OPTIONS'].includes(String(method || 'GET').toUpperCase())
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: toHex supports request-signature.ts by holding or executing the to hex page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function toHex(bytes: ArrayBuffer | Uint8Array) {
|
||||
const view = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)
|
||||
return Array.from(view)
|
||||
.map(byte => byte.toString(16).padStart(2, '0'))
|
||||
.join('')
|
||||
}
|
||||
|
||||
function encodeUtf8(text: string) {
|
||||
return new TextEncoder().encode(text)
|
||||
}
|
||||
|
||||
function rightRotate(value: number, bits: number) {
|
||||
return (value >>> bits) | (value << (32 - bits))
|
||||
}
|
||||
|
||||
function concatBytes(left: Uint8Array, right: Uint8Array) {
|
||||
const result = new Uint8Array(left.length + right.length)
|
||||
result.set(left, 0)
|
||||
result.set(right, left.length)
|
||||
return result
|
||||
}
|
||||
|
||||
function sha256Bytes(input: Uint8Array) {
|
||||
const paddedLength = Math.ceil((input.length + 9) / 64) * 64
|
||||
const padded = new Uint8Array(paddedLength)
|
||||
padded.set(input)
|
||||
padded[input.length] = 0x80
|
||||
|
||||
const bitLength = input.length * 8
|
||||
const view = new DataView(padded.buffer)
|
||||
view.setUint32(paddedLength - 8, Math.floor(bitLength / 0x100000000), false)
|
||||
view.setUint32(paddedLength - 4, bitLength >>> 0, false)
|
||||
|
||||
let h0 = 0x6a09e667
|
||||
let h1 = 0xbb67ae85
|
||||
let h2 = 0x3c6ef372
|
||||
let h3 = 0xa54ff53a
|
||||
let h4 = 0x510e527f
|
||||
let h5 = 0x9b05688c
|
||||
let h6 = 0x1f83d9ab
|
||||
let h7 = 0x5be0cd19
|
||||
const words = new Uint32Array(64)
|
||||
|
||||
for (let offset = 0; offset < paddedLength; offset += 64) {
|
||||
for (let index = 0; index < 16; index++) {
|
||||
words[index] = view.getUint32(offset + index * 4, false)
|
||||
}
|
||||
for (let index = 16; index < 64; index++) {
|
||||
const word15 = words[index - 15]!
|
||||
const word2 = words[index - 2]!
|
||||
const s0 = rightRotate(word15, 7) ^ rightRotate(word15, 18) ^ (word15 >>> 3)
|
||||
const s1 = rightRotate(word2, 17) ^ rightRotate(word2, 19) ^ (word2 >>> 10)
|
||||
words[index] = (words[index - 16]! + s0 + words[index - 7]! + s1) >>> 0
|
||||
}
|
||||
|
||||
let a = h0
|
||||
let b = h1
|
||||
let c = h2
|
||||
let d = h3
|
||||
let e = h4
|
||||
let f = h5
|
||||
let g = h6
|
||||
let h = h7
|
||||
|
||||
for (let index = 0; index < 64; index++) {
|
||||
const s1 = rightRotate(e, 6) ^ rightRotate(e, 11) ^ rightRotate(e, 25)
|
||||
const ch = (e & f) ^ (~e & g)
|
||||
const temp1 = (h + s1 + ch + SHA256_K[index]! + words[index]!) >>> 0
|
||||
const s0 = rightRotate(a, 2) ^ rightRotate(a, 13) ^ rightRotate(a, 22)
|
||||
const maj = (a & b) ^ (a & c) ^ (b & c)
|
||||
const temp2 = (s0 + maj) >>> 0
|
||||
h = g
|
||||
g = f
|
||||
f = e
|
||||
e = (d + temp1) >>> 0
|
||||
d = c
|
||||
c = b
|
||||
b = a
|
||||
a = (temp1 + temp2) >>> 0
|
||||
}
|
||||
|
||||
h0 = (h0 + a) >>> 0
|
||||
h1 = (h1 + b) >>> 0
|
||||
h2 = (h2 + c) >>> 0
|
||||
h3 = (h3 + d) >>> 0
|
||||
h4 = (h4 + e) >>> 0
|
||||
h5 = (h5 + f) >>> 0
|
||||
h6 = (h6 + g) >>> 0
|
||||
h7 = (h7 + h) >>> 0
|
||||
}
|
||||
|
||||
const output = new Uint8Array(32)
|
||||
const outputView = new DataView(output.buffer)
|
||||
;[h0, h1, h2, h3, h4, h5, h6, h7].forEach((value, index) => {
|
||||
outputView.setUint32(index * 4, value, false)
|
||||
})
|
||||
return output
|
||||
}
|
||||
|
||||
function hmacSha256Bytes(secret: string, message: string) {
|
||||
const blockSize = 64
|
||||
let key = encodeUtf8(secret)
|
||||
if (key.length > blockSize) {
|
||||
key = sha256Bytes(key)
|
||||
}
|
||||
|
||||
const paddedKey = new Uint8Array(blockSize)
|
||||
paddedKey.set(key)
|
||||
const outer = new Uint8Array(blockSize)
|
||||
const inner = new Uint8Array(blockSize)
|
||||
for (let index = 0; index < blockSize; index++) {
|
||||
outer[index] = paddedKey[index]! ^ 0x5c
|
||||
inner[index] = paddedKey[index]! ^ 0x36
|
||||
}
|
||||
return sha256Bytes(concatBytes(outer, sha256Bytes(concatBytes(inner, encodeUtf8(message)))))
|
||||
}
|
||||
|
||||
function getSubtleCrypto() {
|
||||
return globalThis.crypto?.subtle
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: sha256Hex supports request-signature.ts by holding or executing the sha256 hex page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
async function sha256Hex(text: string) {
|
||||
const subtle = getSubtleCrypto()
|
||||
if (!subtle) {
|
||||
return toHex(sha256Bytes(encodeUtf8(text)))
|
||||
}
|
||||
const digest = await subtle.digest('SHA-256', encodeUtf8(text))
|
||||
return toHex(digest)
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: hmacSha256Hex supports request-signature.ts by holding or executing the hmac sha256 hex page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
async function hmacSha256Hex(secret: string, message: string) {
|
||||
const subtle = getSubtleCrypto()
|
||||
if (!subtle) {
|
||||
return toHex(hmacSha256Bytes(secret, message))
|
||||
}
|
||||
const key = await subtle.importKey(
|
||||
'raw',
|
||||
encodeUtf8(secret),
|
||||
{ name: 'HMAC', hash: 'SHA-256' },
|
||||
false,
|
||||
['sign']
|
||||
)
|
||||
const signature = await subtle.sign('HMAC', key, encodeUtf8(message))
|
||||
return toHex(signature)
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: randomNonce supports request-signature.ts by holding or executing the random nonce page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function randomNonce() {
|
||||
if (typeof globalThis.crypto?.randomUUID === 'function') {
|
||||
return `${Date.now()}-${globalThis.crypto.randomUUID()}`
|
||||
}
|
||||
return `${Date.now()}-${Math.random().toString(36).slice(2, 12)}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: getDeviceId supports request-signature.ts by holding or executing the get device id page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export function getDeviceId() {
|
||||
try {
|
||||
const stored = localStorage.getItem(DEVICE_ID_STORAGE_KEY)
|
||||
if (stored) {
|
||||
return stored
|
||||
}
|
||||
const next = `web-${randomNonce()}`
|
||||
localStorage.setItem(DEVICE_ID_STORAGE_KEY, next)
|
||||
return next
|
||||
} catch {
|
||||
return `web-${randomNonce()}`
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: setHeader supports request-signature.ts by holding or executing the set header page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function setHeader(config: InternalAxiosRequestConfig, name: string, value: string) {
|
||||
const headers = config.headers as HeaderContainer | undefined
|
||||
if (headers && typeof headers.set === 'function') {
|
||||
headers.set(name, value)
|
||||
return
|
||||
}
|
||||
config.headers = {
|
||||
...(headers || {}),
|
||||
[name]: value
|
||||
} as InternalAxiosRequestConfig['headers']
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: getHeader supports request-signature.ts by holding or executing the get header page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function getHeader(config: InternalAxiosRequestConfig, name: string) {
|
||||
const headers = config.headers as HeaderContainer | undefined
|
||||
if (!headers) {
|
||||
return ''
|
||||
}
|
||||
if (typeof headers.get === 'function') {
|
||||
const value = headers.get(name)
|
||||
if (value !== undefined && value !== null) {
|
||||
return String(value)
|
||||
}
|
||||
}
|
||||
return String(headers[name] || headers[name.toLowerCase()] || '')
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: extractPath supports request-signature.ts by holding or executing the extract path page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function extractPath(value?: string) {
|
||||
if (!value) {
|
||||
return ''
|
||||
}
|
||||
try {
|
||||
return new URL(value, window.location.origin).pathname
|
||||
} catch {
|
||||
return value.split('?')[0] || ''
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: joinAxiosPath supports request-signature.ts by holding or executing the join axios path page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function joinAxiosPath(baseUrl?: string, requestUrl?: string) {
|
||||
if (requestUrl && /^[a-z][a-z\d+\-.]*:\/\//i.test(requestUrl)) {
|
||||
return extractPath(requestUrl)
|
||||
}
|
||||
|
||||
const basePath = extractPath(baseUrl).replace(/^\/+|\/+$/g, '')
|
||||
const requestPath = extractPath(requestUrl).replace(/^\/+|\/+$/g, '')
|
||||
const joined = [basePath, requestPath].filter(Boolean).join('/')
|
||||
return joined ? `/${joined}` : '/'
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: toBackendRequestPath supports request-signature.ts by holding or executing the to backend request path page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function toBackendRequestPath(baseUrl?: string, requestUrl?: string) {
|
||||
const path = joinAxiosPath(baseUrl, requestUrl)
|
||||
if (path === '/api') {
|
||||
return '/'
|
||||
}
|
||||
if (path.startsWith('/api/')) {
|
||||
return `/${path.slice('/api/'.length)}`
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: appendParam supports request-signature.ts by holding or executing the append param page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function appendParam(target: Record<string, unknown[]>, key: string, value: unknown) {
|
||||
if (value === undefined || value === null || value === '') {
|
||||
return
|
||||
}
|
||||
if (!target[key]) {
|
||||
target[key] = []
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach(item => appendParam(target, key, item))
|
||||
return
|
||||
}
|
||||
target[key].push(value)
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: collectParams supports request-signature.ts by holding or executing the collect params page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function collectParams(source: unknown, target: Record<string, unknown[]>) {
|
||||
if (!source) {
|
||||
return
|
||||
}
|
||||
if (source instanceof URLSearchParams) {
|
||||
source.forEach((value, key) => appendParam(target, key, value))
|
||||
return
|
||||
}
|
||||
if (source instanceof FormData) {
|
||||
source.forEach((value, key) => {
|
||||
if (!(value instanceof Blob)) {
|
||||
appendParam(target, key, value)
|
||||
}
|
||||
})
|
||||
return
|
||||
}
|
||||
if (typeof source === 'object') {
|
||||
Object.entries(source as Record<string, unknown>).forEach(([key, value]) => appendParam(target, key, value))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: buildCanonicalParams supports request-signature.ts by holding or executing the build canonical params page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function buildCanonicalParams(...sources: unknown[]) {
|
||||
const params: Record<string, unknown[]> = {}
|
||||
sources.forEach(source => collectParams(source, params))
|
||||
return Object.keys(params)
|
||||
.sort()
|
||||
.map(key => {
|
||||
const normalized = params[key]
|
||||
?.map(value => String(value))
|
||||
.sort()
|
||||
.join(',') || ''
|
||||
return `${key}=${normalized}`
|
||||
})
|
||||
.join('&')
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: buildJsonPayload supports request-signature.ts by holding or executing the build json payload page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function buildJsonPayload(data: unknown) {
|
||||
if (data === undefined || data === null || data === '') {
|
||||
return ''
|
||||
}
|
||||
if (typeof data === 'string') {
|
||||
return data
|
||||
}
|
||||
return JSON.stringify(data)
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: resolvePayload supports request-signature.ts by holding or executing the resolve payload page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function resolvePayload(config: InternalAxiosRequestConfig) {
|
||||
const contentType = getHeader(config, 'Content-Type').toLowerCase()
|
||||
const jsonPayload = contentType.includes('application/json') ? buildJsonPayload(config.data) : ''
|
||||
if (jsonPayload) {
|
||||
return jsonPayload
|
||||
}
|
||||
return buildCanonicalParams(config.params, config.data)
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: attachRequestSignature supports request-signature.ts by holding or executing the attach request signature page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export async function attachRequestSignature(
|
||||
config: InternalAxiosRequestConfig,
|
||||
accessToken?: string | null,
|
||||
options: RequestSignatureOptions = {}
|
||||
) {
|
||||
setHeader(config, DEVICE_ID_HEADER, getDeviceId())
|
||||
|
||||
const method = String(config.method || 'GET').toUpperCase()
|
||||
if (!accessToken || options.authFree || isSafeMethod(method)) {
|
||||
return config
|
||||
}
|
||||
|
||||
const timestamp = String(Date.now())
|
||||
const nonce = randomNonce()
|
||||
const payloadHash = await sha256Hex(resolvePayload(config))
|
||||
const canonical = [
|
||||
method,
|
||||
toBackendRequestPath(config.baseURL, config.url),
|
||||
timestamp,
|
||||
nonce,
|
||||
payloadHash
|
||||
].join('\n')
|
||||
|
||||
setHeader(config, HEADER_TIMESTAMP, timestamp)
|
||||
setHeader(config, HEADER_NONCE, nonce)
|
||||
setHeader(config, HEADER_SIGNATURE, await hmacSha256Hex(accessToken, canonical))
|
||||
setHeader(config, HEADER_SIGNATURE_VERSION, SIGNATURE_VERSION)
|
||||
return config
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { extractRichText, renderRichContent } from './rich-content'
|
||||
|
||||
describe('rich content helpers', () => {
|
||||
it('renders markdown into html', () => {
|
||||
const html = renderRichContent('# 标题\n\n- 甲\n- 乙\n\n**加粗** [链接](https://example.com)')
|
||||
|
||||
expect(html).toContain('<h1>标题</h1>')
|
||||
expect(html).toContain('<ul>')
|
||||
expect(html).toContain('<strong>加粗</strong>')
|
||||
expect(html).toContain('<a href="https://example.com"')
|
||||
})
|
||||
|
||||
it('keeps safe html and strips scripts', () => {
|
||||
const html = renderRichContent('<p>hello <strong>world</strong></p><script>alert(1)</script>')
|
||||
|
||||
expect(html).toBe('<p>hello <strong>world</strong></p>')
|
||||
})
|
||||
|
||||
it('extracts plain text from rich content', () => {
|
||||
expect(extractRichText('<p>Hello <strong>world</strong></p>')).toBe('Hello world')
|
||||
expect(extractRichText('## 标题\n\n内容')).toBe('标题 内容')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,272 @@
|
||||
const HTML_TAG_PATTERN = /<\/?[a-z][\s\S]*>/i
|
||||
const DANGEROUS_TAGS = new Set(['script', 'style', 'iframe', 'object', 'embed', 'form', 'input', 'button', 'textarea', 'select', 'svg', 'math'])
|
||||
const ALLOWED_TAGS = new Set([
|
||||
'a',
|
||||
'blockquote',
|
||||
'br',
|
||||
'code',
|
||||
'del',
|
||||
'div',
|
||||
'em',
|
||||
'h1',
|
||||
'h2',
|
||||
'h3',
|
||||
'h4',
|
||||
'h5',
|
||||
'h6',
|
||||
'hr',
|
||||
'img',
|
||||
'li',
|
||||
'ol',
|
||||
'p',
|
||||
'pre',
|
||||
'span',
|
||||
'strong',
|
||||
'table',
|
||||
'tbody',
|
||||
'td',
|
||||
'th',
|
||||
'thead',
|
||||
'tr',
|
||||
'ul'
|
||||
])
|
||||
const GLOBAL_ATTRS = new Set(['class', 'title'])
|
||||
const TAG_ATTRS: Record<string, Set<string>> = {
|
||||
a: new Set(['href', 'target', 'rel', 'title']),
|
||||
img: new Set(['src', 'alt', 'title']),
|
||||
td: new Set(['colspan', 'rowspan']),
|
||||
th: new Set(['colspan', 'rowspan'])
|
||||
}
|
||||
|
||||
const escapeHtml = (value: string) => value
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''')
|
||||
|
||||
const escapeAttr = (value: string) => escapeHtml(value).replace(/`/g, '`')
|
||||
|
||||
const isSafeUrl = (value: string) => {
|
||||
const normalized = value.trim().replace(/[\u0000-\u001F\u007F\s]+/g, '')
|
||||
if (!normalized) return false
|
||||
if (normalized.startsWith('#')) return true
|
||||
if (normalized.startsWith('/') && !normalized.startsWith('//')) return true
|
||||
if (/^(https?:|mailto:|tel:)/i.test(normalized)) return true
|
||||
return /^data:image\/(?:png|jpe?g|gif|webp);base64,/i.test(normalized)
|
||||
}
|
||||
|
||||
const isAllowedAttr = (tagName: string, attrName: string) => {
|
||||
if (attrName.startsWith('on')) return false
|
||||
return GLOBAL_ATTRS.has(attrName) || TAG_ATTRS[tagName]?.has(attrName)
|
||||
}
|
||||
|
||||
const sanitizeFallback = (html: string) => html
|
||||
.replace(/<\s*(script|style|iframe|object|embed|svg|math)[^>]*>[\s\S]*?<\s*\/\s*\1\s*>/gi, '')
|
||||
.replace(/\s+on[a-z]+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi, '')
|
||||
.replace(/\s+(href|src)\s*=\s*(["'])\s*javascript:[\s\S]*?\2/gi, '')
|
||||
|
||||
export const sanitizeRichHtml = (html: string) => {
|
||||
const source = html.trim()
|
||||
if (!source) return ''
|
||||
|
||||
if (typeof DOMParser === 'undefined') {
|
||||
return sanitizeFallback(source)
|
||||
}
|
||||
|
||||
const parser = new DOMParser()
|
||||
const doc = parser.parseFromString(source, 'text/html')
|
||||
|
||||
const walk = (node: Node) => {
|
||||
if (node.nodeType === Node.COMMENT_NODE) {
|
||||
node.parentNode?.removeChild(node)
|
||||
return
|
||||
}
|
||||
|
||||
if (node.nodeType !== Node.ELEMENT_NODE) {
|
||||
return
|
||||
}
|
||||
|
||||
const element = node as HTMLElement
|
||||
const tagName = element.tagName.toLowerCase()
|
||||
|
||||
if (DANGEROUS_TAGS.has(tagName)) {
|
||||
element.remove()
|
||||
return
|
||||
}
|
||||
|
||||
if (!ALLOWED_TAGS.has(tagName)) {
|
||||
const children = Array.from(element.childNodes)
|
||||
element.replaceWith(...children)
|
||||
children.forEach(walk)
|
||||
return
|
||||
}
|
||||
|
||||
Array.from(element.attributes).forEach(attribute => {
|
||||
const attrName = attribute.name.toLowerCase()
|
||||
const attrValue = attribute.value
|
||||
|
||||
if (!isAllowedAttr(tagName, attrName)) {
|
||||
element.removeAttribute(attribute.name)
|
||||
return
|
||||
}
|
||||
|
||||
if ((attrName === 'href' || attrName === 'src') && !isSafeUrl(attrValue)) {
|
||||
element.removeAttribute(attribute.name)
|
||||
}
|
||||
})
|
||||
|
||||
if (tagName === 'a' && element.getAttribute('href')) {
|
||||
element.setAttribute('target', '_blank')
|
||||
element.setAttribute('rel', 'noopener noreferrer')
|
||||
}
|
||||
|
||||
Array.from(element.childNodes).forEach(walk)
|
||||
}
|
||||
|
||||
Array.from(doc.body.childNodes).forEach(walk)
|
||||
return doc.body.innerHTML.trim()
|
||||
}
|
||||
|
||||
const renderInlineMarkdown = (value: string) => {
|
||||
let html = escapeHtml(value)
|
||||
|
||||
html = html.replace(/`([^`]+)`/g, '<code>$1</code>')
|
||||
html = html.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
|
||||
html = html.replace(/__([^_]+)__/g, '<strong>$1</strong>')
|
||||
html = html.replace(/\*([^*]+)\*/g, '<em>$1</em>')
|
||||
html = html.replace(/_([^_]+)_/g, '<em>$1</em>')
|
||||
html = html.replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g, (_match, label: string, url: string) => {
|
||||
const href = url.replace(/&/g, '&')
|
||||
if (!isSafeUrl(href)) {
|
||||
return label
|
||||
}
|
||||
return `<a href="${escapeAttr(href)}" target="_blank" rel="noopener noreferrer">${label}</a>`
|
||||
})
|
||||
|
||||
return html.replace(/\n/g, '<br>')
|
||||
}
|
||||
|
||||
const markdownToHtml = (markdown: string) => {
|
||||
const lines = markdown.replace(/\r\n?/g, '\n').split('\n')
|
||||
const html: string[] = []
|
||||
const paragraphs: string[] = []
|
||||
const listItems: string[] = []
|
||||
let listTag: 'ul' | 'ol' | '' = ''
|
||||
let inCodeFence = false
|
||||
let codeLines: string[] = []
|
||||
|
||||
const flushParagraph = () => {
|
||||
if (!paragraphs.length) return
|
||||
html.push(`<p>${renderInlineMarkdown(paragraphs.join('\n'))}</p>`)
|
||||
paragraphs.length = 0
|
||||
}
|
||||
|
||||
const flushList = () => {
|
||||
if (!listTag || !listItems.length) return
|
||||
html.push(`<${listTag}>${listItems.map(item => `<li>${renderInlineMarkdown(item)}</li>`).join('')}</${listTag}>`)
|
||||
listItems.length = 0
|
||||
listTag = ''
|
||||
}
|
||||
|
||||
const flushCodeFence = () => {
|
||||
html.push(`<pre><code>${escapeHtml(codeLines.join('\n'))}</code></pre>`)
|
||||
codeLines = []
|
||||
}
|
||||
|
||||
lines.forEach(line => {
|
||||
if (/^```/.test(line.trim())) {
|
||||
if (inCodeFence) {
|
||||
inCodeFence = false
|
||||
flushCodeFence()
|
||||
} else {
|
||||
flushParagraph()
|
||||
flushList()
|
||||
inCodeFence = true
|
||||
codeLines = []
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (inCodeFence) {
|
||||
codeLines.push(line)
|
||||
return
|
||||
}
|
||||
|
||||
if (!line.trim()) {
|
||||
flushParagraph()
|
||||
flushList()
|
||||
return
|
||||
}
|
||||
|
||||
const heading = /^(#{1,6})\s+(.+)$/.exec(line)
|
||||
if (heading) {
|
||||
flushParagraph()
|
||||
flushList()
|
||||
const level = heading[1]!.length
|
||||
html.push(`<h${level}>${renderInlineMarkdown(heading[2]!.trim())}</h${level}>`)
|
||||
return
|
||||
}
|
||||
|
||||
const blockquote = /^>\s?(.*)$/.exec(line)
|
||||
if (blockquote) {
|
||||
flushParagraph()
|
||||
flushList()
|
||||
html.push(`<blockquote>${renderInlineMarkdown(blockquote[1] || '')}</blockquote>`)
|
||||
return
|
||||
}
|
||||
|
||||
const unordered = /^\s*[-*+]\s+(.+)$/.exec(line)
|
||||
if (unordered) {
|
||||
flushParagraph()
|
||||
if (listTag && listTag !== 'ul') flushList()
|
||||
listTag = 'ul'
|
||||
listItems.push(unordered[1] || '')
|
||||
return
|
||||
}
|
||||
|
||||
const ordered = /^\s*\d+\.\s+(.+)$/.exec(line)
|
||||
if (ordered) {
|
||||
flushParagraph()
|
||||
if (listTag && listTag !== 'ol') flushList()
|
||||
listTag = 'ol'
|
||||
listItems.push(ordered[1] || '')
|
||||
return
|
||||
}
|
||||
|
||||
flushList()
|
||||
paragraphs.push(line)
|
||||
})
|
||||
|
||||
if (inCodeFence) {
|
||||
flushCodeFence()
|
||||
}
|
||||
flushParagraph()
|
||||
flushList()
|
||||
|
||||
return html.join('')
|
||||
}
|
||||
|
||||
export const renderRichContent = (content?: string | null) => {
|
||||
const source = String(content || '').trim()
|
||||
if (!source) return ''
|
||||
|
||||
const html = HTML_TAG_PATTERN.test(source) ? source : markdownToHtml(source)
|
||||
return sanitizeRichHtml(html)
|
||||
}
|
||||
|
||||
export const extractRichText = (content?: string | null) => {
|
||||
const html = renderRichContent(content)
|
||||
if (!html) return ''
|
||||
const spacedHtml = html
|
||||
.replace(/<br\s*\/?>/gi, ' ')
|
||||
.replace(/<\/(p|div|h[1-6]|li|blockquote|tr)>/gi, ' </$1>')
|
||||
|
||||
if (typeof DOMParser === 'undefined') {
|
||||
return spacedHtml.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim()
|
||||
}
|
||||
|
||||
const parser = new DOMParser()
|
||||
const doc = parser.parseFromString(spacedHtml, 'text/html')
|
||||
return (doc.body.textContent || '').replace(/\s+/g, ' ').trim()
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
/**
|
||||
* Purpose: SHOP_THEME_CHANGED_EVENT supports shop-theme.ts by holding or executing the shop theme changed event page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const SHOP_THEME_CHANGED_EVENT = 'fingertip-designer-shop-theme-updated'
|
||||
|
||||
/**
|
||||
* Purpose: ShopThemeSource supports shop-theme.ts by holding or executing the shop theme source page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface ShopThemeSource {
|
||||
themePrimaryColor?: string | null
|
||||
themeSecondaryColor?: string | null
|
||||
themeAccentColor?: string | null
|
||||
themePageBgColor?: string | null
|
||||
themeCardBgColor?: string | null
|
||||
themeBackgroundImageFileId?: string | number | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: ResolvedShopTheme supports shop-theme.ts by holding or executing the resolved shop theme page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface ResolvedShopTheme {
|
||||
primaryColor: string
|
||||
secondaryColor: string
|
||||
accentColor: string
|
||||
tertiaryColor: string
|
||||
neutralColor: string
|
||||
pageBgColor: string
|
||||
cardBgColor: string
|
||||
textPrimary: string
|
||||
textSecondary: string
|
||||
borderColor: string
|
||||
primarySoftColor: string
|
||||
secondarySoftColor: string
|
||||
primaryActionColor: string
|
||||
gradient: string
|
||||
softGradient: string
|
||||
backgroundImageFileId?: string
|
||||
cssVars: Record<string, string>
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: HEX_COLOR_PATTERN supports shop-theme.ts by holding or executing the hex color pattern page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const HEX_COLOR_PATTERN = /^#[0-9a-fA-F]{6}$/
|
||||
|
||||
export const DEFAULT_SHOP_THEME: ResolvedShopTheme = resolveShopThemeSource()
|
||||
|
||||
/**
|
||||
* Purpose: resolveShopTheme supports shop-theme.ts by holding or executing the resolve shop theme page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export function resolveShopTheme(source?: ShopThemeSource | null): ResolvedShopTheme {
|
||||
return resolveShopThemeSource(source)
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: applyShopTheme supports shop-theme.ts by holding or executing the apply shop theme page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export function applyShopTheme(theme: ResolvedShopTheme, backgroundImageUrl?: string | null) {
|
||||
if (typeof document === 'undefined') {
|
||||
return
|
||||
}
|
||||
const root = document.documentElement
|
||||
Object.entries(theme.cssVars).forEach(([key, value]) => {
|
||||
root.style.setProperty(key, value)
|
||||
})
|
||||
root.style.setProperty('--theme-background-image', backgroundImageUrl ? `url("${backgroundImageUrl}")` : 'none')
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: notifyShopThemeChanged supports shop-theme.ts by holding or executing the notify shop theme changed page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export function notifyShopThemeChanged() {
|
||||
if (typeof window === 'undefined') {
|
||||
return
|
||||
}
|
||||
window.dispatchEvent(new Event(SHOP_THEME_CHANGED_EVENT))
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: resolveShopThemeSource supports shop-theme.ts by holding or executing the resolve shop theme source page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function resolveShopThemeSource(source?: ShopThemeSource | null): ResolvedShopTheme {
|
||||
const normalizedPrimaryColor = normalizeHexColor(source?.themePrimaryColor)
|
||||
const primaryColor = normalizedPrimaryColor || '#E8B4B8'
|
||||
const secondaryColor = normalizeHexColor(source?.themeSecondaryColor)
|
||||
|| (normalizedPrimaryColor ? mixColor(primaryColor, '#C5A059', 0.35) : '#C5A059')
|
||||
const neutralColor = normalizeHexColor(source?.themeAccentColor)
|
||||
|| (normalizedPrimaryColor ? mixColor('#4A443F', primaryColor, 0.14) : '#4A443F')
|
||||
const accentColor = neutralColor
|
||||
const tertiaryColor = normalizeHexColor(source?.themePageBgColor) || '#FDFBF9'
|
||||
const pageBgColor = tertiaryColor
|
||||
const cardBgColor = normalizeHexColor(source?.themeCardBgColor) || '#FFFFFF'
|
||||
const textPrimary = readableTextColor(pageBgColor, neutralColor)
|
||||
const textSecondary = textPrimary === neutralColor
|
||||
? mixColor(neutralColor, cardBgColor, 0.18)
|
||||
: mixColor('#FFFFFF', primaryColor, 0.3)
|
||||
const borderColor = mixColor(primaryColor, cardBgColor, 0.72)
|
||||
const primarySoftColor = mixColor(primaryColor, cardBgColor, 0.78)
|
||||
const secondarySoftColor = mixColor(secondaryColor, pageBgColor, 0.66)
|
||||
const primaryActionColor = mixColor(neutralColor, primaryColor, 0.28)
|
||||
const gradient = `linear-gradient(135deg, ${primaryActionColor} 0%, ${secondaryColor} 100%)`
|
||||
const softGradient = `linear-gradient(145deg, ${cardBgColor} 0%, ${secondarySoftColor} 58%, ${mixColor(primaryColor, pageBgColor, 0.62)} 100%)`
|
||||
const backgroundImageFileId = source?.themeBackgroundImageFileId === undefined || source?.themeBackgroundImageFileId === null
|
||||
? undefined
|
||||
: String(source.themeBackgroundImageFileId).trim() || undefined
|
||||
|
||||
return {
|
||||
primaryColor,
|
||||
secondaryColor,
|
||||
accentColor,
|
||||
tertiaryColor,
|
||||
neutralColor,
|
||||
pageBgColor,
|
||||
cardBgColor,
|
||||
textPrimary,
|
||||
textSecondary,
|
||||
borderColor,
|
||||
primarySoftColor,
|
||||
secondarySoftColor,
|
||||
primaryActionColor,
|
||||
gradient,
|
||||
softGradient,
|
||||
backgroundImageFileId,
|
||||
cssVars: {
|
||||
'--primary-color': primaryColor,
|
||||
'--theme-primary': primaryColor,
|
||||
'--theme-secondary': secondaryColor,
|
||||
'--theme-accent': accentColor,
|
||||
'--theme-neutral': neutralColor,
|
||||
'--theme-tertiary': tertiaryColor,
|
||||
'--theme-primary-action': primaryActionColor,
|
||||
'--theme-primary-soft': primarySoftColor,
|
||||
'--theme-secondary-soft': secondarySoftColor,
|
||||
'--theme-page-bg': pageBgColor,
|
||||
'--theme-card-bg': cardBgColor,
|
||||
'--theme-border': borderColor,
|
||||
'--theme-gradient': gradient,
|
||||
'--theme-gradient-soft': softGradient,
|
||||
'--theme-button-shadow': `0 12px 28px ${rgba(primaryColor, 0.22)}`,
|
||||
'--theme-focus-shadow': `0 0 0 3px ${rgba(primaryColor, 0.16)}`,
|
||||
'--bg-color': pageBgColor,
|
||||
'--secondary-bg-color': mixColor(secondaryColor, pageBgColor, 0.58),
|
||||
'--surface-color': cardBgColor,
|
||||
'--text-primary': textPrimary,
|
||||
'--text-secondary': textSecondary
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: normalizeHexColor supports shop-theme.ts by holding or executing the normalize hex color page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function normalizeHexColor(value?: string | null): string | undefined {
|
||||
if (!value) {
|
||||
return undefined
|
||||
}
|
||||
const normalized = value.trim()
|
||||
return HEX_COLOR_PATTERN.test(normalized) ? normalized.toUpperCase() : undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: mixColor supports shop-theme.ts by holding or executing the mix color page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function mixColor(foreground: string, background: string, backgroundWeight: number): string {
|
||||
const fg = hexToRgb(foreground)
|
||||
const bg = hexToRgb(background)
|
||||
const weight = clamp(backgroundWeight, 0, 1)
|
||||
return rgbToHex({
|
||||
r: Math.round(fg.r * (1 - weight) + bg.r * weight),
|
||||
g: Math.round(fg.g * (1 - weight) + bg.g * weight),
|
||||
b: Math.round(fg.b * (1 - weight) + bg.b * weight)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: readableTextColor supports shop-theme.ts by holding or executing the readable text color page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function readableTextColor(background: string, preferred: string): string {
|
||||
return relativeLuminance(hexToRgb(background)) > 0.48 ? preferred : '#FFFFFF'
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: rgba supports shop-theme.ts by holding or executing the rgba page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function rgba(color: string, alpha: number): string {
|
||||
const rgb = hexToRgb(color)
|
||||
return `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${clamp(alpha, 0, 1)})`
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: relativeLuminance supports shop-theme.ts by holding or executing the relative luminance page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function relativeLuminance(rgb: { r: number; g: number; b: number }): number {
|
||||
const toLinearChannel = (value: number) => {
|
||||
const channel = value / 255
|
||||
return channel <= 0.03928 ? channel / 12.92 : Math.pow((channel + 0.055) / 1.055, 2.4)
|
||||
}
|
||||
const r = toLinearChannel(rgb.r)
|
||||
const g = toLinearChannel(rgb.g)
|
||||
const b = toLinearChannel(rgb.b)
|
||||
return 0.2126 * r + 0.7152 * g + 0.0722 * b
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: hexToRgb supports shop-theme.ts by holding or executing the hex to rgb page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function hexToRgb(color: string): { r: number; g: number; b: number } {
|
||||
const value = color.replace('#', '')
|
||||
return {
|
||||
r: Number.parseInt(value.slice(0, 2), 16),
|
||||
g: Number.parseInt(value.slice(2, 4), 16),
|
||||
b: Number.parseInt(value.slice(4, 6), 16)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: rgbToHex supports shop-theme.ts by holding or executing the rgb to hex page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function rgbToHex(rgb: { r: number; g: number; b: number }): string {
|
||||
return `#${toHex(rgb.r)}${toHex(rgb.g)}${toHex(rgb.b)}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: toHex supports shop-theme.ts by holding or executing the to hex page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function toHex(value: number): string {
|
||||
return clamp(value, 0, 255).toString(16).padStart(2, '0').toUpperCase()
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: clamp supports shop-theme.ts by holding or executing the clamp page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function clamp(value: number, min: number, max: number): number {
|
||||
return Math.min(max, Math.max(min, value))
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
import { fileApi } from '@/api/file'
|
||||
import type { IdType } from '@/utils/id'
|
||||
|
||||
const SIGNED_IMAGE_CACHE_TTL_MS = 10 * 60 * 1000
|
||||
|
||||
export type SignedImageSource = 'public'
|
||||
|
||||
type SignedImageCacheEntry = {
|
||||
url: string
|
||||
expiresAt: number
|
||||
}
|
||||
|
||||
const signedImageUrlCache = new Map<string, SignedImageCacheEntry>()
|
||||
const pendingSignedImageUrlRequests = new Map<string, Promise<string>>()
|
||||
|
||||
const normalizeFileId = (fileId: IdType | null | undefined) => String(fileId ?? '').trim()
|
||||
const buildCacheKey = (source: SignedImageSource, fileId: string) => `${source}:${fileId}`
|
||||
const normalizeImageUrl = (url: string): string => {
|
||||
const trimmedUrl = url.trim()
|
||||
if (!trimmedUrl) return ''
|
||||
if (/^(https?:)?\/\//i.test(trimmedUrl) || /^(data|blob):/i.test(trimmedUrl) || trimmedUrl.startsWith('/')) {
|
||||
return trimmedUrl
|
||||
}
|
||||
return `http://${trimmedUrl}`
|
||||
}
|
||||
|
||||
const requestSignedImageUrl = (_source: SignedImageSource, fileId: string): Promise<string> => {
|
||||
return fileApi.getSignedUrl(fileId).then(response => String(response.data || ''))
|
||||
}
|
||||
|
||||
const getUsableCacheEntry = (key: string) => {
|
||||
const cached = signedImageUrlCache.get(key)
|
||||
if (!cached) return undefined
|
||||
if (cached.expiresAt <= Date.now()) {
|
||||
signedImageUrlCache.delete(key)
|
||||
return undefined
|
||||
}
|
||||
return cached.url
|
||||
}
|
||||
|
||||
export const parseImageFileIds = (value?: string | null): string[] =>
|
||||
String(value || '')
|
||||
.split(',')
|
||||
.map(id => id.trim())
|
||||
.filter(Boolean)
|
||||
|
||||
export const getCachedSignedImageUrlSync = (
|
||||
fileId: IdType | null | undefined,
|
||||
source: SignedImageSource = 'public'
|
||||
): string => {
|
||||
const fileIdKey = normalizeFileId(fileId)
|
||||
if (!fileIdKey) return ''
|
||||
return getUsableCacheEntry(buildCacheKey(source, fileIdKey)) || ''
|
||||
}
|
||||
|
||||
export const getCachedSignedImageUrl = async (
|
||||
fileId: IdType | null | undefined,
|
||||
fallback = '',
|
||||
source: SignedImageSource = 'public'
|
||||
): Promise<string> => {
|
||||
const fileIdKey = normalizeFileId(fileId)
|
||||
if (!fileIdKey) return fallback
|
||||
const key = buildCacheKey(source, fileIdKey)
|
||||
|
||||
const cachedUrl = getUsableCacheEntry(key)
|
||||
if (cachedUrl) return cachedUrl
|
||||
|
||||
const pendingRequest = pendingSignedImageUrlRequests.get(key)
|
||||
if (pendingRequest) {
|
||||
return pendingRequest.then(url => url || fallback).catch(() => fallback)
|
||||
}
|
||||
|
||||
const request = requestSignedImageUrl(source, fileIdKey)
|
||||
.then(response => {
|
||||
const url = normalizeImageUrl(String(response || ''))
|
||||
if (url) {
|
||||
signedImageUrlCache.set(key, {
|
||||
url,
|
||||
expiresAt: Date.now() + SIGNED_IMAGE_CACHE_TTL_MS
|
||||
})
|
||||
}
|
||||
return url
|
||||
})
|
||||
.finally(() => {
|
||||
pendingSignedImageUrlRequests.delete(key)
|
||||
})
|
||||
|
||||
pendingSignedImageUrlRequests.set(key, request)
|
||||
return request.then(url => url || fallback).catch(() => fallback)
|
||||
}
|
||||
|
||||
export const clearCachedSignedImageUrl = (
|
||||
fileId: IdType | null | undefined,
|
||||
source: SignedImageSource = 'public'
|
||||
): void => {
|
||||
const fileIdKey = normalizeFileId(fileId)
|
||||
if (!fileIdKey) return
|
||||
const cacheKey = buildCacheKey(source, fileIdKey)
|
||||
signedImageUrlCache.delete(cacheKey)
|
||||
pendingSignedImageUrlRequests.delete(cacheKey)
|
||||
}
|
||||
|
||||
export const refreshCachedSignedImageUrl = async (
|
||||
fileId: IdType | null | undefined,
|
||||
fallback = '',
|
||||
source: SignedImageSource = 'public'
|
||||
): Promise<string> => {
|
||||
clearCachedSignedImageUrl(fileId, source)
|
||||
return getCachedSignedImageUrl(fileId, fallback, source)
|
||||
}
|
||||
|
||||
export const getCachedSignedImageUrls = async (
|
||||
fileIds: Array<IdType | null | undefined>,
|
||||
fallback = '',
|
||||
source: SignedImageSource = 'public'
|
||||
): Promise<string[]> => {
|
||||
const urls = await Promise.all(fileIds.map(fileId => getCachedSignedImageUrl(fileId, '', source)))
|
||||
const validUrls = urls.filter(Boolean)
|
||||
return validUrls.length ? validUrls : (fallback ? [fallback] : [])
|
||||
}
|
||||
|
||||
export const getCachedSignedImageUrlsSync = (
|
||||
fileIds: Array<IdType | null | undefined>,
|
||||
source: SignedImageSource = 'public'
|
||||
): string[] =>
|
||||
fileIds.map(fileId => getCachedSignedImageUrlSync(fileId, source)).filter(Boolean)
|
||||
|
||||
export const extractLegacyFileId = (value?: string | null): string => {
|
||||
const source = String(value || '').replace(/<[^>]*>/g, '')
|
||||
return source.match(/\/api\/file\/get\/([^/?#"'<>]+)/)?.[1] || ''
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { buildSystemMessageActionPath } from './system-message-action'
|
||||
|
||||
describe('buildSystemMessageActionPath', () => {
|
||||
it('keeps safe review action paths with order and review query parameters', () => {
|
||||
expect(buildSystemMessageActionPath({
|
||||
actionPath: '/orders?orderId=10&reviewId=99&orderItemId=1001',
|
||||
businessType: 'ORDER_ARTIST_REVIEW',
|
||||
businessId: 99
|
||||
})).toBe('/orders?orderId=10&reviewId=99&orderItemId=1001')
|
||||
})
|
||||
|
||||
it('uses reviewId fallback for review reminder messages when actionPath is absent', () => {
|
||||
expect(buildSystemMessageActionPath({
|
||||
businessType: 'ORDER_ARTIST_REVIEW',
|
||||
businessId: 99
|
||||
})).toBe('/orders?reviewId=99&source=message')
|
||||
})
|
||||
|
||||
it('opens pending reviews when a review reminder has no business id', () => {
|
||||
expect(buildSystemMessageActionPath({
|
||||
businessType: 'ORDER_ARTIST_REVIEW'
|
||||
})).toBe('/orders?review=pending&source=message')
|
||||
})
|
||||
|
||||
it('uses orderId fallback for generic order messages', () => {
|
||||
expect(buildSystemMessageActionPath({
|
||||
businessType: 'ORDER',
|
||||
businessId: 10
|
||||
})).toBe('/orders/10')
|
||||
})
|
||||
|
||||
it('uses after-sale fallback for after-sale messages', () => {
|
||||
expect(buildSystemMessageActionPath({
|
||||
businessType: 'AFTER_SALE',
|
||||
businessId: 10
|
||||
})).toBe('/after-sales?orderId=10&source=message')
|
||||
})
|
||||
|
||||
it('keeps safe order detail and after-sale action paths', () => {
|
||||
expect(buildSystemMessageActionPath({ actionPath: '/orders/10' })).toBe('/orders/10')
|
||||
expect(buildSystemMessageActionPath({ actionPath: '/after-sales?orderId=10' })).toBe('/after-sales?orderId=10')
|
||||
expect(buildSystemMessageActionPath({ actionPath: '/after-sale/apply?orderId=10&orderItemId=99' })).toBe('/after-sale/apply?orderId=10&orderItemId=99')
|
||||
expect(buildSystemMessageActionPath({ actionPath: '/service-progress?orderId=10' })).toBe('/service-progress?orderId=10')
|
||||
})
|
||||
|
||||
it('rejects unsafe or backend-only action paths', () => {
|
||||
expect(buildSystemMessageActionPath({ actionPath: '//evil.example/orders' })).toBe('')
|
||||
expect(buildSystemMessageActionPath({ actionPath: 'https://evil.example/orders' })).toBe('')
|
||||
expect(buildSystemMessageActionPath({ actionPath: '/admin/users' })).toBe('')
|
||||
expect(buildSystemMessageActionPath({ actionPath: '/orders-admin' })).toBe('')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,95 @@
|
||||
import type { SystemMessageVO } from '@/api/user'
|
||||
|
||||
type MessageLike = Pick<SystemMessageVO, 'actionPath' | 'businessType' | 'businessId'>
|
||||
|
||||
const USER_ACTION_PREFIXES = [
|
||||
'/orders',
|
||||
'/after-sales',
|
||||
'/after-sale/apply',
|
||||
'/service-progress',
|
||||
'/help',
|
||||
'/product/',
|
||||
'/shop/',
|
||||
'/coupons',
|
||||
'/vip-center',
|
||||
'/cart',
|
||||
'/notifications',
|
||||
'/wishlist',
|
||||
'/profile',
|
||||
'/settings',
|
||||
'/artist-orders',
|
||||
'/artist-calendar'
|
||||
]
|
||||
|
||||
const appendQuery = (path: string, query: Record<string, string | number | undefined>) => {
|
||||
const params = new URLSearchParams()
|
||||
Object.entries(query).forEach(([key, value]) => {
|
||||
if (value !== undefined && value !== '') {
|
||||
params.set(key, String(value))
|
||||
}
|
||||
})
|
||||
const queryString = params.toString()
|
||||
return queryString ? `${path}?${queryString}` : path
|
||||
}
|
||||
|
||||
const isAllowedUserActionPath = (actionPath: string) => {
|
||||
const pathOnly = actionPath.split('?')[0] || ''
|
||||
return USER_ACTION_PREFIXES.some(prefix => {
|
||||
if (prefix.endsWith('/')) {
|
||||
return pathOnly.startsWith(prefix)
|
||||
}
|
||||
return pathOnly === prefix || pathOnly.startsWith(`${prefix}/`)
|
||||
})
|
||||
}
|
||||
|
||||
export const normalizeSystemMessageActionPath = (value?: string) => {
|
||||
const actionPath = String(value || '').trim()
|
||||
if (!actionPath || !actionPath.startsWith('/') || actionPath.startsWith('//') || actionPath.includes('\\')) {
|
||||
return ''
|
||||
}
|
||||
return isAllowedUserActionPath(actionPath) ? actionPath : ''
|
||||
}
|
||||
|
||||
export const buildSystemMessageActionPath = (message: MessageLike) => {
|
||||
const actionPath = normalizeSystemMessageActionPath(message.actionPath)
|
||||
if (actionPath) {
|
||||
return actionPath
|
||||
}
|
||||
|
||||
const businessType = String(message.businessType || '').toUpperCase()
|
||||
const businessId = message.businessId === undefined || message.businessId === null ? '' : String(message.businessId)
|
||||
if (businessType === 'ORDER_ARTIST_REVIEW') {
|
||||
return businessId
|
||||
? appendQuery('/orders', { reviewId: businessId, source: 'message' })
|
||||
: appendQuery('/orders', { review: 'pending', source: 'message' })
|
||||
}
|
||||
if (businessType === 'ORDER' && businessId) {
|
||||
return `/orders/${encodeURIComponent(businessId)}`
|
||||
}
|
||||
if (businessType === 'ORDER_ARTIST_CHANGE' && businessId) {
|
||||
return appendQuery('/service-progress', { orderId: businessId, source: 'message' })
|
||||
}
|
||||
if (businessType === 'ORDER_ARTIST_CHANGE' || businessType === 'ORDER') {
|
||||
return appendQuery('/orders', { orderId: businessId || undefined, source: 'message' })
|
||||
}
|
||||
if (businessType === 'AFTER_SALE') {
|
||||
return appendQuery('/after-sales', { orderId: businessId || undefined, source: 'message' })
|
||||
}
|
||||
if (businessType === 'PRODUCT' && businessId) {
|
||||
return `/product/${encodeURIComponent(businessId)}`
|
||||
}
|
||||
if (businessType === 'SHOP' && businessId) {
|
||||
return `/shop/${encodeURIComponent(businessId)}`
|
||||
}
|
||||
if (businessType === 'VIP') {
|
||||
return '/vip-center'
|
||||
}
|
||||
if (businessType === 'COUPON') {
|
||||
return '/coupons'
|
||||
}
|
||||
if (businessType === 'CART') {
|
||||
return '/cart'
|
||||
}
|
||||
|
||||
return ''
|
||||
}
|
||||
Reference in New Issue
Block a user