@tzurp/openapi-skills 1.3.0 → 1.5.0
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/LICENSE +2 -1
- package/README.md +20 -0
- package/dist/cli.min.js +24 -24
- package/package.json +1 -1
- package/skill-templates/SKILL.md +28 -9
- package/skill-templates/evals/evals.json +23 -0
package/LICENSE
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
Copyright 2026 Tzur Paldi, Bedekbyte™
|
|
1
2
|
Apache License
|
|
2
3
|
Version 2.0, January 2004
|
|
3
4
|
http://www.apache.org/licenses/
|
|
@@ -186,7 +187,7 @@
|
|
|
186
187
|
same "printed page" as the copyright notice for easier
|
|
187
188
|
identification within third-party archives.
|
|
188
189
|
|
|
189
|
-
Copyright
|
|
190
|
+
Copyright 2026 Tzur Paldi, Bedekbyte™
|
|
190
191
|
|
|
191
192
|
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
193
|
you may not use this file except in compliance with the License.
|
package/README.md
CHANGED
|
@@ -6,6 +6,15 @@ Looking for the Pro version? → https://github.com/tzurp/openapi-skills-pro
|
|
|
6
6
|
|
|
7
7
|
`openapi-skills` is an OpenAPI CLI and GraphQL CLI for exploring APIs, generating artifacts, validating schemas, and preparing live API requests. Its optional AI agent skills enable Copilot, Claude, Cursor, and other agents to use the CLI through natural language.
|
|
8
8
|
|
|
9
|
+
<p align="center">
|
|
10
|
+
<a href="https://github.com/tzurp/openapi-skills-cli">
|
|
11
|
+
<img
|
|
12
|
+
src="https://img.shields.io/badge/⭐%20STAR%20THIS%20PROJECT%20⭐-black?style=for-the-badge&logo=github&logoColor=white"
|
|
13
|
+
height="90"
|
|
14
|
+
/>
|
|
15
|
+
</a>
|
|
16
|
+
</p>
|
|
17
|
+
|
|
9
18
|

|
|
10
19
|

