@hyprnos/dsh-remote-plugin 0.0.0-stage → 0.8.9
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.en.md +61 -0
- package/README.md +60 -2
- package/apk/dsh-remote.apk +0 -0
- package/approval-summary.mjs +115 -0
- package/client.js +197 -0
- package/cordis.patch.yml +5 -0
- package/doctor-skill.mjs +99 -0
- package/doctor-target.mjs +24 -0
- package/file-delivery.mjs +84 -0
- package/gateway-stats.cjs +501 -0
- package/gateway.cjs +8451 -0
- package/index.mjs +1788 -0
- package/insights.mjs +111 -0
- package/market.mjs +86 -0
- package/package.json +73 -4
- package/peak-reminders.mjs +50 -0
- package/plugin-center.mjs +777 -0
- package/plugin-transaction.mjs +300 -0
- package/public/activity.js +188 -0
- package/public/admin.html +820 -0
- package/public/admin.js +1167 -0
- package/public/announcement-forms.js +89 -0
- package/public/announcements.json +464 -0
- package/public/app.js +8826 -0
- package/public/approval-records.js +301 -0
- package/public/approval-summary.js +78 -0
- package/public/build.json +5 -0
- package/public/cache-upgrade.js +51 -0
- package/public/chat-copy.js +59 -0
- package/public/chat-files.js +87 -0
- package/public/desktop/desktop.css +816 -0
- package/public/desktop/desktop.html +871 -0
- package/public/desktop/desktop.js +4548 -0
- package/public/desktop/i18n.js +85 -0
- package/public/diagnostics.js +203 -0
- package/public/doctor-entry.js +94 -0
- package/public/doctor.css +205 -0
- package/public/doctor.js +769 -0
- package/public/donate.png +0 -0
- package/public/e2ee-transport.js +219 -0
- package/public/extensions.css +109 -0
- package/public/extensions.js +215 -0
- package/public/file-inbox.css +66 -0
- package/public/file-inbox.js +289 -0
- package/public/genui.css +8 -0
- package/public/genui.js +254 -0
- package/public/history.js +304 -0
- package/public/i18n.js +57 -0
- package/public/icon.svg +12 -0
- package/public/image-cache.js +141 -0
- package/public/image-preview.js +290 -0
- package/public/index.html +1568 -0
- package/public/insights.css +28 -0
- package/public/insights.js +290 -0
- package/public/jsqr.min.js +10104 -0
- package/public/lan-discovery.js +94 -0
- package/public/link-check.js +109 -0
- package/public/manifest.webmanifest +16 -0
- package/public/md.js +333 -0
- package/public/morphicons-init.js +41 -0
- package/public/motion.js +557 -0
- package/public/network.js +100 -0
- package/public/onboarding.css +36 -0
- package/public/onboarding.js +253 -0
- package/public/operations.js +141 -0
- package/public/permission-presets.js +159 -0
- package/public/plugin-center.css +120 -0
- package/public/plugin-center.js +666 -0
- package/public/plugin-icon.svg +5 -0
- package/public/plugin.html +68 -0
- package/public/plugin.js +211 -0
- package/public/qrcode.min.js +2297 -0
- package/public/relay-autopair.js +251 -0
- package/public/relay-devices.js +80 -0
- package/public/relay-settings.css +24 -0
- package/public/relay-settings.js +194 -0
- package/public/remote-state.js +27 -0
- package/public/remote-ui.css +148 -0
- package/public/remote-ui.js +243 -0
- package/public/session-deck.css +79 -0
- package/public/session-deck.js +180 -0
- package/public/session-presets.js +47 -0
- package/public/setup.css +18 -0
- package/public/setup.js +213 -0
- package/public/sha256.js +119 -0
- package/public/skills.css +81 -0
- package/public/skills.js +202 -0
- package/public/skins/blue-fish/DESIGN.md +24 -0
- package/public/skins/blue-fish/face.png +0 -0
- package/public/skins/blue-fish/icon-blush.png +0 -0
- package/public/skins/blue-fish/icon-sleep.png +0 -0
- package/public/skins/blue-fish/icon-smile.png +0 -0
- package/public/skins/blue-fish/icon-star.png +0 -0
- package/public/skins/blue-fish/icon-wink.png +0 -0
- package/public/skins/blue-fish/icon.png +0 -0
- package/public/skins/blue-fish/mascot.png +0 -0
- package/public/skins/blue-fish/pattern.png +0 -0
- package/public/skins/blue-fish/preview.html +12 -0
- package/public/skins/blue-fish/skin.css +122 -0
- 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 +55 -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 +56 -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 +56 -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 +12 -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 +56 -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 +21 -0
- package/public/styles.css +1526 -0
- package/public/subagents.css +61 -0
- package/public/subagents.js +275 -0
- package/public/task-board.js +109 -0
- package/public/teams.js +98 -0
- package/public/theme-picker.css +58 -0
- package/public/theme-vars.css +1044 -0
- package/public/theme.js +166 -0
- package/public/transcribe-core.js +74 -0
- package/public/turn-results.js +121 -0
- package/public/update.json +49 -0
- package/public/vendor/gsap/NOTICE.md +10 -0
- package/public/vendor/gsap/gsap.min.js +11 -0
- package/public/vendor/morphicons/LICENSE +21 -0
- package/public/vendor/morphicons/README.md +10 -0
- package/public/vendor/morphicons/controller-CXZuwJ_M.js +152 -0
- package/public/vendor/morphicons/dom.js +206 -0
- package/public/vendor/morphicons/element.js +261 -0
- package/public/vendor/morphicons/normalize-CYnN3Npw.js +540 -0
- package/public/vendor/morphicons/spring-CFHloqPP.js +623 -0
- package/public/version.json +3 -0
- package/public/voice-input.js +1151 -0
- package/public/workflow.css +365 -0
- package/public/workflow.js +419 -0
- package/session-file.mjs +39 -0
- package/skills/dsh-remote-doctor/SKILL.md +186 -0
- package/skills/dsh-remote-doctor/references/wiki/README.md +40 -0
- package/skills/dsh-remote-doctor/references/wiki/ai-guide.md +61 -0
- package/skills/dsh-remote-doctor/references/wiki/connection.md +76 -0
- package/skills/dsh-remote-doctor/references/wiki/errors.md +26 -0
- package/skills/dsh-remote-doctor/references/wiki/evidence.md +44 -0
- package/skills/dsh-remote-doctor/references/wiki/files.md +31 -0
- package/skills/dsh-remote-doctor/references/wiki/maintenance.md +30 -0
- package/skills/dsh-remote-doctor/references/wiki/notifications.md +33 -0
- package/skills/dsh-remote-doctor/references/wiki/operations.md +32 -0
- package/skills/dsh-remote-doctor/references/wiki/plugins.md +90 -0
- package/skills/dsh-remote-doctor/references/wiki/sessions.md +45 -0
- package/skills/dsh-remote-doctor/references/wiki/sources.md +27 -0
- package/skills.mjs +53 -0
- package/speech-whisper.mjs +705 -0
- package/task-board.mjs +57 -0
- package/teams.mjs +58 -0
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
/* Shared bounded conversation rendering and asynchronous local cache. No dependencies. */
|
|
2
|
+
'use strict';
|
|
3
|
+
;(function(root) {
|
|
4
|
+
const WINDOW_SIZE = 180, WINDOW_STEP = 60, fingerprints = new WeakMap()
|
|
5
|
+
function signature(entry) {
|
|
6
|
+
if (!fingerprints.has(entry)) fingerprints.set(entry, JSON.stringify([entry.seq, entry.event, entry.view]))
|
|
7
|
+
return fingerprints.get(entry)
|
|
8
|
+
}
|
|
9
|
+
function reconcile(previous, incoming, floor = -Infinity, retainOlder = true, ceiling = Infinity) {
|
|
10
|
+
const old = new Map(previous.map(entry => [entry.seq, entry]))
|
|
11
|
+
const next = new Map(previous.filter(entry => entry.seq >= ceiling || (retainOlder && entry.seq < floor)).map(entry => [entry.seq, entry]))
|
|
12
|
+
for (const entry of incoming) {
|
|
13
|
+
const existing = old.get(entry.seq)
|
|
14
|
+
next.set(entry.seq, existing && signature(existing) === signature(entry) ? existing : entry)
|
|
15
|
+
}
|
|
16
|
+
return [...next.values()].sort((a,b) => a.seq-b.seq)
|
|
17
|
+
}
|
|
18
|
+
function insertSorted(entries, entry) {
|
|
19
|
+
if (!entries.length || entries[entries.length-1].seq < entry.seq) { entries.push(entry); return }
|
|
20
|
+
let low=0,high=entries.length
|
|
21
|
+
while(low<high){const middle=(low+high)>>>1;if(entries[middle].seq<entry.seq)low=middle+1;else high=middle}
|
|
22
|
+
if(entries[low]?.seq===entry.seq)entries[low]=entry
|
|
23
|
+
else entries.splice(low,0,entry)
|
|
24
|
+
}
|
|
25
|
+
class HistoryView {
|
|
26
|
+
constructor(box, options) {
|
|
27
|
+
this.box=box; this.options=options; this.entries=[]; this.start=0; this.end=0; this.nodes=new Map(); this.disclosures=new Map(); this.reading=false; this.suppress=false; this.frame=0; this.pendingOlder=false
|
|
28
|
+
this.more=document.createElement('button'); this.more.type='button'; this.more.className='history-page-control'; this.more.textContent=options.olderLabel()
|
|
29
|
+
this.more.addEventListener('click',()=>this.older())
|
|
30
|
+
this.empty=document.createElement('div'); this.empty.className='history-empty'
|
|
31
|
+
this.retry=document.createElement('button');this.retry.type='button';this.retry.className='history-page-control';this.retry.textContent=options.retryLabel?.()||'Retry'
|
|
32
|
+
this.retry.addEventListener('click',()=>options.retry?.())
|
|
33
|
+
this.live=document.createElement('div'); this.live.className='history-live'
|
|
34
|
+
box.addEventListener('toggle',event=>{const detail=event.target;if(detail?.dataset?.activityKey)this.rememberDisclosure(detail)},true)
|
|
35
|
+
const intent=()=>{this.intentUntil=Date.now()+1200}
|
|
36
|
+
const hold=()=>{intent();this.reading=true;this.options.changed?.(this)}
|
|
37
|
+
box.addEventListener('wheel',event=>{intent();if(event.deltaY<0)hold()},{passive:true})
|
|
38
|
+
box.addEventListener('touchstart',event=>{this.touchY=event.touches?.[0]?.clientY;this.lastScrollTop=box.scrollTop},{passive:true})
|
|
39
|
+
box.addEventListener('touchmove',event=>{const y=event.touches?.[0]?.clientY;intent();if(y>this.touchY)hold();this.touchY=y},{passive:true})
|
|
40
|
+
// Pressing a card or selecting text pauses following, but only when actually
|
|
41
|
+
// scrolled away from the tail: tapping at the bottom must not fake "new content".
|
|
42
|
+
box.addEventListener('pointerdown',()=>{this.lastScrollTop=box.scrollTop;this.intentUntil=0;if(!this.atBottom)this.reading=true;this.options.changed?.(this)},{passive:true})
|
|
43
|
+
box.addEventListener('keydown',event=>{if(['ArrowUp','PageUp','Home'].includes(event.key))hold();else if(['ArrowDown','PageDown','End'].includes(event.key))intent()})
|
|
44
|
+
box.addEventListener('scroll',()=>{
|
|
45
|
+
if(this.suppress || this.frame)return
|
|
46
|
+
this.frame=requestAnimationFrame(()=>{this.frame=0;this.onScroll()})
|
|
47
|
+
},{passive:true})
|
|
48
|
+
}
|
|
49
|
+
anchor() {
|
|
50
|
+
const top=this.box.getBoundingClientRect().top
|
|
51
|
+
for(const node of this.box.querySelectorAll('.history-entry'))if(node.getBoundingClientRect().bottom>=top+1)return {seq:Number(node.dataset.historySeq),top:node.getBoundingClientRect().top}
|
|
52
|
+
return null
|
|
53
|
+
}
|
|
54
|
+
get unread() {return Math.max(0,this.entries.length-this.end)}
|
|
55
|
+
get hasPending() {return this.unread>0||(this.pendingLive||'')!==(this.liveHtml||'')}
|
|
56
|
+
/** Real viewport position, not an intent flag: a stale `reading` must never keep the jump button up at the bottom. */
|
|
57
|
+
get atBottom() {const box=this.box;return box.scrollHeight-box.scrollTop-box.clientHeight<=24}
|
|
58
|
+
set(entries, {reset=false, follow=false, live='', hasMore=false, loading=false, emptyLabel=''}={}) {
|
|
59
|
+
if(this.paused){this.pending={entries:entries.slice(),options:{reset,follow,live,hasMore,loading,emptyLabel}};return}
|
|
60
|
+
// A stale flag is cleaned up only when no gesture is in progress: while the user is
|
|
61
|
+
// actively scrolling up from the bottom a stream update must not clear `reading`,
|
|
62
|
+
// otherwise every chunk snaps the view back to the tail.
|
|
63
|
+
if(this.reading&&Date.now()>(this.intentUntil||0)&&this.atBottom&&this.end>=this.entries.length)this.reading=false
|
|
64
|
+
this.pendingLive=live
|
|
65
|
+
// Reading is explicit user intent. A stream update never changes it by proximity.
|
|
66
|
+
if(this.reading&&!reset)live=this.liveHtml||''
|
|
67
|
+
if(!reset&&!this.renderErrors&&entries.length===this.entries.length&&entries.every((entry,i)=>entry===this.entries[i])&&hasMore===this.hasMore&&loading===this.loading&&(this.end===entries.length?live:'')===this.liveHtml){this.more.disabled=loading;this.more.textContent=loading?this.options.loadingLabel():this.options.olderLabel();this.domChanged=false;this.options.changed?.(this);return}
|
|
68
|
+
const oldWidth=this.end-this.start
|
|
69
|
+
const anchor=this.anchor(), oldStart=this.entries[this.start]?.seq, oldEnd=this.entries[Math.max(this.start,this.end-1)]?.seq
|
|
70
|
+
this.entries=entries.slice(); this.hasMore=hasMore; this.loading=loading
|
|
71
|
+
if(reset || !this.end){this.end=entries.length;this.start=Math.max(0,this.end-WINDOW_SIZE);this.reading=false}
|
|
72
|
+
else if(!this.reading && this.end>=this.previousLength){this.end=entries.length;this.start=Math.max(0,this.end-WINDOW_SIZE)}
|
|
73
|
+
else {
|
|
74
|
+
let start=entries.findIndex(e=>e.seq===oldStart),end=entries.findIndex(e=>e.seq===oldEnd)
|
|
75
|
+
if(start<0)start=anchor?entries.findIndex(e=>e.seq===anchor.seq):0
|
|
76
|
+
this.start=Math.max(0,start-(this.pendingOlder?WINDOW_STEP:0));this.end=Math.min(entries.length,Math.max(this.start+1,end+1,this.start+Math.min(WINDOW_SIZE,oldWidth)))
|
|
77
|
+
}
|
|
78
|
+
this.previousLength=entries.length
|
|
79
|
+
this.emptyLabel=emptyLabel
|
|
80
|
+
this.more.textContent=loading?this.options.loadingLabel():this.options.olderLabel();this.more.disabled=loading;this.more.hidden=this.start===0&&!hasMore
|
|
81
|
+
this.liveHtml=this.reading&&!reset ? this.liveHtml||'' : this.end===entries.length?live:''
|
|
82
|
+
this.render(anchor,reset || (!this.reading && this.end===entries.length))
|
|
83
|
+
}
|
|
84
|
+
rememberDisclosure(detail) {
|
|
85
|
+
const key=detail.dataset.activityKey;if(!key)return
|
|
86
|
+
this.disclosures.delete(key);this.disclosures.set(key,!!detail.open)
|
|
87
|
+
if(this.disclosures.size>512)this.disclosures.delete(this.disclosures.keys().next().value)
|
|
88
|
+
}
|
|
89
|
+
captureDisclosures(node) {for(const detail of node.querySelectorAll('details[data-activity-key]'))this.rememberDisclosure(detail)}
|
|
90
|
+
restoreDisclosures(node) {for(const detail of node.querySelectorAll('details[data-activity-key]'))if(this.disclosures.has(detail.dataset.activityKey))detail.open=this.disclosures.get(detail.dataset.activityKey)}
|
|
91
|
+
render(anchor, bottom=false) {
|
|
92
|
+
const box=this.box, slice=this.entries.slice(this.start,Math.min(this.end,this.start+WINDOW_SIZE)), desired=[]
|
|
93
|
+
this.captureDisclosures(box)
|
|
94
|
+
this.end=this.start+slice.length
|
|
95
|
+
const rangeKey=this.start+':'+this.end
|
|
96
|
+
let changed=rangeKey!==this.lastRange || this.live.innerHTML!==this.liveHtml
|
|
97
|
+
this.lastRange=rangeKey
|
|
98
|
+
this.renderErrors=0
|
|
99
|
+
for(const entry of slice) {
|
|
100
|
+
// Hidden events render an empty string; keeping their node would leave dead gaps.
|
|
101
|
+
let html,key,failed=false
|
|
102
|
+
try{html=this.options.html(entry);key=signature(entry)}catch(error){failed=true;this.renderErrors++;key='render-error';globalThis.DshDiagnostics?.record('history.row',{phase:'failed',...globalThis.DshDiagnostics.errorFacts(error),category:'render'})}
|
|
103
|
+
if(!html&&!failed){if(this.nodes.delete(entry.seq))changed=true;continue}
|
|
104
|
+
let cached=this.nodes.get(entry.seq)
|
|
105
|
+
if(!cached || cached.key!==key){changed=true;const node=document.createElement('div');node.className='history-entry';node.dataset.historySeq=String(entry.seq);if(failed)node.textContent=this.options.errorLabel?.()||'This message could not be displayed. Retry loading history.';else{node.innerHTML=html;this.restoreDisclosures(node)}cached={key,node};this.nodes.set(entry.seq,cached)}
|
|
106
|
+
desired.push(cached.node)
|
|
107
|
+
}
|
|
108
|
+
this.more.hidden=this.start===0&&!this.hasMore
|
|
109
|
+
const keep=new Set(desired)
|
|
110
|
+
this.suppress=true
|
|
111
|
+
for(const child of [...box.children])if(child!==this.more && child!==this.live && child!==this.empty && child!==this.retry && !keep.has(child))child.remove()
|
|
112
|
+
if(this.more.parentNode!==box)box.prepend(this.more)
|
|
113
|
+
let cursor=this.more.nextSibling
|
|
114
|
+
for(const node of desired){if(node===cursor)cursor=cursor.nextSibling;else box.insertBefore(node,cursor)}
|
|
115
|
+
const empty=!desired.length&&!this.liveHtml, unreadable=empty&&slice.length>0
|
|
116
|
+
this.empty.textContent=unreadable?(this.options.unreadableLabel?.()||this.emptyLabel):this.emptyLabel
|
|
117
|
+
if(empty){if(this.empty.parentNode!==box)box.append(this.empty)}else this.empty.remove()
|
|
118
|
+
if((unreadable||this.renderErrors)&&this.options.retry){if(this.retry.parentNode!==box)box.append(this.retry)}else this.retry.remove()
|
|
119
|
+
if(this.live.innerHTML!==this.liveHtml){this.live.innerHTML=this.liveHtml;this.restoreDisclosures(this.live)}
|
|
120
|
+
if(this.live.parentNode!==box)box.append(this.live)
|
|
121
|
+
if(bottom)box.scrollTop=box.scrollHeight
|
|
122
|
+
else if(anchor){const current=this.nodes.get(anchor.seq)?.node;if(current?.parentNode===box)box.scrollTop+=current.getBoundingClientRect().top-anchor.top}
|
|
123
|
+
const active=new Set(slice.map(entry=>entry.seq));for(const seq of this.nodes.keys())if(!active.has(seq))this.nodes.delete(seq)
|
|
124
|
+
cancelAnimationFrame(this.releaseFrame);this.releaseFrame=requestAnimationFrame(()=>{this.suppress=false})
|
|
125
|
+
this.lastScrollTop=box.scrollTop
|
|
126
|
+
this.domChanged=changed
|
|
127
|
+
this.options.changed?.(this)
|
|
128
|
+
}
|
|
129
|
+
onScroll() {
|
|
130
|
+
const box=this.box, atBottom=this.atBottom
|
|
131
|
+
// Position wins over the intent flag: reaching the bottom always resumes following,
|
|
132
|
+
// no matter whether the scroll came from a wheel, a drag, a rail jump or momentum.
|
|
133
|
+
if(atBottom)this.reading=false
|
|
134
|
+
else if(Date.now()<this.intentUntil&&box.scrollTop<(this.lastScrollTop??box.scrollTop))this.reading=true
|
|
135
|
+
this.lastScrollTop=box.scrollTop
|
|
136
|
+
if(box.scrollTop<80 && Date.now()<this.intentUntil)this.older()
|
|
137
|
+
else if(box.scrollHeight-box.scrollTop-box.clientHeight<120 && this.end<this.entries.length && Date.now()<this.intentUntil){const anchor=this.anchor();this.end=Math.min(this.entries.length,this.end+WINDOW_STEP);this.start=Math.max(0,this.end-WINDOW_SIZE);this.liveHtml=this.end===this.entries.length?this.pendingLive||'':'';this.render(anchor,atBottom)}
|
|
138
|
+
else if(atBottom&&this.end>=this.entries.length&&this.liveHtml!==(this.pendingLive||'')){this.liveHtml=this.pendingLive||'';this.render(null,true)}
|
|
139
|
+
this.options.scrolled?.(this)
|
|
140
|
+
this.domChanged=false
|
|
141
|
+
this.options.changed?.(this)
|
|
142
|
+
}
|
|
143
|
+
async older() {
|
|
144
|
+
if(this.pendingOlder)return
|
|
145
|
+
if(this.start>0){const anchor=this.anchor();this.start=Math.max(0,this.start-WINDOW_STEP);this.end=Math.min(this.entries.length,this.start+WINDOW_SIZE);this.reading=true;if(this.end<this.entries.length)this.liveHtml='';this.render(anchor);return}
|
|
146
|
+
if(!this.hasMore || this.loading)return
|
|
147
|
+
this.reading=true
|
|
148
|
+
this.pendingOlder=true
|
|
149
|
+
try{await this.options.older()}finally{this.pendingOlder=false}
|
|
150
|
+
}
|
|
151
|
+
latest() {this.reading=false;this.intentUntil=0;this.end=this.entries.length;this.start=Math.max(0,this.end-WINDOW_SIZE);this.liveHtml=this.options.live?.()??this.pendingLive??'';this.render(null,true)}
|
|
152
|
+
pause() {if(!this.paused)this.savedScroll=this.box.scrollTop;this.paused=true}
|
|
153
|
+
resume() {
|
|
154
|
+
if(!this.paused)return
|
|
155
|
+
this.paused=false;this.box.scrollTop=this.savedScroll||0
|
|
156
|
+
const pending=this.pending;this.pending=null;if(pending)this.set(pending.entries,pending.options)
|
|
157
|
+
}
|
|
158
|
+
reset() {cancelAnimationFrame(this.frame);cancelAnimationFrame(this.releaseFrame);this.frame=0;this.entries=[];this.start=this.end=this.previousLength=0;this.lastRange='';this.nodes.clear();this.disclosures.clear();this.reading=false;this.pendingOlder=false;this.suppress=false;this.intentUntil=0;this.pendingLive='';this.pending=null;this.paused=false;this.lastScrollTop=0;this.box.replaceChildren()}
|
|
159
|
+
}
|
|
160
|
+
let cacheEpoch=0
|
|
161
|
+
let database
|
|
162
|
+
function openDatabase() {
|
|
163
|
+
if(database)return database
|
|
164
|
+
database=new Promise(resolve=>{
|
|
165
|
+
if(typeof indexedDB==='undefined'){resolve(null);return}
|
|
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}
|
|
170
|
+
request.onupgradeneeded=()=>{const store=request.result.createObjectStore('history',{keyPath:'key'});store.createIndex('scopeTime',['scope','updatedAt'])}
|
|
171
|
+
request.onsuccess=()=>{request.result.onversionchange=()=>{request.result.close();database=null};done(request.result)}
|
|
172
|
+
request.onerror=request.onblocked=()=>done(null)
|
|
173
|
+
})
|
|
174
|
+
return database
|
|
175
|
+
}
|
|
176
|
+
function decodeLegacy(raw,id) {
|
|
177
|
+
if(!raw)return Promise.resolve(null)
|
|
178
|
+
if(raw.length>250000&&typeof Worker!=='undefined')return new Promise(resolve=>{
|
|
179
|
+
let worker,url,timer
|
|
180
|
+
const done=value=>{clearTimeout(timer);worker?.terminate();if(url)URL.revokeObjectURL(url);resolve(value)}
|
|
181
|
+
try{url=URL.createObjectURL(new Blob(["self.onmessage=e=>{try{self.postMessage(JSON.parse(e.data.raw)[e.data.id]||null)}catch{self.postMessage(null)}}"],{type:'text/javascript'}));worker=new Worker(url);worker.onmessage=e=>done(e.data);worker.onerror=()=>done(null);timer=setTimeout(()=>done(null),3000);worker.postMessage({raw,id})}catch{done(null)}
|
|
182
|
+
})
|
|
183
|
+
try{return Promise.resolve(JSON.parse(raw)[id]||null)}catch{return Promise.resolve(null)}
|
|
184
|
+
}
|
|
185
|
+
const cacheKey=(scope,id)=>scope+':session:'+encodeURIComponent(id)
|
|
186
|
+
async function cacheLoad(scope,id,legacy) {
|
|
187
|
+
const key=cacheKey(scope,id),db=await openDatabase()
|
|
188
|
+
if(db){const value=await new Promise(resolve=>{
|
|
189
|
+
let tx,settled=false
|
|
190
|
+
const done=value=>{if(settled)return;settled=true;clearTimeout(timer);resolve(value)}
|
|
191
|
+
const timer=setTimeout(()=>{globalThis.DshDiagnostics?.storageFailure(scope,{name:'TimeoutError'},'indexeddb');done(null);try{tx?.abort()}catch{}},1500)
|
|
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)}
|
|
193
|
+
});if(value)return value}
|
|
194
|
+
try{const value=JSON.parse(localStorage.getItem(key)||'null');if(value)return value}catch{}
|
|
195
|
+
// One-time compatibility with the old per-connection JSON cache.
|
|
196
|
+
try{const value=await legacy?.(id);if(value){void cacheSave(scope,id,value);return value}return null}catch{return null}
|
|
197
|
+
}
|
|
198
|
+
async function cacheSave(scope,id,value) {
|
|
199
|
+
const epoch=cacheEpoch,key=cacheKey(scope,id),kept=[];let size=0
|
|
200
|
+
for(let i=(value.events||[]).length-1;i>=0;i--){const entry=value.events[i],length=signature(entry).length;if(size+length>750000)break;kept.unshift(entry);size+=length}
|
|
201
|
+
if(!kept.length)return false
|
|
202
|
+
const data={...value,events:kept,minSeq:kept[0].seq,hasMore:value.hasMore||kept.length<(value.events||[]).length,key,scope,id,updatedAt:Date.now()},db=await openDatabase()
|
|
203
|
+
if(epoch!==cacheEpoch)return false
|
|
204
|
+
if(db)try{const saved=await new Promise(resolve=>{
|
|
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)
|
|
209
|
+
let count=0;const request=store.index('scopeTime').openKeyCursor(IDBKeyRange.bound([scope,0],[scope,Number.MAX_SAFE_INTEGER]),'prev')
|
|
210
|
+
request.onsuccess=()=>{const cursor=request.result;if(!cursor)return;if(++count>10)store.delete(cursor.primaryKey);cursor.continue()}
|
|
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')}
|
|
213
|
+
if(epoch!==cacheEpoch)return false
|
|
214
|
+
try{
|
|
215
|
+
const indexKey=scope+':cache-index',index=JSON.parse(localStorage.getItem(indexKey)||'[]').filter(item=>item!==key),serialized=JSON.stringify(data)
|
|
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())}}
|
|
218
|
+
index.unshift(key)
|
|
219
|
+
for(const removed of index.splice(10))localStorage.removeItem(removed)
|
|
220
|
+
localStorage.setItem(indexKey,JSON.stringify(index));return kept.length>0
|
|
221
|
+
}catch{return false}
|
|
222
|
+
}
|
|
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{}}
|
|
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
|
+
let migrating
|
|
255
|
+
function migrateLegacy(scopes) {
|
|
256
|
+
if(migrating)return migrating
|
|
257
|
+
migrating=(async()=>{
|
|
258
|
+
const epoch=cacheEpoch,allowed=new Set(scopes.filter(value=>/^historyCacheV2:[a-f0-9]{64}$/.test(value)))
|
|
259
|
+
const result={migrated:0,reclaimed:0,pending:0}
|
|
260
|
+
const keys=Object.keys(localStorage).filter(key=>/^historyCacheV2:[a-f0-9]{64}$/.test(key)||/^(?:historyCache(?:V1)?$|dsh-remote-(?:history|sessions)(?:$|[-:]))/.test(key)).slice(0,100)
|
|
261
|
+
for(const key of keys){
|
|
262
|
+
if(epoch!==cacheEpoch)break
|
|
263
|
+
let raw
|
|
264
|
+
try{raw=localStorage.getItem(key)}catch{result.pending++;continue}
|
|
265
|
+
if(!raw)continue
|
|
266
|
+
if(!allowed.has(key)){
|
|
267
|
+
// Unscoped caches cannot be assigned to a newly selected credential.
|
|
268
|
+
// Keep unknown identities; reclaim only the named pre-V2 global cache.
|
|
269
|
+
if(/^historyCacheV2:/.test(key)){result.pending++;continue}
|
|
270
|
+
try{if(localStorage.getItem(key)===raw){localStorage.removeItem(key);result.reclaimed++}}catch{result.pending++}
|
|
271
|
+
continue
|
|
272
|
+
}
|
|
273
|
+
if(raw.length>5*1024*1024){result.pending++;continue}
|
|
274
|
+
let values
|
|
275
|
+
try{
|
|
276
|
+
if(raw.length>250000&&typeof Worker!=='undefined'){
|
|
277
|
+
values=await new Promise(resolve=>{
|
|
278
|
+
let worker,url,timer
|
|
279
|
+
const done=value=>{clearTimeout(timer);worker?.terminate();if(url)URL.revokeObjectURL(url);resolve(value)}
|
|
280
|
+
try{url=URL.createObjectURL(new Blob(['self.onmessage=e=>{try{self.postMessage(Object.entries(JSON.parse(e.data)).filter(x=>Array.isArray(x[1]?.events)).sort((a,b)=>(b[1].updatedAt||0)-(a[1].updatedAt||0)).slice(0,10))}catch{self.postMessage(null)}}'],{type:'text/javascript'}));worker=new Worker(url);worker.onmessage=e=>done(e.data);worker.onerror=()=>done(null);timer=setTimeout(()=>done(null),3000);worker.postMessage(raw)}catch{done(null)}
|
|
281
|
+
})
|
|
282
|
+
}else values=Object.entries(JSON.parse(raw)).filter(([,value])=>Array.isArray(value?.events)).sort((a,b)=>(b[1].updatedAt||0)-(a[1].updatedAt||0)).slice(0,10)
|
|
283
|
+
}catch{result.pending++;continue}
|
|
284
|
+
if(!values){result.pending++;continue}
|
|
285
|
+
let saved=true
|
|
286
|
+
for(const [id,value]of values){
|
|
287
|
+
if(epoch!==cacheEpoch){saved=false;break}
|
|
288
|
+
if(await cacheLoad(key,id)){result.migrated++;continue}
|
|
289
|
+
if(!await cacheSave(key,id,value)){saved=false;break}
|
|
290
|
+
result.migrated++
|
|
291
|
+
}
|
|
292
|
+
if(saved&&epoch===cacheEpoch)try{
|
|
293
|
+
if(localStorage.getItem(key)===raw){localStorage.removeItem(key);result.reclaimed++}
|
|
294
|
+
}catch{result.pending++}
|
|
295
|
+
else result.pending++
|
|
296
|
+
}
|
|
297
|
+
return result
|
|
298
|
+
})().finally(()=>{migrating=null})
|
|
299
|
+
return migrating
|
|
300
|
+
}
|
|
301
|
+
const api={HistoryView,reconcile,insertSorted,signature,cacheLoad,cacheSave,cacheRemove,cacheClear,cacheStats,decodeLegacy,migrateLegacy,WINDOW_SIZE}
|
|
302
|
+
if(typeof module!=='undefined'&&module.exports)module.exports=api
|
|
303
|
+
else root.DshHistory=api
|
|
304
|
+
})(typeof window==='undefined'?globalThis:window)
|
package/public/i18n.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/* DSH Remote 轻量 i18n · 零依赖
|
|
2
|
+
* 页面内联定义 window.XXX_STR = { zh: {...}, en: {...} } 后调用 I18N.init(XXX_STR)。
|
|
3
|
+
* 静态节点用 data-i18n / data-i18n-title / data-i18n-placeholder / data-i18n-aria;
|
|
4
|
+
* JS 动态文案用 I18N.t('key', {var}),支持 {var} 占位。
|
|
5
|
+
* 语言: localStorage dshLang > navigator.language(zh* → 中文, 其余英文),可在页面上切换。 */
|
|
6
|
+
'use strict'
|
|
7
|
+
;(function () {
|
|
8
|
+
const store = {
|
|
9
|
+
get(k) { try { return localStorage.getItem(k) } catch { return null } },
|
|
10
|
+
set(k, v) { try { localStorage.setItem(k, v) } catch {} }
|
|
11
|
+
}
|
|
12
|
+
function detect() {
|
|
13
|
+
const saved = store.get('dshLang')
|
|
14
|
+
if (saved === 'zh' || saved === 'en') return saved
|
|
15
|
+
return (navigator.language || 'zh').toLowerCase().startsWith('zh') ? 'zh' : 'en'
|
|
16
|
+
}
|
|
17
|
+
let dict = null
|
|
18
|
+
let lang = detect()
|
|
19
|
+
|
|
20
|
+
function t(key, vars) {
|
|
21
|
+
const table = (dict && (dict[lang] || dict.zh)) || {}
|
|
22
|
+
let s = table[key]
|
|
23
|
+
if (s == null) s = (dict && dict.zh && dict.zh[key]) != null ? dict.zh[key] : key
|
|
24
|
+
s = String(s)
|
|
25
|
+
if (vars) {
|
|
26
|
+
const keys = new Set(Object.keys(vars))
|
|
27
|
+
s = s.replace(/\{([A-Za-z0-9_]+)\}/g, (m, k) => keys.has(k) ? String(vars[k] ?? '') : '')
|
|
28
|
+
} else {
|
|
29
|
+
s = s.replace(/\{[A-Za-z0-9_]+\}/g, '')
|
|
30
|
+
}
|
|
31
|
+
return s
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function apply(root) {
|
|
35
|
+
root = root || document
|
|
36
|
+
root.querySelectorAll('[data-i18n]').forEach(el => { el.textContent = t(el.getAttribute('data-i18n')) })
|
|
37
|
+
root.querySelectorAll('[data-i18n-title]').forEach(el => { el.title = t(el.getAttribute('data-i18n-title')) })
|
|
38
|
+
root.querySelectorAll('[data-i18n-placeholder]').forEach(el => { el.placeholder = t(el.getAttribute('data-i18n-placeholder')) })
|
|
39
|
+
root.querySelectorAll('[data-i18n-aria]').forEach(el => { el.setAttribute('aria-label', t(el.getAttribute('data-i18n-aria'))) })
|
|
40
|
+
document.documentElement.lang = lang === 'zh' ? 'zh-CN' : 'en'
|
|
41
|
+
return lang
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function setLang(l) {
|
|
45
|
+
if (l !== 'zh' && l !== 'en') return lang
|
|
46
|
+
lang = l
|
|
47
|
+
store.set('dshLang', l)
|
|
48
|
+
apply(document)
|
|
49
|
+
return lang
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
window.I18N = {
|
|
53
|
+
init(strings) { dict = strings || dict; return apply(document) },
|
|
54
|
+
t, setLang, apply,
|
|
55
|
+
get lang() { return lang }
|
|
56
|
+
}
|
|
57
|
+
})()
|
package/public/icon.svg
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128">
|
|
2
|
+
<defs>
|
|
3
|
+
<linearGradient id="g" x1="0" y1="0" x2="1" y2="1">
|
|
4
|
+
<stop offset="0" stop-color="#5b8cff"/>
|
|
5
|
+
<stop offset="1" stop-color="#b48cff"/>
|
|
6
|
+
</linearGradient>
|
|
7
|
+
</defs>
|
|
8
|
+
<rect width="128" height="128" rx="28" fill="#0b0e1a"/>
|
|
9
|
+
<circle cx="64" cy="64" r="40" fill="none" stroke="url(#g)" stroke-width="10"/>
|
|
10
|
+
<path d="M64 24v22M64 82v22M24 64h22M82 64h22" stroke="url(#g)" stroke-width="10" stroke-linecap="round"/>
|
|
11
|
+
<circle cx="64" cy="64" r="12" fill="#7dcfff"/>
|
|
12
|
+
</svg>
|
|
@@ -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)
|