cleaker
Version:
Who am I here.
5 lines (4 loc) • 33.6 kB
JavaScript
(function(M,q){typeof exports=="object"&&typeof module<"u"?q(exports):typeof define=="function"&&define.amd?define(["exports"],q):(M=typeof globalThis<"u"?globalThis:M||self,q(M.Cleaker={}))})(this,(function(M){"use strict";class q extends Error{constructor(t,n,r){super(n),this.name="CleakerError",this.code=t,this.details=r}}class g extends q{constructor(t,n){super("PARSE_TARGET_FAILED",t,n),this.name="CleakerParseError"}}const G="me://",z="[",B="]",lt="|",ut=";",At=",";function ee(e){const t=String(e??"").trim();if(!t)throw new g("Target cannot be empty");return t}function ne(e){return e.startsWith(G)?e.slice(G.length):e}function ft(e,t,n=0){let r=0;for(let o=n;o<e.length;o+=1){const c=e[o];if(c===z){r+=1;continue}if(c===B){r=Math.max(0,r-1);continue}if(r===0&&c===t)return o}return-1}function re(e){let t=0;for(const n of e)if(n===z&&(t+=1),n===B&&(t-=1),t<0)throw new g("Target has an unexpected closing context bracket",{raw:e});if(t!==0)throw new g("Target has an unclosed context bracket",{raw:e})}function oe(e,t,n){const r=[];for(const o of e)for(const c of n)r.push([...o,{key:t,value:c,raw:`${t}:${c}`}]);return r}function se(e){const t=String(e??"").trim();if(!t)return[];const n=t.split(lt).map(o=>o.trim()).filter(Boolean),r=[];for(const o of n){const c=o.split(ut).map(y=>y.trim()).filter(Boolean);let h=[[]];for(const y of c){const S=y.indexOf(":");if(S<0)throw new g("Context atoms must match key:value",{raw:y});const A=y.slice(0,S).trim().toLowerCase(),b=y.slice(S+1).trim();if(!A||!b)throw new g("Context atoms must match key:value",{raw:y});const R=b.split(At).map(C=>C.trim()).filter(Boolean);if(R.length===0)throw new g("Context atoms must include at least one value",{raw:y});h=oe(h,A,R)}r.push(...h)}return r}function ie(e){const t=String(e||"").trim();if(!t)throw new g("Namespace cannot be empty",{raw:e});const n=t.indexOf(z);if(n<0)return{base:t,contextRaw:null,context:[]};const r=t.lastIndexOf(B);if(r!==t.length-1||r<n)throw new g("Namespace context must appear at the end of the namespace",{raw:e});const o=t.slice(0,n).trim(),c=t.slice(n+1,r).trim();if(!o)throw new g("Namespace cannot be empty",{raw:e});return{base:o,contextRaw:c,context:se(c)}}function ae(e){const t=e.split("/").map(h=>h.trim()).filter(Boolean),r=(t[0]||e).split(".").filter(Boolean);if(r.length===0)throw new g("Namespace is missing constant",{raw:e});const o=r[r.length-1],c=r.length>1?r.slice(0,-1).join("."):null;return{segments:t,constant:o,prefix:c}}function ce(e){return!Array.isArray(e)||e.length===0?null:e.map(t=>t.map(n=>`${n.key}:${n.value}`).join(ut)).join(lt)}function le(e){const t=String(e.namespace.fqdn||"").trim();if(!t)throw new g("Namespace cannot be empty");const n=String(e.operation||"").trim();if(!n)throw new g("Operation cannot be empty");const r=String(e.path||"").trim().replace(/^\/+/,"");if(!r)throw new g("Path cannot be empty");const o=ce(e.namespace.context),c=o?`${t}[${o}]`:t;return`${G}${c}:${n}/${r}`}function ue(e,t={}){const n=ee(e);re(n);const r=ne(n).replace(/^\/+/,"").trim();if(!r)throw new g("Target cannot be empty");const o=ft(r,":"),c=o<0;if(c&&!t.allowShorthandRead)throw new g("Target must match namespace[context]:operation/path",{raw:n});const h=c?ft(r,"/"):ft(r,"/",o+1);if(h<0)throw new g("Path cannot be empty",{raw:n});const y=r.slice(0,c?h:o).trim(),S=c?"read":r.slice(o+1,h).trim(),A=r.slice(h+1).trim().replace(/^\/+/,"");if(!y)throw new g("Namespace cannot be empty",{raw:n});if(!S)throw new g("Operation cannot be empty",{raw:n});if(!A)throw new g("Path cannot be empty",{raw:n});const b=ie(y),R=ae(b.base.toLowerCase()),C={scheme:"me",raw:"",namespace:{prefix:R.prefix,constant:R.constant,fqdn:b.base,segments:R.segments,contextRaw:b.contextRaw,context:b.context},intent:{selector:S,path:A,mode:t.defaultMode??"reactive"},operation:S,path:A};return C.raw=le(C),C}function J(e,t={}){return ue(e,t)}const fe="https://cleaker.me",pe="http://localhost",Ct=8161,pt=fe,de=pe;function vt(e,t={}){const n={kind:"remote",target:e,identity:{constant:e.namespace.constant,prefix:e.namespace.prefix},intent:{selector:e.intent.selector,path:e.intent.path,mode:e.intent.mode},resolution:{status:"unresolved",namespaceRecordVerified:!1,sessionToken:null,lastError:null},operationalState:{latencyMs:null,lastSync:null,cacheTtl:t.cacheTtl??300,stale:!1},transport:{preferred:t.preferredTransport??["quic","https"],protocol:null,resolvedEndpoint:null}};async function r(o={}){const c=e.namespace.prefix===null&&(e.namespace.constant==="local"||e.namespace.constant==="self"),h=String(o.origin||pt).replace(/\/+$/,""),y=String(e.intent.path||"").trim().replace(/^\/+/,""),S=`${h}/${y}`,A=Date.now();if(n.resolution.status="resolving",n.resolution.lastError=null,n.transport.protocol=c?"local":h.startsWith("https://")?"https":"http",n.transport.resolvedEndpoint=c?e.raw:S,c&&t.resolveLocalTarget)try{const E=await t.resolveLocalTarget(e),v=Date.now()-A;return n.operationalState.latencyMs=v,n.operationalState.lastSync=Date.now(),n.resolution.status="connected",n.resolution.namespaceRecordVerified=!0,n.operationalState.stale=!1,{ok:!0,status:200,endpoint:e.raw,elapsedMs:v,data:{ok:!0,namespace:e.namespace.constant,path:e.intent.path,value:E}}}catch(E){const v=Date.now()-A;return n.operationalState.latencyMs=v,n.operationalState.lastSync=Date.now(),n.resolution.status="error",n.resolution.lastError=E instanceof Error?E.message:String(E),n.operationalState.stale=!1,{ok:!1,status:500,endpoint:e.raw,elapsedMs:v,data:{ok:!1,error:n.resolution.lastError}}}const b=o.fetcher||fetch,R=String(o.host||e.namespace.fqdn||"").trim(),C={...o.headers||{}};R&&!C.host&&!C.Host&&(C.host=R);try{const E=await b(S,{method:"GET",headers:C});let v=null;try{v=await E.json()}catch{v=await E.text()}const _=Date.now()-A;return n.operationalState.latencyMs=_,n.operationalState.lastSync=Date.now(),E.ok?(n.resolution.status="connected",n.resolution.namespaceRecordVerified=!0,n.operationalState.stale=!1):(n.resolution.status=E.status===401||E.status===403?"unauthorized":"error",n.resolution.lastError=`HTTP_${E.status}`),{ok:E.ok,status:E.status,endpoint:S,elapsedMs:_,data:v}}catch(E){const v=Date.now()-A;return n.operationalState.latencyMs=v,n.operationalState.lastSync=Date.now(),n.resolution.status="timeout",n.resolution.lastError=E instanceof Error?E.message:String(E),n.operationalState.stale=!0,{ok:!1,status:0,endpoint:S,elapsedMs:v,data:{ok:!1,error:n.resolution.lastError}}}}return{__ptr:n,resolve:r}}function me(e){const t=String(e??"").trim();if(!t)throw new g("Namespace cannot be empty");return t}function he(e){return e.startsWith(G)?e.slice(G.length):e}function ye(e){let t=0;for(const n of e)if(n===z&&(t+=1),n===B&&(t-=1),t<0)throw new g("Namespace has an unexpected closing context bracket",{raw:e});if(t!==0)throw new g("Namespace has an unclosed context bracket",{raw:e})}function Ot(e,t,n=0){let r=0;for(let o=n;o<e.length;o+=1){const c=e[o];if(c===z){r+=1;continue}if(c===B){r=Math.max(0,r-1);continue}if(r===0&&c===t)return o}return-1}function ge(e,t,n){const r=[];for(const o of e)for(const c of n)r.push([...o,{key:t,value:c,raw:`${t}:${c}`}]);return r}function we(e){const t=String(e??"").trim();if(!t)return[];const n=t.split(lt).map(o=>o.trim()).filter(Boolean),r=[];for(const o of n){const c=o.split(ut).map(y=>y.trim()).filter(Boolean);let h=[[]];for(const y of c){const S=y.indexOf(":");if(S<0)throw new g("Namespace selectors must match key:value",{raw:y});const A=y.slice(0,S).trim().toLowerCase(),b=y.slice(S+1).trim();if(!A||!b)throw new g("Namespace selectors must match key:value",{raw:y});const R=b.split(At).map(C=>C.trim()).filter(Boolean);if(R.length===0)throw new g("Namespace selectors must include at least one value",{raw:y});h=ge(h,A,R)}r.push(...h)}return r}function Se(e){const t=String(e||"").trim();if(!t)throw new g("Namespace cannot be empty",{raw:e});const n=t.indexOf(z);if(n<0)return{base:t,contextRaw:null,context:[]};const r=t.lastIndexOf(B);if(r!==t.length-1||r<n)throw new g("Namespace context must appear at the end of the namespace",{raw:e});const o=t.slice(0,n).trim(),c=t.slice(n+1,r).trim();if(!o)throw new g("Namespace cannot be empty",{raw:e});return{base:o,contextRaw:c,context:we(c)}}function xt(e){const t=String(e||"").trim().replace(/^https?:\/\//i,"");if(!t)throw new g("Namespace base cannot be empty",{raw:e});const n=t.indexOf("/"),r=(n>=0?t.slice(0,n):t).trim().toLowerCase(),o=r.match(/:(\d+)$/),c=o?Number(o[1]):null,h=o?r.slice(0,-o[0].length):r,y=h.split(".").map(S=>S.trim()).filter(Boolean);if(!h||y.length===0)throw new g("Namespace base cannot be empty",{raw:e});return{host:h,labels:y,port:c}}function Ee(e){const t=xt(e),n=t.port==null?"":`:${t.port}`;return t.labels.length===2&&t.labels[1]==="localhost"?{fqdn:`${t.host}${n}`,prefix:t.labels[0]||null,constant:`localhost${n}`,labels:t.labels,port:t.port}:t.labels.length<=2?{fqdn:`${t.host}${n}`,prefix:null,constant:`${t.host}${n}`,labels:t.labels,port:t.port}:{fqdn:`${t.host}${n}`,prefix:t.labels[0]||null,constant:`${t.labels.slice(1).join(".")}${n}`,labels:t.labels,port:t.port}}function be(e){const t=String(e||"").trim().toLowerCase();return/^(localhost|127(?:\.\d{1,3}){3}|0\.0\.0\.0)$/.test(t)||/\.local$/.test(t)}function Q(e,t){const n=String(t||"").trim().toLowerCase();if(!n)return null;for(const r of e)for(const o of r)if(o.key===n)return o.value;return null}function Re(e,t){const n=xt(e),r=Q(t,"host")||Q(t,"hostname")||Q(t,"device"),o=Q(t,"protocol"),c=Q(t,"port"),h=String(r||n.host).trim().toLowerCase(),y=/:\d+$/.test(h),S=y?h.replace(/:\d+$/,""):h,b=(y&&Number(h.match(/:(\d+)$/)?.[1]||0)||null)??(c&&/^\d+$/.test(c)?Number(c):n.port),R=(o||(be(S)?"http":"https")).toLowerCase()==="http"?"http":"https",C=b==null?S:`${S}:${b}`,E=`${R}://${C}`;return{protocol:R,host:S,port:b,origin:E}}function Ae(e){const t=Ot(e,"/");return t<0?{head:e.trim(),path:""}:{head:e.slice(0,t).trim(),path:e.slice(t+1).trim().replace(/^\/+/,"")}}function Ce(e){const t=Ot(e,":");if(t<0)return{namespaceToken:e.trim(),operation:null};const n=e.slice(t+1).trim();return!n||/^\d+$/.test(n)?{namespaceToken:e.trim(),operation:null}:{namespaceToken:e.slice(0,t).trim(),operation:n}}function dt(e,t){const n=String(t||"").trim().toLowerCase();if(!n)throw new g("Namespace constant cannot be empty",{constant:t});const r=String(e||"").trim().toLowerCase().replace(/\.+$/,"");return r?`${r}.${n}`:n}function Nt(e){const t=String(e.fqdn||"").trim().toLowerCase();if(!t)throw new g("Namespace base cannot be empty",{input:e});const n=String(e.contextRaw||"").trim(),r=String(e.operation||"").trim(),o=String(e.path||"").trim().replace(/^\/+/,""),c=n?`${t}[${n}]`:t,h=r?`:${r}`:"",y=o?`/${o}`:"";return`${c}${h}${y}`}function K(e){const t=me(e);ye(t);const n=he(t).replace(/^\/+/,"").trim();if(!n)throw new g("Namespace cannot be empty",{raw:t});const r=Ae(n),o=Ce(r.head),c=Se(o.namespaceToken),h=Ee(c.base),y=Re(c.base,c.context),S=Nt({fqdn:h.fqdn,contextRaw:c.contextRaw,operation:o.operation,path:r.path});return{raw:t,expression:S,base:c.base,fqdn:h.fqdn,prefix:h.prefix,constant:h.constant,labels:h.labels,contextRaw:c.contextRaw,context:c.context,operation:o.operation,path:r.path,transport:y}}const ve=Symbol.for("me.expression"),Oe=Symbol.for("me.identity");function xe(e){if(!e||typeof e!="object")return e;const t=e,n=t.payload,o={...n&&typeof n=="object"?n:t};if(!Object.prototype.hasOwnProperty.call(o,"path")){const c=String(o.expression||"").trim();c&&(o.path=c)}return Object.prototype.hasOwnProperty.call(o,"operator")||(o.operator=null),Object.prototype.hasOwnProperty.call(o,"value")&&(o.expression=o.value),!Object.prototype.hasOwnProperty.call(o,"timestamp")&&t.timestamp!==void 0&&(o.timestamp=t.timestamp),!Object.prototype.hasOwnProperty.call(o,"identityHash")&&t.identityHash!==void 0&&(o.identityHash=t.identityHash),o}function mt(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(r=>mt(r)).join(",")}]`;const t=e;return`{${Object.keys(t).sort().map(r=>`${JSON.stringify(r)}:${mt(t[r])}`).join(",")}}`}function Z(e){return String(e||"").trim().toLowerCase().replace(/:\d+$/i,"")}function W(e){const t=String(e||"").trim();if(!t)return"";const n=t.includes("://")?t:`${D(t)?"http":"https"}://${t}`;try{const r=new URL(n.endsWith("/")?n:`${n}/`),o=r.protocol.toLowerCase(),c=String(r.hostname||"").trim().toLowerCase();return!o||!c?"":`${o}//${c}`}catch{const r=Z(t.replace(/^https?:\/\//i,"").split("/")[0]||"");return r?`${D(r)?"http":"https"}://${r}`:""}}function ht(e){return/^\d{1,3}(\.\d{1,3}){3}$/.test(e)}function Tt(e){return!e.includes(".")&&!ht(e)}function _t(e){const t=e.lastIndexOf(":");if(t>0){const n=e.slice(t+1),r=parseInt(n,10);if(String(r)===n&&r>0)return{host:e.slice(0,t),port:r}}return{host:e,port:null}}function tt(e){const t=String(e||"").trim();if(!t)return"";if(t.includes("://"))return k(t);const{host:n,port:r}=_t(t),o=n.toLowerCase();if(ht(o))return`http://${o}:${r??Ct}`;if(Tt(o))return`http://${o}.local:${r??Ct}`;const c=r?`:${r}`:"";return`https://${o}${c}`}function Ne(e){const t=String(e||"").trim();if(!t)return"";if(t.includes("://"))try{return new URL(t).hostname.toLowerCase()}catch{return""}const{host:n}=_t(t),r=n.toLowerCase();return ht(r)?r:Tt(r)?`${r}.local`:r}function Te(e){const t=e??{},n=String(t.hash||"").trim();return n?`h:${n}`:`v:${Number(t.timestamp||0)}:${mt(e)}`}function k(e){const t=String(e||"").trim();if(!t)return"";const n=t.includes("://")?t:`http://${t}`;try{return new URL(n.endsWith("/")?n:`${n}/`).origin.toLowerCase()}catch{return t.replace(/\/+$/,"").toLowerCase()}}function yt(e){return(typeof e=="string"?e.trim():"")||null}function L(e){return(typeof e=="string"?e.trim():"")||null}function $t(e,t=""){if(typeof e=="string"){const n=e.trim();if(n)return n}if(e&&typeof e=="object"){const n=e,r=typeof n.me=="string"?n.me.trim():"";if(r)return r;const o=typeof n.host=="string"?n.host.trim():"";if(o)return o}return t}function et(e,t=""){if(!e||typeof e!="object")return t;const n=e,r=$t(n.namespace,"");if(r)return r;const o=n.target;return o&&typeof o=="object"?$t(o.namespace,t):t}function _e(e){try{const t=yt(e[ve]);if(t)return t}catch{}try{const n=e["!"]?.currentExpression;if(typeof n=="function"){const r=yt(n());if(r)return r}if(n&&typeof n=="object"&&typeof n.call=="function"){const r=yt(n.call());if(r)return r}}catch{}return null}function $e(e){try{const t=e[Oe];if(t&&typeof t=="object"){const r=L(t.hash);if(r)return r}const n=L(t);if(n)return n}catch{}try{const n=e["!"]?.identity;if(typeof n=="function"){const r=n();if(r&&typeof r=="object"){const c=L(r.hash);if(c)return c}const o=L(r);if(o)return o}if(n&&typeof n=="object"&&typeof n.call=="function"){const r=n.call();if(r&&typeof r=="object"){const c=L(r.hash);if(c)return c}const o=L(r);if(o)return o}}catch{}return null}function ke(e,t){try{const r=e["!"]?.[t];if(typeof r=="function")return r;if(r&&typeof r=="object"&&typeof r.call=="function")return((...o)=>r.call(...o))}catch{}try{const n=e[t];if(typeof n=="function")return n.bind(e)}catch{}return null}function Le(e){const t=String(e||"").trim();if(!t)return"";try{return K(t).constant}catch{const n=t.split(".").map(r=>r.trim()).filter(Boolean);return n.length>1?n.slice(1).join("."):t}}async function Ie(e,t){const n=ke(e,"prove");if(!n)throw new Error("PROVE_UNSUPPORTED");const r=Le(t);if(!r)throw new Error("ROOT_NAMESPACE_REQUIRED");const o=await n({rootNamespace:r,challenge:null});if(!o||typeof o!="object")throw new Error("PROOF_INVALID");const c=String(o.namespace||"").trim();if(!c)throw new Error("PROOF_INVALID");if(c!==t)throw new Error("PROOF_NAMESPACE_MISMATCH");return o}function D(e){const t=Z(e);return/^(localhost|127(?:\.\d{1,3}){3}|0\.0\.0\.0)$/.test(t)}function nt(e){try{const t=new URL(e).hostname.toLowerCase();return D(t)||t.endsWith(".local")||/^192\.168\./.test(t)||/^10\./.test(t)||/^172\.(1[6-9]|2\d|3[01])\./.test(t)}catch{return!1}}function Me(){if(typeof globalThis>"u")return"";const e=globalThis.location;if(!e)return"";if(typeof e=="string")try{const o=new URL(e.includes("://")?e:`https://${e}`).hostname.toLowerCase();return D(o)?"":o}catch{const o=Z(String(e).trim().toLowerCase());return D(o)?"":o}const t=e,n=Z(String(t.hostname||t.host||"").trim().toLowerCase());if(D(n))return"";if(n)return n;const r=String(t.origin||t.href||"").trim();if(!r)return"";try{const o=new URL(r.includes("://")?r:`https://${r}`).hostname.toLowerCase();return D(o)?"":o}catch{return""}}function Pe(){if(typeof globalThis>"u")return"";const e=globalThis.location;if(!e)return"";if(typeof e=="string")return W(e);const t=e,n=W(String(t.origin||""));if(n)return n;const r=String(t.href||"").trim();if(r)return W(r);const o=String(t.hostname||t.host||"").trim().toLowerCase();return o?W(o):""}function kt(e){const t=rt(e);return t?W(t):""}function He(){if(typeof process>"u")return"";const e=String(process.env.CLEAKER_SURFACE_HOST||process.env.MONAD_SELF_IDENTITY||process.env.CLEAKER_NAMESPACE_ROOT||process.env.CLEAKER_NAMESPACE_HOST||process.env.HOSTNAME||process.env.COMPUTERNAME||"").trim(),t=kt(e);if(t)return t;const n=process;if(typeof n.getBuiltinModule!="function")return"";try{const r=n.getBuiltinModule("node:os"),o=String(r?.hostname?.()||"").trim();return o?W(o):""}catch{return""}}function rt(e){const t=String(e||"").trim();if(!t)return"";if(/^https?:\/\//i.test(t))try{return K(new URL(t).hostname).constant}catch{return""}try{return K(t).constant}catch{try{const n=new URL(t.includes("://")?t:`https://${t}`);return K(n.hostname).constant}catch{return""}}}function De(e){const t=new Set,n=[];for(const r of e){const o=k(String(r||""));!o||t.has(o)||(t.add(o),n.push(o))}return n}function je(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return("00000000"+(t>>>0).toString(16)).slice(-8)}function Ue(e){return je(k(e))}function Fe(e,t){if(t.length)try{let n=e;for(let r=0;r<t.length;r+=1)if(n=n?.[t[r]],n==null)return;if(typeof n=="function")try{return n()}catch{return}return n}catch{return}}function T(e,t,n){if(!t.length)return!1;try{let r=e;for(let o=0;o<t.length;o+=1)if(r=r?.[t[o]],r==null)return!1;if(typeof r=="function")return r(n),!0}catch{return!1}return!1}function Lt(e,t){const n=k(String(e.space||""));if(!n)return null;const r=String(e.id||"").trim()||Ue(n),o=e.status||{transport:"unknown",triad:"unverified",latencyMs:0,lastSeen:0},c=e.capabilities||{canClaim:!1,canOpen:!0,canRelay:!1};return{id:r,alias:e.alias?String(e.alias):void 0,space:n,namespace:t,status:{transport:o.transport||"unknown",triad:o.triad||"unverified",latencyMs:Number(o.latencyMs||0),lastSeen:Number(o.lastSeen||0)},capabilities:{canClaim:!!c.canClaim,canOpen:c.canOpen!==!1,canRelay:!!c.canRelay},error:e.error?String(e.error):void 0}}function ze(e){const t=e.join(".").trim();return t.includes(".cleaker:")||t.includes(":")?!0:e.some((n,r)=>{const o=n.toLowerCase();return o.includes("cleaker:")||o.includes(":")||o==="cleaker"&&r<e.length-1})}function Be(e){const t=e.map(o=>String(o||"").trim()).filter(Boolean);if(t.length===0)return null;const n=t.join(".");if(n.includes(":"))return n;const r=t.findIndex(o=>o.toLowerCase()==="cleaker");if(r>0&&r<t.length-1){const o=t[r-1],c=t.slice(r+1).join(".");return`${o}.cleaker:read/${c||"profile"}`}return null}function It(e){if(!e||typeof e!="object")return e;const t=e;return Object.prototype.hasOwnProperty.call(t,"value")?t.value:e}function ot(e,t){if(!(t.length===0||typeof e!="function"))try{return e(t.join("."))}catch{return}}function Ke(e,t,n){if(typeof e=="function")try{if(t.length===0)return e(...n);let r=e;for(const o of t)r=r?.[o];if(typeof r=="function")return r(...n)}catch{return}}function We(e,t={}){const n=new Set,r=[],o=new Map,c=new Map,h=new Map,y=String(t.namespace||"").trim(),S=String(t.secret||""),A=L(t.identityHash),b=Array.isArray(t.bootstrap)?t.bootstrap.map(s=>k(s)).filter(Boolean):[],R=t.space?tt(t.space):"",C={...R?{origin:R}:{},...t.fetcher?{fetcher:t.fetcher}:{},headers:{accept:"application/json"}};let E="idle",v=0,_={cycleId:0,state:"idle",overall:b.length?"degraded":"offline",activeNamespace:V(),totalHosts:0,verifiedHosts:0,hosts:[]},gt=null,Mt=Promise.resolve(null);function qe(){if(t.space){const a=Ne(t.space);if(a)return a}const s=Me();if(s)return rt(s);const i=typeof process<"u"?String(process.env.CLEAKER_NAMESPACE_ROOT||process.env.CLEAKER_NAMESPACE_HOST||""):"";return rt(i||pt)}function V(s){const i=String(s||y||"").trim();if(i)return i;const a=_e(e);if(!a)return"";if(a.includes("."))try{const l=K(a);if(l.prefix&&l.constant)return dt(l.prefix,l.constant)}catch{}const p=qe();return p?dt(a,p):""}function wt(s=[],i=""){const a=t.space?tt(t.space):"",p=Pe(),l=typeof process<"u"?String(process.env.CLEAKER_NAMESPACE_ROOT||process.env.CLEAKER_NAMESPACE_HOST||""):"",m=kt(l||""),d=He();return De([i,a,...b,...s,p,m,d,pt,de])}function Pt(s){return L(s)||A||$e(e)||""}function Ge(s){const i=String(s||"").trim().replace(/^\/+/,"").replace(/\//g,".");if(i)return ot(e,i.split(".").filter(Boolean))}function Ht(s){const i=String(s||"").trim();return i?i.startsWith("me://")||i.includes(":"):!1}function Dt(s){if(!Ht(s))return null;try{const i=J(s,{defaultMode:"reactive",allowShorthandRead:!0});return String(i.path||"").trim().replace(/^\/+/,"").split("/").map(a=>a.trim()).filter(Boolean)}catch{return null}}function I(s,...i){const a=h.get(s);!a||a.size===0||a.forEach(p=>{try{p(...i)}catch{}})}function jt(s,i){const a=h.get(s)||new Set;return a.add(i),h.set(s,a),()=>Ut(s,i)}function Ut(s,i){const a=h.get(s);a&&(a.delete(i),a.size===0&&h.delete(s))}function Ft(s,i){const a=jt(s,((...p)=>{a(),i(...p)}));return a}function j(s,i){E=s,_={..._,cycleId:i,state:s},I("status:change",P())}function X(s,i){const a=["namespaces",s,"registry","hosts",i.id];T(e,[...a,"id"],i.id),T(e,[...a,"alias"],i.alias||""),T(e,[...a,"space"],i.space),T(e,[...a,"namespace"],i.namespace),T(e,[...a,"status","transport"],i.status.transport),T(e,[...a,"status","triad"],i.status.triad),T(e,[...a,"status","latencyMs"],i.status.latencyMs),T(e,[...a,"status","lastSeen"],i.status.lastSeen),T(e,[...a,"capabilities","canClaim"],i.capabilities.canClaim),T(e,[...a,"capabilities","canOpen"],i.capabilities.canOpen),T(e,[...a,"capabilities","canRelay"],i.capabilities.canRelay),T(e,[...a,"error"],i.error||"")}function St(s={}){const i=V(s.namespace);if(!i)return[];const a=new Map,p=Fe(e,["namespaces",i,"registry","hosts"]);if(p&&typeof p=="object"&&!Array.isArray(p)){const l=p;Object.keys(l).forEach(m=>{const d=l[m],u=Lt({...d,id:d?.id||m},i);u&&a.set(u.id,u)})}if(a.size===0){const l=Array.isArray(s.bootstrap)?s.bootstrap.map(d=>k(d)).filter(Boolean):[];wt(l).forEach(d=>{const u=Lt({space:d},i);u&&(a.set(u.id,u),X(i,u))})}return Array.from(a.values())}async function Qe(s,i,a){const p=typeof AbortController<"u"?new AbortController:null,l=p?setTimeout(()=>p.abort(),i):null;try{return(await a(`${k(s)}/__bootstrap`,{method:"GET",cache:"no-store",signal:p?.signal})).ok}catch{return!1}finally{l&&clearTimeout(l)}}async function st(s,i,a,p,l={}){const m=typeof AbortController<"u"?new AbortController:null,d=m?setTimeout(()=>m.abort(),a):null;try{const u=await p(s,{method:"POST",headers:{"content-type":"application/json",...l},body:JSON.stringify(i),signal:m?.signal});let f=null;try{f=await u.json()}catch{f=null}return!u.ok||!f?.ok?{ok:!1,status:u.status,data:f,error:String(f?.error||`REQUEST_FAILED_${u.status}`)}:{ok:!0,status:u.status,data:f}}catch(u){return{ok:!1,status:0,data:null,error:(u instanceof Error?u.name:String(u))==="AbortError"?"TIMEOUT":"NETWORK_ERROR"}}finally{d&&clearTimeout(d)}}function zt(s,i,a){return{ok:!0,namespace:et(s,i),identityHash:L(s.identityHash)||a,noise:String(s.noise||""),memories:Array.isArray(s.memories)?s.memories:[],openedAt:Number(s.openedAt||Date.now()),target:s.target&&typeof s.target=="object"?s.target:void 0}}function Bt(s,i,a){return{ok:!0,namespace:et(s,i),identityHash:L(s.identityHash)||a,publicKey:typeof s.publicKey=="string"?s.publicKey:void 0,createdAt:Number(s.createdAt||Date.now()),persistentClaim:s.persistentClaim,target:s.target&&typeof s.target=="object"?s.target:void 0}}async function Kt(s,i,a,p,l,m,d={}){const u={namespace:i,secret:a,...p?{identityHash:p}:{}},f=await st(`${k(s)}/claims/signIn`,u,l,m,d);if(f.ok&&f.data)return zt(f.data,i,p);const O=String(f.error||"OPEN_FAILED");if(O==="CLAIM_NOT_FOUND")return{ok:!1,error:O};if(f.status===404){const $=await st(`${k(s)}/`,{operation:"open",...u},l,m,{"x-forwarded-host":i,...d});return $.ok&&$.data?zt($.data,i,p):{ok:!1,error:String($.error||O)}}return{ok:!1,error:O}}async function Wt(s,i,a,p,l,m={}){let d;try{d=await Ie(e,i)}catch(f){return{ok:!1,error:f instanceof Error?f.message:"PROOF_INVALID"}}const u=await st(`${k(s)}/me/kernel:claim/${encodeURIComponent(i)}`,{namespace:i,secret:a,proof:d},p,l,m);if(u.ok&&u.data)return Bt(u.data,i,d.identityHash);if(u.status===404||u.status===405){const f=await st(`${k(s)}/`,{operation:"claim",namespace:i,secret:a,proof:d},p,l,{"x-forwarded-host":i,...m});return f.ok&&f.data?Bt(f.data,i,d.identityHash):{ok:!1,error:String(f.error||u.error||"CLAIM_FAILED")}}return{ok:!1,error:String(u.error||"CLAIM_FAILED")}}async function Vt(s,i,a,p,l,m,d={}){const u=await Kt(s,i,a,p,l,m,d);if(u.ok||u.error!=="CLAIM_NOT_FOUND")return u;const f=await Wt(s,i,a,l,m,d);if(!f.ok)return{ok:!1,error:String(f.error||"CLAIM_FAILED")};const O=L(f.identityHash)||p;return Kt(s,et(f,i),a,O,l,m,d)}function P(){return{..._,hosts:_.hosts.map(s=>({...s,status:{...s.status},capabilities:{...s.capabilities}}))}}async function Xe(s=1e4){return E==="ready"&>?gt:await new Promise((i,a)=>{const p=setTimeout(()=>{l(),a(new Error("TIMEOUT_WAITING_FOR_READY"))},s),l=Ft("ready",m=>{clearTimeout(p),i(m)})})}async function Ye(s={}){const i=V(s.namespace),a=String(s.secret!==void 0?s.secret:S),p=Pt(s.identityHash),l=s.triadStrategy||"first-success",m=Number(s.timeoutMs||5e3),d=t.fetcher||fetch,u=++v;if(!i)return I("error",{code:"NAMESPACE_REQUIRED",message:"Cannot validate hosts without namespace."}),j("offline",u),_={..._,cycleId:u,state:"offline",overall:"offline",activeNamespace:i,totalHosts:0,verifiedHosts:0,hosts:[]},I("status:change",P()),P();j("discovering",u);const f=St({namespace:i,bootstrap:s.bootstrap});if(!f.length)return j("offline",u),_={..._,cycleId:u,state:"offline",overall:"offline",activeNamespace:i,totalHosts:0,verifiedHosts:0,hosts:[]},I("status:change",P()),P();j("probing",u);let O=null,$="",U="",Jt=0;const H=[];for(let N=0;N<f.length;N+=1){const w=f[N],at=Date.now(),ct=await Qe(w.space,m,d);if(w.status.transport=ct?"up":"down",w.status.latencyMs=Date.now()-at,w.status.lastSeen=Date.now(),!ct){w.status.triad="unverified",w.error="NETWORK_ERROR",X(i,w),H.push({origin:w.space,reason:"NETWORK_ERROR"});const x=f[N+1];x&&!nt(w.space)&&nt(x.space)&&I("namespace:fallback",{namespace:i,failedOrigin:w.space,failedReason:"NETWORK_ERROR",fallbackOrigin:x.space});continue}if(!a){w.status.triad="unverified",w.error="SECRET_REQUIRED",X(i,w),H.push({origin:w.space,reason:"SECRET_REQUIRED"});continue}j("opening",u);const F=await Vt(w.space,i,a,p,m,d);if(!F.ok){const x=String(F.error||"OPEN_FAILED");w.status.triad=x==="CLAIM_NOT_FOUND"?"unverified":"failed",w.error=x,I("error",{code:x,message:`Triad open failed on ${w.space}`,hostId:w.id}),X(i,w),H.push({origin:w.space,reason:x});const Rt=f[N+1];Rt&&!nt(w.space)&&nt(Rt.space)&&I("namespace:fallback",{namespace:i,failedOrigin:w.space,failedReason:x,fallbackOrigin:Rt.space});continue}w.status.triad="verified",w.error=void 0,X(i,w),I("host:triad:success",w.id),O||(O=w),j("hydrating",u);const tn=Array.isArray(F.memories)?F.memories:[],en=n.size;if(tn.forEach(x=>{it(x)}),Jt+=Math.max(0,n.size-en),F.noise!==void 0&&(e.noise=String(F.noise||"")),$=w.id,U=String(F.identityHash||""),l==="first-success"){for(let x=N+1;x<f.length;x+=1)f[x].status.triad="skipped";break}}if(u!==v)return P();const Y=f.filter(N=>N.status.triad==="verified").length,Zt=Y>0?"healthy":"degraded";if(Y===0&&H.length>0){const N=H.map((at,ct)=>` [${ct+1}] ${at.origin} → ${at.reason}`),w=`namespace '${i}' failed to resolve. tried ${H.length} surface${H.length===1?"":"s"}:
`+N.join(`
`);I("namespace:failed",{namespace:i,tried:H,explain:w})}const te=Y>0?"ready":"degraded";if(j(te,u),_={cycleId:u,state:te,overall:Zt,activeNamespace:i,totalHosts:f.length,verifiedHosts:Y,hosts:f},I("status:change",P()),O){const N={namespace:i,cycleId:u,sourceHostId:$||O.id,sourceOrigin:O.space,identityHash:U,timestamp:Date.now(),hydratedMemories:Jt,summary:{verifiedHosts:Y,totalHosts:f.length,overall:Zt}};gt=N,I("ready",N)}return P()}function Et(s,i={}){const a=J(s,{defaultMode:"reactive"}),p=vt(a,{...t,resolveLocalTarget:l=>{if(l.namespace.prefix!==null)throw new Error("LOCAL_TARGET_PREFIX_NOT_ALLOWED");if(l.namespace.constant!=="local"&&l.namespace.constant!=="self")throw new Error("LOCAL_TARGET_REQUIRED");return Ge(l.intent.path)}});return Object.keys(i).length?{...p,resolve(l={}){return p.resolve({...i,...l})}}:p}function it(s){const i=xe(s),a=Te(i);return n.has(a)?!1:(n.add(a),r.push(i),typeof e.learn=="function"?(e.learn(i),!0):(typeof e.replayMemories=="function"&&e.replayMemories(r.slice()),!0))}function qt(s,i){const a=s.map(p=>String(p||"").trim()).filter(Boolean);return a.length===0?null:{path:a.join("."),operator:null,expression:i,value:i}}async function Gt(s){const i=V(s.namespace),a=String(s.secret||""),p=Pt(s.identityHash);if(!i)throw new Error("NAMESPACE_REQUIRED");if(!a)throw new Error("SECRET_REQUIRED");const l=s.fetcher||t.fetcher||fetch,m=wt([],s.space?tt(s.space):"");let d="SIGNIN_FAILED";for(const u of m){const f=await Vt(u,i,a,p,5e3,l,s.headers||{});if(!f.ok){d=String(f.error||"SIGNIN_FAILED");continue}const $=(Array.isArray(f.memories)?f.memories:[]).filter(U=>it(U));return e.noise=String(f.noise||""),{status:"verified",namespace:String(f.namespace||i),identityHash:String(f.identityHash||p||""),noise:String(f.noise||""),openedAt:Number(f.openedAt||Date.now()),memoriesCount:$.length}}throw new Error(d)}async function Je(s){const i=V(s.namespace),a=String(s.secret||"");if(!i)throw new Error("NAMESPACE_REQUIRED");if(!a)throw new Error("SECRET_REQUIRED");const p=s.fetcher||t.fetcher||fetch,l=wt([],s.space?tt(s.space):"");let m="CLAIM_FAILED";for(const d of l){const u=await Wt(d,i,a,5e3,p,s.headers||{});if(!u.ok){m=String(u.error||"CLAIM_FAILED");continue}return{status:"verified",namespace:String(et(u,i)),identityHash:String(u.identityHash||""),noise:"",openedAt:Number(u.createdAt||Date.now()),memoriesCount:0}}throw new Error(m)}V()&&St({namespace:y}),t.secret&&(Mt=Gt({namespace:y,secret:t.secret,identityHash:t.identityHash,space:t.space,fetcher:t.fetcher}).catch(()=>null));function Qt(s){if(!ze(s))return;const i=s.join("."),a=c.get(i);if(a)return a;const p=Be(s);if(!p)return;const l=Et(p),m={key:i,path:s.slice(),expression:p,pointer:l,promise:Promise.resolve({ok:!1,status:0,endpoint:"",elapsedMs:0,data:null})};return m.promise=l.resolve(C).then(d=>{if(m.lastResult=d,d.ok){const u=It(d.data);o.set(i,u);const f=qt(s,u);f&&it(f)}return d}),c.set(i,m),m}function Xt(s){const i=Dt(s);if(!i||i.length===0)return;const a=`target:${s}`,p=c.get(a);if(p)return p;const l=Et(s),m={key:a,path:i.slice(),expression:s,pointer:l,promise:Promise.resolve({ok:!1,status:0,endpoint:"",elapsedMs:0,data:null})};return m.promise=l.resolve(C).then(d=>{if(m.lastResult=d,d.ok){const u=It(d.data);o.set(a,u);const f=qt(i,u);f&&it(f)}return d}),c.set(a,m),m}function Yt(s){return{status:"pending",path:s.key,pointer:s.pointer,promise:s.promise}}function Ze(s){if(!(s in e))return;const i=e[s];return typeof i=="function"?i.bind(e):i}function bt(s=[]){const i=(...a)=>{if(s.length===0){if(typeof e=="function"){if(a.length===1&&typeof a[0]=="string"){const l=String(a[0]||"").trim(),m=Dt(l);if(m){const u=ot(e,m);if(u!==void 0)return u;const f=Xt(l);return f?Yt(f):void 0}const d=ot(e,l.split(".").filter(Boolean));if(d!==void 0)return d;if(Ht(l)){const u=Xt(l);return u?Yt(u):void 0}}return e(...a)}return}const p=Ke(e,s,a);return p!==void 0?p:bt(s)};return new Proxy(i,{get(a,p){if(typeof p=="symbol")return i[p];const l=String(p);if(s.length===0){if(l==="kernel")return e;if(l==="claim")return Je;if(l==="signIn")return Gt;if(l==="ready")return Mt;if(l==="pointer")return Et;if(l==="discoverHosts")return St;if(l==="validateHosts")return Ye;if(l==="getStatus")return P;if(l==="waitUntilReady")return Xe;if(l==="on")return jt;if(l==="once")return Ft;if(l==="off")return Ut;if(l==="state")return E;if(l==="currentCycleId")return v;const U=Ze(l);if(U!==void 0)return U}const m=s.join("."),d=o.get(m);if(d&&typeof d=="object"&&!Array.isArray(d)&&Object.prototype.hasOwnProperty.call(d,l))return d[l];const u=Qt(s);if(u){if(l==="status")return u.lastResult?u.pointer.__ptr.resolution.status:"pending";if(l==="pointer")return u.pointer;if(l==="promise")return u.promise;if(l==="result")return u.lastResult;if(l==="then")return u.promise.then.bind(u.promise)}const f=[...s,l],O=f.join(".");if(o.has(O))return o.get(O);const $=ot(e,f);return $!==void 0?$:(Qt(f),bt(f))},apply(a,p,l){return i(...l)}})}return bt([])}function Ve(e,t,n){if(typeof e=="string"){const c=J(e,{defaultMode:"reactive"});return vt(c,t??{})}let r,o;return typeof t=="string"?(r=t,o=n??{}):o=t??{},We(e,{...o,...r?{space:r}:{}})}M.composeNamespace=dt,M.default=Ve,M.parseNamespaceExpression=K,M.parseTarget=J,M.stringifyNamespaceExpression=Nt,Object.defineProperties(M,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
//# sourceMappingURL=cleaker.umd.js.map