@ibgib/space-gib 0.0.22 → 0.0.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,27 @@
1
+ var Sc=Object.defineProperty;var f=(r,e)=>Sc(r,"name",{value:e,configurable:!0});var re=/^[a-zA-Z0-9_\-.]{1,256}$/,Ze=/^[a-zA-Z0-9_]{1,255}$/,_s=/^(\[.+\])?\s?(\(UNEXPECTED\)|\(unexpected\))?(.+)(\([EIWeiw]: [a-fA-F\d]{32}\))(\(UNEXPECTED\)|\(unexpected\))?$/,Ts=/^(\[.+\]).+$/,As=/^[0-9a-fA-F]{32}$/,Ss=/^[0-9a-fA-F]{64}$/;var Nt="/",Gs="_nonalphanumerics_";var Ct=!1,Fo=globalThis.crypto,{subtle:xc}=Fo,we={sha_256:"SHA-256",sha_512:"SHA-512"};function C(r){return JSON.parse(JSON.stringify(r))}f(C,"clone");function Ae(r){return(r??new Date).toUTCString()}f(Ae,"getTimestamp");var vc=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));async function X({s:r,algorithm:e="SHA-256"}){if(!r)return"";try{let t=Object.values(we);if(!t.includes(e))throw new Error(`Only ${t} implemented (E: 73cb52cd4d7f70c3415fdf695ba6ba23)`);let o=new TextEncoder().encode(r),n=await xc.digest(e,o),s=new Uint8Array(n),i="";for(let a=0;a<s.length;a++)i+=vc[s[a]];return i}catch(t){throw console.error(E(t.message)),t}}f(X,"hash");async function F(r){if(!globalThis.crypto)throw new Error("globalThis.crypto falsy. Cannot create UUID, as unknown crypto library version. If using node.js, v19+ is required. (E: c02cee3fd8a94f678d3f4ebe9dc49797)");let e;if(r&&r>16||!globalThis.crypto.randomUUID){if(!globalThis.crypto.getRandomValues)throw new Error("globalThis.crypto.getRandomValues falsy. Cannot create UUID, as unknown crypto library version. If using node.js, v19+ is required. (E: d2fa34b26d0808adc8184d98cc767d26)");r||=32;let t=Fo.getRandomValues(new Uint8Array(r)),o="";for(let n=0;n<t.length;n++)o+=String.fromCharCode(t[n]);e=await X({s:o})}else{if(!globalThis.crypto.randomUUID)throw new Error("globalThis.crypto.randomUUID falsy. Cannot create UUID, as unknown crypto library version. If using node.js, v19+ is required. (E: e30da81f5c284d6a389930b5e7daa826)");let t=Fo.randomUUID();e=await X({s:t})}if(!e)throw new Error("(UNEXPECTED) uuid falsy? could not create uuid? (E: 5276bcc4e8f75aa2c82a54a8c8b2d626)");return e}f(F,"getUUID");function H(r){return JSON.stringify(r,null,2)}f(H,"pretty");async function de(r){return new Promise(e=>{setTimeout(()=>{e()},r)})}f(de,"delay");function E(r){return!r&&r!==0?"[error is falsy]":typeof r=="string"?r:typeof r.message=="string"?r.message:typeof r=="number"?JSON.stringify(r):r.error?(console.warn(`[${E.name}] this fn takes the raw error object. no destructure required. change your call from extractErrorMsg({error}) to extractErrorMsg(error). (W: ea49af5fd76d4b80a55a108d73a3e9b4)`),E(r.error)):`[error is not a string and error.message is not a string. typeof error: ${typeof r} (E: d5a7723ca59646838308bc9e53a43134)]`}f(E,"extractErrorMsg");function qo({items:r,keyFn:e}){let t=`[${qo.name}]`;try{let o={};for(let n=0;n<r.length;n++){let s=r[n],i=e(s);o[i]=[...o[i]??[],s]}return o}catch(o){throw console.error(`${t} ${o.message}`),o}}f(qo,"groupBy");function Ar({min:r,max:e,chars:t,noSpaces:o}){return r=r??1,e=e??999999999999,t=t??"",o?new RegExp(`^[\\w${t}]{${r},${e}}$`):new RegExp(`^[\\w\\s${t}]{${r},${e}}$`)}f(Ar,"getRegExp");function $e(r){let e;if(r){if(e=new Date(r),e.toString()==="Invalid Date")throw new Error(`invalid date created by timestamp (${r}) (E: cbd6aeefe00708184e276ea3c2532b22)`)}else e=new Date;return e.getTime().toString()}f($e,"getTimestampInTicks");function Ho({startDate:r,years:e,months:t,days:o,hours:n,seconds:s}){let i=`[${Ho.name}]`;try{return Et({startDate:r,years:e,months:t,days:o,hours:n,seconds:s}).toUTCString()}catch(a){throw console.log(`${i} ${a.message}`),a}}f(Ho,"getExpirationUTCString");function Et({startDate:r,years:e,months:t,days:o,hours:n,seconds:s}){let i=`[${Et.name}]`;try{if(!r&&!e&&!t&&!o&&!n&&!s)throw new Error("either startDate or a time interval required. (E: 30248f8b306f443ab036fa8c313c50d8)");r=r?new Date(r):new Date;let a,c;return e?(a=r.getFullYear()+e,c=r.setFullYear(a),Et({startDate:new Date(c),months:t,days:o,hours:n,seconds:s})):t?(a=r.getMonth()+t,c=r.setMonth(a),Et({startDate:new Date(c),years:e,days:o,hours:n,seconds:s})):o?(a=r.getDate()+o,c=r.setDate(a),Et({startDate:new Date(c),years:e,months:t,hours:n,seconds:s})):n?(a=r.getHours()+n,c=r.setHours(a),Et({startDate:new Date(c),years:e,months:t,days:o,seconds:s})):s?(a=r.getSeconds()+s,c=r.setSeconds(a),Et({startDate:new Date(c),years:e,months:t,days:o,hours:n})):r}catch(a){throw console.log(`${i} ${a.message}`),a}}f(Et,"addTimeToDate");function Ko({expirationTimestampUTC:r}){let e=`[${Ko.name}]`;try{if(!r)throw new Error("expirationTimestampUTC required (E: 5eeb1e29f93d64f70c71a8112080a222)");let t=new Date(r);if(t.toUTCString()==="Invalid Date")throw new Error(`invalid expirationTimestampUTC: ${r} (E: 66a1a165bcf1f9336fe78856ab777822)`);return t<new Date}catch(t){throw console.error(`${e} ${t.message}`),t}}f(Ko,"isExpired");function Xt(r){return Array.from(new Set(r))}f(Xt,"unique");function Vo({obj:r,value:e,path:t,pathDelimiter:o,logalot:n}){let s=`[${Vo.name}]`;try{if(n&&console.log(`${s} starting...`),!r)throw new Error("obj required (E: 6a9dd32a361476e80b1bf7b91ec50522)");if(typeof r!="object")throw new Error("obj must be type 'object' (E: 66fdc289b32c06492bd95f5d266e6a22)");if(!t)throw new Error("path required (at the very least should be the key in the root obj.) (E: fc779e7794ead8a0b44e5f2e776b0e22)");o=o||Nt;let i=r,a=t.split(o).filter(l=>!!l),c=a.pop();a.forEach(l=>{let d=i[l];if(d){if(typeof d!="object")throw new Error(`invalid path into object. Each step along the path must be typeof === 'object', but typeof targetObj["${l}"] === ${typeof d}. (value: ${d}) (E: 38cf29c5f624a40b4b56502c2ec39d22)`)}else i[l]={};i=i[l]}),i[c]=e}catch(i){throw console.error(`${s} ${i.message}`),i}finally{n&&console.log(`${s} complete.`)}}f(Vo,"patchObject");async function Yt({n:r}){let e=`[${Yt.name}]`;try{Ct&&console.log(`${e} starting...`);let t=[];for(let o=0;o<r;o++){let n=await F();t.push(n.substring(0,16))}return t}catch(t){throw console.error(`${e} ${t.message}`),t}finally{Ct&&console.log(`${e} complete.`)}}f(Yt,"getIdPool");function pe({text:r,length:e,keepLiterals:t=["-"],replaceMap:o}){let n=`[${pe.name}]`;try{if(Ct&&console.log(`${n} starting... (I: 27437e312e5aa621adfebb84e059c822)`),!r)throw new Error("text required (E: 87e0493613c8b30dfade83e1d2862a22)");let s=r,i={};t=t??[];for(let c=0;c<t.length;c++){let l=t[c],d;do d=xs({count:10});while(d.includes(l)||l.includes(d)||r.includes(d));if(s.includes(l))for(i[d]=l;s.includes(l);)s=s.replace(l,d)}if(o&&Object.keys(o).length>0)for(let c=0;c<Object.keys(o).length;c++){let l=Object.keys(o)[c],d=o[l];for(;s.includes(l);)s=s.replace(l,d)}s=s.replace(/\W/g,"");let a=Object.keys(i);for(let c=0;c<a.length;c++){let l=a[c];for(;s.includes(l);)s=s.replace(l,i[l])}return e&&e>0&&s.length>e&&(Ct&&console.log(`${n} curtailing length (I: d7a28e05daa5979c7686b4c1cf519b23)`),s=s.substring(0,e)),s.length===0&&(s=Gs),s}catch(s){throw console.error(`${n} ${s.message}`),s}finally{Ct&&console.log(`${n} complete.`)}}f(pe,"getSaferSubstring");function Dc({x:r}){if((r??[]).length===0)return;let e=Math.floor(Math.random()*r.length);return r[e]}f(Dc,"pickRandom");function xs({count:r}){let e=`${xs.name}]`;try{if(!Number.isInteger(r))throw new Error("count required to be a number. (E: c0a21d884ebd9afc4b2e8025207e0522)");let t="";for(let o=0;o<r;o++)t+=Dc({x:"a b c d e f g h i j k l m n o p q r s t u v w x y z".split(" ")});if(t.length!==r)throw new Error(`${e} (UNEXPECTED) result.length !== count ? (E: 9bec4ec8f78610d8055e565415392a22)`);return t}catch(t){throw console.error(`${e} ${t.message}`),t}finally{Ct&&console.log(`${e} complete.`)}}f(xs,"pickRandom_Letters");function Pt({dominant:r,recessive:e}){let t=`[${Pt.name}]`;try{if(Array.isArray(r)&&Array.isArray(e)){let o=C(r),n=!1;return e.forEach(s=>{if(typeof s=="string")o.includes(s)||o.push(s);else{n||(console.warn(`${t} merging arrays of non-string elements. (W: d8ab113064834abc8eb5fe6c4cf87ba3)`),n=!0);let i=JSON.stringify(s);o.some(a=>JSON.stringify(a)===i)||o.push(s)}}),o}else if(typeof r=="object"&&typeof e=="object"){let o={...e},n=Object.keys(r),s=Object.keys(e);return n.forEach(i=>{s.includes(i)?Array.isArray(r[i])&&Array.isArray(e[i])?o[i]=Pt({dominant:r[i],recessive:e[i]}):r[i]&&!Array.isArray(r[i])&&typeof r[i]=="object"&&e[i]&&!Array.isArray(e[i])&&typeof e[i]=="object"?o[i]=Pt({dominant:r[i],recessive:e[i]}):o[i]=r[i]:o[i]=r[i]}),o}else return console.warn(`${t} unknown values or value types do not match. Both should either be an array or map. Dominant one wins categorically without any merging. (W: 3690ea19b81a4b89b98c1940637df62c)`),r}catch(o){throw console.error(`${t} ${o.message}`),o}}f(Pt,"mergeMapsOrArrays_Naive");function Oc({array:r,target:e,replacement:t}){let o=`[${Oc.name}]`,n=r.indexOf(e);if(n===-1)throw new Error(`${o} Target string "${e}" not found in the array. (E: a0d8647e3284f2c758f9c5455e863726)`);let s=[...r];return s[n]=t,s}f(Oc,"replaceStringInArray");var Nc=globalThis.crypto,{subtle:Os}=Nc,Ns=new Array(256);for(let r=0;r<256;++r)Ns[r]=r.toString(16).padStart(2,"0");function Cs(r){let e=new Uint8Array(r),t="";for(let o=0;o<e.length;o++)t+=Ns[e[o]];return t}f(Cs,"bufToHex");function zt(r){if(r===null||typeof r!="object")return r;if(Array.isArray(r))return r.map(o=>zt(o));let e={},t=Object.keys(r).sort();for(let o of t){let n=r[o];n!==void 0&&(e[o]=zt(n))}return e}f(zt,"toNormalizedForHashing");async function Wt(r){if(!r)return"";let e=new TextEncoder().encode(r),t=await Os.digest("SHA-256",e);return Cs(t)}f(Wt,"hashToHex");async function Cc(r,e){let t;if(r){let n=new TextEncoder().encode(r);t=new Uint8Array(n.length+e.length),t.set(n),t.set(e,n.length)}else t=e;let o=await Os.digest("SHA-256",t);return Cs(o)}f(Cc,"hashToHex_Uint8Array");var Pc=!1,Sr=0,vs=0;async function Ds(r,e=""){let t=e||"",o=r.ib,n=r.data,s=r.rel8ns,i=Object.keys(s||{}).length>0&&Object.keys(s||{}).some(b=>s[b]&&s[b].length>0),a=!!n;a&&(typeof n=="string"?a=n.length>0:n instanceof Uint8Array?a=!0:typeof n=="object"?a=Object.keys(n||{}).length>0:a=!0);let c=(await Wt(t?t+o:o)).toUpperCase(),l="";if(i){let b=zt(s),p=JSON.stringify(b);l=(await Wt(t?t+p:p)).toUpperCase()}let d="";if(a)if(n instanceof Uint8Array)d=(await Cc(t,n)).toUpperCase();else{let b=zt(n),p=JSON.stringify(b);d=(await Wt(t?t+p:p)).toUpperCase()}let u;if(i||a){let b=c+l+d;u=(await Wt(t?t+b:b)).toUpperCase()}else u=(await Wt(t?t+c:c)).toUpperCase();return u}f(Ds,"sha256v1_Internal");async function Re(r,e=""){if(Pc){let t=globalThis.performance?globalThis.performance.now():Date.now(),o=await Ds(r,e),n=(globalThis.performance?globalThis.performance.now():Date.now())-t;return Sr++,vs+=n,Sr%1e3===0&&console.log(`[sha256v1 Profile] Total Runs: ${Sr} | Average Duration: ${(vs/Sr).toFixed(4)} ms`),o}return Ds(r,e)}f(Re,"sha256v1");function _({ib:r,gib:e,ibGib:t,delimiter:o="^"}){return r=r||t?.ib||"",e=e||t?.gib||"",r+o+e}f(_,"getIbGibAddr");function R({ibGib:r,ibGibAddr:e,delimiter:t="^"}){let o="[getIbAndGib]";if(!e)if(r)e=_({ibGib:r});else throw new Error(`${o} We need either an address or an ibGib object`);if(!e)throw new Error(`${o} Couldn't get ibGibAddr. ibGib invalid?`);t||(t="^");let n=e.split(t);return n.length===2?{ib:n[0],gib:n[1]}:n.length===1&&e.endsWith(t)?{ib:n[0],gib:""}:n.length===1&&e.startsWith(t)?{ib:"",gib:n[0]}:n.length===2&&n[0]===""&&n[1]===""?{ib:t,gib:""}:(console.warn(`${o} multiple delimiters found in ibGibAddr. Considering last delimiter as the demarcation of gib hash`),{ib:n.slice(0,n.length-1).join(t),gib:n.slice(n.length-1)[0]})}f(R,"getIbAndGib");var Y;(function(r){r.past="past",r.ancestor="ancestor",r.dna="dna",r.identity="identity",r.tjp="tjp",r.secret="secret",r.encryption="encryption"})(Y||(Y={}));var Lt="ib",U="gib",Z={ib:Lt,gib:U},oe="^",Ue=".",Ps="ib^gib",Qe=["past","ancestor","dna","tjp"],Lc=155,Ls=new RegExp(`^[\\w\\t\\-|=+.&%$#@!~\` \\[\\]\\(\\)\\{\\}]{1,${Lc}}$`);async function wt(r){let e=C(r),t=`[${wt.name}]`;e.srcAddr&&delete e.srcAddr,delete e.src;let o={ib:e.type,data:e,rel8ns:{ancestor:[`${e.type.toString()}${oe}${U}`]}};return o.gib=await Re(o),o}f(wt,"buildDna");function Rc({ibGib:r}){let e=`[${Rc.name}]`;try{if(!r)throw new Error("ibGib required.");let t=["fork","mut8","rel8","plan"].map(n=>`${n}^${U}`);return r.rel8ns&&r.rel8ns.ancestor&&Array.isArray(r.rel8ns.ancestor)&&r.rel8ns.ancestor.some(n=>t.includes(n))||!1}catch(t){throw console.error(`${e} ${E(t)}`),t}}f(Rc,"isDna");function te({ibGib:r,gib:e}){return r?te({gib:r.gib}):e?e===U:!0}f(te,"isPrimitive");async function V({ibGib:r,hasTjp:e,tjpAddr:t,gibDelimiter:o,isPrimitive:n,hashAlgorithm:s}){let i=`[${V.name}]`;try{if(!r)throw new Error("ibGib required. (E: 17d073226b9d42fd841e5a94b065ef21)");if(n)return U;let a=await Re(r,""),c=r.rel8ns??{},l=r.data??{};if(o=o||Ue,e||(e=(c.tjp??[]).length>0||l.isTjp||!1),e){let d;if(c.tjp)if(c.tjp.length===1)if(c.tjp[0])t=c.tjp[0];else throw new Error("rel8ns.tjp[0] is falsy. (E: ed879d2b039543f8b1902e8b7b5a5a7b)");else if(c.tjp.length>1)if(c.tjp[c.tjp.length-1])console.warn(`${i} found more than one tjp addr...only expecting 1 ATOW. (W: 10ed43f716e743e0afd1954f1ab46789)`),t=c.tjp[c.tjp.length-1];else throw new Error("multiple tjp addrs, and the last (most recent) one is falsy. (E: bc835dc89be24075bba8b2b6616ea069)");else throw new Error("hasTjp is true but rel8ns.tjp is empty array. (E: d08b2f9e86494814b5e7d7b4602b2ab7)");else if(l.isTjp)t=_({ib:r.ib,gib:a});else throw new Error("hasTjp is true, but both ibGib.rel8ns.tjp and ibGib.data.isTjp are falsy. (E: 4e246897e52044789594d853bb5b66ee)");if(d=t?R({ibGibAddr:t}).gib:void 0,d)return l.isTjp?a:`${a}${Ue}${d}`;throw new Error("hasTjp is true but could not find tjpAddrGib. (E: 1863df626b754744a1d431a683cb0ba0)")}else return a}catch(a){throw console.error(`${i} ${E(a)}`),a}}f(V,"getGib");function ne({ibGibAddr:r,gib:e,gibDelimiter:t}){let o=`[${ne.name}]`;try{if(!r&&!e)throw new Error("Either ibGibAddr or gib required. (E: 25e3dcbe63cd44909032df12af9df75e)");if(e=e||R({ibGibAddr:r}).gib,e===U)return{isPrimitive:!0};if(t=t??Ue,e.includes(t)){let n=e.split(t);if(n.some(a=>a===""))throw new Error(`unexpected gib that contains gibDelimiter (${t}) but has at least one piece with empty string. (E: 75a94280045541009ee68182d12d3449)`);let s=n.length;return s>2&&console.warn(`${o} gib only expected to have two pieces ATOW. re-examine please. (W: aa4283ac5a5747a386a69966ecdad39d)`),{punctiliarHash:n.splice(0,1)[0],tjpGib:n.join(t),piecesCount:s,delimiter:t}}else return{punctiliarHash:e,piecesCount:1,delimiter:t}}catch(n){throw console.error(`${o} ${E(n)}`),n}}f(ne,"getGibInfo");async function Gr(r){let{noTimestamp:e,dna:t,linkedRel8ns:o,destIb:n,uuid:s,tjp:i,cloneRel8ns:a,cloneData:c,type:l="fork"}=r,d=r.src,u="[fork_v1]";if(l!=="fork")throw new Error(`${u} not a fork transform.`);if(r.type||(r.type="fork"),!d)throw new Error(`${u} src required to fork.`);if(!d.ib)throw new Error(`${u} src.ib required.`);if(n&&n.includes(oe))throw new Error(`${u} destIb can't contain (hardcoded) delimiter right now.`);if(!d.gib)throw new Error(`${u} src.gib required.`);let b={ib:d.ib,gib:d.gib};d.data&&Object.keys(d.data).length>0&&(b.data=d.data),d.rel8ns&&Object.keys(d.rel8ns).length>0&&(b.rel8ns=d.rel8ns),d=b;let p=_({ib:d.ib,gib:d.gib});r.srcAddr=p;let h=a&&d.rel8ns&&Object.keys(d.rel8ns).length>0?C(d.rel8ns):{};delete h.past;let g=c&&d?.data?C(d.data):{};r.nCounter&&(g.n=0);let m=o?.includes(Y.ancestor)?[p]:(h.ancestor||[]).concat([p]);h.ancestor=m,h.tjp&&delete h.tjp;let $=C(d);if(e&&i?.timestamp)throw new Error(`${u} both noTimestamp and tjp.timestamp selected.`);if(!e||i?.timestamp){let A=new Date;g.timestamp=Ae(A),g.timestampMs=A.getMilliseconds()}(i?.uuid||s)&&(g.uuid=await F()),i?.uuid||i?.timestamp?g.isTjp=!0:g.isTjp&&delete g.isTjp,$.ib=n||"ib",p!==Ps&&($.rel8ns=h),Object.keys(g).length>0&&($.data=g);let w=null;if(t){w=await wt(r);let A=_({ibGib:w});h.dna=o?.includes(Y.dna)?h.dna=[A]:h.dna=(h.dna||[]).concat(A)}$.gib=await Re($,"");let T={newIbGib:$};return w&&(T.dnas=[w]),T}f(Gr,"fork");async function Fe(r){let{noTimestamp:e,dna:t,linkedRel8ns:o,dataToRename:n,dataToRemove:s,dataToAddOrPatch:i,mut8Ib:a,type:c="mut8"}=r,l=r.src,d="[mut8_v1]";if(c!=="mut8")throw new Error(`${d} not a mut8 transform.`);if(r.type||(r.type="mut8"),!l)throw new Error(`${d} src required to mut8.`);if(!l.ib)throw new Error(`${d} src.ib required.`);if(l.ib.includes(oe))throw new Error(`${d} ib can't contain hardcoded delimiter (${oe}) right now.`);if(!l.gib)throw new Error(`${d} src.gib required.`);if(!a&&!n&&!s&&!i)throw new Error(`${d} gotta provide either a mut8Ib or some data to change.`);let u=_({ib:l.ib,gib:l.gib});if(r.srcAddr&&u!==r.srcAddr)throw new Error(`${d} srcAddr from src does not equal opts.srcAddr`);if(r.srcAddr=u,te({ibGib:l}))throw new Error(`${d} cannot mutate primitive ibgib`);let b={ib:l.ib,gib:l.gib};l.data&&Object.keys(l.data).length>0&&(b.data=l.data),l.rel8ns&&Object.keys(l.rel8ns).length>0&&(b.rel8ns=l.rel8ns),l=b;let p=C(l),h=l.rel8ns?l.rel8ns:{},g=C(h);g.past=o?.includes(Y.past)?[u]:(g.past||[]).concat([u]);let m=l?.data?C(l.data):{};if(n&&(m=Xo(m,n,"rename")),s&&(m=Xo(m,s,"remove")),i&&(m=Rs(m,i)),!e){let G=new Date;m.timestamp=Ae(G),m.timestampMs=G.getMilliseconds()}if(r.nCounter||Object.keys(m).includes("n"))if(Object.keys(m).includes("n"))if(Number.isInteger(m.n))m.n>=0?m.n=m.n+1:(console.warn(`${d} data.n is less than 0, which is unexpected. Resetting data.n to 0.`),m.n=0);else throw new Error("cannot increment nCounter because data.n is not a number.");else m.n=0;if(m.isTjp){let G=g.tjp??[];G.push(u),g.tjp=G,delete m.isTjp}let w=null;if(t){w=await wt(r);let G=_({ibGib:w});g.dna=o?.includes(Y.dna)?g.dna=[G]:g.dna=(g.dna||[]).concat(G)}p.ib=a||p.ib,p.rel8ns=g,Object.keys(m).length>0?p.data=m:delete p.data;let T=(g.tjp?.length??0)>0;p.gib=await V({ibGib:p,hasTjp:T});let A={newIbGib:p};return w&&(A.dnas=[w]),A}f(Fe,"mut8");function Xo(r,e,t){let o="[renameOrRemove]",n=["timestamp"];return Object.keys(e).forEach(s=>{if(n.includes(s))throw new Error(`${o} Cannot rename to ${s}.`);if(Object.keys(r).includes(s)){let i=e[s];if(typeof i=="string"){if(n.includes(i))throw new Error(`${o} Cannot rename to ${i}.`);t==="rename"&&(r[i]=r[s]),delete r[s]}else r[s]=Xo(r[s],i,t)}else console.log(`${o} key to ${t} does not exist`)}),r}f(Xo,"renameOrRemove");function Rs(r,e){return Object.keys(e).forEach(t=>{let o=e[t],n=r[t];n?Array.isArray(o)||Array.isArray(n)?r[t]=o:typeof o=="object"&&typeof n=="object"?r[t]=Rs(n,o):r[t]=o:r[t]=o}),r}f(Rs,"patch");async function ye(r){let{noTimestamp:e,dna:t,linkedRel8ns:o,rel8nsToAddByAddr:n,rel8nsToRemoveByAddr:s,rel8nsToReplaceByAddr:i,type:a="rel8"}=r,c=r.src,l="[rel8_v1]";if(a!=="rel8")throw new Error(`${l} not a rel8 transform.`);if(r.type||(r.type="rel8"),a!=="rel8")throw new Error(`${l} not a rel8 transform.`);if(r.type||(r.type="rel8"),!c)throw new Error(`${l} src required.`);if(!c.ib)throw new Error(`${l} src.ib required.`);if(c.ib.includes(oe))throw new Error(`${l} ib can't contain hardcoded delimiter (${oe}) right now.`);if(!c.gib)throw new Error(`${l} src.gib required.`);if(te({ibGib:c}))throw new Error(`${l} cannot relate/unrelate primitive ibgib`);let d=n&&Object.keys(n).length>0,u=s&&Object.keys(s).length>0,b=i&&Object.keys(i).length>0;if(!(d||u||b))throw new Error(`${l} gotta provide relations to add, remove, or replace.`);let p=_({ib:c.ib,gib:c.gib});if(r.srcAddr&&p!==r.srcAddr)throw new Error(`${l} srcAddr from src does not equal opts.srcAddr`);r.srcAddr=p;let h=f(y=>y&&typeof y=="string"&&y.length>=2&&y.includes("^")&&y.split("^")[0].length>=1,"fnValidIbGibAddr");Object.keys(n||{}).map(y=>(n||{})[y]).forEach(y=>{if(!(y&&y.every(I=>h(I))))throw new Error(`${l} Invalid rel8n attempt. Must be valid ibGibs. Did you include a delimiter (^)?`)}),Object.keys(s||{}).map(y=>(s||{})[y]).forEach(y=>{if(!(y&&y.every(I=>h(I))))throw new Error(`${l} Invalid remove rel8n attempt. Must be valid ibGibs. Did you include a delimiter (^)?`)}),Object.keys(i||{}).map(y=>(i||{})[y]).forEach(y=>{if(!(y&&y.every(I=>I&&h(I.oldAddr)&&h(I.newAddr))))throw new Error(`${l} Invalid replace rel8n attempt. Must be valid ibGibs with oldAddr and newAddr. Did you include a delimiter (^)?`)});let g={ib:c.ib,gib:c.gib};c.data&&Object.keys(c.data).length>0&&(g.data=c.data),c.rel8ns&&Object.keys(c.rel8ns).length>0&&(g.rel8ns=c.rel8ns),c=g;let m=C(c),$=C(c.data||{});if(r.nCounter||Object.keys($).includes("n"))if(Object.keys($).includes("n"))if(Number.isInteger($.n))$.n>=0?$.n=$.n+1:(console.warn(`${l} data.n is less than 0, which is unexpected. Resetting data.n to 0.`),$.n=0);else throw new Error("cannot increment nCounter because data.n is not a number.");else $.n=0;if(!e){let y=new Date;$.timestamp=Ae(y),$.timestampMs=y.getMilliseconds()}let w=C(c.rel8ns||{});if(Object.keys(i||{}).forEach(y=>{if(Qe.includes(y))throw new Error(`${l} Cannot manually replace relationship: ${y}.`);let I=w[y]||[],v=i[y]||[],N=[...I];for(let x of v){let{oldAddr:P,newAddr:D}=x,L=!1;for(let K=0;K<N.length;K++)N[K]===P&&(N[K]=D,L=!0);if(!L)throw new Error(`${l} Cannot replace oldAddr '${P}' in rel8n '${y}' - oldAddr not found in existing relationships.`)}w[y]=N}),Object.keys(n||{}).forEach(y=>{if(Qe.includes(y))throw new Error(`${l} Cannot manually add relationship: ${y}.`);let I=w[y]||[],N=n[y].filter(x=>!I.includes(x));w[y]=I.concat(N)}),Object.keys(s||{}).forEach(y=>{if(Qe.includes(y))throw new Error(`${l} Cannot manually remove relationship: ${y}.`);let I=w[y]||[],v=s[y]||[],N=I.filter(x=>!v.includes(x));N.length>0?w[y]=N:delete w[y]}),w.past=(w.past||[]).concat([p]),(o||[]).filter(y=>Object.keys(w).includes(y)).filter(y=>(w[y]||[]).length>1).forEach(y=>{let I=w[y].length;w[y]=[w[y][I-1]]}),$.isTjp){let y=w.tjp||[];y.push(p),w.tjp=y,delete $.isTjp}m.data=$,m.rel8ns=w;let T=(w.tjp?.length??0)>0,A=null;if(t){A=await wt(r);let y=_({ibGib:A});w.dna=o?.includes(Y.dna)?w.dna=[y]:w.dna=(w.dna||[]).concat(y)}m.gib=await V({ibGib:m,hasTjp:T});let G={newIbGib:m};return A&&(G.dnas=[A]),G}f(ye,"rel8");function xr({ibGib:r}){let e=`[${xr.name}]`;if(!r)return console.warn(`${e} ibGib falsy. (W: 884178562f5b4f15933ac4d98db74cc6)`),!1;if(r.data?.isTjp||r.rel8ns?.tjp?.length>0)return!0;let t=["fork^gib","mut8^gib","rel8^gib"];return(r.rel8ns?.ancestor??[]).some(n=>t.includes(n))?!1:r.gib?r.gib.includes(Ue)?!0:r.gib===U?!1:!!ne({ibGibAddr:_({ibGib:r})}).tjpGib:(console.warn(`${e} ibGib.gib falsy. (W: 6400d780822b44d992846f1196509be3)`),!1)}f(xr,"hasTjp");function vr({ibGib:r}){let e=`[${vr.name}]`;r.ib||console.warn(`${e} ibGib.ib is falsy. (W: e60e41c2a1fc48268379d88ce13cb77b)`),r.gib||console.warn(`${e} ibGib.gib is falsy. (W: fb3889cbf0684ae4ac51e48f28570377)`);let t={ib:(r.ib||"").slice()};return r.gib&&(t.gib=r.gib.slice()),r.data&&(t.data=r.data instanceof Uint8Array?r.data:C(r.data)),r.rel8ns&&(t.rel8ns=C(r.rel8ns)),t}f(vr,"toDto");var Yo=!1;async function se({ibGib:r}){let e=`[${se.name}]`;try{let t=[];if(r){let o=_({ibGib:r});if(t=tt({addr:o})??[],t.length>0)return console.error(`${e} errors found in addr: ${o}`),t;if(te({gib:r.gib}))return null;let n=await V({ibGib:vr({ibGib:r}),hasTjp:xr({ibGib:r})});return n!==r.gib&&(r.data?.src&&r.data.srcAddr&&r.ib==="rel8"?(delete r.data.src,delete r.data.srcAddr,n=await V({ibGib:vr({ibGib:r}),hasTjp:xr({ibGib:r})}),n!==r.gib&&t.push(`Ibgib invalid intrinsically - gottenGib (${n}) does not equal ibGib.gib (${r.gib}). (E: 020b71479e944b2198fe436e7e137786)`)):t.push(`Ibgib invalid intrinsically - gottenGib (${n}) does not equal ibGib.gib (${r.gib}). (E: 7416db016878430ca3c5b20697f164ed)`)),t.length>0?t:null}else return t.push("ibGib is itself falsy. (E: 4fb98caf6ed24ef7b35a19cef56e2d7e)"),t}catch(t){throw console.error(`${e} ${E(t)}`),t}}f(se,"validateIbGibIntrinsically");function tt({addr:r,delimiter:e,version:t}){let o=`[${tt.name}]`;try{let n=[];if(t&&console.warn(`${o} version not implemented yet. Ignoring. (W: 2d19db16ec0c4766b5d35248787671f3)`),!r)return n.push("addr required. (E: e9a54041aa0b41c1bb2324d9d2d42c7f)"),n;e=e||oe,r.includes(e)||n.push(`No delimiter (${e}) found. (E: 05e28dcb70ff44019edc53ed508bd1e8)`),r.startsWith(e)&&n.push("addr starts with delim. (E: d29f808c5a47452f9bb3ea684694c6eb)");let{ib:s,gib:i}=R({ibGibAddr:r,delimiter:e}),a=rt({ib:s,ibGibAddrDelimiter:e,version:t});a&&(n=n.concat(a));let c=et({gib:i,ibGibAddrDelimiter:e,version:t});return c&&(n=n.concat(c)),n.length>0&&Yo&&console.log(`${o} errors.length > 0. errors: ${n.join("|")} (I: 9c18f993e138f15613e4c6a340d41722)`),n.length>0?n:null}catch(n){throw console.error(`${o} ${E(n)}`),n}}f(tt,"validateIbGibAddr");function rt({ib:r,ibGibAddrDelimiter:e,version:t}){let o=`[${rt.name}]`;try{let n=[];return t&&console.warn(`${o} version not implemented yet. Ignoring. (W: 71228ba4ed994aaa8149910e295ab087)`),r?r===Lt?null:(e=e||oe,r.includes(e)&&n.push(`ib contains ibGibAddrDelimiter (${e}) (E: 09e61b46c3e84874bc02b6918f1f2c39)`),n.length>0?n:null):(n.push("ib required. (E: a76d06c7b9c24db3a731a91dbe46acd5)"),n)}catch(n){throw console.error(`${o} ${E(n)}`),n}}f(rt,"validateIb");function et({gib:r,gibDelimiter:e,ibGibAddrDelimiter:t,version:o}){let n=`[${et.name}]`;try{let s=[];if(o&&console.warn(`${n} version not implemented yet. Ignoring. (E: 90ced1db69774702b92acb261bdaee23)`),!r)return s.push("gib required. (E: e217de4035b04086827199f4bace189c)"),s;t=t||oe;let i=[t],a=[];i.forEach(p=>{r.includes(p)&&a.push(p)}),a.length>0&&s.push(`gib (${r}}) contains invalid characters: (${JSON.stringify(a.join(","))}) (E: 1e584258d9e049ba9ce7e516f3ab97f1)`);let{punctiliarHash:c,tjpGib:l,isPrimitive:d}=ne({gib:r,gibDelimiter:e||Ue});if(d)return null;if(!c)throw new Error(`${n} punctiliarHash is falsy on a non-primitive gib. (E: 72835394918241bdb2632bf0510bdae5)`);let u=c.match(As),b=c.match(Ss);if(!u&&!b&&s.push("gib punctiliar hash is neither a 32- or 64-char hash string. (E: d47ff6d6e14b4c02a62107090c8dad39)"),l){let p=et({gib:l});(p??[]).length>0&&s.push(`tjpGib has errors (E: d6b79228d4a64c0b967cdb0efcea4d0d). tjpGibValidationErrors: ${p.join(". ")}`)}return s.length>0?s:null}catch(s){throw console.error(`${n} ${E(s)}`),s}}f(et,"validateGib");function Wo({rel8ns:r}){let e=`[${Wo.name}]`;try{Yo&&console.log(`${e} starting... (I: 62b4722599798dd8ab95fcebf42c0e23)`);let t=[],o=Object.keys(r);for(let n=0;n<o.length;n++){let s=Object.keys(r)[n];typeof s!="string"&&t.push("non-string rel8nName found. all keys of rel8ns must be of type string. (E: 3b2e4582b638421681951f5475c85178)");let i=r[s]??[];for(let a=0;a<i.length;a++){let c=i[a],l=tt({addr:c})??[];l.length>0&&t.push(`invalid addr found for rel8nName (${s}). addr errors: ${l.join("|")} (E: 56809a746c4f462db426e90395b80364)`)}}return t.length>0?t:null}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Yo&&console.log(`${e} complete.`)}}f(Wo,"validateRel8nsIntrinsically");var Us=!1,k=class r{static{f(this,"Factory_V1")}static root(){return r.primitive({ib:Lt})}static primitive({ib:e}){return{ib:e,gib:U}}static primitives({ibs:e}){return e.map(t=>r.primitive({ib:t}))}static async firstGen({ib:e=Lt,parentIbGib:t=r.root(),data:o,rel8ns:n,dna:s,tjp:i,linkedRel8ns:a,noTimestamp:c,nCounter:l,squash:d}){let u=`[${r.name}][${r.firstGen.name}]`;try{if(Us&&console.log(`${u} starting... (I: b7152fbd94382516d9f7c591bcf4c326)`),s&&d)throw new Error("both dna and squash cannot be true. Squash requires that no dna exist. (E: abfc58b4a4c8654924aa5428d0831826)");let b=[],p=t||Z,h=await Gr({src:p,destIb:e,tjp:i,dna:s,linkedRel8ns:a,noTimestamp:c,nCounter:l});if(b.push(h),p=h.newIbGib,o){let g=await Fe({src:p,dataToAddOrPatch:o,dna:s,linkedRel8ns:a,noTimestamp:c,nCounter:l});b.push(g),p=g.newIbGib}if(n){let g=await ye({src:p,rel8nsToAddByAddr:n,dna:s,linkedRel8ns:a,noTimestamp:c,nCounter:l});b.push(g)}if(b.length>1){let g=b.slice(b.length-1)[0].newIbGib,m={newIbGib:g,intermediateIbGibs:b.slice(0,b.length-1).map($=>$.newIbGib)};if(s){d&&`${u}`;let $=[];return b.forEach(w=>{$=$.concat(w.dnas)}),m.dnas=$,m}else if(d){if(!g.rel8ns)throw new Error("(UNEXPECTED) newIbGib.rel8ns is falsy? (E: 6b09e8057fc5b00c6cfd13be60e97f26)");return delete g.rel8ns.past,g.rel8ns.tjp&&(delete g.rel8ns.tjp,g.data??={},g.data.isTjp=!0),l&&(g.data??={},g.data.n=0),g.gib=await V({ibGib:g}),{newIbGib:g}}else return m}else{if(b.length===1)return b[0];throw new Error("(UNEXPECTED) interimResults.length is not 1 and not greater than 1? 0? But we had to fork? (E: a256c88c56916a46a888796f76ef4826)")}}catch(b){throw console.error(`${u} ${E(b)}`),b}finally{Us&&console.log(`${u} complete.`)}}static async stone({parentPrimitiveIb:e,ib:t,ibRegExpPattern:o,data:n,rel8ns:s,noTimestamp:i,uuid:a}){let c=`[${r.name}][${r.stone.name}]`;try{if(!e)throw new Error("parentPrimitiveIb required. (E: genuuid)");if(rt({ib:e})!==null)throw new Error(`Invalid parentPrimitiveIb: ${e}. (E: genuuid)`);if(!t)throw new Error("ib required. (E: genuuid)");let l=o?new RegExp(o):Ls;if(!t.match(l))throw new Error(`invalid ib. does not match regexp (${l}) (E: genuuid)`);let d=Object.keys(s??{}),u=[...Qe,"tjp"];if(d.some(g=>u.includes(g)))throw new Error(`Invalid rel8ns. forbiddenRel8nNames: ${u}. rel8ns keys: ${Object.keys(s??{})}. (E: genuuid)`);let h=(await r.firstGen({ib:t,parentIbGib:r.primitive({ib:e}),data:n,rel8ns:s,dna:!1,noTimestamp:i,nCounter:!1})).newIbGib;return a&&(h.data||(h.data={}),h.data.uuid=await F()),h.rel8ns?.past&&delete h.rel8ns.past,h.rel8ns?.tjp&&delete h.rel8ns.tjp,h.gib=await V({ibGib:{ib:h.ib,data:h.data,rel8ns:h.rel8ns},hasTjp:!1}),h}catch(l){throw console.error(`${c} ${l.message}`),l}}static async constant({parentPrimitiveIb:e,ib:t,ibRegExpPattern:o,data:n,rel8ns:s}){let i=`[${r.name}][${r.constant.name}]`;try{return await r.stone({parentPrimitiveIb:e,ib:t,ibRegExpPattern:o,data:n,rel8ns:s,noTimestamp:!0,uuid:!1})}catch(a){throw console.error(`${i} ${a.message}`),a}}};var Xf="[core^gib timer]";var zo=`.'",!?-`;var ks=new RegExp("^[\\w\\t\\-|=+.&%$#@!~` \\[\\]\\(\\)\\{\\}]{1,155}$");var Yf=/^[a-zA-Z0-9_\-.]{1,255}$/,Wf=/^[a-zA-Z0-9_\-.\s👀🤖:;&]{1,64}$/;var Dr={tags:"tags",aliases:"aliases",roots:"roots",outerspaces:"outerspaces",secrets:"secrets",encryptions:"encryptions",autosyncs:"autosyncs",robbots:"robbots",apps:"apps",history:"history"};var Uc="robbot";var Ms="zero",Bs="zerospace";var fb=!1,bb="This is a local space. There are many like it, but this one is mine.";var ub=/^[a-zA-Z][\w\-]{0,62}[a-zA-Z]$/,kc="syncSpace";var pb=3e4;var Or="space";var hb="0",js="space_lock",Fs=100,qs=100,gb=60*2,Nr=30;var Jo="root",Zo="x",Hs="root",Qo="analytics-outline",en='This is a root ibgib, which is basically like a root folder that is primarily responsible for "containing" other ibgibs.';var tn="tag",Mc="target";var Ks="pricetag-outline",Vs="This is a tag used for organizing data.";var Tb="always",Xs="archive",Ys="trash";var rn=/^\w{1,32}$/,Cr="Invalid Date";var on={ib:"true",gib:U};var Ws={ib:"false",gib:U};var zs="config_key",Pr=/^v:(\d+)\^spaceId:([^^]+)\^(.+)$/;var Jt=/^[a-zA-Z0-9_\-.]{1,32}$/,Lr="app";var ot=`bootstrap^${U}`,De="defaultSpaceId",Rr="spaceIds";var ke={prependPerHash:"prependPerHash",appendPerHash:"appendPerHash",initialPrepend:"initialPrepend",initialAppend:"initialAppend"},nt=Object.values(ke),Ie={sha_256:"SHA-256",sha_512:"SHA-512"},Ob=Object.values(Ie),Bc={indexOf:"indexOf",lastIndexOf:"lastIndexOf"},qe=Object.values(Bc);function Zt(r){let e=`[${Zt.name}]`;return new Promise((t,o)=>{try{let n=Js(r),s=Zs(n);t(s)}catch(n){console.error(`${e} ${E(n)}`),o(n)}})}f(Zt,"encodeStringToHexString");function Js(r){let e=`[${Js.name}]`;try{return new TextEncoder().encode(r)}catch(t){throw console.error(`${e} ${E(t)}`),t}}f(Js,"stringToUTF8Bytes");function Zs(r){let e=`[${Zs.name}]`;try{return Array.from(r,t=>t.toString(16).padStart(2,"0")).join("")}catch(t){throw console.error(`${e} ${E(t)}`),t}}f(Zs,"bytesToHexString");function He(r){let e=`[${He.name}]`;return new Promise((t,o)=>{try{let n=Qs(r),s=ei(n);t(s)}catch(n){console.error(`${e} ${E(n)}`),o(n)}})}f(He,"decodeHexStringToString");function Qs(r){let e=`[${Qs.name}]`;try{if(r.length%2!==0)throw new Error("invalid hex string. length %2 !== 0");let t=r.length/2,o=new Uint8Array(t);for(let n=0;n<t;n++)o[n]=parseInt(r.substr(n*2,2),16);return o}catch(t){throw console.error(`${e} ${E(t)}`),t}}f(Qs,"hexStringToBytes");function ei(r){let e=`[${ei.name}]`;try{return new TextDecoder().decode(r)}catch(t){throw console.error(`${e} ${E(t)}`),t}}f(ei,"utf8BytesToString");var Ke=ke.appendPerHash,Ve="SHA-512",Xe=1024,Me=2e4,Ye=1,ti="indexOf",Ur="lastIndexOf",kr=5e6,Mr=4,st=",";function jc({secret:r,prevHash:e,salt:t,saltStrategy:o}){if(!(e||r))throw new Error("Either secret or prevHash is required, but both are falsy (E: bee2849729ff410081d963777dcedb49))");switch(o){case ke.prependPerHash:return t+(e||r);case ke.appendPerHash:return(e||r)+t;case ke.initialPrepend:return e||t+r;case ke.initialAppend:return e||r+t;default:throw new Error(`Unknown saltStrategy: ${o} (E: 235136af1a6c40eb9c17b2ca41c08a01)`)}}f(jc,"getPreHash");async function Se({secret:r,prevHash:e,count:t,salt:o,saltStrategy:n,hashAlgorithm:s}){let i=`[${Se.name}]`;try{let a=e||void 0;for(let c=0;c<t;c++){let l=jc({secret:r,prevHash:a,salt:o,saltStrategy:n});a=await X({s:l,algorithm:s})}if(!a)throw new Error("hash was not created (E: 09dfdfd644734727a34a1bc0bd8e93b9)");return a}catch(a){throw console.error(`${i} ${E(a)}`),a}}f(Se,"execRound_getNextHash");async function We({secret:r,initialRecursions:e,salt:t,saltStrategy:o,hashAlgorithm:n}){let s=`[${We.name}]`;try{return await Se({secret:r,count:e,salt:t,saltStrategy:o,hashAlgorithm:n})}catch(i){throw console.error(`${s} ${E(i)}`),i}}f(We,"doInitialRecursions_keystretch");async function nn({hexEncodedData:r,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,secret:s,hashAlgorithm:i,encryptedDataDelimiter:a,indexingMode:c}){let l=`[${nn.name}]`;try{let d=await We({secret:s,initialRecursions:e,salt:o,saltStrategy:n,hashAlgorithm:i}),u=c==="indexOf"?(h,g)=>h.indexOf(g):(h,g)=>h.lastIndexOf(g),b=[];for(let h=0;h<r.length;h++){let g=r[h],m="",$;for(;!m.includes(g);)$=await Se({count:t,prevHash:d,salt:o,saltStrategy:n,hashAlgorithm:i}),m+=$,d=$;let w=u(m,g);b.push(w)}return b.join(a)}catch(d){throw console.error(`${l} ${E(d)}`),d}}f(nn,"encryptFromHex_stream");async function sn({encryptedData:r,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,secret:s,hashAlgorithm:i,encryptedDataDelimiter:a}){let c=`[${sn.name}]`;try{let l=await We({secret:s,initialRecursions:e,salt:o,saltStrategy:n,hashAlgorithm:i}),d=r.split(a).map(p=>parseInt(p)),u=[];for(let p=0;p<d.length;p++){let h=d[p],g="",m;for(;h>=g.length;)m=await Se({count:t,prevHash:l,salt:o,saltStrategy:n,hashAlgorithm:i}),g+=m,l=m;let $=g[h];u.push($)}return u.join("")}catch(l){throw console.error(`${c} ${E(l)}`),l}}f(sn,"decryptToHex_stream");async function Qt({encryptedData:r,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,secret:s,hashAlgorithm:i,encryptedDataDelimiter:a}){let c=`[${Qt.name}]`,l=[],d=[];e=e||Me,t=t||Ye,n=n||Ke,i=i||Ve,o=o||await F(Xe),a=a||st;let u="[validation]";if(!e||e<1){let h=`${u} initialRecursions required, and greater than 0`;console.error(h),l.push(h)}if(!t||t<1){let h=`${u} recursionsPerHash required, and greater than 0`;console.error(h),l.push(h)}if(!r){let h=`${u} encryptedData required`;console.error(h),l.push(h)}if(!o){let h=`${u} salt required`;console.error(h),l.push(h)}if(!n){let h=`${u} saltStrategy required`;console.error(h),l.push(h)}if(!s){let h=`${u} secret required`;console.error(h),l.push(h)}if(!a){let h=`${u} encryptedDataDelimiter required`;console.error(h),l.push(h)}if(!Object.values(Ie).includes(i)){let h=`${u} only ${Object.values(Ie)} hash algorithms implemented`;console.error(h),l.push(h)}if(n&&!nt.includes(n)){let h=`${u} unknown saltStrategy: ${n}`;console.error(h),l.push(h)}if(l.length>0)return{errors:l,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,hashAlgorithm:i,encryptedDataDelimiter:a};let b=await sn({encryptedData:r,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,secret:s,hashAlgorithm:i,encryptedDataDelimiter:a});return{decryptedData:await He(b),initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,hashAlgorithm:i,encryptedDataDelimiter:a,warnings:d.length>0?d:void 0}}f(Qt,"decryptImpl_stream");async function an({dataToEncrypt:r,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,secret:s,hashAlgorithm:i,encryptedDataDelimiter:a,confirm:c,indexingMode:l}){let d=`[${an.name}]`,u=[],b=[];e||(console.warn(`${d} initial recursions required. defaulting to ${Me}`),e=Me),t=t||Ye,n=n||Ke,i=i||Ve,o=o||await F(Xe),a=a||st,l=l||ti;let p="[validation]";if(!e||e<1){let m=`${p} initialRecursions required, and greater than 0`;console.error(m),u.push(m)}if(!t||t<1){let m=`${p} recursionsPerHash required, and greater than 0`;console.error(m),u.push(m)}if(!r){let m=`${p} dataToEncrypt required`;console.error(m),u.push(m)}if(!o){let m=`${p} salt required`;console.error(m),u.push(m)}if(!n){let m=`${p} saltStrategy required`;console.error(m),u.push(m)}if(!s){let m=`${p} secret required`;console.error(m),u.push(m)}if(!a){let m=`${p} encryptedDataDelimiter required`;console.error(m),u.push(m)}if(!qe.includes(l)){let m=`${p} invalid indexingMode (${l}). Must be one of ${qe} (E: 5955c46755434982982823c97adcf076)`;console.error(m),u.push(m)}if(!Object.values(Ie).includes(i)){let m=`${p} only ${Object.values(Ie)} hash algorithms implemented`;console.error(m),u.push(m)}if(n&&!nt.includes(n)){let m=`${p} unknown saltStrategy: ${n}`;console.error(m),u.push(m)}if(u.length>0)return{errors:u,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,hashAlgorithm:i,encryptedDataDelimiter:a};let h=await Zt(r);if(c&&await He(h)!==r)throw new Error("decoding encoded hex failed for this data: The encoded hex did not reverse to the original data.");let g=await nn({hexEncodedData:h,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,secret:s,hashAlgorithm:i,encryptedDataDelimiter:a,indexingMode:"indexOf"});if(c){let m=await Qt({encryptedData:g,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,secret:s,hashAlgorithm:i,encryptedDataDelimiter:a});if((m.errors||[]).length>0)return{errors:["Confirm check found that decrypt had errors.",...m.errors],initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,hashAlgorithm:i,encryptedDataDelimiter:a};if(m.decryptedData){if(m.decryptedData!==r)throw new Error("The ENCRYPTED data did not decrypt back to the original data.")}else throw new Error("Confirm check call to decrypt produced falsy decryptedData");(m.warnings||[]).length>0&&(b=b.concat(["Confirm check call to decrypt had warnings.",...m.warnings]))}return{encryptedData:g,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,hashAlgorithm:i,encryptedDataDelimiter:a,warnings:b.length>0?b:void 0}}f(an,"encryptImpl_stream");async function cn({hexEncodedData:r,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,secret:s,hashAlgorithm:i,encryptedDataDelimiter:a,indexingMode:c,maxBlockSize:l,numOfPasses:d}){let u=`[${cn.name}]`;try{let b=await We({secret:s,initialRecursions:e,salt:o,saltStrategy:n,hashAlgorithm:i}),p=c==="indexOf"?(G,y)=>G.indexOf(y):(G,y)=>G.lastIndexOf(y),h=[],g=r.length,m=l;m>g&&(m=g);let $=Math.ceil(g/m),w=g%m||m,T=0;for(let G=0;G<$;G++){G===$-1&&(m=w);let I=await ri({blockSize:m,indexHexEncodedDataAtStartOfPass:T,numOfPasses:d,hexEncodedData:r,recursionsPerHash:t,salt:o,saltStrategy:n,prevHash:b,hashAlgorithm:i}),v=I.alphabetsThisBlock;b=I.prevHash;let N=await oi({alphabetsThisBlock:v,blockSize:m,indexHexEncodedDataAtStartOfPass:T,hexEncodedData:r,getIndexOfCharInAlphabet:p});h=h.concat(N),T+=m}return h.join(a)}catch(b){throw console.error(`${u} ${E(b)}`),b}}f(cn,"encryptFromHex_blockMode");async function ri({blockSize:r,numOfPasses:e,indexHexEncodedDataAtStartOfPass:t,hexEncodedData:o,recursionsPerHash:n,salt:s,saltStrategy:i,prevHash:a,hashAlgorithm:c}){let l=`[${ri.name}]`;try{let d=[],u,b;for(let p=0;p<e;p++)for(let h=0;h<r;h++){u=t+h;let g=d[h]??"";b=await Se({count:n,prevHash:a,salt:s,saltStrategy:i,hashAlgorithm:c}),g+=b,a=b,d[h]=g}for(let p=0;p<r;p++){u=t+p;let h=o[u],g=d[p];for(;!g.includes(h);)b=await Se({count:n,prevHash:a,salt:s,saltStrategy:i,hashAlgorithm:c}),g+=b,a=b;d[p]=g}return{alphabetsThisBlock:d,prevHash:a}}catch(d){throw console.error(`${l} error: ${E(d)}`),d}}f(ri,"getAlphabetsThisBlock");async function oi({alphabetsThisBlock:r,blockSize:e,indexHexEncodedDataAtStartOfPass:t,hexEncodedData:o,getIndexOfCharInAlphabet:n}){let s=`[${oi.name}]`;try{let i=[];for(let a=0;a<e;a++){let c=t+a,l=r[a],d=n(l,o[c]);i.push(d)}return i}catch(i){throw console.error(`${s} ${E(i)}`),i}}f(oi,"getEncryptedIndexesThisBlock");async function ln({encryptedData:r,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,secret:s,hashAlgorithm:i,encryptedDataDelimiter:a,maxBlockSize:c,numOfPasses:l}){let d=`[${ln.name}]`;try{let u=await We({secret:s,initialRecursions:e,salt:o,saltStrategy:n,hashAlgorithm:i}),b=r.split(a).map(A=>parseInt(A)),p=[],h=b.length,g=c;g>h&&(g=h);let m=Math.ceil(h/g),$=h%g||g,w=0;for(let A=0;A<m;A++){A===m-1&&(g=$);let y=await ni({blockSize:g,indexEncryptedDataIndexesAtStartOfPass:w,numOfPasses:l,encryptedDataIndexes:b,recursionsPerHash:t,salt:o,saltStrategy:n,prevHash:u,hashAlgorithm:i}),I=y.alphabetsThisBlock;u=y.prevHash;let v=await si({alphabetsThisBlock:I,blockSize:g,indexEncryptedDataIndexesAtStartOfPass:w,encryptedDataIndexes:b});p=p.concat(v),w+=g}return p.join("")}catch(u){throw console.error(`${d} ${E(u)}`),u}}f(ln,"decryptToHex_blockMode");async function ni({blockSize:r,numOfPasses:e,indexEncryptedDataIndexesAtStartOfPass:t,encryptedDataIndexes:o,recursionsPerHash:n,salt:s,saltStrategy:i,prevHash:a,hashAlgorithm:c}){let l=`[${ni.name}]`;try{let d=[],u,b;for(let p=0;p<e;p++)for(let h=0;h<r;h++){u=t+h;let g=d[h]??"";b=await Se({count:n,prevHash:a,salt:s,saltStrategy:i,hashAlgorithm:c}),g+=b,a=b,d[h]=g}for(let p=0;p<r;p++){u=t+p;let h=o[u],g=d[p];for(;g.at(h)===void 0;)b=await Se({count:n,prevHash:a,salt:s,saltStrategy:i,hashAlgorithm:c}),g+=b,a=b;d[p]=g}return{alphabetsThisBlock:d,prevHash:a}}catch(d){throw console.error(`${l} error: ${E(d)}`),d}}f(ni,"getAlphabetsThisBlock");async function si({alphabetsThisBlock:r,blockSize:e,indexEncryptedDataIndexesAtStartOfPass:t,encryptedDataIndexes:o}){let n=`[${si.name}]`;try{let s=[];for(let i=0;i<e;i++){let a=t+i,c=o[a],d=r[i][c];s.push(d)}return s}catch(s){throw console.error(`${n} ${E(s)}`),s}}f(si,"getDecryptedDataArrayThisBlock");async function er(r){let e=`[${er.name}]`,{encryptedData:t,initialRecursions:o,recursionsPerHash:n,salt:s,saltStrategy:i,secret:a,hashAlgorithm:c,encryptedDataDelimiter:l,indexingMode:d,blockMode:u,multipass:b}=r,p=[],h=[];if(u&&b)throw new Error("blockMode and multipass set. blockMode was a refactored name of multipass, so these should not both be present. multipass is deprecated. (E: b9b3cd1f701c700835c0419260278223)");if(!u&&b&&(console.warn(`${e}[WARNING] "multipass" option is deprecated. this has been refactored to "blockMode". This will use multipass as blockMode. (W: b77c9773e30549cbb389ce61f31eb6d3)`),u=b),!u)throw new Error("(UNEXPECTED) blockMode required. This should be truthy in order to get to this impl fn. (E: 306bce36afd64b7182ca2b46ac04a261)");o=o||Me,n=n||Ye,i=i||Ke,c=c||Ve,s=s||await F(Xe),l=l||st,d=d||Ur;let{maxBlockSize:g,maxPassSectionLength:m,numOfPasses:$}=u;!g&&m&&(console.warn(`${e}[WARNING] "maxPassSectionLength" option is deprecated. this has been refactored to "maxBlockSize". This will use maxPassSectioLength as maxBlockSize. (W: e2c83d78a3464704a6067e0f767f20b0)`),g=m),g=g||kr,$=$||Mr;let w="[validation]";if(!o||o<1){let y=`${w} initialRecursions required, and greater than 0`;console.error(y),p.push(y)}if(!n||n<1){let y=`${w} recursionsPerHash required, and greater than 0`;console.error(y),p.push(y)}if(!t){let y=`${w} encryptedData required`;console.error(y),p.push(y)}if(!s){let y=`${w} salt required`;console.error(y),p.push(y)}if(!i){let y=`${w} saltStrategy required`;console.error(y),p.push(y)}if(!a){let y=`${w} secret required`;console.error(y),p.push(y)}if(!l){let y=`${w} encryptedDataDelimiter required`;console.error(y),p.push(y)}if(!d){let y=`${w} indexingMode required (E: a6fe15f8ba414e21b5355d23e808b976)`;console.error(y),p.push(y)}if(!qe.includes(d)){let y=`${w} invalid indexingMode (${d}). Must be one of ${qe} (E: 17435268651444e0b7a594135635fc58)`;console.error(y),p.push(y)}if(g<1){let y=`${w} maxBlockSize must be greater than 0 (E: 0870831aa86b4bfa939aeee9f252326a)`;console.error(y),p.push(y)}if($<1){let y=`${w} numOfPasses must be greater than 0 (E: 691d3c3765584c6f8c9aba1ee378df00)`;console.error(y),p.push(y)}if(!Object.values(Ie).includes(c)){let y=`${w} only ${Object.values(Ie)} hash algorithms implemented`;console.error(y),p.push(y)}if(i&&!nt.includes(i)){let y=`${w} unknown saltStrategy: ${i}`;console.error(y),p.push(y)}if(p.length>0){let y={...r,errors:p};return delete y.encryptedData,delete y.secret,y}let T=await ln({encryptedData:t,initialRecursions:o,recursionsPerHash:n,salt:s,saltStrategy:i,secret:a,hashAlgorithm:c,encryptedDataDelimiter:l,maxBlockSize:g,numOfPasses:$}),A=await He(T),G={...r,decryptedData:A,warnings:h.length>0?h:void 0};return delete G.encryptedData,delete G.secret,G}f(er,"decryptImpl_blockMode");async function dn(r){let e=`[${dn.name}]`,{dataToEncrypt:t,initialRecursions:o,recursionsPerHash:n,salt:s,saltStrategy:i,secret:a,hashAlgorithm:c,encryptedDataDelimiter:l,confirm:d,indexingMode:u,blockMode:b,multipass:p}=r,h=[],g=[];if(b&&p)throw new Error("blockMode and multipass set. blockMode was a refactored name of multipass, so these should not both be present. multipass is deprecated. (E: bde5efd1a3e449dca549c5bff147f09b)");if(!b&&p&&(console.warn(`${e}[WARNING] "multipass" option is deprecated. this has been refactored to "blockMode". This will use multipass as blockMode. (W: 046b55a6d1304155b2e5352a9e6140b0)`),b=p),!b)throw new Error("(UNEXPECTED) blockMode required. This should be truthy in order to get to this impl fn. (E: 0b87871f81d849ef8f0263b7775bd3e3)");o||(console.warn(`${e} initial recursions required. defaulting to ${Me}`),o=Me),l=l||st,u=u||Ur;let{maxBlockSize:m,maxPassSectionLength:$,numOfPasses:w}=b;!m&&$&&(console.warn(`${e}[WARNING] "maxPassSectionLength" option is deprecated. this has been refactored to "maxBlockSize". This will use maxPassSectioLength as maxBlockSize. (W: c28fe476105643e184d0ddd5d2aa8a5d)`),m=$),m=m||kr,w=w||Mr;let T="[validation]";if(!o||o<1){let I=`${T} initialRecursions required, and greater than 0 (E: dd96a75f0c504f34b1f9f2f32e011c50)`;console.error(I),h.push(I)}if(!n||n<1){let I=`${T} recursionsPerHash required, and greater than 0 (E: 64cf53e0bf9f4963be6b165ca4e6566d)`;console.error(I),h.push(I)}if(!s){let I=`${T} salt required (E: 136a5d237e0f4b1d89f8c87ac12a1507)`;console.error(I),h.push(I)}if(!i){let I=`${T} saltStrategy required (E: 457ed117bf224b9f86fe81ab6bc35381)`;console.error(I),h.push(I)}if(!a){let I=`${T} secret required (E: 5c363255055a45cfb07656e2f4854ed7)`;console.error(I),h.push(I)}if(!l){let I=`${T} encryptedDataDelimiter required (E: 1bbeb4dce19e4ac2bbe7d1e373739298)`;console.error(I),h.push(I)}if(!u){let I=`${T} indexingMode required (E: 693ebd2be64a438aa3b075d0cb0d92bf)`;console.error(I),h.push(I)}if(!qe.includes(u)){let I=`${T} invalid indexingMode (${u}). Must be one of ${qe} (E: 17435268651444e0b7a594135635fc58)`;console.error(I),h.push(I)}if(m<1){let I=`${T} maxBlockSize must be greater than 0 (E: 9f268207ae274b958fb91855331be259)`;console.error(I),h.push(I)}if(w<1){let I=`${T} numOfPasses must be greater than 0 (E: c3bcab79bb024d65b84947806290a7d4)`;console.error(I),h.push(I)}if(!Object.values(Ie).includes(c)){let I=`${T} only ${Object.values(Ie)} hash algorithms implemented`;console.error(I),h.push(I)}if(i&&!nt.includes(i)){let I=`${T} unknown saltStrategy: ${i}`;console.error(I),h.push(I)}if(h.length>0){let I={...r,errors:h};return delete I.dataToEncrypt,delete I.secret,I}let A=await Zt(t);if(d&&await He(A)!==t)throw new Error("decoding encoded hex failed for this data: The encoded hex did not reverse to the original data.");let G=await cn({hexEncodedData:A,initialRecursions:o,recursionsPerHash:n,salt:s,saltStrategy:i,secret:a,hashAlgorithm:c,encryptedDataDelimiter:l,indexingMode:u,maxBlockSize:m,numOfPasses:w});if(d)try{let I=await er({encryptedData:G,initialRecursions:o,recursionsPerHash:n,salt:s,saltStrategy:i,secret:a,hashAlgorithm:c,encryptedDataDelimiter:l,indexingMode:u,blockMode:b});if(I.decryptedData){if(I.decryptedData!==t)throw new Error("The ENCRYPTED data did not decrypt back to the original data. (E: 16b5f1a11e4f438ab38a7f124178a7b8)")}else throw new Error("Confirm check call to decrypt produced falsy decryptedData (E: a4fe82dee61f497e9dea188ea9c287a4)");(I.warnings||[]).length>0&&(g=g.concat(["Confirm check call to decrypt had warnings.",...I.warnings]))}catch(I){throw new Error(`${e} confirm failed. decrypt error: ${E(I)} (E: 782a84d9dc294ce9a6a325e3ab293adf)`)}let y={...r,encryptedData:G,warnings:g.length>0?g:void 0};return delete y.dataToEncrypt,delete y.secret,y}f(dn,"encryptImpl_blockMode");async function Fc(r){let e=`[${Fc.name}]`;try{if(!r)throw new Error("args required (E: 22e58e03c78f4c27bf18295b8d2cdd3a)");if(!r.dataToEncrypt)throw new Error("dataToEncrypt required (E: 168c9076e5434c83ba81e3485ee6f3e4)");r.salt=r.salt||await F(Xe),r.saltStrategy=r.saltStrategy||Ke,r.hashAlgorithm=r.hashAlgorithm||Ve,r.recursionsPerHash=r.recursionsPerHash||Ye;let t;return r.blockMode?t=await dn(r):t=await an(r),(t.errors??[]).length>0&&t.errors.forEach(o=>console.warn(`${e} ${o}`)),(t.warnings??[]).length>0&&t.warnings.forEach(o=>console.warn(`${e} ${o}`)),t}catch(t){throw console.error(`${e}${t.message}`),t}}f(Fc,"encrypt");async function qc(r){let e=`[${qc.name}]`;try{if(!r)throw new Error("args required (E: fcd9b4aad85c4deba5fe5fde0b9ecb30)");if(!r.encryptedData)throw new Error("encryptedData required (E: f879f612428b4283bae089acee929a58)");r.salt=r.salt||await F(Xe),r.saltStrategy=r.saltStrategy||Ke,r.hashAlgorithm=r.hashAlgorithm||Ve,r.recursionsPerHash=r.recursionsPerHash||Ye;let t;return r.blockMode||r.multipass?t=await er(r):t=await Qt(r),(t.warnings??[]).length>0&&t.warnings.forEach(o=>console.warn(`${e} ${o}`)),(t.errors??[]).length>0&&t.errors.forEach(o=>console.warn(`${e} ${o}`)),t}catch(t){throw console.error(`${e}${t.message}`),t}}f(qc,"decrypt");var Fu=5e4;var qu=ke.appendPerHash,Hu=10,Ku="SHA-256";var Vu="encryption",Xu="ciphertext";var Hc={local:"local",outerspace:"outerspace",innerspace:"innerspace"},Ju=Object.values(Hc).concat(),Kc={user:"user",sync:"sync"},fn=Object.values(Kc).concat(),Vc={node_filesystem:"node-filesystem"},Xc={aws_dynamodb:"aws-dynamodb"},Yc={...Vc,...Xc},bn=Object.values(Yc).concat(),Wc={get:"get",put:"put",delete:"delete"},zc={can:"can",addrs:"addrs",latest:"latest",watch:"watch",unwatch:"unwatch",tjps:"tjps",dependencyGraph:"dependency-graph"};var Jc=!1,jr=class r{static{f(this,"DynamicFormBuilder")}lc=`[${r.name}]`;items=[];what="";idPool=[];getNewId(){let e=`${this.lc}[${this.getNewId.name}]`;if(this.idPool?.length>0)return this.idPool.pop()??"";{let t=[],o="ABCDEFGHIJKLMNOPQRSTUVWXYZ",n=o.length;for(let i=0;i<32;i++){let a=Math.floor(Math.random()*n);t.push(o[a])}let s=t.join("");return Jc&&console.log(`${e} id: ${s} (I: c6591ffee6d5bbea79ed19cfa6630422)`),s}}forA({what:e}){return this.what=e||"thingy",this}addItem(e){e.uuid||(e.uuid=this.getNewId()),this.items.push(e)}with({idPool:e}){return e&&(this.idPool=e),this}and(){return this}name({of:e,required:t=!0,defaultValue:o}){return this.addItem({name:"name",description:`What to call this ${this.what}. Doesn't have to be unique, no spaces, up to 32 alphanumerics/underscores in length.`,label:"Name",placeholder:'e.g. "bob_the_cool"',regexp:Ar({min:1,max:32,noSpaces:!0}),regexpErrorMsg:"1 to 32 characters, no spaces, underscores allowed.",required:t,dataType:"text",value:e,defaultValue:o}),this}description({of:e,required:t,defaultValue:o}){return this.addItem({name:"description",description:`Description/notes for this ${this.what}.`,label:"Description",placeholder:`Describe these ${this.what} settings here...`,regexp:Ar({min:0,max:155,chars:zo}),regexpErrorMsg:`0 to 155 alphanumerics or any of ${zo}`,dataType:"textarea",required:t,value:e,defaultValue:o}),this}classname({of:e,required:t=!0}){return this.addItem({name:"classname",description:`Technical setting that is the name of the ${this.what}'s class in computer code.`,label:"Classname",regexp:Ar({min:1,max:128,noSpaces:!0}),regexpErrorMsg:"1 to 128 alphanumerics or underscores without spaces",dataType:"text",value:e,readonly:!0,required:t}),this}uuid({of:e,label:t,required:o}){return this.addItem({name:"uuid",description:`Unique(ish) id of the ${this.what}.`,label:t??"ID",dataType:"text",value:e,regexp:re,regexpErrorMsg:"1 to 256 alphanumerics, underscores, dots, hyphens allowed.",readonly:!0,required:o}),this}version({of:e,required:t}){return this.addItem({name:"version",description:`Technical setting indicating the version of the ${this.what}.`,label:"Version",dataType:"text",value:e||"",readonly:!0,required:t}),this}customItem(e){return this.addItem(e),this}outputItems(){return this.items}outputForm({formName:e,label:t}){return{name:e,description:`This is a form for a ${this.what}`,label:t??this.what,items:this.items}}};var it=class r extends jr{static{f(this,"WitnessFormBuilder")}lc=`[${r.name}]`;allowPrimitiveArgs({of:e,required:t=!0}){return this.addItem({name:"allowPrimitiveArgs",description:`Technical setting on if this ${this.what} accepts primitive incoming ibgibs`,label:"Allow Primitive Args",dataType:"toggle",value:e??!0,readonly:!0,required:t}),this}catchAllErrors({of:e,required:t=!0}){return this.addItem({name:"catchAllErrors",description:`Technical setting on what the ${this.what} does when it encounters an internal error.`,label:"Catch All Errors",dataType:"toggle",value:e??!0,readonly:!0,required:t}),this}persistOptsAndResultIbGibs({of:e,required:t=!0}){return this.addItem({name:"persistOptsAndResultIbGibs",description:`Technical setting on if the ${this.what} maintains an audit trail of all of its inputs/outputs.`,label:"Persist Opts and Result IbGibs",dataType:"toggle",value:e??!1,readonly:!0,required:t}),this}trace({of:e,required:t}){return this.addItem({name:"trace",description:`Technical setting on if the ${this.what}'s activity should be traced (logged to the console).`,label:"Trace",dataType:"toggle",value:e??!1,readonly:!0,required:t}),this}commonWitnessFields({data:e,allowPrimitiveArgs:t=!0,catchAllErrors:o=!0,persistOptsAndResultIbGibs:n=!0,trace:s=!0,version:i=!0}){return t&&this.allowPrimitiveArgs({of:e.allowPrimitiveArgs}),o&&this.catchAllErrors({of:e.catchAllErrors}),n&&this.persistOptsAndResultIbGibs({of:e.persistOptsAndResultIbGibs}),s&&this.trace({of:e.trace}),i&&this.version({of:e.version}),this}};var Fr=!1;function ii({appData:r}){let e=`[${ii.name}]`;try{if(Fr&&console.log(`${e} starting...`),!r)throw new Error("appData required (E: 3df782b29bc4406a87e4895cfcea28ed)");let t=[],{name:o,uuid:n,classname:s}=r;return o?o.match(Jt)||t.push(`name must match regexp: ${Jt}`):t.push("name required."),n?n.match(re)||t.push(`uuid must match regexp: ${re}`):t.push("uuid required."),s&&(s.match(Jt)||t.push(`classname must match regexp: ${Jt}`)),t}catch(t){throw console.error(`${e} ${t.message}`),t}finally{Fr&&console.log(`${e} complete.`)}}f(ii,"validateCommonAppData");function un({appData:r,classname:e}){let t=`[${un.name}]`;try{let o=ii({appData:r});if(o.length>0)throw new Error(`invalid appData: ${o} (E: 9aff04f0cfc54a5188ca8bc40764160d)`);if(e){if(r.classname&&r.classname!==e)throw new Error("classname does not match appData.classname (E: 66f1447eef97485fba521c40980f5eb5)")}else if(e=r.classname,!e)throw new Error("classname required (E: 5f6ffb4317044125b94f662070e1f40b)");let{name:n,uuid:s}=r;return`app ${e} ${n} ${s}`}catch(o){throw console.error(`${t} ${o.message}`),o}}f(un,"getAppIb");function Zc({appIb:r}){let e=`[${Zc.name}]`;try{if(!r)throw new Error("appIb required (E: 6b065aee67e641ba9f9c6db367ebb0fb)");let t=r.split(" ");return{appClassname:t[1],appName:t[2],appId:t[3]}}catch(t){throw console.error(`${e} ${t.message}`),t}}f(Zc,"getInfoFromAppIb");async function Qc({fnPromptApp:r,ibgibs:e,space:t}){let o=`[${Qc.name}]`;try{if(Fr&&console.log(`${o} starting...`),!e)throw new Error("ibgibs all powerful service required. (E: b24e78de0d204dc78909022bee296b30)");t=t??await e.getLocalUserSpace({lock:!0});let n=await r(t,null);if(!n)throw new Error("resApp falsy after prompt for app. (E: 2225a567abcd680a5e957e81fbb64123)");let s=n.newIbGib,i=[];i.push(s),n.intermediateIbGibs?.forEach(d=>i.push(d)),n.dnas?.forEach(d=>i.push(d));for(let d=0;d<i.length;d++){let u=i[d],b=await se({ibGib:u});if((b??[]).length>0)throw new Error(`(UNEXPECTED) invalid app ibgib created. validationErrors: ${b}. app: ${H(s.toIbGibDto())} (E: 54cfc2f6bc284ed79be91d2da5e4bd2f)`)}await Q({resTransform:n,space:t});let{zeroSpace:a,fnBroadcast:c,fnUpdateBootstrap:l}=e;return await Ge({ibGib:s,space:t,fnBroadcast:f(d=>c(d),"fnBroadcast")}),await Rt({type:"apps",rel8nName:Lr,ibGibsToRel8:[s],space:t,zeroSpace:a,fnUpdateBootstrap:l,fnBroadcast:c}),s}catch(n){debugger;console.error(`${o} ${n.message}`);return}finally{Fr&&console.log(`${o} complete.`)}}f(Qc,"createNewApp");var el="0",tl="chat_gib",rl="A chat app done ibgib style, enabling infinitely nesting comments, pics and links. It's ibgibs all the way down...",ai={version:"1",uuid:el,name:tl,description:rl,classname:"ChatApp_V1",icon:"chatbubbles",persistOptsAndResultIbGibs:!1,allowPrimitiveArgs:!0,catchAllErrors:!0,trace:!1},ci=void 0;var ol="0",nl="raw_gib",sl="Explorer app for navigating raw ibgib data.",li={version:"1",uuid:ol,name:nl,description:sl,classname:"RawApp_V1",icon:"paper-plane",persistOptsAndResultIbGibs:!1,allowPrimitiveArgs:!0,catchAllErrors:!0,trace:!1},di=void 0;var pn="0",il="todo_gib",al="Todo app for viewing and interacting with ibgibs like they're checklists.",fi={version:"1",uuid:pn,name:il,description:al,classname:"TodoApp_V1",icon:"checkbox",persistOptsAndResultIbGibs:!1,allowPrimitiveArgs:!0,catchAllErrors:!0,trace:!1},bi=void 0;async function hn(r){let e=`[${hn.name}]`,t=[];try{_({ibGib:r})!==ot&&t.push(`invalid bootstrapSpace addr. Should equal "${ot}" (E: ecfdbed719284db7a1aa3f867f706fe9)`);let n=await se({ibGib:r});(n?.length??!1)&&n.forEach(a=>t.push(a));let s=r.data,i=r.rel8ns;return Object.keys(s||{}).length===0&&t.push("invalid bootstrapSpace data. data required (E: 5a9bd15dd0644f9b93cafbbba660cfdf)"),(s.spaceIds??[]).length===0&&t.push("invalid bootstrapSpace, data.spaceIds required. (E: 6b91ddc12cfd41e59ded7d7502c1909f)"),Object.keys(r.rel8ns||{}).length===0&&t.push("invalid bootstrapSpace rel8ns (empty). Should have at least one rel8n, with rel8nName corresponding to the spaceId (E: b188ce4ae25e49f794f35e141bc2ecde)"),s.spaceIds.forEach(a=>{(i[a]??[]).length===0&&t.push(`invalid bootstrap. Each spaceId listed in data should have a corresponding address in rel8ns. spaceId (${a}) missing. (E: 62dd0d76e29a415a98b4b27deb8db17e)`)}),s[De]?(i[s[De]]??[]).length===0&&t.push(`invalid bootstrap. data.${De} (${s[De]}) not found in rel8ns. (E: 44d0799d232f4a51a0b0019ebebe019f)`):t.push(`invalid bootstrap. data.${De} required. (E: f763af2e275f445cbf1db5801bacafad)`),t.length===0?!0:(console.error(`${e} errors: ${t.join("|")}`),!1)}catch(o){return console.error(`${e} ${o.message}`),!1}}f(hn,"validateBootstrapIbGib");var Ut="meta_stone";var gn="undefined",tr="target",qr="targetTjp";var xe=!1;function pi({ib:r}){let e=`[${pi.name}]`;try{xe&&console.log(`${e} starting...`);let t=[],o=r.split(" ");o[0]!==Ut&&t.push(`${e} invalid ib. atom is expected to be META_STONE_ATOM: ${Ut} (E: a9812bffc18f44418aa091fb0ed260bd)`);let s=o[1],i=et({gib:s})??[];i.length>0&&t.push(`invalid ib. pieces[1] should be a valid tjpGib. validation errors: ${i} (E: 233db2babfbe4d28a80f98261f1c0e01)`);let a=o[2],c=Number.parseInt(a);isNaN(c)&&t.push("invalid ib. space-delimited pieces[2] should be valid integer (E: 71df0d6abd7b4cf4b11621e6bfb556cd)");let l=o[3];if(l!=="undefined"){let d=rr({timestamp:l});d.valid||t.push(`invalid ib. pieces[3] should be valid timestampInTicks. emsg: (${d.emsg}) (E: 06dae01d66f54f54b71d9c920c730840)`)}return t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{xe&&console.log(`${e} complete.`)}}f(pi,"validateCommonMetaStoneIb");function mn({data:r}){let e=`[${mn.name}]`;try{if(xe&&console.log(`${e} starting...`),!r)throw new Error("data required (E: c50ac422af4501b72af12481fbd4961e)");let t=[],{targetData:o,timestamp:n}=r;rr({timestamp:n}).valid||t.push("invalid timestampInTicks. should be valid ticks number. (E: 7e381ed5b0c8486b90cfd37676da3626)");let{tjpGib:i,n:a,timestamp:c}=o;if(i&&i!=="undefined"){let d=et({gib:i})??[];d.length>0&&t.push(`invalid data (targetTjpGib). validation errors: ${d} (E: d216b12eb75544ef8c5ffb27cd132e2e)`)}if(typeof a!="number"&&t.push("invalid n. should be valid integer. if target.data.n is falsy, targetN should be -1 (E: 8f234967b388ad80776c8054d71fbc23)"),c&&c!=="undefined"){let d=rr({timestamp:c});d.valid||t.push(`invalid targetTimestamp. emsg: ${d.emsg} (E: c15d4fd2a2b74a0fab3223e83d954379)`)}let l=new Date(n);return t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{xe&&console.log(`${e} complete.`)}}f(mn,"validateCommonMetaStoneData");function hi({rel8ns:r}){let e=`[${hi.name}]`;try{if(xe&&console.log(`${e} starting...`),!r)throw new Error("rel8ns required (E: 7737ae550e2347e68c67b715c1221393)");let t=[],o=Wo({rel8ns:r??{}})??[];o.length>0&&t.push(`invalid rel8ns intrinsically. errors: ${o.join("|")}. (E: abc91753f0f946afa0a3ea2c1917960f)`);let n=r[tr]??[];n.length===0?t.push(`invalid metastone rel8ns. should have exactly 1 rel8nName ${tr}. has 0. (E: 8181652da9e89613e204d245db12d723)`):n.length>1&&t.push(`invalid metastone rel8ns. should have exactly 1 rel8nName ${tr}. has ${n.length}. (E: 2318047c6fea482d9f53febe02cf8912)`);let s=r[qr]??[];return s.length>1&&t.push(`invalid metastone rel8ns. should have 0 or 1 rel8nName ${qr}. has ${s.length}. (E: 34a8ae53825f46caa7ad024a64400db2)`),t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{xe&&console.log(`${e} complete.`)}}f(hi,"validateCommonMetaStoneRel8ns");async function cl({ibGib:r}){let e=`[${cl.name}]`;try{xe&&console.log(`${e} starting... (I: f32249d08105b997871a06cdee006311)`);let t=await se({ibGib:r})??[];if(!r.data)throw new Error("MetaStoneIbGib.data required (E: 96432cf4f919d339277d9a1c61ea4264)");let o=[];try{let{atom:a,tjpGib:c,n:l,timestampInTicks:d}=mi({ib:r.ib})}catch(a){o.push(E(a))}let n=mn({data:r.data}),s=hi({rel8ns:r.rel8ns}),i=[...t??[],...o??[],...n??[],...s??[]];return i.length>0?i:void 0}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{xe&&console.log(`${e} complete.`)}}f(cl,"validateCommonMetaStoneIbGib");function gi({data:r,classname:e}){let t=`[${gi.name}]`;try{let o=mn({data:r});if(o.length>0)throw new Error(`invalid MetaStone data: ${o} (E: ac642cc5915f0fc0508cb2fb728c86fa)`);e&&xe&&console.log(`${t} classname not required. no big deal that it is provided here. (I: db4d41471cb976795afd3fa89f8cb823)`);let n=r.targetData.timestamp,s=n&&n!=="undefined"?$e(n):gn;return`${Ut} ${r.targetData.tjpGib} ${r.targetData.n} ${s}`}catch(o){throw console.error(`${t} ${E(o)}`),o}}f(gi,"getMetaStoneIb");function mi({ib:r}){let e=`[${mi.name}]`;try{if(!r)throw new Error("MetaStone ib required (E: 8e74e098d7aeef52d3952e35150d83ed)");let t=pi({ib:r});if(t.length>0)throw new Error(`invalid ib. validationErrors: ${t} (E: a6107f62200eb943e523f70f51300623)`);let o=r.split(" ");return{atom:o[0],tjpGib:o[1],n:Number.parseInt(o[2]),timestampInTicks:o[3]}}catch(t){throw console.error(`${e} ${E(t)}`),t}}f(mi,"parseMetaStoneIb");function Pp({addr:r,ibGib:e}){if(r||=_({ibGib:e}),!r)throw new Error("either addr or ibGib required. (E: 372b2574d5a9fac298119beed9f6e223)");return r.startsWith(`${Ut} `)}f(Pp,"isMetaStone");async function En({targetIbGib:r}){let e=`[${En.name}]`;try{xe&&console.log(`${e} starting... (I: d846313065c89c89e4b5afa2df2b7123)`);let t=_({ibGib:r}),o=he({ibGib:r,defaultIfNone:"incomingAddr"}),n,s={[tr]:[t],[qr]:[o]};if(!r.gib)throw new Error("(UNEXPECTED) targetIbGib.gib falsy? (E: 28eaa8a799021dadd87b043711aee826)");let i=r.data?.isTjp?r.gib:ne({ibGibAddr:t}).tjpGib??r.gib;if(i===U)throw new Error("cannot create metastone for primitive ibgib (E: 2887e8ef83381a0698256b7bc7531826)");let a=new Date,c=Ae(a),l=a.getMilliseconds();r.data?or({ibGib:r})?n={targetData:{n:-1,tjpGib:i},timestamp:c,timestampMs:l}:(n={targetData:{n:r.data.n??-1,tjpGib:i,timestamp:r.data.timestamp??gn},timestamp:c,timestampMs:l},r.data?.isTjp&&(n.targetData.isTjp=!0)):n={targetData:{n:-1,tjpGib:i},timestamp:c,timestampMs:l};let d=gi({data:n}),u=await Oe({parentPrimitiveIb:Ut,ib:d,data:n,rel8ns:s});return xe&&(console.log(`${e} metaStoneIbGib... (I: 2b16197478488b329246d22d2dc41423)`),console.dir(u)),u}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{xe&&console.log(`${e} complete.`)}}f(En,"newUpMetaStone");var Hr="witness",nr="witness_arg",Kr="witness_result",Up="context";var S=!1;async function ie({addr:r,addrs:e,isDna:t,space:o,force:n}){let s=`[${ie.name}]`;try{if(S&&console.log(`${s} starting...`),!o)throw new Error("space required. (E: 4d188d6c863246f28aa575753a052304)");if(!r&&(e??[]).length===0)throw new Error("addr or addrs required. (E: 1a0b92564ba942f1ba91a089ac1a2125)");r&&(e?.length??0)>0&&(console.warn(`${s} both addr and addrs provided, but supposed to be used one or the other. (W: 87226c2ac50e4ea28211334a7b58782f)`),e.includes(r)||e.push(r)),e=(e??[]).length>0?e:[r];let i=await o.argy({ibMetadata:Ce({space:o}),argData:{cmd:"get",ibGibAddrs:e,isDna:t}}),a=await o.witness(i);return a?.data?.success?(S&&console.log(`${s} got.`),{success:!0,ibGibs:a.ibGibs,rawResultIbGib:a}):(S&&console.log(`${s} didn't get.`),{success:!1,errorMsg:a.data?.errors?.join("|")||`${s} something went wrong. addrs: ${e.join(`
2
+ `)} (E: b9e9d5ce0cde4122bfb74f7688db85e0)`,rawResultIbGib:a})}catch(i){return console.error(`${s} ${i.message}`),{errorMsg:i.message}}}f(ie,"getFromSpace");async function yn({ibGib:r,ibGibs:e,isDna:t,force:o,space:n}){let s=`[${yn.name}]`;try{if(!r&&(e??[]).length===0)throw new Error("ibGib or ibGibs required. (E: e59c4de3695f4dd28c8fe82dbb9c4e90)");if(!n)throw new Error("space required. (E: dd0b7189c67c43c586b905a8ed6f51c9)");r&&(e??[]).length>0&&(console.warn(`${s} Both ibGib and ibGibs is assigned, whereas this is intended to be exclusive one or the other. (W: 4c797835b620445f88e4cba6b5aa3460)`),e.some(c=>c.gib===r.gib)||(e=e.concat([r]))),e=e??[r],S&&console.log(`${s} ibGibs.length: ${e.length}`);let i=await n.argy({ibMetadata:Ce({space:n}),argData:{cmd:"put",force:o,isDna:t,ibGibAddrs:e.map(c=>_({ibGib:c}))},ibGibs:e.concat()}),a=await n.witness(i);if(a.data?.success)return(a.data.warnings??[]).length>0&&a.data.warnings.forEach(c=>console.warn(`${s} ${c}`)),{success:!0};{let c=a?.data?.errors?.length>0?`Error(s) putting in local space:
3
+ ${a.data.errors.join(`
4
+ `)}`:"(UNEXPECTED) unknown error putting ibGibs (E: 3d7426d4527243b79c5e55eb25f3fa73)";throw new Error(c)}}catch(i){return console.error(`${s} ${i.message}`),{errorMsg:i.message}}}f(yn,"putInSpace");async function In({addr:r,isDna:e,space:t}){let o=`[${In.name}]`;try{if(!t)throw new Error("space required. (E: 40ab3b51e91c4b5eb4f215baeefbcef0)");if(!t.data)throw new Error("space.data required. (E: 0d02c8e85ee143b8bd6a1a1db0d9af1b)");o=`${o}[${t.data.name||"noname?"}][${t.data.uuid||"nouuid?"}]`;let n=await t.argy({ibMetadata:Ce({space:t}),argData:{cmd:"delete",ibGibAddrs:[r],isDna:e}}),s=await t.witness(n);if(s.data?.success)return{success:!0};{s.data?.warnings?.length>0&&console.warn(`${o} warnings with delete (${r}): ${s.data.warnings.join("|")}`),s.data?.addrs?.length>0&&console.warn(`${o} partial addrs deleted: ${s.data.addrs.join("|")}`);let i=s.data?.errors?.join("|")||`${o} something went wrong (E: e397fd09b4a746a3ba3305d6ea0893cb)`;return i.includes("File does not exist")&&S&&console.log(`${o} tried to delete file that does not exist. (I: cb5d1348ccbc58bf0bfc95f3006f1e22)`),{errorMsg:i}}}catch(n){return console.error(`${o} ${n.message}`),{errorMsg:n.message}}}f(In,"deleteFromSpace");async function Q({resTransform:r,space:e,force:t}){let o=`[${Q.name}]`;try{if(S&&console.log(`${o} starting... (I: dc6835614ff1a1b82b179225023ae823)`),!e)throw new Error("space required. (E: cf94f1d74f1c4561bb88025a2095965b)");let{newIbGib:n,intermediateIbGibs:s,dnas:i}=r,a=[n,...s||[]],c=await e.argy({ibMetadata:Ce({space:e}),argData:{cmd:"put",force:t,ibGibAddrs:a.map(d=>_({ibGib:d}))},ibGibs:a.concat()}),l=await e.witness(c);if(l.data?.success)l.data.warnings?.length>0&&l.data.warnings.forEach(d=>console.warn(`${o} ${d}`));else{let d=l?.data?.errors?.length>0?l.data.errors.join(`
5
+ `):"unknown error putting ibGibs";throw new Error(d)}if(i?.length??!1){let d=await e.argy({ibMetadata:Ce({space:e}),argData:{cmd:"put",isDna:!0,force:t,ibGibAddrs:i.map(b=>_({ibGib:b}))},ibGibs:i.concat()}),u=await e.witness(d);if(u.data?.success)u.data.warnings?.length>0&&u.data.warnings.forEach(b=>console.warn(`${o} ${b}`));else{let b=u?.data?.errors?.length>0?u.data.errors.join(`
6
+ `):"unknown error putting dna ibGibs";throw new Error(b)}}}catch(n){throw console.error(`${o} ${n.message}`),n}finally{S&&console.log(`${o} complete. (I: dc6835614ff1a1b82b179225023ae823)`)}}f(Q,"persistTransformResult");async function ll({type:r,rel8nName:e,space:t}){let o=`[${ll.name}]`;try{if(!t)throw new Error("space required. (E: f73868a952ac4181a4f90ee6d86cacf3)");let n=await Xr({type:r,space:t});if(!n)throw new Error(`couldn't get special (${r}) (E: a65bef190416479697605be486846731)`);let s=n.rel8ns?n.rel8ns[e]||[]:[],i=[];for(let a=0;a<s.length;a++){let c=s[a],l=await ie({addr:c,space:t});if(l.success&&l.ibGibs?.length===1)i.push(l.ibGibs[0]);else throw new Error(`couldn't get addr: ${c} (E: 76ef256ee80149ab860c5786484b0e89)`)}return i}catch(n){throw console.error(`${o} ${n.message}`),n}}f(ll,"getSpecialRel8dIbGibs");async function Xr({type:r,initialize:e,space:t,zeroSpace:o,fnUpdateBootstrap:n,fnBroadcast:s,fnGetInitializing:i,fnSetInitializing:a,dontWarnIfNotExist:c}){let l=`[${Xr.name}]`;try{if(!t)throw new Error("space required. (E: d454b31d58764a9bb9c4e47fb5ef38b5)");let d=ae({type:r}),u=await Yr({key:d,space:t,dontWarn:c||!!e});if(!u){if(e&&(!i||!a))throw new Error("if initialize, you must provide fnGetInitializeLock & fnSetInitializeLock. (E: 8eb322625d0c4538be089800882487de)");if(e&&!i()){a(!0);try{if(!o)throw new Error("zeroSpace required when 'initialize' truthy (E: 8582c92c637f90c9b2dbe0ec8355b523)");u=await $i({type:r,space:t,zeroSpace:o,fnBroadcast:s,fnUpdateBootstrap:n})??void 0}catch(g){console.error(`${l} error initializing: ${g.message}`)}finally{a(!1)}}if(!u){if(i&&i())return console.warn(`${l} couldn't get addr, but we're still initializing...`),null;throw new Error("Special address not in config and couldn't initialize it either. (E: d8ebdc9eaaa640b99cd206f132962c93)")}}S&&console.log(`${l} getting addr: ${u}`);let b=await ie({addr:u,space:t});if(b.success||(b=await ie({addr:u,space:t}),b.success&&(console.warn(`${l} special ibgib was not stored in meta folder...putting in meta folder now for the future (W: e6f5571fd98c449bb2809359be5057cc)`),(await yn({ibGib:b.ibGibs[0],space:t})).success||console.warn(`${l} (UNEXPECTED) tried to put special in meta but success was false? (W: b934b53571c24057af172c790e6a7240)`))),!b.success)throw new Error(b.errorMsg);if(b.ibGibs?.length!==1)throw new Error("no ibGib in result (E: 3a42abdddc3648e292d63dc45c560064)");let p=b.ibGibs[0],h=await _e({ibGibs:[p],space:t});if(h?.data?.success&&h.data.addrs?.length===1){let g=_({ibGib:p}),m=h.data.addrs[0];m!==g&&console.warn(`${l} latest addr is not the one associated with the local space.
7
+ specialAddr: ${g}
8
+ latestAddr: ${m} (W: 141b69dc3c414efc9645bb76fcf12df9)`)}return p}catch(d){let u=`${l} ${d.message}`;return u.includes("d8ebdc9eaaa640b99cd206f132962c93")&&c||console.error(u),null}}f(Xr,"getSpecialIbGib");async function Yr({key:r,space:e,dontWarn:t}){let o=`[${Yr.name}](${r})`;try{if(S&&console.log(`${o} getting... (I: 43e7bfc2515d45e5af8767b9a85b248e)`),!e)throw new Error("space required. (E: 4f135d4276e64054ba21aeb9c304ecec)");if(!e.rel8ns){(S||!t)&&console.warn(`${o} space.rel8ns falsy. (W: 7c642259fbf547dbaa1b2fdf0115f6ef)`);return}if(!e.rel8ns[r]){(S||!t)&&console.warn(`${o} space.rel8ns[${r}] falsy. (W: 3c1c49b9987b45cc96dd78b808f98e91)`);return}if(e.rel8ns[r].length===1)return S&&console.log(`${o} got (I: f13e71b693d5404c9535bda8ff0cc6a9)`),e.rel8ns[r][0];if(e.rel8ns[r].length>1)return(S||!t)&&console.warn(`${o} more than one config addr with ${r} rel8n. (W: 102f63eb74904bcfaac2eaf778043205)`),e.rel8ns[r][0];S&&console.log(`${o} didn't find (I: 1163e6ac60194d25b3f24881650edfad)`);return}catch(n){console.error(`${o} ${n.message}`);return}}f(Yr,"getConfigAddr");async function fe({key:r,addr:e,space:t,zeroSpace:o,fnUpdateBootstrap:n}){let s=`[${fe.name}]`;try{if(!t)throw new Error("space required. (E: c28b663c991d44419aef1026cc689636)");if(!o)throw new Error("zeroSpace required. (E: d3707ae5265d464891ad216f64be6184)");let i={[r]:[e]},a=await ye({src:t.toIbGibDto(),dna:!1,linkedRel8ns:["past","ancestor",r],rel8nsToAddByAddr:i,nCounter:!0});if(!a.newIbGib)throw new Error("create new space failed.");await Q({resTransform:a,space:o}),await Q({resTransform:a,space:t});let c=a.newIbGib;return await t.loadIbGibDto(c),n?await n(c):console.warn(`${s} fnUpdateBootstrap is falsy. (W: 9fb874de2b19454dac18645e61ac463f)`),c}catch(i){throw console.error(`${s} ${i.message}`),i}}f(fe,"setConfigAddr");async function Ei({space:r}){let e=`[${Ei.name}]`;try{if(!r)throw new Error("space required. (E: f0d546101fba4c169256158114ab3c56)");let t=await Xr({type:"roots",space:r});if(!t)throw new Error("Roots not initialized. (E: 89b1ba12ed12416aac41cef9fdaf1fc2)");if(!t.rel8ns)throw new Error("Roots not initialized properly. No rel8ns. (E: 8513a07cf530484db9521a2a3a27b7f6)");if(!t.rel8ns.current)throw new Error("Roots not initialized properly. No current root. (E: 459c3a007a30486d96fb8d83f696e239)");if(t.rel8ns.current.length===0)throw new Error("Invalid Roots: empty current root rel8n. (E: bede5864090440bca01ea7ab7fd107d6)");if(t.rel8ns.current.length>1)throw new Error("Invalid Roots: multiple current roots selected. (E: 97561acbf63a48ecaa037697bd26555a)");let o=t.rel8ns.current[0],n=await ie({addr:o,space:r});if(n.ibGibs?.length===1)return n.ibGibs[0];throw new Error(`could not get current root. addr: ${o}`)}catch(t){console.error(`${e} ${t.message}`);return}}f(Ei,"getCurrentRoot");async function _n({root:r,space:e,zeroSpace:t,fnUpdateBootstrap:o,fnBroadcast:n}){let s=`[${_n.name}]`;try{if(S&&console.log(`${s} starting... (I: 7f16e845a80fe95d28923e4170f0c825)`),!r)throw new Error("root required.");if(!e)throw new Error("space required. (E: 186af2731c5342a78b063a0a4346f3db)");let i=_({ibGib:r}),a=await Xr({type:"roots",space:e});if(!a)throw new Error("Roots not initialized. (E: a8232b9afac89d0d189534480b7a9825)");let l=await ye({src:a,dna:!1,linkedRel8ns:["past","ancestor","current"],rel8nsToAddByAddr:{current:[i]},nCounter:!0});await Q({resTransform:l,space:e});let d=ae({type:"roots"}),u=l.newIbGib,b=_({ibGib:u});await fe({key:d,addr:b,space:e,zeroSpace:t,fnUpdateBootstrap:o}),await Ge({ibGib:u,space:e,fnBroadcast:n})}catch(i){throw console.error(`${s} ${i.message}`),i}finally{S&&console.log(`${s} complete. (I: 7f16e845a80fe95d28923e4170f0c825)`)}}f(_n,"setCurrentRoot");async function wi({ibGib:r,linked:e,rel8nName:t,space:o,fnBroadcast:n,zeroSpace:s,fnUpdateBootstrap:i}){let a=`[${wi.name}]`;try{if(!o)throw new Error("space required. (E: f2758eab3bb844d2b749515672d9e392)");if(!r)throw new Error("ibGib required (E: f1bfd67754a7271553f4af544d30bc22)");let c=await Ei({space:o});if(!c)throw new Error("currentRoot undefined (E: 5c2d84dafc664808866008f6eb535750");let l=he({ibGib:r,defaultIfNone:"incomingAddr"}),d=_({ibGib:r});if(t&&l&&c.rel8ns&&c.rel8ns[t]&&c.rel8ns[t].includes(l))return;t=t||Zo;let u=await ye({src:c,dna:!1,linkedRel8ns:e?["past","ancestor",t]:["past","ancestor"],rel8nsToAddByAddr:{[t]:[d]},nCounter:!0});await Q({resTransform:u,space:o});let b=u.newIbGib,p=_({ibGib:b});S&&console.log(`${a} updating _currentRoot root. newRootAddr: ${p}`),await Ge({ibGib:b,space:o,fnBroadcast:n}),await _n({root:b,space:o,zeroSpace:s,fnUpdateBootstrap:i,fnBroadcast:n})}catch(c){console.error(`${a} ${c.message}`);return}}f(wi,"rel8ToCurrentRoot");async function wn({targetIbGib:r,space:e}){let t=`[${wn.name}]`;try{S&&console.log(`${t} starting... (I: 291638372117dbc983b4b7cbd8f52123)`);let o=await En({targetIbGib:r}),n=await yn({ibGib:o,space:e});if(!n.success)throw new Error(`error putting metaStone in space. error: ${n.errorMsg??"[unknown error (E: 45f700f4f1ff463ca8f5353c8e796ac7)]"} (E: 4c25379e66365055e3e423561a7d6123)`)}catch(o){throw console.error(`${t} ${E(o)}`),o}finally{S&&console.log(`${t} complete.`)}}f(wn,"createAndSaveNewMetaStone");async function Ge({ibGib:r,space:e,fnBroadcast:t}){let o=`[${Ge.name}]`,n=S;try{let s=_({ibGib:r});if(o=`${o}[${s}]`,!e)throw new Error("space required. (E: ea0c03256f8a4062b460aa4de11f1e3e)");if(S&&console.log(`${o} starting...`),!ne({ibGibAddr:s}).tjpGib&&!r.data?.isTjp){S&&console.log(`${o} incoming ibGib has no timeline, so no broadcast. still going to create a metastone for it and return early. (I: 649752e3b1be0e0ceb078e0ec2a84f23)`),await wn({targetIbGib:r,space:e});return}let a=he({ibGib:r,defaultIfNone:"undefined"});if(!a){let h=r.data?.isTjp?r:await $n({ibGib:r,space:e});h||(console.warn(`${o} tjp not found for ${s}? Should at least just be the ibGib's address itself. (W: d9b570e5bf6d4312bc7d9249ed3bbaad)`),h=r),a=_({ibGib:h})}if(!a)throw new Error("(UNEXPECTED) tjpAddr falsy? should be guaranteed at this point. (E: 39aafb70bc3c6d70b6d2cf8882311223)");let c=f(async()=>{S&&console.log(`${o} adding/replacing latest. tjp: ${a} (I: 7f848da003a2436089fd6f044d96bb42)`),await wn({targetIbGib:r,space:e}),t&&(S&&console.log(`${o} fnBroadcast is true...(I: 0e3b561fb5474a0598b5c6d698df5e1f)`),setTimeout(()=>{S&&console.log(`${o} broadcasting... (I: 61785937be0346f0959d476d7267ab24)`),t({ib:"IbGibTimelineUpdateInfo",tjpAddr:a,latestAddr:s,latestIbGib:r})}))},"replaceLatest");if(r.data?.isTjp){S&&console.log(`${o} ibGib.data?.isTjp true. replacingLatest and returning early. (I: 02c626e006668291550e278b461bcb23)`),await c();return}S&&console.log(`${o} ibGib.data?.isTjp is falsy. (I: 84940e3a9eff869c9474b7b92b864b23)`);let l=await _e({ibGibs:[r],space:e});if(!l.data)throw new Error("(UNEXPECTED) resLatest.data falsy? (E: af3d3914d96adcc5525e4db83cc5d223)");let{success:d,latestAddrsMap:u}=l.data;if(!d){let{errors:h}=l.data;throw h??=["[unknown error (E: 344857f1853641aa842cea3931f90428)]"],new Error(`resLatest.success falsy. errors: ${H(h)}. addr: ${s} (E: b66721da6e1ef9ac4f4089e86c059323)`)}if(!u)throw new Error("(UNEXPECTED) latestAddrsMap falsy but success truthy? (E: c34caff7a256503575ff3ff491dec823)");let b=Object.keys(u);if(b.length!==1)throw new Error("(UNEXPECTED) latestAddrsMap size isn't 1? (E: e11ffc2c18d473745b5bbfc3fe5e3a23)");if(b[0]!==s)throw new Error(`(UNEXPECTED) latestAddrsMap has 1 key (correct) but the key isn't the incoming ibGibAddr? (incorrect). incoming ibGibAddr: ${s}. key found: ${b[0]} (E: 82d79a95d2d7de90eae9db571a360f23)`);S&&(console.log(`${o} valid latestAddrsMap. console.dir(latestAddrsMap)... (I: e24de41622cabbef375172c3017cfd23)`),console.dir(u));let p=u[s];if(p)if(p===s){S&&console.log(`${o} no other found. possible idempotent replacement. addr: ${s} (I: 7f5bd5d3391be95919240f0e97976e22)`),await c();return}else{S&&console.log(`${o} different addr found. incoming ibgib addr is newer. existingLatestAddr: ${p}. incoming addr: ${s} (I: 6cadf13f82aabeb71d76babf1813e623)`);let h=await ie({addr:p,space:e});if(!h.success||h.ibGibs?.length!==1){console.error(`Didn't find existing latest ibGib (${p}). I haven't implemented more robust multi-node/distributed strategies for this scenario yet. so we are going ahead with setting the incoming ibgib as the latest in the timeline. (E: 10f6cca6e5ef45bfacbfe48f652e2102)`),await c();return}let g=h.ibGibs[0];if(typeof r.data?.n=="number"&&r.data.n>=0){S&&console.log(`found ibGib.data.n (version counter), using this to determine latest ibGib: ${r.data.n}`);let $=r.data.n;if(typeof g.data?.n=="number"&&g.data.n>=0){let T=g.data.n;if(S&&console.log(`[registerNewIbGib] n_ibGib (${$}) vs n_existingLatest (${T}) in space: ${e.data?.name||e.ib}`),$>T)S&&console.log(`${o} is newer (I: 040d05ac2032f08c7fd0c4d8b2887323)`),await c();else{S&&console.log("is not newer, so we don't need to do anything else. (I: 14c25dc3314748dc909d61b77eb64354)"),console.warn(`${o} incoming ibGib (${s}) is NOT NEWER than existing latest (${p}). multiple branches for the same timeline? ignoring incoming ibGibAddr. n_ibGib: ${$}. n_existingLatest: ${T}. space.ib: ${e.ib} (W: 057baadca494473dabb26fb4fb879774)`);return}}else g.data?.isTjp&&r.data.n===0?await c():(console.warn(`${o} (UNEXPECTED) only existingLatestIbGib (isTjp: ${g.data?.isTjp}) has a data.n counter? ibGib.data.n: ${r.data.n}. usually this only happens when existing latest is a tjp and the new ibGib we are registering is n === 0. This is falsy in this instance though. We will go ahead and replace the latest with the new one, but this is an anomalous state. (W: 73d08aea17ad4e1481a5f97e2556a878)`),console.log(`${o} console.dir(existingLatestIbGib)... (I: 9ef7962d9cc74f1eb0409e5caf98e915)`),console.dir(g),console.log(`${o} console.dir(ibGib)... (I: 9ef7962d9cc74f1eb0409e5caf98e915)`),console.dir(r),await c())}else if(S&&console.log(`${o} no nCounter found. Trying brute force method.`),await Ni({ibGib:r,ibGibAddr:s,existingLatest:g,existingLatestAddr:p,tjpAddr:a,space:e})===s)await c();else return}else if(p===null){S&&console.log(`${o} no existing tjp mapping so incoming ibgib is considered new to this space. ibGib addr: ${s} (I: 4f2bbc32b31e4fa982d95b3a785db82f)`),await c();return}else throw new Error("(UNEXPECTED) latestAddr is falsy but not null? the getLatestAddrs impl in the space should be guaranteed to provide either the incoming ibgib addr, the latest addr (if exists), or null if not found. (E: 3159dd531c0bc0efc1ece116adf28923)")}catch(s){throw console.error(`${o} ${s.message}`),s}finally{S&&console.log(`${o} complete.`),S=n}}f(Ge,"registerNewIbGib");async function Rt({type:r,rel8nName:e,ibGibsToRel8:t,ibGibsToUnRel8:o,addrsToUnRel8:n,linked:s,severPast:i,deletePreviousSpecialIbGib:a,space:c,zeroSpace:l,fnUpdateBootstrap:d,fnBroadcast:u}){let b=`[${Rt.name}](type:${r},rel8nName:${e})`;try{if(!c)throw new Error("space required. (E: 956192eea28047eba6dad81620bb96fb)");if((t??[]).length===0&&(o??[]).length===0&&(n??[]).length===0)throw new Error("either ibGibsToRel8 or ibGibsToUnRel8 required. (E: 5add49c8e46a54e2c6b057c22646a822)");if((o??[]).length>0&&(n??[]).length>0)throw new Error("can't provide both ibGibsToUnRel8 and addrsToUnRel8. There isn't a technical reason but I'm too tired right now to implement the overhead to enable this atow (05/2025). (E: 31ef66be26349cfe1b1f352389b99425)");let p=t?.map(y=>_({ibGib:y}));n??=o?.map(y=>_({ibGib:y}));let h=ae({type:r}),g=await Yr({key:h,space:c});if(!g)throw new Error("specialAddr not found (E: 680dfd1caa3e4d7cb0f593b893a10f0d)");let m=await ie({addr:g,space:c});if(!m.success)throw new Error("couldn't get special (E: 897f7671d2184515866c5a675d33b3dc)");if(!m.ibGibs)throw new Error("resGetSpecial.ibGibs falsy (E: 2405dd295b2444d88503f7731796a5a0)");if(m.ibGibs.length!==1)throw new Error(`resGetSpecial.ibGibs count is not 1 (${m.ibGibs.length}) (E: b4547789016a4729af30cd972a4ca4ab)`);let $=m.ibGibs[0],w=await ye({src:$,rel8nsToAddByAddr:p?{[e]:p}:void 0,rel8nsToRemoveByAddr:n?{[e]:n}:void 0,dna:!1,linkedRel8ns:s?[Y.past,e]:[Y.past],nCounter:!0}),T=w.newIbGib;if(i){if(w.intermediateIbGibs)throw new Error("new special creates intermediate ibgibs. so severing past is harder. (E: b580c0c56253494192e9c62212ee187d)");T.rel8ns.past=[],T.gib=await V({ibGib:T})}await Q({resTransform:w,space:c});let A=_({ibGib:T}),G=he({ibGib:T});return await fe({key:h,addr:A,space:c,zeroSpace:l,fnUpdateBootstrap:d}),a&&await In({addr:g,space:c}),await Ge({ibGib:T,fnBroadcast:u,space:c}),A}catch(p){throw console.error(`${b} ${p.message}`),p}}f(Rt,"rel8ToSpecialIbGib");async function $n({ibGib:r,naive:e=!0,space:t}){let o=`[${$n.name}]`;try{if(!t)throw new Error("space required. (E: 941f973d50e84415b58724af173f52c2)");if(!r)throw new Error("ibGib required.");let n=_({ibGib:r}),{gib:s}=R({ibGibAddr:n});if(s===U||await vn({ibGib:r,naive:e}))return r;if(!r.rel8ns){S&&console.log(`${o} ibgib not tjp in data, and rel8ns is falsy. so tjp is undefined (I: acdadb76a7568807db7a68f6f866de22)`);return}if(r.rel8ns.tjp&&r.rel8ns.tjp.length>0){let u=r.rel8ns.tjp[0],b=await ie({addr:u,space:t});if(b.success&&b.ibGibs?.length===1)return b.ibGibs[0];{let p=b.errorMsg??"[unspecified error in get result]";throw new Error(`ibGib references tjp but could not retrieve from space. res error: ${p} (E: 94f0340706ad48c794c6a62c1b235a22)`)}}let a=r.rel8ns.past||[];if(a.length===0){console.warn(`${o} past.length === 0, so there is no tjp.`),S&&console.log(`${o} ibgib is not tjp in data, not in tjp rel8n, and past is empty. so tjp is undefined (I: bf06f664917dcf4492fb9c4c106a6222)`);return}let c=a[a.length-1],l=await ie({addr:c,space:t});if(!l.success||l.ibGibs?.length!==1)throw new Error(`get past failed. addr: ${c}`);let d=l.ibGibs[0];return await $n({ibGib:d,naive:e,space:t})}catch(n){throw console.error(`${o} ${n.message}`),n}}f($n,"getTjpIbGib");async function $i({type:r,space:e,zeroSpace:t,fnUpdateBootstrap:o,fnBroadcast:n}){let s=`[${$i.name}]`;try{if(!e)throw new Error("space falsy and localUserSpace not initialized. (E: 66e7d3ff098248f0a5ddda51853c92e6)");switch(r){case"roots":return _i({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});case"tags":return yi({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});case"secrets":return Ai({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});case"encryptions":return Si({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});case"outerspaces":return Gi({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});case"autosyncs":return xi({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});case"robbots":return vi({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});case"apps":return Di({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});default:return Oi({type:r,space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o})}}catch(i){throw console.error(`${s} ${i.message}`),i}}f($i,"createSpecial");async function Be({type:r,skipRel8ToRoot:e,space:t,zeroSpace:o,fnUpdateBootstrap:n,fnBroadcast:s}){let i=`[${Be.name}][${r||"falsy type?"}]`;try{S&&console.log(`${i} starting...`);let a=Gn({type:r}),c=k.primitive({ib:a}),l=await Gr({src:c,destIb:a,linkedRel8ns:[Y.past,Y.ancestor],tjp:{uuid:!0,timestamp:!0},dna:!0,nCounter:!0});return await Q({resTransform:l,space:t}),r!=="roots"&&r!=="latest"&&!e&&await wi({ibGib:l.newIbGib,linked:!0,space:t,zeroSpace:o,fnBroadcast:s,fnUpdateBootstrap:n}),S&&console.log(`${i} complete.`),l.newIbGib}catch(a){throw console.error(`${i} ${a.message}`),a}}f(Be,"createSpecialIbGib");async function yi({space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}){let n=`[${yi.name}]`;try{if(!r)throw new Error("space required. (E: 9c05b9bd355943a39ca47afef67a50eb)");let s=ae({type:"tags"}),i=await Be({type:"tags",space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t}),a=_({ibGib:i});await fe({key:s,addr:a,space:r,zeroSpace:e,fnUpdateBootstrap:t});let c=[{text:"home",icon:"home-outline"},{text:"favorite",icon:"heart-outline"}];for(let l of c)a=(await Ii({...l,space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t})).newTagsAddr,await fe({key:s,addr:a,space:r,zeroSpace:e,fnUpdateBootstrap:t});return a}catch(s){return console.error(`${n} ${s.message}`),null}}f(yi,"createSpecial_Tags");async function Ii({text:r,icon:e,description:t,space:o,zeroSpace:n,fnUpdateBootstrap:s,fnBroadcast:i}){let a=`[${Ii.name}]`;try{if(S&&console.log(`${a} starting...`),!o)throw new Error("space required. (E: 5def0b1afab74b0c9286e3ac5060cb8f)");if(!r)throw new Error(`${a} text required`);e=e||Ks,t=t||Vs;let c=$t(r),l=k.primitive({ib:"tag"}),d=await k.firstGen({parentIbGib:l,ib:c,data:{text:r,icon:e,description:t},tjp:{uuid:!0,timestamp:!0},dna:!0,nCounter:!0}),u=d.newIbGib;await Q({resTransform:d,space:o}),await Ge({ibGib:u,space:o,fnBroadcast:i});let b=await dl({tagIbGib:u,space:o,zeroSpace:n,fnUpdateBootstrap:s,fnBroadcast:i});return{newTagIbGib:u,newTagsAddr:b}}catch(c){throw console.error(`${a} ${c.message}`),c}finally{S&&console.log(`${a} complete.`)}}f(Ii,"createTagIbGibAndSundry");async function _i({space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}){let n=`[${_i.name}]`;try{if(!r)throw new Error("space required. (E: d12a8ea31163429fb6e53ff8e7579c57)");let s=ae({type:"roots"}),i=await Be({type:"roots",space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t}),a=_({ibGib:i});await fe({key:s,addr:a,space:r,zeroSpace:e,fnUpdateBootstrap:t});let l=["A","B","C","D","E","F","G"].map(u=>({text:`${u}root`,icon:Qo,description:en})),d;for(let u=0;u<l.length;u++){let b=l[u],p=await Ti({...b,space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o});if(d||(d=p.newRootIbGib),!p.newRootIbGib)throw new Error("(UNEXPECTED) resCreate.newRootIbGib falsy? (E: c9fb2c94a9c1d762c1699b41a4d5ad23)");a=p.newRootsAddr,await fe({key:s,addr:a,space:r,zeroSpace:e,fnUpdateBootstrap:t})}if(!d)throw new Error("(UNEXPECTED) firstRoot still falsy? (E: b2e2c926d242966e7ed7159e4b129e23)");if(await _n({root:d,space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}),a=await Yr({key:s,space:r}),!a)throw new Error("(UNEXPECTED) no roots address in config? (E: 76345340699a4738a195e48803ef0d31)");return a}catch(s){return console.error(`${n} ${s.message}`),null}}f(_i,"createSpecial_Roots");async function Ti({text:r,icon:e,description:t,space:o,zeroSpace:n,fnUpdateBootstrap:s,fnBroadcast:i}){let a=`[${Ti.name}]`;try{if(!o)throw new Error("space required. (E: cfa876e5c8c64a53a463ca7a645571c8)");r=r||Hs,e=e||Qo,t=t||en;let c=xn(r),l=k.primitive({ib:"root"}),d=await k.firstGen({parentIbGib:l,ib:c,data:{text:r,icon:e,description:t},linkedRel8ns:[Y.past,Y.ancestor],tjp:{uuid:!0,timestamp:!0},dna:!0,nCounter:!0}),{newIbGib:u}=d;await Q({resTransform:d,space:o});let b=await Rt({type:"roots",rel8nName:Jo,ibGibsToRel8:[u],space:o,zeroSpace:n,fnUpdateBootstrap:s,fnBroadcast:i});return{newRootIbGib:u,newRootsAddr:b}}catch(c){throw console.error(`${a} ${c.message}`),c}}f(Ti,"createRootIbGib");async function Ai({space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}){let n=`[${Ai.name}]`;try{if(!r)throw new Error("space required. (E: 340960cd5ad24addb300b23d9722e30a)");let s,i=ae({type:"secrets"}),a=await Be({type:"secrets",space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t});return s=_({ibGib:a}),await fe({key:i,addr:s,space:r,zeroSpace:e,fnUpdateBootstrap:t}),s}catch(s){return console.error(`${n} ${s.message}`),null}}f(Ai,"createSpecial_Secrets");async function Si({space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}){let n=`[${Si.name}]`;try{if(!r)throw new Error("space required. (E: 5084e698b6924e7090697ca50075ca59)");let s,i=ae({type:"encryptions"}),a=await Be({type:"encryptions",space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t});return s=_({ibGib:a}),await fe({key:i,addr:s,space:r,zeroSpace:e,fnUpdateBootstrap:t}),s}catch(s){return console.error(`${n} ${s.message}`),null}}f(Si,"createSpecial_Encryptions");async function Gi({space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}){let n=`[${Gi.name}]`;try{if(!r)throw new Error("space required. (E: 99dd9e92535c470482eb9f6625a33831)");let s,i=ae({type:"outerspaces"}),a=await Be({type:"outerspaces",space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t});return s=_({ibGib:a}),await fe({key:i,addr:s,space:r,zeroSpace:e,fnUpdateBootstrap:t}),s}catch(s){return console.error(`${n} ${s.message}`),null}}f(Gi,"createSpecial_OuterSpaces");async function xi({space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}){let n=`[${xi.name}]`;try{if(!r)throw new Error("space required. (E: f01cf6a4a460486796e16d505d629522)");let s,i=ae({type:"autosyncs"}),a=await Be({type:"autosyncs",space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t});return s=_({ibGib:a}),await fe({key:i,addr:s,space:r,zeroSpace:e,fnUpdateBootstrap:t}),s}catch(s){return console.error(`${n} ${s.message}`),null}}f(xi,"createSpecial_Autosyncs");async function vi({space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}){let n=`[${vi.name}]`;try{if(!r)throw new Error("space required. (E: f01cf6a4a460486796e16d505d629522)");let s,i=ae({type:"robbots"}),a=await Be({type:"robbots",space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t});return s=_({ibGib:a}),await fe({key:i,addr:s,space:r,zeroSpace:e,fnUpdateBootstrap:t}),s}catch(s){return console.error(`${n} ${s.message}`),null}}f(vi,"createSpecial_Robbots");async function Di({space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}){let n=`[${Di.name}]`;try{if(!r)throw new Error("space required. (E: f01cf6a4a460486796e16d505d629522)");let s,i=ae({type:"apps"}),a=await Be({type:"apps",space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t});return s=_({ibGib:a}),await fe({key:i,addr:s,space:r,zeroSpace:e,fnUpdateBootstrap:t}),s=await Vr({defaultAppData:ai,defaultAppRel8ns:ci,space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}),s=await Vr({defaultAppData:li,defaultAppRel8ns:di,space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}),s=await Vr({defaultAppData:fi,defaultAppRel8ns:bi,space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}),s}catch(s){return console.error(`${n} ${s.message}`),null}}f(Di,"createSpecial_Apps");async function Vr({defaultAppData:r,defaultAppRel8ns:e,space:t,zeroSpace:o,fnUpdateBootstrap:n,fnBroadcast:s}){let i=`[${Vr.name}]`;try{S&&console.log(`${i} starting... (I: 677f68789abdc7316887e8f38c764e22)`),S&&console.log(`${i} starting...`);let a=C(r),c=e?C(e):void 0;a.uuid=!a.uuid||a.uuid===pn?await F():a.uuid;let{classname:l}=a,d=un({appData:a,classname:l}),u=await k.firstGen({ib:d,parentIbGib:k.primitive({ib:`app ${l}`}),data:a,rel8ns:c,dna:!0,linkedRel8ns:[Y.ancestor,Y.past],nCounter:!0,tjp:{timestamp:!0}});return await Q({resTransform:u,space:t}),await Ge({ibGib:u.newIbGib,fnBroadcast:s,space:t}),await Rt({type:"apps",rel8nName:Lr,ibGibsToRel8:[u.newIbGib],fnBroadcast:s,fnUpdateBootstrap:n,space:t,zeroSpace:o})}catch(a){throw console.error(`${i} ${a.message}`),a}finally{S&&console.log(`${i} complete.`)}}f(Vr,"createApp");async function Oi({type:r,space:e,zeroSpace:t,fnUpdateBootstrap:o,fnBroadcast:n}){let s=`[${Oi.name}]`;try{if(!e)throw new Error("space required. (E: c7bbafcbe901418db4c6048f17f53091)");S&&console.log(`${s} creating special of type: ${r} (I: 283c8bb30ed6f9698b74b886c6078622)`);let i,a=ae({type:r}),c=await Be({type:r,space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});return i=_({ibGib:c}),await fe({key:a,addr:i,space:e,zeroSpace:t,fnUpdateBootstrap:o}),i}catch(i){return console.error(`${s} ${i.message}`),null}}f(Oi,"createSpecial_Default");async function Ni({ibGib:r,ibGibAddr:e,existingLatest:t,existingLatestAddr:o,tjpAddr:n,space:s}){let i=`[${Ni.name}][${e}]`;try{if(S&&console.log(`${i} starting...`),!s)throw new Error("space required. (E: 64eb9a271f5d43deadec30b9638746c8)");let a=r.rel8ns?.past||[],c=t.rel8ns?.past||[];if(a.length===1&&c.length===0)return S&&console.log(`prospective has a past, so it "must" be newer. (won't quote "must" anymore)`),e;if(c.length===1&&a.length===0)return S&&console.log("existing has a past, so it must be newer."),o;if(c.length===0&&a.length===0)return console.warn(`${i} neither existing latest nor prospective new ibGib has a past, so keeping existing.`),o;if(c.includes(e))return S&&console.log("existing by definition is newer"),o;if(a.includes(o))return S&&console.log("ibGib by definition is newer"),e;if(o===e)return S&&console.log("they're the same!"),o;if(o===n&&t.rel8ns?.tjp?.length===1)return S&&console.log("ibGib must be newer because the existingLatestAddr is the tjp, which is by definition first in unique past."),e;if(e===n&&r.rel8ns?.tjp?.length===1)return S&&console.log("existing must be newer because the ibGibAddr is the tjp, which is by definition first in unique past."),o;S&&console.log(`${i} brute forcing through iterating the pasts.`);let l,d=-1,u=f(async(h,g,m)=>{let $=h.rel8ns?.past||[];if($.includes(m))return l=_({ibGib:h}),-1;if($.length===0)return g;let w=g+$.length;if(d!==-1&&w>d)return l=_({ibGib:h}),-1;let T=await ie({addr:$[0],space:s});if(!T.success||T.ibGibs?.length!==1)throw new Error(`Couldn't load past addr (xPast[0]): ${$[0]}`);return u(T.ibGibs[0],g+$.length,m)},"getPastCount");S&&console.log(`${i} doing ibGibPastCount`);let b=await u(r,0,o);if(l)return l;S&&console.log(`${i} Doing existingPastCount`),d=b;let p=await u(t,0,e);return l||(b>p?(S&&console.log(`${i} ibGibPastCount (${b}) is longer than existingPastCount (${p}), so ibGib is newer.`),l=e):(S&&console.log(`${i} existingPastCount (${p}) is longer than ibGibPastCount (${b}), so ibGib is newer.`),l=o),l)}catch(a){throw console.error(`${i} ${a.message}`),a}finally{S&&console.log(`${i} complete.`)}}f(Ni,"getLatestAddr_Brute");function dl({tagIbGib:r,space:e,zeroSpace:t,fnUpdateBootstrap:o,fnBroadcast:n}){return Rt({type:"tags",rel8nName:tn,ibGibsToRel8:[r],space:e,zeroSpace:t,fnUpdateBootstrap:o,fnBroadcast:n})}f(dl,"rel8TagToTagsIbGib");function fl({ibGibs:r,ibGibAddrs:e}){let t=`[${fl.name}]`;try{if(!r&&!e)throw new Error("either ibGibs or ibGibAddrs required. (E: 37776788620f4966b0964945ce181fc6)");r&&e&&console.warn(`${t} both ibGibs and ibGibAddrs provided. You should only provide one. Only ibGibAddrs will be checked. (W: dc13f9e197834e2daaba3bcfd08418db)`);let o=e?e.concat():r.map(n=>_({ibGib:n}));for(let n=0;n<o.length;n++){let s=o[n];if(o.filter(i=>i===s).length>1)throw new Error(`duplicate addr found: ${s} (E: 70fbef040dd449c38c667d53b8092053)`)}}catch(o){throw console.error(`${t} ${o.message}`),o}}f(fl,"throwIfDuplicates");function Tn({space:r,scope:e}){let t=`[${Tn.name}]`;try{if(S&&console.log(`${t} starting...`),!r)throw new Error("space required. (E: 3ba16e6c3e5e47948b0e63448da11752)");if(!r.data?.uuid)throw new Error("invalid space (space.data.uuid falsy) (E: 273262b32f2ef27b2e690bc699f33822)");if(!e)throw new Error("scope required. (E: f47801d6c45e2247b42a53d9b604b522)");for(;e.includes(oe);)S&&console.log(`${t} scope contains ibgib delimiter...replacing... (I: 0f456fd7cc6552a799673a0c5b4a7d22)`),e=e.replace(oe,"_");let o=r.data.uuid,n=`${js} ${o} ${e}`;return _({ib:n,gib:U})}catch(o){throw console.error(`${t} ${o.message}`),o}finally{S&&console.log(`${t} complete.`)}}f(Tn,"getSpaceLockAddr");async function Ne({space:r,scope:e,secondsValid:t,maxDelayMs:o,fn:n,callerInstanceId:s,maxLockAttempts:i}){let a=`[${Ne.name}]`;try{if(S&&console.log(`${a} starting...`),!r)throw new Error("space required. (E: 66fd8f21a5b2b572d18cdeb9472a7722)");if(!t)throw new Error("secondsValid required. (E: 92c5610e57ceede5ce83cff86d5c2a22)");if(t<0)throw new Error("secondsValid must be positive. (E: 970a7510c517235d7a355a843d18d222)");if(!n)throw new Error("fn required (E: 7022e280252ec2faf756b6db05c56e22)");let c;S&&console.log(`${a} attempting to acquire lock with scope ${e} (I: fed36d42a975b1c52897a4df804ac722)`);let l;o=(o??0)>0?o:Fs;let d=0;i=i??!1?i:qs;do{if(l=await Ci({space:r,scope:e,secondsValid:t,instanceId:s}),l?.data?.success)break;let b=Math.ceil(Math.random()*o);await de(b),d++}while(d<i);if(l?.data?.success)S&&console.log(`${a} lock acquired. (I: d847fa953ee131a57e1a89c537342722)`);else throw new Error(`could not acquire lock after ${d} attempts with intermittent delays of ${o} ms (E: 898c559dbd0c9bf20c14cf87a8f1e222)`);let u=`${a}[fn]`;try{S&&console.log(`${u} starting... (I: c2f7bedf95d3f1dd1f76de34a68d3f22)`),c=await n()}catch(b){throw console.error(`${u} ${b.message}`),b}finally{S&&console.log(`${u} unlocking space with scope: ${e} (I: 21034d9c3395499756e9000e40417d22)`),await Pi({space:r,scope:e,instanceId:s}),S&&console.log(`${u} complete. (I: 79d8ac03714a4d429c7e6c2ac6e18d22)`)}return c}catch(c){throw console.error(`${a} ${c.message}`),c}finally{S&&console.log(`${a} complete.`)}}f(Ne,"execInSpaceWithLocking");async function sr({zeroSpace:r}){let e=`[${sr.name}]`;try{if(S&&console.log(`${e} starting...`),!r)throw new Error("zeroSpace required. (E: 66fd8f21a5b2b572d18cdeb9472a7722)");let t=ot;S&&console.log(`${e} getting from zeroSpace...`);let o=await r.argy({ibMetadata:Ce({space:r}),argData:{cmd:"get",ibGibAddrs:[t]}}),n=await r.witness(o);if(n?.data?.success&&n.ibGibs?.length===1){let s=n.ibGibs[0];return S&&console.log(`${e} bootstrapibGib found: ${H(s)}`),await hn(s)?s:(S&&console.log(`${e} bootstrapIbGib was invalid. (I: cce66b26805404fc85525d565e1f8b22)`),null)}else return S&&console.log(`${e} bootstrapIbGib NOT found. (I: 421562993bf3464eb507d2967d311e22)`),null}catch(t){throw console.error(`${e} ${t.message}`),t}finally{S&&console.log(`${e} complete.`)}}f(sr,"getValidatedBootstrapIbGib");async function bl({zeroSpace:r,bootstrapIbGib:e,localSpaceId:t,lock:o,callerInstanceId:n,fnDtoToSpace:s,localSpaceCacheSvc:i}){let a=`[${bl.name}]`;try{if(!r)throw new Error("zeroSpace required. (E: 0793781a98c456a666cfa9eb960bcd22)");if(!e)if(S&&console.log(`${a} bootstrap falsy, so loading it... (I: f2366e38283495a38b5501297aa34422)`),o){let d=ot;S&&console.log(`${a} using locked version of loading bootstrap... (I: 52b9b11999674e586d051c2b23f59b22)`),e=await Ne({space:r,scope:d,fn:f(async()=>{let u=await sr({zeroSpace:r});if(u)return u;throw new Error("(UNEXPECTED) unable to get bootstrap ibgib? (E: c111dc7627acbfb992134ddf4064ea23)")},"fn"),callerInstanceId:n,secondsValid:Nr})}else S&&console.log(`${a} lock is false, so just getting the bootstrap ibgib (I: 49d55e5a824510bb3ee0ccd9f5ec3322)`),e=await sr({zeroSpace:r})??void 0;if(!e)throw new Error("bootstrapIbGib falsy. not initialized? (E: 91f5c82b5e124178d958701ebcb09822)");if(!e.data)throw new Error("(UNEXPECTED) bootstrapIbGib.data required. invalid bootstrap? (E: 568c6b837c1a39f7a25d188a90167423)");if(t=t??e.data[De],!e.rel8ns)throw new Error("(UNEXPECTED) bootstrapIbGib.rel8ns falsy? it should have been validated by now. (E: 817d9a2a0b98ec0c177cd7ab149b9426)");if(!e.rel8ns[t])throw new Error(`localSpaceId (${t}) not found in bootstrapIbGib.rel8ns (E: 8869884093984ec43f942fea24bd9926)`);let c=e.rel8ns[t][0],l=f(async()=>{let d=await r.argy({ibMetadata:Ce({space:r}),argData:{cmd:"get",ibGibAddrs:[c]}}),u=await r.witness(d);if(u?.data?.success&&u.ibGibs?.length===1){let b=u.ibGibs[0],p=await s(b);return i&&(p.cacheSvc=i),p}else throw new Error(`Could not get local space addr (${c}) specified in bootstrap space (${_({ibGib:e})}). (E: 6d6b45e7eae4472697ddc971438e4922)`)},"fnGet");return o?(S&&console.log(`${a} getting localSpaceId (${t}) WITH locking (I: c48a0e4ac5971cdbc57273dd35f8a522)`),await Ne({space:r,scope:t,fn:f(()=>l(),"fn"),callerInstanceId:n,secondsValid:Nr})):(S&&console.log(`${a} getting localSpaceId (${t}) WITHOUT locking (I: 48e504835dee4006839df8820d860b22)`),l())}catch(c){throw console.error(`${a} ${c.message}`),c}}f(bl,"getLocalSpace");async function Ci({space:r,scope:e,secondsValid:t,instanceId:o}){let n=`[${Ci.name}]`;try{if(S&&console.log(`${n} starting...`),!r)throw new Error("space required. (E: 5c0a7197a75f483a82d74e5eea60df37)");if(!e)throw new Error("scope required. (E: c7f1dde9570f4df3b450faa2c2f85122)");if(!t)throw new Error("secondsValid required and positive (E: b42b6733638b46c06c9aff59a6c49822)");if(t<0)throw new Error("secondsValid must be positive (E: bbe3b6d567583bfb35a1c0825eb29622)");let s,i=Tn({space:r,scope:e}),a,c=await ie({addr:i,space:r,force:!0});if(c.success&&c.ibGibs?.length===1?(a=c.ibGibs[0],a?.data?.expirationUTC?Ko({expirationTimestampUTC:a.data.expirationUTC})&&(console.warn(`${n} ignoring expired existing lock in space at ${i}. Should be overwritten (W: 7421c5b051724b189f88cecbbd449b22)`),a=void 0):(console.error(`${n} (UNEXPECTED) exisingLock.data.expirationUTC falsy? (E: 218dc0e935534a149d0be153c532cf25)`),a=void 0)):S&&console.log(`${n} existing lock not found for ${i} (I: 191af56ec4e2db3d19084e46bf949222)`),a){if(!a.data)throw new Error("(UNEXPECTED) existingLock.data falsy? (E: 00069b4662e5566d971760d15e293723)");s=C(a),s.data.alreadyLocked=!0,s.data.success=!1}else{let{ib:l,gib:d}=R({ibGibAddr:i});s={ib:l,gib:d,data:{scope:e,secondsValid:t,instanceId:o,expirationUTC:Ho({seconds:t})}};let u=await r.argy({ibMetadata:Ce({space:r}),argData:{cmd:"put",force:!0,ibGibAddrs:[i]},ibGibs:[s]}),b=await r.witness(u);if(b.data?.success)if((b.data.addrsAlreadyHave??[]).includes(i)){S&&console.log(`${n} racelost! addrsAlreadyHave includes spaceLockAddr (${i}) (I: 2e8a1562947c40698110b64251141753)`);let p=await ie({addr:i,space:r,force:!0});if(p.success&&p.ibGibs?.length===1){let h=p.ibGibs[0];s=C(h),s.data.alreadyLocked=!0,s.data.success=!1}else{let h=`${n} (UNEXPECTED) addrsAlreadyHave true, but couldn't get lock? (E: 8374a2b6628b49369363bc5843105763)`;console.error(h),s.data.success=!1,s.data.errorMsg=h}}else s.data.success=!0;else{let p=`${n} there was an error putting the lock in the space: ${b.data?.errors?.join("|")}`;s.data.success=!1,s.data.errorMsg=p,console.error(p)}}return s}catch(s){throw console.error(`${n} ${s.message}`),s}finally{S&&console.log(`${n} complete.`)}}f(Ci,"lockSpace");async function Pi({space:r,scope:e,instanceId:t}){let o=`[${Pi.name}]`;try{if(S&&console.log(`${o} starting...`),!r)throw new Error("space required. (E: 5c0a7197a75f483a82d74e5eea60df37)");if(!e)throw new Error("scope required. (E: c7f1dde9570f4df3b450faa2c2f85122)");let n=Tn({space:r,scope:e}),s=await In({addr:n,space:r,force:!0});if(s.success){let{ib:i,gib:a}=R({ibGibAddr:n});return{ib:i,gib:a,data:{success:!0,instanceId:t,scope:e}}}else{let i=`Delete lock in space failed. delete errorMsg: ${s.errorMsg}`;if(i.includes("not implemented"))throw new Error(i);if(i.toLowerCase().includes("does not exist")||i.toLowerCase().includes("doesn't exist")||i.toLowerCase().includes("not found")){S&&console.log(`${o} ${i} (I: b647916fd0f3e5366e9387131be21c22)`);let{ib:a,gib:c}=R({ibGibAddr:n});return{ib:a,gib:c,data:{action:"unlock",success:!0,instanceId:t,scope:e}}}else console.warn(`${o} ${i} (W: 14c84fcac15944bd9a417099964d5d9d)`)}}catch(n){throw console.error(`${o} ${n.message}`),n}finally{S&&console.log(`${o} complete.`)}}f(Pi,"unlockSpace");async function ul({space:r,zeroSpace:e,setSpaceAsDefault:t,createIfNotFound:o}){let n=`[${ul.name}]`;try{if(S&&console.log(`${n} starting...`),!r)throw new Error("space required. (E: 6fc19548fa7d1d5219e19871f280a322)");if(!r.data?.uuid)throw new Error("space.data.uuid required (E: 6483188ca6f2ed2085fd355595f3ab22)");if(!e)throw new Error("zeroSpace required. (E: abbf156e18b1018d96273e22a260f122)");let s=r.data.uuid,i=_({ibGib:r}),a=await sr({zeroSpace:e});if(a){if(S&&console.log(`${n} updating existing bootstrap (I: 977d4aa7ed47bef73b35743c05ce0722)`),a.data.spaceIds.includes(s)){S&&console.log(`${n} space already rel8d to bootstrap, possibly updating its addr (I: b5e2c515ef732d4bbcf02625a9e7c722)`);let c=a.rel8ns[s][0];c===i?S&&console.log(`${n} bootstrap already rel8d to space (I: c1be027b23e7350c64790a631cae2822)`):(S&&console.log(`${n} updating rel8ns[${s}] with newSpaceAddr (${i}). (Old address: ${c})(I: 297a9b0061fd471b8d28a06e04a6ad22)`),a.rel8ns[s]=[i])}else S&&console.log(`${n} new space being rel8d. adding spaceId to data.spaceIds and amending rel8ns (I: 40903d71719aa1d56e498299f5699a22)`),a.data.spaceIds.push(s),a.rel8ns[s]=[i];t&&(S&&console.log(`${n} setting spaceId (${s}) as default space (I: f85eda6c6ad2b0bec9750ce3c7795b22)`),a.data[De]=s)}else{if(!o){S&&console.log(`${n} bootstrapIbGib not found but createIfNotFound falsy, so returning early. (I: 5c67d85a8599a5ba4a6780f26a66ea22)`);return}S&&console.log(`${n} creating new bootstrap ibgib for spaceId (${s}) with address of (${i}) (I: 651959c27bf2ebc5be1f7f44e2b9e422)`);let{ib:c,gib:l}=R({ibGibAddr:ot});a=k.primitive({ib:c}),a.gib=l,a.data={[De]:s,[Rr]:[s]},a.rel8ns={[s]:[i]}}if(!a)throw new Error("(UNEXPECTED) bootstrapIbGib still falsy? (E: cf21d7f1756710a66aa0e6a28d762723)");S&&console.log(`${n} saving bootstrapIbGib: ${H(a)} (I: 3cceca0b98dde90e4a58a734be252322)`),await An({zeroSpace:e,bootstrapIbGib:a}),S&&console.log(`${n} complete.`)}catch(s){throw console.error(`${n} ${s.message}`),s}}f(ul,"updateBootstrapIbGib");async function An({zeroSpace:r,bootstrapIbGib:e}){let t=`[${An.name}]`;if(!r)throw new Error("zeroSpace required. (E: 818fa8430b8040dca1917f9db0972b22)");if(!e)throw new Error("bootstrapIbGib required. (E: cf21d7f1756710a66aa0e6a28d762723)");let o=await r.argy({ibMetadata:e.ib,argData:{cmd:"put",force:!0,ibGibAddrs:[_({ibGib:e})]},ibGibs:[e]});S&&console.log(`${t} zeroSpace will witness/put... (I: 1be9aca22ffc4951b6690965a7aeae5b)`);let n=await r.witness(o);if(n?.data?.success)S&&console.log(`${t} zero space put complete. (I: ac3056d655e841f1a3c442bcc64942f9)`);else throw new Error(`${n?.data?.errors?.join("|")||"There was a problem with zeroSpace witnessing the bootstrap^gib primitive."}`)}f(An,"persistBootstrapIbGibInZeroSpace");async function pl({spaceId:r,zeroSpace:e}){let t=`[${pl.name}]`;if(!r)throw new Error("spaceId required. (E: 52f9c31405e24c2999e5a1b32d201a23)");if(!e)throw new Error("zeroSpace required. (E: a115f4007b2c4819a58cf093d5823b23)");await Ne({space:e,scope:ot,fn:f(async()=>{let n=await sr({zeroSpace:e});if(!n)throw new Error("bootstrapIbGib falsy in zeroSpace (E: e36a512781b0467ba1bf1d927a7c1d23)");if(!n.data)throw new Error("bootstrapIbGib.data falsy in zeroSpace (E: 8f92104192b44d71891b092481029ab0)");let s=n.data,i=s[Rr]??[];if(i.length<=1)throw new Error(`Cannot delete space (${r}). It is the only remaining local space. (E: 9c27f71120014b08b5e9f89993380e23)`);if(r===s[De])throw new Error(`Cannot delete space (${r}). It is the default local space. Please select a new default space before deleting. (E: f3c30a5170d14b4fb2478d102e3b2e23)`);if(!i.includes(r))throw new Error(`Space (${r}) not found in bootstrap spaceIds. (E: 61fa940e79124430a618e470bc551d23)`);s[Rr]=i.filter(a=>a!==r),n.rel8ns&&delete n.rel8ns[r],await An({zeroSpace:e,bootstrapIbGib:n})},"fn"),secondsValid:Nr})}f(pl,"deregisterLocalSpaceFromBootstrap");async function hl({spaceId:r,zeroSpace:e}){let t=`[${hl.name}]`;if(!r)throw new Error("spaceId required. (E: 7c2a10529a1b412a8069e22e5190b623)");if(!e)throw new Error("zeroSpace required. (E: f112a512019c41a590b512a8e0915623)");let o=await e.argy({ibMetadata:Ce({space:e}),argData:{cmd:"get",ibGibAddrs:[r]}}),n=await e.witness(o);if(n?.data?.success&&(n.ibGibs?.length??0)>0){let s=_({ibGib:n.ibGibs[0]}),i=await e.argy({ibMetadata:Ce({space:e}),argData:{cmd:"delete",ibGibAddrs:[s]}});await e.witness(i)}}f(hl,"deleteSpaceRecordFromZeroSpace");function Ce({space:r}){return`${r.ib} ${$e()}`}f(Ce,"getSpaceArgMetadata");function dh({space:r}){return`${r.ib} ${$e()}`}f(dh,"getSpaceResultMetadata");function gl({space:r,spaceData:e,classname:t}){let o=`[${gl.name}]`;try{if(!r&&!e)throw new Error("either space or spaceData required (E: 4dabec34ee77d67c9cc30ee3c3049622)");if(r&&!r.data)throw new Error("(UNEXPECTED) given space has falsy space.data? (E: 058d298876ebbeada7bbddb9e3da2f23)");if(r&&e){if(r.data.uuid!==e.uuid)throw new Error("(UNEXPECTED) both space and spaceData given, but uuid don't match? (E: efdd4603cba93a17340a76811fe56b24)");if(r.data.n!==e.n)throw new Error("(UNEXPECTED) both space and spaceData given, but n don't match? (E: e51278a707c9bccc57a08a4b86524524)")}if(e??=r.data,!e)throw new Error("(UNEXPECTED) spaceData falsy? (thought this was a compiler problem that this was even possible.) (E: b3c7ffedcae4b1f45b263b3825930b24)");if(t&&e.classname&&t!==e.classname)throw new Error(`both classname arg (${t}) and spaceData.classname (${e.classname}) are different truthy values. (E: f98f012ee876eb8fbe7403f7b53e4624)`);if(t||=e.classname,!t)throw new Error("classname required (E: fa3af4613ad56742dab51d1b0d839322)");if(t.includes(" "))throw new Error(`invalid classname (${t}). cannot contain spaces (E: 243adbf720dcce7904e2665933208b22)`);let n=e?.name||Bs;if(n.includes(" "))throw new Error("invalid space name. cannot contain spaces (E: a8450e1651081412c8ac018520182422)");let s=e?.uuid||void 0;if(!s)throw new Error("invalid space, spaceData.uuid falsy (E: 50ae723a9ab24f4fc7132613e65faf23)");if(s.includes(" "))throw new Error("invalid space id. cannot contain spaces (E: 8696830fe7f54bfa85e670a063f3e089)");let i=e.type??void 0,a=e.subtype??void 0;if(i&&!a)throw new Error(`spaceType (${i}) is set but spaceSubtype is falsy. (E: 878ab960d7987ae2331103b4a00d0d24)`);return`${Hr} ${Or} ${t} ${n} ${s} ${i} ${a}`}catch(n){throw console.error(`${o} ${n.message}`),n}}f(gl,"getSpaceIb");function ml({ib:r}){let e=`[${ml.name}]`;if(!r){let t=`${e} ib required (E: dd5244f62f964359a86e59bb08ee47e6)`;throw console.error(t),new Error(t)}return r.startsWith(`${Hr} ${Or} `)}f(ml,"isSpaceIb");function Wr({spaceIb:r}){let e=`[${Wr.name}]`;try{if(!r)throw new Error("spaceIb required (E: fa5424cfb7e846e2851562f2f417944f)");let[t,o,n,s,i,a,c]=r.split(" ");if(t!==Hr)throw new Error(`invalid spaceIb (${r}). witnessAtom !== WITNESS_ATOM (E: 5ae1ca12cf8f30ae341f3e582b025224)`);if(o!==Or)throw new Error(`invalid spaceIb (${r}). spaceAtom !== SPACE_ATOM (E: 9cc6b6f30e13455eb29748148a94fa0f)`);if(!n)throw new Error(`invalid spaceIb (${r}). spaceClassname falsy (E: 00d3392da007ca8b2840b16b199d9a24)`);if(!s)throw new Error(`invalid spaceIb (${r}). spaceName falsy (E: b957d8e74ef34d889fa64c60c7a5ea0b)`);if(!i)throw new Error(`invalid spaceIb (${r}). spaceId falsy (E: 7a1773722d8e46a0866d683130b65b89)`);let l;if(a&&a!=="undefined")if(fn.includes(a))l=a;else throw new Error(`invalid spaceIb (${r}). spaceType (${a}) is set but not a valid type. valid types: ${fn.join(", ")} (E: 838f4638a88cfbf3545a3a3a38b6dd24)`);let d;if(c&&c!=="undefined")if(bn.includes(c))d=c;else throw new Error(`invalid spaceIb (${r}). spaceSubtype (${c}) is set but not a valid subtype. valid subtypes: ${bn.join(", ")} (E: 5bdcf23027f94e73860e4340313b04ab)`);return{spaceClassname:n,spaceName:s,spaceId:i,spaceType:l,spaceSubtype:d}}catch(t){throw console.error(`${e} ${t.message}`),t}}f(Wr,"parseSpaceIb");async function _e({ibGibs:r,addrs:e,tjps:t,tjpAddrs:o,space:n}){let s=`[${_e.name}]`;try{if(S&&console.log(`${s} starting...`),!n)throw new Error("space required. (E: 4d188d6c863246f28aa575753a052304)");if(r=r??[],e=e??[],t=t??[],o=o??[],e.length===0&&r.length===0&&t.length===0&&o.length===0)throw new Error("Either addrs, ibGibs, tjps, or tjpAddrs required. (E: 7c6ebfbab98d4d21a431b144457fd991)");let i=new Set(o.concat(t.map(l=>_({ibGib:l})))),a=Array.from(i).map(l=>R({ibGibAddr:l}).gib);r.map(l=>_({ibGib:l})).concat(e).forEach(l=>{let{gib:d}=R({ibGibAddr:l});a.some(b=>d.includes(b))||i.add(l)}),S&&console.log(`${s}[testing] ${n.data?.name||n.ib} (${n.data?.uuid||"[space.data.uuid falsy]"}) addrsToQuery: ${Array.from(i)} (I: 8a2202912c364238b6d6eb09577bc246)`);let c=await n.argy({ibMetadata:Ce({space:n}),argData:{cmd:"get",cmdModifiers:["latest","addrs"],ibGibAddrs:Array.from(i)}});return await n.witness(c)}catch(i){throw console.error(`${s} ${i.message}`),i}}f(_e,"getLatestAddrs");function Sn({ibGib_Context:r}){let e=`[${Sn.name}]`;try{if(S&&console.log(`${e} starting... (I: 5f583fd94d27731a65d514e731b8aa22)`),!ir({ibGib:r}))return;if(["roots","autosyncs"].some(o=>r.ib.includes(o)))throw new Error("cannot perform a modification of this type on this special ibgib (E: b8fb718a7323fc54454464b973412722)")}catch(t){throw console.error(`${e} ${t.message}`),t}finally{S&&console.log(`${e} complete.`)}}f(Sn,"throwIfContextIsSpecial");async function El({ibGib_Context:r,rel8nName_Context:e,addr:t,space:o,zeroSpace:n,fnUpdateBootstrap:s,fnBroadcast:i}){let a=`[${El.name}]`;try{if(S&&console.log(`${a} starting... (I: 2dc486bb2d516e4534f437aaf5ec7f22)`),!r)throw new Error("ibGib_Context required (E: 75f7bfa93145d6dffe85d488443ca722)");if(!e)throw new Error("rel8nName_Context required (E: 12aaa43de9e34b68b25dc9a2a68ad6b9)");if(!t)throw new Error("addr required (E: e27df3bdc5a2554697cc9597afc4e422)");if(!o)throw new Error("space required (E: 2e3562486ed2956a770ed9e8d77a3f22)");let c=ir({ibGib:r});c&&Sn({ibGib_Context:r});let l=await ye({src:r,rel8nsToAddByAddr:{[Ys]:[t]},rel8nsToRemoveByAddr:{[e]:[t]},dna:!0,nCounter:!0});if(await Q({resTransform:l,space:o}),c){let d=_({ibGib:l.newIbGib}),u=zr({ib:r.ib}),b=ae({type:u});await fe({key:b,addr:d,space:o,zeroSpace:n,fnUpdateBootstrap:s})}await Ge({ibGib:l.newIbGib,fnBroadcast:i,space:o})}catch(c){throw console.error(`${a} ${c.message}`),c}finally{S&&console.log(`${a} complete.`)}}f(El,"trash");async function wl({ibGib_Context:r,rel8nName_Context:e,addr:t,space:o,zeroSpace:n,fnUpdateBootstrap:s,fnBroadcast:i}){let a=`[${wl.name}]`;try{if(S&&console.log(`${a} starting... (I: 38098552b830495187299bb24fcddff0)`),!r)throw new Error("ibGib_Context required (E: d819e8c4db5b4c0bb721300ba434cd40)");if(!e)throw new Error("rel8nName_Context required (E: de061adff8c04429a211aa09116a532d)");if(!t)throw new Error("addr required (E: 7059ebb8ef6149ea94e22f961d6b5c81)");if(!o)throw new Error("space required (E: e19566f2d42347798621447edcae312e)");let c=ir({ibGib:r});c&&Sn({ibGib_Context:r});let l=await ye({src:r,rel8nsToAddByAddr:{[Xs]:[t]},rel8nsToRemoveByAddr:{[e]:[t]},dna:!0,nCounter:!0});if(await Q({resTransform:l,space:o}),c){let d=_({ibGib:l.newIbGib}),u=zr({ib:r.ib}),b=ae({type:u});await fe({key:b,addr:d,space:o,zeroSpace:n,fnUpdateBootstrap:s})}await Ge({ibGib:l.newIbGib,fnBroadcast:i,space:o})}catch(c){throw console.error(`${a} ${c.message}`),c}finally{S&&console.log(`${a} complete.`)}}f(wl,"archive");function $l(r){let e=`[${$l.name}]`;try{if(!r)return console.error(`${e} name is falsy`),!1;let t=/[\w-]+/,o=r.match(t);if(o?.length!==1||o[0].length!==r.length)return console.error(`${e} name can only contain letters, numbers, underscores, hyphens`),!1;let n=/[a-zA-Z\d]/;return r[0].match(n)?!0:(console.error(`${e} name must start with a letter or number`),!1)}catch(t){return console.error(`${e} ${t.message}`),!1}}f($l,"spaceNameIsValid");var W=!1;function Ah(r,e){return typeof r=="object"&&r!==null?`v:1^spaceId:${r.spaceId}^${r.ibGibAddr}`:`v:1^spaceId:${r}^${e}`}f(Ah,"getSpaceQualifiedIbGibAddr");function yl(r){try{if(typeof r!="string"||!r.match(Pr))return!1;let t=Dn({sqAddr:r});return!0}catch{return!1}}f(yl,"isSpaceQualifiedAddr");function Dn({sqAddr:r}){let e=`[${Dn.name}]`;if(!r)throw new Error(`${e} sqAddr falsy (E: 3c7af8b05a68272478e830c89b617d26)`);if(typeof r!="string")throw new Error(`(UNEXPECTED) ${e} sqAddr not a string? (E: 172fd36b0e7d02905263bdef1374da26)`);let t=r.match(Pr);if(!t)throw new Error(`${e} invalid sqAddr (${r}). does not match SQ Addr regexp: ${Pr.source} (E: 71c93b63d4a82970c3bada8d92d4f826)`);let o=t[1],n=parseInt(o,10),s=t[2],i=t[3],a=tt({addr:i})??[];if(a.length>0)throw new Error(`${e} invalid sqAddr. ibGibAddr part is not a valid ibGibAddr. errors: ${a.join(",")} (E: 8e105870eb58c78978169d1d7b275526)`);let{ib:c,gib:l}=R({ibGibAddr:i});return{version:n,spaceId:s,ibGibAddr:i,ib:c,gib:l}}f(Dn,"parseSpaceQualifiedIbGibAddr");async function Il({ibGib:r,rel8nNames:e,space:t}){let o=`[${Il.name}]`;try{if(!r)throw new Error("ibGib required (E: genuuid)");if(!t)throw new Error("space required (E: genuuid)");e||(e=Object.keys(r.rel8ns||{}));let n={};for(let s of e){let i=r.rel8ns?.[s]||[];if(i.length>0){let a=await ie({addrs:i,space:t});if(a.success&&a.ibGibs?.length===i.length)n[s]=a.ibGibs.concat();else throw new Error(`Problem getting rel8d ibgibs for rel8nName: ${s}. ${a.errorMsg||"Unknown error"} (E: genuuid)`)}else n[s]=[]}return n}catch(n){throw console.error(`${o} ${E(n)}`),n}}f(Il,"getRel8dIbGibs");async function Oe({parentPrimitiveIb:r,ib:e,ibRegExpPattern:t,data:o,rel8ns:n}){let s=`[${Oe.name}]`;try{if(!r)throw new Error("parentPrimitiveIb required. (E: 88ddf188cc5a4340b597abefba1481e2)");if(rt({ib:r})!==null)throw new Error(`Invalid parentPrimitiveIb: ${r}. (E:5aec0320956d492ebeeaca41eb1fe1c6)`);if(!e)throw new Error("ib required. (E: 7bbc88f4f2e842d6b00126e55b1783e4)");let i=t?new RegExp(t):ks;if(!e.match(i))throw new Error(`invalid ib. does not match regexp (${i})`);let a=Object.keys(n??{}),c=[...Qe,"tjp"];if(a.some(b=>c.includes(b)))throw new Error(`Invalid rel8ns. forbiddenRel8nNames: ${c}. rel8ns keys: ${Object.keys(n??{})}. (E: 837a993c265c4362b6aa0b1a234ea5f8)`);let u=(await k.firstGen({ib:e,parentIbGib:k.primitive({ib:r}),data:o,rel8ns:n,dna:!1,noTimestamp:!0,nCounter:!1})).newIbGib;return u?.rel8ns?.past&&delete u.rel8ns.past,u?.rel8ns?.tjp&&delete u.rel8ns.tjp,u?.rel8ns?.identity&&delete u.rel8ns.identity,u.gib=await V({ibGib:{ib:u.ib,data:u.data,rel8ns:u.rel8ns},hasTjp:!1}),u}catch(i){throw console.error(`${s} ${i.message}`),i}}f(Oe,"constantIbGib");function Sh({binHash:r,binExt:e,binEncoding:t}){return t?e?`bin ${r} ${e} enc=${t}`:`bin ${r} enc=${t}`:e?`bin ${r} ${e}`:`bin ${r}`}f(Sh,"getBinIb");function Gh({addr:r}){return Li({addr:r})}f(Gh,"getBinHashAndExt");function Li({addr:r}){let e=`[${Li.name}]`;try{if(!or({addr:r}))throw new Error("not a bin address (E: df0804d129bc4888bd6939cb76c5e0f6)");let{ib:t}=R({ibGibAddr:r}),o=t.split(" ");if(o.length===2)return{binHash:o[1],binExt:""};if(o.length===3)return o[2].startsWith("enc=")?{binHash:o[1],binExt:"",binEncoding:o[2].substring(4)}:{binHash:o[1],binExt:o[2]};if(o.length===4){if(!o[3].startsWith("enc="))throw new Error(`bin ib (${t}) has 4 space-delimited pieces. we expect therefore the form to be bin \${binHash} \${binExt} enc=\${binEncoding}. but ibPieces[3] doesn't start with "enc=". (E: 87196d7cdd7c12d982cc8204a1163524)`);return{binHash:o[1],binExt:o[2],binEncoding:o[3].substring(4)}}else throw new Error('(UNEXPECTED) ibPieces.length not 2, 3, or 4? atow (01/2024) the only components of a bin ib are: atom, binHash, binExt, binEncoding. binExt and binEncoding are optional, with binEncoding being prefixed with "enc=". (E: b05df3c1b3949f76464a83c9fd1c4f24)')}catch(t){throw console.error(`${e} ${t.message}`),t}}f(Li,"parseBinIb");function or({ibGib:r,addr:e}){let t=`[${or.name}]`;try{if(!r&&!e)throw new Error("either ibGib or addr required. (E: c935b51e773f41a2a547c556e9dc16c6)");if(r&&!r.data)return!1;e=e||_({ibGib:r});let{ib:o,gib:n}=R({ibGibAddr:e});if(!o||!n||!o.startsWith("bin "))return!1;if(n.length!==64)throw new Error('ib starts with "bin " but gib length is not 64, so return false. Two things: 1) bin ibgibs are expected to be stones, i.e., have no temporal junction point and only a single punctiliar hash for the gib. the default hash used atow (01/2024) is sha-256, so the length should be 64. But this may not be true if using another hash algorithm. need to change this function when this becomes the case. (W: 60725d65d13c4b4fbb7b96d7feb19d67)');let s=o.split(" ");if(s.length===2){if(!s[1].match(re))throw new Error('(UNEXPECTED) ib starts with "bin " but space-delimited !ibPieces[1].match(UUID_REGEXP)? (E: f6baca2ff155f1017b278a5d7597a224)')}else if(s.length===3){if(!s[1].match(re))throw new Error('(UNEXPECTED) ib starts with "bin " but space-delimited !ibPieces[1].match(UUID_REGEXP)? (E: 8d0443d6cada4b50be79a8390a7a426c)')}else if(s.length===4){if(!s[1].match(re))throw new Error('(UNEXPECTED) ib starts with "bin " but space-delimited !ibPieces[1].match(UUID_REGEXP)? (E: 3209eacc0a3848a59593d4c3ee956191)');if(!s[3].startsWith("enc="))throw new Error('(UNEXPECTED) ib starts with "bin " but space-delimited !ibPieces[3].startsWith("enc=")? (E: 4c8a0c3b07a90d30e3d1a4373d57d824)')}else throw new Error('(UNEXPECTED) ib starts with "bin " but space-delimited ibPieces length is not 2, 3 or 4? (E: c7eccf88518304997c7e42b32e08d224)');return!0}catch(o){throw console.error(`${t} ${o.message}`),o}}f(or,"isBinary");function Gn({type:r}){if(!r.match(rn))throw new Error(`special ibgib type must not have spaces and just be alphanumerics. regexp: ${rn.source} (E: 6c1c92521b7f076cc4666e4915593723)`);return`meta special ${r}`}f(Gn,"getSpecialIbGibIb");function zr({ib:r}){let e=`[${zr.name}]`;try{if(W&&console.log(`${e} starting... (I: c82ba222bd345ee6b695df4d63a23322)`),!r)throw new Error("ib required (E: 08897145f7138e644fe01c4a59353322)");if(!ir({ib:r}))throw new Error("ib is not special (E: 174aff63b992adff3ac2394643735922)");let t=r.split(" ");if(t.length<3)throw new Error('invalid ib. should be space-delimited in form of "meta special [type]" (E: ffd89e2cbe63427f98634ab897aab222)');let o=t[2];return Object.values(Dr).some(n=>n===o)||console.warn(`unknown special type (${o}). This may be expected, but atow I am adding special types to the SpecialIbGibType enum-like. (W: f4e26c3ebb57fe49d69014a4ba32a922)`),o}catch(t){throw console.error(`${e} ${t.message}`),t}finally{W&&console.log(`${e} complete.`)}}f(zr,"getSpecialTypeFromIb");function _l({type:r}){return`${Gn({type:r})}^${U}`}f(_l,"getSpecialIbGibAddr");function ae({type:r}){return`${zs} ${_l({type:r})}`}f(ae,"getSpecialConfigKey");function ir({ib:r,ibGib:e}){if(!r&&!e?.ib)throw new Error("either ib or ibGib.ib required (E: b4cf539638d7966c2e351987f55e1a23)");return(r??e?.ib)?.startsWith("meta special")}f(ir,"isSpecial");function xn(r){let e=`[${xn.name}]`;if(!r)throw new Error(`${e} text required.`);return`root ${r}`}f(xn,"getRootIb");function $t(r){let e=`[${$t.name}]`;if(!r)throw new Error(`${e} tag required.`);return`tag ${r}`}f($t,"tagTextToIb");function Jr({ibGibs:r,filterPrimitives:e}){let t=`[${Jr.name}]`;try{let o={},n={},s={};return(e?r.filter(a=>a.gib??a.gib!==U):r).forEach(a=>{Ri({ibGib:a})?(a.rel8ns?.dna??[]).length>0?o[a.gib]=a:n[a.gib]=a:s[a.gib]=a}),{mapWithTjp_YesDna:o,mapWithTjp_NoDna:n,mapWithoutTjps:s}}catch(o){throw console.error(`${t} ${o.message}`),o}}f(Jr,"splitPerTjpAndOrDna");function ar({ibGibs:r}){let e=`[${ar.name}]`;try{W&&console.log(`${e} starting...`);let{mapWithTjp_YesDna:t,mapWithTjp_NoDna:o}=Jr({ibGibs:r,filterPrimitives:!0}),n={...t,...o},s=Object.values(n),i=qo({items:s,keyFn:f(a=>a.data?.isTjp?_({ibGib:a}):a.rel8ns?.tjp?a.rel8ns?.tjp[0]??"":(W&&console.log(`${e} neither isTjp nor x.rel8ns.tjp truthy (I: ec9a5597bf53dec1bd3d83350abbf823)`),""),"keyFn")});return W&&console.log(`${e} sorting (ascending) ibGibsWithTjpGroupedByTjpAddr: ${H(i)} (I: 9b9fff5ce61444a6cb06d62db9a99422)`),Object.entries(i).forEach(([a,c])=>{c.some(l=>l.data?.n===void 0)&&console.warn(`${e} timeline includes ibgibs with ibGib.data?.n === undefined (W: cab9a6b64a38c4279fe82c3569bbab22)`),c.sort((l,d)=>(l.data?.n??-1)>(d.data?.n??-1)?1:-1)}),W&&console.log(`${e} after sort ibGibsWithTjpGroupedByTjpAddr: ${H(i)} (I: 9b9fff5ce61444a6cb06d62db9a99422)`),i}catch(t){throw console.error(`${e} ${t.message}`),t}finally{W&&console.log(`${e} complete.`)}}f(ar,"getTimelinesGroupedByTjp");function Ri({ibGib:r}){let e=`[${Ri.name}]`;if(!r)throw new Error("(UNEXPECTED) ibGib falsy? (E: ce3a59f9db14e6158bb2c438ca1a3823)");if((r.rel8ns?.tjp?.length??0)>0||r.data?.isTjp)return!0;let t=["fork^gib","mut8^gib","rel8^gib"];return(r.rel8ns?.ancestor??[]).some(n=>t.includes(n))?!1:r.gib?r.gib.includes(Ue)?!0:r.gib===U?!1:!!ne({ibGibAddr:_({ibGib:r})}).tjpGib:(console.warn(`${e} ibGib.gib falsy. (W: 6400d780822b44d992846f1196509be3)`),!1)}f(Ri,"hasTjp");function he({ibGib:r,defaultIfNone:e="undefined"}){let t=`[${he.name}]`;try{let o=Ui({ibGibs:[r],defaultIfNone:e});return o&&Object.keys(o).length===1?Object.values(o)[0]:void 0}catch(o){throw console.error(`${t} ${o.message}`),o}}f(he,"getTjpAddr");function Ui({ibGibs:r,defaultIfNone:e="undefined"}){let t=`[${Ui.name}]`;try{let o={};return r.forEach(n=>{let s=_({ibGib:n}),i;n.rel8ns?.tjp?.length??!1?i=n.rel8ns.tjp[n.rel8ns.tjp.length-1]:n.data?.isTjp||e==="incomingAddr"?i=s:i=void 0,o[s]=i}),o}catch(o){throw console.error(`${t} ${o.message}`),o}}f(Ui,"getTjpAddrs");async function vn({ibGib:r,naive:e=!0}){let t=`[${vn.name}]`;try{if(!r)throw new Error("ibGib required.");if(e){if(r.data)return r.data.isTjp?!0:r.rel8ns?r.rel8ns.past&&r.rel8ns.past.length>0?!1:!!(r.rel8ns.past&&r.rel8ns.past.length===0):(W&&console.log(`${t} ibGib.rel8ns falsy (I: c69c9e78b34845311ce7c674d7195622)`),!1);throw new Error("loaded ibGib required (data).")}else throw new Error("only naive implemented right now.")}catch(o){throw console.error(`${t} ${o.message}`),o}}f(vn,"isTjp_Naive");function ve({ibGib:r}){let e=`[${ve.name}]`;r.ib||console.warn(`${e} ibGib.ib is falsy. (W: e60e41c2a1fc48268379d88ce13cb77b)`),r.gib||console.warn(`${e} ibGib.gib is falsy. (W: fb3889cbf0684ae4ac51e48f28570377)`);let t={ib:(r.ib||"").slice()};return r.gib&&(t.gib=r.gib.slice()),r.data&&(or({ibGib:r})?t.data=r.data.slice():t.data=C(r.data)),r.rel8ns&&(t.rel8ns=C(r.rel8ns)),t}f(ve,"toDto");function On(r){let e=`[${On.name}]`;try{return W&&console.log(`${e} starting... (I: 57aef93fc6cc2309523b5c72a6b11823)`),!!r&&typeof r.ib=="string"}catch(t){throw console.error(`${e} ${t.message}`),t}finally{W&&console.log(`${e} complete.`)}}f(On,"isIbGib");function rr({ibGib:r,data:e,timestamp:t}){let o=`[${rr.name}]`;try{W&&console.log(`${o} starting... (I: 35cb68744bcf6139d78e37de644fad23)`),t=t||e?.timestamp||r?.data?.timestamp;let n=r?.data?.timestampMs||e?.timestampMs;if(!t){let s=`${o} timestamp is falsy. (W: 5f1f1182c8804807b886a3d922ac3dcf)`;return console.warn(s),{valid:!1,emsg:s}}if(typeof t=="string")if(Number.isInteger(Number.parseInt(t))){let s=Number.parseInt(t),i=new Date;if(i.setTime(s),i.toString()!==Cr)return W&&console.log(`${o} valid timestampInTicks string (I: 7069a1c3047f3bbc92b78674b20f5b23)`),{valid:!0,date:i,utc:i.toUTCString(),ticks:i.getTime().toString(),ms:n};{let a=`${o} data.timestamp (${t}) is an integer string but not a valid timestampInTicks string. (produces invalid date) (E: f49fbb600fe1426c8805dfc8afbe5cf3)`;return console.error(a),{valid:!1,emsg:a}}}else{let s=new Date(t);if(s.toString()!==Cr)return{valid:!0,date:s,utc:s.toUTCString(),ticks:s.getTime().toString(),ms:n};{let i=`${o} data.timestamp is a non-integer string but not a valid date timestamp string (new date instantiated produces invalid date). (W: c6c90f7f3bfb49838d2081ba84fdb5fb)`;return console.warn(i),{valid:!1,emsg:i}}}else if(typeof t=="number")if(Number.isInteger(t)){console.warn(`${o} expected data.timestamp to be a string but is a number (W: 9d786f4d4e8d4279b5af7bee19bf721b)`);let s=new Date;if(s.setTime(t),s.toString()!==Cr)return{valid:!0,date:s,utc:s.toUTCString(),ticks:s.getTime().toString(),ms:n};{let i=`${o} timestamp (${t}) is an integer number but not a valid timestampInTicks (new date setTime produces invalid date). (W: c6c90f7f3bfb49838d2081ba84fdb5fb)`;return console.warn(i),{valid:!1,emsg:i}}}else{let s=`${o} timestamp (${t}) is a non-integer number (supposed to be a string either timestamp string or ticks). (E: 2963d95f8d3b464c992b0bff948b4479)`;return console.error(s),{valid:!1,emsg:s}}else{let s=`${o} unknown typeof timestamp (${typeof t}). (E: 12458a9c16c84e4f859b5771a30dd2ef)`;return console.error(s),{valid:!1,emsg:s}}}catch(n){throw console.error(`${o} ${E(n)}`),n}finally{W&&console.log(`${o} complete.`)}}f(rr,"getTimestampInfo");async function Nn({addrs:r,readCache_graph:e,readCache_array:t,space:o}){let n=`[${Nn.name}]`;try{W&&console.log(`${n} starting... (I: 5db66871239dfa05182277f886a20926)`),e??={},t??=[];let s={...e};t.forEach(l=>s[_({ibGib:l})]=l);let i=Object.keys(e),a=r.filter(l=>!i.includes(l));if(a.length>0){W&&console.log(`${n} ${a.length} addrsNotFoundInCache: ${a} (I: fccbd18116ffb849f813aaebfc6c0826)`);let l=[o],d=a.concat();for(let u of l){let b=await ie({addrs:d,space:u});if(b.success&&b.ibGibs&&b.ibGibs.length===d.length)b.ibGibs.forEach(p=>s[_({ibGib:p})]=p),d=[];else if(b.ibGibs&&b.ibGibs.length>0){if(d=d.filter(p=>!b.ibGibs.some(h=>_({ibGib:h})===p)),d.length===0)break}else W&&console.log(`${n} no addrs found in space (${u.ib}). trying next space. (I: 4f99d8bacbb10ab3f8737a752564b326)`)}if(d.length>0)throw new Error(`could not get all addrs from cache or spaces. addrsStillNotFound: ${d}. spaces: ${l.map(u=>u.ib).join("|")} (E: 0c6418f83dd85bda886e56f5b98f3126)`)}let c=[];for(let l of r){let d=s[l];if(!d)throw new Error(`(UNEXPECTED) allIbGibs_graph doesn't have addr? We're expecting logic to preclude this at this point. addr: ${l} (E: f68e1d236ae5e3eb08da9933c8230626)`);c.push(d)}return c}catch(s){throw console.error(`${n} ${E(s)}`),s}finally{W&&console.log(`${n} complete.`)}}f(Nn,"getIbGibsFromCache_fallbackToSpaces");async function ki({addr:r,space:e,metaspace:t}){let o=`[${ki.name}]`;try{if(W&&console.log(`${o} starting... (I: 9252059c96132637381b3be5486e6826)`),!r)throw new Error("(UNEXPECTED) addr falsy? (E: aeb9084d7f68dabb8a49fd68526ff826)");if(!e)throw new Error("(UNEXPECTED) space falsy? (E: 3ec9df4de82847e13f087bea6f98b826)");let n=yl(r)?Dn({sqAddr:r}).ibGibAddr:r,s=tt({addr:n})??[];if(s.length>0)throw new Error(`invalid incoming addr (${r}). (if space-qualified, then invalid extracted ibGibAddr). errors: ${s.join(", ")} (E: 040dbbcac39990abc8871a1d08b3d826)`);let i;try{let a=await ie({space:e,addrs:[n]});if(!a.success||a.errorMsg)throw new Error(`resGet failed. resGet.success: ${a.success}.errorMsg: ${a.errorMsg} (E: 13f3d82381b87f8078583ad8b3676826)`);if(!a.ibGibs)throw new Error("(UNEXPECTED) resGet.success and no errorMsg, but resGet.ibGibs falsy? (E: f3a75e6fe96b07d288ba9b3976e84826)");if(a.ibGibs.length===0)throw new Error("(UNEXPECTED) resGet.success and no errorMsg, but resGet.ibGibs empty? (E: 4a06589d30050208284fef68adf20426)");if(a.ibGibs.length>1)throw new Error("(UNEXPECTED) resGet.success and no errorMsg, but resGet.ibGibs.length > 1? what in the world? (E: a4d01caa4a78a0a1581b3bb8748af826)");i=a.ibGibs[0]}catch(a){W&&console.log(`${o} suppressing error: ${E(a)} (I: 1256ce73d8e8b567ff4fee4ea48c5d26)`)}return i}catch(n){throw console.error(`${o} ${E(n)}`),n}finally{W&&console.log(`${o} complete.`)}}f(ki,"getIbGibFromSpace");async function Tl({ibGib:r,space:e}){let t=`[${Tl.name}]`;try{W&&console.log(`${t} starting... (I: 64f6a8bd1248f8c3c8c86834431adb26)`);let o=_({ibGib:r}),n=he({ibGib:r,defaultIfNone:"undefined"});if(!n)return W&&console.log(`${t} tjpAddr falsy. returning incoming ibGib (no timeline means no latest tip possible) (I: 621528e00b6988f0abb8a161e7042226)`),r;let s=await _e({ibGibs:[r],space:e});if(!s)throw new Error("(UNEXPECTED) resLatest falsy? (E: 8ce878315ec4020c082ee7796084b826)");if(!s.data)throw new Error("(UNEXPECTED) resLatest.data falsy? (E: 3af5a84dd1eba399fcca51e179b36826)");if(!s.data.latestAddrsMap)throw new Error("(UNEXPECTED) resLatest.data.latestAddrsMap falsy? (E: 37276c35ae58f65cb674389343c2fc26)");let{latestAddrsMap:i}=s.data,a=i[o]??i[n]??o;if(a&&a!==o){let c=await ki({addr:a,space:e});if(c&&(c.data?.n??0)>=(r.data?.n??0))return c;console.warn(`${t} did not find latest. using incoming ibGib (W: 1079fd20b9183fc8a8fef55a8ad2d826)`)}return r}catch(o){throw console.error(`${t} ${E(o)}`),o}finally{W&&console.log(`${t} complete.`)}}f(Tl,"resolveLatestIbGibInSpace");var Mi=!1,Al="space_gib_db",Sl="space_gib_store",Gl="space_gib_api_key";var xl="agent";var Nh=$t(xl);var Ch={dbName:Al,storeName:Sl,additionalStoreNames:[Ms],apiKeyName:Gl};var Bi="0.0.23";var at=!1,Uh="[web^gib timer]",Zr="ibgib";var vl="agent",kh="body-outline",Mh="This tag tracks the active agents for the current local user space.",Bh=$t(vl),ji="#78f87e88",Fi="#78f87e10",qi="#ffffff";var jh="AUTOMATED_TEXT";var Pe=!1;function Hi(r){return new Promise((e,t)=>{let o=new Blob([r],{type:"application/octet-stream"}),n=new FileReader;n.onload=()=>{let i=n.result.split(",")[1];e(i)},n.onerror=s=>t(s),n.readAsDataURL(o)})}f(Hi,"uint8ArrayToBase64");async function Ki(r){let e=`data:application/octet-stream;base64,${r}`,n=await(await(await fetch(e)).blob()).arrayBuffer();return new Uint8Array(n)}f(Ki,"base64ToUint8Array");async function Qr({graph:r}){let e=`[${Qr.name}]`;try{Pe&&console.log(`${e} starting... (I: 4ddb8803cf68e1d3d35f60680cb69825)`);let t=JSON.parse(JSON.stringify(r));for(let n in t)r[n].data instanceof Uint8Array&&(t[n].data={_dataType:"Uint8Array_Base64",value:await Hi(r[n].data)});let o=JSON.stringify(t);return Pe&&console.log(`${e} jsonString.length: ${o.length} (I: 56dec8ad0931ab8ba9b5ca3d4e66be25)`),o}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Pe&&console.log(`${e} complete.`)}}f(Qr,"serializeGraphToString");async function eo({jsonString:r}){let e=`[${eo.name}]`;try{Pe&&console.log(`${e} starting... (I: 52e1a1fb1adcc75168fbc6d819868825)`);let o=JSON.parse(r,f((n,s)=>(s&&s._dataType==="Uint8Array_Base64",s),"reviver"));for(let n in o){let s=o[n].data;s&&s._dataType==="Uint8Array_Base64"&&(o[n].data=await Ki(s.value))}return o}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Pe&&console.log(`${e} complete.`)}}f(eo,"deserializeStringToGraph");async function Vi(r){let e=`[${Vi.name}]`;try{Pe&&console.log(`${e} starting... (I: 8d306868b718596fe8f562bd5118d825)`);let t=await Qr({graph:r}),o=new TextEncoder().encode(t),s=new Response(o).body.pipeThrough(new CompressionStream("gzip"));return await new Response(s).blob()}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Pe&&console.log(`${e} complete.`)}}f(Vi,"compressIbGibToBlob");async function Dl(r){let e=r.stream().pipeThrough(new DecompressionStream("gzip")),t=await new Response(e).text();return await eo({jsonString:t})}f(Dl,"decompressIbGibFromBlob");async function Cn({graph:r}){let e=`[${Cn.name}]`;try{Pe&&console.log(`${e} starting... (I: 1352f8540c08f0b725952df8f18c4825)`);let o=await(await Vi(r)).arrayBuffer(),n=new Uint8Array(o);return await Hi(n)}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Pe&&console.log(`${e} complete.`)}}f(Cn,"compressIbGibGraphToString");async function Pn({compressedBase64:r}){let e=`[${Pn.name}]`;try{Pe&&console.log(`${e} starting... (I: 5f3fa940a2c8f8d7b877978ae7f87825)`);let t=await Ki(r),o=new Blob([t],{type:"application/gzip"});return await Dl(o)}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Pe&&console.log(`${e} complete.`)}}f(Pn,"decompressIbGibGraphFromString");var Xi="export";var cr=!1;function Yi({data:r}){let e=`[${Yi.name}]`;try{cr&&console.log(`${e} starting... (I: 158dfaeb9613a1531be71a9735184624)`);let{graphSize:t,dependencyGraphAsString:o,timestamp:n}=r,s=o.length,i=$e(n),a=r.compression==="gzip"?"gzip":"raw";if(!r.timestamp)throw new Error("(UNEXPECTED) data.timestamp falsy? (E: 2f5bc88488cbf260634239a8a8396825)");let c=new Date(r.timestamp),{ib:l,gib:d}=R({ibGibAddr:r.contextIbGibAddr}),b=ne({gib:d}).tjpGib??d,p=c.toISOString().slice(0,19).replace("T","_").replace(/:/g,"").replace(/ /g,"_");return`${Xi} ${p} ${a} ${t} ${s} ${b}`}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{cr&&console.log(`${e} complete.`)}}f(Yi,"getRawExportIb");async function Ln({ibGib:r,metaspace:e,space:t,compress:o,live:n,ignoreErrors:s}){let i=`[${Ln.name}]`;try{if(cr&&console.log(`${i} starting... (I: 0b6ba8608ba8bde0682a0936b9a01825)`),!r)throw new Error("(UNEXPECTED) ibGib falsy? (E: d2898eea744360865f0da5fb91baae22)");let a=_({ibGib:r}),c=[],l=await se({ibGib:r})??[];if(l.length>0){let $=`ibGib had validation errors: ${l} (E: 84890bbc0598192498178a98ae299825)`;if(s)c.push({errorMsg:$,ibGibAddr:a});else throw new Error($)}let d=await e.getDependencyGraph({ibGib:r,live:n,space:t}),u=o?await Cn({graph:d}):await Qr({graph:d}),b=he({ibGib:r,defaultIfNone:"incomingAddr"})??a,p=new Date,h={contextIbGibAddr:a,tjpAddr:b,dependencyGraphAsString:u,graphSize:Object.keys(d).length,timestamp:Ae(p),timestampMs:p.getMilliseconds()};o&&(h.compression="gzip");let g={ib:Yi({data:h}),data:h},m=await V({ibGib:g,hasTjp:!1});return g.gib=m,cr&&console.log(`${i} JSON.stringify(exportIbGib).length: ${JSON.stringify(g).length} (I: db3a8d913a91d8fc5d6e45981e034822)`),{rawExportIbGib:g,manifest:Object.keys(d),errors:c.length>0?c:void 0}}catch(a){throw console.error(`${i} ${E(a)}`),a}finally{cr&&console.log(`${i} complete.`)}}f(Ln,"getRawExportIbGib");var ng="ibgib-shell-ready",sg="ibgib-ui-busy",ig="ibgib-ui-message",ag="ibgib-identity-request-change",cg="ibgib-identity-changed",lg="ibgib-identity-update-available",dg="ibgib-identity-renewal-required",fg="show-identity-manager",bg="show-keystone-creator",ug="show-add-device",pg="show-privacy-policy";var Wi=at;async function yt({title:r,msg:e,prompt:t,showInput:o,defaultValue:n,okButtonTitle:s,cancelButtonTitle:i,isPassword:a,isBusy:c,animationEmoji:l,passkeys:d,passkeyButtonTitle:u,onPasskeyAuth:b}){let p=`[${yt.name}]`;try{Wi&&console.log(`${p} starting... (I: 037b228a2568181cd3eb25dba4e03225)`);let h=document.getElementById("fullscreen-dialog"),g=document.getElementById("fullscreen-dialog-body"),m=document.getElementById("fullscreen-dialog-title"),$=document.getElementById("fullscreen-dialog-message"),w=document.getElementById("fullscreen-dialog-prompt-input"),T=document.getElementById("fullscreen-dialog-ok-button"),A=document.getElementById("fullscreen-dialog-cancel-button");if(!h||!g||!m||!$||!w||!T||!A)throw new Error("(UNEXPECTED) One or more dialog elements not found in DOM (E: 578e37c0271cc57a99e95e780ad18a25)");if(m.textContent=r||"",[...$.childNodes].forEach(D=>$.removeChild(D)),(e||"").split(`
9
+ `).forEach(D=>{let L=document.createElement("p");L.textContent=D,$.appendChild(L)}),l){let D=document.createElement("div");D.id="fullscreen-dialog-animation-emoji",D.textContent=l,D.style.fontSize="3.5rem",D.style.textAlign="center",D.style.margin="1.5rem 0",D.style.animation="spin-bounce 5s infinite ease-in-out",$.appendChild(D)}let y=document.getElementById("fullscreen-dialog-passkey-container");y&&y.remove();let I=null,v=null,N=null,x=Object.values(d||{}).filter(D=>D!=null);if(x.length>0&&b&&!c){I=document.createElement("div"),I.id="fullscreen-dialog-passkey-container",I.style.margin="1rem 0",I.style.textAlign="center",v=document.createElement("button"),v.id="fullscreen-dialog-btn-passkey",v.type="button",v.className="action-btn",v.style.width="100%",v.style.padding="0.75rem 1rem",v.style.background="linear-gradient(135deg, #1b5e20, #2e7d32)",v.style.color="#ffffff",v.style.fontWeight="bold",v.style.borderRadius="8px",v.style.border="1px solid rgba(255,255,255,0.2)",v.style.cursor="pointer",v.style.fontSize="0.95rem",v.style.marginBottom="0.75rem",v.textContent=u||"\u{1F6E1}\uFE0F Touch ID / Security Key",x.length>1&&(N=document.createElement("select"),N.style.width="100%",N.style.padding="0.4rem",N.style.marginBottom="0.5rem",N.style.borderRadius="4px",N.style.background="rgba(0,0,0,0.3)",N.style.color="inherit",N.style.border="1px solid rgba(255,255,255,0.2)",x.forEach((L,K)=>{let J=document.createElement("option");J.value=K.toString(),J.textContent=`${L.name||"Key"} (${L.credentialId?.substring(0,8)}...)`,N.appendChild(J)}),I.appendChild(N)),I.appendChild(v);let D=document.createElement("div");D.style.display="flex",D.style.alignItems="center",D.style.justifyContent="center",D.style.gap="0.5rem",D.style.fontSize="0.8rem",D.style.color="var(--clr-text-secondary, #b3b3b3)",D.style.margin="0.5rem 0",D.innerHTML=`
10
+ <span style="flex: 1; height: 1px; background: rgba(255,255,255,0.15);"></span>
11
+ <span>OR enter Password below</span>
12
+ <span style="flex: 1; height: 1px; background: rgba(255,255,255,0.15);"></span>
13
+ `,I.appendChild(D),w.parentElement?.insertBefore(I,w)}w.classList.remove("collapsed"),A.classList.remove("collapsed"),A.style.display="inline-block",T.style.display="inline-block",T.textContent=s||"OK";let P=f(D=>{(D.key==="Enter"||D.key===`
14
+ `)&&D.ctrlKey&&T.click()},"onKeypress");return c?(w.classList.add("collapsed"),A.style.display="none",T.style.display="none"):t||o?(w.addEventListener("keypress",P),o?(w.autofocus=!0,w.value=n??"",w.addEventListener("keypress",D=>{D.key==="Enter"&&T.click()}),a?(w.type="password",w.autocomplete="off",w.required=!0):(w.type="text",w.autocomplete="on",w.required=!1,w.attributes["auto-complete"]="on")):(w.autofocus=!1,w.classList.add("collapsed")),A.textContent=i||"Cancel"):(w.classList.add("collapsed"),A.style.display="none"),new Promise(D=>{if(c){let ge=f(_r=>{_r.preventDefault()},"onCancelEvent");h.addEventListener("cancel",ge);let Vt=f(()=>{h.removeEventListener("cancel",ge),h.close()},"close"),Mo=f(({title:_r,msg:ys,animationEmoji:Bo})=>{if(_r!==void 0&&(m.textContent=_r),ys!==void 0){[...$.childNodes].forEach(Tr=>{Tr.id!=="fullscreen-dialog-animation-emoji"&&$.removeChild(Tr)});let Ee=ys.split(`
15
+ `),Is=document.getElementById("fullscreen-dialog-animation-emoji");Ee.forEach(Tr=>{let jo=document.createElement("p");jo.textContent=Tr,Is?$.insertBefore(jo,Is):$.appendChild(jo)})}if(Bo!==void 0){let Ee=document.getElementById("fullscreen-dialog-animation-emoji");Bo?(Ee||(Ee=document.createElement("div"),Ee.id="fullscreen-dialog-animation-emoji",Ee.style.fontSize="3.5rem",Ee.style.textAlign="center",Ee.style.margin="1.5rem 0",Ee.style.animation="spin-bounce 5s infinite ease-in-out",$.appendChild(Ee)),Ee.textContent=Bo):Ee&&Ee.remove()}},"update");h.open||h.showModal(),de(1e3).then(()=>{g.scrollTo({top:0,behavior:"smooth"})}),D({close:Vt,update:Mo});return}let L=f(()=>{(t||o)&&w.removeEventListener("keypress",P),v&&v.removeEventListener("click",J),I&&I.remove(),T.removeEventListener("click",K),A.removeEventListener("click",Je),h.removeEventListener("close",mt)},"removeEventListeners"),K=f(()=>{L();let ge=o?w.value??"":"true";w&&(w.value=""),h.close(ge),x.length>0?D({secret:ge,poolId:"manage"}):D(ge)},"onOK"),J=f(async()=>{try{if(!b)return;v.disabled=!0,v.textContent="Waiting for biometrics / security key...";let ge=x[0];if(N){let Mo=parseInt(N.value,10);ge=x[Mo]||x[0]}let Vt=await b(ge);Vt?(L(),w&&(w.value=""),h.close(Vt),D({secret:Vt,poolId:ge.poolId||"passkey-manage"})):(v.disabled=!1,v.textContent=u||"\u{1F6E1}\uFE0F Touch ID / Security Key")}catch(ge){console.warn("Passkey assertion in dialog failed/cancelled:",ge),v.disabled=!1,v.textContent=u||"\u{1F6E1}\uFE0F Touch ID / Security Key"}},"onPasskeyClick");v&&v.addEventListener("click",J);let Je=f(()=>{L(),w&&(w.value=""),h.close(void 0),D(void 0)},"onCancel"),mt=f(()=>{L(),w&&(w.value=""),h.close(void 0),D(void 0)},"onClose");T.addEventListener("click",K),A.addEventListener("click",Je),h.addEventListener("close",mt),h.open||h.showModal(),de(1e3).then(()=>{g.scrollTo({top:0,behavior:"smooth"})})})}catch(h){throw console.error(`${p} ${E(h)}`),h}finally{Wi&&console.log(`${p} complete.`)}}f(yt,"showFullscreenDialog");var le=at;async function Ol({metaspace:r,space:e}){let t=`[${Ol.name}]`;try{le&&console.log(`${t} starting... (I: 2ccb79537a75e7896bace84e6c710d25)`);let o=await r.getSpecialIbGib({type:Dr.tags,space:e});if(!o)throw new Error(`tagsIbGib not found in metaspace. space: ${e?e.ib:"default local user space"} (E: 4734c510a411274315c0add8f70e1925)`);return o}catch(o){throw console.error(`${t} ${E(o)}`),o}finally{le&&console.log(`${t} complete.`)}}f(Ol,"getTagsIbGib");function Rn({scope:r,ibGib:e,ibGibAddr:t,defaultNameIfError:o}){let n=`[${Rn.name}]`;try{if(!e&&!t)throw new Error(`${n} Must provide either ibGib or ibGibAddr. (E: genuuid)`);r.includes(" ")&&(console.warn(`${n} scope includes one or more spaces. These will be converted to double underscores. (W: 1554a81454e8ae0a6858ea5dd17f8925)`),r=r.replace(/ /g,"__"));let s,i,a;if(e){if(!e.data)throw new Error("(UNEXPECTED) ibGib.data falsy? (E: genuuid)");if(!e.rel8ns)throw new Error("(UNEXPECTED) ibGib.rel8ns falsy? (E: genuuid)");if(!e.rel8ns.ancestor)throw new Error("(UNEXPECTED) ibGib.rel8ns.ancestor falsy? (E: genuuid)");if(e.rel8ns.ancestor.length===0)throw new Error("(UNEXPECTED) ibGib.rel8ns.ancestor.length === 0? there should be at least one ancestor (E: genuuid)");if(e&&t&&_({ibGib:e})!==t)throw new Error("(UNEXPECTED) both ibGib and ibGibAddr provided, but addr of ibGib doesn't equal ibGibAddr? (E: genuuid)");let d=e.rel8ns.ancestor.filter(b=>te({gib:R({ibGibAddr:b}).gib}));if(d.length===0){debugger;console.error(`${n} ibGib has no primitive ancestor addrs? Still going to work off of the ib then, which should have the atom as the first space-delimited term. (E: genuuid)`)}let u=d.at(-1);s=R({ibGibAddr:u}).ib,a=s}t??=_({ibGib:e});let{ib:c}=R({ibGibAddr:t});if(i=c.split(" ").at(0)??"",i=i.replace(/\W/g,"_"),s??=i,s=s.replace(/\W/g,"_"),!s&&!i)throw new Error("(UNEXPECTED) both primitiveAncestorIb and atom falsy? one should be truthy at this point. (E: genuuid)");a=i.toLowerCase(),le&&console.log(`${n} ancestorIbOrAtom: ${a} (I: genuuid)`);let l=`${a}_${r}index`;return le&&console.log(`${n} indexName: ${l} (I: genuuid)`),l}catch(s){if(o)return console.warn(`${n} error happened but defaultNameIfError (${o}) provided. So will return this value. error that was thrown: ${E(s)}`),o;throw console.error(`${n} ${E(s)}`),s}}f(Rn,"getIndexNameFromIbGib");async function Nl({scope:r,ibGib:e,metaspace:t,space:o,skipGetLatest:n}){let s=`[${Nl.name}]`;try{if(le&&console.log(`${s} starting... (I: f19dc86aab380fe809aef27ccc7a7425)`),!r)throw new Error("scope required to be a non-empty string (E: 73e702495c38c7d8747d1cf8850af825)");if(!e)throw new Error("ibGib required (E: genuuid)");let i=Rn({scope:r,ibGib:e}),a=he({ibGib:e,defaultIfNone:"incomingAddr"}),c=f(async()=>{let d=await t.getSpecialIbGib({type:i,space:o,initialize:!1,dontWarnIfNotExist:!0,lock:!0});if(!d||!d.data){le&&console.log(`${s} special ${r} index ibGib not found for indexSpecialIbGibType (${i}). No coupled ibgib registered, returning undefined. (I: genuuid)`);return}let b=(d.data.coupleMap??d.data.agentMap??{})[a];if(!b){le&&console.log(`${s} No coupled ${r} ibgib address found for domain ${a} in the coupled index map. indexSpecialIbGibType: ${i}. returning undefined. (I: genuuid)`);return}let p=n?b:await t.getLatestAddr({addr:b,space:o})??b,h=await t.get({addrs:[p],space:o});if(h.errorMsg||(h.ibGibs??[]).length!==1)throw new Error(`couldn't get latest coupled ibgib (${p}) for domain ${a}. (E: 8aa7b25f5cd4ebadd8bf2f8807dfe825)`);return h.ibGibs[0]},"fn");return await Ne({scope:i,secondsValid:180,maxDelayMs:100,maxLockAttempts:1800,space:o,callerInstanceId:s+$e(),fn:c})}catch(i){throw console.error(`${s} ${E(i)}`),i}finally{le&&console.log(`${s} complete.`)}}f(Nl,"getLocalCoupledIbGibForDomainIbGib");async function Cl({scope:r,domainIbGib:e,localIbGib:t,metaspace:o,space:n}){let s=`[${Cl.name}]`;try{le&&console.log(`${s} starting... (I: 217ae68e0c820e48f4c00409f7f14325)`);let i=Rn({scope:r,ibGib:e}),a=he({ibGib:e}),c=_({ibGib:t});if(!a)throw new Error(`${s} Could not get TJP address for domain ibGib. (E: 35a4e8ac291b0b85cb958e28dd812f25)`);if(!c)throw new Error(`${s} Could not get address for agent ibGib. (E: 2fce1187630b45934c4155a23204d125)`);await Ne({scope:i,secondsValid:60,maxDelayMs:100,maxLockAttempts:600,space:n,fn:f(async()=>{let d=await o.getSpecialIbGib({type:i,space:n,initialize:!0,dontWarnIfNotExist:!0,lock:!1});if(!d)throw new Error(`${s} Could not get or create agent index ibGib.`);if(!d.data)throw new Error("(UNEXPECTED) agentSpecialIndex.data falsy? (E: 74299eed147debf6398ca37e7b8d5c25)");let u=d.data.coupleMap??d.data.agentMap,b=u?C(u):{},p=b[a];if(p)if(p===c){le&&console.log(`${s} domain ibGib (${a}) already mapped to agent (${c}). returning early (I: cb5d4dcef8cf14de7336120fb8ffef25)`);return}else console.warn(`${s} domainTjpAddr (${a}) already assigned to existingMappedAgentAddr (${p}). We will be changing to new localAddr (${c}). (W: eb993e33f7731e570fa76f24a2d80625)`);b[a]=c;let h=await Fe({src:d,dataToAddOrPatch:{coupleMap:b},dna:!1,linkedRel8ns:[Y.past],nCounter:!0}),g=h.newIbGib;await Q({resTransform:h,space:n});let m=ae({type:i});await o.setConfigAddr({key:m,addr:_({ibGib:g}),space:n}),await o.registerNewIbGib({ibGib:g,space:n})},"fn")}),le&&console.log(`${s} Registered domain ${a} with agent ${c}`)}catch(i){throw console.error(`${s} ${E(i)}`),i}finally{le&&console.log(`${s} complete.`)}}f(Cl,"coupleDomainIbGibWithLocalIbGibViaIndex");function It(){let r=`[${It.name}]`;try{le&&console.log(`${r} starting... (I: 890f53e984d69461d9f4ded8741fcc25)`);let e=globalThis[Zr];return e||(console.log(`${r} initializing globalThis.${Zr}... (I: 9d9ff1813448d9a1b82b0e5790a74825)`),e={},globalThis[Zr]=e),e}catch(e){throw console.error(`${r} ${E(e)}`),e}finally{le&&console.log(`${r} complete.`)}}f(It,"getIbGibGlobalThis_IbGib");async function Ji({delayIntervalMs:r=50}={delayIntervalMs:50}){let e=`[${Ji.name}]`;try{le&&console.log(`${e} starting... (I: 4acc22d08dd1100503f9b0423f302925)`);let t;for(;!t;)It().metaspace&&(t=It().metaspace),t||(console.log(`${e} metaspace still not initialized. delayIntervalMs: ${r} until next retry... (I: 490f77ac4ded1d7d3c0340e460404125)`),await de(r));return t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{le&&console.log(`${e} complete.`)}}f(Ji,"getGlobalMetaspace_waitIfNeeded");function Pl({ibGibAddr:r,gib:e,ibGib:t,translucentAlpha:o=10}){let n=`[${Pl.name}]`;try{le&&console.log(`${n} starting... (I: 3b70af42d1c4f6ae91870f3a15c6c625)`),!r&&!e&&!t&&(e=U),e??=t?.gib??R({ibGibAddr:r}).gib;let s=ne({gib:e});o??=10;let i="";if(s.isPrimitive)return{gib:e,gibInfo:s,punctiliarColor:ji,punctiliarColorTranslucent:Fi,punctiliarColorContrast:qi};i=s.tjpGib??s.punctiliarHash??e;let[a,c,l]=zi(o,s.punctiliarHash??e),[d,u,b]=s.tjpGib?zi(o,s.tjpGib):[void 0,void 0,void 0];return{gib:e,gibInfo:s,punctiliarColor:a,punctiliarColorTranslucent:c,punctiliarColorContrast:l,tjpColor:d,tjpColorTranslucent:u,tjpColorContrast:b}}catch(s){let i=`${n} ${E(s)}`;return console.error(i),{gib:e??U,gibInfo:{isPrimitive:!0},punctiliarColor:"#ff0000",punctiliarColorTranslucent:"#ff000010",punctiliarColorContrast:"#ffffff",errorMsg:i}}finally{le&&console.log(`${n} complete.`)}}f(Pl,"getDeterministicColorInfo");function Ll(r,e,t){t/=100;let o=e*Math.min(t,1-t)/100,n=f(s=>{let i=(s+r/30)%12,a=t-o*Math.max(Math.min(i-3,9-i,1),-1);return Math.round(255*a).toString(16).padStart(2,"0")},"f");return`#${n(0)}${n(8)}${n(4)}`}f(Ll,"hslToHex");function zi(r,e){let o=(parseInt(e.substring(0,8),16)||0)%360,n=Ll(o,65,62),s=parseInt(n.substring(1,3),16),i=parseInt(n.substring(3,5),16),a=parseInt(n.substring(5,7),16),l=(s*299+i*587+a*114)/1e3>=128?"#11111b":"#ffffff",d=Math.min(100,Math.max(0,r)),u=Math.round(d/100*255).toString(16).padStart(2,"0"),b=`${n}${u}`;return[n,b,l]}f(zi,"getColorStrings");var Rl="recursive-salt-wrap",Un={recursive_salt_wrap:Rl},Zi=Object.values(Un);var to=!1;async function Ul({masterSecret:r,kdfOpts:e}){let t=`[${Ul.name}]`;try{to&&console.log(`${t} starting... (I: 268e87ec311874ee6822bf459c5a5426)`);let o=e.strategy;switch(o){case Un.recursive_salt_wrap:return await Mt({masterSecret:r,salt:e.salt,rounds:e.rounds,algorithm:e.algorithm});default:throw new Error(`Unknown KDF strategy: ${o}. valid values: ${Zi.join(", ")} (E: c81258e9d9481eb0f88385a825193226)`)}}catch(o){throw console.error(`${t} ${E(o)}`),o}finally{to&&console.log(`${t} complete.`)}}f(Ul,"deriveKey");async function Mt({masterSecret:r,salt:e,rounds:t,algorithm:o=we.sha_256}){let n=`[${Mt.name}]`;try{to&&console.log(`${n} starting... (I: 850868e50aba82ff28c77da8169e4c26)`);let s=r;for(let i=0;i<t;i++)s=await X({s:`${e}${s}${e}`,algorithm:o});return s}catch(s){throw console.error(`${n} ${E(s)}`),s}finally{to&&console.log(`${n} complete.`)}}f(Mt,"kdf_recursiveSaltWrap");var kl="hash-reveal-v1",je={hash_reveal_v1:kl},Qi=Object.values(je);var Ml="top-up",Bl="replace-all",jl="consume",Fl="delete-all",Te={topUp:Ml,replaceAll:Bl,consume:jl,deleteAll:Fl},ea=Object.values(Te);var ql="add-pool",Hl="remove-pool",Kl="replace-pool",Vl="change-password",Bt={add_pool:ql,remove_pool:Hl,replace_pool:Kl,change_password:Vl},Fg=Object.values(Bt);var dr="keystone",kn=/^\w[\w\-.]*$/,Mn=/^[a-zA-Z0-9\-_]{1,64}$/,Bn=/^[a-zA-Z0-9_\-.]{1,63}$/,jn=/^[a-zA-Z0-9\s.,!?:;'"\-()[\]_+=@#$%&*\/]{0,128}$/,ta=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,Fn=1e3,jt="revoke",ce="manage",Xl="sign",ro="sync",ra="connect",qn={REVOKE:jt,MANAGE:ce,SIGN:Xl,SYNC:ro,CONNECT:ra},Yg=Object.values(qn);var fr=ce;var Yl=ra,Wl=ro;var oa=200,na=2,sa=2,ia=5,aa=Te.topUp,ca=we.sha_256,la=1,da=2e3,fa=5,ba=5,ua=16,pa=Te.replaceAll,ha=we.sha_512,ga=10,_t=50;var oo=!1,Hn=class{static{f(this,"KeystoneConfigBuilderBase")}_id;_salt;_size;_replenish;_seq;_rand;_verbs=[];_targetBinding;withId(e){return this._id=e,this}withSalt(e){return this._salt=e,this}withSize(e){return this._size=e,this}withTargetBinding(e){return this._targetBinding=e,this}withFIFO(e){return this._seq=e,this._rand=0,this}withRandom(e){return this._seq=0,this._rand=e,this}withHybrid({seqCount:e,randCount:t}){return this._seq=e,this._rand=t,this}withReplenishStrategy(e){return this._replenish=e,this}buildBehavior(){if(this._size===void 0)throw new Error("size required (E: 68320865d9adb8477836485b20b08826)");if(this._replenish===void 0)throw new Error("replenish strategy required (E: 9f8798d1a568763a282e53c89185b826)");if(this._seq===void 0)throw new Error("sequential required (E: e0da08a24e9790d0a8c1a9322f8eb826)");if(this._rand===void 0)throw new Error("selectRandomly required (E: 7721d84d1a8b7d020d0ab33c3f811426)");if(this._targetBinding===void 0)throw new Error("targetBinding required (E: 9add64d7e8e8cba01d901727a8e9b826)");return{size:this._size,replenish:this._replenish,selectSequentially:this._seq,selectRandomly:this._rand,targetBindingCount:this._targetBinding}}forVerbs(e){return this._verbs=e,this}},Kn=class r extends Hn{static{f(this,"KeystoneConfigBuilder_HashV1")}lc=`[${r}]`;_algo;_rounds;withHash({algo:e,rounds:t}){let o=`${this.lc}[${this.withHash.name}]`;try{return oo&&console.log(`${o} starting... (I: 15d1b3bd2e98bba33fc6c78228755826)`),this._algo=e,this._rounds=t,this}catch(n){throw console.error(`${o} ${E(n)}`),n}finally{oo&&console.log(`${o} complete.`)}}build(){let e=`${this.lc}[${this.build.name}]`;try{if(oo&&console.log(`${e} starting... (I: 5df568c63c4993bb98df0a319ee16826)`),!this._id)throw new Error("id required (E: b50d082adf38bcbf463552f80d2c3226)");if(!this._salt)throw new Error("salt required (E: b0f1926657b8d7d3a88fb9385ead5826)");if(!this._algo)throw new Error("algorithm required (E: cff228f9898fd6383ef752088dae6826)");if(this._rounds===void 0)throw new Error("rounds required (E: eb72580f3b014cda18cba3e399683c26)");return{id:this._id,type:je.hash_reveal_v1,salt:this._salt,allowedVerbs:this._verbs,behavior:this.buildBehavior(),algo:this._algo,rounds:this._rounds}}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{oo&&console.log(`${e} complete.`)}}},br=class{static{f(this,"KeystoneConfig")}static hash(){return new Kn}};function rm(r){if(r.type&&r.type!==je.hash_reveal_v1)throw new Error(`invalid type (${r.type}). Only ${je.hash_reveal_v1} currently implemented. (E: c38616cd7a459149f670418f88766526)`);let{salt:e,id:t,size:o,sequential:n,random:s,targetBinding:i,replenishStrategy:a,verbs:c,hashAlgorithm:l,hashRounds:d}=r;return br.hash().withId(t).withSalt(e).withSize(o??oa).withHybrid({seqCount:n??na,randCount:s??sa}).withTargetBinding(i??ia).withReplenishStrategy(a??aa).withHash({algo:l??ca,rounds:d??la}).forVerbs(c??[]).build()}f(rm,"createStandardPoolConfig");function zl(r){if(r.type&&r.type!==je.hash_reveal_v1)throw new Error(`invalid type (${r.type}). Only ${je.hash_reveal_v1} currently implemented. (E: 09c1f7772bd2a7910f5562b4934d3826)`);let{salt:e,id:t,size:o,sequential:n,random:s,targetBinding:i,replenishStrategy:a,verbs:c,hashAlgorithm:l,hashRounds:d}=r;return br.hash().withId(t).withSalt(e).withSize(o??da).withHybrid({seqCount:n??fa,randCount:s??ba}).withTargetBinding(i??ua).withReplenishStrategy(a??pa).withHash({algo:l??ha,rounds:d??ga}).forVerbs(c??[]).build()}f(zl,"createHighSecurityPoolConfig");function om(r){return zl({...r,id:r.id??fr,verbs:r.verbs??[qn.MANAGE]})}f(om,"createManagePoolConfig");function ma({template:r,salt:e}){let t=r.behavior;return br.hash().withId(r.id).withSalt(e).withSize(t.size).withHybrid({seqCount:t.selectSequentially,randCount:t.selectRandomly}).withTargetBinding(t.targetBindingCount).withReplenishStrategy(t.replenish).withHash({algo:r.algo,rounds:r.rounds}).forVerbs(r.allowedVerbs).build()}f(ma,"createPoolConfigFromJson");var Ea={$schema:"../../schemas/primary/primary-keystone.schema.json",metadata:{name:"Primary Identity Profile (Dev)",securityLevel:"low"},pools:{manage:{id:"manage",allowedVerbs:["manage","revoke"],algo:"SHA-256",rounds:1,behavior:{size:10,replenish:"replace-all",selectSequentially:1,selectRandomly:1,targetBindingCount:2}}}};var wa={$schema:"../../schemas/primary/primary-keystone.schema.json",metadata:{name:"Primary Identity Profile (Staging)",securityLevel:"medium"},pools:{manage:{id:"manage",allowedVerbs:["manage","revoke"],algo:"SHA-512",rounds:3,behavior:{size:500,replenish:"replace-all",selectSequentially:4,selectRandomly:4,targetBindingCount:6}}}};var $a={$schema:"../../schemas/primary/primary-keystone.schema.json",metadata:{name:"Primary Identity Profile (Prod)",securityLevel:"high"},pools:{manage:{id:"manage",allowedVerbs:["manage","revoke"],algo:"SHA-512",rounds:6,behavior:{size:2e3,replenish:"replace-all",selectSequentially:12,selectRandomly:12,targetBindingCount:16}}}};var no={$schema:"../../schemas/sync/sync-keystone.schema.json",metadata:{name:"Sync Delegate Profile (Dev)",securityLevel:"low",defaultTtlSeconds:86400},pools:{sync:{id:"sync",allowedVerbs:["sync"],algo:"SHA-256",rounds:1,behavior:{size:10,replenish:"top-up",selectSequentially:1,selectRandomly:1,targetBindingCount:2}},manage:{id:"manage",allowedVerbs:["manage","revoke"],algo:"SHA-256",rounds:2,behavior:{size:10,replenish:"replace-all",selectSequentially:1,selectRandomly:1,targetBindingCount:2}},connect:{id:"connect",allowedVerbs:["connect"],algo:"SHA-256",rounds:1,behavior:{size:10,replenish:"top-up",selectSequentially:1,selectRandomly:1,targetBindingCount:2}},sign:{id:"default",allowedVerbs:["sign"],algo:"SHA-256",rounds:2,behavior:{size:10,replenish:"top-up",selectSequentially:1,selectRandomly:1,targetBindingCount:2}}}};var ya={$schema:"../../schemas/sync/sync-keystone.schema.json",metadata:{name:"Sync Delegate Profile (Staging)",securityLevel:"medium",defaultTtlSeconds:604800},pools:{sync:{id:"sync",allowedVerbs:["sync"],algo:"SHA-256",rounds:2,behavior:{size:100,replenish:"top-up",selectSequentially:2,selectRandomly:2,targetBindingCount:4}},manage:{id:"manage",allowedVerbs:["manage","revoke"],algo:"SHA-512",rounds:3,behavior:{size:250,replenish:"replace-all",selectSequentially:4,selectRandomly:4,targetBindingCount:6}},connect:{id:"connect",allowedVerbs:["connect"],algo:"SHA-256",rounds:2,behavior:{size:100,replenish:"top-up",selectSequentially:2,selectRandomly:2,targetBindingCount:4}},sign:{id:"default",allowedVerbs:["sign"],algo:"SHA-256",rounds:2,behavior:{size:100,replenish:"top-up",selectSequentially:2,selectRandomly:2,targetBindingCount:4}}}};var Ia={$schema:"../../schemas/sync/sync-keystone.schema.json",metadata:{name:"Sync Delegate Profile (Prod)",securityLevel:"high",defaultTtlSeconds:2592e3},pools:{sync:{id:"sync",allowedVerbs:["sync"],algo:"SHA-512",rounds:4,behavior:{size:500,replenish:"top-up",selectSequentially:4,selectRandomly:4,targetBindingCount:6}},manage:{id:"manage",allowedVerbs:["manage","revoke"],algo:"SHA-512",rounds:6,behavior:{size:1e3,replenish:"replace-all",selectSequentially:8,selectRandomly:8,targetBindingCount:10}},connect:{id:"connect",allowedVerbs:["connect"],algo:"SHA-512",rounds:4,behavior:{size:500,replenish:"top-up",selectSequentially:4,selectRandomly:4,targetBindingCount:6}},sign:{id:"default",allowedVerbs:["sign"],algo:"SHA-512",rounds:4,behavior:{size:500,replenish:"top-up",selectSequentially:4,selectRandomly:4,targetBindingCount:6}}}};var _a={$schema:"../schemas/keystone.low.schema.json",metadata:{name:"Session/Saga Identity Profile",securityLevel:"low"},pools:{sync:{id:"sync",allowedVerbs:["sync"],algo:"SHA-256",rounds:1,behavior:{size:50,replenish:"top-up",selectSequentially:2,selectRandomly:2,targetBindingCount:6}},manage:{id:"manage",allowedVerbs:["manage"],algo:"SHA-256",rounds:2,behavior:{size:50,replenish:"replace-all",selectSequentially:2,selectRandomly:2,targetBindingCount:6}},revoke:{id:"revoke",allowedVerbs:["revoke"],algo:"SHA-256",rounds:5,behavior:{size:50,replenish:"delete-all",selectSequentially:3,selectRandomly:3,targetBindingCount:0}},connect:{id:"connect",allowedVerbs:["connect"],algo:"SHA-256",rounds:1,behavior:{size:50,replenish:"top-up",selectSequentially:2,selectRandomly:2,targetBindingCount:6}},sign:{id:"default",allowedVerbs:["sign"],algo:"SHA-256",rounds:2,behavior:{size:50,replenish:"top-up",selectSequentially:2,selectRandomly:2,targetBindingCount:6}}}};var so=new Map,ur=class r{static{f(this,"KeystoneProfileBuilder")}_template;_username;_emails;_description;_details;_customizations={};constructor(e){this._template=JSON.parse(JSON.stringify(e))}static registerCustomProfile({name:e,template:t}){if(!e||typeof e!="string")throw new Error("Profile name is required to register a custom profile. (E: genuuid)");if(!t||typeof t!="object")throw new Error(`Valid KeystonePolicyConfigTemplate is required to register custom profile '${e}'. (E: genuuid)`);so.set(e,JSON.parse(JSON.stringify(t)))}static clearCustomProfiles(){so.clear()}static fromTemplate(e){if(!e||typeof e!="object")throw new Error("Valid KeystonePolicyConfigTemplate is required for KeystoneProfileBuilder.fromTemplate. (E: genuuid)");return new r(e)}static buildKeystone(e){if(!e||typeof e!="string")throw new Error("Profile name is required for KeystoneProfileBuilder. (E: genuuid)");if(e.endsWith(".dev")||e.startsWith("test")||e.includes("test"))throw new Error(`Security Violation: Development keystone profile '${e}' is prohibited when NODE_ENV=production. (E: genuuid)`);if(so.has(e))return new r(so.get(e));let o;switch(e){case"primary-profile.dev":o=Ea;break;case"primary-profile.staging":o=wa;break;case"primary-profile.prod":o=$a;break;case"sync-profile.dev":o=no;break;case"sync-profile.staging":o=ya;break;case"sync-profile.prod":o=Ia;break;case"sync-profile.test-short-ttl":o={...JSON.parse(JSON.stringify(no)),metadata:{...no.metadata,name:"sync-profile.test-short-ttl",description:"Short 10-second TTL sync profile for testing session expiration and renewal.",defaultTtlSeconds:10}};break;case"session":o=_a;break;default:throw new Error(`Unknown keystone profile name: '${e}' (E: fc10a8ad482ef2bda871ac567d268d26)`)}return new r(o)}withUsername(e){return this._username=e,this}withEmail(e){return this._emails?this._emails.includes(e)||this._emails.push(e):this._emails=[e],this}withEmails(e){return this._emails=[...e],this}withDescription(e){return this._description=e,this}withDetails(e){return this._details=e,this}_expirationUTC;withExpiration(e){return this._expirationUTC=e,this}getDefaultTtlSeconds(){return this._template.metadata?.defaultTtlSeconds}customizePool(e,t){let{behavior:o,...n}=t;return this._customizations[e]={template:n,behavior:o},this}getFrameDetails(){let e={...this._details};if(this._username&&(e.username=this._username),this._emails&&this._emails.length>0&&(e.emails=[...this._emails]),this._description&&(e.description=this._description),this._expirationUTC)e.expirationUTC=this._expirationUTC;else{let t=this.getDefaultTtlSeconds();t&&t>0&&(e.expirationUTC=new Date(Date.now()+t*1e3).toISOString())}return e}async compileConfigs(){let e=[],t="";if(this._username||this._emails&&this._emails.length>0){let o=this._emails?.[0]??"",n=`${this._username||""}:${o}`;t=await X({s:n})}else t=await X({s:"default-keystone-salt"});for(let[o,n]of Object.entries(this._template.pools)){let s=this._customizations[n.id];s&&(s.template&&Object.assign(n,s.template),s.behavior&&n.behavior&&Object.assign(n.behavior,s.behavior));let i=`${t}-${n.id}`,a=await X({s:i}),c=ma({template:n,salt:a});e.push(c)}return e}};var io=class{static{f(this,"KeystoneStrategy")}config;constructor(e){this.config=e}};var ao=class r extends io{static{f(this,"KeystoneStrategy_HashRevealV1")}async derivePoolSecret({masterSecret:e}){let t=`[${r.name}.${this.derivePoolSecret.name}]`;try{let{salt:o,rounds:n,algo:s}=this.config;return await Mt({masterSecret:e,salt:o,rounds:n,algorithm:s})}catch(o){throw console.error(`${t} Error deriving pool secret: ${o.message}`),o}}async generateSolution({poolSecret:e,poolId:t,challengeId:o}){let n=`[${r.name}.${this.generateSolution.name}]`;try{let{rounds:s,algo:i}=this.config,a=o,c=e;for(let l=0;l<s;l++)c=await X({s:`${a}${c}${a}`,algorithm:i});return{type:"hash-reveal-v1",poolId:t,challengeId:o,value:c}}catch(s){throw console.error(`${n} ${s.message}`),s}}async generateChallenge({solution:e}){let t=`[${r.name}.${this.generateChallenge.name}]`;try{let{rounds:o,algo:n}=this.config,{challengeId:s,value:i}=e,a=s,c=i;for(let l=0;l<o;l++)c=await X({s:`${a}${c}${a}`,algorithm:n});return{id:s,type:"hash-reveal-v1",hash:c}}catch(o){throw console.error(`${t} ${o.message}`),o}}async validateSolution({solution:e,challenge:t}){let o=`[${r.name}.${this.validateSolution.name}]`;try{return e.type!=="hash-reveal-v1"||t.type!=="hash-reveal-v1"?(console.warn(`${o} Mismatched types provided.`),!1):(await this.generateChallenge({solution:e})).hash===t.hash}catch(n){return console.error(`${o} ${n.message}`),!1}}};var Tt=class r{static{f(this,"KeystoneStrategyFactory")}static create({config:e}){let t=`[${r.name}.create]`;try{switch(e.type){case"hash-reveal-v1":return new ao(e);default:throw new Error(`Unknown strategy type: ${e.type} (E: 4e3c2f7129a241c1b687555e678c1065)`)}}catch(o){throw console.error(`${t} ${o.message}`),o}}};var M=!1;async function pr({ibGib:r,ibGibs:e,ibGibAddr:t,ibGibAddrs:o,live:n,gotten:s,tjpAddrsAlreadyAnalyzed:i,skipAddrs:a,skipRel8nNames:c,onlyRel8nNames:l,maxRetries:d,msBetweenRetries:u,space:b,spaces:p,timeLogName:h,mapTjpAddrToLatestAddrsInSpace:g}){let m=`[${pr.name}]`;try{M&&console.log(`${m} starting... (I: c2a4426c22e849611ca0cedabe683a22)`);let $=await hr({ibGib:r,ibGibs:e,ibGibAddr:t,ibGibAddrs:o,live:n,gotten:s,tjpAddrsAlreadyAnalyzed:i,skipAddrs:a,skipRel8nNames:c,onlyRel8nNames:l,maxRetries:d,msBetweenRetries:u,space:b,spaces:p,timeLogName:h,mapTjpAddrToLatestAddrsInSpace:g});if(M&&Object.values($).filter(w=>w.ib.startsWith("comment ")).forEach(w=>{console.table(w)}),M){console.log(`${m} graph size: ${Object.keys($).length} (I: c6cb5e7e1e2611d35b9006fac6503d22)`);let w=Object.values($).filter(T=>T.ib.startsWith("comment ")||T.ib.startsWith("pic ")).map(T=>T.ib);Xt(w).forEach(T=>console.log(T))}return $}catch($){throw console.error(`${m} ${$.message}`),$}finally{M&&console.log(`${m} complete.`)}}f(pr,"getDependencyGraph");async function Aa({ibGib:r,ibGibs:e,ibGibAddr:t,ibGibAddrs:o,live:n,gotten:s,tjpAddrsAlreadyAnalyzed:i,skipAddrs:a,skipRel8nNames:c,onlyRel8nNames:l,maxRetries:d,msBetweenRetries:u,space:b,spaces:p,timeLogName:h,mapTjpAddrToLatestAddrsInSpace:g}){let m=`[${Aa.name}]`;try{if(M&&console.log(`${m} starting... (I: bd6807477f679345df9dddefe0b4e922)`),b&&(p??[]).length>0)throw new Error("space and spaces parameters are mutually exclusive. Pass either space or spaces, not both. (E: 994a5323e4214f4e95d5bb2b89f89090)");let $=b?[b]:(p??[]).filter(w=>!!w);if($.length===0)throw new Error("space or spaces required. (E: 9f38166ab70340cb919174f8d26af909)");if(!r&&!t&&(e??[]).length===0&&(o??[]).length===0)throw new Error("either ibGib/s or ibGibAddr/s required. (E: b6d08699651f455697f0d05a41edb039)");return c=c||[],a=a||[],s=s||{},i=i||[],o=(o??[]).filter(w=>!te({gib:R({ibGibAddr:w}).gib})).filter(w=>!a.includes(w)),e=(e??[]).filter(w=>!te({ibGib:w})).filter(w=>!a.includes(_({ibGib:w}))),r&&!te({ibGib:r})&&!e.some(w=>w.gib===r.gib)&&!a.includes(_({ibGib:r}))&&e.push(r),t&&!te({gib:R({ibGibAddr:t}).gib})&&!o.includes(t)&&!a.includes(t)&&o.push(t),{ibGib:r,ibGibs:e,ibGibAddr:t,ibGibAddrs:o,live:n,gotten:s,tjpAddrsAlreadyAnalyzed:i,skipAddrs:a,skipRel8nNames:c,onlyRel8nNames:l,maxRetries:d,msBetweenRetries:u,space:void 0,spaces:$,timeLogName:h,mapTjpAddrToLatestAddrsInSpace:g}}catch($){throw console.error(`${m} ${$.message}`),$}finally{M&&console.log(`${m} complete.`)}}f(Aa,"getGraphProjection_initializeOpts");async function Xn({ibGibs:r,ibGibAddrs:e,gotten:t,skipAddrs:o,maxRetries:n,msBetweenRetries:s,timeLogName:i,space:a,spaces:c}){let l=`[${Xn.name}]`;try{M&&console.log(`${l} starting... (I: 67b2be37ff24393fff56e229304da122)`);let d=c??(a?[a]:[]);if(d.length===0)throw new Error("(UNEXPECTED) spaces empty? (E: aa9f657695717034b3581066932d7d23)");let u=[];r??=[],e??=[],o??=[],t??={};let b=[],p=Object.keys(t??{}),h=r.map(g=>_({ibGib:g}));for(let g=0;g<e.length;g++){let m=e[g];o.includes(m)||h.includes(m)||(p.includes(m)?u.push(t[m]):b.push(e[g]))}if(M&&console.log(`${l}[analyze debugging] addrsToGetFromSpace (${b.length}):
16
+ ${b.join(`
17
+ `)} (I: b45a2614184b48b694becfd377c789f5)`),b.length>0){let g=b.concat(),m=0;for(n=n??0;m<=n&&g.length>0;){i&&m===0&&console.timeLog(i,`${l} FIRST try starting...`),i&&m>0&&console.timeLog(i,`${l} RETRY starting...`),m>0&&s&&(i&&console.timeLog(i,`${l} delaying ${s}ms for retry`),M&&console.log(`${l} retrying. addrsToGet (${g.length}): ${g} (I: 8460694cdd5518472680784c3b96a822)`),await de(s));for(let $ of d){if(g.length===0)break;i&&console.timeLog(i,`${l} getFromSpace (${g.length}) starting...`);let w=await ie({addrs:g,space:$});if(i&&console.timeLog(i,`${l} getFromSpace complete.`),w.success&&(w.ibGibs?.length??0)>0){w.ibGibs.forEach(A=>u.push(A));let T=w.ibGibs.map(A=>_({ibGib:A}));g=g.filter(A=>!T.includes(A))}else{let T=w.rawResultIbGib?.ibGibs??[];if(T.length>0){T.forEach(G=>u.push(G));let A=T.map(G=>_({ibGib:G}));g=g.filter(G=>!A.includes(G))}}}m++}if(g.length>0){let $=d.map(w=>w?.ib).join(", ");throw new Error(`unable to retrieve dependency ibgibs from space/s (ib/s: ${$}). addrsToGet: ${g.join(`
18
+ `)} (E: 8413594b6c1b447988781cf3f3e1729d)`)}}return u}catch(d){throw console.error(`${l} ${d.message}`),d}finally{M&&console.log(`${l} complete.`)}}f(Xn,"getGraphProjection_getIbGibsInIbGibAddrs");async function hr(r){let e=`[${hr.name}]`;try{if(M&&console.log(`${e} starting... (I: 70508d7a5c63eae1f22ae851b32b3d22)`),!r.ibGib&&!r.ibGibAddr&&(r.ibGibs??[]).length===0&&(r.ibGibAddrs??[]).length===0)return{};let{ibGibs:t,ibGibAddrs:o,live:n,gotten:s,tjpAddrsAlreadyAnalyzed:i,skipAddrs:a,skipRel8nNames:c,onlyRel8nNames:l,maxRetries:d,msBetweenRetries:u,space:b,spaces:p,timeLogName:h,mapTjpAddrToLatestAddrsInSpace:g}=await Aa(r);if(h&&console.timeLog(h,`${e} starting...`),o?.length??!1){let $=await Xn({ibGibs:t,ibGibAddrs:o,gotten:s,skipAddrs:a,maxRetries:d,msBetweenRetries:u,timeLogName:h,space:b,spaces:p});t=t?[...t,...$]:[...$]}o=t.map($=>_({ibGib:$}));let m=Xt(t.map($=>$.ib).filter($=>$.startsWith("comment ")));return M&&console.log(`${e}[analyze debugging] ibGibs commentIbs: ${m.join(`
19
+ `)} (I: c89dc951315f746954f9bddbe8941122)`),n?Sa({ibGibs:t,ibGibAddrs:o,gotten:s,tjpAddrsAlreadyAnalyzed:i,skipAddrs:a,skipRel8nNames:c,onlyRel8nNames:l,maxRetries:d,msBetweenRetries:u,space:b,spaces:p,timeLogName:h,mapTjpAddrToLatestAddrsInSpace:g}):Ga({ibGibs:t,ibGibAddrs:o,gotten:s,skipAddrs:a,skipRel8nNames:c,onlyRel8nNames:l,maxRetries:d,msBetweenRetries:u,space:b,spaces:p,timeLogName:h})}catch(t){throw console.error(`${e} ${t.message}`),t}finally{M&&console.log(`${e} complete.`)}}f(hr,"getGraphProjection");async function nd({ibGibAddr:r,latestCommonFrameAddr:e,live:t,space:o,spaces:n}){let s=`[${nd.name}]`;try{if(M&&console.log(`${s} starting... (I: 5d225e56dc11e62cd83c5366ea288826)`),r===e)return console.warn(`${s} ibGibAddr === latestCommonFrameAddr. So the delta graph is empty. what are we doing here? (W: e0c8287ae6de8152bf36b6c73ca59a26)`),{};let i=await pr({ibGibAddr:e,live:!1,space:o,spaces:n});return await pr({ibGibAddr:r,live:t,skipAddrs:Object.keys(i),space:o,spaces:n})}catch(i){throw console.error(`${s} ${E(i)}`),i}finally{M&&console.log(`${s} complete.`)}}f(nd,"getDeltaDependencyGraph");async function Sa({ibGibs:r,ibGibAddrs:e,gotten:t,tjpAddrsAlreadyAnalyzed:o,mapTjpAddrToLatestAddrsInSpace:n,skipAddrs:s,skipRel8nNames:i,onlyRel8nNames:a,maxRetries:c,msBetweenRetries:l,space:d,spaces:u,timeLogName:b}){let p=`[${Sa.name}]`;try{let h=u??(d?[d]:[]);n=n??{},o=o??[];let g={...t};(r??[]).forEach(G=>g[_({ibGib:G})]=G);let m=ar({ibGibs:Object.values(g)});M&&console.log(`${p}[analyze debugging] timeline tjps(${Object.keys(m).length}): ${Object.keys(m)} (I: 509f04ac15ca08c5a3f0777b48934622)`);let $={};Object.keys(m).forEach(G=>{o.includes(G)||($[G]=m[G])}),M&&console.log(`${p}[analyze debugging] timelinesNotAnalyzed: ${H($)} (I: a4b67d95fdd6b98d3241c0a7d0a93c22)`);let w={},T={};Object.keys(m).filter(G=>!o.includes(G)).forEach(G=>{let y=m[G],I=y[y.length-1];w[G]=I;let v=_({ibGib:I});T[v]=G});let A=Object.keys(w).length;if(A>0){let G={};Object.keys(n).filter(P=>!o.includes(P)).forEach(P=>{let D=w[P];if(D){let L=_({ibGib:D});G[L]=n[P]}else console.error(`${p} latestIbGibCorrespondingToTjpAddr is falsy (E: 8a5d3f2e1c4b90876543210fe89abcdf)`)}),M&&console.log(`${p} latestAddrsMap *before* getLatestAddrs: ${H(G)} (I: 427b4bb78595e9e521ecf2c5e5c80722)`);let y=Object.values(w),I={};if(y.length>0){if(h.length===0)throw new Error("(UNEXPECTED) space/s falsy? (E: 8e878975e3561df9a8dc4c628b0abc23)");for(let P of h){let D=await _e({ibGibs:y,space:P});if(!D?.data?.latestAddrsMap)throw new Error("(UNEXPECTED) getLatestAddrs result latestAddrsMap falsy (E: 088caa1fc95fd3b079108ab63ef33422)");let L=D.data.latestAddrsMap;Object.keys(L).forEach(K=>{let J=L[K];J?I[K]=J:I[K]||(I[K]=null)})}if(y.forEach(P=>{let D=_({ibGib:P});I[D]||(I[D]=D)}),Object.keys(I).length!==A)throw new Error("(UNEXPECTED) latestAddrsMap is not the same size as the incoming map (E: 666af512bbd44534983bb28ee8d43fed)");M&&console.log(`${p} queriedLatestAddrsMap: ${H(I)} (I: 7b39a5f7ce9e9d9fabae4be98ed44522)`),G={...I,...G}}M&&console.log(`${p} combined latestAddrsMap: ${H(G)} (I: e3aedea63f29c5b06a79632f691aa522)`);let v=[],N={};Object.values(w).forEach(P=>{let D=_({ibGib:P}),L=T[D],K=G[D];if(!K)throw new Error("(UNEXPECTED) latestAddrInSpace not found in latestAddrsMap (E: 095d2b3f88e3e8a2c3e7d3de4c6d5622)");K===D?(M&&console.log(`${p} analyzed ${L} (I: afb7960900f04b8a87538f4c7bd903b7)`),o.push(L)):(v.push(K),N[K]=L)});let x=[];for(let P=0;P<(r??[]).length;P++){let L=r[P].rel8ns??{};Object.keys(L).filter(J=>!(i??[]).includes(J)).filter(J=>a?a.includes(J):!0).forEach(J=>{(L[J]??[]).forEach(mt=>{!x.includes(mt)&&!r.some(ge=>_({ibGib:ge})===mt)&&!te({gib:R({ibGibAddr:mt}).gib})&&x.push(mt)})})}return e=Xt([...e??[],...x,...v]),await hr({ibGibs:r,ibGibAddrs:e,gotten:t,tjpAddrsAlreadyAnalyzed:o,skipAddrs:s,skipRel8nNames:i,onlyRel8nNames:a,maxRetries:c,msBetweenRetries:l,space:d,spaces:h,timeLogName:b,live:!0,mapTjpAddrToLatestAddrsInSpace:n})}else return r||(r=[]),Object.values(t??{}).forEach(G=>{let y=_({ibGib:G});r.some(I=>_({ibGib:G})===y)||r.push(G)}),await hr({ibGibs:r,ibGibAddrs:e,gotten:t,skipAddrs:s,skipRel8nNames:i,onlyRel8nNames:a,maxRetries:c,msBetweenRetries:l,space:d,spaces:h,timeLogName:b,live:!1})}catch(h){let g=`${p} ${h.message}`;throw console.error(g),b&&console.timeLog(b,`${p} error: ${g}`),h}finally{b&&console.timeLog(b,`${p} complete.`)}}f(Sa,"getGraphProjection_Live");async function Ga({ibGibs:r,ibGibAddrs:e,gotten:t,skipAddrs:o,skipRel8nNames:n,onlyRel8nNames:s,maxRetries:i,msBetweenRetries:a,space:c,spaces:l,timeLogName:d}){let u=`[${Ga.name}]`;try{let b=[];r??=[],t??={},o??=[],n??=[],d&&console.timeLog(d,`${u} analyzing next step starting...`);for(let p=0;p<r.length;p++){let h=r[p],g=_({ibGib:h}),{gib:m}=R({ibGib:h});if(m===U)throw new Error("cannot get dependency graph of primitive. (E: 5493b8908d134bdf887e91122a6a57e3)");Object.keys(t).includes(g)||(t[g]=h);let $={},w=h.rel8ns||{},T=(Object.keys(w)||[]).filter(G=>!n.includes(G));s&&(T=T.filter(G=>s.includes(G)));let A=Object.keys(t);for(let G=0;G<T.length;G++){let y=T[G],I=w[y]??[],v=I.filter(x=>x===""||x===void 0||x===null||!x.includes(oe));v.length>0&&console.warn(`${u} (UNEXPECTED) has falsyAddrs: ${v} (W: da9505cb0a4db68a4aff7f279ad2d322)`),I.filter(x=>!!x).filter(x=>!A.includes(x)).filter(x=>!o.includes(x)).filter(x=>R({ibGibAddr:x}).gib!==U).filter(x=>!b.includes(x)).forEach(x=>{let P=tt({addr:x});(P||[]).length===0?b.push(x):$[x]=P})}if(Object.keys($).length>0)throw new Error(`invalid addresses found in dependency graph. Errors (clipped to 1kB): ${JSON.stringify($).substring(0,1024)} (E: d2416b9b23fa4d178e6c7104b40ee78c)`)}if(d&&console.timeLog(d,`${u} analyzing next step complete.`),b.length>0){d&&console.timeLog(d,`${u} get addrsWeDontHaveAlready_Rel8dAddrs starting...`);let p=await Xn({ibGibAddrs:b,gotten:t,skipAddrs:o,maxRetries:i,msBetweenRetries:a,timeLogName:d,space:c,spaces:l});p.forEach(g=>t[_({ibGib:g})]=g),d&&console.timeLog(d,`${u} call getGraphProjection recursively starting...`);let h=await hr({ibGibs:p,live:!1,gotten:t,skipAddrs:o,skipRel8nNames:n,onlyRel8nNames:s,maxRetries:i,msBetweenRetries:a,space:c,spaces:l});return d&&console.timeLog(d,`${u} call getGraphProjection recursively complete.`),h}else return t}catch(b){let p=`${u} ${b.message}`;throw console.error(`${p} (E: 8a42e56616014e7a8848aa6bb6f2722b)`),d&&console.timeLog(d,`${u} error: ${p}`),new Error(`${p} (E: a21b0682121746a480572b83413cf2d0)`)}finally{d&&console.timeLog(d,`${u} complete.`)}}f(Ga,"getGraphProjection_NonLive");function co({ibGibs:r}){let e=`[${co.name}]`;try{if(M&&console.log(`${e} starting... (I: 6019a812cff8597f79c12088e45cc226)`),r){let t={};return r.forEach(o=>{t[_({ibGib:o})]=o}),t}else return}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{M&&console.log(`${e} complete.`)}}f(co,"toFlatGraph");function sd({graphA:r,graphB:e,slowButThorough:t}){let o=`[${sd.name}]`;try{if(M&&console.log(`${o} starting... (I: e50a98b659189dece8b4ef581e4ad826)`),!(Object.keys(r).length===Object.keys(e).length))return M&&console.log(`${o} not the same size. false. (I: e1044e52421dbf7e067e0fe850ac6826)`),!1;for(let s of Object.keys(r))if(!e[s])return M&&console.log(`${o} addr (${s}) in graphA not found in graphB (I: 264c68408378ce30b8f6a978f8b86926)`),!1;if(t)for(let s of Object.keys(r)){let i=ve({ibGib:r[s]}),a=JSON.stringify(i),c=ve({ibGib:e[s]}),l=JSON.stringify(c);if(a!==l)return M&&console.log(`${o} jsonA !== jsonB for addr (${s}) (I: 98ed9f58ac88dabba83f96582f725926)`),!1}return!0}catch(n){throw console.error(`${o} ${E(n)}`),n}finally{M&&console.log(`${o} complete.`)}}f(sd,"graphsAreEquivalent");var Ta=["past","dna","tjp","ancestor"];async function id({ibGib:r,ibGibAddr:e,onlyRel8nNames:t,skipRel8nNames:o,metaspace:n,space:s}){let i=`[${id.name}]`;try{if(M&&console.log(`${i} starting...`),!r&&!e)throw new Error("Either ibGib or ibGibAddr is required (E: genuuid)");if(r&&e)throw new Error("Cannot provide both ibGib and ibGibAddr (E: genuuid)");if(!s)throw new Error("space is required (E: genuuid)");if(!n)throw new Error("metaspace is required (E: genuuid)");if(t!==void 0){if(t.length===0)throw new Error("onlyRel8nNames cannot be empty (E: genuuid)");let g=t.filter(m=>Ta.includes(m));if(g.length>0)throw new Error(`onlyRel8nNames contains forbidden intrinsic relationship names: ${g.join(", ")} (E: genuuid)`)}let a=Xt([...Ta,...o??[]]),c=r;if(!c&&e&&(c=await Vn({addr:e,space:s,metaspace:n}),!c))throw new Error(`Root ibGib '${e}' not found in space or metaspace (E: genuuid)`);if(!c)throw new Error("(UNEXPECTED) rootNode falsy (E: genuuid)");let l={},d=[],u=new Map,b=new Set;async function p(g){let m=_({ibGib:g});if(u.has(m))return u.get(m);if(b.has(m))return{reifiedIbGib:g,hasChanges:!1};b.add(m);try{let $=g,w=!1,T=g.rel8ns?.tjp?.at(0)??m,A=await _e({addrs:[T],space:s}),G=A?.data?.latestAddrsMap?.[T]??A?.data?.latestAddrsMap?.[m];if(G&&G!==m){let x=await Vn({addr:G,space:s,metaspace:n});x&&($=x,w=!0,l[m]=G)}let y=!1,I={},v=$.rel8ns??{},N=Object.keys(v).filter(x=>!a.includes(x));t&&(N=N.filter(x=>t.includes(x)));for(let x of N){let P=v[x]??[];for(let D of P){if(!D||te({gib:R({ibGibAddr:D}).gib}))continue;let L=await Vn({addr:D,space:s,metaspace:n});if(!L)continue;let K=await p(L);if(K.hasChanges){let J=_({ibGib:K.reifiedIbGib});J!==D&&(y=!0,I[x]??=[],I[x].some(Je=>Je.oldAddr===D)||I[x].push({oldAddr:D,newAddr:J}))}}}if(y){let x=await ye({src:$,rel8nsToReplaceByAddr:I,dna:!0,nCounter:!0});await Q({resTransform:x,space:s}),await Ge({ibGib:x.newIbGib,space:s});let P=x.newIbGib,D=_({ibGib:P});d.push(P),l[m]=D;let L={reifiedIbGib:P,hasChanges:!0};return u.set(m,L),L}else if(w){let x={reifiedIbGib:$,hasChanges:!0};return u.set(m,x),x}else{let x={reifiedIbGib:g,hasChanges:!1};return u.set(m,x),x}}finally{b.delete(m)}}f(p,"reifyNode");let h=await p(c);return{reifiedIbGib:h.reifiedIbGib,hasChanges:h.hasChanges,reifiedAddrsMap:l,evolvedIbGibs:d}}catch(a){throw console.error(`${i} ${E(a)} (E: genuuid)`),a}finally{M&&console.log(`${i} complete.`)}}f(id,"reifyDependencyGraph");async function Vn({addr:r,space:e,metaspace:t}){let o=await ie({addrs:[r],space:e});if(o.success&&o.ibGibs&&o.ibGibs.length>0)return o.ibGibs[0];let n=o.rawResultIbGib?.ibGibs??[];if(n.length>0)return n[0];if(t){let s=await t.get({addrs:[r],space:e});if(s.success&&s.ibGibs&&s.ibGibs.length>0)return s.ibGibs[0]}}f(Vn,"getIbGibFromSpaceOrMetaspace");var ee=!1;async function xa({keystoneData:r}){let e=`[${xa.name}]`;try{return ee&&console.log(`${e} starting... (I: c3022a146faac9730154f34d1439a225)`),[dr].join(" ")}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{ee&&console.log(`${e} complete.`)}}f(xa,"getKeystoneIb");async function va({ib:r}){let e=`[${va.name}]`;try{ee&&console.log(`${e} starting... (I: 73cb6832984255ed48b2f44db6a21e25)`);let[t]=r.split(" ");if(t!==dr)throw new Error(`invalid keystone ib. atom found in ib (${t}) does not match keystone atom (${dr}) (E: 79b3d587824c4271b6e60acc76e0c825)`);return{atom:t}}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{ee&&console.log(`${e} complete.`)}}f(va,"parseKeystoneIb");async function gr({ib:r}){try{return await va({ib:r}),!0}catch{return!1}}f(gr,"validateKeystoneIb");function nE(r){if(!r||typeof r!="string")return!1;let e=r.trim();return e.length<3||e.length>254?!1:ta.test(e)}f(nE,"validateEmail");async function Da({pool:r,requiredChallengeIds:e,targetAddr:t}){let o=r.config.behavior,n=new Set,s=Object.keys(r.challenges);if(e&&e.length>0){for(let i of e){if(!r.challenges[i])throw new Error(`(UNEXPECTED) Required challenge ID not found in pool: ${i} (E: 10c5619d80d8cf6cc84ffbf8be0dbc25)`);s.includes(i)&&n.add(i)}s=s.filter(i=>!n.has(i))}if(o.targetBindingCount>0&&t){let i=[...s].sort(),a=await X({s:t});for(let c=0;c<o.targetBindingCount;c++){if(i.length===0)throw new Error("Entropy Exhaustion. Cannot satisfy target binding. Sorted available pool is empty. (E: 341b95dc3a58be3e083d1d9c4a0c4925)");let l=BigInt("0x"+a),d=Number(l%BigInt(i.length)),u=i[d];n.add(u),i.splice(d,1),s=s.filter(b=>b!==u),a=await X({s:a})}}if(o.selectSequentially>0){if(s.length<o.selectSequentially)throw console.error(`[getDeterministicRequirements] Entropy Exhaustion! AvailableCount: ${s.length}, Required Seq: ${o.selectSequentially}. Available IDs: ${s.join(",")}`),new Error("Entropy Exhaustion. Insufficient challenges for FIFO requirement. (E: 9efa88003e1d5eccb837c85154ee5625)");s.slice(0,o.selectSequentially).forEach(a=>n.add(a)),s=s.slice(o.selectSequentially)}return{mandatoryIds:n,availableIds:s}}f(Da,"getDeterministicRequirements");function mr({pools:r,poolId:e,poolFilter:t,verb:o}){let n="[resolveTargetPool]";try{let s;if(e){if(s=r.find(i=>i.id===e),!s)throw new Error(`Pool not found with ID: ${e} (E: 4a2b17428515c1e82813158581898125)`)}else if(t){let i=r.filter(t);if(i.length===0)throw new Error("No pool matched the provided filter. (E: 5b3c27428515c1e82813158581898125)");s=i[0]}else{if(!o)throw new Error("Cannot auto-resolve pool without a verb. (E: 6c4d37428515c1e82813158581898125)");if(s=r.find(i=>i.config.allowedVerbs&&i.config.allowedVerbs.includes(o)),s||(s=r.find(i=>!i.config.allowedVerbs||i.config.allowedVerbs.length===0)),!s)throw new Error(`No suitable pool found for verb: ${o} (E: 7d5e47428515c1e82813158581898125)`)}if(o&&s.config.allowedVerbs&&s.config.allowedVerbs.length>0&&!s.config.allowedVerbs.includes(o))throw new Error(`Pool ${s.id} is not authorized for verb: ${o} (E: 8e6f57428515c1e82813158581898125)`);return s}catch(s){throw console.error(`${n} ${E(s)}`),s}}f(mr,"resolveTargetPool");async function At({pool:r,targetAddr:e,requiredChallengeIds:t}){let o="[selectChallengeIds]";try{let{mandatoryIds:n,availableIds:s}=await Da({pool:r,requiredChallengeIds:t,targetAddr:e}),i=r.config.behavior.selectRandomly,a=[];if(i>0){if(s.length<i)throw new Error(`Insufficient challenges for random requirement. Need ${i}, have ${s.length} (E: 9f7a67428515c1e82813158581898125)`);let c=[...s].sort(()=>.5-Math.random());a.push(...c.slice(0,i))}return[...n,...a]}catch(n){throw console.error(`${o} ${E(n)}`),n}}f(At,"selectChallengeIds");async function Oa({salt:r,timestamp:e,index:t}){return(await X({s:`${r}${e}${t}`})).substring(0,16)}f(Oa,"generateOpaqueChallengeId");async function ad({prevPools:r,targetPoolId:e,consumedIds:t,masterSecret:o,strategy:n,config:s,verb:i}){let a="[applyReplenishmentStrategy]";try{let c=JSON.parse(JSON.stringify(r)),l=c.findIndex(h=>h.id===e);if(l===-1)throw new Error(`Target pool ${e} not found in keystone data. (E: 75200388d22744838634524233772545)`);let d=c[l],u=await n.derivePoolSecret({masterSecret:o}),b=Date.now().toString(),p=s.behavior.replenish;if(i===jt&&(p=Te.deleteAll),p===Te.topUp){t.forEach(h=>delete d.challenges[h]);for(let h=0;h<t.length;h++){let g=await Oa({salt:s.salt,timestamp:b,index:h}),m=await n.generateSolution({poolSecret:u,poolId:d.id,challengeId:g});d.challenges[g]=await n.generateChallenge({solution:m})}}else if(p===Te.replaceAll)d.challenges=await bo({config:s,masterSecret:o});else if(p===Te.consume)t.forEach(h=>delete d.challenges[h]);else if(p===Te.deleteAll)d.challenges={};else throw new Error(`Unknown replenish strategy: ${p}. Valid list: ${H(ea)} (E: 0acf56f1e1486240080e11e8046d0825)`);return c}catch(c){throw console.error(`${a} ${E(c)}`),c}}f(ad,"applyReplenishmentStrategy");async function St({targetPoolId:r,prevPools:e,masterSecret:t,challengeIds:o,claim:n,requiredChallengeIds:s}){let i="[solveAndReplenish]";try{ee&&console.log(`${i} starting... poolId: ${r}, ids: ${o.length}`);let a=e.find(h=>h.id===r);if(!a)throw new Error(`Target pool not found: ${r} (E: genuuid)`);let c=Tt.create({config:a.config}),l=await c.derivePoolSecret({masterSecret:t});if(!await uo({pool:a,signingSecret:t}))throw new Error(`Crypto Violation: Invalid signing secret for pool: ${a.id} (E: genuuid)`);let u=[];for(let h of o){let g=await c.generateSolution({poolSecret:l,poolId:a.id,challengeId:h});u.push(g)}let b={claim:n,solutions:u,requiredChallengeIds:s&&s.length>0?s:void 0},p=await ad({prevPools:e,targetPoolId:a.id,consumedIds:o,masterSecret:t,strategy:c,config:a.config,verb:n.verb});return{proof:b,nextPools:p}}catch(a){throw console.error(`${i} ${E(a)}`),a}}f(St,"solveAndReplenish");async function Na({pool:r}){let e=`[${Na.name}]`;try{if(ee&&console.log(`${e} starting... (I: e2ffd568b698cc12d8c5e838d73ae726)`),!r.config)throw new Error("(UNEXPECTED) pool.configy falsy? (E: fcde88fe20e8004a58d7e445436bf526)");if(r.config.type!==je.hash_reveal_v1)throw new Error("(UNEXPECTED) pool.config.type !== KeystoneChallengeType.hash_reveal_v1? (E: e205f8872909c37168a624a9df778c26)");let t=[],{algo:o,rounds:n,salt:s}=r.config,i=[we.sha_256,we.sha_512];return o?i.includes(o)||t.push(`${e} invalid hash algorithm (${o}). Must be one of ${i}. (E: a22399ca3a68e63ffcc7507699be5826)`):t.push(`${e} algorithm required. (E: 8cd6bfb0590862b9bae24d98d2cf3826)`),n&&typeof n=="number"&&Number.isInteger(n)?n>Fn&&t.push(`${e} rounds too high. max rounds: ${Fn} (E: 31ce082f7fd88d6b58ef08a816458826)`):t.push(`${e} invalid rounds (${n}). must be positive integer. (E: 73c643ccda78afaf28d52a6871a9e826)`),s&&typeof s=="string"?Mn.test(s)||t.push(`${e} invalid salt (${s.substring(0,99)}). Must match regexp ${Mn}`):t.push(`${e} invalid salt (${s}). must be truthy string value. (E: 564a4844ec88fc1988197ce89c381426)`),t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{ee&&console.log(`${e} complete.`)}}f(Na,"validateChallengePool_typeHashRevealV1");async function Ca({pool:r}){let e=`[${Ca.name}]`;try{ee&&console.log(`${e} starting... (I: 1a0eafc158a83d1ba8fc019d5c979a26)`);let t=[];if(r.config){if(r.config.id?kn.test(r.config.id)||t.push(`${e} pool.config.id is not formatted correctly. must pass regexp: ${kn.source}`):t.push(`${e} pool.config.id falsy (E: 31d7943d95f877326d5f4ea14463d626)`),r.config.behavior){let{size:n,selectSequentially:s,selectRandomly:i,targetBindingCount:a}=r.config.behavior;(!n||n===0)&&t.push(`${e} invalid pool.config.behavior.size (${n}). Must be positive integer. (E: b221e36ec102bdc944552248ce8fe626)`);let c=(s||0)+(i||0)+(a||0);c>=n&&t.push(`${e} Total requested challenges (${c}) cannot equal or exceed pool size (${n}) to prevent full pool exposure and selection exhaustion. (E: 81cb834f826315264bca81c15fca58f1)`)}else t.push(`${e} pool.config.behavior falsy (E: bede081c066c39732eefe2f92e296326)`);let o=r.config.type;switch(o){case je.hash_reveal_v1:(await Na({pool:r})).forEach(s=>t.push(s));break;default:throw new Error(`(UNEXPECTED) unknown pool.config.type (${o})? We only implement the following at this time: ${Qi} (E: cce5285cf7580b8bc82172488eba2826)`)}}else t.push(`${e} pool.config falsy. (E: 8d05c875a1d2c58018a5eaf803977d26)`);return t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{ee&&console.log(`${e} complete.`)}}f(Ca,"validateChallengePool");function Pa({data:r}){let e="[validateKeystoneMetadata]",t=[],o=f((n,s)=>{n&&(n.username!==void 0&&(typeof n.username!="string"||!Bn.test(n.username))&&t.push(`${e} invalid username in ${s} (${n.username}). Must match ${Bn}`),n.description!==void 0&&(typeof n.description!="string"||!jn.test(n.description))&&t.push(`${e} invalid description in ${s} (${n.description}). Must match ${jn}`),n.expirationUTC!==void 0&&(typeof n.expirationUTC!="string"||isNaN(Date.parse(n.expirationUTC)))&&t.push(`${e} invalid expirationUTC in ${s} (${n.expirationUTC}). Must be a valid ISO-8601 string`))},"checkDetails");return o(r.frameDetails,"frameDetails"),o(r.checkpointDetails,"checkpointDetails"),t}f(Pa,"validateKeystoneMetadata");async function lo({keystoneIbGib:r}){let e=`[${lo.name}]`;try{ee&&console.log(`${e} starting... (I: ec6ba82ec848b5ac3d8953e89d8d9826)`);let t=[],{data:o,rel8ns:n}=r;await gr({ib:r.ib})||t.push(`${e} invalid keystone ib (${r.ib}). (E: ad7a88bc38c290a184dfbd42be48f526)`),Pa({data:o}).forEach(a=>t.push(a)),o.proofs&&o.proofs.length>0&&t.push(`${e} proofs already exist on genesis keystone. (E: 7a5e15f20918f1bbd8ffb62857dcd526)`);for(let a of o.challengePools)(await Ca({pool:a})).forEach(l=>t.push(l)),(!a.challenges||Object.keys(a.challenges).length===0)&&t.push(`${e} invalid pool (${a.id}). pool.challenges is falsy/empty. (E: 8cd16a5416ae62a058342828be465b26)`);return o.revocationInfo&&t.push(`${e} genesis keystone already has revocationInfo. (E: e11408d0c558d0fa948efbce611ec826)`),t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{ee&&console.log(`${e} complete.`)}}f(lo,"validateGenesisKeystone");function cd({currDelegates:r,prevDelegates:e}){let t=r||{},o=e||{},n=Object.keys(t),s=Object.keys(o);if(n.length!==s.length)return!0;for(let i of n){let a=t[i],c=o[i];if(!c||a.delegateTjpAddr!==c.delegateTjpAddr||a.delegateAddr!==c.delegateAddr||a.thisAddr!==c.thisAddr)return!0}return!1}f(cd,"isDelegatesChanged");async function ld({currDelegates:r,prevIbGib:e,lc:t,errors:o}){let n=Object.keys(r),s=_({ibGib:e});for(let i of n){let a=r[i];i!==a.delegateTjpAddr&&o.push(`${t} Invalid delegate mapping: Key '${i}' does not match delegateTjpAddr '${a.delegateTjpAddr}'. (E: 9c8da8bc38c290a184dfbd42be48f526)`);let[c,l,d]=await Promise.all([gr({ib:a.delegateTjpAddr.split("^")[0]}),gr({ib:a.delegateAddr.split("^")[0]}),gr({ib:a.thisAddr.split("^")[0]})]);c||o.push(`${t} Delegate delegateTjpAddr '${a.delegateTjpAddr}' is not a valid keystone address. (E: 10d8a8bc38c290a184dfbd42be48f526)`),l||o.push(`${t} Delegate delegateAddr '${a.delegateAddr}' is not a valid keystone address. (E: 20d8a8bc38c290a184dfbd42be48f526)`),d||o.push(`${t} Delegate thisAddr '${a.thisAddr}' is not a valid keystone address. (E: 30d8a8bc38c290a184dfbd42be48f526)`),a.thisAddr===s||(e.rel8ns?.past||[]).includes(a.thisAddr)||o.push(`${t} Delegate thisAddr '${a.thisAddr}' is not a valid historical address in the parent keystone timeline. (E: 40d8a8bc38c290a184dfbd42be48f526)`);let b=a.allowedVerbs||[];(a.role==="sync-delegate"||b.includes("sync")||b.includes(ro))&&!a.spaceId&&o.push(`${t} Sync delegate '${a.delegateTjpAddr}' missing required spaceId. (E: 50d8a8bc38c290a184dfbd42be48f526)`),a.expirationUTC&&isNaN(Date.parse(a.expirationUTC))&&o.push(`${t} Delegate expirationUTC '${a.expirationUTC}' is not a valid ISO-8601 timestamp. (E: 60d8a8bc38c290a184dfbd42be48f526)`)}}f(ld,"validateDelegates");async function Er({currentIbGib:r,prevIbGib:e}){let t=`[${Er.name}]`,o=[];try{if(!r)throw new Error("(UNEXPECTED) currentIbGib falsy? (E: 3c0f02655fa8279e386a079ebb604b25)");if(!e)throw new Error("(UNEXPECTED) prevIbGib falsy? (E: 0d07c812634d839c784f31b8848ba825)");let n=await se({ibGib:r});n&&n.length>0&&o.push(...n);let s=r.data,i=e.data;await gr({ib:r.ib})||o.push(`${t} invalid keystone ib (${r.ib}). (E: a98dc8bc38c290a184dfbd42be48f526)`),Pa({data:s}).forEach(g=>o.push(g));let l=s.delegates||{},d=i.delegates||{};cd({currDelegates:l,prevDelegates:d})&&(s.proofs?.some(m=>m.claim?.verb===ce)||o.push(`${t} Policy Violation: Delegates map was mutated but no proof for manage verb ('${ce}') is present. (E: 819fa8cb28c9b60e68994511a5825)`)),await ld({currDelegates:l,prevIbGib:e,lc:t,errors:o});let b=s.n??-2,p=i.n??-2;b<0&&o.push("invalid keystone.currData.n is undefined or null. (E: 9fbe38704b68829d18ea1d0940d0aa26)"),p<0&&o.push("invalid keystone.prevData.n is undefined or null. (E: 6dc5aa9c87017db6080ed4268b07af26)"),b!==p+1&&o.push(`keystone data.n values are not sequential. prevData.n: ${p}, currData.n: ${b}. (E: 5ae12809f2c67216d38d8ba8d6c42826)`);for(let g of s.proofs){if(g.solutions.length===0){o.push(`Proof ${g.id||"unknown"} has no solutions. (E: e2b4683ce0ce30f798ec77841e88c826)`);continue}let m=g.solutions[0].poolId,$=i.challengePools.find(w=>w.id===m);if(!$){o.push(`Proof references unknown pool: ${m}`);continue}await La({proof:g,pool:$,errors:o})}if(s.revocationInfo){let g=s.revocationInfo.proof.claim.target,m=_({ibGib:e});g!==m&&o.push(`Revocation target mismatch. Expected ${m}, got ${g}`)}let h=new Set(s.proofs.map(g=>g.solutions?.[0]?.poolId).filter(Boolean));for(let g of s.proofs){let m=g.claim;if(m?.details){let $=m.details,w=$.type,T=$.info;if(w==="add-pool"){let A=T;if(!A||!Array.isArray(A.add)||A.add.length===0){o.push(`details type is '${w}' but payload is invalid. (E: 1fa2a8cb28c9b60e68994511a5825)`);continue}let G=new Set(i.challengePools.map(I=>I.id)),y=new Set(s.challengePools.map(I=>I.id));for(let I of A.add)y.has(I)||o.push(`ClaimDetails_AddPool lists pool ${I} but it is missing in the evolved keystone. (E: 2fa2a8cb28c9b60e68994511a5825)`),G.has(I)&&o.push(`ClaimDetails_AddPool attempts to add existing pool ${I}. (E: 3fa2a8cb28c9b60e68994511a5825)`);s.challengePools.length!==i.challengePools.length+A.add.length&&o.push(`Structural mismatch: expected ${i.challengePools.length+A.add.length} pools, found ${s.challengePools.length}. (E: 4fa2a8cb28c9b60e68994511a5825)`);for(let I of i.challengePools){let v=s.challengePools.find(N=>N.id===I.id);if(!v){o.push(`Existing pool ${I.id} was removed during add-pool transition. (E: 5fa2a8cb28c9b60e68994511a5825)`);continue}JSON.stringify(I.config)!==JSON.stringify(v.config)&&o.push(`Existing pool config ${I.id} was mutated during add-pool transition. (E: 6fa2a8cb28c9b60e68994511a5825)`),!h.has(I.id)&&JSON.stringify(I.challenges)!==JSON.stringify(v.challenges)&&o.push(`Existing pool challenges ${I.id} were mutated during add-pool transition. (E: 7fa2a8cb28c9b60e68994511a5825)`)}}else if(w==="replace-pool"){let A=T;if(!A||typeof A.replace!="string"||!A.replace){o.push(`details type is '${w}' but payload is invalid. (E: 8fa2a8cb28c9b60e68994511a5825)`);continue}let G=A.replace,y=i.challengePools.map(x=>x.id).sort(),I=s.challengePools.map(x=>x.id).sort();JSON.stringify(y)!==JSON.stringify(I)&&o.push("replace-pool transition mutated the pool IDs set. (E: 9fa2a8cb28c9b60e68994511a5825)");let v=i.challengePools.find(x=>x.id===G),N=s.challengePools.find(x=>x.id===G);(!v||!N)&&o.push(`Replaced pool ${G} not found in keystone challenge pools. (E: afa2a8cb28c9b60e68994511a5825)`);for(let x of i.challengePools){if(x.id===G)continue;let P=s.challengePools.find(D=>D.id===x.id);P&&(JSON.stringify(x.config)!==JSON.stringify(P.config)&&o.push(`Unrelated pool config ${x.id} was mutated during replace-pool. (E: bfa2a8cb28c9b60e68994511a5825)`),!h.has(x.id)&&JSON.stringify(x.challenges)!==JSON.stringify(P.challenges)&&o.push(`Unrelated pool challenges ${x.id} were mutated during replace-pool. (E: cfa2a8cb28c9b60e68994511a5825)`))}}else if(w==="remove-pool"){let A=T;if(!A||!Array.isArray(A.remove)||A.remove.length===0){o.push(`details type is '${w}' but payload is invalid. (E: b7a2a8cb28c9b60e68994511a5825)`);continue}let G=new Set(A.remove),y=new Set(i.challengePools.map(v=>v.id)),I=new Set(s.challengePools.map(v=>v.id));for(let v of A.remove)y.has(v)||o.push(`ClaimDetails_RemovePool lists pool ${v} but it is missing in the previous keystone. (E: c7a2a8cb28c9b60e68994511a5825)`),I.has(v)&&o.push(`ClaimDetails_RemovePool lists pool ${v} but it is still present in the evolved keystone. (E: d7a2a8cb28c9b60e68994511a5825)`);s.challengePools.length!==i.challengePools.length-A.remove.length&&o.push(`Structural mismatch: expected ${i.challengePools.length-A.remove.length} pools, found ${s.challengePools.length}. (E: e7a2a8cb28c9b60e68994511a5825)`);for(let v of i.challengePools){if(G.has(v.id))continue;let N=s.challengePools.find(x=>x.id===v.id);if(!N){o.push(`Pool ${v.id} was unexpectedly removed. (E: f7a2a8cb28c9b60e68994511a5825)`);continue}JSON.stringify(v.config)!==JSON.stringify(N.config)&&o.push(`Remaining pool config ${v.id} was mutated during remove-pool. (E: 07a2a8cb28c9b60e68994511a5825)`),!h.has(v.id)&&JSON.stringify(v.challenges)!==JSON.stringify(N.challenges)&&o.push(`Remaining pool challenges ${v.id} were mutated during remove-pool. (E: 17a2a8cb28c9b60e68994511a5825)`)}}else if(w==="change-password"){let A=T;if(!A||!Array.isArray(A.change)||A.change.length===0){o.push(`details type is '${w}' but payload is invalid. (E: dfa2a8cb28c9b60e68994511a5825)`);continue}let G=i.challengePools.map(v=>v.id).sort(),y=s.challengePools.map(v=>v.id).sort();JSON.stringify(G)!==JSON.stringify(y)&&o.push("change-password transition mutated the pool IDs set. (E: efa2a8cb28c9b60e68994511a5825)");let I=new Set(A.change);for(let v of i.challengePools){let N=s.challengePools.find(x=>x.id===v.id);if(N)if(I.has(v.id)){v.isForeign&&o.push(`Security Violation: Password rotation attempted on foreign pool ${v.id}. (E: ffa2a8cb28c9b60e68994511a5825)`);let x={...v.config,salt:""},P={...N.config,salt:""};JSON.stringify(x)!==JSON.stringify(P)&&o.push(`Pool config metadata for rotated pool ${v.id} was mutated. (E: 00b2a8cb28c9b60e68994511a5825)`),v.config.salt===N.config.salt&&o.push(`Pool salt for rotated pool ${v.id} was not rotated. (E: 01b2a8cb28c9b60e68994511a5825)`)}else JSON.stringify(v.config)!==JSON.stringify(N.config)&&o.push(`Unrelated pool config ${v.id} was mutated during change-password. (E: 02b2a8cb28c9b60e68994511a5825)`),!h.has(v.id)&&JSON.stringify(v.challenges)!==JSON.stringify(N.challenges)&&o.push(`Unrelated pool challenges ${v.id} were mutated during change-password. (E: 03b2a8cb28c9b60e68994511a5825)`)}}else o.push(`Unknown claim details type: ${w}`)}}return o}catch(n){throw console.error(`${t} ${E(n)}`),n}finally{ee&&console.log(`${t} complete.`)}}f(Er,"validateKeystoneTransition");async function La({proof:r,pool:e,errors:t}){let o=`[${La.name}]`;try{ee&&console.log(`${o} starting... (I: b8f9b6085888eea2258bf579ecd5e825)`),e.config.allowedVerbs&&e.config.allowedVerbs.length>0&&(!r.claim.verb||!e.config.allowedVerbs.includes(r.claim.verb))&&t.push(`Policy Violation: Pool ${e.id} used for unauthorized verb ${r.claim.verb}`);let{mandatoryIds:n,availableIds:s}=await Da({pool:e,requiredChallengeIds:r.requiredChallengeIds,targetAddr:r.claim.target}),i=new Set(r.solutions.map(d=>d.challengeId));for(let d of n)i.has(d)||t.push(`Policy Violation: Missing mandatory challenge ${d}`);let a=[...i].filter(d=>!n.has(d)),c=e.config.behavior.selectRandomly;a.length<c&&t.push(`Policy Violation: Insufficient random count. Need ${c}, got ${a.length}`);for(let d of a)s.includes(d)||t.push(`Policy Violation: ID ${d} is invalid or double-dipped.`);let l=Tt.create({config:e.config});for(let d of r.solutions){let u=e.challenges[d.challengeId];u?await l.validateSolution({solution:d,challenge:u})||t.push(`Crypto Violation: Solution for ${d.challengeId} is invalid.`):t.push(`Crypto Violation: Challenge ${d.challengeId} not found in pool.`)}}catch(n){throw console.error(`${o} ${E(n)}`),n}finally{ee&&console.log(`${o} complete.`)}}f(La,"verifyProofAgainstPool");async function lt({prevIbGib:r,newData:e,metaspace:t,space:o}){let n=`[${lt.name}]`;try{if(ee&&console.log(`${n} starting... (I: 8b10e8920f08b7842803665834cf8925)`),!r.data)throw new Error("(UNEXPECTED) prevIbGib.data falsy? (E: 5e84875bf992c585b979e6c8ed5bf225)");if(r.data.revocationInfo)throw new Error(`Keystone has already been revoked (prevIbGib.data.revocationInfo truthy), so we cannot evolve the keystone. Keystone addr: ${_({ibGib:r})} (E: 45d7f846556829de6b2a701838c3f825)`);let s=r.data,i={};s.proofs&&(i.proofs=[]),s.challengePools&&(i.challengePools=[]),s.frameDetails&&(i.frameDetails={}),s.checkpointDetails&&(i.checkpointDetails={}),s.delegates&&(i.delegates="remove"),Object.keys(i).length===0&&(i=void 0);let a=await Fe({src:r,dataToRemove:i,dataToAddOrPatch:e,nCounter:!0});if(a.intermediateIbGibs)throw new Error("(UNEXPECTED) resMut8.intermediateIbGibs truthy? I'm not sure if we expect there to be intermediateIbGibs, but I feel like we shouldn't. Pretty sure we shouldn't, definitely don't *want* them. (E: ba40d55d7c2d36d438c413886f148625)");if(a.dnas)throw new Error("(UNEXPECTED) resMut8.dnas truthy? We do not want dnas with keystones. (E: 49470513d018f97d28024f4e82da3b25)");let c=a.newIbGib,l=await Er({currentIbGib:c,prevIbGib:r});if(l.length>0)throw console.error(`${n} Validation Failed:
20
+ ${l.join(`
21
+ `)}`),new Error(`(UNEXPECTED) invalid keystone after we just evolved it? Errors: ${l.join("; ")} (E: ae2c58406c1db7687879dfb89fc1f825)`);return await t.put({ibGib:c,space:o}),await t.registerNewIbGib({ibGib:c,space:o}),c}catch(s){throw console.error(`${n} ${E(s)}`),s}finally{ee&&console.log(`${n} complete.`)}}f(lt,"evolvePersistAndRegisterKeystone");async function Yn({data:r,metaspace:e,space:t}){let o=`[${Yn.name}]`;try{if(ee&&console.log(`${o} starting... (I: 5e32389700e9899e788cbefacef7c825)`),t??=await e.getLocalUserSpace({lock:!1}),!t)throw new Error("(UNEXPECTED) space was falsy and we couldn't get default local user space from metaspace? (E: 9a6498cf16a8801f19ec376749742225)");let s=(await k.firstGen({parentIbGib:k.primitive({ib:dr}),ib:await xa({keystoneData:r}),data:r,dna:!1,nCounter:!0,tjp:{timestamp:!0,uuid:!0}})).newIbGib;if(!s.data)throw new Error("(UNEXPECTED) keystoneIbGib.data falsy? We expect the data to be populated with real keystone data. (E: 38a358facdb89d16d81d48c8520d3d25)");if(!s.rel8ns)throw new Error("(UNEXPECTED) keystoneIbGib.rel8ns falsy? we expect the rel8ns to have ancestor and past. (E: 20cb7723dc33ae1ef808fe76d1bf4b25)");if(!s.rel8ns.past||s.rel8ns.past.length===0)throw new Error("(UNEXPECTED) keystoneIbGib.rel8ns.past falsy or empty? we expect the firstGen call to generate an interstitial ibgib that we will splice out. (E: 0fd8388d045ab9f37834c27d67e78825)");return s.data.n=0,s.data.isTjp=!0,delete s.rel8ns.tjp,delete s.rel8ns.past,s.gib=await V({ibGib:s}),await e.put({ibGib:s,space:t}),await e.registerNewIbGib({ibGib:s,space:t}),s}catch(n){throw console.error(`${o} ${E(n)}`),n}finally{ee&&console.log(`${o} complete.`)}}f(Yn,"createKeystoneIbGibImpl");async function fo({keystoneIbGib:r,dependencyGraph:e,getLatest:t,invalidIfMoreRecentKeystoneFoundInSpace:o,space:n}){let s=`[${fo.name}]`;try{if(ee&&console.log(`${s} starting... (I: 22e1ca1d5a08a3f90b7fe9da95df7b26)`),!r)throw new Error("(UNEXPECTED) keystoneIbGib falsy? (E: 26482871d529fff6e8899c5d8a6c3826)");let i=[];if(t){let u=_({ibGib:r}),b=await _e({ibGibs:[r],space:n});if(!b.data)throw new Error("(UNEXPECTED) resGetLatestAddrs.data falsy? (E: 3a23b3b420a8da1928219ca8d47b2126)");if(!b.data.latestAddrsMap)throw new Error("(UNEXPECTED) resGetLatestAddrs.data.latestAddrsMap falsy? (E: 93f1180598fb65a4b8d36e08d6c50426)");let{latestAddrsMap:p}=b.data;if(Object.keys(p).length===0)throw new Error("(UNEXPECTED) latestAddrsMap truthy but empty? (E: 7142f8f7625b9186281d08251e407826)");let h=p[u];if(h)if(h!==u)if(o)i.push(`${s} more recent keystone (${h}) found than the one passed in (${u}) in space (${n.ib}). (E: 64bf48de9448ee5c7528bf03bed2a826)`);else{let[g]=await Nn({addrs:[h],space:n});r=g}else ee&&console.log(`${s} incoming keystone (${u}) is the latest in the space (${n.ib}) (I: 8ffbd8d6cbc8a461e5e7f1084bd22a26)`);else console.warn(`${s} keystoneIbGib (${u}) not found in space (${n.ib}). I don't know what the implications of this are. (W: 258c88742448db34a585669484771826)`)}e??=await pr({ibGib:r,space:n});let a=Object.values(e),{mapWithTjp_NoDna:c,mapWithTjp_YesDna:l,mapWithoutTjps:d}=Jr({ibGibs:a});if(Object.keys(l).length>0&&i.push(`${s} DNA found. Keystones should NOT have DNA. (E: a3ec7827c4284cdea61c2372c0615826)`),Object.keys(d).length>0&&i.push(`${s} Non-tjp ibgibs found? Keystones are expected to have tjps. (E: a3ec7827c4284cdea61c2372c0615826)`),Object.keys(c).length>0){let u=Object.values(c),b=ar({ibGibs:u}),p=Object.keys(b);if(p.length===0)throw new Error("(UNEXPECTED) orderedKeystonesMap empty? (E: d437b80bef58e83a034b28af46278726)");if(p.length>1)throw new Error("(UNEXPECTED) more than one timeline in keystone graph? ATOW (02/19/2026) we are expecting only a single timeline. (E: 66085b14e3887a59c872afd240511f26)");let h=p[0],g=b[h];if(g.length===0)throw new Error("(UNEXPECTED) empty keystoneIbGibs_ordered? (E: 4a6b085aa8a76828a8d65367e7e56526)");if((await lo({keystoneIbGib:g[0]})).forEach($=>i.push($)),g.length!==1)for(let $=0;$<g.length-1;$++){let w=g[$],T=g[$+1],A=await Er({prevIbGib:w,currentIbGib:T});A.length>0&&(i.push(`${s} keystone has ${A.length} transition errors. i: ${$}. prevIbGib addr: ${_({ibGib:w})}. currentIbGib addr: ${_({ibGib:T})}. (E: 3ac17be916141d0c286ca5a87bb1b426)`),A.forEach(G=>i.push(G)));break}}else if(i.length===0)throw new Error("(UNEXPECTED) mapWithTjp_NoDna empty (which is an error) but errors.length === 0? If we get here, we expect one of the other errors to have been populated. (E: 7bca2866b6f8fca318923de8c88e8826)");return i}catch(i){throw console.error(`${s} ${E(i)}`),i}finally{ee&&console.log(`${s} complete.`)}}f(fo,"validateKeystoneGraph");async function bo({config:r,masterSecret:e}){let t=Tt.create({config:r}),o=await t.derivePoolSecret({masterSecret:e}),n={},s=r.behavior.size,i=Date.now().toString();for(let a=0;a<s;a++){let c=await Oa({salt:r.salt,timestamp:i,index:a}),l=await t.generateSolution({poolSecret:o,poolId:r.id,challengeId:c});n[c]=await t.generateChallenge({solution:l})}return n}f(bo,"generatePoolChallenges");async function Ra({prevPool:r,newMasterSecret:e}){let t=r.config,o=(await F()).substring(0,16),n={...t,salt:o},s=await bo({config:n,masterSecret:e});return{id:r.id,config:n,challenges:s,...r.isForeign!==void 0?{isForeign:r.isForeign}:{},...r.metadata?{metadata:r.metadata}:{}}}f(Ra,"rotatePoolChallenges");async function uo({pool:r,signingSecret:e}){let t=Object.keys(r.challenges);if(t.length===0)return!1;try{let o=t[0],n=r.challenges[o],s=Tt.create({config:r.config}),i=await s.derivePoolSecret({masterSecret:e}),a=await s.generateSolution({poolSecret:i,poolId:r.id,challengeId:o});return await s.validateSolution({solution:a,challenge:n})}catch{return!1}}f(uo,"verifyPoolSecret");var q=!1,po=class r{static{f(this,"KeystoneService_V1")}lc=`[${r.name}]`;async genesis({masterSecret:e,emails:t,frameDetails:o,credentialIds:n,dataToPatch:s,configs:i,metaspace:a,space:c,isPrimary:l}){let d=`${this.lc}[${this.genesis.name}]`;try{q&&console.log(`${d} starting... (I: c98ae8adbc5888dbf84c5aced7610b25)`);let u=[];for(let h of i){let g=await bo({config:h,masterSecret:e});u.push({id:h.id,config:h,challenges:g})}if(u.length===0)throw new Error("No challenge pools created. (E: 38e538530996940e1f16a8b199995825)");let b={challengePools:u,proofs:[]};return t&&t.length>0&&(b.emails=[...t]),n&&n.length>0&&(b.credentialIds=[...n]),(o||l!==void 0)&&(b.frameDetails={...o||{}},l!==void 0&&(b.frameDetails.isPrimary=l)),s&&Object.assign(b,s),await Yn({data:b,metaspace:a,space:c})}catch(u){throw console.error(`${d} ${E(u)}`),u}finally{q&&console.log(`${d} complete.`)}}async sign({latestKeystone:e,masterSecret:t,claim:o,poolId:n,poolFilter:s,requiredChallengeIds:i=[],frameDetails:a,metaspace:c,space:l,dataToPatch:d}){let u=`${this.lc}[${this.sign.name}]`;try{q&&console.log(`${u} starting...`);let b=e.data;if(b.revocationInfo)throw new Error("Keystone has been revoked. Cannot sign. (E: 4f2198c39116d15c48ba191940316825)");if(Wn({keystone:e}))throw new Error(`Keystone is expired (${b.frameDetails?.expirationUTC}). Cannot sign. (E: 7f2198c39116d15c48ba191940316825)`);let p=mr({pools:b.challengePools,poolId:n,poolFilter:s,verb:o.verb});q&&console.log(`${u} Selected pool: ${p.id} (size: ${Object.keys(p.challenges).length}) (I: 6b26d6f4aad18380f2b3a0989b592826)`);let h=await At({pool:p,targetAddr:o.target,requiredChallengeIds:i}),{proof:g,nextPools:m}=await St({targetPoolId:p.id,prevPools:b.challengePools,masterSecret:t,challengeIds:h,claim:o,requiredChallengeIds:i}),$=(b.n??0)+1,w;if($%_t===0){let G={...e,data:{...b,frameDetails:a}};w=await this.getAggregateDetails({latestKeystone:G,metaspace:c,space:l})}let T={challengePools:m,proofs:[g],frameDetails:a,checkpointDetails:w,...b.delegates?{delegates:b.delegates}:{},...d};return await lt({prevIbGib:e,newData:T,metaspace:c,space:l})}catch(b){throw console.error(`${u} ${E(b)}`),b}finally{q&&console.log(`${u} complete.`)}}async validate({currentIbGib:e,prevIbGib:t}){return await Er({currentIbGib:e,prevIbGib:t})}async registerDelegate({parentKeystone:e,delegateKeystone:t,masterSecret:o,signingPoolId:n,frameDetails:s,metaspace:i,space:a,allowedVerbs:c,deviceName:l,expirationUTC:d,ttlSeconds:u}){let b=`${this.lc}[${this.registerDelegate.name}]`;try{if(q&&console.log(`${b} starting...`),!n)throw new Error("signingPoolId is required (E: genuuid)");let p=await fo({keystoneIbGib:t,getLatest:!0,invalidIfMoreRecentKeystoneFoundInSpace:!1,space:a});if(p.length>0)throw new Error(`Delegate keystone validation failed: ${p.join(", ")} (E: 88fa8ab28c9b60e68994511a5825)`);let h=e.data,g=h.challengePools.find(y=>y.id===n);if(!g)throw new Error(`Parent keystone does not contain signing pool: ${n} (E: 818fa8ab28c9b60e68994511a5825)`);if(g.config.allowedVerbs&&g.config.allowedVerbs.length>0&&!g.config.allowedVerbs.includes(ce))throw new Error(`Signing pool ${n} is not authorized for verb: ${ce} (E: 918fa8ab28c9b60e68994511a5825)`);let m=he({ibGib:t});if(!m)throw new Error("(UNEXPECTED) delegateTjpAddr falsy? (E: d4d6e8ad03c8925d4838b9a87b8f2826)");let $={target:m,verb:ce},w=h.delegates?{...h.delegates}:{},T=Wr({spaceIb:a.ib}).spaceId,A=d??(u?new Date(Date.now()+u*1e3).toISOString():void 0)??t.data?.frameDetails?.expirationUTC;return w[m]={delegateTjpAddr:m,delegateAddr:_({ibGib:t}),thisAddr:_({ibGib:e}),deviceName:l,allowedVerbs:c,spaceId:T,expirationUTC:A,role:t.data?.frameDetails?.role},await this.sign({latestKeystone:e,masterSecret:o,claim:$,poolId:n,frameDetails:s,metaspace:i,space:a,dataToPatch:{delegates:w}})}catch(p){throw console.error(`${b} ${E(p)}`),p}finally{q&&console.log(`${b} complete.`)}}async unregisterDelegate({parentKeystone:e,delegateTjpAddr:t,masterSecret:o,signingPoolId:n,frameDetails:s,metaspace:i,space:a}){let c=`${this.lc}[${this.unregisterDelegate.name}]`;try{if(q&&console.log(`${c} starting...`),!n)throw new Error("signingPoolId is required (E: b2c3d4e5f6a13889f8ab28c9b60e6899)");let l=e.data,d=l.challengePools.find(h=>h.id===n);if(!d)throw new Error(`Parent keystone does not contain signing pool: ${n} (E: 3889f8ab28c9b60e68994511a5825)`);if(d.config.allowedVerbs&&d.config.allowedVerbs.length>0&&!d.config.allowedVerbs.includes(ce))throw new Error(`Signing pool ${n} is not authorized for verb: ${ce} (E: 4889f8ab28c9b60e68994511a5825)`);let u={target:t,verb:ce},b=l.delegates?{...l.delegates}:{};if(!b[t])throw new Error(`Delegate ${t} is not registered on this parent. (E: 81d9f8ab28c9b60e68994511a5825)`);return delete b[t],await this.sign({latestKeystone:e,masterSecret:o,claim:u,poolId:n,frameDetails:s,metaspace:i,space:a,dataToPatch:{delegates:b}})}catch(l){throw console.error(`${c} ${E(l)}`),l}finally{q&&console.log(`${c} complete.`)}}async getDelegateStatus({parentTjpAddr:e,delegateTjpAddr:t,metaspace:o,space:n}){let s=`${this.lc}[${this.getDelegateStatus.name}]`;try{q&&console.log(`${s} starting...`);let{ib:i,gib:a}=R({ibGibAddr:e}),l=await _e({ibGibs:[{ib:i,gib:a}],space:n});if(!l.data?.latestAddrsMap)return{registered:!1};let d=l.data.latestAddrsMap[e];if(!d)return{registered:!1};let b=(await o.get({addr:d,space:n})).ibGibs?.at(0);if(!b||!b.data)return{registered:!1};let h=(b.data.delegates||{})[t];return{registered:!!h&&!Ua({delegateInfo:h}),delegateInfo:h}}catch(i){throw console.error(`${s} ${E(i)}`),i}finally{q&&console.log(`${s} complete.`)}}async validateGenesisKeystone({keystoneIbGib:e}){return await lo({keystoneIbGib:e})}async getLatestKeystone({addr:e,metaspace:t,space:o}){let n=`${this.lc}[${this.getLatestKeystone.name}]`;try{q&&console.log(`${n} starting...`);let s=await t.getLatestAddr({addr:e,space:o});if(!s)throw new Error(`could not find latest addr for ${e}`);let i=await t.get({addr:s,space:o});if(i.success&&i.ibGibs&&i.ibGibs.length>0)return i.ibGibs[0];{let c=i.rawResultIbGib?.data?.addrsNotFound??"unknown";throw new Error(`couldn't find latest keystone at ${s}. addrsNotFound: ${c}? resGet.errorMsg: ${i.errorMsg}`)}}catch(s){throw console.error(`${n} ${E(s)}`),s}finally{q&&console.log(`${n} complete.`)}}async validateKeystoneGraph({keystoneIbGib:e,dependencyGraph:t,getLatest:o,invalidIfMoreRecentKeystoneFoundInSpace:n,space:s}){let i=`${this.lc}[${this.validateKeystoneGraph.name}]`;try{return q&&console.log(`${i} starting... (I: 01c5cd455038c270cbf1effc1704af26)`),await fo({keystoneIbGib:e,dependencyGraph:t,getLatest:o,invalidIfMoreRecentKeystoneFoundInSpace:n,space:s})}catch(a){throw console.error(`${i} ${E(a)}`),a}finally{q&&console.log(`${i} complete.`)}}async revoke({latestKeystone:e,masterSecret:t,reason:o="User initiated revocation",frameDetails:n,metaspace:s,space:i}){let a=`${this.lc}[${this.revoke.name}]`;try{q&&console.log(`${a} starting...`);let c=e.data,l=mr({pools:c.challengePools,verb:jt}),d={verb:jt,target:_({ibGib:e})},u=await At({pool:l,targetAddr:d.target,requiredChallengeIds:[]});if(u.length===0)throw new Error(`Revocation policy selected 0 challenges? Check config for pool ${l.id}. Revocation requires proof. (E: 97e5a8356d241ae7b882db791cb1f825)`);let{proof:b,nextPools:p}=await St({targetPoolId:l.id,prevPools:c.challengePools,masterSecret:t,challengeIds:u,claim:d,requiredChallengeIds:[]});p.find(T=>T.id===l.id&&Object.keys(T.challenges).length>0)&&console.warn(`${a} revocation pool ${l.id} is not empty after revocation. Is the revocation pool replenish strategy set to ${Te.deleteAll}? (W: 300c28bc8b98fc3e3c0b0d988344f825)`);let h={reason:o,proof:b},g=(c.n??0)+1,m;if(g%_t===0){let T={...e,data:{...c,frameDetails:n,revocationInfo:h}};m=await this.getAggregateDetails({latestKeystone:T,metaspace:s,space:i})}let $={challengePools:p,proofs:[b],revocationInfo:h,frameDetails:n,checkpointDetails:m,...c.delegates?{delegates:c.delegates}:{}};return await lt({prevIbGib:e,newData:$,metaspace:s,space:i})}catch(c){throw console.error(`${a} ${E(c)}`),c}finally{q&&console.log(`${a} complete.`)}}async addPools({latestKeystone:e,masterSecret:t,signingPoolId:o,newPools:n,frameDetails:s,dataToPatch:i,metaspace:a,space:c}){let l=`${this.lc}[${this.addPools.name}]`;try{if(q&&console.log(`${l} starting...`),!e.data)throw new Error("(UNEXPECTED) latestKeystone.data falsy? (E: 7334c8faed128166a999d428c7805b25)");let d=e.data;if(d.revocationInfo)throw new Error("Keystone has been revoked. Cannot add pools. (E: 8599f8f51c78d722252ddb2894fdbe25)");if(n.length===0)throw new Error("No new pools provided to add. (E: 6599f8f51c78d722252ddb2894fdbe25)");let u=mr({pools:d.challengePools,poolId:o,verb:ce});q&&console.log(`${l} Authorized via pool: ${u.id}`);let b=_({ibGib:e}),p={verb:ce,target:b,details:{type:Bt.add_pool,info:{add:n.map(I=>I.id)}}},h=await At({pool:u,targetAddr:b}),{proof:g,nextPools:m}=await St({targetPoolId:u.id,prevPools:d.challengePools,masterSecret:t,challengeIds:h,claim:p}),$=new Set(m.map(I=>I.id));for(let I of n)if($.has(I.id))throw new Error(`Cannot add pool. ID collision: ${I.id} (E: genuuid)`);let w=[...m,...n],T=(d.n??0)+1,A;if(T%_t===0){let I={...e,data:{...d,challengePools:w,frameDetails:s}};A=await this.getAggregateDetails({latestKeystone:I,metaspace:a,space:c})}let G={challengePools:w,proofs:[g],frameDetails:s,checkpointDetails:A,...d.delegates?{delegates:d.delegates}:{},...i};return await lt({prevIbGib:e,newData:G,metaspace:a,space:c})}catch(d){throw console.error(`${l} ${E(d)}`),d}finally{q&&console.log(`${l} complete.`)}}async removePools({latestKeystone:e,masterSecret:t,signingPoolId:o,poolIds:n,frameDetails:s,dataToPatch:i,metaspace:a,space:c}){let l=`${this.lc}[${this.removePools.name}]`;try{if(q&&console.log(`${l} starting...`),!e.data)throw new Error("(UNEXPECTED) latestKeystone.data falsy? (E: 8334c8faed128166a999d428c7805b25)");let d=e.data;if(d.revocationInfo)throw new Error("Keystone has been revoked. Cannot remove pools. (E: 9599f8f51c78d722252ddb2894fdbe25)");if(n.length===0)throw new Error("No pool IDs provided to remove. (E: 7599f8f51c78d722252ddb2894fdbe25)");let u=mr({pools:d.challengePools,poolId:o,verb:ce});q&&console.log(`${l} Authorized via pool: ${u.id}`);let b=_({ibGib:e}),p={verb:ce,target:b,details:{type:Bt.remove_pool,info:{remove:n}}},h=await At({pool:u,targetAddr:b}),{proof:g,nextPools:m}=await St({targetPoolId:u.id,prevPools:d.challengePools,masterSecret:t,challengeIds:h,claim:p}),$=new Set(n),w=m.filter(I=>!$.has(I.id));if(w.length!==m.length-n.length){let I=n.filter(v=>!m.some(N=>N.id===v));throw new Error(`Cannot remove pool. Pool IDs not found in keystone: ${I.join(", ")} (E: genuuid)`)}let T=(d.n??0)+1,A;if(T%_t===0){let I={...e,data:{...d,challengePools:w,frameDetails:s}};A=await this.getAggregateDetails({latestKeystone:I,metaspace:a,space:c})}let G={challengePools:w,proofs:[g],frameDetails:s,checkpointDetails:A,...d.delegates?{delegates:d.delegates}:{},...i};return await lt({prevIbGib:e,newData:G,metaspace:a,space:c})}catch(d){throw console.error(`${l} ${E(d)}`),d}finally{q&&console.log(`${l} complete.`)}}async getAggregateDetails({latestKeystone:e,metaspace:t,space:o}){let n=`${this.lc}[${this.getAggregateDetails.name}]`;try{let s={},i=e;for(;i;){let a=i.data;if(a.checkpointDetails){s=Pt({dominant:s,recessive:a.checkpointDetails});break}if(a.frameDetails&&(s=Pt({dominant:s,recessive:a.frameDetails})),a.n===0)break;let c=i.rel8ns?.past,l=c&&c.length>0?c[c.length-1]:void 0;if(!l)break;let d=await t.get({addr:l,space:o});if(!d.success||!d.ibGibs||d.ibGibs.length===0){console.warn(`${n} Could not find previous keystone frame at ${l} (W: e3d069b22e11e550e58844889ddb5325). Returning aggregated details collected so far.`);break}i=d.ibGibs[0]}return this.pruneTombstoneNulls(s),s}catch(s){throw console.error(`${n} ${E(s)}`),s}}async getKeystoneCommonInfo({addr:e,ibGib:t,metaspace:o,space:n}){let s=`${this.lc}[getKeystoneCommonInfo]`;try{let i=e,a=t;if(!i){if(!a)throw new Error("Both addr and ibGib are falsy. Expected at least one parameter to resolve keystone info. (E: 3a2890b1c28f7449c5d8693a7d4a2828)");i=_({ibGib:a})}if(!a){let{ib:A,gib:G}=R({ibGibAddr:i});a={ib:A,gib:G}}let c=await _e({ibGibs:[a],space:n});if(!c.data?.latestAddrsMap)throw new Error(`Could not get latest address map for keystone ${i} in local space. (E: 4a2890b1c28f7449c5d8693a7d4a2829)`);let l=c.data.latestAddrsMap[i]||Object.values(c.data.latestAddrsMap)[0];if(!l)throw new Error(`No latest address found in map for keystone ${i} in local space. (E: 5a2890b1c28f7449c5d8693a7d4a2830)`);let u=(await o.get({addr:l,space:n})).ibGibs?.at(0);if(!u||!u.data)throw new Error(`Keystone ${l} not found or missing data in local space. (E: 6a2890b1c28f7449c5d8693a7d4a2831)`);let b=u.data.frameDetails||{},p=await this.getAggregateDetails({latestKeystone:u,metaspace:o,space:n}),h=p?.username||p?.name||p?.profile?.name||b?.username||b?.name||"",g=p?.description||p?.profile?.description||b?.description||"",m=!!p?.isPrimary||!!p?.profile?.isPrimary||!!b?.isPrimary,$=u.data.n??0,w=b?.timestamp||p?.timestamp||"",T=b?.timestampMs||p?.timestampMs||void 0;return{name:h,description:g,isPrimary:m,aggregateDetails:p,latestFrameDetails:b,n:$,timestamp:w,timestampMs:T}}catch(i){throw console.error(`${s} ${E(i)}`),i}}async replacePool({latestKeystone:e,newPool:t,signingSecret:o,signingPoolId:n=fr,frameDetails:s,metaspace:i,space:a}){let c=`${this.lc}[${this.replacePool.name}]`;try{if(q&&console.log(`${c} starting... replacing pool: ${t.id}`),!e.data)throw new Error("(UNEXPECTED) latestKeystone.data falsy? (E: 1334c8faed128166a999d428c7805b25)");let l=e.data;if(l.revocationInfo)throw new Error("Keystone has been revoked. Cannot replace pool. (E: 2599f8f51c78d722252ddb2894fdbe25)");let d=l.challengePools,u=d.find(y=>y.id===n);if(!u)throw new Error(`Signing pool not found: ${n} (E: 3599f8f51c78d722252ddb2894fdbe25)`);let b=_({ibGib:e}),p={verb:ce,target:b,details:{type:Bt.replace_pool,info:{replace:t.id}}},h=await At({pool:u,targetAddr:b}),{proof:g,nextPools:m}=await St({targetPoolId:n,prevPools:d,masterSecret:o,challengeIds:h,claim:p}),$=m.findIndex(y=>y.id===t.id);if($===-1)throw new Error(`Target pool to replace '${t.id}' not found in keystone challenge pools.`);m[$]=t;let w=(l.n??0)+1,T;if(w%_t===0){let y={...e,data:{...l,frameDetails:s}};T=await this.getAggregateDetails({latestKeystone:y,metaspace:i,space:a})}let A={challengePools:m,proofs:[g],frameDetails:s,checkpointDetails:T,...l.delegates?{delegates:l.delegates}:{}};return await lt({prevIbGib:e,newData:A,metaspace:i,space:a})}catch(l){throw console.error(`${c} ${E(l)}`),l}finally{q&&console.log(`${c} complete.`)}}async changePassword({keystoneIbGib:e,keystoneAddr:t,newMasterSecret:o,signingSecret:n,signingPoolId:s=fr,poolIds:i,frameDetails:a,metaspace:c,space:l}){let d=`${this.lc}[${this.changePassword.name}]`;try{if(q&&console.log(`${d} starting... (I: 9e3ff83ebd74511f9dad784a1020d926)`),!e&&!t)throw new Error("Either keystoneIbGib or keystoneAddr required. (E: d1b8c8cb75f2c022284e69b8c30af826)");if(e&&t){let x=_({ibGib:e});if(x!==t)throw new Error(`(UNEXPECTED) both keystoneIbGib (addr: ${x}) and keystoneAddr (${t}) provided, but the addrs are unequal? Note that only one is required for this function, but if both are provided the addrs must match exactly. (E: c5574f7e353a48b0bba94a1862af4e26)`)}t??=_({ibGib:e});let u=await this.getLatestKeystone({addr:t,metaspace:c,space:l});if(!u.data)throw new Error("latestKeystone.data falsy (E: 22e498eb8308a33e68b812d8d3905826)");if(u.data.revocationInfo)throw new Error("Keystone has been revoked. Cannot change password. (E: 726298617e8508b3c83b5e985a03e826)");let b=u.data.challengePools,p=b.find(x=>x.id===s);if(!p)throw new Error(`Signing pool not found: ${s} (E: 3599f8f51c78d722252ddb2894fdbe25)`);let h=[];if(i&&i.length>0)for(let x of i){let P=b.find(D=>D.id===x);if(!P)throw new Error(`Target pool to rotate not found: ${x} (E: 4599f8f51c78d722252ddb2894fdbe25)`);h.push(P)}else if(h=b.filter(x=>!x.isForeign),h.length===0)throw new Error("No non-foreign pools found to rotate. (E: 5599f8f51c78d722252ddb2894fdbe25)");let g=[];for(let x of h){let P=await Ra({prevPool:x,newMasterSecret:o});g.push(P)}let m=_({ibGib:u}),$={verb:ce,target:m,details:{type:Bt.change_password,info:{change:g.map(x=>x.id)}}},w=await At({pool:p,targetAddr:m}),{proof:T,nextPools:A}=await St({targetPoolId:s,prevPools:b,masterSecret:n,challengeIds:w,claim:$});for(let x of g){let P=A.findIndex(D=>D.id===x.id);if(P===-1)throw new Error(`Rotated pool ${x.id} not found in next pools list. (E: 6599f8f51c78d722252ddb2894fdbe25)`);A[P]=x}let G=(u.data.n??0)+1,y;if(G%_t===0){let x={...u,data:{...u.data,challengePools:A}};y=await this.getAggregateDetails({latestKeystone:x,metaspace:c,space:l})}let I={challengePools:A,proofs:[T],frameDetails:a,checkpointDetails:y,...u.data.delegates?{delegates:u.data.delegates}:void 0},v=await lt({prevIbGib:u,newData:I,metaspace:c,space:l}),N=[];if((i??[]).length===0){let x=await ct({masterSecret:n}),P=await ct({masterSecret:o}),D=u.data.delegates??{};for(let[L,K]of Object.entries(D)){if(ka({delegateInfo:K})){q&&console.log(`${d} Skipping custodial delegate rotation for ${L} (${K.deviceName})`);continue}try{let{newKeystone:J,newDelegates:Je}=await this.changePassword({keystoneAddr:L,metaspace:c,space:l,newMasterSecret:P,signingSecret:x,signingPoolId:s,poolIds:void 0,frameDetails:a});if(Je&&Je.length>0)throw new Error("(UNEXPECTED) Delegate keystone has its own delegate(s)? ATOW (07/20/2026) second order delegates are not supported. (E: de45a7b7d9b8f61f6e58158269acba26)");N.push(J)}catch(J){console.warn(`${d} Error rotating user delegate ${L}: ${E(J)}. Continuing.`)}}}return{newKeystone:v,newDelegates:N.length>0?N:void 0}}catch(u){throw console.error(`${d} ${E(u)}`),u}finally{q&&console.log(`${d} complete.`)}}async verifySigningSecret({keystoneIbGib:e,signingSecret:t,poolId:o,verb:n=ce}){let s=`${this.lc}[${this.verifySigningSecret.name}]`;try{if(!e.data)return!1;let i=e.data.challengePools;if(o){let c=i.find(l=>l.id===o);return c?await uo({pool:c,signingSecret:t}):!1}let a=i.filter(c=>c.id==="manage"||c.id.startsWith("passkey-manage-")||c.config.allowedVerbs&&n&&c.config.allowedVerbs.includes(n));for(let c of a)if(await uo({pool:c,signingSecret:t}))return!0;return!1}catch(i){return console.warn(`${s} Exception during verification: ${E(i)}`),!1}}pruneTombstoneNulls(e){if(e==null||typeof e!="object")return e;if(Array.isArray(e))return e.filter(t=>t!==null).map(t=>this.pruneTombstoneNulls(t));for(let t of Object.keys(e))e[t]===null?delete e[t]:e[t]!==null&&typeof e[t]=="object"&&this.pruneTombstoneNulls(e[t]);return e}};var Ma="sync-delegate",Ba="custodial-sync";var ho="custodian-manage-";var ja=!1;async function ct({masterSecret:r}){let e=await X({s:r,algorithm:we.sha_512});return await Mt({masterSecret:r,salt:e,rounds:1e3,algorithm:we.sha_512})}f(ct,"deriveDelegateSecret");async function Fa({primaryTjpAddr:r,deviceTag:e}){if(!r)throw new Error("primaryTjpAddr is required to derive device delegate secret (E: genuuid)");let t=await F(32),o=`${r}_${e||""}_${t}`;return await X({s:o,algorithm:we.sha_512})}f(Fa,"deriveDeviceDelegateSecret");async function Gt({profileName:r,profileTemplate:e,username:t,deviceTag:o,primaryTjpAddr:n,delegateSecret:s,custodianReqs:i,expirationUTC:a,additionalFrameDetails:c,metaspace:l,space:d}){let u=`[${Gt.name}]`;try{if(!r&&!e)throw new Error("profileName or profileTemplate is required (E: genuuid)");if(!n)throw new Error("primaryTjpAddr is required (E: genuuid)");if(!s)throw new Error("delegateSecret is required (E: genuuid)");let b=o||"primary-device",p=e?ur.fromTemplate(e):ur.buildKeystone(r),h=pe({text:b,keepLiterals:["-"]})||"device",g=pe({text:t,keepLiterals:["-"]})||"user";p.withUsername(`${g}-sync-${h}`.slice(0,60)).withDescription(`Sync Delegate for ${t} on ${b}`).withDetails({client:"space-gib-web",role:Ma,deviceTag:b,primaryTjpAddr:n,...i?{custodianReqs:i}:{},...c||{}}),a&&p.withExpiration(a);let m=await p.compileConfigs(),$=p.getFrameDetails();return await new po().genesis({masterSecret:s,configs:m,metaspace:l,space:d,frameDetails:$,isPrimary:!1})}catch(b){throw console.error(`${u} ${E(b)}`),b}}f(Gt,"createSyncDelegateKeystone");function Wn({keystone:r,nowUTC:e}){if(!r||!r.data?.frameDetails?.expirationUTC)return!1;let t=Date.parse(r.data.frameDetails.expirationUTC);return isNaN(t)?!1:(e!==void 0?typeof e=="number"?e:e instanceof Date?e.getTime():Date.parse(e):Date.now())>t}f(Wn,"isKeystoneExpired");function Ua({delegateInfo:r,delegateKeystone:e,nowUTC:t}){if(!r&&!e)throw new Error("either delegateInfo or delegateKeystone required. (E: d1baa55ca8d23b26f8562a28179d2126)");if(e)return Wn({keystone:e,nowUTC:t});if(!r||!r.expirationUTC)return!1;let o=Date.parse(r.expirationUTC);return isNaN(o)?!1:(t!==void 0?typeof t=="number"?t:t instanceof Date?t.getTime():Date.parse(t):Date.now())>o}f(Ua,"isDelegateExpired");function dd({keystone:r,aggregatedDetails:e,providerId:t}){let o=`[${dd.name}]`;try{ja&&console.log(`${o} starting... (I: 1db5581127983918ff303dd8370daf26)`);let n=`${ho}${t}`;if(r.data?.challengePools?.some(i=>i.id===n))return!0;if(!(r.data?.frameDetails?.custodyMode==="hybrid"||e?.custodyMode==="hybrid"||r.data?.custodyMode==="hybrid")){let i=e?.custodianProvider||r.data?.frameDetails?.custodianProvider||r.data?.custodianProvider;if(i&&String(i).toLowerCase()===String(t).toLowerCase())return!0}return!1}catch(n){throw console.error(`${o} ${E(n)}`),n}finally{ja&&console.log(`${o} complete.`)}}f(dd,"isSsoProviderLinked");function ka({delegateInfo:r,delegateKeystone:e,providerId:t}){if(!r&&!e)return!1;let o=r?.role||e?.data?.frameDetails?.role,n=r?.deviceName||e?.data?.frameDetails?.deviceTag,s=r?.metadata?.provider||e?.data?.frameDetails?.custodianProvider||e?.data?.frameDetails?.metadata?.provider,i=o===Ba||o==="custodial-sync";if(s)return t?String(s).toLowerCase()===String(t).toLowerCase():!0;if(n){let a=n.toLowerCase();if(t){let c=String(t).toLowerCase();return a.includes(c)||i&&a.includes("custodian")}if(a.includes("custodian")||a.includes("oauth2")||a.includes("google")||a.includes("github")||a.startsWith("email-")||a.includes("@"))return!0}return!!(!t&&i)}f(ka,"isCustodialDelegate");function AE({keystone:r,aggregatedDetails:e}){if(!r)return{isSovereign:!1,isCustodial:!1,isHybrid:!1,providers:[],emails:[]};let t=e?.emails||r.data?.frameDetails?.emails||[],o=r.data?.challengePools||[],n=e?.custodianProvider||r.data?.frameDetails?.custodianProvider||r.data?.custodianProvider,i=!(r.data?.frameDetails?.custodyMode==="hybrid"||e?.custodyMode==="hybrid"||r.data?.custodyMode==="hybrid")&&(!!n||r.data?.frameDetails?.custodyMode==="full"||e?.custodyMode==="full"||r.data?.custodyMode==="full"),a=new Set;for(let w of o)if(w.id.startsWith(ho)){let T=w.id.substring(ho.length);T&&a.add(T)}i&&n&&a.add(n);let c=Array.from(a),l=c.length>0||i,d=o.some(w=>w.id==="manage"),b=o.filter(w=>w.id.startsWith("passkey-manage-")).length||(r.data?.credentialIds?r.data.credentialIds.length:0),p=b>0,h=d&&!i,g=(d||p)&&!i,m=l;return{isSovereign:g,isCustodial:m,isHybrid:g&&m,providers:c,emails:t,hasPasskeys:p,passkeyCount:b,hasPassword:h}}f(AE,"getKeystoneCapabilities");function Ft(r){let e=(r?.userAgent??(typeof navigator<"u"?navigator.userAgent:"")??"").toLowerCase(),t=r?.userAgentData??(typeof navigator<"u"?navigator.userAgentData:void 0),o=r?.maxTouchPoints??(typeof navigator<"u"?navigator.maxTouchPoints:0)??0,n=r?.screenWidth??(typeof window<"u"?window.innerWidth:1024)??1024,s="",i=t?.mobile,a=/mobile|iphone|ipod|android.*mobile|windows phone/i.test(e);/ipad|tablet|(android(?!.*mobile))/i.test(e)||o>1&&/macintosh/i.test(e)&&n<=1366?s="tablet":(i||a)&&(s="mobile");let l="",d=(t?.platform||"").toLowerCase();d.includes("win")||e.includes("windows")?l="win":d.includes("ios")||e.includes("iphone")||e.includes("ipad")||e.includes("ipod")?l="ios":d.includes("mac")||e.includes("macintosh")||e.includes("mac os")?l="mac":d.includes("android")||e.includes("android")?l="android":(d.includes("linux")||e.includes("linux"))&&(l="linux");let u="";e.includes("edg/")||e.includes("edge/")?u="edge":e.includes("chrome/")||e.includes("crios/")?u="chrome":e.includes("firefox/")||e.includes("fxios/")?u="firefox":e.includes("safari/")&&!e.includes("chrome/")&&!e.includes("crios/")&&(u="safari");let b=r?.randomSuffix;if(!b){let h="0123456789abcdef";b="";for(let g=0;g<4;g++)b+=h.charAt(Math.floor(Math.random()*h.length))}b=b.toLowerCase().replace(/[^a-z0-9]/g,"").slice(0,8);let p=[];return s&&p.push(s),u&&p.push(u),l&&p.push(l),p.length===0&&p.push("device"),p.push(b),p.join("-")}f(Ft,"generateDefaultDeviceTag");var fd="ibgib_device_delegate_secret_";function qa({primaryTjpAddr:r}){if(!r)throw new Error("primaryTjpAddr is required to get device delegate secret key (E: genuuid)");return`${fd}${r}`}f(qa,"getDeviceDelegateSecretKey");async function Ha({primaryTjpAddr:r}){let e=`[${Ha.name}]`;try{if(!r)throw new Error("primaryTjpAddr is required to get device delegate secret (E: genuuid)");let t=mo(),o=go(),n=qa({primaryTjpAddr:r});return await kt({dbName:t,storeName:o,key:n})}catch(t){throw console.error(`${e} ${E(t)}`),t}}f(Ha,"getDeviceDelegateSecret");async function wr({primaryTjpAddr:r,delegateSecret:e}){let t=`[${wr.name}]`;try{if(!r)throw new Error("primaryTjpAddr is required to set device delegate secret (E: genuuid)");if(!e)throw new Error("delegateSecret is required to set device delegate secret (E: genuuid)");let o=mo(),n=go(),s=qa({primaryTjpAddr:r});await lr({dbName:o,storeName:n,key:s,value:e})}catch(o){throw console.error(`${t} ${E(o)}`),o}}f(wr,"setDeviceDelegateSecret");async function zn({primaryTjpAddr:r,deviceTag:e}){let t=`[${zn.name}]`;try{if(!r)throw new Error("primaryTjpAddr is required to get or create device delegate secret (E: genuuid)");let o=await Ha({primaryTjpAddr:r});if(o)return o;let n=await Fa({primaryTjpAddr:r,deviceTag:e});return await wr({primaryTjpAddr:r,delegateSecret:n}),n}catch(o){throw console.error(`${t} ${E(o)}`),o}}f(zn,"getOrCreateDeviceDelegateSecret");async function LE({username:r,primaryTjpAddr:e,masterSecret:t,metaspace:o,space:n}){let s=await ct({masterSecret:t});await wr({primaryTjpAddr:e,delegateSecret:s});let i=pe({text:r,length:8,keepLiterals:["-"]})||"user",a=Ft(),c=`pwd-${i}-${a}`,l="sync-profile.dev";if(!l||!l.trim())throw new Error("KEYSTONE_PROFILE_SOVEREIGN_SYNC environment variable is missing.");return{delegateKeystone:await Gt({profileName:l.trim(),username:r,deviceTag:c,primaryTjpAddr:e,delegateSecret:s,additionalFrameDetails:{client:"space-gib-web"},metaspace:o,space:n}),deviceTag:c,delegateSecret:s}}f(LE,"createSovereignDeviceSyncDelegate");async function RE({providerId:r,username:e="user",primaryTjpAddr:t,custodianReqs:o,metaspace:n,space:s}){let i=await zn({primaryTjpAddr:t}),a=Ft(),c=`oauth2-${r}-${a}`,l="sync-profile.dev";if(!l||!l.trim())throw new Error("KEYSTONE_PROFILE_CUSTODIAN_SYNC environment variable is missing.");return{delegateKeystone:await Gt({profileName:l.trim(),username:e,deviceTag:c,primaryTjpAddr:t,delegateSecret:i,custodianReqs:o,additionalFrameDetails:{client:"space-gib-web"},metaspace:n,space:s}),deviceTag:c,delegateSecret:i}}f(RE,"createOAuth2DeviceSyncDelegate");async function UE({email:r,primaryTjpAddr:e,custodianReqs:t,metaspace:o,space:n}){let s=await zn({primaryTjpAddr:e}),i=Ft(),[a="",c=""]=(r||"").split("@"),l=pe({text:a,length:8,keepLiterals:["-"]})||"user",d=c.split(".")[0]||"",u=d?pe({text:d,length:8,keepLiterals:["-"]}):"",p=`email-${u?`${l}@${u}`:l}-${i}`,h=l,g="sync-profile.dev";if(!g||!g.trim())throw new Error("KEYSTONE_PROFILE_CUSTODIAN_SYNC environment variable is missing.");return{delegateKeystone:await Gt({profileName:g.trim(),username:h,deviceTag:p,primaryTjpAddr:e,delegateSecret:s,custodianReqs:t,additionalFrameDetails:{client:"space-gib-web"},metaspace:o,space:n}),deviceTag:p,delegateSecret:s}}f(UE,"createEmailDeviceSyncDelegate");async function Jn(){try{if(typeof window>"u"||!window.PublicKeyCredential)return!1;if(typeof window.PublicKeyCredential.getClientCapabilities=="function"){let r=await window.PublicKeyCredential.getClientCapabilities();if(r&&r.prf)return!0}return typeof PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable=="function"?await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable():!1}catch{return!1}}f(Jn,"isPasskeyPrfSupported");function Eo(r){return Array.from(new Uint8Array(r)).map(e=>e.toString(16).padStart(2,"0")).join("")}f(Eo,"bufferToHex");function Ka(r){let e=r.replace(/[^0-9a-fA-F]/g,""),t=new Uint8Array(Math.floor(e.length/2));for(let o=0;o<t.length;o++)t[o]=parseInt(e.substr(o*2,2),16);return t}f(Ka,"hexToUint8Array");function Va(r){if(r instanceof Uint8Array){if(r.length===32)return r;let o=new Uint8Array(32);return o.set(r.subarray(0,32)),o}if(/^[0-9a-fA-F]{64}$/.test(r))return Ka(r);let e=new TextEncoder().encode(r),t=new Uint8Array(32);return t.set(e.subarray(0,32)),t}f(Va,"normalizeSaltTo32Bytes");async function HE({username:r,displayName:e=r,rpName:t="ibgib",rpId:o,salt:n,userVerification:s="preferred",authenticatorAttachment:i,hints:a=["security-key","client-device","hybrid"]}){let c="[registerPasskeyCredential]";try{if(typeof window>"u"||!navigator.credentials?.create)throw new Error("WebAuthn is not supported in this browser environment.");let l=o||(typeof window<"u"?window.location.hostname:void 0),d=crypto.getRandomValues(new Uint8Array(32)),u=new TextEncoder().encode(r.slice(0,64)),b=n?Va(n):void 0,p=b?{eval:{first:b}}:{},h=await navigator.credentials.create({publicKey:{challenge:d,rp:{name:t,...l?{id:l}:{}},user:{id:u,name:r,displayName:e},pubKeyCredParams:[{alg:-7,type:"public-key"},{alg:-257,type:"public-key"},{alg:-8,type:"public-key"}],authenticatorSelection:{residentKey:"required",userVerification:s,...i?{authenticatorAttachment:i}:{}},...a&&a.length>0?{hints:a}:{},extensions:{prf:p}}});if(!h)throw new Error("Passkey creation was cancelled or failed.");let g=Eo(h.rawId),m=h.response,$=typeof m.getTransports=="function"?m.getTransports():[],w=h.getClientExtensionResults?.()||{};console.log(`${c} WebAuthn registration clientExtensionResults:`,w);let T;return w.prf?.results?.first&&(T=Eo(w.prf.results.first),console.log(`${c} Evaluated PRF directly during create!`)),{credentialId:g,rawId:h.rawId,transports:$,passkeySecret:T}}catch(l){throw console.error(`${c} ${E(l)}`),l}}f(HE,"registerPasskeyCredential");async function Zn({salt:r,credentialId:e,transports:t,rpId:o,userVerification:n="preferred",hints:s=["security-key","client-device","hybrid"]}){let i="[evaluatePasskeyPrf]";try{if(typeof window>"u"||!navigator.credentials?.get)throw new Error("WebAuthn is not supported in this browser environment.");let a=o||(typeof window<"u"?window.location.hostname:void 0),c=crypto.getRandomValues(new Uint8Array(32)),l=Va(r),d,u;if(e){let w=Ka(e);u=[{id:w.buffer,type:"public-key",...t&&t.length>0?{transports:t}:{}}];let T="";for(let A=0;A<w.byteLength;A++)T+=String.fromCharCode(w[A]);d=btoa(T).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}let b={eval:{first:l}};d&&(b.evalByCredential={[d]:{first:l}});let p=await navigator.credentials.get({publicKey:{challenge:c,...a?{rpId:a}:{},allowCredentials:u,userVerification:n,...s&&s.length>0?{hints:s}:{},extensions:{prf:b}}});if(!p)throw new Error("Passkey authentication was cancelled or failed.");let h=Eo(p.rawId),g=p.getClientExtensionResults?.()||{};console.log(`${i} WebAuthn assertion clientExtensionResults:`,JSON.stringify(g),g);let m=g.prf?.results?.first;if(!m&&d&&g.prf?.resultsByCredential?.[d]?.first&&(m=g.prf.resultsByCredential[d].first,console.log(`${i} Extracted PRF result from resultsByCredential!`)),!m)throw console.error(`${i} Extension results did not contain PRF evaluation:`,JSON.stringify(g),g),new Error("Authenticator did not return a PRF evaluation. PRF extension may not be supported on this authenticator.");return{passkeySecret:Eo(m),credentialId:h}}catch(a){throw console.error(`${i} ${E(a)}`),a}}f(Zn,"evaluatePasskeyPrf");async function KE({username:r,primaryTjpAddr:e,passkeySecret:t,transports:o,metaspace:n,space:s}){let i=await ct({masterSecret:t});await wr({primaryTjpAddr:e,delegateSecret:i});let a=pe({text:r,length:8,keepLiterals:["-"]})||"user",c=Ft(),l=`passkey-${a}-${c}`,d="sync-profile.dev";if(!d||!d.trim())throw new Error("KEYSTONE_PROFILE_SOVEREIGN_SYNC environment variable is missing.");return{delegateKeystone:await Gt({profileName:d.trim(),username:r,deviceTag:l,primaryTjpAddr:e,delegateSecret:i,additionalFrameDetails:{client:"space-gib-web",role:"passkey-sync",...o&&o.length>0?{transports:o}:{}},metaspace:n,space:s}),deviceTag:l,delegateSecret:i}}f(KE,"createPasskeyDeviceSyncDelegate");var be=at;function Ya(r){return new TextDecoder().decode(r)}f(Ya,"uint8ArrayToString");var Xa=class r{static{f(this,"PathUtilsHelper")}lc=`[${r.name}]`;constructor(){}isAbsolute(e){if(!e)throw new Error("(UNEXPECTED) path falsy? (E: dcb92e11770ba06205c0afe3e6560b24)");return e.startsWith("/")}isRelative(e){return!this.isAbsolute(e)}join(...e){let t=`${this.lc}[${this.join.name}]`;if(e.length===0)return console.log(`${t} paths.length === 0. returning '.' per node convention. (I: 153da80765ff6160675fae895ebac225)`),".";if(e.length===1&&e[0]==="..")return console.log(`${t} paths.length === 1 && paths[0] === '..'. returning '..' per node convention. (I: 9af242b7615430a8c6899b1a332e9925)`),"..";let o="";for(let n=0;n<e.length;n++){let s=e[n];s===".."?o=o.split("/").slice(0,-1).join("/"):(s.startsWith("/")&&(s=s.slice(1)),s.endsWith("/")&&(s=s.slice(0,-1)),o+=(n>0?"/":"")+s)}return o}dirname(e){return e.split("/").slice(0,-1).join("/")}basename(e,t){return e.split("/").pop()??""}};async function bd({msg:r,title:e,confirm:t,noNewLine:o,rl:n,defaultValue:s,dontCloseRl:i,cancelable:a}){let c=`[${bd.name}]`;try{if(!r)throw new Error("msg required (E: 7f4d67bca4cf98ea95fa110aabc98924)");let l,d=0,u=5;do{if(d++,d>=u)throw new Error("max attempts reached (E: 1ef20ae955622d4b39479f3da91a1d25)");await de(50),l=await yt({title:e||"Prompt for Info",msg:r,prompt:!0,showInput:!0,isPassword:!1,defaultValue:s})}while(l===void 0&&!a);return l??""}catch(l){debugger;throw console.error(`${c} ${E(l)}`),l}}f(bd,"promptForText");async function ud({msg:r,confirm:e,passkeys:t}){let o=`[${ud.name}]`;try{be&&console.log(`${o} starting... (I: 795a4ce348ddb9a5119770f4c572ac24)`);let n,s=!0,i=0,a=5,l=await Jn().catch(()=>!1)&&t&&Object.keys(t).length>0?async d=>{if(!d)return;let{passkeySecret:u}=await Zn({credentialId:d.credentialId,salt:d.salt,transports:d.transports,userVerification:"preferred"});return u}:void 0;do{if(i++,i>=a)throw new Error("max attempts reached (E: d4166b4bf37aff0c6d44567792e9ad25)");if(await de(50),n=await yt({title:s?"Shh...":"Secrets didn't match, try again...",msg:r||"Enter Your Secret...",prompt:!0,showInput:!0,isPassword:!0,defaultValue:void 0,passkeys:t,onPasskeyAuth:l}),n===void 0)throw new Error("user cancelled (E: 91519d04378e84106f3df8eb36d99725)");if(typeof n=="object"&&n?.secret!==void 0&&(n=n.secret),e){await de(250);let d=await yt({title:"Shh...",msg:"Confirm...",prompt:!0,showInput:!0,isPassword:!0,defaultValue:void 0});d===void 0&&(n=void 0),typeof d=="object"&&d?.secret!==void 0&&(d=d.secret),n!==d&&(n=void 0,s=!1,await de(250))}}while(n===void 0);return n}catch(n){throw console.error(`${o} ${E(n)}`),n}finally{be&&console.log(`${o} complete.`)}}f(ud,"promptForSecret");async function pd({keystone:r,aggregatedDetails:e,title:t,msg:o,verb:n="manage"}){let s=`[${pd.name}]`;try{let i=e?.passkeys||r.data?.frameDetails?.passkeys||r.data?.passkeys||{},c=await Jn().catch(()=>!1)&&i&&Object.keys(i).length>0?async b=>{if(!b)return;let{passkeySecret:p}=await Zn({credentialId:b.credentialId,salt:b.salt,transports:b.transports,userVerification:"preferred"});return p}:void 0,d=(r.data?.challengePools||[]).filter(b=>b.id==="manage"||b.id.startsWith("passkey-manage-")||b.config?.allowedVerbs&&n&&b.config.allowedVerbs.includes(n)).some(b=>b.id==="manage"),u=await yt({title:t||"Authorize Action",msg:o||"Authorize this action with your master password or passkey:",prompt:!0,showInput:d,isPassword:!0,defaultValue:void 0,passkeys:i,onPasskeyAuth:c});if(!u)throw new Error("Action cancelled by user.");return typeof u=="object"&&u.secret!==void 0?{secret:u.secret,poolId:u.poolId||"manage"}:{secret:String(u),poolId:"manage"}}catch(i){throw console.error(`${s} ${E(i)}`),i}}f(pd,"promptForAuthoritySecret");async function hd({msg:r,title:e,skipHitEnterToContinue:t}){let o=`[${hd.name}]`;try{if(!r)throw new Error("msg required (E: ffcf7dd00324df7cea2792223d229524)");try{e??="",await de(50),await yt({title:e,msg:r})}catch(n){throw n}}catch(n){throw console.error(`${o} ${E(n)}`),n}}f(hd,"alertUser");async function gd({exportIbGibJsonString:r,metaspace:e}){let t=`[${gd.name}]`;try{debugger;if(be&&console.log(`${t} starting... (I: genuuid)`),!e)throw new Error("(UNEXPECTED) metaspace falsy? (E: genuuid)");if(!await e.getLocalUserSpace({lock:!1}))throw new Error("(UNEXPECTED) couldn't get default local user space? (E: genuuid)");let n,s;try{n=JSON.parse(r)}catch(l){let d=`Error during parse JSON. error: ${E(l)} (E: genuuid)`,u=new Error(d);throw u.cause=l,u}try{let l=await se({ibGib:n})??[];if(l.length>0)throw new Error(`validation errors when validating the parsed ibgib that should be a RawExportIbGib_V1: ${l} (E: 8ba178d3b26e8eca28a67c182fe16825)`);if(s=n,!s.data)throw new Error("(UNEXPECTED) rawExportIbGib.data falsy? (E: ef1824d1cca5584ab8e34288346e9825)")}catch(l){let d=`Error during parse JSON. error: ${E(l)} (E: genuuid)`,u=new Error(d);throw u.cause=l,u}let i;if(s.data.compression)switch(s.data.compression){case"gzip":i=await Pn({compressedBase64:s.data.dependencyGraphAsString});break;default:throw new Error(`unknown value of rawExportIbGib.data.compression: ${s.data.compression} (E: 784672fae568312d887ddbb841199925)`)}else i=await eo({jsonString:s.data.dependencyGraphAsString});let a={};for(let[l,d]of Object.entries(i)){let u=await se({ibGib:d})??[];u.length>0&&(a[l]=u)}if(Object.keys(a).length>0)throw new Error(`there were validation errors for the RawExportIbGib_V1.data payload (contained in data.dependencyGraphAsString). Here is the validationErrorMap:
22
+ ${H({validationErrorMap:a})} (E: e63f38b182a84122d83a55befb369825)`);return[s,i]}catch(o){throw console.error(`${t} ${E(o)}`),o}finally{be&&console.log(`${t} complete.`)}}f(gd,"getRawExportIbGibAndGraphFromJsonString");async function md({ibGib:r,compress:e,metaspace:t,space:o}){let n=`[${md.name}]`;try{if(be&&console.log(`${n} starting... (I: 623d9463d919683be81f749821a95825)`),te({ibGib:r}))throw new Error("ibGib is primitive. Can't export primitive. (E: dd42c42e9fda0707e81c692af1a2a225)");let s=await Ln({ibGib:r,live:!0,compress:e,metaspace:t,space:o}),{rawExportIbGib:i,errors:a}=s;if((a??[]).length>0)throw new Error(`Export had errors: ${a} (E: 05faf83f25d3449ab809dfd24eeaf825)`);let c=JSON.stringify(i),l="data:text/json;charset=utf-8,"+encodeURIComponent(c),u=`${_({ibGib:i})}.json`,b=document.createElement("a");b.setAttribute("style","none"),b.setAttribute("href",l),b.setAttribute("download",u);let p=document.getElementsByTagName("div")[0];p.appendChild(b),b.click(),p.removeChild(b)}catch(s){throw console.error(`${n} ${E(s)}`),s}finally{be&&console.log(`${n} complete.`)}}f(md,"exportIbGib");function Wa({id:r,shadowRoot:e}){let t=`[${Wa.name}]`;try{be&&console.log(`${t} starting... (I: 18a338c6dab8690c72b8759b8d952925)`);let o=e?e.getElementById(r):document.getElementById(r);if(o)return o;throw new Error(`${e?"shadowRoot":"document"}.getElementById(${r}) returned null. So...Element was not found. (E: 5e501f6835cc74cd4c2faf0d9e387825)`)}catch(o){throw console.error(`${t} ${E(o)}`),o}finally{be&&console.log(`${t} complete.`)}}f(Wa,"getElementById_throwsIfFalsy");function aw(r,e){return Wa({id:e,shadowRoot:r})}f(aw,"shadowRoot_getElementById");function go(){let r=`[${go.name}]`;try{be&&console.log(`${r} starting... (I: 62a29f9982b4b5ecd91ff58ca4dd6825)`);let e=It();if(!e.storeName_hack)throw new Error("(UNEXPECTED) global store name falsy? (E: 3b9b680f6a980debbb877c9a13fb2625)");return e.storeName_hack}catch(e){throw console.error(`${r} ${E(e)}`),e}finally{be&&console.log(`${r} complete.`)}}f(go,"getGlobalStoreName");function mo(){let r=`[${mo.name}]`;try{be&&console.log(`${r} starting... (I: 8c8f08728fc7384f87697377358cc825)`);let e=It();if(!e.dbName_hack)throw new Error("(UNEXPECTED) global db name falsy? (E: 3aa028d5e4088f3f3841aae94ac02825)");return e.dbName_hack}catch(e){throw console.error(`${r} ${E(e)}`),e}finally{be&&console.log(`${r} complete.`)}}f(mo,"getGlobalDbName");function Ed(){let r=`[${Ed.name}]`;try{be&&console.log(`${r} starting... (I: 59a2510a85051f97ed15fbc8825b6825)`);let e=It();if(!e.apiKeyName_hack)throw new Error("(UNEXPECTED) global api key name falsy? (E: 1782e812f0c87f54b8059468a5b60125)");return e.apiKeyName_hack}catch(e){throw console.error(`${r} ${E(e)}`),e}finally{be&&console.log(`${r} complete.`)}}f(Ed,"getGlobalIndexedDbKey_APIKey");async function Qn({infos:r}){let e=`[${Qn.name}]`;try{be&&console.log(`${e} starting... (I: 4d41880fb748ee2302a624a255665825)`);for(let t of r){let{dbName:o,storeNames:n}=t;await ts({dbName:o})||await wo({dbName:o});for(let i of n)await es({dbName:o,storeName:i})}}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{be&&console.log(`${e} complete.`)}}f(Qn,"initAppStorage");var me=at,za=0;async function wo({dbName:r,storeName:e,version:t,logalot:o=!1}){let n=`[${wo.name}][${r}][${e??"no store name"}]`,s=crypto.randomUUID();o&&console.time(n+s);let i;try{o&&console.log(`${n} starting... (I: f35d4e1ba37252f14c8532fb861b1125)`),await new Promise((c,l)=>{try{o&&console.log(`${n} starting... (I: 0aeddd9376daa0a044677ce4cf8a4c24)`),o&&console.timeLog(n+s,"opening... (I: e748b4ddb445d77cb10a7ba158b49125)");let d=indexedDB.open(r,t);za++,console.log(`${n} initRequestCount: ${za} (I: 294d5f0b12ffe5512bacebe891824d25)`);let u;d.onupgradeneeded=b=>{try{i=b.target.result,o&&console.timeLog(n+s,"onupgradeneeded... (I: e748b4ddb445d77cb10a7ba158b49125)"),e&&(i.objectStoreNames.contains(e)?u=!0:(u=!1,i.createObjectStore(e,{keyPath:"key"})))}catch(p){console.error(`${n}[openDBRequest.onupgradeneeded] ${E(p)} (E: 4a5fa1b0850be47e28bee653da287325)`),l(p)}},d.onblocked=b=>{console.log(`${n}[openDBRequest.onblocked] openDBRequest blocked...time wasted a bit here. version change event (old -> new): ${b.oldVersion} -> ${b.newVersion} (I: 9074ebf4afdba54d6f9d41b360b96a25)`),console.dir(b)},d.onsuccess=b=>{try{o&&console.log("init success (I: 297a5a71e405a0b56413af813f248d24)"),o&&console.timeLog(n+s,"onupgradeneeded... (I: e748b4ddb445d77cb10a7ba158b49125)"),i=b.target.result,e&&(u??=i.objectStoreNames.contains(e),o&&console.log(`${n} ${r} store "${e}" ${u?"already exists":"does not exist"}. (I: db64712bc69c5287b1cf77af1fc13d24)`)),c()}catch(p){console.error(`${n}[openDBRequest.onsuccess] ${E(p)}`),l(p)}},d.onerror=b=>{debugger;console.error(`${n}[initRequest.onerror] ${E(d.error)} (E: 74cf09e9fba2dd9e41225e943c331124)`),l(d.error)}}catch(d){console.error(`${n} ${E(d)}`);debugger;l(d)}finally{o&&console.log(`${n} complete.`)}})}catch(a){throw console.error(`${n} ${E(a)}`),a}finally{i&&(o&&console.log(`${n} closing db ${r}... (I: 3f1c18eec567ea63f3927eef0f038925)`),i.close(),o&&(console.log(`${n} closing db ${r} complete. (I: bc3b2f504245d6203dbba6bd65d30325)`),console.timeLog(n+s,"db closed. (I: e748b4ddb445d77cb10a7ba158b49125)"))),o&&(console.log(`${n} complete.`),console.timeEnd(n+s))}}f(wo,"initializeStorage");async function Ja({dbName:r,logalot:e=!1}){let t=`[${Ja.name}]`,o=crypto.randomUUID();e&&console.time(t+o);try{return e&&console.log(`${t} starting... (I: 8516795b20529d19eb6923defd7a0f24)`),(await indexedDB.databases()).filter(s=>s.name===r).at(0)}catch(n){console.error(`${t} ${E(n)}`)}finally{e&&console.timeEnd(t+o),e&&console.log(`${t} complete.`)}}f(Ja,"storageGetDBInfo");async function es({dbName:r,storeName:e,logalot:t=!1}){let o=`[${es.name}]`,n=crypto.randomUUID();t&&console.time(o+n);let s;try{if(t&&console.log(`${o} starting... (I: 029f7caa8ea5ea08a865f3924c82b624)`),!(await indexedDB.databases()).filter(u=>u.name===r).at(0))throw new Error(`db (${r}) does not exist. can't create store (${e}) (E: 5b15f7aed6f7068d077b2c7ebcbe8524)`);let a=!1;if(t&&console.timeLog(o+n),await new Promise((u,b)=>{let p=indexedDB.open(r);p.onsuccess=h=>{s=h.target.result,a=s.objectStoreNames?.contains(e),t&&console.timeLog(o+n,"open db request"),u()},p.onerror=h=>{debugger;console.error(`${o}[openDBRequest.onerror] ${E(p.error)} (E: 63695744e9e59ff8019e04ceeb8e2524)`),b(p.error)}}),t&&console.timeLog(o+n),a){t&&console.log(`${o} store ${e} already existed. (I: a2263b510c18240fc59fca54e3892324)`);return}let c=await Ja({dbName:r,logalot:t});if(t&&console.timeLog(o+n,"storageGetDBInfo complete"),!c)throw new Error(`db (${r}) does not exist. can't create store (${e}) (E: c771db13fa28f67079aad45e1ab7e624)`);let l=c.version;if(!l)throw new Error(`db (${r}) has no version. can't create store (${e}) (E: 3d2ec52853ad99f92b19ac5aa7fbfe24)`);let d=l+1;if(t&&console.log(`${o} creating store ${e} with version ${d} (I: 312b79f28243c650cf38935114f21e24)`),s)s.close(),s=void 0;else throw new Error("(UNEXPECTED) how did we get here with db falsy? (E: b561784879e19bac54b1c4936aff0c25)");await wo({dbName:r,storeName:e,version:d,logalot:t})}catch(i){throw console.error(`${o} ${E(i)}`),i}finally{s&&(t&&console.log(`${o} closing db ${r}... (I: 3f1c18eec567ea63f3927eef0f038925)`),s.close(),t&&console.log(`${o} closing db ${r} complete. (I: bc3b2f504245d6203dbba6bd65d30325)`)),t&&console.timeLog(o+n),t&&console.log(`${o} complete.`)}}f(es,"storageCreateStoreIfNotExist");async function lr({dbName:r,version:e,storeName:t,key:o,value:n,logalot:s=!1}){let i=`[${lr.name}]`,a;try{s&&console.log(`${i} starting... (I: bf7316c244888cb8ead2d3aac1d9f625)`),await new Promise((l,d)=>{try{s&&console.log(`${i} starting... (I: 81df59e3961d711ce5d8f2ae3e2f3824)`);let u=indexedDB.open(r,e);u.onsuccess=b=>{a=b.target.result;try{let p=a.transaction(t,"readwrite").objectStore(t),h={key:o,value:n};p.put(h),l()}catch(p){console.error(`${i}[putRequest.onsuccess] ${E(p)}`),d(p)}},u.onerror=b=>{debugger;console.error(`${i}[putRequest.onerror] ${E(u.error)} (E: 7a946d99ede2b248df4dcfea4ac99724)`),d(u.error)}}catch(u){console.error(`${i} ${E(u)}`),d(u)}finally{s&&console.log(`${i} complete.`)}})}catch(c){throw console.error(`${i} ${E(c)}`),c}finally{a&&(s&&console.log(`${i} closing db ${r}... (I: 438c6edced94b83a3478c71b08c6c325)`),a.close(),s&&console.log(`${i} closing db ${r} complete. (I: 0d081553b1eb53c65ade2cedb802cf25)`)),s&&console.log(`${i} complete.`)}}f(lr,"storagePut");async function kt({dbName:r,version:e,storeName:t,key:o,logalot:n=!1}){let s=`[${kt.name}]`,i;try{return n&&console.log(`${s} starting... (I: f8ba7cd5801918a8580e91b7c90aa525)`),await new Promise((l,d)=>{try{n&&console.log(`${s} starting... (I: 24163c4a11c8712097db45febaf9c724)`);let u=indexedDB.open(r,e);u.onsuccess=b=>{i=b.target.result;let p;try{p=i.transaction(t).objectStore(t)}catch(g){debugger;console.error(`${s}[openDBRequest.onsuccess][objectStore] ${E(g)}`),d(g);return}let h=p.get(o);h.onsuccess=g=>{try{let m=g.target?.result?.value??void 0;if(!m){l(m);return}if(n&&console.log("Retrieved value:",m),m instanceof Uint8Array)l(Ya(m));else{if(typeof m!="string")throw new Error("(UNEXPECTED) truthy, non-Uint8Array value is not a string? (E: 6a4ec24e2e5d9848f8b542bc2661dc24)");l(m)}}catch(m){d(m)}},h.onerror=g=>{debugger;let m=h.error;console.error(`${s}[openDBRequest.onsuccess][getRequest.onerror] ${E(m)}`),d(m)}},u.onerror=b=>{debugger;console.error(`${s}[openDBRequest.onerror] ${E(u.error)} (E: 074963a908fa9a075f01c73cae829224)`),d(u.error)}}catch(u){console.error(`${s} ${E(u)}`),d(u)}finally{n&&console.log(`${s} complete.`)}})}catch(a){throw console.error(`${s} ${E(a)}`),a}finally{i&&(n&&console.log(`${s} closing db ${r}... (I: a938fc22dfdc76b15f6926bc4d458225)`),i.close(),n&&console.log(`${s} closing db ${r} complete. (I: 18f2ec1557bc83ec4e2c5d5e72264525)`)),n&&console.log(`${s} complete.`)}}f(kt,"storageGet");async function ts({dbName:r,store:e}){let t=`[${ts.name}]`,o;try{return me&&console.log(`${t} starting... (I: 2b4373affa3841220f0b7ca690406624)`),(await window.indexedDB.databases()).some(i=>i.name===r)?e?await new Promise((i,a)=>{let c=indexedDB.open(r);c.onsuccess=l=>{o=l.target.result;let d=o.objectStoreNames.contains(e);i(d)},c.onerror=l=>{debugger;o=c.result;let{error:d}=l.target;console.error(`${t}[openDBRequest.onerror] ${E(c.error)} (E: c783fe607451e46c1feae3a81e0f7924)`),a(d)}}):!0:!1}catch(n){throw console.error(`${t} ${E(n)}`),n}finally{o&&(me&&console.log(`${t} closing db ${r}... (I: 8782d9eea285cf9eb638d493a421a625)`),o.close(),me&&console.log(`${t} closing db ${r} complete. (I: 76a0c5dea2643e2bb84c82c8446a8125)`)),me&&console.log(`${t} complete.`)}}f(ts,"storageDBExists");async function wd({dbName:r,storeName:e,pathToRm:t}){let o=`[${wd.name}]`,n=me;me&&console.log(`${o} starting... (I: c7e4cb759789ece0a8189d7dfb4d2a24)`);let s;return new Promise((i,a)=>{try{if(!r)throw new Error("(UNEXPECTED) dbName falsy? (E: ed336d88c9c4e8d4916b29356dc58324)");if(!e)throw new Error("(UNEXPECTED) storeName falsy? (E: ad493bb79b63a192524b14c59a706524)");if(!t)throw new Error("(UNEXPECTED) pathToRm falsy? (E: 88c9631d93467e17996946882254af24)");let c=indexedDB.open(r);c.onerror=()=>{debugger;c.result&&c.result.close(),console.error(`${o}[openDBRequest.onerror] ${E(c.error)} (E: 4c5ab71a765e61b4292008fd4fafe324)`),a(c.error)},c.onsuccess=()=>{s=c.result;let d=s.transaction(e,"readwrite").objectStore(e),u=IDBKeyRange.lowerBound(t),b=d.openCursor(u);b.onerror=()=>{debugger;console.error(`${o}[openCursorRequest.onerror] ${E(b.error)} (E: caefdda2bb95f92e9fb8d89ee412b524)`),a(b.error)},b.onsuccess=()=>{try{let p=0,h=b.result;if(h)if(h.key.toString().startsWith(t)){let g=h.delete();p++,g.onerror=()=>{debugger;console.error(`${o}[deleteRequest.onerror] ${E(g.error)} (E: abc031c53e5387322cd8909b3ada9b24)`),a(g.error)},h.continue()}else me&&console.log(`${o} rmCount: ${p} (I: e4bc613a5514c0942484b79267e16724)`),i();else me&&console.log(`${o} cursor is falsy, so either we have no more records or had no records to begin with. (I: 9ff3aec6274416501a7baf6dcc5f2624)`),i()}catch(p){console.error(`${o}[openCursorRequest.onsuccess] ${E(p)}`),a(p)}}}}catch(c){debugger;console.error(`${o} ${E(c)}`),a(c)}}).finally(()=>{s&&(me&&console.log(`${o} closing db ${r}... (I: 39b4ba83de4bdfd541e3384ebab27425)`),s.close(),me&&console.log(`${o} closing db ${r} complete. (I: e4015b9436c4b2bc0ccf0e11e2037925)`)),me&&console.log(`${o} complete.`),me=n})}f(wd,"storageRmRF");async function $d({dbName:r,storeName:e,dirPath:t,withFileTypes:o=!1}){let n=`[${$d.name}]`,s;try{return await new Promise((c,l)=>{let d=indexedDB.open(r);d.onerror=()=>{debugger;l(d.error)},d.onsuccess=()=>{s=d.result;let b=s.transaction(e,"readonly").objectStore(e),p=t.endsWith("/")?t:t+"/",h=IDBKeyRange.lowerBound(p),g=b.openCursor(h),m=new Set,$=[];g.onerror=()=>{debugger;console.error(`${n}[openCursorRequest.onerror] ${E(g.error)}`),l(g.error)},g.onsuccess=()=>{try{let w=g.result;if(w){let T=w.key.toString();if(T.startsWith(p)&&T!==p){let A=T.substring(p.length),G=A.split("/")[0];if(o){let y=A.substring(G.length).startsWith("/");$.push({name:G,isDirectory:f(()=>y,"isDirectory"),isFile:f(()=>!y,"isFile"),isBlockDevice:f(()=>!1,"isBlockDevice"),isCharacterDevice:f(()=>!1,"isCharacterDevice"),isSymbolicLink:f(()=>!1,"isSymbolicLink"),isFIFO:f(()=>!1,"isFIFO"),isSocket:f(()=>!1,"isSocket")})}else m.add(G);w.continue()}else T.startsWith(p)?w.continue():c(o?$:Array.from(m))}else c(o?$:Array.from(m))}catch(w){console.error(`${n}[openCursorRequest.onsuccess] ${E(w)}`),l(w)}}}})}catch(i){throw console.error(`${n} ${E(i)}`),i}finally{s&&(me&&console.log(`${n} closing db ${r}... (I: 39b4ba83de4bdfd541e3384ebab27425)`),s.close(),me&&console.log(`${n} closing db ${r} complete. (I: e4015b9436c4b2bc0ccf0e11e2037925)`))}}f($d,"storageReaddir");var qt=Mi;async function yd(r){let e=`[${yd.name}]`;try{qt&&console.log(`${e} starting... (I: 1905af1827a34ca8a5507fe0c5085b01)`),await Qn({infos:[{dbName:r.dbName,storeNames:[r.storeName,...r.additionalStoreNames??[]]}]})}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{qt&&console.log(`${e} complete.`)}}f(yd,"initIbGibStorage");function Za(r){let e=`[${Za.name}]`;try{qt&&console.log(`${e} starting... (I: 7be20d161bb14a498c44a42d3193bec1)`),globalThis.ibgib||(globalThis.ibgib={dbName_hack:r.dbName,apiKeyName_hack:r.apiKeyName,storeName_hack:r.storeName}),globalThis.ibgib.spaceGib||(globalThis.ibgib.spaceGib={version:Bi,spaceShim:{},fnDefaultGetAPIKey:f(async()=>await kt({dbName:r.dbName,storeName:r.storeName,key:r.apiKeyName})??"","fnDefaultGetAPIKey"),dbName_hack:r.dbName,apiKeyName_hack:r.apiKeyName,storeName_hack:r.storeName})}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{qt&&console.log(`${e} complete.`)}}f(Za,"initIbGibGlobalThis");function Iw(r){if(!globalThis.ibgib?.spaceGib){if(!r)throw new Error("Global context not initialized and config not provided.");Za(r)}return globalThis.ibgib.spaceGib}f(Iw,"getIbGibGlobalThis_SpaceGib");async function Id(r){let e=`[${Id.name}]`;try{qt&&console.log(`${e} starting... (I: 3123b18eb29b480bad056a9a029b9ad4)`),await(await import(r)).bootstrapSpaceGibApp()}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{qt&&console.log(`${e} complete.`)}}f(Id,"dynamicallyLoadBootstrapScript");var ue=!1;async function rs({timeline:r}){let e=`[${rs.name}]`;try{if(ue&&console.log(`${e} starting...`),te({ibGib:r}))return console.warn(`${e} getting lock scope on a primitive ibgib can grossly impact performance. (W: 55203e415ae2ac7ddb19c21772b28925)`),_({ibGib:r});{let t=ne({gib:r.gib}),o=t.tjpGib??t.punctiliarHash;if(!o)throw new Error(`${e} (UNEXPECTED) Could not determine tjpGib or punctiliarHash from ibGib. (E: eb3b6472e9b335991a1b0869f772f7d3)`);return o}}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{ue&&console.log(`${e} complete.`)}}f(rs,"getLockScope");async function _d({timeline:r,rel8nInfos:e,rel8nRemovalInfos:t,timelineIndexInfo:o,metaspace:n,space:s,skipLock:i,noDna:a}){let c=`[${_d.name}]`;try{if(ue&&console.log(`${c} starting... (I: fcdff10832215068019355265f4cbc25)`),s??=await n.getLocalUserSpace({lock:!1}),!s)throw new Error("(UNEXPECTED) space falsy? couldn't even get default local user space? (E: 2051b44a052d6a2984b9a22f680e4625)");let l=await rs({timeline:r}),d=f(async()=>{if(!s)throw new Error("(UNEXPECTED) space falsy? couldn't even get default local user space? (E: 845c4181c8c15d7219166ceb3c4dca25)");let b=_({ibGib:r}),p=await n.getLatestAddr({addr:b,space:s});if(!p)throw new Error(`${c} (UNEXPECTED) Could not get latest address for timeline ${_({ibGib:r})}. (E: genuuid)`);let h=ve({ibGib:r});if(b!==p){let T=await n.get({addrs:[p],space:s});if(T.errorMsg||(T.ibGibs??[]).length!==1)throw new Error(`${c} (UNEXPECTED) couldn't get latest timeline ibgib (${p}) from space (${s.ib}). errorMsg: ${T.errorMsg??"[unknown error]"} (E: genuuid)`);h=T.ibGibs.at(0)}let g;if(t&&t.length>0){g={};for(let T of t){let{rel8nName:A,ibGibAddrs:G}=T;if(G.length===0){console.warn(`${c} tried to remove 0 ibGibAddrs in rel8nName ${A}? skipping... (W: 93aeb601be66d680989e72ec70e4c826)`);continue}g[A]||(g[A]=[]),g[A]=g[A].concat(G)}}let m={};for(let T of e){let{rel8nName:A,ibGibs:G}=T;if(G.length===0){console.warn(`${c} tried to add 0 ibGibs to rel8nName ${A}? skipping... (W: 708252dfdeb60757fee4554e769aaa25)`);continue}m[A]||(m[A]=[]),m[A].push(...G.map(y=>_({ibGib:y})))}let $=await ye({src:h,rel8nsToRemoveByAddr:g,rel8nsToAddByAddr:m,dna:!a,nCounter:!0}),w=$.newIbGib;return await n.persistTransformResult({resTransform:$,space:s}),o&&await os({type:o.type,rel8nInfos:[{rel8nName:o.rel8nName,ibGibs:[w]}],metaspace:n,space:s,skipLock:i}),await n.registerNewIbGib({ibGib:w,space:s}),w},"fn");return i?await d():await Ne({scope:l,secondsValid:180,maxDelayMs:100,maxLockAttempts:1800,space:s,callerInstanceId:$e(),fn:d})}catch(l){throw console.error(`${c} ${E(l)}`),l}finally{ue&&console.log(`${c} complete.`)}}f(_d,"appendToTimeline");async function os({type:r,rel8nInfos:e,dataToAddOrPatch:t,metaspace:o,space:n,skipLock:s}){let i=`[${os.name}]`;try{if(ue&&console.log(`${i} starting... (I: 6e7d05fe916d813b71766e2eaa747c25)`),r==="latest")throw new Error('cannot update the "latest" special index by this function. The registerNewIbGib will do this automatically. (E: 231eb78a221ccdbcf56cd1899260a425)');if(n??=await o.getLocalUserSpace({lock:!1}),!n)throw new Error("(UNEXPECTED) space falsy? couldn't even get default local user space? (E: 43067821a4749a7648fe2612d25d7f25)");let a=f(async()=>{let c=f(async()=>{let l=await o.getSpecialIbGib({type:r,space:n,initialize:!0});if(!l)throw new Error(`(UNEXPECTED) couldn't initialize/get special ibgib index of type ${r}. (E: genuuid)`);return l.rel8ns||console.warn(`${i} not sure if this ever hits, but is there ever a scenario where specialIndex.rel8ns is falsy? (W: 06161c366bc7ec858b9b5aa7ee9b6d25)`),l},"fnGetSpecialIndex");for(let l of e??[]){let{rel8nName:d,ibGibs:u}=l;u.length===0&&console.error(`${i} ibGibs empty. skipping rel8nName (${d}). (E: 150d74f73f97aea1b97d173d92c77125)`);let p=(await c()).rel8ns??{},h,g=p[d]??[];if(g.length>0){let m=new Set;u.forEach($=>{let w=_({ibGib:$}),T=$.rel8ns?.past??[];g.filter(A=>[...T,w].includes(A)).forEach(A=>m.add(A))}),m.size>0&&(h=Array.from(m))}await o.rel8ToSpecialIbGib({type:r,rel8nName:d,ibGibsToRel8:u,addrsToUnRel8:h,space:n,linked:!1,severPast:!1,deletePreviousSpecialIbGib:!1})}if(Object.keys(t??{}).length>0){let l=await c(),d=await Fe({src:l,dataToAddOrPatch:t,dna:!1,linkedRel8ns:[Y.past],nCounter:!0}),u=d.newIbGib;await Q({resTransform:d,space:n});let b=ae({type:r});await o.setConfigAddr({key:b,addr:_({ibGib:u}),space:n}),await o.registerNewIbGib({ibGib:u,space:n})}},"fn");s?await a():await Ne({scope:r,secondsValid:60,maxDelayMs:100,maxLockAttempts:600,space:n,fn:a})}catch(a){throw console.error(`${i} ${E(a)}`),a}finally{ue&&console.log(`${i} complete.`)}}f(os,"updateSpecialIndex");async function ns({timeline:r,timelineAddr:e,metaspace:t,space:o}){let n=`[${ns.name}]`;try{if(ue&&console.log(`${n} starting... (I: f2b605361368e1956f6db878dbfeb825)`),!r&&!e)throw new Error("either timeline or timelineAddr required. (E: 97551b2b18ecd22a18185a783f9a0825)");e??=_({ibGib:r});let s=await t.getLatestAddr({addr:e,space:o})??e;if(!s)throw new Error(`${n} (UNEXPECTED) Could not get latest address for timeline ${_({ibGib:r})}. (E: genuuid)`);let i;if(e===s){if(!r){let a=await t.get({addrs:[s],space:o});if(a.errorMsg||(a.ibGibs??[]).length!==1)throw new Error(`${n} (UNEXPECTED) couldn't get latest timeline ibgib (${s}) from space (${o.ib}). errorMsg: ${a.errorMsg??"[unknown error]"} (E: 3fc767a594788a43a4ba18c87491a825)`);r=a.ibGibs.at(0)}i=ve({ibGib:r})}else{let a=await t.get({addrs:[s],space:o});if(a.errorMsg||(a.ibGibs??[]).length!==1)throw new Error(`${n} (UNEXPECTED) couldn't get latest timeline ibgib (${s}) from space (${o.ib}). errorMsg: ${a.errorMsg??"[unknown error]"} (E: genuuid)`);i=a.ibGibs.at(0)}return i}catch(s){throw console.error(`${n} ${E(s)}`),s}finally{ue&&console.log(`${n} complete.`)}}f(ns,"getLatestTimelineIbGibDto_nonLocking");async function Td({timeline:r,timelineAddr:e,mut8Opts:t,metaspace:o,space:n,skipLock:s,timelineIndexInfo:i,noDna:a}){let c=`[${Td.name}]`;try{if(ue&&console.log(`${c} starting... (I: genuuid)`),!r&&!e)throw new Error("(UNEXPECTED) both timeline and timelineAddr falsy? either one is required. (E: a19d98c6acb87af3b876c1484f6ac825)");if(n??=await o.getLocalUserSpace({lock:!1}),!n)throw new Error("(UNEXPECTED) space falsy? couldn't even get default local user space? (E: genuuid)");if(!r){let b=await o.get({addrs:[e],space:n});if(!b.success||b.ibGibs?.length!==1)throw new Error(`couldn't get timeline ibGib from timelineAddr (${e}) in space (${n?.ib??"undefined"}) (E: genuuid)`);r=b.ibGibs.at(0)}let l=await rs({timeline:r}),d=f(async()=>{if(!n)throw new Error("(UNEXPECTED) space falsy? couldn't even get default local user space? (E: 845c4181c8c15d7219166ceb3c4dca25)");if(!r)throw new Error("(UNEXPECTED) timeline falsy? we should be ensured that it's truthy at this point. (E: 2e1758b2cc3820531f7ac7f5f6b3a825)");let b=await ns({timeline:r,metaspace:o,space:n}),p=await Fe({...t,src:b,dna:!a,nCounter:!0}),h=p.newIbGib;return await o.persistTransformResult({resTransform:p,space:n}),i&&await os({type:i.type,rel8nInfos:[{rel8nName:i.rel8nName,ibGibs:[h]}],metaspace:o,space:n,skipLock:s}),await o.registerNewIbGib({ibGib:h,space:n}),h},"fn");return s?await d():await Ne({scope:l,secondsValid:180,maxDelayMs:100,maxLockAttempts:1800,space:n,callerInstanceId:$e(),fn:d})}catch(l){throw console.error(`${c} ${E(l)}`),l}finally{ue&&console.log(`${c} complete.`)}}f(Td,"mut8Timeline");async function Ad({ib:r,data:e,rel8ns:t,noDna:o,parentIb:n,parentIbGib:s,metaspace:i,space:a}){let c=`[${Ad.name}]`;try{if(ue&&console.log(`${c} starting...`),a??=await i.getLocalUserSpace({lock:!1}),!a)throw new Error("(UNEXPECTED) space is required, but is falsy. (E: 252994a554224b17aa9816c7a765c925)");s??=n?s=k.primitive({ib:n}):s=Z;let l=await k.firstGen({parentIbGib:s,ib:r,data:e,rel8ns:t,dna:!o,nCounter:!0,squash:!!o,tjp:{timestamp:!0,uuid:!e?.uuid}});return await i.persistTransformResult({resTransform:l,space:a}),await i.registerNewIbGib({ibGib:l.newIbGib,space:a}),l}catch(l){throw console.error(`${c} ${E(l)}`),l}}f(Ad,"createTimeline");async function Qa({ibGib:r,metaspace:e,space:t}){let o=`[${Qa.name}]`;try{if(ue&&console.log(`${o} starting...`),t??=await e.getLocalUserSpace({lock:!1}),!t)throw new Error("(UNEXPECTED) space is required. (E: genuuid)");let n=r.rel8ns?.dna??[];if(n.length===0)return[];let s=await e.get({addrs:n,space:t});if(!s.success||(s.ibGibs??[]).length!==n.length){let i=n.filter(a=>!s.ibGibs?.some(c=>_({ibGib:c})===a));throw new Error(`Could not get all dna ibGibs for ${_({ibGib:r})}. Addrs not found: ${i.join(", ")}. Errors: ${s.errorMsg??"[unknown error (E: 92cf95774828d8a978331da859098625)]"} (E: genuuid)`)}return s.ibGibs}catch(n){throw console.error(`${o} ${E(n)}`),n}}f(Qa,"getDna");async function ec({timeline:r,getLatest:e,includeDna:t,metaspace:o,space:n}){let s=`[${ec.name}]`;try{if(ue&&console.log(`${s} starting... (I: 7fbc442a27e8f9fda8ac4228ded84825)`),n??=await o.getLocalUserSpace({lock:!1}),!n)throw new Error("(UNEXPECTED) space is required. (E: genuuid)");let i=e?await ns({timeline:r,metaspace:o,space:n}):ve({ibGib:r}),a=_({ibGib:i}),c={},l=t?co({ibGibs:await Qa({ibGib:i,metaspace:o,space:n})}):void 0,d=r.rel8ns?.past??[];if(d.length===0)return{headIbGib:i,orderedPastIbGibs:[],pastIbGibMap:c,dnaMap:l};let u=await o.get({addrs:d,space:n});if(!u.success||(u.ibGibs??[]).length!==d.length){let p=d.filter(h=>!u.ibGibs?.some(g=>_({ibGib:g})===h));throw new Error(`Could not get all dna ibGibs for ${a}. Addrs not found: ${p.join(", ")}. Errors: ${u.errorMsg??"[unknown error (E: 887339d8b5580ed1ac9892a554255525)]"} (E: 4ab7a8a58adff4e238171f7c110c6825)`)}c=co({ibGibs:u.ibGibs})??{};let b=[];for(let p of d){let h=c[p];if(!h)throw new Error("(UNEXPECTED) pastIbGib falsy? due to our logic, the pastIbGibMap should be complete. (E: 6010d8c14184124008631928e1265525)");b.push(h)}return{headIbGib:i,orderedPastIbGibs:b,pastIbGibMap:c,dnaMap:l}}catch(i){throw console.error(`${s} ${E(i)}`),i}finally{ue&&console.log(`${s} complete.`)}}f(ec,"getHistory");async function Sd({timeline:r,getLatest:e,metaspace:t,space:o}){let n=`[${Sd.name}]`;try{return ue&&console.log(`${n} starting... (I: c7a328b14018642138ebb47870c15626)`),(await ec({timeline:r,getLatest:e,includeDna:!1,metaspace:t,space:o})).orderedPastIbGibs.map(a=>_({ibGib:a}))}catch(s){throw console.error(`${n} ${E(s)}`),s}finally{ue&&console.log(`${n} complete.`)}}f(Sd,"getHistoryAddrs");var dt=!1,ss=class r{static{f(this,"IbGibApiBridge")}lc=`[${r.name}]`;async parseResponseJson(e,t){let o=e.headers.get("content-type")||"";if(!o.includes("application/json")){let n=await e.text();throw n.trim().toLowerCase().startsWith("<!doctype html")||n.includes("<html")?new Error(`API request to '${t}' failed (${e.status} ${e.statusText}): Received HTML fallback instead of JSON. Check API route matching and parameters.`):new Error(`API request to '${t}' failed (${e.status} ${e.statusText}): Returned non-JSON content type '${o}': ${n.slice(0,150)}`)}return await e.json()}async postGenesisKeystone(e){let t=`${this.lc}[${this.postGenesisKeystone.name}]`;try{dt&&console.log(`${t} starting... (I: eecd082fc4a4381c8857928e8b090826)`);let o="/api/keystone/genesis",n=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({keystoneIbGib:e})}),s=await this.parseResponseJson(n,o);if(!n.ok){let i=s.message||s.error||"Unknown error";return console.error(`${t} server rejected genesis keystone: ${i}`),{success:!1,message:i,addr:s.addr,statusCode:n.status}}return dt&&console.log(`${t} genesis keystone posted successfully. pending: ${s.pending}`),{success:!0,pending:!!s.pending,statusCode:n.status,addr:s.addr,message:s.message}}catch(o){let n=E(o);return console.error(`${t} error: ${n}`),{success:!1,message:n}}}async putEvolveKeystone({domainAddr:e,keystoneIbGib:t,relatedKeystoneIbGibs:o=[],revokeTokens:n}){let s=`${this.lc}[${this.putEvolveKeystone.name}]`;try{dt&&console.log(`${s} posting evolved keystone...`);let i=`/api/keystone/evolve/${encodeURIComponent(e)}`,a=await fetch(i,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({keystoneIbGib:t,relatedKeystoneIbGibs:o,revokeTokens:n})}),c=await this.parseResponseJson(a,i);if(!a.ok){let l=c.message||c.error||"Unknown error";return console.error(`${s} server rejected keystone evolution: ${l}`),{success:!1,message:l}}return dt&&console.log(`${s} keystone evolution accepted by server.`),{success:!0}}catch(i){let a=E(i);return console.error(`${s} fetch error: ${a}`),{success:!1,message:a}}}async lookupPrimaryKeystone({identifier:e}){let t=`${this.lc}[${this.lookupPrimaryKeystone.name}]`;try{let o="/api/keystone/lookup",n=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({identifier:e})}),s=await this.parseResponseJson(n,o);if(!n.ok){let i=s.message||s.error||"Identity not found";return console.error(`${t} server lookup failed: ${i}`),{success:!1,message:i}}return{success:!0,tjpAddr:s.tjpAddr,primaryKeystoneIbGib:s.primaryKeystoneIbGib}}catch(o){let n=E(o);return console.error(`${t} lookup fetch error: ${n}`),{success:!1,message:n}}}async checkEmailAvailability({email:e}){let t=`${this.lc}[${this.checkEmailAvailability.name}]`;try{let o=`/api/keystone/check-email?email=${encodeURIComponent(e)}`,n=await fetch(o,{method:"GET",headers:{"Content-Type":"application/json"}}),s=await this.parseResponseJson(n,o);if(!n.ok){let i=s.message||s.error||"Server check failed";return console.error(`${t} email check failed: ${i}`),{available:!1,message:i}}return{available:s.available??!0,message:s.message}}catch(o){let n=E(o);return console.error(`${t} check email error: ${n}`),{available:!0}}}async getKeystoneGraph(e){let t=`${this.lc}[${this.getKeystoneGraph.name}]`;try{dt&&console.log(`${t} fetching keystone graph...`);let o=`/api/keystone/${encodeURIComponent(e)}?getLatest=true&getGraph=true`,n=await fetch(o,{method:"GET",headers:{Accept:"application/json"}}),s=await this.parseResponseJson(n,o);if(!n.ok){let i=s.message||s.error||"Unknown error";return console.error(`${t} server rejected keystone graph get: ${i}`),{success:!1,message:i}}return{success:!0,graph:s.domainGraph}}catch(o){let n=E(o);return console.error(`${t} fetch error: ${n}`),{success:!1,message:n}}}async getIbGib(e,t,o=!1){let n=`${this.lc}[${this.getIbGib.name}]`;try{dt&&console.log(`${n} fetching single ibGib frame...`);let s=`/api/ibgib/${encodeURIComponent(e)}/${encodeURIComponent(t)}?getLatest=${o}&getGraph=false`,i=await fetch(s,{method:"GET",headers:{Accept:"application/json"}}),a=await this.parseResponseJson(i,s);if(!i.ok){let c=a.message||a.error||"Unknown error";return console.error(`${n} server rejected ibGib get: ${c}`),{success:!1,message:c}}return{success:!0,ibGib:a}}catch(s){let i=E(s);return console.error(`${n} fetch error: ${i}`),{success:!1,message:i}}}async getIbGibGraph(e,t,o=!1){let n=`${this.lc}[${this.getIbGibGraph.name}]`;try{dt&&console.log(`${n} fetching ibGib graph...`);let s=`/api/ibgib/${encodeURIComponent(e)}/${encodeURIComponent(t)}?getLatest=${o}&getGraph=true`,i=await fetch(s,{method:"GET",headers:{Accept:"application/json"}}),a=await i.json();if(!i.ok){let c=a.message||a.error||"Unknown error";return console.error(`${n} server rejected ibGib graph get: ${c}`),{success:!1,message:c}}return{success:!0,graph:a.graph,addr:a.addr}}catch(s){let i=E(s);return console.error(`${n} fetch error: ${i}`),{success:!1,message:i}}}async postVerificationCode({email:e,primaryTjpAddr:t}){let o=`${this.lc}[${this.postVerificationCode.name}]`;try{let n="/api/email/verification-code",s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e,primaryTjpAddr:t})}),i=await this.parseResponseJson(s,n);if(!s.ok){let a=i.message||i.error||"Verification code request failed";return console.error(`${o} server verification code post failed: ${a}`),{success:!1,message:a}}return{success:!0,message:i.message}}catch(n){let s=E(n);return console.error(`${o} post verification code error: ${s}`),{success:!1,message:s}}}async postMagicLink(e){return this.postVerificationCode(e)}async postVerifyCode({email:e,primaryTjpAddr:t,code:o}){let n=`${this.lc}[${this.postVerifyCode.name}]`;try{let s="/api/email/verify-code",i=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e,primaryTjpAddr:t,code:o})}),a=await this.parseResponseJson(i,s);if(!i.ok){let c=a.message||a.error||"Code verification failed";return console.error(`${n} server verify-code failed: ${c}`),{success:!1,message:c}}return dt&&console.log(`${n} verification code accepted.`),{success:!0,message:a.message}}catch(s){let i=E(s);return console.error(`${n} fetch error: ${i}`),{success:!1,message:i}}}async postCustodianGenesis({email:e,code:t,username:o}){let n=`${this.lc}[${this.postCustodianGenesis.name}]`;try{let s="/api/identity/custodian/genesis",i=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e,code:t,username:o})}),a=await this.parseResponseJson(i,s);if(!i.ok){let c=a.message||a.error||"Custodian genesis failed";return console.error(`${n} custodian genesis failed: ${c}`),{success:!1,message:c}}return{success:!0,isNewIdentity:!!a.isNewIdentity,primaryTjpAddr:a.primaryTjpAddr,primaryKeystone:a.primaryKeystone,primaryGraph:a.primaryGraph,custodianReqs:a.custodianReqs,message:a.message}}catch(s){let i=E(s);return console.error(`${n} post custodian genesis error: ${i}`),{success:!1,message:i}}}async postCustodianRegisterDelegate({delegateKeystone:e}){let t=`${this.lc}[${this.postCustodianRegisterDelegate.name}]`;try{let o="/api/identity/custodian/register-delegate",n=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({delegateKeystone:e})}),s=await this.parseResponseJson(n,o);if(!n.ok){let i=s.message||s.error||"Custodian delegate registration failed";return console.error(`${t} custodian delegate registration failed: ${i}`),{success:!1,message:i}}return{success:!0,primaryTjpAddr:s.primaryTjpAddr,evolvedPrimaryKeystone:s.evolvedPrimaryKeystone,primaryGraph:s.primaryGraph,message:s.message}}catch(o){let n=E(o);return console.error(`${t} post custodian register delegate error: ${n}`),{success:!1,message:n}}}async getSsoConfig(){let e=`${this.lc}[${this.getSsoConfig.name}]`;try{let t="/api/identity/sso/config",o=await fetch(t,{method:"GET"}),n=await this.parseResponseJson(o,t);return o.ok?{success:!0,providers:n.providers}:{success:!1,message:n.message||n.error||"Failed to fetch SSO config"}}catch(t){let o=E(t);return console.error(`${e} fetch SSO config error: ${o}`),{success:!1,message:o}}}async postSsoLogin({code:e,providerId:t,redirectUri:o}){let n=`${this.lc}[${this.postSsoLogin.name}]`;try{let s="/api/identity/sso/login",i=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e,providerId:t,redirectUri:o})}),a=await this.parseResponseJson(i,s);if(!i.ok){let c=a.message||a.error||"SSO login code exchange failed";return console.error(`${n} SSO login code exchange failed: ${c}`),{success:!1,message:c}}return{success:!0,isNewIdentity:!!a.isNewIdentity,primaryTjpAddr:a.primaryTjpAddr,primaryKeystone:a.primaryKeystone,primaryGraph:a.primaryGraph,custodianReqs:a.custodianReqs,userInfo:a.userInfo,message:a.message}}catch(s){let i=E(s);return console.error(`${n} post SSO login error: ${i}`),{success:!1,message:i}}}},$o;function Bw(){return $o||($o=new ss),$o}f(Bw,"getApiBridge");function jw(r){$o=r}f(jw,"setApiBridge");var tc=/^error (\w+) ([a-fA-F\d]{32}|undefined)$/;var ft=!1;function oc({rawMsg:r}){let e=`[${oc.name}]`;try{ft&&console.log(`${e} starting...`);let t=is({rawMsg:r}),o=t.body.replace(/\s/g,"_").replace(/\W/g,""),n;if(o.length>20)n=o.substring(0,20);else if(o.length>0)n=o;else throw new Error("(UNEXPECTED) error msg should have characters/alphanumerics... (E: a3b9cd11a44cc7892a748819c2885422)");return`error ${n} ${t.uuid??"undefined"}`}catch(t){throw console.error(`${e} ${t.message}`),t}finally{ft&&console.log(`${e} complete.`)}}f(oc,"getErrorIb");function is({rawMsg:r}){let e=`[${is.name}]`;try{if(ft&&console.log(`${e} starting...`),!r)throw new Error("(UNEXPECTED) rawMsg required (E: e5bd3b433a1781ebe885534cd2495622)");let t,o=r.match(_s);if(o){let[n,s,i,a,c,l]=o;if(!a)throw new Error("invalid error msg body (E: a675e6855cca96519d33d44ea5400922)");t={success:!1,raw:r,body:a?.trim(),uuid:c.slice(4,36)},s&&(t.location=s),(i||l)&&(t.unexpected=!0)}else{t={success:!1,raw:r,body:r};let n=r.match(Ts);if(n){let[s,i]=n;t.location=i}r.toLowerCase().includes("(unexpected)")&&(t.unexpected=!0)}return t}catch(t){throw console.error(`${e} ${t.message}`),t}finally{ft&&console.log(`${e} complete.`)}}f(is,"parseRawErrorMsg");function xt({rawMsg:r}){let e=`[${xt.name}]`;try{return ft&&console.log(`${e} starting...`),Oe({parentPrimitiveIb:"error",ib:oc({rawMsg:r}),data:is({rawMsg:r}),ibRegExpPattern:tc.source})}catch(t){throw console.error(`${e} ${t.message}`),t}finally{ft&&console.log(`${e} complete.`)}}f(xt,"getErrorIbGib");function ze({ibGib:r}){let e=`[${ze.name}]`;try{if(ft&&console.log(`${e} starting...`),!r)throw new Error("ibGib required (E: 1d756fbbd96f1734b97ba013537ed522)");return r.ib.startsWith("error ")}catch(t){throw console.error(`${e} ${t.message}`),t}finally{ft&&console.log(`${e} complete.`)}}f(ze,"isError");var nc="___whitespace___";var Le=!1;function sc({commentText:r,addlMetadataText:e}){let t=`[${sc.name}]`;try{if(!r)throw new Error("commentText required. (E: 22fdfd0aa0524a18b63a9405b312c99e)");let o=pe({text:r,length:20,replaceMap:{"?":"__qm__"}});if(e){e.length>128&&console.warn(`${t} addlMetadataText (${e.length}) is too long. Max length: ${128}`);let n=pe({text:e,length:128});if(!n)throw new Error("(UNEXPECTED) addlMetadataText contains no safe characters? (E: dd03c578ada2836b05c94a4aa1785222)");return`comment ${o} ${n}`}else return`comment ${o}`}catch(o){throw console.error(`${t} ${o.message}`),o}}f(sc,"getCommentIb");function xd({ib:r}){let e=`${xd.name}]`;try{if(Le&&console.log(`${e} starting... (I: 1a16f5e3134599eeb585eae77ee6af22)`),!r)throw new Error("ib required (E: d89f8c4df46b970585c82bc89c1c6322)");let[t,o,n]=r.split(" ");for(;o.includes("__qm__");)o=o.replace("__qm__","?");return{safeIbCommentText:o,safeIbCommentMetadataText:n}}catch(t){throw console.error(`${e} ${t.message}`),t}finally{Le&&console.log(`${e} complete.`)}}f(xd,"parseCommentIb");async function vd({text:r,addlMetadataText:e,saveInSpace:t,space:o,dontTrimText:n}){let s=`[${vd.name}]`;Le&&console.log(`${s} starting...`);try{if(!r)throw new Error("text required (E: 3e3d0f555e1a83771a6548eb10943522)");if(n||(r=r.trim()),!r)throw new Error("text cannot be only whitespace when dontTrimText is falsy. (E: d6db3537b9834294836aeb70987c908e)");let i={text:r,textTimestamp:Ae()},a={parentIbGib:k.primitive({ib:"comment"}),ib:sc({commentText:r.trim()||nc,addlMetadataText:e}),data:i,dna:!0,tjp:{uuid:!0,timestamp:!0},nCounter:!0};Le&&console.log(`${s} opts: ${H(a)}`);let c=await k.firstGen(a);if(t){if(!o)throw new Error("space required if saveInSpace is truthy (E: 40f69f22f21b4279a83cb746cb4b0da1)");await Q({resTransform:c,space:o})}return c}catch(i){throw console.error(`${s} ${i.message}`),i}}f(vd,"createCommentIbGib");function Dd({ibGib:r}){let e=`[${Dd.name}]`;try{if(Le&&console.log(`${e} starting...`),!r)throw new Error("ibGib required (E: f204dac30ae548b0a049f1c4d8048502)");let{ib:t,data:o,rel8ns:n}=r;if(!n)return Le&&console.log(`${e} rel8ns falsy, NOT a comment (I: 6e145eb2d0ba46629746215a3b655fd5)`),!1;let s=n.ancestor||[];return s&&s.includes("comment^gib")?(Le&&console.log(`${e} descends from comment^gib, YES is a comment (I: 1a8557780e2e4c1580d5a2585567762b)`),!0):o?o.text&&t?.includes("comment")?(Le&&console.log(`${e} has text, and ib has 'comment', YES is a comment (I: 3aa03bcd639d4ec7abd7ead917eda3d8)`),!0):(Le&&console.log(`${e} reached end, doesn't have comment qualities. NOT a comment. (I: cfa529f27f9d490abd476c924ef77087)`),!1):(Le&&console.log(`${e} data falsy, NOT a comment (I: 30b20ff6785f432f98489f11efe24299)`),!1)}catch(t){throw console.error(`${e} ${t.message}`),t}finally{Le&&console.log(`${e} complete.`)}}f(Dd,"isComment");var bt=!1;function ic(r){let e=`[${ic.name}]`;try{let t=r?`${nr} ${r}`:nr;return bt&&console.log(`${e} ${t}`),t}catch(t){throw console.error(`${e} ${t.message}`),t}}f(ic,"getArgIb");function Od({ib:r,ibGib:e}){let t=`[${Od.name}]`;try{if(bt&&console.log(`${t} starting...`),!r)if(e)r=e.ib;else throw new Error("either ib or ibGib required (E: c052a9d76df867626f9ba17141cdce22)");return r.startsWith(nr)}catch(o){throw console.error(`${t} ${o.message}`),o}finally{bt&&console.log(`${t} complete.`)}}f(Od,"isArg");function ac(r){let e=`[${ac.name}]`;try{let t=r?`${Kr} ${r}`:Kr;return bt&&console.log(`${e} ${t}`),t}catch(t){throw console.error(`${e} ${t.message}`),t}}f(ac,"getResultIb");async function vt({argData:r,ibMetadata:e,noTimestamp:t}){let o=`[${vt.name}]`;try{let n=await k.firstGen({ib:ic(e),parentIbGib:k.primitive({ib:nr}),data:r,dna:!1,noTimestamp:t});if(n.newIbGib){let{newIbGib:s}=n;return s.rel8ns.past=[],s.gib=await Re(s),s}else throw new Error("create ibGib failed")}catch(n){throw console.error(`${o} ${n.message}`),n}}f(vt,"argy_");async function Dt({resultData:r,ibMetadata:e,noTimestamp:t}){let o=`[${Dt.name}]`;try{let n=await k.firstGen({ib:ac(e),parentIbGib:k.primitive({ib:Kr}),data:r,dna:!1,noTimestamp:t});if(n?.newIbGib){let{newIbGib:s}=n;return s.rel8ns.past=[],s.gib=await Re(s),s}else throw new Error("create ibGib failed")}catch(n){throw console.error(`${o} ${n.message}`),n}}f(Dt,"resulty_");function cs({ibGib:r}){let e=`[${cs.name}]`;try{if(bt&&console.log(`${e} starting...`),!r)throw new Error("ibGib required (E: e11cee2a6c59a5e7a4d39ea55751c423)");if(!r.data)return!1;let t=r.data;return t.cmd&&typeof t.cmd=="string"}catch(t){throw console.error(`${e} ${t.message}`),t}finally{bt&&console.log(`${e} complete.`)}}f(cs,"isCommand");function ls({ibGib:r}){let e=`[${ls.name}]`;try{return bt&&console.log(`${e} starting... (I: aad0a14f4d62061424fc92da4d53d823)`),typeof r.witness=="function"}catch(t){throw console.error(`${e} ${t.message}`),t}finally{bt&&console.log(`${e} complete.`)}}f(ls,"isWitness");var yo="subject",ds=/^[a-zA-Z0-9_\-.]{1,255}$/,cc="subject",lc="",Io="subject is a cool ibgib witness that has seriously fascinating behavior.";var dc="observable";var ut={subscribe:"subscribe"},fc=Object.values(ut);var bc={next:"next",error:"error",complete:"complete"};var pt={...ut,...bc};var $r={version:"1",uuid:lc,name:cc,description:Io,classname:"Subject_V1",persistOptsAndResultIbGibs:!1,allowPrimitiveArgs:!0,catchAllErrors:!0,trace:!1},fs=void 0;var _o=class r{static{f(this,"WitnessFactoryBase")}lc=`[${r.name}]`};var bs=!1,Ht=class r extends _o{static{f(this,"DynamicFormFactoryBase")}lc=`[${r.name}]`;patchDataFromItems({data:e,contextPath:t,items:o,pathDelimiter:n}){let s=`${this.lc}[${this.patchDataFromItems.name}]`;try{if(bs&&console.log(`${s} starting...`),!n)throw new Error("pathDelimiter required (E: 958d472a15fb71e45cd2925883f2ec22)");for(let i=0;i<o.length;i++){let a=o[i],c=t?t+n+a.name:a.name;if(!a.items)Vo({obj:e,value:a.value,path:c,logalot:bs,pathDelimiter:n});else if(a.items.length>0)this.patchDataFromItems({data:e,contextPath:c,items:a.items,pathDelimiter:n});else throw new Error("invalid item. items is truthy but with a length of 0. items should either be falsy or have at least one child. (E: ee2765e0b920477f919fcb09e9d951b4)")}}catch(i){throw console.error(`${s} ${i.message}`),i}finally{bs&&console.log(`${s} complete.`)}}};var uc=!1,Kt=class r{static{f(this,"LightWitnessBase_V1")}lc=`[${r.name}]`;instanceId="";ib="";gib;data;rel8ns;initialized;_isInitialized=!1;constructor(e,t){e&&(this.data=e),t&&(this.rel8ns=t),this.initialized=this.initialize().then(()=>{this._isInitialized=!0})}async initialize(){this.instanceId=await F(),this.gib=await V({ibGib:this.toIbGibDto()})}toIbGibDto(){return ve({ibGib:this})}loadIbGibDto(e){let t=`${this.lc}[${this.loadIbGibDto.name}]`;try{return uc&&console.log(`${t} starting...`),e.ib||console.warn(`${t} dto.ib is falsy.`),e.gib||console.warn(`${t} dto.gib is falsy.`),this.ib=C(e.ib),this.gib=C(e.gib),e.data?this.data=C(e.data):delete this.data,e.rel8ns?this.rel8ns=C(e.rel8ns):delete this.rel8ns,Promise.resolve()}catch(o){throw console.error(`${t} ${o.message}`),o}finally{uc&&console.log(`${t} complete.`)}}async validateThis(){let e=`${this.lc}[${this.validateThis.name}]`,t=[];try{this.ib||t.push("this.ib is falsy."),this.gib||t.push("this.gib is falsy.")}catch(o){throw console.error(`${e} ${o.message}`),o}return t}};var pc="subscription",us=/^[a-zA-Z0-9_\-.]{1,255}$/,hc="",gc="subscription",To="subscription is a cool ibgib witness that has seriously fascinating behavior.";var yr={unsubscribe:"unsubscribe",unsubscribed:"unsubscribed"};var ps={version:"1",uuid:hc,name:gc,description:To,classname:"Subscription_V1",persistOptsAndResultIbGibs:!1,allowPrimitiveArgs:!0,catchAllErrors:!1,trace:!1},hs=void 0;var mc=!1;function gs({ibGib:r}){let e=`[${gs.name}]`;try{mc&&console.log(`${e} starting... (I: 3aadb634377acbe42984b61c91975323)`);let{ib:t}=r;return[dc,yo].some(n=>t.includes(n))}catch(t){throw console.error(`${e} ${t.message}`),t}finally{mc&&console.log(`${e} complete.`)}}f(gs,"isObservable");var B=!1,Ao=class r extends Kt{static{f(this,"Subscription_V1")}lc=`[${r.name}]`;metaspace;_subscribed;_unsubscribed;_srcObservable;constructor(e,t){super(e,t)}async initialize(){let e=`${this.lc}[${this.initialize.name}]`;try{if(B&&console.log(`${e} starting... (I: 8097612cda5f43e5b38249d057b65b1e)`),await super.initialize(),!this.data)throw new Error("this.data required (E: 1af73af2d17a48ada42596ad395fd99c)");this.data.uuid=this.instanceId,this.ib=Go({data:this.data,classname:"Subscription_V1"}),this.gib=await V({ibGib:this})}catch(t){throw console.error(`${e} ${t.message}`),t}finally{B&&console.log(`${e} complete.`)}}async witness(e){let t=`${this.lc}[${this.witness.name}]`;try{this._isInitialized||await this.initialized;let{ib:o}=e;if(!o)throw new Error("arg.ib required (E: 1fd9aebef07b4bdaacc0cd323c8ddf76)");if(B&&console.log(`${t} ib: ${o} (I: 4de7771f477dc5b36933343b694ce223)`),o===yr.unsubscribe)return B&&console.log(`${t} routing unsubscribe cmd (I: 5633b86d467af2aa67388abf559a3c23)`),this.witness_unsubscribe();if(o===yr.unsubscribed)return B&&console.log(`${t} routing unsubscribed query (I: 6e0ae61d90f1974d76bcdbb47970e723)`),this.witness_unsubscribed();if(gs({ibGib:e}))return B&&console.log(`${t} routing observerable (I: 165b422cda9ec3052312243dc965cf23)`),this.witness_observable({ibGib:e});throw new Error("unknown arg. expect unsubscribe/unsubscribed primitive ibgib or Observable ibgib. (E: 132dc7cd8f7c4afc9ec4651e2c559c74)")}catch(o){throw console.error(`${t} ${E(o)??"unknown error (E: b0bbaab21833404a9420c3d273df7f21)"}`),o}}async witness_unsubscribe(){let e=`${this.lc}[${this.witness_unsubscribe.name}]`;try{if(B&&console.log(`${e} starting... (I: a3d549220ef24604956aaa2c66fff09b)`),!this._subscribed)return console.warn(`${e} tried to unsubscribe but this._subscribed is ${this._subscribed} (W: cdc94f59447d4011b4b4cc12ef9ec074)`),Z;if(this._unsubscribed)return console.warn("{lc} this._unsubscribed already true. (W: fa287d76cec040e0978a8add5c758093)"),Z;if(!this._srcObservable)throw new Error("(UNEXPECTED) this._subscribed but this._srcObservable falsy? (E: 83687993b7bea299b4ba2438b530a123)");return B&&(console.log(`${e} inspecting srcObservable before src.witness... (I: f15a33d10f1cae3cec6fdbdb32596823)`),console.dir(this._srcObservable)),await this._srcObservable.witness(this),B&&(console.log(`${e} inspecting srcObservable after src.witness... (I: f15a33d10f1cae3cec6fdbdb32596823)`),console.dir(this._srcObservable)),this._subscribed=!1,this._unsubscribed=!0,delete this._srcObservable,B&&console.log(`${e} this._ (I: 7b1bc418a3d32757772391cad7a49523)`),Z}catch(t){throw console.error(`${e} ${t.message}`),t}finally{B&&console.log(`${e} complete.`)}}async witness_observable({ibGib:e}){let t=`${this.lc}[${this.witness_observable.name}]`;try{if(B&&console.log(`${t} starting... (I: faf248f372fc44a7bb0e70492e8284f9)`),this._subscribed!==void 0)throw new Error(`(UNEXPECTED) this._subscribed (${this._subscribed} is not undefined? (E: 09a0e926357676c2c93a173ccbe93923)`);if(this._srcObservable)throw new Error("(UNEXPECTED) this subscription isn't subscribed but this._observable is truthy? (E: acdf5198fb2ff3c8b2db95450bd55b23)");return this._srcObservable=e,B&&console.log(`${t} this._srcObservable set to ibgib with ib: ${e.ib} (I: 4b81d17243f60dfdcc2163fbb55e9223)`),this._subscribed=!0,Z}catch(o){throw console.error(`${t} ${o.message}`),o}finally{B&&console.log(`${t} complete.`)}}async witness_unsubscribed(){let e=`${this.lc}[${this.witness_unsubscribed.name}]`;try{if(B&&console.log(`${e} starting... (I: 1beac551253e4c5694b63e0d36d5d5c0)`),this._subscribed==null)throw new Error("subscription never subscribed in the first place (this._subscribed === undefined) (E: b2c1b21a0e876a4908339a976924b923)");if(this._subscribed&&this._unsubscribed)throw new Error("(UNEXPECTED) both this._subscribed and this._unsubscribed true (E: a967e49de657a43929a74703c656ad23)");let t=this._unsubscribed===!0?on:Ws;return B&&console.log(`${e} result: ${H(t)} (I: b488cf36ce39e006a81d3ad3db5b4a23)`),t}catch(t){throw console.error(`${e} ${t.message}`),t}finally{B&&console.log(`${e} complete.`)}}async unsubscribe(){let e=`${this.lc}[${this.unsubscribe.name}]`;try{B&&console.log(`${e} starting... (I: ef7f3f4787a74fcca65d761880f44594)`);let t=await this.witness(k.primitive({ib:yr.unsubscribe}));if(!t)throw new Error("(UNEXPECTED) unsubscribe returned undefined? (E: 7013193490b94b6880f1049c36577d6f)");if(ze({ibGib:t})){let o=t;throw new Error(`${o.data.raw} (E: fca1200dccb14f84968b2462f1b4c29e)`)}}catch(t){throw console.error(`${e} ${t.message}`),t}finally{B&&console.log(`${e} complete.`)}}async unsubscribed(){let e=`${this.lc}[${this.unsubscribed.name}]`;try{B&&console.log(`${e} starting... (I: 8ee9a93be61647d6aef6a4fa03e96dad)`);let t=await this.witness(k.primitive({ib:yr.unsubscribed}));if(!t)throw new Error("(UNEXPECTED) unsubscribe returned undefined? (E: 5051d7ff4a4d4bf7864c520b53f028d5)");let o=t.ib===on.ib;return B&&console.log(`${e} resUnsubscribed: ${o} (I: b4800166c58d5ba2ca1dccaa53de2323)`),o}catch(t){throw console.error(`${e} ${t.message}`),t}finally{B&&console.log(`${e} complete.`)}}async validateThis(){let e=`${this.lc}[${this.validateThis.name}]`;try{return B&&console.log(`${e} starting...`),this.data,[]}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{B&&console.log(`${e} complete.`)}}async argy({argData:e,ibMetadata:t,noTimestamp:o,ibGibs:n}){let s=await vt({argData:e,ibMetadata:t,noTimestamp:o});return n&&(s.ibGibs=n),s}async resulty({resultData:e,ibGibs:t}){let o=await Dt({resultData:e});return t&&(o.ibGibs=t),o}},So=class r extends Ht{static{f(this,"Subscription_V1_Factory")}lc=`[${r.name}]`;getName(){return Ao.name}async newUp({data:e,rel8ns:t}){let o=`${this.lc}[${this.newUp.name}]`;try{B&&console.log(`${o} starting...`),e??=C(ps),e=e,t=t??hs?C(hs):void 0,e.uuid||=await F();let{classname:n}=e,s=Go({data:e}),i=await Oe({parentPrimitiveIb:`witness ${n}`,ib:s,data:e,rel8ns:t}),a=new Ao(void 0,void 0);return await a.loadIbGibDto(i),B&&console.log(`${o} witnessDto: ${H(i)} (I: 5e41337176d1441f9a5c7b43664d43ef)`),{newIbGib:a}}catch(n){throw console.error(`${o} ${E({error:n})}`),n}finally{B&&console.log(`${o} complete.`)}}async witnessToForm({witness:e}){let t=`${this.lc}[${this.witnessToForm.name}]`;try{B&&console.log(`${t} starting...`);let{data:o}=e;if(!o)throw new Error("(UNEXPECTED) witness.data falsy? (E: ef44497ff97a4e5bac004d52c4ff40eb)");B&&console.log(`${t} data: ${H(o)} (I: c3f4c3d85386461aaefbe33524ff9cbd)`);let n=await Yt({n:100}),s=new xo().with({idPool:n}).name({of:o.name,required:!1}).description({of:o.description??To}).and().and().uuid({of:o.uuid,required:!0}).classname({of:o.classname}).and().commonWitnessFields({data:o}).outputForm({formName:"form",label:"subscription"});return Promise.resolve(s)}catch(o){throw console.error(`${t} ${E({error:o})}`),o}finally{B&&console.log(`${t} complete.`)}}async formToWitness({form:e}){let t=C(ps);return this.patchDataFromItems({data:t,items:e.items,pathDelimiter:Nt}),await this.newUp({data:t})}};var vo=!1;function Ec({data:r}){let e=`[${Ec.name}]`;try{if(vo&&console.log(`${e} starting...`),!r)throw new Error("Subscription Data required (E: 6d1c97931dcab8ea9f3e9b32c794b90c)");let t=[],{name:o,uuid:n,classname:s}=r;return o?o.match(us)||t.push(`name must match regexp: ${us} (E: 21bf77e398d47e9d035376510505eda2)`):t.push("name required."),n?n.match(re)||t.push(`uuid must match regexp: ${re} (E: e53fd08ae69e945b37ed895b864b6bd7)`):t.push("uuid required."),s&&(s.match(Ze)||t.push(`classname must match regexp: ${Ze}`)),t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{vo&&console.log(`${e} complete.`)}}f(Ec,"validateCommonSubscriptionData");function Go({data:r,classname:e}){let t=`[${Go.name}]`;try{let o=Ec({data:r});if(o.length>0)throw new Error(`invalid Subscription data: ${o} (E: fd6b0b32d8f6c4b97eebd489cdb07a4a)`);if(e){if(r.classname&&r.classname!==e)throw new Error("classname does not match data.classname (E: 354285a56a20b9b65b06abfcd9f2e621)")}else if(e=r.classname,!e)throw new Error("classname required (E: 040c1fd71853fa7874146999afb355c3)");let{uuid:n}=r;return`witness ${pc} ${e} ${n}`}catch(o){throw console.error(`${t} ${E(o)}`),o}}f(Go,"getSubscriptionIb");var xo=class r extends it{static{f(this,"SubscriptionFormBuilder")}lc=`[${r.name}]`;constructor(){super(),this.what="subscription"}};function Do({ibGib:r}){let e=`[${Do.name}]`;try{if(vo&&console.log(`${e} starting... (I: 43df7e7f61f25e65662ce8aa5a105a23)`),!r)return!1;let t=r;return typeof t.witness=="function"&&typeof t.unsubscribe=="function"&&typeof t.unsubscribed=="function"}catch(t){throw console.error(`${e} ${t.message}`),t}finally{vo&&console.log(`${e} complete.`)}}f(Do,"isSubscription");async function wc(){return(await new So().newUp({})).newIbGib}f(wc,"newupSubscription");var ms="observable_event";var $c=!1;async function Es({eventType:r,srcObservable:e,payload:t}){let o=`[${Es.name}]`;try{if($c&&console.log(`${o} starting... (I: e2290f2f46d1993d6893a24c19100823)`),!e)throw new Error("srcObservable required (E: 3470a97bbf3802cbc8dd64339f5ef623)");if(!e.data)throw new Error("srcObservable.data required (E: df1786585ba849c08e7f4f1fddd30a31)");if(!e.data.uuid)throw new Error("srcObservable.data.uuid required (E: 173a1a53f274bc1cef879bad2288ca23)");if(!e.data.uuid.match(re))throw new Error(`valid srcObservable.data.uuid required. must pass UUID_REGEXP: ${re.source} (E: 10f4bd1863f18250cc79cd65221da223)`);let n={uuid:await F(),eventType:r,srcObservableId:e.data.uuid,"@srcObservableAddr":_({ibGib:e}),"@payloadAddr":_({ibGib:t})};return await Oe({parentPrimitiveIb:ms,ib:yc({data:n}),data:n})}catch(n){throw console.error(`${o} ${n.message}`),n}finally{$c&&console.log(`${o} complete.`)}}f(Es,"getObservableEventIbGib");function yc({data:r,classname:e}){let t=`[${yc.name}]`;try{if(e){if(r.classname&&r.classname!==e)throw new Error("classname does not match data.classname (E: 523aabc53fb944789202a5f468abd338)")}else if(e=r.classname,!e)throw new Error("classname required (E: d4401ea682894c5fa824b38d4989aa76)");if(!r.uuid)throw new Error("data.uuid required (E: 204cc7c20efd8a55263cdea8b1223e23)");return`${ms} ${e} ${r.uuid}`}catch(o){throw console.error(`${t} ${E(o)}`),o}}f(yc,"getObservableEventIb");var z=!1,Oo=class r extends Kt{static{f(this,"ObservableBase_V1")}lc=`[${r.name}]`;metaspace;_subscribers={};_isComplete=!1;_pastPayloads=[];_pastError;get isCompleteOrErrored(){return this._isComplete||!!this._pastError}get isComplete(){return this._isComplete}get isErrored(){return!!this._pastError}constructor(e,t){super(e,t)}async witness(e){let t=`${this.lc}[${this.witness.name}]`;try{this._isInitialized||await this.initialized;let{ib:o}=e;if(!o)throw new Error("arg.ib required (E: 87659d093b82436ce2f7a87e402a5423)");if(cs({ibGib:e}))return this.witness_cmd({arg:e});if(ls({ibGib:e}))return this.witness_otherWitness({arg:e});throw new Error("unknown arg. expect observable cmd or ibgib witness (E: dc2667cffac5b8d7b1bf2ea737c81a23)")}catch(o){throw console.error(`${t} ${E(o)??"unknown error (E: 3e22bea4c7fb4668bf13d7146b927869)"}`),o}}async witness_cmd({arg:e}){let t=`${this.lc}[${this.witness_cmd.name}]`;try{if(z&&console.log(`${t} starting... (I: 69257fac8328b9de9755fdd237b92723)`),e.data.cmd===ut.subscribe)return this.witness_subscribe_cmd({ibGib:e});throw new Error(`unknown command. must be of type ObservableCmd (${fc}) (E: 5910e5cbafead25ea2917a65a3fc4123)`)}catch(o){throw console.error(`${t} ${o.message}`),o}finally{z&&console.log(`${t} complete.`)}}async witness_otherWitness({arg:e}){let t=`${this.lc}[${this.witness_otherWitness.name}]`;try{return z&&console.log(`${t} starting... (I: 871d0b7a2bef4596bad430f1cbacde02)`),Do({ibGib:e})?this.witness_subscriptionIbGib({arg:e}):this.witness_subscribe_nonCmdWitness({arg:e})}catch(o){throw console.error(`${t} ${o.message}`),o}finally{z&&console.log(`${t} complete.`)}}async witness_subscriptionIbGib({arg:e}){let t=`${this.lc}[${this.witness_subscriptionIbGib.name}]`;try{if(z&&console.log(`${t} starting... (I: 4ac764776ef7e3f9074eb95a999ba423)`),!e.data)throw new Error("arg.data required (E: 764ae772727ceba95a18140fdd938323)");let o=this.getSubscriberKey({subscription:e}),[n,s]=this._subscribers[o];if(e===n)delete this._subscribers[o];else throw new Error("(UNEXPECTED) arg and subscription are two different instances? (E: aab5ef9bdc92abb9e816e2c443ab5723)");return Z}catch(o){throw console.error(`${t} ${o.message}`),o}finally{z&&console.log(`${t} complete.`)}}async replayPastPayloads({observer:e,subscription:t}){let o=`${this.lc}[${this.replayPastPayloads.name}]`;try{z&&console.log(`${o} starting... (I: b3c8f9c76a4af030cf52fdcf01c3fd23)`);let n=this.getSubscriberKey({subscription:t}),s=f(()=>!!this._subscribers[n],"fnStillSubscribed"),i=-1,a=!0;do if(i++,i<this._pastPayloads.length){if(!s()){z&&console.log(`${o} subscription canceled before past payloads dispatch completed. (I: f1778f868446a518030d1cf7800c8a23)`);return}try{let c=this._pastPayloads[i];await e.next(c)}catch{console.error(`${o} observer errored on payload (i: ${i}). aborting replay (E: 1d7efc7c48e1491da4317ef333031077)`);return}}else a=!1;while(a);if(this.isErrored&&e.error&&s())try{await e.error(this._pastError)}catch{console.error(`${o} observer.error(this._pastError) errored itself (E: 18310e5e032345e7bdc3f2479807866c)`)}else if(this.isComplete&&e.complete&&s())try{await e.complete()}catch{console.error(`${o} observer.complete errored (E: d9d027f5520f4d7eadfc669d66b5b550)`)}}catch(n){throw console.error(`${o} ${n.message}`),n}finally{z&&console.log(`${o} complete.`)}}async witness_subscribe_cmd({ibGib:e}){let t=`${this.lc}[${this.witness_subscribe_cmd.name}]`;try{if(z&&console.log(`${t} starting... (I: 0c4c75c3fae297af6449c1048ce55423)`),(e.ibGibs??[]).length!==1)throw new Error("ibGib.ibGibs required. should contain one ObserverWitness (E: 3ed99b32e22284573c497df788a9f923)");let o=e.ibGibs[0],n=await wc();return z&&console.log(`${t} subscription created (I: 89ccd97803c66292f9d7334e1e2de523)`),await n.witness(this),await n.initialized,z&&console.log(`${t} subscription initialized (after witnessing this observable as its src). (I: 3021483402b21c4df64a9173bd223a23)`),this._subscribers[this.getSubscriberKey({subscription:n})]=[n,o],z&&console.log(`${t} stored subscriber (subscription, observer) (I: fb09660d885e33b80188dd0386ffc723)`),this.data.replay&&this._pastPayloads.length>0&&this.replayPastPayloads({observer:o,subscription:n}),n}catch(o){throw console.error(`${t} ${o.message}`),o}finally{z&&console.log(`${t} complete.`)}}async witness_subscribe_nonCmdWitness({arg:e}){let t=`${this.lc}[${this.witness_subscribe_nonCmdWitness.name}]`;try{throw z&&console.log(`${t} starting... (I: d9571dfcab4247d594c838233971886a)`),new Error("not impl (E: 76219cf238ba4f849480bd7c82eefab9)")}catch(o){throw console.error(`${t} ${o.message}`),o}finally{z&&console.log(`${t} complete.`)}}async subscribe(e){let t=`${this.lc}[${this.subscribe.name}]`;try{z&&console.log(`${t} starting... (I: 0dec9a06c562711e19482d45a7075e23)`);let o;if(Ot({ibGib:e})){let n=await this.argy({argData:{cmd:ut.subscribe,ibGibAddrs:[_({ibGib:e})]},ibGibs:[e]});o=await this.witness(n)}else o=await this.witness(e);if(!Do({ibGib:o}))throw new Error("(UNEXPECTED) resSubscription is not a SubscriptionWitness? (E: c29bec4e3a48d6f1299143399ac55a23)");return o}catch(o){throw console.error(`${t} ${o.message}`),o}finally{z&&console.log(`${t} complete.`)}}getSubscriberKey({subscription:e}){if(e.data?.uuid)return e.data.uuid;throw new Error("(UNEXPECTED) subscription.data.uuid falsy? (E: 8d078e6f8155f7567fd9378557e91823)")}async dispatchToEachSubscriber({payload:e,fnForObserver:t,observableEventType:o}){let n=`${this.lc}[${this.dispatchToEachSubscriber.name}]`;try{z&&console.log(`${n} starting... (I: 0b990ce892f689d14458565717e66a23)`);let s=Object.values(this._subscribers);for(let i=0;i<s.length;i++){let[a,c]=s[i];if(Ot({ibGib:c})){let l=c;await t(l,e),l.complete?await a.unsubscribed()?console.warn(`${n} (UNEXPECTED) subscriber reference still held but is unsubscribed? skipping for now (i.e. won't remove subscriber) in case that code is in yielded execution and just hasn't gotten around to it with event loop (but that would be weird). (W: 1d98f35d2fdd4345954c947265d9fb85)`):await l.complete():z&&console.log(`${n} no error handler for observer. skipping. (I: 6a8a52c2012c464790eb406d2ae0383f)`)}else{let l=await Es({eventType:o,srcObservable:this,payload:e});await c.witness(l)}}}catch(s){throw console.error(`${n} ${s.message}`),s}finally{z&&console.log(`${n} complete.`)}}async validateThis(){let e=`${this.lc}[${this.validateThis.name}]`;try{return z&&console.log(`${e} starting...`),this.data,[]}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{z&&console.log(`${e} complete.`)}}async argy({argData:e,ibMetadata:t,noTimestamp:o,ibGibs:n}){let s=await vt({argData:e,ibMetadata:t,noTimestamp:o});return n&&(s.ibGibs=n),s}async resulty({resultData:e,ibGibs:t}){let o=await Dt({resultData:e});return t&&(o.ibGibs=t),o}};var j=!1,No=class r extends Oo{static{f(this,"Subject_V1")}lc=`[${r.name}]`;constructor(e,t){super(e,t)}asObservable(){return this}async subscribe(e){let t=`${this.lc}[${this.subscribe.name}]`;try{j&&console.log(`${t} starting... (I: 8e47b752314870ec78eb14342621f723)`);let o=await this.argy({argData:{cmd:pt.subscribe,ibGibAddrs:[_({ibGib:e})]},ibGibs:[e]});return await this.witness(o)}catch(o){throw console.error(`${t} ${o.message}`),o}finally{j&&console.log(`${t} complete.`)}}async next(e){let t=`${this.lc}[${this.next.name}]`;try{j&&console.log(`${t} starting... (I: b30363827c56450ca918c69aa15b0046)`);let o=await this.argy({argData:{cmd:pt.next,ibGibAddrs:[_({ibGib:e})]},ibGibs:[e]});await this.witness(o)}catch(o){throw console.error(`${t} ${o.message}`),o}finally{j&&console.log(`${t} complete.`)}}async error(e){let t=`${this.lc}[${this.error.name}]`;try{j&&console.log(`${t} starting... (I: 7fcc30e3763c429ea8b212491ad9455a)`);let o;if(typeof e=="string")o=await xt({rawMsg:e});else if(e instanceof Error||typeof e.message=="string")o=await xt({rawMsg:E(e)});else if(e.ib&&ze({ibGib:e}))o=e;else throw new Error("unknown error type. shold either be ErrorIbGib_V1 or an Error instance or have error.message string property. (E: 2cfcab85439c3c845bfe18e8ecde3523)");let n=await this.argy({argData:{cmd:pt.error,ibGibAddrs:[_({ibGib:o})]},ibGibs:[o]});await this.witness(n)}catch(o){throw console.error(`${t} ${o.message}`),o}finally{j&&console.log(`${t} complete.`)}}async complete(){let e=`${this.lc}[${this.complete.name}]`;try{j&&console.log(`${e} starting... (I: 5faaf13c6b0543d399815c03b9cdf80c)`);let t=await this.argy({argData:{cmd:pt.complete}});await this.witness(t)}catch(t){throw console.error(`${e} ${t.message}`),t}finally{j&&console.log(`${e} complete.`)}}async witness_cmd({arg:e}){let t=`${this.lc}[${this.witness_cmd.name}]`;try{j&&console.log(`${t} starting... (I: 2bf7cbcadba446fa92cb649906b2b260)`);let{cmd:o}=e.data;switch(o){case pt.next:return this.witness_next({ibGib:e});case pt.error:return this.witness_error({ibGib:e});case pt.complete:return this.witness_complete({ibGib:e});default:return super.witness_cmd({arg:e})}}catch(o){throw console.error(`${t} ${o.message}`),o}finally{j&&console.log(`${t} complete.`)}}async witness_next({ibGib:e}){let t=`${this.lc}[${this.witness_next.name}]`;try{if(j&&console.log(`${t} starting... (I: 600da780f13f5137a2f76aad344b2923)`),this.isCompleteOrErrored)return j&&console.log(`${t} this.isCompleteOrErrored is true. returning early without producing. (I: aa823831853b134b19657c8673838c23)`),Z;if((e.ibGibs??[]).length!==1)throw new Error("ibGib.ibGibs required. should contain one payload ibgib (E: 4046802ff96d4adfafcee7a74d96af5e)");let o=e.ibGibs[0];this.data.replay&&this._pastPayloads.push(o);let n=Object.values(this._subscribers);for(let s=0;s<n.length;s++){let[i,a]=n[s];if(j&&console.log(`${t} ensuring subscription not unsubscribed (I: ade3fd6d6ff2b5ec69eb8143e32ce223)`),!await i.unsubscribed())j&&console.log(`${t} subscription still active (I: b9ab83b28acecf0d823fdba46a81dc23)`),await a.next(o);else{debugger;console.warn(`${t} (UNEXPECTED) subscriber reference still held but is unsubscribed? skipping for now (i.e. won't remove subscriber) in case that code is in yielded execution and just hasn't gotten around to it with event loop (but that would be weird). (W: c116e799f6b9483c97fd030eb0dd09ea)`)}}return Z}catch(o){throw console.error(`${t} ${o.message}`),o}finally{j&&console.log(`${t} complete.`)}}async witness_error({ibGib:e}){let t=`${this.lc}[${this.witness_error.name}]`;try{if(j&&console.log(`${t} starting... (I: 3367a73bc83c47f98d9ecfe426dc300e)`),(e.ibGibs??[]).length!==1)throw new Error("ibGib.ibGibs required. should contain one error ibgib (E: 905474b45bcb4f0abe7bd4618f08f32c)");let o=e.ibGibs[0];this._pastError=o;let n=Object.values(this._subscribers);for(let s=0;s<n.length;s++){let[i,a]=n[s];if(Ot({ibGib:a})){let c=a;c.error?await i.unsubscribed()?console.warn(`${t} (UNEXPECTED) subscriber reference still held but is unsubscribed? skipping for now (i.e. won't remove subscriber) in case that code is in yielded execution and just hasn't gotten around to it with event loop (but that would be weird). (W: 8946e97f00fd4146a470064b490a4c29)`):await c.error(o):j&&console.log(`${t} no error handler for observer. skipping. (I: 59f4a1ee59a3a27d523d60cd761be923)`)}else await a.witness(o)}return Z}catch(o){throw console.error(`${t} ${o.message}`),o}finally{j&&console.log(`${t} complete.`)}}async witness_complete({ibGib:e}){let t=`${this.lc}[${this.witness_complete.name}]`;try{j&&console.log(`${t} starting... (I: 4db180f465e24df9a4ded37fbd235558)`),this._isComplete=!0;let o=Object.values(this._subscribers);for(let n=0;n<o.length;n++){let[s,i]=o[n];if(Ot({ibGib:i})){let a=i;a.complete?await s.unsubscribed()?console.warn(`${t} (UNEXPECTED) subscriber reference still held but is unsubscribed? skipping for now (i.e. won't remove subscriber) in case that code is in yielded execution and just hasn't gotten around to it with event loop (but that would be weird). (W: 1d98f35d2fdd4345954c947265d9fb85)`):await a.complete():j&&console.log(`${t} no error handler for observer. skipping. (I: 6a8a52c2012c464790eb406d2ae0383f)`)}else await i.witness(e)}return Z}catch(o){throw console.error(`${t} ${o.message}`),o}finally{j&&console.log(`${t} complete.`)}}async validateThis(){let e=`${this.lc}[${this.validateThis.name}]`;try{return j&&console.log(`${e} starting...`),this.data,[]}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{j&&console.log(`${e} complete.`)}}async argy({argData:e,ibMetadata:t,noTimestamp:o,ibGibs:n}){if(e.cmd===ut.subscribe)return super.argy({argData:e,ibMetadata:t,noTimestamp:o,ibGibs:n});{let s=await vt({argData:e,ibMetadata:t,noTimestamp:o});return n&&(s.ibGibs=n),s}}async resulty({resultData:e,ibGibs:t}){let o=await Dt({resultData:e});return t&&(o.ibGibs=t),o}},Co=class r extends Ht{static{f(this,"Subject_V1_Factory")}lc=`[${r.name}]`;getName(){return No.name}async newUp({data:e,rel8ns:t}){let o=`${this.lc}[${this.newUp.name}]`;try{j&&console.log(`${o} starting...`),e??=C($r),e=e,t=t??fs?C(fs):void 0,e.uuid||=await F();let{classname:n}=e,s=ws({data:e}),i=await Oe({parentPrimitiveIb:`witness ${n}`,ib:s,data:e,rel8ns:t}),a=new No(void 0,void 0);return await a.loadIbGibDto(i),j&&console.log(`${o} witnessDto: ${H(i)} (I: 6736d2b2ddf44fef9a1eb27078dfbf23)`),{newIbGib:a}}catch(n){throw console.error(`${o} ${E({error:n})}`),n}finally{j&&console.log(`${o} complete.`)}}async witnessToForm({witness:e}){let t=`${this.lc}[${this.witnessToForm.name}]`;try{j&&console.log(`${t} starting...`);let{data:o}=e;if(!o)throw new Error("(UNEXPECTED) witness.data falsy? (E: 7b70c96e982d4f81b6ffda54da16b3b8)");j&&console.log(`${t} data: ${H(o)} (I: 75abef56f5004a94b2113e3b1461ac25)`);let n=await Yt({n:100}),s=new Po().with({idPool:n}).name({of:o.name,required:!1}).description({of:o.description??Io}).and().and().uuid({of:o.uuid,required:!0}).classname({of:o.classname}).and().commonWitnessFields({data:o}).outputForm({formName:"form",label:"observable"});return Promise.resolve(s)}catch(o){throw console.error(`${t} ${E({error:o})}`),o}finally{j&&console.log(`${t} complete.`)}}async formToWitness({form:e}){let t=C($r);return this.patchDataFromItems({data:t,items:e.items,pathDelimiter:Nt}),await this.newUp({data:t})}};var Lo=!1;function Ic({data:r}){let e=`[${Ic.name}]`;try{if(Lo&&console.log(`${e} starting...`),!r)throw new Error("Subject Data required (E: 207a82725648e2ef234c8bd3fa1a5312)");let t=[],{name:o,uuid:n,classname:s}=r;return o?o.match(ds)||t.push(`name must match regexp: ${ds} (E: de987eb8fea0b6232f60abf31815095c)`):t.push("name required."),n?n.match(re)||t.push(`uuid must match regexp: ${re} (E: 1a6dfda91ad51696f7456bc84dfea60e)`):t.push("uuid required."),s&&(s.match(Ze)||t.push(`classname must match regexp: ${Ze}`)),t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Lo&&console.log(`${e} complete.`)}}f(Ic,"validateCommonSubjectData");function ws({data:r,classname:e}){let t=`[${ws.name}]`;try{let o=Ic({data:r});if(o.length>0)throw new Error(`invalid Subject data: ${o} (E: 55620ac1f17e30a30a92850219f894ac)`);if(e){if(r.classname&&r.classname!==e)throw new Error("classname does not match data.classname (E: 20e86cca70130839a49ad011c9a7aafa)")}else if(e=r.classname,!e)throw new Error("classname required (E: 74e29ae0f618fee7e7ef72a30c654a6c)");let{name:n,uuid:s}=r;return`witness ${yo} ${e} ${n} ${s}`}catch(o){throw console.error(`${t} ${E(o)}`),o}}f(ws,"getSubjectIb");var Po=class r extends it{static{f(this,"SubjectFormBuilder")}lc=`[${r.name}]`;constructor(){super(),this.what="subject"}};function Ot({ibGib:r}){let e=`[${Ot.name}]`;try{return Lo&&console.log(`${e} starting... (I: b54c252104f710c12951aa43b6ead323)`),typeof r.next=="function"}catch(t){throw console.error(`${e} ${t.message}`),t}finally{Lo&&console.log(`${e} complete.`)}}f(Ot,"isObserver");async function p$({data:r,replay:e}={}){let t=new Co;return r??=C($r),e&&(r.replay=!0),(await t.newUp({data:r})).newIbGib}f(p$,"newupSubject");var Ro="anon_fn",_c={fnHash:""};var Tc=!1;function $s({data:r}){let e=`[${$s.name}]`;try{if(Tc&&console.log(`${e} starting... (I: 37bb06e0390c5bcadf04501727d64923)`),!r?.fnHash)throw new Error("data.fnHash required (E: 2e560f2c59822bc5ba024d4a8e99d323)");return`witness ${Ro} ${r.fnHash}`}catch(t){throw console.error(`${e} ${t.message}`),t}finally{Tc&&console.log(`${e} complete.`)}}f($s,"getAnonymousFnIb");var ht=class{static{f(this,"AnonymousFnWitness_V1")}fn;ib=Ro.concat();gib=U;data=C(_c);rel8ns;constructor(e){if(this.fn=e,!e)throw new Error("fn required (E: b1e1478f466a2a347b75e7c336f8d323)")}async witness(e){return this.data.fnHash=await X({s:this.fn.toString()}),this.ib=$s({data:this.data}),this.gib=await V({ibGib:this}),this.fn(e)}};var Uo=!1;function Nd({err:r}){let e=`[${Nd.name}]`;try{if(Uo&&console.log(`${e} starting... (I: 96f8b767c50f24768ced7beebb291723)`),On(r)){let t=r;if(!r.data)throw new Error("err isIbGib but err.data is false. (E: 151a6bab647c638c454fd277ac468f23)");if(ze({ibGib:r}))return r.data.raw;throw new Error("(UNEXPECTED) err isIbGib but not ErrorIbGib_V1? (E: 81c2283fad5db3485c6e9acedbda9723)")}else return E(r)}catch(t){throw console.error(`${e} ${t.message}`),t}finally{Uo&&console.log(`${e} complete.`)}}f(Nd,"extractObsErrMsg");function Cd(r){let e=`[${Cd.name}]`;try{Uo&&console.log(`${e} starting... (I: 3d2c3658a0fda83ece1f2b095a365823)`);let t;if(typeof r=="function"?t={next:r}:t=r,!t.next)throw new Error("observer.next required (typeof observerOrFn !== 'function') (E: da944e93b32ab5918f11751bcd651823)");let o=f(async d=>(await t.next(d),Z),"fnNext"),n=f(async d=>(d.ib==="complete"?t.complete&&await t.complete():ze({ibGib:d})?t.error&&await t.error(d):await t.next(d),Z),"fnWitness"),s=new ht(o),i=new ht(n),a={ib:"observer",witness:f(async d=>await i.witness(d),"witness"),next:f(async d=>{await s.witness(d)},"next")},c=t.error??(async d=>{let u;if(typeof d=="string")u=E(d);else if(d.ib)if(ze({ibGib:d}))u=E(d.data.raw);else throw new Error(`${e} (UNEXPECTED) first off, observer.error is falsy. secondly, error came down pipeline and has an "ib" property but is not an ErrorIbGib_V1? (E: 0a2a46b9620b4a6a84c7ba1100da537b)`);else d instanceof Error?u=E(d):typeof d.message=="string"?u=E(d.message):u="[unknown thing came down pipe that ain't an error]";console.error(`Error occurred but observer.error is falsy. error: ${u} (E: 822c60c7c4d542efacd5c2dea7e88062)`)}),l=new ht(async d=>(c(d),Z));if(a.error=async d=>{typeof d=="string"?d=await xt({rawMsg:d}):d instanceof Error&&(d=await xt({rawMsg:d.message}));try{await l.witness(d)}catch{t.error?console.error(`${e} there was another error when executing errorAnonFnWitness.witness (wrapper of caller's observer.error) trapping this. (E: 8fa3c4e633df4491a82951e3b677d9a9)`):console.error(`${e} there was another error when executing errorAnonFnWitness.witness (caller's observer.error was falsy). trapping this. (E: f5ff2db0d762487287139a4175eb7689)`)}},t.complete){let d=t.complete,u=new ht(async b=>(await d(),Z));a.complete=async()=>{try{await u.witness(Z)}catch(b){console.error(`${e} there was an error when executing completeAnonFnWitness (wrapper for observer.complete fn) error: ${E(b)} (E: c9e61b08429e42c1b85d2215f735ba2f)`)}}}return a}catch(t){throw console.error(`${e} ${t.message}`),t}finally{Uo&&console.log(`${e} complete.`)}}f(Cd,"fnObs");var Ir=!1,Ac=class r{static{f(this,"WitnessBase_V1")}lc=`[${r.name}]`;set trace(e){let t=`${this.lc}[set trace]`;e!==(this.data?.trace||!1)&&(this.data?(this.data.trace=e,delete this.gib):console.warn(`${t} data is falsy. Can't set.`))}get trace(){return this.data?.trace??!1}set catchAllErrors(e){let t=`${this.lc}[set catchAllErrors]`;e!==this.data?.catchAllErrors&&(this.data?(this.data.catchAllErrors=e,delete this.gib):console.error(`${t} data is falsy. Can't set value.`))}get catchAllErrors(){let e=`${this.lc}[catchAllErrors]`,t=this.data?.catchAllErrors||!1;return(Ir||this.trace)&&console.log(`${e} result: ${t}`),t}ib="";gib;data;rel8ns;initialized;constructor(e,t){e&&(this.data=e),t&&(this.rel8ns=t),this.initialized=this.initialize()}initialize(){return Promise.resolve()}toIbGibDto(){return ve({ibGib:this})}loadIbGibDto(e){let t=`${this.lc}[${this.loadIbGibDto.name}]`;try{return Ir&&console.log(`${t} starting...`),e.ib||console.warn(`${t} dto.ib is falsy.`),e.gib||console.warn(`${t} dto.gib is falsy.`),this.ib=C(e.ib),this.gib=C(e.gib),e.data?this.data=C(e.data):delete this.data,e.rel8ns?this.rel8ns=C(e.rel8ns):delete this.rel8ns,Promise.resolve()}catch(o){throw console.error(`${t} ${o.message}`),o}finally{Ir&&console.log(`${t} complete.`)}}async witness(e){let t=`${this.lc}[${this.witness.name}]`;try{await this.initialized,this.gib||(this.gib=await Re(this.toIbGibDto()));let o=await this.validateThis();if(o?.length>0){for(let i of o)console.error(`${t} ${i}`);throw new Error("internal witness validation failed. See `WitnessBase_V1.validateThis` (E: 2b5f73cadbfa416ba189346f3c31cd0c)")}let n=await this.validateWitnessArg(e);if(n?.length>0){for(let i of n)console.error(`${t} ${i}`);throw new Error("arg validation failed. See `WitnessBase_V1.validateWitnessArg` (E: 51531a1d928a485e8ffc277145ec44e9)")}(Ir||this.trace)&&console.log(`${t} addr: ${_(e)}`),Ir&&console.log(`${t} addr: ${_(e)} (I: f4cf13a44c4e4fc3903f14018e616c64)`);let s=await this.witnessImpl(e);return this.data?.persistOptsAndResultIbGibs&&await this.persistOptsAndResultIbGibs({arg:e,result:s}),s}catch(o){if(console.error(`${t} ${o.message||"unknown error (E: 3e22bea4c7fb4668bf13d7146b927869)"}`),this.catchAllErrors)return;throw o}}async validateWitnessArg(e){let t=`${this.lc}[${this.validateWitnessArg.name}]`;try{let o=[];e||o.push("arg required (E: a222db3b668e4bb09cfd82e75c07bfa6)");let n=rt({ib:e?.ib});(n?.length??!1)&&o.push(`invalid arg.ib (E: 2ae362ef274d4c3bb9716800f2106d28) errors: ${n.join(`
23
+ `)}`);let s=et({gib:e?.gib});(s?.length??!1)&&o.push(`invalid arg.gib (E: 73be275058084d768a39299337f2ce34) errors: ${s.join(`
24
+ `)}`);let i=await se({ibGib:e});return i?.length??!1?o.push(`arg ibgib invalid intrinsically (E: 73be275058084d768a39299337f2ce34) errors: ${i.join(`
25
+ `)}`):this.data?.allowPrimitiveArgs||ne({gib:e.gib}).isPrimitive&&o.push('arg is primitive (i.e. gib === "gib") and witness.data.allowPrimitiveArgs is falsy. (E: d0aa3d7ad4f54b01bd0023300d15ecd9)'),o}catch(o){throw console.error(`${t} ${o.message}`),o}}async validateThis(){let e=`${this.lc}[${this.validateThis.name}]`,t=[];try{this.ib||t.push("this.ib is falsy."),this.gib||t.push("this.gib is falsy.")}catch(o){throw console.error(`${e} ${o.message}`),o}return t}persistOptsAndResultIbGibs({arg:e,result:t}){let o=`${this.lc}[${this.persistOptsAndResultIbGibs.name}]`;return console.warn(`${o} not implemented in this base class. Override this in descendent class. (W: 087514e851704322a4ec8069a73ce944)`),Promise.resolve()}};function Pd(r){return r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}f(Pd,"escapeHtml");function ko(r){return pe({text:r,length:20,replaceMap:{" ":"-"}}).toLowerCase()}f(ko,"slugify");function gt(r,e){let t=e?.linkTarget??"_blank",o=e?.linkRel??"noopener",n=t?` target="${t}"`:"",s=o?` rel="${o}"`:"",i=Pd(r);return i=i.replace(/`([^`]+)`/g,"<code>$1</code>"),i=i.replace(/\$([^\$]+)\$/g,'<code class="math">$1</code>'),i=i.replace(/\*\*(.*?)\*\*/g,"<strong>$1</strong>"),i=i.replace(/__(.*?)__/g,"<strong>$1</strong>"),i=i.replace(/\*(.*?)\*/g,"<em>$1</em>"),i=i.replace(/_([^_]+)_/g,"<em>$1</em>"),i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(a,c,l)=>{let d=l.startsWith("#");return`<a href="${l}"${d?"":n}${d?"":s}>${c}</a>`}),i}f(gt,"formatInlineMarkdown");function Ld(r){switch(r.toUpperCase()){case"WARNING":return"\u26A0\uFE0F";case"IMPORTANT":return"\u2139\uFE0F";case"NOTE":return"\u{1F4CC}";case"CAUTION":return"\u{1F6D1}";case"TIP":return"\u{1F4A1}";default:return"\u2139\uFE0F"}}f(Ld,"getAlertEmoji");function Y$(r,e){let t=r.split(`
26
+ `),o=[],n=!1,s=null,i=!1,a="",c=[],l=f(()=>{n&&s&&(o.push(`</${s}>`),n=!1,s=null)},"closeList"),d=f(()=>{if(i){let u=c.map(b=>gt(b,e)).join("<br>");o.push(`<div class="alert-box alert-${a.toLowerCase()}"><div class="alert-icon">${Ld(a)}</div><div class="alert-body">${u}</div></div>`),i=!1,a="",c=[]}},"closeAlert");for(let u=0;u<t.length;u++){let b=t[u];if(b.startsWith("> [!")){l(),d();let h=b.match(/> \[!([A-Z]+)\]/);a=h?h[1]:"NOTE",i=!0,c=[];continue}else if(i&&b.startsWith(">")){c.push(b.replace(/^>\s?/,""));continue}else i&&!b.startsWith(">")&&d();if(b.trim()==="---"||b.trim()==="***"){l(),o.push('<hr class="divider">');continue}if(b.startsWith("# ")){l();let h=b.substring(2),g=ko(h);o.push(`<h1 id="${g}" class="policy-title">${gt(h,e)}</h1>`);continue}if(b.startsWith("## ")){l();let h=b.substring(3),g=ko(h);o.push(`<h2 id="${g}" class="policy-h2">${gt(h,e)}</h2>`);continue}if(b.startsWith("### ")){l();let h=b.substring(4),g=ko(h);o.push(`<h3 id="${g}" class="policy-h3">${gt(h,e)}</h3>`);continue}if(b.startsWith("#### ")){l();let h=b.substring(5),g=ko(h);o.push(`<h4 id="${g}" class="policy-h4">${gt(h,e)}</h4>`);continue}if(b.trim().startsWith("* ")||b.trim().startsWith("- ")){(!n||s!=="ul")&&(l(),o.push("<ul>"),n=!0,s="ul");let h=b.trim().replace(/^[\*\-]\s+/,"");o.push(`<li>${gt(h,e)}</li>`);continue}let p=b.trim().match(/^(\d+)\.\s+(.*)/);if(p){(!n||s!=="ol")&&(l(),o.push("<ol>"),n=!0,s="ol"),o.push(`<li>${gt(p[2],e)}</li>`);continue}if(b.trim()===""){l();continue}l(),o.push(`<p>${gt(b,e)}</p>`)}return l(),d(),o.join(`
27
+ `)}f(Y$,"convertMarkdownToHtml");export{f as a,re as b,we as c,C as d,Ae as e,X as f,F as g,H as h,de as i,E as j,qo as k,$e as l,Xt as m,pe as n,xs as o,Oc as p,Lt as q,U as r,Z as s,oe as t,Ue as u,Ps as v,_ as w,R as x,Y as y,Rc as z,te as A,V as B,ne as C,Fe as D,ye as E,se as F,tt as G,k as H,Xf as I,Yf as J,Wf as K,Dr as L,Uc as M,Ms as N,Bs as O,fb as P,bb as Q,ub as R,kc as S,pb as T,hb as U,Nr as V,tn as W,Mc as X,Tb as Y,Lr as Z,ot as _,Rr as $,ti as aa,Ur as ba,Fc as ca,qc as da,Fu as ea,qu as fa,Hu as ga,Ku as ha,Vu as ia,Xu as ja,Wc as ka,zc as la,ii as ma,un as na,Zc as oa,Qc as pa,Ut as qa,tr as ra,pi as sa,cl as ta,mi as ua,Pp as va,Up as wa,ie as xa,yn as ya,In as za,Q as Aa,ll as Ba,Xr as Ca,Yr as Da,fe as Ea,_n as Fa,wi as Ga,Ge as Ha,Rt as Ia,$n as Ja,Ii as Ka,fl as La,Ne as Ma,sr as Na,bl as Oa,Ci as Pa,Pi as Qa,ul as Ra,pl as Sa,hl as Ta,Ce as Ua,dh as Va,gl as Wa,ml as Xa,Wr as Ya,_e as Za,El as _a,wl as $a,$l as ab,Ah as bb,yl as cb,Dn as db,Il as eb,Oe as fb,Sh as gb,Gh as hb,Li as ib,or as jb,Jr as kb,ar as lb,Ri as mb,he as nb,ve as ob,On as pb,rr as qb,Nn as rb,ki as sb,Tl as tb,at as ub,Uh as vb,vl as wb,kh as xb,Mh as yb,Bh as zb,jh as Ab,Mi as Bb,Ch as Cb,ng as Db,sg as Eb,ig as Fb,ag as Gb,cg as Hb,lg as Ib,dg as Jb,fg as Kb,bg as Lb,ug as Mb,pg as Nb,yt as Ob,Ol as Pb,Nl as Qb,Cl as Rb,It as Sb,Ji as Tb,Pl as Ub,Un as Vb,Ul as Wb,je as Xb,Te as Yb,dr as Zb,Bn as _b,jn as $b,ce as ac,ro as bc,ra as cc,fr as dc,Yl as ec,Wl as fc,rm as gc,om as hc,ma as ic,ur as jc,Tt as kc,pr as lc,nd as mc,sd as nc,id as oc,nE as pc,bo as qc,po as rc,ct as sc,Gt as tc,Ua as uc,dd as vc,ka as wc,AE as xc,Ft as yc,Ha as zc,wr as Ac,zn as Bc,LE as Cc,RE as Dc,UE as Ec,Jn as Fc,Eo as Gc,HE as Hc,Zn as Ic,KE as Jc,Ya as Kc,Xa as Lc,bd as Mc,ud as Nc,pd as Oc,hd as Pc,gd as Qc,md as Rc,aw as Sc,go as Tc,mo as Uc,Ed as Vc,es as Wc,lr as Xc,kt as Yc,wd as Zc,$d as _c,Bi as $c,yd as ad,Za as bd,Iw as cd,Id as dd,_d as ed,os as fd,Td as gd,Ad as hd,ec as id,Sd as jd,ss as kd,Bw as ld,jw as md,xt as nd,Nd as od,Cd as pd,Ac as qd,sc as rd,xd as sd,vd as td,Dd as ud,Od as vd,vt as wd,Dt as xd,cs as yd,Kt as zd,p$ as Ad,Y$ as Bd};