toolcraft-openapi 0.0.232 → 0.0.234

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 (84) hide show
  1. package/dist/composition.json +2 -2
  2. package/dist/define-client.js +4 -64
  3. package/dist/generate.d.ts +10 -0
  4. package/dist/generate.js +5 -5
  5. package/dist/http.js +132 -61
  6. package/dist/network-error.d.ts +1 -0
  7. package/dist/network-error.js +11 -10
  8. package/dist/redaction.js +2 -1
  9. package/dist/runtime.d.ts +1 -0
  10. package/dist/runtime.js +73 -5
  11. package/dist/spec-cache.d.ts +1 -0
  12. package/dist/spec-cache.js +14 -2
  13. package/dist/spec-source.d.ts +2 -0
  14. package/dist/spec-source.js +15 -10
  15. package/node_modules/toolcraft-design/dist/command-registry.d.ts +11 -0
  16. package/node_modules/toolcraft-design/dist/command-registry.js +24 -0
  17. package/node_modules/toolcraft-design/dist/dashboard/ansi.d.ts +2 -0
  18. package/node_modules/toolcraft-design/dist/dashboard/ansi.js +81 -27
  19. package/node_modules/toolcraft-design/dist/dashboard/buffer.js +39 -25
  20. package/node_modules/toolcraft-design/dist/dashboard/components/border.js +6 -5
  21. package/node_modules/toolcraft-design/dist/dashboard/components/footer.js +26 -21
  22. package/node_modules/toolcraft-design/dist/dashboard/components/output-pane.d.ts +1 -1
  23. package/node_modules/toolcraft-design/dist/dashboard/components/output-pane.js +12 -6
  24. package/node_modules/toolcraft-design/dist/dashboard/components/stats-pane.d.ts +2 -1
  25. package/node_modules/toolcraft-design/dist/dashboard/components/stats-pane.js +51 -10
  26. package/node_modules/toolcraft-design/dist/dashboard/dashboard.d.ts +4 -0
  27. package/node_modules/toolcraft-design/dist/dashboard/dashboard.js +77 -4
  28. package/node_modules/toolcraft-design/dist/dashboard/index.d.ts +2 -0
  29. package/node_modules/toolcraft-design/dist/dashboard/index.js +2 -0
  30. package/node_modules/toolcraft-design/dist/dashboard/keymap.js +26 -6
  31. package/node_modules/toolcraft-design/dist/dashboard/layout.d.ts +1 -0
  32. package/node_modules/toolcraft-design/dist/dashboard/layout.js +19 -3
  33. package/node_modules/toolcraft-design/dist/dashboard/line-buffer.d.ts +9 -0
  34. package/node_modules/toolcraft-design/dist/dashboard/line-buffer.js +63 -0
  35. package/node_modules/toolcraft-design/dist/dashboard/output-preview.d.ts +9 -0
  36. package/node_modules/toolcraft-design/dist/dashboard/output-preview.js +70 -0
  37. package/node_modules/toolcraft-design/dist/dashboard/snapshot.js +3 -1
  38. package/node_modules/toolcraft-design/dist/dashboard/store.js +9 -3
  39. package/node_modules/toolcraft-design/dist/dashboard/terminal-strings.d.ts +6 -0
  40. package/node_modules/toolcraft-design/dist/dashboard/terminal-strings.js +108 -0
  41. package/node_modules/toolcraft-design/dist/dashboard/terminal-width.js +3 -1
  42. package/node_modules/toolcraft-design/dist/dashboard/terminal.js +11 -1
  43. package/node_modules/toolcraft-design/dist/dashboard/testing/pipeline-scenario.d.ts +1 -0
  44. package/node_modules/toolcraft-design/dist/dashboard/testing/pipeline-scenario.js +126 -0
  45. package/node_modules/toolcraft-design/dist/dashboard/types.d.ts +3 -1
  46. package/node_modules/toolcraft-design/dist/event-groups.d.ts +19 -0
  47. package/node_modules/toolcraft-design/dist/event-groups.js +49 -0
  48. package/node_modules/toolcraft-design/dist/index.d.ts +6 -1
  49. package/node_modules/toolcraft-design/dist/index.js +5 -1
  50. package/node_modules/toolcraft-design/dist/inline-notice.d.ts +14 -0
  51. package/node_modules/toolcraft-design/dist/inline-notice.js +28 -0
  52. package/node_modules/toolcraft-design/dist/metric.d.ts +8 -0
  53. package/node_modules/toolcraft-design/dist/metric.js +21 -0
  54. package/node_modules/toolcraft-design/dist/overlay-manager.d.ts +6 -0
  55. package/node_modules/toolcraft-design/dist/overlay-manager.js +10 -0
  56. package/node_modules/toolcraft-design/dist/primitives.d.ts +12 -0
  57. package/node_modules/toolcraft-design/dist/primitives.js +7 -0
  58. package/node_modules/toolcraft-design/dist/progress-group.d.ts +7 -0
  59. package/node_modules/toolcraft-design/dist/progress-group.js +10 -0
  60. package/node_modules/toolcraft-design/dist/render-performance.d.ts +33 -0
  61. package/node_modules/toolcraft-design/dist/render-performance.js +71 -0
  62. package/node_modules/toolcraft-design/dist/task-tree.d.ts +22 -0
  63. package/node_modules/toolcraft-design/dist/task-tree.js +79 -0
  64. package/node_modules/toolcraft-design/dist/viewport.d.ts +18 -0
  65. package/node_modules/toolcraft-design/dist/viewport.js +56 -0
  66. package/node_modules/toolcraft-schema/dist/clone-default.d.ts +1 -0
  67. package/node_modules/toolcraft-schema/dist/clone-default.js +26 -0
  68. package/node_modules/toolcraft-schema/dist/index.compile-check.js +1 -0
  69. package/node_modules/toolcraft-schema/dist/index.d.ts +18 -9
  70. package/node_modules/toolcraft-schema/dist/index.js +46 -8
  71. package/node_modules/toolcraft-schema/dist/json-schema/compiler.d.ts +1 -0
  72. package/node_modules/toolcraft-schema/dist/json-schema/compiler.js +6 -0
  73. package/node_modules/toolcraft-schema/dist/json-schema/evaluate.js +6 -3
  74. package/node_modules/toolcraft-schema/dist/json-schema/normalize-nullability.d.ts +1 -0
  75. package/node_modules/toolcraft-schema/dist/json-schema/normalize-nullability.js +69 -0
  76. package/node_modules/toolcraft-schema/dist/json-schema/types.d.ts +1 -0
  77. package/node_modules/toolcraft-schema/dist/json.d.ts +4 -1
  78. package/node_modules/toolcraft-schema/dist/json.js +57 -1
  79. package/node_modules/toolcraft-schema/dist/native-json-schema.d.ts +10 -0
  80. package/node_modules/toolcraft-schema/dist/native-json-schema.js +11 -0
  81. package/node_modules/toolcraft-schema/dist/validate.d.ts +5 -1
  82. package/node_modules/toolcraft-schema/dist/validate.js +61 -47
  83. package/node_modules/toolcraft-schema/package.json +1 -1
  84. package/package.json +4 -4
