OneAlign / web /src /lib /cloud-client.ts
loveaa's picture
Home Pulse 1.2: app interface, recommended event policies and independent location reminders
133b124 verified
Raw History Blame Contribute Delete
2.8 kB
declare global {interface Window {__HOME_PULSE_CLOUD__?:boolean}}
export const isCloud=()=>typeof window!=='undefined'&&window.__HOME_PULSE_CLOUD__===true
export function installCloudClient(){
if(!isCloud())return
const key='home-pulse-cloud-workspace'
let workspace=localStorage.getItem(key)
if(!workspace||!/^[a-f0-9]{64}$/.test(workspace)){
workspace=Array.from(crypto.getRandomValues(new Uint8Array(32)),b=>b.toString(16).padStart(2,'0')).join('')
localStorage.setItem(key,workspace)
}
const token=workspace
document.cookie=`hp_workspace=${token}; Path=/; Max-Age=31536000; ${location.protocol==='https:'?'Secure; SameSite=None; Partitioned':'SameSite=Lax'}`
const original=window.fetch.bind(window)
let clientPromise:Promise<import('@gradio/client').Client>|undefined
window.fetch=async(input,init)=>{
const url=new URL(typeof input==='string'?input:input instanceof URL?input.href:input.url,location.href)
if(url.origin!==location.origin||!url.pathname.startsWith('/api/'))return original(input,init)
const request=new Request(input,init),headers=new Headers(request.headers)
if(!headers.has('X-Home-Pulse-Workspace'))headers.set('X-Home-Pulse-Workspace',token)
const visual=request.method==='POST'&&['/api/contracts/observe','/api/setup/trial','/api/analyze'].includes(url.pathname)
if(!visual)return original(new Request(request,{headers}))
if(request.signal.aborted)throw new DOMException('Aborted','AbortError')
try{
clientPromise ||= import('@gradio/client').then(({Client})=>Client.connect(location.origin))
const client=await clientPromise
const job=client.submit('/visual',[url.pathname,await request.text(),token])
const abort=()=>{void job.cancel()}
request.signal.addEventListener('abort',abort,{once:true})
try{
for await(const event of job){
if(request.signal.aborted)throw new DOMException('Aborted','AbortError')
if(event.type==='data'){
const result=(Array.isArray(event.data)?event.data[0]:event.data) as {status:number;body:unknown}
if(!result||typeof result.status!=='number')throw new Error('云端返回格式异常')
return new Response(JSON.stringify(result.body),{status:result.status,headers:{'Content-Type':'application/json'}})
}
}
throw new Error('云端观察尚未返回,请重试')
}finally{request.signal.removeEventListener('abort',abort)}
}catch(error){
if(request.signal.aborted)throw new DOMException('Aborted','AbortError')
const message=String(error instanceof Error?error.message:error).replace(/<[^>]*>/g,'').slice(0,400)
return new Response(JSON.stringify({error:/quota|exceeded/i.test(message)?'HF 免费 GPU 额度暂时用完,请在额度恢复后再观察。':message}),{status:503,headers:{'Content-Type':'application/json'}})
}
}
}