@ours.network/mcp 1.2.0-nightly.3 → 1.2.0-nightly.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.
- package/README.md +36 -37
- package/dist/cli.js +5 -5
- package/dist/connector.js +30 -30
- package/dist/host-client.js +2 -3
- package/dist/host-profile.js +1 -1
- package/dist/native-session.js +2 -2
- package/dist/server.js +26 -26
- package/package.json +6 -6
- package/dist/network-integration.js +0 -82
package/dist/host-client.js
CHANGED
|
@@ -1,3 +1,2 @@
|
|
|
1
|
-
import{existsSync as
|
|
2
|
-
|
|
3
|
-
`,{mode:384,flag:"wx"}),await Tt(n,t),await K(t,384)}catch(o){try{await Ht(n)}catch{}throw o}}async function Z(t,r){let e=S.get(t)??Promise.resolve(),n,o=new Promise(a=>{n=a}),i=e.catch(()=>{}).then(()=>o);S.set(t,i),await e.catch(()=>{});let s;try{return s=Y(t),await r()}finally{try{s?.()}finally{n(),S.get(t)===i&&S.delete(t)}}}function tt(t,r){return Lt({endpoint:t.endpoint,expectedInstanceId:t.expectedInstanceId,credentialPath:t.credentialPath,sessionMode:"external",leaseToken:r,env:{}})}function X(t,r,e){let n=m.get(t);if(n?.ownerInstanceId===e)return n.promise;n&&(m.delete(t),n.promise.then(s=>s.close()).catch(()=>{}));let o=tt(r,e),i={ownerInstanceId:e,promise:o};return m.set(t,i),o.catch(()=>{m.get(t)===i&&m.delete(t)}),o}async function Wt(t,r,e){let n=m.get(t),o=n?.ownerInstanceId===e?await n.promise:await tt(r,e);try{await o.releaseLease()}finally{n?.ownerInstanceId!==e&&await o.close()}}async function et(t,r,e){await Wt(t,r,e);let n=await b(t);n?.state==="pending"&&n.ownerInstanceId===e&&await F(t,{version:P,ownerInstanceId:e,state:"ended"});let o=m.get(t);o?.ownerInstanceId===e&&(m.delete(t),o.promise.then(i=>i.close()).catch(()=>{}))}async function nt(t,r,e){let n=w(t),o=x(e,n.expectedInstanceId,r);return Z(o,async()=>{let i=await b(o);if(i?.state==="pending"&&(await et(o,n,i.ownerInstanceId),i=await b(o)),i?.state==="active")return X(o,n,i.ownerInstanceId);let s=B();return await F(o,{version:P,ownerInstanceId:s,state:"active"}),X(o,n,s)})}async function rt(t,r,e){let n=w(t),o=x(e,n.expectedInstanceId,r);await Z(o,async()=>{let i=await b(o);i===null||i.state==="ended"||(i.state==="active"&&(i={version:P,ownerInstanceId:i.ownerInstanceId,state:"pending"},await F(o,i)),await et(o,n,i.ownerInstanceId))})}export{bt as completeHostFileCall,rt as endNativeSessionAtRoot,D as hostProfileFromEnv,A as hostProfileSelectionFromEnv,nt as nativeClientForAtRoot,x as nativeSessionRecordPath,St as prepareHostFileCall,C as readHostProfile,w as validateHostProfile};
|
|
1
|
+
import{existsSync as F,lstatSync as O,readFileSync as L}from"node:fs";import{homedir as N}from"node:os";import{resolve as u}from"node:path";var v=["endpoint","expectedInstanceId","credentialPath"],q=["port","stateDir","apiToken","apiVisibility"],G=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,M=["OURS_API_TOKEN","OURS_PORT","OURS_STATE_DIR","OURS_DAEMON_ID"];function c(t){return new Error(`Invalid external host profile: ${t}`)}function f(t){if(!t||typeof t!="object"||Array.isArray(t))throw c("expected a complete host profile object.");let n=t;if(v.filter(d=>Object.hasOwn(n,d)).length!==v.length)throw c("expected a complete host profile tuple: endpoint, expectedInstanceId, credentialPath.");let r=q.filter(d=>Object.hasOwn(n,d));if(r.length)throw c(`legacy selection keys cannot be mixed with a host profile (${r.join(", ")}).`);let i=n.endpoint,o=n.expectedInstanceId,s=n.credentialPath;if(typeof i!="string"||i.trim()!==i||i==="")throw c("endpoint must be a non-empty HTTP or HTTPS origin.");if(typeof o!="string"||!G.test(o))throw c("expectedInstanceId must be a lowercase UUID.");if(typeof s!="string"||s===""||!s.startsWith("/")||u(s)!==s)throw c("credentialPath must be a normalized absolute path.");let a;try{a=new URL(i)}catch{throw c("endpoint must be an HTTP or HTTPS origin.")}if(a.protocol!=="http:"&&a.protocol!=="https:"||a.username||a.password||a.pathname!=="/"||a.search||a.hash)throw c("endpoint must be an HTTP or HTTPS origin without credentials, path, query, or fragment.");return{endpoint:a.origin,expectedInstanceId:o,credentialPath:s}}function V(t){let n;try{n=L(t,"utf8")}catch{throw new Error(`Cannot read host profile ${JSON.stringify(t)}.`)}let e;try{e=JSON.parse(n)}catch{throw c(`config ${JSON.stringify(t)} is not valid JSON.`)}if(!e||typeof e!="object"||Array.isArray(e))throw c(`config ${JSON.stringify(t)} must be an object.`);return e}function W(t){let n;try{n=O(t)}catch{throw new Error(`Cannot read host profile ${JSON.stringify(t)}.`)}if(!n.isFile())throw c(`config ${JSON.stringify(t)} must be a regular file.`);let e=process.getuid?.();if(e===void 0||n.uid!==e)throw c(`config ${JSON.stringify(t)} must be owned by the current user.`);if(n.mode&63)throw c(`config ${JSON.stringify(t)} must have private permissions.`)}function I(t){let n=V(t);return v.filter(r=>Object.hasOwn(n,r)).length===0?null:(W(t),f(n))}function Y(t,n){return(t[n]??"").trim()!==""}function P(t=process.env){let n=(t.OURS_CONFIG??"").trim(),e=u(t.HOME||N(),".ours-client","profile.json"),r=n;if(!r)try{O(e),r=e}catch(s){if(s.code!=="ENOENT")throw new Error(`Cannot read host profile ${JSON.stringify(e)}.`);if(r=u(N(),".ours","config.json"),!F(r))return null}let i=I(r);if(i===null){if(u(r)===e)throw c("managed client config must contain a complete host profile tuple.");return null}let o=M.filter(s=>Y(t,s));if(o.length)throw c(`${o.join(", ")} conflicts with host-profile mode.`);return{profile:i,configPath:r}}function b(t=process.env){return P(t)?.profile??null}import{createHash as nt,randomUUID as k}from"node:crypto";import{chmod as A,mkdir as rt,readFile as it,rename as ot,unlink as st,writeFile as at}from"node:fs/promises";import{dirname as ct,join as dt,resolve as lt}from"node:path";import{attachOursClient as ft}from"@ours.network/sdk";import{createHash as z}from"node:crypto";import{openSync as K,closeSync as X,lstatSync as S,mkdirSync as B,chmodSync as Q,constants as m}from"node:fs";import{join as x}from"node:path";import{createRequire as R}from"node:module";var Z=5e3,p=null,C=!1;function tt(){if(p)return p;if(C)throw new Error("No SQLite implementation available for native session guard");C=!0;try{return p=R(import.meta.url)("node:sqlite").DatabaseSync,p}catch{try{let t=R(import.meta.url)("better-sqlite3");return p=t.default??t,p}catch{throw new Error("Native session guard requires node:sqlite (Node >=22.13) or better-sqlite3")}}}function et(t){try{let e=K(t,m.O_RDWR|m.O_CREAT|m.O_EXCL|m.O_NOFOLLOW,384);X(e)}catch(e){if(e.code!=="EEXIST")throw e}let n=S(t);if(!n.isFile()||n.uid!==process.getuid()||n.mode&63||n.nlink!==1)throw new Error("Native session guard file must be an owner-only regular file")}function $(t){let n=process.getuid(),e=x(`/tmp/ours-${n}`,"session-guards");B(e,{recursive:!0,mode:448});try{Q(e,448)}catch{}let r=z("sha256").update(t).digest("hex"),i=x(e,`${r}.guard`);et(i);let o=S(i),s=tt(),a=new s(i);try{let d=S(i);if(o.dev!==d.dev||o.ino!==d.ino||o.mode!==d.mode||o.uid!==d.uid)throw new Error("Native session guard file changed during acquisition");return a.exec(`PRAGMA busy_timeout=${Z}; BEGIN EXCLUSIVE`),()=>{try{a.close()}catch{}}}catch(d){try{a.close()}catch{}throw d}}var w=1,D=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,l=new Map,g=new Map;function pt(t){if(typeof t!="string"||t.length===0||t.length>4096||t.trim()!==t||t.includes("\0"))throw new Error("Native session metadata is missing or invalid for this host-profile tool call.");return t}function h(t,n,e){if(!t||!t.startsWith("/")||lt(t)!==t)throw new Error("Native session host record root must be a normalized absolute path.");if(!D.test(n))throw new Error("Native session daemon instance must be a lowercase UUID.");let r=nt("sha256").update(pt(e),"utf8").digest("hex");return dt(t,"sessions",n,`${r}.json`)}function ut(t,n){let e;try{e=JSON.parse(t)}catch(o){throw new Error(`Invalid native session record at ${n}: ${String(o)}`)}if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid native session record at ${n}: expected an object.`);let r=e;if(Object.keys(r).sort().join(",")!=="ownerInstanceId,state,version"||r.version!==w||typeof r.ownerInstanceId!="string"||!D.test(r.ownerInstanceId)||!["active","pending","ended"].includes(String(r.state)))throw new Error(`Invalid native session record at ${n}.`);return r}async function y(t){try{return ut(await it(t,"utf8"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function E(t,n){let e=ct(t);await rt(e,{recursive:!0,mode:448}),await A(e,448);let r=`${t}.${process.pid}.${k()}.tmp`;try{await at(r,`${JSON.stringify(n,null,2)}
|
|
2
|
+
`,{mode:384,flag:"wx"}),await ot(r,t),await A(t,384)}catch(i){try{await st(r)}catch{}throw i}}async function H(t,n){let e=g.get(t)??Promise.resolve(),r,i=new Promise(a=>{r=a}),o=e.catch(()=>{}).then(()=>i);g.set(t,o),await e.catch(()=>{});let s;try{return s=$(t),await n()}finally{try{s?.()}finally{r(),g.get(t)===o&&g.delete(t)}}}function U(t,n){return ft({endpoint:t.endpoint,expectedInstanceId:t.expectedInstanceId,credentialPath:t.credentialPath,sessionMode:"external",leaseToken:n,env:{}})}function T(t,n,e){let r=l.get(t);if(r?.ownerInstanceId===e)return r.promise;r&&(l.delete(t),r.promise.then(s=>s.close()).catch(()=>{}));let i=U(n,e),o={ownerInstanceId:e,promise:i};return l.set(t,o),i.catch(()=>{l.get(t)===o&&l.delete(t)}),i}async function mt(t,n,e){let r=l.get(t),i=r?.ownerInstanceId===e?await r.promise:await U(n,e);try{await i.releaseLease()}finally{r?.ownerInstanceId!==e&&await i.close()}}async function j(t,n,e){await mt(t,n,e);let r=await y(t);r?.state==="pending"&&r.ownerInstanceId===e&&await E(t,{version:w,ownerInstanceId:e,state:"ended"});let i=l.get(t);i?.ownerInstanceId===e&&(l.delete(t),i.promise.then(o=>o.close()).catch(()=>{}))}async function _(t,n,e){let r=f(t),i=h(e,r.expectedInstanceId,n);return H(i,async()=>{let o=await y(i);if(o?.state==="pending"&&(await j(i,r,o.ownerInstanceId),o=await y(i)),o?.state==="active")return T(i,r,o.ownerInstanceId);let s=k();return await E(i,{version:w,ownerInstanceId:s,state:"active"}),T(i,r,s)})}async function J(t,n,e){let r=f(t),i=h(e,r.expectedInstanceId,n);await H(i,async()=>{let o=await y(i);o===null||o.state==="ended"||(o.state==="active"&&(o={version:w,ownerInstanceId:o.ownerInstanceId,state:"pending"},await E(i,o)),await j(i,r,o.ownerInstanceId))})}export{J as endNativeSessionAtRoot,b as hostProfileFromEnv,P as hostProfileSelectionFromEnv,_ as nativeClientForAtRoot,h as nativeSessionRecordPath,I as readHostProfile,f as validateHostProfile};
|
package/dist/host-profile.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as h,lstatSync as u,readFileSync as g}from"node:fs";import{homedir as d}from"node:os";import{resolve as l}from"node:path";var p=["endpoint","expectedInstanceId","credentialPath"],m=["port","stateDir","apiToken","apiVisibility"],w=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,y=["OURS_API_TOKEN","OURS_PORT","OURS_STATE_DIR","OURS_DAEMON_ID"];function
|
|
1
|
+
import{existsSync as h,lstatSync as u,readFileSync as g}from"node:fs";import{homedir as d}from"node:os";import{resolve as l}from"node:path";var p=["endpoint","expectedInstanceId","credentialPath"],m=["port","stateDir","apiToken","apiVisibility"],w=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,y=["OURS_API_TOKEN","OURS_PORT","OURS_STATE_DIR","OURS_DAEMON_ID"];function n(t){return new Error(`Invalid external host profile: ${t}`)}function O(t){if(!t||typeof t!="object"||Array.isArray(t))throw n("expected a complete host profile object.");let e=t;if(p.filter(f=>Object.hasOwn(e,f)).length!==p.length)throw n("expected a complete host profile tuple: endpoint, expectedInstanceId, credentialPath.");let o=m.filter(f=>Object.hasOwn(e,f));if(o.length)throw n(`legacy selection keys cannot be mixed with a host profile (${o.join(", ")}).`);let c=e.endpoint,a=e.expectedInstanceId,i=e.credentialPath;if(typeof c!="string"||c.trim()!==c||c==="")throw n("endpoint must be a non-empty HTTP or HTTPS origin.");if(typeof a!="string"||!w.test(a))throw n("expectedInstanceId must be a lowercase UUID.");if(typeof i!="string"||i===""||!i.startsWith("/")||l(i)!==i)throw n("credentialPath must be a normalized absolute path.");let s;try{s=new URL(c)}catch{throw n("endpoint must be an HTTP or HTTPS origin.")}if(s.protocol!=="http:"&&s.protocol!=="https:"||s.username||s.password||s.pathname!=="/"||s.search||s.hash)throw n("endpoint must be an HTTP or HTTPS origin without credentials, path, query, or fragment.");return{endpoint:s.origin,expectedInstanceId:a,credentialPath:i}}function S(t){let e;try{e=g(t,"utf8")}catch{throw new Error(`Cannot read host profile ${JSON.stringify(t)}.`)}let r;try{r=JSON.parse(e)}catch{throw n(`config ${JSON.stringify(t)} is not valid JSON.`)}if(!r||typeof r!="object"||Array.isArray(r))throw n(`config ${JSON.stringify(t)} must be an object.`);return r}function E(t){let e;try{e=u(t)}catch{throw new Error(`Cannot read host profile ${JSON.stringify(t)}.`)}if(!e.isFile())throw n(`config ${JSON.stringify(t)} must be a regular file.`);let r=process.getuid?.();if(r===void 0||e.uid!==r)throw n(`config ${JSON.stringify(t)} must be owned by the current user.`);if(e.mode&63)throw n(`config ${JSON.stringify(t)} must have private permissions.`)}function P(t){let e=S(t);return p.filter(o=>Object.hasOwn(e,o)).length===0?null:(E(t),O(e))}function I(t,e){return(t[e]??"").trim()!==""}function N(t=process.env){let e=(t.OURS_CONFIG??"").trim(),r=l(t.HOME||d(),".ours-client","profile.json"),o=e;if(!o)try{u(r),o=r}catch(i){if(i.code!=="ENOENT")throw new Error(`Cannot read host profile ${JSON.stringify(r)}.`);if(o=l(d(),".ours","config.json"),!h(o))return null}let c=P(o);if(c===null){if(l(o)===r)throw n("managed client config must contain a complete host profile tuple.");return null}let a=y.filter(i=>I(t,i));if(a.length)throw n(`${a.join(", ")} conflicts with host-profile mode.`);return{profile:c,configPath:o}}function R(t=process.env){return N(t)?.profile??null}export{R as hostProfileFromEnv,N as hostProfileSelectionFromEnv,P as readHostProfile,O as validateHostProfile};
|
package/dist/native-session.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createHash as z,randomUUID as $}from"node:crypto";import{chmod as x,mkdir as K,readFile as X,rename as B,unlink as Q,writeFile as Z}from"node:fs/promises";import{dirname as I,join as tt,resolve as et}from"node:path";import{attachOursClient as nt}from"@ours.network/sdk";import{homedir as U}from"node:os";import{dirname as lt,resolve as E}from"node:path";var _="OURS_MCP_CONFIG";function w(t=process.env){let e=(t[_]??"").trim();return E(e||E(U(),".ours-mcp","config.json"))}import{resolve as j}from"node:path";var S=["endpoint","expectedInstanceId","credentialPath"],J=["port","stateDir","apiToken","apiVisibility"],H=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function d(t){return new Error(`Invalid external host profile: ${t}`)}function y(t){if(!t||typeof t!="object"||Array.isArray(t))throw d("expected a complete host profile object.");let e=t;if(S.filter(c=>Object.hasOwn(e,c)).length!==S.length)throw d("expected a complete host profile tuple: endpoint, expectedInstanceId, credentialPath.");let i=J.filter(c=>Object.hasOwn(e,c));if(i.length)throw d(`legacy selection keys cannot be mixed with a host profile (${i.join(", ")}).`);let r=e.endpoint,o=e.expectedInstanceId,s=e.credentialPath;if(typeof r!="string"||r.trim()!==r||r==="")throw d("endpoint must be a non-empty HTTP origin.");if(typeof o!="string"||!H.test(o))throw d("expectedInstanceId must be a lowercase UUID.");if(typeof s!="string"||s===""||!s.startsWith("/")||j(s)!==s)throw d("credentialPath must be a normalized absolute path.");let a;try{a=new URL(r)}catch{throw d("endpoint must be an HTTP origin.")}if(a.protocol!=="http:"||a.username||a.password||a.pathname!=="/"||a.search||a.hash)throw d("endpoint must be an HTTP origin without credentials, path, query, or fragment.");return{endpoint:a.origin,expectedInstanceId:o,credentialPath:s}}import{createHash as L}from"node:crypto";import{openSync as F,closeSync as q,lstatSync as h,mkdirSync as G,chmodSync as M,constants as
|
|
2
|
-
`,{mode:384,flag:"wx"}),await B(i,t),await x(t,384)}catch(r){try{await Q(i)}catch{}throw r}}async function
|
|
1
|
+
import{createHash as z,randomUUID as $}from"node:crypto";import{chmod as x,mkdir as K,readFile as X,rename as B,unlink as Q,writeFile as Z}from"node:fs/promises";import{dirname as I,join as tt,resolve as et}from"node:path";import{attachOursClient as nt}from"@ours.network/sdk";import{homedir as U}from"node:os";import{dirname as lt,resolve as E}from"node:path";var _="OURS_MCP_CONFIG";function w(t=process.env){let e=(t[_]??"").trim();return E(e||E(U(),".ours-mcp","config.json"))}import{resolve as j}from"node:path";var S=["endpoint","expectedInstanceId","credentialPath"],J=["port","stateDir","apiToken","apiVisibility"],H=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function d(t){return new Error(`Invalid external host profile: ${t}`)}function y(t){if(!t||typeof t!="object"||Array.isArray(t))throw d("expected a complete host profile object.");let e=t;if(S.filter(c=>Object.hasOwn(e,c)).length!==S.length)throw d("expected a complete host profile tuple: endpoint, expectedInstanceId, credentialPath.");let i=J.filter(c=>Object.hasOwn(e,c));if(i.length)throw d(`legacy selection keys cannot be mixed with a host profile (${i.join(", ")}).`);let r=e.endpoint,o=e.expectedInstanceId,s=e.credentialPath;if(typeof r!="string"||r.trim()!==r||r==="")throw d("endpoint must be a non-empty HTTP or HTTPS origin.");if(typeof o!="string"||!H.test(o))throw d("expectedInstanceId must be a lowercase UUID.");if(typeof s!="string"||s===""||!s.startsWith("/")||j(s)!==s)throw d("credentialPath must be a normalized absolute path.");let a;try{a=new URL(r)}catch{throw d("endpoint must be an HTTP or HTTPS origin.")}if(a.protocol!=="http:"&&a.protocol!=="https:"||a.username||a.password||a.pathname!=="/"||a.search||a.hash)throw d("endpoint must be an HTTP or HTTPS origin without credentials, path, query, or fragment.");return{endpoint:a.origin,expectedInstanceId:o,credentialPath:s}}import{createHash as L}from"node:crypto";import{openSync as F,closeSync as q,lstatSync as h,mkdirSync as G,chmodSync as M,constants as p}from"node:fs";import{join as P}from"node:path";import{createRequire as N}from"node:module";var V=5e3,f=null,O=!1;function W(){if(f)return f;if(O)throw new Error("No SQLite implementation available for native session guard");O=!0;try{return f=N(import.meta.url)("node:sqlite").DatabaseSync,f}catch{try{let t=N(import.meta.url)("better-sqlite3");return f=t.default??t,f}catch{throw new Error("Native session guard requires node:sqlite (Node >=22.13) or better-sqlite3")}}}function Y(t){try{let n=F(t,p.O_RDWR|p.O_CREAT|p.O_EXCL|p.O_NOFOLLOW,384);q(n)}catch(n){if(n.code!=="EEXIST")throw n}let e=h(t);if(!e.isFile()||e.uid!==process.getuid()||e.mode&63||e.nlink!==1)throw new Error("Native session guard file must be an owner-only regular file")}function b(t){let e=process.getuid(),n=P(`/tmp/ours-${e}`,"session-guards");G(n,{recursive:!0,mode:448});try{M(n,448)}catch{}let i=L("sha256").update(t).digest("hex"),r=P(n,`${i}.guard`);Y(r);let o=h(r),s=W(),a=new s(r);try{let c=h(r);if(o.dev!==c.dev||o.ino!==c.ino||o.mode!==c.mode||o.uid!==c.uid)throw new Error("Native session guard file changed during acquisition");return a.exec(`PRAGMA busy_timeout=${V}; BEGIN EXCLUSIVE`),()=>{try{a.close()}catch{}}}catch(c){try{a.close()}catch{}throw c}}var m=1,R=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,l=new Map,u=new Map;function it(t){if(typeof t!="string"||t.length===0||t.length>4096||t.trim()!==t||t.includes("\0"))throw new Error("Native session metadata is missing or invalid for this host-profile tool call.");return t}function T(t,e,n){if(!t||!t.startsWith("/")||et(t)!==t)throw new Error("Native session host record root must be a normalized absolute path.");if(!R.test(e))throw new Error("Native session daemon instance must be a lowercase UUID.");let i=z("sha256").update(it(n),"utf8").digest("hex");return tt(t,"sessions",e,`${i}.json`)}function rt(t,e){let n;try{n=JSON.parse(t)}catch(o){throw new Error(`Invalid native session record at ${e}: ${String(o)}`)}if(!n||typeof n!="object"||Array.isArray(n))throw new Error(`Invalid native session record at ${e}: expected an object.`);let i=n;if(Object.keys(i).sort().join(",")!=="ownerInstanceId,state,version"||i.version!==m||typeof i.ownerInstanceId!="string"||!R.test(i.ownerInstanceId)||!["active","pending","ended"].includes(String(i.state)))throw new Error(`Invalid native session record at ${e}.`);return i}async function g(t){try{return rt(await X(t,"utf8"),t)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function v(t,e){let n=I(t);await K(n,{recursive:!0,mode:448}),await x(n,448);let i=`${t}.${process.pid}.${$()}.tmp`;try{await Z(i,`${JSON.stringify(e,null,2)}
|
|
2
|
+
`,{mode:384,flag:"wx"}),await B(i,t),await x(t,384)}catch(r){try{await Q(i)}catch{}throw r}}async function A(t,e){let n=u.get(t)??Promise.resolve(),i,r=new Promise(a=>{i=a}),o=n.catch(()=>{}).then(()=>r);u.set(t,o),await n.catch(()=>{});let s;try{return s=b(t),await e()}finally{try{s?.()}finally{i(),u.get(t)===o&&u.delete(t)}}}function k(t,e){return nt({endpoint:t.endpoint,expectedInstanceId:t.expectedInstanceId,credentialPath:t.credentialPath,sessionMode:"external",leaseToken:e,env:{}})}function C(t,e,n){let i=l.get(t);if(i?.ownerInstanceId===n)return i.promise;i&&(l.delete(t),i.promise.then(s=>s.close()).catch(()=>{}));let r=k(e,n),o={ownerInstanceId:n,promise:r};return l.set(t,o),r.catch(()=>{l.get(t)===o&&l.delete(t)}),r}async function ot(t,e,n){let i=l.get(t),r=i?.ownerInstanceId===n?await i.promise:await k(e,n);try{await r.releaseLease()}finally{i?.ownerInstanceId!==n&&await r.close()}}async function D(t,e,n){await ot(t,e,n);let i=await g(t);i?.state==="pending"&&i.ownerInstanceId===n&&await v(t,{version:m,ownerInstanceId:n,state:"ended"});let r=l.get(t);r?.ownerInstanceId===n&&(l.delete(t),r.promise.then(o=>o.close()).catch(()=>{}))}async function bt(t,e,n=process.env){return st(t,e,I(w(n)))}async function st(t,e,n){let i=y(t),r=T(n,i.expectedInstanceId,e);return A(r,async()=>{let o=await g(r);if(o?.state==="pending"&&(await D(r,i,o.ownerInstanceId),o=await g(r)),o?.state==="active")return C(r,i,o.ownerInstanceId);let s=$();return await v(r,{version:m,ownerInstanceId:s,state:"active"}),C(r,i,s)})}async function xt(t,e,n=process.env){return at(t,e,I(w(n)))}async function at(t,e,n){let i=y(t),r=T(n,i.expectedInstanceId,e);await A(r,async()=>{let o=await g(r);o===null||o.state==="ended"||(o.state==="active"&&(o={version:m,ownerInstanceId:o.ownerInstanceId,state:"pending"},await v(r,o)),await D(r,i,o.ownerInstanceId))})}export{xt as endNativeSession,at as endNativeSessionAtRoot,bt as nativeClientFor,st as nativeClientForAtRoot,T as nativeSessionRecordPath};
|