specli 0.0.4 → 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 (209) 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 +73 -163
  201. package/src/cli/runtime/auth/resolve.ts +20 -0
  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 +22 -11
  209. package/src/cli/spec-loader.ts +2 -2
@@ -0,0 +1,670 @@
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/cli/runtime/auth/resolve.ts
99
+ var BEARER_COMPATIBLE_KINDS = new Set([
100
+ "http-bearer",
101
+ "oauth2",
102
+ "openIdConnect"
103
+ ]);
104
+ function resolveAuthScheme(authSchemes, required, inputs) {
105
+ if (inputs.flagAuthScheme)
106
+ return inputs.flagAuthScheme;
107
+ if (inputs.profileAuthScheme && authSchemes.some((s) => s.key === inputs.profileAuthScheme)) {
108
+ return inputs.profileAuthScheme;
109
+ }
110
+ if (inputs.embeddedAuthScheme && authSchemes.some((s) => s.key === inputs.embeddedAuthScheme)) {
111
+ return inputs.embeddedAuthScheme;
112
+ }
113
+ const alts = required.alternatives;
114
+ if (alts.length === 1 && alts[0]?.length === 1)
115
+ return alts[0][0]?.key;
116
+ if (authSchemes.length === 1)
117
+ return authSchemes[0]?.key;
118
+ if (inputs.hasStoredToken && alts.length > 0) {
119
+ for (const alt of alts) {
120
+ if (alt.length !== 1)
121
+ continue;
122
+ const key = alt[0]?.key;
123
+ const scheme = authSchemes.find((s) => s.key === key);
124
+ if (scheme && BEARER_COMPATIBLE_KINDS.has(scheme.kind)) {
125
+ return key;
126
+ }
127
+ }
128
+ }
129
+ return;
130
+ }
131
+
132
+ // src/cli/runtime/compat.ts
133
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
134
+ import { parse as parseYaml } from "yaml";
135
+ var isBun = typeof globalThis.Bun !== "undefined";
136
+ async function readFileText(path) {
137
+ if (isBun) {
138
+ return Bun.file(path).text();
139
+ }
140
+ return readFileSync(path, "utf-8");
141
+ }
142
+ async function fileExists(path) {
143
+ if (isBun) {
144
+ return Bun.file(path).exists();
145
+ }
146
+ return existsSync(path);
147
+ }
148
+ function parseYamlContent(text) {
149
+ if (isBun) {
150
+ const { YAML } = globalThis.Bun;
151
+ return YAML.parse(text);
152
+ }
153
+ return parseYaml(text);
154
+ }
155
+
156
+ // src/cli/runtime/profile/secrets.ts
157
+ var bunLiteral = "bun";
158
+ function secretServiceForSpec(specId) {
159
+ return `specli:${specId}`;
160
+ }
161
+ function tokenSecretKey(specId, profile) {
162
+ return {
163
+ service: secretServiceForSpec(specId),
164
+ name: `profile:${profile}:token`
165
+ };
166
+ }
167
+ async function getToken(specId, profile) {
168
+ if (!isBun) {
169
+ return null;
170
+ }
171
+ const { secrets } = await import(bunLiteral);
172
+ const key = tokenSecretKey(specId, profile);
173
+ return await secrets.get({ service: key.service, name: key.name });
174
+ }
175
+
176
+ // src/cli/runtime/profile/store.ts
177
+ function configDir() {
178
+ const home = process.env.HOME;
179
+ if (!home)
180
+ throw new Error("Missing HOME env var");
181
+ return `${home}/.config/specli`;
182
+ }
183
+ function configPathJson() {
184
+ return `${configDir()}/profiles.json`;
185
+ }
186
+ function configPathYaml() {
187
+ return `${configDir()}/profiles.yaml`;
188
+ }
189
+ async function readProfiles() {
190
+ const jsonPath = configPathJson();
191
+ const yamlPath = configPathYaml();
192
+ const jsonExists = await fileExists(jsonPath);
193
+ const yamlExists = await fileExists(yamlPath);
194
+ const filePath = jsonExists ? jsonPath : yamlExists ? yamlPath : null;
195
+ if (!filePath)
196
+ return { profiles: [] };
197
+ const text = await readFileText(filePath);
198
+ let parsed;
199
+ try {
200
+ parsed = parseYamlContent(text);
201
+ } catch {
202
+ parsed = JSON.parse(text);
203
+ }
204
+ const obj = parsed && typeof parsed === "object" ? parsed : {};
205
+ const profiles = Array.isArray(obj.profiles) ? obj.profiles : [];
206
+ return {
207
+ profiles: profiles.filter(Boolean),
208
+ defaultProfile: typeof obj.defaultProfile === "string" ? obj.defaultProfile : undefined
209
+ };
210
+ }
211
+ function getProfile(data, name) {
212
+ const wanted = name ?? data.defaultProfile;
213
+ if (!wanted)
214
+ return;
215
+ return data.profiles.find((p) => p?.name === wanted);
216
+ }
217
+
218
+ // src/cli/runtime/template.ts
219
+ function extractTemplateVars(template) {
220
+ const out = [];
221
+ const re = /\{([^}]+)\}/g;
222
+ while (true) {
223
+ const match = re.exec(template);
224
+ if (!match)
225
+ break;
226
+ out.push((match[1] ?? "").trim());
227
+ }
228
+ return out.filter(Boolean);
229
+ }
230
+ function applyTemplate(template, vars, options) {
231
+ const encode = options?.encode ?? false;
232
+ return template.replace(/\{([^}]+)\}/g, (_, rawName) => {
233
+ const name = String(rawName).trim();
234
+ const value = vars[name];
235
+ if (typeof value !== "string") {
236
+ throw new Error(`Missing template variable: ${name}`);
237
+ }
238
+ return encode ? encodeURIComponent(value) : value;
239
+ });
240
+ }
241
+
242
+ // src/cli/runtime/server-url.ts
243
+ function resolveServerUrl(input) {
244
+ const base = input.serverOverride || input.servers[0]?.url;
245
+ if (!base) {
246
+ throw new Error("No server URL found. Provide --server <url> or define servers in the OpenAPI spec.");
247
+ }
248
+ const names = extractTemplateVars(base);
249
+ if (!names.length)
250
+ return base;
251
+ const vars = {};
252
+ for (const name of names) {
253
+ const provided = input.serverVars[name];
254
+ if (typeof provided === "string") {
255
+ vars[name] = provided;
256
+ continue;
257
+ }
258
+ const match = input.servers.find((s) => s.url === base);
259
+ const v = match?.variables.find((x) => x.name === name);
260
+ if (typeof v?.default === "string") {
261
+ vars[name] = v.default;
262
+ continue;
263
+ }
264
+ throw new Error(`Missing server variable '${name}'. Provide --server-var ${name}=...`);
265
+ }
266
+ return applyTemplate(base, vars);
267
+ }
268
+
269
+ // src/cli/runtime/validate/ajv.ts
270
+ import Ajv from "ajv";
271
+ import addFormats from "ajv-formats";
272
+ function createAjv() {
273
+ const ajv = new Ajv({
274
+ allErrors: true,
275
+ strict: false,
276
+ coerceTypes: false
277
+ });
278
+ addFormats(ajv);
279
+ return ajv;
280
+ }
281
+ // src/cli/runtime/validate/coerce.ts
282
+ import { InvalidArgumentError } from "commander";
283
+ // src/cli/runtime/validate/error.ts
284
+ function formatAjvErrors(errors) {
285
+ if (!errors?.length)
286
+ return "Invalid input";
287
+ return errors.map((e) => {
288
+ const path = e.instancePath || e.schemaPath || "";
289
+ if (e.keyword === "required" && e.params && typeof e.params === "object" && "missingProperty" in e.params) {
290
+ const missing = String(e.params.missingProperty);
291
+ const where = e.instancePath || "/";
292
+ return `${where} missing required property '${missing}'`.trim();
293
+ }
294
+ const msg = e.message || "invalid";
295
+ return `${path} ${msg}`.trim();
296
+ }).join(`
297
+ `);
298
+ }
299
+ // src/cli/runtime/validate/schema.ts
300
+ function deriveValidationSchemas(action) {
301
+ const query = { type: "object", properties: {}, required: [] };
302
+ const header = { type: "object", properties: {}, required: [] };
303
+ const cookie = { type: "object", properties: {}, required: [] };
304
+ for (const p of action.params) {
305
+ if (p.kind !== "flag")
306
+ continue;
307
+ const target = p.in === "query" ? query : p.in === "header" ? header : p.in === "cookie" ? cookie : undefined;
308
+ if (!target)
309
+ continue;
310
+ const schema = p.schema ?? (p.type === "unknown" ? {} : { type: p.type });
311
+ target.properties[p.name] = schema;
312
+ if (p.required) {
313
+ if (!target.required)
314
+ target.required = [];
315
+ target.required.push(p.name);
316
+ }
317
+ }
318
+ if (!query.required?.length)
319
+ delete query.required;
320
+ if (!header.required?.length)
321
+ delete header.required;
322
+ if (!cookie.required?.length)
323
+ delete cookie.required;
324
+ return {
325
+ querySchema: Object.keys(query.properties).length ? query : undefined,
326
+ headerSchema: Object.keys(header.properties).length ? header : undefined,
327
+ cookieSchema: Object.keys(cookie.properties).length ? cookie : undefined
328
+ };
329
+ }
330
+ // src/cli/runtime/request.ts
331
+ function parseKeyValuePairs(pairs) {
332
+ const out = {};
333
+ for (const pair of pairs ?? []) {
334
+ const idx = pair.indexOf("=");
335
+ if (idx === -1)
336
+ throw new Error(`Invalid pair '${pair}', expected name=value`);
337
+ const name = pair.slice(0, idx).trim();
338
+ const value = pair.slice(idx + 1).trim();
339
+ if (!name)
340
+ throw new Error(`Invalid pair '${pair}', missing name`);
341
+ out[name] = value;
342
+ }
343
+ return out;
344
+ }
345
+ function pickAuthSchemeKey(action, globals) {
346
+ if (globals.auth)
347
+ return globals.auth;
348
+ const req = action.auth.alternatives;
349
+ if (req.length === 1 && req[0]?.length === 1) {
350
+ return req[0][0]?.key;
351
+ }
352
+ return;
353
+ }
354
+ function applyAuth(headers, url, action, globals, authSchemes) {
355
+ const schemeKey = pickAuthSchemeKey(action, globals);
356
+ if (!schemeKey)
357
+ return { headers, url };
358
+ const scheme = authSchemes.find((s) => s.key === schemeKey);
359
+ if (!scheme) {
360
+ throw new Error(`Unknown auth scheme '${schemeKey}'. Available: ${authSchemes.map((s) => s.key).join(", ")}`);
361
+ }
362
+ if (scheme.kind === "http-bearer" || scheme.kind === "oauth2" || scheme.kind === "openIdConnect") {
363
+ const token = globals.bearerToken ?? globals.oauthToken;
364
+ if (!token)
365
+ throw new Error("Missing token. Provide --bearer-token <token>.");
366
+ headers.set("Authorization", `Bearer ${token}`);
367
+ return { headers, url };
368
+ }
369
+ if (scheme.kind === "http-basic") {
370
+ if (!globals.username)
371
+ throw new Error("Missing --username for basic auth");
372
+ if (!globals.password)
373
+ throw new Error("Missing --password for basic auth");
374
+ const raw = `${globals.username}:${globals.password}`;
375
+ const encoded = Buffer.from(raw, "utf8").toString("base64");
376
+ headers.set("Authorization", `Basic ${encoded}`);
377
+ return { headers, url };
378
+ }
379
+ if (scheme.kind === "api-key") {
380
+ if (!scheme.name)
381
+ throw new Error(`apiKey scheme '${scheme.key}' missing name`);
382
+ if (!scheme.in)
383
+ throw new Error(`apiKey scheme '${scheme.key}' missing location`);
384
+ if (!globals.apiKey)
385
+ throw new Error("Missing --api-key for apiKey auth");
386
+ if (scheme.in === "header") {
387
+ headers.set(scheme.name, globals.apiKey);
388
+ }
389
+ if (scheme.in === "query") {
390
+ url.searchParams.set(scheme.name, globals.apiKey);
391
+ }
392
+ if (scheme.in === "cookie") {
393
+ const existing = headers.get("Cookie");
394
+ const part = `${scheme.name}=${globals.apiKey}`;
395
+ headers.set("Cookie", existing ? `${existing}; ${part}` : part);
396
+ }
397
+ return { headers, url };
398
+ }
399
+ return { headers, url };
400
+ }
401
+ async function buildRequest(input) {
402
+ const defaultProfileName = "default";
403
+ const profilesFile = await readProfiles();
404
+ const profile = getProfile(profilesFile, defaultProfileName);
405
+ const embedded = input.embeddedDefaults;
406
+ const embeddedServerVars = parseKeyValuePairs(embedded?.serverVars);
407
+ const cliServerVars = parseKeyValuePairs(input.globals.serverVar);
408
+ const serverVars = { ...embeddedServerVars, ...cliServerVars };
409
+ const serverUrl = resolveServerUrl({
410
+ serverOverride: input.globals.server ?? profile?.server ?? embedded?.server,
411
+ servers: input.servers,
412
+ serverVars
413
+ });
414
+ const pathVars = {};
415
+ for (let i = 0;i < input.action.positionals.length; i++) {
416
+ const pos = input.action.positionals[i];
417
+ const raw = input.action.pathArgs[i];
418
+ const value = input.positionalValues[i];
419
+ if (typeof raw === "string" && typeof value === "string") {
420
+ pathVars[raw] = value;
421
+ }
422
+ if (pos?.name && typeof value === "string") {
423
+ pathVars[pos.name] = value;
424
+ }
425
+ }
426
+ const path = applyTemplate(input.action.path, pathVars, { encode: true });
427
+ const baseUrl = serverUrl.endsWith("/") ? serverUrl : `${serverUrl}/`;
428
+ const relativePath = path.startsWith("/") ? path.slice(1) : path;
429
+ const url = new URL(relativePath, baseUrl);
430
+ const headers = new Headers;
431
+ const queryValues = {};
432
+ const headerValues = {};
433
+ const cookieValues = {};
434
+ for (const p of input.action.params) {
435
+ if (p.kind !== "flag")
436
+ continue;
437
+ const optValue = input.flagValues[optionKeyFromFlag(p.flag)];
438
+ if (typeof optValue === "undefined")
439
+ continue;
440
+ if (p.in === "query") {
441
+ queryValues[p.name] = optValue;
442
+ }
443
+ if (p.in === "header") {
444
+ headerValues[p.name] = optValue;
445
+ }
446
+ if (p.in === "cookie") {
447
+ cookieValues[p.name] = optValue;
448
+ }
449
+ }
450
+ const schemas = deriveValidationSchemas(input.action);
451
+ const ajv2 = createAjv();
452
+ if (schemas.querySchema) {
453
+ const validate = ajv2.compile(schemas.querySchema);
454
+ if (!validate(queryValues)) {
455
+ throw new Error(formatAjvErrors(validate.errors));
456
+ }
457
+ }
458
+ if (schemas.headerSchema) {
459
+ const validate = ajv2.compile(schemas.headerSchema);
460
+ if (!validate(headerValues)) {
461
+ throw new Error(formatAjvErrors(validate.errors));
462
+ }
463
+ }
464
+ if (schemas.cookieSchema) {
465
+ const validate = ajv2.compile(schemas.cookieSchema);
466
+ if (!validate(cookieValues)) {
467
+ throw new Error(formatAjvErrors(validate.errors));
468
+ }
469
+ }
470
+ for (const [name, value] of Object.entries(queryValues)) {
471
+ if (Array.isArray(value)) {
472
+ for (const item of value) {
473
+ url.searchParams.append(name, String(item));
474
+ }
475
+ continue;
476
+ }
477
+ url.searchParams.set(name, String(value));
478
+ }
479
+ for (const [name, value] of Object.entries(headerValues)) {
480
+ headers.set(name, String(value));
481
+ }
482
+ for (const [name, value] of Object.entries(cookieValues)) {
483
+ const existing = headers.get("Cookie");
484
+ const part = `${name}=${String(value)}`;
485
+ headers.set("Cookie", existing ? `${existing}; ${part}` : part);
486
+ }
487
+ let body;
488
+ if (input.action.requestBody) {
489
+ const bodyFlagDefs = input.bodyFlagDefs ?? [];
490
+ const hasBodyFlags = bodyFlagDefs.some((def) => {
491
+ const dotKey = def.path.join(".");
492
+ return input.flagValues[dotKey] !== undefined;
493
+ });
494
+ const contentType = input.action.requestBody.preferredContentType;
495
+ if (contentType)
496
+ headers.set("Content-Type", contentType);
497
+ const schema2 = input.action.requestBodySchema;
498
+ const requiredFields = bodyFlagDefs.filter((d) => d.required);
499
+ if (!hasBodyFlags) {
500
+ if (requiredFields.length > 0) {
501
+ const flagList = requiredFields.map((d) => `--${d.path.join(".")}`);
502
+ throw new Error(`Required: ${flagList.join(", ")}`);
503
+ }
504
+ if (input.action.requestBody.required) {
505
+ body = "{}";
506
+ }
507
+ } else {
508
+ if (!contentType?.includes("json")) {
509
+ throw new Error("Body field flags are only supported for JSON request bodies.");
510
+ }
511
+ const { findMissingRequired: findMissingRequired2, parseDotNotationFlags: parseDotNotationFlags2 } = await Promise.resolve().then(() => exports_body_flags);
512
+ const missing = findMissingRequired2(input.flagValues, bodyFlagDefs);
513
+ if (missing.length > 0) {
514
+ const missingFlags = missing.map((m) => `--${m}`).join(", ");
515
+ throw new Error(`Missing required fields: ${missingFlags}`);
516
+ }
517
+ const built = parseDotNotationFlags2(input.flagValues, bodyFlagDefs);
518
+ if (schema2) {
519
+ const validate = ajv2.compile(schema2);
520
+ if (!validate(built)) {
521
+ throw new Error(formatAjvErrors(validate.errors));
522
+ }
523
+ }
524
+ body = JSON.stringify(built);
525
+ }
526
+ }
527
+ const storedToken = profile?.name ? await getToken(input.specId, profile.name) : null;
528
+ const resolvedAuthScheme = resolveAuthScheme(input.authSchemes, input.action.auth, {
529
+ flagAuthScheme: input.globals.auth,
530
+ profileAuthScheme: profile?.authScheme,
531
+ embeddedAuthScheme: embedded?.auth,
532
+ hasStoredToken: Boolean(storedToken)
533
+ });
534
+ const tokenFromProfile = resolvedAuthScheme ? storedToken : null;
535
+ const globalsWithProfileAuth = {
536
+ ...input.globals,
537
+ auth: resolvedAuthScheme,
538
+ bearerToken: input.globals.bearerToken ?? input.globals.oauthToken ?? tokenFromProfile ?? undefined
539
+ };
540
+ const final = applyAuth(headers, url, input.action, globalsWithProfileAuth, input.authSchemes);
541
+ const req = new Request(final.url.toString(), {
542
+ method: input.action.method,
543
+ headers: final.headers,
544
+ body
545
+ });
546
+ const curl = buildCurl(req, body);
547
+ return { request: req, curl };
548
+ }
549
+ function buildCurl(req, body) {
550
+ const parts = ["curl", "-sS", "-X", req.method];
551
+ for (const [k, v] of req.headers.entries()) {
552
+ parts.push("-H", shellQuote(`${k}: ${v}`));
553
+ }
554
+ if (typeof body === "string") {
555
+ parts.push("--data", shellQuote(body));
556
+ }
557
+ parts.push(shellQuote(req.url));
558
+ return parts.join(" ");
559
+ }
560
+ function shellQuote(value) {
561
+ return `'${value.replace(/'/g, `'\\''`)}'`;
562
+ }
563
+ function optionKeyFromFlag(flag) {
564
+ const name = flag.replace(/^--/, "");
565
+ return name.replace(/-([a-z])/g, (_, c) => String(c).toUpperCase());
566
+ }
567
+
568
+ // src/cli/runtime/execute.ts
569
+ function formatError(message, resourceName, actionName) {
570
+ const helpCmd = resourceName ? `${resourceName} ${actionName} --help` : `${actionName} --help`;
571
+ return `${message}
572
+
573
+ Run '${helpCmd}' to see available options.`;
574
+ }
575
+ async function execute(input) {
576
+ const { request, curl } = await buildRequest({
577
+ specId: input.specId,
578
+ action: input.action,
579
+ positionalValues: input.positionalValues,
580
+ flagValues: input.flagValues,
581
+ globals: input.globals,
582
+ servers: input.servers,
583
+ authSchemes: input.authSchemes,
584
+ embeddedDefaults: input.embeddedDefaults,
585
+ bodyFlagDefs: input.bodyFlagDefs
586
+ });
587
+ const res = await fetch(request);
588
+ const contentType = res.headers.get("content-type") ?? "";
589
+ const text = await res.text();
590
+ let body = text;
591
+ if (contentType.includes("json") && text) {
592
+ try {
593
+ body = JSON.parse(text);
594
+ } catch {}
595
+ }
596
+ return {
597
+ ok: res.ok,
598
+ status: res.status,
599
+ body,
600
+ curl
601
+ };
602
+ }
603
+ async function executeAction(input) {
604
+ const actionName = input.action.action;
605
+ const resourceName = input.resourceName;
606
+ try {
607
+ if (input.globals.curl) {
608
+ const { curl } = await buildRequest({
609
+ specId: input.specId,
610
+ action: input.action,
611
+ positionalValues: input.positionalValues,
612
+ flagValues: input.flagValues,
613
+ globals: input.globals,
614
+ servers: input.servers,
615
+ authSchemes: input.authSchemes,
616
+ embeddedDefaults: input.embeddedDefaults,
617
+ bodyFlagDefs: input.bodyFlagDefs
618
+ });
619
+ process.stdout.write(`${curl}
620
+ `);
621
+ return;
622
+ }
623
+ const result = await execute(input);
624
+ if (!result.ok) {
625
+ if (input.globals.json) {
626
+ process.stdout.write(`${JSON.stringify({ status: result.status, body: result.body })}
627
+ `);
628
+ } else {
629
+ process.stderr.write(`HTTP ${result.status}
630
+ `);
631
+ process.stderr.write(`${typeof result.body === "string" ? result.body : JSON.stringify(result.body, null, 2)}
632
+ `);
633
+ }
634
+ process.exitCode = 1;
635
+ return;
636
+ }
637
+ if (input.globals.json) {
638
+ process.stdout.write(`${JSON.stringify(result.body)}
639
+ `);
640
+ return;
641
+ }
642
+ if (typeof result.body === "string") {
643
+ process.stdout.write(result.body);
644
+ if (!result.body.endsWith(`
645
+ `))
646
+ process.stdout.write(`
647
+ `);
648
+ } else {
649
+ process.stdout.write(`${JSON.stringify(result.body, null, 2)}
650
+ `);
651
+ }
652
+ } catch (err) {
653
+ const rawMessage = err instanceof Error ? err.message : String(err);
654
+ const message = formatError(rawMessage, resourceName, actionName);
655
+ if (input.globals.json) {
656
+ process.stdout.write(`${JSON.stringify({ error: rawMessage })}
657
+ `);
658
+ } else {
659
+ process.stderr.write(`error: ${message}
660
+ `);
661
+ }
662
+ process.exitCode = 1;
663
+ }
664
+ }
665
+ export {
666
+ executeAction,
667
+ execute
668
+ };
669
+
670
+ //# debugId=59F9DD74E1CA28F164756E2164756E21