@npayload/sdk 5.1.0 → 6.1.1

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 (83) hide show
  1. package/README.md +12 -12
  2. package/dist/chunk-2U3QN6IU.mjs +1 -0
  3. package/dist/{chunk-ZDOLKWQD.mjs → chunk-2UJADZ6K.mjs} +1 -1
  4. package/dist/chunk-2ZK6PEZR.mjs +1 -0
  5. package/dist/chunk-3RE3BK3W.mjs +1 -0
  6. package/dist/chunk-4QKJIAQO.mjs +1 -0
  7. package/dist/chunk-64SVI75H.mjs +1 -0
  8. package/dist/chunk-7AZ3YJ62.mjs +1 -0
  9. package/dist/chunk-BPVBERWX.mjs +3 -0
  10. package/dist/chunk-C4LTBM2E.mjs +1 -0
  11. package/dist/chunk-CJIZRYGT.mjs +5 -0
  12. package/dist/{chunk-GG7UQYUV.mjs → chunk-EM46J3TV.mjs} +1 -1
  13. package/dist/chunk-ERQXEWTC.mjs +1 -0
  14. package/dist/chunk-F4F5GA36.mjs +9 -0
  15. package/dist/chunk-F5PMOFZY.mjs +1 -0
  16. package/dist/chunk-GEDYBXWJ.mjs +1 -0
  17. package/dist/chunk-HNHTAV57.mjs +1 -0
  18. package/dist/chunk-IA5ADBRQ.mjs +2 -0
  19. package/dist/chunk-IKKXOIJF.mjs +20 -0
  20. package/dist/chunk-IW34IJP4.mjs +1 -0
  21. package/dist/chunk-JWEUM2BU.mjs +1 -0
  22. package/dist/chunk-JYVB32D3.mjs +1 -0
  23. package/dist/chunk-K6H7MJ4W.mjs +1 -0
  24. package/dist/{chunk-M7WGBUJ2.mjs → chunk-MKQUL5LA.mjs} +1 -1
  25. package/dist/{chunk-HX6PH7C3.mjs → chunk-MYM6C3WY.mjs} +1 -1
  26. package/dist/chunk-NCKK7PHF.mjs +1 -0
  27. package/dist/{chunk-STS7CL74.mjs → chunk-NV6B7I6P.mjs} +1 -1
  28. package/dist/chunk-O2USGVDT.mjs +1 -0
  29. package/dist/chunk-O7KSYRUO.mjs +2 -0
  30. package/dist/chunk-OGXDRDCJ.mjs +1 -0
  31. package/dist/chunk-PX7FINE4.mjs +17 -0
  32. package/dist/chunk-QXEFKQAF.mjs +1 -0
  33. package/dist/chunk-ROYJNUAJ.mjs +4 -0
  34. package/dist/chunk-TOF3BORJ.mjs +5 -0
  35. package/dist/chunk-TYVWHQ4H.mjs +1 -0
  36. package/dist/chunk-VC3Y57EV.mjs +1 -0
  37. package/dist/chunk-VZZ4FDPO.mjs +1 -0
  38. package/dist/{chunk-ORT5FUFW.mjs → chunk-WLHCORNO.mjs} +1 -1
  39. package/dist/chunk-WWSPP7WV.mjs +1 -0
  40. package/dist/chunk-XAB3ANJT.mjs +22 -0
  41. package/dist/chunk-XF6XPU25.mjs +5 -0
  42. package/dist/chunk-XPZRF64T.mjs +1 -0
  43. package/dist/{chunk-YFFHEYYK.mjs → chunk-XVZEP6PT.mjs} +1 -1
  44. package/dist/chunk-YVGH2T7O.mjs +5 -0
  45. package/dist/{chunk-IH2OLS7G.mjs → chunk-Z24VZ6HI.mjs} +1 -1
  46. package/dist/chunk-ZYMM2PCZ.mjs +65 -0
  47. package/dist/cli/index.js +353 -336
  48. package/dist/cli/index.mjs +272 -257
  49. package/dist/index.d.mts +68 -9
  50. package/dist/index.d.ts +68 -9
  51. package/dist/index.js +2 -2
  52. package/dist/index.mjs +2 -2
  53. package/package.json +2 -2
  54. package/dist/chunk-2G46BKEC.mjs +0 -1
  55. package/dist/chunk-2WG7FETK.mjs +0 -22
  56. package/dist/chunk-5R5L7GTT.mjs +0 -17
  57. package/dist/chunk-5SMWYS7Z.mjs +0 -1
  58. package/dist/chunk-6R2QLUWE.mjs +0 -20
  59. package/dist/chunk-7IFTQ52O.mjs +0 -1
  60. package/dist/chunk-7QTR5IWG.mjs +0 -1
  61. package/dist/chunk-AECDYMA2.mjs +0 -1
  62. package/dist/chunk-AGDMCMF3.mjs +0 -1
  63. package/dist/chunk-BBHWYMQA.mjs +0 -1
  64. package/dist/chunk-C5EDDEPR.mjs +0 -1
  65. package/dist/chunk-CDA75PLA.mjs +0 -1
  66. package/dist/chunk-CFM43QNN.mjs +0 -64
  67. package/dist/chunk-GGXNXM73.mjs +0 -1
  68. package/dist/chunk-K3YY77PG.mjs +0 -3
  69. package/dist/chunk-KQCX2PCW.mjs +0 -1
  70. package/dist/chunk-LCUELOEE.mjs +0 -2
  71. package/dist/chunk-N6NIJISZ.mjs +0 -5
  72. package/dist/chunk-OA73YMB6.mjs +0 -6
  73. package/dist/chunk-ONTNXGOM.mjs +0 -1
  74. package/dist/chunk-R6DPWMZM.mjs +0 -1
  75. package/dist/chunk-TQFAYJEP.mjs +0 -4
  76. package/dist/chunk-TUWFD3AZ.mjs +0 -1
  77. package/dist/chunk-UDLS46F5.mjs +0 -1
  78. package/dist/chunk-VZT7RCAC.mjs +0 -4
  79. package/dist/chunk-WOMYXKGW.mjs +0 -5
  80. package/dist/chunk-X3CZMXOZ.mjs +0 -9
  81. package/dist/chunk-XLK55DEY.mjs +0 -1
  82. package/dist/chunk-YHUBO6K4.mjs +0 -1
  83. package/dist/chunk-YLV3KSNV.mjs +0 -1
