specli 0.0.5 → 0.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (209) hide show
  1. package/bin/specli.js +19 -0
  2. package/cli.ts +13 -4
  3. package/dist/cli.d.ts +3 -0
  4. package/dist/cli.d.ts.map +1 -0
  5. package/dist/cli.js +2331 -0
  6. package/dist/cli.js.map +53 -0
  7. package/dist/index.d.ts +2 -0
  8. package/dist/index.d.ts.map +1 -0
  9. package/dist/index.js +2032 -0
  10. package/dist/index.js.map +48 -0
  11. package/dist/src/ai/tools.d.ts +139 -0
  12. package/dist/src/ai/tools.d.ts.map +1 -0
  13. package/dist/src/ai/tools.js +1656 -0
  14. package/dist/src/ai/tools.js.map +45 -0
  15. package/dist/src/cli/auth-requirements.d.ts +10 -0
  16. package/dist/src/cli/auth-requirements.d.ts.map +1 -0
  17. package/dist/src/cli/auth-requirements.js +66 -0
  18. package/dist/src/cli/auth-requirements.js.map +10 -0
  19. package/dist/src/cli/auth-schemes.d.ts +22 -0
  20. package/dist/src/cli/auth-schemes.d.ts.map +1 -0
  21. package/dist/src/cli/auth-schemes.js +116 -0
  22. package/dist/src/cli/auth-schemes.js.map +11 -0
  23. package/dist/src/cli/capabilities.d.ts +32 -0
  24. package/dist/src/cli/capabilities.d.ts.map +1 -0
  25. package/dist/src/cli/capabilities.js +45 -0
  26. package/dist/src/cli/capabilities.js.map +10 -0
  27. package/dist/src/cli/command-id.d.ts +8 -0
  28. package/dist/src/cli/command-id.d.ts.map +1 -0
  29. package/dist/src/cli/command-id.js +18 -0
  30. package/dist/src/cli/command-id.js.map +11 -0
  31. package/dist/src/cli/command-index.d.ts +6 -0
  32. package/dist/src/cli/command-index.d.ts.map +1 -0
  33. package/dist/src/cli/command-index.js +15 -0
  34. package/dist/src/cli/command-index.js.map +10 -0
  35. package/dist/src/cli/command-model.d.ts +40 -0
  36. package/dist/src/cli/command-model.d.ts.map +1 -0
  37. package/dist/src/cli/command-model.js +274 -0
  38. package/dist/src/cli/command-model.js.map +18 -0
  39. package/dist/src/cli/compile.d.ts +15 -0
  40. package/dist/src/cli/compile.d.ts.map +1 -0
  41. package/dist/src/cli/compile.js +146 -0
  42. package/dist/src/cli/compile.js.map +11 -0
  43. package/dist/src/cli/crypto.d.ts +2 -0
  44. package/dist/src/cli/crypto.d.ts.map +1 -0
  45. package/dist/src/cli/crypto.js +15 -0
  46. package/dist/src/cli/crypto.js.map +10 -0
  47. package/dist/src/cli/derive-name.d.ts +9 -0
  48. package/dist/src/cli/derive-name.d.ts.map +1 -0
  49. package/dist/src/cli/derive-name.js +70 -0
  50. package/dist/src/cli/derive-name.js.map +10 -0
  51. package/dist/src/cli/exec.d.ts +14 -0
  52. package/dist/src/cli/exec.d.ts.map +1 -0
  53. package/dist/src/cli/exec.js +2077 -0
  54. package/dist/src/cli/exec.js.map +49 -0
  55. package/dist/src/cli/main.d.ts +10 -0
  56. package/dist/src/cli/main.d.ts.map +1 -0
  57. package/dist/src/cli/main.js +2032 -0
  58. package/dist/src/cli/main.js.map +48 -0
  59. package/dist/src/cli/naming.d.ts +12 -0
  60. package/dist/src/cli/naming.d.ts.map +1 -0
  61. package/dist/src/cli/naming.js +216 -0
  62. package/dist/src/cli/naming.js.map +12 -0
  63. package/dist/src/cli/operations.d.ts +3 -0
  64. package/dist/src/cli/operations.d.ts.map +1 -0
  65. package/dist/src/cli/operations.js +103 -0
  66. package/dist/src/cli/operations.js.map +10 -0
  67. package/dist/src/cli/params.d.ts +19 -0
  68. package/dist/src/cli/params.d.ts.map +1 -0
  69. package/dist/src/cli/params.js +79 -0
  70. package/dist/src/cli/params.js.map +12 -0
  71. package/dist/src/cli/pluralize.d.ts +2 -0
  72. package/dist/src/cli/pluralize.d.ts.map +1 -0
  73. package/dist/src/cli/pluralize.js +43 -0
  74. package/dist/src/cli/pluralize.js.map +10 -0
  75. package/dist/src/cli/positional.d.ts +19 -0
  76. package/dist/src/cli/positional.d.ts.map +1 -0
  77. package/dist/src/cli/positional.js +39 -0
  78. package/dist/src/cli/positional.js.map +10 -0
  79. package/dist/src/cli/request-body.d.ts +20 -0
  80. package/dist/src/cli/request-body.d.ts.map +1 -0
  81. package/dist/src/cli/request-body.js +82 -0
  82. package/dist/src/cli/request-body.js.map +12 -0
  83. package/dist/src/cli/runtime/argv.d.ts +3 -0
  84. package/dist/src/cli/runtime/argv.d.ts.map +1 -0
  85. package/dist/src/cli/runtime/argv.js +22 -0
  86. package/dist/src/cli/runtime/argv.js.map +10 -0
  87. package/dist/src/cli/runtime/auth/resolve.d.ts +9 -0
  88. package/dist/src/cli/runtime/auth/resolve.d.ts.map +1 -0
  89. package/dist/src/cli/runtime/auth/resolve.js +38 -0
  90. package/dist/src/cli/runtime/auth/resolve.js.map +10 -0
  91. package/dist/src/cli/runtime/body-flags.d.ts +41 -0
  92. package/dist/src/cli/runtime/body-flags.d.ts.map +1 -0
  93. package/dist/src/cli/runtime/body-flags.js +86 -0
  94. package/dist/src/cli/runtime/body-flags.js.map +10 -0
  95. package/dist/src/cli/runtime/body.d.ts +15 -0
  96. package/dist/src/cli/runtime/body.d.ts.map +1 -0
  97. package/dist/src/cli/runtime/body.js +40 -0
  98. package/dist/src/cli/runtime/body.js.map +11 -0
  99. package/dist/src/cli/runtime/collect.d.ts +2 -0
  100. package/dist/src/cli/runtime/collect.d.ts.map +1 -0
  101. package/dist/src/cli/runtime/collect.js +9 -0
  102. package/dist/src/cli/runtime/collect.js.map +10 -0
  103. package/dist/src/cli/runtime/compat.d.ts +35 -0
  104. package/dist/src/cli/runtime/compat.d.ts.map +1 -0
  105. package/dist/src/cli/runtime/compat.js +62 -0
  106. package/dist/src/cli/runtime/compat.js.map +10 -0
  107. package/dist/src/cli/runtime/context.d.ts +16 -0
  108. package/dist/src/cli/runtime/context.d.ts.map +1 -0
  109. package/dist/src/cli/runtime/context.js +936 -0
  110. package/dist/src/cli/runtime/context.js.map +32 -0
  111. package/dist/src/cli/runtime/execute.d.ts +33 -0
  112. package/dist/src/cli/runtime/execute.d.ts.map +1 -0
  113. package/dist/src/cli/runtime/execute.js +670 -0
  114. package/dist/src/cli/runtime/execute.js.map +22 -0
  115. package/dist/src/cli/runtime/generated.d.ts +14 -0
  116. package/dist/src/cli/runtime/generated.d.ts.map +1 -0
  117. package/dist/src/cli/runtime/generated.js +869 -0
  118. package/dist/src/cli/runtime/generated.js.map +23 -0
  119. package/dist/src/cli/runtime/headers.d.ts +9 -0
  120. package/dist/src/cli/runtime/headers.d.ts.map +1 -0
  121. package/dist/src/cli/runtime/headers.js +36 -0
  122. package/dist/src/cli/runtime/headers.js.map +10 -0
  123. package/dist/src/cli/runtime/index.d.ts +4 -0
  124. package/dist/src/cli/runtime/index.d.ts.map +1 -0
  125. package/dist/src/cli/runtime/index.js +1808 -0
  126. package/dist/src/cli/runtime/index.js.map +46 -0
  127. package/dist/src/cli/runtime/profile/secrets.d.ts +25 -0
  128. package/dist/src/cli/runtime/profile/secrets.d.ts.map +1 -0
  129. package/dist/src/cli/runtime/profile/secrets.js +51 -0
  130. package/dist/src/cli/runtime/profile/secrets.js.map +11 -0
  131. package/dist/src/cli/runtime/profile/store.d.ts +15 -0
  132. package/dist/src/cli/runtime/profile/store.d.ts.map +1 -0
  133. package/dist/src/cli/runtime/profile/store.js +102 -0
  134. package/dist/src/cli/runtime/profile/store.js.map +11 -0
  135. package/dist/src/cli/runtime/request.d.ts +36 -0
  136. package/dist/src/cli/runtime/request.d.ts.map +1 -0
  137. package/dist/src/cli/runtime/request.js +571 -0
  138. package/dist/src/cli/runtime/request.js.map +21 -0
  139. package/dist/src/cli/runtime/server-url.d.ts +8 -0
  140. package/dist/src/cli/runtime/server-url.d.ts.map +1 -0
  141. package/dist/src/cli/runtime/server-url.js +55 -0
  142. package/dist/src/cli/runtime/server-url.js.map +11 -0
  143. package/dist/src/cli/runtime/template.d.ts +5 -0
  144. package/dist/src/cli/runtime/template.d.ts.map +1 -0
  145. package/dist/src/cli/runtime/template.js +29 -0
  146. package/dist/src/cli/runtime/template.js.map +10 -0
  147. package/dist/src/cli/runtime/validate/ajv.d.ts +3 -0
  148. package/dist/src/cli/runtime/validate/ajv.d.ts.map +1 -0
  149. package/dist/src/cli/runtime/validate/ajv.js +17 -0
  150. package/dist/src/cli/runtime/validate/ajv.js.map +10 -0
  151. package/dist/src/cli/runtime/validate/coerce.d.ts +4 -0
  152. package/dist/src/cli/runtime/validate/coerce.d.ts.map +1 -0
  153. package/dist/src/cli/runtime/validate/coerce.js +60 -0
  154. package/dist/src/cli/runtime/validate/coerce.js.map +10 -0
  155. package/dist/src/cli/runtime/validate/error.d.ts +3 -0
  156. package/dist/src/cli/runtime/validate/error.d.ts.map +1 -0
  157. package/dist/src/cli/runtime/validate/error.js +21 -0
  158. package/dist/src/cli/runtime/validate/error.js.map +10 -0
  159. package/dist/src/cli/runtime/validate/index.d.ts +5 -0
  160. package/dist/src/cli/runtime/validate/index.d.ts.map +1 -0
  161. package/dist/src/cli/runtime/validate/index.js +122 -0
  162. package/dist/src/cli/runtime/validate/index.js.map +13 -0
  163. package/dist/src/cli/runtime/validate/schema.d.ts +9 -0
  164. package/dist/src/cli/runtime/validate/schema.d.ts.map +1 -0
  165. package/dist/src/cli/runtime/validate/schema.js +36 -0
  166. package/dist/src/cli/runtime/validate/schema.js.map +10 -0
  167. package/dist/src/cli/schema-shape.d.ts +5 -0
  168. package/dist/src/cli/schema-shape.d.ts.map +1 -0
  169. package/dist/src/cli/schema-shape.js +41 -0
  170. package/dist/src/cli/schema-shape.js.map +10 -0
  171. package/dist/src/cli/schema.d.ts +30 -0
  172. package/dist/src/cli/schema.d.ts.map +1 -0
  173. package/dist/src/cli/schema.js +38 -0
  174. package/dist/src/cli/schema.js.map +10 -0
  175. package/dist/src/cli/server.d.ts +16 -0
  176. package/dist/src/cli/server.d.ts.map +1 -0
  177. package/dist/src/cli/server.js +64 -0
  178. package/dist/src/cli/server.js.map +11 -0
  179. package/dist/src/cli/spec-id.d.ts +3 -0
  180. package/dist/src/cli/spec-id.d.ts.map +1 -0
  181. package/dist/src/cli/spec-id.js +21 -0
  182. package/dist/src/cli/spec-id.js.map +11 -0
  183. package/dist/src/cli/spec-loader.d.ts +7 -0
  184. package/dist/src/cli/spec-loader.d.ts.map +1 -0
  185. package/dist/src/cli/spec-loader.js +110 -0
  186. package/dist/src/cli/spec-loader.js.map +15 -0
  187. package/dist/src/cli/stable-json.d.ts +4 -0
  188. package/dist/src/cli/stable-json.d.ts.map +1 -0
  189. package/dist/src/cli/stable-json.js +35 -0
  190. package/dist/src/cli/stable-json.js.map +10 -0
  191. package/dist/src/cli/strings.d.ts +3 -0
  192. package/dist/src/cli/strings.d.ts.map +1 -0
  193. package/dist/src/cli/strings.js +16 -0
  194. package/dist/src/cli/strings.js.map +10 -0
  195. package/dist/src/cli/types.d.ts +53 -0
  196. package/dist/src/cli/types.d.ts.map +1 -0
  197. package/dist/src/cli/types.js +9 -0
  198. package/dist/src/cli/types.js.map +10 -0
  199. package/package.json +32 -4
  200. package/src/ai/tools.ts +211 -0
  201. package/src/cli/main.ts +3 -2
  202. package/src/cli/runtime/body.ts +3 -3
  203. package/src/cli/runtime/compat.ts +89 -0
  204. package/src/cli/runtime/execute.ts +98 -39
  205. package/src/cli/runtime/generated.ts +111 -4
  206. package/src/cli/runtime/profile/secrets.ts +42 -1
  207. package/src/cli/runtime/profile/store.ts +15 -13
  208. package/src/cli/runtime/request.ts +12 -4
  209. package/src/cli/spec-loader.ts +2 -2