@@ -33,12 +33,12 @@
33
33
  },
34
34
  {
35
35
  "name": "toolcraft-openapi",
36
- "version": "0.0.232",
36
+ "version": "0.0.234",
37
37
  "license": "MIT"
38
38
  },
39
39
  {
40
40
  "name": "toolcraft-schema",
41
- "version": "0.0.232",
41
+ "version": "0.0.234",
42
42
  "license": "MIT"
43
43
  },
44
44
  {
@@ -1,4 +1,4 @@
1
- import { ToolcraftBugError, defineCommand, defineGroup, UserError } from "toolcraft";
1
+ import { ToolcraftBugError, cloneCommandNode, defineGroup, UserError } from "toolcraft";
2
2
  import { toMcpPrefix } from "./naming.js";
3
3
  const CLI_SCOPE = ["cli"];
4
4
  export function defineClient(options) {
@@ -9,7 +9,7 @@ export function defineClient(options) {
9
9
  const mergedChildren = mergeChildren([
10
10
  { nodes: options.commands, source: "generated" },
11
11
  { nodes: options.handwrittenCommands ?? [], source: "handwritten" },
12
- { nodes: options.auth.commands.map((command) => cloneNode(command, CLI_SCOPE)), source: "auth" }
12
+ { nodes: options.auth.commands.map((command) => cloneCommandNode(command, CLI_SCOPE)), source: "auth" }
13
13
  ]);
14
14
  return {
15
15
  name: options.name,
@@ -33,11 +33,11 @@ function mergeChildren(entries) {
33
33
  // defineGroup snapshots its children at construction time, while mergeInto mutates an
34
34
  // existing group's children after that snapshot. Re-cloning here re-materializes each
35
35
  // merged group so nesting client.root under another group preserves the merged children.
36
- return merged.map((node) => cloneNode(node));
36
+ return merged.map((node) => cloneCommandNode(node));
37
37
  }
38
38
  function mergeInto(target, incoming, path, source, nodeSources) {
39
39
  for (const candidate of incoming) {
40
- const nextNode = cloneNode(candidate);
40
+ const nextNode = cloneCommandNode(candidate);
41
41
  registerSource(nextNode, source, nodeSources);
42
42
  const existing = target.find((node) => node.name === nextNode.name);
43
43
  if (existing === undefined) {
@@ -68,46 +68,6 @@ function getRegisteredSource(nodeSources, node) {
68
68
  function createCollisionError(path, left, right) {
69
69
  return new UserError(`Command path ${JSON.stringify(path.join(" "))} is defined more than once (${left} and ${right}).`);
70
70
  }
71
- function cloneNode(node, scopeOverride) {
72
- if (node.kind === "command") {
73
- return cloneCommand(node, scopeOverride);
74
- }
75
- return cloneGroup(node, scopeOverride);
76
- }
77
- function cloneCommand(command, scopeOverride) {
78
- return defineCommand({
79
- name: command.name,
80
- hidden: command.hidden,
81
- description: command.description,
82
- examples: command.examples.map((example) => ({
83
- title: example.title,
84
- params: { ...example.params }
85
- })),
86
- aliases: [...command.aliases],
87
- positional: [...command.positional],
88
- params: command.params,
89
- secrets: { ...command.secrets },
90
- scope: [...(scopeOverride ?? command.scope)],
91
- confirm: command.confirm,
92
- requires: command.requires,
93
- handler: command.handler,
94
- render: command.render
95
- });
96
- }
97
- function cloneGroup(group, scopeOverride) {
98
- const children = group.children.map((child) => cloneNode(child, scopeOverride));
99
- const defaultCommand = findCommand(children, group.default?.name);
100
- return defineGroup({
101
- name: group.name,
102
- description: group.description,
103
- aliases: [...group.aliases],
104
- scope: cloneScope(group.scope, scopeOverride),
105
- secrets: { ...group.secrets },
106
- requires: group.requires,
107
- children,
108
- default: defaultCommand
109
- });
110
- }
111
71
  function validateClientName(name) {
112
72
  if (!isValidClientName(name)) {
113
73
  throw new UserError(`Client name ${JSON.stringify(name)} must use lowercase letters, numbers, and hyphens only.`);
@@ -131,23 +91,3 @@ function isValidClientName(name) {
131
91
  }
132
92
  return true;
133
93
  }
134
- function cloneScope(scope, scopeOverride) {
135
- if (scopeOverride !== undefined) {
136
- return [...scopeOverride];
137
- }
138
- if (scope === undefined) {
139
- return undefined;
140
- }
141
- return [...scope];
142
- }
143
- function findCommand(nodes, name) {
144
- if (name === undefined) {
145
- return undefined;
146
- }
147
- for (const node of nodes) {
148
- if (node.kind === "command" && node.name === name) {
149
- return node;
150
- }
151
- }
152
- return undefined;
153
- }
@@ -13,6 +13,10 @@ export interface OpenApiTagObject {
13
13
  }
14
14
  export interface OpenApiDocument {
15
15
  openapi?: string;
16
+ swagger?: string;
17
+ host?: string;
18
+ schemes?: string[];
19
+ basePath?: string;
16
20
  info?: {
17
21
  title?: string;
18
22
  version?: string;
@@ -31,6 +35,7 @@ export interface OpenApiDocument {
31
35
  }
32
36
  export interface OpenApiPathItemObject extends OpenApiOperationMap {
33
37
  parameters?: OpenApiParameter[];
38
+ servers?: OpenApiServerObject[];
34
39
  }
35
40
  export interface OpenApiOperationObject {
36
41
  tags?: string[];
@@ -100,6 +105,11 @@ export interface OpenApiReferenceObject {
100
105
  interface OpenApiServerObject {
101
106
  url: string;
102
107
  description?: string;
108
+ variables?: Record<string, {
109
+ default: string;
110
+ enum?: string[];
111
+ description?: string;
112
+ }>;
103
113
  }
104
114
  type OpenApiSecurityRequirementObject = Record<string, string[]>;
105
115
  export interface GenerateOptions {
package/dist/generate.js CHANGED
@@ -263,7 +263,7 @@ function getOwnPathItemValue(pathItem, key) {
263
263
  function createGeneratedCommand(document, entry) {
264
264
  const operation = expectOperation(document, entry.operation, entry.method, entry.path);
265
265
  const operationId = operation.operationId ?? `${entry.method.toUpperCase()} ${entry.path}`;
266
- const operationBaseUrl = resolveOperationBaseUrl(operation, operationId);
266
+ const operationBaseUrl = resolveOperationBaseUrl(operation.servers ?? entry.pathItem.servers, operationId);
267
267
  const auth = getOperationAuthMode(document, operation, operationId);
268
268
  const response = resolveSuccessResponse(document, operation, operationId);
269
269
  const noun = createSafeGeneratedNoun(deriveNoun(operation, entry.path, operationId));
@@ -330,12 +330,12 @@ function collectPathPositionals(pathTemplate, params, operationId) {
330
330
  }
331
331
  return positionals;
332
332
  }
333
- function resolveOperationBaseUrl(operation, operationId) {
334
- if (operation.servers === undefined) {
333
+ function resolveOperationBaseUrl(servers, operationId) {
334
+ if (servers === undefined) {
335
335
  return undefined;
336
336
  }
337
- const [server] = operation.servers;
338
- if (operation.servers.length !== 1 || server === undefined || server.url.includes("{")) {
337
+ const [server] = servers;
338
+ if (servers.length !== 1 || server === undefined || server.url.includes("{")) {
339
339
  throw new UserError(`Operation ${JSON.stringify(operationId)} must define exactly one fixed per-operation server URL in v1.`);
340
340
  }
341
341
  try {
package/dist/http.js CHANGED
@@ -2,8 +2,8 @@ import path from "node:path";
2
2
  import { isIP } from "node:net";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { text as designText } from "toolcraft-design";
5
- import { HttpError, UserError, createHttpError, shouldEmitDiagnostic } from "toolcraft";
6
- import { classifyNetworkError } from "./network-error.js";
5
+ import { HttpError, UserError, createHttpError, redactHttpBody, shouldEmitDiagnostic } from "toolcraft";
6
+ import { classifyNetworkError, isAbortError } from "./network-error.js";
7
7
  import { redactHeaders, redactHeaderValue, redactSensitiveQueryValues } from "./redaction.js";
8
8
  export { HttpError };
9
9
  const TRANSCRIPT_BODY_BYTE_LIMIT = 4 * 1024;
@@ -33,7 +33,8 @@ export async function requestJson(options) {
33
33
  }
34
34
  : {};
35
35
  const headers = createHeaders(token, hasBody, { ...options.headers, ...idempotencyHeader }, options.accept, options.bodyMode, options.contentType);
36
- emitHttpDebug(options, `${method} ${url}`, { method, url });
36
+ const diagnosticUrl = redactSensitiveQueryValues(url);
37
+ emitHttpDebug(options, `${method} ${diagnosticUrl}`, { method, url: diagnosticUrl });
37
38
  emitHttpTrace(options, "HTTP request transcript", () => formatVerboseRequestTranscript(method, url, headers, options.body));
38
39
  const response = await fetchWithRetries(options, url, {
39
40
  method,
@@ -120,34 +121,41 @@ async function fetchWithRetries(options, url, init) {
120
121
  const fetchImpl = options.fetch ?? globalThis.fetch;
121
122
  const retries = options.retries;
122
123
  const maxRetries = retries?.max ?? 0;
124
+ const diagnosticUrl = redactSensitiveQueryValues(url);
123
125
  let attempt = 0;
124
126
  while (true) {
127
+ assertRequestActive(options.signal, diagnosticUrl);
128
+ let response;
125
129
  try {
126
- const response = await fetchImpl(url, init);
127
- if (retries === undefined ||
128
- attempt >= maxRetries ||
129
- !shouldRetryStatus(response.status, retries.retryOn)) {
130
- return response;
131
- }
132
- emitHttpDebug(options, `Retrying ${String(init.method ?? "GET")} ${url}`, {
133
- attempt: attempt + 1,
134
- status: response.status
135
- });
136
- await sleepBeforeRetry(response, retries, attempt);
137
- attempt += 1;
130
+ response = await fetchImpl(url, init);
138
131
  }
139
132
  catch (error) {
133
+ assertRequestActive(options.signal, diagnosticUrl);
140
134
  const classified = classifyNetworkError(error, url) ?? error;
141
- if (attempt >= maxRetries || retries === undefined) {
135
+ if (isAbortError(error) || attempt >= maxRetries || retries === undefined) {
142
136
  throw classified;
143
137
  }
144
- emitHttpDebug(options, `Retrying ${String(init.method ?? "GET")} ${url}`, {
138
+ emitHttpDebug(options, `Retrying ${String(init.method ?? "GET")} ${diagnosticUrl}`, {
145
139
  attempt: attempt + 1,
146
140
  error: classified instanceof Error ? classified.message : String(classified)
147
141
  });
148
- await sleepBeforeRetry(undefined, retries, attempt);
142
+ await sleepBeforeRetry(undefined, retries, attempt, options.signal, diagnosticUrl);
149
143
  attempt += 1;
144
+ continue;
150
145
  }
146
+ if (retries === undefined ||
147
+ attempt >= maxRetries ||
148
+ !shouldRetryStatus(response.status, retries.retryOn)) {
149
+ return response;
150
+ }
151
+ await response.body?.cancel();
152
+ assertRequestActive(options.signal, diagnosticUrl);
153
+ emitHttpDebug(options, `Retrying ${String(init.method ?? "GET")} ${diagnosticUrl}`, {
154
+ attempt: attempt + 1,
155
+ status: response.status
156
+ });
157
+ await sleepBeforeRetry(response, retries, attempt, options.signal, diagnosticUrl);
158
+ attempt += 1;
151
159
  }
152
160
  }
153
161
  function emitHttpDebug(options, message, data) {
@@ -175,10 +183,36 @@ function emitHttpTrace(options, message, createLines) {
175
183
  function shouldRetryStatus(status, retryOn) {
176
184
  return retryOn?.includes(status) === true;
177
185
  }
178
- async function sleepBeforeRetry(response, retries, attempt) {
186
+ async function sleepBeforeRetry(response, retries, attempt, signal, diagnosticUrl) {
187
+ assertRequestActive(signal, diagnosticUrl);
179
188
  const retryAfter = response?.headers.get("retry-after");
180
189
  const delay = parseRetryAfter(retryAfter) ?? calculateBackoffDelay(attempt, retries.random);
181
- await (retries.sleep ?? defaultSleep)(delay);
190
+ assertRequestActive(signal, diagnosticUrl);
191
+ let timer;
192
+ let onAbort;
193
+ try {
194
+ await new Promise((resolve, reject) => {
195
+ onAbort = () => reject(new UserError(`Request aborted: ${diagnosticUrl}.`, { cause: signal?.reason }));
196
+ signal?.addEventListener("abort", onAbort, { once: true });
197
+ if (retries.sleep === undefined) {
198
+ timer = setTimeout(resolve, delay);
199
+ }
200
+ else {
201
+ retries.sleep(delay).then(resolve, reject);
202
+ }
203
+ });
204
+ }
205
+ finally {
206
+ if (timer !== undefined)
207
+ clearTimeout(timer);
208
+ if (onAbort !== undefined)
209
+ signal?.removeEventListener("abort", onAbort);
210
+ }
211
+ }
212
+ function assertRequestActive(signal, diagnosticUrl) {
213
+ if (signal?.aborted) {
214
+ throw new UserError(`Request aborted: ${diagnosticUrl}.`, { cause: signal.reason });
215
+ }
182
216
  }
183
217
  function parseRetryAfter(value) {
184
218
  if (value === null || value === undefined) {
@@ -198,9 +232,6 @@ function calculateBackoffDelay(attempt, random) {
198
232
  const base = 100 * 2 ** attempt;
199
233
  return Math.floor(base * (random ?? Math.random)());
200
234
  }
201
- function defaultSleep(ms) {
202
- return new Promise((resolve) => setTimeout(resolve, ms));
203
- }
204
235
  function formatRawResponseResult(data, response, rawResponse) {
205
236
  return rawResponse === true ? { data, response } : data;
206
237
  }
@@ -243,7 +274,7 @@ export async function prepareMultipartFileInputs(requestShape, options) {
243
274
  };
244
275
  }
245
276
  async function resolveMultipartSource(source, runtime) {
246
- if (URL.canParse(source) && source.includes(":")) {
277
+ if (path.parse(source).root.length === 0 && URL.canParse(source) && source.includes(":")) {
247
278
  const sourceUrl = new URL(source);
248
279
  validateMultipartUrl(sourceUrl, runtime.field);
249
280
  return downloadMultipartSource(sourceUrl, runtime);
@@ -264,43 +295,70 @@ async function resolveMultipartSource(source, runtime) {
264
295
  }
265
296
  async function downloadMultipartSource(initialUrl, runtime) {
266
297
  let url = initialUrl;
267
- const timeoutSignal = AbortSignal.timeout(MULTIPART_DOWNLOAD_TIMEOUT_MS);
268
- const signal = runtime.signal === undefined
269
- ? timeoutSignal
270
- : AbortSignal.any([runtime.signal, timeoutSignal]);
271
- for (let redirects = 0; redirects <= MULTIPART_REDIRECT_LIMIT; redirects += 1) {
272
- validateMultipartUrl(url, runtime.field);
273
- let response;
274
- try {
275
- response = await runtime.fetch(url, { redirect: "manual", signal });
276
- }
277
- catch {
278
- throw new UserError(`Could not download multipart field ${JSON.stringify(runtime.field)} source ${JSON.stringify(redactMultipartUrl(url))}.`);
279
- }
280
- if (response.status >= 300 && response.status < 400) {
281
- const location = response.headers.get("location");
282
- if (location === null || redirects === MULTIPART_REDIRECT_LIMIT) {
283
- throw new UserError(`Multipart field ${JSON.stringify(runtime.field)} source ${JSON.stringify(redactMultipartUrl(initialUrl))} exceeded the redirect limit.`);
298
+ const controller = new AbortController();
299
+ const abort = () => controller.abort(runtime.signal?.reason);
300
+ const timeout = setTimeout(() => {
301
+ controller.abort(new DOMException("Multipart source download timed out.", "TimeoutError"));
302
+ }, MULTIPART_DOWNLOAD_TIMEOUT_MS);
303
+ timeout.unref();
304
+ if (runtime.signal?.aborted)
305
+ abort();
306
+ else
307
+ runtime.signal?.addEventListener("abort", abort, { once: true });
308
+ try {
309
+ for (let redirects = 0; redirects <= MULTIPART_REDIRECT_LIMIT; redirects += 1) {
310
+ validateMultipartUrl(url, runtime.field);
311
+ let response;
312
+ try {
313
+ try {
314
+ controller.signal.throwIfAborted();
315
+ response = await runtime.fetch(url, { redirect: "manual", signal: controller.signal });
316
+ controller.signal.throwIfAborted();
317
+ }
318
+ catch {
319
+ throw new UserError(`Could not download multipart field ${JSON.stringify(runtime.field)} source ${JSON.stringify(redactMultipartUrl(url))}.`);
320
+ }
321
+ if (response.status >= 300 && response.status < 400) {
322
+ const location = response.headers.get("location");
323
+ if (location === null || redirects === MULTIPART_REDIRECT_LIMIT) {
324
+ throw new UserError(`Multipart field ${JSON.stringify(runtime.field)} source ${JSON.stringify(redactMultipartUrl(initialUrl))} exceeded the redirect limit.`);
325
+ }
326
+ url = new URL(location, url);
327
+ continue;
328
+ }
329
+ if (!response.ok) {
330
+ throw new UserError(`Multipart field ${JSON.stringify(runtime.field)} source ${JSON.stringify(redactMultipartUrl(url))} returned HTTP ${response.status}.`);
331
+ }
332
+ const declaredLength = Number(response.headers.get("content-length"));
333
+ if (Number.isFinite(declaredLength) && declaredLength > MULTIPART_FILE_BYTE_LIMIT) {
334
+ throw new UserError(`Multipart field ${JSON.stringify(runtime.field)} source ${JSON.stringify(redactMultipartUrl(url))} exceeds the 100 MiB file limit.`);
335
+ }
336
+ const bytes = await readMultipartResponse(response, url, runtime);
337
+ controller.signal.throwIfAborted();
338
+ accountMultipartBytes(bytes.byteLength, redactMultipartUrl(url), runtime);
339
+ return {
340
+ data: Buffer.from(bytes).toString("base64"),
341
+ filename: selectRemoteFilename(response, url, runtime.field),
342
+ contentType: normalizeContentType(response.headers.get("content-type"))
343
+ };
344
+ }
345
+ finally {
346
+ if (response?.body && !response.bodyUsed) {
347
+ try {
348
+ await response.body.cancel();
349
+ }
350
+ catch {
351
+ controller.abort();
352
+ }
353
+ }
284
354
  }
285
- url = new URL(location, url);
286
- continue;
287
- }
288
- if (!response.ok) {
289
- throw new UserError(`Multipart field ${JSON.stringify(runtime.field)} source ${JSON.stringify(redactMultipartUrl(url))} returned HTTP ${response.status}.`);
290
- }
291
- const declaredLength = Number(response.headers.get("content-length"));
292
- if (Number.isFinite(declaredLength) && declaredLength > MULTIPART_FILE_BYTE_LIMIT) {
293
- throw new UserError(`Multipart field ${JSON.stringify(runtime.field)} source ${JSON.stringify(redactMultipartUrl(url))} exceeds the 100 MiB file limit.`);
294
355
  }
295
- const bytes = await readMultipartResponse(response, url, runtime);
296
- accountMultipartBytes(bytes.byteLength, redactMultipartUrl(url), runtime);
297
- return {
298
- data: Buffer.from(bytes).toString("base64"),
299
- filename: selectRemoteFilename(response, url, runtime.field),
300
- contentType: normalizeContentType(response.headers.get("content-type"))
301
- };
356
+ throw new UserError("Unexpected multipart redirect state.");
357
+ }
358
+ finally {
359
+ clearTimeout(timeout);
360
+ runtime.signal?.removeEventListener("abort", abort);
302
361
  }
303
- throw new UserError("Unexpected multipart redirect state.");
304
362
  }
305
363
  async function readMultipartResponse(response, url, runtime) {
306
364
  if (response.body === null)
@@ -412,7 +470,18 @@ function buildRequestUrl(options) {
412
470
  ? baseUrl.pathname.slice(0, -1)
413
471
  : baseUrl.pathname;
414
472
  const normalizedPath = resolvedPath.startsWith("/") ? resolvedPath : `/${resolvedPath}`;
415
- baseUrl.pathname = `${normalizedBasePath}${normalizedPath}`;
473
+ const requestedPath = `${normalizedBasePath}${normalizedPath}`;
474
+ const templatePath = options.path.replace(/\{([^}]+)\}/g, "_");
475
+ if (templatePath !== options.path) {
476
+ const pathShape = new URL(baseUrl);
477
+ pathShape.pathname = `${requestedPath}/_`;
478
+ const segmentCount = pathShape.pathname.split("/").length;
479
+ pathShape.pathname = `${normalizedBasePath}${templatePath.startsWith("/") ? "" : "/"}${templatePath}/_`;
480
+ if (segmentCount !== pathShape.pathname.split("/").length) {
481
+ throw new UserError("Path parameters must not form dot-only URL segments.");
482
+ }
483
+ }
484
+ baseUrl.pathname = requestedPath;
416
485
  for (const [key, value] of Object.entries(options.query ?? {})) {
417
486
  appendQueryValue(baseUrl.searchParams, key, value);
418
487
  }
@@ -648,8 +717,10 @@ function formatTranscriptLine(line) {
648
717
  return designText.muted(line);
649
718
  }
650
719
  function formatTranscriptBody(body) {
651
- const formatted = typeof body === "string" ? body : JSON.stringify(body, null, 2);
652
- return truncateTranscriptBody(formatted ?? String(body));
720
+ const serialized = typeof body === "string" ? body : JSON.stringify(body);
721
+ const redacted = redactHttpBody(serialized);
722
+ const formatted = typeof redacted === "string" ? redacted : JSON.stringify(redacted, null, 2);
723
+ return truncateTranscriptBody(formatted ?? String(redacted));
653
724
  }
654
725
  function indentTranscriptBlock(value) {
655
726
  return value.split("\n").map((line) => ` ${line}`);
@@ -1,2 +1,3 @@
1
1
  import { UserError } from "toolcraft";
2
2
  export declare function classifyNetworkError(error: unknown, url: string): UserError | null;
3
+ export declare function isAbortError(error: unknown): boolean;
@@ -31,7 +31,7 @@ export function classifyNetworkError(error, url) {
31
31
  case "UND_ERR_BODY_TIMEOUT":
32
32
  return new UserError(`Request timed out: ${redactedUrl}.`, { cause: error });
33
33
  }
34
- if (findAbortError(error) !== null) {
34
+ if (isAbortError(error)) {
35
35
  return new UserError(`Request aborted: ${redactedUrl}.`, { cause: error });
36
36
  }
37
37
  if (error instanceof TypeError && error.message === "fetch failed" && !hasCause(error)) {
@@ -41,7 +41,9 @@ export function classifyNetworkError(error, url) {
41
41
  }
42
42
  function findNetworkError(error) {
43
43
  let current = error;
44
- while (isErrorLikeObject(current)) {
44
+ const visited = new Set();
45
+ while (isErrorLikeObject(current) && !visited.has(current)) {
46
+ visited.add(current);
45
47
  if (readStringProperty(current, "code") !== undefined) {
46
48
  return current;
47
49
  }
@@ -49,18 +51,17 @@ function findNetworkError(error) {
49
51
  }
50
52
  return null;
51
53
  }
52
- function isAbortError(error) {
53
- return isErrorLikeObject(error) && error.name === "AbortError";
54
- }
55
- function findAbortError(error) {
54
+ export function isAbortError(error) {
56
55
  let current = error;
57
- while (isErrorLikeObject(current)) {
58
- if (isAbortError(current)) {
59
- return current;
56
+ const visited = new Set();
57
+ while (isErrorLikeObject(current) && !visited.has(current)) {
58
+ visited.add(current);
59
+ if (current.name === "AbortError") {
60
+ return true;
60
61
  }
61
62
  current = readOwnProperty(current, "cause");
62
63
  }
63
- return null;
64
+ return false;
64
65
  }
65
66
  function hasCause(error) {
66
67
  return readOwnProperty(error, "cause") !== undefined;
package/dist/redaction.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { isSensitiveName } from "toolcraft";
1
2
  const SENSITIVE_QUERY_KEYS = new Set([
2
3
  "apikey",
3
4
  "accesstoken",
@@ -19,7 +20,7 @@ export function redactHeaderValue(key, value) {
19
20
  if (normalizedKey === "authorization") {
20
21
  return value.startsWith("Bearer ") ? "Bearer ****" : "****";
21
22
  }
22
- if (SENSITIVE_HEADER_NAMES.has(normalizedKey)) {
23
+ if (SENSITIVE_HEADER_NAMES.has(normalizedKey) || isSensitiveName(key)) {
23
24
  return "****";
24
25
  }
25
26
  return value;
package/dist/runtime.d.ts CHANGED
@@ -20,6 +20,7 @@ export type DefineClientFromSpecOptions<TServices extends object = Record<string
20
20
  };
21
21
  export interface ResolveOpenApiBaseUrlOptions {
22
22
  document: OpenApiDocument;
23
+ sourceUrl?: string | URL;
23
24
  environments?: Record<string, string>;
24
25
  environment?: string;
25
26
  env?: Record<string, string | undefined>;
package/dist/runtime.js CHANGED
@@ -29,6 +29,7 @@ export async function defineClientFromSpec(spec, options) {
29
29
  const resolvedBaseUrl = baseUrl ??
30
30
  resolveOpenApiBaseUrl({
31
31
  document,
32
+ sourceUrl: resolved.sourceUrl,
32
33
  environments: config?.environments,
33
34
  environment,
34
35
  env: env ?? process.env
@@ -56,6 +57,7 @@ async function resolveDocument(source, options) {
56
57
  });
57
58
  return {
58
59
  document: loaded.document,
60
+ sourceUrl: loaded.sourceUrl,
59
61
  ...(loaded.commit === undefined ? {} : { commit: loaded.commit })
60
62
  };
61
63
  }
@@ -89,17 +91,83 @@ export function resolveOpenApiBaseUrl(options) {
89
91
  const selectedName = options.environment ?? options.env?.TOOLCRAFT_OPENAPI_ENV ?? Object.keys(environments)[0];
90
92
  const selectedUrl = selectedName === undefined ? undefined : environments[selectedName];
91
93
  if (selectedUrl !== undefined) {
92
- return normalizeBaseUrl(selectedUrl);
94
+ return normalizeBaseUrl(selectedUrl, `environments[${JSON.stringify(selectedName)}]`);
93
95
  }
94
96
  if (selectedName !== undefined) {
95
97
  throw new UserError(`Unknown OpenAPI environment ${JSON.stringify(selectedName)}. Available: ${Object.keys(environments).join(", ")}.`);
96
98
  }
97
99
  }
98
- const server = options.document.servers?.[0]?.url;
99
- return server === undefined ? undefined : normalizeBaseUrl(server);
100
+ const document = options.document;
101
+ if (document.swagger === "2.0") {
102
+ if (document.host !== undefined && typeof document.host !== "string") {
103
+ throw new UserError("OpenAPI Swagger host must be a string.");
104
+ }
105
+ if (document.schemes !== undefined && !Array.isArray(document.schemes)) {
106
+ throw new UserError("OpenAPI Swagger schemes must be an array.");
107
+ }
108
+ if (document.schemes !== undefined && document.schemes.length > 0 && typeof document.schemes[0] !== "string") {
109
+ throw new UserError("OpenAPI Swagger schemes[0] must be a string.");
110
+ }
111
+ if (document.basePath !== undefined && (typeof document.basePath !== "string" || !document.basePath.startsWith("/"))) {
112
+ throw new UserError("OpenAPI Swagger basePath must be a string starting with '/'.");
113
+ }
114
+ const source = options.sourceUrl === undefined ? undefined : new URL(options.sourceUrl);
115
+ const host = document.host ?? source?.host;
116
+ const scheme = document.schemes?.[0] ?? source?.protocol.slice(0, -1);
117
+ if (host === undefined || scheme === undefined)
118
+ return undefined;
119
+ return normalizeBaseUrl(`${scheme}://${host}${document.basePath ?? "/"}`, "Swagger host/schemes/basePath");
120
+ }
121
+ if (document.servers !== undefined && !Array.isArray(document.servers)) {
122
+ throw new UserError("OpenAPI servers must be an array.");
123
+ }
124
+ if (document.servers === undefined || document.servers.length === 0) {
125
+ return options.sourceUrl === undefined
126
+ ? undefined
127
+ : normalizeBaseUrl("/", "servers[0].url", options.sourceUrl);
128
+ }
129
+ const server = document.servers[0];
130
+ if (server === null || typeof server !== "object" || Array.isArray(server)) {
131
+ throw new UserError("OpenAPI servers[0] must be an object.");
132
+ }
133
+ if (typeof server.url !== "string") {
134
+ throw new UserError("OpenAPI servers[0].url must be a string.");
135
+ }
136
+ let expanded = "";
137
+ let offset = 0;
138
+ while (offset < server.url.length) {
139
+ const start = server.url.indexOf("{", offset);
140
+ if (start === -1) {
141
+ expanded += server.url.slice(offset);
142
+ break;
143
+ }
144
+ expanded += server.url.slice(offset, start);
145
+ const end = server.url.indexOf("}", start + 1);
146
+ if (end === -1) {
147
+ throw new UserError("OpenAPI servers[0].url contains an unterminated server variable.");
148
+ }
149
+ const name = server.url.slice(start + 1, end);
150
+ const value = server.variables?.[name]?.default;
151
+ if (typeof value !== "string") {
152
+ throw new UserError(`OpenAPI servers[0].variables[${JSON.stringify(name)}].default must be a string.`);
153
+ }
154
+ expanded += value;
155
+ offset = end + 1;
156
+ }
157
+ return normalizeBaseUrl(expanded, "servers[0].url", options.sourceUrl);
100
158
  }
101
- function normalizeBaseUrl(value) {
102
- return new URL(value).toString().replace(/\/$/, "");
159
+ function normalizeBaseUrl(value, field, sourceUrl) {
160
+ let url;
161
+ try {
162
+ url = new URL(value, sourceUrl);
163
+ }
164
+ catch {
165
+ throw new UserError(`OpenAPI ${field} must resolve to an absolute URL. Pass baseUrl for a relative server without a remote document origin.`);
166
+ }
167
+ const normalized = url.toString();
168
+ return normalized.endsWith("/") && url.search === "" && url.hash === ""
169
+ ? normalized.slice(0, -1)
170
+ : normalized;
103
171
  }
104
172
  function createRuntimeNodes(document, config) {
105
173
  const commands = collectGeneratedCommands(document, config);
@@ -35,6 +35,7 @@ export interface OpenApiSpecCacheFileSystem extends OpenApiSourceFileSystem {
35
35
  }
36
36
  export interface LoadedOpenApiSource {
37
37
  sourceText: string;
38
+ sourceUrl: string;
38
39
  document: OpenApiDocument;
39
40
  commit?: () => Promise<void>;
40
41
  }