@ibgib/space-gib 0.0.3 → 0.0.5

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.
Files changed (63) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/IMPLEMENTATION.md +9 -13
  3. package/README.md +7 -0
  4. package/dist/client/bootstrap.mjs +1 -1
  5. package/dist/client/bootstrap.mjs.map +1 -1
  6. package/dist/client/chunk-ANGVYAEK.mjs +42 -0
  7. package/dist/client/chunk-ANGVYAEK.mjs.map +7 -0
  8. package/dist/client/chunk-IRGFDQRD.mjs +1920 -0
  9. package/dist/client/chunk-IRGFDQRD.mjs.map +7 -0
  10. package/dist/client/index.html +103 -5
  11. package/dist/client/index.mjs +1 -1
  12. package/dist/client/script.mjs +1 -1
  13. package/dist/client/style.css +466 -61
  14. package/dist/respec-gib.node.mjs +5 -0
  15. package/dist/server/server.mjs +533 -233
  16. package/dist/server/server.mjs.map +2 -2
  17. package/package.json +6 -6
  18. package/src/client/AUTO-GENERATED-version.mts +1 -1
  19. package/src/client/components/identity-header/IMPLEMENTATION.md +45 -0
  20. package/src/client/components/identity-header/identity-header.css +74 -0
  21. package/src/client/components/identity-header/identity-header.html +10 -0
  22. package/src/client/components/identity-header/identity-header.mts +361 -0
  23. package/src/client/components/identity-manager/IMPLEMENTATION.md +100 -0
  24. package/src/client/components/identity-manager/identity-manager.css +467 -0
  25. package/src/client/components/identity-manager/identity-manager.html +113 -0
  26. package/src/client/components/identity-manager/identity-manager.mts +767 -0
  27. package/src/client/components/keystone-creator/keystone-creator.css +2 -76
  28. package/src/client/components/keystone-creator/keystone-creator.html +41 -26
  29. package/src/client/components/keystone-creator/keystone-creator.mts +178 -41
  30. package/src/client/dev-tools/base-tools.mts +252 -0
  31. package/src/client/dev-tools/common.mts +217 -0
  32. package/src/client/dev-tools/phase-1.mts +156 -0
  33. package/src/client/dev-tools/phase-2.mts +143 -0
  34. package/src/client/dev-tools/phase-3.mts +189 -0
  35. package/src/client/dev-tools/phase-4-1.mts +197 -0
  36. package/src/client/dev-tools/phase-4-10.mts +884 -0
  37. package/src/client/dev-tools/phase-4-2.mts +388 -0
  38. package/src/client/dev-tools/phase-4-3.mts +391 -0
  39. package/src/client/dev-tools/phase-4-4.mts +374 -0
  40. package/src/client/dev-tools/phase-4-5.mts +376 -0
  41. package/src/client/dev-tools/phase-4-6.mts +273 -0
  42. package/src/client/dev-tools/phase-4-7.mts +399 -0
  43. package/src/client/dev-tools/phase-4-8.mts +430 -0
  44. package/src/client/dev-tools/phase-4-9.mts +398 -0
  45. package/src/client/dev-tools/phase-4.mts +1302 -0
  46. package/src/client/dev-tools.mts +52 -1194
  47. package/src/client/index.html +103 -5
  48. package/src/client/style.css +466 -61
  49. package/src/client/ui/shell/space-gib-shell-constants.mts +0 -2
  50. package/src/client/ui/shell/space-gib-shell-service.mts +82 -10
  51. package/src/common/common-constants.mts +0 -0
  52. package/src/common/keystone-policies.json +40 -43
  53. package/src/common/keystone-policies.mts +3 -5
  54. package/src/server/path-helper.respec.mts +99 -94
  55. package/src/server/serve-gib/README.md +9 -0
  56. package/src/server/serve-gib/handlers/api/keystone/keystone-genesis.handler.mts +1 -1
  57. package/src/server/serve-gib/handlers/api/keystone/keystone-get.respec.mts +1 -1
  58. package/src/server/serve-gib/handlers/ws/sync-upgrade-handler-base.mts +31 -3
  59. package/src/server/serve-gib/handlers/ws/ws-helper.mts +73 -45
  60. package/dist/client/chunk-2KJC5XKE.mjs +0 -31
  61. package/dist/client/chunk-2KJC5XKE.mjs.map +0 -7
  62. package/dist/client/chunk-QNIXTRFO.mjs +0 -235
  63. package/dist/client/chunk-QNIXTRFO.mjs.map +0 -7
@@ -0,0 +1,42 @@
1
+ var Td=Object.defineProperty;var f=(r,e)=>Td(r,"name",{value:e,configurable:!0});var ve=/^[a-zA-Z0-9_\-.]{1,256}$/,Wt=/^[a-zA-Z0-9_]{1,255}$/,Hs=/^(\[.+\])?\s?(\(UNEXPECTED\)|\(unexpected\))?(.+)(\([EIWeiw]: [a-fA-F\d]{32}\))(\(UNEXPECTED\)|\(unexpected\))?$/,Ks=/^(\[.+\]).+$/,Xs=/^[0-9a-fA-F]{32}$/,qs=/^[0-9a-fA-F]{64}$/;var Or="/",Ws="_nonalphanumerics_";var Nr=!1,Ys=globalThis.crypto,{subtle:Cd}=Ys,Je={sha_256:"SHA-256",sha_512:"SHA-512"};function H(r){return JSON.parse(JSON.stringify(r))}f(H,"clone");function oe(r){return(r??new Date).toUTCString()}f(oe,"getTimestamp");async function Ke({s:r,algorithm:e="SHA-256"}){if(!r)return"";try{let t=Object.values(Je);if(!t.includes(e))throw new Error(`Only ${t} implemented (E: 73cb52cd4d7f70c3415fdf695ba6ba23)`);let o=new TextEncoder().encode(r),n=await Cd.digest(e,o);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}catch(t){throw console.error(E(t.message)),t}}f(Ke,"hash");async function U(r=64){let e="";if(r<32)throw new Error("Seed size must be at least 32");if(!globalThis.crypto)throw new Error("Cannot create UUID, as unknown crypto library version. If using node.js, v19+ is required. (E: c02cee3fd8a94f678d3f4ebe9dc49797)");let t=Ys.getRandomValues(new Uint8Array(16));if(e=await Ke({s:t.join("")}),!e)throw new Error("Did not create UUID...hmm...");return e}f(U,"getUUID");function K(r){return JSON.stringify(r,null,2)}f(K,"pretty");async function Oe(r){return new Promise(e=>{setTimeout(()=>{e()},r)})}f(Oe,"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 Xn({items:r,keyFn:e}){let t=`[${Xn.name}]`;try{let o={};for(let n=0;n<r.length;n++){let a=r[n],s=e(a);o[s]=[...o[s]??[],a]}return o}catch(o){throw console.error(`${t} ${o.message}`),o}}f(Xn,"groupBy");function yo({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(yo,"getRegExp");function nt(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(nt,"getTimestampInTicks");function qn({startDate:r,years:e,months:t,days:o,hours:n,seconds:a}){let s=`[${qn.name}]`;try{return hr({startDate:r,years:e,months:t,days:o,hours:n,seconds:a}).toUTCString()}catch(i){throw console.log(`${s} ${i.message}`),i}}f(qn,"getExpirationUTCString");function hr({startDate:r,years:e,months:t,days:o,hours:n,seconds:a}){let s=`[${hr.name}]`;try{if(!r&&!e&&!t&&!o&&!n&&!a)throw new Error("either startDate or a time interval required. (E: 30248f8b306f443ab036fa8c313c50d8)");r=r?new Date(r):new Date;let i,c;return e?(i=r.getFullYear()+e,c=r.setFullYear(i),hr({startDate:new Date(c),months:t,days:o,hours:n,seconds:a})):t?(i=r.getMonth()+t,c=r.setMonth(i),hr({startDate:new Date(c),years:e,days:o,hours:n,seconds:a})):o?(i=r.getDate()+o,c=r.setDate(i),hr({startDate:new Date(c),years:e,months:t,hours:n,seconds:a})):n?(i=r.getHours()+n,c=r.setHours(i),hr({startDate:new Date(c),years:e,months:t,days:o,seconds:a})):a?(i=r.getSeconds()+a,c=r.setSeconds(i),hr({startDate:new Date(c),years:e,months:t,days:o,hours:n})):r}catch(i){throw console.log(`${s} ${i.message}`),i}}f(hr,"addTimeToDate");function Wn({expirationTimestampUTC:r}){let e=`[${Wn.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(Wn,"isExpired");function $o(r){return Array.from(new Set(r))}f($o,"unique");function Yn({obj:r,value:e,path:t,pathDelimiter:o,logalot:n}){let a=`[${Yn.name}]`;try{if(n&&console.log(`${a} 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||Or;let s=r,i=t.split(o).filter(d=>!!d),c=i.pop();i.forEach(d=>{let l=s[d];if(l){if(typeof l!="object")throw new Error(`invalid path into object. Each step along the path must be typeof === 'object', but typeof targetObj["${d}"] === ${typeof l}. (value: ${l}) (E: 38cf29c5f624a40b4b56502c2ec39d22)`)}else s[d]={};s=s[d]}),s[c]=e}catch(s){throw console.error(`${a} ${s.message}`),s}finally{n&&console.log(`${a} complete.`)}}f(Yn,"patchObject");async function Yr({n:r}){let e=`[${Yr.name}]`;try{Nr&&console.log(`${e} starting...`);let t=[];for(let o=0;o<r;o++){let n=await U();t.push(n.substring(0,16))}return t}catch(t){throw console.error(`${e} ${t.message}`),t}finally{Nr&&console.log(`${e} complete.`)}}f(Yr,"getIdPool");function vd({text:r,length:e,keepLiterals:t=["-"],replaceMap:o}){let n=`[${vd.name}]`;try{if(Nr&&console.log(`${n} starting... (I: 27437e312e5aa621adfebb84e059c822)`),!r)throw new Error("text required (E: 87e0493613c8b30dfade83e1d2862a22)");let a=r,s={};t=t??[];for(let c=0;c<t.length;c++){let d=t[c],l;do l=zs({count:10});while(l.includes(d)||d.includes(l)||r.includes(l));if(a.includes(d))for(s[l]=d;a.includes(d);)a=a.replace(d,l)}if(o&&Object.keys(o).length>0)for(let c=0;c<Object.keys(o).length;c++){let d=Object.keys(o)[c],l=o[d];for(;a.includes(d);)a=a.replace(d,l)}a=a.replace(/\W/g,"");let i=Object.keys(s);for(let c=0;c<i.length;c++){let d=i[c];for(;a.includes(d);)a=a.replace(d,s[d])}return e&&e>0&&a.length>e&&(Nr&&console.log(`${n} curtailing length (I: d7a28e05daa5979c7686b4c1cf519b23)`),a=a.substring(0,e)),a.length===0&&(a=Ws),a}catch(a){throw console.error(`${n} ${a.message}`),a}finally{Nr&&console.log(`${n} complete.`)}}f(vd,"getSaferSubstring");function Od({x:r}){if((r??[]).length===0)return;let e=Math.floor(Math.random()*r.length);return r[e]}f(Od,"pickRandom");function zs({count:r}){let e=`${zs.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+=Od({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{Nr&&console.log(`${e} complete.`)}}f(zs,"pickRandom_Letters");function xr({dominant:r,recessive:e}){let t=`[${xr.name}]`;try{if(Array.isArray(r)&&Array.isArray(e)){let o=H(r),n=!1;return e.forEach(a=>{if(typeof a=="string")o.includes(a)||o.push(a);else{n||(console.warn(`${t} merging arrays of non-string elements. (W: d8ab113064834abc8eb5fe6c4cf87ba3)`),n=!0);let s=JSON.stringify(a);o.some(i=>JSON.stringify(i)===s)||o.push(a)}}),o}else if(typeof r=="object"&&typeof e=="object"){let o={...e},n=Object.keys(r),a=Object.keys(e);return n.forEach(s=>{a.includes(s)?Array.isArray(r[s])&&Array.isArray(e[s])?o[s]=xr({dominant:r[s],recessive:e[s]}):r[s]&&!Array.isArray(r[s])&&typeof r[s]=="object"&&e[s]&&!Array.isArray(e[s])&&typeof e[s]=="object"?o[s]=xr({dominant:r[s],recessive:e[s]}):o[s]=r[s]:o[s]=r[s]}),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(xr,"mergeMapsOrArrays_Naive");function y({ib:r,gib:e,ibGib:t,delimiter:o="^"}){return r=r||t?.ib||"",e=e||t?.gib||"",r+o+e}f(y,"getIbGibAddr");function ne({ibGib:r,ibGibAddr:e,delimiter:t="^"}){let o="[getIbAndGib]";if(!e)if(r)e=y({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(ne,"getIbAndGib");var Nd=globalThis.crypto,{subtle:Js}=Nd;function Yt(r,e=""){e||(e="");let t=f(async s=>{if(!s)return"";let i=new TextEncoder().encode(s),c=await Js.digest("SHA-256",i);return Array.from(new Uint8Array(c)).map(l=>l.toString(16).padStart(2,"0")).join("")},"hashToHex"),o=f(async(s,i)=>{let c;if(s){let b=new TextEncoder().encode(s);c=new Uint8Array(b.length+i.length),c.set(b),c.set(i,b.length)}else c=i;let d=await Js.digest("SHA-256",c);return Array.from(new Uint8Array(d)).map(b=>b.toString(16).padStart(2,"0")).join("")},"hashToHex_Uint8Array"),n=f(s=>{if(s===null||typeof s!="object")return s;if(Array.isArray(s))return s.map(d=>n(d));let i={},c=Object.keys(s).sort();for(let d of c){let l=s[d];l!==void 0&&(i[d]=n(l))}return i},"toNormalizedForHashing"),a;return e?a=f(async(s,i,c)=>{let d=Object.keys(c||{}).length>0&&Object.keys(c||{}).some(m=>c[m]&&c[m].length>0),l=!!i;l&&(typeof i=="string"?l=i.length>0:i instanceof Uint8Array?l=!0:typeof i=="object"?l=Object.keys(i||{}).length>0:l=!0);let b=(await t(e+s)).toUpperCase(),p=d?(await t(e+JSON.stringify(n(c)))).toUpperCase():"",h="";return l&&(i instanceof Uint8Array?h=(await o(e,i)).toUpperCase():h=(await t(e+JSON.stringify(n(i)))).toUpperCase()),d||l?(await t(e+b+p+h)).toUpperCase():(await t(e+b)).toUpperCase()},"hashFields"):a=f(async(s,i,c)=>{let d=Object.keys(c||{}).length>0&&Object.keys(c||{}).some(m=>c[m]&&c[m].length>0),l=!!i;l&&(typeof i=="string"?l=i.length>0:i instanceof Uint8Array?l=!0:typeof i=="object"?l=Object.keys(i||{}).length>0:l=!0);let b=(await t(s)).toUpperCase(),p=d?(await t(JSON.stringify(n(c)))).toUpperCase():"",h="";return l&&(i instanceof Uint8Array?h=(await o("",i)).toUpperCase():h=(await t(JSON.stringify(n(i)))).toUpperCase()),d||l?(await t(b+p+h)).toUpperCase():(await t(b)).toUpperCase()},"hashFields"),a(r.ib,r?.data,r?.rel8ns)}f(Yt,"sha256v1");var Ee;(function(r){r.past="past",r.ancestor="ancestor",r.dna="dna",r.identity="identity",r.tjp="tjp",r.secret="secret",r.encryption="encryption"})(Ee||(Ee={}));var Lr="ib",re="gib",q={ib:Lr,gib:re},Ne="^",St=".",Zs="ib^gib",ur=["past","ancestor","dna","tjp"],xd=155,Qs=new RegExp(`^[\\w\\t\\-|=+.&%$#@!~\` \\[\\]\\(\\)\\{\\}]{1,${xd}}$`);async function gr(r){let e=H(r),t=`[${gr.name}]`;e.srcAddr&&delete e.srcAddr,delete e.src;let o={ib:e.type,data:e,rel8ns:{ancestor:[`${e.type.toString()}${Ne}${re}`]}};return o.gib=await Yt(o),o}f(gr,"buildDna");function zn({ibGib:r}){let e=`[${zn.name}]`;try{if(!r)throw new Error("ibGib required.");let t=["fork","mut8","rel8","plan"].map(n=>`${n}^${re}`);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(zn,"isDna");function $e({ibGib:r,gib:e}){return r?$e({gib:r.gib}):e?e===re:!0}f($e,"isPrimitive");async function ue({ibGib:r,hasTjp:e,tjpAddr:t,gibDelimiter:o,isPrimitive:n,hashAlgorithm:a}){let s=`[${ue.name}]`;try{if(!r)throw new Error("ibGib required. (E: 17d073226b9d42fd841e5a94b065ef21)");if(n)return re;let i=await Yt(r,""),c=r.rel8ns??{},d=r.data??{};if(o=o||St,e||(e=(c.tjp??[]).length>0||d.isTjp||!1),e){let l;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(`${s} 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(d.isTjp)t=y({ib:r.ib,gib:i});else throw new Error("hasTjp is true, but both ibGib.rel8ns.tjp and ibGib.data.isTjp are falsy. (E: 4e246897e52044789594d853bb5b66ee)");if(l=t?ne({ibGibAddr:t}).gib:void 0,l)return d.isTjp?i:`${i}${St}${l}`;throw new Error("hasTjp is true but could not find tjpAddrGib. (E: 1863df626b754744a1d431a683cb0ba0)")}else return i}catch(i){throw console.error(`${s} ${E(i)}`),i}}f(ue,"getGib");function Pe({ibGibAddr:r,gib:e,gibDelimiter:t}){let o=`[${Pe.name}]`;try{if(!r&&!e)throw new Error("Either ibGibAddr or gib required. (E: 25e3dcbe63cd44909032df12af9df75e)");if(e=e||ne({ibGibAddr:r}).gib,e===re)return{isPrimitive:!0};if(t=t??St,e.includes(t)){let n=e.split(t);if(n.some(i=>i===""))throw new Error(`unexpected gib that contains gibDelimiter (${t}) but has at least one piece with empty string. (E: 75a94280045541009ee68182d12d3449)`);let a=n.length;return a>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:a,delimiter:t}}else return{punctiliarHash:e,piecesCount:1,delimiter:t}}catch(n){throw console.error(`${o} ${E(n)}`),n}}f(Pe,"getGibInfo");async function Io(r){let{noTimestamp:e,dna:t,linkedRel8ns:o,destIb:n,uuid:a,tjp:s,cloneRel8ns:i,cloneData:c,type:d="fork"}=r,l=r.src,b="[fork_v1]";if(d!=="fork")throw new Error(`${b} not a fork transform.`);if(r.type||(r.type="fork"),!l)throw new Error(`${b} src required to fork.`);if(!l.ib)throw new Error(`${b} src.ib required.`);if(n&&n.includes(Ne))throw new Error(`${b} destIb can't contain (hardcoded) delimiter right now.`);if(!l.gib)throw new Error(`${b} src.gib required.`);let p={ib:l.ib,gib:l.gib};l.data&&Object.keys(l.data).length>0&&(p.data=l.data),l.rel8ns&&Object.keys(l.rel8ns).length>0&&(p.rel8ns=l.rel8ns),l=p;let h=y({ib:l.ib,gib:l.gib});r.srcAddr=h;let g=i&&l.rel8ns&&Object.keys(l.rel8ns).length>0?H(l.rel8ns):{};delete g.past;let m=c&&l?.data?H(l.data):{};r.nCounter&&(m.n=0);let w=o?.includes(Ee.ancestor)?[h]:(g.ancestor||[]).concat([h]);g.ancestor=w,g.tjp&&delete g.tjp;let S=H(l);if(e&&s?.timestamp)throw new Error(`${b} both noTimestamp and tjp.timestamp selected.`);if(!e||s?.timestamp){let $=new Date;m.timestamp=oe($),m.timestampMs=$.getMilliseconds()}(s?.uuid||a)&&(m.uuid=await U()),s?.uuid||s?.timestamp?m.isTjp=!0:m.isTjp&&delete m.isTjp,S.ib=n||"ib",h!==Zs&&(S.rel8ns=g),Object.keys(m).length>0&&(S.data=m);let A=null;if(t){A=await gr(r);let $=y({ibGib:A});g.dna=o?.includes(Ee.dna)?g.dna=[$]:g.dna=(g.dna||[]).concat($)}S.gib=await Yt(S,"");let I={newIbGib:S};return A&&(I.dnas=[A]),I}f(Io,"fork");async function at(r){let{noTimestamp:e,dna:t,linkedRel8ns:o,dataToRename:n,dataToRemove:a,dataToAddOrPatch:s,mut8Ib:i,type:c="mut8"}=r,d=r.src,l="[mut8_v1]";if(c!=="mut8")throw new Error(`${l} not a mut8 transform.`);if(r.type||(r.type="mut8"),!d)throw new Error(`${l} src required to mut8.`);if(!d.ib)throw new Error(`${l} src.ib required.`);if(d.ib.includes(Ne))throw new Error(`${l} ib can't contain hardcoded delimiter (${Ne}) right now.`);if(!d.gib)throw new Error(`${l} src.gib required.`);if(!i&&!n&&!a&&!s)throw new Error(`${l} gotta provide either a mut8Ib or some data to change.`);let b=y({ib:d.ib,gib:d.gib});if(r.srcAddr&&b!==r.srcAddr)throw new Error(`${l} srcAddr from src does not equal opts.srcAddr`);if(r.srcAddr=b,$e({ibGib:d}))throw new Error(`${l} cannot mutate primitive ibgib`);let p={ib:d.ib,gib:d.gib};d.data&&Object.keys(d.data).length>0&&(p.data=d.data),d.rel8ns&&Object.keys(d.rel8ns).length>0&&(p.rel8ns=d.rel8ns),d=p;let h=H(d),g=d.rel8ns?d.rel8ns:{},m=H(g);m.past=o?.includes(Ee.past)?[b]:(m.past||[]).concat([b]);let w=d?.data?H(d.data):{};if(n&&(w=Jn(w,n,"rename")),a&&(w=Jn(w,a,"remove")),s&&(w=ei(w,s)),!e){let T=new Date;w.timestamp=oe(T),w.timestampMs=T.getMilliseconds()}if(r.nCounter||Object.keys(w).includes("n"))if(Object.keys(w).includes("n"))if(Number.isInteger(w.n))w.n>=0?w.n=w.n+1:(console.warn(`${l} data.n is less than 0, which is unexpected. Resetting data.n to 0.`),w.n=0);else throw new Error("cannot increment nCounter because data.n is not a number.");else w.n=0;if(w.isTjp){let T=m.tjp??[];T.push(b),m.tjp=T,delete w.isTjp}let A=null;if(t){A=await gr(r);let T=y({ibGib:A});m.dna=o?.includes(Ee.dna)?m.dna=[T]:m.dna=(m.dna||[]).concat(T)}h.ib=i||h.ib,h.rel8ns=m,Object.keys(w).length>0?h.data=w:delete h.data;let I=(m.tjp?.length??0)>0;h.gib=await ue({ibGib:h,hasTjp:I});let $={newIbGib:h};return A&&($.dnas=[A]),$}f(at,"mut8");function Jn(r,e,t){let o="[renameOrRemove]",n=["timestamp"];return Object.keys(e).forEach(a=>{if(n.includes(a))throw new Error(`${o} Cannot rename to ${a}.`);if(Object.keys(r).includes(a)){let s=e[a];if(typeof s=="string"){if(n.includes(s))throw new Error(`${o} Cannot rename to ${s}.`);t==="rename"&&(r[s]=r[a]),delete r[a]}else r[a]=Jn(r[a],s,t)}else console.log(`${o} key to ${t} does not exist`)}),r}f(Jn,"renameOrRemove");function ei(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]=ei(n,o):r[t]=o:r[t]=o}),r}f(ei,"patch");async function Xe(r){let{noTimestamp:e,dna:t,linkedRel8ns:o,rel8nsToAddByAddr:n,rel8nsToRemoveByAddr:a,type:s="rel8"}=r,i=r.src,c="[rel8_v1]";if(s!=="rel8")throw new Error(`${c} not a rel8 transform.`);if(r.type||(r.type="rel8"),s!=="rel8")throw new Error(`${c} not a rel8 transform.`);if(r.type||(r.type="rel8"),!i)throw new Error(`${c} src required.`);if(!i.ib)throw new Error(`${c} src.ib required.`);if(i.ib.includes(Ne))throw new Error(`${c} ib can't contain hardcoded delimiter (${Ne}) right now.`);if(!i.gib)throw new Error(`${c} src.gib required.`);if($e({ibGib:i}))throw new Error(`${c} cannot relate/unrelate primitive ibgib`);let d=n&&Object.keys(n).length>0,l=a&&Object.keys(a).length>0;if(!(d||l))throw new Error(`${c} gotta provide relations to either add or remove.`);let b=y({ib:i.ib,gib:i.gib});if(r.srcAddr&&b!==r.srcAddr)throw new Error(`${c} srcAddr from src does not equal opts.srcAddr`);r.srcAddr=b;let p=f($=>$&&typeof $=="string"&&$.length>=2&&$.includes("^")&&$.split("^")[0].length>=1,"fnValidIbGibAddr");Object.keys(n||{}).map($=>(n||{})[$]).forEach($=>{if(!($&&$.every(T=>p(T))))throw new Error(`${c} Invalid rel8n attempt. Must be valid ibGibs. Did you include a delimiter (^)?`)}),Object.keys(a||{}).map($=>(a||{})[$]).forEach($=>{if(!($&&$.every(T=>p(T))))throw new Error(`${c} Invalid remove rel8n attempt. Must be valid ibGibs. Did you include a delimiter (^)?`)});let h={ib:i.ib,gib:i.gib};i.data&&Object.keys(i.data).length>0&&(h.data=i.data),i.rel8ns&&Object.keys(i.rel8ns).length>0&&(h.rel8ns=i.rel8ns),i=h;let g=H(i),m=H(i.data||{});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(`${c} 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(!e){let $=new Date;m.timestamp=oe($),m.timestampMs=$.getMilliseconds()}let w=H(i.rel8ns||{});if(Object.keys(n||{}).forEach($=>{if(ur.includes($))throw new Error(`${c} Cannot manually add relationship: ${$}.`);let T=w[$]||[],G=n[$].filter(v=>!T.includes(v));w[$]=T.concat(G)}),Object.keys(a||{}).forEach($=>{if(ur.includes($))throw new Error(`${c} Cannot manually remove relationship: ${$}.`);let T=w[$]||[],_=a[$]||[],G=T.filter(v=>!_.includes(v));G.length>0?w[$]=G:delete w[$]}),w.past=(w.past||[]).concat([b]),(o||[]).filter($=>Object.keys(w).includes($)).filter($=>(w[$]||[]).length>1).forEach($=>{let T=w[$].length;w[$]=[w[$][T-1]]}),m.isTjp){let $=w.tjp||[];$.push(b),w.tjp=$,delete m.isTjp}g.data=m,g.rel8ns=w;let S=(w.tjp?.length??0)>0,A=null;if(t){A=await gr(r);let $=y({ibGib:A});w.dna=o?.includes(Ee.dna)?w.dna=[$]:w.dna=(w.dna||[]).concat($)}g.gib=await ue({ibGib:g,hasTjp:S});let I={newIbGib:g};return A&&(I.dnas=[A]),I}f(Xe,"rel8");function So({ibGib:r}){let e=`[${So.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(St)?!0:r.gib===re?!1:!!Pe({ibGibAddr:y({ibGib:r})}).tjpGib:(console.warn(`${e} ibGib.gib falsy. (W: 6400d780822b44d992846f1196509be3)`),!1)}f(So,"hasTjp");function _o({ibGib:r}){let e=`[${_o.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:H(r.data)),r.rel8ns&&(t.rel8ns=H(r.rel8ns)),t}f(_o,"toDto");var Zn=!1;async function ge({ibGib:r}){let e=`[${ge.name}]`;try{let t=[];if(r){let o=y({ibGib:r});if(t=Pr({addr:o})??[],t.length>0)return console.error(`${e} errors found in addr: ${o}`),t;if($e({gib:r.gib}))return null;let n=await ue({ibGib:_o({ibGib:r}),hasTjp:So({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 ue({ibGib:_o({ibGib:r}),hasTjp:So({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(ge,"validateIbGibIntrinsically");function Pr({addr:r,delimiter:e,version:t}){let o=`[${Pr.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||Ne,r.includes(e)||n.push(`No delimiter (${e}) found. (E: 05e28dcb70ff44019edc53ed508bd1e8)`),r.startsWith(e)&&n.push("addr starts with delim. (E: d29f808c5a47452f9bb3ea684694c6eb)");let{ib:a,gib:s}=ne({ibGibAddr:r,delimiter:e}),i=Rr({ib:a,ibGibAddrDelimiter:e,version:t});i&&(n=n.concat(i));let c=Dr({gib:s,ibGibAddrDelimiter:e,version:t});return c&&(n=n.concat(c)),n.length>0&&Zn&&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(Pr,"validateIbGibAddr");function Rr({ib:r,ibGibAddrDelimiter:e,version:t}){let o=`[${Rr.name}]`;try{let n=[];return t&&console.warn(`${o} version not implemented yet. Ignoring. (W: 71228ba4ed994aaa8149910e295ab087)`),r?r===Lr?null:(e=e||Ne,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(Rr,"validateIb");function Dr({gib:r,gibDelimiter:e,ibGibAddrDelimiter:t,version:o}){let n=`[${Dr.name}]`;try{let a=[];if(o&&console.warn(`${n} version not implemented yet. Ignoring. (E: 90ced1db69774702b92acb261bdaee23)`),!r)return a.push("gib required. (E: e217de4035b04086827199f4bace189c)"),a;t=t||Ne;let s=[t],i=[];s.forEach(h=>{r.includes(h)&&i.push(h)}),i.length>0&&a.push(`gib (${r}}) contains invalid characters: (${JSON.stringify(i.join(","))}) (E: 1e584258d9e049ba9ce7e516f3ab97f1)`);let{punctiliarHash:c,tjpGib:d,isPrimitive:l}=Pe({gib:r,gibDelimiter:e||St});if(l)return null;if(!c)throw new Error(`${n} punctiliarHash is falsy on a non-primitive gib. (E: 72835394918241bdb2632bf0510bdae5)`);let b=c.match(Xs),p=c.match(qs);if(!b&&!p&&a.push("gib punctiliar hash is neither a 32- or 64-char hash string. (E: d47ff6d6e14b4c02a62107090c8dad39)"),d){let h=Dr({gib:d});(h??[]).length>0&&a.push(`tjpGib has errors (E: d6b79228d4a64c0b967cdb0efcea4d0d). tjpGibValidationErrors: ${h.join(". ")}`)}return a.length>0?a:null}catch(a){throw console.error(`${n} ${E(a)}`),a}}f(Dr,"validateGib");function Qn({rel8ns:r}){let e=`[${Qn.name}]`;try{Zn&&console.log(`${e} starting... (I: 62b4722599798dd8ab95fcebf42c0e23)`);let t=[],o=Object.keys(r);for(let n=0;n<o.length;n++){let a=Object.keys(r)[n];typeof a!="string"&&t.push("non-string rel8nName found. all keys of rel8ns must be of type string. (E: 3b2e4582b638421681951f5475c85178)");let s=r[a]??[];for(let i=0;i<s.length;i++){let c=s[i],d=Pr({addr:c})??[];d.length>0&&t.push(`invalid addr found for rel8nName (${a}). addr errors: ${d.join("|")} (E: 56809a746c4f462db426e90395b80364)`)}}return t.length>0?t:null}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Zn&&console.log(`${e} complete.`)}}f(Qn,"validateRel8nsIntrinsically");var ti=!1,F=class r{static{f(this,"Factory_V1")}static root(){return r.primitive({ib:Lr})}static primitive({ib:e}){return{ib:e,gib:re}}static primitives({ibs:e}){return e.map(t=>r.primitive({ib:t}))}static async firstGen({ib:e=Lr,parentIbGib:t=r.root(),data:o,rel8ns:n,dna:a,tjp:s,linkedRel8ns:i,noTimestamp:c,nCounter:d,squash:l}){let b=`[${r.name}][${r.firstGen.name}]`;try{if(ti&&console.log(`${b} starting... (I: b7152fbd94382516d9f7c591bcf4c326)`),a&&l)throw new Error("both dna and squash cannot be true. Squash requires that no dna exist. (E: abfc58b4a4c8654924aa5428d0831826)");let p=[],h=t||q,g=await Io({src:h,destIb:e,tjp:s,dna:a,linkedRel8ns:i,noTimestamp:c,nCounter:d});if(p.push(g),h=g.newIbGib,o){let m=await at({src:h,dataToAddOrPatch:o,dna:a,linkedRel8ns:i,noTimestamp:c,nCounter:d});p.push(m),h=m.newIbGib}if(n){let m=await Xe({src:h,rel8nsToAddByAddr:n,dna:a,linkedRel8ns:i,noTimestamp:c,nCounter:d});p.push(m)}if(p.length>1){let m=p.slice(p.length-1)[0].newIbGib,w={newIbGib:m,intermediateIbGibs:p.slice(0,p.length-1).map(S=>S.newIbGib)};if(a){l&&`${b}`;let S=[];return p.forEach(A=>{S=S.concat(A.dnas)}),w.dnas=S,w}else if(l){if(!m.rel8ns)throw new Error("(UNEXPECTED) newIbGib.rel8ns is falsy? (E: 6b09e8057fc5b00c6cfd13be60e97f26)");return delete m.rel8ns.past,m.rel8ns.tjp&&(delete m.rel8ns.tjp,m.data??={},m.data.isTjp=!0),d&&(m.data??={},m.data.n=0),m.gib=await ue({ibGib:m}),{newIbGib:m}}else return w}else{if(p.length===1)return p[0];throw new Error("(UNEXPECTED) interimResults.length is not 1 and not greater than 1? 0? But we had to fork? (E: a256c88c56916a46a888796f76ef4826)")}}catch(p){throw console.error(`${b} ${E(p)}`),p}finally{ti&&console.log(`${b} complete.`)}}static async stone({parentPrimitiveIb:e,ib:t,ibRegExpPattern:o,data:n,rel8ns:a,noTimestamp:s,uuid:i}){let c=`[${r.name}][${r.stone.name}]`;try{if(!e)throw new Error("parentPrimitiveIb required. (E: genuuid)");if(Rr({ib:e})!==null)throw new Error(`Invalid parentPrimitiveIb: ${e}. (E: genuuid)`);if(!t)throw new Error("ib required. (E: genuuid)");let d=o?new RegExp(o):Qs;if(!t.match(d))throw new Error(`invalid ib. does not match regexp (${d}) (E: genuuid)`);let l=Object.keys(a??{}),b=[...ur,"tjp"];if(l.some(m=>b.includes(m)))throw new Error(`Invalid rel8ns. forbiddenRel8nNames: ${b}. rel8ns keys: ${Object.keys(a??{})}. (E: genuuid)`);let g=(await r.firstGen({ib:t,parentIbGib:r.primitive({ib:e}),data:n,rel8ns:a,dna:!1,noTimestamp:s,nCounter:!1})).newIbGib;return i&&(g.data||(g.data={}),g.data.uuid=await U()),g.rel8ns?.past&&delete g.rel8ns.past,g.rel8ns?.tjp&&delete g.rel8ns.tjp,g.gib=await ue({ibGib:{ib:g.ib,data:g.data,rel8ns:g.rel8ns},hasTjp:!1}),g}catch(d){throw console.error(`${c} ${d.message}`),d}}static async constant({parentPrimitiveIb:e,ib:t,ibRegExpPattern:o,data:n,rel8ns:a}){let s=`[${r.name}][${r.constant.name}]`;try{return await r.stone({parentPrimitiveIb:e,ib:t,ibRegExpPattern:o,data:n,rel8ns:a,noTimestamp:!0,uuid:!1})}catch(i){throw console.error(`${s} ${i.message}`),i}}};var Kp="[core^gib timer]";var ea=`.'",!?-`;var ri=new RegExp("^[\\w\\t\\-|=+.&%$#@!~` \\[\\]\\(\\)\\{\\}]{1,155}$");var Xp=/^[a-zA-Z0-9_\-.]{1,255}$/,qp=/^[a-zA-Z0-9_\-.\s👀🤖:;&]{1,64}$/;var Ao={tags:"tags",aliases:"aliases",roots:"roots",outerspaces:"outerspaces",secrets:"secrets",encryptions:"encryptions",autosyncs:"autosyncs",robbots:"robbots",apps:"apps",history:"history"};var Ld="robbot";var oi="zero",ni="zerospace";var lh=!1,dh="This is a local space. There are many like it, but this one is mine.";var fh=/^[a-zA-Z][\w\-]{0,62}[a-zA-Z]$/,Dd="syncSpace";var bh=3e4;var To="space";var ai="space_lock",si=100,ii=100,ph=60*2,ta=30;var ra="root",oa="x",ci="root",na="analytics-outline",aa='This is a root ibgib, which is basically like a root folder that is primarily responsible for "containing" other ibgibs.';var sa="tag",Pd="target";var li="pricetag-outline",di="This is a tag used for organizing data.";var $h="always",fi="archive",bi="trash";var ia=/^\w{1,32}$/,Go="Invalid Date";var ca={ib:"true",gib:re};var pi={ib:"false",gib:re};var hi="config_key";var zr=/^[a-zA-Z0-9_\-.]{1,32}$/,Co="app";var mr=`bootstrap^${re}`,_t="defaultSpaceId",ui="spaceIds";var At={prependPerHash:"prependPerHash",appendPerHash:"appendPerHash",initialPrepend:"initialPrepend",initialAppend:"initialAppend"},zt=Object.values(At),st={sha_256:"SHA-256",sha_512:"SHA-512"},Ch=Object.values(st),Rd={indexOf:"indexOf",lastIndexOf:"lastIndexOf"},kt=Object.values(Rd);function Jr(r){let e=`[${Jr.name}]`;return new Promise((t,o)=>{try{let n=gi(r),a=mi(n);t(a)}catch(n){console.error(`${e} ${E(n)}`),o(n)}})}f(Jr,"encodeStringToHexString");function gi(r){let e=`[${gi.name}]`;try{return new TextEncoder().encode(r)}catch(t){throw console.error(`${e} ${E(t)}`),t}}f(gi,"stringToUTF8Bytes");function mi(r){let e=`[${mi.name}]`;try{return Array.from(r,t=>t.toString(16).padStart(2,"0")).join("")}catch(t){throw console.error(`${e} ${E(t)}`),t}}f(mi,"bytesToHexString");function Bt(r){let e=`[${Bt.name}]`;return new Promise((t,o)=>{try{let n=Ei(r),a=wi(n);t(a)}catch(n){console.error(`${e} ${E(n)}`),o(n)}})}f(Bt,"decodeHexStringToString");function Ei(r){let e=`[${Ei.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(Ei,"hexStringToBytes");function wi(r){let e=`[${wi.name}]`;try{return new TextDecoder().decode(r)}catch(t){throw console.error(`${e} ${E(t)}`),t}}f(wi,"utf8BytesToString");var Ut=At.appendPerHash,Mt="SHA-512",Ft=1024,Tt=2e4,jt=1,yi="indexOf",vo="lastIndexOf",Oo=5e6,No=4,Jt=",";function kd({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 At.prependPerHash:return t+(e||r);case At.appendPerHash:return(e||r)+t;case At.initialPrepend:return e||t+r;case At.initialAppend:return e||r+t;default:throw new Error(`Unknown saltStrategy: ${o} (E: 235136af1a6c40eb9c17b2ca41c08a01)`)}}f(kd,"getPreHash");async function dt({secret:r,prevHash:e,count:t,salt:o,saltStrategy:n,hashAlgorithm:a}){let s=`[${dt.name}]`;try{let i=e||void 0;for(let c=0;c<t;c++){let d=kd({secret:r,prevHash:i,salt:o,saltStrategy:n});i=await Ke({s:d,algorithm:a})}if(!i)throw new Error("hash was not created (E: 09dfdfd644734727a34a1bc0bd8e93b9)");return i}catch(i){throw console.error(`${s} ${E(i)}`),i}}f(dt,"execRound_getNextHash");async function Vt({secret:r,initialRecursions:e,salt:t,saltStrategy:o,hashAlgorithm:n}){let a=`[${Vt.name}]`;try{return await dt({secret:r,count:e,salt:t,saltStrategy:o,hashAlgorithm:n})}catch(s){throw console.error(`${a} ${E(s)}`),s}}f(Vt,"doInitialRecursions_keystretch");async function la({hexEncodedData:r,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,secret:a,hashAlgorithm:s,encryptedDataDelimiter:i,indexingMode:c}){let d=`[${la.name}]`;try{let l=await Vt({secret:a,initialRecursions:e,salt:o,saltStrategy:n,hashAlgorithm:s}),b=c==="indexOf"?(g,m)=>g.indexOf(m):(g,m)=>g.lastIndexOf(m),p=[];for(let g=0;g<r.length;g++){let m=r[g],w="",S;for(;!w.includes(m);)S=await dt({count:t,prevHash:l,salt:o,saltStrategy:n,hashAlgorithm:s}),w+=S,l=S;let A=b(w,m);p.push(A)}return p.join(i)}catch(l){throw console.error(`${d} ${E(l)}`),l}}f(la,"encryptFromHex_stream");async function da({encryptedData:r,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,secret:a,hashAlgorithm:s,encryptedDataDelimiter:i}){let c=`[${da.name}]`;try{let d=await Vt({secret:a,initialRecursions:e,salt:o,saltStrategy:n,hashAlgorithm:s}),l=r.split(i).map(h=>parseInt(h)),b=[];for(let h=0;h<l.length;h++){let g=l[h],m="",w;for(;g>=m.length;)w=await dt({count:t,prevHash:d,salt:o,saltStrategy:n,hashAlgorithm:s}),m+=w,d=w;let S=m[g];b.push(S)}return b.join("")}catch(d){throw console.error(`${c} ${E(d)}`),d}}f(da,"decryptToHex_stream");async function Zr({encryptedData:r,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,secret:a,hashAlgorithm:s,encryptedDataDelimiter:i}){let c=`[${Zr.name}]`,d=[],l=[];e=e||Tt,t=t||jt,n=n||Ut,s=s||Mt,o=o||await U(Ft),i=i||Jt;let b="[validation]";if(!e||e<1){let g=`${b} initialRecursions required, and greater than 0`;console.error(g),d.push(g)}if(!t||t<1){let g=`${b} recursionsPerHash required, and greater than 0`;console.error(g),d.push(g)}if(!r){let g=`${b} encryptedData required`;console.error(g),d.push(g)}if(!o){let g=`${b} salt required`;console.error(g),d.push(g)}if(!n){let g=`${b} saltStrategy required`;console.error(g),d.push(g)}if(!a){let g=`${b} secret required`;console.error(g),d.push(g)}if(!i){let g=`${b} encryptedDataDelimiter required`;console.error(g),d.push(g)}if(!Object.values(st).includes(s)){let g=`${b} only ${Object.values(st)} hash algorithms implemented`;console.error(g),d.push(g)}if(n&&!zt.includes(n)){let g=`${b} unknown saltStrategy: ${n}`;console.error(g),d.push(g)}if(d.length>0)return{errors:d,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,hashAlgorithm:s,encryptedDataDelimiter:i};let p=await da({encryptedData:r,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,secret:a,hashAlgorithm:s,encryptedDataDelimiter:i});return{decryptedData:await Bt(p),initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,hashAlgorithm:s,encryptedDataDelimiter:i,warnings:l.length>0?l:void 0}}f(Zr,"decryptImpl_stream");async function fa({dataToEncrypt:r,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,secret:a,hashAlgorithm:s,encryptedDataDelimiter:i,confirm:c,indexingMode:d}){let l=`[${fa.name}]`,b=[],p=[];e||(console.warn(`${l} initial recursions required. defaulting to ${Tt}`),e=Tt),t=t||jt,n=n||Ut,s=s||Mt,o=o||await U(Ft),i=i||Jt,d=d||yi;let h="[validation]";if(!e||e<1){let w=`${h} initialRecursions required, and greater than 0`;console.error(w),b.push(w)}if(!t||t<1){let w=`${h} recursionsPerHash required, and greater than 0`;console.error(w),b.push(w)}if(!r){let w=`${h} dataToEncrypt required`;console.error(w),b.push(w)}if(!o){let w=`${h} salt required`;console.error(w),b.push(w)}if(!n){let w=`${h} saltStrategy required`;console.error(w),b.push(w)}if(!a){let w=`${h} secret required`;console.error(w),b.push(w)}if(!i){let w=`${h} encryptedDataDelimiter required`;console.error(w),b.push(w)}if(!kt.includes(d)){let w=`${h} invalid indexingMode (${d}). Must be one of ${kt} (E: 5955c46755434982982823c97adcf076)`;console.error(w),b.push(w)}if(!Object.values(st).includes(s)){let w=`${h} only ${Object.values(st)} hash algorithms implemented`;console.error(w),b.push(w)}if(n&&!zt.includes(n)){let w=`${h} unknown saltStrategy: ${n}`;console.error(w),b.push(w)}if(b.length>0)return{errors:b,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,hashAlgorithm:s,encryptedDataDelimiter:i};let g=await Jr(r);if(c&&await Bt(g)!==r)throw new Error("decoding encoded hex failed for this data: The encoded hex did not reverse to the original data.");let m=await la({hexEncodedData:g,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,secret:a,hashAlgorithm:s,encryptedDataDelimiter:i,indexingMode:"indexOf"});if(c){let w=await Zr({encryptedData:m,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,secret:a,hashAlgorithm:s,encryptedDataDelimiter:i});if((w.errors||[]).length>0)return{errors:["Confirm check found that decrypt had errors.",...w.errors],initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,hashAlgorithm:s,encryptedDataDelimiter:i};if(w.decryptedData){if(w.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");(w.warnings||[]).length>0&&(p=p.concat(["Confirm check call to decrypt had warnings.",...w.warnings]))}return{encryptedData:m,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,hashAlgorithm:s,encryptedDataDelimiter:i,warnings:p.length>0?p:void 0}}f(fa,"encryptImpl_stream");async function ba({hexEncodedData:r,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,secret:a,hashAlgorithm:s,encryptedDataDelimiter:i,indexingMode:c,maxBlockSize:d,numOfPasses:l}){let b=`[${ba.name}]`;try{let p=await Vt({secret:a,initialRecursions:e,salt:o,saltStrategy:n,hashAlgorithm:s}),h=c==="indexOf"?(T,_)=>T.indexOf(_):(T,_)=>T.lastIndexOf(_),g=[],m=r.length,w=d;w>m&&(w=m);let S=Math.ceil(m/w),A=m%w||w,I=0;for(let T=0;T<S;T++){T===S-1&&(w=A);let G=await $i({blockSize:w,indexHexEncodedDataAtStartOfPass:I,numOfPasses:l,hexEncodedData:r,recursionsPerHash:t,salt:o,saltStrategy:n,prevHash:p,hashAlgorithm:s}),v=G.alphabetsThisBlock;p=G.prevHash;let N=await Ii({alphabetsThisBlock:v,blockSize:w,indexHexEncodedDataAtStartOfPass:I,hexEncodedData:r,getIndexOfCharInAlphabet:h});g=g.concat(N),I+=w}return g.join(i)}catch(p){throw console.error(`${b} ${E(p)}`),p}}f(ba,"encryptFromHex_blockMode");async function $i({blockSize:r,numOfPasses:e,indexHexEncodedDataAtStartOfPass:t,hexEncodedData:o,recursionsPerHash:n,salt:a,saltStrategy:s,prevHash:i,hashAlgorithm:c}){let d=`[${$i.name}]`;try{let l=[],b,p;for(let h=0;h<e;h++)for(let g=0;g<r;g++){b=t+g;let m=l[g]??"";p=await dt({count:n,prevHash:i,salt:a,saltStrategy:s,hashAlgorithm:c}),m+=p,i=p,l[g]=m}for(let h=0;h<r;h++){b=t+h;let g=o[b],m=l[h];for(;!m.includes(g);)p=await dt({count:n,prevHash:i,salt:a,saltStrategy:s,hashAlgorithm:c}),m+=p,i=p;l[h]=m}return{alphabetsThisBlock:l,prevHash:i}}catch(l){throw console.error(`${d} error: ${E(l)}`),l}}f($i,"getAlphabetsThisBlock");async function Ii({alphabetsThisBlock:r,blockSize:e,indexHexEncodedDataAtStartOfPass:t,hexEncodedData:o,getIndexOfCharInAlphabet:n}){let a=`[${Ii.name}]`;try{let s=[];for(let i=0;i<e;i++){let c=t+i,d=r[i],l=n(d,o[c]);s.push(l)}return s}catch(s){throw console.error(`${a} ${E(s)}`),s}}f(Ii,"getEncryptedIndexesThisBlock");async function pa({encryptedData:r,initialRecursions:e,recursionsPerHash:t,salt:o,saltStrategy:n,secret:a,hashAlgorithm:s,encryptedDataDelimiter:i,maxBlockSize:c,numOfPasses:d}){let l=`[${pa.name}]`;try{let b=await Vt({secret:a,initialRecursions:e,salt:o,saltStrategy:n,hashAlgorithm:s}),p=r.split(i).map($=>parseInt($)),h=[],g=p.length,m=c;m>g&&(m=g);let w=Math.ceil(g/m),S=g%m||m,A=0;for(let $=0;$<w;$++){$===w-1&&(m=S);let _=await Si({blockSize:m,indexEncryptedDataIndexesAtStartOfPass:A,numOfPasses:d,encryptedDataIndexes:p,recursionsPerHash:t,salt:o,saltStrategy:n,prevHash:b,hashAlgorithm:s}),G=_.alphabetsThisBlock;b=_.prevHash;let v=await _i({alphabetsThisBlock:G,blockSize:m,indexEncryptedDataIndexesAtStartOfPass:A,encryptedDataIndexes:p});h=h.concat(v),A+=m}return h.join("")}catch(b){throw console.error(`${l} ${E(b)}`),b}}f(pa,"decryptToHex_blockMode");async function Si({blockSize:r,numOfPasses:e,indexEncryptedDataIndexesAtStartOfPass:t,encryptedDataIndexes:o,recursionsPerHash:n,salt:a,saltStrategy:s,prevHash:i,hashAlgorithm:c}){let d=`[${Si.name}]`;try{let l=[],b,p;for(let h=0;h<e;h++)for(let g=0;g<r;g++){b=t+g;let m=l[g]??"";p=await dt({count:n,prevHash:i,salt:a,saltStrategy:s,hashAlgorithm:c}),m+=p,i=p,l[g]=m}for(let h=0;h<r;h++){b=t+h;let g=o[b],m=l[h];for(;m.at(g)===void 0;)p=await dt({count:n,prevHash:i,salt:a,saltStrategy:s,hashAlgorithm:c}),m+=p,i=p;l[h]=m}return{alphabetsThisBlock:l,prevHash:i}}catch(l){throw console.error(`${d} error: ${E(l)}`),l}}f(Si,"getAlphabetsThisBlock");async function _i({alphabetsThisBlock:r,blockSize:e,indexEncryptedDataIndexesAtStartOfPass:t,encryptedDataIndexes:o}){let n=`[${_i.name}]`;try{let a=[];for(let s=0;s<e;s++){let i=t+s,c=o[i],l=r[s][c];a.push(l)}return a}catch(a){throw console.error(`${n} ${E(a)}`),a}}f(_i,"getDecryptedDataArrayThisBlock");async function Qr(r){let e=`[${Qr.name}]`,{encryptedData:t,initialRecursions:o,recursionsPerHash:n,salt:a,saltStrategy:s,secret:i,hashAlgorithm:c,encryptedDataDelimiter:d,indexingMode:l,blockMode:b,multipass:p}=r,h=[],g=[];if(b&&p)throw new Error("blockMode and multipass set. blockMode was a refactored name of multipass, so these should not both be present. multipass is deprecated. (E: b9b3cd1f701c700835c0419260278223)");if(!b&&p&&(console.warn(`${e}[WARNING] "multipass" option is deprecated. this has been refactored to "blockMode". This will use multipass as blockMode. (W: b77c9773e30549cbb389ce61f31eb6d3)`),b=p),!b)throw new Error("(UNEXPECTED) blockMode required. This should be truthy in order to get to this impl fn. (E: 306bce36afd64b7182ca2b46ac04a261)");o=o||Tt,n=n||jt,s=s||Ut,c=c||Mt,a=a||await U(Ft),d=d||Jt,l=l||vo;let{maxBlockSize:m,maxPassSectionLength:w,numOfPasses:S}=b;!m&&w&&(console.warn(`${e}[WARNING] "maxPassSectionLength" option is deprecated. this has been refactored to "maxBlockSize". This will use maxPassSectioLength as maxBlockSize. (W: e2c83d78a3464704a6067e0f767f20b0)`),m=w),m=m||Oo,S=S||No;let A="[validation]";if(!o||o<1){let _=`${A} initialRecursions required, and greater than 0`;console.error(_),h.push(_)}if(!n||n<1){let _=`${A} recursionsPerHash required, and greater than 0`;console.error(_),h.push(_)}if(!t){let _=`${A} encryptedData required`;console.error(_),h.push(_)}if(!a){let _=`${A} salt required`;console.error(_),h.push(_)}if(!s){let _=`${A} saltStrategy required`;console.error(_),h.push(_)}if(!i){let _=`${A} secret required`;console.error(_),h.push(_)}if(!d){let _=`${A} encryptedDataDelimiter required`;console.error(_),h.push(_)}if(!l){let _=`${A} indexingMode required (E: a6fe15f8ba414e21b5355d23e808b976)`;console.error(_),h.push(_)}if(!kt.includes(l)){let _=`${A} invalid indexingMode (${l}). Must be one of ${kt} (E: 17435268651444e0b7a594135635fc58)`;console.error(_),h.push(_)}if(m<1){let _=`${A} maxBlockSize must be greater than 0 (E: 0870831aa86b4bfa939aeee9f252326a)`;console.error(_),h.push(_)}if(S<1){let _=`${A} numOfPasses must be greater than 0 (E: 691d3c3765584c6f8c9aba1ee378df00)`;console.error(_),h.push(_)}if(!Object.values(st).includes(c)){let _=`${A} only ${Object.values(st)} hash algorithms implemented`;console.error(_),h.push(_)}if(s&&!zt.includes(s)){let _=`${A} unknown saltStrategy: ${s}`;console.error(_),h.push(_)}if(h.length>0){let _={...r,errors:h};return delete _.encryptedData,delete _.secret,_}let I=await pa({encryptedData:t,initialRecursions:o,recursionsPerHash:n,salt:a,saltStrategy:s,secret:i,hashAlgorithm:c,encryptedDataDelimiter:d,maxBlockSize:m,numOfPasses:S}),$=await Bt(I),T={...r,decryptedData:$,warnings:g.length>0?g:void 0};return delete T.encryptedData,delete T.secret,T}f(Qr,"decryptImpl_blockMode");async function ha(r){let e=`[${ha.name}]`,{dataToEncrypt:t,initialRecursions:o,recursionsPerHash:n,salt:a,saltStrategy:s,secret:i,hashAlgorithm:c,encryptedDataDelimiter:d,confirm:l,indexingMode:b,blockMode:p,multipass:h}=r,g=[],m=[];if(p&&h)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(!p&&h&&(console.warn(`${e}[WARNING] "multipass" option is deprecated. this has been refactored to "blockMode". This will use multipass as blockMode. (W: 046b55a6d1304155b2e5352a9e6140b0)`),p=h),!p)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 ${Tt}`),o=Tt),d=d||Jt,b=b||vo;let{maxBlockSize:w,maxPassSectionLength:S,numOfPasses:A}=p;!w&&S&&(console.warn(`${e}[WARNING] "maxPassSectionLength" option is deprecated. this has been refactored to "maxBlockSize". This will use maxPassSectioLength as maxBlockSize. (W: c28fe476105643e184d0ddd5d2aa8a5d)`),w=S),w=w||Oo,A=A||No;let I="[validation]";if(!o||o<1){let G=`${I} initialRecursions required, and greater than 0 (E: dd96a75f0c504f34b1f9f2f32e011c50)`;console.error(G),g.push(G)}if(!n||n<1){let G=`${I} recursionsPerHash required, and greater than 0 (E: 64cf53e0bf9f4963be6b165ca4e6566d)`;console.error(G),g.push(G)}if(!a){let G=`${I} salt required (E: 136a5d237e0f4b1d89f8c87ac12a1507)`;console.error(G),g.push(G)}if(!s){let G=`${I} saltStrategy required (E: 457ed117bf224b9f86fe81ab6bc35381)`;console.error(G),g.push(G)}if(!i){let G=`${I} secret required (E: 5c363255055a45cfb07656e2f4854ed7)`;console.error(G),g.push(G)}if(!d){let G=`${I} encryptedDataDelimiter required (E: 1bbeb4dce19e4ac2bbe7d1e373739298)`;console.error(G),g.push(G)}if(!b){let G=`${I} indexingMode required (E: 693ebd2be64a438aa3b075d0cb0d92bf)`;console.error(G),g.push(G)}if(!kt.includes(b)){let G=`${I} invalid indexingMode (${b}). Must be one of ${kt} (E: 17435268651444e0b7a594135635fc58)`;console.error(G),g.push(G)}if(w<1){let G=`${I} maxBlockSize must be greater than 0 (E: 9f268207ae274b958fb91855331be259)`;console.error(G),g.push(G)}if(A<1){let G=`${I} numOfPasses must be greater than 0 (E: c3bcab79bb024d65b84947806290a7d4)`;console.error(G),g.push(G)}if(!Object.values(st).includes(c)){let G=`${I} only ${Object.values(st)} hash algorithms implemented`;console.error(G),g.push(G)}if(s&&!zt.includes(s)){let G=`${I} unknown saltStrategy: ${s}`;console.error(G),g.push(G)}if(g.length>0){let G={...r,errors:g};return delete G.dataToEncrypt,delete G.secret,G}let $=await Jr(t);if(l&&await Bt($)!==t)throw new Error("decoding encoded hex failed for this data: The encoded hex did not reverse to the original data.");let T=await ba({hexEncodedData:$,initialRecursions:o,recursionsPerHash:n,salt:a,saltStrategy:s,secret:i,hashAlgorithm:c,encryptedDataDelimiter:d,indexingMode:b,maxBlockSize:w,numOfPasses:A});if(l)try{let G=await Qr({encryptedData:T,initialRecursions:o,recursionsPerHash:n,salt:a,saltStrategy:s,secret:i,hashAlgorithm:c,encryptedDataDelimiter:d,indexingMode:b,blockMode:p});if(G.decryptedData){if(G.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)");(G.warnings||[]).length>0&&(m=m.concat(["Confirm check call to decrypt had warnings.",...G.warnings]))}catch(G){throw new Error(`${e} confirm failed. decrypt error: ${E(G)} (E: 782a84d9dc294ce9a6a325e3ab293adf)`)}let _={...r,encryptedData:T,warnings:m.length>0?m:void 0};return delete _.dataToEncrypt,delete _.secret,_}f(ha,"encryptImpl_blockMode");async function Bd(r){let e=`[${Bd.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 U(Ft),r.saltStrategy=r.saltStrategy||Ut,r.hashAlgorithm=r.hashAlgorithm||Mt,r.recursionsPerHash=r.recursionsPerHash||jt;let t;return r.blockMode?t=await ha(r):t=await fa(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(Bd,"encrypt");async function Ud(r){let e=`[${Ud.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 U(Ft),r.saltStrategy=r.saltStrategy||Ut,r.hashAlgorithm=r.hashAlgorithm||Mt,r.recursionsPerHash=r.recursionsPerHash||jt;let t;return r.blockMode||r.multipass?t=await Qr(r):t=await Zr(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(Ud,"decrypt");var Uu=5e4;var Mu=At.appendPerHash,Fu=10,ju="SHA-256";var Vu="encryption",Hu="ciphertext";var Md={local:"local",outerspace:"outerspace",innerspace:"innerspace"},Wu=Object.values(Md).concat(),Fd={user:"user",sync:"sync"},ua=Object.values(Fd).concat(),jd={node_filesystem:"node-filesystem"},Vd={aws_dynamodb:"aws-dynamodb"},Hd={...jd,...Vd},ga=Object.values(Hd).concat(),Kd={get:"get",put:"put",delete:"delete"},Xd={can:"can",addrs:"addrs",latest:"latest",watch:"watch",unwatch:"unwatch",tjps:"tjps",dependencyGraph:"dependency-graph"};var qd=!1,Lo=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 s=0;s<32;s++){let i=Math.floor(Math.random()*n);t.push(o[i])}let a=t.join("");return qd&&console.log(`${e} id: ${a} (I: c6591ffee6d5bbea79ed19cfa6630422)`),a}}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:yo({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:yo({min:0,max:155,chars:ea}),regexpErrorMsg:`0 to 155 alphanumerics or any of ${ea}`,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:yo({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:ve,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 Zt=class r extends Lo{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:a=!0,version:s=!0}){return t&&this.allowPrimitiveArgs({of:e.allowPrimitiveArgs}),o&&this.catchAllErrors({of:e.catchAllErrors}),n&&this.persistOptsAndResultIbGibs({of:e.persistOptsAndResultIbGibs}),a&&this.trace({of:e.trace}),s&&this.version({of:e.version}),this}};var Do=!1;function Ai({appData:r}){let e=`[${Ai.name}]`;try{if(Do&&console.log(`${e} starting...`),!r)throw new Error("appData required (E: 3df782b29bc4406a87e4895cfcea28ed)");let t=[],{name:o,uuid:n,classname:a}=r;return o?o.match(zr)||t.push(`name must match regexp: ${zr}`):t.push("name required."),n?n.match(ve)||t.push(`uuid must match regexp: ${ve}`):t.push("uuid required."),a&&(a.match(zr)||t.push(`classname must match regexp: ${zr}`)),t}catch(t){throw console.error(`${e} ${t.message}`),t}finally{Do&&console.log(`${e} complete.`)}}f(Ai,"validateCommonAppData");function ma({appData:r,classname:e}){let t=`[${ma.name}]`;try{let o=Ai({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:a}=r;return`app ${e} ${n} ${a}`}catch(o){throw console.error(`${t} ${o.message}`),o}}f(ma,"getAppIb");function Wd({appIb:r}){let e=`[${Wd.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(Wd,"getInfoFromAppIb");async function Yd({fnPromptApp:r,ibgibs:e,space:t}){let o=`[${Yd.name}]`;try{if(Do&&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 a=n.newIbGib,s=[];s.push(a),n.intermediateIbGibs?.forEach(l=>s.push(l)),n.dnas?.forEach(l=>s.push(l));for(let l=0;l<s.length;l++){let b=s[l],p=await ge({ibGib:b});if((p??[]).length>0)throw new Error(`(UNEXPECTED) invalid app ibgib created. validationErrors: ${p}. app: ${K(a.toIbGibDto())} (E: 54cfc2f6bc284ed79be91d2da5e4bd2f)`)}await Ie({resTransform:n,space:t});let{zeroSpace:i,fnBroadcast:c,fnUpdateBootstrap:d}=e;return await xe({ibGib:a,space:t,fnBroadcast:f(l=>c(l),"fnBroadcast")}),await kr({type:"apps",rel8nName:Co,ibGibsToRel8:[a],space:t,zeroSpace:i,fnUpdateBootstrap:d,fnBroadcast:c}),a}catch(n){debugger;console.error(`${o} ${n.message}`);return}finally{Do&&console.log(`${o} complete.`)}}f(Yd,"createNewApp");var zd="0",Jd="chat_gib",Zd="A chat app done ibgib style, enabling infinitely nesting comments, pics and links. It's ibgibs all the way down...",Ti={version:"1",uuid:zd,name:Jd,description:Zd,classname:"ChatApp_V1",icon:"chatbubbles",persistOptsAndResultIbGibs:!1,allowPrimitiveArgs:!0,catchAllErrors:!0,trace:!1},Gi=void 0;var Qd="0",ef="raw_gib",tf="Explorer app for navigating raw ibgib data.",Ci={version:"1",uuid:Qd,name:ef,description:tf,classname:"RawApp_V1",icon:"paper-plane",persistOptsAndResultIbGibs:!1,allowPrimitiveArgs:!0,catchAllErrors:!0,trace:!1},vi=void 0;var Ea="0",rf="todo_gib",of="Todo app for viewing and interacting with ibgibs like they're checklists.",Oi={version:"1",uuid:Ea,name:rf,description:of,classname:"TodoApp_V1",icon:"checkbox",persistOptsAndResultIbGibs:!1,allowPrimitiveArgs:!0,catchAllErrors:!0,trace:!1},Ni=void 0;async function wa(r){let e=`[${wa.name}]`,t=[];try{y({ibGib:r})!==mr&&t.push(`invalid bootstrapSpace addr. Should equal "${mr}" (E: ecfdbed719284db7a1aa3f867f706fe9)`);let n=await ge({ibGib:r});(n?.length??!1)&&n.forEach(i=>t.push(i));let a=r.data,s=r.rel8ns;return Object.keys(a||{}).length===0&&t.push("invalid bootstrapSpace data. data required (E: 5a9bd15dd0644f9b93cafbbba660cfdf)"),(a.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)"),a.spaceIds.forEach(i=>{(s[i]??[]).length===0&&t.push(`invalid bootstrap. Each spaceId listed in data should have a corresponding address in rel8ns. spaceId (${i}) missing. (E: 62dd0d76e29a415a98b4b27deb8db17e)`)}),a[_t]?(s[a[_t]]??[]).length===0&&t.push(`invalid bootstrap. data.${_t} (${a[_t]}) not found in rel8ns. (E: 44d0799d232f4a51a0b0019ebebe019f)`):t.push(`invalid bootstrap. data.${_t} required. (E: f763af2e275f445cbf1db5801bacafad)`),t.length===0?!0:(console.error(`${e} errors: ${t.join("|")}`),!1)}catch(o){return console.error(`${e} ${o.message}`),!1}}f(wa,"validateBootstrapIbGib");var Br="meta_stone";var ya="undefined",eo="target",Po="targetTjp";var ft=!1;function Li({ib:r}){let e=`[${Li.name}]`;try{ft&&console.log(`${e} starting...`);let t=[],o=r.split(" ");o[0]!==Br&&t.push(`${e} invalid ib. atom is expected to be META_STONE_ATOM: ${Br} (E: a9812bffc18f44418aa091fb0ed260bd)`);let a=o[1],s=Dr({gib:a})??[];s.length>0&&t.push(`invalid ib. pieces[1] should be a valid tjpGib. validation errors: ${s} (E: 233db2babfbe4d28a80f98261f1c0e01)`);let i=o[2],c=Number.parseInt(i);isNaN(c)&&t.push("invalid ib. space-delimited pieces[2] should be valid integer (E: 71df0d6abd7b4cf4b11621e6bfb556cd)");let d=o[3];if(d!=="undefined"){let l=Qt({timestamp:d});l.valid||t.push(`invalid ib. pieces[3] should be valid timestampInTicks. emsg: (${l.emsg}) (E: 06dae01d66f54f54b71d9c920c730840)`)}return t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{ft&&console.log(`${e} complete.`)}}f(Li,"validateCommonMetaStoneIb");function $a({data:r}){let e=`[${$a.name}]`;try{if(ft&&console.log(`${e} starting...`),!r)throw new Error("data required (E: c50ac422af4501b72af12481fbd4961e)");let t=[],{targetData:o,timestamp:n}=r;Qt({timestamp:n}).valid||t.push("invalid timestampInTicks. should be valid ticks number. (E: 7e381ed5b0c8486b90cfd37676da3626)");let{tjpGib:s,n:i,timestamp:c}=o;if(s&&s!=="undefined"){let l=Dr({gib:s})??[];l.length>0&&t.push(`invalid data (targetTjpGib). validation errors: ${l} (E: d216b12eb75544ef8c5ffb27cd132e2e)`)}if(typeof i!="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 l=Qt({timestamp:c});l.valid||t.push(`invalid targetTimestamp. emsg: ${l.emsg} (E: c15d4fd2a2b74a0fab3223e83d954379)`)}let d=new Date(n);return t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{ft&&console.log(`${e} complete.`)}}f($a,"validateCommonMetaStoneData");function Di({rel8ns:r}){let e=`[${Di.name}]`;try{if(ft&&console.log(`${e} starting...`),!r)throw new Error("rel8ns required (E: 7737ae550e2347e68c67b715c1221393)");let t=[],o=Qn({rel8ns:r??{}})??[];o.length>0&&t.push(`invalid rel8ns intrinsically. errors: ${o.join("|")}. (E: abc91753f0f946afa0a3ea2c1917960f)`);let n=r[eo]??[];n.length===0?t.push(`invalid metastone rel8ns. should have exactly 1 rel8nName ${eo}. has 0. (E: 8181652da9e89613e204d245db12d723)`):n.length>1&&t.push(`invalid metastone rel8ns. should have exactly 1 rel8nName ${eo}. has ${n.length}. (E: 2318047c6fea482d9f53febe02cf8912)`);let a=r[Po]??[];return a.length>1&&t.push(`invalid metastone rel8ns. should have 0 or 1 rel8nName ${Po}. has ${a.length}. (E: 34a8ae53825f46caa7ad024a64400db2)`),t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{ft&&console.log(`${e} complete.`)}}f(Di,"validateCommonMetaStoneRel8ns");async function nf({ibGib:r}){let e=`[${nf.name}]`;try{ft&&console.log(`${e} starting... (I: f32249d08105b997871a06cdee006311)`);let t=await ge({ibGib:r})??[];if(!r.data)throw new Error("MetaStoneIbGib.data required (E: 96432cf4f919d339277d9a1c61ea4264)");let o=[];try{let{atom:i,tjpGib:c,n:d,timestampInTicks:l}=Ri({ib:r.ib})}catch(i){o.push(E(i))}let n=$a({data:r.data}),a=Di({rel8ns:r.rel8ns}),s=[...t??[],...o??[],...n??[],...a??[]];return s.length>0?s:void 0}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{ft&&console.log(`${e} complete.`)}}f(nf,"validateCommonMetaStoneIbGib");function Pi({data:r,classname:e}){let t=`[${Pi.name}]`;try{let o=$a({data:r});if(o.length>0)throw new Error(`invalid MetaStone data: ${o} (E: ac642cc5915f0fc0508cb2fb728c86fa)`);e&&ft&&console.log(`${t} classname not required. no big deal that it is provided here. (I: db4d41471cb976795afd3fa89f8cb823)`);let n=r.targetData.timestamp,a=n&&n!=="undefined"?nt(n):ya;return`${Br} ${r.targetData.tjpGib} ${r.targetData.n} ${a}`}catch(o){throw console.error(`${t} ${E(o)}`),o}}f(Pi,"getMetaStoneIb");function Ri({ib:r}){let e=`[${Ri.name}]`;try{if(!r)throw new Error("MetaStone ib required (E: 8e74e098d7aeef52d3952e35150d83ed)");let t=Li({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(Ri,"parseMetaStoneIb");function Ng({addr:r,ibGib:e}){if(r||=y({ibGib:e}),!r)throw new Error("either addr or ibGib required. (E: 372b2574d5a9fac298119beed9f6e223)");return r.startsWith(`${Br} `)}f(Ng,"isMetaStone");async function Ia({targetIbGib:r}){let e=`[${Ia.name}]`;try{ft&&console.log(`${e} starting... (I: d846313065c89c89e4b5afa2df2b7123)`);let t=y({ibGib:r}),o=de({ibGib:r,defaultIfNone:"incomingAddr"}),n,a={[eo]:[t],[Po]:[o]};if(!r.gib)throw new Error("(UNEXPECTED) targetIbGib.gib falsy? (E: 28eaa8a799021dadd87b043711aee826)");let s=r.data?.isTjp?r.gib:Pe({ibGibAddr:t}).tjpGib??r.gib;if(s===re)throw new Error("cannot create metastone for primitive ibgib (E: 2887e8ef83381a0698256b7bc7531826)");let i=new Date,c=oe(i),d=i.getMilliseconds();r.data?to({ibGib:r})?n={targetData:{n:-1,tjpGib:s},timestamp:c,timestampMs:d}:(n={targetData:{n:r.data.n??-1,tjpGib:s,timestamp:r.data.timestamp??ya},timestamp:c,timestampMs:d},r.data?.isTjp&&(n.targetData.isTjp=!0)):n={targetData:{n:-1,tjpGib:s},timestamp:c,timestampMs:d};let l=Pi({data:n}),b=await mt({parentPrimitiveIb:Br,ib:l,data:n,rel8ns:a});return ft&&(console.log(`${e} metaStoneIbGib... (I: 2b16197478488b329246d22d2dc41423)`),console.dir(b)),b}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{ft&&console.log(`${e} complete.`)}}f(Ia,"newUpMetaStone");var Ro="witness",ro="witness_arg",ko="witness_result",Dg="context";var C=!1;async function te({addr:r,addrs:e,isDna:t,space:o,force:n}){let a=`[${te.name}]`;try{if(C&&console.log(`${a} 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(`${a} 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 s=await o.argy({ibMetadata:Ht({space:o}),argData:{cmd:"get",ibGibAddrs:e,isDna:t}}),i=await o.witness(s);return i?.data?.success?(C&&console.log(`${a} got.`),{success:!0,ibGibs:i.ibGibs,rawResultIbGib:i}):(C&&console.log(`${a} didn't get.`),{success:!1,errorMsg:i.data?.errors?.join("|")||`${a} something went wrong. addrs: ${e.join(`
2
+ `)} (E: b9e9d5ce0cde4122bfb74f7688db85e0)`,rawResultIbGib:i})}catch(s){return console.error(`${a} ${s.message}`),{errorMsg:s.message}}}f(te,"getFromSpace");async function qe({ibGib:r,ibGibs:e,isDna:t,force:o,space:n}){let a=`[${qe.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(`${a} 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],C&&console.log(`${a} ibGibs.length: ${e.length}`);let s=await n.argy({ibMetadata:Ht({space:n}),argData:{cmd:"put",force:o,isDna:t,ibGibAddrs:e.map(c=>y({ibGib:c}))},ibGibs:e.concat()}),i=await n.witness(s);if(i.data?.success)return(i.data.warnings??[]).length>0&&i.data.warnings.forEach(c=>console.warn(`${a} ${c}`)),{success:!0};{let c=i?.data?.errors?.length>0?`Error(s) putting in local space:
3
+ ${i.data.errors.join(`
4
+ `)}`:"(UNEXPECTED) unknown error putting ibGibs (E: 3d7426d4527243b79c5e55eb25f3fa73)";throw new Error(c)}}catch(s){return console.error(`${a} ${s.message}`),{errorMsg:s.message}}}f(qe,"putInSpace");async function _a({addr:r,isDna:e,space:t}){let o=`[${_a.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:Ht({space:t}),argData:{cmd:"delete",ibGibAddrs:[r],isDna:e}}),a=await t.witness(n);if(a.data?.success)return{success:!0};{a.data?.warnings?.length>0&&console.warn(`${o} warnings with delete (${r}): ${a.data.warnings.join("|")}`),a.data?.addrs?.length>0&&console.warn(`${o} partial addrs deleted: ${a.data.addrs.join("|")}`);let s=a.data?.errors?.join("|")||`${o} something went wrong (E: e397fd09b4a746a3ba3305d6ea0893cb)`;return s.includes("File does not exist")&&C&&console.log(`${o} tried to delete file that does not exist. (I: cb5d1348ccbc58bf0bfc95f3006f1e22)`),{errorMsg:s}}}catch(n){return console.error(`${o} ${n.message}`),{errorMsg:n.message}}}f(_a,"deleteFromSpace");async function Ie({resTransform:r,space:e,force:t}){let o=`[${Ie.name}]`;try{if(C&&console.log(`${o} starting... (I: dc6835614ff1a1b82b179225023ae823)`),!e)throw new Error("space required. (E: cf94f1d74f1c4561bb88025a2095965b)");let{newIbGib:n,intermediateIbGibs:a,dnas:s}=r,i=[n,...a||[]],c=await e.argy({ibMetadata:Ht({space:e}),argData:{cmd:"put",force:t,ibGibAddrs:i.map(l=>y({ibGib:l}))},ibGibs:i.concat()}),d=await e.witness(c);if(d.data?.success)d.data.warnings?.length>0&&d.data.warnings.forEach(l=>console.warn(`${o} ${l}`));else{let l=d?.data?.errors?.length>0?d.data.errors.join(`
5
+ `):"unknown error putting ibGibs";throw new Error(l)}if(s?.length??!1){let l=await e.argy({ibMetadata:Ht({space:e}),argData:{cmd:"put",isDna:!0,force:t,ibGibAddrs:s.map(p=>y({ibGib:p}))},ibGibs:s.concat()}),b=await e.witness(l);if(b.data?.success)b.data.warnings?.length>0&&b.data.warnings.forEach(p=>console.warn(`${o} ${p}`));else{let p=b?.data?.errors?.length>0?b.data.errors.join(`
6
+ `):"unknown error putting dna ibGibs";throw new Error(p)}}}catch(n){throw console.error(`${o} ${n.message}`),n}finally{C&&console.log(`${o} complete. (I: dc6835614ff1a1b82b179225023ae823)`)}}f(Ie,"persistTransformResult");async function af({type:r,rel8nName:e,space:t}){let o=`[${af.name}]`;try{if(!t)throw new Error("space required. (E: f73868a952ac4181a4f90ee6d86cacf3)");let n=await Mo({type:r,space:t});if(!n)throw new Error(`couldn't get special (${r}) (E: a65bef190416479697605be486846731)`);let a=n.rel8ns?n.rel8ns[e]||[]:[],s=[];for(let i=0;i<a.length;i++){let c=a[i],d=await te({addr:c,space:t});if(d.success&&d.ibGibs?.length===1)s.push(d.ibGibs[0]);else throw new Error(`couldn't get addr: ${c} (E: 76ef256ee80149ab860c5786484b0e89)`)}return s}catch(n){throw console.error(`${o} ${n.message}`),n}}f(af,"getSpecialRel8dIbGibs");async function Mo({type:r,initialize:e,space:t,zeroSpace:o,fnUpdateBootstrap:n,fnBroadcast:a,fnGetInitializing:s,fnSetInitializing:i,dontWarnIfNotExist:c}){let d=`[${Mo.name}]`;try{if(!t)throw new Error("space required. (E: d454b31d58764a9bb9c4e47fb5ef38b5)");let l=Le({type:r}),b=await Fo({key:l,space:t,dontWarn:c||!!e});if(!b){if(e&&(!s||!i))throw new Error("if initialize, you must provide fnGetInitializeLock & fnSetInitializeLock. (E: 8eb322625d0c4538be089800882487de)");if(e&&!s()){i(!0);try{if(!o)throw new Error("zeroSpace required when 'initialize' truthy (E: 8582c92c637f90c9b2dbe0ec8355b523)");b=await Ui({type:r,space:t,zeroSpace:o,fnBroadcast:a,fnUpdateBootstrap:n})??void 0}catch(m){console.error(`${d} error initializing: ${m.message}`)}finally{i(!1)}}if(!b){if(s&&s())return console.warn(`${d} 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)")}}C&&console.log(`${d} getting addr: ${b}`);let p=await te({addr:b,space:t});if(p.success||(p=await te({addr:b,space:t}),p.success&&(console.warn(`${d} special ibgib was not stored in meta folder...putting in meta folder now for the future (W: e6f5571fd98c449bb2809359be5057cc)`),(await qe({ibGib:p.ibGibs[0],space:t})).success||console.warn(`${d} (UNEXPECTED) tried to put special in meta but success was false? (W: b934b53571c24057af172c790e6a7240)`))),!p.success)throw new Error(p.errorMsg);if(p.ibGibs?.length!==1)throw new Error("no ibGib in result (E: 3a42abdddc3648e292d63dc45c560064)");let h=p.ibGibs[0],g=await We({ibGibs:[h],space:t});if(g?.data?.success&&g.data.addrs?.length===1){let m=y({ibGib:h}),w=g.data.addrs[0];w!==m&&console.warn(`${d} latest addr is not the one associated with the local space.
7
+ specialAddr: ${m}
8
+ latestAddr: ${w} (W: 141b69dc3c414efc9645bb76fcf12df9)`)}return h}catch(l){let b=`${d} ${l.message}`;return b.includes("d8ebdc9eaaa640b99cd206f132962c93")&&c||console.error(b),null}}f(Mo,"getSpecialIbGib");async function Fo({key:r,space:e,dontWarn:t}){let o=`[${Fo.name}](${r})`;try{if(C&&console.log(`${o} getting... (I: 43e7bfc2515d45e5af8767b9a85b248e)`),!e)throw new Error("space required. (E: 4f135d4276e64054ba21aeb9c304ecec)");if(!e.rel8ns){(C||!t)&&console.warn(`${o} space.rel8ns falsy. (W: 7c642259fbf547dbaa1b2fdf0115f6ef)`);return}if(!e.rel8ns[r]){(C||!t)&&console.warn(`${o} space.rel8ns[${r}] falsy. (W: 3c1c49b9987b45cc96dd78b808f98e91)`);return}if(e.rel8ns[r].length===1)return C&&console.log(`${o} got (I: f13e71b693d5404c9535bda8ff0cc6a9)`),e.rel8ns[r][0];if(e.rel8ns[r].length>1)return(C||!t)&&console.warn(`${o} more than one config addr with ${r} rel8n. (W: 102f63eb74904bcfaac2eaf778043205)`),e.rel8ns[r][0];C&&console.log(`${o} didn't find (I: 1163e6ac60194d25b3f24881650edfad)`);return}catch(n){console.error(`${o} ${n.message}`);return}}f(Fo,"getConfigAddr");async function je({key:r,addr:e,space:t,zeroSpace:o,fnUpdateBootstrap:n}){let a=`[${je.name}]`;try{if(!t)throw new Error("space required. (E: c28b663c991d44419aef1026cc689636)");if(!o)throw new Error("zeroSpace required. (E: d3707ae5265d464891ad216f64be6184)");let s={[r]:[e]},i=await Xe({src:t.toIbGibDto(),dna:!1,linkedRel8ns:["past","ancestor",r],rel8nsToAddByAddr:s,nCounter:!0});if(!i.newIbGib)throw new Error("create new space failed.");await Ie({resTransform:i,space:o}),await Ie({resTransform:i,space:t});let c=i.newIbGib;return await t.loadIbGibDto(c),n?await n(c):console.warn(`${a} fnUpdateBootstrap is falsy. (W: 9fb874de2b19454dac18645e61ac463f)`),c}catch(s){throw console.error(`${a} ${s.message}`),s}}f(je,"setConfigAddr");async function ki({space:r}){let e=`[${ki.name}]`;try{if(!r)throw new Error("space required. (E: f0d546101fba4c169256158114ab3c56)");let t=await Mo({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 te({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(ki,"getCurrentRoot");async function Aa({root:r,space:e,zeroSpace:t,fnUpdateBootstrap:o,fnBroadcast:n}){let a=`[${Aa.name}]`;try{if(C&&console.log(`${a} starting... (I: 7f16e845a80fe95d28923e4170f0c825)`),!r)throw new Error("root required.");if(!e)throw new Error("space required. (E: 186af2731c5342a78b063a0a4346f3db)");let s=y({ibGib:r}),i=await Mo({type:"roots",space:e});if(!i)throw new Error("Roots not initialized. (E: a8232b9afac89d0d189534480b7a9825)");let d=await Xe({src:i,dna:!1,linkedRel8ns:["past","ancestor","current"],rel8nsToAddByAddr:{current:[s]},nCounter:!0});await Ie({resTransform:d,space:e});let l=Le({type:"roots"}),b=d.newIbGib,p=y({ibGib:b});await je({key:l,addr:p,space:e,zeroSpace:t,fnUpdateBootstrap:o}),await xe({ibGib:b,space:e,fnBroadcast:n})}catch(s){throw console.error(`${a} ${s.message}`),s}finally{C&&console.log(`${a} complete. (I: 7f16e845a80fe95d28923e4170f0c825)`)}}f(Aa,"setCurrentRoot");async function Bi({ibGib:r,linked:e,rel8nName:t,space:o,fnBroadcast:n,zeroSpace:a,fnUpdateBootstrap:s}){let i=`[${Bi.name}]`;try{if(!o)throw new Error("space required. (E: f2758eab3bb844d2b749515672d9e392)");if(!r)throw new Error("ibGib required (E: f1bfd67754a7271553f4af544d30bc22)");let c=await ki({space:o});if(!c)throw new Error("currentRoot undefined (E: 5c2d84dafc664808866008f6eb535750");let d=de({ibGib:r,defaultIfNone:"incomingAddr"}),l=y({ibGib:r});if(t&&d&&c.rel8ns&&c.rel8ns[t]&&c.rel8ns[t].includes(d))return;t=t||oa;let b=await Xe({src:c,dna:!1,linkedRel8ns:e?["past","ancestor",t]:["past","ancestor"],rel8nsToAddByAddr:{[t]:[l]},nCounter:!0});await Ie({resTransform:b,space:o});let p=b.newIbGib,h=y({ibGib:p});C&&console.log(`${i} updating _currentRoot root. newRootAddr: ${h}`),await xe({ibGib:p,space:o,fnBroadcast:n}),await Aa({root:p,space:o,zeroSpace:a,fnUpdateBootstrap:s,fnBroadcast:n})}catch(c){console.error(`${i} ${c.message}`);return}}f(Bi,"rel8ToCurrentRoot");async function Sa({targetIbGib:r,space:e}){let t=`[${Sa.name}]`;try{C&&console.log(`${t} starting... (I: 291638372117dbc983b4b7cbd8f52123)`);let o=await Ia({targetIbGib:r}),n=await qe({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{C&&console.log(`${t} complete.`)}}f(Sa,"createAndSaveNewMetaStone");async function xe({ibGib:r,space:e,fnBroadcast:t}){let o=`[${xe.name}]`,n=C;try{let a=y({ibGib:r});if(o=`${o}[${a}]`,!e)throw new Error("space required. (E: ea0c03256f8a4062b460aa4de11f1e3e)");if(C&&console.log(`${o} starting...`),!Pe({ibGibAddr:a}).tjpGib&&!r.data?.isTjp){C&&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 Sa({targetIbGib:r,space:e});return}let i=de({ibGib:r,defaultIfNone:"undefined"});if(!i){let g=r.data?.isTjp?r:await oo({ibGib:r,space:e});g||(console.warn(`${o} tjp not found for ${a}? Should at least just be the ibGib's address itself. (W: d9b570e5bf6d4312bc7d9249ed3bbaad)`),g=r),i=y({ibGib:g})}if(!i)throw new Error("(UNEXPECTED) tjpAddr falsy? should be guaranteed at this point. (E: 39aafb70bc3c6d70b6d2cf8882311223)");let c=f(async()=>{C&&console.log(`${o} adding/replacing latest. tjp: ${i} (I: 7f848da003a2436089fd6f044d96bb42)`),await Sa({targetIbGib:r,space:e}),t&&(C&&console.log(`${o} fnBroadcast is true...(I: 0e3b561fb5474a0598b5c6d698df5e1f)`),setTimeout(()=>{C&&console.log(`${o} broadcasting... (I: 61785937be0346f0959d476d7267ab24)`),t({ib:"IbGibTimelineUpdateInfo",tjpAddr:i,latestAddr:a,latestIbGib:r})}))},"replaceLatest");if(r.data?.isTjp){C&&console.log(`${o} ibGib.data?.isTjp true. replacingLatest and returning early. (I: 02c626e006668291550e278b461bcb23)`),await c();return}C&&console.log(`${o} ibGib.data?.isTjp is falsy. (I: 84940e3a9eff869c9474b7b92b864b23)`);let d=await We({ibGibs:[r],space:e});if(!d.data)throw new Error("(UNEXPECTED) resLatest.data falsy? (E: af3d3914d96adcc5525e4db83cc5d223)");let{success:l,latestAddrsMap:b}=d.data;if(!l){let{errors:g}=d.data;throw g??=["[unknown error (E: 344857f1853641aa842cea3931f90428)]"],new Error(`resLatest.success falsy. errors: ${K(g)}. addr: ${a} (E: b66721da6e1ef9ac4f4089e86c059323)`)}if(!b)throw new Error("(UNEXPECTED) latestAddrsMap falsy but success truthy? (E: c34caff7a256503575ff3ff491dec823)");let p=Object.keys(b);if(p.length!==1)throw new Error("(UNEXPECTED) latestAddrsMap size isn't 1? (E: e11ffc2c18d473745b5bbfc3fe5e3a23)");if(p[0]!==a)throw new Error(`(UNEXPECTED) latestAddrsMap has 1 key (correct) but the key isn't the incoming ibGibAddr? (incorrect). incoming ibGibAddr: ${a}. key found: ${p[0]} (E: 82d79a95d2d7de90eae9db571a360f23)`);C&&(console.log(`${o} valid latestAddrsMap. console.dir(latestAddrsMap)... (I: e24de41622cabbef375172c3017cfd23)`),console.dir(b));let h=b[a];if(h)if(h===a){C&&console.log(`${o} no other found. possible idempotent replacement. addr: ${a} (I: 7f5bd5d3391be95919240f0e97976e22)`),await c();return}else{C&&console.log(`${o} different addr found. incoming ibgib addr is newer. existingLatestAddr: ${h}. incoming addr: ${a} (I: 6cadf13f82aabeb71d76babf1813e623)`);let g=await te({addr:h,space:e});if(!g.success||g.ibGibs?.length!==1){console.error(`Didn't find existing latest ibGib (${h}). 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 m=g.ibGibs[0];if(typeof r.data?.n=="number"&&r.data.n>=0){C&&console.log(`found ibGib.data.n (version counter), using this to determine latest ibGib: ${r.data.n}`);let S=r.data.n;if(typeof m.data?.n=="number"&&m.data.n>=0){let I=m.data.n;if(S>I)C&&console.log(`${o} is newer (I: 040d05ac2032f08c7fd0c4d8b2887323)`),await c();else{C&&console.log("is not newer, so we don't need to do anything else. (I: 14c25dc3314748dc909d61b77eb64354)"),console.warn(`${o} incoming ibGib (${a}) is NOT NEWER than existing latest (${h}). multiple branches for the same timeline? ignoring incoming ibGibAddr. n_ibGib: ${S}. n_existingLatest: ${I}. space.ib: ${e.ib} (W: 057baadca494473dabb26fb4fb879774)`);return}}else m.data?.isTjp&&r.data.n===0?await c():(console.warn(`${o} (UNEXPECTED) only existingLatestIbGib (isTjp: ${m.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(m),console.log(`${o} console.dir(ibGib)... (I: 9ef7962d9cc74f1eb0409e5caf98e915)`),console.dir(r),await c())}else if(C&&console.log(`${o} no nCounter found. Trying brute force method.`),await Ji({ibGib:r,ibGibAddr:a,existingLatest:m,existingLatestAddr:h,tjpAddr:i,space:e})===a)await c();else return}else if(h===null){C&&console.log(`${o} no existing tjp mapping so incoming ibgib is considered new to this space. ibGib addr: ${a} (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(a){throw console.error(`${o} ${a.message}`),a}finally{C&&console.log(`${o} complete.`),C=n}}f(xe,"registerNewIbGib");async function kr({type:r,rel8nName:e,ibGibsToRel8:t,ibGibsToUnRel8:o,addrsToUnRel8:n,linked:a,severPast:s,deletePreviousSpecialIbGib:i,space:c,zeroSpace:d,fnUpdateBootstrap:l,fnBroadcast:b}){let p=`[${kr.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 h=t?.map(_=>y({ibGib:_}));n??=o?.map(_=>y({ibGib:_}));let g=Le({type:r}),m=await Fo({key:g,space:c});if(!m)throw new Error("specialAddr not found (E: 680dfd1caa3e4d7cb0f593b893a10f0d)");let w=await te({addr:m,space:c});if(!w.success)throw new Error("couldn't get special (E: 897f7671d2184515866c5a675d33b3dc)");if(!w.ibGibs)throw new Error("resGetSpecial.ibGibs falsy (E: 2405dd295b2444d88503f7731796a5a0)");if(w.ibGibs.length!==1)throw new Error(`resGetSpecial.ibGibs count is not 1 (${w.ibGibs.length}) (E: b4547789016a4729af30cd972a4ca4ab)`);let S=w.ibGibs[0],A=await Xe({src:S,rel8nsToAddByAddr:h?{[e]:h}:void 0,rel8nsToRemoveByAddr:n?{[e]:n}:void 0,dna:!1,linkedRel8ns:a?[Ee.past,e]:[Ee.past],nCounter:!0}),I=A.newIbGib;if(s){if(A.intermediateIbGibs)throw new Error("new special creates intermediate ibgibs. so severing past is harder. (E: b580c0c56253494192e9c62212ee187d)");I.rel8ns.past=[],I.gib=await ue({ibGib:I})}await Ie({resTransform:A,space:c});let $=y({ibGib:I}),T=de({ibGib:I});return await je({key:g,addr:$,space:c,zeroSpace:d,fnUpdateBootstrap:l}),i&&await _a({addr:m,space:c}),await xe({ibGib:I,fnBroadcast:b,space:c}),$}catch(h){throw console.error(`${p} ${h.message}`),h}}f(kr,"rel8ToSpecialIbGib");async function oo({ibGib:r,naive:e=!0,space:t}){let o=`[${oo.name}]`;try{if(!t)throw new Error("space required. (E: 941f973d50e84415b58724af173f52c2)");if(!r)throw new Error("ibGib required.");let n=y({ibGib:r}),{gib:a}=ne({ibGibAddr:n});if(a===re||await Oa({ibGib:r,naive:e}))return r;if(!r.rel8ns){C&&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],p=await te({addr:b,space:t});if(p.success&&p.ibGibs?.length===1)return p.ibGibs[0];{let h=p.errorMsg??"[unspecified error in get result]";throw new Error(`ibGib references tjp but could not retrieve from space. res error: ${h} (E: 94f0340706ad48c794c6a62c1b235a22)`)}}let i=r.rel8ns.past||[];if(i.length===0){console.warn(`${o} past.length === 0, so there is no tjp.`),C&&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=i[i.length-1],d=await te({addr:c,space:t});if(!d.success||d.ibGibs?.length!==1)throw new Error(`get past failed. addr: ${c}`);let l=d.ibGibs[0];return await oo({ibGib:l,naive:e,space:t})}catch(n){throw console.error(`${o} ${n.message}`),n}}f(oo,"getTjpIbGib");async function Ui({type:r,space:e,zeroSpace:t,fnUpdateBootstrap:o,fnBroadcast:n}){let a=`[${Ui.name}]`;try{if(!e)throw new Error("space falsy and localUserSpace not initialized. (E: 66e7d3ff098248f0a5ddda51853c92e6)");switch(r){case"roots":return ji({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});case"tags":return Mi({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});case"secrets":return Hi({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});case"encryptions":return Ki({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});case"outerspaces":return Xi({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});case"autosyncs":return qi({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});case"robbots":return Wi({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});case"apps":return Yi({space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});default:return zi({type:r,space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o})}}catch(s){throw console.error(`${a} ${s.message}`),s}}f(Ui,"createSpecial");async function Ct({type:r,skipRel8ToRoot:e,space:t,zeroSpace:o,fnUpdateBootstrap:n,fnBroadcast:a}){let s=`[${Ct.name}][${r||"falsy type?"}]`;try{C&&console.log(`${s} starting...`);let i=Ca({type:r}),c=F.primitive({ib:i}),d=await Io({src:c,destIb:i,linkedRel8ns:[Ee.past,Ee.ancestor],tjp:{uuid:!0,timestamp:!0},dna:!0,nCounter:!0});return await Ie({resTransform:d,space:t}),r!=="roots"&&r!=="latest"&&!e&&await Bi({ibGib:d.newIbGib,linked:!0,space:t,zeroSpace:o,fnBroadcast:a,fnUpdateBootstrap:n}),C&&console.log(`${s} complete.`),d.newIbGib}catch(i){throw console.error(`${s} ${i.message}`),i}}f(Ct,"createSpecialIbGib");async function Mi({space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}){let n=`[${Mi.name}]`;try{if(!r)throw new Error("space required. (E: 9c05b9bd355943a39ca47afef67a50eb)");let a=Le({type:"tags"}),s=await Ct({type:"tags",space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t}),i=y({ibGib:s});await je({key:a,addr:i,space:r,zeroSpace:e,fnUpdateBootstrap:t});let c=[{text:"home",icon:"home-outline"},{text:"favorite",icon:"heart-outline"}];for(let d of c)i=(await Fi({...d,space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t})).newTagsAddr,await je({key:a,addr:i,space:r,zeroSpace:e,fnUpdateBootstrap:t});return i}catch(a){return console.error(`${n} ${a.message}`),null}}f(Mi,"createSpecial_Tags");async function Fi({text:r,icon:e,description:t,space:o,zeroSpace:n,fnUpdateBootstrap:a,fnBroadcast:s}){let i=`[${Fi.name}]`;try{if(C&&console.log(`${i} starting...`),!o)throw new Error("space required. (E: 5def0b1afab74b0c9286e3ac5060cb8f)");if(!r)throw new Error(`${i} text required`);e=e||li,t=t||di;let c=Er(r),d=F.primitive({ib:"tag"}),l=await F.firstGen({parentIbGib:d,ib:c,data:{text:r,icon:e,description:t},tjp:{uuid:!0,timestamp:!0},dna:!0,nCounter:!0}),b=l.newIbGib;await Ie({resTransform:l,space:o}),await xe({ibGib:b,space:o,fnBroadcast:s});let p=await sf({tagIbGib:b,space:o,zeroSpace:n,fnUpdateBootstrap:a,fnBroadcast:s});return{newTagIbGib:b,newTagsAddr:p}}catch(c){throw console.error(`${i} ${c.message}`),c}finally{C&&console.log(`${i} complete.`)}}f(Fi,"createTagIbGibAndSundry");async function ji({space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}){let n=`[${ji.name}]`;try{if(!r)throw new Error("space required. (E: d12a8ea31163429fb6e53ff8e7579c57)");let a=Le({type:"roots"}),s=await Ct({type:"roots",space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t}),i=y({ibGib:s});await je({key:a,addr:i,space:r,zeroSpace:e,fnUpdateBootstrap:t});let d=["A","B","C","D","E","F","G"].map(b=>({text:`${b}root`,icon:na,description:aa})),l;for(let b=0;b<d.length;b++){let p=d[b],h=await Vi({...p,space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o});if(l||(l=h.newRootIbGib),!h.newRootIbGib)throw new Error("(UNEXPECTED) resCreate.newRootIbGib falsy? (E: c9fb2c94a9c1d762c1699b41a4d5ad23)");i=h.newRootsAddr,await je({key:a,addr:i,space:r,zeroSpace:e,fnUpdateBootstrap:t})}if(!l)throw new Error("(UNEXPECTED) firstRoot still falsy? (E: b2e2c926d242966e7ed7159e4b129e23)");if(await Aa({root:l,space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}),i=await Fo({key:a,space:r}),!i)throw new Error("(UNEXPECTED) no roots address in config? (E: 76345340699a4738a195e48803ef0d31)");return i}catch(a){return console.error(`${n} ${a.message}`),null}}f(ji,"createSpecial_Roots");async function Vi({text:r,icon:e,description:t,space:o,zeroSpace:n,fnUpdateBootstrap:a,fnBroadcast:s}){let i=`[${Vi.name}]`;try{if(!o)throw new Error("space required. (E: cfa876e5c8c64a53a463ca7a645571c8)");r=r||ci,e=e||na,t=t||aa;let c=va(r),d=F.primitive({ib:"root"}),l=await F.firstGen({parentIbGib:d,ib:c,data:{text:r,icon:e,description:t},linkedRel8ns:[Ee.past,Ee.ancestor],tjp:{uuid:!0,timestamp:!0},dna:!0,nCounter:!0}),{newIbGib:b}=l;await Ie({resTransform:l,space:o});let p=await kr({type:"roots",rel8nName:ra,ibGibsToRel8:[b],space:o,zeroSpace:n,fnUpdateBootstrap:a,fnBroadcast:s});return{newRootIbGib:b,newRootsAddr:p}}catch(c){throw console.error(`${i} ${c.message}`),c}}f(Vi,"createRootIbGib");async function Hi({space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}){let n=`[${Hi.name}]`;try{if(!r)throw new Error("space required. (E: 340960cd5ad24addb300b23d9722e30a)");let a,s=Le({type:"secrets"}),i=await Ct({type:"secrets",space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t});return a=y({ibGib:i}),await je({key:s,addr:a,space:r,zeroSpace:e,fnUpdateBootstrap:t}),a}catch(a){return console.error(`${n} ${a.message}`),null}}f(Hi,"createSpecial_Secrets");async function Ki({space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}){let n=`[${Ki.name}]`;try{if(!r)throw new Error("space required. (E: 5084e698b6924e7090697ca50075ca59)");let a,s=Le({type:"encryptions"}),i=await Ct({type:"encryptions",space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t});return a=y({ibGib:i}),await je({key:s,addr:a,space:r,zeroSpace:e,fnUpdateBootstrap:t}),a}catch(a){return console.error(`${n} ${a.message}`),null}}f(Ki,"createSpecial_Encryptions");async function Xi({space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}){let n=`[${Xi.name}]`;try{if(!r)throw new Error("space required. (E: 99dd9e92535c470482eb9f6625a33831)");let a,s=Le({type:"outerspaces"}),i=await Ct({type:"outerspaces",space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t});return a=y({ibGib:i}),await je({key:s,addr:a,space:r,zeroSpace:e,fnUpdateBootstrap:t}),a}catch(a){return console.error(`${n} ${a.message}`),null}}f(Xi,"createSpecial_OuterSpaces");async function qi({space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}){let n=`[${qi.name}]`;try{if(!r)throw new Error("space required. (E: f01cf6a4a460486796e16d505d629522)");let a,s=Le({type:"autosyncs"}),i=await Ct({type:"autosyncs",space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t});return a=y({ibGib:i}),await je({key:s,addr:a,space:r,zeroSpace:e,fnUpdateBootstrap:t}),a}catch(a){return console.error(`${n} ${a.message}`),null}}f(qi,"createSpecial_Autosyncs");async function Wi({space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}){let n=`[${Wi.name}]`;try{if(!r)throw new Error("space required. (E: f01cf6a4a460486796e16d505d629522)");let a,s=Le({type:"robbots"}),i=await Ct({type:"robbots",space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t});return a=y({ibGib:i}),await je({key:s,addr:a,space:r,zeroSpace:e,fnUpdateBootstrap:t}),a}catch(a){return console.error(`${n} ${a.message}`),null}}f(Wi,"createSpecial_Robbots");async function Yi({space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}){let n=`[${Yi.name}]`;try{if(!r)throw new Error("space required. (E: f01cf6a4a460486796e16d505d629522)");let a,s=Le({type:"apps"}),i=await Ct({type:"apps",space:r,zeroSpace:e,fnBroadcast:o,fnUpdateBootstrap:t});return a=y({ibGib:i}),await je({key:s,addr:a,space:r,zeroSpace:e,fnUpdateBootstrap:t}),a=await Bo({defaultAppData:Ti,defaultAppRel8ns:Gi,space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}),a=await Bo({defaultAppData:Ci,defaultAppRel8ns:vi,space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}),a=await Bo({defaultAppData:Oi,defaultAppRel8ns:Ni,space:r,zeroSpace:e,fnUpdateBootstrap:t,fnBroadcast:o}),a}catch(a){return console.error(`${n} ${a.message}`),null}}f(Yi,"createSpecial_Apps");async function Bo({defaultAppData:r,defaultAppRel8ns:e,space:t,zeroSpace:o,fnUpdateBootstrap:n,fnBroadcast:a}){let s=`[${Bo.name}]`;try{C&&console.log(`${s} starting... (I: 677f68789abdc7316887e8f38c764e22)`),C&&console.log(`${s} starting...`);let i=H(r),c=e?H(e):void 0;i.uuid=!i.uuid||i.uuid===Ea?await U():i.uuid;let{classname:d}=i,l=ma({appData:i,classname:d}),b=await F.firstGen({ib:l,parentIbGib:F.primitive({ib:`app ${d}`}),data:i,rel8ns:c,dna:!0,linkedRel8ns:[Ee.ancestor,Ee.past],nCounter:!0,tjp:{timestamp:!0}});return await Ie({resTransform:b,space:t}),await xe({ibGib:b.newIbGib,fnBroadcast:a,space:t}),await kr({type:"apps",rel8nName:Co,ibGibsToRel8:[b.newIbGib],fnBroadcast:a,fnUpdateBootstrap:n,space:t,zeroSpace:o})}catch(i){throw console.error(`${s} ${i.message}`),i}finally{C&&console.log(`${s} complete.`)}}f(Bo,"createApp");async function zi({type:r,space:e,zeroSpace:t,fnUpdateBootstrap:o,fnBroadcast:n}){let a=`[${zi.name}]`;try{if(!e)throw new Error("space required. (E: c7bbafcbe901418db4c6048f17f53091)");C&&console.log(`${a} creating special of type: ${r} (I: 283c8bb30ed6f9698b74b886c6078622)`);let s,i=Le({type:r}),c=await Ct({type:r,space:e,zeroSpace:t,fnBroadcast:n,fnUpdateBootstrap:o});return s=y({ibGib:c}),await je({key:i,addr:s,space:e,zeroSpace:t,fnUpdateBootstrap:o}),s}catch(s){return console.error(`${a} ${s.message}`),null}}f(zi,"createSpecial_Default");async function Ji({ibGib:r,ibGibAddr:e,existingLatest:t,existingLatestAddr:o,tjpAddr:n,space:a}){let s=`[${Ji.name}][${e}]`;try{if(C&&console.log(`${s} starting...`),!a)throw new Error("space required. (E: 64eb9a271f5d43deadec30b9638746c8)");let i=r.rel8ns?.past||[],c=t.rel8ns?.past||[];if(i.length===1&&c.length===0)return C&&console.log(`prospective has a past, so it "must" be newer. (won't quote "must" anymore)`),e;if(c.length===1&&i.length===0)return C&&console.log("existing has a past, so it must be newer."),o;if(c.length===0&&i.length===0)return console.warn(`${s} neither existing latest nor prospective new ibGib has a past, so keeping existing.`),o;if(c.includes(e))return C&&console.log("existing by definition is newer"),o;if(i.includes(o))return C&&console.log("ibGib by definition is newer"),e;if(o===e)return C&&console.log("they're the same!"),o;if(o===n&&t.rel8ns?.tjp?.length===1)return C&&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 C&&console.log("existing must be newer because the ibGibAddr is the tjp, which is by definition first in unique past."),o;C&&console.log(`${s} brute forcing through iterating the pasts.`);let d,l=-1,b=f(async(g,m,w)=>{let S=g.rel8ns?.past||[];if(S.includes(w))return d=y({ibGib:g}),-1;if(S.length===0)return m;let A=m+S.length;if(l!==-1&&A>l)return d=y({ibGib:g}),-1;let I=await te({addr:S[0],space:a});if(!I.success||I.ibGibs?.length!==1)throw new Error(`Couldn't load past addr (xPast[0]): ${S[0]}`);return b(I.ibGibs[0],m+S.length,w)},"getPastCount");C&&console.log(`${s} doing ibGibPastCount`);let p=await b(r,0,o);if(d)return d;C&&console.log(`${s} Doing existingPastCount`),l=p;let h=await b(t,0,e);return d||(p>h?(C&&console.log(`${s} ibGibPastCount (${p}) is longer than existingPastCount (${h}), so ibGib is newer.`),d=e):(C&&console.log(`${s} existingPastCount (${h}) is longer than ibGibPastCount (${p}), so ibGib is newer.`),d=o),d)}catch(i){throw console.error(`${s} ${i.message}`),i}finally{C&&console.log(`${s} complete.`)}}f(Ji,"getLatestAddr_Brute");function sf({tagIbGib:r,space:e,zeroSpace:t,fnUpdateBootstrap:o,fnBroadcast:n}){return kr({type:"tags",rel8nName:sa,ibGibsToRel8:[r],space:e,zeroSpace:t,fnUpdateBootstrap:o,fnBroadcast:n})}f(sf,"rel8TagToTagsIbGib");function Ta({space:r,scope:e}){let t=`[${Ta.name}]`;try{if(C&&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(Ne);)C&&console.log(`${t} scope contains ibgib delimiter...replacing... (I: 0f456fd7cc6552a799673a0c5b4a7d22)`),e=e.replace(Ne,"_");let o=r.data.uuid,n=`${ai} ${o} ${e}`;return y({ib:n,gib:re})}catch(o){throw console.error(`${t} ${o.message}`),o}finally{C&&console.log(`${t} complete.`)}}f(Ta,"getSpaceLockAddr");async function Gt({space:r,scope:e,secondsValid:t,maxDelayMs:o,fn:n,callerInstanceId:a,maxLockAttempts:s}){let i=`[${Gt.name}]`;try{if(C&&console.log(`${i} 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;C&&console.log(`${i} attempting to acquire lock with scope ${e} (I: fed36d42a975b1c52897a4df804ac722)`);let d;o=(o??0)>0?o:si;let l=0;s=s??!1?s:ii;do{if(d=await Zi({space:r,scope:e,secondsValid:t,instanceId:a}),d?.data?.success)break;let p=Math.ceil(Math.random()*o);await Oe(p),l++}while(l<s);if(d?.data?.success)C&&console.log(`${i} lock acquired. (I: d847fa953ee131a57e1a89c537342722)`);else throw new Error(`could not acquire lock after ${l} attempts with intermittent delays of ${o} ms (E: 898c559dbd0c9bf20c14cf87a8f1e222)`);let b=`${i}[fn]`;try{C&&console.log(`${b} starting... (I: c2f7bedf95d3f1dd1f76de34a68d3f22)`),c=await n()}catch(p){throw console.error(`${b} ${p.message}`),p}finally{C&&console.log(`${b} unlocking space with scope: ${e} (I: 21034d9c3395499756e9000e40417d22)`),await Qi({space:r,scope:e,instanceId:a}),C&&console.log(`${b} complete. (I: 79d8ac03714a4d429c7e6c2ac6e18d22)`)}return c}catch(c){throw console.error(`${i} ${c.message}`),c}finally{C&&console.log(`${i} complete.`)}}f(Gt,"execInSpaceWithLocking");async function Uo({zeroSpace:r}){let e=`[${Uo.name}]`;try{if(C&&console.log(`${e} starting...`),!r)throw new Error("zeroSpace required. (E: 66fd8f21a5b2b572d18cdeb9472a7722)");let t=mr;C&&console.log(`${e} getting from zeroSpace...`);let o=await r.argy({ibMetadata:Ht({space:r}),argData:{cmd:"get",ibGibAddrs:[t]}}),n=await r.witness(o);if(n?.data?.success&&n.ibGibs?.length===1){let a=n.ibGibs[0];return C&&console.log(`${e} bootstrapibGib found: ${K(a)}`),await wa(a)?a:(C&&console.log(`${e} bootstrapIbGib was invalid. (I: cce66b26805404fc85525d565e1f8b22)`),null)}else return C&&console.log(`${e} bootstrapIbGib NOT found. (I: 421562993bf3464eb507d2967d311e22)`),null}catch(t){throw console.error(`${e} ${t.message}`),t}finally{C&&console.log(`${e} complete.`)}}f(Uo,"getValidatedBootstrapIbGib");async function cf({zeroSpace:r,bootstrapIbGib:e,localSpaceId:t,lock:o,callerInstanceId:n,fnDtoToSpace:a,localSpaceCacheSvc:s}){let i=`[${cf.name}]`;try{if(!r)throw new Error("zeroSpace required. (E: 0793781a98c456a666cfa9eb960bcd22)");if(!e)if(C&&console.log(`${i} bootstrap falsy, so loading it... (I: f2366e38283495a38b5501297aa34422)`),o){let l=mr;C&&console.log(`${i} using locked version of loading bootstrap... (I: 52b9b11999674e586d051c2b23f59b22)`),e=await Gt({space:r,scope:l,fn:f(async()=>{let b=await Uo({zeroSpace:r});if(b)return b;throw new Error("(UNEXPECTED) unable to get bootstrap ibgib? (E: c111dc7627acbfb992134ddf4064ea23)")},"fn"),callerInstanceId:n,secondsValid:ta})}else C&&console.log(`${i} lock is false, so just getting the bootstrap ibgib (I: 49d55e5a824510bb3ee0ccd9f5ec3322)`),e=await Uo({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[_t];let c=e.rel8ns[t][0],d=f(async()=>{let l=await r.argy({ibMetadata:Ht({space:r}),argData:{cmd:"get",ibGibAddrs:[c]}}),b=await r.witness(l);if(b?.data?.success&&b.ibGibs?.length===1){let p=b.ibGibs[0],h=await a(p);return s&&(h.cacheSvc=s),h}else throw new Error(`Could not get local space addr (${c}) specified in bootstrap space (${y({ibGib:e})}). (E: 6d6b45e7eae4472697ddc971438e4922)`)},"fnGet");return o?(C&&console.log(`${i} getting localSpaceId (${t}) WITH locking (I: c48a0e4ac5971cdbc57273dd35f8a522)`),await Gt({space:r,scope:t,fn:f(()=>d(),"fn"),callerInstanceId:n,secondsValid:ta})):(C&&console.log(`${i} getting localSpaceId (${t}) WITHOUT locking (I: 48e504835dee4006839df8820d860b22)`),d())}catch(c){throw console.error(`${i} ${c.message}`),c}}f(cf,"getLocalSpace");async function Zi({space:r,scope:e,secondsValid:t,instanceId:o}){let n=`[${Zi.name}]`;try{if(C&&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 a,s=Ta({space:r,scope:e}),i,c=await te({addr:s,space:r,force:!0});if(c.success&&c.ibGibs?.length===1?(i=c.ibGibs[0],i?.data?.expirationUTC?Wn({expirationTimestampUTC:i.data.expirationUTC})&&(console.warn(`${n} ignoring expired existing lock in space at ${s}. Should be overwritten (W: 7421c5b051724b189f88cecbbd449b22)`),i=void 0):(console.error(`${n} (UNEXPECTED) exisingLock.data.expirationUTC falsy? (E: 218dc0e935534a149d0be153c532cf25)`),i=void 0)):C&&console.log(`${n} existing lock not found for ${s} (I: 191af56ec4e2db3d19084e46bf949222)`),i){if(!i.data)throw new Error("(UNEXPECTED) existingLock.data falsy? (E: 00069b4662e5566d971760d15e293723)");a=H(i),a.data.alreadyLocked=!0,a.data.success=!1}else{let{ib:d,gib:l}=ne({ibGibAddr:s});a={ib:d,gib:l,data:{scope:e,secondsValid:t,instanceId:o,expirationUTC:qn({seconds:t})}};let b=await r.argy({ibMetadata:Ht({space:r}),argData:{cmd:"put",force:!0,ibGibAddrs:[s]},ibGibs:[a]}),p=await r.witness(b);if(p.data?.success)if((p.data.addrsAlreadyHave??[]).includes(s)){C&&console.log(`${n} racelost! addrsAlreadyHave includes spaceLockAddr (${s}) (I: 2e8a1562947c40698110b64251141753)`);let h=await te({addr:s,space:r,force:!0});if(h.success&&h.ibGibs?.length===1){let g=h.ibGibs[0];a=H(g),a.data.alreadyLocked=!0,a.data.success=!1}else{let g=`${n} (UNEXPECTED) addrsAlreadyHave true, but couldn't get lock? (E: 8374a2b6628b49369363bc5843105763)`;console.error(g),a.data.success=!1,a.data.errorMsg=g}}else a.data.success=!0;else{let h=`${n} there was an error putting the lock in the space: ${p.data?.errors?.join("|")}`;a.data.success=!1,a.data.errorMsg=h,console.error(h)}}return a}catch(a){throw console.error(`${n} ${a.message}`),a}finally{C&&console.log(`${n} complete.`)}}f(Zi,"lockSpace");async function Qi({space:r,scope:e,instanceId:t}){let o=`[${Qi.name}]`;try{if(C&&console.log(`${o} starting...`),!r)throw new Error("space required. (E: 5c0a7197a75f483a82d74e5eea60df37)");if(!e)throw new Error("scope required. (E: c7f1dde9570f4df3b450faa2c2f85122)");let n=Ta({space:r,scope:e}),a=await _a({addr:n,space:r,force:!0});if(a.success){let{ib:s,gib:i}=ne({ibGibAddr:n});return{ib:s,gib:i,data:{success:!0,instanceId:t,scope:e}}}else{let s=`Delete lock in space failed. delete errorMsg: ${a.errorMsg}`;if(s.includes("not implemented"))throw new Error(s);if(s.toLowerCase().includes("does not exist")||s.toLowerCase().includes("doesn't exist")||s.toLowerCase().includes("not found")){C&&console.log(`${o} ${s} (I: b647916fd0f3e5366e9387131be21c22)`);let{ib:i,gib:c}=ne({ibGibAddr:n});return{ib:i,gib:c,data:{action:"unlock",success:!0,instanceId:t,scope:e}}}else console.warn(`${o} ${s} (W: 14c84fcac15944bd9a417099964d5d9d)`)}}catch(n){throw console.error(`${o} ${n.message}`),n}finally{C&&console.log(`${o} complete.`)}}f(Qi,"unlockSpace");async function lf({space:r,zeroSpace:e,setSpaceAsDefault:t,createIfNotFound:o}){let n=`[${lf.name}]`;try{if(C&&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 a=r.data.uuid,s=y({ibGib:r}),i=await Uo({zeroSpace:e});if(i){if(C&&console.log(`${n} updating existing bootstrap (I: 977d4aa7ed47bef73b35743c05ce0722)`),i.data.spaceIds.includes(a)){C&&console.log(`${n} space already rel8d to bootstrap, possibly updating its addr (I: b5e2c515ef732d4bbcf02625a9e7c722)`);let l=i.rel8ns[a][0];l===s?C&&console.log(`${n} bootstrap already rel8d to space (I: c1be027b23e7350c64790a631cae2822)`):(C&&console.log(`${n} updating rel8ns[${a}] with newSpaceAddr (${s}). (Old address: ${l})(I: 297a9b0061fd471b8d28a06e04a6ad22)`),i.rel8ns[a]=[s])}else C&&console.log(`${n} new space being rel8d. adding spaceId to data.spaceIds and amending rel8ns (I: 40903d71719aa1d56e498299f5699a22)`),i.data.spaceIds.push(a),i.rel8ns[a]=[s];t&&(C&&console.log(`${n} setting spaceId (${a}) as default space (I: f85eda6c6ad2b0bec9750ce3c7795b22)`),i.data[_t]=a)}else{if(!o){C&&console.log(`${n} bootstrapIbGib not found but createIfNotFound falsy, so returning early. (I: 5c67d85a8599a5ba4a6780f26a66ea22)`);return}C&&console.log(`${n} creating new bootstrap ibgib for spaceId (${a}) with address of (${s}) (I: 651959c27bf2ebc5be1f7f44e2b9e422)`);let{ib:l,gib:b}=ne({ibGibAddr:mr});i=F.primitive({ib:l}),i.gib=b,i.data={[_t]:a,[ui]:[a]},i.rel8ns={[a]:[s]}}if(!i)throw new Error("(UNEXPECTED) bootstrapIbGib still falsy? (E: cf21d7f1756710a66aa0e6a28d762723)");C&&console.log(`${n} saving bootstrapIbGib: ${K(i)} (I: 3cceca0b98dde90e4a58a734be252322)`);let c=await e.argy({ibMetadata:i.ib,argData:{cmd:"put",force:!0,ibGibAddrs:[y({ibGib:i})]},ibGibs:[i]});C&&console.log(`${n} zeroSpace will witness/put... (I: 1be9aca22ffc4951b6690965a7aeae5b)`);let d=await e.witness(c);if(d?.data?.success)C&&console.log(`${n} zero space put complete. (I: ac3056d655e841f1a3c442bcc64942f9)`);else throw new Error(`${d?.data?.errors?.join("|")||"There was a problem with zeroSpace witnessing the bootstrap^gib primitive pointing to the new user space"}`);C&&console.log(`${n} complete.`)}catch(a){throw console.error(`${n} ${a.message}`),a}}f(lf,"updateBootstrapIbGib");function Ht({space:r}){return`${r.ib} ${nt()}`}f(Ht,"getSpaceArgMetadata");function im({space:r}){return`${r.ib} ${nt()}`}f(im,"getSpaceResultMetadata");function df({space:r,spaceData:e,classname:t}){let o=`[${df.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||ni;if(n.includes(" "))throw new Error("invalid space name. cannot contain spaces (E: a8450e1651081412c8ac018520182422)");let a=e?.uuid||void 0;if(!a)throw new Error("invalid space, spaceData.uuid falsy (E: 50ae723a9ab24f4fc7132613e65faf23)");if(a.includes(" "))throw new Error("invalid space id. cannot contain spaces (E: 8696830fe7f54bfa85e670a063f3e089)");let s=e.type??void 0,i=e.subtype??void 0;if(s&&!i)throw new Error(`spaceType (${s}) is set but spaceSubtype is falsy. (E: 878ab960d7987ae2331103b4a00d0d24)`);return`${Ro} ${To} ${t} ${n} ${a} ${s} ${i}`}catch(n){throw console.error(`${o} ${n.message}`),n}}f(df,"getSpaceIb");function ff({ib:r}){let e=`[${ff.name}]`;if(!r){let t=`${e} ib required (E: dd5244f62f964359a86e59bb08ee47e6)`;throw console.error(t),new Error(t)}return r.startsWith(`${Ro} ${To} `)}f(ff,"isSpaceIb");function bf({spaceIb:r}){let e=`[${bf.name}]`;try{if(!r)throw new Error("spaceIb required (E: fa5424cfb7e846e2851562f2f417944f)");let[t,o,n,a,s,i,c]=r.split(" ");if(t!==Ro)throw new Error(`invalid spaceIb (${r}). witnessAtom !== WITNESS_ATOM (E: 5ae1ca12cf8f30ae341f3e582b025224)`);if(o!==To)throw new Error(`invalid spaceIb (${r}). spaceAtom !== SPACE_ATOM (E: 9cc6b6f30e13455eb29748148a94fa0f)`);if(!n)throw new Error(`invalid spaceIb (${r}). spaceClassname falsy (E: 00d3392da007ca8b2840b16b199d9a24)`);if(!a)throw new Error(`invalid spaceIb (${r}). spaceName falsy (E: b957d8e74ef34d889fa64c60c7a5ea0b)`);if(!s)throw new Error(`invalid spaceIb (${r}). spaceId falsy (E: 7a1773722d8e46a0866d683130b65b89)`);let d;if(i&&i!=="undefined")if(ua.includes(i))d=i;else throw new Error(`invalid spaceIb (${r}). spaceType (${i}) is set but not a valid type. valid types: ${ua.join(", ")} (E: 838f4638a88cfbf3545a3a3a38b6dd24)`);let l;if(c&&c!=="undefined")if(ga.includes(c))l=c;else throw new Error(`invalid spaceIb (${r}). spaceSubtype (${c}) is set but not a valid subtype. valid subtypes: ${ga.join(", ")} (E: 5bdcf23027f94e73860e4340313b04ab)`);return{spaceClassname:n,spaceName:a,spaceId:s,spaceType:d,spaceSubtype:l}}catch(t){throw console.error(`${e} ${t.message}`),t}}f(bf,"parseSpaceIb");async function We({ibGibs:r,addrs:e,tjps:t,tjpAddrs:o,space:n}){let a=`[${We.name}]`;try{if(C&&console.log(`${a} 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 s=new Set(o.concat(t.map(d=>y({ibGib:d})))),i=Array.from(s).map(d=>ne({ibGibAddr:d}).gib);r.map(d=>y({ibGib:d})).concat(e).forEach(d=>{let{gib:l}=ne({ibGibAddr:d});i.some(p=>l.includes(p))||s.add(d)}),C&&console.log(`${a}[testing] ${n.data?.name||n.ib} (${n.data?.uuid||"[space.data.uuid falsy]"}) addrsToQuery: ${Array.from(s)} (I: 8a2202912c364238b6d6eb09577bc246)`);let c=await n.argy({ibMetadata:Ht({space:n}),argData:{cmd:"get",cmdModifiers:["latest","addrs"],ibGibAddrs:Array.from(s)}});return await n.witness(c)}catch(s){throw console.error(`${a} ${s.message}`),s}}f(We,"getLatestAddrs");function Ga({ibGib_Context:r}){let e=`[${Ga.name}]`;try{if(C&&console.log(`${e} starting... (I: 5f583fd94d27731a65d514e731b8aa22)`),!no({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{C&&console.log(`${e} complete.`)}}f(Ga,"throwIfContextIsSpecial");async function pf({ibGib_Context:r,rel8nName_Context:e,addr:t,space:o,zeroSpace:n,fnUpdateBootstrap:a,fnBroadcast:s}){let i=`[${pf.name}]`;try{if(C&&console.log(`${i} 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=no({ibGib:r});c&&Ga({ibGib_Context:r});let d=await Xe({src:r,rel8nsToAddByAddr:{[bi]:[t]},rel8nsToRemoveByAddr:{[e]:[t]},dna:!0,nCounter:!0});if(await Ie({resTransform:d,space:o}),c){let l=y({ibGib:d.newIbGib}),b=jo({ib:r.ib}),p=Le({type:b});await je({key:p,addr:l,space:o,zeroSpace:n,fnUpdateBootstrap:a})}await xe({ibGib:d.newIbGib,fnBroadcast:s,space:o})}catch(c){throw console.error(`${i} ${c.message}`),c}finally{C&&console.log(`${i} complete.`)}}f(pf,"trash");async function hf({ibGib_Context:r,rel8nName_Context:e,addr:t,space:o,zeroSpace:n,fnUpdateBootstrap:a,fnBroadcast:s}){let i=`[${hf.name}]`;try{if(C&&console.log(`${i} 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=no({ibGib:r});c&&Ga({ibGib_Context:r});let d=await Xe({src:r,rel8nsToAddByAddr:{[fi]:[t]},rel8nsToRemoveByAddr:{[e]:[t]},dna:!0,nCounter:!0});if(await Ie({resTransform:d,space:o}),c){let l=y({ibGib:d.newIbGib}),b=jo({ib:r.ib}),p=Le({type:b});await je({key:p,addr:l,space:o,zeroSpace:n,fnUpdateBootstrap:a})}await xe({ibGib:d.newIbGib,fnBroadcast:s,space:o})}catch(c){throw console.error(`${i} ${c.message}`),c}finally{C&&console.log(`${i} complete.`)}}f(hf,"archive");function uf(r){let e=`[${uf.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(uf,"spaceNameIsValid");var ke=!1;async function Na({ibGib:r,rel8nNames:e,space:t}){let o=`[${Na.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 a of e){let s=r.rel8ns?.[a]||[];if(s.length>0){let i=await te({addrs:s,space:t});if(i.success&&i.ibGibs?.length===s.length)n[a]=i.ibGibs.concat();else throw new Error(`Problem getting rel8d ibgibs for rel8nName: ${a}. ${i.errorMsg||"Unknown error"} (E: c5e3d4f5a6b7c8d9e0f1a2b3c4d5e6)`)}else n[a]=[]}return n}catch(n){throw console.error(`${o} ${E(n)}`),n}}f(Na,"getRel8dIbGibs");async function mt({parentPrimitiveIb:r,ib:e,ibRegExpPattern:t,data:o,rel8ns:n}){let a=`[${mt.name}]`;try{if(!r)throw new Error("parentPrimitiveIb required. (E: 88ddf188cc5a4340b597abefba1481e2)");if(Rr({ib:r})!==null)throw new Error(`Invalid parentPrimitiveIb: ${r}. (E:5aec0320956d492ebeeaca41eb1fe1c6)`);if(!e)throw new Error("ib required. (E: 7bbc88f4f2e842d6b00126e55b1783e4)");let s=t?new RegExp(t):ri;if(!e.match(s))throw new Error(`invalid ib. does not match regexp (${s})`);let i=Object.keys(n??{}),c=[...ur,"tjp"];if(i.some(p=>c.includes(p)))throw new Error(`Invalid rel8ns. forbiddenRel8nNames: ${c}. rel8ns keys: ${Object.keys(n??{})}. (E: 837a993c265c4362b6aa0b1a234ea5f8)`);let b=(await F.firstGen({ib:e,parentIbGib:F.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 ue({ibGib:{ib:b.ib,data:b.data,rel8ns:b.rel8ns},hasTjp:!1}),b}catch(s){throw console.error(`${a} ${s.message}`),s}}f(mt,"constantIbGib");function Im({addr:r}){return ec({addr:r})}f(Im,"getBinHashAndExt");function ec({addr:r}){let e=`[${ec.name}]`;try{if(!to({addr:r}))throw new Error("not a bin address (E: df0804d129bc4888bd6939cb76c5e0f6)");let{ib:t}=ne({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(ec,"parseBinIb");function to({ibGib:r,addr:e}){let t=`[${to.name}]`;try{if(!r&&!e)throw new Error("either ibGib or addr required. (E: c935b51e773f41a2a547c556e9dc16c6)");if(r&&!r.data)return!1;e=e||y({ibGib:r});let{ib:o,gib:n}=ne({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 a=o.split(" ");if(a.length===2){if(!a[1].match(ve))throw new Error('(UNEXPECTED) ib starts with "bin " but space-delimited !ibPieces[1].match(UUID_REGEXP)? (E: f6baca2ff155f1017b278a5d7597a224)')}else if(a.length===3){if(!a[1].match(ve))throw new Error('(UNEXPECTED) ib starts with "bin " but space-delimited !ibPieces[1].match(UUID_REGEXP)? (E: 8d0443d6cada4b50be79a8390a7a426c)')}else if(a.length===4){if(!a[1].match(ve))throw new Error('(UNEXPECTED) ib starts with "bin " but space-delimited !ibPieces[1].match(UUID_REGEXP)? (E: 3209eacc0a3848a59593d4c3ee956191)');if(!a[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(to,"isBinary");function Ca({type:r}){if(!r.match(ia))throw new Error(`special ibgib type must not have spaces and just be alphanumerics. regexp: ${ia.source} (E: 6c1c92521b7f076cc4666e4915593723)`);return`meta special ${r}`}f(Ca,"getSpecialIbGibIb");function jo({ib:r}){let e=`[${jo.name}]`;try{if(ke&&console.log(`${e} starting... (I: c82ba222bd345ee6b695df4d63a23322)`),!r)throw new Error("ib required (E: 08897145f7138e644fe01c4a59353322)");if(!no({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(Ao).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{ke&&console.log(`${e} complete.`)}}f(jo,"getSpecialTypeFromIb");function gf({type:r}){return`${Ca({type:r})}^${re}`}f(gf,"getSpecialIbGibAddr");function Le({type:r}){return`${hi} ${gf({type:r})}`}f(Le,"getSpecialConfigKey");function no({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(no,"isSpecial");function va(r){let e=`[${va.name}]`;if(!r)throw new Error(`${e} text required.`);return`root ${r}`}f(va,"getRootIb");function Er(r){let e=`[${Er.name}]`;if(!r)throw new Error(`${e} tag required.`);return`tag ${r}`}f(Er,"tagTextToIb");function vt({ibGibs:r,filterPrimitives:e}){let t=`[${vt.name}]`;try{let o={},n={},a={};return(e?r.filter(i=>i.gib??i.gib!==re):r).forEach(i=>{tc({ibGib:i})?(i.rel8ns?.dna??[]).length>0?o[i.gib]=i:n[i.gib]=i:a[i.gib]=i}),{mapWithTjp_YesDna:o,mapWithTjp_NoDna:n,mapWithoutTjps:a}}catch(o){throw console.error(`${t} ${o.message}`),o}}f(vt,"splitPerTjpAndOrDna");function bt({ibGibs:r}){let e=`[${bt.name}]`;try{ke&&console.log(`${e} starting...`);let{mapWithTjp_YesDna:t,mapWithTjp_NoDna:o}=vt({ibGibs:r,filterPrimitives:!0}),n={...t,...o},a=Object.values(n),s=Xn({items:a,keyFn:f(i=>i.data?.isTjp?y({ibGib:i}):i.rel8ns?.tjp?i.rel8ns?.tjp[0]??"":(ke&&console.log(`${e} neither isTjp nor x.rel8ns.tjp truthy (I: ec9a5597bf53dec1bd3d83350abbf823)`),""),"keyFn")});return ke&&console.log(`${e} sorting (ascending) ibGibsWithTjpGroupedByTjpAddr: ${K(s)} (I: 9b9fff5ce61444a6cb06d62db9a99422)`),Object.entries(s).forEach(([i,c])=>{c.some(d=>d.data?.n===void 0)&&console.warn(`${e} timeline includes ibgibs with ibGib.data?.n === undefined (W: cab9a6b64a38c4279fe82c3569bbab22)`),c.sort((d,l)=>(d.data?.n??-1)>(l.data?.n??-1)?1:-1)}),ke&&console.log(`${e} after sort ibGibsWithTjpGroupedByTjpAddr: ${K(s)} (I: 9b9fff5ce61444a6cb06d62db9a99422)`),s}catch(t){throw console.error(`${e} ${t.message}`),t}finally{ke&&console.log(`${e} complete.`)}}f(bt,"getTimelinesGroupedByTjp");function tc({ibGib:r}){let e=`[${tc.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(St)?!0:r.gib===re?!1:!!Pe({ibGibAddr:y({ibGib:r})}).tjpGib:(console.warn(`${e} ibGib.gib falsy. (W: 6400d780822b44d992846f1196509be3)`),!1)}f(tc,"hasTjp");function de({ibGib:r,defaultIfNone:e="undefined"}){let t=`[${de.name}]`;try{let o=rc({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(de,"getTjpAddr");function rc({ibGibs:r,defaultIfNone:e="undefined"}){let t=`[${rc.name}]`;try{let o={};return r.forEach(n=>{let a=y({ibGib:n}),s;n.rel8ns?.tjp?.length??!1?s=n.rel8ns.tjp[n.rel8ns.tjp.length-1]:n.data?.isTjp||e==="incomingAddr"?s=a:s=void 0,o[a]=s}),o}catch(o){throw console.error(`${t} ${o.message}`),o}}f(rc,"getTjpAddrs");async function Oa({ibGib:r,naive:e=!0}){let t=`[${Oa.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):(ke&&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(Oa,"isTjp_Naive");function Ye({ibGib:r}){let e=`[${Ye.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&&(to({ibGib:r})?t.data=r.data.slice():t.data=H(r.data)),r.rel8ns&&(t.rel8ns=H(r.rel8ns)),t}f(Ye,"toDto");function ao(r){let e=`[${ao.name}]`;try{return ke&&console.log(`${e} starting... (I: 57aef93fc6cc2309523b5c72a6b11823)`),!!r&&typeof r.ib=="string"}catch(t){throw console.error(`${e} ${t.message}`),t}finally{ke&&console.log(`${e} complete.`)}}f(ao,"isIbGib");function Qt({ibGib:r,data:e,timestamp:t}){let o=`[${Qt.name}]`;try{ke&&console.log(`${o} starting... (I: 35cb68744bcf6139d78e37de644fad23)`),t=t||e?.timestamp||r?.data?.timestamp;let n=r?.data?.timestampMs||e?.timestampMs;if(!t){let a=`${o} timestamp is falsy. (W: 5f1f1182c8804807b886a3d922ac3dcf)`;return console.warn(a),{valid:!1,emsg:a}}if(typeof t=="string")if(Number.isInteger(Number.parseInt(t))){let a=Number.parseInt(t),s=new Date;if(s.setTime(a),s.toString()!==Go)return ke&&console.log(`${o} valid timestampInTicks string (I: 7069a1c3047f3bbc92b78674b20f5b23)`),{valid:!0,date:s,utc:s.toUTCString(),ticks:s.getTime().toString(),ms:n};{let i=`${o} data.timestamp (${t}) is an integer string but not a valid timestampInTicks string. (produces invalid date) (E: f49fbb600fe1426c8805dfc8afbe5cf3)`;return console.error(i),{valid:!1,emsg:i}}}else{let a=new Date(t);if(a.toString()!==Go)return{valid:!0,date:a,utc:a.toUTCString(),ticks:a.getTime().toString(),ms:n};{let s=`${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(s),{valid:!1,emsg:s}}}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 a=new Date;if(a.setTime(t),a.toString()!==Go)return{valid:!0,date:a,utc:a.toUTCString(),ticks:a.getTime().toString(),ms:n};{let s=`${o} timestamp (${t}) is an integer number but not a valid timestampInTicks (new date setTime produces invalid date). (W: c6c90f7f3bfb49838d2081ba84fdb5fb)`;return console.warn(s),{valid:!1,emsg:s}}}else{let a=`${o} timestamp (${t}) is a non-integer number (supposed to be a string either timestamp string or ticks). (E: 2963d95f8d3b464c992b0bff948b4479)`;return console.error(a),{valid:!1,emsg:a}}else{let a=`${o} unknown typeof timestamp (${typeof t}). (E: 12458a9c16c84e4f859b5771a30dd2ef)`;return console.error(a),{valid:!1,emsg:a}}}catch(n){throw console.error(`${o} ${E(n)}`),n}finally{ke&&console.log(`${o} complete.`)}}f(Qt,"getTimestampInfo");async function it({addrs:r,readCache_graph:e,readCache_array:t,space:o}){let n=`[${it.name}]`;try{ke&&console.log(`${n} starting... (I: 5db66871239dfa05182277f886a20926)`),e??={},t??=[];let a={...e};t.forEach(d=>a[y({ibGib:d})]=d);let s=Object.keys(e),i=r.filter(d=>!s.includes(d));if(i.length>0){ke&&console.log(`${n} ${i.length} addrsNotFoundInCache: ${i} (I: fccbd18116ffb849f813aaebfc6c0826)`);let d=[o],l=i.concat();for(let b of d){let p=await te({addrs:l,space:b});if(p.success&&p.ibGibs&&p.ibGibs.length===l.length)p.ibGibs.forEach(h=>a[y({ibGib:h})]=h),l=[];else if(p.ibGibs&&p.ibGibs.length>0){if(l=l.filter(h=>!p.ibGibs.some(g=>y({ibGib:g})===h)),l.length===0)break}else ke&&console.log(`${n} no addrs found in space (${b.ib}). trying next space. (I: 4f99d8bacbb10ab3f8737a752564b326)`)}if(l.length>0)throw new Error(`could not get all addrs from cache or spaces. addrsStillNotFound: ${l}. spaces: ${d.map(b=>b.ib).join("|")} (E: 0c6418f83dd85bda886e56f5b98f3126)`)}let c=[];for(let d of r){let l=a[d];if(!l)throw new Error(`(UNEXPECTED) allIbGibs_graph doesn't have addr? We're expecting logic to preclude this at this point. addr: ${d} (E: f68e1d236ae5e3eb08da9933c8230626)`);c.push(l)}return c}catch(a){throw console.error(`${n} ${E(a)}`),a}finally{ke&&console.log(`${n} complete.`)}}f(it,"getIbGibsFromCache_fallbackToSpaces");var so=!1,mf="space_gib_db",Ef="space_gib_store",wf="space_gib_api_key";var yf="agent";var Gm=Er(yf);var Cm={dbName:mf,storeName:Ef,additionalStoreNames:[oi],apiKeyName:wf};var oc="0.0.5";var er=!1,xm="[web^gib timer]",xa="ibgib";var $f="agent",Lm="body-outline",Dm="This tag tracks the active agents for the current local user space.",Pm=Er($f),nc="#78f87e88",ac="#78f87e10",sc="#ffffff";var Rm="AUTOMATED_TEXT";var Et=!1;function ic(r){return new Promise((e,t)=>{let o=new Blob([r],{type:"application/octet-stream"}),n=new FileReader;n.onload=()=>{let s=n.result.split(",")[1];e(s)},n.onerror=a=>t(a),n.readAsDataURL(o)})}f(ic,"uint8ArrayToBase64");async function cc(r){let e=`data:application/octet-stream;base64,${r}`,n=await(await(await fetch(e)).blob()).arrayBuffer();return new Uint8Array(n)}f(cc,"base64ToUint8Array");async function Vo({graph:r}){let e=`[${Vo.name}]`;try{Et&&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 ic(r[n].data)});let o=JSON.stringify(t);return Et&&console.log(`${e} jsonString.length: ${o.length} (I: 56dec8ad0931ab8ba9b5ca3d4e66be25)`),o}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Et&&console.log(`${e} complete.`)}}f(Vo,"serializeGraphToString");async function Ho({jsonString:r}){let e=`[${Ho.name}]`;try{Et&&console.log(`${e} starting... (I: 52e1a1fb1adcc75168fbc6d819868825)`);let o=JSON.parse(r,f((n,a)=>(a&&a._dataType==="Uint8Array_Base64",a),"reviver"));for(let n in o){let a=o[n].data;a&&a._dataType==="Uint8Array_Base64"&&(o[n].data=await cc(a.value))}return o}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Et&&console.log(`${e} complete.`)}}f(Ho,"deserializeStringToGraph");async function lc(r){let e=`[${lc.name}]`;try{Et&&console.log(`${e} starting... (I: 8d306868b718596fe8f562bd5118d825)`);let t=await Vo({graph:r}),o=new TextEncoder().encode(t),a=new Response(o).body.pipeThrough(new CompressionStream("gzip"));return await new Response(a).blob()}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Et&&console.log(`${e} complete.`)}}f(lc,"compressIbGibToBlob");async function If(r){let e=r.stream().pipeThrough(new DecompressionStream("gzip")),t=await new Response(e).text();return await Ho({jsonString:t})}f(If,"decompressIbGibFromBlob");async function La({graph:r}){let e=`[${La.name}]`;try{Et&&console.log(`${e} starting... (I: 1352f8540c08f0b725952df8f18c4825)`);let o=await(await lc(r)).arrayBuffer(),n=new Uint8Array(o);return await ic(n)}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Et&&console.log(`${e} complete.`)}}f(La,"compressIbGibGraphToString");async function Da({compressedBase64:r}){let e=`[${Da.name}]`;try{Et&&console.log(`${e} starting... (I: 5f3fa940a2c8f8d7b877978ae7f87825)`);let t=await cc(r),o=new Blob([t],{type:"application/gzip"});return await If(o)}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Et&&console.log(`${e} complete.`)}}f(Da,"decompressIbGibGraphFromString");var dc="export";var io=!1;function fc({data:r}){let e=`[${fc.name}]`;try{io&&console.log(`${e} starting... (I: 158dfaeb9613a1531be71a9735184624)`);let{graphSize:t,dependencyGraphAsString:o,timestamp:n}=r,a=o.length,s=nt(n),i=r.compression==="gzip"?"gzip":"raw";if(!r.timestamp)throw new Error("(UNEXPECTED) data.timestamp falsy? (E: 2f5bc88488cbf260634239a8a8396825)");let c=new Date(r.timestamp),{ib:d,gib:l}=ne({ibGibAddr:r.contextIbGibAddr}),p=Pe({gib:l}).tjpGib??l,h=c.toISOString().slice(0,19).replace("T","_").replace(/:/g,"").replace(/ /g,"_");return`${dc} ${h} ${i} ${t} ${a} ${p}`}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{io&&console.log(`${e} complete.`)}}f(fc,"getRawExportIb");async function Pa({ibGib:r,metaspace:e,space:t,compress:o,live:n,ignoreErrors:a}){let s=`[${Pa.name}]`;try{if(io&&console.log(`${s} starting... (I: 0b6ba8608ba8bde0682a0936b9a01825)`),!r)throw new Error("(UNEXPECTED) ibGib falsy? (E: d2898eea744360865f0da5fb91baae22)");let i=y({ibGib:r}),c=[],d=await ge({ibGib:r})??[];if(d.length>0){let S=`ibGib had validation errors: ${d} (E: 84890bbc0598192498178a98ae299825)`;if(a)c.push({errorMsg:S,ibGibAddr:i});else throw new Error(S)}let l=await e.getDependencyGraph({ibGib:r,live:n,space:t}),b=o?await La({graph:l}):await Vo({graph:l}),p=de({ibGib:r,defaultIfNone:"incomingAddr"})??i,h=new Date,g={contextIbGibAddr:i,tjpAddr:p,dependencyGraphAsString:b,graphSize:Object.keys(l).length,timestamp:oe(h),timestampMs:h.getMilliseconds()};o&&(g.compression="gzip");let m={ib:fc({data:g}),data:g},w=await ue({ibGib:m,hasTjp:!1});return m.gib=w,console.log(`${s} JSON.stringify(exportIbGib).length: ${JSON.stringify(m).length} (I: db3a8d913a91d8fc5d6e45981e034822)`),{rawExportIbGib:m,manifest:Object.keys(l),errors:c.length>0?c:void 0}}catch(i){throw console.error(`${s} ${E(i)}`),i}finally{io&&console.log(`${s} complete.`)}}f(Pa,"getRawExportIbGib");var Qm="ibgib-shell-ready",eE="ibgib-ui-busy",tE="ibgib-ui-message",rE="ibgib-identity-request-change",oE="ibgib-identity-changed";var bc=er;async function Ur({title:r,msg:e,prompt:t,showInput:o,defaultValue:n,okButtonTitle:a,cancelButtonTitle:s,isPassword:i,isBusy:c,animationEmoji:d}){let l=`[${Ur.name}]`;try{bc&&console.log(`${l} starting... (I: 037b228a2568181cd3eb25dba4e03225)`);let b=document.getElementById("fullscreen-dialog"),p=document.getElementById("fullscreen-dialog-body"),h=document.getElementById("fullscreen-dialog-title"),g=document.getElementById("fullscreen-dialog-message"),m=document.getElementById("fullscreen-dialog-prompt-input"),w=document.getElementById("fullscreen-dialog-ok-button"),S=document.getElementById("fullscreen-dialog-cancel-button");if(!b||!p||!h||!g||!m||!w||!S)throw new Error("(UNEXPECTED) One or more dialog elements not found in DOM (E: 578e37c0271cc57a99e95e780ad18a25)");if(h.textContent=r||"",[...g.childNodes].forEach($=>g.removeChild($)),(e||"").split(`
9
+ `).forEach($=>{let T=document.createElement("p");T.textContent=$,g.appendChild(T)}),d){let $=document.createElement("div");$.id="fullscreen-dialog-animation-emoji",$.textContent=d,$.style.fontSize="3.5rem",$.style.textAlign="center",$.style.margin="1.5rem 0",$.style.animation="spin-bounce 5s infinite ease-in-out",g.appendChild($)}m.classList.remove("collapsed"),S.classList.remove("collapsed"),S.style.display="inline-block",w.style.display="inline-block",w.textContent=a||"OK";let I=f($=>{($.key==="Enter"||$.key===`
10
+ `)&&$.ctrlKey&&w.click()},"onKeypress");return c?(m.classList.add("collapsed"),S.style.display="none",w.style.display="none"):t||o?(m.addEventListener("keypress",I),o?(m.autofocus=!0,m.value=n??"",m.addEventListener("keypress",$=>{$.key==="Enter"&&w.click()}),i?(m.type="password",m.autocomplete="off",m.required=!0):(m.type="text",m.autocomplete="on",m.required=!1,m.attributes["auto-complete"]="on")):(m.autofocus=!1,m.classList.add("collapsed")),S.textContent=s||"Cancel"):(m.classList.add("collapsed"),S.style.display="none"),new Promise($=>{if(c){let N=f(P=>{P.preventDefault()},"onCancelEvent");b.addEventListener("cancel",N);let D=f(()=>{b.removeEventListener("cancel",N),b.close()},"close"),B=f(({title:P,msg:k,animationEmoji:M})=>{if(P!==void 0&&(h.textContent=P),k!==void 0){[...g.childNodes].forEach(ee=>{ee.id!=="fullscreen-dialog-animation-emoji"&&g.removeChild(ee)});let j=k.split(`
11
+ `),Q=document.getElementById("fullscreen-dialog-animation-emoji");j.forEach(ee=>{let Ge=document.createElement("p");Ge.textContent=ee,Q?g.insertBefore(Ge,Q):g.appendChild(Ge)})}if(M!==void 0){let j=document.getElementById("fullscreen-dialog-animation-emoji");M?(j||(j=document.createElement("div"),j.id="fullscreen-dialog-animation-emoji",j.style.fontSize="3.5rem",j.style.textAlign="center",j.style.margin="1.5rem 0",j.style.animation="spin-bounce 5s infinite ease-in-out",g.appendChild(j)),j.textContent=M):j&&j.remove()}},"update");b.open||b.showModal(),Oe(1e3).then(()=>{p.scrollTo({top:0,behavior:"smooth"})}),$({close:D,update:B});return}let T=f(()=>{(t||o)&&m.removeEventListener("keypress",I),w.removeEventListener("click",_),S.removeEventListener("click",G),b.removeEventListener("close",v)},"removeEventListeners"),_=f(()=>{T();let N=o?m.value??"":"true";m&&(m.value=""),b.close(N),$(N)},"onOK"),G=f(()=>{T(),m&&(m.value=""),b.close(void 0),$(void 0)},"onCancel"),v=f(()=>{T(),m&&(m.value=""),b.close(void 0),$(void 0)},"onClose");w.addEventListener("click",_),S.addEventListener("click",G),b.addEventListener("close",v),b.open||b.showModal(),Oe(1e3).then(()=>{p.scrollTo({top:0,behavior:"smooth"})})})}catch(b){throw console.error(`${l} ${E(b)}`),b}finally{bc&&console.log(`${l} complete.`)}}f(Ur,"showFullscreenDialog");var Re=er;async function Sf({metaspace:r,space:e}){let t=`[${Sf.name}]`;try{Re&&console.log(`${t} starting... (I: 2ccb79537a75e7896bace84e6c710d25)`);let o=await r.getSpecialIbGib({type:Ao.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{Re&&console.log(`${t} complete.`)}}f(Sf,"getTagsIbGib");function ka({scope:r,ibGib:e,ibGibAddr:t,defaultNameIfError:o}){let n=`[${ka.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 a,s,i;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&&y({ibGib:e})!==t)throw new Error("(UNEXPECTED) both ibGib and ibGibAddr provided, but addr of ibGib doesn't equal ibGibAddr? (E: genuuid)");let l=e.rel8ns.ancestor.filter(p=>$e({gib:ne({ibGibAddr:p}).gib}));if(l.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=l.at(-1);a=ne({ibGibAddr:b}).ib,i=a}t??=y({ibGib:e});let{ib:c}=ne({ibGibAddr:t});if(s=c.split(" ").at(0)??"",s=s.replace(/\W/g,"_"),a??=s,a=a.replace(/\W/g,"_"),!a&&!s)throw new Error("(UNEXPECTED) both primitiveAncestorIb and atom falsy? one should be truthy at this point. (E: genuuid)");i=s.toLowerCase(),Re&&console.log(`${n} ancestorIbOrAtom: ${i} (I: genuuid)`);let d=`${i}_${r}index`;return Re&&console.log(`${n} indexName: ${d} (I: genuuid)`),d}catch(a){if(o)return console.warn(`${n} error happened but defaultNameIfError (${o}) provided. So will return this value. error that was thrown: ${E(a)}`),o;throw console.error(`${n} ${E(a)}`),a}}f(ka,"getIndexNameFromIbGib");async function _f({scope:r,ibGib:e,metaspace:t,space:o,skipGetLatest:n}){let a=`[${_f.name}]`;try{if(Re&&console.log(`${a} 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 s=ka({scope:r,ibGib:e}),i=de({ibGib:e,defaultIfNone:"incomingAddr"}),c=f(async()=>{let l=await t.getSpecialIbGib({type:s,space:o,initialize:!1,dontWarnIfNotExist:!0,lock:!0});if(!l||!l.data){Re&&console.log(`${a} special ${r} index ibGib not found for indexSpecialIbGibType (${s}). No coupled ibgib registered, returning undefined. (I: genuuid)`);return}let p=(l.data.coupleMap??l.data.agentMap??{})[i];if(!p){Re&&console.log(`${a} No coupled ${r} ibgib address found for domain ${i} in the coupled index map. indexSpecialIbGibType: ${s}. returning undefined. (I: genuuid)`);return}let h=n?p:await t.getLatestAddr({addr:p,space:o})??p,g=await t.get({addrs:[h],space:o});if(g.errorMsg||(g.ibGibs??[]).length!==1)throw new Error(`couldn't get latest coupled ibgib (${h}) for domain ${i}. (E: 8aa7b25f5cd4ebadd8bf2f8807dfe825)`);return g.ibGibs[0]},"fn");return await Gt({scope:s,secondsValid:180,maxDelayMs:100,maxLockAttempts:1800,space:o,callerInstanceId:a+nt(),fn:c})}catch(s){throw console.error(`${a} ${E(s)}`),s}finally{Re&&console.log(`${a} complete.`)}}f(_f,"getLocalCoupledIbGibForDomainIbGib");async function Af({scope:r,domainIbGib:e,localIbGib:t,metaspace:o,space:n}){let a=`[${Af.name}]`;try{Re&&console.log(`${a} starting... (I: 217ae68e0c820e48f4c00409f7f14325)`);let s=ka({scope:r,ibGib:e}),i=de({ibGib:e}),c=y({ibGib:t});if(!i)throw new Error(`${a} Could not get TJP address for domain ibGib. (E: 35a4e8ac291b0b85cb958e28dd812f25)`);if(!c)throw new Error(`${a} Could not get address for agent ibGib. (E: 2fce1187630b45934c4155a23204d125)`);await Gt({scope:s,secondsValid:60,maxDelayMs:100,maxLockAttempts:600,space:n,fn:f(async()=>{let l=await o.getSpecialIbGib({type:s,space:n,initialize:!0,dontWarnIfNotExist:!0,lock:!1});if(!l)throw new Error(`${a} Could not get or create agent index ibGib.`);if(!l.data)throw new Error("(UNEXPECTED) agentSpecialIndex.data falsy? (E: 74299eed147debf6398ca37e7b8d5c25)");let b=l.data.coupleMap??l.data.agentMap,p=b?H(b):{},h=p[i];if(h)if(h===c){Re&&console.log(`${a} domain ibGib (${i}) already mapped to agent (${c}). returning early (I: cb5d4dcef8cf14de7336120fb8ffef25)`);return}else console.warn(`${a} domainTjpAddr (${i}) already assigned to existingMappedAgentAddr (${h}). We will be changing to new localAddr (${c}). (W: eb993e33f7731e570fa76f24a2d80625)`);p[i]=c;let g=await at({src:l,dataToAddOrPatch:{coupleMap:p},dna:!1,linkedRel8ns:[Ee.past],nCounter:!0}),m=g.newIbGib;await Ie({resTransform:g,space:n});let w=Le({type:s});await o.setConfigAddr({key:w,addr:y({ibGib:m}),space:n}),await o.registerNewIbGib({ibGib:m,space:n})},"fn")}),Re&&console.log(`${a} Registered domain ${i} with agent ${c}`)}catch(s){throw console.error(`${a} ${E(s)}`),s}finally{Re&&console.log(`${a} complete.`)}}f(Af,"coupleDomainIbGibWithLocalIbGibViaIndex");function wr(){let r=`[${wr.name}]`;try{Re&&console.log(`${r} starting... (I: 890f53e984d69461d9f4ded8741fcc25)`);let e=globalThis[xa];return e||(console.log(`${r} initializing globalThis.${xa}... (I: 9d9ff1813448d9a1b82b0e5790a74825)`),e={}),e}catch(e){throw console.error(`${r} ${E(e)}`),e}finally{Re&&console.log(`${r} complete.`)}}f(wr,"getIbGibGlobalThis_IbGib");async function V({delayIntervalMs:r=50}={delayIntervalMs:50}){let e=`[${V.name}]`;try{Re&&console.log(`${e} starting... (I: 4acc22d08dd1100503f9b0423f302925)`);let t;for(;!t;)wr().metaspace&&(t=wr().metaspace),t||(console.log(`${e} metaspace still not initialized. delayIntervalMs: ${r} until next retry... (I: 490f77ac4ded1d7d3c0340e460404125)`),await Oe(r));return t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Re&&console.log(`${e} complete.`)}}f(V,"getGlobalMetaspace_waitIfNeeded");function Tf({ibGibAddr:r,gib:e,ibGib:t,translucentAlpha:o=10}){let n=`[${Tf.name}]`;try{Re&&console.log(`${n} starting... (I: 3b70af42d1c4f6ae91870f3a15c6c625)`),!r&&!e&&!t&&(e=re),e??=t?.gib??ne({ibGibAddr:r}).gib;let a=Pe({gib:e});o??=10;let s="";if(a.isPrimitive)return{gib:e,gibInfo:a,punctiliarColor:nc,punctiliarColorTranslucent:ac,punctiliarColorContrast:sc};s=a.tjpGib??a.punctiliarHash??e;let[i,c,d]=pc(o,a.punctiliarHash??e),[l,b,p]=a.tjpGib?pc(o,a.tjpGib):[void 0,void 0,void 0];return{gib:e,gibInfo:a,punctiliarColor:i,punctiliarColorTranslucent:c,punctiliarColorContrast:d,tjpColor:l,tjpColorTranslucent:b,tjpColorContrast:p}}catch(a){let s=`${n} ${E(a)}`;return console.error(s),{gib:e??re,gibInfo:{isPrimitive:!0},punctiliarColor:"#ff0000",punctiliarColorTranslucent:"#ff000010",punctiliarColorContrast:"#ffffff",errorMsg:s}}finally{Re&&console.log(`${n} complete.`)}}f(Tf,"getDeterministicColorInfo");function Gf(r,e,t){t/=100;let o=e*Math.min(t,1-t)/100,n=f(a=>{let s=(a+r/30)%12,i=t-o*Math.max(Math.min(s-3,9-s,1),-1);return Math.round(255*i).toString(16).padStart(2,"0")},"f");return`#${n(0)}${n(8)}${n(4)}`}f(Gf,"hslToHex");function pc(r,e){let o=(parseInt(e.substring(0,8),16)||0)%360,n=Gf(o,65,62),a=parseInt(n.substring(1,3),16),s=parseInt(n.substring(3,5),16),i=parseInt(n.substring(5,7),16),d=(a*299+s*587+i*114)/1e3>=128?"#11111b":"#ffffff",l=Math.min(100,Math.max(0,r)),b=Math.round(l/100*255).toString(16).padStart(2,"0"),p=`${n}${b}`;return[n,p,d]}f(pc,"getColorStrings");var Ze=er;function uc(r){return new TextDecoder().decode(r)}f(uc,"uint8ArrayToString");var hc=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 a=e[n];a===".."?o=o.split("/").slice(0,-1).join("/"):(a.startsWith("/")&&(a=a.slice(1)),a.endsWith("/")&&(a=a.slice(0,-1)),o+=(n>0?"/":"")+a)}return o}dirname(e){return e.split("/").slice(0,-1).join("/")}basename(e,t){return e.split("/").pop()??""}};async function Cf({msg:r,title:e,confirm:t,noNewLine:o,rl:n,defaultValue:a,dontCloseRl:s,cancelable:i}){let c=`[${Cf.name}]`;try{if(!r)throw new Error("msg required (E: 7f4d67bca4cf98ea95fa110aabc98924)");let d,l=0,b=5;do{if(l++,l>=b)throw new Error("max attempts reached (E: 1ef20ae955622d4b39479f3da91a1d25)");await Oe(50),d=await Ur({title:e||"Prompt for Info",msg:r,prompt:!0,showInput:!0,isPassword:!1,defaultValue:a})}while(d===void 0&&!i);return d??""}catch(d){debugger;throw console.error(`${c} ${E(d)}`),d}}f(Cf,"promptForText");async function vf({msg:r,confirm:e}){let t=`[${vf.name}]`;try{Ze&&console.log(`${t} starting... (I: 795a4ce348ddb9a5119770f4c572ac24)`);let o,n=!0,a=0,s=5;do{if(a++,a>=s)throw new Error("max attempts reached (E: d4166b4bf37aff0c6d44567792e9ad25)");if(await Oe(50),o=await Ur({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 Oe(250);let i=await Ur({title:"Shh...",msg:"Confirm...",prompt:!0,showInput:!0,isPassword:!0,defaultValue:void 0});i===void 0&&(o=void 0),o!==i&&(o=void 0,n=!1,await Oe(250))}}while(o===void 0);return o}catch(o){throw console.error(`${t} ${E(o)}`),o}finally{Ze&&console.log(`${t} complete.`)}}f(vf,"promptForSecret");async function Of({msg:r,title:e,skipHitEnterToContinue:t}){let o=`[${Of.name}]`;try{if(!r)throw new Error("msg required (E: ffcf7dd00324df7cea2792223d229524)");try{e??="",await Oe(50),await Ur({title:e,msg:r})}catch(n){throw n}}catch(n){throw console.error(`${o} ${E(n)}`),n}}f(Of,"alertUser");async function Nf({exportIbGibJsonString:r,metaspace:e}){let t=`[${Nf.name}]`;try{debugger;if(Ze&&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,a;try{n=JSON.parse(r)}catch(d){let l=`Error during parse JSON. error: ${E(d)} (E: genuuid)`,b=new Error(l);throw b.cause=d,b}try{let d=await ge({ibGib:n})??[];if(d.length>0)throw new Error(`validation errors when validating the parsed ibgib that should be a RawExportIbGib_V1: ${d} (E: 8ba178d3b26e8eca28a67c182fe16825)`);if(a=n,!a.data)throw new Error("(UNEXPECTED) rawExportIbGib.data falsy? (E: ef1824d1cca5584ab8e34288346e9825)")}catch(d){let l=`Error during parse JSON. error: ${E(d)} (E: genuuid)`,b=new Error(l);throw b.cause=d,b}let s;if(a.data.compression)switch(a.data.compression){case"gzip":s=await Da({compressedBase64:a.data.dependencyGraphAsString});break;default:throw new Error(`unknown value of rawExportIbGib.data.compression: ${a.data.compression} (E: 784672fae568312d887ddbb841199925)`)}else s=await Ho({jsonString:a.data.dependencyGraphAsString});let i={};for(let[d,l]of Object.entries(s)){let b=await ge({ibGib:l})??[];b.length>0&&(i[d]=b)}if(Object.keys(i).length>0)throw new Error(`there were validation errors for the RawExportIbGib_V1.data payload (contained in data.dependencyGraphAsString). Here is the validationErrorMap:
12
+ ${K({validationErrorMap:i})} (E: e63f38b182a84122d83a55befb369825)`);return[a,s]}catch(o){throw console.error(`${t} ${E(o)}`),o}finally{Ze&&console.log(`${t} complete.`)}}f(Nf,"getRawExportIbGibAndGraphFromJsonString");async function xf({ibGib:r,compress:e,metaspace:t,space:o}){let n=`[${xf.name}]`;try{if(Ze&&console.log(`${n} starting... (I: 623d9463d919683be81f749821a95825)`),$e({ibGib:r}))throw new Error("ibGib is primitive. Can't export primitive. (E: dd42c42e9fda0707e81c692af1a2a225)");let a=await Pa({ibGib:r,live:!0,compress:e,metaspace:t,space:o}),{rawExportIbGib:s,errors:i}=a;if((i??[]).length>0)throw new Error(`Export had errors: ${i} (E: 05faf83f25d3449ab809dfd24eeaf825)`);let c=JSON.stringify(s),d="data:text/json;charset=utf-8,"+encodeURIComponent(c),b=`${y({ibGib:s})}.json`,p=document.createElement("a");p.setAttribute("style","none"),p.setAttribute("href",d),p.setAttribute("download",b);let h=document.getElementsByTagName("div")[0];h.appendChild(p),p.click(),h.removeChild(p)}catch(a){throw console.error(`${n} ${E(a)}`),a}finally{Ze&&console.log(`${n} complete.`)}}f(xf,"exportIbGib");function Lf(){let r=`[${Lf.name}]`;try{Ze&&console.log(`${r} starting... (I: 62a29f9982b4b5ecd91ff58ca4dd6825)`);let e=wr();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{Ze&&console.log(`${r} complete.`)}}f(Lf,"getGlobalStoreName");function Df(){let r=`[${Df.name}]`;try{Ze&&console.log(`${r} starting... (I: 8c8f08728fc7384f87697377358cc825)`);let e=wr();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{Ze&&console.log(`${r} complete.`)}}f(Df,"getGlobalDbName");function Pf(){let r=`[${Pf.name}]`;try{Ze&&console.log(`${r} starting... (I: 59a2510a85051f97ed15fbc8825b6825)`);let e=wr();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{Ze&&console.log(`${r} complete.`)}}f(Pf,"getGlobalIndexedDbKey_APIKey");async function Ba({infos:r}){let e=`[${Ba.name}]`;try{Ze&&console.log(`${e} starting... (I: 4d41880fb748ee2302a624a255665825)`);for(let t of r){let{dbName:o,storeNames:n}=t;await Ma({dbName:o})||await Xo({dbName:o});for(let s of n)await Ua({dbName:o,storeName:s})}}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Ze&&console.log(`${e} complete.`)}}f(Ba,"initAppStorage");var Qe=er,gc=0;async function Xo({dbName:r,storeName:e,version:t,logalot:o=!1}){let n=`[${Xo.name}][${r}][${e??"no store name"}]`,a=crypto.randomUUID();o&&console.time(n+a);let s;try{o&&console.log(`${n} starting... (I: f35d4e1ba37252f14c8532fb861b1125)`),await new Promise((c,d)=>{try{o&&console.log(`${n} starting... (I: 0aeddd9376daa0a044677ce4cf8a4c24)`),o&&console.timeLog(n+a,"opening... (I: e748b4ddb445d77cb10a7ba158b49125)");let l=indexedDB.open(r,t);gc++,console.log(`${n} initRequestCount: ${gc} (I: 294d5f0b12ffe5512bacebe891824d25)`);let b;l.onupgradeneeded=p=>{try{s=p.target.result,o&&console.timeLog(n+a,"onupgradeneeded... (I: e748b4ddb445d77cb10a7ba158b49125)"),e&&(s.objectStoreNames.contains(e)?b=!0:(b=!1,s.createObjectStore(e,{keyPath:"key"})))}catch(h){console.error(`${n}[openDBRequest.onupgradeneeded] ${E(h)} (E: 4a5fa1b0850be47e28bee653da287325)`),d(h)}},l.onblocked=p=>{console.log(`${n}[openDBRequest.onblocked] openDBRequest blocked...time wasted a bit here. version change event (old -> new): ${p.oldVersion} -> ${p.newVersion} (I: 9074ebf4afdba54d6f9d41b360b96a25)`),console.dir(p)},l.onsuccess=p=>{try{o&&console.log("init success (I: 297a5a71e405a0b56413af813f248d24)"),o&&console.timeLog(n+a,"onupgradeneeded... (I: e748b4ddb445d77cb10a7ba158b49125)"),s=p.target.result,e&&(b??=s.objectStoreNames.contains(e),o&&console.log(`${n} ${r} store "${e}" ${b?"already exists":"does not exist"}. (I: db64712bc69c5287b1cf77af1fc13d24)`)),c()}catch(h){console.error(`${n}[openDBRequest.onsuccess] ${E(h)}`),d(h)}},l.onerror=p=>{debugger;console.error(`${n}[initRequest.onerror] ${E(l.error)} (E: 74cf09e9fba2dd9e41225e943c331124)`),d(l.error)}}catch(l){console.error(`${n} ${E(l)}`);debugger;d(l)}finally{o&&console.log(`${n} complete.`)}})}catch(i){throw console.error(`${n} ${E(i)}`),i}finally{s&&(o&&console.log(`${n} closing db ${r}... (I: 3f1c18eec567ea63f3927eef0f038925)`),s.close(),o&&(console.log(`${n} closing db ${r} complete. (I: bc3b2f504245d6203dbba6bd65d30325)`),console.timeLog(n+a,"db closed. (I: e748b4ddb445d77cb10a7ba158b49125)"))),o&&(console.log(`${n} complete.`),console.timeEnd(n+a))}}f(Xo,"initializeStorage");async function mc({dbName:r,logalot:e=!1}){let t=`[${mc.name}]`,o=crypto.randomUUID();e&&console.time(t+o);try{return e&&console.log(`${t} starting... (I: 8516795b20529d19eb6923defd7a0f24)`),(await indexedDB.databases()).filter(a=>a.name===r).at(0)}catch(n){console.error(`${t} ${E(n)}`)}finally{e&&console.timeEnd(t+o),e&&console.log(`${t} complete.`)}}f(mc,"storageGetDBInfo");async function Ua({dbName:r,storeName:e,logalot:t=!1}){let o=`[${Ua.name}]`,n=crypto.randomUUID();t&&console.time(o+n);let a;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 i=!1;if(t&&console.timeLog(o+n),await new Promise((b,p)=>{let h=indexedDB.open(r);h.onsuccess=g=>{a=g.target.result,i=a.objectStoreNames?.contains(e),t&&console.timeLog(o+n,"open db request"),b()},h.onerror=g=>{debugger;console.error(`${o}[openDBRequest.onerror] ${E(h.error)} (E: 63695744e9e59ff8019e04ceeb8e2524)`),p(h.error)}}),t&&console.timeLog(o+n),i){t&&console.log(`${o} store ${e} already existed. (I: a2263b510c18240fc59fca54e3892324)`);return}let c=await mc({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 d=c.version;if(!d)throw new Error(`db (${r}) has no version. can't create store (${e}) (E: 3d2ec52853ad99f92b19ac5aa7fbfe24)`);let l=d+1;if(t&&console.log(`${o} creating store ${e} with version ${l} (I: 312b79f28243c650cf38935114f21e24)`),a)a.close(),a=void 0;else throw new Error("(UNEXPECTED) how did we get here with db falsy? (E: b561784879e19bac54b1c4936aff0c25)");await Xo({dbName:r,storeName:e,version:l,logalot:t})}catch(s){throw console.error(`${o} ${E(s)}`),s}finally{a&&(t&&console.log(`${o} closing db ${r}... (I: 3f1c18eec567ea63f3927eef0f038925)`),a.close(),t&&console.log(`${o} closing db ${r} complete. (I: bc3b2f504245d6203dbba6bd65d30325)`)),t&&console.timeLog(o+n),t&&console.log(`${o} complete.`)}}f(Ua,"storageCreateStoreIfNotExist");async function Ra({dbName:r,version:e,storeName:t,key:o,value:n,logalot:a=!1}){let s=`[${Ra.name}]`,i;try{a&&console.log(`${s} starting... (I: bf7316c244888cb8ead2d3aac1d9f625)`),await new Promise((d,l)=>{try{a&&console.log(`${s} starting... (I: 81df59e3961d711ce5d8f2ae3e2f3824)`);let b=indexedDB.open(r,e);b.onsuccess=p=>{i=p.target.result;try{let h=i.transaction(t,"readwrite").objectStore(t),g={key:o,value:n};h.put(g),d()}catch(h){console.error(`${s}[putRequest.onsuccess] ${E(h)}`),l(h)}},b.onerror=p=>{debugger;console.error(`${s}[putRequest.onerror] ${E(b.error)} (E: 7a946d99ede2b248df4dcfea4ac99724)`),l(b.error)}}catch(b){console.error(`${s} ${E(b)}`),l(b)}finally{a&&console.log(`${s} complete.`)}})}catch(c){throw console.error(`${s} ${E(c)}`),c}finally{i&&(a&&console.log(`${s} closing db ${r}... (I: 438c6edced94b83a3478c71b08c6c325)`),i.close(),a&&console.log(`${s} closing db ${r} complete. (I: 0d081553b1eb53c65ade2cedb802cf25)`)),a&&console.log(`${s} complete.`)}}f(Ra,"storagePut");async function Ko({dbName:r,version:e,storeName:t,key:o,logalot:n=!1}){let a=`[${Ko.name}]`,s;try{return n&&console.log(`${a} starting... (I: f8ba7cd5801918a8580e91b7c90aa525)`),await new Promise((d,l)=>{try{n&&console.log(`${a} starting... (I: 24163c4a11c8712097db45febaf9c724)`);let b=indexedDB.open(r,e);b.onsuccess=p=>{s=p.target.result;let h;try{h=s.transaction(t).objectStore(t)}catch(m){debugger;console.error(`${a}[openDBRequest.onsuccess][objectStore] ${E(m)}`),l(m);return}let g=h.get(o);g.onsuccess=m=>{try{let w=m.target?.result?.value??void 0;if(!w){d(w);return}if(n&&console.log("Retrieved value:",w),w instanceof Uint8Array)d(uc(w));else{if(typeof w!="string")throw new Error("(UNEXPECTED) truthy, non-Uint8Array value is not a string? (E: 6a4ec24e2e5d9848f8b542bc2661dc24)");d(w)}}catch(w){l(w)}},g.onerror=m=>{debugger;let w=g.error;console.error(`${a}[openDBRequest.onsuccess][getRequest.onerror] ${E(w)}`),l(w)}},b.onerror=p=>{debugger;console.error(`${a}[openDBRequest.onerror] ${E(b.error)} (E: 074963a908fa9a075f01c73cae829224)`),l(b.error)}}catch(b){console.error(`${a} ${E(b)}`),l(b)}finally{n&&console.log(`${a} complete.`)}})}catch(i){throw console.error(`${a} ${E(i)}`),i}finally{s&&(n&&console.log(`${a} closing db ${r}... (I: a938fc22dfdc76b15f6926bc4d458225)`),s.close(),n&&console.log(`${a} closing db ${r} complete. (I: 18f2ec1557bc83ec4e2c5d5e72264525)`)),n&&console.log(`${a} complete.`)}}f(Ko,"storageGet");async function Ma({dbName:r,store:e}){let t=`[${Ma.name}]`,o;try{return Qe&&console.log(`${t} starting... (I: 2b4373affa3841220f0b7ca690406624)`),(await window.indexedDB.databases()).some(s=>s.name===r)?e?await new Promise((s,i)=>{let c=indexedDB.open(r);c.onsuccess=d=>{o=d.target.result;let l=o.objectStoreNames.contains(e);s(l)},c.onerror=d=>{debugger;o=c.result;let{error:l}=d.target;console.error(`${t}[openDBRequest.onerror] ${E(c.error)} (E: c783fe607451e46c1feae3a81e0f7924)`),i(l)}}):!0:!1}catch(n){throw console.error(`${t} ${E(n)}`),n}finally{o&&(Qe&&console.log(`${t} closing db ${r}... (I: 8782d9eea285cf9eb638d493a421a625)`),o.close(),Qe&&console.log(`${t} closing db ${r} complete. (I: 76a0c5dea2643e2bb84c82c8446a8125)`)),Qe&&console.log(`${t} complete.`)}}f(Ma,"storageDBExists");async function Rf({dbName:r,storeName:e,pathToRm:t}){let o=`[${Rf.name}]`,n=Qe;Qe&&console.log(`${o} starting... (I: c7e4cb759789ece0a8189d7dfb4d2a24)`);let a;return new Promise((s,i)=>{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)`),i(c.error)},c.onsuccess=()=>{a=c.result;let l=a.transaction(e,"readwrite").objectStore(e),b=IDBKeyRange.lowerBound(t),p=l.openCursor(b);p.onerror=()=>{debugger;console.error(`${o}[openCursorRequest.onerror] ${E(p.error)} (E: caefdda2bb95f92e9fb8d89ee412b524)`),i(p.error)},p.onsuccess=()=>{try{let h=0,g=p.result;if(g)if(g.key.toString().startsWith(t)){let m=g.delete();h++,m.onerror=()=>{debugger;console.error(`${o}[deleteRequest.onerror] ${E(m.error)} (E: abc031c53e5387322cd8909b3ada9b24)`),i(m.error)},g.continue()}else Qe&&console.log(`${o} rmCount: ${h} (I: e4bc613a5514c0942484b79267e16724)`),s();else Qe&&console.log(`${o} cursor is falsy, so either we have no more records or had no records to begin with. (I: 9ff3aec6274416501a7baf6dcc5f2624)`),s()}catch(h){console.error(`${o}[openCursorRequest.onsuccess] ${E(h)}`),i(h)}}}}catch(c){debugger;console.error(`${o} ${E(c)}`),i(c)}}).finally(()=>{a&&(Qe&&console.log(`${o} closing db ${r}... (I: 39b4ba83de4bdfd541e3384ebab27425)`),a.close(),Qe&&console.log(`${o} closing db ${r} complete. (I: e4015b9436c4b2bc0ccf0e11e2037925)`)),Qe&&console.log(`${o} complete.`),Qe=n})}f(Rf,"storageRmRF");async function kf({dbName:r,storeName:e,dirPath:t,withFileTypes:o=!1}){let n=`[${kf.name}]`,a;try{return await new Promise((c,d)=>{let l=indexedDB.open(r);l.onerror=()=>{debugger;d(l.error)},l.onsuccess=()=>{a=l.result;let p=a.transaction(e,"readonly").objectStore(e),h=t.endsWith("/")?t:t+"/",g=IDBKeyRange.lowerBound(h),m=p.openCursor(g),w=new Set,S=[];m.onerror=()=>{debugger;console.error(`${n}[openCursorRequest.onerror] ${E(m.error)}`),d(m.error)},m.onsuccess=()=>{try{let A=m.result;if(A){let I=A.key.toString();if(I.startsWith(h)&&I!==h){let $=I.substring(h.length),T=$.split("/")[0];if(o){let _=$.substring(T.length).startsWith("/");S.push({name:T,isDirectory:f(()=>_,"isDirectory"),isFile:f(()=>!_,"isFile"),isBlockDevice:f(()=>!1,"isBlockDevice"),isCharacterDevice:f(()=>!1,"isCharacterDevice"),isSymbolicLink:f(()=>!1,"isSymbolicLink"),isFIFO:f(()=>!1,"isFIFO"),isSocket:f(()=>!1,"isSocket")})}else w.add(T);A.continue()}else I.startsWith(h)?A.continue():c(o?S:Array.from(w))}else c(o?S:Array.from(w))}catch(A){console.error(`${n}[openCursorRequest.onsuccess] ${E(A)}`),d(A)}}}})}catch(s){throw console.error(`${n} ${E(s)}`),s}finally{a&&(Qe&&console.log(`${n} closing db ${r}... (I: 39b4ba83de4bdfd541e3384ebab27425)`),a.close(),Qe&&console.log(`${n} closing db ${r} complete. (I: e4015b9436c4b2bc0ccf0e11e2037925)`))}}f(kf,"storageReaddir");var Mr=so;async function Bf(r){let e=`[${Bf.name}]`;try{Mr&&console.log(`${e} starting... (I: 1905af1827a34ca8a5507fe0c5085b01)`),await Ba({infos:[{dbName:r.dbName,storeNames:[r.storeName,...r.additionalStoreNames??[]]}]})}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Mr&&console.log(`${e} complete.`)}}f(Bf,"initIbGibStorage");function Ec(r){let e=`[${Ec.name}]`;try{Mr&&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:oc,spaceShim:{},fnDefaultGetAPIKey:f(async()=>await Ko({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{Mr&&console.log(`${e} complete.`)}}f(Ec,"initIbGibGlobalThis");function Uf(r){if(!globalThis.ibgib?.spaceGib){if(!r)throw new Error("Global context not initialized and config not provided.");Ec(r)}return globalThis.ibgib.spaceGib}f(Uf,"getIbGibGlobalThis_SpaceGib");async function Mf(r){let e=`[${Mf.name}]`;try{Mr&&console.log(`${e} starting... (I: 3123b18eb29b480bad056a9a029b9ad4)`),await(await import(r)).bootstrapSpaceGibApp()}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Mr&&console.log(`${e} complete.`)}}f(Mf,"dynamicallyLoadBootstrapScript");function zE(){let r=f(async()=>V(),"fnGetMetaspace"),e=new Promise(async(t,o)=>{try{let n=1e5,a=0,s;do{if(s=Uf()?.bootstrapPromise,a++,a>n)break;await Oe(10)}while(s===void 0);if(!s)throw new Error("Timed out waiting for bootstrapPromise. (E: ceb3ba5261994476900e4a623c0e9d10)");await s,t()}catch(n){o(n)}});return{fnGetMetaspace:r,bootstrapPromise:e}}f(zE,"getComponentCtorArg");var Ff="hash-reveal-v1",pt={hash_reveal_v1:Ff},wc=Object.values(pt);var jf="top-up",Vf="replace-all",Hf="consume",Kf="delete-all",De={topUp:jf,replaceAll:Vf,consume:Hf,deleteAll:Kf},yc=Object.values(De);var qo=class{static{f(this,"KeystoneStrategy")}config;constructor(e){this.config=e}};var Xf="recursive-salt-wrap",co={recursive_salt_wrap:Xf},$c=Object.values(co);var Wo=!1;async function Fa({masterSecret:r,kdfOpts:e}){let t=`[${Fa.name}]`;try{Wo&&console.log(`${t} starting... (I: 268e87ec311874ee6822bf459c5a5426)`);let o=e.strategy;switch(o){case co.recursive_salt_wrap:return await Yo({masterSecret:r,salt:e.salt,rounds:e.rounds,algorithm:e.algorithm});default:throw new Error(`Unknown KDF strategy: ${o}. valid values: ${$c.join(", ")} (E: c81258e9d9481eb0f88385a825193226)`)}}catch(o){throw console.error(`${t} ${E(o)}`),o}finally{Wo&&console.log(`${t} complete.`)}}f(Fa,"deriveKey");async function Yo({masterSecret:r,salt:e,rounds:t,algorithm:o=Je.sha_256}){let n=`[${Yo.name}]`;try{Wo&&console.log(`${n} starting... (I: 850868e50aba82ff28c77da8169e4c26)`);let a=r;for(let s=0;s<t;s++)a=await Ke({s:`${e}${a}${e}`,algorithm:o});return a}catch(a){throw console.error(`${n} ${E(a)}`),a}finally{Wo&&console.log(`${n} complete.`)}}f(Yo,"kdf_recursiveSaltWrap");var zo=class r extends qo{static{f(this,"KeystoneStrategy_HashRevealV1")}async derivePoolSecret({masterSecret:e}){let t=`[${r.name}.${this.derivePoolSecret.name}]`;try{let{salt:o,rounds:n,algo:a}=this.config;return await Yo({masterSecret:e,salt:o,rounds:n,algorithm:a})}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:a,algo:s}=this.config,i=o,c=e;for(let d=0;d<a;d++)c=await Ke({s:`${i}${c}${i}`,algorithm:s});return{type:"hash-reveal-v1",poolId:t,challengeId:o,value:c}}catch(a){throw console.error(`${n} ${a.message}`),a}}async generateChallenge({solution:e}){let t=`[${r.name}.${this.generateChallenge.name}]`;try{let{rounds:o,algo:n}=this.config,{challengeId:a,value:s}=e,i=a,c=s;for(let d=0;d<o;d++)c=await Ke({s:`${i}${c}${i}`,algorithm:n});return{id:a,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 Ot=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 zo(e);default:throw new Error(`Unknown strategy type: ${e.type} (E: 4e3c2f7129a241c1b687555e678c1065)`)}}catch(o){throw console.error(`${t} ${o.message}`),o}}};var lo="keystone",ja=/^\w[\w\-.]*$/,Va=/^[a-zA-Z0-9\-_]{1,64}$/,Ha=/^[a-zA-Z0-9_\-.]{1,63}$/,Ka=/^[a-zA-Z0-9\s.,!?:;'"\-()[\]_+=@#$%&*\/]{0,128}$/,Xa=1e3,Jo="revoke",Nt="manage",qf="sign",wt="sync",tr="connect",qa={REVOKE:Jo,MANAGE:Nt,SIGN:qf,SYNC:wt,CONNECT:tr},yw=Object.values(qa);var Wa=Jo,yr=Nt;var yt=tr,$r=wt;var Ic=200,Sc=2,_c=2,Ac=5,Tc=De.topUp,Gc=Je.sha_256,Cc=1,vc=2e3,Oc=5,Nc=5,xc=16,Lc=De.replaceAll,Dc=Je.sha_512,Pc=10,Zo=50;var ce=!1;async function xt({ibGib:r,ibGibs:e,ibGibAddr:t,ibGibAddrs:o,live:n,gotten:a,tjpAddrsAlreadyAnalyzed:s,skipAddrs:i,skipRel8nNames:c,onlyRel8nNames:d,maxRetries:l,msBetweenRetries:b,space:p,timeLogName:h,mapTjpAddrToLatestAddrsInSpace:g}){let m=`[${xt.name}]`;try{ce&&console.log(`${m} starting... (I: c2a4426c22e849611ca0cedabe683a22)`);let w=await fo({ibGib:r,ibGibs:e,ibGibAddr:t,ibGibAddrs:o,live:n,gotten:a,tjpAddrsAlreadyAnalyzed:s,skipAddrs:i,skipRel8nNames:c,onlyRel8nNames:d,maxRetries:l,msBetweenRetries:b,space:p,timeLogName:h,mapTjpAddrToLatestAddrsInSpace:g});if(Object.values(w).filter(S=>S.ib.startsWith("comment ")).forEach(S=>{console.table(S)}),ce){console.log(`${m} graph size: ${Object.keys(w).length} (I: c6cb5e7e1e2611d35b9006fac6503d22)`);let S=Object.values(w).filter(A=>A.ib.startsWith("comment ")||A.ib.startsWith("pic ")).map(A=>A.ib);$o(S).forEach(A=>console.log(A))}return w}catch(w){throw console.error(`${m} ${w.message}`),w}finally{ce&&console.log(`${m} complete.`)}}f(xt,"getDependencyGraph");async function Rc({ibGib:r,ibGibs:e,ibGibAddr:t,ibGibAddrs:o,live:n,gotten:a,tjpAddrsAlreadyAnalyzed:s,skipAddrs:i,skipRel8nNames:c,onlyRel8nNames:d,maxRetries:l,msBetweenRetries:b,space:p,timeLogName:h,mapTjpAddrToLatestAddrsInSpace:g}){let m=`[${Rc.name}]`;try{if(ce&&console.log(`${m} starting... (I: bd6807477f679345df9dddefe0b4e922)`),!p)throw new Error("space 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||[],i=i||[],a=a||{},s=s||[],o=(o??[]).filter(w=>!$e({gib:ne({ibGibAddr:w}).gib})).filter(w=>!i.includes(w)),e=(e??[]).filter(w=>!$e({ibGib:w})).filter(w=>!i.includes(y({ibGib:w}))),r&&!$e({ibGib:r})&&!e.some(w=>w.gib===r.gib)&&!i.includes(y({ibGib:r}))&&e.push(r),t&&!$e({gib:ne({ibGibAddr:t}).gib})&&!o.includes(t)&&!i.includes(t)&&o.push(t),{ibGib:r,ibGibs:e,ibGibAddr:t,ibGibAddrs:o,live:n,gotten:a,tjpAddrsAlreadyAnalyzed:s,skipAddrs:i,skipRel8nNames:c,onlyRel8nNames:d,maxRetries:l,msBetweenRetries:b,space:p,timeLogName:h,mapTjpAddrToLatestAddrsInSpace:g}}catch(w){throw console.error(`${m} ${w.message}`),w}finally{ce&&console.log(`${m} complete.`)}}f(Rc,"getGraphProjection_initializeOpts");async function kc({ibGibs:r,ibGibAddrs:e,gotten:t,skipAddrs:o,maxRetries:n,msBetweenRetries:a,timeLogName:s,space:i}){let c=`[${kc.name}]`;try{ce&&console.log(`${c} starting... (I: 67b2be37ff24393fff56e229304da122)`);let d=[];r??=[],e??=[],o??=[],t??={};let l=[],b=Object.keys(t??{}),p=r.map(h=>y({ibGib:h}));for(let h=0;h<e.length;h++){let g=e[h];o.includes(g)||p.includes(g)||(b.includes(g)?d.push(t[g]):l.push(e[h]))}if(ce&&console.log(`${c}[analyze debugging] addrsToGetFromSpace (${l.length}):
13
+ ${l.join(`
14
+ `)} (I: b45a2614184b48b694becfd377c789f5)`),l.length>0){let h=l.concat(),g=0;for(n=n??0;g<=n&&h.length>0;){if(s&&g===0&&console.timeLog(s,`${c} FIRST try starting...`),s&&g>0&&console.timeLog(s,`${c} RETRY starting...`),g>0&&a&&(s&&console.timeLog(s,`${c} delaying ${a}ms for retry`),ce&&console.log(`${c} retrying. addrsToGet (${h.length}): ${h} (I: 8460694cdd5518472680784c3b96a822)`),await Oe(a)),s&&console.timeLog(s,`${c} getFromSpace (${h?.length}) starting...`),!i)throw new Error("(UNEXPECTED) space falsy? (E: aa9f657695717034b3581066932d7d23)");let m=await te({addrs:h,space:i});if(s&&console.timeLog(s,`${c} getFromSpace complete.`),m.success&&(m.ibGibs?.length??0)>0){m.ibGibs.forEach(S=>d.push(S));let w=m.ibGibs.map(S=>y({ibGib:S}));if(w.length===h.length){s&&console.timeLog(s,`${c} got all.`),h=[];break}else s&&console.timeLog(s,`${c} got some.`),h=h.filter(S=>!w.includes(S))}else{let w=m.rawResultIbGib.ibGibs??[];if(w.length>0){w.forEach(A=>d.push(A));let S=w.map(A=>y({ibGib:A}));s&&console.timeLog(s,`${c} got some.`),h=h.filter(A=>!S.includes(A))}else s&&console.timeLog(s,`${c} failed. addrs: ${h?.join(",")}`)}g++}if(h?.length>0)throw new Error(`unable to retrieve dependency ibgibs from space (ib: ${i?.ib}). addrsToGet: ${h.join(`
15
+ `)} (E: 8413594b6c1b447988781cf3f3e1729d)`)}return d}catch(d){throw console.error(`${c} ${d.message}`),d}finally{ce&&console.log(`${c} complete.`)}}f(kc,"getGraphProjection_getIbGibsInIbGibAddrs");async function fo(r){let e=`[${fo.name}]`;try{if(ce&&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:a,tjpAddrsAlreadyAnalyzed:s,skipAddrs:i,skipRel8nNames:c,onlyRel8nNames:d,maxRetries:l,msBetweenRetries:b,space:p,timeLogName:h,mapTjpAddrToLatestAddrsInSpace:g}=await Rc(r);if(h&&console.timeLog(h,`${e} starting...`),o?.length??!1){let w=await kc({ibGibs:t,ibGibAddrs:o,gotten:a,skipAddrs:i,maxRetries:l,msBetweenRetries:b,timeLogName:h,space:p});t=t?[...t,...w]:[...w]}o=t.map(w=>y({ibGib:w}));let m=$o(t.map(w=>w.ib).filter(w=>w.startsWith("comment ")));return ce&&console.log(`${e}[analyze debugging] ibGibs commentIbs: ${m.join(`
16
+ `)} (I: c89dc951315f746954f9bddbe8941122)`),n?Bc({ibGibs:t,ibGibAddrs:o,gotten:a,tjpAddrsAlreadyAnalyzed:s,skipAddrs:i,skipRel8nNames:c,onlyRel8nNames:d,maxRetries:l,msBetweenRetries:b,space:p,timeLogName:h,mapTjpAddrToLatestAddrsInSpace:g}):Uc({ibGibs:t,ibGibAddrs:o,gotten:a,skipAddrs:i,skipRel8nNames:c,onlyRel8nNames:d,maxRetries:l,msBetweenRetries:b,space:p,timeLogName:h})}catch(t){throw console.error(`${e} ${t.message}`),t}finally{ce&&console.log(`${e} complete.`)}}f(fo,"getGraphProjection");async function Fr({ibGibAddr:r,latestCommonFrameAddr:e,live:t,space:o}){let n=`[${Fr.name}]`;try{if(ce&&console.log(`${n} starting... (I: 5d225e56dc11e62cd83c5366ea288826)`),r===e)return console.warn(`${n} ibGibAddr === latestCommonFrameAddr. So the delta graph is empty. what are we doing here? (W: e0c8287ae6de8152bf36b6c73ca59a26)`),{};let a=await xt({ibGibAddr:e,live:!1,space:o});return await xt({ibGibAddr:r,live:t,skipAddrs:Object.keys(a),space:o})}catch(a){throw console.error(`${n} ${E(a)}`),a}finally{ce&&console.log(`${n} complete.`)}}f(Fr,"getDeltaDependencyGraph");async function Bc({ibGibs:r,ibGibAddrs:e,gotten:t,tjpAddrsAlreadyAnalyzed:o,mapTjpAddrToLatestAddrsInSpace:n,skipAddrs:a,skipRel8nNames:s,onlyRel8nNames:i,maxRetries:c,msBetweenRetries:d,space:l,timeLogName:b}){let p=`[${Bc.name}]`;try{n=n??{},o=o??[];let h={...t};(r??[]).forEach(I=>h[y({ibGib:I})]=I);let g=bt({ibGibs:Object.values(h)});ce&&console.log(`${p}[analyze debugging] timeline tjps(${Object.keys(g).length}): ${Object.keys(g)} (I: 509f04ac15ca08c5a3f0777b48934622)`);let m={};Object.keys(g).forEach(I=>{o.includes(I)||(m[I]=g[I])}),ce&&console.log(`${p}[analyze debugging] timelinesNotAnalyzed: ${K(m)} (I: a4b67d95fdd6b98d3241c0a7d0a93c22)`);let w={},S={};Object.keys(g).filter(I=>!o.includes(I)).forEach(I=>{let $=g[I],T=$[$.length-1];w[I]=T;let _=y({ibGib:T});S[_]=I});let A=Object.keys(w).length;if(A>0){let I={};Object.keys(n).filter(N=>!o.includes(N)).forEach(N=>{let D=w[N];if(D){let B=y({ibGib:D});I[B]=n[N]}else console.error(`${p} latestIbGibCorrespondingToTjpAddr is falsy`)}),ce&&console.log(`${p} latestAddrsMap *before* getLatestAddrs: ${K(I)} (I: 427b4bb78595e9e521ecf2c5e5c80722)`);let $=Object.values(w),T={};if($.length>0){if(!l)throw new Error("(UNEXPECTED) space falsy? (E: 8e878975e3561df9a8dc4c628b0abc23)");let N=await We({ibGibs:$,space:l});if(!N?.data?.latestAddrsMap)throw new Error("(UNEXPECTED) getLatestAddrs result latestAddrsMap falsy (E: 088caa1fc95fd3b079108ab63ef33422)");if(T=N?.data?.latestAddrsMap,Object.keys(T).length!==A)throw new Error("(UNEXPECTED) latestAddrsMap is not the same size as the incoming map (E: 666af512bbd44534983bb28ee8d43fed)");ce&&console.log(`${p} queriedLatestAddrsMap: ${K(T)} (I: 7b39a5f7ce9e9d9fabae4be98ed44522)`),I={...T,...I}}ce&&console.log(`${p} combined latestAddrsMap: ${K(I)} (I: e3aedea63f29c5b06a79632f691aa522)`);let _=[],G={};Object.values(w).forEach(N=>{let D=y({ibGib:N}),B=S[D],P=I[D];if(!P)throw new Error("(UNEXPECTED) latestAddrInSpace not found in latestAddrsMap (E: 095d2b3f88e3e8a2c3e7d3de4c6d5622)");P===D?(ce&&console.log(`${p} analyzed ${B}(I: afb7960900f04b8a87538f4c7bd903b7)`),o.push(B)):(_.push(P),G[P]=B)});let v=[];for(let N=0;N<(r??[]).length;N++){let B=r[N].rel8ns??{};Object.keys(B).filter(k=>!(s??[]).includes(k)).filter(k=>i?i.includes(k):!0).forEach(k=>{(B[k]??[]).forEach(j=>{!v.includes(j)&&!r.some(Q=>y({ibGib:Q})===j)&&!$e({gib:ne({ibGibAddr:j}).gib})&&v.push(j)})})}return e=$o([...e??[],...v,..._]),await fo({ibGibs:r,ibGibAddrs:e,gotten:t,tjpAddrsAlreadyAnalyzed:o,skipAddrs:a,skipRel8nNames:s,onlyRel8nNames:i,maxRetries:c,msBetweenRetries:d,space:l,timeLogName:b,live:!0,mapTjpAddrToLatestAddrsInSpace:n})}else return r||(r=[]),Object.values(t??{}).forEach(I=>{let $=y({ibGib:I});r.some(T=>y({ibGib:I})===$)||r.push(I)}),await fo({ibGibs:r,ibGibAddrs:e,gotten:t,skipAddrs:a,skipRel8nNames:s,onlyRel8nNames:i,maxRetries:c,msBetweenRetries:d,space:l,timeLogName:b,live:!1})}catch(h){let g=`${p} ${h.message}`;throw console.error(g),b&&console.timeLog(b,`${p} error: ${g}`),h}finally{b&&console.timeLog(b,`${p} complete.`)}}f(Bc,"getGraphProjection_Live");async function Uc({ibGibs:r,ibGibAddrs:e,gotten:t,skipAddrs:o,skipRel8nNames:n,onlyRel8nNames:a,maxRetries:s,msBetweenRetries:i,space:c,timeLogName:d}){let l=`[${Uc.name}]`;try{let b=[];r??=[],t??={},o??=[],n??=[],d&&console.timeLog(d,`${l} analyzing next step starting...`);for(let p=0;p<r.length;p++){let h=r[p],g=y({ibGib:h}),{gib:m}=ne({ibGib:h});if(m===re)throw new Error("cannot get dependency graph of primitive.");Object.keys(t).includes(g)||(t[g]=h);let w={},S=h.rel8ns||{},A=(Object.keys(S)||[]).filter($=>!n.includes($));a&&(A=A.filter($=>a.includes($)));let I=Object.keys(t);for(let $=0;$<A.length;$++){let T=A[$],_=S[T]??[],G=_.filter(N=>N===""||N===void 0||N===null||!N.includes(Ne));G.length>0&&console.warn(`${l} (UNEXPECTED) has falsyAddrs: ${G} (W: da9505cb0a4db68a4aff7f279ad2d322)`),_.filter(N=>!!N).filter(N=>!I.includes(N)).filter(N=>!o.includes(N)).filter(N=>ne({ibGibAddr:N}).gib!==re).filter(N=>!b.includes(N)).forEach(N=>{let D=Pr({addr:N});(D||[]).length===0?b.push(N):w[N]=D})}if(Object.keys(w).length>0)throw new Error(`invalid addresses found in dependency graph. Errors (clipped to 1kB): ${JSON.stringify(w).substring(0,1024)}`)}if(d&&console.timeLog(d,`${l} analyzing next step complete.`),b.length>0){if(d&&console.timeLog(d,`${l} get addrsWeDontHaveAlready_Rel8dAddrs starting...`),!c)throw new Error("(UNEXPECTED) space falsy? (E: 0ce327cf5d521bd798340333460f3423)");let p=await te({addrs:b,space:c});if(d&&console.timeLog(d,`${l} get addrsWeDontHaveAlready_Rel8dAddrs complete.`),p.success)if(p.ibGibs?.length===b.length){ce&&console.log(`${l} got ALL of them (happy path)`),p.ibGibs.forEach(g=>t[y({ibGib:g})]=g),d&&console.timeLog(d,`${l} call getGraphProjection recursively starting...`);let h=await fo({ibGibs:p.ibGibs,live:!1,gotten:t,skipAddrs:o,skipRel8nNames:n,onlyRel8nNames:a,maxRetries:s,msBetweenRetries:i,space:c});return d&&console.timeLog(d,`${l} call getGraphProjection recursively complete.`),h}else throw(p.ibGibs?.length??0)>0&&p.ibGibs.length<b.length?(ce&&console.warn(`${l} got SOME of them (happy-ish path?). not sure what to do here... (W: e3458f61a1ae4979af9e6b18ac935c14)`),new Error("trouble getting dependency ibgibs (E: 8156bf65fd084ae4a4e8a0669db28b07)")):(p.ibGibs?.length??!1)&&p.ibGibs.length>b.length?new Error("(UNEXPECTED) got more ibGibs than addrs that we asked for. space not working properly. (E: 352219b3d18543bcbda957f2d60b78f3)"):new Error("couldn't get dependency ibgibs from space. (E: 225f26b7d7f84911bb033753a062209b)");else throw new Error(`failure getting addrs in space ${c?.data?.name||"[no name?]"} (id: ${c?.data?.uuid||"[no uuid?]"}). (E: 60404e6e389249d9bbecf0039cd51878) addrs:
17
+ ${b.join(`
18
+ `)} `)}else return t}catch(b){let p=`${l} ${b.message}`;throw console.error(p),d&&console.timeLog(d,`${l} error: ${p}`),b}finally{d&&console.timeLog(d,`${l} complete.`)}}f(Uc,"getGraphProjection_NonLive");function Qo({ibGibs:r}){let e=`[${Qo.name}]`;try{if(ce&&console.log(`${e} starting... (I: 6019a812cff8597f79c12088e45cc226)`),r){let t={};return r.forEach(o=>{t[y({ibGib:o})]=o}),t}else return}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{ce&&console.log(`${e} complete.`)}}f(Qo,"toFlatGraph");function Se({graphA:r,graphB:e,slowButThorough:t}){let o=`[${Se.name}]`;try{if(ce&&console.log(`${o} starting... (I: e50a98b659189dece8b4ef581e4ad826)`),!(Object.keys(r).length===Object.keys(e).length))return ce&&console.log(`${o} not the same size. false. (I: e1044e52421dbf7e067e0fe850ac6826)`),!1;for(let a of Object.keys(r))if(!e[a])return ce&&console.log(`${o} addr (${a}) in graphA not found in graphB (I: 264c68408378ce30b8f6a978f8b86926)`),!1;if(t)for(let a of Object.keys(r)){let s=Ye({ibGib:r[a]}),i=JSON.stringify(s),c=Ye({ibGib:e[a]}),d=JSON.stringify(c);if(i!==d)return ce&&console.log(`${o} jsonA !== jsonB for addr (${a}) (I: 98ed9f58ac88dabba83f96582f725926)`),!1}return!0}catch(n){throw console.error(`${o} ${E(n)}`),n}finally{ce&&console.log(`${o} complete.`)}}f(Se,"graphsAreEquivalent");var _e=!1;async function Mc({keystoneData:r}){let e=`[${Mc.name}]`;try{return _e&&console.log(`${e} starting... (I: c3022a146faac9730154f34d1439a225)`),[lo].join(" ")}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{_e&&console.log(`${e} complete.`)}}f(Mc,"getKeystoneIb");async function Ya({ib:r}){let e=`[${Ya.name}]`;try{_e&&console.log(`${e} starting... (I: 73cb6832984255ed48b2f44db6a21e25)`);let[t]=r.split(" ");if(t!==lo)throw new Error(`invalid keystone ib. atom found in ib (${t}) does not match keystone atom (${lo}) (E: 79b3d587824c4271b6e60acc76e0c825)`);return{atom:t}}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{_e&&console.log(`${e} complete.`)}}f(Ya,"parseKeystoneIb");async function bo({ib:r}){try{return await Ya({ib:r}),!0}catch{return!1}}f(bo,"validateKeystoneIb");async function Fc({pool:r,requiredChallengeIds:e,targetAddr:t}){let o=r.config.behavior,n=new Set,a=Object.keys(r.challenges);if(e&&e.length>0){for(let s of e){if(!r.challenges[s])throw new Error(`(UNEXPECTED) Required challenge ID not found in pool: ${s} (E: 10c5619d80d8cf6cc84ffbf8be0dbc25)`);a.includes(s)&&n.add(s)}a=a.filter(s=>!n.has(s))}if(o.targetBindingCount>0&&t){let s=[...a].sort(),i=await Ke({s:t});for(let c=0;c<o.targetBindingCount;c++){if(s.length===0)throw new Error("Entropy Exhaustion. Cannot satisfy target binding. Sorted available pool is empty. (E: 341b95dc3a58be3e083d1d9c4a0c4925)");let d=BigInt("0x"+i),l=Number(d%BigInt(s.length)),b=s[l];n.add(b),s.splice(l,1),a=a.filter(p=>p!==b),i=await Ke({s:i})}}if(o.selectSequentially>0){if(a.length<o.selectSequentially)throw console.error(`[getDeterministicRequirements] Entropy Exhaustion! AvailableCount: ${a.length}, Required Seq: ${o.selectSequentially}. Available IDs: ${a.join(",")}`),new Error("Entropy Exhaustion. Insufficient challenges for FIFO requirement. (E: 9efa88003e1d5eccb837c85154ee5625)");a.slice(0,o.selectSequentially).forEach(i=>n.add(i)),a=a.slice(o.selectSequentially)}return{mandatoryIds:n,availableIds:a}}f(Fc,"getDeterministicRequirements");function tn({pools:r,poolId:e,poolFilter:t,verb:o}){let n="[resolveTargetPool]";try{let a;if(e){if(a=r.find(s=>s.id===e),!a)throw new Error(`Pool not found with ID: ${e} (E: 4a2b17428515c1e82813158581898125)`)}else if(t){let s=r.filter(t);if(s.length===0)throw new Error("No pool matched the provided filter. (E: 5b3c27428515c1e82813158581898125)");a=s[0]}else{if(!o)throw new Error("Cannot auto-resolve pool without a verb. (E: 6c4d37428515c1e82813158581898125)");if(a=r.find(s=>s.config.allowedVerbs&&s.config.allowedVerbs.includes(o)),a||(a=r.find(s=>!s.config.allowedVerbs||s.config.allowedVerbs.length===0)),!a)throw new Error(`No suitable pool found for verb: ${o} (E: 7d5e47428515c1e82813158581898125)`)}if(o&&a.config.allowedVerbs&&a.config.allowedVerbs.length>0&&!a.config.allowedVerbs.includes(o))throw new Error(`Pool ${a.id} is not authorized for verb: ${o} (E: 8e6f57428515c1e82813158581898125)`);return a}catch(a){throw console.error(`${n} ${E(a)}`),a}}f(tn,"resolveTargetPool");async function rn({pool:r,targetAddr:e,requiredChallengeIds:t}){let o="[selectChallengeIds]";try{let{mandatoryIds:n,availableIds:a}=await Fc({pool:r,requiredChallengeIds:t,targetAddr:e}),s=r.config.behavior.selectRandomly,i=[];if(s>0){if(a.length<s)throw new Error(`Insufficient challenges for random requirement. Need ${s}, have ${a.length} (E: 9f7a67428515c1e82813158581898125)`);let c=[...a].sort(()=>.5-Math.random());i.push(...c.slice(0,s))}return[...n,...i]}catch(n){throw console.error(`${o} ${E(n)}`),n}}f(rn,"selectChallengeIds");async function en({salt:r,timestamp:e,index:t}){return(await Ke({s:`${r}${e}${t}`})).substring(0,16)}f(en,"generateOpaqueChallengeId");async function Wf({prevPools:r,targetPoolId:e,consumedIds:t,masterSecret:o,strategy:n,config:a}){let s="[applyReplenishmentStrategy]";try{let i=JSON.parse(JSON.stringify(r)),c=i.findIndex(h=>h.id===e);if(c===-1)throw new Error(`Target pool ${e} not found in keystone data. (E: 75200388d22744838634524233772545)`);let d=i[c],l=await n.derivePoolSecret({masterSecret:o}),b=Date.now().toString(),p=a.behavior.replenish;if(p===De.topUp){t.forEach(h=>delete d.challenges[h]);for(let h=0;h<t.length;h++){let g=await en({salt:a.salt,timestamp:b,index:h}),m=await n.generateSolution({poolSecret:l,poolId:d.id,challengeId:g});d.challenges[g]=await n.generateChallenge({solution:m})}}else if(p===De.replaceAll){d.challenges={};for(let h=0;h<a.behavior.size;h++){let g=await en({salt:a.salt,timestamp:b,index:h}),m=await n.generateSolution({poolSecret:l,poolId:d.id,challengeId:g});d.challenges[g]=await n.generateChallenge({solution:m})}}else if(p===De.consume)t.forEach(h=>delete d.challenges[h]);else if(p===De.deleteAll)d.challenges={};else throw new Error(`Unknown replenish strategy: ${p}. Valid list: ${K(yc)} (E: 0acf56f1e1486240080e11e8046d0825)`);return i}catch(i){throw console.error(`${s} ${E(i)}`),i}}f(Wf,"applyReplenishmentStrategy");async function on({targetPoolId:r,prevPools:e,masterSecret:t,challengeIds:o,claim:n,requiredChallengeIds:a}){let s="[solveAndReplenish]";try{_e&&console.log(`${s} starting... poolId: ${r}, ids: ${o.length}`);let i=e.find(h=>h.id===r);if(!i)throw new Error(`Target pool not found: ${r} (E: a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6)`);let c=Ot.create({config:i.config}),d=await c.derivePoolSecret({masterSecret:t}),l=[];for(let h of o){let g=await c.generateSolution({poolSecret:d,poolId:i.id,challengeId:h});l.push(g)}let b={claim:n,solutions:l,requiredChallengeIds:a&&a.length>0?a:void 0},p=await Wf({prevPools:e,targetPoolId:i.id,consumedIds:o,masterSecret:t,strategy:c,config:i.config});return{proof:b,nextPools:p}}catch(i){throw console.error(`${s} ${E(i)}`),i}}f(on,"solveAndReplenish");async function jc({pool:r}){let e=`[${jc.name}]`;try{if(_e&&console.log(`${e} starting... (I: e2ffd568b698cc12d8c5e838d73ae726)`),!r.config)throw new Error("(UNEXPECTED) pool.configy falsy? (E: fcde88fe20e8004a58d7e445436bf526)");if(r.config.type!==pt.hash_reveal_v1)throw new Error("(UNEXPECTED) pool.config.type !== KeystoneChallengeType.hash_reveal_v1? (E: e205f8872909c37168a624a9df778c26)");let t=[],{algo:o,rounds:n,salt:a}=r.config,s=[Je.sha_256,Je.sha_512];return o?s.includes(o)||t.push(`${e} invalid hash algorithm (${o}). Must be one of ${s}. (E: a22399ca3a68e63ffcc7507699be5826)`):t.push(`${e} algorithm required. (E: 8cd6bfb0590862b9bae24d98d2cf3826)`),n&&typeof n=="number"&&Number.isInteger(n)?n>Xa&&t.push(`${e} rounds too high. max rounds: ${Xa} (E: 31ce082f7fd88d6b58ef08a816458826)`):t.push(`${e} invalid rounds (${n}). must be positive integer. (E: 73c643ccda78afaf28d52a6871a9e826)`),a&&typeof a=="string"?Va.test(a)||t.push(`${e} invalid salt (${a.substring(0,99)}). Must match regexp ${Va}`):t.push(`${e} invalid salt (${a}). must be truthy string value. (E: 564a4844ec88fc1988197ce89c381426)`),t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{_e&&console.log(`${e} complete.`)}}f(jc,"validateChallengePool_typeHashRevealV1");async function Vc({pool:r}){let e=`[${Vc.name}]`;try{_e&&console.log(`${e} starting... (I: 1a0eafc158a83d1ba8fc019d5c979a26)`);let t=[];if(r.config){if(r.config.id?ja.test(r.config.id)||t.push(`${e} pool.config.id is not formatted correctly. must pass regexp: ${ja.source}`):t.push(`${e} pool.config.id falsy (E: 31d7943d95f877326d5f4ea14463d626)`),r.config.behavior){let{size:n,selectSequentially:a,selectRandomly:s,targetBindingCount:i}=r.config.behavior;(!n||n===0)&&t.push(`${e} invalid pool.config.behavior.size (${n}). Must be positive integer. (E: b221e36ec102bdc944552248ce8fe626)`);let c=(a||0)+(s||0)+(i||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 pt.hash_reveal_v1:(await jc({pool:r})).forEach(a=>t.push(a));break;default:throw new Error(`(UNEXPECTED) unknown pool.config.type (${o})? We only implement the following at this time: ${wc} (E: cce5285cf7580b8bc82172488eba2826)`)}}else t.push(`${e} pool.config falsy. (E: 8d05c875a1d2c58018a5eaf803977d26)`);return t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{_e&&console.log(`${e} complete.`)}}f(Vc,"validateChallengePool");function Hc({data:r}){let e="[validateKeystoneMetadata]",t=[],o=f((n,a)=>{n&&(n.username!==void 0&&(typeof n.username!="string"||!Ha.test(n.username))&&t.push(`${e} invalid username in ${a} (${n.username}). Must match ${Ha}`),n.description!==void 0&&(typeof n.description!="string"||!Ka.test(n.description))&&t.push(`${e} invalid description in ${a} (${n.description}). Must match ${Ka}`))},"checkDetails");return o(r.frameDetails,"frameDetails"),o(r.checkpointDetails,"checkpointDetails"),t}f(Hc,"validateKeystoneMetadata");async function nn({keystoneIbGib:r}){let e=`[${nn.name}]`;try{_e&&console.log(`${e} starting... (I: ec6ba82ec848b5ac3d8953e89d8d9826)`);let t=[],{data:o,rel8ns:n}=r;await bo({ib:r.ib})||t.push(`${e} invalid keystone ib (${r.ib}). (E: ad7a88bc38c290a184dfbd42be48f526)`),Hc({data:o}).forEach(i=>t.push(i)),o.proofs&&o.proofs.length>0&&t.push(`${e} proofs already exist on genesis keystone. (E: 7a5e15f20918f1bbd8ffb62857dcd526)`);for(let i of o.challengePools)(await Vc({pool:i})).forEach(d=>t.push(d)),(!i.challenges||Object.keys(i.challenges).length===0)&&t.push(`${e} invalid pool (${i.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{_e&&console.log(`${e} complete.`)}}f(nn,"validateGenesisKeystone");function Yf({currDelegates:r,prevDelegates:e}){let t=r||{},o=e||{},n=Object.keys(t),a=Object.keys(o);if(n.length!==a.length)return!0;for(let s of n){let i=t[s],c=o[s];if(!c||i.delegateTjpAddr!==c.delegateTjpAddr||i.delegateAddr!==c.delegateAddr||i.thisAddr!==c.thisAddr)return!0}return!1}f(Yf,"isDelegatesChanged");async function zf({currDelegates:r,prevIbGib:e,lc:t,errors:o}){let n=Object.keys(r),a=y({ibGib:e});for(let s of n){let i=r[s];s!==i.delegateTjpAddr&&o.push(`${t} Invalid delegate mapping: Key '${s}' does not match delegateTjpAddr '${i.delegateTjpAddr}'. (E: 9c8da8bc38c290a184dfbd42be48f526)`);let[c,d,l]=await Promise.all([bo({ib:i.delegateTjpAddr.split("^")[0]}),bo({ib:i.delegateAddr.split("^")[0]}),bo({ib:i.thisAddr.split("^")[0]})]);c||o.push(`${t} Delegate delegateTjpAddr '${i.delegateTjpAddr}' is not a valid keystone address. (E: 10d8a8bc38c290a184dfbd42be48f526)`),d||o.push(`${t} Delegate delegateAddr '${i.delegateAddr}' is not a valid keystone address. (E: 20d8a8bc38c290a184dfbd42be48f526)`),l||o.push(`${t} Delegate thisAddr '${i.thisAddr}' is not a valid keystone address. (E: 30d8a8bc38c290a184dfbd42be48f526)`),i.thisAddr===a||(e.rel8ns?.past||[]).includes(i.thisAddr)||o.push(`${t} Delegate thisAddr '${i.thisAddr}' is not a valid historical address in the parent keystone timeline. (E: 40d8a8bc38c290a184dfbd42be48f526)`)}}f(zf,"validateDelegates");async function po({currentIbGib:r,prevIbGib:e}){let t=`[${po.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 ge({ibGib:r});n&&n.length>0&&o.push(...n);let a=r.data,s=e.data;await bo({ib:r.ib})||o.push(`${t} invalid keystone ib (${r.ib}). (E: a98dc8bc38c290a184dfbd42be48f526)`),Hc({data:a}).forEach(g=>o.push(g));let d=a.delegates||{},l=s.delegates||{};Yf({currDelegates:d,prevDelegates:l})&&(a.proofs?.some(m=>m.claim?.verb===Nt)||o.push(`${t} Policy Violation: Delegates map was mutated but no proof for manage verb ('${Nt}') is present. (E: 819fa8cb28c9b60e68994511a5825)`)),await zf({currDelegates:d,prevIbGib:e,lc:t,errors:o});let p=a.n??-2,h=s.n??-2;p<0&&o.push("invalid keystone.currData.n is undefined or null. (E: 9fbe38704b68829d18ea1d0940d0aa26)"),h<0&&o.push("invalid keystone.prevData.n is undefined or null. (E: 6dc5aa9c87017db6080ed4268b07af26)"),p!==h+1&&o.push(`keystone data.n values are not sequential. prevData.n: ${h}, currData.n: ${p}. (E: 5ae12809f2c67216d38d8ba8d6c42826)`);for(let g of a.proofs){if(g.solutions.length===0){o.push(`Proof ${g.id||"unknown"} has no solutions. (E: e2b4683ce0ce30f798ec77841e88c826)`);continue}let m=g.solutions[0].poolId,w=s.challengePools.find(S=>S.id===m);if(!w){o.push(`Proof references unknown pool: ${m}`);continue}await Kc({proof:g,pool:w,errors:o})}if(a.revocationInfo){let g=a.revocationInfo.proof.claim.target,m=y({ibGib:e});g!==m&&o.push(`Revocation target mismatch. Expected ${m}, got ${g}`)}return o}catch(n){throw console.error(`${t} ${E(n)}`),n}finally{_e&&console.log(`${t} complete.`)}}f(po,"validateKeystoneTransition");async function Kc({proof:r,pool:e,errors:t}){let o=`[${Kc.name}]`;try{_e&&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:a}=await Fc({pool:e,requiredChallengeIds:r.requiredChallengeIds,targetAddr:r.claim.target}),s=new Set(r.solutions.map(l=>l.challengeId));for(let l of n)s.has(l)||t.push(`Policy Violation: Missing mandatory challenge ${l}`);let i=[...s].filter(l=>!n.has(l)),c=e.config.behavior.selectRandomly;i.length<c&&t.push(`Policy Violation: Insufficient random count. Need ${c}, got ${i.length}`);for(let l of i)a.includes(l)||t.push(`Policy Violation: ID ${l} is invalid or double-dipped.`);let d=Ot.create({config:e.config});for(let l of r.solutions){let b=e.challenges[l.challengeId];b?await d.validateSolution({solution:l,challenge:b})||t.push(`Crypto Violation: Solution for ${l.challengeId} is invalid.`):t.push(`Crypto Violation: Challenge ${l.challengeId} not found in pool.`)}}catch(n){throw console.error(`${o} ${E(n)}`),n}finally{_e&&console.log(`${o} complete.`)}}f(Kc,"verifyProofAgainstPool");async function ho({prevIbGib:r,newData:e,metaspace:t,space:o}){let n=`[${ho.name}]`;try{if(_e&&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: ${y({ibGib:r})} (E: 45d7f846556829de6b2a701838c3f825)`);let a=r.data,s={};a.proofs&&(s.proofs=[]),a.challengePools&&(s.challengePools=[]),a.frameDetails&&(s.frameDetails={}),a.checkpointDetails&&(s.checkpointDetails={}),a.delegates&&(s.delegates="remove"),Object.keys(s).length===0&&(s=void 0);let i=await at({src:r,dataToRemove:s,dataToAddOrPatch:e,nCounter:!0});if(i.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(i.dnas)throw new Error("(UNEXPECTED) resMut8.dnas truthy? We do not want dnas with keystones. (E: 49470513d018f97d28024f4e82da3b25)");let c=i.newIbGib,d=await po({currentIbGib:c,prevIbGib:r});if(d.length>0)throw console.error(`${n} Validation Failed:
19
+ ${d.join(`
20
+ `)}`),new Error(`(UNEXPECTED) invalid keystone after we just evolved it? Errors: ${d.join("; ")} (E: ae2c58406c1db7687879dfb89fc1f825)`);return await t.put({ibGib:c,space:o}),await t.registerNewIbGib({ibGib:c,space:o}),c}catch(a){throw console.error(`${n} ${E(a)}`),a}finally{_e&&console.log(`${n} complete.`)}}f(ho,"evolvePersistAndRegisterKeystone");async function za({data:r,metaspace:e,space:t}){let o=`[${za.name}]`;try{if(_e&&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 a=(await F.firstGen({parentIbGib:F.primitive({ib:lo}),ib:await Mc({keystoneData:r}),data:r,dna:!1,nCounter:!0,tjp:{timestamp:!0,uuid:!0}})).newIbGib;if(!a.data)throw new Error("(UNEXPECTED) keystoneIbGib.data falsy? We expect the data to be populated with real keystone data. (E: 38a358facdb89d16d81d48c8520d3d25)");if(!a.rel8ns)throw new Error("(UNEXPECTED) keystoneIbGib.rel8ns falsy? we expect the rel8ns to have ancestor and past. (E: 20cb7723dc33ae1ef808fe76d1bf4b25)");if(!a.rel8ns.past||a.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 a.data.n=0,a.data.isTjp=!0,delete a.rel8ns.tjp,delete a.rel8ns.past,a.gib=await ue({ibGib:a}),await e.put({ibGib:a,space:t}),await e.registerNewIbGib({ibGib:a,space:t}),a}catch(n){throw console.error(`${o} ${E(n)}`),n}finally{_e&&console.log(`${o} complete.`)}}f(za,"createKeystoneIbGibImpl");async function an({keystoneIbGib:r,dependencyGraph:e,getLatest:t,invalidIfMoreRecentKeystoneFoundInSpace:o,space:n}){let a=`[${an.name}]`;try{if(_e&&console.log(`${a} starting... (I: 22e1ca1d5a08a3f90b7fe9da95df7b26)`),!r)throw new Error("(UNEXPECTED) keystoneIbGib falsy? (E: 26482871d529fff6e8899c5d8a6c3826)");let s=[];if(t){let b=y({ibGib:r}),p=await We({ibGibs:[r],space:n});if(!p.data)throw new Error("(UNEXPECTED) resGetLatestAddrs.data falsy? (E: 3a23b3b420a8da1928219ca8d47b2126)");if(!p.data.latestAddrsMap)throw new Error("(UNEXPECTED) resGetLatestAddrs.data.latestAddrsMap falsy? (E: 93f1180598fb65a4b8d36e08d6c50426)");let{latestAddrsMap:h}=p.data;if(Object.keys(h).length===0)throw new Error("(UNEXPECTED) latestAddrsMap truthy but empty? (E: 7142f8f7625b9186281d08251e407826)");let g=h[b];if(g)if(g!==b)if(o)s.push(`${a} more recent keystone (${g}) found than the one passed in (${b}) in space (${n.ib}). (E: 64bf48de9448ee5c7528bf03bed2a826)`);else{let[m]=await it({addrs:[g],space:n});r=m}else _e&&console.log(`${a} incoming keystone (${b}) is the latest in the space (${n.ib}) (I: 8ffbd8d6cbc8a461e5e7f1084bd22a26)`);else console.warn(`${a} keystoneIbGib (${b}) not found in space (${n.ib}). I don't know what the implications of this are. (W: 258c88742448db34a585669484771826)`)}e??=await xt({ibGib:r,space:n});let i=Object.values(e),{mapWithTjp_NoDna:c,mapWithTjp_YesDna:d,mapWithoutTjps:l}=vt({ibGibs:i});if(Object.keys(d).length>0&&s.push(`${a} DNA found. Keystones should NOT have DNA. (E: a3ec7827c4284cdea61c2372c0615826)`),Object.keys(l).length>0&&s.push(`${a} Non-tjp ibgibs found? Keystones are expected to have tjps. (E: a3ec7827c4284cdea61c2372c0615826)`),Object.keys(c).length>0){let b=Object.values(c),p=bt({ibGibs:b}),h=Object.keys(p);if(h.length===0)throw new Error("(UNEXPECTED) orderedKeystonesMap empty? (E: d437b80bef58e83a034b28af46278726)");if(h.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 g=h[0],m=p[g];if(m.length===0)throw new Error("(UNEXPECTED) empty keystoneIbGibs_ordered? (E: 4a6b085aa8a76828a8d65367e7e56526)");if((await nn({keystoneIbGib:m[0]})).forEach(S=>s.push(S)),m.length!==1)for(let S=0;S<m.length-1;S++){let A=m[S],I=m[S+1],$=await po({prevIbGib:A,currentIbGib:I});$.length>0&&(s.push(`${a} keystone has ${$.length} transition errors. i: ${S}. prevIbGib addr: ${y({ibGib:A})}. currentIbGib addr: ${y({ibGib:I})}. (E: 3ac17be916141d0c286ca5a87bb1b426)`),$.forEach(T=>s.push(T)));break}}else if(s.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 s}catch(s){throw console.error(`${a} ${E(s)}`),s}finally{_e&&console.log(`${a} complete.`)}}f(an,"validateKeystoneGraph");var Te=!1,se=class r{static{f(this,"KeystoneService_V1")}lc=`[${r.name}]`;async genesis({masterSecret:e,frameDetails:t,configs:o,metaspace:n,space:a}){let s=`${this.lc}[${this.genesis.name}]`;try{Te&&console.log(`${s} starting... (I: c98ae8adbc5888dbf84c5aced7610b25)`);let i=[];for(let l of o){let b=Ot.create({config:l}),p=await b.derivePoolSecret({masterSecret:e}),h={},g=l.behavior.size,m=Date.now().toString();for(let w=0;w<g;w++){let S=await en({salt:l.salt,timestamp:m,index:w}),A=await b.generateSolution({poolSecret:p,poolId:l.id,challengeId:S}),I=await b.generateChallenge({solution:A});h[S]=I}i.push({id:l.id,config:l,challenges:h})}if(i.length===0)throw new Error("No challenge pools created. (E: 38e538530996940e1f16a8b199995825)");let c={challengePools:i,proofs:[]};return t&&(c.frameDetails=t),await za({data:c,metaspace:n,space:a})}catch(i){throw console.error(`${s} ${E(i)}`),i}finally{Te&&console.log(`${s} complete.`)}}async sign({latestKeystone:e,masterSecret:t,claim:o,poolId:n,poolFilter:a,requiredChallengeIds:s=[],frameDetails:i,metaspace:c,space:d,dataToPatch:l}){let b=`${this.lc}[${this.sign.name}]`;try{Te&&console.log(`${b} starting...`);let p=e.data;if(p.revocationInfo)throw new Error("Keystone has been revoked. Cannot sign. (E: 4f2198c39116d15c48ba191940316825)");let h=tn({pools:p.challengePools,poolId:n,poolFilter:a,verb:o.verb});Te&&console.log(`${b} Selected pool: ${h.id} (size: ${Object.keys(h.challenges).length}) (I: 6b26d6f4aad18380f2b3a0989b592826)`);let g=await rn({pool:h,targetAddr:o.target,requiredChallengeIds:s}),{proof:m,nextPools:w}=await on({targetPoolId:h.id,prevPools:p.challengePools,masterSecret:t,challengeIds:g,claim:o,requiredChallengeIds:s}),S=(p.n??0)+1,A;if(S%Zo===0){let T={...e,data:{...p,frameDetails:i}};A=await this.getAggregateDetails({latestKeystone:T,metaspace:c,space:d})}let I={challengePools:w,proofs:[m],frameDetails:i,checkpointDetails:A,...p.delegates?{delegates:p.delegates}:{},...l};return await ho({prevIbGib:e,newData:I,metaspace:c,space:d})}catch(p){throw console.error(`${b} ${E(p)}`),p}finally{Te&&console.log(`${b} complete.`)}}async validate({currentIbGib:e,prevIbGib:t}){return await po({currentIbGib:e,prevIbGib:t})}async registerDelegate({parentKeystone:e,delegateKeystone:t,masterSecret:o,frameDetails:n,metaspace:a,space:s}){let i=`${this.lc}[${this.registerDelegate.name}]`;try{Te&&console.log(`${i} starting...`);let c=await an({keystoneIbGib:t,getLatest:!0,invalidIfMoreRecentKeystoneFoundInSpace:!1,space:s});if(c.length>0)throw new Error(`Delegate keystone validation failed: ${c.join(", ")} (E: 88fa8ab28c9b60e68994511a5825)`);let d=e.data;if(!d.challengePools.some(m=>m.id===yr))throw new Error("Parent keystone does not support delegation. Manage pool is required. (E: 818fa8ab28c9b60e68994511a5825)");let b=de({ibGib:t});if(!b)throw new Error("(UNEXPECTED) delegateTjpAddr falsy? (E: d4d6e8ad03c8925d4838b9a87b8f2826)");let p={target:b,verb:Nt},h=d.delegates?{...d.delegates}:{};return h[b]={delegateTjpAddr:b,delegateAddr:y({ibGib:t}),thisAddr:y({ibGib:e})},await this.sign({latestKeystone:e,masterSecret:o,claim:p,poolId:yr,frameDetails:n,metaspace:a,space:s,dataToPatch:{delegates:h}})}catch(c){throw console.error(`${i} ${E(c)}`),c}finally{Te&&console.log(`${i} complete.`)}}async unregisterDelegate({parentKeystone:e,delegateTjpAddr:t,masterSecret:o,frameDetails:n,metaspace:a,space:s}){let i=`${this.lc}[${this.unregisterDelegate.name}]`;try{Te&&console.log(`${i} starting...`);let c=e.data;if(!c.challengePools.some(h=>h.id===yr))throw new Error("Parent keystone does not support delegation. Manage pool is required. (E: 3889f8ab28c9b60e68994511a5825)");let l={target:t,verb:Nt},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:l,poolId:yr,frameDetails:n,metaspace:a,space:s,dataToPatch:{delegates:b}})}catch(c){throw console.error(`${i} ${E(c)}`),c}finally{Te&&console.log(`${i} complete.`)}}async getDelegateStatus({parentTjpAddr:e,delegateTjpAddr:t,metaspace:o,space:n}){let a=`${this.lc}[${this.getDelegateStatus.name}]`;try{Te&&console.log(`${a} starting...`);let{ib:s,gib:i}=ne({ibGibAddr:e}),d=await We({ibGibs:[{ib:s,gib:i}],space:n});if(!d.data?.latestAddrsMap)return{registered:!1};let l=d.data.latestAddrsMap[e];if(!l)return{registered:!1};let p=(await o.get({addr:l,space:n})).ibGibs?.at(0);if(!p||!p.data)return{registered:!1};let g=(p.data.delegates||{})[t];return{registered:!!g,delegateInfo:g}}catch(s){throw console.error(`${a} ${E(s)}`),s}finally{Te&&console.log(`${a} complete.`)}}async validateGenesisKeystone({keystoneIbGib:e}){return await nn({keystoneIbGib:e})}async getLatestKeystone({addr:e,metaspace:t,space:o}){let n=`${this.lc}[${this.getLatestKeystone.name}]`;try{Te&&console.log(`${n} starting...`);let a=await t.getLatestAddr({tjpAddr:e,space:o});if(!a)throw new Error(`could not find latest addr for ${e}`);let s=await t.get({addr:a,space:o});if(s.success&&s.ibGibs&&s.ibGibs.length>0)return s.ibGibs[0];{let c=s.rawResultIbGib?.data?.addrsNotFound??"unknown";throw new Error(`couldn't find latest keystone at ${a}. addrsNotFound: ${c}? resGet.errorMsg: ${s.errorMsg}`)}}catch(a){throw console.error(`${n} ${E(a)}`),a}finally{Te&&console.log(`${n} complete.`)}}async validateKeystoneGraph({keystoneIbGib:e,dependencyGraph:t,getLatest:o,invalidIfMoreRecentKeystoneFoundInSpace:n,space:a}){let s=`${this.lc}[${this.validateKeystoneGraph.name}]`;try{return Te&&console.log(`${s} starting... (I: 01c5cd455038c270cbf1effc1704af26)`),await an({keystoneIbGib:e,dependencyGraph:t,getLatest:o,invalidIfMoreRecentKeystoneFoundInSpace:n,space:a})}catch(i){throw console.error(`${s} ${E(i)}`),i}finally{Te&&console.log(`${s} complete.`)}}async revoke({latestKeystone:e,masterSecret:t,reason:o="User initiated revocation",frameDetails:n,metaspace:a,space:s}){let i=`${this.lc}[${this.revoke.name}]`;try{Te&&console.log(`${i} starting...`);let c=e.data,d=tn({pools:c.challengePools,poolId:Wa}),l={verb:Jo,target:y({ibGib:e})},b=await rn({pool:d,targetAddr:l.target,requiredChallengeIds:[]});if(b.length===0)throw new Error(`Revocation policy selected 0 challenges? Check config for pool ${d.id}. Revocation requires proof. (E: 97e5a8356d241ae7b882db791cb1f825)`);let{proof:p,nextPools:h}=await on({targetPoolId:d.id,prevPools:c.challengePools,masterSecret:t,challengeIds:b,claim:l,requiredChallengeIds:[]});h.find(I=>I.id===d.id&&Object.keys(I.challenges).length>0)&&console.warn(`${i} revocation pool ${d.id} is not empty after revocation. Is the revocation pool replenish strategy set to ${De.deleteAll}? (W: 300c28bc8b98fc3e3c0b0d988344f825)`);let g={reason:o,proof:p},m=(c.n??0)+1,w;if(m%Zo===0){let I={...e,data:{...c,frameDetails:n,revocationInfo:g}};w=await this.getAggregateDetails({latestKeystone:I,metaspace:a,space:s})}let S={challengePools:h,proofs:[p],revocationInfo:g,frameDetails:n,checkpointDetails:w,...c.delegates?{delegates:c.delegates}:{}};return await ho({prevIbGib:e,newData:S,metaspace:a,space:s})}catch(c){throw console.error(`${i} ${E(c)}`),c}finally{Te&&console.log(`${i} complete.`)}}async addPools({latestKeystone:e,masterSecret:t,newPools:o,metaspace:n,space:a}){let s=`${this.lc}[${this.addPools.name}]`;try{if(Te&&console.log(`${s} starting...`),!e.data)throw new Error("(UNEXPECTED) latestKeystone.data falsy? (E: 7334c8faed128166a999d428c7805b25)");let i=e.data;if(i.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=tn({pools:i.challengePools,verb:Nt});Te&&console.log(`${s} Authorized via pool: ${c.id}`);let d=y({ibGib:e}),l={verb:Nt,target:d,scope:JSON.stringify({add:o.map($=>$.id)})},b=await rn({pool:c,targetAddr:d}),{proof:p,nextPools:h}=await on({targetPoolId:c.id,prevPools:i.challengePools,masterSecret:t,challengeIds:b,claim:l}),g=new Set(h.map($=>$.id));for(let $ of o)if(g.has($.id))throw new Error(`Cannot add pool. ID collision: ${$.id} (E: 8a4c2b1d3e5f6a7b8c9d0e1f2a3b4c5d)`);let m=[...h,...o],w=(i.n??0)+1,S;if(w%Zo===0){let $={...e,data:{...i,challengePools:m}};S=await this.getAggregateDetails({latestKeystone:$,metaspace:n,space:a})}let A={challengePools:m,proofs:[p],checkpointDetails:S,...i.delegates?{delegates:i.delegates}:{}};return await ho({prevIbGib:e,newData:A,metaspace:n,space:a})}catch(i){throw console.error(`${s} ${E(i)}`),i}finally{Te&&console.log(`${s} complete.`)}}async getAggregateDetails({latestKeystone:e,metaspace:t,space:o}){let n=`${this.lc}[${this.getAggregateDetails.name}]`;try{let a={},s=e;for(;s;){let i=s.data;if(i.checkpointDetails){a=xr({dominant:a,recessive:i.checkpointDetails});break}if(i.frameDetails&&(a=xr({dominant:a,recessive:i.frameDetails})),i.n===0)break;let c=s.rel8ns?.past,d=c&&c.length>0?c[c.length-1]:void 0;if(!d)break;let l=await t.get({addr:d,space:o});if(!l.success||!l.ibGibs||l.ibGibs.length===0)throw new Error(`Could not find previous keystone frame at ${d} (E: e3d069b22e11e550e58844889ddb5325)`);s=l.ibGibs[0]}return a}catch(a){throw console.error(`${n} ${E(a)}`),a}}};var sn="sync",Be="syncmsg",Ja="@payloadAddrsDomain",Jf="init",Zf="ack",Qf="delta",eb="commit",me={init:Jf,ack:Zf,delta:Qf,commit:eb},ny=Object.values(me),tb="abort",rb="optimistic-graft-longest-common-subsequence",X={abort:tb,optimisticWithLCS:rb},Ir=Object.values(X);function cn(r){return Ir.includes(r)}f(cn,"isValidSyncConflictStrategy");var ob="push",nb="pull",ab="sync",Za={push:ob,pull:nb,sync:ab},ly=Object.values(Za);var sb="sender",ib="receiver",ln={sender:sb,receiver:ib},dy=Object.values(ln);var Xc=!1;function Qa({base:r,extended:e,throwIfExtendedDoesntContainBase:t}){let o=`[${Qa.name}]`;try{Xc&&console.log(`${o} starting... (I: 00d70d79a0249165c2a230389c962526)`);let n=!0;for(let s=0;s<r.length;s++)if(r[s]!==e[s]){n=!1;break}if(t&&!n)throw new Error(`base addrs do not correspond to extended addrs. We were expecting the base to be the exact start of the extended strand, e.g., base [a, b, c] with extended [a, b, c, d, e]. base: ${r}. extended: ${e}. (E: fb80b40003289bbf1aaedd4829fa1826)`);let a;if(n)a=e.slice(r.length);else{a=[];for(let s of e)r.includes(s)||a.push(s)}return a}catch(n){throw console.error(`${o} ${E(n)}`),n}finally{Xc&&console.log(`${o} complete.`)}}f(Qa,"getUniqueDnas");async function dn({src:r,createdIbGibs_Running:e,dnaAddrsToApplyToStoreVersion_MUTATES_IN_PLACE:t,allLocalIbGibs:o}){let n=`[${dn.name}]`;try{if(t.length>0){let a=t.splice(0,1)[0],s=o.filter(l=>y({ibGib:l})===a),i;if(s.length>0)i=s[0];else throw new Error(`dna ibGib not found in supplied allLocalIbGibs. dnaAddr: ${a}. (E: 7f56826852cf48a79ab8af16bf27e284)`);let c=H(i.data);c.src=r,c.srcAddr=y({ibGib:r});let d;switch(c.type){case"mut8":d=await at(c);break;case"rel8":d=await Xe(c);break;case"fork":throw new Error("fork transform not expected. atow only a single fork is expected at the beginning of the lifetime of a tjp ibgib. This fork defines the uniqueness of the tjp ibgib. When merging another tjp ibgib, we would only expect update transforms to be mut8 or rel8. (E: f8ad6996ac5545edad2d58a293d37d94)");default:throw new Error(`unknown dna argTransform.type (${c.type}) for dna address: ${a}. Expecting either mut8 or rel8. (fork transform is known but not expected either.) (E: 52a98db56e934e4cb42c64e2f45fa552)`)}if((d.intermediateIbGibs??[]).forEach(l=>e.push(l)),(d.dnas??[]).forEach(l=>e.push(l)),e.push(d.newIbGib),(d.dnas??[]).length>0){if(!d.dnas.some(l=>y(l)===a))throw new Error(`${n}(UNEXPECTED) Expected to generate exact dna that we applied in transform. dnaAddr: ${a} (E: 4a364c0b5d8d46c8af6bd540915fd973)`)}else console.warn(`${n}(UNEXPECTED) expected resTransform to include generated dna. dnaAddr: ${a}(W: 9648e2d5c40d42b7b9fb7efb09c5b13a)`);return await dn({src:d.newIbGib,createdIbGibs_Running:e,dnaAddrsToApplyToStoreVersion_MUTATES_IN_PLACE:t,allLocalIbGibs:o})}else return e.length===0&&console.warn(`${n} no dna transforms to apply but createdIbGibs_Running is empty. Dna is expected to start with at least one transform, otherwise don't call this function. (W: 52c7f2f6bd7e4bd0b31f53611b90268b)(UNEXPECTED)`),r}catch(a){throw console.error(`${n} ${E(a)}`),a}}f(dn,"applyTransforms");var jr="graftinfo",$t=jr,qc="latestcommonaddr",rr="base",Lt="orphan",Wc="dnaapplied",cb="longest-common-subsequence",es={lcs:cb},yy=Object.values(es);var et=!0;async function lb({data:r}){if(!r.conflictStrategy)throw new Error("(UNEXPECTED) data.conflictStrategy required for GraftInfoIb (E: 2c0968a0dac8d0ab3d67da9756d6df26)");if(!cn(r.conflictStrategy))throw new Error(`invalid data.conflictStrategy (${r.conflictStrategy}). valid conflict strategies: ${Ir} (E: 41e2680089786d4d28046b4c0884bd26)`);return[jr,r.conflictStrategy].join(" ")}f(lb,"getGraftInfoIb");async function Yc({conflictStrategy:r,details:e,addlGraftDetails:t,latestCommonFrameAddr:o,baseAddrsSinceLCA:n,orphanAddrsSinceLCA:a,dnaAddrsApplied:s}){let i=`[${Yc.name}]`;try{if(et&&console.log(`${i} starting... (I: 0030f62cbae28cf5882f87981edc3826)`),n.length===0)throw new Error("(UNEXPECTED) baseAddrsSinceLCA empty? (E: 005f8449a9236d445902a148f59fc826)");if(a.length===0)throw new Error("(UNEXPECTED) orphanAddrsSinceLCA empty? (E: 19e4082e82c67759c880392aca186826)");let c={conflictStrategy:r,description:e};t&&(c.addlGraftDetails=t);let d={[qc]:[o],[rr]:n.concat(),[Lt]:a.concat(),[Wc]:s.concat()},l=await lb({data:c});return await F.stone({parentPrimitiveIb:jr,ib:l,data:c,rel8ns:d,uuid:!0})}catch(c){throw console.error(`${i} ${E(c)}`),c}finally{et&&console.log(`${i} complete.`)}}f(Yc,"createGraftInfo");async function db({textA:r,textB:e}){if(r===e)return r;if(r==="")return e;if(e==="")return r;function t(d,l){let b=d.length,p=l.length,h=Array(b+1).fill(0).map(()=>Array(p+1).fill(0));for(let S=1;S<=b;S++)for(let A=1;A<=p;A++)d[S-1]===l[A-1]?h[S][A]=h[S-1][A-1]+1:h[S][A]=Math.max(h[S-1][A],h[S][A-1]);let g=b,m=p,w=[];for(;g>0&&m>0;)d[g-1]===l[m-1]?(w.unshift({line:d[g-1],indexA:g-1,indexB:m-1}),g--,m--):h[g-1][m]>h[g][m-1]?g--:m--;return w}f(t,"longestCommonSubsequence");let o=r.split(`
21
+ `),n=e.split(`
22
+ `),a=t(o,n),s=[],i=0,c=0;for(let d of a){for(;i<d.indexA;)s.push(o[i]),i++;for(;c<d.indexB;)s.push(n[c]),c++;s.push(d.line),i++,c++}for(;i<o.length;)s.push(o[i]),i++;for(;c<n.length;)s.push(n[c]),c++;return s.join(`
23
+ `)}f(db,"mergeTextByLongestCommonSubsequence");async function ts({timelineAddrsA:r,timelineAddrsB:e,latestCommonFrameAddr:t,conflictStrategy:o,ibGibReadCache:n,space:a}){let s=`[${ts.name}]`;try{let A=function(ye){let Rt=`${s}[${A.name}]`;for(let ze of ye){if(!ze.rel8ns)throw new Error(`(UNEXPECTED) ${Rt} someIbGib.rel8ns falsy? All ibgibs with mergeable timelines are expected to have rel8ns. addr: ${y({ibGib:ze})} (E: 5534a478cd183a5ee27b28487448b226)`);if(!ze.rel8ns.dna)throw new Error(`(UNEXPECTED) someIbGib.rel8ns.dna falsy? We only have implemented grafting for dna. addr: ${y({ibGib:ze})} (there should be another route for merging for non-dna timelines) (E: d86b388c627afd613f897e3819d8ab26)`);if(ze.rel8ns.dna.length===0)throw new Error(`(UNEXPECTED) someIbGib.rel8ns.dna.length === 0? We only have implemented grafting for dna. addr: ${y({ibGib:ze})} (there should be another route for merging for non-dna timelines) (E: bf973662a0689dd9089912b861af2826)`)}};var i=A;f(A,"throwIfUnexpected"),et&&console.log(`${s} starting... (I: 3b4c3e8e59c883d9d3c352efd6380826)`);let c=[],d=[];if(r.length===0)throw new Error("timelineAddrsA empty (E: 93a78cd1cd2a4a16ba99bd4820468f26)");if(e.length===0)throw new Error("timelineAddrsB empty (E: 76d53848152a66971b734068c3316826)");if(t){if(!r.includes(t))throw new Error(`timelineAddrsA does not include latestCommonFrameAddr (${t}). timelineAddrsA: ${r} (E: c5a9afe371888da2a79963983426e826)`);if(!e.includes(t))throw new Error(`timelineAddrsB does not include latestCommonFrameAddr (${t}). timelineAddrsB: ${e} (E: 7e641f67c452b67d582d78484a88c826)`)}else if(t=r.findLast(ye=>e.includes(ye)),!t)throw new Error(`timelines do not share a common frame. A: ${r}. B: ${e} (E: 4c0e78a88a375d8588736668573f1e26)`);if(r.at(-1)===t){debugger;throw new Error("timelineAddrsA.at(-1) === latestCommonFrameAddr. Graft requires a branch BEYOND the LCA (E: 3796fc4074a8c5899d549bb8c2e68826)")}if(e.at(-1)===t)throw new Error("timelineAddrsB.at(-1) === latestCommonFrameAddr. Graft requires a branch BEYOND the LCA (E: 66fbb86e9e98531549888bf10a344f26)");let l=r.lastIndexOf(t),b=r.slice(l+1),p=await it({readCache_graph:n,addrs:b,space:a}),h=p.at(-1),g=e.lastIndexOf(t),m=e.slice(g+1),w=await it({readCache_graph:n,addrs:m,space:a}),S=w.at(-1);A(p),A(w);let I,$,T,_,G=Qt({ibGib:h}),v=G.valid?Number.parseInt(G.ticks):Number.MAX_SAFE_INTEGER,N=G.valid?G.ms??0:0,D=Qt({ibGib:S}),B=D.valid?Number.parseInt(D.ticks):Number.MAX_SAFE_INTEGER,P=D.valid?D.ms??0:0;v<B?(I=h,$=p,T=S,_=w):v>B?(I=S,$=w,T=h,_=p):N<=P?(I=h,$=p,T=S,_=w):(I=S,$=w,T=h,_=p);let k=y({ibGib:I}),M=$.map(ye=>y({ibGib:ye})),j=y({ibGib:T}),Q=_.map(ye=>y({ibGib:ye}));et&&console.log(`${s} baseTipAddr: ${k} (I: 93353d9b9b68b17088f57958df85e826)`),et&&console.log(`${s} orphanTipAddr: ${j} (I: 14df8867adc5dab97ff3c1e989b40e26)`);let[ee]=await it({addrs:[t],space:a});if(!ee)throw new Error("(UNEXPECTED) latestCommonFrameIbGib falsy? (E: ead2020b7ab8e4c4f824573133e33826)");if(!ee.rel8ns)throw new Error("(UNEXPECTED) latestCommonFrameIbGib.rel8ns falsy? (E: b3f338032d19816fc87d3c78af255726)");if(!ee.rel8ns.dna||ee.rel8ns.dna.length===0)throw new Error("(UNEXPECTED) latestCommonFrameIbGib.rel8ns.dna falsy/empty? It should at least have the first fork transform. (E: 98fd8c725f484d85c8d23ceb181ce826)");let Ge=ee.rel8ns.dna.concat(),Ce=[];for(let ye of _){if(!ye.rel8ns)throw new Error("(UNEXPECTED) orphanFrame.rel8ns falsy? (E: ed910e3b930b1b5388d87c6f736a4826)");let Rt=Qa({base:Ge,extended:ye.rel8ns.dna??[],throwIfExtendedDoesntContainBase:!0});if(Rt.forEach(ze=>Ge.push(ze)),Rt.length===0)throw new Error("(UNEXPECTED) orphanDnaAddrsToApply empty? (E: d44ed439e538e5b538d12d71063f0826)");Rt.forEach(ze=>Ce.push(ze))}let Me=await it({addrs:Ce,readCache_graph:n,space:a}),Fe=[],pe=await dn({src:I,dnaAddrsToApplyToStoreVersion_MUTATES_IN_PLACE:Ce.concat(),allLocalIbGibs:Me,createdIbGibs_Running:Fe});if(!pe.data)throw new Error("(UNEXPECTED) graftTip_sansGraftInfo.data falsy? (E: 4792f8e84fc84966e89220fae0657826)");if(!pe.data.n)throw new Error("(UNEXPECTED) graftTip_sansGraftInfo.data.n falsy? (E: a2b3ca4cdec8d01f282dd3e4ff9eab26)");if(Fe.length===0)throw new Error("(UNEXPECTED) applyTransforms called but createdIbGibs_Running is empty? This should contain all of the (E: 5b6c788488f5095b08eb8e31d55b1726)");console.warn(`${s} START...................... Do we get a bunch of "already had addr(s)" messages for dna ibgibs? I'm thinking we will already have the dna ibgibs stored in the space (temp space?) before we do this graft. Maybe it creates new dna, I don't know. remove this later when we decide something to do about it. space.ib: ${a.ib} (W: bb60481ecabaa6f49e14203891824a26)`),await qe({space:a,ibGibs:Fe}),console.warn(`${s} END........................ Do we get a bunch of "already had addr(s)" messages for dna ibgibs? I'm thinking we will already have the dna ibgibs stored in the space (temp space?) before we do this graft. Maybe it creates new dna, I don't know. remove this later when we decide something to do about it. space.ib: ${a.ib} (W: bb60481ecabaa6f49e14203891824a26)`);let{mapWithTjp_NoDna:He,mapWithTjp_YesDna:tt,mapWithoutTjps:he}=vt({ibGibs:Fe});if(Object.keys(He).length>0)throw new Error("(UNEXPECTED) mapWithTjp_NoDna is populated? We've just applied the dna from the orphan branch which created ibgibs (and dnas). But we are expected to be executing on an ibgib timeline that has dna. The applyTransforms was not expected to create any other ibgibs than the one in our timeline (with dna) and any corresponding dnas. (E: 236e989fb5e8a4a498a21b98f718c826)");let rt=Object.values(tt),lt=bt({ibGibs:rt});if(Object.keys(lt).length===0)throw new Error("(UNEXPECTED) newGraftedIbGibsByTjp has 0 timelines? we expect this to have a single timeline: the one we're grafting. (E: 2b7127bd0c6bfeaec8d66038ba208226)");if(Object.keys(lt).length>1)throw new Error("(UNEXPECTED) newGraftedIbGibsByTjp has more than one timeline? we expect this to have a single timeline: the one we're grafting. (E: 076758885b8ea7c89849a76334222326)");Object.values(lt)[0].forEach(ye=>c.push(ye));for(let ye of c)await xe({ibGib:ye,space:a});let vr;if(o===X.optimisticWithLCS){if(!I.data)throw new Error("(UNEXPECTED) baseTip.data falsy? (E: 92623857e19b9b4e081e8c8d9eb45526)");if(!T.data)throw new Error("(UNEXPECTED) orphanTip.data falsy? (E: 2e6828a4c9226ac917ab6fe833672826)");if((T.data.text||I.data.text)&&T.data.text!==I.data.text){et&&console.log(`${s} different data.text found. executing text merge for conflictStrategy ${o} (I: cfb5f9580832040388fc576eb71ac526)`);let ye=T.data.text??"",Rt=j,ze=I.data.text??"",Vn=k,Hn=await db({textA:ye,textB:ze}),ot=await at({src:pe,dataToAddOrPatch:{text:Hn},dna:!0,nCounter:!!pe.data.n});if(ot.intermediateIbGibs&&ot.intermediateIbGibs.length>0)throw new Error("(UNEXPECTED) resMut8Text.intermediateIbGibs truthy/non-empty? This is expected to only create the newIbGib with no intermediates. (E: 7932a8964a3869accadc9b0d93d23826)");if(!ot.dnas||ot.dnas.length===0)throw new Error("(UNEXPECTED) resMut8Text.dnas falsy/empty? We're expected to generate dna from this merge text mut8. (E: fdf03754bf0f8661f80f59ea0701dd26)");if(ot.dnas.length!==1)throw new Error("(UNEXPECTED) resMut8Text.dnas.length !== 1? we're expecting a single mut8 dna. (E: 9574d86a9108095cb454b049bcca5326)");if(d.push(ot.dnas[0]),c.push(ot.newIbGib),await Ie({resTransform:ot,space:a}),await xe({ibGib:ot.newIbGib,space:a}),vr={mergeTextStrategy:es.lcs,textAAddr:Rt,textBAddr:Vn},pe=ot.newIbGib,!pe.data)throw new Error("(UNEXPECTED) graftTip_sansGraftInfo.data falsy after mut8 merge text? (E: 6b65d83df6681887686a0098144eea26)")}}let pr=await Yc({conflictStrategy:o,details:`Replayed ${Ce.length} transforms from orphan (${j}) onto base (${k}).`,addlGraftDetails:vr?[vr]:void 0,latestCommonFrameAddr:t,baseAddrsSinceLCA:M,orphanAddrsSinceLCA:Q,dnaAddrsApplied:Ce});et&&console.log(`${s} intrinsic graft complete. graftInfo to be appended to timeline:
24
+ ${K(pr)} (I: ab9d1e73db9a3ff4f8241f38197bb826)`),await qe({ibGib:pr,space:a});let qr=y({ibGib:pr}),gt=await Xe({src:pe,rel8nsToAddByAddr:{[$t]:[qr]},dna:!0,nCounter:!!pe.data.n});if(gt.intermediateIbGibs&&gt.intermediateIbGibs.length>0)throw new Error("(UNEXPECTED) resRel8GraftInfo.intermediateIbGibs truthy/non-empty? This is expected to only create the newIbGib with no intermediates. (E: 78b928ace4287b4dc82f413fdad60826)");if(!gt.dnas||gt.dnas.length===0)throw new Error("(UNEXPECTED) resRel8GraftInfo.dnas falsy/empty? We're expected to generate dna from this rel8. (E: 4c8fdde70368d643f86732dfa48c5526)");if(gt.dnas.length!==1)throw new Error("(UNEXPECTED) resRel8GraftInfo.dnas.length !== 1? we're expecting a single rel8 dna. (E: c2f5085c1718d7149e04f5c814027926)");d.push(gt.dnas[0]),await Ie({resTransform:gt,space:a}),await xe({ibGib:gt.newIbGib,space:a});let wo=gt.newIbGib;et&&console.log(`${s} finalGraftTip: ${K(wo)} (I: 454e72957be8221b96931c289053fc26)`);let Wr={dnasReplayed:Me,dnasCreatedInGraft:d,intermediateIbGibsCreatedInGraft:c,newGraftTip:wo,graftInfoCreated:pr};return et&&console.log(`${s} result... (I: d6a02f95eb2564c621810ef855434226)`),et&&console.dir(Wr),Wr}catch(c){throw console.error(`${s} ${E(c)}`),c}finally{et&&console.log(`${s} complete.`)}}f(ts,"graftTimelines");function rs(r){let e=`[${rs.name}]`;try{if(et&&console.log(`${e} starting... (I: fe9adfe1a3175d87982507c8851f5826)`),!r)throw new Error("(UNEXPECTED) not a graft info, ibGib falsy? (E: bf06cdd700788e777f72fe5a5bdb0e26)");if(!r.data)throw new Error("not a graft info, ibGib.data falsy (E: 5e1b28843ec8571a7623046a06195826)");if(!r.ib.startsWith(jr))throw new Error(`not graft info, ibgib.ib does not start with ${jr} (E: cec6a8e25ff8746aef813e38cbebce26)`);return!0}catch(t){return et&&console.error(`${e} ${E(t)}`),!1}finally{et&&console.log(`${e} complete.`)}}f(rs,"isGraftInfo");var Ae=!1;async function os({data:r}){let e=`[${os.name}]`;try{return[sn,r.uuid].join(" ")}catch(t){throw console.error(`${e} ${E(t)}`),t}}f(os,"getSyncIb");async function zc(){return`tmp_sync_space_${(await U()).substring(0,8)}`}f(zc,"getTempSpaceName");async function Vr({olderAddr:r,newerAddr:e,space:t}){let o=`[${Vr.name}]`;try{if(Ae&&console.log(`${o} starting... (I: 4b3548cbc9a2eb749f447ed82fdcf826)`),r===e)return!0;let n,a=await te({space:t,addr:e});if(a.success&&a.ibGibs?.length===1)n=a.ibGibs[0];else throw new Error(`couldn't get newerAddr (${e}) from space (${t.ib}). (E: 36c758c22b181b2c89a1cd28937a6826)`);if(!n.rel8ns)return console.warn(`${o} newerIbGib.rel8ns falsy? newerAddr: ${e}. (W: 6f920811f7080281189f767813814826)`),!1;let s=n.rel8ns.past??[];if(s.length===0)return!1;if(s.includes(r))return!0;let i=s[0];return await Vr({olderAddr:r,newerAddr:i,space:t})}catch(n){throw console.error(`${o} ${E(n)}`),n}finally{Ae&&console.log(`${o} complete.`)}}f(Vr,"isPastFrame");async function fn({sagaIbGib:r,localSpace:e}){let t=`[${fn.name}]`,o=f(async i=>{let c=await te({space:e,addrs:i});if(c.success&&c.ibGibs?.length===i.length)return c.ibGibs;{let d=c.rawResultIbGib;throw d.data?new Error(`(UNEXPECTED) couldn't find addrs? addrsNotFound: ${d.data.addrsNotFound}? space.ib: ${e.ib} (E: 43b7b5a6ad982715c8f3eed69bfa0d26)`):new Error("(UNEXPECTED) resGet.rawResultIbGib.data falsy? (E: c26c681d2f831fc537ba6f48fee36d26)")}},"fnGet"),n=await bn({sagaIbGib:r});if(n.length>0)throw new Error(`invalid sync sagaIbGib. validationErrors: ${n} (E: 19f9e8c9643858ff41312b62293d2126)`);if(!r.rel8ns)throw new Error("(UNEXPECTED) validated sagaIbGib.rel8ns falsy? (E: 73af48be8bbf271ec5cf78187ce8c826)");let a=r.rel8ns[Be],s=await o(a);return{sagaIbGib:r,msgStones:s}}f(fn,"getSyncSagaFrameDependencyGraph");async function Hr({sagaIbGib:r,space:e}){let t=`[${Hr.name}]`;try{if(Ae&&console.log(`${t} starting... (I: 1ea3f804dd07d1e917a2afaaad497826)`),!r.data)throw new Error("(UNEXPECTED) sagaIbGib.data falsy? (E: fe0a0d0965e87ac852fe7ba4710cc826)");if(!r.rel8ns)throw new Error("(UNEXPECTED) sagaIbGib.rel8ns falsy? (E: b79ff82a732346bdf8a9e1eb9ac96826)");let o=y({ibGib:r}),n=r.rel8ns.past&&r.rel8ns.past.length>0?[...r.rel8ns.past,o]:[o],a=[];for(let s of n){let i,c=await te({addr:s,space:e});if(c.success&&c.ibGibs&&c.ibGibs.length===1)i=c.ibGibs[0];else throw Ae&&console.log(`${t} failed getting full history of sagaIbGib:
25
+ ${K(r)} (I: 2a35685bfe038f63182c7db39b44c826)`),new Error(`couldn't get saga addr (${s}) from space (${e.ib}) (E: 865b78ecd918c244158813650bea7d26)`);let d=await fn({sagaIbGib:i,localSpace:e});a.push(d)}return Ae&&console.log(`${t} resGraphs:...
26
+ ${K(a).split(`
27
+ `).join(`
28
+ `)}
29
+ ...(I: d8e11827d88a3454d887ff05fb4ff526)`),a}catch(o){throw console.error(`${t} ${E(o)}`),o}finally{Ae&&console.log(`${t} complete.`)}}f(Hr,"getFullSyncSagaHistory");async function bn({sagaIbGib:r}){let e=`[${bn.name}]`;try{Ae&&console.log(`${e} starting... (I: dac978e9ec5820f128fbbff817b82826)`);let t=await ge({ibGib:r})??[];if(t.length>0)return t;if(r.data){let{data:o}=r;o.uuid||t.push("data.uuid required (E: aa24eeda7b88d22e5832a2e8083c0826)"),o.timestamp||t.push("data.timestamp required (E: 9c82a88548f4b63c38687428754b3826)"),o.timestampMs||o.timestampMs===0||t.push("data.timestampMs required (E: 9c82a88548f4b63c38687428754b3826)"),o.conflictStrategy?cn(o.conflictStrategy)||t.push(`data.conflictStrategy (${o.conflictStrategy}) is invalid. Must be one of "${Ir}". (E: 6223a8813b688fa2c8644fa8a491bf26)`):t.push("data.conflictStrategy required (E: 9c82a88548f4b63c38687428754b3826)"),o.expirationTimestamp,o.errors,o.successCount}else t.push("sagaIbGib.data falsy (E: 4de5e8de589d0af7245600fb4fe30926)");if(r.rel8ns){let o=r.rel8ns[Be];o&&o.length>0||t.push("sagaIbGib.rel8ns[SYNC_MSG_REL8N_NAME] required. (E: df648dc18148e718682acb4842ecf826)")}else t.push("sagaIbGib.rel8ns falsy (E: da37aa492a7275b68a5e1912c7a5e126)");return t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Ae&&console.log(`${e} complete.`)}}f(bn,"validateSyncSagaFrame");async function pn({history:r}){let e=`[${pn.name}]`;try{return Ae&&console.log(`${e} starting... (I: df02b802f6989096b8d8f728e2c0a526)`),console.error(`${e} NAG ERROR (NOT THROWN) need to implement more validation on full saga history. (E: 9bfcc9247a1c783fd361a4a8216fef26)`),[]}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Ae&&console.log(`${e} complete.`)}}f(pn,"validateFullSyncSagaHistory");async function hn({ibGibs:r,space:e}){let t=`[${hn.name}]`;try{Ae&&console.log(`${t} starting... (I: aa3ab828402836b3914800a8ffa1b826)`);let o=[],n=[];for(let a of r)$e({ibGib:a})||(zn({ibGib:a})?o.push(a):n.push(a));return o.length>0&&await qe({ibGibs:o,isDna:!0,space:e}),n.length>0&&await qe({ibGibs:n,isDna:!1,space:e}),{payload_Dnas:o,payload_NonDnas:n}}catch(o){throw console.error(`${t} ${E(o)}`),o}finally{Ae&&console.log(`${t} complete.`)}}f(hn,"putInSpace_dnasThenNonDnas");function Kr({sagaFrame:r}){let e=`[${Kr.name}]`;try{if(Ae&&console.log(`${e} starting... (I: 93521332d0dd2f5e88398b7db95e8126)`),!r)throw new Error("(UNEXPECTED) sagaFrame falsy? (E: 01fb28be6668d88ea49bb298c739c926)");if(!r.data)throw new Error("(UNEXPECTED) sagaFrame.data falsy? (E: 998298eb17685bdb9a85b46488ccd826)");if(!r.data.n&&r.data.n!==0)throw new Error("(UNEXPECTED) sagaFrame.data.n falsy and not 0? (E: 0394919d5b58300ceb09ba6a264ad826)");let t=r.data.n%2;if(t===0)return ln.sender;if(t===1)return ln.receiver;throw new Error("(UNEXPECTED) modulo is neither 0 nor 1? my logic sucks! This was way too defensive on my part... (E: 559488a2eef8d17b57079ca8886ee826)")}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Ae&&console.log(`${e} complete.`)}}f(Kr,"getSyncSagaFrameOrigin");async function un({sagaHistory:r}){let e=`[${un.name}]`;try{Ae&&console.log(`${e} starting... (I: fe93a8f29e5d8ab2c8bd0e08e56f7826)`);let t=r.findLast(a=>a.msgStones.some(s=>s.data.stage===me.delta));if(!t)throw new Error("(UNEXPECTED) no delta frame? What are we calling this function for? (E: 9b3201207908f79868b93cd893a91626)");let o=t.msgStones.filter(a=>a.data.stage===me.delta);if(o.length>1)throw new Error("(UNEXPECTED) multiple delta stones in history slice? we're expecting a single delta stone per saga frame. (E: a4bd5860b4aa0743753d4798d3163826)");return o[0].data.conflicts}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Ae&&console.log(`${e} complete.`)}}f(un,"getFinalConflictsInfo");async function ns({sagaHistory:r,myTempSpace:e}){let t=`[${ns.name}]`;try{Ae&&console.log(`${t} starting... (I: b755627e99c9a221566d86a81b0da526)`);let o=await un({sagaHistory:r});if(!o||o.length===0)return Ae&&console.log(`${t} no conflicts found. returning empty array (I: 5dce98010128a284c8ec92cd466a3826)`),[];let n=[];for(let a of o){if(!a.resolved)throw new Error("(UNEXPECTED) conflict.resolved falsy? we're expecting all conflicts to be resolved when getting orphaned addresses. (E: 3861e89a18c8ff405eb2117f6d4b9b26)");if(!a.graftInfoAddr)throw new Error("(UNEXPECTED) conflict.graftInfoAddr falsy? we're expecting a resolved conflict whose final ibgib (graft tip) was the graft info and for this addr to be in conflict.graftInfoAddr. (E: 80d86e333028585908f4757bc4d6f826)");let s=await it({addrs:[a.graftInfoAddr],space:e});if(s.length!==1)throw new Error(`(UNEXPECTED) couldn't get conflict.graftInfoAddr (${a.graftInfoAddr}) from myTempSpace (${e.ib})? (E: cf1fe87096f8ea22f84f250d7ab30226)`);let i=s[0];if(!rs(i))throw new Error(`(UNEXPECTED) graft info from conflict.graftInfoAddr (${a.graftInfoAddr}) does not pass the isGraftInfo guard? We're expecting this addr to point to a valid GraftInfoIbGib_V1 (E: 6aa9ecb9a428d92be8d1bdbe0696f826)`);let c=i.rel8ns[Lt];if(!c||c.length===0)throw new Error(`(UNEXPECTED) orphanedAddrs empty for conflict graftInfo (${a.graftInfoAddr})? we're expecting a graft to always necessarily orphan one or other branches, otherwise what are we "grafting"? (E: 3ed1284f6ca84754582801484d751926)`);c.forEach(d=>n.push(d))}return n}catch(o){throw console.error(`${t} ${E(o)}`),o}finally{Ae&&console.log(`${t} complete.`)}}f(ns,"getAllOrphanedAddresses");async function Sr({senderSecret:r,sagaId:e}){let t=`[${Sr.name}]`;try{if(Ae&&console.log(`${t} starting... (I: 0de03f8dcd3e32f1fca244e8f2a8a826)`),!r)throw new Error("(UNEXPECTED) senderSecret falsy? (E: 8ce053fe59825a6678713128953b9d26)");if(!e)throw new Error("(UNEXPECTED) sagaId falsy? (E: 3a17e0c1b2f849de8a42cd15b8ee6826)");return await Fa({masterSecret:r,kdfOpts:{strategy:co.recursive_salt_wrap,salt:e,rounds:1e4,algorithm:"SHA-256"}})}catch(o){throw console.error(`${t} ${E(o)}`),o}finally{Ae&&console.log(`${t} complete.`)}}f(Sr,"deriveSessionSecret");var Jc=!1,or=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 U(),this.gib=await ue({ibGib:this.toIbGibDto()})}toIbGibDto(){return Ye({ibGib:this})}loadIbGibDto(e){let t=`${this.lc}[${this.loadIbGibDto.name}]`;try{return Jc&&console.log(`${t} starting...`),e.ib||console.warn(`${t} dto.ib is falsy.`),e.gib||console.warn(`${t} dto.gib is falsy.`),this.ib=H(e.ib),this.gib=H(e.gib),e.data?this.data=H(e.data):delete this.data,e.rel8ns?this.rel8ns=H(e.rel8ns):delete this.rel8ns,Promise.resolve()}catch(o){throw console.error(`${t} ${o.message}`),o}finally{Jc&&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 gn="subject",as=/^[a-zA-Z0-9_\-.]{1,255}$/,Zc="subject",Qc="",mn="subject is a cool ibgib witness that has seriously fascinating behavior.";var el="observable";var nr={subscribe:"subscribe"},tl=Object.values(nr);var rl={next:"next",error:"error",complete:"complete"};var ar={...nr,...rl};var uo={version:"1",uuid:Qc,name:Zc,description:mn,classname:"Subject_V1",persistOptsAndResultIbGibs:!1,allowPrimitiveArgs:!0,catchAllErrors:!0,trace:!1},ss=void 0;var sr=!1;function ol(r){let e=`[${ol.name}]`;try{let t=r?`${ro} ${r}`:ro;return sr&&console.log(`${e} ${t}`),t}catch(t){throw console.error(`${e} ${t.message}`),t}}f(ol,"getArgIb");function fb({ib:r,ibGib:e}){let t=`[${fb.name}]`;try{if(sr&&console.log(`${t} starting...`),!r)if(e)r=e.ib;else throw new Error("either ib or ibGib required (E: c052a9d76df867626f9ba17141cdce22)");return r.startsWith(ro)}catch(o){throw console.error(`${t} ${o.message}`),o}finally{sr&&console.log(`${t} complete.`)}}f(fb,"isArg");function nl(r){let e=`[${nl.name}]`;try{let t=r?`${ko} ${r}`:ko;return sr&&console.log(`${e} ${t}`),t}catch(t){throw console.error(`${e} ${t.message}`),t}}f(nl,"getResultIb");async function _r({argData:r,ibMetadata:e,noTimestamp:t}){let o=`[${_r.name}]`;try{let n=await F.firstGen({ib:ol(e),parentIbGib:F.primitive({ib:ro}),data:r,dna:!1,noTimestamp:t});if(n.newIbGib){let{newIbGib:a}=n;return a.rel8ns.past=[],a.gib=await Yt(a),a}else throw new Error("create ibGib failed")}catch(n){throw console.error(`${o} ${n.message}`),n}}f(_r,"argy_");async function Ar({resultData:r,ibMetadata:e,noTimestamp:t}){let o=`[${Ar.name}]`;try{let n=await F.firstGen({ib:nl(e),parentIbGib:F.primitive({ib:ko}),data:r,dna:!1,noTimestamp:t});if(n?.newIbGib){let{newIbGib:a}=n;return a.rel8ns.past=[],a.gib=await Yt(a),a}else throw new Error("create ibGib failed")}catch(n){throw console.error(`${o} ${n.message}`),n}}f(Ar,"resulty_");function is({ibGib:r}){let e=`[${is.name}]`;try{if(sr&&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{sr&&console.log(`${e} complete.`)}}f(is,"isCommand");function cs({ibGib:r}){let e=`[${cs.name}]`;try{return sr&&console.log(`${e} starting... (I: aad0a14f4d62061424fc92da4d53d823)`),typeof r.witness=="function"}catch(t){throw console.error(`${e} ${t.message}`),t}finally{sr&&console.log(`${e} complete.`)}}f(cs,"isWitness");var al=/^error (\w+) ([a-fA-F\d]{32}|undefined)$/;var ir=!1;function il({rawMsg:r}){let e=`[${il.name}]`;try{ir&&console.log(`${e} starting...`);let t=ls({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{ir&&console.log(`${e} complete.`)}}f(il,"getErrorIb");function ls({rawMsg:r}){let e=`[${ls.name}]`;try{if(ir&&console.log(`${e} starting...`),!r)throw new Error("(UNEXPECTED) rawMsg required (E: e5bd3b433a1781ebe885534cd2495622)");let t,o=r.match(Hs);if(o){let[n,a,s,i,c,d]=o;if(!i)throw new Error("invalid error msg body (E: a675e6855cca96519d33d44ea5400922)");t={success:!1,raw:r,body:i?.trim(),uuid:c.slice(4,36)},a&&(t.location=a),(s||d)&&(t.unexpected=!0)}else{t={success:!1,raw:r,body:r};let n=r.match(Ks);if(n){let[a,s]=n;t.location=s}r.toLowerCase().includes("(unexpected)")&&(t.unexpected=!0)}return t}catch(t){throw console.error(`${e} ${t.message}`),t}finally{ir&&console.log(`${e} complete.`)}}f(ls,"parseRawErrorMsg");function Tr({rawMsg:r}){let e=`[${Tr.name}]`;try{return ir&&console.log(`${e} starting...`),mt({parentPrimitiveIb:"error",ib:il({rawMsg:r}),data:ls({rawMsg:r}),ibRegExpPattern:al.source})}catch(t){throw console.error(`${e} ${t.message}`),t}finally{ir&&console.log(`${e} complete.`)}}f(Tr,"getErrorIbGib");function Kt({ibGib:r}){let e=`[${Kt.name}]`;try{if(ir&&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{ir&&console.log(`${e} complete.`)}}f(Kt,"isError");var En=class r{static{f(this,"WitnessFactoryBase")}lc=`[${r.name}]`};var ds=!1,Xr=class r extends En{static{f(this,"DynamicFormFactoryBase")}lc=`[${r.name}]`;patchDataFromItems({data:e,contextPath:t,items:o,pathDelimiter:n}){let a=`${this.lc}[${this.patchDataFromItems.name}]`;try{if(ds&&console.log(`${a} starting...`),!n)throw new Error("pathDelimiter required (E: 958d472a15fb71e45cd2925883f2ec22)");for(let s=0;s<o.length;s++){let i=o[s],c=t?t+n+i.name:i.name;if(!i.items)Yn({obj:e,value:i.value,path:c,logalot:ds,pathDelimiter:n});else if(i.items.length>0)this.patchDataFromItems({data:e,contextPath:c,items:i.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(s){throw console.error(`${a} ${s.message}`),s}finally{ds&&console.log(`${a} complete.`)}}};var cl="subscription",fs=/^[a-zA-Z0-9_\-.]{1,255}$/,ll="",dl="subscription",wn="subscription is a cool ibgib witness that has seriously fascinating behavior.";var go={unsubscribe:"unsubscribe",unsubscribed:"unsubscribed"};var bs={version:"1",uuid:ll,name:dl,description:wn,classname:"Subscription_V1",persistOptsAndResultIbGibs:!1,allowPrimitiveArgs:!0,catchAllErrors:!1,trace:!1},ps=void 0;var fl=!1;function hs({ibGib:r}){let e=`[${hs.name}]`;try{fl&&console.log(`${e} starting... (I: 3aadb634377acbe42984b61c91975323)`);let{ib:t}=r;return[el,gn].some(n=>t.includes(n))}catch(t){throw console.error(`${e} ${t.message}`),t}finally{fl&&console.log(`${e} complete.`)}}f(hs,"isObservable");var ie=!1,yn=class r extends or{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(ie&&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=In({data:this.data,classname:"Subscription_V1"}),this.gib=await ue({ibGib:this})}catch(t){throw console.error(`${e} ${t.message}`),t}finally{ie&&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(ie&&console.log(`${t} ib: ${o} (I: 4de7771f477dc5b36933343b694ce223)`),o===go.unsubscribe)return ie&&console.log(`${t} routing unsubscribe cmd (I: 5633b86d467af2aa67388abf559a3c23)`),this.witness_unsubscribe();if(o===go.unsubscribed)return ie&&console.log(`${t} routing unsubscribed query (I: 6e0ae61d90f1974d76bcdbb47970e723)`),this.witness_unsubscribed();if(hs({ibGib:e}))return ie&&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(ie&&console.log(`${e} starting... (I: a3d549220ef24604956aaa2c66fff09b)`),!this._subscribed)return console.warn(`${e} tried to unsubscribe but this._subscribed is ${this._subscribed} (W: cdc94f59447d4011b4b4cc12ef9ec074)`),q;if(this._unsubscribed)return console.warn("{lc} this._unsubscribed already true. (W: fa287d76cec040e0978a8add5c758093)"),q;if(!this._srcObservable)throw new Error("(UNEXPECTED) this._subscribed but this._srcObservable falsy? (E: 83687993b7bea299b4ba2438b530a123)");return ie&&(console.log(`${e} inspecting srcObservable before src.witness... (I: f15a33d10f1cae3cec6fdbdb32596823)`),console.dir(this._srcObservable)),await this._srcObservable.witness(this),ie&&(console.log(`${e} inspecting srcObservable after src.witness... (I: f15a33d10f1cae3cec6fdbdb32596823)`),console.dir(this._srcObservable)),this._subscribed=!1,this._unsubscribed=!0,delete this._srcObservable,ie&&console.log(`${e} this._ (I: 7b1bc418a3d32757772391cad7a49523)`),q}catch(t){throw console.error(`${e} ${t.message}`),t}finally{ie&&console.log(`${e} complete.`)}}async witness_observable({ibGib:e}){let t=`${this.lc}[${this.witness_observable.name}]`;try{if(ie&&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,ie&&console.log(`${t} this._srcObservable set to ibgib with ib: ${e.ib} (I: 4b81d17243f60dfdcc2163fbb55e9223)`),this._subscribed=!0,q}catch(o){throw console.error(`${t} ${o.message}`),o}finally{ie&&console.log(`${t} complete.`)}}async witness_unsubscribed(){let e=`${this.lc}[${this.witness_unsubscribed.name}]`;try{if(ie&&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?ca:pi;return ie&&console.log(`${e} result: ${K(t)} (I: b488cf36ce39e006a81d3ad3db5b4a23)`),t}catch(t){throw console.error(`${e} ${t.message}`),t}finally{ie&&console.log(`${e} complete.`)}}async unsubscribe(){let e=`${this.lc}[${this.unsubscribe.name}]`;try{ie&&console.log(`${e} starting... (I: ef7f3f4787a74fcca65d761880f44594)`);let t=await this.witness(F.primitive({ib:go.unsubscribe}));if(!t)throw new Error("(UNEXPECTED) unsubscribe returned undefined? (E: 7013193490b94b6880f1049c36577d6f)");if(Kt({ibGib:t})){let o=t;throw new Error(`${o.data.raw} (E: fca1200dccb14f84968b2462f1b4c29e)`)}}catch(t){throw console.error(`${e} ${t.message}`),t}finally{ie&&console.log(`${e} complete.`)}}async unsubscribed(){let e=`${this.lc}[${this.unsubscribed.name}]`;try{ie&&console.log(`${e} starting... (I: 8ee9a93be61647d6aef6a4fa03e96dad)`);let t=await this.witness(F.primitive({ib:go.unsubscribed}));if(!t)throw new Error("(UNEXPECTED) unsubscribe returned undefined? (E: 5051d7ff4a4d4bf7864c520b53f028d5)");let o=t.ib===ca.ib;return ie&&console.log(`${e} resUnsubscribed: ${o} (I: b4800166c58d5ba2ca1dccaa53de2323)`),o}catch(t){throw console.error(`${e} ${t.message}`),t}finally{ie&&console.log(`${e} complete.`)}}async validateThis(){let e=`${this.lc}[${this.validateThis.name}]`;try{return ie&&console.log(`${e} starting...`),this.data,[]}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{ie&&console.log(`${e} complete.`)}}async argy({argData:e,ibMetadata:t,noTimestamp:o,ibGibs:n}){let a=await _r({argData:e,ibMetadata:t,noTimestamp:o});return n&&(a.ibGibs=n),a}async resulty({resultData:e,ibGibs:t}){let o=await Ar({resultData:e});return t&&(o.ibGibs=t),o}},$n=class r extends Xr{static{f(this,"Subscription_V1_Factory")}lc=`[${r.name}]`;getName(){return yn.name}async newUp({data:e,rel8ns:t}){let o=`${this.lc}[${this.newUp.name}]`;try{ie&&console.log(`${o} starting...`),e??=H(bs),e=e,t=t??ps?H(ps):void 0,e.uuid||=await U();let{classname:n}=e,a=In({data:e}),s=await mt({parentPrimitiveIb:`witness ${n}`,ib:a,data:e,rel8ns:t}),i=new yn(void 0,void 0);return await i.loadIbGibDto(s),ie&&console.log(`${o} witnessDto: ${K(s)} (I: 5e41337176d1441f9a5c7b43664d43ef)`),{newIbGib:i}}catch(n){throw console.error(`${o} ${E({error:n})}`),n}finally{ie&&console.log(`${o} complete.`)}}async witnessToForm({witness:e}){let t=`${this.lc}[${this.witnessToForm.name}]`;try{ie&&console.log(`${t} starting...`);let{data:o}=e;if(!o)throw new Error("(UNEXPECTED) witness.data falsy? (E: ef44497ff97a4e5bac004d52c4ff40eb)");ie&&console.log(`${t} data: ${K(o)} (I: c3f4c3d85386461aaefbe33524ff9cbd)`);let n=await Yr({n:100}),a=new Sn().with({idPool:n}).name({of:o.name,required:!1}).description({of:o.description??wn}).and().and().uuid({of:o.uuid,required:!0}).classname({of:o.classname}).and().commonWitnessFields({data:o}).outputForm({formName:"form",label:"subscription"});return Promise.resolve(a)}catch(o){throw console.error(`${t} ${E({error:o})}`),o}finally{ie&&console.log(`${t} complete.`)}}async formToWitness({form:e}){let t=H(bs);return this.patchDataFromItems({data:t,items:e.items,pathDelimiter:Or}),await this.newUp({data:t})}};var _n=!1;function bl({data:r}){let e=`[${bl.name}]`;try{if(_n&&console.log(`${e} starting...`),!r)throw new Error("Subscription Data required (E: 6d1c97931dcab8ea9f3e9b32c794b90c)");let t=[],{name:o,uuid:n,classname:a}=r;return o?o.match(fs)||t.push(`name must match regexp: ${fs} (E: 21bf77e398d47e9d035376510505eda2)`):t.push("name required."),n?n.match(ve)||t.push(`uuid must match regexp: ${ve} (E: e53fd08ae69e945b37ed895b864b6bd7)`):t.push("uuid required."),a&&(a.match(Wt)||t.push(`classname must match regexp: ${Wt}`)),t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{_n&&console.log(`${e} complete.`)}}f(bl,"validateCommonSubscriptionData");function In({data:r,classname:e}){let t=`[${In.name}]`;try{let o=bl({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 ${cl} ${e} ${n}`}catch(o){throw console.error(`${t} ${E(o)}`),o}}f(In,"getSubscriptionIb");var Sn=class r extends Zt{static{f(this,"SubscriptionFormBuilder")}lc=`[${r.name}]`;constructor(){super(),this.what="subscription"}};function An({ibGib:r}){let e=`[${An.name}]`;try{if(_n&&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{_n&&console.log(`${e} complete.`)}}f(An,"isSubscription");async function pl(){return(await new $n().newUp({})).newIbGib}f(pl,"newupSubscription");var us="observable_event";var hl=!1;async function gs({eventType:r,srcObservable:e,payload:t}){let o=`[${gs.name}]`;try{if(hl&&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(ve))throw new Error(`valid srcObservable.data.uuid required. must pass UUID_REGEXP: ${ve.source} (E: 10f4bd1863f18250cc79cd65221da223)`);let n={uuid:await U(),eventType:r,srcObservableId:e.data.uuid,"@srcObservableAddr":y({ibGib:e}),"@payloadAddr":y({ibGib:t})};return await mt({parentPrimitiveIb:us,ib:ul({data:n}),data:n})}catch(n){throw console.error(`${o} ${n.message}`),n}finally{hl&&console.log(`${o} complete.`)}}f(gs,"getObservableEventIbGib");function ul({data:r,classname:e}){let t=`[${ul.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`${us} ${e} ${r.uuid}`}catch(o){throw console.error(`${t} ${E(o)}`),o}}f(ul,"getObservableEventIb");var we=!1,Tn=class r extends or{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(is({ibGib:e}))return this.witness_cmd({arg:e});if(cs({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(we&&console.log(`${t} starting... (I: 69257fac8328b9de9755fdd237b92723)`),e.data.cmd===nr.subscribe)return this.witness_subscribe_cmd({ibGib:e});throw new Error(`unknown command. must be of type ObservableCmd (${tl}) (E: 5910e5cbafead25ea2917a65a3fc4123)`)}catch(o){throw console.error(`${t} ${o.message}`),o}finally{we&&console.log(`${t} complete.`)}}async witness_otherWitness({arg:e}){let t=`${this.lc}[${this.witness_otherWitness.name}]`;try{return we&&console.log(`${t} starting... (I: 871d0b7a2bef4596bad430f1cbacde02)`),An({ibGib:e})?this.witness_subscriptionIbGib({arg:e}):this.witness_subscribe_nonCmdWitness({arg:e})}catch(o){throw console.error(`${t} ${o.message}`),o}finally{we&&console.log(`${t} complete.`)}}async witness_subscriptionIbGib({arg:e}){let t=`${this.lc}[${this.witness_subscriptionIbGib.name}]`;try{if(we&&console.log(`${t} starting... (I: 4ac764776ef7e3f9074eb95a999ba423)`),!e.data)throw new Error("arg.data required (E: 764ae772727ceba95a18140fdd938323)");let o=this.getSubscriberKey({subscription:e}),[n,a]=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 q}catch(o){throw console.error(`${t} ${o.message}`),o}finally{we&&console.log(`${t} complete.`)}}async replayPastPayloads({observer:e,subscription:t}){let o=`${this.lc}[${this.replayPastPayloads.name}]`;try{we&&console.log(`${o} starting... (I: b3c8f9c76a4af030cf52fdcf01c3fd23)`);let n=this.getSubscriberKey({subscription:t}),a=f(()=>!!this._subscribers[n],"fnStillSubscribed"),s=-1,i=!0;do if(s++,s<this._pastPayloads.length){if(!a()){we&&console.log(`${o} subscription canceled before past payloads dispatch completed. (I: f1778f868446a518030d1cf7800c8a23)`);return}try{let c=this._pastPayloads[s];await e.next(c)}catch{console.error(`${o} observer errored on payload (i: ${s}). aborting replay (E: 1d7efc7c48e1491da4317ef333031077)`);return}}else i=!1;while(i);if(this.isErrored&&e.error&&a())try{await e.error(this._pastError)}catch{console.error(`${o} observer.error(this._pastError) errored itself (E: 18310e5e032345e7bdc3f2479807866c)`)}else if(this.isComplete&&e.complete&&a())try{await e.complete()}catch{console.error(`${o} observer.complete errored (E: d9d027f5520f4d7eadfc669d66b5b550)`)}}catch(n){throw console.error(`${o} ${n.message}`),n}finally{we&&console.log(`${o} complete.`)}}async witness_subscribe_cmd({ibGib:e}){let t=`${this.lc}[${this.witness_subscribe_cmd.name}]`;try{if(we&&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 pl();return we&&console.log(`${t} subscription created (I: 89ccd97803c66292f9d7334e1e2de523)`),await n.witness(this),await n.initialized,we&&console.log(`${t} subscription initialized (after witnessing this observable as its src). (I: 3021483402b21c4df64a9173bd223a23)`),this._subscribers[this.getSubscriberKey({subscription:n})]=[n,o],we&&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{we&&console.log(`${t} complete.`)}}async witness_subscribe_nonCmdWitness({arg:e}){let t=`${this.lc}[${this.witness_subscribe_nonCmdWitness.name}]`;try{throw we&&console.log(`${t} starting... (I: d9571dfcab4247d594c838233971886a)`),new Error("not impl (E: 76219cf238ba4f849480bd7c82eefab9)")}catch(o){throw console.error(`${t} ${o.message}`),o}finally{we&&console.log(`${t} complete.`)}}async subscribe(e){let t=`${this.lc}[${this.subscribe.name}]`;try{we&&console.log(`${t} starting... (I: 0dec9a06c562711e19482d45a7075e23)`);let o;if(Gr({ibGib:e})){let n=await this.argy({argData:{cmd:nr.subscribe,ibGibAddrs:[y({ibGib:e})]},ibGibs:[e]});o=await this.witness(n)}else o=await this.witness(e);if(!An({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{we&&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{we&&console.log(`${n} starting... (I: 0b990ce892f689d14458565717e66a23)`);let a=Object.values(this._subscribers);for(let s=0;s<a.length;s++){let[i,c]=a[s];if(Gr({ibGib:c})){let d=c;await t(d,e),d.complete?await i.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 d.complete():we&&console.log(`${n} no error handler for observer. skipping. (I: 6a8a52c2012c464790eb406d2ae0383f)`)}else{let d=await gs({eventType:o,srcObservable:this,payload:e});await c.witness(d)}}}catch(a){throw console.error(`${n} ${a.message}`),a}finally{we&&console.log(`${n} complete.`)}}async validateThis(){let e=`${this.lc}[${this.validateThis.name}]`;try{return we&&console.log(`${e} starting...`),this.data,[]}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{we&&console.log(`${e} complete.`)}}async argy({argData:e,ibMetadata:t,noTimestamp:o,ibGibs:n}){let a=await _r({argData:e,ibMetadata:t,noTimestamp:o});return n&&(a.ibGibs=n),a}async resulty({resultData:e,ibGibs:t}){let o=await Ar({resultData:e});return t&&(o.ibGibs=t),o}};var le=!1,Gn=class r extends Tn{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{le&&console.log(`${t} starting... (I: 8e47b752314870ec78eb14342621f723)`);let o=await this.argy({argData:{cmd:ar.subscribe,ibGibAddrs:[y({ibGib:e})]},ibGibs:[e]});return await this.witness(o)}catch(o){throw console.error(`${t} ${o.message}`),o}finally{le&&console.log(`${t} complete.`)}}async next(e){let t=`${this.lc}[${this.next.name}]`;try{le&&console.log(`${t} starting... (I: b30363827c56450ca918c69aa15b0046)`);let o=await this.argy({argData:{cmd:ar.next,ibGibAddrs:[y({ibGib:e})]},ibGibs:[e]});await this.witness(o)}catch(o){throw console.error(`${t} ${o.message}`),o}finally{le&&console.log(`${t} complete.`)}}async error(e){let t=`${this.lc}[${this.error.name}]`;try{le&&console.log(`${t} starting... (I: 7fcc30e3763c429ea8b212491ad9455a)`);let o;if(typeof e=="string")o=await Tr({rawMsg:e});else if(e instanceof Error||typeof e.message=="string")o=await Tr({rawMsg:E(e)});else if(e.ib&&Kt({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:ar.error,ibGibAddrs:[y({ibGib:o})]},ibGibs:[o]});await this.witness(n)}catch(o){throw console.error(`${t} ${o.message}`),o}finally{le&&console.log(`${t} complete.`)}}async complete(){let e=`${this.lc}[${this.complete.name}]`;try{le&&console.log(`${e} starting... (I: 5faaf13c6b0543d399815c03b9cdf80c)`);let t=await this.argy({argData:{cmd:ar.complete}});await this.witness(t)}catch(t){throw console.error(`${e} ${t.message}`),t}finally{le&&console.log(`${e} complete.`)}}async witness_cmd({arg:e}){let t=`${this.lc}[${this.witness_cmd.name}]`;try{le&&console.log(`${t} starting... (I: 2bf7cbcadba446fa92cb649906b2b260)`);let{cmd:o}=e.data;switch(o){case ar.next:return this.witness_next({ibGib:e});case ar.error:return this.witness_error({ibGib:e});case ar.complete:return this.witness_complete({ibGib:e});default:return super.witness_cmd({arg:e})}}catch(o){throw console.error(`${t} ${o.message}`),o}finally{le&&console.log(`${t} complete.`)}}async witness_next({ibGib:e}){let t=`${this.lc}[${this.witness_next.name}]`;try{if(le&&console.log(`${t} starting... (I: 600da780f13f5137a2f76aad344b2923)`),this.isCompleteOrErrored)return le&&console.log(`${t} this.isCompleteOrErrored is true. returning early without producing. (I: aa823831853b134b19657c8673838c23)`),q;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 a=0;a<n.length;a++){let[s,i]=n[a];if(le&&console.log(`${t} ensuring subscription not unsubscribed (I: ade3fd6d6ff2b5ec69eb8143e32ce223)`),!await s.unsubscribed())le&&console.log(`${t} subscription still active (I: b9ab83b28acecf0d823fdba46a81dc23)`),await i.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 q}catch(o){throw console.error(`${t} ${o.message}`),o}finally{le&&console.log(`${t} complete.`)}}async witness_error({ibGib:e}){let t=`${this.lc}[${this.witness_error.name}]`;try{if(le&&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 a=0;a<n.length;a++){let[s,i]=n[a];if(Gr({ibGib:i})){let c=i;c.error?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: 8946e97f00fd4146a470064b490a4c29)`):await c.error(o):le&&console.log(`${t} no error handler for observer. skipping. (I: 59f4a1ee59a3a27d523d60cd761be923)`)}else await i.witness(o)}return q}catch(o){throw console.error(`${t} ${o.message}`),o}finally{le&&console.log(`${t} complete.`)}}async witness_complete({ibGib:e}){let t=`${this.lc}[${this.witness_complete.name}]`;try{le&&console.log(`${t} starting... (I: 4db180f465e24df9a4ded37fbd235558)`),this._isComplete=!0;let o=Object.values(this._subscribers);for(let n=0;n<o.length;n++){let[a,s]=o[n];if(Gr({ibGib:s})){let i=s;i.complete?await a.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 i.complete():le&&console.log(`${t} no error handler for observer. skipping. (I: 6a8a52c2012c464790eb406d2ae0383f)`)}else await s.witness(e)}return q}catch(o){throw console.error(`${t} ${o.message}`),o}finally{le&&console.log(`${t} complete.`)}}async validateThis(){let e=`${this.lc}[${this.validateThis.name}]`;try{return le&&console.log(`${e} starting...`),this.data,[]}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{le&&console.log(`${e} complete.`)}}async argy({argData:e,ibMetadata:t,noTimestamp:o,ibGibs:n}){if(e.cmd===nr.subscribe)return super.argy({argData:e,ibMetadata:t,noTimestamp:o,ibGibs:n});{let a=await _r({argData:e,ibMetadata:t,noTimestamp:o});return n&&(a.ibGibs=n),a}}async resulty({resultData:e,ibGibs:t}){let o=await Ar({resultData:e});return t&&(o.ibGibs=t),o}},Cn=class r extends Xr{static{f(this,"Subject_V1_Factory")}lc=`[${r.name}]`;getName(){return Gn.name}async newUp({data:e,rel8ns:t}){let o=`${this.lc}[${this.newUp.name}]`;try{le&&console.log(`${o} starting...`),e??=H(uo),e=e,t=t??ss?H(ss):void 0,e.uuid||=await U();let{classname:n}=e,a=ms({data:e}),s=await mt({parentPrimitiveIb:`witness ${n}`,ib:a,data:e,rel8ns:t}),i=new Gn(void 0,void 0);return await i.loadIbGibDto(s),le&&console.log(`${o} witnessDto: ${K(s)} (I: 6736d2b2ddf44fef9a1eb27078dfbf23)`),{newIbGib:i}}catch(n){throw console.error(`${o} ${E({error:n})}`),n}finally{le&&console.log(`${o} complete.`)}}async witnessToForm({witness:e}){let t=`${this.lc}[${this.witnessToForm.name}]`;try{le&&console.log(`${t} starting...`);let{data:o}=e;if(!o)throw new Error("(UNEXPECTED) witness.data falsy? (E: 7b70c96e982d4f81b6ffda54da16b3b8)");le&&console.log(`${t} data: ${K(o)} (I: 75abef56f5004a94b2113e3b1461ac25)`);let n=await Yr({n:100}),a=new vn().with({idPool:n}).name({of:o.name,required:!1}).description({of:o.description??mn}).and().and().uuid({of:o.uuid,required:!0}).classname({of:o.classname}).and().commonWitnessFields({data:o}).outputForm({formName:"form",label:"observable"});return Promise.resolve(a)}catch(o){throw console.error(`${t} ${E({error:o})}`),o}finally{le&&console.log(`${t} complete.`)}}async formToWitness({form:e}){let t=H(uo);return this.patchDataFromItems({data:t,items:e.items,pathDelimiter:Or}),await this.newUp({data:t})}};var On=!1;function gl({data:r}){let e=`[${gl.name}]`;try{if(On&&console.log(`${e} starting...`),!r)throw new Error("Subject Data required (E: 207a82725648e2ef234c8bd3fa1a5312)");let t=[],{name:o,uuid:n,classname:a}=r;return o?o.match(as)||t.push(`name must match regexp: ${as} (E: de987eb8fea0b6232f60abf31815095c)`):t.push("name required."),n?n.match(ve)||t.push(`uuid must match regexp: ${ve} (E: 1a6dfda91ad51696f7456bc84dfea60e)`):t.push("uuid required."),a&&(a.match(Wt)||t.push(`classname must match regexp: ${Wt}`)),t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{On&&console.log(`${e} complete.`)}}f(gl,"validateCommonSubjectData");function ms({data:r,classname:e}){let t=`[${ms.name}]`;try{let o=gl({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:a}=r;return`witness ${gn} ${e} ${n} ${a}`}catch(o){throw console.error(`${t} ${E(o)}`),o}}f(ms,"getSubjectIb");var vn=class r extends Zt{static{f(this,"SubjectFormBuilder")}lc=`[${r.name}]`;constructor(){super(),this.what="subject"}};function Gr({ibGib:r}){let e=`[${Gr.name}]`;try{return On&&console.log(`${e} starting... (I: b54c252104f710c12951aa43b6ead323)`),typeof r.next=="function"}catch(t){throw console.error(`${e} ${t.message}`),t}finally{On&&console.log(`${e} complete.`)}}f(Gr,"isObserver");async function Nn({data:r,replay:e}={}){let t=new Cn;return r??=H(uo),e&&(r.replay=!0),(await t.newUp({data:r})).newIbGib}f(Nn,"newupSubject");var xn="sync_sagacontext";var mo=!1;async function Es({data:r}){let e=`[${Es.name}]`;try{if(!r)throw new Error("data required (E: 839d82138c234b3e89582855594191fe)");let t=r["@payloadAddrsDomain"]?r["@payloadAddrsDomain"].length:0;return[xn,r.sagaN,t].join(" ")}catch(t){throw console.error(`${e} ${E(t)}`),t}}f(Es,"getSyncSagaContextIb");async function cr({context:r}){let e=`[${cr.name}]`;try{mo&&console.log(`${e} starting... (I: 7797f8294bd8f7e5089cb722ad468226)`);let t=[],o=await ge({ibGib:r});if(o&&o.length>0)return o.forEach(n=>t.push(n)),t;if(r.sagaFrame?(await bn({sagaIbGib:r.sagaFrame})).forEach(a=>t.push(a)):t.push("context.sagaFrame is falsy. (E: b4edd88f4963f493789f83b29ba2df26)"),r.sagaFrameMsg){if((await ge({ibGib:r.sagaFrameMsg})??[]).forEach(a=>t.push(a)),r.sagaFrame){let a=r.sagaFrame.rel8ns?.[Be]?.[0];if(a){let s=y({ibGib:r.sagaFrameMsg});s!==a&&t.push(`context.sagaFrameMsg address (${s}) does not match the stone address referenced in sagaFrame relations (${a}). (E: a983b271fcae46bbad7e82098bc24826)`)}else t.push(`context.sagaFrame is missing the message stone relation '${Be}'. (E: da872cf3a8d46dbbad89d0a68d712826)`)}}else t.push("context.sagaFrameMsg is falsy. (E: ed405a72ab0d8bbdca7b9605d8f9a26)");return t.length>0?t:(console.error(`${e} NAG ERROR MSG (NOT THROWN): not fully implemented yet (E: d574d85cb578637648ed403857f7a826)`),[])}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{mo&&console.log(`${e} complete.`)}}f(cr,"validateContextAndSagaFrame");async function ws({context:r,space:e}){let t=`[${ws.name}]`;try{mo&&console.log(`${t} starting... (I: 3c34e8f1d6ef965f98725c88459ea926)`);let o=[];if(!r.data)throw new Error("(UNEXPECTED) context.data falsy? (E: 3e4ddd0eb4b828ad489658d88d9a6326)");if(!r.rel8ns)throw new Error("(UNEXPECTED) context.rel8ns falsy? (E: 8026589d4fed69c828334ee842074326)");let{sagaFrame:n,signedSessionIdentity:a}=r;if(!n.data)throw new Error("(UNEXPECTED) sagaFrame.data falsy? (E: b61cc82d25984c92f75db74a5a855b26)");if(!a)return console.error(`${t}[NAG][not thrown] sagaFrame.data.sessionIdentityTjpAddr logic needs to be added in coordinator (E: 4fc47800a1086c917a47381824280826)`),n.data.sessionIdentityTjpAddr?(o.push("Context has no session identity, but sync saga frame shows a session identity (sagaFrame.data.sessionIdentityTjpAddr is truthy). (E: 69dd6cdc2e1859c0f3d62958c4339826)"),o):r.rel8ns.sessionIdentity?(o.push("Context has no signed session identity, but context.rel8ns.sessionIdentity is truthy. (E: 96a04a8a6c88ea8bf88118f89ad8e326)"),o):(mo&&console.log(`${t} context has no signedSessionIdentity and sync saga frame doesn't state there should be session identity. So nothing further to authenticate - returning early with no authentication errors. (I: d708735f9a2899ee98f762b8a09ed826)`),[]);let s=y({ibGib:a}),i=r.rel8ns?.sessionIdentity??[];if(i.length===0)return o.push("context.rel8ns.sessionIdentity is falsy/empty but context.signedSessionIdentity is present. (E: 66f906421eb2468c0b33f908a3cf2826)"),o;if(i.length>1)return o.push("context.rel8ns.sessionIdentity has multiple identity addrs. (E: 489428bfe6fdaa4cd885b938dc4c5826)"),o;let c=i[0],d=await We({addrs:[c],space:e});if(!d)throw new Error(`(UNEXPECTED) resGetLatestAddr for prevSessionIdentityAddr in space (${e.ib}) falsy? (E: 7b207e5cbcec9037ea5adbe822ead826)`);if(!d.data)throw new Error(`(UNEXPECTED) resGetLatestAddr.data for prevSessionIdentityAddr in space (${e.ib}) falsy? (E: de4eb8d730c8c4dcb59c8b9c79277826)`);if(!d.data.success)throw new Error("(UNEXPECTED) resGetLatestAddr.data.success falsy? (E: c94298dfd9684ad6a87eb748459aa826)");let{latestAddrsMap:l}=d.data;if(!l)throw new Error("(UNEXPECTED) resGetLatestAddr.data.latestAddrsMap falsy? (E: 19f1fd5fe798cf2e5fa923919169d826)");if(Object.keys(l).length!==1)throw new Error("(UNEXPECTED) Object.keys(latestAddrsMap).length !== 1? (E: fe526a0747589c6427a8bcc86da34a26)");let b=l[c];if(!b)return o.push(`prevSessionIdentityAddr (${c}) not found in space (${e.ib}). this should have been the incoming prevSessionIdentityAddr (E: f6d042bd6b54819998653228dee34226)`),o;if(c!==b&&b!==s)return o.push(`context.rel8ns.sessionIdentity does not point to the most recent in the space (${e.ib}). (E: 2f8288f53c87b6aa47bd2178d9df0c26)`),console.log(`context: ${K(Ye({ibGib:r}))}`),console.log(`prevSessionIdentityAddr (context.rel8ns.sessionIdentity): ${c}`),console.log(`prevSessionIdentityAddr_latest: ${b}`),console.log(`currSessionIdentity (context.signedSessionIdentity): ${K(Ye({ibGib:{ib:a.ib,gib:a.gib,rel8ns:a.rel8ns,data:{...a.data,challengePools:a.data.challengePools.map(M=>({...M,challenges:{}}))}}}))}`),console.log(`currSessionIdentityAddr: ${s}`),o;let p=await te({addr:c,space:e});if(!p.success||p.ibGibs?.length!==1)return o.push(`could not fetch latest sender identity ${c} from space (${e.ib}). (E: fd48c3e64c9fa4efd8a1f8280af18226)`),o;let h=p.ibGibs[0],g=await oo({ibGib:h,naive:!0,space:e});if(!g)throw new Error(`(UNEXPECTED) couldn't get sessionIdentityTjp in space (${e.ib})? we have already gotten the identity itself in the space, so we would expect the entire timeline to exist in it. (E: 9be0382ff1c8a0e77645ea38c096f826)`);let m=y({ibGib:g});if(m!==n.data.sessionIdentityTjpAddr)throw new Error("(UNEXPECTED) sessionIdentityTjpAddr !== sagaFrame.data.sessionIdentityTjpAddr? (E: c9a4ad5c2728fe38e86afc58e4abaf26)");let w=g.data.frameDetails;if(!w)return o.push("Invalid session identity tjp: sessionIdentityTjp.data.frameDetails is falsy. (E: 0187f8f804a84256281720586620b826)"),o;let{senderIdentityAddr:S,senderIdentityTjpAddr:A}=w;if(!S)throw new Error("sessionGenesisFrameDetails.senderIdentityAddr falsy (E: 02a0c80a3ead9e3af8af4cf3b156e826)");if(!A)throw new Error("sessionGenesisFrameDetails.senderIdentityTjpAddr falsy (E: 271928090ff5dc56d4bb63d8d5c68826)");let I=await We({addrs:[A,S],space:e});if(!I)throw new Error(`(UNEXPECTED) resGetLatestAddr_senderIdentity for prevSessionIdentityAddr in space (${e.ib}) falsy? (E: 2e4ae8083b6fb7cbb8fae2a519062926)`);if(!I.data)throw new Error(`(UNEXPECTED) resGetLatestAddr_senderIdentity.data for prevSessionIdentityAddr in space (${e.ib}) falsy? (E: 2e231850c2a898cc282b4b2841056826)`);if(!I.data.success)throw new Error("(UNEXPECTED) resGetLatestAddr_senderIdentity.data.success falsy? (E: e93508f03e0475925875b00746ffd826)");let{latestAddrsMap:$}=I.data;if(!$)throw new Error("(UNEXPECTED) resGetLatestAddr_senderIdentity.data.latestAddrsMap falsy? (E: 87a91e3f9968ad9ba79cdfe8cd878326)");if(Object.keys($).length!==2&&A!==S)throw new Error("(UNEXPECTED) Object.keys(latestAddrsMap_senderIdentity).length !== 2 && senderIdentityTjpAddr !== senderIdentityAddr? (E: fe46bd584853d8e1e8e2d11f52012826)");let T=$[A],_=$[S];if(!_)throw new Error("(UNEXPECTED) senderIdentityAddr_latest falsy? (E: e151798ae2e9241578d09948937c4b26)");if(T!==_)throw new Error("senderIdentityTjpAddr_latest !== senderIdentityAddr_latest (E: 52478a1053589e72665031a853cc1826)");let G=await te({addr:_,space:e});if(!G.success||G.ibGibs?.length!==1)return o.push(`could not fetch latest sender identity ${c} from space (${e.ib}). (E: 3565ff0ed458f5a2384c40b16e849826)`),o;let v=G.ibGibs[0];if(!v.data.proofs)return o.push("Invalid sender identity. Proofs empty/falsy. (E: ebf488853061614d2b5b137828119526)"),o;let N=v.data.proofs.find(M=>M.claim.verb===wt)?.claim;if(!N)return o.push(`Most recent senderIdentity has no proof whose claim.verb === ${wt}. (E: b0f488ecccbbfe43d9a0b7c8a29d7826)`),o;if(N.target!==m)return o.push(`Most recent sender identity claim has claim.verb === ${wt} but DOES NOT target expected session identity addr ${c}. (E: 3e7f18d99848969be8586423d5ccb826)`),o;let B=await new se().validate({currentIbGib:a,prevIbGib:h});B.length>0&&o.push(`Invalid session identity transition: ${B.join(", ")} (E: da1c81c6d3c86aec3254f48fe7514226)`);let P=y({ibGib:r});return a.data?.proofs?.some(M=>M.claim.target===P)||o.push(`Session identity signature does not target current context ibgib (${P}). (E: acae68938c287178c878d1b88bebb826)`),o}catch(o){let n=`${t} ${E(o)}`;return console.error(n),[`authentication produced an error: ${n} (E: 45e014b82af81993d936611ca6fc4d26)`]}finally{mo&&console.log(`${t} complete.`)}}f(ws,"authenticateContextIntrinsically");var Ue=!1,Ln=class r extends or{static{f(this,"SyncPeer_V1")}lc=`[${r.name}]`;opts;payloadIbGibsDomainReceived$;currentSessionIdentity;get currentSessionIdentityAddr(){return this.currentSessionIdentity?y({ibGib:this.currentSessionIdentity}):void 0}async signContext({contextAddr:e}){let t=`${this.lc}[${this.signContext.name}]`;try{if(!this.currentSessionIdentity)return;if(!this.opts)throw new Error("opts not initialized. (E: bcf5978aed789b0ebcbdc51971ebe826)");let{fnSenderSecret:o,sagaId:n,localMetaspace:a,localSpace:s}=this.opts;if(!o)throw new Error("fnSenderSecret not initialized. (E: 207fd292a2e8c53c05fd0a74a4ae6d26)");if(!n)throw new Error("sagaId not initialized. (E: f2e35cc13ed873b638116188119d1826)");let i=await o(),c=await Sr({senderSecret:i,sagaId:n}),l=await new se().sign({latestKeystone:this.currentSessionIdentity,masterSecret:c,claim:{verb:wt,target:e},metaspace:a,space:s});return this.currentSessionIdentity=l,l}catch(o){throw console.error(`${t} ${E(o)}`),o}}async signContextConnect({challengeUuid:e,demandedIds:t}){let o=`${this.lc}[${this.signContextConnect.name}]`;try{if(!this.currentSessionIdentity)return;if(!this.opts)throw new Error("opts not initialized. (E: bcf5978aed789b0ebcbdc51971ebe826)");let{fnSenderSecret:n,sagaId:a,localMetaspace:s,localSpace:i}=this.opts;if(!n)throw new Error("fnSenderSecret not initialized. (E: 207fd292a2e8c53c05fd0a74a4ae6d26)");if(!a)throw new Error("sagaId not initialized. (E: f2e35cc13ed873b638116188119d1826)");let c=await n(),d=await Sr({senderSecret:c,sagaId:a}),b=await new se().sign({latestKeystone:this.currentSessionIdentity,masterSecret:d,poolId:yt,requiredChallengeIds:t,claim:{verb:tr,target:e},metaspace:s,space:i});return this.currentSessionIdentity=b,b}catch(n){throw console.error(`${o} ${E(n)}`),n}}get classname(){if(!this.data)throw new Error("(UNEXPECTED) this.data falsy? (E: 1ab1841e9338b54f3aa615fa37024826)");if(!this.data.classname)throw new Error("invalid peer. this.data.classname is falsy (E: b0ee28a0abb84a06588d9de7afcef826)");return this.data.classname}constructor(e,t){super(e,t)}async initialize(){this.payloadIbGibsDomainReceived$=await Nn()}async connect(e){let t=`${this.lc}[${this.connect.name}]`;try{Ue&&console.log(`${t} starting... (I: ad89d8137351662fb8a30114a1fa4826)`),await this.preConnectCheck(e),await this.connectImpl(e)}catch(o){throw console.error(`${t} ${E(o)}`),o}finally{Ue&&console.log(`${t} complete.`)}}async establishSessionIdentity(){let e=`${this.lc}[${this.establishSessionIdentity.name}]`;try{if(Ue&&console.log(`${e} starting... (I: f2a1b3c4d5e6f7a8b9c0d1e2f3a4b526)`),!this.opts)throw new Error("(UNEXPECTED) this.opts falsy? Call initializeOpts first. (E: a1b2c3d4e5f6a7b8c9d0e1f2a3b4c526)");let{senderIdentity:t,fnSenderSecret:o,sagaId:n,localMetaspace:a,localSpace:s}=this.opts;if(!t||!o){Ue&&console.log(`${e} no senderIdentity/fnSenderSecret \u2014 skipping establish (I: f29348a77d1542326d14043ea4b69126)`);return}let i=y({ibGib:t}),c=de({ibGib:t});if(!c)throw new Error("(UNEXPECTED) senderIdentityTjpAddr falsy? (E: d5d8c3ab25a83a2c127904fe96de1526)");if(!n)throw new Error("(UNEXPECTED) sagaId falsy? Must be set in initializeOpts before calling establishSessionIdentity. (E: c6ba389d51b8af07d82458f875cf9826)");let d=await o();if(!d)throw new Error("senderSecret falsy. senderSecret required. (E: 1a8b0298bf78cbdf284b7988983b9826)");let l=await Sr({senderSecret:d,sagaId:n}),b=new se;if(!this.opts.sessionConnectPoolConfig)throw new Error("(UNEXPECTED) opts.sessionConnectPoolConfig falsy? (E: 3351fd566eb8bbd2f821bb08c4419826)");if(!this.opts.sessionSyncPoolConfig)throw new Error("(UNEXPECTED) opts.sessionSyncPoolConfig falsy? (E: dbffa810d9e7ff6079088deb5b8e7826)");let p={senderIdentityAddr:i,senderIdentityTjpAddr:c};this.opts.targetAddrs&&(p.targetAddrs=this.opts.targetAddrs);let h=await b.genesis({masterSecret:l,configs:[this.opts.sessionConnectPoolConfig,this.opts.sessionSyncPoolConfig],frameDetails:p,metaspace:a,space:s}),g=y({ibGib:h}),m=await b.sign({latestKeystone:t,masterSecret:d,claim:{verb:wt,target:g},metaspace:a,space:s});await this.postEstablishToReceiver({newSenderIdentity:m,sessionIdentity:h}),this.currentSessionIdentity=h}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Ue&&console.log(`${e} complete.`)}}async initializeOpts(e){let t=`${this.lc}[${this.initializeOpts.name}]`;try{Ue&&console.log(`${t} starting... (I: 31bd5fda37c89fa37fbaf14daf5fe726)`),this.opts=e}catch(o){throw console.error(`${t} ${E(o)}`),o}finally{Ue&&console.log(`${t} complete.`)}}setOptionalOpts(e){let t=`${this.lc}[${this.setOptionalOpts.name}]`;try{if(Ue&&console.log(`${t} starting... (I: ae5ddbd3577db267f84743175a736626)`),!this.opts)throw new Error("(UNEXPECTED) this.opts falsy? (E: 0dd4d6080a6e2f31d86cf4d86e11b826)");Ue&&console.log(`${t} updating opts. arg keys: ${Object.keys(e)} (I: 452d78a558f8fc3468c8e2e68c70b226)`),this.opts={...this.opts,...e}}catch(o){throw console.error(`${t} ${E(o)}`),o}finally{Ue&&console.log(`${t} complete.`)}}async authenticateAndValidate({context:e}){let t=`${this.lc}[${this.authenticateAndValidate.name}]`;try{if(Ue&&console.log(`${t} starting... (I: add238055cd84a222c5b8c89913af526)`),!this.opts)throw new Error("(UNEXPECTED) opts falsy in authenticateValidateAuthorize (E: b7e5a8ad99d84e1ba8d8f7facd288826)");let{localSpace:o}=this.opts,n=await ws({context:e,space:o});if(n.length>0)throw new Error(`invalid context authentication. authenticationErrors: ${n} (E: da89da5ee1269aeb78952d475d607526)`);let a=await cr({context:e});if(a.length>0)throw new Error(`invalid context received. validationErrors: ${a} (E: 8b34c875c968af29bc433138e57a7826)`)}catch(o){throw console.error(`${t} ${E(o)}`),o}finally{Ue&&console.log(`${t} complete.`)}}async witness(e){let t=`${this.lc}[${this.witness.name}]`;try{if(Ue&&console.log(`${t} starting...`),!this.opts)throw new Error("(UNEXPECTED) this.opts falsy? Concrete class should have initialized sender opts by now. (E: 0b9e28287318fdf8bf9f5a6886a24826)");if(!e.sagaFrame)throw new Error("context.sagaFrame falsy. (E: a33dd88aa108e2bad9e885885731ce26)");await this.authenticateAndValidate({context:e});let o=await this.sendContextRequest(e);if(o){let n=await Hr({sagaIbGib:e.sagaFrame,space:this.opts.localSpace});return o}else{Ue&&console.log(`${t} No response from peer. this may be normal if we just sent the very last commit frame. (I: 1855b7728c8898e1f9c001f8170ba826)`);return}}catch(o){throw console.error(`${t} ${E(o)}`),o}finally{Ue&&console.log(`${t} complete.`)}}async getLocalIbGib(e){let t=`${this.lc}[${this.getLocalIbGib.name}]`;try{if(Ue&&console.log(`${t} starting... (I: 27b248cb9801eeb2386b71485389a826)`),console.warn(`${t} possibly a bottleneck here, getLocalIbGib only gets a single ibgib... (W: 2fd448a435480e6b128f6b8bcbef4826)`),!this.opts)throw new Error("(UNEXPECTED) this.opts falsy? (E: cfb9431f2fb851f24a6c88e80c3b3326)");let o=await te({space:this.opts.localSpace,addr:e});if(o.success&&o.ibGibs&&o.ibGibs.length===1)return o.ibGibs[0];throw new Error(`couldn't get addr (${e}) from local space ${this.opts.localSpace}. reason: ${o.errorMsg??"unknown error (E: 926ef8bf4fcc299ab89dba34ea691a26)"} (E: d8a89807e471d3f8b938ab21df44cb26)`)}catch(o){throw console.error(`${t} ${E(o)}`),o}finally{Ue&&console.log(`${t} complete.`)}}};var ml=!1,lr={COMMON:{ALGO:Je.sha_256,TYPE:pt.hash_reveal_v1,ROUNDS:2,REPLENISH:De.topUp},CONNECT_POOL:{ID:yt,VERB:tr,SIZE:10,SELECT_SEQUENTIALLY:2,SELECT_RANDOMLY:2,TARGET_BINDING_COUNT:0,SERVER_DEMAND_COUNT:3}};function Dn(r){let e=`[${Dn.name}]`;try{ml&&console.log(`${e} starting... (I: 3c791af2f978a00a087dfdde90884826)`);let t=(r.data?.challengePools??[]).find(s=>s.id===lr.CONNECT_POOL.ID);if(!t)throw new Error(`Keystone missing "${lr.CONNECT_POOL.ID}" pool (E: 6382e29260e4ddbac42ed18f49733526)`);let o=Object.keys(t.challenges).sort();if(o.length===0)throw new Error("Connect pool has no challenges (E: 1ef62fdbda182a790835c8c796475226)");let n=o[0],a=t.challenges[n];return{challengeId:n,challenge:a}}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{ml&&console.log(`${e} complete.`)}}f(Dn,"getConnectChallenge");var bb="auth-challenge-init",pb="auth-init",hb="auth-challenge",ub="auth-proof",gb="auth-ok",mb="auth-fail",Eb="sync-frame",wb="sync-frame-response",yb="sync-frame-authenticated",$b="sync-frame-response-authenticated",Ib="domain-payload",Sb="sync-error",ae={auth_challenge_init:bb,auth_init:pb,auth_challenge:hb,auth_proof:ub,auth_ok:gb,auth_fail:mb,sync_frame:Eb,sync_frame_response:wb,sync_frame_authenticated:yb,sync_frame_response_authenticated:$b,domain_payload:Ib,sync_error:Sb},Pn=Object.values(ae);function ys(r){return Pn.includes(r)}f(ys,"isSyncWebSocketMsgType");function El(r){throw new Error(`Unhandled message type: ${r} (E: e928a3f82cd7469a98ef1bc248a3f826)`)}f(El,"assertUnreachable");var It=!0,Y=class r extends Ln{static{f(this,"SyncPeerWebSocketSender_V1")}lc=`[${r.name}]`;get classname(){return r.name}get isSocketOpen(){return this.ws!==void 0&&this.ws.readyState===WebSocket.OPEN}ws;activeResolve;activeReject;pendingPayloadsToSend=[];handshakeMessageListener;constructor(e,t){super(e,t)}async preConnectCheck(e){let t=`${this.lc}[${this.preConnectCheck.name}]`;if(!this.data?.wsUrl)throw new Error("Missing wsUrl in peer data (E: a3b2c1d0e9f8e7d6c5b4a3f2e1d0c910)");if(!this.data?.httpEvolveUrl)throw new Error("Missing httpEvolveUrl in peer data (E: a3b2c1d0e9f8e7d6c5b4a3f2e1d0c911)")}async postEstablishToReceiver({newSenderIdentity:e,sessionIdentity:t}){let o=`${this.lc}[${this.postEstablishToReceiver.name}]`;try{if(It&&console.log(`${o} posting evolved keystones to ${this.data.httpEvolveUrl}...`),!this.data)throw new Error("(UNEXPECTED) this.data falsy? (E: d642e8a9af18b532c87c6f581aa53b26)");if(!this.data.httpEvolveUrl)throw new Error("(UNEXPECTED) this.data.httpEvolveUrl falsy? (E: 8589ddbb155914d85c09658881da2c26)");let n=await fetch(this.data.httpEvolveUrl,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({keystoneIbGib:e,relatedIbGibs:[t]})});if(!n.ok){let a=await n.json().catch(()=>({})),s=a.message||a.error||"Unknown error";throw new Error(`HTTP ${n.status} evolution post rejected. errorMsg: ${s} (E: e8a478291b88d05c68cf6b385684b826)`)}It&&console.log(`${o} evolve post accepted by server.`)}catch(n){throw console.error(`${o} establish post failed: ${E(n)}`),n}}async connectImpl(e){let t=`${this.lc}[${this.connectImpl.name}]`;try{It&&console.log(`${t} starting...`);let{senderIdentity:o,fnSenderSecret:n,sagaId:a,localMetaspace:s,localSpace:i}=this.opts;if(!o||!n||!a)throw new Error("Missing identity parameters in peer options (E: ed49b6711ac82efcdb42b8a28c5b6826)");let c=await n(),d=await Sr({senderSecret:c,sagaId:a}),l=y({ibGib:o}),b=y({ibGib:(o.rel8ns?.past,o)}),p=await s.getLatestAddr({ibGib:o,space:i});if(!p)throw new Error("senderIdentityLatestAddr falsy. we should have a latest addr that is different than the sender identity at this point (done in the peer establish phase) (E: 225607318bef485d7821f82de97b6826)");let m=((await s.get({addrs:[p],space:i})).ibGibs?.[0]).data.proofs.at(0)?.claim.target;if(!m)throw new Error("Could not locate session keystone target from identity (E: 5ec4882f7e5e4c33fbd00ab8b3166726)");let S=(await s.get({addrs:[m],space:i})).ibGibs?.[0];if(!S)throw new Error(`Session keystone not found in local space: ${m} (E: 9ba818e6622808bb4ae749be31f80b26)`);let A=(S.data?.challengePools??[]).find(N=>N.id===lr.CONNECT_POOL.ID);if(!A)throw new Error("Session keystone missing connect pool (E: f50968afca04b6d38ec19824ea201826)");let{challengeId:I}=Dn(S),$=Ot.create({config:A.config}),T=await $.derivePoolSecret({masterSecret:d}),_=await $.generateSolution({poolSecret:T,poolId:lr.CONNECT_POOL.ID,challengeId:I}),G=`${this.data.wsUrl}?sAddr=${encodeURIComponent(m)}&solution=${encodeURIComponent(_.value)}`;It&&console.log(`${t} connecting to WebSocket: ${G}`);let v=new WebSocket(G);return this.ws=v,new Promise((N,D)=>{let B=!1;v.addEventListener("open",()=>{It&&console.log(`${t} WebSocket opened. Awaiting challenge...`)}),this.handshakeMessageListener=async P=>{try{let k=JSON.parse(P.data);It&&console.log(`${t} received handshake frame: ${k.type}`);let M=k.type;if(!ys(M)){let j=Pn.join(", ");throw new Error(`Unknown message type '${M}' received during connection handshake. Valid types are: ${j} (E: e983271bc84f46928e4695be2409826)`)}switch(M){case ae.auth_challenge_init:await this.handleHandshakeAuthChallengeInit(v,m);break;case ae.auth_challenge:await this.handleHandshakeAuthChallenge(v,k,S,d);break;case ae.auth_ok:B=!0,this.handleHandshakeAuthOk(v,N);break;case ae.auth_fail:this.handleHandshakeAuthFail(k,D);break;case ae.sync_error:this.handleHandshakeSyncError(k,D);break;case ae.auth_init:case ae.auth_proof:case ae.sync_frame:case ae.sync_frame_response:case ae.sync_frame_authenticated:case ae.sync_frame_response_authenticated:case ae.domain_payload:throw new Error(`Unexpected message type '${M}' during connection handshake (E: e3f80c68ab2a46c2b1858c8a1e2f8926)`);default:El(M)}}catch(k){console.error(`${t} ${E(k)}`),D(k)}},v.addEventListener("message",this.handshakeMessageListener),v.addEventListener("close",P=>{B||(this.disconnect(),D(new Error(`WebSocket closed before connect completed (code: ${P.code})`)))}),v.addEventListener("error",P=>{B||(this.disconnect(),D(new Error("WebSocket connection error")))})})}catch(o){throw console.error(`${t} connect failed: ${E(o)}`),o}}disconnect(){let e=`${this.lc}[${this.disconnect.name}]`;try{if(It&&console.log(`${e} starting... (I: 35c4b85fca0c6e9d042f5ff87cde3826)`),this.ws){this.handshakeMessageListener&&(this.ws.removeEventListener("message",this.handshakeMessageListener),this.handshakeMessageListener=void 0);try{this.ws.close()}catch(t){console.error(`${e} failed to close websocket: ${E(t)}`)}this.ws=void 0}}catch(t){console.error(`${e} ${E(t)}`)}finally{It&&console.log(`${e} complete.`)}}async handleRuntimeMessage(e){let t=`${this.lc}[${this.handleRuntimeMessage.name}]`;try{let o=JSON.parse(e.data);It&&console.log(`${t} received runtime frame: ${o.type}`);let n=o.type;if(!ys(n)){let a=Pn.join(", ");throw new Error(`Unknown message type '${n}' received during active sync saga loop. Valid types are: ${a} (E: e23a8d10b74d47fb90518f8e3f4b826)`)}switch(n){case ae.sync_frame_response:await this.handleRuntimeSyncFrameResponse(o);break;case ae.sync_frame_authenticated:this.handleRuntimeSyncFrameAuthenticated();break;case ae.domain_payload:this.handleRuntimeDomainPayload(o);break;case ae.sync_error:this.handleRuntimeSyncError(o);break;case ae.auth_challenge_init:case ae.auth_init:case ae.auth_challenge:case ae.auth_proof:case ae.auth_ok:case ae.auth_fail:case ae.sync_frame:case ae.sync_frame_response_authenticated:throw new Error(`Unexpected message type '${n}' during active sync saga loop (E: e982b12cf92c448bbad0e84b7263c826)`);default:El(n)}}catch(o){if(console.error(`${t} failed parsing/handling runtime frame: ${E(o)}`),this.disconnect(),this.activeReject){let n=this.activeReject;this.activeResolve=void 0,this.activeReject=void 0,n(o)}}}async handleHandshakeAuthChallengeInit(e,t){e.send(JSON.stringify({type:ae.auth_init,sAddr:t}))}async handleHandshakeAuthChallenge(e,t,o,n){let{challengeUuid:a,demandedIds:s}=t;It&&console.log(`${this.lc} solving demanded challenges: ${s.join(", ")}`);let i=await this.signContextConnect({challengeUuid:a,demandedIds:s});if(!i)throw new Error("Failed to sign connect challenge proof (E: e9807f28ae9248bbadd0a7f1a8e9826)");e.send(JSON.stringify({type:ae.auth_proof,proofFrame:i}))}handleHandshakeAuthOk(e,t){It&&console.log(`${this.lc} WebSocket connect SUCCESS!`),this.handshakeMessageListener&&(e.removeEventListener("message",this.handshakeMessageListener),this.handshakeMessageListener=void 0),e.addEventListener("message",o=>this.handleRuntimeMessage(o)),t()}handleHandshakeAuthFail(e,t){this.disconnect(),t(new Error(`Handshake auth failed: ${e.message||"Unknown fail reason"} (E: f380b271a2be498db257bc8209fa8926)`))}handleHandshakeSyncError(e,t){this.disconnect(),t(new Error(`Handshake sync error: ${e.message||e.error||"Unknown sync error"} (E: f9208a01fe434cbbad83f210ea8f3426)`))}async handleRuntimeSyncFrameResponse(e){let t=e.context,o=await cr({context:t});if(o.length>0)throw new Error(`Invalid response context received: ${o.join(", ")} (E: d7b5a283cf4c43ba8659c803800cf826)`);let n=[Ye({ibGib:t}),t.sagaFrame,t.sagaFrameMsg];t.signedSessionIdentity&&n.push(t.signedSessionIdentity);let{localSpace:a}=this.opts;for(let i of n)await qe({space:a,ibGibs:[i]}),await xe({space:a,ibGib:i});if((t.data?.["@payloadAddrsDomain"]||[]).length>0&&this.ws.send(JSON.stringify({type:ae.sync_frame_response_authenticated,contextAddr:y({ibGib:t})})),this.activeResolve){let i=this.activeResolve;this.activeResolve=void 0,this.activeReject=void 0,i(t)}}handleRuntimeSyncFrameAuthenticated(){let e=this.pendingPayloadsToSend||[];this.pendingPayloadsToSend=[];for(let t of e)this.ws.send(JSON.stringify({type:ae.domain_payload,ibGib:t}))}handleRuntimeDomainPayload(e){let t=e.ibGib;this.payloadIbGibsDomainReceived$.next(t)}handleRuntimeSyncError(e){let t=e.message||e.error||"Unknown sync runtime error",o=new Error(`Sync runtime error from receiver: ${t} (E: e983bc1c828d447fa0581da2b8004f26)`);if(this.activeReject){let n=this.activeReject;this.activeResolve=void 0,this.activeReject=void 0,n(o)}else throw o}async sendContextRequest(e){let t=`${this.lc}[${this.sendContextRequest.name}]`;try{if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("WebSocket is not connected or open (E: a3b2c1d0e9f8e7d6c5b4a3f2e1d0c915)");let o=e.payloadIbGibsDomain??[];this.pendingPayloadsToSend=[...o];let n={...e};return delete n.payloadIbGibsDomain,new Promise((a,s)=>{this.activeResolve=a,this.activeReject=s,this.ws.send(JSON.stringify({type:ae.sync_frame,context:n}))})}catch(o){throw console.error(`${t} sendContextRequest failed: ${E(o)}`),o}}};var Ve=!1;async function $s({timeline:r}){let e=`[${$s.name}]`;try{if(Ve&&console.log(`${e} starting...`),$e({ibGib:r}))return console.warn(`${e} getting lock scope on a primitive ibgib can grossly impact performance. (W: 55203e415ae2ac7ddb19c21772b28925)`),y({ibGib:r});{let t=Pe({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{Ve&&console.log(`${e} complete.`)}}f($s,"getLockScope");async function dr({timeline:r,rel8nInfos:e,rel8nRemovalInfos:t,timelineIndexInfo:o,metaspace:n,space:a,skipLock:s,noDna:i}){let c=`[${dr.name}]`;try{if(Ve&&console.log(`${c} starting... (I: fcdff10832215068019355265f4cbc25)`),a??=await n.getLocalUserSpace({lock:!1}),!a)throw new Error("(UNEXPECTED) space falsy? couldn't even get default local user space? (E: 2051b44a052d6a2984b9a22f680e4625)");let d=await $s({timeline:r}),l=f(async()=>{if(!a)throw new Error("(UNEXPECTED) space falsy? couldn't even get default local user space? (E: 845c4181c8c15d7219166ceb3c4dca25)");let p=y({ibGib:r}),h=await n.getLatestAddr({addr:p,space:a});if(!h)throw new Error(`${c} (UNEXPECTED) Could not get latest address for timeline ${y({ibGib:r})}. (E: a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9)`);let g=Ye({ibGib:r});if(p!==h){let I=await n.get({addrs:[h],space:a});if(I.errorMsg||(I.ibGibs??[]).length!==1)throw new Error(`${c} (UNEXPECTED) couldn't get latest timeline ibgib (${h}) from space (${a.ib}). errorMsg: ${I.errorMsg??"[unknown error]"} (E: b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0)`);g=I.ibGibs.at(0)}let m;if(t&&t.length>0){m={};for(let I of t){let{rel8nName:$,ibGibAddrs:T}=I;if(T.length===0){console.warn(`${c} tried to remove 0 ibGibAddrs in rel8nName ${$}? skipping... (W: 93aeb601be66d680989e72ec70e4c826)`);continue}m[$]||(m[$]=[]),m[$]=m[$].concat(T)}}let w={};for(let I of e){let{rel8nName:$,ibGibs:T}=I;if(T.length===0){console.warn(`${c} tried to add 0 ibGibs to rel8nName ${$}? skipping... (W: 708252dfdeb60757fee4554e769aaa25)`);continue}w[$]||(w[$]=[]),w[$].push(...T.map(_=>y({ibGib:_})))}let S=await Xe({src:g,rel8nsToRemoveByAddr:m,rel8nsToAddByAddr:w,dna:!i,nCounter:!0}),A=S.newIbGib;return await n.persistTransformResult({resTransform:S,space:a}),o&&await Is({type:o.type,rel8nInfos:[{rel8nName:o.rel8nName,ibGibs:[A]}],metaspace:n,space:a,skipLock:s}),await n.registerNewIbGib({ibGib:A,space:a}),A},"fn");return s?await l():await Gt({scope:d,secondsValid:180,maxDelayMs:100,maxLockAttempts:1800,space:a,callerInstanceId:nt(),fn:l})}catch(d){throw console.error(`${c} ${E(d)}`),d}finally{Ve&&console.log(`${c} complete.`)}}f(dr,"appendToTimeline");async function Is({type:r,rel8nInfos:e,dataToAddOrPatch:t,metaspace:o,space:n,skipLock:a}){let s=`[${Is.name}]`;try{if(Ve&&console.log(`${s} 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 i=f(async()=>{let c=f(async()=>{let d=await o.getSpecialIbGib({type:r,space:n,initialize:!0});if(!d)throw new Error(`(UNEXPECTED) couldn't initialize/get special ibgib index of type ${r}. (E: a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6)`);return d.rel8ns||console.warn(`${s} not sure if this ever hits, but is there ever a scenario where specialIndex.rel8ns is falsy? (W: 06161c366bc7ec858b9b5aa7ee9b6d25)`),d},"fnGetSpecialIndex");for(let d of e??[]){let{rel8nName:l,ibGibs:b}=d;b.length===0&&console.error(`${s} ibGibs empty. skipping rel8nName (${l}). (E: 150d74f73f97aea1b97d173d92c77125)`);let h=(await c()).rel8ns??{},g,m=h[l]??[];if(m.length>0){let w=new Set;b.forEach(S=>{let A=y({ibGib:S}),I=S.rel8ns?.past??[];m.filter($=>[...I,A].includes($)).forEach($=>w.add($))}),w.size>0&&(g=Array.from(w))}await o.rel8ToSpecialIbGib({type:r,rel8nName:l,ibGibsToRel8:b,addrsToUnRel8:g,space:n,linked:!1,severPast:!1,deletePreviousSpecialIbGib:!1})}if(Object.keys(t??{}).length>0){let d=await c(),l=await at({src:d,dataToAddOrPatch:t,dna:!1,linkedRel8ns:[Ee.past],nCounter:!0}),b=l.newIbGib;await Ie({resTransform:l,space:n});let p=Le({type:r});await o.setConfigAddr({key:p,addr:y({ibGib:b}),space:n}),await o.registerNewIbGib({ibGib:b,space:n})}},"fn");a?await i():await Gt({scope:r,secondsValid:60,maxDelayMs:100,maxLockAttempts:600,space:n,fn:i})}catch(i){throw console.error(`${s} ${E(i)}`),i}finally{Ve&&console.log(`${s} complete.`)}}f(Is,"updateSpecialIndex");async function Ss({timeline:r,timelineAddr:e,metaspace:t,space:o}){let n=`[${Ss.name}]`;try{if(Ve&&console.log(`${n} starting... (I: f2b605361368e1956f6db878dbfeb825)`),!r&&!e)throw new Error("either timeline or timelineAddr required. (E: 97551b2b18ecd22a18185a783f9a0825)");e??=y({ibGib:r});let a=await t.getLatestAddr({addr:e,space:o})??e;if(!a)throw new Error(`${n} (UNEXPECTED) Could not get latest address for timeline ${y({ibGib:r})}. (E: a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9)`);let s;if(e===a){if(!r){let i=await t.get({addrs:[a],space:o});if(i.errorMsg||(i.ibGibs??[]).length!==1)throw new Error(`${n} (UNEXPECTED) couldn't get latest timeline ibgib (${a}) from space (${o.ib}). errorMsg: ${i.errorMsg??"[unknown error]"} (E: 3fc767a594788a43a4ba18c87491a825)`);r=i.ibGibs.at(0)}s=Ye({ibGib:r})}else{let i=await t.get({addrs:[a],space:o});if(i.errorMsg||(i.ibGibs??[]).length!==1)throw new Error(`${n} (UNEXPECTED) couldn't get latest timeline ibgib (${a}) from space (${o.ib}). errorMsg: ${i.errorMsg??"[unknown error]"} (E: b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0)`);s=i.ibGibs.at(0)}return s}catch(a){throw console.error(`${n} ${E(a)}`),a}finally{Ve&&console.log(`${n} complete.`)}}f(Ss,"getLatestTimelineIbGibDto_nonLocking");async function Z({timeline:r,timelineAddr:e,mut8Opts:t,metaspace:o,space:n,skipLock:a,timelineIndexInfo:s,noDna:i}){let c=`[${Z.name}]`;try{if(Ve&&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 p=await o.get({addrs:[e],space:n});if(!p.success||p.ibGibs?.length!==1)throw new Error(`couldn't get timeline ibGib from timelineAddr (${e}) in space (${n?.ib??"undefined"}) (E: genuuid)`);r=p.ibGibs.at(0)}let d=await $s({timeline:r}),l=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 p=await Ss({timeline:r,metaspace:o,space:n}),h=await at({...t,src:p,dna:!i,nCounter:!0}),g=h.newIbGib;return await o.persistTransformResult({resTransform:h,space:n}),s&&await Is({type:s.type,rel8nInfos:[{rel8nName:s.rel8nName,ibGibs:[g]}],metaspace:o,space:n,skipLock:a}),await o.registerNewIbGib({ibGib:g,space:n}),g},"fn");return a?await l():await Gt({scope:d,secondsValid:180,maxDelayMs:100,maxLockAttempts:1800,space:n,callerInstanceId:nt(),fn:l})}catch(d){throw console.error(`${c} ${E(d)}`),d}finally{Ve&&console.log(`${c} complete.`)}}f(Z,"mut8Timeline");async function _s({ib:r,data:e,rel8ns:t,noDna:o,parentIb:n,parentIbGib:a,metaspace:s,space:i}){let c=`[${_s.name}]`;try{if(Ve&&console.log(`${c} starting...`),i??=await s.getLocalUserSpace({lock:!1}),!i)throw new Error("(UNEXPECTED) space is required, but is falsy. (E: 252994a554224b17aa9816c7a765c925)");a??=n?a=F.primitive({ib:n}):a=q;let d=await F.firstGen({parentIbGib:a,ib:r,data:e,rel8ns:t,dna:!o,nCounter:!0,squash:!!o,tjp:{timestamp:!0,uuid:!e?.uuid}});return await s.persistTransformResult({resTransform:d,space:i}),await s.registerNewIbGib({ibGib:d.newIbGib,space:i}),d}catch(d){throw console.error(`${c} ${E(d)}`),d}}f(_s,"createTimeline");async function wl({ibGib:r,metaspace:e,space:t}){let o=`[${wl.name}]`;try{if(Ve&&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 a=await e.get({addrs:n,space:t});if(!a.success||(a.ibGibs??[]).length!==n.length){let s=n.filter(i=>!a.ibGibs?.some(c=>y({ibGib:c})===i));throw new Error(`Could not get all dna ibGibs for ${y({ibGib:r})}. Addrs not found: ${s.join(", ")}. Errors: ${a.errorMsg??"[unknown error (E: 92cf95774828d8a978331da859098625)]"} (E: d2c0b1a9a8b7c6d5e4f3a2b1a0b9c8d7)`)}return a.ibGibs}catch(n){throw console.error(`${o} ${E(n)}`),n}}f(wl,"getDna");async function Rn({timeline:r,getLatest:e,includeDna:t,metaspace:o,space:n}){let a=`[${Rn.name}]`;try{if(Ve&&console.log(`${a} starting... (I: 7fbc442a27e8f9fda8ac4228ded84825)`),n??=await o.getLocalUserSpace({lock:!1}),!n)throw new Error("(UNEXPECTED) space is required. (E: e3d1c0b1a9a8b7c6d5e4f3a2b1a0b9c8)");let s=e?await Ss({timeline:r,metaspace:o,space:n}):Ye({ibGib:r}),i=y({ibGib:s}),c={},d=t?Qo({ibGibs:await wl({ibGib:s,metaspace:o,space:n})}):void 0,l=r.rel8ns?.past??[];if(l.length===0)return{headIbGib:s,orderedPastIbGibs:[],pastIbGibMap:c,dnaMap:d};let b=await o.get({addrs:l,space:n});if(!b.success||(b.ibGibs??[]).length!==l.length){let h=l.filter(g=>!b.ibGibs?.some(m=>y({ibGib:m})===g));throw new Error(`Could not get all dna ibGibs for ${i}. Addrs not found: ${h.join(", ")}. Errors: ${b.errorMsg??"[unknown error (E: 887339d8b5580ed1ac9892a554255525)]"} (E: 4ab7a8a58adff4e238171f7c110c6825)`)}c=Qo({ibGibs:b.ibGibs})??{};let p=[];for(let h of l){let g=c[h];if(!g)throw new Error("(UNEXPECTED) pastIbGib falsy? due to our logic, the pastIbGibMap should be complete. (E: 6010d8c14184124008631928e1265525)");p.push(g)}return{headIbGib:s,orderedPastIbGibs:p,pastIbGibMap:c,dnaMap:d}}catch(s){throw console.error(`${a} ${E(s)}`),s}finally{Ve&&console.log(`${a} complete.`)}}f(Rn,"getHistory");async function As({timeline:r,getLatest:e,metaspace:t,space:o}){let n=`[${As.name}]`;try{return Ve&&console.log(`${n} starting... (I: c7a328b14018642138ebb47870c15626)`),(await Rn({timeline:r,getLatest:e,includeDna:!1,metaspace:t,space:o})).orderedPastIbGibs.map(i=>y({ibGib:i}))}catch(a){throw console.error(`${n} ${E(a)}`),a}finally{Ve&&console.log(`${n} complete.`)}}f(As,"getHistoryAddrs");var kn="sync_sagamsg";async function Ts({data:r}){let e=`[${Ts.name}]`;try{return[kn,r.sagaId,r.stage].join(" ")}catch(t){throw console.error(`${e} ${E(t)}`),t}}f(Ts,"getSyncSagaMessageIb");async function Gs({frameIbGib:r,space:e}){let t=`[${Gs.name}]`;try{let n=(await Na({ibGib:r,rel8nNames:[Be],space:e}))[Be];if(!n||n.length===0)throw new Error(`(UNEXPECTED) No sync message stone found found for frame: ${r.ib} (E: 8a4b2c1d3e5f6a9b7c8d9e0f1a2b3c4d)`);if(n.length>1)throw new Error(`(UNEXPECTED) Multiple sync message stones found (${n.length}) for frame: ${r.ib}. logic not currently equipped to handle multiple messages per frame. (E: 1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d)`);return n[0]}catch(o){throw console.error(`${t} ${E(o)}`),o}}f(Gs,"getSyncSagaMessageFromFrame");var Bn="anon_fn",yl={fnHash:""};var $l=!1;function Cs({data:r}){let e=`[${Cs.name}]`;try{if($l&&console.log(`${e} starting... (I: 37bb06e0390c5bcadf04501727d64923)`),!r?.fnHash)throw new Error("data.fnHash required (E: 2e560f2c59822bc5ba024d4a8e99d323)");return`witness ${Bn} ${r.fnHash}`}catch(t){throw console.error(`${e} ${t.message}`),t}finally{$l&&console.log(`${e} complete.`)}}f(Cs,"getAnonymousFnIb");var fr=class{static{f(this,"AnonymousFnWitness_V1")}fn;ib=Bn.concat();gib=re;data=H(yl);rel8ns;constructor(e){if(this.fn=e,!e)throw new Error("fn required (E: b1e1478f466a2a347b75e7c336f8d323)")}async witness(e){return this.data.fnHash=await Ke({s:this.fn.toString()}),this.ib=Cs({data:this.data}),this.gib=await ue({ibGib:this}),this.fn(e)}};var Un=!1;function _b({err:r}){let e=`[${_b.name}]`;try{if(Un&&console.log(`${e} starting... (I: 96f8b767c50f24768ced7beebb291723)`),ao(r)){let t=r;if(!r.data)throw new Error("err isIbGib but err.data is false. (E: 151a6bab647c638c454fd277ac468f23)");if(Kt({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{Un&&console.log(`${e} complete.`)}}f(_b,"extractObsErrMsg");function vs(r){let e=`[${vs.name}]`;try{Un&&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 l=>(await t.next(l),q),"fnNext"),n=f(async l=>(l.ib==="complete"?t.complete&&await t.complete():Kt({ibGib:l})?t.error&&await t.error(l):await t.next(l),q),"fnWitness"),a=new fr(o),s=new fr(n),i={ib:"observer",witness:f(async l=>await s.witness(l),"witness"),next:f(async l=>{await a.witness(l)},"next")},c=t.error??(async l=>{let b;if(typeof l=="string")b=E(l);else if(l.ib)if(Kt({ibGib:l}))b=E(l.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 l instanceof Error?b=E(l):typeof l.message=="string"?b=E(l.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)`)}),d=new fr(async l=>(c(l),q));if(i.error=async l=>{typeof l=="string"?l=await Tr({rawMsg:l}):l instanceof Error&&(l=await Tr({rawMsg:l.message}));try{await d.witness(l)}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 l=t.complete,b=new fr(async p=>(await l(),q));i.complete=async()=>{try{await b.witness(q)}catch(p){console.error(`${e} there was an error when executing completeAnonFnWitness (wrapper for observer.complete fn) error: ${E(p)} (E: c9e61b08429e42c1b85d2215f735ba2f)`)}}}return i}catch(t){throw console.error(`${e} ${t.message}`),t}finally{Un&&console.log(`${e} complete.`)}}f(vs,"fnObs");var Mn=!1,Os=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}},Ns=class r extends Os{static{f(this,"KeystoneConfigBuilder_HashV1")}lc=`[${r}]`;_algo;_rounds;withHash({algo:e,rounds:t}){let o=`${this.lc}[${this.withHash.name}]`;try{return Mn&&console.log(`${o} starting... (I: 15d1b3bd2e98bba33fc6c78228755826)`),this._algo=e,this._rounds=t,this}catch(n){throw console.error(`${o} ${E(n)}`),n}finally{Mn&&console.log(`${o} complete.`)}}build(){let e=`${this.lc}[${this.build.name}]`;try{if(Mn&&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:pt.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{Mn&&console.log(`${e} complete.`)}}},Eo=class{static{f(this,"KeystoneConfig")}static hash(){return new Ns}};function xs(r){if(r.type&&r.type!==pt.hash_reveal_v1)throw new Error(`invalid type (${r.type}). Only ${pt.hash_reveal_v1} currently implemented. (E: c38616cd7a459149f670418f88766526)`);let{salt:e,id:t,size:o,sequential:n,random:a,targetBinding:s,replenishStrategy:i,verbs:c,hashAlgorithm:d,hashRounds:l}=r;return Eo.hash().withId(t).withSalt(e).withSize(o??Ic).withHybrid({seqCount:n??Sc,randCount:a??_c}).withTargetBinding(s??Ac).withReplenishStrategy(i??Tc).withHash({algo:d??Gc,rounds:l??Cc}).forVerbs(c??[]).build()}f(xs,"createStandardPoolConfig");function Ab(r){if(r.type&&r.type!==pt.hash_reveal_v1)throw new Error(`invalid type (${r.type}). Only ${pt.hash_reveal_v1} currently implemented. (E: 09c1f7772bd2a7910f5562b4934d3826)`);let{salt:e,id:t,size:o,sequential:n,random:a,targetBinding:s,replenishStrategy:i,verbs:c,hashAlgorithm:d,hashRounds:l}=r;return Eo.hash().withId(t).withSalt(e).withSize(o??vc).withHybrid({seqCount:n??Oc,randCount:a??Nc}).withTargetBinding(s??xc).withReplenishStrategy(i??Lc).withHash({algo:d??Dc,rounds:l??Pc}).forVerbs(c??[]).build()}f(Ab,"createHighSecurityPoolConfig");function Il(r){return Ab({...r,id:r.id??yr,verbs:r.verbs??[qa.MANAGE]})}f(Il,"createManagePoolConfig");function Sl({template:r,salt:e}){let t=r.behavior;return Eo.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(Sl,"createPoolConfigFromJson");var x=!0,Fn=!0,ct="[ControlDomain]",W=class r{static{f(this,"SyncSagaCoordinator")}lc=`[${r.name}]`;constructor(){}defaultSessionConnectPoolConfig(){return xs({id:yt,salt:`session-connect-${Date.now()}`,verbs:[tr],size:20,sequential:2,random:2,targetBinding:0,replenishStrategy:De.deleteAll})}defaultSessionSyncPoolConfig(){return xs({id:$r,salt:`session-sync-${Date.now()}`,verbs:[wt],size:200,sequential:3,random:3,targetBinding:3,replenishStrategy:De.topUp})}async sync({peer:e,domainIbGibs:t,senderIdentity:o,fnSenderSecret:n,conflictStrategy:a=X.abort,metaspace:s,localSpace:i}){let c=`${this.lc}[${this.sync.name}]`;if(x&&console.log(`${c} starting...`),!i){debugger;throw new Error(`${c} source (or localSpace) required (E: 25df3761f7686a1099a552f83c95d326)`)}if(o||n){if(!o)throw new Error("(UNEXPECTED) senderIdentity falsy but fnSenderSecret truthy? if either is used, both must be truthy. (E: e366628a4919c7d727d2cbd8e5b75e26)");if(!n)throw new Error("(UNEXPECTED) fnSenderSecret falsy but senderIdentity truthy? if either is used, both must be truthy. (E: 7d55ce37ae482fec48e3398158161926)")}let d=await U(),l=await Nn();if(!l.next)throw new Error("(UNEXPECTED) updates$.next falsy? (E: d24cd82184aec130c89a320819b39126)");let b,p,h=new Promise((S,A)=>{b=S,p=A}),g=await zc(),m=await s.createNewLocalSpace({opts:{allowCancel:!1,spaceName:g,getFnPrompt:s.getFnPrompt,logalot:x}});if(!m)throw new Error("Failed to create temp space (E: 8f4e2f3d6c1b4b1a8f4e2f3d6c1b4b1a)");await m.initialized;let w=f(async()=>{},"cleanup");return(async()=>{try{let S=t?t.map($=>y({ibGib:$})):void 0;e.setOptionalOpts({sagaId:d,senderIdentity:o,fnSenderSecret:n,sessionConnectPoolConfig:this.defaultSessionConnectPoolConfig(),sessionSyncPoolConfig:this.defaultSessionSyncPoolConfig(),targetAddrs:S}),await e.establishSessionIdentity(),await e.connect({sagaId:d});let{initFrame:A,initDomainGraph:I}=await this.createInitFrame({sagaId:d,domainIbGibs:t,conflictStrategy:a,metaspace:s,localSpace:i,tempSpace:m,peer:e});if(await this.executeSagaLoop({initFrame:A,initDomainGraph:I,peer:e,updates$:l,localSpace:i,tempSpace:m,metaspace:s}),b(),!l.complete)throw new Error("(UNEXPECTED) updates$.complete falsy? (E: d24cd82184aec130c89a320819b39126)");l.complete()}catch(S){if(console.error(`${c} ${E(S)}`),p(S),!l.error)throw new Error("(UNEXPECTED) updates$.error falsy? (E: 392ce77c073272e4c398c3e86583ce26)");l.error(S)}finally{await w()}})(),{sagaId:d,updates$:l,done:h}}async continueSync({sagaContext:e,mySpace:t,myTempSpace:o,metaspace:n,peer:a}){let s=`${this.lc}[${this.continueSync.name}]`;try{x&&console.log(`${s} starting... (I: f64e08bf77d1425378601f380384ec26)`);let i=await this.handleResponseSagaContext({sagaContext:e,mySpace:t,myTempSpace:o,metaspace:n});if(i){if(i.nextFrameInfo?.sagaComplete)return null}else return x&&console.log(`${s} Handler returned null (Saga End). (I: 43da8bb6c846b1fe7766332643be0e26)`),null;if(i.errorMsg)throw new Error(`Couldn't handle response saga context. errorMsg: ${i.errorMsg} (E: 7b41a183cf3cb58a5859c803800cf826)`);if(!i.nextFrameInfo)throw new Error("(UNEXPECTED) contextResult.nextFrameInfo falsy? (E: 5740542f5eb8ccb41dfec188d87c1e26)");let{frame:c,payloadIbGibsDomain:d}=i.nextFrameInfo,l=await this.createSyncSagaContext({sagaFrame:c,localSpace:t,payloadIbGibsDomain:d,metaspace:n,sessionIdentityAddr:e.rel8ns?.sessionIdentity?.[0],peer:a,skipSign:!0}),b=await cr({context:l});if(b.length>0)throw new Error(`(UNEXPECTED) just created sync saga context () and there were immediateValidationErrors? immediateValidationErrors: ${b} (E: c120e8e0aa98673d685267a8a36e5826)`);return l}catch(i){throw console.error(`${s} ${E(i)}`),i}finally{x&&console.log(`${s} complete.`)}}async executeSagaLoop({initFrame:e,initDomainGraph:t,peer:o,updates$:n,localSpace:a,tempSpace:s,metaspace:i}){let c=`${this.lc}[${this.executeSagaLoop.name}]`,d=e,l=[];for(;d;){let b=new Map,p=`${c}[peer.payloadIbGibsDomainReceived$]`,h=await o.payloadIbGibsDomainReceived$.subscribe(vs({next:f(async g=>{x&&console.log(`${p} next fired. (I: 2b4bdf502a38a90ba33d9711e7cb7826)`);let m=y({ibGib:g});Fn&&console.log(`${c}${ct} DOMAIN STREAM RECEIVED <- observable: ${m} (I: d69ee80fcaece272483ec33b2d289826)`),b.set(m,g)},"next"),error:f(async g=>{ao(g)?console.error(`${p} error fired. error: ${JSON.stringify(g.data)} (E: 01cc08ba05ad99682831174fd7c31a26)`):(console.dir(g),console.error(`${p} error fired. error: ${E(g)} (E: 73d3d61464e8e4ce4cd6efd8b9675826)`))},"error"),complete:f(async()=>{x&&console.log(`${p} complete fired. (I: a47218aa9e4433fdb97c068880a45826)`),await h.unsubscribe()},"complete")}));try{let g=await this.createSyncSagaContext({sagaFrame:d,payloadIbGibsDomain:l,localSpace:a,metaspace:i,sessionIdentityAddr:o.currentSessionIdentityAddr,peer:o});if(Fn){let _=l.map(G=>y({ibGib:G}));console.log(`${c}${ct} SENDER TRANSMIT -> peer.witness (I: 5b0081803698770f0bf64992220b312)`),console.log(`${c}${ct} Context: ${y({ibGib:g})}`),console.log(`${c}${ct} Frame: ${y({ibGib:d})}`),console.log(`${c}${ct} DOMAIN Payloads (${_.length}): ${_.join(", ")||"(none)"}`)}n.next(g),o.setOptionalOpts({localSpace:a,localTempSpace:s});let m=await o.witness(g);if(!m)if(d)if((await Gs({frameIbGib:d,space:a}))?.data?.stage===me.commit){x&&console.log(`${c} Sender sent Commit. Peer returned no response. Saga Complete. (I: 26f9ee073858ca78b8284753368b5226)`),d=null;break}else throw new Error("(UNEXPECTED) responseCtx falsy and currentFrame truthy, but we're not in the commit stage? This may be expected ultimately, but atow I am not seeing this as being expected. (E: cc34498962bd370deeff351fac939f26)");else throw new Error("(UNEXPECTED) no response and currentFrame falsy? (E: 8d1085ea2f28cfc3f9c922649864a826)");if(!m.data)throw new Error("(UNEXPECTED) responseCtx.data falsy? (E: a969992bae53ab18a827ec58aec15826)");n.next(m);let w=await cr({context:m});if(w.length>0)throw new Error(`contextAndSagaFrameValidationErrors: ${w} (E: 6eebe8e7fa437c00a8cde3ada3c66826)`);let S=await this.validateReturnContext({requestCtx:g,responseCtx:m,localSpace:a});if(S.length>0)throw new Error(`validateReturnContext errors: ${S.join(", ")} (E: cb8a023b9d0728cceb09fa3da0bb8226)`);let A=m.data[Ja]||[];if(A.length>0&&(m.payloadIbGibsDomain=await this.pollForDomainPayloads({expectedAddrs:A,pollIntervalMs:20,domainPayloadsMap:b,tempSpace:s})),!m.sagaFrame)throw new Error("(UNEXPECTED) responseCtx.sagaFrame falsy? the Peer should have set this when it got the response back from the remote. (E: e650adadf9a2063ec6764a1e31d3d826)");if(Fn){let _=m.data?.["@payloadAddrsControl"]||[];console.log(`${c}${ct} SENDER RECEIVED <- peer.witness (I: 3dc76a9744d89a4fc3e2f076c2be4826)`),console.log(`${c}${ct} Response Context: ${y({ibGib:m})}`),console.log(`${c}${ct} Response Saga Frame: ${y({ibGib:m.sagaFrame})}`),console.log(`${c}${ct} CONTROL Payloads (${_.length}): ${_.join(", ")||"(none)"}`),console.log(`${c}${ct} DOMAIN Payloads (${A.length}): ${A.join(", ")||"(none)"}`)}let I=await this.handleResponseSagaContext({sagaContext:m,initDomainGraph:t,mySpace:a,myTempSpace:s,metaspace:i});if(I){if(I.nextFrameInfo?.sagaComplete){x&&console.log(`${c} Handler returned null (Saga End). (I: 123bf9e7dca8886de72553a8d4f29e26)`);break}}else{console.error(`${c} NAG ERROR (DOES NOT THROW): does this ever hit now? (E: e04d02efc2a8e72a88b79f1f0f95ca26)`);break}if(I.errorMsg)throw new Error(`Couldn't handle response saga context. errorMsg: ${I.errorMsg} (E: c948e81d513b2a0eb8b8afa878edc626)`);if(!I.nextFrameInfo)throw new Error("(UNEXPECTED) contextResult.nextFrameInfo falsy? (E: c287a82e823e662a77923278e2418826)");let{frame:$,payloadIbGibsDomain:T}=I.nextFrameInfo;if(d=$,l=[...T||[]],Fn){let _=l.map(G=>y({ibGib:G}));console.log(`${c}${ct} HANDLER RESULT -> next iteration (I: 6b0d88c4c28857ccd812381515bd7826)`),console.log(`${c}${ct} Next Frame: ${y({ibGib:d})}`),console.log(`${c}${ct} DOMAIN for next (${_.length}): ${_.join(", ")||"(none)"}`)}}finally{await h.unsubscribe()}}}async createSyncSagaContext({sagaFrame:e,payloadIbGibsDomain:t,metaspace:o,localSpace:n,sessionIdentityAddr:a,peer:s,skipSign:i}){let c=`[${this.createSyncSagaContext.name}]`;try{if(x&&console.log(`${c} starting... (I: 6b87bee313e811d1d2fc90e87fbec826)`),!e.data)throw new Error("(UNEXPECTED) sagaFrame.data falsy? (E: 04c49b4cccba6842a8b52e4c6f570726)");if(!e.data.n&&e.data.n!==0)throw new Error("(UNEXPECTED) sagaFrame.data.n falsy and not 0? (E: 45b508da64a8b28428b11765d684b826)");let d=new Date,l=oe(d),b=d.getMilliseconds(),p={timestamp:l,timestampMs:b,sagaN:e.data.n},h=t?t?.map(T=>y({ibGib:T})):void 0;h&&h.length>0&&(p[Ja]=h);let g={sagaFrame:[y({ibGib:e})]},m;if(a){a=await o.getLatestAddr({addr:a,space:n})??a;let T=await te({addr:a,space:n});if(T.success&&T.ibGibs?.length===1)m=T.ibGibs[0],g.sessionIdentity=[a];else{debugger;throw new Error(`Couldn't get sessionIdentityAddr (${a}) in space: ${n.ib} (E: 5c29e80d68dbd1749866c358be093826)`)}}let w=await Es({data:p}),S=await F.stone({parentPrimitiveIb:xn,ib:w,data:p,rel8ns:g}),A=y({ibGib:S}),I;m&&!i&&(I=await s.signContext({contextAddr:A})),await qe({ibGib:S,space:n}),await xe({ibGib:S,space:n,fnBroadcast:void 0}),S.sagaFrame=e;let{msgStones:$}=await fn({sagaIbGib:e,localSpace:n});if($.length!==1)throw new Error("(UNEXPECTED) msgStones.length !== 1 inside createSyncSagaContext? (E: a98165cf46ab4e82b7bd5e45a273b826)");return S.sagaFrameMsg=$[0],t&&t.length>0&&(S.payloadIbGibsDomain=t),I&&(S.signedSessionIdentity=I),S}catch(d){throw console.error(`${c} ${E(d)}`),d}finally{x&&console.log(`${c} complete.`)}}async getKnowledgeMap({space:e,metaspace:t,domainIbGibs:o,tjpAddrs:n}){let a=`${this.lc}[${this.getKnowledgeMap.name}]`;try{if(x&&console.log(`${a} starting... (I: e184f8a7818666febfbbd2d841ed3826)`),!(o&&o.length>0)&&!(n&&n.length>0))throw new Error("(UNEXPECTED) domainIbGibs and tjpAddrs falsy/empty? we need one or the other (E: f674285111c8648398cd79d8c08ec826)");if(o&&o.length>0&&n&&n.length>0)throw new Error("(UNEXPECTED) both domainIbGibs and tjpAddrs truthy? only pass in one or the other. (E: f674285111c8648398cd79d8c08ec826)");let s=[];if(n)s=n;else if(o&&o.length>0){let{mapWithTjp_YesDna:c,mapWithTjp_NoDna:d}=vt({ibGibs:o}),l=[...Object.values(c),...Object.values(d)],b=bt({ibGibs:l});s=Object.keys(b)}else return console.warn(`${a} No domainIbGibs or tjpAddrs provided. Returning empty Knowledge. (W: 2b0e115e7578a83d1b26f7c726bf9426)`),{};if(s.length===0)return{};let i=await We({space:e,tjpAddrs:s});if(!i.data||!i.data.latestAddrsMap)throw new Error(`${a} Failed to get latest addrs. (E: 7d395940c0e1419165c5196c39c6c826)`);return i.data.latestAddrsMap}catch(s){throw console.error(`${a} ${E(s)}`),s}finally{x&&console.log(`${a} complete.`)}}async analyzeDomainIbGibs({domainIbGibs:e,space:t}){let o=`${this.lc}[${this.analyzeDomainIbGibs.name}]`;if(e.length===0)throw new Error("invalid domainIbGibs. expected at least one, but array is empty. (E: 820a719bcac5a16878a2af697113b826)");let n=await xt({ibGibs:e,live:!0,space:t}),a=n&&Object.keys(n).length>0;x&&console.log(`${o} graph generated. nodes: ${a?Object.keys(n).length:0}`);let s=a?Object.values(n):[],{mapWithTjp_YesDna:i,mapWithTjp_NoDna:c,mapWithoutTjps:d}=vt({ibGibs:s}),l=Object.values(d),b=[...Object.values(i),...Object.values(c)],p=bt({ibGibs:b}),h=this.sortTimelinesTopologically(p);return{stones:l,timelinesMap:p,topologicallySortedTjpAddrs:h,fullGraph:n}}async createInitFrame({sagaId:e,domainIbGibs:t,conflictStrategy:o,metaspace:n,localSpace:a,tempSpace:s,peer:i}){let c=`${this.lc}[${this.createInitFrame.name}]`;try{x&&console.log(`${c} starting... (I: 551af8b411ae9be712ce3358d43ee726)`);let d=await this.analyzeDomainIbGibs({domainIbGibs:t,space:a}),{timelinesMap:l,fullGraph:b,stones:p}=d;await qe({ibGibs:Object.values(b),space:s});let h={};Object.keys(l).forEach(S=>{let I=l[S].at(-1);h[S]=y({ibGib:I})});let g={sagaId:e,stage:me.init,knowledgeMap:h,mode:Za.sync,stones:p.map(S=>y({ibGib:S}))};x&&(console.log(`${c} SyncStage.init: ${me.init}, SyncStage.commit: ${me.commit}`),console.log(`${c} initData.stage: ${g.stage}`));let m=await this.createSyncMsgStone({data:g,localSpace:a,metaspace:n}),w=await this.evolveSyncSagaIbGib({msgStones:[m],conflictStrategy:o,metaspace:n,localSpace:a,sessionIdentity:i.currentSessionIdentity});return x&&console.log(`${c} sagaFrame (init): ${K(w)} (I: b3d6a8be69248f18713cc3073cb08626)`),{initFrame:w,initDomainGraph:b}}catch(d){throw console.error(`${c} ${E(d)}`),d}finally{x&&console.log(`${c} complete.`)}}async validateReturnContext({requestCtx:e,responseCtx:t,localSpace:o}){let n=`${this.lc}[${this.validateReturnContext.name}]`,a=[];try{if(e.sagaFrame&&t.sagaFrame){let c=y({ibGib:e.sagaFrame}),d=y({ibGib:t.sagaFrame});await Vr({olderAddr:c,newerAddr:d,space:o})||a.push(`Response saga frame (${d}) is not a valid continuation of request saga frame (${c}). (E: 2c85e8d97318ff24ac8a02bd3a068226)`)}else a.push("Missing sagaFrame on requestCtx or responseCtx. (E: b65c68ff891000ddca8d22384a088226)");let s=e.signedSessionIdentity?y({ibGib:e.signedSessionIdentity}):e.rel8ns?.sessionIdentity?.[0],i=t.rel8ns?.sessionIdentity?.[0];s!==i&&a.push(`Session identity mismatch. Expected ${s}, got ${i}. (E: ab98716bca88d2243cc822187768226)`)}catch(s){a.push(`Error during validateReturnContext: ${E(s)} (E: da878e1239aa88ee27bdfca005c28226)`)}return a}async pollForDomainPayloads({expectedAddrs:e,pollIntervalMs:t,domainPayloadsMap:o,tempSpace:n}){let a=`${this.lc}[${this.pollForDomainPayloads.name}]`;try{x&&console.log(`${a} starting... (I: 26dce86bfca572939885798802d6e926)`);let s=[],i=[...new Set(e)],c=[...i],d=Date.now(),l=5*60*1e3;for(;c.length>0;){if(Date.now()-d>l)throw new Error(`Timeout waiting for payloads: ${c.join(", ")} (E: 46e1683c9578095261aaf798bd5e1826)`);let b=[],p=[];for(let h of c)o.has(h)?(p.push(o.get(h)),o.delete(h)):b.push(h);p.length>0&&(await qe({space:n,ibGibs:p}),p.forEach(h=>s.push(h))),c=b,c.length>0&&await Oe(t)}if(i.length!==s.length)throw new Error("(UNEXPECTED) uniqueExpectedAddrs.length !== resultDomainPayloads.length? at this point, we expect all of the payload ibgibs to have been received. (E: 03749a7478c4b8b28bfc86951887a826)");return s}catch(s){throw console.error(`${a} ${E(s)}`),s}finally{x&&console.log(`${a} complete.`)}}async handleResponseSagaContext({sagaContext:e,initDomainGraph:t,mySpace:o,myTempSpace:n,metaspace:a}){let s=`${this.lc}[${this.handleResponseSagaContext.name}]`;try{x&&console.log(`${s} starting... (I: 5deec8a1f7a6d263c88cd458ad990826)`);let i=e.sagaFrame;if(!i.data)throw new Error("(UNEXPECTED) sagaIbGib.data falsy? (E: 71b938adf1d87c2527bfd4f86dfd0826)");x&&console.log(`${s} sagaIbGib: ${K(i)} (I: 1b99d87d262e9d18d8a607a80b1a0126)`);let{stage:c,messageData:d}=await this.getStageAndPayloadFromFrame({sagaFrame:i,space:o});x&&console.log(`${s} handling frame stage: ${c}`);let l;switch(c){case me.init:l=await this.handleInitFrame({sagaIbGib:i,messageData:d,metaspace:a,mySpace:o,myTempSpace:n});break;case me.ack:if(!t)throw new Error("(UNEXPECTED) initDomainGraph falsy on the sender? (E: a3d758ad954829aba88663188eafc826)");l=await this.handleAckFrame({sagaContext:e,sagaIbGib:i,initDomainGraph:t,metaspace:a,mySpace:o,myTempSpace:n});break;case me.delta:l=await this.handleDeltaFrame({sagaContext:e,sagaIbGib:i,metaspace:a,mySpace:o,myTempSpace:n});break;case me.commit:x&&console.log(`${s}[${Kr({sagaFrame:i})}] mySpace.ib: ${o.ib} (I: 5b270996d848907238d817fffa64a126)`),l=await this.handleCommitFrame({sagaIbGib:i,metaspace:a,mySpace:o,myTempSpace:n});break;default:throw new Error(`${s} (UNEXPECTED) Unknown sync stage: ${c} (E: 9c2b4c8a6d34469f8263544710183355)`)}return x&&console.log(`${s} nextFrameInfo: ${l?K(l):"undefined"} (I: a8ad281ca8e89385686d18327a105726)`),{errorMsg:void 0,nextFrameInfo:l}}catch(i){let c=`${s} ${E(i)}`;return console.error(c),{errorMsg:c}}finally{x&&console.log(`${s} complete.`)}}async handleInitFrame({sagaIbGib:e,messageData:t,mySpace:o,myTempSpace:n,metaspace:a}){let s=`${this.lc}[${this.handleInitFrame.name}]`;try{x&&console.log(`${s} starting... (I: 9d88dcad0408c029e898a4bcf3b08426)`),x&&console.log(`${s} [TEST DEBUG] Receiver mySpace: ${o.ib}`);let i=t;if(i.stage!==me.init)throw new Error(`${s} Invalid init frame: initData.stage !== SyncStage.init (E: c91be82970e4decc58f56bf8fc1ffc26)`);if(!i||!i.knowledgeMap)throw new Error(`${s} Invalid init frame: missing knowledgeMap (E: ed02c869e028d2d06841b9c7f80f2826)`);let c=e.data.conflictStrategy||X.abort,d=[],l=[],b=[],p=i.stones||[];if(p.length>0){x&&console.log(`${s} processing stones: ${p.length}`);let G=(await te({space:o,addrs:p})).rawResultIbGib;if(!G.data)throw new Error("(UNEXPECTED) rawResultIbGib.data falsy? (E: f3c40b492adc02c3f480b998fc7a5926)");let v=G.data.addrsNotFound;v&&v.length>0&&(x&&console.log(`${s} stones missing (requesting): ${v.length}`),v.forEach(N=>{l.some(D=>D.addr===N)||l.push({addr:N})}))}let h=i.knowledgeMap;x&&console.log(`${s} senderKnowledge: ${K(h)} (I: 9f957862356dfeae183c200854e86e26)`);let g=Object.keys(h);x&&console.log(`${s} [TEST DEBUG] senderTjpAddrs: ${JSON.stringify(g)}`),x&&console.log(`${s} senderTjpAddrs: ${K(g)} (I: 86ea4c53db0dc184c8b253386c402126)`);let m={};if(g.length>0){let _=await We({space:o,tjpAddrs:g});if(!_.data)throw new Error("(UNEXPECTED) resGetLatestAddrs.data falsy? (E: b180d813c088042b38e1e02e06a16926)");if(!_.data.latestAddrsMap)throw new Error("(UNEXPECTED) resGetLatestAddrs.data.latestAddrsMap falsy? (E: 16bc386dd51d0ff53a49620b1e641826)");m=_.data.latestAddrsMap,x&&console.log(`${s} [TEST DEBUG] receiverLatestAddrsMap: ${JSON.stringify(m)}`),x&&console.log(`${s} receiverLatestAddrsMap: ${K(m)} (I: 980975642cbccd8018cf0cd808d30826)`)}for(let _ of g){let G=h[_],v=m[_];if(!v){x&&console.log(`${s} [TEST DEBUG] Missing receiver timeline for TJP: ${_}. Requesting remoteAddr: ${G}`),l.push({addr:G,tjpAddr:_});continue}if(v===G){x&&console.log(`${s} [TEST DEBUG] TJP ${_}: Synced (receiverTipAddr === remoteAddr)`);continue}if(x&&console.log(`${s} [TEST DEBUG] TJP ${_}: receiverTipAddr=${v}, remoteAddr=${G} - checking for divergence...`),await Vr({olderAddr:G,newerAddr:v,space:o})){x&&console.log(`${s} [TEST DEBUG] TJP ${_}: Remote (sender) is in past - offering push`);let D=await Fr({ibGibAddr:v,live:!1,latestCommonFrameAddr:G,space:o});b.push({tjpAddr:_,addrs:Object.keys(D)})}else{let D=!1;try{D=await Vr({olderAddr:v,newerAddr:G,space:o})}catch(B){x&&console.log(`${s} expected error if we don't have remote. verbose logging error though: ${E(B)} (I: 47ea08d0b418cf4aa8a502a7bcb80826)`)}if(D)x&&console.log(`${s} [TEST DEBUG] TJP ${_}: receiver is in past - requesting delta`),l.push({addr:G,tjpAddr:_,latestAddrAlreadyHave:v});else if(x&&console.log(`${s} [TEST DEBUG] TJP ${_}: DIVERGENCE DETECTED! conflictStrategy=${c}`),c==="abort")d.push({tjpAddr:_,receiverTipAddr:v,senderTipAddr:G,receiverKnowledgeTimelineAddrs:[],reason:"divergence",terminal:!0});else if(c===X.optimisticWithLCS){let B=await te({addr:v,space:o});if(!B.success||B.ibGibs?.length!==1)throw new Error(`couldn't get local tip (${v}) from space (${o.ib}). errorMsg: ${B.errorMsg??"[unknown error (E: b3c3d823276300aa384ebdba4a8eb826)]"} (E: 83cb88a767e22bbda99c6788bec50526)`);let P=B.ibGibs[0],k=await As({timeline:P,space:o,metaspace:a});d.push({tjpAddr:_,receiverTipAddr:v,senderTipAddr:G,receiverKnowledgeTimelineAddrs:[...k,v],reason:"divergence",terminal:!1})}else throw new Error(`${s} Unsupported conflict strategy: ${c}. Only these currently implemented: ${Ir} (E: 8f12384180f8a718a983a749fe0adf26)`)}}if(d.some(_=>_.terminal))throw x&&console.warn(`${s} ABORTING Sync Saga due to terminal conflicts: ${JSON.stringify(d)}`),new Error(`the saga has terminal conflicts. conflicts: ${JSON.stringify(d)} (E: f2edbe93cc07a63b38bfc013d2213b26)`);if(!e.data)throw new Error("(UNEXPECTED) sagaIbGib.data falsy? (E: 24203af4600fb226ae6c1afbde442826)");let A={sagaId:e.data.uuid,stage:me.ack,deltaRequestAddrInfos:l,pushOfferInfos:b};d?.length>0&&(A.conflicts=d);let I=await this.createSyncMsgStone({data:A,localSpace:o,metaspace:a});x&&console.log(`${s} ackStone created: ${K(I)} (I: 313708132dd53ff946befb7833657826)`);let $=await this.evolveSyncSagaIbGib({prevSagaIbGib:e,msgStones:[I],localSpace:o,metaspace:a}),T;if(b.length>0){let _=[];T=[];let G=b.flatMap(P=>P.addrs),v=await te({addrs:G,space:o}),N=v.rawResultIbGib?.data;if(!N)throw new Error("(UNEXPECTED) resGet.rawResultIbGib.data falsy? (E: 1a2cc8cb99a1ffa60837e45a8229b826)");let D=N.addrsNotFound??[],B=N.addrsErrored??[];if(v.ibGibs&&v.ibGibs.length===G.length)v.ibGibs.forEach(P=>{T.push(P)});else if(v.ibGibs&&v.ibGibs.length>0)if(v.ibGibs.forEach(k=>{T.push(k)}),T.length+D.length+B.length===G.length)D.forEach(k=>_.push(k)),B.forEach(k=>_.push(k));else throw D.length===0&&B.length===0?new Error("(UNEXPECTED) found some but not all addrs but addrsNotFound and addrsErrored both empty? (E: ef1b2cf5bab8de2298ec507abe04e826)"):new Error("(UNEXPECTED) found some but not all addrs but addrsNotFound and addrsErrored don't contain the addrs not found? (E: ae9e015109f8c3c3a813da584cd98826)");else console.warn(`${s} we were expecting all domainAddrs in mySpace (${o.ib}) but we couldn't get all of them. addrsNotFound: ${D??[]}. addrsErrored: ${B??[]}. Trying temp space (${n.ib}). (W: f61908e264f8dddd2e3fb9084463d826)`),G.forEach(P=>_.push(P));if(_.length>0){x&&console.log(`${s} couldn't get all addrs in mySpace (${o.ib}). searchSecondSpaceAddrs: ${_} (I: 233fd954dbd84e51bca02fa8eed5f826)`);let P=await te({addrs:_,space:n});if(P.success&&P.ibGibs&&P.ibGibs.length===_.length)P.ibGibs.forEach(k=>T.push(k));else{P.ibGibs?.forEach(M=>T.push(M));let k=G.filter(M=>!T.map(j=>y({ibGib:j})).includes(M));throw new Error(`couldn't get some or all of addrs from either mySpace (${o.ib}) or myTempSpace (${n.ib}). addrsFailed: ${k} (E: 1394d412c4ffa4dd085f269b43338826)`)}}}return{frame:$,payloadIbGibsDomain:T}}catch(i){throw console.error(`${s} ${E(i)}`),i}finally{x&&console.log(`${s} complete.`)}}async handleAckFrame({sagaContext:e,sagaIbGib:t,initDomainGraph:o,mySpace:n,myTempSpace:a,metaspace:s}){let i=`${this.lc}[${this.handleAckFrame.name}]`;try{x&&console.log(`${i} starting... (I: 605b6860e898267a5b50c6d85704be26)`);let{messageData:c}=await this.getStageAndPayloadFromFrame({sagaFrame:t,space:n}),d=c,l=!0;if(!d)throw new Error(`${i} ackData falsy (E: 3b8415edc876084c88a25b98e2d55826)`);if(d.stage!==me.ack)throw new Error(`${i} Invalid ack frame: ackData.stage !== SyncStage.ack (E: 2e8b0a94b5954a66a6a1a7a0b3f5b7a1)`);if(x&&console.log(`${i} ackData: ${K(d)} (I: b817c5571c5e916fe8f90b892b3e8e26)`),!t.data)throw new Error("(UNEXPECTED) sagaIbGib.data falsy? (E: e3f2e8f162484859787651b85c011826)");let b=d.conflicts?H(d.conflicts):[];x&&console.log(`${i} [CONFLICT DEBUG] Received conflicts from Ack: ${b.length}`),x&&b.length>0&&console.log(`${i} [CONFLICT DEBUG] Conflicts detail: ${JSON.stringify(b,null,2)}`);let p=b.filter(_=>_.terminal);if(p.length>0)throw x&&console.warn(`${i} Received terminal conflicts from Ack: ${JSON.stringify(p)}`),new Error(`${i} Peer reported terminal conflicts. (E: 23a0096ee05a2ccfa89334e8f156b426)`);let h=[],g=[];if(b.length>0){x&&console.log(`${i} [CONFLICT DEBUG] Processing ${b.length} non-terminal conflicts`);for(let _ of b){let{receiverTipAddr:G,reason:v,senderTipAddr:N,terminal:D,receiverKnowledgeTimelineAddrs:B,tjpAddr:P}=_;if(D)throw new Error("(UNEXPECTED) conflict.terminal truthy? We expect this to already throw/abort the saga before this point in execution. (E: b42e982edca8b1156765de38f9e74626)");let k=o[N];if(!k)throw new Error(`(UNEXPECTED) senderTipIbGib falsy? initDomainGraph should have had the senderTipAddr (${N}) that was included in the ack frame conflicts. tjpAddr: ${P}. reason: ${v} (E: 3bd80f2054a924be98e6a7421bff4626)`);let{headIbGib:M,orderedPastIbGibs:j}=await Rn({timeline:k,getLatest:!0,metaspace:s,space:n}),Q=j.map(pe=>y({ibGib:pe})),ee=y({ibGib:M});if(_.senderKnowledgeTimelineAddrs=[...Q,ee],M.gib!==k.gib&&(_.senderTipAddr=ee,!Object.keys(o).includes(ee))){let pe=await xt({ibGibAddr:ee,live:!0,space:n}),He=Object.keys(pe);for(let tt of He)o[tt]||(o[tt]=pe[tt])}let Ge=B.findLast(pe=>Q.includes(pe));if(!Ge)throw new Error(`(UNEXPECTED) no latestCommonFrameAddr in the conflicts.receiverKnowledgeTimelineAddrs (${B.join(`
30
+ `)})? This would mean that it doesn't even have the tjpAddr (${P}). So what are we doing here? (E: 8931d1bdd6d8e100bf55f7c8a6924826)`);let Ce=await Fr({ibGibAddr:ee,live:!0,latestCommonFrameAddr:Ge,space:n}),Me=[];if(Object.keys(Ce).forEach(pe=>{Me.push(pe);let He=Ce[pe];h.push(He)}),Ge===G)x&&console.log(`${i} [CONFLICT DEBUG] TJP ${P}: Fast-forward detected (receiver behind sender). Excluding from active conflicts and sending delta payload.`);else{if(_.accretivePayloadAddrs)throw new Error("(UNEXPECTED) conflict.accretivePayloadAddrs already truthy? This is expected to be falsy at this point in the sync. (E: 6b6b1846779867849cbde208f4374326)");_.accretivePayloadAddrs=Me,g.push(_)}}g.length>0?l=!1:l=!0,x&&console.log(`${i} [CONFLICT DEBUG] Finished processing ${b.length} conflicts. Active (divergent) conflicts: ${g.length}. outgoingPayloadIbGibsDomain_conflicts.length (total outgoing payload ibgibs for ALL conflicts): ${h.length}`)}else x&&console.log(`${i} [CONFLICT DEBUG] No optimistic conflicts to process`);let m=await this.getPayloadsForRequestedInfos({deltaRequestAddrInfos:d.deltaRequestAddrInfos||[],mySpace:n}),w=[...h,...m],S;w.length===0?w=void 0:S=w.map(_=>y({ibGib:_}));let A={sagaId:t.data.uuid,stage:me.delta,conflicts:g,payloadAddrsDomain:S,deltaRequestAddrInfos:void 0,proposeCommit:l},I;x&&console.log(`${i} Creating Delta Stone. Data stage: ${A.stage}`);let $=await this.createSyncMsgStone({data:A,rel8ns:I,localSpace:n,metaspace:s}),T=await this.evolveSyncSagaIbGib({prevSagaIbGib:t,msgStones:[$],localSpace:n,metaspace:s});return x&&console.log(`${i} Delta Frame created. Rel8ns: ${JSON.stringify(T.rel8ns)}`),{frame:T,payloadIbGibsDomain:w}}catch(c){throw console.error(`${i} ${E(c)}`),c}finally{x&&console.log(`${i} complete.`)}}async handleDeltaFrame({sagaContext:e,sagaIbGib:t,mySpace:o,myTempSpace:n,metaspace:a}){let s=`${this.lc}[${this.handleDeltaFrame.name}]`;try{x&&console.log(`${s} starting... (I: a1d0a85eb4189466f86dfd61e3df2626)`);let{messageData:i}=await this.getStageAndPayloadFromFrame({sagaFrame:t,space:o}),c=i;if(!t.data)throw new Error("(UNEXPECTED) sagaIbGib.data falsy? (E: 8874e83e1a1b307938ee832862ec5826)");if(!t.data.conflictStrategy)throw new Error("(UNEXPECTED) sagaIbGib.data.conflictStrategy falsy? (E: 636205ab5b78fcb31d0cb1880770c826)");if(!c)throw new Error(`${s} deltaData falsy (E: 7c28c8d8f08a4421b8344e6727271421)`);if(c.stage!==me.delta)throw new Error(`${s} Invalid delta frame: deltaData.stage !== SyncStage.delta (E: 0c28c8d8f08a4421b8344e6727271421)`);x&&console.log(`${s} deltaData: ${K(c)} (I: a76008681df458cfbcdc4848f825a826)`),x&&console.log(`${s} [CONFLICT DEBUG] deltaData.payloadAddrsDomain count: ${c.payloadAddrsDomain?.length||0}`);let{conflictStrategy:d}=t.data,{deltaRequestAddrInfos:l,payloadAddrsDomain:b,proposeCommit:p}=c,h=c.proposeCommit??!1,g=e.payloadIbGibsDomain??[];x&&console.log(`${s} [CONFLICT DEBUG] Fulfilling ${(c.deltaRequestAddrInfos||[]).length} peer requests`);let m=await this.getPayloadsForRequestedInfos({deltaRequestAddrInfos:c.deltaRequestAddrInfos||[],mySpace:o});x&&console.log(`${s} [CONFLICT DEBUG] Outgoing payload size (with deps): ${m.length}`);let w=c.conflicts?H(c.conflicts):[],S=w.filter(T=>!T.resolved);if(S.length>0){if(d!==X.optimisticWithLCS)throw new Error(`(UNEXPECTED) conflictStrategy (${d}) is not ${X.optimisticWithLCS}? right now, this is the only one we've implemented. (E: ba3e08d92a66b24075016208a0f83226)`);for(let T of S){let _={};for(let he of T.accretivePayloadAddrs??[]){let rt=g.find(lt=>y({ibGib:lt})===he);if(!rt)throw new Error("(UNEXPECTED) conflictPayloadIbGib falsy? At this time in dev (01/27/2026), we're expecting this to be populated because we're only expecting one iteration of conflict resolution. If dev is later, this may no longer be the case. (E: b197417e762639089827aa3edaece826)");_[he]=rt}T.latestCommonFrameAddr;let{receiverKnowledgeTimelineAddrs:G,senderKnowledgeTimelineAddrs:v,reason:N,receiverTipAddr:D,senderTipAddr:B,tjpAddr:P}=T;if(!v)throw new Error("(UNEXPECTED) senderKnowledgeTimelineAddrs falsy? (E: 2a608892d11bd848e8f0c7a8d676d826)");let k=await xt({ibGibAddrs:[D],live:!0,space:o}),M=Object.values(k);await hn({ibGibs:M,space:n});for(let he of G){let rt=k[he];await xe({ibGib:rt,space:n})}let j=v.findLast(he=>G.includes(he));if(!j)throw new Error("(UNEXPECTED) latestCommonFrameAddr falsy? how we can have a conflict without a common point in history? (E: 53de0a181838b3e5bf98d0887994b826)");let Q=await Fr({ibGibAddr:T.receiverTipAddr,latestCommonFrameAddr:j,live:!0,space:o});Object.values(Q).forEach(he=>m.push(he));let ee=await ts({conflictStrategy:d,timelineAddrsA:v,timelineAddrsB:G,latestCommonFrameAddr:j,ibGibReadCache:_,space:n}),{dnasCreatedInGraft:Ge,dnasReplayed:Ce,intermediateIbGibsCreatedInGraft:Me,newGraftTip:Fe,graftInfoCreated:pe}=ee;if(T.createdDnaAddrs=Ge.map(he=>y({ibGib:he})),T.replayedDnaAddrs=Ce.map(he=>y({ibGib:he})),T.createdDomainAddrs=[...Me.map(he=>y({ibGib:he})),y({ibGib:pe}),y({ibGib:Fe})],!Fe.rel8ns)throw new Error("(UNEXPECTED) newGraftTip.rel8ns falsy? we expect this to have graftinfo rel8ns, let alone dna (E: 718788f5a44e815618ac1ba621c8a826)");let He=Fe.rel8ns[$t];if(!He||He.length===0)throw new Error(`(UNEXPECTED) newGraftTip.rel8ns.${$t} falsy/empty? we expect to always have graft info attached to timelines that are grafted. (E: 45abf31654c8aa517df4d0882b996826)`);T.graftInfoAddr=He.at(-1);let tt=[Ge,Ce,Me,[pe,Fe]];for(let he of tt.flat())if((await ge({ibGib:he})??[]).length>0){console.dir(he);debugger;console.log(K(he))}T.accretivePayloadAddrs??=[],tt.forEach(he=>he.forEach(rt=>{let lt=y({ibGib:rt});T.accretivePayloadAddrs.includes(lt)||T.accretivePayloadAddrs.push(lt),m.some(qr=>y({ibGib:qr})===lt)||m.push(rt)})),T.resolved=!0}}let A=[],I=m.length>0,$=A.length>0;if(I||$){let T={sagaId:c.sagaId,stage:me.delta,payloadAddrsDomain:m.map(v=>y({ibGib:v})),requests:$?A:void 0,conflicts:w},_=await this.createSyncMsgStone({data:T,localSpace:o,metaspace:a});return{frame:await this.evolveSyncSagaIbGib({prevSagaIbGib:t,msgStones:[_],localSpace:o,metaspace:a}),payloadIbGibsDomain:m}}else if(h){let T=await Hr({sagaIbGib:t,space:o}),_=await pn({history:T});return _.length>0?{frame:await this.createCommitFrame({sagaIbGib:t,errors:_,metaspace:a,mySpace:o})}:(await this.executeLocalCommit({sagaHistory:T,deltaFrame:t,localTempSpace:n,localSpace:o,metaspace:a}),{frame:await this.createCommitFrame({sagaIbGib:t,errors:void 0,metaspace:a,mySpace:o})})}else{let T={sagaId:c.sagaId,stage:me.delta,proposeCommit:!0,conflicts:w},_=await this.createSyncMsgStone({data:T,localSpace:o,metaspace:a}),G=await this.evolveSyncSagaIbGib({prevSagaIbGib:t,msgStones:[_],localSpace:o,metaspace:a});if(c.proposeCommit){x&&console.log(`${s} Peer proposed commit. Accepting & Committing.`);let v={sagaId:c.sagaId,stage:me.commit,success:!0},N=await this.createSyncMsgStone({data:v,localSpace:o,metaspace:a});return{frame:await this.evolveSyncSagaIbGib({prevSagaIbGib:G,msgStones:[N],localSpace:o,metaspace:a})}}return{frame:G,payloadIbGibsDomain:m}}}catch(i){throw console.error(`${s} ${E(i)}`),i}finally{x&&console.log(`${s} complete.`)}}async executeLocalCommit({deltaFrame:e,commitFrame:t,sagaHistory:o,metaspace:n,localSpace:a,localTempSpace:s}){let i=`${this.lc}[${this.executeLocalCommit.name}]`;try{if(x&&console.log(`${i} starting... (I: 6734980446b86a63c1af6e2e206de826)`),!e&&!t)throw new Error("(UNEXPECTED) !deltaFrame && !commitFrame? we're expecting to execute the commit based off of EITHER a delta OR a commit frame. (E: 10cae319a2685a672866f5583514e326)");if(e&&t)throw new Error("(UNEXPECTED) deltaFrame && commitFrame? we're expecting to execute the commit based off of EITHER a delta OR a commit frame. (E: b9037b1ed6d8684ac8a5d01328bad826)");let d=!!e?e:t;if(!d)throw new Error("(UNEXPECTED) !currentFrame? something wrong with my logic. (E: 4ec0ce6625cc1d677bc902c839ca1a26)");let l=Kr({sagaFrame:d});if(x&&console.log(`${i} currentFrameOrigin: ${l} (I: 3add8f8390c89743ae554bd3cc60b826)`),!d.data)throw new Error("(UNEXPECTED) currentFrame.data falsy? (E: a8be68d48668d93d992d793834823826)");let b=[],p=f(I=>{b.includes(I)||b.push(I)},"fnAddPayloadAddr"),h=o.filter(I=>{let $=Kr({sagaFrame:I.sagaIbGib});return l!==$});o.filter(I=>{let $=Kr({sagaFrame:I.sagaIbGib});return l===$}).forEach(I=>{if(!I.sagaIbGib.data)throw new Error("(UNEXPECTED) sagaIbGib.data falsy? (E: 34d7f8cdee14717ce828878d98f89826)");I.msgStones.forEach($=>{if(!$.data)throw new Error("(UNEXPECTED) msgStone.data falsy? (E: 21406101f91847514cc759c8a7382f26)");if($.data.stage===me.ack){let T=$.data;T.pushOfferInfos&&T.pushOfferInfos.length>0&&T.pushOfferInfos.forEach(_=>{_.addrs.forEach(G=>p(G))})}else if($.data.stage===me.delta){let T=$.data;T.payloadAddrsDomain&&T.payloadAddrsDomain.length>0&&T.payloadAddrsDomain.forEach(_=>p(_))}})}),x&&console.log(`${i}[${l}] allPayloadAddrsDomainTransferred: ${b.length>0?b.join(", "):"none"} (I: a1950eb3ca95bdc9ec18a4b8823e9826)`);let m=[];if(b.length>0){let I=await te({addrs:b,space:s});if(I.success&&I.ibGibs&&I.ibGibs.length===b.length)m=I.ibGibs.concat();else{if(!I.rawResultIbGib)throw new Error("(UNEXPECTED) !resGetAllTransferred.rawResultIbGib falsy? (E: dc6cf8729668f4fbe8c024f887d97a26)");let{addrsNotFound:$,addrsErrored:T,errors:_}=I.rawResultIbGib.data;throw new Error(`(UNEXPECTED) we couldn't get all addrs transferred throughout the saga from the tempspace (${s.ib})? addrsNotFound: ${$??[]}. addrsErrored: ${T??[]}. errors: ${_??[]}(E: 222e341e634862b4d88ae7282584d826)`)}}let w=[],S=await un({sagaHistory:o});if(S)for(let I of S){if(!I.resolved)throw new Error("(UNEXPECTED) finalConflict.resolved falsy? right now, we're expecting to resolve all conflicts. (E: a40ca8f1f54665407892ec21123a4f26)");if(!I.graftInfoAddr)throw new Error("(UNEXPECTED) finalConflict resolved but graftInfoAddr falsy? we're expecting all resolved conflicts to have a graftInfoAddr (E: d082488347570947b82008a835200126)");if(!(await it({addrs:[I.graftInfoAddr],space:s})).at(0))throw new Error(`(UNEXPECTED) couldn't get finalConflictGraftInfo from localTempSpace (${s})? (E: 35e3c8130608d991e8fb295807812826)`);let{createdDnaAddrs:_,replayedDnaAddrs:G,createdDomainAddrs:v}=I;if(!_||_.length===0)throw new Error("(UNEXPECTED) finalConflict.createdDnaAddrs falsy/empty? (E: 9689f8be5bd19650b8d4a058b65db826)");if(!G||G.length===0)throw new Error("(UNEXPECTED) finalConflict.replayedDnaAddrs falsy/empty? (E: f42878ed1cee3e9828567c5ab8179526)");if(!v||v.length===0)throw new Error("(UNEXPECTED) finalConflict.createdDomainAddrs falsy/empty? (E: cc41251d1acfe91a48d1b6080259ed26)");(await it({addrs:[..._,...G,...v],space:s})).forEach(D=>w.push(D))}let A=[];if(m.forEach(I=>A.push(I)),w.forEach(I=>A.push(I)),A.length===0)x&&console.log(`${i}[${l}] no changes on this end (I: fa30d18e83a87ee9e8487fbb5d632b26)`);else{x&&console.log(`${i}[${l}] ${A.length} changes detected (I: fa30d18e83a87ee9e8487fbb5d632b26)`),x&&console.log(`${i} put all into localSpace (${a.ib}) starting... (I: d5e0d9870e380b61e80c729660058826)`);let{payload_Dnas:I,payload_NonDnas:$}=await hn({ibGibs:A,space:a});x&&console.log(`${i} put all into localSpace (${a.ib}) complete. (I: d5e0d9870e380b61e80c729660058826)`);let T=await ns({sagaHistory:o,myTempSpace:s}),{mapWithTjp_NoDna:_,mapWithTjp_YesDna:G,mapWithoutTjps:v}=vt({ibGibs:$,filterPrimitives:!0});x&&console.log(`${i} register mapWithoutTjps starting... (I: 2b84d8f8dda85adde88696d8419bf726)`);let N=Object.values(v);for(let M of N)x&&console.log(`${i} registering ${y({ibGib:M})} (I: 4647b4f42d27cffe0fbfce8846755826)`),await n.registerNewIbGib({ibGib:M,space:a});x&&console.log(`${i} mapWithoutTjps complete. (I: 2b84d8f8dda85adde88696d8419bf726)`),x&&console.log(`${i} register mapWithTjp_NoDna starting... (I: 96e648e4db382499b8bfaa1b37c24826)`);let D=bt({ibGibs:Object.values(_)}),B=Object.keys(D);for(let M of B){let j=D[M];for(let Q of j)await n.registerNewIbGib({ibGib:Q,space:a})}x&&console.log(`${i} register mapWithTjp_NoDna complete. (I: 96e648e4db382499b8bfaa1b37c24826)`),x&&console.log(`${i} register mapWithTjp_YesDna starting... (I: d54a820e9442dee4681f6228a6795926)`);let P=bt({ibGibs:Object.values(G)}),k=Object.keys(P);for(let M of k){let j=P[M];for(let Q of j)T.includes(y({ibGib:Q}))||await n.registerNewIbGib({ibGib:Q,space:a})}x&&console.log(`${i} register mapWithTjp_YesDna complete. (I: d54a820e9442dee4681f6228a6795926)`)}}catch(c){throw console.error(`${i} ${E(c)}`),c}finally{x&&console.log(`${i} complete.`)}}async createCommitFrame({sagaIbGib:e,errors:t,metaspace:o,mySpace:n}){let a=`[${this.createCommitFrame.name}]`;try{x&&console.log(`${a} starting... (I: 48fc57c023f80122135a284855757526)`);let s=t&&t.length>0?{sagaId:e.data.uuid,stage:me.commit,success:!1,errors:t}:{sagaId:e.data.uuid,stage:me.commit,success:!0},i=await this.createSyncMsgStone({data:s,localSpace:n,metaspace:o});return await this.evolveSyncSagaIbGib({prevSagaIbGib:e,msgStones:[i],localSpace:n,metaspace:o})}catch(s){throw console.error(`${a} ${E(s)}`),s}finally{x&&console.log(`${a} complete.`)}}async handleCommitFrame({sagaIbGib:e,mySpace:t,myTempSpace:o,metaspace:n}){let a=`${this.lc}[${this.handleCommitFrame.name}]`;try{if(x&&console.log(`${a} starting... (I: e179573bdd881202f8ba3168da1c3826)`),!e.data)throw new Error("(UNEXPECTED) sagaIbGib.data falsy? (E: cbc31dbb7d28b5b8c8cddb510d7d2826)");if(e.data.errors&&e.data.errors.length>0)throw new Error("not implemented...saga errored out on other end but we've already committed our changes. we need to implement undoing our changes, i.e., rollback commit, which basically is deleting all the payloads that we already put in in our previous commit. (E: e8eb789e0c08f0b3cf93607cb73e9f26)");{let s=await Hr({sagaIbGib:e,space:t}),i=await pn({history:s});return i.length>0?{frame:await this.createCommitFrame({sagaIbGib:e,metaspace:n,mySpace:t,errors:i})}:(await this.executeLocalCommit({commitFrame:e,sagaHistory:s,localSpace:t,localTempSpace:o,metaspace:n}),console.error(`${a} NAG ERROR (NOT THROWN): implement cleanup logic, including add a cleanup method to the peer (E: 3a9a24befb98a981a88fbdbf52920e26)`),x&&console.log(`${a} Peer committed. Finalizing saga locally. Saga Complete.`),{sagaComplete:!0})}}catch(s){let i=`${a} ${E(s)}`;return console.error(i),{frame:await this.createCommitFrame({sagaIbGib:e,errors:[i],metaspace:n,mySpace:t})}}finally{x&&console.log(`${a} complete.`)}}async createSyncMsgStone({data:e,rel8ns:t,localSpace:o,metaspace:n}){let a=`${this.lc}[${this.createSyncMsgStone.name}]`;try{x&&console.log(`${a} starting... (I: 5f7f98e8ff980364f7191fcee4531e26)`);let s=await Ts({data:e}),i=await F.stone({ib:s,parentPrimitiveIb:kn,data:e,rel8ns:t,uuid:!0});return x&&console.log(`${a} Created stone: ${y({ibGib:i})}`),await n.put({ibGib:i,space:o}),await n.registerNewIbGib({ibGib:i}),i}catch(s){throw console.error(`${a} ${E(s)}`),s}finally{x&&console.log(`${a} complete.`)}}async getPayloadsForRequestedInfos({deltaRequestAddrInfos:e,mySpace:t}){let o=`${this.lc}[${this.getPayloadsForRequestedInfos.name}]`;try{x&&console.log(`${o} starting... (I: 4fe13d0d80050f20a8b74ba80cee5826)`);let n={};for(let{addr:s,latestAddrAlreadyHave:i}of e){let c;if(i?c=await Fr({ibGibAddr:s,latestCommonFrameAddr:i,space:t,live:!0}):c=await xt({ibGibAddr:s,space:t,live:!0}),Object.keys(c).length===0)throw new Error(`(UNEXPECTED) couldn't get requested addrs in mySpace (${t.ib})? How did the receiver know to ask for these addrs if they weren't in our original graph? (E: 281eaebcdf77dd73e8245b2872100826)`);Object.values(c).forEach(l=>{n[y({ibGib:l})]=l})}return Object.values(n)}catch(n){throw console.error(`${o} ${E(n)}`),n}finally{x&&console.log(`${o} complete.`)}}async evolveSyncSagaIbGib({prevSagaIbGib:e,conflictStrategy:t,msgStones:o,localSpace:n,metaspace:a,sessionIdentity:s}){let i=`${this.lc}[${this.evolveSyncSagaIbGib.name}]`;try{if(!o||o.length===0)throw new Error(`${i} msgStones required (E: d13f8afcfb8816aeb26baae7df3ef726)`);let c=o[0].data;if(!c?.sagaId||!c?.stage)throw new Error(`${i} Invalid stone data (missing sagaId or stage) (E: c004f85ce8f8958b11839f8d68c38826)`);let d=c.sagaId,l=c.stage;for(let b of o){let p=b.data;if(p.sagaId!==d)throw new Error(`${i} Mismatched sagaId in stones. Expected ${d}, got ${p.sagaId} (E: 29e02719e426ecbbf8ee66887a2be226)`);if(p.stage!==l)throw new Error(`${i} Mismatched stage in stones. Expected ${l}, got ${p.stage} (E: d12c6571b0882f762921b60880c3f826)`)}if(e){let b=[{rel8nName:Be,ibGibs:o}];if(!e.rel8ns)throw new Error("(UNEXPECTED) prevSagaIbGib.rel8ns falsy? (E: 81375841aff85b1e48ea42ca218e6826)");if(!e.rel8ns[Be]||e.rel8ns[Be].length===0)throw new Error("(UNEXPECTED) prevSagaIbGib.rel8ns[SYNC_MSG_REL8N_NAME] falsy/empty? (E: 15156baad26fcccda80aa3a31718c726)");let p=[{rel8nName:Be,ibGibAddrs:e.rel8ns[Be]}];return await dr({timeline:e,rel8nInfos:b,rel8nRemovalInfos:p,metaspace:a,space:n,noDna:!0})}else{let b={uuid:d,n:0,isTjp:!0,conflictStrategy:t};if(s){let w=de({ibGib:s});if(!w)throw new Error("(UNEXPECTED) sessionIdentity is truthy but sessionIdentityTjpAddr falsy? (E: f52004c10288987a6886f4e8fdf90826)");b.sessionIdentityTjpAddr=w}let p=await os({data:b}),h=o.map(w=>y({ibGib:w})),g={[Be]:h},m=await _s({space:n,metaspace:a,ib:p,data:b,rel8ns:g,parentIb:sn,noDna:!0});if(m.intermediateIbGibs)throw new Error("(UNEXPECTED) resNew.intermediateIbGibs? we were assuming we were creating a single frame. (E: 456818147235d991ccb4d10d0bbe4826)");return m.newIbGib}}catch(c){throw console.error(`${i} ${E(c)}`),c}}async getStageAndPayloadFromFrame({sagaFrame:e,space:t}){let o=`${this.lc}[${this.getStageAndPayloadFromFrame.name}]`;try{if(x&&console.log(`${o} starting... (I: fddc287bd4d55253dc50e519fd352226)`),!e.rel8ns)throw new Error("(UNEXPECTED) sagaFrame.rel8ns falsy? (E: 725bc8eb5dfe5c7058907ad8e3063826)");let n=e.rel8ns?.[Be];if(n&&n.length>0){let a=n[0],s=await te({addr:a,space:t});if(s.ibGibs&&s.ibGibs.length>0){let i=s.ibGibs[0];if(!i.data)throw new Error("(UNEXPECTED) message stone.data falsy? (E: 4d4abcea90d87ba1328434e83d0d0826)");if(!i.data.stage)throw new Error("(UNEXPECTED) message stone.data.stage falsy? (E: 72c8d22310996644ecdd2b5fdb288c26)");return{stage:i.data.stage,messageData:i.data}}else throw new Error(`couldn't get stoneAddr (${a}) from space (${t.ib}) (E: f3c826e756f8a5c358beb88aa4a65e26)`)}else throw new Error(`(UNEXPECTED) no stone addrs rel8d to sync saga ibgib frame? sagaFrame addr: ${y(e)} (E: 43eae8579e289d016741b5526052f226)`)}catch(n){throw console.error(`${o} ${E(n)}`),n}finally{x&&console.log(`${o} complete.`)}}sortTimelinesTopologically(e){let t=`${this.lc}[${this.sortTimelinesTopologically.name}]`,o=Object.keys(e);if(o.length===0)return[];let n={};o.forEach(l=>{e[l].forEach(b=>{let p=y({ibGib:b});n[p]=l})});let a={};o.forEach(l=>a[l]=new Set),o.forEach(l=>{e[l].forEach(b=>{b.rel8ns&&Object.values(b.rel8ns).flat().forEach(p=>{if(!p)return;let h=n[p];h&&h!==l&&a[l].add(h)})})});let s=new Set,i=new Set,c=[],d=f(l=>{if(i.has(l)){console.warn(`${t} Cycle detected involving ${l}. Ignoring edge to break cycle. (W: 7e7352347102431aa5318db962459929)`);return}s.has(l)||(i.add(l),a[l].forEach(b=>d(b)),s.add(l),i.delete(l),c.push(l))},"visit");return o.forEach(l=>{s.has(l)||d(l)}),c}};var _l={$schema:"../../../../libs/core-gib/dist/keystone/policy/schemas/keystone.medium.schema.json",metadata:{name:"Space-Gib Default Identity Policy",securityLevel:"medium"},pools:{sync:{id:"sync",allowedVerbs:["sync"],algo:"SHA-256",rounds:1,behavior:{size:200,replenish:"top-up",selectSequentially:2,selectRandomly:2,targetBindingCount:5}},manage:{id:"manage",allowedVerbs:["manage"],algo:"SHA-512",rounds:10,behavior:{size:2e3,replenish:"replace-all",selectSequentially:5,selectRandomly:5,targetBindingCount:16}},revoke:{id:"revoke",allowedVerbs:["revoke"],algo:"SHA-512",rounds:10,behavior:{size:2e3,replenish:"delete-all",selectSequentially:5,selectRandomly:5,targetBindingCount:16}},connect:{id:"connect",allowedVerbs:["connect"],algo:"SHA-256",rounds:1,behavior:{size:20,replenish:"top-up",selectSequentially:2,selectRandomly:2,targetBindingCount:3}}}};var Gb=_l.pools;function fe(r,e){let t=Gb[r];if(!t)throw new Error(`Pool template not found in space-gib JSON config: ${r}`);return Sl({template:t,salt:e})}f(fe,"getSpaceGibPoolConfig");var L={COMMON:lr.COMMON,DEFAULT_POOL:{ID:"default",SIZE:20,SELECT_SEQUENTIALLY:2,SELECT_RANDOMLY:2,TARGET_BINDING_COUNT:3},CONNECT_POOL:lr.CONNECT_POOL},H4={MIN_DEFAULT_POOL_SIZE:50,ALLOWED_ALGORITHMS:[Je.sha_256,Je.sha_512]};var Ls=so,J=class{static{f(this,"SpaceGibApiBridge")}lc="[SpaceGibApiBridge]";async postGenesisKeystone(e){let t=`${this.lc}[${this.postGenesisKeystone.name}]`;try{Ls&&console.log(`${t} starting... (I: eecd082fc4a4381c8857928e8b090826)`);let o=await fetch("/api/keystone/genesis",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({keystoneIbGib:e})}),n=await o.json();if(!o.ok){let a=n.message||n.error||"Unknown error";return console.error(`${t} [NAG][ibgib-paradigm] server rejected genesis keystone: ${a}`),{success:!1,message:a,addr:n.addr}}return Ls&&console.log(`${t} genesis keystone posted successfully.`),{success:!0,addr:n.addr}}catch(o){let n=E(o);return console.error(`${t} error: ${n}`),{success:!1,message:n}}finally{Ls&&console.log(`${t} complete.`)}}async putEvolveKeystone(e,t,o=[]){let n=`${this.lc}[${this.putEvolveKeystone.name}]`;try{console.log(`${n} posting evolved keystone...`);let a=`/api/keystone/evolve/${encodeURIComponent(e)}`,s=await fetch(a,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({keystoneIbGib:t,relatedIbGibs:o})}),i=await s.json();if(!s.ok){let c=i.message||i.error||"Unknown error";return console.error(`${n} server rejected keystone evolution: ${c}`),{success:!1,message:c}}return console.log(`${n} keystone evolution accepted by server.`),{success:!0}}catch(a){let s=E(a);return console.error(`${n} fetch error: ${s}`),{success:!1,message:s}}}async getKeystoneGraph(e){let t=`${this.lc}[${this.getKeystoneGraph.name}]`;try{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"}}),a=await n.json();if(console.log(`${t} fetch keystone graph complete.`),!n.ok){let s=a.message||a.error||"Unknown error";return console.error(`${t} server rejected keystone graph get: ${s}`),{success:!1,message:s}}return{success:!0,graph:a.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{console.log(`${n} fetching single ibGib frame...`);let a=`/api/ibgib/${encodeURIComponent(e)}/${encodeURIComponent(t)}?getLatest=${o}&getGraph=false`,s=await fetch(a,{method:"GET",headers:{Accept:"application/json"}}),i=await s.json();if(console.log(`${n} fetching single ibGib frame complete.`),!s.ok){let c=i.message||i.error||"Unknown error";return console.error(`${n} server rejected ibGib get: ${c}`),{success:!1,message:c}}return{success:!0,ibGib:i}}catch(a){let s=E(a);return console.error(`${n} fetch error: ${s}`),{success:!1,message:s}}}async getIbGibGraph(e,t,o=!1){let n=`${this.lc}[${this.getIbGibGraph.name}]`;try{console.log(`${n} fetching ibGib graph...`);let a=`/api/ibgib/${encodeURIComponent(e)}/${encodeURIComponent(t)}?getLatest=${o}&getGraph=true`,s=await fetch(a,{method:"GET",headers:{Accept:"application/json"}}),i=await s.json();if(console.log(`${n} fetching ibGib graph complete.`),!s.ok){let c=i.message||i.error||"Unknown error";return console.error(`${n} server rejected ibGib graph get: ${c}`),{success:!1,message:c}}return{success:!0,graph:i.graph,addr:i.addr}}catch(a){let s=E(a);return console.error(`${n} fetch error: ${s}`),{success:!1,message:s}}}},Y4=new J;var be="[dev-tools]",O={};window.ibgibDebugState=O;function u(r){let e=document.getElementById("dev-panel-log");if(!e)return;let t=new Date().toISOString().slice(11,23);e.textContent=`[${t}] ${r}
31
+ `+e.textContent}f(u,"devLog");async function Dt(r){let e=`${be}[performPhaseSetup(${r.phaseText})]`,t=document.getElementById(r.btnId);if(t)try{t.disabled=!0,u(`${r.phaseText} Setup: Generating Alice's long-lived Domain Keystone (I) and Target (X)...`);let o=await V(),n=await o.getLocalUserSpace({});if(!n)throw new Error("No default space found in metaspace.");let s=await new se().genesis({masterSecret:r.masterSecret,configs:[fe("sync",r.syncSalt),fe("manage",r.manageSalt)],metaspace:o,space:n,frameDetails:{client:"space-gib-web-dev",timestamp:oe()}});O.domainI=s,O.domainIMasterSecret=r.masterSecret,u(`${r.phaseText} Setup: \u2713 Domain Keystone (I) created locally: ${y({ibGib:s})}`),u(`${r.phaseText} Setup: Starting postGenesisKeystone...`);let c=await new J().postGenesisKeystone(s);if(c.success)u(`${r.phaseText} Setup: \u2713 Domain Keystone registered and stored on receiver (server).`);else throw u(`${r.phaseText} Setup: X postGenesisKeystone failed: ${c.message}.`),new Error(`${r.phaseText} Setup: Server rejected genesis domain keystone: ${c.message}`);let d=await F.firstGen({parentIbGib:q,ib:r.ib,data:r.data,dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),l=d.newIbGib;await o.persistTransformResult({resTransform:d,space:n}),await o.registerNewIbGib({ibGib:l}),O.targetX=l,u(`${r.phaseText} Setup: \u2713 Target (X) created and persisted locally: ${y({ibGib:l})}`),u(`\u2713 ${r.phaseText} Setup Complete! Ready for ${r.phaseText} Sync.`),t.textContent=`\u2713 ${r.phaseText} Setup Complete`;let b=document.getElementById(r.nextBtnId);b&&(b.disabled=!1)}catch(o){u(`\u2717 ${r.phaseText} Setup FAILED: ${E(o)}`),console.error(`${e} ${r.phaseText} Setup error:`,o),t.disabled=!1}}f(Dt,"performPhaseSetup");async function br(r){let e=`${be}[performPhaseSync(${r.phaseText})]`,t=document.getElementById(r.btnId);if(t)try{t.disabled=!0,u(`${r.phaseText} Sync: Executing senderCoordinator.sync(...) using WebSocket Peer...`);let o=O.domainI,n=O.targetX;if(!o||!n){u(`\u26A0 ${r.phaseText} Sync: Missing setup state. Please run Setup first.`),t.disabled=!1;return}let a=y({ibGib:o}),s=await V(),i=await s.getLocalUserSpace({});if(!i)throw new Error("No default space.");let c=location.protocol==="https:"?"wss:":"ws:",d=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(a)}`,wsUrl:`${c}//${location.host}/api/sync/ws/${encodeURIComponent(a)}`}),l=new W,b=await U();O.sagaId=b,O.senderPeer=d,await d.initializeOpts({localMetaspace:s,localSpace:i,senderIdentity:o,fnSenderSecret:f(async()=>O.domainIMasterSecret,"fnSenderSecret"),sagaId:b,sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[a]});try{await(await l.sync({domainIbGibs:[n],senderIdentity:o,fnSenderSecret:f(async()=>O.domainIMasterSecret,"fnSenderSecret"),peer:d,localSpace:i,metaspace:s,conflictStrategy:X.optimisticWithLCS})).done}catch(h){if(r.expectSyncFailure)u(`${r.phaseText} Sync: Coordinator sync executed (${r.failureMessageSuffix??"errors expected"}): ${E(h)}`);else throw h}u(`\u2713 ${r.phaseText} Sync Execution Complete! Ready for State Checks.`),t.textContent=`\u2713 ${r.phaseText} Sync Run`;let p=document.getElementById(r.nextBtnId);p&&(p.disabled=!1)}catch(o){u(`\u2717 ${r.phaseText} Sync FAILED: ${E(o)}`),console.error(`${e} ${r.phaseText} Sync error:`,o),t.disabled=!1}}f(br,"performPhaseSync");var Xt=null;function Al(){let r=`${be}[initWsTestButton]`,e=document.getElementById("btn-test-ws");if(!e){console.warn(`${r} btn-test-ws not found \u2014 skipping`);return}e.addEventListener("click",()=>{try{if(Xt&&Xt.readyState===WebSocket.OPEN){Xt.send(JSON.stringify({ping:"hello from client",ts:Date.now()})),u("\u2192 sent ping on existing connection");return}let o=`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}/api/debug/ws-echo`;u(`\u2192 connecting to ${o}`),Xt=new WebSocket(o),Xt.addEventListener("open",()=>{u("\u2713 WebSocket connected"),e.textContent="Send WS Ping"}),Xt.addEventListener("message",n=>{u(`\u2190 ${n.data}`)}),Xt.addEventListener("close",n=>{u(`\u2717 WebSocket closed (code ${n.code})`),e.textContent="Test WebSocket",Xt=null}),Xt.addEventListener("error",n=>{u("\u2717 WebSocket error \u2014 check console"),console.error(`${r} WebSocket error`,n)})}catch(t){u(`\u2717 ${E(t)}`),console.error(`${r} ${E(t)}`)}})}f(Al,"initWsTestButton");function Tl(){let r=document.getElementById("btn-print-dev-state");r&&r.addEventListener("click",()=>{u("Printing debug state to console..."),console.dir(O)})}f(Tl,"initPrintStateButton");function Gl(){let r=`${be}[initCreateDomainKeystoneButton]`,e=document.getElementById("btn-create-domain-keystone");e&&e.addEventListener("click",async()=>{try{e.disabled=!0,u("Generating dummy Domain Keystone (I)...");let t=await V(),o=await t.getLocalUserSpace({});if(!o)throw new Error("No default space found in metaspace.");let n="password",s=await new se().genesis({masterSecret:n,configs:[Il({id:"default",salt:await U(),replenishStrategy:De.topUp})],metaspace:t,space:o,frameDetails:{client:"space-gib-web-dev",timestamp:oe()}}),i=y({ibGib:s});u(`\u2713 Local genesis complete: ${i}`),O.domainI=s,O.domainIMasterSecret=n,u("Posting genesis keystone to server...");let d=await new J().postGenesisKeystone(s);if(!d.success){u(`\u2717 Server rejected genesis keystone: ${d.message}`),e.disabled=!1;return}u("\u2713 Server accepted Domain Keystone (I)"),e.textContent="\u2713 Domain Keystone Created";let l=document.getElementById("btn-create-test-ibgib");l&&(l.disabled=!1)}catch(t){u(`\u2717 ${E(t)}`),console.error(`${r} ${E(t)}`),e.disabled=!1}})}f(Gl,"initCreateDomainKeystoneButton");function Cl(){let r=`${be}[initCreateTestIbGibButton]`,e=document.getElementById("btn-create-test-ibgib");if(!e){console.warn(`${r} btn-create-test-ibgib not found \u2014 skipping`);return}e.addEventListener("click",async()=>{try{u("Generating dummy X^Xtjp ibgib...");let o=(await F.firstGen({parentIbGib:q,ib:"test data",data:{hello:"world",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}})).newIbGib,n=y({ibGib:o});O.targetX=o,u(`\u2713 Created X: ${n}`),e.textContent="\u2713 Test IbGib (X) Created";let a=document.getElementById("btn-create-session-keystone");a&&(a.disabled=!1)}catch(t){u(`\u2717 ${E(t)}`),console.error(`${r} ${E(t)}`)}})}f(Cl,"initCreateTestIbGibButton");function vl(){let r=`${be}[initCreateSessionKeystoneButton]`,e=document.getElementById("btn-create-session-keystone");if(!e){console.warn(`${r} btn-create-session-keystone not found \u2014 skipping`);return}e.addEventListener("click",async()=>{try{u("Generating Session Keystone (S^Stjp)...");let t=O.domainI,o=O.targetX;if(!t){u("\u26A0 No domain keystone (I) found in state. Please Create Domain Keystone first.");return}if(!o){u("\u26A0 No target ibgib (X) found in state. Please Create Test IbGib first.");return}let n=await V(),a=await n.getLocalUserSpace({});if(!a)throw new Error("No default space found in metaspace.");let s="ephemeral-"+Math.random().toString(),i=new se;console.warn(`${be}[NAG] placeholder genesis keystone config right now (W: 69b108687cf8bec0f9a8e148bcca8d26)`);let c=await i.genesis({masterSecret:s,configs:[{id:L.DEFAULT_POOL.ID,salt:await U(),type:L.COMMON.TYPE,algo:L.COMMON.ALGO,rounds:L.COMMON.ROUNDS,behavior:{size:L.DEFAULT_POOL.SIZE,replenish:L.COMMON.REPLENISH,selectSequentially:L.DEFAULT_POOL.SELECT_SEQUENTIALLY,selectRandomly:L.DEFAULT_POOL.SELECT_RANDOMLY,targetBindingCount:L.DEFAULT_POOL.TARGET_BINDING_COUNT},allowedVerbs:[]},{id:L.CONNECT_POOL.ID,salt:await U(),type:L.COMMON.TYPE,algo:L.COMMON.ALGO,rounds:L.COMMON.ROUNDS,behavior:{size:L.CONNECT_POOL.SIZE,replenish:L.COMMON.REPLENISH,selectSequentially:L.CONNECT_POOL.SELECT_SEQUENTIALLY,selectRandomly:L.CONNECT_POOL.SELECT_RANDOMLY,targetBindingCount:L.CONNECT_POOL.TARGET_BINDING_COUNT},allowedVerbs:[L.CONNECT_POOL.VERB]}],metaspace:n,space:a,frameDetails:{client:"space-gib-web-session",target_I:t?y({ibGib:t}):void 0,target_X:o?y({ibGib:o}):void 0}}),d=y({ibGib:c});O.sessionS=c,O.sessionSecret=s,u(`\u2713 Created Session Keystone: ${d}`),e.textContent="\u2713 Session Keystone Created"}catch(t){u(`\u2717 ${E(t)}`),console.error(`${r} ${E(t)}`)}})}f(vl,"initCreateSessionKeystoneButton");function Ol(){let r=document.getElementById("btn-1b-setup");r&&r.addEventListener("click",()=>{Dt({phaseText:"1B",btnId:"btn-1b-setup",nextBtnId:"btn-1b-sync",masterSecret:"test-sender-secret-phase1",syncSalt:"senderidentitysyncsaltphase1",manageSalt:"senderidentitymanagesaltphase1",ib:"test data",data:{hello:"world",random:Math.random()}})})}f(Ol,"init1bSetupButton");function Nl(){let r=document.getElementById("btn-1b-sync");r&&r.addEventListener("click",()=>{br({phaseText:"1B",btnId:"btn-1b-sync",nextBtnId:"btn-1b-check",expectSyncFailure:!0,failureMessageSuffix:"establish phase successfully run; connection/sync errors expected in 1B"})})}f(Nl,"init1bSyncButton");function xl(){let r=`${be}[init1bCheckButton]`,e=document.getElementById("btn-1b-check");e&&e.addEventListener("click",async()=>{try{u("1B Check: Asserting cryptographic and durable state expectations from respec...");let t=await V(),o=await t.getLocalUserSpace({});if(!o)throw new Error("No default space.");let n=O.domainI,a=O.targetX,s=await t.getLatestAddr({addr:y({ibGib:n}),space:o});if(!s){u("\u2717 Check: Evolved domain keystone tip I1 NOT found in local space!");return}u("\u2713 Check: Evolved Domain Keystone (I1) created and stored locally.");let c=(await t.get({addrs:[s],space:o})).ibGibs?.[0];if(!c){u("\u2717 Check: Failed to load I1 from local space.");return}let d=c.data?.proofs?.find(G=>G.claim?.verb==="sync");d?u("\u2713 Check: I1 contains valid sync-verb claim proof."):u("\u2717 Check: I1 is missing sync-verb claim proof!");let l=d?.claim?.target;if(!l){u("\u2717 Check: I1 sync claim does not target a session keystone.");return}u(`\u2713 Check: Sync claim targets session keystone: ${l}`);let p=(await t.get({addrs:[l],space:o})).ibGibs?.[0];if(!p){u("\u2717 Check: Session Keystone (S) NOT found in local space.");return}u("\u2713 Check: Session Keystone (S) successfully created locally.");let h=p.data?.challengePools??[],g=h.some(G=>G.id===yt),m=h.some(G=>G.id===$r);g&&m?u("\u2713 Check: S contains both connect and sync challenge pools."):u(`\u2717 Check: S is missing challenge pools! (connect: ${g}, sync: ${m})`),u("Check: Verifying registrations on server (receiver metaspace)...");let w=new J,S=!1,A=!1,I=!1,$=y({ibGib:n}),T=await w.getKeystoneGraph($);if(T.success&&T.graph){let G=T.graph;S=G[$]!==void 0,A=G[s]!==void 0}else u(`\u2717 Check Server: Failed to fetch keystone graph from server: ${T.message}`);let _=await w.getIbGib($,l);if(_.success&&_.ibGib?I=!0:u(`\u2717 Check Server: Failed to fetch session keystone from server: ${_.message}`),S?u("\u2713 Check Server: Genesis Domain Keystone (I) registered on server."):u("\u2717 Check Server: Genesis Domain Keystone (I) missing on server!"),A?u("\u2713 Check Server: Evolved Domain Keystone (I1) accepted and stored on server."):u("\u2717 Check Server: Evolved Domain Keystone (I1) missing on server!"),I?u("\u2713 Check Server: Session Keystone (S) accepted and stored on server."):u("\u2717 Check Server: Session Keystone (S) missing on server!"),S&&A&&I){u("\u{1F389} ALL PHASE 1B ESTABLISH CHECKS PASSED FLAWLESSLY! \u2713"),e.textContent="\u2713 1B All Passed";let G=document.getElementById("btn-2b-setup");G&&(G.disabled=!1)}}catch(t){u(`\u2717 1B Check FAILED: ${E(t)}`),console.error(`${r} 1B Check error:`,t)}})}f(xl,"init1bCheckButton");function Ll(){let r=document.getElementById("btn-2b-setup");r&&r.addEventListener("click",()=>{Dt({phaseText:"2B",btnId:"btn-2b-setup",nextBtnId:"btn-2b-sync",masterSecret:"test-sender-secret-phase2",syncSalt:"senderidentitysyncsaltphase2",manageSalt:"senderidentitymanagesaltphase2",ib:"test data",data:{hello:"world2",random:Math.random()}})})}f(Ll,"init2bSetupButton");function Dl(){let r=document.getElementById("btn-2b-sync");r&&r.addEventListener("click",()=>{br({phaseText:"2B",btnId:"btn-2b-sync",nextBtnId:"btn-2b-check",expectSyncFailure:!0,failureMessageSuffix:"connect phase successfully run; subsequent sync errors expected in 2B"})})}f(Dl,"init2bSyncButton");function Pl(){let r=`${be}[init2bCheckButton]`,e=document.getElementById("btn-2b-check");e&&e.addEventListener("click",async()=>{try{u("2B Check: Asserting cryptographic and WebSocket state expectations...");let t=await V(),o=await t.getLocalUserSpace({});if(!o)throw new Error("No default space.");let n=O.domainI,a=y({ibGib:n}),s=await t.getLatestAddr({addr:a,space:o});if(!s){u("\u2717 Check: Evolved domain keystone tip I1 NOT found in local space!");return}u("\u2713 Check: Evolved Domain Keystone (I1) created and stored locally.");let c=(await t.get({addrs:[s],space:o})).ibGibs?.[0];if(!c){u("\u2717 Check: Failed to load I1 from local space.");return}let l=c.data?.proofs?.find(I=>I.claim?.verb==="sync")?.claim?.target;if(!l){u("\u2717 Check: I1 sync claim does not target a session keystone.");return}u(`\u2713 Check: Sync claim targets session keystone: ${l}`);let b=await t.getLatestAddr({addr:l,space:o});if(!b){u("\u2717 Check: Latest Session Keystone (S) NOT found in local space.");return}u("\u2713 Check: Found latest session keystone (S) locally.");let h=(await t.get({addrs:[b],space:o})).ibGibs?.[0];if(!h){u("\u2717 Check: Failed to load latest Session Keystone (S).");return}let g=h.data?.challengePools??[],m=g.find(I=>I.id===yt),w=g.find(I=>I.id===$r);if(m&&w)u("\u2713 Check: S contains both connect and sync challenge pools.");else{u(`\u2717 Check: S is missing challenge pools! (connect: ${!!m}, sync: ${!!w})`);return}let S=Object.keys(m.challenges).length;if(S===0)u("\u2713 Check: S connect pool successfully depleted (0 challenges remaining).");else{u(`\u2717 Check: S connect pool not depleted! (${S} challenges remaining)`);return}if(O.senderPeer&&O.senderPeer.isSocketOpen)u("\u2713 Check: WebSocket connection is active and OPEN.");else{u("\u2717 Check: WebSocket connection is NOT open or peer is missing!");return}u("\u{1F389} ALL PHASE 2B CONNECT CHECKS PASSED FLAWLESSLY! \u2713"),e.textContent="\u2713 2B All Passed";let A=document.getElementById("btn-3b-setup");A&&(A.disabled=!1)}catch(t){u(`\u2717 2B Check FAILED: ${E(t)}`),console.error(`${r} 2B Check error:`,t)}})}f(Pl,"init2bCheckButton");function Rl(){let r=document.getElementById("btn-3b-setup");r&&r.addEventListener("click",()=>{Dt({phaseText:"3B",btnId:"btn-3b-setup",nextBtnId:"btn-3b-sync",masterSecret:"test-sender-secret-phase3",syncSalt:"senderidentitysyncsaltphase3",manageSalt:"senderidentitymanagesaltphase3",ib:"test data 3b",data:{hello:"world3",random:Math.random()}})})}f(Rl,"init3bSetupButton");function kl(){let r=document.getElementById("btn-3b-sync");r&&r.addEventListener("click",()=>{br({phaseText:"3B",btnId:"btn-3b-sync",nextBtnId:"btn-3b-check"})})}f(kl,"init3bSyncButton");function Bl(){let r=`${be}[init3bCheckButton]`,e=document.getElementById("btn-3b-check");e&&e.addEventListener("click",async()=>{try{u("3B Check: Asserting cryptographic and WebSocket state expectations...");let t=await V(),o=await t.getLocalUserSpace({});if(!o)throw new Error("No default space.");let n=O.domainI,a=O.targetX,s=y({ibGib:a}),i=y({ibGib:n}),c=await t.getLatestAddr({addr:s,space:o});if(!c){u("\u2717 Check: Evolved target X NOT found in local space!");return}u(`\u2713 Check: Evolved target X found locally at: ${c}`);let d=await t.getDependencyGraph({ibGibAddr:c,space:o});if(!d||Object.keys(d).length===0){u("\u2717 Check: Failed to load target X dependency graph locally.");return}u(`\u2713 Check: Target X local graph loaded (${Object.keys(d).length} nodes).`);let l=new J,b=await l.getIbGibGraph(i,s,!0);if(!b.success||!b.graph){u(`\u2717 Check: Failed to fetch target X graph from server: ${b.message}`);return}let p=b.graph;if(u(`\u2713 Check: Target X server graph loaded (${Object.keys(p).length} nodes).`),Se({graphA:d,graphB:p}))u("\u2713 Check: Target X dependency graphs are equivalent on client and server.");else{u("\u2717 Check: Target X dependency graphs mismatch between client and server!");return}let g=await t.getLatestAddr({addr:i,space:o});if(!g){u("\u2717 Check: Evolved domain keystone tip I1 NOT found in local space!");return}u("\u2713 Check: Evolved Domain Keystone (I1) exists locally.");let w=(await t.get({addrs:[g],space:o})).ibGibs?.[0];if(!w){u("\u2717 Check: Failed to load I1 from local space.");return}let A=w.data?.proofs?.find(k=>k.claim?.verb==="sync")?.claim?.target;if(!A){u("\u2717 Check: I1 sync claim does not target a session keystone.");return}let I=await l.getIbGib(i,g);if(!I.success||!I.ibGib){u("\u2717 Check: Evolved Domain Keystone (I1) NOT found on server!");return}u("\u2713 Check: Evolved Domain Keystone (I1) exists on server.");let $=await t.getLatestAddr({addr:A,space:o});if(!$){u("\u2717 Check: Latest Session Keystone (S) NOT found in local space.");return}u(`\u2713 Check: Found latest session keystone (S) locally: ${$}`);let _=(await t.get({addrs:[$],space:o})).ibGibs?.[0];if(!_){u("\u2717 Check: Failed to load latest Session Keystone (S) locally.");return}let G=_.data?.n;u(`\u2713 Check: S tip evolved to n = ${G}.`),G!==3&&G!==4&&u(`\u26A0 Check: Expected S to evolve to n = 3 or 4, got n = ${G}. Continuing anyway...`);let v=await l.getIbGib(i,$);if(!v.success||!v.ibGib){u("\u2717 Check: Latest Session Keystone (S) NOT found on server!");return}u("\u2713 Check: Latest Session Keystone (S) exists on server.");let N=await t.getDependencyGraph({ibGibAddr:$,space:o}),D=await l.getIbGibGraph(i,A,!0);if(!D.success||!D.graph){u(`\u2717 Check: Failed to fetch session S graph from server: ${D.message}`);return}let B=D.graph;if(Se({graphA:N,graphB:B}))u("\u2713 Check: Session Keystone (S) dependency graphs are equivalent on client and server.");else{u("\u2717 Check: Session Keystone (S) dependency graphs mismatch between client and server!");return}u("\u{1F389} ALL PHASE 3B TRANSACTION SYNC CHECKS PASSED FLAWLESSLY! \u2713"),e.textContent="\u2713 3B All Passed"}catch(t){u(`\u2717 3B Check FAILED: ${E(t)}`),console.error(`${r} 3B Check error:`,t)}})}f(Bl,"init3bCheckButton");function Ul(){let r=document.getElementById("btn-4-1b-setup");r&&r.addEventListener("click",()=>{Dt({phaseText:"4.1B",btnId:"btn-4-1b-setup",nextBtnId:"btn-4-1b-sync",masterSecret:"test-sender-secret-phase4-1",syncSalt:"senderidentitysyncsaltphase4-1",manageSalt:"senderidentitymanagesaltphase4-1",ib:"test data 4.1b",data:{hello:"world4_1",random:Math.random()}})})}f(Ul,"init4_1bSetupButton");function Ml(){let r=document.getElementById("btn-4-1b-sync");r&&r.addEventListener("click",()=>{br({phaseText:"4.1B",btnId:"btn-4-1b-sync",nextBtnId:"btn-4-1b-check"})})}f(Ml,"init4_1bSyncButton");function Fl(){let r=`${be}[init4_1bCheckButton]`,e=document.getElementById("btn-4-1b-check");e&&e.addEventListener("click",async()=>{try{u("4.1B Check: Asserting cryptographic and WebSocket state expectations...");let t=await V(),o=await t.getLocalUserSpace({});if(!o)throw new Error("No default space.");let n=O.domainI,a=O.targetX,s=y({ibGib:a}),i=y({ibGib:n}),c=await t.getLatestAddr({addr:s,space:o});if(!c){u("\u2717 Check: Evolved target X NOT found in local space!");return}u(`\u2713 Check: Evolved target X found locally at: ${c}`);let d=await t.getDependencyGraph({ibGibAddr:c,space:o});if(!d||Object.keys(d).length===0){u("\u2717 Check: Failed to load target X dependency graph locally.");return}u(`\u2713 Check: Target X local graph loaded (${Object.keys(d).length} nodes).`);let l=new J,b=await l.getIbGibGraph(i,s,!0);if(!b.success||!b.graph){u(`\u2717 Check: Failed to fetch target X graph from server: ${b.message}`);return}let p=b.graph;if(u(`\u2713 Check: Target X server graph loaded (${Object.keys(p).length} nodes).`),Se({graphA:d,graphB:p}))u("\u2713 Check: Target X dependency graphs are equivalent on client and server.");else{u("\u2717 Check: Target X dependency graphs mismatch between client and server!");return}let g=await t.getLatestAddr({addr:i,space:o});if(!g){u("\u2717 Check: Evolved domain keystone tip I1 NOT found in local space!");return}u("\u2713 Check: Evolved Domain Keystone (I1) exists locally.");let w=(await t.get({addrs:[g],space:o})).ibGibs?.[0];if(!w){u("\u2717 Check: Failed to load I1 from local space.");return}let A=w.data?.proofs?.find(k=>k.claim?.verb==="sync")?.claim?.target;if(!A){u("\u2717 Check: I1 sync claim does not target a session keystone.");return}let I=await l.getIbGib(i,g);if(!I.success||!I.ibGib){u("\u2717 Check: Evolved Domain Keystone (I1) NOT found on server!");return}u("\u2713 Check: Evolved Domain Keystone (I1) exists on server.");let $=await t.getLatestAddr({addr:A,space:o});if(!$){u("\u2717 Check: Latest Session Keystone (S) NOT found in local space.");return}u(`\u2713 Check: Found latest session keystone (S) locally: ${$}`);let _=(await t.get({addrs:[$],space:o})).ibGibs?.[0];if(!_){u("\u2717 Check: Failed to load latest Session Keystone (S) locally.");return}let G=_.data?.n;u(`\u2713 Check: S tip evolved to n = ${G}.`),G!==3&&G!==4&&u(`\u26A0 Check: Expected S to evolve to n = 3 or 4, got n = ${G}. Continuing anyway...`);let v=await l.getIbGib(i,$);if(!v.success||!v.ibGib){u("\u2717 Check: Latest Session Keystone (S) NOT found on server!");return}u("\u2713 Check: Latest Session Keystone (S) exists on server.");let N=await t.getDependencyGraph({ibGibAddr:$,space:o}),D=await l.getIbGibGraph(i,A,!0);if(!D.success||!D.graph){u(`\u2717 Check: Failed to fetch session S graph from server: ${D.message}`);return}let B=D.graph;if(Se({graphA:N,graphB:B}))u("\u2713 Check: Session Keystone (S) dependency graphs are equivalent on client and server.");else{u("\u2717 Check: Session Keystone (S) dependency graphs mismatch between client and server!");return}u("\u{1F389} ALL PHASE 4.1B TRANSACTION SYNC CHECKS PASSED FLAWLESSLY! \u2713"),e.textContent="\u2713 4.1B All Passed"}catch(t){u(`\u2717 4.1B Check FAILED: ${E(t)}`),console.error(`${r} 4.1B Check error:`,t)}})}f(Fl,"init4_1bCheckButton");function jl(){let r=document.getElementById("btn-4-2b-setup");r&&r.addEventListener("click",()=>{Dt({phaseText:"4.2B",btnId:"btn-4-2b-setup",nextBtnId:"btn-4-2b-sync",masterSecret:"test-sender-secret-phase4-2",syncSalt:"senderidentitysyncsaltphase4-2",manageSalt:"senderidentitymanagesaltphase4-2",ib:"dummy target 4.2b",data:{hello:"dummy"}})})}f(jl,"init4_2bSetupButton");async function Cb(){let r=`${be}[performPhaseSync4_2b]`,e=document.getElementById("btn-4-2b-sync");if(e)try{e.disabled=!0,u("4.2B Sync: Creating Constants and executing three-pass WebSocket Sync...");let t=O.domainI;if(!t){u("\u26A0 4.2B Sync: Missing setup state. Please run Setup first."),e.disabled=!1;return}let o=y({ibGib:t}),n=await V(),a=await n.getLocalUserSpace({});if(!a)throw new Error("No default space.");let s=await F.constant({parentPrimitiveIb:"root",ib:"constant_c1_"+(await U()).slice(0,8),data:{some:"data_4_2b",random:Math.random()}}),i=y({ibGib:s});await n.put({ibGib:s,space:a}),await n.registerNewIbGib({ibGib:s}),O.targetC1=s,u(`4.2B Sync: \u2713 Constant C1 created: ${i}`),u("4.2B Sync: Starting Pass 1 (Sync C1)...");let c=location.protocol==="https:"?"wss:":"ws:",d=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(o)}`,wsUrl:`${c}//${location.host}/api/sync/ws/${encodeURIComponent(o)}`}),l=new W,b=await U();O.sagaId=b,O.senderPeer=d,await d.initializeOpts({localMetaspace:n,localSpace:a,senderIdentity:t,fnSenderSecret:f(async()=>O.domainIMasterSecret,"fnSenderSecret"),sagaId:b,sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[o]});let p=await l.sync({domainIbGibs:[s],senderIdentity:t,fnSenderSecret:f(async()=>O.domainIMasterSecret,"fnSenderSecret"),peer:d,localSpace:a,metaspace:n,conflictStrategy:X.optimisticWithLCS});await p.done,u("4.2B Sync: \u2713 Pass 1 Complete.");let h=await n.getLatestAddr({addr:y({ibGib:t}),space:a}),m=(await n.get({addrs:[h],space:a})).ibGibs[0];u("4.2B Sync: Starting Pass 2 (Sync C1 - Idempotent)..."),d=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(o)}`,wsUrl:`${c}//${location.host}/api/sync/ws/${encodeURIComponent(o)}`}),l=new W,b=await U(),O.sagaId=b,O.senderPeer=d,await d.initializeOpts({localMetaspace:n,localSpace:a,senderIdentity:m,fnSenderSecret:f(async()=>O.domainIMasterSecret,"fnSenderSecret"),sagaId:b,sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[o]}),p=await l.sync({domainIbGibs:[s],senderIdentity:m,fnSenderSecret:f(async()=>O.domainIMasterSecret,"fnSenderSecret"),peer:d,localSpace:a,metaspace:n,conflictStrategy:X.optimisticWithLCS}),await p.done,u("4.2B Sync: \u2713 Pass 2 Complete.");let w=await n.getLatestAddr({addr:y({ibGib:t}),space:a}),A=(await n.get({addrs:[w],space:a})).ibGibs[0],I=await F.constant({ib:"constant_c2_"+(await U()).slice(0,8),parentPrimitiveIb:"root",rel8ns:{link:[i]}}),$=y({ibGib:I});await n.put({ibGib:I,space:a}),await n.registerNewIbGib({ibGib:I}),O.targetC2=I,u(`4.2B Sync: \u2713 Constant C2 created linking to C1: ${$}`),u("4.2B Sync: Starting Pass 3 (Sync C2)..."),d=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(o)}`,wsUrl:`${c}//${location.host}/api/sync/ws/${encodeURIComponent(o)}`}),l=new W,b=await U(),O.sagaId=b,O.senderPeer=d,await d.initializeOpts({localMetaspace:n,localSpace:a,senderIdentity:A,fnSenderSecret:f(async()=>O.domainIMasterSecret,"fnSenderSecret"),sagaId:b,sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[o]}),p=await l.sync({domainIbGibs:[I],senderIdentity:A,fnSenderSecret:f(async()=>O.domainIMasterSecret,"fnSenderSecret"),peer:d,localSpace:a,metaspace:n,conflictStrategy:X.optimisticWithLCS}),await p.done,u("4.2B Sync: \u2713 Pass 3 Complete."),u("\u2713 4.2B Sync Sequence Complete! Ready for State Checks."),e.textContent="\u2713 4.2B Sync Run";let T=document.getElementById("btn-4-2b-check");T&&(T.disabled=!1)}catch(t){u(`\u2717 4.2B Sync FAILED: ${E(t)}`),console.error(`${r} 4.2B Sync error:`,t),e.disabled=!1}}f(Cb,"performPhaseSync4_2b");function Vl(){let r=document.getElementById("btn-4-2b-sync");r&&r.addEventListener("click",()=>{Cb()})}f(Vl,"init4_2bSyncButton");function Hl(){let r=`${be}[init4_2bCheckButton]`,e=document.getElementById("btn-4-2b-check");e&&e.addEventListener("click",async()=>{try{u("4.2B Check: Asserting cryptographic and WebSocket state expectations...");let t=await V(),o=await t.getLocalUserSpace({});if(!o)throw new Error("No default space.");let n=O.domainI,a=O.targetC1,s=O.targetC2,i=y({ibGib:a}),c=y({ibGib:s}),d=y({ibGib:n}),l=await t.get({addrs:[i],space:o}),b=await t.get({addrs:[c],space:o});if(!l.success||!l.ibGibs?.[0]){u("\u2717 Check: Constant C1 NOT found locally.");return}if(!b.success||!b.ibGibs?.[0]){u("\u2717 Check: Constant C2 NOT found locally.");return}u("\u2713 Check: Constants C1 and C2 exist locally.");let p=new J,h=await p.getIbGib(d,i),g=await p.getIbGib(d,c);if(!h.success||!h.ibGib){u(`\u2717 Check: Constant C1 NOT found on server: ${h.message}`);return}if(!g.success||!g.ibGib){u(`\u2717 Check: Constant C2 NOT found on server: ${g.message}`);return}u("\u2713 Check: Constants C1 and C2 exist on server.");let m=await t.getDependencyGraph({ibGibAddr:c,space:o}),w=await p.getIbGibGraph(d,c,!0);if(!w.success||!w.graph){u(`\u2717 Check: Failed to fetch C2 graph from server: ${w.message}`);return}let S=w.graph;if(Se({graphA:m,graphB:S}))u("\u2713 Check: C2 dependency graphs are equivalent on client and server.");else{u("\u2717 Check: C2 dependency graphs mismatch between client and server!");return}let I=await t.getLatestAddr({addr:d,space:o});if(!I){u("\u2717 Check: Evolved domain keystone tip I3 NOT found in local space!");return}let T=(await t.get({addrs:[I],space:o})).ibGibs?.[0];if(!T){u("\u2717 Check: Failed to load evolved I from local space.");return}u(`\u2713 Check: Evolved Domain Keystone exists locally: ${I}`);let _=T.data?.n;if(u(`\u2713 Check: Evolved I tip is at n = ${_}.`),_!==3){u(`\u2717 Check: Expected I to evolve to n = 3, got n = ${_}.`);return}let G=await p.getIbGib(d,I);if(!G.success||!G.ibGib){u("\u2717 Check: Evolved Domain Keystone tip NOT found on server!");return}u("\u2713 Check: Evolved Domain Keystone tip exists on server.");let N=T.data?.proofs?.find(Ce=>Ce.claim?.verb==="sync")?.claim?.target;if(!N){u("\u2717 Check: Evolved I sync claim does not target a session keystone.");return}let D=await t.getLatestAddr({addr:N,space:o});if(!D){u("\u2717 Check: Latest Session Keystone (S) NOT found in local space.");return}u(`\u2713 Check: Found latest session keystone (S) locally: ${D}`);let P=(await t.get({addrs:[D],space:o})).ibGibs?.[0];if(!P){u("\u2717 Check: Failed to load latest Session Keystone (S) locally.");return}let k=P.data?.n;if(u(`\u2713 Check: Latest session S tip evolved to n = ${k}.`),k!==3){u(`\u2717 Check: Expected latest session S to evolve to n = 3, got n = ${k}.`);return}let M=await p.getIbGib(d,D);if(!M.success||!M.ibGib){u("\u2717 Check: Latest Session Keystone (S) NOT found on server!");return}u("\u2713 Check: Latest Session Keystone (S) exists on server.");let j=await t.getDependencyGraph({ibGibAddr:D,space:o}),Q=await p.getIbGibGraph(d,N,!0);if(!Q.success||!Q.graph){u(`\u2717 Check: Failed to fetch session S graph from server: ${Q.message}`);return}let ee=Q.graph;if(Se({graphA:j,graphB:ee}))u("\u2713 Check: Session Keystone (S) dependency graphs are equivalent on client and server.");else{u("\u2717 Check: Session Keystone (S) dependency graphs mismatch between client and server!");return}u("\u{1F389} ALL PHASE 4.2B TRANSACTION SYNC CHECKS PASSED FLAWLESSLY! \u2713"),e.textContent="\u2713 4.2B All Passed"}catch(t){u(`\u2717 4.2B Check FAILED: ${E(t)}`),console.error(`${r} 4.2B Check error:`,t)}})}f(Hl,"init4_2bCheckButton");function Kl(){let r=document.getElementById("btn-4-3b-setup");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,u("4.3B Setup: Generating Domain Keystone (I) and Target timeline V0 -> V1...");let e=await V(),t=await e.getLocalUserSpace({});if(!t)throw new Error("No default space.");let n=await new se().genesis({masterSecret:"test-sender-secret-phase4-3",configs:[fe("sync","senderidentitysyncsaltphase4-3"),fe("manage","senderidentitymanagesaltphase4-3")],metaspace:e,space:t,frameDetails:{client:"space-gib-web-dev",timestamp:oe()}});O.domainI=n,O.domainIMasterSecret="test-sender-secret-phase4-3",u(`4.3B Setup: \u2713 Domain Keystone (I) created locally: ${y({ibGib:n})}`);let s=await new J().postGenesisKeystone(n);if(s.success)u("4.3B Setup: \u2713 Domain Keystone registered on server.");else throw new Error(`Server rejected genesis domain keystone: ${s.message}`);let i=await F.firstGen({parentIbGib:q,ib:"timeline_root_partial_4_3b",data:{type:"root",label:"Root4_3b",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),c=i.newIbGib;await e.persistTransformResult({resTransform:i,space:t}),await e.registerNewIbGib({ibGib:c});let d=await Z({timeline:c,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"V1_4_3b"}},metaspace:e,space:t});O.targetC1=d,O.targetX=d,u(`4.3B Setup: \u2713 Timeline V0 -> V1 created and stored locally. V1: ${y({ibGib:d})}`),u("\u2713 4.3B Setup Complete! Ready for 4.3B Sync."),r.textContent="\u2713 4.3B Setup Complete";let l=document.getElementById("btn-4-3b-sync");l&&(l.disabled=!1)}catch(e){u(`\u2717 4.3B Setup FAILED: ${E(e)}`),console.error(e),r.disabled=!1}})}f(Kl,"init4_3bSetupButton");async function vb(){let r=`${be}[performPhaseSync4_3b]`,e=document.getElementById("btn-4-3b-sync");if(e)try{e.disabled=!0,u("4.3B Sync: Starting Pass 1 (Sync V1 to server)...");let t=O.domainI,o=O.targetX;if(!t||!o){u("\u26A0 4.3B Sync: Missing setup state. Please run Setup first."),e.disabled=!1;return}let n=y({ibGib:t}),a=await V(),s=await a.getLocalUserSpace({});if(!s)throw new Error("No default space.");let i=location.protocol==="https:"?"wss:":"ws:",c=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(n)}`,wsUrl:`${i}//${location.host}/api/sync/ws/${encodeURIComponent(n)}`}),d=new W,l=await U();O.sagaId=l,O.senderPeer=c,await c.initializeOpts({localMetaspace:a,localSpace:s,senderIdentity:t,fnSenderSecret:f(async()=>O.domainIMasterSecret,"fnSenderSecret"),sagaId:l,sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[n]});let b=await d.sync({domainIbGibs:[o],senderIdentity:t,fnSenderSecret:f(async()=>O.domainIMasterSecret,"fnSenderSecret"),peer:c,localSpace:s,metaspace:a,conflictStrategy:X.optimisticWithLCS});await b.done,u("4.3B Sync: \u2713 Pass 1 Complete (V1 synced).");let p=await a.getLatestAddr({addr:y({ibGib:t}),space:s}),g=(await a.get({addrs:[p],space:s})).ibGibs[0];u("4.3B Sync: Mutating V1 to V2 locally...");let m=await Z({timeline:o,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"V2_4_3b"}},metaspace:a,space:s});O.targetX=m,u(`4.3B Sync: \u2713 V2 created locally: ${y({ibGib:m})}`),u("4.3B Sync: Starting Pass 2 (Sync V2 delta to server)..."),c=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(n)}`,wsUrl:`${i}//${location.host}/api/sync/ws/${encodeURIComponent(n)}`}),d=new W,l=await U(),O.sagaId=l,O.senderPeer=c,await c.initializeOpts({localMetaspace:a,localSpace:s,senderIdentity:g,fnSenderSecret:f(async()=>O.domainIMasterSecret,"fnSenderSecret"),sagaId:l,sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[n]}),b=await d.sync({domainIbGibs:[m],senderIdentity:g,fnSenderSecret:f(async()=>O.domainIMasterSecret,"fnSenderSecret"),peer:c,localSpace:s,metaspace:a,conflictStrategy:X.optimisticWithLCS}),await b.done,u("4.3B Sync: \u2713 Pass 2 Complete (V2 synced)."),u("\u2713 4.3B Sync Sequence Complete! Ready for State Checks."),e.textContent="\u2713 4.3B Sync Run";let w=document.getElementById("btn-4-3b-check");w&&(w.disabled=!1)}catch(t){u(`\u2717 4.3B Sync FAILED: ${E(t)}`),console.error(t),e.disabled=!1}}f(vb,"performPhaseSync4_3b");function Xl(){let r=document.getElementById("btn-4-3b-sync");r&&r.addEventListener("click",()=>{vb()})}f(Xl,"init4_3bSyncButton");function ql(){let r=`${be}[init4_3bCheckButton]`,e=document.getElementById("btn-4-3b-check");e&&e.addEventListener("click",async()=>{try{u("4.3B Check: Asserting cryptographic and WebSocket state expectations...");let t=await V(),o=await t.getLocalUserSpace({});if(!o)throw new Error("No default space.");let n=O.domainI,a=O.targetC1,s=O.targetX,i=y({ibGib:a}),c=y({ibGib:s}),d=y({ibGib:n}),l=await t.get({addrs:[i],space:o}),b=await t.get({addrs:[c],space:o});if(!l.success||!l.ibGibs?.[0]){u("\u2717 Check: Timeline frame V1 NOT found locally.");return}if(!b.success||!b.ibGibs?.[0]){u("\u2717 Check: Timeline frame V2 NOT found locally.");return}u("\u2713 Check: Timeline frames V1 and V2 exist locally.");let p=new J,h=await p.getIbGib(d,c);if(!h.success||!h.ibGib){u(`\u2717 Check: Timeline frame V2 NOT found on server: ${h.message}`);return}u("\u2713 Check: Timeline frame V2 exists on server.");let m=h.ibGib.rel8ns?.past?.at(-1);if(m===i)u("\u2713 Check: Server V2 correctly references V1 in its past relation.");else{u(`\u2717 Check: Server V2 does not reference V1 in past relation! got: ${m}`);return}let w=await t.getDependencyGraph({ibGibAddr:c,space:o}),S=await p.getIbGibGraph(d,c,!0);if(!S.success||!S.graph){u(`\u2717 Check: Failed to fetch V2 graph from server: ${S.message}`);return}let A=S.graph;if(Se({graphA:w,graphB:A}))u("\u2713 Check: V2 timeline dependency graphs are equivalent on client and server.");else{u("\u2717 Check: V2 timeline dependency graphs mismatch between client and server!");return}let $=await t.getLatestAddr({addr:d,space:o});if(!$){u("\u2717 Check: Evolved domain keystone tip NOT found in local space!");return}let _=(await t.get({addrs:[$],space:o})).ibGibs?.[0];if(!_){u("\u2717 Check: Failed to load evolved I from local space.");return}u(`\u2713 Check: Evolved Domain Keystone exists locally: ${$}`);let G=_.data?.n;if(u(`\u2713 Check: Evolved I tip is at n = ${G}.`),G!==2){u(`\u2717 Check: Expected I to evolve to n = 2, got n = ${G}.`);return}let v=await p.getIbGib(d,$);if(!v.success||!v.ibGib){u("\u2717 Check: Evolved Domain Keystone tip NOT found on server!");return}u("\u2713 Check: Evolved Domain Keystone tip exists on server.");let D=_.data?.proofs?.find(Me=>Me.claim?.verb==="sync")?.claim?.target;if(!D){u("\u2717 Check: Evolved I sync claim does not target a session keystone.");return}let B=await t.getLatestAddr({addr:D,space:o});if(!B){u("\u2717 Check: Latest Session Keystone (S) NOT found in local space.");return}u(`\u2713 Check: Found latest session keystone (S) locally: ${B}`);let k=(await t.get({addrs:[B],space:o})).ibGibs?.[0];if(!k){u("\u2717 Check: Failed to load latest Session Keystone (S) locally.");return}let M=k.data?.n;if(u(`\u2713 Check: Latest session S tip evolved to n = ${M}.`),M!==3){u(`\u2717 Check: Expected latest session S to evolve to n = 3, got n = ${M}.`);return}let j=await p.getIbGib(d,B);if(!j.success||!j.ibGib){u("\u2717 Check: Latest Session Keystone (S) NOT found on server!");return}u("\u2713 Check: Latest Session Keystone (S) exists on server.");let Q=await t.getDependencyGraph({ibGibAddr:B,space:o}),ee=await p.getIbGibGraph(d,D,!0);if(!ee.success||!ee.graph){u(`\u2717 Check: Failed to fetch session S graph from server: ${ee.message}`);return}let Ge=ee.graph;if(Se({graphA:Q,graphB:Ge}))u("\u2713 Check: Session Keystone (S) dependency graphs are equivalent on client and server.");else{u("\u2717 Check: Session Keystone (S) dependency graphs mismatch between client and server!");return}u("\u{1F389} ALL PHASE 4.3B TRANSACTION SYNC CHECKS PASSED FLAWLESSLY! \u2713"),e.textContent="\u2713 4.3B All Passed"}catch(t){u(`\u2717 4.3B Check FAILED: ${E(t)}`),console.error(`${r} 4.3B Check error:`,t)}})}f(ql,"init4_3bCheckButton");function Wl(){let r=document.getElementById("btn-4-4b-setup");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,u("4.4B Setup: Generating Domain Keystone (I) and Target timeline V0 -> V1 -> V2...");let e=await V(),t=await e.getLocalUserSpace({});if(!t)throw new Error("No default space.");let n=await new se().genesis({masterSecret:"test-sender-secret-phase4-4",configs:[fe("sync","senderidentitysyncsaltphase4-4"),fe("manage","senderidentitymanagesaltphase4-4")],metaspace:e,space:t,frameDetails:{client:"space-gib-web-dev",timestamp:oe()}});O.domainI=n,O.domainIMasterSecret="test-sender-secret-phase4-4",u(`4.4B Setup: \u2713 Domain Keystone (I) created locally: ${y({ibGib:n})}`);let s=await new J().postGenesisKeystone(n);if(s.success)u("4.4B Setup: \u2713 Domain Keystone registered on server.");else throw new Error(`Server rejected genesis domain keystone: ${s.message}`);let i=await F.firstGen({parentIbGib:q,ib:"timeline_root_deep_4_4b",data:{type:"root",label:"Root4_4b",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),c=i.newIbGib;await e.persistTransformResult({resTransform:i,space:t}),await e.registerNewIbGib({ibGib:c}),O.targetC1=c;let d=await Z({timeline:c,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"V1_4_4b"}},metaspace:e,space:t});O.targetC2=d;let l=await Z({timeline:d,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"V2_4_4b"}},metaspace:e,space:t});O.targetX=l,u(`4.4B Setup: \u2713 Timeline V0 -> V1 -> V2 created locally. V2 Tip: ${y({ibGib:l})}`),u("\u2713 4.4B Setup Complete! Ready for 4.4B Sync."),r.textContent="\u2713 4.4B Setup Complete";let b=document.getElementById("btn-4-4b-sync");b&&(b.disabled=!1)}catch(e){u(`\u2717 4.4B Setup FAILED: ${E(e)}`),console.error(e),r.disabled=!1}})}f(Wl,"init4_4bSetupButton");async function Ob(){let r=`${be}[performPhaseSync4_4b]`,e=document.getElementById("btn-4-4b-sync");if(e)try{e.disabled=!0,u("4.4B Sync: Initiating WebSocket Sync of V2 Tip...");let t=O.domainI,o=O.targetX;if(!t||!o){u("\u26A0 4.4B Sync: Missing setup state. Please run Setup first."),e.disabled=!1;return}let n=y({ibGib:t}),a=await V(),s=await a.getLocalUserSpace({});if(!s)throw new Error("No default space.");let i=location.protocol==="https:"?"wss:":"ws:",c=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(n)}`,wsUrl:`${i}//${location.host}/api/sync/ws/${encodeURIComponent(n)}`}),d=new W,l=await U();O.sagaId=l,O.senderPeer=c,await c.initializeOpts({localMetaspace:a,localSpace:s,senderIdentity:t,fnSenderSecret:f(async()=>O.domainIMasterSecret,"fnSenderSecret"),sagaId:l,sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[n]}),await(await d.sync({domainIbGibs:[o],senderIdentity:t,fnSenderSecret:f(async()=>O.domainIMasterSecret,"fnSenderSecret"),peer:c,localSpace:s,metaspace:a,conflictStrategy:X.optimisticWithLCS})).done,u("4.4B Sync: \u2713 WebSocket Sync completed."),u("\u2713 4.4B Sync Sequence Complete! Ready for State Checks."),e.textContent="\u2713 4.4B Sync Run";let p=document.getElementById("btn-4-4b-check");p&&(p.disabled=!1)}catch(t){u(`\u2717 4.4B Sync FAILED: ${E(t)}`),console.error(t),e.disabled=!1}}f(Ob,"performPhaseSync4_4b");function Yl(){let r=document.getElementById("btn-4-4b-sync");r&&r.addEventListener("click",()=>{Ob()})}f(Yl,"init4_4bSyncButton");function zl(){let r=`${be}[init4_4bCheckButton]`,e=document.getElementById("btn-4-4b-check");e&&e.addEventListener("click",async()=>{try{u("4.4B Check: Asserting cryptographic and WebSocket state expectations...");let t=await V(),o=await t.getLocalUserSpace({});if(!o)throw new Error("No default space.");let n=O.domainI,a=O.targetC1,s=O.targetC2,i=O.targetX,c=y({ibGib:a}),d=y({ibGib:s}),l=y({ibGib:i}),b=y({ibGib:n}),p=await t.get({addrs:[c],space:o}),h=await t.get({addrs:[d],space:o}),g=await t.get({addrs:[l],space:o});if(!p.success||!p.ibGibs?.[0]){u("\u2717 Check: Timeline frame V0 NOT found locally.");return}if(!h.success||!h.ibGibs?.[0]){u("\u2717 Check: Timeline frame V1 NOT found locally.");return}if(!g.success||!g.ibGibs?.[0]){u("\u2717 Check: Timeline frame V2 NOT found locally.");return}u("\u2713 Check: Timeline frames V0, V1, and V2 exist locally.");let m=new J,w=await m.getIbGib(b,l);if(!w.success||!w.ibGib){u(`\u2717 Check: Timeline frame V2 NOT found on server: ${w.message}`);return}u("\u2713 Check: Timeline frame V2 exists on server.");let A=w.ibGib.rel8ns?.past?.at(-1);if(A===d)u("\u2713 Check: Server V2 correctly references V1 in its past relation.");else{u(`\u2717 Check: Server V2 does not reference V1 in past relation! got: ${A}`);return}let I=await m.getIbGib(b,d);if(!I.success||!I.ibGib){u(`\u2717 Check: Timeline frame V1 NOT found on server: ${I.message}`);return}u("\u2713 Check: Timeline frame V1 exists on server.");let T=I.ibGib.rel8ns?.past?.at(-1);if(T===c)u("\u2713 Check: Server V1 correctly references V0 in its past relation.");else{u(`\u2717 Check: Server V1 does not reference V0 in past relation! got: ${T}`);return}let _=await t.getDependencyGraph({ibGibAddr:l,space:o}),G=await m.getIbGibGraph(b,l,!0);if(!G.success||!G.graph){u(`\u2717 Check: Failed to fetch V2 graph from server: ${G.message}`);return}let v=G.graph;if(Se({graphA:_,graphB:v}))u("\u2713 Check: V2 timeline dependency graphs are equivalent on client and server.");else{u("\u2717 Check: V2 timeline dependency graphs mismatch between client and server!");return}let D=await t.getLatestAddr({addr:b,space:o});if(!D){u("\u2717 Check: Evolved domain keystone tip NOT found in local space!");return}let P=(await t.get({addrs:[D],space:o})).ibGibs?.[0];if(!P){u("\u2717 Check: Failed to load evolved I from local space.");return}u(`\u2713 Check: Evolved Domain Keystone exists locally: ${D}`);let k=P.data?.n;if(u(`\u2713 Check: Evolved I tip is at n = ${k}.`),k!==1){u(`\u2717 Check: Expected I to evolve to n = 1, got n = ${k}.`);return}let M=await m.getIbGib(b,D);if(!M.success||!M.ibGib){u("\u2717 Check: Evolved Domain Keystone tip NOT found on server!");return}u("\u2713 Check: Evolved Domain Keystone tip exists on server.");let Q=P.data?.proofs?.find(rt=>rt.claim?.verb==="sync")?.claim?.target;if(!Q){u("\u2717 Check: Evolved I sync claim does not target a session keystone.");return}let ee=await t.getLatestAddr({addr:Q,space:o});if(!ee){u("\u2717 Check: Latest Session Keystone (S) NOT found in local space.");return}u(`\u2713 Check: Found latest session keystone (S) locally: ${ee}`);let Ce=(await t.get({addrs:[ee],space:o})).ibGibs?.[0];if(!Ce){u("\u2717 Check: Failed to load latest Session Keystone (S) locally.");return}let Me=Ce.data?.n;if(u(`\u2713 Check: Latest session S tip evolved to n = ${Me}.`),Me!==3){u(`\u2717 Check: Expected latest session S to evolve to n = 3, got n = ${Me}.`);return}let Fe=await m.getIbGib(b,ee);if(!Fe.success||!Fe.ibGib){u("\u2717 Check: Latest Session Keystone (S) NOT found on server!");return}u("\u2713 Check: Latest Session Keystone (S) exists on server.");let pe=await t.getDependencyGraph({ibGibAddr:ee,space:o}),He=await m.getIbGibGraph(b,Q,!0);if(!He.success||!He.graph){u(`\u2717 Check: Failed to fetch session S graph from server: ${He.message}`);return}let tt=He.graph;if(Se({graphA:pe,graphB:tt}))u("\u2713 Check: Session Keystone (S) dependency graphs are equivalent on client and server.");else{u("\u2717 Check: Session Keystone (S) dependency graphs mismatch between client and server!");return}u("\u{1F389} ALL PHASE 4.4B TRANSACTION SYNC CHECKS PASSED FLAWLESSLY! \u2713"),e.textContent="\u2713 4.4B All Passed"}catch(t){u(`\u2717 4.4B Check FAILED: ${E(t)}`),console.error(`${r} 4.4B Check error:`,t)}})}f(zl,"init4_4bCheckButton");var Cr={};function Jl(){let r=document.getElementById("btn-4-5b-setup");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,u("4.5B Setup: Generating Domain Keystone (I) and Target timeline V0 -> V1 in default local space...");let e=await V(),t=await e.getLocalUserSpace({});if(!t)throw new Error("No default space.");let n=await new se().genesis({masterSecret:"test-sender-secret-phase4-5b",configs:[fe("sync","senderidentitysyncsaltphase4-5b"),fe("manage","senderidentitymanagesaltphase4-5b")],metaspace:e,space:t,frameDetails:{client:"space-gib-web-dev",timestamp:oe()}});O.domainI=n,O.domainIMasterSecret="test-sender-secret-phase4-5b",u(`4.5B Setup: \u2713 Domain Keystone (I) created locally: ${y({ibGib:n})}`);let s=await new J().postGenesisKeystone(n);if(s.success)u("4.5B Setup: \u2713 Domain Keystone registered on server.");else throw new Error(`Server rejected genesis domain keystone: ${s.message}`);let i=await F.firstGen({parentIbGib:q,ib:"timeline_root_partial_4_5b",data:{type:"root",label:"Root4_5b",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),c=i.newIbGib;await e.persistTransformResult({resTransform:i,space:t}),await e.registerNewIbGib({ibGib:c,space:t});let d=await Z({timeline:c,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"V1_4_5b"}},metaspace:e,space:t});Cr.targetV1=d,u(`4.5B Setup: \u2713 Local timeline V0 -> V1 created. V1 Tip: ${y({ibGib:d})}`),u("4.5B Setup: Seeding V1 to the server via WebSocket...");let l=location.protocol==="https:"?"wss:":"ws:",b=y({ibGib:n}),p=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(b)}`,wsUrl:`${l}//${location.host}/api/sync/ws/${encodeURIComponent(b)}`}),h=new W,g=await U();await p.initializeOpts({localMetaspace:e,localSpace:t,senderIdentity:n,fnSenderSecret:f(async()=>"test-sender-secret-phase4-5b","fnSenderSecret"),sagaId:g,sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[b]}),await(await h.sync({domainIbGibs:[d],senderIdentity:n,fnSenderSecret:f(async()=>"test-sender-secret-phase4-5b","fnSenderSecret"),peer:p,localSpace:t,metaspace:e,conflictStrategy:X.optimisticWithLCS})).done,u("4.5B Setup: \u2713 Pass 1 Sync (V1 to server) complete.");let w=await e.getLatestAddr({addr:b,space:t});if(!w)throw new Error("Could not get latest sender address from default space.");let A=(await e.get({addrs:[w],space:t})).ibGibs[0];u('4.5B Setup: Creating secondary local space simulating "remote" client...');let I=`remote-${await U()}`,$=await e.createNewLocalSpace({opts:{allowCancel:!1,spaceName:I,getFnPrompt:e.getFnPrompt}});if(!$)throw new Error("Failed to create remote space");await $.initialized;let T=await e.getDependencyGraph({ibGibAddr:y({ibGib:d}),space:t});await e.put({ibGibs:Object.values(T),space:$}),await e.registerNewIbGib({ibGib:d,space:$});let _=await e.getDependencyGraph({ibGibAddr:w,space:t});await e.put({ibGibs:Object.values(_),space:$}),await e.registerNewIbGib({ibGib:A,space:$}),u("4.5B Setup: \u2713 Copied V1 and identity I to remoteSpace."),u("4.5B Setup: Mutating V1 -> V2 in remoteSpace...");let G=await Z({timeline:d,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"V2_4_5b"}},metaspace:e,space:$});Cr.targetV2=G,u(`4.5B Setup: \u2713 Mutated to V2 in remoteSpace: ${y({ibGib:G})}`),u("4.5B Setup: Syncing V2 from remoteSpace to the server...");let v=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(b)}`,wsUrl:`${l}//${location.host}/api/sync/ws/${encodeURIComponent(b)}`}),N=new W,D=await U();await v.initializeOpts({localMetaspace:e,localSpace:$,senderIdentity:A,fnSenderSecret:f(async()=>"test-sender-secret-phase4-5b","fnSenderSecret"),sagaId:D,sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[b]}),await(await N.sync({domainIbGibs:[G],senderIdentity:A,fnSenderSecret:f(async()=>"test-sender-secret-phase4-5b","fnSenderSecret"),peer:v,localSpace:$,metaspace:e,conflictStrategy:X.optimisticWithLCS})).done,u("4.5B Setup: \u2713 Pass 2 Sync (V2 to server) complete.");let P=await e.getLatestAddr({addr:b,space:$});if(!P)throw new Error("Could not get latest sender address from remoteSpace.");let M=(await e.get({addrs:[P],space:$})).ibGibs[0];Cr.domainI_latest=M;let j=await e.getDependencyGraph({ibGibAddr:P,space:$});await e.put({ibGibs:Object.values(j),space:t}),await e.registerNewIbGib({ibGib:M,space:t}),u("\u2713 4.5B Setup Complete! Server has V2, default local space has V1. Ready for 4.5B Sync."),r.textContent="\u2713 4.5B Setup Complete";let Q=document.getElementById("btn-4-5b-sync");Q&&(Q.disabled=!1)}catch(e){u(`\u2717 4.5B Setup FAILED: ${E(e)}`),console.error(e),r.disabled=!1}})}f(Jl,"init4_5bSetupButton");function Zl(){let r=document.getElementById("btn-4-5b-sync");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,u("4.5B Sync: Initiating WebSocket Sync from default local space (which has V1, server has V2)...");let e=Cr.domainI_latest,t=Cr.targetV1;if(!e||!t){u("\u26A0 4.5B Sync: Missing setup state. Please run Setup first."),r.disabled=!1;return}let o=y({ibGib:e}),n=await V(),a=await n.getLocalUserSpace({});if(!a)throw new Error("No default space.");let s=location.protocol==="https:"?"wss:":"ws:",i=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(o)}`,wsUrl:`${s}//${location.host}/api/sync/ws/${encodeURIComponent(o)}`}),c=new W,d=await U();await i.initializeOpts({localMetaspace:n,localSpace:a,senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-5b","fnSenderSecret"),sagaId:d,sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[o]}),await(await c.sync({domainIbGibs:[t],senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-5b","fnSenderSecret"),peer:i,localSpace:a,metaspace:n,conflictStrategy:X.optimisticWithLCS})).done,u("\u2713 4.5B Sync Execution Complete! Ready for 4.5B Check."),r.textContent="\u2713 4.5B Sync Run";let b=document.getElementById("btn-4-5b-check");b&&(b.disabled=!1)}catch(e){u(`\u2717 4.5B Sync FAILED: ${E(e)}`),console.error(e),r.disabled=!1}})}f(Zl,"init4_5bSyncButton");function Ql(){let r=document.getElementById("btn-4-5b-check");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,u("4.5B Check: Verifying that V2 was pulled down to default local space...");let e=Cr.targetV2;if(!e){u("\u26A0 4.5B Check: Missing target V2 in state. Did Setup run?"),r.disabled=!1;return}let t=y({ibGib:e}),o=await V(),n=await o.getLocalUserSpace({});if(!n)throw new Error("No default space.");let a=await o.get({addr:t,space:n});if(!a.success||a.ibGibs?.length!==1)throw new Error(`V2 tip (${t}) is NOT present in local space!`);let s=a.ibGibs[0];u(`4.5B Check: \u2713 V2 Tip found locally. Label: "${s.data?.label}"`);let i=await o.getDependencyGraph({ibGibAddr:t,space:n});u("4.5B Check: Fetching V2 dependency graph from server...");let c=y({ibGib:Cr.domainI_latest}),l=await new J().getIbGibGraph(c,t,!0);if(!l.success||!l.graph)throw new Error(`Failed to fetch V2 graph from server: ${l.message}`);if(Se({graphA:i,graphB:l.graph}))u("\u2713 4.5B Check SUCCESS: V2 and all dependencies are fully equivalent on client and server!"),r.textContent="\u2713 4.5B Check Success";else throw new Error("Dependency graphs on local space and server are NOT equivalent.")}catch(e){u(`\u2717 4.5B Check FAILED: ${E(e)}`),console.error(e),r.disabled=!1}})}f(Ql,"init4_5bCheckButton");var qt={};function ed(){let r=document.getElementById("btn-4-6b-setup");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,u("4.6B Setup: Generating Domain Keystone (I) and two independent target timelines (Alpha and Beta) in default local space...");let e=await V(),t=await e.getLocalUserSpace({});if(!t)throw new Error("No default space.");let n=await new se().genesis({masterSecret:"test-sender-secret-phase4-6b",configs:[fe("sync","senderidentitysyncsaltphase4-6b"),fe("manage","senderidentitymanagesaltphase4-6b")],metaspace:e,space:t,frameDetails:{client:"space-gib-web-dev",timestamp:oe()}});qt.domainI_latest=n,O.domainI=n,O.domainIMasterSecret="test-sender-secret-phase4-6b",u(`4.6B Setup: \u2713 Domain Keystone (I) created locally: ${y({ibGib:n})}`);let s=await new J().postGenesisKeystone(n);if(s.success)u("4.6B Setup: \u2713 Domain Keystone registered on server.");else throw new Error(`Server rejected genesis domain keystone: ${s.message}`);let i=await F.firstGen({parentIbGib:q,ib:"timeline_root_alpha_4_6b",data:{type:"root",label:"Alpha4_6b",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),c=i.newIbGib;await e.persistTransformResult({resTransform:i,space:t}),await e.registerNewIbGib({ibGib:c,space:t});let d=await Z({timeline:c,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"A1_4_6b"}},metaspace:e,space:t});qt.targetAlphaV1=d,u(`4.6B Setup: \u2713 Local Timeline A created. A1 Tip: ${y({ibGib:d})}`);let l=await F.firstGen({parentIbGib:q,ib:"timeline_root_beta_4_6b",data:{type:"root",label:"Beta4_6b",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),b=l.newIbGib;await e.persistTransformResult({resTransform:l,space:t}),await e.registerNewIbGib({ibGib:b,space:t});let p=await Z({timeline:b,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"B1_4_6b"}},metaspace:e,space:t}),h=await Z({timeline:p,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"B2_4_6b"}},metaspace:e,space:t});qt.targetBetaV2=h,u(`4.6B Setup: \u2713 Local Timeline B created. B2 Tip: ${y({ibGib:h})}`),u("\u2713 4.6B Setup Complete! Timelines created locally. Ready for 4.6B Sync."),r.textContent="\u2713 4.6B Setup Complete";let g=document.getElementById("btn-4-6b-sync");g&&(g.disabled=!1)}catch(e){u(`\u2717 4.6B Setup FAILED: ${E(e)}`),console.error(e),r.disabled=!1}})}f(ed,"init4_6bSetupButton");function td(){let r=document.getElementById("btn-4-6b-sync");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,u("4.6B Sync: Initiating WebSocket Sync for both Timeline A and Timeline B in one call...");let e=qt.domainI_latest,t=qt.targetAlphaV1,o=qt.targetBetaV2;if(!e||!t||!o){u("\u26A0 4.6B Sync: Missing setup state. Please run Setup first."),r.disabled=!1;return}let n=y({ibGib:e}),a=await V(),s=await a.getLocalUserSpace({});if(!s)throw new Error("No default space.");let i=location.protocol==="https:"?"wss:":"ws:",c=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(n)}`,wsUrl:`${i}//${location.host}/api/sync/ws/${encodeURIComponent(n)}`}),d=new W,l=await U();await c.initializeOpts({localMetaspace:a,localSpace:s,senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-6b","fnSenderSecret"),sagaId:l,sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[n]}),await(await d.sync({domainIbGibs:[t,o],senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-6b","fnSenderSecret"),peer:c,localSpace:s,metaspace:a,conflictStrategy:X.optimisticWithLCS})).done,u("\u2713 4.6B Sync Execution Complete! Ready for 4.6B Check."),r.textContent="\u2713 4.6B Sync Run";let p=document.getElementById("btn-4-6b-check");p&&(p.disabled=!1)}catch(e){u(`\u2717 4.6B Sync FAILED: ${E(e)}`),console.error(e),r.disabled=!1}})}f(td,"init4_6bSyncButton");function rd(){let r=document.getElementById("btn-4-6b-check");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,u("4.6B Check: Verifying both Timeline A and Timeline B exist on the server with matching dependency graphs...");let e=qt.domainI_latest,t=qt.targetAlphaV1,o=qt.targetBetaV2;if(!e||!t||!o){u("\u26A0 4.6B Check: Missing state. Did Setup and Sync run?"),r.disabled=!1;return}let n=y({ibGib:e}),a=y({ibGib:t}),s=y({ibGib:o}),i=await V(),c=await i.getLocalUserSpace({});if(!c)throw new Error("No default space.");let d=new J;u("4.6B Check: Fetching Timeline A dependency graph from server...");let l=await d.getIbGibGraph(n,a,!0);if(!l.success||!l.graph)throw new Error(`Failed to fetch Timeline A graph from server: ${l.message}`);let b=await i.getDependencyGraph({ibGibAddr:a,space:c});if(!Se({graphA:b,graphB:l.graph}))throw new Error("Timeline A dependency graphs on local space and server are NOT equivalent.");u("4.6B Check: \u2713 Timeline A graphs are equivalent."),u("4.6B Check: Fetching Timeline B dependency graph from server...");let h=await d.getIbGibGraph(n,s,!0);if(!h.success||!h.graph)throw new Error(`Failed to fetch Timeline B graph from server: ${h.message}`);let g=await i.getDependencyGraph({ibGibAddr:s,space:c});if(!Se({graphA:g,graphB:h.graph}))throw new Error("Timeline B dependency graphs on local space and server are NOT equivalent.");u("4.6B Check: \u2713 Timeline B graphs are equivalent."),u("\u2713 4.6B Check SUCCESS: Both independent timelines are fully synced and identical on client and server!"),r.textContent="\u2713 4.6B Check Success"}catch(e){u(`\u2717 4.6B Check FAILED: ${E(e)}`),console.error(e),r.disabled=!1}})}f(rd,"init4_6bCheckButton");var ht={};function od(){let r=document.getElementById("btn-4-7b-setup");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,u("4.7B Setup: Setting up identities, seeding history, and creating divergent branches in client and remote...");let e=await V(),t=await e.getLocalUserSpace({});if(!t)throw new Error("No default space.");let o=new se,n=location.protocol==="https:"?"wss:":"ws:",a=await o.genesis({masterSecret:"test-sender-secret-phase4-7b",configs:[fe("sync","senderidentitysyncsaltphase4-7b"),fe("manage","senderidentitymanagesaltphase4-7b")],metaspace:e,space:t,frameDetails:{client:"space-gib-web-dev",timestamp:oe()}});ht.domainI_latest=a;let s=a,i=y({ibGib:a});u(`4.7B Setup: \u2713 Created identity: ${i}`);let d=await new J().postGenesisKeystone(a);if(!d.success)throw new Error(`Server rejected genesis domain keystone: ${d.message}`);u("4.7B Setup: \u2713 Identity registered on server."),u("4.7B Setup: Creating temporary remote space...");let l=await e.createNewLocalSpace({opts:{allowCancel:!1,spaceName:"remote_space_4_7b",getFnPrompt:e.getFnPrompt}});await l.initialized,await e.put({ibGib:a,space:l}),await e.registerNewIbGib({ibGib:a,space:l});let b=await F.firstGen({parentIbGib:q,ib:"timeline_root_conflict_4_7b",data:{type:"root",label:"CommonRoot",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),p=b.newIbGib;await e.persistTransformResult({resTransform:b,space:t}),await e.registerNewIbGib({ibGib:p,space:t}),ht.testRoot=p;let h=await Z({timeline:p,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"V1Common"}},metaspace:e,space:t}),g=await e.getDependencyGraph({ibGibAddr:y({ibGib:p}),space:t}),m=await e.getDependencyGraph({ibGibAddr:y({ibGib:h}),space:t}),w={...g,...m};await e.put({ibGibs:Object.values(w),space:l}),await e.registerNewIbGib({ibGib:p,space:l}),await e.registerNewIbGib({ibGib:h,space:l}),u("4.7B Setup: Syncing v1_common to server...");let S=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(i)}`,wsUrl:`${n}//${location.host}/api/sync/ws/${encodeURIComponent(i)}`}),A=new W;await S.initializeOpts({localMetaspace:e,localSpace:t,senderIdentity:a,fnSenderSecret:f(async()=>"test-sender-secret-phase4-7b","fnSenderSecret"),sagaId:await U(),sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[i]}),await(await A.sync({domainIbGibs:[h],senderIdentity:a,fnSenderSecret:f(async()=>"test-sender-secret-phase4-7b","fnSenderSecret"),peer:S,localSpace:t,metaspace:e,conflictStrategy:X.optimisticWithLCS})).done,u("4.7B Setup: \u2713 Seeding complete on server.");let $=await e.getLatestAddr({ibGib:a,space:t});if(!$)throw new Error("Could not find latest evolved identity address in local space.");let T=await e.get({addr:$,space:t});if(!T.success||!T.ibGibs||T.ibGibs.length===0)throw new Error("Could not find latest evolved identity in local space.");s=T.ibGibs[0],ht.domainI_latest=s,u(`4.7B Setup: \u2713 Fetched evolved identity: ${$}`),await e.put({ibGib:s,space:l}),await e.registerNewIbGib({ibGib:s,space:l});let _=await Z({timeline:h,mut8Opts:{dataToAddOrPatch:{fieldA:"source_edit"}},metaspace:e,space:t});ht.targetAlphaV2a=_,u(`4.7B Setup: \u2713 Created client divergent edit V2a: ${y({ibGib:_})}`);let G=await Z({timeline:h,mut8Opts:{dataToAddOrPatch:{fieldB:"dest_edit"}},metaspace:e,space:l});ht.targetBetaV2b=G,u(`4.7B Setup: \u2713 Created remote divergent edit V2b: ${y({ibGib:G})}`),u("4.7B Setup: Pushing V2b from remote space to server...");let v=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(i)}`,wsUrl:`${n}//${location.host}/api/sync/ws/${encodeURIComponent(i)}`}),N=new W;await v.initializeOpts({localMetaspace:e,localSpace:l,senderIdentity:s,fnSenderSecret:f(async()=>"test-sender-secret-phase4-7b","fnSenderSecret"),sagaId:await U(),sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[i]}),await(await N.sync({domainIbGibs:[G],senderIdentity:s,fnSenderSecret:f(async()=>"test-sender-secret-phase4-7b","fnSenderSecret"),peer:v,localSpace:l,metaspace:e,conflictStrategy:X.optimisticWithLCS})).done,u("4.7B Setup: \u2713 Server tip is now V2b.");let B=await e.getLatestAddr({ibGib:a,space:l});if(!B)throw new Error("Could not find latest evolved identity address in remote space.");let P=await e.get({addr:B,space:l});if(!P.success||!P.ibGibs||P.ibGibs.length===0)throw new Error("Could not find latest evolved identity in remote space.");let k=P.ibGibs[0];await e.put({ibGib:k,space:t}),await e.registerNewIbGib({ibGib:k,space:t}),ht.domainI_latest=k,u(`4.7B Setup: \u2713 Copied evolved identity tip (n=3) back to default space: ${B}`),u("\u2713 4.7B Setup Complete! Ready for 4.7B Sync."),r.textContent="\u2713 4.7B Setup Complete";let M=document.getElementById("btn-4-7b-sync");M&&(M.disabled=!1)}catch(e){u(`\u2717 4.7B Setup FAILED: ${E(e)}`),console.error(e),r.disabled=!1}})}f(od,"init4_7bSetupButton");function nd(){let r=document.getElementById("btn-4-7b-sync");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,u("4.7B Sync: Initiating WebSocket Sync for divergent edit V2a...");let e=ht.domainI_latest,t=ht.targetAlphaV2a;if(!e||!t){u("\u26A0 4.7B Sync: Missing setup state. Please run Setup first."),r.disabled=!1;return}let o=y({ibGib:e}),n=await V(),a=await n.getLocalUserSpace({});if(!a)throw new Error("No default space.");let s=location.protocol==="https:"?"wss:":"ws:",i=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(o)}`,wsUrl:`${s}//${location.host}/api/sync/ws/${encodeURIComponent(o)}`}),c=new W,d=await U();await i.initializeOpts({localMetaspace:n,localSpace:a,senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-7b","fnSenderSecret"),sagaId:d,sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[o]}),await(await c.sync({domainIbGibs:[t],senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-7b","fnSenderSecret"),peer:i,localSpace:a,metaspace:n,conflictStrategy:X.optimisticWithLCS})).done,u("\u2713 4.7B Sync Execution Complete! Ready for 4.7B Check."),r.textContent="\u2713 4.7B Sync Run";let b=document.getElementById("btn-4-7b-check");b&&(b.disabled=!1)}catch(e){u(`\u2717 4.7B Sync FAILED: ${E(e)}`),console.error(e),r.disabled=!1}})}f(nd,"init4_7bSyncButton");function ad(){let r=document.getElementById("btn-4-7b-check");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,u("4.7B Check: Verifying merged tip (V3) contains both edits on client and server...");let e=ht.domainI_latest,t=ht.testRoot,o=ht.targetAlphaV2a,n=ht.targetBetaV2b;if(!e||!t||!o||!n){u("\u26A0 4.7B Check: Missing state. Did Setup and Sync run?"),r.disabled=!1;return}let a=y({ibGib:e}),s=de({ibGib:t,defaultIfNone:"incomingAddr"})??y({ibGib:t}),i=await V(),c=await i.getLocalUserSpace({});if(!c)throw new Error("No default space.");let l=(await i.getLocalUserSpace({}).then(T=>new W().getKnowledgeMap({space:T,metaspace:i,domainIbGibs:[t]})))[s];if(u(`4.7B Check: Client tip address: ${l}`),!l)throw new Error("Client default space is missing the timeline tip.");let b=await i.get({addr:l,space:c});if(!b.success||!b.ibGibs||b.ibGibs.length===0)throw new Error("Client tip not found in default local space.");let p=b.ibGibs[0];if(!p.data||!p.data.fieldA||!p.data.fieldB)throw new Error(`Merged client tip is missing expected data edits: fieldA: ${p.data?.fieldA}, fieldB: ${p.data?.fieldB}`);u("4.7B Check: \u2713 Client tip has both fieldA and fieldB edits.");let h=p.rel8ns?.[$t];if(!h?.[0])throw new Error("Client tip is missing graftinfo relations.");let g=await i.get({addr:h[0],space:c});if(!g.success||!g.ibGibs||g.ibGibs.length===0)throw new Error("GraftInfo not found in local space.");let m=g.ibGibs[0],w=m.rel8ns?.[rr],S=m.rel8ns?.[Lt];if(!w||!S)throw new Error("GraftInfo is missing graftbase or graftorphan relations.");u("4.7B Check: \u2713 Client graft base and orphan relations are correctly set.");let A=new J;u("4.7B Check: Fetching server timeline graph...");let I=await A.getIbGibGraph(a,l,!0);if(!I.success||!I.graph)throw new Error(`Failed to fetch merged graph from server: ${I.message}`);let $=I.graph[l];if(!$)throw new Error("Merged V3 tip is not present on the server!");if($.data?.fieldA!=="source_edit"||$.data?.fieldB!=="dest_edit")throw new Error("Server tip data edits do not match merged values.");u("4.7B Check: \u2713 Server tip has matching merged edits."),u("\u2713 4.7B Check SUCCESS: Divergent branches merged successfully on both client and server via optimistic graft!"),r.textContent="\u2713 4.7B Check Success"}catch(e){u(`\u2717 4.7B Check FAILED: ${E(e)}`),console.error(e),r.disabled=!1}})}f(ad,"init4_7bCheckButton");var ut={};function sd(){let r=document.getElementById("btn-4-8b-setup");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,u("4.8B Setup: Setting up identities, seeding history, and creating divergent branches in client and remote...");let e=await V(),t=await e.getLocalUserSpace({});if(!t)throw new Error("No default space.");let o=new se,n=location.protocol==="https:"?"wss:":"ws:",a=await o.genesis({masterSecret:"test-sender-secret-phase4-8b",configs:[fe("sync","senderidentitysyncsaltphase4-8b"),fe("manage","senderidentitymanagesaltphase4-8b")],metaspace:e,space:t,frameDetails:{client:"space-gib-web-dev",timestamp:oe()}});ut.domainI_latest=a;let s=a,i=y({ibGib:a});u(`4.8B Setup: \u2713 Created identity: ${i}`);let d=await new J().postGenesisKeystone(a);if(!d.success)throw new Error(`Server rejected genesis domain keystone: ${d.message}`);u("4.8B Setup: \u2713 Identity registered on server."),u("4.8B Setup: Creating temporary remote space...");let l=await e.createNewLocalSpace({opts:{allowCancel:!1,spaceName:"remote_space_4_8b",getFnPrompt:e.getFnPrompt}});await l.initialized,await e.put({ibGib:a,space:l}),await e.registerNewIbGib({ibGib:a,space:l});let b=await F.firstGen({parentIbGib:q,ib:"timeline_root_conflict_4_8b",data:{type:"root",label:"CommonRoot",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),p=b.newIbGib;await e.persistTransformResult({resTransform:b,space:t}),await e.registerNewIbGib({ibGib:p,space:t}),ut.testRoot=p;let h=await Z({timeline:p,mut8Opts:{dataToAddOrPatch:{type:"comment",label:"V1Common"}},metaspace:e,space:t}),g=await e.getDependencyGraph({ibGibAddr:y({ibGib:p}),space:t}),m=await e.getDependencyGraph({ibGibAddr:y({ibGib:h}),space:t}),w={...g,...m};await e.put({ibGibs:Object.values(w),space:l}),await e.registerNewIbGib({ibGib:p,space:l}),await e.registerNewIbGib({ibGib:h,space:l}),u("4.8B Setup: Syncing v1_common to server...");let S=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(i)}`,wsUrl:`${n}//${location.host}/api/sync/ws/${encodeURIComponent(i)}`}),A=new W;await S.initializeOpts({localMetaspace:e,localSpace:t,senderIdentity:a,fnSenderSecret:f(async()=>"test-sender-secret-phase4-8b","fnSenderSecret"),sagaId:await U(),sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[i]}),await(await A.sync({domainIbGibs:[h],senderIdentity:a,fnSenderSecret:f(async()=>"test-sender-secret-phase4-8b","fnSenderSecret"),peer:S,localSpace:t,metaspace:e,conflictStrategy:X.optimisticWithLCS})).done,u("4.8B Setup: \u2713 Seeding complete on server.");let $=await e.getLatestAddr({ibGib:a,space:t});if(!$)throw new Error("Could not find latest evolved identity address in local space.");let T=await e.get({addr:$,space:t});if(!T.success||!T.ibGibs||T.ibGibs.length===0)throw new Error("Could not find latest evolved identity in local space.");s=T.ibGibs[0],ut.domainI_latest=s,u(`4.8B Setup: \u2713 Fetched evolved identity: ${$}`),await e.put({ibGib:s,space:l}),await e.registerNewIbGib({ibGib:s,space:l});let _=await F.firstGen({parentIbGib:q,ib:"beta_multitimelines_withid_4_8b",data:{fieldA:"beta field A created on source"},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),G=_.newIbGib;await e.persistTransformResult({resTransform:_,space:t}),await e.registerNewIbGib({ibGib:G,space:t}),ut.targetBetaV0=G,u(`4.8B Setup: \u2713 Created client independent related timeline Beta: ${y({ibGib:G})}`);let v=await Z({timeline:h,mut8Opts:{dataToAddOrPatch:{fieldA:"source_edit"}},metaspace:e,space:t}),N=await dr({timeline:v,metaspace:e,space:t,rel8nInfos:[{rel8nName:"testrel8n",ibGibs:[G]}]});ut.targetAlphaV3a=N,u(`4.8B Setup: \u2713 Created client divergent edit V3a: ${y({ibGib:N})}`);let D=await Z({timeline:h,mut8Opts:{dataToAddOrPatch:{fieldB:"dest_edit"}},metaspace:e,space:l});u(`4.8B Setup: \u2713 Created remote divergent edit V2b: ${y({ibGib:D})}`),u("4.8B Setup: Pushing V2b from remote space to server...");let B=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(i)}`,wsUrl:`${n}//${location.host}/api/sync/ws/${encodeURIComponent(i)}`}),P=new W;await B.initializeOpts({localMetaspace:e,localSpace:l,senderIdentity:s,fnSenderSecret:f(async()=>"test-sender-secret-phase4-8b","fnSenderSecret"),sagaId:await U(),sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[i]}),await(await P.sync({domainIbGibs:[D],senderIdentity:s,fnSenderSecret:f(async()=>"test-sender-secret-phase4-8b","fnSenderSecret"),peer:B,localSpace:l,metaspace:e,conflictStrategy:X.optimisticWithLCS})).done,u("4.8B Setup: \u2713 Server tip is now V2b.");let M=await e.getLatestAddr({ibGib:a,space:l});if(!M)throw new Error("Could not find latest evolved identity address in remote space.");let j=await e.get({addr:M,space:l});if(!j.success||!j.ibGibs||j.ibGibs.length===0)throw new Error("Could not find latest evolved identity in remote space.");let Q=j.ibGibs[0];await e.put({ibGib:Q,space:t}),await e.registerNewIbGib({ibGib:Q,space:t}),ut.domainI_latest=Q,u(`4.8B Setup: \u2713 Copied evolved identity tip (n=3) back to default space: ${M}`),u("\u2713 4.8B Setup Complete! Ready for 4.8B Sync."),r.textContent="\u2713 4.8B Setup Complete";let ee=document.getElementById("btn-4-8b-sync");ee&&(ee.disabled=!1)}catch(e){u(`\u2717 4.8B Setup FAILED: ${E(e)}`),console.error(e),r.disabled=!1}})}f(sd,"init4_8bSetupButton");function id(){let r=document.getElementById("btn-4-8b-sync");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,u("4.8B Sync: Initiating WebSocket Sync for divergent edit V3a (with related timeline Beta)...");let e=ut.domainI_latest,t=ut.targetAlphaV3a;if(!e||!t){u("\u26A0 4.8B Sync: Missing setup state. Please run Setup first."),r.disabled=!1;return}let o=y({ibGib:e}),n=await V(),a=await n.getLocalUserSpace({});if(!a)throw new Error("No default space.");let s=location.protocol==="https:"?"wss:":"ws:",i=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(o)}`,wsUrl:`${s}//${location.host}/api/sync/ws/${encodeURIComponent(o)}`}),c=new W,d=await U();await i.initializeOpts({localMetaspace:n,localSpace:a,senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-8b","fnSenderSecret"),sagaId:d,sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[o]}),await(await c.sync({domainIbGibs:[t],senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-8b","fnSenderSecret"),peer:i,localSpace:a,metaspace:n,conflictStrategy:X.optimisticWithLCS})).done,u("\u2713 4.8B Sync Execution Complete! Ready for 4.8B Check."),r.textContent="\u2713 4.8B Sync Run";let b=document.getElementById("btn-4-8b-check");b&&(b.disabled=!1)}catch(e){u(`\u2717 4.8B Sync FAILED: ${E(e)}`),console.error(e),r.disabled=!1}})}f(id,"init4_8bSyncButton");function cd(){let r=document.getElementById("btn-4-8b-check");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,u("4.8B Check: Verifying merged tip (V4) contains both edits on client and server...");let e=ut.domainI_latest,t=ut.testRoot,o=ut.targetAlphaV3a,n=ut.targetBetaV0;if(!e||!t||!o||!n){u("\u26A0 4.8B Check: Missing state. Did Setup and Sync run?"),r.disabled=!1;return}let a=y({ibGib:e}),s=de({ibGib:t,defaultIfNone:"incomingAddr"})??y({ibGib:t}),i=y({ibGib:n}),c=await V(),d=await c.getLocalUserSpace({});if(!d)throw new Error("No default space.");let b=(await c.getLocalUserSpace({}).then(G=>new W().getKnowledgeMap({space:G,metaspace:c,domainIbGibs:[t]})))[s];if(u(`4.8B Check: Client tip address: ${b}`),!b)throw new Error("Client default space is missing the timeline tip.");let p=await c.get({addr:b,space:d});if(!p.success||!p.ibGibs||p.ibGibs.length===0)throw new Error("Client tip not found in default local space.");let h=p.ibGibs[0];if(!h.data||!h.data.fieldA||!h.data.fieldB)throw new Error(`Merged client tip is missing expected data edits: fieldA: ${h.data?.fieldA}, fieldB: ${h.data?.fieldB}`);u("4.8B Check: \u2713 Client tip has both fieldA and fieldB edits.");let g=h.rel8ns?.[$t];if(!g?.[0])throw new Error("Client tip is missing graftinfo relations.");let m=await c.get({addr:g[0],space:d});if(!m.success||!m.ibGibs||m.ibGibs.length===0)throw new Error("GraftInfo not found in local space.");let w=m.ibGibs[0],S=w.rel8ns?.[rr],A=w.rel8ns?.[Lt];if(!S||!A)throw new Error("GraftInfo is missing graftbase or graftorphan relations.");u("4.8B Check: \u2713 Client graft base and orphan relations are correctly set.");let I=new J;u("4.8B Check: Fetching server timeline graph...");let $=await I.getIbGibGraph(a,b,!0);if(!$.success||!$.graph)throw new Error(`Failed to fetch merged graph from server: ${$.message}`);let T=$.graph[b];if(!T)throw new Error("Merged V4 tip is not present on the server!");if(T.data?.fieldA!=="source_edit"||T.data?.fieldB!=="dest_edit")throw new Error("Server tip data edits do not match merged values.");u("4.8B Check: \u2713 Server tip has matching merged edits."),u("4.8B Check: Verifying related timeline Beta is present on the server...");let _=await I.getIbGibGraph(a,i,!0);if(!_.success||!_.graph||!_.graph[i])throw new Error(`Related timeline Beta (${i}) is missing from the server!`);u("4.8B Check: \u2713 Related timeline Beta successfully verified on the server."),u("\u2713 4.8B Check SUCCESS: Divergent branches merged successfully and related timeline synced on server!"),r.textContent="\u2713 4.8B Check Success"}catch(e){u(`\u2717 4.8B Check FAILED: ${E(e)}`),console.error(e),r.disabled=!1}})}f(cd,"init4_8bCheckButton");var Pt={},jn=`This is the initial quiz question.
32
+ It has multiple lines.
33
+ Students will answer this.`,ld=`
34
+ Instructor added hint.`,dd=`Student note: Confusing!
35
+ `;function fd(){let r=document.getElementById("btn-4-9b-setup");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,u("4.9B Setup: Setting up identities, seeding text history, and creating divergent branches...");let e=await V(),t=await e.getLocalUserSpace({});if(!t)throw new Error("No default space.");let o=new se,n=location.protocol==="https:"?"wss:":"ws:",a=await o.genesis({masterSecret:"test-sender-secret-phase4-9b",configs:[fe("sync","senderidentitysyncsaltphase4-9b"),fe("manage","senderidentitymanagesaltphase4-9b")],metaspace:e,space:t,frameDetails:{client:"space-gib-web-dev",timestamp:oe()}});Pt.domainI_latest=a;let s=a,i=y({ibGib:a});u(`4.9B Setup: \u2713 Created identity: ${i}`);let d=await new J().postGenesisKeystone(a);if(!d.success)throw new Error(`Server rejected genesis domain keystone: ${d.message}`);u("4.9B Setup: \u2713 Identity registered on server."),u("4.9B Setup: Creating temporary remote space...");let l=await e.createNewLocalSpace({opts:{allowCancel:!1,spaceName:"remote_space_4_9b",getFnPrompt:e.getFnPrompt}});await l.initialized,await e.put({ibGib:a,space:l}),await e.registerNewIbGib({ibGib:a,space:l});let b=await F.firstGen({parentIbGib:q,ib:"timeline_root_text_conflict_4_9b",data:{text:jn,label:"TextRoot",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),p=b.newIbGib;await e.persistTransformResult({resTransform:b,space:t}),await e.registerNewIbGib({ibGib:p,space:t}),Pt.testRoot=p;let h=await e.getDependencyGraph({ibGibAddr:y({ibGib:p}),space:t});await e.put({ibGibs:Object.values(h),space:l}),await e.registerNewIbGib({ibGib:p,space:l}),u("4.9B Setup: Syncing testRoot to server...");let g=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(i)}`,wsUrl:`${n}//${location.host}/api/sync/ws/${encodeURIComponent(i)}`}),m=new W;await g.initializeOpts({localMetaspace:e,localSpace:t,senderIdentity:a,fnSenderSecret:f(async()=>"test-sender-secret-phase4-9b","fnSenderSecret"),sagaId:await U(),sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[i]}),await(await m.sync({domainIbGibs:[p],senderIdentity:a,fnSenderSecret:f(async()=>"test-sender-secret-phase4-9b","fnSenderSecret"),peer:g,localSpace:t,metaspace:e,conflictStrategy:X.optimisticWithLCS})).done,u("4.9B Setup: \u2713 Seeding complete on server.");let S=await e.getLatestAddr({ibGib:a,space:t});if(!S)throw new Error("Could not find latest evolved identity address in local space.");let A=await e.get({addr:S,space:t});if(!A.success||!A.ibGibs||A.ibGibs.length===0)throw new Error("Could not find latest evolved identity in local space.");s=A.ibGibs[0],Pt.domainI_latest=s,u(`4.9B Setup: \u2713 Fetched evolved identity: ${S}`),await e.put({ibGib:s,space:l}),await e.registerNewIbGib({ibGib:s,space:l});let I=await Z({timeline:p,mut8Opts:{mut8Ib:p.ib+"_appended",dataToAddOrPatch:{text:jn+ld}},metaspace:e,space:t});Pt.targetAlphaV1Source=I,u(`4.9B Setup: \u2713 Created client appended edit: ${y({ibGib:I})}`);let $=await Z({timeline:p,mut8Opts:{mut8Ib:p.ib+"_prepended",dataToAddOrPatch:{text:dd+jn}},metaspace:e,space:l});u(`4.9B Setup: \u2713 Created remote prepended edit: ${y({ibGib:$})}`),u("4.9B Setup: Pushing remote prepended edit to server...");let T=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(i)}`,wsUrl:`${n}//${location.host}/api/sync/ws/${encodeURIComponent(i)}`}),_=new W;await T.initializeOpts({localMetaspace:e,localSpace:l,senderIdentity:s,fnSenderSecret:f(async()=>"test-sender-secret-phase4-9b","fnSenderSecret"),sagaId:await U(),sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[i]}),await(await _.sync({domainIbGibs:[$],senderIdentity:s,fnSenderSecret:f(async()=>"test-sender-secret-phase4-9b","fnSenderSecret"),peer:T,localSpace:l,metaspace:e,conflictStrategy:X.optimisticWithLCS})).done,u("4.9B Setup: \u2713 Server tip is now the prepended edit.");let v=await e.getLatestAddr({ibGib:a,space:l});if(!v)throw new Error("Could not find latest evolved identity address in remote space.");let N=await e.get({addr:v,space:l});if(!N.success||!N.ibGibs||N.ibGibs.length===0)throw new Error("Could not find latest evolved identity in remote space.");let D=N.ibGibs[0];await e.put({ibGib:D,space:t}),await e.registerNewIbGib({ibGib:D,space:t}),Pt.domainI_latest=D,u(`4.9B Setup: \u2713 Copied evolved identity tip (n=3) back to default space: ${v}`),u("\u2713 4.9B Setup Complete! Ready for 4.9B Sync."),r.textContent="\u2713 4.9B Setup Complete";let B=document.getElementById("btn-4-9b-sync");B&&(B.disabled=!1)}catch(e){u(`\u2717 4.9B Setup FAILED: ${E(e)}`),console.error(e),r.disabled=!1}})}f(fd,"init4_9bSetupButton");function bd(){let r=document.getElementById("btn-4-9b-sync");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,u("4.9B Sync: Initiating WebSocket Sync for divergent edit (LCS text merge)...");let e=Pt.domainI_latest,t=Pt.targetAlphaV1Source;if(!e||!t){u("\u26A0 4.9B Sync: Missing setup state. Please run Setup first."),r.disabled=!1;return}let o=y({ibGib:e}),n=await V(),a=await n.getLocalUserSpace({});if(!a)throw new Error("No default space.");let s=location.protocol==="https:"?"wss:":"ws:",i=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(o)}`,wsUrl:`${s}//${location.host}/api/sync/ws/${encodeURIComponent(o)}`}),c=new W,d=await U();await i.initializeOpts({localMetaspace:n,localSpace:a,senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-9b","fnSenderSecret"),sagaId:d,sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[o]}),await(await c.sync({domainIbGibs:[t],senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-9b","fnSenderSecret"),peer:i,localSpace:a,metaspace:n,conflictStrategy:X.optimisticWithLCS})).done,u("\u2713 4.9B Sync Execution Complete! Ready for 4.9B Check."),r.textContent="\u2713 4.9B Sync Run";let b=document.getElementById("btn-4-9b-check");b&&(b.disabled=!1)}catch(e){u(`\u2717 4.9B Sync FAILED: ${E(e)}`),console.error(e),r.disabled=!1}})}f(bd,"init4_9bSyncButton");function pd(){let r=document.getElementById("btn-4-9b-check");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,u("4.9B Check: Verifying LCS merged text on client and server...");let e=Pt.domainI_latest,t=Pt.testRoot,o=Pt.targetAlphaV1Source;if(!e||!t||!o){u("\u26A0 4.9B Check: Missing state. Did Setup and Sync run?"),r.disabled=!1;return}let n=y({ibGib:e}),a=de({ibGib:t,defaultIfNone:"incomingAddr"})??y({ibGib:t}),s=await V(),i=await s.getLocalUserSpace({});if(!i)throw new Error("No default space.");let d=(await s.getLocalUserSpace({}).then(T=>new W().getKnowledgeMap({space:T,metaspace:s,domainIbGibs:[t]})))[a];if(u(`4.9B Check: Client tip address: ${d}`),!d)throw new Error("Client default space is missing the timeline tip.");let l=await s.get({addr:d,space:i});if(!l.success||!l.ibGibs||l.ibGibs.length===0)throw new Error("Client tip not found in default local space.");let b=l.ibGibs[0],p=dd+jn+ld;if(b.data?.text!==p)throw new Error(`Merged client tip text mismatch! Expected:
36
+ ${p}
37
+ Actual:
38
+ ${b.data?.text}`);u("4.9B Check: \u2713 Client tip text contains both prepend and append edits merged correctly.");let h=b.rel8ns?.[$t];if(!h?.[0])throw new Error("Client tip is missing graftinfo relations.");let g=await s.get({addr:h[0],space:i});if(!g.success||!g.ibGibs||g.ibGibs.length===0)throw new Error("GraftInfo not found in local space.");let m=g.ibGibs[0],w=m.rel8ns?.[rr],S=m.rel8ns?.[Lt];if(!w||!S)throw new Error("GraftInfo is missing graftbase or graftorphan relations.");u("4.9B Check: \u2713 Client graft base and orphan relations are correctly set.");let A=new J;u("4.9B Check: Fetching server timeline graph...");let I=await A.getIbGibGraph(n,d,!0);if(!I.success||!I.graph)throw new Error(`Failed to fetch merged graph from server: ${I.message}`);let $=I.graph[d];if(!$)throw new Error("Merged tip is not present on the server!");if($.data?.text!==p)throw new Error(`Server tip text mismatch! Expected:
39
+ ${p}
40
+ Actual:
41
+ ${$.data?.text}`);u("4.9B Check: \u2713 Server tip text matches the client-side merged text."),u("\u2713 4.9B Check SUCCESS: LCS text field merge conflict resolved and verified on both client and server!"),r.textContent="\u2713 4.9B Check Success"}catch(e){u(`\u2717 4.9B Check FAILED: ${E(e)}`),console.error(e),r.disabled=!1}})}f(pd,"init4_9bCheckButton");var z={},Rs="testrel8n";function hd(){let r=document.getElementById("btn-4-10b-setup");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,u("4.10B Setup: Setting up identities and preparing Round 1 & Round 2 divergence...");let e=await V(),t=await e.getLocalUserSpace({});if(!t)throw new Error("No default space.");let o=new se,n=location.protocol==="https:"?"wss:":"ws:",a=await o.genesis({masterSecret:"test-sender-secret-phase4-10b",configs:[fe("sync","senderidentitysyncsaltphase4-10b"),fe("manage","senderidentitymanagesaltphase4-10b")],metaspace:e,space:t,frameDetails:{client:"space-gib-web-dev",timestamp:oe()}});z.domainI_initial=a,z.domainI_latest=a;let s=a,i=y({ibGib:a});u(`4.10B Setup: \u2713 Created identity: ${i}`);let d=await new J().postGenesisKeystone(a);if(!d.success)throw new Error(`Server rejected genesis domain keystone: ${d.message}`);u("4.10B Setup: \u2713 Identity registered on server."),u("4.10B Setup: Creating temporary remote space...");let l=await e.createNewLocalSpace({opts:{allowCancel:!1,spaceName:"remote_space_4_10b",getFnPrompt:e.getFnPrompt}});await l.initialized,z.remoteSpace=l,await e.put({ibGib:a,space:l}),await e.registerNewIbGib({ibGib:a,space:l}),u("4.10B Setup: Creating common history for alpha...");let b=await F.firstGen({parentIbGib:q,ib:"timeline_root_alpha_4_10b",data:{commonField:"common field R1 val",label:"AlphaRoot",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),p=b.newIbGib;z.alpha_v0=p,await e.persistTransformResult({resTransform:b,space:t}),await e.registerNewIbGib({ibGib:p,space:t});let h=de({ibGib:p,defaultIfNone:"incomingAddr"});z.alpha_tjpAddr=h,await e.persistTransformResult({resTransform:b,space:l}),await e.registerNewIbGib({ibGib:p,space:l}),u("4.10B Setup: Seeding alpha_v0 to server...");let g=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(i)}`,wsUrl:`${n}//${location.host}/api/sync/ws/${encodeURIComponent(i)}`}),m=new W;await g.initializeOpts({localMetaspace:e,localSpace:t,senderIdentity:a,fnSenderSecret:f(async()=>"test-sender-secret-phase4-10b","fnSenderSecret"),sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[i]}),await(await m.sync({domainIbGibs:[p],senderIdentity:a,fnSenderSecret:f(async()=>"test-sender-secret-phase4-10b","fnSenderSecret"),peer:g,localSpace:t,metaspace:e,conflictStrategy:X.optimisticWithLCS})).done,u("4.10B Setup: \u2713 alpha_v0 seeded on server.");let S=await e.getLatestAddr({ibGib:a,space:t});if(!S)throw new Error("Could not find latest evolved identity address in local space.");s=(await e.get({addr:S,space:t})).ibGibs[0],z.domainI_latest=s,await e.put({ibGib:s,space:l}),await e.registerNewIbGib({ibGib:s,space:l});let I=await F.firstGen({parentIbGib:q,ib:"timeline_root_beta_4_10b",data:{fieldA:"beta field A created on source",label:"BetaRoot",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),$=I.newIbGib;await e.persistTransformResult({resTransform:I,space:t}),await e.registerNewIbGib({ibGib:$,space:t}),z.r2_beta_v0_source=$;let T=de({ibGib:$,defaultIfNone:"incomingAddr"});z.beta_tjpAddr=T;let _=await Z({timeline:p,mut8Opts:{mut8Ib:p.ib+"_r2client",dataToAddOrPatch:{fieldA:"source_edit_r2"}},metaspace:e,space:t});u(`r2_alpha_v1_source_sansBeta.gib: ${_.gib}`),Ps=y({ibGib:$});let G=await dr({timeline:_,metaspace:e,space:t,rel8nInfos:[{rel8nName:Rs,ibGibs:[$]}]});z.r2_alpha_v3_source_rel8beta=G,u(`r2_alpha_v2_source_rel8dBeta.gib: ${G.gib}`),u("4.10B Setup: \u2713 Created client Round 2 edits (alpha fieldA edit + relate beta).");let v=await Z({timeline:p,mut8Opts:{mut8Ib:p.ib+"_r2remote",dataToAddOrPatch:{fieldB:"remote_edit_r2"}},metaspace:e,space:l});console.log(`alpha_v0: ${K(p)}`),console.log(`r2_alpha_v1_remote: ${K(v)}`),u(`r2_alpha_v1_remote.gib: ${v.gib}`),u("4.10B Setup: Pushing remote Round 2 edit to server...");let N=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(i)}`,wsUrl:`${n}//${location.host}/api/sync/ws/${encodeURIComponent(i)}`}),D=new W;await N.initializeOpts({localMetaspace:e,localSpace:l,senderIdentity:s,fnSenderSecret:f(async()=>"test-sender-secret-phase4-10b","fnSenderSecret"),sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[i]}),await(await D.sync({domainIbGibs:[v],senderIdentity:s,fnSenderSecret:f(async()=>"test-sender-secret-phase4-10b","fnSenderSecret"),peer:N,localSpace:l,metaspace:e,conflictStrategy:X.optimisticWithLCS})).done,u("4.10B Setup: \u2713 Server tip is now remote Round 2 edit.");let P=await e.getLatestAddr({ibGib:a,space:l});if(!P)throw new Error("Could not find latest evolved identity address in remote space.");let M=(await e.get({addr:P,space:l})).ibGibs[0];await e.put({ibGib:M,space:t}),await e.registerNewIbGib({ibGib:M,space:t}),z.domainI_latest=M,u("\u2713 4.10B Setup Complete! Ready for 4.10B Sync (which runs Round 2, 3, and 4 in succession)."),r.textContent="\u2713 4.10B Setup Complete";let j=document.getElementById("btn-4-10b-sync");j&&(j.disabled=!1)}catch(e){u(`\u2717 4.10B Setup FAILED: ${E(e)}`),console.error(e),r.disabled=!1}})}f(hd,"init4_10bSetupButton");var Ds,Ps;function ud(){let r=document.getElementById("btn-4-10b-sync");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,u("4.10B Sync: Initiating WebSocket Sync for Round 2, 3, and 4 sequential evolution...");let e=z.domainI_latest,t=z.remoteSpace,o=z.alpha_tjpAddr,n=z.beta_tjpAddr,a=z.alpha_v0,s=await V(),i=await s.getLocalUserSpace({});if(!i)throw new Error("No default space.");let c=location.protocol==="https:"?"wss:":"ws:",d=y({ibGib:z.domainI_initial});u("4.10B Sync: Running Round 2 Sync (merging divergent alpha edits)...");let l=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(d)}`,wsUrl:`${c}//${location.host}/api/sync/ws/${encodeURIComponent(d)}`}),b=new W;await l.initializeOpts({localMetaspace:s,localSpace:i,senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-10b","fnSenderSecret"),sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[d]}),await(await b.sync({domainIbGibs:[z.r2_alpha_v3_source_rel8beta],senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-10b","fnSenderSecret"),peer:l,localSpace:i,metaspace:s,conflictStrategy:X.optimisticWithLCS})).done,u("4.10B Sync: \u2713 Round 2 Sync complete.");let h=await s.getLatestAddr({ibGib:z.domainI_initial,space:i}),g=await s.get({addr:h,space:i});e=g.ibGibs[0],await s.put({ibGib:e,space:t}),await s.registerNewIbGib({ibGib:e,space:t}),u("4.10B Sync: Preparing Round 3 divergence (multiple conflicting timelines)...");let m=await b.getKnowledgeMap({domainIbGibs:[z.r2_alpha_v3_source_rel8beta,z.r2_beta_v0_source],space:i,metaspace:s}),w=m[o],S=m[n],A=await s.get({addr:w,space:i}),I=await s.get({addr:S,space:i}),$=await Z({timeline:A.ibGibs[0],mut8Opts:{mut8Ib:a.ib+"_r3client",dataToAddOrPatch:{fieldC:"source_edit_r3"}},metaspace:s,space:i}),T=await Z({timeline:I.ibGibs[0],mut8Opts:{mut8Ib:z.r2_beta_v0_source.ib+"_r3client",dataToAddOrPatch:{betaFieldA:"source_beta_edit_r3"}},metaspace:s,space:i});u("4.10B Sync: Updating remote space to latest merged tips...");let _=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(d)}`,wsUrl:`${c}//${location.host}/api/sync/ws/${encodeURIComponent(d)}`}),G=new W;await _.initializeOpts({localMetaspace:s,localSpace:t,senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-10b","fnSenderSecret"),sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[d]});let v=await s.getLatestAddr({addr:o,space:t}),B=[(await s.get({addr:v,space:t})).ibGibs[0]],P=await s.getLatestAddr({addr:n,space:t});if(P){let Kn=await s.get({addr:P,space:t});B.push(Kn.ibGibs[0])}await(await G.sync({domainIbGibs:B,senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-10b","fnSenderSecret"),peer:_,localSpace:t,metaspace:s,conflictStrategy:X.optimisticWithLCS})).done,h=await s.getLatestAddr({ibGib:z.domainI_initial,space:t}),g=await s.get({addr:h,space:t}),e=g.ibGibs[0],await s.put({ibGib:e,space:i}),await s.registerNewIbGib({ibGib:e,space:i});let M=await G.getKnowledgeMap({space:t,metaspace:s,domainIbGibs:[a,z.r2_beta_v0_source]}),j=M[o],Q=M[n],ee=await s.get({addr:j,space:t}),Ge=await s.get({addr:Q,space:t}),Ce=await Z({timeline:ee.ibGibs[0],mut8Opts:{mut8Ib:a.ib+"_r3remote",dataToAddOrPatch:{fieldD:"remote_edit_r3"}},metaspace:s,space:t}),Me=await Z({timeline:Ge.ibGibs[0],mut8Opts:{mut8Ib:z.r2_beta_v0_source.ib+"_r3remote",dataToAddOrPatch:{betaFieldB:"remote_beta_edit_r3"}},metaspace:s,space:t});u("4.10B Sync: Pushing remote Round 3 edits to server...");let Fe=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(d)}`,wsUrl:`${c}//${location.host}/api/sync/ws/${encodeURIComponent(d)}`}),pe=new W;await Fe.initializeOpts({localMetaspace:s,localSpace:t,senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-10b","fnSenderSecret"),sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[d]}),await(await pe.sync({domainIbGibs:[Ce,Me],senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-10b","fnSenderSecret"),peer:Fe,localSpace:t,metaspace:s,conflictStrategy:X.optimisticWithLCS})).done,h=await s.getLatestAddr({ibGib:z.domainI_initial,space:t}),g=await s.get({addr:h,space:t}),e=g.ibGibs[0],await s.put({ibGib:e,space:i}),await s.registerNewIbGib({ibGib:e,space:i}),u("4.10B Sync: Running Round 3 Client Sync (merging alpha & beta divergence)...");let tt=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(d)}`,wsUrl:`${c}//${location.host}/api/sync/ws/${encodeURIComponent(d)}`}),he=new W;await tt.initializeOpts({localMetaspace:s,localSpace:i,senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-10b","fnSenderSecret"),sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[d]}),await(await he.sync({domainIbGibs:[$,T],senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-10b","fnSenderSecret"),peer:tt,localSpace:i,metaspace:s,conflictStrategy:X.optimisticWithLCS})).done,u("4.10B Sync: \u2713 Round 3 Sync complete."),h=await s.getLatestAddr({ibGib:z.domainI_initial,space:i}),g=await s.get({addr:h,space:i}),e=g.ibGibs[0],await s.put({ibGib:e,space:t}),await s.registerNewIbGib({ibGib:e,space:t}),u("4.10B Sync: Preparing Round 4 divergence (post-graft chain edits & new timeline)...");let lt=await he.getKnowledgeMap({space:i,metaspace:s,domainIbGibs:[a,z.r2_beta_v0_source]}),vr=lt[o],pr=lt[n],qr=await s.get({addr:vr,space:i}),gt=await s.get({addr:pr,space:i}),wo=await Z({timeline:qr.ibGibs[0],mut8Opts:{mut8Ib:a.ib+"_r4client_v5",dataToAddOrPatch:{fieldE:"source_edit_r4_v5"}},metaspace:s,space:i}),Wr=await F.firstGen({parentIbGib:q,ib:"timeline_root_gamma_4_10b",data:{gammaField:"gamma created on client",label:"GammaRoot",random:Math.random()},dna:!0,nCounter:!0,tjp:{uuid:!0,timestamp:!0}}),ye=Wr.newIbGib;await s.persistTransformResult({resTransform:Wr,space:i}),await s.registerNewIbGib({ibGib:ye,space:i});let Rt=de({ibGib:ye,defaultIfNone:"incomingAddr"});z.gamma_tjpAddr=Rt,Ds=y({ibGib:ye});let ze=await dr({timeline:wo,metaspace:s,space:i,rel8nInfos:[{rel8nName:Rs,ibGibs:[ye]}]}),Vn=await Z({timeline:ze,mut8Opts:{mut8Ib:a.ib+"_r4client_v7",dataToAddOrPatch:{fieldF:"source_edit_r4_v7"}},metaspace:s,space:i}),Hn=await Z({timeline:gt.ibGibs[0],mut8Opts:{mut8Ib:z.r2_beta_v0_source.ib+"_r4client_v2",dataToAddOrPatch:{betaFieldD:"source_beta_edit_r4_v2"}},metaspace:s,space:i});u("4.10B Sync: Updating remote space to Round 3 merged tips...");let ot=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(d)}`,wsUrl:`${c}//${location.host}/api/sync/ws/${encodeURIComponent(d)}`}),ks=new W;await ot.initializeOpts({localMetaspace:s,localSpace:t,senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-10b","fnSenderSecret"),sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[d]});let md=await s.getLatestAddr({addr:o,space:t}),Bs=[(await s.get({addr:md,space:t})).ibGibs[0]],Us=await s.getLatestAddr({addr:n,space:t});if(Us){let Kn=await s.get({addr:Us,space:t});Bs.push(Kn.ibGibs[0])}await(await ks.sync({domainIbGibs:Bs,senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-10b","fnSenderSecret"),peer:ot,localSpace:t,metaspace:s,conflictStrategy:X.optimisticWithLCS})).done,h=await s.getLatestAddr({ibGib:z.domainI_initial,space:t}),g=await s.get({addr:h,space:t}),e=g.ibGibs[0],await s.put({ibGib:e,space:i}),await s.registerNewIbGib({ibGib:e,space:i});let Ms=await ks.getKnowledgeMap({space:t,metaspace:s,domainIbGibs:[a,z.r2_beta_v0_source]}),Ed=Ms[o],wd=Ms[n],yd=await s.get({addr:Ed,space:t}),$d=await s.get({addr:wd,space:t}),Id=await Z({timeline:yd.ibGibs[0],mut8Opts:{mut8Ib:a.ib+"_r4remote_v5",dataToAddOrPatch:{fieldG:"remote_edit_r4_v5"}},metaspace:s,space:t}),Sd=await Z({timeline:$d.ibGibs[0],mut8Opts:{mut8Ib:z.r2_beta_v0_source.ib+"_r4remote_v2",dataToAddOrPatch:{betaFieldC:"remote_beta_edit_r4_v2"}},metaspace:s,space:t});u("4.10B Sync: Pushing remote Round 4 edits to server...");let Fs=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(d)}`,wsUrl:`${c}//${location.host}/api/sync/ws/${encodeURIComponent(d)}`}),_d=new W;await Fs.initializeOpts({localMetaspace:s,localSpace:t,senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-10b","fnSenderSecret"),sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[d]}),await(await _d.sync({domainIbGibs:[Id,Sd],senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-10b","fnSenderSecret"),peer:Fs,localSpace:t,metaspace:s,conflictStrategy:X.optimisticWithLCS})).done,h=await s.getLatestAddr({ibGib:z.domainI_initial,space:t}),g=await s.get({addr:h,space:t}),e=g.ibGibs[0],await s.put({ibGib:e,space:i}),await s.registerNewIbGib({ibGib:e,space:i}),u("4.10B Sync: Running final Round 4 Client Sync (merging alpha, beta, and propagating gamma)...");let js=new Y({classname:"SyncPeerWebSocketSender_V1",httpEvolveUrl:`${location.protocol}//${location.host}/api/keystone/evolve/${encodeURIComponent(d)}`,wsUrl:`${c}//${location.host}/api/sync/ws/${encodeURIComponent(d)}`}),Ad=new W;await js.initializeOpts({localMetaspace:s,localSpace:i,senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-10b","fnSenderSecret"),sessionConnectPoolConfig:L.CONNECT_POOL,sessionSyncPoolConfig:L.DEFAULT_POOL,targetAddrs:[d]}),await(await Ad.sync({domainIbGibs:[Vn,Hn,ye],senderIdentity:e,fnSenderSecret:f(async()=>"test-sender-secret-phase4-10b","fnSenderSecret"),peer:js,localSpace:i,metaspace:s,conflictStrategy:X.optimisticWithLCS})).done,h=await s.getLatestAddr({ibGib:z.domainI_initial,space:i}),g=await s.get({addr:h,space:i}),e=g.ibGibs[0],z.domainI_latest=e,u("\u2713 4.10B Sync: All rounds of divergent edits and merges complete!"),r.textContent="\u2713 4.10B Sync Complete";let Vs=document.getElementById("btn-4-10b-check");Vs&&(Vs.disabled=!1)}catch(e){u(`\u2717 4.10B Sync FAILED: ${E(e)}`),console.error(e),r.disabled=!1}})}f(ud,"init4_10bSyncButton");function gd(){let r=document.getElementById("btn-4-10b-check");r&&r.addEventListener("click",async()=>{try{r.disabled=!0,u("4.10B Check: Verifying multi-round merged timelines on client and server...");let e=z.domainI_latest,t=z.alpha_tjpAddr,o=z.beta_tjpAddr,n=z.gamma_tjpAddr,a=await V(),s=await a.getLocalUserSpace({});if(!s)throw new Error("No default space.");let i=y({ibGib:z.domainI_initial}),c=await new W().getKnowledgeMap({space:s,metaspace:a,domainIbGibs:[z.domainI_initial]}),d=await a.getLatestAddr({addr:t,space:s}),l=await a.getLatestAddr({addr:o,space:s}),b=await a.getLatestAddr({addr:n,space:s});if(!d||!l||!b)throw new Error("Client space is missing timeline tips for Alpha, Beta, or Gamma.");let p=await a.get({addr:d,space:s}),h=await a.get({addr:l,space:s}),g=p.ibGibs[0],m=h.ibGibs[0];if(g.data?.fieldA!=="source_edit_r2")throw new Error(`Alpha fieldA mismatch! Expected 'source_edit_r2', got '${g.data?.fieldA}'`);if(g.data?.fieldB!=="remote_edit_r2")throw new Error(`Alpha fieldB mismatch! Expected 'remote_edit_r2', got '${g.data?.fieldB}'`);if(g.data?.fieldC!=="source_edit_r3")throw new Error(`Alpha fieldC mismatch! Expected 'source_edit_r3', got '${g.data?.fieldC}'`);if(g.data?.fieldD!=="remote_edit_r3")throw new Error(`Alpha fieldD mismatch! Expected 'remote_edit_r3', got '${g.data?.fieldD}'`);if(g.data?.fieldE!=="source_edit_r4_v5")throw new Error(`Alpha fieldE mismatch! Expected 'source_edit_r4_v5', got '${g.data?.fieldE}'`);if(g.data?.fieldF!=="source_edit_r4_v7")throw new Error(`Alpha fieldF mismatch! Expected 'source_edit_r4_v7', got '${g.data?.fieldF}'`);if(g.data?.fieldG!=="remote_edit_r4_v5")throw new Error(`Alpha fieldG mismatch! Expected 'remote_edit_r4_v5', got '${g.data?.fieldG}'`);if(u("4.10B Check: \u2713 Client Alpha merged tip contains all Round 2, 3, and 4 edits."),m.data?.betaFieldA!=="source_beta_edit_r3")throw new Error(`Beta betaFieldA mismatch! Expected 'source_beta_edit_r3', got '${m.data?.betaFieldA}'`);if(m.data?.betaFieldB!=="remote_beta_edit_r3")throw new Error(`Beta betaFieldB mismatch! Expected 'remote_beta_edit_r3', got '${m.data?.betaFieldB}'`);if(m.data?.betaFieldC!=="remote_beta_edit_r4_v2")throw new Error(`Beta betaFieldC mismatch! Expected 'remote_beta_edit_r4_v2', got '${m.data?.betaFieldC}'`);if(m.data?.betaFieldD!=="source_beta_edit_r4_v2")throw new Error(`Beta betaFieldD mismatch! Expected 'source_beta_edit_r4_v2', got '${m.data?.betaFieldD}'`);u("4.10B Check: \u2713 Client Beta merged tip contains all Round 3 and 4 edits.");let w=g.rel8ns?.[Rs]||[];if(!Ps)throw new Error("(UNEXPECTED) betaAddr falsy? (E: 81c032ae7a93bddfd8eed6664d314826)");if(!w.includes(Ps))throw new Error("Client Alpha tip is missing relation to Beta timeline.");if(!Ds)throw new Error("(UNEXPECTED) gammaAddr falsy? (E: 12220a81d3b86385d1683d5a6bae5826)");if(!w.includes(Ds))throw new Error("Client Alpha tip is missing relation to Gamma timeline.");u("4.10B Check: \u2713 Client Alpha tip retains relation to Gamma.");let S=new J;u("4.10B Check: Fetching server timeline graphs...");let A=await S.getIbGibGraph(i,d,!0),I=await S.getIbGibGraph(i,l,!0);if(!A.success||!A.graph||!I.success||!I.graph)throw new Error("Failed to fetch merged graphs from server.");let $=A.graph[d],T=I.graph[l];if(!$||!T)throw new Error("Server is missing the final merged tips for Alpha or Beta.");if($.data?.fieldF!=="source_edit_r4_v7"||$.data?.fieldG!=="remote_edit_r4_v5")throw new Error("Server Alpha tip does not match final client merged state.");if(T.data?.betaFieldC!=="remote_beta_edit_r4_v2"||T.data?.betaFieldD!=="source_beta_edit_r4_v2")throw new Error("Server Beta tip does not match final client merged state.");u("4.10B Check: \u2713 Server tips match client merged states perfectly."),u("\u2713 4.10B Check SUCCESS: Advanced multi-round/timeline conflict resolved and verified on both client and server!"),r.textContent="\u2713 4.10B Check Success"}catch(e){u(`\u2717 4.10B Check FAILED: ${E(e)}`),console.error(e),r.disabled=!1}})}f(gd,"init4_10bCheckButton");function b6(){let r=`${be}[initDevTools]`;try{Tl(),Gl(),Al(),Cl(),vl(),Ol(),Nl(),xl(),Ll(),Dl(),Pl(),Rl(),kl(),Bl(),Ul(),Ml(),Fl(),jl(),Vl(),Hl(),Kl(),Xl(),ql(),Wl(),Yl(),zl(),Jl(),Zl(),Ql(),ed(),td(),rd(),od(),nd(),ad(),sd(),id(),cd(),fd(),bd(),pd(),hd(),ud(),gd()}catch(e){console.error(`${r} ${E(e)}`)}}f(b6,"initDevTools");export{f as a,ve as b,H as c,oe as d,Ke as e,U as f,K as g,Oe as h,E as i,Xn as j,nt as k,$o as l,vd as m,zs as n,Lr as o,re as p,q,Ne as r,St as s,Zs as t,y as u,ne as v,Yt as w,Ee as x,zn as y,$e as z,ue as A,Pe as B,at as C,Xe as D,ge as E,Pr as F,Rr as G,Dr as H,F as I,Kp as J,Xp as K,qp as L,Ao as M,Ld as N,oi as O,ni as P,lh as Q,dh as R,fh as S,Dd as T,bh as U,ta as V,sa as W,Pd as X,$h as Y,Co as Z,mr as _,ui as $,yi as aa,vo as ba,Bd as ca,Ud as da,Uu as ea,Mu as fa,Fu as ga,ju as ha,Vu as ia,Hu as ja,Kd as ka,Xd as la,Ai as ma,ma as na,Wd as oa,Yd as pa,Br as qa,eo as ra,Li as sa,nf as ta,Ri as ua,Ng as va,Dg as wa,te as xa,qe as ya,_a as za,Ie as Aa,af as Ba,Mo as Ca,Fo as Da,je as Ea,Aa as Fa,Bi as Ga,xe as Ha,kr as Ia,oo as Ja,Fi as Ka,Gt as La,Uo as Ma,cf as Na,lf as Oa,Ht as Pa,im as Qa,df as Ra,ff as Sa,bf as Ta,We as Ua,pf as Va,hf as Wa,uf as Xa,mt as Ya,Im as Za,ec as _a,to as $a,vt as ab,bt as bb,tc as cb,de as db,Ye as eb,er as fb,xm as gb,$f as hb,Lm as ib,Dm as jb,Pm as kb,Rm as lb,so as mb,Cm as nb,Qm as ob,eE as pb,tE as qb,rE as rb,oE as sb,Ur as tb,Sf as ub,_f as vb,Af as wb,wr as xb,V as yb,Tf as zb,uc as Ab,hc as Bb,Cf as Cb,vf as Db,Of as Eb,Nf as Fb,xf as Gb,Lf as Hb,Df as Ib,Pf as Jb,Ua as Kb,Ra as Lb,Ko as Mb,Rf as Nb,kf as Ob,oc as Pb,Bf as Qb,Ec as Rb,Uf as Sb,Mf as Tb,zE as Ub,Ha as Vb,Ka as Wb,xt as Xb,se as Yb,Sl as Zb,Tr as _b,_b as $b,vs as ac,dr as bc,Is as cc,Z as dc,fb as ec,_r as fc,Ar as gc,is as hc,or as ic,Nn as jc,Y4 as kc,u as lc,b6 as mc};
42
+ //# sourceMappingURL=chunk-ANGVYAEK.mjs.map