@aventurevc/mcp-server 0.8.235 → 0.8.237

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 (58) hide show
  1. package/dist/chunks/allowance-type-COW05L2h.js +1 -0
  2. package/dist/chunks/auth-BNDyLTqp-GYAzJXBe.js +1 -0
  3. package/dist/chunks/{cli-help-policy-CEyg0zEz.js → cli-help-policy-CEZPZEOQ.js} +1 -1
  4. package/dist/chunks/client-BwCSrdti.js +1 -0
  5. package/dist/chunks/contract-DuaB1_Ib.js +1 -0
  6. package/dist/chunks/contract-parameter-zkhCaKUz.js +1 -0
  7. package/dist/chunks/detail-Nzc6IsFj.js +1 -0
  8. package/dist/chunks/dist-DaW7WEqw.js +1 -0
  9. package/dist/chunks/entity-Cg2n2mP0.js +1 -0
  10. package/dist/chunks/env-CpA6E7ay.js +1 -0
  11. package/dist/chunks/env-INx_D4Zq.js +1 -0
  12. package/dist/chunks/{esm-Df1PEaVo.js → esm-BjmG0Id8.js} +11 -11
  13. package/dist/chunks/esm-lPyPa01D.js +1 -0
  14. package/dist/chunks/help-catalog-TLFLfBit.js +2 -0
  15. package/dist/chunks/help-intent-mWukB1eR.js +1 -0
  16. package/dist/chunks/http-credentials-BUPEQD7v.js +1 -0
  17. package/dist/chunks/internal-DaW7WEqw.js +1 -0
  18. package/dist/chunks/iso-l1vOidnb.js +56 -0
  19. package/dist/chunks/logging-BHp-5JwI.js +1 -0
  20. package/dist/chunks/logging-CgYAFXRk.js +1 -0
  21. package/dist/chunks/mcp-generation-contract-BqIIjhgK.js +1 -0
  22. package/dist/chunks/oauth-discovery-C4Lo6dIK.js +1 -0
  23. package/dist/chunks/openapi-call-B9zrl6Yl.js +96 -0
  24. package/dist/chunks/openapi-snapshot-BZ96PbpK.js +1 -0
  25. package/dist/chunks/{output-spill-DBSmywMi.js → output-spill-CQ-IUOQG.js} +1 -1
  26. package/dist/chunks/person-owner-BRGa5Dee.js +1 -0
  27. package/dist/chunks/private-telemetry-credential-DbamSREI.js +1 -0
  28. package/dist/chunks/private-telemetry-credential-FZxTymON.js +1 -0
  29. package/dist/chunks/provider-catalog-k5VPfOoO.js +1 -0
  30. package/dist/chunks/request-replay-B983xJ-7.js +1 -0
  31. package/dist/chunks/response-problem-D7yaxq6L.js +1 -0
  32. package/dist/chunks/result-envelope-DXFbrrkt.js +1 -0
  33. package/dist/chunks/rolldown-runtime-B09viugM.js +1 -0
  34. package/dist/chunks/sentry-BDcmqXAw.js +1 -0
  35. package/dist/chunks/sentry-BbZQYSQu.js +1 -0
  36. package/dist/chunks/streamable-http-Mc_ecgj4.js +256 -0
  37. package/dist/chunks/text-response-D44lxcy3.js +15 -0
  38. package/dist/chunks/tool-policy-C37kGt8n.js +1 -0
  39. package/dist/chunks/type-C0VR7LD-.js +1 -0
  40. package/dist/chunks/webapi-B2JTupyg.js +4 -0
  41. package/dist/mcp-server/index.js +2 -257
  42. package/package.json +3 -3
  43. package/dist/chunks/contract-BztWeCTz.js +0 -1
  44. package/dist/chunks/detail-BTjlqGmV.js +0 -1
  45. package/dist/chunks/dist-CGgP_Pxz.js +0 -1
  46. package/dist/chunks/esm-BVGNzX-8.js +0 -1
  47. package/dist/chunks/help-intent-kPjXtxOf.js +0 -1
  48. package/dist/chunks/logging-Bk8_GcPH.js +0 -1
  49. package/dist/chunks/mcp-generation-contract-D0mlhvEk.js +0 -1
  50. package/dist/chunks/openapi-call-Cu_IqRxU.js +0 -96
  51. package/dist/chunks/openapi-snapshot-C2TJ4vNL.js +0 -1
  52. package/dist/chunks/operation-invocation-C29yUZSq.js +0 -2
  53. package/dist/chunks/person-owner-C0YuWKvY.js +0 -56
  54. package/dist/chunks/provider-catalog-Dy5L5Zvr.js +0 -1
  55. package/dist/chunks/reference-recovery-FRzF750i.js +0 -15
  56. package/dist/chunks/response-problem-BGEYFwd5.js +0 -1
  57. package/dist/chunks/result-envelope-5R2VEWAg.js +0 -1
  58. package/dist/chunks/tool-policy-BPefkvzQ.js +0 -1
