import {parseGameDetails} from './schemas.js';
import {setupContentReports,reportContent} from './content-reports.js';
import {memberAvatar} from './member-avatar.js';
import {homeHub} from './home-hub.js';
import {createClient} from '/account-base.js';
import {libraryApp,syncPacket,acceptedGameMessage,themeFrom,THEMES,gameSDK,cloudDecision} from '../public/feature-model.js';
const $=id=>document.getElementById(id);
let db,session,owner=false,revision=0,applying=false,syncTimer,syncPaused=false,syncReady=false,playerCleanup=()=>{},playGeneration=0,cloudChain=Promise.resolve(),providerConfig,pendingCloud=false,catalog=[];
const rpc=async(action,data={})=>{const {data:result,error}=await db.rpc('hub_feature',{p_action:action,p_data:data});if(error)throw Error(error.message);return result;};
function el(tag,text='',className=''){const node=document.createElement(tag);node.textContent=text;if(className)node.className=className;return node;}
function button(text,fn,className=''){const node=el('button',text,className);node.type='button';node.onclick=()=>task(node,fn);return node;}
function link(text,url,className='action-link'){const node=el('a',text,className);node.href=url;return node;}
function tell(text,error=false){const node=$('feature-status')||$('cloud-state');if(node){node.textContent=text;node.dataset.tone=error?'error':'quiet';}}
async function task(control,fn){if(control?.disabled)return;if(control)control.disabled=true;try{await fn();}catch(error){tell(error.message||'Something went wrong.',true);}finally{if(control)control.disabled=false;}}
const read=(key,fallback)=>{try{return JSON.parse(localStorage.getItem('zs.'+key))??fallback;}catch{return fallback;}};
function emit(type,detail){dispatchEvent(new CustomEvent(type,{detail}));}
function applyCloud(remote){
const local=read('settings',{}),safe=syncPacket(remote.settings,remote.favorites);safe.settings.customCss=local.customCss||'';
applying=true;document.body.dataset.cloudApplying='true';try{emit('zs:cloud-apply',safe);if(!$('card-grid')){localStorage.setItem('zs.settings',JSON.stringify(safe.settings));localStorage.setItem('zs.favorites',JSON.stringify(safe.favorites));}}finally{applying=false;delete document.body.dataset.cloudApplying;}
emit('zs:prefs-updated',{});
}
function dirtyState(){try{return JSON.parse(localStorage.getItem('zs.cloudDirty')||'null');}catch{return null;}}
function rememberRevision(){localStorage.setItem('zs.cloudRevision',String(revision));}
function conflict(){syncPaused=true;syncReady=true;tell('This device has unsynced changes and the cloud changed too. Open Account and choose Use cloud settings or Keep this device.',true);}
async function loadCloud(prefer='auto'){
const previousOwner=localStorage.getItem('zs.cloudOwner'),changedOwner=!!previousOwner&&previousOwner!==session.user.id;
const remote=await rpc('cloud_get');revision=remote.revision;
const marker=dirtyState(),ownDirty=marker&&(marker.owner===session.user.id||!previousOwner&&marker.owner===null);
const local=syncPacket(read('settings',{}),read('favorites',[])),same=JSON.stringify(local)===JSON.stringify(syncPacket(remote.settings,remote.favorites));
const decision=prefer==='device'?'push':prefer==='cloud'?'pull':cloudDecision(revision,ownDirty?marker.revision:null,{ownerChanged:changedOwner,sameData:same});
if(decision==='conflict'){conflict();return;}
if(decision==='push'||decision==='empty'){
const result=await rpc('cloud_put',{...(decision==='empty'?syncPacket({},[]):local),revision});
if(result.conflict){conflict();return;}revision=result.revision;applyCloud(result);
}else applyCloud(remote);
localStorage.removeItem('zs.cloudDirty');localStorage.setItem('zs.cloudOwner',session.user.id);rememberRevision();
pendingCloud=false;syncReady=true;syncPaused=false;tell('Favorites and settings are synced.');
const recent=await rpc('recent_get'),items=Object.fromEntries(recent.map(row=>[row.item_id,Date.parse(row.played_at)]));
applying=true;try{emit(changedOwner?'zs:recent-reset':'zs:recent-apply',items);}finally{applying=false;}
}
async function storeCloud(){
if(!syncReady||syncPaused)return;
const marker=dirtyState(),packet=syncPacket(read('settings',{}),read('favorites',[]));pendingCloud=false;
const result=await rpc('cloud_put',{...packet,revision});
if(result.conflict){conflict();return;}
revision=result.revision;rememberRevision();
const latest=dirtyState();if(latest&&latest.stamp!==marker?.stamp){latest.revision=revision;localStorage.setItem('zs.cloudDirty',JSON.stringify(latest));pendingCloud=true;}else localStorage.removeItem('zs.cloudDirty');
tell(pendingCloud?'Saving favorites and settings…':'Favorites and settings are synced.');
}
addEventListener('zs:local-change',event=>{
if(!session||applying)return;const {key,value}=event.detail||{};
if(['settings','favorites'].includes(key)){pendingCloud=true;tell('Saving favorites and settings…');clearTimeout(syncTimer);syncTimer=setTimeout(()=>{cloudChain=cloudChain.then(storeCloud).catch(error=>{syncPaused=true;tell(error.message,true);});},1200);}
if(key==='recent'&&value&&typeof value==='object'){
const id=Object.entries(value).sort((a,b)=>b[1]-a[1])[0]?.[0];if(id)rpc('recent_put',{id}).catch(error=>tell(error.message,true));
}
});
async function library(offset=0){
const rows=await rpc('library_list',{offset});
const apps=rows.filter(row=>row.published).map(libraryApp);catalog=offset?[...catalog,...apps]:apps;emit('zs:library',catalog);
let more=$('load-shared-games');if(!more){more=button('Load more shared games',()=>library(Number(more.dataset.offset)),'secondary-button shared-library-more');more.id='load-shared-games';document.querySelector('.library-footer')?.after(more);}more.dataset.offset=String(offset+100);more.hidden=rows.length<100;
for(const app of apps)if(app.thumbnailPath){
const {data,error}=await db.storage.from('hub-games').createSignedUrl(app.thumbnailPath,300);
if(!error)emit('zs:game-thumbnail',{id:app.id,url:data.signedUrl});
}
return rows;
}
async function play(app){
playerCleanup();const generation=++playGeneration;const dialog=$('shared-player');if(!dialog)throw Error('Game player unavailable.');
$('shared-game-title').textContent=app.name;let report=$('shared-report');if(!report){report=button('Report game',()=>{},'content-report-button');report.id='shared-report';$('shared-close').before(report);}report.onclick=()=>reportContent({kind:'game',id:app.gameId,title:app.name});$('shared-game-state').textContent='Loading game…';dialog.showModal();
const {data,error}=await db.storage.from('hub-games').download(app.htmlPath);if(error)throw error;
if(generation!==playGeneration||!dialog.open)return;
if(data.size>10485760)throw Error('This game exceeds the 10 MB limit.');
const html=await data.text();if(generation!==playGeneration||!dialog.open)return;const channel=crypto.randomUUID(),frame=document.createElement('iframe');
frame.title=app.name;frame.sandbox='allow-scripts allow-pointer-lock';frame.allow='fullscreen; gamepad';frame.allowFullscreen=true;frame.className='shared-game-frame';
const versions=new Map(),inflight=new Set();let alive=true;
const listener=async event=>{
const message=acceptedGameMessage(event,frame.contentWindow,channel);if(!message||inflight.has(message.id))return;
if(inflight.size>=2)return;inflight.add(message.id);
try{
if(!versions.has(message.slot)){const result=await rpc('progress_get',{game_id:app.gameId,slot:message.slot});versions.set(message.slot,result);}
let value;
if(message.op==='load')value=versions.get(message.slot).value;
else{
const result=await rpc('progress_put',{game_id:app.gameId,slot:message.slot,value:message.value,revision:versions.get(message.slot).revision});
if(result.conflict)throw Error('This save changed on another device. Close and reopen the game before saving.');
versions.set(message.slot,{value:message.value,revision:result.revision});value=true;$('shared-game-state').textContent='Progress saved to your account.';
}
if(alive)frame.contentWindow?.postMessage({type:'zs-game-result',channel,id:message.id,value},'*');
}catch(error){if(alive){$('shared-game-state').textContent=error.message;frame.contentWindow?.postMessage({type:'zs-game-result',channel,id:message.id,error:error.message},'*');}}
finally{inflight.delete(message.id);}
};
addEventListener('message',listener);
playerCleanup=()=>{alive=false;removeEventListener('message',listener);frame.remove();$('shared-game-frame').replaceChildren();};
const sdk='';
frame.srcdoc=/
]*)?>/i.test(html)?html.replace(/]*)?>/i,match=>match+sdk):sdk+html;
$('shared-game-frame').replaceChildren(frame);$('shared-game-state').textContent='Cloud saves are available for games that support ZSGame.';
};
addEventListener('zs:play-shared',event=>play(event.detail).catch(error=>{$('shared-game-state').textContent=error.message;}));
function playerControls(){
const dialog=$('shared-player');if(!dialog)return;
$('shared-close').onclick=()=>dialog.close();dialog.addEventListener('close',()=>{playGeneration++;playerCleanup();playerCleanup=()=>{};});
$('shared-fullscreen').onclick=()=>dialog.requestFullscreen?.().catch(error=>{$('shared-game-state').textContent=error.message;});
}
function accountExtras(){
const grid=$('hub-links');if(!grid)return;
for(const [name,description,url] of [['Friends','Requests and people you’ve added.','/friends'],['Suggest something','Submit game requests, suggestions, and bug reports.','/requests'],...(owner?[['Game library','Publish HTML games for everyone.','/library']]:[])]){
const card=link('',url,'hub-tile'),icon=el('span','','hub-tile-icon');const paths=name==='Friends'?'':name==='Game library'?'':'';icon.innerHTML='';card.append(icon,el('strong',name),el('span',description));grid.append(card);
}
const cloud=el('section','','feature-cloud panel');cloud.append(el('h2','Cloud sync'),el('p','Favorites and settings follow your account. Local notes, imported HTML files, and custom CSS stay on this device.','muted'));
const state=el('p','Connecting…');state.id='cloud-state';state.setAttribute('role','status');cloud.append(state,button('Use cloud settings',()=>loadCloud('cloud')),button('Keep this device',()=>loadCloud('device')));grid.after(cloud);
}
function friendActions(row,container){
if(row.state==='pending'&&!row.outgoing)container.append(button('Accept',async()=>{await rpc('friend_update',{id:row.id,state:'accepted'});await friends();},'primary'));
container.append(button(row.state==='blocked'?'Unblock requests':row.state==='pending'?(row.outgoing?'Cancel request':'Decline'):'Remove',async()=>{await rpc('friend_update',{id:row.id,state:'remove'});await friends();}));
if(row.state!=='blocked')container.append(button('Block requests',async()=>{await rpc('friend_update',{id:row.id,state:'blocked'});await friends();}));
}
async function friends(){
const rows=await rpc('friends_list'),list=$('feature-list');list.replaceChildren();
for(const [title,selected] of [['Requests',rows.filter(x=>x.state==='pending')],['Friends',rows.filter(x=>x.state==='accepted')],['Blocked requests',rows.filter(x=>x.state==='blocked')]]){
const group=el('section','','feature-group');group.append(el('h2',title+' · '+selected.length));
if(!selected.length)group.append(el('p',title==='Friends'?'No friends added. Send a request from People.':'No entries.','muted'));
for(const row of selected){const card=el('article','','feature-row'),info=el('div');info.append(el('strong',row.display_name));if(row.username){info.append(link('@'+row.username,'/users/'+encodeURIComponent(row.username),'feature-handle'));info.append(link('Report profile','/users/'+encodeURIComponent(row.username)+'?report=1','content-report-button'));}info.append(el('small',row.state==='pending'?(row.outgoing?'Request sent':'Wants to add you'):row.state==='accepted'?'Friends':'You blocked new requests'));const actions=el('div','','feature-actions');friendActions(row,actions);const person=el('div','','friend-person');person.append(memberAvatar(db,row),info);card.append(person,actions);group.append(card);}list.append(group);
}tell('Friend requests stay private. A friendship starts only after the other person accepts.');
}
async function requestList(staff=false){
const rows=await rpc(staff?'requests_staff':'requests_mine',{offset:requestOffset}),list=staff?$('staff-request-list'):$('feature-list');list.replaceChildren();
if(!rows.length)list.append(el('p','No requests here yet.','muted'));
for(const row of rows){
const card=el('article','','feature-request');const heading=el('div','','feature-row');heading.append(el('h3',row.title),el('span',row.state,'pill'));card.append(heading,el('small',row.kind+' · '+new Date(row.created_at).toLocaleDateString()),el('p',row.body));
if(row.reply){const reply=el('blockquote',row.reply);card.append(reply,button('Report reply',()=>reportContent({kind:'reply',id:row.id,title:'Staff reply: '+row.title}),'content-report-button'));}if(staff)card.append(button('Report suggestion',()=>reportContent({kind:'request',id:row.id,title:row.title}),'content-report-button'));
if(staff){const form=el('form','','feature-review-form'),select=el('select'),label=el('label','Status');for(const value of ['open','reviewing','planned','done','closed']){const option=el('option',value);option.value=value;select.append(option);}select.value=row.state;label.append(select);const response=el('textarea');response.maxLength=1000;response.rows=3;response.value=row.reply;const replyLabel=el('label','Reply (visible to the requester)');replyLabel.append(response);const submit=el('button','Save update','primary');submit.type='submit';form.append(label,replyLabel,submit);form.onsubmit=event=>{event.preventDefault();task(submit,async()=>{await rpc('request_review',{id:row.id,state:select.value,reply:response.value});await requestList(true);});};card.append(form);}
list.append(card);
}
const pager=el('div','','feature-actions');pager.append(button('Previous',async()=>{requestOffset=Math.max(0,requestOffset-50);await requestList(staff);}),el('span','Page '+(requestOffset/50+1)),button('Next',async()=>{requestOffset+=50;await requestList(staff);}));pager.firstChild.disabled=requestOffset===0;pager.lastChild.disabled=rows.length<50;list.append(pager);
}
let requestOffset=0,libraryOffset=0;
function input(labelText,type='text',max=80){const label=el('label',labelText),field=el(type==='textarea'?'textarea':'input');if(type!=='textarea')field.type=type;field.maxLength=max;field.required=true;label.append(field);return {label,field};}
function featurePage(){
const key=document.body.dataset.feature;if(!key)return;
const form=$('feature-form');
if(key==='friends'){
const name=input('Their username');name.field.value=(new URL(location.href).searchParams.get('add')||'').slice(0,24);const submit=el('button','Send friend request','primary');submit.type='submit';form.append(name.label,submit);form.onsubmit=event=>{event.preventDefault();task(submit,async()=>{await rpc('friend_send',{username:name.field.value.replace(/^@/,'')});name.field.value='';await friends();});};friends().catch(error=>tell(error.message,true));
}else if(key==='requests'){
const kind=el('select');kind.setAttribute('aria-label','Request type');for(const [value,title] of [['game','Game request'],['bug','Bug report'],['idea','Idea']]){const option=el('option',title);option.value=value;kind.append(option);}const title=input('Title'),body=input('Description','textarea',2000);title.field.minLength=3;body.field.minLength=10;body.field.rows=5;const submit=el('button','Send to staff','primary');submit.type='submit';form.append(kind,title.label,body.label,submit);form.onsubmit=event=>{event.preventDefault();task(submit,async()=>{await rpc('request_send',{kind:kind.value,title:title.field.value,body:body.field.value});title.field.value='';body.field.value='';requestOffset=0;await requestList();tell('Sent. You can check staff replies here.');});};requestList().then(()=>tell('Requests and staff replies are visible only to the requester and staff.')).catch(error=>tell(error.message,true));
}else if(key==='library'){
if(!owner){form.hidden=true;tell('Only the owner can publish games.',true);return;}
libraryEditor(form);showLibrary().then(()=>tell('Only published games appear in Games. Drafts stay in this workspace.')).catch(error=>tell(error.message,true));
}
}
async function showLibrary(){
const rows=await rpc('library_list',{offset:libraryOffset}),list=$('feature-list');list.replaceChildren();
if(!rows.length)list.append(el('p','No shared games yet. Upload a standalone HTML game to get started.','muted'));
for(const row of rows){const card=el('article','','feature-row'),info=el('div');info.append(el('strong',row.title),el('p',row.category+' · '+(row.published?'Published':'Draft')));card.append(info,button(row.published?'Unpublish':'Publish',async()=>{await rpc('library_visibility',{id:row.id,published:!row.published});await showLibrary();}));list.append(card);}
const pager=el('div','','feature-actions');pager.append(button('Previous',async()=>{libraryOffset=Math.max(0,libraryOffset-100);await showLibrary();}),button('Next',async()=>{libraryOffset+=100;await showLibrary();}));pager.firstChild.disabled=libraryOffset===0;pager.lastChild.disabled=rows.length<100;list.append(pager);
}
function libraryEditor(form){
const title=input('Game title','text',60),description=input('Short description','textarea',180),html=input('HTML game file','file'),thumbnail=input('Thumbnail (optional)','file');
html.field.accept='.html,.htm,text/html';thumbnail.field.accept='image/png,image/jpeg,image/webp';thumbnail.field.required=false;description.field.required=false;
const category=el('select');category.setAttribute('aria-label','Game category');for(const name of ['arcade','puzzle','platformer','other']){const option=el('option',name);option.value=name;category.append(option);}
const submit=el('button','Upload as draft','primary');submit.type='submit';form.append(title.label,description.label,category,html.label,thumbnail.label,el('p','Use games you own or have permission to share. One HTML file, up to 10 MB; optional image up to 2 MB. Uploads start as drafts.','muted'),submit);
form.onsubmit=event=>{event.preventDefault();task(submit,async()=>{
const file=html.field.files?.[0],image=thumbnail.field.files?.[0];if(!file||file.size>10485760||!file.size||!/^.+\.html?$/i.test(file.name))throw Error('Choose an HTML file up to 10 MB.');
if(image&&(!['image/png','image/jpeg','image/webp'].includes(image.type)||image.size>2097152))throw Error('Choose a PNG, JPG, or WebP up to 2 MB.');
const details=parseGameDetails({title:title.field.value,description:description.field.value,category:category.value});
const id=crypto.randomUUID(),path=id+'/'+crypto.randomUUID()+'.html',paths=[];
try{
let result=await db.storage.from('hub-games').upload(path,file,{contentType:'text/html',upsert:false});if(result.error)throw result.error;paths.push(path);let thumbnailPath=null;
if(image){thumbnailPath=id+'/'+crypto.randomUUID()+'.'+({'image/png':'png','image/jpeg':'jpg','image/webp':'webp'}[image.type]);result=await db.storage.from('hub-games').upload(thumbnailPath,image,{contentType:image.type,upsert:false});if(result.error)throw result.error;paths.push(thumbnailPath);}
await rpc('library_save',{id,...details,html_path:path,thumbnail_path:thumbnailPath,published:false});
}catch(error){if(paths.length)await db.storage.from('hub-games').remove(paths);throw error;}
form.reset();await showLibrary();tell('Draft uploaded. Select Publish to make it available to approved members.');
});};
}
function paintTheme(raw){const theme=themeFrom(raw),card=$('public-profile');if(!card)return;card.dataset.profileTheme=theme.preset;card.dataset.profileEffect=theme.effect;card.style.setProperty('--profile-panel',THEMES[theme.preset]);card.style.setProperty('--profile-accent',theme.accent);}
async function profileTheme(){
if(!$('profile-handle'))return;
const load=async()=>{
const username=$('profile-handle').textContent.replace(/^@/,'').trim();if(!username)return;
const {data,error}=await db.rpc('hub_profile_theme',{p_username:username});if(error)throw error;paintTheme(data);
if(session&&$('editor')?.hidden&&!$('profile-add-friend')){const friend=link('Add friend','/friends?add='+encodeURIComponent(username),'action-link');friend.id='profile-add-friend';document.querySelector('.profile-actions')?.append(friend);}
if($('editor')?.hidden||!session||$('theme-editor'))return;
const section=el('section','','feature-theme panel');section.id='theme-editor';const status=el('p','');status.id='feature-status';status.setAttribute('role','status');section.append(status);section.append(el('h2','Profile theme'),el('p','Preview a color and finish. This changes your profile card, not the whole site.','muted'));
const initial=themeFrom(data),preset=el('select');preset.setAttribute('aria-label','Profile theme');for(const name of Object.keys(THEMES)){const option=el('option',name);option.value=name;preset.append(option);}preset.value=initial.preset;
const color=el('input');color.type='color';color.value=initial.accent;color.setAttribute('aria-label','Profile accent color');const effect=el('select');effect.setAttribute('aria-label','Profile effect');for(const value of ['none','glow','stripes']){const option=el('option',value);option.value=value;effect.append(option);}effect.value=initial.effect;
const value=()=>({preset:preset.value,accent:color.value,effect:effect.value});for(const control of [preset,color,effect])control.oninput=()=>paintTheme(value());
const controls=el('div','','feature-theme-controls');for(const [title,control] of [['Theme',preset],['Accent color',color],['Finish',effect]]){const label=el('label',title);label.append(control);controls.append(label);}section.append(controls,button('Save theme',async()=>{await rpc('theme_put',value());tell('Profile theme saved.');}));$('editor').after(section);
};
const observer=new MutationObserver(()=>{if($('profile-handle').textContent){observer.disconnect();load().catch(error=>tell(error.message,true));}});observer.observe($('profile-handle'),{childList:true,subtree:true});if($('profile-handle').textContent){observer.disconnect();await load();}
}
async function start(){
const configResponse=await fetch('/api/account/config',{cache:'no-store'});if(!configResponse.ok)return;const config=await configResponse.json();if(!config.enabled)return;
providerConfig=config;db=createClient(config.url,config.key,{auth:{flowType:'pkce',detectSessionInUrl:false,persistSession:true,autoRefreshToken:true}});
const {data,error}=await db.auth.getSession();if(error)throw error;session=data.session;
await profileTheme();
if(!session){if(document.body.dataset.feature)location.replace('/signin');return;}
const {data:access,error:accessError}=await db.rpc('my_access');if(accessError)throw accessError;if(access?.[0]?.status!=='approved')return;
const {data:isOwner,error:ownerError}=await db.rpc('hub_library_owner');if(ownerError)throw ownerError;owner=!!isOwner;
setupContentReports(db);accountExtras();playerControls();featurePage();if($('card-grid'))homeHub(rpc,owner,db);
if($('card-grid')){if(document.body.dataset.hubReady!=='true')await new Promise(resolve=>addEventListener('zs:hub-ready',resolve,{once:true}));const label=el('label','Category','shared-game-category'),select=el('select');select.setAttribute('aria-label','Game category');for(const value of ['all','arcade','puzzle','platformer','other']){const option=el('option',value==='all'?'All games':value);option.value=value;select.append(option);}select.onchange=()=>emit('zs:game-category',select.value);label.append(select);document.querySelector('.filter-row')?.prepend(label);await library();await loadCloud();}
if($('cloud-state'))await loadCloud();
if($('tab-requests')){$('tab-requests').addEventListener('click',()=>{requestOffset=0;requestList(true).catch(error=>tell(error.message,true));});if(location.hash==='#requests')await requestList(true);}
db.auth.onAuthStateChange((event,next)=>{
if(event==='SIGNED_OUT'){clearTimeout(syncTimer);session=null;syncReady=false;playerCleanup();fetch('/api/account/session',{method:'DELETE'}).catch(()=>{});}
if(event==='TOKEN_REFRESHED'&&next){session=next;fetch('/api/account/session',{method:'POST',headers:{authorization:'Bearer '+next.access_token}}).catch(()=>{});}
if(event==='SIGNED_IN'&&next&&session?.user.id!==next.user.id){clearTimeout(syncTimer);syncReady=false;session=next;document.body.style.visibility='hidden';fetch('/api/account/session',{method:'POST',headers:{authorization:'Bearer '+next.access_token}}).finally(()=>location.replace('/account'));}
});
}
start().catch(error=>tell(error.message,true));
addEventListener('click',event=>{
const a=event.target.closest?.('a[href]');if(!pendingCloud||!syncReady||syncPaused||!a||a.target==='_blank'||a.hasAttribute('download')||event.defaultPrevented||event.button!==0||event.metaKey||event.ctrlKey||event.shiftKey||event.altKey)return;
const url=new URL(a.href,location.href);if(url.origin!==location.origin||url.pathname===location.pathname&&url.search===location.search)return;
event.preventDefault();clearTimeout(syncTimer);cloudChain=cloudChain.then(storeCloud).catch(error=>tell(error.message,true));cloudChain.finally(()=>location.assign(url.href));
});
addEventListener('pagehide',()=>{
if(!pendingCloud||!syncReady||syncPaused||!session||!providerConfig)return;
fetch(providerConfig.url+'/rest/v1/rpc/hub_feature',{method:'POST',keepalive:true,headers:{apikey:providerConfig.key,authorization:'Bearer '+session.access_token,'content-type':'application/json'},body:JSON.stringify({p_action:'cloud_put',p_data:{...syncPacket(read('settings',{}),read('favorites',[])),revision}})}).catch(()=>{});
});