@ibgib/space-gib 0.0.18 → 0.0.19

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,18 @@
1
+ var ja=Object.defineProperty;var f=(r,e)=>ja(r,"name",{value:e,configurable:!0});var Q=/^[a-zA-Z0-9_\-.]{1,256}$/,Ye=/^[a-zA-Z0-9_]{1,255}$/,zn=/^(\[.+\])?\s?(\(UNEXPECTED\)|\(unexpected\))?(.+)(\([EIWeiw]: [a-fA-F\d]{32}\))(\(UNEXPECTED\)|\(unexpected\))?$/,Jn=/^(\[.+\]).+$/,Zn=/^[0-9a-fA-F]{32}$/,Qn=/^[0-9a-fA-F]{64}$/;var yt="/",es="_nonalphanumerics_";var It=!1,yo=globalThis.crypto,{subtle:Fa}=yo,ge={sha_256:"SHA-256",sha_512:"SHA-512"};function O(r){return JSON.parse(JSON.stringify(r))}f(O,"clone");function ve(r){return(r??new Date).toUTCString()}f(ve,"getTimestamp");var qa=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(ge);if(!t.includes(e))throw new Error(`Only ${t} implemented (E: 73cb52cd4d7f70c3415fdf695ba6ba23)`);let o=new TextEncoder().encode(r),n=await Fa.digest(e,o),s=new Uint8Array(n),i="";for(let a=0;a<s.length;a++)i+=qa[s[a]];return i}catch(t){throw console.error(E(t.message)),t}}f(X,"hash");async function k(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=yo.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=yo.randomUUID();e=await X({s:t})}if(!e)throw new Error("(UNEXPECTED) uuid falsy? could not create uuid? (E: 5276bcc4e8f75aa2c82a54a8c8b2d626)");return e}f(k,"getUUID");function H(r){return JSON.stringify(r,null,2)}f(H,"pretty");async function le(r){return new Promise(e=>{setTimeout(()=>{e()},r)})}f(le,"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 Io({items:r,keyFn:e}){let t=`[${Io.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(Io,"groupBy");function lr({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(lr,"getRegExp");function me(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(me,"getTimestampInTicks");function _o({startDate:r,years:e,months:t,days:o,hours:n,seconds:s}){let i=`[${_o.name}]`;try{return lt({startDate:r,years:e,months:t,days:o,hours:n,seconds:s}).toUTCString()}catch(a){throw console.log(`${i} ${a.message}`),a}}f(_o,"getExpirationUTCString");function lt({startDate:r,years:e,months:t,days:o,hours:n,seconds:s}){let i=`[${lt.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),lt({startDate:new Date(c),months:t,days:o,hours:n,seconds:s})):t?(a=r.getMonth()+t,c=r.setMonth(a),lt({startDate:new Date(c),years:e,days:o,hours:n,seconds:s})):o?(a=r.getDate()+o,c=r.setDate(a),lt({startDate:new Date(c),years:e,months:t,hours:n,seconds:s})):n?(a=r.getHours()+n,c=r.setHours(a),lt({startDate:new Date(c),years:e,months:t,days:o,seconds:s})):s?(a=r.getSeconds()+s,c=r.setSeconds(a),lt({startDate:new Date(c),years:e,months:t,days:o,hours:n})):r}catch(a){throw console.log(`${i} ${a.message}`),a}}f(lt,"addTimeToDate");function To({expirationTimestampUTC:r}){let e=`[${To.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(To,"isExpired");function dr(r){return Array.from(new Set(r))}f(dr,"unique");function Ao({obj:r,value:e,path:t,pathDelimiter:o,logalot:n}){let s=`[${Ao.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||yt;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(Ao,"patchObject");async function Ut({n:r}){let e=`[${Ut.name}]`;try{It&&console.log(`${e} starting...`);let t=[];for(let o=0;o<r;o++){let n=await k();t.push(n.substring(0,16))}return t}catch(t){throw console.error(`${e} ${t.message}`),t}finally{It&&console.log(`${e} complete.`)}}f(Ut,"getIdPool");function Ha({text:r,length:e,keepLiterals:t=["-"],replaceMap:o}){let n=`[${Ha.name}]`;try{if(It&&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=ts({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&&(It&&console.log(`${n} curtailing length (I: d7a28e05daa5979c7686b4c1cf519b23)`),s=s.substring(0,e)),s.length===0&&(s=es),s}catch(s){throw console.error(`${n} ${s.message}`),s}finally{It&&console.log(`${n} complete.`)}}f(Ha,"getSaferSubstring");function Ka({x:r}){if((r??[]).length===0)return;let e=Math.floor(Math.random()*r.length);return r[e]}f(Ka,"pickRandom");function ts({count:r}){let e=`${ts.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+=Ka({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{It&&console.log(`${e} complete.`)}}f(ts,"pickRandom_Letters");function _t({dominant:r,recessive:e}){let t=`[${_t.name}]`;try{if(Array.isArray(r)&&Array.isArray(e)){let o=O(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]=_t({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]=_t({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(_t,"mergeMapsOrArrays_Naive");var Xa=globalThis.crypto,{subtle:ns}=Xa,ss=new Array(256);for(let r=0;r<256;++r)ss[r]=r.toString(16).padStart(2,"0");function is(r){let e=new Uint8Array(r),t="";for(let o=0;o<e.length;o++)t+=ss[e[o]];return t}f(is,"bufToHex");function kt(r){if(r===null||typeof r!="object")return r;if(Array.isArray(r))return r.map(o=>kt(o));let e={},t=Object.keys(r).sort();for(let o of t){let n=r[o];n!==void 0&&(e[o]=kt(n))}return e}f(kt,"toNormalizedForHashing");async function Mt(r){if(!r)return"";let e=new TextEncoder().encode(r),t=await ns.digest("SHA-256",e);return is(t)}f(Mt,"hashToHex");async function Va(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 ns.digest("SHA-256",t);return is(o)}f(Va,"hashToHex_Uint8Array");var Ya=!1,fr=0,rs=0;async function os(r,e=""){let t=e||"",o=r.ib,n=r.data,s=r.rel8ns,i=Object.keys(s||{}).length>0&&Object.keys(s||{}).some(u=>s[u]&&s[u].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 Mt(t?t+o:o)).toUpperCase(),l="";if(i){let u=kt(s),p=JSON.stringify(u);l=(await Mt(t?t+p:p)).toUpperCase()}let d="";if(a)if(n instanceof Uint8Array)d=(await Va(t,n)).toUpperCase();else{let u=kt(n),p=JSON.stringify(u);d=(await Mt(t?t+p:p)).toUpperCase()}let b;if(i||a){let u=c+l+d;b=(await Mt(t?t+u:u)).toUpperCase()}else b=(await Mt(t?t+c:c)).toUpperCase();return b}f(os,"sha256v1_Internal");async function We(r,e=""){if(Ya){let t=globalThis.performance?globalThis.performance.now():Date.now(),o=await os(r,e),n=(globalThis.performance?globalThis.performance.now():Date.now())-t;return fr++,rs+=n,fr%1e3===0&&console.log(`[sha256v1 Profile] Total Runs: ${fr} | Average Duration: ${(rs/fr).toFixed(4)} ms`),o}return os(r,e)}f(We,"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 V;(function(r){r.past="past",r.ancestor="ancestor",r.dna="dna",r.identity="identity",r.tjp="tjp",r.secret="secret",r.encryption="encryption"})(V||(V={}));var Tt="ib",P="gib",W={ib:Tt,gib:P},ee="^",De=".",as="ib^gib",ze=["past","ancestor","dna","tjp"],Wa=155,cs=new RegExp(`^[\\w\\t\\-|=+.&%$#@!~\` \\[\\]\\(\\)\\{\\}]{1,${Wa}}$`);async function dt(r){let e=O(r),t=`[${dt.name}]`;e.srcAddr&&delete e.srcAddr,delete e.src;let o={ib:e.type,data:e,rel8ns:{ancestor:[`${e.type.toString()}${ee}${P}`]}};return o.gib=await We(o),o}f(dt,"buildDna");function za({ibGib:r}){let e=`[${za.name}]`;try{if(!r)throw new Error("ibGib required.");let t=["fork","mut8","rel8","plan"].map(n=>`${n}^${P}`);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(za,"isDna");function te({ibGib:r,gib:e}){return r?te({gib:r.gib}):e?e===P:!0}f(te,"isPrimitive");async function K({ibGib:r,hasTjp:e,tjpAddr:t,gibDelimiter:o,isPrimitive:n,hashAlgorithm:s}){let i=`[${K.name}]`;try{if(!r)throw new Error("ibGib required. (E: 17d073226b9d42fd841e5a94b065ef21)");if(n)return P;let a=await We(r,""),c=r.rel8ns??{},l=r.data??{};if(o=o||De,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}${De}${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(K,"getGib");function se({ibGibAddr:r,gib:e,gibDelimiter:t}){let o=`[${se.name}]`;try{if(!r&&!e)throw new Error("Either ibGibAddr or gib required. (E: 25e3dcbe63cd44909032df12af9df75e)");if(e=e||R({ibGibAddr:r}).gib,e===P)return{isPrimitive:!0};if(t=t??De,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(se,"getGibInfo");async function br(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,b="[fork_v1]";if(l!=="fork")throw new Error(`${b} not a fork transform.`);if(r.type||(r.type="fork"),!d)throw new Error(`${b} src required to fork.`);if(!d.ib)throw new Error(`${b} src.ib required.`);if(n&&n.includes(ee))throw new Error(`${b} destIb can't contain (hardcoded) delimiter right now.`);if(!d.gib)throw new Error(`${b} src.gib required.`);let u={ib:d.ib,gib:d.gib};d.data&&Object.keys(d.data).length>0&&(u.data=d.data),d.rel8ns&&Object.keys(d.rel8ns).length>0&&(u.rel8ns=d.rel8ns),d=u;let p=_({ib:d.ib,gib:d.gib});r.srcAddr=p;let h=a&&d.rel8ns&&Object.keys(d.rel8ns).length>0?O(d.rel8ns):{};delete h.past;let g=c&&d?.data?O(d.data):{};r.nCounter&&(g.n=0);let m=o?.includes(V.ancestor)?[p]:(h.ancestor||[]).concat([p]);h.ancestor=m,h.tjp&&delete h.tjp;let $=O(d);if(e&&i?.timestamp)throw new Error(`${b} both noTimestamp and tjp.timestamp selected.`);if(!e||i?.timestamp){let I=new Date;g.timestamp=ve(I),g.timestampMs=I.getMilliseconds()}(i?.uuid||s)&&(g.uuid=await k()),i?.uuid||i?.timestamp?g.isTjp=!0:g.isTjp&&delete g.isTjp,$.ib=n||"ib",p!==as&&($.rel8ns=h),Object.keys(g).length>0&&($.data=g);let y=null;if(t){y=await dt(r);let I=_({ibGib:y});h.dna=o?.includes(V.dna)?h.dna=[I]:h.dna=(h.dna||[]).concat(I)}$.gib=await We($,"");let G={newIbGib:$};return y&&(G.dnas=[y]),G}f(br,"fork");async function Me(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(ee))throw new Error(`${d} ib can't contain hardcoded delimiter (${ee}) 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 b=_({ib:l.ib,gib:l.gib});if(r.srcAddr&&b!==r.srcAddr)throw new Error(`${d} srcAddr from src does not equal opts.srcAddr`);if(r.srcAddr=b,te({ibGib:l}))throw new Error(`${d} cannot mutate primitive ibgib`);let u={ib:l.ib,gib:l.gib};l.data&&Object.keys(l.data).length>0&&(u.data=l.data),l.rel8ns&&Object.keys(l.rel8ns).length>0&&(u.rel8ns=l.rel8ns),l=u;let p=O(l),h=l.rel8ns?l.rel8ns:{},g=O(h);g.past=o?.includes(V.past)?[b]:(g.past||[]).concat([b]);let m=l?.data?O(l.data):{};if(n&&(m=So(m,n,"rename")),s&&(m=So(m,s,"remove")),i&&(m=ls(m,i)),!e){let S=new Date;m.timestamp=ve(S),m.timestampMs=S.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 S=g.tjp??[];S.push(b),g.tjp=S,delete m.isTjp}let y=null;if(t){y=await dt(r);let S=_({ibGib:y});g.dna=o?.includes(V.dna)?g.dna=[S]:g.dna=(g.dna||[]).concat(S)}p.ib=a||p.ib,p.rel8ns=g,Object.keys(m).length>0?p.data=m:delete p.data;let G=(g.tjp?.length??0)>0;p.gib=await K({ibGib:p,hasTjp:G});let I={newIbGib:p};return y&&(I.dnas=[y]),I}f(Me,"mut8");function So(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]=So(r[s],i,t)}else console.log(`${o} key to ${t} does not exist`)}),r}f(So,"renameOrRemove");function ls(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]=ls(n,o):r[t]=o:r[t]=o}),r}f(ls,"patch");async function $e(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(ee))throw new Error(`${l} ib can't contain hardcoded delimiter (${ee}) 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,b=s&&Object.keys(s).length>0,u=i&&Object.keys(i).length>0;if(!(d||b||u))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(w=>w&&typeof w=="string"&&w.length>=2&&w.includes("^")&&w.split("^")[0].length>=1,"fnValidIbGibAddr");Object.keys(n||{}).map(w=>(n||{})[w]).forEach(w=>{if(!(w&&w.every(T=>h(T))))throw new Error(`${l} Invalid rel8n attempt. Must be valid ibGibs. Did you include a delimiter (^)?`)}),Object.keys(s||{}).map(w=>(s||{})[w]).forEach(w=>{if(!(w&&w.every(T=>h(T))))throw new Error(`${l} Invalid remove rel8n attempt. Must be valid ibGibs. Did you include a delimiter (^)?`)}),Object.keys(i||{}).map(w=>(i||{})[w]).forEach(w=>{if(!(w&&w.every(T=>T&&h(T.oldAddr)&&h(T.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=O(c),$=O(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 w=new Date;$.timestamp=ve(w),$.timestampMs=w.getMilliseconds()}let y=O(c.rel8ns||{});if(Object.keys(i||{}).forEach(w=>{if(ze.includes(w))throw new Error(`${l} Cannot manually replace relationship: ${w}.`);let T=y[w]||[],v=i[w]||[],N=[...T];for(let x of v){let{oldAddr:C,newAddr:U}=x,Z=!1;for(let z=0;z<N.length;z++)N[z]===C&&(N[z]=U,Z=!0);if(!Z)throw new Error(`${l} Cannot replace oldAddr '${C}' in rel8n '${w}' - oldAddr not found in existing relationships.`)}y[w]=N}),Object.keys(n||{}).forEach(w=>{if(ze.includes(w))throw new Error(`${l} Cannot manually add relationship: ${w}.`);let T=y[w]||[],N=n[w].filter(x=>!T.includes(x));y[w]=T.concat(N)}),Object.keys(s||{}).forEach(w=>{if(ze.includes(w))throw new Error(`${l} Cannot manually remove relationship: ${w}.`);let T=y[w]||[],v=s[w]||[],N=T.filter(x=>!v.includes(x));N.length>0?y[w]=N:delete y[w]}),y.past=(y.past||[]).concat([p]),(o||[]).filter(w=>Object.keys(y).includes(w)).filter(w=>(y[w]||[]).length>1).forEach(w=>{let T=y[w].length;y[w]=[y[w][T-1]]}),$.isTjp){let w=y.tjp||[];w.push(p),y.tjp=w,delete $.isTjp}m.data=$,m.rel8ns=y;let G=(y.tjp?.length??0)>0,I=null;if(t){I=await dt(r);let w=_({ibGib:I});y.dna=o?.includes(V.dna)?y.dna=[w]:y.dna=(y.dna||[]).concat(w)}m.gib=await K({ibGib:m,hasTjp:G});let S={newIbGib:m};return I&&(S.dnas=[I]),S}f($e,"rel8");function ur({ibGib:r}){let e=`[${ur.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(De)?!0:r.gib===P?!1:!!se({ibGibAddr:_({ibGib:r})}).tjpGib:(console.warn(`${e} ibGib.gib falsy. (W: 6400d780822b44d992846f1196509be3)`),!1)}f(ur,"hasTjp");function pr({ibGib:r}){let e=`[${pr.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:O(r.data)),r.rel8ns&&(t.rel8ns=O(r.rel8ns)),t}f(pr,"toDto");var Go=!1;async function ie({ibGib:r}){let e=`[${ie.name}]`;try{let t=[];if(r){let o=_({ibGib:r});if(t=jt({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 K({ibGib:pr({ibGib:r}),hasTjp:ur({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 K({ibGib:pr({ibGib:r}),hasTjp:ur({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(ie,"validateIbGibIntrinsically");function jt({addr:r,delimiter:e,version:t}){let o=`[${jt.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||ee,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=St({ib:s,ibGibAddrDelimiter:e,version:t});a&&(n=n.concat(a));let c=At({gib:i,ibGibAddrDelimiter:e,version:t});return c&&(n=n.concat(c)),n.length>0&&Go&&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(jt,"validateIbGibAddr");function St({ib:r,ibGibAddrDelimiter:e,version:t}){let o=`[${St.name}]`;try{let n=[];return t&&console.warn(`${o} version not implemented yet. Ignoring. (W: 71228ba4ed994aaa8149910e295ab087)`),r?r===Tt?null:(e=e||ee,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(St,"validateIb");function At({gib:r,gibDelimiter:e,ibGibAddrDelimiter:t,version:o}){let n=`[${At.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||ee;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}=se({gib:r,gibDelimiter:e||De});if(d)return null;if(!c)throw new Error(`${n} punctiliarHash is falsy on a non-primitive gib. (E: 72835394918241bdb2632bf0510bdae5)`);let b=c.match(Zn),u=c.match(Qn);if(!b&&!u&&s.push("gib punctiliar hash is neither a 32- or 64-char hash string. (E: d47ff6d6e14b4c02a62107090c8dad39)"),l){let p=At({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(At,"validateGib");function xo({rel8ns:r}){let e=`[${xo.name}]`;try{Go&&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=jt({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{Go&&console.log(`${e} complete.`)}}f(xo,"validateRel8nsIntrinsically");var ds=!1,j=class r{static{f(this,"Factory_V1")}static root(){return r.primitive({ib:Tt})}static primitive({ib:e}){return{ib:e,gib:P}}static primitives({ibs:e}){return e.map(t=>r.primitive({ib:t}))}static async firstGen({ib:e=Tt,parentIbGib:t=r.root(),data:o,rel8ns:n,dna:s,tjp:i,linkedRel8ns:a,noTimestamp:c,nCounter:l,squash:d}){let b=`[${r.name}][${r.firstGen.name}]`;try{if(ds&&console.log(`${b} starting... (I: b7152fbd94382516d9f7c591bcf4c326)`),s&&d)throw new Error("both dna and squash cannot be true. Squash requires that no dna exist. (E: abfc58b4a4c8654924aa5428d0831826)");let u=[],p=t||W,h=await br({src:p,destIb:e,tjp:i,dna:s,linkedRel8ns:a,noTimestamp:c,nCounter:l});if(u.push(h),p=h.newIbGib,o){let g=await Me({src:p,dataToAddOrPatch:o,dna:s,linkedRel8ns:a,noTimestamp:c,nCounter:l});u.push(g),p=g.newIbGib}if(n){let g=await $e({src:p,rel8nsToAddByAddr:n,dna:s,linkedRel8ns:a,noTimestamp:c,nCounter:l});u.push(g)}if(u.length>1){let g=u.slice(u.length-1)[0].newIbGib,m={newIbGib:g,intermediateIbGibs:u.slice(0,u.length-1).map($=>$.newIbGib)};if(s){d&&`${b}`;let $=[];return u.forEach(y=>{$=$.concat(y.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 K({ibGib:g}),{newIbGib:g}}else return m}else{if(u.length===1)return u[0];throw new Error("(UNEXPECTED) interimResults.length is not 1 and not greater than 1? 0? But we had to fork? (E: a256c88c56916a46a888796f76ef4826)")}}catch(u){throw console.error(`${b} ${E(u)}`),u}finally{ds&&console.log(`${b} 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(St({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):cs;if(!t.match(l))throw new Error(`invalid ib. does not match regexp (${l}) (E: genuuid)`);let d=Object.keys(s??{}),b=[...ze,"tjp"];if(d.some(g=>b.includes(g)))throw new Error(`Invalid rel8ns. forbiddenRel8nNames: ${b}. 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 k()),h.rel8ns?.past&&delete h.rel8ns.past,h.rel8ns?.tjp&&delete h.rel8ns.tjp,h.gib=await K({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 zd="[core^gib timer]";var vo=`.'",!?-`;var fs=new RegExp("^[\\w\\t\\-|=+.&%$#@!~` \\[\\]\\(\\)\\{\\}]{1,155}$");var Jd=/^[a-zA-Z0-9_\-.]{1,255}$/,Zd=/^[a-zA-Z0-9_\-.\s👀🤖:;&]{1,64}$/;var hr={tags:"tags",aliases:"aliases",roots:"roots",outerspaces:"outerspaces",secrets:"secrets",encryptions:"encryptions",autosyncs:"autosyncs",robbots:"robbots",apps:"apps",history:"history"};var Ja="robbot";var bs="zero",us="zerospace";var hf=!1,gf="This is a local space. There are many like it, but this one is mine.";var mf=/^[a-zA-Z][\w\-]{0,62}[a-zA-Z]$/,Za="syncSpace";var Ef=3e4;var gr="space";var ps="space_lock",hs=100,gs=100,wf=60*2,mr=30;var Do="root",Oo="x",ms="root",No="analytics-outline",Co='This is a root ibgib, which is basically like a root folder that is primarily responsible for "containing" other ibgibs.';var Po="tag",Qa="target";var Es="pricetag-outline",ws="This is a tag used for organizing data.";var Gf="always",$s="archive",ys="trash";var Ro=/^\w{1,32}$/,Er="Invalid Date";var Lo={ib:"true",gib:P};var Is={ib:"false",gib:P};var _s="config_key";var Bt=/^[a-zA-Z0-9_\-.]{1,32}$/,wr="app";var Je=`bootstrap^${P}`,_e="defaultSpaceId",$r="spaceIds";var Oe={prependPerHash:"prependPerHash",appendPerHash:"appendPerHash",initialPrepend:"initialPrepend",initialAppend:"initialAppend"},Ze=Object.values(Oe),Ee={sha_256:"SHA-256",sha_512:"SHA-512"},Pf=Object.values(Ee),ec={indexOf:"indexOf",lastIndexOf:"lastIndexOf"},ke=Object.values(ec);function Ft(r){let e=`[${Ft.name}]`;return new Promise((t,o)=>{try{let n=Ts(r),s=As(n);t(s)}catch(n){console.error(`${e} ${E(n)}`),o(n)}})}f(Ft,"encodeStringToHexString");function Ts(r){let e=`[${Ts.name}]`;try{return new TextEncoder().encode(r)}catch(t){throw console.error(`${e} ${E(t)}`),t}}f(Ts,"stringToUTF8Bytes");function As(r){let e=`[${As.name}]`;try{return Array.from(r,t=>t.toString(16).padStart(2,"0")).join("")}catch(t){throw console.error(`${e} ${E(t)}`),t}}f(As,"bytesToHexString");function je(r){let e=`[${je.name}]`;return new Promise((t,o)=>{try{let n=Ss(r),s=Gs(n);t(s)}catch(n){console.error(`${e} ${E(n)}`),o(n)}})}f(je,"decodeHexStringToString");function Ss(r){let e=`[${Ss.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(Ss,"hexStringToBytes");function Gs(r){let e=`[${Gs.name}]`;try{return new TextDecoder().decode(r)}catch(t){throw console.error(`${e} ${E(t)}`),t}}f(Gs,"utf8BytesToString");var Be=Oe.appendPerHash,Fe="SHA-512",qe=1024,Ne=2e4,He=1,xs="indexOf",yr="lastIndexOf",Ir=5e6,_r=4,Qe=",";function tc({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 Oe.prependPerHash:return t+(e||r);case Oe.appendPerHash:return(e||r)+t;case Oe.initialPrepend:return e||t+r;case Oe.initialAppend:return e||r+t;default:throw new Error(`Unknown saltStrategy: ${o} (E: 235136af1a6c40eb9c17b2ca41c08a01)`)}}f(tc,"getPreHash");async function ye({secret:r,prevHash:e,count:t,salt:o,saltStrategy:n,hashAlgorithm:s}){let i=`[${ye.name}]`;try{let a=e||void 0;for(let c=0;c<t;c++){let l=tc({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(ye,"execRound_getNextHash");async function Ke({secret:r,initialRecursions:e,salt:t,saltStrategy:o,hashAlgorithm:n}){let s=`[${Ke.name}]`;try{return await ye({secret:r,count:e,salt:t,saltStrategy:o,hashAlgorithm:n})}catch(i){throw console.error(`${s} ${E(i)}`),i}}f(Ke,"doInitialRecursions_keystretch");async function Uo({hexEncodedData:r,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,secret:s,hashAlgorithm:i,encryptedDataDelimiter:a,indexingMode:c}){let l=`[${Uo.name}]`;try{let d=await Ke({secret:s,initialRecursions:e,salt:o,saltStrategy:n,hashAlgorithm:i}),b=c==="indexOf"?(h,g)=>h.indexOf(g):(h,g)=>h.lastIndexOf(g),u=[];for(let h=0;h<r.length;h++){let g=r[h],m="",$;for(;!m.includes(g);)$=await ye({count:t,prevHash:d,salt:o,saltStrategy:n,hashAlgorithm:i}),m+=$,d=$;let y=b(m,g);u.push(y)}return u.join(a)}catch(d){throw console.error(`${l} ${E(d)}`),d}}f(Uo,"encryptFromHex_stream");async function Mo({encryptedData:r,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,secret:s,hashAlgorithm:i,encryptedDataDelimiter:a}){let c=`[${Mo.name}]`;try{let l=await Ke({secret:s,initialRecursions:e,salt:o,saltStrategy:n,hashAlgorithm:i}),d=r.split(a).map(p=>parseInt(p)),b=[];for(let p=0;p<d.length;p++){let h=d[p],g="",m;for(;h>=g.length;)m=await ye({count:t,prevHash:l,salt:o,saltStrategy:n,hashAlgorithm:i}),g+=m,l=m;let $=g[h];b.push($)}return b.join("")}catch(l){throw console.error(`${c} ${E(l)}`),l}}f(Mo,"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||Ne,t=t||He,n=n||Be,i=i||Fe,o=o||await k(qe),a=a||Qe;let b="[validation]";if(!e||e<1){let h=`${b} initialRecursions required, and greater than 0`;console.error(h),l.push(h)}if(!t||t<1){let h=`${b} recursionsPerHash required, and greater than 0`;console.error(h),l.push(h)}if(!r){let h=`${b} encryptedData required`;console.error(h),l.push(h)}if(!o){let h=`${b} salt required`;console.error(h),l.push(h)}if(!n){let h=`${b} saltStrategy required`;console.error(h),l.push(h)}if(!s){let h=`${b} secret required`;console.error(h),l.push(h)}if(!a){let h=`${b} encryptedDataDelimiter required`;console.error(h),l.push(h)}if(!Object.values(Ee).includes(i)){let h=`${b} only ${Object.values(Ee)} hash algorithms implemented`;console.error(h),l.push(h)}if(n&&!Ze.includes(n)){let h=`${b} 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 u=await Mo({encryptedData:r,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,secret:s,hashAlgorithm:i,encryptedDataDelimiter:a});return{decryptedData:await je(u),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 ko({dataToEncrypt:r,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,secret:s,hashAlgorithm:i,encryptedDataDelimiter:a,confirm:c,indexingMode:l}){let d=`[${ko.name}]`,b=[],u=[];e||(console.warn(`${d} initial recursions required. defaulting to ${Ne}`),e=Ne),t=t||He,n=n||Be,i=i||Fe,o=o||await k(qe),a=a||Qe,l=l||xs;let p="[validation]";if(!e||e<1){let m=`${p} initialRecursions required, and greater than 0`;console.error(m),b.push(m)}if(!t||t<1){let m=`${p} recursionsPerHash required, and greater than 0`;console.error(m),b.push(m)}if(!r){let m=`${p} dataToEncrypt required`;console.error(m),b.push(m)}if(!o){let m=`${p} salt required`;console.error(m),b.push(m)}if(!n){let m=`${p} saltStrategy required`;console.error(m),b.push(m)}if(!s){let m=`${p} secret required`;console.error(m),b.push(m)}if(!a){let m=`${p} encryptedDataDelimiter required`;console.error(m),b.push(m)}if(!ke.includes(l)){let m=`${p} invalid indexingMode (${l}). Must be one of ${ke} (E: 5955c46755434982982823c97adcf076)`;console.error(m),b.push(m)}if(!Object.values(Ee).includes(i)){let m=`${p} only ${Object.values(Ee)} hash algorithms implemented`;console.error(m),b.push(m)}if(n&&!Ze.includes(n)){let m=`${p} unknown saltStrategy: ${n}`;console.error(m),b.push(m)}if(b.length>0)return{errors:b,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,hashAlgorithm:i,encryptedDataDelimiter:a};let h=await Ft(r);if(c&&await je(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 Uo({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&&(u=u.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:u.length>0?u:void 0}}f(ko,"encryptImpl_stream");async function jo({hexEncodedData:r,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,secret:s,hashAlgorithm:i,encryptedDataDelimiter:a,indexingMode:c,maxBlockSize:l,numOfPasses:d}){let b=`[${jo.name}]`;try{let u=await Ke({secret:s,initialRecursions:e,salt:o,saltStrategy:n,hashAlgorithm:i}),p=c==="indexOf"?(S,w)=>S.indexOf(w):(S,w)=>S.lastIndexOf(w),h=[],g=r.length,m=l;m>g&&(m=g);let $=Math.ceil(g/m),y=g%m||m,G=0;for(let S=0;S<$;S++){S===$-1&&(m=y);let T=await vs({blockSize:m,indexHexEncodedDataAtStartOfPass:G,numOfPasses:d,hexEncodedData:r,recursionsPerHash:t,salt:o,saltStrategy:n,prevHash:u,hashAlgorithm:i}),v=T.alphabetsThisBlock;u=T.prevHash;let N=await Ds({alphabetsThisBlock:v,blockSize:m,indexHexEncodedDataAtStartOfPass:G,hexEncodedData:r,getIndexOfCharInAlphabet:p});h=h.concat(N),G+=m}return h.join(a)}catch(u){throw console.error(`${b} ${E(u)}`),u}}f(jo,"encryptFromHex_blockMode");async function vs({blockSize:r,numOfPasses:e,indexHexEncodedDataAtStartOfPass:t,hexEncodedData:o,recursionsPerHash:n,salt:s,saltStrategy:i,prevHash:a,hashAlgorithm:c}){let l=`[${vs.name}]`;try{let d=[],b,u;for(let p=0;p<e;p++)for(let h=0;h<r;h++){b=t+h;let g=d[h]??"";u=await ye({count:n,prevHash:a,salt:s,saltStrategy:i,hashAlgorithm:c}),g+=u,a=u,d[h]=g}for(let p=0;p<r;p++){b=t+p;let h=o[b],g=d[p];for(;!g.includes(h);)u=await ye({count:n,prevHash:a,salt:s,saltStrategy:i,hashAlgorithm:c}),g+=u,a=u;d[p]=g}return{alphabetsThisBlock:d,prevHash:a}}catch(d){throw console.error(`${l} error: ${E(d)}`),d}}f(vs,"getAlphabetsThisBlock");async function Ds({alphabetsThisBlock:r,blockSize:e,indexHexEncodedDataAtStartOfPass:t,hexEncodedData:o,getIndexOfCharInAlphabet:n}){let s=`[${Ds.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(Ds,"getEncryptedIndexesThisBlock");async function Bo({encryptedData:r,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,secret:s,hashAlgorithm:i,encryptedDataDelimiter:a,maxBlockSize:c,numOfPasses:l}){let d=`[${Bo.name}]`;try{let b=await Ke({secret:s,initialRecursions:e,salt:o,saltStrategy:n,hashAlgorithm:i}),u=r.split(a).map(I=>parseInt(I)),p=[],h=u.length,g=c;g>h&&(g=h);let m=Math.ceil(h/g),$=h%g||g,y=0;for(let I=0;I<m;I++){I===m-1&&(g=$);let w=await Os({blockSize:g,indexEncryptedDataIndexesAtStartOfPass:y,numOfPasses:l,encryptedDataIndexes:u,recursionsPerHash:t,salt:o,saltStrategy:n,prevHash:b,hashAlgorithm:i}),T=w.alphabetsThisBlock;b=w.prevHash;let v=await Ns({alphabetsThisBlock:T,blockSize:g,indexEncryptedDataIndexesAtStartOfPass:y,encryptedDataIndexes:u});p=p.concat(v),y+=g}return p.join("")}catch(b){throw console.error(`${d} ${E(b)}`),b}}f(Bo,"decryptToHex_blockMode");async function Os({blockSize:r,numOfPasses:e,indexEncryptedDataIndexesAtStartOfPass:t,encryptedDataIndexes:o,recursionsPerHash:n,salt:s,saltStrategy:i,prevHash:a,hashAlgorithm:c}){let l=`[${Os.name}]`;try{let d=[],b,u;for(let p=0;p<e;p++)for(let h=0;h<r;h++){b=t+h;let g=d[h]??"";u=await ye({count:n,prevHash:a,salt:s,saltStrategy:i,hashAlgorithm:c}),g+=u,a=u,d[h]=g}for(let p=0;p<r;p++){b=t+p;let h=o[b],g=d[p];for(;g.at(h)===void 0;)u=await ye({count:n,prevHash:a,salt:s,saltStrategy:i,hashAlgorithm:c}),g+=u,a=u;d[p]=g}return{alphabetsThisBlock:d,prevHash:a}}catch(d){throw console.error(`${l} error: ${E(d)}`),d}}f(Os,"getAlphabetsThisBlock");async function Ns({alphabetsThisBlock:r,blockSize:e,indexEncryptedDataIndexesAtStartOfPass:t,encryptedDataIndexes:o}){let n=`[${Ns.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(Ns,"getDecryptedDataArrayThisBlock");async function Ht(r){let e=`[${Ht.name}]`,{encryptedData:t,initialRecursions:o,recursionsPerHash:n,salt:s,saltStrategy:i,secret:a,hashAlgorithm:c,encryptedDataDelimiter:l,indexingMode:d,blockMode:b,multipass:u}=r,p=[],h=[];if(b&&u)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(!b&&u&&(console.warn(`${e}[WARNING] "multipass" option is deprecated. this has been refactored to "blockMode". This will use multipass as blockMode. (W: b77c9773e30549cbb389ce61f31eb6d3)`),b=u),!b)throw new Error("(UNEXPECTED) blockMode required. This should be truthy in order to get to this impl fn. (E: 306bce36afd64b7182ca2b46ac04a261)");o=o||Ne,n=n||He,i=i||Be,c=c||Fe,s=s||await k(qe),l=l||Qe,d=d||yr;let{maxBlockSize:g,maxPassSectionLength:m,numOfPasses:$}=b;!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||Ir,$=$||_r;let y="[validation]";if(!o||o<1){let w=`${y} initialRecursions required, and greater than 0`;console.error(w),p.push(w)}if(!n||n<1){let w=`${y} recursionsPerHash required, and greater than 0`;console.error(w),p.push(w)}if(!t){let w=`${y} encryptedData required`;console.error(w),p.push(w)}if(!s){let w=`${y} salt required`;console.error(w),p.push(w)}if(!i){let w=`${y} saltStrategy required`;console.error(w),p.push(w)}if(!a){let w=`${y} secret required`;console.error(w),p.push(w)}if(!l){let w=`${y} encryptedDataDelimiter required`;console.error(w),p.push(w)}if(!d){let w=`${y} indexingMode required (E: a6fe15f8ba414e21b5355d23e808b976)`;console.error(w),p.push(w)}if(!ke.includes(d)){let w=`${y} invalid indexingMode (${d}). Must be one of ${ke} (E: 17435268651444e0b7a594135635fc58)`;console.error(w),p.push(w)}if(g<1){let w=`${y} maxBlockSize must be greater than 0 (E: 0870831aa86b4bfa939aeee9f252326a)`;console.error(w),p.push(w)}if($<1){let w=`${y} numOfPasses must be greater than 0 (E: 691d3c3765584c6f8c9aba1ee378df00)`;console.error(w),p.push(w)}if(!Object.values(Ee).includes(c)){let w=`${y} only ${Object.values(Ee)} hash algorithms implemented`;console.error(w),p.push(w)}if(i&&!Ze.includes(i)){let w=`${y} unknown saltStrategy: ${i}`;console.error(w),p.push(w)}if(p.length>0){let w={...r,errors:p};return delete w.encryptedData,delete w.secret,w}let G=await Bo({encryptedData:t,initialRecursions:o,recursionsPerHash:n,salt:s,saltStrategy:i,secret:a,hashAlgorithm:c,encryptedDataDelimiter:l,maxBlockSize:g,numOfPasses:$}),I=await je(G),S={...r,decryptedData:I,warnings:h.length>0?h:void 0};return delete S.encryptedData,delete S.secret,S}f(Ht,"decryptImpl_blockMode");async function Fo(r){let e=`[${Fo.name}]`,{dataToEncrypt:t,initialRecursions:o,recursionsPerHash:n,salt:s,saltStrategy:i,secret:a,hashAlgorithm:c,encryptedDataDelimiter:l,confirm:d,indexingMode:b,blockMode:u,multipass:p}=r,h=[],g=[];if(u&&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(!u&&p&&(console.warn(`${e}[WARNING] "multipass" option is deprecated. this has been refactored to "blockMode". This will use multipass as blockMode. (W: 046b55a6d1304155b2e5352a9e6140b0)`),u=p),!u)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 ${Ne}`),o=Ne),l=l||Qe,b=b||yr;let{maxBlockSize:m,maxPassSectionLength:$,numOfPasses:y}=u;!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||Ir,y=y||_r;let G="[validation]";if(!o||o<1){let T=`${G} initialRecursions required, and greater than 0 (E: dd96a75f0c504f34b1f9f2f32e011c50)`;console.error(T),h.push(T)}if(!n||n<1){let T=`${G} recursionsPerHash required, and greater than 0 (E: 64cf53e0bf9f4963be6b165ca4e6566d)`;console.error(T),h.push(T)}if(!s){let T=`${G} salt required (E: 136a5d237e0f4b1d89f8c87ac12a1507)`;console.error(T),h.push(T)}if(!i){let T=`${G} saltStrategy required (E: 457ed117bf224b9f86fe81ab6bc35381)`;console.error(T),h.push(T)}if(!a){let T=`${G} secret required (E: 5c363255055a45cfb07656e2f4854ed7)`;console.error(T),h.push(T)}if(!l){let T=`${G} encryptedDataDelimiter required (E: 1bbeb4dce19e4ac2bbe7d1e373739298)`;console.error(T),h.push(T)}if(!b){let T=`${G} indexingMode required (E: 693ebd2be64a438aa3b075d0cb0d92bf)`;console.error(T),h.push(T)}if(!ke.includes(b)){let T=`${G} invalid indexingMode (${b}). Must be one of ${ke} (E: 17435268651444e0b7a594135635fc58)`;console.error(T),h.push(T)}if(m<1){let T=`${G} maxBlockSize must be greater than 0 (E: 9f268207ae274b958fb91855331be259)`;console.error(T),h.push(T)}if(y<1){let T=`${G} numOfPasses must be greater than 0 (E: c3bcab79bb024d65b84947806290a7d4)`;console.error(T),h.push(T)}if(!Object.values(Ee).includes(c)){let T=`${G} only ${Object.values(Ee)} hash algorithms implemented`;console.error(T),h.push(T)}if(i&&!Ze.includes(i)){let T=`${G} unknown saltStrategy: ${i}`;console.error(T),h.push(T)}if(h.length>0){let T={...r,errors:h};return delete T.dataToEncrypt,delete T.secret,T}let I=await Ft(t);if(d&&await je(I)!==t)throw new Error("decoding encoded hex failed for this data: The encoded hex did not reverse to the original data.");let S=await jo({hexEncodedData:I,initialRecursions:o,recursionsPerHash:n,salt:s,saltStrategy:i,secret:a,hashAlgorithm:c,encryptedDataDelimiter:l,indexingMode:b,maxBlockSize:m,numOfPasses:y});if(d)try{let T=await Ht({encryptedData:S,initialRecursions:o,recursionsPerHash:n,salt:s,saltStrategy:i,secret:a,hashAlgorithm:c,encryptedDataDelimiter:l,indexingMode:b,blockMode:u});if(T.decryptedData){if(T.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)");(T.warnings||[]).length>0&&(g=g.concat(["Confirm check call to decrypt had warnings.",...T.warnings]))}catch(T){throw new Error(`${e} confirm failed. decrypt error: ${E(T)} (E: 782a84d9dc294ce9a6a325e3ab293adf)`)}let w={...r,encryptedData:S,warnings:g.length>0?g:void 0};return delete w.dataToEncrypt,delete w.secret,w}f(Fo,"encryptImpl_blockMode");async function rc(r){let e=`[${rc.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 k(qe),r.saltStrategy=r.saltStrategy||Be,r.hashAlgorithm=r.hashAlgorithm||Fe,r.recursionsPerHash=r.recursionsPerHash||He;let t;return r.blockMode?t=await Fo(r):t=await ko(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(rc,"encrypt");async function oc(r){let e=`[${oc.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 k(qe),r.saltStrategy=r.saltStrategy||Be,r.hashAlgorithm=r.hashAlgorithm||Fe,r.recursionsPerHash=r.recursionsPerHash||He;let t;return r.blockMode||r.multipass?t=await Ht(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(oc,"decrypt");var Kb=5e4;var Xb=Oe.appendPerHash,Vb=10,Yb="SHA-256";var Wb="encryption",zb="ciphertext";var nc={local:"local",outerspace:"outerspace",innerspace:"innerspace"},eu=Object.values(nc).concat(),sc={user:"user",sync:"sync"},qo=Object.values(sc).concat(),ic={node_filesystem:"node-filesystem"},ac={aws_dynamodb:"aws-dynamodb"},cc={...ic,...ac},Ho=Object.values(cc).concat(),lc={get:"get",put:"put",delete:"delete"},dc={can:"can",addrs:"addrs",latest:"latest",watch:"watch",unwatch:"unwatch",tjps:"tjps",dependencyGraph:"dependency-graph"};var fc=!1,Ar=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 fc&&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:lr({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:lr({min:0,max:155,chars:vo}),regexpErrorMsg:`0 to 155 alphanumerics or any of ${vo}`,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:lr({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:Q,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 et=class r extends Ar{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 Sr=!1;function Cs({appData:r}){let e=`[${Cs.name}]`;try{if(Sr&&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(Bt)||t.push(`name must match regexp: ${Bt}`):t.push("name required."),n?n.match(Q)||t.push(`uuid must match regexp: ${Q}`):t.push("uuid required."),s&&(s.match(Bt)||t.push(`classname must match regexp: ${Bt}`)),t}catch(t){throw console.error(`${e} ${t.message}`),t}finally{Sr&&console.log(`${e} complete.`)}}f(Cs,"validateCommonAppData");function Ko({appData:r,classname:e}){let t=`[${Ko.name}]`;try{let o=Cs({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(Ko,"getAppIb");function bc({appIb:r}){let e=`[${bc.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(bc,"getInfoFromAppIb");async function uc({fnPromptApp:r,ibgibs:e,space:t}){let o=`[${uc.name}]`;try{if(Sr&&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 b=i[d],u=await ie({ibGib:b});if((u??[]).length>0)throw new Error(`(UNEXPECTED) invalid app ibgib created. validationErrors: ${u}. app: ${H(s.toIbGibDto())} (E: 54cfc2f6bc284ed79be91d2da5e4bd2f)`)}await re({resTransform:n,space:t});let{zeroSpace:a,fnBroadcast:c,fnUpdateBootstrap:l}=e;return await Te({ibGib:s,space:t,fnBroadcast:f(d=>c(d),"fnBroadcast")}),await Gt({type:"apps",rel8nName:wr,ibGibsToRel8:[s],space:t,zeroSpace:a,fnUpdateBootstrap:l,fnBroadcast:c}),s}catch(n){debugger;console.error(`${o} ${n.message}`);return}finally{Sr&&console.log(`${o} complete.`)}}f(uc,"createNewApp");var pc="0",hc="chat_gib",gc="A chat app done ibgib style, enabling infinitely nesting comments, pics and links. It's ibgibs all the way down...",Ps={version:"1",uuid:pc,name:hc,description:gc,classname:"ChatApp_V1",icon:"chatbubbles",persistOptsAndResultIbGibs:!1,allowPrimitiveArgs:!0,catchAllErrors:!0,trace:!1},Rs=void 0;var mc="0",Ec="raw_gib",wc="Explorer app for navigating raw ibgib data.",Ls={version:"1",uuid:mc,name:Ec,description:wc,classname:"RawApp_V1",icon:"paper-plane",persistOptsAndResultIbGibs:!1,allowPrimitiveArgs:!0,catchAllErrors:!0,trace:!1},Us=void 0;var Xo="0",$c="todo_gib",yc="Todo app for viewing and interacting with ibgibs like they're checklists.",Ms={version:"1",uuid:Xo,name:$c,description:yc,classname:"TodoApp_V1",icon:"checkbox",persistOptsAndResultIbGibs:!1,allowPrimitiveArgs:!0,catchAllErrors:!0,trace:!1},ks=void 0;async function Vo(r){let e=`[${Vo.name}]`,t=[];try{_({ibGib:r})!==Je&&t.push(`invalid bootstrapSpace addr. Should equal "${Je}" (E: ecfdbed719284db7a1aa3f867f706fe9)`);let n=await ie({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[_e]?(i[s[_e]]??[]).length===0&&t.push(`invalid bootstrap. data.${_e} (${s[_e]}) not found in rel8ns. (E: 44d0799d232f4a51a0b0019ebebe019f)`):t.push(`invalid bootstrap. data.${_e} required. (E: f763af2e275f445cbf1db5801bacafad)`),t.length===0?!0:(console.error(`${e} errors: ${t.join("|")}`),!1)}catch(o){return console.error(`${e} ${o.message}`),!1}}f(Vo,"validateBootstrapIbGib");var xt="meta_stone";var Yo="undefined",Kt="target",Gr="targetTjp";var Ie=!1;function Bs({ib:r}){let e=`[${Bs.name}]`;try{Ie&&console.log(`${e} starting...`);let t=[],o=r.split(" ");o[0]!==xt&&t.push(`${e} invalid ib. atom is expected to be META_STONE_ATOM: ${xt} (E: a9812bffc18f44418aa091fb0ed260bd)`);let s=o[1],i=At({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=Xt({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{Ie&&console.log(`${e} complete.`)}}f(Bs,"validateCommonMetaStoneIb");function Wo({data:r}){let e=`[${Wo.name}]`;try{if(Ie&&console.log(`${e} starting...`),!r)throw new Error("data required (E: c50ac422af4501b72af12481fbd4961e)");let t=[],{targetData:o,timestamp:n}=r;Xt({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=At({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=Xt({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{Ie&&console.log(`${e} complete.`)}}f(Wo,"validateCommonMetaStoneData");function Fs({rel8ns:r}){let e=`[${Fs.name}]`;try{if(Ie&&console.log(`${e} starting...`),!r)throw new Error("rel8ns required (E: 7737ae550e2347e68c67b715c1221393)");let t=[],o=xo({rel8ns:r??{}})??[];o.length>0&&t.push(`invalid rel8ns intrinsically. errors: ${o.join("|")}. (E: abc91753f0f946afa0a3ea2c1917960f)`);let n=r[Kt]??[];n.length===0?t.push(`invalid metastone rel8ns. should have exactly 1 rel8nName ${Kt}. has 0. (E: 8181652da9e89613e204d245db12d723)`):n.length>1&&t.push(`invalid metastone rel8ns. should have exactly 1 rel8nName ${Kt}. has ${n.length}. (E: 2318047c6fea482d9f53febe02cf8912)`);let s=r[Gr]??[];return s.length>1&&t.push(`invalid metastone rel8ns. should have 0 or 1 rel8nName ${Gr}. has ${s.length}. (E: 34a8ae53825f46caa7ad024a64400db2)`),t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Ie&&console.log(`${e} complete.`)}}f(Fs,"validateCommonMetaStoneRel8ns");async function Ic({ibGib:r}){let e=`[${Ic.name}]`;try{Ie&&console.log(`${e} starting... (I: f32249d08105b997871a06cdee006311)`);let t=await ie({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}=Hs({ib:r.ib})}catch(a){o.push(E(a))}let n=Wo({data:r.data}),s=Fs({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{Ie&&console.log(`${e} complete.`)}}f(Ic,"validateCommonMetaStoneIbGib");function qs({data:r,classname:e}){let t=`[${qs.name}]`;try{let o=Wo({data:r});if(o.length>0)throw new Error(`invalid MetaStone data: ${o} (E: ac642cc5915f0fc0508cb2fb728c86fa)`);e&&Ie&&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"?me(n):Yo;return`${xt} ${r.targetData.tjpGib} ${r.targetData.n} ${s}`}catch(o){throw console.error(`${t} ${E(o)}`),o}}f(qs,"getMetaStoneIb");function Hs({ib:r}){let e=`[${Hs.name}]`;try{if(!r)throw new Error("MetaStone ib required (E: 8e74e098d7aeef52d3952e35150d83ed)");let t=Bs({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(Hs,"parseMetaStoneIb");function Uu({addr:r,ibGib:e}){if(r||=_({ibGib:e}),!r)throw new Error("either addr or ibGib required. (E: 372b2574d5a9fac298119beed9f6e223)");return r.startsWith(`${xt} `)}f(Uu,"isMetaStone");async function zo({targetIbGib:r}){let e=`[${zo.name}]`;try{Ie&&console.log(`${e} starting... (I: d846313065c89c89e4b5afa2df2b7123)`);let t=_({ibGib:r}),o=ue({ibGib:r,defaultIfNone:"incomingAddr"}),n,s={[Kt]:[t],[Gr]:[o]};if(!r.gib)throw new Error("(UNEXPECTED) targetIbGib.gib falsy? (E: 28eaa8a799021dadd87b043711aee826)");let i=r.data?.isTjp?r.gib:se({ibGibAddr:t}).tjpGib??r.gib;if(i===P)throw new Error("cannot create metastone for primitive ibgib (E: 2887e8ef83381a0698256b7bc7531826)");let a=new Date,c=ve(a),l=a.getMilliseconds();r.data?Vt({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??Yo},timestamp:c,timestampMs:l},r.data?.isTjp&&(n.targetData.isTjp=!0)):n={targetData:{n:-1,tjpGib:i},timestamp:c,timestampMs:l};let d=qs({data:n}),b=await Ae({parentPrimitiveIb:xt,ib:d,data:n,rel8ns:s});return Ie&&(console.log(`${e} metaStoneIbGib... (I: 2b16197478488b329246d22d2dc41423)`),console.dir(b)),b}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Ie&&console.log(`${e} complete.`)}}f(zo,"newUpMetaStone");var xr="witness",Yt="witness_arg",vr="witness_result",ju="context";var A=!1;async function ae({addr:r,addrs:e,isDna:t,space:o,force:n}){let s=`[${ae.name}]`;try{if(A&&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:Ge({space:o}),argData:{cmd:"get",ibGibAddrs:e,isDna:t}}),a=await o.witness(i);return a?.data?.success?(A&&console.log(`${s} got.`),{success:!0,ibGibs:a.ibGibs,rawResultIbGib:a}):(A&&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(ae,"getFromSpace");async function Qo({ibGib:r,ibGibs:e,isDna:t,force:o,space:n}){let s=`[${Qo.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],A&&console.log(`${s} ibGibs.length: ${e.length}`);let i=await n.argy({ibMetadata:Ge({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(Qo,"putInSpace");async function en({addr:r,isDna:e,space:t}){let o=`[${en.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:Ge({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")&&A&&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(en,"deleteFromSpace");async function re({resTransform:r,space:e,force:t}){let o=`[${re.name}]`;try{if(A&&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:Ge({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:Ge({space:e}),argData:{cmd:"put",isDna:!0,force:t,ibGibAddrs:i.map(u=>_({ibGib:u}))},ibGibs:i.concat()}),b=await e.witness(d);if(b.data?.success)b.data.warnings?.length>0&&b.data.warnings.forEach(u=>console.warn(`${o} ${u}`));else{let u=b?.data?.errors?.length>0?b.data.errors.join(`
6
+ `):"unknown error putting dna ibGibs";throw new Error(u)}}}catch(n){throw console.error(`${o} ${n.message}`),n}finally{A&&console.log(`${o} complete. (I: dc6835614ff1a1b82b179225023ae823)`)}}f(re,"persistTransformResult");async function _c({type:r,rel8nName:e,space:t}){let o=`[${_c.name}]`;try{if(!t)throw new Error("space required. (E: f73868a952ac4181a4f90ee6d86cacf3)");let n=await Or({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 ae({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(_c,"getSpecialRel8dIbGibs");async function Or({type:r,initialize:e,space:t,zeroSpace:o,fnUpdateBootstrap:n,fnBroadcast:s,fnGetInitializing:i,fnSetInitializing:a,dontWarnIfNotExist:c}){let l=`[${Or.name}]`;try{if(!t)throw new Error("space required. (E: d454b31d58764a9bb9c4e47fb5ef38b5)");let d=oe({type:r}),b=await Nr({key:d,space:t,dontWarn:c||!!e});if(!b){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)");b=await Vs({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(!b){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)")}}A&&console.log(`${l} getting addr: ${b}`);let u=await ae({addr:b,space:t});if(u.success||(u=await ae({addr:b,space:t}),u.success&&(console.warn(`${l} special ibgib was not stored in meta folder...putting in meta folder now for the future (W: e6f5571fd98c449bb2809359be5057cc)`),(await Qo({ibGib:u.ibGibs[0],space:t})).success||console.warn(`${l} (UNEXPECTED) tried to put special in meta but success was false? (W: b934b53571c24057af172c790e6a7240)`))),!u.success)throw new Error(u.errorMsg);if(u.ibGibs?.length!==1)throw new Error("no ibGib in result (E: 3a42abdddc3648e292d63dc45c560064)");let p=u.ibGibs[0],h=await Pe({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 b=`${l} ${d.message}`;return b.includes("d8ebdc9eaaa640b99cd206f132962c93")&&c||console.error(b),null}}f(Or,"getSpecialIbGib");async function Nr({key:r,space:e,dontWarn:t}){let o=`[${Nr.name}](${r})`;try{if(A&&console.log(`${o} getting... (I: 43e7bfc2515d45e5af8767b9a85b248e)`),!e)throw new Error("space required. (E: 4f135d4276e64054ba21aeb9c304ecec)");if(!e.rel8ns){(A||!t)&&console.warn(`${o} space.rel8ns falsy. (W: 7c642259fbf547dbaa1b2fdf0115f6ef)`);return}if(!e.rel8ns[r]){(A||!t)&&console.warn(`${o} space.rel8ns[${r}] falsy. (W: 3c1c49b9987b45cc96dd78b808f98e91)`);return}if(e.rel8ns[r].length===1)return A&&console.log(`${o} got (I: f13e71b693d5404c9535bda8ff0cc6a9)`),e.rel8ns[r][0];if(e.rel8ns[r].length>1)return(A||!t)&&console.warn(`${o} more than one config addr with ${r} rel8n. (W: 102f63eb74904bcfaac2eaf778043205)`),e.rel8ns[r][0];A&&console.log(`${o} didn't find (I: 1163e6ac60194d25b3f24881650edfad)`);return}catch(n){console.error(`${o} ${n.message}`);return}}f(Nr,"getConfigAddr");async function de({key:r,addr:e,space:t,zeroSpace:o,fnUpdateBootstrap:n}){let s=`[${de.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 $e({src:t.toIbGibDto(),dna:!1,linkedRel8ns:["past","ancestor",r],rel8nsToAddByAddr:i,nCounter:!0});if(!a.newIbGib)throw new Error("create new space failed.");await re({resTransform:a,space:o}),await re({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(de,"setConfigAddr");async function Ks({space:r}){let e=`[${Ks.name}]`;try{if(!r)throw new Error("space required. (E: f0d546101fba4c169256158114ab3c56)");let t=await Or({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 ae({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(Ks,"getCurrentRoot");async function tn({root:r,space:e,zeroSpace:t,fnUpdateBootstrap:o,fnBroadcast:n}){let s=`[${tn.name}]`;try{if(A&&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 Or({type:"roots",space:e});if(!a)throw new Error("Roots not initialized. (E: a8232b9afac89d0d189534480b7a9825)");let l=await $e({src:a,dna:!1,linkedRel8ns:["past","ancestor","current"],rel8nsToAddByAddr:{current:[i]},nCounter:!0});await re({resTransform:l,space:e});let d=oe({type:"roots"}),b=l.newIbGib,u=_({ibGib:b});await de({key:d,addr:u,space:e,zeroSpace:t,fnUpdateBootstrap:o}),await Te({ibGib:b,space:e,fnBroadcast:n})}catch(i){throw console.error(`${s} ${i.message}`),i}finally{A&&console.log(`${s} complete. (I: 7f16e845a80fe95d28923e4170f0c825)`)}}f(tn,"setCurrentRoot");async function Xs({ibGib:r,linked:e,rel8nName:t,space:o,fnBroadcast:n,zeroSpace:s,fnUpdateBootstrap:i}){let a=`[${Xs.name}]`;try{if(!o)throw new Error("space required. (E: f2758eab3bb844d2b749515672d9e392)");if(!r)throw new Error("ibGib required (E: f1bfd67754a7271553f4af544d30bc22)");let c=await Ks({space:o});if(!c)throw new Error("currentRoot undefined (E: 5c2d84dafc664808866008f6eb535750");let l=ue({ibGib:r,defaultIfNone:"incomingAddr"}),d=_({ibGib:r});if(t&&l&&c.rel8ns&&c.rel8ns[t]&&c.rel8ns[t].includes(l))return;t=t||Oo;let b=await $e({src:c,dna:!1,linkedRel8ns:e?["past","ancestor",t]:["past","ancestor"],rel8nsToAddByAddr:{[t]:[d]},nCounter:!0});await re({resTransform:b,space:o});let u=b.newIbGib,p=_({ibGib:u});A&&console.log(`${a} updating _currentRoot root. newRootAddr: ${p}`),await Te({ibGib:u,space:o,fnBroadcast:n}),await tn({root:u,space:o,zeroSpace:s,fnUpdateBootstrap:i,fnBroadcast:n})}catch(c){console.error(`${a} ${c.message}`);return}}f(Xs,"rel8ToCurrentRoot");async function Jo({targetIbGib:r,space:e}){let t=`[${Jo.name}]`;try{A&&console.log(`${t} starting... (I: 291638372117dbc983b4b7cbd8f52123)`);let o=await zo({targetIbGib:r}),n=await Qo({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{A&&console.log(`${t} complete.`)}}f(Jo,"createAndSaveNewMetaStone");async function Te({ibGib:r,space:e,fnBroadcast:t}){let o=`[${Te.name}]`,n=A;try{let s=_({ibGib:r});if(o=`${o}[${s}]`,!e)throw new Error("space required. (E: ea0c03256f8a4062b460aa4de11f1e3e)");if(A&&console.log(`${o} starting...`),!se({ibGibAddr:s}).tjpGib&&!r.data?.isTjp){A&&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 Jo({targetIbGib:r,space:e});return}let a=ue({ibGib:r,defaultIfNone:"undefined"});if(!a){let h=r.data?.isTjp?r:await Zo({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()=>{A&&console.log(`${o} adding/replacing latest. tjp: ${a} (I: 7f848da003a2436089fd6f044d96bb42)`),await Jo({targetIbGib:r,space:e}),t&&(A&&console.log(`${o} fnBroadcast is true...(I: 0e3b561fb5474a0598b5c6d698df5e1f)`),setTimeout(()=>{A&&console.log(`${o} broadcasting... (I: 61785937be0346f0959d476d7267ab24)`),t({ib:"IbGibTimelineUpdateInfo",tjpAddr:a,latestAddr:s,latestIbGib:r})}))},"replaceLatest");if(r.data?.isTjp){A&&console.log(`${o} ibGib.data?.isTjp true. replacingLatest and returning early. (I: 02c626e006668291550e278b461bcb23)`),await c();return}A&&console.log(`${o} ibGib.data?.isTjp is falsy. (I: 84940e3a9eff869c9474b7b92b864b23)`);let l=await Pe({ibGibs:[r],space:e});if(!l.data)throw new Error("(UNEXPECTED) resLatest.data falsy? (E: af3d3914d96adcc5525e4db83cc5d223)");let{success:d,latestAddrsMap:b}=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(!b)throw new Error("(UNEXPECTED) latestAddrsMap falsy but success truthy? (E: c34caff7a256503575ff3ff491dec823)");let u=Object.keys(b);if(u.length!==1)throw new Error("(UNEXPECTED) latestAddrsMap size isn't 1? (E: e11ffc2c18d473745b5bbfc3fe5e3a23)");if(u[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: ${u[0]} (E: 82d79a95d2d7de90eae9db571a360f23)`);A&&(console.log(`${o} valid latestAddrsMap. console.dir(latestAddrsMap)... (I: e24de41622cabbef375172c3017cfd23)`),console.dir(b));let p=b[s];if(p)if(p===s){A&&console.log(`${o} no other found. possible idempotent replacement. addr: ${s} (I: 7f5bd5d3391be95919240f0e97976e22)`),await c();return}else{A&&console.log(`${o} different addr found. incoming ibgib addr is newer. existingLatestAddr: ${p}. incoming addr: ${s} (I: 6cadf13f82aabeb71d76babf1813e623)`);let h=await ae({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){A&&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 G=g.data.n;if($>G)A&&console.log(`${o} is newer (I: 040d05ac2032f08c7fd0c4d8b2887323)`),await c();else{A&&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: ${G}. 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(A&&console.log(`${o} no nCounter found. Trying brute force method.`),await si({ibGib:r,ibGibAddr:s,existingLatest:g,existingLatestAddr:p,tjpAddr:a,space:e})===s)await c();else return}else if(p===null){A&&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{A&&console.log(`${o} complete.`),A=n}}f(Te,"registerNewIbGib");async function Gt({type:r,rel8nName:e,ibGibsToRel8:t,ibGibsToUnRel8:o,addrsToUnRel8:n,linked:s,severPast:i,deletePreviousSpecialIbGib:a,space:c,zeroSpace:l,fnUpdateBootstrap:d,fnBroadcast:b}){let u=`[${Gt.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(w=>_({ibGib:w}));n??=o?.map(w=>_({ibGib:w}));let h=oe({type:r}),g=await Nr({key:h,space:c});if(!g)throw new Error("specialAddr not found (E: 680dfd1caa3e4d7cb0f593b893a10f0d)");let m=await ae({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],y=await $e({src:$,rel8nsToAddByAddr:p?{[e]:p}:void 0,rel8nsToRemoveByAddr:n?{[e]:n}:void 0,dna:!1,linkedRel8ns:s?[V.past,e]:[V.past],nCounter:!0}),G=y.newIbGib;if(i){if(y.intermediateIbGibs)throw new Error("new special creates intermediate ibgibs. so severing past is harder. (E: b580c0c56253494192e9c62212ee187d)");G.rel8ns.past=[],G.gib=await K({ibGib:G})}await re({resTransform:y,space:c});let I=_({ibGib:G}),S=ue({ibGib:G});return await de({key:h,addr:I,space:c,zeroSpace:l,fnUpdateBootstrap:d}),a&&await en({addr:g,space:c}),await Te({ibGib:G,fnBroadcast:b,space:c}),I}catch(p){throw console.error(`${u} ${p.message}`),p}}f(Gt,"rel8ToSpecialIbGib");async function Zo({ibGib:r,naive:e=!0,space:t}){let o=`[${Zo.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===P||await cn({ibGib:r,naive:e}))return r;if(!r.rel8ns){A&&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 b=r.rel8ns.tjp[0],u=await ae({addr:b,space:t});if(u.success&&u.ibGibs?.length===1)return u.ibGibs[0];{let p=u.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.`),A&&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 ae({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 Zo({ibGib:d,naive:e,space:t})}catch(n){throw console.error(`${o} ${n.message}`),n}}f(Zo,"getTjpIbGib");async function Vs({type:r,space:e,zeroSpace:t,fnUpdateBootstrap:o,fnBroadcast:n}){let s=`[${Vs.name}]`;try{if(!e)throw new Error("space falsy and localUserSpace not initialized. (E: 66e7d3ff098248f0a5ddda51853c92e6)");switch(r){case"roots":return zs({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});case"tags":return Ys({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});case"secrets":return Zs({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});case"encryptions":return Qs({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});case"outerspaces":return ei({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});case"autosyncs":return ti({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});case"robbots":return ri({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});case"apps":return oi({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});default:return ni({type:r,space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o})}}catch(i){throw console.error(`${s} ${i.message}`),i}}f(Vs,"createSpecial");async function Ce({type:r,skipRel8ToRoot:e,space:t,zeroSpace:o,fnUpdateBootstrap:n,fnBroadcast:s}){let i=`[${Ce.name}][${r||"falsy type?"}]`;try{A&&console.log(`${i} starting...`);let a=sn({type:r}),c=j.primitive({ib:a}),l=await br({src:c,destIb:a,linkedRel8ns:[V.past,V.ancestor],tjp:{uuid:!0,timestamp:!0},dna:!0,nCounter:!0});return await re({resTransform:l,space:t}),r!=="roots"&&r!=="latest"&&!e&&await Xs({ibGib:l.newIbGib,linked:!0,space:t,zeroSpace:o,fnBroadcast:s,fnUpdateBootstrap:n}),A&&console.log(`${i} complete.`),l.newIbGib}catch(a){throw console.error(`${i} ${a.message}`),a}}f(Ce,"createSpecialIbGib");async function Ys({space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}){let n=`[${Ys.name}]`;try{if(!r)throw new Error("space required. (E: 9c05b9bd355943a39ca47afef67a50eb)");let s=oe({type:"tags"}),i=await Ce({type:"tags",space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t}),a=_({ibGib:i});await de({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 Ws({...l,space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t})).newTagsAddr,await de({key:s,addr:a,space:r,zeroSpace:e,fnUpdateBootstrap:t});return a}catch(s){return console.error(`${n} ${s.message}`),null}}f(Ys,"createSpecial_Tags");async function Ws({text:r,icon:e,description:t,space:o,zeroSpace:n,fnUpdateBootstrap:s,fnBroadcast:i}){let a=`[${Ws.name}]`;try{if(A&&console.log(`${a} starting...`),!o)throw new Error("space required. (E: 5def0b1afab74b0c9286e3ac5060cb8f)");if(!r)throw new Error(`${a} text required`);e=e||Es,t=t||ws;let c=ft(r),l=j.primitive({ib:"tag"}),d=await j.firstGen({parentIbGib:l,ib:c,data:{text:r,icon:e,description:t},tjp:{uuid:!0,timestamp:!0},dna:!0,nCounter:!0}),b=d.newIbGib;await re({resTransform:d,space:o}),await Te({ibGib:b,space:o,fnBroadcast:i});let u=await Tc({tagIbGib:b,space:o,zeroSpace:n,fnUpdateBootstrap:s,fnBroadcast:i});return{newTagIbGib:b,newTagsAddr:u}}catch(c){throw console.error(`${a} ${c.message}`),c}finally{A&&console.log(`${a} complete.`)}}f(Ws,"createTagIbGibAndSundry");async function zs({space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}){let n=`[${zs.name}]`;try{if(!r)throw new Error("space required. (E: d12a8ea31163429fb6e53ff8e7579c57)");let s=oe({type:"roots"}),i=await Ce({type:"roots",space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t}),a=_({ibGib:i});await de({key:s,addr:a,space:r,zeroSpace:e,fnUpdateBootstrap:t});let l=["A","B","C","D","E","F","G"].map(b=>({text:`${b}root`,icon:No,description:Co})),d;for(let b=0;b<l.length;b++){let u=l[b],p=await Js({...u,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 de({key:s,addr:a,space:r,zeroSpace:e,fnUpdateBootstrap:t})}if(!d)throw new Error("(UNEXPECTED) firstRoot still falsy? (E: b2e2c926d242966e7ed7159e4b129e23)");if(await tn({root:d,space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}),a=await Nr({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(zs,"createSpecial_Roots");async function Js({text:r,icon:e,description:t,space:o,zeroSpace:n,fnUpdateBootstrap:s,fnBroadcast:i}){let a=`[${Js.name}]`;try{if(!o)throw new Error("space required. (E: cfa876e5c8c64a53a463ca7a645571c8)");r=r||ms,e=e||No,t=t||Co;let c=an(r),l=j.primitive({ib:"root"}),d=await j.firstGen({parentIbGib:l,ib:c,data:{text:r,icon:e,description:t},linkedRel8ns:[V.past,V.ancestor],tjp:{uuid:!0,timestamp:!0},dna:!0,nCounter:!0}),{newIbGib:b}=d;await re({resTransform:d,space:o});let u=await Gt({type:"roots",rel8nName:Do,ibGibsToRel8:[b],space:o,zeroSpace:n,fnUpdateBootstrap:s,fnBroadcast:i});return{newRootIbGib:b,newRootsAddr:u}}catch(c){throw console.error(`${a} ${c.message}`),c}}f(Js,"createRootIbGib");async function Zs({space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}){let n=`[${Zs.name}]`;try{if(!r)throw new Error("space required. (E: 340960cd5ad24addb300b23d9722e30a)");let s,i=oe({type:"secrets"}),a=await Ce({type:"secrets",space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t});return s=_({ibGib:a}),await de({key:i,addr:s,space:r,zeroSpace:e,fnUpdateBootstrap:t}),s}catch(s){return console.error(`${n} ${s.message}`),null}}f(Zs,"createSpecial_Secrets");async function Qs({space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}){let n=`[${Qs.name}]`;try{if(!r)throw new Error("space required. (E: 5084e698b6924e7090697ca50075ca59)");let s,i=oe({type:"encryptions"}),a=await Ce({type:"encryptions",space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t});return s=_({ibGib:a}),await de({key:i,addr:s,space:r,zeroSpace:e,fnUpdateBootstrap:t}),s}catch(s){return console.error(`${n} ${s.message}`),null}}f(Qs,"createSpecial_Encryptions");async function ei({space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}){let n=`[${ei.name}]`;try{if(!r)throw new Error("space required. (E: 99dd9e92535c470482eb9f6625a33831)");let s,i=oe({type:"outerspaces"}),a=await Ce({type:"outerspaces",space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t});return s=_({ibGib:a}),await de({key:i,addr:s,space:r,zeroSpace:e,fnUpdateBootstrap:t}),s}catch(s){return console.error(`${n} ${s.message}`),null}}f(ei,"createSpecial_OuterSpaces");async function ti({space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}){let n=`[${ti.name}]`;try{if(!r)throw new Error("space required. (E: f01cf6a4a460486796e16d505d629522)");let s,i=oe({type:"autosyncs"}),a=await Ce({type:"autosyncs",space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t});return s=_({ibGib:a}),await de({key:i,addr:s,space:r,zeroSpace:e,fnUpdateBootstrap:t}),s}catch(s){return console.error(`${n} ${s.message}`),null}}f(ti,"createSpecial_Autosyncs");async function ri({space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}){let n=`[${ri.name}]`;try{if(!r)throw new Error("space required. (E: f01cf6a4a460486796e16d505d629522)");let s,i=oe({type:"robbots"}),a=await Ce({type:"robbots",space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t});return s=_({ibGib:a}),await de({key:i,addr:s,space:r,zeroSpace:e,fnUpdateBootstrap:t}),s}catch(s){return console.error(`${n} ${s.message}`),null}}f(ri,"createSpecial_Robbots");async function oi({space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}){let n=`[${oi.name}]`;try{if(!r)throw new Error("space required. (E: f01cf6a4a460486796e16d505d629522)");let s,i=oe({type:"apps"}),a=await Ce({type:"apps",space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t});return s=_({ibGib:a}),await de({key:i,addr:s,space:r,zeroSpace:e,fnUpdateBootstrap:t}),s=await Dr({defaultAppData:Ps,defaultAppRel8ns:Rs,space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}),s=await Dr({defaultAppData:Ls,defaultAppRel8ns:Us,space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}),s=await Dr({defaultAppData:Ms,defaultAppRel8ns:ks,space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}),s}catch(s){return console.error(`${n} ${s.message}`),null}}f(oi,"createSpecial_Apps");async function Dr({defaultAppData:r,defaultAppRel8ns:e,space:t,zeroSpace:o,fnUpdateBootstrap:n,fnBroadcast:s}){let i=`[${Dr.name}]`;try{A&&console.log(`${i} starting... (I: 677f68789abdc7316887e8f38c764e22)`),A&&console.log(`${i} starting...`);let a=O(r),c=e?O(e):void 0;a.uuid=!a.uuid||a.uuid===Xo?await k():a.uuid;let{classname:l}=a,d=Ko({appData:a,classname:l}),b=await j.firstGen({ib:d,parentIbGib:j.primitive({ib:`app ${l}`}),data:a,rel8ns:c,dna:!0,linkedRel8ns:[V.ancestor,V.past],nCounter:!0,tjp:{timestamp:!0}});return await re({resTransform:b,space:t}),await Te({ibGib:b.newIbGib,fnBroadcast:s,space:t}),await Gt({type:"apps",rel8nName:wr,ibGibsToRel8:[b.newIbGib],fnBroadcast:s,fnUpdateBootstrap:n,space:t,zeroSpace:o})}catch(a){throw console.error(`${i} ${a.message}`),a}finally{A&&console.log(`${i} complete.`)}}f(Dr,"createApp");async function ni({type:r,space:e,zeroSpace:t,fnUpdateBootstrap:o,fnBroadcast:n}){let s=`[${ni.name}]`;try{if(!e)throw new Error("space required. (E: c7bbafcbe901418db4c6048f17f53091)");A&&console.log(`${s} creating special of type: ${r} (I: 283c8bb30ed6f9698b74b886c6078622)`);let i,a=oe({type:r}),c=await Ce({type:r,space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});return i=_({ibGib:c}),await de({key:a,addr:i,space:e,zeroSpace:t,fnUpdateBootstrap:o}),i}catch(i){return console.error(`${s} ${i.message}`),null}}f(ni,"createSpecial_Default");async function si({ibGib:r,ibGibAddr:e,existingLatest:t,existingLatestAddr:o,tjpAddr:n,space:s}){let i=`[${si.name}][${e}]`;try{if(A&&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 A&&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 A&&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 A&&console.log("existing by definition is newer"),o;if(a.includes(o))return A&&console.log("ibGib by definition is newer"),e;if(o===e)return A&&console.log("they're the same!"),o;if(o===n&&t.rel8ns?.tjp?.length===1)return A&&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 A&&console.log("existing must be newer because the ibGibAddr is the tjp, which is by definition first in unique past."),o;A&&console.log(`${i} brute forcing through iterating the pasts.`);let l,d=-1,b=f(async(h,g,m)=>{let $=h.rel8ns?.past||[];if($.includes(m))return l=_({ibGib:h}),-1;if($.length===0)return g;let y=g+$.length;if(d!==-1&&y>d)return l=_({ibGib:h}),-1;let G=await ae({addr:$[0],space:s});if(!G.success||G.ibGibs?.length!==1)throw new Error(`Couldn't load past addr (xPast[0]): ${$[0]}`);return b(G.ibGibs[0],g+$.length,m)},"getPastCount");A&&console.log(`${i} doing ibGibPastCount`);let u=await b(r,0,o);if(l)return l;A&&console.log(`${i} Doing existingPastCount`),d=u;let p=await b(t,0,e);return l||(u>p?(A&&console.log(`${i} ibGibPastCount (${u}) is longer than existingPastCount (${p}), so ibGib is newer.`),l=e):(A&&console.log(`${i} existingPastCount (${p}) is longer than ibGibPastCount (${u}), so ibGib is newer.`),l=o),l)}catch(a){throw console.error(`${i} ${a.message}`),a}finally{A&&console.log(`${i} complete.`)}}f(si,"getLatestAddr_Brute");function Tc({tagIbGib:r,space:e,zeroSpace:t,fnUpdateBootstrap:o,fnBroadcast:n}){return Gt({type:"tags",rel8nName:Po,ibGibsToRel8:[r],space:e,zeroSpace:t,fnUpdateBootstrap:o,fnBroadcast:n})}f(Tc,"rel8TagToTagsIbGib");function rn({space:r,scope:e}){let t=`[${rn.name}]`;try{if(A&&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(ee);)A&&console.log(`${t} scope contains ibgib delimiter...replacing... (I: 0f456fd7cc6552a799673a0c5b4a7d22)`),e=e.replace(ee,"_");let o=r.data.uuid,n=`${ps} ${o} ${e}`;return _({ib:n,gib:P})}catch(o){throw console.error(`${t} ${o.message}`),o}finally{A&&console.log(`${t} complete.`)}}f(rn,"getSpaceLockAddr");async function Se({space:r,scope:e,secondsValid:t,maxDelayMs:o,fn:n,callerInstanceId:s,maxLockAttempts:i}){let a=`[${Se.name}]`;try{if(A&&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;A&&console.log(`${a} attempting to acquire lock with scope ${e} (I: fed36d42a975b1c52897a4df804ac722)`);let l;o=(o??0)>0?o:hs;let d=0;i=i??!1?i:gs;do{if(l=await ii({space:r,scope:e,secondsValid:t,instanceId:s}),l?.data?.success)break;let u=Math.ceil(Math.random()*o);await le(u),d++}while(d<i);if(l?.data?.success)A&&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 b=`${a}[fn]`;try{A&&console.log(`${b} starting... (I: c2f7bedf95d3f1dd1f76de34a68d3f22)`),c=await n()}catch(u){throw console.error(`${b} ${u.message}`),u}finally{A&&console.log(`${b} unlocking space with scope: ${e} (I: 21034d9c3395499756e9000e40417d22)`),await ai({space:r,scope:e,instanceId:s}),A&&console.log(`${b} complete. (I: 79d8ac03714a4d429c7e6c2ac6e18d22)`)}return c}catch(c){throw console.error(`${a} ${c.message}`),c}finally{A&&console.log(`${a} complete.`)}}f(Se,"execInSpaceWithLocking");async function Wt({zeroSpace:r}){let e=`[${Wt.name}]`;try{if(A&&console.log(`${e} starting...`),!r)throw new Error("zeroSpace required. (E: 66fd8f21a5b2b572d18cdeb9472a7722)");let t=Je;A&&console.log(`${e} getting from zeroSpace...`);let o=await r.argy({ibMetadata:Ge({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 A&&console.log(`${e} bootstrapibGib found: ${H(s)}`),await Vo(s)?s:(A&&console.log(`${e} bootstrapIbGib was invalid. (I: cce66b26805404fc85525d565e1f8b22)`),null)}else return A&&console.log(`${e} bootstrapIbGib NOT found. (I: 421562993bf3464eb507d2967d311e22)`),null}catch(t){throw console.error(`${e} ${t.message}`),t}finally{A&&console.log(`${e} complete.`)}}f(Wt,"getValidatedBootstrapIbGib");async function Ac({zeroSpace:r,bootstrapIbGib:e,localSpaceId:t,lock:o,callerInstanceId:n,fnDtoToSpace:s,localSpaceCacheSvc:i}){let a=`[${Ac.name}]`;try{if(!r)throw new Error("zeroSpace required. (E: 0793781a98c456a666cfa9eb960bcd22)");if(!e)if(A&&console.log(`${a} bootstrap falsy, so loading it... (I: f2366e38283495a38b5501297aa34422)`),o){let d=Je;A&&console.log(`${a} using locked version of loading bootstrap... (I: 52b9b11999674e586d051c2b23f59b22)`),e=await Se({space:r,scope:d,fn:f(async()=>{let b=await Wt({zeroSpace:r});if(b)return b;throw new Error("(UNEXPECTED) unable to get bootstrap ibgib? (E: c111dc7627acbfb992134ddf4064ea23)")},"fn"),callerInstanceId:n,secondsValid:mr})}else A&&console.log(`${a} lock is false, so just getting the bootstrap ibgib (I: 49d55e5a824510bb3ee0ccd9f5ec3322)`),e=await Wt({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)");t=t??e.data[_e];let c=e.rel8ns[t][0],l=f(async()=>{let d=await r.argy({ibMetadata:Ge({space:r}),argData:{cmd:"get",ibGibAddrs:[c]}}),b=await r.witness(d);if(b?.data?.success&&b.ibGibs?.length===1){let u=b.ibGibs[0],p=await s(u);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?(A&&console.log(`${a} getting localSpaceId (${t}) WITH locking (I: c48a0e4ac5971cdbc57273dd35f8a522)`),await Se({space:r,scope:t,fn:f(()=>l(),"fn"),callerInstanceId:n,secondsValid:mr})):(A&&console.log(`${a} getting localSpaceId (${t}) WITHOUT locking (I: 48e504835dee4006839df8820d860b22)`),l())}catch(c){throw console.error(`${a} ${c.message}`),c}}f(Ac,"getLocalSpace");async function ii({space:r,scope:e,secondsValid:t,instanceId:o}){let n=`[${ii.name}]`;try{if(A&&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=rn({space:r,scope:e}),a,c=await ae({addr:i,space:r,force:!0});if(c.success&&c.ibGibs?.length===1?(a=c.ibGibs[0],a?.data?.expirationUTC?To({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)):A&&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=O(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:_o({seconds:t})}};let b=await r.argy({ibMetadata:Ge({space:r}),argData:{cmd:"put",force:!0,ibGibAddrs:[i]},ibGibs:[s]}),u=await r.witness(b);if(u.data?.success)if((u.data.addrsAlreadyHave??[]).includes(i)){A&&console.log(`${n} racelost! addrsAlreadyHave includes spaceLockAddr (${i}) (I: 2e8a1562947c40698110b64251141753)`);let p=await ae({addr:i,space:r,force:!0});if(p.success&&p.ibGibs?.length===1){let h=p.ibGibs[0];s=O(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: ${u.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{A&&console.log(`${n} complete.`)}}f(ii,"lockSpace");async function ai({space:r,scope:e,instanceId:t}){let o=`[${ai.name}]`;try{if(A&&console.log(`${o} starting...`),!r)throw new Error("space required. (E: 5c0a7197a75f483a82d74e5eea60df37)");if(!e)throw new Error("scope required. (E: c7f1dde9570f4df3b450faa2c2f85122)");let n=rn({space:r,scope:e}),s=await en({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")){A&&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{A&&console.log(`${o} complete.`)}}f(ai,"unlockSpace");async function Sc({space:r,zeroSpace:e,setSpaceAsDefault:t,createIfNotFound:o}){let n=`[${Sc.name}]`;try{if(A&&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 Wt({zeroSpace:e});if(a){if(A&&console.log(`${n} updating existing bootstrap (I: 977d4aa7ed47bef73b35743c05ce0722)`),a.data.spaceIds.includes(s)){A&&console.log(`${n} space already rel8d to bootstrap, possibly updating its addr (I: b5e2c515ef732d4bbcf02625a9e7c722)`);let c=a.rel8ns[s][0];c===i?A&&console.log(`${n} bootstrap already rel8d to space (I: c1be027b23e7350c64790a631cae2822)`):(A&&console.log(`${n} updating rel8ns[${s}] with newSpaceAddr (${i}). (Old address: ${c})(I: 297a9b0061fd471b8d28a06e04a6ad22)`),a.rel8ns[s]=[i])}else A&&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&&(A&&console.log(`${n} setting spaceId (${s}) as default space (I: f85eda6c6ad2b0bec9750ce3c7795b22)`),a.data[_e]=s)}else{if(!o){A&&console.log(`${n} bootstrapIbGib not found but createIfNotFound falsy, so returning early. (I: 5c67d85a8599a5ba4a6780f26a66ea22)`);return}A&&console.log(`${n} creating new bootstrap ibgib for spaceId (${s}) with address of (${i}) (I: 651959c27bf2ebc5be1f7f44e2b9e422)`);let{ib:c,gib:l}=R({ibGibAddr:Je});a=j.primitive({ib:c}),a.gib=l,a.data={[_e]:s,[$r]:[s]},a.rel8ns={[s]:[i]}}if(!a)throw new Error("(UNEXPECTED) bootstrapIbGib still falsy? (E: cf21d7f1756710a66aa0e6a28d762723)");A&&console.log(`${n} saving bootstrapIbGib: ${H(a)} (I: 3cceca0b98dde90e4a58a734be252322)`),await on({zeroSpace:e,bootstrapIbGib:a}),A&&console.log(`${n} complete.`)}catch(s){throw console.error(`${n} ${s.message}`),s}}f(Sc,"updateBootstrapIbGib");async function on({zeroSpace:r,bootstrapIbGib:e}){let t=`[${on.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]});A&&console.log(`${t} zeroSpace will witness/put... (I: 1be9aca22ffc4951b6690965a7aeae5b)`);let n=await r.witness(o);if(n?.data?.success)A&&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(on,"persistBootstrapIbGibInZeroSpace");async function Gc({spaceId:r,zeroSpace:e}){let t=`[${Gc.name}]`;if(!r)throw new Error("spaceId required. (E: 52f9c31405e24c2999e5a1b32d201a23)");if(!e)throw new Error("zeroSpace required. (E: a115f4007b2c4819a58cf093d5823b23)");await Se({space:e,scope:Je,fn:f(async()=>{let n=await Wt({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[$r]??[];if(i.length<=1)throw new Error(`Cannot delete space (${r}). It is the only remaining local space. (E: 9c27f71120014b08b5e9f89993380e23)`);if(r===s[_e])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[$r]=i.filter(a=>a!==r),n.rel8ns&&delete n.rel8ns[r],await on({zeroSpace:e,bootstrapIbGib:n})},"fn"),secondsValid:mr})}f(Gc,"deregisterLocalSpaceFromBootstrap");async function xc({spaceId:r,zeroSpace:e}){let t=`[${xc.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:Ge({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:Ge({space:e}),argData:{cmd:"delete",ibGibAddrs:[s]}});await e.witness(i)}}f(xc,"deleteSpaceRecordFromZeroSpace");function Ge({space:r}){return`${r.ib} ${me()}`}f(Ge,"getSpaceArgMetadata");function up({space:r}){return`${r.ib} ${me()}`}f(up,"getSpaceResultMetadata");function vc({space:r,spaceData:e,classname:t}){let o=`[${vc.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||us;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`${xr} ${gr} ${t} ${n} ${s} ${i} ${a}`}catch(n){throw console.error(`${o} ${n.message}`),n}}f(vc,"getSpaceIb");function Dc({ib:r}){let e=`[${Dc.name}]`;if(!r){let t=`${e} ib required (E: dd5244f62f964359a86e59bb08ee47e6)`;throw console.error(t),new Error(t)}return r.startsWith(`${xr} ${gr} `)}f(Dc,"isSpaceIb");function Cr({spaceIb:r}){let e=`[${Cr.name}]`;try{if(!r)throw new Error("spaceIb required (E: fa5424cfb7e846e2851562f2f417944f)");let[t,o,n,s,i,a,c]=r.split(" ");if(t!==xr)throw new Error(`invalid spaceIb (${r}). witnessAtom !== WITNESS_ATOM (E: 5ae1ca12cf8f30ae341f3e582b025224)`);if(o!==gr)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(qo.includes(a))l=a;else throw new Error(`invalid spaceIb (${r}). spaceType (${a}) is set but not a valid type. valid types: ${qo.join(", ")} (E: 838f4638a88cfbf3545a3a3a38b6dd24)`);let d;if(c&&c!=="undefined")if(Ho.includes(c))d=c;else throw new Error(`invalid spaceIb (${r}). spaceSubtype (${c}) is set but not a valid subtype. valid subtypes: ${Ho.join(", ")} (E: 5bdcf23027f94e73860e4340313b04ab)`);return{spaceClassname:n,spaceName:s,spaceId:i,spaceType:l,spaceSubtype:d}}catch(t){throw console.error(`${e} ${t.message}`),t}}f(Cr,"parseSpaceIb");async function Pe({ibGibs:r,addrs:e,tjps:t,tjpAddrs:o,space:n}){let s=`[${Pe.name}]`;try{if(A&&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(u=>d.includes(u))||i.add(l)}),A&&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:Ge({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(Pe,"getLatestAddrs");function nn({ibGib_Context:r}){let e=`[${nn.name}]`;try{if(A&&console.log(`${e} starting... (I: 5f583fd94d27731a65d514e731b8aa22)`),!zt({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{A&&console.log(`${e} complete.`)}}f(nn,"throwIfContextIsSpecial");async function Oc({ibGib_Context:r,rel8nName_Context:e,addr:t,space:o,zeroSpace:n,fnUpdateBootstrap:s,fnBroadcast:i}){let a=`[${Oc.name}]`;try{if(A&&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=zt({ibGib:r});c&&nn({ibGib_Context:r});let l=await $e({src:r,rel8nsToAddByAddr:{[ys]:[t]},rel8nsToRemoveByAddr:{[e]:[t]},dna:!0,nCounter:!0});if(await re({resTransform:l,space:o}),c){let d=_({ibGib:l.newIbGib}),b=Pr({ib:r.ib}),u=oe({type:b});await de({key:u,addr:d,space:o,zeroSpace:n,fnUpdateBootstrap:s})}await Te({ibGib:l.newIbGib,fnBroadcast:i,space:o})}catch(c){throw console.error(`${a} ${c.message}`),c}finally{A&&console.log(`${a} complete.`)}}f(Oc,"trash");async function Nc({ibGib_Context:r,rel8nName_Context:e,addr:t,space:o,zeroSpace:n,fnUpdateBootstrap:s,fnBroadcast:i}){let a=`[${Nc.name}]`;try{if(A&&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=zt({ibGib:r});c&&nn({ibGib_Context:r});let l=await $e({src:r,rel8nsToAddByAddr:{[$s]:[t]},rel8nsToRemoveByAddr:{[e]:[t]},dna:!0,nCounter:!0});if(await re({resTransform:l,space:o}),c){let d=_({ibGib:l.newIbGib}),b=Pr({ib:r.ib}),u=oe({type:b});await de({key:u,addr:d,space:o,zeroSpace:n,fnUpdateBootstrap:s})}await Te({ibGib:l.newIbGib,fnBroadcast:i,space:o})}catch(c){throw console.error(`${a} ${c.message}`),c}finally{A&&console.log(`${a} complete.`)}}f(Nc,"archive");function Cc(r){let e=`[${Cc.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(Cc,"spaceNameIsValid");var ce=!1;async function Pc({ibGib:r,rel8nNames:e,space:t}){let o=`[${Pc.name}]`;try{if(!r)throw new Error("ibGib required (E: a3c1b2d4e5f6a7b8c9d0e1f2a3b4c5d6)");if(!t)throw new Error("space required (E: b4d2c3e4f5a6b7c8d9e0f1a2b3c4d5e6)");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 ae({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: c5e3d4f5a6b7c8d9e0f1a2b3c4d5e6)`)}else n[s]=[]}return n}catch(n){throw console.error(`${o} ${E(n)}`),n}}f(Pc,"getRel8dIbGibs");async function Ae({parentPrimitiveIb:r,ib:e,ibRegExpPattern:t,data:o,rel8ns:n}){let s=`[${Ae.name}]`;try{if(!r)throw new Error("parentPrimitiveIb required. (E: 88ddf188cc5a4340b597abefba1481e2)");if(St({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):fs;if(!e.match(i))throw new Error(`invalid ib. does not match regexp (${i})`);let a=Object.keys(n??{}),c=[...ze,"tjp"];if(a.some(u=>c.includes(u)))throw new Error(`Invalid rel8ns. forbiddenRel8nNames: ${c}. rel8ns keys: ${Object.keys(n??{})}. (E: 837a993c265c4362b6aa0b1a234ea5f8)`);let b=(await j.firstGen({ib:e,parentIbGib:j.primitive({ib:r}),data:o,rel8ns:n,dna:!1,noTimestamp:!0,nCounter:!1})).newIbGib;return b?.rel8ns?.past&&delete b.rel8ns.past,b?.rel8ns?.tjp&&delete b.rel8ns.tjp,b?.rel8ns?.identity&&delete b.rel8ns.identity,b.gib=await K({ibGib:{ib:b.ib,data:b.data,rel8ns:b.rel8ns},hasTjp:!1}),b}catch(i){throw console.error(`${s} ${i.message}`),i}}f(Ae,"constantIbGib");function xp({addr:r}){return ci({addr:r})}f(xp,"getBinHashAndExt");function ci({addr:r}){let e=`[${ci.name}]`;try{if(!Vt({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(ci,"parseBinIb");function Vt({ibGib:r,addr:e}){let t=`[${Vt.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(Q))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(Q))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(Q))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(Vt,"isBinary");function sn({type:r}){if(!r.match(Ro))throw new Error(`special ibgib type must not have spaces and just be alphanumerics. regexp: ${Ro.source} (E: 6c1c92521b7f076cc4666e4915593723)`);return`meta special ${r}`}f(sn,"getSpecialIbGibIb");function Pr({ib:r}){let e=`[${Pr.name}]`;try{if(ce&&console.log(`${e} starting... (I: c82ba222bd345ee6b695df4d63a23322)`),!r)throw new Error("ib required (E: 08897145f7138e644fe01c4a59353322)");if(!zt({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(hr).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{ce&&console.log(`${e} complete.`)}}f(Pr,"getSpecialTypeFromIb");function Rc({type:r}){return`${sn({type:r})}^${P}`}f(Rc,"getSpecialIbGibAddr");function oe({type:r}){return`${_s} ${Rc({type:r})}`}f(oe,"getSpecialConfigKey");function zt({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(zt,"isSpecial");function an(r){let e=`[${an.name}]`;if(!r)throw new Error(`${e} text required.`);return`root ${r}`}f(an,"getRootIb");function ft(r){let e=`[${ft.name}]`;if(!r)throw new Error(`${e} tag required.`);return`tag ${r}`}f(ft,"tagTextToIb");function Rr({ibGibs:r,filterPrimitives:e}){let t=`[${Rr.name}]`;try{let o={},n={},s={};return(e?r.filter(a=>a.gib??a.gib!==P):r).forEach(a=>{li({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(Rr,"splitPerTjpAndOrDna");function Jt({ibGibs:r}){let e=`[${Jt.name}]`;try{ce&&console.log(`${e} starting...`);let{mapWithTjp_YesDna:t,mapWithTjp_NoDna:o}=Rr({ibGibs:r,filterPrimitives:!0}),n={...t,...o},s=Object.values(n),i=Io({items:s,keyFn:f(a=>a.data?.isTjp?_({ibGib:a}):a.rel8ns?.tjp?a.rel8ns?.tjp[0]??"":(ce&&console.log(`${e} neither isTjp nor x.rel8ns.tjp truthy (I: ec9a5597bf53dec1bd3d83350abbf823)`),""),"keyFn")});return ce&&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)}),ce&&console.log(`${e} after sort ibGibsWithTjpGroupedByTjpAddr: ${H(i)} (I: 9b9fff5ce61444a6cb06d62db9a99422)`),i}catch(t){throw console.error(`${e} ${t.message}`),t}finally{ce&&console.log(`${e} complete.`)}}f(Jt,"getTimelinesGroupedByTjp");function li({ibGib:r}){let e=`[${li.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(De)?!0:r.gib===P?!1:!!se({ibGibAddr:_({ibGib:r})}).tjpGib:(console.warn(`${e} ibGib.gib falsy. (W: 6400d780822b44d992846f1196509be3)`),!1)}f(li,"hasTjp");function ue({ibGib:r,defaultIfNone:e="undefined"}){let t=`[${ue.name}]`;try{let o=di({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(ue,"getTjpAddr");function di({ibGibs:r,defaultIfNone:e="undefined"}){let t=`[${di.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(di,"getTjpAddrs");async function cn({ibGib:r,naive:e=!0}){let t=`[${cn.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):(ce&&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(cn,"isTjp_Naive");function Re({ibGib:r}){let e=`[${Re.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&&(Vt({ibGib:r})?t.data=r.data.slice():t.data=O(r.data)),r.rel8ns&&(t.rel8ns=O(r.rel8ns)),t}f(Re,"toDto");function ln(r){let e=`[${ln.name}]`;try{return ce&&console.log(`${e} starting... (I: 57aef93fc6cc2309523b5c72a6b11823)`),!!r&&typeof r.ib=="string"}catch(t){throw console.error(`${e} ${t.message}`),t}finally{ce&&console.log(`${e} complete.`)}}f(ln,"isIbGib");function Xt({ibGib:r,data:e,timestamp:t}){let o=`[${Xt.name}]`;try{ce&&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()!==Er)return ce&&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()!==Er)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()!==Er)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{ce&&console.log(`${o} complete.`)}}f(Xt,"getTimestampInfo");async function dn({addrs:r,readCache_graph:e,readCache_array:t,space:o}){let n=`[${dn.name}]`;try{ce&&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){ce&&console.log(`${n} ${a.length} addrsNotFoundInCache: ${a} (I: fccbd18116ffb849f813aaebfc6c0826)`);let l=[o],d=a.concat();for(let b of l){let u=await ae({addrs:d,space:b});if(u.success&&u.ibGibs&&u.ibGibs.length===d.length)u.ibGibs.forEach(p=>s[_({ibGib:p})]=p),d=[];else if(u.ibGibs&&u.ibGibs.length>0){if(d=d.filter(p=>!u.ibGibs.some(h=>_({ibGib:h})===p)),d.length===0)break}else ce&&console.log(`${n} no addrs found in space (${b.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(b=>b.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{ce&&console.log(`${n} complete.`)}}f(dn,"getIbGibsFromCache_fallbackToSpaces");var fi=!1,Lc="space_gib_db",Uc="space_gib_store",Mc="space_gib_api_key";var kc="agent";var Cp=ft(kc);var Pp={dbName:Lc,storeName:Uc,additionalStoreNames:[bs],apiKeyName:Mc};var bi="0.0.19";var tt=!1,Mp="[web^gib timer]",Lr="ibgib";var jc="agent",kp="body-outline",jp="This tag tracks the active agents for the current local user space.",Bp=ft(jc),ui="#78f87e88",pi="#78f87e10",hi="#ffffff";var Fp="AUTOMATED_TEXT";var xe=!1;function gi(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(gi,"uint8ArrayToBase64");async function mi(r){let e=`data:application/octet-stream;base64,${r}`,n=await(await(await fetch(e)).blob()).arrayBuffer();return new Uint8Array(n)}f(mi,"base64ToUint8Array");async function Ur({graph:r}){let e=`[${Ur.name}]`;try{xe&&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 gi(r[n].data)});let o=JSON.stringify(t);return xe&&console.log(`${e} jsonString.length: ${o.length} (I: 56dec8ad0931ab8ba9b5ca3d4e66be25)`),o}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{xe&&console.log(`${e} complete.`)}}f(Ur,"serializeGraphToString");async function Mr({jsonString:r}){let e=`[${Mr.name}]`;try{xe&&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 mi(s.value))}return o}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{xe&&console.log(`${e} complete.`)}}f(Mr,"deserializeStringToGraph");async function Ei(r){let e=`[${Ei.name}]`;try{xe&&console.log(`${e} starting... (I: 8d306868b718596fe8f562bd5118d825)`);let t=await Ur({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{xe&&console.log(`${e} complete.`)}}f(Ei,"compressIbGibToBlob");async function Bc(r){let e=r.stream().pipeThrough(new DecompressionStream("gzip")),t=await new Response(e).text();return await Mr({jsonString:t})}f(Bc,"decompressIbGibFromBlob");async function fn({graph:r}){let e=`[${fn.name}]`;try{xe&&console.log(`${e} starting... (I: 1352f8540c08f0b725952df8f18c4825)`);let o=await(await Ei(r)).arrayBuffer(),n=new Uint8Array(o);return await gi(n)}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{xe&&console.log(`${e} complete.`)}}f(fn,"compressIbGibGraphToString");async function bn({compressedBase64:r}){let e=`[${bn.name}]`;try{xe&&console.log(`${e} starting... (I: 5f3fa940a2c8f8d7b877978ae7f87825)`);let t=await mi(r),o=new Blob([t],{type:"application/gzip"});return await Bc(o)}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{xe&&console.log(`${e} complete.`)}}f(bn,"decompressIbGibGraphFromString");var wi="export";var Zt=!1;function $i({data:r}){let e=`[${$i.name}]`;try{Zt&&console.log(`${e} starting... (I: 158dfaeb9613a1531be71a9735184624)`);let{graphSize:t,dependencyGraphAsString:o,timestamp:n}=r,s=o.length,i=me(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}),u=se({gib:d}).tjpGib??d,p=c.toISOString().slice(0,19).replace("T","_").replace(/:/g,"").replace(/ /g,"_");return`${wi} ${p} ${a} ${t} ${s} ${u}`}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Zt&&console.log(`${e} complete.`)}}f($i,"getRawExportIb");async function un({ibGib:r,metaspace:e,space:t,compress:o,live:n,ignoreErrors:s}){let i=`[${un.name}]`;try{if(Zt&&console.log(`${i} starting... (I: 0b6ba8608ba8bde0682a0936b9a01825)`),!r)throw new Error("(UNEXPECTED) ibGib falsy? (E: d2898eea744360865f0da5fb91baae22)");let a=_({ibGib:r}),c=[],l=await ie({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}),b=o?await fn({graph:d}):await Ur({graph:d}),u=ue({ibGib:r,defaultIfNone:"incomingAddr"})??a,p=new Date,h={contextIbGibAddr:a,tjpAddr:u,dependencyGraphAsString:b,graphSize:Object.keys(d).length,timestamp:ve(p),timestampMs:p.getMilliseconds()};o&&(h.compression="gzip");let g={ib:$i({data:h}),data:h},m=await K({ibGib:g,hasTjp:!1});return g.gib=m,Zt&&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{Zt&&console.log(`${i} complete.`)}}f(un,"getRawExportIbGib");var sh="ibgib-shell-ready",ih="ibgib-ui-busy",ah="ibgib-ui-message",ch="ibgib-identity-request-change",lh="ibgib-identity-changed",dh="ibgib-identity-update-available",fh="ibgib-identity-renewal-required";var yi=tt;async function vt({title:r,msg:e,prompt:t,showInput:o,defaultValue:n,okButtonTitle:s,cancelButtonTitle:i,isPassword:a,isBusy:c,animationEmoji:l}){let d=`[${vt.name}]`;try{yi&&console.log(`${d} starting... (I: 037b228a2568181cd3eb25dba4e03225)`);let b=document.getElementById("fullscreen-dialog"),u=document.getElementById("fullscreen-dialog-body"),p=document.getElementById("fullscreen-dialog-title"),h=document.getElementById("fullscreen-dialog-message"),g=document.getElementById("fullscreen-dialog-prompt-input"),m=document.getElementById("fullscreen-dialog-ok-button"),$=document.getElementById("fullscreen-dialog-cancel-button");if(!b||!u||!p||!h||!g||!m||!$)throw new Error("(UNEXPECTED) One or more dialog elements not found in DOM (E: 578e37c0271cc57a99e95e780ad18a25)");if(p.textContent=r||"",[...h.childNodes].forEach(I=>h.removeChild(I)),(e||"").split(`
9
+ `).forEach(I=>{let S=document.createElement("p");S.textContent=I,h.appendChild(S)}),l){let I=document.createElement("div");I.id="fullscreen-dialog-animation-emoji",I.textContent=l,I.style.fontSize="3.5rem",I.style.textAlign="center",I.style.margin="1.5rem 0",I.style.animation="spin-bounce 5s infinite ease-in-out",h.appendChild(I)}g.classList.remove("collapsed"),$.classList.remove("collapsed"),$.style.display="inline-block",m.style.display="inline-block",m.textContent=s||"OK";let G=f(I=>{(I.key==="Enter"||I.key===`
10
+ `)&&I.ctrlKey&&m.click()},"onKeypress");return c?(g.classList.add("collapsed"),$.style.display="none",m.style.display="none"):t||o?(g.addEventListener("keypress",G),o?(g.autofocus=!0,g.value=n??"",g.addEventListener("keypress",I=>{I.key==="Enter"&&m.click()}),a?(g.type="password",g.autocomplete="off",g.required=!0):(g.type="text",g.autocomplete="on",g.required=!1,g.attributes["auto-complete"]="on")):(g.autofocus=!1,g.classList.add("collapsed")),$.textContent=i||"Cancel"):(g.classList.add("collapsed"),$.style.display="none"),new Promise(I=>{if(c){let N=f(U=>{U.preventDefault()},"onCancelEvent");b.addEventListener("cancel",N);let x=f(()=>{b.removeEventListener("cancel",N),b.close()},"close"),C=f(({title:U,msg:Z,animationEmoji:z})=>{if(U!==void 0&&(p.textContent=U),Z!==void 0){[...h.childNodes].forEach(Ue=>{Ue.id!=="fullscreen-dialog-animation-emoji"&&h.removeChild(Ue)});let q=Z.split(`
11
+ `),$o=document.getElementById("fullscreen-dialog-animation-emoji");q.forEach(Ue=>{let Lt=document.createElement("p");Lt.textContent=Ue,$o?h.insertBefore(Lt,$o):h.appendChild(Lt)})}if(z!==void 0){let q=document.getElementById("fullscreen-dialog-animation-emoji");z?(q||(q=document.createElement("div"),q.id="fullscreen-dialog-animation-emoji",q.style.fontSize="3.5rem",q.style.textAlign="center",q.style.margin="1.5rem 0",q.style.animation="spin-bounce 5s infinite ease-in-out",h.appendChild(q)),q.textContent=z):q&&q.remove()}},"update");b.open||b.showModal(),le(1e3).then(()=>{u.scrollTo({top:0,behavior:"smooth"})}),I({close:x,update:C});return}let S=f(()=>{(t||o)&&g.removeEventListener("keypress",G),m.removeEventListener("click",w),$.removeEventListener("click",T),b.removeEventListener("close",v)},"removeEventListeners"),w=f(()=>{S();let N=o?g.value??"":"true";g&&(g.value=""),b.close(N),I(N)},"onOK"),T=f(()=>{S(),g&&(g.value=""),b.close(void 0),I(void 0)},"onCancel"),v=f(()=>{S(),g&&(g.value=""),b.close(void 0),I(void 0)},"onClose");m.addEventListener("click",w),$.addEventListener("click",T),b.addEventListener("close",v),b.open||b.showModal(),le(1e3).then(()=>{u.scrollTo({top:0,behavior:"smooth"})})})}catch(b){throw console.error(`${d} ${E(b)}`),b}finally{yi&&console.log(`${d} complete.`)}}f(vt,"showFullscreenDialog");var ne=tt;async function Fc({metaspace:r,space:e}){let t=`[${Fc.name}]`;try{ne&&console.log(`${t} starting... (I: 2ccb79537a75e7896bace84e6c710d25)`);let o=await r.getSpecialIbGib({type:hr.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{ne&&console.log(`${t} complete.`)}}f(Fc,"getTagsIbGib");function hn({scope:r,ibGib:e,ibGibAddr:t,defaultNameIfError:o}){let n=`[${hn.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(u=>te({gib:R({ibGibAddr:u}).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 b=d.at(-1);s=R({ibGibAddr:b}).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(),ne&&console.log(`${n} ancestorIbOrAtom: ${a} (I: genuuid)`);let l=`${a}_${r}index`;return ne&&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(hn,"getIndexNameFromIbGib");async function qc({scope:r,ibGib:e,metaspace:t,space:o,skipGetLatest:n}){let s=`[${qc.name}]`;try{if(ne&&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=hn({scope:r,ibGib:e}),a=ue({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){ne&&console.log(`${s} special ${r} index ibGib not found for indexSpecialIbGibType (${i}). No coupled ibgib registered, returning undefined. (I: genuuid)`);return}let u=(d.data.coupleMap??d.data.agentMap??{})[a];if(!u){ne&&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?u:await t.getLatestAddr({addr:u,space:o})??u,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 Se({scope:i,secondsValid:180,maxDelayMs:100,maxLockAttempts:1800,space:o,callerInstanceId:s+me(),fn:c})}catch(i){throw console.error(`${s} ${E(i)}`),i}finally{ne&&console.log(`${s} complete.`)}}f(qc,"getLocalCoupledIbGibForDomainIbGib");async function Hc({scope:r,domainIbGib:e,localIbGib:t,metaspace:o,space:n}){let s=`[${Hc.name}]`;try{ne&&console.log(`${s} starting... (I: 217ae68e0c820e48f4c00409f7f14325)`);let i=hn({scope:r,ibGib:e}),a=ue({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 Se({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 b=d.data.coupleMap??d.data.agentMap,u=b?O(b):{},p=u[a];if(p)if(p===c){ne&&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)`);u[a]=c;let h=await Me({src:d,dataToAddOrPatch:{coupleMap:u},dna:!1,linkedRel8ns:[V.past],nCounter:!0}),g=h.newIbGib;await re({resTransform:h,space:n});let m=oe({type:i});await o.setConfigAddr({key:m,addr:_({ibGib:g}),space:n}),await o.registerNewIbGib({ibGib:g,space:n})},"fn")}),ne&&console.log(`${s} Registered domain ${a} with agent ${c}`)}catch(i){throw console.error(`${s} ${E(i)}`),i}finally{ne&&console.log(`${s} complete.`)}}f(Hc,"coupleDomainIbGibWithLocalIbGibViaIndex");function bt(){let r=`[${bt.name}]`;try{ne&&console.log(`${r} starting... (I: 890f53e984d69461d9f4ded8741fcc25)`);let e=globalThis[Lr];return e||(console.log(`${r} initializing globalThis.${Lr}... (I: 9d9ff1813448d9a1b82b0e5790a74825)`),e={},globalThis[Lr]=e),e}catch(e){throw console.error(`${r} ${E(e)}`),e}finally{ne&&console.log(`${r} complete.`)}}f(bt,"getIbGibGlobalThis_IbGib");async function _i({delayIntervalMs:r=50}={delayIntervalMs:50}){let e=`[${_i.name}]`;try{ne&&console.log(`${e} starting... (I: 4acc22d08dd1100503f9b0423f302925)`);let t;for(;!t;)bt().metaspace&&(t=bt().metaspace),t||(console.log(`${e} metaspace still not initialized. delayIntervalMs: ${r} until next retry... (I: 490f77ac4ded1d7d3c0340e460404125)`),await le(r));return t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{ne&&console.log(`${e} complete.`)}}f(_i,"getGlobalMetaspace_waitIfNeeded");function Kc({ibGibAddr:r,gib:e,ibGib:t,translucentAlpha:o=10}){let n=`[${Kc.name}]`;try{ne&&console.log(`${n} starting... (I: 3b70af42d1c4f6ae91870f3a15c6c625)`),!r&&!e&&!t&&(e=P),e??=t?.gib??R({ibGibAddr:r}).gib;let s=se({gib:e});o??=10;let i="";if(s.isPrimitive)return{gib:e,gibInfo:s,punctiliarColor:ui,punctiliarColorTranslucent:pi,punctiliarColorContrast:hi};i=s.tjpGib??s.punctiliarHash??e;let[a,c,l]=Ii(o,s.punctiliarHash??e),[d,b,u]=s.tjpGib?Ii(o,s.tjpGib):[void 0,void 0,void 0];return{gib:e,gibInfo:s,punctiliarColor:a,punctiliarColorTranslucent:c,punctiliarColorContrast:l,tjpColor:d,tjpColorTranslucent:b,tjpColorContrast:u}}catch(s){let i=`${n} ${E(s)}`;return console.error(i),{gib:e??P,gibInfo:{isPrimitive:!0},punctiliarColor:"#ff0000",punctiliarColorTranslucent:"#ff000010",punctiliarColorContrast:"#ffffff",errorMsg:i}}finally{ne&&console.log(`${n} complete.`)}}f(Kc,"getDeterministicColorInfo");function Xc(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(Xc,"hslToHex");function Ii(r,e){let o=(parseInt(e.substring(0,8),16)||0)%360,n=Xc(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)),b=Math.round(d/100*255).toString(16).padStart(2,"0"),u=`${n}${b}`;return[n,u,l]}f(Ii,"getColorStrings");var fe=tt;function Ai(r){return new TextDecoder().decode(r)}f(Ai,"uint8ArrayToString");var Ti=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 Vc({msg:r,title:e,confirm:t,noNewLine:o,rl:n,defaultValue:s,dontCloseRl:i,cancelable:a}){let c=`[${Vc.name}]`;try{if(!r)throw new Error("msg required (E: 7f4d67bca4cf98ea95fa110aabc98924)");let l,d=0,b=5;do{if(d++,d>=b)throw new Error("max attempts reached (E: 1ef20ae955622d4b39479f3da91a1d25)");await le(50),l=await vt({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(Vc,"promptForText");async function Yc({msg:r,confirm:e}){let t=`[${Yc.name}]`;try{fe&&console.log(`${t} starting... (I: 795a4ce348ddb9a5119770f4c572ac24)`);let o,n=!0,s=0,i=5;do{if(s++,s>=i)throw new Error("max attempts reached (E: d4166b4bf37aff0c6d44567792e9ad25)");if(await le(50),o=await vt({title:n?"Shh...":"Secrets didn't match, try again...",msg:r||"Enter Your Secret...",prompt:!0,showInput:!0,isPassword:!0,defaultValue:void 0}),o===void 0)throw new Error("user cancelled (E: 91519d04378e84106f3df8eb36d99725)");if(e){await le(250);let a=await vt({title:"Shh...",msg:"Confirm...",prompt:!0,showInput:!0,isPassword:!0,defaultValue:void 0});a===void 0&&(o=void 0),o!==a&&(o=void 0,n=!1,await le(250))}}while(o===void 0);return o}catch(o){throw console.error(`${t} ${E(o)}`),o}finally{fe&&console.log(`${t} complete.`)}}f(Yc,"promptForSecret");async function Wc({msg:r,title:e,skipHitEnterToContinue:t}){let o=`[${Wc.name}]`;try{if(!r)throw new Error("msg required (E: ffcf7dd00324df7cea2792223d229524)");try{e??="",await le(50),await vt({title:e,msg:r})}catch(n){throw n}}catch(n){throw console.error(`${o} ${E(n)}`),n}}f(Wc,"alertUser");async function zc({exportIbGibJsonString:r,metaspace:e}){let t=`[${zc.name}]`;try{debugger;if(fe&&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)`,b=new Error(d);throw b.cause=l,b}try{let l=await ie({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)`,b=new Error(d);throw b.cause=l,b}let i;if(s.data.compression)switch(s.data.compression){case"gzip":i=await bn({compressedBase64:s.data.dependencyGraphAsString});break;default:throw new Error(`unknown value of rawExportIbGib.data.compression: ${s.data.compression} (E: 784672fae568312d887ddbb841199925)`)}else i=await Mr({jsonString:s.data.dependencyGraphAsString});let a={};for(let[l,d]of Object.entries(i)){let b=await ie({ibGib:d})??[];b.length>0&&(a[l]=b)}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:
12
+ ${H({validationErrorMap:a})} (E: e63f38b182a84122d83a55befb369825)`);return[s,i]}catch(o){throw console.error(`${t} ${E(o)}`),o}finally{fe&&console.log(`${t} complete.`)}}f(zc,"getRawExportIbGibAndGraphFromJsonString");async function Jc({ibGib:r,compress:e,metaspace:t,space:o}){let n=`[${Jc.name}]`;try{if(fe&&console.log(`${n} starting... (I: 623d9463d919683be81f749821a95825)`),te({ibGib:r}))throw new Error("ibGib is primitive. Can't export primitive. (E: dd42c42e9fda0707e81c692af1a2a225)");let s=await un({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),b=`${_({ibGib:i})}.json`,u=document.createElement("a");u.setAttribute("style","none"),u.setAttribute("href",l),u.setAttribute("download",b);let p=document.getElementsByTagName("div")[0];p.appendChild(u),u.click(),p.removeChild(u)}catch(s){throw console.error(`${n} ${E(s)}`),s}finally{fe&&console.log(`${n} complete.`)}}f(Jc,"exportIbGib");function Si({id:r,shadowRoot:e}){let t=`[${Si.name}]`;try{fe&&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{fe&&console.log(`${t} complete.`)}}f(Si,"getElementById_throwsIfFalsy");function Hh(r,e){return Si({id:e,shadowRoot:r})}f(Hh,"shadowRoot_getElementById");function Zc(){let r=`[${Zc.name}]`;try{fe&&console.log(`${r} starting... (I: 62a29f9982b4b5ecd91ff58ca4dd6825)`);let e=bt();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{fe&&console.log(`${r} complete.`)}}f(Zc,"getGlobalStoreName");function Qc(){let r=`[${Qc.name}]`;try{fe&&console.log(`${r} starting... (I: 8c8f08728fc7384f87697377358cc825)`);let e=bt();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{fe&&console.log(`${r} complete.`)}}f(Qc,"getGlobalDbName");function el(){let r=`[${el.name}]`;try{fe&&console.log(`${r} starting... (I: 59a2510a85051f97ed15fbc8825b6825)`);let e=bt();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{fe&&console.log(`${r} complete.`)}}f(el,"getGlobalIndexedDbKey_APIKey");async function gn({infos:r}){let e=`[${gn.name}]`;try{fe&&console.log(`${e} starting... (I: 4d41880fb748ee2302a624a255665825)`);for(let t of r){let{dbName:o,storeNames:n}=t;await En({dbName:o})||await jr({dbName:o});for(let i of n)await mn({dbName:o,storeName:i})}}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{fe&&console.log(`${e} complete.`)}}f(gn,"initAppStorage");var pe=tt,Gi=0;async function jr({dbName:r,storeName:e,version:t,logalot:o=!1}){let n=`[${jr.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);Gi++,console.log(`${n} initRequestCount: ${Gi} (I: 294d5f0b12ffe5512bacebe891824d25)`);let b;d.onupgradeneeded=u=>{try{i=u.target.result,o&&console.timeLog(n+s,"onupgradeneeded... (I: e748b4ddb445d77cb10a7ba158b49125)"),e&&(i.objectStoreNames.contains(e)?b=!0:(b=!1,i.createObjectStore(e,{keyPath:"key"})))}catch(p){console.error(`${n}[openDBRequest.onupgradeneeded] ${E(p)} (E: 4a5fa1b0850be47e28bee653da287325)`),l(p)}},d.onblocked=u=>{console.log(`${n}[openDBRequest.onblocked] openDBRequest blocked...time wasted a bit here. version change event (old -> new): ${u.oldVersion} -> ${u.newVersion} (I: 9074ebf4afdba54d6f9d41b360b96a25)`),console.dir(u)},d.onsuccess=u=>{try{o&&console.log("init success (I: 297a5a71e405a0b56413af813f248d24)"),o&&console.timeLog(n+s,"onupgradeneeded... (I: e748b4ddb445d77cb10a7ba158b49125)"),i=u.target.result,e&&(b??=i.objectStoreNames.contains(e),o&&console.log(`${n} ${r} store "${e}" ${b?"already exists":"does not exist"}. (I: db64712bc69c5287b1cf77af1fc13d24)`)),c()}catch(p){console.error(`${n}[openDBRequest.onsuccess] ${E(p)}`),l(p)}},d.onerror=u=>{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(jr,"initializeStorage");async function xi({dbName:r,logalot:e=!1}){let t=`[${xi.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(xi,"storageGetDBInfo");async function mn({dbName:r,storeName:e,logalot:t=!1}){let o=`[${mn.name}]`,n=crypto.randomUUID();t&&console.time(o+n);let s;try{if(t&&console.log(`${o} starting... (I: 029f7caa8ea5ea08a865f3924c82b624)`),!(await indexedDB.databases()).filter(b=>b.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((b,u)=>{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"),b()},p.onerror=h=>{debugger;console.error(`${o}[openDBRequest.onerror] ${E(p.error)} (E: 63695744e9e59ff8019e04ceeb8e2524)`),u(p.error)}}),t&&console.timeLog(o+n),a){t&&console.log(`${o} store ${e} already existed. (I: a2263b510c18240fc59fca54e3892324)`);return}let c=await xi({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 jr({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(mn,"storageCreateStoreIfNotExist");async function pn({dbName:r,version:e,storeName:t,key:o,value:n,logalot:s=!1}){let i=`[${pn.name}]`,a;try{s&&console.log(`${i} starting... (I: bf7316c244888cb8ead2d3aac1d9f625)`),await new Promise((l,d)=>{try{s&&console.log(`${i} starting... (I: 81df59e3961d711ce5d8f2ae3e2f3824)`);let b=indexedDB.open(r,e);b.onsuccess=u=>{a=u.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)}},b.onerror=u=>{debugger;console.error(`${i}[putRequest.onerror] ${E(b.error)} (E: 7a946d99ede2b248df4dcfea4ac99724)`),d(b.error)}}catch(b){console.error(`${i} ${E(b)}`),d(b)}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(pn,"storagePut");async function kr({dbName:r,version:e,storeName:t,key:o,logalot:n=!1}){let s=`[${kr.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 b=indexedDB.open(r,e);b.onsuccess=u=>{i=u.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(Ai(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)}},b.onerror=u=>{debugger;console.error(`${s}[openDBRequest.onerror] ${E(b.error)} (E: 074963a908fa9a075f01c73cae829224)`),d(b.error)}}catch(b){console.error(`${s} ${E(b)}`),d(b)}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(kr,"storageGet");async function En({dbName:r,store:e}){let t=`[${En.name}]`,o;try{return pe&&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&&(pe&&console.log(`${t} closing db ${r}... (I: 8782d9eea285cf9eb638d493a421a625)`),o.close(),pe&&console.log(`${t} closing db ${r} complete. (I: 76a0c5dea2643e2bb84c82c8446a8125)`)),pe&&console.log(`${t} complete.`)}}f(En,"storageDBExists");async function tl({dbName:r,storeName:e,pathToRm:t}){let o=`[${tl.name}]`,n=pe;pe&&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),b=IDBKeyRange.lowerBound(t),u=d.openCursor(b);u.onerror=()=>{debugger;console.error(`${o}[openCursorRequest.onerror] ${E(u.error)} (E: caefdda2bb95f92e9fb8d89ee412b524)`),a(u.error)},u.onsuccess=()=>{try{let p=0,h=u.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 pe&&console.log(`${o} rmCount: ${p} (I: e4bc613a5514c0942484b79267e16724)`),i();else pe&&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&&(pe&&console.log(`${o} closing db ${r}... (I: 39b4ba83de4bdfd541e3384ebab27425)`),s.close(),pe&&console.log(`${o} closing db ${r} complete. (I: e4015b9436c4b2bc0ccf0e11e2037925)`)),pe&&console.log(`${o} complete.`),pe=n})}f(tl,"storageRmRF");async function rl({dbName:r,storeName:e,dirPath:t,withFileTypes:o=!1}){let n=`[${rl.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 u=s.transaction(e,"readonly").objectStore(e),p=t.endsWith("/")?t:t+"/",h=IDBKeyRange.lowerBound(p),g=u.openCursor(h),m=new Set,$=[];g.onerror=()=>{debugger;console.error(`${n}[openCursorRequest.onerror] ${E(g.error)}`),l(g.error)},g.onsuccess=()=>{try{let y=g.result;if(y){let G=y.key.toString();if(G.startsWith(p)&&G!==p){let I=G.substring(p.length),S=I.split("/")[0];if(o){let w=I.substring(S.length).startsWith("/");$.push({name:S,isDirectory:f(()=>w,"isDirectory"),isFile:f(()=>!w,"isFile"),isBlockDevice:f(()=>!1,"isBlockDevice"),isCharacterDevice:f(()=>!1,"isCharacterDevice"),isSymbolicLink:f(()=>!1,"isSymbolicLink"),isFIFO:f(()=>!1,"isFIFO"),isSocket:f(()=>!1,"isSocket")})}else m.add(S);y.continue()}else G.startsWith(p)?y.continue():c(o?$:Array.from(m))}else c(o?$:Array.from(m))}catch(y){console.error(`${n}[openCursorRequest.onsuccess] ${E(y)}`),l(y)}}}})}catch(i){throw console.error(`${n} ${E(i)}`),i}finally{s&&(pe&&console.log(`${n} closing db ${r}... (I: 39b4ba83de4bdfd541e3384ebab27425)`),s.close(),pe&&console.log(`${n} closing db ${r} complete. (I: e4015b9436c4b2bc0ccf0e11e2037925)`))}}f(rl,"storageReaddir");var Dt=fi;async function ol(r){let e=`[${ol.name}]`;try{Dt&&console.log(`${e} starting... (I: 1905af1827a34ca8a5507fe0c5085b01)`),await gn({infos:[{dbName:r.dbName,storeNames:[r.storeName,...r.additionalStoreNames??[]]}]})}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Dt&&console.log(`${e} complete.`)}}f(ol,"initIbGibStorage");function vi(r){let e=`[${vi.name}]`;try{Dt&&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 kr({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{Dt&&console.log(`${e} complete.`)}}f(vi,"initIbGibGlobalThis");function sg(r){if(!globalThis.ibgib?.spaceGib){if(!r)throw new Error("Global context not initialized and config not provided.");vi(r)}return globalThis.ibgib.spaceGib}f(sg,"getIbGibGlobalThis_SpaceGib");async function nl(r){let e=`[${nl.name}]`;try{Dt&&console.log(`${e} starting... (I: 3123b18eb29b480bad056a9a029b9ad4)`),await(await import(r)).bootstrapSpaceGibApp()}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Dt&&console.log(`${e} complete.`)}}f(nl,"dynamicallyLoadBootstrapScript");var sl="hash-reveal-v1",Le={hash_reveal_v1:sl},Di=Object.values(Le);var il="top-up",al="replace-all",cl="consume",ll="delete-all",we={topUp:il,replaceAll:al,consume:cl,deleteAll:ll},Oi=Object.values(we);var dl="add-pool",fl="remove-pool",bl="replace-pool",ul="change-password",Ot={add_pool:dl,remove_pool:fl,replace_pool:bl,change_password:ul},cg=Object.values(Ot);var Qt="keystone",wn=/^\w[\w\-.]*$/,$n=/^[a-zA-Z0-9\-_]{1,64}$/,yn=/^[a-zA-Z0-9_\-.]{1,63}$/,In=/^[a-zA-Z0-9\s.,!?:;'"\-()[\]_+=@#$%&*\/]{0,128}$/,Ni=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,_n=1e3,Nt="revoke",he="manage",pl="sign",Br="sync",Ci="connect",Tn={REVOKE:Nt,MANAGE:he,SIGN:pl,SYNC:Br,CONNECT:Ci},pg=Object.values(Tn);var Xe=he;var hl=Ci,gl=Br;var Pi=200,Ri=2,Li=2,Ui=5,Mi=we.topUp,ki=ge.sha_256,ji=1,Bi=2e3,Fi=5,qi=5,Hi=16,Ki=we.replaceAll,Xi=ge.sha_512,Vi=10,ut=50;var Fr=!1,An=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}},Sn=class r extends An{static{f(this,"KeystoneConfigBuilder_HashV1")}lc=`[${r}]`;_algo;_rounds;withHash({algo:e,rounds:t}){let o=`${this.lc}[${this.withHash.name}]`;try{return Fr&&console.log(`${o} starting... (I: 15d1b3bd2e98bba33fc6c78228755826)`),this._algo=e,this._rounds=t,this}catch(n){throw console.error(`${o} ${E(n)}`),n}finally{Fr&&console.log(`${o} complete.`)}}build(){let e=`${this.lc}[${this.build.name}]`;try{if(Fr&&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:Le.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{Fr&&console.log(`${e} complete.`)}}},er=class{static{f(this,"KeystoneConfig")}static hash(){return new Sn}};function Ig(r){if(r.type&&r.type!==Le.hash_reveal_v1)throw new Error(`invalid type (${r.type}). Only ${Le.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 er.hash().withId(t).withSalt(e).withSize(o??Pi).withHybrid({seqCount:n??Ri,randCount:s??Li}).withTargetBinding(i??Ui).withReplenishStrategy(a??Mi).withHash({algo:l??ki,rounds:d??ji}).forVerbs(c??[]).build()}f(Ig,"createStandardPoolConfig");function ml(r){if(r.type&&r.type!==Le.hash_reveal_v1)throw new Error(`invalid type (${r.type}). Only ${Le.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 er.hash().withId(t).withSalt(e).withSize(o??Bi).withHybrid({seqCount:n??Fi,randCount:s??qi}).withTargetBinding(i??Hi).withReplenishStrategy(a??Ki).withHash({algo:l??Xi,rounds:d??Vi}).forVerbs(c??[]).build()}f(ml,"createHighSecurityPoolConfig");function _g(r){return ml({...r,id:r.id??Xe,verbs:r.verbs??[Tn.MANAGE]})}f(_g,"createManagePoolConfig");function Yi({template:r,salt:e}){let t=r.behavior;return er.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(Yi,"createPoolConfigFromJson");var El="recursive-salt-wrap",Gn={recursive_salt_wrap:El},Wi=Object.values(Gn);var qr=!1;async function wl({masterSecret:r,kdfOpts:e}){let t=`[${wl.name}]`;try{qr&&console.log(`${t} starting... (I: 268e87ec311874ee6822bf459c5a5426)`);let o=e.strategy;switch(o){case Gn.recursive_salt_wrap:return await Ct({masterSecret:r,salt:e.salt,rounds:e.rounds,algorithm:e.algorithm});default:throw new Error(`Unknown KDF strategy: ${o}. valid values: ${Wi.join(", ")} (E: c81258e9d9481eb0f88385a825193226)`)}}catch(o){throw console.error(`${t} ${E(o)}`),o}finally{qr&&console.log(`${t} complete.`)}}f(wl,"deriveKey");async function Ct({masterSecret:r,salt:e,rounds:t,algorithm:o=ge.sha_256}){let n=`[${Ct.name}]`;try{qr&&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{qr&&console.log(`${n} complete.`)}}f(Ct,"kdf_recursiveSaltWrap");var zi={$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 Ji={$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 Zi={$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 Hr={$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 Qi={$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 ea={$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 ta={$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 Kr=new Map,tr=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: 7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d)");if(!t||typeof t!="object")throw new Error(`Valid KeystonePolicyConfigTemplate is required to register custom profile '${e}'. (E: 8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e)`);Kr.set(e,JSON.parse(JSON.stringify(t)))}static clearCustomProfiles(){Kr.clear()}static fromTemplate(e){if(!e||typeof e!="object")throw new Error("Valid KeystonePolicyConfigTemplate is required for KeystoneProfileBuilder.fromTemplate. (E: 9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f)");return new r(e)}static buildKeystone(e){if(!e||typeof e!="string")throw new Error("Profile name is required for KeystoneProfileBuilder. (E: 9a8b7c6d5e4f3210987654321fedcba0)");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: 8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3d)`);if(Kr.has(e))return new r(Kr.get(e));let o;switch(e){case"primary-profile.dev":o=zi;break;case"primary-profile.staging":o=Ji;break;case"primary-profile.prod":o=Zi;break;case"sync-profile.dev":o=Hr;break;case"sync-profile.staging":o=Qi;break;case"sync-profile.prod":o=ea;break;case"sync-profile.test-short-ttl":o={...JSON.parse(JSON.stringify(Hr)),metadata:{...Hr.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=ta;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=Yi({template:n,salt:a});e.push(c)}return e}};var Xr=class{static{f(this,"KeystoneStrategy")}config;constructor(e){this.config=e}};var Vr=class r extends Xr{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 Ct({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 pt=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 Vr(e);default:throw new Error(`Unknown strategy type: ${e.type} (E: 4e3c2f7129a241c1b687555e678c1065)`)}}catch(o){throw console.error(`${t} ${o.message}`),o}}};var B=!1;async function rr({ibGib:r,ibGibs:e,ibGibAddr:t,ibGibAddrs:o,live:n,gotten:s,tjpAddrsAlreadyAnalyzed:i,skipAddrs:a,skipRel8nNames:c,onlyRel8nNames:l,maxRetries:d,msBetweenRetries:b,space:u,spaces:p,timeLogName:h,mapTjpAddrToLatestAddrsInSpace:g}){let m=`[${rr.name}]`;try{B&&console.log(`${m} starting... (I: c2a4426c22e849611ca0cedabe683a22)`);let $=await or({ibGib:r,ibGibs:e,ibGibAddr:t,ibGibAddrs:o,live:n,gotten:s,tjpAddrsAlreadyAnalyzed:i,skipAddrs:a,skipRel8nNames:c,onlyRel8nNames:l,maxRetries:d,msBetweenRetries:b,space:u,spaces:p,timeLogName:h,mapTjpAddrToLatestAddrsInSpace:g});if(Object.values($).filter(y=>y.ib.startsWith("comment ")).forEach(y=>{console.table(y)}),B){console.log(`${m} graph size: ${Object.keys($).length} (I: c6cb5e7e1e2611d35b9006fac6503d22)`);let y=Object.values($).filter(G=>G.ib.startsWith("comment ")||G.ib.startsWith("pic ")).map(G=>G.ib);dr(y).forEach(G=>console.log(G))}return $}catch($){throw console.error(`${m} ${$.message}`),$}finally{B&&console.log(`${m} complete.`)}}f(rr,"getDependencyGraph");async function ra({ibGib:r,ibGibs:e,ibGibAddr:t,ibGibAddrs:o,live:n,gotten:s,tjpAddrsAlreadyAnalyzed:i,skipAddrs:a,skipRel8nNames:c,onlyRel8nNames:l,maxRetries:d,msBetweenRetries:b,space:u,spaces:p,timeLogName:h,mapTjpAddrToLatestAddrsInSpace:g}){let m=`[${ra.name}]`;try{if(B&&console.log(`${m} starting... (I: bd6807477f679345df9dddefe0b4e922)`),u&&(p??[]).length>0)throw new Error("space and spaces parameters are mutually exclusive. Pass either space or spaces, not both. (E: 994a5323e4214f4e95d5bb2b89f89090)");let $=u?[u]:(p??[]).filter(y=>!!y);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(y=>!te({gib:R({ibGibAddr:y}).gib})).filter(y=>!a.includes(y)),e=(e??[]).filter(y=>!te({ibGib:y})).filter(y=>!a.includes(_({ibGib:y}))),r&&!te({ibGib:r})&&!e.some(y=>y.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:b,space:void 0,spaces:$,timeLogName:h,mapTjpAddrToLatestAddrsInSpace:g}}catch($){throw console.error(`${m} ${$.message}`),$}finally{B&&console.log(`${m} complete.`)}}f(ra,"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{B&&console.log(`${l} starting... (I: 67b2be37ff24393fff56e229304da122)`);let d=c??(a?[a]:[]);if(d.length===0)throw new Error("(UNEXPECTED) spaces empty? (E: aa9f657695717034b3581066932d7d23)");let b=[];r??=[],e??=[],o??=[],t??={};let u=[],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)?b.push(t[m]):u.push(e[g]))}if(B&&console.log(`${l}[analyze debugging] addrsToGetFromSpace (${u.length}):
13
+ ${u.join(`
14
+ `)} (I: b45a2614184b48b694becfd377c789f5)`),u.length>0){let g=u.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`),B&&console.log(`${l} retrying. addrsToGet (${g.length}): ${g} (I: 8460694cdd5518472680784c3b96a822)`),await le(s));for(let $ of d){if(g.length===0)break;i&&console.timeLog(i,`${l} getFromSpace (${g.length}) starting...`);let y=await ae({addrs:g,space:$});if(i&&console.timeLog(i,`${l} getFromSpace complete.`),y.success&&(y.ibGibs?.length??0)>0){y.ibGibs.forEach(I=>b.push(I));let G=y.ibGibs.map(I=>_({ibGib:I}));g=g.filter(I=>!G.includes(I))}else{let G=y.rawResultIbGib?.ibGibs??[];if(G.length>0){G.forEach(S=>b.push(S));let I=G.map(S=>_({ibGib:S}));g=g.filter(S=>!I.includes(S))}}}m++}if(g.length>0){let $=d.map(y=>y?.ib).join(", ");throw new Error(`unable to retrieve dependency ibgibs from space/s (ib/s: ${$}). addrsToGet: ${g.join(`
15
+ `)} (E: 8413594b6c1b447988781cf3f3e1729d)`)}}return b}catch(d){throw console.error(`${l} ${d.message}`),d}finally{B&&console.log(`${l} complete.`)}}f(xn,"getGraphProjection_getIbGibsInIbGibAddrs");async function or(r){let e=`[${or.name}]`;try{if(B&&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:b,space:u,spaces:p,timeLogName:h,mapTjpAddrToLatestAddrsInSpace:g}=await ra(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:b,timeLogName:h,space:u,spaces:p});t=t?[...t,...$]:[...$]}o=t.map($=>_({ibGib:$}));let m=dr(t.map($=>$.ib).filter($=>$.startsWith("comment ")));return B&&console.log(`${e}[analyze debugging] ibGibs commentIbs: ${m.join(`
16
+ `)} (I: c89dc951315f746954f9bddbe8941122)`),n?oa({ibGibs:t,ibGibAddrs:o,gotten:s,tjpAddrsAlreadyAnalyzed:i,skipAddrs:a,skipRel8nNames:c,onlyRel8nNames:l,maxRetries:d,msBetweenRetries:b,space:u,spaces:p,timeLogName:h,mapTjpAddrToLatestAddrsInSpace:g}):na({ibGibs:t,ibGibAddrs:o,gotten:s,skipAddrs:a,skipRel8nNames:c,onlyRel8nNames:l,maxRetries:d,msBetweenRetries:b,space:u,spaces:p,timeLogName:h})}catch(t){throw console.error(`${e} ${t.message}`),t}finally{B&&console.log(`${e} complete.`)}}f(or,"getGraphProjection");async function Gl({ibGibAddr:r,latestCommonFrameAddr:e,live:t,space:o,spaces:n}){let s=`[${Gl.name}]`;try{if(B&&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 rr({ibGibAddr:e,live:!1,space:o,spaces:n});return await rr({ibGibAddr:r,live:t,skipAddrs:Object.keys(i),space:o,spaces:n})}catch(i){throw console.error(`${s} ${E(i)}`),i}finally{B&&console.log(`${s} complete.`)}}f(Gl,"getDeltaDependencyGraph");async function oa({ibGibs:r,ibGibAddrs:e,gotten:t,tjpAddrsAlreadyAnalyzed:o,mapTjpAddrToLatestAddrsInSpace:n,skipAddrs:s,skipRel8nNames:i,onlyRel8nNames:a,maxRetries:c,msBetweenRetries:l,space:d,spaces:b,timeLogName:u}){let p=`[${oa.name}]`;try{let h=b??(d?[d]:[]);n=n??{},o=o??[];let g={...t};(r??[]).forEach(S=>g[_({ibGib:S})]=S);let m=Jt({ibGibs:Object.values(g)});B&&console.log(`${p}[analyze debugging] timeline tjps(${Object.keys(m).length}): ${Object.keys(m)} (I: 509f04ac15ca08c5a3f0777b48934622)`);let $={};Object.keys(m).forEach(S=>{o.includes(S)||($[S]=m[S])}),B&&console.log(`${p}[analyze debugging] timelinesNotAnalyzed: ${H($)} (I: a4b67d95fdd6b98d3241c0a7d0a93c22)`);let y={},G={};Object.keys(m).filter(S=>!o.includes(S)).forEach(S=>{let w=m[S],T=w[w.length-1];y[S]=T;let v=_({ibGib:T});G[v]=S});let I=Object.keys(y).length;if(I>0){let S={};Object.keys(n).filter(C=>!o.includes(C)).forEach(C=>{let U=y[C];if(U){let Z=_({ibGib:U});S[Z]=n[C]}else console.error(`${p} latestIbGibCorrespondingToTjpAddr is falsy (E: 8a5d3f2e1c4b90876543210fe89abcdf)`)}),B&&console.log(`${p} latestAddrsMap *before* getLatestAddrs: ${H(S)} (I: 427b4bb78595e9e521ecf2c5e5c80722)`);let w=Object.values(y),T={};if(w.length>0){if(h.length===0)throw new Error("(UNEXPECTED) space/s falsy? (E: 8e878975e3561df9a8dc4c628b0abc23)");for(let C of h){let U=await Pe({ibGibs:w,space:C});if(!U?.data?.latestAddrsMap)throw new Error("(UNEXPECTED) getLatestAddrs result latestAddrsMap falsy (E: 088caa1fc95fd3b079108ab63ef33422)");let Z=U.data.latestAddrsMap;Object.keys(Z).forEach(z=>{let q=Z[z];q?T[z]=q:T[z]||(T[z]=null)})}if(w.forEach(C=>{let U=_({ibGib:C});T[U]||(T[U]=U)}),Object.keys(T).length!==I)throw new Error("(UNEXPECTED) latestAddrsMap is not the same size as the incoming map (E: 666af512bbd44534983bb28ee8d43fed)");B&&console.log(`${p} queriedLatestAddrsMap: ${H(T)} (I: 7b39a5f7ce9e9d9fabae4be98ed44522)`),S={...T,...S}}B&&console.log(`${p} combined latestAddrsMap: ${H(S)} (I: e3aedea63f29c5b06a79632f691aa522)`);let v=[],N={};Object.values(y).forEach(C=>{let U=_({ibGib:C}),Z=G[U],z=S[U];if(!z)throw new Error("(UNEXPECTED) latestAddrInSpace not found in latestAddrsMap (E: 095d2b3f88e3e8a2c3e7d3de4c6d5622)");z===U?(B&&console.log(`${p} analyzed ${Z} (I: afb7960900f04b8a87538f4c7bd903b7)`),o.push(Z)):(v.push(z),N[z]=Z)});let x=[];for(let C=0;C<(r??[]).length;C++){let Z=r[C].rel8ns??{};Object.keys(Z).filter(q=>!(i??[]).includes(q)).filter(q=>a?a.includes(q):!0).forEach(q=>{(Z[q]??[]).forEach(Ue=>{!x.includes(Ue)&&!r.some(Lt=>_({ibGib:Lt})===Ue)&&!te({gib:R({ibGibAddr:Ue}).gib})&&x.push(Ue)})})}return e=dr([...e??[],...x,...v]),await or({ibGibs:r,ibGibAddrs:e,gotten:t,tjpAddrsAlreadyAnalyzed:o,skipAddrs:s,skipRel8nNames:i,onlyRel8nNames:a,maxRetries:c,msBetweenRetries:l,space:d,spaces:h,timeLogName:u,live:!0,mapTjpAddrToLatestAddrsInSpace:n})}else return r||(r=[]),Object.values(t??{}).forEach(S=>{let w=_({ibGib:S});r.some(T=>_({ibGib:S})===w)||r.push(S)}),await or({ibGibs:r,ibGibAddrs:e,gotten:t,skipAddrs:s,skipRel8nNames:i,onlyRel8nNames:a,maxRetries:c,msBetweenRetries:l,space:d,spaces:h,timeLogName:u,live:!1})}catch(h){let g=`${p} ${h.message}`;throw console.error(g),u&&console.timeLog(u,`${p} error: ${g}`),h}finally{u&&console.timeLog(u,`${p} complete.`)}}f(oa,"getGraphProjection_Live");async function na({ibGibs:r,ibGibAddrs:e,gotten:t,skipAddrs:o,skipRel8nNames:n,onlyRel8nNames:s,maxRetries:i,msBetweenRetries:a,space:c,spaces:l,timeLogName:d}){let b=`[${na.name}]`;try{let u=[];r??=[],t??={},o??=[],n??=[],d&&console.timeLog(d,`${b} 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===P)throw new Error("cannot get dependency graph of primitive. (E: 5493b8908d134bdf887e91122a6a57e3)");Object.keys(t).includes(g)||(t[g]=h);let $={},y=h.rel8ns||{},G=(Object.keys(y)||[]).filter(S=>!n.includes(S));s&&(G=G.filter(S=>s.includes(S)));let I=Object.keys(t);for(let S=0;S<G.length;S++){let w=G[S],T=y[w]??[],v=T.filter(x=>x===""||x===void 0||x===null||!x.includes(ee));v.length>0&&console.warn(`${b} (UNEXPECTED) has falsyAddrs: ${v} (W: da9505cb0a4db68a4aff7f279ad2d322)`),T.filter(x=>!!x).filter(x=>!I.includes(x)).filter(x=>!o.includes(x)).filter(x=>R({ibGibAddr:x}).gib!==P).filter(x=>!u.includes(x)).forEach(x=>{let C=jt({addr:x});(C||[]).length===0?u.push(x):$[x]=C})}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,`${b} analyzing next step complete.`),u.length>0){d&&console.timeLog(d,`${b} get addrsWeDontHaveAlready_Rel8dAddrs starting...`);let p=await xn({ibGibAddrs:u,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,`${b} call getGraphProjection recursively starting...`);let h=await or({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,`${b} call getGraphProjection recursively complete.`),h}else return t}catch(u){let p=`${b} ${u.message}`;throw console.error(`${p} (E: 8a42e56616014e7a8848aa6bb6f2722b)`),d&&console.timeLog(d,`${b} error: ${p}`),new Error(`${p} (E: a21b0682121746a480572b83413cf2d0)`)}finally{d&&console.timeLog(d,`${b} complete.`)}}f(na,"getGraphProjection_NonLive");function Wr({ibGibs:r}){let e=`[${Wr.name}]`;try{if(B&&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{B&&console.log(`${e} complete.`)}}f(Wr,"toFlatGraph");function xl({graphA:r,graphB:e,slowButThorough:t}){let o=`[${xl.name}]`;try{if(B&&console.log(`${o} starting... (I: e50a98b659189dece8b4ef581e4ad826)`),!(Object.keys(r).length===Object.keys(e).length))return B&&console.log(`${o} not the same size. false. (I: e1044e52421dbf7e067e0fe850ac6826)`),!1;for(let s of Object.keys(r))if(!e[s])return B&&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=Re({ibGib:r[s]}),a=JSON.stringify(i),c=Re({ibGib:e[s]}),l=JSON.stringify(c);if(a!==l)return B&&console.log(`${o} jsonA !== jsonB for addr (${s}) (I: 98ed9f58ac88dabba83f96582f725926)`),!1}return!0}catch(n){throw console.error(`${o} ${E(n)}`),n}finally{B&&console.log(`${o} complete.`)}}f(xl,"graphsAreEquivalent");var J=!1;async function sa({keystoneData:r}){let e=`[${sa.name}]`;try{return J&&console.log(`${e} starting... (I: c3022a146faac9730154f34d1439a225)`),[Qt].join(" ")}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{J&&console.log(`${e} complete.`)}}f(sa,"getKeystoneIb");async function ia({ib:r}){let e=`[${ia.name}]`;try{J&&console.log(`${e} starting... (I: 73cb6832984255ed48b2f44db6a21e25)`);let[t]=r.split(" ");if(t!==Qt)throw new Error(`invalid keystone ib. atom found in ib (${t}) does not match keystone atom (${Qt}) (E: 79b3d587824c4271b6e60acc76e0c825)`);return{atom:t}}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{J&&console.log(`${e} complete.`)}}f(ia,"parseKeystoneIb");async function nr({ib:r}){try{return await ia({ib:r}),!0}catch{return!1}}f(nr,"validateKeystoneIb");function Om(r){if(!r||typeof r!="string")return!1;let e=r.trim();return e.length<3||e.length>254?!1:Ni.test(e)}f(Om,"validateEmail");async function aa({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)),b=i[d];n.add(b),i.splice(d,1),s=s.filter(u=>u!==b),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(aa,"getDeterministicRequirements");function sr({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(sr,"resolveTargetPool");async function ht({pool:r,targetAddr:e,requiredChallengeIds:t}){let o="[selectChallengeIds]";try{let{mandatoryIds:n,availableIds:s}=await aa({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(ht,"selectChallengeIds");async function ca({salt:r,timestamp:e,index:t}){return(await X({s:`${r}${e}${t}`})).substring(0,16)}f(ca,"generateOpaqueChallengeId");async function vl({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],b=await n.derivePoolSecret({masterSecret:o}),u=Date.now().toString(),p=s.behavior.replenish;if(i===Nt&&(p=we.deleteAll),p===we.topUp){t.forEach(h=>delete d.challenges[h]);for(let h=0;h<t.length;h++){let g=await ca({salt:s.salt,timestamp:u,index:h}),m=await n.generateSolution({poolSecret:b,poolId:d.id,challengeId:g});d.challenges[g]=await n.generateChallenge({solution:m})}}else if(p===we.replaceAll)d.challenges=await Zr({config:s,masterSecret:o});else if(p===we.consume)t.forEach(h=>delete d.challenges[h]);else if(p===we.deleteAll)d.challenges={};else throw new Error(`Unknown replenish strategy: ${p}. Valid list: ${H(Oi)} (E: 0acf56f1e1486240080e11e8046d0825)`);return c}catch(c){throw console.error(`${a} ${E(c)}`),c}}f(vl,"applyReplenishmentStrategy");async function gt({targetPoolId:r,prevPools:e,masterSecret:t,challengeIds:o,claim:n,requiredChallengeIds:s}){let i="[solveAndReplenish]";try{J&&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: a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6)`);let c=pt.create({config:a.config}),l=await c.derivePoolSecret({masterSecret:t});if(!await Dn({pool:a,signingSecret:t}))throw new Error(`Crypto Violation: Invalid signing secret for pool: ${a.id} (E: 8a4c2b1d3e5f6a7b8c9d0e1f2a3b4c5f)`);let b=[];for(let h of o){let g=await c.generateSolution({poolSecret:l,poolId:a.id,challengeId:h});b.push(g)}let u={claim:n,solutions:b,requiredChallengeIds:s&&s.length>0?s:void 0},p=await vl({prevPools:e,targetPoolId:a.id,consumedIds:o,masterSecret:t,strategy:c,config:a.config,verb:n.verb});return{proof:u,nextPools:p}}catch(a){throw console.error(`${i} ${E(a)}`),a}}f(gt,"solveAndReplenish");async function la({pool:r}){let e=`[${la.name}]`;try{if(J&&console.log(`${e} starting... (I: e2ffd568b698cc12d8c5e838d73ae726)`),!r.config)throw new Error("(UNEXPECTED) pool.configy falsy? (E: fcde88fe20e8004a58d7e445436bf526)");if(r.config.type!==Le.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=[ge.sha_256,ge.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>_n&&t.push(`${e} rounds too high. max rounds: ${_n} (E: 31ce082f7fd88d6b58ef08a816458826)`):t.push(`${e} invalid rounds (${n}). must be positive integer. (E: 73c643ccda78afaf28d52a6871a9e826)`),s&&typeof s=="string"?$n.test(s)||t.push(`${e} invalid salt (${s.substring(0,99)}). Must match regexp ${$n}`):t.push(`${e} invalid salt (${s}). must be truthy string value. (E: 564a4844ec88fc1988197ce89c381426)`),t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{J&&console.log(`${e} complete.`)}}f(la,"validateChallengePool_typeHashRevealV1");async function da({pool:r}){let e=`[${da.name}]`;try{J&&console.log(`${e} starting... (I: 1a0eafc158a83d1ba8fc019d5c979a26)`);let t=[];if(r.config){if(r.config.id?wn.test(r.config.id)||t.push(`${e} pool.config.id is not formatted correctly. must pass regexp: ${wn.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 Le.hash_reveal_v1:(await la({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: ${Di} (E: cce5285cf7580b8bc82172488eba2826)`)}}else t.push(`${e} pool.config falsy. (E: 8d05c875a1d2c58018a5eaf803977d26)`);return t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{J&&console.log(`${e} complete.`)}}f(da,"validateChallengePool");function fa({data:r}){let e="[validateKeystoneMetadata]",t=[],o=f((n,s)=>{n&&(n.username!==void 0&&(typeof n.username!="string"||!yn.test(n.username))&&t.push(`${e} invalid username in ${s} (${n.username}). Must match ${yn}`),n.description!==void 0&&(typeof n.description!="string"||!In.test(n.description))&&t.push(`${e} invalid description in ${s} (${n.description}). Must match ${In}`),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(fa,"validateKeystoneMetadata");async function zr({keystoneIbGib:r}){let e=`[${zr.name}]`;try{J&&console.log(`${e} starting... (I: ec6ba82ec848b5ac3d8953e89d8d9826)`);let t=[],{data:o,rel8ns:n}=r;await nr({ib:r.ib})||t.push(`${e} invalid keystone ib (${r.ib}). (E: ad7a88bc38c290a184dfbd42be48f526)`),fa({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 da({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{J&&console.log(`${e} complete.`)}}f(zr,"validateGenesisKeystone");function Dl({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(Dl,"isDelegatesChanged");async function Ol({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([nr({ib:a.delegateTjpAddr.split("^")[0]}),nr({ib:a.delegateAddr.split("^")[0]}),nr({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 u=a.allowedVerbs||[];(a.role==="sync-delegate"||u.includes("sync")||u.includes(Br))&&!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(Ol,"validateDelegates");async function ir({currentIbGib:r,prevIbGib:e}){let t=`[${ir.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 ie({ibGib:r});n&&n.length>0&&o.push(...n);let s=r.data,i=e.data;await nr({ib:r.ib})||o.push(`${t} invalid keystone ib (${r.ib}). (E: a98dc8bc38c290a184dfbd42be48f526)`),fa({data:s}).forEach(g=>o.push(g));let l=s.delegates||{},d=i.delegates||{};Dl({currDelegates:l,prevDelegates:d})&&(s.proofs?.some(m=>m.claim?.verb===he)||o.push(`${t} Policy Violation: Delegates map was mutated but no proof for manage verb ('${he}') is present. (E: 819fa8cb28c9b60e68994511a5825)`)),await Ol({currDelegates:l,prevIbGib:e,lc:t,errors:o});let u=s.n??-2,p=i.n??-2;u<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)"),u!==p+1&&o.push(`keystone data.n values are not sequential. prevData.n: ${p}, currData.n: ${u}. (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(y=>y.id===m);if(!$){o.push(`Proof references unknown pool: ${m}`);continue}await ba({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,y=$.type,G=$.info;if(y==="add-pool"){let I=G;if(!I||!Array.isArray(I.add)||I.add.length===0){o.push(`details type is '${y}' but payload is invalid. (E: 1fa2a8cb28c9b60e68994511a5825)`);continue}let S=new Set(i.challengePools.map(T=>T.id)),w=new Set(s.challengePools.map(T=>T.id));for(let T of I.add)w.has(T)||o.push(`ClaimDetails_AddPool lists pool ${T} but it is missing in the evolved keystone. (E: 2fa2a8cb28c9b60e68994511a5825)`),S.has(T)&&o.push(`ClaimDetails_AddPool attempts to add existing pool ${T}. (E: 3fa2a8cb28c9b60e68994511a5825)`);s.challengePools.length!==i.challengePools.length+I.add.length&&o.push(`Structural mismatch: expected ${i.challengePools.length+I.add.length} pools, found ${s.challengePools.length}. (E: 4fa2a8cb28c9b60e68994511a5825)`);for(let T of i.challengePools){let v=s.challengePools.find(N=>N.id===T.id);if(!v){o.push(`Existing pool ${T.id} was removed during add-pool transition. (E: 5fa2a8cb28c9b60e68994511a5825)`);continue}JSON.stringify(T.config)!==JSON.stringify(v.config)&&o.push(`Existing pool config ${T.id} was mutated during add-pool transition. (E: 6fa2a8cb28c9b60e68994511a5825)`),!h.has(T.id)&&JSON.stringify(T.challenges)!==JSON.stringify(v.challenges)&&o.push(`Existing pool challenges ${T.id} were mutated during add-pool transition. (E: 7fa2a8cb28c9b60e68994511a5825)`)}}else if(y==="replace-pool"){let I=G;if(!I||typeof I.replace!="string"||!I.replace){o.push(`details type is '${y}' but payload is invalid. (E: 8fa2a8cb28c9b60e68994511a5825)`);continue}let S=I.replace,w=i.challengePools.map(x=>x.id).sort(),T=s.challengePools.map(x=>x.id).sort();JSON.stringify(w)!==JSON.stringify(T)&&o.push("replace-pool transition mutated the pool IDs set. (E: 9fa2a8cb28c9b60e68994511a5825)");let v=i.challengePools.find(x=>x.id===S),N=s.challengePools.find(x=>x.id===S);(!v||!N)&&o.push(`Replaced pool ${S} not found in keystone challenge pools. (E: afa2a8cb28c9b60e68994511a5825)`);for(let x of i.challengePools){if(x.id===S)continue;let C=s.challengePools.find(U=>U.id===x.id);C&&(JSON.stringify(x.config)!==JSON.stringify(C.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(C.challenges)&&o.push(`Unrelated pool challenges ${x.id} were mutated during replace-pool. (E: cfa2a8cb28c9b60e68994511a5825)`))}}else if(y==="remove-pool"){let I=G;if(!I||!Array.isArray(I.remove)||I.remove.length===0){o.push(`details type is '${y}' but payload is invalid. (E: b7a2a8cb28c9b60e68994511a5825)`);continue}let S=new Set(I.remove),w=new Set(i.challengePools.map(v=>v.id)),T=new Set(s.challengePools.map(v=>v.id));for(let v of I.remove)w.has(v)||o.push(`ClaimDetails_RemovePool lists pool ${v} but it is missing in the previous keystone. (E: c7a2a8cb28c9b60e68994511a5825)`),T.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-I.remove.length&&o.push(`Structural mismatch: expected ${i.challengePools.length-I.remove.length} pools, found ${s.challengePools.length}. (E: e7a2a8cb28c9b60e68994511a5825)`);for(let v of i.challengePools){if(S.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(y==="change-password"){let I=G;if(!I||!Array.isArray(I.change)||I.change.length===0){o.push(`details type is '${y}' but payload is invalid. (E: dfa2a8cb28c9b60e68994511a5825)`);continue}let S=i.challengePools.map(v=>v.id).sort(),w=s.challengePools.map(v=>v.id).sort();JSON.stringify(S)!==JSON.stringify(w)&&o.push("change-password transition mutated the pool IDs set. (E: efa2a8cb28c9b60e68994511a5825)");let T=new Set(I.change);for(let v of i.challengePools){let N=s.challengePools.find(x=>x.id===v.id);if(N)if(T.has(v.id)){v.isForeign&&o.push(`Security Violation: Password rotation attempted on foreign pool ${v.id}. (E: ffa2a8cb28c9b60e68994511a5825)`);let x={...v.config,salt:""},C={...N.config,salt:""};JSON.stringify(x)!==JSON.stringify(C)&&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: ${y}`)}}return o}catch(n){throw console.error(`${t} ${E(n)}`),n}finally{J&&console.log(`${t} complete.`)}}f(ir,"validateKeystoneTransition");async function ba({proof:r,pool:e,errors:t}){let o=`[${ba.name}]`;try{J&&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 aa({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=pt.create({config:e.config});for(let d of r.solutions){let b=e.challenges[d.challengeId];b?await l.validateSolution({solution:d,challenge:b})||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{J&&console.log(`${o} complete.`)}}f(ba,"verifyProofAgainstPool");async function rt({prevIbGib:r,newData:e,metaspace:t,space:o}){let n=`[${rt.name}]`;try{if(J&&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 Me({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 ir({currentIbGib:c,prevIbGib:r});if(l.length>0)throw console.error(`${n} Validation Failed:
17
+ ${l.join(`
18
+ `)}`),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{J&&console.log(`${n} complete.`)}}f(rt,"evolvePersistAndRegisterKeystone");async function vn({data:r,metaspace:e,space:t}){let o=`[${vn.name}]`;try{if(J&&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 j.firstGen({parentIbGib:j.primitive({ib:Qt}),ib:await sa({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 K({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{J&&console.log(`${o} complete.`)}}f(vn,"createKeystoneIbGibImpl");async function Jr({keystoneIbGib:r,dependencyGraph:e,getLatest:t,invalidIfMoreRecentKeystoneFoundInSpace:o,space:n}){let s=`[${Jr.name}]`;try{if(J&&console.log(`${s} starting... (I: 22e1ca1d5a08a3f90b7fe9da95df7b26)`),!r)throw new Error("(UNEXPECTED) keystoneIbGib falsy? (E: 26482871d529fff6e8899c5d8a6c3826)");let i=[];if(t){let b=_({ibGib:r}),u=await Pe({ibGibs:[r],space:n});if(!u.data)throw new Error("(UNEXPECTED) resGetLatestAddrs.data falsy? (E: 3a23b3b420a8da1928219ca8d47b2126)");if(!u.data.latestAddrsMap)throw new Error("(UNEXPECTED) resGetLatestAddrs.data.latestAddrsMap falsy? (E: 93f1180598fb65a4b8d36e08d6c50426)");let{latestAddrsMap:p}=u.data;if(Object.keys(p).length===0)throw new Error("(UNEXPECTED) latestAddrsMap truthy but empty? (E: 7142f8f7625b9186281d08251e407826)");let h=p[b];if(h)if(h!==b)if(o)i.push(`${s} more recent keystone (${h}) found than the one passed in (${b}) in space (${n.ib}). (E: 64bf48de9448ee5c7528bf03bed2a826)`);else{let[g]=await dn({addrs:[h],space:n});r=g}else J&&console.log(`${s} incoming keystone (${b}) is the latest in the space (${n.ib}) (I: 8ffbd8d6cbc8a461e5e7f1084bd22a26)`);else console.warn(`${s} keystoneIbGib (${b}) not found in space (${n.ib}). I don't know what the implications of this are. (W: 258c88742448db34a585669484771826)`)}e??=await rr({ibGib:r,space:n});let a=Object.values(e),{mapWithTjp_NoDna:c,mapWithTjp_YesDna:l,mapWithoutTjps:d}=Rr({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 b=Object.values(c),u=Jt({ibGibs:b}),p=Object.keys(u);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=u[h];if(g.length===0)throw new Error("(UNEXPECTED) empty keystoneIbGibs_ordered? (E: 4a6b085aa8a76828a8d65367e7e56526)");if((await zr({keystoneIbGib:g[0]})).forEach($=>i.push($)),g.length!==1)for(let $=0;$<g.length-1;$++){let y=g[$],G=g[$+1],I=await ir({prevIbGib:y,currentIbGib:G});I.length>0&&(i.push(`${s} keystone has ${I.length} transition errors. i: ${$}. prevIbGib addr: ${_({ibGib:y})}. currentIbGib addr: ${_({ibGib:G})}. (E: 3ac17be916141d0c286ca5a87bb1b426)`),I.forEach(S=>i.push(S)));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{J&&console.log(`${s} complete.`)}}f(Jr,"validateKeystoneGraph");async function Zr({config:r,masterSecret:e}){let t=pt.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 ca({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(Zr,"generatePoolChallenges");async function ua({prevPool:r,newMasterSecret:e}){let t=r.config,o=(await k()).substring(0,16),n={...t,salt:o},s=await Zr({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(ua,"rotatePoolChallenges");async function Dn({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=pt.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(Dn,"verifyPoolSecret");var F=!1,Qr=class r{static{f(this,"KeystoneService_V1")}lc=`[${r.name}]`;async genesis({masterSecret:e,emails:t,frameDetails:o,configs:n,metaspace:s,space:i,isPrimary:a}){let c=`${this.lc}[${this.genesis.name}]`;try{F&&console.log(`${c} starting... (I: c98ae8adbc5888dbf84c5aced7610b25)`);let l=[];for(let u of n){let p=await Zr({config:u,masterSecret:e});l.push({id:u.id,config:u,challenges:p})}if(l.length===0)throw new Error("No challenge pools created. (E: 38e538530996940e1f16a8b199995825)");let d={challengePools:l,proofs:[]};return t&&t.length>0&&(d.emails=[...t]),(o||a!==void 0)&&(d.frameDetails={...o||{}},a!==void 0&&(d.frameDetails.isPrimary=a)),await vn({data:d,metaspace:s,space:i})}catch(l){throw console.error(`${c} ${E(l)}`),l}finally{F&&console.log(`${c} complete.`)}}async sign({latestKeystone:e,masterSecret:t,claim:o,poolId:n,poolFilter:s,requiredChallengeIds:i=[],frameDetails:a,metaspace:c,space:l,dataToPatch:d}){let b=`${this.lc}[${this.sign.name}]`;try{F&&console.log(`${b} starting...`);let u=e.data;if(u.revocationInfo)throw new Error("Keystone has been revoked. Cannot sign. (E: 4f2198c39116d15c48ba191940316825)");if(On({keystone:e}))throw new Error(`Keystone is expired (${u.frameDetails?.expirationUTC}). Cannot sign. (E: 7f2198c39116d15c48ba191940316825)`);let p=sr({pools:u.challengePools,poolId:n,poolFilter:s,verb:o.verb});F&&console.log(`${b} Selected pool: ${p.id} (size: ${Object.keys(p.challenges).length}) (I: 6b26d6f4aad18380f2b3a0989b592826)`);let h=await ht({pool:p,targetAddr:o.target,requiredChallengeIds:i}),{proof:g,nextPools:m}=await gt({targetPoolId:p.id,prevPools:u.challengePools,masterSecret:t,challengeIds:h,claim:o,requiredChallengeIds:i}),$=(u.n??0)+1,y;if($%ut===0){let S={...e,data:{...u,frameDetails:a}};y=await this.getAggregateDetails({latestKeystone:S,metaspace:c,space:l})}let G={challengePools:m,proofs:[g],frameDetails:a,checkpointDetails:y,...u.delegates?{delegates:u.delegates}:{},...d};return await rt({prevIbGib:e,newData:G,metaspace:c,space:l})}catch(u){throw console.error(`${b} ${E(u)}`),u}finally{F&&console.log(`${b} complete.`)}}async validate({currentIbGib:e,prevIbGib:t}){return await ir({currentIbGib:e,prevIbGib:t})}async registerDelegate({parentKeystone:e,delegateKeystone:t,masterSecret:o,frameDetails:n,metaspace:s,space:i,allowedVerbs:a,deviceName:c,expirationUTC:l,ttlSeconds:d}){let b=`${this.lc}[${this.registerDelegate.name}]`;try{F&&console.log(`${b} starting...`);let u=await Jr({keystoneIbGib:t,getLatest:!0,invalidIfMoreRecentKeystoneFoundInSpace:!1,space:i});if(u.length>0)throw new Error(`Delegate keystone validation failed: ${u.join(", ")} (E: 88fa8ab28c9b60e68994511a5825)`);let p=e.data;if(!p.challengePools.some(S=>S.id===Xe))throw new Error("Parent keystone does not support delegation. Manage pool is required. (E: 818fa8ab28c9b60e68994511a5825)");let g=ue({ibGib:t});if(!g)throw new Error("(UNEXPECTED) delegateTjpAddr falsy? (E: d4d6e8ad03c8925d4838b9a87b8f2826)");let m={target:g,verb:he},$=p.delegates?{...p.delegates}:{},y=Cr({spaceIb:i.ib}).spaceId,G=l??(d?new Date(Date.now()+d*1e3).toISOString():void 0)??t.data?.frameDetails?.expirationUTC;return $[g]={delegateTjpAddr:g,delegateAddr:_({ibGib:t}),thisAddr:_({ibGib:e}),deviceName:c,allowedVerbs:a,spaceId:y,expirationUTC:G},await this.sign({latestKeystone:e,masterSecret:o,claim:m,poolId:Xe,frameDetails:n,metaspace:s,space:i,dataToPatch:{delegates:$}})}catch(u){throw console.error(`${b} ${E(u)}`),u}finally{F&&console.log(`${b} complete.`)}}async unregisterDelegate({parentKeystone:e,delegateTjpAddr:t,masterSecret:o,frameDetails:n,metaspace:s,space:i}){let a=`${this.lc}[${this.unregisterDelegate.name}]`;try{F&&console.log(`${a} starting...`);let c=e.data;if(!c.challengePools.some(p=>p.id===Xe))throw new Error("Parent keystone does not support delegation. Manage pool is required. (E: 3889f8ab28c9b60e68994511a5825)");let d={target:t,verb:he},b=c.delegates?{...c.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:d,poolId:Xe,frameDetails:n,metaspace:s,space:i,dataToPatch:{delegates:b}})}catch(c){throw console.error(`${a} ${E(c)}`),c}finally{F&&console.log(`${a} complete.`)}}async getDelegateStatus({parentTjpAddr:e,delegateTjpAddr:t,metaspace:o,space:n}){let s=`${this.lc}[${this.getDelegateStatus.name}]`;try{F&&console.log(`${s} starting...`);let{ib:i,gib:a}=R({ibGibAddr:e}),l=await Pe({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 u=(await o.get({addr:d,space:n})).ibGibs?.at(0);if(!u||!u.data)return{registered:!1};let h=(u.data.delegates||{})[t];return{registered:!!h&&!pa({delegateInfo:h}),delegateInfo:h}}catch(i){throw console.error(`${s} ${E(i)}`),i}finally{F&&console.log(`${s} complete.`)}}async validateGenesisKeystone({keystoneIbGib:e}){return await zr({keystoneIbGib:e})}async getLatestKeystone({addr:e,metaspace:t,space:o}){let n=`${this.lc}[${this.getLatestKeystone.name}]`;try{F&&console.log(`${n} starting...`);let s=await t.getLatestAddr({tjpAddr: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{F&&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 F&&console.log(`${i} starting... (I: 01c5cd455038c270cbf1effc1704af26)`),await Jr({keystoneIbGib:e,dependencyGraph:t,getLatest:o,invalidIfMoreRecentKeystoneFoundInSpace:n,space:s})}catch(a){throw console.error(`${i} ${E(a)}`),a}finally{F&&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{F&&console.log(`${a} starting...`);let c=e.data,l=sr({pools:c.challengePools,verb:Nt}),d={verb:Nt,target:_({ibGib:e})},b=await ht({pool:l,targetAddr:d.target,requiredChallengeIds:[]});if(b.length===0)throw new Error(`Revocation policy selected 0 challenges? Check config for pool ${l.id}. Revocation requires proof. (E: 97e5a8356d241ae7b882db791cb1f825)`);let{proof:u,nextPools:p}=await gt({targetPoolId:l.id,prevPools:c.challengePools,masterSecret:t,challengeIds:b,claim:d,requiredChallengeIds:[]});p.find(G=>G.id===l.id&&Object.keys(G.challenges).length>0)&&console.warn(`${a} revocation pool ${l.id} is not empty after revocation. Is the revocation pool replenish strategy set to ${we.deleteAll}? (W: 300c28bc8b98fc3e3c0b0d988344f825)`);let h={reason:o,proof:u},g=(c.n??0)+1,m;if(g%ut===0){let G={...e,data:{...c,frameDetails:n,revocationInfo:h}};m=await this.getAggregateDetails({latestKeystone:G,metaspace:s,space:i})}let $={challengePools:p,proofs:[u],revocationInfo:h,frameDetails:n,checkpointDetails:m,...c.delegates?{delegates:c.delegates}:{}};return await rt({prevIbGib:e,newData:$,metaspace:s,space:i})}catch(c){throw console.error(`${a} ${E(c)}`),c}finally{F&&console.log(`${a} complete.`)}}async addPools({latestKeystone:e,masterSecret:t,newPools:o,metaspace:n,space:s}){let i=`${this.lc}[${this.addPools.name}]`;try{if(F&&console.log(`${i} starting...`),!e.data)throw new Error("(UNEXPECTED) latestKeystone.data falsy? (E: 7334c8faed128166a999d428c7805b25)");let a=e.data;if(a.revocationInfo)throw new Error("Keystone has been revoked. Cannot add pools. (E: 8599f8f51c78d722252ddb2894fdbe25)");if(o.length===0)throw new Error("No new pools provided to add. (E: 6599f8f51c78d722252ddb2894fdbe25)");let c=sr({pools:a.challengePools,verb:he});F&&console.log(`${i} Authorized via pool: ${c.id}`);let l=_({ibGib:e}),d={verb:he,target:l,details:{type:Ot.add_pool,info:{add:o.map(I=>I.id)}}},b=await ht({pool:c,targetAddr:l}),{proof:u,nextPools:p}=await gt({targetPoolId:c.id,prevPools:a.challengePools,masterSecret:t,challengeIds:b,claim:d}),h=new Set(p.map(I=>I.id));for(let I of o)if(h.has(I.id))throw new Error(`Cannot add pool. ID collision: ${I.id} (E: 8a4c2b1d3e5f6a7b8c9d0e1f2a3b4c5d)`);let g=[...p,...o],m=(a.n??0)+1,$;if(m%ut===0){let I={...e,data:{...a,challengePools:g}};$=await this.getAggregateDetails({latestKeystone:I,metaspace:n,space:s})}let y={challengePools:g,proofs:[u],checkpointDetails:$,...a.delegates?{delegates:a.delegates}:{}};return await rt({prevIbGib:e,newData:y,metaspace:n,space:s})}catch(a){throw console.error(`${i} ${E(a)}`),a}finally{F&&console.log(`${i} complete.`)}}async removePools({latestKeystone:e,masterSecret:t,poolIds:o,metaspace:n,space:s}){let i=`${this.lc}[${this.removePools.name}]`;try{if(F&&console.log(`${i} starting...`),!e.data)throw new Error("(UNEXPECTED) latestKeystone.data falsy? (E: 8334c8faed128166a999d428c7805b25)");let a=e.data;if(a.revocationInfo)throw new Error("Keystone has been revoked. Cannot remove pools. (E: 9599f8f51c78d722252ddb2894fdbe25)");if(o.length===0)throw new Error("No pool IDs provided to remove. (E: 7599f8f51c78d722252ddb2894fdbe25)");let c=sr({pools:a.challengePools,verb:he});F&&console.log(`${i} Authorized via pool: ${c.id}`);let l=_({ibGib:e}),d={verb:he,target:l,details:{type:Ot.remove_pool,info:{remove:o}}},b=await ht({pool:c,targetAddr:l}),{proof:u,nextPools:p}=await gt({targetPoolId:c.id,prevPools:a.challengePools,masterSecret:t,challengeIds:b,claim:d}),h=new Set(o),g=p.filter(I=>!h.has(I.id));if(g.length!==p.length-o.length){let I=o.filter(S=>!p.some(w=>w.id===S));throw new Error(`Cannot remove pool. Pool IDs not found in keystone: ${I.join(", ")} (E: 8a4c2b1d3e5f6a7b8c9d0e1f2a3b4c5e)`)}let m=(a.n??0)+1,$;if(m%ut===0){let I={...e,data:{...a,challengePools:g}};$=await this.getAggregateDetails({latestKeystone:I,metaspace:n,space:s})}let y={challengePools:g,proofs:[u],checkpointDetails:$,...a.delegates?{delegates:a.delegates}:{}};return await rt({prevIbGib:e,newData:y,metaspace:n,space:s})}catch(a){throw console.error(`${i} ${E(a)}`),a}finally{F&&console.log(`${i} 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=_t({dominant:s,recessive:a.checkpointDetails});break}if(a.frameDetails&&(s=_t({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)throw new Error(`Could not find previous keystone frame at ${l} (E: e3d069b22e11e550e58844889ddb5325)`);i=d.ibGibs[0]}return 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:I,gib:S}=R({ibGibAddr:i});a={ib:I,gib:S}}let c=await Pe({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 b=(await o.get({addr:l,space:n})).ibGibs?.at(0);if(!b||!b.data)throw new Error(`Keystone ${l} not found or missing data in local space. (E: 6a2890b1c28f7449c5d8693a7d4a2831)`);let u=b.data.frameDetails||{},p=await this.getAggregateDetails({latestKeystone:b,metaspace:o,space:n}),h=p?.username||p?.name||p?.profile?.name||u?.username||u?.name||"",g=p?.description||p?.profile?.description||u?.description||"",m=!!p?.isPrimary||!!p?.profile?.isPrimary||!!u?.isPrimary,$=b.data.n??0,y=u?.timestamp||p?.timestamp||"",G=u?.timestampMs||p?.timestampMs||void 0;return{name:h,description:g,isPrimary:m,aggregateDetails:p,latestFrameDetails:u,n:$,timestamp:y,timestampMs:G}}catch(i){throw console.error(`${s} ${E(i)}`),i}}async replacePool({latestKeystone:e,newPool:t,signingSecret:o,signingPoolId:n=Xe,frameDetails:s,metaspace:i,space:a}){let c=`${this.lc}[${this.replacePool.name}]`;try{if(F&&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,b=d.find(w=>w.id===n);if(!b)throw new Error(`Signing pool not found: ${n} (E: 3599f8f51c78d722252ddb2894fdbe25)`);let u=_({ibGib:e}),p={verb:he,target:u,details:{type:Ot.replace_pool,info:{replace:t.id}}},h=await ht({pool:b,targetAddr:u}),{proof:g,nextPools:m}=await gt({targetPoolId:n,prevPools:d,masterSecret:o,challengeIds:h,claim:p}),$=m.findIndex(w=>w.id===t.id);if($===-1)throw new Error(`Target pool to replace '${t.id}' not found in keystone challenge pools.`);m[$]=t;let y=(l.n??0)+1,G;if(y%ut===0){let w={...e,data:{...l,frameDetails:s}};G=await this.getAggregateDetails({latestKeystone:w,metaspace:i,space:a})}let I={challengePools:m,proofs:[g],frameDetails:s,checkpointDetails:G,...l.delegates?{delegates:l.delegates}:{}};return await rt({prevIbGib:e,newData:I,metaspace:i,space:a})}catch(l){throw console.error(`${c} ${E(l)}`),l}finally{F&&console.log(`${c} complete.`)}}async changePassword({keystoneIbGib:e,keystoneAddr:t,newMasterSecret:o,signingSecret:n,signingPoolId:s=Xe,poolIds:i,frameDetails:a,metaspace:c,space:l}){let d=`${this.lc}[${this.changePassword.name}]`;try{if(F&&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 b=await this.getLatestKeystone({addr:t,metaspace:c,space:l});if(!b.data)throw new Error("latestKeystone.data falsy (E: 22e498eb8308a33e68b812d8d3905826)");if(b.data.revocationInfo)throw new Error("Keystone has been revoked. Cannot change password. (E: 726298617e8508b3c83b5e985a03e826)");let u=b.data.challengePools,p=u.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 C=u.find(U=>U.id===x);if(!C)throw new Error(`Target pool to rotate not found: ${x} (E: 4599f8f51c78d722252ddb2894fdbe25)`);h.push(C)}else if(h=u.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 C=await ua({prevPool:x,newMasterSecret:o});g.push(C)}let m=_({ibGib:b}),$={verb:he,target:m,details:{type:Ot.change_password,info:{change:g.map(x=>x.id)}}},y=await ht({pool:p,targetAddr:m}),{proof:G,nextPools:I}=await gt({targetPoolId:s,prevPools:u,masterSecret:n,challengeIds:y,claim:$});for(let x of g){let C=I.findIndex(U=>U.id===x.id);if(C===-1)throw new Error(`Rotated pool ${x.id} not found in next pools list. (E: 6599f8f51c78d722252ddb2894fdbe25)`);I[C]=x}let S=(b.data.n??0)+1,w;if(S%ut===0){let x={...b,data:{...b.data,challengePools:I}};w=await this.getAggregateDetails({latestKeystone:x,metaspace:c,space:l})}let T={challengePools:I,proofs:[G],frameDetails:a,checkpointDetails:w,...b.data.delegates?{delegates:b.data.delegates}:void 0},v=await rt({prevIbGib:b,newData:T,metaspace:c,space:l}),N=[];if((i??[]).length===0){let x=await Yr({masterSecret:n}),C=await Yr({masterSecret:o}),U=Object.keys(b.data.delegates??{});for(let Z of U){let{newKeystone:z,newDelegates:q}=await this.changePassword({keystoneAddr:Z,metaspace:c,space:l,newMasterSecret:C,signingSecret:x,signingPoolId:s,poolIds:void 0,frameDetails:a});if(q&&q.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(z)}}return{newKeystone:v,newDelegates:N.length>0?N:void 0}}catch(b){throw console.error(`${d} ${E(b)}`),b}finally{F&&console.log(`${d} complete.`)}}async verifySigningSecret({keystoneIbGib:e,signingSecret:t,poolId:o}){let n=`${this.lc}[${this.verifySigningSecret.name}]`;try{if(!e.data)return!1;let s=e.data.challengePools.find(i=>i.id===o);return s?await Dn({pool:s,signingSecret:t}):!1}catch(s){return console.warn(`${n} Exception during verification: ${E(s)}`),!1}}};var ha="sync-delegate";var eo="custodian-manage-";async function Yr({masterSecret:r}){let e=await X({s:r,algorithm:ge.sha_512});return await Ct({masterSecret:r,salt:e,rounds:1e3,algorithm:ge.sha_512})}f(Yr,"deriveDelegateSecret");async function Jm({primaryTjpAddr:r,deviceTag:e}){if(!r)throw new Error("primaryTjpAddr is required to derive device delegate secret (E: a1b2c3d4e5f67890123456789a000101)");let t=await k(32),o=`${r}_${e||""}_${t}`;return await X({s:o,algorithm:ge.sha_512})}f(Jm,"deriveDeviceDelegateSecret");async function Nl({profileName:r,profileTemplate:e,username:t,deviceTag:o,primaryTjpAddr:n,delegateSecret:s,custodianReqs:i,expirationUTC:a,additionalFrameDetails:c,metaspace:l,space:d}){let b=`[${Nl.name}]`;try{if(!r&&!e)throw new Error("profileName or profileTemplate is required (E: a1b2c3d4e5f67890123456789a000102)");if(!n)throw new Error("primaryTjpAddr is required (E: a1b2c3d4e5f67890123456789a000104)");if(!s)throw new Error("delegateSecret is required (E: a1b2c3d4e5f67890123456789a000105)");let u=o||"primary-device",p=e?tr.fromTemplate(e):tr.buildKeystone(r);p.withUsername(`${t}-sync-${u}`).withDescription(`Sync Delegate for ${t} on ${u}`).withDetails({client:"space-gib-web",role:ha,deviceTag:u,primaryTjpAddr:n,...i?{custodianReqs:i}:{},...c||{}}),a&&p.withExpiration(a);let h=await p.compileConfigs(),g=p.getFrameDetails();return await new Qr().genesis({masterSecret:s,configs:h,metaspace:l,space:d,frameDetails:g,isPrimary:!1})}catch(u){throw console.error(`${b} ${E(u)}`),u}}f(Nl,"createSyncDelegateKeystone");function On({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(On,"isKeystoneExpired");function pa({delegateInfo:r,delegateKeystone:e,nowUTC:t}){if(e)return On({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(pa,"isDelegateExpired");function Zm({keystone:r,aggregatedDetails:e,providerId:t}){if(!r)return!1;let o=`${eo}${t}`;if(r.data?.challengePools?.some(s=>s.id===o))return!0;if(!(r.data?.frameDetails?.custodyMode==="hybrid"||e?.custodyMode==="hybrid"||r.data?.custodyMode==="hybrid")){let s=e?.custodianProvider||r.data?.frameDetails?.custodianProvider||r.data?.custodianProvider;if(s&&String(s).toLowerCase()===String(t).toLowerCase())return!0}return!1}f(Zm,"isSsoProviderLinked");function Qm({keystone:r,aggregatedDetails:e}){if(!r)return{isSovereign:!1,isCustodial:!1,isHybrid:!1,providers:[],emails:[]};let t=e?.emails||r.data?.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 h of o)if(h.id.startsWith(eo)){let g=h.id.substring(eo.length);g&&a.add(g)}i&&n&&a.add(n);let c=Array.from(a),l=c.length>0||i,b=o.some(h=>h.id==="manage")&&!i,u=l;return{isSovereign:b,isCustodial:u,isHybrid:b&&u,providers:c,emails:t}}f(Qm,"getKeystoneCapabilities");var be=!1;async function Nn({timeline:r}){let e=`[${Nn.name}]`;try{if(be&&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=se({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{be&&console.log(`${e} complete.`)}}f(Nn,"getLockScope");async function Cl({timeline:r,rel8nInfos:e,rel8nRemovalInfos:t,timelineIndexInfo:o,metaspace:n,space:s,skipLock:i,noDna:a}){let c=`[${Cl.name}]`;try{if(be&&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 Nn({timeline:r}),d=f(async()=>{if(!s)throw new Error("(UNEXPECTED) space falsy? couldn't even get default local user space? (E: 845c4181c8c15d7219166ceb3c4dca25)");let u=_({ibGib:r}),p=await n.getLatestAddr({addr:u,space:s});if(!p)throw new Error(`${c} (UNEXPECTED) Could not get latest address for timeline ${_({ibGib:r})}. (E: a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9)`);let h=Re({ibGib:r});if(u!==p){let G=await n.get({addrs:[p],space:s});if(G.errorMsg||(G.ibGibs??[]).length!==1)throw new Error(`${c} (UNEXPECTED) couldn't get latest timeline ibgib (${p}) from space (${s.ib}). errorMsg: ${G.errorMsg??"[unknown error]"} (E: b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0)`);h=G.ibGibs.at(0)}let g;if(t&&t.length>0){g={};for(let G of t){let{rel8nName:I,ibGibAddrs:S}=G;if(S.length===0){console.warn(`${c} tried to remove 0 ibGibAddrs in rel8nName ${I}? skipping... (W: 93aeb601be66d680989e72ec70e4c826)`);continue}g[I]||(g[I]=[]),g[I]=g[I].concat(S)}}let m={};for(let G of e){let{rel8nName:I,ibGibs:S}=G;if(S.length===0){console.warn(`${c} tried to add 0 ibGibs to rel8nName ${I}? skipping... (W: 708252dfdeb60757fee4554e769aaa25)`);continue}m[I]||(m[I]=[]),m[I].push(...S.map(w=>_({ibGib:w})))}let $=await $e({src:h,rel8nsToRemoveByAddr:g,rel8nsToAddByAddr:m,dna:!a,nCounter:!0}),y=$.newIbGib;return await n.persistTransformResult({resTransform:$,space:s}),o&&await Cn({type:o.type,rel8nInfos:[{rel8nName:o.rel8nName,ibGibs:[y]}],metaspace:n,space:s,skipLock:i}),await n.registerNewIbGib({ibGib:y,space:s}),y},"fn");return i?await d():await Se({scope:l,secondsValid:180,maxDelayMs:100,maxLockAttempts:1800,space:s,callerInstanceId:me(),fn:d})}catch(l){throw console.error(`${c} ${E(l)}`),l}finally{be&&console.log(`${c} complete.`)}}f(Cl,"appendToTimeline");async function Cn({type:r,rel8nInfos:e,dataToAddOrPatch:t,metaspace:o,space:n,skipLock:s}){let i=`[${Cn.name}]`;try{if(be&&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: a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6)`);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:b}=l;b.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;b.forEach($=>{let y=_({ibGib:$}),G=$.rel8ns?.past??[];g.filter(I=>[...G,y].includes(I)).forEach(I=>m.add(I))}),m.size>0&&(h=Array.from(m))}await o.rel8ToSpecialIbGib({type:r,rel8nName:d,ibGibsToRel8:b,addrsToUnRel8:h,space:n,linked:!1,severPast:!1,deletePreviousSpecialIbGib:!1})}if(Object.keys(t??{}).length>0){let l=await c(),d=await Me({src:l,dataToAddOrPatch:t,dna:!1,linkedRel8ns:[V.past],nCounter:!0}),b=d.newIbGib;await re({resTransform:d,space:n});let u=oe({type:r});await o.setConfigAddr({key:u,addr:_({ibGib:b}),space:n}),await o.registerNewIbGib({ibGib:b,space:n})}},"fn");s?await a():await Se({scope:r,secondsValid:60,maxDelayMs:100,maxLockAttempts:600,space:n,fn:a})}catch(a){throw console.error(`${i} ${E(a)}`),a}finally{be&&console.log(`${i} complete.`)}}f(Cn,"updateSpecialIndex");async function Pn({timeline:r,timelineAddr:e,metaspace:t,space:o}){let n=`[${Pn.name}]`;try{if(be&&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: a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9)`);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=Re({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: b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0)`);i=a.ibGibs.at(0)}return i}catch(s){throw console.error(`${n} ${E(s)}`),s}finally{be&&console.log(`${n} complete.`)}}f(Pn,"getLatestTimelineIbGibDto_nonLocking");async function Pl({timeline:r,timelineAddr:e,mut8Opts:t,metaspace:o,space:n,skipLock:s,timelineIndexInfo:i,noDna:a}){let c=`[${Pl.name}]`;try{if(be&&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 u=await o.get({addrs:[e],space:n});if(!u.success||u.ibGibs?.length!==1)throw new Error(`couldn't get timeline ibGib from timelineAddr (${e}) in space (${n?.ib??"undefined"}) (E: genuuid)`);r=u.ibGibs.at(0)}let l=await Nn({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 u=await Pn({timeline:r,metaspace:o,space:n}),p=await Me({...t,src:u,dna:!a,nCounter:!0}),h=p.newIbGib;return await o.persistTransformResult({resTransform:p,space:n}),i&&await Cn({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 Se({scope:l,secondsValid:180,maxDelayMs:100,maxLockAttempts:1800,space:n,callerInstanceId:me(),fn:d})}catch(l){throw console.error(`${c} ${E(l)}`),l}finally{be&&console.log(`${c} complete.`)}}f(Pl,"mut8Timeline");async function Rl({ib:r,data:e,rel8ns:t,noDna:o,parentIb:n,parentIbGib:s,metaspace:i,space:a}){let c=`[${Rl.name}]`;try{if(be&&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=j.primitive({ib:n}):s=W;let l=await j.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(Rl,"createTimeline");async function ga({ibGib:r,metaspace:e,space:t}){let o=`[${ga.name}]`;try{if(be&&console.log(`${o} starting...`),t??=await e.getLocalUserSpace({lock:!1}),!t)throw new Error("(UNEXPECTED) space is required. (E: c1b9a9b8c7d6e5f4a3b2a1a0b9c8d7e6)");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: d2c0b1a9a8b7c6d5e4f3a2b1a0b9c8d7)`)}return s.ibGibs}catch(n){throw console.error(`${o} ${E(n)}`),n}}f(ga,"getDna");async function ma({timeline:r,getLatest:e,includeDna:t,metaspace:o,space:n}){let s=`[${ma.name}]`;try{if(be&&console.log(`${s} starting... (I: 7fbc442a27e8f9fda8ac4228ded84825)`),n??=await o.getLocalUserSpace({lock:!1}),!n)throw new Error("(UNEXPECTED) space is required. (E: e3d1c0b1a9a8b7c6d5e4f3a2b1a0b9c8)");let i=e?await Pn({timeline:r,metaspace:o,space:n}):Re({ibGib:r}),a=_({ibGib:i}),c={},l=t?Wr({ibGibs:await ga({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 b=await o.get({addrs:d,space:n});if(!b.success||(b.ibGibs??[]).length!==d.length){let p=d.filter(h=>!b.ibGibs?.some(g=>_({ibGib:g})===h));throw new Error(`Could not get all dna ibGibs for ${a}. Addrs not found: ${p.join(", ")}. Errors: ${b.errorMsg??"[unknown error (E: 887339d8b5580ed1ac9892a554255525)]"} (E: 4ab7a8a58adff4e238171f7c110c6825)`)}c=Wr({ibGibs:b.ibGibs})??{};let u=[];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)");u.push(h)}return{headIbGib:i,orderedPastIbGibs:u,pastIbGibMap:c,dnaMap:l}}catch(i){throw console.error(`${s} ${E(i)}`),i}finally{be&&console.log(`${s} complete.`)}}f(ma,"getHistory");async function Ll({timeline:r,getLatest:e,metaspace:t,space:o}){let n=`[${Ll.name}]`;try{return be&&console.log(`${n} starting... (I: c7a328b14018642138ebb47870c15626)`),(await ma({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{be&&console.log(`${n} complete.`)}}f(Ll,"getHistoryAddrs");var ot=!1,Rn=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{ot&&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 ot&&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{ot&&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 ot&&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{ot&&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{ot&&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{ot&&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 ot&&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}}}},to;function mE(){return to||(to=new Rn),to}f(mE,"getApiBridge");function EE(r){to=r}f(EE,"setApiBridge");var Ea=/^error (\w+) ([a-fA-F\d]{32}|undefined)$/;var nt=!1;function $a({rawMsg:r}){let e=`[${$a.name}]`;try{nt&&console.log(`${e} starting...`);let t=Ln({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{nt&&console.log(`${e} complete.`)}}f($a,"getErrorIb");function Ln({rawMsg:r}){let e=`[${Ln.name}]`;try{if(nt&&console.log(`${e} starting...`),!r)throw new Error("(UNEXPECTED) rawMsg required (E: e5bd3b433a1781ebe885534cd2495622)");let t,o=r.match(zn);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(Jn);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{nt&&console.log(`${e} complete.`)}}f(Ln,"parseRawErrorMsg");function mt({rawMsg:r}){let e=`[${mt.name}]`;try{return nt&&console.log(`${e} starting...`),Ae({parentPrimitiveIb:"error",ib:$a({rawMsg:r}),data:Ln({rawMsg:r}),ibRegExpPattern:Ea.source})}catch(t){throw console.error(`${e} ${t.message}`),t}finally{nt&&console.log(`${e} complete.`)}}f(mt,"getErrorIbGib");function Ve({ibGib:r}){let e=`[${Ve.name}]`;try{if(nt&&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{nt&&console.log(`${e} complete.`)}}f(Ve,"isError");var st=!1;function ya(r){let e=`[${ya.name}]`;try{let t=r?`${Yt} ${r}`:Yt;return st&&console.log(`${e} ${t}`),t}catch(t){throw console.error(`${e} ${t.message}`),t}}f(ya,"getArgIb");function Ul({ib:r,ibGib:e}){let t=`[${Ul.name}]`;try{if(st&&console.log(`${t} starting...`),!r)if(e)r=e.ib;else throw new Error("either ib or ibGib required (E: c052a9d76df867626f9ba17141cdce22)");return r.startsWith(Yt)}catch(o){throw console.error(`${t} ${o.message}`),o}finally{st&&console.log(`${t} complete.`)}}f(Ul,"isArg");function Ia(r){let e=`[${Ia.name}]`;try{let t=r?`${vr} ${r}`:vr;return st&&console.log(`${e} ${t}`),t}catch(t){throw console.error(`${e} ${t.message}`),t}}f(Ia,"getResultIb");async function Et({argData:r,ibMetadata:e,noTimestamp:t}){let o=`[${Et.name}]`;try{let n=await j.firstGen({ib:ya(e),parentIbGib:j.primitive({ib:Yt}),data:r,dna:!1,noTimestamp:t});if(n.newIbGib){let{newIbGib:s}=n;return s.rel8ns.past=[],s.gib=await We(s),s}else throw new Error("create ibGib failed")}catch(n){throw console.error(`${o} ${n.message}`),n}}f(Et,"argy_");async function wt({resultData:r,ibMetadata:e,noTimestamp:t}){let o=`[${wt.name}]`;try{let n=await j.firstGen({ib:Ia(e),parentIbGib:j.primitive({ib:vr}),data:r,dna:!1,noTimestamp:t});if(n?.newIbGib){let{newIbGib:s}=n;return s.rel8ns.past=[],s.gib=await We(s),s}else throw new Error("create ibGib failed")}catch(n){throw console.error(`${o} ${n.message}`),n}}f(wt,"resulty_");function Un({ibGib:r}){let e=`[${Un.name}]`;try{if(st&&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{st&&console.log(`${e} complete.`)}}f(Un,"isCommand");function Mn({ibGib:r}){let e=`[${Mn.name}]`;try{return st&&console.log(`${e} starting... (I: aad0a14f4d62061424fc92da4d53d823)`),typeof r.witness=="function"}catch(t){throw console.error(`${e} ${t.message}`),t}finally{st&&console.log(`${e} complete.`)}}f(Mn,"isWitness");var ro="subject",kn=/^[a-zA-Z0-9_\-.]{1,255}$/,_a="subject",Ta="",oo="subject is a cool ibgib witness that has seriously fascinating behavior.";var Aa="observable";var it={subscribe:"subscribe"},Sa=Object.values(it);var Ga={next:"next",error:"error",complete:"complete"};var at={...it,...Ga};var ar={version:"1",uuid:Ta,name:_a,description:oo,classname:"Subject_V1",persistOptsAndResultIbGibs:!1,allowPrimitiveArgs:!0,catchAllErrors:!0,trace:!1},jn=void 0;var no=class r{static{f(this,"WitnessFactoryBase")}lc=`[${r.name}]`};var Bn=!1,Pt=class r extends no{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(Bn&&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)Ao({obj:e,value:a.value,path:c,logalot:Bn,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{Bn&&console.log(`${s} complete.`)}}};var xa=!1,Rt=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 k(),this.gib=await K({ibGib:this.toIbGibDto()})}toIbGibDto(){return Re({ibGib:this})}loadIbGibDto(e){let t=`${this.lc}[${this.loadIbGibDto.name}]`;try{return xa&&console.log(`${t} starting...`),e.ib||console.warn(`${t} dto.ib is falsy.`),e.gib||console.warn(`${t} dto.gib is falsy.`),this.ib=O(e.ib),this.gib=O(e.gib),e.data?this.data=O(e.data):delete this.data,e.rel8ns?this.rel8ns=O(e.rel8ns):delete this.rel8ns,Promise.resolve()}catch(o){throw console.error(`${t} ${o.message}`),o}finally{xa&&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 va="subscription",Fn=/^[a-zA-Z0-9_\-.]{1,255}$/,Da="",Oa="subscription",so="subscription is a cool ibgib witness that has seriously fascinating behavior.";var cr={unsubscribe:"unsubscribe",unsubscribed:"unsubscribed"};var qn={version:"1",uuid:Da,name:Oa,description:so,classname:"Subscription_V1",persistOptsAndResultIbGibs:!1,allowPrimitiveArgs:!0,catchAllErrors:!1,trace:!1},Hn=void 0;var Na=!1;function Kn({ibGib:r}){let e=`[${Kn.name}]`;try{Na&&console.log(`${e} starting... (I: 3aadb634377acbe42984b61c91975323)`);let{ib:t}=r;return[Aa,ro].some(n=>t.includes(n))}catch(t){throw console.error(`${e} ${t.message}`),t}finally{Na&&console.log(`${e} complete.`)}}f(Kn,"isObservable");var L=!1,io=class r extends Rt{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(L&&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=co({data:this.data,classname:"Subscription_V1"}),this.gib=await K({ibGib:this})}catch(t){throw console.error(`${e} ${t.message}`),t}finally{L&&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(L&&console.log(`${t} ib: ${o} (I: 4de7771f477dc5b36933343b694ce223)`),o===cr.unsubscribe)return L&&console.log(`${t} routing unsubscribe cmd (I: 5633b86d467af2aa67388abf559a3c23)`),this.witness_unsubscribe();if(o===cr.unsubscribed)return L&&console.log(`${t} routing unsubscribed query (I: 6e0ae61d90f1974d76bcdbb47970e723)`),this.witness_unsubscribed();if(Kn({ibGib:e}))return L&&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(L&&console.log(`${e} starting... (I: a3d549220ef24604956aaa2c66fff09b)`),!this._subscribed)return console.warn(`${e} tried to unsubscribe but this._subscribed is ${this._subscribed} (W: cdc94f59447d4011b4b4cc12ef9ec074)`),W;if(this._unsubscribed)return console.warn("{lc} this._unsubscribed already true. (W: fa287d76cec040e0978a8add5c758093)"),W;if(!this._srcObservable)throw new Error("(UNEXPECTED) this._subscribed but this._srcObservable falsy? (E: 83687993b7bea299b4ba2438b530a123)");return L&&(console.log(`${e} inspecting srcObservable before src.witness... (I: f15a33d10f1cae3cec6fdbdb32596823)`),console.dir(this._srcObservable)),await this._srcObservable.witness(this),L&&(console.log(`${e} inspecting srcObservable after src.witness... (I: f15a33d10f1cae3cec6fdbdb32596823)`),console.dir(this._srcObservable)),this._subscribed=!1,this._unsubscribed=!0,delete this._srcObservable,L&&console.log(`${e} this._ (I: 7b1bc418a3d32757772391cad7a49523)`),W}catch(t){throw console.error(`${e} ${t.message}`),t}finally{L&&console.log(`${e} complete.`)}}async witness_observable({ibGib:e}){let t=`${this.lc}[${this.witness_observable.name}]`;try{if(L&&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,L&&console.log(`${t} this._srcObservable set to ibgib with ib: ${e.ib} (I: 4b81d17243f60dfdcc2163fbb55e9223)`),this._subscribed=!0,W}catch(o){throw console.error(`${t} ${o.message}`),o}finally{L&&console.log(`${t} complete.`)}}async witness_unsubscribed(){let e=`${this.lc}[${this.witness_unsubscribed.name}]`;try{if(L&&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?Lo:Is;return L&&console.log(`${e} result: ${H(t)} (I: b488cf36ce39e006a81d3ad3db5b4a23)`),t}catch(t){throw console.error(`${e} ${t.message}`),t}finally{L&&console.log(`${e} complete.`)}}async unsubscribe(){let e=`${this.lc}[${this.unsubscribe.name}]`;try{L&&console.log(`${e} starting... (I: ef7f3f4787a74fcca65d761880f44594)`);let t=await this.witness(j.primitive({ib:cr.unsubscribe}));if(!t)throw new Error("(UNEXPECTED) unsubscribe returned undefined? (E: 7013193490b94b6880f1049c36577d6f)");if(Ve({ibGib:t})){let o=t;throw new Error(`${o.data.raw} (E: fca1200dccb14f84968b2462f1b4c29e)`)}}catch(t){throw console.error(`${e} ${t.message}`),t}finally{L&&console.log(`${e} complete.`)}}async unsubscribed(){let e=`${this.lc}[${this.unsubscribed.name}]`;try{L&&console.log(`${e} starting... (I: 8ee9a93be61647d6aef6a4fa03e96dad)`);let t=await this.witness(j.primitive({ib:cr.unsubscribed}));if(!t)throw new Error("(UNEXPECTED) unsubscribe returned undefined? (E: 5051d7ff4a4d4bf7864c520b53f028d5)");let o=t.ib===Lo.ib;return L&&console.log(`${e} resUnsubscribed: ${o} (I: b4800166c58d5ba2ca1dccaa53de2323)`),o}catch(t){throw console.error(`${e} ${t.message}`),t}finally{L&&console.log(`${e} complete.`)}}async validateThis(){let e=`${this.lc}[${this.validateThis.name}]`;try{return L&&console.log(`${e} starting...`),this.data,[]}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{L&&console.log(`${e} complete.`)}}async argy({argData:e,ibMetadata:t,noTimestamp:o,ibGibs:n}){let s=await Et({argData:e,ibMetadata:t,noTimestamp:o});return n&&(s.ibGibs=n),s}async resulty({resultData:e,ibGibs:t}){let o=await wt({resultData:e});return t&&(o.ibGibs=t),o}},ao=class r extends Pt{static{f(this,"Subscription_V1_Factory")}lc=`[${r.name}]`;getName(){return io.name}async newUp({data:e,rel8ns:t}){let o=`${this.lc}[${this.newUp.name}]`;try{L&&console.log(`${o} starting...`),e??=O(qn),e=e,t=t??Hn?O(Hn):void 0,e.uuid||=await k();let{classname:n}=e,s=co({data:e}),i=await Ae({parentPrimitiveIb:`witness ${n}`,ib:s,data:e,rel8ns:t}),a=new io(void 0,void 0);return await a.loadIbGibDto(i),L&&console.log(`${o} witnessDto: ${H(i)} (I: 5e41337176d1441f9a5c7b43664d43ef)`),{newIbGib:a}}catch(n){throw console.error(`${o} ${E({error:n})}`),n}finally{L&&console.log(`${o} complete.`)}}async witnessToForm({witness:e}){let t=`${this.lc}[${this.witnessToForm.name}]`;try{L&&console.log(`${t} starting...`);let{data:o}=e;if(!o)throw new Error("(UNEXPECTED) witness.data falsy? (E: ef44497ff97a4e5bac004d52c4ff40eb)");L&&console.log(`${t} data: ${H(o)} (I: c3f4c3d85386461aaefbe33524ff9cbd)`);let n=await Ut({n:100}),s=new lo().with({idPool:n}).name({of:o.name,required:!1}).description({of:o.description??so}).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{L&&console.log(`${t} complete.`)}}async formToWitness({form:e}){let t=O(qn);return this.patchDataFromItems({data:t,items:e.items,pathDelimiter:yt}),await this.newUp({data:t})}};var fo=!1;function Ca({data:r}){let e=`[${Ca.name}]`;try{if(fo&&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(Fn)||t.push(`name must match regexp: ${Fn} (E: 21bf77e398d47e9d035376510505eda2)`):t.push("name required."),n?n.match(Q)||t.push(`uuid must match regexp: ${Q} (E: e53fd08ae69e945b37ed895b864b6bd7)`):t.push("uuid required."),s&&(s.match(Ye)||t.push(`classname must match regexp: ${Ye}`)),t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{fo&&console.log(`${e} complete.`)}}f(Ca,"validateCommonSubscriptionData");function co({data:r,classname:e}){let t=`[${co.name}]`;try{let o=Ca({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 ${va} ${e} ${n}`}catch(o){throw console.error(`${t} ${E(o)}`),o}}f(co,"getSubscriptionIb");var lo=class r extends et{static{f(this,"SubscriptionFormBuilder")}lc=`[${r.name}]`;constructor(){super(),this.what="subscription"}};function bo({ibGib:r}){let e=`[${bo.name}]`;try{if(fo&&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{fo&&console.log(`${e} complete.`)}}f(bo,"isSubscription");async function Pa(){return(await new ao().newUp({})).newIbGib}f(Pa,"newupSubscription");var Xn="observable_event";var Ra=!1;async function Vn({eventType:r,srcObservable:e,payload:t}){let o=`[${Vn.name}]`;try{if(Ra&&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(Q))throw new Error(`valid srcObservable.data.uuid required. must pass UUID_REGEXP: ${Q.source} (E: 10f4bd1863f18250cc79cd65221da223)`);let n={uuid:await k(),eventType:r,srcObservableId:e.data.uuid,"@srcObservableAddr":_({ibGib:e}),"@payloadAddr":_({ibGib:t})};return await Ae({parentPrimitiveIb:Xn,ib:La({data:n}),data:n})}catch(n){throw console.error(`${o} ${n.message}`),n}finally{Ra&&console.log(`${o} complete.`)}}f(Vn,"getObservableEventIbGib");function La({data:r,classname:e}){let t=`[${La.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`${Xn} ${e} ${r.uuid}`}catch(o){throw console.error(`${t} ${E(o)}`),o}}f(La,"getObservableEventIb");var Y=!1,uo=class r extends Rt{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(Un({ibGib:e}))return this.witness_cmd({arg:e});if(Mn({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(Y&&console.log(`${t} starting... (I: 69257fac8328b9de9755fdd237b92723)`),e.data.cmd===it.subscribe)return this.witness_subscribe_cmd({ibGib:e});throw new Error(`unknown command. must be of type ObservableCmd (${Sa}) (E: 5910e5cbafead25ea2917a65a3fc4123)`)}catch(o){throw console.error(`${t} ${o.message}`),o}finally{Y&&console.log(`${t} complete.`)}}async witness_otherWitness({arg:e}){let t=`${this.lc}[${this.witness_otherWitness.name}]`;try{return Y&&console.log(`${t} starting... (I: 871d0b7a2bef4596bad430f1cbacde02)`),bo({ibGib:e})?this.witness_subscriptionIbGib({arg:e}):this.witness_subscribe_nonCmdWitness({arg:e})}catch(o){throw console.error(`${t} ${o.message}`),o}finally{Y&&console.log(`${t} complete.`)}}async witness_subscriptionIbGib({arg:e}){let t=`${this.lc}[${this.witness_subscriptionIbGib.name}]`;try{if(Y&&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 W}catch(o){throw console.error(`${t} ${o.message}`),o}finally{Y&&console.log(`${t} complete.`)}}async replayPastPayloads({observer:e,subscription:t}){let o=`${this.lc}[${this.replayPastPayloads.name}]`;try{Y&&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()){Y&&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{Y&&console.log(`${o} complete.`)}}async witness_subscribe_cmd({ibGib:e}){let t=`${this.lc}[${this.witness_subscribe_cmd.name}]`;try{if(Y&&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 Pa();return Y&&console.log(`${t} subscription created (I: 89ccd97803c66292f9d7334e1e2de523)`),await n.witness(this),await n.initialized,Y&&console.log(`${t} subscription initialized (after witnessing this observable as its src). (I: 3021483402b21c4df64a9173bd223a23)`),this._subscribers[this.getSubscriberKey({subscription:n})]=[n,o],Y&&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{Y&&console.log(`${t} complete.`)}}async witness_subscribe_nonCmdWitness({arg:e}){let t=`${this.lc}[${this.witness_subscribe_nonCmdWitness.name}]`;try{throw Y&&console.log(`${t} starting... (I: d9571dfcab4247d594c838233971886a)`),new Error("not impl (E: 76219cf238ba4f849480bd7c82eefab9)")}catch(o){throw console.error(`${t} ${o.message}`),o}finally{Y&&console.log(`${t} complete.`)}}async subscribe(e){let t=`${this.lc}[${this.subscribe.name}]`;try{Y&&console.log(`${t} starting... (I: 0dec9a06c562711e19482d45a7075e23)`);let o;if($t({ibGib:e})){let n=await this.argy({argData:{cmd:it.subscribe,ibGibAddrs:[_({ibGib:e})]},ibGibs:[e]});o=await this.witness(n)}else o=await this.witness(e);if(!bo({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{Y&&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{Y&&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($t({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():Y&&console.log(`${n} no error handler for observer. skipping. (I: 6a8a52c2012c464790eb406d2ae0383f)`)}else{let l=await Vn({eventType:o,srcObservable:this,payload:e});await c.witness(l)}}}catch(s){throw console.error(`${n} ${s.message}`),s}finally{Y&&console.log(`${n} complete.`)}}async validateThis(){let e=`${this.lc}[${this.validateThis.name}]`;try{return Y&&console.log(`${e} starting...`),this.data,[]}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Y&&console.log(`${e} complete.`)}}async argy({argData:e,ibMetadata:t,noTimestamp:o,ibGibs:n}){let s=await Et({argData:e,ibMetadata:t,noTimestamp:o});return n&&(s.ibGibs=n),s}async resulty({resultData:e,ibGibs:t}){let o=await wt({resultData:e});return t&&(o.ibGibs=t),o}};var M=!1,po=class r extends uo{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{M&&console.log(`${t} starting... (I: 8e47b752314870ec78eb14342621f723)`);let o=await this.argy({argData:{cmd:at.subscribe,ibGibAddrs:[_({ibGib:e})]},ibGibs:[e]});return await this.witness(o)}catch(o){throw console.error(`${t} ${o.message}`),o}finally{M&&console.log(`${t} complete.`)}}async next(e){let t=`${this.lc}[${this.next.name}]`;try{M&&console.log(`${t} starting... (I: b30363827c56450ca918c69aa15b0046)`);let o=await this.argy({argData:{cmd:at.next,ibGibAddrs:[_({ibGib:e})]},ibGibs:[e]});await this.witness(o)}catch(o){throw console.error(`${t} ${o.message}`),o}finally{M&&console.log(`${t} complete.`)}}async error(e){let t=`${this.lc}[${this.error.name}]`;try{M&&console.log(`${t} starting... (I: 7fcc30e3763c429ea8b212491ad9455a)`);let o;if(typeof e=="string")o=await mt({rawMsg:e});else if(e instanceof Error||typeof e.message=="string")o=await mt({rawMsg:E(e)});else if(e.ib&&Ve({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:at.error,ibGibAddrs:[_({ibGib:o})]},ibGibs:[o]});await this.witness(n)}catch(o){throw console.error(`${t} ${o.message}`),o}finally{M&&console.log(`${t} complete.`)}}async complete(){let e=`${this.lc}[${this.complete.name}]`;try{M&&console.log(`${e} starting... (I: 5faaf13c6b0543d399815c03b9cdf80c)`);let t=await this.argy({argData:{cmd:at.complete}});await this.witness(t)}catch(t){throw console.error(`${e} ${t.message}`),t}finally{M&&console.log(`${e} complete.`)}}async witness_cmd({arg:e}){let t=`${this.lc}[${this.witness_cmd.name}]`;try{M&&console.log(`${t} starting... (I: 2bf7cbcadba446fa92cb649906b2b260)`);let{cmd:o}=e.data;switch(o){case at.next:return this.witness_next({ibGib:e});case at.error:return this.witness_error({ibGib:e});case at.complete:return this.witness_complete({ibGib:e});default:return super.witness_cmd({arg:e})}}catch(o){throw console.error(`${t} ${o.message}`),o}finally{M&&console.log(`${t} complete.`)}}async witness_next({ibGib:e}){let t=`${this.lc}[${this.witness_next.name}]`;try{if(M&&console.log(`${t} starting... (I: 600da780f13f5137a2f76aad344b2923)`),this.isCompleteOrErrored)return M&&console.log(`${t} this.isCompleteOrErrored is true. returning early without producing. (I: aa823831853b134b19657c8673838c23)`),W;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(M&&console.log(`${t} ensuring subscription not unsubscribed (I: ade3fd6d6ff2b5ec69eb8143e32ce223)`),!await i.unsubscribed())M&&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 W}catch(o){throw console.error(`${t} ${o.message}`),o}finally{M&&console.log(`${t} complete.`)}}async witness_error({ibGib:e}){let t=`${this.lc}[${this.witness_error.name}]`;try{if(M&&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($t({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):M&&console.log(`${t} no error handler for observer. skipping. (I: 59f4a1ee59a3a27d523d60cd761be923)`)}else await a.witness(o)}return W}catch(o){throw console.error(`${t} ${o.message}`),o}finally{M&&console.log(`${t} complete.`)}}async witness_complete({ibGib:e}){let t=`${this.lc}[${this.witness_complete.name}]`;try{M&&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($t({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():M&&console.log(`${t} no error handler for observer. skipping. (I: 6a8a52c2012c464790eb406d2ae0383f)`)}else await i.witness(e)}return W}catch(o){throw console.error(`${t} ${o.message}`),o}finally{M&&console.log(`${t} complete.`)}}async validateThis(){let e=`${this.lc}[${this.validateThis.name}]`;try{return M&&console.log(`${e} starting...`),this.data,[]}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{M&&console.log(`${e} complete.`)}}async argy({argData:e,ibMetadata:t,noTimestamp:o,ibGibs:n}){if(e.cmd===it.subscribe)return super.argy({argData:e,ibMetadata:t,noTimestamp:o,ibGibs:n});{let s=await Et({argData:e,ibMetadata:t,noTimestamp:o});return n&&(s.ibGibs=n),s}}async resulty({resultData:e,ibGibs:t}){let o=await wt({resultData:e});return t&&(o.ibGibs=t),o}},ho=class r extends Pt{static{f(this,"Subject_V1_Factory")}lc=`[${r.name}]`;getName(){return po.name}async newUp({data:e,rel8ns:t}){let o=`${this.lc}[${this.newUp.name}]`;try{M&&console.log(`${o} starting...`),e??=O(ar),e=e,t=t??jn?O(jn):void 0,e.uuid||=await k();let{classname:n}=e,s=Yn({data:e}),i=await Ae({parentPrimitiveIb:`witness ${n}`,ib:s,data:e,rel8ns:t}),a=new po(void 0,void 0);return await a.loadIbGibDto(i),M&&console.log(`${o} witnessDto: ${H(i)} (I: 6736d2b2ddf44fef9a1eb27078dfbf23)`),{newIbGib:a}}catch(n){throw console.error(`${o} ${E({error:n})}`),n}finally{M&&console.log(`${o} complete.`)}}async witnessToForm({witness:e}){let t=`${this.lc}[${this.witnessToForm.name}]`;try{M&&console.log(`${t} starting...`);let{data:o}=e;if(!o)throw new Error("(UNEXPECTED) witness.data falsy? (E: 7b70c96e982d4f81b6ffda54da16b3b8)");M&&console.log(`${t} data: ${H(o)} (I: 75abef56f5004a94b2113e3b1461ac25)`);let n=await Ut({n:100}),s=new go().with({idPool:n}).name({of:o.name,required:!1}).description({of:o.description??oo}).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{M&&console.log(`${t} complete.`)}}async formToWitness({form:e}){let t=O(ar);return this.patchDataFromItems({data:t,items:e.items,pathDelimiter:yt}),await this.newUp({data:t})}};var mo=!1;function Ua({data:r}){let e=`[${Ua.name}]`;try{if(mo&&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(kn)||t.push(`name must match regexp: ${kn} (E: de987eb8fea0b6232f60abf31815095c)`):t.push("name required."),n?n.match(Q)||t.push(`uuid must match regexp: ${Q} (E: 1a6dfda91ad51696f7456bc84dfea60e)`):t.push("uuid required."),s&&(s.match(Ye)||t.push(`classname must match regexp: ${Ye}`)),t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{mo&&console.log(`${e} complete.`)}}f(Ua,"validateCommonSubjectData");function Yn({data:r,classname:e}){let t=`[${Yn.name}]`;try{let o=Ua({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 ${ro} ${e} ${n} ${s}`}catch(o){throw console.error(`${t} ${E(o)}`),o}}f(Yn,"getSubjectIb");var go=class r extends et{static{f(this,"SubjectFormBuilder")}lc=`[${r.name}]`;constructor(){super(),this.what="subject"}};function $t({ibGib:r}){let e=`[${$t.name}]`;try{return mo&&console.log(`${e} starting... (I: b54c252104f710c12951aa43b6ead323)`),typeof r.next=="function"}catch(t){throw console.error(`${e} ${t.message}`),t}finally{mo&&console.log(`${e} complete.`)}}f($t,"isObserver");async function U8({data:r,replay:e}={}){let t=new ho;return r??=O(ar),e&&(r.replay=!0),(await t.newUp({data:r})).newIbGib}f(U8,"newupSubject");var Eo="anon_fn",Ma={fnHash:""};var ka=!1;function Wn({data:r}){let e=`[${Wn.name}]`;try{if(ka&&console.log(`${e} starting... (I: 37bb06e0390c5bcadf04501727d64923)`),!r?.fnHash)throw new Error("data.fnHash required (E: 2e560f2c59822bc5ba024d4a8e99d323)");return`witness ${Eo} ${r.fnHash}`}catch(t){throw console.error(`${e} ${t.message}`),t}finally{ka&&console.log(`${e} complete.`)}}f(Wn,"getAnonymousFnIb");var ct=class{static{f(this,"AnonymousFnWitness_V1")}fn;ib=Eo.concat();gib=P;data=O(Ma);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=Wn({data:this.data}),this.gib=await K({ibGib:this}),this.fn(e)}};var wo=!1;function Ml({err:r}){let e=`[${Ml.name}]`;try{if(wo&&console.log(`${e} starting... (I: 96f8b767c50f24768ced7beebb291723)`),ln(r)){let t=r;if(!r.data)throw new Error("err isIbGib but err.data is false. (E: 151a6bab647c638c454fd277ac468f23)");if(Ve({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{wo&&console.log(`${e} complete.`)}}f(Ml,"extractObsErrMsg");function kl(r){let e=`[${kl.name}]`;try{wo&&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),W),"fnNext"),n=f(async d=>(d.ib==="complete"?t.complete&&await t.complete():Ve({ibGib:d})?t.error&&await t.error(d):await t.next(d),W),"fnWitness"),s=new ct(o),i=new ct(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 b;if(typeof d=="string")b=E(d);else if(d.ib)if(Ve({ibGib:d}))b=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?b=E(d):typeof d.message=="string"?b=E(d.message):b="[unknown thing came down pipe that ain't an error]";console.error(`Error occurred but observer.error is falsy. error: ${b} (E: 822c60c7c4d542efacd5c2dea7e88062)`)}),l=new ct(async d=>(c(d),W));if(a.error=async d=>{typeof d=="string"?d=await mt({rawMsg:d}):d instanceof Error&&(d=await mt({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,b=new ct(async u=>(await d(),W));a.complete=async()=>{try{await b.witness(W)}catch(u){console.error(`${e} there was an error when executing completeAnonFnWitness (wrapper for observer.complete fn) error: ${E(u)} (E: c9e61b08429e42c1b85d2215f735ba2f)`)}}}return a}catch(t){throw console.error(`${e} ${t.message}`),t}finally{wo&&console.log(`${e} complete.`)}}f(kl,"fnObs");export{f as a,Q as b,ge as c,O as d,ve as e,X as f,k as g,H as h,le as i,E as j,Io as k,me as l,dr as m,Ha as n,ts as o,Tt as p,P as q,W as r,ee as s,De as t,as as u,We as v,_ as w,R as x,V as y,za as z,te as A,K as B,se as C,Me as D,$e as E,ie as F,jt as G,St as H,At as I,j as J,zd as K,Jd as L,Zd as M,hr as N,Ja as O,bs as P,us as Q,hf as R,gf as S,mf as T,Za as U,Ef as V,mr as W,Po as X,Qa as Y,Gf as Z,wr as _,Je as $,$r as aa,xs as ba,yr as ca,rc as da,oc as ea,Kb as fa,Xb as ga,Vb as ha,Yb as ia,Wb as ja,zb as ka,lc as la,dc as ma,Cs as na,Ko as oa,bc as pa,uc as qa,xt as ra,Kt as sa,Bs as ta,Ic as ua,Hs as va,Uu as wa,ju as xa,ae as ya,Qo as za,en as Aa,re as Ba,_c as Ca,Or as Da,Nr as Ea,de as Fa,tn as Ga,Xs as Ha,Te as Ia,Gt as Ja,Zo as Ka,Ws as La,Se as Ma,Wt as Na,Ac as Oa,Sc as Pa,Gc as Qa,xc as Ra,Ge as Sa,up as Ta,vc as Ua,Dc as Va,Cr as Wa,Pe as Xa,Oc as Ya,Nc as Za,Cc as _a,Pc as $a,Ae as ab,xp as bb,ci as cb,Vt as db,Rr as eb,Jt as fb,li as gb,ue as hb,Re as ib,ln as jb,Xt as kb,dn as lb,tt as mb,Mp as nb,jc as ob,kp as pb,jp as qb,Bp as rb,Fp as sb,fi as tb,Pp as ub,sh as vb,ih as wb,ah as xb,ch as yb,lh as zb,dh as Ab,fh as Bb,vt as Cb,Fc as Db,qc as Eb,Hc as Fb,bt as Gb,_i as Hb,Kc as Ib,Ai as Jb,Ti as Kb,Vc as Lb,Yc as Mb,Wc as Nb,zc as Ob,Jc as Pb,Hh as Qb,Zc as Rb,Qc as Sb,el as Tb,mn as Ub,pn as Vb,kr as Wb,tl as Xb,rl as Yb,bi as Zb,ol as _b,vi as $b,sg as ac,nl as bc,Le as cc,we as dc,Qt as ec,yn as fc,In as gc,Br as hc,Ci as ic,Xe as jc,hl as kc,gl as lc,Gn as mc,wl as nc,Ig as oc,_g as pc,Yi as qc,tr as rc,Yr as sc,Jm as tc,Nl as uc,pa as vc,Zm as wc,Qm as xc,pt as yc,rr as zc,Gl as Ac,xl as Bc,Om as Cc,Zr as Dc,Qr as Ec,Cl as Fc,Cn as Gc,Pl as Hc,Rl as Ic,ma as Jc,Ll as Kc,Rn as Lc,mE as Mc,EE as Nc,mt as Oc,Ml as Pc,kl as Qc,Ul as Rc,Et as Sc,wt as Tc,Un as Uc,Rt as Vc,U8 as Wc};