specli 0.0.5 → 0.0.7

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 (208) hide show
  1. package/cli.ts +13 -4
  2. package/dist/cli.d.ts +3 -0
  3. package/dist/cli.d.ts.map +1 -0
  4. package/dist/cli.js +2331 -0
  5. package/dist/cli.js.map +53 -0
  6. package/dist/index.d.ts +2 -0
  7. package/dist/index.d.ts.map +1 -0
  8. package/dist/index.js +2032 -0
  9. package/dist/index.js.map +48 -0
  10. package/dist/src/ai/tools.d.ts +139 -0
  11. package/dist/src/ai/tools.d.ts.map +1 -0
  12. package/dist/src/ai/tools.js +1656 -0
  13. package/dist/src/ai/tools.js.map +45 -0
  14. package/dist/src/cli/auth-requirements.d.ts +10 -0
  15. package/dist/src/cli/auth-requirements.d.ts.map +1 -0
  16. package/dist/src/cli/auth-requirements.js +66 -0
  17. package/dist/src/cli/auth-requirements.js.map +10 -0
  18. package/dist/src/cli/auth-schemes.d.ts +22 -0
  19. package/dist/src/cli/auth-schemes.d.ts.map +1 -0
  20. package/dist/src/cli/auth-schemes.js +116 -0
  21. package/dist/src/cli/auth-schemes.js.map +11 -0
  22. package/dist/src/cli/capabilities.d.ts +32 -0
  23. package/dist/src/cli/capabilities.d.ts.map +1 -0
  24. package/dist/src/cli/capabilities.js +45 -0
  25. package/dist/src/cli/capabilities.js.map +10 -0
  26. package/dist/src/cli/command-id.d.ts +8 -0
  27. package/dist/src/cli/command-id.d.ts.map +1 -0
  28. package/dist/src/cli/command-id.js +18 -0
  29. package/dist/src/cli/command-id.js.map +11 -0
  30. package/dist/src/cli/command-index.d.ts +6 -0
  31. package/dist/src/cli/command-index.d.ts.map +1 -0
  32. package/dist/src/cli/command-index.js +15 -0
  33. package/dist/src/cli/command-index.js.map +10 -0
  34. package/dist/src/cli/command-model.d.ts +40 -0
  35. package/dist/src/cli/command-model.d.ts.map +1 -0
  36. package/dist/src/cli/command-model.js +274 -0
  37. package/dist/src/cli/command-model.js.map +18 -0
  38. package/dist/src/cli/compile.d.ts +15 -0
  39. package/dist/src/cli/compile.d.ts.map +1 -0
  40. package/dist/src/cli/compile.js +146 -0
  41. package/dist/src/cli/compile.js.map +11 -0
  42. package/dist/src/cli/crypto.d.ts +2 -0
  43. package/dist/src/cli/crypto.d.ts.map +1 -0
  44. package/dist/src/cli/crypto.js +15 -0
  45. package/dist/src/cli/crypto.js.map +10 -0
  46. package/dist/src/cli/derive-name.d.ts +9 -0
  47. package/dist/src/cli/derive-name.d.ts.map +1 -0
  48. package/dist/src/cli/derive-name.js +70 -0
  49. package/dist/src/cli/derive-name.js.map +10 -0
  50. package/dist/src/cli/exec.d.ts +14 -0
  51. package/dist/src/cli/exec.d.ts.map +1 -0
  52. package/dist/src/cli/exec.js +2077 -0
  53. package/dist/src/cli/exec.js.map +49 -0
  54. package/dist/src/cli/main.d.ts +10 -0
  55. package/dist/src/cli/main.d.ts.map +1 -0
  56. package/dist/src/cli/main.js +2032 -0
  57. package/dist/src/cli/main.js.map +48 -0
  58. package/dist/src/cli/naming.d.ts +12 -0
  59. package/dist/src/cli/naming.d.ts.map +1 -0
  60. package/dist/src/cli/naming.js +216 -0
  61. package/dist/src/cli/naming.js.map +12 -0
  62. package/dist/src/cli/operations.d.ts +3 -0
  63. package/dist/src/cli/operations.d.ts.map +1 -0
  64. package/dist/src/cli/operations.js +103 -0
  65. package/dist/src/cli/operations.js.map +10 -0
  66. package/dist/src/cli/params.d.ts +19 -0
  67. package/dist/src/cli/params.d.ts.map +1 -0
  68. package/dist/src/cli/params.js +79 -0
  69. package/dist/src/cli/params.js.map +12 -0
  70. package/dist/src/cli/pluralize.d.ts +2 -0
  71. package/dist/src/cli/pluralize.d.ts.map +1 -0
  72. package/dist/src/cli/pluralize.js +43 -0
  73. package/dist/src/cli/pluralize.js.map +10 -0
  74. package/dist/src/cli/positional.d.ts +19 -0
  75. package/dist/src/cli/positional.d.ts.map +1 -0
  76. package/dist/src/cli/positional.js +39 -0
  77. package/dist/src/cli/positional.js.map +10 -0
  78. package/dist/src/cli/request-body.d.ts +20 -0
  79. package/dist/src/cli/request-body.d.ts.map +1 -0
  80. package/dist/src/cli/request-body.js +82 -0
  81. package/dist/src/cli/request-body.js.map +12 -0
  82. package/dist/src/cli/runtime/argv.d.ts +3 -0
  83. package/dist/src/cli/runtime/argv.d.ts.map +1 -0
  84. package/dist/src/cli/runtime/argv.js +22 -0
  85. package/dist/src/cli/runtime/argv.js.map +10 -0
  86. package/dist/src/cli/runtime/auth/resolve.d.ts +9 -0
  87. package/dist/src/cli/runtime/auth/resolve.d.ts.map +1 -0
  88. package/dist/src/cli/runtime/auth/resolve.js +38 -0
  89. package/dist/src/cli/runtime/auth/resolve.js.map +10 -0
  90. package/dist/src/cli/runtime/body-flags.d.ts +41 -0
  91. package/dist/src/cli/runtime/body-flags.d.ts.map +1 -0
  92. package/dist/src/cli/runtime/body-flags.js +86 -0
  93. package/dist/src/cli/runtime/body-flags.js.map +10 -0
  94. package/dist/src/cli/runtime/body.d.ts +15 -0
  95. package/dist/src/cli/runtime/body.d.ts.map +1 -0
  96. package/dist/src/cli/runtime/body.js +40 -0
  97. package/dist/src/cli/runtime/body.js.map +11 -0
  98. package/dist/src/cli/runtime/collect.d.ts +2 -0
  99. package/dist/src/cli/runtime/collect.d.ts.map +1 -0
  100. package/dist/src/cli/runtime/collect.js +9 -0
  101. package/dist/src/cli/runtime/collect.js.map +10 -0
  102. package/dist/src/cli/runtime/compat.d.ts +35 -0
  103. package/dist/src/cli/runtime/compat.d.ts.map +1 -0
  104. package/dist/src/cli/runtime/compat.js +62 -0
  105. package/dist/src/cli/runtime/compat.js.map +10 -0
  106. package/dist/src/cli/runtime/context.d.ts +16 -0
  107. package/dist/src/cli/runtime/context.d.ts.map +1 -0
  108. package/dist/src/cli/runtime/context.js +936 -0
  109. package/dist/src/cli/runtime/context.js.map +32 -0
  110. package/dist/src/cli/runtime/execute.d.ts +33 -0
  111. package/dist/src/cli/runtime/execute.d.ts.map +1 -0
  112. package/dist/src/cli/runtime/execute.js +670 -0
  113. package/dist/src/cli/runtime/execute.js.map +22 -0
  114. package/dist/src/cli/runtime/generated.d.ts +14 -0
  115. package/dist/src/cli/runtime/generated.d.ts.map +1 -0
  116. package/dist/src/cli/runtime/generated.js +869 -0
  117. package/dist/src/cli/runtime/generated.js.map +23 -0
  118. package/dist/src/cli/runtime/headers.d.ts +9 -0
  119. package/dist/src/cli/runtime/headers.d.ts.map +1 -0
  120. package/dist/src/cli/runtime/headers.js +36 -0
  121. package/dist/src/cli/runtime/headers.js.map +10 -0
  122. package/dist/src/cli/runtime/index.d.ts +4 -0
  123. package/dist/src/cli/runtime/index.d.ts.map +1 -0
  124. package/dist/src/cli/runtime/index.js +1808 -0
  125. package/dist/src/cli/runtime/index.js.map +46 -0
  126. package/dist/src/cli/runtime/profile/secrets.d.ts +25 -0
  127. package/dist/src/cli/runtime/profile/secrets.d.ts.map +1 -0
  128. package/dist/src/cli/runtime/profile/secrets.js +51 -0
  129. package/dist/src/cli/runtime/profile/secrets.js.map +11 -0
  130. package/dist/src/cli/runtime/profile/store.d.ts +15 -0
  131. package/dist/src/cli/runtime/profile/store.d.ts.map +1 -0
  132. package/dist/src/cli/runtime/profile/store.js +102 -0
  133. package/dist/src/cli/runtime/profile/store.js.map +11 -0
  134. package/dist/src/cli/runtime/request.d.ts +36 -0
  135. package/dist/src/cli/runtime/request.d.ts.map +1 -0
  136. package/dist/src/cli/runtime/request.js +571 -0
  137. package/dist/src/cli/runtime/request.js.map +21 -0
  138. package/dist/src/cli/runtime/server-url.d.ts +8 -0
  139. package/dist/src/cli/runtime/server-url.d.ts.map +1 -0
  140. package/dist/src/cli/runtime/server-url.js +55 -0
  141. package/dist/src/cli/runtime/server-url.js.map +11 -0
  142. package/dist/src/cli/runtime/template.d.ts +5 -0
  143. package/dist/src/cli/runtime/template.d.ts.map +1 -0
  144. package/dist/src/cli/runtime/template.js +29 -0
  145. package/dist/src/cli/runtime/template.js.map +10 -0
  146. package/dist/src/cli/runtime/validate/ajv.d.ts +3 -0
  147. package/dist/src/cli/runtime/validate/ajv.d.ts.map +1 -0
  148. package/dist/src/cli/runtime/validate/ajv.js +17 -0
  149. package/dist/src/cli/runtime/validate/ajv.js.map +10 -0
  150. package/dist/src/cli/runtime/validate/coerce.d.ts +4 -0
  151. package/dist/src/cli/runtime/validate/coerce.d.ts.map +1 -0
  152. package/dist/src/cli/runtime/validate/coerce.js +60 -0
  153. package/dist/src/cli/runtime/validate/coerce.js.map +10 -0
  154. package/dist/src/cli/runtime/validate/error.d.ts +3 -0
  155. package/dist/src/cli/runtime/validate/error.d.ts.map +1 -0
  156. package/dist/src/cli/runtime/validate/error.js +21 -0
  157. package/dist/src/cli/runtime/validate/error.js.map +10 -0
  158. package/dist/src/cli/runtime/validate/index.d.ts +5 -0
  159. package/dist/src/cli/runtime/validate/index.d.ts.map +1 -0
  160. package/dist/src/cli/runtime/validate/index.js +122 -0
  161. package/dist/src/cli/runtime/validate/index.js.map +13 -0
  162. package/dist/src/cli/runtime/validate/schema.d.ts +9 -0
  163. package/dist/src/cli/runtime/validate/schema.d.ts.map +1 -0
  164. package/dist/src/cli/runtime/validate/schema.js +36 -0
  165. package/dist/src/cli/runtime/validate/schema.js.map +10 -0
  166. package/dist/src/cli/schema-shape.d.ts +5 -0
  167. package/dist/src/cli/schema-shape.d.ts.map +1 -0
  168. package/dist/src/cli/schema-shape.js +41 -0
  169. package/dist/src/cli/schema-shape.js.map +10 -0
  170. package/dist/src/cli/schema.d.ts +30 -0
  171. package/dist/src/cli/schema.d.ts.map +1 -0
  172. package/dist/src/cli/schema.js +38 -0
  173. package/dist/src/cli/schema.js.map +10 -0
  174. package/dist/src/cli/server.d.ts +16 -0
  175. package/dist/src/cli/server.d.ts.map +1 -0
  176. package/dist/src/cli/server.js +64 -0
  177. package/dist/src/cli/server.js.map +11 -0
  178. package/dist/src/cli/spec-id.d.ts +3 -0
  179. package/dist/src/cli/spec-id.d.ts.map +1 -0
  180. package/dist/src/cli/spec-id.js +21 -0
  181. package/dist/src/cli/spec-id.js.map +11 -0
  182. package/dist/src/cli/spec-loader.d.ts +7 -0
  183. package/dist/src/cli/spec-loader.d.ts.map +1 -0
  184. package/dist/src/cli/spec-loader.js +110 -0
  185. package/dist/src/cli/spec-loader.js.map +15 -0
  186. package/dist/src/cli/stable-json.d.ts +4 -0
  187. package/dist/src/cli/stable-json.d.ts.map +1 -0
  188. package/dist/src/cli/stable-json.js +35 -0
  189. package/dist/src/cli/stable-json.js.map +10 -0
  190. package/dist/src/cli/strings.d.ts +3 -0
  191. package/dist/src/cli/strings.d.ts.map +1 -0
  192. package/dist/src/cli/strings.js +16 -0
  193. package/dist/src/cli/strings.js.map +10 -0
  194. package/dist/src/cli/types.d.ts +53 -0
  195. package/dist/src/cli/types.d.ts.map +1 -0
  196. package/dist/src/cli/types.js +9 -0
  197. package/dist/src/cli/types.js.map +10 -0
  198. package/package.json +31 -4
  199. package/src/ai/tools.ts +211 -0
  200. package/src/cli/main.ts +3 -2
  201. package/src/cli/runtime/body.ts +3 -3
  202. package/src/cli/runtime/compat.ts +89 -0
  203. package/src/cli/runtime/execute.ts +98 -39
  204. package/src/cli/runtime/generated.ts +111 -4
  205. package/src/cli/runtime/profile/secrets.ts +42 -1
  206. package/src/cli/runtime/profile/store.ts +15 -13
  207. package/src/cli/runtime/request.ts +12 -4
  208. package/src/cli/spec-loader.ts +2 -2
