@aviaratech/ai-delivery 0.3.27 → 0.3.28
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/directoryIndependent.test.js +47 -0
- package/dist/directoryIndependent.test.js.map +1 -1
- package/dist/issueIntake.test.js +18 -3
- package/dist/issueIntake.test.js.map +1 -1
- package/dist/mcp/index.js +9 -1
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp/tools.d.ts +1 -1
- package/dist/mcp/tools.js +6 -3
- package/dist/mcp/tools.js.map +1 -1
- package/dist/pluginPackaging.test.js +8 -0
- package/dist/pluginPackaging.test.js.map +1 -1
- package/package.json +1 -1
- package/plugins/ai-delivery/.claude-plugin/plugin.json +2 -2
- package/plugins/ai-delivery/README.md +8 -0
- package/plugins/ai-delivery/plugin.json +1 -1
- package/plugins/ai-delivery/runtime/dist/cli.js +12 -11
- package/plugins/ai-delivery/runtime/package.json +1 -1
- package/plugins/ai-delivery/skills/intake-create/SKILL.md +19 -3
|
@@ -292,19 +292,20 @@ GFS4: `),console.error(e)}),n[s]||(u(n,global[s]||[]),n.close=(function(e){funct
|
|
|
292
292
|
repository(owner: $owner, name: $repo) { pullRequest(number: $number) {
|
|
293
293
|
closingIssuesReferences(first: 100) { nodes { number repository { nameWithOwner } } pageInfo { hasNextPage } }
|
|
294
294
|
} }
|
|
295
|
-
}`,{...e.repo,number:n})).repository.pullRequest?.closingIssuesReferences;if(r.number!==n||r.head.repo?.full_name.toLowerCase()!==e.config.repository.toLowerCase()||r.base.repo.full_name.toLowerCase()!==e.config.repository.toLowerCase()||!i||i.pageInfo.hasNextPage||!i.nodes.some(n=>n.number===t&&n.repository.nameWithOwner.toLowerCase()===e.config.repository.toLowerCase()))throw new L(`Native PR lineage does not establish the exact repository and closing issue.`);return jx.parse({prNumber:n,headSha:r.head.sha,headBranch:r.head.ref,baseSha:r.base.sha,baseBranch:r.base.ref,mergeSha:r.merge_commit_sha,merged:r.merged,authorLogin:r.user?.login})}async function aS(e,t,n){let r=[...new Set([t.prNumber,n].filter(e=>e!=null))];return Promise.all(r.map(n=>iS(e,t.issueNumber,n)))}function oS(e,t,n,r,i,a,o,s){if(n===`active-resume`){if(![`active`,`pr-published`].includes(t.status)||o!==`open`||a.some(e=>e.merged||e.headSha!==i.sha||e.headBranch!==t.branch))throw new L(`Active resume requires the exact open issue and unmerged source lineage.`);if(s.some(e=>/^git\/ai-delivery\/(?:publications|reviews|merges|merge-intents|merge-attempts|merge-results)\//u.test(e.path)))throw new L(`Existing current publication/review/merge slots require separate authority reconciliation; active resume cannot overwrite them.`)}else{let n=a.find(e=>e.prNumber===r);if(!n||o!==`closed`||!n.merged||n.headSha!==i.sha||n.headBranch!==t.branch||a.some(r=>!r.merged||!r.mergeSha||r.headBranch!==t.branch||r.baseBranch!==n.baseBranch||rd(e,`merge-base`,`--is-ancestor`,r.mergeSha,r.prNumber===n.prNumber?n.mergeSha:i.sha)!==0))throw new L(`Terminal native PR lineage or merged-result ancestry does not bind the retained exact source.`)}}async function sS(e,t,n){let r=async t=>{try{let n=(await e.clients.rest.repos.getBranch({...e.repo,branch:t})).data;if(n.name!==t)throw new L(`Native branch readback belongs to another ref.`);return ud.parse(n.commit.sha)}catch(e){if(e.status===404)return null;throw e}},i=await r(t),a=await r(n);if(a===null)throw new L(`Native retaining base branch is missing.`);return{headSha:i,baseSha:a}}async function cS(e,t){let n=[],r=od(e.root),i=Jb(r).filter(e=>e.type===`issue`&&e.issueNumber===t.issueNumber);if(i.length!==1)return{ready:!1,blockers:[`Expected one canonical legacy issue row.`],plan:null,inventory:[]};let a=[];try{let o=Ax.parse(i[0]);if(a.push(...Rx(r,o)),!e.configuration||e.config.repository!==`${e.repo.owner}/${e.repo.repo}`)throw new L(`Transition requires exact current repository configuration.`);if(o.path!==w(r,`.worktrees`,`issue-${String(o.issueNumber)}`)||o.branch!==`issue/${String(o.issueNumber)}`||id(o.path)!==h(o.path)||ad(o.path)!==ad(r)||nd(o.path,`branch`,`--show-current`)!==o.branch)throw new L(`Legacy row path, branch or Git ownership disagrees.`);cd(o.path);for(let e of[`v1`,`v2`])Ix(w(ad(r),`issue-cli`,`verification-stages`,e))&&n.push(`Unsupported operative issue-cli verification-stages/${e}; no authenticated supported operational closure is available.`);if((!t.retainedAdmissionPath||!t.retainedArchivePath)&&n.push(`Missing retained supported public producer admission/archive and operational closure. Historical UNKNOWN is preservation-only.`),n.length>0)return{ready:!1,blockers:n,plan:null,inventory:a};let s=await Yv({repoRoot:r,configuration:e.configuration,...t.runtimeEntryPath===void 0?{}:{runtimeEntryPath:t.runtimeEntryPath}}),{inventory:c,...l}=Px(e,h(t.retainedAdmissionPath),h(t.retainedArchivePath));a.push(...c);let u={sha:nd(o.path,`rev-parse`,`HEAD`),tree:nd(o.path,`rev-parse`,`HEAD^{tree}`)},d=Fx(r,o,a,l.producerDigest,u);if(a.filter(e=>e.path.startsWith(`git/ai-delivery/runs@2/`)).some(t=>ib(Lx(t.source)).classification.repository!==e.config.repository))throw new L(`Operational run inventory belongs to another repository.`);if(t.disposition===`remove`&&c.some(e=>{let t=se(o.path,e.source);return t===``||!t.startsWith(`..`)&&!t.startsWith(`/`)}))throw new L(`Retained operational producer must remain outside the source selected for removal.`);let f=a.find(e=>e.path.startsWith(`git/ai-delivery/writers@1/`));Yy(o.path,f===void 0?void 0:Lx(f.source));let p=t.purpose===`merged-cleanup`?t.terminalPrNumber??o.prNumber??null:null,m=await aS(e,o,p),g=(await e.clients.rest.issues.get({...e.repo,issue_number:o.issueNumber})).data;oS(r,o,t.purpose,p,u,m,g.state,a);let _=await Qx(e);if(m.some(e=>e.authorLogin.toLowerCase()===_.reviewerActor.toLowerCase()))throw new L(`Configured transition reviewer App is also the native PR author.`);let v=t.disposition===`remove`?await sS(e,o.branch,m.find(e=>e.prNumber===p).baseBranch):null;if(v&&(v.headSha!==null&&v.headSha!==u.sha||nd(r,`rev-parse`,ld(r,uS(e).remote))!==v.baseSha))throw new L(`Native remote branch readback disagrees with exact source or local retaining ref.`);let y=[...t.retainedHoldCommentIds??[]].sort((e,t)=>e-t);if(new Set(y).size!==y.length)throw new L(`Retained hold inventory has duplicates.`);let b=[];for(let t of y){let n=(await e.clients.rest.issues.getComment({...e.repo,comment_id:t})).data;if(!n.body||n.issue_url?.toLowerCase()!==`https://api.github.com/repos/${e.config.repository}/issues/${String(p??o.issueNumber)}`.toLowerCase())throw new L(`Retained hold comment belongs to another subject or is unavailable.`);let r=Buffer.from(z(n));b.push({commentId:t,digest:V(r)})}a.sort((e,t)=>e.path.localeCompare(t.path));let x={schemaVersion:`ai-delivery.worktree-transition-plan@1`,repository:e.config.repository,repoRoot:r,row:o,purpose:t.purpose,disposition:t.disposition??`retain`,head:u,terminalPrNumber:p,lineage:m,remoteRefs:v,retainedHoldCommentIds:y,holdEvidence:b,inventory:a,inventoryId:B(a),historicalProducer:`UNKNOWN`,closure:{family:`public-ai-delivery-0.3.5-posix@1`,...l,runManifestIds:d},currentRuntime:s,policyDigest:V(Lx(uS(e).policyModulePath)),operator:_.operator,reviewerActor:_.reviewerActor},ee=Mx.parse({...x,planId:B(x)});return{ready:!0,blockers:n,plan:ee,inventory:a,relinquishmentBody:$x(ee)}}catch(e){return n.push(e instanceof Error?e.message:String(e)),{ready:!1,blockers:n,plan:null,inventory:a}}}function lS(e,t){for(let n of t){let t=Lx(n.source);if(t.length!==n.size||V(t)!==n.digest)throw new L(`Historical evidence drifted: ${n.path}`);gd(w(e,`${n.digest.slice(7)}.bin`),t,n.digest)}}function uS(e){if(!e.configuration||!(`policyModulePath`in e.configuration))throw new L(`Historical repository configuration binding is unsupported by this runtime; preserve its original controller and records. No policy module was loaded.`);return e.configuration}var dS=k().regex(/^[a-f0-9]{40}$/u),fS=k().regex(/^sha256:[a-f0-9]{64}$/u),pS=N({artifactId:fS,authorIdentity:k().min(1),checks:M(k().min(1)).min(1),diffScopeHash:fS,deliveryMetrics:N({blockerTimeMs:A().int().nonnegative().nullable(),reviewRound:A().int().positive()}).strict().optional(),elapsedMs:A().int().nonnegative(),findings:M(k()),head:N({sha:dS,tree:dS}).strict(),issueNumber:A().int().positive(),prNumber:A().int().positive().nullable(),readOnly:I(!0),requestedEffort:k().min(1),requestedModel:k().min(1),effectiveEffort:k().min(1),effectiveModel:k().min(1),reviewerIdentity:k().min(1),schemaVersion:I(`ai-delivery.review-artifact@1`),summary:k().min(1),verdict:F([`approve`,`request-changes`])}).strict().superRefine((e,t)=>{let{artifactId:n,...r}=e;(n!==B(r)||e.authorIdentity===e.reviewerIdentity)&&t.addIssue({code:`custom`,message:`Review artifact identity or role separation is invalid.`})});N({artifact:pS,completedAt:yu(),githubReviewId:A().int().positive(),githubReviewUrl:ol(),headSha:dS,login:k().min(1),prNumber:A().int().positive(),publicationEvidenceId:fS,receiptId:fS,schemaVersion:I(`ai-delivery.review-receipt@1`),state:I(`APPROVED`)}).strict().superRefine((e,t)=>{let{receiptId:n,...r}=e;(n!==B(r)||e.headSha!==e.artifact.head.sha||e.artifact.prNumber!==null&&e.artifact.prNumber!==e.prNumber)&&t.addIssue({code:`custom`,message:`Submitted review receipt is not bound to its artifact.`})});async function mS(e,t,n,r){let i;try{i=await e.clients.graphql(`query DeliveryReviewDecision($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) { pullRequest(number: $number) { headRefOid reviewDecision } } }`,{owner:e.repo.owner,name:e.repo.repo,number:t})}catch{return{reviewDecision:null,submittedReviewAuthorCanPushToRepository:null,status:`unknown`,nextAction:`Inspect the PR review requirement in GitHub before merge; review decision readback is unavailable.`}}let a=i.repository?.pullRequest;if(!a)return{reviewDecision:null,submittedReviewAuthorCanPushToRepository:null,status:`unknown`,nextAction:`Inspect the PR review requirement in GitHub before merge; PR decision readback is unavailable.`};if(a.headRefOid!==n)throw new L(`GitHub review decision does not match the exact PR head.`);let o=null;if(r)try{let i=await e.clients.graphql(`query DeliveryReviewAccess($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) { pullRequest(number: $number) { reviews(last: 100) { nodes { fullDatabaseId author { login } authorCanPushToRepository commit { oid } state } } } } }`,{owner:e.repo.owner,name:e.repo.repo,number:t}),a=r.login.toLowerCase().replace(/\[bot\]$/u,``),s=i.repository?.pullRequest?.reviews.nodes.find(e=>e!==null&&String(e.fullDatabaseId)===String(r.id)&&e.author?.login.toLowerCase().replace(/\[bot\]$/u,``)===a&&e.commit?.oid===n&&e.state===`APPROVED`);typeof s?.authorCanPushToRepository==`boolean`&&(o=s.authorCanPushToRepository)}catch{}return a.reviewDecision===`APPROVED`?{reviewDecision:`APPROVED`,submittedReviewAuthorCanPushToRepository:o,status:`satisfied`,nextAction:`Continue only after required checks pass.`}:a.reviewDecision===`REVIEW_REQUIRED`?{reviewDecision:`REVIEW_REQUIRED`,submittedReviewAuthorCanPushToRepository:o,status:`still-required`,nextAction:o===!1?`GitHub still requires a qualifying approval; the submitted reviewer App review has no repository write access. Inspect the active rule and the App installation Contents grant, then obtain approval from an eligible independent reviewer.`:`GitHub still requires a qualifying approval. Inspect the active rule and obtain approval from an eligible independent reviewer; do not change actors or protections automatically.`}:a.reviewDecision===`CHANGES_REQUESTED`?{reviewDecision:`CHANGES_REQUESTED`,submittedReviewAuthorCanPushToRepository:o,status:`changes-requested`,nextAction:`Resolve the blocking review and obtain a fresh exact-head independent approval.`}:{reviewDecision:null,submittedReviewAuthorCanPushToRepository:o,status:`unknown`,nextAction:`Inspect the PR review requirement in GitHub before merge; no required-review decision was exposed.`}}function hS(e){let t=typeof e==`string`?JSON.parse(e):e;return pS.parse(t)}function gS(e){try{if(typeof e!=`string`||Buffer.byteLength(e,`utf8`)>65536)throw Error(`Invalid size.`);let t=e.match(/<!-- ai-delivery-review-artifact:[\s\S]*?-->/gu)??[],n=e.match(/<!-- ai-delivery-review-artifact-data:[\s\S]*?-->/gu)??[];if(t.length!==1||n.length!==1)throw Error(`Ambiguous binding.`);let r=t[0].match(/^<!-- ai-delivery-review-artifact: (sha256:[a-f0-9]{64}) -->$/u)?.[1],i=n[0].match(/^<!-- ai-delivery-review-artifact-data: ([A-Za-z0-9_-]+) -->$/u)?.[1];if(!r||!i)throw Error(`Invalid binding.`);let a=Buffer.from(i,`base64url`),o=a.toString(`utf8`);if(a.toString(`base64url`)!==i||!Buffer.from(o,`utf8`).equals(a))throw Error(`Invalid encoding.`);let s=hS(o);if(s.artifactId!==r)throw Error(`Artifact identity differs.`);return s}catch{throw new L(`GitHub review artifact binding is missing, invalid or ambiguous; obtain a fresh review.`)}}function _S(e){pS.parse(e);let t=`${e.summary}\n\n<!-- ai-delivery-review-artifact: ${e.artifactId} -->\n<!-- ai-delivery-review-artifact-data: ${Buffer.from(JSON.stringify(e)).toString(`base64url`)} -->`;return gS(t),t}async function vS(e,t,n){let r=[];for(let n=1;n<=30;n++){let i=(await e.clients.rest.pulls.listFiles({...e.repo,pull_number:t,page:n,per_page:100})).data;if(r.push(...i.map(e=>e.filename)),i.length<100)break}if(!Number.isSafeInteger(n)||r.length!==n||new Set(r).size!==r.length)throw new L(`Independent review scope is incomplete or differs from the remote PR diff.`);return B(r.sort())}async function yS(e,t){let n=[];for(let r=1;r<=20;r+=1){let i=await e.clients.rest.pulls.listReviews({...e.repo,pull_number:t,per_page:100,page:r});if(n.push(...i.data),i.data.length<100)return n}throw new L(`Review history exceeds the bounded readback window.`)}async function bS(e){let{artifact:t,context:n,issueNumber:r,prNumber:i}=e;if(pS.parse(t),t.verdict!==`approve`||t.issueNumber!==r||t.authorIdentity!==n.config.roles.author.identity||t.reviewerIdentity!==n.config.roles.reviewer.identity||t.prNumber!==null&&t.prNumber!==i)throw new L(`Independent review artifact is foreign or rejected.`);if(n.clients.authSource!==`app`||n.clients.role!==`reviewer`||!n.clients.appActorLogin)throw new L(`Formal review requires the independent reviewer GitHub App role.`);let a=(await n.clients.rest.pulls.get({...n.repo,pull_number:i})).data;if(a.number!==i||a.head.sha!==t.head.sha||a.state!==`open`||a.base.repo?.full_name.toLowerCase()!==n.config.repository.toLowerCase()||a.head.repo?.full_name.toLowerCase()!==n.config.repository.toLowerCase())throw new L(`PR identity or head changed before formal review.`);let o=await n.clients.appActorLogin();if(!o||!a.user?.login||o.toLowerCase()===a.user.login.toLowerCase())throw new L(`Reviewer GitHub actor must differ from PR author.`);let s=(await n.clients.rest.git.getCommit({...n.repo,commit_sha:t.head.sha})).data;if(s.sha!==t.head.sha||s.tree.sha!==t.head.tree)throw new L(`Independent review tree differs from the remote commit.`);if(t.diffScopeHash!==await vS(n,i,a.changed_files))throw new L(`Independent review scope is incomplete or differs from the remote PR diff.`);let c=_S(t),l=`<!-- ai-delivery-review-artifact: ${t.artifactId} -->`,u=await yS(n,i);if(u.some(e=>e.user?.login.toLowerCase()===o.toLowerCase()&&e.commit_id===t.head.sha&&e.state===`APPROVED`&&/<!-- ai-delivery-review-artifact: sha256:[a-f0-9]{64} -->/u.test(e.body??``)&&!e.body?.includes(l)))throw new L(`Another independent artifact conflicts with the existing exact-head App approval.`);let d=u.filter(e=>e.body?.includes(l));if(d.length>1)throw new L(`Conflicting GitHub reviews claim the same artifact identity.`);let f=d[0];if(f&&(f.state!==`APPROVED`||f.commit_id!==t.head.sha||f.user?.login.toLowerCase()!==o.toLowerCase()||!f.html_url||gS(f.body).artifactId!==t.artifactId))throw new L(`Prior GitHub review marker conflicts with exact-head approval.`);let p=(await n.clients.rest.pulls.get({...n.repo,pull_number:i})).data;if(p.head.sha!==t.head.sha||p.base.sha!==a.base.sha||p.state!==`open`)throw new L(`PR moved during independent review validation.`);if(e.dryRun)return{dryRun:!0,artifactId:t.artifactId,headSha:t.head.sha};let m=f??(await n.clients.rest.pulls.createReview({...n.repo,pull_number:i,commit_id:t.head.sha,body:c,event:`APPROVE`})).data;if(!m.id||m.state!==`APPROVED`||m.commit_id!==t.head.sha||m.user?.login.toLowerCase()!==o.toLowerCase()||!m.html_url)throw new L(`GitHub did not return complete exact-head independent approval.`);let h={artifact:t,repository:n.config.repository,baseSha:a.base.sha,headSha:t.head.sha,githubReviewId:m.id,githubReviewUrl:m.html_url,login:m.user.login,prNumber:i,schemaVersion:`ai-delivery.github-review@1`,state:`APPROVED`},g={...h,receiptId:B(h)},_=(await n.clients.rest.pulls.getReview({...n.repo,pull_number:i,review_id:m.id})).data;if(_.id!==g.githubReviewId||_.html_url!==g.githubReviewUrl||_.state!==`APPROVED`||_.commit_id!==g.headSha||_.user?.login!==g.login||gS(_.body).artifactId!==t.artifactId)throw new L(`GitHub exact-head App review readback disagrees.`);let v=(await n.clients.rest.pulls.get({...n.repo,pull_number:i})).data;if(v.head.sha!==t.head.sha||v.base.sha!==a.base.sha||v.state!==`open`)throw new L(`PR moved during independent review submission; approval is not current.`);return g}var xS=/^[a-f0-9]{40}$/u,SS=/^(?!.*(?:\.\.|@\{|\/\/))[A-Za-z0-9._/-]+$/u;function CS(e){if(typeof e!=`string`)throw new L(`Incomplete non-closing message readback.`);let t=e.replace(/[*_~`\\<>[\]]/gu,``);if(/\b(?:close[sd]?|fix(?:es|ed)?|resolve[sd]?)\b(?:\s*:\s*|\s+)[^\n]*?(?:#[0-9]+|[A-Za-z0-9.-]+\/[A-Za-z0-9.-]+#[0-9]+|https?:\/\/(?:www\.)?github\.com\/[A-Za-z0-9.-]+\/[A-Za-z0-9.-]+\/(?:issues|pull)\/[0-9]+)/iu.test(t))throw new L(`Non-closing delivery refuses closing directives in body, title or commit messages.`)}function wS(e,t){return`References ${e.config.repository}#${t}`}function TS(e,t,n){CS(n);let r=wS(e,t),i=n.startsWith(`${r}\n`)||n===r?n:`${r}\n\n${n}`;return ES(e,t,i),i}function ES(e,t,n){CS(n);let r=n.split(/\r?\n/u);if(r[0]!==wS(e,t)||r.filter(e=>/^References\s/iu.test(e)).length!==1)throw new L(`Non-closing PR body must retain one leading canonical References line.`)}function DS(e,t){let n=e.pageInfo;if(!n||typeof n.hasNextPage!=`boolean`||n.endCursor!==null&&typeof n.endCursor!=`string`)throw new L(`Incomplete non-closing native pagination.`);if(!n.hasNextPage)return null;if(!n.endCursor||t.has(n.endCursor))throw new L(`Non-closing native pagination did not advance.`);return t.add(n.endCursor),n.endCursor}async function OS(e,t){let n=(await e.clients.rest.issues.get({...e.repo,issue_number:t})).data;if(n.number!==t||`pull_request`in n||n.state!==`open`||typeof n.node_id!=`string`||!n.node_id||typeof n.title!=`string`||typeof n.body!=`string`||n.html_url?.toLowerCase()!==`https://github.com/${e.config.repository}/issues/${t}`.toLowerCase())throw new L(`Non-closing delivery requires the exact canonical OPEN issue and complete title/body.`);return n}function kS(e,t,n=!1){if(n?e.state!==`open`||e.draft||e.merged||t.state!==`closed`||t.draft||!t.merged:e.state!==t.state||e.draft!==t.draft||e.merged!==t.merged)throw new L(`Non-closing PR state/draft/merged readback drifted; reconcile read-only.`);if(e.node_id!==t.node_id||e.head.sha!==t.head.sha||e.head.ref!==t.head.ref||e.base.sha!==t.base.sha||e.base.ref!==t.base.ref||e.body!==t.body||e.title!==t.title||e.user.login.toLowerCase()!==t.user.login.toLowerCase())throw new L(`Non-closing PR identity, reference, message or head/base drifted; reconcile read-only.`)}function AS(e,t){if(e.node_id!==t.node_id||e.title!==t.title||e.body!==t.body)throw new L(`Non-closing issue identity/title/criteria drifted; reconcile read-only.`)}function jS(e){if(e!==void 0&&typeof e!=`boolean`)throw new L(`nonClosing must be a boolean.`);return e===!0}async function MS(e,t){let n=await JS(e.clients.role===`author`?e:{...e,clients:await ch({config:e.config,identity:e.config.roles.author.identity,role:`author`}),reviewerClients:e.clients},t);if(n.rules.visibility!==`complete`||n.approvalEligibility===`insufficient-permission`)throw new L(`Non-closing delivery requires complete native rule visibility and an independent reviewer route.`);return n}async function NS(e,t){let n=null,r=new Set,i=new Map,a;for(let o=0;o<20;o++){let o=await e.clients.graphql(`query DeliveryNonClosingCommits($owner:String!,$repo:String!,$number:Int!,$cursor:String){repository(owner:$owner,name:$repo){nameWithOwner pullRequest(number:$number){id number headRefOid baseRefOid baseRefName commits(first:100,after:$cursor){totalCount nodes{commit{oid message parents(first:100){totalCount nodes{oid} pageInfo{hasNextPage endCursor}}}} pageInfo{hasNextPage endCursor}}}}}`,{...e.repo,number:t.number,cursor:n}),s=o.repository?.pullRequest,c=s?.commits;if(o.repository?.nameWithOwner?.toLowerCase()!==e.config.repository.toLowerCase()||s?.id!==t.node_id||s.number!==t.number||s.headRefOid!==t.head.sha||s.baseRefOid!==t.base.sha||s.baseRefName!==t.base.ref||!c||!Array.isArray(c.nodes)||c.nodes.length>100||!Number.isSafeInteger(c.totalCount)||c.totalCount<1||c.totalCount>2e3||a!==void 0&&a!==c.totalCount)throw new L(`Incomplete or moved introduced commit graph at the non-closing head/base.`);a=c.totalCount;for(let e of c.nodes){let t=e?.commit;if(!t||!LS(t.oid)||i.has(t.oid)||!t.parents||!Array.isArray(t.parents.nodes)||t.parents.nodes.length>100||!Number.isSafeInteger(t.parents.totalCount)||t.parents.totalCount<1||t.parents.totalCount!==t.parents.nodes.length||t.parents.pageInfo?.hasNextPage!==!1||t.parents.nodes.some(e=>!LS(e?.oid)))throw new L(`Incomplete, duplicate or truncated introduced commit identity/parents.`);CS(t.message),i.set(t.oid,t.message)}if(n=DS(c,r),n===null){if(i.size!==a||!i.has(t.head.sha))throw new L(`Introduced commit count/head is incomplete.`);return}}throw new L(`Non-closing commit graph exceeds the bounded readback window.`)}async function PS(e,t,n){let r=new Set,i;for(let a=1;a<=20;a++){let o=(await e.clients.rest.repos.compareCommitsWithBasehead({...e.repo,basehead:`${t}...${n}`,per_page:100,page:a})).data;if(o.base_commit?.sha!==t||!LS(o.merge_base_commit?.sha)||![`ahead`,`diverged`].includes(o.status)||!Number.isSafeInteger(o.total_commits)||o.total_commits<1||o.total_commits>2e3||i!==void 0&&i!==o.total_commits||!Array.isArray(o.commits)||o.commits.length>100)throw new L(`Incomplete introduced commit range before non-closing publication.`);i=o.total_commits;for(let e of o.commits){if(!LS(e.sha)||r.has(e.sha)||!Array.isArray(e.parents)||e.parents.length<1||e.parents.length>100||e.parents.some(e=>!LS(e.sha)))throw new L(`Incomplete or duplicate introduced commit identity.`);CS(e.commit?.message),r.add(e.sha)}if(r.size===i&&r.has(n))return;if(o.commits.length<100)throw new L(`Truncated introduced commit range before publication.`)}throw new L(`Introduced commit range exceeds the bounded readback window.`)}async function FS(e,t,n){if(typeof n.node_id!=`string`||!n.node_id||n.html_url?.toLowerCase()!==`https://github.com/${e.config.repository}/pull/${n.number}`.toLowerCase())throw new L(`Incomplete non-closing PR node identity.`);ES(e,t,n.body),CS(n.title);let r=await OS(e,t),i=(await e.clients.rest.repos.get({...e.repo})).data;if(i.full_name?.toLowerCase()!==e.config.repository.toLowerCase()||n.base.ref!==i.default_branch||typeof i.node_id!=`string`||!i.node_id)throw new L(`Non-closing PR must target the canonical default repository/base.`);let a=await MS(e,n.base.ref);if(n.user.login.toLowerCase()!==a.author.actorLogin.toLowerCase())throw new L(`Non-closing PR author differs from the configured author.`);let o=null,s=new Set,c=new Map,l=!1;for(let u=0;u<20;u++){let d=await e.clients.graphql(`query DeliveryNonClosingReferences($owner:String!,$repo:String!,$number:Int!,$cursor:String){repository(owner:$owner,name:$repo){id nameWithOwner issue(number:$number){id number state timelineItems(first:100,after:$cursor,itemTypes:[CROSS_REFERENCED_EVENT]){nodes{... on CrossReferencedEvent{id actor{login} isCrossRepository willCloseTarget source{__typename ... on Issue{id number repository{id nameWithOwner}} ... on PullRequest{id number repository{id nameWithOwner}}} target{__typename ... on Issue{id number repository{id nameWithOwner}} ... on PullRequest{id number repository{id nameWithOwner}}}}} pageInfo{hasNextPage endCursor}}}}}`,{...e.repo,number:t,cursor:o}),f=d.repository?.issue,p=f?.timelineItems;if(d.repository?.id!==i.node_id||d.repository.nameWithOwner?.toLowerCase()!==e.config.repository.toLowerCase()||f?.id!==r.node_id||f.number!==t||f.state!==`OPEN`||!p||!Array.isArray(p.nodes)||p.nodes.length>100)throw new L(`Incomplete or conflicting native non-closing issue identity.`);for(let o of p.nodes){let s=o?.source,u=o?.target;if(!o||!IS(o.id)||!s||!u||![`Issue`,`PullRequest`].includes(s.__typename)||!IS(s.id)||!Number.isSafeInteger(s.number)||s.number<=0||!IS(s.repository?.id)||typeof s.repository.nameWithOwner!=`string`||u.__typename!==`Issue`||u.id!==r.node_id||u.number!==t||u.repository?.id!==i.node_id||u.repository.nameWithOwner?.toLowerCase()!==e.config.repository.toLowerCase()||typeof o.isCrossRepository!=`boolean`||typeof o.willCloseTarget!=`boolean`||!IS(o.actor?.login))throw new L(`Incomplete native cross-reference event identity/actor.`);let d=JSON.stringify([s.__typename,s.id,s.number,s.repository.id,s.repository.nameWithOwner.toLowerCase(),u.id,u.number,u.repository.id,u.repository.nameWithOwner.toLowerCase(),o.actor.login.toLowerCase(),o.isCrossRepository,o.willCloseTarget]);if(c.has(o.id)&&c.get(o.id)!==d)throw new L(`Conflicting duplicate native reference event.`);if(c.set(o.id,d),s.id===n.node_id||s.__typename===`PullRequest`&&s.number===n.number&&s.repository.nameWithOwner.toLowerCase()===e.config.repository.toLowerCase()){if(s.__typename!==`PullRequest`||s.id!==n.node_id||s.number!==n.number||s.repository.id!==i.node_id||s.repository.nameWithOwner.toLowerCase()!==e.config.repository.toLowerCase()||o.isCrossRepository||o.willCloseTarget!==!1||o.actor.login.toLowerCase()!==a.author.actorLogin.toLowerCase())throw new L(`Conflicting, closing or unauthorized native PR reference.`);l=!0}}if(o=DS(p,s),o===null)break;if(u===19)throw new L(`Native non-closing references exceed the bounded readback window.`)}if(!l)throw new L(`Missing authorized native non-closing PR-to-issue reference.`);if(await BS(e,n.number,t,!0,n.node_id),await NS(e,n),!n.merged){let t=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${n.base.ref}`})).data;if(t.ref!==`refs/heads/${n.base.ref}`||t.object.type!==`commit`||t.object.sha!==n.base.sha)throw new L(`Non-closing default base has moved or is incomplete.`)}return AS(r,await OS(e,t)),kS(n,await zS(e,n.number)),r}function IS(e){return typeof e==`string`&&e.trim().length>0}function LS(e){return typeof e==`string`&&xS.test(e)}function RS(e){if(typeof e!=`string`||!SS.test(e)||e.startsWith(`/`)||e.endsWith(`/`)||e.endsWith(`.lock`))throw new L(`Invalid GitHub branch name.`)}async function zS(e,t){if(e.config.repository.toLowerCase()!==`${e.repo.owner}/${e.repo.repo}`.toLowerCase())throw new L(`Configured and selected GitHub repository identities disagree.`);let n=(await e.clients.rest.pulls.get({...e.repo,pull_number:t})).data;if(n.number!==t||typeof n.base.repo?.full_name!=`string`||typeof n.head.repo?.full_name!=`string`||n.base.repo?.full_name.toLowerCase()!==e.config.repository.toLowerCase()||n.head.repo?.full_name.toLowerCase()!==e.config.repository.toLowerCase()||!LS(n.head.sha)||!LS(n.base.sha)||n.state!==`open`&&n.state!==`closed`||typeof n.merged!=`boolean`||typeof n.draft!=`boolean`||n.merged&&n.state!==`closed`)throw new L(`GitHub PR identity or exact head readback is invalid.`);return RS(n.head.ref),RS(n.base.ref),n}async function BS(e,t,n,r=!1,i,a=!1,o,s){let c=null,l=new Set,u=0;for(let d=0;d<20;d++){let d=await e.clients.graphql(`query DeliveryClosingIssues($owner:String!,$repo:String!,$number:Int!,$cursor:String){repository(owner:$owner,name:$repo){nameWithOwner pullRequest(number:$number){id number closingIssuesReferences(first:100,after:$cursor){nodes{__typename id number repository{id nameWithOwner}} pageInfo{hasNextPage endCursor}}}}}`,{...e.repo,number:t,cursor:c}),f=d.repository?.pullRequest?.closingIssuesReferences;if(typeof d.repository?.nameWithOwner!=`string`||d.repository.nameWithOwner.toLowerCase()!==e.config.repository.toLowerCase()||d.repository?.pullRequest?.number!==t||i!==void 0&&d.repository?.pullRequest?.id!==i||!f||!Array.isArray(f.nodes)||f.nodes.length>100||typeof f.pageInfo?.hasNextPage!=`boolean`||f.pageInfo.endCursor!==null&&typeof f.pageInfo.endCursor!=`string`)throw new L(`Incomplete or conflicting native GitHub PR issue association readback.`);for(let t of f.nodes){if(a&&(!t||t.__typename!==`Issue`||!IS(o)||t.id!==o||!IS(s)||t.repository?.id!==s))throw new L(`Incomplete or conflicting typed closing issue/repository identity before body transition.`);if(r)throw new L(`Non-closing PR has an unintended native closing association.`);if(!t||!Number.isSafeInteger(t.number)||t.number<=0||typeof t.repository?.nameWithOwner!=`string`||!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u.test(t.repository.nameWithOwner))throw new L(`Incomplete native PR closing-issue identity.`);if(t.number===n&&t.repository.nameWithOwner.toLowerCase()===e.config.repository.toLowerCase())u++;else if(a)throw new L(`Existing PR has conflicting closing associations; body transition refused.`)}if(!f.pageInfo.hasNextPage){if(!r&&u!==1)throw new L(`Native GitHub PR closing-issue association does not identify the intended issue.`);return}let p=f.pageInfo.endCursor;if(!p||l.has(p))throw new L(`Native PR issue pagination did not advance.`);l.add(p),c=p}throw new L(`Native PR issue association exceeds the bounded readback window.`)}async function VS(e,t,n){let r=[];for(let i=1;i<=20;i++){let a=(await e.clients.rest.pulls.list({...e.repo,head:`${e.repo.owner}:${t}`,...n===void 0?{}:{base:n},state:`all`,page:i,per_page:100})).data;if(!Array.isArray(a)||a.some(e=>!e||!Number.isSafeInteger(e.number)||e.number<=0))throw new L(`Incomplete GitHub PR match readback.`);if(r.push(...a),a.length<100)return r}throw new L(`GitHub PR match history exceeds the bounded readback window.`)}async function HS(e,t,n,r=!1){let i=await zS(e,n);if(r?await FS(e,t,i):await BS(e,n,t),!i.merged){let n=await Nv(e,t);if(n.length>0){let e=n.filter(e=>e.name===i.head.ref);if(e.length!==1||e[0].sha!==i.head.sha)throw new L(`Native linked issue branches conflict with the exact PR head/ref.`)}let r=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${i.head.ref}`})).data;if(r.ref!==`refs/heads/${i.head.ref}`||r.object.type!==`commit`||r.object.sha!==i.head.sha)throw new L(`Current remote PR head/ref readback is incomplete or has moved.`)}return i}async function US(e,t){let n=jS(t.nonClosing);if(n&&(t.issueNumber===void 0||t.prNumber===void 0))throw new L(`Non-closing inspection requires explicit canonical issue and PR numbers.`);let r=t.prNumber;if(r===void 0){if(t.issueNumber===void 0)throw new L(`prNumber or issueNumber is required.`);let n=await Nv(e,t.issueNumber);if(n.length!==1)throw new L(`Issue-only PR inspection requires one GitHub-linked issue branch. After publication, supply the exact issue and PR numbers (CLI --issue and --pr) to verify the native PR closing-issue association.`);let i=n[0].name,a=await VS(e,i);if(a.length!==1)throw new L(`Select an explicit PR number when the remote issue branch has zero or multiple PRs.`);r=a[0].number}let i=t.issueNumber===void 0?await zS(e,r):await HS(e,t.issueNumber,r,n);return{prNumber:i.number,url:i.html_url,state:i.state,draft:i.draft,headSha:i.head.sha,headBranch:i.head.ref,baseBranch:i.base.ref,merged:i.merged}}async function WS(e,t=`open`){return{schemaVersion:`ai-delivery.pr-list@1`,pullRequests:(await e.clients.rest.paginate(e.clients.rest.pulls.list,{...e.repo,state:t,per_page:100})).map(e=>({number:e.number,state:e.state,draft:e.draft??!1,headSha:e.head.sha,baseSha:e.base.sha,url:e.html_url}))}}async function GS(e,t){let n=(await e.clients.rest.pulls.get({...e.repo,pull_number:t})).data,[r,i,a]=await Promise.all([e.clients.rest.checks.listForRef({...e.repo,ref:n.head.sha,per_page:100}),e.clients.rest.repos.getCombinedStatusForRef({...e.repo,ref:n.head.sha}),mS(e,t,n.head.sha)]);return{schemaVersion:`ai-delivery.pr-checks@1`,prNumber:n.number,headSha:n.head.sha,combinedStatus:i.data.state,reviewState:a,checkRuns:r.data.check_runs.map(e=>({name:e.name,status:e.status,conclusion:e.conclusion}))}}function KS(e){if(typeof e!=`object`||!e)return null;let t=e.required_approving_review_count;return typeof t==`number`&&Number.isSafeInteger(t)&&t>=0?t:null}function qS(e){return e.status===200&&Array.isArray(e.data)&&e.data.length===0&&e.headers!==void 0&&e.headers!==null&&(e.headers.link===void 0||e.headers.link===``)}async function JS(e,t,n,r=`publication`,i){if(t===void 0)try{t=(await e.clients.rest.repos.get({...e.repo})).data.default_branch}catch{throw new L(`Author cannot read the selected GitHub repository; verify configured access.`)}let a=async()=>{await i?.checkResources(),i?.signal.throwIfAborted()};await a();let o=e.config.roles.author.authSource??`app`,s=r===`development`&&o===`app`&&e.clients.authSource===`personal`;if(e.clients.authSource!==o&&!s)throw new L(r===`publication`?`PR publication requires the configured author credential; configure the personal author role for personal publication.`:`Development access preflight requires the configured author credential or the explicit personal author override.`);if(e.clients.role!==`author`||!e.clients.authenticatedAuthor)throw new L(`Delivery access preflight requires authenticated author identity readback.`);let c=await e.clients.authenticatedAuthor(i?.signal);if(await a(),!c.actorLogin||!c.credentialIdentity)throw new L(`Author GitHub identity readback is incomplete.`);let l=n??e.reviewerClients??await ch({config:e.config,identity:e.config.roles.reviewer.identity,role:`reviewer`,selectedAuthor:e.clients,...i===void 0?{}:{signal:i.signal}});if(await a(),l.role!==`reviewer`||l.authSource!==`app`||!l.appActorLogin)throw new L(`Configured reviewer GitHub App identity is unavailable.`);let u=await l.appActorLogin(i?.signal);if(await a(),!u)throw new L(`Reviewer GitHub App actor lookup is incomplete.`);if(c.actorLogin.toLowerCase()===u.toLowerCase())throw new L(`Author and reviewer resolve to the same GitHub actor; select distinct configured credentials.`);try{let t=(await l.rest.repos.get({...e.repo,...i===void 0?{}:{request:{signal:i.signal}}})).data;if(await a(),t.full_name.toLowerCase()!==`${e.repo.owner}/${e.repo.repo}`.toLowerCase())throw new L(`Reviewer GitHub App repository readback disagrees with the selected checkout.`)}catch(e){throw e instanceof L?e:new L(`Reviewer GitHub App cannot read the selected repository; verify its installation and repository access.`)}let[d,f]=await Promise.allSettled([e.clients.rest.request(`GET /repos/{owner}/{repo}/rules/branches/{branch}`,{...e.repo,branch:t,...i===void 0?{}:{request:{signal:i.signal}}}),e.clients.rest.request(`GET /repos/{owner}/{repo}/branches/{branch}/protection`,{...e.repo,branch:t,...i===void 0?{}:{request:{signal:i.signal}}})]);await a();let p=!1,m=f.status===`rejected`?f.reason:null;if(d.status===`fulfilled`&&qS(d.value)&&m?.status===404&&m.response?.status===404&&m.response.data?.message===`Branch not protected`){let n={...e.repo,...i===void 0?{}:{request:{signal:i.signal}}},[r,o,s]=await Promise.allSettled([e.clients.rest.request(`GET /repos/{owner}/{repo}`,n),e.clients.rest.request(`GET /repos/{owner}/{repo}/branches/{branch}`,{...n,branch:t}),e.clients.rest.request(`GET /repos/{owner}/{repo}/rulesets`,{...n,includes_parents:!0,per_page:100,page:1})]);if(await a(),r.status===`fulfilled`&&o.status===`fulfilled`&&s.status===`fulfilled`){let n=r.value.data,i=o.value.data;p=r.value.status===200&&o.value.status===200&&typeof n?.full_name==`string`&&n.full_name.toLowerCase()===`${e.repo.owner}/${e.repo.repo}`.toLowerCase()&&(n.permissions?.push===!0||n.permissions?.admin===!0)&&i?.name===t&&i.protected===!1&&i.protection?.enabled===!1&&qS(s.value)}}let h=[];if(d.status===`fulfilled`&&Array.isArray(d.value.data)){for(let e of d.value.data)if(e.type===`pull_request`){let t=KS(e.parameters);t!==null&&h.push(t)}}if(f.status===`fulfilled`){let e=f.value.data,t=KS(e.required_pull_request_reviews);t!==null&&h.push(t)}let g=d.status===`fulfilled`&&Array.isArray(d.value.data)&&(d.value.headers?.link===void 0||d.value.headers.link===``),_=Number(g)+Number(f.status===`fulfilled`||p),v=_===2?`complete`:_===1?`partial`:`unknown`,y=h.length>0?Math.max(...h):p?0:null,b=y!==null&&y>0&&l.effectiveContentsPermission===`read`;return{author:{actorLogin:c.actorLogin,authSource:e.clients.authSource,credentialSource:e.clients.credentialSource??`unreported`,identity:s?`personal`:e.config.roles.author.identity},reviewer:{actorLogin:u,credentialSource:l.credentialSource??`unreported`,effectiveContentsPermission:l.effectiveContentsPermission??`unknown`,identity:e.config.roles.reviewer.identity,repositoryAccess:`readable`},rules:{observedRequiredApprovals:y,visibility:v},approvalEligibility:b?`insufficient-permission`:`unknown`,nextAction:b?`The reviewer App token has Contents: read, but the visible rule requires approval from a reviewer with repository write access. To use the App for required approval, grant Contents: write, accept the installation permission change, and obtain a fresh token before publication.`:v===`complete`&&y===null?`No required approving review was observed in the visible rules. Confirm the live PR review decision after exact-head submission.`:v===`complete`?`Confirm whether the reviewer approval counts after exact-head submission; installation scopes do not prove required-review eligibility.`:`Inspect the active branch review rule with an authorized repository view and confirm whether the reviewer approval counts after exact-head submission.`}}async function YS(e,t){let n=jS(t.nonClosing);if(t.prNumber!==void 0&&(!Number.isSafeInteger(t.prNumber)||t.prNumber<=0))throw new L(`Existing PR selector must be a positive safe integer.`);let r=n?await OS(e,t.issueNumber):(await e.clients.rest.issues.get({...e.repo,issue_number:t.issueNumber})).data;if(`pull_request`in r||r.number!==t.issueNumber||r.state!==`open`)throw new L(`PR creation requires the requested open GitHub issue.`);let i=(await e.clients.rest.repos.get({...e.repo})).data;if(i.full_name?.toLowerCase()!==e.config.repository.toLowerCase()||e.config.repository.toLowerCase()!==`${e.repo.owner}/${e.repo.repo}`.toLowerCase())throw new L(`Configured and selected GitHub repository identities disagree.`);if(n&&!IS(i.node_id))throw new L(`Incomplete canonical non-closing repository node identity.`);let a=t.baseBranch??i.default_branch;if(a!==i.default_branch)throw new L(`PR delivery requires the repository default branch for durable issue association.`);RS(a),t.headBranch!==void 0&&RS(t.headBranch);let o=t.prNumber===void 0?void 0:await zS(e,t.prNumber),s=t.draft===!1&&t.headBranch!==void 0,c=o?await VS(e,o.head.ref,a):s?await VS(e,t.headBranch,a):void 0,l=o?o.head.ref:s&&c.length>0?t.headBranch:await Pv(e,t.issueNumber,t.headBranch);if(t.headBranch!==void 0&&l!==t.headBranch)throw new L(`Explicit PR and head selectors disagree.`);RS(l);let u=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${l}`})).data;if(u.ref!==`refs/heads/${l}`||u.object.type!==`commit`||!LS(u.object.sha))throw new L(`Remote issue branch head/ref readback is invalid.`);let d=c??await VS(e,l,a);if(d.length>1||o&&(d.length!==1||d[0].number!==o.number))throw new L(`Remote issue branch has conflicting PR matches.`);let f=o??(d[0]===void 0?void 0:await zS(e,d[0].number)),p=t.body??(n?f?.body??wS(e,t.issueNumber):`Closes #${t.issueNumber}`);if(!p.trim())throw new L(`PR body must contain text.`);let m=n?TS(e,t.issueNumber,p):RegExp(`(?:close[sd]?|fix(?:es|ed)?|resolve[sd]?)\\s+#${t.issueNumber}(?![0-9])`,`iu`).test(p)?p:`${p}\n\nCloses #${t.issueNumber}`,h=n&&f!==void 0&&f.body!==m;if(h&&(t.prNumber===void 0||t.body===void 0))throw new L(`Non-closing body transition requires an explicit existing PR number and body.`);if(f&&(f.head.sha!==u.object.sha||f.head.ref!==l||f.base.ref!==a||f.state!==`open`||f.merged||!h&&t.body!==void 0&&f.body!==m||t.title!==void 0&&f.title!==t.title))throw new L(`Existing remote PR conflicts with the requested branch, intent or state.`);let g=n?await MS(e,a):await JS(e,a);if(f&&f.user.login.toLowerCase()!==g.author.actorLogin.toLowerCase())throw new L(`Existing PR author differs from the configured authenticated author.`);if(f&&(typeof f.node_id!=`string`||!f.node_id))throw new L(`Existing PR publication identity is incomplete.`);n&&CS(t.title??f?.title??r.title);let _=t.title??r.title,v,y=f,b=h,x=f?.body,ee=f?.draft,S=!1,te=async()=>{n&&AS(r,await OS(e,t.issueNumber))},ne=async()=>{let o=await HS(e,t.issueNumber,y.number,n&&!b);if(o.state!==`open`||o.merged||o.node_id!==y.node_id||o.head.sha!==u.object.sha||o.head.ref!==l||o.base.ref!==a||o.base.sha!==y.base.sha||o.user.login.toLowerCase()!==g.author.actorLogin.toLowerCase()||h&&!S&&o.draft!==ee||o.body!==x||o.title!==y.title)throw new L(`Existing PR publication head, identity, intent or author readback drifted.`);if(b){await BS(e,o.number,t.issueNumber,!1,o.node_id,!0,r.node_id,i.node_id),CS(o.title),await NS(e,o);let n=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${a}`})).data;if(n.ref!==`refs/heads/${a}`||n.object.type!==`commit`||n.object.sha!==o.base.sha)throw new L(`Non-closing transition default base drifted.`);kS(o,await zS(e,o.number))}return await te(),o},re=async()=>{let t=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${a}`})).data;if(t.ref!==`refs/heads/${a}`||t.object.type!==`commit`||!LS(t.object.sha))throw new L(`Incomplete publication default base.`);if(v!==void 0&&v!==t.object.sha)throw new L(`Publication default base drifted before creation.`);v=t.object.sha,n&&await PS(e,t.object.sha,u.object.sha);let r=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${l}`})).data,i=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${a}`})).data;if(r.ref!==u.ref||r.object.type!==`commit`||r.object.sha!==u.object.sha||i.ref!==t.ref||i.object.type!==`commit`||i.object.sha!==t.object.sha)throw new L(`Non-closing publication head/base drifted.`);await te()};if(f?f=await ne():await re(),t.dryRun)return{dryRun:!0,...f===void 0?{}:{prNumber:f.number,draft:f.draft},...n?{nonClosing:!0,nonClosingVerified:f!==void 0&&!b,body:m,bodyTransition:b}:{},headSha:u.object.sha,headBranch:l,baseBranch:a,reviewRoute:g};let ie=!1;if(f){if(b&&(f=await ne(),await e.clients.rest.pulls.update({...e.repo,pull_number:f.number,body:m}),b=!1,x=m,f=await ne()),t.draft===!1&&f.draft){if(f=await ne(),f.draft){let t=await e.clients.graphql(`mutation DeliveryReadyPr($id:ID!){markPullRequestReadyForReview(input:{pullRequestId:$id}){pullRequest{id isDraft}}}`,{id:f.node_id});if(t?.markPullRequestReadyForReview?.pullRequest?.id!==f.node_id||t.markPullRequestReadyForReview.pullRequest.isDraft!==!1)throw new L(`PR promotion mutation readback is incomplete or conflicting; reconcile this PR.`);S=!0}if(f=await ne(),f.draft)throw new L(`PR promotion readback is still draft.`)}}else{await re();let n;try{n=await e.clients.rest.pulls.create({...e.repo,head:l,base:a,title:_,body:m,draft:t.draft!==!1})}catch(e){throw new L(`PR creation acknowledgement is uncertain; reconcile the remote head read-only before any new mutation. ${e instanceof Error?e.message:`Unknown failure`}`)}if(!Number.isSafeInteger(n.data.number)||n.data.number<=0)throw new L(`PR creation acknowledgement lacks a valid PR identity; reconcile the remote head read-only, do not create again.`);ie=!0;try{f=await zS(e,n.data.number)}catch(e){throw new L(`GitHub returned created PR #${n.data.number}; identity readback is unresolved. Reconcile read-only; do not create again. ${e instanceof Error?e.message:`Unknown failure`}`)}}try{if(ie&&(f.body!==m||f.title!==_||f.draft!==(t.draft!==!1)||f.state!==`open`||f.merged||f.base.sha!==v))throw new L(`Created PR body, title, draft/open state or default base differs from publication intent.`);if(f.head.sha!==u.object.sha||f.head.ref!==l||f.base.ref!==a)throw new L(`GitHub PR creation readback drifted.`);if(f.user.login.toLowerCase()!==g.author.actorLogin.toLowerCase())throw new L(`Published PR author differs from the configured authenticated author.`);if(n){let n=await HS(e,t.issueNumber,f.number,!0);kS(f,n),f=n,await te()}else await BS(e,f.number,t.issueNumber);if(ie){let t=await zS(e,f.number);kS(f,t),f=t}}catch(e){throw ie?new L(`GitHub created PR #${f.number} (${f.html_url}) at ${f.head.sha}; post-publication association/identity verification is unresolved. Reconcile this PR read-only; do not create again. ${e instanceof Error?e.message:`Unknown failure`}`):e}return{prNumber:f.number,url:f.html_url,headSha:f.head.sha,draft:f.draft,reviewRoute:g,...n?{nonClosing:!0}:{}}}async function XS(e,t){let n=jS(t.nonClosing),r=await HS(e,t.issueNumber,t.prNumber,n),i=n?await OS(e,t.issueNumber):void 0,a=await bS({context:e,artifact:hS(t.artifact),issueNumber:t.issueNumber,prNumber:t.prNumber,...t.dryRun===void 0?{}:{dryRun:t.dryRun}});return n&&(kS(r,await HS(e,t.issueNumber,t.prNumber,!0)),AS(i,await OS(e,t.issueNumber))),a}async function ZS(e,t){let n=[];for(let r=1;r<=20;r++){let i=(await e.clients.rest.pulls.listReviews({...e.repo,pull_number:t,page:r,per_page:100})).data;if(n.push(...i),i.length<100)return n}throw new L(`GitHub review history exceeds the bounded readback window.`)}async function QS(e,t){let n=jS(t.nonClosing);if(n&&t.strategy!==void 0&&t.strategy!==`squash`)throw new L(`Non-closing merge requires squash with explicit safe messages.`);if(e.clients.role!==`author`||e.clients.authSource!==(e.config.roles.author.authSource??`app`)||!e.clients.authenticatedAuthor)throw new L(`Merge and finish require the configured authenticated author role.`);let r=await e.clients.authenticatedAuthor();if(!r.actorLogin||!r.credentialIdentity)throw new L(`Author identity readback is incomplete.`);let i=await HS(e,t.issueNumber,t.prNumber,n),a=i,o=n?await OS(e,t.issueNumber):void 0,s=n?{commit_title:i.title,commit_message:`${wS(e,t.issueNumber)}\n\nDelivered by PR #${i.number}.`}:void 0;if(s&&(CS(s.commit_title),CS(s.commit_message)),t.reviewedHeadSha!==void 0&&t.reviewedHeadSha!==i.head.sha)throw new L(`Requested reviewed head differs from the GitHub PR.`);if(i.merged&&i.state===`closed`&&LS(i.merge_commit_sha))return{mergeSha:i.merge_commit_sha,headSha:i.head.sha,reused:!0};if((await JS(e,i.base.ref)).approvalEligibility===`insufficient-permission`)throw new L(`Configured reviewer App is ineligible for the required approval.`);if(i.state!==`open`||i.draft)throw new L(`GitHub PR must be open and ready for merge.`);let c=e.reviewerClients??await ch({config:e.config,identity:e.config.roles.reviewer.identity,role:`reviewer`,selectedAuthor:e.clients});if(c.role!==`reviewer`||c.authSource!==`app`||!c.appActorLogin)throw new L(`Independent reviewer App route is unavailable.`);let l=await c.appActorLogin();if(!i.user?.login||l.toLowerCase()===i.user.login.toLowerCase())throw new L(`Reviewer App must differ from the PR author.`);let u=(await ZS(e,t.prNumber)).filter(e=>e.user?.login.toLowerCase()===l.toLowerCase()&&e.commit_id===i.head.sha&&e.state===`APPROVED`&&/<!-- ai-delivery-review-artifact: sha256:[a-f0-9]{64} -->/u.test(e.body??``));if(u.length!==1)throw new L(`GitHub requires one unambiguous exact-head independent App review.`);let d=u[0],f=(await e.clients.rest.pulls.getReview({...e.repo,pull_number:t.prNumber,review_id:d.id})).data;if(f.id!==d.id||f.state!==`APPROVED`||f.commit_id!==i.head.sha||f.user?.login.toLowerCase()!==l.toLowerCase()||f.body!==d.body)throw new L(`Independent GitHub review readback changed or was dismissed.`);let p=gS(f.body);if(p.verdict!==`approve`||p.issueNumber!==t.issueNumber||p.prNumber!==null&&p.prNumber!==t.prNumber||p.authorIdentity!==e.config.roles.author.identity||p.reviewerIdentity!==e.config.roles.reviewer.identity||p.head.sha!==i.head.sha)throw new L(`Independent review artifact binding is stale, foreign or rejected.`);let m=(await e.clients.rest.git.getCommit({...e.repo,commit_sha:i.head.sha})).data;if(m.sha!==p.head.sha||m.tree.sha!==p.head.tree)throw new L(`Independent review tree differs from the remote commit.`);if(p.diffScopeHash!==await vS(e,t.prNumber,i.changed_files))throw new L(`Independent review scope differs from the remote PR diff.`);let h=p.head.sha;if(t.reviewedHeadSha!==void 0&&t.reviewedHeadSha!==h)throw new L(`Requested reviewed head differs from the independent GitHub review.`);let g=await mS(e,t.prNumber,h,{id:d.id,login:l});if(g.submittedReviewAuthorCanPushToRepository!==!0)throw new L(`Specific reviewer App approval is not verifiably qualifying for required review.`);if(g.status!==`satisfied`)throw new L(`GitHub review eligibility is ${g.status}: ${g.nextAction}`);if((await f_({graphql:e.clients.graphql,issueNumber:t.issueNumber,repo:e.repo})).blockers.some(e=>e.state===`OPEN`))throw new L(`GitHub issue has unresolved native blockers.`);if(i=await HS(e,t.issueNumber,t.prNumber,n),n&&(kS(a,i),AS(o,await OS(e,t.issueNumber)),CS(s.commit_title),CS(s.commit_message)),i.head.sha!==h||i.state!==`open`||i.draft||i.mergeable!==!0||i.mergeable_state!==`clean`)throw new L(`GitHub merge eligibility is ${i.mergeable_state??`unknown`}; CLEAN at the reviewed head is required.`);let _=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${i.base.ref}`})).data.object.sha;if(!LS(_)||_!==i.base.sha)throw new L(`GitHub base moved; refresh clean eligibility and independent review before merge.`);if(t.dryRun)return{dryRun:!0,headSha:h,prNumber:i.number,...s===void 0?{}:{nonClosing:!0,...s}};let v=(await e.clients.rest.pulls.merge({...e.repo,pull_number:t.prNumber,sha:h,merge_method:t.strategy??`squash`,...s})).data;if(!v.merged||!LS(v.sha))throw new L(`GitHub refused the reviewed-head merge.`);let y=await HS(e,t.issueNumber,t.prNumber,n);if(n&&(kS(a,y,!0),AS(o,await OS(e,t.issueNumber))),!y.merged||y.state!==`closed`||y.head.sha!==h||y.merge_commit_sha!==v.sha)throw new L(`GitHub merged PR readback disagrees with the reviewed-head mutation.`);return{mergeSha:v.sha,headSha:h,reused:!1}}async function $S(e,t){if(jS(t.nonClosing))throw new L(`Non-closing delivery cannot finish or close its retained issue.`);let n=await QS(e,t);if(t.dryRun)return n;let r=await HS(e,t.issueNumber,t.prNumber);if(!r.merged||r.state!==`closed`||r.merge_commit_sha!==n.mergeSha)throw new L(`Intended GitHub PR is not verifiably merged; issue remains open.`);let i=(await e.clients.rest.issues.get({...e.repo,issue_number:t.issueNumber})).data;if(i.number!==t.issueNumber||`pull_request`in i)throw new L(`Finish target is not the intended GitHub issue.`);i.state!==`closed`&&await e.clients.rest.issues.update({...e.repo,issue_number:t.issueNumber,state:`closed`,state_reason:`completed`});let a=(await e.clients.rest.issues.get({...e.repo,issue_number:t.issueNumber})).data;if(a.number!==t.issueNumber||a.state!==`closed`)throw new L(`GitHub issue closure readback disagrees.`);return{...n,issueClosed:!0}}function eC(e){let t=od(e.root),n=ed(t,`origin`);if(`${n.owner}/${n.repo}`.toLowerCase()!==e.config.repository.toLowerCase()||`${e.repo.owner}/${e.repo.repo}`.toLowerCase()!==e.config.repository.toLowerCase())throw new L(`Investigation repository identity disagrees.`);return t}async function tC(e,t,n){let r=ad(e);for(let e of[w(r,`ai-delivery`),w(r,`ai-delivery`,`writers@1`)]){try{let t=c(e);if(!t.isDirectory()||t.isSymbolicLink())throw new L(`Investigation writer namespace is unsafe.`)}catch(e){if(e.code!==`ENOENT`)throw e}Lv(e)}return Zy(e,t,n)}async function nC(e,t,n,r){let i=(await e.clients.rest.issues.get({...e.repo,issue_number:t})).data;if(i.number!==t||`pull_request`in i||i.state!==r||new URL(i.html_url).pathname.toLowerCase()!==`/${e.config.repository}/issues/${String(t)}`.toLowerCase())throw new L(`Investigation requires the exact native issue and expected state.`);let a=await Nv(e,t);if(a.length!==1||a[0].name!==`issue/${String(t)}`||a[0].sha!==n)throw new L(`Investigation requires one exact unchanged native linked branch.`);if((await e.clients.rest.pulls.list({...e.repo,state:`all`,head:`${e.repo.owner}:${a[0].name}`,per_page:100})).data.length!==0)throw new L(`Investigation completion cannot substitute for PR delivery.`)}function rC(e){return z({schemaVersion:`ai-delivery.investigation-preparation-acknowledgement@1`,preparation:e,authority:`prospective-registration-before-investigation-no-legacy-adoption`})}function iC(e,t){return z({schemaVersion:`ai-delivery.investigation-removal-authority@1`,preparationId:e.preparationId,repository:e.repository,issueNumber:e.row.issueNumber,head:e.head,worktree:e.row.path,branch:e.row.branch,resultDigest:t,disposition:`remove-only-this-unchanged-investigation-worktree-retain-branch-and-evidence`,operationalClosure:`all-investigation-producers-quiescent-and-excluded-through-completion-and-resume-no-outstanding-holds`})}function aC(e,t,n){return z({schemaVersion:`ai-delivery.investigation-result-acceptance@1`,authority:JSON.parse(iC(e,t)),authorityCommentId:n,verdict:`approved`,independentlyReviewed:`complete-durable-result-exact-source-and-removal-scope`})}async function oC(e,t){if(!Number.isSafeInteger(t.issueNumber)||t.issueNumber<=0||!xS.test(t.expectedHeadSha))throw new L(`Investigation preparation requires a positive issue and expected commit.`);let n=eC(e),r=w(n,`.worktrees`,`issue-${String(t.issueNumber)}`);if(t.investigationWorktree!==r||h(r)!==r)throw new L(`Investigation worktree must be the exact canonical .worktrees/issue-N path.`);if(i(w(n,`.issue-cli`,`issues`,String(t.issueNumber))))throw new L(`Historical issue custody remains preservation-only; investigation cannot adopt it.`);let a=await Qx(e),o=wx(n,t.issueNumber),s=fx(n,t.issueNumber);if(await nC(e,t.issueNumber,o.head.sha,`open`),o.head.sha!==t.expectedHeadSha)throw new L(`Investigation preparation source drifted from the expected head.`);if(s===void 0){let t=(await e.clients.rest.repos.get({...e.repo})).data;if(t.full_name.toLowerCase()!==e.config.repository.toLowerCase()||!t.default_branch)throw new L(`Investigation native repository identity is incomplete.`);if((await e.clients.rest.git.getRef({...e.repo,ref:`heads/${t.default_branch}`})).data.object.sha!==o.head.sha)throw new L(`Prospective investigation must begin at the current native default commit.`)}let c=new Date().toISOString(),l={schemaVersion:`ai-delivery.investigation-preparation@1`,repository:e.config.repository,repoRoot:n,row:s?.row??{branch:`issue/${String(t.issueNumber)}`,createdAt:c,identity:e.config.roles.author.identity,issueNumber:t.issueNumber,path:r,status:`active`,type:`issue`,updatedAt:c},...o,operator:{actorLogin:a.operator.actorLogin,credentialIdentity:a.operator.credentialIdentity},reviewerActor:a.reviewerActor},u=ox.parse({...l,preparationId:B(l)});return await tC(n,r,()=>_x(u,async()=>{if(z(wx(n,t.issueNumber))!==z(o))throw new L(`Investigation source changed before preparation acknowledgement.`);await nC(e,t.issueNumber,o.head.sha,`open`);let{commentId:r,url:i,body:a}=await pv(e,{issueNumber:t.issueNumber,body:rC(u)});if(z(wx(n,t.issueNumber))!==z(o))throw new L(`Investigation source changed during preparation acknowledgement.`);return{commentId:r,url:i,body:a}})),{preparation:u,acknowledgement:px(n,t.issueNumber),registered:!0}}async function sC(e,t){if([`prNumber`,`strategy`,`reviewedHeadSha`,`nonClosing`].some(e=>e in t))throw new L(`Investigation completion refuses PR or merge options.`);let n=eC(e),r=fx(n,t.issueNumber);if(!r)throw new L(`No prospective investigation preparation; historical custody cannot be reconstructed.`);let i=T(t.resultPath),a=se(r.row.path,i),o=a===`..`||a.startsWith(`..${ce}`)||oe(a);if(h(i)!==i||!o)throw new L(`Durable investigation result must be canonical and outside the removable worktree.`);let s=H(i,{maxBytes:524288});if(s.length===0)throw new L(`Investigation result must contain durable evidence.`);let c=V(s),l=iC(r,c),u=t.authorityCommentId===void 0?void 0:aC(r,c,t.authorityCommentId),d=async()=>{await nC(e,t.issueNumber,r.head.sha,`closed`);let i=await Dv(e,t.issueNumber);if(i.state!==`closed`||i.closeReason!==`completed`||i.duplicateOf!==null)throw new L(`Investigation requires native completed closed-issue authority.`);let a=px(n,t.issueNumber),o=(await e.clients.rest.issues.getComment({...e.repo,comment_id:a.commentId})).data;if(o.id!==a.commentId||o.body!==rC(r)||o.body!==a.body||o.issue_url.toLowerCase()!==`https://api.github.com/repos/${r.repository}/issues/${String(t.issueNumber)}`.toLowerCase()||o.user?.type!==`User`||o.user.login.toLowerCase()!==r.operator.actorLogin.toLowerCase()||`user:${String(o.user.id)}`!==r.operator.credentialIdentity)throw new L(`Native prospective preparation acknowledgement changed.`);if(t.authorityCommentId===void 0||t.acceptanceCommentId===void 0||u===void 0)throw new L(`Existing authentic operator and independent App acceptance comments are required.`);let s=await rS(e,{repository:r.repository,subject:t.issueNumber,operator:r.operator,reviewerActor:r.reviewerActor,authorityCommentId:t.authorityCommentId,acceptanceCommentId:t.acceptanceCommentId,operatorBody:l,reviewerBody:u,revokedBody:z({schemaVersion:`ai-delivery.investigation-removal-revocation@1`,preparationId:r.preparationId,resultDigest:c,authorityCommentId:t.authorityCommentId})}),d=Date.parse(o.created_at);for(let e of[s.relinquishment,s.acceptance]){let t=Date.parse(e.created_at);if(!Number.isFinite(d)||!Number.isFinite(t)||t<d)throw new L(`Investigation acceptance must follow its prospective preparation.`)}return{acknowledgement:o,closure:i,...s}};if(t.dryRun&&(t.authorityCommentId===void 0||t.acceptanceCommentId===void 0))return Tx(r,e.root),await nC(e,t.issueNumber,r.head.sha,`closed`),{completed:!1,ready:!1,preparationId:r.preparationId,resultDigest:c,authorityBody:l,...u===void 0?{}:{acceptanceBody:u},missingEvidence:`Existing authentic operator and configured-App exact-result acceptance are prerequisites; no submission route is supplied.`};if(!Number.isSafeInteger(t.authorityCommentId)||!Number.isSafeInteger(t.acceptanceCommentId)||t.authorityCommentId<=0||t.acceptanceCommentId<=0)throw new L(`Investigation evidence requires positive native comment IDs.`);return tC(n,r.row.path,()=>vx({preparation:r,result:s,authorityCommentId:t.authorityCommentId,acceptanceCommentId:t.acceptanceCommentId,dryRun:t.dryRun===!0,authorize:d,assertSource:t=>Tx(r,e.root,t),removeSource:()=>Ex(r,e.root)}))}var cC=k().regex(/^sha256:[a-f0-9]{64}$/u),lC=P({maxAggregateRssBytes:A().int().positive().safe(),minFreeDiskBytes:A().int().positive().safe(),maxNewOutputBytes:A().int().positive().safe(),maxCapturedOutputBytes:A().int().positive().safe().max(8*1024**2)}),uC=P({archivePath:k().min(1),archiveSha256:cC,configDigest:cC,packageVersion:k().regex(/^\d+\.\d+\.\d+$/u),repoRoot:k().min(1),repository:k().min(1),reviewRouteDigest:cC,runtimeDirectory:k().min(1),nativePluginRoot:k().min(1).optional(),sourceCommit:k().regex(/^[a-f0-9]{40}$/u),resourceBounds:lC.optional()}),dC=P({schemaVersion:I(`ai-delivery.runtime-stage@1`),stageId:cC,intent:uC,directory:P({device:A().int(),inode:A().int()}),admission:Gv.optional(),status:F([`incomplete`,`complete`]),recordId:cC}).superRefine((e,t)=>{let{recordId:n,...r}=e;(n!==B(r)||e.stageId!==B(e.intent)||e.status===`complete`!=(e.admission!==void 0)||e.admission!==void 0&&(e.admission.sourceCommit!==e.intent.sourceCommit||e.admission.sourceArchiveSha256!==e.intent.archiveSha256||e.admission.packageVersion!==e.intent.packageVersion||e.admission.configDigest!==e.intent.configDigest||e.admission.repository!==e.intent.repository||e.admission.cliPath!==pC(e.intent.runtimeDirectory,e.intent.nativePluginRoot).cliPath||e.admission.mcpLauncherPath!==pC(e.intent.runtimeDirectory,e.intent.nativePluginRoot).mcpLauncherPath||e.admission.pluginManifestPath!==pC(e.intent.runtimeDirectory,e.intent.nativePluginRoot).pluginManifestPath))&&t.addIssue({code:`custom`,message:`Runtime stage identity or completion is corrupt.`})});function fC(e){if(!oe(e)||T(e)!==e)throw new L(`Runtime setup paths must be absolute and canonical.`);let t=e.split(ce).filter(Boolean),n=ce;for(let e of t){n=w(n,e);try{if(c(n).isSymbolicLink())throw new L(`Runtime setup path contains a symbolic link.`)}catch(e){if(e.code!==`ENOENT`)throw e}}return e}function pC(e,t){let n=w(e,`node_modules`,`@aviaratech`,`ai-delivery`),r=t??w(n,`plugins`,`ai-delivery`);return{cliPath:t?w(r,`runtime`,`dist`,`cli.js`):w(n,`dist`,`cli.js`),mcpLauncherPath:w(r,`dist`,`mcp-launcher.js`),pluginManifestPath:w(r,`.claude-plugin`,`plugin.json`)}}function mC(e,t){if(t!==void 0&&(fC(t),t===e||t.startsWith(`${e}${ce}`)||e.startsWith(`${t}${ce}`)))throw new L(`Native plugin cache and owned runtime stage paths must not overlap.`)}function hC(e){if(e.nativePluginRoot===void 0)return;mC(e.runtimeDirectory,e.nativePluginRoot);let t=fC(w(e.runtimeDirectory,`node_modules/@aviaratech/ai-delivery/plugins/ai-delivery`)),n=0,r=(e,t,i)=>{if(i>16||++n>4096)throw new L(`Native plugin inventory exceeds the reviewed layout bound.`);let a=c(e),o=c(t);if(a.isDirectory()&&o.isDirectory()){let n=p(e).sort();if(JSON.stringify(n)!==JSON.stringify(p(t).sort()))throw new L(`Selected native plugin inventory disagrees with reviewed archive bytes.`);for(let a of n)r(w(e,a),w(t,a),i+1)}else if(!a.isFile()||!o.isFile()||a.nlink!==1||o.nlink!==1||a.size!==o.size||!d(e).equals(d(t)))throw new L(`Selected native plugin files disagree with reviewed archive bytes.`)};try{r(t,e.nativePluginRoot,0)}catch(e){throw e instanceof L?e:new L(`Selected native plugin cannot be matched to reviewed archive bytes.`)}}function gC(e,t){fC(e),cC.parse(t);let n=c(e);if(!n.isFile()||n.nlink!==1)throw new L(`Reviewed runtime archive bytes do not match the expected digest.`);let r=d(e);if(V(r)!==t)throw new L(`Reviewed runtime archive bytes do not match the expected digest.`);return r}function _C(e){let t=fC(w(e.runtimeDirectory,`reviewed-archive.tgz`));if(V(H(t))!==e.archiveSha256)throw new L(`Runtime stage archive snapshot bytes changed.`);return t}async function vC(e,t,n,r){if(await n?.(),typeof e.identity!=`string`||!e.identity.trim())throw new L(`Runtime setup requires an explicit configured author identity.`);let i=id(e.repoRoot);if(i!==od(i))throw new L(`Runtime setup requires the primary consumer controller checkout.`);if(cd(i),sd(i).sha!==e.expectedSourceCommit)throw new L(`Primary controller source commit changed.`);fC(e.runtimeDirectory);let a=await hv({identity:e.identity,repoRoot:i,role:`author`,...r===void 0?{}:{signal:r},...e.personalAuth===void 0?{}:{personalAuth:e.personalAuth}});await n?.();let o=Ih({commandName:t,deliveryConfig:a.config,identity:e.identity,...e.personalAuth===void 0?{}:{personalAuth:e.personalAuth}});if(o.error)throw new L(o.error);if(!a.configuration||a.configuration.configDigest!==e.expectedConfigDigest)throw new L(`Primary controller resolver config digest changed.`);let s=await JS(a,void 0,void 0,`publication`,n===void 0||r===void 0?void 0:{signal:r,checkResources:n});if(await n?.(),cd(i),sd(i).sha!==e.expectedSourceCommit)throw new L(`Primary controller source commit changed during preflight.`);return{root:i,configuration:a.configuration,reviewRoute:s}}function yC(e){fC(e);let t=c(e);if(!t.isDirectory()||(t.mode&511)!=448)throw new L(`Runtime stage directory must be private and owned.`);let n;try{n=dC.parse(JSON.parse(H(w(e,`runtime-stage.json`)).toString(`utf8`)))}catch{throw new L(`Runtime stage is unowned, incompatible or corrupt.`)}if(n.intent.runtimeDirectory!==e||t.dev!==n.directory.device||t.ino!==n.directory.inode)throw new L(`Runtime stage directory ownership changed.`);return n.status===`complete`&&(_C(n.intent),hC(n.intent)),n}function bC(e,t){let n=dC.parse({...t,recordId:B(t)});zv(w(e,`runtime-stage.json`),n);let r=yC(e);if(r.recordId!==n.recordId)throw new L(`Runtime stage completion readback changed.`);return r}function xC(e){let t=u(e,`r`);try{o(t)}finally{n(t)}}function SC(e){let t=H(e),r=u(e,`r`);try{o(r)}finally{n(r)}if(xC(C(e)),!H(e).equals(t))throw new L(`Runtime admission third-party replacement conflict.`)}function CC(e,t,n){if(!e.admission)throw new L(`Runtime stage completion is missing.`);return{stageId:e.stageId,admission:e.admission,reused:n,reviewRoute:t,launch:{cli:{command:process.execPath,args:[e.admission.cliPath]},mcp:{command:process.execPath,args:[e.admission.mcpLauncherPath]}}}}function wC(e,t,n){if(e.intent.repoRoot!==t.root||e.intent.repository!==t.configuration.config.repository||e.intent.sourceCommit!==n.expectedSourceCommit||e.intent.configDigest!==n.expectedConfigDigest)throw new L(`Runtime stage primary controller source or configuration changed.`);if(e.intent.reviewRouteDigest!==B(t.reviewRoute))throw new L(`Runtime stage configured actors or review route changed.`)}async function TC(e){if(e.authority!==`runtime:stage`)throw new L(`Explicit runtime:stage authority is required.`);let t=lC.parse({maxAggregateRssBytes:1024**3,minFreeDiskBytes:256*1024**2,maxNewOutputBytes:512*1024**2,maxCapturedOutputBytes:1024**2,...e.resourceBounds});return fC(e.runtimeDirectory),mC(e.runtimeDirectory,e.nativePluginRoot),Cb(e.repoRoot,async n=>{let r=await vC(e,`runtime:stage`,n.checkResources,n.signal);gC(e.archivePath,e.expectedArchiveSha256);let a=uC.parse({archivePath:e.archivePath,archiveSha256:e.expectedArchiveSha256,configDigest:e.expectedConfigDigest,sourceCommit:e.expectedSourceCommit,packageVersion:e.packageVersion,repoRoot:r.root,repository:r.configuration.config.repository,reviewRouteDigest:B(r.reviewRoute),runtimeDirectory:e.runtimeDirectory,resourceBounds:t,...e.nativePluginRoot===void 0?{}:{nativePluginRoot:e.nativePluginRoot}}),o=B(a);if(n.bindCapturedOutput(o),i(e.runtimeDirectory)){let t=yC(e.runtimeDirectory);if(t.stageId!==o)throw new L(`Runtime stage belongs to an incompatible setup intent.`);if(t.status===`complete`){let r=await vC(e,`runtime:stage`,n.checkResources,n.signal);return wC(t,r,e),gC(a.archivePath,a.archiveSha256),SC(w(e.runtimeDirectory,`reviewed-archive.tgz`)),_C(a),Xv(t.admission,r.configuration,t.admission.cliPath),SC(w(e.runtimeDirectory,`runtime-stage.json`)),xC(C(e.runtimeDirectory)),await n.checkResources(),CC(t,r.reviewRoute,!0)}n.assertQuiescent(),_(e.runtimeDirectory,{recursive:!0})}Lv(C(e.runtimeDirectory)),l(e.runtimeDirectory,{mode:448});let s=c(e.runtimeDirectory),u={schemaVersion:`ai-delivery.runtime-stage@1`,stageId:o,intent:a,directory:{device:s.dev,inode:s.ino},status:`incomplete`},d=!1;try{if(xC(C(e.runtimeDirectory)),bC(e.runtimeDirectory,u),d=!0,e.signal?.aborted)throw new L(`Runtime stage cancelled.`);let r=gC(e.archivePath,e.expectedArchiveSha256);if(!Number.isSafeInteger(t.maxNewOutputBytes)||r.length>=t.maxNewOutputBytes)throw new L(`Reviewed archive snapshot exceeds the stage output limit.`);gd(w(e.runtimeDirectory,`reviewed-archive.tgz`),r);let i=_C(a),o=w(e.runtimeDirectory,`.npm`),s=w(o,`cache`),c=w(o,`logs`),l=w(o,`tmp`);for(let e of[s,c,l])Lv(e);let f=w(o,`user.npmrc`),p=w(o,`global.npmrc`);gd(f,Buffer.alloc(0)),gd(p,Buffer.alloc(0)),await n.checkResources(),await n.run([`npm`,`install`,`--prefix`,e.runtimeDirectory,`--omit=dev`,`--ignore-scripts`,`--no-audit`,`--no-fund`,`--package-lock=false`,`--cache`,s,`--logs-dir`,c,`--logs-max`,`0`,`--userconfig`,f,`--globalconfig`,p,i],{...t,maxNewOutputBytes:t.maxNewOutputBytes-r.length,outputRoots:[e.runtimeDirectory]},e.signal,{...process.env,TMPDIR:l,TMP:l,TEMP:l},e.runtimeDirectory);let m=await vC(e,`runtime:stage`,n.checkResources,n.signal);wC({...u,recordId:B(u)},m,e),gC(e.archivePath,e.expectedArchiveSha256),_C(a),hC(a);let h=Zv({...pC(e.runtimeDirectory,e.nativePluginRoot),packageVersion:e.packageVersion,sourceArchiveSha256:e.expectedArchiveSha256,sourceCommit:e.expectedSourceCommit,configuration:m.configuration});if(hC(a),e.signal?.aborted)throw new L(`Runtime stage cancelled.`);n.assertQuiescent(),Xv(h,m.configuration,h.cliPath),await n.checkResources();let g=bC(e.runtimeDirectory,{...u,status:`complete`,admission:h});return Xv(g.admission,m.configuration,g.admission.cliPath),CC(g,m.reviewRoute,!1)}catch(t){if(d){n.assertQuiescent();let t=yC(e.runtimeDirectory);if(t.stageId!==o)throw new L(`Runtime stage cleanup ownership changed.`);if(t.status===`incomplete`)_(e.runtimeDirectory,{recursive:!0});else{let r=await vC(e,`runtime:stage`,n.checkResources,n.signal);return wC(t,r,e),gC(a.archivePath,a.archiveSha256),SC(w(e.runtimeDirectory,`reviewed-archive.tgz`)),_C(a),Xv(t.admission,r.configuration,t.admission.cliPath),SC(w(e.runtimeDirectory,`runtime-stage.json`)),xC(C(e.runtimeDirectory)),CC(t,r.reviewRoute,!0)}}else{n.assertQuiescent();let t=c(e.runtimeDirectory);if(t.dev!==s.dev||t.ino!==s.ino||t.isSymbolicLink())throw new L(`Runtime stage cleanup ownership changed.`);_(e.runtimeDirectory,{recursive:!0})}throw t}},{bounds:{...t,outputRoots:[e.runtimeDirectory]},maxCapturedOutputBytes:t.maxCapturedOutputBytes,...e.signal===void 0?{}:{signal:e.signal}})}var EC=class extends L{admissionId;stageId;status=`commit-status-unknown`;constructor(e,t){super(`Runtime admission commit-status-unknown for ${e}; retry runtime:admit with the same stage ${t} to reconcile durability.`),this.admissionId=e,this.stageId=t}};async function DC(e){if(e.authority!==`runtime:admit`)throw new L(`Explicit runtime:admit authority is required.`);cC.parse(e.stageId),e.expectedPriorAdmissionSha256!==null&&cC.parse(e.expectedPriorAdmissionSha256);let t=await vC(e,`runtime:admit`),n=w(ad(t.root),`ai-delivery`,`runtime-admission.json`);return fC(n),Lv(C(n)),py(n,{projectRoot:t.root,timeout:200,operation:async()=>{let t=yC(e.runtimeDirectory);if(t.stageId!==e.stageId||t.status!==`complete`||!t.admission)throw new L(`Exact completed runtime stage identity is required.`);let r=await vC(e,`runtime:admit`);wC(t,r,e),gC(t.intent.archivePath,t.intent.archiveSha256),_C(t.intent),Xv(t.admission,r.configuration,t.admission.cliPath);let a=Buffer.from(`${JSON.stringify(t.admission,null,2)}\n`);fC(n);let o=i(n)?H(n):void 0,s=()=>{if(fC(n),_C(t.intent),Xv(t.admission,r.configuration,t.admission.cliPath),!i(n)||!H(n).equals(a))throw new L(`Runtime admission third-party replacement conflict; current bytes preserved.`);try{SC(n)}catch{throw!i(n)||!H(n).equals(a)?new L(`Runtime admission third-party replacement conflict; current bytes preserved.`):new EC(t.admission.admissionId,t.stageId)}return{admission:t.admission,reused:!0}};if(o?.equals(a))return s();if((o===void 0?null:V(o))!==e.expectedPriorAdmissionSha256)throw new L(`Runtime admission prior-byte compare-and-swap conflict; current bytes preserved.`);let c=await vC(e,`runtime:admit`);wC(t,c,e),gC(t.intent.archivePath,t.intent.archiveSha256),_C(t.intent),Xv(t.admission,c.configuration,t.admission.cliPath),fC(n);let l=i(n)?H(n):void 0;if((l===void 0?null:V(l))!==e.expectedPriorAdmissionSha256)throw new L(`Runtime admission prior-byte compare-and-swap conflict; current bytes preserved.`);try{zv(n,t.admission)}catch(t){let r=i(n)?H(n):void 0;if(r?.equals(a))return s();throw(r===void 0?null:V(r))===e.expectedPriorAdmissionSha256?t:new L(`Runtime admission third-party replacement conflict; current bytes preserved.`)}return s(),{admission:t.admission,reused:!1}}})}var U=A().int().positive(),OC=M(k().trim().min(1)),kC=k().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u).optional(),AC={blockedBy:M(U).optional(),blocks:M(U).optional(),overrideReason:w_.optional(),body:k().optional(),issueType:k().min(1).optional(),labels:OC.optional(),milestone:U.optional(),parentIssueNumber:U.optional(),points:U.optional(),priority:k().min(1).optional(),repo:k().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u).optional(),title:k().trim().min(1).max(256)},jC=P({repo:kC,issueNumber:U,investigationWorktree:k().min(1),expectedHeadSha:k().regex(/^[a-f0-9]{40}$/u)}),MC=P({...AC,title:AC.title.optional(),issueNumber:U.optional(),request:k().min(1).optional(),requestId:k().trim().min(1).max(256).optional(),resumeCreated:j().optional(),branch:k().min(1).optional()}),NC=P({repo:kC,issueNumber:U,prNumber:U,nonClosing:j().optional(),reviewedHeadSha:k().regex(/^[a-f0-9]{40}$/u).optional(),strategy:F([`merge`,`squash`,`rebase`]).optional(),dryRun:j().optional()}),PC=P({repo:kC,issueNumber:U,investigation:I(!0),resultPath:k().min(1),authorityCommentId:U.optional(),acceptanceCommentId:U.optional(),dryRun:j().optional()});function FC(e,t,n){let r=e.safeParse(t);r.success||n.addIssue({code:`custom`,message:r.error.message})}var IC={repo:kC,state:F([`open`,`closed`,`all`]).optional(),labels:M(k().min(1).regex(/^[^"\\\r\n]+$/u)).optional(),parentIssueNumber:U.nullable().optional(),issueType:k().min(1).optional(),projectStatus:F([`Todo`,`In Progress`,`Blocked`,`Done`]).nullable().optional(),updatedSince:yu({offset:!0}).optional(),page:U.optional(),perPage:U.max(100).optional()},LC=k().trim().min(1).max(256).regex(/^[^"\\\r\n]+$/u),RC={repo:kC,identity:k().min(1).optional(),expectedSourceCommit:k().regex(/^[a-f0-9]{40}$/u),expectedConfigDigest:k().regex(/^sha256:[a-f0-9]{64}$/u),runtimeDirectory:k().min(1)},zC=[{name:`delivery_health`,commandName:`health`,description:`Read bounded native delivery health for an explicit repository and UTC window`,inputSchema:Gu},{name:`issue_comment`,commandName:`comment`,description:`Post a typed issue journal with authoritative comment readback`,inputSchema:P({...lv.shape,repo:kC}).superRefine(({repo:e,...t},n)=>{let r=lv.safeParse(t);if(!r.success)for(let e of r.error.issues)n.addIssue({code:`custom`,path:e.path,message:e.message})})},{name:`runtime_stage`,commandName:`runtime:stage`,description:`Explicitly stage a reviewed local public archive without host activation or admission`,inputSchema:P({...RC,authority:I(`runtime:stage`),archivePath:k().min(1),expectedArchiveSha256:k().regex(/^sha256:[a-f0-9]{64}$/u),packageVersion:k().regex(/^\d+\.\d+\.\d+$/u),nativePluginRoot:k().min(1).optional(),resourceBounds:P({maxAggregateRssBytes:A().int().positive().safe(),minFreeDiskBytes:A().int().positive().safe(),maxNewOutputBytes:A().int().positive().safe(),maxCapturedOutputBytes:A().int().positive().safe().max(8*1024**2).optional()}).optional()})},{name:`runtime_admit`,commandName:`runtime:admit`,description:`Explicitly admit an exact completed stage with prior-byte compare-and-swap and reconciliation`,inputSchema:P({...RC,authority:I(`runtime:admit`),stageId:k().regex(/^sha256:[a-f0-9]{64}$/u),expectedPriorAdmissionSha256:k().regex(/^sha256:[a-f0-9]{64}$/u).nullable()})},{name:`issue_create`,commandName:`create`,description:`Create a native GitHub tracking issue with configured metadata and relationships`,issueContract:U_,inputSchema:K_(P({...AC,...W_,title:F_.shape.title}))},{name:`issue_start`,commandName:`start`,description:`Start a linked issue, or prospectively register an unchanged host-created investigation worktree`,inputSchema:MC.extend({investigationWorktree:k().optional(),expectedHeadSha:k().optional()}).superRefine((e,t)=>FC(e.investigationWorktree!==void 0||e.expectedHeadSha!==void 0?jC:MC,e,t))},{name:`issue_list`,commandName:`list`,description:`List repository issues with native filters, named organization fields and pagination`,inputSchema:P({...IC,query:LC.optional()})},{name:`issue_search`,commandName:`search`,description:`Search literal issue text in the selected repository with native filters and pagination`,inputSchema:P({...IC,query:LC})},{name:`issue_update`,commandName:`update`,description:`Update native issue fields and exact relationship sets with readback`,inputSchema:K_(P({...W_,repo:kC,blockedBy:M(U).optional(),blocks:M(U).optional(),overrideReason:w_.optional(),body:k().optional(),issueNumber:U,issueType:W_.issueType,labels:OC.optional(),milestone:U.nullable().optional(),parentIssueNumber:U.nullable().optional(),park:I(!0).optional(),points:W_.points,priority:k().min(1).optional(),state:F([`open`,`closed`]).optional(),preserveHistory:j().optional(),closeReason:F([`completed`,`not_planned`,`duplicate`]).optional(),supersededBy:U.optional(),title:W_.title}).superRefine((e,t)=>{(e.closeReason!==void 0||e.supersededBy!==void 0)&&e.state!==`closed`&&t.addIssue({code:`custom`,path:[`state`],message:`Closure details require state closed`,params:{issueCode:`closure.state`}})}))},{name:`issue_info`,commandName:`info`,description:`Read live issue metadata, relationships and Project status`,inputSchema:P({issueNumber:U,repo:kC})},{name:`issue_ready_check`,commandName:`ready:check`,description:`Evaluate deterministic readiness from live native issue state`,inputSchema:P({issueNumber:U,repo:AC.repo})},{name:`issue_pr_create`,commandName:`pr:create`,description:`Create or reuse a PR from its GitHub-linked issue branch`,inputSchema:P({repo:kC,issueNumber:U,prNumber:U.optional(),nonClosing:j().optional(),body:k().min(1).optional(),draft:j().optional(),dryRun:j().optional(),title:k().min(1).optional(),headBranch:k().min(1).optional()})},{name:`issue_pr_info`,commandName:`pr:info`,description:`Inspect a PR by number or its GitHub-linked issue branch`,inputSchema:P({repo:kC,issueNumber:U.optional(),prNumber:U.optional(),nonClosing:j().optional()})},{name:`issue_pr_review`,commandName:`pr:review`,description:`Submit one existing exact-head independent review with the reviewer App role`,inputSchema:P({repo:kC,issueNumber:U,prNumber:U,nonClosing:j().optional(),artifact:k().min(1),identity:k().min(1).optional(),dryRun:j().optional()})},{name:`issue_pr_merge`,commandName:`pr:merge`,description:`Guarded exact-head merge with live blocker, check and review readback`,inputSchema:P({repo:kC,issueNumber:U,prNumber:U,nonClosing:j().optional(),reviewedHeadSha:k().regex(/^[a-f0-9]{40}$/u).optional(),strategy:F([`merge`,`squash`,`rebase`]).optional(),dryRun:j().optional()})},{name:`issue_finish`,commandName:`finish`,description:`Finish merged delivery, or remove a prospectively registered unchanged investigation with native acceptance`,inputSchema:NC.extend({prNumber:U.optional(),investigation:I(!0).optional(),resultPath:k().optional(),authorityCommentId:U.optional(),acceptanceCommentId:U.optional()}).superRefine((e,t)=>FC(e.investigation===!0?PC:NC,e,t))},{name:`issue_worktree_transition_inspect`,commandName:`worktree:transition:inspect`,description:`Read a legacy issue row, original evidence and exact closure gaps without changing ownership`,inputSchema:P({repo:kC,issueNumber:U,purpose:F([`active-resume`,`merged-cleanup`]),disposition:F([`retain`,`remove`]).optional(),terminalPrNumber:U.optional(),retainedHoldCommentIds:M(U).optional(),retainedAdmissionPath:k().min(1).optional(),retainedArchivePath:k().min(1).optional()})},{name:`issue_worktree_transition_apply`,commandName:`worktree:transition:apply`,description:`Apply or resume one exact independently accepted transition with immutable preservation and closure proof`,inputSchema:P({repo:kC,authority:I(`worktree:transition`),planPath:k().min(1),expectedPlanId:k().regex(/^sha256:[a-f0-9]{64}$/u),relinquishmentCommentId:U,acceptanceCommentId:U})}];function BC(e){return zC.find(t=>t.name===e)??null}function VC(e,t){let n=e[t];if(typeof n!=`number`||!Number.isSafeInteger(n)||n<=0)throw new L(`${t} must be positive.`);return n}function HC(e,t){return typeof e[t]==`string`?e[t]:void 0}function UC(e,t){let n=HC(e,t);if(!n?.trim())throw new L(`${t} is required.`);return n}function WC(e){let{issueNumber:t,request:n,requestId:r,repo:i,resumeCreated:a,branch:o,...s}=e;return{...s,issueNumber:VC({issueNumber:t},`issueNumber`)}}async function GC(e,t,n=`author`){let r=await jh(),i=e.identity??r.roles[n].identity,a=Ih({commandName:t,deliveryConfig:r,identity:i,...e.personalAuth===void 0?{}:{personalAuth:e.personalAuth}});if(a.error)throw new L(a.error);return hv({identity:i,repoRoot:e.repoRoot,role:n,...e.repo===void 0?{}:{repository:e.repo},...e.personalAuth===void 0?{}:{personalAuth:e.personalAuth},...e.signal===void 0?{}:{signal:e.signal}})}async function KC(e,t){let n=t.issueNumber===void 0?void 0:VC(t,`issueNumber`),r,i,a,o=!1,s=`branch-or-journal`,c=(o,s)=>({status:`created-not-started`,repository:e.config.repository,createdIssue:r,failure:{phase:o,message:s instanceof Error?s.message:String(s)},safeResume:{tool:`issue_start`,arguments:{...o===`tracking`?{...t,...i===void 0?{}:{body:i},resumeCreated:!0}:{},repo:e.config.repository,issueNumber:n,...(a?.branch??HC(t,`branch`))===void 0?{}:{branch:a?.branch??HC(t,`branch`)}}}});if(n===void 0){let a=HC(t,`title`)??UC(t,`request`),o={...t,title:a,body:HC(t,`body`)??HC(t,`request`)??a};o.body=vv(o);let s=B(Object.fromEntries(Object.entries({title:a,body:o.body,issueType:o.issueType,points:o.points,priority:o.priority,labels:o.labels,blockedBy:o.blockedBy,blocks:o.blocks,overrideReason:o.overrideReason,parentIssueNumber:o.parentIssueNumber,milestone:o.milestone,branch:t.branch}).filter(([,e])=>e!==void 0))),l=HC(t,`requestId`)??s,u=`<!-- ai-delivery-start: ${B({repository:e.config.repository.toLowerCase(),requestKey:l})} -->`;o.body=`${o.body}\n\n<!-- ai-delivery-start-intent: ${s} -->\n${u}`,i=o.body;let d=!1,f=[];for(let t=1;t<=20;t++){let n=(await e.clients.rest.issues.listForRepo({...e.repo,state:`all`,page:t,per_page:100})).data;if(f.push(...n.filter(e=>!(`pull_request`in e)&&e.body?.includes(u))),n.length<100){d=!0;break}}if(!d)throw new L(`Issue-start retry search exceeds the bounded readback window; select a known issue number.`);if(f.length>1)throw new L(`Conflicting issues claim the same start request.`);let p=f[0];if(p&&(p.title!==a||p.body!==o.body||p.state!==`open`))throw new L(`Prior issue-start request conflicts with the requested intent or state.`);try{p?(r={number:p.number,title:p.title,url:p.html_url},n=p.number,await kv(e,{...o,issueNumber:n})):(r=(await bv(e,o)).created,n=r.number)}catch(e){if(e instanceof yv)r=e.created,n=r.number;else if(!r)throw e;return c(`tracking`,e)}}else if(t.resumeCreated===!0){let i=(await e.clients.rest.issues.get({...e.repo,issue_number:n})).data;if(i.number!==n||`pull_request`in i)throw new L(`Known-created issue readback disagrees.`);r={number:n,title:i.title,url:i.html_url};try{await kv(e,WC(t))}catch(e){return c(`tracking`,e)}}try{let r=await Mv(e,n);if(!r.ready)throw new Y_(r.failures);return o=!0,a=await Fv(e,n,HC(t,`branch`)),s=`project-status`,await Iv(e,n),s=`journal`,await mv(e,n),{issueNumber:n,repository:e.config.repository,branch:a.branch,headSha:a.headSha,reused:a.reused}}catch(i){if(r)return c(s,i);if(!o)throw i;return{status:`start-incomplete`,issueNumber:n,repository:e.config.repository,failure:{phase:s,message:i instanceof Error?i.message:String(i)},safeResume:{tool:`issue_start`,arguments:{repo:e.config.repository,issueNumber:n,...(a?.branch??HC(t,`branch`))===void 0?{}:{branch:a?.branch??HC(t,`branch`)}}}}}}async function qC(e,t,n){let r=BC(e);if(!r)throw new L(`Unknown ai-delivery tool ${e}.`);let{repo:i,...a}=r.inputSchema.parse(t);if(e===`issue_finish`&&a.nonClosing===!0)throw new L(`Non-closing delivery cannot finish or close its retained issue.`);if(i!==void 0&&n.repo!==void 0&&i!==n.repo)throw new L(`Tool and execution repository selectors disagree.`);e===`issue_create`&&vv(a);let o=typeof i==`string`?i:n.repo,s={...n,...o===void 0?{}:{repo:o}},c=e===`runtime_stage`||e===`runtime_admit`||e.startsWith(`issue_worktree_transition_`)||e===`issue_start`&&a.investigationWorktree!==void 0||e===`issue_finish`&&a.investigation===!0,l=n.repoRoot;if(c){let t=await jh();if(l=td({repository:o??(()=>{let e=ed(l,`origin`);return`${e.owner}/${e.repo}`})(),launchDirectory:l,checkoutRoots:t.checkoutRoots}),e===`runtime_stage`||e===`runtime_admit`){let r={...a,repoRoot:l,identity:HC(a,`identity`)??n.identity??t.roles.author.identity,...n.personalAuth===void 0?{}:{personalAuth:n.personalAuth},...n.signal===void 0?{}:{signal:n.signal}};return e===`runtime_stage`?TC(r):DC(r)}}let u=e===`issue_pr_review`?HC(a,`identity`):void 0,d=await GC({...s,...u===void 0?{}:{identity:u}},r.commandName,e===`issue_pr_review`?`reviewer`:`author`);switch(c&&(d.root=l),e){case`delivery_health`:return qu(d,{...a,repo:o});case`issue_comment`:return pv(d,a);case`issue_create`:return bv(d,a);case`issue_start`:return a.investigationWorktree===void 0?KC(d,a):oC(d,{issueNumber:VC(a,`issueNumber`),investigationWorktree:UC(a,`investigationWorktree`),expectedHeadSha:UC(a,`expectedHeadSha`)});case`issue_update`:return Ov(d,a);case`issue_list`:case`issue_search`:return Tv(d,a);case`issue_info`:return Av(d,VC(a,`issueNumber`));case`issue_ready_check`:return Mv(d,VC(a,`issueNumber`));case`issue_pr_create`:return YS(d,{...a.prNumber===void 0?{}:{prNumber:VC(a,`prNumber`)},issueNumber:VC(a,`issueNumber`),...a.nonClosing===void 0?{}:{nonClosing:a.nonClosing===!0},...a.body===void 0?{}:{body:UC(a,`body`)},...a.title===void 0?{}:{title:UC(a,`title`)},...a.headBranch===void 0?{}:{headBranch:UC(a,`headBranch`)},draft:a.draft!==!1,dryRun:a.dryRun===!0});case`issue_pr_info`:return US(d,a);case`issue_pr_review`:return XS(d,{artifact:UC(a,`artifact`),issueNumber:VC(a,`issueNumber`),...a.nonClosing===void 0?{}:{nonClosing:a.nonClosing===!0},prNumber:VC(a,`prNumber`),dryRun:a.dryRun===!0});case`issue_pr_merge`:case`issue_finish`:{if(e===`issue_finish`&&a.investigation===!0)return sC(d,{issueNumber:VC(a,`issueNumber`),resultPath:UC(a,`resultPath`),...a.authorityCommentId===void 0?{}:{authorityCommentId:VC(a,`authorityCommentId`)},...a.acceptanceCommentId===void 0?{}:{acceptanceCommentId:VC(a,`acceptanceCommentId`)},dryRun:a.dryRun===!0});let t={issueNumber:VC(a,`issueNumber`),...a.nonClosing===void 0?{}:{nonClosing:a.nonClosing===!0},prNumber:VC(a,`prNumber`),...a.strategy===void 0?{}:{strategy:a.strategy},...a.reviewedHeadSha===void 0?{}:{reviewedHeadSha:UC(a,`reviewedHeadSha`)},dryRun:a.dryRun===!0};return e===`issue_finish`?$S(d,t):QS(d,t)}case`issue_worktree_transition_inspect`:return cS(d,{...a,...n.runtimeEntryPath===void 0?{}:{runtimeEntryPath:n.runtimeEntryPath}});case`issue_worktree_transition_apply`:return Zx(d,{authority:`worktree:transition`,planPath:UC(a,`planPath`),expectedPlanId:UC(a,`expectedPlanId`),relinquishmentCommentId:VC(a,`relinquishmentCommentId`),acceptanceCommentId:VC(a,`acceptanceCommentId`),...n.runtimeEntryPath===void 0?{}:{runtimeEntryPath:n.runtimeEntryPath}})}}var JC;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function n(e){throw Error()}e.assertNever=n,e.arrayToEnum=e=>{let t={};for(let n of e)t[n]=n;return t},e.getValidEnumValues=t=>{let n=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),r={};for(let e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(let n of e)if(t(n))return n},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function r(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=r,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(JC||={});var YC;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(YC||={});var W=JC.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),XC=e=>{switch(typeof e){case`undefined`:return W.undefined;case`string`:return W.string;case`number`:return Number.isNaN(e)?W.nan:W.number;case`boolean`:return W.boolean;case`function`:return W.function;case`bigint`:return W.bigint;case`symbol`:return W.symbol;case`object`:return Array.isArray(e)?W.array:e===null?W.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?W.promise:typeof Map<`u`&&e instanceof Map?W.map:typeof Set<`u`&&e instanceof Set?W.set:typeof Date<`u`&&e instanceof Date?W.date:W.object;default:return W.unknown}},G=JC.arrayToEnum([`invalid_type`,`invalid_literal`,`custom`,`invalid_union`,`invalid_union_discriminator`,`invalid_enum_value`,`unrecognized_keys`,`invalid_arguments`,`invalid_return_type`,`invalid_date`,`invalid_string`,`too_small`,`too_big`,`invalid_intersection_types`,`not_multiple_of`,`not_finite`]),ZC=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`)i.unionErrors.map(r);else if(i.code===`invalid_return_type`)r(i.returnTypeError);else if(i.code===`invalid_arguments`)r(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r],a=r===i.path.length-1;if(n===`_errors`){a&&e._errors.push(t(i)),r++;continue}Object.prototype.hasOwnProperty.call(e,n)||(n===`__proto__`?Object.defineProperty(e,n,{value:{_errors:[]},writable:!0,enumerable:!0,configurable:!0}):e[n]={_errors:[]}),e=e[n],a&&e._errors.push(t(i)),r++}}};return r(this),n}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,JC.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t=Object.create(null),n=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};ZC.create=e=>new ZC(e);var QC=(e,t)=>{let n;switch(e.code){case G.invalid_type:n=e.received===W.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case G.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,JC.jsonStringifyReplacer)}`;break;case G.unrecognized_keys:n=`Unrecognized key(s) in object: ${JC.joinValues(e.keys,`, `)}`;break;case G.invalid_union:n=`Invalid input`;break;case G.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${JC.joinValues(e.options)}`;break;case G.invalid_enum_value:n=`Invalid enum value. Expected ${JC.joinValues(e.options)}, received '${e.received}'`;break;case G.invalid_arguments:n=`Invalid function arguments`;break;case G.invalid_return_type:n=`Invalid function return type`;break;case G.invalid_date:n=`Invalid date`;break;case G.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:JC.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case G.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case G.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case G.custom:n=`Invalid input`;break;case G.invalid_intersection_types:n=`Intersection results could not be merged`;break;case G.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case G.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,JC.assertNever(e)}return{message:n}},$C=QC;function ew(){return $C}var tw=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s=``,c=r.filter(e=>!!e).slice().reverse();for(let e of c)s=e(o,{data:t,defaultError:s}).message;return{...i,path:a,message:s}};function K(e,t){let n=ew(),r=tw({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===QC?void 0:QC].filter(e=>!!e)});e.common.issues.push(r)}var nw=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return q;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(t,n){let r=[];for(let e of n){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return e.mergeObjectSync(t,r)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return q;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}},q=Object.freeze({status:`aborted`}),rw=e=>({status:`dirty`,value:e}),iw=e=>({status:`valid`,value:e}),aw=e=>e.status===`aborted`,ow=e=>e.status===`dirty`,sw=e=>e.status===`valid`,cw=e=>typeof Promise<`u`&&e instanceof Promise,J;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(J||={});var lw=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},uw=(e,t)=>{if(sw(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){if(this._error)return this._error;let t=new ZC(e.common.issues);return this._error=t,this._error}}};function Y(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}var dw=class{get description(){return this._def.description}_getType(e){return XC(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:XC(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new nw,ctx:{common:e.parent.common,data:e.data,parsedType:XC(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(cw(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:XC(e)};return uw(n,this._parseSync({data:e,path:n.path,parent:n}))}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:XC(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return sw(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>sw(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:XC(e)},r=this._parse({data:e,path:n.path,parent:n});return uw(n,await(cw(r)?r:Promise.resolve(r)))}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:G.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new mT({schema:this,typeName:X.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return hT.create(this,this._def)}nullable(){return gT.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Yw.create(this)}promise(){return pT.create(this,this._def)}or(e){return Qw.create([this,e],this._def)}and(e){return nT.create(this,e,this._def)}transform(e){return new mT({...Y(this._def),schema:this,typeName:X.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new _T({...Y(this._def),innerType:this,defaultValue:t,typeName:X.ZodDefault})}brand(){return new bT({typeName:X.ZodBranded,type:this,...Y(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new vT({...Y(this._def),innerType:this,catchValue:t,typeName:X.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return xT.create(this,e)}readonly(){return ST.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},fw=/^c[^\s-]{8,}$/i,pw=/^[0-9a-z]+$/,mw=/^[0-9A-HJKMNP-TV-Z]{26}$/i,hw=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,gw=/^[a-z0-9_-]{21}$/i,_w=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,vw=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,yw=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,bw=`^[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`,xw,Sw=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Cw=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ww=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Tw=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ew=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Dw=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ow=`((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`,kw=RegExp(`^${Ow}$`);function Aw(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let n=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function jw(e){return RegExp(`^${Aw(e)}$`)}function Mw(e){let t=`${Ow}T${Aw(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function Nw(e,t){return!((t!==`v4`&&t||!Sw.test(e))&&(t!==`v6`&&t||!ww.test(e)))}function Pw(e,t){if(!_w.test(e))return!1;try{let[n]=e.split(`.`);if(!n)return!1;let r=n.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(n.length+(4-n.length%4)%4,`=`),i=JSON.parse(atob(r));return!(typeof i!=`object`||!i||`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&i.alg!==t)}catch{return!1}}function Fw(e,t){return!((t!==`v4`&&t||!Cw.test(e))&&(t!==`v6`&&t||!Tw.test(e)))}var Iw=class e extends dw{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==W.string){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.string,received:t.parsedType}),q}let t=new nw,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),K(n,{code:G.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),K(n,{code:G.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?K(n,{code:G.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&K(n,{code:G.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)yw.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`email`,code:G.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)xw||=new RegExp(bw,`u`),xw.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`emoji`,code:G.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)hw.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`uuid`,code:G.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)gw.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`nanoid`,code:G.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)fw.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`cuid`,code:G.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)pw.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`cuid2`,code:G.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)mw.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`ulid`,code:G.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),K(n,{validation:`url`,code:G.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`regex`,code:G.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),K(n,{code:G.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),K(n,{code:G.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),K(n,{code:G.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?Mw(r).test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{code:G.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?kw.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{code:G.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?jw(r).test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{code:G.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?vw.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`duration`,code:G.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?Nw(e.data,r.version)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`ip`,code:G.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?Pw(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`jwt`,code:G.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?Fw(e.data,r.version)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`cidr`,code:G.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?Ew.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`base64`,code:G.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?Dw.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`base64url`,code:G.invalid_string,message:r.message}),t.dirty()):JC.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:G.invalid_string,...J.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...J.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...J.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...J.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...J.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...J.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...J.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...J.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...J.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...J.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...J.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...J.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...J.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...J.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...J.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...J.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...J.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...J.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...J.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...J.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...J.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...J.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...J.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...J.errToObj(t)})}nonempty(e){return this.min(1,J.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};Iw.create=e=>new Iw({checks:[],typeName:X.ZodString,coerce:e?.coerce??!1,...Y(e)});function Lw(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}var Rw=class e extends dw{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==W.number){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.number,received:t.parsedType}),q}let t,n=new nw;for(let r of this._def.checks)r.kind===`int`?JC.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),K(t,{code:G.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),K(t,{code:G.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),K(t,{code:G.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?Lw(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),K(t,{code:G.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),K(t,{code:G.not_finite,message:r.message}),n.dirty()):JC.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,J.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,J.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,J.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,J.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:J.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:J.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:J.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:J.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:J.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:J.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:J.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:J.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:J.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:J.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&JC.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;else n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value);return Number.isFinite(t)&&Number.isFinite(e)}};Rw.create=e=>new Rw({checks:[],typeName:X.ZodNumber,coerce:e?.coerce||!1,...Y(e)});var zw=class e extends dw{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==W.bigint)return this._getInvalidInput(e);let t,n=new nw;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),K(t,{code:G.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),K(t,{code:G.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),K(t,{code:G.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):JC.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.bigint,received:t.parsedType}),q}gte(e,t){return this.setLimit(`min`,e,!0,J.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,J.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,J.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,J.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:J.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:J.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:J.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:J.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:J.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:J.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};zw.create=e=>new zw({checks:[],typeName:X.ZodBigInt,coerce:e?.coerce??!1,...Y(e)});var Bw=class extends dw{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==W.boolean){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.boolean,received:t.parsedType}),q}return iw(e.data)}};Bw.create=e=>new Bw({typeName:X.ZodBoolean,coerce:e?.coerce||!1,...Y(e)});var Vw=class e extends dw{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==W.date){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.date,received:t.parsedType}),q}if(Number.isNaN(e.data.getTime()))return K(this._getOrReturnCtx(e),{code:G.invalid_date}),q;let t=new nw,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),K(n,{code:G.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),K(n,{code:G.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):JC.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:J.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:J.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};Vw.create=e=>new Vw({checks:[],coerce:e?.coerce||!1,typeName:X.ZodDate,...Y(e)});var Hw=class extends dw{_parse(e){if(this._getType(e)!==W.symbol){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.symbol,received:t.parsedType}),q}return iw(e.data)}};Hw.create=e=>new Hw({typeName:X.ZodSymbol,...Y(e)});var Uw=class extends dw{_parse(e){if(this._getType(e)!==W.undefined){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.undefined,received:t.parsedType}),q}return iw(e.data)}};Uw.create=e=>new Uw({typeName:X.ZodUndefined,...Y(e)});var Ww=class extends dw{_parse(e){if(this._getType(e)!==W.null){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.null,received:t.parsedType}),q}return iw(e.data)}};Ww.create=e=>new Ww({typeName:X.ZodNull,...Y(e)});var Gw=class extends dw{constructor(){super(...arguments),this._any=!0}_parse(e){return iw(e.data)}};Gw.create=e=>new Gw({typeName:X.ZodAny,...Y(e)});var Kw=class extends dw{constructor(){super(...arguments),this._unknown=!0}_parse(e){return iw(e.data)}};Kw.create=e=>new Kw({typeName:X.ZodUnknown,...Y(e)});var qw=class extends dw{_parse(e){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.never,received:t.parsedType}),q}};qw.create=e=>new qw({typeName:X.ZodNever,...Y(e)});var Jw=class extends dw{_parse(e){if(this._getType(e)!==W.undefined){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.void,received:t.parsedType}),q}return iw(e.data)}};Jw.create=e=>new Jw({typeName:X.ZodVoid,...Y(e)});var Yw=class e extends dw{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==W.array)return K(t,{code:G.invalid_type,expected:W.array,received:t.parsedType}),q;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(K(t,{code:e?G.too_big:G.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(K(t,{code:G.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(K(t,{code:G.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new lw(t,e,t.path,n)))).then(e=>nw.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new lw(t,e,t.path,n)));return nw.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:J.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:J.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:J.toString(n)}})}nonempty(e){return this.min(1,e)}};Yw.create=(e,t)=>new Yw({type:e,minLength:null,maxLength:null,exactLength:null,typeName:X.ZodArray,...Y(t)});function Xw(e){if(e instanceof Zw){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=hT.create(Xw(r))}return new Zw({...e._def,shape:()=>t})}return e instanceof Yw?new Yw({...e._def,type:Xw(e.element)}):e instanceof hT?hT.create(Xw(e.unwrap())):e instanceof gT?gT.create(Xw(e.unwrap())):e instanceof rT?rT.create(e.items.map(e=>Xw(e))):e}var Zw=class e extends dw{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=JC.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==W.object){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.object,received:t.parsedType}),q}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof qw&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let o=[];for(let e of i){let t=r[e],i=n.data[e];o.push({key:{status:`valid`,value:e},value:t._parse(new lw(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof qw){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)o.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(K(n,{code:G.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new lw(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>nw.mergeObjectSync(t,e)):nw.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return J.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,n)=>{let r=this._def.errorMap?.(e,n).message??n.defaultError;return e.code===`unrecognized_keys`?{message:J.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:X.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of JC.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let e of JC.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return Xw(this)}partial(t){let n={};for(let e of JC.objectKeys(this.shape)){let r=this.shape[e];n[e]=t&&!t[e]?r:r.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let e of JC.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof hT;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return uT(JC.objectKeys(this.shape))}};Zw.create=(e,t)=>new Zw({shape:()=>e,unknownKeys:`strip`,catchall:qw.create(),typeName:X.ZodObject,...Y(t)}),Zw.strictCreate=(e,t)=>new Zw({shape:()=>e,unknownKeys:`strict`,catchall:qw.create(),typeName:X.ZodObject,...Y(t)}),Zw.lazycreate=(e,t)=>new Zw({shape:e,unknownKeys:`strip`,catchall:qw.create(),typeName:X.ZodObject,...Y(t)});var Qw=class extends dw{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new ZC(e.ctx.common.issues));return K(t,{code:G.invalid_union,unionErrors:n}),q}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(r);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new ZC(e));return K(t,{code:G.invalid_union,unionErrors:i}),q}}get options(){return this._def.options}};Qw.create=(e,t)=>new Qw({options:e,typeName:X.ZodUnion,...Y(t)});var $w=e=>e instanceof cT?$w(e.schema):e instanceof mT?$w(e.innerType()):e instanceof lT?[e.value]:e instanceof dT?e.options:e instanceof fT?JC.objectValues(e.enum):e instanceof _T?$w(e._def.innerType):e instanceof Uw?[void 0]:e instanceof Ww?[null]:e instanceof hT?[void 0,...$w(e.unwrap())]:e instanceof gT?[null,...$w(e.unwrap())]:e instanceof bT||e instanceof ST?$w(e.unwrap()):e instanceof vT?$w(e._def.innerType):[],eT=class e extends dw{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==W.object)return K(t,{code:G.invalid_type,expected:W.object,received:t.parsedType}),q;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(K(t,{code:G.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),q)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let e of n){let n=$w(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:X.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...Y(r)})}};function tT(e,t){let n=XC(e),r=XC(t);if(e===t)return{valid:!0,data:e};if(n===W.object&&r===W.object){let n=JC.objectKeys(t),r=JC.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};Object.prototype.hasOwnProperty.call(i,`__proto__`)&&delete i.__proto__;for(let n of r){if(n===`__proto__`)continue;let r=tT(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}if(n===W.array&&r===W.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=tT(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}return n===W.date&&r===W.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var nT=class extends dw{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(aw(e)||aw(r))return q;let i=tT(e.value,r.value);return i.valid?((ow(e)||ow(r))&&t.dirty(),{status:t.value,value:i.data}):(K(n,{code:G.invalid_intersection_types}),q)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};nT.create=(e,t,n)=>new nT({left:e,right:t,typeName:X.ZodIntersection,...Y(n)});var rT=class e extends dw{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==W.array)return K(n,{code:G.invalid_type,expected:W.array,received:n.parsedType}),q;if(n.data.length<this._def.items.length)return K(n,{code:G.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),q;!this._def.rest&&n.data.length>this._def.items.length&&(K(n,{code:G.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new lw(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>nw.mergeArray(t,e)):nw.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};rT.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new rT({items:e,typeName:X.ZodTuple,rest:null,...Y(t)})};var iT=class e extends dw{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==W.object)return K(n,{code:G.invalid_type,expected:W.object,received:n.parsedType}),q;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new lw(n,e,n.path,e)),value:a._parse(new lw(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?nw.mergeObjectAsync(t,r):nw.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof dw?new e({keyType:t,valueType:n,typeName:X.ZodRecord,...Y(r)}):new e({keyType:Iw.create(),valueType:t,typeName:X.ZodRecord,...Y(n)})}},aT=class extends dw{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==W.map)return K(n,{code:G.invalid_type,expected:W.map,received:n.parsedType}),q;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new lw(n,e,n.path,[a,`key`])),value:i._parse(new lw(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return q;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return q;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};aT.create=(e,t,n)=>new aT({valueType:t,keyType:e,typeName:X.ZodMap,...Y(n)});var oT=class e extends dw{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==W.set)return K(n,{code:G.invalid_type,expected:W.set,received:n.parsedType}),q;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(K(n,{code:G.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(K(n,{code:G.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return q;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new lw(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:J.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:J.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};oT.create=(e,t)=>new oT({valueType:e,minSize:null,maxSize:null,typeName:X.ZodSet,...Y(t)});var sT=class e extends dw{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==W.function)return K(t,{code:G.invalid_type,expected:W.function,received:t.parsedType}),q;function n(e,n){return tw({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ew(),QC].filter(e=>!!e),issueData:{code:G.invalid_arguments,argumentsError:n}})}function r(e,n){return tw({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ew(),QC].filter(e=>!!e),issueData:{code:G.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof pT){let e=this;return iw(async function(...t){let o=new ZC([]),s=await e._def.args.parseAsync(t,i).catch(e=>{throw o.addIssue(n(t,e)),o}),c=await Reflect.apply(a,this,s);return await e._def.returns._def.type.parseAsync(c,i).catch(e=>{throw o.addIssue(r(c,e)),o})})}{let e=this;return iw(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new ZC([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new ZC([r(s,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:rT.create(t).rest(Kw.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,n,r){return new e({args:t||rT.create([]).rest(Kw.create()),returns:n||Kw.create(),typeName:X.ZodFunction,...Y(r)})}},cT=class extends dw{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};cT.create=(e,t)=>new cT({getter:e,typeName:X.ZodLazy,...Y(t)});var lT=class extends dw{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return K(t,{received:t.data,code:G.invalid_literal,expected:this._def.value}),q}return{status:`valid`,value:e.data}}get value(){return this._def.value}};lT.create=(e,t)=>new lT({value:e,typeName:X.ZodLiteral,...Y(t)});function uT(e,t){return new dT({values:e,typeName:X.ZodEnum,...Y(t)})}var dT=class e extends dw{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return K(t,{expected:JC.joinValues(n),received:t.parsedType,code:G.invalid_type}),q}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return K(t,{received:t.data,code:G.invalid_enum_value,options:n}),q}return iw(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}};dT.create=uT;var fT=class extends dw{_parse(e){let t=JC.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==W.string&&n.parsedType!==W.number){let e=JC.objectValues(t);return K(n,{expected:JC.joinValues(e),received:n.parsedType,code:G.invalid_type}),q}if(this._cache||=new Set(JC.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=JC.objectValues(t);return K(n,{received:n.data,code:G.invalid_enum_value,options:e}),q}return iw(e.data)}get enum(){return this._def.values}};fT.create=(e,t)=>new fT({values:e,typeName:X.ZodNativeEnum,...Y(t)});var pT=class extends dw{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==W.promise&&t.common.async===!1?(K(t,{code:G.invalid_type,expected:W.promise,received:t.parsedType}),q):iw((t.parsedType===W.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};pT.create=(e,t)=>new pT({type:e,typeName:X.ZodPromise,...Y(t)});var mT=class extends dw{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===X.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{K(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return q;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?q:r.status===`dirty`||t.value===`dirty`?rw(r.value):r});{if(t.value===`aborted`)return q;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?q:r.status===`dirty`||t.value===`dirty`?rw(r.value):r}}if(r.type===`refinement`){let e=e=>{let t=r.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(n.common.async===!1){let r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return r.status===`aborted`?q:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?q:(n.status===`dirty`&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if(r.type===`transform`){if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!sw(e))return q;let a=r.transform(e.value,i);if(a instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:a}}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>sw(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):q)}JC.assertNever(r)}};mT.create=(e,t,n)=>new mT({schema:e,typeName:X.ZodEffects,effect:t,...Y(n)}),mT.createWithPreprocess=(e,t,n)=>new mT({schema:t,effect:{type:`preprocess`,transform:e},typeName:X.ZodEffects,...Y(n)});var hT=class extends dw{_parse(e){return this._getType(e)===W.undefined?iw(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};hT.create=(e,t)=>new hT({innerType:e,typeName:X.ZodOptional,...Y(t)});var gT=class extends dw{_parse(e){return this._getType(e)===W.null?iw(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};gT.create=(e,t)=>new gT({innerType:e,typeName:X.ZodNullable,...Y(t)});var _T=class extends dw{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===W.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};_T.create=(e,t)=>new _T({innerType:e,typeName:X.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...Y(t)});var vT=class extends dw{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return cw(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new ZC(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new ZC(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};vT.create=(e,t)=>new vT({innerType:e,typeName:X.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...Y(t)});var yT=class extends dw{_parse(e){if(this._getType(e)!==W.nan){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.nan,received:t.parsedType}),q}return{status:`valid`,value:e.data}}};yT.create=e=>new yT({typeName:X.ZodNaN,...Y(e)});var bT=class extends dw{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},xT=class e extends dw{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?q:e.status===`dirty`?(t.dirty(),rw(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?q:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:X.ZodPipeline})}},ST=class extends dw{_parse(e){let t=this._def.innerType._parse(e),n=e=>(sw(e)&&(e.value=Object.freeze(e.value)),e);return cw(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};ST.create=(e,t)=>new ST({innerType:e,typeName:X.ZodReadonly,...Y(t)}),Zw.lazycreate;var X;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(X||={}),Iw.create,Rw.create,yT.create,zw.create,Bw.create,Vw.create,Hw.create,Uw.create,Ww.create,Gw.create,Kw.create,qw.create,Jw.create,Yw.create;var CT=Zw.create;Zw.strictCreate,Qw.create,eT.create,nT.create,rT.create,iT.create,aT.create,oT.create,sT.create,cT.create,lT.create,dT.create,fT.create,pT.create,mT.create,hT.create,gT.create,mT.createWithPreprocess,xT.create;var wT=O(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);Yr.init(e,t),e.def=t,e.type=t.type},{get with(){return this.check},set with(e){Jt(this,`with`,e)},parse(e,t){return On(this,e,t,{callee:this.parse})},parseAsync(e,t){return An(this,e,t,{callee:this.parseAsync})},safeParse(e,t){return Mn(this,e,t)},safeParseAsync(e,t){return Fn(this,e,t)},check(...e){let t=this.def;return this.clone({...t,checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]},{parent:!0})},clone(e,t){return St(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},apply(e,...t){return t.length===0?e(this):e(this,...t)}}),TT=O(`ZodMiniObject`,(e,t)=>{Zi.init(e,t),wT.init(e,t),rn(e,`shape`,e=>e._zod.def.shape,!1)});function ET(e,t){return new TT({type:`object`,shape:e??{},...D(t)})}function DT(e){return!!e._zod}function OT(e){let t=Object.values(e);if(t.length===0)return ET({});let n=t.every(DT),r=t.every(e=>!DT(e));if(n)return ET(e);if(r)return CT(e);throw Error(`Mixed Zod versions detected in object shape.`)}function kT(e,t){return DT(e)?Mn(e,t):e.safeParse(t)}async function AT(e,t){return DT(e)?await Fn(e,t):await e.safeParseAsync(t)}function jT(e){if(!e)return;let t;if(t=DT(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function MT(e){if(e){if(typeof e==`object`){let t=e,n=e;if(!t._def&&!n._zod){let t=Object.values(e);if(t.length>0&&t.every(e=>typeof e==`object`&&!!e&&(e._def!==void 0||e._zod!==void 0||typeof e.parse==`function`)))return OT(e)}}if(DT(e)){let t=e._zod?.def;if(t&&(t.type===`object`||t.shape!==void 0))return e}else if(e.shape!==void 0)return e}}function NT(e){return e.length===0?`object root`:e.reduce((e,t,n)=>n===0?String(t):typeof t==`number`?`${e}[${t}]`:`${e}.${t}`,``)}function PT(e){if(e&&typeof e==`object`){if(`issues`in e&&Array.isArray(e.issues)&&e.issues.length>0)return e.issues.map(e=>e.path?.length?`${e.message} at ${NT(e.path)}`:e.message).join(`
|
|
296
|
-
`);if(`message`in e&&typeof e.message==`string`)return e.message;try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function FT(e){return e.description}function IT(e){if(DT(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function LT(e){if(DT(e)){let t=e._zod?.def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}}let t=e._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let n=e.value;if(n!==void 0)return n}var RT=`2025-11-25`,zT=[RT,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],BT=`io.modelcontextprotocol/related-task`,VT=hu(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),HT=Il([k(),A().int()]),UT=k();Pl({ttl:A().optional(),pollInterval:A().optional()});var WT=N({ttl:A().optional()}),GT=N({taskId:k()}),KT=Pl({progressToken:HT.optional(),[BT]:GT.optional()}),qT=N({_meta:KT.optional()}),JT=qT.extend({task:WT.optional()}),YT=e=>JT.safeParse(e).success,XT=N({method:k(),params:qT.loose().optional()}),ZT=N({_meta:KT.optional()}),QT=N({method:k(),params:ZT.loose().optional()}),$T=Pl({_meta:KT.optional()}),eE=Il([k(),A().int()]),tE=N({jsonrpc:I(`2.0`),id:eE,...XT.shape}).strict(),nE=e=>tE.safeParse(e).success,rE=N({jsonrpc:I(`2.0`),...QT.shape}).strict(),iE=e=>rE.safeParse(e).success,aE=N({jsonrpc:I(`2.0`),id:eE,result:$T}).strict(),oE=e=>aE.safeParse(e).success,Z;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`})(Z||={});var sE=N({jsonrpc:I(`2.0`),id:eE.optional(),error:N({code:A().int(),message:k(),data:kl().optional()})}).strict(),cE=e=>sE.safeParse(e).success,lE=Il([tE,rE,aE,sE]);Il([aE,sE]);var uE=$T.strict(),dE=ZT.extend({requestId:eE.optional(),reason:k().optional()}),fE=QT.extend({method:I(`notifications/cancelled`),params:dE}),pE=N({icons:M(N({src:k(),mimeType:k().optional(),sizes:M(k()).optional(),theme:F([`light`,`dark`]).optional()})).optional()}),mE=N({name:k(),title:k().optional()}),hE=mE.extend({...mE.shape,...pE.shape,version:k(),websiteUrl:k().optional(),description:k().optional()}),gE=vu(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Bl(N({form:Bl(N({applyDefaults:j().optional()}),Wl(k(),kl())).optional(),url:VT.optional()}),Wl(k(),kl()).optional())),_E=Pl({list:VT.optional(),cancel:VT.optional(),requests:Pl({sampling:Pl({createMessage:VT.optional()}).optional(),elicitation:Pl({create:VT.optional()}).optional()}).optional()}),vE=Pl({list:VT.optional(),cancel:VT.optional(),requests:Pl({tools:Pl({call:VT.optional()}).optional()}).optional()}),yE=N({experimental:Wl(k(),VT).optional(),sampling:N({context:VT.optional(),tools:VT.optional()}).optional(),elicitation:gE.optional(),roots:N({listChanged:j().optional()}).optional(),tasks:_E.optional(),extensions:Wl(k(),VT).optional()}),bE=qT.extend({protocolVersion:k(),capabilities:yE,clientInfo:hE}),xE=XT.extend({method:I(`initialize`),params:bE}),SE=N({experimental:Wl(k(),VT).optional(),logging:VT.optional(),completions:VT.optional(),prompts:N({listChanged:j().optional()}).optional(),resources:N({subscribe:j().optional(),listChanged:j().optional()}).optional(),tools:N({listChanged:j().optional()}).optional(),tasks:vE.optional(),extensions:Wl(k(),VT).optional()}),CE=$T.extend({protocolVersion:k(),capabilities:SE,serverInfo:hE,instructions:k().optional()}),wE=QT.extend({method:I(`notifications/initialized`),params:ZT.optional()}),TE=XT.extend({method:I(`ping`),params:qT.optional()}),EE=N({progress:A(),total:Xl(A()),message:Xl(k())}),DE=N({...ZT.shape,...EE.shape,progressToken:HT}),OE=QT.extend({method:I(`notifications/progress`),params:DE}),kE=qT.extend({cursor:UT.optional()}),AE=XT.extend({params:kE.optional()}),jE=$T.extend({nextCursor:UT.optional()}),ME=F([`working`,`input_required`,`completed`,`failed`,`cancelled`]),NE=N({taskId:k(),status:ME,ttl:Il([A(),Dl()]),createdAt:k(),lastUpdatedAt:k(),pollInterval:Xl(A()),statusMessage:Xl(k())}),PE=$T.extend({task:NE}),FE=ZT.merge(NE),IE=QT.extend({method:I(`notifications/tasks/status`),params:FE}),LE=XT.extend({method:I(`tasks/get`),params:qT.extend({taskId:k()})}),RE=$T.merge(NE),zE=XT.extend({method:I(`tasks/result`),params:qT.extend({taskId:k()})});$T.loose();var BE=AE.extend({method:I(`tasks/list`)}),VE=jE.extend({tasks:M(NE)}),HE=XT.extend({method:I(`tasks/cancel`),params:qT.extend({taskId:k()})}),UE=$T.merge(NE),WE=N({uri:k(),mimeType:Xl(k()),_meta:Wl(k(),kl()).optional()}),GE=WE.extend({text:k()}),KE=k().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),qE=WE.extend({blob:KE}),JE=F([`user`,`assistant`]),YE=N({audience:M(JE).optional(),priority:A().min(0).max(1).optional(),lastModified:yu({offset:!0}).optional()}),XE=N({...mE.shape,...pE.shape,uri:k(),description:Xl(k()),mimeType:Xl(k()),size:Xl(A()),annotations:YE.optional(),_meta:Xl(Pl({}))}),ZE=N({...mE.shape,...pE.shape,uriTemplate:k(),description:Xl(k()),mimeType:Xl(k()),annotations:YE.optional(),_meta:Xl(Pl({}))}),QE=AE.extend({method:I(`resources/list`)}),$E=jE.extend({resources:M(XE)}),eD=AE.extend({method:I(`resources/templates/list`)}),tD=jE.extend({resourceTemplates:M(ZE)}),nD=qT.extend({uri:k()}),rD=nD,iD=XT.extend({method:I(`resources/read`),params:rD}),aD=$T.extend({contents:M(Il([GE,qE]))}),oD=QT.extend({method:I(`notifications/resources/list_changed`),params:ZT.optional()}),sD=nD,cD=XT.extend({method:I(`resources/subscribe`),params:sD}),lD=nD,uD=XT.extend({method:I(`resources/unsubscribe`),params:lD}),dD=ZT.extend({uri:k()}),fD=QT.extend({method:I(`notifications/resources/updated`),params:dD}),pD=N({name:k(),description:Xl(k()),required:Xl(j())}),mD=N({...mE.shape,...pE.shape,description:Xl(k()),arguments:Xl(M(pD)),_meta:Xl(Pl({}))}),hD=AE.extend({method:I(`prompts/list`)}),gD=jE.extend({prompts:M(mD)}),_D=qT.extend({name:k(),arguments:Wl(k(),k()).optional()}),vD=XT.extend({method:I(`prompts/get`),params:_D}),yD=N({type:I(`text`),text:k(),annotations:YE.optional(),_meta:Wl(k(),kl()).optional()}),bD=N({type:I(`image`),data:KE,mimeType:k(),annotations:YE.optional(),_meta:Wl(k(),kl()).optional()}),xD=N({type:I(`audio`),data:KE,mimeType:k(),annotations:YE.optional(),_meta:Wl(k(),kl()).optional()}),SD=N({type:I(`tool_use`),name:k(),id:k(),input:Wl(k(),kl()),_meta:Wl(k(),kl()).optional()}),CD=N({type:I(`resource`),resource:Il([GE,qE]),annotations:YE.optional(),_meta:Wl(k(),kl()).optional()}),wD=Il([yD,bD,xD,XE.extend({type:I(`resource_link`)}),CD]),TD=N({role:JE,content:wD}),ED=$T.extend({description:k().optional(),messages:M(TD)}),DD=QT.extend({method:I(`notifications/prompts/list_changed`),params:ZT.optional()}),OD=N({title:k().optional(),readOnlyHint:j().optional(),destructiveHint:j().optional(),idempotentHint:j().optional(),openWorldHint:j().optional()}),kD=N({taskSupport:F([`required`,`optional`,`forbidden`]).optional()}),AD=N({...mE.shape,...pE.shape,description:k().optional(),inputSchema:N({type:I(`object`),properties:Wl(k(),VT).optional(),required:M(k()).optional()}).catchall(kl()),outputSchema:N({type:I(`object`),properties:Wl(k(),VT).optional(),required:M(k()).optional()}).catchall(kl()).optional(),annotations:OD.optional(),execution:kD.optional(),_meta:Wl(k(),kl()).optional()}),jD=AE.extend({method:I(`tools/list`)}),MD=jE.extend({tools:M(AD)}),ND=$T.extend({content:M(wD).default([]),structuredContent:Wl(k(),kl()).optional(),isError:j().optional()});ND.or($T.extend({toolResult:kl()}));var PD=JT.extend({name:k(),arguments:Wl(k(),kl()).optional()}),FD=XT.extend({method:I(`tools/call`),params:PD}),ID=QT.extend({method:I(`notifications/tools/list_changed`),params:ZT.optional()}),LD=N({autoRefresh:j().default(!0),debounceMs:A().int().nonnegative().default(300)}),RD=F([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),zD=qT.extend({level:RD}),BD=XT.extend({method:I(`logging/setLevel`),params:zD}),VD=ZT.extend({level:RD,logger:k().optional(),data:kl()}),HD=QT.extend({method:I(`notifications/message`),params:VD}),UD=N({hints:M(N({name:k().optional()})).optional(),costPriority:A().min(0).max(1).optional(),speedPriority:A().min(0).max(1).optional(),intelligencePriority:A().min(0).max(1).optional()}),WD=N({mode:F([`auto`,`required`,`none`]).optional()}),GD=N({type:I(`tool_result`),toolUseId:k().describe(`The unique identifier for the corresponding tool call.`),content:M(wD).default([]),structuredContent:N({}).loose().optional(),isError:j().optional(),_meta:Wl(k(),kl()).optional()}),KD=Rl(`type`,[yD,bD,xD]),qD=Rl(`type`,[yD,bD,xD,SD,GD]),JD=N({role:JE,content:Il([qD,M(qD)]),_meta:Wl(k(),kl()).optional()}),YD=JT.extend({messages:M(JD),modelPreferences:UD.optional(),systemPrompt:k().optional(),includeContext:F([`none`,`thisServer`,`allServers`]).optional(),temperature:A().optional(),maxTokens:A().int(),stopSequences:M(k()).optional(),metadata:VT.optional(),tools:M(AD).optional(),toolChoice:WD.optional()}),XD=XT.extend({method:I(`sampling/createMessage`),params:YD}),ZD=$T.extend({model:k(),stopReason:Xl(F([`endTurn`,`stopSequence`,`maxTokens`]).or(k())),role:JE,content:KD}),QD=$T.extend({model:k(),stopReason:Xl(F([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(k())),role:JE,content:Il([qD,M(qD)])}),$D=N({type:I(`boolean`),title:k().optional(),description:k().optional(),default:j().optional()}),eO=N({type:I(`string`),title:k().optional(),description:k().optional(),minLength:A().optional(),maxLength:A().optional(),format:F([`email`,`uri`,`date`,`date-time`]).optional(),default:k().optional()}),tO=N({type:F([`number`,`integer`]),title:k().optional(),description:k().optional(),minimum:A().optional(),maximum:A().optional(),default:A().optional()}),nO=N({type:I(`string`),title:k().optional(),description:k().optional(),enum:M(k()),default:k().optional()}),rO=N({type:I(`string`),title:k().optional(),description:k().optional(),oneOf:M(N({const:k(),title:k()})),default:k().optional()}),iO=Il([Il([N({type:I(`string`),title:k().optional(),description:k().optional(),enum:M(k()),enumNames:M(k()).optional(),default:k().optional()}),Il([nO,rO]),Il([N({type:I(`array`),title:k().optional(),description:k().optional(),minItems:A().optional(),maxItems:A().optional(),items:N({type:I(`string`),enum:M(k())}),default:M(k()).optional()}),N({type:I(`array`),title:k().optional(),description:k().optional(),minItems:A().optional(),maxItems:A().optional(),items:N({anyOf:M(N({const:k(),title:k()}))}),default:M(k()).optional()})])]),$D,eO,tO]),aO=Il([JT.extend({mode:I(`form`).optional(),message:k(),requestedSchema:N({type:I(`object`),properties:Wl(k(),iO),required:M(k()).optional()})}),JT.extend({mode:I(`url`),message:k(),elicitationId:k(),url:k().url()})]),oO=XT.extend({method:I(`elicitation/create`),params:aO}),sO=ZT.extend({elicitationId:k()}),cO=QT.extend({method:I(`notifications/elicitation/complete`),params:sO}),lO=$T.extend({action:F([`accept`,`decline`,`cancel`]),content:vu(e=>e===null?void 0:e,Wl(k(),Il([k(),A(),j(),M(k())])).optional())}),uO=N({type:I(`ref/resource`),uri:k()}),dO=N({type:I(`ref/prompt`),name:k()}),fO=qT.extend({ref:Il([dO,uO]),argument:N({name:k(),value:k()}),context:N({arguments:Wl(k(),k()).optional()}).optional()}),pO=XT.extend({method:I(`completion/complete`),params:fO});function mO(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function hO(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}var gO=$T.extend({completion:Pl({values:M(k()).max(100),total:Xl(A().int()),hasMore:Xl(j())})}),_O=N({uri:k().startsWith(`file://`),name:k().optional(),_meta:Wl(k(),kl()).optional()}),vO=XT.extend({method:I(`roots/list`),params:qT.optional()}),yO=$T.extend({roots:M(_O)}),bO=QT.extend({method:I(`notifications/roots/list_changed`),params:ZT.optional()});Il([TE,xE,pO,BD,vD,hD,QE,eD,iD,cD,uD,FD,jD,LE,zE,BE,HE]),Il([fE,OE,wE,bO,IE]),Il([uE,ZD,QD,lO,yO,RE,VE,PE]),Il([TE,XD,oO,vO,LE,zE,BE,HE]),Il([fE,OE,HD,fD,oD,ID,DD,IE,cO]),Il([uE,CE,gO,ED,gD,$E,tD,aD,ND,MD,RE,VE,PE]);var Q=class e extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}static fromError(t,n,r){if(t===Z.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new xO(e.elicitations,n)}return new e(t,n,r)}},xO=class extends Q{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(Z.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function SO(e){return e===`completed`||e===`failed`||e===`cancelled`}var CO=Symbol(`Let zodToJsonSchema decide on which parser to use`),wO={name:void 0,$refStrategy:`root`,basePath:[`#`],effectStrategy:`input`,pipeStrategy:`all`,dateStrategy:`format:date-time`,mapStrategy:`entries`,removeAdditionalStrategy:`passthrough`,allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:`definitions`,target:`jsonSchema7`,strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:`escape`,applyRegexFlags:!1,emailStrategy:`format:email`,base64Strategy:`contentEncoding:base64`,nameStrategy:`ref`,openAiAnyTypeName:`OpenAiAnyType`},TO=e=>typeof e==`string`?{...wO,name:e}:{...wO,...e},EO=e=>{let t=TO(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function DO(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function OO(e,t,n,r,i){e[t]=n,DO(e,t,r,i)}var kO=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)};function AO(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?kO(t,e.currentPath):t.join(`/`)}}function jO(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==X.ZodAny&&(n.items=xk(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&OO(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&OO(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(OO(n,`minItems`,e.exactLength.value,e.exactLength.message,t),OO(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function MO(e,t){let n={type:`integer`,format:`int64`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`min`:t.target===`jsonSchema7`?r.inclusive?OO(n,`minimum`,r.value,r.message,t):OO(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),OO(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?OO(n,`maximum`,r.value,r.message,t):OO(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),OO(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:OO(n,`multipleOf`,r.value,r.message,t)}return n}function NO(){return{type:`boolean`}}function PO(e,t){return xk(e.type._def,t)}var FO=(e,t)=>xk(e.innerType._def,t);function IO(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>IO(e,t,n))};switch(r){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return LO(e,t)}}var LO=(e,t)=>{let n={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return n;for(let r of e.checks)switch(r.kind){case`min`:OO(n,`minimum`,r.value,r.message,t);break;case`max`:OO(n,`maximum`,r.value,r.message,t)}return n};function RO(e,t){return{...xk(e.innerType._def,t),default:e.defaultValue()}}function zO(e,t){return t.effectStrategy===`input`?xk(e.schema._def,t):AO(t)}function BO(e){return{type:`string`,enum:Array.from(e.values)}}var VO=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function HO(e,t){let n=[xk(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),xk(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,i=[];return n.forEach(e=>{if(VO(e))i.push(...e.allOf),e.unevaluatedProperties===void 0&&(r=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:n,...r}=e;t=r}else r=void 0;i.push(t)}}),i.length?{allOf:i,...r}:void 0}function UO(e,t){let n=typeof e.value;return n!==`bigint`&&n!==`number`&&n!==`boolean`&&n!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:n===`bigint`?`integer`:n,enum:[e.value]}:{type:n===`bigint`?`integer`:n,const:e.value}}var WO=void 0,GO={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(WO===void 0&&(WO=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),WO),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function KO(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:OO(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:OO(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:XO(n,`email`,r.message,t);break;case`format:idn-email`:XO(n,`idn-email`,r.message,t);break;case`pattern:zod`:ZO(n,GO.email,r.message,t)}break;case`url`:XO(n,`uri`,r.message,t);break;case`uuid`:XO(n,`uuid`,r.message,t);break;case`regex`:ZO(n,r.regex,r.message,t);break;case`cuid`:ZO(n,GO.cuid,r.message,t);break;case`cuid2`:ZO(n,GO.cuid2,r.message,t);break;case`startsWith`:ZO(n,RegExp(`^${qO(r.value,t)}`),r.message,t);break;case`endsWith`:ZO(n,RegExp(`${qO(r.value,t)}$`),r.message,t);break;case`datetime`:XO(n,`date-time`,r.message,t);break;case`date`:XO(n,`date`,r.message,t);break;case`time`:XO(n,`time`,r.message,t);break;case`duration`:XO(n,`duration`,r.message,t);break;case`length`:OO(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),OO(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:ZO(n,RegExp(qO(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&XO(n,`ipv4`,r.message,t),r.version!==`v4`&&XO(n,`ipv6`,r.message,t);break;case`base64url`:ZO(n,GO.base64url,r.message,t);break;case`jwt`:ZO(n,GO.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&ZO(n,GO.ipv4Cidr,r.message,t),r.version!==`v4`&&ZO(n,GO.ipv6Cidr,r.message,t);break;case`emoji`:ZO(n,GO.emoji(),r.message,t);break;case`ulid`:ZO(n,GO.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:XO(n,`binary`,r.message,t);break;case`contentEncoding:base64`:OO(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:ZO(n,GO.base64,r.message,t)}break;case`nanoid`:ZO(n,GO.nanoid,r.message,t)}return n}function qO(e,t){return t.patternStrategy===`escape`?YO(e):e}var JO=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function YO(e){let t=``;for(let n=0;n<e.length;n++)JO.has(e[n])||(t+=`\\`),t+=e[n];return t}function XO(e,t,n,r){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):OO(e,`format`,t,n,r)}function ZO(e,t,n,r){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:QO(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):OO(e,`pattern`,QO(t,r),n,r)}function QO(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},r=n.i?e.source.toLowerCase():e.source,i=``,a=!1,o=!1,s=!1;for(let e=0;e<r.length;e++){if(a){i+=r[e],a=!1;continue}if(n.i){if(o){if(r[e].match(/[a-z]/)){s?(i+=r[e],i+=`${r[e-2]}-${r[e]}`.toUpperCase(),s=!1):r[e+1]===`-`&&r[e+2]?.match(/[a-z]/)?(i+=r[e],s=!0):i+=`${r[e]}${r[e].toUpperCase()}`;continue}}else if(r[e].match(/[a-z]/)){i+=`[${r[e]}${r[e].toUpperCase()}]`;continue}}if(n.m){if(r[e]===`^`){i+=`(^|(?<=[\r
|
|
295
|
+
}`,{...e.repo,number:n})).repository.pullRequest?.closingIssuesReferences;if(r.number!==n||r.head.repo?.full_name.toLowerCase()!==e.config.repository.toLowerCase()||r.base.repo.full_name.toLowerCase()!==e.config.repository.toLowerCase()||!i||i.pageInfo.hasNextPage||!i.nodes.some(n=>n.number===t&&n.repository.nameWithOwner.toLowerCase()===e.config.repository.toLowerCase()))throw new L(`Native PR lineage does not establish the exact repository and closing issue.`);return jx.parse({prNumber:n,headSha:r.head.sha,headBranch:r.head.ref,baseSha:r.base.sha,baseBranch:r.base.ref,mergeSha:r.merge_commit_sha,merged:r.merged,authorLogin:r.user?.login})}async function aS(e,t,n){let r=[...new Set([t.prNumber,n].filter(e=>e!=null))];return Promise.all(r.map(n=>iS(e,t.issueNumber,n)))}function oS(e,t,n,r,i,a,o,s){if(n===`active-resume`){if(![`active`,`pr-published`].includes(t.status)||o!==`open`||a.some(e=>e.merged||e.headSha!==i.sha||e.headBranch!==t.branch))throw new L(`Active resume requires the exact open issue and unmerged source lineage.`);if(s.some(e=>/^git\/ai-delivery\/(?:publications|reviews|merges|merge-intents|merge-attempts|merge-results)\//u.test(e.path)))throw new L(`Existing current publication/review/merge slots require separate authority reconciliation; active resume cannot overwrite them.`)}else{let n=a.find(e=>e.prNumber===r);if(!n||o!==`closed`||!n.merged||n.headSha!==i.sha||n.headBranch!==t.branch||a.some(r=>!r.merged||!r.mergeSha||r.headBranch!==t.branch||r.baseBranch!==n.baseBranch||rd(e,`merge-base`,`--is-ancestor`,r.mergeSha,r.prNumber===n.prNumber?n.mergeSha:i.sha)!==0))throw new L(`Terminal native PR lineage or merged-result ancestry does not bind the retained exact source.`)}}async function sS(e,t,n){let r=async t=>{try{let n=(await e.clients.rest.repos.getBranch({...e.repo,branch:t})).data;if(n.name!==t)throw new L(`Native branch readback belongs to another ref.`);return ud.parse(n.commit.sha)}catch(e){if(e.status===404)return null;throw e}},i=await r(t),a=await r(n);if(a===null)throw new L(`Native retaining base branch is missing.`);return{headSha:i,baseSha:a}}async function cS(e,t){let n=[],r=od(e.root),i=Jb(r).filter(e=>e.type===`issue`&&e.issueNumber===t.issueNumber);if(i.length!==1)return{ready:!1,blockers:[`Expected one canonical legacy issue row.`],plan:null,inventory:[]};let a=[];try{let o=Ax.parse(i[0]);if(a.push(...Rx(r,o)),!e.configuration||e.config.repository!==`${e.repo.owner}/${e.repo.repo}`)throw new L(`Transition requires exact current repository configuration.`);if(o.path!==w(r,`.worktrees`,`issue-${String(o.issueNumber)}`)||o.branch!==`issue/${String(o.issueNumber)}`||id(o.path)!==h(o.path)||ad(o.path)!==ad(r)||nd(o.path,`branch`,`--show-current`)!==o.branch)throw new L(`Legacy row path, branch or Git ownership disagrees.`);cd(o.path);for(let e of[`v1`,`v2`])Ix(w(ad(r),`issue-cli`,`verification-stages`,e))&&n.push(`Unsupported operative issue-cli verification-stages/${e}; no authenticated supported operational closure is available.`);if((!t.retainedAdmissionPath||!t.retainedArchivePath)&&n.push(`Missing retained supported public producer admission/archive and operational closure. Historical UNKNOWN is preservation-only.`),n.length>0)return{ready:!1,blockers:n,plan:null,inventory:a};let s=await Yv({repoRoot:r,configuration:e.configuration,...t.runtimeEntryPath===void 0?{}:{runtimeEntryPath:t.runtimeEntryPath}}),{inventory:c,...l}=Px(e,h(t.retainedAdmissionPath),h(t.retainedArchivePath));a.push(...c);let u={sha:nd(o.path,`rev-parse`,`HEAD`),tree:nd(o.path,`rev-parse`,`HEAD^{tree}`)},d=Fx(r,o,a,l.producerDigest,u);if(a.filter(e=>e.path.startsWith(`git/ai-delivery/runs@2/`)).some(t=>ib(Lx(t.source)).classification.repository!==e.config.repository))throw new L(`Operational run inventory belongs to another repository.`);if(t.disposition===`remove`&&c.some(e=>{let t=se(o.path,e.source);return t===``||!t.startsWith(`..`)&&!t.startsWith(`/`)}))throw new L(`Retained operational producer must remain outside the source selected for removal.`);let f=a.find(e=>e.path.startsWith(`git/ai-delivery/writers@1/`));Yy(o.path,f===void 0?void 0:Lx(f.source));let p=t.purpose===`merged-cleanup`?t.terminalPrNumber??o.prNumber??null:null,m=await aS(e,o,p),g=(await e.clients.rest.issues.get({...e.repo,issue_number:o.issueNumber})).data;oS(r,o,t.purpose,p,u,m,g.state,a);let _=await Qx(e);if(m.some(e=>e.authorLogin.toLowerCase()===_.reviewerActor.toLowerCase()))throw new L(`Configured transition reviewer App is also the native PR author.`);let v=t.disposition===`remove`?await sS(e,o.branch,m.find(e=>e.prNumber===p).baseBranch):null;if(v&&(v.headSha!==null&&v.headSha!==u.sha||nd(r,`rev-parse`,ld(r,uS(e).remote))!==v.baseSha))throw new L(`Native remote branch readback disagrees with exact source or local retaining ref.`);let y=[...t.retainedHoldCommentIds??[]].sort((e,t)=>e-t);if(new Set(y).size!==y.length)throw new L(`Retained hold inventory has duplicates.`);let b=[];for(let t of y){let n=(await e.clients.rest.issues.getComment({...e.repo,comment_id:t})).data;if(!n.body||n.issue_url?.toLowerCase()!==`https://api.github.com/repos/${e.config.repository}/issues/${String(p??o.issueNumber)}`.toLowerCase())throw new L(`Retained hold comment belongs to another subject or is unavailable.`);let r=Buffer.from(z(n));b.push({commentId:t,digest:V(r)})}a.sort((e,t)=>e.path.localeCompare(t.path));let x={schemaVersion:`ai-delivery.worktree-transition-plan@1`,repository:e.config.repository,repoRoot:r,row:o,purpose:t.purpose,disposition:t.disposition??`retain`,head:u,terminalPrNumber:p,lineage:m,remoteRefs:v,retainedHoldCommentIds:y,holdEvidence:b,inventory:a,inventoryId:B(a),historicalProducer:`UNKNOWN`,closure:{family:`public-ai-delivery-0.3.5-posix@1`,...l,runManifestIds:d},currentRuntime:s,policyDigest:V(Lx(uS(e).policyModulePath)),operator:_.operator,reviewerActor:_.reviewerActor},ee=Mx.parse({...x,planId:B(x)});return{ready:!0,blockers:n,plan:ee,inventory:a,relinquishmentBody:$x(ee)}}catch(e){return n.push(e instanceof Error?e.message:String(e)),{ready:!1,blockers:n,plan:null,inventory:a}}}function lS(e,t){for(let n of t){let t=Lx(n.source);if(t.length!==n.size||V(t)!==n.digest)throw new L(`Historical evidence drifted: ${n.path}`);gd(w(e,`${n.digest.slice(7)}.bin`),t,n.digest)}}function uS(e){if(!e.configuration||!(`policyModulePath`in e.configuration))throw new L(`Historical repository configuration binding is unsupported by this runtime; preserve its original controller and records. No policy module was loaded.`);return e.configuration}var dS=k().regex(/^[a-f0-9]{40}$/u),fS=k().regex(/^sha256:[a-f0-9]{64}$/u),pS=N({artifactId:fS,authorIdentity:k().min(1),checks:M(k().min(1)).min(1),diffScopeHash:fS,deliveryMetrics:N({blockerTimeMs:A().int().nonnegative().nullable(),reviewRound:A().int().positive()}).strict().optional(),elapsedMs:A().int().nonnegative(),findings:M(k()),head:N({sha:dS,tree:dS}).strict(),issueNumber:A().int().positive(),prNumber:A().int().positive().nullable(),readOnly:I(!0),requestedEffort:k().min(1),requestedModel:k().min(1),effectiveEffort:k().min(1),effectiveModel:k().min(1),reviewerIdentity:k().min(1),schemaVersion:I(`ai-delivery.review-artifact@1`),summary:k().min(1),verdict:F([`approve`,`request-changes`])}).strict().superRefine((e,t)=>{let{artifactId:n,...r}=e;(n!==B(r)||e.authorIdentity===e.reviewerIdentity)&&t.addIssue({code:`custom`,message:`Review artifact identity or role separation is invalid.`})});N({artifact:pS,completedAt:yu(),githubReviewId:A().int().positive(),githubReviewUrl:ol(),headSha:dS,login:k().min(1),prNumber:A().int().positive(),publicationEvidenceId:fS,receiptId:fS,schemaVersion:I(`ai-delivery.review-receipt@1`),state:I(`APPROVED`)}).strict().superRefine((e,t)=>{let{receiptId:n,...r}=e;(n!==B(r)||e.headSha!==e.artifact.head.sha||e.artifact.prNumber!==null&&e.artifact.prNumber!==e.prNumber)&&t.addIssue({code:`custom`,message:`Submitted review receipt is not bound to its artifact.`})});async function mS(e,t,n,r){let i;try{i=await e.clients.graphql(`query DeliveryReviewDecision($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) { pullRequest(number: $number) { headRefOid reviewDecision } } }`,{owner:e.repo.owner,name:e.repo.repo,number:t})}catch{return{reviewDecision:null,submittedReviewAuthorCanPushToRepository:null,status:`unknown`,nextAction:`Inspect the PR review requirement in GitHub before merge; review decision readback is unavailable.`}}let a=i.repository?.pullRequest;if(!a)return{reviewDecision:null,submittedReviewAuthorCanPushToRepository:null,status:`unknown`,nextAction:`Inspect the PR review requirement in GitHub before merge; PR decision readback is unavailable.`};if(a.headRefOid!==n)throw new L(`GitHub review decision does not match the exact PR head.`);let o=null;if(r)try{let i=await e.clients.graphql(`query DeliveryReviewAccess($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) { pullRequest(number: $number) { reviews(last: 100) { nodes { fullDatabaseId author { login } authorCanPushToRepository commit { oid } state } } } } }`,{owner:e.repo.owner,name:e.repo.repo,number:t}),a=r.login.toLowerCase().replace(/\[bot\]$/u,``),s=i.repository?.pullRequest?.reviews.nodes.find(e=>e!==null&&String(e.fullDatabaseId)===String(r.id)&&e.author?.login.toLowerCase().replace(/\[bot\]$/u,``)===a&&e.commit?.oid===n&&e.state===`APPROVED`);typeof s?.authorCanPushToRepository==`boolean`&&(o=s.authorCanPushToRepository)}catch{}return a.reviewDecision===`APPROVED`?{reviewDecision:`APPROVED`,submittedReviewAuthorCanPushToRepository:o,status:`satisfied`,nextAction:`Continue only after required checks pass.`}:a.reviewDecision===`REVIEW_REQUIRED`?{reviewDecision:`REVIEW_REQUIRED`,submittedReviewAuthorCanPushToRepository:o,status:`still-required`,nextAction:o===!1?`GitHub still requires a qualifying approval; the submitted reviewer App review has no repository write access. Inspect the active rule and the App installation Contents grant, then obtain approval from an eligible independent reviewer.`:`GitHub still requires a qualifying approval. Inspect the active rule and obtain approval from an eligible independent reviewer; do not change actors or protections automatically.`}:a.reviewDecision===`CHANGES_REQUESTED`?{reviewDecision:`CHANGES_REQUESTED`,submittedReviewAuthorCanPushToRepository:o,status:`changes-requested`,nextAction:`Resolve the blocking review and obtain a fresh exact-head independent approval.`}:{reviewDecision:null,submittedReviewAuthorCanPushToRepository:o,status:`unknown`,nextAction:`Inspect the PR review requirement in GitHub before merge; no required-review decision was exposed.`}}function hS(e){let t=typeof e==`string`?JSON.parse(e):e;return pS.parse(t)}function gS(e){try{if(typeof e!=`string`||Buffer.byteLength(e,`utf8`)>65536)throw Error(`Invalid size.`);let t=e.match(/<!-- ai-delivery-review-artifact:[\s\S]*?-->/gu)??[],n=e.match(/<!-- ai-delivery-review-artifact-data:[\s\S]*?-->/gu)??[];if(t.length!==1||n.length!==1)throw Error(`Ambiguous binding.`);let r=t[0].match(/^<!-- ai-delivery-review-artifact: (sha256:[a-f0-9]{64}) -->$/u)?.[1],i=n[0].match(/^<!-- ai-delivery-review-artifact-data: ([A-Za-z0-9_-]+) -->$/u)?.[1];if(!r||!i)throw Error(`Invalid binding.`);let a=Buffer.from(i,`base64url`),o=a.toString(`utf8`);if(a.toString(`base64url`)!==i||!Buffer.from(o,`utf8`).equals(a))throw Error(`Invalid encoding.`);let s=hS(o);if(s.artifactId!==r)throw Error(`Artifact identity differs.`);return s}catch{throw new L(`GitHub review artifact binding is missing, invalid or ambiguous; obtain a fresh review.`)}}function _S(e){pS.parse(e);let t=`${e.summary}\n\n<!-- ai-delivery-review-artifact: ${e.artifactId} -->\n<!-- ai-delivery-review-artifact-data: ${Buffer.from(JSON.stringify(e)).toString(`base64url`)} -->`;return gS(t),t}async function vS(e,t,n){let r=[];for(let n=1;n<=30;n++){let i=(await e.clients.rest.pulls.listFiles({...e.repo,pull_number:t,page:n,per_page:100})).data;if(r.push(...i.map(e=>e.filename)),i.length<100)break}if(!Number.isSafeInteger(n)||r.length!==n||new Set(r).size!==r.length)throw new L(`Independent review scope is incomplete or differs from the remote PR diff.`);return B(r.sort())}async function yS(e,t){let n=[];for(let r=1;r<=20;r+=1){let i=await e.clients.rest.pulls.listReviews({...e.repo,pull_number:t,per_page:100,page:r});if(n.push(...i.data),i.data.length<100)return n}throw new L(`Review history exceeds the bounded readback window.`)}async function bS(e){let{artifact:t,context:n,issueNumber:r,prNumber:i}=e;if(pS.parse(t),t.verdict!==`approve`||t.issueNumber!==r||t.authorIdentity!==n.config.roles.author.identity||t.reviewerIdentity!==n.config.roles.reviewer.identity||t.prNumber!==null&&t.prNumber!==i)throw new L(`Independent review artifact is foreign or rejected.`);if(n.clients.authSource!==`app`||n.clients.role!==`reviewer`||!n.clients.appActorLogin)throw new L(`Formal review requires the independent reviewer GitHub App role.`);let a=(await n.clients.rest.pulls.get({...n.repo,pull_number:i})).data;if(a.number!==i||a.head.sha!==t.head.sha||a.state!==`open`||a.base.repo?.full_name.toLowerCase()!==n.config.repository.toLowerCase()||a.head.repo?.full_name.toLowerCase()!==n.config.repository.toLowerCase())throw new L(`PR identity or head changed before formal review.`);let o=await n.clients.appActorLogin();if(!o||!a.user?.login||o.toLowerCase()===a.user.login.toLowerCase())throw new L(`Reviewer GitHub actor must differ from PR author.`);let s=(await n.clients.rest.git.getCommit({...n.repo,commit_sha:t.head.sha})).data;if(s.sha!==t.head.sha||s.tree.sha!==t.head.tree)throw new L(`Independent review tree differs from the remote commit.`);if(t.diffScopeHash!==await vS(n,i,a.changed_files))throw new L(`Independent review scope is incomplete or differs from the remote PR diff.`);let c=_S(t),l=`<!-- ai-delivery-review-artifact: ${t.artifactId} -->`,u=await yS(n,i);if(u.some(e=>e.user?.login.toLowerCase()===o.toLowerCase()&&e.commit_id===t.head.sha&&e.state===`APPROVED`&&/<!-- ai-delivery-review-artifact: sha256:[a-f0-9]{64} -->/u.test(e.body??``)&&!e.body?.includes(l)))throw new L(`Another independent artifact conflicts with the existing exact-head App approval.`);let d=u.filter(e=>e.body?.includes(l));if(d.length>1)throw new L(`Conflicting GitHub reviews claim the same artifact identity.`);let f=d[0];if(f&&(f.state!==`APPROVED`||f.commit_id!==t.head.sha||f.user?.login.toLowerCase()!==o.toLowerCase()||!f.html_url||gS(f.body).artifactId!==t.artifactId))throw new L(`Prior GitHub review marker conflicts with exact-head approval.`);let p=(await n.clients.rest.pulls.get({...n.repo,pull_number:i})).data;if(p.head.sha!==t.head.sha||p.base.sha!==a.base.sha||p.state!==`open`)throw new L(`PR moved during independent review validation.`);if(e.dryRun)return{dryRun:!0,artifactId:t.artifactId,headSha:t.head.sha};let m=f??(await n.clients.rest.pulls.createReview({...n.repo,pull_number:i,commit_id:t.head.sha,body:c,event:`APPROVE`})).data;if(!m.id||m.state!==`APPROVED`||m.commit_id!==t.head.sha||m.user?.login.toLowerCase()!==o.toLowerCase()||!m.html_url)throw new L(`GitHub did not return complete exact-head independent approval.`);let h={artifact:t,repository:n.config.repository,baseSha:a.base.sha,headSha:t.head.sha,githubReviewId:m.id,githubReviewUrl:m.html_url,login:m.user.login,prNumber:i,schemaVersion:`ai-delivery.github-review@1`,state:`APPROVED`},g={...h,receiptId:B(h)},_=(await n.clients.rest.pulls.getReview({...n.repo,pull_number:i,review_id:m.id})).data;if(_.id!==g.githubReviewId||_.html_url!==g.githubReviewUrl||_.state!==`APPROVED`||_.commit_id!==g.headSha||_.user?.login!==g.login||gS(_.body).artifactId!==t.artifactId)throw new L(`GitHub exact-head App review readback disagrees.`);let v=(await n.clients.rest.pulls.get({...n.repo,pull_number:i})).data;if(v.head.sha!==t.head.sha||v.base.sha!==a.base.sha||v.state!==`open`)throw new L(`PR moved during independent review submission; approval is not current.`);return g}var xS=/^[a-f0-9]{40}$/u,SS=/^(?!.*(?:\.\.|@\{|\/\/))[A-Za-z0-9._/-]+$/u;function CS(e){if(typeof e!=`string`)throw new L(`Incomplete non-closing message readback.`);let t=e.replace(/[*_~`\\<>[\]]/gu,``);if(/\b(?:close[sd]?|fix(?:es|ed)?|resolve[sd]?)\b(?:\s*:\s*|\s+)[^\n]*?(?:#[0-9]+|[A-Za-z0-9.-]+\/[A-Za-z0-9.-]+#[0-9]+|https?:\/\/(?:www\.)?github\.com\/[A-Za-z0-9.-]+\/[A-Za-z0-9.-]+\/(?:issues|pull)\/[0-9]+)/iu.test(t))throw new L(`Non-closing delivery refuses closing directives in body, title or commit messages.`)}function wS(e,t){return`References ${e.config.repository}#${t}`}function TS(e,t,n){CS(n);let r=wS(e,t),i=n.startsWith(`${r}\n`)||n===r?n:`${r}\n\n${n}`;return ES(e,t,i),i}function ES(e,t,n){CS(n);let r=n.split(/\r?\n/u);if(r[0]!==wS(e,t)||r.filter(e=>/^References\s/iu.test(e)).length!==1)throw new L(`Non-closing PR body must retain one leading canonical References line.`)}function DS(e,t){let n=e.pageInfo;if(!n||typeof n.hasNextPage!=`boolean`||n.endCursor!==null&&typeof n.endCursor!=`string`)throw new L(`Incomplete non-closing native pagination.`);if(!n.hasNextPage)return null;if(!n.endCursor||t.has(n.endCursor))throw new L(`Non-closing native pagination did not advance.`);return t.add(n.endCursor),n.endCursor}async function OS(e,t){let n=(await e.clients.rest.issues.get({...e.repo,issue_number:t})).data;if(n.number!==t||`pull_request`in n||n.state!==`open`||typeof n.node_id!=`string`||!n.node_id||typeof n.title!=`string`||typeof n.body!=`string`||n.html_url?.toLowerCase()!==`https://github.com/${e.config.repository}/issues/${t}`.toLowerCase())throw new L(`Non-closing delivery requires the exact canonical OPEN issue and complete title/body.`);return n}function kS(e,t,n=!1){if(n?e.state!==`open`||e.draft||e.merged||t.state!==`closed`||t.draft||!t.merged:e.state!==t.state||e.draft!==t.draft||e.merged!==t.merged)throw new L(`Non-closing PR state/draft/merged readback drifted; reconcile read-only.`);if(e.node_id!==t.node_id||e.head.sha!==t.head.sha||e.head.ref!==t.head.ref||e.base.sha!==t.base.sha||e.base.ref!==t.base.ref||e.body!==t.body||e.title!==t.title||e.user.login.toLowerCase()!==t.user.login.toLowerCase())throw new L(`Non-closing PR identity, reference, message or head/base drifted; reconcile read-only.`)}function AS(e,t){if(e.node_id!==t.node_id||e.title!==t.title||e.body!==t.body)throw new L(`Non-closing issue identity/title/criteria drifted; reconcile read-only.`)}function jS(e){if(e!==void 0&&typeof e!=`boolean`)throw new L(`nonClosing must be a boolean.`);return e===!0}async function MS(e,t){let n=await JS(e.clients.role===`author`?e:{...e,clients:await ch({config:e.config,identity:e.config.roles.author.identity,role:`author`}),reviewerClients:e.clients},t);if(n.rules.visibility!==`complete`||n.approvalEligibility===`insufficient-permission`)throw new L(`Non-closing delivery requires complete native rule visibility and an independent reviewer route.`);return n}async function NS(e,t){let n=null,r=new Set,i=new Map,a;for(let o=0;o<20;o++){let o=await e.clients.graphql(`query DeliveryNonClosingCommits($owner:String!,$repo:String!,$number:Int!,$cursor:String){repository(owner:$owner,name:$repo){nameWithOwner pullRequest(number:$number){id number headRefOid baseRefOid baseRefName commits(first:100,after:$cursor){totalCount nodes{commit{oid message parents(first:100){totalCount nodes{oid} pageInfo{hasNextPage endCursor}}}} pageInfo{hasNextPage endCursor}}}}}`,{...e.repo,number:t.number,cursor:n}),s=o.repository?.pullRequest,c=s?.commits;if(o.repository?.nameWithOwner?.toLowerCase()!==e.config.repository.toLowerCase()||s?.id!==t.node_id||s.number!==t.number||s.headRefOid!==t.head.sha||s.baseRefOid!==t.base.sha||s.baseRefName!==t.base.ref||!c||!Array.isArray(c.nodes)||c.nodes.length>100||!Number.isSafeInteger(c.totalCount)||c.totalCount<1||c.totalCount>2e3||a!==void 0&&a!==c.totalCount)throw new L(`Incomplete or moved introduced commit graph at the non-closing head/base.`);a=c.totalCount;for(let e of c.nodes){let t=e?.commit;if(!t||!LS(t.oid)||i.has(t.oid)||!t.parents||!Array.isArray(t.parents.nodes)||t.parents.nodes.length>100||!Number.isSafeInteger(t.parents.totalCount)||t.parents.totalCount<1||t.parents.totalCount!==t.parents.nodes.length||t.parents.pageInfo?.hasNextPage!==!1||t.parents.nodes.some(e=>!LS(e?.oid)))throw new L(`Incomplete, duplicate or truncated introduced commit identity/parents.`);CS(t.message),i.set(t.oid,t.message)}if(n=DS(c,r),n===null){if(i.size!==a||!i.has(t.head.sha))throw new L(`Introduced commit count/head is incomplete.`);return}}throw new L(`Non-closing commit graph exceeds the bounded readback window.`)}async function PS(e,t,n){let r=new Set,i;for(let a=1;a<=20;a++){let o=(await e.clients.rest.repos.compareCommitsWithBasehead({...e.repo,basehead:`${t}...${n}`,per_page:100,page:a})).data;if(o.base_commit?.sha!==t||!LS(o.merge_base_commit?.sha)||![`ahead`,`diverged`].includes(o.status)||!Number.isSafeInteger(o.total_commits)||o.total_commits<1||o.total_commits>2e3||i!==void 0&&i!==o.total_commits||!Array.isArray(o.commits)||o.commits.length>100)throw new L(`Incomplete introduced commit range before non-closing publication.`);i=o.total_commits;for(let e of o.commits){if(!LS(e.sha)||r.has(e.sha)||!Array.isArray(e.parents)||e.parents.length<1||e.parents.length>100||e.parents.some(e=>!LS(e.sha)))throw new L(`Incomplete or duplicate introduced commit identity.`);CS(e.commit?.message),r.add(e.sha)}if(r.size===i&&r.has(n))return;if(o.commits.length<100)throw new L(`Truncated introduced commit range before publication.`)}throw new L(`Introduced commit range exceeds the bounded readback window.`)}async function FS(e,t,n){if(typeof n.node_id!=`string`||!n.node_id||n.html_url?.toLowerCase()!==`https://github.com/${e.config.repository}/pull/${n.number}`.toLowerCase())throw new L(`Incomplete non-closing PR node identity.`);ES(e,t,n.body),CS(n.title);let r=await OS(e,t),i=(await e.clients.rest.repos.get({...e.repo})).data;if(i.full_name?.toLowerCase()!==e.config.repository.toLowerCase()||n.base.ref!==i.default_branch||typeof i.node_id!=`string`||!i.node_id)throw new L(`Non-closing PR must target the canonical default repository/base.`);let a=await MS(e,n.base.ref);if(n.user.login.toLowerCase()!==a.author.actorLogin.toLowerCase())throw new L(`Non-closing PR author differs from the configured author.`);let o=null,s=new Set,c=new Map,l=!1;for(let u=0;u<20;u++){let d=await e.clients.graphql(`query DeliveryNonClosingReferences($owner:String!,$repo:String!,$number:Int!,$cursor:String){repository(owner:$owner,name:$repo){id nameWithOwner issue(number:$number){id number state timelineItems(first:100,after:$cursor,itemTypes:[CROSS_REFERENCED_EVENT]){nodes{... on CrossReferencedEvent{id actor{login} isCrossRepository willCloseTarget source{__typename ... on Issue{id number repository{id nameWithOwner}} ... on PullRequest{id number repository{id nameWithOwner}}} target{__typename ... on Issue{id number repository{id nameWithOwner}} ... on PullRequest{id number repository{id nameWithOwner}}}}} pageInfo{hasNextPage endCursor}}}}}`,{...e.repo,number:t,cursor:o}),f=d.repository?.issue,p=f?.timelineItems;if(d.repository?.id!==i.node_id||d.repository.nameWithOwner?.toLowerCase()!==e.config.repository.toLowerCase()||f?.id!==r.node_id||f.number!==t||f.state!==`OPEN`||!p||!Array.isArray(p.nodes)||p.nodes.length>100)throw new L(`Incomplete or conflicting native non-closing issue identity.`);for(let o of p.nodes){let s=o?.source,u=o?.target;if(!o||!IS(o.id)||!s||!u||![`Issue`,`PullRequest`].includes(s.__typename)||!IS(s.id)||!Number.isSafeInteger(s.number)||s.number<=0||!IS(s.repository?.id)||typeof s.repository.nameWithOwner!=`string`||u.__typename!==`Issue`||u.id!==r.node_id||u.number!==t||u.repository?.id!==i.node_id||u.repository.nameWithOwner?.toLowerCase()!==e.config.repository.toLowerCase()||typeof o.isCrossRepository!=`boolean`||typeof o.willCloseTarget!=`boolean`||!IS(o.actor?.login))throw new L(`Incomplete native cross-reference event identity/actor.`);let d=JSON.stringify([s.__typename,s.id,s.number,s.repository.id,s.repository.nameWithOwner.toLowerCase(),u.id,u.number,u.repository.id,u.repository.nameWithOwner.toLowerCase(),o.actor.login.toLowerCase(),o.isCrossRepository,o.willCloseTarget]);if(c.has(o.id)&&c.get(o.id)!==d)throw new L(`Conflicting duplicate native reference event.`);if(c.set(o.id,d),s.id===n.node_id||s.__typename===`PullRequest`&&s.number===n.number&&s.repository.nameWithOwner.toLowerCase()===e.config.repository.toLowerCase()){if(s.__typename!==`PullRequest`||s.id!==n.node_id||s.number!==n.number||s.repository.id!==i.node_id||s.repository.nameWithOwner.toLowerCase()!==e.config.repository.toLowerCase()||o.isCrossRepository||o.willCloseTarget!==!1||o.actor.login.toLowerCase()!==a.author.actorLogin.toLowerCase())throw new L(`Conflicting, closing or unauthorized native PR reference.`);l=!0}}if(o=DS(p,s),o===null)break;if(u===19)throw new L(`Native non-closing references exceed the bounded readback window.`)}if(!l)throw new L(`Missing authorized native non-closing PR-to-issue reference.`);if(await BS(e,n.number,t,!0,n.node_id),await NS(e,n),!n.merged){let t=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${n.base.ref}`})).data;if(t.ref!==`refs/heads/${n.base.ref}`||t.object.type!==`commit`||t.object.sha!==n.base.sha)throw new L(`Non-closing default base has moved or is incomplete.`)}return AS(r,await OS(e,t)),kS(n,await zS(e,n.number)),r}function IS(e){return typeof e==`string`&&e.trim().length>0}function LS(e){return typeof e==`string`&&xS.test(e)}function RS(e){if(typeof e!=`string`||!SS.test(e)||e.startsWith(`/`)||e.endsWith(`/`)||e.endsWith(`.lock`))throw new L(`Invalid GitHub branch name.`)}async function zS(e,t){if(e.config.repository.toLowerCase()!==`${e.repo.owner}/${e.repo.repo}`.toLowerCase())throw new L(`Configured and selected GitHub repository identities disagree.`);let n=(await e.clients.rest.pulls.get({...e.repo,pull_number:t})).data;if(n.number!==t||typeof n.base.repo?.full_name!=`string`||typeof n.head.repo?.full_name!=`string`||n.base.repo?.full_name.toLowerCase()!==e.config.repository.toLowerCase()||n.head.repo?.full_name.toLowerCase()!==e.config.repository.toLowerCase()||!LS(n.head.sha)||!LS(n.base.sha)||n.state!==`open`&&n.state!==`closed`||typeof n.merged!=`boolean`||typeof n.draft!=`boolean`||n.merged&&n.state!==`closed`)throw new L(`GitHub PR identity or exact head readback is invalid.`);return RS(n.head.ref),RS(n.base.ref),n}async function BS(e,t,n,r=!1,i,a=!1,o,s){let c=null,l=new Set,u=0;for(let d=0;d<20;d++){let d=await e.clients.graphql(`query DeliveryClosingIssues($owner:String!,$repo:String!,$number:Int!,$cursor:String){repository(owner:$owner,name:$repo){nameWithOwner pullRequest(number:$number){id number closingIssuesReferences(first:100,after:$cursor){nodes{__typename id number repository{id nameWithOwner}} pageInfo{hasNextPage endCursor}}}}}`,{...e.repo,number:t,cursor:c}),f=d.repository?.pullRequest?.closingIssuesReferences;if(typeof d.repository?.nameWithOwner!=`string`||d.repository.nameWithOwner.toLowerCase()!==e.config.repository.toLowerCase()||d.repository?.pullRequest?.number!==t||i!==void 0&&d.repository?.pullRequest?.id!==i||!f||!Array.isArray(f.nodes)||f.nodes.length>100||typeof f.pageInfo?.hasNextPage!=`boolean`||f.pageInfo.endCursor!==null&&typeof f.pageInfo.endCursor!=`string`)throw new L(`Incomplete or conflicting native GitHub PR issue association readback.`);for(let t of f.nodes){if(a&&(!t||t.__typename!==`Issue`||!IS(o)||t.id!==o||!IS(s)||t.repository?.id!==s))throw new L(`Incomplete or conflicting typed closing issue/repository identity before body transition.`);if(r)throw new L(`Non-closing PR has an unintended native closing association.`);if(!t||!Number.isSafeInteger(t.number)||t.number<=0||typeof t.repository?.nameWithOwner!=`string`||!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u.test(t.repository.nameWithOwner))throw new L(`Incomplete native PR closing-issue identity.`);if(t.number===n&&t.repository.nameWithOwner.toLowerCase()===e.config.repository.toLowerCase())u++;else if(a)throw new L(`Existing PR has conflicting closing associations; body transition refused.`)}if(!f.pageInfo.hasNextPage){if(!r&&u!==1)throw new L(`Native GitHub PR closing-issue association does not identify the intended issue.`);return}let p=f.pageInfo.endCursor;if(!p||l.has(p))throw new L(`Native PR issue pagination did not advance.`);l.add(p),c=p}throw new L(`Native PR issue association exceeds the bounded readback window.`)}async function VS(e,t,n){let r=[];for(let i=1;i<=20;i++){let a=(await e.clients.rest.pulls.list({...e.repo,head:`${e.repo.owner}:${t}`,...n===void 0?{}:{base:n},state:`all`,page:i,per_page:100})).data;if(!Array.isArray(a)||a.some(e=>!e||!Number.isSafeInteger(e.number)||e.number<=0))throw new L(`Incomplete GitHub PR match readback.`);if(r.push(...a),a.length<100)return r}throw new L(`GitHub PR match history exceeds the bounded readback window.`)}async function HS(e,t,n,r=!1){let i=await zS(e,n);if(r?await FS(e,t,i):await BS(e,n,t),!i.merged){let n=await Nv(e,t);if(n.length>0){let e=n.filter(e=>e.name===i.head.ref);if(e.length!==1||e[0].sha!==i.head.sha)throw new L(`Native linked issue branches conflict with the exact PR head/ref.`)}let r=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${i.head.ref}`})).data;if(r.ref!==`refs/heads/${i.head.ref}`||r.object.type!==`commit`||r.object.sha!==i.head.sha)throw new L(`Current remote PR head/ref readback is incomplete or has moved.`)}return i}async function US(e,t){let n=jS(t.nonClosing);if(n&&(t.issueNumber===void 0||t.prNumber===void 0))throw new L(`Non-closing inspection requires explicit canonical issue and PR numbers.`);let r=t.prNumber;if(r===void 0){if(t.issueNumber===void 0)throw new L(`prNumber or issueNumber is required.`);let n=await Nv(e,t.issueNumber);if(n.length!==1)throw new L(`Issue-only PR inspection requires one GitHub-linked issue branch. After publication, supply the exact issue and PR numbers (CLI --issue and --pr) to verify the native PR closing-issue association.`);let i=n[0].name,a=await VS(e,i);if(a.length!==1)throw new L(`Select an explicit PR number when the remote issue branch has zero or multiple PRs.`);r=a[0].number}let i=t.issueNumber===void 0?await zS(e,r):await HS(e,t.issueNumber,r,n);return{prNumber:i.number,url:i.html_url,state:i.state,draft:i.draft,headSha:i.head.sha,headBranch:i.head.ref,baseBranch:i.base.ref,merged:i.merged}}async function WS(e,t=`open`){return{schemaVersion:`ai-delivery.pr-list@1`,pullRequests:(await e.clients.rest.paginate(e.clients.rest.pulls.list,{...e.repo,state:t,per_page:100})).map(e=>({number:e.number,state:e.state,draft:e.draft??!1,headSha:e.head.sha,baseSha:e.base.sha,url:e.html_url}))}}async function GS(e,t){let n=(await e.clients.rest.pulls.get({...e.repo,pull_number:t})).data,[r,i,a]=await Promise.all([e.clients.rest.checks.listForRef({...e.repo,ref:n.head.sha,per_page:100}),e.clients.rest.repos.getCombinedStatusForRef({...e.repo,ref:n.head.sha}),mS(e,t,n.head.sha)]);return{schemaVersion:`ai-delivery.pr-checks@1`,prNumber:n.number,headSha:n.head.sha,combinedStatus:i.data.state,reviewState:a,checkRuns:r.data.check_runs.map(e=>({name:e.name,status:e.status,conclusion:e.conclusion}))}}function KS(e){if(typeof e!=`object`||!e)return null;let t=e.required_approving_review_count;return typeof t==`number`&&Number.isSafeInteger(t)&&t>=0?t:null}function qS(e){return e.status===200&&Array.isArray(e.data)&&e.data.length===0&&e.headers!==void 0&&e.headers!==null&&(e.headers.link===void 0||e.headers.link===``)}async function JS(e,t,n,r=`publication`,i){if(t===void 0)try{t=(await e.clients.rest.repos.get({...e.repo})).data.default_branch}catch{throw new L(`Author cannot read the selected GitHub repository; verify configured access.`)}let a=async()=>{await i?.checkResources(),i?.signal.throwIfAborted()};await a();let o=e.config.roles.author.authSource??`app`,s=r===`development`&&o===`app`&&e.clients.authSource===`personal`;if(e.clients.authSource!==o&&!s)throw new L(r===`publication`?`PR publication requires the configured author credential; configure the personal author role for personal publication.`:`Development access preflight requires the configured author credential or the explicit personal author override.`);if(e.clients.role!==`author`||!e.clients.authenticatedAuthor)throw new L(`Delivery access preflight requires authenticated author identity readback.`);let c=await e.clients.authenticatedAuthor(i?.signal);if(await a(),!c.actorLogin||!c.credentialIdentity)throw new L(`Author GitHub identity readback is incomplete.`);let l=n??e.reviewerClients??await ch({config:e.config,identity:e.config.roles.reviewer.identity,role:`reviewer`,selectedAuthor:e.clients,...i===void 0?{}:{signal:i.signal}});if(await a(),l.role!==`reviewer`||l.authSource!==`app`||!l.appActorLogin)throw new L(`Configured reviewer GitHub App identity is unavailable.`);let u=await l.appActorLogin(i?.signal);if(await a(),!u)throw new L(`Reviewer GitHub App actor lookup is incomplete.`);if(c.actorLogin.toLowerCase()===u.toLowerCase())throw new L(`Author and reviewer resolve to the same GitHub actor; select distinct configured credentials.`);try{let t=(await l.rest.repos.get({...e.repo,...i===void 0?{}:{request:{signal:i.signal}}})).data;if(await a(),t.full_name.toLowerCase()!==`${e.repo.owner}/${e.repo.repo}`.toLowerCase())throw new L(`Reviewer GitHub App repository readback disagrees with the selected checkout.`)}catch(e){throw e instanceof L?e:new L(`Reviewer GitHub App cannot read the selected repository; verify its installation and repository access.`)}let[d,f]=await Promise.allSettled([e.clients.rest.request(`GET /repos/{owner}/{repo}/rules/branches/{branch}`,{...e.repo,branch:t,...i===void 0?{}:{request:{signal:i.signal}}}),e.clients.rest.request(`GET /repos/{owner}/{repo}/branches/{branch}/protection`,{...e.repo,branch:t,...i===void 0?{}:{request:{signal:i.signal}}})]);await a();let p=!1,m=f.status===`rejected`?f.reason:null;if(d.status===`fulfilled`&&qS(d.value)&&m?.status===404&&m.response?.status===404&&m.response.data?.message===`Branch not protected`){let n={...e.repo,...i===void 0?{}:{request:{signal:i.signal}}},[r,o,s]=await Promise.allSettled([e.clients.rest.request(`GET /repos/{owner}/{repo}`,n),e.clients.rest.request(`GET /repos/{owner}/{repo}/branches/{branch}`,{...n,branch:t}),e.clients.rest.request(`GET /repos/{owner}/{repo}/rulesets`,{...n,includes_parents:!0,per_page:100,page:1})]);if(await a(),r.status===`fulfilled`&&o.status===`fulfilled`&&s.status===`fulfilled`){let n=r.value.data,i=o.value.data;p=r.value.status===200&&o.value.status===200&&typeof n?.full_name==`string`&&n.full_name.toLowerCase()===`${e.repo.owner}/${e.repo.repo}`.toLowerCase()&&(n.permissions?.push===!0||n.permissions?.admin===!0)&&i?.name===t&&i.protected===!1&&i.protection?.enabled===!1&&qS(s.value)}}let h=[];if(d.status===`fulfilled`&&Array.isArray(d.value.data)){for(let e of d.value.data)if(e.type===`pull_request`){let t=KS(e.parameters);t!==null&&h.push(t)}}if(f.status===`fulfilled`){let e=f.value.data,t=KS(e.required_pull_request_reviews);t!==null&&h.push(t)}let g=d.status===`fulfilled`&&Array.isArray(d.value.data)&&(d.value.headers?.link===void 0||d.value.headers.link===``),_=Number(g)+Number(f.status===`fulfilled`||p),v=_===2?`complete`:_===1?`partial`:`unknown`,y=h.length>0?Math.max(...h):p?0:null,b=y!==null&&y>0&&l.effectiveContentsPermission===`read`;return{author:{actorLogin:c.actorLogin,authSource:e.clients.authSource,credentialSource:e.clients.credentialSource??`unreported`,identity:s?`personal`:e.config.roles.author.identity},reviewer:{actorLogin:u,credentialSource:l.credentialSource??`unreported`,effectiveContentsPermission:l.effectiveContentsPermission??`unknown`,identity:e.config.roles.reviewer.identity,repositoryAccess:`readable`},rules:{observedRequiredApprovals:y,visibility:v},approvalEligibility:b?`insufficient-permission`:`unknown`,nextAction:b?`The reviewer App token has Contents: read, but the visible rule requires approval from a reviewer with repository write access. To use the App for required approval, grant Contents: write, accept the installation permission change, and obtain a fresh token before publication.`:v===`complete`&&y===null?`No required approving review was observed in the visible rules. Confirm the live PR review decision after exact-head submission.`:v===`complete`?`Confirm whether the reviewer approval counts after exact-head submission; installation scopes do not prove required-review eligibility.`:`Inspect the active branch review rule with an authorized repository view and confirm whether the reviewer approval counts after exact-head submission.`}}async function YS(e,t){let n=jS(t.nonClosing);if(t.prNumber!==void 0&&(!Number.isSafeInteger(t.prNumber)||t.prNumber<=0))throw new L(`Existing PR selector must be a positive safe integer.`);let r=n?await OS(e,t.issueNumber):(await e.clients.rest.issues.get({...e.repo,issue_number:t.issueNumber})).data;if(`pull_request`in r||r.number!==t.issueNumber||r.state!==`open`)throw new L(`PR creation requires the requested open GitHub issue.`);let i=(await e.clients.rest.repos.get({...e.repo})).data;if(i.full_name?.toLowerCase()!==e.config.repository.toLowerCase()||e.config.repository.toLowerCase()!==`${e.repo.owner}/${e.repo.repo}`.toLowerCase())throw new L(`Configured and selected GitHub repository identities disagree.`);if(n&&!IS(i.node_id))throw new L(`Incomplete canonical non-closing repository node identity.`);let a=t.baseBranch??i.default_branch;if(a!==i.default_branch)throw new L(`PR delivery requires the repository default branch for durable issue association.`);RS(a),t.headBranch!==void 0&&RS(t.headBranch);let o=t.prNumber===void 0?void 0:await zS(e,t.prNumber),s=t.draft===!1&&t.headBranch!==void 0,c=o?await VS(e,o.head.ref,a):s?await VS(e,t.headBranch,a):void 0,l=o?o.head.ref:s&&c.length>0?t.headBranch:await Pv(e,t.issueNumber,t.headBranch);if(t.headBranch!==void 0&&l!==t.headBranch)throw new L(`Explicit PR and head selectors disagree.`);RS(l);let u=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${l}`})).data;if(u.ref!==`refs/heads/${l}`||u.object.type!==`commit`||!LS(u.object.sha))throw new L(`Remote issue branch head/ref readback is invalid.`);let d=c??await VS(e,l,a);if(d.length>1||o&&(d.length!==1||d[0].number!==o.number))throw new L(`Remote issue branch has conflicting PR matches.`);let f=o??(d[0]===void 0?void 0:await zS(e,d[0].number)),p=t.body??(n?f?.body??wS(e,t.issueNumber):`Closes #${t.issueNumber}`);if(!p.trim())throw new L(`PR body must contain text.`);let m=n?TS(e,t.issueNumber,p):RegExp(`(?:close[sd]?|fix(?:es|ed)?|resolve[sd]?)\\s+#${t.issueNumber}(?![0-9])`,`iu`).test(p)?p:`${p}\n\nCloses #${t.issueNumber}`,h=n&&f!==void 0&&f.body!==m;if(h&&(t.prNumber===void 0||t.body===void 0))throw new L(`Non-closing body transition requires an explicit existing PR number and body.`);if(f&&(f.head.sha!==u.object.sha||f.head.ref!==l||f.base.ref!==a||f.state!==`open`||f.merged||!h&&t.body!==void 0&&f.body!==m||t.title!==void 0&&f.title!==t.title))throw new L(`Existing remote PR conflicts with the requested branch, intent or state.`);let g=n?await MS(e,a):await JS(e,a);if(f&&f.user.login.toLowerCase()!==g.author.actorLogin.toLowerCase())throw new L(`Existing PR author differs from the configured authenticated author.`);if(f&&(typeof f.node_id!=`string`||!f.node_id))throw new L(`Existing PR publication identity is incomplete.`);n&&CS(t.title??f?.title??r.title);let _=t.title??r.title,v,y=f,b=h,x=f?.body,ee=f?.draft,S=!1,te=async()=>{n&&AS(r,await OS(e,t.issueNumber))},ne=async()=>{let o=await HS(e,t.issueNumber,y.number,n&&!b);if(o.state!==`open`||o.merged||o.node_id!==y.node_id||o.head.sha!==u.object.sha||o.head.ref!==l||o.base.ref!==a||o.base.sha!==y.base.sha||o.user.login.toLowerCase()!==g.author.actorLogin.toLowerCase()||h&&!S&&o.draft!==ee||o.body!==x||o.title!==y.title)throw new L(`Existing PR publication head, identity, intent or author readback drifted.`);if(b){await BS(e,o.number,t.issueNumber,!1,o.node_id,!0,r.node_id,i.node_id),CS(o.title),await NS(e,o);let n=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${a}`})).data;if(n.ref!==`refs/heads/${a}`||n.object.type!==`commit`||n.object.sha!==o.base.sha)throw new L(`Non-closing transition default base drifted.`);kS(o,await zS(e,o.number))}return await te(),o},re=async()=>{let t=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${a}`})).data;if(t.ref!==`refs/heads/${a}`||t.object.type!==`commit`||!LS(t.object.sha))throw new L(`Incomplete publication default base.`);if(v!==void 0&&v!==t.object.sha)throw new L(`Publication default base drifted before creation.`);v=t.object.sha,n&&await PS(e,t.object.sha,u.object.sha);let r=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${l}`})).data,i=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${a}`})).data;if(r.ref!==u.ref||r.object.type!==`commit`||r.object.sha!==u.object.sha||i.ref!==t.ref||i.object.type!==`commit`||i.object.sha!==t.object.sha)throw new L(`Non-closing publication head/base drifted.`);await te()};if(f?f=await ne():await re(),t.dryRun)return{dryRun:!0,...f===void 0?{}:{prNumber:f.number,draft:f.draft},...n?{nonClosing:!0,nonClosingVerified:f!==void 0&&!b,body:m,bodyTransition:b}:{},headSha:u.object.sha,headBranch:l,baseBranch:a,reviewRoute:g};let ie=!1;if(f){if(b&&(f=await ne(),await e.clients.rest.pulls.update({...e.repo,pull_number:f.number,body:m}),b=!1,x=m,f=await ne()),t.draft===!1&&f.draft){if(f=await ne(),f.draft){let t=await e.clients.graphql(`mutation DeliveryReadyPr($id:ID!){markPullRequestReadyForReview(input:{pullRequestId:$id}){pullRequest{id isDraft}}}`,{id:f.node_id});if(t?.markPullRequestReadyForReview?.pullRequest?.id!==f.node_id||t.markPullRequestReadyForReview.pullRequest.isDraft!==!1)throw new L(`PR promotion mutation readback is incomplete or conflicting; reconcile this PR.`);S=!0}if(f=await ne(),f.draft)throw new L(`PR promotion readback is still draft.`)}}else{await re();let n;try{n=await e.clients.rest.pulls.create({...e.repo,head:l,base:a,title:_,body:m,draft:t.draft!==!1})}catch(e){throw new L(`PR creation acknowledgement is uncertain; reconcile the remote head read-only before any new mutation. ${e instanceof Error?e.message:`Unknown failure`}`)}if(!Number.isSafeInteger(n.data.number)||n.data.number<=0)throw new L(`PR creation acknowledgement lacks a valid PR identity; reconcile the remote head read-only, do not create again.`);ie=!0;try{f=await zS(e,n.data.number)}catch(e){throw new L(`GitHub returned created PR #${n.data.number}; identity readback is unresolved. Reconcile read-only; do not create again. ${e instanceof Error?e.message:`Unknown failure`}`)}}try{if(ie&&(f.body!==m||f.title!==_||f.draft!==(t.draft!==!1)||f.state!==`open`||f.merged||f.base.sha!==v))throw new L(`Created PR body, title, draft/open state or default base differs from publication intent.`);if(f.head.sha!==u.object.sha||f.head.ref!==l||f.base.ref!==a)throw new L(`GitHub PR creation readback drifted.`);if(f.user.login.toLowerCase()!==g.author.actorLogin.toLowerCase())throw new L(`Published PR author differs from the configured authenticated author.`);if(n){let n=await HS(e,t.issueNumber,f.number,!0);kS(f,n),f=n,await te()}else await BS(e,f.number,t.issueNumber);if(ie){let t=await zS(e,f.number);kS(f,t),f=t}}catch(e){throw ie?new L(`GitHub created PR #${f.number} (${f.html_url}) at ${f.head.sha}; post-publication association/identity verification is unresolved. Reconcile this PR read-only; do not create again. ${e instanceof Error?e.message:`Unknown failure`}`):e}return{prNumber:f.number,url:f.html_url,headSha:f.head.sha,draft:f.draft,reviewRoute:g,...n?{nonClosing:!0}:{}}}async function XS(e,t){let n=jS(t.nonClosing),r=await HS(e,t.issueNumber,t.prNumber,n),i=n?await OS(e,t.issueNumber):void 0,a=await bS({context:e,artifact:hS(t.artifact),issueNumber:t.issueNumber,prNumber:t.prNumber,...t.dryRun===void 0?{}:{dryRun:t.dryRun}});return n&&(kS(r,await HS(e,t.issueNumber,t.prNumber,!0)),AS(i,await OS(e,t.issueNumber))),a}async function ZS(e,t){let n=[];for(let r=1;r<=20;r++){let i=(await e.clients.rest.pulls.listReviews({...e.repo,pull_number:t,page:r,per_page:100})).data;if(n.push(...i),i.length<100)return n}throw new L(`GitHub review history exceeds the bounded readback window.`)}async function QS(e,t){let n=jS(t.nonClosing);if(n&&t.strategy!==void 0&&t.strategy!==`squash`)throw new L(`Non-closing merge requires squash with explicit safe messages.`);if(e.clients.role!==`author`||e.clients.authSource!==(e.config.roles.author.authSource??`app`)||!e.clients.authenticatedAuthor)throw new L(`Merge and finish require the configured authenticated author role.`);let r=await e.clients.authenticatedAuthor();if(!r.actorLogin||!r.credentialIdentity)throw new L(`Author identity readback is incomplete.`);let i=await HS(e,t.issueNumber,t.prNumber,n),a=i,o=n?await OS(e,t.issueNumber):void 0,s=n?{commit_title:i.title,commit_message:`${wS(e,t.issueNumber)}\n\nDelivered by PR #${i.number}.`}:void 0;if(s&&(CS(s.commit_title),CS(s.commit_message)),t.reviewedHeadSha!==void 0&&t.reviewedHeadSha!==i.head.sha)throw new L(`Requested reviewed head differs from the GitHub PR.`);if(i.merged&&i.state===`closed`&&LS(i.merge_commit_sha))return{mergeSha:i.merge_commit_sha,headSha:i.head.sha,reused:!0};if((await JS(e,i.base.ref)).approvalEligibility===`insufficient-permission`)throw new L(`Configured reviewer App is ineligible for the required approval.`);if(i.state!==`open`||i.draft)throw new L(`GitHub PR must be open and ready for merge.`);let c=e.reviewerClients??await ch({config:e.config,identity:e.config.roles.reviewer.identity,role:`reviewer`,selectedAuthor:e.clients});if(c.role!==`reviewer`||c.authSource!==`app`||!c.appActorLogin)throw new L(`Independent reviewer App route is unavailable.`);let l=await c.appActorLogin();if(!i.user?.login||l.toLowerCase()===i.user.login.toLowerCase())throw new L(`Reviewer App must differ from the PR author.`);let u=(await ZS(e,t.prNumber)).filter(e=>e.user?.login.toLowerCase()===l.toLowerCase()&&e.commit_id===i.head.sha&&e.state===`APPROVED`&&/<!-- ai-delivery-review-artifact: sha256:[a-f0-9]{64} -->/u.test(e.body??``));if(u.length!==1)throw new L(`GitHub requires one unambiguous exact-head independent App review.`);let d=u[0],f=(await e.clients.rest.pulls.getReview({...e.repo,pull_number:t.prNumber,review_id:d.id})).data;if(f.id!==d.id||f.state!==`APPROVED`||f.commit_id!==i.head.sha||f.user?.login.toLowerCase()!==l.toLowerCase()||f.body!==d.body)throw new L(`Independent GitHub review readback changed or was dismissed.`);let p=gS(f.body);if(p.verdict!==`approve`||p.issueNumber!==t.issueNumber||p.prNumber!==null&&p.prNumber!==t.prNumber||p.authorIdentity!==e.config.roles.author.identity||p.reviewerIdentity!==e.config.roles.reviewer.identity||p.head.sha!==i.head.sha)throw new L(`Independent review artifact binding is stale, foreign or rejected.`);let m=(await e.clients.rest.git.getCommit({...e.repo,commit_sha:i.head.sha})).data;if(m.sha!==p.head.sha||m.tree.sha!==p.head.tree)throw new L(`Independent review tree differs from the remote commit.`);if(p.diffScopeHash!==await vS(e,t.prNumber,i.changed_files))throw new L(`Independent review scope differs from the remote PR diff.`);let h=p.head.sha;if(t.reviewedHeadSha!==void 0&&t.reviewedHeadSha!==h)throw new L(`Requested reviewed head differs from the independent GitHub review.`);let g=await mS(e,t.prNumber,h,{id:d.id,login:l});if(g.submittedReviewAuthorCanPushToRepository!==!0)throw new L(`Specific reviewer App approval is not verifiably qualifying for required review.`);if(g.status!==`satisfied`)throw new L(`GitHub review eligibility is ${g.status}: ${g.nextAction}`);if((await f_({graphql:e.clients.graphql,issueNumber:t.issueNumber,repo:e.repo})).blockers.some(e=>e.state===`OPEN`))throw new L(`GitHub issue has unresolved native blockers.`);if(i=await HS(e,t.issueNumber,t.prNumber,n),n&&(kS(a,i),AS(o,await OS(e,t.issueNumber)),CS(s.commit_title),CS(s.commit_message)),i.head.sha!==h||i.state!==`open`||i.draft||i.mergeable!==!0||i.mergeable_state!==`clean`)throw new L(`GitHub merge eligibility is ${i.mergeable_state??`unknown`}; CLEAN at the reviewed head is required.`);let _=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${i.base.ref}`})).data.object.sha;if(!LS(_)||_!==i.base.sha)throw new L(`GitHub base moved; refresh clean eligibility and independent review before merge.`);if(t.dryRun)return{dryRun:!0,headSha:h,prNumber:i.number,...s===void 0?{}:{nonClosing:!0,...s}};let v=(await e.clients.rest.pulls.merge({...e.repo,pull_number:t.prNumber,sha:h,merge_method:t.strategy??`squash`,...s})).data;if(!v.merged||!LS(v.sha))throw new L(`GitHub refused the reviewed-head merge.`);let y=await HS(e,t.issueNumber,t.prNumber,n);if(n&&(kS(a,y,!0),AS(o,await OS(e,t.issueNumber))),!y.merged||y.state!==`closed`||y.head.sha!==h||y.merge_commit_sha!==v.sha)throw new L(`GitHub merged PR readback disagrees with the reviewed-head mutation.`);return{mergeSha:v.sha,headSha:h,reused:!1}}async function $S(e,t){if(jS(t.nonClosing))throw new L(`Non-closing delivery cannot finish or close its retained issue.`);let n=await QS(e,t);if(t.dryRun)return n;let r=await HS(e,t.issueNumber,t.prNumber);if(!r.merged||r.state!==`closed`||r.merge_commit_sha!==n.mergeSha)throw new L(`Intended GitHub PR is not verifiably merged; issue remains open.`);let i=(await e.clients.rest.issues.get({...e.repo,issue_number:t.issueNumber})).data;if(i.number!==t.issueNumber||`pull_request`in i)throw new L(`Finish target is not the intended GitHub issue.`);i.state!==`closed`&&await e.clients.rest.issues.update({...e.repo,issue_number:t.issueNumber,state:`closed`,state_reason:`completed`});let a=(await e.clients.rest.issues.get({...e.repo,issue_number:t.issueNumber})).data;if(a.number!==t.issueNumber||a.state!==`closed`)throw new L(`GitHub issue closure readback disagrees.`);return{...n,issueClosed:!0}}function eC(e){let t=od(e.root),n=ed(t,`origin`);if(`${n.owner}/${n.repo}`.toLowerCase()!==e.config.repository.toLowerCase()||`${e.repo.owner}/${e.repo.repo}`.toLowerCase()!==e.config.repository.toLowerCase())throw new L(`Investigation repository identity disagrees.`);return t}async function tC(e,t,n){let r=ad(e);for(let e of[w(r,`ai-delivery`),w(r,`ai-delivery`,`writers@1`)]){try{let t=c(e);if(!t.isDirectory()||t.isSymbolicLink())throw new L(`Investigation writer namespace is unsafe.`)}catch(e){if(e.code!==`ENOENT`)throw e}Lv(e)}return Zy(e,t,n)}async function nC(e,t,n,r){let i=(await e.clients.rest.issues.get({...e.repo,issue_number:t})).data;if(i.number!==t||`pull_request`in i||i.state!==r||new URL(i.html_url).pathname.toLowerCase()!==`/${e.config.repository}/issues/${String(t)}`.toLowerCase())throw new L(`Investigation requires the exact native issue and expected state.`);let a=await Nv(e,t);if(a.length!==1||a[0].name!==`issue/${String(t)}`||a[0].sha!==n)throw new L(`Investigation requires one exact unchanged native linked branch.`);if((await e.clients.rest.pulls.list({...e.repo,state:`all`,head:`${e.repo.owner}:${a[0].name}`,per_page:100})).data.length!==0)throw new L(`Investigation completion cannot substitute for PR delivery.`)}function rC(e){return z({schemaVersion:`ai-delivery.investigation-preparation-acknowledgement@1`,preparation:e,authority:`prospective-registration-before-investigation-no-legacy-adoption`})}function iC(e,t){return z({schemaVersion:`ai-delivery.investigation-removal-authority@1`,preparationId:e.preparationId,repository:e.repository,issueNumber:e.row.issueNumber,head:e.head,worktree:e.row.path,branch:e.row.branch,resultDigest:t,disposition:`remove-only-this-unchanged-investigation-worktree-retain-branch-and-evidence`,operationalClosure:`all-investigation-producers-quiescent-and-excluded-through-completion-and-resume-no-outstanding-holds`})}function aC(e,t,n){return z({schemaVersion:`ai-delivery.investigation-result-acceptance@1`,authority:JSON.parse(iC(e,t)),authorityCommentId:n,verdict:`approved`,independentlyReviewed:`complete-durable-result-exact-source-and-removal-scope`})}async function oC(e,t){if(!Number.isSafeInteger(t.issueNumber)||t.issueNumber<=0||!xS.test(t.expectedHeadSha))throw new L(`Investigation preparation requires a positive issue and expected commit.`);let n=eC(e),r=w(n,`.worktrees`,`issue-${String(t.issueNumber)}`);if(t.investigationWorktree!==r||h(r)!==r)throw new L(`Investigation worktree must be the exact canonical .worktrees/issue-N path.`);if(i(w(n,`.issue-cli`,`issues`,String(t.issueNumber))))throw new L(`Historical issue custody remains preservation-only; investigation cannot adopt it.`);let a=await Qx(e),o=wx(n,t.issueNumber),s=fx(n,t.issueNumber);if(await nC(e,t.issueNumber,o.head.sha,`open`),o.head.sha!==t.expectedHeadSha)throw new L(`Investigation preparation source drifted from the expected head.`);if(s===void 0){let t=(await e.clients.rest.repos.get({...e.repo})).data;if(t.full_name.toLowerCase()!==e.config.repository.toLowerCase()||!t.default_branch)throw new L(`Investigation native repository identity is incomplete.`);if((await e.clients.rest.git.getRef({...e.repo,ref:`heads/${t.default_branch}`})).data.object.sha!==o.head.sha)throw new L(`Prospective investigation must begin at the current native default commit.`)}let c=new Date().toISOString(),l={schemaVersion:`ai-delivery.investigation-preparation@1`,repository:e.config.repository,repoRoot:n,row:s?.row??{branch:`issue/${String(t.issueNumber)}`,createdAt:c,identity:e.config.roles.author.identity,issueNumber:t.issueNumber,path:r,status:`active`,type:`issue`,updatedAt:c},...o,operator:{actorLogin:a.operator.actorLogin,credentialIdentity:a.operator.credentialIdentity},reviewerActor:a.reviewerActor},u=ox.parse({...l,preparationId:B(l)});return await tC(n,r,()=>_x(u,async()=>{if(z(wx(n,t.issueNumber))!==z(o))throw new L(`Investigation source changed before preparation acknowledgement.`);await nC(e,t.issueNumber,o.head.sha,`open`);let{commentId:r,url:i,body:a}=await pv(e,{issueNumber:t.issueNumber,body:rC(u)});if(z(wx(n,t.issueNumber))!==z(o))throw new L(`Investigation source changed during preparation acknowledgement.`);return{commentId:r,url:i,body:a}})),{preparation:u,acknowledgement:px(n,t.issueNumber),registered:!0}}async function sC(e,t){if([`prNumber`,`strategy`,`reviewedHeadSha`,`nonClosing`].some(e=>e in t))throw new L(`Investigation completion refuses PR or merge options.`);let n=eC(e),r=fx(n,t.issueNumber);if(!r)throw new L(`No prospective investigation preparation; historical custody cannot be reconstructed.`);let i=T(t.resultPath),a=se(r.row.path,i),o=a===`..`||a.startsWith(`..${ce}`)||oe(a);if(h(i)!==i||!o)throw new L(`Durable investigation result must be canonical and outside the removable worktree.`);let s=H(i,{maxBytes:524288});if(s.length===0)throw new L(`Investigation result must contain durable evidence.`);let c=V(s),l=iC(r,c),u=t.authorityCommentId===void 0?void 0:aC(r,c,t.authorityCommentId),d=async()=>{await nC(e,t.issueNumber,r.head.sha,`closed`);let i=await Dv(e,t.issueNumber);if(i.state!==`closed`||i.closeReason!==`completed`||i.duplicateOf!==null)throw new L(`Investigation requires native completed closed-issue authority.`);let a=px(n,t.issueNumber),o=(await e.clients.rest.issues.getComment({...e.repo,comment_id:a.commentId})).data;if(o.id!==a.commentId||o.body!==rC(r)||o.body!==a.body||o.issue_url.toLowerCase()!==`https://api.github.com/repos/${r.repository}/issues/${String(t.issueNumber)}`.toLowerCase()||o.user?.type!==`User`||o.user.login.toLowerCase()!==r.operator.actorLogin.toLowerCase()||`user:${String(o.user.id)}`!==r.operator.credentialIdentity)throw new L(`Native prospective preparation acknowledgement changed.`);if(t.authorityCommentId===void 0||t.acceptanceCommentId===void 0||u===void 0)throw new L(`Existing authentic operator and independent App acceptance comments are required.`);let s=await rS(e,{repository:r.repository,subject:t.issueNumber,operator:r.operator,reviewerActor:r.reviewerActor,authorityCommentId:t.authorityCommentId,acceptanceCommentId:t.acceptanceCommentId,operatorBody:l,reviewerBody:u,revokedBody:z({schemaVersion:`ai-delivery.investigation-removal-revocation@1`,preparationId:r.preparationId,resultDigest:c,authorityCommentId:t.authorityCommentId})}),d=Date.parse(o.created_at);for(let e of[s.relinquishment,s.acceptance]){let t=Date.parse(e.created_at);if(!Number.isFinite(d)||!Number.isFinite(t)||t<d)throw new L(`Investigation acceptance must follow its prospective preparation.`)}return{acknowledgement:o,closure:i,...s}};if(t.dryRun&&(t.authorityCommentId===void 0||t.acceptanceCommentId===void 0))return Tx(r,e.root),await nC(e,t.issueNumber,r.head.sha,`closed`),{completed:!1,ready:!1,preparationId:r.preparationId,resultDigest:c,authorityBody:l,...u===void 0?{}:{acceptanceBody:u},missingEvidence:`Existing authentic operator and configured-App exact-result acceptance are prerequisites; no submission route is supplied.`};if(!Number.isSafeInteger(t.authorityCommentId)||!Number.isSafeInteger(t.acceptanceCommentId)||t.authorityCommentId<=0||t.acceptanceCommentId<=0)throw new L(`Investigation evidence requires positive native comment IDs.`);return tC(n,r.row.path,()=>vx({preparation:r,result:s,authorityCommentId:t.authorityCommentId,acceptanceCommentId:t.acceptanceCommentId,dryRun:t.dryRun===!0,authorize:d,assertSource:t=>Tx(r,e.root,t),removeSource:()=>Ex(r,e.root)}))}var cC=k().regex(/^sha256:[a-f0-9]{64}$/u),lC=P({maxAggregateRssBytes:A().int().positive().safe(),minFreeDiskBytes:A().int().positive().safe(),maxNewOutputBytes:A().int().positive().safe(),maxCapturedOutputBytes:A().int().positive().safe().max(8*1024**2)}),uC=P({archivePath:k().min(1),archiveSha256:cC,configDigest:cC,packageVersion:k().regex(/^\d+\.\d+\.\d+$/u),repoRoot:k().min(1),repository:k().min(1),reviewRouteDigest:cC,runtimeDirectory:k().min(1),nativePluginRoot:k().min(1).optional(),sourceCommit:k().regex(/^[a-f0-9]{40}$/u),resourceBounds:lC.optional()}),dC=P({schemaVersion:I(`ai-delivery.runtime-stage@1`),stageId:cC,intent:uC,directory:P({device:A().int(),inode:A().int()}),admission:Gv.optional(),status:F([`incomplete`,`complete`]),recordId:cC}).superRefine((e,t)=>{let{recordId:n,...r}=e;(n!==B(r)||e.stageId!==B(e.intent)||e.status===`complete`!=(e.admission!==void 0)||e.admission!==void 0&&(e.admission.sourceCommit!==e.intent.sourceCommit||e.admission.sourceArchiveSha256!==e.intent.archiveSha256||e.admission.packageVersion!==e.intent.packageVersion||e.admission.configDigest!==e.intent.configDigest||e.admission.repository!==e.intent.repository||e.admission.cliPath!==pC(e.intent.runtimeDirectory,e.intent.nativePluginRoot).cliPath||e.admission.mcpLauncherPath!==pC(e.intent.runtimeDirectory,e.intent.nativePluginRoot).mcpLauncherPath||e.admission.pluginManifestPath!==pC(e.intent.runtimeDirectory,e.intent.nativePluginRoot).pluginManifestPath))&&t.addIssue({code:`custom`,message:`Runtime stage identity or completion is corrupt.`})});function fC(e){if(!oe(e)||T(e)!==e)throw new L(`Runtime setup paths must be absolute and canonical.`);let t=e.split(ce).filter(Boolean),n=ce;for(let e of t){n=w(n,e);try{if(c(n).isSymbolicLink())throw new L(`Runtime setup path contains a symbolic link.`)}catch(e){if(e.code!==`ENOENT`)throw e}}return e}function pC(e,t){let n=w(e,`node_modules`,`@aviaratech`,`ai-delivery`),r=t??w(n,`plugins`,`ai-delivery`);return{cliPath:t?w(r,`runtime`,`dist`,`cli.js`):w(n,`dist`,`cli.js`),mcpLauncherPath:w(r,`dist`,`mcp-launcher.js`),pluginManifestPath:w(r,`.claude-plugin`,`plugin.json`)}}function mC(e,t){if(t!==void 0&&(fC(t),t===e||t.startsWith(`${e}${ce}`)||e.startsWith(`${t}${ce}`)))throw new L(`Native plugin cache and owned runtime stage paths must not overlap.`)}function hC(e){if(e.nativePluginRoot===void 0)return;mC(e.runtimeDirectory,e.nativePluginRoot);let t=fC(w(e.runtimeDirectory,`node_modules/@aviaratech/ai-delivery/plugins/ai-delivery`)),n=0,r=(e,t,i)=>{if(i>16||++n>4096)throw new L(`Native plugin inventory exceeds the reviewed layout bound.`);let a=c(e),o=c(t);if(a.isDirectory()&&o.isDirectory()){let n=p(e).sort();if(JSON.stringify(n)!==JSON.stringify(p(t).sort()))throw new L(`Selected native plugin inventory disagrees with reviewed archive bytes.`);for(let a of n)r(w(e,a),w(t,a),i+1)}else if(!a.isFile()||!o.isFile()||a.nlink!==1||o.nlink!==1||a.size!==o.size||!d(e).equals(d(t)))throw new L(`Selected native plugin files disagree with reviewed archive bytes.`)};try{r(t,e.nativePluginRoot,0)}catch(e){throw e instanceof L?e:new L(`Selected native plugin cannot be matched to reviewed archive bytes.`)}}function gC(e,t){fC(e),cC.parse(t);let n=c(e);if(!n.isFile()||n.nlink!==1)throw new L(`Reviewed runtime archive bytes do not match the expected digest.`);let r=d(e);if(V(r)!==t)throw new L(`Reviewed runtime archive bytes do not match the expected digest.`);return r}function _C(e){let t=fC(w(e.runtimeDirectory,`reviewed-archive.tgz`));if(V(H(t))!==e.archiveSha256)throw new L(`Runtime stage archive snapshot bytes changed.`);return t}async function vC(e,t,n,r){if(await n?.(),typeof e.identity!=`string`||!e.identity.trim())throw new L(`Runtime setup requires an explicit configured author identity.`);let i=id(e.repoRoot);if(i!==od(i))throw new L(`Runtime setup requires the primary consumer controller checkout.`);if(cd(i),sd(i).sha!==e.expectedSourceCommit)throw new L(`Primary controller source commit changed.`);fC(e.runtimeDirectory);let a=await hv({identity:e.identity,repoRoot:i,role:`author`,...r===void 0?{}:{signal:r},...e.personalAuth===void 0?{}:{personalAuth:e.personalAuth}});await n?.();let o=Ih({commandName:t,deliveryConfig:a.config,identity:e.identity,...e.personalAuth===void 0?{}:{personalAuth:e.personalAuth}});if(o.error)throw new L(o.error);if(!a.configuration||a.configuration.configDigest!==e.expectedConfigDigest)throw new L(`Primary controller resolver config digest changed.`);let s=await JS(a,void 0,void 0,`publication`,n===void 0||r===void 0?void 0:{signal:r,checkResources:n});if(await n?.(),cd(i),sd(i).sha!==e.expectedSourceCommit)throw new L(`Primary controller source commit changed during preflight.`);return{root:i,configuration:a.configuration,reviewRoute:s}}function yC(e){fC(e);let t=c(e);if(!t.isDirectory()||(t.mode&511)!=448)throw new L(`Runtime stage directory must be private and owned.`);let n;try{n=dC.parse(JSON.parse(H(w(e,`runtime-stage.json`)).toString(`utf8`)))}catch{throw new L(`Runtime stage is unowned, incompatible or corrupt.`)}if(n.intent.runtimeDirectory!==e||t.dev!==n.directory.device||t.ino!==n.directory.inode)throw new L(`Runtime stage directory ownership changed.`);return n.status===`complete`&&(_C(n.intent),hC(n.intent)),n}function bC(e,t){let n=dC.parse({...t,recordId:B(t)});zv(w(e,`runtime-stage.json`),n);let r=yC(e);if(r.recordId!==n.recordId)throw new L(`Runtime stage completion readback changed.`);return r}function xC(e){let t=u(e,`r`);try{o(t)}finally{n(t)}}function SC(e){let t=H(e),r=u(e,`r`);try{o(r)}finally{n(r)}if(xC(C(e)),!H(e).equals(t))throw new L(`Runtime admission third-party replacement conflict.`)}function CC(e,t,n){if(!e.admission)throw new L(`Runtime stage completion is missing.`);return{stageId:e.stageId,admission:e.admission,reused:n,reviewRoute:t,launch:{cli:{command:process.execPath,args:[e.admission.cliPath]},mcp:{command:process.execPath,args:[e.admission.mcpLauncherPath]}}}}function wC(e,t,n){if(e.intent.repoRoot!==t.root||e.intent.repository!==t.configuration.config.repository||e.intent.sourceCommit!==n.expectedSourceCommit||e.intent.configDigest!==n.expectedConfigDigest)throw new L(`Runtime stage primary controller source or configuration changed.`);if(e.intent.reviewRouteDigest!==B(t.reviewRoute))throw new L(`Runtime stage configured actors or review route changed.`)}async function TC(e){if(e.authority!==`runtime:stage`)throw new L(`Explicit runtime:stage authority is required.`);let t=lC.parse({maxAggregateRssBytes:1024**3,minFreeDiskBytes:256*1024**2,maxNewOutputBytes:512*1024**2,maxCapturedOutputBytes:1024**2,...e.resourceBounds});return fC(e.runtimeDirectory),mC(e.runtimeDirectory,e.nativePluginRoot),Cb(e.repoRoot,async n=>{let r=await vC(e,`runtime:stage`,n.checkResources,n.signal);gC(e.archivePath,e.expectedArchiveSha256);let a=uC.parse({archivePath:e.archivePath,archiveSha256:e.expectedArchiveSha256,configDigest:e.expectedConfigDigest,sourceCommit:e.expectedSourceCommit,packageVersion:e.packageVersion,repoRoot:r.root,repository:r.configuration.config.repository,reviewRouteDigest:B(r.reviewRoute),runtimeDirectory:e.runtimeDirectory,resourceBounds:t,...e.nativePluginRoot===void 0?{}:{nativePluginRoot:e.nativePluginRoot}}),o=B(a);if(n.bindCapturedOutput(o),i(e.runtimeDirectory)){let t=yC(e.runtimeDirectory);if(t.stageId!==o)throw new L(`Runtime stage belongs to an incompatible setup intent.`);if(t.status===`complete`){let r=await vC(e,`runtime:stage`,n.checkResources,n.signal);return wC(t,r,e),gC(a.archivePath,a.archiveSha256),SC(w(e.runtimeDirectory,`reviewed-archive.tgz`)),_C(a),Xv(t.admission,r.configuration,t.admission.cliPath),SC(w(e.runtimeDirectory,`runtime-stage.json`)),xC(C(e.runtimeDirectory)),await n.checkResources(),CC(t,r.reviewRoute,!0)}n.assertQuiescent(),_(e.runtimeDirectory,{recursive:!0})}Lv(C(e.runtimeDirectory)),l(e.runtimeDirectory,{mode:448});let s=c(e.runtimeDirectory),u={schemaVersion:`ai-delivery.runtime-stage@1`,stageId:o,intent:a,directory:{device:s.dev,inode:s.ino},status:`incomplete`},d=!1;try{if(xC(C(e.runtimeDirectory)),bC(e.runtimeDirectory,u),d=!0,e.signal?.aborted)throw new L(`Runtime stage cancelled.`);let r=gC(e.archivePath,e.expectedArchiveSha256);if(!Number.isSafeInteger(t.maxNewOutputBytes)||r.length>=t.maxNewOutputBytes)throw new L(`Reviewed archive snapshot exceeds the stage output limit.`);gd(w(e.runtimeDirectory,`reviewed-archive.tgz`),r);let i=_C(a),o=w(e.runtimeDirectory,`.npm`),s=w(o,`cache`),c=w(o,`logs`),l=w(o,`tmp`);for(let e of[s,c,l])Lv(e);let f=w(o,`user.npmrc`),p=w(o,`global.npmrc`);gd(f,Buffer.alloc(0)),gd(p,Buffer.alloc(0)),await n.checkResources(),await n.run([`npm`,`install`,`--prefix`,e.runtimeDirectory,`--omit=dev`,`--ignore-scripts`,`--no-audit`,`--no-fund`,`--package-lock=false`,`--cache`,s,`--logs-dir`,c,`--logs-max`,`0`,`--userconfig`,f,`--globalconfig`,p,i],{...t,maxNewOutputBytes:t.maxNewOutputBytes-r.length,outputRoots:[e.runtimeDirectory]},e.signal,{...process.env,TMPDIR:l,TMP:l,TEMP:l},e.runtimeDirectory);let m=await vC(e,`runtime:stage`,n.checkResources,n.signal);wC({...u,recordId:B(u)},m,e),gC(e.archivePath,e.expectedArchiveSha256),_C(a),hC(a);let h=Zv({...pC(e.runtimeDirectory,e.nativePluginRoot),packageVersion:e.packageVersion,sourceArchiveSha256:e.expectedArchiveSha256,sourceCommit:e.expectedSourceCommit,configuration:m.configuration});if(hC(a),e.signal?.aborted)throw new L(`Runtime stage cancelled.`);n.assertQuiescent(),Xv(h,m.configuration,h.cliPath),await n.checkResources();let g=bC(e.runtimeDirectory,{...u,status:`complete`,admission:h});return Xv(g.admission,m.configuration,g.admission.cliPath),CC(g,m.reviewRoute,!1)}catch(t){if(d){n.assertQuiescent();let t=yC(e.runtimeDirectory);if(t.stageId!==o)throw new L(`Runtime stage cleanup ownership changed.`);if(t.status===`incomplete`)_(e.runtimeDirectory,{recursive:!0});else{let r=await vC(e,`runtime:stage`,n.checkResources,n.signal);return wC(t,r,e),gC(a.archivePath,a.archiveSha256),SC(w(e.runtimeDirectory,`reviewed-archive.tgz`)),_C(a),Xv(t.admission,r.configuration,t.admission.cliPath),SC(w(e.runtimeDirectory,`runtime-stage.json`)),xC(C(e.runtimeDirectory)),CC(t,r.reviewRoute,!0)}}else{n.assertQuiescent();let t=c(e.runtimeDirectory);if(t.dev!==s.dev||t.ino!==s.ino||t.isSymbolicLink())throw new L(`Runtime stage cleanup ownership changed.`);_(e.runtimeDirectory,{recursive:!0})}throw t}},{bounds:{...t,outputRoots:[e.runtimeDirectory]},maxCapturedOutputBytes:t.maxCapturedOutputBytes,...e.signal===void 0?{}:{signal:e.signal}})}var EC=class extends L{admissionId;stageId;status=`commit-status-unknown`;constructor(e,t){super(`Runtime admission commit-status-unknown for ${e}; retry runtime:admit with the same stage ${t} to reconcile durability.`),this.admissionId=e,this.stageId=t}};async function DC(e){if(e.authority!==`runtime:admit`)throw new L(`Explicit runtime:admit authority is required.`);cC.parse(e.stageId),e.expectedPriorAdmissionSha256!==null&&cC.parse(e.expectedPriorAdmissionSha256);let t=await vC(e,`runtime:admit`),n=w(ad(t.root),`ai-delivery`,`runtime-admission.json`);return fC(n),Lv(C(n)),py(n,{projectRoot:t.root,timeout:200,operation:async()=>{let t=yC(e.runtimeDirectory);if(t.stageId!==e.stageId||t.status!==`complete`||!t.admission)throw new L(`Exact completed runtime stage identity is required.`);let r=await vC(e,`runtime:admit`);wC(t,r,e),gC(t.intent.archivePath,t.intent.archiveSha256),_C(t.intent),Xv(t.admission,r.configuration,t.admission.cliPath);let a=Buffer.from(`${JSON.stringify(t.admission,null,2)}\n`);fC(n);let o=i(n)?H(n):void 0,s=()=>{if(fC(n),_C(t.intent),Xv(t.admission,r.configuration,t.admission.cliPath),!i(n)||!H(n).equals(a))throw new L(`Runtime admission third-party replacement conflict; current bytes preserved.`);try{SC(n)}catch{throw!i(n)||!H(n).equals(a)?new L(`Runtime admission third-party replacement conflict; current bytes preserved.`):new EC(t.admission.admissionId,t.stageId)}return{admission:t.admission,reused:!0}};if(o?.equals(a))return s();if((o===void 0?null:V(o))!==e.expectedPriorAdmissionSha256)throw new L(`Runtime admission prior-byte compare-and-swap conflict; current bytes preserved.`);let c=await vC(e,`runtime:admit`);wC(t,c,e),gC(t.intent.archivePath,t.intent.archiveSha256),_C(t.intent),Xv(t.admission,c.configuration,t.admission.cliPath),fC(n);let l=i(n)?H(n):void 0;if((l===void 0?null:V(l))!==e.expectedPriorAdmissionSha256)throw new L(`Runtime admission prior-byte compare-and-swap conflict; current bytes preserved.`);try{zv(n,t.admission)}catch(t){let r=i(n)?H(n):void 0;if(r?.equals(a))return s();throw(r===void 0?null:V(r))===e.expectedPriorAdmissionSha256?t:new L(`Runtime admission third-party replacement conflict; current bytes preserved.`)}return s(),{admission:t.admission,reused:!1}}})}var U=A().int().positive(),OC=M(k().trim().min(1)),kC=`GitHub owner/name. Pass the repository named by the user. An explicit repo avoids launch-directory Git for ordinary remote issue/PR work; retained local modes keep their own checkout requirements.`,AC=k().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u).optional().describe(kC),jC={blockedBy:M(U).optional(),blocks:M(U).optional(),overrideReason:w_.optional(),body:k().optional(),issueType:k().min(1).optional(),labels:OC.optional(),milestone:U.optional(),parentIssueNumber:U.optional(),points:U.optional(),priority:k().min(1).optional(),repo:k().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u).optional().describe(kC),title:k().trim().min(1).max(256)},MC=P({repo:AC,issueNumber:U,investigationWorktree:k().min(1),expectedHeadSha:k().regex(/^[a-f0-9]{40}$/u)}),NC=P({...jC,title:jC.title.optional(),issueNumber:U.optional(),request:k().min(1).optional(),requestId:k().trim().min(1).max(256).optional(),resumeCreated:j().optional(),branch:k().min(1).optional()}),PC=P({repo:AC,issueNumber:U,prNumber:U,nonClosing:j().optional(),reviewedHeadSha:k().regex(/^[a-f0-9]{40}$/u).optional(),strategy:F([`merge`,`squash`,`rebase`]).optional(),dryRun:j().optional()}),FC=P({repo:AC,issueNumber:U,investigation:I(!0),resultPath:k().min(1),authorityCommentId:U.optional(),acceptanceCommentId:U.optional(),dryRun:j().optional()});function IC(e,t,n){let r=e.safeParse(t);r.success||n.addIssue({code:`custom`,message:r.error.message})}var LC={repo:AC,state:F([`open`,`closed`,`all`]).optional(),labels:M(k().min(1).regex(/^[^"\\\r\n]+$/u)).optional(),parentIssueNumber:U.nullable().optional(),issueType:k().min(1).optional(),projectStatus:F([`Todo`,`In Progress`,`Blocked`,`Done`]).nullable().optional(),updatedSince:yu({offset:!0}).optional(),page:U.optional(),perPage:U.max(100).optional()},RC=k().trim().min(1).max(256).regex(/^[^"\\\r\n]+$/u),zC={repo:AC,identity:k().min(1).optional(),expectedSourceCommit:k().regex(/^[a-f0-9]{40}$/u),expectedConfigDigest:k().regex(/^sha256:[a-f0-9]{64}$/u),runtimeDirectory:k().min(1)},BC=[{name:`delivery_health`,commandName:`health`,description:`Read bounded native delivery health for an explicit repository and UTC window`,inputSchema:Gu},{name:`issue_comment`,commandName:`comment`,description:`Post a typed issue journal with authoritative comment readback`,inputSchema:P({...lv.shape,repo:AC}).superRefine(({repo:e,...t},n)=>{let r=lv.safeParse(t);if(!r.success)for(let e of r.error.issues)n.addIssue({code:`custom`,path:e.path,message:e.message})})},{name:`runtime_stage`,commandName:`runtime:stage`,description:`Explicitly stage a reviewed local public archive without host activation or admission`,inputSchema:P({...zC,authority:I(`runtime:stage`),archivePath:k().min(1),expectedArchiveSha256:k().regex(/^sha256:[a-f0-9]{64}$/u),packageVersion:k().regex(/^\d+\.\d+\.\d+$/u),nativePluginRoot:k().min(1).optional(),resourceBounds:P({maxAggregateRssBytes:A().int().positive().safe(),minFreeDiskBytes:A().int().positive().safe(),maxNewOutputBytes:A().int().positive().safe(),maxCapturedOutputBytes:A().int().positive().safe().max(8*1024**2).optional()}).optional()})},{name:`runtime_admit`,commandName:`runtime:admit`,description:`Explicitly admit an exact completed stage with prior-byte compare-and-swap and reconciliation`,inputSchema:P({...zC,authority:I(`runtime:admit`),stageId:k().regex(/^sha256:[a-f0-9]{64}$/u),expectedPriorAdmissionSha256:k().regex(/^sha256:[a-f0-9]{64}$/u).nullable()})},{name:`issue_create`,commandName:`create`,description:`Create a native GitHub tracking issue with configured metadata and relationships`,issueContract:U_,inputSchema:K_(P({...jC,...W_,title:F_.shape.title}))},{name:`issue_start`,commandName:`start`,description:`Start a linked issue, or prospectively register an unchanged host-created investigation worktree`,inputSchema:NC.extend({investigationWorktree:k().optional(),expectedHeadSha:k().optional()}).superRefine((e,t)=>IC(e.investigationWorktree!==void 0||e.expectedHeadSha!==void 0?MC:NC,e,t))},{name:`issue_list`,commandName:`list`,description:`List repository issues with native filters, named organization fields and pagination`,inputSchema:P({...LC,query:RC.optional()})},{name:`issue_search`,commandName:`search`,description:`Search literal issue text in the selected repository with native filters and pagination`,inputSchema:P({...LC,query:RC})},{name:`issue_update`,commandName:`update`,description:`Update native issue fields and exact relationship sets with readback`,inputSchema:K_(P({...W_,repo:AC,blockedBy:M(U).optional(),blocks:M(U).optional(),overrideReason:w_.optional(),body:k().optional(),issueNumber:U,issueType:W_.issueType,labels:OC.optional(),milestone:U.nullable().optional(),parentIssueNumber:U.nullable().optional(),park:I(!0).optional(),points:W_.points,priority:k().min(1).optional(),state:F([`open`,`closed`]).optional(),preserveHistory:j().optional(),closeReason:F([`completed`,`not_planned`,`duplicate`]).optional(),supersededBy:U.optional(),title:W_.title}).superRefine((e,t)=>{(e.closeReason!==void 0||e.supersededBy!==void 0)&&e.state!==`closed`&&t.addIssue({code:`custom`,path:[`state`],message:`Closure details require state closed`,params:{issueCode:`closure.state`}})}))},{name:`issue_info`,commandName:`info`,description:`Read live GitHub issue metadata, relationships and Project status. Pass the requested owner/name as repo; an explicit repo works outside Git without a checkout. This read does not start or update the issue.`,inputSchema:P({issueNumber:U,repo:AC})},{name:`issue_ready_check`,commandName:`ready:check`,description:`Evaluate deterministic readiness from live native issue state`,inputSchema:P({issueNumber:U,repo:jC.repo})},{name:`issue_pr_create`,commandName:`pr:create`,description:`Create or reuse a PR from its GitHub-linked issue branch`,inputSchema:P({repo:AC,issueNumber:U,prNumber:U.optional(),nonClosing:j().optional(),body:k().min(1).optional(),draft:j().optional(),dryRun:j().optional(),title:k().min(1).optional(),headBranch:k().min(1).optional()})},{name:`issue_pr_info`,commandName:`pr:info`,description:`Inspect a PR by number or its GitHub-linked issue branch`,inputSchema:P({repo:AC,issueNumber:U.optional(),prNumber:U.optional(),nonClosing:j().optional()})},{name:`issue_pr_review`,commandName:`pr:review`,description:`Submit one existing exact-head independent review with the reviewer App role`,inputSchema:P({repo:AC,issueNumber:U,prNumber:U,nonClosing:j().optional(),artifact:k().min(1),identity:k().min(1).optional(),dryRun:j().optional()})},{name:`issue_pr_merge`,commandName:`pr:merge`,description:`Guarded exact-head merge with live blocker, check and review readback`,inputSchema:P({repo:AC,issueNumber:U,prNumber:U,nonClosing:j().optional(),reviewedHeadSha:k().regex(/^[a-f0-9]{40}$/u).optional(),strategy:F([`merge`,`squash`,`rebase`]).optional(),dryRun:j().optional()})},{name:`issue_finish`,commandName:`finish`,description:`Finish merged delivery, or remove a prospectively registered unchanged investigation with native acceptance`,inputSchema:PC.extend({prNumber:U.optional(),investigation:I(!0).optional(),resultPath:k().optional(),authorityCommentId:U.optional(),acceptanceCommentId:U.optional()}).superRefine((e,t)=>IC(e.investigation===!0?FC:PC,e,t))},{name:`issue_worktree_transition_inspect`,commandName:`worktree:transition:inspect`,description:`Read a legacy issue row, original evidence and exact closure gaps without changing ownership`,inputSchema:P({repo:AC,issueNumber:U,purpose:F([`active-resume`,`merged-cleanup`]),disposition:F([`retain`,`remove`]).optional(),terminalPrNumber:U.optional(),retainedHoldCommentIds:M(U).optional(),retainedAdmissionPath:k().min(1).optional(),retainedArchivePath:k().min(1).optional()})},{name:`issue_worktree_transition_apply`,commandName:`worktree:transition:apply`,description:`Apply or resume one exact independently accepted transition with immutable preservation and closure proof`,inputSchema:P({repo:AC,authority:I(`worktree:transition`),planPath:k().min(1),expectedPlanId:k().regex(/^sha256:[a-f0-9]{64}$/u),relinquishmentCommentId:U,acceptanceCommentId:U})}];function VC(e){return BC.find(t=>t.name===e)??null}function HC(e,t){let n=e[t];if(typeof n!=`number`||!Number.isSafeInteger(n)||n<=0)throw new L(`${t} must be positive.`);return n}function UC(e,t){return typeof e[t]==`string`?e[t]:void 0}function WC(e,t){let n=UC(e,t);if(!n?.trim())throw new L(`${t} is required.`);return n}function GC(e){let{issueNumber:t,request:n,requestId:r,repo:i,resumeCreated:a,branch:o,...s}=e;return{...s,issueNumber:HC({issueNumber:t},`issueNumber`)}}async function KC(e,t,n=`author`){let r=await jh(),i=e.identity??r.roles[n].identity,a=Ih({commandName:t,deliveryConfig:r,identity:i,...e.personalAuth===void 0?{}:{personalAuth:e.personalAuth}});if(a.error)throw new L(a.error);return hv({identity:i,repoRoot:e.repoRoot,role:n,...e.repo===void 0?{}:{repository:e.repo},...e.personalAuth===void 0?{}:{personalAuth:e.personalAuth},...e.signal===void 0?{}:{signal:e.signal}})}async function qC(e,t){let n=t.issueNumber===void 0?void 0:HC(t,`issueNumber`),r,i,a,o=!1,s=`branch-or-journal`,c=(o,s)=>({status:`created-not-started`,repository:e.config.repository,createdIssue:r,failure:{phase:o,message:s instanceof Error?s.message:String(s)},safeResume:{tool:`issue_start`,arguments:{...o===`tracking`?{...t,...i===void 0?{}:{body:i},resumeCreated:!0}:{},repo:e.config.repository,issueNumber:n,...(a?.branch??UC(t,`branch`))===void 0?{}:{branch:a?.branch??UC(t,`branch`)}}}});if(n===void 0){let a=UC(t,`title`)??WC(t,`request`),o={...t,title:a,body:UC(t,`body`)??UC(t,`request`)??a};o.body=vv(o);let s=B(Object.fromEntries(Object.entries({title:a,body:o.body,issueType:o.issueType,points:o.points,priority:o.priority,labels:o.labels,blockedBy:o.blockedBy,blocks:o.blocks,overrideReason:o.overrideReason,parentIssueNumber:o.parentIssueNumber,milestone:o.milestone,branch:t.branch}).filter(([,e])=>e!==void 0))),l=UC(t,`requestId`)??s,u=`<!-- ai-delivery-start: ${B({repository:e.config.repository.toLowerCase(),requestKey:l})} -->`;o.body=`${o.body}\n\n<!-- ai-delivery-start-intent: ${s} -->\n${u}`,i=o.body;let d=!1,f=[];for(let t=1;t<=20;t++){let n=(await e.clients.rest.issues.listForRepo({...e.repo,state:`all`,page:t,per_page:100})).data;if(f.push(...n.filter(e=>!(`pull_request`in e)&&e.body?.includes(u))),n.length<100){d=!0;break}}if(!d)throw new L(`Issue-start retry search exceeds the bounded readback window; select a known issue number.`);if(f.length>1)throw new L(`Conflicting issues claim the same start request.`);let p=f[0];if(p&&(p.title!==a||p.body!==o.body||p.state!==`open`))throw new L(`Prior issue-start request conflicts with the requested intent or state.`);try{p?(r={number:p.number,title:p.title,url:p.html_url},n=p.number,await kv(e,{...o,issueNumber:n})):(r=(await bv(e,o)).created,n=r.number)}catch(e){if(e instanceof yv)r=e.created,n=r.number;else if(!r)throw e;return c(`tracking`,e)}}else if(t.resumeCreated===!0){let i=(await e.clients.rest.issues.get({...e.repo,issue_number:n})).data;if(i.number!==n||`pull_request`in i)throw new L(`Known-created issue readback disagrees.`);r={number:n,title:i.title,url:i.html_url};try{await kv(e,GC(t))}catch(e){return c(`tracking`,e)}}try{let r=await Mv(e,n);if(!r.ready)throw new Y_(r.failures);return o=!0,a=await Fv(e,n,UC(t,`branch`)),s=`project-status`,await Iv(e,n),s=`journal`,await mv(e,n),{issueNumber:n,repository:e.config.repository,branch:a.branch,headSha:a.headSha,reused:a.reused}}catch(i){if(r)return c(s,i);if(!o)throw i;return{status:`start-incomplete`,issueNumber:n,repository:e.config.repository,failure:{phase:s,message:i instanceof Error?i.message:String(i)},safeResume:{tool:`issue_start`,arguments:{repo:e.config.repository,issueNumber:n,...(a?.branch??UC(t,`branch`))===void 0?{}:{branch:a?.branch??UC(t,`branch`)}}}}}}async function JC(e,t,n){let r=VC(e);if(!r)throw new L(`Unknown ai-delivery tool ${e}.`);let{repo:i,...a}=r.inputSchema.parse(t);if(e===`issue_finish`&&a.nonClosing===!0)throw new L(`Non-closing delivery cannot finish or close its retained issue.`);if(i!==void 0&&n.repo!==void 0&&i!==n.repo)throw new L(`Tool and execution repository selectors disagree.`);e===`issue_create`&&vv(a);let o=typeof i==`string`?i:n.repo,s={...n,...o===void 0?{}:{repo:o}},c=e===`runtime_stage`||e===`runtime_admit`||e.startsWith(`issue_worktree_transition_`)||e===`issue_start`&&a.investigationWorktree!==void 0||e===`issue_finish`&&a.investigation===!0,l=n.repoRoot;if(c){let t=await jh();if(l=td({repository:o??(()=>{let e=ed(l,`origin`);return`${e.owner}/${e.repo}`})(),launchDirectory:l,checkoutRoots:t.checkoutRoots}),e===`runtime_stage`||e===`runtime_admit`){let r={...a,repoRoot:l,identity:UC(a,`identity`)??n.identity??t.roles.author.identity,...n.personalAuth===void 0?{}:{personalAuth:n.personalAuth},...n.signal===void 0?{}:{signal:n.signal}};return e===`runtime_stage`?TC(r):DC(r)}}let u=e===`issue_pr_review`?UC(a,`identity`):void 0,d=await KC({...s,...u===void 0?{}:{identity:u}},r.commandName,e===`issue_pr_review`?`reviewer`:`author`);switch(c&&(d.root=l),e){case`delivery_health`:return qu(d,{...a,repo:o});case`issue_comment`:return pv(d,a);case`issue_create`:return bv(d,a);case`issue_start`:return a.investigationWorktree===void 0?qC(d,a):oC(d,{issueNumber:HC(a,`issueNumber`),investigationWorktree:WC(a,`investigationWorktree`),expectedHeadSha:WC(a,`expectedHeadSha`)});case`issue_update`:return Ov(d,a);case`issue_list`:case`issue_search`:return Tv(d,a);case`issue_info`:return Av(d,HC(a,`issueNumber`));case`issue_ready_check`:return Mv(d,HC(a,`issueNumber`));case`issue_pr_create`:return YS(d,{...a.prNumber===void 0?{}:{prNumber:HC(a,`prNumber`)},issueNumber:HC(a,`issueNumber`),...a.nonClosing===void 0?{}:{nonClosing:a.nonClosing===!0},...a.body===void 0?{}:{body:WC(a,`body`)},...a.title===void 0?{}:{title:WC(a,`title`)},...a.headBranch===void 0?{}:{headBranch:WC(a,`headBranch`)},draft:a.draft!==!1,dryRun:a.dryRun===!0});case`issue_pr_info`:return US(d,a);case`issue_pr_review`:return XS(d,{artifact:WC(a,`artifact`),issueNumber:HC(a,`issueNumber`),...a.nonClosing===void 0?{}:{nonClosing:a.nonClosing===!0},prNumber:HC(a,`prNumber`),dryRun:a.dryRun===!0});case`issue_pr_merge`:case`issue_finish`:{if(e===`issue_finish`&&a.investigation===!0)return sC(d,{issueNumber:HC(a,`issueNumber`),resultPath:WC(a,`resultPath`),...a.authorityCommentId===void 0?{}:{authorityCommentId:HC(a,`authorityCommentId`)},...a.acceptanceCommentId===void 0?{}:{acceptanceCommentId:HC(a,`acceptanceCommentId`)},dryRun:a.dryRun===!0});let t={issueNumber:HC(a,`issueNumber`),...a.nonClosing===void 0?{}:{nonClosing:a.nonClosing===!0},prNumber:HC(a,`prNumber`),...a.strategy===void 0?{}:{strategy:a.strategy},...a.reviewedHeadSha===void 0?{}:{reviewedHeadSha:WC(a,`reviewedHeadSha`)},dryRun:a.dryRun===!0};return e===`issue_finish`?$S(d,t):QS(d,t)}case`issue_worktree_transition_inspect`:return cS(d,{...a,...n.runtimeEntryPath===void 0?{}:{runtimeEntryPath:n.runtimeEntryPath}});case`issue_worktree_transition_apply`:return Zx(d,{authority:`worktree:transition`,planPath:WC(a,`planPath`),expectedPlanId:WC(a,`expectedPlanId`),relinquishmentCommentId:HC(a,`relinquishmentCommentId`),acceptanceCommentId:HC(a,`acceptanceCommentId`),...n.runtimeEntryPath===void 0?{}:{runtimeEntryPath:n.runtimeEntryPath}})}}var YC;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function n(e){throw Error()}e.assertNever=n,e.arrayToEnum=e=>{let t={};for(let n of e)t[n]=n;return t},e.getValidEnumValues=t=>{let n=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),r={};for(let e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(let n of e)if(t(n))return n},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function r(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=r,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(YC||={});var XC;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(XC||={});var W=YC.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),ZC=e=>{switch(typeof e){case`undefined`:return W.undefined;case`string`:return W.string;case`number`:return Number.isNaN(e)?W.nan:W.number;case`boolean`:return W.boolean;case`function`:return W.function;case`bigint`:return W.bigint;case`symbol`:return W.symbol;case`object`:return Array.isArray(e)?W.array:e===null?W.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?W.promise:typeof Map<`u`&&e instanceof Map?W.map:typeof Set<`u`&&e instanceof Set?W.set:typeof Date<`u`&&e instanceof Date?W.date:W.object;default:return W.unknown}},G=YC.arrayToEnum([`invalid_type`,`invalid_literal`,`custom`,`invalid_union`,`invalid_union_discriminator`,`invalid_enum_value`,`unrecognized_keys`,`invalid_arguments`,`invalid_return_type`,`invalid_date`,`invalid_string`,`too_small`,`too_big`,`invalid_intersection_types`,`not_multiple_of`,`not_finite`]),QC=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`)i.unionErrors.map(r);else if(i.code===`invalid_return_type`)r(i.returnTypeError);else if(i.code===`invalid_arguments`)r(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r],a=r===i.path.length-1;if(n===`_errors`){a&&e._errors.push(t(i)),r++;continue}Object.prototype.hasOwnProperty.call(e,n)||(n===`__proto__`?Object.defineProperty(e,n,{value:{_errors:[]},writable:!0,enumerable:!0,configurable:!0}):e[n]={_errors:[]}),e=e[n],a&&e._errors.push(t(i)),r++}}};return r(this),n}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,YC.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t=Object.create(null),n=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};QC.create=e=>new QC(e);var $C=(e,t)=>{let n;switch(e.code){case G.invalid_type:n=e.received===W.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case G.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,YC.jsonStringifyReplacer)}`;break;case G.unrecognized_keys:n=`Unrecognized key(s) in object: ${YC.joinValues(e.keys,`, `)}`;break;case G.invalid_union:n=`Invalid input`;break;case G.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${YC.joinValues(e.options)}`;break;case G.invalid_enum_value:n=`Invalid enum value. Expected ${YC.joinValues(e.options)}, received '${e.received}'`;break;case G.invalid_arguments:n=`Invalid function arguments`;break;case G.invalid_return_type:n=`Invalid function return type`;break;case G.invalid_date:n=`Invalid date`;break;case G.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:YC.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case G.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case G.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case G.custom:n=`Invalid input`;break;case G.invalid_intersection_types:n=`Intersection results could not be merged`;break;case G.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case G.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,YC.assertNever(e)}return{message:n}},ew=$C;function tw(){return ew}var nw=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s=``,c=r.filter(e=>!!e).slice().reverse();for(let e of c)s=e(o,{data:t,defaultError:s}).message;return{...i,path:a,message:s}};function K(e,t){let n=tw(),r=nw({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===$C?void 0:$C].filter(e=>!!e)});e.common.issues.push(r)}var rw=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return q;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(t,n){let r=[];for(let e of n){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return e.mergeObjectSync(t,r)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return q;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}},q=Object.freeze({status:`aborted`}),iw=e=>({status:`dirty`,value:e}),aw=e=>({status:`valid`,value:e}),ow=e=>e.status===`aborted`,sw=e=>e.status===`dirty`,cw=e=>e.status===`valid`,lw=e=>typeof Promise<`u`&&e instanceof Promise,J;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(J||={});var uw=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},dw=(e,t)=>{if(cw(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){if(this._error)return this._error;let t=new QC(e.common.issues);return this._error=t,this._error}}};function Y(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}var fw=class{get description(){return this._def.description}_getType(e){return ZC(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:ZC(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new rw,ctx:{common:e.parent.common,data:e.data,parsedType:ZC(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(lw(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ZC(e)};return dw(n,this._parseSync({data:e,path:n.path,parent:n}))}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ZC(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return cw(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>cw(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ZC(e)},r=this._parse({data:e,path:n.path,parent:n});return dw(n,await(lw(r)?r:Promise.resolve(r)))}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:G.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new hT({schema:this,typeName:X.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return gT.create(this,this._def)}nullable(){return _T.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Xw.create(this)}promise(){return mT.create(this,this._def)}or(e){return $w.create([this,e],this._def)}and(e){return rT.create(this,e,this._def)}transform(e){return new hT({...Y(this._def),schema:this,typeName:X.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new vT({...Y(this._def),innerType:this,defaultValue:t,typeName:X.ZodDefault})}brand(){return new xT({typeName:X.ZodBranded,type:this,...Y(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new yT({...Y(this._def),innerType:this,catchValue:t,typeName:X.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return ST.create(this,e)}readonly(){return CT.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},pw=/^c[^\s-]{8,}$/i,mw=/^[0-9a-z]+$/,hw=/^[0-9A-HJKMNP-TV-Z]{26}$/i,gw=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,_w=/^[a-z0-9_-]{21}$/i,vw=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,yw=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,bw=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,xw=`^[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`,Sw,Cw=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ww=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Tw=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Ew=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Dw=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ow=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,kw=`((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`,Aw=RegExp(`^${kw}$`);function jw(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let n=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function Mw(e){return RegExp(`^${jw(e)}$`)}function Nw(e){let t=`${kw}T${jw(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function Pw(e,t){return!((t!==`v4`&&t||!Cw.test(e))&&(t!==`v6`&&t||!Tw.test(e)))}function Fw(e,t){if(!vw.test(e))return!1;try{let[n]=e.split(`.`);if(!n)return!1;let r=n.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(n.length+(4-n.length%4)%4,`=`),i=JSON.parse(atob(r));return!(typeof i!=`object`||!i||`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&i.alg!==t)}catch{return!1}}function Iw(e,t){return!((t!==`v4`&&t||!ww.test(e))&&(t!==`v6`&&t||!Ew.test(e)))}var Lw=class e extends fw{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==W.string){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.string,received:t.parsedType}),q}let t=new rw,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),K(n,{code:G.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),K(n,{code:G.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?K(n,{code:G.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&K(n,{code:G.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)bw.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`email`,code:G.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)Sw||=new RegExp(xw,`u`),Sw.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`emoji`,code:G.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)gw.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`uuid`,code:G.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)_w.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`nanoid`,code:G.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)pw.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`cuid`,code:G.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)mw.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`cuid2`,code:G.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)hw.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`ulid`,code:G.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),K(n,{validation:`url`,code:G.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`regex`,code:G.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),K(n,{code:G.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),K(n,{code:G.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),K(n,{code:G.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?Nw(r).test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{code:G.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?Aw.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{code:G.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?Mw(r).test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{code:G.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?yw.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`duration`,code:G.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?Pw(e.data,r.version)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`ip`,code:G.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?Fw(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`jwt`,code:G.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?Iw(e.data,r.version)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`cidr`,code:G.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?Dw.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`base64`,code:G.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?Ow.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`base64url`,code:G.invalid_string,message:r.message}),t.dirty()):YC.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:G.invalid_string,...J.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...J.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...J.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...J.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...J.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...J.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...J.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...J.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...J.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...J.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...J.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...J.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...J.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...J.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...J.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...J.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...J.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...J.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...J.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...J.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...J.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...J.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...J.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...J.errToObj(t)})}nonempty(e){return this.min(1,J.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};Lw.create=e=>new Lw({checks:[],typeName:X.ZodString,coerce:e?.coerce??!1,...Y(e)});function Rw(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}var zw=class e extends fw{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==W.number){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.number,received:t.parsedType}),q}let t,n=new rw;for(let r of this._def.checks)r.kind===`int`?YC.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),K(t,{code:G.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),K(t,{code:G.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),K(t,{code:G.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?Rw(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),K(t,{code:G.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),K(t,{code:G.not_finite,message:r.message}),n.dirty()):YC.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,J.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,J.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,J.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,J.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:J.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:J.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:J.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:J.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:J.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:J.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:J.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:J.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:J.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:J.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&YC.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;else n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value);return Number.isFinite(t)&&Number.isFinite(e)}};zw.create=e=>new zw({checks:[],typeName:X.ZodNumber,coerce:e?.coerce||!1,...Y(e)});var Bw=class e extends fw{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==W.bigint)return this._getInvalidInput(e);let t,n=new rw;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),K(t,{code:G.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),K(t,{code:G.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),K(t,{code:G.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):YC.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.bigint,received:t.parsedType}),q}gte(e,t){return this.setLimit(`min`,e,!0,J.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,J.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,J.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,J.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:J.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:J.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:J.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:J.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:J.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:J.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};Bw.create=e=>new Bw({checks:[],typeName:X.ZodBigInt,coerce:e?.coerce??!1,...Y(e)});var Vw=class extends fw{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==W.boolean){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.boolean,received:t.parsedType}),q}return aw(e.data)}};Vw.create=e=>new Vw({typeName:X.ZodBoolean,coerce:e?.coerce||!1,...Y(e)});var Hw=class e extends fw{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==W.date){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.date,received:t.parsedType}),q}if(Number.isNaN(e.data.getTime()))return K(this._getOrReturnCtx(e),{code:G.invalid_date}),q;let t=new rw,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),K(n,{code:G.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),K(n,{code:G.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):YC.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:J.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:J.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};Hw.create=e=>new Hw({checks:[],coerce:e?.coerce||!1,typeName:X.ZodDate,...Y(e)});var Uw=class extends fw{_parse(e){if(this._getType(e)!==W.symbol){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.symbol,received:t.parsedType}),q}return aw(e.data)}};Uw.create=e=>new Uw({typeName:X.ZodSymbol,...Y(e)});var Ww=class extends fw{_parse(e){if(this._getType(e)!==W.undefined){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.undefined,received:t.parsedType}),q}return aw(e.data)}};Ww.create=e=>new Ww({typeName:X.ZodUndefined,...Y(e)});var Gw=class extends fw{_parse(e){if(this._getType(e)!==W.null){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.null,received:t.parsedType}),q}return aw(e.data)}};Gw.create=e=>new Gw({typeName:X.ZodNull,...Y(e)});var Kw=class extends fw{constructor(){super(...arguments),this._any=!0}_parse(e){return aw(e.data)}};Kw.create=e=>new Kw({typeName:X.ZodAny,...Y(e)});var qw=class extends fw{constructor(){super(...arguments),this._unknown=!0}_parse(e){return aw(e.data)}};qw.create=e=>new qw({typeName:X.ZodUnknown,...Y(e)});var Jw=class extends fw{_parse(e){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.never,received:t.parsedType}),q}};Jw.create=e=>new Jw({typeName:X.ZodNever,...Y(e)});var Yw=class extends fw{_parse(e){if(this._getType(e)!==W.undefined){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.void,received:t.parsedType}),q}return aw(e.data)}};Yw.create=e=>new Yw({typeName:X.ZodVoid,...Y(e)});var Xw=class e extends fw{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==W.array)return K(t,{code:G.invalid_type,expected:W.array,received:t.parsedType}),q;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(K(t,{code:e?G.too_big:G.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(K(t,{code:G.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(K(t,{code:G.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new uw(t,e,t.path,n)))).then(e=>rw.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new uw(t,e,t.path,n)));return rw.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:J.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:J.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:J.toString(n)}})}nonempty(e){return this.min(1,e)}};Xw.create=(e,t)=>new Xw({type:e,minLength:null,maxLength:null,exactLength:null,typeName:X.ZodArray,...Y(t)});function Zw(e){if(e instanceof Qw){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=gT.create(Zw(r))}return new Qw({...e._def,shape:()=>t})}return e instanceof Xw?new Xw({...e._def,type:Zw(e.element)}):e instanceof gT?gT.create(Zw(e.unwrap())):e instanceof _T?_T.create(Zw(e.unwrap())):e instanceof iT?iT.create(e.items.map(e=>Zw(e))):e}var Qw=class e extends fw{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=YC.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==W.object){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.object,received:t.parsedType}),q}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Jw&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let o=[];for(let e of i){let t=r[e],i=n.data[e];o.push({key:{status:`valid`,value:e},value:t._parse(new uw(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof Jw){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)o.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(K(n,{code:G.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new uw(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>rw.mergeObjectSync(t,e)):rw.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return J.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,n)=>{let r=this._def.errorMap?.(e,n).message??n.defaultError;return e.code===`unrecognized_keys`?{message:J.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:X.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of YC.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let e of YC.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return Zw(this)}partial(t){let n={};for(let e of YC.objectKeys(this.shape)){let r=this.shape[e];n[e]=t&&!t[e]?r:r.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let e of YC.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof gT;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return dT(YC.objectKeys(this.shape))}};Qw.create=(e,t)=>new Qw({shape:()=>e,unknownKeys:`strip`,catchall:Jw.create(),typeName:X.ZodObject,...Y(t)}),Qw.strictCreate=(e,t)=>new Qw({shape:()=>e,unknownKeys:`strict`,catchall:Jw.create(),typeName:X.ZodObject,...Y(t)}),Qw.lazycreate=(e,t)=>new Qw({shape:e,unknownKeys:`strip`,catchall:Jw.create(),typeName:X.ZodObject,...Y(t)});var $w=class extends fw{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new QC(e.ctx.common.issues));return K(t,{code:G.invalid_union,unionErrors:n}),q}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(r);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new QC(e));return K(t,{code:G.invalid_union,unionErrors:i}),q}}get options(){return this._def.options}};$w.create=(e,t)=>new $w({options:e,typeName:X.ZodUnion,...Y(t)});var eT=e=>e instanceof lT?eT(e.schema):e instanceof hT?eT(e.innerType()):e instanceof uT?[e.value]:e instanceof fT?e.options:e instanceof pT?YC.objectValues(e.enum):e instanceof vT?eT(e._def.innerType):e instanceof Ww?[void 0]:e instanceof Gw?[null]:e instanceof gT?[void 0,...eT(e.unwrap())]:e instanceof _T?[null,...eT(e.unwrap())]:e instanceof xT||e instanceof CT?eT(e.unwrap()):e instanceof yT?eT(e._def.innerType):[],tT=class e extends fw{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==W.object)return K(t,{code:G.invalid_type,expected:W.object,received:t.parsedType}),q;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(K(t,{code:G.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),q)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let e of n){let n=eT(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:X.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...Y(r)})}};function nT(e,t){let n=ZC(e),r=ZC(t);if(e===t)return{valid:!0,data:e};if(n===W.object&&r===W.object){let n=YC.objectKeys(t),r=YC.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};Object.prototype.hasOwnProperty.call(i,`__proto__`)&&delete i.__proto__;for(let n of r){if(n===`__proto__`)continue;let r=nT(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}if(n===W.array&&r===W.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=nT(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}return n===W.date&&r===W.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var rT=class extends fw{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(ow(e)||ow(r))return q;let i=nT(e.value,r.value);return i.valid?((sw(e)||sw(r))&&t.dirty(),{status:t.value,value:i.data}):(K(n,{code:G.invalid_intersection_types}),q)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};rT.create=(e,t,n)=>new rT({left:e,right:t,typeName:X.ZodIntersection,...Y(n)});var iT=class e extends fw{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==W.array)return K(n,{code:G.invalid_type,expected:W.array,received:n.parsedType}),q;if(n.data.length<this._def.items.length)return K(n,{code:G.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),q;!this._def.rest&&n.data.length>this._def.items.length&&(K(n,{code:G.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new uw(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>rw.mergeArray(t,e)):rw.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};iT.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new iT({items:e,typeName:X.ZodTuple,rest:null,...Y(t)})};var aT=class e extends fw{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==W.object)return K(n,{code:G.invalid_type,expected:W.object,received:n.parsedType}),q;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new uw(n,e,n.path,e)),value:a._parse(new uw(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?rw.mergeObjectAsync(t,r):rw.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof fw?new e({keyType:t,valueType:n,typeName:X.ZodRecord,...Y(r)}):new e({keyType:Lw.create(),valueType:t,typeName:X.ZodRecord,...Y(n)})}},oT=class extends fw{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==W.map)return K(n,{code:G.invalid_type,expected:W.map,received:n.parsedType}),q;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new uw(n,e,n.path,[a,`key`])),value:i._parse(new uw(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return q;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return q;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};oT.create=(e,t,n)=>new oT({valueType:t,keyType:e,typeName:X.ZodMap,...Y(n)});var sT=class e extends fw{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==W.set)return K(n,{code:G.invalid_type,expected:W.set,received:n.parsedType}),q;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(K(n,{code:G.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(K(n,{code:G.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return q;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new uw(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:J.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:J.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};sT.create=(e,t)=>new sT({valueType:e,minSize:null,maxSize:null,typeName:X.ZodSet,...Y(t)});var cT=class e extends fw{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==W.function)return K(t,{code:G.invalid_type,expected:W.function,received:t.parsedType}),q;function n(e,n){return nw({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,tw(),$C].filter(e=>!!e),issueData:{code:G.invalid_arguments,argumentsError:n}})}function r(e,n){return nw({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,tw(),$C].filter(e=>!!e),issueData:{code:G.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof mT){let e=this;return aw(async function(...t){let o=new QC([]),s=await e._def.args.parseAsync(t,i).catch(e=>{throw o.addIssue(n(t,e)),o}),c=await Reflect.apply(a,this,s);return await e._def.returns._def.type.parseAsync(c,i).catch(e=>{throw o.addIssue(r(c,e)),o})})}{let e=this;return aw(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new QC([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new QC([r(s,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:iT.create(t).rest(qw.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,n,r){return new e({args:t||iT.create([]).rest(qw.create()),returns:n||qw.create(),typeName:X.ZodFunction,...Y(r)})}},lT=class extends fw{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};lT.create=(e,t)=>new lT({getter:e,typeName:X.ZodLazy,...Y(t)});var uT=class extends fw{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return K(t,{received:t.data,code:G.invalid_literal,expected:this._def.value}),q}return{status:`valid`,value:e.data}}get value(){return this._def.value}};uT.create=(e,t)=>new uT({value:e,typeName:X.ZodLiteral,...Y(t)});function dT(e,t){return new fT({values:e,typeName:X.ZodEnum,...Y(t)})}var fT=class e extends fw{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return K(t,{expected:YC.joinValues(n),received:t.parsedType,code:G.invalid_type}),q}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return K(t,{received:t.data,code:G.invalid_enum_value,options:n}),q}return aw(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}};fT.create=dT;var pT=class extends fw{_parse(e){let t=YC.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==W.string&&n.parsedType!==W.number){let e=YC.objectValues(t);return K(n,{expected:YC.joinValues(e),received:n.parsedType,code:G.invalid_type}),q}if(this._cache||=new Set(YC.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=YC.objectValues(t);return K(n,{received:n.data,code:G.invalid_enum_value,options:e}),q}return aw(e.data)}get enum(){return this._def.values}};pT.create=(e,t)=>new pT({values:e,typeName:X.ZodNativeEnum,...Y(t)});var mT=class extends fw{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==W.promise&&t.common.async===!1?(K(t,{code:G.invalid_type,expected:W.promise,received:t.parsedType}),q):aw((t.parsedType===W.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};mT.create=(e,t)=>new mT({type:e,typeName:X.ZodPromise,...Y(t)});var hT=class extends fw{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===X.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{K(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return q;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?q:r.status===`dirty`||t.value===`dirty`?iw(r.value):r});{if(t.value===`aborted`)return q;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?q:r.status===`dirty`||t.value===`dirty`?iw(r.value):r}}if(r.type===`refinement`){let e=e=>{let t=r.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(n.common.async===!1){let r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return r.status===`aborted`?q:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?q:(n.status===`dirty`&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if(r.type===`transform`){if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!cw(e))return q;let a=r.transform(e.value,i);if(a instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:a}}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>cw(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):q)}YC.assertNever(r)}};hT.create=(e,t,n)=>new hT({schema:e,typeName:X.ZodEffects,effect:t,...Y(n)}),hT.createWithPreprocess=(e,t,n)=>new hT({schema:t,effect:{type:`preprocess`,transform:e},typeName:X.ZodEffects,...Y(n)});var gT=class extends fw{_parse(e){return this._getType(e)===W.undefined?aw(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};gT.create=(e,t)=>new gT({innerType:e,typeName:X.ZodOptional,...Y(t)});var _T=class extends fw{_parse(e){return this._getType(e)===W.null?aw(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};_T.create=(e,t)=>new _T({innerType:e,typeName:X.ZodNullable,...Y(t)});var vT=class extends fw{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===W.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};vT.create=(e,t)=>new vT({innerType:e,typeName:X.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...Y(t)});var yT=class extends fw{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return lw(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new QC(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new QC(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};yT.create=(e,t)=>new yT({innerType:e,typeName:X.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...Y(t)});var bT=class extends fw{_parse(e){if(this._getType(e)!==W.nan){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.nan,received:t.parsedType}),q}return{status:`valid`,value:e.data}}};bT.create=e=>new bT({typeName:X.ZodNaN,...Y(e)});var xT=class extends fw{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},ST=class e extends fw{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?q:e.status===`dirty`?(t.dirty(),iw(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?q:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:X.ZodPipeline})}},CT=class extends fw{_parse(e){let t=this._def.innerType._parse(e),n=e=>(cw(e)&&(e.value=Object.freeze(e.value)),e);return lw(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};CT.create=(e,t)=>new CT({innerType:e,typeName:X.ZodReadonly,...Y(t)}),Qw.lazycreate;var X;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(X||={}),Lw.create,zw.create,bT.create,Bw.create,Vw.create,Hw.create,Uw.create,Ww.create,Gw.create,Kw.create,qw.create,Jw.create,Yw.create,Xw.create;var wT=Qw.create;Qw.strictCreate,$w.create,tT.create,rT.create,iT.create,aT.create,oT.create,sT.create,cT.create,lT.create,uT.create,fT.create,pT.create,mT.create,hT.create,gT.create,_T.create,hT.createWithPreprocess,ST.create;var TT=O(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);Yr.init(e,t),e.def=t,e.type=t.type},{get with(){return this.check},set with(e){Jt(this,`with`,e)},parse(e,t){return On(this,e,t,{callee:this.parse})},parseAsync(e,t){return An(this,e,t,{callee:this.parseAsync})},safeParse(e,t){return Mn(this,e,t)},safeParseAsync(e,t){return Fn(this,e,t)},check(...e){let t=this.def;return this.clone({...t,checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]},{parent:!0})},clone(e,t){return St(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},apply(e,...t){return t.length===0?e(this):e(this,...t)}}),ET=O(`ZodMiniObject`,(e,t)=>{Zi.init(e,t),TT.init(e,t),rn(e,`shape`,e=>e._zod.def.shape,!1)});function DT(e,t){return new ET({type:`object`,shape:e??{},...D(t)})}function OT(e){return!!e._zod}function kT(e){let t=Object.values(e);if(t.length===0)return DT({});let n=t.every(OT),r=t.every(e=>!OT(e));if(n)return DT(e);if(r)return wT(e);throw Error(`Mixed Zod versions detected in object shape.`)}function AT(e,t){return OT(e)?Mn(e,t):e.safeParse(t)}async function jT(e,t){return OT(e)?await Fn(e,t):await e.safeParseAsync(t)}function MT(e){if(!e)return;let t;if(t=OT(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function NT(e){if(e){if(typeof e==`object`){let t=e,n=e;if(!t._def&&!n._zod){let t=Object.values(e);if(t.length>0&&t.every(e=>typeof e==`object`&&!!e&&(e._def!==void 0||e._zod!==void 0||typeof e.parse==`function`)))return kT(e)}}if(OT(e)){let t=e._zod?.def;if(t&&(t.type===`object`||t.shape!==void 0))return e}else if(e.shape!==void 0)return e}}function PT(e){return e.length===0?`object root`:e.reduce((e,t,n)=>n===0?String(t):typeof t==`number`?`${e}[${t}]`:`${e}.${t}`,``)}function FT(e){if(e&&typeof e==`object`){if(`issues`in e&&Array.isArray(e.issues)&&e.issues.length>0)return e.issues.map(e=>e.path?.length?`${e.message} at ${PT(e.path)}`:e.message).join(`
|
|
296
|
+
`);if(`message`in e&&typeof e.message==`string`)return e.message;try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function IT(e){return e.description}function LT(e){if(OT(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function RT(e){if(OT(e)){let t=e._zod?.def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}}let t=e._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let n=e.value;if(n!==void 0)return n}var zT=`2025-11-25`,BT=[zT,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],VT=`io.modelcontextprotocol/related-task`,HT=hu(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),UT=Il([k(),A().int()]),WT=k();Pl({ttl:A().optional(),pollInterval:A().optional()});var GT=N({ttl:A().optional()}),KT=N({taskId:k()}),qT=Pl({progressToken:UT.optional(),[VT]:KT.optional()}),JT=N({_meta:qT.optional()}),YT=JT.extend({task:GT.optional()}),XT=e=>YT.safeParse(e).success,ZT=N({method:k(),params:JT.loose().optional()}),QT=N({_meta:qT.optional()}),$T=N({method:k(),params:QT.loose().optional()}),eE=Pl({_meta:qT.optional()}),tE=Il([k(),A().int()]),nE=N({jsonrpc:I(`2.0`),id:tE,...ZT.shape}).strict(),rE=e=>nE.safeParse(e).success,iE=N({jsonrpc:I(`2.0`),...$T.shape}).strict(),aE=e=>iE.safeParse(e).success,oE=N({jsonrpc:I(`2.0`),id:tE,result:eE}).strict(),sE=e=>oE.safeParse(e).success,Z;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`})(Z||={});var cE=N({jsonrpc:I(`2.0`),id:tE.optional(),error:N({code:A().int(),message:k(),data:kl().optional()})}).strict(),lE=e=>cE.safeParse(e).success,uE=Il([nE,iE,oE,cE]);Il([oE,cE]);var dE=eE.strict(),fE=QT.extend({requestId:tE.optional(),reason:k().optional()}),pE=$T.extend({method:I(`notifications/cancelled`),params:fE}),mE=N({icons:M(N({src:k(),mimeType:k().optional(),sizes:M(k()).optional(),theme:F([`light`,`dark`]).optional()})).optional()}),hE=N({name:k(),title:k().optional()}),gE=hE.extend({...hE.shape,...mE.shape,version:k(),websiteUrl:k().optional(),description:k().optional()}),_E=vu(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Bl(N({form:Bl(N({applyDefaults:j().optional()}),Wl(k(),kl())).optional(),url:HT.optional()}),Wl(k(),kl()).optional())),vE=Pl({list:HT.optional(),cancel:HT.optional(),requests:Pl({sampling:Pl({createMessage:HT.optional()}).optional(),elicitation:Pl({create:HT.optional()}).optional()}).optional()}),yE=Pl({list:HT.optional(),cancel:HT.optional(),requests:Pl({tools:Pl({call:HT.optional()}).optional()}).optional()}),bE=N({experimental:Wl(k(),HT).optional(),sampling:N({context:HT.optional(),tools:HT.optional()}).optional(),elicitation:_E.optional(),roots:N({listChanged:j().optional()}).optional(),tasks:vE.optional(),extensions:Wl(k(),HT).optional()}),xE=JT.extend({protocolVersion:k(),capabilities:bE,clientInfo:gE}),SE=ZT.extend({method:I(`initialize`),params:xE}),CE=N({experimental:Wl(k(),HT).optional(),logging:HT.optional(),completions:HT.optional(),prompts:N({listChanged:j().optional()}).optional(),resources:N({subscribe:j().optional(),listChanged:j().optional()}).optional(),tools:N({listChanged:j().optional()}).optional(),tasks:yE.optional(),extensions:Wl(k(),HT).optional()}),wE=eE.extend({protocolVersion:k(),capabilities:CE,serverInfo:gE,instructions:k().optional()}),TE=$T.extend({method:I(`notifications/initialized`),params:QT.optional()}),EE=ZT.extend({method:I(`ping`),params:JT.optional()}),DE=N({progress:A(),total:Xl(A()),message:Xl(k())}),OE=N({...QT.shape,...DE.shape,progressToken:UT}),kE=$T.extend({method:I(`notifications/progress`),params:OE}),AE=JT.extend({cursor:WT.optional()}),jE=ZT.extend({params:AE.optional()}),ME=eE.extend({nextCursor:WT.optional()}),NE=F([`working`,`input_required`,`completed`,`failed`,`cancelled`]),PE=N({taskId:k(),status:NE,ttl:Il([A(),Dl()]),createdAt:k(),lastUpdatedAt:k(),pollInterval:Xl(A()),statusMessage:Xl(k())}),FE=eE.extend({task:PE}),IE=QT.merge(PE),LE=$T.extend({method:I(`notifications/tasks/status`),params:IE}),RE=ZT.extend({method:I(`tasks/get`),params:JT.extend({taskId:k()})}),zE=eE.merge(PE),BE=ZT.extend({method:I(`tasks/result`),params:JT.extend({taskId:k()})});eE.loose();var VE=jE.extend({method:I(`tasks/list`)}),HE=ME.extend({tasks:M(PE)}),UE=ZT.extend({method:I(`tasks/cancel`),params:JT.extend({taskId:k()})}),WE=eE.merge(PE),GE=N({uri:k(),mimeType:Xl(k()),_meta:Wl(k(),kl()).optional()}),KE=GE.extend({text:k()}),qE=k().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),JE=GE.extend({blob:qE}),YE=F([`user`,`assistant`]),XE=N({audience:M(YE).optional(),priority:A().min(0).max(1).optional(),lastModified:yu({offset:!0}).optional()}),ZE=N({...hE.shape,...mE.shape,uri:k(),description:Xl(k()),mimeType:Xl(k()),size:Xl(A()),annotations:XE.optional(),_meta:Xl(Pl({}))}),QE=N({...hE.shape,...mE.shape,uriTemplate:k(),description:Xl(k()),mimeType:Xl(k()),annotations:XE.optional(),_meta:Xl(Pl({}))}),$E=jE.extend({method:I(`resources/list`)}),eD=ME.extend({resources:M(ZE)}),tD=jE.extend({method:I(`resources/templates/list`)}),nD=ME.extend({resourceTemplates:M(QE)}),rD=JT.extend({uri:k()}),iD=rD,aD=ZT.extend({method:I(`resources/read`),params:iD}),oD=eE.extend({contents:M(Il([KE,JE]))}),sD=$T.extend({method:I(`notifications/resources/list_changed`),params:QT.optional()}),cD=rD,lD=ZT.extend({method:I(`resources/subscribe`),params:cD}),uD=rD,dD=ZT.extend({method:I(`resources/unsubscribe`),params:uD}),fD=QT.extend({uri:k()}),pD=$T.extend({method:I(`notifications/resources/updated`),params:fD}),mD=N({name:k(),description:Xl(k()),required:Xl(j())}),hD=N({...hE.shape,...mE.shape,description:Xl(k()),arguments:Xl(M(mD)),_meta:Xl(Pl({}))}),gD=jE.extend({method:I(`prompts/list`)}),_D=ME.extend({prompts:M(hD)}),vD=JT.extend({name:k(),arguments:Wl(k(),k()).optional()}),yD=ZT.extend({method:I(`prompts/get`),params:vD}),bD=N({type:I(`text`),text:k(),annotations:XE.optional(),_meta:Wl(k(),kl()).optional()}),xD=N({type:I(`image`),data:qE,mimeType:k(),annotations:XE.optional(),_meta:Wl(k(),kl()).optional()}),SD=N({type:I(`audio`),data:qE,mimeType:k(),annotations:XE.optional(),_meta:Wl(k(),kl()).optional()}),CD=N({type:I(`tool_use`),name:k(),id:k(),input:Wl(k(),kl()),_meta:Wl(k(),kl()).optional()}),wD=N({type:I(`resource`),resource:Il([KE,JE]),annotations:XE.optional(),_meta:Wl(k(),kl()).optional()}),TD=Il([bD,xD,SD,ZE.extend({type:I(`resource_link`)}),wD]),ED=N({role:YE,content:TD}),DD=eE.extend({description:k().optional(),messages:M(ED)}),OD=$T.extend({method:I(`notifications/prompts/list_changed`),params:QT.optional()}),kD=N({title:k().optional(),readOnlyHint:j().optional(),destructiveHint:j().optional(),idempotentHint:j().optional(),openWorldHint:j().optional()}),AD=N({taskSupport:F([`required`,`optional`,`forbidden`]).optional()}),jD=N({...hE.shape,...mE.shape,description:k().optional(),inputSchema:N({type:I(`object`),properties:Wl(k(),HT).optional(),required:M(k()).optional()}).catchall(kl()),outputSchema:N({type:I(`object`),properties:Wl(k(),HT).optional(),required:M(k()).optional()}).catchall(kl()).optional(),annotations:kD.optional(),execution:AD.optional(),_meta:Wl(k(),kl()).optional()}),MD=jE.extend({method:I(`tools/list`)}),ND=ME.extend({tools:M(jD)}),PD=eE.extend({content:M(TD).default([]),structuredContent:Wl(k(),kl()).optional(),isError:j().optional()});PD.or(eE.extend({toolResult:kl()}));var FD=YT.extend({name:k(),arguments:Wl(k(),kl()).optional()}),ID=ZT.extend({method:I(`tools/call`),params:FD}),LD=$T.extend({method:I(`notifications/tools/list_changed`),params:QT.optional()}),RD=N({autoRefresh:j().default(!0),debounceMs:A().int().nonnegative().default(300)}),zD=F([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),BD=JT.extend({level:zD}),VD=ZT.extend({method:I(`logging/setLevel`),params:BD}),HD=QT.extend({level:zD,logger:k().optional(),data:kl()}),UD=$T.extend({method:I(`notifications/message`),params:HD}),WD=N({hints:M(N({name:k().optional()})).optional(),costPriority:A().min(0).max(1).optional(),speedPriority:A().min(0).max(1).optional(),intelligencePriority:A().min(0).max(1).optional()}),GD=N({mode:F([`auto`,`required`,`none`]).optional()}),KD=N({type:I(`tool_result`),toolUseId:k().describe(`The unique identifier for the corresponding tool call.`),content:M(TD).default([]),structuredContent:N({}).loose().optional(),isError:j().optional(),_meta:Wl(k(),kl()).optional()}),qD=Rl(`type`,[bD,xD,SD]),JD=Rl(`type`,[bD,xD,SD,CD,KD]),YD=N({role:YE,content:Il([JD,M(JD)]),_meta:Wl(k(),kl()).optional()}),XD=YT.extend({messages:M(YD),modelPreferences:WD.optional(),systemPrompt:k().optional(),includeContext:F([`none`,`thisServer`,`allServers`]).optional(),temperature:A().optional(),maxTokens:A().int(),stopSequences:M(k()).optional(),metadata:HT.optional(),tools:M(jD).optional(),toolChoice:GD.optional()}),ZD=ZT.extend({method:I(`sampling/createMessage`),params:XD}),QD=eE.extend({model:k(),stopReason:Xl(F([`endTurn`,`stopSequence`,`maxTokens`]).or(k())),role:YE,content:qD}),$D=eE.extend({model:k(),stopReason:Xl(F([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(k())),role:YE,content:Il([JD,M(JD)])}),eO=N({type:I(`boolean`),title:k().optional(),description:k().optional(),default:j().optional()}),tO=N({type:I(`string`),title:k().optional(),description:k().optional(),minLength:A().optional(),maxLength:A().optional(),format:F([`email`,`uri`,`date`,`date-time`]).optional(),default:k().optional()}),nO=N({type:F([`number`,`integer`]),title:k().optional(),description:k().optional(),minimum:A().optional(),maximum:A().optional(),default:A().optional()}),rO=N({type:I(`string`),title:k().optional(),description:k().optional(),enum:M(k()),default:k().optional()}),iO=N({type:I(`string`),title:k().optional(),description:k().optional(),oneOf:M(N({const:k(),title:k()})),default:k().optional()}),aO=Il([Il([N({type:I(`string`),title:k().optional(),description:k().optional(),enum:M(k()),enumNames:M(k()).optional(),default:k().optional()}),Il([rO,iO]),Il([N({type:I(`array`),title:k().optional(),description:k().optional(),minItems:A().optional(),maxItems:A().optional(),items:N({type:I(`string`),enum:M(k())}),default:M(k()).optional()}),N({type:I(`array`),title:k().optional(),description:k().optional(),minItems:A().optional(),maxItems:A().optional(),items:N({anyOf:M(N({const:k(),title:k()}))}),default:M(k()).optional()})])]),eO,tO,nO]),oO=Il([YT.extend({mode:I(`form`).optional(),message:k(),requestedSchema:N({type:I(`object`),properties:Wl(k(),aO),required:M(k()).optional()})}),YT.extend({mode:I(`url`),message:k(),elicitationId:k(),url:k().url()})]),sO=ZT.extend({method:I(`elicitation/create`),params:oO}),cO=QT.extend({elicitationId:k()}),lO=$T.extend({method:I(`notifications/elicitation/complete`),params:cO}),uO=eE.extend({action:F([`accept`,`decline`,`cancel`]),content:vu(e=>e===null?void 0:e,Wl(k(),Il([k(),A(),j(),M(k())])).optional())}),dO=N({type:I(`ref/resource`),uri:k()}),fO=N({type:I(`ref/prompt`),name:k()}),pO=JT.extend({ref:Il([fO,dO]),argument:N({name:k(),value:k()}),context:N({arguments:Wl(k(),k()).optional()}).optional()}),mO=ZT.extend({method:I(`completion/complete`),params:pO});function hO(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function gO(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}var _O=eE.extend({completion:Pl({values:M(k()).max(100),total:Xl(A().int()),hasMore:Xl(j())})}),vO=N({uri:k().startsWith(`file://`),name:k().optional(),_meta:Wl(k(),kl()).optional()}),yO=ZT.extend({method:I(`roots/list`),params:JT.optional()}),bO=eE.extend({roots:M(vO)}),xO=$T.extend({method:I(`notifications/roots/list_changed`),params:QT.optional()});Il([EE,SE,mO,VD,yD,gD,$E,tD,aD,lD,dD,ID,MD,RE,BE,VE,UE]),Il([pE,kE,TE,xO,LE]),Il([dE,QD,$D,uO,bO,zE,HE,FE]),Il([EE,ZD,sO,yO,RE,BE,VE,UE]),Il([pE,kE,UD,pD,sD,LD,OD,LE,lO]),Il([dE,wE,_O,DD,_D,eD,nD,oD,PD,ND,zE,HE,FE]);var Q=class e extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}static fromError(t,n,r){if(t===Z.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new SO(e.elicitations,n)}return new e(t,n,r)}},SO=class extends Q{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(Z.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function CO(e){return e===`completed`||e===`failed`||e===`cancelled`}var wO=Symbol(`Let zodToJsonSchema decide on which parser to use`),TO={name:void 0,$refStrategy:`root`,basePath:[`#`],effectStrategy:`input`,pipeStrategy:`all`,dateStrategy:`format:date-time`,mapStrategy:`entries`,removeAdditionalStrategy:`passthrough`,allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:`definitions`,target:`jsonSchema7`,strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:`escape`,applyRegexFlags:!1,emailStrategy:`format:email`,base64Strategy:`contentEncoding:base64`,nameStrategy:`ref`,openAiAnyTypeName:`OpenAiAnyType`},EO=e=>typeof e==`string`?{...TO,name:e}:{...TO,...e},DO=e=>{let t=EO(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function OO(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function kO(e,t,n,r,i){e[t]=n,OO(e,t,r,i)}var AO=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)};function jO(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?AO(t,e.currentPath):t.join(`/`)}}function MO(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==X.ZodAny&&(n.items=Sk(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&kO(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&kO(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(kO(n,`minItems`,e.exactLength.value,e.exactLength.message,t),kO(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function NO(e,t){let n={type:`integer`,format:`int64`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`min`:t.target===`jsonSchema7`?r.inclusive?kO(n,`minimum`,r.value,r.message,t):kO(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),kO(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?kO(n,`maximum`,r.value,r.message,t):kO(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),kO(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:kO(n,`multipleOf`,r.value,r.message,t)}return n}function PO(){return{type:`boolean`}}function FO(e,t){return Sk(e.type._def,t)}var IO=(e,t)=>Sk(e.innerType._def,t);function LO(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>LO(e,t,n))};switch(r){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return RO(e,t)}}var RO=(e,t)=>{let n={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return n;for(let r of e.checks)switch(r.kind){case`min`:kO(n,`minimum`,r.value,r.message,t);break;case`max`:kO(n,`maximum`,r.value,r.message,t)}return n};function zO(e,t){return{...Sk(e.innerType._def,t),default:e.defaultValue()}}function BO(e,t){return t.effectStrategy===`input`?Sk(e.schema._def,t):jO(t)}function VO(e){return{type:`string`,enum:Array.from(e.values)}}var HO=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function UO(e,t){let n=[Sk(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),Sk(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,i=[];return n.forEach(e=>{if(HO(e))i.push(...e.allOf),e.unevaluatedProperties===void 0&&(r=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:n,...r}=e;t=r}else r=void 0;i.push(t)}}),i.length?{allOf:i,...r}:void 0}function WO(e,t){let n=typeof e.value;return n!==`bigint`&&n!==`number`&&n!==`boolean`&&n!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:n===`bigint`?`integer`:n,enum:[e.value]}:{type:n===`bigint`?`integer`:n,const:e.value}}var GO=void 0,KO={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(GO===void 0&&(GO=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),GO),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function qO(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:kO(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:kO(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:ZO(n,`email`,r.message,t);break;case`format:idn-email`:ZO(n,`idn-email`,r.message,t);break;case`pattern:zod`:QO(n,KO.email,r.message,t)}break;case`url`:ZO(n,`uri`,r.message,t);break;case`uuid`:ZO(n,`uuid`,r.message,t);break;case`regex`:QO(n,r.regex,r.message,t);break;case`cuid`:QO(n,KO.cuid,r.message,t);break;case`cuid2`:QO(n,KO.cuid2,r.message,t);break;case`startsWith`:QO(n,RegExp(`^${JO(r.value,t)}`),r.message,t);break;case`endsWith`:QO(n,RegExp(`${JO(r.value,t)}$`),r.message,t);break;case`datetime`:ZO(n,`date-time`,r.message,t);break;case`date`:ZO(n,`date`,r.message,t);break;case`time`:ZO(n,`time`,r.message,t);break;case`duration`:ZO(n,`duration`,r.message,t);break;case`length`:kO(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),kO(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:QO(n,RegExp(JO(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&ZO(n,`ipv4`,r.message,t),r.version!==`v4`&&ZO(n,`ipv6`,r.message,t);break;case`base64url`:QO(n,KO.base64url,r.message,t);break;case`jwt`:QO(n,KO.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&QO(n,KO.ipv4Cidr,r.message,t),r.version!==`v4`&&QO(n,KO.ipv6Cidr,r.message,t);break;case`emoji`:QO(n,KO.emoji(),r.message,t);break;case`ulid`:QO(n,KO.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:ZO(n,`binary`,r.message,t);break;case`contentEncoding:base64`:kO(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:QO(n,KO.base64,r.message,t)}break;case`nanoid`:QO(n,KO.nanoid,r.message,t)}return n}function JO(e,t){return t.patternStrategy===`escape`?XO(e):e}var YO=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function XO(e){let t=``;for(let n=0;n<e.length;n++)YO.has(e[n])||(t+=`\\`),t+=e[n];return t}function ZO(e,t,n,r){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):kO(e,`format`,t,n,r)}function QO(e,t,n,r){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:$O(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):kO(e,`pattern`,$O(t,r),n,r)}function $O(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},r=n.i?e.source.toLowerCase():e.source,i=``,a=!1,o=!1,s=!1;for(let e=0;e<r.length;e++){if(a){i+=r[e],a=!1;continue}if(n.i){if(o){if(r[e].match(/[a-z]/)){s?(i+=r[e],i+=`${r[e-2]}-${r[e]}`.toUpperCase(),s=!1):r[e+1]===`-`&&r[e+2]?.match(/[a-z]/)?(i+=r[e],s=!0):i+=`${r[e]}${r[e].toUpperCase()}`;continue}}else if(r[e].match(/[a-z]/)){i+=`[${r[e]}${r[e].toUpperCase()}]`;continue}}if(n.m){if(r[e]===`^`){i+=`(^|(?<=[\r
|
|
297
297
|
]))`;continue}if(r[e]===`$`){i+=`($|(?=[\r
|
|
298
|
-
]))`;continue}}if(n.s&&r[e]===`.`){i+=o?`${r[e]}\r\n`:`[${r[e]}\r\n]`;continue}i+=r[e],r[e]===`\\`?a=!0:o&&r[e]===`]`?o=!1:!o&&r[e]===`[`&&(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function $O(e,t){if(t.target===`openAi`&&console.warn(`Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.`),t.target===`openApi3`&&e.keyType?._def.typeName===X.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:xk(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??AO(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:xk(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===X.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=KO(e.keyType._def,t);return{...n,propertyNames:i}}if(e.keyType?._def.typeName===X.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===X.ZodBranded&&e.keyType._def.type._def.typeName===X.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=PO(e.keyType._def,t);return{...n,propertyNames:i}}return n}function ek(e,t){return t.mapStrategy===`record`?$O(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[xk(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||AO(t),xk(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||AO(t)],minItems:2,maxItems:2}}}function tk(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}function nk(e){return e.target===`openAi`?void 0:{not:AO({...e,currentPath:[...e.currentPath,`not`]})}}function rk(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}var ik={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function ak(e,t){if(t.target===`openApi3`)return ok(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in ik&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=ik[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return ok(e,t)}var ok=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>xk(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function sk(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target===`openApi3`?{type:ik[e.innerType._def.typeName],nullable:!0}:{type:[ik[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=xk(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=xk(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function ck(e,t){let n={type:`number`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`int`:n.type=`integer`,DO(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?OO(n,`minimum`,r.value,r.message,t):OO(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),OO(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?OO(n,`maximum`,r.value,r.message,t):OO(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),OO(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:OO(n,`multipleOf`,r.value,r.message,t)}return n}function lk(e,t){let n=t.target===`openAi`,r={type:`object`,properties:{}},i=[],a=e.shape();for(let e in a){let o=a[e];if(o===void 0||o._def===void 0)continue;let s=dk(o);s&&n&&(o._def.typeName===`ZodOptional`&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=xk(o._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});c!==void 0&&(r.properties[e]=c,s||i.push(e))}i.length&&(r.required=i);let o=uk(e,t);return o!==void 0&&(r.additionalProperties=o),r}function uk(e,t){if(e.catchall._def.typeName!==`ZodNever`)return xk(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]});switch(e.unknownKeys){case`passthrough`:return t.allowedAdditionalProperties;case`strict`:return t.rejectedAdditionalProperties;case`strip`:return t.removeAdditionalStrategy===`strict`?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function dk(e){try{return e.isOptional()}catch{return!0}}var fk=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return xk(e.innerType._def,t);let n=xk(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:AO(t)},n]}:AO(t)},pk=(e,t)=>{if(t.pipeStrategy===`input`)return xk(e.in._def,t);if(t.pipeStrategy===`output`)return xk(e.out._def,t);let n=xk(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,xk(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function mk(e,t){return xk(e.type._def,t)}function hk(e,t){let n={type:`array`,uniqueItems:!0,items:xk(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&OO(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&OO(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function gk(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>xk(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:xk(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>xk(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function _k(e){return{not:AO(e)}}function vk(e){return AO(e)}var yk=(e,t)=>xk(e.innerType._def,t),bk=(e,t,n)=>{switch(t){case X.ZodString:return KO(e,n);case X.ZodNumber:return ck(e,n);case X.ZodObject:return lk(e,n);case X.ZodBigInt:return MO(e,n);case X.ZodBoolean:return NO();case X.ZodDate:return IO(e,n);case X.ZodUndefined:return _k(n);case X.ZodNull:return rk(n);case X.ZodArray:return jO(e,n);case X.ZodUnion:case X.ZodDiscriminatedUnion:return ak(e,n);case X.ZodIntersection:return HO(e,n);case X.ZodTuple:return gk(e,n);case X.ZodRecord:return $O(e,n);case X.ZodLiteral:return UO(e,n);case X.ZodEnum:return BO(e);case X.ZodNativeEnum:return tk(e);case X.ZodNullable:return sk(e,n);case X.ZodOptional:return fk(e,n);case X.ZodMap:return ek(e,n);case X.ZodSet:return hk(e,n);case X.ZodLazy:return()=>e.getter()._def;case X.ZodPromise:return mk(e,n);case X.ZodNaN:case X.ZodNever:return nk(n);case X.ZodEffects:return zO(e,n);case X.ZodAny:return AO(n);case X.ZodUnknown:return vk(n);case X.ZodDefault:return RO(e,n);case X.ZodBranded:return PO(e,n);case X.ZodReadonly:return yk(e,n);case X.ZodCatch:return FO(e,n);case X.ZodPipeline:return pk(e,n);case X.ZodFunction:case X.ZodVoid:case X.ZodSymbol:return;default:return(e=>void 0)(t)}};function xk(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==CO)return i}if(r&&!n){let e=Sk(r,t);if(e!==void 0)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let a=bk(e,e.typeName,t),o=typeof a==`function`?xk(a(),t):a;if(o&&Ck(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}var Sk=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:kO(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),AO(t)):t.$refStrategy===`seen`?AO(t):void 0}},Ck=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),wk=(e,t)=>{let n=EO(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:xk(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??AO(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=xk(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??AO(n),o=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;o!==void 0&&(a.title=o),n.flags.hasReferencedOpenAiAnyType&&(r||={},r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:[`string`,`number`,`integer`,`boolean`,`array`,`null`],items:{$ref:n.$refStrategy===`relative`?`1`:[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join(`/`)}}));let s=i===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,i].join(`/`),[n.definitionPath]:{...r,[i]:a}};return n.target===`jsonSchema7`?s.$schema=`http://json-schema.org/draft-07/schema#`:(n.target===`jsonSchema2019-09`||n.target===`openAi`)&&(s.$schema=`https://json-schema.org/draft/2019-09/schema#`),n.target===`openAi`&&(`anyOf`in s||`oneOf`in s||`allOf`in s||`type`in s&&Array.isArray(s.type))&&console.warn(`Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.`),s};function Tk(e){return!e||e===`jsonSchema7`||e===`draft-7`?`draft-7`:e===`jsonSchema2019-09`||e===`draft-2020-12`?`draft-2020-12`:`draft-7`}function Ek(e,t){return DT(e)?kc(e,{target:Tk(t?.target),io:t?.pipeStrategy??`input`}):wk(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??`input`})}function Dk(e){let t=jT(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=LT(t);if(typeof n!=`string`)throw Error(`Schema method literal must be a string`);return n}function Ok(e,t){let n=kT(e,t);if(!n.success)throw n.error;return n.data}var kk=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(fE,e=>{this._oncancel(e)}),this.setNotificationHandler(OE,e=>{this._onprogress(e)}),this.setRequestHandler(TE,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(LE,async(e,t)=>{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new Q(Z.InvalidParams,`Failed to retrieve task: Task not found`);return{...n}}),this.setRequestHandler(zE,async(e,t)=>{let n=async()=>{let r=e.params.taskId;if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(r,t.sessionId);){if(e.type===`response`||e.type===`error`){let t=e.message,n=t.id,r=this._requestResolvers.get(n);if(r){if(this._requestResolvers.delete(n),e.type===`response`)r(t);else{let e=t;r(new Q(e.error.code,e.error.message,e.error.data))}}else{let t=e.type===`response`?`Response`:`Error`;this._onerror(Error(`${t} handler missing for request ${n}`))}continue}await this._transport?.send(e.message,{relatedRequestId:t.requestId})}}let i=await this._taskStore.getTask(r,t.sessionId);if(!i)throw new Q(Z.InvalidParams,`Task not found: ${r}`);if(!SO(i.status))return await this._waitForTaskUpdate(r,t.signal),await n();if(SO(i.status)){let e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r),{...e,_meta:{...e._meta,[BT]:{taskId:r}}}}return await n()};return await n()}),this.setRequestHandler(BE,async(e,t)=>{try{let{tasks:n,nextCursor:r}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:n,nextCursor:r,_meta:{}}}catch(e){throw new Q(Z.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(HE,async(e,t)=>{try{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new Q(Z.InvalidParams,`Task not found: ${e.params.taskId}`);if(SO(n.status))throw new Q(Z.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,`cancelled`,`Client cancelled task execution.`,t.sessionId),this._clearTaskQueue(e.params.taskId);let r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new Q(Z.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){throw e instanceof Q?e:new Q(Z.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}async _oncancel(e){e.params.requestId&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,r,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:r})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),Q.fromError(Z.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw Error(`Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.`);this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=e=>{n?.(e),this._onerror(e)};let r=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{r?.(e,t),oE(e)||cE(e)?this._onresponse(e):nE(e)?this._onrequest(e,t):iE(e)?this._onnotification(e):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let e of this._timeoutInfo.values())clearTimeout(e.timeoutId);this._timeoutInfo.clear();for(let e of this._requestHandlerAbortControllers.values())e.abort();this._requestHandlerAbortControllers.clear();let t=Q.fromError(Z.ConnectionClosed,`Connection closed`);this._transport=void 0,this.onclose?.();for(let n of e.values())n(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,r=this._transport,i=e.params?._meta?.[BT]?.taskId;if(n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:Z.MethodNotFound,message:`Method not found`}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:`error`,message:t,timestamp:Date.now()},r?.sessionId).catch(e=>this._onerror(Error(`Failed to enqueue error response: ${e}`))):r?.send(t).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let o=YT(e.params)?e.params.task:void 0,s=this._taskStore?this.requestTaskStore(e,r?.sessionId):void 0,c={signal:a.signal,sessionId:r?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{if(a.signal.aborted)return;let n={relatedRequestId:e.id};i&&(n.relatedTask={taskId:i}),await this.notification(t,n)},sendRequest:async(t,n,r)=>{if(a.signal.aborted)throw new Q(Z.ConnectionClosed,`Request was cancelled`);let o={...r,relatedRequestId:e.id};i&&!o.relatedTask&&(o.relatedTask={taskId:i});let c=o.relatedTask?.taskId??i;return c&&s&&await s.updateTaskStatus(c,`input_required`),await this.request(t,n,o)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:i,taskStore:s,taskRequestedTtl:o?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{o&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,c)).then(async t=>{if(a.signal.aborted)return;let n={result:t,jsonrpc:`2.0`,id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`response`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)},async t=>{if(a.signal.aborted)return;let n={jsonrpc:`2.0`,id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:Z.InternalError,message:t.message??`Internal error`,...t.data!==void 0&&{data:t.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`error`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===a&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,r=Number(t),i=this._progressHandlers.get(r);if(!i){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(r),o=this._timeoutInfo.get(r);if(o&&a&&o.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(e){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(e);return}i(n)}_onresponse(e){let t=Number(e.id),n=this._requestResolvers.get(t);if(n){this._requestResolvers.delete(t),oE(e)?n(e):n(new Q(e.error.code,e.error.message,e.error.data));return}let r=this._responseHandlers.get(t);if(r===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let i=!1;if(oE(e)&&e.result&&typeof e.result==`object`){let n=e.result;if(n.task&&typeof n.task==`object`){let e=n.task;typeof e.taskId==`string`&&(i=!0,this._taskProgressTokens.set(e.taskId,t))}}i||this._progressHandlers.delete(t),oE(e)?r(e):r(Q.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,n){let{task:r}=n??{};if(!r){try{yield{type:`result`,result:await this.request(e,t,n)}}catch(e){yield{type:`error`,error:e instanceof Q?e:new Q(Z.InternalError,String(e))}}return}let i;try{let r=await this.request(e,PE,n);if(r.task)i=r.task.taskId,yield{type:`taskCreated`,task:r.task};else throw new Q(Z.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:i},n);if(yield{type:`taskStatus`,task:e},SO(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)}:e.status===`failed`?yield{type:`error`,error:new Q(Z.InternalError,`Task ${i} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new Q(Z.InternalError,`Task ${i} was cancelled`)});return}if(e.status===`input_required`){yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)};return}let r=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,r)),n?.signal?.throwIfAborted()}}catch(e){yield{type:`error`,error:e instanceof Q?e:new Q(Z.InternalError,String(e))}}}request(e,t,n){let{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a,task:o,relatedTask:s}=n??{};return new Promise((c,l)=>{let u=e=>{l(e)};if(!this._transport){u(Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),o&&this.assertTaskCapability(e.method)}catch(e){u(e);return}n?.signal?.throwIfAborted();let d=this._requestMessageId++,f={...e,jsonrpc:`2.0`,id:d};n?.onprogress&&(this._progressHandlers.set(d,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),o&&(f.params={...f.params,task:o}),s&&(f.params={...f.params,_meta:{...f.params?._meta||{},[BT]:s}});let p=e=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:`2.0`,method:`notifications/cancelled`,params:{requestId:d,reason:String(e)}},{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))),l(e instanceof Q?e:new Q(Z.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=kT(t,e.result);n.success?c(n.data):l(n.error)}catch(e){l(e)}}}),n?.signal?.addEventListener(`abort`,()=>{p(n?.signal?.reason)});let m=n?.timeout??6e4;this._setupTimeout(d,m,n?.maxTotalTimeout,()=>p(Q.fromError(Z.RequestTimeout,`Request timed out`,{timeout:m})),n?.resetTimeoutOnProgress??!1);let h=s?.taskId;h?(this._requestResolvers.set(d,e=>{let t=this._responseHandlers.get(d);t?t(e):this._onerror(Error(`Response handler missing for side-channeled request ${d}`))}),this._enqueueTaskMessage(h,{type:`request`,message:f,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(d),l(e)})):this._transport.send(f,{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>{this._cleanupTimeout(d),l(e)})})}async getTask(e,t){return this.request({method:`tasks/get`,params:e},RE,t)}async getTaskResult(e,t,n){return this.request({method:`tasks/result`,params:e},t,n)}async listTasks(e,t){return this.request({method:`tasks/list`,params:e},VE,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},UE,t)}async notification(e,t){if(!this._transport)throw Error(`Not connected`);this.assertNotificationCapability(e.method);let n=t?.relatedTask?.taskId;if(n){let r={...e,jsonrpc:`2.0`,params:{...e.params,_meta:{...e.params?._meta||{},[BT]:t.relatedTask}}};await this._enqueueTaskMessage(n,{type:`notification`,message:r,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let n={...e,jsonrpc:`2.0`};t?.relatedTask&&(n={...n,params:{...n.params,_meta:{...n.params?._meta||{},[BT]:t.relatedTask}}}),this._transport?.send(n,t).catch(e=>this._onerror(e))});return}let r={...e,jsonrpc:`2.0`};t?.relatedTask&&(r={...r,params:{...r.params,_meta:{...r.params?._meta||{},[BT]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let n=Dk(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{let i=Ok(e,n);return Promise.resolve(t(i,r))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let n=Dk(e);this._notificationHandlers.set(n,n=>{let r=Ok(e,n);return Promise.resolve(t(r))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);t!==void 0&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,n){if(!this._taskStore||!this._taskMessageQueue)throw Error(`Cannot enqueue task message: taskStore and taskMessageQueue are not configured`);let r=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,n,r)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,t);for(let t of n)if(t.type===`request`&&nE(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new Q(Z.InternalError,`Task cancelled or completed`)),this._requestResolvers.delete(n)):this._onerror(Error(`Resolver missing for request ${n} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let n=this._options?.defaultTaskPollInterval??1e3;try{let t=await this._taskStore?.getTask(e);t?.pollInterval&&(n=t.pollInterval)}catch{}return new Promise((e,r)=>{if(t.aborted){r(new Q(Z.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,n);t.addEventListener(`abort`,()=>{clearTimeout(i),r(new Q(Z.InvalidRequest,`Request cancelled`))},{once:!0})})}requestTaskStore(e,t){let n=this._taskStore;if(!n)throw Error(`No task store configured`);return{createTask:async r=>{if(!e)throw Error(`No request provided`);return await n.createTask(r,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{let r=await n.getTask(e,t);if(!r)throw new Q(Z.InvalidParams,`Failed to retrieve task: Task not found`);return r},storeTaskResult:async(e,r,i)=>{await n.storeTaskResult(e,r,i,t);let a=await n.getTask(e,t);if(a){let t=IE.parse({method:`notifications/tasks/status`,params:a});await this.notification(t),SO(a.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>n.getTaskResult(e,t),updateTaskStatus:async(e,r,i)=>{let a=await n.getTask(e,t);if(!a)throw new Q(Z.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(SO(a.status))throw new Q(Z.InvalidParams,`Cannot update task "${e}" from terminal status "${a.status}" to "${r}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(e,r,i,t);let o=await n.getTask(e,t);if(o){let t=IE.parse({method:`notifications/tasks/status`,params:o});await this.notification(t),SO(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}};function Ak(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function jk(e,t){let n={...e};for(let e in t){let r=e,i=t[r];if(i===void 0)continue;let a=n[r];n[r]=Ak(a)&&Ak(i)?{...a,...i}:i}return n}var Mk=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;var t=class{};e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var n=class extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw Error(`CodeGen: name must be a valid identifier`);this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};e.Name=n;var r=class extends t{constructor(e){super(),this._items=typeof e==`string`?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===``||e===`""`}get str(){return this._str??=this._items.reduce((e,t)=>`${e}${t}`,``)}get names(){return this._names??=this._items.reduce((e,t)=>(t instanceof n&&(e[t.str]=(e[t.str]||0)+1),e),{})}};e._Code=r,e.nil=new r(``);function i(e,...t){let n=[e[0]],i=0;for(;i<t.length;)s(n,t[i]),n.push(e[++i]);return new r(n)}e._=i;var a=new r(`+`);function o(e,...t){let n=[p(e[0])],i=0;for(;i<t.length;)n.push(a),s(n,t[i]),n.push(a,p(e[++i]));return c(n),new r(n)}e.str=o;function s(e,t){t instanceof r?e.push(...t._items):t instanceof n?e.push(t):e.push(d(t))}e.addCodeArg=s;function c(e){let t=1;for(;t<e.length-1;){if(e[t]===a){let n=l(e[t-1],e[t+1]);if(n!==void 0){e.splice(t-1,3,n);continue}e[t++]=`+`}t++}}function l(e,t){if(t===`""`)return e;if(e===`""`)return t;if(typeof e==`string`)return t instanceof n||e[e.length-1]!==`"`?void 0:typeof t==`string`?t[0]===`"`?e.slice(0,-1)+t.slice(1):void 0:`${e.slice(0,-1)}${t}"`;if(typeof t==`string`&&t[0]===`"`&&!(e instanceof n))return`"${e}${t.slice(1)}`}function u(e,t){return t.emptyStr()?e:e.emptyStr()?t:o`${e}${t}`}e.strConcat=u;function d(e){return typeof e==`number`||typeof e==`boolean`||e===null?e:p(Array.isArray(e)?e.join(`,`):e)}function f(e){return new r(p(e))}e.stringify=f;function p(e){return JSON.stringify(e).replace(/\u2028/g,`\\u2028`).replace(/\u2029/g,`\\u2029`)}e.safeStringify=p;function m(t){return typeof t==`string`&&e.IDENTIFIER.test(t)?new r(`.${t}`):i`[${t}]`}e.getProperty=m;function h(t){if(typeof t==`string`&&e.IDENTIFIER.test(t))return new r(`${t}`);throw Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}e.getEsmExportName=h;function g(e){return new r(e.toString())}e.regexpCode=g})),Nk=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;var t=Mk(),n=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},r;(function(e){e[e.Started=0]=`Started`,e[e.Completed=1]=`Completed`})(r||(e.UsedValueState=r={})),e.varKinds={const:new t.Name(`const`),let:new t.Name(`let`),var:new t.Name(`var`)};var i=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof t.Name?e:this.name(e)}name(e){return new t.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){if((this._parent?._prefixes)?.has(e)||this._prefixes&&!this._prefixes.has(e))throw Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};e.Scope=i;var a=class extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,t._)`.${new t.Name(n)}[${r}]`}};e.ValueScopeName=a;var o=(0,t._)`\n`;e.ValueScope=class extends i{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?o:t.nil}}get(){return this._scope}name(e){return new a(e,this._newName(e))}value(e,t){if(t.ref===void 0)throw Error(`CodeGen: ref must be passed in value`);let n=this.toName(e),{prefix:r}=n,i=t.key??t.ref,a=this._values[r];if(a){let e=a.get(i);if(e)return e}else a=this._values[r]=new Map;a.set(i,n);let o=this._scope[r]||(this._scope[r]=[]),s=o.length;return o[s]=t.ref,n.setValue(t,{property:r,itemIndex:s}),n}getValue(e,t){let n=this._values[e];if(n)return n.get(t)}scopeRefs(e,n=this._values){return this._reduceValues(n,n=>{if(n.scopePath===void 0)throw Error(`CodeGen: name "${n}" has no value`);return(0,t._)`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,e=>{if(e.value===void 0)throw Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,n)}_reduceValues(i,a,o={},s){let c=t.nil;for(let l in i){let u=i[l];if(!u)continue;let d=o[l]=o[l]||new Map;u.forEach(i=>{if(d.has(i))return;d.set(i,r.Started);let o=a(i);if(o){let n=this.opts.es5?e.varKinds.var:e.varKinds.const;c=(0,t._)`${c}${n} ${i} = ${o};${this.opts._n}`}else if(o=s?.(i))c=(0,t._)`${c}${o}${this.opts._n}`;else throw new n(i);d.set(i,r.Completed)})}return c}}})),$=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;var t=Mk(),n=Nk(),r=Mk();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}});var i=Nk();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return i.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return i.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return i.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return i.varKinds}}),e.operators={GT:new t._Code(`>`),GTE:new t._Code(`>=`),LT:new t._Code(`<`),LTE:new t._Code(`<=`),EQ:new t._Code(`===`),NEQ:new t._Code(`!==`),NOT:new t._Code(`!`),OR:new t._Code(`||`),AND:new t._Code(`&&`),ADD:new t._Code(`+`)};var a=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},o=class extends a{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let r=e?n.varKinds.var:this.varKind,i=this.rhs===void 0?``:` = ${this.rhs}`;return`${r} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&=C(this.rhs,e,t),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},s=class extends a{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof t.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=C(this.rhs,e,n),this}get names(){return ae(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},c=class extends s{constructor(e,t,n,r){super(e,n,r),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},l=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},u=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:``};`+e}},d=class extends a{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},f=class extends a{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=C(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},p=class extends a{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),``)}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,r=n.length;for(;r--;){let i=n[r];i.optimizeNames(e,t)||(oe(e,i.names),n.splice(r,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>ie(e,t.names),{})}},m=class extends p{render(e){return`{`+e._n+super.render(e)+`}`+e._n}},h=class extends p{},g=class extends m{};g.kind=`else`;var _=class e extends m{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+=`else `+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let n=this.else;if(n){let e=n.optimizeNodes();n=this.else=Array.isArray(e)?new g(e):e}if(n)return t===!1?n instanceof e?n:n.nodes:this.nodes.length?this:new e(w(t),n instanceof e?[n]:n.nodes);if(t!==!1&&this.nodes.length)return this}optimizeNames(e,t){if(this.else=this.else?.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=C(this.condition,e,t),this}get names(){let e=super.names;return ae(e,this.condition),this.else&&ie(e,this.else.names),e}};_.kind=`if`;var v=class extends m{};v.kind=`for`;var y=class extends v{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=C(this.iteration,e,t),this}get names(){return ie(super.names,this.iteration.names)}},b=class extends v{constructor(e,t,n,r){super(),this.varKind=e,this.name=t,this.from=n,this.to=r}render(e){let t=e.es5?n.varKinds.var:this.varKind,{name:r,from:i,to:a}=this;return`for(${t} ${r}=${i}; ${r}<${a}; ${r}++)`+super.render(e)}get names(){return ae(ae(super.names,this.from),this.to)}},x=class extends v{constructor(e,t,n,r){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=r}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=C(this.iterable,e,t),this}get names(){return ie(super.names,this.iterable.names)}},ee=class extends m{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?`async `:``}function ${this.name}(${this.args})`+super.render(e)}};ee.kind=`func`;var S=class extends p{render(e){return`return `+super.render(e)}};S.kind=`return`;var te=class extends m{render(e){let t=`try`+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)==null||e.optimizeNodes(),(t=this.finally)==null||t.optimizeNodes(),this}optimizeNames(e,t){var n,r;return super.optimizeNames(e,t),(n=this.catch)==null||n.optimizeNames(e,t),(r=this.finally)==null||r.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&ie(e,this.catch.names),this.finally&&ie(e,this.finally.names),e}},ne=class extends m{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};ne.kind=`catch`;var re=class extends m{render(e){return`finally`+super.render(e)}};re.kind=`finally`,e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
|
|
299
|
-
`:``},this._extScope=e,this._scope=new n.Scope({parent:e}),this._nodes=[new h]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,n,r){let i=this._scope.toName(t);return n!==void 0&&r&&(this._constants[i.str]=n),this._leafNode(new o(e,i,n)),i}const(e,t,r){return this._def(n.varKinds.const,e,t,r)}let(e,t,r){return this._def(n.varKinds.let,e,t,r)}var(e,t,r){return this._def(n.varKinds.var,e,t,r)}assign(e,t,n){return this._leafNode(new s(e,t,n))}add(t,n){return this._leafNode(new c(t,e.operators.ADD,n))}code(e){return typeof e==`function`?e():e!==t.nil&&this._leafNode(new f(e)),this}object(...e){let n=[`{`];for(let[r,i]of e)n.length>1&&n.push(`,`),n.push(r),(r!==i||this.opts.es5)&&(n.push(`:`),(0,t.addCodeArg)(n,i));return n.push(`}`),new t._Code(n)}if(e,t,n){if(this._blockNode(new _(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw Error(`CodeGen: "else" body without "then" body`);return this}elseIf(e){return this._elseNode(new _(e))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(_,g)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new y(e),t)}forRange(e,t,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.let){let o=this._scope.toName(e);return this._for(new b(a,o,t,r),()=>i(o))}forOf(e,r,i,a=n.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let e=r instanceof t.Name?r:this.var(`_arr`,r);return this.forRange(`_i`,0,(0,t._)`${e}.length`,n=>{this.var(o,(0,t._)`${e}[${n}]`),i(o)})}return this._for(new x(`of`,a,o,r),()=>i(o))}forIn(e,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,t._)`Object.keys(${r})`,i);let o=this._scope.toName(e);return this._for(new x(`in`,a,o,r),()=>i(o))}endFor(){return this._endBlockNode(v)}label(e){return this._leafNode(new l(e))}break(e){return this._leafNode(new u(e))}return(e){let t=new S;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error(`CodeGen: "return" should have one node`);return this._endBlockNode(S)}try(e,t,n){if(!t&&!n)throw Error(`CodeGen: "try" without "catch" and "finally"`);let r=new te;if(this._blockNode(r),this.code(e),t){let e=this.name(`e`);this._currNode=r.catch=new ne(e),t(e)}return n&&(this._currNode=r.finally=new re,this.code(n)),this._endBlockNode(ne,re)}throw(e){return this._leafNode(new d(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw Error(`CodeGen: not in self-balancing block`);let n=this._nodes.length-t;if(n<0||e!==void 0&&n!==e)throw Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,n=t.nil,r,i){return this._blockNode(new ee(e,n,r)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(ee)}optimize(e=1){for(;e-->0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof _))throw Error(`CodeGen: "else" without "if"`);return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}};function ie(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function ae(e,n){return n instanceof t._CodeOrName?ie(e,n.names):e}function C(e,n,r){return e instanceof t.Name?i(e):a(e)?new t._Code(e._items.reduce((e,n)=>(n instanceof t.Name&&(n=i(n)),n instanceof t._Code?e.push(...n._items):e.push(n),e),[])):e;function i(e){let t=r[e.str];return t===void 0||n[e.str]!==1?e:(delete n[e.str],t)}function a(e){return e instanceof t._Code&&e._items.some(e=>e instanceof t.Name&&n[e.str]===1&&r[e.str]!==void 0)}}function oe(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function w(e){return typeof e==`boolean`||typeof e==`number`||e===null?!e:(0,t._)`!${de(e)}`}e.not=w;var se=ue(e.operators.AND);function T(...e){return e.reduce(se)}e.and=T;var ce=ue(e.operators.OR);function le(...e){return e.reduce(ce)}e.or=le;function ue(e){return(n,r)=>n===t.nil?r:r===t.nil?n:(0,t._)`${de(n)} ${e} ${de(r)}`}function de(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),Pk=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.checkStrictMode=e.getErrorPath=e.Type=e.useFunc=e.setEvaluated=e.evaluatedPropsToName=e.mergeEvaluated=e.eachItem=e.unescapeJsonPointer=e.escapeJsonPointer=e.escapeFragment=e.unescapeFragment=e.schemaRefOrVal=e.schemaHasRulesButRef=e.schemaHasRules=e.checkUnknownRules=e.alwaysValidSchema=e.toHash=void 0;var t=$(),n=Mk();function r(e){let t={};for(let n of e)t[n]=!0;return t}e.toHash=r;function i(e,t){return typeof t==`boolean`?t:Object.keys(t).length===0||(a(e,t),!o(t,e.self.RULES.all))}e.alwaysValidSchema=i;function a(e,t=e.schema){let{opts:n,self:r}=e;if(!n.strictSchema||typeof t==`boolean`)return;let i=r.RULES.keywords;for(let n in t)i[n]||x(e,`unknown keyword: "${n}"`)}e.checkUnknownRules=a;function o(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(t[n])return!0;return!1}e.schemaHasRules=o;function s(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(n!==`$ref`&&t.all[n])return!0;return!1}e.schemaHasRulesButRef=s;function c({topSchemaRef:e,schemaPath:n},r,i,a){if(!a){if(typeof r==`number`||typeof r==`boolean`)return r;if(typeof r==`string`)return(0,t._)`${r}`}return(0,t._)`${e}${n}${(0,t.getProperty)(i)}`}e.schemaRefOrVal=c;function l(e){return f(decodeURIComponent(e))}e.unescapeFragment=l;function u(e){return encodeURIComponent(d(e))}e.escapeFragment=u;function d(e){return typeof e==`number`?`${e}`:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}e.escapeJsonPointer=d;function f(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}e.unescapeJsonPointer=f;function p(e,t){if(Array.isArray(e))for(let n of e)t(n);else t(e)}e.eachItem=p;function m({mergeNames:e,mergeToName:n,mergeValues:r,resultToName:i}){return(a,o,s,c)=>{let l=s===void 0?o:s instanceof t.Name?(o instanceof t.Name?e(a,o,s):n(a,o,s),s):o instanceof t.Name?(n(a,s,o),o):r(o,s);return c===t.Name&&!(l instanceof t.Name)?i(a,l):l}}e.mergeEvaluated={props:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>{e.if((0,t._)`${n} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,t._)`${r} || {}`).code((0,t._)`Object.assign(${r}, ${n})`))}),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>{n===!0?e.assign(r,!0):(e.assign(r,(0,t._)`${r} || {}`),g(e,r,n))}),mergeValues:(e,t)=>e===!0||{...e,...t},resultToName:h}),items:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>e.assign(r,(0,t._)`${n} === true ? true : ${r} > ${n} ? ${r} : ${n}`)),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>e.assign(r,n===!0||(0,t._)`${r} > ${n} ? ${r} : ${n}`)),mergeValues:(e,t)=>e===!0||Math.max(e,t),resultToName:(e,t)=>e.var(`items`,t)})};function h(e,n){if(n===!0)return e.var(`props`,!0);let r=e.var(`props`,(0,t._)`{}`);return n!==void 0&&g(e,r,n),r}e.evaluatedPropsToName=h;function g(e,n,r){Object.keys(r).forEach(r=>e.assign((0,t._)`${n}${(0,t.getProperty)(r)}`,!0))}e.setEvaluated=g;var _={};function v(e,t){return e.scopeValue(`func`,{ref:t,code:_[t.code]||(_[t.code]=new n._Code(t.code))})}e.useFunc=v;var y;(function(e){e[e.Num=0]=`Num`,e[e.Str=1]=`Str`})(y||(e.Type=y={}));function b(e,n,r){if(e instanceof t.Name){let i=n===y.Num;return r?i?(0,t._)`"[" + ${e} + "]"`:(0,t._)`"['" + ${e} + "']"`:i?(0,t._)`"/" + ${e}`:(0,t._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,t.getProperty)(e).toString():`/`+d(e)}e.getErrorPath=b;function x(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,n===!0)throw Error(t);e.self.logger.warn(t)}}e.checkStrictMode=x})),Fk=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$();e.default={data:new t.Name(`data`),valCxt:new t.Name(`valCxt`),instancePath:new t.Name(`instancePath`),parentData:new t.Name(`parentData`),parentDataProperty:new t.Name(`parentDataProperty`),rootData:new t.Name(`rootData`),dynamicAnchors:new t.Name(`dynamicAnchors`),vErrors:new t.Name(`vErrors`),errors:new t.Name(`errors`),this:new t.Name(`this`),self:new t.Name(`self`),scope:new t.Name(`scope`),json:new t.Name(`json`),jsonPos:new t.Name(`jsonPos`),jsonLen:new t.Name(`jsonLen`),jsonPart:new t.Name(`jsonPart`)}})),Ik=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;var t=$(),n=Pk(),r=Fk();e.keywordError={message:({keyword:e})=>(0,t.str)`must pass "${e}" keyword validation`},e.keyword$DataError={message:({keyword:e,schemaType:n})=>n?(0,t.str)`"${e}" keyword must be ${n} ($data)`:(0,t.str)`"${e}" keyword is invalid ($data)`};function i(n,r=e.keywordError,i,a){let{it:o}=n,{gen:s,compositeRule:u,allErrors:f}=o,p=d(n,r,i);a??(u||f)?c(s,p):l(o,(0,t._)`[${p}]`)}e.reportError=i;function a(t,n=e.keywordError,i){let{it:a}=t,{gen:o,compositeRule:s,allErrors:u}=a;c(o,d(t,n,i)),s||u||l(a,r.default.vErrors)}e.reportExtraError=a;function o(e,n){e.assign(r.default.errors,n),e.if((0,t._)`${r.default.vErrors} !== null`,()=>e.if(n,()=>e.assign((0,t._)`${r.default.vErrors}.length`,n),()=>e.assign(r.default.vErrors,null)))}e.resetErrorsCount=o;function s({gen:e,keyword:n,schemaValue:i,data:a,errsCount:o,it:s}){if(o===void 0)throw Error(`ajv implementation error`);let c=e.name(`err`);e.forRange(`i`,o,r.default.errors,o=>{e.const(c,(0,t._)`${r.default.vErrors}[${o}]`),e.if((0,t._)`${c}.instancePath === undefined`,()=>e.assign((0,t._)`${c}.instancePath`,(0,t.strConcat)(r.default.instancePath,s.errorPath))),e.assign((0,t._)`${c}.schemaPath`,(0,t.str)`${s.errSchemaPath}/${n}`),s.opts.verbose&&(e.assign((0,t._)`${c}.schema`,i),e.assign((0,t._)`${c}.data`,a))})}e.extendErrors=s;function c(e,n){let i=e.const(`err`,n);e.if((0,t._)`${r.default.vErrors} === null`,()=>e.assign(r.default.vErrors,(0,t._)`[${i}]`),(0,t._)`${r.default.vErrors}.push(${i})`),e.code((0,t._)`${r.default.errors}++`)}function l(e,n){let{gen:r,validateName:i,schemaEnv:a}=e;a.$async?r.throw((0,t._)`new ${e.ValidationError}(${n})`):(r.assign((0,t._)`${i}.errors`,n),r.return(!1))}var u={keyword:new t.Name(`keyword`),schemaPath:new t.Name(`schemaPath`),params:new t.Name(`params`),propertyName:new t.Name(`propertyName`),message:new t.Name(`message`),schema:new t.Name(`schema`),parentSchema:new t.Name(`parentSchema`)};function d(e,n,r){let{createErrors:i}=e.it;return i===!1?(0,t._)`{}`:f(e,n,r)}function f(e,t,n={}){let{gen:r,it:i}=e,a=[p(i,n),m(e,n)];return h(e,t,a),r.object(...a)}function p({errorPath:e},{instancePath:i}){let a=i?(0,t.str)`${e}${(0,n.getErrorPath)(i,n.Type.Str)}`:e;return[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,a)]}function m({keyword:e,it:{errSchemaPath:r}},{schemaPath:i,parentSchema:a}){let o=a?r:(0,t.str)`${r}/${e}`;return i&&(o=(0,t.str)`${o}${(0,n.getErrorPath)(i,n.Type.Str)}`),[u.schemaPath,o]}function h(e,{params:n,message:i},a){let{keyword:o,data:s,schemaValue:c,it:l}=e,{opts:d,propertyName:f,topSchemaRef:p,schemaPath:m}=l;a.push([u.keyword,o],[u.params,typeof n==`function`?n(e):n||(0,t._)`{}`]),d.messages&&a.push([u.message,typeof i==`function`?i(e):i]),d.verbose&&a.push([u.schema,c],[u.parentSchema,(0,t._)`${p}${m}`],[r.default.data,s]),f&&a.push([u.propertyName,f])}})),Lk=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;var t=Ik(),n=$(),r=Fk(),i={message:`boolean schema is false`};function a(e){let{gen:t,schema:i,validateName:a}=e;i===!1?s(e,!1):typeof i==`object`&&i.$async===!0?t.return(r.default.data):(t.assign((0,n._)`${a}.errors`,null),t.return(!0))}e.topBoolOrEmptySchema=a;function o(e,t){let{gen:n,schema:r}=e;r===!1?(n.var(t,!1),s(e)):n.var(t,!0)}e.boolOrEmptySchema=o;function s(e,n){let{gen:r,data:a}=e,o={gen:r,keyword:`false schema`,data:a,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,t.reportError)(o,i,void 0,n)}})),Rk=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getRules=e.isJSONType=void 0;var t=new Set([`string`,`number`,`integer`,`boolean`,`null`,`object`,`array`]);function n(e){return typeof e==`string`&&t.has(e)}e.isJSONType=n;function r(){let e={number:{type:`number`,rules:[]},string:{type:`string`,rules:[]},array:{type:`array`,rules:[]},object:{type:`object`,rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}e.getRules=r})),zk=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.shouldUseRule=e.shouldUseGroup=e.schemaHasRulesForType=void 0;function t({schema:e,self:t},r){let i=t.RULES.types[r];return i&&i!==!0&&n(e,i)}e.schemaHasRulesForType=t;function n(e,t){return t.rules.some(t=>r(e,t))}e.shouldUseGroup=n;function r(e,t){return e[t.keyword]!==void 0||t.definition.implements?.some(t=>e[t]!==void 0)}e.shouldUseRule=r})),Bk=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.reportTypeError=e.checkDataTypes=e.checkDataType=e.coerceAndCheckDataType=e.getJSONTypes=e.getSchemaTypes=e.DataType=void 0;var t=Rk(),n=zk(),r=Ik(),i=$(),a=Pk(),o;(function(e){e[e.Correct=0]=`Correct`,e[e.Wrong=1]=`Wrong`})(o||(e.DataType=o={}));function s(e){let t=c(e.type);if(t.includes(`null`)){if(e.nullable===!1)throw Error(`type: null contradicts nullable: false`)}else{if(!t.length&&e.nullable!==void 0)throw Error(`"nullable" cannot be used without "type"`);e.nullable===!0&&t.push(`null`)}return t}e.getSchemaTypes=s;function c(e){let n=Array.isArray(e)?e:e?[e]:[];if(n.every(t.isJSONType))return n;throw Error(`type must be JSONType or JSONType[]: `+n.join(`,`))}e.getJSONTypes=c;function l(e,t){let{gen:r,data:i,opts:a}=e,s=d(t,a.coerceTypes),c=t.length>0&&!(s.length===0&&t.length===1&&(0,n.schemaHasRulesForType)(e,t[0]));if(c){let n=h(t,i,a.strictNumbers,o.Wrong);r.if(n,()=>{s.length?f(e,t,s):_(e)})}return c}e.coerceAndCheckDataType=l;var u=new Set([`string`,`number`,`integer`,`boolean`,`null`]);function d(e,t){return t?e.filter(e=>u.has(e)||t===`array`&&e===`array`):[]}function f(e,t,n){let{gen:r,data:a,opts:o}=e,s=r.let(`dataType`,(0,i._)`typeof ${a}`),c=r.let(`coerced`,(0,i._)`undefined`);o.coerceTypes===`array`&&r.if((0,i._)`${s} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>r.assign(a,(0,i._)`${a}[0]`).assign(s,(0,i._)`typeof ${a}`).if(h(t,a,o.strictNumbers),()=>r.assign(c,a))),r.if((0,i._)`${c} !== undefined`);for(let e of n)(u.has(e)||e===`array`&&o.coerceTypes===`array`)&&l(e);r.else(),_(e),r.endIf(),r.if((0,i._)`${c} !== undefined`,()=>{r.assign(a,c),p(e,c)});function l(e){switch(e){case`string`:r.elseIf((0,i._)`${s} == "number" || ${s} == "boolean"`).assign(c,(0,i._)`"" + ${a}`).elseIf((0,i._)`${a} === null`).assign(c,(0,i._)`""`);return;case`number`:r.elseIf((0,i._)`${s} == "boolean" || ${a} === null
|
|
298
|
+
]))`;continue}}if(n.s&&r[e]===`.`){i+=o?`${r[e]}\r\n`:`[${r[e]}\r\n]`;continue}i+=r[e],r[e]===`\\`?a=!0:o&&r[e]===`]`?o=!1:!o&&r[e]===`[`&&(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function ek(e,t){if(t.target===`openAi`&&console.warn(`Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.`),t.target===`openApi3`&&e.keyType?._def.typeName===X.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:Sk(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??jO(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:Sk(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===X.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=qO(e.keyType._def,t);return{...n,propertyNames:i}}if(e.keyType?._def.typeName===X.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===X.ZodBranded&&e.keyType._def.type._def.typeName===X.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=FO(e.keyType._def,t);return{...n,propertyNames:i}}return n}function tk(e,t){return t.mapStrategy===`record`?ek(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[Sk(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||jO(t),Sk(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||jO(t)],minItems:2,maxItems:2}}}function nk(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}function rk(e){return e.target===`openAi`?void 0:{not:jO({...e,currentPath:[...e.currentPath,`not`]})}}function ik(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}var ak={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function ok(e,t){if(t.target===`openApi3`)return sk(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in ak&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=ak[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return sk(e,t)}var sk=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>Sk(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function ck(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target===`openApi3`?{type:ak[e.innerType._def.typeName],nullable:!0}:{type:[ak[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=Sk(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=Sk(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function lk(e,t){let n={type:`number`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`int`:n.type=`integer`,OO(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?kO(n,`minimum`,r.value,r.message,t):kO(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),kO(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?kO(n,`maximum`,r.value,r.message,t):kO(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),kO(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:kO(n,`multipleOf`,r.value,r.message,t)}return n}function uk(e,t){let n=t.target===`openAi`,r={type:`object`,properties:{}},i=[],a=e.shape();for(let e in a){let o=a[e];if(o===void 0||o._def===void 0)continue;let s=fk(o);s&&n&&(o._def.typeName===`ZodOptional`&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=Sk(o._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});c!==void 0&&(r.properties[e]=c,s||i.push(e))}i.length&&(r.required=i);let o=dk(e,t);return o!==void 0&&(r.additionalProperties=o),r}function dk(e,t){if(e.catchall._def.typeName!==`ZodNever`)return Sk(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]});switch(e.unknownKeys){case`passthrough`:return t.allowedAdditionalProperties;case`strict`:return t.rejectedAdditionalProperties;case`strip`:return t.removeAdditionalStrategy===`strict`?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function fk(e){try{return e.isOptional()}catch{return!0}}var pk=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return Sk(e.innerType._def,t);let n=Sk(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:jO(t)},n]}:jO(t)},mk=(e,t)=>{if(t.pipeStrategy===`input`)return Sk(e.in._def,t);if(t.pipeStrategy===`output`)return Sk(e.out._def,t);let n=Sk(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,Sk(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function hk(e,t){return Sk(e.type._def,t)}function gk(e,t){let n={type:`array`,uniqueItems:!0,items:Sk(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&kO(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&kO(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function _k(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>Sk(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:Sk(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>Sk(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function vk(e){return{not:jO(e)}}function yk(e){return jO(e)}var bk=(e,t)=>Sk(e.innerType._def,t),xk=(e,t,n)=>{switch(t){case X.ZodString:return qO(e,n);case X.ZodNumber:return lk(e,n);case X.ZodObject:return uk(e,n);case X.ZodBigInt:return NO(e,n);case X.ZodBoolean:return PO();case X.ZodDate:return LO(e,n);case X.ZodUndefined:return vk(n);case X.ZodNull:return ik(n);case X.ZodArray:return MO(e,n);case X.ZodUnion:case X.ZodDiscriminatedUnion:return ok(e,n);case X.ZodIntersection:return UO(e,n);case X.ZodTuple:return _k(e,n);case X.ZodRecord:return ek(e,n);case X.ZodLiteral:return WO(e,n);case X.ZodEnum:return VO(e);case X.ZodNativeEnum:return nk(e);case X.ZodNullable:return ck(e,n);case X.ZodOptional:return pk(e,n);case X.ZodMap:return tk(e,n);case X.ZodSet:return gk(e,n);case X.ZodLazy:return()=>e.getter()._def;case X.ZodPromise:return hk(e,n);case X.ZodNaN:case X.ZodNever:return rk(n);case X.ZodEffects:return BO(e,n);case X.ZodAny:return jO(n);case X.ZodUnknown:return yk(n);case X.ZodDefault:return zO(e,n);case X.ZodBranded:return FO(e,n);case X.ZodReadonly:return bk(e,n);case X.ZodCatch:return IO(e,n);case X.ZodPipeline:return mk(e,n);case X.ZodFunction:case X.ZodVoid:case X.ZodSymbol:return;default:return(e=>void 0)(t)}};function Sk(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==wO)return i}if(r&&!n){let e=Ck(r,t);if(e!==void 0)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let a=xk(e,e.typeName,t),o=typeof a==`function`?Sk(a(),t):a;if(o&&wk(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}var Ck=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:AO(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),jO(t)):t.$refStrategy===`seen`?jO(t):void 0}},wk=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),Tk=(e,t)=>{let n=DO(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:Sk(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??jO(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=Sk(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??jO(n),o=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;o!==void 0&&(a.title=o),n.flags.hasReferencedOpenAiAnyType&&(r||={},r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:[`string`,`number`,`integer`,`boolean`,`array`,`null`],items:{$ref:n.$refStrategy===`relative`?`1`:[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join(`/`)}}));let s=i===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,i].join(`/`),[n.definitionPath]:{...r,[i]:a}};return n.target===`jsonSchema7`?s.$schema=`http://json-schema.org/draft-07/schema#`:(n.target===`jsonSchema2019-09`||n.target===`openAi`)&&(s.$schema=`https://json-schema.org/draft/2019-09/schema#`),n.target===`openAi`&&(`anyOf`in s||`oneOf`in s||`allOf`in s||`type`in s&&Array.isArray(s.type))&&console.warn(`Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.`),s};function Ek(e){return!e||e===`jsonSchema7`||e===`draft-7`?`draft-7`:e===`jsonSchema2019-09`||e===`draft-2020-12`?`draft-2020-12`:`draft-7`}function Dk(e,t){return OT(e)?kc(e,{target:Ek(t?.target),io:t?.pipeStrategy??`input`}):Tk(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??`input`})}function Ok(e){let t=MT(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=RT(t);if(typeof n!=`string`)throw Error(`Schema method literal must be a string`);return n}function kk(e,t){let n=AT(e,t);if(!n.success)throw n.error;return n.data}var Ak=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(pE,e=>{this._oncancel(e)}),this.setNotificationHandler(kE,e=>{this._onprogress(e)}),this.setRequestHandler(EE,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(RE,async(e,t)=>{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new Q(Z.InvalidParams,`Failed to retrieve task: Task not found`);return{...n}}),this.setRequestHandler(BE,async(e,t)=>{let n=async()=>{let r=e.params.taskId;if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(r,t.sessionId);){if(e.type===`response`||e.type===`error`){let t=e.message,n=t.id,r=this._requestResolvers.get(n);if(r){if(this._requestResolvers.delete(n),e.type===`response`)r(t);else{let e=t;r(new Q(e.error.code,e.error.message,e.error.data))}}else{let t=e.type===`response`?`Response`:`Error`;this._onerror(Error(`${t} handler missing for request ${n}`))}continue}await this._transport?.send(e.message,{relatedRequestId:t.requestId})}}let i=await this._taskStore.getTask(r,t.sessionId);if(!i)throw new Q(Z.InvalidParams,`Task not found: ${r}`);if(!CO(i.status))return await this._waitForTaskUpdate(r,t.signal),await n();if(CO(i.status)){let e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r),{...e,_meta:{...e._meta,[VT]:{taskId:r}}}}return await n()};return await n()}),this.setRequestHandler(VE,async(e,t)=>{try{let{tasks:n,nextCursor:r}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:n,nextCursor:r,_meta:{}}}catch(e){throw new Q(Z.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(UE,async(e,t)=>{try{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new Q(Z.InvalidParams,`Task not found: ${e.params.taskId}`);if(CO(n.status))throw new Q(Z.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,`cancelled`,`Client cancelled task execution.`,t.sessionId),this._clearTaskQueue(e.params.taskId);let r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new Q(Z.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){throw e instanceof Q?e:new Q(Z.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}async _oncancel(e){e.params.requestId&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,r,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:r})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),Q.fromError(Z.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw Error(`Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.`);this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=e=>{n?.(e),this._onerror(e)};let r=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{r?.(e,t),sE(e)||lE(e)?this._onresponse(e):rE(e)?this._onrequest(e,t):aE(e)?this._onnotification(e):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let e of this._timeoutInfo.values())clearTimeout(e.timeoutId);this._timeoutInfo.clear();for(let e of this._requestHandlerAbortControllers.values())e.abort();this._requestHandlerAbortControllers.clear();let t=Q.fromError(Z.ConnectionClosed,`Connection closed`);this._transport=void 0,this.onclose?.();for(let n of e.values())n(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,r=this._transport,i=e.params?._meta?.[VT]?.taskId;if(n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:Z.MethodNotFound,message:`Method not found`}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:`error`,message:t,timestamp:Date.now()},r?.sessionId).catch(e=>this._onerror(Error(`Failed to enqueue error response: ${e}`))):r?.send(t).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let o=XT(e.params)?e.params.task:void 0,s=this._taskStore?this.requestTaskStore(e,r?.sessionId):void 0,c={signal:a.signal,sessionId:r?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{if(a.signal.aborted)return;let n={relatedRequestId:e.id};i&&(n.relatedTask={taskId:i}),await this.notification(t,n)},sendRequest:async(t,n,r)=>{if(a.signal.aborted)throw new Q(Z.ConnectionClosed,`Request was cancelled`);let o={...r,relatedRequestId:e.id};i&&!o.relatedTask&&(o.relatedTask={taskId:i});let c=o.relatedTask?.taskId??i;return c&&s&&await s.updateTaskStatus(c,`input_required`),await this.request(t,n,o)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:i,taskStore:s,taskRequestedTtl:o?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{o&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,c)).then(async t=>{if(a.signal.aborted)return;let n={result:t,jsonrpc:`2.0`,id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`response`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)},async t=>{if(a.signal.aborted)return;let n={jsonrpc:`2.0`,id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:Z.InternalError,message:t.message??`Internal error`,...t.data!==void 0&&{data:t.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`error`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===a&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,r=Number(t),i=this._progressHandlers.get(r);if(!i){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(r),o=this._timeoutInfo.get(r);if(o&&a&&o.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(e){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(e);return}i(n)}_onresponse(e){let t=Number(e.id),n=this._requestResolvers.get(t);if(n){this._requestResolvers.delete(t),sE(e)?n(e):n(new Q(e.error.code,e.error.message,e.error.data));return}let r=this._responseHandlers.get(t);if(r===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let i=!1;if(sE(e)&&e.result&&typeof e.result==`object`){let n=e.result;if(n.task&&typeof n.task==`object`){let e=n.task;typeof e.taskId==`string`&&(i=!0,this._taskProgressTokens.set(e.taskId,t))}}i||this._progressHandlers.delete(t),sE(e)?r(e):r(Q.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,n){let{task:r}=n??{};if(!r){try{yield{type:`result`,result:await this.request(e,t,n)}}catch(e){yield{type:`error`,error:e instanceof Q?e:new Q(Z.InternalError,String(e))}}return}let i;try{let r=await this.request(e,FE,n);if(r.task)i=r.task.taskId,yield{type:`taskCreated`,task:r.task};else throw new Q(Z.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:i},n);if(yield{type:`taskStatus`,task:e},CO(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)}:e.status===`failed`?yield{type:`error`,error:new Q(Z.InternalError,`Task ${i} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new Q(Z.InternalError,`Task ${i} was cancelled`)});return}if(e.status===`input_required`){yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)};return}let r=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,r)),n?.signal?.throwIfAborted()}}catch(e){yield{type:`error`,error:e instanceof Q?e:new Q(Z.InternalError,String(e))}}}request(e,t,n){let{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a,task:o,relatedTask:s}=n??{};return new Promise((c,l)=>{let u=e=>{l(e)};if(!this._transport){u(Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),o&&this.assertTaskCapability(e.method)}catch(e){u(e);return}n?.signal?.throwIfAborted();let d=this._requestMessageId++,f={...e,jsonrpc:`2.0`,id:d};n?.onprogress&&(this._progressHandlers.set(d,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),o&&(f.params={...f.params,task:o}),s&&(f.params={...f.params,_meta:{...f.params?._meta||{},[VT]:s}});let p=e=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:`2.0`,method:`notifications/cancelled`,params:{requestId:d,reason:String(e)}},{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))),l(e instanceof Q?e:new Q(Z.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=AT(t,e.result);n.success?c(n.data):l(n.error)}catch(e){l(e)}}}),n?.signal?.addEventListener(`abort`,()=>{p(n?.signal?.reason)});let m=n?.timeout??6e4;this._setupTimeout(d,m,n?.maxTotalTimeout,()=>p(Q.fromError(Z.RequestTimeout,`Request timed out`,{timeout:m})),n?.resetTimeoutOnProgress??!1);let h=s?.taskId;h?(this._requestResolvers.set(d,e=>{let t=this._responseHandlers.get(d);t?t(e):this._onerror(Error(`Response handler missing for side-channeled request ${d}`))}),this._enqueueTaskMessage(h,{type:`request`,message:f,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(d),l(e)})):this._transport.send(f,{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>{this._cleanupTimeout(d),l(e)})})}async getTask(e,t){return this.request({method:`tasks/get`,params:e},zE,t)}async getTaskResult(e,t,n){return this.request({method:`tasks/result`,params:e},t,n)}async listTasks(e,t){return this.request({method:`tasks/list`,params:e},HE,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},WE,t)}async notification(e,t){if(!this._transport)throw Error(`Not connected`);this.assertNotificationCapability(e.method);let n=t?.relatedTask?.taskId;if(n){let r={...e,jsonrpc:`2.0`,params:{...e.params,_meta:{...e.params?._meta||{},[VT]:t.relatedTask}}};await this._enqueueTaskMessage(n,{type:`notification`,message:r,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let n={...e,jsonrpc:`2.0`};t?.relatedTask&&(n={...n,params:{...n.params,_meta:{...n.params?._meta||{},[VT]:t.relatedTask}}}),this._transport?.send(n,t).catch(e=>this._onerror(e))});return}let r={...e,jsonrpc:`2.0`};t?.relatedTask&&(r={...r,params:{...r.params,_meta:{...r.params?._meta||{},[VT]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let n=Ok(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{let i=kk(e,n);return Promise.resolve(t(i,r))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let n=Ok(e);this._notificationHandlers.set(n,n=>{let r=kk(e,n);return Promise.resolve(t(r))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);t!==void 0&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,n){if(!this._taskStore||!this._taskMessageQueue)throw Error(`Cannot enqueue task message: taskStore and taskMessageQueue are not configured`);let r=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,n,r)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,t);for(let t of n)if(t.type===`request`&&rE(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new Q(Z.InternalError,`Task cancelled or completed`)),this._requestResolvers.delete(n)):this._onerror(Error(`Resolver missing for request ${n} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let n=this._options?.defaultTaskPollInterval??1e3;try{let t=await this._taskStore?.getTask(e);t?.pollInterval&&(n=t.pollInterval)}catch{}return new Promise((e,r)=>{if(t.aborted){r(new Q(Z.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,n);t.addEventListener(`abort`,()=>{clearTimeout(i),r(new Q(Z.InvalidRequest,`Request cancelled`))},{once:!0})})}requestTaskStore(e,t){let n=this._taskStore;if(!n)throw Error(`No task store configured`);return{createTask:async r=>{if(!e)throw Error(`No request provided`);return await n.createTask(r,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{let r=await n.getTask(e,t);if(!r)throw new Q(Z.InvalidParams,`Failed to retrieve task: Task not found`);return r},storeTaskResult:async(e,r,i)=>{await n.storeTaskResult(e,r,i,t);let a=await n.getTask(e,t);if(a){let t=LE.parse({method:`notifications/tasks/status`,params:a});await this.notification(t),CO(a.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>n.getTaskResult(e,t),updateTaskStatus:async(e,r,i)=>{let a=await n.getTask(e,t);if(!a)throw new Q(Z.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(CO(a.status))throw new Q(Z.InvalidParams,`Cannot update task "${e}" from terminal status "${a.status}" to "${r}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(e,r,i,t);let o=await n.getTask(e,t);if(o){let t=LE.parse({method:`notifications/tasks/status`,params:o});await this.notification(t),CO(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}};function jk(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Mk(e,t){let n={...e};for(let e in t){let r=e,i=t[r];if(i===void 0)continue;let a=n[r];n[r]=jk(a)&&jk(i)?{...a,...i}:i}return n}var Nk=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;var t=class{};e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var n=class extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw Error(`CodeGen: name must be a valid identifier`);this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};e.Name=n;var r=class extends t{constructor(e){super(),this._items=typeof e==`string`?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===``||e===`""`}get str(){return this._str??=this._items.reduce((e,t)=>`${e}${t}`,``)}get names(){return this._names??=this._items.reduce((e,t)=>(t instanceof n&&(e[t.str]=(e[t.str]||0)+1),e),{})}};e._Code=r,e.nil=new r(``);function i(e,...t){let n=[e[0]],i=0;for(;i<t.length;)s(n,t[i]),n.push(e[++i]);return new r(n)}e._=i;var a=new r(`+`);function o(e,...t){let n=[p(e[0])],i=0;for(;i<t.length;)n.push(a),s(n,t[i]),n.push(a,p(e[++i]));return c(n),new r(n)}e.str=o;function s(e,t){t instanceof r?e.push(...t._items):t instanceof n?e.push(t):e.push(d(t))}e.addCodeArg=s;function c(e){let t=1;for(;t<e.length-1;){if(e[t]===a){let n=l(e[t-1],e[t+1]);if(n!==void 0){e.splice(t-1,3,n);continue}e[t++]=`+`}t++}}function l(e,t){if(t===`""`)return e;if(e===`""`)return t;if(typeof e==`string`)return t instanceof n||e[e.length-1]!==`"`?void 0:typeof t==`string`?t[0]===`"`?e.slice(0,-1)+t.slice(1):void 0:`${e.slice(0,-1)}${t}"`;if(typeof t==`string`&&t[0]===`"`&&!(e instanceof n))return`"${e}${t.slice(1)}`}function u(e,t){return t.emptyStr()?e:e.emptyStr()?t:o`${e}${t}`}e.strConcat=u;function d(e){return typeof e==`number`||typeof e==`boolean`||e===null?e:p(Array.isArray(e)?e.join(`,`):e)}function f(e){return new r(p(e))}e.stringify=f;function p(e){return JSON.stringify(e).replace(/\u2028/g,`\\u2028`).replace(/\u2029/g,`\\u2029`)}e.safeStringify=p;function m(t){return typeof t==`string`&&e.IDENTIFIER.test(t)?new r(`.${t}`):i`[${t}]`}e.getProperty=m;function h(t){if(typeof t==`string`&&e.IDENTIFIER.test(t))return new r(`${t}`);throw Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}e.getEsmExportName=h;function g(e){return new r(e.toString())}e.regexpCode=g})),Pk=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;var t=Nk(),n=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},r;(function(e){e[e.Started=0]=`Started`,e[e.Completed=1]=`Completed`})(r||(e.UsedValueState=r={})),e.varKinds={const:new t.Name(`const`),let:new t.Name(`let`),var:new t.Name(`var`)};var i=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof t.Name?e:this.name(e)}name(e){return new t.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){if((this._parent?._prefixes)?.has(e)||this._prefixes&&!this._prefixes.has(e))throw Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};e.Scope=i;var a=class extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,t._)`.${new t.Name(n)}[${r}]`}};e.ValueScopeName=a;var o=(0,t._)`\n`;e.ValueScope=class extends i{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?o:t.nil}}get(){return this._scope}name(e){return new a(e,this._newName(e))}value(e,t){if(t.ref===void 0)throw Error(`CodeGen: ref must be passed in value`);let n=this.toName(e),{prefix:r}=n,i=t.key??t.ref,a=this._values[r];if(a){let e=a.get(i);if(e)return e}else a=this._values[r]=new Map;a.set(i,n);let o=this._scope[r]||(this._scope[r]=[]),s=o.length;return o[s]=t.ref,n.setValue(t,{property:r,itemIndex:s}),n}getValue(e,t){let n=this._values[e];if(n)return n.get(t)}scopeRefs(e,n=this._values){return this._reduceValues(n,n=>{if(n.scopePath===void 0)throw Error(`CodeGen: name "${n}" has no value`);return(0,t._)`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,e=>{if(e.value===void 0)throw Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,n)}_reduceValues(i,a,o={},s){let c=t.nil;for(let l in i){let u=i[l];if(!u)continue;let d=o[l]=o[l]||new Map;u.forEach(i=>{if(d.has(i))return;d.set(i,r.Started);let o=a(i);if(o){let n=this.opts.es5?e.varKinds.var:e.varKinds.const;c=(0,t._)`${c}${n} ${i} = ${o};${this.opts._n}`}else if(o=s?.(i))c=(0,t._)`${c}${o}${this.opts._n}`;else throw new n(i);d.set(i,r.Completed)})}return c}}})),$=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;var t=Nk(),n=Pk(),r=Nk();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}});var i=Pk();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return i.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return i.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return i.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return i.varKinds}}),e.operators={GT:new t._Code(`>`),GTE:new t._Code(`>=`),LT:new t._Code(`<`),LTE:new t._Code(`<=`),EQ:new t._Code(`===`),NEQ:new t._Code(`!==`),NOT:new t._Code(`!`),OR:new t._Code(`||`),AND:new t._Code(`&&`),ADD:new t._Code(`+`)};var a=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},o=class extends a{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let r=e?n.varKinds.var:this.varKind,i=this.rhs===void 0?``:` = ${this.rhs}`;return`${r} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&=C(this.rhs,e,t),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},s=class extends a{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof t.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=C(this.rhs,e,n),this}get names(){return ae(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},c=class extends s{constructor(e,t,n,r){super(e,n,r),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},l=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},u=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:``};`+e}},d=class extends a{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},f=class extends a{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=C(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},p=class extends a{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),``)}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,r=n.length;for(;r--;){let i=n[r];i.optimizeNames(e,t)||(oe(e,i.names),n.splice(r,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>ie(e,t.names),{})}},m=class extends p{render(e){return`{`+e._n+super.render(e)+`}`+e._n}},h=class extends p{},g=class extends m{};g.kind=`else`;var _=class e extends m{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+=`else `+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let n=this.else;if(n){let e=n.optimizeNodes();n=this.else=Array.isArray(e)?new g(e):e}if(n)return t===!1?n instanceof e?n:n.nodes:this.nodes.length?this:new e(w(t),n instanceof e?[n]:n.nodes);if(t!==!1&&this.nodes.length)return this}optimizeNames(e,t){if(this.else=this.else?.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=C(this.condition,e,t),this}get names(){let e=super.names;return ae(e,this.condition),this.else&&ie(e,this.else.names),e}};_.kind=`if`;var v=class extends m{};v.kind=`for`;var y=class extends v{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=C(this.iteration,e,t),this}get names(){return ie(super.names,this.iteration.names)}},b=class extends v{constructor(e,t,n,r){super(),this.varKind=e,this.name=t,this.from=n,this.to=r}render(e){let t=e.es5?n.varKinds.var:this.varKind,{name:r,from:i,to:a}=this;return`for(${t} ${r}=${i}; ${r}<${a}; ${r}++)`+super.render(e)}get names(){return ae(ae(super.names,this.from),this.to)}},x=class extends v{constructor(e,t,n,r){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=r}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=C(this.iterable,e,t),this}get names(){return ie(super.names,this.iterable.names)}},ee=class extends m{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?`async `:``}function ${this.name}(${this.args})`+super.render(e)}};ee.kind=`func`;var S=class extends p{render(e){return`return `+super.render(e)}};S.kind=`return`;var te=class extends m{render(e){let t=`try`+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)==null||e.optimizeNodes(),(t=this.finally)==null||t.optimizeNodes(),this}optimizeNames(e,t){var n,r;return super.optimizeNames(e,t),(n=this.catch)==null||n.optimizeNames(e,t),(r=this.finally)==null||r.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&ie(e,this.catch.names),this.finally&&ie(e,this.finally.names),e}},ne=class extends m{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};ne.kind=`catch`;var re=class extends m{render(e){return`finally`+super.render(e)}};re.kind=`finally`,e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
|
|
299
|
+
`:``},this._extScope=e,this._scope=new n.Scope({parent:e}),this._nodes=[new h]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,n,r){let i=this._scope.toName(t);return n!==void 0&&r&&(this._constants[i.str]=n),this._leafNode(new o(e,i,n)),i}const(e,t,r){return this._def(n.varKinds.const,e,t,r)}let(e,t,r){return this._def(n.varKinds.let,e,t,r)}var(e,t,r){return this._def(n.varKinds.var,e,t,r)}assign(e,t,n){return this._leafNode(new s(e,t,n))}add(t,n){return this._leafNode(new c(t,e.operators.ADD,n))}code(e){return typeof e==`function`?e():e!==t.nil&&this._leafNode(new f(e)),this}object(...e){let n=[`{`];for(let[r,i]of e)n.length>1&&n.push(`,`),n.push(r),(r!==i||this.opts.es5)&&(n.push(`:`),(0,t.addCodeArg)(n,i));return n.push(`}`),new t._Code(n)}if(e,t,n){if(this._blockNode(new _(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw Error(`CodeGen: "else" body without "then" body`);return this}elseIf(e){return this._elseNode(new _(e))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(_,g)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new y(e),t)}forRange(e,t,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.let){let o=this._scope.toName(e);return this._for(new b(a,o,t,r),()=>i(o))}forOf(e,r,i,a=n.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let e=r instanceof t.Name?r:this.var(`_arr`,r);return this.forRange(`_i`,0,(0,t._)`${e}.length`,n=>{this.var(o,(0,t._)`${e}[${n}]`),i(o)})}return this._for(new x(`of`,a,o,r),()=>i(o))}forIn(e,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,t._)`Object.keys(${r})`,i);let o=this._scope.toName(e);return this._for(new x(`in`,a,o,r),()=>i(o))}endFor(){return this._endBlockNode(v)}label(e){return this._leafNode(new l(e))}break(e){return this._leafNode(new u(e))}return(e){let t=new S;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error(`CodeGen: "return" should have one node`);return this._endBlockNode(S)}try(e,t,n){if(!t&&!n)throw Error(`CodeGen: "try" without "catch" and "finally"`);let r=new te;if(this._blockNode(r),this.code(e),t){let e=this.name(`e`);this._currNode=r.catch=new ne(e),t(e)}return n&&(this._currNode=r.finally=new re,this.code(n)),this._endBlockNode(ne,re)}throw(e){return this._leafNode(new d(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw Error(`CodeGen: not in self-balancing block`);let n=this._nodes.length-t;if(n<0||e!==void 0&&n!==e)throw Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,n=t.nil,r,i){return this._blockNode(new ee(e,n,r)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(ee)}optimize(e=1){for(;e-->0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof _))throw Error(`CodeGen: "else" without "if"`);return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}};function ie(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function ae(e,n){return n instanceof t._CodeOrName?ie(e,n.names):e}function C(e,n,r){return e instanceof t.Name?i(e):a(e)?new t._Code(e._items.reduce((e,n)=>(n instanceof t.Name&&(n=i(n)),n instanceof t._Code?e.push(...n._items):e.push(n),e),[])):e;function i(e){let t=r[e.str];return t===void 0||n[e.str]!==1?e:(delete n[e.str],t)}function a(e){return e instanceof t._Code&&e._items.some(e=>e instanceof t.Name&&n[e.str]===1&&r[e.str]!==void 0)}}function oe(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function w(e){return typeof e==`boolean`||typeof e==`number`||e===null?!e:(0,t._)`!${de(e)}`}e.not=w;var se=ue(e.operators.AND);function T(...e){return e.reduce(se)}e.and=T;var ce=ue(e.operators.OR);function le(...e){return e.reduce(ce)}e.or=le;function ue(e){return(n,r)=>n===t.nil?r:r===t.nil?n:(0,t._)`${de(n)} ${e} ${de(r)}`}function de(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),Fk=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.checkStrictMode=e.getErrorPath=e.Type=e.useFunc=e.setEvaluated=e.evaluatedPropsToName=e.mergeEvaluated=e.eachItem=e.unescapeJsonPointer=e.escapeJsonPointer=e.escapeFragment=e.unescapeFragment=e.schemaRefOrVal=e.schemaHasRulesButRef=e.schemaHasRules=e.checkUnknownRules=e.alwaysValidSchema=e.toHash=void 0;var t=$(),n=Nk();function r(e){let t={};for(let n of e)t[n]=!0;return t}e.toHash=r;function i(e,t){return typeof t==`boolean`?t:Object.keys(t).length===0||(a(e,t),!o(t,e.self.RULES.all))}e.alwaysValidSchema=i;function a(e,t=e.schema){let{opts:n,self:r}=e;if(!n.strictSchema||typeof t==`boolean`)return;let i=r.RULES.keywords;for(let n in t)i[n]||x(e,`unknown keyword: "${n}"`)}e.checkUnknownRules=a;function o(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(t[n])return!0;return!1}e.schemaHasRules=o;function s(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(n!==`$ref`&&t.all[n])return!0;return!1}e.schemaHasRulesButRef=s;function c({topSchemaRef:e,schemaPath:n},r,i,a){if(!a){if(typeof r==`number`||typeof r==`boolean`)return r;if(typeof r==`string`)return(0,t._)`${r}`}return(0,t._)`${e}${n}${(0,t.getProperty)(i)}`}e.schemaRefOrVal=c;function l(e){return f(decodeURIComponent(e))}e.unescapeFragment=l;function u(e){return encodeURIComponent(d(e))}e.escapeFragment=u;function d(e){return typeof e==`number`?`${e}`:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}e.escapeJsonPointer=d;function f(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}e.unescapeJsonPointer=f;function p(e,t){if(Array.isArray(e))for(let n of e)t(n);else t(e)}e.eachItem=p;function m({mergeNames:e,mergeToName:n,mergeValues:r,resultToName:i}){return(a,o,s,c)=>{let l=s===void 0?o:s instanceof t.Name?(o instanceof t.Name?e(a,o,s):n(a,o,s),s):o instanceof t.Name?(n(a,s,o),o):r(o,s);return c===t.Name&&!(l instanceof t.Name)?i(a,l):l}}e.mergeEvaluated={props:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>{e.if((0,t._)`${n} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,t._)`${r} || {}`).code((0,t._)`Object.assign(${r}, ${n})`))}),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>{n===!0?e.assign(r,!0):(e.assign(r,(0,t._)`${r} || {}`),g(e,r,n))}),mergeValues:(e,t)=>e===!0||{...e,...t},resultToName:h}),items:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>e.assign(r,(0,t._)`${n} === true ? true : ${r} > ${n} ? ${r} : ${n}`)),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>e.assign(r,n===!0||(0,t._)`${r} > ${n} ? ${r} : ${n}`)),mergeValues:(e,t)=>e===!0||Math.max(e,t),resultToName:(e,t)=>e.var(`items`,t)})};function h(e,n){if(n===!0)return e.var(`props`,!0);let r=e.var(`props`,(0,t._)`{}`);return n!==void 0&&g(e,r,n),r}e.evaluatedPropsToName=h;function g(e,n,r){Object.keys(r).forEach(r=>e.assign((0,t._)`${n}${(0,t.getProperty)(r)}`,!0))}e.setEvaluated=g;var _={};function v(e,t){return e.scopeValue(`func`,{ref:t,code:_[t.code]||(_[t.code]=new n._Code(t.code))})}e.useFunc=v;var y;(function(e){e[e.Num=0]=`Num`,e[e.Str=1]=`Str`})(y||(e.Type=y={}));function b(e,n,r){if(e instanceof t.Name){let i=n===y.Num;return r?i?(0,t._)`"[" + ${e} + "]"`:(0,t._)`"['" + ${e} + "']"`:i?(0,t._)`"/" + ${e}`:(0,t._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,t.getProperty)(e).toString():`/`+d(e)}e.getErrorPath=b;function x(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,n===!0)throw Error(t);e.self.logger.warn(t)}}e.checkStrictMode=x})),Ik=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$();e.default={data:new t.Name(`data`),valCxt:new t.Name(`valCxt`),instancePath:new t.Name(`instancePath`),parentData:new t.Name(`parentData`),parentDataProperty:new t.Name(`parentDataProperty`),rootData:new t.Name(`rootData`),dynamicAnchors:new t.Name(`dynamicAnchors`),vErrors:new t.Name(`vErrors`),errors:new t.Name(`errors`),this:new t.Name(`this`),self:new t.Name(`self`),scope:new t.Name(`scope`),json:new t.Name(`json`),jsonPos:new t.Name(`jsonPos`),jsonLen:new t.Name(`jsonLen`),jsonPart:new t.Name(`jsonPart`)}})),Lk=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;var t=$(),n=Fk(),r=Ik();e.keywordError={message:({keyword:e})=>(0,t.str)`must pass "${e}" keyword validation`},e.keyword$DataError={message:({keyword:e,schemaType:n})=>n?(0,t.str)`"${e}" keyword must be ${n} ($data)`:(0,t.str)`"${e}" keyword is invalid ($data)`};function i(n,r=e.keywordError,i,a){let{it:o}=n,{gen:s,compositeRule:u,allErrors:f}=o,p=d(n,r,i);a??(u||f)?c(s,p):l(o,(0,t._)`[${p}]`)}e.reportError=i;function a(t,n=e.keywordError,i){let{it:a}=t,{gen:o,compositeRule:s,allErrors:u}=a;c(o,d(t,n,i)),s||u||l(a,r.default.vErrors)}e.reportExtraError=a;function o(e,n){e.assign(r.default.errors,n),e.if((0,t._)`${r.default.vErrors} !== null`,()=>e.if(n,()=>e.assign((0,t._)`${r.default.vErrors}.length`,n),()=>e.assign(r.default.vErrors,null)))}e.resetErrorsCount=o;function s({gen:e,keyword:n,schemaValue:i,data:a,errsCount:o,it:s}){if(o===void 0)throw Error(`ajv implementation error`);let c=e.name(`err`);e.forRange(`i`,o,r.default.errors,o=>{e.const(c,(0,t._)`${r.default.vErrors}[${o}]`),e.if((0,t._)`${c}.instancePath === undefined`,()=>e.assign((0,t._)`${c}.instancePath`,(0,t.strConcat)(r.default.instancePath,s.errorPath))),e.assign((0,t._)`${c}.schemaPath`,(0,t.str)`${s.errSchemaPath}/${n}`),s.opts.verbose&&(e.assign((0,t._)`${c}.schema`,i),e.assign((0,t._)`${c}.data`,a))})}e.extendErrors=s;function c(e,n){let i=e.const(`err`,n);e.if((0,t._)`${r.default.vErrors} === null`,()=>e.assign(r.default.vErrors,(0,t._)`[${i}]`),(0,t._)`${r.default.vErrors}.push(${i})`),e.code((0,t._)`${r.default.errors}++`)}function l(e,n){let{gen:r,validateName:i,schemaEnv:a}=e;a.$async?r.throw((0,t._)`new ${e.ValidationError}(${n})`):(r.assign((0,t._)`${i}.errors`,n),r.return(!1))}var u={keyword:new t.Name(`keyword`),schemaPath:new t.Name(`schemaPath`),params:new t.Name(`params`),propertyName:new t.Name(`propertyName`),message:new t.Name(`message`),schema:new t.Name(`schema`),parentSchema:new t.Name(`parentSchema`)};function d(e,n,r){let{createErrors:i}=e.it;return i===!1?(0,t._)`{}`:f(e,n,r)}function f(e,t,n={}){let{gen:r,it:i}=e,a=[p(i,n),m(e,n)];return h(e,t,a),r.object(...a)}function p({errorPath:e},{instancePath:i}){let a=i?(0,t.str)`${e}${(0,n.getErrorPath)(i,n.Type.Str)}`:e;return[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,a)]}function m({keyword:e,it:{errSchemaPath:r}},{schemaPath:i,parentSchema:a}){let o=a?r:(0,t.str)`${r}/${e}`;return i&&(o=(0,t.str)`${o}${(0,n.getErrorPath)(i,n.Type.Str)}`),[u.schemaPath,o]}function h(e,{params:n,message:i},a){let{keyword:o,data:s,schemaValue:c,it:l}=e,{opts:d,propertyName:f,topSchemaRef:p,schemaPath:m}=l;a.push([u.keyword,o],[u.params,typeof n==`function`?n(e):n||(0,t._)`{}`]),d.messages&&a.push([u.message,typeof i==`function`?i(e):i]),d.verbose&&a.push([u.schema,c],[u.parentSchema,(0,t._)`${p}${m}`],[r.default.data,s]),f&&a.push([u.propertyName,f])}})),Rk=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;var t=Lk(),n=$(),r=Ik(),i={message:`boolean schema is false`};function a(e){let{gen:t,schema:i,validateName:a}=e;i===!1?s(e,!1):typeof i==`object`&&i.$async===!0?t.return(r.default.data):(t.assign((0,n._)`${a}.errors`,null),t.return(!0))}e.topBoolOrEmptySchema=a;function o(e,t){let{gen:n,schema:r}=e;r===!1?(n.var(t,!1),s(e)):n.var(t,!0)}e.boolOrEmptySchema=o;function s(e,n){let{gen:r,data:a}=e,o={gen:r,keyword:`false schema`,data:a,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,t.reportError)(o,i,void 0,n)}})),zk=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getRules=e.isJSONType=void 0;var t=new Set([`string`,`number`,`integer`,`boolean`,`null`,`object`,`array`]);function n(e){return typeof e==`string`&&t.has(e)}e.isJSONType=n;function r(){let e={number:{type:`number`,rules:[]},string:{type:`string`,rules:[]},array:{type:`array`,rules:[]},object:{type:`object`,rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}e.getRules=r})),Bk=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.shouldUseRule=e.shouldUseGroup=e.schemaHasRulesForType=void 0;function t({schema:e,self:t},r){let i=t.RULES.types[r];return i&&i!==!0&&n(e,i)}e.schemaHasRulesForType=t;function n(e,t){return t.rules.some(t=>r(e,t))}e.shouldUseGroup=n;function r(e,t){return e[t.keyword]!==void 0||t.definition.implements?.some(t=>e[t]!==void 0)}e.shouldUseRule=r})),Vk=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.reportTypeError=e.checkDataTypes=e.checkDataType=e.coerceAndCheckDataType=e.getJSONTypes=e.getSchemaTypes=e.DataType=void 0;var t=zk(),n=Bk(),r=Lk(),i=$(),a=Fk(),o;(function(e){e[e.Correct=0]=`Correct`,e[e.Wrong=1]=`Wrong`})(o||(e.DataType=o={}));function s(e){let t=c(e.type);if(t.includes(`null`)){if(e.nullable===!1)throw Error(`type: null contradicts nullable: false`)}else{if(!t.length&&e.nullable!==void 0)throw Error(`"nullable" cannot be used without "type"`);e.nullable===!0&&t.push(`null`)}return t}e.getSchemaTypes=s;function c(e){let n=Array.isArray(e)?e:e?[e]:[];if(n.every(t.isJSONType))return n;throw Error(`type must be JSONType or JSONType[]: `+n.join(`,`))}e.getJSONTypes=c;function l(e,t){let{gen:r,data:i,opts:a}=e,s=d(t,a.coerceTypes),c=t.length>0&&!(s.length===0&&t.length===1&&(0,n.schemaHasRulesForType)(e,t[0]));if(c){let n=h(t,i,a.strictNumbers,o.Wrong);r.if(n,()=>{s.length?f(e,t,s):_(e)})}return c}e.coerceAndCheckDataType=l;var u=new Set([`string`,`number`,`integer`,`boolean`,`null`]);function d(e,t){return t?e.filter(e=>u.has(e)||t===`array`&&e===`array`):[]}function f(e,t,n){let{gen:r,data:a,opts:o}=e,s=r.let(`dataType`,(0,i._)`typeof ${a}`),c=r.let(`coerced`,(0,i._)`undefined`);o.coerceTypes===`array`&&r.if((0,i._)`${s} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>r.assign(a,(0,i._)`${a}[0]`).assign(s,(0,i._)`typeof ${a}`).if(h(t,a,o.strictNumbers),()=>r.assign(c,a))),r.if((0,i._)`${c} !== undefined`);for(let e of n)(u.has(e)||e===`array`&&o.coerceTypes===`array`)&&l(e);r.else(),_(e),r.endIf(),r.if((0,i._)`${c} !== undefined`,()=>{r.assign(a,c),p(e,c)});function l(e){switch(e){case`string`:r.elseIf((0,i._)`${s} == "number" || ${s} == "boolean"`).assign(c,(0,i._)`"" + ${a}`).elseIf((0,i._)`${a} === null`).assign(c,(0,i._)`""`);return;case`number`:r.elseIf((0,i._)`${s} == "boolean" || ${a} === null
|
|
300
300
|
|| (${s} == "string" && ${a} && ${a} == +${a})`).assign(c,(0,i._)`+${a}`);return;case`integer`:r.elseIf((0,i._)`${s} === "boolean" || ${a} === null
|
|
301
301
|
|| (${s} === "string" && ${a} && ${a} == +${a} && !(${a} % 1))`).assign(c,(0,i._)`+${a}`);return;case`boolean`:r.elseIf((0,i._)`${a} === "false" || ${a} === 0 || ${a} === null`).assign(c,!1).elseIf((0,i._)`${a} === "true" || ${a} === 1`).assign(c,!0);return;case`null`:r.elseIf((0,i._)`${a} === "" || ${a} === 0 || ${a} === false`),r.assign(c,null);return;case`array`:r.elseIf((0,i._)`${s} === "string" || ${s} === "number"
|
|
302
|
-
|| ${s} === "boolean" || ${a} === null`).assign(c,(0,i._)`[${a}]`)}}}function p({gen:e,parentData:t,parentDataProperty:n},r){e.if((0,i._)`${t} !== undefined`,()=>e.assign((0,i._)`${t}[${n}]`,r))}function m(e,t,n,r=o.Correct){let a=r===o.Correct?i.operators.EQ:i.operators.NEQ,s;switch(e){case`null`:return(0,i._)`${t} ${a} null`;case`array`:s=(0,i._)`Array.isArray(${t})`;break;case`object`:s=(0,i._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case`integer`:s=c((0,i._)`!(${t} % 1) && !isNaN(${t})`);break;case`number`:s=c();break;default:return(0,i._)`typeof ${t} ${a} ${e}`}return r===o.Correct?s:(0,i.not)(s);function c(e=i.nil){return(0,i.and)((0,i._)`typeof ${t} == "number"`,e,n?(0,i._)`isFinite(${t})`:i.nil)}}e.checkDataType=m;function h(e,t,n,r){if(e.length===1)return m(e[0],t,n,r);let o,s=(0,a.toHash)(e);if(s.array&&s.object){let e=(0,i._)`typeof ${t} != "object"`;o=s.null?e:(0,i._)`!${t} || ${e}`,delete s.null,delete s.array,delete s.object}else o=i.nil;s.number&&delete s.integer;for(let e in s)o=(0,i.and)(o,m(e,t,n,r));return o}e.checkDataTypes=h;var g={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e==`string`?(0,i._)`{type: ${e}}`:(0,i._)`{type: ${t}}`};function _(e){let t=v(e);(0,r.reportError)(t,g)}e.reportTypeError=_;function v(e){let{gen:t,data:n,schema:r}=e,i=(0,a.schemaRefOrVal)(e,r,`type`);return{gen:t,keyword:`type`,data:n,schema:r.type,schemaCode:i,schemaValue:i,parentSchema:r,params:{},it:e}}})),Vk=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.assignDefaults=void 0;var t=$(),n=Pk();function r(e,t){let{properties:n,items:r}=e.schema;if(t===`object`&&n)for(let t in n)i(e,t,n[t].default);else t===`array`&&Array.isArray(r)&&r.forEach((t,n)=>i(e,n,t.default))}e.assignDefaults=r;function i(e,r,i){let{gen:a,compositeRule:o,data:s,opts:c}=e;if(i===void 0)return;let l=(0,t._)`${s}${(0,t.getProperty)(r)}`;if(o){(0,n.checkStrictMode)(e,`default is ignored for: ${l}`);return}let u=(0,t._)`${l} === undefined`;c.useDefaults===`empty`&&(u=(0,t._)`${u} || ${l} === null || ${l} === ""`),a.if(u,(0,t._)`${l} = ${(0,t.stringify)(i)}`)}})),Hk=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateUnion=e.validateArray=e.usePattern=e.callValidateCode=e.schemaProperties=e.allSchemaProperties=e.noPropertyInData=e.propertyInData=e.isOwnProperty=e.hasPropFunc=e.reportMissingProp=e.checkMissingProp=e.checkReportMissingProp=void 0;var t=$(),n=Pk(),r=Fk(),i=Pk();function a(e,n){let{gen:r,data:i,it:a}=e;r.if(d(r,i,n,a.opts.ownProperties),()=>{e.setParams({missingProperty:(0,t._)`${n}`},!0),e.error()})}e.checkReportMissingProp=a;function o({gen:e,data:n,it:{opts:r}},i,a){return(0,t.or)(...i.map(i=>(0,t.and)(d(e,n,i,r.ownProperties),(0,t._)`${a} = ${i}`)))}e.checkMissingProp=o;function s(e,t){e.setParams({missingProperty:t},!0),e.error()}e.reportMissingProp=s;function c(e){return e.scopeValue(`func`,{ref:Object.prototype.hasOwnProperty,code:(0,t._)`Object.prototype.hasOwnProperty`})}e.hasPropFunc=c;function l(e,n,r){return(0,t._)`${c(e)}.call(${n}, ${r})`}e.isOwnProperty=l;function u(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} !== undefined`;return i?(0,t._)`${a} && ${l(e,n,r)}`:a}e.propertyInData=u;function d(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} === undefined`;return i?(0,t.or)(a,(0,t.not)(l(e,n,r))):a}e.noPropertyInData=d;function f(e){return e?Object.keys(e).filter(e=>e!==`__proto__`):[]}e.allSchemaProperties=f;function p(e,t){return f(t).filter(r=>!(0,n.alwaysValidSchema)(e,t[r]))}e.schemaProperties=p;function m({schemaCode:e,data:n,it:{gen:i,topSchemaRef:a,schemaPath:o,errorPath:s},it:c},l,u,d){let f=d?(0,t._)`${e}, ${n}, ${a}${o}`:n,p=[[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,s)],[r.default.parentData,c.parentData],[r.default.parentDataProperty,c.parentDataProperty],[r.default.rootData,r.default.rootData]];c.opts.dynamicRef&&p.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);let m=(0,t._)`${f}, ${i.object(...p)}`;return u===t.nil?(0,t._)`${l}(${m})`:(0,t._)`${l}.call(${u}, ${m})`}e.callValidateCode=m;var h=(0,t._)`new RegExp`;function g({gen:e,it:{opts:n}},r){let a=n.unicodeRegExp?`u`:``,{regExp:o}=n.code,s=o(r,a);return e.scopeValue(`pattern`,{key:s.toString(),ref:s,code:(0,t._)`${o.code===`new RegExp`?h:(0,i.useFunc)(e,o)}(${r}, ${a})`})}e.usePattern=g;function _(e){let{gen:r,data:i,keyword:a,it:o}=e,s=r.name(`valid`);if(o.allErrors){let e=r.let(`valid`,!0);return c(()=>r.assign(e,!1)),e}return r.var(s,!0),c(()=>r.break()),s;function c(o){let c=r.const(`len`,(0,t._)`${i}.length`);r.forRange(`i`,0,c,i=>{e.subschema({keyword:a,dataProp:i,dataPropType:n.Type.Num},s),r.if((0,t.not)(s),o)})}}e.validateArray=_;function v(e){let{gen:r,schema:i,keyword:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(i.some(e=>(0,n.alwaysValidSchema)(o,e))&&!o.opts.unevaluated)return;let s=r.let(`valid`,!1),c=r.name(`_valid`);r.block(()=>i.forEach((n,i)=>{let o=e.subschema({keyword:a,schemaProp:i,compositeRule:!0},c);r.assign(s,(0,t._)`${s} || ${c}`),e.mergeValidEvaluated(o,c)||r.if((0,t.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}e.validateUnion=v})),Uk=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;var t=$(),n=Fk(),r=Hk(),i=Ik();function a(e,n){let{gen:r,keyword:i,schema:a,parentSchema:o,it:s}=e,c=n.macro.call(s.self,a,o,s),l=u(r,i,c);s.opts.validateSchema!==!1&&s.self.validateSchema(c,!0);let d=r.name(`valid`);e.subschema({schema:c,schemaPath:t.nil,errSchemaPath:`${s.errSchemaPath}/${i}`,topSchemaRef:l,compositeRule:!0},d),e.pass(d,()=>e.error(!0))}e.macroKeywordCode=a;function o(e,i){let{gen:a,keyword:o,schema:d,parentSchema:f,$data:p,it:m}=e;l(m,i);let h=u(a,o,!p&&i.compile?i.compile.call(m.self,d,f,m):i.validate),g=a.let(`valid`);e.block$data(g,_),e.ok(i.valid??g);function _(){if(i.errors===!1)b(),i.modifying&&s(e),x(()=>e.error());else{let t=i.async?v():y();i.modifying&&s(e),x(()=>c(e,t))}}function v(){let e=a.let(`ruleErrs`,null);return a.try(()=>b((0,t._)`await `),n=>a.assign(g,!1).if((0,t._)`${n} instanceof ${m.ValidationError}`,()=>a.assign(e,(0,t._)`${n}.errors`),()=>a.throw(n))),e}function y(){let e=(0,t._)`${h}.errors`;return a.assign(e,null),b(t.nil),e}function b(o=i.async?(0,t._)`await `:t.nil){let s=m.opts.passContext?n.default.this:n.default.self,c=!(`compile`in i&&!p||i.schema===!1);a.assign(g,(0,t._)`${o}${(0,r.callValidateCode)(e,h,s,c)}`,i.modifying)}function x(e){a.if((0,t.not)(i.valid??g),e)}}e.funcKeywordCode=o;function s(e){let{gen:n,data:r,it:i}=e;n.if(i.parentData,()=>n.assign(r,(0,t._)`${i.parentData}[${i.parentDataProperty}]`))}function c(e,r){let{gen:a}=e;a.if((0,t._)`Array.isArray(${r})`,()=>{a.assign(n.default.vErrors,(0,t._)`${n.default.vErrors} === null ? ${r} : ${n.default.vErrors}.concat(${r})`).assign(n.default.errors,(0,t._)`${n.default.vErrors}.length`),(0,i.extendErrors)(e)},()=>e.error())}function l({schemaEnv:e},t){if(t.async&&!e.$async)throw Error(`async keyword in sync schema`)}function u(e,n,r){if(r===void 0)throw Error(`keyword "${n}" failed to compile`);return e.scopeValue(`keyword`,typeof r==`function`?{ref:r}:{ref:r,code:(0,t.stringify)(r)})}function d(e,t,n=!1){return!t.length||t.some(t=>t===`array`?Array.isArray(e):t===`object`?e&&typeof e==`object`&&!Array.isArray(e):typeof e==t||n&&e===void 0)}e.validSchemaType=d;function f({schema:e,opts:t,self:n,errSchemaPath:r},i,a){if(Array.isArray(i.keyword)?!i.keyword.includes(a):i.keyword!==a)throw Error(`ajv implementation error`);let o=i.dependencies;if(o?.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw Error(`parent schema must have dependencies of ${a}: ${o.join(`,`)}`);if(i.validateSchema&&!i.validateSchema(e[a])){let e=`keyword "${a}" value is invalid at path "${r}": `+n.errorsText(i.validateSchema.errors);if(t.validateSchema===`log`)n.logger.error(e);else throw Error(e)}}e.validateKeywordUsage=f})),Wk=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;var t=$(),n=Pk();function r(e,{keyword:r,schemaProp:i,schema:a,schemaPath:o,errSchemaPath:s,topSchemaRef:c}){if(r!==void 0&&a!==void 0)throw Error(`both "keyword" and "schema" passed, only one allowed`);if(r!==void 0){let a=e.schema[r];return i===void 0?{schema:a,schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${r}`}:{schema:a[i],schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}${(0,t.getProperty)(i)}`,errSchemaPath:`${e.errSchemaPath}/${r}/${(0,n.escapeFragment)(i)}`}}if(a!==void 0){if(o===void 0||s===void 0||c===void 0)throw Error(`"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"`);return{schema:a,schemaPath:o,topSchemaRef:c,errSchemaPath:s}}throw Error(`either "keyword" or "schema" must be passed`)}e.getSubschema=r;function i(e,r,{dataProp:i,dataPropType:a,data:o,dataTypes:s,propertyName:c}){if(o!==void 0&&i!==void 0)throw Error(`both "data" and "dataProp" passed, only one allowed`);let{gen:l}=r;if(i!==void 0){let{errorPath:o,dataPathArr:s,opts:c}=r;u(l.let(`data`,(0,t._)`${r.data}${(0,t.getProperty)(i)}`,!0)),e.errorPath=(0,t.str)`${o}${(0,n.getErrorPath)(i,a,c.jsPropertySyntax)}`,e.parentDataProperty=(0,t._)`${i}`,e.dataPathArr=[...s,e.parentDataProperty]}o!==void 0&&(u(o instanceof t.Name?o:l.let(`data`,o,!0)),c!==void 0&&(e.propertyName=c)),s&&(e.dataTypes=s);function u(t){e.data=t,e.dataLevel=r.dataLevel+1,e.dataTypes=[],r.definedProperties=new Set,e.parentData=r.data,e.dataNames=[...r.dataNames,t]}}e.extendSubschemaData=i;function a(e,{jtdDiscriminator:t,jtdMetadata:n,compositeRule:r,createErrors:i,allErrors:a}){r!==void 0&&(e.compositeRule=r),i!==void 0&&(e.createErrors=i),a!==void 0&&(e.allErrors=a),e.jtdDiscriminator=t,e.jtdMetadata=n}e.extendSubschemaMode=a})),Gk=E(((e,t)=>{t.exports=function e(t,n){if(t===n)return!0;if(t&&n&&typeof t==`object`&&typeof n==`object`){if(t.constructor!==n.constructor)return!1;var r,i,a;if(Array.isArray(t)){if(r=t.length,r!=n.length)return!1;for(i=r;i--!==0;)if(!e(t[i],n[i]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(a=Object.keys(t),r=a.length,r!==Object.keys(n).length)return!1;for(i=r;i--!==0;)if(!Object.prototype.hasOwnProperty.call(n,a[i]))return!1;for(i=r;i--!==0;){var o=a[i];if(!e(t[o],n[o]))return!1}return!0}return t!==t&&n!==n}})),Kk=E(((e,t)=>{var n=t.exports=function(e,t,n){typeof t==`function`&&(n=t,t={}),n=t.cb||n;var i=typeof n==`function`?n:n.pre||function(){},a=n.post||function(){};r(t,i,a,e,``,e)};n.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},n.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},n.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},n.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function r(e,t,a,o,s,c,l,u,d,f){if(o&&typeof o==`object`&&!Array.isArray(o)){for(var p in t(o,s,c,l,u,d,f),o){var m=o[p];if(Array.isArray(m)){if(p in n.arrayKeywords)for(var h=0;h<m.length;h++)r(e,t,a,m[h],s+`/`+p+`/`+h,c,s,p,o,h)}else if(p in n.propsKeywords){if(m&&typeof m==`object`)for(var g in m)r(e,t,a,m[g],s+`/`+p+`/`+i(g),c,s,p,o,g)}else(p in n.keywords||e.allKeys&&!(p in n.skipKeywords))&&r(e,t,a,m,s+`/`+p,c,s,p,o)}a(o,s,c,l,u,d,f)}}function i(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}})),qk=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;var t=Pk(),n=Gk(),r=Kk(),i=new Set([`type`,`format`,`pattern`,`maxLength`,`minLength`,`maxProperties`,`minProperties`,`maxItems`,`minItems`,`maximum`,`minimum`,`uniqueItems`,`multipleOf`,`required`,`enum`,`const`]);function a(e,t=!0){return typeof e==`boolean`?!0:t===!0?!s(e):t?c(e)<=t:!1}e.inlineRef=a;var o=new Set([`$ref`,`$recursiveRef`,`$recursiveAnchor`,`$dynamicRef`,`$dynamicAnchor`]);function s(e){for(let t in e){if(o.has(t))return!0;let n=e[t];if(Array.isArray(n)&&n.some(s)||typeof n==`object`&&s(n))return!0}return!1}function c(e){let n=0;for(let r in e)if(r===`$ref`||(n++,!i.has(r)&&(typeof e[r]==`object`&&(0,t.eachItem)(e[r],e=>n+=c(e)),n===1/0)))return 1/0;return n}function l(e,t=``,n){return n!==!1&&(t=f(t)),u(e,e.parse(t))}e.getFullPath=l;function u(e,t){return e.serialize(t).split(`#`)[0]+`#`}e._getFullPath=u;var d=/#\/?$/;function f(e){return e?e.replace(d,``):``}e.normalizeId=f;function p(e,t,n){return n=f(n),e.resolve(t,n)}e.resolveUrl=p;var m=/^[a-z_][-a-z0-9._]*$/i;function h(e,t){if(typeof e==`boolean`)return{};let{schemaId:i,uriResolver:a}=this.opts,o=f(e[i]||t),s={"":o},c=l(a,o,!1),u={},d=new Set;return r(e,{allKeys:!0},(e,t,n,r)=>{if(r===void 0)return;let a=c+t,o=s[r];typeof e[i]==`string`&&(o=l.call(this,e[i])),g.call(this,e.$anchor),g.call(this,e.$dynamicAnchor),s[t]=o;function l(t){let n=this.opts.uriResolver.resolve;if(t=f(o?n(o,t):t),d.has(t))throw h(t);d.add(t);let r=this.refs[t];return typeof r==`string`&&(r=this.refs[r]),typeof r==`object`?p(e,r.schema,t):t!==f(a)&&(t[0]===`#`?(p(e,u[t],t),u[t]=e):this.refs[t]=a),t}function g(e){if(typeof e==`string`){if(!m.test(e))throw Error(`invalid anchor "${e}"`);l.call(this,`#${e}`)}}}),u;function p(e,t,r){if(t!==void 0&&!n(e,t))throw h(r)}function h(e){return Error(`reference "${e}" resolves to more than one schema`)}}e.getSchemaRefs=h})),Jk=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;var t=Lk(),n=Bk(),r=zk(),i=Bk(),a=Vk(),o=Uk(),s=Wk(),c=$(),l=Fk(),u=qk(),d=Pk(),f=Ik();function p(e){if(ee(e)&&(te(e),x(e))){_(e);return}m(e,()=>(0,t.topBoolOrEmptySchema)(e))}e.validateFunctionCode=p;function m({gen:e,validateName:t,schema:n,schemaEnv:r,opts:i},a){i.code.es5?e.func(t,(0,c._)`${l.default.data}, ${l.default.valCxt}`,r.$async,()=>{e.code((0,c._)`"use strict"; ${y(n,i)}`),g(e,i),e.code(a)}):e.func(t,(0,c._)`${l.default.data}, ${h(i)}`,r.$async,()=>e.code(y(n,i)).code(a))}function h(e){return(0,c._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${e.dynamicRef?(0,c._)`, ${l.default.dynamicAnchors}={}`:c.nil}}={}`}function g(e,t){e.if(l.default.valCxt,()=>{e.var(l.default.instancePath,(0,c._)`${l.default.valCxt}.${l.default.instancePath}`),e.var(l.default.parentData,(0,c._)`${l.default.valCxt}.${l.default.parentData}`),e.var(l.default.parentDataProperty,(0,c._)`${l.default.valCxt}.${l.default.parentDataProperty}`),e.var(l.default.rootData,(0,c._)`${l.default.valCxt}.${l.default.rootData}`),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{e.var(l.default.instancePath,(0,c._)`""`),e.var(l.default.parentData,(0,c._)`undefined`),e.var(l.default.parentDataProperty,(0,c._)`undefined`),e.var(l.default.rootData,l.default.data),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`{}`)})}function _(e){let{schema:t,opts:n,gen:r}=e;m(e,()=>{n.$comment&&t.$comment&&oe(e),ie(e),r.let(l.default.vErrors,null),r.let(l.default.errors,0),n.unevaluated&&v(e),ne(e),w(e)})}function v(e){let{gen:t,validateName:n}=e;e.evaluated=t.const(`evaluated`,(0,c._)`${n}.evaluated`),t.if((0,c._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,c._)`${e.evaluated}.props`,(0,c._)`undefined`)),t.if((0,c._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,c._)`${e.evaluated}.items`,(0,c._)`undefined`))}function y(e,t){let n=typeof e==`object`&&e[t.schemaId];return n&&(t.code.source||t.code.process)?(0,c._)`/*# sourceURL=${n} */`:c.nil}function b(e,n){if(ee(e)&&(te(e),x(e))){S(e,n);return}(0,t.boolOrEmptySchema)(e,n)}function x({schema:e,self:t}){if(typeof e==`boolean`)return!e;for(let n in e)if(t.RULES.all[n])return!0;return!1}function ee(e){return typeof e.schema!=`boolean`}function S(e,t){let{schema:n,gen:r,opts:i}=e;i.$comment&&n.$comment&&oe(e),ae(e),C(e);let a=r.const(`_errs`,l.default.errors);ne(e,a),r.var(t,(0,c._)`${a} === ${l.default.errors}`)}function te(e){(0,d.checkUnknownRules)(e),re(e)}function ne(e,t){if(e.opts.jtd)return T(e,[],!1,t);let r=(0,n.getSchemaTypes)(e.schema);T(e,r,!(0,n.coerceAndCheckDataType)(e,r),t)}function re(e){let{schema:t,errSchemaPath:n,opts:r,self:i}=e;t.$ref&&r.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function ie(e){let{schema:t,opts:n}=e;t.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,d.checkStrictMode)(e,`default is ignored in the schema root`)}function ae(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,u.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function C(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error(`async schema in sync schema`)}function oe({gen:e,schemaEnv:t,schema:n,errSchemaPath:r,opts:i}){let a=n.$comment;if(i.$comment===!0)e.code((0,c._)`${l.default.self}.logger.log(${a})`);else if(typeof i.$comment==`function`){let n=(0,c.str)`${r}/$comment`,i=e.scopeValue(`root`,{ref:t.root});e.code((0,c._)`${l.default.self}.opts.$comment(${a}, ${n}, ${i}.schema)`)}}function w(e){let{gen:t,schemaEnv:n,validateName:r,ValidationError:i,opts:a}=e;n.$async?t.if((0,c._)`${l.default.errors} === 0`,()=>t.return(l.default.data),()=>t.throw((0,c._)`new ${i}(${l.default.vErrors})`)):(t.assign((0,c._)`${r}.errors`,l.default.vErrors),a.unevaluated&&se(e),t.return((0,c._)`${l.default.errors} === 0`))}function se({gen:e,evaluated:t,props:n,items:r}){n instanceof c.Name&&e.assign((0,c._)`${t}.props`,n),r instanceof c.Name&&e.assign((0,c._)`${t}.items`,r)}function T(e,t,n,a){let{gen:o,schema:s,data:u,allErrors:f,opts:p,self:m}=e,{RULES:h}=m;if(s.$ref&&(p.ignoreKeywordsWithRef||!(0,d.schemaHasRulesButRef)(s,h))){o.block(()=>ve(e,`$ref`,h.all.$ref.definition));return}p.jtd||le(e,t),o.block(()=>{for(let e of h.rules)g(e);g(h.post)});function g(d){(0,r.shouldUseGroup)(s,d)&&(d.type?(o.if((0,i.checkDataType)(d.type,u,p.strictNumbers)),ce(e,d),t.length===1&&t[0]===d.type&&n&&(o.else(),(0,i.reportTypeError)(e)),o.endIf()):ce(e,d),f||o.if((0,c._)`${l.default.errors} === ${a||0}`))}}function ce(e,t){let{gen:n,schema:i,opts:{useDefaults:o}}=e;o&&(0,a.assignDefaults)(e,t.type),n.block(()=>{for(let n of t.rules)(0,r.shouldUseRule)(i,n)&&ve(e,n.keyword,n.definition,t.type)})}function le(e,t){!e.schemaEnv.meta&&e.opts.strictTypes&&(ue(e,t),e.opts.allowUnionTypes||de(e,t),fe(e,e.dataTypes))}function ue(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(t=>{me(e.dataTypes,t)||ge(e,`type "${t}" not allowed by context "${e.dataTypes.join(`,`)}"`)}),he(e,t)}}function de(e,t){t.length>1&&!(t.length===2&&t.includes(`null`))&&ge(e,`use allowUnionTypes to allow union type keyword`)}function fe(e,t){let n=e.self.RULES.all;for(let i in n){let a=n[i];if(typeof a==`object`&&(0,r.shouldUseRule)(e.schema,a)){let{type:n}=a.definition;n.length&&!n.some(e=>pe(t,e))&&ge(e,`missing type "${n.join(`,`)}" for keyword "${i}"`)}}}function pe(e,t){return e.includes(t)||t===`number`&&e.includes(`integer`)}function me(e,t){return e.includes(t)||t===`integer`&&e.includes(`number`)}function he(e,t){let n=[];for(let r of e.dataTypes)me(t,r)?n.push(r):t.includes(`integer`)&&r===`number`&&n.push(`integer`);e.dataTypes=n}function ge(e,t){let n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,d.checkStrictMode)(e,t,e.opts.strictTypes)}var _e=class{constructor(e,t,n){if((0,o.validateKeywordUsage)(e,t,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,d.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const(`vSchema`,xe(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,o.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);(`code`in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const(`_errs`,l.default.errors))}result(e,t,n){this.failResult((0,c.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,c.not)(e),void 0,t)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail((0,c._)`${t} !== undefined && (${(0,c.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t){this.setParams(t),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,t){(e?f.reportExtraError:f.reportError)(this,this.def.error,t)}$dataError(){(0,f.reportError)(this,this.def.$dataError||f.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error(`add "trackErrors" to keyword definition`);(0,f.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=c.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=c.nil,t=c.nil){if(!this.$data)return;let{gen:n,schemaCode:r,schemaType:i,def:a}=this;n.if((0,c.or)((0,c._)`${r} === undefined`,t)),e!==c.nil&&n.assign(e,!0),(i.length||a.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==c.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:r,it:a}=this;return(0,c.or)(o(),s());function o(){if(n.length){if(!(t instanceof c.Name))throw Error(`ajv implementation error`);let e=Array.isArray(n)?n:[n];return(0,c._)`${(0,i.checkDataTypes)(e,t,a.opts.strictNumbers,i.DataType.Wrong)}`}return c.nil}function s(){if(r.validateSchema){let n=e.scopeValue(`validate$data`,{ref:r.validateSchema});return(0,c._)`!${n}(${t})`}return c.nil}}subschema(e,t){let n=(0,s.getSubschema)(this.it,e);(0,s.extendSubschemaData)(n,this.it,e),(0,s.extendSubschemaMode)(n,e);let r={...this.it,...n,items:void 0,props:void 0};return b(r,t),r}mergeEvaluated(e,t){let{it:n,gen:r}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=d.mergeEvaluated.props(r,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=d.mergeEvaluated.items(r,e.items,n.items,t)))}mergeValidEvaluated(e,t){let{it:n,gen:r}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return r.if(t,()=>this.mergeEvaluated(e,c.Name)),!0}};e.KeywordCxt=_e;function ve(e,t,n,r){let i=new _e(e,n,t);`code`in n?n.code(i,r):i.$data&&n.validate?(0,o.funcKeywordCode)(i,n):`macro`in n?(0,o.macroKeywordCode)(i,n):(n.compile||n.validate)&&(0,o.funcKeywordCode)(i,n)}var ye=/^\/(?:[^~]|~0|~1)*$/,be=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function xe(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let i,a;if(e===``)return l.default.rootData;if(e[0]===`/`){if(!ye.test(e))throw Error(`Invalid JSON-pointer: ${e}`);i=e,a=l.default.rootData}else{let o=be.exec(e);if(!o)throw Error(`Invalid JSON-pointer: ${e}`);let s=+o[1];if(i=o[2],i===`#`){if(s>=t)throw Error(u(`property/index`,s));return r[t-s]}if(s>t)throw Error(u(`data`,s));if(a=n[t-s],!i)return a}let o=a,s=i.split(`/`);for(let e of s)e&&(a=(0,c._)`${a}${(0,c.getProperty)((0,d.unescapeJsonPointer)(e))}`,o=(0,c._)`${o} && ${a}`);return o;function u(e,n){return`Cannot access ${e} ${n} levels up, current level is ${t}`}}e.getData=xe})),Yk=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=class extends Error{constructor(e){super(`validation failed`),this.errors=e,this.ajv=this.validation=!0}}})),Xk=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=qk();e.default=class extends Error{constructor(e,n,r,i){super(i||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,t.resolveUrl)(e,n,r),this.missingSchema=(0,t.normalizeId)((0,t.getFullPath)(e,this.missingRef))}}})),Zk=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;var t=$(),n=Yk(),r=Fk(),i=qk(),a=Pk(),o=Jk(),s=class{constructor(e){this.refs={},this.dynamicAnchors={};let t;typeof e.schema==`object`&&(t=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=e.baseId??(0,i.normalizeId)(t?.[e.schemaId||`$id`]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=t?.$async,this.refs={}}};e.SchemaEnv=s;function c(e){let a=d.call(this,e);if(a)return a;let s=(0,i.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:c,lines:l}=this.opts.code,{ownProperties:u}=this.opts,f=new t.CodeGen(this.scope,{es5:c,lines:l,ownProperties:u}),p;e.$async&&(p=f.scopeValue(`Error`,{ref:n.default,code:(0,t._)`require("ajv/dist/runtime/validation_error").default`}));let m=f.scopeName(`validate`);e.validateName=m;let h={gen:f,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[t.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:f.scopeValue(`schema`,this.opts.code.source===!0?{ref:e.schema,code:(0,t.stringify)(e.schema)}:{ref:e.schema}),validateName:m,ValidationError:p,schema:e.schema,schemaEnv:e,rootId:s,baseId:e.baseId||s,schemaPath:t.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?``:`#`),errorPath:(0,t._)`""`,opts:this.opts,self:this},g;try{this._compilations.add(e),(0,o.validateFunctionCode)(h),f.optimize(this.opts.code.optimize);let n=f.toString();g=`${f.scopeRefs(r.default.scope)}return ${n}`,this.opts.code.process&&(g=this.opts.code.process(g,e));let i=Function(`${r.default.self}`,`${r.default.scope}`,g)(this,this.scope.get());if(this.scope.value(m,{ref:i}),i.errors=null,i.schema=e.schema,i.schemaEnv=e,e.$async&&(i.$async=!0),this.opts.code.source===!0&&(i.source={validateName:m,validateCode:n,scopeValues:f._values}),this.opts.unevaluated){let{props:e,items:n}=h;i.evaluated={props:e instanceof t.Name?void 0:e,items:n instanceof t.Name?void 0:n,dynamicProps:e instanceof t.Name,dynamicItems:n instanceof t.Name},i.source&&(i.source.evaluated=(0,t.stringify)(i.evaluated))}return e.validate=i,e}catch(t){throw delete e.validate,delete e.validateName,g&&this.logger.error(`Error compiling schema, function code:`,g),t}finally{this._compilations.delete(e)}}e.compileSchema=c;function l(e,t,n){n=(0,i.resolveUrl)(this.opts.uriResolver,t,n);let r=e.refs[n];if(r)return r;let a=p.call(this,e,n);if(a===void 0){let r=e.localRefs?.[n],{schemaId:i}=this.opts;r&&(a=new s({schema:r,schemaId:i,root:e,baseId:t}))}if(a!==void 0)return e.refs[n]=u.call(this,a)}e.resolveRef=l;function u(e){return(0,i.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:c.call(this,e)}function d(e){for(let t of this._compilations)if(f(t,e))return t}e.getCompilingSchema=d;function f(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function p(e,t){let n;for(;typeof(n=this.refs[t])==`string`;)t=n;return n||this.schemas[t]||m.call(this,e,t)}function m(e,t){let n=this.opts.uriResolver.parse(t),r=(0,i._getFullPath)(this.opts.uriResolver,n),a=(0,i.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&r===a)return g.call(this,n,e);let o=(0,i.normalizeId)(r),l=this.refs[o]||this.schemas[o];if(typeof l==`string`){let t=m.call(this,e,l);return typeof t?.schema==`object`?g.call(this,n,t):void 0}if(typeof l?.schema==`object`){if(l.validate||c.call(this,l),o===(0,i.normalizeId)(t)){let{schema:t}=l,{schemaId:n}=this.opts,r=t[n];return r&&(a=(0,i.resolveUrl)(this.opts.uriResolver,a,r)),new s({schema:t,schemaId:n,root:e,baseId:a})}return g.call(this,n,l)}}e.resolveSchema=m;var h=new Set([`properties`,`patternProperties`,`enum`,`dependencies`,`definitions`]);function g(e,{baseId:t,schema:n,root:r}){if(e.fragment?.[0]!==`/`)return;for(let r of e.fragment.slice(1).split(`/`)){if(typeof n==`boolean`)return;let e=n[(0,a.unescapeFragment)(r)];if(e===void 0)return;n=e;let o=typeof n==`object`&&n[this.opts.schemaId];!h.has(r)&&o&&(t=(0,i.resolveUrl)(this.opts.uriResolver,t,o))}let o;if(typeof n!=`boolean`&&n.$ref&&!(0,a.schemaHasRulesButRef)(n,this.RULES)){let e=(0,i.resolveUrl)(this.opts.uriResolver,t,n.$ref);o=m.call(this,r,e)}let{schemaId:c}=this.opts;if(o||=new s({schema:n,schemaId:c,root:r,baseId:t}),o.schema!==o.root.schema)return o}})),Qk=Oe({$id:()=>$k,additionalProperties:()=>!1,default:()=>iA,description:()=>eA,properties:()=>rA,required:()=>nA,type:()=>tA}),$k,eA,tA,nA,rA,iA,aA=De((()=>{$k=`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`,eA=`Meta-schema for $data reference (JSON AnySchema extension proposal)`,tA=`object`,nA=[`$data`],rA={$data:{type:`string`,anyOf:[{format:`relative-json-pointer`},{format:`json-pointer`}]}},iA={$id:$k,description:eA,type:tA,required:nA,properties:rA,additionalProperties:!1}})),oA=E(((e,t)=>{var n=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),r=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),i=RegExp.prototype.test.bind(/^\d*$/u),a=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),o=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),s=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),c=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),l=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),u=Array(256);{let e=`0123456789ABCDEF`;for(let t=0;t<256;t++)u[t]=`%`+e[t>>4]+e[t&15]}function d(e){return e<2048?u[192|e>>6]+u[128|e&63]:e<65536?u[224|e>>12]+u[128|e>>6&63]+u[128|e&63]:u[240|e>>18]+u[128|e>>12&63]+u[128|e>>6&63]+u[128|e&63]}function f(e){let t=``,n=0,r=0;for(r=0;r<e.length;r++)if(n=e[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r];break}for(r+=1;r<e.length;r++){if(n=e[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r]}return t}var p=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),m=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),h=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),g=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function _(e){if(e.length===0)return!1;for(let t=0;t<e.length;t++)if(!h(e[t])){if(e[t]===`%`&&t+2<e.length&&a(e.slice(t+1,t+3))){t+=2;continue}return!1}return!0}function v(e){let t=-1,n=0,r=-1,i=0;for(let a=0;a<e.length;a++)e[a]===`0`?(r===-1&&(r=a),i++,i>n&&(n=i,t=r)):(r=-1,i=0);if(n<2)return e.join(`:`);let a=e.slice(0,t).join(`:`),o=e.slice(t+n).join(`:`);return a+`::`+o}function y(e){let t=e.indexOf(`::`);if(t!==-1&&e.indexOf(`::`,t+1)!==-1)return;let n=t===-1?e.split(`:`):e.slice(0,t).split(`:`),i=t===-1?[]:e.slice(t+2).split(`:`);t!==-1&&(n.length===1&&n[0]===``&&(n.length=0),i.length===1&&i[0]===``&&(i.length=0));let a=n.concat(i),o=0;for(let e=0;e<a.length;e++){let n=a[e];if(n===``)return;if(n.indexOf(`.`)!==-1){if(e!==a.length-1||t!==-1&&i.length===0||!r(n))return;o+=2;continue}if(!p(n))return;a[e]=parseInt(n,16).toString(16),o++}if(t===-1)return o===8?v(a):void 0;if(o>=8)return;let s=a.slice(0,n.length);for(let e=o;e<8;e++)s.push(`0`);for(let e=n.length;e<a.length;e++)s.push(a[e]);return v(s)}function b(e){let t=e[0]===`[`&&e[e.length-1]===`]`;if((e[0]===`[`||e[e.length-1]===`]`)&&!t)return{host:e,isIPV6:!1,error:!0};let n=t?e.slice(1,-1):e;if(t&&m(n))return n=n.toLowerCase(),{host:`[${n}]`,escapedHost:n,isIPV6:!1,isIPVFuture:!0};if(x(n,`:`)<2)return{host:e,isIPV6:!1,error:t};let r=``,i=n.indexOf(`%`);if(i!==-1){let t=n.slice(i,i+3).toLowerCase()===`%25`?3:1;if(r=n.slice(i+t),!_(r))return{host:e,isIPV6:!1,error:!0};n=n.slice(0,i)}let a=y(n);return a===void 0?{host:e,isIPV6:!1,error:!0}:{host:a+(r?`%`+r:``),escapedHost:a+(r?`%25`+r:``),isIPV6:!0}}function x(e,t){let n=0;for(let r=0;r<e.length;r++)e[r]===t&&n++;return n}function ee(e){let t=e,n=[],r=-1,i=0;for(;i=t.length;){if(i===1){if(t===`.`)break;if(t===`/`){n.push(`/`);break}n.push(t);break}if(i===2){if(t[0]===`.`){if(t[1]===`.`)break;if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&(t[1]===`.`||t[1]===`/`)){n.push(`/`);break}}else if(i===3&&t===`/..`){n.length!==0&&n.pop(),n.push(`/`);break}if(t[0]===`.`){if(t[1]===`.`){if(t[2]===`/`){t=t.slice(3);continue}}else if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&t[1]===`.`){if(t[2]===`/`){t=t.slice(2);continue}if(t[2]===`.`&&t[3]===`/`){t=t.slice(3),n.length!==0&&n.pop();continue}}if((r=t.indexOf(`/`,1))===-1){n.push(t);break}n.push(t.slice(0,r)),t=t.slice(r)}return n.join(``)}var S={"@":`%40`,"/":`%2F`,"?":`%3F`,"#":`%23`,":":`%3A`},te=/[@/?#:]/g,ne=/[@/?#]/g;function re(e,t){let n=t?ne:te;return n.lastIndex=0,e.replace(n,e=>S[e])}function ie(e,t=!1){if(e.indexOf(`%`)===-1)return e;let n=``;for(let r=0;r<e.length;r++){if(e[r]===`%`&&r+2<e.length){let i=e.slice(r+1,r+3);if(a(i)){let e=i.toUpperCase(),a=String.fromCharCode(parseInt(e,16));t&&o(a)?n+=a:n+=`%`+e,r+=2;continue}}n+=e[r]}return n}function ae(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(r===`%`&&n+2<e.length){let r=e.slice(n+1,n+3);if(a(r)){let e=r.toUpperCase(),i=String.fromCharCode(parseInt(e,16));i!==`.`&&o(i)?t+=i:t+=`%`+e,n+=2;continue}}if(s(r))t+=r;else{let i=e.charCodeAt(n);if(i<128)t+=ce(i)?r:u[i];else if(i<55296||i>57343)t+=d(i);else if(i<=56319&&n+1<e.length){let r=e.charCodeAt(n+1);r>=56320&&r<=57343?(t+=d(65536+(i-55296<<10)+(r-56320)),n++):t+=d(65533)}else t+=d(65533)}}return t}function C(e,t=!1){let n=``,r=t&&e[0]!==`/`;for(let t=0;t<e.length;t++){let i=e[t];if(i===`%`&&t+2<e.length){let r=e.slice(t+1,t+3);if(a(r)){n+=`%`+r.toUpperCase(),t+=2;continue}}if(i===`/`&&(r=!1),s(i)&&(i!==`:`||!r))n+=i;else{let r=e.charCodeAt(t);if(r<128)n+=u[r];else if(r<55296||r>57343)n+=d(r);else if(r<=56319&&t+1<e.length){let i=e.charCodeAt(t+1);i>=56320&&i<=57343?(n+=d(65536+(r-55296<<10)+(i-56320)),t++):n+=d(65533)}else n+=d(65533)}}return n}function oe(e,t){let n=``;for(let r=0;r<e.length;r++){let i=e[r];if(i===`%`&&r+2<e.length){let t=e.slice(r+1,r+3);if(a(t)){n+=`%`+t.toUpperCase(),r+=2;continue}}if(t(i))n+=i;else{let t=e.charCodeAt(r);if(t<128)n+=u[t];else if(t<55296||t>57343)n+=d(t);else if(t<=56319&&r+1<e.length){let i=e.charCodeAt(r+1);i>=56320&&i<=57343?(n+=d(65536+(t-55296<<10)+(i-56320)),r++):n+=d(65533)}else n+=d(65533)}}return n}function w(e){return oe(e,l)}function se(e){return oe(e,c)}function T(e){return oe(e,c)}function ce(e){return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===42||e===43||e===45||e===46||e===47||e===64||e===95}function le(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(r===`%`&&n+2<e.length){let r=e.slice(n+1,n+3);if(a(r)){let e=r.toUpperCase(),i=String.fromCharCode(parseInt(e,16));o(i)?t+=i:t+=`%`+e,n+=2;continue}}if(c(r))t+=r;else{let i=e.charCodeAt(n);if(i<128)t+=ce(i)?r:u[i];else if(i<55296||i>57343)t+=d(i);else if(i<=56319&&n+1<e.length){let r=e.charCodeAt(n+1);r>=56320&&r<=57343?(t+=d(65536+(i-55296<<10)+(r-56320)),n++):t+=d(65533)}else t+=d(65533)}}return t}function ue(e){let t=``;for(let n=0;n<e.length;n++){if(e[n]===`%`&&n+2<e.length){let r=e.slice(n+1,n+3);if(a(r)){t+=`%`+r.toUpperCase(),n+=2;continue}}t+=escape(e[n])}return t}function de(e){let t=[];if(e.userinfo!==void 0&&(t.push(w(e.userinfo)),t.push(`@`)),e.host!==void 0){let n=e.host;if(!r(n)){let e=b(n);e.isIPV6!==!0&&e.isIPVFuture!==!0&&(n=ie(n,!0),e=b(n)),n=e.isIPV6===!0||e.isIPVFuture===!0?`[${e.escapedHost}]`:re(n,!1)}t.push(n)}if(typeof e.port==`number`||typeof e.port==`string`){let n=String(e.port);if(!i(n))throw TypeError(`URI port is malformed.`);t.push(`:`),t.push(n)}return t.length?t.join(``):void 0}t.exports={nonSimpleDomain:g,recomposeAuthority:de,reescapeHostDelimiters:re,normalizePercentEncoding:ie,normalizePathEncoding:ae,serializePathEncoding:C,normalizeQueryFragmentEncoding:le,encodeUserinfo:w,encodeQuery:se,encodeFragment:T,escapePreservingEscapes:ue,removeDotSegments:ee,isIPv4:r,isUUID:n,normalizeIPv6:b,stringArrayToHexStripped:f}})),sA=E(((e,t)=>{var{isUUID:n}=oA(),r=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,i=[`http`,`https`,`ws`,`wss`,`urn`,`urn:uuid`];function a(e){return i.indexOf(e)!==-1}function o(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]===`w`||e.scheme[0]===`W`)&&(e.scheme[1]===`s`||e.scheme[1]===`S`)&&(e.scheme[2]===`s`||e.scheme[2]===`S`):!1}function s(e){return e.host||(e.error=e.error||`HTTP URIs must have a host.`),e}function c(e){let t=String(e.scheme).toLowerCase()===`https`;return(e.port===(t?443:80)||e.port===``)&&(e.port=void 0),e.path||=`/`,e}function l(e){return e.secure=o(e),e.resourceName=(e.path||`/`)+(e.query?`?`+e.query:``),e.path=void 0,e.query=void 0,e}function u(e){if((e.port===(o(e)?443:80)||e.port===``)&&(e.port=void 0),typeof e.secure==`boolean`&&(e.scheme=e.secure?`wss`:`ws`,e.secure=void 0),e.resourceName){let t=e.resourceName.indexOf(`?`),n=t===-1?e.resourceName:e.resourceName.slice(0,t);e.path=n&&n!==`/`?n:void 0,e.query=t===-1?void 0:e.resourceName.slice(t+1),e.resourceName=void 0}return e.fragment=void 0,e}function d(e,t){if(!e.path)return e.error=`URN can not be parsed`,e;let n=e.path.match(r);if(n&&n[0]===e.path){let r=t.scheme||e.scheme||`urn`;e.nid=n[1].toLowerCase(),e.nss=n[2];let i=y(`${r}:${t.nid||e.nid}`);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||`URN can not be parsed.`;return e}function f(e,t){if(e.nid===void 0)throw Error(`URN without nid cannot be serialized`);let n=t.scheme||e.scheme||`urn`,r=e.nid.toLowerCase(),i=y(`${n}:${t.nid||r}`);i&&(e=i.serialize(e,t));let a=e,o=e.nss;return a.path=`${r||t.nid}:${o}`,t.skipEscape=!0,a}function p(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!n(r.uuid))&&(r.error=r.error||`UUID is not valid.`),r}function m(e){let t=e;return t.nss=(e.uuid||``).toLowerCase(),t}var h={scheme:`http`,domainHost:!0,parse:s,serialize:c},g={scheme:`https`,domainHost:h.domainHost,parse:s,serialize:c},_={scheme:`ws`,domainHost:!0,parse:l,serialize:u},v={http:h,https:g,ws:_,wss:{scheme:`wss`,domainHost:_.domainHost,parse:_.parse,serialize:_.serialize},urn:{scheme:`urn`,parse:d,serialize:f,skipNormalize:!0},"urn:uuid":{scheme:`urn:uuid`,parse:p,serialize:m,skipNormalize:!0}};Object.setPrototypeOf(v,null);function y(e){return e&&(v[e]||v[e.toLowerCase()])||void 0}t.exports={wsIsSecure:o,SCHEMES:v,isValidSchemeName:a,getSchemeHandler:y}})),cA=E(((e,t)=>{var{normalizeIPv6:n,removeDotSegments:r,recomposeAuthority:i,normalizePercentEncoding:a,normalizePathEncoding:o,serializePathEncoding:s,normalizeQueryFragmentEncoding:c,encodeQuery:l,encodeFragment:u,reescapeHostDelimiters:d,isIPv4:f,nonSimpleDomain:p}=oA(),{SCHEMES:m,getSchemeHandler:h}=sA(),g=/^[A-Za-z][A-Za-z0-9+.-]*$/u,_=`URI scheme is malformed.`;function v(e){let t=unescape(String(e));if(!g.test(t))throw TypeError(_);return t}function y(e,t){return typeof e==`string`?e=ce(e,t):typeof e==`object`&&(e=T(S(e,t),t)),e}function b(e,t,r){let i=r?Object.assign({scheme:`null`},r):{scheme:`null`},{parsed:a,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:c,malformedHost:l,malformedScheme:u}=se(e,i),{parsed:d,malformedAuthorityOrPort:p,malformedPercentEncoding:m,malformedSchemeSpecific:g,malformedHost:_,malformedScheme:v}=se(t,i);if(o||p||s||m||c||g||l||_||u||v)throw Error(a.error||d.error||`URI is malformed.`);let y=x(a,d,i,!0),b=h(r&&r.scheme||y.scheme),ee=y.host,te=ee!==void 0&&ee!==``&&(f(ee)||n(ee).isIPV6);w(y,r||{},b,te);let ne=ee&&ee.indexOf(`%`)!==-1&&!/\P{ASCII}/u.test(ee);if(y.error&&!ne)throw Error(y.error);return i.skipEscape=!0,S(y,i)}function x(e,t,n,i){let a={};return i||(e=T(S(e,n),n),t=T(S(t,n),n)),n||={},!n.tolerant&&t.scheme?(a.scheme=t.scheme,a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.path?(t.path[0]===`/`?a.path=r(t.path):(a.path=(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?`/`+t.path:e.path?e.path.slice(0,e.path.lastIndexOf(`/`)+1)+t.path:t.path,a.path=r(a.path)),a.query=t.query):(a.path=e.path,a.query=t.query===void 0?e.query:t.query),a.userinfo=e.userinfo,a.host=e.host,a.port=e.port),a.scheme=e.scheme),a.fragment=t.fragment,a}function ee(e,t,n){let r=ue(e,n),i=ue(t,n);return r!==void 0&&i!==void 0&&r===i}function S(e,t){let n={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:``},o=Object.assign({},t),c=[];n.scheme&&=v(n.scheme);let d=h(o.scheme||n.scheme);d&&d.serialize&&d.serialize(n,o);let f=n.userinfo!==void 0||n.host!==void 0||n.port!==void 0,p=!o.skipEscape&&n.scheme===void 0&&!f;n.path!==void 0&&(n.path=o.skipEscape?a(n.path):s(n.path,p)),o.reference!==`suffix`&&n.scheme&&(n.scheme=v(n.scheme),c.push(n.scheme,`:`));let m=i(n);if(m!==void 0&&(o.reference!==`suffix`&&c.push(`//`),c.push(m),n.path&&n.path[0]!==`/`&&c.push(`/`)),n.path!==void 0){let e=n.path;!o.absolutePath&&(!d||!d.absolutePath)&&(e=r(e)),p&&(e=s(e,!0)),m===void 0&&e[0]===`/`&&e[1]===`/`&&(e=`/%2F`+e.slice(2)),c.push(e)}return n.query!==void 0&&c.push(`?`,l(n.query)),n.fragment!==void 0&&c.push(`#`,u(n.fragment)),c.join(``)}var te=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,ne=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,re=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function ie(e,t){if(t[2]!==void 0&&e.path&&e.path[0]!==`/`)return`URI path must start with "/" when authority is present.`;if(typeof e.port==`number`&&(e.port<0||e.port>65535))return`URI port is malformed.`}function ae(e){if(e===void 0)return!1;let t=e.indexOf(`%`);for(;t!==-1;){if(t+2>=e.length||!/^[\da-f]{2}$/iu.test(e.slice(t+1,t+3)))return!0;t=e.indexOf(`%`,t+3)}return!1}function C(e){return e[0]===`[`&&e[e.length-1]===`]`}function oe(e){let t=e[4];return ae(e[3])||t!==void 0&&!C(t)&&ae(t)||ae(e[6])||ae(e[7])||ae(e[8])}function w(e,t,n,r){if(!t.unicodeSupport&&(!n||!n.unicodeSupport)&&e.host&&!C(e.host)&&(t.domainHost||n&&n.domainHost)&&r===!1&&p(e.host))try{e.host=new URL(`http://`+e.host).hostname}catch(t){return e.error=e.error||`Host's domain name can not be converted to ASCII: `+t,!0}return!1}function se(e,t){let r=Object.assign({},t),i={scheme:void 0,userinfo:void 0,host:``,port:void 0,path:``,query:void 0,fragment:void 0},s=!1,l=!1,u=!1,p=!1,v=!1,y=!1,b=!1;r.reference===`suffix`&&(e=r.scheme?r.scheme+`:`+e:`//`+e);let x=e.match(ne);x!==null&&x[1].indexOf(`\\`)!==-1&&(i.error=`URI authority must not contain a literal backslash.`,s=!0);let ee=e.match(re);if(ee!==null){let e=ee[1],t=e.replace(/[\t\n\r]/g,``);t.length>=2&&(t.slice(0,2)===`//`?e.length!==t.length&&(i.error=i.error||`URI authority introducer must not contain whitespace.`,s=!0):(i.error=i.error||`URI authority must not contain a literal backslash.`,s=!0))}let S=e.match(te);if(S){if(i.scheme=S[1],i.userinfo=S[3],i.host=S[4],i.port=parseInt(S[5],10),i.path=S[6]||``,i.query=S[7],i.fragment=S[8],i.scheme!==void 0){let e=unescape(i.scheme);g.test(e)?i.scheme=e.toLowerCase():(i.error=i.error||_,y=!0)}l=oe(S),l&&(i.error=i.error||`URI contains malformed percent-encoding.`),isNaN(i.port)&&(i.port=S[5]);let t=ie(i,S);if(t!==void 0&&(i.error=i.error||t,s=!0),i.host){if(f(i.host)===!1){let e=C(i.host),t=i.host.indexOf(`[`)!==-1||i.host.indexOf(`]`)!==-1,r=n(i.host);b=r.isIPV6||r.isIPVFuture===!0,v=t&&(!e||r.error===!0),i.host=b?r.host:r.host.toLowerCase(),v&&(i.error=i.error||`URI host is malformed.`,s=!0)}else b=!0}i.reference=i.scheme===void 0&&i.userinfo===void 0&&i.host===void 0&&i.port===void 0&&i.query===void 0&&!i.path?`same-document`:i.scheme===void 0?`relative`:i.fragment===void 0?`absolute`:`uri`,r.reference&&r.reference!==`suffix`&&r.reference!==i.reference&&(i.error=i.error||`URI is not a `+r.reference+` reference.`);let x=h(r.scheme||i.scheme);if(v||(p=w(i,r,x,b)),e.indexOf(`%`)!==-1&&i.host!==void 0&&!v){let e=b?i.host:a(i.host,!0);b||(e=a(e.toLowerCase())),i.host=d(e,b)}(!x||x&&!x.skipNormalize)&&(i.path&&=o(i.path),i.query&&=c(i.query),i.fragment&&=c(i.fragment)),x&&x.parse&&(x.parse(i,r),x===m.urn&&i.nid===void 0&&(u=!0))}else i.error=i.error||`URI can not be parsed.`;return{parsed:i,malformedAuthorityOrPort:s,malformedPercentEncoding:l,malformedSchemeSpecific:u,malformedHost:p,malformedScheme:y}}function T(e,t){return se(e,t).parsed}function ce(e,t){return le(e,t).normalized}function le(e,t){let{parsed:n,malformedAuthorityOrPort:r,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:o,malformedScheme:s}=se(e,t);return{normalized:r||i||a||o||s?e:S(n,t),malformedAuthorityOrPort:r,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:o,malformedScheme:s}}function ue(e,t){if(typeof e!=`string`&&typeof e!=`object`)return;let n;try{n=typeof e==`string`?e:S(e,t)}catch{return}let{normalized:r,malformedAuthorityOrPort:i,malformedPercentEncoding:a,malformedSchemeSpecific:o,malformedHost:s,malformedScheme:c}=le(n,t);return i||a||o||s||c?void 0:r}var de={SCHEMES:m,normalize:y,resolve:b,resolveComponent:x,equal:ee,serialize:S,parse:T};t.exports=de,t.exports.default=de,t.exports.fastUri=de})),lA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=cA();t.code=`require("ajv/dist/runtime/uri").default`,e.default=t})),uA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=Jk();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var n=$();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return n.CodeGen}});var r=Yk(),i=Xk(),a=Rk(),o=Zk(),s=$(),c=qk(),l=Bk(),u=Pk(),d=(aA(),je(Qk).default),f=lA(),p=(e,t)=>new RegExp(e,t);p.code=`new RegExp`;var m=[`removeAdditional`,`useDefaults`,`coerceTypes`],h=new Set([`validate`,`serialize`,`parse`,`wrapper`,`root`,`schema`,`keyword`,`pattern`,`formats`,`validate$data`,`func`,`obj`,`Error`]),g={errorDataPath:``,format:"`validateFormats: false` can be used instead.",nullable:`"nullable" keyword is supported by default.`,jsonPointers:`Deprecated jsPropertySyntax can be used instead.`,extendRefs:`Deprecated ignoreKeywordsWithRef can be used instead.`,missingRefs:`Pass empty schema with $id that should be ignored to ajv.addSchema.`,processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:`"uniqueItems" keyword is always validated.`,unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:`Map is used as cache, schema object as key.`,serialize:`Map is used as cache, schema object as key.`,ajvErrors:`It is default now.`},_={ignoreKeywordsWithRef:``,jsPropertySyntax:``,unicode:`"minLength"/"maxLength" account for unicode characters by default.`},v=200;function y(e){let t=e.strict,n=e.code?.optimize,r=n===!0||n===void 0?1:n||0,i=e.code?.regExp??p,a=e.uriResolver??f.default;return{strictSchema:e.strictSchema??t??!0,strictNumbers:e.strictNumbers??t??!0,strictTypes:e.strictTypes??t??`log`,strictTuples:e.strictTuples??t??`log`,strictRequired:e.strictRequired??t??!1,code:e.code?{...e.code,optimize:r,regExp:i}:{optimize:r,regExp:i},loopRequired:e.loopRequired??v,loopEnum:e.loopEnum??v,meta:e.meta??!0,messages:e.messages??!0,inlineRefs:e.inlineRefs??!0,schemaId:e.schemaId??`$id`,addUsedSchema:e.addUsedSchema??!0,validateSchema:e.validateSchema??!0,validateFormats:e.validateFormats??!0,unicodeRegExp:e.unicodeRegExp??!0,int32range:e.int32range??!0,uriResolver:a}}var b=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...y(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new s.ValueScope({scope:{},prefixes:h,es5:t,lines:n}),this.logger=ae(e.logger);let r=e.validateFormats;e.validateFormats=!1,this.RULES=(0,a.getRules)(),x.call(this,g,e,`NOT SUPPORTED`),x.call(this,_,e,`DEPRECATED`,`warn`),this._metaOpts=re.call(this),e.formats&&te.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&ne.call(this,e.keywords),typeof e.meta==`object`&&this.addMetaSchema(e.meta),S.call(this),e.validateFormats=r}_addVocabularies(){this.addKeyword(`$async`)}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,r=d;n===`id`&&(r={...d},r.id=r.$id,delete r.$id),t&&e&&this.addMetaSchema(r,r[n],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e==`object`?e[t]||e:void 0}validate(e,t){let n;if(typeof e==`string`){if(n=this.getSchema(e),!n)throw Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let r=n(t);return`$async`in n||(this.errors=n.errors),r}compile(e,t){let n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if(typeof this.opts.loadSchema!=`function`)throw Error(`options.loadSchema should be a function`);let{loadSchema:n}=this.opts;return r.call(this,e,t);async function r(e,t){await a.call(this,e.$schema);let n=this._addSchema(e,t);return n.validate||o.call(this,n)}async function a(e){e&&!this.getSchema(e)&&await r.call(this,{$ref:e},!0)}async function o(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof i.default))throw t;return s.call(this,t),await c.call(this,t.missingSchema),o.call(this,e)}}function s({missingSchema:e,missingRef:t}){if(this.refs[e])throw Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function c(e){let n=await l.call(this,e);this.refs[e]||await a.call(this,n.$schema),this.refs[e]||this.addSchema(n,e,t)}async function l(e){let t=this._loading[e];if(t)return t;try{return await(this._loading[e]=n(e))}finally{delete this._loading[e]}}}addSchema(e,t,n,r=this.opts.validateSchema){if(Array.isArray(e)){for(let t of e)this.addSchema(t,void 0,n,r);return this}let i;if(typeof e==`object`){let{schemaId:t}=this.opts;if(i=e[t],i!==void 0&&typeof i!=`string`)throw Error(`schema ${t} must be string`)}return t=(0,c.normalizeId)(t||i),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,r,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if(typeof e==`boolean`)return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!=`string`)throw Error(`$schema must be a string`);if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn(`meta-schema not available`),this.errors=null,!0;let r=this.validate(n,e);if(!r&&t){let e=`schema is invalid: `+this.errorsText();if(this.opts.validateSchema===`log`)this.logger.error(e);else throw Error(e)}return r}getSchema(e){let t;for(;typeof(t=ee.call(this,e))==`string`;)e=t;if(t===void 0){let{schemaId:n}=this.opts,r=new o.SchemaEnv({schema:{},schemaId:n});if(t=o.resolveSchema.call(this,r,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case`undefined`:return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case`string`:{let t=ee.call(this,e);return typeof t==`object`&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case`object`:{let t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,c.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw Error(`ajv.removeSchema: invalid parameter`)}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if(typeof e==`string`)n=e,typeof t==`object`&&(this.logger.warn(`these parameters are deprecated, see docs for addKeyword`),t.keyword=n);else if(typeof e==`object`&&t===void 0){if(t=e,n=t.keyword,Array.isArray(n)&&!n.length)throw Error(`addKeywords: keyword must be string or non-empty array`)}else throw Error(`invalid addKeywords parameters`);if(oe.call(this,n,t),!t)return(0,u.eachItem)(n,e=>w.call(this,e)),this;T.call(this,t);let r={...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)};return(0,u.eachItem)(n,r.type.length===0?e=>w.call(this,e,r):e=>r.type.forEach(t=>w.call(this,e,r,t))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t==`object`?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let n of t.rules){let t=n.rules.findIndex(t=>t.keyword===e);t>=0&&n.rules.splice(t,1)}return this}addFormat(e,t){return typeof t==`string`&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=`, `,dataVar:n=`data`}={}){return!e||e.length===0?`No errors`:e.map(e=>`${n}${e.instancePath} ${e.message}`).reduce((e,n)=>e+t+n)}$dataMetaSchema(e,t){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let r of t){let t=r.split(`/`).slice(1),i=e;for(let e of t)i=i[e];for(let e in n){let t=n[e];if(typeof t!=`object`)continue;let{$data:r}=t.definition,a=i[e];r&&a&&(i[e]=le(a))}}return e}_removeAllSchemas(e,t){for(let n in e){let r=e[n];(!t||t.test(n))&&(typeof r==`string`?delete e[n]:r&&!r.meta&&(this._cache.delete(r.schema),delete e[n]))}}_addSchema(e,t,n,r=this.opts.validateSchema,i=this.opts.addUsedSchema){let a,{schemaId:s}=this.opts;if(typeof e==`object`)a=e[s];else if(this.opts.jtd)throw Error(`schema must be object`);else if(typeof e!=`boolean`)throw Error(`schema must be object or boolean`);let l=this._cache.get(e);if(l!==void 0)return l;n=(0,c.normalizeId)(a||n);let u=c.getSchemaRefs.call(this,e,n);return l=new o.SchemaEnv({schema:e,schemaId:s,meta:t,baseId:n,localRefs:u}),this._cache.set(l.schema,l),i&&!n.startsWith(`#`)&&(n&&this._checkUnique(n),this.refs[n]=l),r&&this.validateSchema(e,!0),l}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):o.compileSchema.call(this,e),!e.validate)throw Error(`ajv implementation error`);return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{o.compileSchema.call(this,e)}finally{this.opts=t}}};b.ValidationError=r.default,b.MissingRefError=i.default,e.default=b;function x(e,t,n,r=`error`){for(let i in e){let a=i;a in t&&this.logger[r](`${n}: option ${i}. ${e[a]}`)}}function ee(e){return e=(0,c.normalizeId)(e),this.schemas[e]||this.refs[e]}function S(){let e=this.opts.schemas;if(e){if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}}function te(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function ne(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn(`keywords option as map is deprecated, pass array`);for(let t in e){let n=e[t];n.keyword||=t,this.addKeyword(n)}}function re(){let e={...this.opts};for(let t of m)delete e[t];return e}var ie={log(){},warn(){},error(){}};function ae(e){if(e===!1)return ie;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw Error(`logger must implement log, warn and error methods`)}var C=/^[a-z_$][a-z0-9_$:-]*$/i;function oe(e,t){let{RULES:n}=this;if((0,u.eachItem)(e,e=>{if(n.keywords[e])throw Error(`Keyword ${e} is already defined`);if(!C.test(e))throw Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!(`code`in t||`validate`in t))throw Error(`$data keyword must have "code" or "validate" function`)}function w(e,t,n){var r;let i=t?.post;if(n&&i)throw Error(`keyword with "post" flag cannot have "type"`);let{RULES:a}=this,o=i?a.post:a.rules.find(({type:e})=>e===n);if(o||(o={type:n,rules:[]},a.rules.push(o)),a.keywords[e]=!0,!t)return;let s={keyword:e,definition:{...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)}};t.before?se.call(this,o,s,t.before):o.rules.push(s),a.all[e]=s,(r=t.implements)==null||r.forEach(e=>this.addKeyword(e))}function se(e,t,n){let r=e.rules.findIndex(e=>e.keyword===n);r>=0?e.rules.splice(r,0,t):(e.rules.push(t),this.logger.warn(`rule ${n} is not defined`))}function T(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=le(t)),e.validateSchema=this.compile(t,!0))}var ce={$ref:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`};function le(e){return{anyOf:[e,ce]}}})),dA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`id`,code(){throw Error(`NOT SUPPORTED: keyword "id", use "$id" for schema ID`)}}})),fA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.callRef=e.getValidate=void 0;var t=Xk(),n=Hk(),r=$(),i=Fk(),a=Zk(),o=Pk(),s={keyword:`$ref`,schemaType:`string`,code(e){let{gen:n,schema:i,it:o}=e,{baseId:s,schemaEnv:u,validateName:d,opts:f,self:p}=o,{root:m}=u;if((i===`#`||i===`#/`)&&s===m.baseId)return g();let h=a.resolveRef.call(p,m,s,i);if(h===void 0)throw new t.default(o.opts.uriResolver,s,i);return h instanceof a.SchemaEnv?_(h):v(h);function g(){if(u===m)return l(e,d,u,u.$async);let t=n.scopeValue(`root`,{ref:m});return l(e,(0,r._)`${t}.validate`,m,m.$async)}function _(t){l(e,c(e,t),t,t.$async)}function v(t){let a=n.scopeValue(`schema`,f.code.source===!0?{ref:t,code:(0,r.stringify)(t)}:{ref:t}),o=n.name(`valid`),s=e.subschema({schema:t,dataTypes:[],schemaPath:r.nil,topSchemaRef:a,errSchemaPath:i},o);e.mergeEvaluated(s),e.ok(o)}}};function c(e,t){let{gen:n}=e;return t.validate?n.scopeValue(`validate`,{ref:t.validate}):(0,r._)`${n.scopeValue(`wrapper`,{ref:t})}.validate`}e.getValidate=c;function l(e,t,a,s){let{gen:c,it:l}=e,{allErrors:u,schemaEnv:d,opts:f}=l,p=f.passContext?i.default.this:r.nil;s?m():h();function m(){if(!d.$async)throw Error(`async schema referenced by sync schema`);let i=c.let(`valid`);c.try(()=>{c.code((0,r._)`await ${(0,n.callValidateCode)(e,t,p)}`),_(t),u||c.assign(i,!0)},e=>{c.if((0,r._)`!(${e} instanceof ${l.ValidationError})`,()=>c.throw(e)),g(e),u||c.assign(i,!1)}),e.ok(i)}function h(){e.result((0,n.callValidateCode)(e,t,p),()=>_(t),()=>g(t))}function g(e){let t=(0,r._)`${e}.errors`;c.assign(i.default.vErrors,(0,r._)`${i.default.vErrors} === null ? ${t} : ${i.default.vErrors}.concat(${t})`),c.assign(i.default.errors,(0,r._)`${i.default.vErrors}.length`)}function _(e){if(!l.opts.unevaluated)return;let t=a?.validate?.evaluated;if(l.props!==!0){if(t&&!t.dynamicProps)t.props!==void 0&&(l.props=o.mergeEvaluated.props(c,t.props,l.props));else{let t=c.var(`props`,(0,r._)`${e}.evaluated.props`);l.props=o.mergeEvaluated.props(c,t,l.props,r.Name)}}if(l.items!==!0){if(t&&!t.dynamicItems)t.items!==void 0&&(l.items=o.mergeEvaluated.items(c,t.items,l.items));else{let t=c.var(`items`,(0,r._)`${e}.evaluated.items`);l.items=o.mergeEvaluated.items(c,t,l.items,r.Name)}}}}e.callRef=l,e.default=s})),pA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=dA(),n=fA();e.default=[`$schema`,`$id`,`$defs`,`$vocabulary`,{keyword:`$comment`},`definitions`,t.default,n.default]})),mA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=t.operators,r={maximum:{okStr:`<=`,ok:n.LTE,fail:n.GT},minimum:{okStr:`>=`,ok:n.GTE,fail:n.LT},exclusiveMaximum:{okStr:`<`,ok:n.LT,fail:n.GTE},exclusiveMinimum:{okStr:`>`,ok:n.GT,fail:n.LTE}};e.default={keyword:Object.keys(r),type:`number`,schemaType:`number`,$data:!0,error:{message:({keyword:e,schemaCode:n})=>(0,t.str)`must be ${r[e].okStr} ${n}`,params:({keyword:e,schemaCode:n})=>(0,t._)`{comparison: ${r[e].okStr}, limit: ${n}}`},code(e){let{keyword:n,data:i,schemaCode:a}=e;e.fail$data((0,t._)`${i} ${r[n].fail} ${a} || isNaN(${i})`)}}})),hA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$();e.default={keyword:`multipleOf`,type:`number`,schemaType:`number`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,t._)`{multipleOf: ${e}}`},code(e){let{gen:n,data:r,schemaCode:i,it:a}=e,o=a.opts.multipleOfPrecision,s=n.let(`res`),c=o?(0,t._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${o}`:(0,t._)`${s} !== parseInt(${s})`;e.fail$data((0,t._)`(${i} === 0 || (${s} = ${r}/${i}, ${c}))`)}}})),gA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e){let t=e.length,n=0,r=0,i;for(;r<t;)n++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<t&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return n}e.default=t,t.code=`require("ajv/dist/runtime/ucs2length").default`})),_A=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=Pk(),r=gA();e.default={keyword:[`maxLength`,`minLength`],type:`string`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxLength`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} characters`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:i,data:a,schemaCode:o,it:s}=e,c=i===`maxLength`?t.operators.GT:t.operators.LT,l=s.opts.unicode===!1?(0,t._)`${a}.length`:(0,t._)`${(0,n.useFunc)(e.gen,r.default)}(${a})`;e.fail$data((0,t._)`${l} ${c} ${o}`)}}})),vA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Hk(),n=Pk(),r=$();e.default={keyword:`pattern`,type:`string`,schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,r.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,r._)`{pattern: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e,u=l.opts.unicodeRegExp?`u`:``;if(o){let{regExp:t}=l.opts.code,o=t.code===`new RegExp`?(0,r._)`new RegExp`:(0,n.useFunc)(i,t),s=i.let(`valid`);i.try(()=>i.assign(s,(0,r._)`${o}(${c}, ${u}).test(${a})`),()=>i.assign(s,!1)),e.fail$data((0,r._)`!${s}`)}else{let n=(0,t.usePattern)(e,s);e.fail$data((0,r._)`!${n}.test(${a})`)}}}})),yA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$();e.default={keyword:[`maxProperties`,`minProperties`],type:`object`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxProperties`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} properties`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxProperties`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`Object.keys(${r}).length ${a} ${i}`)}}})),bA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Hk(),n=$(),r=Pk();e.default={keyword:`required`,type:`object`,schemaType:`array`,$data:!0,error:{message:({params:{missingProperty:e}})=>(0,n.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,n._)`{missingProperty: ${e}}`},code(e){let{gen:i,schema:a,schemaCode:o,data:s,$data:c,it:l}=e,{opts:u}=l;if(!c&&a.length===0)return;let d=a.length>=u.loopRequired;if(l.allErrors?f():p(),u.strictRequired){let t=e.parentSchema.properties,{definedProperties:n}=e.it;for(let e of a)if(t?.[e]===void 0&&!n.has(e)){let t=`required property "${e}" is not defined at "${l.schemaEnv.baseId+l.errSchemaPath}" (strictRequired)`;(0,r.checkStrictMode)(l,t,l.opts.strictRequired)}}function f(){if(d||c)e.block$data(n.nil,m);else for(let n of a)(0,t.checkReportMissingProp)(e,n)}function p(){let n=i.let(`missing`);if(d||c){let t=i.let(`valid`,!0);e.block$data(t,()=>h(n,t)),e.ok(t)}else i.if((0,t.checkMissingProp)(e,a,n)),(0,t.reportMissingProp)(e,n),i.else()}function m(){i.forOf(`prop`,o,n=>{e.setParams({missingProperty:n}),i.if((0,t.noPropertyInData)(i,s,n,u.ownProperties),()=>e.error())})}function h(r,a){e.setParams({missingProperty:r}),i.forOf(r,o,()=>{i.assign(a,(0,t.propertyInData)(i,s,r,u.ownProperties)),i.if((0,n.not)(a),()=>{e.error(),i.break()})},n.nil)}}}})),xA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$();e.default={keyword:[`maxItems`,`minItems`],type:`array`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxItems`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} items`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxItems`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`${r}.length ${a} ${i}`)}}})),SA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Gk();t.code=`require("ajv/dist/runtime/equal").default`,e.default=t})),CA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Bk(),n=$(),r=Pk(),i=SA();e.default={keyword:`uniqueItems`,type:`array`,schemaType:`boolean`,$data:!0,error:{message:({params:{i:e,j:t}})=>(0,n.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,n._)`{i: ${e}, j: ${t}}`},code(e){let{gen:a,data:o,$data:s,schema:c,parentSchema:l,schemaCode:u,it:d}=e;if(!s&&!c)return;let f=a.let(`valid`),p=l.items?(0,t.getSchemaTypes)(l.items):[];e.block$data(f,m,(0,n._)`${u} === false`),e.ok(f);function m(){let t=a.let(`i`,(0,n._)`${o}.length`),r=a.let(`j`);e.setParams({i:t,j:r}),a.assign(f,!0),a.if((0,n._)`${t} > 1`,()=>(h()?g:_)(t,r))}function h(){return p.length>0&&!p.some(e=>e===`object`||e===`array`)}function g(r,i){let s=a.name(`item`),c=(0,t.checkDataTypes)(p,s,d.opts.strictNumbers,t.DataType.Wrong),l=a.const(`indices`,(0,n._)`{}`);a.for((0,n._)`;${r}--;`,()=>{a.let(s,(0,n._)`${o}[${r}]`),a.if(c,(0,n._)`continue`),p.length>1&&a.if((0,n._)`typeof ${s} == "string"`,(0,n._)`${s} += "_"`),a.if((0,n._)`typeof ${l}[${s}] == "number"`,()=>{a.assign(i,(0,n._)`${l}[${s}]`),e.error(),a.assign(f,!1).break()}).code((0,n._)`${l}[${s}] = ${r}`)})}function _(t,s){let c=(0,r.useFunc)(a,i.default),l=a.name(`outer`);a.label(l).for((0,n._)`;${t}--;`,()=>a.for((0,n._)`${s} = ${t}; ${s}--;`,()=>a.if((0,n._)`${c}(${o}[${t}], ${o}[${s}])`,()=>{e.error(),a.assign(f,!1).break(l)})))}}}})),wA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=Pk(),r=SA();e.default={keyword:`const`,$data:!0,error:{message:`must be equal to constant`,params:({schemaCode:e})=>(0,t._)`{allowedValue: ${e}}`},code(e){let{gen:i,data:a,$data:o,schemaCode:s,schema:c}=e;o||c&&typeof c==`object`?e.fail$data((0,t._)`!${(0,n.useFunc)(i,r.default)}(${a}, ${s})`):e.fail((0,t._)`${c} !== ${a}`)}}})),TA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=Pk(),r=SA();e.default={keyword:`enum`,schemaType:`array`,$data:!0,error:{message:`must be equal to one of the allowed values`,params:({schemaCode:e})=>(0,t._)`{allowedValues: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e;if(!o&&s.length===0)throw Error(`enum must have non-empty array`);let u=s.length>=l.opts.loopEnum,d,f=()=>d??=(0,n.useFunc)(i,r.default),p;if(u||o)p=i.let(`valid`),e.block$data(p,m);else{if(!Array.isArray(s))throw Error(`ajv implementation error`);let e=i.const(`vSchema`,c);p=(0,t.or)(...s.map((t,n)=>h(e,n)))}e.pass(p);function m(){i.assign(p,!1),i.forOf(`v`,c,e=>i.if((0,t._)`${f()}(${a}, ${e})`,()=>i.assign(p,!0).break()))}function h(e,n){let r=s[n];return typeof r==`object`&&r?(0,t._)`${f()}(${a}, ${e}[${n}])`:(0,t._)`${a} === ${r}`}}}})),EA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=mA(),n=hA(),r=_A(),i=vA(),a=yA(),o=bA(),s=xA(),c=CA(),l=wA(),u=TA();e.default=[t.default,n.default,r.default,i.default,a.default,o.default,s.default,c.default,{keyword:`type`,schemaType:[`string`,`array`]},{keyword:`nullable`,schemaType:`boolean`},l.default,u.default]})),DA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateAdditionalItems=void 0;var t=$(),n=Pk(),r={keyword:`additionalItems`,type:`array`,schemaType:[`boolean`,`object`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{parentSchema:t,it:r}=e,{items:a}=t;if(!Array.isArray(a)){(0,n.checkStrictMode)(r,`"additionalItems" is ignored when "items" is not an array of schemas`);return}i(e,a)}};function i(e,r){let{gen:i,schema:a,data:o,keyword:s,it:c}=e;c.items=!0;let l=i.const(`len`,(0,t._)`${o}.length`);if(a===!1)e.setParams({len:r.length}),e.pass((0,t._)`${l} <= ${r.length}`);else if(typeof a==`object`&&!(0,n.alwaysValidSchema)(c,a)){let n=i.var(`valid`,(0,t._)`${l} <= ${r.length}`);i.if((0,t.not)(n),()=>u(n)),e.ok(n)}function u(a){i.forRange(`i`,r.length,l,r=>{e.subschema({keyword:s,dataProp:r,dataPropType:n.Type.Num},a),c.allErrors||i.if((0,t.not)(a),()=>i.break())})}}e.validateAdditionalItems=i,e.default=r})),OA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateTuple=void 0;var t=$(),n=Pk(),r=Hk(),i={keyword:`items`,type:`array`,schemaType:[`object`,`array`,`boolean`],before:`uniqueItems`,code(e){let{schema:t,it:i}=e;if(Array.isArray(t))return a(e,`additionalItems`,t);i.items=!0,!(0,n.alwaysValidSchema)(i,t)&&e.ok((0,r.validateArray)(e))}};function a(e,r,i=e.schema){let{gen:a,parentSchema:o,data:s,keyword:c,it:l}=e;f(o),l.opts.unevaluated&&i.length&&l.items!==!0&&(l.items=n.mergeEvaluated.items(a,i.length,l.items));let u=a.name(`valid`),d=a.const(`len`,(0,t._)`${s}.length`);i.forEach((r,i)=>{(0,n.alwaysValidSchema)(l,r)||(a.if((0,t._)`${d} > ${i}`,()=>e.subschema({keyword:c,schemaProp:i,dataProp:i},u)),e.ok(u))});function f(e){let{opts:t,errSchemaPath:a}=l,o=i.length,s=o===e.minItems&&(o===e.maxItems||e[r]===!1);if(t.strictTuples&&!s){let e=`"${c}" is ${o}-tuple, but minItems or maxItems/${r} are not specified or different at path "${a}"`;(0,n.checkStrictMode)(l,e,t.strictTuples)}}}e.validateTuple=a,e.default=i})),kA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=OA();e.default={keyword:`prefixItems`,type:`array`,schemaType:[`array`],before:`uniqueItems`,code:e=>(0,t.validateTuple)(e,`items`)}})),AA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=Pk(),r=Hk(),i=DA();e.default={keyword:`items`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{schema:t,parentSchema:a,it:o}=e,{prefixItems:s}=a;o.items=!0,!(0,n.alwaysValidSchema)(o,t)&&(s?(0,i.validateAdditionalItems)(e,s):e.ok((0,r.validateArray)(e)))}}})),jA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=Pk();e.default={keyword:`contains`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,trackErrors:!0,error:{message:({params:{min:e,max:n}})=>n===void 0?(0,t.str)`must contain at least ${e} valid item(s)`:(0,t.str)`must contain at least ${e} and no more than ${n} valid item(s)`,params:({params:{min:e,max:n}})=>n===void 0?(0,t._)`{minContains: ${e}}`:(0,t._)`{minContains: ${e}, maxContains: ${n}}`},code(e){let{gen:r,schema:i,parentSchema:a,data:o,it:s}=e,c,l,{minContains:u,maxContains:d}=a;s.opts.next?(c=u===void 0?1:u,l=d):c=1;let f=r.const(`len`,(0,t._)`${o}.length`);if(e.setParams({min:c,max:l}),l===void 0&&c===0){(0,n.checkStrictMode)(s,`"minContains" == 0 without "maxContains": "contains" keyword ignored`);return}if(l!==void 0&&c>l){(0,n.checkStrictMode)(s,`"minContains" > "maxContains" is always invalid`),e.fail();return}if((0,n.alwaysValidSchema)(s,i)){let n=(0,t._)`${f} >= ${c}`;l!==void 0&&(n=(0,t._)`${n} && ${f} <= ${l}`),e.pass(n);return}s.items=!0;let p=r.name(`valid`);l===void 0&&c===1?h(p,()=>r.if(p,()=>r.break())):c===0?(r.let(p,!0),l!==void 0&&r.if((0,t._)`${o}.length > 0`,m)):(r.let(p,!1),m()),e.result(p,()=>e.reset());function m(){let e=r.name(`_valid`),t=r.let(`count`,0);h(e,()=>r.if(e,()=>g(t)))}function h(t,i){r.forRange(`i`,0,f,r=>{e.subschema({keyword:`contains`,dataProp:r,dataPropType:n.Type.Num,compositeRule:!0},t),i()})}function g(e){r.code((0,t._)`${e}++`),l===void 0?r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0).break()):(r.if((0,t._)`${e} > ${l}`,()=>r.assign(p,!1).break()),c===1?r.assign(p,!0):r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0)))}}}})),MA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;var t=$(),n=Pk(),r=Hk();e.error={message:({params:{property:e,depsCount:n,deps:r}})=>{let i=n===1?`property`:`properties`;return(0,t.str)`must have ${i} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:n,deps:r,missingProperty:i}})=>(0,t._)`{property: ${e},
|
|
302
|
+
|| ${s} === "boolean" || ${a} === null`).assign(c,(0,i._)`[${a}]`)}}}function p({gen:e,parentData:t,parentDataProperty:n},r){e.if((0,i._)`${t} !== undefined`,()=>e.assign((0,i._)`${t}[${n}]`,r))}function m(e,t,n,r=o.Correct){let a=r===o.Correct?i.operators.EQ:i.operators.NEQ,s;switch(e){case`null`:return(0,i._)`${t} ${a} null`;case`array`:s=(0,i._)`Array.isArray(${t})`;break;case`object`:s=(0,i._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case`integer`:s=c((0,i._)`!(${t} % 1) && !isNaN(${t})`);break;case`number`:s=c();break;default:return(0,i._)`typeof ${t} ${a} ${e}`}return r===o.Correct?s:(0,i.not)(s);function c(e=i.nil){return(0,i.and)((0,i._)`typeof ${t} == "number"`,e,n?(0,i._)`isFinite(${t})`:i.nil)}}e.checkDataType=m;function h(e,t,n,r){if(e.length===1)return m(e[0],t,n,r);let o,s=(0,a.toHash)(e);if(s.array&&s.object){let e=(0,i._)`typeof ${t} != "object"`;o=s.null?e:(0,i._)`!${t} || ${e}`,delete s.null,delete s.array,delete s.object}else o=i.nil;s.number&&delete s.integer;for(let e in s)o=(0,i.and)(o,m(e,t,n,r));return o}e.checkDataTypes=h;var g={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e==`string`?(0,i._)`{type: ${e}}`:(0,i._)`{type: ${t}}`};function _(e){let t=v(e);(0,r.reportError)(t,g)}e.reportTypeError=_;function v(e){let{gen:t,data:n,schema:r}=e,i=(0,a.schemaRefOrVal)(e,r,`type`);return{gen:t,keyword:`type`,data:n,schema:r.type,schemaCode:i,schemaValue:i,parentSchema:r,params:{},it:e}}})),Hk=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.assignDefaults=void 0;var t=$(),n=Fk();function r(e,t){let{properties:n,items:r}=e.schema;if(t===`object`&&n)for(let t in n)i(e,t,n[t].default);else t===`array`&&Array.isArray(r)&&r.forEach((t,n)=>i(e,n,t.default))}e.assignDefaults=r;function i(e,r,i){let{gen:a,compositeRule:o,data:s,opts:c}=e;if(i===void 0)return;let l=(0,t._)`${s}${(0,t.getProperty)(r)}`;if(o){(0,n.checkStrictMode)(e,`default is ignored for: ${l}`);return}let u=(0,t._)`${l} === undefined`;c.useDefaults===`empty`&&(u=(0,t._)`${u} || ${l} === null || ${l} === ""`),a.if(u,(0,t._)`${l} = ${(0,t.stringify)(i)}`)}})),Uk=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateUnion=e.validateArray=e.usePattern=e.callValidateCode=e.schemaProperties=e.allSchemaProperties=e.noPropertyInData=e.propertyInData=e.isOwnProperty=e.hasPropFunc=e.reportMissingProp=e.checkMissingProp=e.checkReportMissingProp=void 0;var t=$(),n=Fk(),r=Ik(),i=Fk();function a(e,n){let{gen:r,data:i,it:a}=e;r.if(d(r,i,n,a.opts.ownProperties),()=>{e.setParams({missingProperty:(0,t._)`${n}`},!0),e.error()})}e.checkReportMissingProp=a;function o({gen:e,data:n,it:{opts:r}},i,a){return(0,t.or)(...i.map(i=>(0,t.and)(d(e,n,i,r.ownProperties),(0,t._)`${a} = ${i}`)))}e.checkMissingProp=o;function s(e,t){e.setParams({missingProperty:t},!0),e.error()}e.reportMissingProp=s;function c(e){return e.scopeValue(`func`,{ref:Object.prototype.hasOwnProperty,code:(0,t._)`Object.prototype.hasOwnProperty`})}e.hasPropFunc=c;function l(e,n,r){return(0,t._)`${c(e)}.call(${n}, ${r})`}e.isOwnProperty=l;function u(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} !== undefined`;return i?(0,t._)`${a} && ${l(e,n,r)}`:a}e.propertyInData=u;function d(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} === undefined`;return i?(0,t.or)(a,(0,t.not)(l(e,n,r))):a}e.noPropertyInData=d;function f(e){return e?Object.keys(e).filter(e=>e!==`__proto__`):[]}e.allSchemaProperties=f;function p(e,t){return f(t).filter(r=>!(0,n.alwaysValidSchema)(e,t[r]))}e.schemaProperties=p;function m({schemaCode:e,data:n,it:{gen:i,topSchemaRef:a,schemaPath:o,errorPath:s},it:c},l,u,d){let f=d?(0,t._)`${e}, ${n}, ${a}${o}`:n,p=[[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,s)],[r.default.parentData,c.parentData],[r.default.parentDataProperty,c.parentDataProperty],[r.default.rootData,r.default.rootData]];c.opts.dynamicRef&&p.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);let m=(0,t._)`${f}, ${i.object(...p)}`;return u===t.nil?(0,t._)`${l}(${m})`:(0,t._)`${l}.call(${u}, ${m})`}e.callValidateCode=m;var h=(0,t._)`new RegExp`;function g({gen:e,it:{opts:n}},r){let a=n.unicodeRegExp?`u`:``,{regExp:o}=n.code,s=o(r,a);return e.scopeValue(`pattern`,{key:s.toString(),ref:s,code:(0,t._)`${o.code===`new RegExp`?h:(0,i.useFunc)(e,o)}(${r}, ${a})`})}e.usePattern=g;function _(e){let{gen:r,data:i,keyword:a,it:o}=e,s=r.name(`valid`);if(o.allErrors){let e=r.let(`valid`,!0);return c(()=>r.assign(e,!1)),e}return r.var(s,!0),c(()=>r.break()),s;function c(o){let c=r.const(`len`,(0,t._)`${i}.length`);r.forRange(`i`,0,c,i=>{e.subschema({keyword:a,dataProp:i,dataPropType:n.Type.Num},s),r.if((0,t.not)(s),o)})}}e.validateArray=_;function v(e){let{gen:r,schema:i,keyword:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(i.some(e=>(0,n.alwaysValidSchema)(o,e))&&!o.opts.unevaluated)return;let s=r.let(`valid`,!1),c=r.name(`_valid`);r.block(()=>i.forEach((n,i)=>{let o=e.subschema({keyword:a,schemaProp:i,compositeRule:!0},c);r.assign(s,(0,t._)`${s} || ${c}`),e.mergeValidEvaluated(o,c)||r.if((0,t.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}e.validateUnion=v})),Wk=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;var t=$(),n=Ik(),r=Uk(),i=Lk();function a(e,n){let{gen:r,keyword:i,schema:a,parentSchema:o,it:s}=e,c=n.macro.call(s.self,a,o,s),l=u(r,i,c);s.opts.validateSchema!==!1&&s.self.validateSchema(c,!0);let d=r.name(`valid`);e.subschema({schema:c,schemaPath:t.nil,errSchemaPath:`${s.errSchemaPath}/${i}`,topSchemaRef:l,compositeRule:!0},d),e.pass(d,()=>e.error(!0))}e.macroKeywordCode=a;function o(e,i){let{gen:a,keyword:o,schema:d,parentSchema:f,$data:p,it:m}=e;l(m,i);let h=u(a,o,!p&&i.compile?i.compile.call(m.self,d,f,m):i.validate),g=a.let(`valid`);e.block$data(g,_),e.ok(i.valid??g);function _(){if(i.errors===!1)b(),i.modifying&&s(e),x(()=>e.error());else{let t=i.async?v():y();i.modifying&&s(e),x(()=>c(e,t))}}function v(){let e=a.let(`ruleErrs`,null);return a.try(()=>b((0,t._)`await `),n=>a.assign(g,!1).if((0,t._)`${n} instanceof ${m.ValidationError}`,()=>a.assign(e,(0,t._)`${n}.errors`),()=>a.throw(n))),e}function y(){let e=(0,t._)`${h}.errors`;return a.assign(e,null),b(t.nil),e}function b(o=i.async?(0,t._)`await `:t.nil){let s=m.opts.passContext?n.default.this:n.default.self,c=!(`compile`in i&&!p||i.schema===!1);a.assign(g,(0,t._)`${o}${(0,r.callValidateCode)(e,h,s,c)}`,i.modifying)}function x(e){a.if((0,t.not)(i.valid??g),e)}}e.funcKeywordCode=o;function s(e){let{gen:n,data:r,it:i}=e;n.if(i.parentData,()=>n.assign(r,(0,t._)`${i.parentData}[${i.parentDataProperty}]`))}function c(e,r){let{gen:a}=e;a.if((0,t._)`Array.isArray(${r})`,()=>{a.assign(n.default.vErrors,(0,t._)`${n.default.vErrors} === null ? ${r} : ${n.default.vErrors}.concat(${r})`).assign(n.default.errors,(0,t._)`${n.default.vErrors}.length`),(0,i.extendErrors)(e)},()=>e.error())}function l({schemaEnv:e},t){if(t.async&&!e.$async)throw Error(`async keyword in sync schema`)}function u(e,n,r){if(r===void 0)throw Error(`keyword "${n}" failed to compile`);return e.scopeValue(`keyword`,typeof r==`function`?{ref:r}:{ref:r,code:(0,t.stringify)(r)})}function d(e,t,n=!1){return!t.length||t.some(t=>t===`array`?Array.isArray(e):t===`object`?e&&typeof e==`object`&&!Array.isArray(e):typeof e==t||n&&e===void 0)}e.validSchemaType=d;function f({schema:e,opts:t,self:n,errSchemaPath:r},i,a){if(Array.isArray(i.keyword)?!i.keyword.includes(a):i.keyword!==a)throw Error(`ajv implementation error`);let o=i.dependencies;if(o?.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw Error(`parent schema must have dependencies of ${a}: ${o.join(`,`)}`);if(i.validateSchema&&!i.validateSchema(e[a])){let e=`keyword "${a}" value is invalid at path "${r}": `+n.errorsText(i.validateSchema.errors);if(t.validateSchema===`log`)n.logger.error(e);else throw Error(e)}}e.validateKeywordUsage=f})),Gk=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;var t=$(),n=Fk();function r(e,{keyword:r,schemaProp:i,schema:a,schemaPath:o,errSchemaPath:s,topSchemaRef:c}){if(r!==void 0&&a!==void 0)throw Error(`both "keyword" and "schema" passed, only one allowed`);if(r!==void 0){let a=e.schema[r];return i===void 0?{schema:a,schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${r}`}:{schema:a[i],schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}${(0,t.getProperty)(i)}`,errSchemaPath:`${e.errSchemaPath}/${r}/${(0,n.escapeFragment)(i)}`}}if(a!==void 0){if(o===void 0||s===void 0||c===void 0)throw Error(`"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"`);return{schema:a,schemaPath:o,topSchemaRef:c,errSchemaPath:s}}throw Error(`either "keyword" or "schema" must be passed`)}e.getSubschema=r;function i(e,r,{dataProp:i,dataPropType:a,data:o,dataTypes:s,propertyName:c}){if(o!==void 0&&i!==void 0)throw Error(`both "data" and "dataProp" passed, only one allowed`);let{gen:l}=r;if(i!==void 0){let{errorPath:o,dataPathArr:s,opts:c}=r;u(l.let(`data`,(0,t._)`${r.data}${(0,t.getProperty)(i)}`,!0)),e.errorPath=(0,t.str)`${o}${(0,n.getErrorPath)(i,a,c.jsPropertySyntax)}`,e.parentDataProperty=(0,t._)`${i}`,e.dataPathArr=[...s,e.parentDataProperty]}o!==void 0&&(u(o instanceof t.Name?o:l.let(`data`,o,!0)),c!==void 0&&(e.propertyName=c)),s&&(e.dataTypes=s);function u(t){e.data=t,e.dataLevel=r.dataLevel+1,e.dataTypes=[],r.definedProperties=new Set,e.parentData=r.data,e.dataNames=[...r.dataNames,t]}}e.extendSubschemaData=i;function a(e,{jtdDiscriminator:t,jtdMetadata:n,compositeRule:r,createErrors:i,allErrors:a}){r!==void 0&&(e.compositeRule=r),i!==void 0&&(e.createErrors=i),a!==void 0&&(e.allErrors=a),e.jtdDiscriminator=t,e.jtdMetadata=n}e.extendSubschemaMode=a})),Kk=E(((e,t)=>{t.exports=function e(t,n){if(t===n)return!0;if(t&&n&&typeof t==`object`&&typeof n==`object`){if(t.constructor!==n.constructor)return!1;var r,i,a;if(Array.isArray(t)){if(r=t.length,r!=n.length)return!1;for(i=r;i--!==0;)if(!e(t[i],n[i]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(a=Object.keys(t),r=a.length,r!==Object.keys(n).length)return!1;for(i=r;i--!==0;)if(!Object.prototype.hasOwnProperty.call(n,a[i]))return!1;for(i=r;i--!==0;){var o=a[i];if(!e(t[o],n[o]))return!1}return!0}return t!==t&&n!==n}})),qk=E(((e,t)=>{var n=t.exports=function(e,t,n){typeof t==`function`&&(n=t,t={}),n=t.cb||n;var i=typeof n==`function`?n:n.pre||function(){},a=n.post||function(){};r(t,i,a,e,``,e)};n.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},n.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},n.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},n.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function r(e,t,a,o,s,c,l,u,d,f){if(o&&typeof o==`object`&&!Array.isArray(o)){for(var p in t(o,s,c,l,u,d,f),o){var m=o[p];if(Array.isArray(m)){if(p in n.arrayKeywords)for(var h=0;h<m.length;h++)r(e,t,a,m[h],s+`/`+p+`/`+h,c,s,p,o,h)}else if(p in n.propsKeywords){if(m&&typeof m==`object`)for(var g in m)r(e,t,a,m[g],s+`/`+p+`/`+i(g),c,s,p,o,g)}else(p in n.keywords||e.allKeys&&!(p in n.skipKeywords))&&r(e,t,a,m,s+`/`+p,c,s,p,o)}a(o,s,c,l,u,d,f)}}function i(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}})),Jk=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;var t=Fk(),n=Kk(),r=qk(),i=new Set([`type`,`format`,`pattern`,`maxLength`,`minLength`,`maxProperties`,`minProperties`,`maxItems`,`minItems`,`maximum`,`minimum`,`uniqueItems`,`multipleOf`,`required`,`enum`,`const`]);function a(e,t=!0){return typeof e==`boolean`?!0:t===!0?!s(e):t?c(e)<=t:!1}e.inlineRef=a;var o=new Set([`$ref`,`$recursiveRef`,`$recursiveAnchor`,`$dynamicRef`,`$dynamicAnchor`]);function s(e){for(let t in e){if(o.has(t))return!0;let n=e[t];if(Array.isArray(n)&&n.some(s)||typeof n==`object`&&s(n))return!0}return!1}function c(e){let n=0;for(let r in e)if(r===`$ref`||(n++,!i.has(r)&&(typeof e[r]==`object`&&(0,t.eachItem)(e[r],e=>n+=c(e)),n===1/0)))return 1/0;return n}function l(e,t=``,n){return n!==!1&&(t=f(t)),u(e,e.parse(t))}e.getFullPath=l;function u(e,t){return e.serialize(t).split(`#`)[0]+`#`}e._getFullPath=u;var d=/#\/?$/;function f(e){return e?e.replace(d,``):``}e.normalizeId=f;function p(e,t,n){return n=f(n),e.resolve(t,n)}e.resolveUrl=p;var m=/^[a-z_][-a-z0-9._]*$/i;function h(e,t){if(typeof e==`boolean`)return{};let{schemaId:i,uriResolver:a}=this.opts,o=f(e[i]||t),s={"":o},c=l(a,o,!1),u={},d=new Set;return r(e,{allKeys:!0},(e,t,n,r)=>{if(r===void 0)return;let a=c+t,o=s[r];typeof e[i]==`string`&&(o=l.call(this,e[i])),g.call(this,e.$anchor),g.call(this,e.$dynamicAnchor),s[t]=o;function l(t){let n=this.opts.uriResolver.resolve;if(t=f(o?n(o,t):t),d.has(t))throw h(t);d.add(t);let r=this.refs[t];return typeof r==`string`&&(r=this.refs[r]),typeof r==`object`?p(e,r.schema,t):t!==f(a)&&(t[0]===`#`?(p(e,u[t],t),u[t]=e):this.refs[t]=a),t}function g(e){if(typeof e==`string`){if(!m.test(e))throw Error(`invalid anchor "${e}"`);l.call(this,`#${e}`)}}}),u;function p(e,t,r){if(t!==void 0&&!n(e,t))throw h(r)}function h(e){return Error(`reference "${e}" resolves to more than one schema`)}}e.getSchemaRefs=h})),Yk=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;var t=Rk(),n=Vk(),r=Bk(),i=Vk(),a=Hk(),o=Wk(),s=Gk(),c=$(),l=Ik(),u=Jk(),d=Fk(),f=Lk();function p(e){if(ee(e)&&(te(e),x(e))){_(e);return}m(e,()=>(0,t.topBoolOrEmptySchema)(e))}e.validateFunctionCode=p;function m({gen:e,validateName:t,schema:n,schemaEnv:r,opts:i},a){i.code.es5?e.func(t,(0,c._)`${l.default.data}, ${l.default.valCxt}`,r.$async,()=>{e.code((0,c._)`"use strict"; ${y(n,i)}`),g(e,i),e.code(a)}):e.func(t,(0,c._)`${l.default.data}, ${h(i)}`,r.$async,()=>e.code(y(n,i)).code(a))}function h(e){return(0,c._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${e.dynamicRef?(0,c._)`, ${l.default.dynamicAnchors}={}`:c.nil}}={}`}function g(e,t){e.if(l.default.valCxt,()=>{e.var(l.default.instancePath,(0,c._)`${l.default.valCxt}.${l.default.instancePath}`),e.var(l.default.parentData,(0,c._)`${l.default.valCxt}.${l.default.parentData}`),e.var(l.default.parentDataProperty,(0,c._)`${l.default.valCxt}.${l.default.parentDataProperty}`),e.var(l.default.rootData,(0,c._)`${l.default.valCxt}.${l.default.rootData}`),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{e.var(l.default.instancePath,(0,c._)`""`),e.var(l.default.parentData,(0,c._)`undefined`),e.var(l.default.parentDataProperty,(0,c._)`undefined`),e.var(l.default.rootData,l.default.data),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`{}`)})}function _(e){let{schema:t,opts:n,gen:r}=e;m(e,()=>{n.$comment&&t.$comment&&oe(e),ie(e),r.let(l.default.vErrors,null),r.let(l.default.errors,0),n.unevaluated&&v(e),ne(e),w(e)})}function v(e){let{gen:t,validateName:n}=e;e.evaluated=t.const(`evaluated`,(0,c._)`${n}.evaluated`),t.if((0,c._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,c._)`${e.evaluated}.props`,(0,c._)`undefined`)),t.if((0,c._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,c._)`${e.evaluated}.items`,(0,c._)`undefined`))}function y(e,t){let n=typeof e==`object`&&e[t.schemaId];return n&&(t.code.source||t.code.process)?(0,c._)`/*# sourceURL=${n} */`:c.nil}function b(e,n){if(ee(e)&&(te(e),x(e))){S(e,n);return}(0,t.boolOrEmptySchema)(e,n)}function x({schema:e,self:t}){if(typeof e==`boolean`)return!e;for(let n in e)if(t.RULES.all[n])return!0;return!1}function ee(e){return typeof e.schema!=`boolean`}function S(e,t){let{schema:n,gen:r,opts:i}=e;i.$comment&&n.$comment&&oe(e),ae(e),C(e);let a=r.const(`_errs`,l.default.errors);ne(e,a),r.var(t,(0,c._)`${a} === ${l.default.errors}`)}function te(e){(0,d.checkUnknownRules)(e),re(e)}function ne(e,t){if(e.opts.jtd)return T(e,[],!1,t);let r=(0,n.getSchemaTypes)(e.schema);T(e,r,!(0,n.coerceAndCheckDataType)(e,r),t)}function re(e){let{schema:t,errSchemaPath:n,opts:r,self:i}=e;t.$ref&&r.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function ie(e){let{schema:t,opts:n}=e;t.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,d.checkStrictMode)(e,`default is ignored in the schema root`)}function ae(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,u.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function C(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error(`async schema in sync schema`)}function oe({gen:e,schemaEnv:t,schema:n,errSchemaPath:r,opts:i}){let a=n.$comment;if(i.$comment===!0)e.code((0,c._)`${l.default.self}.logger.log(${a})`);else if(typeof i.$comment==`function`){let n=(0,c.str)`${r}/$comment`,i=e.scopeValue(`root`,{ref:t.root});e.code((0,c._)`${l.default.self}.opts.$comment(${a}, ${n}, ${i}.schema)`)}}function w(e){let{gen:t,schemaEnv:n,validateName:r,ValidationError:i,opts:a}=e;n.$async?t.if((0,c._)`${l.default.errors} === 0`,()=>t.return(l.default.data),()=>t.throw((0,c._)`new ${i}(${l.default.vErrors})`)):(t.assign((0,c._)`${r}.errors`,l.default.vErrors),a.unevaluated&&se(e),t.return((0,c._)`${l.default.errors} === 0`))}function se({gen:e,evaluated:t,props:n,items:r}){n instanceof c.Name&&e.assign((0,c._)`${t}.props`,n),r instanceof c.Name&&e.assign((0,c._)`${t}.items`,r)}function T(e,t,n,a){let{gen:o,schema:s,data:u,allErrors:f,opts:p,self:m}=e,{RULES:h}=m;if(s.$ref&&(p.ignoreKeywordsWithRef||!(0,d.schemaHasRulesButRef)(s,h))){o.block(()=>ve(e,`$ref`,h.all.$ref.definition));return}p.jtd||le(e,t),o.block(()=>{for(let e of h.rules)g(e);g(h.post)});function g(d){(0,r.shouldUseGroup)(s,d)&&(d.type?(o.if((0,i.checkDataType)(d.type,u,p.strictNumbers)),ce(e,d),t.length===1&&t[0]===d.type&&n&&(o.else(),(0,i.reportTypeError)(e)),o.endIf()):ce(e,d),f||o.if((0,c._)`${l.default.errors} === ${a||0}`))}}function ce(e,t){let{gen:n,schema:i,opts:{useDefaults:o}}=e;o&&(0,a.assignDefaults)(e,t.type),n.block(()=>{for(let n of t.rules)(0,r.shouldUseRule)(i,n)&&ve(e,n.keyword,n.definition,t.type)})}function le(e,t){!e.schemaEnv.meta&&e.opts.strictTypes&&(ue(e,t),e.opts.allowUnionTypes||de(e,t),fe(e,e.dataTypes))}function ue(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(t=>{me(e.dataTypes,t)||ge(e,`type "${t}" not allowed by context "${e.dataTypes.join(`,`)}"`)}),he(e,t)}}function de(e,t){t.length>1&&!(t.length===2&&t.includes(`null`))&&ge(e,`use allowUnionTypes to allow union type keyword`)}function fe(e,t){let n=e.self.RULES.all;for(let i in n){let a=n[i];if(typeof a==`object`&&(0,r.shouldUseRule)(e.schema,a)){let{type:n}=a.definition;n.length&&!n.some(e=>pe(t,e))&&ge(e,`missing type "${n.join(`,`)}" for keyword "${i}"`)}}}function pe(e,t){return e.includes(t)||t===`number`&&e.includes(`integer`)}function me(e,t){return e.includes(t)||t===`integer`&&e.includes(`number`)}function he(e,t){let n=[];for(let r of e.dataTypes)me(t,r)?n.push(r):t.includes(`integer`)&&r===`number`&&n.push(`integer`);e.dataTypes=n}function ge(e,t){let n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,d.checkStrictMode)(e,t,e.opts.strictTypes)}var _e=class{constructor(e,t,n){if((0,o.validateKeywordUsage)(e,t,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,d.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const(`vSchema`,xe(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,o.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);(`code`in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const(`_errs`,l.default.errors))}result(e,t,n){this.failResult((0,c.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,c.not)(e),void 0,t)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail((0,c._)`${t} !== undefined && (${(0,c.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t){this.setParams(t),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,t){(e?f.reportExtraError:f.reportError)(this,this.def.error,t)}$dataError(){(0,f.reportError)(this,this.def.$dataError||f.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error(`add "trackErrors" to keyword definition`);(0,f.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=c.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=c.nil,t=c.nil){if(!this.$data)return;let{gen:n,schemaCode:r,schemaType:i,def:a}=this;n.if((0,c.or)((0,c._)`${r} === undefined`,t)),e!==c.nil&&n.assign(e,!0),(i.length||a.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==c.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:r,it:a}=this;return(0,c.or)(o(),s());function o(){if(n.length){if(!(t instanceof c.Name))throw Error(`ajv implementation error`);let e=Array.isArray(n)?n:[n];return(0,c._)`${(0,i.checkDataTypes)(e,t,a.opts.strictNumbers,i.DataType.Wrong)}`}return c.nil}function s(){if(r.validateSchema){let n=e.scopeValue(`validate$data`,{ref:r.validateSchema});return(0,c._)`!${n}(${t})`}return c.nil}}subschema(e,t){let n=(0,s.getSubschema)(this.it,e);(0,s.extendSubschemaData)(n,this.it,e),(0,s.extendSubschemaMode)(n,e);let r={...this.it,...n,items:void 0,props:void 0};return b(r,t),r}mergeEvaluated(e,t){let{it:n,gen:r}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=d.mergeEvaluated.props(r,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=d.mergeEvaluated.items(r,e.items,n.items,t)))}mergeValidEvaluated(e,t){let{it:n,gen:r}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return r.if(t,()=>this.mergeEvaluated(e,c.Name)),!0}};e.KeywordCxt=_e;function ve(e,t,n,r){let i=new _e(e,n,t);`code`in n?n.code(i,r):i.$data&&n.validate?(0,o.funcKeywordCode)(i,n):`macro`in n?(0,o.macroKeywordCode)(i,n):(n.compile||n.validate)&&(0,o.funcKeywordCode)(i,n)}var ye=/^\/(?:[^~]|~0|~1)*$/,be=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function xe(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let i,a;if(e===``)return l.default.rootData;if(e[0]===`/`){if(!ye.test(e))throw Error(`Invalid JSON-pointer: ${e}`);i=e,a=l.default.rootData}else{let o=be.exec(e);if(!o)throw Error(`Invalid JSON-pointer: ${e}`);let s=+o[1];if(i=o[2],i===`#`){if(s>=t)throw Error(u(`property/index`,s));return r[t-s]}if(s>t)throw Error(u(`data`,s));if(a=n[t-s],!i)return a}let o=a,s=i.split(`/`);for(let e of s)e&&(a=(0,c._)`${a}${(0,c.getProperty)((0,d.unescapeJsonPointer)(e))}`,o=(0,c._)`${o} && ${a}`);return o;function u(e,n){return`Cannot access ${e} ${n} levels up, current level is ${t}`}}e.getData=xe})),Xk=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=class extends Error{constructor(e){super(`validation failed`),this.errors=e,this.ajv=this.validation=!0}}})),Zk=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Jk();e.default=class extends Error{constructor(e,n,r,i){super(i||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,t.resolveUrl)(e,n,r),this.missingSchema=(0,t.normalizeId)((0,t.getFullPath)(e,this.missingRef))}}})),Qk=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;var t=$(),n=Xk(),r=Ik(),i=Jk(),a=Fk(),o=Yk(),s=class{constructor(e){this.refs={},this.dynamicAnchors={};let t;typeof e.schema==`object`&&(t=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=e.baseId??(0,i.normalizeId)(t?.[e.schemaId||`$id`]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=t?.$async,this.refs={}}};e.SchemaEnv=s;function c(e){let a=d.call(this,e);if(a)return a;let s=(0,i.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:c,lines:l}=this.opts.code,{ownProperties:u}=this.opts,f=new t.CodeGen(this.scope,{es5:c,lines:l,ownProperties:u}),p;e.$async&&(p=f.scopeValue(`Error`,{ref:n.default,code:(0,t._)`require("ajv/dist/runtime/validation_error").default`}));let m=f.scopeName(`validate`);e.validateName=m;let h={gen:f,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[t.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:f.scopeValue(`schema`,this.opts.code.source===!0?{ref:e.schema,code:(0,t.stringify)(e.schema)}:{ref:e.schema}),validateName:m,ValidationError:p,schema:e.schema,schemaEnv:e,rootId:s,baseId:e.baseId||s,schemaPath:t.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?``:`#`),errorPath:(0,t._)`""`,opts:this.opts,self:this},g;try{this._compilations.add(e),(0,o.validateFunctionCode)(h),f.optimize(this.opts.code.optimize);let n=f.toString();g=`${f.scopeRefs(r.default.scope)}return ${n}`,this.opts.code.process&&(g=this.opts.code.process(g,e));let i=Function(`${r.default.self}`,`${r.default.scope}`,g)(this,this.scope.get());if(this.scope.value(m,{ref:i}),i.errors=null,i.schema=e.schema,i.schemaEnv=e,e.$async&&(i.$async=!0),this.opts.code.source===!0&&(i.source={validateName:m,validateCode:n,scopeValues:f._values}),this.opts.unevaluated){let{props:e,items:n}=h;i.evaluated={props:e instanceof t.Name?void 0:e,items:n instanceof t.Name?void 0:n,dynamicProps:e instanceof t.Name,dynamicItems:n instanceof t.Name},i.source&&(i.source.evaluated=(0,t.stringify)(i.evaluated))}return e.validate=i,e}catch(t){throw delete e.validate,delete e.validateName,g&&this.logger.error(`Error compiling schema, function code:`,g),t}finally{this._compilations.delete(e)}}e.compileSchema=c;function l(e,t,n){n=(0,i.resolveUrl)(this.opts.uriResolver,t,n);let r=e.refs[n];if(r)return r;let a=p.call(this,e,n);if(a===void 0){let r=e.localRefs?.[n],{schemaId:i}=this.opts;r&&(a=new s({schema:r,schemaId:i,root:e,baseId:t}))}if(a!==void 0)return e.refs[n]=u.call(this,a)}e.resolveRef=l;function u(e){return(0,i.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:c.call(this,e)}function d(e){for(let t of this._compilations)if(f(t,e))return t}e.getCompilingSchema=d;function f(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function p(e,t){let n;for(;typeof(n=this.refs[t])==`string`;)t=n;return n||this.schemas[t]||m.call(this,e,t)}function m(e,t){let n=this.opts.uriResolver.parse(t),r=(0,i._getFullPath)(this.opts.uriResolver,n),a=(0,i.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&r===a)return g.call(this,n,e);let o=(0,i.normalizeId)(r),l=this.refs[o]||this.schemas[o];if(typeof l==`string`){let t=m.call(this,e,l);return typeof t?.schema==`object`?g.call(this,n,t):void 0}if(typeof l?.schema==`object`){if(l.validate||c.call(this,l),o===(0,i.normalizeId)(t)){let{schema:t}=l,{schemaId:n}=this.opts,r=t[n];return r&&(a=(0,i.resolveUrl)(this.opts.uriResolver,a,r)),new s({schema:t,schemaId:n,root:e,baseId:a})}return g.call(this,n,l)}}e.resolveSchema=m;var h=new Set([`properties`,`patternProperties`,`enum`,`dependencies`,`definitions`]);function g(e,{baseId:t,schema:n,root:r}){if(e.fragment?.[0]!==`/`)return;for(let r of e.fragment.slice(1).split(`/`)){if(typeof n==`boolean`)return;let e=n[(0,a.unescapeFragment)(r)];if(e===void 0)return;n=e;let o=typeof n==`object`&&n[this.opts.schemaId];!h.has(r)&&o&&(t=(0,i.resolveUrl)(this.opts.uriResolver,t,o))}let o;if(typeof n!=`boolean`&&n.$ref&&!(0,a.schemaHasRulesButRef)(n,this.RULES)){let e=(0,i.resolveUrl)(this.opts.uriResolver,t,n.$ref);o=m.call(this,r,e)}let{schemaId:c}=this.opts;if(o||=new s({schema:n,schemaId:c,root:r,baseId:t}),o.schema!==o.root.schema)return o}})),$k=Oe({$id:()=>eA,additionalProperties:()=>!1,default:()=>aA,description:()=>tA,properties:()=>iA,required:()=>rA,type:()=>nA}),eA,tA,nA,rA,iA,aA,oA=De((()=>{eA=`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`,tA=`Meta-schema for $data reference (JSON AnySchema extension proposal)`,nA=`object`,rA=[`$data`],iA={$data:{type:`string`,anyOf:[{format:`relative-json-pointer`},{format:`json-pointer`}]}},aA={$id:eA,description:tA,type:nA,required:rA,properties:iA,additionalProperties:!1}})),sA=E(((e,t)=>{var n=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),r=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),i=RegExp.prototype.test.bind(/^\d*$/u),a=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),o=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),s=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),c=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),l=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),u=Array(256);{let e=`0123456789ABCDEF`;for(let t=0;t<256;t++)u[t]=`%`+e[t>>4]+e[t&15]}function d(e){return e<2048?u[192|e>>6]+u[128|e&63]:e<65536?u[224|e>>12]+u[128|e>>6&63]+u[128|e&63]:u[240|e>>18]+u[128|e>>12&63]+u[128|e>>6&63]+u[128|e&63]}function f(e){let t=``,n=0,r=0;for(r=0;r<e.length;r++)if(n=e[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r];break}for(r+=1;r<e.length;r++){if(n=e[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r]}return t}var p=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),m=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),h=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),g=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function _(e){if(e.length===0)return!1;for(let t=0;t<e.length;t++)if(!h(e[t])){if(e[t]===`%`&&t+2<e.length&&a(e.slice(t+1,t+3))){t+=2;continue}return!1}return!0}function v(e){let t=-1,n=0,r=-1,i=0;for(let a=0;a<e.length;a++)e[a]===`0`?(r===-1&&(r=a),i++,i>n&&(n=i,t=r)):(r=-1,i=0);if(n<2)return e.join(`:`);let a=e.slice(0,t).join(`:`),o=e.slice(t+n).join(`:`);return a+`::`+o}function y(e){let t=e.indexOf(`::`);if(t!==-1&&e.indexOf(`::`,t+1)!==-1)return;let n=t===-1?e.split(`:`):e.slice(0,t).split(`:`),i=t===-1?[]:e.slice(t+2).split(`:`);t!==-1&&(n.length===1&&n[0]===``&&(n.length=0),i.length===1&&i[0]===``&&(i.length=0));let a=n.concat(i),o=0;for(let e=0;e<a.length;e++){let n=a[e];if(n===``)return;if(n.indexOf(`.`)!==-1){if(e!==a.length-1||t!==-1&&i.length===0||!r(n))return;o+=2;continue}if(!p(n))return;a[e]=parseInt(n,16).toString(16),o++}if(t===-1)return o===8?v(a):void 0;if(o>=8)return;let s=a.slice(0,n.length);for(let e=o;e<8;e++)s.push(`0`);for(let e=n.length;e<a.length;e++)s.push(a[e]);return v(s)}function b(e){let t=e[0]===`[`&&e[e.length-1]===`]`;if((e[0]===`[`||e[e.length-1]===`]`)&&!t)return{host:e,isIPV6:!1,error:!0};let n=t?e.slice(1,-1):e;if(t&&m(n))return n=n.toLowerCase(),{host:`[${n}]`,escapedHost:n,isIPV6:!1,isIPVFuture:!0};if(x(n,`:`)<2)return{host:e,isIPV6:!1,error:t};let r=``,i=n.indexOf(`%`);if(i!==-1){let t=n.slice(i,i+3).toLowerCase()===`%25`?3:1;if(r=n.slice(i+t),!_(r))return{host:e,isIPV6:!1,error:!0};n=n.slice(0,i)}let a=y(n);return a===void 0?{host:e,isIPV6:!1,error:!0}:{host:a+(r?`%`+r:``),escapedHost:a+(r?`%25`+r:``),isIPV6:!0}}function x(e,t){let n=0;for(let r=0;r<e.length;r++)e[r]===t&&n++;return n}function ee(e){let t=e,n=[],r=-1,i=0;for(;i=t.length;){if(i===1){if(t===`.`)break;if(t===`/`){n.push(`/`);break}n.push(t);break}if(i===2){if(t[0]===`.`){if(t[1]===`.`)break;if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&(t[1]===`.`||t[1]===`/`)){n.push(`/`);break}}else if(i===3&&t===`/..`){n.length!==0&&n.pop(),n.push(`/`);break}if(t[0]===`.`){if(t[1]===`.`){if(t[2]===`/`){t=t.slice(3);continue}}else if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&t[1]===`.`){if(t[2]===`/`){t=t.slice(2);continue}if(t[2]===`.`&&t[3]===`/`){t=t.slice(3),n.length!==0&&n.pop();continue}}if((r=t.indexOf(`/`,1))===-1){n.push(t);break}n.push(t.slice(0,r)),t=t.slice(r)}return n.join(``)}var S={"@":`%40`,"/":`%2F`,"?":`%3F`,"#":`%23`,":":`%3A`},te=/[@/?#:]/g,ne=/[@/?#]/g;function re(e,t){let n=t?ne:te;return n.lastIndex=0,e.replace(n,e=>S[e])}function ie(e,t=!1){if(e.indexOf(`%`)===-1)return e;let n=``;for(let r=0;r<e.length;r++){if(e[r]===`%`&&r+2<e.length){let i=e.slice(r+1,r+3);if(a(i)){let e=i.toUpperCase(),a=String.fromCharCode(parseInt(e,16));t&&o(a)?n+=a:n+=`%`+e,r+=2;continue}}n+=e[r]}return n}function ae(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(r===`%`&&n+2<e.length){let r=e.slice(n+1,n+3);if(a(r)){let e=r.toUpperCase(),i=String.fromCharCode(parseInt(e,16));i!==`.`&&o(i)?t+=i:t+=`%`+e,n+=2;continue}}if(s(r))t+=r;else{let i=e.charCodeAt(n);if(i<128)t+=ce(i)?r:u[i];else if(i<55296||i>57343)t+=d(i);else if(i<=56319&&n+1<e.length){let r=e.charCodeAt(n+1);r>=56320&&r<=57343?(t+=d(65536+(i-55296<<10)+(r-56320)),n++):t+=d(65533)}else t+=d(65533)}}return t}function C(e,t=!1){let n=``,r=t&&e[0]!==`/`;for(let t=0;t<e.length;t++){let i=e[t];if(i===`%`&&t+2<e.length){let r=e.slice(t+1,t+3);if(a(r)){n+=`%`+r.toUpperCase(),t+=2;continue}}if(i===`/`&&(r=!1),s(i)&&(i!==`:`||!r))n+=i;else{let r=e.charCodeAt(t);if(r<128)n+=u[r];else if(r<55296||r>57343)n+=d(r);else if(r<=56319&&t+1<e.length){let i=e.charCodeAt(t+1);i>=56320&&i<=57343?(n+=d(65536+(r-55296<<10)+(i-56320)),t++):n+=d(65533)}else n+=d(65533)}}return n}function oe(e,t){let n=``;for(let r=0;r<e.length;r++){let i=e[r];if(i===`%`&&r+2<e.length){let t=e.slice(r+1,r+3);if(a(t)){n+=`%`+t.toUpperCase(),r+=2;continue}}if(t(i))n+=i;else{let t=e.charCodeAt(r);if(t<128)n+=u[t];else if(t<55296||t>57343)n+=d(t);else if(t<=56319&&r+1<e.length){let i=e.charCodeAt(r+1);i>=56320&&i<=57343?(n+=d(65536+(t-55296<<10)+(i-56320)),r++):n+=d(65533)}else n+=d(65533)}}return n}function w(e){return oe(e,l)}function se(e){return oe(e,c)}function T(e){return oe(e,c)}function ce(e){return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===42||e===43||e===45||e===46||e===47||e===64||e===95}function le(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(r===`%`&&n+2<e.length){let r=e.slice(n+1,n+3);if(a(r)){let e=r.toUpperCase(),i=String.fromCharCode(parseInt(e,16));o(i)?t+=i:t+=`%`+e,n+=2;continue}}if(c(r))t+=r;else{let i=e.charCodeAt(n);if(i<128)t+=ce(i)?r:u[i];else if(i<55296||i>57343)t+=d(i);else if(i<=56319&&n+1<e.length){let r=e.charCodeAt(n+1);r>=56320&&r<=57343?(t+=d(65536+(i-55296<<10)+(r-56320)),n++):t+=d(65533)}else t+=d(65533)}}return t}function ue(e){let t=``;for(let n=0;n<e.length;n++){if(e[n]===`%`&&n+2<e.length){let r=e.slice(n+1,n+3);if(a(r)){t+=`%`+r.toUpperCase(),n+=2;continue}}t+=escape(e[n])}return t}function de(e){let t=[];if(e.userinfo!==void 0&&(t.push(w(e.userinfo)),t.push(`@`)),e.host!==void 0){let n=e.host;if(!r(n)){let e=b(n);e.isIPV6!==!0&&e.isIPVFuture!==!0&&(n=ie(n,!0),e=b(n)),n=e.isIPV6===!0||e.isIPVFuture===!0?`[${e.escapedHost}]`:re(n,!1)}t.push(n)}if(typeof e.port==`number`||typeof e.port==`string`){let n=String(e.port);if(!i(n))throw TypeError(`URI port is malformed.`);t.push(`:`),t.push(n)}return t.length?t.join(``):void 0}t.exports={nonSimpleDomain:g,recomposeAuthority:de,reescapeHostDelimiters:re,normalizePercentEncoding:ie,normalizePathEncoding:ae,serializePathEncoding:C,normalizeQueryFragmentEncoding:le,encodeUserinfo:w,encodeQuery:se,encodeFragment:T,escapePreservingEscapes:ue,removeDotSegments:ee,isIPv4:r,isUUID:n,normalizeIPv6:b,stringArrayToHexStripped:f}})),cA=E(((e,t)=>{var{isUUID:n}=sA(),r=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,i=[`http`,`https`,`ws`,`wss`,`urn`,`urn:uuid`];function a(e){return i.indexOf(e)!==-1}function o(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]===`w`||e.scheme[0]===`W`)&&(e.scheme[1]===`s`||e.scheme[1]===`S`)&&(e.scheme[2]===`s`||e.scheme[2]===`S`):!1}function s(e){return e.host||(e.error=e.error||`HTTP URIs must have a host.`),e}function c(e){let t=String(e.scheme).toLowerCase()===`https`;return(e.port===(t?443:80)||e.port===``)&&(e.port=void 0),e.path||=`/`,e}function l(e){return e.secure=o(e),e.resourceName=(e.path||`/`)+(e.query?`?`+e.query:``),e.path=void 0,e.query=void 0,e}function u(e){if((e.port===(o(e)?443:80)||e.port===``)&&(e.port=void 0),typeof e.secure==`boolean`&&(e.scheme=e.secure?`wss`:`ws`,e.secure=void 0),e.resourceName){let t=e.resourceName.indexOf(`?`),n=t===-1?e.resourceName:e.resourceName.slice(0,t);e.path=n&&n!==`/`?n:void 0,e.query=t===-1?void 0:e.resourceName.slice(t+1),e.resourceName=void 0}return e.fragment=void 0,e}function d(e,t){if(!e.path)return e.error=`URN can not be parsed`,e;let n=e.path.match(r);if(n&&n[0]===e.path){let r=t.scheme||e.scheme||`urn`;e.nid=n[1].toLowerCase(),e.nss=n[2];let i=y(`${r}:${t.nid||e.nid}`);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||`URN can not be parsed.`;return e}function f(e,t){if(e.nid===void 0)throw Error(`URN without nid cannot be serialized`);let n=t.scheme||e.scheme||`urn`,r=e.nid.toLowerCase(),i=y(`${n}:${t.nid||r}`);i&&(e=i.serialize(e,t));let a=e,o=e.nss;return a.path=`${r||t.nid}:${o}`,t.skipEscape=!0,a}function p(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!n(r.uuid))&&(r.error=r.error||`UUID is not valid.`),r}function m(e){let t=e;return t.nss=(e.uuid||``).toLowerCase(),t}var h={scheme:`http`,domainHost:!0,parse:s,serialize:c},g={scheme:`https`,domainHost:h.domainHost,parse:s,serialize:c},_={scheme:`ws`,domainHost:!0,parse:l,serialize:u},v={http:h,https:g,ws:_,wss:{scheme:`wss`,domainHost:_.domainHost,parse:_.parse,serialize:_.serialize},urn:{scheme:`urn`,parse:d,serialize:f,skipNormalize:!0},"urn:uuid":{scheme:`urn:uuid`,parse:p,serialize:m,skipNormalize:!0}};Object.setPrototypeOf(v,null);function y(e){return e&&(v[e]||v[e.toLowerCase()])||void 0}t.exports={wsIsSecure:o,SCHEMES:v,isValidSchemeName:a,getSchemeHandler:y}})),lA=E(((e,t)=>{var{normalizeIPv6:n,removeDotSegments:r,recomposeAuthority:i,normalizePercentEncoding:a,normalizePathEncoding:o,serializePathEncoding:s,normalizeQueryFragmentEncoding:c,encodeQuery:l,encodeFragment:u,reescapeHostDelimiters:d,isIPv4:f,nonSimpleDomain:p}=sA(),{SCHEMES:m,getSchemeHandler:h}=cA(),g=/^[A-Za-z][A-Za-z0-9+.-]*$/u,_=`URI scheme is malformed.`;function v(e){let t=unescape(String(e));if(!g.test(t))throw TypeError(_);return t}function y(e,t){return typeof e==`string`?e=ce(e,t):typeof e==`object`&&(e=T(S(e,t),t)),e}function b(e,t,r){let i=r?Object.assign({scheme:`null`},r):{scheme:`null`},{parsed:a,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:c,malformedHost:l,malformedScheme:u}=se(e,i),{parsed:d,malformedAuthorityOrPort:p,malformedPercentEncoding:m,malformedSchemeSpecific:g,malformedHost:_,malformedScheme:v}=se(t,i);if(o||p||s||m||c||g||l||_||u||v)throw Error(a.error||d.error||`URI is malformed.`);let y=x(a,d,i,!0),b=h(r&&r.scheme||y.scheme),ee=y.host,te=ee!==void 0&&ee!==``&&(f(ee)||n(ee).isIPV6);w(y,r||{},b,te);let ne=ee&&ee.indexOf(`%`)!==-1&&!/\P{ASCII}/u.test(ee);if(y.error&&!ne)throw Error(y.error);return i.skipEscape=!0,S(y,i)}function x(e,t,n,i){let a={};return i||(e=T(S(e,n),n),t=T(S(t,n),n)),n||={},!n.tolerant&&t.scheme?(a.scheme=t.scheme,a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.path?(t.path[0]===`/`?a.path=r(t.path):(a.path=(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?`/`+t.path:e.path?e.path.slice(0,e.path.lastIndexOf(`/`)+1)+t.path:t.path,a.path=r(a.path)),a.query=t.query):(a.path=e.path,a.query=t.query===void 0?e.query:t.query),a.userinfo=e.userinfo,a.host=e.host,a.port=e.port),a.scheme=e.scheme),a.fragment=t.fragment,a}function ee(e,t,n){let r=ue(e,n),i=ue(t,n);return r!==void 0&&i!==void 0&&r===i}function S(e,t){let n={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:``},o=Object.assign({},t),c=[];n.scheme&&=v(n.scheme);let d=h(o.scheme||n.scheme);d&&d.serialize&&d.serialize(n,o);let f=n.userinfo!==void 0||n.host!==void 0||n.port!==void 0,p=!o.skipEscape&&n.scheme===void 0&&!f;n.path!==void 0&&(n.path=o.skipEscape?a(n.path):s(n.path,p)),o.reference!==`suffix`&&n.scheme&&(n.scheme=v(n.scheme),c.push(n.scheme,`:`));let m=i(n);if(m!==void 0&&(o.reference!==`suffix`&&c.push(`//`),c.push(m),n.path&&n.path[0]!==`/`&&c.push(`/`)),n.path!==void 0){let e=n.path;!o.absolutePath&&(!d||!d.absolutePath)&&(e=r(e)),p&&(e=s(e,!0)),m===void 0&&e[0]===`/`&&e[1]===`/`&&(e=`/%2F`+e.slice(2)),c.push(e)}return n.query!==void 0&&c.push(`?`,l(n.query)),n.fragment!==void 0&&c.push(`#`,u(n.fragment)),c.join(``)}var te=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,ne=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,re=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function ie(e,t){if(t[2]!==void 0&&e.path&&e.path[0]!==`/`)return`URI path must start with "/" when authority is present.`;if(typeof e.port==`number`&&(e.port<0||e.port>65535))return`URI port is malformed.`}function ae(e){if(e===void 0)return!1;let t=e.indexOf(`%`);for(;t!==-1;){if(t+2>=e.length||!/^[\da-f]{2}$/iu.test(e.slice(t+1,t+3)))return!0;t=e.indexOf(`%`,t+3)}return!1}function C(e){return e[0]===`[`&&e[e.length-1]===`]`}function oe(e){let t=e[4];return ae(e[3])||t!==void 0&&!C(t)&&ae(t)||ae(e[6])||ae(e[7])||ae(e[8])}function w(e,t,n,r){if(!t.unicodeSupport&&(!n||!n.unicodeSupport)&&e.host&&!C(e.host)&&(t.domainHost||n&&n.domainHost)&&r===!1&&p(e.host))try{e.host=new URL(`http://`+e.host).hostname}catch(t){return e.error=e.error||`Host's domain name can not be converted to ASCII: `+t,!0}return!1}function se(e,t){let r=Object.assign({},t),i={scheme:void 0,userinfo:void 0,host:``,port:void 0,path:``,query:void 0,fragment:void 0},s=!1,l=!1,u=!1,p=!1,v=!1,y=!1,b=!1;r.reference===`suffix`&&(e=r.scheme?r.scheme+`:`+e:`//`+e);let x=e.match(ne);x!==null&&x[1].indexOf(`\\`)!==-1&&(i.error=`URI authority must not contain a literal backslash.`,s=!0);let ee=e.match(re);if(ee!==null){let e=ee[1],t=e.replace(/[\t\n\r]/g,``);t.length>=2&&(t.slice(0,2)===`//`?e.length!==t.length&&(i.error=i.error||`URI authority introducer must not contain whitespace.`,s=!0):(i.error=i.error||`URI authority must not contain a literal backslash.`,s=!0))}let S=e.match(te);if(S){if(i.scheme=S[1],i.userinfo=S[3],i.host=S[4],i.port=parseInt(S[5],10),i.path=S[6]||``,i.query=S[7],i.fragment=S[8],i.scheme!==void 0){let e=unescape(i.scheme);g.test(e)?i.scheme=e.toLowerCase():(i.error=i.error||_,y=!0)}l=oe(S),l&&(i.error=i.error||`URI contains malformed percent-encoding.`),isNaN(i.port)&&(i.port=S[5]);let t=ie(i,S);if(t!==void 0&&(i.error=i.error||t,s=!0),i.host){if(f(i.host)===!1){let e=C(i.host),t=i.host.indexOf(`[`)!==-1||i.host.indexOf(`]`)!==-1,r=n(i.host);b=r.isIPV6||r.isIPVFuture===!0,v=t&&(!e||r.error===!0),i.host=b?r.host:r.host.toLowerCase(),v&&(i.error=i.error||`URI host is malformed.`,s=!0)}else b=!0}i.reference=i.scheme===void 0&&i.userinfo===void 0&&i.host===void 0&&i.port===void 0&&i.query===void 0&&!i.path?`same-document`:i.scheme===void 0?`relative`:i.fragment===void 0?`absolute`:`uri`,r.reference&&r.reference!==`suffix`&&r.reference!==i.reference&&(i.error=i.error||`URI is not a `+r.reference+` reference.`);let x=h(r.scheme||i.scheme);if(v||(p=w(i,r,x,b)),e.indexOf(`%`)!==-1&&i.host!==void 0&&!v){let e=b?i.host:a(i.host,!0);b||(e=a(e.toLowerCase())),i.host=d(e,b)}(!x||x&&!x.skipNormalize)&&(i.path&&=o(i.path),i.query&&=c(i.query),i.fragment&&=c(i.fragment)),x&&x.parse&&(x.parse(i,r),x===m.urn&&i.nid===void 0&&(u=!0))}else i.error=i.error||`URI can not be parsed.`;return{parsed:i,malformedAuthorityOrPort:s,malformedPercentEncoding:l,malformedSchemeSpecific:u,malformedHost:p,malformedScheme:y}}function T(e,t){return se(e,t).parsed}function ce(e,t){return le(e,t).normalized}function le(e,t){let{parsed:n,malformedAuthorityOrPort:r,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:o,malformedScheme:s}=se(e,t);return{normalized:r||i||a||o||s?e:S(n,t),malformedAuthorityOrPort:r,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:o,malformedScheme:s}}function ue(e,t){if(typeof e!=`string`&&typeof e!=`object`)return;let n;try{n=typeof e==`string`?e:S(e,t)}catch{return}let{normalized:r,malformedAuthorityOrPort:i,malformedPercentEncoding:a,malformedSchemeSpecific:o,malformedHost:s,malformedScheme:c}=le(n,t);return i||a||o||s||c?void 0:r}var de={SCHEMES:m,normalize:y,resolve:b,resolveComponent:x,equal:ee,serialize:S,parse:T};t.exports=de,t.exports.default=de,t.exports.fastUri=de})),uA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=lA();t.code=`require("ajv/dist/runtime/uri").default`,e.default=t})),dA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=Yk();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var n=$();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return n.CodeGen}});var r=Xk(),i=Zk(),a=zk(),o=Qk(),s=$(),c=Jk(),l=Vk(),u=Fk(),d=(oA(),je($k).default),f=uA(),p=(e,t)=>new RegExp(e,t);p.code=`new RegExp`;var m=[`removeAdditional`,`useDefaults`,`coerceTypes`],h=new Set([`validate`,`serialize`,`parse`,`wrapper`,`root`,`schema`,`keyword`,`pattern`,`formats`,`validate$data`,`func`,`obj`,`Error`]),g={errorDataPath:``,format:"`validateFormats: false` can be used instead.",nullable:`"nullable" keyword is supported by default.`,jsonPointers:`Deprecated jsPropertySyntax can be used instead.`,extendRefs:`Deprecated ignoreKeywordsWithRef can be used instead.`,missingRefs:`Pass empty schema with $id that should be ignored to ajv.addSchema.`,processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:`"uniqueItems" keyword is always validated.`,unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:`Map is used as cache, schema object as key.`,serialize:`Map is used as cache, schema object as key.`,ajvErrors:`It is default now.`},_={ignoreKeywordsWithRef:``,jsPropertySyntax:``,unicode:`"minLength"/"maxLength" account for unicode characters by default.`},v=200;function y(e){let t=e.strict,n=e.code?.optimize,r=n===!0||n===void 0?1:n||0,i=e.code?.regExp??p,a=e.uriResolver??f.default;return{strictSchema:e.strictSchema??t??!0,strictNumbers:e.strictNumbers??t??!0,strictTypes:e.strictTypes??t??`log`,strictTuples:e.strictTuples??t??`log`,strictRequired:e.strictRequired??t??!1,code:e.code?{...e.code,optimize:r,regExp:i}:{optimize:r,regExp:i},loopRequired:e.loopRequired??v,loopEnum:e.loopEnum??v,meta:e.meta??!0,messages:e.messages??!0,inlineRefs:e.inlineRefs??!0,schemaId:e.schemaId??`$id`,addUsedSchema:e.addUsedSchema??!0,validateSchema:e.validateSchema??!0,validateFormats:e.validateFormats??!0,unicodeRegExp:e.unicodeRegExp??!0,int32range:e.int32range??!0,uriResolver:a}}var b=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...y(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new s.ValueScope({scope:{},prefixes:h,es5:t,lines:n}),this.logger=ae(e.logger);let r=e.validateFormats;e.validateFormats=!1,this.RULES=(0,a.getRules)(),x.call(this,g,e,`NOT SUPPORTED`),x.call(this,_,e,`DEPRECATED`,`warn`),this._metaOpts=re.call(this),e.formats&&te.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&ne.call(this,e.keywords),typeof e.meta==`object`&&this.addMetaSchema(e.meta),S.call(this),e.validateFormats=r}_addVocabularies(){this.addKeyword(`$async`)}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,r=d;n===`id`&&(r={...d},r.id=r.$id,delete r.$id),t&&e&&this.addMetaSchema(r,r[n],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e==`object`?e[t]||e:void 0}validate(e,t){let n;if(typeof e==`string`){if(n=this.getSchema(e),!n)throw Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let r=n(t);return`$async`in n||(this.errors=n.errors),r}compile(e,t){let n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if(typeof this.opts.loadSchema!=`function`)throw Error(`options.loadSchema should be a function`);let{loadSchema:n}=this.opts;return r.call(this,e,t);async function r(e,t){await a.call(this,e.$schema);let n=this._addSchema(e,t);return n.validate||o.call(this,n)}async function a(e){e&&!this.getSchema(e)&&await r.call(this,{$ref:e},!0)}async function o(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof i.default))throw t;return s.call(this,t),await c.call(this,t.missingSchema),o.call(this,e)}}function s({missingSchema:e,missingRef:t}){if(this.refs[e])throw Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function c(e){let n=await l.call(this,e);this.refs[e]||await a.call(this,n.$schema),this.refs[e]||this.addSchema(n,e,t)}async function l(e){let t=this._loading[e];if(t)return t;try{return await(this._loading[e]=n(e))}finally{delete this._loading[e]}}}addSchema(e,t,n,r=this.opts.validateSchema){if(Array.isArray(e)){for(let t of e)this.addSchema(t,void 0,n,r);return this}let i;if(typeof e==`object`){let{schemaId:t}=this.opts;if(i=e[t],i!==void 0&&typeof i!=`string`)throw Error(`schema ${t} must be string`)}return t=(0,c.normalizeId)(t||i),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,r,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if(typeof e==`boolean`)return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!=`string`)throw Error(`$schema must be a string`);if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn(`meta-schema not available`),this.errors=null,!0;let r=this.validate(n,e);if(!r&&t){let e=`schema is invalid: `+this.errorsText();if(this.opts.validateSchema===`log`)this.logger.error(e);else throw Error(e)}return r}getSchema(e){let t;for(;typeof(t=ee.call(this,e))==`string`;)e=t;if(t===void 0){let{schemaId:n}=this.opts,r=new o.SchemaEnv({schema:{},schemaId:n});if(t=o.resolveSchema.call(this,r,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case`undefined`:return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case`string`:{let t=ee.call(this,e);return typeof t==`object`&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case`object`:{let t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,c.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw Error(`ajv.removeSchema: invalid parameter`)}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if(typeof e==`string`)n=e,typeof t==`object`&&(this.logger.warn(`these parameters are deprecated, see docs for addKeyword`),t.keyword=n);else if(typeof e==`object`&&t===void 0){if(t=e,n=t.keyword,Array.isArray(n)&&!n.length)throw Error(`addKeywords: keyword must be string or non-empty array`)}else throw Error(`invalid addKeywords parameters`);if(oe.call(this,n,t),!t)return(0,u.eachItem)(n,e=>w.call(this,e)),this;T.call(this,t);let r={...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)};return(0,u.eachItem)(n,r.type.length===0?e=>w.call(this,e,r):e=>r.type.forEach(t=>w.call(this,e,r,t))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t==`object`?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let n of t.rules){let t=n.rules.findIndex(t=>t.keyword===e);t>=0&&n.rules.splice(t,1)}return this}addFormat(e,t){return typeof t==`string`&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=`, `,dataVar:n=`data`}={}){return!e||e.length===0?`No errors`:e.map(e=>`${n}${e.instancePath} ${e.message}`).reduce((e,n)=>e+t+n)}$dataMetaSchema(e,t){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let r of t){let t=r.split(`/`).slice(1),i=e;for(let e of t)i=i[e];for(let e in n){let t=n[e];if(typeof t!=`object`)continue;let{$data:r}=t.definition,a=i[e];r&&a&&(i[e]=le(a))}}return e}_removeAllSchemas(e,t){for(let n in e){let r=e[n];(!t||t.test(n))&&(typeof r==`string`?delete e[n]:r&&!r.meta&&(this._cache.delete(r.schema),delete e[n]))}}_addSchema(e,t,n,r=this.opts.validateSchema,i=this.opts.addUsedSchema){let a,{schemaId:s}=this.opts;if(typeof e==`object`)a=e[s];else if(this.opts.jtd)throw Error(`schema must be object`);else if(typeof e!=`boolean`)throw Error(`schema must be object or boolean`);let l=this._cache.get(e);if(l!==void 0)return l;n=(0,c.normalizeId)(a||n);let u=c.getSchemaRefs.call(this,e,n);return l=new o.SchemaEnv({schema:e,schemaId:s,meta:t,baseId:n,localRefs:u}),this._cache.set(l.schema,l),i&&!n.startsWith(`#`)&&(n&&this._checkUnique(n),this.refs[n]=l),r&&this.validateSchema(e,!0),l}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):o.compileSchema.call(this,e),!e.validate)throw Error(`ajv implementation error`);return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{o.compileSchema.call(this,e)}finally{this.opts=t}}};b.ValidationError=r.default,b.MissingRefError=i.default,e.default=b;function x(e,t,n,r=`error`){for(let i in e){let a=i;a in t&&this.logger[r](`${n}: option ${i}. ${e[a]}`)}}function ee(e){return e=(0,c.normalizeId)(e),this.schemas[e]||this.refs[e]}function S(){let e=this.opts.schemas;if(e){if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}}function te(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function ne(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn(`keywords option as map is deprecated, pass array`);for(let t in e){let n=e[t];n.keyword||=t,this.addKeyword(n)}}function re(){let e={...this.opts};for(let t of m)delete e[t];return e}var ie={log(){},warn(){},error(){}};function ae(e){if(e===!1)return ie;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw Error(`logger must implement log, warn and error methods`)}var C=/^[a-z_$][a-z0-9_$:-]*$/i;function oe(e,t){let{RULES:n}=this;if((0,u.eachItem)(e,e=>{if(n.keywords[e])throw Error(`Keyword ${e} is already defined`);if(!C.test(e))throw Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!(`code`in t||`validate`in t))throw Error(`$data keyword must have "code" or "validate" function`)}function w(e,t,n){var r;let i=t?.post;if(n&&i)throw Error(`keyword with "post" flag cannot have "type"`);let{RULES:a}=this,o=i?a.post:a.rules.find(({type:e})=>e===n);if(o||(o={type:n,rules:[]},a.rules.push(o)),a.keywords[e]=!0,!t)return;let s={keyword:e,definition:{...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)}};t.before?se.call(this,o,s,t.before):o.rules.push(s),a.all[e]=s,(r=t.implements)==null||r.forEach(e=>this.addKeyword(e))}function se(e,t,n){let r=e.rules.findIndex(e=>e.keyword===n);r>=0?e.rules.splice(r,0,t):(e.rules.push(t),this.logger.warn(`rule ${n} is not defined`))}function T(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=le(t)),e.validateSchema=this.compile(t,!0))}var ce={$ref:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`};function le(e){return{anyOf:[e,ce]}}})),fA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`id`,code(){throw Error(`NOT SUPPORTED: keyword "id", use "$id" for schema ID`)}}})),pA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.callRef=e.getValidate=void 0;var t=Zk(),n=Uk(),r=$(),i=Ik(),a=Qk(),o=Fk(),s={keyword:`$ref`,schemaType:`string`,code(e){let{gen:n,schema:i,it:o}=e,{baseId:s,schemaEnv:u,validateName:d,opts:f,self:p}=o,{root:m}=u;if((i===`#`||i===`#/`)&&s===m.baseId)return g();let h=a.resolveRef.call(p,m,s,i);if(h===void 0)throw new t.default(o.opts.uriResolver,s,i);return h instanceof a.SchemaEnv?_(h):v(h);function g(){if(u===m)return l(e,d,u,u.$async);let t=n.scopeValue(`root`,{ref:m});return l(e,(0,r._)`${t}.validate`,m,m.$async)}function _(t){l(e,c(e,t),t,t.$async)}function v(t){let a=n.scopeValue(`schema`,f.code.source===!0?{ref:t,code:(0,r.stringify)(t)}:{ref:t}),o=n.name(`valid`),s=e.subschema({schema:t,dataTypes:[],schemaPath:r.nil,topSchemaRef:a,errSchemaPath:i},o);e.mergeEvaluated(s),e.ok(o)}}};function c(e,t){let{gen:n}=e;return t.validate?n.scopeValue(`validate`,{ref:t.validate}):(0,r._)`${n.scopeValue(`wrapper`,{ref:t})}.validate`}e.getValidate=c;function l(e,t,a,s){let{gen:c,it:l}=e,{allErrors:u,schemaEnv:d,opts:f}=l,p=f.passContext?i.default.this:r.nil;s?m():h();function m(){if(!d.$async)throw Error(`async schema referenced by sync schema`);let i=c.let(`valid`);c.try(()=>{c.code((0,r._)`await ${(0,n.callValidateCode)(e,t,p)}`),_(t),u||c.assign(i,!0)},e=>{c.if((0,r._)`!(${e} instanceof ${l.ValidationError})`,()=>c.throw(e)),g(e),u||c.assign(i,!1)}),e.ok(i)}function h(){e.result((0,n.callValidateCode)(e,t,p),()=>_(t),()=>g(t))}function g(e){let t=(0,r._)`${e}.errors`;c.assign(i.default.vErrors,(0,r._)`${i.default.vErrors} === null ? ${t} : ${i.default.vErrors}.concat(${t})`),c.assign(i.default.errors,(0,r._)`${i.default.vErrors}.length`)}function _(e){if(!l.opts.unevaluated)return;let t=a?.validate?.evaluated;if(l.props!==!0){if(t&&!t.dynamicProps)t.props!==void 0&&(l.props=o.mergeEvaluated.props(c,t.props,l.props));else{let t=c.var(`props`,(0,r._)`${e}.evaluated.props`);l.props=o.mergeEvaluated.props(c,t,l.props,r.Name)}}if(l.items!==!0){if(t&&!t.dynamicItems)t.items!==void 0&&(l.items=o.mergeEvaluated.items(c,t.items,l.items));else{let t=c.var(`items`,(0,r._)`${e}.evaluated.items`);l.items=o.mergeEvaluated.items(c,t,l.items,r.Name)}}}}e.callRef=l,e.default=s})),mA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=fA(),n=pA();e.default=[`$schema`,`$id`,`$defs`,`$vocabulary`,{keyword:`$comment`},`definitions`,t.default,n.default]})),hA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=t.operators,r={maximum:{okStr:`<=`,ok:n.LTE,fail:n.GT},minimum:{okStr:`>=`,ok:n.GTE,fail:n.LT},exclusiveMaximum:{okStr:`<`,ok:n.LT,fail:n.GTE},exclusiveMinimum:{okStr:`>`,ok:n.GT,fail:n.LTE}};e.default={keyword:Object.keys(r),type:`number`,schemaType:`number`,$data:!0,error:{message:({keyword:e,schemaCode:n})=>(0,t.str)`must be ${r[e].okStr} ${n}`,params:({keyword:e,schemaCode:n})=>(0,t._)`{comparison: ${r[e].okStr}, limit: ${n}}`},code(e){let{keyword:n,data:i,schemaCode:a}=e;e.fail$data((0,t._)`${i} ${r[n].fail} ${a} || isNaN(${i})`)}}})),gA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$();e.default={keyword:`multipleOf`,type:`number`,schemaType:`number`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,t._)`{multipleOf: ${e}}`},code(e){let{gen:n,data:r,schemaCode:i,it:a}=e,o=a.opts.multipleOfPrecision,s=n.let(`res`),c=o?(0,t._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${o}`:(0,t._)`${s} !== parseInt(${s})`;e.fail$data((0,t._)`(${i} === 0 || (${s} = ${r}/${i}, ${c}))`)}}})),_A=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e){let t=e.length,n=0,r=0,i;for(;r<t;)n++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<t&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return n}e.default=t,t.code=`require("ajv/dist/runtime/ucs2length").default`})),vA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=Fk(),r=_A();e.default={keyword:[`maxLength`,`minLength`],type:`string`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxLength`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} characters`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:i,data:a,schemaCode:o,it:s}=e,c=i===`maxLength`?t.operators.GT:t.operators.LT,l=s.opts.unicode===!1?(0,t._)`${a}.length`:(0,t._)`${(0,n.useFunc)(e.gen,r.default)}(${a})`;e.fail$data((0,t._)`${l} ${c} ${o}`)}}})),yA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Uk(),n=Fk(),r=$();e.default={keyword:`pattern`,type:`string`,schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,r.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,r._)`{pattern: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e,u=l.opts.unicodeRegExp?`u`:``;if(o){let{regExp:t}=l.opts.code,o=t.code===`new RegExp`?(0,r._)`new RegExp`:(0,n.useFunc)(i,t),s=i.let(`valid`);i.try(()=>i.assign(s,(0,r._)`${o}(${c}, ${u}).test(${a})`),()=>i.assign(s,!1)),e.fail$data((0,r._)`!${s}`)}else{let n=(0,t.usePattern)(e,s);e.fail$data((0,r._)`!${n}.test(${a})`)}}}})),bA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$();e.default={keyword:[`maxProperties`,`minProperties`],type:`object`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxProperties`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} properties`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxProperties`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`Object.keys(${r}).length ${a} ${i}`)}}})),xA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Uk(),n=$(),r=Fk();e.default={keyword:`required`,type:`object`,schemaType:`array`,$data:!0,error:{message:({params:{missingProperty:e}})=>(0,n.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,n._)`{missingProperty: ${e}}`},code(e){let{gen:i,schema:a,schemaCode:o,data:s,$data:c,it:l}=e,{opts:u}=l;if(!c&&a.length===0)return;let d=a.length>=u.loopRequired;if(l.allErrors?f():p(),u.strictRequired){let t=e.parentSchema.properties,{definedProperties:n}=e.it;for(let e of a)if(t?.[e]===void 0&&!n.has(e)){let t=`required property "${e}" is not defined at "${l.schemaEnv.baseId+l.errSchemaPath}" (strictRequired)`;(0,r.checkStrictMode)(l,t,l.opts.strictRequired)}}function f(){if(d||c)e.block$data(n.nil,m);else for(let n of a)(0,t.checkReportMissingProp)(e,n)}function p(){let n=i.let(`missing`);if(d||c){let t=i.let(`valid`,!0);e.block$data(t,()=>h(n,t)),e.ok(t)}else i.if((0,t.checkMissingProp)(e,a,n)),(0,t.reportMissingProp)(e,n),i.else()}function m(){i.forOf(`prop`,o,n=>{e.setParams({missingProperty:n}),i.if((0,t.noPropertyInData)(i,s,n,u.ownProperties),()=>e.error())})}function h(r,a){e.setParams({missingProperty:r}),i.forOf(r,o,()=>{i.assign(a,(0,t.propertyInData)(i,s,r,u.ownProperties)),i.if((0,n.not)(a),()=>{e.error(),i.break()})},n.nil)}}}})),SA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$();e.default={keyword:[`maxItems`,`minItems`],type:`array`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxItems`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} items`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxItems`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`${r}.length ${a} ${i}`)}}})),CA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Kk();t.code=`require("ajv/dist/runtime/equal").default`,e.default=t})),wA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Vk(),n=$(),r=Fk(),i=CA();e.default={keyword:`uniqueItems`,type:`array`,schemaType:`boolean`,$data:!0,error:{message:({params:{i:e,j:t}})=>(0,n.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,n._)`{i: ${e}, j: ${t}}`},code(e){let{gen:a,data:o,$data:s,schema:c,parentSchema:l,schemaCode:u,it:d}=e;if(!s&&!c)return;let f=a.let(`valid`),p=l.items?(0,t.getSchemaTypes)(l.items):[];e.block$data(f,m,(0,n._)`${u} === false`),e.ok(f);function m(){let t=a.let(`i`,(0,n._)`${o}.length`),r=a.let(`j`);e.setParams({i:t,j:r}),a.assign(f,!0),a.if((0,n._)`${t} > 1`,()=>(h()?g:_)(t,r))}function h(){return p.length>0&&!p.some(e=>e===`object`||e===`array`)}function g(r,i){let s=a.name(`item`),c=(0,t.checkDataTypes)(p,s,d.opts.strictNumbers,t.DataType.Wrong),l=a.const(`indices`,(0,n._)`{}`);a.for((0,n._)`;${r}--;`,()=>{a.let(s,(0,n._)`${o}[${r}]`),a.if(c,(0,n._)`continue`),p.length>1&&a.if((0,n._)`typeof ${s} == "string"`,(0,n._)`${s} += "_"`),a.if((0,n._)`typeof ${l}[${s}] == "number"`,()=>{a.assign(i,(0,n._)`${l}[${s}]`),e.error(),a.assign(f,!1).break()}).code((0,n._)`${l}[${s}] = ${r}`)})}function _(t,s){let c=(0,r.useFunc)(a,i.default),l=a.name(`outer`);a.label(l).for((0,n._)`;${t}--;`,()=>a.for((0,n._)`${s} = ${t}; ${s}--;`,()=>a.if((0,n._)`${c}(${o}[${t}], ${o}[${s}])`,()=>{e.error(),a.assign(f,!1).break(l)})))}}}})),TA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=Fk(),r=CA();e.default={keyword:`const`,$data:!0,error:{message:`must be equal to constant`,params:({schemaCode:e})=>(0,t._)`{allowedValue: ${e}}`},code(e){let{gen:i,data:a,$data:o,schemaCode:s,schema:c}=e;o||c&&typeof c==`object`?e.fail$data((0,t._)`!${(0,n.useFunc)(i,r.default)}(${a}, ${s})`):e.fail((0,t._)`${c} !== ${a}`)}}})),EA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=Fk(),r=CA();e.default={keyword:`enum`,schemaType:`array`,$data:!0,error:{message:`must be equal to one of the allowed values`,params:({schemaCode:e})=>(0,t._)`{allowedValues: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e;if(!o&&s.length===0)throw Error(`enum must have non-empty array`);let u=s.length>=l.opts.loopEnum,d,f=()=>d??=(0,n.useFunc)(i,r.default),p;if(u||o)p=i.let(`valid`),e.block$data(p,m);else{if(!Array.isArray(s))throw Error(`ajv implementation error`);let e=i.const(`vSchema`,c);p=(0,t.or)(...s.map((t,n)=>h(e,n)))}e.pass(p);function m(){i.assign(p,!1),i.forOf(`v`,c,e=>i.if((0,t._)`${f()}(${a}, ${e})`,()=>i.assign(p,!0).break()))}function h(e,n){let r=s[n];return typeof r==`object`&&r?(0,t._)`${f()}(${a}, ${e}[${n}])`:(0,t._)`${a} === ${r}`}}}})),DA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=hA(),n=gA(),r=vA(),i=yA(),a=bA(),o=xA(),s=SA(),c=wA(),l=TA(),u=EA();e.default=[t.default,n.default,r.default,i.default,a.default,o.default,s.default,c.default,{keyword:`type`,schemaType:[`string`,`array`]},{keyword:`nullable`,schemaType:`boolean`},l.default,u.default]})),OA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateAdditionalItems=void 0;var t=$(),n=Fk(),r={keyword:`additionalItems`,type:`array`,schemaType:[`boolean`,`object`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{parentSchema:t,it:r}=e,{items:a}=t;if(!Array.isArray(a)){(0,n.checkStrictMode)(r,`"additionalItems" is ignored when "items" is not an array of schemas`);return}i(e,a)}};function i(e,r){let{gen:i,schema:a,data:o,keyword:s,it:c}=e;c.items=!0;let l=i.const(`len`,(0,t._)`${o}.length`);if(a===!1)e.setParams({len:r.length}),e.pass((0,t._)`${l} <= ${r.length}`);else if(typeof a==`object`&&!(0,n.alwaysValidSchema)(c,a)){let n=i.var(`valid`,(0,t._)`${l} <= ${r.length}`);i.if((0,t.not)(n),()=>u(n)),e.ok(n)}function u(a){i.forRange(`i`,r.length,l,r=>{e.subschema({keyword:s,dataProp:r,dataPropType:n.Type.Num},a),c.allErrors||i.if((0,t.not)(a),()=>i.break())})}}e.validateAdditionalItems=i,e.default=r})),kA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateTuple=void 0;var t=$(),n=Fk(),r=Uk(),i={keyword:`items`,type:`array`,schemaType:[`object`,`array`,`boolean`],before:`uniqueItems`,code(e){let{schema:t,it:i}=e;if(Array.isArray(t))return a(e,`additionalItems`,t);i.items=!0,!(0,n.alwaysValidSchema)(i,t)&&e.ok((0,r.validateArray)(e))}};function a(e,r,i=e.schema){let{gen:a,parentSchema:o,data:s,keyword:c,it:l}=e;f(o),l.opts.unevaluated&&i.length&&l.items!==!0&&(l.items=n.mergeEvaluated.items(a,i.length,l.items));let u=a.name(`valid`),d=a.const(`len`,(0,t._)`${s}.length`);i.forEach((r,i)=>{(0,n.alwaysValidSchema)(l,r)||(a.if((0,t._)`${d} > ${i}`,()=>e.subschema({keyword:c,schemaProp:i,dataProp:i},u)),e.ok(u))});function f(e){let{opts:t,errSchemaPath:a}=l,o=i.length,s=o===e.minItems&&(o===e.maxItems||e[r]===!1);if(t.strictTuples&&!s){let e=`"${c}" is ${o}-tuple, but minItems or maxItems/${r} are not specified or different at path "${a}"`;(0,n.checkStrictMode)(l,e,t.strictTuples)}}}e.validateTuple=a,e.default=i})),AA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=kA();e.default={keyword:`prefixItems`,type:`array`,schemaType:[`array`],before:`uniqueItems`,code:e=>(0,t.validateTuple)(e,`items`)}})),jA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=Fk(),r=Uk(),i=OA();e.default={keyword:`items`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{schema:t,parentSchema:a,it:o}=e,{prefixItems:s}=a;o.items=!0,!(0,n.alwaysValidSchema)(o,t)&&(s?(0,i.validateAdditionalItems)(e,s):e.ok((0,r.validateArray)(e)))}}})),MA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=Fk();e.default={keyword:`contains`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,trackErrors:!0,error:{message:({params:{min:e,max:n}})=>n===void 0?(0,t.str)`must contain at least ${e} valid item(s)`:(0,t.str)`must contain at least ${e} and no more than ${n} valid item(s)`,params:({params:{min:e,max:n}})=>n===void 0?(0,t._)`{minContains: ${e}}`:(0,t._)`{minContains: ${e}, maxContains: ${n}}`},code(e){let{gen:r,schema:i,parentSchema:a,data:o,it:s}=e,c,l,{minContains:u,maxContains:d}=a;s.opts.next?(c=u===void 0?1:u,l=d):c=1;let f=r.const(`len`,(0,t._)`${o}.length`);if(e.setParams({min:c,max:l}),l===void 0&&c===0){(0,n.checkStrictMode)(s,`"minContains" == 0 without "maxContains": "contains" keyword ignored`);return}if(l!==void 0&&c>l){(0,n.checkStrictMode)(s,`"minContains" > "maxContains" is always invalid`),e.fail();return}if((0,n.alwaysValidSchema)(s,i)){let n=(0,t._)`${f} >= ${c}`;l!==void 0&&(n=(0,t._)`${n} && ${f} <= ${l}`),e.pass(n);return}s.items=!0;let p=r.name(`valid`);l===void 0&&c===1?h(p,()=>r.if(p,()=>r.break())):c===0?(r.let(p,!0),l!==void 0&&r.if((0,t._)`${o}.length > 0`,m)):(r.let(p,!1),m()),e.result(p,()=>e.reset());function m(){let e=r.name(`_valid`),t=r.let(`count`,0);h(e,()=>r.if(e,()=>g(t)))}function h(t,i){r.forRange(`i`,0,f,r=>{e.subschema({keyword:`contains`,dataProp:r,dataPropType:n.Type.Num,compositeRule:!0},t),i()})}function g(e){r.code((0,t._)`${e}++`),l===void 0?r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0).break()):(r.if((0,t._)`${e} > ${l}`,()=>r.assign(p,!1).break()),c===1?r.assign(p,!0):r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0)))}}}})),NA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;var t=$(),n=Fk(),r=Uk();e.error={message:({params:{property:e,depsCount:n,deps:r}})=>{let i=n===1?`property`:`properties`;return(0,t.str)`must have ${i} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:n,deps:r,missingProperty:i}})=>(0,t._)`{property: ${e},
|
|
303
303
|
missingProperty: ${i},
|
|
304
304
|
depsCount: ${n},
|
|
305
|
-
deps: ${r}}`};var i={keyword:`dependencies`,type:`object`,schemaType:`object`,error:e.error,code(e){let[t,n]=a(e);o(e,t),s(e,n)}};function a({schema:e}){let t={},n={};for(let r in e){if(r===`__proto__`)continue;let i=Array.isArray(e[r])?t:n;i[r]=e[r]}return[t,n]}function o(e,n=e.schema){let{gen:i,data:a,it:o}=e;if(Object.keys(n).length===0)return;let s=i.let(`missing`);for(let c in n){let l=n[c];if(l.length===0)continue;let u=(0,r.propertyInData)(i,a,c,o.opts.ownProperties);e.setParams({property:c,depsCount:l.length,deps:l.join(`, `)}),o.allErrors?i.if(u,()=>{for(let t of l)(0,r.checkReportMissingProp)(e,t)}):(i.if((0,t._)`${u} && (${(0,r.checkMissingProp)(e,l,s)})`),(0,r.reportMissingProp)(e,s),i.else())}}e.validatePropertyDeps=o;function s(e,t=e.schema){let{gen:i,data:a,keyword:o,it:s}=e,c=i.name(`valid`);for(let l in t)(0,n.alwaysValidSchema)(s,t[l])||(i.if((0,r.propertyInData)(i,a,l,s.opts.ownProperties),()=>{let t=e.subschema({keyword:o,schemaProp:l},c);e.mergeValidEvaluated(t,c)},()=>i.var(c,!0)),e.ok(c))}e.validateSchemaDeps=s,e.default=i})),NA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=Pk();e.default={keyword:`propertyNames`,type:`object`,schemaType:[`object`,`boolean`],error:{message:`property name must be valid`,params:({params:e})=>(0,t._)`{propertyName: ${e.propertyName}}`},code(e){let{gen:r,schema:i,data:a,it:o}=e;if((0,n.alwaysValidSchema)(o,i))return;let s=r.name(`valid`);r.forIn(`key`,a,n=>{e.setParams({propertyName:n}),e.subschema({keyword:`propertyNames`,data:n,dataTypes:[`string`],propertyName:n,compositeRule:!0},s),r.if((0,t.not)(s),()=>{e.error(!0),o.allErrors||r.break()})}),e.ok(s)}}})),PA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Hk(),n=$(),r=Fk(),i=Pk();e.default={keyword:`additionalProperties`,type:[`object`],schemaType:[`boolean`,`object`],allowUndefined:!0,trackErrors:!0,error:{message:`must NOT have additional properties`,params:({params:e})=>(0,n._)`{additionalProperty: ${e.additionalProperty}}`},code(e){let{gen:a,schema:o,parentSchema:s,data:c,errsCount:l,it:u}=e;if(!l)throw Error(`ajv implementation error`);let{allErrors:d,opts:f}=u;if(u.props=!0,f.removeAdditional!==`all`&&(0,i.alwaysValidSchema)(u,o))return;let p=(0,t.allSchemaProperties)(s.properties),m=(0,t.allSchemaProperties)(s.patternProperties);h(),e.ok((0,n._)`${l} === ${r.default.errors}`);function h(){a.forIn(`key`,c,e=>{!p.length&&!m.length?v(e):a.if(g(e),()=>v(e))})}function g(r){let o;if(p.length>8){let e=(0,i.schemaRefOrVal)(u,s.properties,`properties`);o=(0,t.isOwnProperty)(a,e,r)}else o=p.length?(0,n.or)(...p.map(e=>(0,n._)`${r} === ${e}`)):n.nil;return m.length&&(o=(0,n.or)(o,...m.map(i=>(0,n._)`${(0,t.usePattern)(e,i)}.test(${r})`))),(0,n.not)(o)}function _(e){a.code((0,n._)`delete ${c}[${e}]`)}function v(t){if(f.removeAdditional===`all`||f.removeAdditional&&o===!1){_(t);return}if(o===!1){e.setParams({additionalProperty:t}),e.error(),d||a.break();return}if(typeof o==`object`&&!(0,i.alwaysValidSchema)(u,o)){let r=a.name(`valid`);f.removeAdditional===`failing`?(y(t,r,!1),a.if((0,n.not)(r),()=>{e.reset(),_(t)})):(y(t,r),d||a.if((0,n.not)(r),()=>a.break()))}}function y(t,n,r){let a={keyword:`additionalProperties`,dataProp:t,dataPropType:i.Type.Str};r===!1&&Object.assign(a,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(a,n)}}}})),FA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Jk(),n=Hk(),r=Pk(),i=PA();e.default={keyword:`properties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,parentSchema:s,data:c,it:l}=e;l.opts.removeAdditional===`all`&&s.additionalProperties===void 0&&i.default.code(new t.KeywordCxt(l,i.default,`additionalProperties`));let u=(0,n.allSchemaProperties)(o);for(let e of u)l.definedProperties.add(e);l.opts.unevaluated&&u.length&&l.props!==!0&&(l.props=r.mergeEvaluated.props(a,(0,r.toHash)(u),l.props));let d=u.filter(e=>!(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0)return;let f=a.name(`valid`);for(let t of d)p(t)?m(t):(a.if((0,n.propertyInData)(a,c,t,l.opts.ownProperties)),m(t),l.allErrors||a.else().var(f,!0),a.endIf()),e.it.definedProperties.add(t),e.ok(f);function p(e){return l.opts.useDefaults&&!l.compositeRule&&o[e].default!==void 0}function m(t){e.subschema({keyword:`properties`,schemaProp:t,dataProp:t},f)}}}})),IA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Hk(),n=$(),r=Pk(),i=Pk();e.default={keyword:`patternProperties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,data:s,parentSchema:c,it:l}=e,{opts:u}=l,d=(0,t.allSchemaProperties)(o),f=d.filter(e=>(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0||f.length===d.length&&(!l.opts.unevaluated||l.props===!0))return;let p=u.strictSchema&&!u.allowMatchingProperties&&c.properties,m=a.name(`valid`);l.props!==!0&&!(l.props instanceof n.Name)&&(l.props=(0,i.evaluatedPropsToName)(a,l.props));let{props:h}=l;g();function g(){for(let e of d)p&&_(e),l.allErrors?v(e):(a.var(m,!0),v(e),a.if(m))}function _(e){for(let t in p)new RegExp(e).test(t)&&(0,r.checkStrictMode)(l,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function v(r){a.forIn(`key`,s,o=>{a.if((0,n._)`${(0,t.usePattern)(e,r)}.test(${o})`,()=>{let t=f.includes(r);t||e.subschema({keyword:`patternProperties`,schemaProp:r,dataProp:o,dataPropType:i.Type.Str},m),l.opts.unevaluated&&h!==!0?a.assign((0,n._)`${h}[${o}]`,!0):!t&&!l.allErrors&&a.if((0,n.not)(m),()=>a.break())})})}}}})),LA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Pk();e.default={keyword:`not`,schemaType:[`object`,`boolean`],trackErrors:!0,code(e){let{gen:n,schema:r,it:i}=e;if((0,t.alwaysValidSchema)(i,r)){e.fail();return}let a=n.name(`valid`);e.subschema({keyword:`not`,compositeRule:!0,createErrors:!1,allErrors:!1},a),e.failResult(a,()=>e.reset(),()=>e.error())},error:{message:`must NOT be valid`}}})),RA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:Hk().validateUnion,error:{message:`must match a schema in anyOf`}}})),zA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=Pk();e.default={keyword:`oneOf`,schemaType:`array`,trackErrors:!0,error:{message:`must match exactly one schema in oneOf`,params:({params:e})=>(0,t._)`{passingSchemas: ${e.passing}}`},code(e){let{gen:r,schema:i,parentSchema:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(o.opts.discriminator&&a.discriminator)return;let s=i,c=r.let(`valid`,!1),l=r.let(`passing`,null),u=r.name(`_valid`);e.setParams({passing:l}),r.block(d),e.result(c,()=>e.reset(),()=>e.error(!0));function d(){s.forEach((i,a)=>{let s;(0,n.alwaysValidSchema)(o,i)?r.var(u,!0):s=e.subschema({keyword:`oneOf`,schemaProp:a,compositeRule:!0},u),a>0&&r.if((0,t._)`${u} && ${c}`).assign(c,!1).assign(l,(0,t._)`[${l}, ${a}]`).else(),r.if(u,()=>{r.assign(c,!0),r.assign(l,a),s&&e.mergeEvaluated(s,t.Name)})})}}}})),BA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Pk();e.default={keyword:`allOf`,schemaType:`array`,code(e){let{gen:n,schema:r,it:i}=e;if(!Array.isArray(r))throw Error(`ajv implementation error`);let a=n.name(`valid`);r.forEach((n,r)=>{if((0,t.alwaysValidSchema)(i,n))return;let o=e.subschema({keyword:`allOf`,schemaProp:r},a);e.ok(a),e.mergeEvaluated(o)})}}})),VA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=Pk(),r={keyword:`if`,schemaType:[`object`,`boolean`],trackErrors:!0,error:{message:({params:e})=>(0,t.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,t._)`{failingKeyword: ${e.ifClause}}`},code(e){let{gen:r,parentSchema:a,it:o}=e;a.then===void 0&&a.else===void 0&&(0,n.checkStrictMode)(o,`"if" without "then" and "else" is ignored`);let s=i(o,`then`),c=i(o,`else`);if(!s&&!c)return;let l=r.let(`valid`,!0),u=r.name(`_valid`);if(d(),e.reset(),s&&c){let t=r.let(`ifClause`);e.setParams({ifClause:t}),r.if(u,f(`then`,t),f(`else`,t))}else s?r.if(u,f(`then`)):r.if((0,t.not)(u),f(`else`));e.pass(l,()=>e.error(!0));function d(){let t=e.subschema({keyword:`if`,compositeRule:!0,createErrors:!1,allErrors:!1},u);e.mergeEvaluated(t)}function f(n,i){return()=>{let a=e.subschema({keyword:n},u);r.assign(l,u),e.mergeValidEvaluated(a,l),i?r.assign(i,(0,t._)`${n}`):e.setParams({ifClause:n})}}}};function i(e,t){let r=e.schema[t];return r!==void 0&&!(0,n.alwaysValidSchema)(e,r)}e.default=r})),HA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Pk();e.default={keyword:[`then`,`else`],schemaType:[`object`,`boolean`],code({keyword:e,parentSchema:n,it:r}){n.if===void 0&&(0,t.checkStrictMode)(r,`"${e}" without "if" is ignored`)}}})),UA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=DA(),n=kA(),r=OA(),i=AA(),a=jA(),o=MA(),s=NA(),c=PA(),l=FA(),u=IA(),d=LA(),f=RA(),p=zA(),m=BA(),h=VA(),g=HA();function _(e=!1){let _=[d.default,f.default,p.default,m.default,h.default,g.default,s.default,c.default,o.default,l.default,u.default];return e?_.push(n.default,i.default):_.push(t.default,r.default),_.push(a.default),_}e.default=_})),WA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$();e.default={keyword:`format`,type:[`number`,`string`],schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,t._)`{format: ${e}}`},code(e,n){let{gen:r,data:i,$data:a,schema:o,schemaCode:s,it:c}=e,{opts:l,errSchemaPath:u,schemaEnv:d,self:f}=c;if(!l.validateFormats)return;a?p():m();function p(){let a=r.scopeValue(`formats`,{ref:f.formats,code:l.code.formats}),o=r.const(`fDef`,(0,t._)`${a}[${s}]`),c=r.let(`fType`),u=r.let(`format`);r.if((0,t._)`typeof ${o} == "object" && !(${o} instanceof RegExp)`,()=>r.assign(c,(0,t._)`${o}.type || "string"`).assign(u,(0,t._)`${o}.validate`),()=>r.assign(c,(0,t._)`"string"`).assign(u,o)),e.fail$data((0,t.or)(p(),m()));function p(){return l.strictSchema===!1?t.nil:(0,t._)`${s} && !${u}`}function m(){let e=d.$async?(0,t._)`(${o}.async ? await ${u}(${i}) : ${u}(${i}))`:(0,t._)`${u}(${i})`,r=(0,t._)`(typeof ${u} == "function" ? ${e} : ${u}.test(${i}))`;return(0,t._)`${u} && ${u} !== true && ${c} === ${n} && !${r}`}}function m(){let a=f.formats[o];if(!a){m();return}if(a===!0)return;let[s,c,p]=h(a);s===n&&e.pass(g());function m(){if(l.strictSchema===!1){f.logger.warn(e());return}throw Error(e());function e(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function h(e){let n=e instanceof RegExp?(0,t.regexpCode)(e):l.code.formats?(0,t._)`${l.code.formats}${(0,t.getProperty)(o)}`:void 0,i=r.scopeValue(`formats`,{key:o,ref:e,code:n});return typeof e==`object`&&!(e instanceof RegExp)?[e.type||`string`,e.validate,(0,t._)`${i}.validate`]:[`string`,e,i]}function g(){if(typeof a==`object`&&!(a instanceof RegExp)&&a.async){if(!d.$async)throw Error(`async format in sync schema`);return(0,t._)`await ${p}(${i})`}return typeof c==`function`?(0,t._)`${p}(${i})`:(0,t._)`${p}.test(${i})`}}}}})),GA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=[WA().default]})),KA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.contentVocabulary=e.metadataVocabulary=void 0,e.metadataVocabulary=[`title`,`description`,`default`,`deprecated`,`readOnly`,`writeOnly`,`examples`],e.contentVocabulary=[`contentMediaType`,`contentEncoding`,`contentSchema`]})),qA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=pA(),n=EA(),r=UA(),i=GA(),a=KA();e.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),JA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DiscrError=void 0;var t;(function(e){e.Tag=`tag`,e.Mapping=`mapping`})(t||(e.DiscrError=t={}))})),YA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=JA(),r=Zk(),i=Xk(),a=Pk();e.default={keyword:`discriminator`,type:`object`,schemaType:`object`,error:{message:({params:{discrError:e,tagName:t}})=>e===n.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:n,tagName:r}})=>(0,t._)`{error: ${e}, tag: ${r}, tagValue: ${n}}`},code(e){let{gen:o,data:s,schema:c,parentSchema:l,it:u}=e,{oneOf:d}=l;if(!u.opts.discriminator)throw Error(`discriminator: requires discriminator option`);let f=c.propertyName;if(typeof f!=`string`)throw Error(`discriminator: requires propertyName`);if(c.mapping)throw Error(`discriminator: mapping is not supported`);if(!d)throw Error(`discriminator: requires oneOf keyword`);let p=o.let(`valid`,!1),m=o.const(`tag`,(0,t._)`${s}${(0,t.getProperty)(f)}`);o.if((0,t._)`typeof ${m} == "string"`,()=>h(),()=>e.error(!1,{discrError:n.DiscrError.Tag,tag:m,tagName:f})),e.ok(p);function h(){let r=_();o.if(!1);for(let e in r)o.elseIf((0,t._)`${m} === ${e}`),o.assign(p,g(r[e]));o.else(),e.error(!1,{discrError:n.DiscrError.Mapping,tag:m,tagName:f}),o.endIf()}function g(n){let r=o.name(`valid`),i=e.subschema({keyword:`oneOf`,schemaProp:n},r);return e.mergeEvaluated(i,t.Name),r}function _(){let e={},t=o(l),n=!0;for(let e=0;e<d.length;e++){let c=d[e];if(c?.$ref&&!(0,a.schemaHasRulesButRef)(c,u.self.RULES)){let e=c.$ref;if(c=r.resolveRef.call(u.self,u.schemaEnv.root,u.baseId,e),c instanceof r.SchemaEnv&&(c=c.schema),c===void 0)throw new i.default(u.opts.uriResolver,u.baseId,e)}let l=c?.properties?.[f];if(typeof l!=`object`)throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${f}"`);n&&=t||o(c),s(l,e)}if(!n)throw Error(`discriminator: "${f}" must be required`);return e;function o({required:e}){return Array.isArray(e)&&e.includes(f)}function s(e,t){if(e.const)c(e.const,t);else if(e.enum)for(let n of e.enum)c(n,t);else throw Error(`discriminator: "properties/${f}" must have "const" or "enum"`)}function c(t,n){if(typeof t!=`string`||t in e)throw Error(`discriminator: "${f}" values must be unique strings`);e[t]=n}}}}})),XA=Oe({$id:()=>QA,$schema:()=>ZA,default:()=>rj,definitions:()=>ej,properties:()=>nj,title:()=>$A,type:()=>tj}),ZA,QA,$A,ej,tj,nj,rj,ij=De((()=>{ZA=`http://json-schema.org/draft-07/schema#`,QA=`http://json-schema.org/draft-07/schema#`,$A=`Core schema meta-schema`,ej={schemaArray:{type:`array`,minItems:1,items:{$ref:`#`}},nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:`#/definitions/nonNegativeInteger`},{default:0}]},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}},tj=[`object`,`boolean`],nj={$id:{type:`string`,format:`uri-reference`},$schema:{type:`string`,format:`uri`},$ref:{type:`string`,format:`uri-reference`},$comment:{type:`string`},title:{type:`string`},description:{type:`string`},default:!0,readOnly:{type:`boolean`,default:!1},examples:{type:`array`,items:!0},multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/definitions/nonNegativeInteger`},minLength:{$ref:`#/definitions/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},additionalItems:{$ref:`#`},items:{anyOf:[{$ref:`#`},{$ref:`#/definitions/schemaArray`}],default:!0},maxItems:{$ref:`#/definitions/nonNegativeInteger`},minItems:{$ref:`#/definitions/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},contains:{$ref:`#`},maxProperties:{$ref:`#/definitions/nonNegativeInteger`},minProperties:{$ref:`#/definitions/nonNegativeIntegerDefault0`},required:{$ref:`#/definitions/stringArray`},additionalProperties:{$ref:`#`},definitions:{type:`object`,additionalProperties:{$ref:`#`},default:{}},properties:{type:`object`,additionalProperties:{$ref:`#`},default:{}},patternProperties:{type:`object`,additionalProperties:{$ref:`#`},propertyNames:{format:`regex`},default:{}},dependencies:{type:`object`,additionalProperties:{anyOf:[{$ref:`#`},{$ref:`#/definitions/stringArray`}]}},propertyNames:{$ref:`#`},const:!0,enum:{type:`array`,items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:`#/definitions/simpleTypes`},{type:`array`,items:{$ref:`#/definitions/simpleTypes`},minItems:1,uniqueItems:!0}]},format:{type:`string`},contentMediaType:{type:`string`},contentEncoding:{type:`string`},if:{$ref:`#`},then:{$ref:`#`},else:{$ref:`#`},allOf:{$ref:`#/definitions/schemaArray`},anyOf:{$ref:`#/definitions/schemaArray`},oneOf:{$ref:`#/definitions/schemaArray`},not:{$ref:`#`}},rj={$schema:ZA,$id:QA,title:$A,definitions:ej,type:tj,properties:nj,default:!0}})),aj=E(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;var n=uA(),r=qA(),i=YA(),a=(ij(),je(XA).default),o=[`/properties`],s=`http://json-schema.org/draft-07/schema`,c=class extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(i.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(a,o):a;this.addMetaSchema(e,s,!1),this.refs[`http://json-schema.org/schema`]=s}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s)?s:void 0)}};e.Ajv=c,t.exports=e=c,t.exports.Ajv=c,Object.defineProperty(e,"__esModule",{value:!0}),e.default=c;var l=Jk();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return l.KeywordCxt}});var u=$();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var d=Yk();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return d.default}});var f=Xk();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return f.default}})})),oj=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(e,t){return{validate:e,compare:t}}e.fullFormats={date:t(a,o),time:t(c(!0),l),"date-time":t(f(!0),p),"iso-time":t(c(),u),"iso-date-time":t(f(),m),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:_,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:re,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:y,int32:{type:`number`,validate:ee},int64:{type:`number`,validate:S},float:{type:`number`,validate:te},double:{type:`number`,validate:te},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,o),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,l),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,p),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,m),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function n(e){return e%4==0&&(e%100!=0||e%400==0)}var r=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,i=[0,31,28,31,30,31,30,31,31,30,31,30,31];function a(e){let t=r.exec(e);if(!t)return!1;let a=+t[1],o=+t[2],s=+t[3];return o>=1&&o<=12&&s>=1&&s<=(o===2&&n(a)?29:i[o])}function o(e,t){if(e&&t)return e>t?1:e<t?-1:0}var s=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function c(e){return function(t){let n=s.exec(t);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=n[4],c=n[5]===`-`?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||e&&!o)return!1;if(r<=23&&i<=59&&a<60)return!0;let d=i-u*c,f=r-l*c-+(d<0);return(f===23||f===-1)&&(d===59||d===-1)&&a<61}}function l(e,t){if(!(e&&t))return;let n=new Date(`2020-01-01T`+e).valueOf(),r=new Date(`2020-01-01T`+t).valueOf();if(n&&r)return n-r}function u(e,t){if(!(e&&t))return;let n=s.exec(e),r=s.exec(t);if(n&&r)return e=n[1]+n[2]+n[3],t=r[1]+r[2]+r[3],e>t?1:e<t?-1:0}var d=/t|\s/i;function f(e){let t=c(e);return function(e){let n=e.split(d);return n.length===2&&a(n[0])&&t(n[1])}}function p(e,t){if(!(e&&t))return;let n=new Date(e).valueOf(),r=new Date(t).valueOf();if(n&&r)return n-r}function m(e,t){if(!(e&&t))return;let[n,r]=e.split(d),[i,a]=t.split(d),s=o(n,i);if(s!==void 0)return s||l(r,a)}var h=/\/|:/,g=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function _(e){return h.test(e)&&g.test(e)}var v=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function y(e){return v.lastIndex=0,v.test(e)}var b=-(2**31),x=2**31-1;function ee(e){return Number.isInteger(e)&&e<=x&&e>=b}function S(e){return Number.isInteger(e)}function te(){return!0}var ne=/[^\\]\\Z/;function re(e){if(ne.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}})),sj=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;var t=aj(),n=$(),r=n.operators,i={formatMaximum:{okStr:`<=`,ok:r.LTE,fail:r.GT},formatMinimum:{okStr:`>=`,ok:r.GTE,fail:r.LT},formatExclusiveMaximum:{okStr:`<`,ok:r.LT,fail:r.GTE},formatExclusiveMinimum:{okStr:`>`,ok:r.GT,fail:r.LTE}};e.formatLimitDefinition={keyword:Object.keys(i),type:`string`,schemaType:`string`,$data:!0,error:{message:({keyword:e,schemaCode:t})=>(0,n.str)`should be ${i[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,n._)`{comparison: ${i[e].okStr}, limit: ${t}}`},code(e){let{gen:r,data:a,schemaCode:o,keyword:s,it:c}=e,{opts:l,self:u}=c;if(!l.validateFormats)return;let d=new t.KeywordCxt(c,u.RULES.all.format.definition,`format`);d.$data?f():p();function f(){let t=r.scopeValue(`formats`,{ref:u.formats,code:l.code.formats}),i=r.const(`fmt`,(0,n._)`${t}[${d.schemaCode}]`);e.fail$data((0,n.or)((0,n._)`typeof ${i} != "object"`,(0,n._)`${i} instanceof RegExp`,(0,n._)`typeof ${i}.compare != "function"`,m(i)))}function p(){let t=d.schema,i=u.formats[t];if(!i||i===!0)return;if(typeof i!=`object`||i instanceof RegExp||typeof i.compare!=`function`)throw Error(`"${s}": format "${t}" does not define "compare" function`);let a=r.scopeValue(`formats`,{key:t,ref:i,code:l.code.formats?(0,n._)`${l.code.formats}${(0,n.getProperty)(t)}`:void 0});e.fail$data(m(a))}function m(e){return(0,n._)`${e}.compare(${a}, ${o}) ${i[s].fail} 0`}},dependencies:[`format`]},e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)})),cj=E(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});var n=oj(),r=sj(),i=$(),a=new i.Name(`fullFormats`),o=new i.Name(`fastFormats`),s=(e,t={keywords:!0})=>{if(Array.isArray(t))return c(e,t,n.fullFormats,a),e;let[i,s]=t.mode===`fast`?[n.fastFormats,o]:[n.fullFormats,a];return c(e,t.formats||n.formatNames,i,s),t.keywords&&(0,r.default)(e),e};s.get=(e,t=`full`)=>{let r=(t===`fast`?n.fastFormats:n.fullFormats)[e];if(!r)throw Error(`Unknown format "${e}"`);return r};function c(e,t,n,r){var a;(a=e.opts.code).formats??(a.formats=(0,i._)`require("ajv-formats/dist/formats").${r}`);for(let r of t)e.addFormat(r,n[r])}t.exports=e=s,Object.defineProperty(e,"__esModule",{value:!0}),e.default=s})),lj=Ae(aj(),1),uj=Ae(cj(),1);function dj(){let e=new lj.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,uj.default)(e),e}var fj=class{constructor(e){this._ajv=e??dj()}getValidator(e){let t=`$id`in e&&typeof e.$id==`string`?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}},pj=class{constructor(e){this._server=e}requestStream(e,t,n){return this._server.requestStream(e,t,n)}createMessageStream(e,t){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return this.requestStream({method:`sampling/createMessage`,params:e},ZD,t)}elicitInputStream(e,t){let n=this._server.getClientCapabilities(),r=e.mode??`form`;switch(r){case`url`:if(!n?.elicitation?.url)throw Error(`Client does not support url elicitation.`);break;case`form`:if(!n?.elicitation?.form)throw Error(`Client does not support form elicitation.`)}let i=r===`form`&&e.mode===void 0?{...e,mode:`form`}:e;return this.requestStream({method:`elicitation/create`,params:i},lO,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._server.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}};function mj(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);if(t===`tools/call`&&!e.tools?.call)throw Error(`${n} does not support task creation for tools/call (required for ${t})`)}function hj(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw Error(`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw Error(`${n} does not support task creation for elicitation/create (required for ${t})`)}}var gj=class extends kk{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(RD.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let n=this._loggingLevels.get(t);return n?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new fj,this.setRequestHandler(xE,e=>this._oninitialize(e)),this.setNotificationHandler(wE,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(BD,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=RD.safeParse(r);return i.success&&this._loggingLevels.set(n,i.data),{}})}get experimental(){return this._experimental||={tasks:new pj(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=jk(this._capabilities,e)}setRequestHandler(e,t){let n=jT(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r=LT(n);if(typeof r!=`string`)throw Error(`Schema method literal must be a string`);return r===`tools/call`?super.setRequestHandler(e,async(e,n)=>{let r=kT(FD,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new Q(Z.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=kT(PE,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new Q(Z.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=kT(ND,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new Q(Z.InvalidParams,`Invalid tools/call result: ${e}`)}return o.data}):super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`)}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`)}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`completion/complete`:if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`)}}assertTaskCapability(e){hj(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&mj(this._capabilities.tasks?.requests,e,`Server`)}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:zT.includes(t)?t:RT,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:`ping`},uE)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return e.tools?this.request({method:`sampling/createMessage`,params:e},QD,t):this.request({method:`sampling/createMessage`,params:e},ZD,t)}async elicitInput(e,t){switch(e.mode??`form`){case`url`:{if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support url elicitation.`);let n=e;return this.request({method:`elicitation/create`,params:n},lO,t)}case`form`:{if(!this._clientCapabilities?.elicitation?.form)throw Error(`Client does not support form elicitation.`);let n=e.mode===`form`?e:{...e,mode:`form`},r=await this.request({method:`elicitation/create`,params:n},lO,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new Q(Z.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof Q?e:new Q(Z.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:`roots/list`,params:e},yO,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}},_j=Symbol.for(`mcp.completable`);function vj(e){return!!e&&typeof e==`object`&&_j in e}function yj(e){return e[_j]?.complete}var bj;(function(e){e.Completable=`McpCompletable`})(bj||={});var xj=/^[A-Za-z0-9._-]{1,128}$/;function Sj(e){let t=[];if(e.length===0)return{isValid:!1,warnings:[`Tool name cannot be empty`]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(` `)&&t.push(`Tool name contains spaces, which may cause parsing issues`),e.includes(`,`)&&t.push(`Tool name contains commas, which may cause parsing issues`),(e.startsWith(`-`)||e.endsWith(`-`))&&t.push(`Tool name starts or ends with a dash, which may cause parsing issues in some contexts`),(e.startsWith(`.`)||e.endsWith(`.`))&&t.push(`Tool name starts or ends with a dot, which may cause parsing issues in some contexts`),!xj.test(e)){let n=e.split(``).filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,n)=>n.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${n.map(e=>`"${e}"`).join(`, `)}`,`Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)`),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function Cj(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let e of t)console.warn(` - ${e}`);console.warn(`Tool registration will proceed, but this may cause compatibility issues.`),console.warn(`Consider updating the tool name to conform to the MCP tool naming standard.`),console.warn(`See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.`)}}function wj(e){let t=Sj(e);return Cj(e,t.warnings),t.isValid}var Tj=class{constructor(e){this._mcpServer=e}registerToolTask(e,t,n){let r={taskSupport:`required`,...t.execution};if(r.taskSupport===`forbidden`)throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,r,t._meta,n)}},Ej=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new gj(e,t)}get experimental(){return this._experimental||={tasks:new Tj(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(Nj(jD)),this.server.assertCanSetRequestHandler(Nj(FD)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(jD,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:(()=>{let e=MT(t.inputSchema);return e?Ek(e,{strictUnions:!0,pipeStrategy:`input`}):Dj})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=MT(t.outputSchema);e&&(n.outputSchema=Ek(e,{strictUnions:!0,pipeStrategy:`output`}))}return n})})),this.server.setRequestHandler(FD,async(e,t)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new Q(Z.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new Q(Z.InvalidParams,`Tool ${e.params.name} disabled`);let r=!!e.params.task,i=n.execution?.taskSupport,a=`createTask`in n.handler;if((i===`required`||i===`optional`)&&!a)throw new Q(Z.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i===`required`&&!r)throw new Q(Z.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(i===`optional`&&!r&&a)return await this.handleAutomaticTaskPolling(n,e,t);let o=await this.validateToolInput(n,e.params.arguments,e.params.name),s=await this.executeToolHandler(n,o,t);return r||await this.validateToolOutput(n,s,e.params.name),s}catch(e){if(e instanceof Q&&e.code===Z.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),!0)}createToolError(e){return{content:[{type:`text`,text:e}],isError:!0}}async validateToolInput(e,t,n){if(!e.inputSchema)return;let r=await AT(MT(e.inputSchema)??e.inputSchema,t);if(!r.success){let e=PT(`error`in r?r.error:`Unknown error`);throw new Q(Z.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${e}`)}return r.data}async validateToolOutput(e,t,n){if(!e.outputSchema||!(`content`in t)||t.isError)return;if(!t.structuredContent)throw new Q(Z.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await AT(MT(e.outputSchema),t.structuredContent);if(!r.success){let e=PT(`error`in r?r.error:`Unknown error`);throw new Q(Z.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${e}`)}}async executeToolHandler(e,t,n){let r=e.handler;if(`createTask`in r){if(!n.taskStore)throw Error(`No task store provided.`);let i={...n,taskStore:n.taskStore};if(e.inputSchema){let e=r;return await Promise.resolve(e.createTask(t,i))}{let e=r;return await Promise.resolve(e.createTask(i))}}if(e.inputSchema){let e=r;return await Promise.resolve(e(t,n))}{let e=r;return await Promise.resolve(e(n))}}async handleAutomaticTaskPolling(e,t,n){if(!n.taskStore)throw Error(`No task store provided for task-capable tool.`);let r=await this.validateToolInput(e,t.params.arguments,t.params.name),i=e.handler,a={...n,taskStore:n.taskStore},o=r?await Promise.resolve(i.createTask(r,a)):await Promise.resolve(i.createTask(a)),s=o.task.taskId,c=o.task,l=c.pollInterval??5e3;for(;c.status!==`completed`&&c.status!==`failed`&&c.status!==`cancelled`;){await new Promise(e=>setTimeout(e,l));let e=await n.taskStore.getTask(s);if(!e)throw new Q(Z.InternalError,`Task ${s} not found during polling`);c=e}return await n.taskStore.getTaskResult(s)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(Nj(pO)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(pO,async e=>{switch(e.params.ref.type){case`ref/prompt`:return mO(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return hO(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Q(Z.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new Q(Z.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new Q(Z.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return Fj;let r=jT(n.argsSchema)?.[e.params.argument.name];if(!vj(r))return Fj;let i=yj(r);return i?Pj(await i(e.params.argument.value,e.params.context)):Fj}async handleResourceCompletion(e,t){let n=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!n){if(this._registeredResources[t.uri])return Fj;throw new Q(Z.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?Pj(await r(e.params.argument.value,e.params.context)):Fj}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(Nj(QE)),this.server.assertCanSetRequestHandler(Nj(eD)),this.server.assertCanSetRequestHandler(Nj(iD)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(QE,async(e,t)=>{let n=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),r=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let n=await e.resourceTemplate.listCallback(t);for(let t of n.resources)r.push({...e.metadata,...t})}return{resources:[...n,...r]}}),this.server.setRequestHandler(eD,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(iD,async(e,t)=>{let n=new URL(e.params.uri),r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new Q(Z.InvalidParams,`Resource ${n} disabled`);return r.readCallback(n,t)}for(let e of Object.values(this._registeredResourceTemplates)){let r=e.resourceTemplate.uriTemplate.match(n.toString());if(r)return e.readCallback(n,r,t)}throw new Q(Z.InvalidParams,`Resource ${n} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(Nj(hD)),this.server.assertCanSetRequestHandler(Nj(vD)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(hD,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?Mj(t.argsSchema):void 0}))})),this.server.setRequestHandler(vD,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new Q(Z.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new Q(Z.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let r=await AT(MT(n.argsSchema),e.params.arguments);if(!r.success){let t=PT(`error`in r?r.error:`Unknown error`);throw new Q(Z.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}let i=r.data,a=n.callback;return await Promise.resolve(a(i,t))}{let e=n.callback;return await Promise.resolve(e(t))}}),!0)}resource(e,t,...n){let r;typeof n[0]==`object`&&(r=n.shift());let i=n[0];if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let n=this._createRegisteredResource(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let n=this._createRegisteredResourceTemplate(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}}registerResource(e,t,n,r){if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let i=this._createRegisteredResource(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,t,n,r,i){let a={name:e,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==n&&(delete this._registeredResources[n],e.uri&&(this._registeredResources[e.uri]=a)),e.name!==void 0&&(a.name=e.name),e.title!==void 0&&(a.title=e.title),e.metadata!==void 0&&(a.metadata=e.metadata),e.callback!==void 0&&(a.readCallback=e.callback),e.enabled!==void 0&&(a.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,t,n,r,i){let a={resourceTemplate:n,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.template!==void 0&&(a.resourceTemplate=t.template),t.metadata!==void 0&&(a.metadata=t.metadata),t.callback!==void 0&&(a.readCallback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;let o=n.uriTemplate.variableNames;return Array.isArray(o)&&o.some(e=>!!n.completeCallback(e))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,t,n,r,i){let a={title:t,description:n,argsSchema:r===void 0?void 0:OT(r),callback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.description!==void 0&&(a.description=t.description),t.argsSchema!==void 0&&(a.argsSchema=OT(t.argsSchema)),t.callback!==void 0&&(a.callback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,r&&Object.values(r).some(e=>vj(e instanceof Yl?e._def?.innerType:e))&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,t,n,r,i,a,o,s,c){wj(e);let l={title:t,description:n,inputSchema:jj(r),outputSchema:jj(i),annotations:a,execution:o,_meta:s,handler:c,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(typeof t.name==`string`&&wj(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=l)),t.title!==void 0&&(l.title=t.title),t.description!==void 0&&(l.description=t.description),t.paramsSchema!==void 0&&(l.inputSchema=OT(t.paramsSchema)),t.outputSchema!==void 0&&(l.outputSchema=OT(t.outputSchema)),t.callback!==void 0&&(l.handler=t.callback),t.annotations!==void 0&&(l.annotations=t.annotations),t._meta!==void 0&&(l._meta=t._meta),t.enabled!==void 0&&(l.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let n,r,i,a;if(typeof t[0]==`string`&&(n=t.shift()),t.length>1){let n=t[0];if(Aj(n))r=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!Aj(t[0])&&(a=t.shift());else if(typeof n==`object`&&n){if(Object.values(n).some(e=>typeof e==`object`&&!!e))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);a=t.shift()}}let o=t[0];return this._createRegisteredTool(e,void 0,n,r,i,a,{taskSupport:`forbidden`},void 0,o)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:r,description:i,inputSchema:a,outputSchema:o,annotations:s,_meta:c}=t;return this._createRegisteredTool(e,r,i,a,o,s,{taskSupport:`forbidden`},c,n)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let n;typeof t[0]==`string`&&(n=t.shift());let r;t.length>1&&(r=t.shift());let i=t[0],a=this._createRegisteredPrompt(e,void 0,n,r,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:r,description:i,argsSchema:a}=t,o=this._createRegisteredPrompt(e,r,i,a,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},Dj={type:`object`,properties:{}};function Oj(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`&&`safeParse`in e&&typeof e.safeParse==`function`}function kj(e){return`_def`in e||`_zod`in e||Oj(e)}function Aj(e){return typeof e!=`object`||!e||kj(e)?!1:Object.keys(e).length===0||Object.values(e).some(Oj)}function jj(e){if(e){if(Aj(e))return OT(e);if(!kj(e))throw Error(`inputSchema must be a Zod schema or raw shape, received an unrecognized object`);return e}}function Mj(e){let t=jT(e);return t?Object.entries(t).map(([e,t])=>({name:e,description:FT(t),required:!IT(t)})):[]}function Nj(e){let t=jT(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=LT(t);if(typeof n==`string`)return n;throw Error(`Schema method literal must be a string`)}function Pj(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var Fj={completion:{values:[],hasMore:!1}},Ij=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??10485760}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
306
|
-
`);if(e===-1)return null;let t=this._buffer.toString(`utf8`,0,e).replace(/\r$/,``);return this._buffer=this._buffer.subarray(e+1),
|
|
307
|
-
`}var
|
|
308
|
-
`)
|
|
309
|
-
`),points:Number(a[0])}}function eM(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0}function tM(e){let t=new Map;for(let n of e){if(!eM(n.number))throw new L(`Native blocked-by relationship evidence is malformed.`);let e=t.get(n.number);if(e!==void 0&&e!==n.state)throw new L(`Native blocker #${String(n.number)} has conflicting relationship states.`);t.set(n.number,n.state)}return t}function nM(e){if(eM(e))return e;if(typeof e!=`string`)return;let t=/^#?([1-9]\d*)$/u.exec(e.trim()),n=t?.[1]===void 0?NaN:Number(t[1]);return eM(n)?n:void 0}function rM(e,t){let n=RegExp(`<!--\\s*${t}:\\s*([\\s\\S]*?)\\s*-->`,`u`).exec(e)?.[1];if(n!==void 0)try{let e=JSON.parse(n);if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`not an object`);return e}catch{throw new L(`Invalid legacy ${t} payload.`)}}function iM(e){return e.replace(/<!--\s*(?:executionContract|dependencyDeclaration|related):[\s\S]*?-->\s*/gu,``).trim()}function aM({dependencyDeclaration:e,executionContract:t,related:n}){let r=[],i=t?.dependencies;if(Array.isArray(i))for(let e of i){if(typeof e!=`object`||!e)continue;let t=e,n=nM(t.issue);t.type===`blockedBy`&&n!==void 0&&r.push(n)}return r.push(...oM(e?.blockedBy)),r.push(...oM(n?.blockedBy)),[...new Set(r)].sort((e,t)=>e-t)}function oM(e){return Array.isArray(e)?e.map(nM).filter(e=>e!==void 0):[]}function sM(e){if(e.unresolvedBlockers.size>0)return`Blocked`;let t=e.labels.some(e=>[`status:in-progress`,`status:review`].includes(e.toLowerCase()));return e.existing===`In Progress`||t?`In Progress`:`Todo`}function cM(e){let t=[];for(let n of e.labels){let e=Jj.get(n.toLowerCase());e!==void 0&&t.push(e);let r=/^points:(1|2|3|5|8|13)$/u.exec(n.toLowerCase());r?.[1]!==void 0&&t.push(Number(r[1]))}let n=e.executionContract?.effort;if(typeof n==`string`){let e=n.startsWith(`effort:`)?n:`effort:${n}`,r=Jj.get(e.toLowerCase());r!==void 0&&t.push(r)}e.bodyPoint!==void 0&&t.push(e.bodyPoint);let r=[...new Set(t)];if(r.length>1)throw new L(`Found conflicting legacy sizing values: ${r.join(`, `)}.`);let[i]=r;if(i===void 0)throw new L(`Issue has no canonical Fibonacci sizing value; assign native Points before migration.`);return i}function lM({label:e,labels:t,mapping:n}){let r=t.flatMap(e=>{let t=n.get(e.toLowerCase());return t===void 0?[]:[t]}),i=[...new Set(r)];if(i.length>1)throw new L(`Found conflicting legacy ${e} values.`);return i[0]}var uM=class{constructor(e){this._client=e}async*callToolStream(e,t=ND,n){let r=this._client,i={...n,task:n?.task??(r.isToolTask(e.name)?{}:void 0)},a=r.requestStream({method:`tools/call`,params:e},t,i),o=r.getToolOutputValidator(e.name);for await(let t of a){if(t.type===`result`&&o){let n=t.result;if(!n.structuredContent&&!n.isError){yield{type:`error`,error:new Q(Z.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(n.structuredContent)try{let e=o(n.structuredContent);if(!e.valid){yield{type:`error`,error:new Q(Z.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)};return}}catch(e){if(e instanceof Q){yield{type:`error`,error:e};return}yield{type:`error`,error:new Q(Z.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)};return}}yield t}}async getTask(e,t){return this._client.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._client.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._client.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._client.cancelTask({taskId:e},t)}requestStream(e,t,n){return this._client.requestStream(e,t,n)}};function dM(e,t){if(e&&typeof t==`object`&&t){if(e.type===`object`&&e.properties&&typeof e.properties==`object`){let n=t,r=e.properties;for(let e of Object.keys(r)){let t=r[e];n[e]===void 0&&Object.prototype.hasOwnProperty.call(t,`default`)&&(n[e]=t.default),n[e]!==void 0&&dM(t,n[e])}}if(Array.isArray(e.anyOf))for(let n of e.anyOf)typeof n!=`boolean`&&dM(n,t);if(Array.isArray(e.oneOf))for(let n of e.oneOf)typeof n!=`boolean`&&dM(n,t)}}function fM(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};let t=e.form!==void 0,n=e.url!==void 0;return{supportsFormMode:t||!t&&!n,supportsUrlMode:n}}var pM=class extends kk{constructor(e,t){super(t),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=t?.capabilities??{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new fj,t?.listChanged&&(this._pendingListChangedConfig=t.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler(`tools`,ID,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler(`prompts`,DD,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler(`resources`,oD,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||={tasks:new uM(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=jk(this._capabilities,e)}setRequestHandler(e,t){let n=jT(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r=LT(n);if(typeof r!=`string`)throw Error(`Schema method literal must be a string`);let i=r;return i===`elicitation/create`?super.setRequestHandler(e,async(e,n)=>{let r=kT(oO,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new Q(Z.InvalidParams,`Invalid elicitation request: ${e}`)}let{params:i}=r.data;i.mode=i.mode??`form`;let{supportsFormMode:a,supportsUrlMode:o}=fM(this._capabilities.elicitation);if(i.mode===`form`&&!a)throw new Q(Z.InvalidParams,`Client does not support form-mode elicitation requests`);if(i.mode===`url`&&!o)throw new Q(Z.InvalidParams,`Client does not support URL-mode elicitation requests`);let s=await Promise.resolve(t(e,n));if(i.task){let e=kT(PE,s);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new Q(Z.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let c=kT(lO,s);if(!c.success){let e=c.error instanceof Error?c.error.message:String(c.error);throw new Q(Z.InvalidParams,`Invalid elicitation result: ${e}`)}let l=c.data,u=i.mode===`form`?i.requestedSchema:void 0;if(i.mode===`form`&&l.action===`accept`&&l.content&&u&&this._capabilities.elicitation?.form?.applyDefaults)try{dM(u,l.content)}catch{}return l}):i===`sampling/createMessage`?super.setRequestHandler(e,async(e,n)=>{let r=kT(XD,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new Q(Z.InvalidParams,`Invalid sampling request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=kT(PE,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new Q(Z.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=kT(i.tools||i.toolChoice?QD:ZD,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new Q(Z.InvalidParams,`Invalid sampling result: ${e}`)}return o.data}):super.setRequestHandler(e,t)}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw Error(`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(await super.connect(e),e.sessionId===void 0)try{let n=await this.request({method:`initialize`,params:{protocolVersion:RT,capabilities:this._capabilities,clientInfo:this._clientInfo}},CE,t);if(n===void 0)throw Error(`Server sent invalid initialize result: ${n}`);if(!zT.includes(n.protocolVersion))throw Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:`notifications/initialized`}),this._pendingListChangedConfig&&=(this._setupListChangedHandlers(this._pendingListChangedConfig),void 0)}catch(e){throw this.close(),e}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case`logging/setLevel`:if(!this._serverCapabilities?.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._serverCapabilities?.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:case`resources/subscribe`:case`resources/unsubscribe`:if(!this._serverCapabilities?.resources)throw Error(`Server does not support resources (required for ${e})`);if(e===`resources/subscribe`&&!this._serverCapabilities.resources.subscribe)throw Error(`Server does not support resource subscriptions (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._serverCapabilities?.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`completion/complete`:if(!this._serverCapabilities?.completions)throw Error(`Server does not support completions (required for ${e})`)}}assertNotificationCapability(e){if(e===`notifications/roots/list_changed`&&!this._capabilities.roots?.listChanged)throw Error(`Client does not support roots list changed notifications (required for ${e})`)}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`sampling/createMessage`:if(!this._capabilities.sampling)throw Error(`Client does not support sampling capability (required for ${e})`);break;case`elicitation/create`:if(!this._capabilities.elicitation)throw Error(`Client does not support elicitation capability (required for ${e})`);break;case`roots/list`:if(!this._capabilities.roots)throw Error(`Client does not support roots capability (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Client does not support tasks capability (required for ${e})`)}}assertTaskCapability(e){mj(this._serverCapabilities?.tasks?.requests,e,`Server`)}assertTaskHandlerCapability(e){this._capabilities&&hj(this._capabilities.tasks?.requests,e,`Client`)}async ping(e){return this.request({method:`ping`},uE,e)}async complete(e,t){return this.request({method:`completion/complete`,params:e},gO,t)}async setLoggingLevel(e,t){return this.request({method:`logging/setLevel`,params:{level:e}},uE,t)}async getPrompt(e,t){return this.request({method:`prompts/get`,params:e},ED,t)}async listPrompts(e,t){return this.request({method:`prompts/list`,params:e},gD,t)}async listResources(e,t){return this.request({method:`resources/list`,params:e},$E,t)}async listResourceTemplates(e,t){return this.request({method:`resources/templates/list`,params:e},tD,t)}async readResource(e,t){return this.request({method:`resources/read`,params:e},aD,t)}async subscribeResource(e,t){return this.request({method:`resources/subscribe`,params:e},uE,t)}async unsubscribeResource(e,t){return this.request({method:`resources/unsubscribe`,params:e},uE,t)}async callTool(e,t=ND,n){if(this.isToolTaskRequired(e.name))throw new Q(Z.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let r=await this.request({method:`tools/call`,params:e},t,n),i=this.getToolOutputValidator(e.name);if(i){if(!r.structuredContent&&!r.isError)throw new Q(Z.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(r.structuredContent)try{let e=i(r.structuredContent);if(!e.valid)throw new Q(Z.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)}catch(e){throw e instanceof Q?e:new Q(Z.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)}}return r}isToolTask(e){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let t of e){if(t.outputSchema){let e=this._jsonSchemaValidator.getValidator(t.outputSchema);this._cachedToolOutputValidators.set(t.name,e)}let e=t.execution?.taskSupport;(e===`required`||e===`optional`)&&this._cachedKnownTaskTools.add(t.name),e===`required`&&this._cachedRequiredTaskTools.add(t.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,t){let n=await this.request({method:`tools/list`,params:e},MD,t);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(e,t,n,r){let i=LD.safeParse(n);if(!i.success)throw Error(`Invalid ${e} listChanged options: ${i.error.message}`);if(typeof n.onChanged!=`function`)throw Error(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:a,debounceMs:o}=i.data,{onChanged:s}=n,c=async()=>{if(!a){s(null,null);return}try{let e=await r();s(null,e)}catch(e){let t=e instanceof Error?e:Error(String(e));s(t,null)}};this.setNotificationHandler(t,()=>{if(o){let t=this._listChangedDebounceTimers.get(e);t&&clearTimeout(t);let n=setTimeout(c,o);this._listChangedDebounceTimers.set(e,n)}else c()})}async sendRootsListChanged(){return this.notification({method:`notifications/roots/list_changed`})}},mM=E(((e,t)=>{t.exports=a,a.sync=o;var n=Me(`fs`);function r(e,t){var n=t.pathExt===void 0?process.env.PATHEXT:t.pathExt;if(!n||(n=n.split(`;`),n.indexOf(``)!==-1))return!0;for(var r=0;r<n.length;r++){var i=n[r].toLowerCase();if(i&&e.substr(-i.length).toLowerCase()===i)return!0}return!1}function i(e,t,n){return!e.isSymbolicLink()&&!e.isFile()?!1:r(t,n)}function a(e,t,r){n.stat(e,function(n,a){r(n,!n&&i(a,e,t))})}function o(e,t){return i(n.statSync(e),e,t)}})),hM=E(((e,t)=>{t.exports=r,r.sync=i;var n=Me(`fs`);function r(e,t,r){n.stat(e,function(e,n){r(e,!e&&a(n,t))})}function i(e,t){return a(n.statSync(e),t)}function a(e,t){return e.isFile()&&o(e,t)}function o(e,t){var n=e.mode,r=e.uid,i=e.gid,a=t.uid===void 0?process.getuid&&process.getuid():t.uid,o=t.gid===void 0?process.getgid&&process.getgid():t.gid,s=64,c=8,l=1,u=s|c;return n&l||n&c&&i===o||n&s&&r===a||n&u&&a===0}})),gM=E(((e,t)=>{Me(`fs`);var n=process.platform===`win32`||global.TESTING_WINDOWS?mM():hM();t.exports=r,r.sync=i;function r(e,t,i){if(typeof t==`function`&&(i=t,t={}),!i){if(typeof Promise!=`function`)throw TypeError(`callback not provided`);return new Promise(function(n,i){r(e,t||{},function(e,t){e?i(e):n(t)})})}n(e,t||{},function(e,n){e&&(e.code===`EACCES`||t&&t.ignoreErrors)&&(e=null,n=!1),i(e,n)})}function i(e,t){try{return n.sync(e,t||{})}catch(e){if(t&&t.ignoreErrors||e.code===`EACCES`)return!1;throw e}}})),_M=E(((e,t)=>{var n=process.platform===`win32`||process.env.OSTYPE===`cygwin`||process.env.OSTYPE===`msys`,r=Me(`path`),i=n?`;`:`:`,a=gM(),o=e=>Object.assign(Error(`not found: ${e}`),{code:`ENOENT`}),s=(e,t)=>{let r=t.colon||i,a=e.match(/\//)||n&&e.match(/\\/)?[``]:[...n?[process.cwd()]:[],...(t.path||process.env.PATH||``).split(r)],o=n?t.pathExt||process.env.PATHEXT||`.EXE;.CMD;.BAT;.COM`:``,s=n?o.split(r):[``];return n&&e.indexOf(`.`)!==-1&&s[0]!==``&&s.unshift(``),{pathEnv:a,pathExt:s,pathExtExe:o}},c=(e,t,n)=>{typeof t==`function`&&(n=t,t={}),t||={};let{pathEnv:i,pathExt:c,pathExtExe:l}=s(e,t),u=[],d=n=>new Promise((a,s)=>{if(n===i.length)return t.all&&u.length?a(u):s(o(e));let c=i[n],l=/^".*"$/.test(c)?c.slice(1,-1):c,d=r.join(l,e),p=!l&&/^\.[\\\/]/.test(e)?e.slice(0,2)+d:d;a(f(p,n,0))}),f=(e,n,r)=>new Promise((i,o)=>{if(r===c.length)return i(d(n+1));let s=c[r];a(e+s,{pathExt:l},(a,o)=>{if(!a&&o){if(t.all)u.push(e+s);else return i(e+s)}return i(f(e,n,r+1))})});return n?d(0).then(e=>n(null,e),n):d(0)};t.exports=c,c.sync=(e,t)=>{t||={};let{pathEnv:n,pathExt:i,pathExtExe:c}=s(e,t),l=[];for(let o=0;o<n.length;o++){let s=n[o],u=/^".*"$/.test(s)?s.slice(1,-1):s,d=r.join(u,e),f=!u&&/^\.[\\\/]/.test(e)?e.slice(0,2)+d:d;for(let e=0;e<i.length;e++){let n=f+i[e];try{if(a.sync(n,{pathExt:c})){if(t.all)l.push(n);else return n}}catch{}}}if(t.all&&l.length)return l;if(t.nothrow)return null;throw o(e)}})),vM=E(((e,t)=>{var n=(e={})=>{let t=e.env||process.env;return(e.platform||process.platform)===`win32`?Object.keys(t).reverse().find(e=>e.toUpperCase()===`PATH`)||`Path`:`PATH`};t.exports=n,t.exports.default=n})),yM=E(((e,t)=>{var n=Me(`path`),r=_M(),i=vM();function a(e,t){let a=e.options.env||process.env,o=process.cwd(),s=e.options.cwd!=null,c=s&&process.chdir!==void 0&&!process.chdir.disabled;if(c)try{process.chdir(e.options.cwd)}catch{}let l;try{l=r.sync(e.command,{path:a[i({env:a})],pathExt:t?n.delimiter:void 0})}catch{}finally{c&&process.chdir(o)}return l&&=n.resolve(s?e.options.cwd:``,l),l}function o(e){return a(e)||a(e,!0)}t.exports=o})),bM=E(((e,t)=>{var n=/([()\][%!^"`<>&|;, *?])/g;function r(e){return e=e.replace(n,`^$1`),e}function i(e,t){return e=`${e}`,e=e.replace(/(?=(\\+?)?)\1"/g,`$1$1\\"`),e=e.replace(/(?=(\\+?)?)\1$/,`$1$1`),e=`"${e}"`,e=e.replace(n,`^$1`),t&&(e=e.replace(n,`^$1`)),e}t.exports.command=r,t.exports.argument=i})),xM=E(((e,t)=>{t.exports=/^#!(.*)/})),SM=E(((e,t)=>{var n=xM();t.exports=(e=``)=>{let t=e.match(n);if(!t)return null;let[r,i]=t[0].replace(/#! ?/,``).split(` `),a=r.split(`/`).pop();return a===`env`?i:i?`${a} ${i}`:a}})),CM=E(((e,t)=>{var n=Me(`fs`),r=SM();function i(e){let t=Buffer.alloc(150),i;try{i=n.openSync(e,`r`),n.readSync(i,t,0,150,0),n.closeSync(i)}catch{}return r(t.toString())}t.exports=i})),wM=E(((e,t)=>{var n=Me(`path`),r=yM(),i=bM(),a=CM(),o=process.platform===`win32`,s=/\.(?:com|exe)$/i,c=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function l(e){e.file=r(e);let t=e.file&&a(e.file);return t?(e.args.unshift(e.file),e.command=t,r(e)):e.file}function u(e){if(!o)return e;let t=l(e),r=!s.test(t);if(e.options.forceShell||r){let r=c.test(t);e.command=n.normalize(e.command),e.command=i.command(e.command),e.args=e.args.map(e=>i.argument(e,r)),e.args=[`/d`,`/s`,`/c`,`"${[e.command].concat(e.args).join(` `)}"`],e.command=process.env.comspec||`cmd.exe`,e.options.windowsVerbatimArguments=!0}return e}function d(e,t,n){t&&!Array.isArray(t)&&(n=t,t=null),t=t?t.slice(0):[],n=Object.assign({},n);let r={command:e,args:t,options:n,file:void 0,original:{command:e,args:t}};return n.shell?r:u(r)}t.exports=d})),TM=E(((e,t)=>{var n=process.platform===`win32`;function r(e,t){return Object.assign(Error(`${t} ${e.command} ENOENT`),{code:`ENOENT`,errno:`ENOENT`,syscall:`${t} ${e.command}`,path:e.command,spawnargs:e.args})}function i(e,t){if(!n)return;let r=e.emit;e.emit=function(n,i){if(n===`exit`){let n=a(i,t);if(n)return r.call(e,`error`,n)}return r.apply(e,arguments)}}function a(e,t){return n&&e===1&&!t.file?r(t.original,`spawn`):null}function o(e,t){return n&&e===1&&!t.file?r(t.original,`spawnSync`):null}t.exports={hookChildProcess:i,verifyENOENT:a,verifyENOENTSync:o,notFoundError:r}})),EM=Ae(E(((e,t)=>{var n=Me(`child_process`),r=wM(),i=TM();function a(e,t,a){let o=r(e,t,a),s=n.spawn(o.command,o.args,o.options);return i.hookChildProcess(s,o),s}function o(e,t,a){let o=r(e,t,a),s=n.spawnSync(o.command,o.args,o.options);return s.error=s.error||i.verifyENOENTSync(s.status,o),s}t.exports=a,t.exports.spawn=a,t.exports.sync=o,t.exports._parse=r,t.exports._enoent=i}))(),1),DM=le.platform===`win32`?[`APPDATA`,`HOMEDRIVE`,`HOMEPATH`,`LOCALAPPDATA`,`PATH`,`PROCESSOR_ARCHITECTURE`,`SYSTEMDRIVE`,`SYSTEMROOT`,`TEMP`,`USERNAME`,`USERPROFILE`,`PROGRAMFILES`]:[`HOME`,`LOGNAME`,`PATH`,`SHELL`,`TERM`,`USER`];function OM(){let e={};for(let t of DM){let n=le.env[t];n!==void 0&&(n.startsWith(`()`)||(e[t]=n))}return e}var kM=class{constructor(e){this._stderrStream=null,this._serverParams=e,this._readBuffer=new Ij({maxBufferSize:e.maxBufferSize}),(e.stderr===`pipe`||e.stderr===`overlapped`)&&(this._stderrStream=new be)}async start(){if(this._process)throw Error(`StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.`);return new Promise((e,t)=>{this._process=(0,EM.default)(this._serverParams.command,this._serverParams.args??[],{env:{...OM(),...this._serverParams.env},stdio:[`pipe`,`pipe`,this._serverParams.stderr??`inherit`],shell:!1,windowsHide:le.platform===`win32`,cwd:this._serverParams.cwd}),this._process.on(`error`,e=>{t(e),this.onerror?.(e)}),this._process.on(`spawn`,()=>{e()}),this._process.on(`close`,e=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on(`error`,e=>{this.onerror?.(e)}),this._process.stdout?.on(`data`,e=>{try{this._readBuffer.append(e),this.processReadBuffer()}catch(e){this.onerror?.(e),this.close().catch(()=>{})}}),this._process.stdout?.on(`error`,e=>{this.onerror?.(e)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){return this._stderrStream?this._stderrStream:this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){if(this._process){let e=this._process;this._process=void 0;let t=new Promise(t=>{e.once(`close`,()=>{t()})});try{e.stdin?.end()}catch{}if(await Promise.race([t,new Promise(e=>setTimeout(e,2e3).unref())]),e.exitCode===null){try{e.kill(`SIGTERM`)}catch{}await Promise.race([t,new Promise(e=>setTimeout(e,2e3).unref())])}if(e.exitCode===null)try{e.kill(`SIGKILL`)}catch{}}this._readBuffer.clear()}send(e){return new Promise(t=>{if(!this._process?.stdin)throw Error(`Not connected`);let n=Rj(e);this._process.stdin.write(n)?t():this._process.stdin.once(`drain`,t)})}};async function AM(e,t,n,r=3e4,i){let a=new AbortController,o=()=>a.abort();i?.addEventListener(`abort`,o,{once:!0}),i?.aborted&&o();let s=setTimeout(o,r),c=``,l=!1;try{let r=await sb(e,t,a.signal,void 0,{maxAggregateRssBytes:1024**3,minFreeDiskBytes:256*1024**2,maxNewOutputBytes:1048576},void 0,void 0,{starting:()=>{},observed:()=>{},idle:()=>{l=!0},assertQuiescent:()=>{}},{environment:n,cwd:e,maxCapturedOutputBytes:1048576,stdoutOnly:!0,failedOutput:e=>{let t=e.toString(`utf8`).trimEnd().split(/\r?\n/u).at(-1);return[`ai-delivery: Configured personal author token is invalid or expired; refresh the selected token.`,`ai-delivery: Machine GitHub session is invalid or expired; verify the selected github.com account.`,`ai-delivery: Author cannot read the selected GitHub repository; verify configured access.`,`ai-delivery: Reviewer GitHub App cannot read the selected repository; verify its installation and repository access.`].includes(t??``)&&(c=t),` Authentication probe failed; raw output withheld.`}});return{failed:!l,stdout:l?r.toString(`utf8`):``,diagnostic:c,cleanupConfirmed:l}}catch{return{failed:!0,stdout:``,diagnostic:c,cleanupConfirmed:l}}finally{clearTimeout(s),i?.removeEventListener(`abort`,o)}}var jM=k().max(128).regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/u),MM=P({action:F([`install`,`doctor`,`update`,`rollback`,`remove`]),host:F([`codex`,`claude-code`]),scope:F([`user`,`project`,`local`]),version:jM.optional(),dryRun:j().default(!1),checkAuth:j().default(!1),repo:k().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u).optional(),repoRoot:k().min(1)}),NM=P({pid:A().int().positive(),birth:k().min(1)}),PM=P({action:MM.shape.action,targetVersion:jM.nullable(),owner:NM,producerDigest:k().regex(/^sha256:[a-f0-9]{64}$/u),staging:P({path:k(),device:A().int().nonnegative().optional(),inode:A().int().nonnegative().optional()}).optional(),command:Rl(`phase`,[P({phase:I(`idle`)}),P({phase:I(`starting`)}),P({phase:I(`running`),process:NM,tracked:M(NM.extend({pgid:A().int().positive()})).max(256)})])}),FM=P({owner:I(`@aviaratech/ai-delivery.plugin@1`),host:MM.shape.host,scope:MM.shape.scope,projectRoot:k().nullable(),nativeHome:k().min(1),marketplace:k(),currentVersion:jM.nullable(),previousVersion:jM.nullable(),installedPath:k().nullable(),nativeVersion:k().optional(),pending:PM.optional()}),IM=P({owner:I(`@aviaratech/ai-delivery.plugin-version@1`),version:jM,archiveSha256:k().regex(/^[a-f0-9]{64}$/u),files:Wl(k(),k().regex(/^[a-f0-9]{64}$/u))}),LM=e=>fe(`sha256`).update(e).digest(`hex`);function RM(){let e={PATH:process.env.PATH??``,DISABLE_AUTOUPDATER:`1`};for(let t of[`HOME`,`CODEX_HOME`,`CLAUDE_CONFIG_DIR`])process.env[t]!==void 0&&(e[t]=process.env[t]);return e}var zM=N({routing:N({repository:MM.shape.repo.unwrap()}),reviewRoute:N({author:N({actorLogin:k().regex(/^[A-Za-z0-9-]+(?:\[bot\])?$/u).max(200),authSource:F([`app`,`personal`]),credentialSource:k().optional(),identity:k()}),reviewer:N({actorLogin:k().regex(/^[A-Za-z0-9-]+(?:\[bot\])?$/u).max(200),identity:k(),repositoryAccess:I(`readable`)}),rules:N({visibility:F([`complete`,`partial`,`unknown`]),observedRequiredApprovals:A().int().nonnegative().nullable()}),approvalEligibility:F([`unknown`,`insufficient-permission`])})});async function BM(e,t,n){let r;try{r=await jh(),n.settings=`valid`}catch{n.settings=`unavailable_or_invalid`,n.outcome=`blocked`,n.reason=`settings_unavailable_or_invalid`;return}let i=Object.values(r.roles).flatMap(e=>Object.values(e.credentialEnv)),a=r.roles.author,o=a.authSource===`personal`&&Jm(a.credentialEnv.token,process.env),s=o?i.filter(e=>e!==`GH_TOKEN`):i;n.processReferences.requiredNames=s;let c=s.filter(e=>!process.env[e]?.trim());if(n.processReferences.missingNames=c,c.length>0){n.processReferences.status=`missing`,n.outcome=`blocked`,n.reason=`missing_references`;return}if(i.some(e=>/^(?:NODE_|NPM_|GIT_)/u.test(e)||[...Ym,`PATH`,`HOME`,`CODEX_HOME`,`CLAUDE_CONFIG_DIR`,`AI_DELIVERY_CONFIG`,`AI_DELIVERY_IDENTITY`,`DISABLE_AUTOUPDATER`].includes(e))){n.processReferences.status=`invalid`,n.outcome=`blocked`,n.reason=`invalid_references`;return}let l={PATH:process.env.PATH??``,AI_DELIVERY_CONFIG:r.configPath,NODE_OPTIONS:`--max-old-space-size=512 --v8-pool-size=1`,DISABLE_AUTOUPDATER:`1`};for(let e of i)process.env[e]!==void 0&&(l[e]=process.env[e].trim());if(o)for(let e of Ym)process.env[e]!==void 0&&(l[e]=process.env[e]);try{a.authSource===`personal`&&qm(process.env);for(let e of[`author`,`reviewer`])r.roles[e].authSource!==`personal`&&Nh({config:r,role:e,env:l})}catch{n.processReferences.status=`invalid`,n.outcome=`blocked`,n.reason=`invalid_references`;return}n.processReferences.status=`complete`;let u=await AM(e.repoRoot,[process.execPath,w(t,`runtime/dist/cli.js`),`--repo`,e.repo,`config:resolve`],l);if(!u.cleanupConfirmed){n.outcome=`failed`,n.authentication.status=`unverified`,n.repositoryAccess.status=`unverified`,n.reason=`probe_cleanup_unverified`;return}if(u.failed){n.outcome=`failed`,n.authentication.status=`unverified`,n.repositoryAccess.status=`unverified`;let e=u.diagnostic;e===`ai-delivery: Configured personal author token is invalid or expired; refresh the selected token.`||e===`ai-delivery: Machine GitHub session is invalid or expired; verify the selected github.com account.`?(n.authentication.status=`failed`,n.reason=`authentication_failed`):[`ai-delivery: Author cannot read the selected GitHub repository; verify configured access.`,`ai-delivery: Reviewer GitHub App cannot read the selected repository; verify its installation and repository access.`].includes(e??``)?(n.repositoryAccess.status=`denied`,n.reason=`repository_denied`):n.reason=`probe_failed`;return}try{let t=zM.parse(JSON.parse(u.stdout)),a=t.reviewRoute;if(t.routing.repository.toLowerCase()!==e.repo.toLowerCase()||a.author.authSource!==(r.roles.author.authSource??`app`)||a.author.identity!==r.roles.author.identity||a.reviewer.identity!==r.roles.reviewer.identity||a.author.actorLogin.toLowerCase()===a.reviewer.actorLogin.toLowerCase())throw Error(`Inconsistent readback`);let s={author:{actorLogin:a.author.actorLogin,authSource:a.author.authSource,...o&&a.author.credentialSource!==void 0?{credentialSource:a.author.credentialSource}:{}},reviewer:{actorLogin:a.reviewer.actorLogin,authSource:`app`}};if(o&&!a.author.credentialSource?.startsWith(`gh:github.com:`))throw Error(`Missing session route`);if(i.some(e=>l[e]!==void 0&&JSON.stringify(s).includes(l[e])))throw Error(`Unsafe readback`);n.authentication={status:`verified`,...s},n.repositoryAccess.status=`verified`,n.reviewRules={...a.rules,approvalEligibility:a.approvalEligibility},n.outcome=`readback_complete`}catch{n.authentication.status=`unverified`,n.repositoryAccess.status=`unverified`,n.outcome=`failed`,n.reason=`invalid_readback`}}function VM(e){let t=T(e);for(;;){if(i(t)&&c(t).isSymbolicLink())throw Error(`Managed plugin paths must not use symlinks.`);let e=C(t);if(e===t)break;t=e}}function HM(e){let t=h(T(e.repoRoot)),n=T(t,(e.host===`codex`?process.env.CODEX_HOME:process.env.CLAUDE_CONFIG_DIR)??w(de(),e.host===`codex`?`.codex`:`.claude`)),r=[];for(;!i(n);)r.unshift(ie(n)),n=C(n);let a=w(h(n),...r),o=e.scope===`user`?`user`:`${e.scope}-${fe(`sha256`).update(t).digest(`hex`).slice(0,16)}`,s=w(de(),`.cache`,`ai-delivery`,`plugins`,e.host,o);if(VM(s),i(s)&&(!c(s).isDirectory()||c(s).mode&63))throw Error(`Managed plugin directory is not private.`);return{directory:s,projectRoot:t,nativeHome:a,marketplace:`ai-delivery-${o}`,catalog:w(s,`marketplace`),statePath:w(s,`state.json`),tool:e.host===`codex`?`codex`:`claude`}}function UM(e,t){if(!i(t.statePath))return;let n=c(t.statePath);if(!n.isFile()||n.nlink!==1||n.mode&63||n.size>65536)throw Error(`Managed plugin state is unsafe.`);let r=FM.parse(JSON.parse(d(t.statePath,`utf8`)));if(r.nativeHome!==t.nativeHome)throw Error(`Managed plugin state belongs to a different native profile.`);if(r.host!==e.host||r.scope!==e.scope||r.marketplace!==t.marketplace||r.projectRoot!==(e.scope===`user`?null:t.projectRoot))throw Error(`Managed plugin state belongs to a different target.`);return r}function WM(e){let t=Vy().get(e);return t&&!t.status.startsWith(`Z`)?t.identity:void 0}async function GM(e){if(WM(e.owner.pid)===e.owner.birth)throw Error(`A live plugin installer still owns this target.`);if(e.command.phase===`starting`)throw Error(`Interrupted installer command ownership is unknown; preserve its state before recovery.`);if(e.command.phase!==`running`)return;let t={rootPid:e.command.process.pid,rootIdentity:e.command.process.birth,sampled:!0,tracked:new Map(e.command.tracked.map(({pid:e,birth:t,pgid:n})=>[e,{pid:e,identity:t,pgid:n,ppid:0,rssBytes:0,status:``}]))};Ky(t),await Gy(t)}async function KM(e,t,n,r,i,a=!1){return(await sb(n,[e,...t],r,void 0,{maxAggregateRssBytes:1024**3,minFreeDiskBytes:256*1024**2,maxNewOutputBytes:512*1024**2},void 0,void 0,{starting:()=>i?.({phase:`starting`}),observed:e=>i?.({phase:`running`,process:{pid:e.rootPid,birth:e.rootIdentity},tracked:[...e.tracked.values()].map(({pid:e,identity:t,pgid:n})=>({pid:e,birth:t,pgid:n}))}),idle:()=>i?.({phase:`idle`}),assertQuiescent:()=>{}},{environment:a?RM():{...process.env,DISABLE_AUTOUPDATER:`1`},cwd:n,maxCapturedOutputBytes:1048576,stdoutOnly:!0,failedOutput:e=>a?` Native inventory failed; raw output withheld.`:` Native command output: ${e.toString(`utf8`).slice(-2e3)}`})).toString(`utf8`)}function qM(e){let t=u(e,`r`);try{o(t)}finally{n(t)}}function JM(e,t){return w(e.catalog,`versions`,t,`plugins`,`ai-delivery`)}function YM(e,t){return w(e.catalog,`versions`,t)}function XM(e){let t={},n=0,r=(e,i,a)=>{if(a>16)throw Error(`Plugin tree exceeds the depth bound.`);for(let o of p(e).sort()){if(++n>4096)throw Error(`Plugin tree exceeds the entry bound.`);let s=w(e,o),l=`${i}${o}`,u=c(s);if(u.isSymbolicLink()||!u.isDirectory()&&(!u.isFile()||u.nlink!==1))throw Error(`Plugin tree contains links or special files.`);if(u.isDirectory())r(s,`${l}/`,a+1);else{if(u.size>32*1024**2)throw Error(`Plugin file exceeds the size bound.`);t[l]=LM(d(s))}}};return r(e,``,0),t}function ZM(e,t){let n=YM(e,t);VM(n);let r=w(n,`version.json`);if(!i(r))throw Error(`No completed immutable plugin unit for ${t}.`);let a=c(r),o=w(n,`archive.tgz`),s=c(o);if(!a.isFile()||a.nlink!==1||a.size>1048576||!s.isFile()||s.nlink!==1||s.size>32*1024**2)throw Error(`Immutable plugin unit metadata is unsafe.`);let l=IM.parse(JSON.parse(d(r,`utf8`)));if(l.version!==t||JSON.stringify(XM(JM(e,t)))!==JSON.stringify(l.files)||LM(d(o))!==l.archiveSha256)throw Error(`Immutable plugin unit integrity changed.`);return l}function QM(e){if(e.length>32*1024**2)throw Error(`Plugin archive exceeds 32 MiB.`);let t=ve(e,{maxOutputLength:128*1024**2}),n=new Map;for(let e=0;e+512<=t.length;){let r=t.subarray(e,e+512);if(r.every(e=>e===0))break;let i=(e,t)=>r.subarray(e,e+t).toString().replace(/\0.*$/su,``).trim(),a=(e,t)=>{let n=i(e,t);if(!/^[0-7]+$/u.test(n))throw Error(`Unsupported tar numeric header.`);return Number.parseInt(n,8)};if([...r].reduce((e,t,n)=>e+(n>=148&&n<156?32:t),0)!==a(148,8))throw Error(`Plugin archive header checksum mismatch.`);let o=`${i(345,155)?`${i(345,155)}/`:``}${i(0,100)}`,s=a(124,12),c=i(156,1);if(!/^package\/[A-Za-z0-9_./-]+$/u.test(o)||o.split(`/`).some(e=>e===`..`||e===`.`)||o.split(`/`).length>16||![``,`0`,`5`].includes(c)||e+512+s>t.length||n.has(o)||n.size>=4096)throw Error(`Unsafe or unsupported plugin archive member.`);c!==`5`&&n.set(o,t.subarray(e+512,e+512+s)),e+=512+Math.ceil(s/512)*512}return n}async function $M(e,t,n,r,a){let o=YM(e,t);if(i(o)){ZM(e,t);return}let s=C(o);Lv(s);let u=w(s,`.stage-${me()}`);a({path:u}),l(u,{mode:448});let f=c(u);qM(s),a({path:u,device:f.dev,inode:f.ino});let p=!0,m=!1,h,v=e=>{p=e.phase===`idle`,r(e)};try{let r=JSON.parse(await KM(`npm`,[`pack`,`@aviaratech/ai-delivery@${t}`,`--ignore-scripts`,`--json`,`--logs-max`,`0`,`--cache`,w(e.directory,`npm-cache`),`--pack-destination`,u],u,n,v))[0]?.filename;if(typeof r!=`string`||!/^aviaratech-ai-delivery-[A-Za-z0-9.+_-]+\.tgz$/u.test(r))throw Error(`npm returned an unsafe archive path.`);let i=d(w(u,r)),c=QM(i),l=JSON.parse(c.get(`package/package.json`)?.toString()??`null`);if(l?.name!==`@aviaratech/ai-delivery`||l.version!==t)throw Error(`Archive package identity does not match the explicit version.`);let f=w(u,`plugins`,`ai-delivery`);for(let[e,t]of c)if(e.startsWith(`package/plugins/ai-delivery/`)){let n=w(f,e.slice(28));Lv(C(n)),ee(n,t,{mode:384,flag:`wx`}),qM(n)}let p=JSON.parse(d(w(f,`plugin.json`),`utf8`)),m=JSON.parse(d(w(f,`.claude-plugin/plugin.json`),`utf8`)),h=JSON.parse(d(w(f,`runtime/package.json`),`utf8`));if(p.name!==`ai-delivery`||p.version!==t||m.name!==p.name||m.version!==t||m.packageVersion!==t||m.deliveryCapabilityVersion!==2||h.name!==l.name||h.version!==t)throw Error(`Archive does not contain a coherent self-contained native plugin.`);if((await KM(process.execPath,[w(f,`runtime/dist/cli.js`),`--version`],u,n,v)).trim()!==t)throw Error(`Built native CLI version does not match its archive.`);g(w(u,r),w(u,`archive.tgz`)),qM(w(u,`archive.tgz`)),zv(w(u,`version.json`),{owner:`@aviaratech/ai-delivery.plugin-version@1`,version:t,archiveSha256:LM(i),files:XM(f)}),g(u,o),qM(s),a(void 0),ZM(e,t)}catch(e){m=!0,h=e}try{if(p&&i(u)){let e=c(u);if(e.dev!==f.dev||e.ino!==f.ino||!e.isDirectory()||e.isSymbolicLink())throw Error(`Owned staging directory identity changed.`);_(u,{recursive:!0}),qM(s)}p&&a(void 0)}catch(e){h=m?AggregateError([h,e],`Plugin preparation failed and staging cleanup also failed.`):e,m=!0}if(m)throw h}function eN(e,t){ZM(e,t);let n=`./versions/${t}/plugins/ai-delivery`;zv(w(e.catalog,`.agents/plugins/marketplace.json`),{name:e.marketplace,interface:{displayName:`ai-delivery`},plugins:[{name:`ai-delivery`,source:{source:`local`,path:n},policy:{installation:`AVAILABLE`,authentication:`ON_INSTALL`},category:`Productivity`}]}),zv(w(e.catalog,`.claude-plugin/marketplace.json`),{name:e.marketplace,owner:{name:`AviaraTech`},plugins:[{name:`ai-delivery`,source:n,version:t}]})}async function tN(e,t,n,r){let i=JSON.parse(await KM(t.tool,[`plugin`,`list`,...e.host===`codex`?[`--marketplace`,t.marketplace,`--available`]:[],`--json`],t.projectRoot,n,r,e.action===`doctor`));if(e.host===`claude-code`)return M(Wl(k(),kl())).parse(i);let a=N({installed:M(Wl(k(),kl())),available:M(Wl(k(),kl()))}).parse(i);return[...a.installed.map(e=>({...e,installed:!0})),...a.available.map(e=>({...e,installed:!1}))]}function nN(e,t,n){if(e.host===`claude-code`){let e=w(t.nativeHome,`plugins/known_marketplaces.json`);if(!i(e))return!1;if(!c(e).isFile()||c(e).size>1048576)throw Error(`Native marketplace registry is unsafe.`);let n=Wl(k(),kl()).parse(JSON.parse(d(e,`utf8`)));if(n[t.marketplace]===void 0)return!1;let r=N({source:N({source:I(`directory`),path:k()}),installLocation:k()}).parse(n[t.marketplace]);if(T(r.source.path)!==t.catalog||T(r.installLocation)!==t.catalog)throw Error(`Native marketplace name belongs to an unmanaged source.`);return!0}let r=n.filter(e=>e.marketplaceName===t.marketplace);for(let e of r){let n=N({sourceType:I(`local`),source:k()}).parse(e.marketplaceSource);if(T(n.source)!==t.catalog)throw Error(`Native marketplace name belongs to an unmanaged source.`)}return r.length>0}function rN(e,t,n){let r=n.filter(n=>(n.pluginId??n.id)===`ai-delivery@${t.marketplace}`&&(e.host===`codex`?n.installed===!0:n.scope===e.scope)&&(e.scope===`user`||n.projectPath===t.projectRoot));if(r.length>1)throw Error(`Native plugin readback is ambiguous.`);let i=r[0];if(!i)return;let a=e.host===`codex`?N({source:I(`local`),path:k()}).parse(i.source).path:void 0;return{version:jM.parse(i.version),enabled:j().parse(i.enabled),...typeof i.installPath==`string`?{installedPath:i.installPath}:{},...a?{sourceRoot:a}:{},...i.mcpServers?{mcpServers:Wl(k(),kl()).parse(i.mcpServers)}:{}}}function iN(e){let t=w(e.catalog,`.claude-plugin/marketplace.json`);if(VM(t),!c(t).isFile()||c(t).size>1048576)throw Error(`Managed Claude catalog is unsafe.`);let n=N({name:I(e.marketplace),plugins:M(N({name:k(),version:jM,source:k()}))}).parse(JSON.parse(d(t,`utf8`))).plugins.filter(e=>e.name===`ai-delivery`);if(n.length!==1)throw Error(`Managed Claude catalog selection is ambiguous.`);let r=n[0];if(!r.source.startsWith(`./`)||T(e.catalog,r.source)!==JM(e,r.version))throw Error(`Claude catalog source differs from the immutable managed unit.`);return r}function aN(e,t,n,r,i=n.version){let a=ZM(t,e.host===`claude-code`?i:n.version),o=JM(t,e.host===`claude-code`?i:n.version);if(e.host===`claude-code`&&iN(t).version!==i)throw Error(`Claude catalog version differs from its native selection.`);if(e.host===`codex`&&T(n.sourceRoot)!==o)throw Error(`Native plugin source differs from the managed version.`);let s=e.host===`codex`?r:o;if(!s)throw Error(`Native cache path is missing.`);if(e.host===`codex`&&T(s)!==w(t.nativeHome,`plugins/cache`,t.marketplace,`ai-delivery`,n.version))throw Error(`Native cache path is outside the managed native selection.`);if(VM(s),JSON.stringify(XM(s))!==JSON.stringify(a.files))throw Error(`Selected native plugin bytes differ from the verified archive.`);if(e.host===`claude-code`&&!N({command:I(`node`),args:Hl([I("${CLAUDE_PLUGIN_ROOT}/dist/mcp-launcher.js")])}).parse(n.mcpServers?.[`ai-delivery`]))throw Error(`Native MCP binding is missing.`);return s}async function oN(e,t,n){let r=new kM({command:process.execPath,args:[w(e,`dist/mcp-launcher.js`)],cwd:n,env:{...Object.fromEntries(DM.map(e=>[e,``])),NODE_OPTIONS:`--max-old-space-size=1024`},stderr:`pipe`,maxBufferSize:1048576}),i=new pM({name:`ai-delivery-plugin-doctor`,version:`1.0.0`});try{if(await i.connect(r,{timeout:3e4}),i.getServerVersion()?.version!==t)throw Error(`MCP server version differs from the selected archive.`);return await i.listTools({},{timeout:3e4}),{configuration:`native_manifest_present`,startup:`ready`,version:t}}catch{return{configuration:`native_manifest_present`,startup:`failed`,error:`Bundled MCP startup failed; raw output withheld.`}}finally{await i.close(),await r.close()}}async function sN(e){let t=MM.parse(e);if(t.checkAuth&&t.action!==`doctor`)throw Error(`--check-auth is supported only for doctor.`);if(t.checkAuth&&t.repo===void 0)throw Error(`doctor --check-auth requires explicit --repo owner/name.`);if(t.host===`codex`&&t.scope!==`user`)throw Error(`Codex currently supports user plugin installation; select --scope user.`);if((t.action===`install`||t.action===`update`)&&t.version===void 0)throw Error(`An explicit --version is required for install and update.`);if(t.version!==void 0&&t.action!==`install`&&t.action!==`update`)throw Error(`--version is supported only for install and update; rollback selects the recorded previous version.`);if(![`darwin`,`linux`].includes(process.platform))throw Error(`Plugin management requires the supported POSIX runtime environment.`);let n=HM(t),r=UM(t,n),a={action:t.action,host:t.host,scope:t.scope,version:t.action===`remove`?null:t.version??(t.action===`rollback`?r?.previousVersion:r?.currentVersion)??null,changed:!1,dryRun:t.dryRun,installed:!1,marketplace:n.marketplace,managedDirectory:n.directory,repositoryAdmission:`explicit_stage_and_admit_required`};if(t.checkAuth&&(a.authProbe={invocationContext:`selected_runtime_cli`,nativeGuiPropagation:`unverified`,settings:`not_checked`,processReferences:{status:`not_checked`,requiredNames:[],missingNames:[]},authentication:{status:`not_checked`},repositoryAccess:{repository:t.repo,status:`not_checked`},outcome:t.dryRun?`not_checked`:`blocked`,reason:t.dryRun?`dry_run`:`native_plugin_not_ready`}),t.dryRun)return a;if(t.action===`doctor`){if(!r||(a.recoveryRequired=r.pending!==void 0,r.pending||!r.currentVersion))return a;try{ZM(n,r.currentVersion)}catch{return a.sourceIntegrity=!1,a.mcp={configuration:`unverified`,startup:`not_checked`,error:`Managed archive integrity failed.`},a}let e=await tN(t,n,new AbortController().signal),i=nN(t,n,e),o=rN(t,n,e);if(a.installed=o?.version===r.currentVersion,a.enabled=o?.enabled??!1,r.installedPath&&(a.nativeCachePath=r.installedPath),r.nativeVersion&&(a.nativeVersion=r.nativeVersion),!i||!a.installed)return a.mcp={configuration:`missing`,startup:`not_checked`},a;try{a.nativePluginRoot=aN(t,n,o,r.installedPath),a.sourceIntegrity=!0,a.skills=p(w(a.nativePluginRoot,`skills`)).sort(),a.mcp=o.enabled?await oN(a.nativePluginRoot,r.currentVersion,n.projectRoot):{configuration:`disabled`,startup:`not_checked`}}catch(e){a.sourceIntegrity=!1,a.mcp={configuration:`unverified`,startup:`not_checked`,error:t.checkAuth?`Selected native plugin integrity failed; raw output withheld.`:(e instanceof Error?e.message:String(e)).slice(0,2e3)}}return a.authProbe&&a.sourceIntegrity&&a.enabled&&a.mcp?.startup===`ready`&&(delete a.authProbe.reason,await BM(t,a.nativePluginRoot,a.authProbe)),a}if(!r&&t.action===`remove`)return a;if(!r&&i(n.directory)&&p(n.directory).length>0)throw Error(`Managed plugin directory contains unrecognized content.`);return Lv(n.directory),py(n.statePath,{projectRoot:n.directory,timeout:200,onReleaseError:e=>{throw e},operation:async()=>{r=UM(t,n);let e=r?.pending!==void 0;if(r?.pending){if(await GM(r.pending),r.pending.producerDigest!==nb(C(ye(import.meta.url))))throw Error(`Interrupted plugin operation belongs to a different controller; resume with its original version.`);let e=r.pending.staging;if(e&&i(e.path)){let t=C(YM(n,r.pending.targetVersion));if(C(e.path)!==t||!/^\.stage-[a-f0-9-]{36}$/u.test(e.path.slice(t.length+1)))throw Error(`Recorded staging path is outside this version target.`);VM(e.path);let i=c(e.path);if(!i.isDirectory()||(e.device===void 0?p(e.path).length!==0:i.dev!==e.device||i.ino!==e.inode))throw Error(`Interrupted staging directory ownership is unresolved.`);_(e.path,{recursive:!0}),qM(t)}if(r.pending.action!==t.action||r.pending.targetVersion!==a.version)throw Error(`Resume the interrupted original plugin command before selecting a different operation.`)}if((t.action===`update`||t.action===`rollback`)&&(!r||t.action===`update`&&!r.currentVersion))throw Error(`Install a managed plugin before updating or rolling it back.`);let o=t.action===`remove`?null:a.version;if(o===null&&t.action!==`remove`)throw Error(`No previous managed plugin version is available.`);let s=r?.currentVersion??null;r??={owner:`@aviaratech/ai-delivery.plugin@1`,host:t.host,scope:t.scope,projectRoot:t.scope===`user`?null:n.projectRoot,nativeHome:n.nativeHome,marketplace:n.marketplace,currentVersion:null,previousVersion:null,installedPath:null};let l=WM(process.pid);if(!l)throw Error(`Installer owner identity is unknown.`);r.pending={action:t.action,targetVersion:o,owner:{pid:process.pid,birth:l},producerDigest:nb(C(ye(import.meta.url))),command:{phase:`idle`}},zv(n.statePath,r);let u=new AbortController,d=()=>u.abort();process.once(`SIGINT`,d),process.once(`SIGTERM`,d);let f=e=>{r.pending.command=e,zv(n.statePath,r)},m=e=>KM(n.tool,e,n.projectRoot,u.signal,f),h=`ai-delivery@${n.marketplace}`,g=t.host===`codex`?[`plugin`,`remove`,h,`--json`]:[`plugin`,`uninstall`,h,`--scope`,t.scope,`--keep-data`],v=t.host===`codex`?[`plugin`,`add`,h,`--json`]:[`plugin`,`install`,h,`--scope`,t.scope],y=!1;try{if(r.nativeVersion=(await m([`--version`])).trim(),t.host===`claude-code`&&!(await m([`plugin`,`uninstall`,`--help`])).includes(`--keep-data`))throw Error(`This Claude Code version cannot preserve plugin data; upgrade the native tool first.`);process.stderr.write(`ai-delivery.plugin ${JSON.stringify({action:t.action,host:t.host,scope:t.scope,stage:o?`prepare_version`:`native_remove`,version:o})}\n`);let i=await tN(t,n,u.signal,f),c=nN(t,n,i),l=rN(t,n,i);if(l&&!s&&!(e&&l.version===o))throw Error(`Existing native plugin is not owned by managed state.`);let d=l?.version;if(l&&e&&t.host===`claude-code`&&(d=iN(n).version,d!==s&&d!==o))throw Error(`Interrupted native selection has an incompatible catalog version.`);l&&aN(t,n,l,l.version===s?r.installedPath:w(n.nativeHome,`plugins/cache`,n.marketplace,`ai-delivery`,l.version),d),o&&(await $M(n,o,u.signal,f,e=>{e?r.pending.staging=e:delete r.pending.staging,zv(n.statePath,r)}),y=!0,eN(n,o),c||await m([`plugin`,`marketplace`,`add`,n.catalog,...t.host===`codex`?[`--json`]:[`--scope`,t.scope]])),l&&(l.version!==o||t.action===`remove`)&&(y=!0,await m(g));let p=r.installedPath;if(o){let e=await m(v);t.host===`codex`&&(p=N({installedPath:k()}).parse(JSON.parse(e)).installedPath)}let h=await tN(t,n,u.signal,f);if(!nN(t,n,h)&&o)throw Error(`Native marketplace registration is missing.`);let _=rN(t,n,h);if(o?_?.version!==o:_!==void 0)throw Error(`Native installation readback does not match the selected version.`);if(o&&(aN(t,n,_,_?.installedPath??p),!_.enabled))throw Error(`Native plugin selection is disabled.`);return r.currentVersion=o,s!==o&&(r.previousVersion=s),r.installedPath=o?_?.installedPath??p:null,delete r.pending,zv(n.statePath,r),a.version=o,a.changed=s!==o,a.installed=o!==null,a.restartRequired=!0,o&&(a.nativePluginRoot=t.host===`codex`?r.installedPath??JM(n,o):JM(n,o)),a}catch(t){if(!e&&!u.signal.aborted&&!y&&r.pending?.command.phase===`idle`&&r.pending.staging===void 0){delete r.pending;try{zv(n.statePath,r)}catch(e){throw AggregateError([t,e],`Plugin preparation failed and pending-state cleanup also failed.`)}}if(y&&s)try{eN(n,s)}catch{}throw t}finally{process.removeListener(`SIGINT`,d),process.removeListener(`SIGTERM`,d)}}})}var cN=new Ke;cN.name(`ai-delivery`).description(`Generic GitHub issue and pull request delivery`).version(Vj).option(`--identity <name>`,`Configured author or reviewer identity`).option(`--personal-auth`,`Explicit legacy personal-token author override`).option(`--repo <owner/name>`,`GitHub repository owner/name; works from any directory`).option(`--repo-root <path>`,`Launch directory or explicit clone for local operations`,process.cwd());for(let e=2;e<process.argv.length;e++){let t=process.argv[e],n=cN.options.find(e=>e.long===t.split(`=`)[0]||e.short===t);if(n){n.required&&!t.includes(`=`)&&e++;continue}t===`plugin`&&cN.enablePositionalOptions();break}function lN(){let e=cN.opts(),t=(e.identity??process.env.AI_DELIVERY_IDENTITY)?.trim()||void 0;return{repoRoot:e.repoRoot,...t===void 0?{}:{identity:t},personalAuth:e.personalAuth===!0,...e.repo===void 0?{}:{repo:e.repo}}}function uN(e){return e===void 0?void 0:Number(e)}function dN(e){return e===void 0?void 0:e.split(`,`).map(e=>e.trim()).filter(Boolean)}function fN(e){return dN(e)?.map(Number)}function pN(e,t){if(e!==void 0&&t!==void 0)throw Error(`Pass either --body or --body-file.`);return t===void 0?e:d(t,`utf8`)}function mN(e,t){let n=e===void 0?{}:JSON.parse(d(e,`utf8`));return{...G_.parse(n),...Object.fromEntries(Object.entries(t).filter(([,e])=>e!==void 0))}}function hN(e,t){return qC(e,t,lN()).then(t=>Xe(e,t))}function gN(e){process.stdout.write(`${JSON.stringify(e,null,2)}\n`)}var _N=cN.command(`plugin`).description(`Manage the ai-delivery native plugin`);for(let e of[`install`,`doctor`,`update`,`rollback`,`remove`]){let t=_N.command(e).requiredOption(`--host <host>`,`Native host: codex or claude-code`).option(`--scope <scope>`,`Native scope: user, project, or local; Codex supports user`,`user`).option(`--dry-run`,`Describe the selected target without changing files or contacting native tools`).option(`--json`,`Print the result as JSON`);(e===`install`||e===`update`)&&t.requiredOption(`--version <version>`,`Explicit published package version`),e===`doctor`&&t.option(`--check-auth`,`Read configured role identities and repository access; requires explicit --repo`),t.action(async t=>{let n=await sN({action:e,host:t.host,scope:t.scope,...t.version===void 0?{}:{version:t.version},dryRun:t.dryRun===!0,checkAuth:t.checkAuth===!0,...t.checkAuth&&lN().repo?{repo:lN().repo}:{},repoRoot:lN().repoRoot});if(t.json){gN(n);return}process.stdout.write(`${n.dryRun?`Dry run: `:``}${n.host} ${n.scope}: ${e}; version ${n.version??`none`}; installed ${n.installed}; changed ${n.changed}\n`),n.mcp&&process.stdout.write(`Bundled MCP startup: ${n.mcp.startup}${n.mcp.error?` (${n.mcp.error})`:``}\n`),n.recoveryRequired&&process.stdout.write(`Resume the interrupted original plugin command to recover this target.
|
|
310
|
-
`),n.authProbe&&process.stdout.write(`Selected-runtime CLI auth probe: ${n.authProbe.outcome}; settings ${n.authProbe.settings}; process references ${n.authProbe.processReferences.status}; authentication ${n.authProbe.authentication.status}; repository access ${n.authProbe.repositoryAccess.status}${n.authProbe.reason?` (${n.authProbe.reason})`:``}\nNative GUI credential propagation and counted exact-head approval remain unverified.\n`)})}cN.command(`runtime:stage`).description(`Stage a reviewed archive in a private directory; does not activate or admit it`).requiredOption(`--archive <path>`).requiredOption(`--archive-sha256 <digest>`).requiredOption(`--package-version <version>`).requiredOption(`--source-commit <sha>`).requiredOption(`--config-digest <digest>`).requiredOption(`--runtime-directory <path>`).option(`--native-plugin-root <path>`,`Bind the exact reviewed native plugin root`).option(`--max-aggregate-rss-bytes <bytes>`,`Sampled controller plus children RSS limit`).option(`--max-new-output-bytes <bytes>`,`Owned stage and metadata output limit`).option(`--min-free-disk-bytes <bytes>`,`Required free disk headroom`).option(`--max-captured-output-bytes <bytes>`,`Retained command log cap; defaults to 1 MiB`).option(`--authorize-stage`,`Explicit authority to stage this reviewed archive`).action(async e=>hN(`runtime_stage`,{authority:e.authorizeStage===!0?`runtime:stage`:``,archivePath:e.archive,expectedArchiveSha256:e.archiveSha256,packageVersion:e.packageVersion,expectedSourceCommit:e.sourceCommit,expectedConfigDigest:e.configDigest,runtimeDirectory:e.runtimeDirectory,...e.nativePluginRoot===void 0?{}:{nativePluginRoot:e.nativePluginRoot},...[`maxAggregateRssBytes`,`maxNewOutputBytes`,`minFreeDiskBytes`,`maxCapturedOutputBytes`].some(t=>e[t]!==void 0)?{resourceBounds:{maxAggregateRssBytes:Number(e.maxAggregateRssBytes??1024**3),minFreeDiskBytes:Number(e.minFreeDiskBytes??256*1024**2),maxNewOutputBytes:Number(e.maxNewOutputBytes??512*1024**2),maxCapturedOutputBytes:Number(e.maxCapturedOutputBytes??1024**2)}}:{}})),cN.command(`runtime:admit`).description(`Explicitly publish the existing admission for an exact completed stage`).requiredOption(`--stage-id <digest>`).requiredOption(`--source-commit <sha>`).requiredOption(`--config-digest <digest>`).requiredOption(`--runtime-directory <path>`).option(`--expected-prior <digest>`,`SHA-256 of the exact current private admission bytes`).option(`--expected-absent`,`Explicitly require no current admission`).option(`--authorize-admit`,`Explicit authority for the final admission write`).action(async e=>{if(e.expectedPrior===void 0==(e.expectedAbsent!==!0))throw Error(`Choose exactly one of --expected-prior or --expected-absent.`);return hN(`runtime_admit`,{authority:e.authorizeAdmit===!0?`runtime:admit`:``,stageId:e.stageId,expectedSourceCommit:e.sourceCommit,expectedConfigDigest:e.configDigest,runtimeDirectory:e.runtimeDirectory,expectedPriorAdmissionSha256:e.expectedAbsent===!0?null:e.expectedPrior})}),cN.command(`create`).requiredOption(`--title <title>`).option(`--fields-file <path>`,`UTF-8 JSON typed fields; explicit CLI fields take precedence`).option(`--draft`,`Explicitly write an incomplete parked draft`).option(`--body <markdown>`).option(`--body-file <path>`).option(`--type <type>`).option(`--points <number>`).option(`--priority <priority>`).option(`--labels <labels>`).option(`--blocked-by <numbers>`).option(`--blocks <numbers>`,`Add this issue as a blocker of these dependents`).option(`--override-reason <reason>`,`Required explanation when adding a blocker to active work`).option(`--milestone <number>`).option(`--parent <number>`).action(async e=>hN(`issue_create`,mN(e.fieldsFile,{title:e.title,body:pN(e.body,e.bodyFile),issueType:e.type,points:uN(e.points),priority:e.priority,labels:dN(e.labels),blockedBy:fN(e.blockedBy),blocks:fN(e.blocks),overrideReason:e.overrideReason,milestone:uN(e.milestone),parentIssueNumber:uN(e.parent),...e.draft===!0?{draft:!0}:{}}))),cN.command(`start`).option(`--issue <number>`).option(`--request <text>`).option(`--request-id <id>`,`Stable retry identity for a new issue start`).option(`--title <title>`).option(`--body <markdown>`).option(`--body-file <path>`).option(`--type <type>`).option(`--points <number>`).option(`--priority <priority>`).option(`--labels <labels>`).option(`--blocked-by <numbers>`).option(`--blocks <numbers>`,`Add this issue as a blocker of these dependents`).option(`--override-reason <reason>`,`Required explanation when adding a blocker to active work`).option(`--milestone <number>`).option(`--parent <number>`).option(`--branch <branch>`).option(`--resume-created`).option(`--investigation-worktree <path>`,`Prospectively register an already linked host-created investigation`).option(`--expected-head <sha>`,`Exact unchanged initial commit for investigation registration`).action(async e=>{if(e.investigationWorktree!==void 0||e.expectedHead!==void 0){if(Object.keys(e).some(e=>![`issue`,`investigationWorktree`,`expectedHead`].includes(e)))throw Error(`Investigation registration cannot create or change issue/branch metadata.`);return hN(`issue_start`,{issueNumber:uN(e.issue),investigationWorktree:e.investigationWorktree,expectedHeadSha:e.expectedHead})}return hN(`issue_start`,{issueNumber:uN(e.issue),request:e.request,requestId:e.requestId,title:e.title,body:pN(e.body,e.bodyFile),issueType:e.type,points:uN(e.points),priority:e.priority,labels:dN(e.labels),blockedBy:fN(e.blockedBy),blocks:fN(e.blocks),overrideReason:e.overrideReason,milestone:uN(e.milestone),parentIssueNumber:uN(e.parent),branch:e.branch,resumeCreated:e.resumeCreated===!0})});for(let e of[`list`,`search`])cN.command(e).option(`--query <text>`,`Literal text to search in the selected repository`).option(`--state <state>`).option(`--labels <labels>`).option(`--parent <number>`).option(`--type <type>`).option(`--project-status <status>`).option(`--updated-since <timestamp>`).option(`--page <number>`).option(`--per-page <number>`).action(async t=>hN(e===`list`?`issue_list`:`issue_search`,{query:t.query,state:t.state,labels:dN(t.labels),parentIssueNumber:uN(t.parent),issueType:t.type,projectStatus:t.projectStatus,updatedSince:t.updatedSince,page:uN(t.page),perPage:uN(t.perPage)}));cN.command(`update`).requiredOption(`--issue <number>`).option(`--fields-file <path>`,`UTF-8 JSON typed issue field patch`).option(`--draft`,`Explicitly write an incomplete parked draft`).option(`--title <title>`).option(`--body <markdown>`).option(`--body-file <path>`).option(`--type <type>`).option(`--points <number>`).option(`--priority <priority>`).option(`--labels <labels>`).option(`--blocked-by <numbers>`).option(`--blocks <numbers>`,`Add this issue as a blocker of these dependents`).option(`--override-reason <reason>`,`Required explanation when adding a blocker to active work`).option(`--milestone <number>`).option(`--parent <number>`).option(`--state <state>`).option(`--preserve-history`,`Preserve the previous title and body before a rewrite`).option(`--close-reason <reason>`).option(`--superseded-by <number>`).option(`--park`,`Park execution while retaining the issue worktree`).action(async e=>hN(`issue_update`,mN(e.fieldsFile,{issueNumber:uN(e.issue),title:e.title,...e.draft===!0?{draft:!0}:{},body:pN(e.body,e.bodyFile),issueType:e.type,points:uN(e.points),priority:e.priority,labels:dN(e.labels),blockedBy:fN(e.blockedBy),blocks:fN(e.blocks),overrideReason:e.overrideReason,milestone:uN(e.milestone),parentIssueNumber:uN(e.parent),state:e.state,preserveHistory:e.preserveHistory===!0||void 0,closeReason:e.closeReason,supersededBy:uN(e.supersededBy),park:e.park===!0||void 0}))),cN.command(`health`).requiredOption(`--from <utc>`,`Inclusive UTC ISO timestamp`).requiredOption(`--to <utc>`,`Exclusive UTC ISO timestamp`).option(`--max-issues <number>`).option(`--max-timeline-pages <number>`).option(`--max-project-pages <number>`).option(`--oldest-limit <number>`).action(async e=>hN(`delivery_health`,{repo:lN().repo,from:e.from,to:e.to,maxIssues:uN(e.maxIssues),maxTimelinePages:uN(e.maxTimelinePages),maxProjectPages:uN(e.maxProjectPages),oldestLimit:uN(e.oldestLimit)})),cN.command(`info`).requiredOption(`--issue <number>`).action(async e=>hN(`issue_info`,{issueNumber:uN(e.issue)})),cN.command(`ready:check`).requiredOption(`--issue <number>`).action(async e=>hN(`issue_ready_check`,{issueNumber:uN(e.issue)}));for(let e of[`parent`,`blockers`])cN.command(e).requiredOption(`--issue <number>`).action(async t=>{let n=await qC(`issue_info`,{issueNumber:uN(t.issue)},lN());gN(e===`parent`?{issueNumber:uN(t.issue),parentIssueNumber:n.parentIssueNumber}:{issueNumber:uN(t.issue),blockedBy:n.blockedBy})});cN.command(`subissues`).requiredOption(`--issue <number>`).action(async e=>{let t=await GC(lN(),`subissues`);gN({issueNumber:uN(e.issue),subissues:await jv(t,Number(e.issue))})}),cN.command(`pr:create`).description(`Create a PR from a linked issue branch, or promote an existing associated PR with --head and --ready.`).requiredOption(`--issue <number>`).option(`--pr <number>`,`Exact existing PR selector; never creates a replacement`).option(`--non-closing`,`Retain the issue OPEN using native non-closing reference proof`).option(`--title <title>`).option(`--body-file <path>`).option(`--head <branch>`,`Explicit remote head; existing PR promotion verifies its native issue association`).option(`--ready`,`Publish ready, or promote the author-owned PR selected by --head`).option(`--dry-run`).action(async e=>hN(`issue_pr_create`,{issueNumber:uN(e.issue),prNumber:uN(e.pr),nonClosing:e.nonClosing,title:e.title,body:pN(void 0,e.bodyFile),headBranch:e.head,draft:e.ready!==!0,dryRun:e.dryRun===!0})),cN.command(`pr:info`).description(`Inspect an exact PR; combine --issue and --pr to verify its native closing-issue association.`).option(`--non-closing`,`Verify an exact native non-closing PR-to-issue reference`).option(`--issue <number>`,`Issue to verify; issue-only lookup requires a GitHub-linked branch`).option(`--pr <number>`,`Exact PR number; include --issue after issue branch links are replaced on publication`).action(async e=>hN(`issue_pr_info`,{issueNumber:uN(e.issue),prNumber:uN(e.pr),nonClosing:e.nonClosing})),cN.command(`pr:list`).option(`--state <state>`,`open, closed or all`,`open`).action(async e=>{if(![`open`,`closed`,`all`].includes(e.state))throw Error(`Invalid PR state.`);gN(await WS(await GC(lN(),`pr:list`),e.state))}),cN.command(`pr:checks`).requiredOption(`--pr <number>`).action(async e=>{gN(await GS(await GC(lN(),`pr:checks`),Number(e.pr)))}),cN.command(`pr:review`).requiredOption(`--issue <number>`).requiredOption(`--pr <number>`).requiredOption(`--artifact <path>`,`Path to a UTF-8 JSON review artifact file (not inline JSON)`).option(`--non-closing`,`Retain the referenced issue OPEN; finish refuses this mode`).option(`--dry-run`).action(async e=>hN(`issue_pr_review`,{issueNumber:uN(e.issue),prNumber:uN(e.pr),artifact:d(e.artifact,`utf8`),dryRun:e.dryRun===!0,nonClosing:e.nonClosing}));for(let[e,t]of[[`pr:merge`,`issue_pr_merge`],[`finish`,`issue_finish`]]){let n=cN.command(e).requiredOption(`--issue <number>`);e===`pr:merge`?n.requiredOption(`--pr <number>`):n.option(`--pr <number>`),n.option(`--strategy <method>`).option(`--reviewed-head <sha>`).option(`--non-closing`,`Retain the referenced issue OPEN; finish refuses this mode`).option(`--dry-run`),e===`finish`&&n.option(`--investigation`,`Complete an unchanged prospectively registered investigation`).option(`--result <path>`,`Durable independently reviewed result outside the removable worktree`).option(`--authority-comment <number>`,`Exact native operator removal authority comment`).option(`--acceptance-comment <number>`,`Exact configured-App result acceptance comment`),n.action(async e=>{if(e.investigation===!0){if(e.pr!==void 0||e.strategy!==void 0||e.reviewedHead!==void 0||e.nonClosing!==void 0)throw Error(`Investigation completion cannot accept PR or merge options.`);return hN(t,{issueNumber:uN(e.issue),investigation:!0,resultPath:e.result,authorityCommentId:uN(e.authorityComment),acceptanceCommentId:uN(e.acceptanceComment),dryRun:e.dryRun===!0})}if(e.result!==void 0||e.authorityComment!==void 0||e.acceptanceComment!==void 0)throw Error(`Investigation evidence requires --investigation.`);return hN(t,{issueNumber:uN(e.issue),prNumber:uN(e.pr),strategy:e.strategy,reviewedHeadSha:e.reviewedHead,dryRun:e.dryRun===!0,nonClosing:e.nonClosing})})}cN.command(`worktree:transition:inspect`).requiredOption(`--issue <number>`).requiredOption(`--purpose <purpose>`,`active-resume or merged-cleanup`).option(`--disposition <disposition>`,`retain (default) or explicitly unheld remove`).option(`--terminal-pr <number>`).option(`--retained-holds <comment-ids>`,`Comma-separated native retained-hold comment IDs`).option(`--retained-admission <path>`).option(`--retained-archive <path>`).action(async e=>hN(`issue_worktree_transition_inspect`,{issueNumber:uN(e.issue),purpose:e.purpose,...e.disposition===void 0?{}:{disposition:e.disposition},...e.terminalPr===void 0?{}:{terminalPrNumber:uN(e.terminalPr)},...e.retainedHolds===void 0?{}:{retainedHoldCommentIds:fN(e.retainedHolds)},...e.retainedAdmission===void 0?{}:{retainedAdmissionPath:e.retainedAdmission},...e.retainedArchive===void 0?{}:{retainedArchivePath:e.retainedArchive}})),cN.command(`worktree:transition:apply`).requiredOption(`--plan <path>`).requiredOption(`--plan-id <digest>`).requiredOption(`--relinquishment-comment <id>`).requiredOption(`--acceptance-comment <id>`).option(`--authorize-transition`,`Explicit authority for this exact independently accepted plan`).action(async e=>hN(`issue_worktree_transition_apply`,{authority:e.authorizeTransition===!0?`worktree:transition`:``,planPath:e.plan,expectedPlanId:e.planId,relinquishmentCommentId:Number(e.relinquishmentComment),acceptanceCommentId:Number(e.acceptanceComment)})),cN.command(`migrate:legacy-issues`).requiredOption(`--input-file <path>`,`Offline legacy issue inventory JSON`).action(e=>{let t=qj(JSON.parse(d(e.inputFile,`utf8`)));process.stdout.write(`${JSON.stringify(t,null,2)}\n`)}),cN.command(`config:resolve`).description(`Read the effective GitHub destination and admission digest`).action(async()=>{let e=await GC(lN(),`config:resolve`);gN({configDigest:e.configuration?.configDigest,routing:e.configuration?.routing,reviewRoute:await JS(e,void 0,void 0,`development`)})}),cN.command(`mcp:serve`).action(async()=>Uj(lN())),cN.parseAsync(process.argv).catch(e=>{process.stderr.write(`ai-delivery: ${e instanceof Error?e.message:String(e)}\n`),process.exitCode=1});export{};
|
|
305
|
+
deps: ${r}}`};var i={keyword:`dependencies`,type:`object`,schemaType:`object`,error:e.error,code(e){let[t,n]=a(e);o(e,t),s(e,n)}};function a({schema:e}){let t={},n={};for(let r in e){if(r===`__proto__`)continue;let i=Array.isArray(e[r])?t:n;i[r]=e[r]}return[t,n]}function o(e,n=e.schema){let{gen:i,data:a,it:o}=e;if(Object.keys(n).length===0)return;let s=i.let(`missing`);for(let c in n){let l=n[c];if(l.length===0)continue;let u=(0,r.propertyInData)(i,a,c,o.opts.ownProperties);e.setParams({property:c,depsCount:l.length,deps:l.join(`, `)}),o.allErrors?i.if(u,()=>{for(let t of l)(0,r.checkReportMissingProp)(e,t)}):(i.if((0,t._)`${u} && (${(0,r.checkMissingProp)(e,l,s)})`),(0,r.reportMissingProp)(e,s),i.else())}}e.validatePropertyDeps=o;function s(e,t=e.schema){let{gen:i,data:a,keyword:o,it:s}=e,c=i.name(`valid`);for(let l in t)(0,n.alwaysValidSchema)(s,t[l])||(i.if((0,r.propertyInData)(i,a,l,s.opts.ownProperties),()=>{let t=e.subschema({keyword:o,schemaProp:l},c);e.mergeValidEvaluated(t,c)},()=>i.var(c,!0)),e.ok(c))}e.validateSchemaDeps=s,e.default=i})),PA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=Fk();e.default={keyword:`propertyNames`,type:`object`,schemaType:[`object`,`boolean`],error:{message:`property name must be valid`,params:({params:e})=>(0,t._)`{propertyName: ${e.propertyName}}`},code(e){let{gen:r,schema:i,data:a,it:o}=e;if((0,n.alwaysValidSchema)(o,i))return;let s=r.name(`valid`);r.forIn(`key`,a,n=>{e.setParams({propertyName:n}),e.subschema({keyword:`propertyNames`,data:n,dataTypes:[`string`],propertyName:n,compositeRule:!0},s),r.if((0,t.not)(s),()=>{e.error(!0),o.allErrors||r.break()})}),e.ok(s)}}})),FA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Uk(),n=$(),r=Ik(),i=Fk();e.default={keyword:`additionalProperties`,type:[`object`],schemaType:[`boolean`,`object`],allowUndefined:!0,trackErrors:!0,error:{message:`must NOT have additional properties`,params:({params:e})=>(0,n._)`{additionalProperty: ${e.additionalProperty}}`},code(e){let{gen:a,schema:o,parentSchema:s,data:c,errsCount:l,it:u}=e;if(!l)throw Error(`ajv implementation error`);let{allErrors:d,opts:f}=u;if(u.props=!0,f.removeAdditional!==`all`&&(0,i.alwaysValidSchema)(u,o))return;let p=(0,t.allSchemaProperties)(s.properties),m=(0,t.allSchemaProperties)(s.patternProperties);h(),e.ok((0,n._)`${l} === ${r.default.errors}`);function h(){a.forIn(`key`,c,e=>{!p.length&&!m.length?v(e):a.if(g(e),()=>v(e))})}function g(r){let o;if(p.length>8){let e=(0,i.schemaRefOrVal)(u,s.properties,`properties`);o=(0,t.isOwnProperty)(a,e,r)}else o=p.length?(0,n.or)(...p.map(e=>(0,n._)`${r} === ${e}`)):n.nil;return m.length&&(o=(0,n.or)(o,...m.map(i=>(0,n._)`${(0,t.usePattern)(e,i)}.test(${r})`))),(0,n.not)(o)}function _(e){a.code((0,n._)`delete ${c}[${e}]`)}function v(t){if(f.removeAdditional===`all`||f.removeAdditional&&o===!1){_(t);return}if(o===!1){e.setParams({additionalProperty:t}),e.error(),d||a.break();return}if(typeof o==`object`&&!(0,i.alwaysValidSchema)(u,o)){let r=a.name(`valid`);f.removeAdditional===`failing`?(y(t,r,!1),a.if((0,n.not)(r),()=>{e.reset(),_(t)})):(y(t,r),d||a.if((0,n.not)(r),()=>a.break()))}}function y(t,n,r){let a={keyword:`additionalProperties`,dataProp:t,dataPropType:i.Type.Str};r===!1&&Object.assign(a,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(a,n)}}}})),IA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Yk(),n=Uk(),r=Fk(),i=FA();e.default={keyword:`properties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,parentSchema:s,data:c,it:l}=e;l.opts.removeAdditional===`all`&&s.additionalProperties===void 0&&i.default.code(new t.KeywordCxt(l,i.default,`additionalProperties`));let u=(0,n.allSchemaProperties)(o);for(let e of u)l.definedProperties.add(e);l.opts.unevaluated&&u.length&&l.props!==!0&&(l.props=r.mergeEvaluated.props(a,(0,r.toHash)(u),l.props));let d=u.filter(e=>!(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0)return;let f=a.name(`valid`);for(let t of d)p(t)?m(t):(a.if((0,n.propertyInData)(a,c,t,l.opts.ownProperties)),m(t),l.allErrors||a.else().var(f,!0),a.endIf()),e.it.definedProperties.add(t),e.ok(f);function p(e){return l.opts.useDefaults&&!l.compositeRule&&o[e].default!==void 0}function m(t){e.subschema({keyword:`properties`,schemaProp:t,dataProp:t},f)}}}})),LA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Uk(),n=$(),r=Fk(),i=Fk();e.default={keyword:`patternProperties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,data:s,parentSchema:c,it:l}=e,{opts:u}=l,d=(0,t.allSchemaProperties)(o),f=d.filter(e=>(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0||f.length===d.length&&(!l.opts.unevaluated||l.props===!0))return;let p=u.strictSchema&&!u.allowMatchingProperties&&c.properties,m=a.name(`valid`);l.props!==!0&&!(l.props instanceof n.Name)&&(l.props=(0,i.evaluatedPropsToName)(a,l.props));let{props:h}=l;g();function g(){for(let e of d)p&&_(e),l.allErrors?v(e):(a.var(m,!0),v(e),a.if(m))}function _(e){for(let t in p)new RegExp(e).test(t)&&(0,r.checkStrictMode)(l,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function v(r){a.forIn(`key`,s,o=>{a.if((0,n._)`${(0,t.usePattern)(e,r)}.test(${o})`,()=>{let t=f.includes(r);t||e.subschema({keyword:`patternProperties`,schemaProp:r,dataProp:o,dataPropType:i.Type.Str},m),l.opts.unevaluated&&h!==!0?a.assign((0,n._)`${h}[${o}]`,!0):!t&&!l.allErrors&&a.if((0,n.not)(m),()=>a.break())})})}}}})),RA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Fk();e.default={keyword:`not`,schemaType:[`object`,`boolean`],trackErrors:!0,code(e){let{gen:n,schema:r,it:i}=e;if((0,t.alwaysValidSchema)(i,r)){e.fail();return}let a=n.name(`valid`);e.subschema({keyword:`not`,compositeRule:!0,createErrors:!1,allErrors:!1},a),e.failResult(a,()=>e.reset(),()=>e.error())},error:{message:`must NOT be valid`}}})),zA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:Uk().validateUnion,error:{message:`must match a schema in anyOf`}}})),BA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=Fk();e.default={keyword:`oneOf`,schemaType:`array`,trackErrors:!0,error:{message:`must match exactly one schema in oneOf`,params:({params:e})=>(0,t._)`{passingSchemas: ${e.passing}}`},code(e){let{gen:r,schema:i,parentSchema:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(o.opts.discriminator&&a.discriminator)return;let s=i,c=r.let(`valid`,!1),l=r.let(`passing`,null),u=r.name(`_valid`);e.setParams({passing:l}),r.block(d),e.result(c,()=>e.reset(),()=>e.error(!0));function d(){s.forEach((i,a)=>{let s;(0,n.alwaysValidSchema)(o,i)?r.var(u,!0):s=e.subschema({keyword:`oneOf`,schemaProp:a,compositeRule:!0},u),a>0&&r.if((0,t._)`${u} && ${c}`).assign(c,!1).assign(l,(0,t._)`[${l}, ${a}]`).else(),r.if(u,()=>{r.assign(c,!0),r.assign(l,a),s&&e.mergeEvaluated(s,t.Name)})})}}}})),VA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Fk();e.default={keyword:`allOf`,schemaType:`array`,code(e){let{gen:n,schema:r,it:i}=e;if(!Array.isArray(r))throw Error(`ajv implementation error`);let a=n.name(`valid`);r.forEach((n,r)=>{if((0,t.alwaysValidSchema)(i,n))return;let o=e.subschema({keyword:`allOf`,schemaProp:r},a);e.ok(a),e.mergeEvaluated(o)})}}})),HA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=Fk(),r={keyword:`if`,schemaType:[`object`,`boolean`],trackErrors:!0,error:{message:({params:e})=>(0,t.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,t._)`{failingKeyword: ${e.ifClause}}`},code(e){let{gen:r,parentSchema:a,it:o}=e;a.then===void 0&&a.else===void 0&&(0,n.checkStrictMode)(o,`"if" without "then" and "else" is ignored`);let s=i(o,`then`),c=i(o,`else`);if(!s&&!c)return;let l=r.let(`valid`,!0),u=r.name(`_valid`);if(d(),e.reset(),s&&c){let t=r.let(`ifClause`);e.setParams({ifClause:t}),r.if(u,f(`then`,t),f(`else`,t))}else s?r.if(u,f(`then`)):r.if((0,t.not)(u),f(`else`));e.pass(l,()=>e.error(!0));function d(){let t=e.subschema({keyword:`if`,compositeRule:!0,createErrors:!1,allErrors:!1},u);e.mergeEvaluated(t)}function f(n,i){return()=>{let a=e.subschema({keyword:n},u);r.assign(l,u),e.mergeValidEvaluated(a,l),i?r.assign(i,(0,t._)`${n}`):e.setParams({ifClause:n})}}}};function i(e,t){let r=e.schema[t];return r!==void 0&&!(0,n.alwaysValidSchema)(e,r)}e.default=r})),UA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Fk();e.default={keyword:[`then`,`else`],schemaType:[`object`,`boolean`],code({keyword:e,parentSchema:n,it:r}){n.if===void 0&&(0,t.checkStrictMode)(r,`"${e}" without "if" is ignored`)}}})),WA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=OA(),n=AA(),r=kA(),i=jA(),a=MA(),o=NA(),s=PA(),c=FA(),l=IA(),u=LA(),d=RA(),f=zA(),p=BA(),m=VA(),h=HA(),g=UA();function _(e=!1){let _=[d.default,f.default,p.default,m.default,h.default,g.default,s.default,c.default,o.default,l.default,u.default];return e?_.push(n.default,i.default):_.push(t.default,r.default),_.push(a.default),_}e.default=_})),GA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$();e.default={keyword:`format`,type:[`number`,`string`],schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,t._)`{format: ${e}}`},code(e,n){let{gen:r,data:i,$data:a,schema:o,schemaCode:s,it:c}=e,{opts:l,errSchemaPath:u,schemaEnv:d,self:f}=c;if(!l.validateFormats)return;a?p():m();function p(){let a=r.scopeValue(`formats`,{ref:f.formats,code:l.code.formats}),o=r.const(`fDef`,(0,t._)`${a}[${s}]`),c=r.let(`fType`),u=r.let(`format`);r.if((0,t._)`typeof ${o} == "object" && !(${o} instanceof RegExp)`,()=>r.assign(c,(0,t._)`${o}.type || "string"`).assign(u,(0,t._)`${o}.validate`),()=>r.assign(c,(0,t._)`"string"`).assign(u,o)),e.fail$data((0,t.or)(p(),m()));function p(){return l.strictSchema===!1?t.nil:(0,t._)`${s} && !${u}`}function m(){let e=d.$async?(0,t._)`(${o}.async ? await ${u}(${i}) : ${u}(${i}))`:(0,t._)`${u}(${i})`,r=(0,t._)`(typeof ${u} == "function" ? ${e} : ${u}.test(${i}))`;return(0,t._)`${u} && ${u} !== true && ${c} === ${n} && !${r}`}}function m(){let a=f.formats[o];if(!a){m();return}if(a===!0)return;let[s,c,p]=h(a);s===n&&e.pass(g());function m(){if(l.strictSchema===!1){f.logger.warn(e());return}throw Error(e());function e(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function h(e){let n=e instanceof RegExp?(0,t.regexpCode)(e):l.code.formats?(0,t._)`${l.code.formats}${(0,t.getProperty)(o)}`:void 0,i=r.scopeValue(`formats`,{key:o,ref:e,code:n});return typeof e==`object`&&!(e instanceof RegExp)?[e.type||`string`,e.validate,(0,t._)`${i}.validate`]:[`string`,e,i]}function g(){if(typeof a==`object`&&!(a instanceof RegExp)&&a.async){if(!d.$async)throw Error(`async format in sync schema`);return(0,t._)`await ${p}(${i})`}return typeof c==`function`?(0,t._)`${p}(${i})`:(0,t._)`${p}.test(${i})`}}}}})),KA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=[GA().default]})),qA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.contentVocabulary=e.metadataVocabulary=void 0,e.metadataVocabulary=[`title`,`description`,`default`,`deprecated`,`readOnly`,`writeOnly`,`examples`],e.contentVocabulary=[`contentMediaType`,`contentEncoding`,`contentSchema`]})),JA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=mA(),n=DA(),r=WA(),i=KA(),a=qA();e.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),YA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DiscrError=void 0;var t;(function(e){e.Tag=`tag`,e.Mapping=`mapping`})(t||(e.DiscrError=t={}))})),XA=E((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=YA(),r=Qk(),i=Zk(),a=Fk();e.default={keyword:`discriminator`,type:`object`,schemaType:`object`,error:{message:({params:{discrError:e,tagName:t}})=>e===n.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:n,tagName:r}})=>(0,t._)`{error: ${e}, tag: ${r}, tagValue: ${n}}`},code(e){let{gen:o,data:s,schema:c,parentSchema:l,it:u}=e,{oneOf:d}=l;if(!u.opts.discriminator)throw Error(`discriminator: requires discriminator option`);let f=c.propertyName;if(typeof f!=`string`)throw Error(`discriminator: requires propertyName`);if(c.mapping)throw Error(`discriminator: mapping is not supported`);if(!d)throw Error(`discriminator: requires oneOf keyword`);let p=o.let(`valid`,!1),m=o.const(`tag`,(0,t._)`${s}${(0,t.getProperty)(f)}`);o.if((0,t._)`typeof ${m} == "string"`,()=>h(),()=>e.error(!1,{discrError:n.DiscrError.Tag,tag:m,tagName:f})),e.ok(p);function h(){let r=_();o.if(!1);for(let e in r)o.elseIf((0,t._)`${m} === ${e}`),o.assign(p,g(r[e]));o.else(),e.error(!1,{discrError:n.DiscrError.Mapping,tag:m,tagName:f}),o.endIf()}function g(n){let r=o.name(`valid`),i=e.subschema({keyword:`oneOf`,schemaProp:n},r);return e.mergeEvaluated(i,t.Name),r}function _(){let e={},t=o(l),n=!0;for(let e=0;e<d.length;e++){let c=d[e];if(c?.$ref&&!(0,a.schemaHasRulesButRef)(c,u.self.RULES)){let e=c.$ref;if(c=r.resolveRef.call(u.self,u.schemaEnv.root,u.baseId,e),c instanceof r.SchemaEnv&&(c=c.schema),c===void 0)throw new i.default(u.opts.uriResolver,u.baseId,e)}let l=c?.properties?.[f];if(typeof l!=`object`)throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${f}"`);n&&=t||o(c),s(l,e)}if(!n)throw Error(`discriminator: "${f}" must be required`);return e;function o({required:e}){return Array.isArray(e)&&e.includes(f)}function s(e,t){if(e.const)c(e.const,t);else if(e.enum)for(let n of e.enum)c(n,t);else throw Error(`discriminator: "properties/${f}" must have "const" or "enum"`)}function c(t,n){if(typeof t!=`string`||t in e)throw Error(`discriminator: "${f}" values must be unique strings`);e[t]=n}}}}})),ZA=Oe({$id:()=>$A,$schema:()=>QA,default:()=>ij,definitions:()=>tj,properties:()=>rj,title:()=>ej,type:()=>nj}),QA,$A,ej,tj,nj,rj,ij,aj=De((()=>{QA=`http://json-schema.org/draft-07/schema#`,$A=`http://json-schema.org/draft-07/schema#`,ej=`Core schema meta-schema`,tj={schemaArray:{type:`array`,minItems:1,items:{$ref:`#`}},nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:`#/definitions/nonNegativeInteger`},{default:0}]},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}},nj=[`object`,`boolean`],rj={$id:{type:`string`,format:`uri-reference`},$schema:{type:`string`,format:`uri`},$ref:{type:`string`,format:`uri-reference`},$comment:{type:`string`},title:{type:`string`},description:{type:`string`},default:!0,readOnly:{type:`boolean`,default:!1},examples:{type:`array`,items:!0},multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/definitions/nonNegativeInteger`},minLength:{$ref:`#/definitions/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},additionalItems:{$ref:`#`},items:{anyOf:[{$ref:`#`},{$ref:`#/definitions/schemaArray`}],default:!0},maxItems:{$ref:`#/definitions/nonNegativeInteger`},minItems:{$ref:`#/definitions/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},contains:{$ref:`#`},maxProperties:{$ref:`#/definitions/nonNegativeInteger`},minProperties:{$ref:`#/definitions/nonNegativeIntegerDefault0`},required:{$ref:`#/definitions/stringArray`},additionalProperties:{$ref:`#`},definitions:{type:`object`,additionalProperties:{$ref:`#`},default:{}},properties:{type:`object`,additionalProperties:{$ref:`#`},default:{}},patternProperties:{type:`object`,additionalProperties:{$ref:`#`},propertyNames:{format:`regex`},default:{}},dependencies:{type:`object`,additionalProperties:{anyOf:[{$ref:`#`},{$ref:`#/definitions/stringArray`}]}},propertyNames:{$ref:`#`},const:!0,enum:{type:`array`,items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:`#/definitions/simpleTypes`},{type:`array`,items:{$ref:`#/definitions/simpleTypes`},minItems:1,uniqueItems:!0}]},format:{type:`string`},contentMediaType:{type:`string`},contentEncoding:{type:`string`},if:{$ref:`#`},then:{$ref:`#`},else:{$ref:`#`},allOf:{$ref:`#/definitions/schemaArray`},anyOf:{$ref:`#/definitions/schemaArray`},oneOf:{$ref:`#/definitions/schemaArray`},not:{$ref:`#`}},ij={$schema:QA,$id:$A,title:ej,definitions:tj,type:nj,properties:rj,default:!0}})),oj=E(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;var n=dA(),r=JA(),i=XA(),a=(aj(),je(ZA).default),o=[`/properties`],s=`http://json-schema.org/draft-07/schema`,c=class extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(i.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(a,o):a;this.addMetaSchema(e,s,!1),this.refs[`http://json-schema.org/schema`]=s}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s)?s:void 0)}};e.Ajv=c,t.exports=e=c,t.exports.Ajv=c,Object.defineProperty(e,"__esModule",{value:!0}),e.default=c;var l=Yk();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return l.KeywordCxt}});var u=$();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var d=Xk();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return d.default}});var f=Zk();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return f.default}})})),sj=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(e,t){return{validate:e,compare:t}}e.fullFormats={date:t(a,o),time:t(c(!0),l),"date-time":t(f(!0),p),"iso-time":t(c(),u),"iso-date-time":t(f(),m),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:_,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:re,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:y,int32:{type:`number`,validate:ee},int64:{type:`number`,validate:S},float:{type:`number`,validate:te},double:{type:`number`,validate:te},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,o),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,l),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,p),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,m),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function n(e){return e%4==0&&(e%100!=0||e%400==0)}var r=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,i=[0,31,28,31,30,31,30,31,31,30,31,30,31];function a(e){let t=r.exec(e);if(!t)return!1;let a=+t[1],o=+t[2],s=+t[3];return o>=1&&o<=12&&s>=1&&s<=(o===2&&n(a)?29:i[o])}function o(e,t){if(e&&t)return e>t?1:e<t?-1:0}var s=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function c(e){return function(t){let n=s.exec(t);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=n[4],c=n[5]===`-`?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||e&&!o)return!1;if(r<=23&&i<=59&&a<60)return!0;let d=i-u*c,f=r-l*c-+(d<0);return(f===23||f===-1)&&(d===59||d===-1)&&a<61}}function l(e,t){if(!(e&&t))return;let n=new Date(`2020-01-01T`+e).valueOf(),r=new Date(`2020-01-01T`+t).valueOf();if(n&&r)return n-r}function u(e,t){if(!(e&&t))return;let n=s.exec(e),r=s.exec(t);if(n&&r)return e=n[1]+n[2]+n[3],t=r[1]+r[2]+r[3],e>t?1:e<t?-1:0}var d=/t|\s/i;function f(e){let t=c(e);return function(e){let n=e.split(d);return n.length===2&&a(n[0])&&t(n[1])}}function p(e,t){if(!(e&&t))return;let n=new Date(e).valueOf(),r=new Date(t).valueOf();if(n&&r)return n-r}function m(e,t){if(!(e&&t))return;let[n,r]=e.split(d),[i,a]=t.split(d),s=o(n,i);if(s!==void 0)return s||l(r,a)}var h=/\/|:/,g=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function _(e){return h.test(e)&&g.test(e)}var v=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function y(e){return v.lastIndex=0,v.test(e)}var b=-(2**31),x=2**31-1;function ee(e){return Number.isInteger(e)&&e<=x&&e>=b}function S(e){return Number.isInteger(e)}function te(){return!0}var ne=/[^\\]\\Z/;function re(e){if(ne.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}})),cj=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;var t=oj(),n=$(),r=n.operators,i={formatMaximum:{okStr:`<=`,ok:r.LTE,fail:r.GT},formatMinimum:{okStr:`>=`,ok:r.GTE,fail:r.LT},formatExclusiveMaximum:{okStr:`<`,ok:r.LT,fail:r.GTE},formatExclusiveMinimum:{okStr:`>`,ok:r.GT,fail:r.LTE}};e.formatLimitDefinition={keyword:Object.keys(i),type:`string`,schemaType:`string`,$data:!0,error:{message:({keyword:e,schemaCode:t})=>(0,n.str)`should be ${i[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,n._)`{comparison: ${i[e].okStr}, limit: ${t}}`},code(e){let{gen:r,data:a,schemaCode:o,keyword:s,it:c}=e,{opts:l,self:u}=c;if(!l.validateFormats)return;let d=new t.KeywordCxt(c,u.RULES.all.format.definition,`format`);d.$data?f():p();function f(){let t=r.scopeValue(`formats`,{ref:u.formats,code:l.code.formats}),i=r.const(`fmt`,(0,n._)`${t}[${d.schemaCode}]`);e.fail$data((0,n.or)((0,n._)`typeof ${i} != "object"`,(0,n._)`${i} instanceof RegExp`,(0,n._)`typeof ${i}.compare != "function"`,m(i)))}function p(){let t=d.schema,i=u.formats[t];if(!i||i===!0)return;if(typeof i!=`object`||i instanceof RegExp||typeof i.compare!=`function`)throw Error(`"${s}": format "${t}" does not define "compare" function`);let a=r.scopeValue(`formats`,{key:t,ref:i,code:l.code.formats?(0,n._)`${l.code.formats}${(0,n.getProperty)(t)}`:void 0});e.fail$data(m(a))}function m(e){return(0,n._)`${e}.compare(${a}, ${o}) ${i[s].fail} 0`}},dependencies:[`format`]},e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)})),lj=E(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});var n=sj(),r=cj(),i=$(),a=new i.Name(`fullFormats`),o=new i.Name(`fastFormats`),s=(e,t={keywords:!0})=>{if(Array.isArray(t))return c(e,t,n.fullFormats,a),e;let[i,s]=t.mode===`fast`?[n.fastFormats,o]:[n.fullFormats,a];return c(e,t.formats||n.formatNames,i,s),t.keywords&&(0,r.default)(e),e};s.get=(e,t=`full`)=>{let r=(t===`fast`?n.fastFormats:n.fullFormats)[e];if(!r)throw Error(`Unknown format "${e}"`);return r};function c(e,t,n,r){var a;(a=e.opts.code).formats??(a.formats=(0,i._)`require("ajv-formats/dist/formats").${r}`);for(let r of t)e.addFormat(r,n[r])}t.exports=e=s,Object.defineProperty(e,"__esModule",{value:!0}),e.default=s})),uj=Ae(oj(),1),dj=Ae(lj(),1);function fj(){let e=new uj.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,dj.default)(e),e}var pj=class{constructor(e){this._ajv=e??fj()}getValidator(e){let t=`$id`in e&&typeof e.$id==`string`?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}},mj=class{constructor(e){this._server=e}requestStream(e,t,n){return this._server.requestStream(e,t,n)}createMessageStream(e,t){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return this.requestStream({method:`sampling/createMessage`,params:e},QD,t)}elicitInputStream(e,t){let n=this._server.getClientCapabilities(),r=e.mode??`form`;switch(r){case`url`:if(!n?.elicitation?.url)throw Error(`Client does not support url elicitation.`);break;case`form`:if(!n?.elicitation?.form)throw Error(`Client does not support form elicitation.`)}let i=r===`form`&&e.mode===void 0?{...e,mode:`form`}:e;return this.requestStream({method:`elicitation/create`,params:i},uO,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._server.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}};function hj(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);if(t===`tools/call`&&!e.tools?.call)throw Error(`${n} does not support task creation for tools/call (required for ${t})`)}function gj(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw Error(`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw Error(`${n} does not support task creation for elicitation/create (required for ${t})`)}}var _j=class extends Ak{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(zD.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let n=this._loggingLevels.get(t);return n?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new pj,this.setRequestHandler(SE,e=>this._oninitialize(e)),this.setNotificationHandler(TE,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(VD,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=zD.safeParse(r);return i.success&&this._loggingLevels.set(n,i.data),{}})}get experimental(){return this._experimental||={tasks:new mj(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=Mk(this._capabilities,e)}setRequestHandler(e,t){let n=MT(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r=RT(n);if(typeof r!=`string`)throw Error(`Schema method literal must be a string`);return r===`tools/call`?super.setRequestHandler(e,async(e,n)=>{let r=AT(ID,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new Q(Z.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=AT(FE,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new Q(Z.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=AT(PD,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new Q(Z.InvalidParams,`Invalid tools/call result: ${e}`)}return o.data}):super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`)}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`)}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`completion/complete`:if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`)}}assertTaskCapability(e){gj(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&hj(this._capabilities.tasks?.requests,e,`Server`)}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:BT.includes(t)?t:zT,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:`ping`},dE)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return e.tools?this.request({method:`sampling/createMessage`,params:e},$D,t):this.request({method:`sampling/createMessage`,params:e},QD,t)}async elicitInput(e,t){switch(e.mode??`form`){case`url`:{if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support url elicitation.`);let n=e;return this.request({method:`elicitation/create`,params:n},uO,t)}case`form`:{if(!this._clientCapabilities?.elicitation?.form)throw Error(`Client does not support form elicitation.`);let n=e.mode===`form`?e:{...e,mode:`form`},r=await this.request({method:`elicitation/create`,params:n},uO,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new Q(Z.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof Q?e:new Q(Z.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:`roots/list`,params:e},bO,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}},vj=Symbol.for(`mcp.completable`);function yj(e){return!!e&&typeof e==`object`&&vj in e}function bj(e){return e[vj]?.complete}var xj;(function(e){e.Completable=`McpCompletable`})(xj||={});var Sj=/^[A-Za-z0-9._-]{1,128}$/;function Cj(e){let t=[];if(e.length===0)return{isValid:!1,warnings:[`Tool name cannot be empty`]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(` `)&&t.push(`Tool name contains spaces, which may cause parsing issues`),e.includes(`,`)&&t.push(`Tool name contains commas, which may cause parsing issues`),(e.startsWith(`-`)||e.endsWith(`-`))&&t.push(`Tool name starts or ends with a dash, which may cause parsing issues in some contexts`),(e.startsWith(`.`)||e.endsWith(`.`))&&t.push(`Tool name starts or ends with a dot, which may cause parsing issues in some contexts`),!Sj.test(e)){let n=e.split(``).filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,n)=>n.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${n.map(e=>`"${e}"`).join(`, `)}`,`Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)`),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function wj(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let e of t)console.warn(` - ${e}`);console.warn(`Tool registration will proceed, but this may cause compatibility issues.`),console.warn(`Consider updating the tool name to conform to the MCP tool naming standard.`),console.warn(`See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.`)}}function Tj(e){let t=Cj(e);return wj(e,t.warnings),t.isValid}var Ej=class{constructor(e){this._mcpServer=e}registerToolTask(e,t,n){let r={taskSupport:`required`,...t.execution};if(r.taskSupport===`forbidden`)throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,r,t._meta,n)}},Dj=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new _j(e,t)}get experimental(){return this._experimental||={tasks:new Ej(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(Pj(MD)),this.server.assertCanSetRequestHandler(Pj(ID)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(MD,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:(()=>{let e=NT(t.inputSchema);return e?Dk(e,{strictUnions:!0,pipeStrategy:`input`}):Oj})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=NT(t.outputSchema);e&&(n.outputSchema=Dk(e,{strictUnions:!0,pipeStrategy:`output`}))}return n})})),this.server.setRequestHandler(ID,async(e,t)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new Q(Z.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new Q(Z.InvalidParams,`Tool ${e.params.name} disabled`);let r=!!e.params.task,i=n.execution?.taskSupport,a=`createTask`in n.handler;if((i===`required`||i===`optional`)&&!a)throw new Q(Z.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i===`required`&&!r)throw new Q(Z.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(i===`optional`&&!r&&a)return await this.handleAutomaticTaskPolling(n,e,t);let o=await this.validateToolInput(n,e.params.arguments,e.params.name),s=await this.executeToolHandler(n,o,t);return r||await this.validateToolOutput(n,s,e.params.name),s}catch(e){if(e instanceof Q&&e.code===Z.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),!0)}createToolError(e){return{content:[{type:`text`,text:e}],isError:!0}}async validateToolInput(e,t,n){if(!e.inputSchema)return;let r=await jT(NT(e.inputSchema)??e.inputSchema,t);if(!r.success){let e=FT(`error`in r?r.error:`Unknown error`);throw new Q(Z.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${e}`)}return r.data}async validateToolOutput(e,t,n){if(!e.outputSchema||!(`content`in t)||t.isError)return;if(!t.structuredContent)throw new Q(Z.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await jT(NT(e.outputSchema),t.structuredContent);if(!r.success){let e=FT(`error`in r?r.error:`Unknown error`);throw new Q(Z.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${e}`)}}async executeToolHandler(e,t,n){let r=e.handler;if(`createTask`in r){if(!n.taskStore)throw Error(`No task store provided.`);let i={...n,taskStore:n.taskStore};if(e.inputSchema){let e=r;return await Promise.resolve(e.createTask(t,i))}{let e=r;return await Promise.resolve(e.createTask(i))}}if(e.inputSchema){let e=r;return await Promise.resolve(e(t,n))}{let e=r;return await Promise.resolve(e(n))}}async handleAutomaticTaskPolling(e,t,n){if(!n.taskStore)throw Error(`No task store provided for task-capable tool.`);let r=await this.validateToolInput(e,t.params.arguments,t.params.name),i=e.handler,a={...n,taskStore:n.taskStore},o=r?await Promise.resolve(i.createTask(r,a)):await Promise.resolve(i.createTask(a)),s=o.task.taskId,c=o.task,l=c.pollInterval??5e3;for(;c.status!==`completed`&&c.status!==`failed`&&c.status!==`cancelled`;){await new Promise(e=>setTimeout(e,l));let e=await n.taskStore.getTask(s);if(!e)throw new Q(Z.InternalError,`Task ${s} not found during polling`);c=e}return await n.taskStore.getTaskResult(s)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(Pj(mO)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(mO,async e=>{switch(e.params.ref.type){case`ref/prompt`:return hO(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return gO(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Q(Z.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new Q(Z.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new Q(Z.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return Ij;let r=MT(n.argsSchema)?.[e.params.argument.name];if(!yj(r))return Ij;let i=bj(r);return i?Fj(await i(e.params.argument.value,e.params.context)):Ij}async handleResourceCompletion(e,t){let n=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!n){if(this._registeredResources[t.uri])return Ij;throw new Q(Z.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?Fj(await r(e.params.argument.value,e.params.context)):Ij}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(Pj($E)),this.server.assertCanSetRequestHandler(Pj(tD)),this.server.assertCanSetRequestHandler(Pj(aD)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler($E,async(e,t)=>{let n=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),r=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let n=await e.resourceTemplate.listCallback(t);for(let t of n.resources)r.push({...e.metadata,...t})}return{resources:[...n,...r]}}),this.server.setRequestHandler(tD,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(aD,async(e,t)=>{let n=new URL(e.params.uri),r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new Q(Z.InvalidParams,`Resource ${n} disabled`);return r.readCallback(n,t)}for(let e of Object.values(this._registeredResourceTemplates)){let r=e.resourceTemplate.uriTemplate.match(n.toString());if(r)return e.readCallback(n,r,t)}throw new Q(Z.InvalidParams,`Resource ${n} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(Pj(gD)),this.server.assertCanSetRequestHandler(Pj(yD)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(gD,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?Nj(t.argsSchema):void 0}))})),this.server.setRequestHandler(yD,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new Q(Z.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new Q(Z.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let r=await jT(NT(n.argsSchema),e.params.arguments);if(!r.success){let t=FT(`error`in r?r.error:`Unknown error`);throw new Q(Z.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}let i=r.data,a=n.callback;return await Promise.resolve(a(i,t))}{let e=n.callback;return await Promise.resolve(e(t))}}),!0)}resource(e,t,...n){let r;typeof n[0]==`object`&&(r=n.shift());let i=n[0];if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let n=this._createRegisteredResource(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let n=this._createRegisteredResourceTemplate(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}}registerResource(e,t,n,r){if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let i=this._createRegisteredResource(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,t,n,r,i){let a={name:e,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==n&&(delete this._registeredResources[n],e.uri&&(this._registeredResources[e.uri]=a)),e.name!==void 0&&(a.name=e.name),e.title!==void 0&&(a.title=e.title),e.metadata!==void 0&&(a.metadata=e.metadata),e.callback!==void 0&&(a.readCallback=e.callback),e.enabled!==void 0&&(a.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,t,n,r,i){let a={resourceTemplate:n,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.template!==void 0&&(a.resourceTemplate=t.template),t.metadata!==void 0&&(a.metadata=t.metadata),t.callback!==void 0&&(a.readCallback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;let o=n.uriTemplate.variableNames;return Array.isArray(o)&&o.some(e=>!!n.completeCallback(e))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,t,n,r,i){let a={title:t,description:n,argsSchema:r===void 0?void 0:kT(r),callback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.description!==void 0&&(a.description=t.description),t.argsSchema!==void 0&&(a.argsSchema=kT(t.argsSchema)),t.callback!==void 0&&(a.callback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,r&&Object.values(r).some(e=>yj(e instanceof Yl?e._def?.innerType:e))&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,t,n,r,i,a,o,s,c){Tj(e);let l={title:t,description:n,inputSchema:Mj(r),outputSchema:Mj(i),annotations:a,execution:o,_meta:s,handler:c,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(typeof t.name==`string`&&Tj(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=l)),t.title!==void 0&&(l.title=t.title),t.description!==void 0&&(l.description=t.description),t.paramsSchema!==void 0&&(l.inputSchema=kT(t.paramsSchema)),t.outputSchema!==void 0&&(l.outputSchema=kT(t.outputSchema)),t.callback!==void 0&&(l.handler=t.callback),t.annotations!==void 0&&(l.annotations=t.annotations),t._meta!==void 0&&(l._meta=t._meta),t.enabled!==void 0&&(l.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let n,r,i,a;if(typeof t[0]==`string`&&(n=t.shift()),t.length>1){let n=t[0];if(jj(n))r=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!jj(t[0])&&(a=t.shift());else if(typeof n==`object`&&n){if(Object.values(n).some(e=>typeof e==`object`&&!!e))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);a=t.shift()}}let o=t[0];return this._createRegisteredTool(e,void 0,n,r,i,a,{taskSupport:`forbidden`},void 0,o)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:r,description:i,inputSchema:a,outputSchema:o,annotations:s,_meta:c}=t;return this._createRegisteredTool(e,r,i,a,o,s,{taskSupport:`forbidden`},c,n)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let n;typeof t[0]==`string`&&(n=t.shift());let r;t.length>1&&(r=t.shift());let i=t[0],a=this._createRegisteredPrompt(e,void 0,n,r,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:r,description:i,argsSchema:a}=t,o=this._createRegisteredPrompt(e,r,i,a,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},Oj={type:`object`,properties:{}};function kj(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`&&`safeParse`in e&&typeof e.safeParse==`function`}function Aj(e){return`_def`in e||`_zod`in e||kj(e)}function jj(e){return typeof e!=`object`||!e||Aj(e)?!1:Object.keys(e).length===0||Object.values(e).some(kj)}function Mj(e){if(e){if(jj(e))return kT(e);if(!Aj(e))throw Error(`inputSchema must be a Zod schema or raw shape, received an unrecognized object`);return e}}function Nj(e){let t=MT(e);return t?Object.entries(t).map(([e,t])=>({name:e,description:IT(t),required:!LT(t)})):[]}function Pj(e){let t=MT(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=RT(t);if(typeof n==`string`)return n;throw Error(`Schema method literal must be a string`)}function Fj(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var Ij={completion:{values:[],hasMore:!1}},Lj=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??10485760}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
306
|
+
`);if(e===-1)return null;let t=this._buffer.toString(`utf8`,0,e).replace(/\r$/,``);return this._buffer=this._buffer.subarray(e+1),Rj(t)}clear(){this._buffer=void 0}};function Rj(e){return uE.parse(JSON.parse(e))}function zj(e){return JSON.stringify(e)+`
|
|
307
|
+
`}var Bj=class{constructor(e=le.stdin,t=le.stdout,n){this._stdin=e,this._stdout=t,this._started=!1,this._ondata=e=>{try{this._readBuffer.append(e),this.processReadBuffer()}catch(e){this.onerror?.(e),this.close().catch(()=>{})}},this._onerror=e=>{this.onerror?.(e)},this._readBuffer=new Lj({maxBufferSize:n?.maxBufferSize})}async start(){if(this._started)throw Error(`StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.`);this._started=!0,this._stdin.on(`data`,this._ondata),this._stdin.on(`error`,this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off(`data`,this._ondata),this._stdin.off(`error`,this._onerror),this._stdin.listenerCount(`data`)===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(t=>{let n=zj(e);this._stdout.write(n)?t():this._stdout.once(`drain`,t)})}},Vj=JSON.parse(d(new URL(`../package.json`,import.meta.url),`utf8`));if(typeof Vj!=`object`||!Vj||!(`version`in Vj)||typeof Vj.version!=`string`||!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/u.test(Vj.version))throw Error(`The adjacent ai-delivery package identity must contain a stable version.`);var Hj=Vj.version,Uj=[`Use these ai-delivery GitHub issue and pull request tools for ordinary requests, including "Use the ai-delivery MCP issue_info tool to read owner/name issue N".`,`Carry the repository named by the user into the repo argument (owner/name). Ordinary remote issue/PR tools work outside Git with an explicit repo; do not move into a checkout to read an issue.`,`In Claude Code, when bare and plugin-qualified ai-delivery tools coexist, discover the installed plugin provider and inspect its schema before calling. The observed plugin example is mcp__plugin_ai-delivery_ai-delivery__issue_info with {"repo":"example/widget","issueNumber":17}; use the requested repository and issue instead. This Claude namespace is not a universal tool name for other hosts.`,`A different issue_info accepting issueNumber/cached but no repo cannot receive that repository argument. Do not add unsupported fields or select a provider by name similarity alone. Honor an explicitly requested provider; if it is unavailable or incompatible, report that limitation rather than silently substituting.`,`Preserve read-only and MCP-only intent: do not create/update/start, use another GitHub provider or fall back to a CLI for such a read. Do not alter registrations, permissions, actors, credentials or host settings to make it work.`,`Retained local runtime, transition and investigation modes keep their separate checkout and authority requirements.`].join(`
|
|
308
|
+
`);function Wj(e,t){let n=new Dj({name:`ai-delivery`,version:Hj},{instructions:Uj}),r=BC;for(let i of r)n.registerTool(i.name,{description:i.description,inputSchema:i.inputSchema},async(n,r)=>{let a=i.inputSchema.safeParse(n);if(!a.success)return{content:[{type:`text`,text:`Invalid arguments for ${i.name}.`}],isError:!0};try{let n=e.signal===void 0?r.signal:AbortSignal.any([e.signal,r.signal]),o=JC(i.name,a.data,{...e,signal:n});t?.add(o);let s;try{s=await o}finally{t?.delete(o)}return{content:[{type:`text`,text:JSON.stringify(s)}]}}catch(e){return{content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],isError:!0}}});return n}async function Gj(e){i_(!0);let t=new AbortController,n=new Set,r=Wj({...e,signal:t.signal},n),i,a=()=>(i??=(async()=>{t.abort(),await Promise.allSettled(n),await r.close(),process.exit(0)})(),i);process.once(`SIGINT`,()=>{a()}),process.once(`SIGTERM`,()=>{a()}),await r.connect(new Bj),process.stderr.write(`ai-delivery MCP server started
|
|
309
|
+
`),await new Promise(()=>{})}var Kj=e=>/^(?:area|risk):[^\s:]+$/u.test(e),qj=Kj,Jj=N({number:A().int().positive(),body:k(),labels:M(k()),trackingParent:j().optional(),resolvedLegacyBlockers:M(N({number:A().int().positive(),state:F([`OPEN`,`CLOSED`])}).strict()).optional(),existingNative:N({blockedBy:M(N({number:A().int().positive(),state:F([`OPEN`,`CLOSED`])}).strict()),issueType:k().optional(),points:A().int().positive().optional(),priority:k().optional(),projectStatus:F([`Todo`,`In Progress`,`Blocked`,`Done`]).optional()}).strict().optional()}).strict();function Yj(e){let t=N({issues:M(Jj),repositoryLabels:M(k()).optional()}).strict().parse(e),n=t.issues.map(e=>e.number);if(new Set(n).size!==n.length)throw new L(`Legacy issue input repeats an issue number.`);return{mode:`dry-run`,plans:t.issues.map(e=>{let t=e.existingNative,n=t===void 0?void 0:{blockedBy:t.blockedBy,...t.issueType===void 0?{}:{issueType:t.issueType},...t.points===void 0?{}:{points:t.points},...t.priority===void 0?{}:{priority:t.priority},...t.projectStatus===void 0?{}:{projectStatus:t.projectStatus}};return{number:e.number,...$j({body:e.body,labels:e.labels,...n===void 0?{}:{existingNative:n},...e.resolvedLegacyBlockers===void 0?{}:{resolvedLegacyBlockers:e.resolvedLegacyBlockers},...e.trackingParent===void 0?{}:{trackingParent:e.trackingParent}})}}),retiredRepositoryLabels:eM(t.repositoryLabels??[]),schemaVersion:`ai-delivery.legacy-issue-migration@1`,validated:0}}var Xj=new Map([[`effort:l`,5],[`effort:m`,3],[`effort:medium`,3],[`effort:s`,2],[`effort:xl`,8],[`effort:xs`,1]]),Zj=new Map([[`priority:high`,`P1`],[`priority:p0`,`P0`],[`priority:p1`,`P1`],[`priority:p2`,`P2`],[`priority:p3`,`P3`],[`priority:p4`,`P4`]]),Qj=new Map([[`type:bug`,`Bug`],[`type:design`,`Task`],[`type:epic`,`Task`],[`type:feature`,`Feature`],[`type:spike`,`Task`],[`type:task`,`Task`],[`type:tracking`,`Task`]]);function $j(e){let t=[...new Set(e.labels.map(e=>e.trim()).filter(Boolean))],n=tM(e.body),r=aM(e.body,`executionContract`),i=aM(e.body,`dependencyDeclaration`),a=aM(e.body,`related`),o=rM([...e.existingNative?.blockedBy??[],...e.resolvedLegacyBlockers??[]]),s=sM({dependencyDeclaration:i,executionContract:r,related:a}),c=[...new Set([...o.keys(),...s])].sort((e,t)=>e-t),l=new Set(c.filter(e=>o.get(e)!==`CLOSED`));if(t.some(e=>e.toLowerCase()===`type:tracking`)&&e.trackingParent!==!0)throw new L(`Legacy type:tracking requires a native sub-issue relationship before its label can be retired.`);let u=e.trackingParent===!0,d=u?void 0:e.existingNative?.points??uM({...n.points===void 0?{}:{bodyPoint:n.points},executionContract:r,labels:t}),f=e.existingNative?.priority??dM({label:`priority`,labels:t,mapping:Zj}),p=e.existingNative?.issueType??dM({label:`issue type`,labels:t,mapping:Qj});if(e.existingNative?.projectStatus===`Done`)throw new L(`An open issue cannot retain Project Done during legacy migration.`);let m=lM({existing:e.existingNative?.projectStatus,labels:t,unresolvedBlockers:l}),h=t.filter(Kj);h.sort();let g=t.filter(e=>!h.includes(e)).sort();return{body:oM(n.body),clearPoints:u&&e.existingNative?.points!==void 0,native:{blockedBy:c,...p===void 0?{}:{issueType:p},...d===void 0?{}:{points:d},...f===void 0?{}:{priority:f},projectStatus:m},retainedLabels:h,retiredLabels:g}}function eM(e){return[...new Set(e.map(e=>e.trim()).filter(e=>e.length>0))].filter(e=>!qj(e)).sort((e,t)=>e.localeCompare(t))}function tM(e){let t=e.split(/\r?\n/u),n=t.flatMap((e,t)=>e.trim().toLowerCase()===`## fibonacci points`?[t]:[]);if(n.length===0)return{body:e};if(n.length>1)throw new L(`Found duplicate legacy Fibonacci points sections.`);let r=n[0];if(r===void 0)return{body:e};let i=t.length;for(let e=r+1;e<t.length;e+=1)if(t[e]?.trimStart().startsWith(`## `)===!0){i=e;break}let a=t.slice(r+1,i).map(e=>e.trim()).filter(Boolean);if(a.length!==1||!/^(?:1|2|3|5|8|13)$/u.test(a[0]??``))throw new L(`Legacy Fibonacci points section must contain exactly one supported numeric value.`);return{body:[...t.slice(0,r),...t.slice(i)].join(`
|
|
310
|
+
`),points:Number(a[0])}}function nM(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0}function rM(e){let t=new Map;for(let n of e){if(!nM(n.number))throw new L(`Native blocked-by relationship evidence is malformed.`);let e=t.get(n.number);if(e!==void 0&&e!==n.state)throw new L(`Native blocker #${String(n.number)} has conflicting relationship states.`);t.set(n.number,n.state)}return t}function iM(e){if(nM(e))return e;if(typeof e!=`string`)return;let t=/^#?([1-9]\d*)$/u.exec(e.trim()),n=t?.[1]===void 0?NaN:Number(t[1]);return nM(n)?n:void 0}function aM(e,t){let n=RegExp(`<!--\\s*${t}:\\s*([\\s\\S]*?)\\s*-->`,`u`).exec(e)?.[1];if(n!==void 0)try{let e=JSON.parse(n);if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`not an object`);return e}catch{throw new L(`Invalid legacy ${t} payload.`)}}function oM(e){return e.replace(/<!--\s*(?:executionContract|dependencyDeclaration|related):[\s\S]*?-->\s*/gu,``).trim()}function sM({dependencyDeclaration:e,executionContract:t,related:n}){let r=[],i=t?.dependencies;if(Array.isArray(i))for(let e of i){if(typeof e!=`object`||!e)continue;let t=e,n=iM(t.issue);t.type===`blockedBy`&&n!==void 0&&r.push(n)}return r.push(...cM(e?.blockedBy)),r.push(...cM(n?.blockedBy)),[...new Set(r)].sort((e,t)=>e-t)}function cM(e){return Array.isArray(e)?e.map(iM).filter(e=>e!==void 0):[]}function lM(e){if(e.unresolvedBlockers.size>0)return`Blocked`;let t=e.labels.some(e=>[`status:in-progress`,`status:review`].includes(e.toLowerCase()));return e.existing===`In Progress`||t?`In Progress`:`Todo`}function uM(e){let t=[];for(let n of e.labels){let e=Xj.get(n.toLowerCase());e!==void 0&&t.push(e);let r=/^points:(1|2|3|5|8|13)$/u.exec(n.toLowerCase());r?.[1]!==void 0&&t.push(Number(r[1]))}let n=e.executionContract?.effort;if(typeof n==`string`){let e=n.startsWith(`effort:`)?n:`effort:${n}`,r=Xj.get(e.toLowerCase());r!==void 0&&t.push(r)}e.bodyPoint!==void 0&&t.push(e.bodyPoint);let r=[...new Set(t)];if(r.length>1)throw new L(`Found conflicting legacy sizing values: ${r.join(`, `)}.`);let[i]=r;if(i===void 0)throw new L(`Issue has no canonical Fibonacci sizing value; assign native Points before migration.`);return i}function dM({label:e,labels:t,mapping:n}){let r=t.flatMap(e=>{let t=n.get(e.toLowerCase());return t===void 0?[]:[t]}),i=[...new Set(r)];if(i.length>1)throw new L(`Found conflicting legacy ${e} values.`);return i[0]}var fM=class{constructor(e){this._client=e}async*callToolStream(e,t=PD,n){let r=this._client,i={...n,task:n?.task??(r.isToolTask(e.name)?{}:void 0)},a=r.requestStream({method:`tools/call`,params:e},t,i),o=r.getToolOutputValidator(e.name);for await(let t of a){if(t.type===`result`&&o){let n=t.result;if(!n.structuredContent&&!n.isError){yield{type:`error`,error:new Q(Z.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(n.structuredContent)try{let e=o(n.structuredContent);if(!e.valid){yield{type:`error`,error:new Q(Z.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)};return}}catch(e){if(e instanceof Q){yield{type:`error`,error:e};return}yield{type:`error`,error:new Q(Z.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)};return}}yield t}}async getTask(e,t){return this._client.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._client.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._client.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._client.cancelTask({taskId:e},t)}requestStream(e,t,n){return this._client.requestStream(e,t,n)}};function pM(e,t){if(e&&typeof t==`object`&&t){if(e.type===`object`&&e.properties&&typeof e.properties==`object`){let n=t,r=e.properties;for(let e of Object.keys(r)){let t=r[e];n[e]===void 0&&Object.prototype.hasOwnProperty.call(t,`default`)&&(n[e]=t.default),n[e]!==void 0&&pM(t,n[e])}}if(Array.isArray(e.anyOf))for(let n of e.anyOf)typeof n!=`boolean`&&pM(n,t);if(Array.isArray(e.oneOf))for(let n of e.oneOf)typeof n!=`boolean`&&pM(n,t)}}function mM(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};let t=e.form!==void 0,n=e.url!==void 0;return{supportsFormMode:t||!t&&!n,supportsUrlMode:n}}var hM=class extends Ak{constructor(e,t){super(t),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=t?.capabilities??{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new pj,t?.listChanged&&(this._pendingListChangedConfig=t.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler(`tools`,LD,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler(`prompts`,OD,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler(`resources`,sD,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||={tasks:new fM(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=Mk(this._capabilities,e)}setRequestHandler(e,t){let n=MT(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r=RT(n);if(typeof r!=`string`)throw Error(`Schema method literal must be a string`);let i=r;return i===`elicitation/create`?super.setRequestHandler(e,async(e,n)=>{let r=AT(sO,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new Q(Z.InvalidParams,`Invalid elicitation request: ${e}`)}let{params:i}=r.data;i.mode=i.mode??`form`;let{supportsFormMode:a,supportsUrlMode:o}=mM(this._capabilities.elicitation);if(i.mode===`form`&&!a)throw new Q(Z.InvalidParams,`Client does not support form-mode elicitation requests`);if(i.mode===`url`&&!o)throw new Q(Z.InvalidParams,`Client does not support URL-mode elicitation requests`);let s=await Promise.resolve(t(e,n));if(i.task){let e=AT(FE,s);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new Q(Z.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let c=AT(uO,s);if(!c.success){let e=c.error instanceof Error?c.error.message:String(c.error);throw new Q(Z.InvalidParams,`Invalid elicitation result: ${e}`)}let l=c.data,u=i.mode===`form`?i.requestedSchema:void 0;if(i.mode===`form`&&l.action===`accept`&&l.content&&u&&this._capabilities.elicitation?.form?.applyDefaults)try{pM(u,l.content)}catch{}return l}):i===`sampling/createMessage`?super.setRequestHandler(e,async(e,n)=>{let r=AT(ZD,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new Q(Z.InvalidParams,`Invalid sampling request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=AT(FE,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new Q(Z.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=AT(i.tools||i.toolChoice?$D:QD,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new Q(Z.InvalidParams,`Invalid sampling result: ${e}`)}return o.data}):super.setRequestHandler(e,t)}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw Error(`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(await super.connect(e),e.sessionId===void 0)try{let n=await this.request({method:`initialize`,params:{protocolVersion:zT,capabilities:this._capabilities,clientInfo:this._clientInfo}},wE,t);if(n===void 0)throw Error(`Server sent invalid initialize result: ${n}`);if(!BT.includes(n.protocolVersion))throw Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:`notifications/initialized`}),this._pendingListChangedConfig&&=(this._setupListChangedHandlers(this._pendingListChangedConfig),void 0)}catch(e){throw this.close(),e}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case`logging/setLevel`:if(!this._serverCapabilities?.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._serverCapabilities?.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:case`resources/subscribe`:case`resources/unsubscribe`:if(!this._serverCapabilities?.resources)throw Error(`Server does not support resources (required for ${e})`);if(e===`resources/subscribe`&&!this._serverCapabilities.resources.subscribe)throw Error(`Server does not support resource subscriptions (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._serverCapabilities?.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`completion/complete`:if(!this._serverCapabilities?.completions)throw Error(`Server does not support completions (required for ${e})`)}}assertNotificationCapability(e){if(e===`notifications/roots/list_changed`&&!this._capabilities.roots?.listChanged)throw Error(`Client does not support roots list changed notifications (required for ${e})`)}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`sampling/createMessage`:if(!this._capabilities.sampling)throw Error(`Client does not support sampling capability (required for ${e})`);break;case`elicitation/create`:if(!this._capabilities.elicitation)throw Error(`Client does not support elicitation capability (required for ${e})`);break;case`roots/list`:if(!this._capabilities.roots)throw Error(`Client does not support roots capability (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Client does not support tasks capability (required for ${e})`)}}assertTaskCapability(e){hj(this._serverCapabilities?.tasks?.requests,e,`Server`)}assertTaskHandlerCapability(e){this._capabilities&&gj(this._capabilities.tasks?.requests,e,`Client`)}async ping(e){return this.request({method:`ping`},dE,e)}async complete(e,t){return this.request({method:`completion/complete`,params:e},_O,t)}async setLoggingLevel(e,t){return this.request({method:`logging/setLevel`,params:{level:e}},dE,t)}async getPrompt(e,t){return this.request({method:`prompts/get`,params:e},DD,t)}async listPrompts(e,t){return this.request({method:`prompts/list`,params:e},_D,t)}async listResources(e,t){return this.request({method:`resources/list`,params:e},eD,t)}async listResourceTemplates(e,t){return this.request({method:`resources/templates/list`,params:e},nD,t)}async readResource(e,t){return this.request({method:`resources/read`,params:e},oD,t)}async subscribeResource(e,t){return this.request({method:`resources/subscribe`,params:e},dE,t)}async unsubscribeResource(e,t){return this.request({method:`resources/unsubscribe`,params:e},dE,t)}async callTool(e,t=PD,n){if(this.isToolTaskRequired(e.name))throw new Q(Z.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let r=await this.request({method:`tools/call`,params:e},t,n),i=this.getToolOutputValidator(e.name);if(i){if(!r.structuredContent&&!r.isError)throw new Q(Z.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(r.structuredContent)try{let e=i(r.structuredContent);if(!e.valid)throw new Q(Z.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)}catch(e){throw e instanceof Q?e:new Q(Z.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)}}return r}isToolTask(e){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let t of e){if(t.outputSchema){let e=this._jsonSchemaValidator.getValidator(t.outputSchema);this._cachedToolOutputValidators.set(t.name,e)}let e=t.execution?.taskSupport;(e===`required`||e===`optional`)&&this._cachedKnownTaskTools.add(t.name),e===`required`&&this._cachedRequiredTaskTools.add(t.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,t){let n=await this.request({method:`tools/list`,params:e},ND,t);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(e,t,n,r){let i=RD.safeParse(n);if(!i.success)throw Error(`Invalid ${e} listChanged options: ${i.error.message}`);if(typeof n.onChanged!=`function`)throw Error(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:a,debounceMs:o}=i.data,{onChanged:s}=n,c=async()=>{if(!a){s(null,null);return}try{let e=await r();s(null,e)}catch(e){let t=e instanceof Error?e:Error(String(e));s(t,null)}};this.setNotificationHandler(t,()=>{if(o){let t=this._listChangedDebounceTimers.get(e);t&&clearTimeout(t);let n=setTimeout(c,o);this._listChangedDebounceTimers.set(e,n)}else c()})}async sendRootsListChanged(){return this.notification({method:`notifications/roots/list_changed`})}},gM=E(((e,t)=>{t.exports=a,a.sync=o;var n=Me(`fs`);function r(e,t){var n=t.pathExt===void 0?process.env.PATHEXT:t.pathExt;if(!n||(n=n.split(`;`),n.indexOf(``)!==-1))return!0;for(var r=0;r<n.length;r++){var i=n[r].toLowerCase();if(i&&e.substr(-i.length).toLowerCase()===i)return!0}return!1}function i(e,t,n){return!e.isSymbolicLink()&&!e.isFile()?!1:r(t,n)}function a(e,t,r){n.stat(e,function(n,a){r(n,!n&&i(a,e,t))})}function o(e,t){return i(n.statSync(e),e,t)}})),_M=E(((e,t)=>{t.exports=r,r.sync=i;var n=Me(`fs`);function r(e,t,r){n.stat(e,function(e,n){r(e,!e&&a(n,t))})}function i(e,t){return a(n.statSync(e),t)}function a(e,t){return e.isFile()&&o(e,t)}function o(e,t){var n=e.mode,r=e.uid,i=e.gid,a=t.uid===void 0?process.getuid&&process.getuid():t.uid,o=t.gid===void 0?process.getgid&&process.getgid():t.gid,s=64,c=8,l=1,u=s|c;return n&l||n&c&&i===o||n&s&&r===a||n&u&&a===0}})),vM=E(((e,t)=>{Me(`fs`);var n=process.platform===`win32`||global.TESTING_WINDOWS?gM():_M();t.exports=r,r.sync=i;function r(e,t,i){if(typeof t==`function`&&(i=t,t={}),!i){if(typeof Promise!=`function`)throw TypeError(`callback not provided`);return new Promise(function(n,i){r(e,t||{},function(e,t){e?i(e):n(t)})})}n(e,t||{},function(e,n){e&&(e.code===`EACCES`||t&&t.ignoreErrors)&&(e=null,n=!1),i(e,n)})}function i(e,t){try{return n.sync(e,t||{})}catch(e){if(t&&t.ignoreErrors||e.code===`EACCES`)return!1;throw e}}})),yM=E(((e,t)=>{var n=process.platform===`win32`||process.env.OSTYPE===`cygwin`||process.env.OSTYPE===`msys`,r=Me(`path`),i=n?`;`:`:`,a=vM(),o=e=>Object.assign(Error(`not found: ${e}`),{code:`ENOENT`}),s=(e,t)=>{let r=t.colon||i,a=e.match(/\//)||n&&e.match(/\\/)?[``]:[...n?[process.cwd()]:[],...(t.path||process.env.PATH||``).split(r)],o=n?t.pathExt||process.env.PATHEXT||`.EXE;.CMD;.BAT;.COM`:``,s=n?o.split(r):[``];return n&&e.indexOf(`.`)!==-1&&s[0]!==``&&s.unshift(``),{pathEnv:a,pathExt:s,pathExtExe:o}},c=(e,t,n)=>{typeof t==`function`&&(n=t,t={}),t||={};let{pathEnv:i,pathExt:c,pathExtExe:l}=s(e,t),u=[],d=n=>new Promise((a,s)=>{if(n===i.length)return t.all&&u.length?a(u):s(o(e));let c=i[n],l=/^".*"$/.test(c)?c.slice(1,-1):c,d=r.join(l,e),p=!l&&/^\.[\\\/]/.test(e)?e.slice(0,2)+d:d;a(f(p,n,0))}),f=(e,n,r)=>new Promise((i,o)=>{if(r===c.length)return i(d(n+1));let s=c[r];a(e+s,{pathExt:l},(a,o)=>{if(!a&&o){if(t.all)u.push(e+s);else return i(e+s)}return i(f(e,n,r+1))})});return n?d(0).then(e=>n(null,e),n):d(0)};t.exports=c,c.sync=(e,t)=>{t||={};let{pathEnv:n,pathExt:i,pathExtExe:c}=s(e,t),l=[];for(let o=0;o<n.length;o++){let s=n[o],u=/^".*"$/.test(s)?s.slice(1,-1):s,d=r.join(u,e),f=!u&&/^\.[\\\/]/.test(e)?e.slice(0,2)+d:d;for(let e=0;e<i.length;e++){let n=f+i[e];try{if(a.sync(n,{pathExt:c})){if(t.all)l.push(n);else return n}}catch{}}}if(t.all&&l.length)return l;if(t.nothrow)return null;throw o(e)}})),bM=E(((e,t)=>{var n=(e={})=>{let t=e.env||process.env;return(e.platform||process.platform)===`win32`?Object.keys(t).reverse().find(e=>e.toUpperCase()===`PATH`)||`Path`:`PATH`};t.exports=n,t.exports.default=n})),xM=E(((e,t)=>{var n=Me(`path`),r=yM(),i=bM();function a(e,t){let a=e.options.env||process.env,o=process.cwd(),s=e.options.cwd!=null,c=s&&process.chdir!==void 0&&!process.chdir.disabled;if(c)try{process.chdir(e.options.cwd)}catch{}let l;try{l=r.sync(e.command,{path:a[i({env:a})],pathExt:t?n.delimiter:void 0})}catch{}finally{c&&process.chdir(o)}return l&&=n.resolve(s?e.options.cwd:``,l),l}function o(e){return a(e)||a(e,!0)}t.exports=o})),SM=E(((e,t)=>{var n=/([()\][%!^"`<>&|;, *?])/g;function r(e){return e=e.replace(n,`^$1`),e}function i(e,t){return e=`${e}`,e=e.replace(/(?=(\\+?)?)\1"/g,`$1$1\\"`),e=e.replace(/(?=(\\+?)?)\1$/,`$1$1`),e=`"${e}"`,e=e.replace(n,`^$1`),t&&(e=e.replace(n,`^$1`)),e}t.exports.command=r,t.exports.argument=i})),CM=E(((e,t)=>{t.exports=/^#!(.*)/})),wM=E(((e,t)=>{var n=CM();t.exports=(e=``)=>{let t=e.match(n);if(!t)return null;let[r,i]=t[0].replace(/#! ?/,``).split(` `),a=r.split(`/`).pop();return a===`env`?i:i?`${a} ${i}`:a}})),TM=E(((e,t)=>{var n=Me(`fs`),r=wM();function i(e){let t=Buffer.alloc(150),i;try{i=n.openSync(e,`r`),n.readSync(i,t,0,150,0),n.closeSync(i)}catch{}return r(t.toString())}t.exports=i})),EM=E(((e,t)=>{var n=Me(`path`),r=xM(),i=SM(),a=TM(),o=process.platform===`win32`,s=/\.(?:com|exe)$/i,c=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function l(e){e.file=r(e);let t=e.file&&a(e.file);return t?(e.args.unshift(e.file),e.command=t,r(e)):e.file}function u(e){if(!o)return e;let t=l(e),r=!s.test(t);if(e.options.forceShell||r){let r=c.test(t);e.command=n.normalize(e.command),e.command=i.command(e.command),e.args=e.args.map(e=>i.argument(e,r)),e.args=[`/d`,`/s`,`/c`,`"${[e.command].concat(e.args).join(` `)}"`],e.command=process.env.comspec||`cmd.exe`,e.options.windowsVerbatimArguments=!0}return e}function d(e,t,n){t&&!Array.isArray(t)&&(n=t,t=null),t=t?t.slice(0):[],n=Object.assign({},n);let r={command:e,args:t,options:n,file:void 0,original:{command:e,args:t}};return n.shell?r:u(r)}t.exports=d})),DM=E(((e,t)=>{var n=process.platform===`win32`;function r(e,t){return Object.assign(Error(`${t} ${e.command} ENOENT`),{code:`ENOENT`,errno:`ENOENT`,syscall:`${t} ${e.command}`,path:e.command,spawnargs:e.args})}function i(e,t){if(!n)return;let r=e.emit;e.emit=function(n,i){if(n===`exit`){let n=a(i,t);if(n)return r.call(e,`error`,n)}return r.apply(e,arguments)}}function a(e,t){return n&&e===1&&!t.file?r(t.original,`spawn`):null}function o(e,t){return n&&e===1&&!t.file?r(t.original,`spawnSync`):null}t.exports={hookChildProcess:i,verifyENOENT:a,verifyENOENTSync:o,notFoundError:r}})),OM=Ae(E(((e,t)=>{var n=Me(`child_process`),r=EM(),i=DM();function a(e,t,a){let o=r(e,t,a),s=n.spawn(o.command,o.args,o.options);return i.hookChildProcess(s,o),s}function o(e,t,a){let o=r(e,t,a),s=n.spawnSync(o.command,o.args,o.options);return s.error=s.error||i.verifyENOENTSync(s.status,o),s}t.exports=a,t.exports.spawn=a,t.exports.sync=o,t.exports._parse=r,t.exports._enoent=i}))(),1),kM=le.platform===`win32`?[`APPDATA`,`HOMEDRIVE`,`HOMEPATH`,`LOCALAPPDATA`,`PATH`,`PROCESSOR_ARCHITECTURE`,`SYSTEMDRIVE`,`SYSTEMROOT`,`TEMP`,`USERNAME`,`USERPROFILE`,`PROGRAMFILES`]:[`HOME`,`LOGNAME`,`PATH`,`SHELL`,`TERM`,`USER`];function AM(){let e={};for(let t of kM){let n=le.env[t];n!==void 0&&(n.startsWith(`()`)||(e[t]=n))}return e}var jM=class{constructor(e){this._stderrStream=null,this._serverParams=e,this._readBuffer=new Lj({maxBufferSize:e.maxBufferSize}),(e.stderr===`pipe`||e.stderr===`overlapped`)&&(this._stderrStream=new be)}async start(){if(this._process)throw Error(`StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.`);return new Promise((e,t)=>{this._process=(0,OM.default)(this._serverParams.command,this._serverParams.args??[],{env:{...AM(),...this._serverParams.env},stdio:[`pipe`,`pipe`,this._serverParams.stderr??`inherit`],shell:!1,windowsHide:le.platform===`win32`,cwd:this._serverParams.cwd}),this._process.on(`error`,e=>{t(e),this.onerror?.(e)}),this._process.on(`spawn`,()=>{e()}),this._process.on(`close`,e=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on(`error`,e=>{this.onerror?.(e)}),this._process.stdout?.on(`data`,e=>{try{this._readBuffer.append(e),this.processReadBuffer()}catch(e){this.onerror?.(e),this.close().catch(()=>{})}}),this._process.stdout?.on(`error`,e=>{this.onerror?.(e)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){return this._stderrStream?this._stderrStream:this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){if(this._process){let e=this._process;this._process=void 0;let t=new Promise(t=>{e.once(`close`,()=>{t()})});try{e.stdin?.end()}catch{}if(await Promise.race([t,new Promise(e=>setTimeout(e,2e3).unref())]),e.exitCode===null){try{e.kill(`SIGTERM`)}catch{}await Promise.race([t,new Promise(e=>setTimeout(e,2e3).unref())])}if(e.exitCode===null)try{e.kill(`SIGKILL`)}catch{}}this._readBuffer.clear()}send(e){return new Promise(t=>{if(!this._process?.stdin)throw Error(`Not connected`);let n=zj(e);this._process.stdin.write(n)?t():this._process.stdin.once(`drain`,t)})}};async function MM(e,t,n,r=3e4,i){let a=new AbortController,o=()=>a.abort();i?.addEventListener(`abort`,o,{once:!0}),i?.aborted&&o();let s=setTimeout(o,r),c=``,l=!1;try{let r=await sb(e,t,a.signal,void 0,{maxAggregateRssBytes:1024**3,minFreeDiskBytes:256*1024**2,maxNewOutputBytes:1048576},void 0,void 0,{starting:()=>{},observed:()=>{},idle:()=>{l=!0},assertQuiescent:()=>{}},{environment:n,cwd:e,maxCapturedOutputBytes:1048576,stdoutOnly:!0,failedOutput:e=>{let t=e.toString(`utf8`).trimEnd().split(/\r?\n/u).at(-1);return[`ai-delivery: Configured personal author token is invalid or expired; refresh the selected token.`,`ai-delivery: Machine GitHub session is invalid or expired; verify the selected github.com account.`,`ai-delivery: Author cannot read the selected GitHub repository; verify configured access.`,`ai-delivery: Reviewer GitHub App cannot read the selected repository; verify its installation and repository access.`].includes(t??``)&&(c=t),` Authentication probe failed; raw output withheld.`}});return{failed:!l,stdout:l?r.toString(`utf8`):``,diagnostic:c,cleanupConfirmed:l}}catch{return{failed:!0,stdout:``,diagnostic:c,cleanupConfirmed:l}}finally{clearTimeout(s),i?.removeEventListener(`abort`,o)}}var NM=k().max(128).regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/u),PM=P({action:F([`install`,`doctor`,`update`,`rollback`,`remove`]),host:F([`codex`,`claude-code`]),scope:F([`user`,`project`,`local`]),version:NM.optional(),dryRun:j().default(!1),checkAuth:j().default(!1),repo:k().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u).optional(),repoRoot:k().min(1)}),FM=P({pid:A().int().positive(),birth:k().min(1)}),IM=P({action:PM.shape.action,targetVersion:NM.nullable(),owner:FM,producerDigest:k().regex(/^sha256:[a-f0-9]{64}$/u),staging:P({path:k(),device:A().int().nonnegative().optional(),inode:A().int().nonnegative().optional()}).optional(),command:Rl(`phase`,[P({phase:I(`idle`)}),P({phase:I(`starting`)}),P({phase:I(`running`),process:FM,tracked:M(FM.extend({pgid:A().int().positive()})).max(256)})])}),LM=P({owner:I(`@aviaratech/ai-delivery.plugin@1`),host:PM.shape.host,scope:PM.shape.scope,projectRoot:k().nullable(),nativeHome:k().min(1),marketplace:k(),currentVersion:NM.nullable(),previousVersion:NM.nullable(),installedPath:k().nullable(),nativeVersion:k().optional(),pending:IM.optional()}),RM=P({owner:I(`@aviaratech/ai-delivery.plugin-version@1`),version:NM,archiveSha256:k().regex(/^[a-f0-9]{64}$/u),files:Wl(k(),k().regex(/^[a-f0-9]{64}$/u))}),zM=e=>fe(`sha256`).update(e).digest(`hex`);function BM(){let e={PATH:process.env.PATH??``,DISABLE_AUTOUPDATER:`1`};for(let t of[`HOME`,`CODEX_HOME`,`CLAUDE_CONFIG_DIR`])process.env[t]!==void 0&&(e[t]=process.env[t]);return e}var VM=N({routing:N({repository:PM.shape.repo.unwrap()}),reviewRoute:N({author:N({actorLogin:k().regex(/^[A-Za-z0-9-]+(?:\[bot\])?$/u).max(200),authSource:F([`app`,`personal`]),credentialSource:k().optional(),identity:k()}),reviewer:N({actorLogin:k().regex(/^[A-Za-z0-9-]+(?:\[bot\])?$/u).max(200),identity:k(),repositoryAccess:I(`readable`)}),rules:N({visibility:F([`complete`,`partial`,`unknown`]),observedRequiredApprovals:A().int().nonnegative().nullable()}),approvalEligibility:F([`unknown`,`insufficient-permission`])})});async function HM(e,t,n){let r;try{r=await jh(),n.settings=`valid`}catch{n.settings=`unavailable_or_invalid`,n.outcome=`blocked`,n.reason=`settings_unavailable_or_invalid`;return}let i=Object.values(r.roles).flatMap(e=>Object.values(e.credentialEnv)),a=r.roles.author,o=a.authSource===`personal`&&Jm(a.credentialEnv.token,process.env),s=o?i.filter(e=>e!==`GH_TOKEN`):i;n.processReferences.requiredNames=s;let c=s.filter(e=>!process.env[e]?.trim());if(n.processReferences.missingNames=c,c.length>0){n.processReferences.status=`missing`,n.outcome=`blocked`,n.reason=`missing_references`;return}if(i.some(e=>/^(?:NODE_|NPM_|GIT_)/u.test(e)||[...Ym,`PATH`,`HOME`,`CODEX_HOME`,`CLAUDE_CONFIG_DIR`,`AI_DELIVERY_CONFIG`,`AI_DELIVERY_IDENTITY`,`DISABLE_AUTOUPDATER`].includes(e))){n.processReferences.status=`invalid`,n.outcome=`blocked`,n.reason=`invalid_references`;return}let l={PATH:process.env.PATH??``,AI_DELIVERY_CONFIG:r.configPath,NODE_OPTIONS:`--max-old-space-size=512 --v8-pool-size=1`,DISABLE_AUTOUPDATER:`1`};for(let e of i)process.env[e]!==void 0&&(l[e]=process.env[e].trim());if(o)for(let e of Ym)process.env[e]!==void 0&&(l[e]=process.env[e]);try{a.authSource===`personal`&&qm(process.env);for(let e of[`author`,`reviewer`])r.roles[e].authSource!==`personal`&&Nh({config:r,role:e,env:l})}catch{n.processReferences.status=`invalid`,n.outcome=`blocked`,n.reason=`invalid_references`;return}n.processReferences.status=`complete`;let u=await MM(e.repoRoot,[process.execPath,w(t,`runtime/dist/cli.js`),`--repo`,e.repo,`config:resolve`],l);if(!u.cleanupConfirmed){n.outcome=`failed`,n.authentication.status=`unverified`,n.repositoryAccess.status=`unverified`,n.reason=`probe_cleanup_unverified`;return}if(u.failed){n.outcome=`failed`,n.authentication.status=`unverified`,n.repositoryAccess.status=`unverified`;let e=u.diagnostic;e===`ai-delivery: Configured personal author token is invalid or expired; refresh the selected token.`||e===`ai-delivery: Machine GitHub session is invalid or expired; verify the selected github.com account.`?(n.authentication.status=`failed`,n.reason=`authentication_failed`):[`ai-delivery: Author cannot read the selected GitHub repository; verify configured access.`,`ai-delivery: Reviewer GitHub App cannot read the selected repository; verify its installation and repository access.`].includes(e??``)?(n.repositoryAccess.status=`denied`,n.reason=`repository_denied`):n.reason=`probe_failed`;return}try{let t=VM.parse(JSON.parse(u.stdout)),a=t.reviewRoute;if(t.routing.repository.toLowerCase()!==e.repo.toLowerCase()||a.author.authSource!==(r.roles.author.authSource??`app`)||a.author.identity!==r.roles.author.identity||a.reviewer.identity!==r.roles.reviewer.identity||a.author.actorLogin.toLowerCase()===a.reviewer.actorLogin.toLowerCase())throw Error(`Inconsistent readback`);let s={author:{actorLogin:a.author.actorLogin,authSource:a.author.authSource,...o&&a.author.credentialSource!==void 0?{credentialSource:a.author.credentialSource}:{}},reviewer:{actorLogin:a.reviewer.actorLogin,authSource:`app`}};if(o&&!a.author.credentialSource?.startsWith(`gh:github.com:`))throw Error(`Missing session route`);if(i.some(e=>l[e]!==void 0&&JSON.stringify(s).includes(l[e])))throw Error(`Unsafe readback`);n.authentication={status:`verified`,...s},n.repositoryAccess.status=`verified`,n.reviewRules={...a.rules,approvalEligibility:a.approvalEligibility},n.outcome=`readback_complete`}catch{n.authentication.status=`unverified`,n.repositoryAccess.status=`unverified`,n.outcome=`failed`,n.reason=`invalid_readback`}}function UM(e){let t=T(e);for(;;){if(i(t)&&c(t).isSymbolicLink())throw Error(`Managed plugin paths must not use symlinks.`);let e=C(t);if(e===t)break;t=e}}function WM(e){let t=h(T(e.repoRoot)),n=T(t,(e.host===`codex`?process.env.CODEX_HOME:process.env.CLAUDE_CONFIG_DIR)??w(de(),e.host===`codex`?`.codex`:`.claude`)),r=[];for(;!i(n);)r.unshift(ie(n)),n=C(n);let a=w(h(n),...r),o=e.scope===`user`?`user`:`${e.scope}-${fe(`sha256`).update(t).digest(`hex`).slice(0,16)}`,s=w(de(),`.cache`,`ai-delivery`,`plugins`,e.host,o);if(UM(s),i(s)&&(!c(s).isDirectory()||c(s).mode&63))throw Error(`Managed plugin directory is not private.`);return{directory:s,projectRoot:t,nativeHome:a,marketplace:`ai-delivery-${o}`,catalog:w(s,`marketplace`),statePath:w(s,`state.json`),tool:e.host===`codex`?`codex`:`claude`}}function GM(e,t){if(!i(t.statePath))return;let n=c(t.statePath);if(!n.isFile()||n.nlink!==1||n.mode&63||n.size>65536)throw Error(`Managed plugin state is unsafe.`);let r=LM.parse(JSON.parse(d(t.statePath,`utf8`)));if(r.nativeHome!==t.nativeHome)throw Error(`Managed plugin state belongs to a different native profile.`);if(r.host!==e.host||r.scope!==e.scope||r.marketplace!==t.marketplace||r.projectRoot!==(e.scope===`user`?null:t.projectRoot))throw Error(`Managed plugin state belongs to a different target.`);return r}function KM(e){let t=Vy().get(e);return t&&!t.status.startsWith(`Z`)?t.identity:void 0}async function qM(e){if(KM(e.owner.pid)===e.owner.birth)throw Error(`A live plugin installer still owns this target.`);if(e.command.phase===`starting`)throw Error(`Interrupted installer command ownership is unknown; preserve its state before recovery.`);if(e.command.phase!==`running`)return;let t={rootPid:e.command.process.pid,rootIdentity:e.command.process.birth,sampled:!0,tracked:new Map(e.command.tracked.map(({pid:e,birth:t,pgid:n})=>[e,{pid:e,identity:t,pgid:n,ppid:0,rssBytes:0,status:``}]))};Ky(t),await Gy(t)}async function JM(e,t,n,r,i,a=!1){return(await sb(n,[e,...t],r,void 0,{maxAggregateRssBytes:1024**3,minFreeDiskBytes:256*1024**2,maxNewOutputBytes:512*1024**2},void 0,void 0,{starting:()=>i?.({phase:`starting`}),observed:e=>i?.({phase:`running`,process:{pid:e.rootPid,birth:e.rootIdentity},tracked:[...e.tracked.values()].map(({pid:e,identity:t,pgid:n})=>({pid:e,birth:t,pgid:n}))}),idle:()=>i?.({phase:`idle`}),assertQuiescent:()=>{}},{environment:a?BM():{...process.env,DISABLE_AUTOUPDATER:`1`},cwd:n,maxCapturedOutputBytes:1048576,stdoutOnly:!0,failedOutput:e=>a?` Native inventory failed; raw output withheld.`:` Native command output: ${e.toString(`utf8`).slice(-2e3)}`})).toString(`utf8`)}function YM(e){let t=u(e,`r`);try{o(t)}finally{n(t)}}function XM(e,t){return w(e.catalog,`versions`,t,`plugins`,`ai-delivery`)}function ZM(e,t){return w(e.catalog,`versions`,t)}function QM(e){let t={},n=0,r=(e,i,a)=>{if(a>16)throw Error(`Plugin tree exceeds the depth bound.`);for(let o of p(e).sort()){if(++n>4096)throw Error(`Plugin tree exceeds the entry bound.`);let s=w(e,o),l=`${i}${o}`,u=c(s);if(u.isSymbolicLink()||!u.isDirectory()&&(!u.isFile()||u.nlink!==1))throw Error(`Plugin tree contains links or special files.`);if(u.isDirectory())r(s,`${l}/`,a+1);else{if(u.size>32*1024**2)throw Error(`Plugin file exceeds the size bound.`);t[l]=zM(d(s))}}};return r(e,``,0),t}function $M(e,t){let n=ZM(e,t);UM(n);let r=w(n,`version.json`);if(!i(r))throw Error(`No completed immutable plugin unit for ${t}.`);let a=c(r),o=w(n,`archive.tgz`),s=c(o);if(!a.isFile()||a.nlink!==1||a.size>1048576||!s.isFile()||s.nlink!==1||s.size>32*1024**2)throw Error(`Immutable plugin unit metadata is unsafe.`);let l=RM.parse(JSON.parse(d(r,`utf8`)));if(l.version!==t||JSON.stringify(QM(XM(e,t)))!==JSON.stringify(l.files)||zM(d(o))!==l.archiveSha256)throw Error(`Immutable plugin unit integrity changed.`);return l}function eN(e){if(e.length>32*1024**2)throw Error(`Plugin archive exceeds 32 MiB.`);let t=ve(e,{maxOutputLength:128*1024**2}),n=new Map;for(let e=0;e+512<=t.length;){let r=t.subarray(e,e+512);if(r.every(e=>e===0))break;let i=(e,t)=>r.subarray(e,e+t).toString().replace(/\0.*$/su,``).trim(),a=(e,t)=>{let n=i(e,t);if(!/^[0-7]+$/u.test(n))throw Error(`Unsupported tar numeric header.`);return Number.parseInt(n,8)};if([...r].reduce((e,t,n)=>e+(n>=148&&n<156?32:t),0)!==a(148,8))throw Error(`Plugin archive header checksum mismatch.`);let o=`${i(345,155)?`${i(345,155)}/`:``}${i(0,100)}`,s=a(124,12),c=i(156,1);if(!/^package\/[A-Za-z0-9_./-]+$/u.test(o)||o.split(`/`).some(e=>e===`..`||e===`.`)||o.split(`/`).length>16||![``,`0`,`5`].includes(c)||e+512+s>t.length||n.has(o)||n.size>=4096)throw Error(`Unsafe or unsupported plugin archive member.`);c!==`5`&&n.set(o,t.subarray(e+512,e+512+s)),e+=512+Math.ceil(s/512)*512}return n}async function tN(e,t,n,r,a){let o=ZM(e,t);if(i(o)){$M(e,t);return}let s=C(o);Lv(s);let u=w(s,`.stage-${me()}`);a({path:u}),l(u,{mode:448});let f=c(u);YM(s),a({path:u,device:f.dev,inode:f.ino});let p=!0,m=!1,h,v=e=>{p=e.phase===`idle`,r(e)};try{let r=JSON.parse(await JM(`npm`,[`pack`,`@aviaratech/ai-delivery@${t}`,`--ignore-scripts`,`--json`,`--logs-max`,`0`,`--cache`,w(e.directory,`npm-cache`),`--pack-destination`,u],u,n,v))[0]?.filename;if(typeof r!=`string`||!/^aviaratech-ai-delivery-[A-Za-z0-9.+_-]+\.tgz$/u.test(r))throw Error(`npm returned an unsafe archive path.`);let i=d(w(u,r)),c=eN(i),l=JSON.parse(c.get(`package/package.json`)?.toString()??`null`);if(l?.name!==`@aviaratech/ai-delivery`||l.version!==t)throw Error(`Archive package identity does not match the explicit version.`);let f=w(u,`plugins`,`ai-delivery`);for(let[e,t]of c)if(e.startsWith(`package/plugins/ai-delivery/`)){let n=w(f,e.slice(28));Lv(C(n)),ee(n,t,{mode:384,flag:`wx`}),YM(n)}let p=JSON.parse(d(w(f,`plugin.json`),`utf8`)),m=JSON.parse(d(w(f,`.claude-plugin/plugin.json`),`utf8`)),h=JSON.parse(d(w(f,`runtime/package.json`),`utf8`));if(p.name!==`ai-delivery`||p.version!==t||m.name!==p.name||m.version!==t||m.packageVersion!==t||m.deliveryCapabilityVersion!==2||h.name!==l.name||h.version!==t)throw Error(`Archive does not contain a coherent self-contained native plugin.`);if((await JM(process.execPath,[w(f,`runtime/dist/cli.js`),`--version`],u,n,v)).trim()!==t)throw Error(`Built native CLI version does not match its archive.`);g(w(u,r),w(u,`archive.tgz`)),YM(w(u,`archive.tgz`)),zv(w(u,`version.json`),{owner:`@aviaratech/ai-delivery.plugin-version@1`,version:t,archiveSha256:zM(i),files:QM(f)}),g(u,o),YM(s),a(void 0),$M(e,t)}catch(e){m=!0,h=e}try{if(p&&i(u)){let e=c(u);if(e.dev!==f.dev||e.ino!==f.ino||!e.isDirectory()||e.isSymbolicLink())throw Error(`Owned staging directory identity changed.`);_(u,{recursive:!0}),YM(s)}p&&a(void 0)}catch(e){h=m?AggregateError([h,e],`Plugin preparation failed and staging cleanup also failed.`):e,m=!0}if(m)throw h}function nN(e,t){$M(e,t);let n=`./versions/${t}/plugins/ai-delivery`;zv(w(e.catalog,`.agents/plugins/marketplace.json`),{name:e.marketplace,interface:{displayName:`ai-delivery`},plugins:[{name:`ai-delivery`,source:{source:`local`,path:n},policy:{installation:`AVAILABLE`,authentication:`ON_INSTALL`},category:`Productivity`}]}),zv(w(e.catalog,`.claude-plugin/marketplace.json`),{name:e.marketplace,owner:{name:`AviaraTech`},plugins:[{name:`ai-delivery`,source:n,version:t}]})}async function rN(e,t,n,r){let i=JSON.parse(await JM(t.tool,[`plugin`,`list`,...e.host===`codex`?[`--marketplace`,t.marketplace,`--available`]:[],`--json`],t.projectRoot,n,r,e.action===`doctor`));if(e.host===`claude-code`)return M(Wl(k(),kl())).parse(i);let a=N({installed:M(Wl(k(),kl())),available:M(Wl(k(),kl()))}).parse(i);return[...a.installed.map(e=>({...e,installed:!0})),...a.available.map(e=>({...e,installed:!1}))]}function iN(e,t,n){if(e.host===`claude-code`){let e=w(t.nativeHome,`plugins/known_marketplaces.json`);if(!i(e))return!1;if(!c(e).isFile()||c(e).size>1048576)throw Error(`Native marketplace registry is unsafe.`);let n=Wl(k(),kl()).parse(JSON.parse(d(e,`utf8`)));if(n[t.marketplace]===void 0)return!1;let r=N({source:N({source:I(`directory`),path:k()}),installLocation:k()}).parse(n[t.marketplace]);if(T(r.source.path)!==t.catalog||T(r.installLocation)!==t.catalog)throw Error(`Native marketplace name belongs to an unmanaged source.`);return!0}let r=n.filter(e=>e.marketplaceName===t.marketplace);for(let e of r){let n=N({sourceType:I(`local`),source:k()}).parse(e.marketplaceSource);if(T(n.source)!==t.catalog)throw Error(`Native marketplace name belongs to an unmanaged source.`)}return r.length>0}function aN(e,t,n){let r=n.filter(n=>(n.pluginId??n.id)===`ai-delivery@${t.marketplace}`&&(e.host===`codex`?n.installed===!0:n.scope===e.scope)&&(e.scope===`user`||n.projectPath===t.projectRoot));if(r.length>1)throw Error(`Native plugin readback is ambiguous.`);let i=r[0];if(!i)return;let a=e.host===`codex`?N({source:I(`local`),path:k()}).parse(i.source).path:void 0;return{version:NM.parse(i.version),enabled:j().parse(i.enabled),...typeof i.installPath==`string`?{installedPath:i.installPath}:{},...a?{sourceRoot:a}:{},...i.mcpServers?{mcpServers:Wl(k(),kl()).parse(i.mcpServers)}:{}}}function oN(e){let t=w(e.catalog,`.claude-plugin/marketplace.json`);if(UM(t),!c(t).isFile()||c(t).size>1048576)throw Error(`Managed Claude catalog is unsafe.`);let n=N({name:I(e.marketplace),plugins:M(N({name:k(),version:NM,source:k()}))}).parse(JSON.parse(d(t,`utf8`))).plugins.filter(e=>e.name===`ai-delivery`);if(n.length!==1)throw Error(`Managed Claude catalog selection is ambiguous.`);let r=n[0];if(!r.source.startsWith(`./`)||T(e.catalog,r.source)!==XM(e,r.version))throw Error(`Claude catalog source differs from the immutable managed unit.`);return r}function sN(e,t,n,r,i=n.version){let a=$M(t,e.host===`claude-code`?i:n.version),o=XM(t,e.host===`claude-code`?i:n.version);if(e.host===`claude-code`&&oN(t).version!==i)throw Error(`Claude catalog version differs from its native selection.`);if(e.host===`codex`&&T(n.sourceRoot)!==o)throw Error(`Native plugin source differs from the managed version.`);let s=e.host===`codex`?r:o;if(!s)throw Error(`Native cache path is missing.`);if(e.host===`codex`&&T(s)!==w(t.nativeHome,`plugins/cache`,t.marketplace,`ai-delivery`,n.version))throw Error(`Native cache path is outside the managed native selection.`);if(UM(s),JSON.stringify(QM(s))!==JSON.stringify(a.files))throw Error(`Selected native plugin bytes differ from the verified archive.`);if(e.host===`claude-code`&&!N({command:I(`node`),args:Hl([I("${CLAUDE_PLUGIN_ROOT}/dist/mcp-launcher.js")])}).parse(n.mcpServers?.[`ai-delivery`]))throw Error(`Native MCP binding is missing.`);return s}async function cN(e,t,n){let r=new jM({command:process.execPath,args:[w(e,`dist/mcp-launcher.js`)],cwd:n,env:{...Object.fromEntries(kM.map(e=>[e,``])),NODE_OPTIONS:`--max-old-space-size=1024`},stderr:`pipe`,maxBufferSize:1048576}),i=new hM({name:`ai-delivery-plugin-doctor`,version:`1.0.0`});try{if(await i.connect(r,{timeout:3e4}),i.getServerVersion()?.version!==t)throw Error(`MCP server version differs from the selected archive.`);return await i.listTools({},{timeout:3e4}),{configuration:`native_manifest_present`,startup:`ready`,version:t}}catch{return{configuration:`native_manifest_present`,startup:`failed`,error:`Bundled MCP startup failed; raw output withheld.`}}finally{await i.close(),await r.close()}}async function lN(e){let t=PM.parse(e);if(t.checkAuth&&t.action!==`doctor`)throw Error(`--check-auth is supported only for doctor.`);if(t.checkAuth&&t.repo===void 0)throw Error(`doctor --check-auth requires explicit --repo owner/name.`);if(t.host===`codex`&&t.scope!==`user`)throw Error(`Codex currently supports user plugin installation; select --scope user.`);if((t.action===`install`||t.action===`update`)&&t.version===void 0)throw Error(`An explicit --version is required for install and update.`);if(t.version!==void 0&&t.action!==`install`&&t.action!==`update`)throw Error(`--version is supported only for install and update; rollback selects the recorded previous version.`);if(![`darwin`,`linux`].includes(process.platform))throw Error(`Plugin management requires the supported POSIX runtime environment.`);let n=WM(t),r=GM(t,n),a={action:t.action,host:t.host,scope:t.scope,version:t.action===`remove`?null:t.version??(t.action===`rollback`?r?.previousVersion:r?.currentVersion)??null,changed:!1,dryRun:t.dryRun,installed:!1,marketplace:n.marketplace,managedDirectory:n.directory,repositoryAdmission:`explicit_stage_and_admit_required`};if(t.checkAuth&&(a.authProbe={invocationContext:`selected_runtime_cli`,nativeGuiPropagation:`unverified`,settings:`not_checked`,processReferences:{status:`not_checked`,requiredNames:[],missingNames:[]},authentication:{status:`not_checked`},repositoryAccess:{repository:t.repo,status:`not_checked`},outcome:t.dryRun?`not_checked`:`blocked`,reason:t.dryRun?`dry_run`:`native_plugin_not_ready`}),t.dryRun)return a;if(t.action===`doctor`){if(!r||(a.recoveryRequired=r.pending!==void 0,r.pending||!r.currentVersion))return a;try{$M(n,r.currentVersion)}catch{return a.sourceIntegrity=!1,a.mcp={configuration:`unverified`,startup:`not_checked`,error:`Managed archive integrity failed.`},a}let e=await rN(t,n,new AbortController().signal),i=iN(t,n,e),o=aN(t,n,e);if(a.installed=o?.version===r.currentVersion,a.enabled=o?.enabled??!1,r.installedPath&&(a.nativeCachePath=r.installedPath),r.nativeVersion&&(a.nativeVersion=r.nativeVersion),!i||!a.installed)return a.mcp={configuration:`missing`,startup:`not_checked`},a;try{a.nativePluginRoot=sN(t,n,o,r.installedPath),a.sourceIntegrity=!0,a.skills=p(w(a.nativePluginRoot,`skills`)).sort(),a.mcp=o.enabled?await cN(a.nativePluginRoot,r.currentVersion,n.projectRoot):{configuration:`disabled`,startup:`not_checked`}}catch(e){a.sourceIntegrity=!1,a.mcp={configuration:`unverified`,startup:`not_checked`,error:t.checkAuth?`Selected native plugin integrity failed; raw output withheld.`:(e instanceof Error?e.message:String(e)).slice(0,2e3)}}return a.authProbe&&a.sourceIntegrity&&a.enabled&&a.mcp?.startup===`ready`&&(delete a.authProbe.reason,await HM(t,a.nativePluginRoot,a.authProbe)),a}if(!r&&t.action===`remove`)return a;if(!r&&i(n.directory)&&p(n.directory).length>0)throw Error(`Managed plugin directory contains unrecognized content.`);return Lv(n.directory),py(n.statePath,{projectRoot:n.directory,timeout:200,onReleaseError:e=>{throw e},operation:async()=>{r=GM(t,n);let e=r?.pending!==void 0;if(r?.pending){if(await qM(r.pending),r.pending.producerDigest!==nb(C(ye(import.meta.url))))throw Error(`Interrupted plugin operation belongs to a different controller; resume with its original version.`);let e=r.pending.staging;if(e&&i(e.path)){let t=C(ZM(n,r.pending.targetVersion));if(C(e.path)!==t||!/^\.stage-[a-f0-9-]{36}$/u.test(e.path.slice(t.length+1)))throw Error(`Recorded staging path is outside this version target.`);UM(e.path);let i=c(e.path);if(!i.isDirectory()||(e.device===void 0?p(e.path).length!==0:i.dev!==e.device||i.ino!==e.inode))throw Error(`Interrupted staging directory ownership is unresolved.`);_(e.path,{recursive:!0}),YM(t)}if(r.pending.action!==t.action||r.pending.targetVersion!==a.version)throw Error(`Resume the interrupted original plugin command before selecting a different operation.`)}if((t.action===`update`||t.action===`rollback`)&&(!r||t.action===`update`&&!r.currentVersion))throw Error(`Install a managed plugin before updating or rolling it back.`);let o=t.action===`remove`?null:a.version;if(o===null&&t.action!==`remove`)throw Error(`No previous managed plugin version is available.`);let s=r?.currentVersion??null;r??={owner:`@aviaratech/ai-delivery.plugin@1`,host:t.host,scope:t.scope,projectRoot:t.scope===`user`?null:n.projectRoot,nativeHome:n.nativeHome,marketplace:n.marketplace,currentVersion:null,previousVersion:null,installedPath:null};let l=KM(process.pid);if(!l)throw Error(`Installer owner identity is unknown.`);r.pending={action:t.action,targetVersion:o,owner:{pid:process.pid,birth:l},producerDigest:nb(C(ye(import.meta.url))),command:{phase:`idle`}},zv(n.statePath,r);let u=new AbortController,d=()=>u.abort();process.once(`SIGINT`,d),process.once(`SIGTERM`,d);let f=e=>{r.pending.command=e,zv(n.statePath,r)},m=e=>JM(n.tool,e,n.projectRoot,u.signal,f),h=`ai-delivery@${n.marketplace}`,g=t.host===`codex`?[`plugin`,`remove`,h,`--json`]:[`plugin`,`uninstall`,h,`--scope`,t.scope,`--keep-data`],v=t.host===`codex`?[`plugin`,`add`,h,`--json`]:[`plugin`,`install`,h,`--scope`,t.scope],y=!1;try{if(r.nativeVersion=(await m([`--version`])).trim(),t.host===`claude-code`&&!(await m([`plugin`,`uninstall`,`--help`])).includes(`--keep-data`))throw Error(`This Claude Code version cannot preserve plugin data; upgrade the native tool first.`);process.stderr.write(`ai-delivery.plugin ${JSON.stringify({action:t.action,host:t.host,scope:t.scope,stage:o?`prepare_version`:`native_remove`,version:o})}\n`);let i=await rN(t,n,u.signal,f),c=iN(t,n,i),l=aN(t,n,i);if(l&&!s&&!(e&&l.version===o))throw Error(`Existing native plugin is not owned by managed state.`);let d=l?.version;if(l&&e&&t.host===`claude-code`&&(d=oN(n).version,d!==s&&d!==o))throw Error(`Interrupted native selection has an incompatible catalog version.`);l&&sN(t,n,l,l.version===s?r.installedPath:w(n.nativeHome,`plugins/cache`,n.marketplace,`ai-delivery`,l.version),d),o&&(await tN(n,o,u.signal,f,e=>{e?r.pending.staging=e:delete r.pending.staging,zv(n.statePath,r)}),y=!0,nN(n,o),c||await m([`plugin`,`marketplace`,`add`,n.catalog,...t.host===`codex`?[`--json`]:[`--scope`,t.scope]])),l&&(l.version!==o||t.action===`remove`)&&(y=!0,await m(g));let p=r.installedPath;if(o){let e=await m(v);t.host===`codex`&&(p=N({installedPath:k()}).parse(JSON.parse(e)).installedPath)}let h=await rN(t,n,u.signal,f);if(!iN(t,n,h)&&o)throw Error(`Native marketplace registration is missing.`);let _=aN(t,n,h);if(o?_?.version!==o:_!==void 0)throw Error(`Native installation readback does not match the selected version.`);if(o&&(sN(t,n,_,_?.installedPath??p),!_.enabled))throw Error(`Native plugin selection is disabled.`);return r.currentVersion=o,s!==o&&(r.previousVersion=s),r.installedPath=o?_?.installedPath??p:null,delete r.pending,zv(n.statePath,r),a.version=o,a.changed=s!==o,a.installed=o!==null,a.restartRequired=!0,o&&(a.nativePluginRoot=t.host===`codex`?r.installedPath??XM(n,o):XM(n,o)),a}catch(t){if(!e&&!u.signal.aborted&&!y&&r.pending?.command.phase===`idle`&&r.pending.staging===void 0){delete r.pending;try{zv(n.statePath,r)}catch(e){throw AggregateError([t,e],`Plugin preparation failed and pending-state cleanup also failed.`)}}if(y&&s)try{nN(n,s)}catch{}throw t}finally{process.removeListener(`SIGINT`,d),process.removeListener(`SIGTERM`,d)}}})}var uN=new Ke;uN.name(`ai-delivery`).description(`Generic GitHub issue and pull request delivery`).version(Hj).option(`--identity <name>`,`Configured author or reviewer identity`).option(`--personal-auth`,`Explicit legacy personal-token author override`).option(`--repo <owner/name>`,`GitHub repository owner/name; works from any directory`).option(`--repo-root <path>`,`Launch directory or explicit clone for local operations`,process.cwd());for(let e=2;e<process.argv.length;e++){let t=process.argv[e],n=uN.options.find(e=>e.long===t.split(`=`)[0]||e.short===t);if(n){n.required&&!t.includes(`=`)&&e++;continue}t===`plugin`&&uN.enablePositionalOptions();break}function dN(){let e=uN.opts(),t=(e.identity??process.env.AI_DELIVERY_IDENTITY)?.trim()||void 0;return{repoRoot:e.repoRoot,...t===void 0?{}:{identity:t},personalAuth:e.personalAuth===!0,...e.repo===void 0?{}:{repo:e.repo}}}function fN(e){return e===void 0?void 0:Number(e)}function pN(e){return e===void 0?void 0:e.split(`,`).map(e=>e.trim()).filter(Boolean)}function mN(e){return pN(e)?.map(Number)}function hN(e,t){if(e!==void 0&&t!==void 0)throw Error(`Pass either --body or --body-file.`);return t===void 0?e:d(t,`utf8`)}function gN(e,t){let n=e===void 0?{}:JSON.parse(d(e,`utf8`));return{...G_.parse(n),...Object.fromEntries(Object.entries(t).filter(([,e])=>e!==void 0))}}function _N(e,t){return JC(e,t,dN()).then(t=>Xe(e,t))}function vN(e){process.stdout.write(`${JSON.stringify(e,null,2)}\n`)}var yN=uN.command(`plugin`).description(`Manage the ai-delivery native plugin`);for(let e of[`install`,`doctor`,`update`,`rollback`,`remove`]){let t=yN.command(e).requiredOption(`--host <host>`,`Native host: codex or claude-code`).option(`--scope <scope>`,`Native scope: user, project, or local; Codex supports user`,`user`).option(`--dry-run`,`Describe the selected target without changing files or contacting native tools`).option(`--json`,`Print the result as JSON`);(e===`install`||e===`update`)&&t.requiredOption(`--version <version>`,`Explicit published package version`),e===`doctor`&&t.option(`--check-auth`,`Read configured role identities and repository access; requires explicit --repo`),t.action(async t=>{let n=await lN({action:e,host:t.host,scope:t.scope,...t.version===void 0?{}:{version:t.version},dryRun:t.dryRun===!0,checkAuth:t.checkAuth===!0,...t.checkAuth&&dN().repo?{repo:dN().repo}:{},repoRoot:dN().repoRoot});if(t.json){vN(n);return}process.stdout.write(`${n.dryRun?`Dry run: `:``}${n.host} ${n.scope}: ${e}; version ${n.version??`none`}; installed ${n.installed}; changed ${n.changed}\n`),n.mcp&&process.stdout.write(`Bundled MCP startup: ${n.mcp.startup}${n.mcp.error?` (${n.mcp.error})`:``}\n`),n.recoveryRequired&&process.stdout.write(`Resume the interrupted original plugin command to recover this target.
|
|
311
|
+
`),n.authProbe&&process.stdout.write(`Selected-runtime CLI auth probe: ${n.authProbe.outcome}; settings ${n.authProbe.settings}; process references ${n.authProbe.processReferences.status}; authentication ${n.authProbe.authentication.status}; repository access ${n.authProbe.repositoryAccess.status}${n.authProbe.reason?` (${n.authProbe.reason})`:``}\nNative GUI credential propagation and counted exact-head approval remain unverified.\n`)})}uN.command(`runtime:stage`).description(`Stage a reviewed archive in a private directory; does not activate or admit it`).requiredOption(`--archive <path>`).requiredOption(`--archive-sha256 <digest>`).requiredOption(`--package-version <version>`).requiredOption(`--source-commit <sha>`).requiredOption(`--config-digest <digest>`).requiredOption(`--runtime-directory <path>`).option(`--native-plugin-root <path>`,`Bind the exact reviewed native plugin root`).option(`--max-aggregate-rss-bytes <bytes>`,`Sampled controller plus children RSS limit`).option(`--max-new-output-bytes <bytes>`,`Owned stage and metadata output limit`).option(`--min-free-disk-bytes <bytes>`,`Required free disk headroom`).option(`--max-captured-output-bytes <bytes>`,`Retained command log cap; defaults to 1 MiB`).option(`--authorize-stage`,`Explicit authority to stage this reviewed archive`).action(async e=>_N(`runtime_stage`,{authority:e.authorizeStage===!0?`runtime:stage`:``,archivePath:e.archive,expectedArchiveSha256:e.archiveSha256,packageVersion:e.packageVersion,expectedSourceCommit:e.sourceCommit,expectedConfigDigest:e.configDigest,runtimeDirectory:e.runtimeDirectory,...e.nativePluginRoot===void 0?{}:{nativePluginRoot:e.nativePluginRoot},...[`maxAggregateRssBytes`,`maxNewOutputBytes`,`minFreeDiskBytes`,`maxCapturedOutputBytes`].some(t=>e[t]!==void 0)?{resourceBounds:{maxAggregateRssBytes:Number(e.maxAggregateRssBytes??1024**3),minFreeDiskBytes:Number(e.minFreeDiskBytes??256*1024**2),maxNewOutputBytes:Number(e.maxNewOutputBytes??512*1024**2),maxCapturedOutputBytes:Number(e.maxCapturedOutputBytes??1024**2)}}:{}})),uN.command(`runtime:admit`).description(`Explicitly publish the existing admission for an exact completed stage`).requiredOption(`--stage-id <digest>`).requiredOption(`--source-commit <sha>`).requiredOption(`--config-digest <digest>`).requiredOption(`--runtime-directory <path>`).option(`--expected-prior <digest>`,`SHA-256 of the exact current private admission bytes`).option(`--expected-absent`,`Explicitly require no current admission`).option(`--authorize-admit`,`Explicit authority for the final admission write`).action(async e=>{if(e.expectedPrior===void 0==(e.expectedAbsent!==!0))throw Error(`Choose exactly one of --expected-prior or --expected-absent.`);return _N(`runtime_admit`,{authority:e.authorizeAdmit===!0?`runtime:admit`:``,stageId:e.stageId,expectedSourceCommit:e.sourceCommit,expectedConfigDigest:e.configDigest,runtimeDirectory:e.runtimeDirectory,expectedPriorAdmissionSha256:e.expectedAbsent===!0?null:e.expectedPrior})}),uN.command(`create`).requiredOption(`--title <title>`).option(`--fields-file <path>`,`UTF-8 JSON typed fields; explicit CLI fields take precedence`).option(`--draft`,`Explicitly write an incomplete parked draft`).option(`--body <markdown>`).option(`--body-file <path>`).option(`--type <type>`).option(`--points <number>`).option(`--priority <priority>`).option(`--labels <labels>`).option(`--blocked-by <numbers>`).option(`--blocks <numbers>`,`Add this issue as a blocker of these dependents`).option(`--override-reason <reason>`,`Required explanation when adding a blocker to active work`).option(`--milestone <number>`).option(`--parent <number>`).action(async e=>_N(`issue_create`,gN(e.fieldsFile,{title:e.title,body:hN(e.body,e.bodyFile),issueType:e.type,points:fN(e.points),priority:e.priority,labels:pN(e.labels),blockedBy:mN(e.blockedBy),blocks:mN(e.blocks),overrideReason:e.overrideReason,milestone:fN(e.milestone),parentIssueNumber:fN(e.parent),...e.draft===!0?{draft:!0}:{}}))),uN.command(`start`).option(`--issue <number>`).option(`--request <text>`).option(`--request-id <id>`,`Stable retry identity for a new issue start`).option(`--title <title>`).option(`--body <markdown>`).option(`--body-file <path>`).option(`--type <type>`).option(`--points <number>`).option(`--priority <priority>`).option(`--labels <labels>`).option(`--blocked-by <numbers>`).option(`--blocks <numbers>`,`Add this issue as a blocker of these dependents`).option(`--override-reason <reason>`,`Required explanation when adding a blocker to active work`).option(`--milestone <number>`).option(`--parent <number>`).option(`--branch <branch>`).option(`--resume-created`).option(`--investigation-worktree <path>`,`Prospectively register an already linked host-created investigation`).option(`--expected-head <sha>`,`Exact unchanged initial commit for investigation registration`).action(async e=>{if(e.investigationWorktree!==void 0||e.expectedHead!==void 0){if(Object.keys(e).some(e=>![`issue`,`investigationWorktree`,`expectedHead`].includes(e)))throw Error(`Investigation registration cannot create or change issue/branch metadata.`);return _N(`issue_start`,{issueNumber:fN(e.issue),investigationWorktree:e.investigationWorktree,expectedHeadSha:e.expectedHead})}return _N(`issue_start`,{issueNumber:fN(e.issue),request:e.request,requestId:e.requestId,title:e.title,body:hN(e.body,e.bodyFile),issueType:e.type,points:fN(e.points),priority:e.priority,labels:pN(e.labels),blockedBy:mN(e.blockedBy),blocks:mN(e.blocks),overrideReason:e.overrideReason,milestone:fN(e.milestone),parentIssueNumber:fN(e.parent),branch:e.branch,resumeCreated:e.resumeCreated===!0})});for(let e of[`list`,`search`])uN.command(e).option(`--query <text>`,`Literal text to search in the selected repository`).option(`--state <state>`).option(`--labels <labels>`).option(`--parent <number>`).option(`--type <type>`).option(`--project-status <status>`).option(`--updated-since <timestamp>`).option(`--page <number>`).option(`--per-page <number>`).action(async t=>_N(e===`list`?`issue_list`:`issue_search`,{query:t.query,state:t.state,labels:pN(t.labels),parentIssueNumber:fN(t.parent),issueType:t.type,projectStatus:t.projectStatus,updatedSince:t.updatedSince,page:fN(t.page),perPage:fN(t.perPage)}));uN.command(`update`).requiredOption(`--issue <number>`).option(`--fields-file <path>`,`UTF-8 JSON typed issue field patch`).option(`--draft`,`Explicitly write an incomplete parked draft`).option(`--title <title>`).option(`--body <markdown>`).option(`--body-file <path>`).option(`--type <type>`).option(`--points <number>`).option(`--priority <priority>`).option(`--labels <labels>`).option(`--blocked-by <numbers>`).option(`--blocks <numbers>`,`Add this issue as a blocker of these dependents`).option(`--override-reason <reason>`,`Required explanation when adding a blocker to active work`).option(`--milestone <number>`).option(`--parent <number>`).option(`--state <state>`).option(`--preserve-history`,`Preserve the previous title and body before a rewrite`).option(`--close-reason <reason>`).option(`--superseded-by <number>`).option(`--park`,`Park execution while retaining the issue worktree`).action(async e=>_N(`issue_update`,gN(e.fieldsFile,{issueNumber:fN(e.issue),title:e.title,...e.draft===!0?{draft:!0}:{},body:hN(e.body,e.bodyFile),issueType:e.type,points:fN(e.points),priority:e.priority,labels:pN(e.labels),blockedBy:mN(e.blockedBy),blocks:mN(e.blocks),overrideReason:e.overrideReason,milestone:fN(e.milestone),parentIssueNumber:fN(e.parent),state:e.state,preserveHistory:e.preserveHistory===!0||void 0,closeReason:e.closeReason,supersededBy:fN(e.supersededBy),park:e.park===!0||void 0}))),uN.command(`health`).requiredOption(`--from <utc>`,`Inclusive UTC ISO timestamp`).requiredOption(`--to <utc>`,`Exclusive UTC ISO timestamp`).option(`--max-issues <number>`).option(`--max-timeline-pages <number>`).option(`--max-project-pages <number>`).option(`--oldest-limit <number>`).action(async e=>_N(`delivery_health`,{repo:dN().repo,from:e.from,to:e.to,maxIssues:fN(e.maxIssues),maxTimelinePages:fN(e.maxTimelinePages),maxProjectPages:fN(e.maxProjectPages),oldestLimit:fN(e.oldestLimit)})),uN.command(`info`).requiredOption(`--issue <number>`).action(async e=>_N(`issue_info`,{issueNumber:fN(e.issue)})),uN.command(`ready:check`).requiredOption(`--issue <number>`).action(async e=>_N(`issue_ready_check`,{issueNumber:fN(e.issue)}));for(let e of[`parent`,`blockers`])uN.command(e).requiredOption(`--issue <number>`).action(async t=>{let n=await JC(`issue_info`,{issueNumber:fN(t.issue)},dN());vN(e===`parent`?{issueNumber:fN(t.issue),parentIssueNumber:n.parentIssueNumber}:{issueNumber:fN(t.issue),blockedBy:n.blockedBy})});uN.command(`subissues`).requiredOption(`--issue <number>`).action(async e=>{let t=await KC(dN(),`subissues`);vN({issueNumber:fN(e.issue),subissues:await jv(t,Number(e.issue))})}),uN.command(`pr:create`).description(`Create a PR from a linked issue branch, or promote an existing associated PR with --head and --ready.`).requiredOption(`--issue <number>`).option(`--pr <number>`,`Exact existing PR selector; never creates a replacement`).option(`--non-closing`,`Retain the issue OPEN using native non-closing reference proof`).option(`--title <title>`).option(`--body-file <path>`).option(`--head <branch>`,`Explicit remote head; existing PR promotion verifies its native issue association`).option(`--ready`,`Publish ready, or promote the author-owned PR selected by --head`).option(`--dry-run`).action(async e=>_N(`issue_pr_create`,{issueNumber:fN(e.issue),prNumber:fN(e.pr),nonClosing:e.nonClosing,title:e.title,body:hN(void 0,e.bodyFile),headBranch:e.head,draft:e.ready!==!0,dryRun:e.dryRun===!0})),uN.command(`pr:info`).description(`Inspect an exact PR; combine --issue and --pr to verify its native closing-issue association.`).option(`--non-closing`,`Verify an exact native non-closing PR-to-issue reference`).option(`--issue <number>`,`Issue to verify; issue-only lookup requires a GitHub-linked branch`).option(`--pr <number>`,`Exact PR number; include --issue after issue branch links are replaced on publication`).action(async e=>_N(`issue_pr_info`,{issueNumber:fN(e.issue),prNumber:fN(e.pr),nonClosing:e.nonClosing})),uN.command(`pr:list`).option(`--state <state>`,`open, closed or all`,`open`).action(async e=>{if(![`open`,`closed`,`all`].includes(e.state))throw Error(`Invalid PR state.`);vN(await WS(await KC(dN(),`pr:list`),e.state))}),uN.command(`pr:checks`).requiredOption(`--pr <number>`).action(async e=>{vN(await GS(await KC(dN(),`pr:checks`),Number(e.pr)))}),uN.command(`pr:review`).requiredOption(`--issue <number>`).requiredOption(`--pr <number>`).requiredOption(`--artifact <path>`,`Path to a UTF-8 JSON review artifact file (not inline JSON)`).option(`--non-closing`,`Retain the referenced issue OPEN; finish refuses this mode`).option(`--dry-run`).action(async e=>_N(`issue_pr_review`,{issueNumber:fN(e.issue),prNumber:fN(e.pr),artifact:d(e.artifact,`utf8`),dryRun:e.dryRun===!0,nonClosing:e.nonClosing}));for(let[e,t]of[[`pr:merge`,`issue_pr_merge`],[`finish`,`issue_finish`]]){let n=uN.command(e).requiredOption(`--issue <number>`);e===`pr:merge`?n.requiredOption(`--pr <number>`):n.option(`--pr <number>`),n.option(`--strategy <method>`).option(`--reviewed-head <sha>`).option(`--non-closing`,`Retain the referenced issue OPEN; finish refuses this mode`).option(`--dry-run`),e===`finish`&&n.option(`--investigation`,`Complete an unchanged prospectively registered investigation`).option(`--result <path>`,`Durable independently reviewed result outside the removable worktree`).option(`--authority-comment <number>`,`Exact native operator removal authority comment`).option(`--acceptance-comment <number>`,`Exact configured-App result acceptance comment`),n.action(async e=>{if(e.investigation===!0){if(e.pr!==void 0||e.strategy!==void 0||e.reviewedHead!==void 0||e.nonClosing!==void 0)throw Error(`Investigation completion cannot accept PR or merge options.`);return _N(t,{issueNumber:fN(e.issue),investigation:!0,resultPath:e.result,authorityCommentId:fN(e.authorityComment),acceptanceCommentId:fN(e.acceptanceComment),dryRun:e.dryRun===!0})}if(e.result!==void 0||e.authorityComment!==void 0||e.acceptanceComment!==void 0)throw Error(`Investigation evidence requires --investigation.`);return _N(t,{issueNumber:fN(e.issue),prNumber:fN(e.pr),strategy:e.strategy,reviewedHeadSha:e.reviewedHead,dryRun:e.dryRun===!0,nonClosing:e.nonClosing})})}uN.command(`worktree:transition:inspect`).requiredOption(`--issue <number>`).requiredOption(`--purpose <purpose>`,`active-resume or merged-cleanup`).option(`--disposition <disposition>`,`retain (default) or explicitly unheld remove`).option(`--terminal-pr <number>`).option(`--retained-holds <comment-ids>`,`Comma-separated native retained-hold comment IDs`).option(`--retained-admission <path>`).option(`--retained-archive <path>`).action(async e=>_N(`issue_worktree_transition_inspect`,{issueNumber:fN(e.issue),purpose:e.purpose,...e.disposition===void 0?{}:{disposition:e.disposition},...e.terminalPr===void 0?{}:{terminalPrNumber:fN(e.terminalPr)},...e.retainedHolds===void 0?{}:{retainedHoldCommentIds:mN(e.retainedHolds)},...e.retainedAdmission===void 0?{}:{retainedAdmissionPath:e.retainedAdmission},...e.retainedArchive===void 0?{}:{retainedArchivePath:e.retainedArchive}})),uN.command(`worktree:transition:apply`).requiredOption(`--plan <path>`).requiredOption(`--plan-id <digest>`).requiredOption(`--relinquishment-comment <id>`).requiredOption(`--acceptance-comment <id>`).option(`--authorize-transition`,`Explicit authority for this exact independently accepted plan`).action(async e=>_N(`issue_worktree_transition_apply`,{authority:e.authorizeTransition===!0?`worktree:transition`:``,planPath:e.plan,expectedPlanId:e.planId,relinquishmentCommentId:Number(e.relinquishmentComment),acceptanceCommentId:Number(e.acceptanceComment)})),uN.command(`migrate:legacy-issues`).requiredOption(`--input-file <path>`,`Offline legacy issue inventory JSON`).action(e=>{let t=Yj(JSON.parse(d(e.inputFile,`utf8`)));process.stdout.write(`${JSON.stringify(t,null,2)}\n`)}),uN.command(`config:resolve`).description(`Read the effective GitHub destination and admission digest`).action(async()=>{let e=await KC(dN(),`config:resolve`);vN({configDigest:e.configuration?.configDigest,routing:e.configuration?.routing,reviewRoute:await JS(e,void 0,void 0,`development`)})}),uN.command(`mcp:serve`).action(async()=>Gj(dN())),uN.parseAsync(process.argv).catch(e=>{process.stderr.write(`ai-delivery: ${e instanceof Error?e.message:String(e)}\n`),process.exitCode=1});export{};
|