dsh-remote-plugin 0.8.1 → 0.8.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/apk/dsh-remote.apk +0 -0
- package/cordis.patch.yml +2 -1
- package/gateway.cjs +323 -64
- package/index.mjs +2 -2
- package/insights.mjs +5 -3
- package/market.mjs +4 -1
- package/package.json +1 -1
- package/plugin-center.mjs +120 -7
- package/plugin-transaction.mjs +10 -3
- package/public/admin.html +19 -14
- package/public/admin.js +71 -23
- package/public/announcements.json +192 -0
- package/public/app.js +192 -60
- package/public/build.json +2 -2
- package/public/chat-copy.js +46 -0
- package/public/desktop/desktop.css +10 -0
- package/public/desktop/desktop.html +28 -15
- package/public/desktop/desktop.js +74 -22
- package/public/diagnostics.js +115 -21
- package/public/history.js +45 -9
- package/public/image-cache.js +141 -0
- package/public/image-preview.js +48 -5
- package/public/index.html +39 -34
- package/public/lan-discovery.js +94 -0
- package/public/md.js +8 -2
- package/public/plugin-center.js +1 -1
- package/public/plugin.html +8 -2
- package/public/relay-settings.js +7 -6
- package/public/skins/blue-fish/DESIGN.md +24 -0
- package/public/skins/blue-fish/preview.html +11 -289
- package/public/skins/blue-fish/skin.css +95 -585
- package/public/skins/blue-fish/sparkles.svg +18 -0
- package/public/skins/bocchi/DESIGN.md +99 -0
- package/public/skins/bocchi/face.png +0 -0
- package/public/skins/bocchi/grain.png +0 -0
- package/public/skins/bocchi/icon-blush.png +0 -0
- package/public/skins/bocchi/icon-sleep.png +0 -0
- package/public/skins/bocchi/icon-smile.png +0 -0
- package/public/skins/bocchi/icon-star.png +0 -0
- package/public/skins/bocchi/icon-wink.png +0 -0
- package/public/skins/bocchi/icon.png +0 -0
- package/public/skins/bocchi/pattern-soft.png +0 -0
- package/public/skins/bocchi/pattern.png +0 -0
- package/public/skins/bocchi/preview.html +54 -0
- package/public/skins/bocchi/skin.css +233 -0
- package/public/skins/bocchi/stage-bg.png +0 -0
- package/public/skins/bocchi/stage-soft.png +0 -0
- package/public/skins/bocchi/stand.png +0 -0
- package/public/skins/bocchi/sticker-guitar.png +0 -0
- package/public/skins/kessoku/DESIGN.md +38 -0
- package/public/skins/kessoku/grain.png +0 -0
- package/public/skins/kessoku/skin.css +212 -0
- package/public/skins/kita/SOURCES.json +51 -0
- package/public/skins/kita/face.png +0 -0
- package/public/skins/kita/icon-live.png +0 -0
- package/public/skins/kita/icon-reddress.png +0 -0
- package/public/skins/kita/icon-seifuku.png +0 -0
- package/public/skins/kita/pattern.png +0 -0
- package/public/skins/kita/preview.html +55 -0
- package/public/skins/kita/skin.css +26 -0
- package/public/skins/kita/stand.png +0 -0
- package/public/skins/kita/sticker-live.png +0 -0
- package/public/skins/nijika/SOURCES.json +51 -0
- package/public/skins/nijika/face.png +0 -0
- package/public/skins/nijika/icon-live.png +0 -0
- package/public/skins/nijika/icon-reddress.png +0 -0
- package/public/skins/nijika/icon-seifuku.png +0 -0
- package/public/skins/nijika/pattern.png +0 -0
- package/public/skins/nijika/preview.html +55 -0
- package/public/skins/nijika/skin.css +25 -0
- package/public/skins/nijika/stand.png +0 -0
- package/public/skins/nijika/sticker-live.png +0 -0
- package/public/skins/penguin/DESIGN.md +33 -0
- package/public/skins/penguin/SOURCES.json +22 -0
- package/public/skins/penguin/aic-blueprint.svg +24 -0
- package/public/skins/penguin/endfield-triangles.svg +4 -0
- package/public/skins/penguin/face.png +0 -0
- package/public/skins/penguin/icon-blush.png +0 -0
- package/public/skins/penguin/icon-dizzy.png +0 -0
- package/public/skins/penguin/icon-laugh.png +0 -0
- package/public/skins/penguin/icon-sleep.png +0 -0
- package/public/skins/penguin/icon-smile.png +0 -0
- package/public/skins/penguin/icon-star.png +0 -0
- package/public/skins/penguin/icon-wink.png +0 -0
- package/public/skins/penguin/icon.png +0 -0
- package/public/skins/penguin/mascot.png +0 -0
- package/public/skins/penguin/pattern-night.png +0 -0
- package/public/skins/penguin/pattern.png +0 -0
- package/public/skins/penguin/preview.html +11 -0
- package/public/skins/penguin/skin.css +212 -0
- package/public/skins/ryo/SOURCES.json +51 -0
- package/public/skins/ryo/face.png +0 -0
- package/public/skins/ryo/icon-live.png +0 -0
- package/public/skins/ryo/icon-reddress.png +0 -0
- package/public/skins/ryo/icon-seifuku.png +0 -0
- package/public/skins/ryo/pattern.png +0 -0
- package/public/skins/ryo/preview.html +55 -0
- package/public/skins/ryo/skin.css +25 -0
- package/public/skins/ryo/stand.png +0 -0
- package/public/skins/ryo/sticker-live.png +0 -0
- package/public/sponsor-entry.js +22 -0
- package/public/styles.css +13 -0
- package/public/theme-picker.css +58 -0
- package/public/theme-vars.css +532 -5
- package/public/theme.js +111 -3
- package/public/update.json +12 -12
- package/public/version.json +1 -1
- package/public/workflow.css +2 -1
- package/public/workflow.js +24 -1
- package/skills/dsh-remote-doctor/references/wiki/notifications.md +4 -0
package/public/diagnostics.js
CHANGED
|
@@ -1,12 +1,20 @@
|
|
|
1
|
-
/*
|
|
1
|
+
/* Bounded support evidence. No message bodies, credentials or dependencies. */
|
|
2
2
|
'use strict'
|
|
3
3
|
function createDiagnosticSchema() {
|
|
4
|
-
const MAX_EVENTS=160,MAX_BYTES=48000
|
|
5
|
-
const kinds=new Set(['rpc','history.load','history.cache','history.render','history.row','session.open','session.back','stream.state','stream.retry','poll.state','client.lifecycle','client.error','feedback.submit'])
|
|
4
|
+
const MAX_EVENTS=160,MAX_CRITICAL=40,MAX_BYTES=48000
|
|
5
|
+
const kinds=new Set(['rpc','history.load','history.cache','history.render','history.row','session.open','session.back','stream.state','stream.retry','poll.state','client.lifecycle','client.error','feedback.submit','announcement.storage','announcement.fetch','announcement.show','announcement.close','announcement.vote','storage.write','diagnostics.persist'])
|
|
6
6
|
const enums={phase:['start','response','prepared','rendered','complete','failed','navigate','cleanup','hit','miss','retry'],channel:['mux','host'],status:['open','closed','connecting','poll','ws','visible','hidden','online','offline','running','stopped','starting','disabled','start-failed','timeout','error','unknown','granted','denied','default'],category:['authentication','timeout','network','render','syntax','upstream','unknown'],errorName:['Error','TypeError','RangeError','SyntaxError','ReferenceError','AbortError','TimeoutError','NetworkError']}
|
|
7
7
|
enums.serviceState=['starting','running','stopped','disabled','start-failed','system-timeout','auth-expired']
|
|
8
|
-
|
|
9
|
-
|
|
8
|
+
enums.storageKey=['seen','history','votes']
|
|
9
|
+
enums.storageBackend=['session','memory']
|
|
10
|
+
enums.storageBackend.push('local','indexeddb')
|
|
11
|
+
enums.storageKey.push('settings','session-list','diagnostics','approvals','receipts')
|
|
12
|
+
enums.phase.push('received','shown','dismissed','acknowledged','skipped')
|
|
13
|
+
enums.category.push('storage','validation')
|
|
14
|
+
enums.errorName.push('QuotaExceededError','SecurityError','InvalidStateError','DataError','UnknownError')
|
|
15
|
+
enums.reason=['already-open','already-read','version-warning','empty','http','network','invalid-json','too-large','unavailable']
|
|
16
|
+
const numbers=['durationMs','httpStatus','closeCode','attempt','delayMs','count','rawCount','renderedCount','renderErrors','lastSuccessAt','intervalMin','apiLevel','storageChars','storageKeys','legacyCacheChars','legacyCacheKeys','historyCacheChars','sessionCacheChars','announcementChars','diagnosticChars','droppedEvents']
|
|
17
|
+
const booleans=['reset','cached','loading','loaded','hasMore','online','enabled','serviceRunning','loginExpired','powerSave','ignoreBatteryOptimizations','notificationsEnabled','persisted','indexedDbAvailable','storageAvailable']
|
|
10
18
|
const methods=new Set(['session.list','session.history','session.create','session.prompt','session.fork','session.cancel','session.rename','session.selectModel','session.updateQueue','session.getModels','session.getQueue','session.getCompactionStatus','workspace.list','workspace.create','workspace.archiveSession','host.describe','subagent.list','subagent.interrupt','goal.edit','goal.pause','goal.resume','goal.complete','goal.clear'])
|
|
11
19
|
for(const method of ['session.models','llm.discoverModels','llm.providers','credentials.describe','credentials.set','credentials.unset','settings.describe','settings.mutate','settings.openDocument'])methods.add(method)
|
|
12
20
|
const hex=(v,n)=>typeof v==='string'&&new RegExp('^[a-f0-9]{'+n+'}$').test(v)?v:undefined
|
|
@@ -17,52 +25,134 @@ function createDiagnosticSchema() {
|
|
|
17
25
|
for(const key of numbers)if(typeof input[key]==='number'&&Number.isFinite(input[key])&&input[key]>=0)out[key]=Math.min(input[key],Number.MAX_SAFE_INTEGER)
|
|
18
26
|
for(const key of booleans)if(typeof input[key]==='boolean')out[key]=input[key]
|
|
19
27
|
if(methods.has(input.method))out.method=input.method
|
|
20
|
-
for(const key of ['sessionRef','serverRef'])if(hex(input[key],16))out[key]=input[key]
|
|
28
|
+
for(const key of ['sessionRef','serverRef','announcementRef'])if(hex(input[key],16))out[key]=input[key]
|
|
21
29
|
if(hex(input.traceId,24))out.traceId=input.traceId
|
|
22
30
|
if(Array.isArray(input.frames))out.frames=input.frames.slice(0,3).filter(f=>['app.js','desktop.js','history.js','activity.js','turn-results.js','network.js','operations.js','diagnostics.js'].includes(f?.file)&&Number.isSafeInteger(f.line)&&f.line>0&&Number.isSafeInteger(f.column)&&f.column>0).map(f=>({file:f.file,line:f.line,column:f.column}))
|
|
23
31
|
return out
|
|
24
32
|
}
|
|
33
|
+
const critical=row=>row.kind==='client.error'||row.phase==='failed'
|
|
34
|
+
function retain(events) {
|
|
35
|
+
const errors=events.filter(critical).slice(-MAX_CRITICAL),keep=new Set([...events.slice(-(MAX_EVENTS-errors.length)),...errors])
|
|
36
|
+
return events.filter(row=>keep.has(row))
|
|
37
|
+
}
|
|
38
|
+
function shrink(events,budget) {
|
|
39
|
+
while(events.length&&JSON.stringify(events).length>budget){const index=events.findIndex(row=>!critical(row));events.splice(index<0?0:index,1)}
|
|
40
|
+
return events
|
|
41
|
+
}
|
|
25
42
|
function sanitizeReport(input) {
|
|
26
43
|
if(!input||input.schema!==1||!Array.isArray(input.events))return null
|
|
27
44
|
const report={schema:1,reportId:hex(input.reportId,24)||'000000000000000000000000',capturedAt:typeof input.capturedAt==='number'&&Number.isFinite(input.capturedAt)?input.capturedAt:0,
|
|
28
45
|
client:{version:version(input.client?.version),buildId:hex(input.client?.buildId,64)||'unknown',surface:['mobile','desktop'].includes(input.client?.surface)?input.client.surface:'mobile'},
|
|
29
46
|
snapshot:facts(input.snapshot),events:[]}
|
|
30
|
-
for(const item of input.events
|
|
31
|
-
|
|
47
|
+
for(const item of input.events)if(item&&kinds.has(item.kind)&&typeof item.at==='number'&&Number.isFinite(item.at))report.events.push({at:item.at,kind:item.kind,...facts(item)})
|
|
48
|
+
report.events=retain(report.events)
|
|
49
|
+
if(input.persistence&&typeof input.persistence==='object'){
|
|
50
|
+
report.persistence={}
|
|
51
|
+
for(const key of ['local','session','indexeddb'])if(['unknown','saved','failed','unavailable','pending'].includes(input.persistence[key]))report.persistence[key]=input.persistence[key]
|
|
52
|
+
}
|
|
53
|
+
while(JSON.stringify(report).length>MAX_BYTES&&report.events.length){const index=report.events.findIndex(row=>!critical(row));report.events.splice(index<0?0:index,1)}
|
|
32
54
|
return report
|
|
33
55
|
}
|
|
34
|
-
return {MAX_EVENTS,MAX_BYTES,kinds,facts,sanitizeReport
|
|
56
|
+
return {MAX_EVENTS,MAX_CRITICAL,MAX_BYTES,kinds,facts,sanitizeReport,retain,shrink,
|
|
57
|
+
definition:{MAX_EVENTS,MAX_CRITICAL,MAX_BYTES,kinds:[...kinds],enums,numbers,booleans,methods:[...methods]}}
|
|
35
58
|
}
|
|
36
59
|
;(function(root){
|
|
37
60
|
const schema=createDiagnosticSchema()
|
|
38
61
|
function createDiagnostics(env) {
|
|
39
62
|
const KEY='dshRemoteDiagnosticsV1',SALT_KEY=KEY+'Salt',MAX_AGE=86400000
|
|
40
|
-
let rows=[],timer,config={},metadata={},sequence=0,sheet,exportTimer
|
|
63
|
+
let rows=[],timer,config={},metadata={},sequence=0,sheet,exportTimer,droppedEvents=0,epoch=0
|
|
64
|
+
let database,backupJob,pendingBackup,storageAt=0,storageInventory={}
|
|
65
|
+
const persistence={local:'unknown',session:'unknown',indexeddb:'unknown'}
|
|
41
66
|
const random=()=>{const bytes=new Uint8Array(12);env.crypto?.getRandomValues?.(bytes);return [...bytes].map(n=>n.toString(16).padStart(2,'0')).join('')}
|
|
42
67
|
let salt=random(),run=random()
|
|
43
|
-
try{salt=env.localStorage.getItem(SALT_KEY)||salt;env.localStorage.setItem(SALT_KEY,salt)
|
|
68
|
+
try{salt=env.localStorage.getItem(SALT_KEY)||salt;env.localStorage.setItem(SALT_KEY,salt)}catch{}
|
|
69
|
+
for(const storage of [env.localStorage,env.sessionStorage])try{const saved=schema.sanitizeReport(JSON.parse(storage.getItem(KEY)||'null'));if(saved)rows.push(...saved.events)}catch{}
|
|
70
|
+
rows=[...new Map(rows.map(row=>[JSON.stringify(row),row])).values()].sort((a,b)=>a.at-b.at)
|
|
44
71
|
const now=()=>Date.now()
|
|
45
72
|
const pseudonym=value=>{if(!value||!env.SHA256)return undefined;try{return new env.SHA256().update(new TextEncoder().encode(salt+'\0'+value)).hex().slice(0,16)}catch{return undefined}}
|
|
46
|
-
const trim=()=>{rows=rows.filter(row=>row.at>now()-MAX_AGE&&row.at<=now()+60000)
|
|
47
|
-
function
|
|
48
|
-
|
|
49
|
-
|
|
73
|
+
const trim=()=>{const before=rows.length;rows=schema.shrink(schema.retain(rows.filter(row=>row.at>now()-MAX_AGE&&row.at<=now()+60000)),schema.MAX_BYTES-3000);droppedEvents+=before-rows.length}
|
|
74
|
+
function storageFacts(force=false){
|
|
75
|
+
if(!force&&storageAt&&now()-storageAt<30000)return storageInventory
|
|
76
|
+
const value={storageChars:0,storageKeys:0,legacyCacheChars:0,legacyCacheKeys:0,historyCacheChars:0,sessionCacheChars:0,announcementChars:0,diagnosticChars:0,indexedDbAvailable:!!env.indexedDB,storageAvailable:false}
|
|
77
|
+
try{const storage=env.localStorage;if(typeof storage.length!=='number')throw Error('storage unavailable');for(let i=0;i<storage.length;i++){
|
|
78
|
+
const key=storage.key(i),size=key.length+(storage.getItem(key)||'').length;value.storageKeys++;value.storageChars+=size
|
|
79
|
+
if(/^historyCache/.test(key)){value.historyCacheChars+=size;if(!key.includes(':session:')&&!key.endsWith(':cache-index')){value.legacyCacheChars+=size;value.legacyCacheKeys++}}
|
|
80
|
+
else if(/^sessionsCache/.test(key))value.sessionCacheChars+=size
|
|
81
|
+
else if(/^(?:seenAnnouncements|announcementHistory|announcementVotes)V1$/.test(key))value.announcementChars+=size
|
|
82
|
+
else if(key===KEY)value.diagnosticChars+=size
|
|
83
|
+
}value.storageAvailable=true}catch{}
|
|
84
|
+
storageAt=now();storageInventory=value;return value
|
|
85
|
+
}
|
|
86
|
+
function snapshot(force=false){let value={};try{value=config.snapshot?.()||{}}catch{};return schema.facts({...value,...storageFacts(force),droppedEvents,sessionRef:pseudonym(value.sessionId),serverRef:pseudonym(value.server||env.location?.origin),online:env.navigator?.onLine!==false})}
|
|
87
|
+
function makeReport(force=false){trim();return schema.sanitizeReport({schema:1,reportId:random(),capturedAt:now(),client:{...metadata,surface:config.surface||'mobile'},snapshot:snapshot(force),persistence,events:rows})}
|
|
88
|
+
const report=()=>makeReport(true)
|
|
89
|
+
function openDatabase(){
|
|
90
|
+
if(database)return database
|
|
91
|
+
if(!env.indexedDB)return Promise.resolve(null)
|
|
92
|
+
database=new Promise(resolve=>{
|
|
93
|
+
let settled=false,request
|
|
94
|
+
const done=value=>{if(settled){value?.close();return}settled=true;env.clearTimeout?.(deadline);resolve(value)}
|
|
95
|
+
const deadline=env.setTimeout?.(()=>done(null),1500)
|
|
96
|
+
try{request=env.indexedDB.open('dshRemoteDiagnosticsV1',1);request.onupgradeneeded=()=>request.result.createObjectStore('reports')
|
|
97
|
+
request.onsuccess=()=>{request.result.onversionchange=()=>{request.result.close();database=null};done(request.result)}
|
|
98
|
+
request.onerror=request.onblocked=()=>done(null)
|
|
99
|
+
}catch{done(null)}
|
|
100
|
+
})
|
|
101
|
+
return database
|
|
102
|
+
}
|
|
103
|
+
function transaction(db,mode,value){return new Promise(resolve=>{
|
|
104
|
+
let tx,result,settled=false
|
|
105
|
+
const done=value=>{if(settled)return;settled=true;env.clearTimeout?.(deadline);resolve(value)}
|
|
106
|
+
const deadline=env.setTimeout?.(()=>{done({ok:false,error:{name:'TimeoutError'}});try{tx?.abort()}catch{}},2000)
|
|
107
|
+
try{tx=db.transaction('reports',mode);const store=tx.objectStore('reports'),request=mode==='readonly'?store.get('latest'):store.put(value,'latest')
|
|
108
|
+
request.onsuccess=()=>{result=request.result}
|
|
109
|
+
tx.oncomplete=()=>done({ok:true,value:result});tx.onerror=tx.onabort=()=>done({ok:false,error:tx.error||{name:'UnknownError'}})
|
|
110
|
+
}catch(error){done({ok:false,error})}
|
|
111
|
+
})}
|
|
112
|
+
function persistFailure(backend,error){rows.push({at:now(),kind:'diagnostics.persist',phase:'failed',storageBackend:backend,...errorFacts(error)});trim()}
|
|
113
|
+
const restoredEpoch=epoch
|
|
114
|
+
const ready=openDatabase().then(async db=>{
|
|
115
|
+
if(!db){persistence.indexeddb='unavailable';return}
|
|
116
|
+
const saved=await transaction(db,'readonly')
|
|
117
|
+
if(saved.ok&&restoredEpoch===epoch){const previous=schema.sanitizeReport(saved.value),unique=new Map();for(const row of [...(previous?.events||[]),...rows])unique.set(JSON.stringify(row),row);rows=[...unique.values()].sort((a,b)=>a.at-b.at);trim()}
|
|
118
|
+
}).catch(()=>{persistence.indexeddb='failed'})
|
|
119
|
+
function backup(value){
|
|
120
|
+
pendingBackup=value
|
|
121
|
+
if(!backupJob)backupJob=(async()=>{
|
|
122
|
+
await ready;const db=await openDatabase()
|
|
123
|
+
if(!db){pendingBackup=null;persistence.indexeddb='unavailable';return}
|
|
124
|
+
while(pendingBackup){const value=makeReport();pendingBackup=null;const result=await transaction(db,'readwrite',value),previous=persistence.indexeddb;persistence.indexeddb=result.ok?'saved':'failed'
|
|
125
|
+
if(!result.ok&&previous!=='failed'){persistFailure('indexeddb',result.error);flush(false)}
|
|
126
|
+
}
|
|
127
|
+
})().catch(()=>{persistence.indexeddb='failed'}).finally(()=>{backupJob=null})
|
|
128
|
+
return backupJob
|
|
129
|
+
}
|
|
130
|
+
function flush(withBackup=true){
|
|
131
|
+
if(timer)env.clearTimeout?.(timer);timer=null
|
|
132
|
+
const previous=persistence.local
|
|
133
|
+
try{persistence.local='saved';const value=JSON.stringify(makeReport());env.localStorage.setItem(KEY,value);if(env.localStorage.getItem(KEY)!==value)throw Error('storage write unconfirmed');persistence.session='unknown';try{env.sessionStorage?.removeItem(KEY)}catch{}}
|
|
134
|
+
catch(error){persistence.local='failed';if(previous!=='failed')persistFailure('local',error)
|
|
135
|
+
try{persistence.session='saved';env.sessionStorage.setItem(KEY,JSON.stringify(makeReport()))}catch{persistence.session=env.sessionStorage?'failed':'unavailable'}
|
|
136
|
+
}
|
|
137
|
+
return withBackup?backup(makeReport()):Promise.resolve()
|
|
138
|
+
}
|
|
50
139
|
function record(kind,fields={}) {
|
|
51
140
|
if(!schema.kinds.has(kind))return
|
|
52
|
-
const row={at:now(),kind,...schema.facts({...fields,sessionRef:fields.sessionRef||pseudonym(fields.sessionId),serverRef:fields.serverRef||pseudonym(fields.server||env.location?.origin)})};rows.push(row);trim()
|
|
141
|
+
const row={at:now(),kind,...schema.facts({...fields,sessionRef:fields.sessionRef||pseudonym(fields.sessionId),serverRef:fields.serverRef||pseudonym(fields.server||env.location?.origin),announcementRef:fields.announcementRef||pseudonym(fields.announcementId)})};rows.push(row);trim()
|
|
53
142
|
if(fields.phase==='failed'||kind==='client.error'||fields.phase==='start'&&['session.open','session.back','history.load','history.render','history.cache'].includes(kind))flush()
|
|
54
143
|
else if(!timer)timer=env.setTimeout?.(flush,500)
|
|
55
144
|
return row
|
|
56
145
|
}
|
|
57
146
|
function errorFacts(error){
|
|
58
|
-
const message=String(error?.message||''),category=/auth|ticket|401|403/i.test(message)?'authentication':/timeout|abort/i.test(message+' '+error?.name)?'timeout':/network|fetch|socket/i.test(message)?'network':error?.name==='SyntaxError'?'syntax':'unknown',frames=[]
|
|
147
|
+
const message=typeof error==='string'?error:String(error?.message||''),category=/quota|storage|indexeddb/i.test(message+' '+error?.name)?'storage':/auth|ticket|401|403/i.test(message)?'authentication':/timeout|abort/i.test(message+' '+error?.name)?'timeout':/network|fetch|socket/i.test(message)?'network':/invalid.*payload|validation|schema/i.test(message)?'validation':error?.name==='SyntaxError'?'syntax':'unknown',frames=[]
|
|
59
148
|
for(const line of String(error?.stack||'').split('\n').slice(1,8)){const match=line.match(/(?:[/\\])(app|desktop|history|activity|turn-results|network|operations|diagnostics)\.js(?:\?[^\s:]*)?:(\d+):(\d+)\)?$/);if(match)frames.push({file:match[1]+'.js',line:Number(match[2]),column:Number(match[3])})}
|
|
60
149
|
return schema.facts({category,errorName:error?.name,frames,...(/^HTTP \d{3}$/.test(message)?{httpStatus:Number(message.slice(5))}:{})})
|
|
61
150
|
}
|
|
62
151
|
function start(kind,fields={}){const begun=now(),traceId=run.slice(0,12)+(++sequence).toString(16).padStart(12,'0');record(kind,{...fields,phase:'start',traceId});return {traceId,end:value=>record(kind,{...fields,...value,traceId,durationMs:now()-begun}),fail:error=>record(kind,{...fields,...errorFacts(error),phase:'failed',traceId,durationMs:now()-begun})}}
|
|
63
152
|
function nativeSnapshot(){try{const value=JSON.parse(env.NativeBackground?.getBackgroundConfig?.()||'{}');return schema.facts({...value,httpStatus:value.lastHttpStatus})}catch{return {}}}
|
|
64
153
|
function configure(value){config=value;record('client.lifecycle',{status:env.document?.visibilityState==='hidden'?'hidden':'visible',...nativeSnapshot()});mount()}
|
|
65
|
-
function clear(){rows=[];flush();refreshPreview()}
|
|
154
|
+
function clear(){epoch++;rows=[];droppedEvents=0;flush();refreshPreview()}
|
|
155
|
+
function storageFailure(key,error,backend='local'){const category=/^historyCache/.test(key)?'history':/^sessionsCache/.test(key)?'session-list':key==='seenAnnouncementsV1'?'seen':key==='announcementHistoryV1'?'history':key==='announcementVotesV1'?'votes':/^dshApprovalRecordsV1/.test(key)?'approvals':'settings';storageFacts(true);return record('storage.write',{phase:'failed',storageKey:category,storageBackend:backend,...errorFacts(error)})}
|
|
66
156
|
function text(){return JSON.stringify(report(),null,2)}
|
|
67
157
|
const label=(zh,en)=>env.I18N?.lang==='en'?en:zh
|
|
68
158
|
const $=id=>env.document?.getElementById(id)
|
|
@@ -84,7 +174,7 @@ function createDiagnosticSchema() {
|
|
|
84
174
|
const panel=details.closest('.client-diagnostics'),entry=env.document.createElement('button');entry.type='button';entry.className='workflow-button';entry.dataset.logLabel='entry';panel.parentNode.insertBefore(entry,panel);entry.addEventListener('click',show)
|
|
85
175
|
sheet=env.document.createElement('dialog');sheet.className='client-log-dialog';sheet.setAttribute('aria-labelledby','client-log-title')
|
|
86
176
|
const head=env.document.createElement('div');head.className='client-log-head';const title=env.document.createElement('h2');title.id='client-log-title';title.dataset.logLabel='title';const close=env.document.createElement('button');close.type='button';close.dataset.logLabel='close';close.addEventListener('click',()=>sheet.close());head.append(title,close);sheet.append(head,panel);env.document.body.append(sheet)
|
|
87
|
-
const labels={entry:['查看本地操作日志','View local operation logs'],title:['本地操作日志','Local operation logs'],close:['关闭','Close'],privacy:['
|
|
177
|
+
const labels={entry:['查看本地操作日志','View local operation logs'],title:['本地操作日志','Local operation logs'],close:['关闭','Close'],privacy:['操作日志默认保存在此设备。提交反馈时勾选诊断选项可附带脱敏日志,也可复制或导出。','Logs stay on this device by default. Select diagnostics when submitting feedback to attach a sanitized report, or copy/export it.'],details:['查看详细记录','View detailed records'],refresh:['刷新预览','Refresh preview'],copy:['复制日志','Copy report'],export:['导出日志','Export report'],clear:['清除日志','Clear report']}
|
|
88
178
|
const translate=()=>{for(const node of env.document.querySelectorAll('[data-log-label]')){const pair=labels[node.dataset.logLabel];if(pair)node.textContent=label(...pair)}}
|
|
89
179
|
translate();if(env.MutationObserver)new env.MutationObserver(translate).observe(env.document.documentElement,{attributes:true,attributeFilter:['lang']})
|
|
90
180
|
details.addEventListener('toggle',()=>{if(details.open)refreshPreview()})
|
|
@@ -93,13 +183,17 @@ function createDiagnosticSchema() {
|
|
|
93
183
|
$('fb-log-export')?.addEventListener('click',download)
|
|
94
184
|
$('fb-log-clear')?.addEventListener('click',clear)
|
|
95
185
|
}
|
|
96
|
-
env.addEventListener?.('error',event=>
|
|
186
|
+
env.addEventListener?.('error',event=>{
|
|
187
|
+
const facts=errorFacts(event.error||event.message),file=String(event.filename||'').split(/[\\/]/).at(-1).split('?')[0]
|
|
188
|
+
if(!facts.frames?.length&&['app.js','desktop.js','history.js','activity.js','turn-results.js','network.js','operations.js','diagnostics.js'].includes(file)&&Number.isSafeInteger(event.lineno)&&event.lineno>0&&Number.isSafeInteger(event.colno)&&event.colno>0)facts.frames=[{file,line:event.lineno,column:event.colno}]
|
|
189
|
+
record('client.error',{...facts,phase:'failed'})
|
|
190
|
+
})
|
|
97
191
|
env.addEventListener?.('unhandledrejection',event=>record('client.error',{...errorFacts(event.reason),phase:'failed'}))
|
|
98
192
|
for(const status of ['online','offline'])env.addEventListener?.(status,()=>record('client.lifecycle',{status,online:status==='online'}))
|
|
99
193
|
env.document?.addEventListener('visibilitychange',()=>{record('client.lifecycle',{status:env.document.visibilityState==='visible'?'visible':'hidden',...nativeSnapshot()});flush()})
|
|
100
194
|
env.addEventListener?.('pagehide',flush)
|
|
101
195
|
function build(value){metadata={version:value?.version,buildId:value?.buildId}}
|
|
102
|
-
return {record,start,errorFacts,report,text,flush,clear,configure,show,download,build,nativeSnapshot}
|
|
196
|
+
return {record,start,errorFacts,report,text,flush,clear,configure,show,download,build,nativeSnapshot,storageFailure,storageFacts,ready}
|
|
103
197
|
}
|
|
104
198
|
if(typeof module!=='undefined'&&module.exports)module.exports={createDiagnostics,createDiagnosticSchema}
|
|
105
199
|
else {
|
package/public/history.js
CHANGED
|
@@ -163,10 +163,13 @@
|
|
|
163
163
|
if(database)return database
|
|
164
164
|
database=new Promise(resolve=>{
|
|
165
165
|
if(typeof indexedDB==='undefined'){resolve(null);return}
|
|
166
|
-
|
|
166
|
+
let request,settled=false
|
|
167
|
+
const done=db=>{if(settled){db?.close();return}settled=true;clearTimeout(timer);resolve(db)}
|
|
168
|
+
const timer=setTimeout(()=>done(null),1500)
|
|
169
|
+
try{request=indexedDB.open('dshRemoteHistoryV1',1)}catch{done(null);return}
|
|
167
170
|
request.onupgradeneeded=()=>{const store=request.result.createObjectStore('history',{keyPath:'key'});store.createIndex('scopeTime',['scope','updatedAt'])}
|
|
168
|
-
request.onsuccess=()=>{
|
|
169
|
-
request.onerror=request.onblocked=()=>
|
|
171
|
+
request.onsuccess=()=>{request.result.onversionchange=()=>{request.result.close();database=null};done(request.result)}
|
|
172
|
+
request.onerror=request.onblocked=()=>done(null)
|
|
170
173
|
})
|
|
171
174
|
return database
|
|
172
175
|
}
|
|
@@ -185,7 +188,7 @@
|
|
|
185
188
|
if(db){const value=await new Promise(resolve=>{
|
|
186
189
|
let tx,settled=false
|
|
187
190
|
const done=value=>{if(settled)return;settled=true;clearTimeout(timer);resolve(value)}
|
|
188
|
-
|
|
191
|
+
const timer=setTimeout(()=>{globalThis.DshDiagnostics?.storageFailure(scope,{name:'TimeoutError'},'indexeddb');done(null);try{tx?.abort()}catch{}},1500)
|
|
189
192
|
try{tx=db.transaction('history');const request=tx.objectStore('history').get(key);request.onsuccess=()=>done(request.result);request.onerror=tx.onabort=tx.onerror=()=>done(null)}catch{done(null)}
|
|
190
193
|
});if(value)return value}
|
|
191
194
|
try{const value=JSON.parse(localStorage.getItem(key)||'null');if(value)return value}catch{}
|
|
@@ -200,22 +203,55 @@
|
|
|
200
203
|
if(epoch!==cacheEpoch)return false
|
|
201
204
|
if(db)try{const saved=await new Promise(resolve=>{
|
|
202
205
|
const tx=db.transaction('history','readwrite'),store=tx.objectStore('history');store.put(data)
|
|
206
|
+
let settled=false
|
|
207
|
+
const done=value=>{if(settled)return;settled=true;clearTimeout(timer);resolve(value)}
|
|
208
|
+
const timer=setTimeout(()=>{done(false);try{tx.abort()}catch{}},1500)
|
|
203
209
|
let count=0;const request=store.index('scopeTime').openKeyCursor(IDBKeyRange.bound([scope,0],[scope,Number.MAX_SAFE_INTEGER]),'prev')
|
|
204
210
|
request.onsuccess=()=>{const cursor=request.result;if(!cursor)return;if(++count>10)store.delete(cursor.primaryKey);cursor.continue()}
|
|
205
|
-
tx.oncomplete=()=>
|
|
206
|
-
});if(saved)return true}catch{}
|
|
211
|
+
tx.oncomplete=()=>done(true);tx.onabort=tx.onerror=()=>{globalThis.DshDiagnostics?.storageFailure(scope,tx.error||{name:'UnknownError'},'indexeddb');done(false)}
|
|
212
|
+
});if(saved)return true}catch(error){globalThis.DshDiagnostics?.storageFailure(scope,error,'indexeddb')}
|
|
207
213
|
if(epoch!==cacheEpoch)return false
|
|
208
214
|
try{
|
|
209
215
|
const indexKey=scope+':cache-index',index=JSON.parse(localStorage.getItem(indexKey)||'[]').filter(item=>item!==key),serialized=JSON.stringify(data)
|
|
210
|
-
|
|
216
|
+
let diagnosed=false
|
|
217
|
+
while(true){try{localStorage.setItem(key,serialized);break}catch(error){if(!diagnosed){diagnosed=true;globalThis.DshDiagnostics?.storageFailure(scope,error)}if(!index.length)throw error;localStorage.removeItem(index.pop())}}
|
|
211
218
|
index.unshift(key)
|
|
212
219
|
for(const removed of index.splice(10))localStorage.removeItem(removed)
|
|
213
220
|
localStorage.setItem(indexKey,JSON.stringify(index));return kept.length>0
|
|
214
221
|
}catch{return false}
|
|
215
222
|
}
|
|
216
223
|
async function cacheRemove(scope,id) {const key=cacheKey(scope,id);try{localStorage.removeItem(key)}catch{};const db=await openDatabase();if(db)try{db.transaction('history','readwrite').objectStore('history').delete(key)}catch{}}
|
|
217
|
-
async function
|
|
218
|
-
|
|
224
|
+
async function cacheInspect(mode,action,fallback) {
|
|
225
|
+
const db=await openDatabase();if(!db)return fallback
|
|
226
|
+
return new Promise(resolve=>{
|
|
227
|
+
let tx,value=fallback,settled=false
|
|
228
|
+
const done=result=>{if(settled)return;settled=true;clearTimeout(timer);resolve(result)}
|
|
229
|
+
const timer=setTimeout(()=>{done(fallback);try{tx?.abort()}catch{}},1500)
|
|
230
|
+
try{tx=db.transaction('history',mode);tx.oncomplete=()=>done(value);tx.onabort=tx.onerror=()=>done(fallback);action(tx.objectStore('history'),result=>{value=result})}catch{done(fallback)}
|
|
231
|
+
})
|
|
232
|
+
}
|
|
233
|
+
async function cacheStats() {
|
|
234
|
+
const rows=new Map(),bytes=value=>{const text=JSON.stringify(value);return typeof TextEncoder==='function'?new TextEncoder().encode(text).length:text.length*2}
|
|
235
|
+
const available=await cacheInspect('readonly',(store,result)=>{
|
|
236
|
+
const request=store.openCursor()
|
|
237
|
+
request.onsuccess=()=>{const cursor=request.result;if(!cursor){result(true);return}rows.set(cursor.primaryKey,bytes(cursor.value));cursor.continue()}
|
|
238
|
+
},false)
|
|
239
|
+
try{for(const key of Object.keys(localStorage))if(key.includes(':session:')||/^(?:(?:history|sessions)Cache|dsh-remote-(?:sessions|history))/.test(key)){
|
|
240
|
+
if(key.endsWith(':cache-index'))continue
|
|
241
|
+
const text=localStorage.getItem(key);if(text&&!rows.has(key))rows.set(key,typeof TextEncoder==='function'?new TextEncoder().encode(text).length:text.length*2)
|
|
242
|
+
}}catch{}
|
|
243
|
+
return {available:available||typeof indexedDB==='undefined',count:rows.size,bytes:[...rows.values()].reduce((a,b)=>a+b,0)}
|
|
244
|
+
}
|
|
245
|
+
async function cacheClear(scope) {
|
|
246
|
+
cacheEpoch++
|
|
247
|
+
try{for(const key of Object.keys(localStorage))if(scope===undefined?(key.includes(':session:')||key.endsWith(':cache-index')||/^(?:(?:history|sessions)Cache|dsh-remote-(?:sessions|history))/.test(key)):(key===scope||key.startsWith(scope+':')||key===scope.replace(/^history/,'sessions')))localStorage.removeItem(key)}catch{}
|
|
248
|
+
return cacheInspect('readwrite',(store,result)=>{
|
|
249
|
+
if(scope===undefined){store.clear();result(true);return}
|
|
250
|
+
const request=store.openCursor()
|
|
251
|
+
request.onsuccess=()=>{const cursor=request.result;if(!cursor){result(true);return}if(cursor.value.scope===scope)cursor.delete();cursor.continue()}
|
|
252
|
+
},typeof indexedDB==='undefined')
|
|
253
|
+
}
|
|
254
|
+
const api={HistoryView,reconcile,insertSorted,signature,cacheLoad,cacheSave,cacheRemove,cacheClear,cacheStats,decodeLegacy,WINDOW_SIZE}
|
|
219
255
|
if(typeof module!=='undefined'&&module.exports)module.exports=api
|
|
220
256
|
else root.DshHistory=api
|
|
221
257
|
})(typeof window==='undefined'?globalThis:window)
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
/* Persistent chat images. Native IndexedDB only; credentials never enter records. */
|
|
2
|
+
'use strict';
|
|
3
|
+
;(function(root){
|
|
4
|
+
const LIMIT=200*1024*1024, ITEM_LIMIT=12*1024*1024, MAX_ITEMS=500, MAX_AGE=30*86400000, TIMEOUT=1500
|
|
5
|
+
let database, epoch=0
|
|
6
|
+
const pending=new Map(),scopeEpoch=new Map()
|
|
7
|
+
const versionOf=scope=>epoch+':'+(scopeEpoch.get(scope)||0)
|
|
8
|
+
const CONTROL='!cache-control',revisionOf=(control,scope)=>(control?.all||0)+':'+(control?.scopes?.[scope]||0)
|
|
9
|
+
function open(){
|
|
10
|
+
if(database)return database
|
|
11
|
+
database=new Promise(resolve=>{
|
|
12
|
+
let request,settled=false
|
|
13
|
+
const finish=db=>{if(settled){db?.close();return}settled=true;clearTimeout(timer);resolve(db)}
|
|
14
|
+
const timer=setTimeout(()=>finish(null),TIMEOUT)
|
|
15
|
+
try{
|
|
16
|
+
request=root.indexedDB.open('dshRemoteImagesV1',1)
|
|
17
|
+
request.onupgradeneeded=()=>request.result.createObjectStore('images',{keyPath:'key'}).createIndex('accessedAt','accessedAt')
|
|
18
|
+
request.onsuccess=()=>{const db=request.result;db.onversionchange=()=>{db.close();database=null};finish(db)}
|
|
19
|
+
request.onerror=request.onblocked=()=>finish(null)
|
|
20
|
+
}catch{finish(null)}
|
|
21
|
+
})
|
|
22
|
+
return database
|
|
23
|
+
}
|
|
24
|
+
async function transaction(mode,action,fallback){
|
|
25
|
+
const db=await open()
|
|
26
|
+
if(!db)return fallback
|
|
27
|
+
return new Promise(resolve=>{
|
|
28
|
+
let tx,value=fallback,settled=false
|
|
29
|
+
const finish=result=>{if(settled)return;settled=true;clearTimeout(timer);resolve(result)}
|
|
30
|
+
const timer=setTimeout(()=>{finish(fallback);try{tx?.abort()}catch{}},TIMEOUT)
|
|
31
|
+
try{
|
|
32
|
+
tx=db.transaction('images',mode)
|
|
33
|
+
tx.oncomplete=()=>finish(value);tx.onerror=tx.onabort=()=>finish(fallback)
|
|
34
|
+
action(tx.objectStore('images'),result=>{value=result})
|
|
35
|
+
}catch{finish(fallback);try{tx?.abort()}catch{}}
|
|
36
|
+
})
|
|
37
|
+
}
|
|
38
|
+
const keyOf=(scope,id)=>JSON.stringify([scope,id])
|
|
39
|
+
const usable=row=>row?.blob instanceof root.Blob && row.blob.size>0 && row.blob.size<=ITEM_LIMIT && /^image\/(?:png|jpeg|webp|gif|bmp|avif|svg\+xml)$/.test(row.blob.type)
|
|
40
|
+
async function read(key,scope){
|
|
41
|
+
return transaction('readwrite',(store,result)=>{
|
|
42
|
+
const snapshot={row:null,revision:'0:0'};result(snapshot)
|
|
43
|
+
const control=store.get(CONTROL)
|
|
44
|
+
control.onsuccess=()=>{snapshot.revision=revisionOf(control.result,scope)}
|
|
45
|
+
const request=store.get(key)
|
|
46
|
+
request.onsuccess=()=>{
|
|
47
|
+
const row=request.result
|
|
48
|
+
if(!usable(row)||!Number.isFinite(row.accessedAt)||Date.now()-row.accessedAt>MAX_AGE){if(row)store.delete(key);return}
|
|
49
|
+
row.accessedAt=Date.now();store.put(row);snapshot.row=row
|
|
50
|
+
}
|
|
51
|
+
},{row:null,revision:null})
|
|
52
|
+
}
|
|
53
|
+
async function save(row,version,valid,revision,retry=true){
|
|
54
|
+
if(revision===null||!usable(row)||version!==versionOf(row.scope)||!valid())return false
|
|
55
|
+
const saved=await transaction('readwrite',(store,result)=>{
|
|
56
|
+
if(version!==versionOf(row.scope)||!valid())return
|
|
57
|
+
const control=store.get(CONTROL)
|
|
58
|
+
control.onsuccess=()=>{
|
|
59
|
+
// A clear in another tab must also invalidate this outstanding download.
|
|
60
|
+
if(revision!==revisionOf(control.result,row.scope)){result('cleared');return}
|
|
61
|
+
store.put(row)
|
|
62
|
+
const rows=[];let bytes=0
|
|
63
|
+
const request=store.index('accessedAt').openCursor()
|
|
64
|
+
request.onsuccess=()=>{
|
|
65
|
+
const cursor=request.result
|
|
66
|
+
if(cursor){if(cursor.primaryKey===CONTROL){cursor.continue();return}const value=cursor.value;if(!usable(value)||!Number.isFinite(value.accessedAt)||Date.now()-value.accessedAt>MAX_AGE)cursor.delete();else{rows.push({key:cursor.primaryKey,size:value.blob.size});bytes+=value.blob.size}cursor.continue();return}
|
|
67
|
+
while(bytes>LIMIT||rows.length>MAX_ITEMS){const old=rows.shift();bytes-=old.size;store.delete(old.key)}
|
|
68
|
+
result(true)
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
},false)
|
|
72
|
+
if(saved||!retry||version!==versionOf(row.scope)||!valid())return saved
|
|
73
|
+
// Browser quota may be lower than our cap. Free oldest images and retry once.
|
|
74
|
+
const freed=await transaction('readwrite',(store,result)=>{
|
|
75
|
+
if(version!==versionOf(row.scope)||!valid())return
|
|
76
|
+
let bytes=0
|
|
77
|
+
const request=store.index('accessedAt').openCursor()
|
|
78
|
+
request.onsuccess=()=>{const cursor=request.result;if(!cursor||bytes>=row.blob.size){result(true);return}if(cursor.primaryKey!==CONTROL){bytes+=cursor.value.blob?.size||0;cursor.delete()}cursor.continue()}
|
|
79
|
+
},false)
|
|
80
|
+
return freed?save(row,version,valid,revision,false):false
|
|
81
|
+
}
|
|
82
|
+
async function load(scope,id,loader,{revalidate=false,valid=()=>true}={}){
|
|
83
|
+
if(!scope||!id)throw Error('Missing image identity')
|
|
84
|
+
const key=keyOf(scope,id),version=versionOf(scope)
|
|
85
|
+
const check=()=>{if(version!==versionOf(scope)||!valid())throw Error('stale image')}
|
|
86
|
+
check()
|
|
87
|
+
if(pending.has(key)){const value=await pending.get(key);check();return value}
|
|
88
|
+
const job=(async()=>{
|
|
89
|
+
const snapshot=await read(key,scope),cached=snapshot.row;check()
|
|
90
|
+
if(cached&&!revalidate)return cached
|
|
91
|
+
let value=cached
|
|
92
|
+
if(!cached||revalidate){
|
|
93
|
+
try{value=await loader(cached)}catch(error){
|
|
94
|
+
// Offline reuse is allowed, authentication or missing-file failures are not.
|
|
95
|
+
if(!cached||error.status||error.message==='stale image'){
|
|
96
|
+
if(cached&&error.status)await transaction('readwrite',store=>store.delete(key),false)
|
|
97
|
+
throw error
|
|
98
|
+
}
|
|
99
|
+
value=cached
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
check()
|
|
103
|
+
if(!(value?.blob instanceof root.Blob)||!value.blob.size||!/^image\/(?:png|jpeg|webp|gif|bmp|avif|svg\+xml)$/.test(value.blob.type))throw Error('Invalid image data')
|
|
104
|
+
const saved=await save({key,scope,blob:value.blob,etag:String(value.etag||'').slice(0,512),lastModified:String(value.lastModified||'').slice(0,128),accessedAt:Date.now()},version,valid,snapshot.revision)
|
|
105
|
+
if(saved==='cleared')throw Error('stale image')
|
|
106
|
+
check();return value
|
|
107
|
+
})()
|
|
108
|
+
pending.set(key,job)
|
|
109
|
+
try{return await job}finally{if(pending.get(key)===job)pending.delete(key)}
|
|
110
|
+
}
|
|
111
|
+
async function clear(scope){
|
|
112
|
+
if(scope===undefined){epoch++;pending.clear();scopeEpoch.clear()}
|
|
113
|
+
else{scopeEpoch.set(scope,(scopeEpoch.get(scope)||0)+1);for(const key of pending.keys())if(JSON.parse(key)[0]===scope)pending.delete(key)}
|
|
114
|
+
return transaction('readwrite',(store,result)=>{
|
|
115
|
+
const request=store.get(CONTROL)
|
|
116
|
+
request.onsuccess=()=>{
|
|
117
|
+
const control=request.result||{key:CONTROL,all:0,scopes:{}}
|
|
118
|
+
if(scope===undefined){control.all++;control.scopes={};store.clear();store.put(control);result(true);return}
|
|
119
|
+
control.scopes[scope]=(control.scopes[scope]||0)+1;store.put(control)
|
|
120
|
+
const rows=store.openCursor()
|
|
121
|
+
rows.onsuccess=()=>{const cursor=rows.result;if(!cursor){result(true);return}if(cursor.value.scope===scope)cursor.delete();cursor.continue()}
|
|
122
|
+
}
|
|
123
|
+
},false)
|
|
124
|
+
}
|
|
125
|
+
async function stats(){
|
|
126
|
+
return transaction('readwrite',(store,result)=>{
|
|
127
|
+
let count=0,bytes=0
|
|
128
|
+
const request=store.openCursor()
|
|
129
|
+
request.onsuccess=()=>{
|
|
130
|
+
const cursor=request.result
|
|
131
|
+
if(!cursor){result({available:true,count,bytes,limitBytes:LIMIT});return}
|
|
132
|
+
if(cursor.primaryKey===CONTROL){cursor.continue();return}
|
|
133
|
+
const row=cursor.value
|
|
134
|
+
if(!usable(row)||!Number.isFinite(row.accessedAt)||Date.now()-row.accessedAt>MAX_AGE)cursor.delete()
|
|
135
|
+
else{count++;bytes+=row.blob.size}
|
|
136
|
+
cursor.continue()
|
|
137
|
+
}
|
|
138
|
+
},{available:false,count:0,bytes:0,limitBytes:LIMIT})
|
|
139
|
+
}
|
|
140
|
+
root.DshImageCache={load,clear,stats,limitBytes:LIMIT,itemLimitBytes:ITEM_LIMIT}
|
|
141
|
+
})(typeof window==='undefined'?globalThis:window)
|
package/public/image-preview.js
CHANGED
|
@@ -3,7 +3,8 @@
|
|
|
3
3
|
;(function(root){
|
|
4
4
|
const english=()=>root.I18N?.lang==='en'
|
|
5
5
|
let lightbox=null,stage=null,image=null,closeButton=null,hint=null,opener=null
|
|
6
|
-
let resolver=null,attachmentResolver=null,observer=null,mutation=null
|
|
6
|
+
let resolver=null,attachmentResolver=null,capture=null,observer=null,mutation=null,generation=0
|
|
7
|
+
const objectUrls=new Map()
|
|
7
8
|
const escape=value=>String(value??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]))
|
|
8
9
|
function attachmentHtml(attachment,label,sessionId){
|
|
9
10
|
if(!/^(?:sha256:)?[a-f0-9]{64}$/.test(attachment?.attachmentId||''))return '<span class="chat-image-status">'+escape(label)+'</span>'
|
|
@@ -53,10 +54,16 @@
|
|
|
53
54
|
function configure(options={}){
|
|
54
55
|
if(typeof options.resolvePath==='function')resolver=options.resolvePath
|
|
55
56
|
if(typeof options.resolveAttachment==='function')attachmentResolver=options.resolveAttachment
|
|
57
|
+
if(typeof options.capture==='function')capture=options.capture
|
|
56
58
|
if(!mutation&&typeof root.MutationObserver==='function'&&root.document?.body){
|
|
57
59
|
// History renders (paging, streaming, cache restore) replace nodes without a full render call.
|
|
58
60
|
mutation=new root.MutationObserver(records=>{
|
|
59
|
-
for(const record of records)
|
|
61
|
+
for(const record of records){
|
|
62
|
+
for(const node of record.addedNodes)if(node?.nodeType===1)hydrate(node)
|
|
63
|
+
if(record.removedNodes?.length)Promise.resolve().then(()=>{
|
|
64
|
+
for(const [button,url] of objectUrls)if(button.isConnected===false){root.URL?.revokeObjectURL?.(url);objectUrls.delete(button)}
|
|
65
|
+
})
|
|
66
|
+
}
|
|
60
67
|
})
|
|
61
68
|
mutation.observe(root.document.body,{childList:true,subtree:true})
|
|
62
69
|
}
|
|
@@ -90,9 +97,40 @@
|
|
|
90
97
|
const path=button.dataset.chatImagePath
|
|
91
98
|
const attachmentId=button.dataset.chatImageAttachment
|
|
92
99
|
if(attachmentId?!attachmentResolver:(!path||!resolver))return
|
|
100
|
+
const identity=capture?.(),version=generation
|
|
101
|
+
const valid=()=>version===generation&&button.isConnected!==false&&(!identity||identity.valid())
|
|
93
102
|
try{
|
|
94
103
|
let url
|
|
95
|
-
if(
|
|
104
|
+
if(root.DshImageCache&&identity?.scope){
|
|
105
|
+
// Scope includes the connection credential hash; attachments are also session-scoped.
|
|
106
|
+
const request=attachmentId?null:await resolver(path)
|
|
107
|
+
if(!valid())return
|
|
108
|
+
const target=typeof request==='string'?{url:request}:request||{}
|
|
109
|
+
const id=attachmentId?JSON.stringify(['attachment',button.dataset.chatImageSession,attachmentId]):JSON.stringify(['path',target.url])
|
|
110
|
+
const value=await root.DshImageCache.load(identity.scope,id,async cached=>{
|
|
111
|
+
if(!valid())throw Error('stale image')
|
|
112
|
+
if(attachmentId){
|
|
113
|
+
const result=await attachmentResolver(attachmentId,button.dataset.chatImageSession)
|
|
114
|
+
if(result?.attachment?.attachmentId!==attachmentId||!/^image\/(?:png|jpeg|webp|gif)$/.test(result.attachment.mediaType)||typeof result.data!=='string'||!result.data||result.data.length>16*1024*1024||!/^[A-Za-z0-9+/]*={0,2}$/.test(result.data))throw Object.assign(Error('invalid image attachment'),{status:422})
|
|
115
|
+
const binary=root.atob(result.data),bytes=new Uint8Array(binary.length)
|
|
116
|
+
for(let i=0;i<binary.length;i++)bytes[i]=binary.charCodeAt(i)
|
|
117
|
+
return {blob:new root.Blob([bytes],{type:result.attachment.mediaType})}
|
|
118
|
+
}
|
|
119
|
+
const headers={...target.headers}
|
|
120
|
+
if(cached?.etag)headers['If-None-Match']=cached.etag
|
|
121
|
+
else if(cached?.lastModified)headers['If-Modified-Since']=cached.lastModified
|
|
122
|
+
const read=async signal=>{
|
|
123
|
+
const response=await (root.fetch||fetch)(target.url,{headers,signal,cache:'no-cache'})
|
|
124
|
+
if(response.status===304&&cached)return cached
|
|
125
|
+
if(!response.ok)throw Object.assign(Error('HTTP '+response.status),{status:response.status})
|
|
126
|
+
return {blob:await response.blob(),etag:response.headers?.get('etag'),lastModified:response.headers?.get('last-modified')}
|
|
127
|
+
}
|
|
128
|
+
return root.DshNetwork?.readWithDeadline?root.DshNetwork.readWithDeadline(read,45000):read(root.AbortSignal?.timeout?.(45000))
|
|
129
|
+
},{revalidate:!attachmentId,valid})
|
|
130
|
+
if(!valid())return
|
|
131
|
+
url=root.URL.createObjectURL(value.blob)
|
|
132
|
+
objectUrls.set(button,url)
|
|
133
|
+
}else if(attachmentId){
|
|
96
134
|
const result=await attachmentResolver(attachmentId,button.dataset.chatImageSession)
|
|
97
135
|
if(result?.attachment?.attachmentId!==attachmentId||!/^image\/(?:png|jpeg|webp|gif)$/.test(result.attachment.mediaType)||typeof result.data!=='string'||!result.data||result.data.length>16*1024*1024||!/^[A-Za-z0-9+/]*={0,2}$/.test(result.data))throw new Error('invalid image attachment')
|
|
98
136
|
url='data:'+result.attachment.mediaType+';base64,'+result.data
|
|
@@ -105,7 +143,9 @@
|
|
|
105
143
|
if(!blob||!blob.size)throw new Error('empty image')
|
|
106
144
|
url=root.URL?.createObjectURL?root.URL.createObjectURL(blob):''
|
|
107
145
|
if(!url)throw new Error('no blob url')
|
|
146
|
+
objectUrls.set(button,url)
|
|
108
147
|
}
|
|
148
|
+
if(!valid()){release(button);return}
|
|
109
149
|
const node=root.document.createElement('img')
|
|
110
150
|
node.src=url;node.alt=button.dataset.chatImageAlt||'';node.draggable=false;node.loading='lazy'
|
|
111
151
|
node.addEventListener('error',()=>pathImageFailed(button))
|
|
@@ -113,9 +153,12 @@
|
|
|
113
153
|
button.replaceChildren(node)
|
|
114
154
|
button.dataset.chatImageLoaded='1'
|
|
115
155
|
delete button.dataset.chatImagePath
|
|
116
|
-
}catch(error){pathImageFailed(button)}
|
|
156
|
+
}catch(error){if(valid())pathImageFailed(button)}
|
|
117
157
|
}
|
|
158
|
+
function release(button){const url=objectUrls.get(button);if(url)root.URL?.revokeObjectURL?.(url);objectUrls.delete(button)}
|
|
159
|
+
function reset(){generation++;close();for(const button of objectUrls.keys())release(button)}
|
|
118
160
|
function pathImageFailed(button){
|
|
161
|
+
release(button)
|
|
119
162
|
button.classList.remove('is-loading')
|
|
120
163
|
button.classList.add('is-error')
|
|
121
164
|
const status=button.querySelector?.('.chat-image-status')
|
|
@@ -143,6 +186,6 @@
|
|
|
143
186
|
})
|
|
144
187
|
return lightbox
|
|
145
188
|
}
|
|
146
|
-
root.DshImagePreview={open,close,isOpen,zoom:toggleZoom,mount:elements,configure,hydrate,attachmentHtml}
|
|
189
|
+
root.DshImagePreview={open,close,isOpen,zoom:toggleZoom,mount:elements,configure,hydrate,attachmentHtml,reset}
|
|
147
190
|
root.document?.addEventListener('DOMContentLoaded',()=>{elements();hydrate(root.document)})
|
|
148
191
|
})(typeof window==='undefined'?globalThis:window)
|