feat(思维导图助手):优化重构
parent
46f3467959
commit
f445884497
|
|
@ -0,0 +1,28 @@
|
|||
// The parent owns authentication. No token or provider secret is sent to this frame.
|
||||
import { uuid } from '@/utils/uuid'
|
||||
const pending = new Map<string, { resolve: (value: any) => void; reject: (error: Error) => void; timer: ReturnType<typeof setTimeout> }>()
|
||||
const parentOrigin = (() => { try { return new URL(document.referrer).origin } catch { return '' } })()
|
||||
window.addEventListener('message', event => {
|
||||
if (event.source !== window.parent || event.origin !== parentOrigin || event.data?.type !== 'ai-hub-response') return
|
||||
const call = pending.get(event.data.id)
|
||||
if (!call) return
|
||||
clearTimeout(call.timer); pending.delete(event.data.id)
|
||||
if (event.data.error) call.reject(new Error(event.data.error)); else call.resolve(event.data.data)
|
||||
})
|
||||
export async function hubCall(kind: string, method = 'get', data?: any, recordId?: string, file?: File): Promise<any> {
|
||||
if (window.parent === window || !parentOrigin) throw new Error('请从管理平台打开思维导图')
|
||||
const id = uuid()
|
||||
const upload = file ? { name: file.name, content: await file.arrayBuffer() } : undefined
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => { pending.delete(id); reject(new Error('请求超时')) }, 45000)
|
||||
pending.set(id, { resolve, reject, timer })
|
||||
window.parent.postMessage({ type: 'ai-hub-request', id, kind, method, data, recordId, file: upload }, parentOrigin)
|
||||
})
|
||||
}
|
||||
export function onOpenArtifact(callback: (artifact: any) => void) {
|
||||
const handler = (event: MessageEvent) => {
|
||||
if (event.source === window.parent && event.origin === parentOrigin && event.data?.type === 'ai-hub-open') callback(event.data.artifact)
|
||||
}
|
||||
window.addEventListener('message', handler)
|
||||
return () => window.removeEventListener('message', handler)
|
||||
}
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
// crypto.randomUUID 仅在安全上下文(HTTPS/localhost)可用;管理平台可能以 HTTP 访问,需要降级。
|
||||
export function uuid(): string {
|
||||
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') return crypto.randomUUID()
|
||||
const buf = new Uint8Array(16)
|
||||
crypto.getRandomValues(buf)
|
||||
buf[6] = (buf[6] & 0x0f) | 0x40
|
||||
buf[8] = (buf[8] & 0x3f) | 0x80
|
||||
const hex = Array.from(buf, b => b.toString(16).padStart(2, '0')).join('')
|
||||
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`
|
||||
}
|
||||
Loading…
Reference in New Issue