|
|
11
20
|
<p align="center">
|
|
@@ -54,6 +63,7 @@ Here’s a concise comparison to help you understand where each version shines:
|
|
|
54
63
|
| **Validate schemas** | ✔ Built‑in validation | ✔ Deep validation + version comparison |
|
|
55
64
|
| **Prepare & execute live API requests** | ✔ Postman‑like request builder | ✔ Same, plus mock‑server integration |
|
|
56
65
|
| **AI agent workflows** | ✔ Optional skill bundle for LLM agents | ✔ Enhanced Skills (OpenAPI annotation generation) |
|
|
66
|
+
| **Cookie jar** | ✔ Cookie jar support | ✔ Automatically merge cookies into requests |
|
|
57
67
|
| **Mock server** | — | ✔ Local mock server from schema artifacts |
|
|
58
68
|
| **HTML API documentation** | — | ✔ Generate interactive HTML docs |
|
|
59
69
|
| **Compare API responses with response schemas** | — | ✔ Validate API responses against their OpenAPI response schemas |
|
|
@@ -72,6 +82,7 @@ Enable the optional Skill bundle, and AI agents (Copilot, Claude, Cursor, etc.)
|
|
|
72
82
|
- Explore operations by method, path, tag, or keyword
|
|
73
83
|
- Describe endpoints with full request/response details
|
|
74
84
|
- Prepare and execute live API requests (Postman‑like, no code needed)
|
|
85
|
+
- Cookie jar support for managing cookies across requests
|
|
75
86
|
- Parse OpenAPI 2.0/3.0.x and GraphQL schemas
|
|
76
87
|
- Generate artifacts (`endpoints.json`, `schemas/`)
|
|
77
88
|
- Work with multiple API schemas simultaneously (stored under: .openapi-skills/<apiName>/ directory)
|
|
@@ -113,6 +124,11 @@ This creates:
|
|
|
113
124
|
schemas/
|
|
114
125
|
```
|
|
115
126
|
|
|
127
|
+
For single-API commands such as `list`, `request`, `get-env`, and `set-env`,
|
|
128
|
+
`--api` may be omitted when exactly one API is installed. If no API is
|
|
129
|
+
available, generate one first. If multiple APIs are installed, the CLI lists
|
|
130
|
+
their names and asks you to pass `--api <apiName>`.
|
|
131
|
+
|
|
116
132
|
### Explore the API manually
|
|
117
133
|
|
|
118
134
|
```bash
|
|
@@ -131,6 +147,10 @@ Use `--force-request` to reset only the request artifact from the cached operati
|
|
|
131
147
|
|
|
132
148
|
`--omit-empty` removes empty-string values from optional fields using the operation schema; required fields and other values are preserved.
|
|
133
149
|
|
|
150
|
+
### Cookie handling
|
|
151
|
+
|
|
152
|
+
Cookies received from responses are saved per API, but are not automatically attached to later requests. Retrieve an applicable `Cookie` header with `openapi-skills get-env --api <apiName> --cookie-for <operationId>` and pass it with `request --header`. Use `openapi-skills set-env --api <apiName> --clear-cookies` to clear the saved cookies.
|
|
153
|
+
|
|
134
154
|
---
|
|
135
155
|
|
|
136
156
|
## ⚡ One‑line agent command
|
package/dist/cli.min.js
CHANGED
|
@@ -1,31 +1,31 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var fn=Object.defineProperty;var S=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var mn=(e,t)=>{for(var r in t)fn(e,r,{get:t[r],enumerable:!0})};function se(e){return e.normalize("NFKD").replace(/[\\/]/g,"_").split("_").map(s=>s===""?"_":(s=s.replace(/\./g,"_"),s=s.replace(/[^a-zA-Z0-9_-]/g,"_"),s=s.replace(/^_+|_+$/g,""),s||"_")).join("_")}var mt=S(()=>{"use strict"});import Pe from"fs-extra";import gn from"os";import Ie from"path";import{createRequire as zt}from"module";import{pathToFileURL as hn}from"url";import{buildSchema as yn,isEnumType as Kt,isInputObjectType as wn,isListType as Yt,isNonNullType as Xt,isObjectType as bn,isScalarType as Zt,valueFromAST as An}from"graphql";function er(e){if(!(e instanceof Error))return[String(e)];let t=[e.message],r=e.cause;return r instanceof Error?t.push(...er(r)):r!=null&&t.push(String(r)),t}function xn(e){return!/typescript/i.test(e)||!/(?:Cannot find (?:package|module)|ERR_MODULE_NOT_FOUND|MODULE_NOT_FOUND)/i.test(e)?!1:/['"]typescript(?:\/(?:unstable\/)?(?:ast|sync))?['"]/i.test(e)||/Cannot find typescript(?:\/(?:unstable\/)?(?:ast|sync))?/i.test(e)}function tr(e){return er(e).some(t=>/TypeScript is required to analyze builder GraphQL schemas/i.test(t)||xn(t))}function rr(e){let t=[zt(import.meta.url),zt(Ie.join(process.cwd(),"package.json"))];for(let r of t)try{return hn(r.resolve(e)).href}catch{}throw new Error(`Cannot find ${e}`)}async function En(){let e;for(let t of Tn)try{let r=await Sn(t);if(typeof r.isCallExpression=="function")return r;e=new Error(`TypeScript module '${t}' does not export the AST API.`)}catch(r){e=r;try{let n=await import(rr(t));if(typeof n.isCallExpression=="function")return n;e=new Error(`TypeScript module '${t}' does not export the AST API.`)}catch(n){e=n}}throw e??new Error("TypeScript is required to analyze builder GraphQL schemas.")}async function Sn(e){return await import(e)}async function Pn(){let e;for(let t of kn)try{let r=await In(t);if(typeof r.API=="function")return r.API;let n=Ht(r);if(n)return n;e=new Error(`TypeScript module '${t}' does not export API.`)}catch(r){e=r;try{let n=await import(rr(t));if(typeof n.API=="function")return n.API;let s=Ht(n);if(s)return s;e=new Error(`TypeScript module '${t}' does not export API.`)}catch(n){e=n}}throw e??new Error("TypeScript is required to analyze builder GraphQL schemas.")}function Ht(e){return typeof e.createSourceFile!="function"||!e.ScriptTarget||!e.ScriptKind?null:class{updateSnapshot(r){let n=r.openFiles[0],s=Pe.readFileSync(n,"utf8"),i=e.createSourceFile(n,s,e.ScriptTarget.Latest,!0,e.ScriptKind.TS);return{getDefaultProjectForFile:()=>({program:{getSourceFile:()=>i}}),dispose:()=>{}}}close(){}}}async function In(e){return await import(e)}async function nr(){if(ge&&Me)return ge;try{ge=await En(),Me=await Pn()}catch(e){throw new Error("TypeScript is required to analyze builder GraphQL schemas.",{cause:e})}return ge}function J(){if(!ge)throw new Error("TypeScript has not been loaded.");return ge}async function Rn(e,t){await nr();let r=Ie.extname(t??"").toLowerCase(),n=`graphql-source${r===".tsx"||r===".jsx"?r:".ts"}`,s=await Pe.mkdtemp(Ie.join(gn.tmpdir(),"openapi-skills-graphql-")),i=Ie.join(s,n);if(await Pe.writeFile(i,e,"utf8"),!Me)throw new Error("TypeScript API has not been loaded.");let o=new Me,a=o.updateSnapshot({openFiles:[i]});try{let c=a.getDefaultProjectForFile(i)?.program.getSourceFile(i);if(!c)throw new Error("TypeScript could not parse the GraphQL builder source.");return c}finally{a.dispose(),o.close(),await Pe.remove(s)}}function On(e,t){return t&&[".ts",".tsx",".mts",".cts"].includes(Ie.extname(t).toLowerCase())?!0:[/\bbuilder\.queryType\s*\(/,/\bbuilder\.mutationType\s*\(/,/\bbuilder\.subscriptionType\s*\(/,/\bobjectType\s*\(/,/\bnew\s+SchemaBuilder\s*\(/].some(r=>r.test(e))}async function He(e){if(/^https?:\/\//i.test(e)){let t=await fetch(e);if(!t.ok)throw new Error(`Failed to load GraphQL source from ${e}: HTTP ${t.status}`);return await t.text()}return await Pe.readFile(e,"utf8")}function We(e){return[/\btype\s+Query\b/i,/\btype\s+Mutation\b/i,/\btype\s+Subscription\b/i,/\bschema\s*\{/i,/\bextend\s+type\s+Query\b/i,/\bbuilder\.(queryType|mutationType|subscriptionType)\s*\(/i,/\btoSchema\s*\(/i].some(t=>t.test(e))}function gt(e){let t=J();if(e&&(t.isStringLiteral(e)||t.isNoSubstitutionTemplateLiteral(e)))return e.text}function qn(e,t){let r=J();if(e)return e.properties.find(n=>r.isPropertyAssignment(n)||r.isShorthandPropertyAssignment(n)?(r.isIdentifier(n.name)||r.isStringLiteral(n.name)||r.isNumericLiteral(n.name)?n.name.text:n.name.getText())===t:!1)}function C(e,t){let r=J(),n=qn(e,t);if(!(!n||!r.isPropertyAssignment(n)))return n.initializer}function he(e){let t=J(),r=e;for(;r&&t.isParenthesizedExpression(r);)r=r.expression;return r}function G(e){let t=J(),r=he(e);if(r){if(t.isObjectLiteralExpression(r))return r;if(t.isArrowFunction(r)||t.isFunctionExpression(r)){if(t.isBlock(r.body)){for(let n of r.body.statements)if(t.isReturnStatement(n)&&n.expression){let s=G(n.expression);if(s)return s}return}return G(r.body)}}}function vn(e){let t=J(),r=e.expression;if(!t.isPropertyAccessExpression(r))return;let n=r.name.text;if(n==="queryType")return"query";if(n==="mutationType")return"mutation";if(n==="subscriptionType")return"subscription"}function Wt(e,t){let r=J(),n=he(e);if(n)return r.isStringLiteral(n)||r.isNoSubstitutionTemplateLiteral(n)?n.text:r.isIdentifier(n)?t.objectTypeNames[n.text]??n.text:n.getText()}function Nn(e,t){let r=J(),n=he(e);if(n){if(r.isCallExpression(n)){let s=n.expression.getText();if(/\.exposeID$/i.test(s))return"ID";if(/\.exposeString$/i.test(s))return"String";if(/\.exposeInt$/i.test(s))return"Int";if(/\.exposeFloat$/i.test(s))return"Float";if(/\.exposeBoolean$/i.test(s))return"Boolean";if(/\.string$/i.test(s))return"String";if(/\.int$/i.test(s))return"Int";if(/\.float$/i.test(s))return"Float";if(/\.boolean$/i.test(s))return"Boolean";if(/\.id$/i.test(s))return"ID";if(/\.stringList$/i.test(s))return"[String]";if(/\.intList$/i.test(s))return"[Int]";if(/\.floatList$/i.test(s))return"[Float]";if(/\.booleanList$/i.test(s))return"[Boolean]";if(/\.idList$/i.test(s))return"[ID]";let i=n.arguments[0];if(i&&r.isObjectLiteralExpression(i)){let o=C(i,"type");if(o){let a=Wt(o,t);if(a)return a}}}return Wt(n,t)}}function jn(e){let t=J(),r={},n={};function s(i){if(t.isVariableDeclaration(i)&&i.initializer&&t.isCallExpression(i.initializer)&&t.isPropertyAccessExpression(i.initializer.expression)&&i.initializer.expression.name.text==="objectRef"){let o=i.initializer.arguments[0],a=i.name.getText(e);o&&t.isStringLiteral(o)&&(r[a]=o.text)}if(t.isCallExpression(i)&&t.isPropertyAccessExpression(i.expression)&&i.expression.name.text==="objectType"&&i.arguments.length>1){let o=i.arguments[0],a=G(i.arguments[1]),p=C(a,"name")?gt(C(a,"name")):o&&t.isIdentifier(o)?r[o.text]??o.text:o&&t.isStringLiteral(o)?o.text:void 0;if(p&&a){let c=C(a,"fields"),u=G(c);if(u){let m={};for(let f of u.properties){if(!t.isPropertyAssignment(f))continue;let l=t.isIdentifier(f.name)||t.isStringLiteral(f.name)||t.isNumericLiteral(f.name)?f.name.text:f.name.getText(e),g=Nn(f.initializer,{objectTypeNames:r,objectFields:n});g&&(m[l]=g)}n[p]=m}}}i.forEachChild(s)}return s(e),{objectTypeNames:r,objectFields:n}}function Ue(e,t,r=new Set){let n=e.trim();if(!n)return{kind:"unknown",typeName:"Unknown"};if(n.endsWith("!"))return{kind:"non-null",typeName:n,required:!0,ofType:Ue(n.slice(0,-1),t,r)};if(n.startsWith("[")&&n.endsWith("]"))return{kind:"list",typeName:n,ofType:Ue(n.slice(1,-1).trim(),t,r)};if(wt.has(n))return{kind:"scalar",typeName:n};let s=t.objectTypeNames[n]??n;if(r.has(s))return{kind:"object",typeName:s,circular:s,fields:{}};let i=t.objectFields[s];if(!i)return{kind:"object",typeName:s};let o=new Set(r);o.add(s);let a={};for(let[p,c]of Object.entries(i))a[p]=Ue(c,t,o);return{kind:"object",typeName:s,fields:a}}function Ke(e){let t=e.trim();for(;t.endsWith("!");)t=t.slice(0,-1).trim();return t.startsWith("[")&&t.endsWith("]")&&(t=t.slice(1,-1).trim()),t}function _n(e,t){let r=Ke(e);return wt.has(r)?"scalar":t&&/input|filter|where|args?/i.test(r)||t?"input-object":"object"}function Ve(e,t){let r=e.trim();if(!r)return{kind:"unknown",typeName:"Unknown"};if(r.endsWith("!"))return{kind:"non-null",typeName:r,required:!0,ofType:Ve(r.slice(0,-1),t)};if(r.startsWith("[")&&r.endsWith("]")){let s=r.slice(1,-1).trim();return{kind:"list",typeName:r,ofType:Ve(s,t)}}return{kind:_n(r,t),typeName:r}}function ze(e){let t=J(),r=he(e);if(r){if(t.isStringLiteral(r)||t.isNoSubstitutionTemplateLiteral(r))return r.text;if(t.isNumericLiteral(r))return Number(r.text);if(r.kind===t.SyntaxKind.TrueKeyword)return!0;if(r.kind===t.SyntaxKind.FalseKeyword)return!1;if(r.kind===t.SyntaxKind.NullKeyword)return null;if(t.isArrayLiteralExpression(r))return r.elements.map(n=>ze(n));if(t.isObjectLiteralExpression(r)){let n={};for(let s of r.properties)if(t.isPropertyAssignment(s)){let i=t.isIdentifier(s.name)||t.isStringLiteral(s.name)||t.isNumericLiteral(s.name)?s.name.text:s.name.getText();n[i]=ze(s.initializer)}return n}t.isIdentifier(r)&&r.text}}function Ln(e){let t=J(),r=he(e);if(!r)return{kind:"unknown",typeName:"Unknown"};if(t.isCallExpression(r)){let n=r.expression.getText(),s=r.arguments[0];if(s&&t.isObjectLiteralExpression(s)){let i=C(s,"type"),o=C(s,"required"),a=C(s,"defaultValue"),p;if(i?p=Ve(i.getText(),!0):/\.string$/i.test(n)?p={kind:"scalar",typeName:"String"}:/\.int$/i.test(n)?p={kind:"scalar",typeName:"Int"}:/\.float$/i.test(n)?p={kind:"scalar",typeName:"Float"}:/\.boolean$/i.test(n)?p={kind:"scalar",typeName:"Boolean"}:/\.id$/i.test(n)&&(p={kind:"scalar",typeName:"ID"}),p)return p.defaultValue=ze(a),o&&ze(o)===!0?{kind:"non-null",typeName:`${p.typeName}!`,required:!0,ofType:p}:p}if(/\.string$/i.test(n))return{kind:"scalar",typeName:"String"};if(/\.int$/i.test(n))return{kind:"scalar",typeName:"Int"};if(/\.float$/i.test(n))return{kind:"scalar",typeName:"Float"};if(/\.boolean$/i.test(n))return{kind:"scalar",typeName:"Boolean"};if(/\.id$/i.test(n))return{kind:"scalar",typeName:"ID"}}return Ve(r.getText(),!0)}function Cn(e){let t=Ke(e);return t==="Boolean"?!1:t==="Int"||t==="Float"?0:t==="ID"||t==="String"?"":null}function ht(e){if(e.kind==="non-null"&&e.ofType)return ht(e.ofType);if(e.kind==="list")return[];if(e.kind==="scalar")return Cn(e.typeName);if(e.kind==="enum")return e.enumValues?.[0]??null;if(e.kind==="input-object"){let t={};for(let[r,n]of Object.entries(e.fields??{}))t[r]=ht(n);return t}return null}function yt(e){return e.kind==="non-null"&&e.ofType?`${yt(e.ofType)}!`:e.kind==="list"&&e.ofType?`[${yt(e.ofType)}]`:e.typeName}function $n(e){let t=Ke(e.typeName);return e.kind==="scalar"||e.kind==="enum"||wt.has(t)}function Ge(e,t=new Set){if(e.kind==="non-null"&&e.ofType||e.kind==="list"&&e.ofType)return Ge(e.ofType,t);if($n(e))return"";let r=Ke(e.typeName);if(t.has(r))return"__typename";if(e.kind==="object"||e.kind==="input-object"){let n=new Set(t);n.add(r);let s=Object.entries(e.fields??{});return s.length===0?"{ __typename }":`{ ${s.map(([o,a])=>{let p=Ge(a,n);if(!p)return o;if(a.kind==="object"||a.kind==="input-object"||a.kind==="list"||a.kind==="non-null"){let c=p.startsWith("{")?p:`{ ${p} }`;return`${o} ${c}`}return`${o} ${p}`}).join(" ")} }`}return"__typename"}function Dn(e){let t=Object.keys(e.args),r=t.map(u=>{let m=e.args[u];return`$${u}: ${m?yt(m):"String"}`}),n={};for(let[u,m]of Object.entries(e.args))n[u]=ht(m);let s=t.map(u=>`${u}: $${u}`).join(", "),i=Ge(e.returns),o=i?` ${i}`:"",a=se(e.operationId)||e.operationId,p=r.length>0?`(${r.join(", ")})`:"",c=s.length>0?`(${s})`:"";return{query:`${e.rootType} ${a}${p} { ${e.name}${c}${o} }`,variables:n}}function Fn(e){let t=yn(e),r=[["query",t.getQueryType()],["mutation",t.getMutationType()],["subscription",t.getSubscriptionType()]],n=[];for(let[s,i]of r)if(i)for(let o of Object.values(i.getFields())){let a={};for(let u of o.args){let m=Be(u.type),f=sr(u);f!==void 0&&(m.defaultValue=f),a[u.name]=m}let p={name:o.name,operationId:o.name,sanitizedOperationId:se(o.name),rootType:s,args:a,returns:Qe(o.type)},c=o.description?.split(`
|
|
3
|
-
`).map(u=>u.trim()).filter(Boolean)[0];c&&(p.summary=c),o.description&&(p.description=o.description),n.push(p)}return n}function
|
|
4
|
-
`:e)}function
|
|
5
|
-
`)},progress(e){
|
|
6
|
-
`)}}});import{promises as
|
|
2
|
+
var $n=Object.defineProperty;var I=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var Dn=(e,t)=>{for(var r in t)$n(e,r,{get:t[r],enumerable:!0})};function ce(e){return e.normalize("NFKD").replace(/[\\/]/g,"_").split("_").map(s=>s===""?"_":(s=s.replace(/\./g,"_"),s=s.replace(/[^a-zA-Z0-9_-]/g,"_"),s=s.replace(/^_+|_+$/g,""),s||"_")).join("_")}var xt=I(()=>{"use strict"});import Ne from"fs-extra";import Fn from"os";import Ce from"path";import{createRequire as sr}from"module";import{pathToFileURL as Jn}from"url";import{buildSchema as Un,isEnumType as ar,isInputObjectType as Gn,isListType as pr,isNonNullType as cr,isObjectType as Qn,isScalarType as ur,valueFromAST as Bn}from"graphql";function dr(e){if(!(e instanceof Error))return[String(e)];let t=[e.message],r=e.cause;return r instanceof Error?t.push(...dr(r)):r!=null&&t.push(String(r)),t}function Hn(e){return!/typescript/i.test(e)||!/(?:Cannot find (?:package|module)|ERR_MODULE_NOT_FOUND|MODULE_NOT_FOUND)/i.test(e)?!1:/['"]typescript(?:\/(?:unstable\/)?(?:ast|sync))?['"]/i.test(e)||/Cannot find typescript(?:\/(?:unstable\/)?(?:ast|sync))?/i.test(e)}function lr(e){return dr(e).some(t=>/TypeScript is required to analyze builder GraphQL schemas/i.test(t)||Hn(t))}function fr(e){let t=[sr(import.meta.url),sr(Ce.join(process.cwd(),"package.json"))];for(let r of t)try{return Jn(r.resolve(e)).href}catch{}throw new Error(`Cannot find ${e}`)}async function zn(){let e;for(let t of Mn)try{let r=await Wn(t);if(typeof r.isCallExpression=="function")return r;e=new Error(`TypeScript module '${t}' does not export the AST API.`)}catch(r){e=r;try{let n=await import(fr(t));if(typeof n.isCallExpression=="function")return n;e=new Error(`TypeScript module '${t}' does not export the AST API.`)}catch(n){e=n}}throw e??new Error("TypeScript is required to analyze builder GraphQL schemas.")}async function Wn(e){return await import(e)}async function Kn(){let e;for(let t of Vn)try{let r=await Xn(t);if(typeof r.API=="function")return r.API;let n=ir(r);if(n)return n;e=new Error(`TypeScript module '${t}' does not export API.`)}catch(r){e=r;try{let n=await import(fr(t));if(typeof n.API=="function")return n.API;let s=ir(n);if(s)return s;e=new Error(`TypeScript module '${t}' does not export API.`)}catch(n){e=n}}throw e??new Error("TypeScript is required to analyze builder GraphQL schemas.")}function ir(e){return typeof e.createSourceFile!="function"||!e.ScriptTarget||!e.ScriptKind?null:class{updateSnapshot(r){let n=r.openFiles[0],s=Ne.readFileSync(n,"utf8"),i=e.createSourceFile(n,s,e.ScriptTarget.Latest,!0,e.ScriptKind.TS);return{getDefaultProjectForFile:()=>({program:{getSourceFile:()=>i}}),dispose:()=>{}}}close(){}}}async function Xn(e){return await import(e)}async function mr(){if(be&&Xe)return be;try{be=await zn(),Xe=await Kn()}catch(e){throw new Error("TypeScript is required to analyze builder GraphQL schemas.",{cause:e})}return be}function G(){if(!be)throw new Error("TypeScript has not been loaded.");return be}async function Yn(e,t){await mr();let r=Ce.extname(t??"").toLowerCase(),n=`graphql-source${r===".tsx"||r===".jsx"?r:".ts"}`,s=await Ne.mkdtemp(Ce.join(Fn.tmpdir(),"openapi-skills-graphql-")),i=Ce.join(s,n);if(await Ne.writeFile(i,e,"utf8"),!Xe)throw new Error("TypeScript API has not been loaded.");let o=new Xe,a=o.updateSnapshot({openFiles:[i]});try{let c=a.getDefaultProjectForFile(i)?.program.getSourceFile(i);if(!c)throw new Error("TypeScript could not parse the GraphQL builder source.");return c}finally{a.dispose(),o.close(),await Ne.remove(s)}}function Zn(e,t){return t&&[".ts",".tsx",".mts",".cts"].includes(Ce.extname(t).toLowerCase())?!0:[/\bbuilder\.queryType\s*\(/,/\bbuilder\.mutationType\s*\(/,/\bbuilder\.subscriptionType\s*\(/,/\bobjectType\s*\(/,/\bnew\s+SchemaBuilder\s*\(/].some(r=>r.test(e))}async function et(e){if(/^https?:\/\//i.test(e)){let t=await fetch(e);if(!t.ok)throw new Error(`Failed to load GraphQL source from ${e}: HTTP ${t.status}`);return await t.text()}return await Ne.readFile(e,"utf8")}function tt(e){return[/\btype\s+Query\b/i,/\btype\s+Mutation\b/i,/\btype\s+Subscription\b/i,/\bschema\s*\{/i,/\bextend\s+type\s+Query\b/i,/\bbuilder\.(queryType|mutationType|subscriptionType)\s*\(/i,/\btoSchema\s*\(/i].some(t=>t.test(e))}function Et(e){let t=G();if(e&&(t.isStringLiteral(e)||t.isNoSubstitutionTemplateLiteral(e)))return e.text}function es(e,t){let r=G();if(e)return e.properties.find(n=>r.isPropertyAssignment(n)||r.isShorthandPropertyAssignment(n)?(r.isIdentifier(n.name)||r.isStringLiteral(n.name)||r.isNumericLiteral(n.name)?n.name.text:n.name.getText())===t:!1)}function J(e,t){let r=G(),n=es(e,t);if(!(!n||!r.isPropertyAssignment(n)))return n.initializer}function ke(e){let t=G(),r=e;for(;r&&t.isParenthesizedExpression(r);)r=r.expression;return r}function V(e){let t=G(),r=ke(e);if(r){if(t.isObjectLiteralExpression(r))return r;if(t.isArrowFunction(r)||t.isFunctionExpression(r)){if(t.isBlock(r.body)){for(let n of r.body.statements)if(t.isReturnStatement(n)&&n.expression){let s=V(n.expression);if(s)return s}return}return V(r.body)}}}function ts(e){let t=G(),r=e.expression;if(!t.isPropertyAccessExpression(r))return;let n=r.name.text;if(n==="queryType")return"query";if(n==="mutationType")return"mutation";if(n==="subscriptionType")return"subscription"}function or(e,t){let r=G(),n=ke(e);if(n)return r.isStringLiteral(n)||r.isNoSubstitutionTemplateLiteral(n)?n.text:r.isIdentifier(n)?t.objectTypeNames[n.text]??n.text:n.getText()}function rs(e,t){let r=G(),n=ke(e);if(n){if(r.isCallExpression(n)){let s=n.expression.getText();if(/\.exposeID$/i.test(s))return"ID";if(/\.exposeString$/i.test(s))return"String";if(/\.exposeInt$/i.test(s))return"Int";if(/\.exposeFloat$/i.test(s))return"Float";if(/\.exposeBoolean$/i.test(s))return"Boolean";if(/\.string$/i.test(s))return"String";if(/\.int$/i.test(s))return"Int";if(/\.float$/i.test(s))return"Float";if(/\.boolean$/i.test(s))return"Boolean";if(/\.id$/i.test(s))return"ID";if(/\.stringList$/i.test(s))return"[String]";if(/\.intList$/i.test(s))return"[Int]";if(/\.floatList$/i.test(s))return"[Float]";if(/\.booleanList$/i.test(s))return"[Boolean]";if(/\.idList$/i.test(s))return"[ID]";let i=n.arguments[0];if(i&&r.isObjectLiteralExpression(i)){let o=J(i,"type");if(o){let a=or(o,t);if(a)return a}}}return or(n,t)}}function ns(e){let t=G(),r={},n={};function s(i){if(t.isVariableDeclaration(i)&&i.initializer&&t.isCallExpression(i.initializer)&&t.isPropertyAccessExpression(i.initializer.expression)&&i.initializer.expression.name.text==="objectRef"){let o=i.initializer.arguments[0],a=i.name.getText(e);o&&t.isStringLiteral(o)&&(r[a]=o.text)}if(t.isCallExpression(i)&&t.isPropertyAccessExpression(i.expression)&&i.expression.name.text==="objectType"&&i.arguments.length>1){let o=i.arguments[0],a=V(i.arguments[1]),p=J(a,"name")?Et(J(a,"name")):o&&t.isIdentifier(o)?r[o.text]??o.text:o&&t.isStringLiteral(o)?o.text:void 0;if(p&&a){let c=J(a,"fields"),u=V(c);if(u){let m={};for(let f of u.properties){if(!t.isPropertyAssignment(f))continue;let g=t.isIdentifier(f.name)||t.isStringLiteral(f.name)||t.isNumericLiteral(f.name)?f.name.text:f.name.getText(e),l=rs(f.initializer,{objectTypeNames:r,objectFields:n});l&&(m[g]=l)}n[p]=m}}}i.forEachChild(s)}return s(e),{objectTypeNames:r,objectFields:n}}function He(e,t,r=new Set){let n=e.trim();if(!n)return{kind:"unknown",typeName:"Unknown"};if(n.endsWith("!"))return{kind:"non-null",typeName:n,required:!0,ofType:He(n.slice(0,-1),t,r)};if(n.startsWith("[")&&n.endsWith("]"))return{kind:"list",typeName:n,ofType:He(n.slice(1,-1).trim(),t,r)};if(It.has(n))return{kind:"scalar",typeName:n};let s=t.objectTypeNames[n]??n;if(r.has(s))return{kind:"object",typeName:s,circular:s,fields:{}};let i=t.objectFields[s];if(!i)return{kind:"object",typeName:s};let o=new Set(r);o.add(s);let a={};for(let[p,c]of Object.entries(i))a[p]=He(c,t,o);return{kind:"object",typeName:s,fields:a}}function rt(e){let t=e.trim();for(;t.endsWith("!");)t=t.slice(0,-1).trim();return t.startsWith("[")&&t.endsWith("]")&&(t=t.slice(1,-1).trim()),t}function ss(e,t){let r=rt(e);return It.has(r)?"scalar":t&&/input|filter|where|args?/i.test(r)||t?"input-object":"object"}function Ye(e,t){let r=e.trim();if(!r)return{kind:"unknown",typeName:"Unknown"};if(r.endsWith("!"))return{kind:"non-null",typeName:r,required:!0,ofType:Ye(r.slice(0,-1),t)};if(r.startsWith("[")&&r.endsWith("]")){let s=r.slice(1,-1).trim();return{kind:"list",typeName:r,ofType:Ye(s,t)}}return{kind:ss(r,t),typeName:r}}function Ze(e){let t=G(),r=ke(e);if(r){if(t.isStringLiteral(r)||t.isNoSubstitutionTemplateLiteral(r))return r.text;if(t.isNumericLiteral(r))return Number(r.text);if(r.kind===t.SyntaxKind.TrueKeyword)return!0;if(r.kind===t.SyntaxKind.FalseKeyword)return!1;if(r.kind===t.SyntaxKind.NullKeyword)return null;if(t.isArrayLiteralExpression(r))return r.elements.map(n=>Ze(n));if(t.isObjectLiteralExpression(r)){let n={};for(let s of r.properties)if(t.isPropertyAssignment(s)){let i=t.isIdentifier(s.name)||t.isStringLiteral(s.name)||t.isNumericLiteral(s.name)?s.name.text:s.name.getText();n[i]=Ze(s.initializer)}return n}t.isIdentifier(r)&&r.text}}function is(e){let t=G(),r=ke(e);if(!r)return{kind:"unknown",typeName:"Unknown"};if(t.isCallExpression(r)){let n=r.expression.getText(),s=r.arguments[0];if(s&&t.isObjectLiteralExpression(s)){let i=J(s,"type"),o=J(s,"required"),a=J(s,"defaultValue"),p;if(i?p=Ye(i.getText(),!0):/\.string$/i.test(n)?p={kind:"scalar",typeName:"String"}:/\.int$/i.test(n)?p={kind:"scalar",typeName:"Int"}:/\.float$/i.test(n)?p={kind:"scalar",typeName:"Float"}:/\.boolean$/i.test(n)?p={kind:"scalar",typeName:"Boolean"}:/\.id$/i.test(n)&&(p={kind:"scalar",typeName:"ID"}),p)return p.defaultValue=Ze(a),o&&Ze(o)===!0?{kind:"non-null",typeName:`${p.typeName}!`,required:!0,ofType:p}:p}if(/\.string$/i.test(n))return{kind:"scalar",typeName:"String"};if(/\.int$/i.test(n))return{kind:"scalar",typeName:"Int"};if(/\.float$/i.test(n))return{kind:"scalar",typeName:"Float"};if(/\.boolean$/i.test(n))return{kind:"scalar",typeName:"Boolean"};if(/\.id$/i.test(n))return{kind:"scalar",typeName:"ID"}}return Ye(r.getText(),!0)}function os(e){let t=rt(e);return t==="Boolean"?!1:t==="Int"||t==="Float"?0:t==="ID"||t==="String"?"":null}function St(e){if(e.kind==="non-null"&&e.ofType)return St(e.ofType);if(e.kind==="list")return[];if(e.kind==="scalar")return os(e.typeName);if(e.kind==="enum")return e.enumValues?.[0]??null;if(e.kind==="input-object"){let t={};for(let[r,n]of Object.entries(e.fields??{}))t[r]=St(n);return t}return null}function Rt(e){return e.kind==="non-null"&&e.ofType?`${Rt(e.ofType)}!`:e.kind==="list"&&e.ofType?`[${Rt(e.ofType)}]`:e.typeName}function as(e){let t=rt(e.typeName);return e.kind==="scalar"||e.kind==="enum"||It.has(t)}function ze(e,t=new Set){if(e.kind==="non-null"&&e.ofType||e.kind==="list"&&e.ofType)return ze(e.ofType,t);if(as(e))return"";let r=rt(e.typeName);if(t.has(r))return"__typename";if(e.kind==="object"||e.kind==="input-object"){let n=new Set(t);n.add(r);let s=Object.entries(e.fields??{});return s.length===0?"{ __typename }":`{ ${s.map(([o,a])=>{let p=ze(a,n);if(!p)return o;if(a.kind==="object"||a.kind==="input-object"||a.kind==="list"||a.kind==="non-null"){let c=p.startsWith("{")?p:`{ ${p} }`;return`${o} ${c}`}return`${o} ${p}`}).join(" ")} }`}return"__typename"}function ps(e){let t=Object.keys(e.args),r=t.map(u=>{let m=e.args[u];return`$${u}: ${m?Rt(m):"String"}`}),n={};for(let[u,m]of Object.entries(e.args))n[u]=St(m);let s=t.map(u=>`${u}: $${u}`).join(", "),i=ze(e.returns),o=i?` ${i}`:"",a=ce(e.operationId)||e.operationId,p=r.length>0?`(${r.join(", ")})`:"",c=s.length>0?`(${s})`:"";return{query:`${e.rootType} ${a}${p} { ${e.name}${c}${o} }`,variables:n}}function cs(e){let t=Un(e),r=[["query",t.getQueryType()],["mutation",t.getMutationType()],["subscription",t.getSubscriptionType()]],n=[];for(let[s,i]of r)if(i)for(let o of Object.values(i.getFields())){let a={};for(let u of o.args){let m=We(u.type),f=gr(u);f!==void 0&&(m.defaultValue=f),a[u.name]=m}let p={name:o.name,operationId:o.name,sanitizedOperationId:ce(o.name),rootType:s,args:a,returns:Ke(o.type)},c=o.description?.split(`
|
|
3
|
+
`).map(u=>u.trim()).filter(Boolean)[0];c&&(p.summary=c),o.description&&(p.description=o.description),n.push(p)}return n}function gr(e){if(e.defaultValue!==void 0)return e.defaultValue;let t=e.astNode?.defaultValue;return t?Bn(t,e.type):void 0}function We(e,t=new Set){if(cr(e))return{kind:"non-null",typeName:e.toString(),required:!0,ofType:We(e.ofType,t)};if(pr(e))return{kind:"list",typeName:e.toString(),ofType:We(e.ofType,t)};if(ur(e))return{kind:"scalar",typeName:e.name};if(ar(e))return{kind:"enum",typeName:e.name,enumValues:e.getValues().map(r=>r.name)};if(Gn(e)){if(t.has(e.name))return{kind:"input-object",typeName:e.name,circular:e.name,fields:{}};let r=new Set(t);r.add(e.name);let n={};for(let[s,i]of Object.entries(e.getFields())){let o=We(i.type,r),a=gr(i);a!==void 0&&(o.defaultValue=a),n[s]=o}return{kind:"input-object",typeName:e.name,fields:n}}return{kind:"unknown",typeName:String(e)}}function Ke(e,t=new Set){if(cr(e))return{kind:"non-null",typeName:e.toString(),required:!0,ofType:Ke(e.ofType,t)};if(pr(e))return{kind:"list",typeName:e.toString(),ofType:Ke(e.ofType,t)};if(ur(e))return{kind:"scalar",typeName:e.name};if(ar(e))return{kind:"enum",typeName:e.name,enumValues:e.getValues().map(r=>r.name)};if(Qn(e)){if(t.has(e.name))return{kind:"object",typeName:e.name,circular:e.name,fields:{}};let r=new Set(t);r.add(e.name);let n={};for(let[s,i]of Object.entries(e.getFields()))n[s]=Ke(i.type,r);return{kind:"object",typeName:e.name,fields:n}}return{kind:"unknown",typeName:e.toString()}}async function us(e,t){let r=await mr(),n=await Yn(e,t),s=ns(n),i=[];function o(a){if(r.isCallExpression(a)&&r.isPropertyAccessExpression(a.expression)){let p=ts(a);if(p&&a.arguments.length>0){let c=V(a.arguments[0]),u=J(c,"fields"),m=V(u);if(m)for(let f of m.properties){if(!r.isPropertyAssignment(f))continue;let g=r.isIdentifier(f.name)||r.isStringLiteral(f.name)||r.isNumericLiteral(f.name)?f.name.text:f.name.getText(n),l=V(f.initializer)??V(f.initializer),b=ke(f.initializer),y=b&&r.isCallExpression(b)?b:void 0,h=y?V(y.arguments[0]):l,w=J(h,"type"),T=Et(J(h,"summary")),R=Et(J(h,"description")),A=J(h,"args"),E=V(A),_={};if(E)for(let S of E.properties){if(!r.isPropertyAssignment(S))continue;let te=r.isIdentifier(S.name)||r.isStringLiteral(S.name)||r.isNumericLiteral(S.name)?S.name.text:S.name.getText(n);_[te]=is(S.initializer)}let L={name:g,operationId:g,sanitizedOperationId:ce(g),rootType:p,args:_,returns:w?He(w.getText(n),s):{kind:"unknown",typeName:"Unknown"}};T&&(L.summary=T),R&&(L.description=R),i.push(L)}}}a.forEachChild(o)}return o(n),i}async function nt(e,t){return Zn(e,t)?await us(e,t):cs(e)}async function Ae(e,t,r,n){let i=(await nt(e,n)).find(o=>o.rootType===t&&o.name===r);if(!i)throw new Error(`GraphQL field '${r}' not found on root type '${t}'.`);return i}function _e(e){return ps(e)}var It,Pt,Mn,Vn,be,Xe,Le=I(()=>{"use strict";xt();It=new Set(["String","Int","Float","Boolean","ID"]),Pt="npm install typescript",Mn=["typescript/ast","typescript","typescript/unstable/ast"],Vn=["typescript/sync","typescript","typescript/unstable/sync"],be=null,Xe=null});function Te(e,t){process.stderr.write(t?`${e}
|
|
4
|
+
`:e)}function H(e){return e instanceof Error?e.message:String(e)}var X,d,xe=I(()=>{"use strict";X=process.stderr.isTTY&&process.stdout.isTTY;d={info(e){Te(e,!0)},warn(e){let t="\u26A0\uFE0F ";if(X){let r=`\x1B[33m${t}${e}\x1B[0m`;Te(r,!0)}else Te(t+e,!0)},banner(e){Te(X?`\x1B[35m${e}\x1B[0m`:e,!0)},error(e){process.stderr.write(`\u274C ${e}
|
|
5
|
+
`)},progress(e){X&&Te(e,!1)},progressLine(e){X&&Te(e,!0)},result(e){process.stdout.write(`${JSON.stringify(e)}
|
|
6
|
+
`)}}});import{promises as st}from"fs";import hr from"path";import it from"fs-extra";async function at(e){try{return await it.readJSON(e,"utf8")}catch(t){if(t.code==="ENOENT")return{};throw t}}function ds(e,t,r){let n=t.split("."),s=e;for(let i=0;i<n.length;i++){let o=n[i]??"",a=i===n.length-1,p=typeof o=="string"&&/^[0-9]+$/.test(o),c=p?Number(o):void 0;if(a)p&&Array.isArray(s)&&c!==void 0?s[c]=r:s[o]=r;else if(p&&c!==void 0){if(!Array.isArray(s)&&i>0){let u=n[i-1]??"";s[u]=[],s=s[u]}s[c]||(s[c]={}),s=s[c]}else(!(o in s)||typeof s[o]!="object"||s[o]===null)&&(s[o]={}),s=s[o]}}function ls(e,t){let r=t.split(".");if(r.length===0)return!1;let n=e;for(let o=0;o<r.length-1;o++){let a=r[o]??"",c=/^[0-9]+$/.test(a)&&Array.isArray(n)?n[Number(a)]:n&&typeof n=="object"?n[a]:void 0;if(c==null)return!1;n=c}let s=r[r.length-1]??"",i=/^[0-9]+$/.test(s);if(Array.isArray(n)&&i){let o=Number(s);return o<0||o>=n.length?!1:(n.splice(o,1),!0)}return n&&typeof n=="object"&&Object.prototype.hasOwnProperty.call(n,s)?(delete n[s],!0):!1}function fs(e,t){return e===t||e.startsWith(`${t}.`)}function ms(e,t){let r=e.split("."),n=t.split(".");if(r.length!==n.length)return n.length-r.length;let s=r[r.length-1]??"",i=n[n.length-1]??"",o=r.slice(0,-1).join("."),a=n.slice(0,-1).join(".");return o===a&&/^[0-9]+$/.test(s)&&/^[0-9]+$/.test(i)?Number(i)-Number(s):t.localeCompare(e)}async function $e(e,t,r=2,n={}){let s={};try{let h=await st.readFile(e,"utf8");s=JSON.parse(h)}catch(h){if(h.code!=="ENOENT")throw h}let i=JSON.parse(JSON.stringify(s)),o=n.deleteSentinel,a=o===void 0?[]:Object.entries(t).filter(([,h])=>h===o).map(([h])=>h).sort(ms);for(let h of a)ls(i,h);for(let[h,w]of Object.entries(t))o!==void 0&&w===o||a.some(T=>fs(h,T))||ds(i,h,w);if(n.transform?.(i),!(JSON.stringify(s)!==JSON.stringify(i)))return{changed:!1,before:s,after:i};let c=hr.resolve(e),u=hr.dirname(c),m=Math.random().toString(36).slice(2,10),f=`${c}.tmp.${process.pid}.${m}`,g,l=new Set(["EPERM","EACCES","EBUSY"]);async function b(h){await new Promise(w=>setTimeout(w,h))}async function y(h,w){for(let R=1;R<=5;R++)try{await st.rename(h,w);return}catch(A){if(!l.has(A?.code)||R===5)throw A;await b(25*R)}}try{await st.mkdir(u,{recursive:!0}),g=await st.open(f,"w"),await g.writeFile(JSON.stringify(i,null,r),"utf8"),await g.sync(),await g.close(),await y(f,c);try{let h=it.openSync(u,"r");it.fsyncSync(h),it.closeSync(h)}catch{}return{changed:!0,before:s,after:i}}catch(h){if(g)try{await g.close()}catch{}throw(h.code==="EPERM"||h.code==="EACCES"||h.code==="EBUSY")&&d.error(`Failed to atomically update JSON file due to a file lock or permission error.
|
|
7
7
|
Please close any programs that may have the file open and try again.
|
|
8
|
-
The temporary file with your changes is: ${f}`),h}}var et,At=S(()=>{"use strict";be();et="__delete__"});import B from"path";import Mn from"find-root";function ae(e,t){let r=v(e);return B.join(r,`${t}.json`)}function oe(e){return B.resolve(ie,".openapi-skills",e,"bundled.json")}function Tt(e){return B.resolve(ie,".openapi-skills",e,"components.json")}function pe(e,t){let r=v(e);return B.resolve(r,t)}function v(e){return B.resolve(ie,".openapi-skills",e,"schemas")}function ve(e){return B.resolve(ie,".openapi-skills",e)}function or(){return B.resolve(ie,".openapi-skills","config.json")}function L(e){return B.resolve(ie,".openapi-skills",e,"endpoints.json")}function tt(e,t,r){let n=pe(e,t),s=r==="response-schema"?"response-schema.json":`${r}.json`;return B.join(n,s)}function rt(){return B.resolve(ie,".openapi-skills")}function nt(){let e=process.cwd();try{return Mn(e)}catch{return e}}var ie,K=S(()=>{"use strict";ie=nt()});import{readFile as Vn}from"fs/promises";import zn from"path";import ce from"fs-extra";async function U(){return await ce.readJSON(Ae)}async function kt(){if(await ce.ensureDir(Hn),!await ce.pathExists(Ae)){let e={apis:{}};await ce.writeJson(Ae,e,{spaces:2})}}function pr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}async function Te(e,t={}){if(typeof e!="string"||e.trim().length===0)throw new Error("API name is required.");let{baseUrl:r,auth:n,vars:s,version:i,openapiSource:o,schemaType:a,removeApi:p}=t,c={};if(p){if(!await ce.pathExists(Ae))throw new Error("Config file not found.");let u=await U();if(!pr(u)||!pr(u.apis))throw new Error("Invalid config file.");if(!(e in u.apis))throw new Error(`API '${e}' not found`);delete u.apis[e],await ce.writeJson(Ae,u,{spaces:2});return}if(await kt(),n!==void 0&&(c[`apis.${e}.auth.headers`]=n),s!==void 0)for(let[u,m]of Object.entries(s))c[`apis.${e}.vars.${u}`]=m;if(i!==void 0&&(c[`apis.${e}.version`]=i),o!==void 0){let u=o;try{new URL(o)}catch{u=zn.normalize(o)}c[`apis.${e}.openapiSource`]=u}r!==void 0&&(c[`apis.${e}.baseUrl`]=r),a!==void 0&&(c[`apis.${e}.schemaType`]=a),Object.keys(c).length!==0&&await qe(Ae,c,2)}function Wn(e){let t=e instanceof Error?e.message:String(e);return/config/i.test(t)?{type:"ConfigError",message:t}:/permission|EACCES|EPERM/i.test(t)?{type:"DirectoryDeletionError",message:t}:{type:"DeleteApiError",message:t}}async function cr(e){if(typeof e!="string"||e.trim().length===0)return{ok:!1,error:{type:"InvalidApiName",message:"API name is required."}};try{if(!(await ue()).includes(e))return{ok:!1,error:{type:"ApiNotFound",message:`API '${e}' is not installed.`}};await Te(e,{removeApi:!0});let r=ve(e);return await ce.remove(r),{ok:!0,message:`API ${e} removed successfully`,data:{removedApi:e}}}catch(t){return{ok:!1,error:Wn(t)}}}async function st(e,t){let n=(await U()).apis[e];if(!n)throw new Error(`API '${e}' not found`);switch(t){case"version":return n.version??"unknown";case"baseUrl":return n.baseUrl;case"authHeaders":return n.auth?.headers??{};case"vars":return Object.entries(n.vars??{})}}async function ur(e){try{let t=await Vn(L(e),"utf-8");return JSON.parse(t)}catch(t){throw t instanceof SyntaxError?new Error(`Failed to parse endpoints.json: Invalid JSON format. ${t.message}`):new Error(`Failed to read endpoints.json: ${t instanceof Error?t.message:String(t)}`)}}async function ue(){let e=await U();return Object.keys(e.apis)||[]}var Hn,Ae,de=S(()=>{"use strict";At();K();Hn=rt(),Ae=or()});import xt from"@apidevtools/swagger-parser";import Kn from"@apidevtools/json-schema-ref-parser";import I from"fs-extra";import Y from"path";function dr(e){let t;try{let r=new URL(e);t=Y.basename(r.pathname,Y.extname(r.pathname))}catch{t=Y.basename(e,Y.extname(e))}return se(t||"api")}function Yn(e){if(e instanceof Error)return/circular/i.test(e.message)||/circular/i.test(e.name);if(typeof e=="object"&&e!==null){let t=String(e.message??""),r=String(e.name??"");return/circular/i.test(t)||/circular/i.test(r)}return!1}function Et(e,t=new WeakSet){if(e&&typeof e=="object"){if(t.has(e))return;if(t.add(e),Array.isArray(e)){let n=e.map(s=>Et(s,t));return t.delete(e),n}let r={};for(let[n,s]of Object.entries(e)){let i=Et(s,t);i!==void 0&&(r[n]=i)}return t.delete(e),r}return e}async function Xn(e){let t=oe(e),r=await I.readJson(t),n=typeof r?.source=="string"?r.source:typeof r?.sourceText=="string"?r.sourceText:void 0;if(!n)throw new Error(`GraphQL source not found for API '${e}'. Run generate first.`);return n}async function Zn(e,t,r,n=!1){let s=ae(e,r);if(!n&&await I.pathExists(s))return I.readJson(s);let i=await I.readJson(L(e)),o=Array.isArray(i)?i.find(u=>u.operationId===t||u.name===t||u.sanitizedOperationId===r):void 0;if(!o)throw new Error(`Endpoint '${t}' not found in GraphQL endpoint list.`);let a=typeof o.rootType=="string"?o.rootType:typeof o.method=="string"?o.method:void 0;if(!a||a!=="query"&&a!=="mutation"&&a!=="subscription")throw new Error(`Invalid GraphQL endpoint metadata for '${t}'.`);let p=await Xn(e),c=await ye(p,a,t);return await I.ensureDir(Y.dirname(s)),await I.writeJson(s,c,{spaces:2}),c}function es(e,t){for(let[r,n]of Object.entries(e))for(let[s,i]of Object.entries(n))if(i&&typeof i=="object"&&"operationId"in i){let o=i;if(o.operationId===t)return{pathKey:r,method:s,operation:o}}}async function ts(e,t){let r=typeof e.operationId=="string"?e.operationId:"unknown-operation",n=typeof e.method=="string"?e.method.toUpperCase():"GET",s=typeof e.path=="string"?e.path:"unknown-path",i=H;i&&d.progressLine(`Dereferencing endpoint ${r} (${n} ${s})...`);let o={openapi:"3.0.0",paths:{"/temp":{get:e}},definitions:t,components:t},a=await Kn.dereference(o,{mutateInputSchema:!1,dereference:{circular:"ignore"}}),p=Et(a),c=p.paths,u=c&&typeof c=="object"?c["/temp"]:void 0,m=u&&typeof u=="object"?u.get:void 0;return m&&typeof m=="object"?(i&&d.progressLine(`Endpoint ${r} (${n} ${s}) dereference complete.`),m):(i&&d.progressLine(`Endpoint ${r} (${n} ${s}) dereference complete.`),p)}async function Q(e,t,r,n=!1){let s=ae(e,r);if(!n&&await I.pathExists(s))return I.readJson(s);let i=oe(e),o=Tt(e),a=await I.readJson(i);if(a&&typeof a=="object"&&a.schemaType==="graphql")return await Zn(e,t,r,n);if(!a||typeof a!="object"||!("paths"in a))throw new Error(`Bundled OpenAPI document not found for API '${e}'. Run generate first.`);let p={},c=a.components,u=a.definitions;c&&typeof c=="object"&&!Array.isArray(c)?p=c:u&&typeof u=="object"&&!Array.isArray(u)?p=u:await I.pathExists(o)&&(p=await I.readJson(o));let m=es(a.paths,t);if(!m)throw new Error(`Endpoint '${t}' not found in bundled OpenAPI document.`);let f={operationId:t,method:m.method,path:m.pathKey,...m.operation},l=await ts(f,p);return await I.ensureDir(Y.dirname(s)),await I.writeJson(s,l,{spaces:2}),l}async function rs(e,t){if(!t)return xt.bundle(e);try{return await xt.dereference(e,{dereference:{circular:!1}})}catch(r){throw Yn(r)?new Error("The --dereference flag cannot be used because this OpenAPI spec contains circular references. Try running without --dereference."):r}}function ns(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("Invalid OpenAPI schema: expected a document object.");let t=e;if(t.swagger!==void 0&&t.openapi!==void 0)throw new Error("Invalid OpenAPI schema: both 'swagger' and 'openapi' version fields are present.");if(t.swagger!==void 0){if(t.swagger==="2.0")return"2";throw new Error(`Unsupported Swagger version '${String(t.swagger)}'. This CLI supports Swagger 2.0 and OpenAPI 3.0.x.`)}if(t.openapi!==void 0){if(typeof t.openapi!="string")throw new Error("Invalid OpenAPI schema: 'openapi' version must be a string.");if(/^3\.0\.\d+$/.test(t.openapi))return"3";throw new Error(`Unsupported OpenAPI version '${t.openapi}'. This CLI supports OpenAPI 2.0 and 3.0.x; For OpenAPI 3.1.0 and later, please use openapi-skills Pro.`)}throw new Error("Invalid OpenAPI schema: missing version declaration ('swagger' or 'openapi'); cannot determine a supported version.")}async function ss(e,t,r={}){let n="",s="unknown",i,o=r.progress!==!1&&H;try{o&&d.progressLine(`Loading OpenAPI document from ${e}...`),i=await rs(e,r.dereference===!0),o&&d.progressLine("OpenAPI document load complete.")}catch(a){throw d.error(`Error during parsing OpenAPI schema: ${a instanceof Error?a.message:String(a)}`),a}if(typeof i!="object"||!i.paths)throw new Error("Invalid OpenAPI schema: Missing 'paths'");try{s=ns(i),n=r.rename||dr(e);let a=ve(n);await I.remove(a);let p=v(n);await I.ensureDir(p);let c=oe(n);if(await I.writeJson(c,i,{spaces:2}),!r.dereference){let g=Tt(n);await I.writeJson(g,i?.components??{},{spaces:2})}let u=[],m=0,f=0,l=r.progress!==!1&&H;for(let[g,b]of Object.entries(i.paths))for(let[T,h]of Object.entries(b))h&&typeof h=="object"&&"operationId"in h&&h.operationId&&(m+=1);for(let[g,b]of Object.entries(i.paths))for(let[T,h]of Object.entries(b))if(h&&typeof h=="object"&&"operationId"in h){let y=h;if(y.operationId){let A={operationId:y.operationId,sanitizedOperationId:se(y.operationId),method:T,path:g};if(Array.isArray(y.tags)){let P=y.tags.map(O=>typeof O=="string"?O.trim():"").filter(O=>O.length>0);P.length>0&&(A.tags=P)}y.summary!==void 0&&(A.summary=y.summary),y.description!==void 0&&(A.description=y.description),u.push(A),f+=1,l&&d.progress(`\rProcessed ${f}/${m}`)}}l&&m>0&&d.progressLine("");try{let g=Y.join(a,"endpoints.json");await I.writeJson(g,u,{spaces:2})}catch(g){throw d.error(`Error writing endpoints.json: ${g instanceof Error?g.message:String(g)}`),g}try{await Te(n,{baseUrl:t,openapiSource:e,schemaType:"openapi",version:s});let g=t?"with baseUrl":"without baseUrl";d.info(`Schema '${n}' added to config.json ${g} and openapiSource recorded.`)}catch(g){throw d.error(`Error updating config.json: ${g instanceof Error?g.message:String(g)}`),g}}catch(a){throw d.error(`Error during OpenAPI schema processing: ${a instanceof Error?a.message:String(a)}`),a}return n}async function is(e,t,r={},n){let s="",i=r.progress!==!1&&H,o=n??await He(e);if(!We(o))throw new Error("Invalid GraphQL schema: missing GraphQL schema markers or builder pattern.");i&&d.progressLine(`Loading GraphQL schema from ${e}...`),s=r.rename||dr(e);let a=ve(s);await I.remove(a);let p=v(s);await I.ensureDir(p);let c=await Ye(o,e);if(c.length===0)throw new Error("Invalid GraphQL schema: no query, mutation, or subscription fields were found.");let u=oe(s);await I.writeJson(u,{schemaType:"graphql",source:o},{spaces:2});let m=c.map(f=>({name:f.name,sanitizedOperationId:f.sanitizedOperationId,rootType:f.rootType,summary:f.summary,description:f.description}));for(let f of c){let l=ae(s,f.sanitizedOperationId);await I.ensureDir(Y.dirname(l)),await I.writeJson(l,f,{spaces:2})}await I.writeJson(Y.join(a,"endpoints.json"),m,{spaces:2});try{await Te(s,{baseUrl:t,openapiSource:e,schemaType:"graphql",version:"graphql"});let f=t?"with baseUrl":"without baseUrl";d.info(`Schema '${s}' added to config.json ${f} and GraphQL source recorded.`)}catch(f){throw d.error(`Error updating config.json: ${f instanceof Error?f.message:String(f)}`),f}return i&&d.progressLine("GraphQL schema load complete."),s}async function lr(e,t,r={}){let n=await He(e).catch(()=>{});return n&&We(n)?await is(e,t,r,n):await ss(e,t,r)}async function fr(e){try{let t=await He(e).catch(()=>{});if(t&&We(t)){await Ye(t,e);return}await xt.validate(e);return}catch(t){throw new Error(t instanceof Error?t.message:String(t))}}var ke=S(()=>{"use strict";Oe();de();K();be();mt()});function as(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function St(e){if(!(!e||typeof e!="object"))return as(e.schema)?e.schema:e}function mr(e){let t=St(e);switch(typeof t?.type=="string"?t.type:typeof e?.type=="string"?e.type:void 0){case"string":return"";case"number":case"integer":return 0;case"boolean":return!1;case"array":return[];case"object":return{};default:return null}}var Pt=S(()=>{"use strict"});import xe from"fs-extra";function it(e){return e.replace(/[^a-zA-Z0-9]+(.)/g,(t,r)=>r.toUpperCase()).replace(/^[a-z]/,t=>t.toUpperCase())}function Z(e,t,r){if(!(!e||typeof e!="object")){if(Array.isArray(e.enum)){let n=it(r);t[n]=e.enum}if(e.properties&&typeof e.properties=="object")for(let[n,s]of Object.entries(e.properties))Z(s,t,`${r}_${n}`);e.items&&Z(e.items,t,`${r}_item`),e.oneOf&&e.oneOf.forEach((n,s)=>Z(n,t,`${r}_oneOf_${s}`)),e.anyOf&&e.anyOf.forEach((n,s)=>Z(n,t,`${r}_anyOf_${s}`)),e.allOf&&e.allOf.forEach((n,s)=>Z(n,t,`${r}_allOf_${s}`))}}function ee(e){if(!(!e||typeof e!="object")){if(delete e.xml,e.properties&&typeof e.properties=="object")for(let t of Object.values(e.properties))ee(t);e.items&&ee(e.items),e.oneOf&&e.oneOf.forEach(ee),e.anyOf&&e.anyOf.forEach(ee),e.allOf&&e.allOf.forEach(ee)}}function gr(e){if(!e||typeof e!="object")return null;let r=Object.keys(e).filter(n=>/^\d{3}$/.test(n)).find(n=>n.startsWith("2"));return r?e[r]:null}function It(e){if(!e||typeof e!="object")return null;let t=Object.entries(e).find(([r])=>r.toLowerCase().includes("json"));return t?t[1]:null}function os(e){let t=gr(e);if(!t)return null;if(t.content){let r=It(t.content);return!r||!r.schema?null:r.schema}return t.schema??null}function ps(e){let t=gr(e);return t?t.schema??null:null}function cs(e){let t=Array.isArray(e?.parameters)?e.parameters:[],r=t.find(i=>i.in==="body");if(r?.schema)return r.schema;let n=t.filter(i=>i.in==="formData");if(n.length===0)return null;let s={type:"object",properties:{}};for(let i of n){let o={};i.schema&&typeof i.schema=="object"?Object.assign(o,i.schema):(typeof i.type=="string"&&(o.type=i.type),i.items&&(o.items=i.items),typeof i.format=="string"&&(o.format=i.format),Array.isArray(i.enum)&&(o.enum=i.enum),i.type==="file"&&(o.type="string",o.format="binary")),s.properties[i.name]=o}return s}function ds(e){let t={};if(!e||typeof e!="object")return t;for(let[r,n]of Object.entries(e)){if(!/^\d{3}$/.test(r)||r.startsWith("2"))continue;let s=n.content,i=s?It(s):null,o=i&&i.schema?i.schema:n.schema??us;t[r]=o}return t}function ls(e,t){let r={};for(let n of["path","query","header"])for(let[s,i]of Object.entries(e[n]||{}))r[s]={...i.schema,required:i.required??!1,description:i.description,in:n};return{typeName:`${it(t)}Params`,schema:r}}async function Ne(e,t,r,n=!1){let s=await U(),i=await xe.readJson(L(e)),o=Array.isArray(i)&&i.some(y=>typeof y?.rootType=="string");if(s.apis?.[e]?.schemaType==="graphql"||s.apis?.[e]?.schemaType!=="openapi"&&o){let y=i.find(E=>E.operationId===t||E.name===t);if(!y)throw new Error(`Endpoint with operationId '${t}' not found.`);let A=typeof y.rootType=="string"?y.rootType:typeof y.method=="string"?y.method:void 0;if(!A||A!=="query"&&A!=="mutation"&&A!=="subscription")throw new Error(`Invalid GraphQL endpoint metadata for '${t}'.`);let P=v(e)+`/${r}.json`,O;if(!n&&await xe.pathExists(P))O=await xe.readJson(P);else{let E=await xe.readJson(oe(e)),V=typeof E?.source=="string"?E.source:typeof E?.sourceText=="string"?E.sourceText:void 0;if(!V)throw new Error(`GraphQL source not found for API '${e}'. Run generate first.`);O=await ye(V,A,t),await xe.ensureDir(v(e)),await xe.writeJson(P,O,{spaces:2})}return{schemaType:"graphql",fieldName:y.name??t,rootType:A,args:Object.fromEntries(Object.entries(O.args??{}).map(([E,V])=>{let x=V;return[E,{type:x.typeName??"unknown",required:x.required===!0}]})),returnType:O.returns?.typeName??"unknown",query:Re(O).query}}let p=i.find(y=>y.operationId===t);if(!p)throw new Error(`Endpoint with operationId '${t}' not found.`);let c=await Q(e,t,r,n),u={path:{},query:{},header:{}};for(let y of c.parameters||[])(y.in==="path"||y.in==="query"||y.in==="header")&&(u[y.in][y.name]={description:y.description,required:y.required,schema:St(y)});let m=os(c.responses)??ps(c.responses),f={};m&&(ee(m),Z(m,f,`${t}_response`));let l=ls(u,t),g=ds(c.responses),b=null,T=c.requestBody;if(T&&T.content){let y=It(T.content);y&&y.schema&&(b=y.schema,ee(b),Z(b,f,`${t}_request`))}else b=cs(c),b&&(ee(b),Z(b,f,`${t}_request`));let h=it(t.replace(/^(get|post|put|delete|patch|head|options)/i,"")||t);return{schemaType:"rest",operationId:t,method:p.method,path:p.path,deprecated:p.deprecated??c.deprecated??!1,params:l,response:m?{typeName:h,schema:m}:null,requestBody:b?{typeName:`${it(t)}Request`,schema:b}:null,errors:g,enums:f}}var us,Rt=S(()=>{"use strict";K();ke();Pt();Oe();de();us={type:"object",properties:{message:{type:"string"},status:{type:"number"}}}});var je,hr=S(()=>{"use strict";je=class{constructor(t){this.baseUrl=t}baseUrl;async request(t,r,n={}){if(!/^https?:\/\//i.test(this.baseUrl))throw new Error(`Invalid baseUrl: "${this.baseUrl}". Must include http:// or https://`);let s=this.baseUrl.endsWith("/")?this.baseUrl:this.baseUrl+"/",i=new URL(r.replace(/^\//,""),s).toString(),o="body"in n&&n.body!==void 0&&t!=="GET"&&t!=="HEAD",a=new Headers(n.headers??{}),p=null;if(o){let f=n.body,l=typeof FormData<"u"&&f instanceof FormData,g=typeof Blob<"u"&&f instanceof Blob,b=f instanceof ArrayBuffer||ArrayBuffer.isView(f),T=typeof Buffer<"u"&&Buffer.isBuffer(f);l?(a.delete("Content-Type"),p=f):g||b||T||typeof f=="string"?p=f:(a.has("Content-Type")||a.set("Content-Type","application/json"),p=JSON.stringify(f))}let c=await fetch(i,{method:t,headers:a,body:p}),u=await c.text(),m={};if(u.trim().length>0)try{m=JSON.parse(u)}catch{m=u}return m!==null&&typeof m=="object"&&!Array.isArray(m)?{...m,status:c.status,statusText:c.statusText}:{body:m,status:c.status,statusText:c.statusText}}get(t,r){return this.request("GET",t,r)}head(t,r){return this.request("HEAD",t,r)}options(t,r){return this.request("OPTIONS",t,r)}post(t,r){return this.request("POST",t,r)}put(t,r){return this.request("PUT",t,r)}patch(t,r){return this.request("PATCH",t,r)}delete(t,r){return this.request("DELETE",t,r)}}});import fs from"fs-extra";function yr(e){return{orGroups:e.trim().toLowerCase().split("|").map(r=>r.trim()).filter(Boolean).map(r=>r.split(/\s+/).filter(Boolean))}}function ms(e,t){return t.orGroups.length===0?!0:t.orGroups.some(r=>r.every(n=>e.includes(n)))}function gs(e){return e.split("/").map(t=>t.trim().toLowerCase()).filter(Boolean).flatMap(t=>{if(t.startsWith("{")&&t.endsWith("}")){let r=t.slice(1,-1).trim();return r?[t,r]:[t]}return[t]})}function hs(e,t){return t?t===":param"?/\{[^/{}]+\}/.test(e):t.startsWith("/")?e.startsWith(t):gs(e).includes(t):!0}function ys(e,t){return yr(t).orGroups.some(n=>n.every(s=>hs(e,s)))}function ws(e){return e?(Array.isArray(e)?e:[e]).map(t=>t.trim()).filter(Boolean):[]}function bs(e,t){if(typeof t!="string"||t.trim().length===0||t.trim()===":")return e;let r=t.trim(),n=r.match(/^-?\d+$/),s=r.match(/^(-?\d*)?:(-?\d*)?$/),i,o;if(n)i=Number(r),o=i;else if(s){let f=s[1],l=s[2];i=f===void 0||f===""?0:Number(f),o=l===void 0||l===""?e.length-1:Number(l)}else throw new Error(`Invalid --index value: ${t}`);if(Number.isNaN(i)||Number.isNaN(o))throw new Error(`Invalid --index value: ${t}`);let a=f=>f<0?e.length+f:f,p=a(i),c=a(o);if(e.length===0)return[];let u=Math.max(0,p),m=Math.min(e.length-1,c);return u>m?[]:e.slice(u,m+1)}function wr(e,t){return bs(e,t)}function at(e,t){let r=e;if(t.operationId){let s=t.operationId.toLowerCase();r=r.filter(i=>(i.operationId||"").toLowerCase()===s)}if(t.method){let s=t.method.toLowerCase();r=r.filter(i=>(i.method||"").toLowerCase()===s)}if(t.rootType){let s=t.rootType.toLowerCase();r=r.filter(i=>(i.rootType||"").toLowerCase()===s)}if(t.tag){let s=t.tag.toLowerCase();r=r.filter(i=>(Array.isArray(i.tags)?i.tags:[]).some(a=>typeof a=="string"&&a.toLowerCase()===s))}let n=ws(t.path);if(n.length>0&&(r=r.filter(s=>{let i=(s.path||"").toString().toLowerCase();return n.every(o=>ys(i,o))})),t.filter){let s=yr(t.filter);r=r.filter(i=>{let o=[i.operationId,i.name,i.method,i.rootType,i.path,i.summary,i.description].map(a=>(a||"").toString().toLowerCase()).join(" ");return ms(o,s)})}return r}async function As(e){let t=v(e);try{let r=await fs.readdir(t,{withFileTypes:!0});return new Set(r.filter(n=>n.isFile()&&n.name.toLowerCase().endsWith(".json")).map(n=>n.name.slice(0,-5)))}catch(r){if(r?.code==="ENOENT")return new Set;throw r}}async function br(e,t){let r=await As(e);return r.size===0?[]:t.filter(n=>{let s=typeof n.sanitizedOperationId=="string"?n.sanitizedOperationId:"";return r.has(s)})}var Ot=S(()=>{"use strict";K()});async function X(e,t){let r={operationId:t},n=await ur(e),s=at(n,r)[0]??n.find(i=>i.name===t);return s?.sanitizedOperationId??s?.operationId??s?.name??""}var le,ot=S(()=>{"use strict";de();Ot();le=X});function Ts(e){return e.replace(/\[(\d+)\]/g,".$1").split(".").filter(r=>r.length>0).map(r=>/^\d+$/.test(r)?Number(r):r)}function _e(e,t){let r=e;for(let n of Ts(t)){if(r==null)return;if(typeof n=="number"){if(!Array.isArray(r)&&typeof r!="object")return;r=r[n];continue}if(typeof r!="object")return;r=r[n]}return r}function Ar(e,t,r){return Array.isArray(e)?e.filter(n=>String(_e(n,t))===String(r)):e}var qt=S(()=>{"use strict"});function N(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ks(e){let t=e.requestBody;if(N(t)&&N(t.content)){for(let a of Object.values(t.content))if(N(a)&&a.schema)return a.schema}let r=Array.isArray(e.parameters)?e.parameters:[],n=r.find(a=>N(a)&&a.in==="body");if(N(n)&&n.schema)return n.schema;let s=r.filter(a=>N(a)&&a.in==="formData");if(s.length===0)return;let i={},o=[];for(let a of s)!N(a)||typeof a.name!="string"||(i[a.name]=N(a.schema)?a.schema:Object.fromEntries(["type","items","format","enum"].filter(p=>a[p]!==void 0).map(p=>[p,a[p]])),a.required===!0&&o.push(a.name));return{type:"object",properties:i,...o.length>0?{required:o}:{}}}function xs(e){let t=[],r=new Set,n=!1,s=i=>{if(!N(i)){n=!0;return}if(r.has(i)){n=!0;return}if("$ref"in i||"oneOf"in i||"anyOf"in i||"not"in i){n=!0;return}if(r.add(i),t.push(i),Array.isArray(i.allOf))for(let o of i.allOf)s(o);r.delete(i)};for(let i of e)s(i);return{schemas:t,ambiguous:n}}function vt(e,t){let r=xs(t);if(r.ambiguous)return!1;let n=r.schemas;if(Array.isArray(e)){let a=n.map(p=>p.items).filter(p=>N(p));return a.length===0?!1:e.reduce((p,c)=>vt(c,a)||p,!1)}if(!N(e))return!1;let s=new Set(n.flatMap(a=>Array.isArray(a.required)?a.required.filter(p=>typeof p=="string"):[])),i=new Map;for(let a of n)if(N(a.properties))for(let[p,c]of Object.entries(a.properties)){let u=i.get(p)??[];u.push(c),i.set(p,u)}let o=!1;for(let[a,p]of Object.entries(e)){let c=i.get(a);if(c){if(p===""&&!s.has(a)){delete e[a],o=!0;continue}o=vt(p,c)||o}}return o}function kr(e,t){if(!N(e)||!N(t))return!1;let r=!1;if(Array.isArray(e.parameters)&&Array.isArray(t.parameters)){let s=t.parameters.filter(N),i=e.parameters.filter(o=>{if(!N(o)||o.value!==""||!["path","query","header"].includes(String(o.in)))return!0;let a=s.find(p=>p.name===o.name&&p.in===o.in);return!a||o.in==="path"||a.required===!0?!0:(r=!0,!1)});r&&(e.parameters=i)}let n=ks(t);return n&&"requestBody"in e&&(r=vt(e.requestBody,[n])||r),r}function Tr(e){let t=e;for(;t&&t.kind==="non-null"&&t.ofType;)t=t.ofType;return t}function Es(e){if(!e)return!1;let t=e;for(;t;){if(t.defaultValue!==void 0)return!1;t=t.ofType}return e.required===!0||e.kind==="non-null"||e.typeName.trim().endsWith("!")}function xr(e,t){if(Array.isArray(e)){let n=Tr(t);return n?.kind!=="list"||!n.ofType?!1:e.reduce((s,i)=>xr(i,n.ofType)||s,!1)}if(!N(e))return!1;let r=Tr(t);return r?.kind!=="input-object"||!r.fields?!1:Er(e,r.fields)}function Er(e,t){let r=!1;for(let[n,s]of Object.entries(e)){let i=t[n];if(i){if(s===""&&!Es(i)){delete e[n],r=!0;continue}r=xr(s,i)||r}}return r}function Sr(e,t){return!N(e)||!N(e.variables)?!1:Er(e.variables,t.args)}var Pr=S(()=>{"use strict"});import k from"fs-extra";import R from"path";import Ss from"ajv";import{fileURLToPath as Ps}from"url";function Le(e,t="",r={}){if(!e||typeof e!="object"||Array.isArray(e))return r;for(let[n,s]of Object.entries(e)){let i=t?`${t}.${n}`:n;s&&typeof s=="object"&&!Array.isArray(s)?Le(s,i,r):r[i]=s}return r}function vr(e,t=""){if(!e||typeof e!="object"||Array.isArray(e))return[];let r=[];for(let[n,s]of Object.entries(e)){let i=t?`${t}.${n}`:n;s&&typeof s=="object"&&!Array.isArray(s)&&(r.push(i),r.push(...vr(s,i)))}return Array.from(new Set(r))}function Is(e){let t=vr(e);if(t.length===0)return;let r=Le(e);return["Use only flattened object dot-notation keys with --force.",`Example: --force --update-request '${JSON.stringify(r)}'.`,`Detected nested keys: ${t.join(", ")}.`].join(" ")}function Ir(e){return e===null?"null":Nr(e)?"file":Array.isArray(e)?"array":typeof e}function Nr(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&e.kind==="file"}function Ct(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&typeof e.path=="string"&&(e.kind===void 0||e.kind==="file")}function Rs(e,t){return Nr(e)?typeof t=="string"||Ct(t):e===null?t===null:Array.isArray(e)?Array.isArray(t):typeof e=="object"?!!t&&typeof t=="object"&&!Array.isArray(t):typeof t==typeof e}function jr(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&typeof e.query=="string"&&typeof e.variables=="object"&&!Array.isArray(e.variables)}function _r(e){if(e)return e.split(",")[0]?.trim()||void 0}function Os(e){switch(R.extname(e).toLowerCase()){case".pdf":return"application/pdf";case".jpg":case".jpeg":return"image/jpeg";case".png":return"image/png";case".webp":return"image/webp";case".gif":return"image/gif";case".txt":return"text/plain";case".csv":return"text/csv";case".json":return"application/json";case".xml":return"application/xml";case".xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case".xls":return"application/vnd.ms-excel";case".docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case".zip":return"application/zip";default:return"application/octet-stream"}}function Rr(e){let t=e.trim();return t.startsWith("@")?R.resolve(t.slice(1)):t.startsWith("file://")?R.resolve(Ps(new URL(t))):R.resolve(t)}async function Nt(e,t){let r,n,s;if(typeof e=="string"){if(e.trim().length===0)throw new Error("File upload path cannot be empty.");r=Rr(e)}else if(Ct(e)){if(e.path.trim().length===0)throw new Error("File upload path cannot be empty.");r=Rr(e.path),n=e.fileName?.trim()||void 0,s=e.mimeType?.trim()||void 0}if(!r)throw new Error("File upload values must be a file path string or { kind: 'file', path, fileName?, mimeType? } object.");if(!await k.pathExists(r))throw new Error(`Upload file not found: ${r}`);let i=await k.readFile(r),o=n||R.basename(r),a=s||_r(t)||Os(r);return{buffer:i,path:r,fileName:o,mimeType:a}}function Or(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}function qs(e){let t=Object.entries(e),r=t.find(([o])=>o.toLowerCase().includes("multipart/form-data"));if(r)return{contentType:r[0],contentObject:r[1]};let n=t.find(([o,a])=>{let p=a?.schema;return o.toLowerCase().includes("octet-stream")||p?.type==="string"&&p?.format==="binary"});if(n)return{contentType:n[0],contentObject:n[1]};let s=t.find(([o])=>o.toLowerCase().includes("json"));if(s)return{contentType:s[0],contentObject:s[1]};let i=t[0];return i?{contentType:i[0],contentObject:i[1]}:void 0}function vs(e){let t=e?.requestBody,n=(Array.isArray(e?.parameters)?e.parameters:[]).filter(a=>a&&a.in==="formData"),i=(Array.isArray(e?.consumes)?e.consumes:[]).some(a=>typeof a=="string"&&a.toLowerCase().includes("multipart/form-data"));if(n.length>0&&i)return{kind:"multipart",schema:_t(e)??{type:"object",properties:{}},encoding:{}};if(!t||typeof t!="object")return n.length>0?{kind:"multipart",schema:_t(e)??{type:"object",properties:{}},encoding:{}}:{kind:"json"};let o=t.content;if(o&&typeof o=="object"&&!Array.isArray(o)){let a=qs(o);if(!a)return{kind:"json"};let p=a.contentObject,c=p?.schema;if(a.contentType.toLowerCase().includes("multipart/form-data"))return{kind:"multipart",schema:c&&typeof c=="object"?c:{type:"object",properties:{}},encoding:p?.encoding??{}};if(a.contentType.toLowerCase().includes("octet-stream")||c?.type==="string"&&c?.format==="binary")return{kind:"binary",contentType:a.contentType}}return{kind:"json"}}async function jt(e,t){let r=vs(e);if(r.kind==="multipart"){let o=t,a=!!o&&typeof o=="object"&&!Array.isArray(o)&&("requestBody"in o||"parameters"in o),p=a?o.requestBody:t,c=a&&Array.isArray(o?.parameters)?Object.fromEntries(o.parameters.filter(l=>!!l&&l.in==="formData"&&typeof l.name=="string").map(l=>[l.name,l.value])):{},u=p&&typeof p=="object"&&!Array.isArray(p)?p:c;if(!u||typeof u!="object"||Array.isArray(u))throw new Error("multipart/form-data request bodies must be JSON objects.");let m=new FormData,f=r.schema?.properties&&typeof r.schema.properties=="object"?r.schema.properties:{};for(let[l,g]of Object.entries(u)){let b=f[l],T=r.encoding[l],h=_r(T?.contentType);if(b?.type==="string"&&b?.format==="binary"){let y=await Nt(g,h);m.append(l,new Blob([Or(y.buffer)],{type:y.mimeType}),y.fileName);continue}if(Ct(g)){let y=await Nt(g,h);m.append(l,new Blob([Or(y.buffer)],{type:y.mimeType}),y.fileName);continue}g==null?m.append(l,""):typeof g=="object"?m.append(l,JSON.stringify(g)):m.append(l,String(g))}return{kind:"multipart",body:m,headers:{}}}if(r.kind==="binary"){let o=t,p=!!o&&typeof o=="object"&&!Array.isArray(o)&&"requestBody"in o?o.requestBody:t,c=await Nt(p,r.contentType);return{kind:"binary",body:c.buffer,headers:{"Content-Type":c.mimeType}}}let n=t;return{kind:"json",body:!!n&&typeof n=="object"&&!Array.isArray(n)&&"requestBody"in n?n.requestBody:t,headers:{}}}function Ns(e){let t={};for(let[r,n]of Object.entries(e)){let s=n.type.trim(),i=s.endsWith("!")?s.slice(0,-1).trim():s;i.startsWith("[")&&i.endsWith("]")?t[r]=[]:i==="Boolean"?t[r]=!1:i==="Int"||i==="Float"?t[r]=0:t[r]=""}return t}async function $t(e){let r=(await U()).apis?.[e]?.schemaType;if(r==="graphql")return"graphql";if(r==="openapi")return"openapi";try{let n=await k.readJson(L(e));if(Array.isArray(n)&&n.some(s=>typeof s?.rootType=="string"))return"graphql"}catch{}return"openapi"}async function js(e){let t=R.join(R.dirname(v(e)),"bundled.json"),r=await k.readJson(t),n=typeof r?.source=="string"?r.source:typeof r?.sourceText=="string"?r.sourceText:void 0;if(!n)throw new Error(`GraphQL source not found for API '${e}'. Run generate first.`);return n}async function Dt(e,t,r=!1){let n=await le(e,t),s=ae(e,n);if(!r&&await k.pathExists(s))return await k.readJson(s);let o=(await k.readJson(L(e))).find(u=>u.operationId===t||u.name===t);if(!o)throw new Error(`Endpoint '${t}' not found in GraphQL endpoint list.`);let a=await js(e),p=typeof o.rootType=="string"?o.rootType:typeof o.method=="string"?o.method:void 0;if(!p||p!=="query"&&p!=="mutation"&&p!=="subscription")throw new Error(`Invalid GraphQL endpoint metadata for '${t}'.`);let c=await ye(a,p,t);return await k.ensureDir(R.dirname(s)),await k.writeJson(s,c,{spaces:2}),c}async function Ft(e){return await $t(e)}function Jt(e,t){let r=Le(t),n=[];for(let[s,i]of Object.entries(r)){if(i===et)continue;let o=_e(e,s);o!==void 0&&(Rs(o,i)||n.push(`--update-request type mismatch at ${s}: expected ${Ir(o)}, received ${Ir(i)}.`))}return n}async function Ut(e,t){if(await Ft(e)==="graphql"){let p=await le(e,t),c=R.join(pe(e,p),"response-schema.json");if(await k.pathExists(c))return await k.readJson(c);let u=await Dt(e,t,!1);return await k.ensureDir(R.dirname(c)),await k.writeJson(c,u,{spaces:2}),u}let r=await le(e,t),n=v(e),s=await ar(R.resolve(n,`${r}.json`)),i=pe(e,r),o=R.join(i,"response-schema.json");if(await k.pathExists(o))return await k.readJson(o);let a=Qs(s);return a!==void 0&&(await k.ensureDir(i),await k.writeJson(o,a,{spaces:2})),a}async function Gt(e,t,r=!1,n,s,i,o=!1,a=!1){let p=await Ne(e,t,await le(e,t),r),c=await U(),u=c.apis?.[e]?.baseUrl;if(!u)throw new Error("Base URL not found in config");if(p.schemaType==="graphql"){let x=await le(e,t),D=await Dt(e,t,r),{requestJson:ne,responseJsonPath:me}=await _s(e,x,r||a,D),Fe=R.join(v(e),x,"request.json"),dt=ne,Vt=[];if(i&&i.length>0&&Vt.push(...i),s&&typeof s=="object"&&Object.keys(s).length>0||o){let ft={...s?Le(s):{}};for(let[Je,ln]of Object.entries(s??{}))Je in ft||(ft[Je]=ln);await qe(Fe,ft,2,{deleteSentinel:et,transform:o?Je=>Sr(Je,D):void 0}),dt=await k.readJson(Fe)}let cn={...Ns(p.args),...jr(dt)?dt.variables:{}},lt={query:p.query,variables:cn},F={headers:{"Content-Type":"application/json"},url:"",warnings:Vt,responseJsonPath:me},un=new je(u),_;try{if(_=await un.post(u,{headers:F.headers,body:lt}),_&&typeof _=="object"&&"status"in _){let z=_.status;typeof z=="number"&&(z<200||z>=300)&&F.warnings.push(`\u26A0\uFE0F The live HTTP request failed for ${u}: HTTP ${z}${"statusText"in _&&typeof _.statusText=="string"&&_.statusText?` ${_.statusText}`:""}`)}_&&typeof _=="object"&&Array.isArray(_.errors)&&_.errors?.length&&F.warnings.push("\u26A0\uFE0F GraphQL response contains errors."),await k.writeJson(F.responseJsonPath,_,{spaces:2})}catch(z){if(F.warnings.push(`\u26A0\uFE0F The live HTTP request failed for ${u}: ${z instanceof Error?z.message:String(z)}`),!await k.pathExists(F.responseJsonPath))return F.warnings.push(`response.json not found at ${F.responseJsonPath}`),{request:lt,response:void 0,warnings:F.warnings}}let dn=await k.readJson(F.responseJsonPath);return{request:lt,response:dn?.data?.[p.fieldName],warnings:F.warnings}}let m=await le(e,t),f=await Ne(e,t,m);if(f.schemaType!=="rest")throw new Error(`Invalid REST endpoint metadata for '${t}'.`);let l=await Q(e,t,m,r),{requestJson:g,responseJsonPath:b}=await Cr(e,m,r||a),T=R.join(v(e),m,"request.json"),h=g,y=[];if(i&&i.length>0&&y.push(...i),s&&typeof s=="object"&&Object.keys(s).length>0||o){let x=s?Is(s):void 0;x&&y.push(x);let ne={...s?Le(s):{}};for(let[me,Fe]of Object.entries(s??{}))me in ne||(ne[me]=Fe);await qe(T,ne,2,{deleteSentinel:et,transform:o?me=>kr(me,l):void 0}),h=await k.readJson(T)}let A=Cs(e,f,h,c,b,n,y),P=new je(u);if(!f.method||!f.path)throw new Error(`Invalid OpenAPI endpoint metadata for '${t}'.`);let O=f.method.toLowerCase(),E;try{switch(O){case"get":E=await P.get(A.url,{headers:A.headers});break;case"post":{let x=await jt(l,h);E=await P.post(A.url,{headers:{...A.headers,...x.headers},body:x.body})}break;case"put":{let x=await jt(l,h);E=await P.put(A.url,{headers:{...A.headers,...x.headers},body:x.body})}break;case"delete":E=await P.delete(A.url,{headers:A.headers});break;case"patch":{let x=await jt(l,h);E=await P.patch(A.url,{headers:{...A.headers,...x.headers},body:x.body})}break;case"head":E=await P.head(A.url,{headers:A.headers});break;case"options":E=await P.options(A.url,{headers:A.headers});break;default:throw new Error(`Unsupported HTTP method: ${f.method}`)}if(E&&typeof E=="object"&&"status"in E){let x=E.status;typeof x=="number"&&(x<200||x>=300)&&A.warnings.push(`\u26A0\uFE0F The live HTTP request failed for ${u}${A.url}: HTTP ${x}${"statusText"in E&&typeof E.statusText=="string"&&E.statusText?` ${E.statusText}`:""}`)}await k.writeJson(A.responseJsonPath,E,{spaces:2})}catch(x){if(A.warnings.push(`\u26A0\uFE0F The live HTTP request failed for ${u}${A.url}: ${x instanceof Error?x.message:String(x)}`),!await k.pathExists(A.responseJsonPath))return A.warnings.push(`response.json not found at ${A.responseJsonPath}`),{request:h,response:void 0,warnings:A.warnings}}let V=await k.readJson(A.responseJsonPath);return{request:h,response:V,warnings:A.warnings}}async function Lr(e,t,r=!1,n,s,i,o=!1,a=!1){let{request:p,response:c,warnings:u}=await Gt(e,t,r,n,s,i,o,a),m=u??[];if(await Ft(e)==="graphql"){if(!c||typeof c!="object")return{valid:!1,warnings:m,errors:["response.body missing or invalid"]};let T=c;return Array.isArray(T.errors)&&T.errors.length>0?{valid:!1,warnings:m,errors:["GraphQL response contains errors"]}:{valid:!0,warnings:m}}let f=await Ut(e,t);if(f===void 0||Object.keys(f).length===0)return u.push("No response schema found for this operation. Skipping validation."),{valid:!0,warnings:m};if(!c)return{valid:!1,warnings:m};let g=new Ss({allErrors:!0,strict:!1,strictSchema:!1,allowUnknownKeywords:!0,removeAdditional:!1}).compile(f);return g(c)?{valid:!0,warnings:m}:{valid:!1,errors:(g.errors||[]).map(h=>`${h.instancePath?h.instancePath.replace(/^\//,"response.body.").replace(/\//g,"."):"response.body"} ${h.message}`),warnings:m}}async function Ce(e,t,r=!1,n=!1){if(await Ft(e)==="graphql"){let a=await Dt(e,t,r),p=R.join(v(e),t,"request.json"),c=R.join(pe(e,t),"response.json"),u=Re(a);return await k.ensureDir(R.dirname(p)),await k.writeJson(p,u,{spaces:2}),{requestJsonPath:p,responseJsonPath:c,requestJson:u}}let{requestJson:s,responseJsonPath:i}=await Cr(e,t,r||n);return{requestJsonPath:R.join(v(e),t,"request.json"),responseJsonPath:i,requestJson:s}}async function Cr(e,t,r){let n=ae(e,t),s=await k.readJson(n),i=R.join(v(e),t);await k.ensureDir(i);let o=R.join(i,"request.json"),a=R.join(i,"response.json");if(await(async()=>{if(r||!await k.pathExists(o))return!0;let c=await k.readJson(o);return!Ls(c)})()){let c=Ds(s);return await k.writeJson(o,c,{spaces:2}),{requestJson:c,responseJsonPath:a}}return{requestJson:await k.readJson(o),responseJsonPath:a}}async function _s(e,t,r,n){let s=R.join(v(e),t);await k.ensureDir(s);let i=R.join(s,"request.json"),o=R.join(s,"response.json");if(await(async()=>{if(r||!await k.pathExists(i))return!0;let p=await k.readJson(i);return!jr(p)})()){let p=Re(n);return await k.writeJson(i,p,{spaces:2}),{requestJson:p,responseJsonPath:o}}return{requestJson:await k.readJson(i),responseJsonPath:o}}function Ls(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return Object.prototype.hasOwnProperty.call(t,"parameters")&&Array.isArray(t.parameters)}function Cs(e,t,r,n,s,i,o=[]){let a={},p=n.apis?.[e]?.auth?.headers;p&&typeof p=="object"&&Object.assign(a,p),i&&typeof i=="object"&&Object.assign(a,i);let c={},u={};for(let l of r.parameters||[])l.in==="path"?c[l.name]=l.value:l.in==="query"?u[l.name]=l.value:l.in==="header"&&(a[l.name]=String(l.value));if(!t.path)throw new Error(`Invalid OpenAPI endpoint metadata for '${t.operationId}'.`);let m=Fs(t.path,c),f=$s(u);return{headers:a,url:m+f,warnings:o,responseJsonPath:s}}function $s(e){return Object.keys(e).length?"?"+Object.entries(e).map(([t,r])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(r))}`).join("&"):""}function Ds(e){let t=[];if(Array.isArray(e.parameters))for(let s of e.parameters){let i=mr(s);t.push({name:s.name,in:s.in,value:i})}let r=null;(e?.requestBody||e?.parameters)&&(r=Js(e));let n={parameters:t};return r!==null&&(n.requestBody=r),n}function Fs(e,t){return e.replace(/\{([^}]+)\}/g,(r,n)=>{if(!(n in t))throw new Error(`Missing path parameter: ${n}`);return encodeURIComponent(t[n])})}function Js(e){let t=Us(e);if(t)return Ee(t);let r=_t(e);return r?Ee(r):null}function Us(e){let t=e?.requestBody?.content;if(!t||typeof t!="object")return null;for(let r of Object.values(t)){let n=r;if(n?.schema)return n.schema}return null}function _t(e){let t=Array.isArray(e?.parameters)?e.parameters:[],r=t.find(o=>o.in==="body");if(r?.schema){let o=r.schema;return!o.type&&o.properties&&(o.type="object"),o}let n=e?.consumes||[],s=n.includes("application/x-www-form-urlencoded")||n.includes("multipart/form-data"),i=t.filter(o=>o.in==="formData");if(s&&i.length){let o={type:"object",properties:{},required:[]};for(let a of i){let p={};a.schema?Object.assign(p,a.schema):(a.type&&(p.type=a.type),a.items&&(p.items=a.items),a.format&&(p.format=a.format),a.enum&&(p.enum=a.enum),a.type==="file"&&(p.type="string",p.format="binary")),o.properties[a.name]=p,a.required&&o.required.push(a.name)}return o.required.length===0&&delete o.required,o}return null}function Ee(e){if(!e)return null;if(e.const!==void 0)return e.const;if(e.default!==void 0)return e.default;if(Array.isArray(e.allOf)&&e.allOf.length>0){let t=e.allOf.map(r=>Ee(r)).filter(r=>r!=null).reduce((r,n)=>$r(r,n),{});if(t!=null)return t}if(Array.isArray(e.oneOf)&&e.oneOf.length>0)return qr(e.oneOf.map(t=>Ee(t)));if(Array.isArray(e.anyOf)&&e.anyOf.length>0)return qr(e.anyOf.map(t=>Ee(t)));if(!e.type&&e.properties&&(e.type="object"),e.$ref)throw new Error("Schema contains $ref. Resolve references before building template.");switch(e.type){case"string":return e.format==="binary"?{kind:"file",path:"",fileName:"",mimeType:""}:e.example??"";case"integer":case"number":return e.example??0;case"boolean":return e.example??!1;case"array":return[];case"object":let t={};if(e.properties)for(let[r,n]of Object.entries(e.properties))t[r]=Ee(n);return t;default:return null}}function Lt(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function $r(e,t){if(e==null)return t;if(t==null)return e;if(Lt(e)&&Lt(t)){let r={...e};for(let[n,s]of Object.entries(t))r[n]=n in r?$r(r[n],s):s;return r}return t}function qr(e){let t=e.filter(n=>n!=null);if(t.length===0)return null;let r=t.filter(Lt);return r.length>0?r.reduce((n,s)=>{let i=Object.keys(n).length;return Object.keys(s).length>i?s:n}):t[0]}function Gs(e){let t=e?.responses;if(!t)return null;let r=t[200]||t[201]||t.default||Object.values(t)[0];if(!r?.content)return null;let n=r.content["application/json"];if(n?.schema)return n.schema;for(let s of Object.values(r.content)){let i=s;if(i.schema)return i.schema}return null}function Bs(e){let t=e?.responses;return t?(t[200]||t[201]||t.default||Object.values(t)[0])?.schema||{}:{}}function Qs(e){let t=Gs(e);if(t)return t;let r=Bs(e);if(r)return r}var Bt=S(()=>{"use strict";hr();K();Rt();At();de();ot();Pt();qt();Oe();K();ke();Pr()});import*as te from"node:fs/promises";import $ from"path";import Ms from"readline";import{fileURLToPath as Vs}from"url";function Se(e){return e?"Yes":"No"}function Hs(e){return Array.isArray(e)?e.join(`
|
|
9
|
-
`):e}function
|
|
8
|
+
The temporary file with your changes is: ${f}`),h}}var ot,Ot=I(()=>{"use strict";xe();ot="__delete__"});import Q from"path";import gs from"find-root";function ne(e,t){let r=j(e);return Q.join(r,`${t}.json`)}function de(e){return Q.resolve(ue,".openapi-skills",e,"bundled.json")}function vt(e){return Q.resolve(ue,".openapi-skills",e,"components.json")}function le(e,t){let r=j(e);return Q.resolve(r,t)}function j(e){return Q.resolve(ue,".openapi-skills",e,"schemas")}function Ee(e){return Q.resolve(ue,".openapi-skills",e)}function pt(e){return Q.join(Ee(e),"cookies.json")}function yr(){return Q.resolve(ue,".openapi-skills","config.json")}function D(e){return Q.resolve(ue,".openapi-skills",e,"endpoints.json")}function Se(e,t,r){let n=le(e,t),s=r==="response-schema"?"response-schema.json":`${r}.json`;return Q.join(n,s)}function ct(){return Q.resolve(ue,".openapi-skills")}function ut(){let e=process.cwd();try{return gs(e)}catch{return e}}var ue,z=I(()=>{"use strict";ue=ut()});import{readFile as hs}from"fs/promises";import ys from"path";import fe from"fs-extra";async function B(){return await fe.readJSON(Re)}async function qt(){if(await fe.ensureDir(ws),!await fe.pathExists(Re)){let e={apis:{}};await fe.writeJson(Re,e,{spaces:2})}}function wr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}async function Ie(e,t={}){if(typeof e!="string"||e.trim().length===0)throw new Error("API name is required.");let{baseUrl:r,auth:n,vars:s,version:i,openapiSource:o,schemaType:a,removeApi:p}=t,c={};if(p){if(!await fe.pathExists(Re))throw new Error("Config file not found.");let u=await B();if(!wr(u)||!wr(u.apis))throw new Error("Invalid config file.");if(!(e in u.apis))throw new Error(`API '${e}' not found`);delete u.apis[e],await fe.writeJson(Re,u,{spaces:2});return}if(await qt(),n!==void 0&&(c[`apis.${e}.auth.headers`]=n),s!==void 0)for(let[u,m]of Object.entries(s))c[`apis.${e}.vars.${u}`]=m;if(i!==void 0&&(c[`apis.${e}.version`]=i),o!==void 0){let u=o;try{new URL(o)}catch{u=ys.normalize(o)}c[`apis.${e}.openapiSource`]=u}r!==void 0&&(c[`apis.${e}.baseUrl`]=r),a!==void 0&&(c[`apis.${e}.schemaType`]=a),Object.keys(c).length!==0&&await $e(Re,c,2)}function bs(e){let t=e instanceof Error?e.message:String(e);return/config/i.test(t)?{type:"ConfigError",message:t}:/permission|EACCES|EPERM/i.test(t)?{type:"DirectoryDeletionError",message:t}:{type:"DeleteApiError",message:t}}async function br(e){if(typeof e!="string"||e.trim().length===0)return{ok:!1,error:{type:"InvalidApiName",message:"API name is required."}};try{if(!(await se()).includes(e))return{ok:!1,error:{type:"ApiNotFound",message:`API '${e}' is not installed.`}};await Ie(e,{removeApi:!0});let r=Ee(e);return await fe.remove(r),{ok:!0,message:`API ${e} removed successfully`,data:{removedApi:e}}}catch(t){return{ok:!1,error:bs(t)}}}async function dt(e,t){let n=(await B()).apis[e];if(!n)throw new Error(`API '${e}' not found`);switch(t){case"version":return n.version??"unknown";case"baseUrl":return n.baseUrl;case"authHeaders":return n.auth?.headers??{};case"vars":return Object.entries(n.vars??{})}}async function kr(e){try{let t=await hs(D(e),"utf-8");return JSON.parse(t)}catch(t){throw t instanceof SyntaxError?new Error(`Failed to parse endpoints.json: Invalid JSON format. ${t.message}`):new Error(`Failed to read endpoints.json: ${t instanceof Error?t.message:String(t)}`)}}async function se(){let e=await B();return Object.keys(e.apis)||[]}var ws,Re,me=I(()=>{"use strict";Ot();z();ws=ct(),Re=yr()});import jt from"@apidevtools/swagger-parser";import ks from"@apidevtools/json-schema-ref-parser";import v from"fs-extra";import Y from"path";function Ar(e){let t;try{let r=new URL(e);t=Y.basename(r.pathname,Y.extname(r.pathname))}catch{t=Y.basename(e,Y.extname(e))}return ce(t||"api")}function As(e){if(e instanceof Error)return/circular/i.test(e.message)||/circular/i.test(e.name);if(typeof e=="object"&&e!==null){let t=String(e.message??""),r=String(e.name??"");return/circular/i.test(t)||/circular/i.test(r)}return!1}function Nt(e,t=new WeakSet){if(e&&typeof e=="object"){if(t.has(e))return;if(t.add(e),Array.isArray(e)){let n=e.map(s=>Nt(s,t));return t.delete(e),n}let r={};for(let[n,s]of Object.entries(e)){let i=Nt(s,t);i!==void 0&&(r[n]=i)}return t.delete(e),r}return e}async function Ts(e){let t=de(e),r=await v.readJson(t),n=typeof r?.source=="string"?r.source:typeof r?.sourceText=="string"?r.sourceText:void 0;if(!n)throw new Error(`GraphQL source not found for API '${e}'. Run generate first.`);return n}async function xs(e,t,r,n=!1){let s=ne(e,r);if(!n&&await v.pathExists(s))return v.readJson(s);let i=await v.readJson(D(e)),o=Array.isArray(i)?i.find(u=>u.operationId===t||u.name===t||u.sanitizedOperationId===r):void 0;if(!o)throw new Error(`Endpoint '${t}' not found in GraphQL endpoint list.`);let a=typeof o.rootType=="string"?o.rootType:typeof o.method=="string"?o.method:void 0;if(!a||a!=="query"&&a!=="mutation"&&a!=="subscription")throw new Error(`Invalid GraphQL endpoint metadata for '${t}'.`);let p=await Ts(e),c=await Ae(p,a,t);return await v.ensureDir(Y.dirname(s)),await v.writeJson(s,c,{spaces:2}),c}function Es(e,t){for(let[r,n]of Object.entries(e))for(let[s,i]of Object.entries(n))if(i&&typeof i=="object"&&"operationId"in i){let o=i;if(o.operationId===t)return{pathKey:r,method:s,operation:o}}}async function Ss(e,t){let r=typeof e.operationId=="string"?e.operationId:"unknown-operation",n=typeof e.method=="string"?e.method.toUpperCase():"GET",s=typeof e.path=="string"?e.path:"unknown-path",i=X;i&&d.progressLine(`Dereferencing endpoint ${r} (${n} ${s})...`);let o={openapi:"3.0.0",paths:{"/temp":{get:e}},definitions:t,components:t},a=await ks.dereference(o,{mutateInputSchema:!1,dereference:{circular:"ignore"}}),p=Nt(a),c=p.paths,u=c&&typeof c=="object"?c["/temp"]:void 0,m=u&&typeof u=="object"?u.get:void 0;return m&&typeof m=="object"?(i&&d.progressLine(`Endpoint ${r} (${n} ${s}) dereference complete.`),m):(i&&d.progressLine(`Endpoint ${r} (${n} ${s}) dereference complete.`),p)}async function W(e,t,r,n=!1){let s=ne(e,r);if(!n&&await v.pathExists(s))return v.readJson(s);let i=de(e),o=vt(e),a=await v.readJson(i);if(a&&typeof a=="object"&&a.schemaType==="graphql")return await xs(e,t,r,n);if(!a||typeof a!="object"||!("paths"in a))throw new Error(`Bundled OpenAPI document not found for API '${e}'. Run generate first.`);let p={},c=a.components,u=a.definitions;c&&typeof c=="object"&&!Array.isArray(c)?p=c:u&&typeof u=="object"&&!Array.isArray(u)?p=u:await v.pathExists(o)&&(p=await v.readJson(o));let m=Es(a.paths,t);if(!m)throw new Error(`Endpoint '${t}' not found in bundled OpenAPI document.`);let f={operationId:t,method:m.method,path:m.pathKey,...m.operation},g=await Ss(f,p);return await v.ensureDir(Y.dirname(s)),await v.writeJson(s,g,{spaces:2}),g}async function Rs(e,t){if(!t)return jt.bundle(e);try{return await jt.dereference(e,{dereference:{circular:!1}})}catch(r){throw As(r)?new Error("The --dereference flag cannot be used because this OpenAPI spec contains circular references. Try running without --dereference."):r}}function Is(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("Invalid OpenAPI schema: expected a document object.");let t=e;if(t.swagger!==void 0&&t.openapi!==void 0)throw new Error("Invalid OpenAPI schema: both 'swagger' and 'openapi' version fields are present.");if(t.swagger!==void 0){if(t.swagger==="2.0")return"2";throw new Error(`Unsupported Swagger version '${String(t.swagger)}'. This CLI supports Swagger 2.0 and OpenAPI 3.0.x.`)}if(t.openapi!==void 0){if(typeof t.openapi!="string")throw new Error("Invalid OpenAPI schema: 'openapi' version must be a string.");if(/^3\.0\.\d+$/.test(t.openapi))return"3";throw new Error(`Unsupported OpenAPI version '${t.openapi}'. This CLI supports OpenAPI 2.0 and 3.0.x; For OpenAPI 3.1.0 and later, please use openapi-skills Pro.`)}throw new Error("Invalid OpenAPI schema: missing version declaration ('swagger' or 'openapi'); cannot determine a supported version.")}async function Ps(e,t,r={}){let n="",s="unknown",i,o=r.progress!==!1&&X;try{o&&d.progressLine(`Loading OpenAPI document from ${e}...`),i=await Rs(e,r.dereference===!0),o&&d.progressLine("OpenAPI document load complete.")}catch(a){throw d.error(`Error during parsing OpenAPI schema: ${a instanceof Error?a.message:String(a)}`),a}if(typeof i!="object"||!i.paths)throw new Error("Invalid OpenAPI schema: Missing 'paths'");try{s=Is(i),n=r.rename||Ar(e);let a=Ee(n);await v.remove(a);let p=j(n);await v.ensureDir(p);let c=de(n);if(await v.writeJson(c,i,{spaces:2}),!r.dereference){let l=vt(n);await v.writeJson(l,i?.components??{},{spaces:2})}let u=[],m=0,f=0,g=r.progress!==!1&&X;for(let[l,b]of Object.entries(i.paths))for(let[y,h]of Object.entries(b))h&&typeof h=="object"&&"operationId"in h&&h.operationId&&(m+=1);for(let[l,b]of Object.entries(i.paths))for(let[y,h]of Object.entries(b))if(h&&typeof h=="object"&&"operationId"in h){let w=h;if(w.operationId){let T={operationId:w.operationId,sanitizedOperationId:ce(w.operationId),method:y,path:l};if(Array.isArray(w.tags)){let R=w.tags.map(A=>typeof A=="string"?A.trim():"").filter(A=>A.length>0);R.length>0&&(T.tags=R)}w.summary!==void 0&&(T.summary=w.summary),w.description!==void 0&&(T.description=w.description),u.push(T),f+=1,g&&d.progress(`\rProcessed ${f}/${m}`)}}g&&m>0&&d.progressLine("");try{let l=Y.join(a,"endpoints.json");await v.writeJson(l,u,{spaces:2})}catch(l){throw d.error(`Error writing endpoints.json: ${l instanceof Error?l.message:String(l)}`),l}try{await Ie(n,{baseUrl:t,openapiSource:e,schemaType:"openapi",version:s});let l=t?"with baseUrl":"without baseUrl";d.info(`Schema '${n}' added to config.json ${l} and openapiSource recorded.`)}catch(l){throw d.error(`Error updating config.json: ${l instanceof Error?l.message:String(l)}`),l}}catch(a){throw d.error(`Error during OpenAPI schema processing: ${a instanceof Error?a.message:String(a)}`),a}return n}async function Os(e,t,r={},n){let s="",i=r.progress!==!1&&X,o=n??await et(e);if(!tt(o))throw new Error("Invalid GraphQL schema: missing GraphQL schema markers or builder pattern.");i&&d.progressLine(`Loading GraphQL schema from ${e}...`),s=r.rename||Ar(e);let a=Ee(s);await v.remove(a);let p=j(s);await v.ensureDir(p);let c=await nt(o,e);if(c.length===0)throw new Error("Invalid GraphQL schema: no query, mutation, or subscription fields were found.");let u=de(s);await v.writeJson(u,{schemaType:"graphql",source:o},{spaces:2});let m=c.map(f=>({name:f.name,sanitizedOperationId:f.sanitizedOperationId,rootType:f.rootType,summary:f.summary,description:f.description}));for(let f of c){let g=ne(s,f.sanitizedOperationId);await v.ensureDir(Y.dirname(g)),await v.writeJson(g,f,{spaces:2})}await v.writeJson(Y.join(a,"endpoints.json"),m,{spaces:2});try{await Ie(s,{baseUrl:t,openapiSource:e,schemaType:"graphql",version:"graphql"});let f=t?"with baseUrl":"without baseUrl";d.info(`Schema '${s}' added to config.json ${f} and GraphQL source recorded.`)}catch(f){throw d.error(`Error updating config.json: ${f instanceof Error?f.message:String(f)}`),f}return i&&d.progressLine("GraphQL schema load complete."),s}async function Tr(e,t,r={}){let n=await et(e).catch(()=>{});return n&&tt(n)?await Os(e,t,r,n):await Ps(e,t,r)}async function xr(e){try{let t=await et(e).catch(()=>{});if(t&&tt(t)){await nt(t,e);return}await jt.validate(e);return}catch(t){throw new Error(t instanceof Error?t.message:String(t))}}var Pe=I(()=>{"use strict";Le();me();z();xe();xt()});function vs(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ct(e){if(!(!e||typeof e!="object"))return vs(e.schema)?e.schema:e}function Er(e){let t=Ct(e);switch(typeof t?.type=="string"?t.type:typeof e?.type=="string"?e.type:void 0){case"string":return"";case"number":case"integer":return 0;case"boolean":return!1;case"array":return[];case"object":return{};default:return null}}var _t=I(()=>{"use strict"});import Oe from"fs-extra";function lt(e){return e.replace(/[^a-zA-Z0-9]+(.)/g,(t,r)=>r.toUpperCase()).replace(/^[a-z]/,t=>t.toUpperCase())}function ie(e,t,r){if(!(!e||typeof e!="object")){if(Array.isArray(e.enum)){let n=lt(r);t[n]=e.enum}if(e.properties&&typeof e.properties=="object")for(let[n,s]of Object.entries(e.properties))ie(s,t,`${r}_${n}`);e.items&&ie(e.items,t,`${r}_item`),e.oneOf&&e.oneOf.forEach((n,s)=>ie(n,t,`${r}_oneOf_${s}`)),e.anyOf&&e.anyOf.forEach((n,s)=>ie(n,t,`${r}_anyOf_${s}`)),e.allOf&&e.allOf.forEach((n,s)=>ie(n,t,`${r}_allOf_${s}`))}}function oe(e){if(!(!e||typeof e!="object")){if(delete e.xml,e.properties&&typeof e.properties=="object")for(let t of Object.values(e.properties))oe(t);e.items&&oe(e.items),e.oneOf&&e.oneOf.forEach(oe),e.anyOf&&e.anyOf.forEach(oe),e.allOf&&e.allOf.forEach(oe)}}function Sr(e){if(!e||typeof e!="object")return null;let r=Object.keys(e).filter(n=>/^\d{3}$/.test(n)).find(n=>n.startsWith("2"));return r?e[r]:null}function Lt(e){if(!e||typeof e!="object")return null;let t=Object.entries(e).find(([r])=>r.toLowerCase().includes("json"));return t?t[1]:null}function qs(e){let t=Sr(e);if(!t)return null;if(t.content){let r=Lt(t.content);return!r||!r.schema?null:r.schema}return t.schema??null}function js(e){let t=Sr(e);return t?t.schema??null:null}function Ns(e){let t=Array.isArray(e?.parameters)?e.parameters:[],r=t.find(i=>i.in==="body");if(r?.schema)return r.schema;let n=t.filter(i=>i.in==="formData");if(n.length===0)return null;let s={type:"object",properties:{}};for(let i of n){let o={};i.schema&&typeof i.schema=="object"?Object.assign(o,i.schema):(typeof i.type=="string"&&(o.type=i.type),i.items&&(o.items=i.items),typeof i.format=="string"&&(o.format=i.format),Array.isArray(i.enum)&&(o.enum=i.enum),i.type==="file"&&(o.type="string",o.format="binary")),s.properties[i.name]=o}return s}function _s(e){let t={};if(!e||typeof e!="object")return t;for(let[r,n]of Object.entries(e)){if(!/^\d{3}$/.test(r)||r.startsWith("2"))continue;let s=n.content,i=s?Lt(s):null,o=i&&i.schema?i.schema:n.schema??Cs;t[r]=o}return t}function Ls(e,t){let r={};for(let n of["path","query","header"])for(let[s,i]of Object.entries(e[n]||{}))r[s]={...i.schema,required:i.required??!1,description:i.description,in:n};return{typeName:`${lt(t)}Params`,schema:r}}async function De(e,t,r,n=!1){let s=await B(),i=await Oe.readJson(D(e)),o=Array.isArray(i)&&i.some(w=>typeof w?.rootType=="string");if(s.apis?.[e]?.schemaType==="graphql"||s.apis?.[e]?.schemaType!=="openapi"&&o){let w=i.find(E=>E.operationId===t||E.name===t);if(!w)throw new Error(`Endpoint with operationId '${t}' not found.`);let T=typeof w.rootType=="string"?w.rootType:typeof w.method=="string"?w.method:void 0;if(!T||T!=="query"&&T!=="mutation"&&T!=="subscription")throw new Error(`Invalid GraphQL endpoint metadata for '${t}'.`);let R=j(e)+`/${r}.json`,A;if(!n&&await Oe.pathExists(R))A=await Oe.readJson(R);else{let E=await Oe.readJson(de(e)),_=typeof E?.source=="string"?E.source:typeof E?.sourceText=="string"?E.sourceText:void 0;if(!_)throw new Error(`GraphQL source not found for API '${e}'. Run generate first.`);A=await Ae(_,T,t),await Oe.ensureDir(j(e)),await Oe.writeJson(R,A,{spaces:2})}return{schemaType:"graphql",fieldName:w.name??t,rootType:T,args:Object.fromEntries(Object.entries(A.args??{}).map(([E,_])=>{let L=_;return[E,{type:L.typeName??"unknown",required:L.required===!0}]})),returnType:A.returns?.typeName??"unknown",query:_e(A).query}}let p=i.find(w=>w.operationId===t);if(!p)throw new Error(`Endpoint with operationId '${t}' not found.`);let c=await W(e,t,r,n),u={path:{},query:{},header:{}};for(let w of c.parameters||[])(w.in==="path"||w.in==="query"||w.in==="header")&&(u[w.in][w.name]={description:w.description,required:w.required,schema:Ct(w)});let m=qs(c.responses)??js(c.responses),f={};m&&(oe(m),ie(m,f,`${t}_response`));let g=Ls(u,t),l=_s(c.responses),b=null,y=c.requestBody;if(y&&y.content){let w=Lt(y.content);w&&w.schema&&(b=w.schema,oe(b),ie(b,f,`${t}_request`))}else b=Ns(c),b&&(oe(b),ie(b,f,`${t}_request`));let h=lt(t.replace(/^(get|post|put|delete|patch|head|options)/i,"")||t);return{schemaType:"rest",operationId:t,method:p.method,path:p.path,deprecated:p.deprecated??c.deprecated??!1,params:g,response:m?{typeName:h,schema:m}:null,requestBody:b?{typeName:`${lt(t)}Request`,schema:b}:null,errors:l,enums:f}}var Cs,$t=I(()=>{"use strict";z();Pe();_t();Le();me();Cs={type:"object",properties:{message:{type:"string"},status:{type:"number"}}}});function Ds(e){return e.split(/,(?=\s*[^=;,\s]+\s*=)/).map(t=>t.trim()).filter(Boolean)}function Fs(e){let t={};return e.forEach((r,n)=>{t[n]=/auth|cookie|api[-_]?key|token|secret|session/i.test(n)?"[REDACTED]":r}),t}function ft(e,t){if(!/^https?:\/\//i.test(e))throw new Error(`Invalid baseUrl: "${e}". Must include http:// or https://`);let r=e.endsWith("/")?e:`${e}/`;return new URL(t.replace(/^\//,""),r).toString()}var $s,Fe,Rr=I(()=>{"use strict";$s=["location","www-authenticate","retry-after","x-request-id","traceparent"];Fe=class{constructor(t,r=!1){this.baseUrl=t;this.verboseTransport=r}baseUrl;verboseTransport;async request(t,r,n={}){let s=ft(this.baseUrl,r),i="body"in n&&n.body!==void 0&&t!=="GET"&&t!=="HEAD",o=new Headers(n.headers??{}),a=null;if(i){let y=n.body,h=typeof FormData<"u"&&y instanceof FormData,w=typeof Blob<"u"&&y instanceof Blob,T=y instanceof ArrayBuffer||ArrayBuffer.isView(y),R=typeof Buffer<"u"&&Buffer.isBuffer(y);h?(o.delete("Content-Type"),a=y):w||T||R||typeof y=="string"?a=y:(o.has("Content-Type")||o.set("Content-Type","application/json"),a=JSON.stringify(y))}let p=await fetch(s,{method:t,headers:o,body:a}),c=await p.text(),u={};if(c.trim().length>0)try{u=JSON.parse(c)}catch{u=c}let m=p.headers,f=m?.getSetCookie,g=m?.get("set-cookie"),l=typeof f=="function"?f.call(m):g?Ds(g):[],b={};for(let y of $s){let h=m?.get(y);h!=null&&(b[y]=h)}return{body:u,transport:{status:p.status,statusText:p.statusText,setCookies:l,headers:b,...this.verboseTransport?{requestHeadersSent:Fs(o)}:{},...m?.get("content-type")?{contentType:m.get("content-type")}:{},...m?.get("content-disposition")?{contentDisposition:m.get("content-disposition")}:{}},responseUrl:p.url||s}}get(t,r){return this.request("GET",t,r)}head(t,r){return this.request("HEAD",t,r)}options(t,r){return this.request("OPTIONS",t,r)}post(t,r){return this.request("POST",t,r)}put(t,r){return this.request("PUT",t,r)}patch(t,r){return this.request("PATCH",t,r)}delete(t,r){return this.request("DELETE",t,r)}}});import Js from"fs-extra";function Ir(e){return{orGroups:e.trim().toLowerCase().split("|").map(r=>r.trim()).filter(Boolean).map(r=>r.split(/\s+/).filter(Boolean))}}function Us(e,t){return t.orGroups.length===0?!0:t.orGroups.some(r=>r.every(n=>e.includes(n)))}function Gs(e){return e.split("/").map(t=>t.trim().toLowerCase()).filter(Boolean).flatMap(t=>{if(t.startsWith("{")&&t.endsWith("}")){let r=t.slice(1,-1).trim();return r?[t,r]:[t]}return[t]})}function Qs(e,t){return t?t===":param"?/\{[^/{}]+\}/.test(e):t.startsWith("/")?e.startsWith(t):Gs(e).includes(t):!0}function Bs(e,t){return Ir(t).orGroups.some(n=>n.every(s=>Qs(e,s)))}function Ms(e){return e?(Array.isArray(e)?e:[e]).map(t=>t.trim()).filter(Boolean):[]}function Vs(e,t){if(typeof t!="string"||t.trim().length===0||t.trim()===":")return e;let r=t.trim(),n=r.match(/^-?\d+$/),s=r.match(/^(-?\d*)?:(-?\d*)?$/),i,o;if(n)i=Number(r),o=i;else if(s){let f=s[1],g=s[2];i=f===void 0||f===""?0:Number(f),o=g===void 0||g===""?e.length-1:Number(g)}else throw new Error(`Invalid --index value: ${t}`);if(Number.isNaN(i)||Number.isNaN(o))throw new Error(`Invalid --index value: ${t}`);let a=f=>f<0?e.length+f:f,p=a(i),c=a(o);if(e.length===0)return[];let u=Math.max(0,p),m=Math.min(e.length-1,c);return u>m?[]:e.slice(u,m+1)}function Pr(e,t){return Vs(e,t)}function mt(e,t){let r=e;if(t.operationId){let s=t.operationId.toLowerCase();r=r.filter(i=>(i.operationId||"").toLowerCase()===s)}if(t.method){let s=t.method.toLowerCase();r=r.filter(i=>(i.method||"").toLowerCase()===s)}if(t.rootType){let s=t.rootType.toLowerCase();r=r.filter(i=>(i.rootType||"").toLowerCase()===s)}if(t.tag){let s=t.tag.toLowerCase();r=r.filter(i=>(Array.isArray(i.tags)?i.tags:[]).some(a=>typeof a=="string"&&a.toLowerCase()===s))}let n=Ms(t.path);if(n.length>0&&(r=r.filter(s=>{let i=(s.path||"").toString().toLowerCase();return n.every(o=>Bs(i,o))})),t.filter){let s=Ir(t.filter);r=r.filter(i=>{let o=[i.operationId,i.name,i.method,i.rootType,i.path,i.summary,i.description].map(a=>(a||"").toString().toLowerCase()).join(" ");return Us(o,s)})}return r}async function Hs(e){let t=j(e);try{let r=await Js.readdir(t,{withFileTypes:!0});return new Set(r.filter(n=>n.isFile()&&n.name.toLowerCase().endsWith(".json")).map(n=>n.name.slice(0,-5)))}catch(r){if(r?.code==="ENOENT")return new Set;throw r}}async function Or(e,t){let r=await Hs(e);return r.size===0?[]:t.filter(n=>{let s=typeof n.sanitizedOperationId=="string"?n.sanitizedOperationId:"";return r.has(s)})}var Dt=I(()=>{"use strict";z()});async function Z(e,t){let r={operationId:t},n=await kr(e),s=mt(n,r)[0]??n.find(i=>i.name===t);return s?.sanitizedOperationId??s?.operationId??s?.name??""}var ee,gt=I(()=>{"use strict";me();Dt();ee=Z});function zs(e){return e.replace(/\[(\d+)\]/g,".$1").split(".").filter(r=>r.length>0).map(r=>/^\d+$/.test(r)?Number(r):r)}function ve(e,t){let r=e;for(let n of zs(t)){if(r==null)return;if(typeof n=="number"){if(!Array.isArray(r)&&typeof r!="object")return;r=r[n];continue}if(typeof r!="object")return;r=r[n]}return r}function vr(e,t,r){return Array.isArray(e)?e.filter(n=>String(ve(n,t))===String(r)):e}var Ft=I(()=>{"use strict"});function N(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ws(e){let t=e.requestBody;if(N(t)&&N(t.content)){for(let a of Object.values(t.content))if(N(a)&&a.schema)return a.schema}let r=Array.isArray(e.parameters)?e.parameters:[],n=r.find(a=>N(a)&&a.in==="body");if(N(n)&&n.schema)return n.schema;let s=r.filter(a=>N(a)&&a.in==="formData");if(s.length===0)return;let i={},o=[];for(let a of s)!N(a)||typeof a.name!="string"||(i[a.name]=N(a.schema)?a.schema:Object.fromEntries(["type","items","format","enum"].filter(p=>a[p]!==void 0).map(p=>[p,a[p]])),a.required===!0&&o.push(a.name));return{type:"object",properties:i,...o.length>0?{required:o}:{}}}function Ks(e){let t=[],r=new Set,n=!1,s=i=>{if(!N(i)){n=!0;return}if(r.has(i)){n=!0;return}if("$ref"in i||"oneOf"in i||"anyOf"in i||"not"in i){n=!0;return}if(r.add(i),t.push(i),Array.isArray(i.allOf))for(let o of i.allOf)s(o);r.delete(i)};for(let i of e)s(i);return{schemas:t,ambiguous:n}}function Jt(e,t){let r=Ks(t);if(r.ambiguous)return!1;let n=r.schemas;if(Array.isArray(e)){let a=n.map(p=>p.items).filter(p=>N(p));return a.length===0?!1:e.reduce((p,c)=>Jt(c,a)||p,!1)}if(!N(e))return!1;let s=new Set(n.flatMap(a=>Array.isArray(a.required)?a.required.filter(p=>typeof p=="string"):[])),i=new Map;for(let a of n)if(N(a.properties))for(let[p,c]of Object.entries(a.properties)){let u=i.get(p)??[];u.push(c),i.set(p,u)}let o=!1;for(let[a,p]of Object.entries(e)){let c=i.get(a);if(c){if(p===""&&!s.has(a)){delete e[a],o=!0;continue}o=Jt(p,c)||o}}return o}function jr(e,t){if(!N(e)||!N(t))return!1;let r=!1;if(Array.isArray(e.parameters)&&Array.isArray(t.parameters)){let s=t.parameters.filter(N),i=e.parameters.filter(o=>{if(!N(o)||o.value!==""||!["path","query","header"].includes(String(o.in)))return!0;let a=s.find(p=>p.name===o.name&&p.in===o.in);return!a||o.in==="path"||a.required===!0?!0:(r=!0,!1)});r&&(e.parameters=i)}let n=Ws(t);return n&&"requestBody"in e&&(r=Jt(e.requestBody,[n])||r),r}function qr(e){let t=e;for(;t&&t.kind==="non-null"&&t.ofType;)t=t.ofType;return t}function Xs(e){if(!e)return!1;let t=e;for(;t;){if(t.defaultValue!==void 0)return!1;t=t.ofType}return e.required===!0||e.kind==="non-null"||e.typeName.trim().endsWith("!")}function Nr(e,t){if(Array.isArray(e)){let n=qr(t);return n?.kind!=="list"||!n.ofType?!1:e.reduce((s,i)=>Nr(i,n.ofType)||s,!1)}if(!N(e))return!1;let r=qr(t);return r?.kind!=="input-object"||!r.fields?!1:Cr(e,r.fields)}function Cr(e,t){let r=!1;for(let[n,s]of Object.entries(e)){let i=t[n];if(i){if(s===""&&!Xs(i)){delete e[n],r=!0;continue}r=Nr(s,i)||r}}return r}function _r(e,t){return!N(e)||!N(e.variables)?!1:Cr(e.variables,t.args)}var Lr=I(()=>{"use strict"});import ge from"fs-extra";import{randomUUID as Ys}from"node:crypto";import Zs from"node:path";function ri(e){if(!e.startsWith("/")||e==="/")return"/";let t=e.lastIndexOf("/");return t<=0?"/":e.slice(0,t)}function Ut(e,t){return e===t||e.endsWith(`.${t}`)}function $r(e){return`${e.name}\0${e.domain}\0${e.path}`}function ni(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.name=="string"&&typeof t.value=="string"&&typeof t.domain=="string"&&typeof t.hostOnly=="boolean"&&typeof t.path=="string"&&(t.expiresAt===void 0||typeof t.expiresAt=="number")&&typeof t.secure=="boolean"&&typeof t.createdAt=="number"}async function ht(e){let t=pt(e);if(!await ge.pathExists(t))return{...ei,cookies:[]};let r=await ge.readJson(t);if(!r||typeof r!="object"||Array.isArray(r))throw new Error(`Cookie jar at '${t}' has an invalid format.`);let n=r;if(n.version!==1||!Array.isArray(n.cookies)||!n.cookies.every(ni))throw new Error(`Cookie jar at '${t}' has an unsupported or invalid format.`);return{version:1,cookies:n.cookies}}async function Dr(e,t){let r=pt(e),n=`${r}.${process.pid}.${Ys()}.tmp`;await ge.ensureDir(Zs.dirname(r));try{await ge.writeJson(n,t,{spaces:2}),await ge.rename(n,r)}catch(s){try{await ge.remove(n)}catch(i){throw new AggregateError([s,i],`Failed to save cookie jar at '${r}'.`)}throw s}}async function Fr(e){await ge.remove(pt(e))}function Jr(e,t,r,n=Date.now()){let s=new URL(r),o={version:1,cookies:[...e.cookies.filter(a=>a.expiresAt===void 0||a.expiresAt>n)]};for(let a of t){let p=a.split(";"),c=p.shift()?.trim()??"",u=c.indexOf("=");if(u<=0)throw new Error(`Invalid Set-Cookie value received from '${s.origin}'.`);let m=c.slice(0,u).trim(),f=c.slice(u+1).trim();if(!ti.test(m))throw new Error(`Invalid cookie name received from '${s.origin}'.`);let g=s.hostname.toLowerCase(),l=!0,b,y,h,w=!1;for(let L of p){let S=L.trim();if(!S)continue;let te=S.indexOf("="),O=(te<0?S:S.slice(0,te)).trim().toLowerCase(),M=te<0?"":S.slice(te+1).trim();if(O==="domain")g=M.replace(/^\./,"").toLowerCase(),l=!1;else if(O==="path")b=M.startsWith("/")?M:void 0;else if(O==="expires"){let re=Date.parse(M);if(Number.isNaN(re))throw new Error(`Invalid Expires attribute for cookie '${m}'.`);y=re}else O==="max-age"&&/^-?\d+$/.test(M)?h=Number(M):O==="secure"&&(w=!0)}if(!g||!Ut(s.hostname.toLowerCase(),g))throw new Error(`Cookie '${m}' has a Domain attribute that does not match '${s.hostname}'.`);let T=b??ri(s.pathname),R={name:m,value:f,domain:g,hostOnly:l,path:T,...h!==void 0?{expiresAt:n+h*1e3}:y!==void 0?{expiresAt:y}:{},secure:w,createdAt:n},A=$r(R),E=o.cookies.findIndex(L=>$r(L)===A),_=E>=0?o.cookies[E]:void 0;E>=0&&o.cookies.splice(E,1),!(h!==void 0&&h<=0||R.expiresAt!==void 0&&R.expiresAt<=n)&&o.cookies.push({...R,..._?{createdAt:_.createdAt}:{}})}return o}function si(e,t){return t===e?!0:t.startsWith(e)?e.endsWith("/")||t[e.length]==="/":!1}function Ur(e,t,r=Date.now()){let n=new URL(t),s=n.hostname.toLowerCase(),i=e.cookies.filter(o=>o.expiresAt===void 0||o.expiresAt>r).filter(o=>o.hostOnly?s===o.domain:Ut(s,o.domain)).filter(o=>si(o.path,n.pathname)).filter(o=>!o.secure||n.protocol==="https:").sort((o,a)=>a.path.length-o.path.length||o.createdAt-a.createdAt);return i.length>0?i.map(o=>`${o.name}=${o.value}`).join("; "):void 0}function Gr(e,t,r=Date.now()){let n=new URL(t);return e.cookies.filter(s=>s.expiresAt===void 0||s.expiresAt>r).filter(s=>s.hostOnly?n.hostname.toLowerCase()===s.domain:Ut(n.hostname.toLowerCase(),s.domain)).map(({name:s,domain:i,path:o,expiresAt:a,secure:p})=>({name:s,domain:i,path:o,expiresAt:a===void 0?null:new Date(a).toISOString(),secure:p}))}var ei,ti,Gt=I(()=>{"use strict";z();ei={version:1,cookies:[]},ti=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/});import x from"fs-extra";import P from"path";import ii from"ajv";import{fileURLToPath as oi}from"url";async function Qr(e,t,r,n){return r}async function Br(e,t,r,n){if(!n){let i=await ht(e),o=Jr(i,t.transport.setCookies,t.responseUrl);await Dr(e,o)}let s={body:t.body,transport:t.transport};return await x.writeJson(r,s,{spaces:2}),s}function Je(e,t="",r={}){if(!e||typeof e!="object"||Array.isArray(e))return r;for(let[n,s]of Object.entries(e)){let i=t?`${t}.${n}`:n;s&&typeof s=="object"&&!Array.isArray(s)?Je(s,i,r):r[i]=s}return r}function Wr(e,t=""){if(!e||typeof e!="object"||Array.isArray(e))return[];let r=[];for(let[n,s]of Object.entries(e)){let i=t?`${t}.${n}`:n;s&&typeof s=="object"&&!Array.isArray(s)&&(r.push(i),r.push(...Wr(s,i)))}return Array.from(new Set(r))}function ai(e){let t=Wr(e);if(t.length===0)return;let r=Je(e);return["Use only flattened object dot-notation keys with --force.",`Example: --force --update-request '${JSON.stringify(r)}'.`,`Detected nested keys: ${t.join(", ")}.`].join(" ")}function Mr(e){return e===null?"null":Kr(e)?"file":Array.isArray(e)?"array":typeof e}function Kr(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&e.kind==="file"}function zt(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&typeof e.path=="string"&&(e.kind===void 0||e.kind==="file")}function pi(e,t){return Kr(e)?typeof t=="string"||zt(t):e===null?t===null:Array.isArray(e)?Array.isArray(t):typeof e=="object"?!!t&&typeof t=="object"&&!Array.isArray(t):typeof t==typeof e}function Xr(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&typeof e.query=="string"&&typeof e.variables=="object"&&!Array.isArray(e.variables)}function Yr(e){if(e)return e.split(",")[0]?.trim()||void 0}function ci(e){switch(P.extname(e).toLowerCase()){case".pdf":return"application/pdf";case".jpg":case".jpeg":return"image/jpeg";case".png":return"image/png";case".webp":return"image/webp";case".gif":return"image/gif";case".txt":return"text/plain";case".csv":return"text/csv";case".json":return"application/json";case".xml":return"application/xml";case".xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case".xls":return"application/vnd.ms-excel";case".docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case".zip":return"application/zip";default:return"application/octet-stream"}}function Vr(e){let t=e.trim();return t.startsWith("@")?P.resolve(t.slice(1)):t.startsWith("file://")?P.resolve(oi(new URL(t))):P.resolve(t)}async function Qt(e,t){let r,n,s;if(typeof e=="string"){if(e.trim().length===0)throw new Error("File upload path cannot be empty.");r=Vr(e)}else if(zt(e)){if(e.path.trim().length===0)throw new Error("File upload path cannot be empty.");r=Vr(e.path),n=e.fileName?.trim()||void 0,s=e.mimeType?.trim()||void 0}if(!r)throw new Error("File upload values must be a file path string or { kind: 'file', path, fileName?, mimeType? } object.");if(!await x.pathExists(r))throw new Error(`Upload file not found: ${r}`);let i=await x.readFile(r),o=n||P.basename(r),a=s||Yr(t)||ci(r);return{buffer:i,path:r,fileName:o,mimeType:a}}function Hr(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}function ui(e){let t=Object.entries(e),r=t.find(([o])=>o.toLowerCase().includes("multipart/form-data"));if(r)return{contentType:r[0],contentObject:r[1]};let n=t.find(([o,a])=>{let p=a?.schema;return o.toLowerCase().includes("octet-stream")||p?.type==="string"&&p?.format==="binary"});if(n)return{contentType:n[0],contentObject:n[1]};let s=t.find(([o])=>o.toLowerCase().includes("json"));if(s)return{contentType:s[0],contentObject:s[1]};let i=t[0];return i?{contentType:i[0],contentObject:i[1]}:void 0}function di(e){let t=e?.requestBody,n=(Array.isArray(e?.parameters)?e.parameters:[]).filter(a=>a&&a.in==="formData"),i=(Array.isArray(e?.consumes)?e.consumes:[]).some(a=>typeof a=="string"&&a.toLowerCase().includes("multipart/form-data"));if(n.length>0&&i)return{kind:"multipart",schema:Vt(e)??{type:"object",properties:{}},encoding:{}};if(!t||typeof t!="object")return n.length>0?{kind:"multipart",schema:Vt(e)??{type:"object",properties:{}},encoding:{}}:{kind:"json"};let o=t.content;if(o&&typeof o=="object"&&!Array.isArray(o)){let a=ui(o);if(!a)return{kind:"json"};let p=a.contentObject,c=p?.schema;if(a.contentType.toLowerCase().includes("multipart/form-data"))return{kind:"multipart",schema:c&&typeof c=="object"?c:{type:"object",properties:{}},encoding:p?.encoding??{}};if(a.contentType.toLowerCase().includes("octet-stream")||c?.type==="string"&&c?.format==="binary")return{kind:"binary",contentType:a.contentType}}return{kind:"json"}}async function Bt(e,t){let r=di(e);if(r.kind==="multipart"){let o=t,a=!!o&&typeof o=="object"&&!Array.isArray(o)&&("requestBody"in o||"parameters"in o),p=a?o.requestBody:t,c=a&&Array.isArray(o?.parameters)?Object.fromEntries(o.parameters.filter(g=>!!g&&g.in==="formData"&&typeof g.name=="string").map(g=>[g.name,g.value])):{},u=p&&typeof p=="object"&&!Array.isArray(p)?p:c;if(!u||typeof u!="object"||Array.isArray(u))throw new Error("multipart/form-data request bodies must be JSON objects.");let m=new FormData,f=r.schema?.properties&&typeof r.schema.properties=="object"?r.schema.properties:{};for(let[g,l]of Object.entries(u)){let b=f[g],y=r.encoding[g],h=Yr(y?.contentType);if(b?.type==="string"&&b?.format==="binary"){let w=await Qt(l,h);m.append(g,new Blob([Hr(w.buffer)],{type:w.mimeType}),w.fileName);continue}if(zt(l)){let w=await Qt(l,h);m.append(g,new Blob([Hr(w.buffer)],{type:w.mimeType}),w.fileName);continue}l==null?m.append(g,""):typeof l=="object"?m.append(g,JSON.stringify(l)):m.append(g,String(l))}return{kind:"multipart",body:m,headers:{}}}if(r.kind==="binary"){let o=t,p=!!o&&typeof o=="object"&&!Array.isArray(o)&&"requestBody"in o?o.requestBody:t,c=await Qt(p,r.contentType);return{kind:"binary",body:c.buffer,headers:{"Content-Type":c.mimeType}}}let n=t;return{kind:"json",body:!!n&&typeof n=="object"&&!Array.isArray(n)&&"requestBody"in n?n.requestBody:t,headers:{}}}function li(e){let t={};for(let[r,n]of Object.entries(e)){let s=n.type.trim(),i=s.endsWith("!")?s.slice(0,-1).trim():s;i.startsWith("[")&&i.endsWith("]")?t[r]=[]:i==="Boolean"?t[r]=!1:i==="Int"||i==="Float"?t[r]=0:t[r]=""}return t}async function Wt(e){let r=(await B()).apis?.[e]?.schemaType;if(r==="graphql")return"graphql";if(r==="openapi")return"openapi";try{let n=await x.readJson(D(e));if(Array.isArray(n)&&n.some(s=>typeof s?.rootType=="string"))return"graphql"}catch{}return"openapi"}async function fi(e){let t=P.join(P.dirname(j(e)),"bundled.json"),r=await x.readJson(t),n=typeof r?.source=="string"?r.source:typeof r?.sourceText=="string"?r.sourceText:void 0;if(!n)throw new Error(`GraphQL source not found for API '${e}'. Run generate first.`);return n}async function Kt(e,t,r=!1){let n=await ee(e,t),s=ne(e,n);if(!r&&await x.pathExists(s))return await x.readJson(s);let o=(await x.readJson(D(e))).find(u=>u.operationId===t||u.name===t);if(!o)throw new Error(`Endpoint '${t}' not found in GraphQL endpoint list.`);let a=await fi(e),p=typeof o.rootType=="string"?o.rootType:typeof o.method=="string"?o.method:void 0;if(!p||p!=="query"&&p!=="mutation"&&p!=="subscription")throw new Error(`Invalid GraphQL endpoint metadata for '${t}'.`);let c=await Ae(a,p,t);return await x.ensureDir(P.dirname(s)),await x.writeJson(s,c,{spaces:2}),c}async function yt(e){return await Wt(e)}function Xt(e,t){let r=Je(t),n=[];for(let[s,i]of Object.entries(r)){if(i===ot)continue;let o=ve(e,s);o!==void 0&&(pi(o,i)||n.push(`--update-request type mismatch at ${s}: expected ${Mr(o)}, received ${Mr(i)}.`))}return n}async function Yt(e,t){if(await yt(e)==="graphql"){let p=await ee(e,t),c=P.join(le(e,p),"response-schema.json");if(await x.pathExists(c))return await x.readJson(c);let u=await Kt(e,t,!1);return await x.ensureDir(P.dirname(c)),await x.writeJson(c,u,{spaces:2}),u}let r=await ee(e,t),n=j(e),s=await at(P.resolve(n,`${r}.json`)),i=le(e,r),o=P.join(i,"response-schema.json");if(await x.pathExists(o))return await x.readJson(o);let a=Ei(s);return a!==void 0&&(await x.ensureDir(i),await x.writeJson(o,a,{spaces:2})),a}async function Zt(e,t,r=!1,n,s,i,o=!1,a=!1,p=!1,c=!1){let u=await De(e,t,await ee(e,t),r),m=await B(),f=m.apis?.[e]?.baseUrl;if(!f)throw new Error("Base URL not found in config");if(u.schemaType==="graphql"){let O=await ee(e,t),M=await Kt(e,t,r),{requestJson:re,responseJsonPath:ye}=await hi(e,O,r||a,M),Be=P.join(j(e),O,"request.json"),At=re,nr=[];if(i&&i.length>0&&nr.push(...i),s&&typeof s=="object"&&Object.keys(s).length>0||o){let Tt={...s?Je(s):{}};for(let[Ve,Ln]of Object.entries(s??{}))Ve in Tt||(Tt[Ve]=Ln);await $e(Be,Tt,2,{deleteSentinel:ot,transform:o?Ve=>_r(Ve,M):void 0}),At=await x.readJson(Be)}let Nn={...li(u.args),...Xr(At)?At.variables:{}},Me={query:u.query,variables:Nn},$={headers:Mt({"Content-Type":"application/json"},m.apis?.[e]?.auth?.headers,n),url:"",warnings:nr,responseJsonPath:ye};$.headers=await Qr(e,f,$.headers,p);let Cn=new Fe(f,c),F;try{F=await Cn.post(f,{headers:$.headers,body:Me})}catch(we){if($.warnings.push(`\u26A0\uFE0F The live HTTP request failed for ${f}: ${we instanceof Error?we.message:String(we)}`),!await x.pathExists($.responseJsonPath))return $.warnings.push(`response.json not found at ${$.responseJsonPath}`),{request:Me,response:void 0,warnings:$.warnings}}if(F){(F.transport.status<200||F.transport.status>=300)&&$.warnings.push(`\u26A0\uFE0F The live HTTP request failed for ${f}: HTTP ${F.transport.status}${F.transport.statusText?` ${F.transport.statusText}`:""}`),F.body&&typeof F.body=="object"&&Array.isArray(F.body.errors)&&F.body.errors?.length&&$.warnings.push("\u26A0\uFE0F GraphQL response contains errors.");let we=await Br(e,F,$.responseJsonPath,p);return{request:Me,response:we,warnings:$.warnings}}let _n=await x.readJson($.responseJsonPath);return{request:Me,response:_n,warnings:$.warnings}}let g=await ee(e,t),l=await De(e,t,g);if(l.schemaType!=="rest")throw new Error(`Invalid REST endpoint metadata for '${t}'.`);let b=await W(e,t,g,r),{requestJson:y,responseJsonPath:h}=await tn(e,g,r||a),w=P.join(j(e),g,"request.json"),T=y,R=[];if(i&&i.length>0&&R.push(...i),s&&typeof s=="object"&&Object.keys(s).length>0||o){let O=s?ai(s):void 0;O&&R.push(O);let re={...s?Je(s):{}};for(let[ye,Be]of Object.entries(s??{}))ye in re||(re[ye]=Be);await $e(w,re,2,{deleteSentinel:ot,transform:o?ye=>jr(ye,b):void 0}),T=await x.readJson(w)}let A=yi(e,l,T,m,h,n,R),E=new Fe(f,c);if(!l.method||!l.path)throw new Error(`Invalid OpenAPI endpoint metadata for '${t}'.`);let _=new URL(A.url.replace(/^\//,""),f.endsWith("/")?f:`${f}/`).toString();A.headers=await Qr(e,_,A.headers,p);let L=l.method.toLowerCase(),S;try{switch(L){case"get":S=await E.get(A.url,{headers:A.headers});break;case"post":{let O=await Bt(b,T);S=await E.post(A.url,{headers:{...A.headers,...O.headers},body:O.body})}break;case"put":{let O=await Bt(b,T);S=await E.put(A.url,{headers:{...A.headers,...O.headers},body:O.body})}break;case"delete":S=await E.delete(A.url,{headers:A.headers});break;case"patch":{let O=await Bt(b,T);S=await E.patch(A.url,{headers:{...A.headers,...O.headers},body:O.body})}break;case"head":S=await E.head(A.url,{headers:A.headers});break;case"options":S=await E.options(A.url,{headers:A.headers});break;default:throw new Error(`Unsupported HTTP method: ${l.method}`)}}catch(O){if(A.warnings.push(`\u26A0\uFE0F The live HTTP request failed for ${f}${A.url}: ${O instanceof Error?O.message:String(O)}`),!await x.pathExists(A.responseJsonPath))return A.warnings.push(`response.json not found at ${A.responseJsonPath}`),{request:T,response:void 0,warnings:A.warnings}}if(S)return(S.transport.status<200||S.transport.status>=300)&&A.warnings.push(`\u26A0\uFE0F The live HTTP request failed for ${f}${A.url}: HTTP ${S.transport.status}${S.transport.statusText?` ${S.transport.statusText}`:""}`),{request:T,response:await Br(e,S,A.responseJsonPath,p),warnings:A.warnings};let te=await x.readJson(A.responseJsonPath);return{request:T,response:te,warnings:A.warnings}}async function Zr(e,t,r=!1,n,s,i,o=!1,a=!1,p=!1,c=!1){let{request:u,response:m,warnings:f}=await Zt(e,t,r,n,s,i,o,a,p,c),g=f??[],l=m&&typeof m=="object"&&!Array.isArray(m)?m:void 0,b=l?.transport&&typeof l.transport=="object"?l.transport:void 0,y=l&&b&&Object.prototype.hasOwnProperty.call(l,"body")?l.body:l&&typeof l.status=="number"?Object.fromEntries(Object.entries(l).filter(([_])=>!["status","statusText","_http","setCookies","headers"].includes(_))):m,h=typeof b?.status=="number"?b.status:typeof l?.status=="number"?l.status:void 0;if(await yt(e)==="graphql"){if(!y||typeof y!="object")return{valid:!1,warnings:g,errors:["response.body missing or invalid"]};let _=y;return Array.isArray(_.errors)&&_.errors.length>0?{valid:!1,warnings:g,errors:["GraphQL response contains errors"]}:{valid:!0,warnings:g}}let w=await Yt(e,t),T=h===void 0?w:await gi(e,t,h);if(T===void 0||Object.keys(T).length===0)return g.push(h===void 0?"No response schema found for this operation. Skipping validation.":`No response schema found for HTTP ${h}. Skipping validation.`),{valid:!0,warnings:g};if(y===void 0)return{valid:!1,warnings:g};let A=new ii({allErrors:!0,strict:!1,strictSchema:!1,allowUnknownKeywords:!0,removeAdditional:!1}).compile(T);return A(y)?{valid:!0,warnings:g}:{valid:!1,errors:(A.errors||[]).map(L=>`${L.instancePath?L.instancePath.replace(/^\//,"response.body.").replace(/\//g,"."):"response.body"} ${L.message}`),warnings:g}}function mi(e,t){let r=e.responses;if(!r||typeof r!="object"||Array.isArray(r))return;let n=r,s=n[String(t)]??n[`${Math.floor(t/100)}XX`]??n.default;if(!s||typeof s!="object"||Array.isArray(s))return;let i=s,o=i.content;if(o&&typeof o=="object"&&!Array.isArray(o)){let a=o,p=a["application/json"];if(p&&typeof p=="object"&&!Array.isArray(p)){let c=p.schema;if(c!==void 0)return c}for(let c of Object.values(a))if(c&&typeof c=="object"&&!Array.isArray(c)){let u=c.schema;if(u!==void 0)return u}}return i.schema}async function gi(e,t,r){let n=await ee(e,t),s=await at(P.resolve(j(e),`${n}.json`));return mi(s,r)}async function Ue(e,t,r=!1,n=!1){if(await yt(e)==="graphql"){let a=await Kt(e,t,r),p=P.join(j(e),t,"request.json"),c=P.join(le(e,t),"response.json"),u=_e(a);return await x.ensureDir(P.dirname(p)),await x.writeJson(p,u,{spaces:2}),{requestJsonPath:p,responseJsonPath:c,requestJson:u}}let{requestJson:s,responseJsonPath:i}=await tn(e,t,r||n);return{requestJsonPath:P.join(j(e),t,"request.json"),responseJsonPath:i,requestJson:s}}async function en(e,t,r){let n=await ee(e,t);if(!n)throw new Error(`Operation '${t}' was not found for API '${e}'.`);if(await yt(e)==="graphql")return ft(r,r);let s=await x.readJson(D(e)),i=Array.isArray(s)?s.find(u=>u.operationId===t):void 0;if(!i||typeof i.path!="string")throw new Error(`OpenAPI operation '${t}' was not found or has no request path.`);let o=await at(ne(e,n)),a=Se(e,n,"request"),p=await x.pathExists(a)?await x.readJson(a):void 0,c=rn(p)?p:sn(o);return ft(r,nn(i.path,c))}async function tn(e,t,r){let n=ne(e,t),s=await x.readJson(n),i=P.join(j(e),t);await x.ensureDir(i);let o=P.join(i,"request.json"),a=P.join(i,"response.json");if(await(async()=>{if(r||!await x.pathExists(o))return!0;let c=await x.readJson(o);return!rn(c)})()){let c=sn(s);return await x.writeJson(o,c,{spaces:2}),{requestJson:c,responseJsonPath:a}}return{requestJson:await x.readJson(o),responseJsonPath:a}}async function hi(e,t,r,n){let s=P.join(j(e),t);await x.ensureDir(s);let i=P.join(s,"request.json"),o=P.join(s,"response.json");if(await(async()=>{if(r||!await x.pathExists(i))return!0;let p=await x.readJson(i);return!Xr(p)})()){let p=_e(n);return await x.writeJson(i,p,{spaces:2}),{requestJson:p,responseJsonPath:o}}return{requestJson:await x.readJson(i),responseJsonPath:o}}function rn(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return Object.prototype.hasOwnProperty.call(t,"parameters")&&Array.isArray(t.parameters)}function yi(e,t,r,n,s,i,o=[]){let a=n.apis?.[e]?.auth?.headers,p=Mt(a,i);for(let c of r.parameters||[])c.in==="header"&&(p=Mt(p,{[c.name]:String(c.value)}));if(!t.path)throw new Error(`Invalid OpenAPI endpoint metadata for '${t.operationId}'.`);return{headers:p,url:nn(t.path,r),warnings:o,responseJsonPath:s}}function nn(e,t){let r={},n={};for(let s of t.parameters||[])s.in==="path"?r[s.name]=s.value:s.in==="query"&&(n[s.name]=s.value);return bi(e,r)+wi(n)}function Mt(...e){let t=new Map;for(let r of e)if(!(!r||typeof r!="object"||Array.isArray(r)))for(let[n,s]of Object.entries(r)){let i=n.toLowerCase(),o=t.get(i);t.set(i,{name:o?.name??n,value:s})}return Object.fromEntries(Array.from(t.values(),({name:r,value:n})=>[r,n]))}function wi(e){return Object.keys(e).length?"?"+Object.entries(e).map(([t,r])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(r))}`).join("&"):""}function sn(e){let t=[];if(Array.isArray(e.parameters))for(let s of e.parameters){let i=Er(s);t.push({name:s.name,in:s.in,value:i})}let r=null;(e?.requestBody||e?.parameters)&&(r=ki(e));let n={parameters:t};return r!==null&&(n.requestBody=r),n}function bi(e,t){return e.replace(/\{([^}]+)\}/g,(r,n)=>{if(!(n in t))throw new Error(`Missing path parameter: ${n}`);return encodeURIComponent(t[n])})}function ki(e){let t=Ai(e);if(t)return qe(t);let r=Vt(e);return r?qe(r):null}function Ai(e){let t=e?.requestBody?.content;if(!t||typeof t!="object")return null;for(let r of Object.values(t)){let n=r;if(n?.schema)return n.schema}return null}function Vt(e){let t=Array.isArray(e?.parameters)?e.parameters:[],r=t.find(o=>o.in==="body");if(r?.schema){let o=r.schema;return!o.type&&o.properties&&(o.type="object"),o}let n=e?.consumes||[],s=n.includes("application/x-www-form-urlencoded")||n.includes("multipart/form-data"),i=t.filter(o=>o.in==="formData");if(s&&i.length){let o={type:"object",properties:{},required:[]};for(let a of i){let p={};a.schema?Object.assign(p,a.schema):(a.type&&(p.type=a.type),a.items&&(p.items=a.items),a.format&&(p.format=a.format),a.enum&&(p.enum=a.enum),a.type==="file"&&(p.type="string",p.format="binary")),o.properties[a.name]=p,a.required&&o.required.push(a.name)}return o.required.length===0&&delete o.required,o}return null}function qe(e){if(!e)return null;if(e.const!==void 0)return e.const;if(e.default!==void 0)return e.default;if(Array.isArray(e.allOf)&&e.allOf.length>0){let t=e.allOf.map(r=>qe(r)).filter(r=>r!=null).reduce((r,n)=>on(r,n),{});if(t!=null)return t}if(Array.isArray(e.oneOf)&&e.oneOf.length>0)return zr(e.oneOf.map(t=>qe(t)));if(Array.isArray(e.anyOf)&&e.anyOf.length>0)return zr(e.anyOf.map(t=>qe(t)));if(!e.type&&e.properties&&(e.type="object"),e.$ref)throw new Error("Schema contains $ref. Resolve references before building template.");switch(e.type){case"string":return e.format==="binary"?{kind:"file",path:"",fileName:"",mimeType:""}:e.example??"";case"integer":case"number":return e.example??0;case"boolean":return e.example??!1;case"array":return[];case"object":let t={};if(e.properties)for(let[r,n]of Object.entries(e.properties))t[r]=qe(n);return t;default:return null}}function Ht(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function on(e,t){if(e==null)return t;if(t==null)return e;if(Ht(e)&&Ht(t)){let r={...e};for(let[n,s]of Object.entries(t))r[n]=n in r?on(r[n],s):s;return r}return t}function zr(e){let t=e.filter(n=>n!=null);if(t.length===0)return null;let r=t.filter(Ht);return r.length>0?r.reduce((n,s)=>{let i=Object.keys(n).length;return Object.keys(s).length>i?s:n}):t[0]}function Ti(e){let t=e?.responses;if(!t)return null;let r=t[200]||t[201]||t.default||Object.values(t)[0];if(!r?.content)return null;let n=r.content["application/json"];if(n?.schema)return n.schema;for(let s of Object.values(r.content)){let i=s;if(i.schema)return i.schema}return null}function xi(e){let t=e?.responses;return t?(t[200]||t[201]||t.default||Object.values(t)[0])?.schema||{}:{}}function Ei(e){let t=Ti(e);if(t)return t;let r=xi(e);if(r)return r}var er=I(()=>{"use strict";Rr();z();$t();Ot();me();gt();_t();Ft();Le();z();Pe();Lr();Gt()});import*as ae from"node:fs/promises";import U from"path";import Si from"readline";import{fileURLToPath as Ri}from"url";function je(e){return e?"Yes":"No"}function Pi(e){return Array.isArray(e)?e.join(`
|
|
9
|
+
`):e}function Oi(e){let t=e.arguments.length>0?e.arguments.map(s=>{let i=[s.type,s.required?"required":"optional"];s.positional&&i.push("positional"),s.flag&&i.push("flag");let o=s.description?`: ${s.description}`:"",a=s.flag?"--":"";return`- \`${s.positional?s.name:`${a}${s.name}`}\` (${i.join(", ")})${o}`}).join(`
|
|
10
10
|
`):"- None",r=e.examples.length>0?e.examples.map(s=>`- \`\`\`bash
|
|
11
11
|
${s}
|
|
12
12
|
\`\`\``).join(`
|
|
13
|
-
`):"- None",n=e.filesWritten.length>0?e.filesWritten.map(s=>`\`${s}\``).join(", "):"None";return[`### ${e.name}`,"",`**Category:** ${e.category}`,"","**Usage:**","```bash",e.usage,"```","",`**Description:** ${
|
|
14
|
-
`)}async function
|
|
13
|
+
`):"- None",n=e.filesWritten.length>0?e.filesWritten.map(s=>`\`${s}\``).join(", "):"None";return[`### ${e.name}`,"",`**Category:** ${e.category}`,"","**Usage:**","```bash",e.usage,"```","",`**Description:** ${Pi(e.description)}`,"","**Arguments:**",t,"","**Examples:**",r,"",`**Returns:** ${e.returns.type} - ${e.returns.description}`,"",`**Side Effects:** Writes Files: ${je(e.sideEffects.writesFiles)}, Reads Files: ${je(e.sideEffects.readsFiles)}, Network: ${je(e.sideEffects.network)}`,"",`**Constraints:** Destructive: ${je(e.constraints.destructive)}, Idempotent: ${je(e.constraints.idempotent)}, Requires Parsed API: ${je(e.constraints.requiresParsedApi)}`,"",`**Files Written:** ${n}`].join(`
|
|
14
|
+
`)}async function vi(){let{program:e}=await ln().then(()=>dn);return e.commands.filter(n=>!!n.agentMeta).filter(n=>n.agentMeta.name!=="help"&&n.agentMeta.name!=="install").map(n=>Oi(n.agentMeta)).join(`
|
|
15
15
|
|
|
16
|
-
`)}async function
|
|
17
|
-
https://openapi-skills.lemonsqueezy.com/`)}catch{}}var
|
|
18
|
-
`),payload:a}}var
|
|
16
|
+
`)}async function pn(e,t){let r=[{label:"~/.claude/skills/openapi-skills",value:U.join(e,".claude","skills","openapi-skills")},{label:"~/.cursor/skills/openapi-skills",value:U.join(e,".cursor","skills","openapi-skills")},{label:"~/.agents/skills/openapi-skills",value:U.join(e,".agents","skills","openapi-skills")},{label:"~/.github/skills/openapi-skills",value:U.join(e,".github","skills","openapi-skills")},{label:"Other (enter a custom path)",value:"__custom__"}];function n(i){let o=Si.createInterface({input:process.stdin,output:process.stderr});return new Promise(a=>o.question(i,p=>{o.close(),a(p)}))}d.info("Select install location:"),r.forEach((i,o)=>{d.info(` ${o+1}) ${i.label}`)});let s;for(;;){s=await n(`Enter number (1-${r.length}): `);let i=parseInt(s,10)-1;if(!isNaN(i)&&i>=0&&i<r.length&&r[i])return r[i].value==="__custom__"?(await n(`Enter custom install path [${t}]: `)).trim()||t:r[i].value;d.warn(`Invalid selection. Please enter a number between 1 and ${r.length}.`)}}async function an(e,t,r){let n=U.join(Ii,"../skill-templates",e);try{let s=await ae.readFile(n,"utf8"),i=r?await r(s):s;await ae.mkdir(U.dirname(t),{recursive:!0}),await ae.writeFile(t,i,"utf8")}catch(s){let i=s instanceof Error?s.message:String(s);throw new Error(`Failed to copy skill template "${e}" from "${n}" to "${t}": ${i}`,{cause:s instanceof Error?s:void 0})}}async function cn(e,t){await ae.mkdir(t,{recursive:!0});let r=U.join(t,"references");await ae.mkdir(r,{recursive:!0});let n=[{templateName:"SKILL.md",outputPath:U.join(t,"SKILL.md")},{templateName:"write-client-code.md",outputPath:U.join(r,"write-client-code.md")},{templateName:"create-endpoint-test.md",outputPath:U.join(r,"create-endpoint-test.md")},{templateName:"http-client.md",outputPath:U.join(r,"http-client.md")}];for(let s of n){if(s.templateName==="SKILL.md"){await an(s.templateName,s.outputPath,async i=>{let o=await vi();if(!i.includes("<command-list-here>"))throw new Error("SKILL.md template is missing <command-list-here>.");return i.replace("<command-list-here>",o)});continue}await an(s.templateName,s.outputPath)}return{destDir:t,files:n.map(s=>s.outputPath)}}var Ii,un=I(()=>{"use strict";xe();Ii=U.dirname(Ri(import.meta.url))});import fn from"fs-extra";import qi from"https";import ji from"os";import Ni from"path";async function mn(e){try{let t=new Date().toISOString().slice(0,10),r=Ni.join(ji.tmpdir(),`openapi-skills-session-${t}`);if(fn.existsSync(r))return;fn.writeFileSync(r,String(Date.now()));let n=await new Promise((s,i)=>{qi.get("https://registry.npmjs.org/@tzurp/openapi-skills/latest",o=>{let a="";o.on("data",p=>a+=p),o.on("end",()=>{try{let p=JSON.parse(a);s(p.version)}catch(p){i(p)}})}).on("error",i)});n&&n!==e&&(d.warn(`UPDATE_AVAILABLE: A newer version of openapi-skills is available \u2192 ${n} (current: ${e})`),d.warn("Update with: npm install -g @tzurp/openapi-skills")),d.banner(`\u{1F48E} openapi-skills v2 is available \u2014 including mock APIs, HTML docs, schema diffing, code\u2011first tools, full OpenAPI 3.1 support, premium support, and additional Pro tools.
|
|
17
|
+
https://openapi-skills.lemonsqueezy.com/`)}catch{}}var gn=I(()=>{"use strict";xe()});function Ge(e){let t=JSON.stringify(e)??"",r=Buffer.byteLength(t,"utf8");return{text:t,sizeBytes:r}}var hn=I(()=>{"use strict"});import Ci from"readline";async function yn(e){let t=`Are you sure you want to delete ${e}? Y/n `;return await new Promise(r=>{let n=Ci.createInterface({input:process.stdin,output:process.stderr});n.question(t,s=>{n.close();let i=s.trim().toLowerCase();r(i==="y"||i==="yes")})})}var wn=I(()=>{"use strict"});function Qe(e,t="",r=new Set){if(t&&r.add(t),!e||typeof e!="object")return r;if(Array.isArray(e)){for(let n=0;n<e.length;n++){let s=t?`${t}.${n}`:`${n}`;Qe(e[n],s,r)}return r}for(let[n,s]of Object.entries(e)){let i=t?`${t}.${n}`:n;Qe(s,i,r)}return r}function wt(e,t="",r=new Set){if(!e||typeof e!="object")return r;if(Array.isArray(e))return t&&r.add(t),r;for(let[n,s]of Object.entries(e)){let i=t?`${t}.${n}`:n;s&&typeof s=="object"&&!Array.isArray(s)?wt(s,i,r):r.add(i)}return r}function bn(e){let t=[];return e.request&&t.push("request"),e.response&&t.push("response"),e.responseSchema&&t.push("response-schema"),t.length!==1?{artifactName:void 0,error:t.length===0?"Exactly one of --request, --response, or --response-schema is required.":"Only one of --request, --response, or --response-schema can be used at a time."}:{artifactName:t[0],error:void 0}}var kn=I(()=>{"use strict"});import An from"fs-extra";function bt(e,t){let r=le(e,t);return{fileCount:An.existsSync(r)?An.readdirSync(r).length:0}}async function _i(e,t){let r=new Set,n=new Set;for(let o of t)r.has(o)&&n.add(o),r.add(o);if(n.size>0)throw new Error(`Duplicate operationId(s) are not allowed in prepare-only mode: ${Array.from(n).join(", ")}`);let s=await se();if(!Array.isArray(s)||!s.includes(e))throw new Error(`API '${e}' is not installed. Run generate first.`);let i=[];for(let o of t){let a=await Z(e,o);if(!a)throw new Error(`OperationId '${o}' was not found for API '${e}'.`);i.push({operationId:o,sanitizedOperationId:a})}return i}async function Tn(e,t,r=!1,n=!1){let s=await _i(e,t),i=[];for(let{operationId:p,sanitizedOperationId:c}of s){await W(e,p,c),await Ue(e,c,r,n);let u=bt(e,c);i.push({kind:"request-result",apiName:e,operationId:p,sanitizedOperationId:c,preparedOnly:!0,request:null,response:null,warnings:[],...u})}let o=[`Prepared request templates for ${i.length} operations:`,"",...i.map(p=>` \u2713 ${p.operationId}`),"","No live requests were executed.","Use `openapi-skills request <operationId> --force-request --update-request ...` with only flattened object dot-notation keys to reset the request template from the cached schema and run each step."],a={kind:"request-result",apiName:e,preparedOnly:!0,operationIds:t,summary:o,message:"No live requests were executed.",hint:"Use `openapi-skills request <operationId> --force-request --update-request ...` with only flattened object dot-notation keys to reset the request template from the cached schema and run each step.",operations:i};return{operations:i,summaryText:o.join(`
|
|
18
|
+
`),payload:a}}var xn=I(()=>{"use strict";Pe();me();gt();z();er()});function En(e){let t=e.trim();if(t==="count")return{kind:"count"};if(/^-?\d+$/.test(t))return{kind:"index",index:Number(t)};let r=t.match(/^(-?\d*):(-?\d*)$/);if(r)return{kind:"range",start:r[1]===""?0:Number(r[1]),end:r[2]===""?Number.POSITIVE_INFINITY:Number(r[2])};let n=t.indexOf("=");if(n>0){let s=t.slice(0,n).trim();if(s)return{kind:"path",path:s,value:t.slice(n+1)}}return{kind:"invalid"}}var Sn=I(()=>{"use strict"});function Li(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function kt(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be a non-empty base64url string.`);let r;try{r=Buffer.from(e,"base64url").toString("utf8")}catch{throw new Error(`${t} must be valid base64url-encoded JSON.`)}let n;try{n=JSON.parse(r)}catch(s){let i=s instanceof Error?s.message:String(s);throw new Error(`${t} decoded value must be valid JSON: ${i}`)}if(!Li(n))throw new Error(`${t} decoded value must be a JSON object.`);return n}var Rn=I(()=>{"use strict"});var In,Pn,tr=I(()=>{"use strict";In={UNKNOWN_API:{reason:"The API name is not registered in .openapi-skills/config.json.",nextCommandHint:"Run 'openapi-skills get-api-names' to list available APIs, then use the correct name."},API_SELECTION_REQUIRED:{reason:"More than one API is available, so an API name must be selected explicitly.",nextCommandHint:"Pass --api <apiName> using one of the listed API names."},MISSING_PARSED_API:{reason:"No APIs have been parsed yet. The workspace is empty.",nextCommandHint:"Run 'openapi-skills generate' with an OpenAPI or GraphQL source."},NO_ENDPOINTS_FOUND:{reason:"The API endpoint file does not exist. Run generate first.",nextCommandHint:"Run 'openapi-skills generate' to create endpoints.json."},NO_RESPONSE_SCHEMA:{reason:"The response schema artifact has not been created yet.",nextCommandHint:"Run 'openapi-skills request <operationId> --api <apiName>' to create the response-schema artifact."},REQUEST_TEMPLATE_STALE:{reason:"The request template does not exist for this operation.",nextCommandHint:"Run the command again with --force to regenerate the request template."},SCHEMA_VALIDATION_FAILED:{reason:"The provided OpenAPI or GraphQL schema is malformed.",nextCommandHint:"Fix the schema at its source and retry."},INVALID_FILTER_SYNTAX:{reason:"--filter requires the target to be an array.",nextCommandHint:"Use --response-schema first to inspect the response shape, then use --get to narrow the value before filtering."},MISSING_FILTER_ARGUMENT:{reason:"The list command requires at least one filter to avoid returning large, unbounded result sets.",nextCommandHint:"Add --path, --filter, --method, --root-type, or --index to narrow results."},SCHEMA_TYPE_MISMATCH:{reason:"The flag used is incompatible with this schema type.",nextCommandHint:"Use --path and --method for OpenAPI; use --root-type for GraphQL."},INVALID_JSON_ARGUMENT:{reason:"The provided JSON argument is malformed.",nextCommandHint:"Fix the JSON syntax and retry."},INVALID_VARIABLE_SYNTAX:{reason:"Variable syntax is invalid. Expected key=value format.",nextCommandHint:"Use --var key=value format."},INVALID_UPDATE_REQUEST_JSON:{reason:"The --update-request JSON could not be parsed.",nextCommandHint:"Fix the JSON syntax and retry."},INVALID_REQUEST_UPDATE:{reason:"The request keys specified do not exist in request.json.",nextCommandHint:"Use valid request.json keys. Inspect with 'openapi-skills get-operation <operationId> --api <apiName> --request' first."},OVERSIZED_OUTPUT:{reason:"The output is too large to display.",nextCommandHint:"Use --get or --filter to reduce output size."},API_PARSE_ERROR:{reason:"An error occurred while parsing the API schema.",nextCommandHint:"Review the error details and fix the schema at its source."},REQUEST_FAILED:{reason:"The HTTP request failed.",nextCommandHint:"Check the base URL, authentication headers, and network connectivity."},VALIDATION_FAILED:{reason:"The response does not match the expected schema.",nextCommandHint:"Verify that the API response matches the declared schema."},CONFIG_ERROR:{reason:"Failed to read or write configuration file.",nextCommandHint:"Check file permissions on .openapi-skills/config.json."}},Pn={UNKNOWN_API:"usage",API_SELECTION_REQUIRED:"usage",MISSING_FILTER_ARGUMENT:"usage",INVALID_FILTER_SYNTAX:"usage",SCHEMA_TYPE_MISMATCH:"usage",INVALID_VARIABLE_SYNTAX:"usage",INVALID_JSON_ARGUMENT:"usage",SCHEMA_VALIDATION_FAILED:"validation",INVALID_REQUEST_UPDATE:"validation",INVALID_UPDATE_REQUEST_JSON:"validation",MISSING_PARSED_API:"state",NO_ENDPOINTS_FOUND:"state",NO_RESPONSE_SCHEMA:"state",REQUEST_TEMPLATE_STALE:"state",OVERSIZED_OUTPUT:"state",API_PARSE_ERROR:"runtime",REQUEST_FAILED:"runtime",VALIDATION_FAILED:"runtime",CONFIG_ERROR:"runtime"}});function k(e,t){let r=Pn[e],n=In[e],s=t.nextCommand??"None",i=t.reason??n?.reason??"Unable to remediate automatically.",o=t.severity??"error";return{ok:!1,error:{code:e,category:r,severity:o,summary:t.summary,message:t.message,remediation:{required:!0,next_command:s,reason:i},context:t.context??{}}}}function q(e,t){let r={ok:!0,data:e};return t?.kind!==void 0&&(r.kind=t.kind),r}var On=I(()=>{"use strict";tr()});var dn={};Dn(dn,{program:()=>C});import{Command as $i}from"commander";import K from"fs-extra";import Di from"path";import Fi from"os";import{createRequire as Ji}from"module";function jn(e){d.result(k("CONFIG_ERROR",{summary:"Failed to list installed APIs.",message:H(e),context:{},nextCommand:"openapi-skills get-api-names"})),process.exitCode=1}async function Qi(e){let t;try{t=await se()}catch(r){return jn(r),!1}return t.includes(e)?!0:(d.result(k("UNKNOWN_API",{summary:`API '${e}' is not installed.`,message:`No API named '${e}' was found. Run 'openapi-skills get-api-names' to list installed APIs, or run 'openapi-skills generate <openapi-source>' first.`,context:{api_name:e},nextCommand:"openapi-skills get-api-names"})),process.exitCode=1,!1)}async function he(e){if(e!==void 0)return await Qi(e)?e:void 0;let t;try{t=await se()}catch(r){jn(r);return}if(t.length===1)return t[0];if(t.length===0){d.result(k("MISSING_PARSED_API",{summary:"No API is available.",message:"No API is available in this project. Generate an API first, then retry.",context:{api_names:t},nextCommand:"openapi-skills generate <openapi-source>"})),process.exitCode=1;return}d.result(k("API_SELECTION_REQUIRED",{summary:"An API must be selected.",message:`More than one API is available: ${t.join(", ")}. Pass --api <apiName> to choose one.`,context:{api_names:t},nextCommand:"openapi-skills get-api-names"})),process.exitCode=1}function Yi(e,t){if(!e||typeof e!="object"||Array.isArray(e))return t;let r=e,n=r.transport;return!Object.prototype.hasOwnProperty.call(r,"body")||!n||typeof n!="object"||Array.isArray(n)||t==="body"||t==="transport"||t.startsWith("body.")||t.startsWith("transport.")?t:ve(n,t)!==void 0?`transport.${t}`:`body.${t}`}function vn(e,t){let r=new URL(e),n=new URL(t??e,r);if(n.origin!==r.origin)throw new Error("Cookie target URL must use the configured API base URL origin.");return n.toString()}var Ui,rr,Gi,vp,C,qn,Bi,Mi,Vi,Hi,zi,Wi,Ki,Xi,Zi,eo,to,ro,no,so,ln=I(async()=>{Pe();z();me();$t();er();un();Pe();xe();Dt();gt();gn();hn();wn();kn();xn();Ft();Sn();Rn();Gt();On();tr();Le();Ui=Ji(import.meta.url),rr=Ui("../package.json"),Gi=rr.repository.url;await mn(rr.version);vp=ct(),C=new $i,qn=process.argv.includes("--silent");C.name("openapi-skills").description("A command\u2011line tool for working with OpenAPI/Swagger and GraphQL specs. Use it to parse specs into artifacts, explore API endpoints and root fields, validate requests, generate typed client metadata, and teach AI agents how to operate the CLI and write API tests and client code.").version(rr.version);Bi=`
|
|
19
19
|
\x1B[32m
|
|
20
20
|
\u2584\u2584\u2584 \u2584\u2584\u2584\u2584 \u2584\u2584\u2584\u2584\u2584 \u2584\u2584 \u2584\u2584 \u2584\u2584\u2584 \u2584\u2584\u2584\u2584 \u2584\u2584 \u2584\u2584\u2584\u2584 \u2584\u2584 \u2584\u2584 \u2584\u2584 \u2584\u2584 \u2584\u2584 \u2584\u2584\u2584\u2584
|
|
21
21
|
\u2588\u2588\u2580\u2588\u2588 \u2588\u2588\u2584\u2588\u2580 \u2588\u2588\u2584\u2584 \u2588\u2588\u2588\u2584\u2588\u2588 \u2588\u2588\u2580\u2588\u2588 \u2588\u2588\u2584\u2588\u2580 \u2588\u2588 \u2584\u2584\u2584 \u2588\u2588\u2588\u2584\u2584 \u2588\u2588\u2584\u2588\u2580 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588\u2588\u2584\u2584
|
|
22
22
|
\u2580\u2588\u2588\u2588\u2580 \u2588\u2588 \u2588\u2588\u2584\u2584\u2584 \u2588\u2588 \u2580\u2588\u2588 \u2588\u2588\u2580\u2588\u2588 \u2588\u2588 \u2588\u2588 \u2584\u2584\u2588\u2588\u2580 \u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588\u2584\u2584\u2584 \u2588\u2588\u2584\u2584\u2584 \u2584\u2584\u2588\u2588\u2580
|
|
23
23
|
\x1B[0m
|
|
24
|
-
`;
|
|
24
|
+
`;C.option("--silent","Hide the banner and Pro feature summary in help output for agent-friendly usage.");qn||C.addHelpText("before",Bi);C.addHelpText("before",`
|
|
25
25
|
===================
|
|
26
26
|
openapi-skills CLI
|
|
27
27
|
===================
|
|
28
|
-
`);
|
|
28
|
+
`);Mi=2026,Vi=new Date().getFullYear(),Hi=`${Mi}-${Vi}`;qn||C.addHelpText("after",`
|
|
29
29
|
\x1B[35m
|
|
30
30
|
-------------------------------------------------------------------------------
|
|
31
31
|
openapi-skills Pro-only commands:
|
|
@@ -45,13 +45,13 @@ Pro-only options on shared commands:
|
|
|
45
45
|
Learn more: https://github.com/tzurp/openapi-skills-pro
|
|
46
46
|
-------------------------------------------------------------------------------
|
|
47
47
|
\x1B[0m
|
|
48
|
-
`);
|
|
48
|
+
`);C.addHelpText("after",`
|
|
49
49
|
-------------------------------------------------------------------------------
|
|
50
|
-
Copyright \xA9 ${
|
|
50
|
+
Copyright \xA9 ${Hi} Tzur Paldi \u2014 Powered by Bedekbyte\xAE All rights reserved
|
|
51
51
|
Support: tzur.paldi@outlook.com
|
|
52
|
-
Project: ${
|
|
52
|
+
Project: ${Gi}
|
|
53
53
|
-------------------------------------------------------------------------------
|
|
54
|
-
`);
|
|
54
|
+
`);C.command("install").description("Install SKILL.md and scenario markdowns for agent frameworks like Claude and GitHub Copilot. Supports: --skills [--global].").option("--skills","Install SKILL.md files for agent frameworks.").option("--global","Install the skill bundle under the user's home directory instead of the current project.").action(async e=>{if(e.global&&!e.skills){d.result(k("CONFIG_ERROR",{summary:"--global requires --skills.",message:"Use `openapi-skills install --skills --global` to install the skill bundle under your home directory.",context:{},nextCommand:"openapi-skills install --skills --global"})),process.exitCode=1;return}if(!e.skills){await qt(),d.info(".openapi-skills directory and configuration installed. Use --skills to install SKILL.md files for agent frameworks.");return}let t=e.global?Fi.homedir():ut(),r=ut(),n=Di.join(t,"installed-skills");d.info(`Source directory (copied): ${r}`);let s=await pn(t,n);d.info(`Target install directory: ${s}`);try{let i=await cn(r,s);d.info("openapi-skills skill bundle installed")}catch(i){d.result(k("CONFIG_ERROR",{summary:"Failed to install skill bundle.",message:i instanceof Error?i.message:String(i),context:{install_path:s},nextCommand:"openapi-skills install --skills"})),process.exitCode=1}});zi=C.command("generate [openapi-source]").description("Parse an OpenAPI 2.0, OpenAPI 3.0.x, or GraphQL source (file path or URL) and generate endpoints.json, schemas/, and config.json. OpenAPI 3.1.0 and later are not supported. Run this command first for a new spec. Supports: --validate, --base-url, --dereference, --no-progress.").option("--validate <schema>","Validate an OpenAPI or GraphQL schema (file path or URL) and exit").option("--base-url <url>","Base URL for the API").option("--dereference","Fully dereference the entire OpenAPI document before processing endpoints").option("--no-progress","Disable the progress indicator").option("--rename <newName>","Optional new name for the generated schema.").action(async(e,t)=>{try{if(typeof t.validate=="string"&&t.validate.length>0){try{await xr(t.validate),d.result(q({valid:!0,schemaSource:t.validate,message:"Schema is valid"},{kind:"schema-validation"})),process.exitCode=0}catch(o){d.result(k("SCHEMA_VALIDATION_FAILED",{summary:"OpenAPI or GraphQL schema is invalid.",message:`Schema validation failed: ${H(o)}`,context:{schema_source:t.validate},nextCommand:`openapi-skills generate ${t.validate}`})),process.exitCode=1}return}if(!e)throw new Error("An OpenAPI source is required unless --validate is used.");let r=typeof t.baseUrl=="string"?t.baseUrl.trim():"",n=r.length>0,i=await Tr(e,n?r:"",{dereference:t.dereference===!0,progress:t.progress!==!1,rename:t.rename});if(!n){let o=[`You haven't included --base-url for API "${i}".`,`If you need to make requests and validations, add baseUrl directly to .openapi-skills/config.json under apis.${i}.baseUrl.`,"Example:",`{
|
|
55
55
|
"apis": {
|
|
56
56
|
"${i}": {
|
|
57
57
|
"baseUrl": "https://petstore3.swagger.io/api/v3",
|
|
@@ -59,13 +59,13 @@ Project: ${pi}
|
|
|
59
59
|
}
|
|
60
60
|
}
|
|
61
61
|
}`].join(`
|
|
62
|
-
`);d.warn(o),d.result(q({apiName:i,openapiSource:e,warning:o},{kind:"generate-warning"}))}d.result(q({apiName:i,openapiSource:e,fileCount:3},{kind:"generate-result"})),process.exitCode=0}catch(r){if(
|
|
63
|
-
`),(e,t)=>[...Array.isArray(t)?t:t?[t]:[],e]).option("--filter <filterPattern>","Filter operations by any of their searchable properties. Supports AND/OR (use spaces for AND, | for OR), e.g. --filter 'create account|register user'.").option("--tag <tag>","Filter OpenAPI operations by an exact tag, case-insensitive.").option("--method <method>","Filter operations by HTTP method (GET, POST, etc). Use this for OpenAPI operations.").option("--root-type <rootType>","Filter GraphQL root fields by root type (query, mutation, or subscription).").option("--index <range>","Slice the filtered results with inclusive Python-like range syntax, e.g. 0:10, 5:, :10, -1, or :").action(async e=>{let t=e.api;if(
|
|
62
|
+
`);d.warn(o),d.result(q({apiName:i,openapiSource:e,warning:o},{kind:"generate-warning"}))}d.result(q({apiName:i,openapiSource:e,fileCount:3},{kind:"generate-result"})),process.exitCode=0}catch(r){if(lr(r)){d.result(k("API_PARSE_ERROR",{summary:"TypeScript is required to analyze builder GraphQL schemas.",message:`TypeScript is not available in this environment. Install it with \`${Pt}\` and rerun the command.`,context:{openapi_source:e},nextCommand:Pt,reason:"GraphQL builder parsing requires TypeScript to be installed in the current workspace."})),process.exitCode=1;return}d.result(k(t.validate?"SCHEMA_VALIDATION_FAILED":"API_PARSE_ERROR",{summary:t.validate?"OpenAPI or GraphQL schema is invalid.":"Failed to parse the provided schema.",message:H(r),context:{openapi_source:e},nextCommand:t.validate?`openapi-skills generate ${t.validate}`:`openapi-skills generate ${e??"<openapi-source>"}`})),process.exitCode=1}});zi.agentMeta={name:"generate",category:"Generation",usage:"openapi-skills generate [openapi-source] [--validate <schema>] [--base-url <url>] [--dereference] [--no-progress] [--rename <newName>]",description:"Parse an OpenAPI 2.0, OpenAPI 3.0.x, or GraphQL source file or URL and generate the API artifacts used by the rest of the CLI. OpenAPI 3.1.0 and later are not supported. Use --validate to check a schema and exit, --base-url to set the API base URL, --dereference when full dereferencing is appropriate, --rename to override the generated API name, and --no-progress to suppress progress output.",arguments:[{name:"openapi-source",type:"path|url",required:!1,positional:!0,description:"OpenAPI source file path or URL."},{name:"validate",type:"path|url",required:!1,flag:!0,description:"Validate an OpenAPI schema and exit."},{name:"base-url",type:"string",required:!1,flag:!0,description:"Base URL for the generated API."},{name:"dereference",type:"boolean",required:!1,flag:!0,description:"Fully dereference the OpenAPI document before processing endpoints."},{name:"no-progress",type:"boolean",required:!1,flag:!0,description:"Disable the progress indicator."},{name:"rename",type:"string",required:!1,flag:!0,description:"Optional new name for the generated schema."}],examples:["openapi-skills generate ./petstore.yaml --base-url https://api.example.com","openapi-skills generate https://example.com/openapi.yaml","openapi-skills generate ./petstore.yaml --validate ./petstore.yaml","openapi-skills generate ./petstore.yaml --dereference","openapi-skills generate ./petstore.yaml --rename petstore-v2","openapi-skills generate ./petstore.yaml --no-progress"],returns:{type:"json",description:"Prints output directory and config.json path."},sideEffects:{writesFiles:!0,readsFiles:!0,network:!0},constraints:{destructive:!1,idempotent:!1,requiresParsedApi:!1},filesWritten:["endpoints.json","schemas/","config.json"]};Wi=C.command("list").description("List summarized operation objects for the specified API as JSON. Supports --filter, --tag, --resolved/--dereferenced, --index slicing, and --count for operation totals. Also supports OpenAPI\u2011only options (--path, --method) and the GraphQL\u2011only option (--root-type). At least one filter is required unless --index : is used intentionally. GraphQL APIs reject --method, --path, and --tag, and OpenAPI APIs reject --root-type.").option("--api <apiName>","API name to use. Optional when exactly one API is installed.").option("--count","Return the number of operations after applying any list filters and index slicing. With no filters, returns the total operation count.").option("--resolved, --dereferenced","Show only operations that already have generated schema details saved.").option("--path <path>",["Filter operations by path structure. Repeatable; multiple values are ANDed.","Supports:"," - Path prefix: /users (matches operations whose path begins with /users)"," - Parameter detection: :param (matches operations with any {param} in the path)"," - Segment matching: 'store order' (matches operations whose path contains BOTH 'store' AND 'order' as segments, in any order)"," - OR within a clause: 'store|shop' (matches operations whose path contains EITHER 'store' OR 'shop')"," - Combined AND+OR: 'store order|shop item' (matches endpoints with both 'store' and 'order', OR both 'shop' and 'item')"," - Multiple --path flags are ANDed: --path /store --path order (matches endpoints starting with /store AND containing 'order')","","Examples:"," --path /users"," --path :param"," --path 'store order'"," --path 'store|shop'"," --path /store --path order"].join(`
|
|
63
|
+
`),(e,t)=>[...Array.isArray(t)?t:t?[t]:[],e]).option("--filter <filterPattern>","Filter operations by any of their searchable properties. Supports AND/OR (use spaces for AND, | for OR), e.g. --filter 'create account|register user'.").option("--tag <tag>","Filter OpenAPI operations by an exact tag, case-insensitive.").option("--method <method>","Filter operations by HTTP method (GET, POST, etc). Use this for OpenAPI operations.").option("--root-type <rootType>","Filter GraphQL root fields by root type (query, mutation, or subscription).").option("--index <range>","Slice the filtered results with inclusive Python-like range syntax, e.g. 0:10, 5:, :10, -1, or :").action(async e=>{let t=await he(e.api);if(t)try{let r=D(t),n=await Wt(t),s=e.resolved===!0||e.dereferenced===!0,i=!!(e.path||e.filter||e.tag||e.method||e.rootType||e.index||s),o={};if((typeof e.path=="string"||Array.isArray(e.path))&&(o.path=e.path),typeof e.filter=="string"&&(o.filter=e.filter),typeof e.tag=="string"&&(o.tag=e.tag),typeof e.method=="string"&&(o.method=e.method),typeof e.rootType=="string"&&(o.rootType=e.rootType),n==="graphql"&&(typeof e.method=="string"||typeof e.path=="string"||typeof e.tag=="string")){d.result(k("SCHEMA_TYPE_MISMATCH",{summary:"--method, --path, and --tag are only valid for OpenAPI APIs.",message:"This API is GraphQL. Use --root-type with --filter instead.",context:{api_name:t,schema_type:n},nextCommand:`openapi-skills list --api ${t} --root-type query`})),process.exitCode=2;return}if(n==="openapi"&&typeof e.rootType=="string"){d.result(k("SCHEMA_TYPE_MISMATCH",{summary:"--root-type is only valid for GraphQL APIs.",message:"This API is OpenAPI. Use --method and --path or --filter instead.",context:{api_name:t,schema_type:n},nextCommand:`openapi-skills list --api ${t} --method GET`})),process.exitCode=2;return}if(!e.count&&!i){d.result(k("MISSING_FILTER_ARGUMENT",{summary:"No filter provided. Use --path, --filter, --tag, --method, --root-type, or --index.",message:"The list command requires at least one filter to avoid returning large, unbounded result sets.",context:{api_name:t},nextCommand:`openapi-skills list --api ${t} --index :`,severity:"warning"})),process.exitCode=0;return}if(K.existsSync(r)===!1){if(e.count){d.result(q({count:0,message:`No endpoints.json found for API "${t}".`},{kind:"endpoint-count"}));return}d.result(k("NO_ENDPOINTS_FOUND",{summary:`No endpoints.json found for API "${t}".`,message:"The API has not been parsed yet. Run 'openapi-skills generate' to create it.",context:{api_name:t},nextCommand:`openapi-skills generate <openapi-source> --rename ${t}`,reason:"The API artifacts have not been generated."})),d.warn(`No endpoints found for "${t}". This API name may be misspelled or not generated yet. (openapi-skills generate <openapi-source> [options])`);return}let a=await K.readJson(r),p=mt(a,o);s&&(p=await Or(t,p)),p=Pr(p,e.index);let c=p.map(({tags:u,...m})=>m);if(e.count){d.result(q({count:p.length,apiName:t},{kind:"endpoint-count"}));return}if(p.length===0){if(d.result(q({apiName:t,items:[]},{kind:"endpoint-list"})),e.path||e.filter||e.tag||e.method||e.rootType||e.index||s){let u=Array.isArray(e.path)?e.path.join(", "):e.path,m=u?`path "${u}"`:"",f=e.filter?`filter "${e.filter}"`:"",g=e.tag?`tag "${e.tag}"`:"",l=e.method?`method "${e.method}"`:"",b=e.rootType?`rootType "${e.rootType}"`:"",y=s?"resolve":"",h=e.index?`index "${e.index}"`:"",w=[m,f,g,l,b,y,h].filter(Boolean).join(", ");d.warn(`No endpoints matched the ${w}.`)}return}d.result(q({apiName:t,items:c},{kind:"endpoint-list"}))}catch(r){d.result(k("API_PARSE_ERROR",{summary:"Error listing endpoints.",message:H(r),context:{api_name:t}})),process.exitCode=1}});Wi.agentMeta={name:"list",category:"Navigation",usage:"openapi-skills list [--api <apiName>] [--count] [--resolved|--dereferenced] [--path <path>]... [--filter <pattern>] [--tag <tag>] [--method <method>] [--root-type <rootType>] [--index <range>]",description:["List operation summaries for a parsed API as JSON. --api is optional only when exactly one API is installed.","At least one filter is required. --index is treated as a filter input, so the command can run when only a slice is requested.","Use --count to return the number of operations after filtering and slicing, or --resolved to show only operations that already have generated schema details saved.","Filter usage differs by schema type: use --method, --path, and --tag for OpenAPI operations, use --root-type for GraphQL root fields, and use --filter and --index with either schema. Filtering is case-insensitive and supports:","- Path prefix: --path '/users' (matches operations whose path begins with the prefix)","- Parameter detection: --path :param (matches operations that contain at least one '{...}' path placeholder)","- Segment matching: --path 'store order' (matches endpoints whose path contains both segments)","- OR within a single path clause: --path 'store|shop' (matches either segment)","- Multiple path flags are ANDed: --path /store --path order","- Exact tag matching: --tag pet (matches OpenAPI operations whose tag is exactly 'pet', ignoring case)","- Simple substring filtering: --filter 'user account' (matches operations containing both 'user' and 'account' in any field, including GraphQL name/rootType fields)","- OR filtering: --filter 'create|register|signup' (matches any operation containing any of the words)","- Combined AND+OR: --filter 'create account|register user' (matches operations containing both 'create' and 'account', OR both 'register' and 'user')","- Path substring search: --filter '/users' (matches operations whose path contains the substring)","- OperationId: --filter 'getUser' (matches operationId field)","- Summary/description: --filter 'delete permanently'","- Method filtering: --method GET (OpenAPI only; can be combined with --path and/or --filter)","- GraphQL root type filtering: --root-type query (query, mutation, or subscription)","- Index slicing: --index 0:10, --index 5:, --index :10, --index -1, --index :"," Slices the filtered results using inclusive Python-like range syntax:"," N = only the Nth item (0-based, negative counts from end)"," start:end = all items from start to end, inclusive"," start: = from start to last"," :end = from first to end"," : = all items"," Negative indices count from the end (e.g., -1 is the last item, -2 is second-to-last)."," Examples:"," --index 0:2 (first three items)"," --index 5: (from 6th to last)"," --index :3 (first four items)"," --index -1 (last item)"," --index : (all items)"," --count (return the filtered/sliced endpoint count, or the total count when no filters are used)",`
|
|
64
64
|
`,"Use --path for path-aware matching. Use --filter for substring matching across path, operationId/name, rootType, summary, or description.","If no operations match, outputs [] and prints a message to stderr."].join(`
|
|
65
|
-
`),arguments:[{name:"api",type:"string",required:!
|
|
66
|
-
`),arguments:[{name:"operationId",type:"string",required:!0,positional:!0,description:"The operationId of the endpoint to describe."},{name:"api",type:"string",required:!0,flag:!0,description:"The API name as defined in .openapi-skills/config.json."},{name:"force",type:"flag",required:!1,flag:!0,description:"Overwrite the cached schema file before printing the raw schema."}],examples:["openapi-skills describe getPetById --api petstore","openapi-skills describe deletePet --api petstore","openapi-skills describe getPetById --api petstore --force"],returns:{type:"json",description:"Structured JSON with a fallback warning and the raw OpenAPI schema nested under `schema`."},sideEffects:{writesFiles:!1,readsFiles:!0,network:!1},constraints:{destructive:!1,idempotent:!0,requiresParsedApi:!0},filesWritten:[]};yi=j.command("get-operation <operationId>").alias("get-operation-artifact").requiredOption("--api <apiName>","API name to use").option("--request","Return request artifact for the operation.").option("--response","Return response artifact for the operation.").option("--response-schema","Return response-schema artifact for the operation. Inspect this first when the response shape is unknown.").option("--get <path>","Select a nested value by dot-notation path first. Inspect --response-schema first so the path matches the actual response shape.").option("--filter <expr>","Filter the selected value using count, index, range, or <path>=<value> syntax (e.g. count, 0, 0:10, status=sold). Select path first with --get, then filter or slice the selected value.").description("Return one stored operation artifact as JSON. Run `request` first for the same operationId so the artifact exists. Exactly one of --request, --response, or --response-schema is required. Select path first with --get, then apply --filter to the selected value. Use --response-schema first when the response shape is unknown.").action(async(e,t)=>{let r=t.api;if(!await fe(r))return;let n=Kr(t),s=await X(r,e);if(n.error||!n.artifactName){d.result(w("INVALID_REQUEST_UPDATE",{summary:"Invalid operation artifact selection.",message:n.error??"Invalid operation artifact selection.",context:{api_name:r,operation_id:e},nextCommand:`openapi-skills get-operation ${e} --api ${r} --request`})),process.exitCode=1;return}let i=tt(r,s,n.artifactName);if(!await M.pathExists(i)){if(n.artifactName==="response-schema"){d.result(w("NO_RESPONSE_SCHEMA",{summary:"No response schema artifact exists for this operation.",message:"The response schema has not been created yet.",context:{api_name:r,operation_id:e,artifact_type:"response-schema"},nextCommand:`openapi-skills request ${e} --api ${r}`,reason:"Make a request first to generate the response-schema artifact."})),process.exitCode=1;return}d.result(w("REQUEST_TEMPLATE_STALE",{summary:`Artifact '${n.artifactName}' is missing for this operation.`,message:`The '${n.artifactName}' artifact does not exist yet.`,context:{api_name:r,operation_id:e,artifact_type:n.artifactName},nextCommand:`openapi-skills request ${e} --api ${r}`})),process.exitCode=1;return}try{let o=await M.readJson(i),a=typeof t.get=="string"?t.get:void 0,p=typeof t.filter=="string"?t.filter:void 0,c=typeof a=="string"&&a.length>0,u=typeof p=="string"&&p.length>0,m=c?_e(o,a):o;if(c&&!u){let{sizeBytes:l}=$e(m);l>=51200?d.result(w("OVERSIZED_OUTPUT",{summary:"Output is too large to display.",message:`The selected value is ${l} bytes, exceeding the limit of ${51200} bytes.`,context:{api_name:r,operation_id:e,artifact_type:n.artifactName,size_bytes:l},nextCommand:`openapi-skills get-operation ${e} --api ${r} --${n.artifactName} --get ${a} --filter count`})):d.result(q({apiName:r,value:m},{kind:"artifact-value"}));return}if(u){let l=m,g=[];!Array.isArray(l)&&l!==null&&typeof l=="object"&&(g=Object.values(l).filter(y=>Array.isArray(y)),g.length===1&&(l=g[0]));let b=tn(p),T;if(b.kind==="count"||b.kind==="index"||b.kind==="range"){if(!Array.isArray(l))if(g.length===1)l=g[0];else{d.result(w("INVALID_FILTER_SYNTAX",{summary:"--filter requires the target to be an array.",message:"The selected value is not an array and contains no single array field to unwrap.",context:{api_name:r,operation_id:e,artifact_type:n.artifactName,filter:p,selected_path:c?a:void 0},nextCommand:`openapi-skills get-operation ${e} --api ${r} --${n.artifactName} --response-schema`})),process.exitCode=1;return}if(!Array.isArray(l)){d.result(w("INVALID_FILTER_SYNTAX",{summary:"--filter requires the target to be an array.",message:"The selected value is not an array.",context:{api_name:r,operation_id:e,artifact_type:n.artifactName,filter:p,selected_path:c?a:void 0},nextCommand:`openapi-skills get-operation ${e} --api ${r} --${n.artifactName}`})),process.exitCode=1;return}if(b.kind==="count")T=l.length;else if(b.kind==="index"){let y=b.index<0?l.length+b.index:b.index;T=l[y]}else T=l.slice(b.start,b.end)}else if(b.kind==="path"){let y=b.path,P=b.value;if(c&&!Array.isArray(l)){d.result(w("INVALID_FILTER_SYNTAX",{summary:"--filter requires the --get result to be an array.",message:`The value at path '${a}' is not an array.`,context:{api_name:r,operation_id:e,artifact_type:n.artifactName,filter:p,selected_path:a},nextCommand:`openapi-skills get-operation ${e} --api ${r} --${n.artifactName} --response-schema`})),process.exitCode=1;return}if(!Array.isArray(l)){let{sizeBytes:O}=$e(l);O>=51200?d.result(w("OVERSIZED_OUTPUT",{summary:"Output is too large to display.",message:`The selected value is ${O} bytes, exceeding the limit of ${51200} bytes.`,context:{api_name:r,operation_id:e,artifact_type:n.artifactName,size_bytes:O},nextCommand:`openapi-skills get-operation ${e} --api ${r} --${n.artifactName} --filter count`})):d.result(q({apiName:r,value:l},{kind:"artifact-value"}));return}T=Ar(l,y,P)}else{d.result(w("INVALID_FILTER_SYNTAX",{summary:"Invalid --filter syntax.",message:"--filter must use count, index, range, or <path>=<value> syntax.",context:{api_name:r,operation_id:e,artifact_type:n.artifactName,filter:p},nextCommand:`openapi-skills get-operation ${e} --api ${r} --${n.artifactName} --filter 0`})),process.exitCode=1;return}let{sizeBytes:h}=$e(T);h>=51200?d.result(w("OVERSIZED_OUTPUT",{summary:"Output is too large to display.",message:`The filtered result is ${h} bytes, exceeding the limit of ${51200} bytes.`,context:{api_name:r,operation_id:e,artifact_type:n.artifactName,size_bytes:h},nextCommand:`openapi-skills get-operation ${e} --api ${r} --${n.artifactName} --filter count`})):d.result(q({apiName:r,value:T},{kind:"artifact-value"}));return}let{sizeBytes:f}=$e(o);f>=51200?d.result(w("OVERSIZED_OUTPUT",{summary:"Output is too large to display.",message:`The artifact is ${f} bytes, exceeding the limit of ${51200} bytes.`,context:{api_name:r,operation_id:e,artifact_type:n.artifactName,size_bytes:f},nextCommand:`openapi-skills get-operation ${e} --api ${r} --${n.artifactName} --get <path> --filter count`})):d.result(q({apiName:r,operationId:e,artifact:o},{kind:"artifact"}))}catch(o){d.result(w("API_PARSE_ERROR",{summary:`Failed to read artifact '${n.artifactName}'.`,message:W(o),context:{api_name:r,operation_id:e,artifact_type:n.artifactName}})),process.exitCode=1}});yi.agentMeta={name:"get-operation",category:"Navigation",usage:"openapi-skills get-operation|get-operation-artifact <operationId> --api <apiName> [--request] [--response] [--response-schema] [--get <path>] [--filter count|<index>|<range>|<path>=<value>]",description:"Return a stored operation artifact created by `openapi-skills request` as raw JSON. Run `request` first so the artifact exists. Use --get to select a nested value, then --filter to count, slice, or match values. Use --response-schema first when the response shape is unknown. Exactly one of --request, --response, or --response-schema is required. Alias: `get-operation-artifact`.",arguments:[{name:"operationId",type:"string",required:!0,positional:!0,description:"The operationId whose stored artifact should be returned."},{name:"api",type:"string",required:!0,flag:!0,description:"The API name as defined in .openapi-skills/config.json."},{name:"request",type:"flag",required:!1,flag:!0,description:"Return request artifact for the operation."},{name:"response",type:"flag",required:!1,flag:!0,description:"Return response artifact for the operation."},{name:"response-schema",type:"flag",required:!1,flag:!0,description:"Return response-schema artifact for the operation. Inspect this first when the response shape is unknown."},{name:"get",type:"string",required:!1,flag:!0,description:"Select a nested value by dot-notation path first. Inspect get-operation --response-schema first so the path matches the actual response shape."},{name:"filter",type:"string",required:!1,flag:!0,description:"Filter the selected value using count, index, range, or <path>=<value> syntax. Examples: --filter count, --filter 0, --filter 0:10, --filter status=sold. Select path first with --get, then filter or slice the selected value."}],examples:["openapi-skills request getPetById --api petstore --force","openapi-skills get-operation getPetById --api petstore --request","openapi-skills get-operation-artifact getPetById --api petstore --request","openapi-skills get-operation getPetById --api petstore --response-schema","openapi-skills get-operation-artifact getPetById --api petstore --response-schema","openapi-skills get-operation getPetById --api petstore --response","openapi-skills get-operation-artifact getPetById --api petstore --response","openapi-skills get-operation getPetById --api petstore --response --get name","openapi-skills get-operation getPetById --api petstore --response --get body --filter id=555","openapi-skills get-operation getPetById --api petstore --response --filter id=5555","openapi-skills get-operation getPetById --api petstore --response --filter count","openapi-skills get-operation getPetById --api petstore --response --filter 0","openapi-skills get-operation getPetById --api petstore --response --filter 0:10"],returns:{type:"json",description:"Returns the selected artifact as raw JSON, or a nested value / filtered array when --get or --filter is supplied. When both are used, --get runs first and --filter applies to the narrowed result. Inspect --response-schema first when the response shape is unknown so --get and --filter can be applied in the right order. --filter can also return an array count, single item, or slice when the selected target is an array."},sideEffects:{writesFiles:!1,readsFiles:!0,network:!1},constraints:{destructive:!1,idempotent:!0,requiresParsedApi:!0},filesWritten:[]};wi=j.command("request <operationId...>").description("Make a live HTTP request for a specific operation, or prepare a multi-step request scenario without executing requests. Supports: --validate (validate only the response against the schema after the request is sent; it does not validate request bodies or guarantee a response exists), --force (refresh operation schema and regenerate request artifact), --force-request (regenerate only request artifact from the cached operation schema), --update-request (patch request artifact using flattened dot-notation keys; binary fields can be file paths or {kind:'file', path,...} descriptors), --update-request-encoded (patch request artifact using base64url-encoded JSON), --omit-empty (remove empty-string values from schema-optional request fields before sending), --header (add headers), --header-encoded (add headers using base64url-encoded JSON).").requiredOption("--api <apiName>","API name to use").option("--validate","Validate only the response against the schema after the request is sent. Does not validate the request body or guarantee a response exists.").option("--omit-empty","For single-operation requests, remove empty-string values from schema-optional fields before sending and persist the cleaned artifact.").option("--force","Refresh the operation schema and overwrite the request artifact with defaults.").option("--force-request","Force overwrite only the request artifact with defaults from the cached operation schema; does not refresh the operation schema.").option("--update-request <json>",["Update request artifact before making the request using a single-quoted JSON string that represents a flattened object with dot-notation keys.","Nested JSON objects are supported (they will be flattened and issue a warning), but the top-level value must be a JSON object. Invalid JSON will cause the command to fail.",'To delete a field, set its value to "__delete__".','Binary request fields may be patched with a file path string or an object like {"kind":"file","path":"c:/path/file.pdf","fileName":"file.pdf","mimeType":"application/pdf"}.',`Format (POSIX shells): --update-request '{"field.path":value,...}'`,'Format (PowerShell): --update-request "{"field.path":value,...}" (escape inner quotes as needed)'," - Only flattened object dot-notation keys are recommended (e.g. 'items.0.name').","Examples:",` --update-request '{"person.id":"2"}'`,` --update-request '{"items.0.name":"Alice","items.1.value":42}'`,` --update-request '{"parameters.0":"__delete__"}'`,` --update-request '{"address.street":"Main St","address.zip":12345}'`,"Note: The CLI runs JSON.parse on the provided value; if parsing fails the command exits with an error."].join(`
|
|
65
|
+
`),arguments:[{name:"api",type:"string",required:!1,flag:!0,description:"API name to use; optional only when exactly one API is installed."},{name:"count",type:"flag",required:!1,flag:!0,description:"Return the number of operations after filtering and slicing."},{name:"resolved",type:"flag",required:!1,flag:!0,description:"Show only operations that already have generated schema details saved. Alias: --dereferenced."},{name:"path",type:"string[]",required:!1,flag:!0,description:"Filter operations by path structure."},{name:"filter",type:"string",required:!1,flag:!0,description:"Filter operations by keywords, operationId/name, rootType, path, summary, or description."},{name:"tag",type:"string",required:!1,flag:!0,description:"Filter OpenAPI operations by an exact tag, case-insensitive."},{name:"method",type:"string",required:!1,flag:!0,description:"Filter OpenAPI operations by HTTP method."},{name:"rootType",type:"string",required:!1,flag:!0,description:"Filter GraphQL operations by root type (query, mutation, or subscription)."},{name:"index",type:"string",required:!1,flag:!0,description:"Slice the filtered results with inclusive Python-like range syntax."}],examples:["openapi-skills list --api petstore","openapi-skills list --api petstore --count","openapi-skills list --api petstore --resolved","openapi-skills list --api petstore --tag pet","openapi-skills list --api petstore --path /users","openapi-skills list --api petstore --path /store --path order","openapi-skills list --api petstore --path 'store order'","openapi-skills list --api petstore --path :param","openapi-skills list --api petstore --filter addpet","openapi-skills list --api petstore --filter 'create|register' --method POST","openapi-skills list --api countries --root-type query","openapi-skills list --api petstore --resolved --count","openapi-skills list --api petstore --filter '/users'","openapi-skills list --api petstore --index 0:10"],returns:{type:"json",description:"Returns filtered operation summaries as JSON, or a count object when --count is used. When no filters are provided, returns a structured warning object."},sideEffects:{writesFiles:!1,readsFiles:!0,network:!1},constraints:{destructive:!1,idempotent:!0,requiresParsedApi:!0},filesWritten:[]};Ki=C.command("generate-client-schema <operationId>").option("--api <apiName>","API name to use. Optional when exactly one API is installed.").option("--force","Overwrite the cached <operationId> artifact file before generating metadata.").description("Return structured metadata for client code generation for a specific operation. Use --force to overwrite the cached <operationId> artifact file before reading it.").action(async(e,t)=>{let r=await he(t.api);if(r)try{let n=await Z(r,e),s=await De(r,e,n,t.force===!0);d.result(q(s,{kind:"client-schema"}))}catch(n){let s=n instanceof Error?n.message:String(n);d.result(k("API_PARSE_ERROR",{summary:"Error generating client code metadata.",message:s,context:{api_name:r,operation_id:e}})),process.exitCode=1}});Ki.agentMeta={name:"generate-client-schema",category:"Code Generation",usage:"openapi-skills generate-client-schema <operationId> [--api <apiName>] [--force]",description:"Print structured metadata optimized for client code generation as pretty-printed JSON. Returns `response: null` for operations with no JSON response body, in which case the generated client should return `Promise<void>`. The cached artifact is reused unless --force is provided.",arguments:[{name:"operationId",type:"string",required:!0,positional:!0,description:"The operationId of the operation to inspect."},{name:"api",type:"string",required:!1,flag:!0,description:"The API name as defined in .openapi-skills/config.json; optional only when exactly one API is installed."},{name:"force",type:"flag",required:!1,flag:!0,description:"Overwrite the cached artifact file before generating metadata."}],examples:["openapi-skills generate-client-schema addPet --api petstore","openapi-skills generate-client-schema addPet --api petstore --force"],returns:{type:"json",description:"Returns metadata as pretty-printed JSON."},sideEffects:{writesFiles:!1,readsFiles:!0,network:!1},constraints:{destructive:!1,idempotent:!0,requiresParsedApi:!0},filesWritten:[]};Xi=C.command("describe <operationId>").option("--api <apiName>","API name to use. Optional when exactly one API is installed.").option("--force","Overwrite the cached <operationId> artifact file before printing the raw schema.").description("describe \u2192 fallback for generate-client-schema. Use generate-client-schema first. Prints the complete raw schema for a specific operation as JSON, including all parameters, request body, and all response codes. The cached <operationId> artifact file is reused unless --force is provided, which overwrites the cached schema from the bundled API document before output.").action(async(e,t)=>{let r=await he(t.api);if(r)try{let n=await Z(r,e),s=await W(r,e,n,t.force===!0);d.result(q({operationId:e,warnings:["describe \u2192 fallback for generate-client-schema. Use openapi-skills generate-client-schema first for client code generation."],schema:s},{kind:"describe-result"}));return}catch(n){let s=n instanceof Error?n.message:String(n);d.result(k("API_PARSE_ERROR",{summary:"Error describing operation.",message:s,context:{api_name:r,operation_id:e}})),process.exitCode=1;return}});Xi.agentMeta={name:"describe",category:"Navigation",usage:"openapi-skills describe <operationId> [--api <apiName>] [--force]",description:["Fallback for generate-client-schema. Prints the complete raw schema for a specific operation as JSON, including all parameters, request body, and response codes. The cached artifact is reused unless --force is provided.","","**Agents MUST use `generate-client-schema` for client code generation. Use `describe` only when you need full raw schema detail beyond what `generate-client-schema` provides.**"].join(`
|
|
66
|
+
`),arguments:[{name:"operationId",type:"string",required:!0,positional:!0,description:"The operationId of the endpoint to describe."},{name:"api",type:"string",required:!1,flag:!0,description:"The API name as defined in .openapi-skills/config.json; optional only when exactly one API is installed."},{name:"force",type:"flag",required:!1,flag:!0,description:"Overwrite the cached schema file before printing the raw schema."}],examples:["openapi-skills describe getPetById --api petstore","openapi-skills describe deletePet --api petstore","openapi-skills describe getPetById --api petstore --force"],returns:{type:"json",description:"Structured JSON with a fallback warning and the raw OpenAPI schema nested under `schema`."},sideEffects:{writesFiles:!1,readsFiles:!0,network:!1},constraints:{destructive:!1,idempotent:!0,requiresParsedApi:!0},filesWritten:[]};Zi=C.command("get-operation <operationId>").alias("get-operation-artifact").option("--api <apiName>","API name to use. Optional when exactly one API is installed.").option("--request","Return request artifact for the operation.").option("--response","Return response artifact for the operation.").option("--response-schema","Return response-schema artifact for the operation. Inspect this first when the response shape is unknown.").option("--get <path>","Select a nested value by dot-notation path. For response artifacts, use body.* or transport.*; unqualified paths resolve body fields or transport fields.").option("--filter <expr>","Filter the selected value using count, index, range, or <path>=<value> syntax (e.g. count, 0, 0:10, status=sold). Select path first with --get, then filter or slice the selected value.").description("Return one stored operation artifact as JSON. Run `request` first for the same operationId so the artifact exists. Responses use {body, transport}; unqualified --get paths select body fields, while known transport fields such as setCookies and status select transport metadata. Legacy flat artifacts remain readable.").action(async(e,t)=>{let r=await he(t.api);if(!r)return;let n=bn(t),s=await Z(r,e);if(n.error||!n.artifactName){d.result(k("INVALID_REQUEST_UPDATE",{summary:"Invalid operation artifact selection.",message:n.error??"Invalid operation artifact selection.",context:{api_name:r,operation_id:e},nextCommand:`openapi-skills get-operation ${e} --api ${r} --request`})),process.exitCode=1;return}let i=Se(r,s,n.artifactName);if(!await K.pathExists(i)){if(n.artifactName==="response-schema"){d.result(k("NO_RESPONSE_SCHEMA",{summary:"No response schema artifact exists for this operation.",message:"The response schema has not been created yet.",context:{api_name:r,operation_id:e,artifact_type:"response-schema"},nextCommand:`openapi-skills request ${e} --api ${r}`,reason:"Make a request first to generate the response-schema artifact."})),process.exitCode=1;return}d.result(k("REQUEST_TEMPLATE_STALE",{summary:`Artifact '${n.artifactName}' is missing for this operation.`,message:`The '${n.artifactName}' artifact does not exist yet.`,context:{api_name:r,operation_id:e,artifact_type:n.artifactName},nextCommand:`openapi-skills request ${e} --api ${r}`})),process.exitCode=1;return}try{let o=await K.readJson(i),a=typeof t.get=="string"?t.get:void 0,p=typeof t.filter=="string"?t.filter:void 0,c=typeof a=="string"&&a.length>0,u=typeof p=="string"&&p.length>0,m=c&&n.artifactName==="response"?Yi(o,a):a,f=c&&m?ve(o,m):o;if(c&&!u){let{sizeBytes:l}=Ge(f);l>=51200?d.result(k("OVERSIZED_OUTPUT",{summary:"Output is too large to display.",message:`The selected value is ${l} bytes, exceeding the limit of ${51200} bytes.`,context:{api_name:r,operation_id:e,artifact_type:n.artifactName,size_bytes:l},nextCommand:`openapi-skills get-operation ${e} --api ${r} --${n.artifactName} --get ${a} --filter count`})):d.result(q({apiName:r,value:f},{kind:"artifact-value"}));return}if(u){let l=f,b=[];!Array.isArray(l)&&l!==null&&typeof l=="object"&&(b=Object.values(l).filter(T=>Array.isArray(T)),b.length===1&&(l=b[0]));let y=En(p),h;if(y.kind==="count"||y.kind==="index"||y.kind==="range"){if(!Array.isArray(l))if(b.length===1)l=b[0];else{d.result(k("INVALID_FILTER_SYNTAX",{summary:"--filter requires the target to be an array.",message:"The selected value is not an array and contains no single array field to unwrap.",context:{api_name:r,operation_id:e,artifact_type:n.artifactName,filter:p,selected_path:c?a:void 0},nextCommand:`openapi-skills get-operation ${e} --api ${r} --${n.artifactName} --response-schema`})),process.exitCode=1;return}if(!Array.isArray(l)){d.result(k("INVALID_FILTER_SYNTAX",{summary:"--filter requires the target to be an array.",message:"The selected value is not an array.",context:{api_name:r,operation_id:e,artifact_type:n.artifactName,filter:p,selected_path:c?a:void 0},nextCommand:`openapi-skills get-operation ${e} --api ${r} --${n.artifactName}`})),process.exitCode=1;return}if(y.kind==="count")h=l.length;else if(y.kind==="index"){let T=y.index<0?l.length+y.index:y.index;h=l[T]}else h=l.slice(y.start,y.end)}else if(y.kind==="path"){let T=y.path,A=y.value;if(c&&!Array.isArray(l)){d.result(k("INVALID_FILTER_SYNTAX",{summary:"--filter requires the --get result to be an array.",message:`The value at path '${a}' is not an array.`,context:{api_name:r,operation_id:e,artifact_type:n.artifactName,filter:p,selected_path:a},nextCommand:`openapi-skills get-operation ${e} --api ${r} --${n.artifactName} --response-schema`})),process.exitCode=1;return}if(!Array.isArray(l)){let{sizeBytes:E}=Ge(l);E>=51200?d.result(k("OVERSIZED_OUTPUT",{summary:"Output is too large to display.",message:`The selected value is ${E} bytes, exceeding the limit of ${51200} bytes.`,context:{api_name:r,operation_id:e,artifact_type:n.artifactName,size_bytes:E},nextCommand:`openapi-skills get-operation ${e} --api ${r} --${n.artifactName} --filter count`})):d.result(q({apiName:r,value:l},{kind:"artifact-value"}));return}h=vr(l,T,A)}else{d.result(k("INVALID_FILTER_SYNTAX",{summary:"Invalid --filter syntax.",message:"--filter must use count, index, range, or <path>=<value> syntax.",context:{api_name:r,operation_id:e,artifact_type:n.artifactName,filter:p},nextCommand:`openapi-skills get-operation ${e} --api ${r} --${n.artifactName} --filter 0`})),process.exitCode=1;return}let{sizeBytes:w}=Ge(h);w>=51200?d.result(k("OVERSIZED_OUTPUT",{summary:"Output is too large to display.",message:`The filtered result is ${w} bytes, exceeding the limit of ${51200} bytes.`,context:{api_name:r,operation_id:e,artifact_type:n.artifactName,size_bytes:w},nextCommand:`openapi-skills get-operation ${e} --api ${r} --${n.artifactName} --filter count`})):d.result(q({apiName:r,value:h},{kind:"artifact-value"}));return}let{sizeBytes:g}=Ge(o);g>=51200?d.result(k("OVERSIZED_OUTPUT",{summary:"Output is too large to display.",message:`The artifact is ${g} bytes, exceeding the limit of ${51200} bytes.`,context:{api_name:r,operation_id:e,artifact_type:n.artifactName,size_bytes:g},nextCommand:`openapi-skills get-operation ${e} --api ${r} --${n.artifactName} --get <path> --filter count`})):d.result(q({apiName:r,operationId:e,artifact:o},{kind:"artifact"}))}catch(o){d.result(k("API_PARSE_ERROR",{summary:`Failed to read artifact '${n.artifactName}'.`,message:H(o),context:{api_name:r,operation_id:e,artifact_type:n.artifactName}})),process.exitCode=1}});Zi.agentMeta={name:"get-operation",category:"Navigation",usage:"openapi-skills get-operation|get-operation-artifact <operationId> [--api <apiName>] [--request] [--response] [--response-schema] [--get body.<path>|transport.<path>] [--filter count|<index>|<range>|<path>=<value>]",description:"Return a stored operation artifact created by `openapi-skills request` as raw JSON. Responses use {body, transport}. Use --get body.<path> for contract fields and --get transport.<path> for HTTP metadata; unqualified paths remain compatible, including --get setCookies. Legacy flat artifacts remain readable.",arguments:[{name:"operationId",type:"string",required:!0,positional:!0,description:"The operationId whose stored artifact should be returned."},{name:"api",type:"string",required:!1,flag:!0,description:"The API name as defined in .openapi-skills/config.json; optional only when exactly one API is installed."},{name:"request",type:"flag",required:!1,flag:!0,description:"Return request artifact for the operation."},{name:"response",type:"flag",required:!1,flag:!0,description:"Return response artifact for the operation."},{name:"response-schema",type:"flag",required:!1,flag:!0,description:"Return response-schema artifact for the operation. Inspect this first when the response shape is unknown."},{name:"get",type:"string",required:!1,flag:!0,description:"Select a nested value by dot-notation path. Response artifacts support body.* and transport.*; unqualified paths select body fields or known transport fields."},{name:"filter",type:"string",required:!1,flag:!0,description:"Filter the selected value using count, index, range, or <path>=<value> syntax. Examples: --filter count, --filter 0, --filter 0:10, --filter status=sold. Select path first with --get, then filter or slice the selected value."}],examples:["openapi-skills request getPetById --api petstore --force","openapi-skills get-operation getPetById --api petstore --request","openapi-skills get-operation-artifact getPetById --api petstore --request","openapi-skills get-operation getPetById --api petstore --response-schema","openapi-skills get-operation-artifact getPetById --api petstore --response-schema","openapi-skills get-operation getPetById --api petstore --response","openapi-skills get-operation-artifact getPetById --api petstore --response","openapi-skills get-operation getPetById --api petstore --response --get name","openapi-skills get-operation getPetById --api petstore --response --get body --filter id=555","openapi-skills get-operation getPetById --api petstore --response --filter id=5555","openapi-skills get-operation getPetById --api petstore --response --filter count","openapi-skills get-operation getPetById --api petstore --response --filter 0","openapi-skills get-operation getPetById --api petstore --response --filter 0:10"],returns:{type:"json",description:"Returns the selected artifact as raw JSON, or a nested value / filtered array when --get or --filter is supplied. When both are used, --get runs first and --filter applies to the narrowed result. Inspect --response-schema first when the response shape is unknown so --get and --filter can be applied in the right order. --filter can also return an array count, single item, or slice when the selected target is an array."},sideEffects:{writesFiles:!1,readsFiles:!0,network:!1},constraints:{destructive:!1,idempotent:!0,requiresParsedApi:!0},filesWritten:[]};eo=C.command("request <operationId...>").description("Make a live HTTP request for a specific operation, or prepare a multi-step request scenario without executing requests. Supports: --validate (validate only the response against the schema after the request is sent; it does not validate request bodies or guarantee a response exists), --force (refresh operation schema and regenerate request artifact), --force-request (regenerate only request artifact from the cached operation schema), --update-request (patch request artifact using flattened dot-notation keys; binary fields can be file paths or {kind:'file', path,...} descriptors), --update-request-encoded (patch request artifact using base64url-encoded JSON), --omit-empty (remove empty-string values from schema-optional request fields before sending), --header (add headers), --header-encoded (add headers using base64url-encoded JSON).").option("--api <apiName>","API name to use. Optional when exactly one API is installed.").option("--validate","Validate only the response against the schema after the request is sent. Does not validate the request body or guarantee a response exists.").option("--omit-empty","For single-operation requests, remove empty-string values from schema-optional fields before sending and persist the cleaned artifact.").option("--force","Refresh the operation schema and overwrite the request artifact with defaults.").option("--force-request","Force overwrite only the request artifact with defaults from the cached operation schema; does not refresh the operation schema.").option("--update-request <json>",["Update request artifact before making the request using a single-quoted JSON string that represents a flattened object with dot-notation keys.","Nested JSON objects are supported (they will be flattened and issue a warning), but the top-level value must be a JSON object. Invalid JSON will cause the command to fail.",'To delete a field, set its value to "__delete__".','Binary request fields may be patched with a file path string or an object like {"kind":"file","path":"c:/path/file.pdf","fileName":"file.pdf","mimeType":"application/pdf"}.',`Format (POSIX shells): --update-request '{"field.path":value,...}'`,'Format (PowerShell): --update-request "{"field.path":value,...}" (escape inner quotes as needed)'," - Only flattened object dot-notation keys are recommended (e.g. 'items.0.name').","Examples:",` --update-request '{"person.id":"2"}'`,` --update-request '{"items.0.name":"Alice","items.1.value":42}'`,` --update-request '{"parameters.0":"__delete__"}'`,` --update-request '{"address.street":"Main St","address.zip":12345}'`,"Note: The CLI runs JSON.parse on the provided value; if parsing fails the command exits with an error."].join(`
|
|
67
67
|
`)).option("--update-request-encoded <base64url>",["Patch request artifact before making the request using base64url-encoded JSON.","Use this when a shell or agent may strip quotes from literal JSON.","Example:"," --update-request-encoded eyJyZXF1ZXN0Qm9keS5pZCI6MTJ9"].join(`
|
|
68
68
|
`)).option("--header <json>",["Additional headers as a JSON string (merged with config and defaults).",`Format: --header '{"Header-Name":"value"}'`,"Example:",` --header '{"X-Api-Key":"abc"}'`].join(`
|
|
69
69
|
`)).option("--header-encoded <base64url>",["Additional headers as base64url-encoded JSON (merged with config and defaults).","Use this when a shell or agent may strip quotes from literal JSON.","Example:"," --header-encoded eyJBdXRob3JpemF0aW9uIjoiQmVhcmVyIGFiYyJ9"].join(`
|
|
70
|
-
`)).action(async(e,t)=>{let r=t.api;if(!await fe(r))return;if(e.length>1){if(t.omitEmpty){d.result(w("INVALID_REQUEST_UPDATE",{summary:"--omit-empty requires a single operation request.",message:"Multiple operationIds prepare a request scenario without sending requests, so there are no request values to omit.",context:{api_name:r,operation_ids:e},nextCommand:`openapi-skills request <operationId> --api ${r} --omit-empty`})),process.exitCode=2;return}try{let{summaryText:a,payload:p}=await Zr(r,e,t.force===!0,t.forceRequest===!0);d.result(q({summary:a,operationIds:e,apiName:r},{kind:"request-prepare"})),process.exitCode=0}catch(a){let p=W(a);d.result(w("API_PARSE_ERROR",{summary:"Failed to prepare multi-operation request scenario.",message:p,context:{api_name:r,operation_ids:e}})),process.exitCode=1}return}let n=e[0];if(!n){d.result(w("INVALID_REQUEST_UPDATE",{summary:"An operationId is required.",message:"Provide at least one operationId to invoke.",context:{api_name:r},nextCommand:`openapi-skills request <operationId> --api ${r}`})),process.exitCode=1;return}let s,i;if(t.updateRequest&&t.updateRequestEncoded){d.result(w("INVALID_REQUEST_UPDATE",{summary:"Specify only one of --update-request or --update-request-encoded.",message:"Choose the raw JSON form or the base64url-encoded form, not both.",context:{api_name:r,operation_id:n},nextCommand:`openapi-skills request ${n} --api ${r} --update-request-encoded eyJyZXF1ZXN0Qm9keS5pZCI6MTJ9`})),process.exitCode=2;return}if(t.updateRequest){let a;try{a=JSON.parse(t.updateRequest)}catch(g){let b=`Invalid JSON for --update-request: ${g instanceof Error?g.message:String(g)}`;d.result(w("INVALID_UPDATE_REQUEST_JSON",{summary:"--update-request JSON is malformed.",message:b,context:{api_name:r,operation_id:n,update_request:t.updateRequest},nextCommand:`openapi-skills request ${n} --api ${r} --update-request '{"field.path":"value"}'`})),process.exitCode=2;return}if(typeof a!="object"||Array.isArray(a)||!a||Object.keys(a).length===0){d.result(w("INVALID_REQUEST_UPDATE",{summary:"--update-request must be a non-empty JSON object.",message:"Use flattened dot-notation keys and provide at least one update.",context:{api_name:r,operation_id:n,update_request:t.updateRequest},nextCommand:`openapi-skills request ${n} --api ${r} --update-request '{"field.path":"value"}'`})),process.exitCode=2;return}let p=await X(r,n),c=tt(r,p,"request");if(t.force===!0||t.forceRequest===!0){let b=(await U()).apis?.[r]?.schemaType,T=b==="graphql";if(!T&&b!=="openapi")try{let h=await M.readJson(L(r));T=Array.isArray(h)&&h.some(y=>typeof y?.rootType=="string")}catch{T=!1}T||await Q(r,n,p),await Ce(r,p,t.force===!0,t.forceRequest===!0)}else if(!await M.pathExists(c)){d.result(w("REQUEST_TEMPLATE_STALE",{summary:"request.json does not exist for this operation.",message:"--update-request requires an existing request.json artifact. Use --force-request to regenerate it from the cached operation schema, or --force to refresh the schema too.",context:{api_name:r,operation_id:n,artifact_type:"request"},nextCommand:`openapi-skills request ${n} --api ${r} --force-request --update-request '{"field.path":"value"}'`})),process.exitCode=2;return}let u=await M.readJson(c),m=De(u),f=pt(a),l=Array.from(f).filter(g=>!m.has(g));if(l.length>0){d.result(w("INVALID_REQUEST_UPDATE",{summary:"--update-request contains keys not present in request.json.",message:`The following keys are missing from request.json: ${l.join(", ")}.`,context:{api_name:r,operation_id:n,update_request:t.updateRequest,missing_keys:l},nextCommand:`openapi-skills request ${n} --api ${r} ${t.force?"--force":"--force-request"}`})),process.exitCode=2;return}if(t.force===!0||t.forceRequest===!0){let g=Jt(u,a);g.length>0&&(i=g)}s=a}if(t.updateRequestEncoded){let a;try{a=ut(t.updateRequestEncoded,"--update-request-encoded")}catch(g){let b=`Invalid base64url for --update-request-encoded: ${g instanceof Error?g.message:String(g)}`;d.result(w("INVALID_UPDATE_REQUEST_JSON",{summary:"--update-request-encoded value is malformed.",message:b,context:{api_name:r,operation_id:n,update_request_encoded:t.updateRequestEncoded},nextCommand:`openapi-skills request ${n} --api ${r} --update-request-encoded eyJyZXF1ZXN0Qm9keS5pZCI6MTJ9`})),process.exitCode=2;return}if(typeof a!="object"||Array.isArray(a)||!a||Object.keys(a).length===0){d.result(w("INVALID_REQUEST_UPDATE",{summary:"--update-request-encoded must decode to a non-empty JSON object.",message:"The decoded payload must contain at least one flattened dot-notation key.",context:{api_name:r,operation_id:n,update_request_encoded:t.updateRequestEncoded},nextCommand:`openapi-skills request ${n} --api ${r} --update-request-encoded eyJyZXF1ZXN0Qm9keS5pZCI6MTJ9`})),process.exitCode=2;return}let p=await X(r,n),c=tt(r,p,"request");if(t.force===!0||t.forceRequest===!0){let b=(await U()).apis?.[r]?.schemaType,T=b==="graphql";if(!T&&b!=="openapi")try{let h=await M.readJson(L(r));T=Array.isArray(h)&&h.some(y=>typeof y?.rootType=="string")}catch{T=!1}T||await Q(r,n,p),await Ce(r,p,t.force===!0,t.forceRequest===!0)}else if(!await M.pathExists(c)){d.result(w("REQUEST_TEMPLATE_STALE",{summary:"request.json does not exist for this operation.",message:"--update-request-encoded requires an existing request.json artifact. Use --force-request to regenerate it from the cached operation schema, or --force to refresh the schema too.",context:{api_name:r,operation_id:n,artifact_type:"request"},nextCommand:`openapi-skills request ${n} --api ${r} --force-request --update-request-encoded eyJyZXF1ZXN0Qm9keS5pZCI6MTJ9`})),process.exitCode=2;return}let u=await M.readJson(c),m=De(u),f=pt(a),l=Array.from(f).filter(g=>!m.has(g));if(l.length>0){d.result(w("INVALID_REQUEST_UPDATE",{summary:"--update-request-encoded contains keys not present in request.json.",message:`The following keys are missing from request.json: ${l.join(", ")}.`,context:{api_name:r,operation_id:n,update_request_encoded:t.updateRequestEncoded,missing_keys:l},nextCommand:`openapi-skills request ${n} --api ${r} ${t.force?"--force":"--force-request"}`})),process.exitCode=2;return}if(t.force===!0||t.forceRequest===!0){let g=Jt(u,a);g.length>0&&(i=g)}s=a}if(t.header&&t.headerEncoded){d.result(w("INVALID_JSON_ARGUMENT",{summary:"Provide only one of --header or --header-encoded.",message:"--header and --header-encoded are mutually exclusive.",context:{api_name:r,operation_id:n,header:t.header,header_encoded:t.headerEncoded},nextCommand:`openapi-skills request ${n} --api ${r} --header-encoded eyJBdXRob3JpemF0aW9uIjoiQmVhcmVyIGFiYyJ9`})),process.exitCode=2;return}let o;if(t.header)try{if(o=JSON.parse(t.header),typeof o!="object"||Array.isArray(o)||!o)throw new Error("--header must be a JSON object")}catch{d.result(w("INVALID_JSON_ARGUMENT",{summary:"--header JSON is malformed.",message:`Invalid --header JSON. Example: --header '{"X-Api-Key":"abc"}'`,context:{header:t.header},nextCommand:`openapi-skills request ${n} --api ${r} --header '{"Header-Name":"value"}'`})),process.exitCode=2;return}if(t.headerEncoded)try{o=ut(t.headerEncoded,"--header-encoded")}catch(a){let p=`Invalid base64url for --header-encoded: ${a instanceof Error?a.message:String(a)}`;d.result(w("INVALID_JSON_ARGUMENT",{summary:"--header-encoded value is malformed.",message:p,context:{header_encoded:t.headerEncoded},nextCommand:`openapi-skills request ${n} --api ${r} --header-encoded eyJBdXRob3JpemF0aW9uIjoiQmVhcmVyIGFiYyJ9`})),process.exitCode=2;return}if(t.validate)try{let a=await Lr(r,n,t.force,o,s,i,t.omitEmpty,t.forceRequest),p=ct(r,n);if(!a.valid){d.result(w("VALIDATION_FAILED",{summary:"Response validation failed.",message:(a.errors??[]).join("; ")||"The response did not match the expected schema.",context:{api_name:r,operation_id:n,validation_warnings:a.warnings??[],validation_errors:a.errors??[],operation_artifact_count:p.fileCount},nextCommand:`openapi-skills request ${n} --api ${r} --validate`})),process.exitCode=1;return}d.result(q({apiName:r,operationId:n,valid:a.valid,warnings:a.warnings??[],errors:a.errors??[],operationArtifactCount:p.fileCount,retrieveArtifacts:"Use `get-operation-artifact [--request|--response|--response-schema] <operationId>` to view this operation's artifacts."},{kind:"validation-result"})),process.exitCode=0}catch(a){d.result(w("VALIDATION_FAILED",{summary:"Validation failed.",message:W(a),context:{api_name:r,operation_id:n},nextCommand:`openapi-skills request ${n} --api ${r} --validate`})),process.exitCode=2;return}else try{let{request:a,response:p,warnings:c}=await Gt(r,n,t.force,o,s,i,t.omitEmpty,t.forceRequest);await Ut(r,n);let u=ct(r,n);d.result(q({apiName:r,operationId:n,warnings:c??[],fileCount:u.fileCount,retrieveArtifacts:"Use `get-operation-artifact [--request|--response|--response-schema] <operationId>` to view this operation's artifacts."},{kind:"request-result"})),process.exitCode=0}catch(a){d.result(w("REQUEST_FAILED",{summary:"Request failed.",message:W(a),context:{api_name:r,operation_id:n},nextCommand:`openapi-skills request ${n} --api ${r}`})),process.exitCode=2;return}});wi.agentMeta={name:"request",category:"Validation",usage:"openapi-skills request <operationId...> --api <apiName> [--validate] [--force] [--force-request] [--update-request <json>] [--update-request-encoded <base64url>] [--omit-empty] [--header <json>] [--header-encoded <base64url>]",description:["Make a live HTTP request for an operation, or prepare a multi-step request scenario without executing requests.","When multiple operationIds are supplied, the command enters prepare-only mode and refreshes request artifact templates for the scenario.","With --validate, validate only the response against the schema after the request is sent.","With --force, refresh the operation schema and regenerate the request artifact from defaults.","With --force-request, regenerate only the request artifact from the cached operation schema without refreshing the schema.",'With --update-request, patch the request artifact using flattened dot-notation keys. Nested JSON objects are accepted, but the provided value must be valid JSON. With --update-request-encoded, pass base64url-encoded JSON instead. With --omit-empty on a single-operation request, remove empty-string values from schema-optional fields after updates and persist the cleaned artifact; this option is not available in multi-operation prepare-only mode. With --header, merge JSON headers into the request. With --header-encoded, pass base64url-encoded JSON headers instead. Binary fields can be set to a file path string or a file descriptor object. Set a field to "__delete__" to remove it.'].join(" "),arguments:[{name:"operationId",type:"string[]",required:!0,positional:!0,description:"One or more operationIds to invoke. Multiple values switch the command into prepare-only mode for a multi-step scenario."},{name:"api",type:"string",required:!0,flag:!0,description:"The API name as defined in .openapi-skills/config.json."},{name:"validate",type:"flag",required:!1,flag:!0,description:"Validate only the response against the schema after the request is sent. Does not validate the request body or guarantee a response exists."},{name:"force",type:"flag",required:!1,flag:!0,description:"Refresh the operation schema and overwrite the request artifact with defaults."},{name:"force-request",type:"flag",required:!1,flag:!0,description:"Force overwrite only the request artifact with defaults from the cached operation schema; does not refresh the operation schema. If used with --force, --force behavior applies."},{name:"omit-empty",type:"flag",required:!1,flag:!0,description:"For single-operation requests, remove empty-string values from schema-optional fields after updates and persist the cleaned request artifact."},{name:"update-request",type:"json",required:!1,flag:!0,description:'Patch request artifact before making the request. Only flattened object dot-notation keys are allowed. Binary fields can be set to a file path string or file descriptor object. Set a field to "__delete__" to remove it. Use with --force-request to rebuild defaults from the cached schema, or --force to refresh the schema too.'},{name:"update-request-encoded",type:"string",required:!1,flag:!0,description:"Patch request artifact before making the request using base64url-encoded JSON. Use this when quoting is unreliable."},{name:"header",type:"json",required:!1,flag:!0,description:"Additional headers as a JSON string."},{name:"header-encoded",type:"string",required:!1,flag:!0,description:"Additional headers as base64url-encoded JSON. Use this when quoting is unreliable."}],examples:["openapi-skills request getPetById --api petstore","openapi-skills request getPetById --api petstore --validate","openapi-skills request createPet --api petstore --omit-empty",`openapi-skills request getPetById --api petstore --force-request --update-request '{"user.profile.name":"Ada"}'`,"openapi-skills request getPetById --api petstore --force-request","openapi-skills request getPetById --api petstore --force --update-request-encoded eyJyZXF1ZXN0Qm9keS5pZCI6MTJ9",`openapi-skills request getPetById --api petstore --update-request '{"user.profile.name":"Ada"}'`,`openapi-skills request getPetById --api petstore --update-request '{"parameters.0.id":1}'`,"openapi-skills request getPetById --api petstore --header-encoded eyJBdXRob3JpemF0aW9uIjoiQmVhcmVyIGFiYyJ9",`openapi-skills request getPetById --api petstore --update-request '{"parameters.0":"__delete__"}'`,"openapi-skills request operationId1 operationId2 --api petstore"],returns:{type:"json",description:"Returns raw request and response for single-operation requests, or a structured batch preparation summary when multiple operationIds are supplied."},sideEffects:{writesFiles:!0,readsFiles:!0,network:!0},constraints:{destructive:!1,idempotent:!1,requiresParsedApi:!0},filesWritten:["request artifact","response artifact","response-schema artifact (when response has JSON body)"]};bi=j.command("set-env").requiredOption("--api <apiName>","API name to use").option("--base-url <url>","Base URL for the API environment.").option("--auth <json>","Authentication headers as a JSON string.").option("--auth-encoded <base64url>","Authentication headers as base64url-encoded JSON. Use this when a shell or agent may strip quotes from literal JSON.").option("--var <key=value>","Set a runtime variable for the API environment. Repeatable.",(e,t)=>[...Array.isArray(t)?t:t?[t]:[],e]).description("Set or update the runtime environment for a parsed API.").addHelpText("after",["Use this command to set baseUrl, auth headers, and runtime vars for a parsed API.","Pass auth headers with --auth as JSON or --auth-encoded as base64url-encoded JSON when quoting is unreliable.","","Examples:",` set-env --api petstore --base-url https://dev.example.com --auth '{"Authorization":"Bearer abc"}'`," set-env --api petstore --auth-encoded eyJBdXRob3JpemF0aW9uIjoiQmVhcmVyIGFiYyJ9",` set-env --api petstore --auth '{"Authorization":"Bearer abc"}'`," set-env --api petstore --var userId=123"].join(`
|
|
71
|
-
`)).action(async e=>{let t=e.api;if(!await fe(t))return;let r=typeof e.baseUrl=="string"?e.baseUrl.trim():"",n=r.length>0?r:void 0,s;if(typeof e.auth=="string"&&typeof e.authEncoded=="string"){d.result(w("INVALID_JSON_ARGUMENT",{summary:"Provide only one of --auth or --auth-encoded.",message:"--auth and --auth-encoded are mutually exclusive.",context:{api_name:t,auth:e.auth,auth_encoded:e.authEncoded},nextCommand:`openapi-skills set-env --api ${t} --auth-encoded eyJBdXRob3JpemF0aW9uIjoiQmVhcmVyIGFiYyJ9`})),process.exitCode=1;return}if(typeof e.auth=="string")try{let a=JSON.parse(e.auth);if(typeof a!="object"||Array.isArray(a)||!a)throw new Error("Auth must be a JSON object");s=a}catch{d.result(w("INVALID_JSON_ARGUMENT",{summary:"--auth JSON is malformed.",message:`Invalid --auth JSON. Example: '{"Authorization":"Bearer abc"}'`,context:{api_name:t,auth:e.auth??null},nextCommand:`openapi-skills set-env --api ${t} --auth '{"Authorization":"Bearer abc"}'`})),process.exitCode=1;return}if(typeof e.authEncoded=="string")try{let a=ut(e.authEncoded,"--auth-encoded"),p={};for(let[c,u]of Object.entries(a)){if(typeof u!="string")throw new Error(`Auth header "${c}" must be a string`);p[c]=u}s=p}catch(a){d.result(w("INVALID_JSON_ARGUMENT",{summary:"--auth-encoded value is malformed.",message:`Invalid base64url for --auth-encoded: ${a instanceof Error?a.message:String(a)}`,context:{api_name:t,auth_encoded:e.authEncoded},nextCommand:`openapi-skills set-env --api ${t} --auth-encoded eyJBdXRob3JpemF0aW9uIjoiQmVhcmVyIGFiYyJ9`})),process.exitCode=1;return}let i=e.var?Array.isArray(e.var)?e.var:[e.var]:[],o={};for(let a of i){let p=a.indexOf("=");if(p<=0){d.result(w("INVALID_VARIABLE_SYNTAX",{summary:"Invalid --var syntax.",message:`Invalid --var value "${a}". Use key=value.`,context:{api_name:t,variable:a},nextCommand:`openapi-skills set-env --api ${t} --var userId=123`})),process.exitCode=1;return}let c=a.slice(0,p).trim(),u=a.slice(p+1);if(!c){d.result(w("INVALID_VARIABLE_SYNTAX",{summary:"Invalid --var syntax.",message:`Invalid --var value "${a}". Use key=value.`,context:{api_name:t,variable:a},nextCommand:`openapi-skills set-env --api ${t} --var userId=123`})),process.exitCode=1;return}o[c]=u}try{let a={};n!==void 0&&(a.baseUrl=n),s!==void 0&&(a.auth=s),Object.keys(o).length>0&&(a.vars=o),await Te(t,a),d.result(q({apiName:t,baseUrl:n,hasAuth:s!==void 0,varCount:Object.keys(o).length},{kind:"set-env-result"}))}catch(a){d.result(w("CONFIG_ERROR",{summary:"Failed to update API environment.",message:W(a),context:{api_name:t,base_url:n??null,var_count:Object.keys(o).length},nextCommand:`openapi-skills set-env --api ${t}`})),process.exitCode=1}});bi.agentMeta={name:"set-env",category:"Configuration",usage:"openapi-skills set-env --api <apiName> [--base-url <url>] [--auth <json>] [--auth-encoded <base64url>] [--var key=value]",description:"Set or update the runtime environment for a parsed API. Persists baseUrl, auth headers, and named vars in config.json.",arguments:[{name:"api",type:"string",required:!0,flag:!0,description:"The API name as defined in .openapi-skills/config.json."},{name:"base-url",type:"string",required:!1,flag:!0,description:"Base URL for the API environment."},{name:"auth",type:"json",required:!1,flag:!0,description:"Authentication headers as a JSON object."},{name:"auth-encoded",type:"string",required:!1,flag:!0,description:"Authentication headers as base64url-encoded JSON."},{name:"var",type:"string",required:!1,flag:!0,description:"Runtime variable in key=value form. Repeatable."}],examples:[`openapi-skills set-env --api petstore --base-url https://dev.example.com --auth '{"Authorization":"Bearer abc"}'`,"openapi-skills set-env --api petstore --auth-encoded eyJBdXRob3JpemF0aW9uIjoiQmVhcmVyIGFiYyJ9",`openapi-skills set-env --api petstore --auth '{"Authorization":"Bearer abc"}'`,"openapi-skills set-env --api petstore --var userId=123 --var env=staging"],returns:{type:"json",description:"Returns success or error message."},sideEffects:{writesFiles:!0,readsFiles:!0,network:!1},constraints:{destructive:!1,idempotent:!1,requiresParsedApi:!1},filesWritten:["config.json"]};Ai=j.command("get-env").requiredOption("--api <apiName>","API name to use").option("--base-url","Include baseUrl in output").option("--auth","Include auth headers in output").option("--var <key=value>","Request one or more runtime vars. Repeatable; only the key part is used to filter output.",(e,t)=>[...Array.isArray(t)?t:t?[t]:[],e]).description("Read API environment configuration from `.openapi-skills/config.json`. Returns all values unless a specific field is requested via flags.").action(async e=>{let t=e.api;if(await fe(t))try{let r=e.baseUrl===!0,n=e.auth===!0,s=e.var?Array.isArray(e.var)?e.var:[e.var]:[],i=r||n||s.length>0,o=await st(t,"baseUrl"),a=await st(t,"authHeaders"),p=await st(t,"vars"),c=Array.isArray(p)?p:[],u=Object.fromEntries(c),m={apiName:t};if((!i||r)&&(m.baseUrl=o),(!i||n)&&(m.authHeaders=a),!i)m.vars=c;else if(s.length>0){let f=s.map(l=>{let g=l.indexOf("=");return g>=0?l.slice(0,g).trim():l.trim()}).filter(Boolean);m.vars=f.map(l=>[l,u[l]]).filter(([l,g])=>g!==void 0)}d.result(q(m,{kind:"get-env-result"})),process.exitCode=0}catch(r){d.result(w("CONFIG_ERROR",{summary:"Failed to read API environment.",message:r instanceof Error?r.message:String(r),context:{api_name:t},nextCommand:`openapi-skills get-env --api ${t}`})),process.exitCode=1}});Ai.agentMeta={name:"get-env",category:"Configuration",usage:"openapi-skills get-env --api <apiName>",description:"Read environment configuration for an API. Returns all values by default, or only a specific field when a flag is provided.",arguments:[{name:"api",type:"string",required:!0,flag:!0,description:"The API name as defined in .openapi-skills/config.json."}],examples:["openapi-skills get-env --api petstore","openapi-skills get-env --api petstore --base-url","openapi-skills get-env --api petstore --var userId"],returns:{type:"json",description:"Prints { apiName, baseUrl, authHeaders, vars } where vars is an entries array."},sideEffects:{writesFiles:!1,readsFiles:!0,network:!1},constraints:{destructive:!1,idempotent:!0,requiresParsedApi:!1},filesWritten:[]};Ti=j.command("get-api-names").description("List all available API names (parsed OpenAPI bundles) in the project.").action(async()=>{try{let e=await ue();d.result(q({apiNames:e},{kind:"api-list"})),(!e||e.length===0)&&d.warn("No APIs were generated yet. Run first: openapi-skills generate <openapi-source> [options]")}catch{d.result(w("CONFIG_ERROR",{summary:"Failed to list APIs.",message:"Run `openapi-skills generate [options] [openapi-source]` to parse APIs first.",context:{},nextCommand:"openapi-skills generate <openapi-source>"})),process.exitCode=1}});Ti.agentMeta={name:"get-api-names",category:"Navigation",usage:"openapi-skills get-api-names",description:"List all available parsed API names in the project. Output is always JSON: { kind: 'api-list', apiNames: [<apiName>, ...] }.",arguments:[],examples:["openapi-skills get-api-names"],returns:{type:"json",description:"Returns { kind: 'api-list', apiNames: [<apiName>, ...] } as JSON."},sideEffects:{writesFiles:!1,readsFiles:!0,network:!1},constraints:{destructive:!1,idempotent:!0,requiresParsedApi:!1},filesWritten:[]};ki=j.command("remove-api <apiName>").description("Remove an API from config.json and delete its .openapi-skills directory after confirmation.").option("-y, --yes","Confirm removal automatically without prompting.").action(async(e,t)=>{let r=e;try{if(!(await ue()).includes(r)){d.result(w("UNKNOWN_API",{summary:`API '${r}' is not installed.`,message:`API '${r}' is not installed.`,context:{api_name:r},nextCommand:"openapi-skills get-api-names"})),process.exitCode=1;return}if(!(t?.yes===!0?!0:await Hr(r))){d.result(q({cancelled:!0,apiName:r},{kind:"remove-api-result"})),process.exitCode=0;return}let i=await cr(r);if(i.ok){d.result(q({removedApi:i.data.removedApi,message:i.message},{kind:"remove-api-result"})),process.exitCode=0;return}let o=/config/i.test(i.error.message)?"CONFIG_ERROR":i.error.type==="ApiNotFound"?"UNKNOWN_API":"REQUEST_FAILED";d.result(w(o,{summary:`Remove API error for ${r}.`,message:i.error.message,context:{api_name:r},nextCommand:o==="UNKNOWN_API"?"openapi-skills get-api-names":"None"})),process.exitCode=1;return}catch(n){let s=n instanceof Error?n.message:String(n);d.result(w(/config/i.test(s)?"CONFIG_ERROR":"REQUEST_FAILED",{summary:`Remove API error for ${r}.`,message:s,context:{api_name:r},nextCommand:/config/i.test(s)?"None":`openapi-skills remove-api ${r} --yes`})),process.exitCode=1}});ki.agentMeta={name:"remove-api",category:"Configuration",usage:"openapi-skills remove-api <apiName> [--yes|-y]",description:"Remove a parsed API after confirmation. The command deletes the API entry from config.json and removes the API directory under .openapi-skills.",arguments:[{name:"apiName",type:"string",required:!0,positional:!0,description:"The API name to remove."},{name:"yes",type:"flag",required:!1,flag:!0,description:"Confirm removal automatically without prompting."}],examples:["openapi-skills remove-api petstore --yes"],returns:{type:"json",description:"Returns a structured success or error result for the deletion operation."},sideEffects:{writesFiles:!0,readsFiles:!0,network:!1},constraints:{destructive:!0,idempotent:!1,requiresParsedApi:!0},filesWritten:["config.json"]};j.parse(process.argv)});await Br();export{j as program};
|
|
70
|
+
`)).option("--no-cookie-jar","Do not load, send, or update cookies for this request.").option("--verbose-transport","Include the request headers passed to fetch in transport metadata, with sensitive values redacted.").action(async(e,t)=>{let r=await he(t.api);if(!r)return;if(e.length>1){if(t.omitEmpty||t.cookieJar===!1||t.verboseTransport){let a=t.omitEmpty?"--omit-empty":t.cookieJar===!1?"--no-cookie-jar":"--verbose-transport";d.result(k("INVALID_REQUEST_UPDATE",{summary:`${a} requires a single operation request.`,message:"Multiple operationIds prepare a request scenario without sending requests, so this option cannot be applied.",context:{api_name:r,operation_ids:e},nextCommand:`openapi-skills request <operationId> --api ${r} ${a}`})),process.exitCode=2;return}try{let{summaryText:a,payload:p}=await Tn(r,e,t.force===!0,t.forceRequest===!0);d.result(q({summary:a,operationIds:e,apiName:r},{kind:"request-prepare"})),process.exitCode=0}catch(a){let p=H(a);d.result(k("API_PARSE_ERROR",{summary:"Failed to prepare multi-operation request scenario.",message:p,context:{api_name:r,operation_ids:e}})),process.exitCode=1}return}let n=e[0];if(!n){d.result(k("INVALID_REQUEST_UPDATE",{summary:"An operationId is required.",message:"Provide at least one operationId to invoke.",context:{api_name:r},nextCommand:`openapi-skills request <operationId> --api ${r}`})),process.exitCode=1;return}let s,i;if(t.updateRequest&&t.updateRequestEncoded){d.result(k("INVALID_REQUEST_UPDATE",{summary:"Specify only one of --update-request or --update-request-encoded.",message:"Choose the raw JSON form or the base64url-encoded form, not both.",context:{api_name:r,operation_id:n},nextCommand:`openapi-skills request ${n} --api ${r} --update-request-encoded eyJyZXF1ZXN0Qm9keS5pZCI6MTJ9`})),process.exitCode=2;return}if(t.updateRequest){let a;try{a=JSON.parse(t.updateRequest)}catch(l){let b=`Invalid JSON for --update-request: ${l instanceof Error?l.message:String(l)}`;d.result(k("INVALID_UPDATE_REQUEST_JSON",{summary:"--update-request JSON is malformed.",message:b,context:{api_name:r,operation_id:n,update_request:t.updateRequest},nextCommand:`openapi-skills request ${n} --api ${r} --update-request '{"field.path":"value"}'`})),process.exitCode=2;return}if(typeof a!="object"||Array.isArray(a)||!a||Object.keys(a).length===0){d.result(k("INVALID_REQUEST_UPDATE",{summary:"--update-request must be a non-empty JSON object.",message:"Use flattened dot-notation keys and provide at least one update.",context:{api_name:r,operation_id:n,update_request:t.updateRequest},nextCommand:`openapi-skills request ${n} --api ${r} --update-request '{"field.path":"value"}'`})),process.exitCode=2;return}let p=await Z(r,n),c=Se(r,p,"request");if(t.force===!0||t.forceRequest===!0){let b=(await B()).apis?.[r]?.schemaType,y=b==="graphql";if(!y&&b!=="openapi")try{let h=await K.readJson(D(r));y=Array.isArray(h)&&h.some(w=>typeof w?.rootType=="string")}catch{y=!1}y||await W(r,n,p),await Ue(r,p,t.force===!0,t.forceRequest===!0)}else if(!await K.pathExists(c)){d.result(k("REQUEST_TEMPLATE_STALE",{summary:"request.json does not exist for this operation.",message:"--update-request requires an existing request.json artifact. Use --force-request to regenerate it from the cached operation schema, or --force to refresh the schema too.",context:{api_name:r,operation_id:n,artifact_type:"request"},nextCommand:`openapi-skills request ${n} --api ${r} --force-request --update-request '{"field.path":"value"}'`})),process.exitCode=2;return}let u=await K.readJson(c),m=Qe(u),f=wt(a),g=Array.from(f).filter(l=>!m.has(l));if(g.length>0){d.result(k("INVALID_REQUEST_UPDATE",{summary:"--update-request contains keys not present in request.json.",message:`The following keys are missing from request.json: ${g.join(", ")}.`,context:{api_name:r,operation_id:n,update_request:t.updateRequest,missing_keys:g},nextCommand:`openapi-skills request ${n} --api ${r} ${t.force?"--force":"--force-request"}`})),process.exitCode=2;return}if(t.force===!0||t.forceRequest===!0){let l=Xt(u,a);l.length>0&&(i=l)}s=a}if(t.updateRequestEncoded){let a;try{a=kt(t.updateRequestEncoded,"--update-request-encoded")}catch(l){let b=`Invalid base64url for --update-request-encoded: ${l instanceof Error?l.message:String(l)}`;d.result(k("INVALID_UPDATE_REQUEST_JSON",{summary:"--update-request-encoded value is malformed.",message:b,context:{api_name:r,operation_id:n,update_request_encoded:t.updateRequestEncoded},nextCommand:`openapi-skills request ${n} --api ${r} --update-request-encoded eyJyZXF1ZXN0Qm9keS5pZCI6MTJ9`})),process.exitCode=2;return}if(typeof a!="object"||Array.isArray(a)||!a||Object.keys(a).length===0){d.result(k("INVALID_REQUEST_UPDATE",{summary:"--update-request-encoded must decode to a non-empty JSON object.",message:"The decoded payload must contain at least one flattened dot-notation key.",context:{api_name:r,operation_id:n,update_request_encoded:t.updateRequestEncoded},nextCommand:`openapi-skills request ${n} --api ${r} --update-request-encoded eyJyZXF1ZXN0Qm9keS5pZCI6MTJ9`})),process.exitCode=2;return}let p=await Z(r,n),c=Se(r,p,"request");if(t.force===!0||t.forceRequest===!0){let b=(await B()).apis?.[r]?.schemaType,y=b==="graphql";if(!y&&b!=="openapi")try{let h=await K.readJson(D(r));y=Array.isArray(h)&&h.some(w=>typeof w?.rootType=="string")}catch{y=!1}y||await W(r,n,p),await Ue(r,p,t.force===!0,t.forceRequest===!0)}else if(!await K.pathExists(c)){d.result(k("REQUEST_TEMPLATE_STALE",{summary:"request.json does not exist for this operation.",message:"--update-request-encoded requires an existing request.json artifact. Use --force-request to regenerate it from the cached operation schema, or --force to refresh the schema too.",context:{api_name:r,operation_id:n,artifact_type:"request"},nextCommand:`openapi-skills request ${n} --api ${r} --force-request --update-request-encoded eyJyZXF1ZXN0Qm9keS5pZCI6MTJ9`})),process.exitCode=2;return}let u=await K.readJson(c),m=Qe(u),f=wt(a),g=Array.from(f).filter(l=>!m.has(l));if(g.length>0){d.result(k("INVALID_REQUEST_UPDATE",{summary:"--update-request-encoded contains keys not present in request.json.",message:`The following keys are missing from request.json: ${g.join(", ")}.`,context:{api_name:r,operation_id:n,update_request_encoded:t.updateRequestEncoded,missing_keys:g},nextCommand:`openapi-skills request ${n} --api ${r} ${t.force?"--force":"--force-request"}`})),process.exitCode=2;return}if(t.force===!0||t.forceRequest===!0){let l=Xt(u,a);l.length>0&&(i=l)}s=a}if(t.header&&t.headerEncoded){d.result(k("INVALID_JSON_ARGUMENT",{summary:"Provide only one of --header or --header-encoded.",message:"--header and --header-encoded are mutually exclusive.",context:{api_name:r,operation_id:n,header:t.header,header_encoded:t.headerEncoded},nextCommand:`openapi-skills request ${n} --api ${r} --header-encoded eyJBdXRob3JpemF0aW9uIjoiQmVhcmVyIGFiYyJ9`})),process.exitCode=2;return}let o;if(t.header)try{if(o=JSON.parse(t.header),typeof o!="object"||Array.isArray(o)||!o)throw new Error("--header must be a JSON object")}catch{d.result(k("INVALID_JSON_ARGUMENT",{summary:"--header JSON is malformed.",message:`Invalid --header JSON. Example: --header '{"X-Api-Key":"abc"}'`,context:{header:t.header},nextCommand:`openapi-skills request ${n} --api ${r} --header '{"Header-Name":"value"}'`})),process.exitCode=2;return}if(t.headerEncoded)try{o=kt(t.headerEncoded,"--header-encoded")}catch(a){let p=`Invalid base64url for --header-encoded: ${a instanceof Error?a.message:String(a)}`;d.result(k("INVALID_JSON_ARGUMENT",{summary:"--header-encoded value is malformed.",message:p,context:{header_encoded:t.headerEncoded},nextCommand:`openapi-skills request ${n} --api ${r} --header-encoded eyJBdXRob3JpemF0aW9uIjoiQmVhcmVyIGFiYyJ9`})),process.exitCode=2;return}if(t.validate)try{let a=await Zr(r,n,t.force,o,s,i,t.omitEmpty,t.forceRequest,t.cookieJar===!1,t.verboseTransport),p=bt(r,n);if(!a.valid){d.result(k("VALIDATION_FAILED",{summary:"Response validation failed.",message:(a.errors??[]).join("; ")||"The response did not match the expected schema.",context:{api_name:r,operation_id:n,validation_warnings:a.warnings??[],validation_errors:a.errors??[],operation_artifact_count:p.fileCount},nextCommand:`openapi-skills request ${n} --api ${r} --validate`})),process.exitCode=1;return}d.result(q({apiName:r,operationId:n,valid:a.valid,warnings:a.warnings??[],errors:a.errors??[],operationArtifactCount:p.fileCount,retrieveArtifacts:"Use `get-operation-artifact [--request|--response|--response-schema] <operationId>` to view this operation's artifacts."},{kind:"validation-result"})),process.exitCode=0}catch(a){d.result(k("VALIDATION_FAILED",{summary:"Validation failed.",message:H(a),context:{api_name:r,operation_id:n},nextCommand:`openapi-skills request ${n} --api ${r} --validate`})),process.exitCode=2;return}else try{let{request:a,response:p,warnings:c}=await Zt(r,n,t.force,o,s,i,t.omitEmpty,t.forceRequest,t.cookieJar===!1,t.verboseTransport);await Yt(r,n);let u=bt(r,n);d.result(q({apiName:r,operationId:n,warnings:c??[],fileCount:u.fileCount,retrieveArtifacts:"Use `get-operation-artifact [--request|--response|--response-schema] <operationId>` to view this operation's artifacts."},{kind:"request-result"})),process.exitCode=0}catch(a){d.result(k("REQUEST_FAILED",{summary:"Request failed.",message:H(a),context:{api_name:r,operation_id:n},nextCommand:`openapi-skills request ${n} --api ${r}`})),process.exitCode=2;return}});eo.agentMeta={name:"request",category:"Validation",usage:"openapi-skills request <operationId...> [--api <apiName>] [--validate] [--force] [--force-request] [--update-request <json>] [--update-request-encoded <base64url>] [--omit-empty] [--header <json>] [--header-encoded <base64url>] [--no-cookie-jar] [--verbose-transport]",description:["Make a live HTTP request for an operation, or prepare a multi-step request scenario without executing requests. --api is optional only when exactly one API is installed.","When multiple operationIds are supplied, the command enters prepare-only mode and refreshes request artifact templates for the scenario.","With --validate, validate only the response against the schema after the request is sent.","With --force, refresh the operation schema and regenerate the request artifact from defaults.","With --force-request, regenerate only the request artifact from the cached operation schema without refreshing the schema.",'With --update-request, patch the request artifact using flattened dot-notation keys. Nested JSON objects are accepted, but the provided value must be valid JSON. With --update-request-encoded, pass base64url-encoded JSON instead. With --omit-empty on a single-operation request, remove empty-string values from schema-optional fields after updates and persist the cleaned artifact; this option is not available in multi-operation prepare-only mode. With --header, merge JSON headers into the request. With --header-encoded, pass base64url-encoded JSON headers instead. Cookies received from responses are saved per API. Use get-env --cookie-for <operationId> or --cookie-for-url <url> to retrieve an applicable Cookie header for explicit forwarding; requests do not automatically attach saved cookies in this build. With --no-cookie-jar, skip cookie loading and updates for this request. With --verbose-transport, include request headers passed to fetch in transport metadata with sensitive values redacted. Binary fields can be set to a file path string or a file descriptor object. Set a field to "__delete__" to remove it.'].join(" "),arguments:[{name:"operationId",type:"string[]",required:!0,positional:!0,description:"One or more operationIds to invoke. Multiple values switch the command into prepare-only mode for a multi-step scenario."},{name:"api",type:"string",required:!1,flag:!0,description:"The API name as defined in .openapi-skills/config.json; optional only when exactly one API is installed."},{name:"validate",type:"flag",required:!1,flag:!0,description:"Validate only the response against the schema after the request is sent. Does not validate the request body or guarantee a response exists."},{name:"force",type:"flag",required:!1,flag:!0,description:"Refresh the operation schema and overwrite the request artifact with defaults."},{name:"force-request",type:"flag",required:!1,flag:!0,description:"Force overwrite only the request artifact with defaults from the cached operation schema; does not refresh the operation schema. If used with --force, --force behavior applies."},{name:"omit-empty",type:"flag",required:!1,flag:!0,description:"For single-operation requests, remove empty-string values from schema-optional fields after updates and persist the cleaned request artifact."},{name:"update-request",type:"json",required:!1,flag:!0,description:'Patch request artifact before making the request. Only flattened object dot-notation keys are allowed. Binary fields can be set to a file path string or file descriptor object. Set a field to "__delete__" to remove it. Use with --force-request to rebuild defaults from the cached schema, or --force to refresh the schema too.'},{name:"update-request-encoded",type:"string",required:!1,flag:!0,description:"Patch request artifact before making the request using base64url-encoded JSON. Use this when quoting is unreliable."},{name:"header",type:"json",required:!1,flag:!0,description:"Additional headers as a JSON string."},{name:"header-encoded",type:"string",required:!1,flag:!0,description:"Additional headers as base64url-encoded JSON. Use this when quoting is unreliable."},{name:"no-cookie-jar",type:"flag",required:!1,flag:!0,description:"Do not load, send, or update cookies for this request."},{name:"verbose-transport",type:"flag",required:!1,flag:!0,description:"Include request headers passed to fetch in transport metadata with sensitive values redacted."}],examples:["openapi-skills request getPetById --api petstore","openapi-skills request getPetById --api petstore --validate","openapi-skills request createPet --api petstore --omit-empty",`openapi-skills request getPetById --api petstore --force-request --update-request '{"user.profile.name":"Ada"}'`,"openapi-skills request getPetById --api petstore --force-request","openapi-skills request getPetById --api petstore --force --update-request-encoded eyJyZXF1ZXN0Qm9keS5pZCI6MTJ9",`openapi-skills request getPetById --api petstore --update-request '{"user.profile.name":"Ada"}'`,`openapi-skills request getPetById --api petstore --update-request '{"parameters.0.id":1}'`,"openapi-skills request getPetById --api petstore --header-encoded eyJBdXRob3JpemF0aW9uIjoiQmVhcmVyIGFiYyJ9",`openapi-skills request getPetById --api petstore --update-request '{"parameters.0":"__delete__"}'`,"openapi-skills request operationId1 operationId2 --api petstore"],returns:{type:"json",description:"Returns raw request and response for single-operation requests, or a structured batch preparation summary when multiple operationIds are supplied."},sideEffects:{writesFiles:!0,readsFiles:!0,network:!0},constraints:{destructive:!1,idempotent:!1,requiresParsedApi:!0},filesWritten:["request artifact","response artifact","response-schema artifact (when response has JSON body)"]};to=C.command("set-env").option("--api <apiName>","API name to use. Optional when exactly one API is installed.").option("--base-url <url>","Base URL for the API environment.").option("--auth <json>","Authentication headers as a JSON string.").option("--auth-encoded <base64url>","Authentication headers as base64url-encoded JSON. Use this when a shell or agent may strip quotes from literal JSON.").option("--clear-cookies","Delete the saved cookie jar for this API.").option("--var <key=value>","Set a runtime variable for the API environment. Repeatable.",(e,t)=>[...Array.isArray(t)?t:t?[t]:[],e]).description("Set or update the runtime environment for a parsed API.").addHelpText("after",["Use this command to set baseUrl, auth headers, and runtime vars for a parsed API. Use --clear-cookies to delete the saved per-API cookie jar.","Pass auth headers with --auth as JSON or --auth-encoded as base64url-encoded JSON when quoting is unreliable.","","Examples:",` set-env --api petstore --base-url https://dev.example.com --auth '{"Authorization":"Bearer abc"}'`," set-env --api petstore --auth-encoded eyJBdXRob3JpemF0aW9uIjoiQmVhcmVyIGFiYyJ9",` set-env --api petstore --auth '{"Authorization":"Bearer abc"}'`," set-env --api petstore --var userId=123"].join(`
|
|
71
|
+
`)).action(async e=>{let t=await he(e.api);if(!t)return;let r=typeof e.baseUrl=="string"?e.baseUrl.trim():"",n=r.length>0?r:void 0,s;if(typeof e.auth=="string"&&typeof e.authEncoded=="string"){d.result(k("INVALID_JSON_ARGUMENT",{summary:"Provide only one of --auth or --auth-encoded.",message:"--auth and --auth-encoded are mutually exclusive.",context:{api_name:t,auth:e.auth,auth_encoded:e.authEncoded},nextCommand:`openapi-skills set-env --api ${t} --auth-encoded eyJBdXRob3JpemF0aW9uIjoiQmVhcmVyIGFiYyJ9`})),process.exitCode=1;return}if(typeof e.auth=="string")try{let a=JSON.parse(e.auth);if(typeof a!="object"||Array.isArray(a)||!a)throw new Error("Auth must be a JSON object");s=a}catch{d.result(k("INVALID_JSON_ARGUMENT",{summary:"--auth JSON is malformed.",message:`Invalid --auth JSON. Example: '{"Authorization":"Bearer abc"}'`,context:{api_name:t,auth:e.auth??null},nextCommand:`openapi-skills set-env --api ${t} --auth '{"Authorization":"Bearer abc"}'`})),process.exitCode=1;return}if(typeof e.authEncoded=="string")try{let a=kt(e.authEncoded,"--auth-encoded"),p={};for(let[c,u]of Object.entries(a)){if(typeof u!="string")throw new Error(`Auth header "${c}" must be a string`);p[c]=u}s=p}catch(a){d.result(k("INVALID_JSON_ARGUMENT",{summary:"--auth-encoded value is malformed.",message:`Invalid base64url for --auth-encoded: ${a instanceof Error?a.message:String(a)}`,context:{api_name:t,auth_encoded:e.authEncoded},nextCommand:`openapi-skills set-env --api ${t} --auth-encoded eyJBdXRob3JpemF0aW9uIjoiQmVhcmVyIGFiYyJ9`})),process.exitCode=1;return}let i=e.var?Array.isArray(e.var)?e.var:[e.var]:[],o={};for(let a of i){let p=a.indexOf("=");if(p<=0){d.result(k("INVALID_VARIABLE_SYNTAX",{summary:"Invalid --var syntax.",message:`Invalid --var value "${a}". Use key=value.`,context:{api_name:t,variable:a},nextCommand:`openapi-skills set-env --api ${t} --var userId=123`})),process.exitCode=1;return}let c=a.slice(0,p).trim(),u=a.slice(p+1);if(!c){d.result(k("INVALID_VARIABLE_SYNTAX",{summary:"Invalid --var syntax.",message:`Invalid --var value "${a}". Use key=value.`,context:{api_name:t,variable:a},nextCommand:`openapi-skills set-env --api ${t} --var userId=123`})),process.exitCode=1;return}o[c]=u}try{let a={};n!==void 0&&(a.baseUrl=n),s!==void 0&&(a.auth=s),Object.keys(o).length>0&&(a.vars=o),Object.keys(a).length>0&&await Ie(t,a),e.clearCookies&&await Fr(t),d.result(q({apiName:t,baseUrl:n,hasAuth:s!==void 0,varCount:Object.keys(o).length,cookiesCleared:e.clearCookies===!0},{kind:"set-env-result"}))}catch(a){d.result(k("CONFIG_ERROR",{summary:"Failed to update API environment.",message:H(a),context:{api_name:t,base_url:n??null,var_count:Object.keys(o).length},nextCommand:`openapi-skills set-env --api ${t}`})),process.exitCode=1}});to.agentMeta={name:"set-env",category:"Configuration",usage:"openapi-skills set-env [--api <apiName>] [--base-url <url>] [--auth <json>] [--auth-encoded <base64url>] [--var key=value] [--clear-cookies]",description:"Set or update the runtime environment for a parsed API. Persists baseUrl, auth headers, and named vars in config.json; --clear-cookies removes saved cookies.",arguments:[{name:"api",type:"string",required:!1,flag:!0,description:"The API name as defined in .openapi-skills/config.json; optional only when exactly one API is installed."},{name:"base-url",type:"string",required:!1,flag:!0,description:"Base URL for the API environment."},{name:"auth",type:"json",required:!1,flag:!0,description:"Authentication headers as a JSON object."},{name:"auth-encoded",type:"string",required:!1,flag:!0,description:"Authentication headers as base64url-encoded JSON."},{name:"var",type:"string",required:!1,flag:!0,description:"Runtime variable in key=value form. Repeatable."},{name:"clear-cookies",type:"flag",required:!1,flag:!0,description:"Delete the saved cookie jar for this API."}],examples:[`openapi-skills set-env --api petstore --base-url https://dev.example.com --auth '{"Authorization":"Bearer abc"}'`,"openapi-skills set-env --api petstore --auth-encoded eyJBdXRob3JpemF0aW9uIjoiQmVhcmVyIGFiYyJ9",`openapi-skills set-env --api petstore --auth '{"Authorization":"Bearer abc"}'`,"openapi-skills set-env --api petstore --var userId=123 --var env=staging"],returns:{type:"json",description:"Returns success or error message."},sideEffects:{writesFiles:!0,readsFiles:!0,network:!1},constraints:{destructive:!1,idempotent:!1,requiresParsedApi:!1},filesWritten:["config.json"]};ro=C.command("get-env").option("--api <apiName>","API name to use. Optional when exactly one API is installed.").option("--base-url","Include baseUrl in output").option("--auth","Include auth headers in output").option("--cookie","Return the applicable Cookie header value for explicit forwarding.").option("--cookie-for <operationId>","Scope the returned Cookie header to this operation's resolved request URL.").option("--cookie-for-url <url>","Scope the returned Cookie header to an explicit URL on the configured API origin.").option("--cookies","Return a summary of saved cookie names, scope, and expiry.").option("--var <key=value>","Request one or more runtime vars. Repeatable; only the key part is used to filter output.",(e,t)=>[...Array.isArray(t)?t:t?[t]:[],e]).description("Read API environment configuration and saved cookie data. Returns all values unless a specific field is requested via flags; cookie values are secrets.").action(async e=>{let t=await he(e.api);if(t)try{let r=e.baseUrl===!0,n=e.auth===!0;if(e.cookieFor&&e.cookieForUrl)throw new Error("Specify only one of --cookie-for <operationId> or --cookie-for-url <url>.");let s=e.cookie===!0||typeof e.cookieFor=="string"||typeof e.cookieForUrl=="string",i=e.cookies===!0,o=e.var?Array.isArray(e.var)?e.var:[e.var]:[],a=r||n||s||i||o.length>0,p=await dt(t,"baseUrl"),c=await dt(t,"authHeaders"),u=await dt(t,"vars"),m=Array.isArray(u)?u:[],f=Object.fromEntries(m),g=typeof p=="string"?p:void 0;if((s||i)&&!g)throw new Error("Cannot read cookies because this API has no configured base URL. Set it with set-env --base-url first.");let l={apiName:t};if((!a||r)&&(l.baseUrl=p),(!a||n)&&(l.authHeaders=c),s||i){let b=await ht(t);if(!g)throw new Error("Cannot read cookies because this API has no configured base URL. Set it with set-env --base-url first.");if(s){let y=e.cookieFor?vn(g,await en(t,e.cookieFor,g)):vn(g,e.cookieForUrl);l.cookieHeader=Ur(b,y)??null}i&&(l.cookies=Gr(b,g))}if(!a)l.vars=m;else if(o.length>0){let b=o.map(y=>{let h=y.indexOf("=");return h>=0?y.slice(0,h).trim():y.trim()}).filter(Boolean);l.vars=b.map(y=>[y,f[y]]).filter(([y,h])=>h!==void 0)}d.result(q(l,{kind:"get-env-result"})),process.exitCode=0}catch(r){d.result(k("CONFIG_ERROR",{summary:"Failed to read API environment.",message:r instanceof Error?r.message:String(r),context:{api_name:t},nextCommand:`openapi-skills get-env --api ${t}`})),process.exitCode=1}});ro.agentMeta={name:"get-env",category:"Configuration",usage:"openapi-skills get-env [--api <apiName>] [--base-url] [--auth] [--cookie] [--cookie-for <operationId> | --cookie-for-url <url>] [--cookies]",description:"Read environment configuration for an API. --cookie returns a ready-to-forward Cookie header for the configured base URL; --cookie-for resolves an operation's request URL; --cookie-for-url scopes it to an explicit URL on the configured API origin. --cookies returns cookie names and scope metadata without values.",arguments:[{name:"api",type:"string",required:!1,flag:!0,description:"The API name as defined in .openapi-skills/config.json; optional only when exactly one API is installed."},{name:"cookie",type:"flag",required:!1,flag:!0,description:"Return the applicable Cookie header value for explicit forwarding. Treat it as secret."},{name:"cookie-for",type:"string",required:!1,flag:!0,description:"Resolve this operation's request URL and return cookies applicable to it. Treat the result as secret."},{name:"cookie-for-url",type:"string",required:!1,flag:!0,description:"Scope the Cookie header to an explicit URL on this API's configured origin."},{name:"cookies",type:"flag",required:!1,flag:!0,description:"Return saved cookie names, scope, and expiry without cookie values."}],examples:["openapi-skills get-env --api petstore","openapi-skills get-env --api petstore --base-url","openapi-skills get-env --api petstore --cookie","openapi-skills get-env --api petstore --cookie-for getProtected","openapi-skills get-env --api petstore --cookie-for-url https://api.example.com/auth/otp","openapi-skills get-env --api petstore --var userId"],returns:{type:"json",description:"Prints selected environment values and, when requested, a cookieHeader string or cookie summary."},sideEffects:{writesFiles:!1,readsFiles:!0,network:!1},constraints:{destructive:!1,idempotent:!0,requiresParsedApi:!1},filesWritten:[]};no=C.command("get-api-names").description("List all available API names (parsed OpenAPI bundles) in the project.").action(async()=>{try{let e=await se();d.result(q({apiNames:e},{kind:"api-list"})),(!e||e.length===0)&&d.warn("No APIs were generated yet. Run first: openapi-skills generate <openapi-source> [options]")}catch{d.result(k("CONFIG_ERROR",{summary:"Failed to list APIs.",message:"Run `openapi-skills generate [options] [openapi-source]` to parse APIs first.",context:{},nextCommand:"openapi-skills generate <openapi-source>"})),process.exitCode=1}});no.agentMeta={name:"get-api-names",category:"Navigation",usage:"openapi-skills get-api-names",description:"List all available parsed API names in the project. Output is always JSON: { kind: 'api-list', apiNames: [<apiName>, ...] }.",arguments:[],examples:["openapi-skills get-api-names"],returns:{type:"json",description:"Returns { kind: 'api-list', apiNames: [<apiName>, ...] } as JSON."},sideEffects:{writesFiles:!1,readsFiles:!0,network:!1},constraints:{destructive:!1,idempotent:!0,requiresParsedApi:!1},filesWritten:[]};so=C.command("remove-api <apiName>").description("Remove an API from config.json and delete its .openapi-skills directory after confirmation.").option("-y, --yes","Confirm removal automatically without prompting.").action(async(e,t)=>{let r=e;try{if(!(await se()).includes(r)){d.result(k("UNKNOWN_API",{summary:`API '${r}' is not installed.`,message:`API '${r}' is not installed.`,context:{api_name:r},nextCommand:"openapi-skills get-api-names"})),process.exitCode=1;return}if(!(t?.yes===!0?!0:await yn(r))){d.result(q({cancelled:!0,apiName:r},{kind:"remove-api-result"})),process.exitCode=0;return}let i=await br(r);if(i.ok){d.result(q({removedApi:i.data.removedApi,message:i.message},{kind:"remove-api-result"})),process.exitCode=0;return}let o=/config/i.test(i.error.message)?"CONFIG_ERROR":i.error.type==="ApiNotFound"?"UNKNOWN_API":"REQUEST_FAILED";d.result(k(o,{summary:`Remove API error for ${r}.`,message:i.error.message,context:{api_name:r},nextCommand:o==="UNKNOWN_API"?"openapi-skills get-api-names":"None"})),process.exitCode=1;return}catch(n){let s=n instanceof Error?n.message:String(n);d.result(k(/config/i.test(s)?"CONFIG_ERROR":"REQUEST_FAILED",{summary:`Remove API error for ${r}.`,message:s,context:{api_name:r},nextCommand:/config/i.test(s)?"None":`openapi-skills remove-api ${r} --yes`})),process.exitCode=1}});so.agentMeta={name:"remove-api",category:"Configuration",usage:"openapi-skills remove-api <apiName> [--yes|-y]",description:"Remove a parsed API after confirmation. The command deletes the API entry from config.json and removes the API directory under .openapi-skills.",arguments:[{name:"apiName",type:"string",required:!0,positional:!0,description:"The API name to remove."},{name:"yes",type:"flag",required:!1,flag:!0,description:"Confirm removal automatically without prompting."}],examples:["openapi-skills remove-api petstore --yes"],returns:{type:"json",description:"Returns a structured success or error result for the deletion operation."},sideEffects:{writesFiles:!0,readsFiles:!0,network:!1},constraints:{destructive:!0,idempotent:!1,requiresParsedApi:!0},filesWritten:["config.json"]};C.parse(process.argv)});await ln();export{C as program};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tzurp/openapi-skills",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.5.0",
|
|
4
4
|
"description": "CLI toolkit for exploring OpenAPI and GraphQL schemas, generating operation artifacts, validators, and tests. Includes an agent skill bundle that teaches AI tools how to operate the CLI safely and efficiently.",
|
|
5
5
|
"bin": {
|
|
6
6
|
"openapi-skills": "dist/cli.min.js"
|
package/skill-templates/SKILL.md
CHANGED
|
@@ -22,7 +22,7 @@ Before doing anything else, check these first:
|
|
|
22
22
|
- This is the sole exception to Rule 1's ban on shell-based data transformation. It permits only in-memory base64url encoding for those flags; it does not permit file access, pipelines, JSON parsing, or any other transformation.
|
|
23
23
|
- If no safe encoder is available, use the corresponding raw JSON flag only when the shell can pass the JSON without changing it. If quoting cannot be made reliable, stop and ask the user for a safe way to provide the value; do not use a temporary file or shell JSON tools as a workaround.
|
|
24
24
|
- For auth headers, encode the final header object as-is. Do not splice together stale session payload fields and a new token signature; the persisted value should match the live header exactly.
|
|
25
|
-
-
|
|
25
|
+
- Persist explicitly supplied auth headers with `set-env --auth` or `set-env --auth-encoded` only when they should be reused; use `request --header` or `request --header-encoded` for a one-off request instead. Saved auth headers are merged into requests, but this does not automatically attach cookies stored from responses in the per-API cookie jar. The raw and encoded forms are alternatives, not flags to combine.
|
|
26
26
|
- Prefer a minimal flow that builds the exact header object, applies the permitted in-memory encoding, persists it with `set-env --auth-encoded`, and checks the round trip with `get-env`.
|
|
27
27
|
- If a live `request` command fails in the agent shell but works in a manual terminal, request elevated execution and prefer re-running `request` with elevated privileges before treating it as a CLI bug.
|
|
28
28
|
|
|
@@ -64,6 +64,7 @@ When you need CLI help as an agent, use `openapi-skills --help --silent` so the
|
|
|
64
64
|
- Use the CLI's upload support directly instead of inventing ad-hoc body shapes.
|
|
65
65
|
|
|
66
66
|
Fast defaults:
|
|
67
|
+
- For single-API commands, `--api` may be omitted only when exactly one API is installed. If the CLI reports multiple APIs, pass `--api <apiName>` using one of the listed names; never guess which API to use.
|
|
67
68
|
- `openapi-skills request <operationId> --api <apiName>`
|
|
68
69
|
- `openapi-skills get-operation <operationId> --api <apiName> --request`
|
|
69
70
|
- `openapi-skills get-operation-artifact <operationId> --api <apiName> --request`
|
|
@@ -193,18 +194,36 @@ All commands use Bash syntax: `openapi-skills <command> [options]`.
|
|
|
193
194
|
3. Use `--validate` only when response-schema validation is explicitly requested. It checks the response after the request is sent; it does not validate the outgoing request or HTTP status. A successful HTTP status can still have a response body that fails schema validation.
|
|
194
195
|
4. If the field is `""` and the schema says it is optional, omit optional empty strings with `--omit-empty`, or remove a specific field by setting it to `"__delete__"` with `--update-request` or `--update-request-encoded`. Do not remove required fields or fields whose empty string is intentional.
|
|
195
196
|
5. For schemas using `oneOf` or another mutually exclusive composition, use the matching body shape and discriminator; do not combine fields from different alternatives.
|
|
196
|
-
6. Use `--force-request`
|
|
197
|
+
6. Use `--force-request` when you need to regenerate a schema-shaped request template without refreshing its operation schema. `--force` also refreshes the operation schema and resets the request artifact to schema defaults. Either reset discards prior request values and patches, so include any needed patch in the same request invocation. These flags do not clear auth saved by `set-env`; configured auth headers are merged into each request, including requests that rebuild the artifact. For the first authenticated smoke request, omit both force flags. If a forced protected request returns 401, retry without the force flag and check the saved auth with `get-env`.
|
|
197
198
|
7. Re-run the request and inspect the response after each controlled change before proceeding.
|
|
198
199
|
|
|
199
200
|
### Persist API Authentication
|
|
200
201
|
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
202
|
+
For OpenAPI, inspect the operation's security requirements and referenced scheme. For GraphQL, consult the API documentation or configuration because its SDL may not describe authentication. The CLI does not infer or enforce these requirements. Public operations need no auth; protected REST or GraphQL operations need their required auth on each request. Headers saved with `set-env --auth` are merged into each request; headers passed per request are one-off. This is separate from the cookie jar: response cookies are persisted there, but this CLI does not automatically attach them to later requests. Retrieve a cookie with `get-env --cookie-for <operationId>` and explicitly pass it as a request header when needed. The jar and saved auth headers are independent; `get-env --auth` only reads saved headers and does not set them.
|
|
203
|
+
|
|
204
|
+
GraphQL requests merge `Content-Type: application/json`, saved auth headers, then per-request headers. Matching names are merged case-insensitively, and per-request values take precedence. GraphQL has no operation-level header parameters. Cookie-based auth can be forwarded explicitly with a `Cookie` request header; requests do not automatically attach cookies from the per-API cookie store.
|
|
205
|
+
|
|
206
|
+
1. Run `openapi-skills get-api-names`. If the API is absent, confirm the schema source and base URL with the user, then generate it once with `openapi-skills generate <schemaPath> --base-url <url>`. Do not regenerate an already configured API just to begin authentication.
|
|
207
|
+
2. Before changing the base URL or sending credentials, confirm the intended environment and host with the user. Configure it with `openapi-skills set-env --api <apiName> --base-url <url>`, then verify it with `openapi-skills get-env --api <apiName> --base-url`.
|
|
208
|
+
Discover candidate operations with filtered `list` queries, then inspect candidates with `describe`. Treat words such as `login` and `token` as search hints, not proof of an auth flow.
|
|
209
|
+
3. Inspect the operation with `openapi-skills describe <operationId> --api <apiName>` and inspect the request and response shapes with `openapi-skills get-operation <operationId> --api <apiName> --request` and `--response-schema`. Determine the authentication sequence, security scheme, credential path, and value format from the API schema; do not assume Bearer auth, token names, operation IDs, or response paths. If the CLI output does not expose the referenced security-scheme definition, ask the user for the relevant schema details rather than guessing.
|
|
210
|
+
4. Classify the flow from the schema. Credentials already supplied by the user or an approved environment need no login operation; a single- or multi-step authentication exchange should follow the schema-defined sequence. Build each payload from its inspected request shape and use Rule 0 for JSON transport. Run and inspect each intended auth operation in order; do not send a mutating operation merely to create an artifact for inspection. Response artifacts separate the contract body from transport metadata: use `--get body.<path>` for response fields and `--get transport.setCookies` to inspect raw `Set-Cookie` values. `transport` also includes allowlisted response headers and available content metadata; `--verbose-transport` adds request headers passed to fetch with sensitive values redacted. `--validate` validates only the body against the schema for the returned HTTP status. After a response is available, confirm the credential path with `--response-schema`, then extract only that value with `openapi-skills get-operation <operationId> --api <apiName> --response --get body.<path>`. Treat extracted credentials as secrets.
|
|
211
|
+
5. For REST cookie-bound sequences, responses save received cookies per API, but requests do not attach them automatically. After each response, use `openapi-skills get-env --api <apiName> --cookie-for <nextOperationId>` to retrieve the `Cookie` header applicable to that operation's resolved request URL, then explicitly pass it with `--header` or `--header-encoded`. The CLI uses the operation's current request artifact values, or the same schema-derived defaults used to create a new request template. If the intended path parameters differ from those values, use `--cookie-for-url <full-url>` instead; explicit URLs must use the configured API origin. Both forms respect cookie Path and Secure attributes. Repeat this after responses that update cookies. The returned value is a secret; keep it private and do not paste it into chat or logs. `--no-cookie-jar` skips cookie loading and updates for one request, and `set-env --clear-cookies` clears saved cookie state. Cookie scope handling covers basic domain, path, expiry, and Secure rules; it does not emulate browser SameSite or third-party policies, and cookies from intermediate redirects are not captured. The cookie jar is independent of saved auth headers: `set-env --auth` values are sent because they are explicitly saved as headers, not because they came from the cookie jar. The jar does not update saved auth headers, and those saved headers do not enable automatic jar replay. Avoid persisting short-lived response cookies with `set-env --auth`.
|
|
212
|
+
6. To persist long-lived headers for reuse on REST or GraphQL requests, use exactly one of `openapi-skills set-env --api <apiName> --auth <json>` or `openapi-skills set-env --api <apiName> --auth-encoded <base64urlJson>`. The flags are mutually exclusive. Use `--auth` only when shell quoting is reliable; prefer `--auth-encoded` when quoting is fragile. Persist the exact current header object required by the scheme, not stale auth values. These explicitly saved header values are merged into each request; they are not populated or refreshed from response cookies. `get-env --api <apiName> --auth` displays saved header values; inspect its output only in a private context and never paste it into chat or logs.
|
|
213
|
+
7. For a one-off REST or GraphQL request, use exactly one of `--header <json>` or `--header-encoded <base64urlJson>` on `request`; these headers are not persisted. CLI-supplied headers override saved auth for the same header name. In REST, an explicit header parameter in the operation's request artifact is applied afterward and can override either value; GraphQL has no such parameter layer. To forward a stored cookie, use `get-env --api <apiName> --cookie-for <operationId>` and pass the result explicitly. If the target path parameters differ from the current request artifact or schema defaults, use `--cookie-for-url <full-url>`. Do not silently substitute cookies for a different security mechanism.
|
|
214
|
+
8. In PowerShell, if `AUTH_HEADER_NAME` and `AUTH_HEADER_VALUE` have been supplied securely and formatted according to the schema, construct and encode the exact header object in memory:
|
|
215
|
+
|
|
216
|
+
```powershell
|
|
217
|
+
$encoded = node -e "process.stdout.write(Buffer.from(JSON.stringify({[process.env.AUTH_HEADER_NAME]:process.env.AUTH_HEADER_VALUE})).toString('base64url'))"
|
|
218
|
+
openapi-skills set-env --api <apiName> --auth-encoded $encoded
|
|
219
|
+
openapi-skills get-env --api <apiName> --auth
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
The verification command displays saved credentials. Keep that output private; do not print or expose credentials or the encoded value in chat, logs, or diagnostics. For other schemes, encode the exact schema-confirmed header object.
|
|
223
|
+
9. Make the first authenticated smoke request without `--force` or `--force-request`, using an operation confirmed by its schema to be safe and read-only. These flags rebuild the request artifact (`--force` also refreshes the operation schema); they do not clear saved auth or cookies. Reapply request patches in the same invocation when rebuilding.
|
|
224
|
+
10. If the safe smoke request returns 401, do not force-reset artifacts or blindly retry. Recheck the operation's security requirement and exact header name/value format; privately inspect saved auth with `get-env --auth` and, for cookie flows, retrieve the applicable header with `get-env --api <apiName> --cookie-for <operationId>` before explicitly forwarding it on a safe read-only request. Use `--cookie-for-url <full-url>` when the intended path parameters are not represented in the operation's request artifact or schema defaults. Do not retry a mutating operation without confirmation.
|
|
225
|
+
|
|
226
|
+
`get-operation` requires a prior `request` to create its artifacts. Inspect artifacts only when they already exist or after a request that is safe and necessary; do not send a mutating auth operation merely to populate them. Use `describe` and available schema details to prepare intended authentication calls.
|
|
208
227
|
|
|
209
228
|
### Prepare a Multi-Step Flow
|
|
210
229
|
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
{
|
|
2
|
+
"skill_name": "openapi-skills",
|
|
3
|
+
"evals": [
|
|
4
|
+
{
|
|
5
|
+
"id": 1,
|
|
6
|
+
"prompt": "I imported an API whose schema has both public and protected read operations. The protected operation uses a schema-defined header, and I want later requests to reuse my credential. Explain how to discover the right auth details, save the header, verify it without exposing the secret, and make a first safe request.",
|
|
7
|
+
"expected_output": "Distinguish public from protected operations, derive the auth scheme and header from the schema, use set-env with either --auth or --auth-encoded, explain that get-env --auth only reads saved headers and may display secrets, and recommend a first read-only request without force flags.",
|
|
8
|
+
"files": []
|
|
9
|
+
},
|
|
10
|
+
{
|
|
11
|
+
"id": 2,
|
|
12
|
+
"prompt": "I only need to send one request with an API key and do not want it stored for future calls. What request flags should I use, and what should I do in PowerShell if JSON quoting is unreliable?",
|
|
13
|
+
"expected_output": "Use request --header or request --header-encoded for one-off auth, not set-env; show an in-memory base64url approach using a schema-appropriate header and caution against printing credentials.",
|
|
14
|
+
"files": []
|
|
15
|
+
},
|
|
16
|
+
{
|
|
17
|
+
"id": 3,
|
|
18
|
+
"prompt": "A request template looks stale, but I already saved the API auth. I need to rebuild the template and patch request values in the same call. Will that clear auth, and what is a safe way to diagnose a 401?",
|
|
19
|
+
"expected_output": "Explain the distinct resets of --force and --force-request, that neither clears saved auth, and that --update-request or --update-request-encoded can accompany the force flag. Recommend a first smoke request without force and a schema-based, read-only 401 diagnostic that keeps credentials private.",
|
|
20
|
+
"files": []
|
|
21
|
+
}
|
|
22
|
+
]
|
|
23
|
+
}
|