@@ -0,0 +1,2032 @@
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(schema, reservedFlags) {
20
+ if (!schema || schema.type !== "object" || !schema.properties) {
21
+ return [];
22
+ }
23
+ const flags = [];
24
+ const requiredSet = new Set(schema.required ?? []);
25
+ collectFlags(schema.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/cli/main.ts
99
+ import { Command as Command2 } from "commander";
100
+
101
+ // src/cli/runtime/argv.ts
102
+ function getArgValue(argv, key) {
103
+ for (let i = 0;i < argv.length; i++) {
104
+ const a = argv[i];
105
+ if (!a)
106
+ continue;
107
+ if (a === key)
108
+ return argv[i + 1];
109
+ if (a.startsWith(`${key}=`))
110
+ return a.slice(key.length + 1);
111
+ }
112
+ return;
113
+ }
114
+ function hasAnyArg(argv, names) {
115
+ return argv.some((a) => a && names.includes(a));
116
+ }
117
+
118
+ // src/cli/runtime/collect.ts
119
+ function collectRepeatable(value, previous) {
120
+ return [...previous ?? [], value];
121
+ }
122
+
123
+ // src/cli/runtime/compat.ts
124
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
125
+ import { parse as parseYaml } from "yaml";
126
+ var isBun = typeof globalThis.Bun !== "undefined";
127
+ async function readFileText(path) {
128
+ if (isBun) {
129
+ return Bun.file(path).text();
130
+ }
131
+ return readFileSync(path, "utf-8");
132
+ }
133
+ async function fileExists(path) {
134
+ if (isBun) {
135
+ return Bun.file(path).exists();
136
+ }
137
+ return existsSync(path);
138
+ }
139
+ async function writeFileText(path, content) {
140
+ if (isBun) {
141
+ await Bun.write(path, content);
142
+ return;
143
+ }
144
+ writeFileSync(path, content, "utf-8");
145
+ }
146
+ async function mkdirp(path) {
147
+ if (isBun) {
148
+ await Bun.$`mkdir -p ${path}`;
149
+ return;
150
+ }
151
+ mkdirSync(path, { recursive: true });
152
+ }
153
+ function parseYamlContent(text) {
154
+ if (isBun) {
155
+ const { YAML } = globalThis.Bun;
156
+ return YAML.parse(text);
157
+ }
158
+ return parseYaml(text);
159
+ }
160
+ async function readStdinText() {
161
+ if (isBun) {
162
+ return Bun.stdin.text();
163
+ }
164
+ return new Promise((resolve, reject) => {
165
+ let data = "";
166
+ process.stdin.setEncoding("utf8");
167
+ process.stdin.on("data", (chunk) => {
168
+ data += chunk;
169
+ });
170
+ process.stdin.on("end", () => resolve(data));
171
+ process.stdin.on("error", reject);
172
+ });
173
+ }
174
+
175
+ // src/cli/strings.ts
176
+ function kebabCase(input) {
177
+ const trimmed = input.trim();
178
+ if (!trimmed)
179
+ return "";
180
+ 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();
181
+ }
182
+
183
+ // src/cli/auth-schemes.ts
184
+ function parseOAuthFlow(flow) {
185
+ if (!flow)
186
+ return;
187
+ const scopesObj = flow.scopes;
188
+ const scopes = scopesObj && typeof scopesObj === "object" && !Array.isArray(scopesObj) ? Object.keys(scopesObj) : [];
189
+ return {
190
+ authorizationUrl: typeof flow.authorizationUrl === "string" ? flow.authorizationUrl : undefined,
191
+ tokenUrl: typeof flow.tokenUrl === "string" ? flow.tokenUrl : undefined,
192
+ refreshUrl: typeof flow.refreshUrl === "string" ? flow.refreshUrl : undefined,
193
+ scopes: scopes.sort()
194
+ };
195
+ }
196
+ function parseOAuthFlows(flows) {
197
+ if (!flows)
198
+ return;
199
+ const out = {};
200
+ const implicit = parseOAuthFlow(flows.implicit);
201
+ if (implicit)
202
+ out.implicit = implicit;
203
+ const password = parseOAuthFlow(flows.password);
204
+ if (password)
205
+ out.password = password;
206
+ const clientCredentials = parseOAuthFlow(flows.clientCredentials);
207
+ if (clientCredentials)
208
+ out.clientCredentials = clientCredentials;
209
+ const authorizationCode = parseOAuthFlow(flows.authorizationCode);
210
+ if (authorizationCode)
211
+ out.authorizationCode = authorizationCode;
212
+ return Object.keys(out).length ? out : undefined;
213
+ }
214
+ function listAuthSchemes(doc) {
215
+ const schemes = doc.components?.securitySchemes;
216
+ if (!schemes || typeof schemes !== "object")
217
+ return [];
218
+ const out = [];
219
+ for (const [key, raw] of Object.entries(schemes)) {
220
+ if (!raw || typeof raw !== "object")
221
+ continue;
222
+ const s = raw;
223
+ const type = s.type;
224
+ if (type === "http") {
225
+ const scheme = (s.scheme ?? "").toLowerCase();
226
+ if (scheme === "bearer") {
227
+ out.push({
228
+ key,
229
+ kind: "http-bearer",
230
+ scheme,
231
+ bearerFormat: s.bearerFormat,
232
+ description: s.description
233
+ });
234
+ } else if (scheme === "basic") {
235
+ out.push({
236
+ key,
237
+ kind: "http-basic",
238
+ scheme,
239
+ description: s.description
240
+ });
241
+ } else {
242
+ out.push({
243
+ key,
244
+ kind: "unknown",
245
+ scheme: s.scheme,
246
+ description: s.description
247
+ });
248
+ }
249
+ continue;
250
+ }
251
+ if (type === "apiKey") {
252
+ const where = s.in;
253
+ const loc = where === "header" || where === "query" || where === "cookie" ? where : undefined;
254
+ out.push({
255
+ key,
256
+ kind: "api-key",
257
+ name: s.name,
258
+ in: loc,
259
+ description: s.description
260
+ });
261
+ continue;
262
+ }
263
+ if (type === "oauth2") {
264
+ out.push({
265
+ key,
266
+ kind: "oauth2",
267
+ description: s.description,
268
+ oauthFlows: parseOAuthFlows(s.flows)
269
+ });
270
+ continue;
271
+ }
272
+ if (type === "openIdConnect") {
273
+ out.push({
274
+ key,
275
+ kind: "openIdConnect",
276
+ description: s.description,
277
+ openIdConnectUrl: s.openIdConnectUrl
278
+ });
279
+ continue;
280
+ }
281
+ out.push({ key, kind: "unknown", description: s.description });
282
+ }
283
+ out.sort((a, b) => kebabCase(a.key).localeCompare(kebabCase(b.key)));
284
+ return out;
285
+ }
286
+
287
+ // src/cli/capabilities.ts
288
+ function uniqueSorted(items, compare) {
289
+ const out = [...items];
290
+ out.sort(compare);
291
+ return out.filter((v, i) => i === 0 || compare(out[i - 1], v) !== 0);
292
+ }
293
+ function hasSecurity(requirements) {
294
+ if (!requirements?.length)
295
+ return false;
296
+ return true;
297
+ }
298
+ function deriveCapabilities(input) {
299
+ const serverHasVars = input.servers.some((s) => s.variableNames.length > 0);
300
+ const authKinds = uniqueSorted(input.authSchemes.map((s) => s.kind), (a, b) => a.localeCompare(b));
301
+ const hasSecurityRequirements = hasSecurity(input.doc.security) || input.operations.some((op) => hasSecurity(op.security));
302
+ const opHasBodies = input.operations.some((op) => Boolean(op.requestBody));
303
+ const cmdResources = input.commands?.resources ?? [];
304
+ const cmdActions = cmdResources.flatMap((r) => r.actions);
305
+ const cmdHasBodies = cmdActions.some((a) => Boolean(a.requestBody));
306
+ return {
307
+ servers: {
308
+ count: input.servers.length,
309
+ hasVariables: serverHasVars
310
+ },
311
+ auth: {
312
+ count: input.authSchemes.length,
313
+ kinds: authKinds,
314
+ hasSecurityRequirements
315
+ },
316
+ operations: {
317
+ count: input.operations.length,
318
+ hasRequestBodies: opHasBodies
319
+ },
320
+ commands: {
321
+ countResources: cmdResources.length,
322
+ countActions: cmdActions.length,
323
+ hasRequestBodies: cmdHasBodies
324
+ }
325
+ };
326
+ }
327
+
328
+ // src/cli/command-index.ts
329
+ function buildCommandsIndex(commands) {
330
+ const byId = {};
331
+ for (const resource of commands?.resources ?? []) {
332
+ for (const action of resource.actions) {
333
+ byId[action.id] = action;
334
+ }
335
+ }
336
+ return { byId };
337
+ }
338
+
339
+ // src/cli/auth-requirements.ts
340
+ function isSecurityRequirement(value) {
341
+ if (!value || typeof value !== "object")
342
+ return false;
343
+ if (Array.isArray(value))
344
+ return false;
345
+ for (const [k, v] of Object.entries(value)) {
346
+ if (typeof k !== "string")
347
+ return false;
348
+ if (!Array.isArray(v))
349
+ return false;
350
+ if (!v.every((s) => typeof s === "string"))
351
+ return false;
352
+ }
353
+ return true;
354
+ }
355
+ function normalizeSecurity(value) {
356
+ if (value == null)
357
+ return { requirements: [], source: "none" };
358
+ if (!Array.isArray(value))
359
+ return { requirements: [], source: "none" };
360
+ const reqs = value.filter(isSecurityRequirement);
361
+ if (reqs.length === 0)
362
+ return { requirements: [], source: "empty" };
363
+ return { requirements: reqs, source: "non-empty" };
364
+ }
365
+ function summarizeAuth(operationSecurity, globalSecurity, knownSchemes) {
366
+ const op = normalizeSecurity(operationSecurity);
367
+ if (op.source === "non-empty") {
368
+ return { alternatives: toAlternatives(op.requirements, knownSchemes) };
369
+ }
370
+ if (op.source === "empty") {
371
+ return { alternatives: [] };
372
+ }
373
+ const global = normalizeSecurity(globalSecurity);
374
+ if (global.source === "non-empty") {
375
+ return { alternatives: toAlternatives(global.requirements, knownSchemes) };
376
+ }
377
+ return { alternatives: [] };
378
+ }
379
+ function toAlternatives(requirements, knownSchemes) {
380
+ const known = new Set(knownSchemes.map((s) => s.key));
381
+ return requirements.map((req) => {
382
+ const out = [];
383
+ for (const [key, scopes] of Object.entries(req)) {
384
+ out.push({
385
+ key,
386
+ scopes: Array.isArray(scopes) ? scopes : []
387
+ });
388
+ }
389
+ out.sort((a, b) => a.key.localeCompare(b.key));
390
+ out.sort((a, b) => {
391
+ const ak = known.has(a.key) ? 0 : 1;
392
+ const bk = known.has(b.key) ? 0 : 1;
393
+ if (ak !== bk)
394
+ return ak - bk;
395
+ return a.key.localeCompare(b.key);
396
+ });
397
+ return out;
398
+ });
399
+ }
400
+
401
+ // src/cli/command-id.ts
402
+ function buildCommandId(parts) {
403
+ const op = kebabCase(parts.operationKey.replace(/\s+/g, "-"));
404
+ return `${parts.specId}:${kebabCase(parts.resource)}:${kebabCase(parts.action)}:${op}`;
405
+ }
406
+
407
+ // src/cli/schema-shape.ts
408
+ function getSchemaType(schema) {
409
+ if (!schema || typeof schema !== "object")
410
+ return "unknown";
411
+ const t = schema.type;
412
+ if (t === "string")
413
+ return "string";
414
+ if (t === "number")
415
+ return "number";
416
+ if (t === "integer")
417
+ return "integer";
418
+ if (t === "boolean")
419
+ return "boolean";
420
+ if (t === "array")
421
+ return "array";
422
+ if (t === "object")
423
+ return "object";
424
+ return "unknown";
425
+ }
426
+ function getSchemaFormat(schema) {
427
+ if (!schema || typeof schema !== "object")
428
+ return;
429
+ const f = schema.format;
430
+ return typeof f === "string" ? f : undefined;
431
+ }
432
+ function getSchemaEnumStrings(schema) {
433
+ if (!schema || typeof schema !== "object")
434
+ return;
435
+ const e = schema.enum;
436
+ if (!Array.isArray(e))
437
+ return;
438
+ const values = e.filter((v) => typeof v === "string");
439
+ return values.length ? values : undefined;
440
+ }
441
+
442
+ // src/cli/params.ts
443
+ function deriveParamSpecs(op) {
444
+ const out = [];
445
+ for (const p of op.parameters) {
446
+ const flag = `--${kebabCase(p.name)}`;
447
+ const type = getSchemaType(p.schema);
448
+ const schemaObj = p.schema && typeof p.schema === "object" ? p.schema : undefined;
449
+ const itemsSchema = schemaObj && type === "array" && typeof schemaObj.items === "object" ? schemaObj.items : undefined;
450
+ out.push({
451
+ kind: p.in === "path" ? "positional" : "flag",
452
+ in: p.in,
453
+ name: p.name,
454
+ flag,
455
+ required: p.required,
456
+ description: p.description,
457
+ type,
458
+ format: getSchemaFormat(p.schema),
459
+ enum: getSchemaEnumStrings(p.schema),
460
+ itemType: type === "array" ? getSchemaType(itemsSchema) : undefined,
461
+ itemFormat: type === "array" ? getSchemaFormat(itemsSchema) : undefined,
462
+ itemEnum: type === "array" ? getSchemaEnumStrings(itemsSchema) : undefined,
463
+ schema: schemaObj
464
+ });
465
+ }
466
+ out.sort((a, b) => {
467
+ if (a.in !== b.in)
468
+ return a.in.localeCompare(b.in);
469
+ return a.name.localeCompare(b.name);
470
+ });
471
+ return out;
472
+ }
473
+
474
+ // src/cli/positional.ts
475
+ function derivePositionals(action) {
476
+ const byName = new Map;
477
+ for (const name of action.pathArgs) {
478
+ const p = action.params.find((x) => x.in === "path" && x.name === name);
479
+ byName.set(name, {
480
+ name,
481
+ required: true,
482
+ description: p?.description,
483
+ type: p?.type ?? "unknown",
484
+ format: p?.format,
485
+ enum: p?.enum
486
+ });
487
+ }
488
+ return [...byName.values()];
489
+ }
490
+ function deriveFlags(action) {
491
+ return {
492
+ flags: action.params.filter((p) => p.kind === "flag").map((p) => ({
493
+ in: p.in,
494
+ name: p.name,
495
+ flag: p.flag,
496
+ required: p.required,
497
+ description: p.description,
498
+ type: p.type,
499
+ format: p.format,
500
+ enum: p.enum,
501
+ itemType: p.itemType,
502
+ itemFormat: p.itemFormat,
503
+ itemEnum: p.itemEnum
504
+ }))
505
+ };
506
+ }
507
+
508
+ // src/cli/types.ts
509
+ function isJsonSchema(value) {
510
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
511
+ }
512
+
513
+ // src/cli/request-body.ts
514
+ function getRequestBody(op) {
515
+ return op.requestBody;
516
+ }
517
+ function deriveRequestBodyInfo(op) {
518
+ const rb = getRequestBody(op);
519
+ if (!rb)
520
+ return;
521
+ const content = [];
522
+ for (const contentType of rb.contentTypes) {
523
+ const schema = rb.schemasByContentType[contentType];
524
+ content.push({
525
+ contentType,
526
+ required: rb.required,
527
+ schemaType: getSchemaType(schema),
528
+ schemaFormat: getSchemaFormat(schema),
529
+ schemaEnum: getSchemaEnumStrings(schema)
530
+ });
531
+ }
532
+ content.sort((a, b) => a.contentType.localeCompare(b.contentType));
533
+ const hasJson = content.some((c) => c.contentType.includes("json"));
534
+ const hasFormUrlEncoded = content.some((c) => c.contentType === "application/x-www-form-urlencoded");
535
+ const hasMultipart = content.some((c) => c.contentType.startsWith("multipart/"));
536
+ const bodyFlags = ["--data", "--file"];
537
+ const preferredContentType = content.find((c) => c.contentType === "application/json")?.contentType ?? content.find((c) => c.contentType.includes("json"))?.contentType ?? content[0]?.contentType;
538
+ const preferredSchema = preferredContentType ? rb.schemasByContentType[preferredContentType] : undefined;
539
+ return {
540
+ required: rb.required,
541
+ content,
542
+ hasJson,
543
+ hasFormUrlEncoded,
544
+ hasMultipart,
545
+ bodyFlags,
546
+ preferredContentType,
547
+ preferredSchema: isJsonSchema(preferredSchema) ? preferredSchema : undefined
548
+ };
549
+ }
550
+
551
+ // src/cli/command-model.ts
552
+ function buildCommandModel(planned, options) {
553
+ const byResource = new Map;
554
+ for (const op of planned) {
555
+ const list = byResource.get(op.resource) ?? [];
556
+ const params = deriveParamSpecs(op);
557
+ const positionals = derivePositionals({ pathArgs: op.pathArgs, params });
558
+ const flags = deriveFlags({ pathArgs: op.pathArgs, params });
559
+ list.push({
560
+ id: buildCommandId({
561
+ specId: options.specId,
562
+ resource: op.resource,
563
+ action: op.action,
564
+ operationKey: op.key
565
+ }),
566
+ key: op.key,
567
+ action: op.action,
568
+ pathArgs: op.pathArgs,
569
+ method: op.method,
570
+ path: op.path,
571
+ operationId: op.operationId,
572
+ tags: op.tags,
573
+ summary: op.summary,
574
+ description: op.description,
575
+ deprecated: op.deprecated,
576
+ style: op.style,
577
+ params,
578
+ positionals,
579
+ flags: flags.flags,
580
+ auth: summarizeAuth(op.security, options.globalSecurity, options.authSchemes ?? []),
581
+ requestBody: deriveRequestBodyInfo(op),
582
+ requestBodySchema: deriveRequestBodyInfo(op)?.preferredSchema
583
+ });
584
+ byResource.set(op.resource, list);
585
+ }
586
+ const resources = [];
587
+ for (const [resource, actions] of byResource.entries()) {
588
+ actions.sort((a, b) => {
589
+ if (a.action !== b.action)
590
+ return a.action.localeCompare(b.action);
591
+ if (a.path !== b.path)
592
+ return a.path.localeCompare(b.path);
593
+ return a.method.localeCompare(b.method);
594
+ });
595
+ resources.push({ resource, actions });
596
+ }
597
+ resources.sort((a, b) => a.resource.localeCompare(b.resource));
598
+ return { resources };
599
+ }
600
+
601
+ // src/cli/pluralize.ts
602
+ var IRREGULAR = {
603
+ person: "people",
604
+ man: "men",
605
+ woman: "women",
606
+ child: "children",
607
+ tooth: "teeth",
608
+ foot: "feet",
609
+ mouse: "mice",
610
+ goose: "geese"
611
+ };
612
+ var UNCOUNTABLE = new Set([
613
+ "metadata",
614
+ "information",
615
+ "equipment",
616
+ "money",
617
+ "series",
618
+ "species"
619
+ ]);
620
+ function pluralize(word) {
621
+ const w = word.trim();
622
+ if (!w)
623
+ return w;
624
+ const lower = w.toLowerCase();
625
+ if (UNCOUNTABLE.has(lower))
626
+ return lower;
627
+ if (IRREGULAR[lower])
628
+ return IRREGULAR[lower];
629
+ if (lower.endsWith("s"))
630
+ return lower;
631
+ if (/[bcdfghjklmnpqrstvwxyz]y$/.test(lower)) {
632
+ return lower.replace(/y$/, "ies");
633
+ }
634
+ if (/(ch|sh|x|z)$/.test(lower)) {
635
+ return `${lower}es`;
636
+ }
637
+ return `${lower}s`;
638
+ }
639
+
640
+ // src/cli/naming.ts
641
+ var GENERIC_TAGS = new Set(["default", "defaults", "api"]);
642
+ function getPathSegments(path) {
643
+ return path.split("/").map((s) => s.trim()).filter(Boolean);
644
+ }
645
+ function getPathArgs(path) {
646
+ const args = [];
647
+ const re = /\{([^}]+)\}/g;
648
+ while (true) {
649
+ const match = re.exec(path);
650
+ if (!match)
651
+ break;
652
+ args.push(match[1]);
653
+ }
654
+ return args;
655
+ }
656
+ function pickResourceFromTags(tags) {
657
+ if (!tags.length)
658
+ return;
659
+ const first = tags[0]?.trim();
660
+ if (!first)
661
+ return;
662
+ if (GENERIC_TAGS.has(first.toLowerCase()))
663
+ return;
664
+ return first;
665
+ }
666
+ function splitOperationId(operationId) {
667
+ const trimmed = operationId.trim();
668
+ if (!trimmed)
669
+ return {};
670
+ if (trimmed.includes(".")) {
671
+ const [prefix, ...rest] = trimmed.split(".");
672
+ return { prefix, suffix: rest.join(".") };
673
+ }
674
+ if (trimmed.includes("__")) {
675
+ const [prefix, ...rest] = trimmed.split("__");
676
+ return { prefix, suffix: rest.join("__") };
677
+ }
678
+ if (trimmed.includes("_")) {
679
+ const [prefix, ...rest] = trimmed.split("_");
680
+ return { prefix, suffix: rest.join("_") };
681
+ }
682
+ return { suffix: trimmed };
683
+ }
684
+ function inferStyle(op) {
685
+ if (op.path.includes("."))
686
+ return "rpc";
687
+ if (op.operationId?.includes(".") && op.method === "POST")
688
+ return "rpc";
689
+ return "rest";
690
+ }
691
+ function inferResource(op) {
692
+ const tag = pickResourceFromTags(op.tags);
693
+ if (tag)
694
+ return pluralize(kebabCase(tag));
695
+ if (op.operationId) {
696
+ const { prefix } = splitOperationId(op.operationId);
697
+ if (prefix) {
698
+ const fromId = kebabCase(prefix);
699
+ if (fromId === "ping")
700
+ return "ping";
701
+ return pluralize(fromId);
702
+ }
703
+ }
704
+ const segments = getPathSegments(op.path);
705
+ let first = segments[0] ?? "api";
706
+ first = first.includes(".") ? first.split(".")[0] : first;
707
+ if (first.toLowerCase() === "ping")
708
+ return "ping";
709
+ const cleaned = first.replace(/^\{.+\}$/, "");
710
+ return pluralize(kebabCase(cleaned || "api"));
711
+ }
712
+ function canonicalizeAction(action) {
713
+ const a = kebabCase(action);
714
+ if (a === "retrieve" || a === "read")
715
+ return "get";
716
+ if (a === "list" || a === "search")
717
+ return "list";
718
+ if (a === "create")
719
+ return "create";
720
+ if (a === "update" || a === "patch")
721
+ return "update";
722
+ if (a === "delete" || a === "remove")
723
+ return "delete";
724
+ return a;
725
+ }
726
+ function inferRestAction(op) {
727
+ if (op.operationId) {
728
+ const { suffix } = splitOperationId(op.operationId);
729
+ if (suffix) {
730
+ const fromId = canonicalizeAction(suffix);
731
+ if (fromId === "get" || fromId === "list" || fromId === "create" || fromId === "update" || fromId === "delete") {
732
+ return fromId;
733
+ }
734
+ }
735
+ }
736
+ const method = op.method.toUpperCase();
737
+ const args = getPathArgs(op.path);
738
+ const hasId = args.length > 0;
739
+ if (method === "GET" && !hasId)
740
+ return "list";
741
+ if (method === "POST" && !hasId)
742
+ return "create";
743
+ if (method === "GET" && hasId)
744
+ return "get";
745
+ if ((method === "PUT" || method === "PATCH") && hasId)
746
+ return "update";
747
+ if (method === "DELETE" && hasId)
748
+ return "delete";
749
+ return kebabCase(method);
750
+ }
751
+ function inferRpcAction(op) {
752
+ if (op.operationId) {
753
+ const { suffix } = splitOperationId(op.operationId);
754
+ if (suffix)
755
+ return canonicalizeAction(suffix);
756
+ }
757
+ const segments = getPathSegments(op.path);
758
+ const last = segments[segments.length - 1] ?? "";
759
+ if (last.includes(".")) {
760
+ const part = last.split(".").pop() ?? last;
761
+ return canonicalizeAction(part);
762
+ }
763
+ return kebabCase(op.method);
764
+ }
765
+ function planOperation(op) {
766
+ const style = inferStyle(op);
767
+ const resource = inferResource(op);
768
+ const action = style === "rpc" ? inferRpcAction(op) : inferRestAction(op);
769
+ return {
770
+ ...op,
771
+ key: op.key,
772
+ style,
773
+ resource,
774
+ action,
775
+ canonicalAction: action,
776
+ pathArgs: getPathArgs(op.path).map((a) => kebabCase(a))
777
+ };
778
+ }
779
+ function planOperations(ops) {
780
+ const planned = ops.map(planOperation);
781
+ const counts = new Map;
782
+ for (const op of planned) {
783
+ const key = `${op.resource}:${op.action}`;
784
+ counts.set(key, (counts.get(key) ?? 0) + 1);
785
+ }
786
+ const seen = new Map;
787
+ return planned.map((op) => {
788
+ const key = `${op.resource}:${op.action}`;
789
+ const total = counts.get(key) ?? 0;
790
+ if (total <= 1)
791
+ return op;
792
+ const idx = (seen.get(key) ?? 0) + 1;
793
+ seen.set(key, idx);
794
+ const suffix = op.operationId ? kebabCase(op.operationId) : kebabCase(`${op.method}-${op.path}`);
795
+ const disambiguatedAction = `${op.action}-${suffix}-${idx}`;
796
+ return {
797
+ ...op,
798
+ action: disambiguatedAction,
799
+ aliasOf: `${op.resource} ${op.canonicalAction}`
800
+ };
801
+ });
802
+ }
803
+
804
+ // src/cli/operations.ts
805
+ function operationKey(method, path) {
806
+ return `${method.toUpperCase()} ${path}`;
807
+ }
808
+ var HTTP_METHODS = [
809
+ "get",
810
+ "post",
811
+ "put",
812
+ "patch",
813
+ "delete",
814
+ "options",
815
+ "head",
816
+ "trace"
817
+ ];
818
+ function normalizeParam(p) {
819
+ if (!p || typeof p !== "object")
820
+ return;
821
+ const loc = p.in;
822
+ const name = p.name;
823
+ if (loc !== "path" && loc !== "query" && loc !== "header" && loc !== "cookie") {
824
+ return;
825
+ }
826
+ if (!name)
827
+ return;
828
+ return {
829
+ in: loc,
830
+ name,
831
+ required: Boolean(p.required || loc === "path"),
832
+ description: p.description,
833
+ schema: p.schema
834
+ };
835
+ }
836
+ function mergeParameters(pathParams, opParams) {
837
+ const merged = new Map;
838
+ for (const p of pathParams ?? []) {
839
+ const normalized = normalizeParam(p);
840
+ if (!normalized)
841
+ continue;
842
+ merged.set(`${normalized.in}:${normalized.name}`, normalized);
843
+ }
844
+ for (const p of opParams ?? []) {
845
+ const normalized = normalizeParam(p);
846
+ if (!normalized)
847
+ continue;
848
+ merged.set(`${normalized.in}:${normalized.name}`, normalized);
849
+ }
850
+ return [...merged.values()];
851
+ }
852
+ function normalizeRequestBody(rb) {
853
+ if (!rb)
854
+ return;
855
+ const content = rb.content ?? {};
856
+ const contentTypes = Object.keys(content);
857
+ const schemasByContentType = {};
858
+ for (const contentType of contentTypes) {
859
+ schemasByContentType[contentType] = content[contentType]?.schema;
860
+ }
861
+ return {
862
+ required: Boolean(rb.required),
863
+ contentTypes,
864
+ schemasByContentType
865
+ };
866
+ }
867
+ function indexOperations(doc) {
868
+ const out = [];
869
+ const paths = doc.paths ?? {};
870
+ for (const [path, rawPathItem] of Object.entries(paths)) {
871
+ if (!rawPathItem || typeof rawPathItem !== "object")
872
+ continue;
873
+ const pathItem = rawPathItem;
874
+ for (const method of HTTP_METHODS) {
875
+ const op = pathItem[method];
876
+ if (!op)
877
+ continue;
878
+ const parameters = mergeParameters(pathItem.parameters, op.parameters);
879
+ const normalizedMethod = method.toUpperCase();
880
+ out.push({
881
+ key: operationKey(normalizedMethod, path),
882
+ method: normalizedMethod,
883
+ path,
884
+ operationId: op.operationId,
885
+ tags: op.tags ?? [],
886
+ summary: op.summary,
887
+ description: op.description,
888
+ deprecated: op.deprecated,
889
+ security: op.security ?? doc.security,
890
+ parameters,
891
+ requestBody: normalizeRequestBody(op.requestBody)
892
+ });
893
+ }
894
+ }
895
+ out.sort((a, b) => {
896
+ if (a.path !== b.path)
897
+ return a.path.localeCompare(b.path);
898
+ return a.method.localeCompare(b.method);
899
+ });
900
+ return out;
901
+ }
902
+
903
+ // src/cli/schema.ts
904
+ function buildSchemaOutput(loaded, operations, planned, servers, authSchemes, commands, commandsIndex, capabilities) {
905
+ return {
906
+ schemaVersion: 1,
907
+ openapi: {
908
+ version: loaded.doc.openapi,
909
+ title: loaded.doc.info?.title,
910
+ infoVersion: loaded.doc.info?.version
911
+ },
912
+ spec: {
913
+ id: loaded.id,
914
+ fingerprint: loaded.fingerprint,
915
+ source: loaded.source
916
+ },
917
+ capabilities,
918
+ servers,
919
+ authSchemes,
920
+ operations,
921
+ planned,
922
+ commands,
923
+ commandsIndex
924
+ };
925
+ }
926
+ function toMinimalSchemaOutput(output) {
927
+ return {
928
+ schemaVersion: output.schemaVersion,
929
+ openapi: output.openapi,
930
+ spec: output.spec,
931
+ capabilities: output.capabilities,
932
+ commands: output.commands
933
+ };
934
+ }
935
+
936
+ // src/cli/server.ts
937
+ function extractVariableNames(url) {
938
+ const names = [];
939
+ const re = /\{([^}]+)\}/g;
940
+ while (true) {
941
+ const match = re.exec(url);
942
+ if (!match)
943
+ break;
944
+ names.push(match[1] ?? "");
945
+ }
946
+ return names.map((n) => n.trim()).filter(Boolean);
947
+ }
948
+ function listServers(doc) {
949
+ const servers = doc.servers ?? [];
950
+ const out = [];
951
+ for (const raw of servers) {
952
+ const s = raw;
953
+ if (!s || typeof s !== "object")
954
+ continue;
955
+ if (typeof s.url !== "string")
956
+ continue;
957
+ const variableNames = extractVariableNames(s.url);
958
+ const variables = [];
959
+ const rawVars = s.variables && typeof s.variables === "object" && !Array.isArray(s.variables) ? s.variables : {};
960
+ for (const name of variableNames) {
961
+ const v = rawVars[name];
962
+ const def = v?.default;
963
+ const desc = v?.description;
964
+ variables.push({
965
+ name,
966
+ default: typeof def === "string" ? def : undefined,
967
+ enum: getSchemaEnumStrings(v),
968
+ description: typeof desc === "string" ? desc : undefined
969
+ });
970
+ }
971
+ out.push({
972
+ url: s.url,
973
+ description: typeof s.description === "string" ? s.description : undefined,
974
+ variables,
975
+ variableNames
976
+ });
977
+ }
978
+ return out;
979
+ }
980
+
981
+ // src/cli/spec-loader.ts
982
+ import SwaggerParser from "@apidevtools/swagger-parser";
983
+
984
+ // src/cli/crypto.ts
985
+ async function sha256Hex(text) {
986
+ const data = new TextEncoder().encode(text);
987
+ const hash = await crypto.subtle.digest("SHA-256", data);
988
+ const bytes = new Uint8Array(hash);
989
+ let out = "";
990
+ for (const b of bytes)
991
+ out += b.toString(16).padStart(2, "0");
992
+ return out;
993
+ }
994
+
995
+ // src/cli/spec-id.ts
996
+ function getSpecId(loaded) {
997
+ const title = loaded.doc.info?.title;
998
+ const fromTitle = title ? kebabCase(title) : "";
999
+ if (fromTitle)
1000
+ return fromTitle;
1001
+ return loaded.fingerprint.slice(0, 12);
1002
+ }
1003
+
1004
+ // src/cli/stable-json.ts
1005
+ function stableStringify(value, options) {
1006
+ const visiting = new WeakSet;
1007
+ return JSON.stringify(sort(value, visiting), null, options?.space);
1008
+ }
1009
+ function sort(value, visiting) {
1010
+ if (value === null)
1011
+ return null;
1012
+ if (Array.isArray(value)) {
1013
+ if (visiting.has(value))
1014
+ return { __specli_circular: true };
1015
+ visiting.add(value);
1016
+ const out = value.map((v) => sort(v, visiting));
1017
+ visiting.delete(value);
1018
+ return out;
1019
+ }
1020
+ if (typeof value === "object") {
1021
+ if (visiting.has(value))
1022
+ return { __specli_circular: true };
1023
+ visiting.add(value);
1024
+ const obj = value;
1025
+ const out = {};
1026
+ for (const key of Object.keys(obj).sort()) {
1027
+ out[key] = sort(obj[key], visiting);
1028
+ }
1029
+ visiting.delete(value);
1030
+ return out;
1031
+ }
1032
+ return value;
1033
+ }
1034
+
1035
+ // src/cli/spec-loader.ts
1036
+ function isProbablyUrl(input) {
1037
+ return /^https?:\/\//i.test(input);
1038
+ }
1039
+ function parseSpecText(text) {
1040
+ const trimmed = text.trimStart();
1041
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
1042
+ return JSON.parse(text);
1043
+ }
1044
+ return parseYamlContent(text);
1045
+ }
1046
+ async function loadSpec(options) {
1047
+ const { spec, embeddedSpecText } = options;
1048
+ let source;
1049
+ let inputForParser;
1050
+ if (typeof embeddedSpecText === "string") {
1051
+ source = "embedded";
1052
+ inputForParser = parseSpecText(embeddedSpecText);
1053
+ } else if (spec) {
1054
+ source = isProbablyUrl(spec) ? "url" : "file";
1055
+ inputForParser = spec;
1056
+ } else {
1057
+ throw new Error("Missing spec. Provide --spec <url|path> or build with an embedded spec.");
1058
+ }
1059
+ const doc = await SwaggerParser.dereference(inputForParser);
1060
+ if (!doc || typeof doc !== "object" || typeof doc.openapi !== "string") {
1061
+ throw new Error("Loaded spec is not a valid OpenAPI document");
1062
+ }
1063
+ const fingerprint = await sha256Hex(stableStringify(doc));
1064
+ const id = getSpecId({ doc, fingerprint });
1065
+ return { source, id, fingerprint, doc };
1066
+ }
1067
+
1068
+ // src/cli/runtime/context.ts
1069
+ async function buildRuntimeContext(options) {
1070
+ const loaded = await loadSpec({
1071
+ spec: options.spec,
1072
+ embeddedSpecText: options.embeddedSpecText
1073
+ });
1074
+ const operations = indexOperations(loaded.doc);
1075
+ const servers = listServers(loaded.doc);
1076
+ const authSchemes = listAuthSchemes(loaded.doc);
1077
+ const planned = planOperations(operations);
1078
+ const commands = buildCommandModel(planned, {
1079
+ specId: loaded.id,
1080
+ globalSecurity: loaded.doc.security,
1081
+ authSchemes
1082
+ });
1083
+ const commandsIndex = buildCommandsIndex(commands);
1084
+ const capabilities = deriveCapabilities({
1085
+ doc: loaded.doc,
1086
+ servers,
1087
+ authSchemes,
1088
+ operations,
1089
+ commands
1090
+ });
1091
+ const schema = buildSchemaOutput(loaded, operations, planned, servers, authSchemes, commands, commandsIndex, capabilities);
1092
+ return {
1093
+ loaded,
1094
+ operations,
1095
+ servers,
1096
+ authSchemes,
1097
+ planned,
1098
+ commands,
1099
+ commandsIndex,
1100
+ capabilities,
1101
+ schema
1102
+ };
1103
+ }
1104
+
1105
+ // src/cli/runtime/generated.ts
1106
+ import { Command } from "commander";
1107
+
1108
+ // src/cli/runtime/auth/resolve.ts
1109
+ var BEARER_COMPATIBLE_KINDS = new Set([
1110
+ "http-bearer",
1111
+ "oauth2",
1112
+ "openIdConnect"
1113
+ ]);
1114
+ function resolveAuthScheme(authSchemes, required, inputs) {
1115
+ if (inputs.flagAuthScheme)
1116
+ return inputs.flagAuthScheme;
1117
+ if (inputs.profileAuthScheme && authSchemes.some((s) => s.key === inputs.profileAuthScheme)) {
1118
+ return inputs.profileAuthScheme;
1119
+ }
1120
+ if (inputs.embeddedAuthScheme && authSchemes.some((s) => s.key === inputs.embeddedAuthScheme)) {
1121
+ return inputs.embeddedAuthScheme;
1122
+ }
1123
+ const alts = required.alternatives;
1124
+ if (alts.length === 1 && alts[0]?.length === 1)
1125
+ return alts[0][0]?.key;
1126
+ if (authSchemes.length === 1)
1127
+ return authSchemes[0]?.key;
1128
+ if (inputs.hasStoredToken && alts.length > 0) {
1129
+ for (const alt of alts) {
1130
+ if (alt.length !== 1)
1131
+ continue;
1132
+ const key = alt[0]?.key;
1133
+ const scheme = authSchemes.find((s) => s.key === key);
1134
+ if (scheme && BEARER_COMPATIBLE_KINDS.has(scheme.kind)) {
1135
+ return key;
1136
+ }
1137
+ }
1138
+ }
1139
+ return;
1140
+ }
1141
+
1142
+ // src/cli/runtime/profile/secrets.ts
1143
+ var bunLiteral = "bun";
1144
+ function secretServiceForSpec(specId) {
1145
+ return `specli:${specId}`;
1146
+ }
1147
+ function tokenSecretKey(specId, profile) {
1148
+ return {
1149
+ service: secretServiceForSpec(specId),
1150
+ name: `profile:${profile}:token`
1151
+ };
1152
+ }
1153
+ async function setToken(specId, profile, token) {
1154
+ if (!isBun) {
1155
+ console.warn("Warning: Secure token storage requires Bun. Token will not be persisted.");
1156
+ console.warn("Use --bearer-token <token> flag instead when running with Node.js.");
1157
+ return;
1158
+ }
1159
+ const { secrets } = await import(bunLiteral);
1160
+ const key = tokenSecretKey(specId, profile);
1161
+ await secrets.set({ service: key.service, name: key.name, value: token });
1162
+ }
1163
+ async function getToken(specId, profile) {
1164
+ if (!isBun) {
1165
+ return null;
1166
+ }
1167
+ const { secrets } = await import(bunLiteral);
1168
+ const key = tokenSecretKey(specId, profile);
1169
+ return await secrets.get({ service: key.service, name: key.name });
1170
+ }
1171
+ async function deleteToken(specId, profile) {
1172
+ if (!isBun) {
1173
+ console.warn("Warning: Secure token storage requires Bun. No token to delete.");
1174
+ return false;
1175
+ }
1176
+ const { secrets } = await import(bunLiteral);
1177
+ const key = tokenSecretKey(specId, profile);
1178
+ return await secrets.delete({ service: key.service, name: key.name });
1179
+ }
1180
+
1181
+ // src/cli/runtime/profile/store.ts
1182
+ function configDir() {
1183
+ const home = process.env.HOME;
1184
+ if (!home)
1185
+ throw new Error("Missing HOME env var");
1186
+ return `${home}/.config/specli`;
1187
+ }
1188
+ function configPathJson() {
1189
+ return `${configDir()}/profiles.json`;
1190
+ }
1191
+ function configPathYaml() {
1192
+ return `${configDir()}/profiles.yaml`;
1193
+ }
1194
+ async function readProfiles() {
1195
+ const jsonPath = configPathJson();
1196
+ const yamlPath = configPathYaml();
1197
+ const jsonExists = await fileExists(jsonPath);
1198
+ const yamlExists = await fileExists(yamlPath);
1199
+ const filePath = jsonExists ? jsonPath : yamlExists ? yamlPath : null;
1200
+ if (!filePath)
1201
+ return { profiles: [] };
1202
+ const text = await readFileText(filePath);
1203
+ let parsed;
1204
+ try {
1205
+ parsed = parseYamlContent(text);
1206
+ } catch {
1207
+ parsed = JSON.parse(text);
1208
+ }
1209
+ const obj = parsed && typeof parsed === "object" ? parsed : {};
1210
+ const profiles = Array.isArray(obj.profiles) ? obj.profiles : [];
1211
+ return {
1212
+ profiles: profiles.filter(Boolean),
1213
+ defaultProfile: typeof obj.defaultProfile === "string" ? obj.defaultProfile : undefined
1214
+ };
1215
+ }
1216
+ async function writeProfiles(data) {
1217
+ const dir = configDir();
1218
+ await mkdirp(dir);
1219
+ await writeFileText(configPathJson(), JSON.stringify(data, null, 2));
1220
+ }
1221
+ function getProfile(data, name) {
1222
+ const wanted = name ?? data.defaultProfile;
1223
+ if (!wanted)
1224
+ return;
1225
+ return data.profiles.find((p) => p?.name === wanted);
1226
+ }
1227
+ function upsertProfile(data, profile) {
1228
+ const profiles = data.profiles.filter((p) => p.name !== profile.name);
1229
+ profiles.push(profile);
1230
+ profiles.sort((a, b) => a.name.localeCompare(b.name));
1231
+ return { ...data, profiles };
1232
+ }
1233
+
1234
+ // src/cli/runtime/template.ts
1235
+ function extractTemplateVars(template) {
1236
+ const out = [];
1237
+ const re = /\{([^}]+)\}/g;
1238
+ while (true) {
1239
+ const match = re.exec(template);
1240
+ if (!match)
1241
+ break;
1242
+ out.push((match[1] ?? "").trim());
1243
+ }
1244
+ return out.filter(Boolean);
1245
+ }
1246
+ function applyTemplate(template, vars, options) {
1247
+ const encode = options?.encode ?? false;
1248
+ return template.replace(/\{([^}]+)\}/g, (_, rawName) => {
1249
+ const name = String(rawName).trim();
1250
+ const value = vars[name];
1251
+ if (typeof value !== "string") {
1252
+ throw new Error(`Missing template variable: ${name}`);
1253
+ }
1254
+ return encode ? encodeURIComponent(value) : value;
1255
+ });
1256
+ }
1257
+
1258
+ // src/cli/runtime/server-url.ts
1259
+ function resolveServerUrl(input) {
1260
+ const base = input.serverOverride || input.servers[0]?.url;
1261
+ if (!base) {
1262
+ throw new Error("No server URL found. Provide --server <url> or define servers in the OpenAPI spec.");
1263
+ }
1264
+ const names = extractTemplateVars(base);
1265
+ if (!names.length)
1266
+ return base;
1267
+ const vars = {};
1268
+ for (const name of names) {
1269
+ const provided = input.serverVars[name];
1270
+ if (typeof provided === "string") {
1271
+ vars[name] = provided;
1272
+ continue;
1273
+ }
1274
+ const match = input.servers.find((s) => s.url === base);
1275
+ const v = match?.variables.find((x) => x.name === name);
1276
+ if (typeof v?.default === "string") {
1277
+ vars[name] = v.default;
1278
+ continue;
1279
+ }
1280
+ throw new Error(`Missing server variable '${name}'. Provide --server-var ${name}=...`);
1281
+ }
1282
+ return applyTemplate(base, vars);
1283
+ }
1284
+
1285
+ // src/cli/runtime/validate/ajv.ts
1286
+ import Ajv from "ajv";
1287
+ import addFormats from "ajv-formats";
1288
+ function createAjv() {
1289
+ const ajv = new Ajv({
1290
+ allErrors: true,
1291
+ strict: false,
1292
+ coerceTypes: false
1293
+ });
1294
+ addFormats(ajv);
1295
+ return ajv;
1296
+ }
1297
+ // src/cli/runtime/validate/coerce.ts
1298
+ import { InvalidArgumentError } from "commander";
1299
+ function coerceValue(raw, type) {
1300
+ if (type === "string" || type === "unknown")
1301
+ return raw;
1302
+ if (type === "boolean") {
1303
+ if (raw === "true")
1304
+ return true;
1305
+ if (raw === "false")
1306
+ return false;
1307
+ throw new InvalidArgumentError(`Expected boolean, got '${raw}'`);
1308
+ }
1309
+ if (type === "integer") {
1310
+ const n = Number.parseInt(raw, 10);
1311
+ if (!Number.isFinite(n))
1312
+ throw new InvalidArgumentError(`Expected integer, got '${raw}'`);
1313
+ return n;
1314
+ }
1315
+ if (type === "number") {
1316
+ const n = Number(raw);
1317
+ if (!Number.isFinite(n))
1318
+ throw new InvalidArgumentError(`Expected number, got '${raw}'`);
1319
+ return n;
1320
+ }
1321
+ if (type === "object") {
1322
+ try {
1323
+ return JSON.parse(raw);
1324
+ } catch {
1325
+ throw new InvalidArgumentError(`Expected JSON object, got '${raw}'. Use --data/--file for complex bodies.`);
1326
+ }
1327
+ }
1328
+ if (type === "array") {
1329
+ return coerceArrayInput(raw, "string");
1330
+ }
1331
+ return raw;
1332
+ }
1333
+ function coerceArrayInput(raw, itemType) {
1334
+ const trimmed = raw.trim();
1335
+ if (!trimmed)
1336
+ return [];
1337
+ if (trimmed.startsWith("[")) {
1338
+ let parsed;
1339
+ try {
1340
+ parsed = JSON.parse(trimmed);
1341
+ } catch {
1342
+ throw new InvalidArgumentError(`Expected JSON array, got '${raw}'`);
1343
+ }
1344
+ if (!Array.isArray(parsed)) {
1345
+ throw new InvalidArgumentError(`Expected JSON array, got '${raw}'`);
1346
+ }
1347
+ return parsed.map((v) => coerceValue(String(v), itemType));
1348
+ }
1349
+ return trimmed.split(",").map((s) => s.trim()).filter(Boolean).map((s) => coerceValue(s, itemType));
1350
+ }
1351
+ // src/cli/runtime/validate/error.ts
1352
+ function formatAjvErrors(errors) {
1353
+ if (!errors?.length)
1354
+ return "Invalid input";
1355
+ return errors.map((e) => {
1356
+ const path = e.instancePath || e.schemaPath || "";
1357
+ if (e.keyword === "required" && e.params && typeof e.params === "object" && "missingProperty" in e.params) {
1358
+ const missing = String(e.params.missingProperty);
1359
+ const where = e.instancePath || "/";
1360
+ return `${where} missing required property '${missing}'`.trim();
1361
+ }
1362
+ const msg = e.message || "invalid";
1363
+ return `${path} ${msg}`.trim();
1364
+ }).join(`
1365
+ `);
1366
+ }
1367
+ // src/cli/runtime/validate/schema.ts
1368
+ function deriveValidationSchemas(action) {
1369
+ const query = { type: "object", properties: {}, required: [] };
1370
+ const header = { type: "object", properties: {}, required: [] };
1371
+ const cookie = { type: "object", properties: {}, required: [] };
1372
+ for (const p of action.params) {
1373
+ if (p.kind !== "flag")
1374
+ continue;
1375
+ const target = p.in === "query" ? query : p.in === "header" ? header : p.in === "cookie" ? cookie : undefined;
1376
+ if (!target)
1377
+ continue;
1378
+ const schema = p.schema ?? (p.type === "unknown" ? {} : { type: p.type });
1379
+ target.properties[p.name] = schema;
1380
+ if (p.required) {
1381
+ if (!target.required)
1382
+ target.required = [];
1383
+ target.required.push(p.name);
1384
+ }
1385
+ }
1386
+ if (!query.required?.length)
1387
+ delete query.required;
1388
+ if (!header.required?.length)
1389
+ delete header.required;
1390
+ if (!cookie.required?.length)
1391
+ delete cookie.required;
1392
+ return {
1393
+ querySchema: Object.keys(query.properties).length ? query : undefined,
1394
+ headerSchema: Object.keys(header.properties).length ? header : undefined,
1395
+ cookieSchema: Object.keys(cookie.properties).length ? cookie : undefined
1396
+ };
1397
+ }
1398
+ // src/cli/runtime/request.ts
1399
+ function parseKeyValuePairs(pairs) {
1400
+ const out = {};
1401
+ for (const pair of pairs ?? []) {
1402
+ const idx = pair.indexOf("=");
1403
+ if (idx === -1)
1404
+ throw new Error(`Invalid pair '${pair}', expected name=value`);
1405
+ const name = pair.slice(0, idx).trim();
1406
+ const value = pair.slice(idx + 1).trim();
1407
+ if (!name)
1408
+ throw new Error(`Invalid pair '${pair}', missing name`);
1409
+ out[name] = value;
1410
+ }
1411
+ return out;
1412
+ }
1413
+ function pickAuthSchemeKey(action, globals) {
1414
+ if (globals.auth)
1415
+ return globals.auth;
1416
+ const req = action.auth.alternatives;
1417
+ if (req.length === 1 && req[0]?.length === 1) {
1418
+ return req[0][0]?.key;
1419
+ }
1420
+ return;
1421
+ }
1422
+ function applyAuth(headers, url, action, globals, authSchemes) {
1423
+ const schemeKey = pickAuthSchemeKey(action, globals);
1424
+ if (!schemeKey)
1425
+ return { headers, url };
1426
+ const scheme = authSchemes.find((s) => s.key === schemeKey);
1427
+ if (!scheme) {
1428
+ throw new Error(`Unknown auth scheme '${schemeKey}'. Available: ${authSchemes.map((s) => s.key).join(", ")}`);
1429
+ }
1430
+ if (scheme.kind === "http-bearer" || scheme.kind === "oauth2" || scheme.kind === "openIdConnect") {
1431
+ const token = globals.bearerToken ?? globals.oauthToken;
1432
+ if (!token)
1433
+ throw new Error("Missing token. Provide --bearer-token <token>.");
1434
+ headers.set("Authorization", `Bearer ${token}`);
1435
+ return { headers, url };
1436
+ }
1437
+ if (scheme.kind === "http-basic") {
1438
+ if (!globals.username)
1439
+ throw new Error("Missing --username for basic auth");
1440
+ if (!globals.password)
1441
+ throw new Error("Missing --password for basic auth");
1442
+ const raw = `${globals.username}:${globals.password}`;
1443
+ const encoded = Buffer.from(raw, "utf8").toString("base64");
1444
+ headers.set("Authorization", `Basic ${encoded}`);
1445
+ return { headers, url };
1446
+ }
1447
+ if (scheme.kind === "api-key") {
1448
+ if (!scheme.name)
1449
+ throw new Error(`apiKey scheme '${scheme.key}' missing name`);
1450
+ if (!scheme.in)
1451
+ throw new Error(`apiKey scheme '${scheme.key}' missing location`);
1452
+ if (!globals.apiKey)
1453
+ throw new Error("Missing --api-key for apiKey auth");
1454
+ if (scheme.in === "header") {
1455
+ headers.set(scheme.name, globals.apiKey);
1456
+ }
1457
+ if (scheme.in === "query") {
1458
+ url.searchParams.set(scheme.name, globals.apiKey);
1459
+ }
1460
+ if (scheme.in === "cookie") {
1461
+ const existing = headers.get("Cookie");
1462
+ const part = `${scheme.name}=${globals.apiKey}`;
1463
+ headers.set("Cookie", existing ? `${existing}; ${part}` : part);
1464
+ }
1465
+ return { headers, url };
1466
+ }
1467
+ return { headers, url };
1468
+ }
1469
+ async function buildRequest(input) {
1470
+ const defaultProfileName = "default";
1471
+ const profilesFile = await readProfiles();
1472
+ const profile = getProfile(profilesFile, defaultProfileName);
1473
+ const embedded = input.embeddedDefaults;
1474
+ const embeddedServerVars = parseKeyValuePairs(embedded?.serverVars);
1475
+ const cliServerVars = parseKeyValuePairs(input.globals.serverVar);
1476
+ const serverVars = { ...embeddedServerVars, ...cliServerVars };
1477
+ const serverUrl = resolveServerUrl({
1478
+ serverOverride: input.globals.server ?? profile?.server ?? embedded?.server,
1479
+ servers: input.servers,
1480
+ serverVars
1481
+ });
1482
+ const pathVars = {};
1483
+ for (let i = 0;i < input.action.positionals.length; i++) {
1484
+ const pos = input.action.positionals[i];
1485
+ const raw = input.action.pathArgs[i];
1486
+ const value = input.positionalValues[i];
1487
+ if (typeof raw === "string" && typeof value === "string") {
1488
+ pathVars[raw] = value;
1489
+ }
1490
+ if (pos?.name && typeof value === "string") {
1491
+ pathVars[pos.name] = value;
1492
+ }
1493
+ }
1494
+ const path = applyTemplate(input.action.path, pathVars, { encode: true });
1495
+ const baseUrl = serverUrl.endsWith("/") ? serverUrl : `${serverUrl}/`;
1496
+ const relativePath = path.startsWith("/") ? path.slice(1) : path;
1497
+ const url = new URL(relativePath, baseUrl);
1498
+ const headers = new Headers;
1499
+ const queryValues = {};
1500
+ const headerValues = {};
1501
+ const cookieValues = {};
1502
+ for (const p of input.action.params) {
1503
+ if (p.kind !== "flag")
1504
+ continue;
1505
+ const optValue = input.flagValues[optionKeyFromFlag(p.flag)];
1506
+ if (typeof optValue === "undefined")
1507
+ continue;
1508
+ if (p.in === "query") {
1509
+ queryValues[p.name] = optValue;
1510
+ }
1511
+ if (p.in === "header") {
1512
+ headerValues[p.name] = optValue;
1513
+ }
1514
+ if (p.in === "cookie") {
1515
+ cookieValues[p.name] = optValue;
1516
+ }
1517
+ }
1518
+ const schemas = deriveValidationSchemas(input.action);
1519
+ const ajv2 = createAjv();
1520
+ if (schemas.querySchema) {
1521
+ const validate = ajv2.compile(schemas.querySchema);
1522
+ if (!validate(queryValues)) {
1523
+ throw new Error(formatAjvErrors(validate.errors));
1524
+ }
1525
+ }
1526
+ if (schemas.headerSchema) {
1527
+ const validate = ajv2.compile(schemas.headerSchema);
1528
+ if (!validate(headerValues)) {
1529
+ throw new Error(formatAjvErrors(validate.errors));
1530
+ }
1531
+ }
1532
+ if (schemas.cookieSchema) {
1533
+ const validate = ajv2.compile(schemas.cookieSchema);
1534
+ if (!validate(cookieValues)) {
1535
+ throw new Error(formatAjvErrors(validate.errors));
1536
+ }
1537
+ }
1538
+ for (const [name, value] of Object.entries(queryValues)) {
1539
+ if (Array.isArray(value)) {
1540
+ for (const item of value) {
1541
+ url.searchParams.append(name, String(item));
1542
+ }
1543
+ continue;
1544
+ }
1545
+ url.searchParams.set(name, String(value));
1546
+ }
1547
+ for (const [name, value] of Object.entries(headerValues)) {
1548
+ headers.set(name, String(value));
1549
+ }
1550
+ for (const [name, value] of Object.entries(cookieValues)) {
1551
+ const existing = headers.get("Cookie");
1552
+ const part = `${name}=${String(value)}`;
1553
+ headers.set("Cookie", existing ? `${existing}; ${part}` : part);
1554
+ }
1555
+ let body;
1556
+ if (input.action.requestBody) {
1557
+ const bodyFlagDefs = input.bodyFlagDefs ?? [];
1558
+ const hasBodyFlags = bodyFlagDefs.some((def) => {
1559
+ const dotKey = def.path.join(".");
1560
+ return input.flagValues[dotKey] !== undefined;
1561
+ });
1562
+ const contentType = input.action.requestBody.preferredContentType;
1563
+ if (contentType)
1564
+ headers.set("Content-Type", contentType);
1565
+ const schema2 = input.action.requestBodySchema;
1566
+ const requiredFields = bodyFlagDefs.filter((d) => d.required);
1567
+ if (!hasBodyFlags) {
1568
+ if (requiredFields.length > 0) {
1569
+ const flagList = requiredFields.map((d) => `--${d.path.join(".")}`);
1570
+ throw new Error(`Required: ${flagList.join(", ")}`);
1571
+ }
1572
+ if (input.action.requestBody.required) {
1573
+ body = "{}";
1574
+ }
1575
+ } else {
1576
+ if (!contentType?.includes("json")) {
1577
+ throw new Error("Body field flags are only supported for JSON request bodies.");
1578
+ }
1579
+ const { findMissingRequired: findMissingRequired2, parseDotNotationFlags: parseDotNotationFlags2 } = await Promise.resolve().then(() => exports_body_flags);
1580
+ const missing = findMissingRequired2(input.flagValues, bodyFlagDefs);
1581
+ if (missing.length > 0) {
1582
+ const missingFlags = missing.map((m) => `--${m}`).join(", ");
1583
+ throw new Error(`Missing required fields: ${missingFlags}`);
1584
+ }
1585
+ const built = parseDotNotationFlags2(input.flagValues, bodyFlagDefs);
1586
+ if (schema2) {
1587
+ const validate = ajv2.compile(schema2);
1588
+ if (!validate(built)) {
1589
+ throw new Error(formatAjvErrors(validate.errors));
1590
+ }
1591
+ }
1592
+ body = JSON.stringify(built);
1593
+ }
1594
+ }
1595
+ const storedToken = profile?.name ? await getToken(input.specId, profile.name) : null;
1596
+ const resolvedAuthScheme = resolveAuthScheme(input.authSchemes, input.action.auth, {
1597
+ flagAuthScheme: input.globals.auth,
1598
+ profileAuthScheme: profile?.authScheme,
1599
+ embeddedAuthScheme: embedded?.auth,
1600
+ hasStoredToken: Boolean(storedToken)
1601
+ });
1602
+ const tokenFromProfile = resolvedAuthScheme ? storedToken : null;
1603
+ const globalsWithProfileAuth = {
1604
+ ...input.globals,
1605
+ auth: resolvedAuthScheme,
1606
+ bearerToken: input.globals.bearerToken ?? input.globals.oauthToken ?? tokenFromProfile ?? undefined
1607
+ };
1608
+ const final = applyAuth(headers, url, input.action, globalsWithProfileAuth, input.authSchemes);
1609
+ const req = new Request(final.url.toString(), {
1610
+ method: input.action.method,
1611
+ headers: final.headers,
1612
+ body
1613
+ });
1614
+ const curl = buildCurl(req, body);
1615
+ return { request: req, curl };
1616
+ }
1617
+ function buildCurl(req, body) {
1618
+ const parts = ["curl", "-sS", "-X", req.method];
1619
+ for (const [k, v] of req.headers.entries()) {
1620
+ parts.push("-H", shellQuote(`${k}: ${v}`));
1621
+ }
1622
+ if (typeof body === "string") {
1623
+ parts.push("--data", shellQuote(body));
1624
+ }
1625
+ parts.push(shellQuote(req.url));
1626
+ return parts.join(" ");
1627
+ }
1628
+ function shellQuote(value) {
1629
+ return `'${value.replace(/'/g, `'\\''`)}'`;
1630
+ }
1631
+ function optionKeyFromFlag(flag) {
1632
+ const name = flag.replace(/^--/, "");
1633
+ return name.replace(/-([a-z])/g, (_, c) => String(c).toUpperCase());
1634
+ }
1635
+
1636
+ // src/cli/runtime/execute.ts
1637
+ function formatError(message, resourceName, actionName) {
1638
+ const helpCmd = resourceName ? `${resourceName} ${actionName} --help` : `${actionName} --help`;
1639
+ return `${message}
1640
+
1641
+ Run '${helpCmd}' to see available options.`;
1642
+ }
1643
+ async function execute(input) {
1644
+ const { request, curl } = await buildRequest({
1645
+ specId: input.specId,
1646
+ action: input.action,
1647
+ positionalValues: input.positionalValues,
1648
+ flagValues: input.flagValues,
1649
+ globals: input.globals,
1650
+ servers: input.servers,
1651
+ authSchemes: input.authSchemes,
1652
+ embeddedDefaults: input.embeddedDefaults,
1653
+ bodyFlagDefs: input.bodyFlagDefs
1654
+ });
1655
+ const res = await fetch(request);
1656
+ const contentType = res.headers.get("content-type") ?? "";
1657
+ const text = await res.text();
1658
+ let body = text;
1659
+ if (contentType.includes("json") && text) {
1660
+ try {
1661
+ body = JSON.parse(text);
1662
+ } catch {}
1663
+ }
1664
+ return {
1665
+ ok: res.ok,
1666
+ status: res.status,
1667
+ body,
1668
+ curl
1669
+ };
1670
+ }
1671
+ async function executeAction(input) {
1672
+ const actionName = input.action.action;
1673
+ const resourceName = input.resourceName;
1674
+ try {
1675
+ if (input.globals.curl) {
1676
+ const { curl } = await buildRequest({
1677
+ specId: input.specId,
1678
+ action: input.action,
1679
+ positionalValues: input.positionalValues,
1680
+ flagValues: input.flagValues,
1681
+ globals: input.globals,
1682
+ servers: input.servers,
1683
+ authSchemes: input.authSchemes,
1684
+ embeddedDefaults: input.embeddedDefaults,
1685
+ bodyFlagDefs: input.bodyFlagDefs
1686
+ });
1687
+ process.stdout.write(`${curl}
1688
+ `);
1689
+ return;
1690
+ }
1691
+ const result = await execute(input);
1692
+ if (!result.ok) {
1693
+ if (input.globals.json) {
1694
+ process.stdout.write(`${JSON.stringify({ status: result.status, body: result.body })}
1695
+ `);
1696
+ } else {
1697
+ process.stderr.write(`HTTP ${result.status}
1698
+ `);
1699
+ process.stderr.write(`${typeof result.body === "string" ? result.body : JSON.stringify(result.body, null, 2)}
1700
+ `);
1701
+ }
1702
+ process.exitCode = 1;
1703
+ return;
1704
+ }
1705
+ if (input.globals.json) {
1706
+ process.stdout.write(`${JSON.stringify(result.body)}
1707
+ `);
1708
+ return;
1709
+ }
1710
+ if (typeof result.body === "string") {
1711
+ process.stdout.write(result.body);
1712
+ if (!result.body.endsWith(`
1713
+ `))
1714
+ process.stdout.write(`
1715
+ `);
1716
+ } else {
1717
+ process.stdout.write(`${JSON.stringify(result.body, null, 2)}
1718
+ `);
1719
+ }
1720
+ } catch (err) {
1721
+ const rawMessage = err instanceof Error ? err.message : String(err);
1722
+ const message = formatError(rawMessage, resourceName, actionName);
1723
+ if (input.globals.json) {
1724
+ process.stdout.write(`${JSON.stringify({ error: rawMessage })}
1725
+ `);
1726
+ } else {
1727
+ process.stderr.write(`error: ${message}
1728
+ `);
1729
+ }
1730
+ process.exitCode = 1;
1731
+ }
1732
+ }
1733
+
1734
+ // src/cli/runtime/generated.ts
1735
+ function formatCustomHelp(cmd, action, operationFlags, bodyFlagDefs) {
1736
+ const lines = [];
1737
+ const cmdName = cmd.name();
1738
+ const parentName = cmd.parent?.name() ?? "";
1739
+ const fullCmd = parentName ? `${parentName} ${cmdName}` : cmdName;
1740
+ const positionals = action.positionals.map((p) => `<${p.name}>`).join(" ");
1741
+ const usageSuffix = positionals ? ` ${positionals}` : "";
1742
+ lines.push(`Usage: ${fullCmd}${usageSuffix} [options]`);
1743
+ lines.push("");
1744
+ const desc = action.summary ?? action.description ?? `${action.method} ${action.path}`;
1745
+ lines.push(desc);
1746
+ lines.push("");
1747
+ const requiredOpts = [];
1748
+ const optionalOpts = [];
1749
+ const formatOpt = (flag, type, desc2, required) => {
1750
+ const typeStr = type === "boolean" ? "" : ` <${type}>`;
1751
+ const reqMarker = required ? " (required)" : "";
1752
+ return ` ${flag}${typeStr}${reqMarker}
1753
+ ${desc2}`;
1754
+ };
1755
+ for (const f of operationFlags) {
1756
+ const type = f.type === "array" ? `${f.itemType ?? "string"}[]` : f.type;
1757
+ const line = formatOpt(f.flag, type, f.description ?? `${f.in} parameter`, f.required);
1758
+ if (f.required) {
1759
+ requiredOpts.push(line);
1760
+ } else {
1761
+ optionalOpts.push(line);
1762
+ }
1763
+ }
1764
+ for (const def of bodyFlagDefs) {
1765
+ const line = formatOpt(def.flag, def.type, def.description, def.required);
1766
+ if (def.required) {
1767
+ requiredOpts.push(line);
1768
+ } else {
1769
+ optionalOpts.push(line);
1770
+ }
1771
+ }
1772
+ if (requiredOpts.length > 0) {
1773
+ lines.push("Required:");
1774
+ lines.push(...requiredOpts);
1775
+ lines.push("");
1776
+ }
1777
+ if (optionalOpts.length > 0) {
1778
+ lines.push("Options:");
1779
+ lines.push(...optionalOpts);
1780
+ lines.push("");
1781
+ }
1782
+ lines.push("Global:");
1783
+ lines.push(` --curl
1784
+ Print curl command instead of executing`);
1785
+ lines.push(` --json
1786
+ Output response as JSON`);
1787
+ lines.push(` --server <url>
1788
+ Override the API server URL`);
1789
+ lines.push(` --bearer-token <token>
1790
+ Provide auth token (or use 'login' command)`);
1791
+ lines.push(` -h, --help
1792
+ Show this help message`);
1793
+ lines.push("");
1794
+ return lines.join(`
1795
+ `);
1796
+ }
1797
+ function addGeneratedCommands(program, context) {
1798
+ for (const resource of context.commands.resources) {
1799
+ const resourceCmd = program.command(resource.resource).description(`Operations for ${resource.resource}`);
1800
+ for (const action of resource.actions) {
1801
+ const cmd = resourceCmd.command(action.action);
1802
+ cmd.description(action.summary ?? action.description ?? `${action.method} ${action.path}`);
1803
+ for (const pos of action.positionals) {
1804
+ cmd.argument(`<${pos.name}>`, pos.description);
1805
+ }
1806
+ for (const flag of action.flags) {
1807
+ const opt = flag.flag;
1808
+ const desc = flag.description ?? `${flag.in} parameter`;
1809
+ if (flag.type === "boolean") {
1810
+ cmd.option(opt, desc);
1811
+ continue;
1812
+ }
1813
+ const isArray = flag.type === "array";
1814
+ const itemType = flag.itemType ?? "string";
1815
+ const flagType = isArray ? itemType : flag.type;
1816
+ const parser = (raw) => coerceValue(raw, flagType);
1817
+ if (isArray) {
1818
+ const key2 = `${opt} <value>`;
1819
+ cmd.option(key2, desc, (value, prev) => {
1820
+ const next = [...prev ?? []];
1821
+ const items = coerceArrayInput(value, itemType);
1822
+ for (const item of items) {
1823
+ next.push(item);
1824
+ }
1825
+ return next;
1826
+ });
1827
+ continue;
1828
+ }
1829
+ const key = `${opt} <value>`;
1830
+ if (flag.required)
1831
+ cmd.requiredOption(key, desc, parser);
1832
+ else
1833
+ cmd.option(key, desc, parser);
1834
+ }
1835
+ const operationFlagSet = new Set(action.flags.map((f) => f.flag));
1836
+ const reservedFlags = new Set([...operationFlagSet, "--curl"]);
1837
+ if (!operationFlagSet.has("--curl")) {
1838
+ cmd.option("--curl", "Print curl command without sending");
1839
+ }
1840
+ let bodyFlagDefs = [];
1841
+ if (action.requestBody) {
1842
+ bodyFlagDefs = generateBodyFlags(action.requestBodySchema, reservedFlags);
1843
+ for (const def of bodyFlagDefs) {
1844
+ if (def.type === "boolean") {
1845
+ cmd.option(def.flag, def.description);
1846
+ } else {
1847
+ cmd.option(`${def.flag} <value>`, def.description);
1848
+ }
1849
+ }
1850
+ }
1851
+ cmd.configureHelp({
1852
+ formatHelp: () => formatCustomHelp(cmd, action, action.flags, bodyFlagDefs)
1853
+ });
1854
+ cmd.action(async (...args) => {
1855
+ const command = args[args.length - 1];
1856
+ const positionalValues = args.slice(0, -1).map((v) => String(v));
1857
+ if (!(command instanceof Command)) {
1858
+ throw new Error("Unexpected commander action signature");
1859
+ }
1860
+ const globals = command.optsWithGlobals();
1861
+ const local = command.opts();
1862
+ await executeAction({
1863
+ action,
1864
+ positionalValues,
1865
+ flagValues: local,
1866
+ globals,
1867
+ servers: context.servers,
1868
+ authSchemes: context.authSchemes,
1869
+ specId: context.specId,
1870
+ embeddedDefaults: context.embeddedDefaults,
1871
+ bodyFlagDefs,
1872
+ resourceName: resource.resource
1873
+ });
1874
+ });
1875
+ }
1876
+ }
1877
+ }
1878
+
1879
+ // src/cli/main.ts
1880
+ async function main(argv, options = {}) {
1881
+ const program = new Command2;
1882
+ program.name(options.cliName ?? "specli").description("Generate a CLI from an OpenAPI spec").option("--spec <urlOrPath>", "OpenAPI URL or file path").option("--server <url>", "Override server/base URL").option("--server-var <name=value>", "Server URL template variable (repeatable)", collectRepeatable).option("--auth <scheme>", "Select auth scheme by key").option("--bearer-token <token>", "Bearer token (Authorization: Bearer)").option("--oauth-token <token>", "OAuth token (alias of bearer)").option("--username <username>", "Basic auth username").option("--password <password>", "Basic auth password").option("--api-key <key>", "API key value").option("--json", "Machine-readable output").showHelpAfterError();
1883
+ const spec = getArgValue(argv, "--spec");
1884
+ const wantsHelp = hasAnyArg(argv, ["-h", "--help"]);
1885
+ if (!spec && !options.embeddedSpecText && wantsHelp) {
1886
+ program.addHelpText("after", `
1887
+ To see generated commands, run with --spec <url|path>.
1888
+ `);
1889
+ program.parse(argv);
1890
+ return;
1891
+ }
1892
+ const ctx = await buildRuntimeContext({
1893
+ spec,
1894
+ embeddedSpecText: options.embeddedSpecText
1895
+ });
1896
+ const defaultProfileName = "default";
1897
+ program.command("login [token]").description("Store a bearer token for authentication").action(async (tokenArg, _opts, command) => {
1898
+ const globals = command.optsWithGlobals();
1899
+ let token = tokenArg;
1900
+ if (!token) {
1901
+ const isTTY = process.stdin.isTTY;
1902
+ if (isTTY) {
1903
+ process.stdout.write("Enter token: ");
1904
+ const reader = process.stdin;
1905
+ const chunks = [];
1906
+ for await (const chunk of reader) {
1907
+ chunks.push(chunk);
1908
+ if (chunk.includes(10))
1909
+ break;
1910
+ }
1911
+ token = Buffer.concat(chunks).toString().trim();
1912
+ } else {
1913
+ const text = await readStdinText();
1914
+ token = text.trim();
1915
+ }
1916
+ }
1917
+ if (!token) {
1918
+ throw new Error("No token provided. Usage: login <token> or echo $TOKEN | login");
1919
+ }
1920
+ const file = await readProfiles();
1921
+ if (!file.profiles.find((p) => p.name === defaultProfileName)) {
1922
+ const updated = upsertProfile(file, { name: defaultProfileName });
1923
+ await writeProfiles({ ...updated, defaultProfile: defaultProfileName });
1924
+ } else if (!file.defaultProfile) {
1925
+ await writeProfiles({ ...file, defaultProfile: defaultProfileName });
1926
+ }
1927
+ await setToken(ctx.loaded.id, defaultProfileName, token);
1928
+ if (globals.json) {
1929
+ process.stdout.write(`${JSON.stringify({ ok: true })}
1930
+ `);
1931
+ return;
1932
+ }
1933
+ process.stdout.write(`ok: logged in
1934
+ `);
1935
+ });
1936
+ program.command("logout").description("Clear stored authentication token").action(async (_opts, command) => {
1937
+ const globals = command.optsWithGlobals();
1938
+ const deleted = await deleteToken(ctx.loaded.id, defaultProfileName);
1939
+ if (globals.json) {
1940
+ process.stdout.write(`${JSON.stringify({ ok: deleted })}
1941
+ `);
1942
+ return;
1943
+ }
1944
+ process.stdout.write(deleted ? `ok: logged out
1945
+ ` : `ok: not logged in
1946
+ `);
1947
+ });
1948
+ program.command("whoami").description("Show current authentication status").action(async (_opts, command) => {
1949
+ const globals = command.optsWithGlobals();
1950
+ const token = await getToken(ctx.loaded.id, defaultProfileName);
1951
+ const hasToken = Boolean(token);
1952
+ let maskedToken = null;
1953
+ if (token && token.length > 16) {
1954
+ maskedToken = `${token.slice(0, 8)}...${token.slice(-4)}`;
1955
+ } else if (token) {
1956
+ maskedToken = `${token.slice(0, 4)}...`;
1957
+ }
1958
+ if (globals.json) {
1959
+ process.stdout.write(`${JSON.stringify({ authenticated: hasToken, token: maskedToken })}
1960
+ `);
1961
+ return;
1962
+ }
1963
+ if (hasToken) {
1964
+ process.stdout.write(`authenticated: yes
1965
+ `);
1966
+ process.stdout.write(`token: ${maskedToken}
1967
+ `);
1968
+ } else {
1969
+ process.stdout.write(`authenticated: no
1970
+ `);
1971
+ process.stdout.write(`Run 'login <token>' to authenticate.
1972
+ `);
1973
+ }
1974
+ });
1975
+ program.command("__schema").description("Print indexed operations (machine-readable when --json)").option("--pretty", "Pretty-print JSON when used with --json").option("--min", "Minimal JSON output (commands + metadata only)").action(async (_opts, command) => {
1976
+ const flags = command.optsWithGlobals();
1977
+ if (flags.json) {
1978
+ const pretty = Boolean(flags.pretty);
1979
+ const payload = flags.min ? toMinimalSchemaOutput(ctx.schema) : ctx.schema;
1980
+ const text = stableStringify(payload, { space: pretty ? 2 : 0 });
1981
+ process.stdout.write(`${text}
1982
+ `);
1983
+ return;
1984
+ }
1985
+ process.stdout.write(`${ctx.schema.openapi.title ?? "(untitled)"}
1986
+ `);
1987
+ process.stdout.write(`OpenAPI: ${ctx.schema.openapi.version}
1988
+ `);
1989
+ process.stdout.write(`Spec: ${ctx.schema.spec.id} (${ctx.schema.spec.source})
1990
+ `);
1991
+ process.stdout.write(`Fingerprint: ${ctx.schema.spec.fingerprint}
1992
+ `);
1993
+ process.stdout.write(`Servers: ${ctx.schema.servers.length}
1994
+ `);
1995
+ process.stdout.write(`Auth Schemes: ${ctx.schema.authSchemes.length}
1996
+ `);
1997
+ process.stdout.write(`Operations: ${ctx.schema.operations.length}
1998
+ `);
1999
+ for (const op of ctx.schema.operations) {
2000
+ const id = op.operationId ? ` (${op.operationId})` : "";
2001
+ process.stdout.write(`- ${op.method} ${op.path}${id}
2002
+ `);
2003
+ }
2004
+ if (ctx.schema.planned?.length) {
2005
+ process.stdout.write(`
2006
+ Planned commands:
2007
+ `);
2008
+ for (const op of ctx.schema.planned) {
2009
+ const args = op.pathArgs.length ? ` ${op.pathArgs.map((a) => `<${a}>`).join(" ")}` : "";
2010
+ process.stdout.write(`- specli ${op.resource} ${op.action}${args}
2011
+ `);
2012
+ }
2013
+ }
2014
+ });
2015
+ addGeneratedCommands(program, {
2016
+ servers: ctx.servers,
2017
+ authSchemes: ctx.authSchemes,
2018
+ commands: ctx.commands,
2019
+ specId: ctx.loaded.id,
2020
+ embeddedDefaults: {
2021
+ server: options.server,
2022
+ serverVars: options.serverVars,
2023
+ auth: options.auth
2024
+ }
2025
+ });
2026
+ await program.parseAsync(argv);
2027
+ }
2028
+ export {
2029
+ main
2030
+ };
2031
+
2032
+ //# debugId=4FE857249D0B04F164756E2164756E21