@@ -0,0 +1 @@
1
+ import{a}from"./chunk-2UJADZ6K.mjs";import"./chunk-ZYMM2PCZ.mjs";import"./chunk-OGXDRDCJ.mjs";import"./chunk-ROYJNUAJ.mjs";import"./chunk-4NWQCPI4.mjs";import"./chunk-MYM6C3WY.mjs";import"./chunk-QXEFKQAF.mjs";import"./chunk-CJDCY2NH.mjs";import"./chunk-MKQUL5LA.mjs";import"./chunk-7AZ3YJ62.mjs";import"./chunk-YVGH2T7O.mjs";import"./chunk-IA5ADBRQ.mjs";import"./chunk-WWSPP7WV.mjs";import"./chunk-XF6XPU25.mjs";import"./chunk-XVZEP6PT.mjs";import"./chunk-JWEUM2BU.mjs";import"./chunk-O7KSYRUO.mjs";import"./chunk-BPVBERWX.mjs";import"./chunk-IW34IJP4.mjs";import"./chunk-HNHTAV57.mjs";import"./chunk-K6H7MJ4W.mjs";import"./chunk-LJNU5QHZ.mjs";export{a as projectAllPermissions};
@@ -0,0 +1,2 @@
1
+ import{e as Jn,f as Yn,g as Xn}from"./chunk-BPVBERWX.mjs";import{f as Wn,g as Gn,h as jn}from"./chunk-HNHTAV57.mjs";import{a as i}from"./chunk-LJNU5QHZ.mjs";import{webcrypto as G}from"crypto";import{inspect as es}from"util";var Wt="[REDACTED_DPOP_PRIVATE_JWK]",Ue=class{static{i(this,"DpopPrivateJwk")}#e;constructor(e){if(!e||typeof e!="object")throw new TypeError("DpopPrivateJwk requires a JsonWebKey");if(e.kty!=="EC"||e.crv!=="P-256")throw new TypeError(`DpopPrivateJwk requires kty=EC, crv=P-256 (got kty=${e.kty}, crv=${e.crv})`);if(typeof e.d!="string"||e.d.length===0)throw new TypeError("DpopPrivateJwk requires the private `d` field");this.#e=e}get publicJwk(){let{d:e,...n}=this.#e;return n}get crv(){return this.#e.crv}unsafeUse(e){return e(this.#e)}toJSON(){return Wt}[es.custom](){return Wt}toString(){return Wt}};function rt(t){return t instanceof Ue}i(rt,"isDpopPrivateJwk");var Gt=new TextEncoder;function ot(t){let e=t instanceof Uint8Array?t:new Uint8Array(t),n="";for(let r=0;r<e.length;r++)n+=String.fromCharCode(e[r]);return Buffer.from(n,"binary").toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}i(ot,"b64url");function Qn(t){return Buffer.from(t,"utf8").toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}i(Qn,"b64urlFromString");async function ts(t){let e=await G.subtle.digest("SHA-256",Gt.encode(t));return ot(e)}i(ts,"sha256B64Url");async function uc(){let t=await G.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign","verify"]),e=await G.subtle.exportKey("jwk",t.publicKey),n=await G.subtle.exportKey("jwk",t.privateKey);return{publicJwk:e,privateJwk:n}}i(uc,"generateDpopKeyPair");function ns(t){let e={EC:["kty","crv","x","y"],RSA:["kty","n","e"],OKP:["kty","crv","x"]},n=t,r=typeof t.kty=="string"?e[t.kty]:void 0;if(r){let d={};for(let l of r)n[l]!==void 0&&(d[l]=n[l]);return d}let{d:o,key_ops:s,ext:a,use:c,alg:u,...f}=n;return f}i(ns,"publicHalf");async function Zn(t){let e=t,n={EC:["crv","kty","x","y"],RSA:["e","kty","n"],OKP:["crv","kty","x"]},r=typeof e.kty=="string"?e.kty:"",o=n[r];if(!o)throw new TypeError(`jwkThumbprint: unsupported key type ${JSON.stringify(e.kty)}`);let s={};for(let c of o){if(typeof e[c]!="string"||e[c].length===0)throw new TypeError(`jwkThumbprint: the ${r} key carries no "${c}" member`);s[c]=e[c]}let a=await G.subtle.digest("SHA-256",Gt.encode(JSON.stringify(s)));return ot(a)}i(Zn,"jwkThumbprint");function rs(t){if(t)return t();let e=G.getRandomValues(new Uint8Array(16));return ot(e)}i(rs,"newJti");function os(t){try{let e=new URL(t);return e.hash="",e.search="",e.toString()}catch{return t}}i(os,"canonicalHtu");async function jt(t,e){let n=e.now?Math.floor(e.now()/1e3):Math.floor(Date.now()/1e3),r={typ:"dpop+jwt",alg:"ES256",jwk:ns(t.publicJwk)},o={htm:e.method.toUpperCase(),htu:os(e.url),iat:n,jti:rs(e.randomJti)};e.accessToken&&(o.ath=await ts(e.accessToken)),e.nonce&&(o.nonce=e.nonce);let s=Qn(JSON.stringify(r)),a=Qn(JSON.stringify(o)),c=`${s}.${a}`,u=await ss(t.privateJwk),f=await G.subtle.sign({name:"ECDSA",hash:"SHA-256"},u,Gt.encode(c));return`${c}.${ot(f)}`}i(jt,"signDpopProof");var zn=new WeakMap;async function ss(t){if(rt(t)){let e=zn.get(t);if(e)return e;let n=await t.unsafeUse(r=>G.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]));return zn.set(t,n),n}return G.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"])}i(ss,"resolveSigningKey");var C=class extends Error{static{i(this,"NPayloadError")}code;requestId;status;constructor(e,n){super(e),this.name=this.constructor.name,this.code=n.code,this.requestId=n.requestId,this.status=n.status}isRetryable(){return this.status==null?!1:this.status===408||this.status===429?!0:this.status>=500&&this.status<600}},z=class extends C{static{i(this,"AuthError")}},me=class extends C{static{i(this,"AuthScopeError")}isRetryable(){return!1}},ke=class extends C{static{i(this,"NotFoundError")}isRetryable(){return!1}},Z=class extends C{static{i(this,"ValidationError")}details;constructor(e,n){super(e,n),this.details=n.details}isRetryable(){return!1}},st=class extends C{static{i(this,"RateLimitedError")}retryAfterMs;constructor(e,n){super(e,n),this.retryAfterMs=n.retryAfterMs}isRetryable(){return!0}},it=class extends C{static{i(this,"ConflictError")}isRetryable(){return!1}},at=class extends C{static{i(this,"ServerError")}isRetryable(){return!0}},fe=class extends C{static{i(this,"NetworkError")}isRetryable(){return!0}},le=class extends C{static{i(this,"TimeoutError")}isRetryable(){return!0}},ct=class extends C{static{i(this,"PlanRequiredError")}product;upgradeUrl;constructor(e,n){super(e,{code:n.code,status:402,...n.requestId!==void 0?{requestId:n.requestId}:{}}),this.product=n.product,this.upgradeUrl=n.upgradeUrl}isRetryable(){return!1}},is=["source_network_not_allowed","source_network_not_declared"],as=["thumbprint_not_bound"];function ft(t){return typeof t=="string"&&is.includes(t.toLowerCase())}i(ft,"isSourceNotAllowedCode");function lt(t){return typeof t=="string"&&as.includes(t.toLowerCase())}i(lt,"isFingerprintNotEnrolledCode");function te(t){if(t===null||typeof t!="object")return;let e=t,n=e.error!==null&&typeof e.error=="object"?e.error:void 0;for(let r of[n?.code,e.code,typeof e.error=="string"?e.error:void 0,e.reason])if(ft(r)||lt(r))return r}i(te,"networkRuleCodeOf");var ee=class extends C{static{i(this,"SourceNotAllowedError")}reason;constructor(e,n){super(e,{code:n.code,status:n.status??403,...n.requestId!==void 0?{requestId:n.requestId}:{}}),this.reason=n.code.toLowerCase()==="source_network_not_declared"?"not_declared":"not_allowed"}isRetryable(){return!1}},V=class extends C{static{i(this,"FingerprintNotEnrolledError")}fingerprint;constructor(e,n){super(e,{code:n.code,status:n.status??403,...n.requestId!==void 0?{requestId:n.requestId}:{}}),this.fingerprint=n.fingerprint}isRetryable(){return!1}},er="npayload refused this call: it came from a network this app environment does not allow. An administrator can add the network in the dashboard under Settings > Security > Networks.",tr="npayload refused this call: this app environment has no network yet, so its keys cannot be used. An administrator can add one in the dashboard under Settings > Security > Networks.",nr=`npayload refused this call: this instance's key fingerprint is not enrolled for this API key. An administrator can open the key's window in the dashboard under Settings > Security > Networks: in Instances, choose "Allow new instances for one hour" on this API key. Then start this instance again.`,ut=class extends C{static{i(this,"CircuitOpenError")}isRetryable(){return!1}};var dt=class extends C{static{i(this,"ClockDriftError")}driftMs;maxDriftMs;constructor(e,n){let r=Math.round(Math.abs(e)/1e3);super(`local clock is ${r} s ${e>0?"behind":"ahead of"} the server (allowed skew ${Math.round(n/1e3)} s) \u2014 authenticated requests are refused until the clock is corrected`,{code:"clock_drift"}),this.driftMs=e,this.maxDriftMs=n}};function pt(t){let{status:e,body:n,headers:r}=t,o=r.get("x-request-id")??r.get("x-npayload-request-id")??us(n)??void 0,s=typeof n=="object"&&n!==null?n:null,a=be(cs(s)??ds(e)),c=be(Xt(s)??fs(e)),u={code:a,status:e,...o!==void 0?{requestId:o}:{}};if(e===402||a==="PLAN_REQUIRED"){let d=Jt(s),l=Yt(d?.product),y=Yt(d?.upgradePath)??Yt(d?.upgradeUrl);return new ct(c,{code:a,...o!==void 0?{requestId:o}:{},...l!==void 0?{product:l}:{},...y!==void 0?{upgradeUrl:y}:{}})}let f=ft(a)||lt(a)?a:te(s);if(f!==void 0&&ft(f)){let d=f.toLowerCase()==="source_network_not_declared";return new ee(be(Xt(s)??(d?tr:er)),{code:f,status:e,...o!==void 0?{requestId:o}:{}})}if(f!==void 0&&lt(f))return new V(be(Xt(s)??nr),{code:f,status:e,...o!==void 0?{requestId:o}:{}});switch(e){case 400:case 422:{let d=Jt(s);return new Z(c,{...u,...d!==void 0?{details:d}:{}})}case 401:return new z(c,u);case 403:{let d=Jt(s)?.reason;return a.toLowerCase().includes("scope")||typeof d=="string"&&d.toLowerCase().includes("scope")?new me(c,u):new z(c,u)}case 404:return new ke(c,u);case 409:return new it(c,u);case 429:{let d=ls(r,s);return new st(c,{...u,...d!==void 0?{retryAfterMs:d}:{}})}default:return e>=500&&e<600?new at(c,u):new C(c,u)}}i(pt,"errorFromResponse");function rr(t){if(t instanceof C)return t;if(t instanceof Error){let e=t.name;return e==="AbortError"?new le("Request aborted (timeout)",{code:"request_timeout"}):e==="TimeoutError"?new le("Request timed out",{code:"request_timeout"}):e==="TypeError"?new fe(`Network error: ${be(t.message)}`,{code:"network_error"}):new fe(be(t.message),{code:"network_error"})}return new fe("Unknown network error",{code:"network_error"})}i(rr,"errorFromException");function Pe(t){return t&&typeof t.error=="object"&&t.error!==null?t.error:void 0}i(Pe,"nestedError");function cs(t){if(!t)return null;let e=Pe(t);return e?.code?e.code:t.code?t.code:null}i(cs,"envelopeCode");function Jt(t){if(!t)return;let e=Pe(t)?.details;if(e&&typeof e=="object")return e;if(t.details&&typeof t.details=="object")return t.details}i(Jt,"envelopeDetails");function Yt(t){return typeof t=="string"&&t.length>0?t:void 0}i(Yt,"nonEmptyString");function Xt(t){if(!t)return null;let e=Pe(t);return e?.message?e.message:t.message?t.message:t.error_description?t.error_description:null}i(Xt,"envelopeMessage");function us(t){if(typeof t!="object"||t===null)return;let e=Pe(t);return e?.request_id??e?.requestId??t.request_id??t.requestId}i(us,"extractRequestId");function ds(t){switch(t){case 400:case 422:return"validation_error";case 401:return"unauthorized";case 402:return"payment_required";case 403:return"forbidden";case 404:return"not_found";case 409:return"conflict";case 429:return"rate_limited";default:return t>=500?"server_error":"request_failed"}}i(ds,"defaultCodeForStatus");function fs(t){return`Request failed with status ${t}`}i(fs,"defaultMessageForStatus");function ls(t,e){let n=t.get("retry-after");if(n){let s=Number(n);if(!Number.isNaN(s)&&s>=0)return Math.round(s*1e3);let a=Date.parse(n);if(!Number.isNaN(a)){let c=a-Date.now();if(c>0)return c}}let r=Pe(e),o=r?.retry_after_ms??r?.retryAfterMs??void 0;return typeof o=="number"&&o>=0?o:void 0}i(ls,"parseRetryAfterMs");function be(t){return t.replace(/\bBearer\s+[A-Za-z0-9._-]+/gi,"Bearer [REDACTED]").replace(/\bDPoP\s+[A-Za-z0-9._-]+/gi,"DPoP [REDACTED]").replace(/\bBasic\s+[A-Za-z0-9+/=._-]+/gi,"Basic [REDACTED]").replace(/\b[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\b/g,"[JWT_REDACTED]").replace(/(\b(?:Set-)?Cookie:\s*)[^;\r\n]+/gi,"$1[REDACTED]").replace(/("d"\s*:\s*")[^"]+(")/g,"$1[REDACTED]$2").replace(/(["']?(?:hmac|secret|token|api[_-]?key|auth[_-]?token|private[_-]?key|key)["']?\s*[:=]\s*["'])[^"']+(["'])/gi,"$1[REDACTED]$2").replace(/\b([A-Z][A-Z0-9_]*(?:TOKEN|KEY|SECRET|PASSWORD|PWD)[A-Z0-9_]*)=\S+/g,"$1=[REDACTED]")}i(be,"redactSecretLike");var or=3e4,Et=class{static{i(this,"KernelAuthState")}config;fetchImpl;now;cache=null;inflight=new Map;nonces=new Map;fingerprintPromise;constructor(e){this.config=e,this.fetchImpl=e.fetch??globalThis.fetch,this.now=e.now??Date.now}async getAccessToken(e){let n=this.config.refreshMarginMs??or,r=this.cache;if(r&&r.expiresAt-this.now()>n&&ht(r.scopes,e))return Qt(r);let o=hs(e),s=this.inflight.get(o);if(s)return Qt(await s);let a=this.fetchToken(e);this.inflight.set(o,a);try{let c=await a;return Qt(c)}finally{this.inflight.get(o)===a&&this.inflight.delete(o)}}async signDpopProof(e){let n=ps(e.url),r=n?this.nonces.get(n):void 0,o={method:e.method,url:e.url,...e.accessToken?{accessToken:e.accessToken}:{},...r?{nonce:r}:{},now:this.now};return jt(this.config.keys,o)}async requireScope(e){let n=await this.getAccessToken([e]);if(!ht(n.scopes,[e]))throw new me(`Missing required scope: ${e}. Granted: ${n.scopes.join(",")}`,{code:"insufficient_scope",status:403})}cacheNonce(e,n){this.nonces.set(e,n)}peekCache(){return this.cache}invalidate(){this.cache=null}fingerprint(){return this.fingerprintPromise||(this.fingerprintPromise=Zn(this.config.keys.publicJwk).catch(e=>{throw this.fingerprintPromise=void 0,e})),this.fingerprintPromise}async fetchToken(e){let n=this.config.authServerUrl,r=await jt(this.config.keys,{method:"POST",url:n,now:this.now}),o=new URLSearchParams({grant_type:"client_credentials",client_id:this.config.clientId,scope:e.join(" ")});this.config.appId&&o.set("app_id",this.config.appId),this.config.env&&o.set("env_id",this.config.env),this.config.clientSecret&&o.set("client_secret",this.config.clientSecret);let s=await this.fetchImpl(n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",DPoP:r},body:o.toString()});if(!s.ok){let g={};try{g=await s.json()}catch{}let b=typeof g.error=="object"&&g.error!==null?g.error:void 0,A=typeof g.error=="string"?g.error:void 0;if(te(g)!==void 0){let L=pt({status:s.status,body:g,headers:s.headers??new Headers});if(L instanceof V){let v=await this.fingerprint().catch(()=>{});throw new V(L.message,{code:L.code,...L.status!==void 0?{status:L.status}:{},...L.requestId!==void 0?{requestId:L.requestId}:{},...v!==void 0?{fingerprint:v}:{}})}if(L instanceof ee)throw L}throw new z(g.error_description??A??b?.message??`OAuth token request failed (${s.status})`,{code:A??b?.code??"oauth_failed",status:s.status})}let a=await s.json();if(!a.access_token)throw new z("OAuth token response missing access_token",{code:"oauth_missing_token"});if(a.token_type&&a.token_type.toLowerCase()!=="dpop")throw new C(`Refusing non-DPoP token (got ${a.token_type})`,{code:"non_dpop_token"});let c=this.now()+(a.expires_in??600)*1e3,u=a.scope?a.scope.split(/\s+/).filter(Boolean):Array.from(e),f={token:a.access_token,expiresAt:c,scopes:u},d=this.cache,l=this.config.refreshMarginMs??or;return d&&d.expiresAt-this.now()>l&&!ht(f.scopes,d.scopes)||(this.cache=f),f}};function Qt(t){return{token:t.token,tokenType:"DPoP",expiresAt:t.expiresAt,scopes:t.scopes}}i(Qt,"toAccessToken");function Rc(t,e){return ht(t,[e])}i(Rc,"scopesCover");function ht(t,e){return t.includes("*")?!0:e.every(n=>Wn(t,n)||jn(t,n)||Gn(t,n))}i(ht,"hasAllScopes");function ps(t){try{return new URL(t).origin}catch{return null}}i(ps,"safeOrigin");function hs(t){return[...t].sort().join(" ")}i(hs,"scopeKey");var Es="NPAYLOAD_TEST_RESTART_WINDOW_MS";function ir(t=globalThis.process?.env){if(!t||t.VITEST!=="true")return;let e=t[Es];if(e===void 0||e==="")return;let n=Number(e);return Number.isFinite(n)&&n>=0?n:void 0}i(ir,"harnessRestartWindowMs");function sr(t,e,n){let r=0;for(let o=0;o<e;o++){let s=Math.min(o,8);r+=gt(Math.round(t*2**s*.8),0,n)}return r}i(sr,"lowestScheduleSum");function ar(t,e,n=3e4){let r=Math.max(0,t-1);if(r===0||e<=0)return 200;let o=Math.ceil(n/.8);if(sr(o,r,n)<e)return o;let s=1,a=o;for(;s<a;){let c=Math.floor((s+a)/2);sr(c,r,n)>=e?a=c:s=c+1}return s}i(ar,"baseDelayForWindow");var cr=new Set([408,425,429,500,502,503,504]);function wt(t){let e=t.maxAttempts??5,n=t.attempt,r=t.status,o=t.jitter??Math.random,s=t.now??Date.now;if(n>=e)return{retryable:!1,delayMs:0,attempt:n,reason:`max attempts reached (${e})`};if(r!==void 0&&!cr.has(r)&&!(r>=500&&r<600))return{retryable:!1,delayMs:0,attempt:n,reason:`non-retryable status ${r}`};let a=gs(t.retryAfterHeader,s);if(a!==void 0)return{retryable:!0,delayMs:gt(a,0,3e4),attempt:n,reason:"retry-after header"};if(t.retryAfterMs!==void 0&&t.retryAfterMs>=0)return{retryable:!0,delayMs:gt(t.retryAfterMs,0,3e4),attempt:n,reason:"retry-after envelope"};let u=(t.restartWindowMs!==void 0?ar(e,t.restartWindowMs):200)*2**Math.min(n-1,8),f=1+(o()*.4-.2),d=gt(Math.round(u*f),0,3e4),l=r!==void 0?`status ${r}`:"transport error";return{retryable:!0,delayMs:d,attempt:n,reason:`${l} (backoff)`}}i(wt,"defaultRetryPolicy");function gs(t,e){if(!t)return;let n=Number(t);if(!Number.isNaN(n)&&n>=0)return Math.round(n*1e3);let r=Date.parse(t);if(!Number.isNaN(r)){let o=r-e();return o>0?o:0}}i(gs,"parseRetryAfter");function gt(t,e,n){return Math.max(e,Math.min(n,t))}i(gt,"clamp");function zt(t){return cr.has(t)||t>=500&&t<600}i(zt,"isRetryableStatus");var ws=5,ys=3e4,pe=class{static{i(this,"KernelCircuitBreaker")}hosts=new Map;threshold;probeAfterMs;now;openHandlers=new Set;closeHandlers=new Set;deferUntil=new Map;constructor(e={}){this.threshold=e.failureThreshold??ws,this.probeAfterMs=e.probeAfterMs??ys,this.now=e.now??Date.now}shouldAllow(e){let n=this.get(e);if(n.state==="closed")return!0;if(n.state==="open"){let r=n.openedAt??this.now();return this.now()-r>=this.probeAfterMs?(n.state="half-open",n.probeInFlight=!0,!0):!1}return n.probeInFlight?!1:(n.probeInFlight=!0,!0)}onOpen(e){return this.openHandlers.add(e),()=>{this.openHandlers.delete(e)}}onClose(e){return this.closeHandlers.add(e),()=>{this.closeHandlers.delete(e)}}noteRateLimit(e,n){this.deferUntil.set(e,n)}rateLimitedUntil(e){let n=this.deferUntil.get(e);if(n!==void 0){if(n<=this.now()){this.deferUntil.delete(e);return}return n}}fire(e,n){for(let r of e)try{r(n)}catch{}}recordSuccess(e){let n=this.get(e),r=n.state!=="closed";n.state="closed",n.failures=0,delete n.openedAt,delete n.lastFailureAt,n.probeInFlight=!1,r&&this.fire(this.closeHandlers,e)}recordFailure(e,n){let r=this.get(e);if(r.probeInFlight=!1,n===void 0||n>=500){if(r.lastFailureAt=this.now(),r.state==="half-open"){r.state="open",r.openedAt=this.now(),this.fire(this.openHandlers,e);return}r.failures+=1,r.failures>=this.threshold&&(r.state="open",r.openedAt=this.now(),this.fire(this.openHandlers,e))}}state(e){let n=this.get(e),r={state:n.state,failures:n.failures};return n.openedAt!==void 0&&n.lastFailureAt!==void 0?{...r,openedAt:n.openedAt,lastFailureAt:n.lastFailureAt}:n.openedAt!==void 0?{...r,openedAt:n.openedAt}:n.lastFailureAt!==void 0?{...r,lastFailureAt:n.lastFailureAt}:r}guard(e){if(!this.shouldAllow(e))throw new ut(`Circuit open for ${e}`,{code:"circuit_open"})}get(e){let n=this.hosts.get(e);return n||(n={state:"closed",failures:0,probeInFlight:!1},this.hosts.set(e,n)),n}};import{randomBytes as ms}from"crypto";function he(t=Date.now){let n=BigInt(t()).toString(16).padStart(12,"0"),r=ms(10),o=(r[0]&15|112).toString(16).padStart(2,"0")+r[1].toString(16).padStart(2,"0"),s=(r[2]&63|128).toString(16).padStart(2,"0")+r[3].toString(16).padStart(2,"0")+r[4].toString(16).padStart(2,"0")+r[5].toString(16).padStart(2,"0")+r[6].toString(16).padStart(2,"0")+r[7].toString(16).padStart(2,"0")+r[8].toString(16).padStart(2,"0")+r[9].toString(16).padStart(2,"0");return[n.slice(0,8),n.slice(8,12),o,s.slice(0,4),s.slice(4,16)].join("-")}i(he,"newIdempotencyKey");var bs=new Set(["POST","PUT","PATCH","DELETE"]);function Rs(t,e){let n=e.toLowerCase();return Object.keys(t).some(r=>r.toLowerCase()===n)}i(Rs,"hasHeader");function Ls(t,e){if(!t)return{};if(!e)return{...t};let n=e.toLowerCase();return Object.fromEntries(Object.entries(t).filter(([r])=>r.toLowerCase()!==n))}i(Ls,"withoutHeader");function _s(t,e){if(!t)return;let n=e.toLowerCase();for(let[r,o]of Object.entries(t))if(r.toLowerCase()===n&&typeof o=="string"&&o!=="")return o}i(_s,"headerValue");function Ss(t){return new Promise(e=>setTimeout(e,t))}i(Ss,"defaultSleep");async function Ts(t,e){if(e?.aborted)throw e.reason??new DOMException("Aborted","AbortError");return e?new Promise((n,r)=>{let o=setTimeout(()=>{e.removeEventListener("abort",s),n()},t),s=i(()=>{clearTimeout(o),r(e.reason??new DOMException("Aborted","AbortError"))},"onAbort");e.addEventListener("abort",s,{once:!0})}):Ss(t)}i(Ts,"abortableSleep");function As(t){try{return new URL(t).host}catch{return t}}i(As,"hostOf");function vs(t){try{return new URL(t).origin}catch{return t}}i(vs,"originOf");function ur(t){if(!t)return null;let e=/\bnonce="([^"]+)"/.exec(t);return e?e[1]:null}i(ur,"readNonceFromHeader");async function Zt(t){try{if((t.headers.get("content-type")??"").includes("application/json"))return await t.json();let n=await t.text();if(!n)return null;try{return JSON.parse(n)}catch{return n}}catch{return null}}i(Zt,"readResponseBody");function Ns(t,e=Date.now){let n={},r=t.get("x-ratelimit-remaining");r!==null&&r.trim()!==""&&!Number.isNaN(Number(r))&&(n.remaining=Number(r));let o=t.get("x-ratelimit-reset");if(o!==null&&o.trim()!==""&&!Number.isNaN(Number(o))){let a=Number(o);n.resetAt=a>1e12?a:a*1e3}let s=t.get("retry-after");if(s!==null&&s.trim()!==""){let a=Number(s);if(!Number.isNaN(a))n.retryAfterMs=Math.max(0,a*1e3);else{let c=Date.parse(s);Number.isNaN(c)||(n.retryAfterMs=Math.max(0,c-e()))}}return n}i(Ns,"parseRateLimit");function Cs(t){return t.get("x-request-id")??t.get("x-npayload-request-id")}i(Cs,"requestIdOf");async function en(t,e){let n=t.fetchImpl??globalThis.fetch,r=t.circuit??new pe,o=t.sleep??((v,S)=>Ts(v,S)),s=t.now??Date.now,a=t.httpClient,c=a?async(v,S)=>a.fetch({method:S.method,url:v,headers:S.headers,body:S.body,...S.signal?{signal:S.signal}:{}}):async(v,S)=>n(v,t.dispatcher?{...S,dispatcher:t.dispatcher}:S),u=As(e.url),f=e.method.toUpperCase(),l=bs.has(f)?e.idempotencyKey??_s(e.headers,"Idempotency-Key")??he():null;e.scope&&await t.auth.requireScope(e.scope);let y=0,E=!0,g=!0,b=!0;r.guard(u);let A=e.restartWindowMs??ir()??6e4,L=null;try{for(;;){y+=1;let v=r.rateLimitedUntil(u);if(v!==void 0){let I=v-s();I>0&&await o(I,e.signal)}t.clockDrift?.check();let S=await t.auth.getAccessToken(e.scope?[e.scope]:[]),N=await t.auth.signDpopProof({method:f,url:e.url,accessToken:S.token}),x={...Ls(e.headers,l?"Idempotency-Key":void 0),Authorization:`DPoP ${S.token}`,DPoP:N,Accept:"application/json"};if(l&&(x["Idempotency-Key"]=l),e.traceparent&&(x.traceparent=e.traceparent),e.tracestate&&(x.tracestate=e.tracestate),e.body!=null&&!Rs(x,"content-type")&&(x["Content-Type"]="application/json"),e.signal?.aborted)throw e.signal.reason??new DOMException("Aborted","AbortError");let _=e.timeoutMs!=null&&e.timeoutMs>0?AbortSignal.timeout(e.timeoutMs):void 0,R=[e.signal,_].filter(I=>I!=null),T=R.length>1?AbortSignal.any(R):R[0],p;try{p=await c(e.url,{method:f,headers:x,body:e.body??null,...T?{signal:T}:{}})}catch(I){if(I instanceof Error&&I.name==="AbortError")throw I;let tt=I instanceof Error&&I.name==="TimeoutError",nt=wt({attempt:y,...e.maxAttempts!==void 0?{maxAttempts:e.maxAttempts}:{},restartWindowMs:A});if(L={},nt.retryable){t.onRetry?.({attempt:y,reason:nt.reason,nextDelayMs:nt.delayMs}),await o(nt.delayMs,e.signal);continue}throw tt?new le(`Request timed out after ${e.timeoutMs}ms`,{code:"timeout"}):rr(I)}if(p.status===401&&E){let I=p.headers.get("www-authenticate"),tt=ur(I);if(tt){t.auth.cacheNonce(vs(e.url),tt),E=!1,y-=1;continue}}let P;if(p.status===401&&g&&!ur(p.headers.get("www-authenticate"))&&(P={body:await Zt(p)},te(P.body)===void 0)){g=!1,t.auth.invalidate();continue}t.clockDrift?.observe(p.headers.get("date"),s());let U=Ns(p.headers,s);U.remaining===0&&(U.resetAt!==void 0?r.noteRateLimit(u,U.resetAt):U.retryAfterMs!==void 0&&r.noteRateLimit(u,s()+U.retryAfterMs),t.onRateLimit?.(U));let et=Cs(p.headers);if(p.status>=200&&p.status<300)return r.recordSuccess(u),{data:await Zt(p),response:p,idempotencyKey:l,requestId:et,rateLimit:U};let Zo=P!==void 0?P.body:await Zt(p),M=pt({status:p.status,body:Zo,headers:p.headers,url:e.url});if(L={status:p.status},M instanceof ee&&b){b=!1,t.auth.peekCache()?.token===S.token&&t.auth.invalidate();continue}if(M instanceof V&&M.fingerprint===void 0){let I=await t.auth.fingerprint().catch(()=>{});M=new V(M.message,{code:M.code,...M.status!==void 0?{status:M.status}:{},...M.requestId!==void 0?{requestId:M.requestId}:{},...I!==void 0?{fingerprint:I}:{}})}if(zt(p.status)){let I=wt({attempt:y,status:p.status,retryAfterHeader:p.headers.get("retry-after"),...e.maxAttempts!==void 0?{maxAttempts:e.maxAttempts}:{},restartWindowMs:A});if(I.retryable){t.onRetry?.({attempt:y,reason:I.reason,nextDelayMs:I.delayMs}),await o(I.delayMs,e.signal);continue}}throw M instanceof C?M:new C(String(M),{code:"unknown"})}}catch(v){throw L&&r.recordFailure(u,L.status),v}}i(en,"kernelSend");import{promises as fr}from"dns";import{isIP as lr}from"net";import*as rn from"tls";import{Agent as Os,Dispatcher as Is,ProxyAgent as Ds,buildConnector as Us,interceptors as ks}from"undici";var pr=20,hr=3e4,Er=1e4,Ps=250;function gr(t,e,n){if(!n)return!1;let r=t.toLowerCase();for(let o of n.split(/[\s,]+/)){let s=o.trim().toLowerCase();if(!s)continue;if(s==="*")return!0;let[a,c]=s.startsWith("[")?[s.slice(0,s.indexOf("]")+1),s.slice(s.indexOf("]")+2)]:s.split(":"),u=a.startsWith(".")?a.slice(1):a;if((r===u||r.endsWith(`.${u}`))&&!(c&&c!==e))return!0}return!1}i(gr,"noProxyMatches");function tn(t,...e){for(let n of e){let r=t[n];if(r&&r.trim())return r.trim()}}i(tn,"pick");function wr(t,e){let n=t.port||(t.protocol==="https:"?"443":"80");if(gr(t.hostname,n,tn(e,"NO_PROXY","no_proxy")))return;let r=t.protocol==="https:"?tn(e,"HTTPS_PROXY","https_proxy","ALL_PROXY","all_proxy"):tn(e,"HTTP_PROXY","http_proxy","ALL_PROXY","all_proxy");if(r)try{return new URL(r).origin}catch{return}}i(wr,"proxyFor");function xs(t){return typeof t=="string"?new URL(t):t}i(xs,"originUrl");var nn,yr=i(async t=>{nn??=new fr.Resolver({timeout:2e3,tries:2});let[e,n]=await Promise.allSettled([nn.resolve4(t,{ttl:!0}),nn.resolve6(t,{ttl:!0})]),r=[];if(e.status==="fulfilled")for(let s of e.value)r.push({address:s.address,family:4,ttlMs:s.ttl*1e3});if(n.status==="fulfilled")for(let s of n.value)r.push({address:s.address,family:6,ttlMs:s.ttl*1e3});return r.length>0?r:(await fr.lookup(t,{all:!0})).map(s=>({address:s.address,family:s.family===6?6:4,ttlMs:0}))},"resolveWithServerTtl");function Ms(){let t=rn;return typeof t.getCACertificates=="function"?t.getCACertificates("default"):rn.rootCertificates}i(Ms,"defaultTrustStore");var xe=class extends Is{static{i(this,"KernelDispatcher")}pool;tunnels=new Map;env;connections;tlsMin;ca;allowH2;constructor(e={}){super(),this.connections=e.connections??pr,this.tlsMin=e.tlsMin??"TLSv1.3",this.ca=e.ca,this.allowH2=e.allowH2??!0,this.env=e.env??process.env;let n=e.dns?.lookup??yr,r=new Map,o=new WeakMap,s=ks.dns({maxTTL:e.dns?.maxTtlMs??Er,dualStack:!0,lookup:i((u,f,d)=>{n(u.hostname).then(l=>{for(let y of l)r.set(y.address,l);d(null,l.map(y=>({address:y.address,family:y.family,ttl:y.ttlMs})))},l=>d(l instanceof Error?l:new Error(String(l)),[]))},"lookup")}),a=Us({...this.tlsOptions(),allowH2:this.allowH2}),c=i((u,f)=>{let d=r.get(u.hostname),l=lr(u.hostname)===6?6:4,y=(d&&o.get(d))??l,E=d?.find(N=>N.family!==y)?.address;if(d===void 0||E===void 0)return a(u,f);let g=[y===l?u.hostname:d.find(N=>N.family===y).address,E],b=[],A=!1,L=0,v,S=i(()=>{let N=g[b.length],x=a({...u,hostname:N},(_,R)=>{if(A)return void R?.destroy();if(_){L+=1,L===g.length?(A=!0,f(_,null)):b.length<g.length&&(clearTimeout(v),S());return}A=!0,clearTimeout(v),o.set(d,lr(N)===6?6:4);for(let T of b)T!==R&&T.destroy();f(null,R)});b.push(x)},"attempt");S(),v=setTimeout(()=>{!A&&b.length<g.length&&S()},Ps)},"connect");this.pool=new Os({connections:this.connections,pipelining:1,keepAliveTimeout:e.keepAliveTimeoutMs??hr,allowH2:this.allowH2,connect:c}).compose(s)}tlsOptions(){return this.ca!==void 0?{minVersion:this.tlsMin,ca:[...Ms(),...this.ca]}:{minVersion:this.tlsMin}}dispatch(e,n){if(e.origin===void 0)return this.pool.dispatch(e,n);let r=xs(e.origin),o=wr(r,this.env);if(!o)return this.pool.dispatch(e,n);if(r.protocol==="http:")return this.pool.dispatch({...e,origin:o,path:`${r.origin}${e.path}`},n);let s=this.tunnels.get(o);return s||(s=new Ds({uri:o,connections:this.connections,allowH2:this.allowH2,proxyTls:{minVersion:this.tlsMin},requestTls:this.tlsOptions()}),this.tunnels.set(o,s)),s.dispatch(e,n)}everyDispatcher(){return[this.pool,...this.tunnels.values()]}close(e){let n=Promise.all(this.everyDispatcher().map(r=>r.close())).then(()=>{this.tunnels.clear()});if(e){n.then(e,e);return}return n}destroy(e,n){let r=typeof e=="function"?null:e??null,o=typeof e=="function"?e:n,s=Promise.all(this.everyDispatcher().map(a=>a.destroy(r))).then(()=>{this.tunnels.clear()});if(o){s.then(o,o);return}return s}};var mr=6e4,Me=class{static{i(this,"ClockDriftGuard")}maxDriftMs;drift;constructor(e=mr){this.maxDriftMs=e}get driftMs(){return this.drift}observe(e,n){if(!e)return;let r=Date.parse(e);Number.isNaN(r)||(this.drift=r-n)}check(){if(this.drift!==void 0&&Math.abs(this.drift)>this.maxDriftMs)throw new dt(this.drift,this.maxDriftMs)}};import{AsyncLocalStorage as js}from"async_hooks";var j="1.9.1";var br=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function Bs(t){let e=new Set([t]),n=new Set,r=t.match(br);if(!r)return()=>!1;let o={major:+r[1],minor:+r[2],patch:+r[3],prerelease:r[4]};if(o.prerelease!=null)return i(function(u){return u===t},"isExactmatch");function s(c){return n.add(c),!1}i(s,"_reject");function a(c){return e.add(c),!0}return i(a,"_accept"),i(function(u){if(e.has(u))return!0;if(n.has(u))return!1;let f=u.match(br);if(!f)return s(u);let d={major:+f[1],minor:+f[2],patch:+f[3],prerelease:f[4]};return d.prerelease!=null||o.major!==d.major?s(u):o.major===0?o.minor===d.minor&&o.patch<=d.patch?a(u):s(u):o.minor<=d.minor?a(u):s(u)},"isCompatible")}i(Bs,"_makeCompatibilityCheck");var Rr=Bs(j);var $s=j.split(".")[0],Be=Symbol.for(`opentelemetry.js.api.${$s}`),$e=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{};function Re(t,e,n,r=!1){var o;let s=$e[Be]=(o=$e[Be])!==null&&o!==void 0?o:{version:j};if(!r&&s[t]){let a=new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${t}`);return n.error(a.stack||a.message),!1}if(s.version!==j){let a=new Error(`@opentelemetry/api: Registration of version v${s.version} for ${t} does not match previously registered API v${j}`);return n.error(a.stack||a.message),!1}return s[t]=e,n.debug(`@opentelemetry/api: Registered a global for ${t} v${j}.`),!0}i(Re,"registerGlobal");function J(t){var e,n;let r=(e=$e[Be])===null||e===void 0?void 0:e.version;if(!(!r||!Rr(r)))return(n=$e[Be])===null||n===void 0?void 0:n[t]}i(J,"getGlobal");function Le(t,e){e.debug(`@opentelemetry/api: Unregistering a global for ${t} v${j}.`);let n=$e[Be];n&&delete n[t]}i(Le,"unregisterGlobal");var yt=class{static{i(this,"DiagComponentLogger")}constructor(e){this._namespace=e.namespace||"DiagComponentLogger"}debug(...e){return Ke("debug",this._namespace,e)}error(...e){return Ke("error",this._namespace,e)}info(...e){return Ke("info",this._namespace,e)}warn(...e){return Ke("warn",this._namespace,e)}verbose(...e){return Ke("verbose",this._namespace,e)}};function Ke(t,e,n){let r=J("diag");if(r)return r[t](e,...n)}i(Ke,"logProxy");var k;(function(t){t[t.NONE=0]="NONE",t[t.ERROR=30]="ERROR",t[t.WARN=50]="WARN",t[t.INFO=60]="INFO",t[t.DEBUG=70]="DEBUG",t[t.VERBOSE=80]="VERBOSE",t[t.ALL=9999]="ALL"})(k||(k={}));function Lr(t,e){t<k.NONE?t=k.NONE:t>k.ALL&&(t=k.ALL),e=e||{};function n(r,o){let s=e[r];return typeof s=="function"&&t>=o?s.bind(e):function(){}}return i(n,"_filterFunc"),{error:n("error",k.ERROR),warn:n("warn",k.WARN),info:n("info",k.INFO),debug:n("debug",k.DEBUG),verbose:n("verbose",k.VERBOSE)}}i(Lr,"createLogLevelDiagLogger");var Ks="diag",ne=class t{static{i(this,"DiagAPI")}static instance(){return this._instance||(this._instance=new t),this._instance}constructor(){function e(o){return function(...s){let a=J("diag");if(a)return a[o](...s)}}i(e,"_logProxy");let n=this,r=i((o,s={logLevel:k.INFO})=>{var a,c,u;if(o===n){let l=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return n.error((a=l.stack)!==null&&a!==void 0?a:l.message),!1}typeof s=="number"&&(s={logLevel:s});let f=J("diag"),d=Lr((c=s.logLevel)!==null&&c!==void 0?c:k.INFO,o);if(f&&!s.suppressOverrideMessage){let l=(u=new Error().stack)!==null&&u!==void 0?u:"<failed to generate stacktrace>";f.warn(`Current logger will be overwritten from ${l}`),d.warn(`Current logger will overwrite one already registered from ${l}`)}return Re("diag",d,n,!0)},"setLogger");n.setLogger=r,n.disable=()=>{Le(Ks,n)},n.createComponentLogger=o=>new yt(o),n.verbose=e("verbose"),n.debug=e("debug"),n.info=e("info"),n.warn=e("warn"),n.error=e("error")}};function sn(t){return Symbol.for(t)}i(sn,"createContextKey");var on=class t{static{i(this,"BaseContext")}constructor(e){let n=this;n._currentContext=e?new Map(e):new Map,n.getValue=r=>n._currentContext.get(r),n.setValue=(r,o)=>{let s=new t(n._currentContext);return s._currentContext.set(r,o),s},n.deleteValue=r=>{let o=new t(n._currentContext);return o._currentContext.delete(r),o}}},He=new on;var mt=class{static{i(this,"NoopContextManager")}active(){return He}with(e,n,r,...o){return n.call(r,...o)}bind(e,n){return n}enable(){return this}disable(){return this}};var an="context",Hs=new mt,re=class t{static{i(this,"ContextAPI")}constructor(){}static getInstance(){return this._instance||(this._instance=new t),this._instance}setGlobalContextManager(e){return Re(an,e,ne.instance())}active(){return this._getContextManager().active()}with(e,n,r,...o){return this._getContextManager().with(e,n,r,...o)}bind(e,n){return this._getContextManager().bind(e,n)}_getContextManager(){return J(an)||Hs}disable(){this._getContextManager().disable(),Le(an,ne.instance())}};var bt;(function(t){t[t.NONE=0]="NONE",t[t.SAMPLED=1]="SAMPLED"})(bt||(bt={}));var cn="0000000000000000",un="00000000000000000000000000000000",_r={traceId:un,spanId:cn,traceFlags:bt.NONE};var q=class{static{i(this,"NonRecordingSpan")}constructor(e=_r){this._spanContext=e}spanContext(){return this._spanContext}setAttribute(e,n){return this}setAttributes(e){return this}addEvent(e,n){return this}addLink(e){return this}addLinks(e){return this}setStatus(e){return this}updateName(e){return this}end(e){}isRecording(){return!1}recordException(e,n){}};var dn=sn("OpenTelemetry Context Key SPAN");function Rt(t){return t.getValue(dn)||void 0}i(Rt,"getSpan");function Sr(){return Rt(re.getInstance().active())}i(Sr,"getActiveSpan");function Fe(t,e){return t.setValue(dn,e)}i(Fe,"setSpan");function Tr(t){return t.deleteValue(dn)}i(Tr,"deleteSpan");function Ar(t,e){return Fe(t,new q(e))}i(Ar,"setSpanContext");function Lt(t){var e;return(e=Rt(t))===null||e===void 0?void 0:e.spanContext()}i(Lt,"getSpanContext");var _t=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1]);function vr(t,e){if(typeof t!="string"||t.length!==e)return!1;let n=0;for(let r=0;r<t.length;r+=4)n+=(_t[t.charCodeAt(r)]|0)+(_t[t.charCodeAt(r+1)]|0)+(_t[t.charCodeAt(r+2)]|0)+(_t[t.charCodeAt(r+3)]|0);return n===e}i(vr,"isValidHex");function Fs(t){return vr(t,32)&&t!==un}i(Fs,"isValidTraceId");function Vs(t){return vr(t,16)&&t!==cn}i(Vs,"isValidSpanId");function St(t){return Fs(t.traceId)&&Vs(t.spanId)}i(St,"isSpanContextValid");function Nr(t){return new q(t)}i(Nr,"wrapSpanContext");var fn=re.getInstance(),_e=class{static{i(this,"NoopTracer")}startSpan(e,n,r=fn.active()){if(!!n?.root)return new q;let s=r&&Lt(r);return qs(s)&&St(s)?new q(s):new q}startActiveSpan(e,n,r,o){let s,a,c;if(arguments.length<2)return;arguments.length===2?c=n:arguments.length===3?(s=n,c=r):(s=n,a=r,c=o);let u=a??fn.active(),f=this.startSpan(e,s,u),d=Fe(u,f);return fn.with(d,c,void 0,f)}};function qs(t){return t!==null&&typeof t=="object"&&"spanId"in t&&typeof t.spanId=="string"&&"traceId"in t&&typeof t.traceId=="string"&&"traceFlags"in t&&typeof t.traceFlags=="number"}i(qs,"isSpanContext");var Ws=new _e,Tt=class{static{i(this,"ProxyTracer")}constructor(e,n,r,o){this._provider=e,this.name=n,this.version=r,this.options=o}startSpan(e,n,r){return this._getTracer().startSpan(e,n,r)}startActiveSpan(e,n,r,o){let s=this._getTracer();return Reflect.apply(s.startActiveSpan,s,arguments)}_getTracer(){if(this._delegate)return this._delegate;let e=this._provider.getDelegateTracer(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):Ws}};var At=class{static{i(this,"NoopTracerProvider")}getTracer(e,n,r){return new _e}};var Gs=new At,Ve=class{static{i(this,"ProxyTracerProvider")}getTracer(e,n,r){var o;return(o=this.getDelegateTracer(e,n,r))!==null&&o!==void 0?o:new Tt(this,e,n,r)}getDelegate(){var e;return(e=this._delegate)!==null&&e!==void 0?e:Gs}setDelegate(e){this._delegate=e}getDelegateTracer(e,n,r){var o;return(o=this._delegate)===null||o===void 0?void 0:o.getTracer(e,n,r)}};var qe;(function(t){t[t.INTERNAL=0]="INTERNAL",t[t.SERVER=1]="SERVER",t[t.CLIENT=2]="CLIENT",t[t.PRODUCER=3]="PRODUCER",t[t.CONSUMER=4]="CONSUMER"})(qe||(qe={}));var Se;(function(t){t[t.UNSET=0]="UNSET",t[t.OK=1]="OK",t[t.ERROR=2]="ERROR"})(Se||(Se={}));var vt=re.getInstance();var ln="trace",Nt=class t{static{i(this,"TraceAPI")}constructor(){this._proxyTracerProvider=new Ve,this.wrapSpanContext=Nr,this.isSpanContextValid=St,this.deleteSpan=Tr,this.getSpan=Rt,this.getActiveSpan=Sr,this.getSpanContext=Lt,this.setSpan=Fe,this.setSpanContext=Ar}static getInstance(){return this._instance||(this._instance=new t),this._instance}setGlobalTracerProvider(e){let n=Re(ln,this._proxyTracerProvider,ne.instance());return n&&this._proxyTracerProvider.setDelegate(e),n}getTracerProvider(){return J(ln)||this._proxyTracerProvider}getTracer(e,n){return this.getTracerProvider().getTracer(e,n)}disable(){Le(ln,ne.instance()),this._proxyTracerProvider=new Ve}};var Ct=Nt.getInstance();var Or="@npayload/sdk",pn=class{static{i(this,"AsyncLocalStorageContextManager")}storage=new js;active(){return this.storage.getStore()??He}with(e,n,r,...o){return this.storage.run(e,()=>n.call(r,...o))}bind(e,n){if(typeof n!="function")return n;let r=this,o=n;return function(...s){return r.with(e,()=>o.apply(this,s))}}enable(){return this}disable(){return this.storage.disable(),this}},Cr=!1;function Js(){let t=Ct.getTracerProvider(),n=(typeof t.getDelegate=="function"?t.getDelegate():t)?.constructor?.name??"";return n!==""&&n!=="NoopTracerProvider"}i(Js,"hostHasTracerProvider");function Ys(){Cr||Js()&&(Cr=!0,vt.setGlobalContextManager(new pn))}i(Ys,"ensureContextManager");function hn(t){Ys();let e=Ct.getTracer(Or,t.kernelVersion),n="";try{n=new URL(t.url).host}catch{}let r=e.startSpan("http.client",{kind:qe.CLIENT,attributes:{"http.request.method":t.method,"url.full":t.url,"server.address":n,"npayload.sdk":"node-kernel","npayload.kernel_version":t.kernelVersion,"npayload.client_id":t.clientId,"npayload.path":t.path,"npayload.traceparent":t.traceparent,...t.env!==void 0?{"npayload.env":t.env}:{}}},vt.active());return{span:r,end(o){o.status!==void 0&&r.setAttribute("http.response.status_code",o.status),o.requestId&&r.setAttribute("npayload.request_id",o.requestId),o.error!==void 0?(r.setStatus({code:Se.ERROR,message:o.error instanceof Error?o.error.message:String(o.error)}),o.error instanceof Error&&r.recordException(o.error)):r.setStatus({code:Se.OK}),r.end()}}}i(hn,"startHttpClientSpan");import{randomBytes as Xs}from"crypto";var Qs=/^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$/i;function En(t){return Xs(t).toString("hex")}i(En,"hex");function Ir(){return`00-${En(16)}-${En(8)}-01`}i(Ir,"generateTraceparent");function Dr(t){if(!t||!Qs.test(t))return Ir();let n=t.split("-")[1],r=En(8);return`00-${n}-${r}-01`}i(Dr,"propagateTraceparent");var We=class{static{i(this,"KernelObserver")}handlers=new Map;on(e,n){let r=this.handlers.get(e);return r||(r=new Set,this.handlers.set(e,r)),r.add(n),()=>{this.handlers.get(e)?.delete(n)}}traceparent(e){return Dr(e)}emit(e){let n=this.handlers.get(e.type);if(n)for(let r of n)try{r(e)}catch{}}};function gn(t){let e,n="message",r=[],o;for(let c of t.split(/\r?\n/)){if(c===""||c.startsWith(":"))continue;let u=c.indexOf(":"),f=u===-1?c:c.slice(0,u),d=u===-1?"":c.slice(u+1);switch(d.startsWith(" ")&&(d=d.slice(1)),f){case"id":e=d;break;case"event":n=d;break;case"data":r.push(d);break;case"retry":{let l=Number(d);!Number.isNaN(l)&&l>=0&&(o=l);break}default:break}}if(r.length===0)return null;let s=r.join(`
2
+ `),a;try{a=JSON.parse(s)}catch{a=s}return e!==void 0?o!==void 0?{id:e,event:n,data:a,raw:s,retryAfterMs:o}:{id:e,event:n,data:a,raw:s}:o!==void 0?{event:n,data:a,raw:s,retryAfterMs:o}:{event:n,data:a,raw:s}}i(gn,"parseSseBlock");async function*zs(t){let e=t.getReader(),n=new TextDecoder("utf-8"),r="";try{for(;;){let{done:o,value:s}=await e.read();s&&(r+=n.decode(s,{stream:!0}));let a=r.split(/\r?\n\r?\n/);r=a.pop()??"";for(let c of a){let u=gn(c);u&&(yield u)}if(o){if(r.trim().length>0){let c=gn(r);c&&(yield c)}return}}}finally{e.releaseLock()}}i(zs,"parseEventStream");import{createHmac as ef,timingSafeEqual as tf}from"crypto";import{readFileSync as ff,writeFileSync as lf}from"fs";var Ot="0.2.0",Pr="https://api.npayload.com";function Zs(t){return`${(t.authUrl??t.baseUrl??Pr).replace(/\/+$/,"")}/oauth/token`}i(Zs,"tokenEndpointOf");var ei="X-NPayload-Env",ti=/^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$/i,Ur=class{static{i(this,"Kernel")}config;auth;observer;circuit;dispatcher;clockDrift;clockNow;methods=new Set;constructor(e){let n=e.config;ri(n);let r=rt(n.dpopPrivateJwk)?n.dpopPrivateJwk:new Ue(n.dpopPrivateJwk),o=n.tlsMin??"TLSv1.3";if(o!=="TLSv1.3"&&o!=="TLSv1.2")throw new Z(`tlsMin must be "TLSv1.3" or "TLSv1.2" (TLS 1.2 is the floor); got ${String(o)}`,{code:"tls_min_below_floor"});let s={...n,tlsMin:o,dpopPrivateJwk:r};this.config=s,this.observer=new We;let a=n.testClock!==void 0?()=>n.testClock.now():void 0;this.circuit=new pe(a!==void 0?{now:a}:{}),this.clockDrift=new Me(n.maxClockDriftMs),this.clockNow=a,this.dispatcher=new xe({tlsMin:o,...n.tlsCa!==void 0?{ca:n.tlsCa}:{},...n.dns!==void 0?{dns:n.dns}:{}}),this.auth=new Et({clientId:n.clientId,keys:{publicJwk:r.publicJwk,privateJwk:r},authServerUrl:Zs(n),...n.appId!==void 0?{appId:n.appId}:{},...n.clientSecret!==void 0?{clientSecret:n.clientSecret}:{},...n.env!==void 0?{env:n.env}:{},...a!==void 0?{now:a}:{}})}async send(e){if(this.config.mockMode)throw new Error("Kernel.send called in mockMode \u2014 use the resource-layer mock helpers");ai(e);let n=oi(this.config.baseUrl??Pr,e),r=e.traceparent!==void 0&&ti.test(e.traceparent)?e.traceparent:this.observer.traceparent(void 0),o=Date.now();this.observer.emit({type:"request",method:e.method,path:e.path,traceparent:r,...e.idempotencyKey!==void 0?{idempotencyKey:e.idempotencyKey}:{}});let a={...this.config.env?{[ei]:this.config.env}:{},...e.headers??{}},c=this.config.telemetry===!1?void 0:hn({method:e.method,url:n,path:e.path,clientId:this.config.clientId,kernelVersion:Ot,traceparent:r,...this.config.env!==void 0?{env:this.config.env}:{}});try{let u=await en({auth:this.auth,circuit:this.circuit,clockDrift:this.clockDrift,...this.clockNow!==void 0?{now:this.clockNow}:{},...this.config.httpClient!==void 0?{httpClient:this.config.httpClient}:{dispatcher:this.dispatcher},onRetry:i(E=>this.observer.emit({type:"retry",...E}),"onRetry"),onRateLimit:i(E=>{for(let g of this.rateLimitHandlers)try{g(E.remaining??0,E.resetAt??0)}catch{}},"onRateLimit")},{method:e.method,url:n,...Object.keys(a).length>0?{headers:a}:{},...e.body!==void 0?{body:si(e.body)}:{},...e.idempotencyKey!==void 0?{idempotencyKey:e.idempotencyKey}:{},...e.maxAttempts!==void 0?{maxAttempts:e.maxAttempts}:{},...e.restartWindowMs!==void 0?{restartWindowMs:e.restartWindowMs}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},traceparent:r,...e.tracestate!==void 0?{tracestate:e.tracestate}:{},...e.signal!==void 0?{signal:e.signal}:{},...e.scope!==void 0?{scope:e.scope}:{}}),f=u.response,d=f.status??200,l=f.headers?.get("content-length"),y=l&&Number.parseInt(l,10)||0;return this.observer.emit({type:"response",status:d,durationMs:Date.now()-o,...u.requestId!==null?{requestId:u.requestId}:{},bytes:y}),c?.end({status:d,requestId:u.requestId}),u.data}catch(u){this.observer.emit({type:"error",code:kr(u),durationMs:Date.now()-o});let f=ci(u);throw c?.end({error:u,...f!==void 0?{status:f}:{}}),u}}newIdempotencyKey(){return he()}rateLimitHandlers=new Set;onCircuitOpen(e){return this.circuit.onOpen(e)}onCircuitClose(e){return this.circuit.onClose(e)}onRateLimited(e){return this.rateLimitHandlers.add(e),()=>{this.rateLimitHandlers.delete(e)}}registerMethod(e){this.methods.add(e)}listMethods(){return Array.from(this.methods).sort()}async health(){if(this.config.mockMode)return{ok:!0,serverVersion:"mock",sdkVersion:Ot};try{let e=await this.send({method:"GET",path:"/v1/_health"});return{ok:e.ok,serverVersion:e.version??"unknown",sdkVersion:Ot}}catch(e){return{ok:!1,serverVersion:"unknown",sdkVersion:Ot,error:kr(e)}}}},ni=["apiKey","api_key","orgId","org_id","tenantId","tenant_id","ownerId","hmacSecret","hmac_secret","secret","bearer"];function ri(t){for(let e of ni)if(e in t)throw new Error(`KernelConfig MUST NOT include "${e}". The npayload kernel uses DPoP-bound OAuth tokens \u2014 never an API key, secret, or org id.`)}i(ri,"rejectForbiddenFields");function oi(t,e){let n=e.path;if(e.pathParams)for(let[o,s]of Object.entries(e.pathParams))n=n.replace(`{${o}}`,encodeURIComponent(s));let r=t.replace(/\/+$/,"")+n;if(e.query&&Object.keys(e.query).length>0){let o=new URLSearchParams;for(let[s,a]of Object.entries(e.query))o.set(s,String(a));r+=`?${o.toString()}`}return r}i(oi,"composeUrl");function si(t){if(typeof t=="string")return t;try{return JSON.stringify(t)}catch(e){let n=e instanceof Error?e.message:String(e);throw new Z(`Failed to serialise request body: ${n}`,{code:"body_serialisation_failed"})}}i(si,"serialiseBody");function kr(t){return t&&typeof t=="object"&&"code"in t?String(t.code):"unknown"}i(kr,"getCode");var ii=new Set(["orgid","org_id","organizationid","organization_id","tenantid","tenant_id","ownerid","owner_id","x-org-id","x-tenant-id","x-owner-id","x-organization-id"]);function ai(t){let e=[];for(let n of[t.headers,t.query])if(n)for(let r of Object.keys(n))ii.has(r.toLowerCase())&&e.push(r);if(e.length>0)throw new Z(`Org-shaped request fields are never sent by the kernel (the org is the credential's): ${e.join(", ")}`,{code:"org_context_forbidden"})}i(ai,"rejectOrgShapedRequestFields");function ci(t){let e=t?.status;return typeof e=="number"?e:void 0}i(ci,"getStatus");var h=16,Ge=144,H=64,ui=128;function $r(t){return(t&W.PQ_HYBRID)!==0?ui:H}i($r,"publishSignatureLen");var Ae=32,rl=new Uint8Array([78,80,80,1]),oe=new Uint8Array([78,80,80,1]),m={HELLO:0,HELLO_ACK:1,PUBLISH:2,PUBLISH_BATCH:3,BULK_ACK:4,SUBSCRIBE:5,DELIVER:6,DELIVER_BATCH:7,ACK:8,SEEK:9,FLOW_CREDIT:13,PING:14,PONG:15,GOODBYE:16,ERROR:17,SYS_EVENT:18,REKEY:19},Kr={ZSTD:1,E2E:2,HLC:4,PQ_HYBRID:64};var Hr=1,Fr=0,Vr={AT_MOST_ONCE:0,AT_LEAST_ONCE:1,EXACTLY_ONCE:2},ol=Vr.EXACTLY_ONCE;var W={COMPRESSED:1,ENCRYPTED:2,BATCH:4,URGENT:8,RESERVED_V2:16,EXTENDED_HEADER:32,PQ_HYBRID:64,SESSION_PARAMS:128},ve={ACCEPTED:0,ACCEPTED_DUPLICATE:1,REJECTED_GAP:16,REJECTED_DUPLICATE:17,REJECTED_SIGNATURE:32,REJECTED_AUTH:33,REJECTED_SCHEMA:48,REJECTED_PAYLOAD:49,REJECTED_INVALID_FILTER:50,REJECTED_QUOTA:64,REJECTED_GRANT:65,DEFERRED_RETRY:80,REJECTED_OTHER:255},qr={REJECTED_HW_ATTESTATION:144};function Y(t){if(t.headerLen<h)throw new RangeError(`headerLen must be \u2265 ${h}, got ${t.headerLen}`);if(t.frameType<0||t.frameType>255)throw new RangeError(`frameType out of range: ${t.frameType}`);if(t.flags<0||t.flags>255)throw new RangeError(`flags out of range: ${t.flags}`);if(t.headerLen>65535)throw new RangeError(`headerLen exceeds u16: ${t.headerLen}`);if(t.sessionId<0||t.sessionId>4294967295)throw new RangeError(`sessionId out of range: ${t.sessionId}`);if(t.payloadLen<0||t.payloadLen>4294967295)throw new RangeError(`payloadLen out of range: ${t.payloadLen}`);let e=new Uint8Array(h);e.set(oe,0),e[4]=t.frameType,e[5]=t.flags;let n=new DataView(e.buffer,e.byteOffset,e.byteLength);return n.setUint16(6,t.headerLen,!1),n.setUint32(8,t.sessionId,!1),n.setUint32(12,t.payloadLen,!1),e}i(Y,"encodeCommonHeader");function B(t){if(t.byteLength<h)throw new RangeError(`frame too short for common header: ${t.byteLength} < ${h}`);for(let c=0;c<4;c+=1)if(t[c]!==oe[c])throw new Error("npp: bad magic \u2014 not an NPP frame");let e=new DataView(t.buffer,t.byteOffset,t.byteLength),n=t[4],r=t[5],o=e.getUint16(6,!1),s=e.getUint32(8,!1),a=e.getUint32(12,!1);if(o<h)throw new RangeError(`headerLen below minimum: ${o} < ${h}`);return{frameType:n,flags:r,headerLen:o,sessionId:s,payloadLen:a}}i(B,"decodeCommonHeader");var xr=5;function Wr(t){if(t.nppVersionMajor<0||t.nppVersionMajor>255)throw new RangeError(`nppVersionMajor out of u8 range: ${t.nppVersionMajor}`);if(t.nppVersionMinor<0||t.nppVersionMinor>255)throw new RangeError(`nppVersionMinor out of u8 range: ${t.nppVersionMinor}`);if(t.capabilityFlags<0||t.capabilityFlags>65535)throw new RangeError(`capabilityFlags out of u16 range: ${t.capabilityFlags}`);let e=t.qosCapabilities??Vr.AT_LEAST_ONCE;if(e<0||e>255)throw new RangeError(`qosCapabilities out of u8 range: ${e}`);let n=t.authBody??new Uint8Array(0),r=xr+n.byteLength,o=new Uint8Array(h+r);return o.set(Y({frameType:m.HELLO,flags:0,headerLen:h,sessionId:t.sessionId??0,payloadLen:r}),0),o[16]=t.nppVersionMajor,o[17]=t.nppVersionMinor,new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(18,t.capabilityFlags,!1),o[20]=e,n.byteLength>0&&o.set(n,h+xr),o}i(Wr,"encodeHello");var wn=6,Te=32,Rn=32,di=8+Rn,fi=1,li=8,yn=4+li,Mr=5;function pi(t,e){let n=new DataView(t.buffer,t.byteOffset,t.byteLength),r,o=e;for(;o<t.byteLength;){if(o+Mr>t.byteLength)throw new RangeError(`HELLO_ACK SESSION_PARAMS entry header runs past the frame at ${o}`);let s=t[o],a=n.getUint32(o+1,!1),c=o+Mr,u=c+a;if(u>t.byteLength)throw new RangeError(`HELLO_ACK SESSION_PARAMS entry 0x${s.toString(16).padStart(2,"0")} runs past the frame: have ${t.byteLength}, need ${u}`);if(s===fi){if(r!==void 0)throw new RangeError("HELLO_ACK SESSION_PARAMS carries two identity lists");r=hi(t,n,c,u)}o=u}return r}i(pi,"decodeSessionParamsEntries");function hi(t,e,n,r){let o=n,s=i(u=>{if(o+2>r)throw new RangeError("HELLO_ACK identity list shorter than its counts");let f=e.getUint16(o,!1);o+=2;let d=[];for(let l=0;l<f;l+=1){if(o+yn>r)throw new RangeError("HELLO_ACK identity list shorter than its tuples");d.push(u(e.getUint32(o,!1),t.slice(o+4,o+yn))),o+=yn}return d},"tuples"),a=s((u,f)=>({channelId:u,gidHash:f})),c=s((u,f)=>({schemaFingerprint:u,schemaGidHash:f}));if(o!==r)throw new RangeError("HELLO_ACK identity list longer than its tuples");return{channels:a,schemas:c}}i(hi,"decodeIdentityList");function Gr(t){let e=Ei(t),n=mn(e.prefix,e.nonce);return t.byteLength<=e.sigEnd?[n]:[mn(n,t.slice(e.sigEnd)),n]}i(Gr,"helloAckSigningInputs");function Ei(t){let e=B(t),n=e.headerLen,r=n+e.payloadLen,o=r+Te,s=o+H;if(t.byteLength<s)throw new RangeError(`HELLO_ACK truncated for signing input: have ${t.byteLength}, need ${s}`);return{prefix:mn(t.slice(8,h),t.slice(n,r)),nonce:t.slice(r,o),sigEnd:s}}i(Ei,"helloAckSignedParts");function mn(...t){let e=0;for(let o of t)e+=o.byteLength;let n=new Uint8Array(e),r=0;for(let o of t)n.set(o,r),r+=o.byteLength;return n}i(mn,"concatBytes");function jr(t){if(t.byteLength<h+wn)throw new RangeError(`HELLO_ACK too short: ${t.byteLength} < ${h+wn}`);let e=B(t);if(e.frameType!==m.HELLO_ACK)throw new Error(`decodeHelloAck: expected frameType=HELLO_ACK (0x01), got 0x${e.frameType.toString(16).padStart(2,"0")}`);let n=new DataView(t.buffer,t.byteOffset,t.byteLength),r={sessionId:e.sessionId,nppVersionMajor:t[16],nppVersionMinor:t[17],negotiatedCapabilities:n.getUint16(20,!1)},o=h+wn,s=(e.flags&W.EXTENDED_HEADER)!==0,a=o+Te+H;if(s&&t.byteLength>=a&&(r.nonceEcho=t.slice(o,o+Te),r.serverSignature=t.slice(o+Te,a)),(e.flags&W.SESSION_PARAMS)!==0){let c=o+(s?Te+H:0),u=c+di;if(t.byteLength<u)throw new RangeError(`HELLO_ACK SESSION_PARAMS truncated: have ${t.byteLength}, need ${u}`);r.sessionTtlSec=n.getUint32(c,!1),r.publishWindowMs=n.getUint32(c+4,!1),r.ephemeralPublicKey=t.slice(c+8,c+8+Rn);let f=pi(t,u);f!==void 0&&(r.identities=f)}return r}i(jr,"decodeHelloAck");function Ln(t,e){if(t.frameType!==m.PUBLISH)throw new Error(`encodePublishEnvelope: expected frameType=PUBLISH (0x02), got 0x${t.frameType.toString(16).padStart(2,"0")}`);if(e.payloadHash.byteLength!==Ae)throw new RangeError(`payloadHash must be ${Ae} bytes, got ${e.payloadHash.byteLength}`);let n=$r(t.flags);if(e.detachedSignature.byteLength!==n)throw new RangeError(`detachedSignature must be ${n} bytes for ${(t.flags&W.PQ_HYBRID)!==0?"PQ_HYBRID":"classical"} mode, got ${e.detachedSignature.byteLength}`);if(e.qosLevel<0||e.qosLevel>2)throw new RangeError(`qosLevel must be 0..2, got ${e.qosLevel}`);if(e.encryptionMode<0||e.encryptionMode>3)throw new RangeError(`encryptionMode must be 0..3, got ${e.encryptionMode}`);if(e.attributesCount<0||e.attributesCount>65535)throw new RangeError(`attributesCount out of range: ${e.attributesCount}`);let r=e.priority!==void 0;if(r&&(e.priority<0||e.priority>9))throw new RangeError(`priority must be 0..9, got ${e.priority}`);let o=48+Ae+n,s=o+(r?1:0),a=r?t.flags|W.EXTENDED_HEADER:t.flags,c=new Uint8Array(s);c.set(Y({...t,flags:a}),0);let u=new DataView(c.buffer,c.byteOffset,c.byteLength);return u.setUint32(16,e.channelId,!1),u.setUint32(20,e.partitionId,!1),u.setBigUint64(24,e.sequence,!1),u.setBigUint64(32,e.hlcTimestamp,!1),u.setUint32(40,e.schemaFingerprint,!1),c[44]=e.qosLevel,c[45]=e.encryptionMode,u.setUint16(46,e.attributesCount,!1),c.set(e.payloadHash,48),c.set(e.detachedSignature,80),r&&(c[o]=e.priority),c}i(Ln,"encodePublishEnvelope");function kt(t){if(t.byteLength<80)throw new RangeError(`envelope bytes too short for signing input: ${t.byteLength}`);return t.slice(8,80)}i(kt,"canonicalPublishSigningInput");var gi=10;function Jr(t){let e=B(t);if(e.frameType!==m.BULK_ACK)throw new Error(`decodeBulkAck: expected frameType=BULK_ACK (0x04), got 0x${e.frameType.toString(16).padStart(2,"0")}`);let n=gi,r=h+e.payloadLen;if(t.byteLength<r)throw new RangeError(`BULK_ACK truncated: have ${t.byteLength}, need ${r}`);if(e.payloadLen%n!==0)throw new RangeError(`BULK_ACK payloadLen not a multiple of ${n}: ${e.payloadLen}`);let o=new DataView(t.buffer,t.byteOffset,t.byteLength),s=e.payloadLen/n,a=[];for(let u=0;u<s;u+=1){let f=h+u*n;a.push({seq:o.getBigUint64(f,!1),status:o.getUint16(f+8,!1)})}let c;return(e.flags&W.EXTENDED_HEADER)!==0&&t.byteLength>=r+H&&(c=t.slice(r,r+H)),{header:e,records:a,serverSignature:c}}i(Jr,"decodeBulkAck");var se=48,$={LOG:0,QUEUE:1,TOPIC:2,TAIL:3,OUTCOMES:4,DEAD_LETTERS:5,TABLE_HEAD:6,WINDOW:7,COUNTERS:8,UNIT_HEAD:9},Ee={PUSH:0,PULL:1,HYBRID:2},It={NONE:0,JSONPATH:1,CEL:2,ROUTING_KEY_PREFIX:3},sl=new Set([It.NONE,It.JSONPATH,It.CEL,It.ROUTING_KEY_PREFIX]);function Yr(t,e){return t===$.TOPIC&&(e===Ee.PULL||e===Ee.HYBRID)?"TOPIC mode is push-only (no cursor)":t===$.TAIL&&(e===Ee.PULL||e===Ee.HYBRID)?"TAIL mode is push-only (subscribe-from-now)":wi(t)&&e!==Ee.PUSH?"a view mode (OUTCOMES, DEAD_LETTERS, TABLE_HEAD, WINDOW, COUNTERS, UNIT_HEAD) is push-only":null}i(Yr,"validateSubscribeModeCompat");function Ne(t){let e=t.envelope;if(e.mode<0||e.mode>255)throw new RangeError(`mode out of range: ${e.mode}`);if(e.deliveryPreference<0||e.deliveryPreference>255)throw new RangeError(`deliveryPreference out of range: ${e.deliveryPreference}`);let n=Yr(e.mode,e.deliveryPreference);if(n)throw new RangeError(`SUBSCRIBE compat: ${n}`);if(e.qosCapabilities<0||e.qosCapabilities>65535)throw new RangeError(`qosCapabilities out of range: ${e.qosCapabilities}`);if(e.partitionFilter<0||e.partitionFilter>4294967295)throw new RangeError(`partitionFilter out of range: ${e.partitionFilter}`);if(e.filters.length>255)throw new RangeError(`too many filters (filterCount is u8): ${e.filters.length}`);let r=0;for(let d of e.filters){if(d.value.byteLength>65535)throw new RangeError(`filter value too large: ${d.value.byteLength}`);r+=3+d.value.byteLength}let o=t.consumerSignature??new Uint8Array(0);if(o.byteLength>65535)throw new RangeError(`consumerSignature too large: ${o.byteLength}`);let a=se-h+r+o.byteLength,c=new Uint8Array(h+a);c.set(Y({frameType:m.SUBSCRIBE,flags:0,headerLen:h,sessionId:t.sessionId,payloadLen:a}),0);let u=new DataView(c.buffer,c.byteOffset,c.byteLength);u.setUint32(16,e.channelId,!1),u.setUint32(20,e.partitionFilter,!1),c[24]=e.mode,c[25]=e.deliveryPreference,u.setUint16(26,e.qosCapabilities,!1),u.setBigUint64(28,e.startCursor,!1),u.setBigUint64(36,e.startHlc,!1),c[44]=e.filters.length;let f=se;for(let d of e.filters)c[f]=d.type&255,u.setUint16(f+1,d.value.byteLength,!1),c.set(d.value,f+3),f+=3+d.value.byteLength;return c.set(o,f),c}i(Ne,"encodeSubscribeFrame");function _n(t){if(t.byteLength<se)throw new RangeError(`envelope too short for SUBSCRIBE signing input: ${t.byteLength}`);let e=new DataView(t.buffer,t.byteOffset,t.byteLength),n=Math.min(t.byteLength,h+e.getUint32(12,!1)),r=se;for(let o=0;o<t[44];o+=1){if(r+3>n)throw new RangeError(`SUBSCRIBE filter ${o} header truncated: no signing input`);if(r+=3+e.getUint16(r+1,!1),r>n)throw new RangeError(`SUBSCRIBE filter ${o} value truncated: no signing input`)}return t.slice(8,r)}i(_n,"canonicalSubscribeSigningInput");var il=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),Xr=new TextEncoder;function wi(t){return Number.isInteger(t)&&t>=$.OUTCOMES&&t<=$.UNIT_HEAD}i(wi,"isViewMode");var K={RECORD:0,OUTCOME:1,DEAD_LETTER:2,TABLE_HEAD:3,WINDOW:4,COUNTERS:5,UNIT_HEAD:6},yi="npk_view",mi={[K.OUTCOME]:"outcome",[K.DEAD_LETTER]:"dead_letter",[K.TABLE_HEAD]:"table_head",[K.WINDOW]:"window",[K.COUNTERS]:"counters",[K.UNIT_HEAD]:"unit_head"},al=Xr.encode(yi),cl=[K.OUTCOME,K.DEAD_LETTER,K.TABLE_HEAD,K.WINDOW,K.COUNTERS,K.UNIT_HEAD].map(t=>[t,Xr.encode(mi[t])]);var ul={[$.OUTCOMES]:"kernel:outcomes:",[$.DEAD_LETTERS]:"kernel:dead_letters:",[$.TABLE_HEAD]:"kernel:head:",[$.WINDOW]:"kernel:window:",[$.COUNTERS]:"kernel:counters:",[$.UNIT_HEAD]:"kernel:unit_head:"};var bi=22,Ri=27,Li=27;function _i(t){let e=B(t);if(e.headerLen>t.byteLength)throw new RangeError(`headerLen ${e.headerLen} beyond the frame's ${t.byteLength} bytes`);let n=[],r=h;for(;r<e.headerLen;){if(r+2>e.headerLen)throw new RangeError("TLV region does not fill 16..headerLen exactly: a type without its length");let s=t[r+1];if(r+2+s>e.headerLen)throw new RangeError(`TLV 0x${t[r].toString(16)} of ${s} bytes runs past headerLen ${e.headerLen}`);n.push({type:t[r],value:t.slice(r+2,r+2+s)}),r+=2+s}for(let s=0;s<n.length;s+=1){let a=n[s].type;if(a>=1&&a<=Li&&a!==bi&&a!==Ri&&n.slice(0,s).some(c=>c.type===a))throw new RangeError(`TLV 0x${a.toString(16)} repeated: a registered TLV appears once in a frame`)}if(e.headerLen===h)return{canonical:t,tlvs:n};let o=new Uint8Array(t.byteLength-(e.headerLen-h));return o.set(t.subarray(0,h),0),o.set(t.subarray(e.headerLen),h),new DataView(o.buffer).setUint16(6,h,!1),{canonical:o,tlvs:n}}i(_i,"splitHeaderTlvs");var Si=10,Ti=26;function Qr(t,e,n){if(n.length===0)throw new RangeError("ACK must contain at least one record");let r=n.some(d=>d.deliveryToken!==void 0),o=r?Ti:Si,s=4,a=s+n.length*o,c=new Uint8Array(h+a);c.set(Y({frameType:m.ACK,flags:r?W.EXTENDED_HEADER:0,headerLen:h,sessionId:t,payloadLen:a}),0);let u=new DataView(c.buffer,c.byteOffset,c.byteLength);u.setUint32(16,e,!1);let f=h+s;for(let d of n){if(d.disposition<0||d.disposition>65535)throw new RangeError(`disposition out of range: ${d.disposition}`);if(u.setBigUint64(f,d.seq,!1),u.setUint16(f+8,d.disposition,!1),r){let l=d.deliveryToken??{hi:0n,lo:0n};u.setBigUint64(f+10,l.hi,!1),u.setBigUint64(f+18,l.lo,!1)}f+=o}return c}i(Qr,"encodeAck");var Ai=16;function Dt(t,e){if(!Number.isInteger(e)||e<0||e>4294967295)throw new RangeError(`FLOW_CREDIT ${t} out of u32 range: ${e}`)}i(Dt,"assertU32");function zr(t,e){Dt("channelId",e.channelId),Dt("creditDelta",e.creditDelta),Dt("projectedLagMs",e.projectedLagMs),Dt("bandwidthBudgetBps",e.bandwidthBudgetBps);let n=Ai,r=new Uint8Array(h+n);r.set(Y({frameType:m.FLOW_CREDIT,flags:0,headerLen:h,sessionId:t,payloadLen:n}),0);let o=new DataView(r.buffer,r.byteOffset,r.byteLength);return o.setUint32(h+0,e.channelId,!1),o.setUint32(h+4,e.creditDelta,!1),o.setUint32(h+8,e.projectedLagMs,!1),o.setUint32(h+12,e.bandwidthBudgetBps,!1),r}i(zr,"encodeFlowCredit");function Zr(t){let e=B(t);if(e.frameType!==m.SYS_EVENT)throw new Error(`expected SYS_EVENT (0x12), got 0x${e.frameType.toString(16)}`);if(e.payloadLen<16)throw new RangeError("SYS_EVENT payload too small");let n=new DataView(t.buffer,t.byteOffset,t.byteLength),r=n.getUint32(16,!1),o=n.getUint32(20,!1),s=n.getBigUint64(24,!1),a=t.slice(h+16,h+e.payloadLen);return{header:e,frame:{channelId:r,eventCode:o,hlcTimestamp:s,payload:a}}}i(Zr,"decodeSysEvent");var Ut=10;function eo(t){let e=B(t);if(e.frameType!==m.ERROR)throw new Error(`decodeError: expected frameType=ERROR (0x11), got 0x${e.frameType.toString(16).padStart(2,"0")}`);if(e.payloadLen<Ut)throw new RangeError(`ERROR payload too small: ${e.payloadLen}`);e.headerLen!==h&&_i(t);let n=e.headerLen;if(t.byteLength<n+e.payloadLen)throw new RangeError("ERROR frame truncated");let r=new DataView(t.buffer,t.byteOffset,t.byteLength),o=n+Ut,s=n+e.payloadLen;return{header:e,frame:{seq:r.getBigUint64(n,!1),reasonCode:r.getUint16(n+8,!1),detail:t.slice(o,s)}}}i(eo,"decodeError");var Ce={FRAME_MALFORMED:498,PROTOCOL_VIOLATION:499,UPSTREAM_REFUSED:500};function bn(t){for(let[e,n]of Object.entries(Ce))if(n===t)return e}i(bn,"nppErrorCodeName");function Pt(t){for(let[e,n]of Object.entries(ve))if(n===t)return e}i(Pt,"bulkAckStatusName");function ie(t,e){let n=B(t);if(n.frameType!==m.ERROR)throw new Error(`decodeErrorSideband: expected frameType=ERROR (0x11), got 0x${n.frameType.toString(16).padStart(2,"0")}`);if(n.payloadLen<2)throw new RangeError(`ERROR sideband payload too small: ${n.payloadLen}`);let r=n.headerLen,o=r+n.payloadLen;if(t.byteLength<o)throw new RangeError("ERROR sideband truncated");let s=new DataView(t.buffer,t.byteOffset,t.byteLength),a=new TextDecoder("utf-8",{fatal:!1});if(e!==void 0&&n.payloadLen>=Ut&&s.getBigUint64(r,!1)===e){let f=s.getUint16(r+8,!1);return{header:n,layout:"seq-linked",seq:e,code:f,name:bn(f)??Pt(f),reason:a.decode(t.subarray(r+Ut,o))}}let c=s.getUint16(r,!1),u=a.decode(t.subarray(r+2,o));return{header:n,layout:"sideband",code:c,name:bn(c),reason:u}}i(ie,"decodeErrorSideband");function vi(t,e){if(t.byteLength-e<h)return;for(let u=0;u<oe.length;u+=1)if(t[e+u]!==oe[u])return;let n=new DataView(t.buffer,t.byteOffset+e,t.byteLength-e),r=t[e+4],o=t[e+5],s=n.getUint16(6,!1),a=n.getUint32(12,!1);if(s<h)return;let c=s+a;if((o&W.EXTENDED_HEADER)!==0&&(c+=$r(o),r===m.HELLO_ACK&&(c+=Te)),r===m.HELLO_ACK&&(o&W.SESSION_PARAMS)!==0&&(c+=8+Rn),!(e+c>t.byteLength))return c}i(vi,"frameByteLengthAt");function xt(t){let e=[],n=0;for(;n<t.byteLength;){let r=vi(t,n);if(r===void 0)return e.push(t.subarray(n)),e;e.push(t.subarray(n,n+r)),n+=r}return e.length>0?e:[t]}i(xt,"splitFrames");var dl=Ge-h;var fl=64*1024;function to(t,e=15){let n=new Uint16Array(e+1);for(let s of t)n[s]+=1;n[0]=0;let r=new Uint16Array(e+2);for(let s=1;s<=e;s+=1)r[s+1]=r[s]+n[s];let o=new Uint16Array(t.length);for(let s=0;s<t.length;s+=1)t[s]!==0&&(o[r[t[s]]]=s,r[t[s]]+=1);return{counts:n,symbols:o}}i(to,"buildHuffTable");var ll=(()=>{let t=new Uint8Array(288);for(let e=0;e<=143;e+=1)t[e]=8;for(let e=144;e<=255;e+=1)t[e]=9;for(let e=256;e<=279;e+=1)t[e]=7;for(let e=280;e<=287;e+=1)t[e]=8;return to(t)})(),pl=(()=>{let t=new Uint8Array(30).fill(5);return to(t)})();var Br=2;function no(t,e){if(e.reasonCode<0||e.reasonCode>65535)throw new RangeError(`GOODBYE reasonCode out of u16 range: ${e.reasonCode}`);let n=new Uint8Array(h+Br);return n.set(Y({frameType:m.GOODBYE,flags:0,headerLen:h,sessionId:t,payloadLen:Br}),0),new DataView(n.buffer,n.byteOffset,n.byteLength).setUint16(16,e.reasonCode,!1),n}i(no,"encodeGoodbye");function ro(t,e=new Uint8Array(0)){let n=new Uint8Array(h+e.byteLength);return n.set(Y({frameType:m.PONG,flags:0,headerLen:h,sessionId:t,payloadLen:e.byteLength}),0),e.byteLength>0&&n.set(e,h),n}i(ro,"encodePong");var hl=1024*1024;var je=16,Ni=144;var Ci=new Uint8Array([78,80,80,1]),Oi={HELLO:0,HELLO_ACK:1,PUBLISH:2,PUBLISH_BATCH:3,BULK_ACK:4,SUBSCRIBE:5,DELIVER:6,DELIVER_BATCH:7,ACK:8,SEEK:9,FLOW_CREDIT:13,PING:14,PONG:15,GOODBYE:16,ERROR:17,SYS_EVENT:18,REKEY:19},Ii={COMPRESSED:1,ENCRYPTED:2,BATCH:4,URGENT:8,RESERVED_V2:16,EXTENDED_HEADER:32,PQ_HYBRID:64};function Di(t){if(t.byteLength<je)throw new RangeError(`frame too short for common header: ${t.byteLength} < ${je}`);for(let c=0;c<4;c+=1)if(t[c]!==Ci[c])throw new Error("npp: bad magic \u2014 not an NPP frame");let e=new DataView(t.buffer,t.byteOffset,t.byteLength),n=t[4],r=t[5],o=e.getUint16(6,!1),s=e.getUint32(8,!1),a=e.getUint32(12,!1);if(o<je)throw new RangeError(`headerLen below minimum: ${o} < ${je}`);return{frameType:n,flags:r,headerLen:o,sessionId:s,payloadLen:a}}i(Di,"decodeCommonHeader");var ae=Ni,Ui=3309;var ki=32,Pi="traceparent",Mt={STRING:0,NUMBER:1,BOOL:2,NULL:3};function xi(t,e){let n=new TextDecoder;switch(t){case Mt.STRING:return n.decode(e);case Mt.NUMBER:return Number(n.decode(e));case Mt.BOOL:return e[0]===1;case Mt.NULL:return null;default:throw new RangeError(`DELIVER attribute: unknown value tag 0x${t.toString(16)}`)}}i(xi,"decodeAttrValue");function Mi(t,e){let n=new DataView(t.buffer,t.byteOffset,t.byteLength),r=new TextDecoder,o=[],s=0;for(let a=0;a<e;a+=1){if(s+4>t.byteLength)throw new RangeError(`DELIVER attribute ${a} header truncated`);let c=n.getUint16(s,!1),u=n.getUint16(s+2,!1);if(s+=4,u<1||s+c+u>t.byteLength)throw new RangeError(`DELIVER attribute ${a} body truncated`);let f=r.decode(t.slice(s,s+c));s+=c;let d=t[s],l=xi(d,t.slice(s+1,s+u));s+=u,o.push({key:f,value:l})}return{attributes:o,byteLength:s}}i(Mi,"decodeDeliverAttributes");var Rl=new Uint8Array([78,80,80,84]);function Bi(t){if(t.byteLength<80)throw new RangeError(`envelope too short for signing input: ${t.byteLength}`);return t.slice(8,80)}i(Bi,"canonicalDeliverSigningInput");function $i(t){if(t.byteLength<ae)throw new RangeError(`bytes too short for DELIVER envelope: ${t.byteLength} < ${ae}`);let e=Di(t);if(e.frameType!==Oi.DELIVER)throw new Error(`decodeDeliverFrame: expected frameType=DELIVER (0x06), got 0x${e.frameType.toString(16).padStart(2,"0")}`);let n=new DataView(t.buffer,t.byteOffset,t.byteLength),r=n.getUint32(16,!1),o=n.getUint32(20,!1),s=n.getBigUint64(24,!1),a=n.getBigUint64(32,!1),c=n.getUint32(40,!1),u=t[44],f=t[45],d=n.getUint16(46,!1),l=t.slice(48,80),y=t.slice(80,144),E=ae-je,g=e.payloadLen-E;if(g<0)throw new RangeError(`DELIVER payloadLen header (${e.payloadLen}) smaller than envelope body (${E})`);let b=ae+g;if(t.byteLength<b)throw new RangeError(`DELIVER frame truncated: have ${t.byteLength}, expected >= ${b}`);let A=[],L=ae;if(d>0&&(e.flags&ki)!==0){let T=Mi(t.slice(ae,b),d);A=T.attributes,L=ae+T.byteLength}let v=b,S=t.slice(L,v),N=A.find(T=>T.key===Pi),x=typeof N?.value=="string"?N.value:void 0,_=null;if(e.flags&Ii.PQ_HYBRID){let T=v,p=T+Ui;if(t.byteLength<p)throw new RangeError(`DELIVER frame PQ_HYBRID flag set but Dilithium sig truncated: have ${t.byteLength}, expected >= ${p}`);_=t.slice(T,p)}let R=Bi(t.slice(0,ae));return{flags:e.flags,sessionId:e.sessionId,channelId:r,partitionId:o,sequence:s,hlcTimestamp:a,schemaFingerprint:c,qosLevel:u,encryptionMode:f,attributesCount:d,attributes:A,traceparent:x,payloadHash:l,detachedSignature:y,payload:S,dilithiumSignature:_,signingInput:R}}i($i,"decodeDeliverFrame");var lo=class extends Error{static{i(this,"CellError")}code;statusCode;constructor(t,e="CELL_ERROR",n=500){super(t),this.name="CellError",this.code=e,this.statusCode=n,Object.setPrototypeOf(this,new.target.prototype)}toJSON(){return{name:this.name,code:this.code,message:this.message,statusCode:this.statusCode}}};var Ki=class extends lo{static{i(this,"CellPlanRequiredError")}product;upgradeUrl;constructor(t,e={}){super(t,e.code??"PLAN_REQUIRED",402),this.name="CellPlanRequiredError",this.product=e.product,this.upgradeUrl=e.upgradeUrl}toJSON(){return{...super.toJSON(),...this.product!==void 0?{product:this.product}:{},...this.upgradeUrl!==void 0?{upgradeUrl:this.upgradeUrl}:{}}}},Hi=class extends lo{static{i(this,"CellQuotaExceededError")}upgradeUrl;constructor(t,e={}){super(t,e.code??"QUOTA_EXCEEDED",429),this.name="CellQuotaExceededError",this.upgradeUrl=e.upgradeUrl}toJSON(){return{...super.toJSON(),...this.upgradeUrl!==void 0?{upgradeUrl:this.upgradeUrl}:{}}}};function kn(t){return`${t.thumbprint}\0${t.channelGid}`}i(kn,"nppSequenceKeyId");var Pn=class{static{i(this,"InMemoryNppSequenceStore")}states=new Map;tails=new Map;async exclusive(t,e){let n=kn(t),r=this.tails.get(n)??Promise.resolve(),o,s=new Promise(c=>{o=c}),a=r.then(()=>s);this.tails.set(n,a),await r;try{return await e({load:i(async()=>({...this.states.get(n)??{lastAccepted:0n}}),"load"),save:i(async c=>{this.states.set(n,{...c})},"save")})}finally{o(),this.tails.get(n)===a&&this.tails.delete(n)}}},ze=new Pn,Fi=0,Vi=1,qi=2,Wi=3,Gi=16,ji=17,Ji="another process signing with this credential's key already stored this sequence on the channel with an identical payload; this publish was NOT stored as a new message. The producer moved past it \u2014 publish again to store it.",Yi="another process signing with this credential's key already used this sequence on the channel (a different HOME, container or host holding the same credential); this publish was NOT stored. The producer moved past it.",Xi="the broker's last accepted sequence for this producer on the channel is lower than this producer recorded; the producer rewound, and the next publish restarts the sequence.";async function Ze(t,e,n){return t.exclusive(e,async r=>{let o=await r.load();for(let s=!1;;s=!0){let a=o.lastAccepted+1n,c=o.inFlight===a;await r.save({lastAccepted:o.lastAccepted,inFlight:a});let u=await n(a);switch(u.status){case Fi:case qi:case Wi:return await r.save({lastAccepted:a}),{answer:u,sequence:a,verdict:{kind:"stored"}};case Vi:return await r.save({lastAccepted:a}),c||u.retried===!0?{answer:u,sequence:a,verdict:{kind:"stored"}}:{answer:u,sequence:a,verdict:{kind:"conflict",reason:Ji}};case ji:if(await r.save({lastAccepted:a}),c&&!s){o={lastAccepted:a};continue}return{answer:u,sequence:a,verdict:{kind:"conflict",reason:Yi}};case Gi:return await r.save({lastAccepted:0n}),{answer:u,sequence:a,verdict:{kind:"rewound",reason:Xi}};default:return{answer:u,sequence:a,verdict:{kind:"unsettled"}}}}})}i(Ze,"publishAtNextSequence");var Bt="KERNEL_DOOR_URL",Qe=8,D={ACK_CLASS:1,PRODUCER_EPOCH:2,BYTE_CREDIT:4,SUBSCRIPTION_HANDLE:5,POSITION:6,PARTITION:7,ROUTE_EPOCH:8,ENGINE_INFO:9,ACK_STRIDE:11,RECORD_KEY:16,TENANT_SELECT:17,CURSOR_ID:18,NACK_DELAY_MS:19,INITIAL_CREDIT:20,LINK_ORIGIN:21,MESSAGE_GID:22},Qi={2:"ACCEPTED_LOCAL",3:"ACCEPTED_GEO",81:"DEFERRED_UNDER_REPLICATED",82:"REJECTED_ROUTE_EPOCH",83:"REJECTED_CLASS_UNAVAILABLE",84:"REJECTED_WRONG_PARTITION",85:"REJECTED_NOT_PRIMARY",105:"REJECTED_PRODUCER_EPOCH"},oo=85,so=255,io=250,zi=1e3,po="plan_required",ho="internal_apps",Nn="/settings/billing";function Eo(t){let e=t.indexOf(":");return e<0?t:t.slice(0,e)}i(Eo,"reasonToken");function go(t){return Eo(t)===po}i(go,"isKernelPlanRefusal");var wo="quota_exceeded",Cn="/settings/billing";function yo(t){return Eo(t)===wo}i(yo,"isKernelQuotaRefusal");var mo=class extends Ki{static{i(this,"KernelPlanRequiredError")}kernelStatus;kernelStatusName;kernelReason;constructor(t,e){super("PLAN_REQUIRED: this app publishes only on a plan, so the message was not published; choose a plan at "+Nn,{code:"PLAN_REQUIRED",product:ho,upgradeUrl:Nn}),this.name="KernelPlanRequiredError",this.kernelStatus=t,this.kernelStatusName=Q(t)??Ye(t),this.kernelReason=e}},bo=class extends Hi{static{i(this,"KernelQuotaExceededError")}kernelStatus;kernelStatusName;kernelReason;constructor(t,e){super(`QUOTA_EXCEEDED: this organization's usage is past its allowance and it has no payment method on file, so the message was not published; add a payment method or choose a plan at ${Cn}`,{code:"QUOTA_EXCEEDED",upgradeUrl:Cn}),this.name="KernelQuotaExceededError",this.kernelStatus=t,this.kernelStatusName=Q(t)??Ye(t),this.kernelReason=e}},Zi=258,Ro=3,Je=new Set([0,1,2,3]);function Q(t){return Pt(t)??Qi[t]}i(Q,"kernelStatusName");var O=16,Sn=22,ao=0xffffffffffffffffn,w=class extends Error{static{i(this,"KernelDoorError")}code;reasonCode;reasonName;constructor(t,e,n){if(super(e),this.name="KernelDoorError",this.code=t,n!==void 0){this.reasonCode=n;let r=Q(n)??Lo[n];r!==void 0&&(this.reasonName=r)}}},Lo={1:"REJECTED_VERSION",2:"REJECTED_QOS",498:"FRAME_MALFORMED",499:"PROTOCOL_VIOLATION",500:"UPSTREAM_REFUSED",501:"UNSUPPORTED",502:"SESSION_EXPIRED"};function Ye(t){return`0x${t.toString(16).padStart(4,"0")}`}i(Ye,"hex16");function ea(){return globalThis.process?.env??{}}i(ea,"processEnv");function co(t,e){let n=e==="option"?"the door option":Bt,r;try{r=new URL(t)}catch{throw new w("KERNEL_DOOR_CONFIG",`${n} is not a URL: ${JSON.stringify(t)}`)}if(r.protocol==="wss:")return{kind:"kernel",url:r.toString(),source:e};if(e==="option"&&(r.protocol==="https:"||r.protocol==="http:"))return{kind:"edge",url:t,source:e};throw new w("KERNEL_DOOR_CONFIG",`${n} must be a wss:// kernel door (TLS 1.3)${e==="option"?" or the http(s):// edge door":""}; got ${r.protocol}//`)}i(co,"classifyDoor");function _o(t={}){if(t.door!==void 0&&t.door.trim()!=="")return co(t.door.trim(),"option");let n=(t.env??ea())[Bt];return n!==void 0&&n.trim()!==""?co(n.trim(),"env"):{kind:"edge",url:t.edgeUrl,source:"default"}}i(_o,"resolveDoor");function de(t){if(t.byteLength<O)throw new RangeError("frame shorter than the common header");let n=new DataView(t.buffer,t.byteOffset,t.byteLength).getUint16(6,!1);if(n<O||n>t.byteLength)throw new RangeError(`bad headerLen ${n}`);let r=[],o=O;for(;o<n;){if(o+2>n)throw new RangeError("TLV region does not fill headerLen exactly");let a=t[o],c=t[o+1];if(o+2+c>n)throw new RangeError("TLV region does not fill headerLen exactly");r.push({type:a,value:t.slice(o+2,o+2+c)}),o+=2+c}if(n===O)return{canonical:t,tlvs:r};let s=new Uint8Array(t.byteLength-(n-O));return s.set(t.subarray(0,O),0),s.set(t.subarray(n),O),new DataView(s.buffer).setUint16(6,O,!1),{canonical:s,tlvs:r}}i(de,"stripKernelTlvs");function Ie(t,e){if(e.length===0)return t;if(new DataView(t.buffer,t.byteOffset,t.byteLength).getUint16(6,!1)!==O)throw new RangeError("insertKernelTlvs expects a canonical frame");let r=0;for(let c of e){if(c.value.byteLength>255)throw new RangeError(`TLV 0x${c.type.toString(16)} value longer than 255 bytes`);r+=2+c.value.byteLength}let o=O+r;if(o>65535)throw new RangeError("TLV region too large");let s=new Uint8Array(t.byteLength+r);s.set(t.subarray(0,O),0);let a=O;for(let c of e)s[a]=c.type,s[a+1]=c.value.byteLength,s.set(c.value,a+2),a+=2+c.value.byteLength;return s.set(t.subarray(O),a),new DataView(s.buffer).setUint16(6,o,!1),s}i(Ie,"insertKernelTlvs");function ta(t){return Uint8Array.of(t&255)}i(ta,"tlvU8");function Oe(t){let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t>>>0,!1),e}i(Oe,"tlvU32");function na(t){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,t,!1),e}i(na,"tlvU64");function Xe(t,e){return t.find(n=>n.type===e)?.value}i(Xe,"findTlv");function uo(t){return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint32(0,!1)}i(uo,"readU32");function $t(t,e){let n=Xe(e,D.ACK_STRIDE);if(!n||n[0]!==Sn)return Jr(t).records.map(a=>({seq:a.seq,status:a.status}));let r=B(t);if(r.payloadLen%Sn!==0||O+r.payloadLen>t.byteLength)throw new RangeError("positioned BULK_ACK records do not fill payloadLen");let o=new DataView(t.buffer,t.byteOffset,t.byteLength),s=[];for(let a=O;a<O+r.payloadLen;a+=Sn)s.push({seq:o.getBigUint64(a,!1),status:o.getUint16(a+8,!1),position:{partition:o.getUint32(a+10,!1),offset:o.getBigUint64(a+14,!1)}});return s}i($t,"readKernelBulkAck");function Kt(t){let e=Xe(t,D.MESSAGE_GID);return e&&e.byteLength>0?Mn.decode(e):void 0}i(Kt,"readKernelMessageGid");var So=3e4,To=250;function ra(t){let e=i(n=>n!==null&&typeof n=="object"&&!Array.isArray(n),"isDoc");return e(t)?[t,t.channel,t.data].filter(e):[]}i(ra,"channelAnswerDocs");async function xn(t,e={}){let n=e.waitMs??So,r=e.pollMs??To,o=Date.now()+n;for(;;){let s;try{s=await t()}catch(u){return{refused:"read",detail:`the read of its answer was refused (${u instanceof Error?u.message:String(u)})`}}let a=ra(s);if(a.map(u=>u.engine).find(u=>typeof u=="string")==="convex")return{refused:"convex",detail:"its answer names the engine convex, which has no kernel table"};let c=a.map(u=>u.kernelTableId).find(u=>typeof u=="number"&&Number.isInteger(u)&&u>=0&&u<=4294967295);if(c!==void 0)return{table:c};if(Date.now()+r>o)return{refused:"pending",detail:`its answer named no kernelTableId within ${n} ms (the compile still pending)`};await new Promise(u=>setTimeout(u,r))}}i(xn,"resolveKernelTableId");function oa(t,e){try{for(let n of e){let r=ie(t,n);if(r.layout==="seq-linked")return r}return ie(t)}catch{return}}i(oa,"decodeLinkedError");async function Ao(t){let e=await In(t.payload),n={frameType:m.PUBLISH,flags:0,headerLen:O,sessionId:t.sessionId,payloadLen:t.payload.byteLength},r={channelId:t.table,partitionId:t.partition,sequence:t.seq,hlcTimestamp:0n,schemaFingerprint:0,qosLevel:t.qosLevel??1,encryptionMode:0,attributesCount:0,payloadHash:e,detachedSignature:new Uint8Array(64)},o=Ln(n,r),s=await t.sign(kt(o));if(s.byteLength!==64)throw new RangeError(`a PUBLISH signature is 64 bytes, got ${s.byteLength}`);let a=Ln(n,{...r,detachedSignature:s}),c=new Uint8Array(a.byteLength+t.payload.byteLength);return c.set(a,0),c.set(t.payload,a.byteLength),t.tlvs&&t.tlvs.length>0?Ie(c,t.tlvs):c}i(Ao,"encodeKernelPublishFrame");var Tn=64;function vo(t){let e=new DataView(t.buffer,t.byteOffset,t.byteLength);if(t.byteLength<se||e.getUint16(6,!1)!==O)throw new RangeError("a SUBSCRIBE signing input is read from the canonical form (headerLen 16, a 32-byte body)");let n=O+e.getUint32(12,!1),r=se;for(let o=0,s=t[O+28];o<s;o++){if(r+3>n)throw new RangeError("a SUBSCRIBE filter runs past the body");r+=3+(t[r+1]<<8|t[r+2])}if(r>n)throw new RangeError("a SUBSCRIBE filter runs past the body");return t.slice(8,r)}i(vo,"kernelSubscribeSigningInput");async function No(t){let e;if(t.sign){e=Ne({sessionId:t.sessionId,envelope:t.envelope,consumerSignature:new Uint8Array(Tn)});let n=await t.sign(vo(e));if(n.byteLength!==Tn)throw new RangeError(`a SUBSCRIBE consumerSignature is 64 bytes, got ${n.byteLength}`);e.set(n,e.byteLength-Tn)}else e=Ne({sessionId:t.sessionId,envelope:t.envelope});return t.tlvs&&t.tlvs.length>0?Ie(e,t.tlvs):e}i(No,"encodeKernelSubscribeFrame");var An=Uint8Array.from([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]),ce="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";function X(t){let e="",n=0;for(;n+2<t.length;n+=3){let r=t[n]<<16|t[n+1]<<8|t[n+2];e+=ce[r>>18&63]+ce[r>>12&63]+ce[r>>6&63]+ce[r&63]}if(n<t.length){let r=t[n]<<16|(n+1<t.length?t[n+1]:0)<<8;e+=ce[r>>18&63]+ce[r>>12&63],n+1<t.length&&(e+=ce[r>>6&63])}return e}i(X,"b64u");function Ht(t){let e=t.replace(/=+$/,""),n=[],r=0,o=0;for(let s of e){let a=ce.indexOf(s==="+"?"-":s==="/"?"_":s);if(a<0)throw new RangeError("not base64url");r=r<<6|a,o+=6,o>=8&&(o-=8,n.push(r>>o&255))}return Uint8Array.from(n)}i(Ht,"b64uDecode");function sa(t){let e=t.split(".")[1];if(e)try{let n=JSON.parse(Mn.decode(Ht(e)));return typeof n.npk_unit=="string"?n.npk_unit:void 0}catch{return}}i(sa,"tokenUnitOf");function ia(t){let e=X(t).replace(/-/g,"+").replace(/_/g,"/");return e+"=".repeat((4-e.length%4)%4)}i(ia,"b64std");var ue=new TextEncoder,Mn=new TextDecoder;function De(){let t=globalThis.crypto;if(!t?.subtle)throw new w("KERNEL_DOOR_CONFIG","Web Crypto (globalThis.crypto.subtle) is not available");return t.subtle}i(De,"subtle");function On(t){let e=new Uint8Array(t);return globalThis.crypto.getRandomValues(e),e}i(On,"randomBytes");async function In(t){return new Uint8Array(await De().digest("SHA-256",t))}i(In,"sha256");var aa=class Dn{static{i(this,"_KernelDoorKey")}jkt;publicKeyRaw;privateKey;constructor(e,n,r){this.privateKey=e,this.publicKeyRaw=n,this.jkt=r}static async fromSeed(e){if(e.byteLength!==32)throw new RangeError("an Ed25519 seed is 32 bytes");let n=new Uint8Array(An.byteLength+32);n.set(An,0),n.set(e,An.byteLength);let r=await De().importKey("pkcs8",n,{name:"Ed25519"},!0,["sign"]),o=await De().exportKey("jwk",r);if(typeof o.x!="string")throw new w("KERNEL_DOOR_CONFIG","Ed25519 key export carried no public x");let s=Ht(o.x),a=`{"crv":"Ed25519","kty":"OKP","x":"${X(s)}"}`,c=X(await In(ue.encode(a)));return new Dn(r,s,c)}static async generate(){return Dn.fromSeed(On(32))}async sign(e){return new Uint8Array(await De().sign({name:"Ed25519"},this.privateKey,e))}async dpopProof(e,n,r=Date.now()){let o={typ:"dpop+jwt",alg:"EdDSA",jwk:{kty:"OKP",crv:"Ed25519",x:X(this.publicKeyRaw)}},s={jti:X(On(16)),htm:"POST",htu:`https://${e}/v1/npp`,iat:Math.floor(r/1e3),ath:X(await In(ue.encode(n)))},a=`${X(ue.encode(JSON.stringify(o)))}.${X(ue.encode(JSON.stringify(s)))}`;return`${a}.${X(await this.sign(ue.encode(a)))}`}},Co="pass nodeKeys: the JWKS the kernel serves at GET /.well-known/npp-cell-jwks.json on its control door, its https:// URL, or the raw 32-byte Ed25519 key";function ca(t){if(t==null)throw new w("KERNEL_DOOR_CONFIG",`no node key source to verify the HELLO_ACK with: ${Co}`);if(t instanceof Uint8Array){if(t.byteLength!==32)throw new w("KERNEL_DOOR_CONFIG",`a raw node key is 32 bytes (Ed25519), got ${t.byteLength}`);return{raws:[t]}}if(typeof t=="string"){let e;try{e=new URL(t)}catch{throw new w("KERNEL_DOOR_CONFIG",`nodeKeys is not a URL: ${JSON.stringify(t)}`)}if(e.protocol!=="https:")throw new w("KERNEL_DOOR_CONFIG",`a node JWKS URL must be https://, got ${e.protocol}//`);return{url:e.toString()}}return{raws:Oo(t)}}i(ca,"classifyNodeKeys");function Oo(t){let e=t?.keys;if(!Array.isArray(e))throw new w("KERNEL_DOOR_CONFIG",`nodeKeys is not a JWKS document (no keys array): ${Co}`);let n=[];for(let r of e){if(r?.kty!=="OKP"||r.crv!=="Ed25519"||typeof r.x!="string"||r.use!==void 0&&r.use!=="sig")continue;let o;try{o=Ht(r.x)}catch{continue}o.byteLength===32&&n.push(o)}if(n.length===0)throw new w("KERNEL_DOOR_CONFIG","the node key set holds no Ed25519 signing key (kty OKP, crv Ed25519)");return n}i(Oo,"ed25519KeysOf");async function fo(t){let e=[];for(let n of t)try{e.push(await De().importKey("raw",n,{name:"Ed25519"},!1,["verify"]))}catch{}if(e.length===0)throw new w("KERNEL_DOOR_CONFIG","none of the node keys is a usable Ed25519 public key");return e}i(fo,"importVerifyKeys");async function ua(t,e){let n=ca(t);if("raws"in n)return fo(n.raws);let r=e??globalThis.fetch;if(typeof r!="function")throw new w("KERNEL_DOOR_CONFIG",`no fetch to read the node JWKS at ${n.url}; pass the JWKS document instead`);let o,s;try{let a=await r(n.url,{headers:{accept:"application/json"}});if((a.status===401||a.status===403)&&(s=a.status),!a.ok)throw new Error(`HTTP ${a.status}`);o=await a.json()}catch(a){throw s!==void 0?new w("KERNEL_DOOR_UNAVAILABLE",`the keys at ${n.url} were refused to this read (HTTP ${s}): that address answers a signed-in npayload client only. Pass the key document itself as nodeKeys, or open the session from your npayload client, which reads them with its own credential.`):new w("KERNEL_DOOR_UNAVAILABLE",`could not read the node JWKS at ${n.url}: ${a.message}`)}return fo(Oo(o))}i(ua,"loadNodeVerifyKeys");async function da(t,e,n){for(let r of t)try{if(await De().verify({name:"Ed25519"},r,e,n))return!0}catch{}return!1}i(da,"verifiesUnderAny");function fa(){let t=globalThis.WebSocket;if(typeof t!="function")throw new w("KERNEL_DOOR_UNAVAILABLE","no global WebSocket in this runtime; pass the `webSocket` factory option (Node < 22: the `ws` package)");return e=>new t(e)}i(fa,"defaultWebSocketFactory");async function la(t){if(t instanceof Uint8Array)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);if(typeof t=="string"){try{let n=JSON.parse(t);if(n.type==="npp_frame"&&n.encoding==="base64"&&typeof n.data=="string")return Ht(n.data)}catch{return null}return null}let e=t;return typeof e?.arrayBuffer=="function"?new Uint8Array(await e.arrayBuffer()):null}i(la,"messageBytes");function Io(t){let e=t.find(n=>n.key==="npp_delivery_token")?.value;if(!(typeof e!="string"||!/^[0-9a-fA-F]{32}$/.test(e)))return{hi:BigInt(`0x${e.slice(0,16)}`),lo:BigInt(`0x${e.slice(16)}`)}}i(Io,"deliveryTokenOf");function pa(t){if(t===void 0)return{answered:!1,accepted:!1};let e=Q(t.status)??(t.error?Lo[t.status]:void 0);return{answered:!0,accepted:!t.error&&Je.has(t.status),statusCode:t.status,...e!==void 0?{statusName:e}:{},...t.reason?{reason:t.reason}:{}}}i(pa,"ackResultOf");function ha(t){if(t===void 0||t==="beginning")return 0n;if(t==="end")return ao;let e=typeof t=="bigint"?t:t.offset;if(e<0n||e>=ao-1n)throw new RangeError(`start offset out of range: ${e} (0 \u2264 offset < 2^64 \u2212 2)`);return e}i(ha,"startCursorOf");function vn(t,e){return`${t}/${e}`}i(vn,"partitionKey");function Ea(){let t={parkedAt:void 0,moved:Promise.resolve(),wake:i(()=>{},"wake")};return t.moved=new Promise(e=>{t.wake=e}),t}i(Ea,"newFlight");function ga(t,e){t.parkedAt=e;let n=t.wake;t.moved=new Promise(r=>{t.wake=r}),n()}i(ga,"park");function wa(t,e){return{resolve:i(n=>{e.parkedAt=void 0,t.resolve(n)},"resolve"),reject:i(n=>{e.parkedAt=void 0,t.reject(n)},"reject")}}i(wa,"unparking");var ya=/^(?:\[[0-9A-Fa-f:.]+\]|[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?):(\d{1,5})$/;function ma(t,e){let n=ya.exec(e);if(!n)return;let r=Number(n[1]);if(r<1||r>65535)return;let o=new URL(t);return o.host=e,o.toString()}i(ma,"redirectDoor");var Do=class{static{i(this,"KernelSubscription")}constructor(t,e,n,r,o,s){this.session=t,this.table=e,this.handle=n,this.partition=r,this.creditFrames=o,this.creditBytes=s}queue=[];waiters=[];ended;push(t){let e=this.waiters.shift();e?e.resolve(t):this.queue.push(t)}end(t){if(this.ended===void 0){this.ended=t;for(let e of this.waiters.splice(0))t?e.reject(t):e.resolve(null)}}async next(t=3e4){let e=this.queue.shift();if(e)return this.handOut(e);if(this.ended!==void 0){if(this.ended)throw this.ended;return null}let n=await new Promise((r,o)=>{let s=setTimeout(()=>{let c=this.waiters.indexOf(a);c>=0&&this.waiters.splice(c,1),o(new w("KERNEL_DOOR_TIMEOUT",`no delivery within ${t} ms`))},t),a={resolve:i(c=>{clearTimeout(s),r(c)},"resolve"),reject:i(c=>{clearTimeout(s),o(c)},"reject")};this.waiters.push(a)});return n?this.handOut(n):null}handOut(t){return this.session.sendCredit(this.table,this.handle,1,0),t}ack(t){return this.session.sendAck(this.table,this.handle,t.partition,t.offset,t.deliveryToken)}credit(t,e=0){this.session.sendCredit(this.table,this.handle,t,e)}open(){this.session.sendCredit(this.table,this.handle,this.creditFrames,this.creditBytes)}async*[Symbol.asyncIterator](){for(;;){let t=await this.next(2147483647);if(t===null)return;yield t}}},ba=class Un{static{i(this,"_KernelDoorSession")}sessionId;negotiatedCapabilities;door;ws;key;timeoutMs;options;followRedirects;sequenceStore;publishes=new Map;publishPartitions=new Map;awaitingReason=new Map;primaryHints=new Map;links=new Map;routes=new Map;lanes=new Map;owed=[];reasonDueBy;ackDeadline;subscriptions=[];closedWith;goodbyeWaiter;constructor(e){this.ws=e.ws,this.key=e.key,this.door=e.door,this.sessionId=e.sessionId,this.negotiatedCapabilities=e.negotiatedCapabilities,this.timeoutMs=e.timeoutMs,this.options=e.options,this.followRedirects=e.options.followRedirects===!0,this.sequenceStore=e.options.sequenceStore??ze}get engineExt(){return(this.negotiatedCapabilities&Qe)!==0}static async connect(e){let n=_o({door:e.door,env:e.env});if(n.kind!=="kernel"||n.url===void 0)throw new w("KERNEL_DOOR_UNAVAILABLE",`no kernel door configured: pass the door option (wss://host:port/v1/npp) or set ${Bt}`);let r=n.url;if(!e.dpop&&!e.key)throw new w("KERNEL_DOOR_CONFIG","a kernel session needs `key` or `dpop` to sign its HELLO's DPoP proof");let o=await ua(e.nodeKeys,e.fetch),s=e.timeoutMs??15e3,a=e.webSocket??fa(),c=new URL(r).host,u;try{u=a(r)}catch(_){throw new w("KERNEL_DOOR_UNAVAILABLE",`could not open ${r}: ${_.message}`)}u.binaryType="arraybuffer";let f=[],d,l,y,E=Promise.resolve();u.addEventListener("message",_=>{E=E.then(async()=>{let R=await la(_.data);R&&(d?d.onFrame(R):l?l.resolve(R):f.push(R))})}),u.addEventListener("close",_=>{E=E.then(()=>{let R=new w("KERNEL_DOOR_UNAVAILABLE",`the kernel door closed the connection (code ${_?.code??"?"}${_?.reason?`: ${_.reason}`:""})`);d?d.onClosed(R):(y=R,l?.reject(R))})}),await new Promise((_,R)=>{let T=setTimeout(()=>R(new w("KERNEL_DOOR_TIMEOUT",`${r} did not open within ${s} ms`)),s);u.addEventListener("open",()=>{clearTimeout(T),_()}),u.addEventListener("error",p=>{clearTimeout(T),R(new w("KERNEL_DOOR_UNAVAILABLE",`could not connect to ${r}${p?.error?.message??p?.message?`: ${p?.error?.message??p?.message}`:""}`))})});let g=On(32),b=e.dpop,A=e.key,L=ue.encode(JSON.stringify({access_token:e.accessToken,dpop:b?await b.proof(`https://${c}/v1/npp`,e.accessToken):await A.dpopProof(c,e.accessToken),jkt:b?b.jkt:A.jkt,nonce:ia(g),...e.unit!==void 0?{unit:e.unit}:{},...e.sessionTtlSec!==void 0?{sessionTtlSec:e.sessionTtlSec}:{},...e.followRedirects===!0?{redirectOk:!0}:{}})),v=Wr({sessionId:0,nppVersionMajor:Hr,nppVersionMinor:Fr,capabilityFlags:Qe|Kr.HLC,qosCapabilities:1,authBody:L}),S=e.producerEpoch===void 0?[]:[{type:D.PRODUCER_EPOCH,value:Oe(e.producerEpoch)}];u.send(Ie(v,S));let N=Date.now()+s,x=i(()=>{if(y)return Promise.reject(y);let _=f.shift();return _?Promise.resolve(_):new Promise((R,T)=>{let p=setTimeout(()=>{l=void 0,T(new w("KERNEL_DOOR_TIMEOUT",`no HELLO_ACK within ${s} ms`))},Math.max(1,N-Date.now()));l={resolve:i(P=>{clearTimeout(p),l=void 0,R(P)},"resolve"),reject:i(P=>{clearTimeout(p),l=void 0,T(P)},"reject")}})},"nextEarly");try{for(;;){let _=await x(),{canonical:R}=de(_),T=B(R);if(T.frameType===m.ERROR){let U=eo(R).frame;throw new w("KERNEL_DOOR_REFUSED",`HELLO refused: ${Ye(U.reasonCode)}`,U.reasonCode)}if(T.frameType===m.GOODBYE)throw new w("KERNEL_DOOR_REFUSED","the kernel said GOODBYE before HELLO_ACK");if(T.frameType!==m.HELLO_ACK)continue;let p=jr(R);if(!p.nonceEcho||!p.serverSignature)throw new w("KERNEL_DOOR_PROTOCOL","HELLO_ACK carries no node signature trailer (nonceEcho + signature)");let P=!1;for(let U of Gr(R))if(await da(o,p.serverSignature,U)){P=!0;break}if(!P)throw new w("KERNEL_DOOR_PROTOCOL","HELLO_ACK node signature does not verify against the node's published keys");if(!Ra(p.nonceEcho,g))throw new w("KERNEL_DOOR_PROTOCOL","HELLO_ACK nonceEcho is not this connection's nonce");if(p.sessionId===0)throw new w("KERNEL_DOOR_PROTOCOL","HELLO_ACK sessionId MUST be non-zero");d=new Un({ws:u,key:e.key,door:r,sessionId:p.sessionId,negotiatedCapabilities:p.negotiatedCapabilities,timeoutMs:s,options:{...e,door:r,env:{}}});for(let U of f.splice(0))d.onFrame(U);return d}}catch(_){try{u.close()}catch{}throw _ instanceof w?_:new w("KERNEL_DOOR_PROTOCOL",`bad HELLO answer: ${_.message}`)}}send(e){if(this.closedWith!==void 0)throw this.closedWith??new w("KERNEL_DOOR_UNAVAILABLE","the session is closed");this.ws.send(e)}wait(e,n,r){return new Promise((o,s)=>{let a=setTimeout(()=>{n(),s(new w("KERNEL_DOOR_TIMEOUT",`no ${r} within ${this.timeoutMs} ms`))},this.timeoutMs);e({resolve:i(c=>{clearTimeout(a),o(c)},"resolve"),reject:i(c=>{clearTimeout(a),s(c)},"reject")})})}async publish(e){if(e.seq!==void 0)return this.publishAt({...e,seq:e.seq});if(this.closedWith!==void 0)throw this.closedWith??new w("KERNEL_DOOR_UNAVAILABLE","the session is closed");let{answer:n,sequence:r,verdict:o}=await Ze(this.sequenceStore,this.producerScope(e),a=>this.publishAt({...e,seq:a}).then(c=>({result:c,status:c.statusCode}))),{result:s}=n;return o.kind==="stored"?{...s,accepted:!0}:o.kind==="unsettled"?s:{accepted:!1,statusCode:s.statusCode,statusName:s.statusName,sequence:s.sequence,...s.position?{position:s.position}:{},sequenceConflict:{sequence:r,reason:o.reason}}}producerScope(e){let n=this.options,r=n.producerEpoch!==void 0?`epoch ${n.producerEpoch}`:`session ${this.sessionId}`;return{thumbprint:n.dpop?.jkt??this.key?.jkt??"",channelGid:`kernel:${n.unit??sa(n.accessToken)??""}/${e.table}/${e.partition}@${r}`}}async publishAt(e){if(e.seq<1n)throw new RangeError("seq must be \u2265 1 (seq 0 is the SUBSCRIBE acceptance record)");if(this.closedWith!==void 0)throw this.closedWith??new w("KERNEL_DOOR_UNAVAILABLE","the session is closed");let n=vn(e.table,e.partition),r=this.joinLane(n);try{if(!this.followRedirects)return(await this.publishOnce(e,r)).result;let o=await this.routeFor(n);for(let s=0;;s+=1){let{result:a,primary:c}=await o.publishOnce(e,r);if(a.statusCode!==oo||c===void 0||s>=Ro)return a;let u=ma(o.door,c.authority);if(u===void 0)return a;o=await this.linkTo(u),o===this?this.routes.delete(n):this.routes.set(n,u)}}finally{this.leaveLane(r)}}joinLane(e){let n=Ea(),r=this.lanes.get(e);return r?r.push(n):this.lanes.set(e,[n]),{origin:this,key:e,flight:n}}leaveLane(e){let n=this.lanes.get(e.key),r=n?n.indexOf(e.flight):-1;n&&r>=0&&(n.splice(r,1),n.length===0&&this.lanes.delete(e.key)),e.flight.wake()}async turnAt(e,n){for(;;){let r=this.lanes.get(e.key)??[],o=r.indexOf(e.flight),s=o<0?void 0:r.slice(0,o).find(a=>a.parkedAt!==n);if(s===void 0)return;await s.moved}}async routeFor(e){let n=this.routes.get(e);if(n===void 0)return this;let r=await this.links.get(n)?.catch(()=>{});return r!==void 0&&r.closedWith===void 0?r:(this.routes.delete(e),this.primaryHints.delete(e),this)}async linkTo(e){if(e===this.door)return this;let n=this.links.get(e);if(n!==void 0){let o=await n.catch(()=>{});if(o!==void 0&&o.closedWith===void 0)return o;if(this.links.get(e)!==n)return this.linkTo(e);this.links.delete(e)}let r=Un.connect({...this.options,door:e,env:{}});this.links.set(e,r);try{return await r}catch(o){throw this.links.get(e)===r&&this.links.delete(e),o}}async publishOnce(e,n){if(e.seq<1n)throw new RangeError("seq must be \u2265 1 (seq 0 is the SUBSCRIBE acceptance record)");if(this.publishes.has(e.seq))throw new RangeError(`a PUBLISH with seq ${e.seq} is already waiting for its ack`);let r=[];e.ackClass!==void 0&&r.push({type:D.ACK_CLASS,value:ta(e.ackClass)}),e.key&&r.push({type:D.RECORD_KEY,value:e.key}),e.tenant!==void 0&&r.push({type:D.TENANT_SELECT,value:ue.encode(e.tenant)});let o=this.key;if(!o)throw new w("KERNEL_DOOR_CONFIG","a PUBLISH is signed with the session key: connect with `key` to publish");let s=await Ao({sessionId:this.sessionId,table:e.table,partition:e.partition,seq:e.seq,payload:e.payload,sign:i(c=>o.sign(c),"sign"),...this.engineExt?{tlvs:r}:{}});if(await n.origin.turnAt(n,this.door),this.closedWith!==void 0)throw this.closedWith??new w("KERNEL_DOOR_UNAVAILABLE","the session is closed");if(this.publishes.has(e.seq))throw new RangeError(`a PUBLISH with seq ${e.seq} is already waiting for its ack`);let a=this.wait(c=>{this.publishes.set(e.seq,wa(c,n.flight)),this.publishPartitions.set(e.seq,vn(e.table,e.partition))},()=>{this.publishes.delete(e.seq),this.publishPartitions.delete(e.seq),n.flight.parkedAt=void 0},`BULK_ACK for seq ${e.seq}`);return this.send(s),ga(n.flight,this.door),a}async subscribe(e){if(this.owed.some(d=>d.kind==="subscribe"))throw new RangeError("a SUBSCRIBE is already waiting for its acceptance");let n=e.mode==="queue";if(n&&(e.cursorId===void 0||!this.engineExt))throw new w("KERNEL_DOOR_CONFIG",e.cursorId===void 0?"a queue SUBSCRIBE names its durable cursor (cursorId, TLV CURSOR_ID)":"a queue SUBSCRIBE names its cursor in a TLV, which needs a session that negotiated ENGINE_EXT");let r=[];e.partition!==void 0&&r.push({type:D.PARTITION,value:Oe(e.partition)}),e.cursorId!==void 0&&r.push({type:D.CURSOR_ID,value:na(e.cursorId)}),e.tenant!==void 0&&r.push({type:D.TENANT_SELECT,value:ue.encode(e.tenant)});let o=this.key,s=await No({sessionId:this.sessionId,...o?{sign:i(d=>o.sign(d),"sign")}:{},tlvs:r,envelope:{channelId:e.table,mode:n?1:0,deliveryPreference:n?2:0,qosCapabilities:1,partitionFilter:0,startCursor:e.cursorId!==void 0?0n:ha(e.from),startHlc:0n,filters:[]}});this.send(s);let a,c=await this.wait(d=>{a={kind:"subscribe",waiter:d},this.owed.push(a)},()=>this.forgetOwed(a),"SUBSCRIBE acceptance");if(c.error||!Je.has(c.status)){let d=c.error?Ye(c.status):Q(c.status)??Ye(c.status);throw new w("KERNEL_DOOR_REFUSED",`SUBSCRIBE refused: ${d}`,c.status)}let u=Xe(c.tlvs,D.SUBSCRIPTION_HANDLE),f=new Do(this,e.table,u?uo(u):void 0,e.partition,e.credit??64,e.creditBytes??4*1024*1024);return this.subscriptions.push(f),this.closedWith!==void 0?f.end(this.closedWith):f.open(),f}sendCredit(e,n,r,o){if(this.closedWith!==void 0)return;let s=zr(this.sessionId,{channelId:e,creditDelta:r,projectedLagMs:0,bandwidthBudgetBps:0}),a=[];o>0&&a.push({type:D.BYTE_CREDIT,value:Oe(o)}),n!==void 0&&a.push({type:D.SUBSCRIPTION_HANDLE,value:Oe(n)}),this.send(this.engineExt?Ie(s,a):s)}sendAck(e,n,r,o,s){let a=Qr(this.sessionId,e,[{seq:o,disposition:0,...s?{deliveryToken:s}:{}}]),c=[{type:D.PARTITION,value:Oe(r)}];return n!==void 0&&c.push({type:D.SUBSCRIPTION_HANDLE,value:Oe(n)}),this.send(this.engineExt?Ie(a,c):a),new Promise(u=>{this.owed.push({kind:"ack",settle:i(f=>u(pa(f)),"settle"),at:Date.now()}),this.armAckDeadline()})}answerOwed(e){let n;!e.error&&!Je.has(e.status)?n="subscribe":!e.error&&this.engineExt&&(n=Xe(e.tlvs,D.SUBSCRIPTION_HANDLE)?"subscribe":"ack");let r=n===void 0?this.owed.length>0?0:-1:this.owed.findIndex(s=>s.kind===n);if(r<0)return;let[o]=this.owed.splice(r,1);if(o.kind==="ack"){o.settle(e);return}for(let s of this.owed.splice(0,r))s.kind==="ack"&&s.settle(void 0);o.waiter.resolve(e)}controlError(e,n){let r=this.reasonDueBy;this.reasonDueBy=void 0,!(r!==void 0&&Date.now()<=r)&&this.answerOwed({status:e,tlvs:[],error:!0,reason:n})}forgetOwed(e){let n=e===void 0?-1:this.owed.indexOf(e);n>=0&&this.owed.splice(n,1)}armAckDeadline(){if(this.ackDeadline!==void 0)return;let e=this.owed.find(r=>r.kind==="ack");if(e===void 0)return;let n=Math.max(Math.min(zi,this.timeoutMs),e.at+this.timeoutMs-Date.now());this.ackDeadline=setTimeout(()=>{this.ackDeadline=void 0;let r=Date.now(),o=[],s=[],a=!0;for(let c of this.owed){if(c.kind==="ack"&&a){if(r-c.at>=this.timeoutMs){o.push(c);continue}a=!1}s.push(c)}if(o.length>0){this.owed.length=0;for(let c of s)this.owed.push(c)}for(let c of o)c.settle(void 0);this.armAckDeadline()},n)}async close(e=5e3){if(this.closedWith!==void 0)return;let n=[...this.links.values()];this.links.clear(),await Promise.all(n.map(o=>o.then(s=>s.close(e)).catch(()=>{})));let r=new Promise(o=>{let s=setTimeout(o,e);this.goodbyeWaiter=()=>{clearTimeout(s),o()}});try{this.ws.send(no(this.sessionId,{reasonCode:0}))}catch{}await r,this.onClosed(null);try{this.ws.close()}catch{}}onClosed(e){if(this.closedWith!==void 0)return;this.closedWith=e;let n=e??new w("KERNEL_DOOR_UNAVAILABLE","the session is closed");for(let r of this.publishes.values())r.reject(n);this.publishes.clear(),this.publishPartitions.clear();for(let r of this.awaitingReason.values())clearTimeout(r.timer),r.waiter.resolve(r.answer);this.awaitingReason.clear();for(let r of this.links.values())r.then(o=>o.close()).catch(()=>{});this.links.clear(),this.routes.clear();for(let r of this.owed.splice(0))r.kind==="subscribe"?r.waiter.reject(n):r.settle(void 0);this.ackDeadline!==void 0&&clearTimeout(this.ackDeadline),this.ackDeadline=void 0,this.reasonDueBy=void 0;for(let r of this.subscriptions)r.end(e);this.goodbyeWaiter?.()}onFrame(e){let n,r;try{({canonical:n,tlvs:r}=de(e))}catch{return}let o=B(n);switch(o.frameType){case m.PING:this.ws.send(ro(this.sessionId,n.slice(O,O+o.payloadLen)));return;case m.BULK_ACK:{let s=$t(n,r),a=s.length===1?Kt(r):void 0;for(let c of s){if(c.seq===0n){this.reasonDueBy=c.status===so?Date.now()+io:void 0,this.answerOwed({status:c.status,tlvs:r,error:!1});continue}let u=this.publishes.get(c.seq);if(!u)continue;this.publishes.delete(c.seq);let f=this.publishPartitions.get(c.seq);this.publishPartitions.delete(c.seq);let d=c.status===oo&&f!==void 0?this.primaryHints.get(f):void 0,l={result:{accepted:Je.has(c.status),statusCode:c.status,statusName:Q(c.status),sequence:c.seq,...c.position?{position:c.position}:{},...a!==void 0&&Je.has(c.status)?{messageGid:a}:{}},...d?{primary:d}:{}};if(c.status===so){let y=c.seq,E=setTimeout(()=>{let g=this.awaitingReason.get(y);g&&(this.awaitingReason.delete(y),g.waiter.resolve(g.answer))},io);this.awaitingReason.set(y,{waiter:u,answer:l,timer:E});continue}u.resolve(l)}return}case m.DELIVER:this.route(this.readDeliver(n),void 0);return;case m.DELIVER_BATCH:{let s=Xe(r,D.SUBSCRIPTION_HANDLE),a=s?uo(s):void 0,c=new DataView(n.buffer,n.byteOffset,n.byteLength),u=c.getUint16(O,!1),f=O+2;for(let d=0;d<u;d+=1){let l=c.getUint32(f,!1);f+=4,this.route(this.readDeliver(de(n.slice(f,f+l)).canonical),a),f+=l}return}case m.ERROR:{let s=this.owed.length>0||this.reasonDueBy!==void 0,a=[...this.awaitingReason.keys(),...s?[0n]:[]],c=oa(n,a);if(!c||c.layout!=="seq-linked"||c.seq===void 0)return;if(c.seq===0n){this.controlError(c.code,c.reason);return}let u=this.awaitingReason.get(c.seq);if(u){this.awaitingReason.delete(c.seq),clearTimeout(u.timer);let f=c.reason;go(f)?u.waiter.reject(new mo(u.answer.result.statusCode,f)):yo(f)?u.waiter.reject(new bo(u.answer.result.statusCode,f)):u.waiter.resolve(u.answer)}return}case m.GOODBYE:this.onClosed(null);return;case m.SYS_EVENT:this.onSysEvent(n);return;default:return}}onSysEvent(e){if(!this.followRedirects)return;let n;try{let r=Zr(e).frame;if(r.eventCode!==Zi)return;n=JSON.parse(Mn.decode(r.payload))}catch{return}typeof n?.table!="number"||typeof n.partition!="number"||typeof n.authority!="string"||this.primaryHints.set(vn(n.table,n.partition),{authority:n.authority})}readDeliver(e){let n=$i(e),r=Io(n.attributes);return{table:n.channelId,partition:n.partitionId,offset:n.sequence,hlc:n.hlcTimestamp,position:{partition:n.partitionId,offset:n.sequence},attributes:n.attributes,payload:n.payload,...r?{deliveryToken:r}:{}}}route(e,n){((n!==void 0?this.subscriptions.find(o=>o.handle===n):void 0)??this.subscriptions.find(o=>o.table===e.table&&(o.partition===void 0||o.partition===e.partition))??this.subscriptions.find(o=>o.table===e.table))?.push(e)}};function Ra(t,e){if(t.byteLength!==e.byteLength)return!1;let n=0;for(let r=0;r<t.byteLength;r+=1)n|=t[r]^e[r];return n===0}i(Ra,"bytesEqual");var La=m.PUBLISH,Fl=m.BULK_ACK,_a=48;function Bn(t){let e=new Uint8Array(t.byteLength);return e.set(t),e}i(Bn,"copyToArrayBuffer");async function Uo(t){let e=globalThis.crypto.subtle,n=new TextEncoder().encode(JSON.stringify(t.payload)),r=await e.digest("SHA-256",Bn(n)),o=new Uint8Array(r);if(o.byteLength!==Ae)throw new Error(`payloadHash must be ${Ae} bytes, got ${o.byteLength}`);let s=new Uint8Array(Ge);s.set(Y({frameType:La,flags:0,headerLen:h,sessionId:t.sessionId,payloadLen:n.byteLength}),0);let a=new DataView(s.buffer,s.byteOffset,s.byteLength);a.setUint32(16,t.channelId??1,!1),a.setUint32(20,t.partitionId??0,!1),a.setBigUint64(24,t.sequence,!1),a.setBigUint64(32,0n,!1),a.setUint32(40,0,!1),s[44]=t.qosLevel??1,s[45]=0,a.setUint16(46,0,!1),s.set(o,48);let c=kt(s),u=await e.sign("Ed25519",t.ed25519PrivateKey,Bn(c)),f=new Uint8Array(u);if(f.byteLength!==H)throw new Error(`ed25519 signature must be ${H} bytes, got ${f.byteLength}`);s.set(f,80);let d=new Uint8Array(Ge+n.byteLength);return d.set(s,0),d.set(n,Ge),d}i(Uo,"buildSignedPublishFrame");async function ko(t){let e=Ne({sessionId:t.sessionId,envelope:{channelId:1,mode:t.mode,deliveryPreference:t.deliveryPreference,qosCapabilities:0,partitionFilter:0,startCursor:t.startCursor??0n,startHlc:t.startHlc??0n,filters:[]},consumerSignature:new Uint8Array(H)}),n=await globalThis.crypto.subtle.sign("Ed25519",t.ed25519PrivateKey,Bn(_n(e))),r=new Uint8Array(n);if(r.byteLength!==H)throw new Error(`ed25519 sig must be ${H} bytes`);return e.set(r,_a),e}i(ko,"buildSignedSubscribeFrame");function Po(t){if(t.byteLength<h+10)throw new Error(`BULK_ACK too short: ${t.byteLength}`);let{canonical:e,tlvs:n}=de(t),r=$t(e,n),o=r[0];if(!o)throw new RangeError("BULK_ACK carries no record");let s=r.length===1?Kt(n):void 0;return{sessionId:B(e).sessionId,seq:o.seq,status:o.status,...o.position?{position:o.position}:{},...s!==void 0?{messageGid:s}:{}}}i(Po,"decodeBulkAck");function F(t){return typeof t=="string"&&t.length>0?t:void 0}i(F,"str");function $n(t){let e=t.split(".");if(e.length<2)return{};try{let n=e[1].replace(/-/g,"+").replace(/_/g,"/"),r=n.length%4===0?"":"=".repeat(4-n.length%4),o=typeof Buffer<"u"?Buffer.from(n+r,"base64").toString("utf8"):atob(n+r);return JSON.parse(o)}catch{return{}}}i($n,"decodeJwtClaims");function Sa(t){return F(t["npayload/orgId"])??F(t.orgId)??F(t.org)??F(t.org_id)??F(t.sub)}i(Sa,"orgOfClaims");async function xo(t){if(t!==void 0)return Sa($n(typeof t=="function"?await t():t))}i(xo,"orgOfCredential");var Ta=/^[a-z0-9][a-z0-9._-]{0,127}$/;function Aa(t){let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e=Math.imul(e,16777619)>>>0;return e.toString(16).padStart(8,"0")}i(Aa,"fnv1aHex");function va(t){return Ta.test(t)?t:`${t.toLowerCase().replace(/[^a-z0-9._-]/g,"-").replace(/^[^a-z0-9]+/,"").slice(0,110)||"x"}-h${Aa(t)}`}i(va,"kernelSafeName");function Mo(t,e){return va(`${t}.${e}`)}i(Mo,"kernelUnitFor");function Bo(t){let e=i(n=>n!==null&&typeof n=="object"&&!Array.isArray(n),"isDoc");return e(t)?[t,t.channel,t.data].filter(e):[]}i(Bo,"answerDocs");function Jl(t){let e=Bo(t);return e.some(n=>n.engine==="convex")?!1:e.some(n=>n.engine==="kernel"||typeof n.kernelTable=="string"&&n.kernelTable!==""||typeof n.kernelTableId=="number"&&Number.isInteger(n.kernelTableId))}i(Jl,"channelAnswerNamesKernelTable");function $o(t){for(let e of Bo(t)){let n=F(e.appId),r=F(e.envId);if(n!==void 0&&r!==void 0)return Mo(n,r)}}i($o,"channelAnswerUnit");function Yl(t){let e=$n(t),n=F(e["npayload/appId"])??F(e.app),r=F(e["npayload/envId"]);return n!==void 0&&r!==void 0?Mo(n,r):void 0}i(Yl,"tokenUnit");var Na={1:"REJECTED_VERSION",2:"REJECTED_QOS",[Ce.FRAME_MALFORMED]:"FRAME_MALFORMED",[Ce.PROTOCOL_VIOLATION]:"PROTOCOL_VIOLATION",[Ce.UPSTREAM_REFUSED]:"UPSTREAM_REFUSED",501:"UNSUPPORTED",502:"SESSION_EXPIRED"};function Ft(t){return Q(t)??(t===qr.REJECTED_HW_ATTESTATION?"REJECTED_HW_ATTESTATION":void 0)}i(Ft,"nppStatusName");function Vt(t){return Na[t]??Ft(t)}i(Vt,"nppErrorName");var Ca=new Set(["REJECTED_AUTH","SESSION_EXPIRED","REJECTED_SIGNATURE","REJECTED_GRANT"]),Oa=new Set(["DEFERRED_RETRY","DEFERRED_UNDER_REPLICATED","REJECTED_QUOTA"]),Ia=new Set(["FRAME_MALFORMED","PROTOCOL_VIOLATION","UNSUPPORTED","REJECTED_VERSION","REJECTED_QOS"]);function ep(t){return t===void 0?"protocol":Ca.has(t)?"auth":Oa.has(t)?"deferred":Ia.has(t)?"protocol":"admission"}i(ep,"nppRefusalClass");var Da=new Set([301,302,303,307,308]),Ko=20,Ua=["authorization","proxy-authorization","cookie","dpop"],ka=["content-type","content-length","content-encoding","content-language","content-location"];function Ho(t,e){if(t===void 0)return;let n=i(r=>e.includes(r.toLowerCase()),"dropped");if(t instanceof Headers){let r=new Headers(t);for(let o of e)r.delete(o);return r}return Array.isArray(t)?t.filter(([r])=>!n(r)):Object.fromEntries(Object.entries(t).filter(([r])=>!n(r)))}i(Ho,"withoutHeaders");function Pa(t){return typeof t=="string"?t:t instanceof URL?t.href:t.url}i(Pa,"urlOf");function qt(t){try{let e=new URL(t).origin;return e&&e!=="null"?e:t}catch{return t}}i(qt,"originOf");async function Kn(t){try{await t.body?.cancel()}catch{}}i(Kn,"discard");function Fo(t,e,n){return async(r,o)=>{let s=Pa(r),a=t(s);if(a!==void 0)throw e(a,s);let c=n??globalThis.fetch,u={...o??{},redirect:"manual"},f=s;for(let d=0;;d+=1){let l=await c(d===0?r:f,u),y=Da.has(l.status)?l.headers.get("location"):null;if(y===null)return l;let E=new URL(y,f).href,g=t(E);if(g!==void 0)throw await Kn(l),e(`the redirect from ${qt(f)} to ${qt(E)} is not followed: ${g}`,E);if(d===Ko)throw await Kn(l),new TypeError(`fetch failed: more than ${Ko} redirects from ${s}`);let b=(u.method??"GET").toUpperCase(),A=l.status===303&&b!=="HEAD"||(l.status===301||l.status===302)&&b==="POST",L=u.headers;A&&(L=Ho(L,ka)),qt(E)!==qt(f)&&(L=Ho(L,Ua)),u={...u,...A?{method:"GET",body:null}:{},...L!==void 0?{headers:L}:{}},await Kn(l),f=E}}}i(Fo,"dialFetch");var Vo=Symbol.for("npayload.error.nppTransport"),ye=class t extends Error{static{i(this,"NppTransportError")}code;status;upstreamCode;details;constructor(e,n,r){super(e),this.name="NppTransportError",this.code=n,this.details=r,this.status=r.status,this.upstreamCode=r.upstreamCode,Object.defineProperty(this,Vo,{value:!0})}static[Symbol.hasInstance](e){return this!==t?Function.prototype[Symbol.hasInstance].call(this,e):typeof e=="object"&&e!==null&&e[Vo]===!0}},qo=Symbol.for("npayload.error.transportUnavailable"),ge=class t extends ye{static{i(this,"TransportUnavailableError")}constructor(e,n="npp",r={}){super(e,"TRANSPORT_UNAVAILABLE",{failedTransport:n,...r}),this.name="TransportUnavailableError",Object.defineProperty(this,qo,{value:!0})}static[Symbol.hasInstance](e){return this!==t?Function.prototype[Symbol.hasInstance].call(this,e):typeof e=="object"&&e!==null&&e[qo]===!0}},Hn=class extends ye{static{i(this,"TransportRefusedError")}constructor(e,n){super(e,"TRANSPORT_REFUSED",{failedTransport:"npp",...n}),this.name="TransportRefusedError"}},we=class extends ye{static{i(this,"NppKernelDoorError")}constructor(e,n,r={}){super(`${e}: ${n}`,e,{failedTransport:"npp",...r}),this.name="NppKernelDoorError"}},Fn=class extends ye{static{i(this,"NppRefusedError")}refusal;constructor(e,n,r){super(e,"NPP_REFUSED",{failedTransport:"npp",...r,upstreamCode:n.name??qn(n.code),...n.reason?{upstreamMessage:n.reason}:{}}),this.name="NppRefusedError",this.refusal=n}},Vn=class extends ye{static{i(this,"NppProtocolError")}frameType;constructor(e,n,r){super(e,"NPP_PROTOCOL",{failedTransport:"npp",...r}),this.name="NppProtocolError",this.frameType=n}},Yo=new Set([429,500,502,503,504]),xa=`0x${Qe.toString(16).padStart(4,"0")}`,Ma=2147483647;function Ba(t){let e=t.producerEpoch;if(typeof e!="number"||!Number.isInteger(e)||e<0||e>Ma)throw new we("KERNEL_CONFIG",`producerEpoch must be an integer from 0 to 0x7FFF_FFFF (the node's implicit epochs start at 0x8000_0000), got ${String(e)}; nothing was sent.`);if(typeof t.readChannel!="function")throw new we("KERNEL_CONFIG","the kernel door needs `readChannel`, the client's read of a channel's answer; nothing was sent.");let n=t.credential;if(n!==void 0&&(typeof n.accessToken!="function"||typeof n.proof!="function"))throw new we("KERNEL_CONFIG","the kernel door's `credential` needs `accessToken` and `proof`; nothing was sent.")}i(Ba,"assertKernelDoorOptions");var $a=6e4,Ka=50,Ha=5e3,Fa="NPAYLOAD_TEST_RESTART_WINDOW_MS";function Va(){let t=globalThis.process?.env;if(!t||t.VITEST!=="true")return;let e=t[Fa];if(e===void 0||e==="")return;let n=Number(e);return Number.isFinite(n)&&n>=0?n:void 0}i(Va,"harnessRestartWindowMs");function qa(t){return t!==void 0&&Number.isFinite(t)&&t>=0?t:Va()??$a}i(qa,"restartWindowFor");function Wa(t){let e=t.get("Retry-After");if(e===null||e.trim()==="")return;let n=Number(e.trim());if(Number.isFinite(n)&&n>=0)return Math.round(n*1e3);let r=Date.parse(e);return Number.isNaN(r)?void 0:Math.max(0,r-Date.now())}i(Wa,"retryAfterMs");function Wo(t,e,n,r){if(t>=e)return;let o=n-Date.now();if(o<=0||r!==void 0&&r>o)return;let s=Math.min(Ha,Ka*2**Math.min(t-1,16))*(.8+Math.random()*.4);return Math.min(Math.max(r??0,Math.round(s)),o)}i(Wo,"nextRepostWaitMs");function gp(t){let e=qn(t.statusCode),n=t.statusName??Ft(t.statusCode)??"UNREGISTERED_STATUS";if(t.sequenceConflict)return`NPP publish not stored: the broker answered ${n} (BULK_ACK ${e}, HTTP ${t.httpStatus}) for producer sequence ${t.sequenceConflict.sequence} \u2014 ${t.sequenceConflict.reason}`;let r=`NPP publish rejected by the edge: ${n} (BULK_ACK ${e}, HTTP ${t.httpStatus})`;if(t.error){let o=`0x${t.error.code.toString(16).padStart(4,"0")}`,s=t.error.name??o;r+=` \u2014 ${s}${t.error.name?` (${o})`:""}${t.error.reason?`: ${t.error.reason}`:""}`}return t.upstream&&(t.upstream.component||t.upstream.status!==void 0)&&(r+=` [upstream ${t.upstream.component??"unknown"}${t.upstream.status!==void 0?` ${t.upstream.status}`:""}]`),r}i(gp,"describeNppRejection");function Ga(t,e){for(let n of t.slice(1)){if(n.byteLength<h||n[4]!==m.ERROR)continue;let r=ie(n,e);return{code:r.code,name:Vt(r.code),reason:r.reason}}}i(Ga,"linkedErrorSideband");function ja(t){let e=t.get("X-NPayload-Upstream-Component")??void 0,n=t.get("X-NPayload-Upstream-Status"),r=n!==null&&/^\d+$/.test(n.trim())?Number(n.trim()):void 0;if(!(e===void 0&&r===void 0))return{...e!==void 0?{component:e}:{},...r!==void 0?{status:r}:{}}}i(ja,"upstreamFromHeaders");var Ja=8*1024;function Ya(t){if(t.byteLength<h)return!1;for(let e=0;e<oe.length;e+=1)if(t[e]!==oe[e])return!1;return!0}i(Ya,"isNppFrame");function Xa(t){let e;try{e=JSON.parse(new TextDecoder().decode(t.subarray(0,Ja)))}catch{return{}}if(!e||typeof e!="object")return{};let n=e,r=n.error&&typeof n.error=="object"?n.error:void 0,o=te(e)??r?.code??n.code??(typeof n.error=="string"?n.error:void 0),s=r?.message??n.message;return{...typeof o=="string"&&o?{upstreamCode:o}:{},...typeof s=="string"&&s?{upstreamMessage:s}:{}}}i(Xa,"readUpstream");function Qa(t,e,n,r){let o=t.headers.get("content-type")??void 0,{upstreamCode:s,upstreamMessage:a}=Xa(e),c={status:t.status,url:n,...o?{contentType:o}:{},...s?{upstreamCode:s}:{},...a?{upstreamMessage:a}:{}},u=`answered HTTP ${t.status}`+(o?` (${o})`:"")+(s?` with code ${s}`:"")+(a?`: ${a}`:"")+", which is not an NPP frame";return Yo.has(t.status)?new ge(`npp: the frame door ${n} ${u}, on every one of ${r} attempt(s) across the restart window; the NPP transport is unavailable and the operation was not downgraded to HTTP/JSON.`,"npp",c):new Hn(`npp: the frame door ${n} ${u}; the operation was refused, not retried, and not downgraded to HTTP/JSON.`,c)}i(Qa,"nonFrameAnswer");function qn(t){return`0x${t.toString(16).padStart(4,"0")}`}i(qn,"hex16");function za(t){for(let[e,n]of Object.entries(m))if(n===t)return e;return`0x${t.toString(16).padStart(2,"0")}`}i(za,"frameTypeWord");function Za(t,e){return`${t.name??"UNREGISTERED_CODE"} (ERROR ${qn(t.code)}, HTTP ${e})${t.reason?`: ${t.reason}`:""}`}i(Za,"describeNppRefusal");function ec(t,e){try{let{canonical:n}=de(t),r=e!==void 0&&e!==0n?[e,0n]:[0n];for(let s of r){let a=ie(n,s);if(a.layout==="seq-linked")return{code:a.code,name:Vt(a.code),reason:a.reason}}let o=ie(n);return{code:o.code,name:Vt(o.code),reason:o.reason}}catch{return}}i(ec,"readFrameDoorError");function tc(t,e,n,r,o){let s=t.headers.get("content-type")??void 0,a={status:t.status,url:n,...s?{contentType:s}:{}},c=r>1?` on every one of ${r} attempts across the restart window`:"",u=e[4];if(u===m.ERROR){let d=ec(e,o);if(d)return new Fn(`npp: the frame door ${n} refused the frame${c}: ${Za(d,t.status)}`,d,a)}let f=u===m.ERROR?"an ERROR frame too short or too malformed to carry its code":`a ${za(u)} frame (type 0x${u.toString(16).padStart(2,"0")})`;return new Vn(`npp: the frame door ${n} answered HTTP ${t.status} with ${f}${c}, where the answer to a frame is a BULK_ACK or an ERROR; the answer breaks the NPP protocol, so the operation failed and was not downgraded to HTTP/JSON.`,u,a)}i(tc,"frameDoorRefusal");var Xo=Symbol.for("npayload.transport.npp"),Qo=Symbol.for("npayload.transport.npp.edge"),zo=Symbol.for("npayload.transport.npp.frameGuard");function wp(t){return typeof t=="object"&&t!==null&&t[Xo]===!0}i(wp,"isNppTransport");function nc(t){return t[Qo]}i(nc,"nppTransportEdge");function yp(t,e){Object.defineProperty(t,zo,{value:e,configurable:!0})}i(yp,"guardFrames");function Go(t,e){let n=t[zo];if(n!==void 0)return n(e);let r=typeof process<"u"?process.env:{},o=Jn([["the transport's edgeUrl",nc(t)],...Yn(r)]),s=Xn(o,e);return s===void 0?void 0:`${s}. Build the transport with the edge of that estate, or name no other estate in the environment.`}i(Go,"frameRefusal");var jo=class{static{i(this,"NppTransport")}kind="npp";cfg;fetchImpl;sessionId;credentialOrg;sequenceStore;kernelTableIds=new Map;kernelAnswers=new Map;kernelUnits=new Map;constructor(e,n){if(!e||typeof e.edgeUrl!="string"||e.edgeUrl.length===0)throw new Error("NppTransport requires edgeUrl");e.kernel&&Ba(e.kernel),this.cfg=e,Object.defineProperty(this,Xo,{value:!0}),Object.defineProperty(this,Qo,{value:e.edgeUrl}),this.sequenceStore=e.sequenceStore??ze,this.fetchImpl=e.fetchImpl??globalThis.fetch.bind(globalThis),this.sessionId=n!==void 0?n>>>0:globalThis.crypto.getRandomValues(new Uint32Array(1))[0]>>>0}async subscribe(e,n){let r=await ko({sessionId:this.sessionId,ed25519PrivateKey:this.cfg.ed25519PrivateKey,mode:n.mode??0,deliveryPreference:n.deliveryPreference??0,...n.startCursor!==void 0?{startCursor:n.startCursor}:{}}),o=await this.postFrame(r,{"X-NPP-Channel-Gid":e,"X-NPP-Consumer-Id":n.consumerId});return{accepted:o.accepted,statusCode:o.statusCode,transport:"npp"}}async postFrame(e,n,r={},o){let s=`${this.cfg.edgeUrl.replace(/\/+$/,"")}/v1/npp/frame`,a=Go(this,s);if(a!==void 0)throw new ge(`npp: ${a}`,"npp",{url:s});this.credentialOrg??=await xo(this.cfg.accessToken);let c=this.credentialOrg,u={"Content-Type":"application/octet-stream",...c?{"X-NPP-Org-Id":c}:{},"X-NPP-App-Id":this.cfg.appId,"X-NPP-Jkt":this.cfg.jwkThumbprint,"X-NPP-Client-Id":this.cfg.clientId,...n},f=r.maxRetries!==void 0?Math.max(1,r.maxRetries):Number.POSITIVE_INFINITY,d=Date.now()+qa(r.restartWindowMs??this.cfg.restartWindowMs),l=this.cfg.kernel?.credential,y=Fo(E=>Go(this,E),(E,g)=>new ge(`npp: ${E}`,"npp",{url:g}),this.fetchImpl);for(let E=1;;E+=1){let g=u;if(l){let p=await l.accessToken();g={...u,Authorization:`DPoP ${p}`,DPoP:await l.proof(s,p)}}let b,A;try{b=await y(s,{method:"POST",headers:g,body:e}),A=new Uint8Array(await b.arrayBuffer())}catch(p){if(p instanceof ge)throw p;let P=Wo(E,f,d,void 0);if(P!==void 0){await Jo(P);continue}let U=p instanceof Error?p.message:String(p),et=new ge(`npp: the frame door ${s} gave no answer (${U}) on every one of ${E} attempt(s) across the restart window; the NPP transport is unavailable and the operation was not downgraded to HTTP/JSON.`,"npp",{url:s});throw et.cause=p,et}let v=Ya(A)?xt(A):[],S=v[0],N=S!==void 0&&S[4]===m.BULK_ACK?Po(S):void 0;if(Yo.has(b.status)||N?.status===ve.DEFERRED_RETRY){let p=Wo(E,f,d,Wa(b.headers));if(p!==void 0){await Jo(p);continue}}if(S===void 0)throw Qa(b,A,s,E);if(!N)throw tc(b,S,s,E,o);let _=N.messageGid??b.headers.get("X-NPP-Message-Gid")??void 0,R=Ga(v,N.seq),T=ja(b.headers);return{accepted:N.status===ve.ACCEPTED||N.status===ve.ACCEPTED_DUPLICATE,statusCode:N.status,statusName:Ft(N.status),httpStatus:b.status,sequence:N.seq.toString(),..._?{gid:_}:{},...N.position?{position:N.position}:{},...R?{error:R}:{},...T?{upstream:T}:{},attempts:E}}}async publish(e,n,r){let o=this.cfg.kernel,s=o?await this.kernelTableIdOf(e,o):void 0,a=o?.credential?await this.kernelUnitOf(e,o):void 0,c={"X-NPP-Channel-Gid":e,...r?.routingKey?{"X-NPP-Routing-Key":r.routingKey}:{},...o?{"X-NPP-Capabilities":xa,"X-NPP-Producer-Epoch":String(o.producerEpoch)}:{},...a!==void 0?{"X-NPP-Unit":a}:{}},{answer:u,sequence:f,verdict:d}=await Ze(this.sequenceStore,{thumbprint:this.cfg.jwkThumbprint,channelGid:e},async y=>{let E=await Uo({sessionId:this.sessionId,sequence:y,payload:n,ed25519PrivateKey:this.cfg.ed25519PrivateKey,...r?.qosLevel!==void 0?{qosLevel:r.qosLevel}:{},...s!==void 0?{channelId:s}:{}}),g=await this.postFrame(E,c,{...r?.maxRetries!==void 0?{maxRetries:r.maxRetries}:{},...r?.restartWindowMs!==void 0?{restartWindowMs:r.restartWindowMs}:{}},y);return{...g,status:g.statusCode,retried:g.attempts>1}}),l=d.kind==="stored";return{accepted:l,statusCode:u.statusCode,statusName:u.statusName,httpStatus:u.httpStatus,sequence:u.sequence,transport:"npp",...u.gid&&l?{gid:u.gid}:{},...u.position?{position:u.position}:{},...u.error?{error:u.error}:{},...u.upstream?{upstream:u.upstream}:{},...d.kind==="conflict"||d.kind==="rewound"?{sequenceConflict:{sequence:f.toString(),reason:d.reason}}:{}}}async kernelTableIdOf(e,n){let r=this.kernelTableIds.get(e);if(r!==void 0)return r;let o=await xn(async()=>{let s=await n.readChannel(e);return this.kernelAnswers.set(e,s),s},{...n.tableIdWaitMs!==void 0?{waitMs:n.tableIdWaitMs}:{},...n.tableIdPollMs!==void 0?{pollMs:n.tableIdPollMs}:{}});if("refused"in o)throw new we("KERNEL_TABLE_ID_UNRESOLVED",`channel ${e}: ${o.detail}. A PUBLISH to the kernel's door carries the kernelTableId its channel's answer names; no frame was sent.`,{channel:e});return this.kernelTableIds.set(e,o.table),o.table}async kernelUnitOf(e,n){let r=this.kernelUnits.get(e);if(r!==void 0)return r;let o=(n.unit!==void 0&&n.unit!==""?n.unit:void 0)??$o(this.kernelAnswers.get(e))??await n.credential?.unit?.();if(o===void 0||o==="")throw new we("KERNEL_UNIT_UNRESOLVED",`channel ${e}: no unit was given, its answer names no appId and envId, and the credential names no app and environment, so the unit its frames name cannot be read; no frame was sent.`,{channel:e});return this.kernelUnits.set(e,o),o}};function Jo(t){return new Promise(e=>setTimeout(e,t))}i(Jo,"sleep");export{uc as a,Zn as b,C as c,z as d,me as e,ke as f,Z as g,st as h,at as i,fe as j,le as k,ct as l,ft as m,lt as n,ee as o,V as p,er as q,tr as r,nr as s,ut as t,Rc as u,zs as v,Ur as w,m as x,ve as y,kn as z,Pn as A,ze as B,Bt as C,ho as D,Nn as E,go as F,w as G,_o as H,aa as I,Do as J,ba as K,F as L,$n as M,Sa as N,Jl as O,Yl as P,Ft as Q,ep as R,Fo as S,ye as T,ge as U,Hn as V,we as W,Fn as X,Vn as Y,gp as Z,wp as _,nc as $,yp as aa,jo as ba};
@@ -0,0 +1 @@
1
+ import{a as o}from"./chunk-LJNU5QHZ.mjs";var u={agents:[{path:"skills",publicField:"skillGids",parent:"skills",wire:"gid",array:!0,label:"skills"}],skills:[{path:"definition.tools",publicField:"definition.tools",parent:"tools",wire:"name",array:!0,label:"tools"}],triggers:[{path:"agentGid",publicField:"agentGid",parent:"agents",wire:"gid",array:!1,label:"agent"},{path:"action.skillIds",publicField:"action.skillGids",parent:"skills",wire:"gid",array:!0,label:"skills"}]};function p(){return Object.keys(u)}o(p,"relationResources");function c(e){return u[e]??[]}o(c,"refSpecsForResource");function f(e,t){let n=e;for(let r of t.split(".")){if(n==null||typeof n!="object")return;n=n[r]}return n}o(f,"getAtPath");function d(e,t,n){let r=t.split("."),i=e;for(let s=0;s<r.length-1;s++){let l=r[s],a=i[l];(a==null||typeof a!="object"||Array.isArray(a))&&(i[l]={}),i=i[l]}i[r[r.length-1]]=n}o(d,"setAtPath");function y(e){return e==null?null:typeof e=="string"?[e]:Array.isArray(e)&&e.every(t=>typeof t=="string")?e:null}o(y,"refNames");function k(e,t){if(e.length!==t.length)return!1;let n=new Set(e);return t.every(r=>n.has(r))}o(k,"sameNameSet");function R(e,t){let n=new Map,r=e.get(t);if(r)for(let[i,s]of r)n.set(s,i);return n}o(R,"gidToNameFor");function b(e,t,n){if(t.wire==="name")return{resolved:[...e],unresolved:null};let r=n.get(t.parent),i=[];for(let s of e){if(g(s))return{resolved:i,unresolved:s};let l=r?.get(s);if(!l)return{resolved:i,unresolved:s};i.push(l)}return{resolved:i,unresolved:null}}o(b,"resolveRefNames");function g(e){return e.split("_").length===2&&/^[a-z]{2,4}_[A-Za-z0-9]*[0-9][A-Za-z0-9]*$/.test(e)}o(g,"isGid");export{p as a,c as b,f as c,d,y as e,k as f,R as g,b as h,g as i};
@@ -0,0 +1,17 @@
1
+ import{a as G}from"./chunk-F5PMOFZY.mjs";import{S as q}from"./chunk-ZYMM2PCZ.mjs";import{b as J}from"./chunk-ROYJNUAJ.mjs";import{g as H,j as K}from"./chunk-YVGH2T7O.mjs";import{b as D,c as W}from"./chunk-IA5ADBRQ.mjs";import{a as C}from"./chunk-WWSPP7WV.mjs";import{b as B,c as V}from"./chunk-XF6XPU25.mjs";import{b as T,f as M}from"./chunk-JWEUM2BU.mjs";import{U as E}from"./chunk-O7KSYRUO.mjs";import{b as S}from"./chunk-IW34IJP4.mjs";import{a}from"./chunk-LJNU5QHZ.mjs";import{existsSync as Z,readFileSync as pe}from"fs";import{join as ee}from"path";import i from"chalk";import d from"chalk";import ie from"ora";var y=class{static{a(this,"Spinner")}instance;constructor(t){this.instance=ie({text:t,isSilent:!process.stderr.isTTY})}start(t){return t&&(this.instance.text=t),this.instance.start(),this}succeed(t){this.instance.succeed(t)}fail(t){this.instance.fail(t)}warn(t){this.instance.warn(t)}info(t){this.instance.info(t)}stop(){this.instance.stop()}set text(t){this.instance.text=t}};function ke(e){return new y(e).start()}a(ke,"spin");var ce=new Set(["human","table","json","yaml","ndjson"]);function Q(e){if(e===void 0)return"human";let t=e.toLowerCase();if(!ce.has(t))throw new Error("Unknown --output value (not shown here). Use one of: human, table, json, yaml, ndjson.");return t}a(Q,"resolveOutputFormat");function b(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}a(b,"isScalar");function j(e){return e===null?"":String(e)}a(j,"scalarToString");function N(e){if(e==null)return"null";if(typeof e=="number"||typeof e=="boolean")return String(e);let t=String(e);return t===""||/[:#\-?,[\]{}&*!|>'"%@`]/.test(t)||/^\s|\s$/.test(t)||/^(true|false|null|~|\d)/i.test(t)?`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:t}a(N,"yamlScalar");function $(e,t=0){let n=" ".repeat(t);if(b(e)||e===void 0)return`${n}${N(e)}`;if(Array.isArray(e))return e.length===0?`${n}[]`:e.map(s=>{if(b(s)||s===void 0)return`${n}- ${N(s)}`;let c=$(s,t+1).replace(/^ {2}/,"");return`${n}- ${c.replace(/^\s+/,"")}
2
+ ${$(s,t+1).split(`
3
+ `).slice(1).join(`
4
+ `)}`.trimEnd()}).join(`
5
+ `);let r=Object.entries(e);return r.length===0?`${n}{}`:r.map(([s,c])=>b(c)||c===void 0?`${n}${s}: ${N(c)}`:Array.isArray(c)&&c.length===0?`${n}${s}: []`:!Array.isArray(c)&&Object.keys(c).length===0?`${n}${s}: {}`:`${n}${s}:
6
+ ${$(c,t+1)}`).join(`
7
+ `)}a($,"toYaml");function le(e){if(e.length===0)return"(no rows)";let t=[];for(let o of e)for(let p of Object.keys(o))t.includes(p)||t.push(p);let n=a(o=>o==null?"":b(o)?j(o):JSON.stringify(o),"cell"),r=t.map(o=>Math.max(o.length,...e.map(p=>n(p[o]).length))),s=a(o=>o.map((p,g)=>p.padEnd(r[g])).join(" ").trimEnd(),"fmtRow"),c=s(t),l=r.map(o=>"-".repeat(o)).join(" "),f=e.map(o=>s(t.map(p=>n(o[p]))));return[c,l,...f].join(`
8
+ `)}a(le,"toTable");function X(e,t){switch(t){case"json":return JSON.stringify(e,null,2);case"ndjson":return(Array.isArray(e)?e:[e]).map(n=>JSON.stringify(n)).join(`
9
+ `);case"yaml":return $(e);case"table":{let n=Array.isArray(e)?e:[e];return n.every(s=>s!==null&&typeof s=="object"&&!Array.isArray(s))?le(n):$(e)}case"human":default:return x(e)}}a(X,"renderResult");function x(e,t=0){let n=" ".repeat(t);if(b(e)||e===void 0)return`${n}${e===void 0?"":j(e)}`;if(Array.isArray(e))return e.length===0?`${n}${d.dim("(none)")}`:e.map((c,l)=>`${n}${d.dim(`[${l}]`)}
10
+ ${x(c,t+1)}`).join(`
11
+ `);let r=Object.entries(e);if(r.length===0)return`${n}${d.dim("(empty)")}`;let s=Math.max(...r.map(([c])=>c.length));return r.map(([c,l])=>{let f=d.cyan(c.padEnd(s));return b(l)||l===void 0?`${n}${f} ${l===void 0?"":j(l)}`:`${n}${f}
12
+ ${x(l,t+1)}`}).join(`
13
+ `)}a(x,"renderHuman");var z=class{constructor(t){this.format=t;this.tty=t==="human"&&!!process.stderr.isTTY}static{a(this,"StepLog")}tty;spinner=null;lines=[];start(t){this.tty&&(this.spinner=new y(`\u25C9 ${t}`).start())}finish(t){if(this.lines.push(t),!this.tty)return;let n=t.message?d.dim(` (${t.message})`):"",r=`${t.label}${n}`;this.spinner?(t.status==="succeeded"?this.spinner.succeed(`\u2713 ${r}`):t.status==="failed"?this.spinner.fail(`\u2716 ${r}`):t.status==="skipped"?this.spinner.warn(`\u293F ${r}`):this.spinner.info(r),this.spinner=null):process.stderr.write(`${ue(t.status)} ${r}
14
+ `)}all(){return this.lines}hasFailure(){return this.lines.some(t=>t.status==="failed")}};function ue(e){switch(e){case"succeeded":return d.green("\u2713");case"failed":return d.red("\u2716");case"skipped":return d.yellow("\u293F");default:return d.cyan("\u25C9")}}a(ue,"glyph");var Oe="__set_by_npayload_login__",Se="__set_by_npayload_login__",Re="__set_by_npayload_login__";function v(e){if(e==null)return!0;let t=e.trim();return t.length===0?!0:t.startsWith("__set_by_npayload_login__")}a(v,"isPlaceholderCredential");async function te(e,t){try{let n=new URL("/health",e);return await T(D())(n,{signal:AbortSignal.timeout(2500)}),"reachable"}catch(n){return n instanceof E?(t.push(n),"refused"):"unreachable"}}a(te,"reachable");async function de(e,t){let n;try{n=await T(D())(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:"grant_type=client_credentials",signal:AbortSignal.timeout(2500)})}catch(l){return l instanceof E?(t.push(l),{probe:"refused"}):{probe:"unreachable"}}let r;try{r=await n.json()}catch{r=void 0}let s=typeof r=="object"&&r!==null?r.error:void 0;return{probe:(n.status===400||n.status===401)&&typeof s=="string"&&s.length>0?"reachable":"not-a-token-endpoint",status:n.status}}a(de,"tokenEndpointProbe");function he(){let e=process.env.npm_config_user_agent??"";return e.startsWith("bun")?"bun":e.startsWith("pnpm")?"pnpm":e.startsWith("yarn")?"yarn":e.startsWith("npm")?"npm":process.env.BUN_INSTALL?"bun":"unknown"}a(he,"detectPackageManager");function fe(){switch(process.platform){case"darwin":return"macOS Keychain";case"win32":return"Windows Credential Manager";case"linux":return"Linux Secret Service (libsecret)";default:return`${process.platform} (unsupported)`}}a(fe,"keychainBackend");async function me(){let e=await B(),t=!1;if(e)try{let h=await V();t=!!(h?.clientId&&h?.hmacSecret)}catch{t=!1}let n=!!process.env.NPAYLOAD_TOKEN,r=!!(process.env.NPAYLOAD_CLIENT_ID&&(process.env.NPAYLOAD_CLIENT_SECRET||process.env.NPAYLOAD_HMAC_SECRET)),s=J(),c=!!(s?.clientId&&s?.hmacSecret&&!v(s.clientId)&&!v(s.hmacSecret)),l=t||n||r||c,f=[];(process.env.NPAYLOAD_CLIENT_SECRET||process.env.NPAYLOAD_HMAC_SECRET)&&f.push("A client secret is set in the environment. Prefer a short-lived NPAYLOAD_TOKEN, source it from a secret manager, and never commit it to a .env file.");let o=[];l||(e||o.push(process.platform==="linux"?"No OS keychain: install and start a Secret Service (e.g. `gnome-keyring` or KWallet).":"OS keychain is not reachable on this host."),o.push("In a project: run `"+S("init")+"` (provisions machine credentials into .npayload.json).","Interactive: run `"+S("login")+"` (stores the session in the OS keychain).","Headless / CI: export NPAYLOAD_CLIENT_ID + NPAYLOAD_CLIENT_SECRET (or NPAYLOAD_TOKEN)."));let p=!1,g=C(process.env.NPAYLOAD_API_URL,"apiUrl")??"https://api.npayload.com",m=C(process.env.NPAYLOAD_AUTH_URL,"authUrl")??null,A=[],R=await te(g,A),_=m?await te(m,A):null,w=M({authUrl:W().authUrl}),k=await de(w,A),ne=R==="reachable",re=_===null?null:_==="reachable",se=k.probe==="reachable";for(let h of A)o.push(H(`Not probed: ${h.message}`,h));R==="unreachable"&&o.push(`API endpoint ${g} is unreachable \u2014 check your network / status page.`),m&&_==="unreachable"&&o.push(`Auth endpoint ${m} is unreachable \u2014 token minting will fail until it is back.`);let U=m?"Check the auth host NPAYLOAD_AUTH_URL names, or unset it so the CLI gets its token from the API it calls.":"Check your network and npayload's status page.";k.probe==="unreachable"?o.push(`Token endpoint ${w} is unreachable, so no command can get its access token. ${U}`):k.probe==="not-a-token-endpoint"&&o.push(`Token endpoint ${w} answered HTTP ${k.status} but is not a token endpoint, so no command can get its access token. ${U}`);let P="n/a",Y=ee(process.cwd(),"npayload","_generated","contract.lock");if(Z(Y)){try{P=JSON.parse(pe(Y,"utf8")).hash===G?"ok":"stale"}catch{P="stale"}P==="stale"&&o.push("npayload/_generated/contract.lock disagrees with the installed npayload contract \u2014 this project was authored against a different version; re-run `"+S("validate")+"` after upgrading (or reinstall the pinned version).")}let L="n/a";try{let h=q(),F=ee(h,"..","permissions.generated.ts"),{projectAllPermissions:ae}=await import("./chunk-O2USGVDT.mjs"),{checkScopesDrift:oe}=await import("./chunk-2ZK6PEZR.mjs"),O=oe(await ae(),F);L=O.ok?"ok":Z(F)?"stale":"missing",!O.ok&&O.reason&&o.push(O.reason)}catch{L="n/a"}return{os:process.platform,arch:process.arch,node:process.version,packageManager:he(),keychain:{reachable:e,backend:fe()},credentials:{envToken:n,envClient:r,project:c,keychain:t},authReady:l,stack:{apiUrl:g,apiReachable:ne,apiProbe:R,authUrl:m,authReachable:re,authProbe:_,mintUrl:w,mintReachable:se,mintProbe:k.probe,contractLock:P,permissions:L},warnings:f,remediation:o}}a(me,"buildReport");function I(e){return e==="reachable"?i.green("reachable"):e==="not-a-token-endpoint"?i.red("answered, but is not a token endpoint"):e==="refused"?i.yellow("refused by this run's estate (TRANSPORT_UNAVAILABLE)"):i.red("unreachable")}a(I,"probeWords");function u(e){return e?i.green("\u2713"):i.dim("\u25CB")}a(u,"mark");function be(e){let t=["",i.bold(" npayload doctor"),""];t.push(` ${i.dim("platform")} ${e.os} ${e.arch} \xB7 node ${e.node} \xB7 pm ${e.packageManager}`),t.push(` ${u(e.keychain.reachable)} ${i.dim("keychain")} ${e.keychain.backend} \u2014 ${e.keychain.reachable?i.green("reachable"):i.yellow("not reachable")}`),t.push(""),t.push(` ${i.bold("credentials")}`),t.push(` ${u(e.credentials.project)} project credentials (.npayload.json)`),t.push(` ${u(e.credentials.keychain)} login session in OS keychain`),t.push(` ${u(e.credentials.envClient)} NPAYLOAD_CLIENT_ID + NPAYLOAD_CLIENT_SECRET (env)`),t.push(` ${u(e.credentials.envToken)} NPAYLOAD_TOKEN (env, short-lived)`),t.push(""),t.push(` ${i.bold("stack")}`),t.push(` ${u(e.stack.apiReachable)} API ${i.dim(e.stack.apiUrl)} \u2014 ${I(e.stack.apiProbe)}`),e.stack.authUrl&&e.stack.authProbe!==null&&t.push(` ${u(e.stack.authReachable===!0)} auth ${i.dim(e.stack.authUrl)} \u2014 ${I(e.stack.authProbe)}`),t.push(` ${u(e.stack.mintReachable)} token endpoint ${i.dim(e.stack.mintUrl)} \u2014 ${I(e.stack.mintProbe)}`),e.stack.contractLock!=="n/a"&&t.push(` ${u(e.stack.contractLock==="ok")} contract.lock \u2014 ${e.stack.contractLock}`),e.stack.permissions!=="n/a"&&t.push(` ${u(e.stack.permissions==="ok")} permissions.generated.ts \u2014 ${e.stack.permissions}`),t.push("");let n=!e.stack.apiReachable||e.stack.authReachable===!1,r=e.stack.apiProbe==="refused"||e.stack.authProbe==="refused"||e.stack.mintProbe==="refused";e.authReady?r?t.push(` ${i.yellow("! credentials present, but this run's estate refused a probe \u2014 see next")}`):n?t.push(` ${i.yellow("! credentials present, but the stack is unreachable \u2014 see next")}`):e.stack.mintReachable?t.push(` ${i.green("\u2713 ready \u2014 credentials present and the stack is reachable")}`):t.push(` ${i.yellow("! credentials present, but no access token can be minted. See next.")}`):t.push(` ${i.red("\u2716 no credential source available")}`);for(let s of e.warnings)t.push(i.yellow(` ! ${s}`));if(e.remediation.length){t.push(""),t.push(` ${i.bold("next")}`);for(let s of e.remediation)t.push(i.dim(` \u2022 ${s}`))}return t.push(""),t.join(`
15
+ `)}a(be,"renderHuman");function Je(e){e.command("doctor").description("diagnose OS / package manager / keychain reachability, which credential source is available, and the API and token endpoints").option("--output <fmt>","human | table | json | yaml | ndjson").action(async t=>{try{let n=Q(t.output),r=await me();n==="human"?process.stdout.write(be(r)+`
16
+ `):process.stdout.write(`${X(r,n)}
17
+ `);let s=r.stack.authReachable===!1;(!r.authReady||!r.stack.apiReachable||s||!r.stack.mintReachable)&&(process.exitCode=1)}catch(n){K(n)}})}a(Je,"registerDoctor");export{y as a,ke as b,Oe as c,Se as d,Re as e,v as f,Q as g,X as h,z as i,me as j,Je as k};