1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["js/rolloutCapsBJsLLLO7.js","js/chunkReloadRecoveryrjuMb-b8.js","js/vue-runtimeBHGad_ZB.js","js/cjs-helpersC4iS2aBk.js","js/bootstrap-vue-nextDXY4qsO1.js","assets/bootstrap-vue-nexthA7rx8St.css","js/dexie2jmnBxhj.js","assets/chunkReloadRecoveryUbLNi8xK.css","js/item-name.utilsBH3paGZr.js","js/item.typesx7Q7rrX9.js","js/content.typesyje91KzF.js","js/constantsDW26WJ6H.js","js/extraction.pure.utilsDQPW8yIh.js","js/url.utils3SlYVg-c.js","js/TaskServiceWHtFbUzu.js","js/TaskCompletionRefStateServiceDiefvKK0.js","js/refStateBatchSupportDh0Q7mM-.js","js/TaskItemServiceP03d_i_t.js","js/ItemServiceDYS7Z6Pr.js","js/noteAttachmentDId5R_kp.js","js/file_utilsBvAXo0vA.js","js/api-typesD1zIcSfT.js","js/freshSignInv8N2vL5e.js","js/textEmbeddingUtilsBRNkRshv.js","js/searchContentKindsBGoDYC-k.js","js/feedback.utilscwcZGi10.js","js/feedDiscoveryCsjZq3pR.js","js/itemImageSourcesCubmTdva.js","js/search-provider.utilsBiOzVtNa.js","js/statusFacetsB0tsuUpJ.js","js/browseFacets8dSOpUAG.js","js/libraryWriteGuardslN41qmuD.js","js/restrictedSiteAccessWarning.utilsCD4Urb73.js"])))=>i.map(i=>d[i]); 2var Qt=Object.defineProperty;var Jt=(n,e,t)=>e in n?Qt(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var S=(n,e,t)=>Jt(n,typeof e!="symbol"?e+"":e,t);import{T as kt,o as Xt,q as P,C as l,L as ze,P as nt,g as Ce,h as ge,R as Ue,b as bt,s as Zt,t as Re,u as er,v as tr,w as rr,x as nr}from"./item-name.utilsBH3paGZr.js";import{f,c as M,O as q,R,U as D,V as K,bF as vt,b as Ye,cJ as ar,cI as sr,am as Et,dD as At,dE as Ct,cE as ne,ch as ir,cH as cr,d as or,e as xe,s as dr,q as ur,N as V}from"./chunkReloadRecoveryrjuMb-b8.js";import{I as Be,o as lr}from"./item.typesx7Q7rrX9.js";import{f as yr,O as Ut,N as Tt,n as pr,g as fr,z as gr,r as hr}from"./content.typesyje91KzF.js";import{I as he}from"./constantsDW26WJ6H.js";import{r as wr,a as mr,F as Ir}from"./extraction.pure.utilsDQPW8yIh.js";import{m as Kr,l as Sr}from"./url.utils3SlYVg-c.js";class Qe{constructor(){S(this,"isLocked",!1);S(this,"queue",[])}async acquire(){return new Promise(e=>{this.isLocked?this.queue.push(e):(this.isLocked=!0,e())})}tryAcquire(){return this.isLocked?!1:(this.isLocked=!0,!0)}release(){if(this.queue.length>0){const e=this.queue.shift();e&&e()}else this.isLocked=!1}}const wa=new Qe,at=new Qe;class kr{static getMutex(e){return this.mutexes[e]||(this.mutexes[e]=new Qe),this.mutexes[e]}}S(kr,"mutexes",{});function br(n=16){const e=new Uint8Array(Math.ceil(n/2));return crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("").slice(0,n)}let _t=!1;function ma(){return _t}function Ia(n){_t=n===!0}function Ft(n){const e=n.fieldPath??"",t=`kindredly|atrest|v1|sv:${n.schemaVersion}|acnt:${n.acntId}|rt:${n.recordType}|rid:${n.recordId}|fp:${e}`;return kt.instance.encode(t)}async function vr(n,e,t){const r=P.getRandomValues(new Uint8Array(12)),a=Ft(t),s=await P.subtle.encrypt({name:"AES-GCM",iv:r,additionalData:a},n.key,e);return{format:"atrest-v1",alg:"AES-GCM",keyId:n.keyId,iv:l.ab2str(r),data:l.ab2str(s)}}async function Er(n,e,t){if(e.format!=="atrest-v1")throw new Error(`Unsupported at-rest envelope format: ${String(e==null?void 0:e.format)}`);if(e.alg!=="AES-GCM")throw new Error(`Unsupported at-rest envelope alg: ${String(e==null?void 0:e.alg)}`);if(e.keyId!==n.keyId)throw new Error("At-rest envelope keyId mismatch");const r=new Uint8Array(l.str2ab(e.iv)),a=l.str2ab(e.data),s=Ft(t);return await P.subtle.decrypt({name:"AES-GCM",iv:r,additionalData:s},n.key,a)}async function Ar(n,e,t){const a=kt.instance.encode(JSON.stringify(e));return await vr(n,a.buffer,t)}async function Cr(n,e,t){const r=await Er(n,e,t),a=Xt.instance.decode(r);return JSON.parse(a)}function st(n){var e;return(n==null?void 0:n.format)==="local-at-rest-kv-v1"&&(n==null?void 0:n.v)===1&&((e=n==null?void 0:n.envelope)==null?void 0:e.format)==="atrest-v1"}function it(n,e,t){return{schemaVersion:1,acntId:n,recordType:(t==null?void 0:t.recordType)||"kv",recordId:e}}function Ka(n){const e=n.recordType||"kv",t=n.allowPlaintextFallbackWrite??!0,r=n.allowPlaintextReadWhenEnabled??!0;return{get:async i=>{const d=await n.backend.getRaw(i),c=await n.getAccountId();if(!c)return d;if(await n.isEnabled(c)&&!r&&!st(d))return null;if(!st(d))return d;try{const u=await n.getDataKeyIfUnlocked(c);return u?await Cr(u,d.envelope,it(c,i,{recordType:e})):null}catch(u){return console.warn("[atRestKv] decrypt failed for key",i,u),null}}
2,set:async(i,d)=>{const c=await n.getAccountId();if(!c){await n.backend.setRaw(i,d);return}if(!await n.isEnabled(c)){await n.backend.setRaw(i,d);return}try{const u=await n.getDataKeyIfUnlocked(c);if(!u){t&&await n.backend.setRaw(i,d);return}const p={format:"local-at-rest-kv-v1",v:1,envelope:await Ar(u,d,it(c,i,{recordType:e}))};await n.backend.setRaw(i,p)}catch(u){console.warn("[atRestKv] encrypt failed for key",i,u),t&&await n.backend.setRaw(i,d)}}}}class L{constructor(e,t,r,a=[],s=new Map){S(this,"userId");S(this,"accountId");S(this,"userSecret");S(this,"keyEntryList");S(this,"keyInstanceMap");S(this,"encoder",new TextEncoder);S(this,"decoder",new TextDecoder);this.userId=e,this.accountId=t,this.userSecret=r;const i=l.getUserSecretKeyId(e);this.keyEntryList=a?a.filter(d=>d.wrappingKeyId!="userPassword"&&d.keyId!=i):[],this.keyInstanceMap=s}static async instanceFromPassword(e,t,r,a,s){var y,p;f("[KM] Creating key manager from password");const i=l.getUserSecretKeyId(e),d=s.find(g=>g.keyId===i&&g.wrappingKeyId==="userPassword"),c=((y=d==null?void 0:d.keyData)==null?void 0:y.kdfIterations)??ze,o=((p=d==null?void 0:d.keyData)==null?void 0:p.kdfSalt)??a,u=await l.createPasswordKey(r,o,"password",c);return L._instanceFromKey(e,t,u,s)}static async instanceFromAdminKey(e,t,r,a){return f("[KM] Creating key manager admin key"),L._instanceFromKey(e,t,r,a)}static async _instanceFromKey(e,t,r,a){f("[KM] Creating key managerxx",e,t,r,a);const s=l.getUserSecretKeyId(e),i=a.find(o=>o.keyId===s&&o.wrappingKeyId==="userPassword");if(!i)throw new Error("No user secret key entry found:"+e);f("[KM] Unwrapping user secret",i);const d=await l.keyEntryToWrappedKey(i),c=await l.unwrapKey(d,r);return new L(e,t,c,a)}static async instanceFromSerialized(e){const{userId:t,accountId:r,userSecret:a,keyEntries:s}=e,i=await l.deserializeKey(a);return new L(t,r,i,s)}static async emptyInstance(e,t){return new L(e,t,null,null)}static async instanceFromPasskeyKey(e,t,r,a){f("[KM] Creating key manager from passkey-derived key");const s=l.getUserSecretKeyId(e),i=a.find(o=>o.wrappingKeyId===r.keyId&&o.keyId===s);if(!i)throw new Error("Passkey-wrapped secret key not found");const d=await l.keyEntryToWrappedKey(i),c=await l.unwrapKey(d,r);return new L(e,t,c,a)}static async instanceFromRecoveryKey(e,t,r,a){const s=l.getRecoveryKeyId(e),i=JSON.stringify({alg:"A256GCM",ext:!0,k:r,key_ops:["encrypt","decrypt","wrapKey","unwrapKey"],kty:"oct"}),d={groupType:"user",groupId:e,keyType:"sym",keyName:"recovery",keyAlgo:{name:"AES-GCM",length:256},keyOps:["encrypt","decrypt","wrapKey","unwrapKey"]},c=JSON.parse(i),o=await P.subtle.importKey("jwk",c,{name:"AES-GCM",length:256},!0,["encrypt","decrypt","wrapKey","unwrapKey"]),u={keyId:s,key:o,keyInfo:d},y=l.getUserSecretKeyId(e);let p=a.filter(m=>m.wrappingKeyId==s&&m.keyId==y);if(p.length!=1)throw new Error("Recovery key not found");const g=p[0];let h=await l.keyEntryToWrappedKey(g);const w=await l.unwrapKey(h,u);return new L(e,t,w,a)}static async instanceFromSecretKey(e,t,r,a){const s=l.getUserSecretKeyId(e),i=JSON.stringify({alg:"A256GCM",ext:!0,k:r,key_ops:["encrypt","decrypt","wrapKey","unwrapKey"],kty:"oct"}),d={groupType:"user",groupId:e,keyType:"sym",keyName:"default",keyAlgo:{name:"AES-GCM",length:256},keyOps:["encrypt","decrypt","wrapKey","unwrapKey"]},c=JSON.parse(i),o=await P.subtle.importKey("jwk",c,{name:"AES-GCM",length:256},!0,["encrypt","decrypt","wrapKey","unwrapKey"]),u={keyId:s,key:o,keyInfo:d};return new L(e,t,u,a)}isEmpty(){return this.userSecret==null}async getRecoveryKey(){if(this.isEmpty())throw new Error(`Cannot get recovery key: KeyManager is empty for user ${this.userId}`);try{const e=this.getRecoveryKeyId(),t=await this.getRecoveryKeyById(e);return f("Found key!!",t),t}catch{console.error("Not using recovery key, returning actual key")}
2return await this.getSecretKeyById(this.getUserSecretId())}async getRecoveryKeyById(e){const t=await this.getKey(e),r=await l.serializeKey(t),a=JSON.parse(r.data);return{keyString:a.k,jwk:a,serializedRecoveryKey:r}}async getSecretKeyById(e){const t=await this.getKey(e),r=await l.serializeKey(t),a=JSON.parse(r.data);return{keyString:a.k,jwk:a,serializedUserSecret:r}}async getSecretKey(){return this.getSecretKeyById(this.getUserSecretId())}async serialize(){if(this.userSecret==null)return{userId:this.userId,accountId:this.accountId,userSecret:null,keyEntries:[]};const e=this.keyEntryList;return{userId:this.userId,accountId:this.accountId,userSecret:await l.serializeKey(this.userSecret,"self"),keyEntries:e}}getUserSecretId(){if(!this.userSecret)throw new Error(`No user secret key available for user ${this.userId}`);return this.userSecret.keyId}getUserSecret(){return this.getKey(this.getUserSecretId())}getUserPublicKeyId(){return l.getUserPublicKeyId(this.userId)}getRecoveryKeyId(){return l.getRecoveryKeyId(this.userId)}getRecoveryKeyInstance(){return this.getKey(this.getRecoveryKeyId())}getAcntSecretKeyId(){return l.getAcntSecretKeyId(this.accountId)}getAcntPublicKeyId(){return l.getAcntPublicKeyId(this.accountId)}getAcntPublicKey(){return this.getKey(this.getAcntPublicKeyId())}getAcntAdminSecretKeyId(){return l.getAcntAdminSecretKeyId(this.accountId)}async getAcntSecretKey(){return this.getKey(this.getAcntSecretKeyId())}async getAcntAdminSecretKey(){return this.getKey(this.getAcntAdminSecretKeyId())}async getInvKeyId(e){const t=await this.getKey(e);if(t==null)throw new Error("KM:Key not found: "+e);return l.invKeyInfoToId(t.keyInfo)}async getInvKey(e){const t=await this.getKey(e);if(t==null)throw new Error("KM:Key not found: "+e);if(t.keyInfo.keyType=="sym")return t;const r=await l.invKeyInfoToId(t.keyInfo),a=await this.getKey(r);if(a==null)throw new Error("KM:Key not found: "+r);return a}async _getKey(e,t=new Set){var a,s;if(f("[KM] Getting key **",e,"Secret: å",(a=this.userSecret)==null?void 0:a.keyId),e!=null&&e==((s=this.userSecret)==null?void 0:s.keyId))return this.userSecret;if(e==null)throw console.error("KM:KeyId is null"),new Error("KM:KeyId is null");let r=this.keyInstanceMap.get(e);if(r==null){if(t.has(e))throw console.error("KM:Key circular reference detected",e,t),new Error("KM:Key circular reference detected: "+e);t.add(e),r=await this._unwrapKeyEntry(e,t)}return r}async getKey(e){return this._getKey(e,new Set)}async getKeyEntriesWithId(e){return this.keyEntryList.filter(t=>t.keyId==e)}async _unwrapKeyEntry(e,t){let r=await this.getKeyEntriesWithId(e);for(let a of r)try{let s=await this._unwrapKeyEntryInner(a,t);return f("[KM] success to unwrap key entry",a.keyId,s),s}catch(s){console.error("KM: Failed to unwrap key entry",a,s)}throw new Error("KM:Key not found: "+e)}async _unwrapKeyEntryInner(e,t){if(e.isWrapped){if(e.unwrappingKeyId==null)throw console.error("KM:Wrapping key not found",e.unwrappingKeyId),new Error("KM:Wrapping key not found"+e.unwrappingKeyId);const r=await l.keyEntryToWrappedKey(e),a=await this._getKey(e.unwrappingKeyId,t);if(f("[KM] Unwrapping key00",e.keyId,a.keyId,a.keyInfo),a==null)throw console.error("KM:Wrapping key not found",e.unwrappingKeyId),new Error("KM:Wrapping key not found"+e.unwrappingKeyId);const s=await l.unwrapKey(r,a);return this.keyInstanceMap.set(e.keyId,s),s}else{const r=await l.keyEntryToKeyInstance(e);return this.keyInstanceMap.set(e.keyId,r),r}}async encryptSymmetric(e,t){let r=this.encoder.encode(t),a=P.getRandomValues(new Uint8Array(12)),s=await P.subtle.encrypt({name:e.keyInfo.keyAlgo.name,iv:a},e.key,r);return{encrypted:l.ab2str(s),iv:l.ab2str(a)}}async encryptSymmetricWithIV(e,t,r){let a=this.encoder.encode(t),s=await P.subtle.encrypt({name:e.keyInfo.keyAlgo.name,iv:r},e.key,a);return l.ab2str(s)}_looksLikeJsonObjectString(e){const t=e.trim();return t.startsWith("{")||t.startsWith('"')}_looksLikeBase64Token(e){const t=e.trim();return/^[A-Za-z0-9+/_-]*={0,2}$/.test(t)&&t.length>0}_looksLikeCiphertextBase64(e){const t=e.trim();return/^(?:[a-z]{2,16}_)?[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(t)?!1:this._looksLikeBase64Token(t)&&t.length>=24}_looksLikeIvBase64(e){const t=e.trim();return this._looksLikeBase64Token(t)&&t.length>=12}_parseEncryptedValueWithOptionalIv(e,t){if(typeof e=="string"){let r=null;try{this._looksLikeJsonObjectString(e)&&(r=JSON.parse(e))}catch{r=null}let a=null,s=null;if(typeof r=="string"?(a=r,s=null):r&&typeof r=="object"&&(typeof r.encrypted=="str
2ing"&&(a=r.encrypted),typeof r.encryptedData=="string"&&(a=r.encryptedData),typeof r.iv=="string"&&(s=r.iv)),a||(a=e),!this._looksLikeCiphertextBase64(a))return{kind:"plaintext"};const i=s&&this._looksLikeIvBase64(s)?l.str2ab(s):t;return{kind:"cipher",encrypted:l.str2ab(a),iv:i}}if(e&&typeof e=="object"){const r=e;if(typeof r.encryptedData=="string"){if(!this._looksLikeCiphertextBase64(r.encryptedData))return{kind:"plaintext"};const a=typeof r.iv=="string"&&this._looksLikeIvBase64(r.iv)?l.str2ab(r.iv):t;return{kind:"cipher",encrypted:l.str2ab(r.encryptedData),iv:a}}if(typeof r.encrypted=="string"){if(!this._looksLikeCiphertextBase64(r.encrypted))return{kind:"plaintext"};const a=typeof r.iv=="string"&&this._looksLikeIvBase64(r.iv)?l.str2ab(r.iv):t;return{kind:"cipher",encrypted:l.str2ab(r.encrypted),iv:a}}}throw new Error("Unsupported encrypted value format")}async encryptObjectUsingKeyInstancePerFieldIV(e,t,r,a=1){for(const[s,i]of Object.entries(r))try{if(i.minSv&&a<i.minSv)continue;const d=i.type,c=t[s];if(c==null)continue;if(d=="string")if(typeof c=="string"){const o=await this.encryptSymmetric(e,c);t[s]=JSON.stringify(o)}else console.error("Failed to encrypt",s,c);else if(d=="object")if(typeof c=="object"){const o=await this.encryptSymmetric(e,JSON.stringify(c));t[s]={encryptedData:o.encrypted,iv:o.iv}}else console.error("Failed to encrypt",s,c);else if(d=="array")if(Array.isArray(c)){const o=[];for(const u of c){const y=await this.encryptSymmetric(e,JSON.stringify(u));o.push(JSON.stringify(y))}t[s]={data:o}}else console.error("Failed to encrypt",s,c)}catch(d){throw console.error("Failed to encrypt",s,d),d}return t}async decryptSymmetricWithCryptoKey(e,t,r,a){return await P.subtle.decrypt({name:t,iv:a},e,r)}async decryptSymmetric(e,t){let r=JSON.parse(t),a=await P.subtle.decrypt({name:e.keyInfo.keyAlgo.name,iv:l.str2ab(r.iv)},e.key,l.str2ab(r.encrypted));return this.decoder.decode(a)}async encryptString(e,t){const r=await this.getKey(e);if(!r)throw new Error("Key not found"+e);const a=await this.encryptSymmetric(r,t);return JSON.stringify(a)}async decryptString(e,t){const r=await this.getKey(e);if(!r)throw new Error("Key not found"+e);return await this.decryptSymmetric(r,t)}async wrap(e,t){const r=P.getRandomValues(new Uint8Array(12)),a=await P.subtle.exportKey("jwk",e.key),i=new TextEncoder().encode(JSON.stringify(a)),d=await P.subtle.encrypt({name:t.keyInfo.keyAlgo.name,iv:r},t.key,i);return{iv:r,wrappedData:d,keyAlgo:e.keyInfo.keyAlgo}}async unwrap(e,t){const r={name:t.keyInfo.keyAlgo.name,iv:e.iv},a=await P.subtle.decrypt(r,t.key,e.wrappedData),s=JSON.parse(l.ab2strPlain(a)),i=s;return{unwrappedKey:await P.subtle.importKey("jwk",i,e.keyAlgo,!0,s.key_ops),keyAlgo:e.keyAlgo}}async wrappedKeyToKeyInstance(e,t){const r={iv:l.str2ab(t.iv),wrappedData:l.str2ab(t.wrappedData),keyAlgo:l.deserializeAlgo(t.keyAlgo)},a=await this.unwrap(r,e);return{keyId:"temp",keyInfo:{groupType:"user",groupId:this.userId,keyType:"sym",keyName:"data",keyAlgo:a.keyAlgo,keyOps:["encrypt","decrypt"]},key:a.unwrappedKey}}async encryptObjectUsingKeyInstanceAndIV(e,t,r,a,s=1){for(const[i,d]of Object.entries(a))try{if(d.minSv&&s<d.minSv)continue;const c=d.type,o=r[i];if(o==null)continue;if(c=="string")typeof o=="string"?r[i]=JSON.stringify(await this.encryptSymmetricWithIV(e,o,t)):console.error("Failed to encrypt",i,o);else if(c=="array")if(Array.isArray(o)){let u=[];for(const y of o)if(typeof y=="object"){const p=await this.encryptSymmetricWithIV(e,JSON.stringify(y),t);u.push(p)}else typeof y=="string"&&u.push(JSON.stringify(await this.encryptSymmetricWithIV(e,y,t)));r[i]={data:u}}else console.error("Failed to encrypt",i,o);else if(c=="object")if(typeof o=="object"){const u=await this.encryptSymmetricWithIV(e,JSON.stringify(o),t);r[i]={encryptedData:u}}else console.error("Failed to encrypt",i,o)}catch(c){throw console.error("Failed to encrypt",i,c),c}return r}async encryptOrReencryptObject(e,t,r,a=!1,s){const i=t.encInfo,d=s==null?void 0:s.targetVersion,c=(s==null?void 0:s.schemaVersion)??1;if(i&&typeof i=="object"&&"keys"in i){const o=typeof i.v=="number"?i.v:1,u=d??(o>=2?2:1);return u===(o>=2?2:1)?await this.encryptObjectUsingEncInfo(i,t,r,a):await this._encryptObjectUsingEncInfoWithVersion(i,t,r,a,u,c)}return await this.encryptObjectWithKeyIds(e,t,r,a,d??1,c)}async _encryptObjectUsingEncInfoWithVersion(e,t,r,a,s,i){if(!("keys"in e))throw new Error("Cannot encrypt with decrypt-only encInfo");const d=e.keys;for(const c of d){const{unwrappingKeyId:o,wrappedEncKey:u}=c;try{const y=await this.getKey(o);if(!y)continue;const p=a?y:await this.wrappedKeyToKeyInstance(y,u);let g={...e,v:s};if(i>1?g.sv=i:delete g.sv,s===1){const h=P.getRandomValues(new Uint8Array(12));g.iv=l.ab2str(h),t=await this.encryptObjectUsingKeyInstanceAndIV(p,h,t,r)}else t=await this.encryptObjectUsingKeyInstancePerFieldIV(p,t,r),g.iv||(g.iv=l.ab2str(P.getRandomValues(new Uint8Array(12))));return{obj:t,encInfo:g}}catch{continue}}throw new Error("Failed to encrypt object")}async encryptObjectUsingEncInfo(e,t,r,a=!1){if(f("DEC (re)? encrypting using encInfo",e,t),!("keys"in e))throw new Error("Cannot encrypt with decrypt-only encInfo");const{keys:s}=e,i=typeof e.v=="number"?e.v:1;for(const d of s){const{unwrappingKeyId:c,wrappedEncKey:o}=d;try{const u=await this.getKey(c);if(!u)continue;const y=a?u:await this.wrappedKeyToKeyInstance(u,o);if(i>=2)t=await this.encryptObjectUsingKeyInstancePerFieldIV(y,t,r);else{const p=l.str2ab(e.iv),g=new Uint8Array(p);t=await this.encryptObjectUsingKeyInstanceAndIV(y,g,t,r)}return{obj:t,encInfo:e}}catch{continue}}throw new Error("Failed to encrypt object")}async encryptObjectWithKeyIds(e,t,r,a=!1,s=1,i=1){let d=[];const c=P.getRandomValues(new Uint8Array(12));if(a==!1){const o=await l.createSecretKey("onetime","onetime","onetime",["encrypt","decrypt"]);s===1?await this.encryptObjectUsingKeyInstanceAndIV(o,c,t,r,i):await this.encryptObjectUsingKeyInstancePerFieldIV(o,t,r,i);for(const u of e){let y=await this._generateWrappedKeyData(u,o);d.push(y)}}else{if(e.length!=1)throw new Error("Encryption only allowed for one key when woWrapKey is true");const o=e[0],u=await this.getKey(o);s===1?await this.encryptObjectUsingKeyInstanceAndIV(u,c,t,r,i):await this.encryptObjectUsingKeyInstancePerFieldIV(u,t,r,i),d.push({unwrappingKeyId:o,wrappingKeyId:o,wrappedEncKey:null})}return{obj:t,encInfo:{keys:d,v:s,...i>1?{sv:i}:{},iv:l.ab2str(c)}}}async _generateWrappedKeyData(e,t){const r=await this.getKey(e);
2if(!r)throw new Error("Key not found"+e);let a=e;r.keyInfo.keyType=="pub"&&(a=l.invKeyInfoToId(r.keyInfo));const s=await this.wrap(t,r);return{wrappedEncKey:{iv:l.ab2str(s.iv),wrappedData:l.ab2str(s.wrappedData),keyAlgo:l.serializeAlgo(s.keyAlgo)},wrappingKeyId:e,unwrappingKeyId:a}}async unwrapEncInfoKeyToDataKey(e){const{unwrappingKeyId:t,wrappedEncKey:r}=e,a=await this.getKey(t);if(!a)throw new Error("Key not found"+t);return await this.wrappedKeyToKeyInstance(a,r)}async generateEncInfoKeyForWrappingKey(e,t){return await this._generateWrappedKeyData(e,t)}async decryptObject(e,t,r){if(!r||!("keys"in r)||!r.keys)return e;const{keys:a,iv:s}=r,i=l.str2ab(s),d=typeof r.sv=="number"?r.sv:1;f("[KM] DEC - decryptObject",{obj:e,properties:t,encInfo:r});for(let o=0;o<a.length;o++){const u=a[o];try{let y=await this.decryptObjectWithEncInfoKey(e,t,u,i,d);if(y.decrypted)return y}catch{}}return this._hasEncryptedPayloadData(e,t,i)?(e==null||e._id,e==null||e.key,e==null||e.encrypted,console.error("Failed to decrypt object with",r),e.decrypted=!1,e):(e==null||e._id,e==null||e.key,e==null||e.encrypted,e==null||e.decrypted,e.decrypted=!0,e)}_hasEncryptedPayloadData(e,t,r){for(const[a,s]of Object.entries(t)){if(!(s!=null&&s.encrypted))continue;const i=e==null?void 0:e[a];if(i!=null)try{const d=s.type;if(d==="string"){if(this._parseEncryptedValueWithOptionalIv(i,r).kind==="cipher")return!0;continue}if(d==="object"){if(typeof i!="object")continue;const c=i==null?void 0:i.encryptedData,o=i==null?void 0:i.encrypted;if(typeof c=="string"&&this._looksLikeCiphertextBase64(c)||typeof o=="string"&&this._looksLikeCiphertextBase64(o))return!0;continue}if(d==="array"){const c=Array.isArray(i==null?void 0:i.data)?i.data:null;if(!c)continue;for(const o of c)try{if(this._parseEncryptedValueWithOptionalIv(o,r).kind==="cipher")return!0}catch{}}}catch{}}return!1}async decryptObjectWithEncInfoKey(e,t,r,a,s=1){if(!r)return e;const{wrappedEncKey:i,wrappingKeyId:d,unwrappingKeyId:c}=r;let o=await this.getKey(c);if(!o)throw new Error("Key not found"+c);let u=null;if(i!=null){const y={iv:l.str2ab(i.iv),wrappedData:l.str2ab(i.wrappedData),keyAlgo:l.deserializeAlgo(i.keyAlgo)};u=await this.unwrap(y,o)}else u={unwrappedKey:o.key,keyAlgo:o.keyInfo.keyAlgo};for(const[y,p]of Object.entries(t)){const g=e[y],h=p.type;try{if(g==null||!p.encrypted||p.minSv&&s<p.minSv)continue;if(h=="string"){const w=this._parseEncryptedValueWithOptionalIv(g,a);if(w.kind==="plaintext")continue;const m=await this.decryptSymmetricWithCryptoKey(u.unwrappedKey,u.keyAlgo.name,w.encrypted,w.iv);e[y]=l.ab2strUTF(m)}else if(h=="object"){if(typeof e[y]=="object")if(g.encryptedData){const w=this._parseEncryptedValueWithOptionalIv(g,a);if(w.kind==="plaintext")continue;const m=await this.decryptSymmetricWithCryptoKey(u.unwrappedKey,u.keyAlgo.name,w.encrypted,w.iv);e[y]=JSON.parse(l.ab2strUTF(m))}else e[y]=null}else if(h=="array"){if(Array.isArray(g.data)){let w=[];for(let m of g.data){const C=this._parseEncryptedValueWithOptionalIv(m,a);if(C.kind==="plaintext"){w.push(m);continue}const I=await this.decryptSymmetricWithCryptoKey(u.unwrappedKey,u.keyAlgo.name,C.encrypted,C.iv);w.push(JSON.parse(l.ab2strUTF(I)))}e[y]=w}}else console.error("Unsupported attr type,cannot decrypt",h)}catch(w){throw console.error("Failed to decrypt : ",y,p,e,w),w}}return e.decrypted=!0,e}}const ct={usageLimitsData:{version:2,contentUsageLimits:[]},ruleOverrideSettings:{ruleOverrides:[]},whitelistingEnabled:!1,codeInjectionEnabled:!1,contentFilteringEnabled:!1,appEditorEnabled:!1,commandBarEnabled:!1,historySearchEnabled:!1,explorePublishedEnabled:!1,emailEnabled:!1,speechModeEnabled:!1,wakeWordEnabled:!1,communityContentEnabled:!1,companionDevicesEnabled:!1,remoteChildActionsEnabled:!1,shoppingCartEnabled:!1,logActivity:!1,accessControlSettings:{takeBreakSettings:{enabled:!0,consecutiveUseMinutes:30,breakMinutes:5,includeAllTypes:!1,appliesToEduValues:["eduval_fun","eduval_edutainment"]}}};class we{constructor(e,t=null){S(this,"user");S(this,"currentUser");this.currentUser=e,this.user=t||e}get currentUserId(){var e;return(e=this.currentUser)==null?void 0:e._id}get isCurrentUser(){return this.currentUserId===this.userId}get userId(){return this.user._id}get accountId(){return this.user.accountId}}const ot={encryptHistory:!0,encryptItems:!0,encryptPostsAndComments:!0};function Ur(n,e){var t;return e?((t=n==null?void 0:n.encSettings)==null?void 0:t[e])!==!1:!1}const ee={name:{type:"string",encrypted:!0},description:{type:"string",encrypted:!0},comment:{type:"string",encrypted:!0},url:{type:"string",encrypted:!0},meta:{type:"object",encrypted:!0},sourceInfo:{type:"object",encrypted:!0},info:{type:"object",encrypted:!0},tags:{type:"object",encrypted:!0},kinds:{type:"object",encrypted:!0},patterns:{type:"object",encrypted:!0},key:{type:"string",encrypted:!0},publishId:{type:"string",encrypted:!0,minSv:2},imageFilename:{type:"string",encrypted:!0,minSv:2}},O={details:{type:"object",encryptedChildren:!0,properties:ee},pathItems:{type:"array",encryptedChildren:!0,properties:ee}},se={version:1,route:{"/ref_state/user/upsert":{encSettingsKey:"encryptItems",defaultKeyType:"user",encSchema:{type:"object",properties:{data:{type:"object",encrypted:!0}}},decSchema:{type:"object",properties:{entry:{type:"object",encryptedChildren:!0,properties:{data:{type:"object",encrypted:!0}}}}}},"/ref_state/user/list":{encSettingsKey:"encryptItems",decSchema:{type:"object",properties:{entries:{type:"array",encryptedChildren:!0,properties:{data:{type:"object",encrypted:!0}}}}}},"/ref_state/user/delete":{encSettingsKey:"encryptItems"},"/ref_state/account/upsert":{encSettingsKey:"encryptItems",defaultKeyType:"account",encSchema:{type:"object",properties:{data:{type:"object",encrypted:!0}}},decSchema:{type:"object",properties:{entry:{type:"object",encryptedChildren:!0,properties:{data:{type:"object",encrypted:!0}}}}}},"/ref_state/account/list":{encSettingsKey:"encryptItems",decSchema:{type:"object",properties:{entries:{type:"array",encryptedChildren:!0,properties:{data:{type:"object",encrypted:!0}}}}}},"/ref_state/account/delete":{encSettingsKey:"encryptItems",defaultKeyType:"account"},"/familyPolicyRule/upsert":{encSettingsKey:"encryptItems",defaultKeyType:"account",encSchema:{type:"object",properties:{data:{type:"object",encrypted:!0}}},decSchema:{type:"object",properties:{entry:{type:"object",encryptedChildren:!0,properties:{data:{type:"object",encrypted:!0}}}}}},"/familyPolicyRule/list":{encSettingsKey:"encryptItems",decSchema:{type:"object",properties:{entries:{type:"array",encryptedChildren:!0,properties:{data:{type:"object",encrypted:!0}}}}}},"/familyPolicyRule/delete":{encSettingsKey:"encryptItems",defaultKeyType:"account"},"/user/activity/logList":{decSchema:{type:"object",encTarget:"userActivityLog",properties:{userActivityLog:{encryptedChildren:!0,type:"array",properties:{data:{type:"object",encrypted:!0}}}}}},"/user/activity/push":{encSettingsKey:"encryptHistory",defaultKeyType:"user",encSchema:{type:"object",properties:{data:{type:"object",encrypted:!0}}}},"/post/create":{encSettingsKey:"encryptPostsAndComments",defaultKeyType:"account",encSchema:{type:"object",properties:{data:{type:"object",encrypted:!0}}}},"/subscription/add":{encSettingsKey:"encryptItems",defaultKeyType:"account",encSchema:{type:"object",properties:{data:{type:"object",encrypted:!0}}}},"/subscription/listForUser":{encSettingsKey:"encryptItems",decSchema:{type:"array",encryptedChildren:!0,properties:{data:{type:"object",encrypted:!0}}}},"/subscription/listForRef":{encSettingsKey:"encryptItems",decSchema:{type:"array",encryptedChildren:!0,properties:{data:{type:"object",encrypted:!0}}}},"/subscription/edit":{encSettingsKey:"encryptItems",defaultKeyType:"account",encSchema:{type:"object",properties:{data:{type:"object",encrypted:!0}}}},"/comment/create":{encSettingsKey:"encryptPostsAndComments",defaultKeyType:"account",encSchema:{type:"object",properties:{data:{type:"object",encrypted:!0}}}},"/comment/list":{decSchema:{type:"object",properties:{records:{encryptedChildren:!0,type:"array",properties:{data:{type:"object",encrypted:!0}}}}}},"/feed/getByPostId":{encSettingsKey:"encryptHistory",defaultKeyType:"account",decSchema:{type:"object",properties:{data:{encryptedChildren:!0,type:"object",properties:{data:{type:"object",encrypted:!0}}}}}},"/library/root":{encSettingsKey:"encryptItems",decSchema:{type:"array",properties:O}},"/collection/listByUser":{encSettingsKey:"encryptItems",decSchema:{type:"array",properties:O}},"/collection/listByIds":{encSettingsKey:"encryptItems",decSchema:{type:"array",properties:O}},"/item/parents/bychildid":{encSettingsKey:"encryptItems",decSchema:{type:"array",properties:O}},"/item/query":{encSettingsKey:"encryptItems",decSchema:{type:"object",properties:{items:{type:"array",properties:O}}}},"/item/listSharedWithUser":{encSettingsKey:"encryptItems",decSchema:{type:"array",properties:O}},"/item/listSharedByUser":{encSettingsKey:"encryptItems",decSchema:{type:"array",properties:O}},"/item/listRecentAccessibleByUser":{encSettingsKey:"encryptItems",decSchema:{type:"array",properties:O}},"/collection/items":{encSettingsKey:"encryptItems",decSchema:{type:"array",properties:O}},"/item/listByIds":{encSettingsKey:"encryptItems",decSchema:{type:"array",properties:O}},"/item/listWithFeedback":{encSettingsKey:"encryptItems",decSchema:{type:"array",properties:O}},"/library/archived":{encSettingsKey:"encryptItems",decSchema:{type:"array",properties:O}},"/library/hidden":{encSettingsKey:"encryptItems",decSchema:{type:"array",properties:O}},"/library/uncategorized":{encSettingsKey:"encryptItems",decSchema:{type:"array",properties:O}},"/item/findWithPublishId":{encSettingsKey:"encryptItems",decSchema:{type:"array",properties:O}},"/item/pathtree":{encSettingsKey:"encryptItems",decSchema:{type:"array",properties:{item:{type:"object",encryptedChildren:!0,properties:ee}}}},"/sync/update":{encSettingsKey:"encryptItems",decSchema:{type:"object",properties:{updatedItems:{type:"array",properties:O}}}},"/item/infoById":{encSettingsKey:"encryptItems",decSchema:{type:"object",properties:O}},"/collection/getItemRelInfo":{encSettingsKey:"encryptItems",defaultKeyType:"account",decSchema:{type:"object",encryptedChildren:!0,properties:{details:{type:"object",encrypted:!0}}}},"/collection/itemDetails/save":{encSettingsKey:"encryptItems",defaultKeyType:"account",encSchema:{type:"object",encTarget:"details",encryptedChildren:!0,properties:{details:{type:"object",encrypted:!0}}}},"/item/update":{encSettingsKey:"encryptItems",defaultKeyType:"account",encSchema:{type:"object",constraintFunc:async(n,e)=>{var t;return((t=n==null?void 0:n.data)==null?void 0:t.encInfo)!=null},encTarget:"data",properties:{data:{type:"object",encryptedChildren:!0,properties:ee}}}},"/item/duplicates/merge":{encSettingsKey:"encryptItems",defaultKeyType:"account",encSchema:{type:"object",constraintFunc:async(n,e)=>{var t;
2return((t=n==null?void 0:n.mergedDetails)==null?void 0:t.encInfo)!=null},encTarget:"mergedDetails",properties:{mergedDetails:{type:"object",encryptedChildren:!0,properties:ee}}}},"/collection/create":{encSettingsKey:"encryptItems",defaultKeyType:"account",encSchema:{type:"object",encTarget:"details",properties:{details:{type:"object",encryptedChildren:!0,properties:ee}}}},"/collection/showcase/create":{encSettingsKey:"encryptItems",defaultKeyType:"account",encSchema:{type:"object",encTarget:"details",properties:{details:{type:"object",encryptedChildren:!0,properties:ee}}}},"/item/save":{encSettingsKey:"encryptItems",defaultKeyType:"account",encSchema:{type:"object",encTarget:"details",properties:O}}}};function ae(n){const e=new Uint8Array(n);let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Pe(n){for(n=n.replace(/-/g,"+").replace(/_/g,"/");n.length%4;)n+="=";const e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t.buffer}function le(n){return n instanceof ArrayBuffer?n:n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)}const Tr="kindredly-passkey-prf-v1:",_r="kindredly-passkey-prf-discoverable-v1";class Oe{static isLikelyAppleWebKitPasskeySurface(e){const t=/iPhone|iPad|iPod/i.test(e)&&/AppleWebKit/i.test(e),r=/CriOS|FxiOS|EdgiOS|OPiOS/i.test(e);return t&&!r}static async getClientCapabilities(){if(!this.isWebAuthnSupported())return null;try{if(typeof PublicKeyCredential.getClientCapabilities!="function")return null;const e=await PublicKeyCredential.getClientCapabilities();return!e||typeof e!="object"?null:e}catch{return null}}static async evaluateCredentialPRF(e){var i,d,c;const t={publicKey:{challenge:new TextEncoder().encode(this.generateChallenge()),rpId:e.rpId,allowCredentials:[{type:"public-key",id:Pe(e.credentialId),transports:["internal","hybrid","usb","ble","nfc"]}],userVerification:"preferred",timeout:6e4,extensions:{prf:{eval:{first:new Uint8Array(e.firstSalt),second:e.secondSalt?new Uint8Array(e.secondSalt):void 0}}}}},r=await navigator.credentials.get(t);if(!r)return{};const s=(((i=r.getClientExtensionResults)==null?void 0:i.call(r))||{}).prf;return{first:(d=s==null?void 0:s.results)!=null&&d.first?le(s.results.first):void 0,second:(c=s==null?void 0:s.results)!=null&&c.second?le(s.results.second):void 0}}static isWebAuthnSupported(){return!!(window.PublicKeyCredential&&typeof window.PublicKeyCredential=="function")}static async isPlatformAuthenticatorAvailable(){if(!this.isWebAuthnSupported())return!1;try{return await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}static async isConditionalMediationAvailable(){if(!this.isWebAuthnSupported())return!1;try{return PublicKeyCredential.isConditionalMediationAvailable?await PublicKeyCredential.isConditionalMediationAvailable():!1}catch{return!1}}static async isPRFLikelySupported(){if(!this.isWebAuthnSupported())return!1;try{const e=await this.getClientCapabilities();if((e==null?void 0:e.passkeyPlatformAuthenticator)===!0)return!0;if(!await this.isPlatformAuthenticatorAvailable())return!1;const r=navigator.userAgent;if(this.isLikelyAppleWebKitPasskeySurface(r))return!0;const a=r.match(/Chrome\/(\d+)/);if(a&&parseInt(a[1])>=116)return!0;const s=r.match(/Version\/(\d+).*Safari/);if(s&&parseInt(s[1])>=17)return!0;if(r.includes("Firefox"))return!1;const i=r.match(/Edg\/(\d+)/);return!!(i&&parseInt(i[1])>=116)}catch{return!1}}static generatePRFSalt(e){const t=new TextEncoder,r=Tr+e;return t.encode(r).buffer}static generateDiscoverablePRFSalt(){return new TextEncoder().encode(_r).buffer}static async registerPasskey(e){var c,o,u,y,p,g,h;f("PasskeyUtils: Registering passkey for",e.username);const t=new TextEncoder().encode(e.challenge),r=new TextEncoder().encode(e.userId),a=this.generatePRFSalt(e.userId),s=this.generateDiscoverablePRFSalt(),i=(e.existingCredentialIds||[]).map(w=>({type:"public-key",id:Pe(w),transports:["internal","hybrid","usb","ble","nfc"]})),d={publicKey:{challenge:t,rp:{name:e.rpName,id:e.rpId},user:{id:r,name:e.username,displayName:e.displayName},pubKeyCredParams:[{alg:-7,type:"public-key"},{alg:-257,type:"public-key"}],authenticatorSelection:{authenticatorAttachment:e.preferPlatformAuthenticator?"platform":void 0,residentKey:"preferred",userVerification:"preferred"},timeout:6e4,attestation:"none",excludeCredentials:i,extensions:{prf:{eval:{first:new Uint8Array(s),second:new Uint8Array(a)}}}}};try{const w=await navigator.credentials.create(d);if(!w)throw new Error("No credential returned from authenticator");const m=w.response,I=(((c=w.getClientExtensionResults)==null?void 0:c.call(w))||{}).prf,U=ae(w.rawId);let b;(o=I==null?void 0:I.results)!=null&&o.first&&(b=le(I.results.first));let A;if((u=I==null?void 0:I.results)!=null&&u.second&&(A=le(I.results.second)),!b||!A)try{const F=await this.evaluateCredentialPRF({credentialId:U,rpId:e.rpId,firstSalt:s,secondSalt:a});b||(b=F.first),A||(A=F.second)}catch(F){f("PasskeyUtils: Registration PRF follow-up assertion failed",F)}const T=!!(b||A||I!=null&&I.enabled||(y=I==null?void 0:I.results)!=null&&y.first||(p=I==null?void 0:I.results)!=null&&p.second),J=(g=m.getTransports)==null?void 0:g.call(m),v={credentialId:U,publicKey:ae(((h=m.getPublicKey)==null?void 0:h.call(m))||new ArrayBuffer(0)),userId:e.userId,createdAt:new Date().toISOString(),transports:J,prfSupported:T};return f("PasskeyUtils: Registration successful, PRF supported:",T),{credential:v,prfOutput:A,discoverablePrfOutput:b,attestationObject:ae(m.attestationObject),clientDataJSON:ae(m.clientDataJSON)}}catch(w){throw f("PasskeyUtils: Registration failed",w),w}}static async authenticateWithPasskey(e){var d,c,o,u;f("PasskeyUtils: Authenticating with passkey");const t=new TextEncoder().encode(e.challenge),r=e.mode==="legacy"&&e.userId?this.generatePRFSalt(e.userId):this.generateDiscoverablePRFSalt(),a=(d=e.allowCredentials)==null?void 0:d.map(y=>({type:"public-key",id:Pe(y.credentialId),transports:y.transports||["internal","hybrid","usb","ble","nfc"]})),s={};r&&(s.prf={eval:{first:new Uint8Array(r)}});const i={publicKey:{challenge:t,rpId:e.rpId,allowCredentials:a!=null&&a.length?a:void 0,userVerification:"preferred",timeout:6e4,extensions:Object.keys(s).length>0?s:void 0},mediation:e.conditionalMediation?"conditional":void 0};try{const y=await navigator.credentials.get(i);if(!y)throw new Error("No credential returned from authenticator");const p=y.response,h=(((c=y.getClientExtensionResults)==null?void 0:c.call(y))||{}).prf,w=!!((o=h==null?void 0:h.results)!=null&&o.first);let m;if((u=h==null?void 0:h.results)!=null&&u.first){const I=h.results.first;m=I instanceof ArrayBuffer?I:I.buffer.slice(I.byteOffset,I.byteOffset+I.byteLength),f("PasskeyUtils: PRF output received, length:",m.byteLength)}const C={credentialId:ae(y.rawId),prfOutput:m,prfSupported:w,signature:p.signature,authenticatorData:p.authenticatorData,clientDataJSON:p.clientDataJSON};return f("PasskeyUtils: Authentication successful, PRF supported:",w),
2C}catch(y){throw f("PasskeyUtils: Authentication failed",y),y}}static async deriveKeyFromPRF(e,t,r="legacy"){f("PasskeyUtils: Deriving key from PRF output");const a=await P.subtle.importKey("raw",e,"HKDF",!1,["deriveKey"]),s=new TextEncoder,i=s.encode("kindredly-passkey-key-v1"),d=s.encode(`passkey-wrap-key:${t}`),c=await P.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:i,info:d},a,{name:"AES-GCM",length:256},!1,["wrapKey","unwrapKey","encrypt","decrypt"]),o={groupType:"user",groupId:t,keyType:"sym",keyName:r==="discoverable"?"passkeyDiscoverable":"passkey",keyAlgo:{name:"AES-GCM",length:256},keyOps:["wrapKey","unwrapKey","encrypt","decrypt"]};return{keyId:r==="discoverable"?l.getDiscoverablePasskeyKeyId(t):l.getPasskeyKeyId(t),key:c,keyInfo:o}}static getPasskeyKeyId(e){return l.keyFieldsToId({groupType:"user",groupId:e,keyType:"sym",keyName:"passkey",version:0})}static async wrapSecretWithPasskey(e,t){f("PasskeyUtils: Wrapping secret with passkey-derived key");const r=await l.wrapKey(e,t);return await l.serializeWrappedKey(r,"self")}static generateChallenge(){const e=new Uint8Array(32);return P.getRandomValues(e),ae(e.buffer)}}const dt="[ENC_GRANT]",j=class j{constructor(){S(this,"passwordSyncVerifiedSig",new Map);S(this,"passwordKdfUpgradeInFlight",new Set);S(this,"stalePasswordKeyRepairInFlight",new Set)}static get instance(){return this._instance||(this._instance=new j),this._instance}static passwordSyncSignature(e,t){var d,c;const r=((d=t==null?void 0:t.keyData)==null?void 0:d.wrappedKey)||"",a=String(((c=t==null?void 0:t.keyData)==null?void 0:c.kdfIterations)??""),s=`${e} ${r} ${a}`;let i=5381;for(let o=0;o<s.length;o++)i=(i<<5)+i+s.charCodeAt(o)|0;return String(i>>>0)}async maybeUpgradePasswordKdf(e,t,r,a){var d,c;const s=((d=r==null?void 0:r.keyData)==null?void 0:d.kdfIterations)??ze,i=!!((c=r==null?void 0:r.keyData)!=null&&c.kdfSalt);if(!(s>=nt&&i)&&!this.passwordKdfUpgradeInFlight.has(e)){this.passwordKdfUpgradeInFlight.add(e);try{const o=await a.getUserSecret();if(!o)return;f("[EKS] Upgrading password KDF",e,s,"->",nt),await this.setEncPasswordWithKey(e,t,o),this.passwordSyncVerifiedSig.delete(e)}catch(o){console.error("[EKS] Password KDF upgrade failed (non-fatal)",o)}finally{this.passwordKdfUpgradeInFlight.delete(e)}}}static async unwrapsWithKey0Constant(e){var t,r;try{const a=((t=e==null?void 0:e.keyData)==null?void 0:t.kdfIterations)??ze,s=((r=e==null?void 0:e.keyData)==null?void 0:r.kdfSalt)??M.passwordEncSalt,i=await l.createPasswordKey("null",s,"password",a),d=await l.keyEntryToWrappedKey(e);return await l.unwrapKey(d,i),!0}catch{return!1}}static async canOpenUserSecret(e){if(!e)return!1;try{return await e.getUserSecret()!=null}catch{return!1}}async maybeRemoveStalePasswordKey(e,t,r,a,s){if(e.currentUserId!==t||r||!a)return;const i=l.getUserSecretKeyId(t),d=s.find(c=>c.keyId===i&&c.unwrappingKeyId==="userPassword"&&!c.deletedAt);if(d&&await j.unwrapsWithKey0Constant(d)&&!this.stalePasswordKeyRepairInFlight.has(t)){this.stalePasswordKeyRepairInFlight.add(t);try{f("[KND_SECURITY] Removing constant-wrapped user secret (KEY-0) for",t),await k("/user/encryption/deletePasswordWrappedSecret",{userId:t})}catch(c){console.error("[EKS] KEY-0 repair failed (non-fatal)",c)}finally{this.stalePasswordKeyRepairInFlight.delete(t)}}}async encStatus(e,t=!1){if(await q())return{hasPassword:!1,hasCachedPassword:!1,userEncSetup:!1,userRecoveryKeyExists:!1,acntEncSetup:!1,userEncEnabled:!1,acntEncEnabled:!1,acntEncSupported:!1,needsPassword:!1};f("[EKS] Getting enc status for",e.user.username,"force:",t);const r=e.userId,a=e.accountId;if(!r||!a)throw console.error("User or account not defined",r,a),new R(`User or account not defined ${r} ${a}`);const s=await k("/user/encryption/listKeys",{userId:r},{forceRefresh:!0});f("[EKS] Current keys for",r,"count:",s==null?void 0:s.length);const i=l.getUserSecretKeyId(r),d=l.getAcntSecretKeyId(a),c=l.getRecoveryKeyId(r),o=s.findIndex(A=>A.keyId===i)!=-1,u=s.findIndex(A=>A.keyId===c)!=-1,y=s.findIndex(A=>A.keyId===d)!=-1,p=s.filter(A=>A.selectType==="account").length>0,g=e.user.hasPassword==!0,h=await D.getEncPassword(r),w=!!h;let m=!1,C=!1,I=!1;try{const A=$.instance;let T=await A.getKeyManagerFromKeys(e.currentUserId,r,a,s);const J=await j.canOpenUserSecret(T);if(!J){const v=await A.getKeyManager(e.currentUserId,r,a);await j.canOpenUserSecret(v)&&(T=v)}if(T){try{if(m=await T.getUserSecret()!=null,e.user.type=="restricted"){const v=l.getUserSecretKeyId(r),F=await T.getSecretKeyById(v);F!=null&&F.keyString&&(f("[EKS] User secret key found p1:",r),await D.setEncSecretyKey(r,F==null?void 0:F.keyString))}if(e.currentUserId==r&&g&&h){const v=s.find(E=>E.keyId===i),F=j.passwordSyncSignature(h,v);if(this.passwordSyncVerifiedSig.get(r)===F)I=!0;else{f("[EKS] Checking password sync for",r);try{let E=await L.instanceFromPassword(r,a,h,M.passwordEncSalt,s);if(!E)throw new Error("Passwords not in sync");const z=await E.getSecretKeyById(i);z?z!=null&&z.keyString&&f("[EKS] User secret key found p2:",r):f("[EKS] No user secret key found for",r),I=!0,this.passwordSyncVerifiedSig.set(r,F)}catch(E){console.error("[EKS]",E.message,E),this.passwordSyncVerifiedSig.delete(r);const z=await T.getUserSecret();f("[EKS] Syncing encryption password for",r),await this.setEncPasswordWithKey(e.userId,h,z)}}I&&M.passwordKdfV2Enabled&&await this.maybeUpgradePasswordKdf(r,h,v,T)}await this.maybeRemoveStalePasswordKey(e,r,g,J,s)}catch(v){console.error("** *Error getting user secret key",v)}try{y?C=await T.getAcntSecretKey()!=null:C=!1}catch(v){console.error(`${dt} ** Error getting account secret key`,v);try{const F=(s||[]).map(E=>({keyId:E==null?void 0:E.keyId,selectType:E==null?void 0:E.selectType,permission:E==null?void 0:E.permission,groupType:E==null?void 0:E.groupType,groupId:E==null?void 0:E.groupId}));f(`${dt} [EKS] acnt secret load failed`,{currentUserId:e.currentUserId,targetUserId:r,accountId:a,acntSecretKeyId:d,userSecretKeyId:i,acntEncSetup:y,acntEncSupported:p,keyCount:s==null?void 0:s.length,keys:F,err:(v==null?void 0:v.message)||String(v)}
2)}catch{}}}}catch{}const b={hasPassword:g,hasCachedPassword:w,userEncSetup:o,userRecoveryKeyExists:u,acntEncSetup:y,userEncEnabled:m,acntEncEnabled:C,acntEncSupported:p,needsPassword:g&&o&&!w&&!m,passwordSyncVerified:I};return D.set(r,"encStatus",{statusResults:b,cacheTime:new Date().getTime()}),b}async setEncPassword(e,t){f("Changing enc password for ",e.user.username);const a=await(await this.getKeyManager(e)).getUserSecret();await this.setEncPasswordWithKey(e.userId,t,a)}async setEncPasswordWithKey(e,t,r){const a=await l.generateNewPasswordWrappedKey(t,M.passwordEncSalt,r),s=await l.serializeWrappedKey(a.secretWrapped,"self"),i=await l.serializedKeyThingToKeyEntry(s);await k("/user/encryption/saveUserKeys",{userId:e,keyList:[i]})}async generateNewRecoveryKey(e){const r=await(await this.getKeyManager(e,!0)).getUserSecret(),a=await l.generateRecoveryKeys(e.userId,r),s=await l.serializeWrappedKey(a.recoveryKeyWrapped,"user"),i=await l.serializeWrappedKey(a.recoverySecretWrapped,"user"),d=await l.serializedKeyThingToKeyEntry(s),c=await l.serializedKeyThingToKeyEntry(i);await k("/user/encryption/saveUserKeys",{userId:e.userId,keyList:[d,c]})}async getRecoveryKey(e){const t=await this.getKeyManager(e,!0);if(t.isEmpty())throw new R(`No key access available for user ${e.userId}. You may need to log in as this user or have their keys shared with you.`,403,null,"NO_KEY_ACCESS");try{return await t.getRecoveryKey()}catch(r){throw console.error("Error getting recovery key",r),new R("Error getting recovery key")}}async saveRecoveryKeyOnServer(e){const r=await(await this.getKeyManager(e,!0)).getRecoveryKey();await k("/auth/saveRecoveryKeyOnServer",{userId:e.userId,recoveryKey:r.keyString})}async removeRecoveryKeyFromServer(e,t){if(t.method==="password"){const r=await l.hashPassword(t.password,M.passwordSalt);await k("/auth/removeRecoveryKeyFromServer",{method:"password",password:r,userId:e.userId});return}await k("/auth/removeRecoveryKeyFromServer",{...t,userId:e.userId})}async createAccountBackupKey(e){f("createAccountBackupKey enc password for ",e.user.username);const r=await(await this.getKeyManager(e)).getAcntSecretKey(),a=l.randomUUID(),s=await l.hashPassword(a,M.passwordEncSalt),i=await l.generateNewPasswordWrappedKey(s,M.passwordEncSalt,r),d=await l.serializeWrappedKey(i.secretWrapped,"admin"),c=await l.serializedKeyThingToKeyEntry(d);return await k("/user/encryption/saveAccountKeys",{keyList:[c]}),a}async shareAccountKey(e,t){f("[EKS] shareAccountKey for",e.user.username,"targetUserId:",t),f("[ENC:SHARE_ACCT_KEY] Starting to share account key",{currentUser:e.userId,targetUser:t});const r=await this.getKeyManager(e,!0),s=(await k("/user/encryption/listKeys",{userId:t},{forceRefresh:!0})).find(y=>y.selectType==="user"&&y.keyType==="pub");f("[EKS] Pub key entry found:",!!s),f("[ENC:SHARE_ACCT_KEY] Found public key for user",{userId:t,hasPubKey:!!s});const i=await l.keyEntryToKeyInstance(s),d=await r.getAcntSecretKey(),c=await l.wrapKey(d,i),o=await l.serializeWrappedKey(c,"user"),u=await l.serializedKeyThingToKeyEntry(o);return await k("/user/encryption/saveUserKeys",{userId:t,keyList:[u]}),f("[ENC:SHARE_ACCT_KEY] Successfully shared account key with user",t),!0}async generateKeys(e){f("[EKS] Generating keys for",e.userId);const t=e.userId,r=e.accountId;if(!t||!r)throw console.error("User or account not defined",t,r),new R(`User or account not defined ${t} ${r}`);await k("/encryption/updateSettings",{userId:e.userId,encSettings:ot});const a=await D.getEncPassword(t),s=await k("/user/encryption/listKeys",{userId:t},{forceRefresh:!0}),i=s.filter(p=>p.selectType==="account"),d=s.filter(p=>p.selectType==="user"&&p.selectId==t),c=i.length==0,o=d.length==0,u=e.user.type=="admin";let y=null;if(f("About to save keys"),u&&c&&o){if(f("Saving keys1"),!e.isCurrentUser)throw new R("Only current user can create new account");const p=await l.generateUserKeyBundleForNewAccount(t,r,a,M.passwordEncSalt);e.isCurrentUser&&p.userSecretKeyString&&(y=p.userSecretKeyString,await D.setEncSecretyKey(t,p.userSecretKeyString));const g=await l.serializedKeyMapToKeyEntries(p.user),h=await l.serializedKeyMapToKeyEntries(p.acnt);await k("/user/encryption/saveUserKeys",{keyList:g,userId:t}),await k("/user/encryption/saveAccountKeys",{keyList:h})}else if(u&&!c&&o){if(f("Saving keys2"),!e.isCurrentUser)throw new R("Only current user can create new account");const p=await l.generateUserKeys(t,a,M.passwordEncSalt),g={userPublicKey:await l.serializeKey(p.publicKey,"public"),userSecretWrapped:p.secretWrapped?await l.serializeWrappedKey(p.secretWrapped,"self"):void 0,userPrivateKeyWrapped:await l.serializeWrappedKey(p.privateKeyWrapped,"user"),userRecoveryKeyWrapped:await l.serializeWrappedKey(p.recoveryKeyWrapped,"user"),userRecoverySecretWrapped:await l.serializeWrappedKey(p.recoverySecretWrapped,"user")},h=await l.getSymmetricKeyString(p.secret);e.isCurrentUser&&h&&(y=h,await D.setEncSecretyKey(t,h));const w=await l.serializedKeyMapToKeyEntries(g);await k("/user/encryption/saveUserKeys",{keyList:w,userId:t})}else if(!u&&o){f("Saving keys3");const p=await l.generateUserKeys(t,a,M.passwordEncSalt),g={userPublicKey:await l.serializeKey(p.publicKey,"public"),userSecretWrapped:p.secretWrapped?await l.serializeWrappedKey(p.secretWrapped,"self"):void 0,userPrivateKeyWrapped:await l.serializeWrappedKey(p.privateKeyWrapped,"user"),userRecoveryKeyWrapped:await l.serializeWrappedKey(p.recoveryKeyWrapped,"user"),userRecoverySecretWrapped:await l.serializeWrappedKey(p.recoverySecretWrapped,"user")},h=await l.getSymmetricKeyString(p.secret);e.isCurrentUser&&h&&(y=h,await D.setEncSecretyKey(t,h));const w=await l.serializedKeyMapToKeyEntries(g);await k("/user/encryption/saveUserKeys",{userId:t,keyList:w});const m=await this.getKeyManager(e,!0),C=await m.getUserSecret(),I=await m.getAcntPublicKey(),U=await l.wrapKey(C,I),A={wrappedUserSecret:await l.serializeWrappedKey(U,"admin")},T=await l.serializedKeyMapToKeyEntries(A);await k("/user/encryption/saveAccountKeys",{userId:t,keyList:T})}else throw console.error("User or account keys already exist"),new R("User or account keys already exist");if(e.currentUserId!==t&&await $.instance.getKeyManager(e.currentUserId,t,r,!0))try{await this.shareAccountKey(new we(e.currentUser),t)}catch(h){console.error("Error sharing account key",h)}return{cachedUserSecretKeyString:y}
2}async generateKeysForRestrictedUser(e){const t=e.userId,r=e.accountId;f("[ENC:GEN_RESTRICTED_KEYS] Starting for user",t),await k("/encryption/updateSettings",{userId:t,encSettings:ot});const s=await(await $.instance).getKeyManager(e.currentUserId,e.currentUserId,r,!0),i=await s.getSecretKeyById(s.getUserSecretId());await D.setEncSecretyKey(e.currentUserId,i==null?void 0:i.keyString),f("[ENC:GEN_RESTRICTED_KEYS] Generating user key bundle",t);const d=await l.generateUserKeyBundleWithAccountSecretKey(e.userId,await s.getAcntSecretKey()),c=await l.serializedKeyMapToKeyEntries(d.user);await k("/user/encryption/saveUserKeys",{userId:t,keyList:c});const o=await l.serializedKeyMapToKeyEntries(d.acnt);await k("/user/encryption/saveAccountKeys",{keyList:o}),f("[ENC:GEN_RESTRICTED_KEYS] Sharing account key with user",t),await this.shareAccountKey(new we(e.currentUser),t),f("[ENC:GEN_RESTRICTED_KEYS] Successfully completed for user",t)}async getKeyManager(e,t=!1){f("[EKS] getKeyManager","userId:",e.userId,"currentUserId:",e.currentUserId,"accountId:",e.accountId,"forceRefresh:",t);const r=e.userId,a=e.accountId;if(!r||!a)return console.error("[EKS] User or account not defined",r,a),null;try{return await $.instance.getKeyManager(e.currentUserId,r,a,t)}catch(s){return console.error("[EKS] Error getting key manager",r,a,s),null}}async getEncryptionKeys(e){f("[EKS] Getting encryption keys for",e.userId);const t=await this.getKeyManager(e);return t?(f("[EKS] KM found for",e.userId),await t.serialize()):(console.error("[EKS] KM not defined for",e.userId),null)}async listKeys(e,t=null){return await k("/user/encryption/listKeys",{userId:t||e.userId})}async listKeysWithStatus(e,t=null){t=t||e.userId;const r=await k("/user/encryption/listKeys",{userId:t});f("[EKS] Keys for",t,"count:",r==null?void 0:r.length);const s=await $.instance.getKeyManagerFromKeys(e.currentUserId,t,e.accountId,r);for(const i of r){let d=!1;try{await s.getKey(i.keyId)&&(d=!0)}catch(c){console.error("[EKS] Error getting key",i==null?void 0:i.keyId,c)}i.keyAccess=d}return r}async getKeyBackup(e){f("[EKS] Getting key backup for",e.userId);const t=await this.getKeyManager(e);if(t)return await t.serialize();throw console.error("[EKS] KM not defined for getKeyBackup",e.userId),new R("KM not defined")}async encryptData(e,t){f("Encrypting data");const r=await this.getKeyManager(e);return r?await r.encryptString(r.getUserSecretId(),JSON.stringify(t)):(console.error("Encryption not setup for user"),null)}async decryptData(e,t){f("Decrypting data");const r=await this.getKeyManager(e);return r?JSON.parse(await r.decryptString(r.getUserSecretId(),t)):(console.error("Encryption not setup for user"),null)}async setPasskeyWrappedSecret(e,t,r,a){f("Setting passkey-wrapped secret for",e.user.username);const s=await this.getKeyManager(e,!0);if(!s||s.isEmpty())throw new R("Encryption not setup for user",400);const i=await s.getUserSecret(),d=[];if(t){const c=await Oe.deriveKeyFromPRF(t,e.userId),o=await l.wrapKey(i,c),u=await l.serializeWrappedKey(o,"self");d.push(await l.serializedKeyThingToKeyEntry(u))}if(a){const c=await Oe.deriveKeyFromPRF(a,e.userId,"discoverable"),o=await l.wrapKey(i,c),u=await l.serializeWrappedKey(o,"self");d.push(await l.serializedKeyThingToKeyEntry(u))}if(d.length===0)throw new R("Passkey PRF output unavailable for encrypted-data unlock.",400);return await k("/user/encryption/saveUserKeys",{userId:e.userId,keyList:d}),f("Passkey-wrapped secret saved successfully"),!0}async hasPasskeyWrappedSecret(e){const t=await k("/user/encryption/listKeys",{userId:e.userId},{forceRefresh:!0}),r=[l.getPasskeyKeyId(e.userId),l.getDiscoverablePasskeyKeyId(e.userId)],a=l.getUserSecretKeyId(e.userId);return t.some(s=>r.includes(s.wrappingKeyId)&&s.keyId===a)}async unlockWithPasskey(e,t){f("Attempting to unlock encryption with passkey for",e.user.username);try{const r=await k("/user/encryption/listKeys",{userId:e.userId},{forceRefresh:!0}),a=l.getUserSecretKeyId(e.userId),s=[];r.some(i=>i.wrappingKeyId===l.getDiscoverablePasskeyKeyId(e.userId)&&i.keyId===a)&&s.push("discoverable"),r.some(i=>i.wrappingKeyId===l.getPasskeyKeyId(e.userId)&&i.keyId===a)&&s.push("legacy"),s.length===0&&s.push("discoverable","legacy");for(const i of s)try{const d=await Oe.deriveKeyFromPRF(t,e.userId,i),c=await L.instanceFromPasskeyKey(e.userId,e.accountId,d,r);if(c&&!c.isEmpty()){const o=await c.getSecretKey();return o!=null&&o.keyString&&await D.setEncSecretyKey(e.userId,o.keyString),f("Passkey unlock successful with variant",i),!0}}catch(d){f("Passkey unlock variant failed",i,d)}}catch(r){console.error("Passkey unlock failed:",r)}return!1}async removePasskeyWrappedSecret(e){return f("Passkey wrapped secret removal requested (no-op for now)"),!0}};S(j,"_instance",null);let N=j;const Sa=Object.freeze(Object.defineProperty({__proto__:null,EncryptionKeyService:N},Symbol.toStringTag,{value:"Module"})),Fr="eduval_unknown",ut=0,Rr="guardian";function Pr(n){if(typeof n!="number"||!Number.isFinite(n))return ut;const e=Math.trunc(n);return e<0||e>23?ut:e}function Or(n,e){const t=Pr(e),r=new Date(n),a=new Date(r.getFullYear(),r.getMonth(),r.getDate(),t,0,0,0);return a.getTime()<=n&&a.setDate(a.getDate()+1),a.getTime()}
2function Lr(n,e,t=Date.now()){if(!n||n.enabled!==!0)return!1;const r=e==null?void 0:e.releasedUntilMs;return!(typeof r=="number"&&Number.isFinite(r)&&r>t)}function Te(n){const e=n==null?void 0:n.mode;return e==="reminder"||e==="self"||e==="guardian"?e:Rr}function ka(n){return n==="restricted"?"guardian":"self"}function ba(n){return Te(n)!=="guardian"}function va(n,e,t=Date.now()){return Te(n)==="reminder"?!1:Lr(n,e,t)}function Dr(n,e,t,r){return{releasedAtMs:n,releasedUntilMs:Or(n,e==null?void 0:e.resetHourLocal),releasedByUserId:t||void 0,releasedBySelf:r===!0?!0:void 0}}function Ea(n){const e=n==null?void 0:n.exceptions;return Array.isArray(e)?e.some(t=>((t==null?void 0:t.conditions)||[]).some(r=>(r==null?void 0:r.type)==="eduValue"&&((r==null?void 0:r.values)||[]).some(a=>a!==Fr))):!1}function Mr(n){const e=n==null?void 0:n.taskGate;return(e==null?void 0:e.enabled)!==!0?!1:Array.isArray(e.requiredTaskIds)&&e.requiredTaskIds.length>0}function Wr(n){return Te(n)!=="self"?!1:Mr(n)}const Le="local_account",ke=class ke{constructor(){}static get instance(){return this._staticInstance||(this._staticInstance=new ke),this._staticInstance}async getAccountDb(){const e=await Ce();if(!e)throw new Error("LocalUserRepo.getAccountDb: No current user or accountId available");return e}async getUserById(e){if(!e)throw new R("userId required",400);return await(await this.getAccountDb()).getUserById(e)}async getUserByIdLocalOnly(e){if(!e)throw new R("userId required",400);return await ge(Le).getUserById(e)}async updateAccountUsersLocal(e){const t=await K.instance.getCurrentUser();if(!t)return;if(e&&e.length>0){const a=e.find(s=>s._id===(t==null?void 0:t._id));a&&await K.instance.updateUserObj(a)}const r=await this.getAccountDb();await r.clearUsers(),await r.upsertUsers(e)}async listAccountUsersLocal(){const e=await K.instance.getCurrentUser();if(!e)return;const r=await(await this.getAccountDb()).getAllUsers(),a=r.findIndex(s=>s._id===(e==null?void 0:e._id));return a!==-1?r[a]=e:r.push(e),r.length>0?r:void 0}async listAccountUsersLocalOnly(){return await ge(Le).getAllUsers()}async createLocalUser(e){const t=Le,r={...e,accountId:t,createdAt:new Date,updatedAt:new Date};f("Creating local user:",r);const a=ge(t);await a.upsertUser(r);const s=await a.getAllUsers();return f("Created local user:",r,"Total users:",s.length),r}async updateUser(e,t){const r=await this.getAccountDb(),a=await K.instance.getCurrentUser();if(e=e||(a==null?void 0:a._id),!e)throw new R("userId required",400);const s=await r.getUserById(e),i={...s||{},...t,_id:e,accountId:t.accountId||(s==null?void 0:s.accountId)||(a==null?void 0:a.accountId),updated:new Date().toISOString()};return await r.upsertUser(i),a&&e===(a==null?void 0:a._id)&&await K.instance.updateUserObj(i),i}async deleteUser(e){const t=await K.instance.getCurrentUser();if((t==null?void 0:t._id)===e)throw new R("Cannot delete the currently active user. Switch to another user first.",400);const a=await this.getAccountDb();if(!await a.getUserById(e))throw new R("User not found",404);await a.deleteUser(e)}async updateProfileImage(e,t){if(!e)throw new R("userId required",400);if(!t||!t.type)throw new R("imageData with type required",400);let r;if(t.type==="path")r={type:"path",data:t.data};else if(t.type==="data"){const{fileData:s,imageType:i}=t.data||{};s&&(r={type:"base64",data:s.startsWith("data:")?s:`data:image/${i||"png"};base64,${s}`})}else t.type==="base64"&&(r=t);if(!r)throw new R("Could not process image data",400);await this.updateUser(e,{profileImage:r});const a=await K.instance.getCurrentUser();a&&e===(a==null?void 0:a._id)&&await K.instance.updateUserObj({...a,profileImage:r}),f("Updated profile image for user:",e,r.type)}async getUserOptions(e){const t=await K.instance.getCurrentUser(),r=e||(t==null?void 0:t._id);if(!r)return;const s=await(await this.getAccountDb()).getUserById(r);return s==null?void 0:s.options}async updateUserOptions(e,t){const r=await K.instance.getCurrentUser(),a=t||(r==null?void 0:r._id),s=JSON.parse(JSON.stringify(e)),i=await this.getAccountDb(),d=await i.getUserById(a);if(d){if(s&&typeof s=="object"&&("whitelistingEnabled"in s||"contentFilteringEnabled"in s)){const o={...d.options,...s},u=vt({userType:d==null?void 0:d.type,isLocalRestrictedMode:(d==null?void 0:d.type)!=="admin",options:{whitelistingEnabled:!!(o!=null&&o.whitelistingEnabled),contentFilteringEnabled:!!(o!=null&&o.contentFilteringEnabled),accessControlSettings:(o==null?void 0:o.accessControlSettings)||null}});
2s.whitelistingEnabled=u.normalized.whitelistingEnabled,s.contentFilteringEnabled=u.normalized.contentFilteringEnabled}const c={...d,options:{...d.options,...s}};await i.upsertUser(c)}(r==null?void 0:r._id)===a&&await K.instance.updateUserObj({...r,options:{...r.options,...s}})}async clearOwnCheckpointLocal(){var s;const e=await K.instance.getCurrentUser(),r=(((s=e==null?void 0:e.options)==null?void 0:s.accessControlSettings)||{}).checkpointSettings;if((r==null?void 0:r.enabled)!==!0)throw new R("No daily check-in is set up",400);if(Te(r)==="guardian")throw new R("Only an adult can clear this check-in",403);const a=Dr(Date.now(),r,(e==null?void 0:e._id)||void 0,!0);return await this.applyOwnCheckpointRelease(a),{release:a}}async applyOwnCheckpointRelease(e){var a;const t=await K.instance.getCurrentUser();if(!(t!=null&&t._id))return;const r=((a=t.options)==null?void 0:a.accessControlSettings)||{};await this.updateUserOptions({accessControlSettings:{...r,checkpointRelease:e}},t._id)}async updateUserPINLocal(e,t){if(!e)throw new R("userId required",400);const r=await this.getAccountDb(),a=await r.getUserById(e);if(!a)throw new R("User not found",404);const s={...a,pin:t,hasPin:!0,updated:new Date().toISOString()};await r.upsertUser(s);const i=await K.instance.getCurrentUser();return i&&e===(i==null?void 0:i._id)&&await K.instance.updateUserObj({...i,pin:t,hasPin:!0}),f("Updated PIN for user:",e),{success:!0}}};S(ke,"_staticInstance",null);let _=ke;const Nr="api_global_force_refresh";async function zr(){return await Ye(Nr)===!0}function xr(n){return n==null?!0:Array.isArray(n)?n.length===0:typeof n=="object"?Object.keys(n).length===0:!1}function Br(n){const{data:e,meta:t,maxAge:r,emptyIsStale:a}=n;return!!(a&&xr(e)||r!==void 0&&(t!=null&&t.updatedAt)&&Date.now()-t.updatedAt>r)}async function ce(n,e,t,r={}){const{getLocal:a,updateLocalAfterFetch:s,fetchRemote:i,localModeOverrideResult:d,config:c}=t,o=r.localOnly||await q();if(o&&d)return f("dataRequest: skipping local storage (device-only mode + skipForLocalMode)"),d;let u,y;if(a&&(u=await a(e)),o)return f("dataRequest: returning local (device-only mode enabled)"),u;const p=r.forceRefresh||(c==null?void 0:c.isWrite)||(c==null?void 0:c.onlineOnly)||(c==null?void 0:c.preferFresh)||await zr(),h=((c==null?void 0:c.maxAge)!==void 0||(c==null?void 0:c.emptyIsStale))&&Br({data:u,meta:y,maxAge:c==null?void 0:c.maxAge,emptyIsStale:c==null?void 0:c.emptyIsStale});if(u&&!(p||h))return f("[REQ] Returning cached local data for ",n,e),u;{p?f("[REQ] Fetching from server (forceRefresh)"):h?f("[REQ] Fetching from server (data is stale)"):f("[REQ] Fetching from server (cache miss)");const m=i?await i(e):await k(n,e,r);return f("[REQ] Fetched from server",m),s&&await s(e,m),m}}const ye={},re=class re{constructor(){}static get instance(){return re._staticInstance||(re._staticInstance=new re),re._staticInstance}async getCurrentUserId(){var e;return(e=await K.instance.getCurrentUser())==null?void 0:e._id}async getCurrentUser(e=!1){return ce("/user/current",{},{getLocal:async()=>await K.instance.getCurrentUser(),updateLocalAfterFetch:async(t,r)=>{if(!r||!r._id)return;await K.instance.updateUserObj(r),r.accountId,await(await Ce()).upsertUser(r)},config:{emptyIsStale:!0}},{forceRefresh:e})}async getUserById(e,t=!1){return ce("/user/info",{userId:e},{getLocal:async()=>await _.instance.getUserById(e),updateLocalAfterFetch:async(r,a)=>{a&&await _.instance.updateUser(a._id,a)}},{forceRefresh:t})}async listAccountUsers(){return await q()?await _.instance.listAccountUsersLocal():await ce("/account/users",{},{updateLocalAfterFetch:async(t,r)=>{await _.instance.updateAccountUsersLocal(r)}},{forceRefresh:!0})}async listAccountUsersWithCache(e=!1){return await ce("/account/users",{},{getLocal:async()=>await _.instance.listAccountUsersLocal(),updateLocalAfterFetch:async(t,r)=>{await _.instance.updateAccountUsersLocal(r)}},{forceRefresh:e})}async createUser(e){const t=await k("/auth/createUser",e),r=t.accountId;await ge(r).upsertUsers([t]);const s=t;try{const i=await N.instance.encStatus(await this.getUserRequestContext(),!0);f("[ENC:CREATE_USER] Current user enc status",{userId:s._id,userEncEnabled:i.userEncEnabled,acntEncEnabled:i.acntEncEnabled}),i.userEncEnabled&&(f("[ENC:CREATE_USER] Generating keys for restricted user",s._id),await N.instance.generateKeysForRestrictedUser(await this.getUserRequestContext(s._id)),f("[ENC:CREATE_USER] Keys generated and shared successfully",s._id))}catch(i){f("[ENC:CREATE_USER] Error creating user encryption",i)}return await this.listAccountUsers(),s}async getUserRequestContext(e=null){const t=await this.getCurrentUser();return e!=null?new we(t,await this.getUserById(e)):new we(t)}async getLocalUserClientSettings(e=!1,t=null){const r=t||await this.getCurrentUserId();if(!r)return null;if(ye[r]&&!e)return ye[r];const a=await ar(r);return ye[r]=a,a}async saveLocalUserClientSettings({settings:e,userId:t}){if(t=t||await this.getCurrentUserId(),!t)return;const r=await sr(e,t);ye[t]=r}async getUserOptions(e=null,t=!1){if(e){const r=await this.getUserById(e,t),a=r==null?void 0:r.options;return await q()&&!a?{...ct}:a}else{const r=await this.getCurrentUser(t),a=r==null?void 0:r.options;return await q()&&!a?{...ct}:a}}async clearCachedEncValues(e){const t=await this.getCurrentUser(),r=e||(t==null?void 0:t._id);await D.clearEncPassword(r),await D.clearEncRecoveryKey(r),await D.clearEncSecretyKey(r),await $.instance.clearUserKeyManager(r)}async checkTempDisableBlocking(){var a;let e=await this.getCurrentUser();if(!e)return!1;let t=(a=e==null?void 0:e.options)==null?void 0:a.accessControlSettings,r=!1;return t!=null&&t.disableRestrictions&&(t==null?void 0:t.disableRestrictionsExpires)>new Date().getTime()&&(r=!0),r}};S(re,"_staticInstance",null);let Q=re;const Aa=Object.freeze(Object.defineProperty({__proto__:null,UserService:Q},Symbol.toStringTag,{value:"Module"}));function pe(n,e){const t=n==null?void 0:n.encInfo;return!t||typeof t!="object"||!("keys"in t)?e:(typeof t.v=="number"?t.v:1)>=2?2:1}const lt=16;async function yt(n,e,t){const r=new Array(n.length),a=Math.max(1,e);for(let s=0;s<n.length;s+=a){const i=n.slice(s,s+a),d=await Promise.all(i.map((c,o)=>t(c,s+o)));for(let c=0;c<d.length;c++)r[s+c]=d[c]}return r}function pt(n,e){for(const[t,r]of Object.entries(e))t in n&&(r.type=="object"?n[t]=null:n[t]="**decryption error");return n.decryptionError=!0,n}const B=class B{constructor(e,t,r){this.userService=e,this.encryptionKeyService=t,this.remoteRequester=r}static get instance(){return B._staticInstance||(B._staticInstance=new B(Q.instance,N.instance,Ue.instance)),B._staticInstance}async decryptData(e,t,r){const a=await this.userService.getUserRequestContext(),s=await this.encryptionKeyService.getKeyManager(a);return await this.decryptDataWithKeyManager(s,e,t,r)}async decryptDataWithKeyManager(e,t,r,a){if(a){let s=null;try{const i=a.properties;a.type=="array"?a.encryptedChildren==!0?s=await this.decryptListEntries(e,r,i
2):s=await this.decryptEncryptedListItems(e,r,i):a.type=="object"&&(a.encryptedChildren==!0?s=await e.decryptObject(r,i,r.encInfo):s=await this.decryptNestedProperties(e,r,i))}catch(i){console.error("DEC Error decrypting data",t,i)}return s}else return r}async decryptListEntries(e,t,r){return yt(t,lt,async a=>(a==null?void 0:a.encrypted)===!0||a!=null&&a.encInfo?e.decryptObject(a,r,a.encInfo):a)}async decryptEncryptedListItems(e,t,r){return yt(t,lt,async a=>{const s=a;for(const[i,d]of Object.entries(r))if(d.encryptedChildren==!0){const c=d.properties,o=a==null?void 0:a[i];if(!o)continue;const u=await e.decryptObject(o,c,o.encInfo||a.encInfo);s[i]=u}return s})}async decryptNestedProperties(e,t,r){let a=t;for(const[s,i]of Object.entries(r))if(i.type=="object"){if(i.encryptedChildren==!0){const d=i.properties,c=t[s];if((c==null?void 0:c.encrypted)==!0){const o=await e.decryptObject(c,d,c.encInfo);a[s]=o}}}else if(i.type=="array"){const d=t[s];if(!Array.isArray(d))continue;const c=[],o=i.properties;if(i.encryptedChildren==!0)for(const u of d)if(u!=null&&u.encrypted||u!=null&&u.encInfo)if(e)try{const y=await e.decryptObject(u,o,u.encInfo);c.push(y)}catch(y){console.error("Error decrypting:",y,u.encInfo),c.push(pt(u,o))}else c.push(pt(u,o));else c.push(u);else{const u=i.properties;for(const y of d){const p=y;for(const[g,h]of Object.entries(u))if(h.type=="object"&&h.encryptedChildren==!0){const w=h.properties,m=y==null?void 0:y[g];if((m==null?void 0:m.encrypted)==!0||m!=null&&m.encInfo){const C=await e.decryptObject(m,w,m.encInfo);p[g]=C}}else if(h.type=="array"){const w=y==null?void 0:y[g];if(!Array.isArray(w))continue;h.encryptedChildren==!0?p[g]=await this.decryptListEntries(e,w,h.properties):p[g]=await this.decryptEncryptedListItems(e,w,h.properties)}c.push(p)}a[s]=c}}return a}async encryptObject(e,t,r,a,s=!1,i){const d=M.cryptoWriteEncInfoVersion===2?2:1,c=i??se.version;if(a.encTarget==null||a.encTarget=="this"||a.encryptedChildren==!0){const o=pe(r,d),{obj:u,encInfo:y}=await e.encryptOrReencryptObject(t,r,a.properties,s,{targetVersion:o,schemaVersion:c});return{...u,encInfo:y}}else{const o=r[a.encTarget],u=a.properties[a.encTarget].properties;if(!o)throw new Error("Invalid encTarget");const y=pe(o,d),{obj:p,encInfo:g}=await e.encryptOrReencryptObject(t,o,u,s,{targetVersion:y,schemaVersion:c});return r[a.encTarget]={...p,encInfo:g},r}}async encryptArray(e,t,r,a,s=!1,i){const d=M.cryptoWriteEncInfoVersion===2?2:1,c=i??se.version;if(a.encTarget==null||a.encTarget=="this"||a.encryptedChildren==!0){let o=[];for(const u of r){const y=pe(u,d),{obj:p,encInfo:g}=await e.encryptOrReencryptObject(t,u,a.properties,s,{targetVersion:y,schemaVersion:c});o.push({...p,encInfo:g})}return o}else{const o=a.properties[a.encTarget].properties;let u=[];for(const y of r){const p=y==null?void 0:y[a.encTarget];if(!p)throw new Error("Invalid encTarget");const g=pe(p,d),{obj:h,encInfo:w}=await e.encryptOrReencryptObject(t,p,o,s,{targetVersion:g,schemaVersion:c});y[a.encTarget]={...h,encInfo:w},u.push(y)}return u}}async encryptData(e,t,r,a,s,i=!1,d){if(s.type=="object")return await this.encryptObject(e,t,a,s,i,d);if(s.type=="array")return await this.encryptArray(e,t,a,s,i,d);throw new Error("Encryption not supported for this type")}async resolveSchemaVersionForRoute(e){const t=se.version;if(!B.PUBLISH_PRIVACY_ROUTES.has(e))return t;try{const{isRolloutCapReady:r}=await Et(async()=>{const{isRolloutCapReady:a}=await import("./rolloutCapsBJsLLLO7.js");return{isRolloutCapReady:a}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13]));if(await r("publishPrivacy"))return Math.max(t,2)}catch{}return t}async remoteRequestEncryptionWrapper(e,t,r={},a={}){var J;const s=se.route[e]||{},{encSettingsKey:i,decSchema:d,encSchema:c,defaultKeyType:o,withoutWrapKey:u}=s,y=await this.userService.getUserRequestContext((r==null?void 0:r.encryptionUserId)||null),p=y==null?void 0:y.user,g=await this.encryptionKeyService.getKeyManager(y);let h=(r==null?void 0:r.dontEncrypt)==!0;if((()=>{var v;try{if(e!=="/item/update"||!t||typeof t!="object")return!1;const F=t.data;if(!F||typeof F!="object"||!F.encInfo)return!1;const E=(v=c==null?void 0:c.properties)==null?void 0:v[c.encTarget||""],z=E==null?void 0:E.properties;if(!z)return!0;for(const Yt of Object.keys(z))if(F[Yt]!=null)return!1;return!0}catch{return!1}})()){const v=t==null?void 0:t.data;t==null||t.itemId,v!=null&&v.encInfo,v==null||v.encrypted,v==null||v.encrypted,h=!0}const m=!!c&&!!g&&!h;let C=Ur(p,i);const I=(r==null?void 0:r.forceEncrypt)==!0;let U=!1;if(m)if(I||C&&(!c.constraintFunc||c.constraintFunc!=null&&await c.constraintFunc(t,y))){const v=o=="account"?g.getAcntSecretKeyId():g.getUserSecretId(),F=Array.from(new Set([v,...r.additionalWrappingKeyIds||[]].filter(E=>typeof E=="string"&&E.length>0)));try{if(await g.getKey(v)){const z=await this.resolveSchemaVersionForRoute(e);t=await this.encryptData(g,F,"ROUTE:"+e,t,c,u==!0,z),U=!0}}
2catch(E){if(console.error("Error encrypting data",E),e==="/item/update"&&((J=t==null?void 0:t.data)!=null&&J.encInfo))throw t==null||t.itemId,new Error("Encryption failed for /item/update with encInfo; blocked to prevent plaintext+encInfo corruption")}}else f("DEC - Constraint failed",e,t);U&&t&&typeof t=="object"&&t.encrypted!==!0&&(t.encrypted=!0);const b=await this.remoteRequester.remoteAPIRequest(e,t,r,a),A=!!d&&!!g;let T;return A?T=await this.decryptDataWithKeyManager(g,e,b,d):T=b,(r==null?void 0:r.includeSentDataInResult)==!0&&(T={result:T,sentData:t}),T}};S(B,"_staticInstance",null),S(B,"PUBLISH_PRIVACY_ROUTES",new Set(["/item/save","/item/update","/item/duplicates/merge","/collection/create","/collection/showcase/create"]));let Ve=B;async function Vr(n,e,t){return t()}async function k(n,e,t={}){const r=t.deduplicate!==!1,a=async()=>{try{const s=!!(se.route&&se.route[n]);let i;return s&&!t.dontEncrypt?i=await Ve.instance.remoteRequestEncryptionWrapper(n,e,t,{}):i=await Ue.instance.remoteAPIRequest(n,e,t,{}),i}catch(s){const i=At(s,n);throw Ct.handle(i,t.errorHandler),i}};return r?Vr(n,e,a):a()}async function Ca(n,e,t={},r={}){try{return await Ue.instance.remoteStreamRequest(n,e,t,r)}catch(a){const s=At(a,n);throw Ct.handle(s,r.errorHandler),s}}class jr{constructor(e,t={}){S(this,"scopeId");S(this,"defaultTTL");this.keyPrefix=e,this.scopeId=t.scopeId,this.defaultTTL=t.ttl??5*60*1e3}async get(e){const t=this.buildKey(e),r=await ne.kvGet(t);return r?this.isExpired(r)?(await ne.kvDelete(t),null):r.data:null}async set(e,t){const r=this.buildKey(e);await ne.kvSet(r,{data:t,timestamp:Date.now()})}async invalidate(e){const t=this.buildKey(e);await ne.kvDelete(t)}async clearAll(){const e=await ne.kvGetWithPrefix(this.keyPrefix);for(const t of Object.keys(e))await ne.kvDelete(t)}buildKey(e){return this.scopeId?`${this.keyPrefix}:${this.scopeId}:${e}`:`${this.keyPrefix}:${e}`}isExpired(e){return Date.now()-e.timestamp>this.defaultTTL}}class Hr{constructor(){S(this,"valueStores",new Map)}getValueStore(e,t,r){const a=t?`${e}:${t}`:e;return this.valueStores.has(a)||this.valueStores.set(a,new jr(e,{scopeId:t,ttl:r==null?void 0:r.ttl})),this.valueStores.get(a)}clearAllCaches(){this.valueStores.clear()}}const W=new Hr;var $r=(n=>(n.admin="admin",n.restricted="restricted",n))($r||{}),Rt=(n=>(n.standard="standard",n.plus="plus",n.superplus="superplus",n))(Rt||{}),Gr=(n=>(n.google="google",n.apple="apple",n.internal="internal",n))(Gr||{});const Ua="features.imageImprovement.enabled",be=class be{constructor(){}static get instance(){return this._staticInstance||(this._staticInstance=new be),this._staticInstance}async getAccountInfo(){try{const e=await K.instance.getCurrentUser();if(!e)return;const t=W.getValueStore("account:info",e.accountId);let r=await t.get("info")??void 0;if(!r)if(e.localUser===!0)r={_id:e.accountId,accountType:Rt.standard,options:{setupComplete:!1}},await t.set("info",r);else return;return r}catch{return}}async updateAccountInfo(e){const t=await K.instance.getCurrentUser();t&&await W.getValueStore("account:info",t.accountId).set("info",e)}async getAccountStats(){const e=await Ce(),t=await e.getAllUsers(),r=await e.items.toArray(),a=r.filter(i=>{var d;return((d=i==null?void 0:i.details)==null?void 0:d.type)===Be.collection}).length,s=r.filter(i=>{var d;return((d=i==null?void 0:i.details)==null?void 0:d.type)!==Be.collection}).length;return{userCount:(t==null?void 0:t.length)??0,itemCount:s,collectionCount:a}}};S(be,"_staticInstance",null);let te=be;async function qr(n){if(!(n!=null&&n.options)||typeof n.options!="object"||!("whitelistingEnabled"in n.options)&&!("contentFilteringEnabled"in n.options))return;const e=await K.instance.getCurrentUser(),t=n.userId||(e==null?void 0:e._id);if(!t)return;const r=await _.instance.getUserById(t).catch(()=>{}),a={...r==null?void 0:r.options,...n.options},s=vt({userType:r==null?void 0:r.type,options:{whitelistingEnabled:!!(a!=null&&a.whitelistingEnabled),contentFilteringEnabled:!!(a!=null&&a.contentFilteringEnabled),accessControlSettings:(a==null?void 0:a.accessControlSettings)||null}});n.options={...n.options,whitelistingEnabled:s.normalized.whitelistingEnabled,contentFilteringEnabled:s.normalized.contentFilteringEnabled}}async function Yr(n){const e=n==null?void 0:n.options;if(!e||typeof e!="object"||!("accessControlSettings"in e)||n.tempAuthToken||!await Qr())return e;const{accessControlSettings:t,...r}=e;return r}async function Qr(){try{const n=await K.instance.getCurrentUser();return n?n.type==="restricted":!0}catch{return!0}}function De(n,e){return!n||!("keys"in n)||!n.keys?!1:n.keys.some(t=>(t==null?void 0:t.wrappingKeyId)===e)}async function X(n,e){try{return await n.getKey(e)}catch(t){return f("[EncShare] getKey failed",e,t),null}}const ve=class ve{static get instance(){return this._instance||(this._instance=new ve),this._instance}getCollectionShareWrappingKeyId(e){return l.keyFieldsToId({groupType:"onetime",groupId:`col_${e}`,keyType:"sym",keyName:"collectionShare",version:0})}getGlobalFriendWrappingKeyId(e){return l.keyFieldsToId({groupType:"acnt",groupId:e,keyType:"sym",keyName:"friendGlobal",version:0})}async ensureGlobalFriendWrappingKey(e){const t=await N.instance.getKeyManager(e,!0);if(!t)throw new Error("Encryption not available (no KeyManager)");const r=this.getGlobalFriendWrappingKeyId(e.accountId),a=await X(t,r);if(a)return{km:t,wrappingKey:a,wrappingKeyId:r};const s=await t.getAcntSecretKey();if(!s)throw new Error("Account secret key not available");const i=await l.createSecretKey("acnt",e.accountId,"friendGlobal"),d=await l.wrapKey(i,s),c=await l.serializeWrappedKey(d,"user"),o=await l.serializedKeyThingToKeyEntry(c);await k("/user/encryption/saveAccountKeys",{keyList:[o]});const u=await N.instance.getKeyManager(e,!0),y=u?await X(u,r):null;if(!u||!y)throw new Error("Failed to persist global friend wrapping key");return{km:u,wrappingKey:y,wrappingKeyId:r}}async ensureCollectionShareWrappingKey(e,t){const r=await N.instance.getKeyManager(e,!0);if(!r)throw new Error("Encryption not available (no KeyManager)");const a=this.getCollectionShareWrappingKeyId(t),s=await X(r,a);if(s)return{km:r,wrappingKey:s,wrappingKeyId:a};const i=await r.getUserSecret();if(!i)throw new Error("User secret key not available");const d=await l.createSecretKey("onetime",`col_${t}`,"collectionShare",["encrypt","decrypt"]),c=await l.wrapKey(d,i),o=await l.serializeWrappedKey(c,"self"),u=await l.serializedKeyThingToKeyEntry(o);await k("/user/encryption/saveUserKeys",{userId:e.userId,keyList:[u]});const y=await N.instance.getKeyManager(e,!0),p=y?await X(y,a):null;if(!y||!p)throw new Error("Failed to persist collection share wrapping key");return{km:y,wrappingKey:p,wrappingKeyId:a}}async ensureEncInfoHasWrappingKey(e){const{km:t,itemId:r,encInfo:a,wrappingKeyId:s}=e;if(De(a,s))return;if(!("keys"in a)||!a.keys||a.keys.length===0)throw new Error("Invalid encInfo (no keys)");let i=null;for(const o of a.keys)try{i=await t.unwrapEncInfoKeyToDataKey(o);break}catch{}if(!i)throw new Error("Unable to unwrap item data key");const d=await t.generateEncInfoKeyForWrappingKey(s,i),c={...a,keys:[...a.keys,d]};await k("/item/update",{itemId:r,data:{encInfo:c}},{dontEncrypt:!0})}async ensurePostEncInfoHasWrappingKey(e){const{km:t,postId:r,encInfo:a,wrappingKeyId:s}=e;if(De(a,s))return;if(!("keys"in a)||!a.keys||a.keys.length===0)throw new Error("Invalid encInfo (no keys)");let i=null;for(const o of a.keys)try{i=await t.unwrapEncInfoKeyToDataKey(o);break}catch{}if(!i)throw new Error("Unable to unwrap post data key");const d=await t.generateEncInfoKeyForWrappingKey(s,i),c={...a,keys:[...a.keys,d]};await k("/post/updateEncInfo",{postId:r,encInfo:c})}_friendKeyError(e,t){const r=e.map(d=>d.userId),a=e.map(d=>d.keyId),s=t&&t.length===e.length?t:r,i=e.length>1?"their accounts":"their account";return new R(`Can't share with ${s.join(", ")} â they haven't finished setting up ${i}. Ask them to sign in, then try again.`,400,{missingUserIds:r,missingKeyIds:a},ir)}async _buildFriendKeyError(e){let t;try{const r=await k("/user/friend/list",{},{forceRefresh:!0}),a=new Map((r.friends||[]).map(s=>[s.userId,s.displayedName||s.username||s.userId]));t=e.map(s=>a.get(s.userId)||s.userId)}catch(r){f("[EncShare] Failed to resolve friend names for key error",r)}return console.error("[EncShare] Friend public key unavailable",{missingUserIds:e.map(r=>r.userId),missingKeyIds:e.map(r=>r.keyId)}),this._friendKeyError(e,t)}async assertFriendKeysAvailable(e,t){const r=Array.from(new Set((t||[]).filter(d=>
2typeof d=="string"&&d.length>0)));if(r.length===0)return;const a=async d=>{const c=[];for(const o of r){const u=l.getUserPublicKeyId(o);await X(d,u)||c.push({userId:o,keyId:u})}return c};let s=await N.instance.getKeyManager(e),i=s?await a(s):null;if(!s||i&&i.length>0){if(s=await N.instance.getKeyManager(e,!0),!s)throw new Error("Encryption not available (no KeyManager)");i=await a(s)}if(i&&i.length>0){const d=l.getUserPublicKeyId(e.userId);throw await X(s,d)?await this._buildFriendKeyError(i):new Error("Encryption not available (keys not loaded)")}}async deliverWrappingKeyToUser(e){const{km:t,wrappingKey:r,targetUserId:a}=e,s=l.getUserPublicKeyId(a),i=await X(t,s);if(!i)throw this._friendKeyError([{userId:a,keyId:s}]);const d=await l.wrapKey(r,i),c=await l.serializeWrappedKey(d,"user"),o=await l.serializedKeyThingToKeyEntry(c),u=`ke_wrap_${o.keyId}__${o.unwrappingKeyId}`;await k("/user/encryption/createKeyEntryForUser",{targetUserId:a,keyEntry:{...o,_id:u}})}async _listConfirmedFriendUserIds(e){try{const r=((await k("/user/friend/list",{},{forceRefresh:!0})).friends||[]).map(a=>a.userId).filter(a=>typeof a=="string"&&a.length>0);return Array.from(new Set(r))}catch(t){return f("[EncShare] Failed to list friends for global friend-key delivery",t),[]}}async ensureGlobalFriendWrappingKeyDeliveredToAllFriends(e){const{km:t,wrappingKey:r}=await this.ensureGlobalFriendWrappingKey(e),a=await this._listConfirmedFriendUserIds(e);let s=0,i=0;for(const d of a)try{await this.deliverWrappingKeyToUser({uctx:e,km:t,wrappingKey:r,targetUserId:d}),s++}catch(c){i++,f("[EncShare] Failed to deliver global friend wrapping key to friend",{friendUserId:d,e:c})}return{friendCount:a.length,delivered:s,failed:i}}async ensureUserFileEncInfoHasWrappingKey(e){const{km:t,fileId:r,encInfo:a,wrappingKeyId:s}=e;if(De(a,s))return;if(!("keys"in a)||!a.keys||a.keys.length===0)throw new Error("Invalid encInfo (no keys)");let i=null;for(const o of a.keys)try{i=await t.unwrapEncInfoKeyToDataKey(o);break}catch{}if(!i)throw new Error("Unable to unwrap file data key");const d=await t.generateEncInfoKeyForWrappingKey(s,i),c={...a,keys:[...a.keys,d]};await k("/userfile/updateEncInfo",{fileId:r,encInfo:c})}};S(ve,"_instance",null);let me=ve;const Pt="__task_global__",Jr=24*60*60*1e3;function Ot(n){return!n||n.completionStatus==="skipped"?!1:n.completionStatus==="completed"||n.completed===!0}function Ta(n){return(n??[]).filter(Ot).map(e=>{var t;return((t=e.task)==null?void 0:t.taskId)||""}).filter(Boolean)}function Lt(n){const e=new Date(n);return e.setHours(0,0,0,0),e.getTime()}function _a(n){var t;return(((t=n.task)==null?void 0:t.completionScope)==="once"?"once":"per_user")==="once"?Pt:n.viewerType==="admin"?n.forUserId:void 0}function Xr(n){const e=typeof(n==null?void 0:n.createdAt)=="number"&&Number.isFinite(n.createdAt)?n.createdAt:void 0;return e===void 0?Number.NEGATIVE_INFINITY:Lt(e)}function Fa(n){const{task:e,nowMs:t}=n,r=e.recurrence;if(!r||r.type==="none")return e.createdAt;const a=r.resetHourLocal??0,s=new Date(t);if(r.type==="daily"){const o=new Date(s);return o.setHours(a,0,0,0),s.getTime()<o.getTime()&&o.setDate(o.getDate()-1),o.getTime()}const i=r.daysOfWeek&&r.daysOfWeek.length>0?r.daysOfWeek:[0,1,2,3,4,5,6],d=new Set(i.map(o=>(o%7+7)%7)),c=new Date(s);c.setHours(a,0,0,0);for(let o=0;o<8;o++){const u=c.getDay();if(d.has(u)){if(o===0&&s.getTime()<c.getTime()){c.setDate(c.getDate()-1);continue}return c.getTime()}c.setDate(c.getDate()-1)}return t}function Dt(n){const{task:e,occurrenceStartMs:t}=n,r=e.recurrence;if(!r||r.type==="none")return e.dueAtMs;const a=r.dueTimeLocal;if(!a)return;const s=new Date(t);return s.setHours(a.hour,a.minute,0,0),s.getTime()<=t&&s.setDate(s.getDate()+1),s.getTime()}function Zr(n){return Lt(n.dueAtMs??n.dueDateMs??n.occurrenceStartMs)}function Ra(n){const{task:e,startMs:t,endMs:r}=n;if(!Number.isFinite(t)||!Number.isFinite(r)||r<=t)return[];const a=e.recurrence;if(!a||a.type==="none"){const p=typeof e.dueAtMs=="number"&&Number.isFinite(e.dueAtMs)?e.dueAtMs:typeof e.dueDateMs=="number"&&Number.isFinite(e.dueDateMs)?e.dueDateMs:void 0;return p===void 0?[]:p<t||p>=r?[]:[e.createdAt]}const s=Xr(e),i=Math.max(t,s);if(i>=r)return[];const d=i-Jr,c=a.resetHourLocal??0,o=new Date(d);o.setHours(c,0,0,0),o.getTime()<d&&o.setDate(o.getDate()+1);const u=a.type==="weekly"?new Set((a.daysOfWeek&&a.daysOfWeek.length>0?a.daysOfWeek:[0,1,2,3,4,5,6]).map(p=>(p%7+7)%7)):null,y=[];for(;o.getTime()<r;){const p=o.getTime();if((!u||u.has(o.getDay()))&&p>=s){const w=Dt({task:e,occurrenceStartMs:p})??p;w>=i&&w<r&&y.push(p)}o.setDate(o.getDate()+1)}return y}function Pa(n){const{task:e,userId:t,occurrenceStartMs:r,completed:a,completionStatus:s,completionAtMs:i,completionNote:d,completedByUserId:c,nowMs:o}=n,u=Dt({task:e,occurrenceStartMs:r}),y=Zr({occurrenceStartMs:r,dueAtMs:u,dueDateMs:e.dueDateMs}),p=e.completionScope==="once"?Pt:t;return{occurrenceId:`${e.taskId}:${p}:${r}`,taskId:e.taskId,task:e,userId:t,occurrenceStartMs:r,dueAtMs:u,dis
2playDateMs:y,completed:a,completionStatus:s,completionAtMs:i,completionNote:d,completedByUserId:c,overdue:!a&&typeof u=="number"?o>u:!1}}function Oa(n,e){if(n.displayDateMs!==e.displayDateMs)return n.displayDateMs-e.displayDateMs;const t=n.dueAtMs??n.occurrenceStartMs,r=e.dueAtMs??e.occurrenceStartMs;return t!==r?t-r:n.taskId.localeCompare(e.taskId)}const en=5e3;function ft(n){return{active:!1,satisfied:!0,outstanding:[],missingTaskIds:[],evaluatedAtMs:n}}const Ee=class Ee{constructor(){S(this,"cache",null)}static get instance(){return this._staticInstance||(this._staticInstance=new Ee),this._staticInstance}invalidate(){this.cache=null}async evaluate(e,t=!1){var u,y,p;const r=Date.now(),a=e||await Q.instance.getCurrentUserId()||null;if(!a)return ft(r);if(!t&&this.cache&&this.cache.userId===a&&r-this.cache.ts<en)return this.cache.value;const s=await Q.instance.getUserOptions(null,t),d=((s==null?void 0:s.accessControlSettings)||{}).checkpointSettings;if(!Wr(d)){const g=ft(r);return this.cache={userId:a,ts:r,value:g},g}const c=((u=d==null?void 0:d.taskGate)==null?void 0:u.requiredTaskIds)||[];let o;try{const{TaskService:g}=await Et(async()=>{const{TaskService:U}=await import("./TaskServiceWHtFbUzu.js");return{TaskService:U}},__vite__mapDeps([14,1,2,3,4,5,6,7,15,16,17,18,19,8,20,12,11,21,13,22,23,9,24,10,25,26,27,28,29,30,0,31,32])),h=await g.instance.listStatus({userId:a,nowMs:r}),w=(h==null?void 0:h.due)??[],m=new Map;for(const U of w){const b=(y=U==null?void 0:U.task)==null?void 0:y.taskId;b&&m.set(b,U)}const C=[],I=[];for(const U of c){const b=m.get(U);if(!b){I.push(U);continue}Ot(b)||C.push({taskId:U,title:((p=b.task)==null?void 0:p.title)||"Task",occurrenceStartMs:b.occurrenceStartMs})}o={active:!0,satisfied:C.length===0,outstanding:C,missingTaskIds:I,evaluatedAtMs:r}}catch(g){f("[CHECKPOINT_TASK_GATE] could not read tasks, refusing clear:",g),o={active:!0,satisfied:!1,outstanding:[],missingTaskIds:[],evaluatedAtMs:r}}return this.cache={userId:a,ts:r,value:o},o}async assertClearAllowed(){const e=await this.evaluate(null,!0);if(!e.active||e.satisfied)return;const t=e.outstanding.length;throw new Error(t>0?`Finish your tasks first â ${t} still to do.`:"We couldn't check your tasks. Ask a parent to unblock.")}};S(Ee,"_staticInstance",null);let je=Ee;const tn="::pref::",rn=5*60*1e3,nn=24*60*60*1e3;function Je(n,e){return`${n}${tn}${e}`}function _e(n){return W.getValueStore("user:prefs",n,{ttl:Number.POSITIVE_INFINITY})}function an(n){return cr(n)?rn:nn}function sn(n,e){return an(n)}function cn(n,e){const t=sn(n);return Number.isFinite(t)?Date.now()-e.fetchedAt>t:!1}function on(n){if(!n||typeof n!="object")return null;const e=n.state,t=typeof n.fetchedAt=="number"?n.fetchedAt:0;return e==="present"?{state:"present",value:n.value,fetchedAt:t}:e==="empty"?{state:"empty",fetchedAt:t}:null}async function Ie(n,e,t){const r=await _e(n).get(Je(e,t));return on(r)}function He(n,e){return!!e&&!cn(n,e)}async function Me(n,e,t,r){const a={state:"present",value:r,fetchedAt:Date.now()};await _e(n).set(Je(e,t),a)}async function dn(n,e,t){const r={state:"empty",fetchedAt:Date.now()};await _e(n).set(Je(e,t),r)}async function un(n,e,t){const r=await Ie(n,e,t);return(r==null?void 0:r.state)==="present"?r.value:void 0}const We=new Set;async function ln(n,e){const t=`${n}:${e}`;if(!We.has(t)){We.add(t);try{const r=_e(n);await r.invalidate(e),await r.invalidate(`__authority__:${e}`)}catch{We.delete(t)}}}const Xe=[{id:"media",label:"Podcasts & media",description:"Play podcasts from your subscriptions, list what you follow, and manage the Play Queue.",icon:"headphones",defaultEnabled:!0},{id:"web",label:"Wikipedia answers",description:"Look up and answer questions using Wikipedia.",icon:"wikipedia",defaultEnabled:!0},{id:"library",label:"Library management",description:"Search your library, save links, notes, collections and pictures, and change, file or archive what is already there.",icon:"collection",defaultEnabled:!0},{id:"tasks",label:"Tasks & reminders",description:"Create, change, complete and archive tasks and reminders.",icon:"check2-square",defaultEnabled:!0},{id:"parental",label:"Parental controls",description:"Adjust filtering, screen time, site access and Family Downtime for your family, answer requests, and check who can get online.",icon:"shield-lock",defaultEnabled:!0,adminOnly:!0},{id:"activity",label:"Activity insights",description:"Summarize what your children have been doing.",icon:"graph-up",defaultEnabled:!0,adminOnly:!0}
2,{id:"setup",label:"Guided setup",description:"Review your family setup, walk through fixes, and explain settings.",icon:"magic",defaultEnabled:!0,adminOnly:!0}],La=new Set(Xe.map(n=>n.id));function Mt(n){return`features.aiCapability.${n}.enabled`}const Da=Xe.map(n=>Mt(n.id)),yn=5e3;let oe=null;async function Ma(){const n=Date.now();if(oe&&n<oe.expiresAt)return oe.value;const e=new Set;try{const t=await K.instance.getCurrentUser();if(t!=null&&t._id&&(t!=null&&t.accountId))for(const r of Xe)await un(t.accountId,t._id,Mt(r.id))===!1&&e.add(r.id)}catch(t){f("[AI_CAPABILITY] disabled-groups read error",t)}return oe={value:e,expiresAt:n+yn},e}function pn(){oe=null}async function gt(){const n=await Ce();if(!n)throw new Error("getAccountDb: No current user or accountId available");return n}function de(n,e){return n!=null&&n.userId&&typeof n.userId=="string"?n.userId:e}function $e(n){return Array.isArray(n==null?void 0:n.keys)?n.keys.filter(e=>typeof e=="string"&&e.length>0):[]}async function Wa(n){const e=await K.instance.getCurrentUser();if(!(e!=null&&e._id)||!(e!=null&&e.accountId))return;const t=de(n,e._id),r=$e(n),a={},s={},i=[];for(const c of r){const o=await Ie(e.accountId,t,c);if(!He(c,o)){i.push(c),s[c]=null;continue}o.state==="present"?(a[c]=o.value,s[c]=o.value):s[c]=null}const d=r.length>0&&i.length===0;return{storedPrefs:a,requestedPrefs:s,requestedKeys:r,authorityEstablished:d,missingAuthorityKeys:i,source:d?"local-authoritative":"unknown"}}const fn={"/account/users":{getLocal:async n=>{const e=await _.instance.listAccountUsersLocal();if(e&&e.length>0)return e},updateLocalAfterFetch:async(n,e)=>{await _.instance.updateAccountUsersLocal(e)},config:{emptyIsStale:!0}},"/user/options/update":{getLocal:async n=>{await qr(n);const e=await Yr(n);await _.instance.updateUserOptions(e,n.userId)},updateLocalAfterFetch:async(n,e)=>{},config:{isWrite:!0}},"/user/checkpoint/clear":{getLocal:async n=>{if(await je.instance.assertClearAllowed(),!!await q())return _.instance.clearOwnCheckpointLocal()},updateLocalAfterFetch:async(n,e)=>{e!=null&&e.release&&await _.instance.applyOwnCheckpointRelease(e.release)},config:{isWrite:!0}},"/account/invites/list":{getLocal:async n=>{},updateLocalAfterFetch:async(n,e)=>{},localModeOverrideResult:[]},"/user/notification/list":{getLocal:async n=>{},updateLocalAfterFetch:async(n,e)=>{},localModeOverrideResult:[]},"/feed/list":{getLocal:async n=>{},updateLocalAfterFetch:async(n,e)=>{},localModeOverrideResult:{records:[]}},"/feed/sharedFeedback/list":{getLocal:async n=>{},updateLocalAfterFetch:async(n,e)=>{},localModeOverrideResult:{events:[]}},"/feed/sharedFeedback/markSeen":{getLocal:async n=>{},updateLocalAfterFetch:async(n,e)=>{},localModeOverrideResult:{success:!0},config:{isWrite:!0}},"/user/friend/list":{getLocal:async n=>{},updateLocalAfterFetch:async(n,e)=>{try{const t=await Q.instance.getUserRequestContext();await me.instance.ensureGlobalFriendWrappingKeyDeliveredToAllFriends(t)}catch(t){f("[EncShare] Skipping friend-key delivery on friend/list refresh",t)}},localModeOverrideResult:{friends:[],requestedOutBound:[],requestedInBound:[]}},"/user/friend/takeAction":{getLocal:async n=>{},updateLocalAfterFetch:async(n,e)=>{if((n==null?void 0:n.action)==="confirm")try{const t=await Q.instance.getUserRequestContext();await me.instance.ensureGlobalFriendWrappingKeyDeliveredToAllFriends(t)}catch(t){f("[EncShare] Failed to deliver friend key after friend confirm",t)}},localModeOverrideResult:void 0,config:{isWrite:!0,onlineOnly:!0}},"/account/stats":{getLocal:async n=>await te.instance.getAccountStats(),updateLocalAfterFetch:async(n,e)=>{},config:{preferFresh:!0}},"/account/info":{getLocal:async n=>await te.instance.getAccountInfo(),updateLocalAfterFetch:async(n,e)=>{await te.instance.updateAccountInfo(e)}},"/account/extendedFeatures/get":{getLocal:async n=>{const e=await K.instance.getCurrentUser();return e?await W.getValueStore("account:extendedFeatures",e.accountId).get("current")??void 0:void 0},updateLocalAfterFetch:async(n,e)=>{const t=await K.instance.getCurrentUser();if(!t)return;await W.getValueStore("account:extendedFeatures",t.accountId).set("current",e)}},"/account/extendedFeatures/update":{getLocal:async n=>{},updateLocalAfterFetch:async(n,e)=>{const t=await K.instance.getCurrentUser();if(!t)return;const r=W.getValueStore("account:extendedFeatures",t.accountId),a=await r.get("
2current"),s=(a==null?void 0:a.extendedFeatures)??{};await r.set("current",{extendedFeatures:{...s,...n.updates}})},config:{isWrite:!0,onlineOnly:!0}},"/account/options/update":{getLocal:async n=>{const e=await te.instance.getAccountInfo();if(!e)return;const r={...e.options,...n.options};await te.instance.updateAccountInfo({...e,options:r})},config:{isWrite:!0}},"/user/prefs/get":{getLocal:async n=>{const e=await K.instance.getCurrentUser();if(!(e!=null&&e._id)||!(e!=null&&e.accountId))return;const t=de(n,e._id),r=$e(n);if(r.length===0)return;const a=await Promise.all(r.map(i=>Ie(e.accountId,t,i).then(d=>({key:i,record:d})))),s={};for(const{key:i,record:d}of a){if(!He(i,d))return;d.state==="present"&&(s[i]=d.value)}return s},updateLocalAfterFetch:async(n,e)=>{const t=await K.instance.getCurrentUser();if(!(t!=null&&t._id)||!(t!=null&&t.accountId))return;const r=de(n,t._id),a=$e(n),s=e||{};await Promise.all([...Object.entries(s).map(([i,d])=>Me(t.accountId,r,i,d)),...a.filter(i=>!(i in s)).map(i=>dn(t.accountId,r,i))]),ln(t.accountId,r)},config:{}},"/user/prefs/getValue":{getLocal:async n=>{const e=await K.instance.getCurrentUser();if(!(e!=null&&e._id)||!(e!=null&&e.accountId))return;const t=de(n,e._id),r=n,a=await Ie(e.accountId,t,r.key);if(He(r.key,a))return{key:r.key,value:a.state==="present"?a.value:void 0}},updateLocalAfterFetch:async(n,e)=>{},config:{}},"/user/prefs/update":{getLocal:async n=>{const e=await K.instance.getCurrentUser();if(!(e!=null&&e._id)||!(e!=null&&e.accountId))return;const t=de(n,e._id),r=n.updates||{};await Promise.all(Object.entries(r).map(([a,s])=>Me(e.accountId,t,a,s))),Object.keys(r).some(a=>a.startsWith("features.aiCapability."))&&pn()},updateLocalAfterFetch:async(n,e)=>{},config:{isWrite:!0}},"/user/settings/copy":{getLocal:async n=>{},updateLocalAfterFetch:async(n,e)=>{const t=await K.instance.getCurrentUser();if(!(t!=null&&t._id)||!(t!=null&&t.accountId))return;const r=e||{},a=String(r.targetUserId||n.targetUserId||"").trim();if(!a)return;const s=new Set(Array.isArray(r.appliedGroups)?r.appliedGroups:[]),i=r.appliedSnapshot||{},d={},c={};for(const o of s){const u=i[o];u!=null&&u.optionsPatch&&typeof u.optionsPatch=="object"&&Object.assign(d,u.optionsPatch),u!=null&&u.preferenceUpdates&&typeof u.preferenceUpdates=="object"&&Object.assign(c,u.preferenceUpdates)}if(Object.keys(d).length>0&&await _.instance.updateUserOptions(d,a),Object.keys(c).length>0)for(const[o,u]of Object.entries(c))await Me(t.accountId,a,o,u)},config:{isWrite:!0}},"/user/info":{getLocal:async n=>{const t=await(await gt()).getUserById(n.userId);if(t)return t},updateLocalAfterFetch:async(n,e)=>{e&&await(await gt()).upsertUser(e)}},"/user/profile/get":{getLocal:async n=>{const e=await K.instance.getCurrentUser();return await _.instance.getUserById(n.userId||(e==null?void 0:e._id))},updateLocalAfterFetch:async(n,e)=>{},config:{}},"/user/plugin/list":{getLocal:async n=>{const e=await K.instance.getCurrentUser();return e?await W.getValueStore("account:plugins").get(e.accountId):void 0},updateLocalAfterFetch:async(n,e)=>{const t=await K.instance.getCurrentUser();t&&e&&await W.getValueStore("account:plugins").set(t.accountId,e)}},"/item/userPermissionLookup":{getLocal:async n=>{},updateLocalAfterFetch:async(n,e)=>{}},"/user/miscStats":{getLocal:async n=>{try{const e=await K.instance.getCurrentUser();return e?await W.getValueStore("user:miscStats").get(e==null?void 0:e._id):void 0}catch{return}},updateLocalAfterFetch:async(n,e)=>{const t=await K.instance.getCurrentUser();t&&await W.getValueStore("user:miscStats").set(t==null?void 0:t._id,e)}},"/user/encryption/listKeys":{getLocal:async n=>{const e=await K.instance.getCurrentUser();if(e)try{const r=await W.getValueStore("user:enckeys").get(e==null?void 0:e._id);return r&&r.length>0?r:void 0}catch{return}},updateLocalAfterFetch:async(n,e)=>{const t=await K.instance.getCurrentUser();t&&await W.getValueStore("user:enckeys").set(t==null?void 0:t._id,e)}},"/user/prefs/defaultsByKey":{getLocal:async n=>{},updateLocalAfterFetch:async(n,e)=>{}},"/user/delete":{getLocal:async n=>{await q()&&n.userIdToDelete&&await _.instance.deleteUser(n.userIdToDelete)},updateLocalAfterFetch:async(n,e)=>{if(n.userIdToDelete)try{await _.instance.deleteUser(n.userIdToDelete)}catch{}},config:{isWrite:!0}},"/user/userType/update":{getLocal:async n=>{n.userId&&n.type&&await _.instance.updateUser(n.userId,{type:n.type})},updateLocalAfterFetch:async(n,e)=>{if(n.userId&&n.type)try{await _.instance.updateUser(n.userId,{type:n.type})}catch{}},config:{isWrite:!0}},"/user/info/update":{getLocal:async n=>{await q()&&await _.instance.updateUser(n.userId,n.data)},updateLocalAfterFetch:async(n,e)=>{n.data&&await _.instance.updateUser(n.userId,n.data)},config:{isWrite:!0}},"/user/info/updateUsername":{getLocal:async n=>{n.username&&await _.instance.updateUser(n.userId,{username:n.username})},updateLocalAfterFetch:async(n,e)=>{n.username&&await _.instance.updateUser(n.userId,{username:n.username})},config:{isWrite:!0}},"/user/profileImage/update":{getLocal:async n=>{const e=await K.instance.getCurrentUser(),t=n.userId||(e==null?void 0:e._id);t&&n.imageData&&await _.instance.updateProfileImage(t,n.imageData)},updateLocalAfterFetch:async(n,e)=>{},config:{isWrite:!0}},"/subscription/edit":{getLocal:async n=>{},updateLocalAfterFetch:async(n,e)=>{},config:{isWrite:!0},localModeOverrideResult:void 0}};function gn(n){return fn[n]}const hn=new Set(["/items/match","/item/matchesForURLs","/item/matchesForPubIds"]);function wn(n){return hn.has(n)}function mn(n){return new Error(`"${n}" is a BG-local-only route with no server endpoint â call it via BGRouter.call() or the owning service, not the remote request path.`)}async function In(n,e,t={},r){const a=gn(n);if(!a){if(wn(n))throw mn(n);return k(n,e,t)}return ce(n,e,a,t)}const H=class H{constructor(){S(this,"kms",{})}async isKeyManagerReadyForDecryption(e){try{if(await e.getUserSecret())return!0}catch{}try{if(await e.getAcntSecretKey())return!0}catch{}return!1}static get instance(){return H._staticInstance||(H._staticInstance=new H),H._staticInstance}async clearUserKeyManager(e){e&&(delete this.kms[e],await or(`km_${e}`))}clearAllKeyManagers(){this.kms={}}async getKeyManager(e,t,r,a=!1){await at.acquire();try{return await this.loadKeyManager(e,t,r,a)}finally{at.release()}}async loadKeyManager(e,t,r,a=!1){{if(!a){if(this.kms[t]&&await this.isKeyManagerReadyForDecryption(this.kms[t]))return this.kms[t];const d=await Ye(`km_${t}`);if(d&&d.keys&&d.keys.length>0)try{const c=await L.instanceFromSerialized(d);if(await this.isKeyManagerReadyForDecryption(c))return this.kms[t]=c,this.kms[t]}catch(c){f("[KMF] Failed to deserialize cached KeyManager:",c)}}const s=await In("/user/encryption/listKeys",{userId:t},{forceRefresh:a}),i=await this.getKeyManagerFromKeys(e,t,r,s,{holdsKeyLock:!0});if(!i)return await L.emptyInstance(t,r);this.kms[t]=i,await xe(`km_${t}`,this.kms[t].serialize())}return this.kms[t]}async getKeyManagerFromKeys(e,t,r,a,s={}){try{if(f("[KMF] getKeyManagerFromKeys for user",t,"currentUserId:",e,"keysCount:",a==null?void 0:a.length),a&&a.length>0){let i=null;const d=await D.getEncSecretyKey(t);if(f("[KMF] Trying secretKey for",t,"hasSecretKey:",!!d),d)try{f("[KMF] Loading from secret key",t),i=await L.instanceFromSecretKey(t,r,d,a),f("[KMF] Successfully loaded from secret key",t)}catch(o){f("[KMF] Failed to load from secret key",t,o)}if(!i)try{const o=await D.getEncPassword(t);f("[KMF] Trying password for",t,"hasPassword:",!!o),o&&(f("[KMF] Loading from password",t),i=await L.instanceFromPassword(t,r,o,M.passwordEncSalt,a),f("[KMF] Successfully loaded from password",t))}catch(o){f("[KMF] Failed to load from password",t,o)}if(!i)try{const o=await D.getEncRecoveryKey(t);f("[KMF] Trying recovery key for",t,"hasRecoveryKey:",!!o),o&&(f("[KMF] Loading from recovery key",t),i=await L.instanceFromRecoveryKey(t,r,o,a),f("[KMF] Successfully loaded from recovery key",t))}catch(o){f("[KMF] Failed to load from recovery key",t,o)}if(!i)if(f("[KMF] Trying current user access for",t,"currentUserId:",e,"isSameUser:",e===t),e!=t){f("[KMF] Loading from current user access",t,"via currentUserId:",e);const o=s.holdsKeyLock?await this.loadKeyManager(e,e,r,!0):await H.instance.getKeyManager(e,e,r,!0),u=l.getUserSecretKeyId(t);try{const y=(a||[]).filter(p=>(p==null?void 0:p.keyId)===u).sort((p,g)=>{const h=(p==null?void 0:p.unwrappingKeyId)==="userPassword"?1:0,w=(g==null?void 0:g.unwrappingKeyId)==="userPassword"?1:0;return h-w});for(const p of y)try{let g=null;if(p!=null&&p.isWrapped){const h=await l.keyEntryToWrappedKey(p),w=p.unwrappingKeyId;if(!w||w==="userPassword")continue;const m=await o.getKey(w);g=await l.unwrapKey(h,m)}else g=await l.keyEntryToKeyInstance(p);
2if(g!=null&&g.key){g.keyId=u,i=new L(t,r,g,a),f("[KMF] Successfully loaded from current user access (unwrapped from target keys)",t);break}}catch(g){f("[KMF] Candidate secret unwrap failed (trying next)",t,g)}}catch(y){f("[KMF] Failed to unwrap secret key from target keys (will try legacy fallback)",t,y)}if(!i)try{const y=await o.getSecretKeyById(u);f("[KMF] Got secretKey from current user KM:",!!y,"for keyId:",u),y!=null&&y.keyString&&(i=await L.instanceFromSecretKey(t,r,y.keyString,a),f("[KMF] Successfully loaded from current user access (legacy current-user key list)",t))}catch(y){f("[KMF] Legacy current-user secret lookup failed",t,y)}}else throw new Error("[KMF] Unable to access users key manager (same user, no credentials): "+t);if(!i)throw new Error("[KMF] Unable to access users key manager (all methods failed): "+t);const c=i.serialize();return await xe(`km_${t}`,c),this.kms[t]=i,i}}catch(i){console.error("[KMF] Error in getKeyManagerFromKeys:",i)}return null}};S(H,"_staticInstance");let $=H;function Kn(n){return"privateKey"in n||"publicKey"in n}async function Sn(n,e){const t={name:"HMAC",hash:"SHA-256",length:256},r=["sign","verify"],a=await P.subtle.generateKey(t,!0,r);if(Kn(a))throw new Error("Unexpected CryptoKeyPair for HMAC key generation");const s=a,i={groupType:"acnt",groupId:n,keyType:"sym",keyName:e,keyAlgo:t,keyOps:r};return{keyId:l.keyInfoToId(i),keyInfo:i,key:s}}class Na{constructor(){S(this,"keysetPromisesByAcntId",new Map)}lock(e){if(e){this.keysetPromisesByAcntId.delete(e);return}this.keysetPromisesByAcntId.clear()}async getOrCreateKeyset(e,t,r){const a=this.keysetPromisesByAcntId.get(e);if(a)return await a;const s=this.getOrCreateKeysetImpl(e,t,r);this.keysetPromisesByAcntId.set(e,s);try{return await s}catch(i){throw this.keysetPromisesByAcntId.delete(e),i}}async getOrCreateKeysetImpl(e,t,r){const a=await r.loadWrappedKeyset(e);if(a)return await this.unwrapKeyset(a,t);const s=await l.createSecretKey("acnt",e,"local_at_rest_data_v1",["encrypt","decrypt"]),i=await Sn(e,"local_at_rest_index_v1"),d=await l.wrapKey(s,t),c=await l.wrapKey(i,t),o={format:"local-at-rest-keyset-v1",v:1,acntId:e,createdAtMs:Date.now(),dataKeyWrapped:await l.serializeWrappedKey(d,"self"),indexKeyWrapped:await l.serializeWrappedKey(c,"self")};return await r.saveWrappedKeyset(e,o),{dataKey:s,indexKey:i}}async unwrapKeyset(e,t){if(e.format!=="local-at-rest-keyset-v1"||e.v!==1)throw new Error("Unsupported local-at-rest keyset format");const r=await l.deserializeSerializedWrappedKey(e.dataKeyWrapped),a=await l.deserializeSerializedWrappedKey(e.indexKeyWrapped),s=await l.unwrapKey(r,t),i=await l.unwrapKey(a,t);return{dataKey:s,indexKey:i}}}const za="apps.search",xa="apps.reference",Fe=[{id:"apps.search",label:"Search",group:"Apps",icon:"search",appLike:!0,taskbarTarget:"search",cardinality:"single",searchHints:["google","duckduckgo","bing","search engine"]},{id:"apps.email",label:"Email",group:"Apps",icon:"envelope",appLike:!0,taskbarTarget:"email",cardinality:"single",searchHints:["gmail","outlook","mail","inbox"]},{id:"apps.chat",label:"Chat",group:"Apps",icon:"chat",appLike:!0,taskbarTarget:"chat",cardinality:"single",searchHints:["messages","whatsapp","signal","messenger"]},{id:"apps.calendar",label:"Calendar",group:"Apps",icon:"calendar",appLike:!0,taskbarTarget:"calendar",cardinality:"single",searchHints:["google calendar","schedule","agenda"]},{id:"apps.photos",label:"Photos",group:"Apps",icon:"image",appLike:!0,taskbarTarget:"photos",cardinality:"single",searchHints:["google photos","icloud","album","pictures"]},{id:"apps.files",label:"Files",group:"Apps",icon:"files",appLike:!0,taskbarTarget:"files",cardinality:"single",searchHints:["drive","dropbox","onedrive","documents"]},{id:"apps.music",label:"Music",group:"Apps",icon:"headphones",appLike:!0,taskbarTarget:"music",cardinality:"single",searchHints:["spotify","apple music","youtube music","playlist"]},{id:"apps.notes",label:"Notes",group:"Apps",icon:"journal-text",appLike:!0,taskbarTarget:"notes",cardinality:"single",searchHints:["notion","keep","obsidian","notepad"]},{id:"apps.ai",label:"AI Assistant",group:"Apps",icon:"stars",appLike:!0,taskbarTarget:"ai",cardinality:"single",searchHints:["chatgpt","claude","gemini","assistant"]},{id:"apps.reference",label:"Reference",group:"Apps",icon:"book",expectedTypes:["website"],searchHints:["wikipedia","encyclopedia","dictionary","britannica"]},{id:"health.insurance.medical",label:"Health insurance",group:"Health",icon:"shield-check",cardinality:"single",expectedTypes:["information","website"],searchHints:["insurance","member portal","coverage","aetna","blue cross"]},{id:"health.insurance.dental",label:"Dental insurance",group:"Health",icon:"shield-check",cardinality:"single",expectedTypes:["information","website"],searchHints:["dental","insurance","delta dental","coverage"]},{id:"health.provider.physician",label:"Primary physician",group:"Health",icon:"heart-pulse",cardinality:"single",expectedTypes:["person","organization","website"],searchHints:["doctor","clinic","patient portal","mychart"]},{id:"health.provider.dentist",label:"Dentist",group:"Health",icon:"emoji-smile",cardinality:"single",expectedTypes:["person","organization","website"],searchHints:["dentist","dental","orthodontist","teeth"]},{id:"health.provider.physicalTherapist",label:"Physical therapist",group:"Health",icon:"person-walking",cardinality:"single",expectedTypes:["person","organization","website"],searchHints:["physical therapy","pt","rehab","sports medicine"]},{id:"health.pharmacy",label:"Pharmacy",group:"Health",icon:"capsule",cardinality:"single",expectedTypes:["organization","website"],searchHints:["cvs","walgreens","prescription","refill"]},{id:"home.wifi",label:"Wi-Fi & network",group:"Home",icon:"wifi",cardinality:"single",expectedTypes:["information","website"],searchHints:["wifi","router","network","modem","password"]},{id:"home.insurance",label:"Home insurance",group:"Home",icon:"shield-check",cardinality:"single",expectedTypes:["information","website"],searchHints:["homeowners","renters","insurance","policy"]},{id:"home.utilities",label:"Utilities",group:"Home",icon:"lightning-charge",expectedTypes:["website","organization"],searchHints:["electric","gas","water","utility","internet bill"]},{id:"home.warranties",label:"Manuals & warranties",group:"Home",icon:"file-earmark-text",expectedTypes:["information","website"],searchHints:["manual","warranty","receipt","serial number"]},{id:"home.serviceProviders",label:"Service providers",group:"Home",icon:"tools",expectedTypes:["organization","person","website"],searchHints:["plumber","electrician","hvac","handyman","landscaping"]},{id:"finance.bank",label:"Bank",group:"Finance",icon:"bank",expectedTypes:["website","organization"],searchHints:["bank","checking","credit union","chase"]},{id:"finance.taxes",label:"Tax portal",group:"Finance",icon:"receipt",cardinality:"single",expectedTypes:["website","information"],searchHints:["irs","turbotax","w2","filing","tax"]},{id:"finance.insurance.auto",label:"Auto insurance",group:"Finance",icon:"car-front",cardinality:"single",expectedTypes:["information","website"],searchHints:["auto insurance","car insurance","geico","policy"]},{id:"finance.retirement",label:"Retirement account",group:"Finance",icon:"piggy-bank",expectedTypes:["website","organization"],searchHints:["401k","ira","fidelity","vanguard","retirement"]},{id:"school.portal",label:"School portal",group:"School",icon:"mortarboard",cardinality:"single",expectedTypes:["website"],searchHints:["powerschool","canvas","schoology","gradebook"]},{id:"school.teacher",label:"Teacher contact",group:"School",icon:"person",expectedTypes:["person","information"],searchHints:["teacher","classroom","homeroom","email teacher"]}
2,{id:"school.calendar",label:"School calendar",group:"School",icon:"calendar-event",cardinality:"single",expectedTypes:["website","information"],searchHints:["school calendar","schedule","bell schedule","holidays"]},{id:"school.lunchMenu",label:"Lunch menu",group:"School",icon:"cup-straw",cardinality:"single",expectedTypes:["website","information"],searchHints:["lunch","menu","cafeteria","school meals"]}],kn=new Set(Fe.map(n=>n.id)),Ze=new Map(Fe.map(n=>[n.id,n]));function Ba(n){return Ze.get(n)??null}function Va(){const n=[],e=new Map;for(const t of Fe){let r=e.get(t.group);r||(r=[],e.set(t.group,r),n.push({group:t.group,kinds:r})),r.push(t)}return n}function ja(n){const e=Fe.find(t=>t.taskbarTarget===n);return(e==null?void 0:e.id)??null}const Wt="custom.",bn=/^custom\.[a-z0-9][a-z0-9_-]{0,47}$/;function et(n){return typeof n=="string"&&bn.test(n)}function Ha(n){const e=(n||"").toLowerCase().trim().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48);return e?`${Wt}${e}`:null}function vn(n){const e=Ze.get(n);if(e)return e.label;if(et(n)){const t=n.slice(Wt.length).replace(/[-_]+/g," ").trim();return t.charAt(0).toUpperCase()+t.slice(1)}return n}function $a(n){const e=Ze.get(n);return e?[e.label,...e.searchHints||[]]:et(n)?[vn(n)]:[]}function Ga(n){if(!Array.isArray(n))return[];const e=[],t=new Set;for(const r of n){if(typeof r!="string")continue;const a=r.trim();!a||t.has(a)||(kn.has(a)||et(a))&&(t.add(a),e.push(a))}return e}function En(n){return!!n&&typeof n[Symbol.iterator]=="function"}function ie(n){if(n){if(typeof n=="string")return n;if(n instanceof Date)return n.toISOString()}}function G(n){if(n){if(Array.isArray(n)){const e=n.filter(Boolean).map(t=>String(t));return e.length>0?e:void 0}if(n instanceof Set){const e=Array.from(n).filter(Boolean).map(t=>String(t));return e.length>0?e:void 0}if(typeof n=="string")return n?[n]:void 0;if(typeof n=="object"){const e=n;if("ids"in e)return G(e.ids);if("categories"in e)return G(e.categories);if(En(e))try{const t=Array.from(e).filter(Boolean).map(r=>String(r));return t.length>0?t:void 0}catch{}}}}function Z(n){return typeof n!="string"?void 0:n.trim()||void 0}function fe(n,e){const t=Z(n);if(t)return e&&wr(e,t)||t}function Ke(n){if(n)return Zt(n)?void 0:n}function tt(n){var a;const e=n==null?void 0:n.details;if(!e)return null;const t=n,r=Array.isArray((a=t.encInfo)==null?void 0:a.keys)&&t.encInfo.keys.length>0;return t.encrypted===!0&&r&&t.decrypted!==!0?null:e}function An(n,e){var t;return bt(n,{relationName:(t=tt(e))==null?void 0:t.name})}function Cn(n,e,t){var r;return(Ke((r=tt(e))==null?void 0:r.description)||Ke(n.description)||(t==null?void 0:t.description))??void 0}function Un(n,e){var t;return(Ke((t=tt(e))==null?void 0:t.comment)||Ke(n.comment))??void 0}function Nt(n,e){if(n==="col")return{typeName:"Collection",typeIcon:"collection"};const t=pr(n,e)??void 0,a=fr(t||n||"default");return a?{typeName:a.name,typeIcon:a.icon}:{typeName:t||n,typeIcon:t||n}}function zt(n,e,t){const r=Z(t)||Z(n.url)||Z(e==null?void 0:e.url);return Z(n.imageFilename)||Z(e==null?void 0:e.bannerImagePath)||fe(e==null?void 0:e.imageSrc,r)||fe(e==null?void 0:e.bannerImageSrcPath,r)||fe(e==null?void 0:e.faviconSrcPath,r)||fe(e==null?void 0:e.favicon,r)||Z(e==null?void 0:e.faviconPath)}function xt(n,e={}){var A;const{details:t,feedback:r,collectionRelation:a,collectionIds:s,itemId:i}=n,d=t.meta,c=lr(n),o=yr(G(t.useCriteria)||[]),u=Ut(t),{typeName:y,typeIcon:p}=Nt(t.type,u??void 0),g=Tt(t.type,u??""),h=zt(t,d),w=(t==null?void 0:t.encInfo)!=null&&Array.isArray(t.encInfo.keys)&&t.encInfo.keys.length>0,m=t.encrypted===!0&&w&&t.decrypted===!1;let C=An(t,a),I=Cn(t,a,d),U=Un(t,a);m&&(C="[Decryption failed] - check encryption settings",I="[Decryption failed] - check encryption settings",U="[Decryption failed] - check encryption settings");const b={baseType:"library",type:t.type,subType:u??void 0,contractId:g.contractId,experienceKind:g.experienceKind,defaultViewMode:g.defaultViewMode,capabilityFlags:g.capabilityFlags,provider:g.provider,resourceType:g.resourceType,typeName:y??void 0,typeIcon:p??void 0,_id:t._id||i,name:C,description:I,comment:U,url:t.url??void 0,defaultImage:h,accountId:t.accountId??void 0,userId:t.userId??void 0,visibility:t.visibility??void 0,categories:G(t.categories),tags:t.tags??void 0,kinds:G(t.kinds),useCriteria:G(t.useCriteria),eduValue:o.eduValue,patterns:t.patterns??void 0,imageFilename:t.imageFilename??void 0,archived:t.archived??void 0,createdAt:ie(t.createdAt),updatedAt:ie(t.updatedAt),order:(a==null?void 0:a.order)??void 0,collectionIds:s,collectionRelationId:a==null?void 0:a._id,collectionRelation:a,addedToCollectionAt:(a==null?void 0:a.createdAt)??void 0,publishedUpdatedAt:(a==null?void 0:a.publishedUpdatedAt)??void 0,lastVisit:(r==null?void 0:r.lastVisit)??void 0,visit
2Count:(r==null?void 0:r.visitCount)||0,visitTime:(r==null?void 0:r.visitTime)??void 0,feedback:r,permission:t.permission??void 0,permissionUserId:t.permissionUserId??void 0,sharedByUserId:t.sharedByUserId??void 0,sharedWithUserId:t.sharedWithUserId??void 0,sharedAt:ie(t.sharedAt),publishId:t.publishId??void 0,published:t.published??void 0,meta:d??void 0,attachments:t.attachments??void 0,info:t.info??void 0,sysInfo:t.sysInfo??void 0,audioUrl:c==null?void 0:c.audioUrl,audioType:c==null?void 0:c.audioType,audioDuration:c==null?void 0:c.audioDuration,playbackSchema:c??void 0,encrypted:t.encrypted??void 0,decrypted:t.decrypted??void 0,decryptionFailed:m,encInfo:t.encInfo};if("scoreInfo"in n&&(b.scoreInfo=n.scoreInfo,b.orderIdx=e.orderIdx??void 0,b.finalRelScore=((A=b.scoreInfo)==null?void 0:A._relScore)||0,b.visitCount&&b.visitCount>0)){const T=b.finalRelScore||0;b.finalRelScore=T+(T||1)*.56*Math.log(b.visitCount)}return b}function qa(n,e={}){return n.map((t,r)=>xt(t,{...e,orderIdx:r}))}function Bt(n){var m,C,I,U,b,A,T;const{details:e,stats:t,curation:r,parentRelation:a,inLibrary:s}=n,i=e.meta,d=Ut(e),{typeName:c,typeIcon:o}=Nt(e.type,d??void 0),u=Tt(e.type,d??""),y=zt(e,i,(m=e.data)==null?void 0:m.url),p=bt({name:e.name,meta:i,url:(C=e.data)==null?void 0:C.url},{relationName:(I=a==null?void 0:a.details)==null?void 0:I.name}),g=((U=a==null?void 0:a.details)==null?void 0:U.description)||e.description||(i==null?void 0:i.description),h=(b=a==null?void 0:a.details)==null?void 0:b.comment;return{baseType:"published",pubItem:!0,type:e.type,subType:d??void 0,contractId:u.contractId,experienceKind:u.experienceKind,defaultViewMode:u.defaultViewMode,capabilityFlags:u.capabilityFlags,provider:u.provider,resourceType:u.resourceType,_id:e._id,easyId:e.easyId??void 0,name:p||"?",description:g,comment:h,url:(A=e.data)==null?void 0:A.url,typeName:c??void 0,typeIcon:o??void 0,defaultImage:y,imageFilename:y,patterns:(T=e.data)==null?void 0:T.patterns,data:e.data??void 0,categories:G(e.categories),useCriteria:G(e.useCriteria),username:e.username??void 0,publicUserId:e.publicUserId??void 0,publishType:e.publishType??void 0,publishConfig:e.publishConfig??void 0,stats:t,overallRating:t==null?void 0:t.overallRating,numRatings:t==null?void 0:t.numRatings,statSubCount:t==null?void 0:t.statSubCount,statViewCount:t==null?void 0:t.statViewCount,curation:r,curated:r==null?void 0:r.curated,curationStatus:r==null?void 0:r.curationStatus,curatedDate:(r==null?void 0:r.curatedDate)??void 0,curatorId:r==null?void 0:r.curatorId,curatorComment:r==null?void 0:r.curatorComment,underReview:!!(r!=null&&r.underReviewAt),nextReviewAt:(r==null?void 0:r.nextReviewAt)??void 0,inLibrary:s,parentRelation:a,createdAt:ie(e.availableAt)||ie(e.createdAt),updatedAt:ie(e.updatedAt),attachments:e.attachments??void 0,sysInfo:e.sysInfo??void 0,info:e.info??void 0,meta:i??void 0}}function Ya(n){return n.map(Bt)}function Tn(n){return{baseType:"tab",type:"tab",_id:`tab_${n.id}`,name:n.title||n.url,url:n.url,tabId:n.id,windowId:n.windowId,index:n.index,tabInfo:n}}const ht=500,_n=.8,Fn=.6,Rn=.5;function x(n){return typeof n!="string"?void 0:n.replace(/\s+/g," ").trim()||void 0}function Pn(n){var t,r;const e=(r=(t=n.documentElement)==null?void 0:t.localName)==null?void 0:r.toLowerCase();return e==="feed"?"atom":e==="rss"||e==="rdf"?"rss":null}function Vt(n,e){if(e==="atom")return Array.from(n.querySelectorAll("entry"));const t=Array.from(n.querySelectorAll("item"));return t.length>0?t:Array.from(n.querySelectorAll("channel > item"))}function wt(n){return typeof n=="string"&&n.trim().toLowerCase().startsWith("audio/")}function On(n){var e;for(const t of Array.from(n.getElementsByTagName("enclosure"))){const r=t.getAttribute("type"),a=x(t.getAttribute("url"));if(wt(r)&&a)return{url:a,type:r??void 0}}for(const t of Array.from(n.getElementsByTagName("link"))){if(((e=t.getAttribute("rel"))==null?void 0:e.trim().toLowerCase())!=="enclosure")continue;const r=t.getAttribute("type"),a=x(t.getAttribute("href"));if(wt(r)&&a)return{url:a,type:r??void 0}}return null}function Ln(n){return On(n)!==null}function Dn(n,e){var t;return e?!!x((t=n.getElementsByTagNameNS(e,"duration")[0])==null?void 0:t.textContent):!1}function Mn(n,e){return e?["type","category","author","image","owner"].some(t=>n.getElementsByTagNameNS(e,t).length>0):!1}function Wn(n,e,t){if(e.length===0)return;const r=n.lookupNamespaceURI("itunes");if(t.length===0)return;const a=t.length/e.length,s=t.filter(i=>Dn(i,r)).length/t.length;if(a>=_n||a>=Fn&&(s>=Rn||Mn(n,r)))return"audio"}function Nn(n){const e=String((n==null?void 0:n.type)||"").trim().toLowerCase();return e==="rss"||e==="feed"||e==="podcast"?"rss":e==="atom"?"atom":e==="json"?"json":null}const mt="http://www.w3.org/2005/Atom",jt=["siriusxm.com","simplecast.com","megaphone.fm","art19.com","acast.com","iheart.com","iheartradio.com","spotify.com","wondery.com","audioboom.com","libsyn.com","buzzsprout.com","podbean.com","anchor.fm","spreaker.com","soundcloud.com","omny.fm","omnycontent.com","omnystudio.com","transistor.fm","captivate.fm","redcircle.com","blubrry.com","stitcher.com","podtrac.com","chrt.fm","pdst.fm","podscribe.com","feedbur
2ner.com","apple.com"];function Ht(n,e){return e.some(t=>n===t||n.endsWith(`.${t}`))}function $t(n,e){const t=x(n);if(!t)return;const r=/^(?:[a-z0-9-]+\.)+[a-z]{2,}(?:[/:?#]|$)/i.test(t)?`https://${t}`:t;return rt(r,e)}function It(n,e){let t;try{t=new URL(n)}catch{return!1}const r=t.hostname.toLowerCase();return!(e.has(Ge(n))||mr(n)||Ir.has(r)||["feed","feeds","rss"].includes(r.split(".")[0])||(t.pathname==="/"||t.pathname==="")&&!t.search&&Ht(r,jt))}function Ge(n){return n.trim().replace(/\/+$/,"").toLowerCase()}function Gt(n){const e=n?Array.from(n.children).filter(t=>t.localName==="link"):[];return{plain:e.filter(t=>t.namespaceURI!==mt&&!t.hasAttribute("href")),atom:e.filter(t=>t.namespaceURI===mt||t.hasAttribute("href"))}}function qe(n){const e=n.find(t=>{var a;const r=(a=t.getAttribute("rel"))==null?void 0:a.trim().toLowerCase();return r==="alternate"||!r});return(e==null?void 0:e.getAttribute("href"))??void 0}function zn(n,e,t){var d;const r=new Map;let a=0;for(const c of Vt(n,e)){const{plain:o,atom:u}=Gt(c),y=$t(x((d=o[0])==null?void 0:d.textContent)||qe(u),t);if(!y)continue;const{hostname:p,origin:g}=new URL(y);if(Ht(p.toLowerCase(),jt))continue;a+=1;const h=p.toLowerCase().replace(/^www\./,""),w=r.get(h)||{count:0,origins:new Map};w.count+=1,w.origins.set(g,(w.origins.get(g)||0)+1),r.set(h,w)}const s=[...r.values()].sort((c,o)=>o.count-c.count)[0];if(!s||s.count*2<a)return;const[i]=[...s.origins.entries()].sort((c,o)=>o[1]-c[1])[0];return`${i}/`}function xn(n,e,t){var o;const r=e==="atom"?n.documentElement:n.querySelector("channel"),{plain:a,atom:s}=Gt(r),i=new Set;t&&i.add(Ge(t));for(const u of s){if(((o=u.getAttribute("rel"))==null?void 0:o.trim().toLowerCase())!=="self")continue;const y=rt(u.getAttribute("href")??void 0,t);y&&i.add(Ge(y))}const d=e==="atom"?[qe(s)]:[...a.map(u=>u.textContent??void 0),qe(s.filter(u=>u.hasAttribute("rel")))];for(const u of d){const y=$t(u,t);if(y&&It(y,i))return y}const c=zn(n,e,t);return c&&It(c,i)?c:void 0}function rt(n,e){const t=x(n);if(t)try{const r=e?new URL(t,e):new URL(t);return r.protocol!=="http:"&&r.protocol!=="https:"?void 0:r.toString()}catch{return}}function ue(n,e){if(!n)return;const t=Array.from(n.children).find(r=>r.localName===e);return x(t==null?void 0:t.textContent)}function Bn(n,e){const t=e==="atom"?n.documentElement:n.querySelector("channel"),r=e==="atom"?ue(t,"subtitle"):ue(t,"description")||ue(t,"summary")||ue(t,"subtitle");if(!r)return;const a=x(r.replace(/<[^>]+>/g," "));if(a)return a.length>ht?`${a.slice(0,ht-1).trimEnd()}â¦`:a}function Vn(n,e,t){const r=e==="atom"?n.documentElement:n.querySelector("channel");if(!r)return;const a=[];for(const s of Array.from(r.children)){const i=s.localName;e!=="atom"&&i==="image"&&(a.push(s.getAttribute("href")||void 0),a.push(ue(s,"url"))),e==="atom"&&(i==="logo"||i==="icon")&&a.push(x(s.textContent))}for(const s of a){const i=rt(s,t);if(i)return i}}function Qa(n,e){var u;const t=x(n);if(!t)return{ok:!1,reason:"Feed URL returned an empty response."};const a=new DOMParser().parseFromString(t,"text/xml");if(a.querySelector("parsererror"))return{ok:!1,reason:"Feed URL did not return valid XML."};const s=Pn(a);if(!s)return{ok:!1,reason:"Feed URL did not return an RSS or Atom feed."};const i=s==="atom"?"feed > title":"channel > title",d=x((u=a.querySelector(i))==null?void 0:u.textContent),c=Vt(a,s);if(!d)return{ok:!1,reason:"Feed is missing a title."};if(c.length===0)return{ok:!1,reason:"Feed does not contain any entries yet."};const o=c.filter(Ln);return{ok:!0,feedType:s,mediaKind:Wn(a,c,o),title:d,itemCount:c.length,playableEpisodeCount:o.length,homePageUrl:xn(a,s,e),description:Bn(a,s),imageUrl:Vn(a,s,e)}}function Ja(n){for(const e of n){if(typeof e!="string")continue;const t=e.trim();if(t)return t}return""}function Xa(n){return n.includes("youtube.com/c/")||n.includes("youtube.com/channel/")||n.includes("youtube.com/@")||n.includes("youtube.com/user/")}const jn=/\/(channel|c|user)\/([^\/?#]+)(?:[/?#].*)?/i,Hn=/\/@([^\/?#]+)(?:[/?#].*)?/i;function Y(n){const e=String(n||"").trim();return e?e.startsWith("@")?e.slice(1).toLowerCase():e.startsWith("UC")?e:e.toLowerCase():null}function $n(n){const e=n.match(jn);return e?Y(e[2]):null}function Za(n){const e=/(?:v=|\/)([a-zA-Z0-9_-]{11})/,t=n.match(e);return t?t[1]:null}function Gn(n){const e=n.match(Hn);return e?Y(e[1]):null}function qn(n){if(!n)return[];const e=new Set,t=$n(n),r=Gn(n);return t&&e.add(t),r&&e.add(r),Array.from(e)}function es(n){var t,r,a;let e=!1;return(((r=(t=n==null?void 0:n.meta)==null?void 0:t.tsExtractedInfo)==null?void 0:r.pageType)==he.YT_CHANNEL||(a=n==null?void 0:n.info)!=null&&a.feeds&&(n==null?void 0:n.info.feeds.length)>0||n.type=="col")&&(e=!0),n!=null&&n.sysInfo||(n.sysInfo={}),n.sysInfo.hasFeeds=e,n.sysInfo.v=1,n.sysInfo.updatedAt=new Date,n}function Se(n,e){const t=new Set,r=(n==null?void 0:n.tsExtractedInfo)||null;for(const a of[...(n==null?void 0:n.youtubeChannelIds)||[],...(r==null?void 0:r.youtubeChannelIds)||[]]){const s=Y(a);s&&t.add(s)}for(const a of[n==null?void 0:n.channelId,n==null?void 0:n.handleId,r==null?void 0:r.channelId,r==null?void 0:r.handleId]){const s=Y(a);s&&t.add(s)}for(const a of qn((n==null?void 0:n.url)||e)){const s=Y(a);s&&t.add(s)}return Array.from(t)}function Yn(n){try{return new URL(n).pathname.startsWith("/shorts/")}catch{return!1}}function qt(n){var a,s,i;const e=(a=n.details)==null?void 0:a.meta,t=((s=e==null?void 0:e.tsExtractedInfo)==null?void 0:s.pageType)||(e==null?void 0:e.pageType),r=((i=n.details)==null?void 0:i.url)||(e==null?void 0:e.url);return t===he.YT_VIDEO||r&&(Kr(r)||Yn(r))?!1:t===he.YT_CHANNEL?!0:!!r&&(Sr(r)||!!Zn(r))}function Ne(n){var e,t;return qt(n)?Se((e=n.details)==null?void 0:e.meta,(t=n.details)==null?void 0:t.url):[]}async function ts(n,e,t){var i,d;const r=Se({channelId:e})[0];if(!r)return[];const a=n.filter(c=>Ne(c).includes(r));if(a.length>0)return a;const s=new Set([r]);for(const c of n){const o=Se((i=c.details)==null?void 0:i.meta,(d=c.details)==null?void 0:d.url);if(o.includes(r))for(const u of o)s.add(u)}if(s.size>1){const c=n.filter(o=>
2Ne(o).some(u=>s.has(u)));if(c.length>0)return c}if(t){const c=n.filter(u=>qt(u)).filter(u=>!Ne(u).includes(r)).slice(0,25),o=[];for(const u of c)try{(await t(u)).includes(r)&&o.push(u)}catch{}if(o.length>0)return o}return[]}function Qn(n){if(!Array.isArray(n)||n.length===0)return null;const e=n.map(t=>Y(t)).filter(t=>!!t);return e.find(t=>t.startsWith("UC"))||e[0]||null}function Jn(n){const e=Y(n);return!e||!e.startsWith("UC")||e.length<=2?null:`UULF${e.slice(2)}`}function Xn(n){const e=Y(n);return!e||!e.startsWith("UC")?null:`https://www.youtube.com/feeds/videos.xml?channel_id=${e}`}function Zn(n){const e=String(n||"").trim();if(!e)return null;let t;try{t=new URL(e)}catch{return null}if(!t.hostname.toLowerCase().endsWith("youtube.com")||t.pathname!=="/feeds/videos.xml")return null;const a=Jn(t.searchParams.get("channel_id"));if(!a)return null;const s=new URL(t.toString());return s.searchParams.delete("channel_id"),s.searchParams.set("playlist_id",a),s.toString()}function ea(n,e=50,t=null){var a;const r=xt(n);return r.scoreInfo=n.scoreInfo,r.orderIdx=t,r.finalRelScore=((a=r.scoreInfo)==null?void 0:a._relScore)||0,r.visitCount&&r.visitCount>0&&(r.finalRelScore=r.finalRelScore+(r.finalRelScore||1)*.56*Math.log(r.visitCount)),r.type!==Be.collection&&e&&r.name&&(r.name=dr(r.name,e)),r}function rs(n,e=50,t=!1){if(!n)return console.warn("[prepareItems] missing itemList â caller likely skipped a response.success check"),[];const r=[];for(const[a,s]of Object.values(n).entries()){const i=ea(s,e,a);r.push(i)}return t&&r.sort((a,s)=>s.order-a.order),r}function ta(n,e){return String(n).trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||e}function ra(n,e){if(!n||typeof n!="object")return null;const t=n.type||"rss",r=typeof n.feedURL=="string"?n.feedURL.trim():"",a=String(n.title||n.url||r||"Feed").trim()||"Feed";return t!=="pub_col"&&!r?null:{...n,feedId:String(n.feedId||ta(a,e)),type:t,title:a,feedURL:r||void 0}}function na(n){var a,s,i,d;const e=[],t=new Set,r=(c,o)=>{const u=ra(c||null,o);if(!u)return;const y=u.type==="pub_col"?`${u.type}:${u.feedId}`:u.feedURL||`${u.type}:${u.feedId}`;t.has(y)||(t.add(y),e.push(u))};for(const[c,o]of(((a=n.info)==null?void 0:a.feeds)||[]).entries())r(o,`feed-${c+1}`);if(n.type=="col"||n.subType=="pub_col_slink")r({feedId:"default",title:n.name,description:"Get notified when new items are added to this collection.",config:{pubId:n.publishId||n._id},type:"pub_col"},"default");else if(((i=(s=n==null?void 0:n.meta)==null?void 0:s.tsExtractedInfo)==null?void 0:i.pageType)==he.YT_CHANNEL){const c=Qn(Se(n==null?void 0:n.meta,n.url)),o=Xn(c);o&&r({feedId:"main",title:"Channel Feed",type:"rss",url:n.url,feedURL:o},"main")}for(const[c,o]of(((d=n.info)==null?void 0:d.additionalLinks)||[]).entries()){const u=Nn(o);u&&r({feedId:o.id||`link-feed-${c+1}`,title:o.title||"Feed",type:u,url:n.url,feedURL:o.url},`link-feed-${c+1}`)}return e}function ns(n){return n.filter(e=>
2typeof(e==null?void 0:e.url)=="string"&&e.url.startsWith("http")).map(e=>Tn(e))}async function as(n={}){return new Promise((e,t)=>{chrome.tabs.query(n,r=>{if(chrome.runtime.lastError)return t(chrome.runtime.lastError);e(r)})})}function aa(n){return n?na(n).length>0:!1}const sa=new Set(["yt_channel"]);function ss(n){return aa(n)?!sa.has(hr(n)):!1}function ia(n){const e={publishedId:n._id,details:n,stats:n.stats||{overallRating:n.overallRating,numRatings:n.numRatings,statSubCount:n.statSubCount,statViewCount:n.statViewCount},curation:n.curation||{curated:n.curated,curationStatus:n.curationStatus,curatedDate:n.curatedDate,curatorId:n.curatorId,curatorComment:n.curatorComment,underReviewAt:n.underReviewAt,nextReviewAt:n.nextReviewAt},parentRelation:n.parentRelation},t=Bt(e);t.imageFilename&&!t.imageFilename.startsWith("http")&&(t.imageFilename=ur(t.imageFilename));const r=gr(n.useCriteria);return Object.assign(t,{eduValue:r.eduValue,minAgeGroup:r.minAgeGroup,targetAudiences:r.targetAudiences,cost:r.cost,ads:r.ads,costDetails:r.costDetails}),t}function is(n){return"iconBG"+n.length%6+"grad"}function cs(n){const e=[];for(const t of n)e.push(ia(t));return e}const Kt="operationQueue",ca=3,oa=5e3,Ae=class Ae{constructor(e=Ue.instance){S(this,"syncInterval",null);S(this,"isSyncing",!1);S(this,"conflictStrategy","last-write-wins");S(this,"onlineListenerCleanup");S(this,"offlineListenerCleanup");this.remoteRequester=e,this.startSyncWorker(),this.setupOnlineListener()}static get instance(){return this._staticInstance||(this._staticInstance=new Ae),this._staticInstance}async queueWrite(e,t,r={}){const a={id:this.generateId(),timestamp:Date.now(),path:e,data:t,status:"pending",retryCount:0,maxRetries:r.maxRetries||ca};try{return await this.addToQueue(a),f("OperationQueue: Queued operation",a.id,e),Re()&&this.processSingleOperation(a.id),a.localResult}catch(s){throw console.error("OperationQueue: Failed to queue operation",s),s}}async addToQueue(e){const t=await this.getQueueState();t.operations.push(e),await this.saveQueueState(t),V.emit("sync-queue-updated",{action:"queued",operationId:e.id,path:e.path,status:e.status,pendingCount:t.operations.filter(r=>r.status==="pending"||r.status==="syncing").length})}async getQueueState(){return await Ye(Kt)||{operations:[],lastSyncAttempt:null}}async saveQueueState(e){await xe(Kt,e)}async processQueue(){if(this.isSyncing){f("OperationQueue: Already syncing, skipping");return}if(!Re()){f("OperationQueue: Offline, skipping sync");return}this.isSyncing=!0;try{const e=await this.getQueueState(),t=e.operations.filter(a=>a.status==="pending"||a.status==="failed");if(t.length===0)return;f(`OperationQueue: Processing ${t.length} operations`),V.emit("sync-batch-started",{count:t.length});for(const a of t)await this.syncOperation(a);e.lastSyncAttempt=Date.now(),await this.saveQueueState(e);const r=e.operations.filter(a=>a.status==="pending"||a.status==="failed");V.emit("sync-batch-completed",{processed:t.length,remaining:r.length,timestamp:e.lastSyncAttempt})}catch(e){console.error("OperationQueue: Error processing queue",e)}finally{this.isSyncing=!1}}async processSingleOperation(e){const t=await this.getQueueState(),r=t.operations.find(a=>a.id===e);r&&(await this.syncOperation(r),await this.saveQueueState(t))}async syncOperation(e){const t=e.status;e.status="syncing",V.emit("sync-operation-status-changed",{operationId:e.id,path:e.path,status:"syncing",previousStatus:t});try{await this.remoteRequester.remoteAPIRequest(e.path,e.data),e.status="synced",f("OperationQueue: Synced operation",e.id),V.emit("sync-operation-status-changed",{operationId:e.id,path:e.path,status:"synced",previousStatus:"syncing"})}catch(r){if(e.error=r.message,(r==null?void 0:r.status)===401&&(r==null?void 0:r.errorType)==="AUTH"){e.status="failed",f("OperationQueue: Operation failed (auth), not retrying",e.id),V.emit("sync-operation-failed",{operationId:e.id,path:e.path,error:r.message,retryCount:e.retryCount,maxRetries:e.maxRetries});return}e.retryCount++,e.retryCount>=e.maxRetries?(e.status="failed",console.error("OperationQueue: Operation failed permanently",e.id,r),V.emit("sync-operation-failed",{operationId:e.id,path:e.path,error:r.message,retryCount:e.retryCount,maxRetries:e.maxRetries}
2)):(e.status="pending",f("OperationQueue: Operation failed, will retry",e.id),V.emit("sync-operation-retry",{operationId:e.id,path:e.path,error:r.message,retryCount:e.retryCount,maxRetries:e.maxRetries}))}}async getPendingCount(){return(await this.getQueueState()).operations.filter(t=>t.status==="pending"||t.status==="syncing").length}async getStatus(){const e=await this.getQueueState(),t=e.operations.filter(a=>a.status==="pending"||a.status==="syncing").length,r=e.operations.filter(a=>a.status==="failed"&&!!a.error).map(a=>a.error).slice(-10);return{enabled:this.syncInterval!==null,...e.lastSyncAttempt?{lastSync:e.lastSyncAttempt}:{},pendingOperations:t,syncInProgress:this.isSyncing,...r.length>0?{errors:r}:{}}}async getAllOperations(){return(await this.getQueueState()).operations}async clearOldSyncedOperations(e=7){const t=await this.getQueueState(),r=Date.now()-e*24*60*60*1e3;t.operations=t.operations.filter(a=>!(a.status==="synced"&&a.timestamp<r)),await this.saveQueueState(t)}async retryOperation(e){const t=await this.getQueueState(),r=t.operations.find(a=>a.id===e);r&&r.status==="failed"&&(r.status="pending",r.retryCount=0,r.error=void 0,await this.saveQueueState(t),await this.processSingleOperation(e))}async clearAll(){await this.saveQueueState({operations:[],lastSyncAttempt:null})}startSyncWorker(){this.syncInterval===null&&(this.syncInterval=er(()=>{Re()&&this.processQueue()},oa))}stopSyncWorker(){this.syncInterval!==null&&(tr(this.syncInterval),this.syncInterval=null)}setupOnlineListener(){this.onlineListenerCleanup=rr(()=>{f("OperationQueue: Back online, processing queue"),this.processQueue()}),this.offlineListenerCleanup=nr(()=>{f("OperationQueue: Went offline")})}cleanup(){this.stopSyncWorker(),this.onlineListenerCleanup&&this.onlineListenerCleanup(),this.offlineListenerCleanup&&this.offlineListenerCleanup()}generateId(){return`op_${Date.now()}_${br(9)}`}setConflictStrategy(e){this.conflictStrategy=e}};S(Ae,"_staticInstance");let St=Ae;export{Ur as $,vn as A,qa as B,$r as C,k as D,Ve as E,je as F,Pt as G,N as H,ia as I,ea as J,Xe as K,Mt as L,Qn as M,Xn as N,Ta as O,Oe as P,In as Q,xa as R,za as S,is as T,Q as U,ja as V,ae as W,Fe as X,te as Y,me as Z,se as _,cs as a,ce as a0,L as a1,un as a2,Or as a3,br as a4,ns as a5,as as a6,kn as a7,et as a8,$a as a9,Lt as aA,Qe as aB,ts as aC,Ua as aD,La as aE,Ka as aF,Ca as aG,Ma as aH,ma as aI,ee as aJ,Ja as aK,wa as aL,qt as aM,Ne as aN,Ea as aO,Sa as aP,Aa as aQ,Zn as aa,Qa as ab,On as ac,Gr as ad,Fr as ae,ka as af,Ot as ag,Va as ah,Ha as ai,Xa as aj,$n as ak,Gn as al,Za as am,$ as an,Na as ao,Ar as ap,it as aq,st as ar,Cr as as,Ia as at,Da as au,St as av,kr as aw,Wa as ax,we as ay,_ as az,Ya as b,xt as c,Bt as d,W as e,Se as f,qn as g,aa as h,es as i,_a as j,Fa as k,Dt as l,Ra as m,Y as n,Pa as o,na as p,Oa as q,rs as r,ss as s,Te as t,Lr as u,va as v,ba as w,Dr as x,Ga as y,Ba as z};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.