loadam 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.js ADDED
@@ -0,0 +1,3083 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/program.ts
4
+ import { Command } from "commander";
5
+
6
+ // src/commands/auth.ts
7
+ import { readFile } from "fs/promises";
8
+
9
+ // ../auth/dist/index.js
10
+ function tokenizeCurl(input) {
11
+ const collapsed = input.replace(/\\\r?\n/g, " ").trim();
12
+ const tokens = [];
13
+ let buf = "";
14
+ let i = 0;
15
+ let quote = null;
16
+ while (i < collapsed.length) {
17
+ const ch = collapsed[i];
18
+ if (quote) {
19
+ if (ch === "\\" && quote === '"' && collapsed[i + 1] !== void 0) {
20
+ buf += collapsed[i + 1];
21
+ i += 2;
22
+ continue;
23
+ }
24
+ if (ch === quote) {
25
+ quote = null;
26
+ i++;
27
+ continue;
28
+ }
29
+ buf += ch;
30
+ i++;
31
+ continue;
32
+ }
33
+ if (ch === '"' || ch === "'") {
34
+ quote = ch;
35
+ i++;
36
+ continue;
37
+ }
38
+ if (ch === "\\" && collapsed[i + 1] !== void 0) {
39
+ buf += collapsed[i + 1];
40
+ i += 2;
41
+ continue;
42
+ }
43
+ if (/\s/.test(ch)) {
44
+ if (buf.length > 0) {
45
+ tokens.push(buf);
46
+ buf = "";
47
+ }
48
+ i++;
49
+ continue;
50
+ }
51
+ buf += ch;
52
+ i++;
53
+ }
54
+ if (buf.length > 0) tokens.push(buf);
55
+ if (quote) {
56
+ throw new Error(`Unterminated ${quote} quote in curl command`);
57
+ }
58
+ return tokens;
59
+ }
60
+ function importCurl(input) {
61
+ const tokens = tokenizeCurl(input);
62
+ const headers = {};
63
+ const notes = [];
64
+ let url;
65
+ let method;
66
+ let basicCred;
67
+ for (let i = 0; i < tokens.length; i++) {
68
+ const t = tokens[i];
69
+ if (t === "curl") continue;
70
+ if ((t === "-H" || t === "--header") && tokens[i + 1] !== void 0) {
71
+ const raw = tokens[++i];
72
+ const idx = raw.indexOf(":");
73
+ if (idx > 0) {
74
+ const name = raw.slice(0, idx).trim();
75
+ const value = raw.slice(idx + 1).trim();
76
+ headers[name.toLowerCase()] = value;
77
+ }
78
+ continue;
79
+ }
80
+ if ((t === "-u" || t === "--user") && tokens[i + 1] !== void 0) {
81
+ basicCred = tokens[++i];
82
+ continue;
83
+ }
84
+ if ((t === "-X" || t === "--request") && tokens[i + 1] !== void 0) {
85
+ method = tokens[++i].toUpperCase();
86
+ continue;
87
+ }
88
+ if (t === "-d" || t === "--data" || t === "--data-raw" || t === "--data-binary" || t === "-b" || t === "--cookie" || t === "-A" || t === "--user-agent" || t === "-e" || t === "--referer" || t === "-o" || t === "--output") {
89
+ i++;
90
+ continue;
91
+ }
92
+ if (t.startsWith("-") && t !== "--") continue;
93
+ if (!url && /^https?:\/\//i.test(t)) {
94
+ url = t;
95
+ }
96
+ }
97
+ const profile = inferProfile({ headers, basicCred, url, notes });
98
+ return { profile, headers, url, method, tokens, notes };
99
+ }
100
+ function inferProfile(args) {
101
+ const { headers, basicCred, url, notes } = args;
102
+ const authz = headers.authorization;
103
+ if (authz) {
104
+ const match = authz.match(/^Bearer\s+(.+)$/i);
105
+ if (match) {
106
+ notes.push("Detected Bearer token in Authorization header.");
107
+ return { id: "bearer", kind: "bearer", tokenEnv: "API_TOKEN" };
108
+ }
109
+ const basicMatch = authz.match(/^Basic\s+/i);
110
+ if (basicMatch) {
111
+ notes.push("Detected Basic auth in Authorization header.");
112
+ return {
113
+ id: "basic",
114
+ kind: "basic",
115
+ userEnv: "API_USER",
116
+ passEnv: "API_PASSWORD"
117
+ };
118
+ }
119
+ }
120
+ const apiKeyHeader = findApiKeyHeader(headers);
121
+ if (apiKeyHeader) {
122
+ notes.push(`Detected API key header: ${apiKeyHeader}`);
123
+ return {
124
+ id: "apiKey",
125
+ kind: "apiKey",
126
+ in: "header",
127
+ name: apiKeyHeader,
128
+ valueEnv: "API_KEY"
129
+ };
130
+ }
131
+ if (basicCred) {
132
+ notes.push("Detected -u credentials (Basic auth).");
133
+ return {
134
+ id: "basic",
135
+ kind: "basic",
136
+ userEnv: "API_USER",
137
+ passEnv: "API_PASSWORD"
138
+ };
139
+ }
140
+ if (url) {
141
+ try {
142
+ const u = new URL(url);
143
+ const apiKeyParam = ["api_key", "apikey", "key", "access_token", "token"].find(
144
+ (k) => u.searchParams.has(k)
145
+ );
146
+ if (apiKeyParam) {
147
+ notes.push(`Detected API key in query parameter: ${apiKeyParam}`);
148
+ return {
149
+ id: "apiKey",
150
+ kind: "apiKey",
151
+ in: "query",
152
+ name: apiKeyParam,
153
+ valueEnv: "API_KEY"
154
+ };
155
+ }
156
+ } catch {
157
+ }
158
+ }
159
+ return null;
160
+ }
161
+ var API_KEY_HEADER_PATTERNS = [
162
+ /^x-api-key$/i,
163
+ /^api-key$/i,
164
+ /^x-auth-token$/i,
165
+ /^x-access-token$/i
166
+ ];
167
+ function findApiKeyHeader(headers) {
168
+ for (const name of Object.keys(headers)) {
169
+ if (API_KEY_HEADER_PATTERNS.some((rx) => rx.test(name))) {
170
+ return name.split("-").map((s) => s.charAt(0).toUpperCase() + s.slice(1).toLowerCase()).join("-");
171
+ }
172
+ }
173
+ return null;
174
+ }
175
+
176
+ // src/commands/auth.ts
177
+ import { consola as consola2 } from "consola";
178
+
179
+ // src/util/errors.ts
180
+ import { consola } from "consola";
181
+ import { ZodError } from "zod";
182
+ function withFriendlyErrors(fn) {
183
+ return async (...args) => {
184
+ try {
185
+ await fn(...args);
186
+ } catch (err) {
187
+ reportError(err);
188
+ process.exit(1);
189
+ }
190
+ };
191
+ }
192
+ function reportError(err) {
193
+ if (err instanceof ZodError) {
194
+ consola.error("Invalid IR \u2014 the spec produced a structurally invalid model.");
195
+ for (const issue of err.issues.slice(0, 5)) {
196
+ const path = issue.path.length > 0 ? issue.path.join(".") : "<root>";
197
+ consola.log(` \u2022 ${path}: ${issue.message}`);
198
+ }
199
+ if (err.issues.length > 5) {
200
+ consola.log(` \u2026and ${err.issues.length - 5} more.`);
201
+ }
202
+ consola.log("");
203
+ consola.log("Hint: this usually means the spec uses a feature loadam does not yet model.");
204
+ consola.log(" Open an issue with the spec attached.");
205
+ return;
206
+ }
207
+ const e = err;
208
+ if (e?.code === "ENOENT") {
209
+ consola.error(`File not found: ${e.path ?? "<unknown>"}`);
210
+ consola.log("Hint: pass an absolute or workspace-relative path to the spec.");
211
+ return;
212
+ }
213
+ const msg = e?.message ?? String(err);
214
+ if (/^Cannot find module/i.test(msg) || /SyntaxError/.test(msg)) {
215
+ consola.error(`Failed to parse spec: ${msg}`);
216
+ consola.log("Hint: confirm the file is valid YAML or JSON.");
217
+ return;
218
+ }
219
+ consola.error(msg);
220
+ }
221
+
222
+ // src/commands/auth.ts
223
+ function registerAuthCommands(program) {
224
+ const auth = program.command("auth").description("Auth helpers");
225
+ auth.command("import").description(
226
+ "Parse a curl command and infer an auth profile. Reads from --file, then stdin, then args."
227
+ ).option("-f, --file <path>", "read curl command from a file").option("--json", "emit JSON instead of pretty output", false).argument("[curl...]", "inline curl command").action(withFriendlyErrors(runAuthImport));
228
+ }
229
+ async function runAuthImport(curlArgs, opts) {
230
+ const input = await loadCurlInput(curlArgs, opts);
231
+ if (!input.trim()) {
232
+ consola2.error("No curl command provided. Pass via --file, stdin, or as arguments.");
233
+ process.exit(2);
234
+ }
235
+ const result = importCurl(input);
236
+ if (opts.json) {
237
+ process.stdout.write(`${JSON.stringify(result, null, 2)}
238
+ `);
239
+ return;
240
+ }
241
+ if (result.profile) {
242
+ consola2.success(`Detected auth profile: ${result.profile.kind} (id: ${result.profile.id})`);
243
+ consola2.log(JSON.stringify(result.profile, null, 2));
244
+ } else {
245
+ consola2.warn("No recognizable auth profile found in this curl.");
246
+ }
247
+ if (result.notes.length > 0) {
248
+ consola2.info("Notes:");
249
+ for (const n of result.notes) consola2.log(` \xB7 ${n}`);
250
+ }
251
+ if (result.url) consola2.info(`URL: ${result.url}`);
252
+ }
253
+ async function loadCurlInput(curlArgs, opts) {
254
+ if (opts.file) {
255
+ return await readFile(opts.file, "utf8");
256
+ }
257
+ if (curlArgs.length > 0) {
258
+ return curlArgs.join(" ");
259
+ }
260
+ if (!process.stdin.isTTY) {
261
+ return await readStdin();
262
+ }
263
+ return "";
264
+ }
265
+ function readStdin() {
266
+ return new Promise((resolvePromise, rejectPromise) => {
267
+ const chunks = [];
268
+ process.stdin.on("data", (chunk) => chunks.push(chunk));
269
+ process.stdin.on("end", () => resolvePromise(Buffer.concat(chunks).toString("utf8")));
270
+ process.stdin.on("error", rejectPromise);
271
+ });
272
+ }
273
+
274
+ // src/commands/completion.ts
275
+ var BASH = `# loadam bash completion. Install:
276
+ # loadam completion bash > ~/.loadam-completion.bash
277
+ # echo 'source ~/.loadam-completion.bash' >> ~/.bashrc
278
+ _loadam_complete() {
279
+ local cur prev cmds
280
+ COMPREPLY=()
281
+ cur="\${COMP_WORDS[COMP_CWORD]}"
282
+ cmds="init auth test contract diff mcp completion help -h --help -v --version"
283
+ if [ "$COMP_CWORD" -eq 1 ]; then
284
+ COMPREPLY=( $(compgen -W "$cmds" -- "$cur") )
285
+ return 0
286
+ fi
287
+ COMPREPLY=( $(compgen -f -- "$cur") )
288
+ }
289
+ complete -F _loadam_complete loadam
290
+ `;
291
+ var ZSH = `#compdef loadam
292
+ # loadam zsh completion. Install:
293
+ # loadam completion zsh > "\${fpath[1]}/_loadam"
294
+ # then restart your shell.
295
+ _loadam() {
296
+ local -a cmds
297
+ cmds=(
298
+ 'init:Parse spec and emit loadam.ir.json'
299
+ 'auth:Auth helpers (e.g. import from curl)'
300
+ 'test:Compile to k6 smoke + load tests'
301
+ 'contract:Compile to Schemathesis contract suite'
302
+ 'diff:Probe live API and report drift'
303
+ 'mcp:Compile to MCP server (stdio + HTTP)'
304
+ 'completion:Print shell completion script'
305
+ )
306
+ if (( CURRENT == 2 )); then
307
+ _describe 'command' cmds
308
+ else
309
+ _files
310
+ fi
311
+ }
312
+ _loadam "$@"
313
+ `;
314
+ var FISH = `# loadam fish completion. Install:
315
+ # loadam completion fish > ~/.config/fish/completions/loadam.fish
316
+ complete -c loadam -f
317
+ complete -c loadam -n __fish_use_subcommand -a init -d 'Parse spec to IR'
318
+ complete -c loadam -n __fish_use_subcommand -a auth -d 'Auth helpers'
319
+ complete -c loadam -n __fish_use_subcommand -a test -d 'Compile to k6 tests'
320
+ complete -c loadam -n __fish_use_subcommand -a contract -d 'Compile to Schemathesis suite'
321
+ complete -c loadam -n __fish_use_subcommand -a diff -d 'Spec-vs-live drift report'
322
+ complete -c loadam -n __fish_use_subcommand -a mcp -d 'Compile to MCP server'
323
+ complete -c loadam -n __fish_use_subcommand -a completion -d 'Print shell completion'
324
+ `;
325
+ function registerCompletionCommand(program) {
326
+ program.command("completion").description("Print shell completion script (bash | zsh | fish)").argument("<shell>", "shell name: bash, zsh, or fish").action((shell) => {
327
+ switch (shell) {
328
+ case "bash":
329
+ process.stdout.write(BASH);
330
+ return;
331
+ case "zsh":
332
+ process.stdout.write(ZSH);
333
+ return;
334
+ case "fish":
335
+ process.stdout.write(FISH);
336
+ return;
337
+ default:
338
+ process.stderr.write(`Unknown shell: ${shell}. Use bash, zsh, or fish.
339
+ `);
340
+ process.exit(1);
341
+ }
342
+ });
343
+ }
344
+
345
+ // src/commands/contract.ts
346
+ import { mkdir, readFile as readFile3, writeFile } from "fs/promises";
347
+ import { dirname, resolve as resolve2 } from "path";
348
+
349
+ // ../core/dist/index.js
350
+ import { z } from "zod";
351
+ import { readFile as readFile2 } from "fs/promises";
352
+ import { resolve } from "path";
353
+ import SwaggerParser from "@apidevtools/swagger-parser";
354
+ import { parse as parseYaml } from "yaml";
355
+ var IR_VERSION = "1";
356
+ var HttpMethod = z.enum(["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]);
357
+ var ResourceAction = z.enum([
358
+ "create",
359
+ "read",
360
+ "list",
361
+ "update",
362
+ "delete",
363
+ "search",
364
+ "action"
365
+ ]);
366
+ var Safety = z.enum(["safe", "mutating", "destructive"]);
367
+ var Idempotency = z.enum(["idempotent", "non-idempotent", "unknown"]);
368
+ var JsonSchema = z.unknown();
369
+ var Meta = z.object({
370
+ title: z.string(),
371
+ version: z.string(),
372
+ description: z.string().optional(),
373
+ source: z.object({
374
+ kind: z.enum(["openapi", "postman", "har", "grpc", "graphql"]),
375
+ sourceVersion: z.string(),
376
+ ingestedAt: z.string(),
377
+ sourceUri: z.string().optional()
378
+ })
379
+ });
380
+ var ServerVariable = z.object({
381
+ default: z.string(),
382
+ enum: z.array(z.string()).optional(),
383
+ description: z.string().optional()
384
+ });
385
+ var Server = z.object({
386
+ url: z.string(),
387
+ description: z.string().optional(),
388
+ variables: z.record(ServerVariable).optional()
389
+ });
390
+ var AuthProfile = z.discriminatedUnion("kind", [
391
+ z.object({ id: z.string(), kind: z.literal("none") }),
392
+ z.object({
393
+ id: z.string(),
394
+ kind: z.literal("bearer"),
395
+ tokenEnv: z.string().optional()
396
+ }),
397
+ z.object({
398
+ id: z.string(),
399
+ kind: z.literal("apiKey"),
400
+ in: z.enum(["header", "query", "cookie"]),
401
+ name: z.string(),
402
+ valueEnv: z.string().optional()
403
+ }),
404
+ z.object({
405
+ id: z.string(),
406
+ kind: z.literal("basic"),
407
+ userEnv: z.string().optional(),
408
+ passEnv: z.string().optional()
409
+ }),
410
+ z.object({
411
+ id: z.string(),
412
+ kind: z.literal("oauth2_cc"),
413
+ tokenUrl: z.string(),
414
+ clientIdEnv: z.string(),
415
+ clientSecretEnv: z.string(),
416
+ scopes: z.array(z.string()).optional()
417
+ }),
418
+ z.object({
419
+ id: z.string(),
420
+ kind: z.literal("custom"),
421
+ signerRef: z.string()
422
+ })
423
+ ]);
424
+ var AuthRef = z.object({
425
+ profileId: z.string(),
426
+ scopes: z.array(z.string()).optional()
427
+ });
428
+ var SchemaIdSchema = z.string();
429
+ var Schema = z.object({
430
+ id: SchemaIdSchema,
431
+ name: z.string().optional(),
432
+ jsonSchema: JsonSchema,
433
+ examples: z.array(z.unknown()).optional(),
434
+ _raw: z.unknown().optional()
435
+ });
436
+ var InlineSchema = z.object({
437
+ jsonSchema: JsonSchema
438
+ });
439
+ var SchemaRefOrInline = z.union([SchemaIdSchema, InlineSchema]);
440
+ var Param = z.object({
441
+ name: z.string(),
442
+ schema: SchemaRefOrInline,
443
+ required: z.boolean(),
444
+ description: z.string().optional(),
445
+ examples: z.array(z.unknown()).optional(),
446
+ resourceKind: z.string().optional(),
447
+ resourceField: z.string().optional()
448
+ });
449
+ var RequestBody = z.object({
450
+ required: z.boolean(),
451
+ contentTypes: z.record(
452
+ z.object({
453
+ schema: SchemaRefOrInline,
454
+ examples: z.array(z.unknown()).optional()
455
+ })
456
+ )
457
+ });
458
+ var ResponseDef = z.object({
459
+ status: z.union([z.number().int(), z.literal("default")]),
460
+ description: z.string().optional(),
461
+ headers: z.array(Param).optional(),
462
+ contentTypes: z.record(
463
+ z.object({
464
+ schema: SchemaRefOrInline,
465
+ examples: z.array(z.unknown()).optional()
466
+ })
467
+ ).optional()
468
+ });
469
+ var ResourceRef = z.object({
470
+ kind: z.string(),
471
+ field: z.string().optional()
472
+ });
473
+ var Operation = z.object({
474
+ id: z.string(),
475
+ method: HttpMethod,
476
+ path: z.string(),
477
+ summary: z.string().optional(),
478
+ description: z.string().optional(),
479
+ tags: z.array(z.string()).optional(),
480
+ pathParams: z.array(Param).default([]),
481
+ queryParams: z.array(Param).default([]),
482
+ headerParams: z.array(Param).default([]),
483
+ cookieParams: z.array(Param).default([]),
484
+ body: RequestBody.optional(),
485
+ responses: z.array(ResponseDef).default([]),
486
+ security: z.array(AuthRef).default([]),
487
+ servers: z.array(Server).optional(),
488
+ // Inferred
489
+ resourceKind: z.string().optional(),
490
+ resourceAction: ResourceAction.optional(),
491
+ produces: z.array(ResourceRef).optional(),
492
+ consumes: z.array(ResourceRef).optional(),
493
+ idempotency: Idempotency.optional(),
494
+ safety: Safety.optional(),
495
+ rateLimit: z.object({
496
+ rps: z.number().optional(),
497
+ burst: z.number().optional()
498
+ }).optional(),
499
+ _raw: z.unknown().optional()
500
+ });
501
+ var ResourceKind = z.object({
502
+ name: z.string(),
503
+ schemaId: SchemaIdSchema.optional(),
504
+ idField: z.string(),
505
+ createOps: z.array(z.string()).default([]),
506
+ readOps: z.array(z.string()).default([]),
507
+ listOps: z.array(z.string()).default([]),
508
+ updateOps: z.array(z.string()).default([]),
509
+ deleteOps: z.array(z.string()).default([])
510
+ });
511
+ var ResourceEdge = z.object({
512
+ from: z.string(),
513
+ to: z.string(),
514
+ via: z.object({ operationId: z.string(), param: z.string() }),
515
+ cardinality: z.enum(["1:1", "1:N", "N:M"]),
516
+ confidence: z.number().min(0).max(1).optional()
517
+ });
518
+ var ResourceGraph = z.object({
519
+ kinds: z.array(ResourceKind).default([]),
520
+ edges: z.array(ResourceEdge).default([])
521
+ });
522
+ var OperationExample = z.object({
523
+ source: z.enum(["spec", "har", "user"]),
524
+ request: z.object({
525
+ params: z.record(z.unknown()).optional(),
526
+ headers: z.record(z.string()).optional(),
527
+ body: z.unknown().optional()
528
+ }),
529
+ response: z.object({
530
+ status: z.number(),
531
+ body: z.unknown().optional()
532
+ }).optional()
533
+ });
534
+ var ExampleSet = z.object({
535
+ byOperation: z.record(z.array(OperationExample)).default({}),
536
+ byEntity: z.record(z.array(z.unknown())).default({})
537
+ });
538
+ var ParamBinding = z.object({
539
+ paramName: z.string(),
540
+ source: z.discriminatedUnion("kind", [
541
+ z.object({ kind: z.literal("literal"), value: z.unknown() }),
542
+ z.object({
543
+ kind: z.literal("fromStep"),
544
+ stepIndex: z.number().int(),
545
+ jsonPath: z.string()
546
+ }),
547
+ z.object({ kind: z.literal("fromFixture"), name: z.string() }),
548
+ z.object({ kind: z.literal("faker"), generator: z.string() })
549
+ ])
550
+ });
551
+ var WorkflowStep = z.object({
552
+ operationId: z.string(),
553
+ inputs: z.array(ParamBinding).optional(),
554
+ expect: z.object({
555
+ status: z.array(z.number()).optional(),
556
+ schemaPath: z.string().optional()
557
+ }).optional()
558
+ });
559
+ var Workflow = z.object({
560
+ id: z.string(),
561
+ description: z.string().optional(),
562
+ source: z.enum(["inferred", "declared", "har"]),
563
+ steps: z.array(WorkflowStep)
564
+ });
565
+ var PaginationHint = z.object({
566
+ operationId: z.string(),
567
+ style: z.enum(["cursor", "offset", "page", "link-header", "unknown"]),
568
+ cursorParam: z.string().optional(),
569
+ pageParam: z.string().optional(),
570
+ limitParam: z.string().optional(),
571
+ responseCursorPath: z.string().optional()
572
+ });
573
+ var VersioningHint = z.object({
574
+ style: z.enum(["url", "header", "media-type", "query", "none"]),
575
+ detail: z.string().optional()
576
+ });
577
+ var Hints = z.object({
578
+ pagination: z.array(PaginationHint).optional(),
579
+ idempotencyKeys: z.array(z.string()).optional(),
580
+ tenantHeaders: z.array(z.string()).optional(),
581
+ rateLimitHeaders: z.array(z.string()).optional(),
582
+ versioning: VersioningHint.optional()
583
+ }).catchall(z.unknown());
584
+ var IR = z.object({
585
+ version: z.literal(IR_VERSION),
586
+ meta: Meta,
587
+ servers: z.array(Server).default([]),
588
+ auth: z.array(AuthProfile).default([]),
589
+ schemas: z.record(Schema).default({}),
590
+ operations: z.array(Operation).default([]),
591
+ resources: ResourceGraph.default({ kinds: [], edges: [] }),
592
+ examples: ExampleSet.default({ byOperation: {}, byEntity: {} }),
593
+ workflows: z.array(Workflow).default([]),
594
+ hints: Hints.default({}),
595
+ _raw: z.unknown().optional()
596
+ });
597
+ function parseIR(input) {
598
+ return IR.parse(input);
599
+ }
600
+ var HTTP_METHODS = [
601
+ "GET",
602
+ "POST",
603
+ "PUT",
604
+ "PATCH",
605
+ "DELETE",
606
+ "HEAD",
607
+ "OPTIONS"
608
+ ];
609
+ async function fromOpenApiFile(path, opts = {}) {
610
+ const absolute = resolve(path);
611
+ const raw = await readFile2(absolute, "utf8");
612
+ const doc = parseDocument(raw);
613
+ const bundled = await SwaggerParser.bundle(doc);
614
+ return fromOpenApi(bundled, { sourceUri: opts.sourceUri ?? absolute });
615
+ }
616
+ function fromOpenApi(doc, opts = {}) {
617
+ const sourceVersion = doc.openapi ?? "3.0.0";
618
+ const schemas = {};
619
+ const componentSchemas = doc.components?.schemas ?? {};
620
+ for (const [name, s] of Object.entries(componentSchemas)) {
621
+ const id = schemaIdFromComponentName(name);
622
+ schemas[id] = {
623
+ id,
624
+ name,
625
+ jsonSchema: rewriteRefs(s)
626
+ };
627
+ }
628
+ const auth = extractAuthProfiles(doc);
629
+ const servers = extractServers(doc);
630
+ const operations = extractOperations(doc);
631
+ return {
632
+ version: IR_VERSION,
633
+ meta: {
634
+ title: doc.info?.title ?? "Untitled API",
635
+ version: doc.info?.version ?? "0.0.0",
636
+ description: doc.info?.description,
637
+ source: {
638
+ kind: "openapi",
639
+ sourceVersion,
640
+ ingestedAt: (/* @__PURE__ */ new Date()).toISOString(),
641
+ sourceUri: opts.sourceUri
642
+ }
643
+ },
644
+ servers,
645
+ auth,
646
+ schemas,
647
+ operations,
648
+ resources: { kinds: [], edges: [] },
649
+ examples: { byOperation: {}, byEntity: {} },
650
+ workflows: [],
651
+ hints: {}
652
+ };
653
+ }
654
+ function parseDocument(raw) {
655
+ const trimmed = raw.trimStart();
656
+ if (trimmed.startsWith("{")) {
657
+ return JSON.parse(raw);
658
+ }
659
+ return parseYaml(raw);
660
+ }
661
+ function schemaIdFromComponentName(name) {
662
+ return `#/components/schemas/${name}`;
663
+ }
664
+ function rewriteRefs(value) {
665
+ if (Array.isArray(value)) return value.map(rewriteRefs);
666
+ if (value && typeof value === "object") {
667
+ const obj = value;
668
+ if (typeof obj.$ref === "string") {
669
+ return { $ref: obj.$ref };
670
+ }
671
+ const out = {};
672
+ for (const [k, v] of Object.entries(obj)) out[k] = rewriteRefs(v);
673
+ return out;
674
+ }
675
+ return value;
676
+ }
677
+ function extractServers(doc) {
678
+ if (!doc.servers || doc.servers.length === 0) return [];
679
+ return doc.servers.map((s) => ({
680
+ url: s.url,
681
+ description: s.description,
682
+ variables: s.variables ? Object.fromEntries(
683
+ Object.entries(s.variables).map(([k, v]) => [
684
+ k,
685
+ { default: v.default ?? "", enum: v.enum, description: v.description }
686
+ ])
687
+ ) : void 0
688
+ }));
689
+ }
690
+ function extractAuthProfiles(doc) {
691
+ const schemes = doc.components?.securitySchemes ?? {};
692
+ const out = [];
693
+ for (const [id, scheme] of Object.entries(schemes)) {
694
+ if (isRef(scheme)) continue;
695
+ const mapped = mapSecurityScheme(id, scheme);
696
+ if (mapped) out.push(mapped);
697
+ }
698
+ if (out.length === 0) out.push({ id: "none", kind: "none" });
699
+ return out;
700
+ }
701
+ function mapSecurityScheme(id, s) {
702
+ if (s.type === "http") {
703
+ if (s.scheme === "bearer") return { id, kind: "bearer" };
704
+ if (s.scheme === "basic") return { id, kind: "basic" };
705
+ return null;
706
+ }
707
+ if (s.type === "apiKey") {
708
+ return {
709
+ id,
710
+ kind: "apiKey",
711
+ in: s.in,
712
+ name: s.name
713
+ };
714
+ }
715
+ if (s.type === "oauth2") {
716
+ const cc = s.flows?.clientCredentials;
717
+ if (cc) {
718
+ return {
719
+ id,
720
+ kind: "oauth2_cc",
721
+ tokenUrl: cc.tokenUrl,
722
+ clientIdEnv: `${envify(id)}_CLIENT_ID`,
723
+ clientSecretEnv: `${envify(id)}_CLIENT_SECRET`,
724
+ scopes: cc.scopes ? Object.keys(cc.scopes) : void 0
725
+ };
726
+ }
727
+ }
728
+ return null;
729
+ }
730
+ function envify(id) {
731
+ return id.replace(/[^A-Za-z0-9]/g, "_").toUpperCase();
732
+ }
733
+ function extractOperations(doc) {
734
+ const ops = [];
735
+ const paths = doc.paths ?? {};
736
+ for (const [path, pathItem] of Object.entries(paths)) {
737
+ if (!pathItem) continue;
738
+ const pathLevelParams = pathItem.parameters ?? [];
739
+ for (const method of HTTP_METHODS) {
740
+ const opObj = pathItem[method.toLowerCase()];
741
+ if (!opObj) continue;
742
+ const allParams = [...pathLevelParams, ...opObj.parameters ?? []].filter(
743
+ (p) => !isRef(p)
744
+ );
745
+ const id = opObj.operationId ?? autoOperationId(method, path);
746
+ const safety = inferSafety(method);
747
+ ops.push({
748
+ id,
749
+ method,
750
+ path,
751
+ summary: opObj.summary,
752
+ description: opObj.description,
753
+ tags: opObj.tags,
754
+ pathParams: paramsByLocation(allParams, "path"),
755
+ queryParams: paramsByLocation(allParams, "query"),
756
+ headerParams: paramsByLocation(allParams, "header"),
757
+ cookieParams: paramsByLocation(allParams, "cookie"),
758
+ body: extractRequestBody(opObj.requestBody),
759
+ responses: extractResponses(opObj.responses ?? {}),
760
+ security: extractSecurityRefs(opObj.security ?? doc.security),
761
+ safety,
762
+ idempotency: method === "GET" || method === "HEAD" ? "idempotent" : "unknown"
763
+ });
764
+ }
765
+ }
766
+ return ops;
767
+ }
768
+ function autoOperationId(method, path) {
769
+ const cleaned = path.replace(/[{}]/g, "").replace(/\//g, "_").replace(/[^A-Za-z0-9_]/g, "").replace(/^_+/, "");
770
+ return `${method.toLowerCase()}_${cleaned || "root"}`;
771
+ }
772
+ function paramsByLocation(params, loc) {
773
+ return params.filter((p) => p.in === loc).map((p) => ({
774
+ name: p.name,
775
+ schema: schemaFromAny(p.schema),
776
+ required: p.required ?? loc === "path",
777
+ description: p.description,
778
+ examples: p.example !== void 0 ? [p.example] : void 0
779
+ }));
780
+ }
781
+ function schemaFromAny(s) {
782
+ if (s && typeof s === "object" && "$ref" in s && typeof s.$ref === "string") {
783
+ return s.$ref;
784
+ }
785
+ return { jsonSchema: rewriteRefs(s ?? {}) };
786
+ }
787
+ function extractRequestBody(rb) {
788
+ if (!rb || isRef(rb)) return void 0;
789
+ const contentTypes = {};
790
+ for (const [ct, media] of Object.entries(rb.content ?? {})) {
791
+ contentTypes[ct] = {
792
+ schema: schemaFromAny(media.schema),
793
+ examples: media.example !== void 0 ? [media.example] : void 0
794
+ };
795
+ }
796
+ return {
797
+ required: rb.required ?? false,
798
+ contentTypes
799
+ };
800
+ }
801
+ function extractResponses(responses) {
802
+ const out = [];
803
+ for (const [status, resp] of Object.entries(responses)) {
804
+ if (isRef(resp)) continue;
805
+ const numericStatus = status === "default" ? "default" : Number.parseInt(status, 10);
806
+ if (numericStatus !== "default" && Number.isNaN(numericStatus)) continue;
807
+ const contentTypes = {};
808
+ for (const [ct, media] of Object.entries(resp.content ?? {})) {
809
+ contentTypes[ct] = {
810
+ schema: schemaFromAny(media.schema),
811
+ examples: media.example !== void 0 ? [media.example] : void 0
812
+ };
813
+ }
814
+ out.push({
815
+ status: numericStatus,
816
+ description: resp.description,
817
+ contentTypes: Object.keys(contentTypes).length > 0 ? contentTypes : void 0
818
+ });
819
+ }
820
+ return out;
821
+ }
822
+ function extractSecurityRefs(security) {
823
+ if (!security) return [];
824
+ const refs = [];
825
+ for (const entry of security) {
826
+ for (const [profileId, scopes] of Object.entries(entry)) {
827
+ refs.push({ profileId, scopes: scopes.length > 0 ? scopes : void 0 });
828
+ }
829
+ }
830
+ return refs;
831
+ }
832
+ function inferSafety(method) {
833
+ if (method === "GET" || method === "HEAD" || method === "OPTIONS") return "safe";
834
+ if (method === "DELETE") return "destructive";
835
+ return "mutating";
836
+ }
837
+ function isRef(v) {
838
+ return !!v && typeof v === "object" && "$ref" in v;
839
+ }
840
+
841
+ // ../graph/dist/index.js
842
+ var IRREGULAR = {
843
+ people: "person",
844
+ children: "child",
845
+ men: "man",
846
+ women: "woman",
847
+ feet: "foot",
848
+ teeth: "tooth",
849
+ geese: "goose",
850
+ mice: "mouse",
851
+ data: "datum",
852
+ media: "medium",
853
+ criteria: "criterion",
854
+ series: "series",
855
+ species: "species"
856
+ };
857
+ function singularize(word) {
858
+ if (!word) return word;
859
+ const lower = word.toLowerCase();
860
+ if (lower in IRREGULAR) return preserveCase(word, IRREGULAR[lower] ?? word);
861
+ if (/[^aeiou]ies$/i.test(word)) {
862
+ return word.slice(0, -3) + (isUpper(word.slice(-3, -2)) ? "Y" : "y");
863
+ }
864
+ if (/ves$/i.test(word) && word.length > 3) {
865
+ return word.slice(0, -3) + (isUpper(word.slice(-3, -2)) ? "F" : "f");
866
+ }
867
+ if (/(sses|shes|ches|xes|zes)$/i.test(word)) {
868
+ return word.slice(0, -2);
869
+ }
870
+ if (/(us|ss|is)$/i.test(word)) return word;
871
+ if (/[^s]s$/i.test(word)) return word.slice(0, -1);
872
+ return word;
873
+ }
874
+ function isUpper(ch) {
875
+ return ch === ch.toUpperCase() && ch !== ch.toLowerCase();
876
+ }
877
+ function preserveCase(source, replacement) {
878
+ if (source[0] && isUpper(source[0])) {
879
+ return replacement[0].toUpperCase() + replacement.slice(1);
880
+ }
881
+ return replacement;
882
+ }
883
+ function toEntityName(segment) {
884
+ const singular = singularize(segment);
885
+ return singular.split(/[-_]/).filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase()).join("");
886
+ }
887
+ function inferResourceGraph(ir) {
888
+ const opsByKind = /* @__PURE__ */ new Map();
889
+ const kindIdField = /* @__PURE__ */ new Map();
890
+ const kindSchemaId = /* @__PURE__ */ new Map();
891
+ const edges = [];
892
+ for (const op of ir.operations) {
893
+ const classification = classifyOperation(op, ir.schemas);
894
+ if (!classification) continue;
895
+ const { kind, action, idField, schemaId } = classification;
896
+ op.resourceKind = kind;
897
+ op.resourceAction = action;
898
+ if (!opsByKind.has(kind)) opsByKind.set(kind, []);
899
+ opsByKind.get(kind).push(op);
900
+ if (idField && !kindIdField.has(kind)) kindIdField.set(kind, idField);
901
+ if (schemaId && !kindSchemaId.has(kind)) kindSchemaId.set(kind, schemaId);
902
+ op.produces = action === "create" && schemaId ? [{ kind }] : op.produces;
903
+ }
904
+ for (const op of ir.operations) {
905
+ if (!op.resourceKind) continue;
906
+ const parents = parentResourcesFromPath(op.path, op.resourceKind);
907
+ if (parents.length === 0) continue;
908
+ op.consumes = [
909
+ ...op.consumes ?? [],
910
+ ...parents.map((p) => ({ kind: p.kind, field: p.field }))
911
+ ];
912
+ for (const parent of parents) {
913
+ edges.push({
914
+ from: op.resourceKind,
915
+ to: parent.kind,
916
+ via: { operationId: op.id, param: parent.field },
917
+ cardinality: "1:N",
918
+ confidence: 0.9
919
+ // path-nesting is high signal
920
+ });
921
+ }
922
+ }
923
+ for (const op of ir.operations) {
924
+ if (!op.resourceKind || !op.body) continue;
925
+ for (const media of Object.values(op.body.contentTypes)) {
926
+ const refs = collectRefs(media.schema, ir.schemas);
927
+ for (const refKind of refs) {
928
+ if (refKind === op.resourceKind) continue;
929
+ if (!opsByKind.has(refKind)) continue;
930
+ edges.push({
931
+ from: op.resourceKind,
932
+ to: refKind,
933
+ via: { operationId: op.id, param: "body" },
934
+ cardinality: "1:1",
935
+ confidence: 0.7
936
+ });
937
+ }
938
+ }
939
+ }
940
+ const kinds = [];
941
+ for (const [name, ops] of opsByKind) {
942
+ kinds.push({
943
+ name,
944
+ schemaId: kindSchemaId.get(name),
945
+ idField: kindIdField.get(name) ?? "id",
946
+ createOps: ops.filter((o) => o.resourceAction === "create").map((o) => o.id),
947
+ readOps: ops.filter((o) => o.resourceAction === "read").map((o) => o.id),
948
+ listOps: ops.filter((o) => o.resourceAction === "list").map((o) => o.id),
949
+ updateOps: ops.filter((o) => o.resourceAction === "update").map((o) => o.id),
950
+ deleteOps: ops.filter((o) => o.resourceAction === "delete").map((o) => o.id)
951
+ });
952
+ }
953
+ const seen = /* @__PURE__ */ new Set();
954
+ const dedupedEdges = edges.filter((e) => {
955
+ const key = `${e.from}|${e.to}|${e.via.operationId}|${e.via.param}`;
956
+ if (seen.has(key)) return false;
957
+ seen.add(key);
958
+ return true;
959
+ });
960
+ ir.resources = { kinds, edges: dedupedEdges };
961
+ return ir;
962
+ }
963
+ function classifyOperation(op, schemas) {
964
+ const segments = op.path.split("/").filter(Boolean);
965
+ if (segments.length === 0) return null;
966
+ const last = segments[segments.length - 1];
967
+ const lastIsParam = isParamSegment(last);
968
+ let collectionSegment;
969
+ for (let i = segments.length - 1; i >= 0; i--) {
970
+ const s = segments[i];
971
+ if (!isParamSegment(s) && !isVersionSegment(s)) {
972
+ collectionSegment = s;
973
+ break;
974
+ }
975
+ }
976
+ if (!collectionSegment) return null;
977
+ const kind = toEntityName(collectionSegment);
978
+ if (!kind) return null;
979
+ let action;
980
+ if (lastIsParam) {
981
+ if (op.method === "GET") action = "read";
982
+ else if (op.method === "PUT" || op.method === "PATCH") action = "update";
983
+ else if (op.method === "DELETE") action = "delete";
984
+ else action = "action";
985
+ } else {
986
+ if (op.method === "GET") action = "list";
987
+ else if (op.method === "POST") action = "create";
988
+ else if (op.method === "DELETE")
989
+ action = "delete";
990
+ else action = "action";
991
+ }
992
+ const collectionIdx = segments.lastIndexOf(collectionSegment);
993
+ const tail = segments.slice(collectionIdx + 1);
994
+ if (tail.length > 0 && !tail.every(isParamSegment)) {
995
+ action = "action";
996
+ }
997
+ const { schemaId, idField } = pickSuccessSchema(op, schemas);
998
+ return { kind, action, idField, schemaId };
999
+ }
1000
+ function isParamSegment(seg) {
1001
+ return seg.startsWith("{") && seg.endsWith("}");
1002
+ }
1003
+ function isVersionSegment(seg) {
1004
+ return /^v\d+$/i.test(seg);
1005
+ }
1006
+ function pickSuccessSchema(op, schemas) {
1007
+ const success = op.responses.filter((r) => typeof r.status === "number" && r.status >= 200 && r.status < 300).sort((a, b) => a.status - b.status)[0];
1008
+ if (!success) return {};
1009
+ const json = success.contentTypes?.["application/json"];
1010
+ if (!json) return {};
1011
+ const sid = resolveTopRef(json.schema, schemas);
1012
+ if (!sid) return {};
1013
+ return { schemaId: sid, idField: pickIdField(schemas[sid]) };
1014
+ }
1015
+ function pickIdField(schema) {
1016
+ const js = schema?.jsonSchema;
1017
+ const props = js?.properties;
1018
+ if (!props) return void 0;
1019
+ const keys = Object.keys(props);
1020
+ if (keys.includes("id")) return "id";
1021
+ if (keys.includes("uuid")) return "uuid";
1022
+ const idLike = keys.find((k) => /^id$|_id$/i.test(k));
1023
+ return idLike;
1024
+ }
1025
+ function resolveTopRef(schema, schemas) {
1026
+ if (typeof schema === "string") {
1027
+ const target = schemas[schema];
1028
+ if (!target) return schema;
1029
+ const inner2 = unwrapArrayItem(target.jsonSchema);
1030
+ if (inner2 && typeof inner2 === "string") return inner2;
1031
+ return schema;
1032
+ }
1033
+ const inner = unwrapArrayItem(schema.jsonSchema);
1034
+ if (inner && typeof inner === "string") return inner;
1035
+ if (typeof schema.jsonSchema === "object" && schema.jsonSchema !== null) {
1036
+ const direct = schema.jsonSchema.$ref;
1037
+ if (direct) return direct;
1038
+ }
1039
+ return void 0;
1040
+ }
1041
+ function unwrapArrayItem(js) {
1042
+ if (!js || typeof js !== "object") return void 0;
1043
+ const obj = js;
1044
+ if (obj.type === "array" && obj.items?.$ref) return obj.items.$ref;
1045
+ return void 0;
1046
+ }
1047
+ function parentResourcesFromPath(path, selfKind) {
1048
+ const segments = path.split("/").filter(Boolean);
1049
+ const pairs = [];
1050
+ for (let i = 0; i < segments.length - 1; i++) {
1051
+ const cur = segments[i];
1052
+ const next = segments[i + 1];
1053
+ if (!isParamSegment(cur) && !isVersionSegment(cur) && isParamSegment(next)) {
1054
+ pairs.push({
1055
+ collection: cur,
1056
+ paramName: next.slice(1, -1)
1057
+ });
1058
+ }
1059
+ }
1060
+ const parents = [];
1061
+ for (const pair of pairs) {
1062
+ const kind = toEntityName(pair.collection);
1063
+ if (kind === selfKind) continue;
1064
+ parents.push({ kind, field: pair.paramName });
1065
+ }
1066
+ return parents;
1067
+ }
1068
+ function collectRefs(schema, schemas, seen = /* @__PURE__ */ new Set()) {
1069
+ const out = [];
1070
+ if (typeof schema === "string") {
1071
+ if (seen.has(schema)) return out;
1072
+ seen.add(schema);
1073
+ const target = schemas[schema];
1074
+ if (target) {
1075
+ const refKind = entityNameForSchemaId(schema);
1076
+ if (refKind) out.push(refKind);
1077
+ walk(target.jsonSchema, out, schemas, seen);
1078
+ }
1079
+ return out;
1080
+ }
1081
+ walk(schema.jsonSchema, out, schemas, seen);
1082
+ return out;
1083
+ }
1084
+ function walk(js, out, schemas, seen) {
1085
+ if (!js) return;
1086
+ if (Array.isArray(js)) {
1087
+ for (const item of js) walk(item, out, schemas, seen);
1088
+ return;
1089
+ }
1090
+ if (typeof js !== "object") return;
1091
+ const obj = js;
1092
+ if (typeof obj.$ref === "string") {
1093
+ const ref = obj.$ref;
1094
+ if (seen.has(ref)) return;
1095
+ seen.add(ref);
1096
+ const refKind = entityNameForSchemaId(ref);
1097
+ if (refKind) out.push(refKind);
1098
+ const target = schemas[ref];
1099
+ if (target) walk(target.jsonSchema, out, schemas, seen);
1100
+ return;
1101
+ }
1102
+ for (const v of Object.values(obj)) walk(v, out, schemas, seen);
1103
+ }
1104
+ function entityNameForSchemaId(schemaId) {
1105
+ const m = schemaId.match(/\/([^/]+)$/);
1106
+ return m ? m[1] : void 0;
1107
+ }
1108
+ function renderGraphTree(ir) {
1109
+ const { resources } = ir;
1110
+ if (resources.kinds.length === 0) {
1111
+ return "(no resources detected)";
1112
+ }
1113
+ const lines = [];
1114
+ for (const kind of resources.kinds) {
1115
+ lines.push(formatKind(kind));
1116
+ const inEdges = resources.edges.filter((e) => e.from === kind.name);
1117
+ if (inEdges.length > 0) {
1118
+ const parents = [...new Set(inEdges.map((e) => e.to))].join(", ");
1119
+ lines.push(` depends on: ${parents}`);
1120
+ }
1121
+ }
1122
+ return lines.join("\n");
1123
+ }
1124
+ function formatKind(kind) {
1125
+ const head = `${kind.name} (${kind.idField})`;
1126
+ const rows = [head];
1127
+ if (kind.createOps.length > 0) rows.push(` create: ${kind.createOps.join(", ")}`);
1128
+ if (kind.readOps.length > 0) rows.push(` read: ${kind.readOps.join(", ")}`);
1129
+ if (kind.listOps.length > 0) rows.push(` list: ${kind.listOps.join(", ")}`);
1130
+ if (kind.updateOps.length > 0) rows.push(` update: ${kind.updateOps.join(", ")}`);
1131
+ if (kind.deleteOps.length > 0) rows.push(` delete: ${kind.deleteOps.join(", ")}`);
1132
+ return rows.join("\n");
1133
+ }
1134
+ function graphStats(graph) {
1135
+ const linked = /* @__PURE__ */ new Set();
1136
+ for (const e of graph.edges) {
1137
+ linked.add(e.from);
1138
+ linked.add(e.to);
1139
+ }
1140
+ const orphanKinds = graph.kinds.filter((k) => !linked.has(k.name)).map((k) => k.name);
1141
+ return {
1142
+ kinds: graph.kinds.length,
1143
+ edges: graph.edges.length,
1144
+ orphanKinds
1145
+ };
1146
+ }
1147
+
1148
+ // ../test-contract/dist/index.js
1149
+ function compileContract(ir, specSource, opts = {}) {
1150
+ const specFileName = opts.specFileName ?? "openapi.yaml";
1151
+ const baseUrl = opts.baseUrl ?? ir.servers[0]?.url ?? "http://localhost:4010";
1152
+ const examples = opts.examples ?? 25;
1153
+ const envVars = collectEnvVars(ir.auth);
1154
+ const files = {
1155
+ [specFileName]: specSource.endsWith("\n") ? specSource : `${specSource}
1156
+ `,
1157
+ "pyproject.toml": emitPyProject(ir),
1158
+ "conftest.py": emitConftest(ir, specFileName, baseUrl, envVars),
1159
+ "test_contract.py": emitContractTests(ir, examples),
1160
+ "README.md": emitReadme(ir, specFileName),
1161
+ ".env.example": emitEnvExample(baseUrl, envVars)
1162
+ };
1163
+ return { files, envVars };
1164
+ }
1165
+ function collectEnvVars(profiles) {
1166
+ const out = /* @__PURE__ */ new Set();
1167
+ for (const p of profiles) {
1168
+ switch (p.kind) {
1169
+ case "bearer":
1170
+ out.add(p.tokenEnv ?? "API_TOKEN");
1171
+ break;
1172
+ case "apiKey":
1173
+ out.add(p.valueEnv ?? p.name.toUpperCase().replace(/[^A-Z0-9]/g, "_"));
1174
+ break;
1175
+ case "basic":
1176
+ out.add(p.userEnv ?? "API_USER");
1177
+ out.add(p.passEnv ?? "API_PASS");
1178
+ break;
1179
+ case "oauth2_cc":
1180
+ out.add(p.clientIdEnv);
1181
+ out.add(p.clientSecretEnv);
1182
+ break;
1183
+ }
1184
+ }
1185
+ return [...out].sort();
1186
+ }
1187
+ function emitPyProject(ir) {
1188
+ const name = slugify(ir.meta.title) || "loadam-contract";
1189
+ return `[project]
1190
+ name = "${name}-contract"
1191
+ version = "0.0.0"
1192
+ description = "Schemathesis contract suite for ${ir.meta.title} \u2014 generated by loadam"
1193
+ requires-python = ">=3.10"
1194
+ dependencies = [
1195
+ "schemathesis>=3.36",
1196
+ "pytest>=8.0",
1197
+ "pyyaml>=6.0",
1198
+ "python-dotenv>=1.0",
1199
+ ]
1200
+
1201
+ [tool.pytest.ini_options]
1202
+ addopts = "-q"
1203
+ testpaths = ["."]
1204
+ `;
1205
+ }
1206
+ function emitConftest(ir, specFileName, baseUrl, envVars) {
1207
+ const authBuilder = emitAuthBuilder(ir.auth);
1208
+ return `# AUTO-GENERATED by @loadam/test-contract
1209
+ """
1210
+ Shared fixtures for the Schemathesis contract suite.
1211
+
1212
+ The schema is loaded from a checked-in copy of the spec so the suite is
1213
+ self-contained and reproducible. Override BASE_URL / credentials via env vars.
1214
+ """
1215
+
1216
+ import os
1217
+ from pathlib import Path
1218
+
1219
+ import schemathesis
1220
+ from dotenv import load_dotenv
1221
+
1222
+ load_dotenv()
1223
+
1224
+ SPEC_PATH = Path(__file__).parent / "${specFileName}"
1225
+ BASE_URL = os.getenv("BASE_URL", ${JSON.stringify(baseUrl)})
1226
+
1227
+ # Required env vars \u2014 listed for ergonomic discovery; not hard-required
1228
+ # (Schemathesis can still run unauth flows).
1229
+ REQUIRED_ENV = ${JSON.stringify(envVars)}
1230
+
1231
+ schema = schemathesis.from_path(str(SPEC_PATH), base_url=BASE_URL)
1232
+
1233
+
1234
+ def auth_kwargs() -> dict:
1235
+ ${authBuilder}
1236
+ `;
1237
+ }
1238
+ function emitAuthBuilder(profiles) {
1239
+ if (profiles.length === 0) {
1240
+ return " return {}\n";
1241
+ }
1242
+ const lines = [" headers: dict = {}", " params: dict = {}"];
1243
+ for (const p of profiles) {
1244
+ switch (p.kind) {
1245
+ case "bearer": {
1246
+ const env = p.tokenEnv ?? "API_TOKEN";
1247
+ lines.push(` if os.getenv(${JSON.stringify(env)}):`);
1248
+ lines.push(
1249
+ ` headers["Authorization"] = f"Bearer {os.environ[${JSON.stringify(env)}]}"`
1250
+ );
1251
+ break;
1252
+ }
1253
+ case "apiKey": {
1254
+ const env = p.valueEnv ?? p.name.toUpperCase().replace(/[^A-Z0-9]/g, "_");
1255
+ if (p.in === "header") {
1256
+ lines.push(` if os.getenv(${JSON.stringify(env)}):`);
1257
+ lines.push(
1258
+ ` headers[${JSON.stringify(p.name)}] = os.environ[${JSON.stringify(env)}]`
1259
+ );
1260
+ } else if (p.in === "query") {
1261
+ lines.push(` if os.getenv(${JSON.stringify(env)}):`);
1262
+ lines.push(
1263
+ ` params[${JSON.stringify(p.name)}] = os.environ[${JSON.stringify(env)}]`
1264
+ );
1265
+ }
1266
+ break;
1267
+ }
1268
+ case "basic": {
1269
+ const u = p.userEnv ?? "API_USER";
1270
+ const pw = p.passEnv ?? "API_PASS";
1271
+ lines.push(` if os.getenv(${JSON.stringify(u)}) and os.getenv(${JSON.stringify(pw)}):`);
1272
+ lines.push(
1273
+ ` import base64; headers["Authorization"] = "Basic " + base64.b64encode(f"{os.environ[${JSON.stringify(u)}]}:{os.environ[${JSON.stringify(pw)}]}".encode()).decode()`
1274
+ );
1275
+ break;
1276
+ }
1277
+ }
1278
+ }
1279
+ lines.push(` return {"headers": headers, "params": params}`);
1280
+ return `${lines.join("\n")}
1281
+ `;
1282
+ }
1283
+ function emitContractTests(_ir, examples) {
1284
+ return `# AUTO-GENERATED by @loadam/test-contract
1285
+ """
1286
+ Property-based contract tests for every declared operation.
1287
+
1288
+ Each operation is fuzzed ~${examples} times. Schemathesis asserts:
1289
+ - response status is one of the declared statuses
1290
+ - response body validates against the declared response schema
1291
+ - server returns no 500s on valid inputs
1292
+
1293
+ Mutating endpoints (POST/PUT/PATCH/DELETE) are included by default \u2014 point
1294
+ the suite at a disposable / sandbox environment, not production.
1295
+ """
1296
+
1297
+ from hypothesis import settings
1298
+
1299
+ from conftest import auth_kwargs, schema
1300
+
1301
+ import schemathesis
1302
+
1303
+
1304
+ @schema.parametrize()
1305
+ @settings(max_examples=${examples}, deadline=None)
1306
+ def test_contract(case: "schemathesis.Case") -> None:
1307
+ response = case.call(**auth_kwargs())
1308
+ case.validate_response(response)
1309
+ `;
1310
+ }
1311
+ function emitReadme(ir, specFileName) {
1312
+ return `# ${ir.meta.title} \u2014 contract test suite
1313
+
1314
+ Generated by [loadam](https://github.com/loadam) from your API spec.
1315
+
1316
+ ## Run
1317
+
1318
+ \`\`\`bash
1319
+ # 1. install
1320
+ python -m venv .venv && source .venv/bin/activate
1321
+ pip install -e .
1322
+
1323
+ # 2. fill credentials (optional \u2014 Schemathesis runs unauth flows too)
1324
+ cp .env.example .env
1325
+
1326
+ # 3. run
1327
+ pytest
1328
+ \`\`\`
1329
+
1330
+ ## What's in here
1331
+
1332
+ - \`${specFileName}\` \u2014 checked-in copy of the spec under test.
1333
+ - \`conftest.py\` \u2014 schema loader + auth builder.
1334
+ - \`test_contract.py\` \u2014 Schemathesis property-based suite.
1335
+
1336
+ ## Why contract tests?
1337
+
1338
+ For each operation, [Schemathesis](https://schemathesis.readthedocs.io/) derives
1339
+ Hypothesis strategies from the declared schemas, sends randomised requests, and
1340
+ asserts the responses conform. It catches the long tail of "we didn't validate
1341
+ this combination" bugs unit tests miss.
1342
+
1343
+ ## Regenerating
1344
+
1345
+ Re-run \`loadam contract\` to refresh. Edits to generated files will be overwritten.
1346
+ `;
1347
+ }
1348
+ function emitEnvExample(baseUrl, envVars) {
1349
+ const lines = ["# Generated by loadam \u2014 copy to .env and fill in.", `BASE_URL=${baseUrl}`, ""];
1350
+ for (const v of envVars) lines.push(`${v}=`);
1351
+ return `${lines.join("\n")}
1352
+ `;
1353
+ }
1354
+ function slugify(s) {
1355
+ return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
1356
+ }
1357
+
1358
+ // src/util/output.ts
1359
+ import { consola as consola3 } from "consola";
1360
+ function makeOutput(jsonMode) {
1361
+ if (jsonMode) {
1362
+ return {
1363
+ json: true,
1364
+ start: () => void 0,
1365
+ info: () => void 0,
1366
+ success: () => void 0,
1367
+ step: () => void 0,
1368
+ result(payload) {
1369
+ process.stdout.write(`${JSON.stringify(payload, null, 2)}
1370
+ `);
1371
+ }
1372
+ };
1373
+ }
1374
+ return {
1375
+ json: false,
1376
+ start: (m) => consola3.start(m),
1377
+ info: (m) => consola3.info(m),
1378
+ success: (m) => consola3.success(m),
1379
+ step: (m) => consola3.log(m),
1380
+ result: () => void 0
1381
+ };
1382
+ }
1383
+
1384
+ // src/commands/contract.ts
1385
+ function registerContractCommand(program) {
1386
+ program.command("contract").description("Compile an OpenAPI spec into a Schemathesis property-based contract suite.").argument("<spec>", "path to OpenAPI 3.x spec (YAML or JSON)").option(
1387
+ "-o, --output <dir>",
1388
+ "output directory for the generated suite",
1389
+ "./loadam-out/contract"
1390
+ ).option("--target <url>", "override base URL written to conftest.py").option("--examples <n>", "Hypothesis examples per operation", "25").option("--json", "emit a single JSON summary on stdout (CI mode)", false).action(withFriendlyErrors(runContract));
1391
+ }
1392
+ async function runContract(spec, opts) {
1393
+ const out = makeOutput(!!opts.json);
1394
+ const specPath = resolve2(spec);
1395
+ out.start(`Parsing OpenAPI spec: ${specPath}`);
1396
+ const ir = await fromOpenApiFile(specPath);
1397
+ inferResourceGraph(ir);
1398
+ parseIR(ir);
1399
+ const specSource = await readFile3(specPath, "utf8");
1400
+ const examples = Number.parseInt(opts.examples ?? "25", 10);
1401
+ const result = compileContract(ir, specSource, {
1402
+ baseUrl: opts.target,
1403
+ examples: Number.isFinite(examples) ? examples : 25
1404
+ });
1405
+ const outDir = resolve2(opts.output);
1406
+ await mkdir(outDir, { recursive: true });
1407
+ for (const [rel, contents] of Object.entries(result.files)) {
1408
+ const full = resolve2(outDir, rel);
1409
+ await mkdir(dirname(full), { recursive: true });
1410
+ await writeFile(full, contents, "utf8");
1411
+ }
1412
+ const fileCount = Object.keys(result.files).length;
1413
+ out.success(`Wrote ${fileCount} files to ${outDir}`);
1414
+ out.info(` ${ir.operations.length} operations to fuzz`);
1415
+ if (!out.json) {
1416
+ out.step("");
1417
+ out.step("Next steps:");
1418
+ out.step(` cd ${opts.output}`);
1419
+ out.step(" python -m venv .venv && source .venv/bin/activate");
1420
+ out.step(" pip install -e .");
1421
+ out.step(" pytest");
1422
+ }
1423
+ out.result({
1424
+ command: "contract",
1425
+ outputDir: outDir,
1426
+ files: fileCount,
1427
+ operations: ir.operations.length,
1428
+ envVars: result.envVars
1429
+ });
1430
+ }
1431
+
1432
+ // src/commands/diff.ts
1433
+ import { writeFile as writeFile2 } from "fs/promises";
1434
+ import { resolve as resolve3 } from "path";
1435
+
1436
+ // ../test-drift/dist/index.js
1437
+ import Ajv from "ajv";
1438
+ import addFormats from "ajv-formats";
1439
+ function compareProbes(input) {
1440
+ const findings = [];
1441
+ const opsById = new Map(input.ir.operations.map((o) => [o.id, o]));
1442
+ const ajv = buildAjv(input.ir);
1443
+ for (const probe of input.probes) {
1444
+ const op = opsById.get(probe.operationId);
1445
+ if (!op) continue;
1446
+ const declared = pickResponseFor(op, probe.status);
1447
+ if (!declared) {
1448
+ findings.push({
1449
+ operationId: op.id,
1450
+ method: op.method,
1451
+ path: op.path,
1452
+ severity: "error",
1453
+ kind: "undeclared-status",
1454
+ message: `Got ${probe.status} but the spec declares only ${describeStatuses(op.responses)}.`
1455
+ });
1456
+ continue;
1457
+ }
1458
+ if (!declared.contentTypes || Object.keys(declared.contentTypes).length === 0) {
1459
+ if (probe.body !== void 0 && probe.body !== null && probe.body !== "") {
1460
+ findings.push({
1461
+ operationId: op.id,
1462
+ method: op.method,
1463
+ path: op.path,
1464
+ severity: "info",
1465
+ kind: "no-response-schema",
1466
+ message: `Response ${probe.status} has no schema in the spec; got a body.`
1467
+ });
1468
+ }
1469
+ continue;
1470
+ }
1471
+ const ct = probe.contentType ?? Object.keys(declared.contentTypes)[0];
1472
+ const media = ct ? declared.contentTypes[ct] : void 0;
1473
+ if (!media) {
1474
+ findings.push({
1475
+ operationId: op.id,
1476
+ method: op.method,
1477
+ path: op.path,
1478
+ severity: "warning",
1479
+ kind: "content-type-mismatch",
1480
+ message: `Response content-type ${ct ?? "<none>"} not declared (spec declares ${Object.keys(declared.contentTypes).join(", ")}).`
1481
+ });
1482
+ continue;
1483
+ }
1484
+ const errors = validateAgainstSchema(ajv, media.schema, probe.body, input.ir);
1485
+ if (errors.length > 0) {
1486
+ findings.push({
1487
+ operationId: op.id,
1488
+ method: op.method,
1489
+ path: op.path,
1490
+ severity: "error",
1491
+ kind: "schema-mismatch",
1492
+ message: `Response body does not match declared schema (${errors.length} violation(s)).`,
1493
+ details: errors.slice(0, 5).map(formatAjvError)
1494
+ });
1495
+ }
1496
+ }
1497
+ return findings;
1498
+ }
1499
+ function pickResponseFor(op, status) {
1500
+ const exact = op.responses.find((r) => r.status === status);
1501
+ if (exact) return exact;
1502
+ const def = op.responses.find((r) => r.status === "default");
1503
+ return def;
1504
+ }
1505
+ function describeStatuses(responses) {
1506
+ const codes = responses.map((r) => String(r.status));
1507
+ return codes.length === 0 ? "<none>" : codes.join(", ");
1508
+ }
1509
+ function buildAjv(ir) {
1510
+ const ajv = new Ajv({
1511
+ strict: false,
1512
+ allErrors: true,
1513
+ validateFormats: true,
1514
+ // Resolve internal $refs against IR schemas.
1515
+ loadSchema: () => Promise.resolve({})
1516
+ });
1517
+ addFormats(ajv);
1518
+ for (const [id, schema] of Object.entries(ir.schemas)) {
1519
+ try {
1520
+ ajv.addSchema(schema.jsonSchema, id);
1521
+ } catch {
1522
+ }
1523
+ }
1524
+ return ajv;
1525
+ }
1526
+ function validateAgainstSchema(ajv, schemaRef, body, ir) {
1527
+ const target = resolveRef(schemaRef, ir);
1528
+ if (!target) return [];
1529
+ let validate;
1530
+ try {
1531
+ validate = ajv.compile(target);
1532
+ } catch {
1533
+ return [];
1534
+ }
1535
+ const ok = validate(body);
1536
+ if (ok) return [];
1537
+ return validate.errors ?? [];
1538
+ }
1539
+ function resolveRef(schema, ir) {
1540
+ if (typeof schema === "string") {
1541
+ return ir.schemas[schema]?.jsonSchema;
1542
+ }
1543
+ return schema.jsonSchema;
1544
+ }
1545
+ function formatAjvError(err) {
1546
+ return {
1547
+ path: err.instancePath || "/",
1548
+ message: err.message ?? "",
1549
+ keyword: err.keyword
1550
+ };
1551
+ }
1552
+ async function probeOperations(ir, opts) {
1553
+ const probes = [];
1554
+ const skipped = [];
1555
+ const safeOnly = opts.safeOnly ?? true;
1556
+ const timeout = opts.timeoutMs ?? 5e3;
1557
+ for (const op of ir.operations) {
1558
+ if (safeOnly && !isSafeMethod(op.method)) {
1559
+ skipped.push({
1560
+ operationId: op.id,
1561
+ reason: `mutating ${op.method} skipped (safe-only)`
1562
+ });
1563
+ continue;
1564
+ }
1565
+ const url = buildUrl(opts.baseUrl, op, opts.pathParams ?? {});
1566
+ if (!url) {
1567
+ skipped.push({ operationId: op.id, reason: "missing required path param" });
1568
+ continue;
1569
+ }
1570
+ try {
1571
+ const ac = new AbortController();
1572
+ const timer = setTimeout(() => ac.abort(), timeout);
1573
+ const resp = await fetch(url, {
1574
+ method: op.method,
1575
+ headers: opts.headers ?? {},
1576
+ signal: ac.signal
1577
+ });
1578
+ clearTimeout(timer);
1579
+ const ct = resp.headers.get("content-type") ?? void 0;
1580
+ const body = await readBody(resp, ct);
1581
+ probes.push({
1582
+ operationId: op.id,
1583
+ status: resp.status,
1584
+ contentType: ct ? ct.split(";")[0].trim() : void 0,
1585
+ body
1586
+ });
1587
+ } catch (err) {
1588
+ skipped.push({
1589
+ operationId: op.id,
1590
+ reason: err instanceof Error ? err.message : String(err)
1591
+ });
1592
+ }
1593
+ }
1594
+ return { probes, skipped };
1595
+ }
1596
+ function isSafeMethod(method) {
1597
+ return method === "GET" || method === "HEAD" || method === "OPTIONS";
1598
+ }
1599
+ function buildUrl(base, op, pathParams) {
1600
+ let path = op.path;
1601
+ for (const p of op.pathParams) {
1602
+ const v = pathParams[p.name];
1603
+ if (v === void 0 && p.required) return void 0;
1604
+ if (v !== void 0) {
1605
+ path = path.split(`{${p.name}}`).join(encodeURIComponent(String(v)));
1606
+ }
1607
+ }
1608
+ return base.replace(/\/$/, "") + path;
1609
+ }
1610
+ async function readBody(resp, ct) {
1611
+ const text = await resp.text();
1612
+ if (!text) return void 0;
1613
+ if (ct?.includes("json")) {
1614
+ try {
1615
+ return JSON.parse(text);
1616
+ } catch {
1617
+ return text;
1618
+ }
1619
+ }
1620
+ return text;
1621
+ }
1622
+ var SEVERITY_ORDER = ["error", "warning", "info"];
1623
+ function renderMarkdownReport(opts) {
1624
+ const ts = opts.generatedAt ?? (/* @__PURE__ */ new Date()).toISOString();
1625
+ const counts = countBySeverity(opts.findings);
1626
+ const sections = [];
1627
+ sections.push(`# Drift report \u2014 ${opts.ir.meta.title}`);
1628
+ sections.push("");
1629
+ sections.push(`- Spec version: \`${opts.ir.meta.version}\``);
1630
+ sections.push(`- Target: \`${opts.baseUrl}\``);
1631
+ sections.push(`- Generated: ${ts}`);
1632
+ sections.push(
1633
+ `- Findings: **${opts.findings.length}** (${counts.error} error \xB7 ${counts.warning} warning \xB7 ${counts.info} info)`
1634
+ );
1635
+ if (opts.skipped && opts.skipped.length > 0) {
1636
+ sections.push(`- Skipped: ${opts.skipped.length} operation(s)`);
1637
+ }
1638
+ sections.push("");
1639
+ if (opts.findings.length === 0) {
1640
+ sections.push("No drift detected \u2014 spec and live API agree on every probed operation.");
1641
+ sections.push("");
1642
+ } else {
1643
+ sections.push("## Findings");
1644
+ sections.push("");
1645
+ const sorted = [...opts.findings].sort(
1646
+ (a, b) => SEVERITY_ORDER.indexOf(a.severity) - SEVERITY_ORDER.indexOf(b.severity)
1647
+ );
1648
+ for (const f of sorted) {
1649
+ sections.push(`### \`${f.method} ${f.path}\` \u2014 ${f.kind} (${severityBadge(f.severity)})`);
1650
+ sections.push("");
1651
+ sections.push(f.message);
1652
+ sections.push("");
1653
+ if (f.details !== void 0) {
1654
+ sections.push("```json");
1655
+ sections.push(JSON.stringify(f.details, null, 2));
1656
+ sections.push("```");
1657
+ sections.push("");
1658
+ }
1659
+ }
1660
+ }
1661
+ if (opts.skipped && opts.skipped.length > 0) {
1662
+ sections.push("## Skipped operations");
1663
+ sections.push("");
1664
+ for (const s of opts.skipped) {
1665
+ sections.push(`- \`${s.operationId}\` \u2014 ${s.reason}`);
1666
+ }
1667
+ sections.push("");
1668
+ }
1669
+ return `${sections.join("\n").trimEnd()}
1670
+ `;
1671
+ }
1672
+ function countBySeverity(findings) {
1673
+ const c = { error: 0, warning: 0, info: 0 };
1674
+ for (const f of findings) c[f.severity]++;
1675
+ return c;
1676
+ }
1677
+ function severityBadge(s) {
1678
+ if (s === "error") return "\u274C error";
1679
+ if (s === "warning") return "\u26A0\uFE0F warning";
1680
+ return "\u2139\uFE0F info";
1681
+ }
1682
+
1683
+ // src/commands/diff.ts
1684
+ function registerDiffCommand(program) {
1685
+ program.command("diff").description("Probe a live API and report drift against the spec (Markdown).").argument("<spec>", "path to OpenAPI 3.x spec (YAML or JSON)").requiredOption("--target <url>", "base URL of the live API").option("-o, --output <path>", "write report to this file (otherwise stdout)").option("--timeout-ms <n>", "per-request timeout", "5000").option("--mutating", "also probe mutating ops (DANGEROUS \u2014 not for prod)", false).option("-H, --header <kv...>", 'additional headers, repeatable, "Name: value" form').option("--path-param <kv...>", 'fallback path-param values, repeatable, "name=value" form').option("--fail-on <severity>", "exit non-zero when findings of this severity exist", "error").option("--json", "emit a single JSON summary on stdout (CI mode)", false).action(withFriendlyErrors(runDiff));
1686
+ }
1687
+ async function runDiff(spec, opts) {
1688
+ const out = makeOutput(!!opts.json);
1689
+ const specPath = resolve3(spec);
1690
+ out.start(`Parsing OpenAPI spec: ${specPath}`);
1691
+ const ir = await fromOpenApiFile(specPath);
1692
+ inferResourceGraph(ir);
1693
+ parseIR(ir);
1694
+ const headers = parseKvPairs(opts.header ?? [], ":");
1695
+ const pathParams = parseKvPairs(opts.pathParam ?? [], "=");
1696
+ const timeoutMs = Number.parseInt(opts.timeoutMs ?? "5000", 10);
1697
+ out.start(`Probing ${ir.operations.length} operations on ${opts.target}\u2026`);
1698
+ const { probes, skipped } = await probeOperations(ir, {
1699
+ baseUrl: opts.target,
1700
+ headers,
1701
+ pathParams,
1702
+ timeoutMs: Number.isFinite(timeoutMs) ? timeoutMs : 5e3,
1703
+ safeOnly: !opts.mutating
1704
+ });
1705
+ const findings = compareProbes({ ir, probes });
1706
+ const counts = countBySeverity(findings);
1707
+ if (!out.json) {
1708
+ const report = renderMarkdownReport({
1709
+ ir,
1710
+ baseUrl: opts.target,
1711
+ findings,
1712
+ skipped
1713
+ });
1714
+ if (opts.output) {
1715
+ const outFile = resolve3(opts.output);
1716
+ await writeFile2(outFile, report, "utf8");
1717
+ out.success(`Wrote drift report to ${outFile}`);
1718
+ } else {
1719
+ process.stdout.write(report);
1720
+ }
1721
+ out.info(
1722
+ ` ${probes.length} probed \xB7 ${skipped.length} skipped \xB7 ${counts.error} error \xB7 ${counts.warning} warning \xB7 ${counts.info} info`
1723
+ );
1724
+ } else if (opts.output) {
1725
+ const report = renderMarkdownReport({
1726
+ ir,
1727
+ baseUrl: opts.target,
1728
+ findings,
1729
+ skipped
1730
+ });
1731
+ await writeFile2(resolve3(opts.output), report, "utf8");
1732
+ }
1733
+ const failOn = opts.failOn ?? "error";
1734
+ const failed = failOn === "error" && counts.error > 0 || failOn === "warning" && counts.error + counts.warning > 0;
1735
+ out.result({
1736
+ command: "diff",
1737
+ target: opts.target,
1738
+ probed: probes.length,
1739
+ skipped: skipped.length,
1740
+ findings: findings.length,
1741
+ counts,
1742
+ reportPath: opts.output ? resolve3(opts.output) : null,
1743
+ failOn,
1744
+ failed
1745
+ });
1746
+ if (failOn !== "never" && failed) process.exit(1);
1747
+ }
1748
+ function parseKvPairs(values, sep) {
1749
+ const out = {};
1750
+ for (const v of values) {
1751
+ const idx = v.indexOf(sep);
1752
+ if (idx <= 0) continue;
1753
+ const k = v.slice(0, idx).trim();
1754
+ const val = v.slice(idx + 1).trim();
1755
+ if (k) out[k] = val;
1756
+ }
1757
+ return out;
1758
+ }
1759
+
1760
+ // src/commands/init.ts
1761
+ import { writeFile as writeFile3 } from "fs/promises";
1762
+ import { resolve as resolve4 } from "path";
1763
+ function registerInitCommand(program) {
1764
+ program.command("init").description("Parse a spec and emit loadam.ir.json with inferred resource graph").argument("<spec>", "path to OpenAPI 3.x spec (YAML or JSON)").option("-o, --output <path>", "output path for IR JSON", "./loadam.ir.json").option("--no-tree", "skip printing the resource-graph tree").option("--json", "emit a single JSON summary on stdout (CI mode)", false).action(withFriendlyErrors(runInit));
1765
+ }
1766
+ async function runInit(spec, opts) {
1767
+ const out = makeOutput(!!opts.json);
1768
+ const specPath = resolve4(spec);
1769
+ out.start(`Parsing OpenAPI spec: ${specPath}`);
1770
+ const ir = await fromOpenApiFile(specPath);
1771
+ inferResourceGraph(ir);
1772
+ parseIR(ir);
1773
+ const outPath = resolve4(opts.output);
1774
+ await writeFile3(outPath, `${JSON.stringify(ir, null, 2)}
1775
+ `, "utf8");
1776
+ const stats = graphStats(ir.resources);
1777
+ out.success(`Wrote ${outPath}`);
1778
+ out.info(
1779
+ ` ${ir.operations.length} operations \xB7 ${Object.keys(ir.schemas).length} schemas \xB7 ${ir.auth.length} auth profile(s)`
1780
+ );
1781
+ out.info(` ${stats.kinds} resource kind(s) \xB7 ${stats.edges} edge(s)`);
1782
+ if (!out.json && opts.tree && ir.resources.kinds.length > 0) {
1783
+ out.step("");
1784
+ out.step(renderGraphTree(ir));
1785
+ }
1786
+ out.result({
1787
+ command: "init",
1788
+ outputPath: outPath,
1789
+ operations: ir.operations.length,
1790
+ schemas: Object.keys(ir.schemas).length,
1791
+ authProfiles: ir.auth.length,
1792
+ resourceKinds: stats.kinds,
1793
+ resourceEdges: stats.edges
1794
+ });
1795
+ }
1796
+
1797
+ // src/commands/mcp.ts
1798
+ import { mkdir as mkdir2, writeFile as writeFile4 } from "fs/promises";
1799
+ import { dirname as dirname2, resolve as resolve5 } from "path";
1800
+
1801
+ // ../mcp/dist/index.js
1802
+ function emitAuth(ir) {
1803
+ const headers = {};
1804
+ const query = {};
1805
+ const envVars = /* @__PURE__ */ new Set();
1806
+ const notes = [];
1807
+ for (const profile of ir.auth) apply(profile, headers, query, envVars, notes);
1808
+ return {
1809
+ headers,
1810
+ query,
1811
+ envVars: [...envVars].sort(),
1812
+ notes
1813
+ };
1814
+ }
1815
+ function apply(p, headers, query, envVars, notes) {
1816
+ switch (p.kind) {
1817
+ case "none":
1818
+ return;
1819
+ case "bearer": {
1820
+ const env = p.tokenEnv ?? "API_TOKEN";
1821
+ headers.Authorization = `Bearer \${${env}}`;
1822
+ envVars.add(env);
1823
+ return;
1824
+ }
1825
+ case "apiKey": {
1826
+ const env = p.valueEnv ?? p.name.toUpperCase().replace(/[^A-Z0-9]/g, "_");
1827
+ if (p.in === "header") headers[p.name] = `\${${env}}`;
1828
+ else if (p.in === "query") query[p.name] = `\${${env}}`;
1829
+ else notes.push(`Cookie-based apiKey "${p.name}" requires manual handling.`);
1830
+ envVars.add(env);
1831
+ return;
1832
+ }
1833
+ case "basic": {
1834
+ const u = p.userEnv ?? "API_USER";
1835
+ const pw = p.passEnv ?? "API_PASS";
1836
+ envVars.add(u);
1837
+ envVars.add(pw);
1838
+ headers.Authorization = `__BASIC__:${u}:${pw}`;
1839
+ notes.push("Basic auth: server encodes credentials per request.");
1840
+ return;
1841
+ }
1842
+ case "oauth2_cc":
1843
+ envVars.add(p.clientIdEnv);
1844
+ envVars.add(p.clientSecretEnv);
1845
+ notes.push(
1846
+ `OAuth2 client-credentials profile "${p.id}" \u2014 set ${p.clientIdEnv}/${p.clientSecretEnv}; V1 emits stubs only.`
1847
+ );
1848
+ return;
1849
+ case "custom":
1850
+ notes.push(`Custom auth signer "${p.signerRef}" \u2014 wire manually.`);
1851
+ return;
1852
+ }
1853
+ }
1854
+ var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "OPTIONS"]);
1855
+ function curateTools(ir, opts = {}) {
1856
+ const exclude = new Set(opts.exclude ?? []);
1857
+ const tools = [];
1858
+ for (const op of ir.operations) {
1859
+ if (exclude.has(op.id)) continue;
1860
+ const isSafe = op.safety === "safe" || SAFE_METHODS.has(op.method);
1861
+ if (!isSafe && !opts.includeWrites) continue;
1862
+ tools.push(buildTool(ir, op));
1863
+ }
1864
+ return tools;
1865
+ }
1866
+ function buildTool(ir, op) {
1867
+ const properties = {};
1868
+ const required = [];
1869
+ for (const p of op.pathParams) {
1870
+ properties[p.name] = annotate(resolveSchema(ir, p.schema), p);
1871
+ required.push(p.name);
1872
+ }
1873
+ for (const p of op.queryParams) {
1874
+ properties[p.name] = annotate(resolveSchema(ir, p.schema), p);
1875
+ if (p.required) required.push(p.name);
1876
+ }
1877
+ for (const p of op.headerParams) {
1878
+ if (isAuthHeader(p.name)) continue;
1879
+ properties[p.name] = annotate(resolveSchema(ir, p.schema), p);
1880
+ if (p.required) required.push(p.name);
1881
+ }
1882
+ let hasBody = false;
1883
+ if (op.body) {
1884
+ const json = op.body.contentTypes["application/json"];
1885
+ if (json) {
1886
+ properties.body = resolveSchema(ir, json.schema);
1887
+ if (op.body.required) required.push("body");
1888
+ hasBody = true;
1889
+ }
1890
+ }
1891
+ const inputSchema = {
1892
+ type: "object",
1893
+ properties,
1894
+ additionalProperties: false
1895
+ };
1896
+ if (required.length > 0) inputSchema.required = required;
1897
+ return {
1898
+ name: op.id,
1899
+ description: buildDescription(op),
1900
+ inputSchema,
1901
+ operation: {
1902
+ id: op.id,
1903
+ method: op.method,
1904
+ path: op.path,
1905
+ pathParamNames: op.pathParams.map((p) => p.name),
1906
+ queryParamNames: op.queryParams.map((p) => p.name),
1907
+ headerParamNames: op.headerParams.filter((p) => !isAuthHeader(p.name)).map((p) => p.name),
1908
+ hasBody
1909
+ }
1910
+ };
1911
+ }
1912
+ function resolveSchema(ir, ref) {
1913
+ if (typeof ref === "string") {
1914
+ const found = ir.schemas[ref];
1915
+ if (found) return cloneJson(found.jsonSchema);
1916
+ return {};
1917
+ }
1918
+ const inline = ref;
1919
+ return cloneJson(inline.jsonSchema);
1920
+ }
1921
+ function annotate(schema, p) {
1922
+ if (!p.description) return schema;
1923
+ if (typeof schema.description === "string") return schema;
1924
+ return { ...schema, description: p.description };
1925
+ }
1926
+ function buildDescription(op) {
1927
+ const parts = [];
1928
+ if (op.summary) parts.push(op.summary);
1929
+ else if (op.description) parts.push(op.description.split("\n")[0]?.trim() ?? "");
1930
+ parts.push(`(${op.method} ${op.path})`);
1931
+ return parts.filter(Boolean).join(" ");
1932
+ }
1933
+ var AUTH_HEADER_NAMES = /* @__PURE__ */ new Set(["authorization", "x-api-key", "api-key", "apikey"]);
1934
+ function isAuthHeader(name) {
1935
+ return AUTH_HEADER_NAMES.has(name.toLowerCase());
1936
+ }
1937
+ function cloneJson(value) {
1938
+ return structuredClone(value);
1939
+ }
1940
+ function emitPackageJson(ctx) {
1941
+ const name = slugify2(ctx.ir.meta.title) || "loadam-mcp";
1942
+ return `${JSON.stringify(
1943
+ {
1944
+ name: `${name}-mcp`,
1945
+ version: "0.0.0",
1946
+ description: `MCP server for ${ctx.ir.meta.title} \u2014 generated by loadam`,
1947
+ private: true,
1948
+ type: "module",
1949
+ bin: {
1950
+ [`${name}-mcp`]: "./bin.js"
1951
+ },
1952
+ scripts: {
1953
+ start: "node bin.js",
1954
+ "start:http": "node bin.js --http"
1955
+ },
1956
+ dependencies: {
1957
+ "@modelcontextprotocol/sdk": ctx.sdkVersion
1958
+ },
1959
+ engines: {
1960
+ node: ">=20"
1961
+ }
1962
+ },
1963
+ null,
1964
+ 2
1965
+ )}
1966
+ `;
1967
+ }
1968
+ function emitBinJs(_ctx) {
1969
+ return `#!/usr/bin/env node
1970
+ // AUTO-GENERATED by @loadam/mcp
1971
+ import { buildServer } from './server.js';
1972
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
1973
+
1974
+ function parseArgs(argv) {
1975
+ const args = { http: false, port: 3333, host: '127.0.0.1' };
1976
+ for (let i = 2; i < argv.length; i++) {
1977
+ const a = argv[i];
1978
+ if (a === '--http') args.http = true;
1979
+ else if (a === '--port') args.port = Number(argv[++i]);
1980
+ else if (a === '--host') args.host = String(argv[++i]);
1981
+ else if (a === '--help' || a === '-h') {
1982
+ process.stdout.write(\`Usage: <bin> [--http] [--port N] [--host H]\\n\`);
1983
+ process.exit(0);
1984
+ }
1985
+ }
1986
+ return args;
1987
+ }
1988
+
1989
+ async function main() {
1990
+ const args = parseArgs(process.argv);
1991
+ const server = buildServer();
1992
+
1993
+ if (args.http) {
1994
+ const { StreamableHTTPServerTransport } = await import(
1995
+ '@modelcontextprotocol/sdk/server/streamableHttp.js'
1996
+ );
1997
+ const { createServer } = await import('node:http');
1998
+ const { randomUUID } = await import('node:crypto');
1999
+
2000
+ const transport = new StreamableHTTPServerTransport({
2001
+ sessionIdGenerator: () => randomUUID(),
2002
+ });
2003
+ await server.connect(transport);
2004
+
2005
+ const http = createServer(async (req, res) => {
2006
+ try {
2007
+ await transport.handleRequest(req, res);
2008
+ } catch (err) {
2009
+ process.stderr.write(\`[mcp] http error: \${err && err.stack ? err.stack : err}\\n\`);
2010
+ if (!res.headersSent) {
2011
+ res.statusCode = 500;
2012
+ res.end();
2013
+ }
2014
+ }
2015
+ });
2016
+ http.listen(args.port, args.host, () => {
2017
+ process.stderr.write(\`[mcp] listening on http://\${args.host}:\${args.port}/mcp\\n\`);
2018
+ });
2019
+ return;
2020
+ }
2021
+
2022
+ // Default: stdio transport \u2014 what Claude Desktop uses.
2023
+ const transport = new StdioServerTransport();
2024
+ await server.connect(transport);
2025
+ process.stderr.write('[mcp] stdio ready\\n');
2026
+ }
2027
+
2028
+ main().catch((err) => {
2029
+ process.stderr.write(\`[mcp] fatal: \${err && err.stack ? err.stack : err}\\n\`);
2030
+ process.exit(1);
2031
+ });
2032
+ `;
2033
+ }
2034
+ function emitServerJs(ctx) {
2035
+ const name = slugify2(ctx.ir.meta.title) || "loadam-mcp";
2036
+ return `// AUTO-GENERATED by @loadam/mcp
2037
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
2038
+ import {
2039
+ CallToolRequestSchema,
2040
+ ListToolsRequestSchema,
2041
+ } from '@modelcontextprotocol/sdk/types.js';
2042
+ import { TOOLS } from './tools.js';
2043
+ import { invokeTool } from './client.js';
2044
+
2045
+ export function buildServer() {
2046
+ const server = new Server(
2047
+ { name: ${JSON.stringify(`${name}-mcp`)}, version: '0.0.0' },
2048
+ { capabilities: { tools: {} } },
2049
+ );
2050
+
2051
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
2052
+ tools: TOOLS.map((t) => ({
2053
+ name: t.name,
2054
+ description: t.description,
2055
+ inputSchema: t.inputSchema,
2056
+ })),
2057
+ }));
2058
+
2059
+ server.setRequestHandler(CallToolRequestSchema, async (req) => {
2060
+ const tool = TOOLS.find((t) => t.name === req.params.name);
2061
+ if (!tool) {
2062
+ return {
2063
+ isError: true,
2064
+ content: [
2065
+ { type: 'text', text: \`Unknown tool: \${req.params.name}\` },
2066
+ ],
2067
+ };
2068
+ }
2069
+ try {
2070
+ const result = await invokeTool(tool, req.params.arguments || {});
2071
+ return {
2072
+ content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
2073
+ };
2074
+ } catch (err) {
2075
+ const msg = err && err.message ? err.message : String(err);
2076
+ return {
2077
+ isError: true,
2078
+ content: [{ type: 'text', text: \`Error: \${msg}\` }],
2079
+ };
2080
+ }
2081
+ });
2082
+
2083
+ return server;
2084
+ }
2085
+ `;
2086
+ }
2087
+ function emitToolsJs(ctx) {
2088
+ const entries = ctx.tools.map(
2089
+ (t) => ` ${JSON.stringify(
2090
+ {
2091
+ name: t.name,
2092
+ description: t.description,
2093
+ inputSchema: t.inputSchema,
2094
+ operation: t.operation
2095
+ },
2096
+ null,
2097
+ 2
2098
+ ).split("\n").map((line, i) => i === 0 ? line : ` ${line}`).join("\n")}`
2099
+ ).join(",\n");
2100
+ return `// AUTO-GENERATED by @loadam/mcp
2101
+ export const TOOLS = [
2102
+ ${entries}
2103
+ ];
2104
+ `;
2105
+ }
2106
+ function emitAuthJs(ctx) {
2107
+ const headerEntries = Object.entries(ctx.auth.headers);
2108
+ const queryEntries = Object.entries(ctx.auth.query);
2109
+ const headerLines = headerEntries.length ? headerEntries.map(([k, v]) => ` ${buildHeaderLine(k, v)}`).join("\n") : " // no auth headers";
2110
+ const queryLines = queryEntries.length ? queryEntries.map(([k, v]) => ` ${JSON.stringify(k)}: ${interpolate(v)},`).join("\n") : "";
2111
+ return `// AUTO-GENERATED by @loadam/mcp
2112
+ export function authHeaders() {
2113
+ const h = {};
2114
+ ${headerLines}
2115
+ return h;
2116
+ }
2117
+
2118
+ export function authQuery() {
2119
+ return {
2120
+ ${queryLines}
2121
+ };
2122
+ }
2123
+ `;
2124
+ }
2125
+ function buildHeaderLine(name, value) {
2126
+ if (value.startsWith("__BASIC__:")) {
2127
+ const [, userEnv, passEnv] = value.split(":");
2128
+ return `if (process.env.${userEnv} && process.env.${passEnv}) { h.Authorization = 'Basic ' + Buffer.from(process.env.${userEnv} + ':' + process.env.${passEnv}).toString('base64'); }`;
2129
+ }
2130
+ return `h[${JSON.stringify(name)}] = ${interpolate(value)};`;
2131
+ }
2132
+ function interpolate(value) {
2133
+ const replaced = value.replace(
2134
+ /\$\{([A-Z0-9_]+)\}/g,
2135
+ (_m, name) => `\${process.env.${name} || ''}`
2136
+ );
2137
+ return `\`${replaced}\``;
2138
+ }
2139
+ function emitClientJs(ctx) {
2140
+ return `// AUTO-GENERATED by @loadam/mcp
2141
+ import { authHeaders, authQuery } from './auth.js';
2142
+
2143
+ const BASE_URL = process.env.BASE_URL || ${JSON.stringify(ctx.baseUrl)};
2144
+
2145
+ const PATH_PARAM_RE = /\\{([^}]+)\\}/g;
2146
+
2147
+ export async function invokeTool(tool, args) {
2148
+ const op = tool.operation;
2149
+ const headers = Object.assign({}, authHeaders());
2150
+
2151
+ // Build URL: substitute path params, append query.
2152
+ let path = op.path;
2153
+ for (const name of op.pathParamNames) {
2154
+ const v = args[name];
2155
+ if (v === undefined || v === null) {
2156
+ throw new Error(\`Missing required path param "\${name}" for tool "\${tool.name}"\`);
2157
+ }
2158
+ path = path.split('{' + name + '}').join(encodeURIComponent(String(v)));
2159
+ }
2160
+ // Defensive: any unsubstituted "{...}" placeholders become an explicit error.
2161
+ const unresolved = path.match(PATH_PARAM_RE);
2162
+ if (unresolved) {
2163
+ throw new Error(\`Unresolved path placeholders: \${unresolved.join(', ')}\`);
2164
+ }
2165
+
2166
+ const merged = Object.assign({}, authQuery());
2167
+ for (const name of op.queryParamNames) {
2168
+ if (args[name] !== undefined && args[name] !== null) merged[name] = args[name];
2169
+ }
2170
+ const qs = Object.keys(merged)
2171
+ .filter((k) => merged[k] !== undefined && merged[k] !== null && merged[k] !== '')
2172
+ .map((k) => encodeURIComponent(k) + '=' + encodeURIComponent(String(merged[k])))
2173
+ .join('&');
2174
+
2175
+ const url = BASE_URL + path + (qs ? '?' + qs : '');
2176
+
2177
+ for (const name of op.headerParamNames) {
2178
+ if (args[name] !== undefined && args[name] !== null) {
2179
+ headers[name] = String(args[name]);
2180
+ }
2181
+ }
2182
+
2183
+ let body;
2184
+ if (op.hasBody && args.body !== undefined) {
2185
+ headers['Content-Type'] = 'application/json';
2186
+ body = JSON.stringify(args.body);
2187
+ }
2188
+
2189
+ const resp = await fetch(url, { method: op.method, headers, body });
2190
+ const text = await resp.text();
2191
+ let parsed;
2192
+ try {
2193
+ parsed = text ? JSON.parse(text) : null;
2194
+ } catch (_) {
2195
+ parsed = text;
2196
+ }
2197
+ return {
2198
+ status: resp.status,
2199
+ headers: Object.fromEntries(resp.headers.entries()),
2200
+ body: parsed,
2201
+ };
2202
+ }
2203
+ `;
2204
+ }
2205
+ function emitEnvExample2(ctx) {
2206
+ const lines = [
2207
+ "# Generated by loadam \u2014 copy to .env or export in your shell.",
2208
+ `BASE_URL=${ctx.baseUrl}`,
2209
+ ""
2210
+ ];
2211
+ for (const v of ctx.auth.envVars) lines.push(`${v}=`);
2212
+ return `${lines.join("\n")}
2213
+ `;
2214
+ }
2215
+ function emitReadme2(ctx) {
2216
+ const toolList = ctx.tools.map((t) => `- \`${t.name}\` \u2014 ${t.description}`).join("\n");
2217
+ const writesNote = ctx.includeWrites ? "This server was generated with `--writes`, so it includes mutating operations (POST/PUT/PATCH/DELETE). Audit before connecting it to a writable backend." : "This server is **read-only by default** \u2014 it only exposes safe HTTP methods. Re-run `loadam mcp <spec> --writes` to include mutating ops.";
2218
+ const authNotes = ctx.auth.notes.length ? `
2219
+ ## Auth notes
2220
+
2221
+ ${ctx.auth.notes.map((n) => `- ${n}`).join("\n")}
2222
+ ` : "";
2223
+ return `# ${ctx.ir.meta.title} \u2014 MCP server
2224
+
2225
+ Generated by [loadam](https://github.com/loadam) from your API spec.
2226
+
2227
+ ${writesNote}
2228
+
2229
+ ## Run
2230
+
2231
+ \`\`\`bash
2232
+ npm install
2233
+
2234
+ # stdio (Claude Desktop, Cursor, etc.)
2235
+ node bin.js
2236
+
2237
+ # Streamable HTTP transport
2238
+ node bin.js --http --port 3333
2239
+ \`\`\`
2240
+
2241
+ ## Connect to Claude Desktop
2242
+
2243
+ Add to \`~/Library/Application Support/Claude/claude_desktop_config.json\`:
2244
+
2245
+ \`\`\`json
2246
+ {
2247
+ "mcpServers": {
2248
+ "${slugify2(ctx.ir.meta.title) || "loadam-mcp"}": {
2249
+ "command": "node",
2250
+ "args": ["${"<absolute path to this directory>"}/bin.js"],
2251
+ "env": {
2252
+ "BASE_URL": "${ctx.baseUrl}"${ctx.auth.envVars.length ? "," : ""}
2253
+ ${ctx.auth.envVars.map((v) => ` "${v}": "<value>"`).join(",\n")}
2254
+ }
2255
+ }
2256
+ }
2257
+ }
2258
+ \`\`\`
2259
+
2260
+ ## Tools (${ctx.tools.length})
2261
+
2262
+ ${toolList || "_No tools exposed \u2014 try regenerating with `--writes`._"}
2263
+ ${authNotes}
2264
+ ## Regenerating
2265
+
2266
+ Re-run \`loadam mcp <spec>\` to refresh. Edits to generated files will be overwritten.
2267
+ `;
2268
+ }
2269
+ function slugify2(s) {
2270
+ return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
2271
+ }
2272
+ var MCP_SDK_VERSION = "^1.29.0";
2273
+ function compileMcp(ir, opts = {}) {
2274
+ const baseUrl = opts.baseUrl ?? ir.servers[0]?.url ?? "http://localhost:4010";
2275
+ const tools = curateTools(ir, opts);
2276
+ const auth = emitAuth(ir);
2277
+ const ctx = {
2278
+ ir,
2279
+ baseUrl,
2280
+ tools,
2281
+ auth,
2282
+ includeWrites: !!opts.includeWrites,
2283
+ sdkVersion: MCP_SDK_VERSION
2284
+ };
2285
+ const files = {
2286
+ "package.json": emitPackageJson(ctx),
2287
+ "bin.js": emitBinJs(ctx),
2288
+ "server.js": emitServerJs(ctx),
2289
+ "tools.js": emitToolsJs(ctx),
2290
+ "client.js": emitClientJs(ctx),
2291
+ "auth.js": emitAuthJs(ctx),
2292
+ ".env.example": emitEnvExample2(ctx),
2293
+ "README.md": emitReadme2(ctx)
2294
+ };
2295
+ return { files, tools, envVars: auth.envVars };
2296
+ }
2297
+
2298
+ // src/commands/mcp.ts
2299
+ function registerMcpCommand(program) {
2300
+ program.command("mcp").description("Compile an OpenAPI spec into a runnable MCP server (stdio + HTTP).").argument("<spec>", "path to OpenAPI 3.x spec (YAML or JSON)").option("-o, --output <dir>", "output directory for the generated server", "./loadam-out/mcp").option(
2301
+ "--target <url>",
2302
+ "override base URL baked into client.js (env BASE_URL still wins at runtime)"
2303
+ ).option("--writes", "include mutating ops (POST/PUT/PATCH/DELETE) \u2014 off by default", false).option("--exclude <opIds...>", "operation ids to exclude from the tool list, repeatable").option("--json", "emit a single JSON summary on stdout (CI mode)", false).action(withFriendlyErrors(runMcp));
2304
+ }
2305
+ async function runMcp(spec, opts) {
2306
+ const out = makeOutput(!!opts.json);
2307
+ const specPath = resolve5(spec);
2308
+ out.start(`Parsing OpenAPI spec: ${specPath}`);
2309
+ const ir = await fromOpenApiFile(specPath);
2310
+ inferResourceGraph(ir);
2311
+ parseIR(ir);
2312
+ const result = compileMcp(ir, {
2313
+ baseUrl: opts.target,
2314
+ includeWrites: !!opts.writes,
2315
+ exclude: opts.exclude
2316
+ });
2317
+ const outDir = resolve5(opts.output);
2318
+ await mkdir2(outDir, { recursive: true });
2319
+ for (const [rel, contents] of Object.entries(result.files)) {
2320
+ const full = resolve5(outDir, rel);
2321
+ await mkdir2(dirname2(full), { recursive: true });
2322
+ await writeFile4(full, contents, "utf8");
2323
+ }
2324
+ const fileCount = Object.keys(result.files).length;
2325
+ out.success(`Wrote ${fileCount} files to ${outDir}`);
2326
+ out.info(
2327
+ ` ${result.tools.length} tools \xB7 ${opts.writes ? "writes enabled" : "read-only"} \xB7 ${result.envVars.length} auth env vars`
2328
+ );
2329
+ if (!out.json) {
2330
+ out.step("");
2331
+ out.step("Next steps:");
2332
+ out.step(` cd ${opts.output}`);
2333
+ out.step(" npm install");
2334
+ out.step(" node bin.js # stdio (Claude Desktop)");
2335
+ out.step(" node bin.js --http # streamable HTTP on :3333");
2336
+ }
2337
+ out.result({
2338
+ command: "mcp",
2339
+ outputDir: outDir,
2340
+ files: fileCount,
2341
+ tools: result.tools.length,
2342
+ toolNames: result.tools.map((t) => t.name),
2343
+ writes: !!opts.writes,
2344
+ envVars: result.envVars
2345
+ });
2346
+ }
2347
+
2348
+ // src/commands/test.ts
2349
+ import { mkdir as mkdir3, writeFile as writeFile5 } from "fs/promises";
2350
+ import { dirname as dirname3, resolve as resolve6 } from "path";
2351
+
2352
+ // ../data/dist/index.js
2353
+ import { faker } from "@faker-js/faker";
2354
+ import jsf from "json-schema-faker";
2355
+ var configured = false;
2356
+ function configureJsf() {
2357
+ if (configured) return;
2358
+ configured = true;
2359
+ jsf.option({
2360
+ alwaysFakeOptionals: false,
2361
+ failOnInvalidTypes: false,
2362
+ failOnInvalidFormat: false,
2363
+ useExamplesValue: true,
2364
+ useDefaultValue: true,
2365
+ fillProperties: false
2366
+ });
2367
+ jsf.extend("faker", () => faker);
2368
+ }
2369
+ function fakeFromSchema(schema, opts = {}) {
2370
+ configureJsf();
2371
+ if (opts.seed !== void 0) {
2372
+ faker.seed(opts.seed);
2373
+ }
2374
+ const expanded = expandRefs(schema, opts.resolveRef ?? (() => void 0), /* @__PURE__ */ new Set());
2375
+ const generated = jsf.generate(expanded);
2376
+ return overlayRegistry(generated, schema, opts);
2377
+ }
2378
+ function overlayRegistry(value, schema, opts) {
2379
+ if (!opts.registry || value === null || typeof value !== "object") return value;
2380
+ if (Array.isArray(value)) return value.map((v) => overlayRegistry(v, void 0, opts));
2381
+ const obj = value;
2382
+ for (const [key, current] of Object.entries(obj)) {
2383
+ if (typeof current === "string" || typeof current === "number") {
2384
+ const candidateKind = inferKindFromFieldName(key);
2385
+ if (candidateKind && opts.registry.size(candidateKind) > 0) {
2386
+ const replacement = opts.registry.pickField(candidateKind, "id");
2387
+ if (replacement !== void 0) {
2388
+ obj[key] = replacement;
2389
+ }
2390
+ }
2391
+ } else if (current && typeof current === "object") {
2392
+ obj[key] = overlayRegistry(current, void 0, opts);
2393
+ }
2394
+ }
2395
+ return obj;
2396
+ }
2397
+ function inferKindFromFieldName(field) {
2398
+ const m = field.match(/^([a-zA-Z][a-zA-Z0-9]*?)(Id|_id|Uuid|_uuid)$/) || field.match(/^([a-zA-Z][a-zA-Z0-9]*?)Ref$/);
2399
+ if (!m || !m[1]) return void 0;
2400
+ const root = m[1];
2401
+ return root.charAt(0).toUpperCase() + root.slice(1);
2402
+ }
2403
+ function expandRefs(node, resolve7, seen) {
2404
+ if (Array.isArray(node)) return node.map((n) => expandRefs(n, resolve7, seen));
2405
+ if (!node || typeof node !== "object") return node;
2406
+ const obj = node;
2407
+ if (typeof obj.$ref === "string") {
2408
+ if (seen.has(obj.$ref)) return {};
2409
+ const target = resolve7(obj.$ref);
2410
+ if (target === void 0) return obj;
2411
+ const next = new Set(seen);
2412
+ next.add(obj.$ref);
2413
+ return expandRefs(target, resolve7, next);
2414
+ }
2415
+ const out = {};
2416
+ for (const [k, v] of Object.entries(obj)) out[k] = expandRefs(v, resolve7, seen);
2417
+ return out;
2418
+ }
2419
+
2420
+ // ../test-k6/dist/index.js
2421
+ function emitAuth2(ir) {
2422
+ const headers = {};
2423
+ const query = {};
2424
+ const envVars = /* @__PURE__ */ new Set();
2425
+ const notes = [];
2426
+ for (const profile of ir.auth) {
2427
+ applyProfile(profile, headers, query, envVars, notes);
2428
+ }
2429
+ return {
2430
+ headers,
2431
+ query,
2432
+ envVars: [...envVars].sort(),
2433
+ notes
2434
+ };
2435
+ }
2436
+ function applyProfile(p, headers, query, envVars, notes) {
2437
+ switch (p.kind) {
2438
+ case "none":
2439
+ return;
2440
+ case "bearer": {
2441
+ const env = p.tokenEnv ?? "API_TOKEN";
2442
+ headers.Authorization = `Bearer \${${env}}`;
2443
+ envVars.add(env);
2444
+ return;
2445
+ }
2446
+ case "apiKey": {
2447
+ const env = p.valueEnv ?? `${p.name.toUpperCase().replace(/[^A-Z0-9]/g, "_")}`;
2448
+ if (p.in === "header") headers[p.name] = `\${${env}}`;
2449
+ else if (p.in === "query") query[p.name] = `\${${env}}`;
2450
+ else notes.push(`Cookie-based apiKey "${p.name}" requires manual handling.`);
2451
+ envVars.add(env);
2452
+ return;
2453
+ }
2454
+ case "basic": {
2455
+ const u = p.userEnv ?? "API_USER";
2456
+ const pw = p.passEnv ?? "API_PASS";
2457
+ envVars.add(u);
2458
+ envVars.add(pw);
2459
+ notes.push(`Basic auth: scripts encode \`${u}:${pw}\` per request. Set both env vars.`);
2460
+ headers.Authorization = `__BASIC__:${u}:${pw}`;
2461
+ return;
2462
+ }
2463
+ case "oauth2_cc": {
2464
+ notes.push(
2465
+ `OAuth2 client-credentials profile "${p.id}" detected \u2014 V1 emits stubs only; populate \`${p.clientIdEnv}\`/\`${p.clientSecretEnv}\` and supply your own token endpoint call.`
2466
+ );
2467
+ envVars.add(p.clientIdEnv);
2468
+ envVars.add(p.clientSecretEnv);
2469
+ return;
2470
+ }
2471
+ case "custom":
2472
+ notes.push(`Custom auth signer "${p.signerRef}" \u2014 wire manually.`);
2473
+ return;
2474
+ }
2475
+ }
2476
+ function sequenceForSmoke(ir) {
2477
+ const opsById = new Map(ir.operations.map((o) => [o.id, o]));
2478
+ const out = [];
2479
+ const seen = /* @__PURE__ */ new Set();
2480
+ const orderedKinds = topoSortKinds(ir.resources.kinds, ir.resources.edges);
2481
+ for (const kind of orderedKinds) {
2482
+ for (const bucket of ["listOps", "createOps", "readOps", "updateOps", "deleteOps"]) {
2483
+ for (const opId of kind[bucket]) {
2484
+ const op = opsById.get(opId);
2485
+ if (op && !seen.has(op.id)) {
2486
+ out.push(op);
2487
+ seen.add(op.id);
2488
+ }
2489
+ }
2490
+ }
2491
+ }
2492
+ for (const op of ir.operations) {
2493
+ if (!seen.has(op.id)) {
2494
+ out.push(op);
2495
+ seen.add(op.id);
2496
+ }
2497
+ }
2498
+ return out;
2499
+ }
2500
+ function topoSortKinds(kinds, edges) {
2501
+ const incoming = /* @__PURE__ */ new Map();
2502
+ for (const k of kinds) incoming.set(k.name, /* @__PURE__ */ new Set());
2503
+ for (const e of edges) {
2504
+ if (incoming.has(e.from) && incoming.has(e.to) && e.from !== e.to) {
2505
+ incoming.get(e.from)?.add(e.to);
2506
+ }
2507
+ }
2508
+ const out = [];
2509
+ const remaining = new Map(kinds.map((k) => [k.name, k]));
2510
+ while (remaining.size > 0) {
2511
+ let picked;
2512
+ for (const name of remaining.keys()) {
2513
+ if (incoming.get(name)?.size === 0) {
2514
+ picked = name;
2515
+ break;
2516
+ }
2517
+ }
2518
+ if (!picked) picked = remaining.keys().next().value;
2519
+ if (!picked) break;
2520
+ const kind = remaining.get(picked);
2521
+ if (kind) out.push(kind);
2522
+ remaining.delete(picked);
2523
+ for (const set of incoming.values()) set.delete(picked);
2524
+ }
2525
+ return out;
2526
+ }
2527
+ function pickContentType(body) {
2528
+ const types = Object.keys(body.contentTypes);
2529
+ return types.find((t) => t.includes("json")) ?? types[0];
2530
+ }
2531
+ function defaultBaseUrl(ir) {
2532
+ const first = ir.servers[0]?.url;
2533
+ if (!first) return "http://localhost:4010";
2534
+ const vars = ir.servers[0]?.variables ?? {};
2535
+ return first.replace(/\{(\w+)\}/g, (_match, name) => vars[name]?.default ?? "");
2536
+ }
2537
+ function buildFixturePool(ir, opts = {}) {
2538
+ const size = opts.size ?? 10;
2539
+ const seed = opts.seed ?? 1;
2540
+ const resolveRef2 = makeRefResolver(ir);
2541
+ const byOperationId = {};
2542
+ for (let i = 0; i < ir.operations.length; i++) {
2543
+ const op = ir.operations[i];
2544
+ if (!op) continue;
2545
+ const fix = {};
2546
+ if (op.body) {
2547
+ const ct = pickContentType(op.body);
2548
+ const media = ct ? op.body.contentTypes[ct] : void 0;
2549
+ if (media) {
2550
+ fix.bodies = generateMany(media.schema, size, seed + i, resolveRef2);
2551
+ }
2552
+ }
2553
+ if (op.pathParams.length > 0) {
2554
+ fix.pathParams = generateParamPool(op.pathParams, size, seed + i, resolveRef2);
2555
+ }
2556
+ if (op.queryParams.length > 0) {
2557
+ const required = op.queryParams.filter((p) => p.required);
2558
+ if (required.length > 0) {
2559
+ fix.queryParams = generateParamPool(required, size, seed + i, resolveRef2);
2560
+ }
2561
+ }
2562
+ if (fix.bodies || fix.pathParams || fix.queryParams) {
2563
+ byOperationId[op.id] = fix;
2564
+ }
2565
+ }
2566
+ return { byOperationId, size };
2567
+ }
2568
+ function generateMany(schema, count, seed, resolveRef2) {
2569
+ const out = [];
2570
+ const target = resolveSchemaRef(schema, resolveRef2);
2571
+ for (let i = 0; i < count; i++) {
2572
+ try {
2573
+ out.push(fakeFromSchema(target, { resolveRef: resolveRef2, seed: seed + i }));
2574
+ } catch {
2575
+ out.push(null);
2576
+ }
2577
+ }
2578
+ return out;
2579
+ }
2580
+ function generateParamPool(params, count, seed, resolveRef2) {
2581
+ const out = {};
2582
+ for (let i = 0; i < params.length; i++) {
2583
+ const p = params[i];
2584
+ if (!p) continue;
2585
+ out[p.name] = generateMany(p.schema, count, seed + i, resolveRef2);
2586
+ }
2587
+ return out;
2588
+ }
2589
+ function resolveSchemaRef(schema, resolveRef2) {
2590
+ if (typeof schema === "string") {
2591
+ return resolveRef2(schema) ?? {};
2592
+ }
2593
+ if (schema && typeof schema === "object" && "jsonSchema" in schema) {
2594
+ return schema.jsonSchema;
2595
+ }
2596
+ return schema;
2597
+ }
2598
+ function makeRefResolver(ir) {
2599
+ return (ref) => {
2600
+ const direct = ir.schemas[ref];
2601
+ if (direct) return direct.jsonSchema;
2602
+ for (const [id, s] of Object.entries(ir.schemas)) {
2603
+ if (id.endsWith(ref) || s.name === ref) return s.jsonSchema;
2604
+ }
2605
+ return void 0;
2606
+ };
2607
+ }
2608
+ function emitConfigJs(ctx) {
2609
+ const { auth } = ctx;
2610
+ const base = ctx.baseUrl;
2611
+ const headerEntries = Object.entries(auth.headers);
2612
+ const queryEntries = Object.entries(auth.query);
2613
+ const needsB64 = headerEntries.some(([, v]) => v.startsWith("__BASIC__:"));
2614
+ const importLine = needsB64 ? "import encoding from 'k6/encoding';\n" : "";
2615
+ const headersBody = headerEntries.length ? headerEntries.map(([k, v]) => ` ${buildHeaderLine2(k, v)}`).join("\n") : " // no auth headers";
2616
+ const queryBody = queryEntries.length ? queryEntries.map(([k, v]) => ` ${JSON.stringify(k)}: ${interpolate2(v)},`).join("\n") : "";
2617
+ return `// AUTO-GENERATED by @loadam/test-k6
2618
+ ${importLine}
2619
+ const BASE_URL = (typeof __ENV !== 'undefined' && __ENV.BASE_URL) || ${JSON.stringify(base)};
2620
+
2621
+ export function baseUrl() {
2622
+ return BASE_URL;
2623
+ }
2624
+
2625
+ export function authHeaders() {
2626
+ const h = {};
2627
+ ${headersBody}
2628
+ return h;
2629
+ }
2630
+
2631
+ export function authQuery() {
2632
+ return {
2633
+ ${queryBody}
2634
+ };
2635
+ }
2636
+
2637
+ export function buildUrl(path, pathParams, queryParams) {
2638
+ let p = path;
2639
+ if (pathParams) {
2640
+ for (const k in pathParams) {
2641
+ if (pathParams[k] === undefined || pathParams[k] === null) continue;
2642
+ p = p.split('{' + k + '}').join(encodeURIComponent(String(pathParams[k])));
2643
+ }
2644
+ }
2645
+ const aq = authQuery();
2646
+ const merged = Object.assign({}, queryParams || {}, aq);
2647
+ const qs = Object.keys(merged)
2648
+ .filter((k) => merged[k] !== undefined && merged[k] !== null && merged[k] !== '')
2649
+ .map((k) => encodeURIComponent(k) + '=' + encodeURIComponent(String(merged[k])))
2650
+ .join('&');
2651
+ return BASE_URL + p + (qs ? '?' + qs : '');
2652
+ }
2653
+ `;
2654
+ }
2655
+ function buildHeaderLine2(name, value) {
2656
+ if (value.startsWith("__BASIC__:")) {
2657
+ const [, userEnv, passEnv] = value.split(":");
2658
+ return `if (__ENV.${userEnv} && __ENV.${passEnv}) { h.Authorization = 'Basic ' + encoding.b64encode(__ENV.${userEnv} + ':' + __ENV.${passEnv}); }`;
2659
+ }
2660
+ return `h[${JSON.stringify(name)}] = ${interpolate2(value)};`;
2661
+ }
2662
+ function interpolate2(value) {
2663
+ const replaced = value.replace(/\$\{([A-Z0-9_]+)\}/g, (_m, name) => `\${__ENV.${name} || ''}`);
2664
+ return `\`${replaced}\``;
2665
+ }
2666
+ function emitFlowJs(ctx) {
2667
+ const ops = ctx.sequencedOps;
2668
+ const lines = [];
2669
+ for (let i = 0; i < ops.length; i++) {
2670
+ const op = ops[i];
2671
+ if (!op) continue;
2672
+ lines.push(emitOpCall(op, i));
2673
+ }
2674
+ return `// AUTO-GENERATED by @loadam/test-k6
2675
+ import http from 'k6/http';
2676
+ import { check } from 'k6';
2677
+ import { SharedArray } from 'k6/data';
2678
+ import { authHeaders, buildUrl } from './config.js';
2679
+
2680
+ const fixtures = new SharedArray('loadam-fixtures', function () {
2681
+ return [JSON.parse(open('./fixtures.json'))];
2682
+ });
2683
+
2684
+ function pickFixture(opId, slot, idx) {
2685
+ const pool = fixtures[0][opId];
2686
+ if (!pool || !pool[slot]) return undefined;
2687
+ const arr = pool[slot];
2688
+ if (Array.isArray(arr)) return arr[idx % arr.length];
2689
+ return undefined;
2690
+ }
2691
+
2692
+ function pickPathParam(opId, name, state, kind, idx) {
2693
+ if (kind && state[kind] && state[kind].length > 0) {
2694
+ return state[kind][state[kind].length - 1];
2695
+ }
2696
+ const pool = fixtures[0][opId];
2697
+ if (pool && pool.pathParams && pool.pathParams[name]) {
2698
+ const arr = pool.pathParams[name];
2699
+ return arr[idx % arr.length];
2700
+ }
2701
+ return undefined;
2702
+ }
2703
+
2704
+ /**
2705
+ * Run one flow iteration. \`state\` accumulates created IDs by ResourceKind
2706
+ * so subsequent ops in the same iteration reuse them.
2707
+ */
2708
+ export function runFlow(iter) {
2709
+ const state = {};
2710
+ const __ITER = iter || 0;
2711
+ ${lines.join("\n")}
2712
+ }
2713
+ `;
2714
+ }
2715
+ function emitOpCall(op, _index) {
2716
+ const headersExpr = "Object.assign({}, authHeaders())";
2717
+ const opIdLit = JSON.stringify(op.id);
2718
+ const pathParamLines = [];
2719
+ let pathParamObj = "undefined";
2720
+ if (op.pathParams.length > 0) {
2721
+ const entries = [];
2722
+ for (const p of op.pathParams) {
2723
+ const ident = safeIdent(p.name);
2724
+ const kindLit = p.resourceKind ? JSON.stringify(p.resourceKind) : "undefined";
2725
+ pathParamLines.push(
2726
+ ` const __pp_${ident} = pickPathParam(${opIdLit}, ${JSON.stringify(p.name)}, state, ${kindLit}, __ITER);`
2727
+ );
2728
+ entries.push(`${JSON.stringify(p.name)}: __pp_${ident}`);
2729
+ }
2730
+ pathParamObj = `{ ${entries.join(", ")} }`;
2731
+ }
2732
+ const requiredQuery = op.queryParams.filter((p) => p.required);
2733
+ let queryParamObj = "undefined";
2734
+ if (requiredQuery.length > 0) {
2735
+ const entries = requiredQuery.map(
2736
+ (p) => `${JSON.stringify(p.name)}: (function () { const f = pickFixture(${opIdLit}, 'queryParams', __ITER); return f ? f[${JSON.stringify(p.name)}] : undefined; })()`
2737
+ ).join(", ");
2738
+ queryParamObj = `{ ${entries} }`;
2739
+ }
2740
+ const requestLine = emitRequestCall(op, headersExpr, pathParamObj, queryParamObj);
2741
+ const captureId = op.resourceAction === "create" && op.resourceKind ? ` if (resp.status >= 200 && resp.status < 300) {
2742
+ let body;
2743
+ try { body = resp.json(); } catch (_) { body = undefined; }
2744
+ if (body && body.id !== undefined) {
2745
+ (state[${JSON.stringify(op.resourceKind)}] = state[${JSON.stringify(op.resourceKind)}] || []).push(body.id);
2746
+ }
2747
+ }` : "";
2748
+ return ` // ${op.method} ${op.path} \u2014 ${op.id}
2749
+ {
2750
+ ${pathParamLines.join("\n")}
2751
+ const resp = ${requestLine};
2752
+ check(resp, { ${JSON.stringify(`${op.id} 2xx-3xx`)}: (r) => r.status >= 200 && r.status < 400 });
2753
+ ${captureId}
2754
+ }
2755
+ `;
2756
+ }
2757
+ function emitRequestCall(op, headersExpr, pathParamObj, queryParamObj) {
2758
+ const url = `buildUrl(${JSON.stringify(op.path)}, ${pathParamObj}, ${queryParamObj})`;
2759
+ const method = op.method.toLowerCase();
2760
+ const hasBody = !!op.body;
2761
+ const opIdLit = JSON.stringify(op.id);
2762
+ const bodyExpr = hasBody ? `JSON.stringify(pickFixture(${opIdLit}, 'bodies', __ITER))` : "null";
2763
+ const headersWithCT = hasBody ? `Object.assign(${headersExpr}, { 'Content-Type': 'application/json' })` : headersExpr;
2764
+ if (method === "get" || method === "head" || method === "options") {
2765
+ return `http.${method}(${url}, { headers: ${headersExpr}, tags: { name: ${opIdLit} } })`;
2766
+ }
2767
+ if (method === "delete") {
2768
+ return `http.del(${url}, null, { headers: ${headersExpr}, tags: { name: ${opIdLit} } })`;
2769
+ }
2770
+ return `http.${method}(${url}, ${bodyExpr}, { headers: ${headersWithCT}, tags: { name: ${opIdLit} } })`;
2771
+ }
2772
+ function safeIdent(s) {
2773
+ return s.replace(/[^A-Za-z0-9_]/g, "_");
2774
+ }
2775
+ function emitSmokeJs() {
2776
+ return `// AUTO-GENERATED by @loadam/test-k6 \u2014 smoke test
2777
+ import { runFlow } from './flow.js';
2778
+
2779
+ export const options = {
2780
+ vus: 1,
2781
+ iterations: 1,
2782
+ thresholds: {
2783
+ checks: ['rate>=0.95'],
2784
+ http_req_failed: ['rate<0.05'],
2785
+ http_req_duration: ['p(95)<2000'],
2786
+ },
2787
+ };
2788
+
2789
+ export default function () {
2790
+ runFlow(0);
2791
+ }
2792
+ `;
2793
+ }
2794
+ function emitLoadJs() {
2795
+ return `// AUTO-GENERATED by @loadam/test-k6 \u2014 load test
2796
+ import { runFlow } from './flow.js';
2797
+
2798
+ export const options = {
2799
+ stages: [
2800
+ { duration: '15s', target: 5 },
2801
+ { duration: '45s', target: 10 },
2802
+ { duration: '15s', target: 0 },
2803
+ ],
2804
+ thresholds: {
2805
+ checks: ['rate>=0.95'],
2806
+ http_req_failed: ['rate<0.05'],
2807
+ http_req_duration: ['p(95)<1000'],
2808
+ },
2809
+ };
2810
+
2811
+ export default function () {
2812
+ runFlow(__ITER);
2813
+ }
2814
+ `;
2815
+ }
2816
+ function emitFixturesJson(pool) {
2817
+ return `${JSON.stringify(pool, null, 2)}
2818
+ `;
2819
+ }
2820
+ function emitPackageJson2(ctx) {
2821
+ const name = slugify3(ctx.ir.meta.title) || "loadam-k6";
2822
+ return `${JSON.stringify(
2823
+ {
2824
+ name: `${name}-k6`,
2825
+ version: "0.0.0",
2826
+ description: `k6 test rig for ${ctx.ir.meta.title} \u2014 generated by loadam`,
2827
+ private: true,
2828
+ scripts: {
2829
+ smoke: "k6 run smoke.js",
2830
+ load: "k6 run load.js"
2831
+ }
2832
+ },
2833
+ null,
2834
+ 2
2835
+ )}
2836
+ `;
2837
+ }
2838
+ function emitEnvExample3(ctx) {
2839
+ const lines = [
2840
+ "# Generated by loadam \u2014 copy to .env and fill in.",
2841
+ `BASE_URL=${ctx.baseUrl}`,
2842
+ ""
2843
+ ];
2844
+ for (const v of ctx.auth.envVars) lines.push(`${v}=`);
2845
+ return `${lines.join("\n")}
2846
+ `;
2847
+ }
2848
+ function emitReadme3(ctx) {
2849
+ const opCount = ctx.sequencedOps.length;
2850
+ const notes = ctx.auth.notes.length ? `
2851
+ ## Auth notes
2852
+
2853
+ ${ctx.auth.notes.map((n) => `- ${n}`).join("\n")}
2854
+ ` : "";
2855
+ return `# ${ctx.ir.meta.title} \u2014 k6 test rig
2856
+
2857
+ Generated by [loadam](https://github.com/loadam) from your API spec.
2858
+
2859
+ ## Run
2860
+
2861
+ \`\`\`bash
2862
+ # 1. fill credentials
2863
+ cp .env.example .env
2864
+
2865
+ # 2. smoke test (1 VU, 1 iteration)
2866
+ k6 run smoke.js
2867
+
2868
+ # 3. load test (ramps to 10 VUs over 75s)
2869
+ k6 run load.js
2870
+ \`\`\`
2871
+
2872
+ ## What's in here
2873
+
2874
+ - \`smoke.js\` \u2014 runs each of the ${opCount} operations once, threading IDs from create\u2192read\u2192delete.
2875
+ - \`load.js\` \u2014 same flow under ramping load with SLO thresholds.
2876
+ - \`flow.js\` \u2014 shared per-iteration flow used by both scripts.
2877
+ - \`fixtures.json\` \u2014 pre-generated request bodies and path-param values (k6 cannot run npm modules).
2878
+ - \`config.js\` \u2014 base URL + auth header builder.
2879
+ ${notes}
2880
+ ## Regenerating
2881
+
2882
+ Re-run \`loadam test\` to refresh. Edits to generated files will be overwritten \u2014
2883
+ preserve-user-block markers land in V1.1.
2884
+ `;
2885
+ }
2886
+ function slugify3(s) {
2887
+ return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
2888
+ }
2889
+ function compileK6(ir, opts = {}) {
2890
+ const baseUrl = opts.baseUrl ?? defaultBaseUrl(ir);
2891
+ const sequencedOps = sequenceForSmoke(ir);
2892
+ const auth = emitAuth2(ir);
2893
+ const fixtures = buildFixturePool(ir, {
2894
+ size: opts.fixtureSize,
2895
+ seed: opts.seed
2896
+ });
2897
+ const ctx = { ir, baseUrl, sequencedOps, auth };
2898
+ const files = {
2899
+ "config.js": emitConfigJs(ctx),
2900
+ "flow.js": emitFlowJs(ctx),
2901
+ "smoke.js": emitSmokeJs(),
2902
+ "load.js": emitLoadJs(),
2903
+ "fixtures.json": emitFixturesJson(fixtures.byOperationId),
2904
+ "package.json": emitPackageJson2(ctx),
2905
+ ".env.example": emitEnvExample3(ctx),
2906
+ "README.md": emitReadme3(ctx)
2907
+ };
2908
+ return { files, fixtures };
2909
+ }
2910
+
2911
+ // src/commands/test.ts
2912
+ function registerTestCommand(program) {
2913
+ program.command("test").description("Compile an OpenAPI spec into a runnable k6 test rig (smoke + load).").argument("<spec>", "path to OpenAPI 3.x spec (YAML or JSON)").option("-o, --output <dir>", "output directory for the generated rig", "./loadam-out/k6").option(
2914
+ "--target <url>",
2915
+ "override base URL baked into config.js (env BASE_URL still wins at runtime)"
2916
+ ).option("--fixture-size <n>", "number of fixtures per slot", "10").option("--seed <n>", "deterministic seed for fixture generation", "1").option("--json", "emit a single JSON summary on stdout (CI mode)", false).action(withFriendlyErrors(runTest));
2917
+ }
2918
+ async function runTest(spec, opts) {
2919
+ const out = makeOutput(!!opts.json);
2920
+ const specPath = resolve6(spec);
2921
+ out.start(`Parsing OpenAPI spec: ${specPath}`);
2922
+ const ir = await fromOpenApiFile(specPath);
2923
+ inferResourceGraph(ir);
2924
+ parseIR(ir);
2925
+ const fixtureSize = Number.parseInt(opts.fixtureSize ?? "10", 10);
2926
+ const seed = Number.parseInt(opts.seed ?? "1", 10);
2927
+ const result = compileK6(ir, {
2928
+ baseUrl: opts.target,
2929
+ fixtureSize: Number.isFinite(fixtureSize) ? fixtureSize : 10,
2930
+ seed: Number.isFinite(seed) ? seed : 1
2931
+ });
2932
+ const outDir = resolve6(opts.output);
2933
+ await mkdir3(outDir, { recursive: true });
2934
+ for (const [rel, contents] of Object.entries(result.files)) {
2935
+ const full = resolve6(outDir, rel);
2936
+ await mkdir3(dirname3(full), { recursive: true });
2937
+ await writeFile5(full, contents, "utf8");
2938
+ }
2939
+ const fileCount = Object.keys(result.files).length;
2940
+ const fixtureCount = Object.keys(result.fixtures.byOperationId).length;
2941
+ out.success(`Wrote ${fileCount} files to ${outDir}`);
2942
+ out.info(
2943
+ ` ${ir.operations.length} operations \xB7 ${fixtureCount} ops with fixtures \xB7 ${result.fixtures.size} samples each`
2944
+ );
2945
+ if (!out.json) {
2946
+ out.step("");
2947
+ out.step("Next steps:");
2948
+ out.step(` cd ${opts.output}`);
2949
+ out.step(" cp .env.example .env # fill in credentials");
2950
+ out.step(" k6 run smoke.js");
2951
+ }
2952
+ out.result({
2953
+ command: "test",
2954
+ outputDir: outDir,
2955
+ files: fileCount,
2956
+ operations: ir.operations.length,
2957
+ fixtureOps: fixtureCount,
2958
+ fixtureSize: result.fixtures.size
2959
+ });
2960
+ }
2961
+
2962
+ // src/util/update.ts
2963
+ var PKG = "loadam";
2964
+ var REGISTRY = "https://registry.npmjs.org";
2965
+ async function fetchLatestVersion(timeoutMs = 3e3) {
2966
+ try {
2967
+ const ctrl = new AbortController();
2968
+ const timer = setTimeout(() => ctrl.abort(), timeoutMs);
2969
+ const res = await fetch(`${REGISTRY}/${PKG}/latest`, {
2970
+ signal: ctrl.signal,
2971
+ headers: { accept: "application/json" }
2972
+ });
2973
+ clearTimeout(timer);
2974
+ if (!res.ok) return null;
2975
+ const data = await res.json();
2976
+ return typeof data.version === "string" ? data.version : null;
2977
+ } catch {
2978
+ return null;
2979
+ }
2980
+ }
2981
+ function compareVersions(a, b) {
2982
+ const parse = (v) => v.replace(/^v/, "").split("-")[0].split(".").map((n) => Number.parseInt(n, 10) || 0);
2983
+ const [aa, bb] = [parse(a), parse(b)];
2984
+ for (let i = 0; i < 3; i++) {
2985
+ const d = (aa[i] ?? 0) - (bb[i] ?? 0);
2986
+ if (d !== 0) return d > 0 ? 1 : -1;
2987
+ }
2988
+ return 0;
2989
+ }
2990
+
2991
+ // src/commands/update.ts
2992
+ function registerUpdateCommand(program, currentVersion) {
2993
+ program.command("update").description("Check whether a newer version of loadam is on npm").option("--json", "emit machine-readable output").action(async (opts) => {
2994
+ const latest = await fetchLatestVersion();
2995
+ if (!latest) {
2996
+ if (opts.json) {
2997
+ process.stdout.write(
2998
+ `${JSON.stringify({ ok: false, current: currentVersion, latest: null, reason: "registry-unreachable" })}
2999
+ `
3000
+ );
3001
+ } else {
3002
+ process.stderr.write("Could not reach the npm registry. Skipping update check.\n");
3003
+ }
3004
+ return;
3005
+ }
3006
+ const cmp = compareVersions(currentVersion, latest);
3007
+ const upToDate = cmp >= 0;
3008
+ if (opts.json) {
3009
+ process.stdout.write(
3010
+ `${JSON.stringify({ ok: true, current: currentVersion, latest, upToDate })}
3011
+ `
3012
+ );
3013
+ return;
3014
+ }
3015
+ if (upToDate) {
3016
+ process.stdout.write(`loadam ${currentVersion} is up to date (latest: ${latest}).
3017
+ `);
3018
+ } else {
3019
+ process.stdout.write(
3020
+ `A new version of loadam is available: ${currentVersion} \u2192 ${latest}
3021
+ Run: npm i -g loadam
3022
+ `
3023
+ );
3024
+ }
3025
+ });
3026
+ }
3027
+
3028
+ // src/util/banner.ts
3029
+ var ART = String.raw`
3030
+ _ _
3031
+ | | ___ __ _ __| | __ _ _ __ ___
3032
+ | |/ _ \ / _' |/ _' |/ _' | '_ ' _ \
3033
+ | | (_) | (_| | (_| | (_| | | | | | |
3034
+ |_|\___/ \__,_|\__,_|\__,_|_| |_| |_|
3035
+ `;
3036
+ var TAGLINE = " spec \u2192 tests \xB7 contract \xB7 drift \xB7 MCP server";
3037
+ function banner() {
3038
+ const useColor = process.stdout.isTTY && !process.env.NO_COLOR;
3039
+ if (!useColor) {
3040
+ return `${ART}
3041
+ ${TAGLINE}
3042
+ `;
3043
+ }
3044
+ const cyan = "\x1B[36m";
3045
+ const dim = "\x1B[2m";
3046
+ const reset = "\x1B[0m";
3047
+ return `${cyan}${ART}${reset}
3048
+ ${dim}${TAGLINE}${reset}
3049
+ `;
3050
+ }
3051
+
3052
+ // src/program.ts
3053
+ var VERSION = "0.0.0";
3054
+ function buildProgram() {
3055
+ const program = new Command();
3056
+ program.name("loadam").description(
3057
+ "Generate test rigs and MCP servers from any API spec. From spec to running rig in 60s."
3058
+ ).version(VERSION, "-v, --version", "print version").addHelpText("beforeAll", banner());
3059
+ registerInitCommand(program);
3060
+ registerAuthCommands(program);
3061
+ registerTestCommand(program);
3062
+ registerContractCommand(program);
3063
+ registerDiffCommand(program);
3064
+ registerMcpCommand(program);
3065
+ registerCompletionCommand(program);
3066
+ registerUpdateCommand(program, VERSION);
3067
+ return program;
3068
+ }
3069
+
3070
+ // src/bin.ts
3071
+ async function main() {
3072
+ const program = buildProgram();
3073
+ if (process.argv.length <= 2) {
3074
+ program.outputHelp();
3075
+ return;
3076
+ }
3077
+ await program.parseAsync(process.argv);
3078
+ }
3079
+ main().catch((err) => {
3080
+ console.error(err instanceof Error ? err.message : err);
3081
+ process.exit(1);
3082
+ });
3083
+ //# sourceMappingURL=bin.js.map