@@ -0,0 +1,15 @@
1
+ import{C as e,E as t,S as n,_ as r,c as i,d as a,g as o,i as s,n as c,s as l,x as u}from"./iso-l1vOidnb.js";import{A as d,C as f,D as p,E as m,O as h,S as ee,T as te,_ as ne,a as re,b as g,c as ie,d as ae,f as oe,g as se,h as ce,i as le,k as ue,l as de,m as fe,n as pe,o as me,p as he,r as _,s as ge,t as v,u as _e,v as ve,w as ye,x as be,y}from"./detail-Nzc6IsFj.js";import{t as xe}from"./person-owner-BRGa5Dee.js";import{t as b}from"./entity-Cg2n2mP0.js";import{t as x}from"./type-C0VR7LD-.js";import{f as Se}from"./result-envelope-DXFbrrkt.js";import{i as Ce,l as we}from"./tool-policy-C37kGt8n.js";import{a as S,c as Te,i as Ee,l as De,n as C,r as w,s as T,t as E}from"./text-field-jFKOGMzr.js";import{a as Oe,n as D,o as ke,r as Ae,s as O,t as je}from"./human-text-cap-BcNmIPQA.js";import{a as Me,d as k,f as Ne,m as A,o as Pe,p as Fe,u as Ie,x as Le}from"./help-catalog-TLFLfBit.js";import{Buffer as Re}from"node:buffer";var j=`aventure`;function M(e,t,n=`cli`){let r=t.find(t=>t.operationId===e);if(n===`mcp`&&r!==void 0){let e=Pe(r);return`${e.tool} ${JSON.stringify(e.arguments)}`}let i=r?.cliPath;return i===void 0?void 0:`${j} ${i.join(` `)}`}function ze(e,t,n=e,r=`cli`){return r===`mcp`?M(e,t,r)??e:Le(e,t,`aventure`)??n}function Be(e,t,n=`cli`){let r=Ie.safeParse(e);if(!r.success)return null;let{answer:i,citation:a,confidence:o,resolution:s}=r.data;if(s!=null)return Ve(i,s,t,n);let c=i.trimEnd().split(`
2
+ `),l=new Set(a.flatMap(({sourceType:e,sourceId:r})=>{if(e!==Fe.options[0].enum.OPERATION)return[];let i=M(r,t,n);return i===void 0?[]:[i]}));return l.size>0&&c.push(``,n===`mcp`?`MCP calls:`:`Commands:`,...[...l].map(e=>` ${e}`)),c.push(``,`Confidence: ${o}`),a.length===0||(c.push(`Sources (${a.length}):`),c.push(...a.map(({excerpt:e,sourceId:t})=>{let n=e.trim();return n.length>0?` - ${t}: ${n}`:` - ${t}`}))),c}function Ve(e,t,n,r){let{outcome:i,operationId:a,probability:o,candidate:s,taskKey:c,taskPlan:l}=t,u=[l==null?e.trimEnd():Ue(l)],d=[``,`Outcome: ${i}${o==null?``:` (probability ${o.toFixed(2)})`}`];switch(i){case k.enum.TASK_PLAN:return[...u,...l==null?[]:We(l,n,r),...d];case k.enum.OPERATION_ADVICE:{let e=s.filter(({sourceId:e})=>e!==a);return[...u,...a==null?[]:[``,r===`mcp`?`MCP call:`:`Command:`,` ${ze(a,n,a,r)}`],...d,...e.length===0?[]:[`Alternatives: ${e.map(({sourceId:e})=>e).join(`, `)}`]]}case k.enum.CLARIFY:return[...u,...c==null?[]:[``,`Leading catalog task: ${c}`],...Ke(`Candidates:`,s,n,r),...d];case k.enum.ABSTAIN:return[...u,...Ke(`Nearest operations:`,s,n,r),...d];default:throw Error(`Unhandled help resolution outcome ${String(i)}`)}}function He(e,t,n=`cli`){let r=Ne.safeParse(e);return r.success?[Ue(r.data),...We(r.data,t,n)]:null}var Ue=({taskKey:e,catalogRevision:t})=>e===void 0?`Run these steps in order.`:`Run catalog task ${e}${t===void 0?``:` (catalog revision ${t})`}.`;function We(e,t,n){return e.step.length===0?[``,`This catalog task has no planned steps yet.`]:[...e.input.length===0?[]:[``,`Inputs:`,...e.input.map(({key:e,type:t,description:n,required:r})=>` ${e} (${t}, ${r===!1?`optional`:`required`}): ${n}`)],``,`Steps:`,...e.step.flatMap(({step:r,cliCommand:i,writeGuidance:a},o)=>[` ${o+1}. ${r.stepKey===void 0?``:`${r.stepKey}: `}${ze(r.operationId,t,i,n)}`,` ${r.instruction}`,...Ge(e,o,a)]),...e.gateId?.length?[``,`Completion gates: ${e.gateId.join(`, `)}`]:[]]}function Ge(e,t,n){if(n==null)return[];let r=JSON.stringify(n),i=e.step.findIndex(({writeGuidance:e})=>JSON.stringify(e)===r);return i===t?[` Write guidance:`,` - Expectation: ${n.expectation}`,` - Body: ${n.body}`,` - Read first: ${n.typeCatalog}`,` - Rejected when:`,...n.reject.map(e=>` - ${e}`),` - Override: ${n.override}`,` - Method: ${n.method.join(`; `)}`]:[` Write guidance: as step ${i+1}.`]}function Ke(e,t,n,r){if(t.length===0)return[];let i=t.map(({sourceId:e,excerpt:t})=>({command:M(e,n,r)??e,excerpt:t})),a=Math.max(...i.map(({command:e})=>e.length));return[``,e,...i.map(({command:e,excerpt:t})=>` ${e.padEnd(a)} # ${t}`)]}var N=/\{([^}]+)\}/gu;function qe(e,t,n=`cli`){let r=t.filter(e=>e.method===`GET`&&(n===`cli`||e.binaryResponse!==!0)),i=t=>e.endpoint!==void 0&&t.endsWith(e.endpoint),a=t.find(t=>t.operationId===e.operationId),o=e.ok&&a!==void 0&&Ce(a.intent),s=[...o&&e.endpoint!==void 0?Ze(e.endpoint.split(`?`)[0]??``,r,!1,n).map(e=>n===`mcp`?e:`${e} --data --to-file <path>`):[],...e.references.filter(e=>!i(e)).flatMap(Xe).flatMap(e=>Ze(e.pathname,r,!0,n)),...e.references.filter(i).flatMap(Xe).flatMap(e=>Qe(e,r,n))],c=n===`mcp`?Je:void 0;return s.length===0?{write:o,narrowerRead:c}:{exactRecovery:`Read the full result ${s.join(`; `)}.`,write:o,narrowerRead:c}}var Je=`Refetch a narrower result: call aventure_help with q set to the read intent, then call aventure_read with its operationId and declared query or pathParams, using ids/references, filters, or smaller query.page/query.size windows.`;function Ye(e,t){let n=t.find(t=>t.operationId===e.operationId);if(!e.ok||n?.method!==`GET`||n.mutates===!0||Ce(n.intent)||e.endpoint===void 0)return;let r=new URL(e.endpoint,`https://localhost`),i=[...n.path.matchAll(N)].map(([,e])=>e),a=RegExp(`^${n.path.replace(N,`([^/]+)`)}$`,`u`).exec(r.pathname);if(a===null)return;let o=n.parameters.find(e=>e.location===`query`&&e.name===`compact`&&e.schemaType===`boolean`);o!==void 0&&r.searchParams.set(o.name,`true`);let s=[];for(let e of n.parameters){let t=e.location===`path`?[decodeURIComponent(a[i.indexOf(e.name)+1]??``)]:e.location===`query`?r.searchParams.getAll(e.name):[];if(e.required&&t.length===0)return;t.length>0&&s.push(F(e),...t.map(tt))}return`Run: \`${P(n,[...s,`--data`,`--to-file`,`./aventure-output.json`])}\`. On success, the spill file contains the bare payload (top-level keys as returned), not the result envelope or a data.response wrapper.`}function Xe(e){return URL.canParse(e)?[new URL(e)]:[]}function Ze(e,t,n,r){return t.flatMap(t=>{let i=[...t.path.matchAll(N)].map(([,e])=>e),a=RegExp(`^${t.path.replace(N,`([^/]+)`)}$`,`u`),o=n&&i.length===0?null:a.exec(e);if(o===null)return[];if(r===`mcp`)return[$e(t,{pathParams:Object.fromEntries(i.map((e,t)=>[e??``,decodeURIComponent(o[t+1]??``)]))})];let s=i.flatMap((e,n)=>{let r=t.parameters.find(t=>t.name===e);return r===void 0?[]:[F(r),o[n+1]??``]});return[`${et(t)}, ${P(t,s)}`]})}function Qe(e,t,n){let r=t.find(t=>t.path===e.pathname);return r===void 0?[]:t.flatMap(t=>{if(!t.path.startsWith(`${r.path}/`))return[];let i=t.parameters.find(({name:e})=>e.endsWith(`Offset`)),a=t.parameters.find(({name:e})=>e.endsWith(`Limit`));if(i===void 0||a===void 0)return[];if(n===`mcp`)return[`in windows: ${$e(t,{query:{...Object.fromEntries([...e.searchParams].filter(([e])=>t.parameters.some(t=>t.location===`query`&&t.name===e))),[i.name]:`<offset>`,[a.name]:`<limit>`}})}, advancing query.${i.name} until a window returns fewer than query.${a.name} units`];let o=t.parameters.flatMap(t=>{let n=e.searchParams.get(t.name);return t.location!==`query`||n===null?[]:[F(t),tt(n)]}),s=[F(i),`<n>`,F(a),`<n>`];return[`${et(t)}, in windows: ${P(t,[...o,...s])}, advancing ${F(i)} until a window returns fewer than ${F(a)} units`]})}function $e(e,t){return`${we(e.intent)} ${JSON.stringify({operationId:e.operationId,...t})}`}function et(e){return e.auth===`write`?`with admin sign-in`:`with any sign-in`}function P(e,t){return[j,...e.cliPath,...t].join(` `)}function F(e){return e.flag.split(/\s+/u)[0]??e.flag}function tt(e){return`'${e.replaceAll(`'`,`'"'"'`)}'`}var nt=r({detail:n(),field:n().nullish(),scope:s([`entity`,`person`,`news`])}),rt=s([`auto`,`exact`,`keyword`,`semantic`,`natural`,`hybrid`]),it=Object.assign(e([rt,n()]),{enum:rt.enum}),I=r({modeRequested:it,modeUsed:it}),at=r({answerUnavailable:i(),entity:I,news:I,person:I,rejection:l(nt),unavailable:l(s([`entity`,`person`,`news`]))}),ot=r({acceleratorParticipation:l(se),detail:l(ce)}),L=r({core:b,enrichment:te,fundraiseRound:l(y),provider:ve.nullish(),research:ot,semanticMatch:me.nullish()}),st=s([`curated`,`semantic`,`precomputed`,`derived`,`computed`]),ct=r({compositeScore:o().nullish(),cosineScore:o().nullish(),curatedAsOf:n().regex(/^(?!0000)[0-9]{4}(?:-(?:0[1-9]|1[0-2])(?:-(?:0[1-9]|[12][0-9]|3[01])(?:T(?:[01][0-9]|2[0-3]):[0-5][0-9](?::[0-5][0-9](?:\.[0-9]{1,9})?)?(?:Z|[+-](?:(?:0[0-9]|1[0-7]):[0-5][0-9]|18:00)))?)?)?$/).nullish(),curatedRelationshipType:n().nullish(),curatedSource:n().nullish(),derivedFromEntityId:t().nullish(),matchedSectionWeight:o().nullish(),origin:st,rank:a(),sharedSectionCount:a().nullish()}),lt=r({entity:L,similarity:ct}),ut=r({fundraiseInvestorJoin:i(),fundraiseTransaction:i(),operatingStatus:i(),relationship:i()}),dt=s([`Acquisition`,`Acquired`,`Acquired Subsidiary`]),ft=s([`Announced`,`Announced; subject to approvals and closing conditions`,`Active`,`Closed`,`Completed`,`In Progress`,`Open`]),pt=r({acquiredEntity:b,acquirerEntity:b,amount:o().int().nullish(),announcedAt:n().regex(/^(?!0000)[0-9]{4}(?:-(?:0[1-9]|1[0-2])(?:-(?:0[1-9]|[12][0-9]|3[01])(?:T(?:[01][0-9]|2[0-3]):[0-5][0-9](?::[0-5][0-9](?:\.[0-9]{1,9})?)?(?:Z|[+-](?:(?:0[0-9]|1[0-7]):[0-5][0-9]|18:00)))?)?)?$/).nullish(),asOf:n().regex(/^(?!0000)[0-9]{4}(?:-(?:0[1-9]|1[0-2])(?:-(?:0[1-9]|[12][0-9]|3[01])(?:T(?:[01][0-9]|2[0-3]):[0-5][0-9](?::[0-5][0-9](?:\.[0-9]{1,9})?)?(?:Z|[+-](?:(?:0[0-9]|1[0-7]):[0-5][0-9]|18:00)))?)?)?$/).nullish(),completedAt:n().regex(/^(?!0000)[0-9]{4}(?:-(?:0[1-9]|1[0-2])(?:-(?:0[1-9]|[12][0-9]|3[01])(?:T(?:[01][0-9]|2[0-3]):[0-5][0-9](?::[0-5][0-9](?:\.[0-9]{1,9})?)?(?:Z|[+-](?:(?:0[0-9]|1[0-7]):[0-5][0-9]|18:00)))?)?)?$/).nullish(),createdAt:c({offset:!0}).nullish(),currency:n().nullish(),dataConfidence:ee.nullish(),evidence:ut,fundraiseTransactionId:t().nullish(),investorJoinId:t().nullish(),isCurrent:i().nullish(),publicSource:f.nullish(),relationshipId:a(),status:dt,transactionStatus:ft.nullish(),updatedAt:c({offset:!0}).nullish()}),mt=r({entity:v,investorAttribution:l(g),round:l(be),roundCount:a()}),ht=r({core:b,fundingDetail:h.nullish(),similarity:ct,urlLink:l(m)}),gt=r({compliance:fe.nullish(),createdAt:c({offset:!0}).nullish(),id:a(),isCurrent:i().nullish(),isPrimary:i().nullish(),language:n().nullish(),owner:xe,text:n(),textName:n().nullish(),textType:n(),updatedAt:c({offset:!0}).nullish()}),_t=s([`stored`,`derivedFromPreAndRaised`,`derivedFromPostMinusRaised`,`reportedAssumedPost`]),vt=s([`fundraiseRound`,`researchDetail`]),yt=s([`preMoney`,`postMoney`,`reported`]),bt=r({amountRaised:o().int().nullish(),asOfDate:n().regex(/^(?!0000)[0-9]{4}(?:-(?:0[1-9]|1[0-2])(?:-(?:0[1-9]|[12][0-9]|3[01])(?:T(?:[01][0-9]|2[0-3]):[0-5][0-9](?::[0-5][0-9](?:\.[0-9]{1,9})?)?(?:Z|[+-](?:(?:0[0-9]|1[0-7]):[0-5][0-9]|18:00)))?)?)?$/),confidence:de,currency:n(),declaredBasis:yt,derivation:_t,detailId:a().nullish(),label:n().nullish(),source:vt,sourceRef:n(),valuationPostMoney:o().int().nullish(),valuationPreMoney:o().int().nullish()}),xt=r({createdAt:c({offset:!0}).nullish(),description:n().nullish(),forkCount:a(),githubId:o().int(),homepageUrl:n().nullish(),id:o().int(),isArchived:i(),isFork:i(),language:n().nullish(),license:n().nullish(),name:n(),ownerLogin:n(),repoCreatedAt:c({offset:!0}).nullish(),repoPushedAt:c({offset:!0}).nullish(),stargazerCount:a(),topic:l(n()),updatedAt:c({offset:!0}).nullish(),url:n()}),R=r({empty:i().optional(),sorted:i().optional(),unsorted:i().optional()}),z=r({offset:o().int().optional(),paged:i().optional(),pageNumber:a().optional(),pageSize:a().optional(),sort:R.optional(),unpaged:i().optional()}),St=r({investorAttribution:l(g),person:_,round:l(be),roundCount:a()}),Ct=s([`by`,`about`]),wt=s([`newsArticle`,`blogPost`,`externalSocialPost`,`repositoryOwner`,`repository`,`webSite`,`webPage`,`researchPaper`]),Tt=r({canonicalUrl:n().nullish(),contentId:n(),contentType:wt,createdAt:c({offset:!0}).nullish(),publishedAt:c({offset:!0}).nullish(),relation:Ct.nullish(),sourceDomain:n().nullish(),sourceName:n().nullish(),summary:n().nullish(),title:n(),topic:n().nullish(),updatedAt:c({offset:!0}).nullish(),url:n().nullish(),year:a().nullish()});r({content:l(ae).optional(),empty:i().optional(),first:i().optional(),last:i().optional(),number:a().optional(),numberOfElements:a().optional(),pageable:z.optional(),size:a().optional(),sort:R.optional(),totalElements:o().int().optional(),totalPages:a().optional()}),r({content:l(e([d,ue])).optional(),empty:i().optional(),first:i().optional(),last:i().optional(),number:a().optional(),numberOfElements:a().optional(),pageable:z.optional(),size:a().optional(),sort:R.optional(),totalElements:o().int().optional(),totalPages:a().optional()}),r({content:l(ie).optional(),empty:i().optional(),first:i().optional(),last:i().optional(),number:a().optional(),numberOfElements:a().optional(),pageable:z.optional(),size:a().optional(),sort:R.optional(),totalElements:o().int().optional(),totalPages:a().optional()}),r({content:l(b).optional(),empty:i().optional(),first:i().optional(),last:i().optional(),number:a().optional(),numberOfElements:a().optional(),pageable:z.optional(),size:a().optional(),sort:R.optional(),totalElements:o().int().optional(),totalPages:a().optional()}),r({content:l(pt).optional(),empty:i().optional(),first:i().optional(),last:i().optional(),number:a().optional(),numberOfElements:a().optional(),pageable:z.optional(),size:a().optional(),sort:R.optional(),totalElements:o().int().optional(),totalPages:a().optional()}),r({content:l(v).optional(),empty:i().optional(),first:i().optional(),last:i().optional(),number:a().optional(),numberOfElements:a().optional(),pageable:z.optional(),size:a().optional(),sort:R.optional(),totalElements:o().int().optional(),totalPages:a().optional()}),r({content:l(ye).optional(),empty:i().optional(),first:i().optional(),last:i().optional(),number:a().optional(),numberOfElements:a().optional(),pageable:z.optional(),size:a().optional(),sort:R.optional(),totalElements:o().int().optional(),totalPages:a().optional()}),r({content:l(y).optional(),empty:i().optional(),first:i().optional(),last:i().optional(),number:a().optional(),numberOfElements:a().optional(),pageable:z.optional(),size:a().optional(),sort:R.optional(),totalElements:o().int().optional(),totalPages:a().optional()}),r({content:l(mt).optional(),empty:i().optional(),first:i().optional(),last:i().optional(),number:a().optional(),numberOfElements:a().optional(),pageable:z.optional(),size:a().optional(),sort:R.optional(),totalElements:o().int().optional(),totalPages:a().optional()}),r({content:l(L).optional(),empty:i().optional(),first:i().optional(),last:i().optional(),number:a().optional(),numberOfElements:a().optional(),pageable:z.optional(),size:a().optional(),sort:R.optional(),totalElements:o().int().optional(),totalPages:a().optional()}),r({content:l(_e).optional(),empty:i().optional(),first:i().optional(),last:i().optional(),number:a().optional(),numberOfElements:a().optional(),pageable:z.optional(),size:a().optional(),sort:R.optional(),totalElements:o().int().optional(),totalPages:a().optional()}),r({content:l(ne).optional(),empty:i().optional(),first:i().optional(),last:i().optional(),number:a().optional(),numberOfElements:a().optional(),pageable:z.optional(),size:a().optional(),sort:R.optional(),totalElements:o().int().optional(),totalPages:a().optional()}),r({content:l(ce).optional(),empty:i().optional(),first:i().optional(),last:i().optional(),number:a().optional(),numberOfElements:a().optional(),pageable:z.optional(),size:a().optional(),sort:R.optional(),totalElements:o().int().optional(),totalPages:a().optional()}),r({content:l(he).optional(),empty:i().optional(),first:i().optional(),last:i().optional(),number:a().optional(),numberOfElements:a().optional(),pageable:z.optional(),size:a().optional(),sort:R.optional(),totalElements:o().int().optional(),totalPages:a().optional()}),r({content:l(lt).optional(),empty:i().optional(),first:i().optional(),last:i().optional(),number:a().optional(),numberOfElements:a().optional(),pageable:z.optional(),size:a().optional(),sort:R.optional(),totalElements:o().int().optional(),totalPages:a().optional()}),r({content:l(ht).optional(),empty:i().optional(),first:i().optional(),last:i().optional(),number:a().optional(),numberOfElements:a().optional(),pageable:z.optional(),size:a().optional(),sort:R.optional(),totalElements:o().int().optional(),totalPages:a().optional()}),r({content:l(gt).optional(),empty:i().optional(),first:i().optional(),last:i().optional(),number:a().optional(),numberOfElements:a().optional(),pageable:z.optional(),size:a().optional(),sort:R.optional(),totalElements:o().int().optional(),totalPages:a().optional()}),r({content:l(m).optional(),empty:i().optional(),first:i().optional(),last:i().optional(),number:a().optional(),numberOfElements:a().optional(),pageable:z.optional(),size:a().optional(),sort:R.optional(),totalElements:o().int().optional(),totalPages:a().optional()}),r({content:l(bt).optional(),empty:i().optional(),first:i().optional(),last:i().optional(),number:a().optional(),numberOfElements:a().optional(),pageable:z.optional(),size:a().optional(),sort:R.optional(),totalElements:o().int().optional(),totalPages:a().optional()}),r({content:l(xt).optional(),empty:i().optional(),first:i().optional(),last:i().optional(),number:a().optional(),numberOfElements:a().optional(),pageable:z.optional(),size:a().optional(),sort:R.optional(),totalElements:o().int().optional(),totalPages:a().optional()}),r({content:l(oe).optional(),empty:i().optional(),first:i().optional(),last:i().optional(),number:a().optional(),numberOfElements:a().optional(),pageable:z.optional(),size:a().optional(),sort:R.optional(),totalElements:o().int().optional(),totalPages:a().optional()}),r({content:l(re).optional(),empty:i().optional(),first:i().optional(),last:i().optional(),number:a().optional(),numberOfElements:a().optional(),pageable:z.optional(),size:a().optional(),sort:R.optional(),totalElements:o().int().optional(),totalPages:a().optional()}),r({content:l(_).optional(),empty:i().optional(),first:i().optional(),last:i().optional(),number:a().optional(),numberOfElements:a().optional(),pageable:z.optional(),size:a().optional(),sort:R.optional(),totalElements:o().int().optional(),totalPages:a().optional()}),r({content:l(ge).optional(),empty:i().optional(),first:i().optional(),last:i().optional(),number:a().optional(),numberOfElements:a().optional(),pageable:z.optional(),size:a().optional(),sort:R.optional(),totalElements:o().int().optional(),totalPages:a().optional()}),r({content:l(St).optional(),empty:i().optional(),first:i().optional(),last:i().optional(),number:a().optional(),numberOfElements:a().optional(),pageable:z.optional(),size:a().optional(),sort:R.optional(),totalElements:o().int().optional(),totalPages:a().optional()}),r({content:l(le).optional(),empty:i().optional(),first:i().optional(),last:i().optional(),number:a().optional(),numberOfElements:a().optional(),pageable:z.optional(),size:a().optional(),sort:R.optional(),totalElements:o().int().optional(),totalPages:a().optional()}),r({content:l(Tt).optional(),empty:i().optional(),first:i().optional(),last:i().optional(),number:a().optional(),numberOfElements:a().optional(),pageable:z.optional(),size:a().optional(),sort:R.optional(),totalElements:o().int().optional(),totalPages:a().optional()});var Et=r({content:l(L),number:a(),size:a(),totalElements:o().int(),totalPages:a()}),Dt=r({content:l(oe),number:a(),size:a(),totalElements:o().int(),totalPages:a()}),Ot=r({content:l(re),number:a(),size:a(),totalElements:o().int(),totalPages:a()});r({content:l(pe).optional(),empty:i().optional(),first:i().optional(),last:i().optional(),number:a().optional(),numberOfElements:a().optional(),pageable:z.optional(),size:a().optional(),sort:R.optional(),totalElements:o().int().optional(),totalPages:a().optional()});var kt=s([`entityRecord`,`researchSnippet`,`newsArticle`,`personRecord`,`fundraiseTransaction`,`webProfile`]),At=Object.assign(e([kt,n()]),{enum:kt.enum}),jt=r({entityId:t(),source:At,sourceId:n()}),Mt=r({citation:l(jt),text:n(),topic:n().nullish()}),Nt=r({citation:l(jt),confidence:A,description:n().nullish(),heading:n().nullish(),paragraph:l(Mt),relatedQuery:l(n()),shareable:i(),text:n(),title:n().nullish()}),Pt=r({enrichmentRunId:t().nullish(),entityId:t()}),Ft=r({sortPriority:s([`NONE`,`ANY_LOGO_FIRST`,`REAL_LOGO_FIRST`]).optional()}),It=r({max:c({offset:!0}).nullish(),min:c({offset:!0}).nullish()}),B=r({max:o().nullish(),min:o().nullish()}),V=r({max:a().nullish(),min:a().nullish()}),Lt=r({averageAmountInvestedUsdRange:l(B).optional(),largestAmountInvestedUsdRange:l(B).optional(),smallestAmountInvestedUsdRange:l(B).optional(),totalAmountInvestedUsdRange:l(B).optional(),totalInvestmentRange:l(V).optional()}),Rt=s([`any`,`every`]),zt=r({amountInvestedRange:l(B).optional(),amountRaisedRange:l(B).optional(),dateAnnouncedRange:It.nullish(),investedCompanyName:l(n()).optional(),investedCountry:l(n()).optional(),investedIndustry:l(n()).optional(),investedRound:l(n()).optional(),investorActivity:Lt.optional(),investorName:l(n()).optional(),investorNameMatch:Rt.nullish(),lastRoundYearRange:l(V).optional(),rankByInvestmentActivity:i().nullish(),round:l(n()).optional(),totalRaisedRange:l(B).optional(),valuationRange:l(B).optional()}),Bt=s([`NONE`,`COMPANY_LISTING_READY`]),Vt=s([`Operating`,`Acquired`,`Acquired Subsidiary`,`Closed`,`Closed (Acquihire)`,`Inactive`]),Ht=s([`hostPath`,`domain`]),Ut=u({acceleratorBrand:l(n()).optional(),acceleratorCohort:l(n()).optional(),acceleratorName:l(n()).optional(),acceleratorStatus:l(n()).optional(),affinity:l(n()).optional(),closedLast:i().optional(),employeeCountRange:l(V).optional(),entityId:l(t()).optional(),entityName:l(n()).optional(),featured:i().nullish(),fundraiseActivity:zt.optional(),hasFundraising:i().nullish(),headquartersCity:l(n()).optional(),headquartersCountry:l(n()).optional(),headquartersState:l(n()).optional(),industry:l(n()).optional(),letter:n().nullish(),location:l(n()).optional(),logoOption:Ft.optional(),mainProduct:l(n()).optional(),operatingStatus:l(Vt).optional(),originCountry:l(n()).optional(),person:l(n()).optional(),portfolioHeadquartersCity:l(n()).optional(),portfolioHeadquartersCountry:l(n()).optional(),portfolioHeadquartersState:l(n()).optional(),qualityGate:Bt.optional(),rankByProminence:i().nullish(),semanticQuery:n().nullish(),slug:l(n().regex(/^[a-z0-9_-]+$/).max(255)).optional(),stage:l(n()).optional(),suppressLateStage:i().nullish(),suppressNonOperating:i().nullish(),suppressZeroTotalRaised:i().nullish(),tag:l(n()).optional(),textSearch:n().nullish(),typeCustomer:l(n()).optional(),typeModel:l(n()).optional(),typeOwnership:l(n()).optional(),typeRecord:l(x).optional(),typeRevenue:l(n()).optional(),typeTechnologyUsed:l(n()).optional(),url:n().nullish(),urlDomain:n().nullish(),urlMatchMode:Ht.nullish(),urlType:p.nullish(),yearFoundedRange:l(V).optional()}),Wt=s([`discovery`,`profile`,`peer`,`comparison`]),Gt=s([`keyword`,`semantic`]),Kt=s([`ID`,`NAME_BRAND`,`YEAR_FOUNDED`,`STATUS_OPERATING`,`UPDATED_AT`,`CREATED_AT`,`NEXT_DUE_AT`,`DATA_COMPLETION_COVERAGE`,`TOTAL_RAISED`,`AMOUNT_INVESTED`,`RECENT_INVESTMENT_AT`,`STAGE`,`MOST_RECENT_AMOUNT`,`LATEST_VALUATION`,`MOST_RECENT_DATE`,`ACCELERATOR_BRAND`,`ACCELERATOR_COHORT`,`HEADQUARTERS_COUNTRY`,`EMPLOYEE_COUNT`]),qt=Object.assign(e([Kt,n()]),{enum:Kt.enum}),Jt=r({descending:i(),field:qt,sortKey:n().nullish()}),Yt=r({order:l(Jt),relevance:Gt.nullish()}),Xt=r({confidence:A,execution:I,fallbackUsed:i(),filter:Ut,intent:Wt,interpretation:n(),sort:Yt,subjectEntityName:l(n()),unsupported:n().nullish()}),H=r({changedAt:c({offset:!0}).nullish(),dataSourceUpdatedAt:c({offset:!0}).nullish(),pendingApproval:a().nullish(),sourceId:n().nullish(),status:n().nullish()}),Zt=r({fundManagerRelationshipSource:H.nullish(),fundraiseTransaction:y,fundraiseTransactionSource:H.nullish(),investorJoinSource:H.nullish()}),Qt=r({evidence:Zt,investor:xe,semanticMatch:me.nullish()}),$t=r({entityId:t(),matchedOffering:b.nullish(),probability:o(),webUrl:l(n())}),en=r({entityId:t(),label:n(),publishedAt:c({offset:!0}).nullish(),score:o(),source:At,sourceId:n(),text:n(),url:n().nullish()}),tn=r({answer:Nt.nullish(),filing:l(Pt).nullish(),interpretation:Xt,investment:l(Qt),judgment:l($t),passage:l(en),peer:l(lt),pendingWebQuery:l(n()),personLead:i(),result:Et,searchRequestId:t().nullish(),subject:l(L)}),nn=s([`auto-match`,`needs-review`,`approved`,`rejected`]),rn=r({createdAt:c({offset:!0}),entityId:t(),href:n().nullish(),internal:i(),matchStatus:nn.nullish(),mention:n().nullish(),slug:n().regex(/^[a-z0-9_-]+$/).max(255).nullish(),typeRecord:x.nullish(),updatedAt:c({offset:!0})}),an=r({entity:l(rn),newsId:a()}),on=u({acceleratorBrand:l(n()).optional(),acceleratorCohort:l(n()).optional(),acceleratorName:l(n()).optional(),acceleratorStatus:l(n()).optional(),affinity:l(n()).optional(),closedLast:i().optional(),employeeCountRange:l(V).optional(),entityId:l(t()).optional(),entityName:l(n()).optional(),featured:i().nullish(),fundraiseActivity:zt.optional(),hasFundraising:i().nullish(),headquartersCity:l(n()).optional(),headquartersCountry:l(n()).optional(),headquartersState:l(n()).optional(),industry:l(n()).optional(),letter:n().nullish(),location:l(n()).optional(),logoOption:Ft.optional(),mainProduct:l(n()).optional(),operatingStatus:l(Vt).optional(),originCountry:l(n()).optional(),person:l(n()).optional(),portfolioHeadquartersCity:l(n()).optional(),portfolioHeadquartersCountry:l(n()).optional(),portfolioHeadquartersState:l(n()).optional(),qualityGate:Bt.optional(),rankByProminence:i().nullish(),slug:l(n().regex(/^[a-z0-9_-]+$/).max(255)).optional(),stage:l(n()).optional(),suppressLateStage:i().nullish(),suppressNonOperating:i().nullish(),suppressZeroTotalRaised:i().nullish(),tag:l(n()).optional(),textSearch:n().nullish(),typeCustomer:l(n()).optional(),typeModel:l(n()).optional(),typeOwnership:l(n()).optional(),typeRecord:l(x).optional(),typeRevenue:l(n()).optional(),typeTechnologyUsed:l(n()).optional(),url:n().nullish(),urlDomain:n().nullish(),urlMatchMode:Ht.nullish(),urlType:p.nullish(),yearFoundedRange:l(V).optional()}),sn=r({entityFilter:on.nullish(),isCurrent:i().nullish(),personTitle:l(n()).optional()}),cn=r({amountInvestedRange:l(B).nullish(),amountRaisedRange:l(B).nullish(),entityName:l(n()).nullish(),investedCompany:l(n()).nullish(),personTitle:l(n()).nullish(),round:l(n()).nullish(),totalInvestmentCount:l(V).nullish(),typeRecord:l(x).nullish()}),ln=r({additionalAssociation:sn.nullish(),arrayFilter:cn.optional(),entityFilter:on.optional(),entityId:t().nullish(),entitySlug:n().nullish(),firstName:n().nullish(),includeAddress:i().nullish(),includeUrl:i().nullish(),investorActivity:Lt.optional(),isCurrent:i().nullish(),lastName:n().nullish(),letter:n().nullish(),personId:l(t()).max(200).optional(),personName:l(n()).optional(),rankByEmployer:i().nullish(),role:n().nullish(),search:n().nullish(),semanticQuery:n().nullish(),status:n().nullish()}),un=r({descending:i(),field:s([`ID`,`FIRST_NAME`,`LAST_NAME`,`FULL_NAME`,`SLUG`,`CREATED_AT`,`UPDATED_AT`,`STATUS`,`GENDER`,`AMOUNT_INVESTED`,`TOTAL_INVESTMENTS`]),sortKey:n().nullish()}),dn=r({order:l(un),relevance:Gt.nullish()}),fn=r({confidence:A,employerSemanticQuery:n().nullish(),execution:I,fallbackUsed:i(),filter:ln,interpretation:n(),sort:dn,unsupported:n().nullish()}),pn=r({currentCompany:n().nullish(),headline:n().nullish(),id:t(),location:n().nullish(),name:n(),named:n(),organizationEvidence:s([`headline`,`profile`,`none`]).nullish(),photoUrl:n().nullish(),profileUrl:n(),slug:n().regex(/^[a-z0-9_-]+$/).max(255)}),mn=r({interpretation:fn,investment:l(Qt),personLead:i(),profile:l(pn),result:Ot,searchRequestId:t().nullish()}),hn=r({label:n(),query:n()}),gn=r({key:n(),option:l(hn),prompt:n()}),_n=r({entity:tn,entityDetail:l(v),news:Dt,newsEntityMention:l(an),person:mn,personDetail:l(_),personLead:i(),provenance:at,qualifier:gn.nullish(),section:l(s([`person`,`company`,`productService`,`investor`])).optional()}),U=30,vn=8,W=10,yn=2,bn=[`id`,`association.associationId`,`slug`,`name`,`nameBrand`,`nameFull`,`core.nameBrand`,`core.nameFull`,`core.slug`,`core.typeRecord`,`entity.core.nameBrand`,`entity.core.slug`,`title`,`sourceName`,`publishedAt`,`round`,`dateAnnounced`,`amountRaised`,`investorAttribution.amountInvested`,`stage`,`updatedAt`,`createdAt`],xn=new Set([`page`,`size`,`sort`,`cursor`,`mode`,`projection`]);function Sn(e,t,n,{transport:r=`cli`,trailer:i=[]}={}){if(typeof t==`string`)return ke(t,r,i);let a=Me(t,i);if(a!==null)return Ae(a,i,r);let o=Nn(t);if(o===null)return null;let s=e.find(({operationId:e})=>e===o.operationId),c=De(s?.detailField,o.response),l=[...c.hiddenNote,...i],u=(e,t)=>D([e.trimEnd(),...t].join(`
3
+ `),{appendNewline:!0,preservedTrailerLines:t.length>0?t.length:void 0,transport:r}),d=s?.parameters??[],f={...o,response:c.response,parameters:d,transport:r},p=Be(f.response,e,r)??He(f.response,e,r);if(p!==null)return u(p.join(`
4
+ `),i);let m=Cn(f);if(m!==null)return u(m.join(`
5
+ `),l);let h=[f.summary??n??f.operationId??`OpenAPI call succeeded`,`${f.method} ${f.endpoint}`],ee=Oe(Dn(f),117-l.length,je-Re.byteLength(`${[...h,...l].join(`
6
+ `)}\n`,`utf8`),r);return u([...h,...ee].filter(Boolean).join(`
7
+ `),l)}function Cn({response:e,...t}){if(e===void 0||!Q(e)||!(`entity`in e&&`person`in e&&`news`in e))return null;let n=_n.safeParse(e);if(!n.success)return null;let{entity:r,person:i,news:a,provenance:o}=n.data;return[...r.answer?wn(r.answer):[],...o.unavailable.map(e=>`${e} unavailable: retry this scope later`),...o.answerUnavailable?[`answer unavailable: retry this search later`]:[],...o.rejection.map(({scope:e,detail:t})=>S(`${e} rejected: ${t}`)),[`entities:`,...G(r.result,t)].join(`
8
+ `),[`people:`,...G(i.result,t)].join(`
9
+ `),[`news:`,...G(a,t)].join(`
10
+ `)]}function wn(e){let t=`relatedQuery:\n${e.relatedQuery.map(e=>` - ${S(e)}`).join(`
11
+ `)}`,n=`citations:\n${e.citation.map(({source:e,sourceId:t,entityId:n})=>S(` - ${e}:${t} entity=${n}`)).join(`
12
+ `)}`;return[`answer:\n ${Ee(e.text).replaceAll(`
13
+ `,`
14
+ `)}`,...e.relatedQuery.length===0?[]:[t],...e.citation.length===0?[]:[n]]}function Tn(e){let t=Nn(e)?.response,n=Q(t)?t.interpretation:void 0;if(!Q(n))return null;let r=I.safeParse(n.execution);if(!r.success)return null;let{modeRequested:i,modeUsed:a}=r.data,o=E(n.filter),{unsupported:s,fallbackUsed:c}=n,l=[`strategy: requested=${i} used=${a}`,...Q(o)?[`constraints:`,...Object.entries(o).flatMap(([e,t])=>t===void 0?[]:[` ${e}: ${En(t)}`])]:[],typeof s==`string`&&s.trim().length>0?`unsupported: ${s}`:``,c===!0?`fallback: semantic search over the original query`:``];return D(l.filter(Boolean).join(`
15
+ `),{appendNewline:!0})}var En=e=>$(e)?S(e):Array.isArray(e)&&e.every($)?e.map(e=>S(e)).join(`, `):JSON.stringify(e);function Dn(e){let{response:t,method:n,nextCursor:r,httpStatus:i,location:a,transport:o}=e;if(t===void 0)return a!==void 0&&i!==void 0?[`status=${i} redirect=${a}`]:i===void 0?[]:[`status=${i} no response body`];let s=i===void 0||n===`GET`?``:`status=${i}`,c=Q(t)&&!X(t)?Pn(t):null,l=c===null?void 0:Q(c.context.interpretation)?E(c.context):c.context,u=l!==void 0&&Q(l)?Object.entries(l):[],d=u.filter(e=>Array.isArray(e[1])&&e[1].length>0&&e[1].every(Q)),f=new Set(d.map(([e])=>e)),p=Object.fromEntries(u.filter(([e])=>!f.has(e)));return[s,...X(t)?G(t,e,r):c===null?In(t)?An(t,[`filter`],t.meta,o):Ln(t)?An(t,[`arrayFilterEntry`,`rangeFilterEntry`],t.filtersMeta,o):Rn(t)?jn(t,o):K(t,``):[...G(c.page,e,r),...Object.keys(p).length===0?[]:K(p,``),...d.flatMap(([e,t])=>[`${e}:`].concat(On(t,o)))]].filter(Boolean)}function G(e,t,n){let r=Mn(t),i=e.numberOfElements??e.content.length,a=Math.min(e.content.length,U),o=Math.max(1,a),s=(e.number??0)*(e.size??i),c=(e.totalElements??0)-s-i,l=e.number===void 0?``:` page=${e.number}`,u=e.size===void 0?``:` size=${e.size}`,d=e.totalElements===void 0?``:` total=${e.totalElements}`,f=e.totalPages===void 0?``:` totalPages=${e.totalPages}`,p=(e.number??0)+1,m=e.totalPages===void 0||p<e.totalPages,h=C(`page`,t.parameters);return[`rows=${i}${l}${u}${d}${f}`,a>=i?``:`page rows omitted: ${i-a} (${a}/${i} shown); ${e.content.length>a?O(t.transport,`.content`):`reread with ${C(`size`,t.parameters)} ${o} and ${h} ${Math.floor((s+a)/o)} through ${Math.floor((s+i-1)/o)} (MCP: size, page); pages start at 0`}`,r.length>0?`filters: ${r.join(` `)}`:``,n===void 0?``:`next: --cursor ${T(n)}`,c<=0||n!==void 0?``:m&&i===e.size?`more: ${c} rows not shown; use ${h} or ${C(`size`,t.parameters)} to see them`:`more: ${c} more matched but this response returns only these ${i}; narrow the query to reach them${m?` (${h} ${p} starts after this page)`:``}`,...On(e.content.slice(0,a),t.transport)].filter(Boolean)}function On(e,t){if(!e.every(Q))return q(e,``);let n=e.filter(Q);if(n.length===0)return e.length===0?[`(empty)`]:q(e,``);let r=kn(n);if(r.length===0)return q(e,``);let i=n.slice(0,U).map(e=>{let t=J(e);return r.map(e=>t[e]??``)}),a=r.map(e=>e.split(`.`).at(-1)??e),o=a.map((e,t)=>{let n=i.map(e=>e[t]??``),r=Math.max(e.length,...n.map(e=>e.length));return e===`id`||e.endsWith(`Id`)?r:Math.min(32,r)}),s=e=>e.map((e,t)=>Te(e,o[t]??12).padEnd(o[t]??12)).join(` `),c=[s(a),s(o.map(e=>`-`.repeat(e)))];return i.forEach(e=>c.push(s(e))),n.length>U&&c.push(`... ${n.length-U} more rows omitted; ${O(t)}`),c}function kn(e){let t=e.map(e=>J(e)),n=new Set(t.flatMap(e=>Object.keys(e))),r=bn.filter(e=>n.has(e)),i=new Set(r.map(Y)),a=[...n].filter(e=>{let n=t.every(t=>/^-?\d+(?:\.\d+)?$/u.test(t[e]??`0`));return!e.includes(`.`)||/id$/iu.test(e)||i.has(Y(e))?!1:(n&&i.add(Y(e)),n)}),o=[...n].filter(e=>/(?:^|\.)id$/u.test(e)).slice(0,1),s=[...new Set([...r,...o,...a])],c=[...n].filter(e=>!s.includes(e)).filter(e=>!e.toLowerCase().includes(`logo`)).slice(0,vn-s.length);return[...s,...c].slice(0,vn)}function An(e,t,n,r){let i=t.flatMap(t=>e[t].map((e,n)=>({...e,path:`.${t}[${n}].choiceOption`}))),a=n!==void 0&&Q(n)?n:{},o=[`total`,`limit`].flatMap(e=>typeof a[e]==`number`?[` ${e}=${a[e]}`]:[]).join(``),s=[`filters=${i.length}${o}`];for(let e of i){let t=e.choiceOption.length,n=e.choiceOptionTotal===null?`unknown (degraded)`:e.choiceOptionTotal??t,i=e.choiceOptionTruncated===!0?` truncated`:``;s.push(`- ${e.filterKey} (${e.label}): choices ${t}/${n}${i}`),e.choiceOption.slice(0,W).forEach(t=>{s.push(` ${C(e.filterKey)} ${T(t.value)}`)}),t>W&&s.push(` ... ${t-W} choices omitted for ${e.filterKey}; ${O(r,e.path)}`)}return s}function jn(e,t){let n=C(e.filterKey);return[`${e.filterKey}: ${e.result.length} matches`,...e.result.slice(0,W).map(e=>`${n} ${T(e)}`),e.result.length>W?`... ${e.result.length-W} matches omitted; ${O(t,`.result`)}`:``].filter(Boolean)}function Mn({endpoint:e,parameters:t}){let n=e.indexOf(`?`);return n<0?[]:[...new URLSearchParams(e.slice(n+1)).entries()].filter(([e,t])=>!xn.has(e)&&t.length>0).map(([e,n])=>`${C(e,t)} ${T(n)}`)}function Nn(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=t=>{let n=Reflect.get(e,t);return typeof n==`string`?n:void 0},[n,r,i]=[t(`method`),t(`endpoint`),t(`nextCursor`)];if(n===void 0||r===void 0)return null;let a=Reflect.get(e,`httpStatus`),o=Reflect.get(e,`response`),s=o===void 0?void 0:Se.safeParse(o);return s!==void 0&&!s.success?null:{method:n,endpoint:r,httpStatus:typeof a==`number`?a:void 0,location:t(`location`),operationId:t(`operationId`),summary:t(`summary`),nextCursor:i===``?void 0:i,response:s?.data}}function K(e,t,n){if(e===void 0)return[];if($(e))return[`${t}${w(e,n)}`];if(Array.isArray(e))return q(e,t,n);let r=[];for(let[n,i]of Object.entries(e))if(i!==void 0){if($(i))r.push(`${t}${n}: ${w(i,n)}`);else{r.push(`${t}${n}:`);for(let e of K(i,`${t} `,n))r.push(e)}}return r.length===0?[`${t}(empty)`]:r}function q(e,t,n){if(e.length===0)return[`${t}(empty)`];let r=[];for(let i of e)if($(i))r.push(`${t}- ${w(i,n)}`);else{r.push(`${t}-`);for(let e of K(i,`${t} `))r.push(e)}return r}function J(e,t=``,n=0){return $(e)?t.length===0?{}:{[t]:S(e,t)}:n>yn?{}:Array.isArray(e)?e[0]===void 0?{}:J(e[0],t,n+1):Object.fromEntries(Object.entries(e).flatMap(([e,r])=>{if(r===void 0)return[];let i=t.length===0?e:`${t}.${e}`;return $(r)?[[i,S(r,i)]]:Object.entries(J(r,i,n+1))}))}var Y=e=>e.split(`.`,1)[0],X=e=>Q(e)&&Array.isArray(e.content);function Pn(e){let[t,...n]=Object.entries(e).filter(e=>X(e[1])&&typeof e[1].totalElements==`number`);if(t===void 0||n.length>0)return null;let[r,i]=t;return{page:i,context:Object.fromEntries(Object.entries(e).filter(([e])=>e!==r))}}function Fn(e){return Q(e)&&typeof e.label==`string`&&typeof e.filterKey==`string`&&Array.isArray(e.choiceOption)}var In=e=>Q(e)&&Z(e.filter),Ln=e=>Q(e)&&Z(e.arrayFilterEntry)&&Z(e.rangeFilterEntry),Z=e=>Array.isArray(e)&&e.every(Fn),Rn=e=>Q(e)&&typeof e.filterKey==`string`&&Array.isArray(e.result)&&e.result.every(e=>typeof e==`string`),Q=e=>typeof e==`object`&&!!e&&!Array.isArray(e),$=e=>typeof e!=`object`||!e;export{qe as i,Tn as n,Ye as r,Sn as t};
@@ -0,0 +1 @@
1
+ import{n as e}from"./commander-DEj7N1b9.js";import{a as t}from"./package-CZBWjlYb.js";import{C as n,S as r,_ as i,b as a,c as o,g as s,i as c,m as l,p as u,s as d,x as f}from"./iso-l1vOidnb.js";import{c as p,f as m,r as h}from"./result-envelope-DXFbrrkt.js";import{A as ee,O as te,S as ne,_ as re,b as ie,d as g,h as ae,i as _,l as v,n as y,p as b,w as x,x as oe}from"./esm-lPyPa01D.js";import{C as S,G as se,K as ce,L as le,M as ue,N as de,O as fe,Q as C,R as pe,T as me,U as he,V as w,W as ge,X as _e,Y as T,_ as ve,at as ye,d as be,f as xe,g as Se,h as Ce,it as we,j as Te,k as Ee,m as De,nt as E,ot as Oe,q as ke,s as Ae,tt as je,v as Me,x as Ne,y as Pe,z as D}from"./logging-BHp-5JwI.js";import{basename as Fe,extname as Ie}from"node:path";import{readFile as Le}from"node:fs/promises";import{AsyncLocalStorage as Re}from"node:async_hooks";i({bodyPath:r(),valueField:d(i({path:d(r().nullable()).readonly(),type:c([`object`,`array`,`string`,`number`,`integer`,`boolean`]),nullable:o()})).readonly()});var O=n([l(``),r().regex(/^(?:\/(?:[^~/]|~[01])*)+$/)]),ze=f({readOperationId:r().min(1),writePointer:O,readPointer:O,readParameter:r().min(1).optional(),submittedMap:d(f({bodyPointer:O,readPointer:O,identityPointer:O})).min(1).optional()});function Be(e){return new URL(e,`https://placeholder.invalid`).pathname}function Ve(e,t){let n=e.split(`/`).filter(Boolean),r=t.split(`/`).filter(Boolean);return n.length!==r.length||r.some(Ue)?!1:n.every((e,t)=>He(e)||e===r[t])}function He(e){let t=e.slice(1,-1);return e.startsWith(`{`)&&e.endsWith(`}`)&&t.length>0&&!t.includes(`/`)&&!t.includes(`{`)&&!t.includes(`}`)}function Ue(e){if(He(e))return!0;let t=e.toLowerCase(),n=e.slice(3,-3);return t.startsWith(`%7b`)&&t.endsWith(`%7d`)&&n.length>0&&!n.includes(`/`)&&!n.includes(`%`)&&!n.includes(`{`)&&!n.includes(`}`)}var k=[`get`,`post`,`put`,`patch`,`delete`],We={get:`GET`,post:`POST`,put:`PUT`,patch:`PATCH`,delete:`DELETE`},Ge=e=>We[e];function Ke(e){let t=e.toLowerCase(),n=k.find(e=>e===t);if(n===void 0)throw Error(`Unsupported OpenAPI method: ${e}`);return n}var qe=[`oauth`,`start`,`poll`,`acknowledge`,`revoke`],Je=f({name:r().regex(/^[A-Z][A-Z0-9_]*$/u)}),A=n([l(`private`),i({scope:r().optional(),value:r().optional()})]),j=u(()=>i({$ref:r().optional(),description:r().optional(),type:n([r(),d(r())]).optional(),format:r().optional(),default:m.optional(),enum:d(m).optional(),"x-extensible-enum":d(m).optional(),"x-aventure-parsed-enum":o().optional(),readOnly:o().optional(),items:j.optional(),minItems:s().int().nonnegative().optional(),maxItems:s().int().nonnegative().optional(),properties:a(r(),j).optional(),required:d(r()).optional(),oneOf:d(j).optional(),anyOf:d(j).optional(),allOf:d(j).optional(),propertyNames:j.optional(),additionalProperties:n([j,o()]).optional(),"x-aventure-visibility":A.optional(),"x-aventure-cli-conflicts":d(d(r().min(1)).min(2)).min(1).optional(),"x-aventure-env":Je.optional(),"x-aventure-detail":l(!0).optional(),"x-aventure-operation-only":d(r().min(1)).min(1).optional()})),Ye=i({in:r(),name:r(),required:o().optional(),description:r().optional(),schema:j.optional(),"x-aventure-visibility":A.optional(),"x-aventure-legacy-name":f({name:r().trim().min(1)}).optional()}).superRefine((e,t)=>{let n=e[`x-aventure-legacy-name`]?.name;n!==void 0&&(e.in!==`path`&&t.addIssue({code:`custom`,path:[`x-aventure-legacy-name`],message:`x-aventure-legacy-name is valid only for path parameters`}),n===e.name&&t.addIssue({code:`custom`,path:[`x-aventure-legacy-name`,`name`],message:`Legacy path parameter name must differ from its canonical name`}))}),Xe=a(r(),i({schema:j.optional()})),Ze=i({description:r().optional(),content:Xe.optional(),"x-aventure-standard-response":o().optional()}),Qe=i({description:r().optional(),required:o().optional(),content:Xe.optional()}),$e=f({auth:c([`none`,`read`]).optional(),mutates:o().optional()}).optional(),et=r().trim().regex(/^[a-z0-9]+(?:-[a-z0-9]+)* [a-z0-9]+(?:-[a-z0-9]+)*$/u),tt=r().regex(/^[a-z][A-Za-z0-9]*$/u),nt=r().regex(/^--(?:no-)?[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u),rt=f({command:et,role:c(qe),summary:r().trim().min(1).optional(),description:r().trim().min(1).optional(),bodyOption:d(tt).min(1).optional(),localOption:d(f({optionKey:tt,flag:nt,description:r().trim().min(1)})).min(1).optional()}).superRefine((t,n)=>{let r=[t.bodyOption??[],(t.localOption??[]).map(e=>e.optionKey),(t.localOption??[]).map(e=>e.flag)].some(e=>new Set(e).size!==e.length),i=(t.localOption??[]).some(t=>new e(t.flag).attributeName()!==t.optionKey);(r||i)&&n.addIssue({code:`custom`,message:`Composite CLI options must be unique and match their local flags`})}).optional(),it=i({operationId:r(),summary:r().optional(),description:r().optional(),tags:d(r()).optional(),deprecated:o().optional(),hidden:o().optional(),security:d(a(r(),d(r()))).optional(),parameters:d(Ye).optional(),requestBody:Qe.optional(),responses:a(r(),Ze),"x-aventure-visibility":A.optional(),"x-aventure-tool":$e,"x-aventure-mutation-readback":ze.optional(),"x-aventure-cli-composite":rt}).superRefine((e,t)=>{let n=e.parameters??[];for(let[e,r]of n.entries()){let i=r[`x-aventure-legacy-name`]?.name;r.in===`path`&&i!==void 0&&n.some((t,n)=>n!==e&&t.in===`path`&&(t.name===i||t[`x-aventure-legacy-name`]?.name===i))&&t.addIssue({code:`custom`,path:[`parameters`,e,`x-aventure-legacy-name`,`name`],message:`Legacy path parameter name '${i}' collides with another declared path parameter`})}}),at=i(Object.fromEntries(k.map(e=>[e,it.optional()]))),ot=i({$ref:r().optional(),description:r().optional(),type:n([r(),d(r())]).optional(),format:r().optional(),default:m.optional(),enum:d(m).optional(),"x-extensible-enum":d(m).optional(),"x-aventure-parsed-enum":o().optional(),readOnly:o().optional(),items:j.optional(),minItems:s().int().nonnegative().optional(),maxItems:s().int().nonnegative().optional(),oneOf:d(j).optional(),anyOf:d(j).optional(),allOf:d(j).optional(),propertyNames:j.optional(),additionalProperties:n([j,o()]).optional(),properties:a(r(),j).optional(),required:d(r()).optional(),"x-aventure-visibility":A.optional(),"x-aventure-cli-conflicts":d(d(r().min(1)).min(2)).min(1).optional(),"x-aventure-env":Je.optional(),"x-aventure-detail":l(!0).optional(),"x-aventure-noun":f({one:r().trim().min(1),other:r().trim().min(1)}).optional()});i({info:i({description:r().optional()}).optional(),tags:d(i({name:r(),description:r().optional(),"x-aventure-cli":f({section:c([`researchData`,`account`,`administration`,`cli`])}).optional()})).optional(),paths:a(r(),at),webhooks:a(r(),i({post:i({description:r(),requestBody:Qe})})).optional(),components:i({schemas:a(r(),ot)})}).superRefine((e,t)=>{for(let[n,r]of Object.entries(e.paths))for(let i of k){let a=r[i]?.[`x-aventure-mutation-readback`];a!==void 0&&ct(e.paths,a.readOperationId)===null&&t.addIssue({code:`custom`,path:[`paths`,n,i,`x-aventure-mutation-readback`,`readOperationId`],message:`mutation readback names '${a.readOperationId}', which no operation in this document emits`})}});var st=new Set([`page`,`size`,`sort`]);function M(e){return e?.$ref?.startsWith(`#/components/schemas/`)===!0?e.$ref.slice(21):void 0}function ct(e,t){for(let[n,r]of Object.entries(e))for(let e of k){let i=r[e];if(i?.operationId===t)return{method:e,template:n,operation:i}}return null}function lt(e,t,n){let r=Be(n),i=e[r]?.[t];if(i)return{method:t,template:r,operation:i};for(let[n,i]of Object.entries(e)){let e=i[t];if(e&&Ve(n,r))return{method:t,template:n,operation:e}}return null}function ut(e,t,n=e){return e.replace(/\{([^}]+)}/g,(...e)=>{let r=e[1],i=t[r];if(i==null)throw Error(`Missing path parameter '${r}' for ${n}`);return encodeURIComponent(String(i))})}function dt(e,t,n){let r=t;for(let i of e.parameters??[]){let e=i[`x-aventure-legacy-name`]?.name;if(i.in!==`path`||e===void 0)continue;let a=t[e];if(Object.hasOwn(t,e)&&a!==void 0){if(Object.hasOwn(t,i.name))throw Error(`Path parameters '${i.name}' and legacy alias '${e}' were both supplied for ${n}`);r===t&&(r={...t}),r[i.name]=a,delete r[e]}}return r}function ft(e,t){let n={};for(let r of e.parameters??[]){if(r.in!==`query`||st.has(r.name))continue;let e=t?.[r.name]??pt(r.schema?.default);e!==void 0&&(n[r.name]=e)}return Object.keys(n).length===0?void 0:n}function pt(e){if(typeof e==`string`||typeof e==`number`||typeof e==`boolean`||Array.isArray(e)&&e.every(e=>typeof e==`string`||typeof e==`number`||typeof e==`boolean`))return e}var mt={name:`span`,countItems:e=>e.length},ht=256,gt=512;function _t(e,t){let n=e&255|ht;return t&&(n|=gt),n}function vt(e,t){let n=e.spanContext(),r=e.status,i=e.parentSpanContext?.spanId?t.encodeSpanContext(e.parentSpanContext?.spanId):void 0;return{traceId:t.encodeSpanContext(n.traceId),spanId:t.encodeSpanContext(n.spanId),parentSpanId:i,traceState:n.traceState?.serialize(),name:e.name,kind:e.kind==null?0:e.kind+1,startTimeUnixNano:t.encodeHrTime(e.startTime),endTimeUnixNano:t.encodeHrTime(e.endTime),attributes:ve(e.attributes,t),droppedAttributesCount:e.droppedAttributesCount,events:e.events.map(e=>bt(e,t)),droppedEventsCount:e.droppedEventsCount,status:{code:r.code,message:r.message},links:e.links.map(e=>yt(e,t)),droppedLinksCount:e.droppedLinksCount,flags:_t(n.traceFlags,e.parentSpanContext?.isRemote)}}function yt(e,t){return{attributes:e.attributes?ve(e.attributes,t):[],spanId:t.encodeSpanContext(e.context.spanId),traceId:t.encodeSpanContext(e.context.traceId),traceState:e.context.traceState?.serialize(),droppedAttributesCount:e.droppedAttributesCount||0,flags:_t(e.context.traceFlags,e.context.isRemote)}}function bt(e,t){return{attributes:e.attributes?ve(e.attributes,t):[],name:e.name,timeUnixNano:t.encodeHrTime(e.time),droppedAttributesCount:e.droppedAttributesCount||0}}function xt(e,t){return{resourceSpans:Ct(e,t)}}function St(e){let t=new Map;for(let n of e){let e=t.get(n.resource);e||(e=new Map,t.set(n.resource,e));let r=`${n.instrumentationScope.name}@${n.instrumentationScope.version||``}:${n.instrumentationScope.schemaUrl||``}`,i=e.get(r);i||(i=[],e.set(r,i)),i.push(n)}return t}function Ct(e,t){let n=St(e),r=[],i=n.entries(),a=i.next();for(;!a.done;){let[e,n]=a.value,o=[],s=n.values(),c=s.next();for(;!c.done;){let e=c.value;if(e.length>0){let n=e.map(e=>vt(e,t));o.push({scope:Ce(e[0].instrumentationScope,t),spans:n,schemaUrl:e[0].instrumentationScope.schemaUrl})}c=s.next()}let l=Se(e,t),u={resource:l,scopeSpans:o,schemaUrl:l.schemaUrl};r.push(u),a=i.next()}return r}y();var wt={serializeRequest:e=>{let t=xt(e,De);return new TextEncoder().encode(JSON.stringify(t))},deserializeResponse:e=>{if(e.length===0)return{};let t=new TextDecoder;try{return JSON.parse(t.decode(e))}catch(e){return v.warn(`Failed to parse trace export response: ${e.message}. Returning empty response`),{}}}},Tt=`otlp_http_span_exporter`,Et=class extends Oe{constructor(e={}){super(xe(be(e,`TRACES`,`v1/traces`,{"Content-Type":`application/json`}),wt,Tt,mt,e.selfObsMeterProvider))}};he(),S(),Me();var Dt=`exception`,N=Symbol.for(`nodejs.util.inspect.custom`);function Ot(e){let t={};for(let[n,r]of e.getRawAttributes())typeof r?.then!=`function`&&r!=null&&(t[n]??=r);return t}function P(e,t,n,r,i){if(typeof n==`number`&&n<0){let t=`[${e}]`;return r?.stylize?r.stylize(t,`special`):t}return typeof i!=`function`||!r?t:`${e} ${i(t,{...r,depth:r.depth==null?r.depth:r.depth-1})}`}y();var kt=class{_spanContext;kind;parentSpanContext;attributes={};links=[];events=[];startTime;resource;instrumentationScope;_droppedAttributesCount=0;_droppedEventsCount=0;_droppedLinksCount=0;_attributesCount=0;name;status={code:b.UNSET};endTime=[0,0];_ended=!1;_duration=[-1,-1];_spanProcessor;_spanLimits;_attributeValueLengthLimit;_recordEndMetrics;_performanceStartTime;_performanceOffset;_startTimeProvided;constructor(e){let t=Date.now();if(this._spanContext=e.spanContext,this._performanceStartTime=w.now(),this._performanceOffset=t-(this._performanceStartTime+w.timeOrigin),this._startTimeProvided=e.startTime!=null,this._spanLimits=e.spanLimits,this._attributeValueLengthLimit=this._spanLimits.attributeValueLengthLimit??0,this._spanProcessor=e.spanProcessor,this.name=e.name,this.parentSpanContext=e.parentSpanContext,this.kind=e.kind,e.links)for(let t of e.links)this.addLink(t);this.startTime=this._getTime(e.startTime??t),this.resource=e.resource,this.instrumentationScope=e.scope,this._recordEndMetrics=e.recordEndMetrics,e.attributes!=null&&this.setAttributes(e.attributes),this._spanProcessor.onStart(this,e.context)}spanContext(){return this._spanContext}setAttribute(e,t){if(t==null||this._isSpanEnded())return this;if(e.length===0)return v.warn(`Invalid attribute key: ${e}`),this;if(!je(t))return v.warn(`Invalid attribute value set for key: ${e}`),this;let{attributeCountLimit:n}=this._spanLimits,r=!Object.prototype.hasOwnProperty.call(this.attributes,e);return n!==void 0&&this._attributesCount>=n&&r?(this._droppedAttributesCount++,this):(this.attributes[e]=this._truncateToSize(t),r&&this._attributesCount++,this)}setAttributes(e){for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&this.setAttribute(t,e[t]);return this}addEvent(e,t,n){if(this._isSpanEnded())return this;let{eventCountLimit:r}=this._spanLimits;if(r===0)return v.warn(`No events allowed.`),this._droppedEventsCount++,this;r!==void 0&&this.events.length>=r&&(this._droppedEventsCount===0&&v.debug(`Dropping extra events.`),this.events.shift(),this._droppedEventsCount++),le(t)&&(le(n)||(n=t),t=void 0);let i=E(t),{attributePerEventCountLimit:a}=this._spanLimits,o={},s=0,c=0;for(let e in i){if(!Object.prototype.hasOwnProperty.call(i,e))continue;let t=i[e];a!==void 0&&c>=a?s++:(o[e]=this._truncateToSize(t),c++)}return this.events.push({name:e,attributes:o,time:this._getTime(n),droppedAttributesCount:s}),this}addLink(e){if(this._isSpanEnded())return this;let{linkCountLimit:t}=this._spanLimits;if(t===0)return this._droppedLinksCount++,this;t!==void 0&&this.links.length>=t&&(this._droppedLinksCount===0&&v.debug(`Dropping extra links.`),this.links.shift(),this._droppedLinksCount++);let{attributePerLinkCountLimit:n}=this._spanLimits,r=E(e.attributes),i={},a=0,o=0;for(let e in r){if(!Object.prototype.hasOwnProperty.call(r,e))continue;let t=r[e];n!==void 0&&o>=n?a++:(i[e]=this._truncateToSize(t),o++)}let s={context:e.context};return o>0&&(s.attributes=i),a>0&&(s.droppedAttributesCount=a),this.links.push(s),this}addLinks(e){for(let t of e)this.addLink(t);return this}setStatus(e){if(this._isSpanEnded()||e.code===b.UNSET||this.status.code===b.OK)return this;let t={code:e.code};return e.code===b.ERROR&&(typeof e.message==`string`?t.message=e.message:e.message!=null&&v.warn(`Dropping invalid status.message of type '${typeof e.message}', expected 'string'`)),this.status=t,this}updateName(e){return this._isSpanEnded()||(this.name=e),this}end(e){this._isSpanEnded()?v.error(`${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`):(this.endTime=this._getTime(e),this._duration=de(this.startTime,this.endTime),this._duration[0]<0&&(v.warn(`Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.`,this.startTime,this.endTime),this.endTime=this.startTime.slice(),this._duration=[0,0]),this._droppedEventsCount>0&&v.warn(`Dropped ${this._droppedEventsCount} events because eventCountLimit reached`),this._droppedLinksCount>0&&v.warn(`Dropped ${this._droppedLinksCount} links because linkCountLimit reached`),this._spanProcessor.onEnding&&this._spanProcessor.onEnding(this),this._recordEndMetrics?.(),this._ended=!0,this._spanProcessor.onEnd(this))}_getTime(e){if(typeof e==`number`&&e<=w.now())return ue(e+this._performanceOffset);if(typeof e==`number`)return D(e);if(e instanceof Date)return D(e.getTime());if(pe(e))return e;if(this._startTimeProvided)return D(Date.now());let t=w.now()-this._performanceStartTime;return Te(this.startTime,D(t))}isRecording(){return this._ended===!1}recordException(e,t){let n={};typeof e==`string`?n[se]=e:e&&(e.code?n[ke]=e.code.toString():e.name&&(n[ke]=e.name),e.message&&(n[se]=e.message),e.stack&&(n[ce]=e.stack)),n[`exception.type`]||n[`exception.message`]?this.addEvent(Dt,n,t):v.warn(`Failed to record an exception ${e}`)}get duration(){return this._duration}get ended(){return this._ended}get droppedAttributesCount(){return this._droppedAttributesCount}get droppedEventsCount(){return this._droppedEventsCount}get droppedLinksCount(){return this._droppedLinksCount}_isSpanEnded(){if(this._ended){let e=Error(`Operation attempted on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`);v.warn(`Cannot execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`,e)}return this._ended}_truncateToLimitUtil(e,t){return e.length<=t?e:e.substring(0,t)}_truncateToSize(e){let t=this._attributeValueLengthLimit;return t<=0?(v.warn(`Attribute value limit must be positive, got ${t}`),e):typeof e==`string`?this._truncateToLimitUtil(e,t):Array.isArray(e)?e.map(e=>typeof e==`string`?this._truncateToLimitUtil(e,t):e):e}[N](e,t,n){return P(`SpanImpl`,{name:this.name,kind:this.kind,spanContext:this._spanContext,parentSpanContext:this.parentSpanContext,status:this.status,startTime:this.startTime,endTime:this.endTime,duration:this._duration,ended:this._ended,attributes:this.attributes,events:this.events,links:this.links,droppedAttributesCount:this._droppedAttributesCount,droppedEventsCount:this._droppedEventsCount,droppedLinksCount:this._droppedLinksCount,instrumentationScope:this.instrumentationScope,resource:{attributes:Ot(this.resource)}},e,t,n)}},F;(function(e){e[e.NOT_RECORD=0]=`NOT_RECORD`,e[e.RECORD=1]=`RECORD`,e[e.RECORD_AND_SAMPLED=2]=`RECORD_AND_SAMPLED`})(F||={});var At=`otel.component.name`,jt=`otel.component.type`,Mt=`otel.span.parent.origin`,Nt=`otel.span.sampling_result`,Pt=`otel.sdk.processor.span.processed`,Ft=`otel.sdk.processor.span.queue.capacity`,It=`otel.sdk.processor.span.queue.size`,Lt=`otel.sdk.span.live`,Rt=`otel.sdk.span.started`,zt=`batching_span_processor`,Bt=class{startedSpans;liveSpans;constructor(e){this.startedSpans=e.createCounter(Rt,{unit:`{span}`,description:`The number of created spans.`}),this.liveSpans=e.createUpDownCounter(Lt,{unit:`{span}`,description:`The number of currently live spans.`})}startSpan(e,t){let n=Ht(t);if(this.startedSpans.add(1,{[Mt]:Vt(e),[Nt]:n}),t===F.NOT_RECORD)return()=>{};let r={[Nt]:n};return this.liveSpans.add(1,r),()=>{this.liveSpans.add(-1,r)}}};function Vt(e){return e?e.isRemote?`remote`:`local`:`none`}function Ht(e){switch(e){case F.RECORD_AND_SAMPLED:return`RECORD_AND_SAMPLE`;case F.RECORD:return`RECORD_ONLY`;case F.NOT_RECORD:return`DROP`}}var Ut=`2.11.0`;y(),S();var Wt=class{_sampler;_spanLimits;_idGenerator;instrumentationScope;_resource;_spanProcessor;_tracerMetrics;constructor(e,t){this.instrumentationScope=e,this._sampler=t.sampler,this._spanLimits=t.spanLimits,this._resource=t.resource,this._idGenerator=t.idGenerator,this._spanProcessor=t.spanProcessor;let n=t.meterProvider.getMeter(`@opentelemetry/sdk-trace`,Ut);this._tracerMetrics=new Bt(n)}startSpan(e,t={},n=g.active()){t.root&&(n=_.deleteSpan(n));let r=_.getSpan(n);if(we(n))return v.debug(`Instrumentation suppressed, returning Noop Span`),_.wrapSpanContext(ne);let i=r?.spanContext(),a=this._idGenerator.generateSpanId(),o,s,c;!i||!_.isSpanContextValid(i)?s=this._idGenerator.generateTraceId():(s=i.traceId,c=i.traceState,o=i);let l=t.kind??ae.INTERNAL,u=(t.links??[]).map(e=>({context:e.context,attributes:E(e.attributes)})),d=E(t.attributes),f=this._sampler.shouldSample(n,s,e,l,d,u),p=this._tracerMetrics.startSpan(i,f.decision);c=f.traceState??c;let m=f.decision===re.RECORD_AND_SAMPLED?x.SAMPLED:x.NONE,h={traceId:s,spanId:a,traceFlags:m,traceState:c};if(f.decision===re.NOT_RECORD)return v.debug(`Recording is off, propagating context in a non-recording span`),_.wrapSpanContext(h);let ee=E(Object.assign(d,f.attributes));return new kt({resource:this._resource,scope:this.instrumentationScope,context:n,spanContext:h,name:e,kind:l,links:u,parentSpanContext:o,attributes:ee,startTime:t.startTime,spanProcessor:this._spanProcessor,spanLimits:this._spanLimits,recordEndMetrics:p})}startActiveSpan(e,t,n,r){let i,a,o;if(arguments.length<2)return;arguments.length===2?o=t:arguments.length===3?(i=t,o=n):(i=t,a=n,o=r);let s=a??g.active(),c=this.startSpan(e,i,s),l=_.setSpan(s,c);return g.with(l,o,void 0,c)}[N](e,t,n){return P(`Tracer`,{instrumentationScope:this.instrumentationScope,resource:{attributes:Ot(this._resource)},spanLimits:this._spanLimits},e,t,n)}};S();var Gt=class{_spanProcessors;constructor(e){this._spanProcessors=e}forceFlush(){let e=[];for(let t of this._spanProcessors)e.push(t.forceFlush());return new Promise(t=>{Promise.all(e).then(()=>{t()}).catch(e=>{C(e||Error(`MultiSpanProcessor: forceFlush failed`)),t()})})}onStart(e,t){for(let n of this._spanProcessors)n.onStart(e,t)}onEnding(e){for(let t of this._spanProcessors)t.onEnding&&t.onEnding(e)}onEnd(e){for(let t of this._spanProcessors)t.onEnd(e)}shutdown(){let e=[];for(let t of this._spanProcessors)e.push(t.shutdown());return new Promise((t,n)=>{Promise.all(e).then(()=>{t()},n)})}},I=class{shouldSample(){return{decision:F.NOT_RECORD}}toString(){return`AlwaysOffSampler`}},L=class{shouldSample(){return{decision:F.RECORD_AND_SAMPLED}}toString(){return`AlwaysOnSampler`}};y(),S();var R=class{_root;_remoteParentSampled;_remoteParentNotSampled;_localParentSampled;_localParentNotSampled;constructor(e){this._root=e.root,this._root||=(C(Error(`ParentBasedSampler must have a root sampler configured`)),new L),this._remoteParentSampled=e.remoteParentSampled??new L,this._remoteParentNotSampled=e.remoteParentNotSampled??new I,this._localParentSampled=e.localParentSampled??new L,this._localParentNotSampled=e.localParentNotSampled??new I}shouldSample(e,t,n,r,i,a){let o=_.getSpanContext(e);return!o||!ie(o)?this._root.shouldSample(e,t,n,r,i,a):o.isRemote?o.traceFlags&x.SAMPLED?this._remoteParentSampled.shouldSample(e,t,n,r,i,a):this._remoteParentNotSampled.shouldSample(e,t,n,r,i,a):o.traceFlags&x.SAMPLED?this._localParentSampled.shouldSample(e,t,n,r,i,a):this._localParentNotSampled.shouldSample(e,t,n,r,i,a)}toString(){return`ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`}};he();var Kt=new Map,qt=class{processedSpans;queueSize;queueSizeCallback;standardAttrs;droppedAttrs;constructor(e,t,n){let r=Kt.get(e)??0;if(Kt.set(e,r+1),this.standardAttrs={[jt]:e,[At]:`${e}/${r}`},this.droppedAttrs={...this.standardAttrs,[ge]:`queue_full`},this.processedSpans=t.createCounter(Pt,{unit:`{span}`,description:`The number of spans for which the processing has finished, either successful or failed.`}),n){let{capacity:e,getQueueSize:r}=n;t.createUpDownCounter(Ft,{unit:`{span}`,description:`The maximum number of spans the queue of a given instance of an SDK span processor can hold.`}).add(e,this.standardAttrs),this.queueSize=t.createObservableUpDownCounter(It,{unit:`{span}`,description:`The number of spans in the queue of a given instance of an SDK span processor.`}),this.queueSizeCallback=e=>e.observe(r(),this.standardAttrs),this.queueSize.addCallback(this.queueSizeCallback)}}dropSpans(e){this.processedSpans.add(e,this.droppedAttrs)}finishSpans(e,t){if(!t){this.processedSpans.add(e,this.standardAttrs);return}let n={...this.standardAttrs,[ge]:t.name};this.processedSpans.add(e,n)}shutdown(){this.queueSize&&this.queueSizeCallback&&this.queueSize.removeCallback(this.queueSizeCallback)}};y(),S();var Jt=class{_maxExportBatchSize;_maxQueueSize;_scheduledDelayMillis;_exportTimeoutMillis;_exporter;_metrics;_isExporting=!1;_finishedSpans=[];_timer;_shutdownOnce;_droppedSpansCount=0;constructor(e){this._exporter=e.exporter,this._maxExportBatchSize=e.maxExportBatchSize??512,this._maxQueueSize=e.maxQueueSize??2048,this._scheduledDelayMillis=e.scheduledDelayMillis??5e3,this._exportTimeoutMillis=e.exportTimeoutMillis??3e4,this._shutdownOnce=new me(this._shutdown,this),this._maxExportBatchSize>this._maxQueueSize&&(v.warn(`BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize`),this._maxExportBatchSize=this._maxQueueSize);let t=e.selfObsMeterProvider?e.selfObsMeterProvider.getMeter(`@opentelemetry/sdk-trace`):te();this._metrics=new qt(zt,t,{capacity:this._maxQueueSize,getQueueSize:()=>this._finishedSpans.length})}forceFlush(){return this._shutdownOnce.isCalled?this._shutdownOnce.promise:this._flushAll()}onStart(e,t){}onEnd(e){this._shutdownOnce.isCalled||(e.spanContext().traceFlags&x.SAMPLED)!==0&&this._addToBuffer(e)}shutdown(){return this._shutdownOnce.call()}_shutdown(){return Promise.resolve().then(()=>this.onShutdown()).then(()=>this._flushAll()).then(()=>(this._metrics.shutdown(),this._exporter.shutdown()))}_addToBuffer(e){this._finishedSpans.length>=this._maxQueueSize?(this._droppedSpansCount===0&&v.debug(`maxQueueSize reached, dropping spans`),this._droppedSpansCount++,this._metrics.dropSpans(1)):(this._droppedSpansCount>0&&(v.warn(`Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`),this._droppedSpansCount=0),this._finishedSpans.push(e),this._maybeStartTimer())}_flushAll(){return new Promise((e,t)=>{let n=[],r=Math.ceil(this._finishedSpans.length/this._maxExportBatchSize);for(let e=0,t=r;e<t;e++)n.push(this._flushOneBatch());Promise.all(n).then(()=>{e()}).catch(t)})}_flushOneBatch(){return this._clearTimer(),this._finishedSpans.length===0?Promise.resolve():new Promise((e,t)=>{let n=setTimeout(()=>{t(Error(`Timeout`))},this._exportTimeoutMillis);g.with(ye(g.active()),()=>{let r;this._finishedSpans.length<=this._maxExportBatchSize?(r=this._finishedSpans,this._finishedSpans=[]):r=this._finishedSpans.splice(0,this._maxExportBatchSize);let i=()=>this._exporter.export(r,i=>{clearTimeout(n),this._metrics.finishSpans(r.length,i.error),i.code===Ee.SUCCESS?e():t(i.error??Error(`BatchSpanProcessor: span export failed`))}),a=null;for(let e=0,t=r.length;e<t;e++){let t=r[e];t.resource.asyncAttributesPending&&t.resource.waitForAsyncAttributes&&(a??=[],a.push(t.resource.waitForAsyncAttributes()))}a===null?i():Promise.all(a).then(i,e=>{C(e),t(e)})})})}_maybeStartTimer(){if(this._isExporting)return;let e=()=>{this._isExporting=!0,this._flushOneBatch().finally(()=>{this._isExporting=!1,this._finishedSpans.length>0&&(this._clearTimer(),this._maybeStartTimer())}).catch(e=>{this._isExporting=!1,C(e)})};if(this._finishedSpans.length>=this._maxExportBatchSize)return e();this._timer===void 0&&(this._timer=setTimeout(()=>e(),this._scheduledDelayMillis),typeof this._timer!=`number`&&this._timer.unref())}_clearTimer(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)}},Yt=class extends Jt{onShutdown(){}},Xt=8,Zt=16,Qt=class{generateTraceId=$t(Zt);generateSpanId=$t(Xt)},z=Buffer.allocUnsafe(Zt);function $t(e){return function(){for(let t=0;t<e/4;t++)z.writeUInt32BE(Math.random()*2**32>>>0,t*4);for(let t=0;t<e&&!(z[t]>0);t++)t===e-1&&(z[e-1]=1);return z.toString(`hex`,0,e)}}y();var B;(function(e){e[e.resolved=0]=`resolved`,e[e.timeout=1]=`timeout`,e[e.error=2]=`error`,e[e.unresolved=3]=`unresolved`})(B||={});var en=class{_resource;_activeSpanProcessor;_forceFlushTimeoutMillis;_tracerOptions;_tracers=new Map;constructor(e={}){this._forceFlushTimeoutMillis=e.forceFlushTimeoutMillis??3e4,this._resource=e.resource??Pe();let t=e.spanProcessors??[];this._activeSpanProcessor=new Gt(t),this._tracerOptions={resource:this._resource,sampler:e.sampler??new R({root:new L}),spanLimits:{attributeCountLimit:e.spanLimits?.attributeCountLimit??128,attributeValueLengthLimit:e.spanLimits?.attributeValueLengthLimit??1/0,eventCountLimit:e.spanLimits?.eventCountLimit??128,linkCountLimit:e.spanLimits?.linkCountLimit??128,attributePerEventCountLimit:e.spanLimits?.attributePerEventCountLimit??128,attributePerLinkCountLimit:e.spanLimits?.attributePerLinkCountLimit??128},idGenerator:e.idGenerator||new Qt,spanProcessor:this._activeSpanProcessor,meterProvider:e.meterProvider??{getMeter(){return te()}}}}getTracer(e,t,n){let r=`${e}@${t||``}:${n?.schemaUrl||``}`;return this._tracers.has(r)||this._tracers.set(r,new Wt({name:e,version:t,schemaUrl:n?.schemaUrl},this._tracerOptions)),this._tracers.get(r)}forceFlush(e){let t=e?.timeoutMillis??this._forceFlushTimeoutMillis,n=this._activeSpanProcessor._spanProcessors.map(e=>new Promise(n=>{let r,i=setTimeout(()=>{n(Error(`Span processor did not completed within timeout period of ${t} ms`)),r=B.timeout},t);e.forceFlush().then(()=>{clearTimeout(i),r!==B.timeout&&(r=B.resolved,n(r))}).catch(e=>{clearTimeout(i),r=B.error,n(e)})}));return new Promise((e,t)=>{Promise.all(n).then(n=>{let r=n.filter(e=>e!==B.resolved);r.length>0?t(r):e()}).catch(e=>t([e]))})}shutdown(){return this._activeSpanProcessor.shutdown()}[N](e,t,n){let r=this._activeSpanProcessor._spanProcessors;return P(`TracerProvider`,{resource:{attributes:Ot(this._resource)},tracers:Array.from(this._tracers.keys()),spanProcessors:r.map(e=>e.constructor?.name??`SpanProcessor`)},e,t,n)}};y();var tn=class{_ratio;_upperBound;constructor(e=0){this._ratio=this._normalize(e),this._upperBound=this._ratio===1?4294967296:Math.floor(this._ratio*4294967295)}shouldSample(e,t){return{decision:oe(t)&&this._accumulate(t)<this._upperBound?F.RECORD_AND_SAMPLED:F.NOT_RECORD}}toString(){return`TraceIdRatioBased{${this._ratio}}`}_normalize(e){return typeof e!=`number`||isNaN(e)?0:e>=1?1:e<=0?0:e}_accumulate(e){let t=0;for(let n=0;n<32;n+=8){let r=0;for(let t=0;t<8;t++){let i=e.charCodeAt(n+t),a=i<58?i-48:i<71?i-55:i-87;r=r<<4|a}t=(t^r)>>>0}return t}};y(),S();var V;(function(e){e.AlwaysOff=`always_off`,e.AlwaysOn=`always_on`,e.ParentBasedAlwaysOff=`parentbased_always_off`,e.ParentBasedAlwaysOn=`parentbased_always_on`,e.ParentBasedTraceIdRatio=`parentbased_traceidratio`,e.TraceIdRatio=`traceidratio`})(V||={});var H=1;function nn(){return{sampler:rn(),forceFlushTimeoutMillis:3e4,generalLimits:{attributeValueLengthLimit:T(`OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT`)??1/0,attributeCountLimit:T(`OTEL_ATTRIBUTE_COUNT_LIMIT`)??128},spanLimits:{attributeValueLengthLimit:T(`OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT`)??1/0,attributeCountLimit:T(`OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT`)??128,linkCountLimit:T(`OTEL_SPAN_LINK_COUNT_LIMIT`)??128,eventCountLimit:T(`OTEL_SPAN_EVENT_COUNT_LIMIT`)??128,attributePerEventCountLimit:T(`OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT`)??128,attributePerLinkCountLimit:T(`OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT`)??128}}}function rn(){let e=_e(`OTEL_TRACES_SAMPLER`)??V.ParentBasedAlwaysOn;switch(e){case V.AlwaysOn:return new L;case V.AlwaysOff:return new I;case V.ParentBasedAlwaysOn:return new R({root:new L});case V.ParentBasedAlwaysOff:return new R({root:new I});case V.TraceIdRatio:return new tn(an());case V.ParentBasedTraceIdRatio:return new R({root:new tn(an())});default:return v.error(`OTEL_TRACES_SAMPLER value "${e}" invalid, defaulting to "${V.ParentBasedAlwaysOn}".`),new R({root:new L})}}function an(){let e=T(`OTEL_TRACES_SAMPLER_ARG`);return e==null?(v.error(`OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${H}.`),H):e<0||e>1?(v.error(`OTEL_TRACES_SAMPLER_ARG=${e} was given, but it is out of range ([0..1]), defaulting to ${H}.`),H):e}S();function on(e){let t=Object.assign({},e.spanLimits);return t.attributeCountLimit=e.spanLimits?.attributeCountLimit??e.generalLimits?.attributeCountLimit??T(`OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT`)??T(`OTEL_ATTRIBUTE_COUNT_LIMIT`)??128,t.attributeValueLengthLimit=e.spanLimits?.attributeValueLengthLimit??e.generalLimits?.attributeValueLengthLimit??T(`OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT`)??T(`OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT`)??1/0,Object.assign({},e,{spanLimits:t})}S();var sn=class extends en{constructor(e={}){let t=fe({},nn(),on(e));delete t.generalLimits,super(t)}};S();var cn=class extends Yt{constructor(e,t){t||={};for(let[e,n]of[[`maxExportBatchSize`,`OTEL_BSP_MAX_EXPORT_BATCH_SIZE`],[`maxQueueSize`,`OTEL_BSP_MAX_QUEUE_SIZE`],[`scheduledDelayMillis`,`OTEL_BSP_SCHEDULE_DELAY`],[`exportTimeoutMillis`,`OTEL_BSP_EXPORT_TIMEOUT`]])if(t[e]===void 0){let r=T(n);r!==void 0&&(t[e]=r)}super({exporter:e,...t})}};y(),Me();var ln=`aventure-mcp-server`,un=`aventure=mcp`,dn=`langfuse.session.id`,fn=`/api/public/otel/v1/traces`,pn=5e3,mn=new Set([`langfuse.observation.input`,`langfuse.observation.output`,`langfuse.observation.status_message`]),hn=[`OTEL_EXPORTER_OTLP_HEADERS`,`OTEL_EXPORTER_OTLP_TRACES_HEADERS`],U,W;function G(e){return e?.trim()||void 0}function gn(){return G(process.env.GIT_SHA)??G(process.env.SENTRY_RELEASE)??t().version}function _n(){let e=G(process.env.LANGFUSE_BASE_URL),t=G(process.env.LANGFUSE_PUBLIC_KEY),n=G(process.env.LANGFUSE_SECRET_KEY);if(e!==void 0&&t!==void 0&&n!==void 0){for(let e of hn){let t=(process.env[e]??``).split(`,`).map(e=>e.split(`=`,1)[0]?.trim().toLowerCase()??``).filter(e=>e!==``&&e!==`authorization`);if(t.length>0)throw Error(`${e} sets ${t.join(`, `)}, which the Langfuse trace exporter would forward`)}return new Et({url:new URL(fn,e).href,headers:{Authorization:`Basic ${Buffer.from(`${t}:${n}`).toString(`base64`)}`,"x-langfuse-ingestion-version":`4`},timeoutMillis:pn})}}function vn(e){let t={};for(let[n,r]of Object.entries(e.attributes))mn.has(n)||(t[n]=r);return{name:e.name,kind:e.kind,spanContext:()=>e.spanContext(),...e.parentSpanContext===void 0?{}:{parentSpanContext:e.parentSpanContext},startTime:e.startTime,endTime:e.endTime,status:e.status,attributes:t,links:e.links,events:e.events,duration:e.duration,ended:e.ended,resource:e.resource,instrumentationScope:e.instrumentationScope,droppedAttributesCount:e.droppedAttributesCount,droppedEventsCount:e.droppedEventsCount,droppedLinksCount:e.droppedLinksCount}}function yn(e){return{export:(t,n)=>e.export(t.map(vn),n),shutdown:()=>e.shutdown(),forceFlush:()=>e.forceFlush?.()??Promise.resolve()}}function bn(){if(U!==void 0)return W;let e=G(process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT),t=[...e===void 0?[]:[yn(new Et({url:e,timeoutMillis:pn}))],...[_n()].filter(e=>e!==void 0)];return U=new sn({sampler:new L,resource:Ne({...Ae(),"service.version":gn()}),spanProcessors:t.map(e=>new cn(e,{exportTimeoutMillis:pn}))}),W=t.length===0?void 0:U.getTracer(ln),W}function xn(){bn()}var Sn=/^00-(?<traceId>[0-9a-f]{32})-(?<spanId>[0-9a-f]{16})-(?<flags>[0-9a-f]{2})$/u,Cn=/[13579bdf]$/u;function wn(e,t,n){let r=bn();if(r===void 0)return;let i=Sn.exec(n??``)?.groups,a=i?.traceId===void 0||i.spanId===void 0?ee:_.setSpanContext(ee,{traceId:i.traceId,spanId:i.spanId,traceFlags:Cn.test(i.flags??``)?x.SAMPLED:x.NONE,isRemote:!0});return r.startSpan(e,{kind:ae.SERVER,attributes:{"langfuse.trace.name":e,...t,"langfuse.environment":Ae()[`deployment.environment.name`],"langfuse.release":gn()}},a)}function Tn(e){let{traceId:t,spanId:n,traceFlags:r}=e.spanContext();return`00-${t}-${n}-${(r&x.SAMPLED)===0?`00`:`01`}`}function En(e,t,n){e.setAttributes(t),e.setStatus({code:n?b.ERROR:b.OK}),e.end()}async function Dn(){let e=U;U=void 0,W=void 0,await e?.shutdown()}var K=new Re,On=`X-Client-Request-Id`,kn=()=>K.getStore()?.requestId,An=()=>K.getStore()?.toolApiCall,jn=()=>K.getStore()?.userBearerToken;function Mn(){let e=K.getStore(),t=[...e?.sessionId===void 0?[]:[`${dn}=${encodeURIComponent(e.sessionId)}`],...e?.traceName===void 0?[]:[`langfuse.trace.name=${encodeURIComponent(e.traceName)}`],...e?.traceTag===void 0?[]:[`langfuse.trace.tags=${encodeURIComponent(e.traceTag.map(encodeURIComponent).join(`,`))}`]].join(`,`);return{...e?.requestId===void 0?{}:{[On]:e.requestId},...e?.traceparent===void 0?{}:{traceparent:e.traceparent,tracestate:un,...t.length===0?{}:{baggage:t}}}}function Nn(e,t){return K.run({...K.getStore(),requestId:e,toolApiCall:{failed:!1}},t)}function Pn(e,t){return K.run({...K.getStore(),userBearerToken:e},t)}function Fn(e,t){return K.run({...K.getStore(),...e},t)}var In=Object.freeze({total:8,perOrigin:2,originLimit:64,failureThreshold:3,cooldownMs:3e4,idleMs:3e4,halfOpenProbes:1}),Ln=Object.freeze({total:128,perOrigin:64,originLimit:64,failureThreshold:5,cooldownMs:15e3,idleMs:3e5,halfOpenProbes:1}),Rn=new WeakMap,q=class extends Error{reason;constructor(e){super(e===`capacity`?`Origin capacity exceeded; try again later.`:`Origin circuit is open; try again later.`),this.reason=e}};function zn(e,t){let n=Date.now(),r=Rn.get(t);r===void 0&&(r={active:0,origin:new Map},Rn.set(t,r));for(let[i,a]of r.origin)i!==e&&a.active===0&&a.updatedAt+t.idleMs<=n&&r.origin.delete(i);let i=r.origin.get(e);if(i===void 0){if(r.origin.size>=t.originLimit)throw new q(`capacity`);i={active:0,failures:0,openUntil:0,updatedAt:n},r.origin.set(e,i)}if(i.openUntil>n||i.failures>=t.failureThreshold&&i.active>=t.halfOpenProbes)throw new q(`circuit`);if(r.active>=t.total||i.active>=t.perOrigin)throw new q(`capacity`);return i.active++,r.active++,{finish:Bn(r,i,t)}}function Bn(e,t,n){let r=!1;return i=>{r||(r=!0,t.active--,e.active--,t.updatedAt=Date.now(),i===`failure`?(t.failures++,t.failures>=n.failureThreshold&&(t.openUntil=t.updatedAt+n.cooldownMs)):i===`success`&&(t.failures=0,t.openUntil=0))}}var Vn=3e4,Hn=20,J=5242880;async function Un(e,t,n,r={}){let i=Jn(Y(e.requestBody?.content),n);if(!i.ok||i.data===null)return h(i.summary,i.warnings);let a=i.data;if(e.requestBody?.required===!0&&t===void 0&&a?.kind!==`multipart`)return h(`Request body is required.`);if(a?.kind===`multipart`)return await Xn(e.requestBody?.required===!0,a.schema,t,r);let o=a?.contentType??r.defaultContentType;return p(`Request body prepared`,{...t===void 0?{}:{body:t},...o===void 0?{}:{contentType:o}})}function Wn(e){if(typeof e!=`string`)return p(`Request body unchanged`,e);let t=e.trimStart().slice(0,1);if(t!==`{`&&t!==`[`)return p(`Request body unchanged`,e);try{let t=m.safeParse(JSON.parse(e));if(!t.success)throw t.error;return p(`Request body parsed`,t.data)}catch(e){return h(`Request body string must be valid JSON: ${e instanceof Error?e.message:String(e)}`)}}function Gn(e,t){let n=e?.schema;if(n===void 0)return!1;let r=M(n),i=n.type??(r===void 0?void 0:t[r]?.type);return Array.isArray(i)?i.includes(`array`):i===`array`}function Kn(e){return Y(e)[0]?.kind??`json`}function qn(e){return e===void 0||Object.keys(e).length===0||Y(e).length>0}function Y(e){let t=Object.entries(e??{});return[...t.flatMap(e=>lr(e[0])?[Yn(e,`json`)]:[]),...t.flatMap(e=>ur(e[0])?[Yn(e,`multipart`)]:[])]}function Jn(e,t){if(t===void 0)return p(`Default request content selected`,e[0]);let n=Z(t),r=e.find(e=>Z(e.contentType)===n);return r===void 0?h(`Request Content-Type '${t}' is not supported. Supported choices: ${e.map(({contentType:e})=>e).join(`, `)||`none`}.`):p(`Explicit request content selected`,r)}function Yn(e,t){let n=e[1].schema;return{contentType:e[0],kind:t,...n===void 0?{}:{schema:n}}}async function Xn(e,t,n,r){if(!e&&n==null)return p(`Optional multipart body omitted`,{});let i=Zn(n);if(!i.ok||i.data===null)return h(i.summary,i.warnings);let a=new FormData;for(let e of Qn(t)){let t=i.data[e.name];if(t==null){if(e.required)return h(`Multipart body requires '${e.name}'.`)}else{if(Array.isArray(t)&&t.length<(e.schema.minItems??0))return h(`Multipart part '${e.name}' requires more entries.`);if(Array.isArray(t)&&t.length>(e.schema.maxItems??2**53-1))return h(`Multipart part '${e.name}' has too many entries.`);if($n(e.schema)||er(e.schema)){let n=er(e.schema)?t:[t];if(!Array.isArray(n)||n.some(e=>typeof e!=`string`))return h(`Multipart part '${e.name}' must contain file paths or URLs.`);for(let t of n){if(typeof t!=`string`)continue;let n=await rr(t,r);if(!n.ok||n.data===null)return h(n.summary,n.warnings,{httpStatus:n.httpStatus});a.append(e.name,n.data.blob,n.data.filename)}}else if(tr(e.schema,t)){let n=JSON.stringify(t);a.append(e.name,new Blob([n],{type:`application/json`}),`${e.name}.json`)}else{let n=nr(a,e.name,t);if(!n.ok)return n}}}return p(`Multipart body prepared`,{body:a})}function Zn(e){if(typeof e==`object`&&e&&!Array.isArray(e)){let t=Object.fromEntries(Object.entries(e));return p(`Multipart input parsed`,t)}return h(`Multipart request body must be a JSON object keyed by form part name.`)}function Qn(e){let t=new Set(e?.required??[]);return Object.entries(e?.properties??{}).map(([e,n])=>({name:e,schema:n,required:t.has(e)}))}function $n(e){return e.type===`string`&&e.format===`binary`}function er(e){return e.type===`array`&&e.items!==void 0&&$n(e.items)}function tr(e,t){return typeof t!=`object`||!t||Array.isArray(t)?!1:e.type===`object`||typeof e.$ref==`string`&&e.$ref.length>0}function nr(e,t,n){if(Array.isArray(n)){for(let r of n){let n=nr(e,t,r);if(!n.ok)return n}return p(`Multipart scalar array appended`,null)}return typeof n==`object`?h(`Multipart part '${t}' must be scalar.`):(e.append(t,String(n)),p(`Multipart scalar appended`,null))}async function rr(e,t){if(t.signal?.aborted||(t.deadline??1/0)<=Date.now()){let e=An();return e!==void 0&&!X(t.signal)&&(e.failed=!0),h(`Media preparation canceled or invocation deadline exceeded.`)}return sr(e)?kn()===void 0?await ir(e,t):h(`MCP media URL fetching is disabled. Pass the page as sourceUrl in the JSON body instead.`):kn()===void 0?await or(e,t.signal):h(`MCP callers cannot upload local files: pass an http(s) URL as the multipart part, or send media by sourceUrl in a JSON body. Local file paths are CLI-only.`)}async function ir(e,t){let n=new AbortController,r=Math.min(Vn,(t.deadline??1/0)-Date.now()),i=setTimeout(()=>n.abort(),Math.max(r,1)),a=t.signal?AbortSignal.any([n.signal,t.signal]):n.signal,o,s,c=`neutral`;try{if(a.throwIfAborted(),r<=0)throw Error(`Invocation deadline exceeded.`);let t=new URL(e),n=t;for(let e=0;;e++){a.throwIfAborted(),o=zn(n.origin,In),c=`failure`,s=await fetch(n.href,{signal:a,redirect:`manual`});let t=s.headers.get(`location`);if(![301,302,303,307,308].includes(s.status)||t===null)break;if(await s.body?.cancel(),e>=Hn)throw Error(`Media URL exceeded the redirect limit.`);let r=new URL(t,n);o.finish(`success`),o=void 0,s=void 0,n=r}if(c=s.status===429||s.status>=500?`failure`:`success`,!s.ok)return await s.body?.cancel(),h(`Failed to fetch media URL: ${s.status} ${s.statusText}`,[],{httpStatus:s.status});c=`failure`;let i=s.headers.get(`content-type`)?.split(`;`)[0]?.trim()??cr(t.pathname)??``,l=await ar(s,{type:i,signal:a});return c=`success`,p(`URL media fetched`,{blob:l,filename:Fe(t.pathname)||`upload`})}catch(e){(e instanceof q||a.aborted||r<=0)&&(c=`failure`),e instanceof RangeError&&(c=`success`),X(t.signal)&&(c=`neutral`),s?.body&&!s.body.locked&&!s.bodyUsed&&await s.body.cancel();let i=X(t.signal)?`Failed to fetch media URL: canceled.`:t.signal?.aborted?`Failed to fetch media URL: invocation deadline exceeded.`:n.signal.aborted?`Failed to fetch media URL: timed out after ${r}ms.`:`Failed to fetch media URL: ${e instanceof Error?e.message:String(e)}`;return h(i,[],{httpStatus:e instanceof RangeError?void 0:s?.status})}finally{clearTimeout(i);let e=An();e!==void 0&&c===`failure`&&!X(t.signal)&&(e.failed=!0),o?.finish(c)}}function X(e){return e?.aborted===!0&&!(e.reason instanceof DOMException&&e.reason.name===`TimeoutError`)}async function ar(e,{type:t,signal:n}){let r=e.body?.getReader();if(r===void 0)throw Error(`Media URL returned no body.`);let i=[],a=0,o=!1,s,c=new Promise(e=>{s=()=>e({done:!0,value:void 0}),n.addEventListener(`abort`,s,{once:!0})});try{if(Number(e.headers.get(`content-length`))>J)throw RangeError(`Media exceeds the ${J}-byte upload limit.`);for(;;){n.throwIfAborted();let e=await Promise.race([r.read(),c]);if(n.throwIfAborted(),e.done)break;if(a+=e.value.byteLength,a>J)throw RangeError(`Media exceeds the ${J}-byte upload limit.`);i.push(new Blob([e.value.slice()]))}return o=!0,new Blob(i,{type:t})}finally{s&&n.removeEventListener(`abort`,s),o||await r.cancel(),r.releaseLock()}}async function or(e,t){try{let n=cr(e)??``,r=await Le(e,{signal:t});return p(`File media read`,{blob:new Blob([r],{type:n}),filename:Fe(e)})}catch(t){return h(`Failed to read media file '${e}': ${t instanceof Error?t.message:String(t)}`)}}function sr(e){return e.startsWith(`http://`)||e.startsWith(`https://`)}function cr(e){return dr[Ie(e).toLowerCase()]}function lr(e){let t=Z(e);return t===`*/*`||t===`application/json`||t.endsWith(`+json`)}function ur(e){return Z(e)===`multipart/form-data`}var Z=e=>e.split(`;`)[0]?.trim().toLowerCase()??``,dr={".gif":`image/gif`,".heic":`image/heic`,".heif":`image/heif`,".jpeg":`image/jpeg`,".jpg":`image/jpeg`,".png":`image/png`,".webp":`image/webp`};function fr(e,t,n){let r=new Map,i=(t,a,o)=>{let s=M(t);if(a>n||s!==void 0&&o.includes(s))return;let c=s===void 0?o:[...o,s],l=mr(e,t);for(let e of[...l.items===void 0?[]:[l.items],...l.oneOf??[],...l.anyOf??[],...l.allOf??[]])i(e,a,c);for(let[e,t]of Object.entries(l.properties??{}))r.set(e,Math.min(r.get(e)??a,a)),i(t,a+1,c)};for(let[e,n]of Object.entries(t))e.startsWith(`2`)&&i(pr(n.content),0,[]);return r}function pr(e){return e?.[`application/json`]?.schema??Object.values(e??{}).find(e=>e.schema!==void 0)?.schema}function mr(e,t){let n=M(t);return{...n===void 0?void 0:e.components.schemas[n],...t}}function hr(e){if(e===`private`||typeof e==`object`&&(e.scope===`private`||e.value===`private`))return`private`}function gr(e){return e===`write`||e===`delete`}function _r(e){return gr(e)||e===`job`}function vr(e,t){return e===`DELETE`||t===`delete`}var yr=`Shell-safe input: single-quote string flag values that contain $; use --from-file or stdin for JSON bodies, multiline text, and free text with currency amounts.`;function br(e,t){let n=e===`array`?t:e;return n===void 0||n===`string`}function xr(e){let t=e.operation[`x-aventure-tool`];if(!Er(e.path,e.operation,e.method===`GET`&&t?.auth===`none`,e.includeBinary===!0))return null;let n=Tr(e.operation.operationId),r=Lr(e.path,n),i=wr(r,n,e.method),a=Sr(e.method,e.operation);if(a===null)return null;let o=t?.auth===`read`&&i===`write`?`lookup`:i,s=e.method===`GET`||a===`read`||a===`none`;return{resource:Rr(e.path),intent:o,cliPath:r,scope:s&&!gr(o)?`read`:`write`,auth:a,visibility:hr(e.operation[`x-aventure-visibility`]),mutates:t?.mutates===!0||void 0,stdinBody:e.operation.requestBody!==void 0&&Kn(e.operation.requestBody.content)===`json`,destructive:vr(e.method,o)}}function Sr(e,t){let n=t[`x-aventure-tool`]?.auth;if(n===`none`)return`none`;if(n===`read`)return`read`;if(e===`GET`&&(t.security?.length??0)===0)return`none`;let r=!1,i=!1,a=!1;for(let e of t.security??[]){let t=Object.keys(e);t.includes(`clientSecretAuth`)&&(r=!0),t.includes(`adminApiKeyAuth`)&&(a=!0),(t.includes(`bearerAuth`)||t.includes(`clerkApiKeyAuth`))&&(i=!0)}return e===`GET`&&r||r&&!a&&!i?`read`:a?`write`:i?`bearer`:e===`GET`?`read`:null}var Q={add:`write`,answer:`search`,ask:`search`,attach:`write`,audit:`read`,batch:`lookup`,convert:`write`,create:`write`,delete:`delete`,enrich:`write`,filter:`search`,get:`read`,import:`write`,join:`write`,list:`read`,lookup:`lookup`,merge:`write`,preview:`lookup`,reconcile:`write`,remove:`delete`,replace:`write`,resolve:`lookup`,search:`search`,status:`read`,suggest:`read`,update:`write`,upload:`write`},Cr=`status`;function wr(e,t,n){if(e.length===1&&e[0]===Cr)return`status`;let r=Object.hasOwn(Q,t)?Q[t]:void 0;return r===void 0?n===`GET`?`read`:n===`DELETE`?`delete`:`write`:r}function Tr(e){let t=/^[a-z]+/u.exec(e)?.[0];if(t===void 0)throw Error(`operationId '${e}' has no verb`);return t}function Er(e,t,n,r){return Dr(e)&&t.hidden!==!0&&(n||!Or.some(t=>t.test(e)))&&qn(t.requestBody?.content)&&(Nr(t.responses)||r&&Mr(t))}function Dr(e){return e.startsWith(`/v1/`)||e.startsWith(`/v2/`)}var Or=[/^\/v1\/auth\/(?:session|login|ui|registrations|password-resets|cli-authorizations)(?:\/|$)/u,/^\/v1\/addresses\/locations(?:\/|$)/u,/^\/v1\/entities\/\{entityId\}\/sites$/u,/^\/v1\/(?:chat\/completions|embeddings)$/u,/^\/v1\/observability(?:\/|$)/u,/^\/v1\/media\/identicons(?:\/|$)/u];function kr(e){return e!==`/v1/auth/api-key`&&!/^\/v1\/sitemap(?:\/|$)/u.test(e)}var Ar=/(?:^|-)(?:runs|jobs)$/u;function jr(e){switch(e.intent){case`read`:case`lookup`:case`search`:case`status`:case`job`:return e.intent;case`write`:{let t=Tr(e.operationId);return t===`enrich`||t===`create`&&Ar.test(e.cliPath.at(-2)??``)?`job`:null}case`delete`:return null;default:{let t=e.intent;throw Error(`No public MCP intent for ${String(t)}`)}}}function Mr(e){let t=Object.entries(e.responses).filter(([e])=>e.startsWith(`2`));return t.length>0&&t.every(([,e])=>Object.values(e.content??{}).some(e=>Ir(e.schema)))}function Nr(e){return Object.entries(e).filter(([e])=>e.startsWith(`2`)).every(([,e])=>Pr(e.content))}function Pr(e){if(e===void 0)return!0;let t=Object.entries(e);return t.length===0||t.some(([e,t])=>Fr(e)&&!Ir(t.schema))}function Fr(e){return e===`*/*`||e===`application/json`||e.endsWith(`+json`)}function Ir(e){return e?.format===`byte`||e?.format===`binary`}function Lr(e,t){let n=Vr(e).map($),r=n.length===1&&t===`get`&&!e.includes(`{`),i=n.some(e=>e.split(`-`).includes(t));return r||i?n:[...n,t]}function Rr(e){return $(Vr(e).at(0)??`system`)}function zr(e){return`aventure_${e}`}function $(e){return e.replace(/([a-z0-9])([A-Z])/gu,`$1-$2`).replace(/[^A-Za-z0-9]+/gu,`-`).replace(/^-+|-+$/gu,``).toLowerCase()}var Br=e=>`--${$(e)}`;function Vr(e){return Hr(e).filter(e=>!Ur(e)&&!Wr(e))}function Hr(e){return e.split(`/`).filter(e=>e.length>0)}function Ur(e){return/^v\d+$/u.test(e)}function Wr(e){return e.startsWith(`{`)&&e.endsWith(`}`)}export{Pn as A,dt as B,On as C,jn as D,Mn as E,xn as F,M as G,Ke as H,Tn as I,Be as K,k as L,En as M,Dn as N,Nn as O,wn as P,Ge as R,zn as S,An as T,ft as U,ct as V,lt as W,Y as _,br as a,Ln as b,gr as c,$ as d,jr as f,Un as g,Wn as h,_r as i,dn as j,Fn as k,zr as l,fr as m,Q as n,Br as o,xr as p,Mr as r,vr as s,yr as t,kr as u,Gn as v,kn as w,q as x,Jn as y,ut as z};
@@ -0,0 +1 @@
1
+ import{i as e}from"./iso-l1vOidnb.js";var t=e([`Company`,`Investment Firm`,`Fund`,`Nonprofit`,`Government`,`Organization`,`Business Line`,`Product`,`Service`]);export{t};
@@ -0,0 +1,4 @@
1
+ import{r as e}from"./rolldown-runtime-B09viugM.js";var t=new TextEncoder,n=new TextDecoder,r=new TextDecoder(`utf-8`,{fatal:!0}),i=2**32;function a(...e){let t=e.reduce((e,{length:t})=>e+t,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function o(e,t,n){if(t<0||t>=i)throw RangeError(`value must be >= 0 and <= ${i-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,t&255],n)}function s(e){let t=Math.floor(e/i),n=e%i,r=new Uint8Array(8);return o(r,t,0),o(r,n,4),r}function c(e){let t=new Uint8Array(4);return o(t,e),t}var l=/[^\x00-\x7f]/;function u(e){if(typeof e==`string`&&e.length>=128){if(l.test(e))throw TypeError(`non-ASCII string encountered in encode()`);return t.encode(e)}let n=new Uint8Array(e.length);for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r>127)throw TypeError(`non-ASCII string encountered in encode()`);n[t]=r}return n}function d(e,t=!1){if(Uint8Array.prototype.toBase64)return e.toBase64({alphabet:t?`base64url`:`base64`,omitPadding:t});let n=32768,r=[];for(let t=0;t<e.length;t+=n)r.push(String.fromCharCode.apply(null,e.subarray(t,t+n)));let i=btoa(r.join(``));return t?i.replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`):i}function f(e,t=!1){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e,{alphabet:t?`base64url`:`base64`});if(t){if(e.includes(`+`)||e.includes(`/`))throw TypeError(`Invalid base64url`);e=e.replace(/-/g,`+`).replace(/_/g,`/`)}let n=atob(e),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r}async function p(e,t){let n=`SHA-${e.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(n,t))}var m=e({JOSEAlgNotAllowed:()=>v,JOSEError:()=>h,JOSENotSupported:()=>y,JWEDecryptionFailed:()=>b,JWEInvalid:()=>x,JWKInvalid:()=>w,JWKSInvalid:()=>T,JWKSMultipleMatchingKeys:()=>D,JWKSNoMatchingKey:()=>E,JWKSTimeout:()=>O,JWSInvalid:()=>S,JWSSignatureVerificationFailed:()=>k,JWTClaimValidationFailed:()=>g,JWTExpired:()=>_,JWTInvalid:()=>C}),h=class extends Error{static code=`ERR_JOSE_GENERIC`;code=`ERR_JOSE_GENERIC`;constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},g=class extends h{static code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},_=class extends h{static code=`ERR_JWT_EXPIRED`;code=`ERR_JWT_EXPIRED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},v=class extends h{static code=`ERR_JOSE_ALG_NOT_ALLOWED`;code=`ERR_JOSE_ALG_NOT_ALLOWED`},y=class extends h{static code=`ERR_JOSE_NOT_SUPPORTED`;code=`ERR_JOSE_NOT_SUPPORTED`},b=class extends h{static code=`ERR_JWE_DECRYPTION_FAILED`;code=`ERR_JWE_DECRYPTION_FAILED`;constructor(e=`decryption operation failed`,t){super(e,t)}},x=class extends h{static code=`ERR_JWE_INVALID`;code=`ERR_JWE_INVALID`},S=class extends h{static code=`ERR_JWS_INVALID`;code=`ERR_JWS_INVALID`},C=class extends h{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`},w=class extends h{static code=`ERR_JWK_INVALID`;code=`ERR_JWK_INVALID`},T=class extends h{static code=`ERR_JWKS_INVALID`;code=`ERR_JWKS_INVALID`},E=class extends h{static code=`ERR_JWKS_NO_MATCHING_KEY`;code=`ERR_JWKS_NO_MATCHING_KEY`;constructor(e=`no applicable key found in the JSON Web Key Set`,t){super(e,t)}},D=class extends h{[Symbol.asyncIterator]=async function*(){};static code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`;code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`;constructor(e=`multiple matching keys found in the JSON Web Key Set`,t){super(e,t)}},O=class extends h{static code=`ERR_JWKS_TIMEOUT`;code=`ERR_JWKS_TIMEOUT`;constructor(e=`request timed out`,t){super(e,t)}},k=class extends h{static code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;constructor(e=`signature verification failed`,t){super(e,t)}},A=e({decode:()=>M,encode:()=>N}),j=`The input to be decoded is not correctly encoded.`;function M(e){try{return f(typeof e==`string`?e:n.decode(e),!0)}catch(e){throw TypeError(j,{cause:e})}}function N(e){return d(typeof e==`string`?t.encode(e):e,!0)}function P(e,t){if(!(e instanceof Uint8Array))throw TypeError(`${t} must be an instance of Uint8Array`)}function F(e){if(typeof e!=`object`||!e||Object.prototype.toString.call(e)!==`[object Object]`)return!1;let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}function ee(e){return F(e)&&Array.isArray(e.keys)&&Array.from(e.keys).every(F)}function te(...e){let t=new Set;for(let n of e)if(n)for(let e of Object.keys(n)){if(t.has(e))return!1;t.add(e)}return!0}function I(e,t){if(e!==void 0)throw TypeError(`${t} can only be called once`)}function L(e,t,n){try{return M(e)}catch{throw new n(`Failed to base64url decode the ${t}`)}}function ne(e,t,n){try{return u(e)}catch{throw new n(`The ${t} is not a valid base64url string`)}}function re(e,t,n){let i;try{i=JSON.parse(r.decode(M(e)))}catch{throw new t(n)}if(!F(i))throw new t(n);return i}var ie={__proto__:null,b64:!0},ae={__proto__:null};function oe(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some(e=>typeof e!=`string`)))throw TypeError(`"${e}" option must be an array of strings`);return t===void 0?void 0:new Set(t)}function se(e,t){let{crit:n}=t??{};if(Array.isArray(n)&&new Set(n).size!==n.length)throw new e(`"crit" (Critical) Header Parameter MUST NOT contain duplicate values`)}function ce(e,t,n,r,i){if(i.crit!==void 0&&r?.crit===void 0)throw new e(`"crit" (Critical) Header Parameter MUST be integrity protected`);if(!r||r.crit===void 0)return[];if(!Array.isArray(r.crit)||r.crit.length===0||r.crit.some(e=>typeof e!=`string`||e.length===0))throw new e(`"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present`);let a=n===void 0?t:{__proto__:null,...n,...t};for(let t of r.crit){if(!(t in a))throw new y(`Extension Header Parameter "${t}" is not recognized`);if(!Object.hasOwn(i,t)||i[t]===void 0)throw new e(`Extension Header Parameter "${t}" is missing`);if(a[t]&&(!Object.hasOwn(r,t)||r[t]===void 0))throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return r.crit}function le(e,t){if(t.includes(`b64`)){let t=e.b64;if(typeof t!=`boolean`)throw new S(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);return t}return!0}function ue(e,t){let n,r;try{n=JSON.stringify(t),r=JSON.parse(n)}catch(t){throw new e(`JOSE Header is not valid JSON`,{cause:t})}if(!F(r))throw new e(`JOSE Header is not a JSON object`);return[r,n]}var de=e=>e[Symbol.toStringTag],fe=(e,t,n)=>{let{alg:r}=e;if(t.use!==void 0){let e=n===`sign`||n===`verify`?`sig`:`enc`;if(t.use!==e)throw TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(t.alg!==void 0&&t.alg!==r)throw TypeError(`Invalid key for this operation, its "alg" must be "${r}" when present`);if(Array.isArray(t.key_ops)){let r=n===`encrypt`||n===`decrypt`?e.ops?.[n===`encrypt`?0:1]:n;if(r&&!t.key_ops.includes(r))throw TypeError(`Invalid key for this operation, its "key_ops" must include "${r}" when present`)}};async function R(e,t,n){let{alg:r,secret:i}=e,a=n===`decrypt`||n===`sign`;if(i&&t instanceof Uint8Array)return t;let o,s;if(F(t)){if(o=Te(t),typeof o.kty!=`string`)throw ye(r,t,i);if(!(i?o.kty===`oct`&&typeof o.k==`string`:o.kty!==`oct`&&(a?o.kty===`AKP`&&typeof o.priv==`string`||typeof o.d==`string`:o.d===void 0&&o.priv===void 0)))throw TypeError(i?`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`:`JSON Web Key for this operation must be a ${a?`private`:`public`} JWK`);if(fe(e,o,n),o.kty===`oct`)return M(o.k);if(!Object.isFrozen(t)){let{key_ops:e}=t;Array.isArray(e)&&Object.freeze(e),Object.freeze(t)}}else{if(!_e(t))throw ye(r,t,i);let e=i?`secret`:a?`private`:`public`;if(t.type!==e&&(i||[`secret`,`public`,`private`].includes(t.type)))throw TypeError(`${de(t)} instances must be of type "${e}" for the ${r} algorithm`);if(z(t))return t;if(s=t,s.type===`secret`)return s.export()}pe||=new WeakMap;let c=t,l=pe.get(c);if(l?.[r])return l[r];if(l||pe.set(c,l={}),s&&typeof s.toCryptoKey==`function`){let t=s.type===`public`,n=me[s.asymmetricKeyDetails?.namedCurve],i=e.resolve?.({crv:n,asymmetricKeyType:s.asymmetricKeyType})??e.subtle;return l[r]=s.toCryptoKey(i,t,e.usages[+!t])}return o??=s.export({format:`jwk`}),o.alg=r,l[r]=await V(e,o)}var pe,me={__proto__:null,prime256v1:`P-256`,secp384r1:`P-384`,secp521r1:`P-521`};function he(e){if(!z(e))throw Error(`CryptoKey instance expected`)}var z=e=>{if(e?.[Symbol.toStringTag]===`CryptoKey`)return!0;try{return e instanceof CryptoKey}catch{return!1}},ge=e=>e?.[Symbol.toStringTag]===`KeyObject`,_e=e=>z(e)||ge(e);function ve(e,t,...n){if(n.length>2){let t=n.pop();e+=`one of type ${n.join(`, `)}, or ${t}.`}else n.length===2?e+=`one of type ${n[0]} or ${n[1]}.`:e+=`of type ${n[0]}.`;return t==null?e+=` Received ${t}`:typeof t==`function`&&t.name?e+=` Received function ${t.name}`:typeof t==`object`&&t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var B=(e,...t)=>ve(`Key must be `,e,...t);function ye(e,t,n){let r=[`CryptoKey`,`KeyObject`,`JSON Web Key`];return n&&r.push(`Uint8Array`),TypeError(ve(`Key for the ${e} algorithm must be `,t,...r))}var be=(e,t=`algorithm.name`)=>TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function xe(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function Se(e,t){let{modulusLength:n}=t.algorithm;if(typeof n!=`number`||n<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}function Ce(e,t,n){let r=e.algorithm;if(r.name!==t.name)throw be(t.name);if(t.hash&&r.hash?.name!==t.hash)throw be(t.hash,`algorithm.hash`);if(t.namedCurve&&r.namedCurve!==t.namedCurve)throw be(t.namedCurve,`algorithm.namedCurve`);if(t.length!==void 0&&r.length!==t.length)throw be(t.length,`algorithm.length`);xe(e,n)}function we(e){return{__proto__:null,...e}}function Te(e){let t=we(e);if(t.ext!==void 0&&typeof t.ext!=`boolean`)throw TypeError(`"ext" (Extractable) Parameter must be a boolean`);if(t.key_ops!==void 0){let e=t.key_ops,n=Array.isArray(e)?[...e]:void 0;if(!n||n.some(e=>typeof e!=`string`)||new Set(n).size!==n.length)throw TypeError(`"key_ops" (Key Operations) Parameter must be an array of unique strings`);t.key_ops=n}return t}function Ee(e){if(e!==void 0&&typeof e!=`boolean`)throw TypeError(`"extractable" option must be a boolean`);return e}async function V(e,t,n){if(!e.kty.includes(t.kty))throw new y(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`);let r=e.resolve?.({kty:t.kty,crv:t.crv})??e.subtle,i=!!(t.d||t.priv),a={...t,ext:n??t.ext};return a.kty!==`AKP`&&delete a.alg,delete a.use,crypto.subtle.importKey(`jwk`,a,r,a.ext??!i,t.key_ops??e.usages[+!!i])}async function H(e,t,n,r=!1){return e instanceof Uint8Array&&(e=await crypto.subtle.importKey(`raw`,e,t,r,[n])),Ce(e,t,n),e}var De=e=>crypto.getRandomValues(new Uint8Array(e.cekBits>>3));function Oe(e,t){let n=e.byteLength<<3;if(n!==t)throw new x(`Invalid Content Encryption Key length. Expected ${t} bits, got ${n} bits`)}var ke=e=>crypto.getRandomValues(new Uint8Array(e.ivBits>>3));function Ae(e,t){if(t.length<<3!==e.ivBits)throw new x(`Invalid Initialization Vector length`)}async function je(e,t,n){if(!(t instanceof Uint8Array))throw TypeError(B(t,`Uint8Array`));let r=e.cekBits>>1;return[await crypto.subtle.importKey(`raw`,t.subarray(r>>3),`AES-CBC`,!1,[n]),await crypto.subtle.importKey(`raw`,t.subarray(0,r>>3),{hash:`SHA-${r<<1}`,name:`HMAC`},!1,[`sign`]),r]}async function Me(e,t,n){return new Uint8Array((await crypto.subtle.sign(`HMAC`,e,t)).slice(0,n>>3))}async function Ne(e,t,n,r,i){let[o,c,l]=await je(e,n,`encrypt`),u=new Uint8Array(await crypto.subtle.encrypt({iv:r,name:`AES-CBC`},o,t));return{ciphertext:u,tag:await Me(c,a(i,r,u,s(i.length*8)),l),iv:r}}async function Pe(e,t){let n={name:`HMAC`,hash:`SHA-256`},r=await crypto.subtle.generateKey(n,!1,[`sign`,`verify`]),i=await crypto.subtle.sign(n,r,e);return crypto.subtle.verify(n,r,i,t)}async function Fe(e,t,n,r,i,o){let[c,l,u]=await je(e,t,`decrypt`),d=await Me(l,a(o,r,n,s(o.length*8)),u);try{if(await Pe(i,d))return new Uint8Array(await crypto.subtle.decrypt({iv:r,name:`AES-CBC`},c,n))}catch{}throw new b}async function Ie(e,t,n,r,i){if(!z(n)&&!(n instanceof Uint8Array))throw TypeError(B(n,`CryptoKey`,`KeyObject`,`Uint8Array`,`JSON Web Key`));if(r?Ae(e,r):r=ke(e),n instanceof Uint8Array&&Oe(n,e.cekBits),e.cbc)return Ne(e,t,n,r,i);let a=await H(n,e.subtle,`encrypt`),o=new Uint8Array(await crypto.subtle.encrypt({additionalData:i,iv:r,name:`AES-GCM`,tagLength:128},a,t));return{ciphertext:o.subarray(0,-16),tag:o.subarray(-16),iv:r}}async function Le(e,t,n,r,i,o){if(!z(t)&&!(t instanceof Uint8Array))throw TypeError(B(t,`CryptoKey`,`KeyObject`,`Uint8Array`,`JSON Web Key`));if(!r)throw new x(`JWE Initialization Vector missing`);if(!i)throw new x(`JWE Authentication Tag missing`);if(!e.cbc&&i.length!==16)throw new x(`Invalid Authentication Tag length`);if(Ae(e,r),t instanceof Uint8Array&&Oe(t,e.cekBits),e.cbc)return Fe(e,t,n,r,i,o);let s=await H(t,e.subtle,`decrypt`);try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:o,iv:r,name:`AES-GCM`,tagLength:128},s,a(n,i)))}catch{throw new b}}function Re(e){let t={__proto__:null};for(let n in e)t[n]={...e[n],alg:n};return t}var ze=[[`encrypt`,`wrapKey`],[`decrypt`,`unwrapKey`]],Be=[[],[`deriveBits`]],Ve=[[],[]];function He(e){return{kty:[`RSA`],mode:`key-encryption`,subtle:{name:`RSA-OAEP`,hash:`SHA-${e}`},usages:ze,ops:[`wrapKey`,`unwrapKey`]}}function Ue(e){return{kty:[`EC`,`OKP`],mode:e,subtle:{name:`ECDH`},resolve:({kty:e,crv:t,asymmetricKeyType:n})=>{if(t===`X25519`||n===`x25519`)return{name:`X25519`};if(e===`OKP`)throw new y(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`);return{name:`ECDH`,namedCurve:t}},usages:Be,ops:[void 0,`deriveBits`]}}function U(e,t=!1){return{kty:[`oct`],mode:`key-wrapping`,secret:!0,subtle:{name:t?`AES-GCM`:`AES-KW`,length:e},usages:Ve,ops:t?[`encrypt`,`decrypt`]:[`wrapKey`,`unwrapKey`]}}function We(){return{kty:[`oct`],mode:`key-wrapping`,secret:!0,subtle:{name:`PBKDF2`},usages:Ve,ops:[`deriveBits`,`deriveBits`]}}var Ge=Re({dir:{kty:[`oct`],mode:`direct-encryption`,secret:!0,subtle:{name:`AES-GCM`},usages:Ve,ops:[`encrypt`,`decrypt`]},"RSA-OAEP":He(1),"RSA-OAEP-256":He(256),"RSA-OAEP-384":He(384),"RSA-OAEP-512":He(512),"ECDH-ES":Ue(`direct-key-agreement`),"ECDH-ES+A128KW":Ue(`key-agreement-with-key-wrapping`),"ECDH-ES+A192KW":Ue(`key-agreement-with-key-wrapping`),"ECDH-ES+A256KW":Ue(`key-agreement-with-key-wrapping`),A128KW:U(128),A192KW:U(192),A256KW:U(256),A128GCMKW:U(128,!0),A192GCMKW:U(192,!0),A256GCMKW:U(256,!0),"PBES2-HS256+A128KW":We(),"PBES2-HS384+A192KW":We(),"PBES2-HS512+A256KW":We()}),Ke=[`encrypt`,`decrypt`];function W(e,t=!1){return{kty:[`oct`],secret:!0,subtle:{name:t?`AES-CBC`:`AES-GCM`,length:e},usages:Ve,ops:Ke,cekBits:e,ivBits:t?128:96,cbc:t}}var qe=Re({A128GCM:W(128),A192GCM:W(192),A256GCM:W(256),"A128CBC-HS256":W(256,!0),"A192CBC-HS384":W(384,!0),"A256CBC-HS512":W(512,!0)});function Je(e,t){throw new y(`Invalid or unsupported "${e}" (JWE ${t}) header value`)}function G(e){return(typeof e==`string`?Ge[e]:void 0)??Je(`alg`,`Algorithm`)}function K(e){return e.mode===`key-wrapping`||e.mode===`key-encryption`||e.mode===`key-agreement-with-key-wrapping`}function Ye(e){return(typeof e==`string`?qe[e]:void 0)??Je(`enc`,`Encryption Algorithm`)}function Xe(e,t){if(e.algorithm.name!==`ECDH`&&e.algorithm.name!==`X25519`)throw TypeError(`CryptoKey does not support this operation, its algorithm.name must be ECDH or X25519`);xe(e,t)}async function Ze(e,t,n){let r=await H(t,G(e).subtle,`wrapKey`,!0),i=await crypto.subtle.importKey(`raw`,n,{hash:`SHA-256`,name:`HMAC`},!0,[`sign`]);return new Uint8Array(await crypto.subtle.wrapKey(`raw`,i,r,`AES-KW`))}async function Qe(e,t,n){let r=await H(t,G(e).subtle,`unwrapKey`,!0),i=await crypto.subtle.unwrapKey(`raw`,n,r,`AES-KW`,{hash:`SHA-256`,name:`HMAC`},!0,[`sign`]);return new Uint8Array(await crypto.subtle.exportKey(`raw`,i))}function $e(e,t,n){Ce(t,G(e).subtle,n),Se(e,t)}async function et(e,t,n,r){if(!(e instanceof Uint8Array)||e.length<8)throw new x(`PBES2 Salt Input must be 8 or more octets`);if(!Number.isSafeInteger(n)||Math.sign(n)!==1)throw new x(`PBES2 Count Input must be a positive integer`);let i=a(u(t),Uint8Array.of(0),e),o=parseInt(t.slice(13,16),10),s={hash:`SHA-${t.slice(8,11)}`,iterations:n,name:`PBKDF2`,salt:i},c=await H(r,G(t).subtle,`deriveBits`);return new Uint8Array(await crypto.subtle.deriveBits(s,c,o))}function tt(e){return a(c(e.length),e)}async function nt(e,t,n){let r=t>>3,i=Math.ceil(r/32),o=new Uint8Array(i*32);for(let t=1;t<=i;t++){let r=await p(`sha256`,a(c(t),e,n));o.set(r,(t-1)*32)}return o.slice(0,r)}async function rt(e,t,n,r,i=new Uint8Array,o=new Uint8Array){Xe(e),Xe(t,`deriveBits`);let s=a(tt(u(n)),tt(i),tt(o),c(r));return nt(new Uint8Array(await crypto.subtle.deriveBits({name:e.algorithm.name,public:e},t,e.algorithm.name===`X25519`?256:Math.ceil(parseInt(e.algorithm.namedCurve.slice(-3),10)/8)<<3)),r,s)}function it(e){he(e);let t=e.algorithm.namedCurve;if(t!==`P-256`&&t!==`P-384`&&t!==`P-521`&&e.algorithm.name!==`X25519`)throw new y(`ECDH with the provided key is not allowed or not supported by your javascript runtime`)}function at(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`string`)throw new x(`JOSE Header "${t}" (Agreement Party${t===`apu`?`U`:`V`}Info) invalid`);return L(n,t,x)}}function ot(e,t){if(e!==void 0&&t!==void 0&&e.byteLength===t.byteLength){for(let n=0;n<e.byteLength;n++)if(e[n]!==t[n])return;throw new x(`JOSE Header "apu" and "apv" values must be distinct`)}}function st(e){if(e===void 0)throw new x(`JWE Encrypted Key missing`)}function ct(e){if(e!==void 0)throw new x(`Encountered unexpected JWE Encrypted Key`)}function lt(e){if(e!==void 0&&e!==1/0&&(!Number.isSafeInteger(e)||e<1))throw TypeError(`maxPBES2Count must be a positive safe integer or Infinity`)}async function ut(e,t,n,r,i,a){let{alg:o}=e,s=e.mode;if(s===`direct-encryption`)return ct(r),n;let c=s===`direct-key-agreement`;switch(c?ct(r):st(r),e.subtle.name){case`ECDH`:{let{epk:r}=i;if(!F(r)||[`d`,`k`,`p`,`q`,`dp`,`dq`,`qi`,`oth`,`priv`].some(e=>Object.hasOwn(r,e)))throw new x(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`);it(n);let a=await V(e,r),s=at(i,`apu`),l=at(i,`apv`);ot(s,l);let u=await rt(a,n,c?t.alg:o,c?t.cekBits:parseInt(o.slice(-5,-2),10),s,l);if(c)return u;n=u;break}case`RSA-OAEP`:return he(n),$e(o,n,`decrypt`),new Uint8Array(await crypto.subtle.decrypt(`RSA-OAEP`,n,r));case`PBKDF2`:{if(typeof i.p2c!=`number`)throw new x(`JOSE Header "p2c" (PBES2 Count) missing or invalid`);lt(a);let e=a??1e4;if(i.p2c>e)throw new x(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`);if(typeof i.p2s!=`string`)throw new x(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`);n=await et(L(i.p2s,`p2s`,x),o,i.p2c,n);break}case`AES-GCM`:{if(typeof i.iv!=`string`)throw new x(`JOSE Header "iv" (Initialization Vector) missing or invalid`);if(typeof i.tag!=`string`)throw new x(`JOSE Header "tag" (Authentication Tag) missing or invalid`);let e=L(i.iv,`iv`,x),t=L(i.tag,`tag`,x);if(e.byteLength!==12)throw new x(`Invalid Initialization Vector length`);if(t.byteLength!==16)throw new x(`Invalid Authentication Tag length`);return Le(Ye(o.slice(0,-2)),n,r,e,t,new Uint8Array)}}return Qe(o.slice(-6),n,r)}async function dt(e,t,n,r,i,a={}){let{alg:o,mode:s}=e,c=K(e);if(i!==void 0&&!c)throw TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${o}`);let l=await R(s===`direct-encryption`?t:e,n,`encrypt`);if(s===`direct-encryption`)return[l,void 0,void 0];let u=c?i??De(t):void 0;u&&Oe(u,t.cekBits);let d,f;switch(e.subtle.name){case`ECDH`:{it(l);let{apu:n,apv:i}=a;n!==void 0&&P(n,`"apu"`),i!==void 0&&P(i,`"apv"`);let c=n??at(r,`apu`),u=i??at(r,`apv`);ot(c,u);let d;d=a.epk===void 0?(await crypto.subtle.generateKey(l.algorithm,!0,[`deriveBits`])).privateKey:await R(e,a.epk,`decrypt`);let p=crypto.subtle,m=d;if(!m.extractable){if(typeof p.getPublicKey!=`function`)throw TypeError(`CryptoKey for "epk" must be extractable`);m=await p.getPublicKey(d,[])}let{x:h,y:g,crv:_,kty:v}=await p.exportKey(`jwk`,m),y=s===`direct-key-agreement`,b=await rt(l,d,y?t.alg:o,y?t.cekBits:parseInt(o.slice(-5,-2),10),c,u),x={x:h,crv:_,kty:v};if(v===`EC`&&(x.y=g),f={epk:x},n!==void 0&&(f.apu=N(n)),i!==void 0&&(f.apv=N(i)),y)return[b,void 0,f];l=b;break}case`RSA-OAEP`:he(l),$e(o,l,`encrypt`),d=new Uint8Array(await crypto.subtle.encrypt(`RSA-OAEP`,l,u));break;case`PBKDF2`:{let{p2c:e=2048,p2s:t=crypto.getRandomValues(new Uint8Array(16))}=a;l=await et(t,o,e,l),f={p2c:e,p2s:N(t)};break}case`AES-GCM`:{let e=a.iv===void 0?crypto.getRandomValues(new Uint8Array(12)):a.iv;if(!(e instanceof Uint8Array))throw TypeError(`"iv" must be an instance of Uint8Array`);let t=await Ie(Ye(o.slice(0,-2)),u,l,e,new Uint8Array);d=t.ciphertext,f={iv:N(t.iv),tag:N(t.tag)}}}if(d??=await Ze(o.slice(-6),l,u),!(d instanceof Uint8Array)||!d.byteLength)throw TypeError(`JWE key management algorithm did not produce an Encrypted Key`);return[u,d,f]}function ft(e,t){if(e.zip!==void 0&&e.zip!==`DEF`)throw new y(`Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.`);if(e.zip!==void 0&&!t?.zip)throw new x(`JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.`)}function pt(e){if(typeof globalThis[e]>`u`)throw new y(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${e} API.`)}async function mt(e,t,n=1/0){let r=e.writable.getWriter();r.write(t).catch(()=>{}),r.close().catch(()=>{});let i=[],o=0,s=e.readable.getReader();for(;;){let{value:e,done:t}=await s.read();if(t)break;if(i.push(e),o+=e.byteLength,n!==1/0&&o>n)throw new x(`Decompressed plaintext exceeded the configured limit`)}return a(...i)}async function ht(e){return pt(`CompressionStream`),mt(new CompressionStream(`deflate-raw`),e)}async function gt(e,t){return pt(`DecompressionStream`),mt(new DecompressionStream(`deflate-raw`),e,t)}function _t(e){let{aad:t,ciphertext:n,iv:r,protected:i,tag:a,unprotected:o}=e;if(r!==void 0&&(typeof r!=`string`||!r))throw new x(`JWE Initialization Vector incorrect type`);if(typeof n!=`string`)throw new x(`JWE Ciphertext missing or incorrect type`);if(a!==void 0&&(typeof a!=`string`||!a))throw new x(`JWE Authentication Tag incorrect type`);if(i!==void 0&&typeof i!=`string`)throw new x(`JWE Protected Header incorrect type`);if(t!==void 0&&(typeof t!=`string`||!t))throw new x(`JWE AAD incorrect type`);if(o!==void 0&&!F(o))throw new x(`JWE Shared Unprotected Header incorrect type`);return{aad:t,ciphertext:n,iv:r,protected:i,tag:a,unprotected:o===void 0?void 0:{...o}}}function vt(e){let t,n;try{let{header:r}=e;if(F(r)){n=r.alg;let e=Object.keys(r);e.includes(`alg`)||(n=void 0),t=Object.fromEntries(e.map(e=>[e,e===`alg`?n:r[e]]))}else t=r;let{encrypted_key:i}=e;return[{encrypted_key:i,header:t},n]}catch(e){return[void 0,n,e]}}function yt(e){let{encrypted_key:t,header:n}=e;if(t!==void 0&&typeof t!=`string`)throw new x(`JWE Encrypted Key incorrect type`);if(n!==void 0&&!F(n))throw new x(`JWE Per-Recipient Unprotected Header incorrect type`);if(e.protected===void 0&&n===void 0&&e.unprotected===void 0)throw new x(`JOSE Header missing`)}function bt(e){let{protected:t,ciphertext:n,iv:r,tag:i,aad:a}=e,o;return t!==void 0&&(o=re(t,x,`JWE Protected Header is invalid`)),[o,L(n,`ciphertext`,x),r===void 0?void 0:L(r,`iv`,x),i===void 0?void 0:L(i,`tag`,x),ne((t??``)+(a===void 0?``:`.${a}`),`aad`,x)]}function xt(e){return[e&&oe(`keyManagementAlgorithms`,e.keyManagementAlgorithms),e&&oe(`contentEncryptionAlgorithms`,e.contentEncryptionAlgorithms),e?.crit,e?.maxPBES2Count,e?.maxDecompressedLength]}async function St(e,t,n,r=bt(e)){let[i,a,o,s,c]=r,{header:l,unprotected:u,aad:d}=e,f;if(l!==void 0||u!==void 0){if(!te(i,l,u))throw new x(`JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint`);f={...i,...l,...u}}else f=i??{};let[p,m,h,g,_]=t,{encrypted_key:b}=e;ce(x,ae,h,i,f),ft(f,i);let{alg:S,enc:C}=f;if(typeof S!=`string`||!S)throw new x(`missing JWE Algorithm (alg) in JWE Header`);let w=Ge[S];if(b===``&&(!w||!K(w)))throw new x(`JWE Encrypted Key incorrect type`);let T=w?.mode===`integrated-encryption`;if(!T&&(typeof C!=`string`||!C))throw new x(`missing JWE Encryption Algorithm (enc) in JWE Header`);if(p&&!p.has(S)||!p&&S.startsWith(`PBES2`))throw new v(`"alg" (Algorithm) Header Parameter value not allowed`);let E;if(T){if(C!==void 0)throw new x(`JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption`);if(o?.byteLength)throw new x(`JWE Initialization Vector must be empty for integrated encryption`);if(s?.byteLength)throw new x(`JWE Authentication Tag must be empty for integrated encryption`)}else{if(m&&!m.has(C))throw new v(`"enc" (Encryption Algorithm) Header Parameter value not allowed`);E=Ye(C)}let D;if(b!==void 0)try{D=L(b,`encrypted_key`,x)}catch(e){if(!w||!K(w))throw e;D=new Uint8Array}let O=!1;typeof n==`function`&&(n=await n(i,e),O=!0);let k=w??G(S);K(k)&&D===void 0&&(D=new Uint8Array);let A=await R(k.mode===`direct-encryption`?E:k,n,`decrypt`),j;if(k.mode===`integrated-encryption`)j=await k.decrypt(A,D,a,c,i,f);else{let e=E,t;try{t=await ut(k,e,A,D,f,g),K(k)&&t instanceof Uint8Array&&t.byteLength<<3!==e.cekBits&&(t=De(e))}catch(n){if(n instanceof TypeError||n instanceof x||n instanceof y)throw n;t=De(e)}j=await Le(e,t,a,o,s,c)}if(f.zip===`DEF`){let e=_??25e4;if(e===0)throw new y(`JWE "zip" (Compression Algorithm) Header Parameter is not supported.`);if(e!==1/0&&(!Number.isSafeInteger(e)||e<1))throw TypeError(`maxDecompressedLength must be 0, a positive safe integer, or Infinity`);j=await gt(j,e).catch(e=>{throw e instanceof x?e:new x(`Failed to decompress plaintext`,{cause:e})})}return{plaintext:j,...i&&{protectedHeader:i},...d!==void 0&&{additionalAuthenticatedData:L(d,`aad`,x)},...u&&{sharedUnprotectedHeader:u},...l&&{unprotectedHeader:l},...O&&{key:A}}}async function Ct(e,t,r){if(e instanceof Uint8Array&&(e=n.decode(e)),typeof e!=`string`)throw new x(`Compact JWE must be a string or Uint8Array`);let{0:i,1:a,2:o,3:s,4:c,length:l}=e.split(`.`);if(l!==5)throw new x(`Invalid Compact JWE`);return St({ciphertext:s,iv:o||void 0,protected:i,tag:c||void 0,encrypted_key:a||void 0},t,r)}async function wt(e,t,n){return Ct(e,xt(n),t)}async function Tt(e,t,n){if(!F(e))throw new x(`Flattened JWE must be an object`);let r=_t(e),[i,,a]=vt(e);if(!i)throw a;let o={...r,...i};return yt(o),St(o,xt(n),t)}async function Et(e,t,n){if(!F(e))throw new x(`General JWE must be an object`);let r=e.recipients;if(!Array.isArray(r))throw new x(`JWE Recipients missing or incorrect type`);let i=Array.from(r);if(!i.every(F))throw new x(`JWE Recipients missing or incorrect type`);if(!i.length)throw new x(`JWE Recipients has no members`);let a,o,s;try{a=xt(n),o=_t(e),s=bt(o)}catch{throw new b}let c=i.map(e=>vt(e));if(i.length>1)for(let[,e]of c){let t=s[0]?.alg??e??o.unprotected?.alg,n=typeof t==`string`?Ge[t]:void 0;if(n&&!K(n))throw new x(`"${t}" alg may only have a single recipient`)}for(let[e]of c)if(e)try{let n={...o,...e};return yt(n),await St(n,a,t,s)}catch{}throw new b}function Dt(e,t,n){if(!te(e,t,n))throw new x(`JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint`)}function Ot(e,t,n=!1){if(!e[1]&&!e[2]&&!e[3])throw new x(`either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()`);t!==void 0&&(e[8]=t?.crit);let[,r,i,a,o,s,c,l,u]=e;if(o!==void 0&&P(o,`JWE Additional Authenticated Data`),s!==void 0&&P(s,`JWE Content Encryption Key`),c!==void 0&&P(c,`JWE Initialization Vector`),!n&&r!==void 0&&(r=ue(x,r)[0],e[1]=r),i!==void 0&&(i=ue(x,i)[0],e[2]=i),!n&&a!==void 0&&(a=ue(x,a)[0],e[3]=a),l!==void 0&&!F(l))throw TypeError(`JWE Key Management Parameters must be an object`);Dt(r,i,a);let d={...r,...i,...a};se(x,r),ce(x,ae,u,r,d),ft(d,r);let{alg:f,enc:p}=d;if(typeof f!=`string`||!f)throw new x(`JWE "alg" (Algorithm) Header Parameter missing or invalid`);let m=Ge[f];if(m?.mode===`integrated-encryption`){if(p!==void 0)throw new x(`JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption`);if(s!==void 0)throw TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${f}`);if(c!==void 0)throw TypeError(`setInitializationVector cannot be called with JWE "alg" (Algorithm) Header ${f}`);return[d,void 0,m]}if(typeof p!=`string`||!p)throw new x(`JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid`);return[d,Ye(p),m]}async function kt(e,t,n){let[r,i,a]=t,[o,s,c,l,d,f,p,m,,h]=e,g=s,_=c,v=a??G(r.alg),y,b,S;v.mode===`integrated-encryption`?S=await R(v,n,`encrypt`):[S,y,b]=await dt(v,i,n,r,f,m),b&&(h?_=_?{..._,...b}:b:g=g?{...g,...b}:b,Dt(g,_,l));let C=g?N(JSON.stringify(g)):``,w=d?.byteLength?N(d):void 0,T=u(w?`${C}.${w}`:C),E=o;r.zip===`DEF`&&(E=await ht(E).catch(e=>{throw new x(`Failed to compress plaintext`,{cause:e})}));let D,O,k;v.mode===`integrated-encryption`?[y,D]=await v.encrypt(S,E,T,g,r,m):{ciphertext:D,tag:O,iv:k}=await Ie(i,E,S,p,T);let A={ciphertext:N(D)};return k&&(A.iv=N(k)),O&&(A.tag=N(O)),y?.byteLength&&(A.encrypted_key=N(y)),w&&(A.aad=w),g&&(A.protected=C),l&&(A.unprotected=l),_&&(A.header=_),A}async function At(e,t,n){return kt(e,Ot(e,n),t)}function jt(e){return[e.protected,e.encrypted_key,e.iv,e.ciphertext,e.tag].join(`.`)}var Mt=class{#e;state;constructor(e,t,n){this.#e=e,this.state=[void 0,void 0,t,n]}setUnprotectedHeader(e){return I(this.state[0],`setUnprotectedHeader`),this.state[0]=e,this}setKeyManagementParameters(e){return I(this.state[1],`setKeyManagementParameters`),this.state[1]=e,this}addRecipient(...e){return this.#e.addRecipient(...e)}encrypt(...e){return this.#e.encrypt(...e)}done(){return this.#e}},Nt=class{#e;#t=[];#n;#r;#i;constructor(e){this.#e=e}addRecipient(e,t){let n=new Mt(this,e,t?.crit);return this.#t.push(n),n}setProtectedHeader(e){return I(this.#n,`setProtectedHeader`),this.#n=e,this}setSharedUnprotectedHeader(e){return I(this.#r,`setSharedUnprotectedHeader`),this.#r=e,this}setAdditionalAuthenticatedData(e){return this.#i=e,this}async encrypt(){if(!this.#t.length)throw new x(`at least one recipient must be added`);P(this.#e,`plaintext`);let e=this.#t.length>1,t,n=this.#n,r=this.#r,i=[];for(let a of this.#t){let[o,s,c,l]=a.state,u=[this.#e,n,o,r,this.#i,void 0,void 0,s,l,e],d=Ot(u,void 0,i.length>0);i.length||(n=u[1],r=u[3]),i.push([u,d,c]);let[{alg:f,enc:p},,m]=d;if(e&&m&&!K(m))throw new x(`"${f}" alg may only have a single recipient`);if(!t)t=p;else if(t!==p)throw new x(`JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients`)}for(let[,e]of i)e[2]??=G(e[0].alg);let[a,o,s]=i[0],c=e?De(o[1]):void 0;a[5]=c;let{encrypted_key:l,header:u,...d}=await kt(a,o,s),f={...d,recipients:[{}]};l&&(f.recipients[0].encrypted_key=l),u&&(f.recipients[0].header=u);for(let e=1;e<i.length;e++){let[t,[n,r,a],o]=i[e],s=t[2],[,l,u]=await dt(a,r,o,n,c,t[7]),d={encrypted_key:N(l)};if(s||u){let e={...s,...u};u&&Dt(t[1],e,t[3]),d.header=e}f.recipients.push(d)}return f}},Pt=[[`verify`],[`sign`]];function Ft(e){let t={name:`HMAC`,hash:`SHA-${e}`};return{kty:[`oct`],secret:!0,subtle:t,signing:t,usages:Pt}}function q(e,t){let n={name:t?`RSA-PSS`:`RSASSA-PKCS1-v1_5`,hash:`SHA-${e}`};return{kty:[`RSA`],subtle:n,signing:t?{...n,saltLength:t}:n,usages:Pt,minRsaBits:2048}}function It(e,t){return{kty:[`EC`],crv:e,subtle:{name:`ECDSA`,namedCurve:e},signing:{name:`ECDSA`,hash:`SHA-${t}`},usages:Pt}}function Lt(){let e={name:`Ed25519`};return{kty:[`OKP`],crv:`Ed25519`,subtle:e,signing:e,usages:Pt}}function Rt(e){let t={name:`ML-DSA-${e}`};return{kty:[`AKP`],subtle:t,signing:t,usages:Pt}}var zt=Re({HS256:Ft(256),HS384:Ft(384),HS512:Ft(512),RS256:q(256),RS384:q(384),RS512:q(512),PS256:q(256,32),PS384:q(384,48),PS512:q(512,64),ES256:It(`P-256`,256),ES384:It(`P-384`,384),ES512:It(`P-521`,512),EdDSA:Lt(),Ed25519:Lt(),"ML-DSA-44":Rt(44),"ML-DSA-65":Rt(65),"ML-DSA-87":Rt(87)});function Bt(e){let t=typeof e==`string`?zt[e]:void 0;if(!t)throw new y(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}function Vt(e,t){let n=e.protected,r=e.header,i=F(r)?{...r}:r,a=t?t[0]:e.payload;!t&&a instanceof Uint8Array&&(a=new Uint8Array(a));let o=e.signature,s={payload:a,signature:o};if(n!==void 0&&(s.protected=n),r!==void 0&&(s.header=i),n===void 0&&i===void 0)throw new S(`Flattened JWS must have either of the "protected" or "header" members`);if(n!==void 0&&typeof n!=`string`)throw new S(`JWS Protected Header incorrect type`);if(a===void 0)throw new S(`JWS Payload missing`);if(typeof o!=`string`)throw new S(`JWS Signature missing or incorrect type`);if(i!==void 0&&!F(i))throw new S(`JWS Unprotected Header incorrect type`);return s}function Ht(e){return[e&&oe(`algorithms`,e.algorithms),e?.crit]}function Ut(e){return e===void 0?{}:re(e,S,`JWS Protected Header is invalid`)}function Wt(e){let n=/[\p{Cs}\p{Cn}]/u.exec(e)?.[0];if(n!==void 0)throw new S(/\p{Cs}/u.test(n)?`JWS Payload must be a well-formed Unicode string`:`JWS Payload must not contain unassigned Unicode code points`);return t.encode(e)}function Gt(e){try{return u(e)}catch{throw new S(`JWS Compact Serialization payload must use only ASCII characters`)}}async function Kt(e,t,n,r,i){let{protected:o,header:s,payload:c}=e,l=i??Ut(o);if(!te(l,s))throw new S(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let d={...l,...s},f=le(l,ce(S,ie,t[1],l,d)),{alg:p}=d;if(typeof p!=`string`||!p)throw new S(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);if(t[0]&&!t[0].has(p))throw new v(`"alg" (Algorithm) Header Parameter value not allowed`);if(f){if(typeof c!=`string`)throw new S(`JWS Payload must be a string`)}else if(typeof c!=`string`&&!(c instanceof Uint8Array))throw new S(`JWS Payload must be a string or an Uint8Array instance`);let m=f||typeof c!=`string`?c:r(c),h=!1;typeof n==`function`&&(n=await n(l,e),h=!0);let g=Bt(p),_=a(o===void 0?new Uint8Array:u(o),u(`.`),typeof m==`string`?t[2]??=ne(m,`payload`,S):m),y=L(e.signature,`signature`,S),b=await R(g,n,`verify`),x=await H(b,g.subtle,`verify`);g.minRsaBits&&Se(g.alg,x);let C=!1;try{C=await crypto.subtle.verify(g.signing,x,y,_)}catch{}if(!C)throw new k;let w={payload:typeof m==`string`?L(m,`payload`,S):m};return o!==void 0&&(w.protectedHeader=l),s!==void 0&&(w.unprotectedHeader=s),h?[{...w,key:b},f]:[w,f]}async function qt(e,t,r){if(e instanceof Uint8Array&&(e=n.decode(e)),typeof e!=`string`)throw new S(`Compact JWS must be a string or Uint8Array`);let{0:i,1:a,2:o,length:s}=e.split(`.`);if(s!==3)throw new S(`Invalid Compact JWS`);return Kt({payload:a,protected:i,signature:o},t,r,Gt)}async function Jt(e,t,n){let[r]=await qt(e,Ht(n),t);return r}async function Yt(e,t,n){if(!F(e))throw new S(`Flattened JWS must be an object`);let[r]=await Kt(Vt(e),Ht(n),t,Wt);return r}function Xt(e,t){try{let n=Vt(e,[t]),r=Ut(n.protected),{b64:i,crit:a}=r;return[n,r,Array.isArray(a)&&a.includes(`b64`)?typeof i==`boolean`?i?1:2:0:1]}catch{return}}async function Zt(e,t,n){if(!F(e))throw new S(`General JWS must be an object`);let{signatures:r,payload:i}=e;if(!Array.isArray(r))throw new S(`JWS Signatures missing or incorrect type`);let a=Array.from(r);if(!a.every(F))throw new S(`JWS Signatures missing or incorrect type`);let o;try{if(i===void 0)throw Error();o=Ht(n)}catch{throw new k}let s=i instanceof Uint8Array?new Uint8Array(i):i,c=a.map(e=>Xt(e,s)).filter(e=>e!==void 0),l=0;for(let[,,e]of c)if(l|=e,l===3)throw new S(`inconsistent use of JWS Unencoded Payload (RFC7797)`);for(let e of c)try{let[n]=await Kt(e[0],o,t,Wt,e[1]);return n}catch{}throw new k}var Qt=e=>Math.floor(e.getTime()/1e3),$t={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},en=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,J=`check_failed`;function tn(){throw TypeError(`Invalid time period format`)}function nn(e){typeof e!=`string`&&tn();let t=en.exec(e);(!t||t[4]&&t[1])&&tn();let n=parseFloat(t[2]),r=Math.round(n*$t[t[3][0].toLowerCase()]);return Number.isFinite(r)||tn(),t[1]===`-`||t[4]===`ago`?-r:r}function Y(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}function rn(e,t){if(typeof t!=`string`)throw TypeError(`"${e}" claim must be a string`)}function an(e){if(typeof e!=`string`&&(!Array.isArray(e)||Array.from(e).some(e=>typeof e!=`string`)))throw TypeError(`"aud" claim must be a string or an array of strings`)}function on(e,t){return typeof e==`number`?Y(t,e):e instanceof Date?Y(t,Qt(e)):Qt(new Date)+nn(e)}var sn=e=>{let t=e.toLowerCase();return e.includes(`/`)?t:`application/${t}`},cn=(e,t)=>typeof e==`string`?t.includes(e):Array.isArray(e)?t.some(t=>e.includes(t)):!1;function ln(e,t,n=!1){let r=e[t];if(r!==void 0||n){if(typeof r!=`number`)throw new g(`"${t}" claim must be a number`,e,t,`invalid`);return r}}function un(e,t){throw new g(`unexpected "${t}" claim value`,e,t,J)}function dn(e,t,n={}){let i;try{i=JSON.parse(r.decode(t))}catch{}if(!F(i))throw new C(`JWT Claims Set must be a top-level JSON object`);let{typ:a}=n;if(a!==void 0&&(typeof e.typ!=`string`||sn(e.typ)!==sn(a)))throw new g(`unexpected "typ" JWT header value`,i,`typ`,J);let{requiredClaims:o=[],issuer:s,subject:c,audience:l,maxTokenAge:u}=n,d=[...o];u!==void 0&&d.push(`iat`),l!==void 0&&d.push(`aud`),c!==void 0&&d.push(`sub`),s!==void 0&&d.push(`iss`);for(let e of new Set(d.reverse()))if(!Object.hasOwn(i,e))throw new g(`missing required "${e}" claim`,i,e,`missing`);s!==void 0&&!(Array.isArray(s)?s:[s]).includes(i.iss)&&un(i,`iss`),c!==void 0&&i.sub!==c&&un(i,`sub`),l!==void 0&&!cn(i.aud,typeof l==`string`?[l]:l)&&un(i,`aud`);let{clockTolerance:f}=n,p=0;if(typeof f==`string`)p=nn(f);else if(f!==void 0){if(typeof f!=`number`)throw TypeError(`Invalid clockTolerance option type`);p=f}Y(`clockTolerance option`,p);let{currentDate:m}=n,h=Y(`currentDate option`,Qt(m===void 0?new Date:m)),v=ln(i,`iat`,u!==void 0),y=ln(i,`nbf`);if(y!==void 0&&y>h+p)throw new g(`"nbf" claim timestamp check failed`,i,`nbf`,J);let b=ln(i,`exp`);if(b!==void 0&&b<=h-p)throw new _(`"exp" claim timestamp check failed`,i,`exp`,J);if(u!==void 0){let e=h-v,t=Y(`maxTokenAge option`,typeof u==`number`?u:nn(u));if(e-p>t)throw new _(`"iat" claim timestamp check failed (too far in the past)`,i,`iat`,J);if(e<-p)throw new g(`"iat" claim timestamp check failed (it should be in the past)`,i,`iat`,J)}return i}var fn;function X(e){return fn.get(e)}function pn(e){let n=X(e);for(let e of[`iat`,`nbf`,`exp`]){let t=n[e];if(typeof t==`number`&&!Number.isFinite(t))throw TypeError(`"${e}" claim must be a finite number`)}return t.encode(JSON.stringify(n))}function mn(e,t){return X(e)[t]}var hn=class{constructor(e={}){if(!F(e))throw TypeError(`JWT Claims Set MUST be an object`);(fn||=new WeakMap).set(this,structuredClone(e))}setIssuer(e){return rn(`iss`,e),X(this).iss=e,this}setSubject(e){return rn(`sub`,e),X(this).sub=e,this}setAudience(e){return an(e),X(this).aud=e,this}setJti(e){return rn(`jti`,e),X(this).jti=e,this}setNotBefore(e){return X(this).nbf=on(e,`setNotBefore`),this}setExpirationTime(e){return X(this).exp=on(e,`setExpirationTime`),this}setIssuedAt(e){let t=X(this);return t.iat=e===void 0?Qt(new Date):typeof e==`string`?Y(`setIssuedAt`,Qt(new Date)+nn(e)):on(e,`setIssuedAt`),this}};async function gn(e,t,n){let[r,i]=await qt(e,Ht(n),t);if(!i)throw new C(`JWTs MUST NOT use unencoded payload`);let a=dn(r.protectedHeader,r.payload,n);return{...r,payload:a}}async function _n(e,t,n){let{plaintext:r,...i}=await Ct(e,xt(n),t),{protectedHeader:a}=i,o=dn(a,r,n);for(let e of[`iss`,`sub`,`aud`])if(a[e]!==void 0&&(e===`aud`?JSON.stringify(a.aud)!==JSON.stringify(o.aud):a[e]!==o[e]))throw new g(`replicated "${e}" claim header parameter mismatch`,o,e,`mismatch`);return{payload:o,...i}}var vn=class{#e;constructor(e){P(e,`plaintext`),this.#e=[e]}setContentEncryptionKey(e){return I(this.#e[5],`setContentEncryptionKey`),this.#e[5]=e,this}setInitializationVector(e){return I(this.#e[6],`setInitializationVector`),this.#e[6]=e,this}setProtectedHeader(e){return I(this.#e[1],`setProtectedHeader`),this.#e[1]=e,this}setKeyManagementParameters(e){return I(this.#e[7],`setKeyManagementParameters`),this.#e[7]=e,this}async encrypt(e,t){return jt(await At([...this.#e],e,t))}},yn=class{#e;constructor(e){P(e,`plaintext`),this.#e=[e]}setKeyManagementParameters(e){return I(this.#e[7],`setKeyManagementParameters`),this.#e[7]=e,this}setProtectedHeader(e){return I(this.#e[1],`setProtectedHeader`),this.#e[1]=e,this}setSharedUnprotectedHeader(e){return I(this.#e[3],`setSharedUnprotectedHeader`),this.#e[3]=e,this}setUnprotectedHeader(e){return I(this.#e[2],`setUnprotectedHeader`),this.#e[2]=e,this}setAdditionalAuthenticatedData(e){return this.#e[4]=e,this}setContentEncryptionKey(e){return I(this.#e[5],`setContentEncryptionKey`),this.#e[5]=e,this}setInitializationVector(e){return I(this.#e[6],`setInitializationVector`),this.#e[6]=e,this}async encrypt(e,t){return At([...this.#e],e,t)}};async function bn(e,n,r){let[i,o,s,c]=e,l=``;if(o!==void 0){let e=ue(S,o);o=e[0],l=N(e[1])}if(s!==void 0&&(s=ue(S,s)[0]),!o&&!s)throw new S(`either setProtectedHeader or setUnprotectedHeader must be called before #sign()`);if(!te(o,s))throw new S(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let d={...o,...s};se(S,o);let f=le(o,ce(S,ie,c,o,d));f||r?.();let{alg:p}=d;if(typeof p!=`string`||!p)throw new S(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);let m=Bt(p),h=``,g=i,_;if(f){let n=e[4];n?(h=n[0]??=N(i),g=n[1]??=u(h)):(h=N(i),_=t.encode(`${l}.${h}`))}_??=a(u(l),u(`.`),g);let v=await H(await R(m,n,`sign`),m.subtle,`sign`);m.minRsaBits&&Se(m.alg,v);let y={signature:N(new Uint8Array(await crypto.subtle.sign(m.signing,v,_))),payload:h};return o&&(y.protected=l),s&&(y.header=s),[y,f]}async function xn(e,t,n,r,i){let[a]=await bn([e,t,void 0,n],r,i);return`${a.protected}.${a.payload}.${a.signature}`}var Sn=class{#e;#t;constructor(e){P(e,`payload`),this.#e=e}setProtectedHeader(e){return I(this.#t,`setProtectedHeader`),this.#t=e,this}async sign(e,t){return xn(this.#e,this.#t,t?.crit,e,()=>{throw TypeError(`use the flattened module for creating JWS with b64: false`)})}},Cn=class{#e;constructor(e){P(e,`payload`),this.#e=[e]}setProtectedHeader(e){return I(this.#e[1],`setProtectedHeader`),this.#e[1]=e,this}setUnprotectedHeader(e){return I(this.#e[2],`setUnprotectedHeader`),this.#e[2]=e,this}async sign(e,t){let n=[...this.#e];n[3]=t?.crit;let[r]=await bn(n,e);return r}},wn=class{#e;state;constructor(e,t,n){this.#e=e,this.state=[void 0,void 0,t,n?.crit]}setProtectedHeader(e){return I(this.state[0],`setProtectedHeader`),this.state[0]=e,this}setUnprotectedHeader(e){return I(this.state[1],`setUnprotectedHeader`),this.state[1]=e,this}addSignature(...e){return this.#e.addSignature(...e)}sign(...e){return this.#e.sign(...e)}done(){return this.#e}},Tn=class{#e;#t=[];constructor(e){this.#e=e}addSignature(e,t){let n=new wn(this,e,t);return this.#t.push(n),n}async sign(){if(!this.#t.length)throw new S(`at least one signature must be added`);P(this.#e,`payload`);let e={signatures:[],payload:``},t=[],n;for(let r of this.#t){let[i,a,o,s]=r.state,[{payload:c,...l},u]=await bn([this.#e,i,a,s,t],o);if(n===void 0)n=u,e.payload=c;else if(n!==u)throw new S(`inconsistent use of JWS Unencoded Payload (RFC7797)`);e.signatures.push(l)}return e}},En=hn,Dn=class extends En{#e;setProtectedHeader(e){return I(this.#e,`setProtectedHeader`),this.#e=e,this}async sign(e,t){return xn(pn(this),this.#e,t?.crit,e,()=>{throw new C(`JWTs MUST NOT use unencoded payload`)})}},On=hn,kn=class extends On{#e=[void 0];#t;#n;#r;setProtectedHeader(e){return I(this.#e[1],`setProtectedHeader`),this.#e[1]=e,this}setKeyManagementParameters(e){return I(this.#e[7],`setKeyManagementParameters`),this.#e[7]=e,this}setContentEncryptionKey(e){return I(this.#e[5],`setContentEncryptionKey`),this.#e[5]=e,this}setInitializationVector(e){return I(this.#e[6],`setInitializationVector`),this.#e[6]=e,this}replicateIssuerAsHeader(){return this.#t=!0,this}replicateSubjectAsHeader(){return this.#n=!0,this}replicateAudienceAsHeader(){return this.#r=!0,this}async encrypt(e,t){let n=pn(this);this.#e[1]&&(this.#t||this.#n||this.#r)&&(this.#e[1]={...this.#e[1],iss:this.#t?mn(this,`iss`):void 0,sub:this.#n?mn(this,`sub`):void 0,aud:this.#r?mn(this,`aud`):void 0});let r=[...this.#e];return r[0]=n,jt(await At(r,e,t))}},An=`"alg" (Algorithm)`;function jn(e=`JWK "alg" (Algorithm) Parameter`){throw new y(`Invalid or unsupported ${e} value`)}function Mn(e,t){return(typeof e==`string`?zt[e]??Ge[e]:void 0)??jn(t)}var Nn=(e,t)=>`-----BEGIN ${t}-----
2
+ ${(e.match(/.{1,64}/g)||[]).join(`
3
+ `)}
4
+ -----END ${t}-----`,Pn=async(e,t,n)=>{if(ge(n)){if(n.type!==e)throw TypeError(`key is not a ${e} key`);return n.export({format:`pem`,type:t})}if(!z(n))throw TypeError(B(n,`CryptoKey`,`KeyObject`));if(!n.extractable)throw TypeError(`CryptoKey is not extractable`);if(n.type!==e)throw TypeError(`key is not a ${e} key`);return Nn(d(new Uint8Array(await crypto.subtle.exportKey(t,n))),`${e.toUpperCase()} KEY`)},Fn=e=>Pn(`public`,`spki`,e),In=e=>Pn(`private`,`pkcs8`,e),Ln=(e,t)=>{if(e.byteLength!==t.length)return!1;for(let n=0;n<e.byteLength;n++)if(e[n]!==t[n])return!1;return!0},Rn=e=>({data:e,pos:0}),zn=e=>{let t=e.data[e.pos++];if(t===void 0)throw Error(`Unexpected end of ASN.1 input`);return t},Z=e=>{let t=zn(e);if(t&128){let n=t&127,r=0;for(let t=0;t<n;t++)r=r<<8|zn(e);return r}return t},Bn=(e,t=1)=>{for(;t-->0;){e.pos++;let t=Z(e);e.pos+=t}},Q=(e,t,n)=>{if(zn(e)!==t)throw Error(n)},Vn=(e,t)=>{if(t<0||e.pos+t>e.data.length)throw Error(`Unexpected end of ASN.1 input`);let n=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,n},Hn=e=>(Q(e,6,`Expected algorithm OID`),Vn(e,Z(e)));function Un(e,t){if(Q(e,48,`Invalid ${t===`spki`?`SPKI`:`PKCS#8`} structure`),Z(e),t===`pkcs8`){Q(e,2,`Expected version field`);let t=Z(e);e.pos+=t}Q(e,48,`Expected algorithm identifier`),Z(e)}var Wn=e=>{let t=Hn(e);if(Ln(t,[43,101,110]))return`X25519`;if(!Ln(t,[42,134,72,206,61,2,1]))throw Error(`Unsupported key algorithm`);Q(e,6,`Expected curve OID`);let n=Vn(e,Z(e));if(Ln(n,[42,134,72,206,61,3,1,7]))return`P-256`;if(Ln(n,[43,129,4,0,34]))return`P-384`;if(Ln(n,[43,129,4,0,35]))return`P-521`;throw Error(`Unsupported named curve`)},Gn=async(e,t,n,r)=>{let i=Ee(r?.extractable),a=Mn(n,An);a.secret&&jn(`"alg" (Algorithm)`);let o=e===`spki`,s;if(a.resolve)try{let n=Rn(t);Un(n,e),s=a.resolve({crv:Wn(n)})}catch{throw new y(`Invalid or unsupported key format`)}else s=a.subtle;return crypto.subtle.importKey(e,t,s,i??o,a.usages[+!o])},Kn=(e,t)=>f(e.replace(t,``)),qn=(e,t,n)=>Gn(`pkcs8`,Kn(e,/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g),t,n),Jn=(e,t,n)=>Gn(`spki`,Kn(e,/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g),t,n);function Yn(e){let t=Rn(e);Q(t,48,`Invalid certificate structure`);let n=Z(t);if(n<0||t.pos+n>t.data.length)throw Error(`Unexpected end of ASN.1 input`);Q(t,48,`Invalid tbsCertificate structure`),Z(t),e[t.pos]===160?Bn(t,6):Bn(t,5);let r=t.pos;Q(t,48,`Invalid SPKI structure`);let i=Z(t);return e.subarray(r,r+i+(t.pos-r))}var Xn=(e,t,n)=>{let r;try{r=Yn(Kn(e,/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g))}catch(e){throw TypeError(`Failed to parse the X.509 certificate`,{cause:e})}return Gn(`spki`,r,t,n)};function Zn(e){return Fn(e)}function Qn(e){return In(e)}async function $n(e){if(ge(e)){if(e.type===`secret`)e=e.export();else return e.export({format:`jwk`})}if(e instanceof Uint8Array)return{kty:`oct`,k:N(e)};if(!z(e))throw TypeError(B(e,`CryptoKey`,`KeyObject`,`Uint8Array`));if(!e.extractable)throw TypeError(`non-extractable CryptoKey cannot be exported as a JWK`);let t=await crypto.subtle.exportKey(`jwk`,e);delete t.ext,delete t.key_ops,delete t.use,t.kty!==`AKP`&&delete t.alg;for(let e of Object.keys(t))t[e]===void 0&&delete t[e];return t}var $=(e,t)=>{if(typeof e!=`string`||!e)throw new w(`${t} missing or invalid`)};async function er(e,t){let n;if(F(e)){if(n=we(e),typeof n.kty!=`string`)throw TypeError(B(e,`CryptoKey`,`KeyObject`,`JSON Web Key`))}else if(_e(e))n=we(await $n(e));else throw TypeError(B(e,`CryptoKey`,`KeyObject`,`JSON Web Key`));if(t??=`sha256`,t!==`sha256`&&t!==`sha384`&&t!==`sha512`)throw TypeError(`digestAlgorithm must one of "sha256", "sha384", or "sha512"`);let r;switch(n.kty){case`AKP`:$(n.alg,`"alg" (Algorithm) Parameter`),$(n.pub,`"pub" (Public key) Parameter`),r={alg:n.alg,kty:n.kty,pub:n.pub};break;case`EC`:$(n.crv,`"crv" (Curve) Parameter`),$(n.x,`"x" (X Coordinate) Parameter`),$(n.y,`"y" (Y Coordinate) Parameter`),r={crv:n.crv,kty:n.kty,x:n.x,y:n.y};break;case`OKP`:$(n.crv,`"crv" (Subtype of Key Pair) Parameter`),$(n.x,`"x" (Public Key) Parameter`),r={crv:n.crv,kty:n.kty,x:n.x};break;case`RSA`:$(n.e,`"e" (Exponent) Parameter`),$(n.n,`"n" (Modulus) Parameter`),r={e:n.e,kty:n.kty,n:n.n};break;case`oct`:if(typeof n.k!=`string`)throw new w(`"k" (Key Value) Parameter missing or invalid`);r={k:n.k,kty:n.kty};break;default:throw new y(`"kty" (Key Type) Parameter missing or unsupported`)}let i=u(JSON.stringify(r));return N(await p(t,i))}async function tr(e,t){t??=`sha256`;let n=await er(e,t);return`urn:ietf:params:oauth:jwk-thumbprint:sha-${t.slice(-3)}:${n}`}async function nr(e,t){let n={...e,...t?.header};if(!F(n.jwk))throw new S(`"jwk" (JSON Web Key) Header Parameter must be a JSON object`);let r;try{r=Te(n.jwk)}catch(e){throw new S(`Invalid Embedded JWK`,{cause:e})}let i=Bt(n.alg);if(r.use!==void 0&&r.use!==`sig`)throw new S(`Invalid Embedded JWK, its "use" must be "sig" when present`);if(r.alg!==void 0&&r.alg!==i.alg)throw new S(`Invalid Embedded JWK, its "alg" must be "${i.alg}" when present`);let a=await V(i,r,!0);if(a.type!==`public`)throw new S(`"jwk" (JSON Web Key) Header Parameter must be a public key`);return a}function rr(e,t,n,r){let{kty:i,key_ops:a,ext:o,kid:s,alg:c,use:l,crv:u}=e;return(o===void 0||typeof o==`boolean`)&&(a===void 0||Array.isArray(a)&&a.every((e,t)=>typeof e==`string`&&a.indexOf(e)===t)&&a.includes(`verify`))&&t.kty.includes(i)&&(r===void 0||typeof r==`string`&&r===s)&&(c===void 0?i!==`AKP`:n===c)&&(l===void 0||l===`sig`)&&(!t.crv||u===t.crv)}async function ir(e,t,n){let r=e.get(t)||e.set(t,{}).get(t),{alg:i}=n;if(r[i]===void 0){let e=V(n,t,!0).then(e=>{if(e.type!==`public`)throw new T(`JSON Web Key Set members must be public keys`);return r[i]=e,e}).catch(t=>{throw r[i]===e&&delete r[i],t});r[i]=e}return r[i]}function ar(e){let t;try{t=structuredClone(e)}catch{}if(!ee(t))throw new T(`JSON Web Key Set malformed`);let n=t.keys.map(e=>{let t=we(e);return Array.isArray(t.key_ops)&&(t.key_ops=[...t.key_ops]),t}),r=new WeakMap;return Object.defineProperty(async(e,i)=>{let{alg:a,kid:o}={...e,...i?.header},s=typeof a==`string`?zt[a]:void 0;if(!s||s.secret)throw new y(`Unsupported "alg" value for a JSON Web Key Set`);let c=t.keys.filter((e,t)=>rr(n[t],s,a,o)),{0:l,length:u}=c;if(!u)throw new E;if(u!==1){let e=new D;throw e[Symbol.asyncIterator]=async function*(){for(let e of c)try{yield await ir(r,e,s)}catch{}},e}return ir(r,l,s)},"jwks",{value:()=>structuredClone(t)})}function or(){return typeof WebSocketPair<`u`||typeof navigator<`u`&&navigator.userAgent===`Cloudflare-Workers`||typeof EdgeRuntime<`u`&&EdgeRuntime===`vercel`}var sr;typeof navigator<`u`&&navigator.userAgent?.startsWith?.(`Mozilla/5.0 `)||(sr=`jose/v6.2.12`);var cr=Symbol();async function lr(e,t,n,r=fetch){let i=await r(e,{method:`GET`,signal:n,redirect:`manual`,headers:t}).catch(e=>{throw e.name===`TimeoutError`?new O:e});if(i.status!==200)throw new h(`Expected 200 OK from the JSON Web Key Set HTTP response`);try{return await i.json()}catch{throw new h(`Failed to parse the JSON Web Key Set HTTP response as JSON`)}}var ur=Symbol();function dr(e,t){return Number.isFinite(e)&&Date.now()<e+t}function fr(e,t,n){if(Number.isNaN(e))throw TypeError(`"${n}" option must not be NaN`);return typeof e==`number`?e:t}function pr(e,t){if(!(e instanceof URL))throw TypeError(`url must be an instance of URL`);let n=new URL(e.href).href,r=t??{},i=r.timeoutDuration;if(typeof i==`number`&&(!Number.isInteger(i)||i<0))throw TypeError(`"timeoutDuration" option must be a non-negative integer`);let a=typeof i==`number`?i:5e3,o=fr(r.cooldownDuration,3e4,`cooldownDuration`),s=fr(r.cacheMaxAge,6e5,`cacheMaxAge`),c=new Headers(r.headers);sr&&!c.has(`User-Agent`)&&c.set(`User-Agent`,sr),c.has(`accept`)||c.set(`accept`,`application/json, application/jwk-set+json`);let l=r[cr],u=r[ur],d,f,p=0,m=0,h;if(u&&typeof u==`object`){let{uat:e,jwks:t}=u;dr(e,s)&&ee(t)&&(d=e,h=ar(t))}let g=async()=>{if(f&&or()&&(f=void 0),!f){let e=++p,t=f=lr(n,c,AbortSignal.timeout(a),l).then(t=>{let n=ar(t);if(e<=m)return;h=n;let r=Date.now();u&&(u.uat=r,u.jwks=t),d=r,m=e}).finally(()=>{f===t&&(f=void 0)})}await f};return Object.defineProperties(async(e,t)=>{h&&dr(d,s)||await g();try{return await h(e,t)}catch(n){if(n instanceof E&&!dr(d,o))return await g(),h(e,t);throw n}},{coolingDown:{get:()=>dr(d,o),enumerable:!0},fresh:{get:()=>dr(d,s),enumerable:!0},reload:{value:g,enumerable:!0},reloading:{get:()=>!!f,enumerable:!0},jwks:{value:()=>h?.jwks(),enumerable:!0}})}var mr=hn,hr=class extends mr{encode(){return`${N(JSON.stringify({alg:`none`}))}.${N(pn(this))}.`}static decode(e,t){if(typeof e!=`string`)throw new C(`Unsecured JWT must be a string`);let{0:n,1:r,2:i,length:a}=e.split(`.`);if(a!==3||i!==``)throw new C(`Invalid Unsecured JWT`);let o,s;try{o=re(n,S,`JWS Protected Header is invalid`);let e=ce(S,ie,void 0,o,o);s=le(o,e)}catch(e){throw e instanceof S?new C(`Invalid Unsecured JWT`,{cause:e}):e}if(o.alg!==`none`)throw new C(`Invalid Unsecured JWT`);if(!s)throw new C(`JWTs MUST NOT use unencoded payload`);return{payload:dn(o,L(r,`payload`,C),t),header:o}}};async function gr(e,t,n){if(typeof e!=`string`||e.indexOf(`-----BEGIN PUBLIC KEY-----`)!==0)throw TypeError(`"spki" must be SPKI formatted string`);return Jn(e,t,n)}async function _r(e,t,n){if(typeof e!=`string`||e.indexOf(`-----BEGIN CERTIFICATE-----`)!==0)throw TypeError(`"x509" must be X.509 formatted string`);return Xn(e,t,n)}async function vr(e,t,n){if(typeof e!=`string`||e.indexOf(`-----BEGIN PRIVATE KEY-----`)!==0)throw TypeError(`"pkcs8" must be PKCS#8 formatted string`);return qn(e,t,n)}async function yr(e,t,n){if(!F(e))throw TypeError(`JWK must be an object`);let r=Te(e),i=Ee(n?.extractable),{alg:a}=r;if(t??=a,r.kty!==`oct`&&!t)throw TypeError(`"alg" argument is required when "jwk.alg" is not present`);switch(r.kty){case`oct`:if(typeof r.k!=`string`)throw TypeError(`missing "k" (Key Value) Parameter value`);return M(r.k);case`AKP`:if(typeof a!=`string`||!a)throw TypeError(`missing "alg" (Algorithm) Parameter value`);if(t!==a)throw TypeError(`JWK alg and alg option value mismatch`);return V(Mn(t),r,i);case`RSA`:case`EC`:case`OKP`:return V(Mn(t),r,i);default:throw new y(`Unsupported "kty" (Key Type) Parameter value`)}}function br(e){let t;if(typeof e==`string`){let n=e.split(`.`);(n.length===3||n.length===5)&&([t]=n)}else if(typeof e==`object`&&e){if(`protected`in e)t=e.protected;else throw TypeError(`Token does not contain a Protected Header`)}let n=`Invalid Token or Protected Header formatting`;if(typeof t!=`string`||!t)throw TypeError(n);return re(t,TypeError,n)}function xr(e){if(typeof e!=`string`)throw new C(`JWTs must use Compact JWS serialization, JWT must be a string`);let{1:t,length:n}=e.split(`.`);if(n===5)throw new C(`Only JWTs using Compact JWS serialization can be decoded`);if(n!==3)throw new C(`Invalid JWT`);if(!t)throw new C(`JWTs must contain a payload`);let i;try{i=M(t)}catch{throw new C(`Failed to base64url decode the payload`)}let a;try{a=JSON.parse(r.decode(i))}catch{throw new C(`Failed to parse the decoded payload as JSON`)}if(!F(a))throw new C(`Invalid JWT Claims Set`);return a}function Sr(e){let t=e?.modulusLength??2048;if(typeof t!=`number`||!Number.isInteger(t)||t<2048)throw new y(`Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used`);return t}async function Cr(e,t){let n=Ee(t?.extractable),r=Mn(e,An);r.secret&&jn(`"alg" (Algorithm)`);let i;if(r.resolve){let e=t?.crv??`P-256`;if(![`P-256`,`P-384`,`P-521`,`X25519`].includes(e))throw new y(`Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519`);i=r.resolve({crv:e})}else{if(r.crv!==void 0&&t?.crv!==void 0&&t.crv!==r.crv)throw new y(`Invalid or unsupported crv option provided, the only supported value for ${e} is ${r.crv}`);i=r.kty[0]===`RSA`?{...r.subtle,publicExponent:Uint8Array.of(1,0,1),modulusLength:Sr(t)}:r.subtle}return crypto.subtle.generateKey(i,n??!1,[...r.usages[1],...r.usages[0]])}async function wr(e,t){let n=Ee(t?.extractable),r,i,a;switch(e){case`HS256`:case`HS384`:case`HS512`:r=+e.slice(-3),i={name:`HMAC`,hash:`SHA-${r}`,length:r},a=[`sign`,`verify`];break;case`A128CBC-HS256`:case`A192CBC-HS384`:case`A256CBC-HS512`:return crypto.getRandomValues(new Uint8Array(e.slice(-3)>>3));case`A128KW`:case`A192KW`:case`A256KW`:r=+e.slice(1,4),i={name:`AES-KW`,length:r},a=[`wrapKey`,`unwrapKey`];break;case`A128GCMKW`:case`A192GCMKW`:case`A256GCMKW`:case`A128GCM`:case`A192GCM`:case`A256GCM`:r=+e.slice(1,4),i={name:`AES-GCM`,length:r},a=[`encrypt`,`decrypt`];break;default:jn(An)}return crypto.subtle.generateKey(i,n??!1,a)}var Tr=`WebCryptoAPI`;export{Zt as A,Tn as C,vn as D,yn as E,Tt as F,wt as I,A as L,Jt as M,Nt as N,_n as O,Et as P,C as R,Dn as S,Sn as T,tr as _,br as a,Zn as b,gr as c,pr as d,cr as f,er as g,nr as h,xr as i,Yt as j,gn as k,_r as l,ar as m,wr as n,yr as o,ur as p,Cr as r,vr as s,Tr as t,hr as u,$n as v,Cn as w,kn as x,Qn as y,m as z};