@@ -0,0 +1,1656 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, {
5
+ get: all[name],
6
+ enumerable: true,
7
+ configurable: true,
8
+ set: (newValue) => all[name] = () => newValue
9
+ });
10
+ };
11
+
12
+ // src/cli/runtime/body-flags.ts
13
+ var exports_body_flags = {};
14
+ __export(exports_body_flags, {
15
+ parseDotNotationFlags: () => parseDotNotationFlags,
16
+ generateBodyFlags: () => generateBodyFlags,
17
+ findMissingRequired: () => findMissingRequired
18
+ });
19
+ function generateBodyFlags(schema2, reservedFlags) {
20
+ if (!schema2 || schema2.type !== "object" || !schema2.properties) {
21
+ return [];
22
+ }
23
+ const flags = [];
24
+ const requiredSet = new Set(schema2.required ?? []);
25
+ collectFlags(schema2.properties, [], requiredSet, flags, reservedFlags);
26
+ return flags;
27
+ }
28
+ function collectFlags(properties, pathPrefix, requiredAtRoot, out, reservedFlags) {
29
+ for (const [name, propSchema] of Object.entries(properties)) {
30
+ if (!name || typeof name !== "string")
31
+ continue;
32
+ if (!propSchema || typeof propSchema !== "object")
33
+ continue;
34
+ const path = [...pathPrefix, name];
35
+ const flagName = `--${path.join(".")}`;
36
+ if (reservedFlags.has(flagName))
37
+ continue;
38
+ const t = propSchema.type;
39
+ if (t === "object" && propSchema.properties) {
40
+ const nestedRequired = new Set(propSchema.required ?? []);
41
+ collectFlags(propSchema.properties, path, nestedRequired, out, reservedFlags);
42
+ } else if (t === "string" || t === "number" || t === "integer" || t === "boolean") {
43
+ const isRequired = pathPrefix.length === 0 ? requiredAtRoot.has(name) : false;
44
+ out.push({
45
+ flag: flagName,
46
+ path,
47
+ type: t,
48
+ description: propSchema.description ?? `Body field '${path.join(".")}'`,
49
+ required: isRequired
50
+ });
51
+ }
52
+ }
53
+ }
54
+ function parseDotNotationFlags(flagValues, flagDefs) {
55
+ const result = {};
56
+ for (const def of flagDefs) {
57
+ const dotKey = def.path.join(".");
58
+ const value = flagValues[dotKey];
59
+ if (value === undefined)
60
+ continue;
61
+ setNestedValue(result, def.path, value, def.type);
62
+ }
63
+ return result;
64
+ }
65
+ function setNestedValue(obj, path, value, type) {
66
+ let current = obj;
67
+ for (let i = 0;i < path.length - 1; i++) {
68
+ const key = path[i];
69
+ if (!(key in current) || typeof current[key] !== "object") {
70
+ current[key] = {};
71
+ }
72
+ current = current[key];
73
+ }
74
+ const finalKey = path[path.length - 1];
75
+ if (type === "boolean") {
76
+ current[finalKey] = true;
77
+ } else if (type === "integer") {
78
+ current[finalKey] = Number.parseInt(String(value), 10);
79
+ } else if (type === "number") {
80
+ current[finalKey] = Number(String(value));
81
+ } else {
82
+ current[finalKey] = String(value);
83
+ }
84
+ }
85
+ function findMissingRequired(flagValues, flagDefs) {
86
+ const missing = [];
87
+ for (const def of flagDefs) {
88
+ if (!def.required)
89
+ continue;
90
+ const dotKey = def.path.join(".");
91
+ if (flagValues[dotKey] === undefined) {
92
+ missing.push(dotKey);
93
+ }
94
+ }
95
+ return missing;
96
+ }
97
+
98
+ // src/ai/tools.ts
99
+ import { tool } from "ai";
100
+ import { z } from "zod";
101
+
102
+ // src/cli/strings.ts
103
+ function kebabCase(input) {
104
+ const trimmed = input.trim();
105
+ if (!trimmed)
106
+ return "";
107
+ return trimmed.replace(/([a-z0-9])([A-Z])/g, "$1-$2").replace(/[\s_.:/]+/g, "-").replace(/[^a-zA-Z0-9-]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "").toLowerCase();
108
+ }
109
+
110
+ // src/cli/auth-schemes.ts
111
+ function parseOAuthFlow(flow) {
112
+ if (!flow)
113
+ return;
114
+ const scopesObj = flow.scopes;
115
+ const scopes = scopesObj && typeof scopesObj === "object" && !Array.isArray(scopesObj) ? Object.keys(scopesObj) : [];
116
+ return {
117
+ authorizationUrl: typeof flow.authorizationUrl === "string" ? flow.authorizationUrl : undefined,
118
+ tokenUrl: typeof flow.tokenUrl === "string" ? flow.tokenUrl : undefined,
119
+ refreshUrl: typeof flow.refreshUrl === "string" ? flow.refreshUrl : undefined,
120
+ scopes: scopes.sort()
121
+ };
122
+ }
123
+ function parseOAuthFlows(flows) {
124
+ if (!flows)
125
+ return;
126
+ const out = {};
127
+ const implicit = parseOAuthFlow(flows.implicit);
128
+ if (implicit)
129
+ out.implicit = implicit;
130
+ const password = parseOAuthFlow(flows.password);
131
+ if (password)
132
+ out.password = password;
133
+ const clientCredentials = parseOAuthFlow(flows.clientCredentials);
134
+ if (clientCredentials)
135
+ out.clientCredentials = clientCredentials;
136
+ const authorizationCode = parseOAuthFlow(flows.authorizationCode);
137
+ if (authorizationCode)
138
+ out.authorizationCode = authorizationCode;
139
+ return Object.keys(out).length ? out : undefined;
140
+ }
141
+ function listAuthSchemes(doc) {
142
+ const schemes = doc.components?.securitySchemes;
143
+ if (!schemes || typeof schemes !== "object")
144
+ return [];
145
+ const out = [];
146
+ for (const [key, raw] of Object.entries(schemes)) {
147
+ if (!raw || typeof raw !== "object")
148
+ continue;
149
+ const s = raw;
150
+ const type = s.type;
151
+ if (type === "http") {
152
+ const scheme = (s.scheme ?? "").toLowerCase();
153
+ if (scheme === "bearer") {
154
+ out.push({
155
+ key,
156
+ kind: "http-bearer",
157
+ scheme,
158
+ bearerFormat: s.bearerFormat,
159
+ description: s.description
160
+ });
161
+ } else if (scheme === "basic") {
162
+ out.push({
163
+ key,
164
+ kind: "http-basic",
165
+ scheme,
166
+ description: s.description
167
+ });
168
+ } else {
169
+ out.push({
170
+ key,
171
+ kind: "unknown",
172
+ scheme: s.scheme,
173
+ description: s.description
174
+ });
175
+ }
176
+ continue;
177
+ }
178
+ if (type === "apiKey") {
179
+ const where = s.in;
180
+ const loc = where === "header" || where === "query" || where === "cookie" ? where : undefined;
181
+ out.push({
182
+ key,
183
+ kind: "api-key",
184
+ name: s.name,
185
+ in: loc,
186
+ description: s.description
187
+ });
188
+ continue;
189
+ }
190
+ if (type === "oauth2") {
191
+ out.push({
192
+ key,
193
+ kind: "oauth2",
194
+ description: s.description,
195
+ oauthFlows: parseOAuthFlows(s.flows)
196
+ });
197
+ continue;
198
+ }
199
+ if (type === "openIdConnect") {
200
+ out.push({
201
+ key,
202
+ kind: "openIdConnect",
203
+ description: s.description,
204
+ openIdConnectUrl: s.openIdConnectUrl
205
+ });
206
+ continue;
207
+ }
208
+ out.push({ key, kind: "unknown", description: s.description });
209
+ }
210
+ out.sort((a, b) => kebabCase(a.key).localeCompare(kebabCase(b.key)));
211
+ return out;
212
+ }
213
+
214
+ // src/cli/capabilities.ts
215
+ function uniqueSorted(items, compare) {
216
+ const out = [...items];
217
+ out.sort(compare);
218
+ return out.filter((v, i) => i === 0 || compare(out[i - 1], v) !== 0);
219
+ }
220
+ function hasSecurity(requirements) {
221
+ if (!requirements?.length)
222
+ return false;
223
+ return true;
224
+ }
225
+ function deriveCapabilities(input) {
226
+ const serverHasVars = input.servers.some((s) => s.variableNames.length > 0);
227
+ const authKinds = uniqueSorted(input.authSchemes.map((s) => s.kind), (a, b) => a.localeCompare(b));
228
+ const hasSecurityRequirements = hasSecurity(input.doc.security) || input.operations.some((op) => hasSecurity(op.security));
229
+ const opHasBodies = input.operations.some((op) => Boolean(op.requestBody));
230
+ const cmdResources = input.commands?.resources ?? [];
231
+ const cmdActions = cmdResources.flatMap((r) => r.actions);
232
+ const cmdHasBodies = cmdActions.some((a) => Boolean(a.requestBody));
233
+ return {
234
+ servers: {
235
+ count: input.servers.length,
236
+ hasVariables: serverHasVars
237
+ },
238
+ auth: {
239
+ count: input.authSchemes.length,
240
+ kinds: authKinds,
241
+ hasSecurityRequirements
242
+ },
243
+ operations: {
244
+ count: input.operations.length,
245
+ hasRequestBodies: opHasBodies
246
+ },
247
+ commands: {
248
+ countResources: cmdResources.length,
249
+ countActions: cmdActions.length,
250
+ hasRequestBodies: cmdHasBodies
251
+ }
252
+ };
253
+ }
254
+
255
+ // src/cli/command-index.ts
256
+ function buildCommandsIndex(commands) {
257
+ const byId = {};
258
+ for (const resource of commands?.resources ?? []) {
259
+ for (const action of resource.actions) {
260
+ byId[action.id] = action;
261
+ }
262
+ }
263
+ return { byId };
264
+ }
265
+
266
+ // src/cli/auth-requirements.ts
267
+ function isSecurityRequirement(value) {
268
+ if (!value || typeof value !== "object")
269
+ return false;
270
+ if (Array.isArray(value))
271
+ return false;
272
+ for (const [k, v] of Object.entries(value)) {
273
+ if (typeof k !== "string")
274
+ return false;
275
+ if (!Array.isArray(v))
276
+ return false;
277
+ if (!v.every((s) => typeof s === "string"))
278
+ return false;
279
+ }
280
+ return true;
281
+ }
282
+ function normalizeSecurity(value) {
283
+ if (value == null)
284
+ return { requirements: [], source: "none" };
285
+ if (!Array.isArray(value))
286
+ return { requirements: [], source: "none" };
287
+ const reqs = value.filter(isSecurityRequirement);
288
+ if (reqs.length === 0)
289
+ return { requirements: [], source: "empty" };
290
+ return { requirements: reqs, source: "non-empty" };
291
+ }
292
+ function summarizeAuth(operationSecurity, globalSecurity, knownSchemes) {
293
+ const op = normalizeSecurity(operationSecurity);
294
+ if (op.source === "non-empty") {
295
+ return { alternatives: toAlternatives(op.requirements, knownSchemes) };
296
+ }
297
+ if (op.source === "empty") {
298
+ return { alternatives: [] };
299
+ }
300
+ const global = normalizeSecurity(globalSecurity);
301
+ if (global.source === "non-empty") {
302
+ return { alternatives: toAlternatives(global.requirements, knownSchemes) };
303
+ }
304
+ return { alternatives: [] };
305
+ }
306
+ function toAlternatives(requirements, knownSchemes) {
307
+ const known = new Set(knownSchemes.map((s) => s.key));
308
+ return requirements.map((req) => {
309
+ const out = [];
310
+ for (const [key, scopes] of Object.entries(req)) {
311
+ out.push({
312
+ key,
313
+ scopes: Array.isArray(scopes) ? scopes : []
314
+ });
315
+ }
316
+ out.sort((a, b) => a.key.localeCompare(b.key));
317
+ out.sort((a, b) => {
318
+ const ak = known.has(a.key) ? 0 : 1;
319
+ const bk = known.has(b.key) ? 0 : 1;
320
+ if (ak !== bk)
321
+ return ak - bk;
322
+ return a.key.localeCompare(b.key);
323
+ });
324
+ return out;
325
+ });
326
+ }
327
+
328
+ // src/cli/command-id.ts
329
+ function buildCommandId(parts) {
330
+ const op = kebabCase(parts.operationKey.replace(/\s+/g, "-"));
331
+ return `${parts.specId}:${kebabCase(parts.resource)}:${kebabCase(parts.action)}:${op}`;
332
+ }
333
+
334
+ // src/cli/schema-shape.ts
335
+ function getSchemaType(schema) {
336
+ if (!schema || typeof schema !== "object")
337
+ return "unknown";
338
+ const t = schema.type;
339
+ if (t === "string")
340
+ return "string";
341
+ if (t === "number")
342
+ return "number";
343
+ if (t === "integer")
344
+ return "integer";
345
+ if (t === "boolean")
346
+ return "boolean";
347
+ if (t === "array")
348
+ return "array";
349
+ if (t === "object")
350
+ return "object";
351
+ return "unknown";
352
+ }
353
+ function getSchemaFormat(schema) {
354
+ if (!schema || typeof schema !== "object")
355
+ return;
356
+ const f = schema.format;
357
+ return typeof f === "string" ? f : undefined;
358
+ }
359
+ function getSchemaEnumStrings(schema) {
360
+ if (!schema || typeof schema !== "object")
361
+ return;
362
+ const e = schema.enum;
363
+ if (!Array.isArray(e))
364
+ return;
365
+ const values = e.filter((v) => typeof v === "string");
366
+ return values.length ? values : undefined;
367
+ }
368
+
369
+ // src/cli/params.ts
370
+ function deriveParamSpecs(op) {
371
+ const out = [];
372
+ for (const p of op.parameters) {
373
+ const flag = `--${kebabCase(p.name)}`;
374
+ const type = getSchemaType(p.schema);
375
+ const schemaObj = p.schema && typeof p.schema === "object" ? p.schema : undefined;
376
+ const itemsSchema = schemaObj && type === "array" && typeof schemaObj.items === "object" ? schemaObj.items : undefined;
377
+ out.push({
378
+ kind: p.in === "path" ? "positional" : "flag",
379
+ in: p.in,
380
+ name: p.name,
381
+ flag,
382
+ required: p.required,
383
+ description: p.description,
384
+ type,
385
+ format: getSchemaFormat(p.schema),
386
+ enum: getSchemaEnumStrings(p.schema),
387
+ itemType: type === "array" ? getSchemaType(itemsSchema) : undefined,
388
+ itemFormat: type === "array" ? getSchemaFormat(itemsSchema) : undefined,
389
+ itemEnum: type === "array" ? getSchemaEnumStrings(itemsSchema) : undefined,
390
+ schema: schemaObj
391
+ });
392
+ }
393
+ out.sort((a, b) => {
394
+ if (a.in !== b.in)
395
+ return a.in.localeCompare(b.in);
396
+ return a.name.localeCompare(b.name);
397
+ });
398
+ return out;
399
+ }
400
+
401
+ // src/cli/positional.ts
402
+ function derivePositionals(action) {
403
+ const byName = new Map;
404
+ for (const name of action.pathArgs) {
405
+ const p = action.params.find((x) => x.in === "path" && x.name === name);
406
+ byName.set(name, {
407
+ name,
408
+ required: true,
409
+ description: p?.description,
410
+ type: p?.type ?? "unknown",
411
+ format: p?.format,
412
+ enum: p?.enum
413
+ });
414
+ }
415
+ return [...byName.values()];
416
+ }
417
+ function deriveFlags(action) {
418
+ return {
419
+ flags: action.params.filter((p) => p.kind === "flag").map((p) => ({
420
+ in: p.in,
421
+ name: p.name,
422
+ flag: p.flag,
423
+ required: p.required,
424
+ description: p.description,
425
+ type: p.type,
426
+ format: p.format,
427
+ enum: p.enum,
428
+ itemType: p.itemType,
429
+ itemFormat: p.itemFormat,
430
+ itemEnum: p.itemEnum
431
+ }))
432
+ };
433
+ }
434
+
435
+ // src/cli/types.ts
436
+ function isJsonSchema(value) {
437
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
438
+ }
439
+
440
+ // src/cli/request-body.ts
441
+ function getRequestBody(op) {
442
+ return op.requestBody;
443
+ }
444
+ function deriveRequestBodyInfo(op) {
445
+ const rb = getRequestBody(op);
446
+ if (!rb)
447
+ return;
448
+ const content = [];
449
+ for (const contentType of rb.contentTypes) {
450
+ const schema = rb.schemasByContentType[contentType];
451
+ content.push({
452
+ contentType,
453
+ required: rb.required,
454
+ schemaType: getSchemaType(schema),
455
+ schemaFormat: getSchemaFormat(schema),
456
+ schemaEnum: getSchemaEnumStrings(schema)
457
+ });
458
+ }
459
+ content.sort((a, b) => a.contentType.localeCompare(b.contentType));
460
+ const hasJson = content.some((c) => c.contentType.includes("json"));
461
+ const hasFormUrlEncoded = content.some((c) => c.contentType === "application/x-www-form-urlencoded");
462
+ const hasMultipart = content.some((c) => c.contentType.startsWith("multipart/"));
463
+ const bodyFlags = ["--data", "--file"];
464
+ const preferredContentType = content.find((c) => c.contentType === "application/json")?.contentType ?? content.find((c) => c.contentType.includes("json"))?.contentType ?? content[0]?.contentType;
465
+ const preferredSchema = preferredContentType ? rb.schemasByContentType[preferredContentType] : undefined;
466
+ return {
467
+ required: rb.required,
468
+ content,
469
+ hasJson,
470
+ hasFormUrlEncoded,
471
+ hasMultipart,
472
+ bodyFlags,
473
+ preferredContentType,
474
+ preferredSchema: isJsonSchema(preferredSchema) ? preferredSchema : undefined
475
+ };
476
+ }
477
+
478
+ // src/cli/command-model.ts
479
+ function buildCommandModel(planned, options) {
480
+ const byResource = new Map;
481
+ for (const op of planned) {
482
+ const list = byResource.get(op.resource) ?? [];
483
+ const params = deriveParamSpecs(op);
484
+ const positionals = derivePositionals({ pathArgs: op.pathArgs, params });
485
+ const flags = deriveFlags({ pathArgs: op.pathArgs, params });
486
+ list.push({
487
+ id: buildCommandId({
488
+ specId: options.specId,
489
+ resource: op.resource,
490
+ action: op.action,
491
+ operationKey: op.key
492
+ }),
493
+ key: op.key,
494
+ action: op.action,
495
+ pathArgs: op.pathArgs,
496
+ method: op.method,
497
+ path: op.path,
498
+ operationId: op.operationId,
499
+ tags: op.tags,
500
+ summary: op.summary,
501
+ description: op.description,
502
+ deprecated: op.deprecated,
503
+ style: op.style,
504
+ params,
505
+ positionals,
506
+ flags: flags.flags,
507
+ auth: summarizeAuth(op.security, options.globalSecurity, options.authSchemes ?? []),
508
+ requestBody: deriveRequestBodyInfo(op),
509
+ requestBodySchema: deriveRequestBodyInfo(op)?.preferredSchema
510
+ });
511
+ byResource.set(op.resource, list);
512
+ }
513
+ const resources = [];
514
+ for (const [resource, actions] of byResource.entries()) {
515
+ actions.sort((a, b) => {
516
+ if (a.action !== b.action)
517
+ return a.action.localeCompare(b.action);
518
+ if (a.path !== b.path)
519
+ return a.path.localeCompare(b.path);
520
+ return a.method.localeCompare(b.method);
521
+ });
522
+ resources.push({ resource, actions });
523
+ }
524
+ resources.sort((a, b) => a.resource.localeCompare(b.resource));
525
+ return { resources };
526
+ }
527
+
528
+ // src/cli/pluralize.ts
529
+ var IRREGULAR = {
530
+ person: "people",
531
+ man: "men",
532
+ woman: "women",
533
+ child: "children",
534
+ tooth: "teeth",
535
+ foot: "feet",
536
+ mouse: "mice",
537
+ goose: "geese"
538
+ };
539
+ var UNCOUNTABLE = new Set([
540
+ "metadata",
541
+ "information",
542
+ "equipment",
543
+ "money",
544
+ "series",
545
+ "species"
546
+ ]);
547
+ function pluralize(word) {
548
+ const w = word.trim();
549
+ if (!w)
550
+ return w;
551
+ const lower = w.toLowerCase();
552
+ if (UNCOUNTABLE.has(lower))
553
+ return lower;
554
+ if (IRREGULAR[lower])
555
+ return IRREGULAR[lower];
556
+ if (lower.endsWith("s"))
557
+ return lower;
558
+ if (/[bcdfghjklmnpqrstvwxyz]y$/.test(lower)) {
559
+ return lower.replace(/y$/, "ies");
560
+ }
561
+ if (/(ch|sh|x|z)$/.test(lower)) {
562
+ return `${lower}es`;
563
+ }
564
+ return `${lower}s`;
565
+ }
566
+
567
+ // src/cli/naming.ts
568
+ var GENERIC_TAGS = new Set(["default", "defaults", "api"]);
569
+ function getPathSegments(path) {
570
+ return path.split("/").map((s) => s.trim()).filter(Boolean);
571
+ }
572
+ function getPathArgs(path) {
573
+ const args = [];
574
+ const re = /\{([^}]+)\}/g;
575
+ while (true) {
576
+ const match = re.exec(path);
577
+ if (!match)
578
+ break;
579
+ args.push(match[1]);
580
+ }
581
+ return args;
582
+ }
583
+ function pickResourceFromTags(tags) {
584
+ if (!tags.length)
585
+ return;
586
+ const first = tags[0]?.trim();
587
+ if (!first)
588
+ return;
589
+ if (GENERIC_TAGS.has(first.toLowerCase()))
590
+ return;
591
+ return first;
592
+ }
593
+ function splitOperationId(operationId) {
594
+ const trimmed = operationId.trim();
595
+ if (!trimmed)
596
+ return {};
597
+ if (trimmed.includes(".")) {
598
+ const [prefix, ...rest] = trimmed.split(".");
599
+ return { prefix, suffix: rest.join(".") };
600
+ }
601
+ if (trimmed.includes("__")) {
602
+ const [prefix, ...rest] = trimmed.split("__");
603
+ return { prefix, suffix: rest.join("__") };
604
+ }
605
+ if (trimmed.includes("_")) {
606
+ const [prefix, ...rest] = trimmed.split("_");
607
+ return { prefix, suffix: rest.join("_") };
608
+ }
609
+ return { suffix: trimmed };
610
+ }
611
+ function inferStyle(op) {
612
+ if (op.path.includes("."))
613
+ return "rpc";
614
+ if (op.operationId?.includes(".") && op.method === "POST")
615
+ return "rpc";
616
+ return "rest";
617
+ }
618
+ function inferResource(op) {
619
+ const tag = pickResourceFromTags(op.tags);
620
+ if (tag)
621
+ return pluralize(kebabCase(tag));
622
+ if (op.operationId) {
623
+ const { prefix } = splitOperationId(op.operationId);
624
+ if (prefix) {
625
+ const fromId = kebabCase(prefix);
626
+ if (fromId === "ping")
627
+ return "ping";
628
+ return pluralize(fromId);
629
+ }
630
+ }
631
+ const segments = getPathSegments(op.path);
632
+ let first = segments[0] ?? "api";
633
+ first = first.includes(".") ? first.split(".")[0] : first;
634
+ if (first.toLowerCase() === "ping")
635
+ return "ping";
636
+ const cleaned = first.replace(/^\{.+\}$/, "");
637
+ return pluralize(kebabCase(cleaned || "api"));
638
+ }
639
+ function canonicalizeAction(action) {
640
+ const a = kebabCase(action);
641
+ if (a === "retrieve" || a === "read")
642
+ return "get";
643
+ if (a === "list" || a === "search")
644
+ return "list";
645
+ if (a === "create")
646
+ return "create";
647
+ if (a === "update" || a === "patch")
648
+ return "update";
649
+ if (a === "delete" || a === "remove")
650
+ return "delete";
651
+ return a;
652
+ }
653
+ function inferRestAction(op) {
654
+ if (op.operationId) {
655
+ const { suffix } = splitOperationId(op.operationId);
656
+ if (suffix) {
657
+ const fromId = canonicalizeAction(suffix);
658
+ if (fromId === "get" || fromId === "list" || fromId === "create" || fromId === "update" || fromId === "delete") {
659
+ return fromId;
660
+ }
661
+ }
662
+ }
663
+ const method = op.method.toUpperCase();
664
+ const args = getPathArgs(op.path);
665
+ const hasId = args.length > 0;
666
+ if (method === "GET" && !hasId)
667
+ return "list";
668
+ if (method === "POST" && !hasId)
669
+ return "create";
670
+ if (method === "GET" && hasId)
671
+ return "get";
672
+ if ((method === "PUT" || method === "PATCH") && hasId)
673
+ return "update";
674
+ if (method === "DELETE" && hasId)
675
+ return "delete";
676
+ return kebabCase(method);
677
+ }
678
+ function inferRpcAction(op) {
679
+ if (op.operationId) {
680
+ const { suffix } = splitOperationId(op.operationId);
681
+ if (suffix)
682
+ return canonicalizeAction(suffix);
683
+ }
684
+ const segments = getPathSegments(op.path);
685
+ const last = segments[segments.length - 1] ?? "";
686
+ if (last.includes(".")) {
687
+ const part = last.split(".").pop() ?? last;
688
+ return canonicalizeAction(part);
689
+ }
690
+ return kebabCase(op.method);
691
+ }
692
+ function planOperation(op) {
693
+ const style = inferStyle(op);
694
+ const resource = inferResource(op);
695
+ const action = style === "rpc" ? inferRpcAction(op) : inferRestAction(op);
696
+ return {
697
+ ...op,
698
+ key: op.key,
699
+ style,
700
+ resource,
701
+ action,
702
+ canonicalAction: action,
703
+ pathArgs: getPathArgs(op.path).map((a) => kebabCase(a))
704
+ };
705
+ }
706
+ function planOperations(ops) {
707
+ const planned = ops.map(planOperation);
708
+ const counts = new Map;
709
+ for (const op of planned) {
710
+ const key = `${op.resource}:${op.action}`;
711
+ counts.set(key, (counts.get(key) ?? 0) + 1);
712
+ }
713
+ const seen = new Map;
714
+ return planned.map((op) => {
715
+ const key = `${op.resource}:${op.action}`;
716
+ const total = counts.get(key) ?? 0;
717
+ if (total <= 1)
718
+ return op;
719
+ const idx = (seen.get(key) ?? 0) + 1;
720
+ seen.set(key, idx);
721
+ const suffix = op.operationId ? kebabCase(op.operationId) : kebabCase(`${op.method}-${op.path}`);
722
+ const disambiguatedAction = `${op.action}-${suffix}-${idx}`;
723
+ return {
724
+ ...op,
725
+ action: disambiguatedAction,
726
+ aliasOf: `${op.resource} ${op.canonicalAction}`
727
+ };
728
+ });
729
+ }
730
+
731
+ // src/cli/operations.ts
732
+ function operationKey(method, path) {
733
+ return `${method.toUpperCase()} ${path}`;
734
+ }
735
+ var HTTP_METHODS = [
736
+ "get",
737
+ "post",
738
+ "put",
739
+ "patch",
740
+ "delete",
741
+ "options",
742
+ "head",
743
+ "trace"
744
+ ];
745
+ function normalizeParam(p) {
746
+ if (!p || typeof p !== "object")
747
+ return;
748
+ const loc = p.in;
749
+ const name = p.name;
750
+ if (loc !== "path" && loc !== "query" && loc !== "header" && loc !== "cookie") {
751
+ return;
752
+ }
753
+ if (!name)
754
+ return;
755
+ return {
756
+ in: loc,
757
+ name,
758
+ required: Boolean(p.required || loc === "path"),
759
+ description: p.description,
760
+ schema: p.schema
761
+ };
762
+ }
763
+ function mergeParameters(pathParams, opParams) {
764
+ const merged = new Map;
765
+ for (const p of pathParams ?? []) {
766
+ const normalized = normalizeParam(p);
767
+ if (!normalized)
768
+ continue;
769
+ merged.set(`${normalized.in}:${normalized.name}`, normalized);
770
+ }
771
+ for (const p of opParams ?? []) {
772
+ const normalized = normalizeParam(p);
773
+ if (!normalized)
774
+ continue;
775
+ merged.set(`${normalized.in}:${normalized.name}`, normalized);
776
+ }
777
+ return [...merged.values()];
778
+ }
779
+ function normalizeRequestBody(rb) {
780
+ if (!rb)
781
+ return;
782
+ const content = rb.content ?? {};
783
+ const contentTypes = Object.keys(content);
784
+ const schemasByContentType = {};
785
+ for (const contentType of contentTypes) {
786
+ schemasByContentType[contentType] = content[contentType]?.schema;
787
+ }
788
+ return {
789
+ required: Boolean(rb.required),
790
+ contentTypes,
791
+ schemasByContentType
792
+ };
793
+ }
794
+ function indexOperations(doc) {
795
+ const out = [];
796
+ const paths = doc.paths ?? {};
797
+ for (const [path, rawPathItem] of Object.entries(paths)) {
798
+ if (!rawPathItem || typeof rawPathItem !== "object")
799
+ continue;
800
+ const pathItem = rawPathItem;
801
+ for (const method of HTTP_METHODS) {
802
+ const op = pathItem[method];
803
+ if (!op)
804
+ continue;
805
+ const parameters = mergeParameters(pathItem.parameters, op.parameters);
806
+ const normalizedMethod = method.toUpperCase();
807
+ out.push({
808
+ key: operationKey(normalizedMethod, path),
809
+ method: normalizedMethod,
810
+ path,
811
+ operationId: op.operationId,
812
+ tags: op.tags ?? [],
813
+ summary: op.summary,
814
+ description: op.description,
815
+ deprecated: op.deprecated,
816
+ security: op.security ?? doc.security,
817
+ parameters,
818
+ requestBody: normalizeRequestBody(op.requestBody)
819
+ });
820
+ }
821
+ }
822
+ out.sort((a, b) => {
823
+ if (a.path !== b.path)
824
+ return a.path.localeCompare(b.path);
825
+ return a.method.localeCompare(b.method);
826
+ });
827
+ return out;
828
+ }
829
+
830
+ // src/cli/schema.ts
831
+ function buildSchemaOutput(loaded, operations, planned, servers, authSchemes, commands, commandsIndex, capabilities) {
832
+ return {
833
+ schemaVersion: 1,
834
+ openapi: {
835
+ version: loaded.doc.openapi,
836
+ title: loaded.doc.info?.title,
837
+ infoVersion: loaded.doc.info?.version
838
+ },
839
+ spec: {
840
+ id: loaded.id,
841
+ fingerprint: loaded.fingerprint,
842
+ source: loaded.source
843
+ },
844
+ capabilities,
845
+ servers,
846
+ authSchemes,
847
+ operations,
848
+ planned,
849
+ commands,
850
+ commandsIndex
851
+ };
852
+ }
853
+
854
+ // src/cli/server.ts
855
+ function extractVariableNames(url) {
856
+ const names = [];
857
+ const re = /\{([^}]+)\}/g;
858
+ while (true) {
859
+ const match = re.exec(url);
860
+ if (!match)
861
+ break;
862
+ names.push(match[1] ?? "");
863
+ }
864
+ return names.map((n) => n.trim()).filter(Boolean);
865
+ }
866
+ function listServers(doc) {
867
+ const servers = doc.servers ?? [];
868
+ const out = [];
869
+ for (const raw of servers) {
870
+ const s = raw;
871
+ if (!s || typeof s !== "object")
872
+ continue;
873
+ if (typeof s.url !== "string")
874
+ continue;
875
+ const variableNames = extractVariableNames(s.url);
876
+ const variables = [];
877
+ const rawVars = s.variables && typeof s.variables === "object" && !Array.isArray(s.variables) ? s.variables : {};
878
+ for (const name of variableNames) {
879
+ const v = rawVars[name];
880
+ const def = v?.default;
881
+ const desc = v?.description;
882
+ variables.push({
883
+ name,
884
+ default: typeof def === "string" ? def : undefined,
885
+ enum: getSchemaEnumStrings(v),
886
+ description: typeof desc === "string" ? desc : undefined
887
+ });
888
+ }
889
+ out.push({
890
+ url: s.url,
891
+ description: typeof s.description === "string" ? s.description : undefined,
892
+ variables,
893
+ variableNames
894
+ });
895
+ }
896
+ return out;
897
+ }
898
+
899
+ // src/cli/spec-loader.ts
900
+ import SwaggerParser from "@apidevtools/swagger-parser";
901
+
902
+ // src/cli/crypto.ts
903
+ async function sha256Hex(text) {
904
+ const data = new TextEncoder().encode(text);
905
+ const hash = await crypto.subtle.digest("SHA-256", data);
906
+ const bytes = new Uint8Array(hash);
907
+ let out = "";
908
+ for (const b of bytes)
909
+ out += b.toString(16).padStart(2, "0");
910
+ return out;
911
+ }
912
+
913
+ // src/cli/runtime/compat.ts
914
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
915
+ import { parse as parseYaml } from "yaml";
916
+ var isBun = typeof globalThis.Bun !== "undefined";
917
+ async function readFileText(path) {
918
+ if (isBun) {
919
+ return Bun.file(path).text();
920
+ }
921
+ return readFileSync(path, "utf-8");
922
+ }
923
+ async function fileExists(path) {
924
+ if (isBun) {
925
+ return Bun.file(path).exists();
926
+ }
927
+ return existsSync(path);
928
+ }
929
+ function parseYamlContent(text) {
930
+ if (isBun) {
931
+ const { YAML } = globalThis.Bun;
932
+ return YAML.parse(text);
933
+ }
934
+ return parseYaml(text);
935
+ }
936
+
937
+ // src/cli/spec-id.ts
938
+ function getSpecId(loaded) {
939
+ const title = loaded.doc.info?.title;
940
+ const fromTitle = title ? kebabCase(title) : "";
941
+ if (fromTitle)
942
+ return fromTitle;
943
+ return loaded.fingerprint.slice(0, 12);
944
+ }
945
+
946
+ // src/cli/stable-json.ts
947
+ function stableStringify(value, options) {
948
+ const visiting = new WeakSet;
949
+ return JSON.stringify(sort(value, visiting), null, options?.space);
950
+ }
951
+ function sort(value, visiting) {
952
+ if (value === null)
953
+ return null;
954
+ if (Array.isArray(value)) {
955
+ if (visiting.has(value))
956
+ return { __specli_circular: true };
957
+ visiting.add(value);
958
+ const out = value.map((v) => sort(v, visiting));
959
+ visiting.delete(value);
960
+ return out;
961
+ }
962
+ if (typeof value === "object") {
963
+ if (visiting.has(value))
964
+ return { __specli_circular: true };
965
+ visiting.add(value);
966
+ const obj = value;
967
+ const out = {};
968
+ for (const key of Object.keys(obj).sort()) {
969
+ out[key] = sort(obj[key], visiting);
970
+ }
971
+ visiting.delete(value);
972
+ return out;
973
+ }
974
+ return value;
975
+ }
976
+
977
+ // src/cli/spec-loader.ts
978
+ function isProbablyUrl(input) {
979
+ return /^https?:\/\//i.test(input);
980
+ }
981
+ function parseSpecText(text) {
982
+ const trimmed = text.trimStart();
983
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
984
+ return JSON.parse(text);
985
+ }
986
+ return parseYamlContent(text);
987
+ }
988
+ async function loadSpec(options) {
989
+ const { spec, embeddedSpecText } = options;
990
+ let source;
991
+ let inputForParser;
992
+ if (typeof embeddedSpecText === "string") {
993
+ source = "embedded";
994
+ inputForParser = parseSpecText(embeddedSpecText);
995
+ } else if (spec) {
996
+ source = isProbablyUrl(spec) ? "url" : "file";
997
+ inputForParser = spec;
998
+ } else {
999
+ throw new Error("Missing spec. Provide --spec <url|path> or build with an embedded spec.");
1000
+ }
1001
+ const doc = await SwaggerParser.dereference(inputForParser);
1002
+ if (!doc || typeof doc !== "object" || typeof doc.openapi !== "string") {
1003
+ throw new Error("Loaded spec is not a valid OpenAPI document");
1004
+ }
1005
+ const fingerprint = await sha256Hex(stableStringify(doc));
1006
+ const id = getSpecId({ doc, fingerprint });
1007
+ return { source, id, fingerprint, doc };
1008
+ }
1009
+
1010
+ // src/cli/runtime/context.ts
1011
+ async function buildRuntimeContext(options) {
1012
+ const loaded = await loadSpec({
1013
+ spec: options.spec,
1014
+ embeddedSpecText: options.embeddedSpecText
1015
+ });
1016
+ const operations = indexOperations(loaded.doc);
1017
+ const servers = listServers(loaded.doc);
1018
+ const authSchemes = listAuthSchemes(loaded.doc);
1019
+ const planned = planOperations(operations);
1020
+ const commands = buildCommandModel(planned, {
1021
+ specId: loaded.id,
1022
+ globalSecurity: loaded.doc.security,
1023
+ authSchemes
1024
+ });
1025
+ const commandsIndex = buildCommandsIndex(commands);
1026
+ const capabilities = deriveCapabilities({
1027
+ doc: loaded.doc,
1028
+ servers,
1029
+ authSchemes,
1030
+ operations,
1031
+ commands
1032
+ });
1033
+ const schema = buildSchemaOutput(loaded, operations, planned, servers, authSchemes, commands, commandsIndex, capabilities);
1034
+ return {
1035
+ loaded,
1036
+ operations,
1037
+ servers,
1038
+ authSchemes,
1039
+ planned,
1040
+ commands,
1041
+ commandsIndex,
1042
+ capabilities,
1043
+ schema
1044
+ };
1045
+ }
1046
+
1047
+ // src/cli/runtime/auth/resolve.ts
1048
+ var BEARER_COMPATIBLE_KINDS = new Set([
1049
+ "http-bearer",
1050
+ "oauth2",
1051
+ "openIdConnect"
1052
+ ]);
1053
+ function resolveAuthScheme(authSchemes, required, inputs) {
1054
+ if (inputs.flagAuthScheme)
1055
+ return inputs.flagAuthScheme;
1056
+ if (inputs.profileAuthScheme && authSchemes.some((s) => s.key === inputs.profileAuthScheme)) {
1057
+ return inputs.profileAuthScheme;
1058
+ }
1059
+ if (inputs.embeddedAuthScheme && authSchemes.some((s) => s.key === inputs.embeddedAuthScheme)) {
1060
+ return inputs.embeddedAuthScheme;
1061
+ }
1062
+ const alts = required.alternatives;
1063
+ if (alts.length === 1 && alts[0]?.length === 1)
1064
+ return alts[0][0]?.key;
1065
+ if (authSchemes.length === 1)
1066
+ return authSchemes[0]?.key;
1067
+ if (inputs.hasStoredToken && alts.length > 0) {
1068
+ for (const alt of alts) {
1069
+ if (alt.length !== 1)
1070
+ continue;
1071
+ const key = alt[0]?.key;
1072
+ const scheme = authSchemes.find((s) => s.key === key);
1073
+ if (scheme && BEARER_COMPATIBLE_KINDS.has(scheme.kind)) {
1074
+ return key;
1075
+ }
1076
+ }
1077
+ }
1078
+ return;
1079
+ }
1080
+
1081
+ // src/cli/runtime/profile/secrets.ts
1082
+ var bunLiteral = "bun";
1083
+ function secretServiceForSpec(specId) {
1084
+ return `specli:${specId}`;
1085
+ }
1086
+ function tokenSecretKey(specId, profile) {
1087
+ return {
1088
+ service: secretServiceForSpec(specId),
1089
+ name: `profile:${profile}:token`
1090
+ };
1091
+ }
1092
+ async function getToken(specId, profile) {
1093
+ if (!isBun) {
1094
+ return null;
1095
+ }
1096
+ const { secrets } = await import(bunLiteral);
1097
+ const key = tokenSecretKey(specId, profile);
1098
+ return await secrets.get({ service: key.service, name: key.name });
1099
+ }
1100
+
1101
+ // src/cli/runtime/profile/store.ts
1102
+ function configDir() {
1103
+ const home = process.env.HOME;
1104
+ if (!home)
1105
+ throw new Error("Missing HOME env var");
1106
+ return `${home}/.config/specli`;
1107
+ }
1108
+ function configPathJson() {
1109
+ return `${configDir()}/profiles.json`;
1110
+ }
1111
+ function configPathYaml() {
1112
+ return `${configDir()}/profiles.yaml`;
1113
+ }
1114
+ async function readProfiles() {
1115
+ const jsonPath = configPathJson();
1116
+ const yamlPath = configPathYaml();
1117
+ const jsonExists = await fileExists(jsonPath);
1118
+ const yamlExists = await fileExists(yamlPath);
1119
+ const filePath = jsonExists ? jsonPath : yamlExists ? yamlPath : null;
1120
+ if (!filePath)
1121
+ return { profiles: [] };
1122
+ const text = await readFileText(filePath);
1123
+ let parsed;
1124
+ try {
1125
+ parsed = parseYamlContent(text);
1126
+ } catch {
1127
+ parsed = JSON.parse(text);
1128
+ }
1129
+ const obj = parsed && typeof parsed === "object" ? parsed : {};
1130
+ const profiles = Array.isArray(obj.profiles) ? obj.profiles : [];
1131
+ return {
1132
+ profiles: profiles.filter(Boolean),
1133
+ defaultProfile: typeof obj.defaultProfile === "string" ? obj.defaultProfile : undefined
1134
+ };
1135
+ }
1136
+ function getProfile(data, name) {
1137
+ const wanted = name ?? data.defaultProfile;
1138
+ if (!wanted)
1139
+ return;
1140
+ return data.profiles.find((p) => p?.name === wanted);
1141
+ }
1142
+
1143
+ // src/cli/runtime/template.ts
1144
+ function extractTemplateVars(template) {
1145
+ const out = [];
1146
+ const re = /\{([^}]+)\}/g;
1147
+ while (true) {
1148
+ const match = re.exec(template);
1149
+ if (!match)
1150
+ break;
1151
+ out.push((match[1] ?? "").trim());
1152
+ }
1153
+ return out.filter(Boolean);
1154
+ }
1155
+ function applyTemplate(template, vars, options) {
1156
+ const encode = options?.encode ?? false;
1157
+ return template.replace(/\{([^}]+)\}/g, (_, rawName) => {
1158
+ const name = String(rawName).trim();
1159
+ const value = vars[name];
1160
+ if (typeof value !== "string") {
1161
+ throw new Error(`Missing template variable: ${name}`);
1162
+ }
1163
+ return encode ? encodeURIComponent(value) : value;
1164
+ });
1165
+ }
1166
+
1167
+ // src/cli/runtime/server-url.ts
1168
+ function resolveServerUrl(input) {
1169
+ const base = input.serverOverride || input.servers[0]?.url;
1170
+ if (!base) {
1171
+ throw new Error("No server URL found. Provide --server <url> or define servers in the OpenAPI spec.");
1172
+ }
1173
+ const names = extractTemplateVars(base);
1174
+ if (!names.length)
1175
+ return base;
1176
+ const vars = {};
1177
+ for (const name of names) {
1178
+ const provided = input.serverVars[name];
1179
+ if (typeof provided === "string") {
1180
+ vars[name] = provided;
1181
+ continue;
1182
+ }
1183
+ const match = input.servers.find((s) => s.url === base);
1184
+ const v = match?.variables.find((x) => x.name === name);
1185
+ if (typeof v?.default === "string") {
1186
+ vars[name] = v.default;
1187
+ continue;
1188
+ }
1189
+ throw new Error(`Missing server variable '${name}'. Provide --server-var ${name}=...`);
1190
+ }
1191
+ return applyTemplate(base, vars);
1192
+ }
1193
+
1194
+ // src/cli/runtime/validate/ajv.ts
1195
+ import Ajv from "ajv";
1196
+ import addFormats from "ajv-formats";
1197
+ function createAjv() {
1198
+ const ajv = new Ajv({
1199
+ allErrors: true,
1200
+ strict: false,
1201
+ coerceTypes: false
1202
+ });
1203
+ addFormats(ajv);
1204
+ return ajv;
1205
+ }
1206
+ // src/cli/runtime/validate/coerce.ts
1207
+ import { InvalidArgumentError } from "commander";
1208
+ // src/cli/runtime/validate/error.ts
1209
+ function formatAjvErrors(errors) {
1210
+ if (!errors?.length)
1211
+ return "Invalid input";
1212
+ return errors.map((e) => {
1213
+ const path = e.instancePath || e.schemaPath || "";
1214
+ if (e.keyword === "required" && e.params && typeof e.params === "object" && "missingProperty" in e.params) {
1215
+ const missing = String(e.params.missingProperty);
1216
+ const where = e.instancePath || "/";
1217
+ return `${where} missing required property '${missing}'`.trim();
1218
+ }
1219
+ const msg = e.message || "invalid";
1220
+ return `${path} ${msg}`.trim();
1221
+ }).join(`
1222
+ `);
1223
+ }
1224
+ // src/cli/runtime/validate/schema.ts
1225
+ function deriveValidationSchemas(action) {
1226
+ const query = { type: "object", properties: {}, required: [] };
1227
+ const header = { type: "object", properties: {}, required: [] };
1228
+ const cookie = { type: "object", properties: {}, required: [] };
1229
+ for (const p of action.params) {
1230
+ if (p.kind !== "flag")
1231
+ continue;
1232
+ const target = p.in === "query" ? query : p.in === "header" ? header : p.in === "cookie" ? cookie : undefined;
1233
+ if (!target)
1234
+ continue;
1235
+ const schema = p.schema ?? (p.type === "unknown" ? {} : { type: p.type });
1236
+ target.properties[p.name] = schema;
1237
+ if (p.required) {
1238
+ if (!target.required)
1239
+ target.required = [];
1240
+ target.required.push(p.name);
1241
+ }
1242
+ }
1243
+ if (!query.required?.length)
1244
+ delete query.required;
1245
+ if (!header.required?.length)
1246
+ delete header.required;
1247
+ if (!cookie.required?.length)
1248
+ delete cookie.required;
1249
+ return {
1250
+ querySchema: Object.keys(query.properties).length ? query : undefined,
1251
+ headerSchema: Object.keys(header.properties).length ? header : undefined,
1252
+ cookieSchema: Object.keys(cookie.properties).length ? cookie : undefined
1253
+ };
1254
+ }
1255
+ // src/cli/runtime/request.ts
1256
+ function parseKeyValuePairs(pairs) {
1257
+ const out = {};
1258
+ for (const pair of pairs ?? []) {
1259
+ const idx = pair.indexOf("=");
1260
+ if (idx === -1)
1261
+ throw new Error(`Invalid pair '${pair}', expected name=value`);
1262
+ const name = pair.slice(0, idx).trim();
1263
+ const value = pair.slice(idx + 1).trim();
1264
+ if (!name)
1265
+ throw new Error(`Invalid pair '${pair}', missing name`);
1266
+ out[name] = value;
1267
+ }
1268
+ return out;
1269
+ }
1270
+ function pickAuthSchemeKey(action, globals) {
1271
+ if (globals.auth)
1272
+ return globals.auth;
1273
+ const req = action.auth.alternatives;
1274
+ if (req.length === 1 && req[0]?.length === 1) {
1275
+ return req[0][0]?.key;
1276
+ }
1277
+ return;
1278
+ }
1279
+ function applyAuth(headers, url, action, globals, authSchemes) {
1280
+ const schemeKey = pickAuthSchemeKey(action, globals);
1281
+ if (!schemeKey)
1282
+ return { headers, url };
1283
+ const scheme = authSchemes.find((s) => s.key === schemeKey);
1284
+ if (!scheme) {
1285
+ throw new Error(`Unknown auth scheme '${schemeKey}'. Available: ${authSchemes.map((s) => s.key).join(", ")}`);
1286
+ }
1287
+ if (scheme.kind === "http-bearer" || scheme.kind === "oauth2" || scheme.kind === "openIdConnect") {
1288
+ const token = globals.bearerToken ?? globals.oauthToken;
1289
+ if (!token)
1290
+ throw new Error("Missing token. Provide --bearer-token <token>.");
1291
+ headers.set("Authorization", `Bearer ${token}`);
1292
+ return { headers, url };
1293
+ }
1294
+ if (scheme.kind === "http-basic") {
1295
+ if (!globals.username)
1296
+ throw new Error("Missing --username for basic auth");
1297
+ if (!globals.password)
1298
+ throw new Error("Missing --password for basic auth");
1299
+ const raw = `${globals.username}:${globals.password}`;
1300
+ const encoded = Buffer.from(raw, "utf8").toString("base64");
1301
+ headers.set("Authorization", `Basic ${encoded}`);
1302
+ return { headers, url };
1303
+ }
1304
+ if (scheme.kind === "api-key") {
1305
+ if (!scheme.name)
1306
+ throw new Error(`apiKey scheme '${scheme.key}' missing name`);
1307
+ if (!scheme.in)
1308
+ throw new Error(`apiKey scheme '${scheme.key}' missing location`);
1309
+ if (!globals.apiKey)
1310
+ throw new Error("Missing --api-key for apiKey auth");
1311
+ if (scheme.in === "header") {
1312
+ headers.set(scheme.name, globals.apiKey);
1313
+ }
1314
+ if (scheme.in === "query") {
1315
+ url.searchParams.set(scheme.name, globals.apiKey);
1316
+ }
1317
+ if (scheme.in === "cookie") {
1318
+ const existing = headers.get("Cookie");
1319
+ const part = `${scheme.name}=${globals.apiKey}`;
1320
+ headers.set("Cookie", existing ? `${existing}; ${part}` : part);
1321
+ }
1322
+ return { headers, url };
1323
+ }
1324
+ return { headers, url };
1325
+ }
1326
+ async function buildRequest(input) {
1327
+ const defaultProfileName = "default";
1328
+ const profilesFile = await readProfiles();
1329
+ const profile = getProfile(profilesFile, defaultProfileName);
1330
+ const embedded = input.embeddedDefaults;
1331
+ const embeddedServerVars = parseKeyValuePairs(embedded?.serverVars);
1332
+ const cliServerVars = parseKeyValuePairs(input.globals.serverVar);
1333
+ const serverVars = { ...embeddedServerVars, ...cliServerVars };
1334
+ const serverUrl = resolveServerUrl({
1335
+ serverOverride: input.globals.server ?? profile?.server ?? embedded?.server,
1336
+ servers: input.servers,
1337
+ serverVars
1338
+ });
1339
+ const pathVars = {};
1340
+ for (let i = 0;i < input.action.positionals.length; i++) {
1341
+ const pos = input.action.positionals[i];
1342
+ const raw = input.action.pathArgs[i];
1343
+ const value = input.positionalValues[i];
1344
+ if (typeof raw === "string" && typeof value === "string") {
1345
+ pathVars[raw] = value;
1346
+ }
1347
+ if (pos?.name && typeof value === "string") {
1348
+ pathVars[pos.name] = value;
1349
+ }
1350
+ }
1351
+ const path = applyTemplate(input.action.path, pathVars, { encode: true });
1352
+ const baseUrl = serverUrl.endsWith("/") ? serverUrl : `${serverUrl}/`;
1353
+ const relativePath = path.startsWith("/") ? path.slice(1) : path;
1354
+ const url = new URL(relativePath, baseUrl);
1355
+ const headers = new Headers;
1356
+ const queryValues = {};
1357
+ const headerValues = {};
1358
+ const cookieValues = {};
1359
+ for (const p of input.action.params) {
1360
+ if (p.kind !== "flag")
1361
+ continue;
1362
+ const optValue = input.flagValues[optionKeyFromFlag(p.flag)];
1363
+ if (typeof optValue === "undefined")
1364
+ continue;
1365
+ if (p.in === "query") {
1366
+ queryValues[p.name] = optValue;
1367
+ }
1368
+ if (p.in === "header") {
1369
+ headerValues[p.name] = optValue;
1370
+ }
1371
+ if (p.in === "cookie") {
1372
+ cookieValues[p.name] = optValue;
1373
+ }
1374
+ }
1375
+ const schemas = deriveValidationSchemas(input.action);
1376
+ const ajv2 = createAjv();
1377
+ if (schemas.querySchema) {
1378
+ const validate = ajv2.compile(schemas.querySchema);
1379
+ if (!validate(queryValues)) {
1380
+ throw new Error(formatAjvErrors(validate.errors));
1381
+ }
1382
+ }
1383
+ if (schemas.headerSchema) {
1384
+ const validate = ajv2.compile(schemas.headerSchema);
1385
+ if (!validate(headerValues)) {
1386
+ throw new Error(formatAjvErrors(validate.errors));
1387
+ }
1388
+ }
1389
+ if (schemas.cookieSchema) {
1390
+ const validate = ajv2.compile(schemas.cookieSchema);
1391
+ if (!validate(cookieValues)) {
1392
+ throw new Error(formatAjvErrors(validate.errors));
1393
+ }
1394
+ }
1395
+ for (const [name, value] of Object.entries(queryValues)) {
1396
+ if (Array.isArray(value)) {
1397
+ for (const item of value) {
1398
+ url.searchParams.append(name, String(item));
1399
+ }
1400
+ continue;
1401
+ }
1402
+ url.searchParams.set(name, String(value));
1403
+ }
1404
+ for (const [name, value] of Object.entries(headerValues)) {
1405
+ headers.set(name, String(value));
1406
+ }
1407
+ for (const [name, value] of Object.entries(cookieValues)) {
1408
+ const existing = headers.get("Cookie");
1409
+ const part = `${name}=${String(value)}`;
1410
+ headers.set("Cookie", existing ? `${existing}; ${part}` : part);
1411
+ }
1412
+ let body;
1413
+ if (input.action.requestBody) {
1414
+ const bodyFlagDefs = input.bodyFlagDefs ?? [];
1415
+ const hasBodyFlags = bodyFlagDefs.some((def) => {
1416
+ const dotKey = def.path.join(".");
1417
+ return input.flagValues[dotKey] !== undefined;
1418
+ });
1419
+ const contentType = input.action.requestBody.preferredContentType;
1420
+ if (contentType)
1421
+ headers.set("Content-Type", contentType);
1422
+ const schema2 = input.action.requestBodySchema;
1423
+ const requiredFields = bodyFlagDefs.filter((d) => d.required);
1424
+ if (!hasBodyFlags) {
1425
+ if (requiredFields.length > 0) {
1426
+ const flagList = requiredFields.map((d) => `--${d.path.join(".")}`);
1427
+ throw new Error(`Required: ${flagList.join(", ")}`);
1428
+ }
1429
+ if (input.action.requestBody.required) {
1430
+ body = "{}";
1431
+ }
1432
+ } else {
1433
+ if (!contentType?.includes("json")) {
1434
+ throw new Error("Body field flags are only supported for JSON request bodies.");
1435
+ }
1436
+ const { findMissingRequired: findMissingRequired2, parseDotNotationFlags: parseDotNotationFlags2 } = await Promise.resolve().then(() => exports_body_flags);
1437
+ const missing = findMissingRequired2(input.flagValues, bodyFlagDefs);
1438
+ if (missing.length > 0) {
1439
+ const missingFlags = missing.map((m) => `--${m}`).join(", ");
1440
+ throw new Error(`Missing required fields: ${missingFlags}`);
1441
+ }
1442
+ const built = parseDotNotationFlags2(input.flagValues, bodyFlagDefs);
1443
+ if (schema2) {
1444
+ const validate = ajv2.compile(schema2);
1445
+ if (!validate(built)) {
1446
+ throw new Error(formatAjvErrors(validate.errors));
1447
+ }
1448
+ }
1449
+ body = JSON.stringify(built);
1450
+ }
1451
+ }
1452
+ const storedToken = profile?.name ? await getToken(input.specId, profile.name) : null;
1453
+ const resolvedAuthScheme = resolveAuthScheme(input.authSchemes, input.action.auth, {
1454
+ flagAuthScheme: input.globals.auth,
1455
+ profileAuthScheme: profile?.authScheme,
1456
+ embeddedAuthScheme: embedded?.auth,
1457
+ hasStoredToken: Boolean(storedToken)
1458
+ });
1459
+ const tokenFromProfile = resolvedAuthScheme ? storedToken : null;
1460
+ const globalsWithProfileAuth = {
1461
+ ...input.globals,
1462
+ auth: resolvedAuthScheme,
1463
+ bearerToken: input.globals.bearerToken ?? input.globals.oauthToken ?? tokenFromProfile ?? undefined
1464
+ };
1465
+ const final = applyAuth(headers, url, input.action, globalsWithProfileAuth, input.authSchemes);
1466
+ const req = new Request(final.url.toString(), {
1467
+ method: input.action.method,
1468
+ headers: final.headers,
1469
+ body
1470
+ });
1471
+ const curl = buildCurl(req, body);
1472
+ return { request: req, curl };
1473
+ }
1474
+ function buildCurl(req, body) {
1475
+ const parts = ["curl", "-sS", "-X", req.method];
1476
+ for (const [k, v] of req.headers.entries()) {
1477
+ parts.push("-H", shellQuote(`${k}: ${v}`));
1478
+ }
1479
+ if (typeof body === "string") {
1480
+ parts.push("--data", shellQuote(body));
1481
+ }
1482
+ parts.push(shellQuote(req.url));
1483
+ return parts.join(" ");
1484
+ }
1485
+ function shellQuote(value) {
1486
+ return `'${value.replace(/'/g, `'\\''`)}'`;
1487
+ }
1488
+ function optionKeyFromFlag(flag) {
1489
+ const name = flag.replace(/^--/, "");
1490
+ return name.replace(/-([a-z])/g, (_, c) => String(c).toUpperCase());
1491
+ }
1492
+
1493
+ // src/cli/runtime/execute.ts
1494
+ async function execute(input) {
1495
+ const { request, curl } = await buildRequest({
1496
+ specId: input.specId,
1497
+ action: input.action,
1498
+ positionalValues: input.positionalValues,
1499
+ flagValues: input.flagValues,
1500
+ globals: input.globals,
1501
+ servers: input.servers,
1502
+ authSchemes: input.authSchemes,
1503
+ embeddedDefaults: input.embeddedDefaults,
1504
+ bodyFlagDefs: input.bodyFlagDefs
1505
+ });
1506
+ const res = await fetch(request);
1507
+ const contentType = res.headers.get("content-type") ?? "";
1508
+ const text = await res.text();
1509
+ let body = text;
1510
+ if (contentType.includes("json") && text) {
1511
+ try {
1512
+ body = JSON.parse(text);
1513
+ } catch {}
1514
+ }
1515
+ return {
1516
+ ok: res.ok,
1517
+ status: res.status,
1518
+ body,
1519
+ curl
1520
+ };
1521
+ }
1522
+
1523
+ // src/ai/tools.ts
1524
+ var contextCache = new Map;
1525
+ async function getContext(spec) {
1526
+ let ctx = contextCache.get(spec);
1527
+ if (!ctx) {
1528
+ ctx = await buildRuntimeContext({ spec });
1529
+ contextCache.set(spec, ctx);
1530
+ }
1531
+ return ctx;
1532
+ }
1533
+ function findAction(ctx, resource, action) {
1534
+ const r = ctx.commands.resources.find((r2) => r2.resource.toLowerCase() === resource.toLowerCase());
1535
+ return r?.actions.find((a) => a.action.toLowerCase() === action.toLowerCase());
1536
+ }
1537
+ function specli(options) {
1538
+ const {
1539
+ spec,
1540
+ server,
1541
+ serverVars,
1542
+ bearerToken,
1543
+ apiKey,
1544
+ basicAuth,
1545
+ authScheme
1546
+ } = options;
1547
+ return tool({
1548
+ description: `Execute API operations. Commands: "list" (show resources/actions), "help" (action details), "exec" (call API).`,
1549
+ inputSchema: z.object({
1550
+ command: z.enum(["list", "help", "exec"]).describe("Command to run"),
1551
+ resource: z.string().optional().describe("Resource name (e.g. users)"),
1552
+ action: z.string().optional().describe("Action name (e.g. list, get, create)"),
1553
+ args: z.array(z.string()).optional().describe("Positional arguments"),
1554
+ flags: z.record(z.string(), z.unknown()).optional().describe("Named flags")
1555
+ }),
1556
+ execute: async ({ command, resource, action, args, flags }) => {
1557
+ const ctx = await getContext(spec);
1558
+ if (command === "list") {
1559
+ return {
1560
+ resources: ctx.commands.resources.map((r) => ({
1561
+ name: r.resource,
1562
+ actions: r.actions.map((a) => ({
1563
+ name: a.action,
1564
+ summary: a.summary,
1565
+ method: a.method,
1566
+ path: a.path,
1567
+ args: a.positionals.map((p) => p.name),
1568
+ requiredFlags: a.flags.filter((f) => f.required).map((f) => f.flag)
1569
+ }))
1570
+ }))
1571
+ };
1572
+ }
1573
+ if (command === "help") {
1574
+ if (!resource)
1575
+ return { error: "Missing resource" };
1576
+ const r = ctx.commands.resources.find((r2) => r2.resource.toLowerCase() === resource.toLowerCase());
1577
+ if (!r)
1578
+ return { error: `Unknown resource: ${resource}` };
1579
+ if (!action) {
1580
+ return {
1581
+ resource: r.resource,
1582
+ actions: r.actions.map((a2) => a2.action)
1583
+ };
1584
+ }
1585
+ const a = r.actions.find((a2) => a2.action.toLowerCase() === action.toLowerCase());
1586
+ if (!a)
1587
+ return { error: `Unknown action: ${action}` };
1588
+ return {
1589
+ action: a.action,
1590
+ method: a.method,
1591
+ path: a.path,
1592
+ summary: a.summary,
1593
+ args: a.positionals.map((p) => ({
1594
+ name: p.name,
1595
+ description: p.description
1596
+ })),
1597
+ flags: a.flags.map((f) => ({
1598
+ name: f.flag,
1599
+ type: f.type,
1600
+ required: f.required,
1601
+ description: f.description
1602
+ }))
1603
+ };
1604
+ }
1605
+ if (command === "exec") {
1606
+ if (!resource || !action)
1607
+ return { error: "Missing resource or action" };
1608
+ const actionDef = findAction(ctx, resource, action);
1609
+ if (!actionDef)
1610
+ return { error: `Unknown: ${resource} ${action}` };
1611
+ const positionalValues = args ?? [];
1612
+ if (positionalValues.length < actionDef.positionals.length) {
1613
+ return {
1614
+ error: `Missing args: ${actionDef.positionals.slice(positionalValues.length).map((p) => p.name).join(", ")}`
1615
+ };
1616
+ }
1617
+ const globals = {
1618
+ server,
1619
+ serverVar: serverVars ? Object.entries(serverVars).map(([k, v]) => `${k}=${v}`) : undefined,
1620
+ auth: authScheme,
1621
+ bearerToken,
1622
+ apiKey,
1623
+ username: basicAuth?.username,
1624
+ password: basicAuth?.password
1625
+ };
1626
+ try {
1627
+ const result = await execute({
1628
+ specId: ctx.loaded.id,
1629
+ action: actionDef,
1630
+ positionalValues,
1631
+ flagValues: flags ?? {},
1632
+ globals,
1633
+ servers: ctx.servers,
1634
+ authSchemes: ctx.authSchemes
1635
+ });
1636
+ return { status: result.status, ok: result.ok, body: result.body };
1637
+ } catch (err) {
1638
+ return { error: err instanceof Error ? err.message : String(err) };
1639
+ }
1640
+ }
1641
+ return { error: `Unknown command: ${command}` };
1642
+ }
1643
+ });
1644
+ }
1645
+ function clearSpecliCache(spec) {
1646
+ if (spec)
1647
+ contextCache.delete(spec);
1648
+ else
1649
+ contextCache.clear();
1650
+ }
1651
+ export {
1652
+ specli,
1653
+ clearSpecliCache
1654
+ };
1655
+
1656
+ //# debugId=7378D9634BF6BBAD64756E2164756E21