UNPKG

cleaker

Version:
5 lines (4 loc) 33.4 kB
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});class ce extends Error{constructor(t,n,r){super(n),this.name="CleakerError",this.code=t,this.details=r}}class g extends ce{constructor(t,n){super("PARSE_TARGET_FAILED",t,n),this.name="CleakerParseError"}}const Q="me://",K="[",W="]",wt="|",St=";",Wt=",";function le(e){const t=String(e??"").trim();if(!t)throw new g("Target cannot be empty");return t}function ue(e){return e.startsWith(Q)?e.slice(Q.length):e}function dt(e,t,n=0){let r=0;for(let o=n;o<e.length;o+=1){const c=e[o];if(c===K){r+=1;continue}if(c===W){r=Math.max(0,r-1);continue}if(r===0&&c===t)return o}return-1}function fe(e){let t=0;for(const n of e)if(n===K&&(t+=1),n===W&&(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 pe(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 de(e){const t=String(e??"").trim();if(!t)return[];const n=t.split(wt).map(o=>o.trim()).filter(Boolean),r=[];for(const o of n){const c=o.split(St).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(Wt).map(C=>C.trim()).filter(Boolean);if(R.length===0)throw new g("Context atoms must include at least one value",{raw:y});h=pe(h,A,R)}r.push(...h)}return r}function me(e){const t=String(e||"").trim();if(!t)throw new g("Namespace cannot be empty",{raw:e});const n=t.indexOf(K);if(n<0)return{base:t,contextRaw:null,context:[]};const r=t.lastIndexOf(W);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:de(c)}}function he(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 ye(e){return!Array.isArray(e)||e.length===0?null:e.map(t=>t.map(n=>`${n.key}:${n.value}`).join(St)).join(wt)}function ge(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=ye(e.namespace.context),c=o?`${t}[${o}]`:t;return`${Q}${c}:${n}/${r}`}function we(e,t={}){const n=le(e);fe(n);const r=ue(n).replace(/^\/+/,"").trim();if(!r)throw new g("Target cannot be empty");const o=dt(r,":"),c=o<0;if(c&&!t.allowShorthandRead)throw new g("Target must match namespace[context]:operation/path",{raw:n});const h=c?dt(r,"/"):dt(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=me(y),R=he(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=ge(C),C}function st(e,t={}){return we(e,t)}const Se="https://cleaker.me",Ee="http://localhost",Ft=8161,ht=Se,be=Ee;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||ht).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 T=Date.now()-A;return n.operationalState.latencyMs=T,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:T,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 Re(e){const t=String(e??"").trim();if(!t)throw new g("Namespace cannot be empty");return t}function Ae(e){return e.startsWith(Q)?e.slice(Q.length):e}function Ce(e){let t=0;for(const n of e)if(n===K&&(t+=1),n===W&&(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 qt(e,t,n=0){let r=0;for(let o=n;o<e.length;o+=1){const c=e[o];if(c===K){r+=1;continue}if(c===W){r=Math.max(0,r-1);continue}if(r===0&&c===t)return o}return-1}function ve(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 Oe(e){const t=String(e??"").trim();if(!t)return[];const n=t.split(wt).map(o=>o.trim()).filter(Boolean),r=[];for(const o of n){const c=o.split(St).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(Wt).map(C=>C.trim()).filter(Boolean);if(R.length===0)throw new g("Namespace selectors must include at least one value",{raw:y});h=ve(h,A,R)}r.push(...h)}return r}function xe(e){const t=String(e||"").trim();if(!t)throw new g("Namespace cannot be empty",{raw:e});const n=t.indexOf(K);if(n<0)return{base:t,contextRaw:null,context:[]};const r=t.lastIndexOf(W);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:Oe(c)}}function Gt(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 Ne(e){const t=Gt(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 Te(e){const t=String(e||"").trim().toLowerCase();return/^(localhost|127(?:\.\d{1,3}){3}|0\.0\.0\.0)$/.test(t)||/\.local$/.test(t)}function G(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 _e(e,t){const n=Gt(e),r=G(t,"host")||G(t,"hostname")||G(t,"device"),o=G(t,"protocol"),c=G(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||(Te(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 $e(e){const t=qt(e,"/");return t<0?{head:e.trim(),path:""}:{head:e.slice(0,t).trim(),path:e.slice(t+1).trim().replace(/^\/+/,"")}}function Le(e){const t=qt(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 yt(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 Qt(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 B(e){const t=Re(e);Ce(t);const n=Ae(t).replace(/^\/+/,"").trim();if(!n)throw new g("Namespace cannot be empty",{raw:t});const r=$e(n),o=Le(r.head),c=xe(o.namespaceToken),h=Ne(c.base),y=_e(c.base,c.context),S=Qt({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 ke=Symbol.for("me.expression"),Ie=Symbol.for("me.identity");function Me(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 gt(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(r=>gt(r)).join(",")}]`;const t=e;return`{${Object.keys(t).sort().map(r=>`${JSON.stringify(r)}:${gt(t[r])}`).join(",")}}`}function it(e){return String(e||"").trim().toLowerCase().replace(/:\d+$/i,"")}function z(e){const t=String(e||"").trim();if(!t)return"";const n=t.includes("://")?t:`${U(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=it(t.replace(/^https?:\/\//i,"").split("/")[0]||"");return r?`${U(r)?"http":"https"}://${r}`:""}}function Et(e){return/^\d{1,3}(\.\d{1,3}){3}$/.test(e)}function Xt(e){return!e.includes(".")&&!Et(e)}function Yt(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}=Yt(t),o=n.toLowerCase();if(Et(o))return`http://${o}:${r??Ft}`;if(Xt(o))return`http://${o}.local:${r??Ft}`;const c=r?`:${r}`:"";return`https://${o}${c}`}function Pe(e){const t=String(e||"").trim();if(!t)return"";if(t.includes("://"))try{return new URL(t).hostname.toLowerCase()}catch{return""}const{host:n}=Yt(t),r=n.toLowerCase();return Et(r)?r:Xt(r)?`${r}.local`:r}function He(e){const t=e??{},n=String(t.hash||"").trim();return n?`h:${n}`:`v:${Number(t.timestamp||0)}:${gt(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 mt(e){return(typeof e=="string"?e.trim():"")||null}function I(e){return(typeof e=="string"?e.trim():"")||null}function zt(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=zt(n.namespace,"");if(r)return r;const o=n.target;return o&&typeof o=="object"?zt(o.namespace,t):t}function De(e){try{const t=mt(e[ke]);if(t)return t}catch{}try{const n=e["!"]?.currentExpression;if(typeof n=="function"){const r=mt(n());if(r)return r}if(n&&typeof n=="object"&&typeof n.call=="function"){const r=mt(n.call());if(r)return r}}catch{}return null}function je(e){try{const t=e[Ie];if(t&&typeof t=="object"){const r=I(t.hash);if(r)return r}const n=I(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=I(r.hash);if(c)return c}const o=I(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=I(r.hash);if(c)return c}const o=I(r);if(o)return o}}catch{}return null}function Ue(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 Fe(e){const t=String(e||"").trim();if(!t)return"";try{return B(t).constant}catch{const n=t.split(".").map(r=>r.trim()).filter(Boolean);return n.length>1?n.slice(1).join("."):t}}async function ze(e,t){const n=Ue(e,"prove");if(!n)throw new Error("PROVE_UNSUPPORTED");const r=Fe(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 U(e){const t=it(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 U(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 Be(){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 U(o)?"":o}catch{const o=it(String(e).trim().toLowerCase());return U(o)?"":o}const t=e,n=it(String(t.hostname||t.host||"").trim().toLowerCase());if(U(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 U(o)?"":o}catch{return""}}function Ke(){if(typeof globalThis>"u")return"";const e=globalThis.location;if(!e)return"";if(typeof e=="string")return z(e);const t=e,n=z(String(t.origin||""));if(n)return n;const r=String(t.href||"").trim();if(r)return z(r);const o=String(t.hostname||t.host||"").trim().toLowerCase();return o?z(o):""}function Jt(e){const t=ot(e);return t?z(t):""}function We(){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=Jt(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?z(o):""}catch{return""}}function ot(e){const t=String(e||"").trim();if(!t)return"";if(/^https?:\/\//i.test(t))try{return B(new URL(t).hostname).constant}catch{return""}try{return B(t).constant}catch{try{const n=new URL(t.includes("://")?t:`https://${t}`);return B(n.hostname).constant}catch{return""}}}function Ve(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 qe(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 Ge(e){return qe(k(e))}function Qe(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 $(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 Bt(e,t){const n=k(String(e.space||""));if(!n)return null;const r=String(e.id||"").trim()||Ge(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 Xe(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 Ye(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 Kt(e){if(!e||typeof e!="object")return e;const t=e;return Object.prototype.hasOwnProperty.call(t,"value")?t.value:e}function rt(e,t){if(!(t.length===0||typeof e!="function"))try{return e(t.join("."))}catch{return}}function Je(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 Ze(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=I(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,T={cycleId:0,state:"idle",overall:b.length?"degraded":"offline",activeNamespace:F(),totalHosts:0,verifiedHosts:0,hosts:[]},at=null,bt=Promise.resolve(null);function Zt(){if(t.space){const a=Pe(t.space);if(a)return a}const s=Be();if(s)return ot(s);const i=typeof process<"u"?String(process.env.CLEAKER_NAMESPACE_ROOT||process.env.CLEAKER_NAMESPACE_HOST||""):"";return ot(i||ht)}function F(s){const i=String(s||y||"").trim();if(i)return i;const a=De(e);if(!a)return"";if(a.includes("."))try{const l=B(a);if(l.prefix&&l.constant)return yt(l.prefix,l.constant)}catch{}const p=Zt();return p?yt(a,p):""}function ct(s=[],i=""){const a=t.space?tt(t.space):"",p=Ke(),l=typeof process<"u"?String(process.env.CLEAKER_NAMESPACE_ROOT||process.env.CLEAKER_NAMESPACE_HOST||""):"",m=Jt(l||""),d=We();return Ve([i,a,...b,...s,p,m,d,ht,be])}function Rt(s){return I(s)||A||je(e)||""}function te(s){const i=String(s||"").trim().replace(/^\/+/,"").replace(/\//g,".");if(i)return rt(e,i.split(".").filter(Boolean))}function At(s){const i=String(s||"").trim();return i?i.startsWith("me://")||i.includes(":"):!1}function Ct(s){if(!At(s))return null;try{const i=st(s,{defaultMode:"reactive",allowShorthandRead:!0});return String(i.path||"").trim().replace(/^\/+/,"").split("/").map(a=>a.trim()).filter(Boolean)}catch{return null}}function L(s,...i){const a=h.get(s);!a||a.size===0||a.forEach(p=>{try{p(...i)}catch{}})}function vt(s,i){const a=h.get(s)||new Set;return a.add(i),h.set(s,a),()=>Ot(s,i)}function Ot(s,i){const a=h.get(s);a&&(a.delete(i),a.size===0&&h.delete(s))}function xt(s,i){const a=vt(s,((...p)=>{a(),i(...p)}));return a}function H(s,i){E=s,T={...T,cycleId:i,state:s},L("status:change",M())}function V(s,i){const a=["namespaces",s,"registry","hosts",i.id];$(e,[...a,"id"],i.id),$(e,[...a,"alias"],i.alias||""),$(e,[...a,"space"],i.space),$(e,[...a,"namespace"],i.namespace),$(e,[...a,"status","transport"],i.status.transport),$(e,[...a,"status","triad"],i.status.triad),$(e,[...a,"status","latencyMs"],i.status.latencyMs),$(e,[...a,"status","lastSeen"],i.status.lastSeen),$(e,[...a,"capabilities","canClaim"],i.capabilities.canClaim),$(e,[...a,"capabilities","canOpen"],i.capabilities.canOpen),$(e,[...a,"capabilities","canRelay"],i.capabilities.canRelay),$(e,[...a,"error"],i.error||"")}function lt(s={}){const i=F(s.namespace);if(!i)return[];const a=new Map,p=Qe(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=Bt({...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):[];ct(l).forEach(d=>{const u=Bt({space:d},i);u&&(a.set(u.id,u),V(i,u))})}return Array.from(a.values())}async function ee(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 X(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 Nt(s,i,a){return{ok:!0,namespace:et(s,i),identityHash:I(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 Tt(s,i,a){return{ok:!0,namespace:et(s,i),identityHash:I(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 _t(s,i,a,p,l,m,d={}){const u={namespace:i,secret:a,...p?{identityHash:p}:{}},f=await X(`${k(s)}/claims/signIn`,u,l,m,d);if(f.ok&&f.data)return Nt(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 X(`${k(s)}/`,{operation:"open",...u},l,m,{"x-forwarded-host":i,...d});return _.ok&&_.data?Nt(_.data,i,p):{ok:!1,error:String(_.error||O)}}return{ok:!1,error:O}}async function $t(s,i,a,p,l,m={}){let d;try{d=await ze(e,i)}catch(f){return{ok:!1,error:f instanceof Error?f.message:"PROOF_INVALID"}}const u=await X(`${k(s)}/me/kernel:claim/${encodeURIComponent(i)}`,{namespace:i,secret:a,proof:d},p,l,m);if(u.ok&&u.data)return Tt(u.data,i,d.identityHash);if(u.status===404||u.status===405){const f=await X(`${k(s)}/`,{operation:"claim",namespace:i,secret:a,proof:d},p,l,{"x-forwarded-host":i,...m});return f.ok&&f.data?Tt(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 Lt(s,i,a,p,l,m,d={}){const u=await _t(s,i,a,p,l,m,d);if(u.ok||u.error!=="CLAIM_NOT_FOUND")return u;const f=await $t(s,i,a,l,m,d);if(!f.ok)return{ok:!1,error:String(f.error||"CLAIM_FAILED")};const O=I(f.identityHash)||p;return _t(s,et(f,i),a,O,l,m,d)}function M(){return{...T,hosts:T.hosts.map(s=>({...s,status:{...s.status},capabilities:{...s.capabilities}}))}}async function ne(s=1e4){return E==="ready"&&at?at:await new Promise((i,a)=>{const p=setTimeout(()=>{l(),a(new Error("TIMEOUT_WAITING_FOR_READY"))},s),l=xt("ready",m=>{clearTimeout(p),i(m)})})}async function re(s={}){const i=F(s.namespace),a=String(s.secret!==void 0?s.secret:S),p=Rt(s.identityHash),l=s.triadStrategy||"first-success",m=Number(s.timeoutMs||5e3),d=t.fetcher||fetch,u=++v;if(!i)return L("error",{code:"NAMESPACE_REQUIRED",message:"Cannot validate hosts without namespace."}),H("offline",u),T={...T,cycleId:u,state:"offline",overall:"offline",activeNamespace:i,totalHosts:0,verifiedHosts:0,hosts:[]},L("status:change",M()),M();H("discovering",u);const f=lt({namespace:i,bootstrap:s.bootstrap});if(!f.length)return H("offline",u),T={...T,cycleId:u,state:"offline",overall:"offline",activeNamespace:i,totalHosts:0,verifiedHosts:0,hosts:[]},L("status:change",M()),M();H("probing",u);let O=null,_="",D="",Dt=0;const P=[];for(let N=0;N<f.length;N+=1){const w=f[N],J=Date.now(),Z=await ee(w.space,m,d);if(w.status.transport=Z?"up":"down",w.status.latencyMs=Date.now()-J,w.status.lastSeen=Date.now(),!Z){w.status.triad="unverified",w.error="NETWORK_ERROR",V(i,w),P.push({origin:w.space,reason:"NETWORK_ERROR"});const x=f[N+1];x&&!nt(w.space)&&nt(x.space)&&L("namespace:fallback",{namespace:i,failedOrigin:w.space,failedReason:"NETWORK_ERROR",fallbackOrigin:x.space});continue}if(!a){w.status.triad="unverified",w.error="SECRET_REQUIRED",V(i,w),P.push({origin:w.space,reason:"SECRET_REQUIRED"});continue}H("opening",u);const j=await Lt(w.space,i,a,p,m,d);if(!j.ok){const x=String(j.error||"OPEN_FAILED");w.status.triad=x==="CLAIM_NOT_FOUND"?"unverified":"failed",w.error=x,L("error",{code:x,message:`Triad open failed on ${w.space}`,hostId:w.id}),V(i,w),P.push({origin:w.space,reason:x});const pt=f[N+1];pt&&!nt(w.space)&&nt(pt.space)&&L("namespace:fallback",{namespace:i,failedOrigin:w.space,failedReason:x,fallbackOrigin:pt.space});continue}w.status.triad="verified",w.error=void 0,V(i,w),L("host:triad:success",w.id),O||(O=w),H("hydrating",u);const ie=Array.isArray(j.memories)?j.memories:[],ae=n.size;if(ie.forEach(x=>{Y(x)}),Dt+=Math.max(0,n.size-ae),j.noise!==void 0&&(e.noise=String(j.noise||"")),_=w.id,D=String(j.identityHash||""),l==="first-success"){for(let x=N+1;x<f.length;x+=1)f[x].status.triad="skipped";break}}if(u!==v)return M();const q=f.filter(N=>N.status.triad==="verified").length,jt=q>0?"healthy":"degraded";if(q===0&&P.length>0){const N=P.map((J,Z)=>` [${Z+1}] ${J.origin}${J.reason}`),w=`namespace '${i}' failed to resolve. tried ${P.length} surface${P.length===1?"":"s"}: `+N.join(` `);L("namespace:failed",{namespace:i,tried:P,explain:w})}const Ut=q>0?"ready":"degraded";if(H(Ut,u),T={cycleId:u,state:Ut,overall:jt,activeNamespace:i,totalHosts:f.length,verifiedHosts:q,hosts:f},L("status:change",M()),O){const N={namespace:i,cycleId:u,sourceHostId:_||O.id,sourceOrigin:O.space,identityHash:D,timestamp:Date.now(),hydratedMemories:Dt,summary:{verifiedHosts:q,totalHosts:f.length,overall:jt}};at=N,L("ready",N)}return M()}function ut(s,i={}){const a=st(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 te(l.intent.path)}});return Object.keys(i).length?{...p,resolve(l={}){return p.resolve({...i,...l})}}:p}function Y(s){const i=Me(s),a=He(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 kt(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 It(s){const i=F(s.namespace),a=String(s.secret||""),p=Rt(s.identityHash);if(!i)throw new Error("NAMESPACE_REQUIRED");if(!a)throw new Error("SECRET_REQUIRED");const l=s.fetcher||t.fetcher||fetch,m=ct([],s.space?tt(s.space):"");let d="SIGNIN_FAILED";for(const u of m){const f=await Lt(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(D=>Y(D));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 oe(s){const i=F(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=ct([],s.space?tt(s.space):"");let m="CLAIM_FAILED";for(const d of l){const u=await $t(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)}F()&&lt({namespace:y}),t.secret&&(bt=It({namespace:y,secret:t.secret,identityHash:t.identityHash,space:t.space,fetcher:t.fetcher}).catch(()=>null));function Mt(s){if(!Xe(s))return;const i=s.join("."),a=c.get(i);if(a)return a;const p=Ye(s);if(!p)return;const l=ut(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=Kt(d.data);o.set(i,u);const f=kt(s,u);f&&Y(f)}return d}),c.set(i,m),m}function Pt(s){const i=Ct(s);if(!i||i.length===0)return;const a=`target:${s}`,p=c.get(a);if(p)return p;const l=ut(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=Kt(d.data);o.set(a,u);const f=kt(i,u);f&&Y(f)}return d}),c.set(a,m),m}function Ht(s){return{status:"pending",path:s.key,pointer:s.pointer,promise:s.promise}}function se(s){if(!(s in e))return;const i=e[s];return typeof i=="function"?i.bind(e):i}function ft(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=Ct(l);if(m){const u=rt(e,m);if(u!==void 0)return u;const f=Pt(l);return f?Ht(f):void 0}const d=rt(e,l.split(".").filter(Boolean));if(d!==void 0)return d;if(At(l)){const u=Pt(l);return u?Ht(u):void 0}}return e(...a)}return}const p=Je(e,s,a);return p!==void 0?p:ft(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 oe;if(l==="signIn")return It;if(l==="ready")return bt;if(l==="pointer")return ut;if(l==="discoverHosts")return lt;if(l==="validateHosts")return re;if(l==="getStatus")return M;if(l==="waitUntilReady")return ne;if(l==="on")return vt;if(l==="once")return xt;if(l==="off")return Ot;if(l==="state")return E;if(l==="currentCycleId")return v;const D=se(l);if(D!==void 0)return D}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=Mt(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 _=rt(e,f);return _!==void 0?_:(Mt(f),ft(f))},apply(a,p,l){return i(...l)}})}return ft([])}function tn(e,t,n){if(typeof e=="string"){const c=st(e,{defaultMode:"reactive"});return Vt(c,t??{})}let r,o;return typeof t=="string"?(r=t,o=n??{}):o=t??{},Ze(e,{...o,...r?{space:r}:{}})}exports.composeNamespace=yt;exports.default=tn;exports.parseNamespaceExpression=B;exports.parseTarget=st;exports.stringifyNamespaceExpression=Qt; //# sourceMappingURL=cleaker.cjs.map